@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.
Files changed (145) hide show
  1. package/dist/color/index.d.ts +28 -7
  2. package/dist/color/index.d.ts.map +1 -1
  3. package/dist/color/index.js +40 -15
  4. package/dist/color/index.js.map +1 -1
  5. package/dist/color/management.d.ts +19 -6
  6. package/dist/color/management.d.ts.map +1 -1
  7. package/dist/color/management.js +56 -1
  8. package/dist/color/management.js.map +1 -1
  9. package/dist/color/profile.d.ts +32 -0
  10. package/dist/color/profile.d.ts.map +1 -0
  11. package/dist/color/profile.js +140 -0
  12. package/dist/color/profile.js.map +1 -0
  13. package/dist/comments/index.d.ts +2 -2
  14. package/dist/comments/index.js +2 -2
  15. package/dist/comments/merge.d.ts.map +1 -1
  16. package/dist/comments/merge.js +1 -0
  17. package/dist/comments/merge.js.map +1 -1
  18. package/dist/comments/schema.d.ts +3 -1
  19. package/dist/comments/schema.d.ts.map +1 -1
  20. package/dist/comments/schema.js +19 -2
  21. package/dist/comments/schema.js.map +1 -1
  22. package/dist/comments/threads.d.ts +3 -1
  23. package/dist/comments/threads.d.ts.map +1 -1
  24. package/dist/comments/threads.js +2 -1
  25. package/dist/comments/threads.js.map +1 -1
  26. package/dist/components/properties.d.ts.map +1 -1
  27. package/dist/components/properties.js +7 -7
  28. package/dist/components/properties.js.map +1 -1
  29. package/dist/css/shadows.d.ts +2 -2
  30. package/dist/css/shadows.d.ts.map +1 -1
  31. package/dist/css/shadows.js +4 -4
  32. package/dist/css/shadows.js.map +1 -1
  33. package/dist/css/values.d.ts +7 -2
  34. package/dist/css/values.d.ts.map +1 -1
  35. package/dist/css/values.js +8 -4
  36. package/dist/css/values.js.map +1 -1
  37. package/dist/empty-values.js +9 -0
  38. package/dist/empty-values.js.map +1 -1
  39. package/dist/graph.d.ts +4 -0
  40. package/dist/graph.d.ts.map +1 -1
  41. package/dist/graph.js +11 -2
  42. package/dist/graph.js.map +1 -1
  43. package/dist/images.d.ts +3 -2
  44. package/dist/images.d.ts.map +1 -1
  45. package/dist/images.js +18 -2
  46. package/dist/images.js.map +1 -1
  47. package/dist/index.d.ts +2 -2
  48. package/dist/instances/copies.js +2 -1
  49. package/dist/instances/copies.js.map +1 -1
  50. package/dist/instances/index.d.ts.map +1 -1
  51. package/dist/instances/index.js +12 -11
  52. package/dist/instances/index.js.map +1 -1
  53. package/dist/instances/overrides.d.ts +15 -1
  54. package/dist/instances/overrides.d.ts.map +1 -1
  55. package/dist/instances/overrides.js +37 -1
  56. package/dist/instances/overrides.js.map +1 -1
  57. package/dist/instances/swap-overrides.js +3 -3
  58. package/dist/instances/swap-overrides.js.map +1 -1
  59. package/dist/instances/sync.js +9 -7
  60. package/dist/instances/sync.js.map +1 -1
  61. package/dist/node-defaults.js +2 -2
  62. package/dist/node-defaults.js.map +1 -1
  63. package/dist/plugin-data/fields.d.ts +15 -0
  64. package/dist/plugin-data/fields.d.ts.map +1 -1
  65. package/dist/plugin-data/fields.js +15 -23
  66. package/dist/plugin-data/fields.js.map +1 -1
  67. package/dist/plugin-data/index.d.ts +2 -2
  68. package/dist/plugin-data/index.js +2 -2
  69. package/dist/plugin-data/schema.d.ts +6 -1
  70. package/dist/plugin-data/schema.d.ts.map +1 -1
  71. package/dist/plugin-data/schema.js +24 -1
  72. package/dist/plugin-data/schema.js.map +1 -1
  73. package/dist/shaders/animation.d.ts +21 -0
  74. package/dist/shaders/animation.d.ts.map +1 -0
  75. package/dist/shaders/animation.js +25 -0
  76. package/dist/shaders/animation.js.map +1 -0
  77. package/dist/shaders/index.d.ts +2 -1
  78. package/dist/shaders/index.js +2 -1
  79. package/dist/slots/content.d.ts.map +1 -1
  80. package/dist/slots/content.js +4 -4
  81. package/dist/slots/content.js.map +1 -1
  82. package/dist/statuses/index.d.ts +2 -2
  83. package/dist/statuses/index.js +2 -2
  84. package/dist/statuses/workflow.d.ts +3 -1
  85. package/dist/statuses/workflow.d.ts.map +1 -1
  86. package/dist/statuses/workflow.js +6 -2
  87. package/dist/statuses/workflow.js.map +1 -1
  88. package/dist/transfer/variables.d.ts.map +1 -1
  89. package/dist/transfer/variables.js +1 -1
  90. package/dist/transfer/variables.js.map +1 -1
  91. package/dist/types.d.ts +34 -2
  92. package/dist/types.d.ts.map +1 -1
  93. package/dist/types.js.map +1 -1
  94. package/dist/variables/bindings.d.ts +6 -5
  95. package/dist/variables/bindings.d.ts.map +1 -1
  96. package/dist/variables/bindings.js +24 -16
  97. package/dist/variables/bindings.js.map +1 -1
  98. package/dist/variables/formula/index.d.ts.map +1 -1
  99. package/dist/variables/formula/index.js +12 -6
  100. package/dist/variables/formula/index.js.map +1 -1
  101. package/dist/variables/index.d.ts +14 -1
  102. package/dist/variables/index.d.ts.map +1 -1
  103. package/dist/variables/index.js +38 -10
  104. package/dist/variables/index.js.map +1 -1
  105. package/dist/variables/paints.d.ts +9 -8
  106. package/dist/variables/paints.d.ts.map +1 -1
  107. package/dist/variables/paints.js +35 -26
  108. package/dist/variables/paints.js.map +1 -1
  109. package/dist/variables/resolver.d.ts +45 -0
  110. package/dist/variables/resolver.d.ts.map +1 -0
  111. package/dist/variables/resolver.js +106 -0
  112. package/dist/variables/resolver.js.map +1 -0
  113. package/package.json +1 -1
  114. package/src/color/index.ts +43 -9
  115. package/src/color/management.ts +54 -1
  116. package/src/color/profile.ts +131 -0
  117. package/src/comments/merge.ts +3 -0
  118. package/src/comments/schema.ts +32 -2
  119. package/src/comments/threads.ts +5 -2
  120. package/src/components/properties.ts +13 -7
  121. package/src/css/shadows.ts +8 -5
  122. package/src/css/values.ts +12 -5
  123. package/src/empty-values.ts +16 -0
  124. package/src/graph.ts +13 -1
  125. package/src/images.ts +27 -3
  126. package/src/instances/copies.ts +2 -1
  127. package/src/instances/index.ts +19 -11
  128. package/src/instances/overrides.ts +49 -0
  129. package/src/instances/swap-overrides.ts +3 -2
  130. package/src/instances/sync.ts +11 -7
  131. package/src/node-defaults.ts +2 -2
  132. package/src/plugin-data/fields.ts +16 -31
  133. package/src/plugin-data/index.ts +1 -0
  134. package/src/plugin-data/schema.ts +30 -0
  135. package/src/shaders/animation.ts +39 -0
  136. package/src/shaders/index.ts +1 -0
  137. package/src/slots/content.ts +8 -4
  138. package/src/statuses/workflow.ts +6 -4
  139. package/src/transfer/variables.ts +2 -1
  140. package/src/types.ts +30 -1
  141. package/src/variables/bindings.ts +35 -18
  142. package/src/variables/formula/index.ts +19 -18
  143. package/src/variables/index.ts +49 -10
  144. package/src/variables/paints.ts +64 -29
  145. package/src/variables/resolver.ts +178 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/index.ts"],"sourcesContent":["import type { NodeCloneMode } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { shapeGeometryChanges } from '../resize'\nimport { slotScope } from '../slots/content'\nimport { detachOwnedSlotContent, restoreOwnedSlotContent } from '../slots/frames'\nimport { changesMoreThanStrokeLines } from '../strokes'\nimport type { SceneNode } from '../types'\nimport { applyBoundPaintColorsIn, keepCopyBoundPaints } from '../variables/paints'\nimport { keepOwnContentSize } from './content-size'\nimport { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from './copies'\nimport { canCreateInstance, createsComponentCycle } from './cycles'\nimport {\n INSTANCE_FRAME_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_PROPS\n} from './fields'\nimport { differingVariableModeCollections } from './modes'\nimport {\n assignmentOverrideField,\n cloneInstanceOverrideState,\n copiedComponentLayerId,\n createInstanceOverrideState,\n getInstanceOverride,\n hasInstanceOverride as hasNodeInstanceOverride,\n type InstanceOverrideState,\n overriddenAssignmentId,\n REPLACED_LAYER_OVERRIDE,\n setInstanceOverride,\n variableModeOverrideField\n} from './overrides'\nimport { owningInstance, replacedLayerIn } from './replacements'\nimport { walkInstanceSources } from './source-walk'\nimport { captureInstanceOverrides, restoreInstanceOverrides } from './swap-overrides'\nimport {\n applySyncedStrokeLines,\n bindingProtection,\n cloneChildrenWithMapping,\n copyProp,\n enclosingInstanceOverrideFields,\n isProtectedSyncField,\n sourceInTargetCoordinates,\n syncBindingFields,\n syncChildren,\n syncVariableModeFields,\n updateSyncedProps\n} from './sync'\n\nexport { canCreateInstance, createsComponentCycle, cycleSafeParent } from './cycles'\nexport { walkInstanceSources } from './source-walk'\nexport { instanceMainComponent } from './main-component'\nexport {\n isInShownReplacedLayer,\n isReplacedLayer,\n owningInstance,\n replacedComponentLayerId,\n showsReplacedLayer\n} from './replacements'\nexport {\n INSTANCE_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_FIELDS,\n INSTANCE_SYNC_PROPS,\n INSTANCE_SYNC_TEXT_PROPS\n} from './fields'\n\nexport function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {\n const props: Partial<SceneNode> = {}\n // A new instance starts with the fields its component frame lends it, as resyncing one does.\n for (const key of [...INSTANCE_SYNC_PROPS, ...INSTANCE_FRAME_FOLLOWED_FIELDS])\n copyProp(props, component, key)\n return props\n}\n\n/**\n * The name Figma gives a new instance of `component`: its component set's name for a variant,\n * whose own name only says which variant it is, and the component's own name otherwise.\n */\nfunction instanceComponentName(graph: SceneGraph, component: SceneNode): string {\n const parent = component.parentId ? graph.nodes.get(component.parentId) : undefined\n return parent?.type === 'COMPONENT_SET' ? parent.name : component.name\n}\n\nexport function createInstance(\n graph: SceneGraph,\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n): SceneNode | null {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))\n return null\n\n const props: Partial<SceneNode> = {\n ...copyInstanceComponentProps(component),\n name: instanceComponentName(graph, component)\n }\n\n // The component checked above is the one the instance shows, whatever `overrides` holds.\n const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })\n\n cloneChildrenWithMapping(graph, component.id, instance.id)\n // A copy shows its bound paints in its own context, not as its component's paints hold them.\n applyBoundPaintColorsIn(graph, instance.id)\n\n return instance\n}\n\nexport function populateInstanceChildren(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || !component || instance.type !== 'INSTANCE') return\n cloneChildrenWithMapping(graph, componentId, instanceId, mode)\n}\n\n/**\n * A nested instance's link to the enclosing component's record is its `componentId` when it\n * was populated by cloning. A swap replaces that field, so keep the correspondence as the\n * owner's `sourceComponentId` override and record the swap itself; materialized documents\n * already carry the correspondence and only gain the swap.\n */\nfunction recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {\n const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined\n if (!owner) return\n const existing = getInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId'\n )\n if (typeof existing !== 'string' && instance.componentId)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId',\n instance.componentId\n )\n setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, 'componentId', componentId)\n graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })\n}\n\nexport interface SwapInstanceOptions {\n /**\n * Keep the instance's name even when it is its old component's. A swap otherwise renames such\n * an instance after the new component, as Figma does; a view that only shows another variant,\n * such as preview, keeps names so layer paths stay the same.\n */\n keepName?: boolean\n /**\n * Keep the overrides the instance's layers record, matched to the layers of the new component\n * that take their places, as Figma keeps them when a variant changes. A swap that only\n * materializes a layer the caller re-applies itself, such as a pen icon's glyph, skips this:\n * what the placeholder recorded is scaffolding, not a user's edit.\n */\n restoreOverrides?: boolean\n}\n\nexport function swapInstanceComponent(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n { keepName = false, restoreOverrides = true }: SwapInstanceOptions = {}\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return\n if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return\n\n const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined\n recordNestedSwap(graph, instance, componentId)\n const updates: Partial<SceneNode> = { componentId }\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const overridden = (field: string) =>\n hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, field)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key === 'variableModes' || overridden(key)) continue\n copyProp(updates, source, key)\n }\n syncVariableModeFields(instance, source, updates, overridden)\n applySyncedStrokeLines(graph, instance, updates, overridden)\n\n if (\n !keepName &&\n (!previousComponent || instance.name === instanceComponentName(graph, previousComponent))\n )\n updates.name = instanceComponentName(graph, component)\n\n keepCopyBoundPaints(graph, instance, updates)\n const childIds = Array.from(instance.childIds)\n const slotContent = detachOwnedSlotContent(graph, instance)\n swapInstanceLayers(graph, instanceId, componentId, updates, childIds, restoreOverrides)\n restoreOwnedSlotContent(graph, instance, slotContent)\n}\n\n/**\n * Replaces the instance's layers with clones of its new component's and gives the recorded\n * overrides back to the layers that take the old ones' places, matched by name path.\n */\nfunction swapInstanceLayers(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n updates: Partial<SceneNode>,\n childIds: string[],\n restoreOverrides: boolean\n): void {\n // The clones take new IDs, so what was recorded for the removed layers only applies again once\n // it is matched to the layers of the new component that take their places.\n const capturedOverrides = restoreOverrides\n ? captureInstanceOverrides(graph, graph.nodes.get(instanceId) as SceneNode)\n : undefined\n for (const childId of childIds) {\n forgetOverridesOf(graph, childId)\n graph.deleteNode(childId)\n }\n graph.updateNode(instanceId, updates)\n cloneChildrenWithMapping(graph, componentId, instanceId)\n applyBoundPaintColorsIn(graph, instanceId)\n const swapped = graph.nodes.get(instanceId)\n if (swapped && capturedOverrides) restoreInstanceOverrides(graph, swapped, capturedOverrides)\n}\n\nconst syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()\n\nexport function syncInstances(graph: SceneGraph, componentId: string): void {\n syncInstancesOf(graph, componentId, getInstances(graph, componentId))\n}\n\n/**\n * Syncs each component's instances, in order, as one edit: the copies they remove stay\n * restorable together for as long as undo keeps that edit.\n */\nexport function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {\n groupCopyRemovals(graph, () => {\n for (const id of componentIds) syncInstances(graph, id)\n })\n}\n\n/** Syncs one instance from its component, as `syncInstances` does for every instance. */\nexport function syncInstance(graph: SceneGraph, instanceId: string): void {\n const instance = graph.nodes.get(instanceId)\n if (instance?.type !== 'INSTANCE' || !instance.componentId) return\n syncInstancesOf(graph, instance.componentId, [instance])\n}\n\nfunction syncInstancesOf(\n graph: SceneGraph,\n componentId: string,\n instances: Iterable<SceneNode>\n): void {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT') return\n let syncing = syncingComponentsByGraph.get(graph)\n if (!syncing) {\n syncing = new Set()\n syncingComponentsByGraph.set(graph, syncing)\n }\n if (syncing.has(componentId)) return\n syncing.add(componentId)\n try {\n groupCopyRemovals(graph, (removals) => {\n for (const instance of instances) {\n const enclosing = enclosingInstanceOverrideFields(graph, instance)\n enclosing.push(new Set(instance.instanceOverrides.self.keys()))\n const protectedField = bindingProtection(enclosing)\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const updates: Partial<SceneNode> = {}\n syncBindingFields(instance, source, updates, protectedField)\n syncVariableModeFields(instance, source, updates, protectedField)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key === 'boundVariables' || key === 'variableModes') continue\n if (isProtectedSyncField(instance, key, protectedField)) continue\n copyProp(updates, source, key)\n }\n // The file keeps one value for the instance frame and its component, so the frame takes\n // those the layers inside an instance may not set.\n for (const key of INSTANCE_FRAME_FOLLOWED_FIELDS) {\n if (!isProtectedSyncField(instance, key, protectedField)) copyProp(updates, source, key)\n }\n // An instance that hugs its layers sizes to what it shows, not to the component.\n keepOwnContentSize(graph, updates, instance, source)\n // A size that follows the component invalidates outlines the file saved on the instance;\n // its live box draws them again.\n if (updates.width !== undefined || updates.height !== undefined) {\n Object.assign(\n updates,\n shapeGeometryChanges(\n instance,\n updates.width ?? instance.width,\n updates.height ?? instance.height\n )\n )\n }\n updateSyncedProps(graph, instance, updates, (key) =>\n isProtectedSyncField(instance, key, protectedField)\n )\n const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)\n syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)\n removeLeftoverCopies(graph, context, removals)\n }\n })\n } finally {\n syncing.delete(componentId)\n }\n}\n\n/**\n * Renames the layers that the copied instances among `copies` record overrides for to their\n * copies, as a copied instance records its own layers' overrides. The values keep naming what\n * they name, since a copy shows the same components as its source.\n */\nexport function retargetCopiedOverrides(\n graph: SceneGraph,\n copies: ReadonlyMap<string, string>\n): void {\n for (const id of copies.values()) {\n const node = graph.nodes.get(id)\n if (node?.type !== 'INSTANCE' || node.instanceOverrides.descendants.size === 0) continue\n const descendants = new Map(\n [...node.instanceOverrides.descendants].map(([target, fields]) => [\n copies.get(target) ?? target,\n fields\n ])\n )\n graph.updateNode(id, { instanceOverrides: { ...node.instanceOverrides, descendants } })\n }\n}\n\nexport function detachInstance(graph: SceneGraph, instanceId: string): void {\n const node = graph.nodes.get(instanceId)\n if (node?.type !== 'INSTANCE') return\n for (const nested of outermostNestedInstances(graph, node))\n adoptNestedOverrides(graph, node, nested)\n // Through `updateNode`, so the instance index, change observers, and undo recorders see it.\n graph.updateNode(instanceId, {\n type: 'FRAME',\n componentId: null,\n instanceOverrides: createInstanceOverrideState()\n })\n // Its mirrored layers stand on their own: a component child id would name a layer of another\n // node, which the format never stores and a later sync would read as a link back. A nested\n // instance is not a mirror and keeps its own links, which its overrides are written through.\n const detachLinks = (parentId: string): void => {\n for (const child of graph.getChildren(parentId)) {\n if (child.type === 'INSTANCE') continue\n if (child.componentId) graph.updateNode(child.id, { componentId: null })\n detachLinks(child.id)\n }\n }\n detachLinks(instanceId)\n}\n\n// A swap's bookkeeping belongs to the instance enclosing the swapped one, never to the swapped one.\nconst OWNER_ONLY_FIELDS = new Set(['componentId', 'sourceComponentId'])\n\nfunction outermostNestedInstances(graph: SceneGraph, instance: SceneNode): SceneNode[] {\n return graph\n .getChildren(instance.id)\n .flatMap((child) =>\n child.type === 'INSTANCE' ? [child] : outermostNestedInstances(graph, child)\n )\n}\n\n/**\n * An instance a detached one holds stands on its own once that one is a frame, and so must what\n * makes it differ from its component. Cloned in, it kept the overrides of the instance it copies,\n * under that instance's layers; those, and the ones the detached instance recorded on its layers,\n * now go under its own.\n */\nfunction adoptNestedOverrides(graph: SceneGraph, detached: SceneNode, nested: SceneNode): void {\n const ownLayer = new Map<string, string>()\n walkInstanceSources(graph, nested, (source, target) => {\n ownLayer.set(source.id, target.id)\n return true\n })\n const { self, descendants: kept } = cloneInstanceOverrideState(nested.instanceOverrides)\n const outer = cloneInstanceOverrideState(detached.instanceOverrides).descendants\n const descendants = new Map<string, Map<string, unknown>>()\n const claim = (layerId: string, fields: Map<string, unknown>): void => {\n const merged = descendants.get(layerId)\n if (!merged) descendants.set(layerId, fields)\n else for (const [field, value] of fields) merged.set(field, value)\n }\n // What was recorded on its own layers is more recent than what it copied, so it is laid on top.\n for (const [layerId, fields] of kept)\n if (ownLayer.has(layerId)) claim(ownLayer.get(layerId) ?? layerId, fields)\n for (const [layerId, fields] of kept) if (!ownLayer.has(layerId)) claim(layerId, fields)\n for (const [layerId, fields] of outer) {\n if (layerId === nested.id) {\n for (const [field, value] of fields) if (!OWNER_ONLY_FIELDS.has(field)) self.set(field, value)\n } else if (graph.isDescendant(layerId, nested.id)) claim(layerId, fields)\n }\n graph.updateNode(nested.id, { instanceOverrides: { self, descendants } })\n}\n\nexport function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {\n const node = graph.nodes.get(instanceId)\n if (!node?.componentId) return undefined\n return graph.nodes.get(node.componentId)\n}\n\nexport function getInstances(graph: SceneGraph, componentId: string): SceneNode[] {\n const ids = graph.instanceIndex.get(componentId)\n if (!ids) return []\n const instances: SceneNode[] = []\n for (const id of ids) {\n const node = graph.nodes.get(id)\n if (node) instances.push(node)\n }\n return instances\n}\n\n/** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */\nexport function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNode | undefined {\n let current = graph.nodes.get(nodeId)\n while (current) {\n if (current.type === 'INSTANCE') return current\n current = current.parentId ? graph.nodes.get(current.parentId) : undefined\n }\n return undefined\n}\n\n/**\n * Whether Figma lets this layer take a size of its own: a layer inside an instance shows its\n * component's size and cannot be resized, while an instance nested in another may be.\n */\nexport function takesOwnSize(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'INSTANCE' || !node.parentId || !findInstanceAncestor(graph, node.parentId)\n}\n\n/**\n * True when a node field is protected from instance synchronization.\n */\nexport function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return false\n return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\n/**\n * The layer of the component an instance layer copies, which its overrides are measured\n * against: the instance's component for the instance itself.\n */\nfunction copiedLayer(graph: SceneGraph, instance: SceneNode, node: SceneNode) {\n const id =\n node.id === instance.id\n ? instance.componentId\n : copiedComponentLayerId(instance.instanceOverrides, instance.id, node)\n return id ? graph.nodes.get(id) : undefined\n}\n\n/**\n * The override fields an edit of these fields records. A mode edit claims only the collections\n * whose mode now differs from the component layer's, so the component's other modes still\n * reach the layer; with no layer to compare, it claims every mode.\n */\nfunction overrideFieldsOf(\n graph: SceneGraph,\n instance: SceneNode,\n nodeId: string,\n fields: string[]\n): string[] {\n if (!fields.includes('variableModes')) return fields\n const node = graph.nodes.get(nodeId)\n const source = node && copiedLayer(graph, instance, node)\n if (!node || !source) return fields\n return [\n ...fields.filter((field) => field !== 'variableModes'),\n ...differingVariableModeCollections(node, source).map(variableModeOverrideField)\n ]\n}\n\n/**\n * The instance above `instanceId` that records an assignment made through it: an assignment of a\n * nested instance's property is an edit of the instance it sits in, not of the nested instance.\n */\nexport function assignmentOverrideOwner(\n graph: SceneGraph,\n instanceId: string\n): SceneNode | undefined {\n const parentId = graph.nodes.get(instanceId)?.parentId\n return parentId ? findInstanceAncestor(graph, parentId) : undefined\n}\n\n/** The overrides an assignment edit writes on the instance above it, for undo to restore. */\nexport interface AssignmentOverrideState {\n ownerId: string\n overrides: InstanceOverrideState\n}\n\nexport function takeAssignmentOverrideState(\n graph: SceneGraph,\n instanceId: string\n): AssignmentOverrideState | undefined {\n const owner = assignmentOverrideOwner(graph, instanceId)\n return owner\n ? { ownerId: owner.id, overrides: cloneInstanceOverrideState(owner.instanceOverrides) }\n : undefined\n}\n\nexport function restoreAssignmentOverrideState(\n graph: SceneGraph,\n state: AssignmentOverrideState\n): void {\n graph.updateNode(state.ownerId, {\n instanceOverrides: cloneInstanceOverrideState(state.overrides)\n })\n}\n\n/**\n * Records that an instance assigned one of its component properties, as an edit of the instance\n * above it: the assignment is made through the outer instance, so a text override of the same\n * level does not outrank it. A top-level instance has no outer instance to record it on.\n */\nexport function recordAssignmentOverride(\n graph: SceneGraph,\n instanceId: string,\n propertyId: string,\n value: string\n): void {\n const outer = assignmentOverrideOwner(graph, instanceId)\n if (!outer) return\n setInstanceOverride(\n outer.instanceOverrides,\n outer.id,\n instanceId,\n assignmentOverrideField(propertyId),\n value\n )\n graph.updateNode(outer.id, { instanceOverrides: outer.instanceOverrides })\n}\n\n/**\n * The fields `changes` overrides on an instance layer. New strokes that change only what the\n * layer's line fields say override those fields, not the paints (`changesMoreThanStrokeLines`).\n */\nexport function instanceOverrideFields(node: SceneNode, changes: Partial<SceneNode>): string[] {\n const fields = Object.keys(changes)\n if (!changes.strokes || changesMoreThanStrokeLines(node, changes)) return fields\n return fields.filter((field) => field !== 'strokes')\n}\n\nexport function recordInstanceOverride(\n graph: SceneGraph,\n nodeId: string,\n fields: Iterable<string>\n): void {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return\n\n const relevant = overrideFieldsOf(\n graph,\n instance,\n nodeId,\n [...fields].filter(\n (field) =>\n (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field) ||\n overriddenAssignmentId(field) !== null\n )\n )\n\n const added = relevant.filter(\n (field) => !hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n )\n if (added.length === 0) return\n\n // A new state rather than an edit of the old one, so a preview that captured the old state\n // puts it back on cancel.\n const overrides = cloneInstanceOverrideState(instance.instanceOverrides)\n for (const field of added) setInstanceOverride(overrides, instance.id, nodeId, field)\n graph.updateNode(instance.id, { instanceOverrides: overrides })\n}\n\n/** Every layer at or below `rootId`. */\nfunction subtreeIds(graph: SceneGraph, rootId: string): string[] {\n const ids: string[] = []\n const visit = (id: string) => {\n ids.push(id)\n for (const childId of graph.nodes.get(id)?.childIds ?? []) visit(childId)\n }\n visit(rootId)\n return ids\n}\n\n/** Forget what the instances above `nodeId` recorded for it and the layers inside it. */\nfunction forgetOverridesOf(graph: SceneGraph, nodeId: string): void {\n const ids = subtreeIds(graph, nodeId)\n const parentId = graph.nodes.get(nodeId)?.parentId\n if (!parentId) return\n graph.closest(parentId, (ancestor) => {\n if (ancestor.type !== 'INSTANCE') return false\n const { descendants } = ancestor.instanceOverrides\n if (ids.some((id) => descendants.delete(id)))\n graph.updateNode(ancestor.id, { instanceOverrides: ancestor.instanceOverrides })\n return false\n })\n}\n\n/** Whether a layer can be replaced in its instance: it sits in the part the component owns. */\nexport function canReplaceInstanceLayer(graph: SceneGraph, nodeId: string): boolean {\n const node = graph.nodes.get(nodeId)\n const owner = node && owningInstance(graph, node)\n if (!node?.parentId || !owner) return false\n // Slot content is the instance's own already, and a generated frame's layers are fixed.\n const scope = slotScope(graph, node.parentId)\n if (scope.kind !== 'locked' || scope.owner.type !== 'INSTANCE') return false\n return (\n replacedLayerIn(owner, node.id) !== undefined ||\n copiedComponentLayerId(owner.instanceOverrides, owner.id, node) !== undefined\n )\n}\n\n/**\n * Put `replacementId` in place of `targetId`, a layer an instance copies from its component, as\n * an override of the nearest instance above it, as pen.dev replaces a layer inside an instance.\n * The replacement takes the target's place among its siblings and its position, the target\n * goes, and syncs keep the replacement in place of the component layer the target copied. A\n * replaced layer can be replaced again. Returns false and changes nothing when the target is no\n * such layer, or the replacement cannot go there.\n */\nexport function replaceInstanceLayer(\n graph: SceneGraph,\n targetId: string,\n replacementId: string\n): boolean {\n const target = graph.nodes.get(targetId)\n const replacement = graph.nodes.get(replacementId)\n const parentId = target?.parentId\n if (!target || !replacement || !parentId || targetId === replacementId) return false\n const owner = owningInstance(graph, target)\n if (!owner || graph.isDescendant(parentId, replacementId)) return false\n if (createsComponentCycle(graph, replacementId, parentId)) return false\n const layerId =\n replacedLayerIn(owner, target.id) ??\n copiedComponentLayerId(owner.instanceOverrides, owner.id, target)\n if (!layerId) return false\n\n // The replacement copies no layer of the component, so its own layers lose such links; an\n // instance among them keeps its own component and layers.\n const unlink = (id: string) => {\n const node = graph.nodes.get(id)\n if (!node) return\n if (node.type !== 'INSTANCE' && node.componentId) graph.updateNode(id, { componentId: null })\n if (node.type !== 'INSTANCE') node.childIds.forEach(unlink)\n }\n unlink(replacementId)\n\n const index = graph.nodes.get(parentId)?.childIds.indexOf(target.id) ?? -1\n forgetOverridesOf(graph, target.id)\n forgetOverridesOf(graph, replacementId)\n graph.insertChildAt(replacementId, parentId, index < 0 ? Number.MAX_SAFE_INTEGER : index)\n graph.updateNode(replacementId, {\n x: target.x,\n y: target.y,\n layoutPositioning: target.layoutPositioning,\n horizontalConstraint: target.horizontalConstraint,\n verticalConstraint: target.verticalConstraint\n })\n graph.deleteNode(target.id)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n replacementId,\n REPLACED_LAYER_OVERRIDE,\n layerId\n )\n graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })\n return true\n}\n\n/**\n * Take a replaced layer out and bring back the component layer it stood in for, synced from the\n * outermost instance as a reset syncs. Returns false when the layer is not a replaced one.\n */\nexport function restoreReplacedLayer(graph: SceneGraph, nodeId: string): boolean {\n const node = graph.nodes.get(nodeId)\n const owner = node && owningInstance(graph, node)\n if (!node || !owner || replacedLayerIn(owner, nodeId) === undefined) return false\n let outermost = owner\n for (let above = owningInstance(graph, owner); above; above = owningInstance(graph, above))\n outermost = above\n forgetOverridesOf(graph, nodeId)\n graph.deleteNode(nodeId)\n syncInstance(graph, outermost.id)\n // An enclosing sync stops at a swapped instance, which brings its layers back itself.\n const above = owningInstance(graph, owner)\n if (above && getInstanceOverride(above.instanceOverrides, above.id, owner.id, 'componentId'))\n syncInstance(graph, owner.id)\n return true\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiEA,SAAgB,2BAA2B,WAA0C;CACnF,MAAM,QAA4B,CAAC;CAEnC,KAAK,MAAM,OAAO,CAAC,GAAG,qBAAqB,GAAG,8BAA8B,GAC1E,SAAS,OAAO,WAAW,GAAG;CAChC,OAAO;AACT;;;;;AAMA,SAAS,sBAAsB,OAAmB,WAA8B;CAC9E,MAAM,SAAS,UAAU,WAAW,MAAM,MAAM,IAAI,UAAU,QAAQ,IAAI,KAAA;CAC1E,OAAO,QAAQ,SAAS,kBAAkB,OAAO,OAAO,UAAU;AACpE;AAEA,SAAgB,eACd,OACA,aACA,UACA,YAAgC,CAAC,GACf;CAClB,MAAM,YAAY,MAAM,MAAM,IAAI,WAAW;CAC7C,IAAI,WAAW,SAAS,eAAe,CAAC,kBAAkB,OAAO,aAAa,QAAQ,GACpF,OAAO;CAET,MAAM,QAA4B;EAChC,GAAG,2BAA2B,SAAS;EACvC,MAAM,sBAAsB,OAAO,SAAS;CAC9C;CAGA,MAAM,WAAW,MAAM,WAAW,YAAY,UAAU;EAAE,GAAG;EAAO,GAAG;EAAW;CAAY,CAAC;CAE/F,yBAAyB,OAAO,UAAU,IAAI,SAAS,EAAE;CAEzD,wBAAwB,OAAO,SAAS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Ae,UAAU,QAAQ,IAAI,OAAO,mBAAmB,KAAK;CACxF,MAAM,WAAW,eAAe;EAC9B,GAAG,OAAO;EACV,GAAG,OAAO;EACV,mBAAmB,OAAO;EAC1B,sBAAsB,OAAO;EAC7B,oBAAoB,OAAO;CAC7B,CAAC;CACD,MAAM,WAAW,OAAO,EAAE;CAC1B,oBACE,MAAM,mBACN,MAAM,IACN,eACA,yBACA,OACF;CACA,MAAM,WAAW,MAAM,IAAI,EAAE,mBAAmB,MAAM,kBAAkB,CAAC;CACzE,OAAO;AACT;;;;;AAMA,SAAgB,qBAAqB,OAAmB,QAAyB;CAC/E,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,MAAM,QAAQ,QAAQ,eAAe,OAAO,IAAI;CAChD,IAAI,CAAC,QAAQ,CAAC,SAAS,gBAAgB,OAAO,MAAM,MAAM,KAAA,GAAW,OAAO;CAC5E,IAAI,YAAY;CAChB,KAAK,IAAI,QAAQ,eAAe,OAAO,KAAK,GAAG,OAAO,QAAQ,eAAe,OAAO,KAAK,GACvF,YAAY;CACd,kBAAkB,OAAO,MAAM;CAC/B,MAAM,WAAW,MAAM;CACvB,aAAa,OAAO,UAAU,EAAE;CAEhC,MAAM,QAAQ,eAAe,OAAO,KAAK;CACzC,IAAI,SAAS,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,MAAM,IAAI,aAAa,GACzF,aAAa,OAAO,MAAM,EAAE;CAC9B,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/index.ts"],"sourcesContent":["import type { NodeCloneMode } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { shapeGeometryChanges } from '../resize'\nimport { slotScope } from '../slots/content'\nimport { detachOwnedSlotContent, restoreOwnedSlotContent } from '../slots/frames'\nimport { changesMoreThanStrokeLines } from '../strokes'\nimport type { SceneNode } from '../types'\nimport { applyBoundPaintColorsIn, keepCopyBoundPaints } from '../variables/paints'\nimport { keepOwnContentSize } from './content-size'\nimport { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from './copies'\nimport { canCreateInstance, createsComponentCycle } from './cycles'\nimport {\n INSTANCE_FRAME_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_PROPS\n} from './fields'\nimport { differingVariableModeCollections } from './modes'\nimport {\n assignmentOverrideField,\n cloneInstanceOverrideState,\n copiedComponentLayerId,\n createInstanceOverrideState,\n getInstanceOverride,\n hasInstanceOverride as hasNodeInstanceOverride,\n type InstanceOverrideState,\n overriddenAssignmentId,\n ownInstanceOverrides,\n REPLACED_LAYER_OVERRIDE,\n setInstanceOverride,\n variableModeOverrideField\n} from './overrides'\nimport { owningInstance, replacedLayerIn } from './replacements'\nimport { walkInstanceSources } from './source-walk'\nimport { captureInstanceOverrides, restoreInstanceOverrides } from './swap-overrides'\nimport {\n applySyncedStrokeLines,\n bindingProtection,\n cloneChildrenWithMapping,\n copyProp,\n enclosingInstanceOverrideFields,\n isProtectedSyncField,\n sourceInTargetCoordinates,\n syncBindingFields,\n syncChildren,\n syncVariableModeFields,\n updateSyncedProps\n} from './sync'\n\nexport { canCreateInstance, createsComponentCycle, cycleSafeParent } from './cycles'\nexport { walkInstanceSources } from './source-walk'\nexport { instanceMainComponent } from './main-component'\nexport {\n isInShownReplacedLayer,\n isReplacedLayer,\n owningInstance,\n replacedComponentLayerId,\n showsReplacedLayer\n} from './replacements'\nexport {\n INSTANCE_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_FIELDS,\n INSTANCE_SYNC_PROPS,\n INSTANCE_SYNC_TEXT_PROPS\n} from './fields'\n\nexport function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {\n const props: Partial<SceneNode> = {}\n // A new instance starts with the fields its component frame lends it, as resyncing one does.\n for (const key of [...INSTANCE_SYNC_PROPS, ...INSTANCE_FRAME_FOLLOWED_FIELDS])\n copyProp(props, component, key)\n return props\n}\n\n/**\n * The name Figma gives a new instance of `component`: its component set's name for a variant,\n * whose own name only says which variant it is, and the component's own name otherwise.\n */\nfunction instanceComponentName(graph: SceneGraph, component: SceneNode): string {\n const parent = component.parentId ? graph.nodes.get(component.parentId) : undefined\n return parent?.type === 'COMPONENT_SET' ? parent.name : component.name\n}\n\nexport function createInstance(\n graph: SceneGraph,\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n): SceneNode | null {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))\n return null\n\n const props: Partial<SceneNode> = {\n ...copyInstanceComponentProps(component),\n name: instanceComponentName(graph, component)\n }\n\n // The component checked above is the one the instance shows, whatever `overrides` holds.\n const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })\n\n cloneChildrenWithMapping(graph, component.id, instance.id)\n // A copy shows its bound paints in its own context, not as its component's paints hold them.\n applyBoundPaintColorsIn(graph, instance.id)\n\n return instance\n}\n\nexport function populateInstanceChildren(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || !component || instance.type !== 'INSTANCE') return\n cloneChildrenWithMapping(graph, componentId, instanceId, mode)\n}\n\n/**\n * A nested instance's link to the enclosing component's record is its `componentId` when it\n * was populated by cloning. A swap replaces that field, so keep the correspondence as the\n * owner's `sourceComponentId` override and record the swap itself; materialized documents\n * already carry the correspondence and only gain the swap.\n */\nfunction recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {\n const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined\n if (!owner) return\n const existing = getInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId'\n )\n if (typeof existing !== 'string' && instance.componentId)\n setInstanceOverride(\n ownInstanceOverrides(owner),\n owner.id,\n instance.id,\n 'sourceComponentId',\n instance.componentId\n )\n setInstanceOverride(\n ownInstanceOverrides(owner),\n owner.id,\n instance.id,\n 'componentId',\n componentId\n )\n graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) })\n}\n\nexport interface SwapInstanceOptions {\n /**\n * Keep the instance's name even when it is its old component's. A swap otherwise renames such\n * an instance after the new component, as Figma does; a view that only shows another variant,\n * such as preview, keeps names so layer paths stay the same.\n */\n keepName?: boolean\n /**\n * Keep the overrides the instance's layers record, matched to the layers of the new component\n * that take their places, as Figma keeps them when a variant changes. A swap that only\n * materializes a layer the caller re-applies itself, such as a pen icon's glyph, skips this:\n * what the placeholder recorded is scaffolding, not a user's edit.\n */\n restoreOverrides?: boolean\n}\n\nexport function swapInstanceComponent(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n { keepName = false, restoreOverrides = true }: SwapInstanceOptions = {}\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return\n if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return\n\n const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined\n recordNestedSwap(graph, instance, componentId)\n const updates: Partial<SceneNode> = { componentId }\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const overridden = (field: string) =>\n hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, field)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key === 'variableModes' || overridden(key)) continue\n copyProp(updates, source, key)\n }\n syncVariableModeFields(instance, source, updates, overridden)\n applySyncedStrokeLines(graph, instance, updates, overridden)\n\n if (\n !keepName &&\n (!previousComponent || instance.name === instanceComponentName(graph, previousComponent))\n )\n updates.name = instanceComponentName(graph, component)\n\n keepCopyBoundPaints(graph, instance, updates)\n const childIds = Array.from(instance.childIds)\n const slotContent = detachOwnedSlotContent(graph, instance)\n swapInstanceLayers(graph, instanceId, componentId, updates, childIds, restoreOverrides)\n restoreOwnedSlotContent(graph, instance, slotContent)\n}\n\n/**\n * Replaces the instance's layers with clones of its new component's and gives the recorded\n * overrides back to the layers that take the old ones' places, matched by name path.\n */\nfunction swapInstanceLayers(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n updates: Partial<SceneNode>,\n childIds: string[],\n restoreOverrides: boolean\n): void {\n // The clones take new IDs, so what was recorded for the removed layers only applies again once\n // it is matched to the layers of the new component that take their places.\n const capturedOverrides = restoreOverrides\n ? captureInstanceOverrides(graph, graph.nodes.get(instanceId) as SceneNode)\n : undefined\n for (const childId of childIds) {\n forgetOverridesOf(graph, childId)\n graph.deleteNode(childId)\n }\n graph.updateNode(instanceId, updates)\n cloneChildrenWithMapping(graph, componentId, instanceId)\n applyBoundPaintColorsIn(graph, instanceId)\n const swapped = graph.nodes.get(instanceId)\n if (swapped && capturedOverrides) restoreInstanceOverrides(graph, swapped, capturedOverrides)\n}\n\nconst syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()\n\nexport function syncInstances(graph: SceneGraph, componentId: string): void {\n syncInstancesOf(graph, componentId, getInstances(graph, componentId))\n}\n\n/**\n * Syncs each component's instances, in order, as one edit: the copies they remove stay\n * restorable together for as long as undo keeps that edit.\n */\nexport function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {\n groupCopyRemovals(graph, () => {\n for (const id of componentIds) syncInstances(graph, id)\n })\n}\n\n/** Syncs one instance from its component, as `syncInstances` does for every instance. */\nexport function syncInstance(graph: SceneGraph, instanceId: string): void {\n const instance = graph.nodes.get(instanceId)\n if (instance?.type !== 'INSTANCE' || !instance.componentId) return\n syncInstancesOf(graph, instance.componentId, [instance])\n}\n\nfunction syncInstancesOf(\n graph: SceneGraph,\n componentId: string,\n instances: Iterable<SceneNode>\n): void {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT') return\n let syncing = syncingComponentsByGraph.get(graph)\n if (!syncing) {\n syncing = new Set()\n syncingComponentsByGraph.set(graph, syncing)\n }\n if (syncing.has(componentId)) return\n syncing.add(componentId)\n try {\n groupCopyRemovals(graph, (removals) => {\n for (const instance of instances) {\n const enclosing = enclosingInstanceOverrideFields(graph, instance)\n enclosing.push(new Set(instance.instanceOverrides.self.keys()))\n const protectedField = bindingProtection(enclosing)\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const updates: Partial<SceneNode> = {}\n syncBindingFields(instance, source, updates, protectedField)\n syncVariableModeFields(instance, source, updates, protectedField)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key === 'boundVariables' || key === 'variableModes') continue\n if (isProtectedSyncField(instance, key, protectedField)) continue\n copyProp(updates, source, key)\n }\n // The file keeps one value for the instance frame and its component, so the frame takes\n // those the layers inside an instance may not set.\n for (const key of INSTANCE_FRAME_FOLLOWED_FIELDS) {\n if (!isProtectedSyncField(instance, key, protectedField)) copyProp(updates, source, key)\n }\n // An instance that hugs its layers sizes to what it shows, not to the component.\n keepOwnContentSize(graph, updates, instance, source)\n // A size that follows the component invalidates outlines the file saved on the instance;\n // its live box draws them again.\n if (updates.width !== undefined || updates.height !== undefined) {\n Object.assign(\n updates,\n shapeGeometryChanges(\n instance,\n updates.width ?? instance.width,\n updates.height ?? instance.height\n )\n )\n }\n updateSyncedProps(graph, instance, updates, (key) =>\n isProtectedSyncField(instance, key, protectedField)\n )\n const owned = ownInstanceOverrides(instance)\n const context = createInstanceSyncContext(instance.id, owned)\n syncChildren(graph, component.id, instance.id, owned, context)\n removeLeftoverCopies(graph, context, removals)\n }\n })\n } finally {\n syncing.delete(componentId)\n }\n}\n\n/**\n * Renames the layers that the copied instances among `copies` record overrides for to their\n * copies, as a copied instance records its own layers' overrides. The values keep naming what\n * they name, since a copy shows the same components as its source.\n */\nexport function retargetCopiedOverrides(\n graph: SceneGraph,\n copies: ReadonlyMap<string, string>\n): void {\n for (const id of copies.values()) {\n const node = graph.nodes.get(id)\n if (node?.type !== 'INSTANCE' || node.instanceOverrides.descendants.size === 0) continue\n const descendants = new Map(\n [...node.instanceOverrides.descendants].map(([target, fields]) => [\n copies.get(target) ?? target,\n fields\n ])\n )\n graph.updateNode(id, { instanceOverrides: { ...node.instanceOverrides, descendants } })\n }\n}\n\nexport function detachInstance(graph: SceneGraph, instanceId: string): void {\n const node = graph.nodes.get(instanceId)\n if (node?.type !== 'INSTANCE') return\n for (const nested of outermostNestedInstances(graph, node))\n adoptNestedOverrides(graph, node, nested)\n // Through `updateNode`, so the instance index, change observers, and undo recorders see it.\n graph.updateNode(instanceId, {\n type: 'FRAME',\n componentId: null,\n instanceOverrides: createInstanceOverrideState()\n })\n // Its mirrored layers stand on their own: a component child id would name a layer of another\n // node, which the format never stores and a later sync would read as a link back. A nested\n // instance is not a mirror and keeps its own links, which its overrides are written through.\n const detachLinks = (parentId: string): void => {\n for (const child of graph.getChildren(parentId)) {\n if (child.type === 'INSTANCE') continue\n if (child.componentId) graph.updateNode(child.id, { componentId: null })\n detachLinks(child.id)\n }\n }\n detachLinks(instanceId)\n}\n\n// A swap's bookkeeping belongs to the instance enclosing the swapped one, never to the swapped one.\nconst OWNER_ONLY_FIELDS = new Set(['componentId', 'sourceComponentId'])\n\nfunction outermostNestedInstances(graph: SceneGraph, instance: SceneNode): SceneNode[] {\n return graph\n .getChildren(instance.id)\n .flatMap((child) =>\n child.type === 'INSTANCE' ? [child] : outermostNestedInstances(graph, child)\n )\n}\n\n/**\n * An instance a detached one holds stands on its own once that one is a frame, and so must what\n * makes it differ from its component. Cloned in, it kept the overrides of the instance it copies,\n * under that instance's layers; those, and the ones the detached instance recorded on its layers,\n * now go under its own.\n */\nfunction adoptNestedOverrides(graph: SceneGraph, detached: SceneNode, nested: SceneNode): void {\n const ownLayer = new Map<string, string>()\n walkInstanceSources(graph, nested, (source, target) => {\n ownLayer.set(source.id, target.id)\n return true\n })\n const { self, descendants: kept } = cloneInstanceOverrideState(nested.instanceOverrides)\n const outer = cloneInstanceOverrideState(detached.instanceOverrides).descendants\n const descendants = new Map<string, Map<string, unknown>>()\n const claim = (layerId: string, fields: Map<string, unknown>): void => {\n const merged = descendants.get(layerId)\n if (!merged) descendants.set(layerId, fields)\n else for (const [field, value] of fields) merged.set(field, value)\n }\n // What was recorded on its own layers is more recent than what it copied, so it is laid on top.\n for (const [layerId, fields] of kept)\n if (ownLayer.has(layerId)) claim(ownLayer.get(layerId) ?? layerId, fields)\n for (const [layerId, fields] of kept) if (!ownLayer.has(layerId)) claim(layerId, fields)\n for (const [layerId, fields] of outer) {\n if (layerId === nested.id) {\n for (const [field, value] of fields) if (!OWNER_ONLY_FIELDS.has(field)) self.set(field, value)\n } else if (graph.isDescendant(layerId, nested.id)) claim(layerId, fields)\n }\n graph.updateNode(nested.id, { instanceOverrides: { self, descendants } })\n}\n\nexport function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {\n const node = graph.nodes.get(instanceId)\n if (!node?.componentId) return undefined\n return graph.nodes.get(node.componentId)\n}\n\nexport function getInstances(graph: SceneGraph, componentId: string): SceneNode[] {\n const ids = graph.instanceIndex.get(componentId)\n if (!ids) return []\n const instances: SceneNode[] = []\n for (const id of ids) {\n const node = graph.nodes.get(id)\n if (node) instances.push(node)\n }\n return instances\n}\n\n/** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */\nexport function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNode | undefined {\n let current = graph.nodes.get(nodeId)\n while (current) {\n if (current.type === 'INSTANCE') return current\n current = current.parentId ? graph.nodes.get(current.parentId) : undefined\n }\n return undefined\n}\n\n/**\n * Whether Figma lets this layer take a size of its own: a layer inside an instance shows its\n * component's size and cannot be resized, while an instance nested in another may be.\n */\nexport function takesOwnSize(graph: SceneGraph, node: SceneNode): boolean {\n return node.type === 'INSTANCE' || !node.parentId || !findInstanceAncestor(graph, node.parentId)\n}\n\n/**\n * True when a node field is protected from instance synchronization.\n */\nexport function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return false\n return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\n/**\n * The layer of the component an instance layer copies, which its overrides are measured\n * against: the instance's component for the instance itself.\n */\nfunction copiedLayer(graph: SceneGraph, instance: SceneNode, node: SceneNode) {\n const id =\n node.id === instance.id\n ? instance.componentId\n : copiedComponentLayerId(instance.instanceOverrides, instance.id, node)\n return id ? graph.nodes.get(id) : undefined\n}\n\n/**\n * The override fields an edit of these fields records. A mode edit claims only the collections\n * whose mode now differs from the component layer's, so the component's other modes still\n * reach the layer; with no layer to compare, it claims every mode.\n */\nfunction overrideFieldsOf(\n graph: SceneGraph,\n instance: SceneNode,\n nodeId: string,\n fields: string[]\n): string[] {\n if (!fields.includes('variableModes')) return fields\n const node = graph.nodes.get(nodeId)\n const source = node && copiedLayer(graph, instance, node)\n if (!node || !source) return fields\n return [\n ...fields.filter((field) => field !== 'variableModes'),\n ...differingVariableModeCollections(node, source).map(variableModeOverrideField)\n ]\n}\n\n/**\n * The instance above `instanceId` that records an assignment made through it: an assignment of a\n * nested instance's property is an edit of the instance it sits in, not of the nested instance.\n */\nexport function assignmentOverrideOwner(\n graph: SceneGraph,\n instanceId: string\n): SceneNode | undefined {\n const parentId = graph.nodes.get(instanceId)?.parentId\n return parentId ? findInstanceAncestor(graph, parentId) : undefined\n}\n\n/** The overrides an assignment edit writes on the instance above it, for undo to restore. */\nexport interface AssignmentOverrideState {\n ownerId: string\n overrides: InstanceOverrideState\n}\n\nexport function takeAssignmentOverrideState(\n graph: SceneGraph,\n instanceId: string\n): AssignmentOverrideState | undefined {\n const owner = assignmentOverrideOwner(graph, instanceId)\n return owner\n ? { ownerId: owner.id, overrides: cloneInstanceOverrideState(owner.instanceOverrides) }\n : undefined\n}\n\nexport function restoreAssignmentOverrideState(\n graph: SceneGraph,\n state: AssignmentOverrideState\n): void {\n graph.updateNode(state.ownerId, {\n instanceOverrides: cloneInstanceOverrideState(state.overrides)\n })\n}\n\n/**\n * Records that an instance assigned one of its component properties, as an edit of the instance\n * above it: the assignment is made through the outer instance, so a text override of the same\n * level does not outrank it. A top-level instance has no outer instance to record it on.\n */\nexport function recordAssignmentOverride(\n graph: SceneGraph,\n instanceId: string,\n propertyId: string,\n value: string\n): void {\n const outer = assignmentOverrideOwner(graph, instanceId)\n if (!outer) return\n setInstanceOverride(\n ownInstanceOverrides(outer),\n outer.id,\n instanceId,\n assignmentOverrideField(propertyId),\n value\n )\n graph.updateNode(outer.id, { instanceOverrides: outer.instanceOverrides })\n}\n\n/**\n * The fields `changes` overrides on an instance layer. New strokes that change only what the\n * layer's line fields say override those fields, not the paints (`changesMoreThanStrokeLines`).\n */\nexport function instanceOverrideFields(node: SceneNode, changes: Partial<SceneNode>): string[] {\n const fields = Object.keys(changes)\n if (!changes.strokes || changesMoreThanStrokeLines(node, changes)) return fields\n return fields.filter((field) => field !== 'strokes')\n}\n\nexport function recordInstanceOverride(\n graph: SceneGraph,\n nodeId: string,\n fields: Iterable<string>\n): void {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return\n\n const relevant = overrideFieldsOf(\n graph,\n instance,\n nodeId,\n [...fields].filter(\n (field) =>\n (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field) ||\n overriddenAssignmentId(field) !== null\n )\n )\n\n const added = relevant.filter(\n (field) => !hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n )\n if (added.length === 0) return\n\n // A new state rather than an edit of the old one, so a preview that captured the old state\n // puts it back on cancel.\n const overrides = cloneInstanceOverrideState(instance.instanceOverrides)\n for (const field of added) setInstanceOverride(overrides, instance.id, nodeId, field)\n graph.updateNode(instance.id, { instanceOverrides: overrides })\n}\n\n/** Every layer at or below `rootId`. */\nfunction subtreeIds(graph: SceneGraph, rootId: string): string[] {\n const ids: string[] = []\n const visit = (id: string) => {\n ids.push(id)\n for (const childId of graph.nodes.get(id)?.childIds ?? []) visit(childId)\n }\n visit(rootId)\n return ids\n}\n\n/** Forget what the instances above `nodeId` recorded for it and the layers inside it. */\nfunction forgetOverridesOf(graph: SceneGraph, nodeId: string): void {\n const ids = subtreeIds(graph, nodeId)\n const parentId = graph.nodes.get(nodeId)?.parentId\n if (!parentId) return\n graph.closest(parentId, (ancestor) => {\n if (ancestor.type !== 'INSTANCE') return false\n const owned = ownInstanceOverrides(ancestor)\n if (ids.some((id) => owned.descendants.delete(id)))\n graph.updateNode(ancestor.id, { instanceOverrides: owned })\n return false\n })\n}\n\n/** Whether a layer can be replaced in its instance: it sits in the part the component owns. */\nexport function canReplaceInstanceLayer(graph: SceneGraph, nodeId: string): boolean {\n const node = graph.nodes.get(nodeId)\n const owner = node && owningInstance(graph, node)\n if (!node?.parentId || !owner) return false\n // Slot content is the instance's own already, and a generated frame's layers are fixed.\n const scope = slotScope(graph, node.parentId)\n if (scope.kind !== 'locked' || scope.owner.type !== 'INSTANCE') return false\n return (\n replacedLayerIn(owner, node.id) !== undefined ||\n copiedComponentLayerId(owner.instanceOverrides, owner.id, node) !== undefined\n )\n}\n\n/**\n * Put `replacementId` in place of `targetId`, a layer an instance copies from its component, as\n * an override of the nearest instance above it, as pen.dev replaces a layer inside an instance.\n * The replacement takes the target's place among its siblings and its position, the target\n * goes, and syncs keep the replacement in place of the component layer the target copied. A\n * replaced layer can be replaced again. Returns false and changes nothing when the target is no\n * such layer, or the replacement cannot go there.\n */\nexport function replaceInstanceLayer(\n graph: SceneGraph,\n targetId: string,\n replacementId: string\n): boolean {\n const target = graph.nodes.get(targetId)\n const replacement = graph.nodes.get(replacementId)\n const parentId = target?.parentId\n if (!target || !replacement || !parentId || targetId === replacementId) return false\n const owner = owningInstance(graph, target)\n if (!owner || graph.isDescendant(parentId, replacementId)) return false\n if (createsComponentCycle(graph, replacementId, parentId)) return false\n const layerId =\n replacedLayerIn(owner, target.id) ??\n copiedComponentLayerId(owner.instanceOverrides, owner.id, target)\n if (!layerId) return false\n\n // The replacement copies no layer of the component, so its own layers lose such links; an\n // instance among them keeps its own component and layers.\n const unlink = (id: string) => {\n const node = graph.nodes.get(id)\n if (!node) return\n if (node.type !== 'INSTANCE' && node.componentId) graph.updateNode(id, { componentId: null })\n if (node.type !== 'INSTANCE') node.childIds.forEach(unlink)\n }\n unlink(replacementId)\n\n const index = graph.nodes.get(parentId)?.childIds.indexOf(target.id) ?? -1\n forgetOverridesOf(graph, target.id)\n forgetOverridesOf(graph, replacementId)\n graph.insertChildAt(replacementId, parentId, index < 0 ? Number.MAX_SAFE_INTEGER : index)\n graph.updateNode(replacementId, {\n x: target.x,\n y: target.y,\n layoutPositioning: target.layoutPositioning,\n horizontalConstraint: target.horizontalConstraint,\n verticalConstraint: target.verticalConstraint\n })\n graph.deleteNode(target.id)\n setInstanceOverride(\n ownInstanceOverrides(owner),\n owner.id,\n replacementId,\n REPLACED_LAYER_OVERRIDE,\n layerId\n )\n graph.updateNode(owner.id, { instanceOverrides: ownInstanceOverrides(owner) })\n return true\n}\n\n/**\n * Take a replaced layer out and bring back the component layer it stood in for, synced from the\n * outermost instance as a reset syncs. Returns false when the layer is not a replaced one.\n */\nexport function restoreReplacedLayer(graph: SceneGraph, nodeId: string): boolean {\n const node = graph.nodes.get(nodeId)\n const owner = node && owningInstance(graph, node)\n if (!node || !owner || replacedLayerIn(owner, nodeId) === undefined) return false\n let outermost = owner\n for (let above = owningInstance(graph, owner); above; above = owningInstance(graph, above))\n outermost = above\n forgetOverridesOf(graph, nodeId)\n graph.deleteNode(nodeId)\n syncInstance(graph, outermost.id)\n // An enclosing sync stops at a swapped instance, which brings its layers back itself.\n const above = owningInstance(graph, owner)\n if (above && getInstanceOverride(above.instanceOverrides, above.id, owner.id, 'componentId'))\n syncInstance(graph, owner.id)\n return true\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkEA,SAAgB,2BAA2B,WAA0C;CACnF,MAAM,QAA4B,CAAC;CAEnC,KAAK,MAAM,OAAO,CAAC,GAAG,qBAAqB,GAAG,8BAA8B,GAC1E,SAAS,OAAO,WAAW,GAAG;CAChC,OAAO;AACT;;;;;AAMA,S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eAAe,OAAO,KAAK,GAAG,OAAO,QAAQ,eAAe,OAAO,KAAK,GACvF,YAAY;CACd,kBAAkB,OAAO,MAAM;CAC/B,MAAM,WAAW,MAAM;CACvB,aAAa,OAAO,UAAU,EAAE;CAEhC,MAAM,QAAQ,eAAe,OAAO,KAAK;CACzC,IAAI,SAAS,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,MAAM,IAAI,aAAa,GACzF,aAAa,OAAO,MAAM,EAAE;CAC9B,OAAO;AACT"}
@@ -1,3 +1,4 @@
1
+ import { SceneNode } from "../types.js";
1
2
  //#region src/instances/overrides.d.ts
2
3
  type InstanceOverrideField = string;
3
4
  interface InstanceOverrideState {
@@ -34,6 +35,19 @@ declare const REPLACED_LAYER_OVERRIDE = "replacedLayer";
34
35
  /** Override fields whose value names another layer of the document. */
35
36
  declare function isLayerReferenceOverride(field: InstanceOverrideField): boolean;
36
37
  declare function createInstanceOverrideState(): InstanceOverrideState;
38
+ /**
39
+ * What a layer holds until it records an override of its own. Shared and frozen, so an empty state
40
+ * costs nothing per layer and a write that skipped `ownInstanceOverrides` throws where it happens
41
+ * instead of reaching every layer of every document.
42
+ */
43
+ declare const EMPTY_INSTANCE_OVERRIDES: InstanceOverrideState;
44
+ declare function isEmptyInstanceOverrideState(state: InstanceOverrideState): boolean;
45
+ /**
46
+ * The layer's own override state, giving it a fresh one when it still holds the shared empty
47
+ * state. Writers record through this and then persist it with `updateNode`, so the change reaches
48
+ * events and undo instead of only the layer.
49
+ */
50
+ declare function ownInstanceOverrides(node: SceneNode): InstanceOverrideState;
37
51
  interface SerializedOverrideValue {
38
52
  defined: boolean;
39
53
  value?: unknown;
@@ -68,5 +82,5 @@ declare function deleteInstanceOverride(state: InstanceOverrideState, instanceId
68
82
  declare function clearInstanceOverrides(state: InstanceOverrideState): void;
69
83
  declare function forEachInstanceOverride(state: InstanceOverrideState, callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void): void;
70
84
  //#endregion
71
- export { InstanceOverrideField, InstanceOverrideReferenceMapper, InstanceOverrideState, REPLACED_LAYER_OVERRIDE, SerializedInstanceOverrideState, SerializedOverrideValue, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, isLayerReferenceOverride, overriddenAssignmentId, overriddenBindingField, overriddenVariableModeCollection, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideField };
85
+ export { EMPTY_INSTANCE_OVERRIDES, InstanceOverrideField, InstanceOverrideReferenceMapper, InstanceOverrideState, REPLACED_LAYER_OVERRIDE, SerializedInstanceOverrideState, SerializedOverrideValue, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, isEmptyInstanceOverrideState, isLayerReferenceOverride, overriddenAssignmentId, overriddenBindingField, overriddenVariableModeCollection, ownInstanceOverrides, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideField };
72
86
  //# sourceMappingURL=overrides.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"overrides.d.ts","names":[],"sources":["../../src/instances/overrides.ts"],"mappings":";KAAY;UAEK;EACf,MAAM,IAAI;EACV,aAAa,YAAY,IAAI;;;;;;iBASf,qBAAqB,gBAAgB;;iBAKrC,uBAAuB,OAAO;;;;;iBAY9B,0BAA0B,uBAAuB;;iBAKjD,iCAAiC,OAAO;;;;;iBAYxC,wBAAwB,qBAAqB;;iBAK7C,uBAAuB,OAAO;;;;;;cAWjC;;iBAGG,yBAAyB,OAAO;iBAMhC,+BAA+B;UAI9B;EACf;EACA;;UAGe;EACf,MAAM,OAAO,uBAAuB;EACpC,aAAa,eAAe,OAAO,uBAAuB;;iBAiC5C,+BACd,OAAO,wBACN;iBAUa,iCAAiC,iBAAiB;iBAgBlD,2BAA2B,OAAO,wBAAwB;UAYzD;EACf,OAAO;EACP,WAAW;EACX,cAAc;EACd,YAAY;;;iBAIE,2BACd,OAAO,uBACP,YAAY,kCACX;iBAkCa,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO;;;;;iBASO,uBACd,OAAO,uBACP,oBACA;EAAQ;EAAY;;iBAMN,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO;iBAMO,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO,uBACP;iBAWc,uBACd,OAAO,uBACP,oBACA,gBACA,OAAO;iBAQO,uBAAuB,OAAO;iBAK9B,wBACd,OAAO,uBACP,WAAW,gBAAgB,OAAO,uBAAuB"}
1
+ {"version":3,"file":"overrides.d.ts","names":[],"sources":["../../src/instances/overrides.ts"],"mappings":";;KAAY;UAIK;EACf,MAAM,IAAI;EACV,aAAa,YAAY,IAAI;;;;;;iBASf,qBAAqB,gBAAgB;;iBAKrC,uBAAuB,OAAO;;;;;iBAY9B,0BAA0B,uBAAuB;;iBAKjD,iCAAiC,OAAO;;;;;iBAYxC,wBAAwB,qBAAqB;;iBAK7C,uBAAuB,OAAO;;;;;;cAWjC;;iBAGG,yBAAyB,OAAO;iBAMhC,+BAA+B;;;;;;cA8BlC,0BAA0B;iBAKvB,6BAA6B,OAAO;;;;;;iBASpC,qBAAqB,MAAM,YAAY;UAOtC;EACf;EACA;;UAGe;EACf,MAAM,OAAO,uBAAuB;EACpC,aAAa,eAAe,OAAO,uBAAuB;;iBAiC5C,+BACd,OAAO,wBACN;iBAUa,iCAAiC,iBAAiB;iBAgBlD,2BAA2B,OAAO,wBAAwB;UAYzD;EACf,OAAO;EACP,WAAW;EACX,cAAc;EACd,YAAY;;;iBAIE,2BACd,OAAO,uBACP,YAAY,kCACX;iBAkCa,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO;;;;;iBASO,uBACd,OAAO,uBACP,oBACA;EAAQ;EAAY;;iBAMN,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO;iBAMO,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO,uBACP;iBAWc,uBACd,OAAO,uBACP,oBACA,gBACA,OAAO;iBAQO,uBAAuB,OAAO;iBAK9B,wBACd,OAAO,uBACP,WAAW,gBAAgB,OAAO,uBAAuB"}
@@ -51,6 +51,42 @@ function createInstanceOverrideState() {
51
51
  descendants: /* @__PURE__ */ new Map()
52
52
  };
53
53
  }
54
+ const SHARED_STATE_WRITE = "the shared empty instance overrides are read-only; call ownInstanceOverrides(node) first";
55
+ /** A map the shared state throws from on every write, which still answers all reads. */
56
+ var SharedOverrideMap = class extends Map {
57
+ set(key, value) {
58
+ throw new Error(SHARED_STATE_WRITE);
59
+ }
60
+ delete(key) {
61
+ throw new Error(SHARED_STATE_WRITE);
62
+ }
63
+ clear() {
64
+ throw new Error(SHARED_STATE_WRITE);
65
+ }
66
+ };
67
+ /**
68
+ * What a layer holds until it records an override of its own. Shared and frozen, so an empty state
69
+ * costs nothing per layer and a write that skipped `ownInstanceOverrides` throws where it happens
70
+ * instead of reaching every layer of every document.
71
+ */
72
+ const EMPTY_INSTANCE_OVERRIDES = Object.freeze({
73
+ self: new SharedOverrideMap(),
74
+ descendants: new SharedOverrideMap()
75
+ });
76
+ function isEmptyInstanceOverrideState(state) {
77
+ return state.self.size === 0 && state.descendants.size === 0;
78
+ }
79
+ /**
80
+ * The layer's own override state, giving it a fresh one when it still holds the shared empty
81
+ * state. Writers record through this and then persist it with `updateNode`, so the change reaches
82
+ * events and undo instead of only the layer.
83
+ */
84
+ function ownInstanceOverrides(node) {
85
+ if (node.instanceOverrides !== EMPTY_INSTANCE_OVERRIDES) return node.instanceOverrides;
86
+ const owned = createInstanceOverrideState();
87
+ node.instanceOverrides = owned;
88
+ return owned;
89
+ }
54
90
  function serializeOverrideValue(value) {
55
91
  return value === void 0 ? { defined: false } : {
56
92
  defined: true,
@@ -185,6 +221,6 @@ function forEachInstanceOverride(state, callback) {
185
221
  for (const [nodeId, fields] of state.descendants) for (const [field, value] of fields) callback(nodeId, field, value);
186
222
  }
187
223
  //#endregion
188
- export { REPLACED_LAYER_OVERRIDE, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, isLayerReferenceOverride, overriddenAssignmentId, overriddenBindingField, overriddenVariableModeCollection, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideField };
224
+ export { EMPTY_INSTANCE_OVERRIDES, REPLACED_LAYER_OVERRIDE, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, isEmptyInstanceOverrideState, isLayerReferenceOverride, overriddenAssignmentId, overriddenBindingField, overriddenVariableModeCollection, ownInstanceOverrides, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideField };
189
225
 
190
226
  //# sourceMappingURL=overrides.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"overrides.js","names":[],"sources":["../../src/instances/overrides.ts"],"sourcesContent":["export type InstanceOverrideField = string\n\nexport interface InstanceOverrideState {\n self: Map<InstanceOverrideField, unknown>\n descendants: Map<string, Map<InstanceOverrideField, unknown>>\n}\n\nconst BINDING_OVERRIDE_PREFIX = 'boundVariables/'\n\n/**\n * The override field that claims a layer's binding of `field`, which keeps that binding, or its\n * absence, through a sync. `boundVariables` alone claims every binding of the layer.\n */\nexport function bindingOverrideField(field: string): InstanceOverrideField {\n return `${BINDING_OVERRIDE_PREFIX}${field}`\n}\n\n/** The binding field an override field claims, or null for an override of anything else. */\nexport function overriddenBindingField(field: InstanceOverrideField): string | null {\n return field.startsWith(BINDING_OVERRIDE_PREFIX)\n ? field.slice(BINDING_OVERRIDE_PREFIX.length)\n : null\n}\n\nconst VARIABLE_MODE_OVERRIDE_PREFIX = 'variableModes/'\n\n/**\n * The override field that keeps a layer's mode for one collection through a sync, so the\n * component's modes for other collections still reach it. `variableModes` alone keeps them all.\n */\nexport function variableModeOverrideField(collectionId: string): InstanceOverrideField {\n return `${VARIABLE_MODE_OVERRIDE_PREFIX}${collectionId}`\n}\n\n/** The collection a mode override field claims, or null for an override of anything else. */\nexport function overriddenVariableModeCollection(field: InstanceOverrideField): string | null {\n return field.startsWith(VARIABLE_MODE_OVERRIDE_PREFIX)\n ? field.slice(VARIABLE_MODE_OVERRIDE_PREFIX.length)\n : null\n}\n\nconst ASSIGNMENT_OVERRIDE_PREFIX = 'componentPropertyAssignments/'\n\n/**\n * The override field that claims a nested instance's assignment of `propertyId`, which keeps\n * that assignment through a sync of the instance that makes it.\n */\nexport function assignmentOverrideField(propertyId: string): InstanceOverrideField {\n return `${ASSIGNMENT_OVERRIDE_PREFIX}${propertyId}`\n}\n\n/** The property an assignment override field claims, or null for an override of anything else. */\nexport function overriddenAssignmentId(field: InstanceOverrideField): string | null {\n return field.startsWith(ASSIGNMENT_OVERRIDE_PREFIX)\n ? field.slice(ASSIGNMENT_OVERRIDE_PREFIX.length)\n : null\n}\n\n/**\n * The override field that marks a layer of an instance as one put in place of a component's\n * layer, recorded by the nearest instance above it. Its value is the layer it replaces, which\n * sync matches it to instead of copying that layer in again.\n */\nexport const REPLACED_LAYER_OVERRIDE = 'replacedLayer'\n\n/** Override fields whose value names another layer of the document. */\nexport function isLayerReferenceOverride(field: InstanceOverrideField): boolean {\n return (\n field === 'componentId' || field === 'sourceComponentId' || field === REPLACED_LAYER_OVERRIDE\n )\n}\n\nexport function createInstanceOverrideState(): InstanceOverrideState {\n return { self: new Map(), descendants: new Map() }\n}\n\nexport interface SerializedOverrideValue {\n defined: boolean\n value?: unknown\n}\n\nexport interface SerializedInstanceOverrideState {\n self: Array<[InstanceOverrideField, SerializedOverrideValue]>\n descendants: Array<[string, Array<[InstanceOverrideField, SerializedOverrideValue]>]>\n}\n\nfunction serializeOverrideValue(value: unknown): SerializedOverrideValue {\n return value === undefined ? { defined: false } : { defined: true, value }\n}\n\nfunction deserializeOverrideValue(value: unknown): { valid: boolean; value: unknown } {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return { valid: false, value: undefined }\n }\n if (!('defined' in value) || typeof value.defined !== 'boolean') {\n return { valid: false, value: undefined }\n }\n if (value.defined) {\n return 'value' in value\n ? { valid: true, value: value['value'] }\n : { valid: false, value: undefined }\n }\n return { valid: true, value: undefined }\n}\n\nfunction deserializeEntries(value: unknown): Map<InstanceOverrideField, unknown> {\n const result = new Map<InstanceOverrideField, unknown>()\n if (!Array.isArray(value)) return result\n for (const entry of value) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue\n const decoded = deserializeOverrideValue(entry[1])\n if (decoded.valid) result.set(entry[0], decoded.value)\n }\n return result\n}\n\nexport function serializeInstanceOverrideState(\n state: InstanceOverrideState\n): SerializedInstanceOverrideState {\n return {\n self: [...state.self].map(([field, value]) => [field, serializeOverrideValue(value)]),\n descendants: [...state.descendants].map(([nodeId, fields]) => [\n nodeId,\n [...fields].map(([field, value]) => [field, serializeOverrideValue(value)])\n ])\n }\n}\n\nexport function deserializeInstanceOverrideState(state: unknown): InstanceOverrideState {\n if (!state || typeof state !== 'object' || Array.isArray(state)) {\n return createInstanceOverrideState()\n }\n const self =\n 'self' in state ? deserializeEntries(state.self) : new Map<InstanceOverrideField, unknown>()\n const descendants = new Map<string, Map<InstanceOverrideField, unknown>>()\n if ('descendants' in state && Array.isArray(state.descendants)) {\n for (const entry of state.descendants) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue\n descendants.set(entry[0], deserializeEntries(entry[1]))\n }\n }\n return { self, descendants }\n}\n\nexport function cloneInstanceOverrideState(state: InstanceOverrideState): InstanceOverrideState {\n return {\n self: new Map([...state.self].map(([field, value]) => [field, structuredClone(value)])),\n descendants: new Map(\n [...state.descendants].map(([id, fields]) => [\n id,\n new Map([...fields].map(([field, value]) => [field, structuredClone(value)]))\n ])\n )\n }\n}\n\nexport interface InstanceOverrideReferenceMapper {\n node: (id: string) => string\n variable: (id: string) => string\n collection?: (id: string) => string | undefined\n property?: (id: string) => string | undefined\n}\n\n/** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */\nexport function remapInstanceOverrideState(\n state: InstanceOverrideState,\n references: InstanceOverrideReferenceMapper\n): InstanceOverrideState {\n const remapValue = (field: string, value: unknown): unknown => {\n if (typeof value !== 'string') return structuredClone(value)\n if (isLayerReferenceOverride(field)) return references.node(value)\n if (overriddenBindingField(field) !== null) return references.variable(value)\n return value\n }\n const remapField = (field: string): string | undefined => {\n const property = overriddenAssignmentId(field)\n if (property !== null && references.property) {\n const mapped = references.property(property)\n return mapped === undefined ? undefined : assignmentOverrideField(mapped)\n }\n const collection = overriddenVariableModeCollection(field)\n if (collection === null || !references.collection) return field\n const mapped = references.collection(collection)\n return mapped === undefined ? undefined : variableModeOverrideField(mapped)\n }\n const fields = (entries: ReadonlyMap<string, unknown>) =>\n new Map(\n [...entries].flatMap(([field, value]) => {\n const mapped = remapField(field)\n return mapped === undefined ? [] : [[mapped, remapValue(field, value)] as const]\n })\n )\n const descendants = new Map<string, Map<string, unknown>>()\n for (const [id, entries] of state.descendants) {\n const mapped = references.node(id)\n if (descendants.has(mapped)) throw new Error(`Duplicate remapped override target ${mapped}`)\n descendants.set(mapped, fields(entries))\n }\n return { self: fields(state.self), descendants }\n}\n\nexport function getInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): unknown {\n return nodeId === instanceId ? state.self.get(field) : state.descendants.get(nodeId)?.get(field)\n}\n\n/**\n * The component layer a layer of an instance copies: the one its instance recorded for it, as\n * a swapped nested instance keeps, or else the one it was cloned from.\n */\nexport function copiedComponentLayerId(\n state: InstanceOverrideState,\n instanceId: string,\n node: { id: string; componentId: string | null }\n): string | undefined {\n const recorded = getInstanceOverride(state, instanceId, node.id, 'sourceComponentId')\n return typeof recorded === 'string' ? recorded : (node.componentId ?? undefined)\n}\n\nexport function hasInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): boolean {\n const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)\n return fields?.has(field) ?? false\n}\n\nexport function setInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField,\n value: unknown = true\n): void {\n if (nodeId === instanceId) {\n state.self.set(field, value)\n return\n }\n const fields = state.descendants.get(nodeId) ?? new Map<string, unknown>()\n fields.set(field, value)\n state.descendants.set(nodeId, fields)\n}\n\nexport function deleteInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): boolean {\n const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)\n if (!fields?.delete(field)) return false\n if (nodeId !== instanceId && fields.size === 0) state.descendants.delete(nodeId)\n return true\n}\n\nexport function clearInstanceOverrides(state: InstanceOverrideState): void {\n state.self.clear()\n state.descendants.clear()\n}\n\nexport function forEachInstanceOverride(\n state: InstanceOverrideState,\n callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void\n): void {\n for (const [field, value] of state.self) callback('', field, value)\n for (const [nodeId, fields] of state.descendants) {\n for (const [field, value] of fields) callback(nodeId, field, value)\n }\n}\n"],"mappings":";AAOA,MAAM,0BAA0B;;;;;AAMhC,SAAgB,qBAAqB,OAAsC;CACzE,OAAO,GAAG,0BAA0B;AACtC;;AAGA,SAAgB,uBAAuB,OAA6C;CAClF,OAAO,MAAM,WAAW,uBAAuB,IAC3C,MAAM,MAAM,EAA8B,IAC1C;AACN;AAEA,MAAM,gCAAgC;;;;;AAMtC,SAAgB,0BAA0B,cAA6C;CACrF,OAAO,GAAG,gCAAgC;AAC5C;;AAGA,SAAgB,iCAAiC,OAA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AO,UAAU,QAAQ,SAAS,QAAQ,OAAO,KAAK;AAEtE"}
1
+ {"version":3,"file":"overrides.js","names":[],"sources":["../../src/instances/overrides.ts"],"sourcesContent":["export type InstanceOverrideField = string\n\nimport type { SceneNode } from '../types'\n\nexport interface InstanceOverrideState {\n self: Map<InstanceOverrideField, unknown>\n descendants: Map<string, Map<InstanceOverrideField, unknown>>\n}\n\nconst BINDING_OVERRIDE_PREFIX = 'boundVariables/'\n\n/**\n * The override field that claims a layer's binding of `field`, which keeps that binding, or its\n * absence, through a sync. `boundVariables` alone claims every binding of the layer.\n */\nexport function bindingOverrideField(field: string): InstanceOverrideField {\n return `${BINDING_OVERRIDE_PREFIX}${field}`\n}\n\n/** The binding field an override field claims, or null for an override of anything else. */\nexport function overriddenBindingField(field: InstanceOverrideField): string | null {\n return field.startsWith(BINDING_OVERRIDE_PREFIX)\n ? field.slice(BINDING_OVERRIDE_PREFIX.length)\n : null\n}\n\nconst VARIABLE_MODE_OVERRIDE_PREFIX = 'variableModes/'\n\n/**\n * The override field that keeps a layer's mode for one collection through a sync, so the\n * component's modes for other collections still reach it. `variableModes` alone keeps them all.\n */\nexport function variableModeOverrideField(collectionId: string): InstanceOverrideField {\n return `${VARIABLE_MODE_OVERRIDE_PREFIX}${collectionId}`\n}\n\n/** The collection a mode override field claims, or null for an override of anything else. */\nexport function overriddenVariableModeCollection(field: InstanceOverrideField): string | null {\n return field.startsWith(VARIABLE_MODE_OVERRIDE_PREFIX)\n ? field.slice(VARIABLE_MODE_OVERRIDE_PREFIX.length)\n : null\n}\n\nconst ASSIGNMENT_OVERRIDE_PREFIX = 'componentPropertyAssignments/'\n\n/**\n * The override field that claims a nested instance's assignment of `propertyId`, which keeps\n * that assignment through a sync of the instance that makes it.\n */\nexport function assignmentOverrideField(propertyId: string): InstanceOverrideField {\n return `${ASSIGNMENT_OVERRIDE_PREFIX}${propertyId}`\n}\n\n/** The property an assignment override field claims, or null for an override of anything else. */\nexport function overriddenAssignmentId(field: InstanceOverrideField): string | null {\n return field.startsWith(ASSIGNMENT_OVERRIDE_PREFIX)\n ? field.slice(ASSIGNMENT_OVERRIDE_PREFIX.length)\n : null\n}\n\n/**\n * The override field that marks a layer of an instance as one put in place of a component's\n * layer, recorded by the nearest instance above it. Its value is the layer it replaces, which\n * sync matches it to instead of copying that layer in again.\n */\nexport const REPLACED_LAYER_OVERRIDE = 'replacedLayer'\n\n/** Override fields whose value names another layer of the document. */\nexport function isLayerReferenceOverride(field: InstanceOverrideField): boolean {\n return (\n field === 'componentId' || field === 'sourceComponentId' || field === REPLACED_LAYER_OVERRIDE\n )\n}\n\nexport function createInstanceOverrideState(): InstanceOverrideState {\n return { self: new Map(), descendants: new Map() }\n}\n\nconst SHARED_STATE_WRITE =\n 'the shared empty instance overrides are read-only; call ownInstanceOverrides(node) first'\n\n/** A map the shared state throws from on every write, which still answers all reads. */\nclass SharedOverrideMap<K, V> extends Map<K, V> {\n override set(key: K, value: V): this {\n void key\n void value\n throw new Error(SHARED_STATE_WRITE)\n }\n\n override delete(key: K): boolean {\n void key\n throw new Error(SHARED_STATE_WRITE)\n }\n\n override clear(): void {\n throw new Error(SHARED_STATE_WRITE)\n }\n}\n\n/**\n * What a layer holds until it records an override of its own. Shared and frozen, so an empty state\n * costs nothing per layer and a write that skipped `ownInstanceOverrides` throws where it happens\n * instead of reaching every layer of every document.\n */\nexport const EMPTY_INSTANCE_OVERRIDES: InstanceOverrideState = Object.freeze({\n self: new SharedOverrideMap<InstanceOverrideField, unknown>(),\n descendants: new SharedOverrideMap<string, Map<InstanceOverrideField, unknown>>()\n})\n\nexport function isEmptyInstanceOverrideState(state: InstanceOverrideState): boolean {\n return state.self.size === 0 && state.descendants.size === 0\n}\n\n/**\n * The layer's own override state, giving it a fresh one when it still holds the shared empty\n * state. Writers record through this and then persist it with `updateNode`, so the change reaches\n * events and undo instead of only the layer.\n */\nexport function ownInstanceOverrides(node: SceneNode): InstanceOverrideState {\n if (node.instanceOverrides !== EMPTY_INSTANCE_OVERRIDES) return node.instanceOverrides\n const owned = createInstanceOverrideState()\n node.instanceOverrides = owned\n return owned\n}\n\nexport interface SerializedOverrideValue {\n defined: boolean\n value?: unknown\n}\n\nexport interface SerializedInstanceOverrideState {\n self: Array<[InstanceOverrideField, SerializedOverrideValue]>\n descendants: Array<[string, Array<[InstanceOverrideField, SerializedOverrideValue]>]>\n}\n\nfunction serializeOverrideValue(value: unknown): SerializedOverrideValue {\n return value === undefined ? { defined: false } : { defined: true, value }\n}\n\nfunction deserializeOverrideValue(value: unknown): { valid: boolean; value: unknown } {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return { valid: false, value: undefined }\n }\n if (!('defined' in value) || typeof value.defined !== 'boolean') {\n return { valid: false, value: undefined }\n }\n if (value.defined) {\n return 'value' in value\n ? { valid: true, value: value['value'] }\n : { valid: false, value: undefined }\n }\n return { valid: true, value: undefined }\n}\n\nfunction deserializeEntries(value: unknown): Map<InstanceOverrideField, unknown> {\n const result = new Map<InstanceOverrideField, unknown>()\n if (!Array.isArray(value)) return result\n for (const entry of value) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue\n const decoded = deserializeOverrideValue(entry[1])\n if (decoded.valid) result.set(entry[0], decoded.value)\n }\n return result\n}\n\nexport function serializeInstanceOverrideState(\n state: InstanceOverrideState\n): SerializedInstanceOverrideState {\n return {\n self: [...state.self].map(([field, value]) => [field, serializeOverrideValue(value)]),\n descendants: [...state.descendants].map(([nodeId, fields]) => [\n nodeId,\n [...fields].map(([field, value]) => [field, serializeOverrideValue(value)])\n ])\n }\n}\n\nexport function deserializeInstanceOverrideState(state: unknown): InstanceOverrideState {\n if (!state || typeof state !== 'object' || Array.isArray(state)) {\n return createInstanceOverrideState()\n }\n const self =\n 'self' in state ? deserializeEntries(state.self) : new Map<InstanceOverrideField, unknown>()\n const descendants = new Map<string, Map<InstanceOverrideField, unknown>>()\n if ('descendants' in state && Array.isArray(state.descendants)) {\n for (const entry of state.descendants) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue\n descendants.set(entry[0], deserializeEntries(entry[1]))\n }\n }\n return { self, descendants }\n}\n\nexport function cloneInstanceOverrideState(state: InstanceOverrideState): InstanceOverrideState {\n return {\n self: new Map([...state.self].map(([field, value]) => [field, structuredClone(value)])),\n descendants: new Map(\n [...state.descendants].map(([id, fields]) => [\n id,\n new Map([...fields].map(([field, value]) => [field, structuredClone(value)]))\n ])\n )\n }\n}\n\nexport interface InstanceOverrideReferenceMapper {\n node: (id: string) => string\n variable: (id: string) => string\n collection?: (id: string) => string | undefined\n property?: (id: string) => string | undefined\n}\n\n/** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */\nexport function remapInstanceOverrideState(\n state: InstanceOverrideState,\n references: InstanceOverrideReferenceMapper\n): InstanceOverrideState {\n const remapValue = (field: string, value: unknown): unknown => {\n if (typeof value !== 'string') return structuredClone(value)\n if (isLayerReferenceOverride(field)) return references.node(value)\n if (overriddenBindingField(field) !== null) return references.variable(value)\n return value\n }\n const remapField = (field: string): string | undefined => {\n const property = overriddenAssignmentId(field)\n if (property !== null && references.property) {\n const mapped = references.property(property)\n return mapped === undefined ? undefined : assignmentOverrideField(mapped)\n }\n const collection = overriddenVariableModeCollection(field)\n if (collection === null || !references.collection) return field\n const mapped = references.collection(collection)\n return mapped === undefined ? undefined : variableModeOverrideField(mapped)\n }\n const fields = (entries: ReadonlyMap<string, unknown>) =>\n new Map(\n [...entries].flatMap(([field, value]) => {\n const mapped = remapField(field)\n return mapped === undefined ? [] : [[mapped, remapValue(field, value)] as const]\n })\n )\n const descendants = new Map<string, Map<string, unknown>>()\n for (const [id, entries] of state.descendants) {\n const mapped = references.node(id)\n if (descendants.has(mapped)) throw new Error(`Duplicate remapped override target ${mapped}`)\n descendants.set(mapped, fields(entries))\n }\n return { self: fields(state.self), descendants }\n}\n\nexport function getInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): unknown {\n return nodeId === instanceId ? state.self.get(field) : state.descendants.get(nodeId)?.get(field)\n}\n\n/**\n * The component layer a layer of an instance copies: the one its instance recorded for it, as\n * a swapped nested instance keeps, or else the one it was cloned from.\n */\nexport function copiedComponentLayerId(\n state: InstanceOverrideState,\n instanceId: string,\n node: { id: string; componentId: string | null }\n): string | undefined {\n const recorded = getInstanceOverride(state, instanceId, node.id, 'sourceComponentId')\n return typeof recorded === 'string' ? recorded : (node.componentId ?? undefined)\n}\n\nexport function hasInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): boolean {\n const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)\n return fields?.has(field) ?? false\n}\n\nexport function setInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField,\n value: unknown = true\n): void {\n if (nodeId === instanceId) {\n state.self.set(field, value)\n return\n }\n const fields = state.descendants.get(nodeId) ?? new Map<string, unknown>()\n fields.set(field, value)\n state.descendants.set(nodeId, fields)\n}\n\nexport function deleteInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): boolean {\n const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)\n if (!fields?.delete(field)) return false\n if (nodeId !== instanceId && fields.size === 0) state.descendants.delete(nodeId)\n return true\n}\n\nexport function clearInstanceOverrides(state: InstanceOverrideState): void {\n state.self.clear()\n state.descendants.clear()\n}\n\nexport function forEachInstanceOverride(\n state: InstanceOverrideState,\n callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void\n): void {\n for (const [field, value] of state.self) callback('', field, value)\n for (const [nodeId, fields] of state.descendants) {\n for (const [field, value] of fields) callback(nodeId, field, value)\n }\n}\n"],"mappings":";AASA,MAAM,0BAA0B;;;;;AAMhC,SAAgB,qBAAqB,OAAsC;CACzE,OAAO,GAAG,0BAA0B;AACtC;;AAGA,SAAgB,uBAAuB,OAA6C;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,KAAK,KAAK;AAC/B;AAEA,SAAgB,oBACd,OACA,YACA,QACA,OACA,QAAiB,MACX;CACN,IAAI,WAAW,YAAY;EACzB,MAAM,KAAK,IAAI,OAAO,KAAK;EAC3B;CACF;CACA,MAAM,SAAS,MAAM,YAAY,IAAI,MAAM,qBAAK,IAAI,IAAqB;CACzE,OAAO,IAAI,OAAO,KAAK;CACvB,MAAM,YAAY,IAAI,QAAQ,MAAM;AACtC;AAEA,SAAgB,uBACd,OACA,YACA,QACA,OACS;CACT,MAAM,SAAS,WAAW,aAAa,MAAM,OAAO,MAAM,YAAY,IAAI,MAAM;CAChF,IAAI,CAAC,QAAQ,OAAO,KAAK,GAAG,OAAO;CACnC,IAAI,WAAW,cAAc,OAAO,SAAS,GAAG,MAAM,YAAY,OAAO,MAAM;CAC/E,OAAO;AACT;AAEA,SAAgB,uBAAuB,OAAoC;CACzE,MAAM,KAAK,MAAM;CACjB,MAAM,YAAY,MAAM;AAC1B;AAEA,SAAgB,wBACd,OACA,UACM;CACN,KAAK,MAAM,CAAC,OAAO,UAAU,MAAM,MAAM,SAAS,IAAI,OAAO,KAAK;CAClE,KAAK,MAAM,CAAC,QAAQ,WAAW,MAAM,aACnC,KAAK,MAAM,CAAC,OAAO,UAAU,QAAQ,SAAS,QAAQ,OAAO,KAAK;AAEtE"}
@@ -1,4 +1,4 @@
1
- import { isLayerReferenceOverride, overriddenBindingField, overriddenVariableModeCollection, setInstanceOverride } from "./overrides.js";
1
+ import { isLayerReferenceOverride, overriddenBindingField, overriddenVariableModeCollection, ownInstanceOverrides, setInstanceOverride } from "./overrides.js";
2
2
  import { INSTANCE_OVERRIDE_FIELDS } from "./fields.js";
3
3
  import { copyProp } from "./sync.js";
4
4
  //#region src/instances/swap-overrides.ts
@@ -84,9 +84,9 @@ function restoreInstanceOverrides(graph, instance, captured) {
84
84
  for (const { child, layer } of paths) {
85
85
  const changes = changesFor(layer);
86
86
  if (Object.keys(changes).length) graph.updateNode(child.id, changes);
87
- for (const field of layer.fields) setInstanceOverride(instance.instanceOverrides, instance.id, child.id, field);
87
+ for (const field of layer.fields) setInstanceOverride(ownInstanceOverrides(instance), instance.id, child.id, field);
88
88
  }
89
- graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides });
89
+ graph.updateNode(instance.id, { instanceOverrides: ownInstanceOverrides(instance) });
90
90
  }
91
91
  //#endregion
92
92
  export { captureInstanceOverrides, restoreInstanceOverrides };
@@ -1 +1 @@
1
- {"version":3,"file":"swap-overrides.js","names":[],"sources":["../../src/instances/swap-overrides.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport type { SceneNode } from '../types'\nimport { INSTANCE_OVERRIDE_FIELDS } from './fields'\nimport {\n isLayerReferenceOverride,\n overriddenBindingField,\n overriddenVariableModeCollection,\n setInstanceOverride\n} from './overrides'\nimport { copyProp } from './sync'\n\n/** What a swap keeps for one layer, so the layer that replaces it can take the values over. */\ninterface CapturedLayer {\n snapshot: SceneNode\n fields: string[]\n}\n\n/** Overrides kept across a swap, keyed by each layer's name path inside the instance. */\nexport type CapturedInstanceOverrides = Map<string, CapturedLayer>\n\nconst OVERRIDE_FIELD_KEYS = new Set<string>(INSTANCE_OVERRIDE_FIELDS)\n\nfunction isInstanceOverrideField(field: string): field is keyof SceneNode {\n return OVERRIDE_FIELD_KEYS.has(field)\n}\n\n/**\n * A layer's place inside its instance: the names from the instance down, with the position among\n * siblings of the same name appended, so two layers called the same stay apart.\n */\nfunction childPath(parentPath: string, name: string, index: number): string {\n return `${parentPath}/${name}#${index}`\n}\n\nfunction forEachChildPath(\n graph: SceneGraph,\n parentId: string,\n parentPath: string,\n visit: (child: SceneNode, path: string) => void\n): void {\n const seen = new Map<string, number>()\n for (const child of graph.getChildren(parentId)) {\n const index = seen.get(child.name) ?? 0\n seen.set(child.name, index + 1)\n const path = childPath(parentPath, child.name, index)\n visit(child, path)\n forEachChildPath(graph, child.id, path, visit)\n }\n}\n\n/**\n * Every override an instance's layers record, keyed by path, so a swap of the component can give\n * them back to the layers of the variant that replace them, as Figma keeps overrides where the\n * two variants share a layer.\n */\nexport function captureInstanceOverrides(\n graph: SceneGraph,\n instance: SceneNode\n): CapturedInstanceOverrides {\n const captured: CapturedInstanceOverrides = new Map()\n forEachChildPath(graph, instance.id, '', (child, path) => {\n const fields = instance.instanceOverrides.descendants.get(child.id)\n if (!fields?.size) return\n const kept = [...fields.keys()].filter(\n (field) => isInstanceOverrideField(field) || !isLayerReferenceOverride(field)\n )\n if (kept.length) captured.set(path, { snapshot: structuredClone(child), fields: kept })\n })\n return captured\n}\n\nfunction changesFor(layer: CapturedLayer): Partial<SceneNode> {\n const changes: Partial<SceneNode> = {}\n const bindings: Record<string, string> = {}\n const modes: Record<string, string> = {}\n let bindingsTouched = false\n let modesTouched = false\n for (const field of layer.fields) {\n const binding = overriddenBindingField(field)\n if (binding) {\n bindingsTouched = true\n if (binding in layer.snapshot.boundVariables)\n bindings[binding] = layer.snapshot.boundVariables[binding]\n continue\n }\n const collection = overriddenVariableModeCollection(field)\n if (collection) {\n modesTouched = true\n if (collection in layer.snapshot.variableModes)\n modes[collection] = layer.snapshot.variableModes[collection]\n continue\n }\n if (isInstanceOverrideField(field)) copyProp(changes, layer.snapshot, field)\n }\n if (bindingsTouched) changes.boundVariables = bindings\n if (modesTouched) changes.variableModes = modes\n return changes\n}\n\n/**\n * Gives the captured overrides back to the layers of the instance's new component, matching each\n * layer by path, and records them again for the layers that take the old ones' places.\n */\nexport function restoreInstanceOverrides(\n graph: SceneGraph,\n instance: SceneNode,\n captured: CapturedInstanceOverrides\n): void {\n if (!captured.size) return\n const paths: Array<{ child: SceneNode; layer: CapturedLayer }> = []\n forEachChildPath(graph, instance.id, '', (child, path) => {\n const layer = captured.get(path)\n if (layer) paths.push({ child, layer })\n })\n if (!paths.length) return\n for (const { child, layer } of paths) {\n const changes = changesFor(layer)\n if (Object.keys(changes).length) graph.updateNode(child.id, changes)\n for (const field of layer.fields)\n setInstanceOverride(instance.instanceOverrides, instance.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AAS,MAAM,QAAQ;EAChC,MAAM,UAAU,uBAAuB,KAAK;EAC5C,IAAI,SAAS;GACX,kBAAkB;GAClB,IAAI,WAAW,MAAM,SAAS,gBAC5B,SAAS,WAAW,MAAM,SAAS,eAAe;GACpD;EACF;EACA,MAAM,aAAa,iCAAiC,KAAK;EACzD,IAAI,YAAY;GACd,eAAe;GACf,IAAI,cAAc,MAAM,SAAS,eAC/B,MAAM,cAAc,MAAM,SAAS,cAAc;GACnD;EACF;EACA,IAAI,wBAAwB,KAAK,GAAG,SAAS,SAAS,MAAM,UAAU,KAAK;CAC7E;CACA,IAAI,iBAAiB,QAAQ,iBAAiB;CAC9C,IAAI,cAAc,QAAQ,gBAAgB;CAC1C,OAAO;AACT;;;;;AAMA,SAAgB,yBACd,OACA,UACA,UACM;CACN,IAAI,CAAC,SAAS,MAAM;CACpB,MAAM,QAA2D,CAAC;CAClE,iBAAiB,OAAO,SAAS,IAAI,KAAK,OAAO,SAAS;EACxD,MAAM,QAAQ,SAAS,IAAI,IAAI;EAC/B,IAAI,OAAO,MAAM,KAAK;GAAE;GAAO;EAAM,CAAC;CACxC,CAAC;CACD,IAAI,CAAC,MAAM,QAAQ;CACnB,KAAK,MAAM,EAAE,OAAO,WAAW,OAAO;EACpC,MAAM,UAAU,WAAW,KAAK;EAChC,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,QAAQ,MAAM,WAAW,MAAM,IAAI,OAAO;EACnE,KAAK,MAAM,SAAS,MAAM,QACxB,oBAAoB,SAAS,mBAAmB,SAAS,IAAI,MAAM,IAAI,KAAK;CAChF;CACA,MAAM,WAAW,SAAS,IAAI,EAAE,mBAAmB,SAAS,kBAAkB,CAAC;AACjF"}
1
+ {"version":3,"file":"swap-overrides.js","names":[],"sources":["../../src/instances/swap-overrides.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport type { SceneNode } from '../types'\nimport { INSTANCE_OVERRIDE_FIELDS } from './fields'\nimport {\n isLayerReferenceOverride,\n overriddenBindingField,\n overriddenVariableModeCollection,\n ownInstanceOverrides,\n setInstanceOverride\n} from './overrides'\nimport { copyProp } from './sync'\n\n/** What a swap keeps for one layer, so the layer that replaces it can take the values over. */\ninterface CapturedLayer {\n snapshot: SceneNode\n fields: string[]\n}\n\n/** Overrides kept across a swap, keyed by each layer's name path inside the instance. */\nexport type CapturedInstanceOverrides = Map<string, CapturedLayer>\n\nconst OVERRIDE_FIELD_KEYS = new Set<string>(INSTANCE_OVERRIDE_FIELDS)\n\nfunction isInstanceOverrideField(field: string): field is keyof SceneNode {\n return OVERRIDE_FIELD_KEYS.has(field)\n}\n\n/**\n * A layer's place inside its instance: the names from the instance down, with the position among\n * siblings of the same name appended, so two layers called the same stay apart.\n */\nfunction childPath(parentPath: string, name: string, index: number): string {\n return `${parentPath}/${name}#${index}`\n}\n\nfunction forEachChildPath(\n graph: SceneGraph,\n parentId: string,\n parentPath: string,\n visit: (child: SceneNode, path: string) => void\n): void {\n const seen = new Map<string, number>()\n for (const child of graph.getChildren(parentId)) {\n const index = seen.get(child.name) ?? 0\n seen.set(child.name, index + 1)\n const path = childPath(parentPath, child.name, index)\n visit(child, path)\n forEachChildPath(graph, child.id, path, visit)\n }\n}\n\n/**\n * Every override an instance's layers record, keyed by path, so a swap of the component can give\n * them back to the layers of the variant that replace them, as Figma keeps overrides where the\n * two variants share a layer.\n */\nexport function captureInstanceOverrides(\n graph: SceneGraph,\n instance: SceneNode\n): CapturedInstanceOverrides {\n const captured: CapturedInstanceOverrides = new Map()\n forEachChildPath(graph, instance.id, '', (child, path) => {\n const fields = instance.instanceOverrides.descendants.get(child.id)\n if (!fields?.size) return\n const kept = [...fields.keys()].filter(\n (field) => isInstanceOverrideField(field) || !isLayerReferenceOverride(field)\n )\n if (kept.length) captured.set(path, { snapshot: structuredClone(child), fields: kept })\n })\n return captured\n}\n\nfunction changesFor(layer: CapturedLayer): Partial<SceneNode> {\n const changes: Partial<SceneNode> = {}\n const bindings: Record<string, string> = {}\n const modes: Record<string, string> = {}\n let bindingsTouched = false\n let modesTouched = false\n for (const field of layer.fields) {\n const binding = overriddenBindingField(field)\n if (binding) {\n bindingsTouched = true\n if (binding in layer.snapshot.boundVariables)\n bindings[binding] = layer.snapshot.boundVariables[binding]\n continue\n }\n const collection = overriddenVariableModeCollection(field)\n if (collection) {\n modesTouched = true\n if (collection in layer.snapshot.variableModes)\n modes[collection] = layer.snapshot.variableModes[collection]\n continue\n }\n if (isInstanceOverrideField(field)) copyProp(changes, layer.snapshot, field)\n }\n if (bindingsTouched) changes.boundVariables = bindings\n if (modesTouched) changes.variableModes = modes\n return changes\n}\n\n/**\n * Gives the captured overrides back to the layers of the instance's new component, matching each\n * layer by path, and records them again for the layers that take the old ones' places.\n */\nexport function restoreInstanceOverrides(\n graph: SceneGraph,\n instance: SceneNode,\n captured: CapturedInstanceOverrides\n): void {\n if (!captured.size) return\n const paths: Array<{ child: SceneNode; layer: CapturedLayer }> = []\n forEachChildPath(graph, instance.id, '', (child, path) => {\n const layer = captured.get(path)\n if (layer) paths.push({ child, layer })\n })\n if (!paths.length) return\n for (const { child, layer } of paths) {\n const changes = changesFor(layer)\n if (Object.keys(changes).length) graph.updateNode(child.id, changes)\n for (const field of layer.fields)\n setInstanceOverride(ownInstanceOverrides(instance), instance.id, child.id, field)\n }\n graph.updateNode(instance.id, { instanceOverrides: ownInstanceOverrides(instance) })\n}\n"],"mappings":";;;;AAqBA,MAAM,sBAAsB,IAAI,IAAY,wBAAwB;AAEpE,SAAS,wBAAwB,OAAyC;CACxE,OAAO,oBAAoB,IAAI,KAAK;AACtC;;;;;AAMA,SAAS,UAAU,YAAoB,MAAc,OAAuB;CAC1E,OAAO,GAAG,WAAW,GAAG,KAAK,GAAG;AAClC;AAEA,SAAS,iBACP,OACA,UACA,YACA,OACM;CACN,MAAM,uBAAO,IAAI,IAAoB;CACrC,KAAK,MAAM,SAAS,MAAM,YAAY,QAAQ,GAAG;EAC/C,MAAM,QAAQ,KAAK,IAAI,MAAM,IAAI,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AC1C,OAAO;AACT;;;;;AAMA,SAAgB,yBACd,OACA,UACA,UACM;CACN,IAAI,CAAC,SAAS,MAAM;CACpB,MAAM,QAA2D,CAAC;CAClE,iBAAiB,OAAO,SAAS,IAAI,KAAK,OAAO,SAAS;EACxD,MAAM,QAAQ,SAAS,IAAI,IAAI;EAC/B,IAAI,OAAO,MAAM,KAAK;GAAE;GAAO;EAAM,CAAC;CACxC,CAAC;CACD,IAAI,CAAC,MAAM,QAAQ;CACnB,KAAK,MAAM,EAAE,OAAO,WAAW,OAAO;EACpC,MAAM,UAAU,WAAW,KAAK;EAChC,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,QAAQ,MAAM,WAAW,MAAM,IAAI,OAAO;EACnE,KAAK,MAAM,SAAS,MAAM,QACxB,oBAAoB,qBAAqB,QAAQ,GAAG,SAAS,IAAI,MAAM,IAAI,KAAK;CACpF;CACA,MAAM,WAAW,SAAS,IAAI,EAAE,mBAAmB,qBAAqB,QAAQ,EAAE,CAAC;AACrF"}
@@ -5,6 +5,7 @@ import { isNumericVariableBindingField, paintBindingTarget } from "../variables/
5
5
  import { ownsSelfFillField, sourceWithEffectiveFill } from "./main-component.js";
6
6
  import { ownsSlotContent, slotPropertyId } from "../slots/frames.js";
7
7
  import { STROKE_LINE_FIELDS, STROKE_LINE_KEYS, strokeLine, withStrokeLines } from "../strokes.js";
8
+ import { createVariableResolver } from "../variables/resolver.js";
8
9
  import { applyBoundPaintColorsIn, copyAppliedBoundPaints, keepCopyBoundPaints } from "../variables/paints.js";
9
10
  import { scaleVariableBindingUnits } from "../variables/units.js";
10
11
  import { resolvedNumericBindings } from "../variables/bindings.js";
@@ -118,12 +119,13 @@ function copySyncedFields(updates, copy, source, { compParent, instParent, facto
118
119
  };
119
120
  }
120
121
  function updateSyncedProps(graph, target, updates, kept = () => false) {
121
- resolveBoundNumbersInPlace(graph, target, updates, kept);
122
+ const resolver = createVariableResolver(graph);
123
+ resolveBoundNumbersInPlace(graph, target, updates, kept, resolver);
122
124
  if (updates.fills || updates.strokes || updates.boundVariables) {
123
125
  applySyncedModes(graph, target, updates);
124
- keepCopyBoundPaints(graph, target, updates);
126
+ keepCopyBoundPaints(graph, target, updates, resolver);
125
127
  }
126
- applySyncedStrokeLines(graph, target, updates, kept);
128
+ applySyncedStrokeLines(graph, target, updates, kept, resolver);
127
129
  const changed = Object.fromEntries(Object.entries(updates).filter(([key, value]) => !isEqual(target[key], value)));
128
130
  if (changed.fills && updates.fillStyleId !== void 0) changed.fillStyleId = updates.fillStyleId;
129
131
  if (Object.keys(changed).length) graph.updateNode(target.id, changed);
@@ -134,7 +136,7 @@ function updateSyncedProps(graph, target, updates, kept = () => false) {
134
136
  * that mode's value, as Figma draws it. A field the sync leaves alone, such as one an instance
135
137
  * overrides, keeps its own value.
136
138
  */
137
- function resolveBoundNumbersInPlace(graph, target, updates, kept) {
139
+ function resolveBoundNumbersInPlace(graph, target, updates, kept, resolver) {
138
140
  const bound = updates.boundVariables ?? target.boundVariables;
139
141
  const rebound = updates.boundVariables ? Object.keys(bound).filter((field) => bound[field] !== target.boundVariables[field]) : [];
140
142
  const synced = uniq([...Object.keys(updates), ...rebound]).filter((field) => isNumericVariableBindingField(field) && bound[field] && !kept(field));
@@ -143,7 +145,7 @@ function resolveBoundNumbersInPlace(graph, target, updates, kept) {
143
145
  const resolved = resolvedNumericBindings(graph, {
144
146
  ...target,
145
147
  ...updates
146
- });
148
+ }, "active", resolver);
147
149
  Object.assign(updates, pick(resolved, synced));
148
150
  }
149
151
  /** The modes the copy takes in this sync decide what its bindings resolve to. */
@@ -155,13 +157,13 @@ function applySyncedModes(graph, target, updates) {
155
157
  * alignment, cap, join, or dash it overrides, and a bound weight resolved in its modes. Figma
156
158
  * keeps a stroke weight override when the component's color changes (live).
157
159
  */
158
- function applySyncedStrokeLines(graph, target, updates, kept) {
160
+ function applySyncedStrokeLines(graph, target, updates, kept, resolver = createVariableResolver(graph)) {
159
161
  const strokes = updates.strokes;
160
162
  const first = strokes?.at(0);
161
163
  if (!strokes || !first) return;
162
164
  const boundWeight = kept("strokeWeight") ? void 0 : (updates.boundVariables ?? target.boundVariables).strokeWeight;
163
165
  const weightScale = (updates.variableBindingScales ?? target.variableBindingScales).strokeWeight ?? 1;
164
- const resolvedWeight = boundWeight ? graph.resolveNumberVariableForNode(target.id, boundWeight, "active") : void 0;
166
+ const resolvedWeight = boundWeight ? resolver.forNode(target.id, "active").number(boundWeight) : void 0;
165
167
  const lines = {};
166
168
  let set = false;
167
169
  for (const key of STROKE_LINE_KEYS) {