@pairdraw/scene-graph 0.21.1 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/constants.d.ts +10 -4
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +60 -2
- package/dist/constants.js.map +1 -1
- package/dist/copy.js +7 -0
- package/dist/copy.js.map +1 -1
- package/dist/effects.d.ts +9 -1
- package/dist/effects.d.ts.map +1 -1
- package/dist/effects.js +10 -1
- package/dist/effects.js.map +1 -1
- package/dist/fields/layout.d.ts +1 -1
- package/dist/fields/layout.d.ts.map +1 -1
- package/dist/fields/layout.js +3 -1
- package/dist/fields/layout.js.map +1 -1
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +3 -3
- package/dist/geometry.js.map +1 -1
- package/dist/graph.d.ts +4 -1
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +9 -0
- package/dist/graph.js.map +1 -1
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +1 -1
- package/dist/hit-test.js.map +1 -1
- package/dist/images.d.ts +17 -1
- package/dist/images.d.ts.map +1 -1
- package/dist/images.js +41 -1
- package/dist/images.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/instances/fields.d.ts +5 -3
- package/dist/instances/fields.d.ts.map +1 -1
- package/dist/instances/fields.js +5 -0
- package/dist/instances/fields.js.map +1 -1
- package/dist/instances/index.d.ts +2 -2
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +8 -3
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/placement.js +1 -1
- package/dist/instances/placement.js.map +1 -1
- package/dist/instances/sync.js +24 -5
- package/dist/instances/sync.js.map +1 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +4 -0
- package/dist/node-defaults.js.map +1 -1
- package/dist/resize.d.ts +9 -2
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +20 -8
- package/dist/resize.js.map +1 -1
- package/dist/slots/content.d.ts +46 -1
- package/dist/slots/content.d.ts.map +1 -1
- package/dist/slots/content.js +146 -2
- package/dist/slots/content.js.map +1 -1
- package/dist/slots/index.d.ts +3 -2
- package/dist/slots/index.js +3 -2
- package/dist/slots/owners.d.ts +17 -0
- package/dist/slots/owners.d.ts.map +1 -0
- package/dist/slots/owners.js +39 -0
- package/dist/slots/owners.js.map +1 -0
- package/dist/types.d.ts +115 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/variables/bindings.d.ts +9 -3
- package/dist/variables/bindings.d.ts.map +1 -1
- package/dist/variables/bindings.js +128 -26
- package/dist/variables/bindings.js.map +1 -1
- package/dist/variables/fields.d.ts +20 -1
- package/dist/variables/fields.d.ts.map +1 -1
- package/dist/variables/fields.js +29 -3
- package/dist/variables/fields.js.map +1 -1
- package/dist/variables/index.d.ts +3 -3
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +25 -4
- package/dist/variables/index.js.map +1 -1
- package/dist/variant-properties.d.ts +7 -2
- package/dist/variant-properties.d.ts.map +1 -1
- package/dist/variant-properties.js +35 -3
- package/dist/variant-properties.js.map +1 -1
- package/package.json +1 -1
- package/src/constants.ts +32 -3
- package/src/copy.ts +7 -0
- package/src/effects.ts +21 -0
- package/src/fields/layout.ts +3 -1
- package/src/geometry.ts +5 -3
- package/src/graph.ts +13 -0
- package/src/hit-test.ts +7 -1
- package/src/images.ts +61 -2
- package/src/instances/fields.ts +5 -0
- package/src/instances/index.ts +10 -1
- package/src/instances/placement.ts +2 -1
- package/src/instances/sync.ts +38 -5
- package/src/node-defaults.ts +4 -0
- package/src/resize.ts +44 -6
- package/src/slots/content.ts +208 -1
- package/src/slots/index.ts +1 -0
- package/src/slots/owners.ts +45 -0
- package/src/types.ts +207 -3
- package/src/variables/bindings.ts +155 -33
- package/src/variables/fields.ts +41 -2
- package/src/variables/index.ts +40 -1
- package/src/variant-properties.ts +36 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/sync.ts"],"sourcesContent":["import { uniq } from 'es-toolkit/array'\n// Child cloning and property synchronization shared by instance creation, swap, and sync.\nimport { pick } from 'es-toolkit/object'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from '../copy'\nimport type { NodeCloneMode } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { scaleNodeChanges } from '../scaling/node'\nimport { ownsSlotContent, slotPropertyId } from '../slots/frames'\nimport {\n STROKE_LINE_FIELDS,\n STROKE_LINE_KEYS,\n strokeLine,\n type StrokeLines,\n withStrokeLines\n} from '../strokes'\nimport type { SceneNode } from '../types'\nimport { resolvedNumericBindings } from '../variables/bindings'\nimport { isNumericVariableBindingField, paintBindingTarget } from '../variables/fields'\nimport {\n applyBoundPaintColorsIn,\n copyAppliedBoundPaints,\n keepCopyBoundPaints\n} from '../variables/paints'\nimport { createVariableResolver, type VariableResolver } from '../variables/resolver'\nimport { scaleVariableBindingUnits } from '../variables/units'\nimport { applyEnclosingAssignments, assignedFieldValues, propertyDrivenFields } from './assignments'\nimport { keepOwnContentSize, remeasureChangedText, type SyncedPlacement } from './content-size'\nimport {\n createInstanceSyncContext,\n hasUnplacedCopiesBelow,\n restoreRemovedCopy,\n unplacedCopy,\n type InstanceSyncContext\n} from './copies'\nimport { INSTANCE_SYNC_FIELD_OWNERS, INSTANCE_SYNC_FIELDS } from './fields'\nimport { ownsSelfFillField, sourceWithEffectiveFill } from './main-component'\nimport { syncedVariableModes } from './modes'\nimport {\n bindingOverrideField,\n copiedComponentLayerId,\n hasInstanceOverride as hasNodeInstanceOverride,\n overriddenBindingField,\n setInstanceOverride,\n type InstanceOverrideState\n} from './overrides'\nimport { PLACEMENT_FIELDS, placedByConstraints } from './placement'\nimport { replacedLayerIn, replacedLayerMatch } from './replacements'\nimport { followVectorGeometry } from './vector-geometry'\n\nfunction setSceneProp<K extends keyof SceneNode>(\n target: Partial<SceneNode>,\n key: K,\n value: SceneNode[K]\n): void {\n target[key] = value\n}\n\nexport function copyProp(\n target: Partial<SceneNode> | SceneNode,\n source: SceneNode,\n key: keyof SceneNode\n): void {\n if (key === 'fills') {\n setSceneProp(target, key, copyFills(source.fills))\n } else if (key === 'strokes') {\n setSceneProp(target, key, copyStrokes(source.strokes))\n } else if (key === 'effects') {\n setSceneProp(target, key, copyEffects(source.effects))\n } else if (key === 'styleRuns') {\n setSceneProp(target, key, copyStyleRuns(source.styleRuns))\n } else if (key === 'boundVariables') {\n // Shallow copy the binding map — values are variable IDs (strings), not objects\n setSceneProp(target, key, { ...source.boundVariables })\n setSceneProp(target, 'variableBindingScales', { ...source.variableBindingScales })\n } else if (key === 'variableModes') {\n setSceneProp(target, key, { ...source.variableModes })\n } else if (key === 'gridPosition') {\n // Shallow copy the grid position object — all fields are primitives\n setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null)\n } else if (key === 'targetAspectRatio') {\n setSceneProp(target, key, source.targetAspectRatio ? { ...source.targetAspectRatio } : null)\n } else {\n const value = source[key]\n setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value)\n }\n}\n\nexport function bindingProtection(scopes: ReadonlySet<string>[]): (field: string) => boolean {\n const fields = new Set<string>()\n for (const scope of scopes) {\n const perField = [...scope].some((field) => overriddenBindingField(field) !== null)\n for (const field of scope) {\n if (field !== 'boundVariables' || !perField) fields.add(field)\n }\n }\n return (field) => {\n if (fields.has(field)) return true\n // Paints an instance set itself own their bindings too, bound or not.\n const binding = overriddenBindingField(field)\n if (binding === null) return false\n const paint = paintBindingTarget(binding)\n return paint !== null && fields.has(paint.list)\n }\n}\n\nexport function syncBindingFields(\n target: SceneNode,\n source: SceneNode,\n updates: Partial<SceneNode>,\n protectedField: (field: string) => boolean\n): void {\n if (protectedField('boundVariables')) return\n const bindings = { ...source.boundVariables }\n const scales = { ...source.variableBindingScales }\n for (const field of new Set([\n ...Object.keys(source.boundVariables),\n ...Object.keys(target.boundVariables),\n ...Object.keys(target.variableBindingScales)\n ])) {\n if (!protectedField(bindingOverrideField(field))) continue\n if (!Object.hasOwn(target.boundVariables, field)) Reflect.deleteProperty(bindings, field)\n else bindings[field] = target.boundVariables[field]\n if (target.variableBindingScales[field] === undefined) Reflect.deleteProperty(scales, field)\n else scales[field] = target.variableBindingScales[field]\n }\n updates.boundVariables = bindings\n updates.variableBindingScales = scales\n}\n\n/**\n * Takes the component layer's variable modes, but those the copy overrides, collection by\n * collection. A nested instance's own claims count too, as its enclosing component syncs it.\n */\nexport function syncVariableModeFields(\n target: SceneNode,\n source: SceneNode,\n updates: Partial<SceneNode>,\n protectedField: (field: string) => boolean\n): void {\n const ownClaim = (field: string) =>\n target.type === 'INSTANCE' && target.instanceOverrides.self.has(field)\n const modes = syncedVariableModes(\n target,\n source,\n (field) => protectedField(field) || ownClaim(field)\n )\n if (modes) updates.variableModes = modes\n}\n\nexport function isProtectedSyncField(\n node: SceneNode,\n key: string,\n protectedField: (field: string) => boolean\n): boolean {\n return (\n protectedField(key) ||\n (key in node.boundVariables &&\n (protectedField('boundVariables') || protectedField(bindingOverrideField(key))))\n )\n}\n\nexport function sourceInTargetCoordinates(source: SceneNode, targetScale: number): SceneNode {\n const factor = targetScale / source.componentScale\n if (!Number.isFinite(factor) || factor <= 0) throw new Error('Invalid component coordinate scale')\n if (factor === 1) return source\n const scaled = scaleNodeChanges(source, factor, true)\n return {\n ...source,\n ...scaled,\n ...scaleVariableBindingUnits(source, factor, scaled.styleRuns)\n }\n}\n\ninterface SyncedFieldsInput {\n compParent: SceneNode\n instParent: SceneNode\n /** The component's coordinates in the copy's. */\n factor: number\n /** Fields the copy keeps: overridden, bound, or driven by a property. */\n skip: (key: string) => boolean\n}\n\n/** The fields a copy takes from its component's layer, placed in the copy's parent. */\nfunction copySyncedFields(\n updates: Partial<SceneNode>,\n copy: SceneNode,\n source: SceneNode,\n { compParent, instParent, factor, skip }: SyncedFieldsInput\n): SyncedPlacement {\n // In an auto layout flow the layout places the copy, as it placed the component's layer.\n const placedByLayout = instParent.layoutMode !== 'NONE' && source.layoutPositioning !== 'ABSOLUTE'\n const placed = placedByLayout\n ? source\n : placedByConstraints(source, compParent, instParent, factor)\n for (const key of INSTANCE_SYNC_FIELDS) {\n // Bindings and modes merge entry by entry, apart from this loop.\n if (key === 'boundVariables' || key === 'variableModes') continue\n if (placedByLayout && (key === 'x' || key === 'y')) continue\n if (skip(key)) continue\n const owner = INSTANCE_SYNC_FIELD_OWNERS[key]\n if (owner && skip(owner)) continue\n const from = PLACEMENT_FIELDS.has(key) ? placed : source\n // Most fields already match: comparing first spares cloning them for nothing.\n if (isEqual(copy[key], from[key])) continue\n copyProp(updates, from, key)\n }\n // New paints bring their style link, unless the copy keeps a style of its own.\n if (updates.fills)\n updates.fillStyleId = skip('fillStyleId') ? copy.fillStyleId : source.fillStyleId\n followVectorGeometry(updates, copy, source)\n remeasureChangedText(updates, copy)\n return { placed, x: !placedByLayout && !skip('x'), y: !placedByLayout && !skip('y') }\n}\n\nexport function updateSyncedProps(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>,\n /** A field the copy keeps as its own, which the sync leaves as it is. */\n kept: (field: string) => boolean = () => false\n): void {\n const resolver = createVariableResolver(graph)\n resolveBoundNumbersInPlace(graph, target, updates, kept, resolver)\n if (updates.fills || updates.strokes || updates.boundVariables) {\n applySyncedModes(graph, target, updates)\n keepCopyBoundPaints(graph, target, updates, resolver)\n }\n // After the copy's own bound paints, which can bring its strokes into the write.\n applySyncedStrokeLines(graph, target, updates, kept, resolver)\n const changed = Object.fromEntries(\n Object.entries(updates).filter(\n ([key, value]) => !isEqual(target[key as keyof SceneNode], value)\n )\n ) as Partial<SceneNode>\n if (changed.fills && updates.fillStyleId !== undefined) changed.fillStyleId = updates.fillStyleId\n if (Object.keys(changed).length) graph.updateNode(target.id, changed)\n}\n\n/**\n * A bound number the sync writes takes the value it resolves to where the copy sits, not the\n * one its component holds: an instance that sets another mode, or sits in one that does, shows\n * that mode's value, as Figma draws it. A field the sync leaves alone, such as one an instance\n * overrides, keeps its own value.\n */\nfunction resolveBoundNumbersInPlace(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>,\n kept: (field: string) => boolean,\n resolver: VariableResolver\n): void {\n const bound = updates.boundVariables ?? target.boundVariables\n // The fields the sync writes, and the ones it binds anew, which keep an equal value only in\n // the component's mode.\n const rebound = updates.boundVariables\n ? Object.keys(bound).filter((field) => bound[field] !== target.boundVariables[field])\n : []\n const synced = uniq([...Object.keys(updates), ...rebound]).filter(\n (field) => isNumericVariableBindingField(field) && bound[field] && !kept(field)\n )\n if (synced.length === 0) return\n applySyncedModes(graph, target, updates)\n const resolved = resolvedNumericBindings(graph, { ...target, ...updates }, 'active', resolver)\n Object.assign(updates, pick(resolved, synced as (keyof SceneNode)[]))\n}\n\n/** The modes the copy takes in this sync decide what its bindings resolve to. */\nfunction applySyncedModes(graph: SceneGraph, target: SceneNode, updates: Partial<SceneNode>): void {\n if (updates.variableModes && !isEqual(updates.variableModes, target.variableModes))\n graph.updateNode(target.id, { variableModes: updates.variableModes })\n}\n\n/**\n * Strokes a sync or swap gives a copy draw with the copy's own line fields: the weight,\n * alignment, cap, join, or dash it overrides, and a bound weight resolved in its modes. Figma\n * keeps a stroke weight override when the component's color changes (live).\n */\nexport function applySyncedStrokeLines(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>,\n kept: (field: string) => boolean,\n resolver: VariableResolver = createVariableResolver(graph)\n): void {\n const strokes = updates.strokes\n const first = strokes?.at(0)\n if (!strokes || !first) return\n const boundWeight = kept('strokeWeight')\n ? undefined\n : (updates.boundVariables ?? target.boundVariables).strokeWeight\n const weightScale =\n (updates.variableBindingScales ?? target.variableBindingScales).strokeWeight ?? 1\n const resolvedWeight = boundWeight\n ? resolver.forNode(target.id, 'active').number(boundWeight)\n : undefined\n const lines: StrokeLines = {}\n let set = false\n for (const key of STROKE_LINE_KEYS) {\n const field = STROKE_LINE_FIELDS[key]\n const own = kept(field)\n // A bound weight takes the value it resolves to where the copy sits, not its component's.\n const synced = own ? target[field] : updates[field]\n const value =\n field === 'strokeWeight' && resolvedWeight !== undefined\n ? resolvedWeight * weightScale\n : synced\n if (value === undefined) continue\n // A field the copy overrides holds for every stroke; the component's own values keep its\n // strokes' differences unless a binding resolved the first one apart.\n const differs = own\n ? strokes.some((stroke) => !isEqual(value, strokeLine(stroke, key)))\n : !isEqual(value, strokeLine(first, key))\n if (!differs) continue\n Reflect.set(lines, key, value)\n set = true\n }\n if (set) updates.strokes = withStrokeLines(strokes, lines)\n}\n\nfunction cloneChildInCoordinates(\n graph: SceneGraph,\n src: SceneNode,\n sourceParent: SceneNode,\n targetParent: SceneNode,\n mode: NodeCloneMode = 'deep'\n): SceneNode {\n const componentScale =\n (src.componentScale * targetParent.componentScale) / sourceParent.componentScale\n const clone = graph.createNode(src.type, targetParent.id, {\n ...cloneNodeProps(sourceInTargetCoordinates(src, componentScale), src.id, mode),\n componentScale\n })\n copyAppliedBoundPaints(src, clone)\n return clone\n}\n\nexport function cloneChildrenWithMapping(\n graph: SceneGraph,\n sourceParentId: string,\n destParentId: string,\n mode: NodeCloneMode = 'deep'\n): void {\n // A cyclic component, such as an instance of an ancestor, would clone itself without end.\n if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return\n\n const sourceParent = graph.nodes.get(sourceParentId)\n const targetParent = graph.nodes.get(destParentId)\n if (!sourceParent || !targetParent) return\n\n for (const childId of sourceParent.childIds) {\n const src = graph.nodes.get(childId)\n if (!src) continue\n\n const clone = cloneChildInCoordinates(graph, src, sourceParent, targetParent, mode)\n\n if (src.childIds.length > 0) {\n cloneChildrenWithMapping(graph, childId, clone.id, mode)\n }\n }\n}\n\nexport function enclosingInstanceOverrideFields(graph: SceneGraph, node: SceneNode): Set<string>[] {\n const fields: Set<string>[] = []\n let parent = node.parentId ? graph.nodes.get(node.parentId) : undefined\n while (parent) {\n if (parent.type === 'INSTANCE') {\n fields.push(new Set(parent.instanceOverrides.descendants.get(node.id)?.keys()))\n }\n parent = parent.parentId ? graph.nodes.get(parent.parentId) : undefined\n }\n return fields\n}\n\nfunction childBindingProtection(\n graph: SceneGraph,\n child: SceneNode,\n overrides: InstanceOverrideState\n) {\n const fields = enclosingInstanceOverrideFields(graph, child)\n fields.push(new Set(overrides.descendants.get(child.id)?.keys()))\n const protectedField = bindingProtection(fields)\n return (field: string) => protectedField(field) || ownsSelfFillField(child, field)\n}\n\n/** Links a copy to the component layer it matched, reporting each changed node and its owner. */\nfunction linkMatchedChild(\n graph: SceneGraph,\n context: InstanceSyncContext,\n instParentId: string,\n instChild: SceneNode,\n compChildId: string\n): void {\n const { overrides } = context\n const recorded = hasNodeInstanceOverride(\n overrides,\n instParentId,\n instChild.id,\n 'sourceComponentId'\n )\n if (instChild.type === 'INSTANCE' || recorded) {\n const owner = graph.nodes.get(context.instanceId)\n graph.willChangeNode(owner)\n setInstanceOverride(overrides, instParentId, instChild.id, 'sourceComponentId', compChildId)\n if (owner) graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })\n }\n if (instChild.type !== 'INSTANCE') graph.updateNode(instChild.id, { componentId: compChildId })\n}\n\nfunction matchFallbackChildren(\n graph: SceneGraph,\n compParent: SceneNode,\n instParent: SceneNode,\n instParentId: string,\n context: InstanceSyncContext,\n instChildMap: Map<string, SceneNode>,\n usedInstChildIds: Set<string>\n): void {\n const fallbackByType = new Map<SceneNode['type'], Map<string, SceneNode[]>>()\n const remainingCandidateCount = new Map<SceneNode['type'], number>()\n const unmatchedComponentCount = new Map<SceneNode['type'], number>()\n for (const compChildId of compParent.childIds) {\n if (instChildMap.has(compChildId)) continue\n const child = graph.nodes.get(compChildId)\n if (child) {\n unmatchedComponentCount.set(child.type, (unmatchedComponentCount.get(child.type) ?? 0) + 1)\n }\n }\n for (const childId of instParent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || usedInstChildIds.has(child.id)) continue\n remainingCandidateCount.set(child.type, (remainingCandidateCount.get(child.type) ?? 0) + 1)\n let byName = fallbackByType.get(child.type)\n if (!byName) {\n byName = new Map()\n fallbackByType.set(child.type, byName)\n }\n const queue = byName.get(child.name)\n if (queue) queue.push(child)\n else byName.set(child.name, [child])\n }\n\n // Match by name and type with FIFO queues to preserve sibling order in linear time.\n for (const compChildId of compParent.childIds) {\n if (instChildMap.has(compChildId)) continue\n const compChild = graph.nodes.get(compChildId)\n if (!compChild) continue\n const candidatesByName = fallbackByType.get(compChild.type)\n const candidateCount = remainingCandidateCount.get(compChild.type) ?? 0\n if (candidateCount > (unmatchedComponentCount.get(compChild.type) ?? 0)) continue\n const match = candidatesByName?.get(compChild.name)?.shift()\n if (!match) continue\n remainingCandidateCount.set(compChild.type, candidateCount - 1)\n instChildMap.set(compChildId, match)\n usedInstChildIds.add(match.id)\n linkMatchedChild(graph, context, instParentId, match, compChildId)\n }\n}\n\nfunction sortInstanceChildren(\n graph: SceneGraph,\n instParent: SceneNode,\n instParentId: string,\n compChildOrder: string[],\n overrides: InstanceOverrideState,\n matched: ReadonlyMap<string, SceneNode>\n): void {\n // A replaced layer copies nothing, so its place comes from the layer it was matched to.\n const matchedLayer = new Map([...matched].map(([layerId, child]) => [child.id, layerId]))\n const orderMap = new Map<string, number>()\n for (let i = 0; i < compChildOrder.length; i++) orderMap.set(compChildOrder[i], i)\n\n const ranks = new Map<string, number>()\n for (let index = 0; index < instParent.childIds.length; index++) {\n const childId = instParent.childIds[index]\n const node = graph.nodes.get(childId)\n const mapped =\n matchedLayer.get(childId) ?? (node && copiedComponentLayerId(overrides, instParentId, node))\n const componentIndex = mapped ? orderMap.get(mapped) : undefined\n ranks.set(childId, componentIndex ?? compChildOrder.length + index)\n }\n const sorted = instParent.childIds.toSorted(\n (left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0)\n )\n // Move through the graph so the reorder is reported, as collaboration syncs it.\n sorted.forEach((childId, index) => {\n if (instParent.childIds[index] !== childId) graph.insertChildAt(childId, instParentId, index)\n })\n}\n\n/** True when syncing `compParentId` into `instParentId` would form a cycle. */\nfunction isCyclicSync(graph: SceneGraph, compParentId: string, instParentId: string): boolean {\n return compParentId === instParentId || graph.isDescendant(instParentId, compParentId)\n}\n\n/**\n * Children already linked to a component child: a layer an instance put in place of one, or a\n * copy by sourceComponentId or componentId.\n */\nfunction matchLinkedChildren(\n graph: SceneGraph,\n instParent: SceneNode,\n instParentId: string,\n overrides: InstanceOverrideState,\n owner: SceneNode | undefined,\n compParent: SceneNode,\n instChildMap: Map<string, SceneNode>,\n usedInstChildIds: Set<string>\n): void {\n const compChildIdSet = new Set(compParent.childIds)\n const replacements = new Set<string>()\n // Replaced layers first: each keeps the place it took, whatever else claims it.\n for (const childId of instParent.childIds) {\n const replaced = replacedLayerIn(owner, childId)\n const layerId = replaced && replacedLayerMatch(graph, replaced, compParent.childIds)\n const child = graph.nodes.get(childId)\n if (!layerId || !child || instChildMap.has(layerId)) continue\n instChildMap.set(layerId, child)\n usedInstChildIds.add(child.id)\n replacements.add(child.id)\n }\n for (const childId of instParent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || replacements.has(child.id)) continue\n const mappedComponentId = copiedComponentLayerId(overrides, instParentId, child)\n if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {\n // The first copy of a layer keeps it; a duplicate stays unmatched for the sync to remove.\n if (instChildMap.has(mappedComponentId)) continue\n instChildMap.set(mappedComponentId, child)\n usedInstChildIds.add(child.id)\n }\n }\n}\n\n/**\n * Pass 3 of a sync: bring along the copy of a layer moved here inside the component, bring back\n * one the sync removed when its layer returns, or clone a layer the instance has no copy of. A\n * clone takes its own subtree unless copies the instance has belong in it, which the recursion\n * moves in instead. Children left unmatched are the sync's to remove once it finishes.\n */\nfunction placeMissingChildren(\n graph: SceneGraph,\n compParent: SceneNode,\n instParent: SceneNode,\n instChildMap: Map<string, SceneNode>,\n usedInstChildIds: Set<string>,\n context: InstanceSyncContext\n): void {\n for (const child of instChildMap.values()) context.matched.add(child.id)\n\n for (const compChildId of compParent.childIds) {\n if (instChildMap.has(compChildId)) continue\n const moved =\n unplacedCopy(graph, context, compChildId, instParent.id) ??\n restoreRemovedCopy(graph, context, compChildId, instParent.id)\n if (moved) {\n graph.insertChildAt(moved.id, instParent.id, instParent.childIds.length)\n instChildMap.set(compChildId, moved)\n usedInstChildIds.add(moved.id)\n context.matched.add(moved.id)\n continue\n }\n const src = graph.nodes.get(compChildId)\n if (!src) continue\n const clone = cloneChildInCoordinates(graph, src, compParent, instParent)\n if (src.childIds.length > 0 && !hasUnplacedCopiesBelow(graph, context, compChildId)) {\n cloneChildrenWithMapping(graph, compChildId, clone.id)\n }\n applyEnclosingAssignments(graph, clone)\n applyBoundPaintColorsIn(graph, clone.id)\n instChildMap.set(compChildId, clone)\n usedInstChildIds.add(clone.id)\n context.matched.add(clone.id)\n }\n for (const childId of instParent.childIds) {\n if (!usedInstChildIds.has(childId)) context.leftovers.add(childId)\n }\n}\n\nexport function syncChildren(\n graph: SceneGraph,\n compParentId: string,\n instParentId: string,\n overrides: InstanceOverrideState,\n context: InstanceSyncContext = createInstanceSyncContext(instParentId, overrides)\n): void {\n // An instance inside its own component would clone the component into itself without end.\n if (isCyclicSync(graph, compParentId, instParentId)) return\n\n const compParent = graph.nodes.get(compParentId)\n const instParent = graph.nodes.get(instParentId)\n if (!compParent || !instParent) return\n\n const instChildMap = new Map<string, SceneNode>()\n const usedInstChildIds = new Set<string>()\n\n // The instance that records overrides of these children is the same for all of them.\n const owner =\n instParent.type === 'INSTANCE'\n ? instParent\n : graph.closest(instParent.id, (node) => node.type === 'INSTANCE')\n\n // Pass 1: Direct matching via a replacement, sourceComponentId, or componentId\n matchLinkedChildren(\n graph,\n instParent,\n instParentId,\n overrides,\n owner,\n compParent,\n instChildMap,\n usedInstChildIds\n )\n\n // Pass 2: Fallback matching for unmatched children (e.g. from Figma imports)\n matchFallbackChildren(\n graph,\n compParent,\n instParent,\n instParentId,\n context,\n instChildMap,\n usedInstChildIds\n )\n\n placeMissingChildren(graph, compParent, instParent, instChildMap, usedInstChildIds, context)\n\n // Pass 4: Synchronize properties and recurse\n for (const compChildId of compParent.childIds) {\n const compChild = graph.nodes.get(compChildId)\n const instChild = instChildMap.get(compChildId)\n if (!compChild || !instChild) continue\n // A replaced layer is the instance's own: nothing of the layer it replaced reaches it, also\n // when it followed that layer here from elsewhere in the component.\n if (replacedLayerIn(owner, instChild.id) !== undefined) continue\n\n const protectedField = childBindingProtection(graph, instChild, overrides)\n const driven = propertyDrivenFields(graph, instChild, compChild)\n const kept = (key: string) =>\n driven.has(key) || isProtectedSyncField(instChild, key, protectedField)\n const componentScale =\n (compChild.componentScale * instParent.componentScale) / compParent.componentScale\n const effectiveSource = sourceWithEffectiveFill(graph, compChild, instChild)\n const source = sourceInTargetCoordinates(effectiveSource, componentScale)\n // Which properties a layer serves is the component's to say; a slot or exposed layer\n // created on the component becomes one in every instance.\n const updates: Partial<SceneNode> = {\n componentScale,\n componentPropertyReferences: structuredClone(compChild.componentPropertyReferences)\n }\n syncBindingFields(instChild, source, updates, protectedField)\n syncVariableModeFields(\n instChild,\n source,\n updates,\n (field) => driven.has(field) || protectedField(field)\n )\n const placement = copySyncedFields(updates, instChild, source, {\n compParent,\n instParent,\n factor: componentScale / compChild.componentScale,\n skip: kept\n })\n Object.assign(updates, assignedFieldValues(graph, instChild, compChild))\n keepOwnContentSize(graph, updates, instChild, source, placement)\n updateSyncedProps(graph, instChild, updates, kept)\n\n if (\n compChild.childIds.length > 0 &&\n !hasNodeInstanceOverride(overrides, instParentId, instChild.id, 'componentId') &&\n // The component's frame is the authority on which slot this is; instance copies of\n // its bindings are not synced.\n !ownsSlotContent(graph, instChild, slotPropertyId(compChild))\n ) {\n syncChildren(graph, compChildId, instChild.id, overrides, context)\n }\n }\n\n // Pass 5: Sort instance children to match component child order\n sortInstanceChildren(\n graph,\n instParent,\n instParentId,\n compParent.childIds,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CAErE;CAGA,qBACE,OACA,YACA,cACA,WAAW,UACX,WACA,YACF;AACF"}
|
|
1
|
+
{"version":3,"file":"sync.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/sync.ts"],"sourcesContent":["import { uniq } from 'es-toolkit/array'\n// Child cloning and property synchronization shared by instance creation, swap, and sync.\nimport { pick } from 'es-toolkit/object'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from '../copy'\nimport type { NodeCloneMode } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { scaleNodeChanges } from '../scaling/node'\nimport { ownsSlotContent, slotPropertyId } from '../slots/frames'\nimport {\n STROKE_LINE_FIELDS,\n STROKE_LINE_KEYS,\n strokeLine,\n type StrokeLines,\n withStrokeLines\n} from '../strokes'\nimport type { SceneNode } from '../types'\nimport { resolvedEffectColorBindings, resolvedNumericBindings } from '../variables/bindings'\nimport {\n effectBindingTarget,\n effectColorBindingTarget,\n isNumericVariableBindingField,\n layoutGridBindingTarget,\n paintBindingTarget\n} from '../variables/fields'\nimport {\n applyBoundPaintColorsIn,\n copyAppliedBoundPaints,\n keepCopyBoundPaints\n} from '../variables/paints'\nimport { createVariableResolver, type VariableResolver } from '../variables/resolver'\nimport { scaleVariableBindingUnits } from '../variables/units'\nimport { applyEnclosingAssignments, assignedFieldValues, propertyDrivenFields } from './assignments'\nimport { keepOwnContentSize, remeasureChangedText, type SyncedPlacement } from './content-size'\nimport {\n createInstanceSyncContext,\n hasUnplacedCopiesBelow,\n restoreRemovedCopy,\n unplacedCopy,\n type InstanceSyncContext\n} from './copies'\nimport { INSTANCE_SYNC_FIELD_OWNERS, INSTANCE_SYNC_FIELDS } from './fields'\nimport { ownsSelfFillField, sourceWithEffectiveFill } from './main-component'\nimport { syncedVariableModes } from './modes'\nimport {\n bindingOverrideField,\n copiedComponentLayerId,\n hasInstanceOverride as hasNodeInstanceOverride,\n overriddenBindingField,\n setInstanceOverride,\n type InstanceOverrideState\n} from './overrides'\nimport { PLACEMENT_FIELDS, placedByConstraints } from './placement'\nimport { replacedLayerIn, replacedLayerMatch } from './replacements'\nimport { followVectorGeometry } from './vector-geometry'\n\nfunction setSceneProp<K extends keyof SceneNode>(\n target: Partial<SceneNode>,\n key: K,\n value: SceneNode[K]\n): void {\n target[key] = value\n}\n\nexport function copyProp(\n target: Partial<SceneNode> | SceneNode,\n source: SceneNode,\n key: keyof SceneNode\n): void {\n if (key === 'fills') {\n setSceneProp(target, key, copyFills(source.fills))\n } else if (key === 'strokes') {\n setSceneProp(target, key, copyStrokes(source.strokes))\n } else if (key === 'effects') {\n setSceneProp(target, key, copyEffects(source.effects))\n } else if (key === 'styleRuns') {\n setSceneProp(target, key, copyStyleRuns(source.styleRuns))\n } else if (key === 'boundVariables') {\n // Shallow copy the binding map — values are variable IDs (strings), not objects\n setSceneProp(target, key, { ...source.boundVariables })\n setSceneProp(target, 'variableBindingScales', { ...source.variableBindingScales })\n } else if (key === 'variableModes') {\n setSceneProp(target, key, { ...source.variableModes })\n } else if (key === 'gridPosition') {\n // Shallow copy the grid position object — all fields are primitives\n setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null)\n } else if (key === 'targetAspectRatio') {\n setSceneProp(target, key, source.targetAspectRatio ? { ...source.targetAspectRatio } : null)\n } else {\n const value = source[key]\n setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value)\n }\n}\n\nexport function bindingProtection(scopes: ReadonlySet<string>[]): (field: string) => boolean {\n const fields = new Set<string>()\n for (const scope of scopes) {\n const perField = [...scope].some((field) => overriddenBindingField(field) !== null)\n for (const field of scope) {\n if (field !== 'boundVariables' || !perField) fields.add(field)\n }\n }\n return (field) => {\n if (fields.has(field)) return true\n // Paints an instance set itself own their bindings too, bound or not.\n const binding = overriddenBindingField(field)\n if (binding === null) return false\n const paint = paintBindingTarget(binding)\n return paint !== null && fields.has(paint.list)\n }\n}\n\nexport function syncBindingFields(\n target: SceneNode,\n source: SceneNode,\n updates: Partial<SceneNode>,\n protectedField: (field: string) => boolean\n): void {\n if (protectedField('boundVariables')) return\n const bindings = { ...source.boundVariables }\n const scales = { ...source.variableBindingScales }\n for (const field of new Set([\n ...Object.keys(source.boundVariables),\n ...Object.keys(target.boundVariables),\n ...Object.keys(target.variableBindingScales)\n ])) {\n if (!protectedField(bindingOverrideField(field))) continue\n if (!Object.hasOwn(target.boundVariables, field)) Reflect.deleteProperty(bindings, field)\n else bindings[field] = target.boundVariables[field]\n if (target.variableBindingScales[field] === undefined) Reflect.deleteProperty(scales, field)\n else scales[field] = target.variableBindingScales[field]\n }\n updates.boundVariables = bindings\n updates.variableBindingScales = scales\n}\n\n/**\n * Takes the component layer's variable modes, but those the copy overrides, collection by\n * collection. A nested instance's own claims count too, as its enclosing component syncs it.\n */\nexport function syncVariableModeFields(\n target: SceneNode,\n source: SceneNode,\n updates: Partial<SceneNode>,\n protectedField: (field: string) => boolean\n): void {\n const ownClaim = (field: string) =>\n target.type === 'INSTANCE' && target.instanceOverrides.self.has(field)\n const modes = syncedVariableModes(\n target,\n source,\n (field) => protectedField(field) || ownClaim(field)\n )\n if (modes) updates.variableModes = modes\n}\n\nexport function isProtectedSyncField(\n node: SceneNode,\n key: string,\n protectedField: (field: string) => boolean\n): boolean {\n return (\n protectedField(key) ||\n (key in node.boundVariables &&\n (protectedField('boundVariables') || protectedField(bindingOverrideField(key))))\n )\n}\n\nexport function sourceInTargetCoordinates(source: SceneNode, targetScale: number): SceneNode {\n const factor = targetScale / source.componentScale\n if (!Number.isFinite(factor) || factor <= 0) throw new Error('Invalid component coordinate scale')\n if (factor === 1) return source\n const scaled = scaleNodeChanges(source, factor, true)\n return {\n ...source,\n ...scaled,\n ...scaleVariableBindingUnits(source, factor, scaled.styleRuns)\n }\n}\n\ninterface SyncedFieldsInput {\n compParent: SceneNode\n instParent: SceneNode\n /** The component's coordinates in the copy's. */\n factor: number\n /** Fields the copy keeps: overridden, bound, or driven by a property. */\n skip: (key: string) => boolean\n}\n\n/** The fields a copy takes from its component's layer, placed in the copy's parent. */\nfunction copySyncedFields(\n updates: Partial<SceneNode>,\n copy: SceneNode,\n source: SceneNode,\n { compParent, instParent, factor, skip }: SyncedFieldsInput\n): SyncedPlacement {\n // In an auto layout flow the layout places the copy, as it placed the component's layer.\n const placedByLayout = instParent.layoutMode !== 'NONE' && source.layoutPositioning !== 'ABSOLUTE'\n const placed = placedByLayout\n ? source\n : placedByConstraints(source, compParent, instParent, factor)\n for (const key of INSTANCE_SYNC_FIELDS) {\n // Bindings and modes merge entry by entry, apart from this loop.\n if (key === 'boundVariables' || key === 'variableModes') continue\n if (placedByLayout && (key === 'x' || key === 'y')) continue\n if (skip(key)) continue\n const owner = INSTANCE_SYNC_FIELD_OWNERS[key]\n if (owner && skip(owner)) continue\n const from = PLACEMENT_FIELDS.has(key) ? placed : source\n // Most fields already match: comparing first spares cloning them for nothing.\n if (isEqual(copy[key], from[key])) continue\n copyProp(updates, from, key)\n }\n // New paints bring their style link, unless the copy keeps a style of its own.\n if (updates.fills)\n updates.fillStyleId = skip('fillStyleId') ? copy.fillStyleId : source.fillStyleId\n followVectorGeometry(updates, copy, source)\n remeasureChangedText(updates, copy)\n return { placed, x: !placedByLayout && !skip('x'), y: !placedByLayout && !skip('y') }\n}\n\nexport function updateSyncedProps(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>,\n /** A field the copy keeps as its own, which the sync leaves as it is. */\n kept: (field: string) => boolean = () => false\n): void {\n const resolver = createVariableResolver(graph)\n resolveBoundNumbersInPlace(graph, target, updates, kept, resolver)\n if (updates.fills || updates.strokes || updates.boundVariables) {\n applySyncedModes(graph, target, updates)\n keepCopyBoundPaints(graph, target, updates, resolver)\n }\n // After the copy's own bound paints, which can bring its strokes into the write.\n applySyncedStrokeLines(graph, target, updates, kept, resolver)\n const changed = Object.fromEntries(\n Object.entries(updates).filter(\n ([key, value]) => !isEqual(target[key as keyof SceneNode], value)\n )\n ) as Partial<SceneNode>\n if (changed.fills && updates.fillStyleId !== undefined) changed.fillStyleId = updates.fillStyleId\n if (Object.keys(changed).length) graph.updateNode(target.id, changed)\n}\n\n/**\n * A bound number the sync writes takes the value it resolves to where the copy sits, not the\n * one its component holds: an instance that sets another mode, or sits in one that does, shows\n * that mode's value, as Figma draws it. A field the sync leaves alone, such as one an instance\n * overrides, keeps its own value.\n */\nfunction resolveBoundNumbersInPlace(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>,\n kept: (field: string) => boolean,\n resolver: VariableResolver\n): void {\n const bound = updates.boundVariables ?? target.boundVariables\n // The fields the sync writes, and the ones it binds anew, which keep an equal value only in\n // the component's mode.\n const rebound = updates.boundVariables\n ? Object.keys(bound).filter((field) => bound[field] !== target.boundVariables[field])\n : []\n // A list binding (`effects/0/radius`) resolves into the whole list, so the list is what a sync\n // copies when it writes that list and the resolved value would change.\n const lists = Object.keys(bound).flatMap((field) => {\n let list: 'effects' | 'layoutGrids' | null = null\n if (effectBindingTarget(field) || effectColorBindingTarget(field)) list = 'effects'\n else if (layoutGridBindingTarget(field)) list = 'layoutGrids'\n return list && list in updates ? [list] : []\n })\n const hasBinding = (field: string) =>\n field === 'effects' || field === 'layoutGrids'\n ? Object.keys(bound).some((key) => key.startsWith(`${field}/`))\n : Boolean(bound[field])\n const synced = uniq([...Object.keys(updates), ...rebound, ...lists]).filter(\n (field) =>\n (isNumericVariableBindingField(field) || field === 'effects' || field === 'layoutGrids') &&\n hasBinding(field) &&\n !kept(field)\n )\n if (synced.length === 0) return\n applySyncedModes(graph, target, updates)\n const merged = { ...target, ...updates }\n const resolved = resolvedNumericBindings(graph, merged, 'active', resolver)\n Object.assign(updates, pick(resolved, synced as (keyof SceneNode)[]))\n if (synced.includes('effects')) {\n const colors = resolvedEffectColorBindings(\n graph,\n {\n ...merged,\n ...(updates.effects ? { effects: updates.effects } : {})\n },\n resolver\n )\n if (colors) updates.effects = colors\n }\n}\n\n/** The modes the copy takes in this sync decide what its bindings resolve to. */\nfunction applySyncedModes(graph: SceneGraph, target: SceneNode, updates: Partial<SceneNode>): void {\n if (updates.variableModes && !isEqual(updates.variableModes, target.variableModes))\n graph.updateNode(target.id, { variableModes: updates.variableModes })\n}\n\n/**\n * Strokes a sync or swap gives a copy draw with the copy's own line fields: the weight,\n * alignment, cap, join, or dash it overrides, and a bound weight resolved in its modes. Figma\n * keeps a stroke weight override when the component's color changes (live).\n */\nexport function applySyncedStrokeLines(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>,\n kept: (field: string) => boolean,\n resolver: VariableResolver = createVariableResolver(graph)\n): void {\n const strokes = updates.strokes\n const first = strokes?.at(0)\n if (!strokes || !first) return\n const boundWeight = kept('strokeWeight')\n ? undefined\n : (updates.boundVariables ?? target.boundVariables).strokeWeight\n const weightScale =\n (updates.variableBindingScales ?? target.variableBindingScales).strokeWeight ?? 1\n const resolvedWeight = boundWeight\n ? resolver.forNode(target.id, 'active').number(boundWeight)\n : undefined\n const lines: StrokeLines = {}\n let set = false\n for (const key of STROKE_LINE_KEYS) {\n const field = STROKE_LINE_FIELDS[key]\n const own = kept(field)\n // A bound weight takes the value it resolves to where the copy sits, not its component's.\n const synced = own ? target[field] : updates[field]\n const value =\n field === 'strokeWeight' && resolvedWeight !== undefined\n ? resolvedWeight * weightScale\n : synced\n if (value === undefined) continue\n // A field the copy overrides holds for every stroke; the component's own values keep its\n // strokes' differences unless a binding resolved the first one apart.\n const differs = own\n ? strokes.some((stroke) => !isEqual(value, strokeLine(stroke, key)))\n : !isEqual(value, strokeLine(first, key))\n if (!differs) continue\n Reflect.set(lines, key, value)\n set = true\n }\n if (set) updates.strokes = withStrokeLines(strokes, lines)\n}\n\nfunction cloneChildInCoordinates(\n graph: SceneGraph,\n src: SceneNode,\n sourceParent: SceneNode,\n targetParent: SceneNode,\n mode: NodeCloneMode = 'deep'\n): SceneNode {\n const componentScale =\n (src.componentScale * targetParent.componentScale) / sourceParent.componentScale\n const clone = graph.createNode(src.type, targetParent.id, {\n ...cloneNodeProps(sourceInTargetCoordinates(src, componentScale), src.id, mode),\n componentScale\n })\n copyAppliedBoundPaints(src, clone)\n return clone\n}\n\nexport function cloneChildrenWithMapping(\n graph: SceneGraph,\n sourceParentId: string,\n destParentId: string,\n mode: NodeCloneMode = 'deep'\n): void {\n // A cyclic component, such as an instance of an ancestor, would clone itself without end.\n if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return\n\n const sourceParent = graph.nodes.get(sourceParentId)\n const targetParent = graph.nodes.get(destParentId)\n if (!sourceParent || !targetParent) return\n\n for (const childId of sourceParent.childIds) {\n const src = graph.nodes.get(childId)\n if (!src) continue\n\n const clone = cloneChildInCoordinates(graph, src, sourceParent, targetParent, mode)\n\n if (src.childIds.length > 0) {\n cloneChildrenWithMapping(graph, childId, clone.id, mode)\n }\n }\n}\n\nexport function enclosingInstanceOverrideFields(graph: SceneGraph, node: SceneNode): Set<string>[] {\n const fields: Set<string>[] = []\n let parent = node.parentId ? graph.nodes.get(node.parentId) : undefined\n while (parent) {\n if (parent.type === 'INSTANCE') {\n fields.push(new Set(parent.instanceOverrides.descendants.get(node.id)?.keys()))\n }\n parent = parent.parentId ? graph.nodes.get(parent.parentId) : undefined\n }\n return fields\n}\n\nfunction childBindingProtection(\n graph: SceneGraph,\n child: SceneNode,\n overrides: InstanceOverrideState\n) {\n const fields = enclosingInstanceOverrideFields(graph, child)\n fields.push(new Set(overrides.descendants.get(child.id)?.keys()))\n const protectedField = bindingProtection(fields)\n return (field: string) => protectedField(field) || ownsSelfFillField(child, field)\n}\n\n/** Links a copy to the component layer it matched, reporting each changed node and its owner. */\nfunction linkMatchedChild(\n graph: SceneGraph,\n context: InstanceSyncContext,\n instParentId: string,\n instChild: SceneNode,\n compChildId: string\n): void {\n const { overrides } = context\n const recorded = hasNodeInstanceOverride(\n overrides,\n instParentId,\n instChild.id,\n 'sourceComponentId'\n )\n if (instChild.type === 'INSTANCE' || recorded) {\n const owner = graph.nodes.get(context.instanceId)\n graph.willChangeNode(owner)\n setInstanceOverride(overrides, instParentId, instChild.id, 'sourceComponentId', compChildId)\n if (owner) graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })\n }\n if (instChild.type !== 'INSTANCE') graph.updateNode(instChild.id, { componentId: compChildId })\n}\n\nfunction matchFallbackChildren(\n graph: SceneGraph,\n compParent: SceneNode,\n instParent: SceneNode,\n instParentId: string,\n context: InstanceSyncContext,\n instChildMap: Map<string, SceneNode>,\n usedInstChildIds: Set<string>\n): void {\n const fallbackByType = new Map<SceneNode['type'], Map<string, SceneNode[]>>()\n const remainingCandidateCount = new Map<SceneNode['type'], number>()\n const unmatchedComponentCount = new Map<SceneNode['type'], number>()\n for (const compChildId of compParent.childIds) {\n if (instChildMap.has(compChildId)) continue\n const child = graph.nodes.get(compChildId)\n if (child) {\n unmatchedComponentCount.set(child.type, (unmatchedComponentCount.get(child.type) ?? 0) + 1)\n }\n }\n for (const childId of instParent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || usedInstChildIds.has(child.id)) continue\n remainingCandidateCount.set(child.type, (remainingCandidateCount.get(child.type) ?? 0) + 1)\n let byName = fallbackByType.get(child.type)\n if (!byName) {\n byName = new Map()\n fallbackByType.set(child.type, byName)\n }\n const queue = byName.get(child.name)\n if (queue) queue.push(child)\n else byName.set(child.name, [child])\n }\n\n // Match by name and type with FIFO queues to preserve sibling order in linear time.\n for (const compChildId of compParent.childIds) {\n if (instChildMap.has(compChildId)) continue\n const compChild = graph.nodes.get(compChildId)\n if (!compChild) continue\n const candidatesByName = fallbackByType.get(compChild.type)\n const candidateCount = remainingCandidateCount.get(compChild.type) ?? 0\n if (candidateCount > (unmatchedComponentCount.get(compChild.type) ?? 0)) continue\n const match = candidatesByName?.get(compChild.name)?.shift()\n if (!match) continue\n remainingCandidateCount.set(compChild.type, candidateCount - 1)\n instChildMap.set(compChildId, match)\n usedInstChildIds.add(match.id)\n linkMatchedChild(graph, context, instParentId, match, compChildId)\n }\n}\n\nfunction sortInstanceChildren(\n graph: SceneGraph,\n instParent: SceneNode,\n instParentId: string,\n compChildOrder: string[],\n overrides: InstanceOverrideState,\n matched: ReadonlyMap<string, SceneNode>\n): void {\n // A replaced layer copies nothing, so its place comes from the layer it was matched to.\n const matchedLayer = new Map([...matched].map(([layerId, child]) => [child.id, layerId]))\n const orderMap = new Map<string, number>()\n for (let i = 0; i < compChildOrder.length; i++) orderMap.set(compChildOrder[i], i)\n\n const ranks = new Map<string, number>()\n for (let index = 0; index < instParent.childIds.length; index++) {\n const childId = instParent.childIds[index]\n const node = graph.nodes.get(childId)\n const mapped =\n matchedLayer.get(childId) ?? (node && copiedComponentLayerId(overrides, instParentId, node))\n const componentIndex = mapped ? orderMap.get(mapped) : undefined\n ranks.set(childId, componentIndex ?? compChildOrder.length + index)\n }\n const sorted = instParent.childIds.toSorted(\n (left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0)\n )\n // Move through the graph so the reorder is reported, as collaboration syncs it.\n sorted.forEach((childId, index) => {\n if (instParent.childIds[index] !== childId) graph.insertChildAt(childId, instParentId, index)\n })\n}\n\n/** True when syncing `compParentId` into `instParentId` would form a cycle. */\nfunction isCyclicSync(graph: SceneGraph, compParentId: string, instParentId: string): boolean {\n return compParentId === instParentId || graph.isDescendant(instParentId, compParentId)\n}\n\n/**\n * Children already linked to a component child: a layer an instance put in place of one, or a\n * copy by sourceComponentId or componentId.\n */\nfunction matchLinkedChildren(\n graph: SceneGraph,\n instParent: SceneNode,\n instParentId: string,\n overrides: InstanceOverrideState,\n owner: SceneNode | undefined,\n compParent: SceneNode,\n instChildMap: Map<string, SceneNode>,\n usedInstChildIds: Set<string>\n): void {\n const compChildIdSet = new Set(compParent.childIds)\n const replacements = new Set<string>()\n // Replaced layers first: each keeps the place it took, whatever else claims it.\n for (const childId of instParent.childIds) {\n const replaced = replacedLayerIn(owner, childId)\n const layerId = replaced && replacedLayerMatch(graph, replaced, compParent.childIds)\n const child = graph.nodes.get(childId)\n if (!layerId || !child || instChildMap.has(layerId)) continue\n instChildMap.set(layerId, child)\n usedInstChildIds.add(child.id)\n replacements.add(child.id)\n }\n for (const childId of instParent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || replacements.has(child.id)) continue\n const mappedComponentId = copiedComponentLayerId(overrides, instParentId, child)\n if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {\n // The first copy of a layer keeps it; a duplicate stays unmatched for the sync to remove.\n if (instChildMap.has(mappedComponentId)) continue\n instChildMap.set(mappedComponentId, child)\n usedInstChildIds.add(child.id)\n }\n }\n}\n\n/**\n * Pass 3 of a sync: bring along the copy of a layer moved here inside the component, bring back\n * one the sync removed when its layer returns, or clone a layer the instance has no copy of. A\n * clone takes its own subtree unless copies the instance has belong in it, which the recursion\n * moves in instead. Children left unmatched are the sync's to remove once it finishes.\n */\nfunction placeMissingChildren(\n graph: SceneGraph,\n compParent: SceneNode,\n instParent: SceneNode,\n instChildMap: Map<string, SceneNode>,\n usedInstChildIds: Set<string>,\n context: InstanceSyncContext\n): void {\n for (const child of instChildMap.values()) context.matched.add(child.id)\n\n for (const compChildId of compParent.childIds) {\n if (instChildMap.has(compChildId)) continue\n const moved =\n unplacedCopy(graph, context, compChildId, instParent.id) ??\n restoreRemovedCopy(graph, context, compChildId, instParent.id)\n if (moved) {\n graph.insertChildAt(moved.id, instParent.id, instParent.childIds.length)\n instChildMap.set(compChildId, moved)\n usedInstChildIds.add(moved.id)\n context.matched.add(moved.id)\n continue\n }\n const src = graph.nodes.get(compChildId)\n if (!src) continue\n const clone = cloneChildInCoordinates(graph, src, compParent, instParent)\n if (src.childIds.length > 0 && !hasUnplacedCopiesBelow(graph, context, compChildId)) {\n cloneChildrenWithMapping(graph, compChildId, clone.id)\n }\n applyEnclosingAssignments(graph, clone)\n applyBoundPaintColorsIn(graph, clone.id)\n instChildMap.set(compChildId, clone)\n usedInstChildIds.add(clone.id)\n context.matched.add(clone.id)\n }\n for (const childId of instParent.childIds) {\n if (!usedInstChildIds.has(childId)) context.leftovers.add(childId)\n }\n}\n\nexport function syncChildren(\n graph: SceneGraph,\n compParentId: string,\n instParentId: string,\n overrides: InstanceOverrideState,\n context: InstanceSyncContext = createInstanceSyncContext(instParentId, overrides)\n): void {\n // An instance inside its own component would clone the component into itself without end.\n if (isCyclicSync(graph, compParentId, instParentId)) return\n\n const compParent = graph.nodes.get(compParentId)\n const instParent = graph.nodes.get(instParentId)\n if (!compParent || !instParent) return\n\n const instChildMap = new Map<string, SceneNode>()\n const usedInstChildIds = new Set<string>()\n\n // The instance that records overrides of these children is the same for all of them.\n const owner =\n instParent.type === 'INSTANCE'\n ? instParent\n : graph.closest(instParent.id, (node) => node.type === 'INSTANCE')\n\n // Pass 1: Direct matching via a replacement, sourceComponentId, or componentId\n matchLinkedChildren(\n graph,\n instParent,\n instParentId,\n overrides,\n owner,\n compParent,\n instChildMap,\n usedInstChildIds\n )\n\n // Pass 2: Fallback matching for unmatched children (e.g. from Figma imports)\n matchFallbackChildren(\n graph,\n compParent,\n instParent,\n instParentId,\n context,\n instChildMap,\n usedInstChildIds\n )\n\n placeMissingChildren(graph, compParent, instParent, instChildMap, usedInstChildIds, context)\n\n // Pass 4: Synchronize properties and recurse\n for (const compChildId of compParent.childIds) {\n const compChild = graph.nodes.get(compChildId)\n const instChild = instChildMap.get(compChildId)\n if (!compChild || !instChild) continue\n // A replaced layer is the instance's own: nothing of the layer it replaced reaches it, also\n // when it followed that layer here from elsewhere in the component.\n if (replacedLayerIn(owner, instChild.id) !== undefined) continue\n\n const protectedField = childBindingProtection(graph, instChild, overrides)\n const driven = propertyDrivenFields(graph, instChild, compChild)\n const kept = (key: string) =>\n driven.has(key) || isProtectedSyncField(instChild, key, protectedField)\n const componentScale =\n (compChild.componentScale * instParent.componentScale) / compParent.componentScale\n const effectiveSource = sourceWithEffectiveFill(graph, compChild, instChild)\n const source = sourceInTargetCoordinates(effectiveSource, componentScale)\n // Which properties a layer serves is the component's to say; a slot or exposed layer\n // created on the component becomes one in every instance.\n const updates: Partial<SceneNode> = {\n componentScale,\n componentPropertyReferences: structuredClone(compChild.componentPropertyReferences)\n }\n syncBindingFields(instChild, source, updates, protectedField)\n syncVariableModeFields(\n instChild,\n source,\n updates,\n (field) => driven.has(field) || protectedField(field)\n )\n const placement = copySyncedFields(updates, instChild, source, {\n compParent,\n instParent,\n factor: componentScale / compChild.componentScale,\n skip: kept\n })\n Object.assign(updates, assignedFieldValues(graph, instChild, compChild))\n keepOwnContentSize(graph, updates, instChild, source, placement)\n updateSyncedProps(graph, instChild, updates, kept)\n\n if (\n compChild.childIds.length > 0 &&\n !hasNodeInstanceOverride(overrides, instParentId, instChild.id, 'componentId') &&\n // The component's frame is the authority on which slot this is; instance copies of\n // its bindings are not synced.\n !ownsSlotContent(graph, instChild, slotPropertyId(compChild))\n ) {\n syncChildren(graph, compChildId, instChild.id, overrides, context)\n }\n }\n\n // Pass 5: Sort instance children to match component child order\n sortInstanceChildren(\n graph,\n instParent,\n instParentId,\n compParent.childIds,\n overrides,\n instChildMap\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAS,aACP,QACA,KACA,OACM;CACN,OAAO,OAAO;AAChB;AAEA,SAAgB,SACd,QACA,QACA,KACM;CACN,IAAI,QAAQ,SACV,aAAa,QAAQ,KAAK,UAAU,OAAO,KAAK,CAAC;MAC5C,IAAI,QAAQ,WACjB,aAAa,QAAQ,KAAK,YAAY,OAAO,OAAO,CAAC;MAChD,IAAI,QAAQ,WACjB,aAAa,QAAQ,KAAK,YAAY,OAAO,OAAO,CAAC;MAChD,IAAI,QAAQ,aACjB,aAAa,QAAQ,KAAK,cAAc,OAAO,SAAS,CAAC;MACpD,IAAI,QAAQ,kBAAkB;EAEnC,aAAa,QAAQ,KAAK,EAAE,GAAG,OAAO,eAAe,CAAC;EACtD,aAAa,QAAQ,yBAAyB,EAAE,GAAG,OAAO,sBAAsB,CAAC;CACnF,OAAO,IAAI,QAAQ,iBACjB,aAAa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CAAC,GAE5D,aAAa,OAAO,aAAa,UAAU,IAAI,WAAW,OAAO;CAErE;CAGA,qBACE,OACA,YACA,cACA,WAAW,UACX,WACA,YACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-defaults.d.ts","names":[],"sources":["../src/node-defaults.ts"],"mappings":";;iBAYgB,+BAA+B;;iBA6B/B,mBAAmB,MAAM,WAAW;;;;;iBASpC,kBACd,MAAM,KAAK,yDACV,KAAK;;;;;iBASQ,gBAAgB,MAAM;;;;;iBAStB,cAAc,MAAM,UAAU;;;;;;cAajC;;;;;;;;;;;;;;;iBAgBG,kBACd,0BACA,MAAM,UACN,YAAW,QAAQ,aAClB;;
|
|
1
|
+
{"version":3,"file":"node-defaults.d.ts","names":[],"sources":["../src/node-defaults.ts"],"mappings":";;iBAYgB,+BAA+B;;iBA6B/B,mBAAmB,MAAM,WAAW;;;;;iBASpC,kBACd,MAAM,KAAK,yDACV,KAAK;;;;;iBASQ,gBAAgB,MAAM;;;;;iBAStB,cAAc,MAAM,UAAU;;;;;;cAajC;;;;;;;;;;;;;;;iBAgBG,kBACd,0BACA,MAAM,UACN,YAAW,QAAQ,aAClB;;cAoLU,wBAAwB,YAAY;;cAMpC,mBAAmB,YAAY;cAQ/B,iBAAe,IAAA"}
|
package/dist/node-defaults.js
CHANGED
|
@@ -189,6 +189,8 @@ function createDefaultNode(generateId, type, overrides = {}) {
|
|
|
189
189
|
maskType: "ALPHA",
|
|
190
190
|
maskIsOutline: false,
|
|
191
191
|
gridTemplateColumns: EMPTY_LIST,
|
|
192
|
+
gridChildHorizontalAlign: "AUTO",
|
|
193
|
+
gridChildVerticalAlign: "AUTO",
|
|
192
194
|
gridTemplateRows: EMPTY_LIST,
|
|
193
195
|
gridColumnGap: 0,
|
|
194
196
|
gridRowGap: 0,
|
|
@@ -222,6 +224,8 @@ function createDefaultNode(generateId, type, overrides = {}) {
|
|
|
222
224
|
isExposedInstance: false,
|
|
223
225
|
symbolDescription: "",
|
|
224
226
|
symbolLinks: EMPTY_LIST,
|
|
227
|
+
annotations: EMPTY_LIST,
|
|
228
|
+
measurements: EMPTY_LIST,
|
|
225
229
|
variantPropSpecs: EMPTY_LIST,
|
|
226
230
|
boundVariables: EMPTY_RECORD,
|
|
227
231
|
variableBindingScales: EMPTY_RECORD,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-defaults.js","names":[],"sources":["../src/node-defaults.ts"],"sourcesContent":["import {\n BLACK,\n DEFAULT_FONT_FAMILY,\n DEFAULT_STROKE_MITER_LIMIT,\n DEFAULT_STROKE_WEIGHT\n} from './constants'\nimport { normalizeEffects } from './effects'\nimport { EMPTY_LIST, EMPTY_RECORD, shareEmptyNodeValues } from './empty-values'\nimport { EMPTY_INSTANCE_OVERRIDES } from './instances/overrides'\nimport { NO_LETTER_SPACING } from './text/lengths'\nimport type { NodeType, SceneNode, SourceMetadata } from './types'\n\nexport function createDefaultSourceMetadata(): SourceMetadata {\n return {\n format: null,\n id: null,\n orderKey: null,\n editedFields: EMPTY_LIST,\n fig: {\n rawSize: null,\n rawTransform: null,\n rawNodeFields: EMPTY_RECORD,\n layout: null,\n symbolOverrides: EMPTY_LIST,\n componentPropAssignments: EMPTY_LIST,\n derivedSymbolData: EMPTY_LIST,\n derivedSymbolDataLayoutVersion: null,\n uniformScaleFactor: null\n },\n drawio: null\n }\n}\n\n/**\n * Every SceneNode field. Nodes start with all of them, so setting any field later keeps the\n * shape every node shares; a key added after creation turns a JavaScriptCore object into a\n * slower, larger dictionary.\n */\ntype CompleteNodeFields = SceneNode & Record<keyof SceneNode, unknown>\n\n/** Where Figma aligns a new node's strokes: centered on lines and vectors, outside text, else inside. */\nexport function defaultStrokeAlign(type: NodeType): SceneNode['strokeAlign'] {\n if (type === 'LINE' || type === 'VECTOR') return 'CENTER'\n return type === 'TEXT' ? 'OUTSIDE' : 'INSIDE'\n}\n\n/**\n * Weight and alignment a stroke added to `node` takes: its first stroke's, or what the node keeps\n * with none. Adding a stroke from the panel and from the plugin API both go through here.\n */\nexport function newStrokeGeometry(\n node: Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'>\n): Pick<SceneNode['strokes'][number], 'weight' | 'align'> {\n const first = node.strokes.at(0)\n return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }\n}\n\n/**\n * The name a layer of `type` carries when nothing names it, as Figma writes a type's name: words\n * of a compound type apart, so a shape with text is a \"Shape with text\".\n */\nexport function defaultNodeName(type: NodeType): string {\n const words = type.toLowerCase().replaceAll('_', ' ')\n return words.charAt(0).toUpperCase() + words.slice(1)\n}\n\n/**\n * The name Figma gives a layer that follows its text: the characters trimmed, on one line, and\n * the type's own name while they hold nothing.\n */\nexport function textLayerName(type: NodeType, text: string): string {\n const lines = text\n .split(/\\r\\n|\\r|\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== '')\n return lines.join(' ') || defaultNodeName(type)\n}\n\n/**\n * The fields auto layout sets on the frame that holds it, with the value each holds when no frame\n * lays anything out. A page holds layers; it is not one, so none of these apply to it and a page\n * that took them would place its layers by a container nobody can see.\n */\nexport const FRAME_LAYOUT_DEFAULTS = {\n layoutMode: 'NONE',\n layoutDirection: 'AUTO',\n layoutWrap: 'NO_WRAP',\n primaryAxisAlign: 'MIN',\n counterAxisAlign: 'MIN',\n primaryAxisSizing: 'FIXED',\n counterAxisSizing: 'FIXED',\n itemSpacing: 0,\n counterAxisSpacing: 0,\n paddingTop: 0,\n paddingRight: 0,\n paddingBottom: 0,\n paddingLeft: 0\n} as const satisfies Partial<SceneNode>\n\nexport function createDefaultNode(\n generateId: () => string,\n type: NodeType,\n overrides: Partial<SceneNode> = {}\n): SceneNode {\n // A literal ending in a spread is built one field at a time, and V8 keeps an object given this\n // many fields that way in dictionary mode, about 3 KB more per layer; a spread copy of a\n // finished literal keeps fast fields, in JavaScriptCore as well.\n const defaults = {\n id: generateId(),\n type,\n name: type.charAt(0) + type.slice(1).toLowerCase(),\n parentId: null,\n childIds: [],\n x: 0,\n y: 0,\n width: 100,\n height: 100,\n rotation: 0,\n source: createDefaultSourceMetadata(),\n derivedLayout: null,\n fills:\n type === 'TEXT'\n ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }]\n : EMPTY_LIST,\n strokes: EMPTY_LIST,\n effects: EMPTY_LIST,\n layoutGrids: EMPTY_LIST,\n guides: EMPTY_LIST,\n fillStyleId: null,\n strokeStyleId: null,\n textStyleId: null,\n effectStyleId: null,\n gridStyleId: null,\n sharedStyleType: null,\n opacity: 1,\n cornerRadius: 0,\n topLeftRadius: 0,\n topRightRadius: 0,\n bottomRightRadius: 0,\n bottomLeftRadius: 0,\n independentCorners: false,\n cornerSmoothing: 0,\n visible: true,\n locked: false,\n clipsContent: false,\n overflowDirection: 'NONE',\n scrollBehavior: 'SCROLLS',\n text: '',\n fontSize: 14,\n fontFamily: DEFAULT_FONT_FAMILY,\n fontWeight: 400,\n italic: false,\n fontStyle: null,\n textAlignHorizontal: 'LEFT',\n textDirection: 'AUTO',\n textLanguage: null,\n leadingTrim: 'NONE',\n lineHeight: null,\n letterSpacing: NO_LETTER_SPACING,\n ...FRAME_LAYOUT_DEFAULTS,\n blendMode: 'PASS_THROUGH',\n layoutPositioning: 'AUTO',\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO',\n vectorNetwork: null,\n handleMirroring: 'NONE',\n fillGeometry: EMPTY_LIST,\n strokeGeometry: EMPTY_LIST,\n arcData: null,\n textAlignVertical: 'TOP',\n textAutoResize: 'NONE',\n textCase: 'ORIGINAL',\n textDecoration: 'NONE',\n textDecorationStyle: 'SOLID',\n textDecorationThickness: null,\n textDecorationFills: EMPTY_LIST,\n textDecorationSkipInk: true,\n textUnderlineOffset: null,\n maxLines: null,\n textParagraphs: EMPTY_LIST,\n listSpacing: 0,\n paragraphSpacing: 0,\n paragraphIndent: 0,\n hangingList: false,\n styleRuns: EMPTY_LIST,\n fontVariations: EMPTY_LIST,\n opticalSizeFromFontSize: true,\n fontFeatures: EMPTY_LIST,\n horizontalConstraint: 'MIN',\n verticalConstraint: 'MIN',\n strokeCap: 'NONE',\n strokeJoin: 'MITER',\n dashPattern: EMPTY_LIST,\n borderTopWeight: 0,\n borderRightWeight: 0,\n borderBottomWeight: 0,\n borderLeftWeight: 0,\n independentStrokeWeights: false,\n strokeWeight: DEFAULT_STROKE_WEIGHT,\n strokeAlign: defaultStrokeAlign(type),\n strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,\n minWidth: null,\n maxWidth: null,\n minHeight: null,\n maxHeight: null,\n targetAspectRatio: null,\n connectorStart: null,\n connectorEnd: null,\n connectorLineType: 'ELBOWED',\n connectorStartCap: 'ROUND',\n connectorEndCap: 'ARROW_LINES',\n connectorControlPoints: EMPTY_LIST,\n connectorCurveHandles: null,\n connectorLabelPosition: null,\n isMask: false,\n maskType: 'ALPHA',\n maskIsOutline: false,\n gridTemplateColumns: EMPTY_LIST,\n gridTemplateRows: EMPTY_LIST,\n gridColumnGap: 0,\n gridRowGap: 0,\n gridPosition: null,\n counterAxisAlignContent: 'AUTO',\n itemReverseZIndex: false,\n strokesIncludedInLayout: false,\n expanded: true,\n textTruncation: 'DISABLED',\n autoRename: true,\n pointCount: 5,\n starInnerRadius: 0.38,\n shapeWithTextType: 'SQUARE',\n shapeUserHeight: 0,\n shapeTruncates: false,\n componentId: null,\n instanceOverrides: EMPTY_INSTANCE_OVERRIDES,\n componentPropertyDefinitions: EMPTY_LIST,\n componentPropertyReferences: EMPTY_LIST,\n componentPropertyAssignments: EMPTY_RECORD,\n componentPropertyValues: EMPTY_RECORD,\n componentKey: null,\n sourceLibraryKey: null,\n publishId: null,\n overrideKey: null,\n sharedSymbolVersion: null,\n publishedVersion: null,\n librarySource: null,\n isPublishable: false,\n isSymbolPublishable: false,\n isExposedInstance: false,\n symbolDescription: '',\n symbolLinks: EMPTY_LIST,\n variantPropSpecs: EMPTY_LIST,\n boundVariables: EMPTY_RECORD,\n variableBindingScales: EMPTY_RECORD,\n variableAssignmentScales: EMPTY_RECORD,\n componentScale: 1,\n variableModes: EMPTY_RECORD,\n exportSettings: EMPTY_LIST,\n status: null,\n pluginData: EMPTY_LIST,\n pluginRelaunchData: EMPTY_LIST,\n prototypeReactions: EMPTY_LIST,\n internalOnly: false,\n flipX: false,\n flipY: false,\n textPicture: null,\n derivedTextGlyphs: null,\n derivedTextHeight: null,\n textPathData: null,\n textPathBox: null,\n booleanOperation: undefined\n } satisfies CompleteNodeFields\n const node: SceneNode = { ...defaults, ...overrides }\n node.effects = normalizeEffects(node.effects)\n shareEmptyNodeValues(node, Object.keys(overrides))\n return node\n}\n\n/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */\nexport const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\n/** Layers whose stroke can take a weight per side, as Figma's `strokeTopWeight` and its siblings. */\nexport const SIDE_STROKE_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'RECTANGLE',\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\nexport const CONTAINER_TYPES = new Set<NodeType>([\n 'CANVAS',\n 'FRAME',\n 'GROUP',\n 'BOOLEAN_OPERATION',\n 'SECTION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n"],"mappings":";;;;;;AAYA,SAAgB,8BAA8C;CAC5D,OAAO;EACL,QAAQ;EACR,IAAI;EACJ,UAAU;EACV,cAAc;EACd,KAAK;GACH,SAAS;GACT,cAAc;GACd,eAAe;GACf,QAAQ;GACR,iBAAiB;GACjB,0BAA0B;GAC1B,mBAAmB;GACnB,gCAAgC;GAChC,oBAAoB;EACtB;EACA,QAAQ;CACV;AACF;;AAUA,SAAgB,mBAAmB,MAA0C;CAC3E,IAAI,SAAS,UAAU,SAAS,UAAU,OAAO;CACjD,OAAO,SAAS,SAAS,YAAY;AACvC;;;;;AAMA,S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ACnB,iBAAiB;EACjB,gBAAgB;EAChB,aAAa;EACb,mBAAmB;EACnB,8BAA8B;EAC9B,6BAA6B;EAC7B,8BAA8B;EAC9B,yBAAyB;EACzB,cAAc;EACd,kBAAkB;EAClB,WAAW;EACX,aAAa;EACb,qBAAqB;EACrB,kBAAkB;EAClB,eAAe;EACf,eAAe;EACf,qBAAqB;EACrB,mBAAmB;EACnB,mBAAmB;EACnB,aAAa;EACb,kBAAkB;EAClB,gBAAgB;EAChB,uBAAuB;EACvB,0BAA0B;EAC1B,gBAAgB;EAChB,eAAe;EACf,gBAAgB;EAChB,QAAQ;EACR,YAAY;EACZ,oBAAoB;EACpB,oBAAoB;EACpB,cAAc;EACd,OAAO;EACP,OAAO;EACP,aAAa;EACb,mBAAmB;EACnB,mBAAmB;EACnB,cAAc;EACd,aAAa;EACb,kBAAkB,KAAA;EAEmB,GAAG;CAAU;CACpD,KAAK,UAAU,iBAAiB,KAAK,OAAO;CAC5C,qBAAqB,MAAM,OAAO,KAAK,SAAS,CAAC;CACjD,OAAO;AACT;;AAGA,MAAa,yCAAgD,IAAI,IAAc,CAC7E,SACA,mBACF,CAAC;;AAGD,MAAa,oCAA2C,IAAI,IAAc;CACxE;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkB,IAAI,IAAc;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"node-defaults.js","names":[],"sources":["../src/node-defaults.ts"],"sourcesContent":["import {\n BLACK,\n DEFAULT_FONT_FAMILY,\n DEFAULT_STROKE_MITER_LIMIT,\n DEFAULT_STROKE_WEIGHT\n} from './constants'\nimport { normalizeEffects } from './effects'\nimport { EMPTY_LIST, EMPTY_RECORD, shareEmptyNodeValues } from './empty-values'\nimport { EMPTY_INSTANCE_OVERRIDES } from './instances/overrides'\nimport { NO_LETTER_SPACING } from './text/lengths'\nimport type { NodeType, SceneNode, SourceMetadata } from './types'\n\nexport function createDefaultSourceMetadata(): SourceMetadata {\n return {\n format: null,\n id: null,\n orderKey: null,\n editedFields: EMPTY_LIST,\n fig: {\n rawSize: null,\n rawTransform: null,\n rawNodeFields: EMPTY_RECORD,\n layout: null,\n symbolOverrides: EMPTY_LIST,\n componentPropAssignments: EMPTY_LIST,\n derivedSymbolData: EMPTY_LIST,\n derivedSymbolDataLayoutVersion: null,\n uniformScaleFactor: null\n },\n drawio: null\n }\n}\n\n/**\n * Every SceneNode field. Nodes start with all of them, so setting any field later keeps the\n * shape every node shares; a key added after creation turns a JavaScriptCore object into a\n * slower, larger dictionary.\n */\ntype CompleteNodeFields = SceneNode & Record<keyof SceneNode, unknown>\n\n/** Where Figma aligns a new node's strokes: centered on lines and vectors, outside text, else inside. */\nexport function defaultStrokeAlign(type: NodeType): SceneNode['strokeAlign'] {\n if (type === 'LINE' || type === 'VECTOR') return 'CENTER'\n return type === 'TEXT' ? 'OUTSIDE' : 'INSIDE'\n}\n\n/**\n * Weight and alignment a stroke added to `node` takes: its first stroke's, or what the node keeps\n * with none. Adding a stroke from the panel and from the plugin API both go through here.\n */\nexport function newStrokeGeometry(\n node: Pick<SceneNode, 'strokes' | 'strokeWeight' | 'strokeAlign'>\n): Pick<SceneNode['strokes'][number], 'weight' | 'align'> {\n const first = node.strokes.at(0)\n return { weight: first?.weight ?? node.strokeWeight, align: first?.align ?? node.strokeAlign }\n}\n\n/**\n * The name a layer of `type` carries when nothing names it, as Figma writes a type's name: words\n * of a compound type apart, so a shape with text is a \"Shape with text\".\n */\nexport function defaultNodeName(type: NodeType): string {\n const words = type.toLowerCase().replaceAll('_', ' ')\n return words.charAt(0).toUpperCase() + words.slice(1)\n}\n\n/**\n * The name Figma gives a layer that follows its text: the characters trimmed, on one line, and\n * the type's own name while they hold nothing.\n */\nexport function textLayerName(type: NodeType, text: string): string {\n const lines = text\n .split(/\\r\\n|\\r|\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== '')\n return lines.join(' ') || defaultNodeName(type)\n}\n\n/**\n * The fields auto layout sets on the frame that holds it, with the value each holds when no frame\n * lays anything out. A page holds layers; it is not one, so none of these apply to it and a page\n * that took them would place its layers by a container nobody can see.\n */\nexport const FRAME_LAYOUT_DEFAULTS = {\n layoutMode: 'NONE',\n layoutDirection: 'AUTO',\n layoutWrap: 'NO_WRAP',\n primaryAxisAlign: 'MIN',\n counterAxisAlign: 'MIN',\n primaryAxisSizing: 'FIXED',\n counterAxisSizing: 'FIXED',\n itemSpacing: 0,\n counterAxisSpacing: 0,\n paddingTop: 0,\n paddingRight: 0,\n paddingBottom: 0,\n paddingLeft: 0\n} as const satisfies Partial<SceneNode>\n\nexport function createDefaultNode(\n generateId: () => string,\n type: NodeType,\n overrides: Partial<SceneNode> = {}\n): SceneNode {\n // A literal ending in a spread is built one field at a time, and V8 keeps an object given this\n // many fields that way in dictionary mode, about 3 KB more per layer; a spread copy of a\n // finished literal keeps fast fields, in JavaScriptCore as well.\n const defaults = {\n id: generateId(),\n type,\n name: type.charAt(0) + type.slice(1).toLowerCase(),\n parentId: null,\n childIds: [],\n x: 0,\n y: 0,\n width: 100,\n height: 100,\n rotation: 0,\n source: createDefaultSourceMetadata(),\n derivedLayout: null,\n fills:\n type === 'TEXT'\n ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }]\n : EMPTY_LIST,\n strokes: EMPTY_LIST,\n effects: EMPTY_LIST,\n layoutGrids: EMPTY_LIST,\n guides: EMPTY_LIST,\n fillStyleId: null,\n strokeStyleId: null,\n textStyleId: null,\n effectStyleId: null,\n gridStyleId: null,\n sharedStyleType: null,\n opacity: 1,\n cornerRadius: 0,\n topLeftRadius: 0,\n topRightRadius: 0,\n bottomRightRadius: 0,\n bottomLeftRadius: 0,\n independentCorners: false,\n cornerSmoothing: 0,\n visible: true,\n locked: false,\n clipsContent: false,\n overflowDirection: 'NONE',\n scrollBehavior: 'SCROLLS',\n text: '',\n fontSize: 14,\n fontFamily: DEFAULT_FONT_FAMILY,\n fontWeight: 400,\n italic: false,\n fontStyle: null,\n textAlignHorizontal: 'LEFT',\n textDirection: 'AUTO',\n textLanguage: null,\n leadingTrim: 'NONE',\n lineHeight: null,\n letterSpacing: NO_LETTER_SPACING,\n ...FRAME_LAYOUT_DEFAULTS,\n blendMode: 'PASS_THROUGH',\n layoutPositioning: 'AUTO',\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO',\n vectorNetwork: null,\n handleMirroring: 'NONE',\n fillGeometry: EMPTY_LIST,\n strokeGeometry: EMPTY_LIST,\n arcData: null,\n textAlignVertical: 'TOP',\n textAutoResize: 'NONE',\n textCase: 'ORIGINAL',\n textDecoration: 'NONE',\n textDecorationStyle: 'SOLID',\n textDecorationThickness: null,\n textDecorationFills: EMPTY_LIST,\n textDecorationSkipInk: true,\n textUnderlineOffset: null,\n maxLines: null,\n textParagraphs: EMPTY_LIST,\n listSpacing: 0,\n paragraphSpacing: 0,\n paragraphIndent: 0,\n hangingList: false,\n styleRuns: EMPTY_LIST,\n fontVariations: EMPTY_LIST,\n opticalSizeFromFontSize: true,\n fontFeatures: EMPTY_LIST,\n horizontalConstraint: 'MIN',\n verticalConstraint: 'MIN',\n strokeCap: 'NONE',\n strokeJoin: 'MITER',\n dashPattern: EMPTY_LIST,\n borderTopWeight: 0,\n borderRightWeight: 0,\n borderBottomWeight: 0,\n borderLeftWeight: 0,\n independentStrokeWeights: false,\n strokeWeight: DEFAULT_STROKE_WEIGHT,\n strokeAlign: defaultStrokeAlign(type),\n strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,\n minWidth: null,\n maxWidth: null,\n minHeight: null,\n maxHeight: null,\n targetAspectRatio: null,\n connectorStart: null,\n connectorEnd: null,\n connectorLineType: 'ELBOWED',\n connectorStartCap: 'ROUND',\n connectorEndCap: 'ARROW_LINES',\n connectorControlPoints: EMPTY_LIST,\n connectorCurveHandles: null,\n connectorLabelPosition: null,\n isMask: false,\n maskType: 'ALPHA',\n maskIsOutline: false,\n gridTemplateColumns: EMPTY_LIST,\n gridChildHorizontalAlign: 'AUTO',\n gridChildVerticalAlign: 'AUTO',\n gridTemplateRows: EMPTY_LIST,\n gridColumnGap: 0,\n gridRowGap: 0,\n gridPosition: null,\n counterAxisAlignContent: 'AUTO',\n itemReverseZIndex: false,\n strokesIncludedInLayout: false,\n expanded: true,\n textTruncation: 'DISABLED',\n autoRename: true,\n pointCount: 5,\n starInnerRadius: 0.38,\n shapeWithTextType: 'SQUARE',\n shapeUserHeight: 0,\n shapeTruncates: false,\n componentId: null,\n instanceOverrides: EMPTY_INSTANCE_OVERRIDES,\n componentPropertyDefinitions: EMPTY_LIST,\n componentPropertyReferences: EMPTY_LIST,\n componentPropertyAssignments: EMPTY_RECORD,\n componentPropertyValues: EMPTY_RECORD,\n componentKey: null,\n sourceLibraryKey: null,\n publishId: null,\n overrideKey: null,\n sharedSymbolVersion: null,\n publishedVersion: null,\n librarySource: null,\n isPublishable: false,\n isSymbolPublishable: false,\n isExposedInstance: false,\n symbolDescription: '',\n symbolLinks: EMPTY_LIST,\n annotations: EMPTY_LIST,\n measurements: EMPTY_LIST,\n variantPropSpecs: EMPTY_LIST,\n boundVariables: EMPTY_RECORD,\n variableBindingScales: EMPTY_RECORD,\n variableAssignmentScales: EMPTY_RECORD,\n componentScale: 1,\n variableModes: EMPTY_RECORD,\n exportSettings: EMPTY_LIST,\n status: null,\n pluginData: EMPTY_LIST,\n pluginRelaunchData: EMPTY_LIST,\n prototypeReactions: EMPTY_LIST,\n internalOnly: false,\n flipX: false,\n flipY: false,\n textPicture: null,\n derivedTextGlyphs: null,\n derivedTextHeight: null,\n textPathData: null,\n textPathBox: null,\n booleanOperation: undefined\n } satisfies CompleteNodeFields\n const node: SceneNode = { ...defaults, ...overrides }\n node.effects = normalizeEffects(node.effects)\n shareEmptyNodeValues(node, Object.keys(overrides))\n return node\n}\n\n/** Containers whose bounds follow their children and that set no coordinate space, as in Figma. */\nexport const FITTED_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\n/** Layers whose stroke can take a weight per side, as Figma's `strokeTopWeight` and its siblings. */\nexport const SIDE_STROKE_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([\n 'RECTANGLE',\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\nexport const CONTAINER_TYPES = new Set<NodeType>([\n 'CANVAS',\n 'FRAME',\n 'GROUP',\n 'BOOLEAN_OPERATION',\n 'SECTION',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n"],"mappings":";;;;;;AAYA,SAAgB,8BAA8C;CAC5D,OAAO;EACL,QAAQ;EACR,IAAI;EACJ,UAAU;EACV,cAAc;EACd,KAAK;GACH,SAAS;GACT,cAAc;GACd,eAAe;GACf,QAAQ;GACR,iBAAiB;GACjB,0BAA0B;GAC1B,mBAAmB;GACnB,gCAAgC;GAChC,oBAAoB;EACtB;EACA,QAAQ;CACV;AACF;;AAUA,SAAgB,mBAAmB,MAA0C;CAC3E,IAAI,SAAS,UAAU,SAAS,UAAU,OAAO;CACjD,OAAO,SAAS,SAAS,YAAY;AACvC;;;;;AAMA,SAAgB,kBACd,MACwD;CACxD,MAAM,QAAQ,KAAK,QAAQ,GAAG,CAAC;CAC/B,OAAO;EAAE,QAAQ,OAAO,UAAU,KAAK;EAAc,OAAO,OAAO,SAAS,KAAK;CAAY;AAC/F;;;;;AAMA,SAAgB,gBAAgB,MAAwB;CACtD,MAAM,QAAQ,KAAK,YAAY,CAAC,CAAC,WAAW,KAAK,GAAG;CACpD,OAAO,MAAM,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,MAAM,MAAM,CAAC;AACtD;;;;;AAMA,SAAgB,cAAc,MAAgB,MAAsB;CAKlE,OAJc,KACX,MAAM,YAAY,CAAC,CACnB,KAAK,SAAS,KAAK,KAAK,CAAC,CAAC,CAC1B,QAAQ,SAAS,SAAS,EAClB,CAAC,CAAC,KAAK,GAAG,KAAK,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;EACP,aAAa;EACb,mBAAmB;EACnB,mBAAmB;EACnB,cAAc;EACd,aAAa;EACb,kBAAkB,KAAA;EAEmB,GAAG;CAAU;CACpD,KAAK,UAAU,iBAAiB,KAAK,OAAO;CAC5C,qBAAqB,MAAM,OAAO,KAAK,SAAS,CAAC;CACjD,OAAO;AACT;;AAGA,MAAa,yCAAgD,IAAI,IAAc,CAC7E,SACA,mBACF,CAAC;;AAGD,MAAa,oCAA2C,IAAI,IAAc;CACxE;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,kCAAkB,IAAI,IAAc;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
package/dist/resize.d.ts
CHANGED
|
@@ -18,7 +18,14 @@ type ConstrainedRect = Rect & {
|
|
|
18
18
|
};
|
|
19
19
|
/** Keep a placed box's constrained edges or center when its content determines its size. */
|
|
20
20
|
declare function resizedChildRect(placed: Rect, size: Pick<Rect, 'width' | 'height'>, horizontal: ConstraintType, vertical: ConstraintType): Rect;
|
|
21
|
-
|
|
21
|
+
/** The limits a layer's own size fields put on an automatic resize. */
|
|
22
|
+
interface ConstraintLimits {
|
|
23
|
+
minWidth?: number | null;
|
|
24
|
+
maxWidth?: number | null;
|
|
25
|
+
minHeight?: number | null;
|
|
26
|
+
maxHeight?: number | null;
|
|
27
|
+
}
|
|
28
|
+
type ChildRectPlacer = (child: Rect, parentBefore: Pick<Rect, 'width' | 'height'>, parentAfter: Pick<Rect, 'width' | 'height'>, horizontal: ConstraintType, vertical: ConstraintType, aspectRatio?: number | null, limits?: ConstraintLimits) => ConstrainedRect;
|
|
22
29
|
/**
|
|
23
30
|
* A child's box after its parent is resized, by a handle or `resize()`, keeping a locked aspect
|
|
24
31
|
* ratio as Figma does.
|
|
@@ -60,5 +67,5 @@ declare function collectResizeDescendants(graph: ResizeGraph, rootId: string): M
|
|
|
60
67
|
declare function flipChanges(from: Pick<SceneNode, 'flipX' | 'flipY'>, current: Pick<SceneNode, 'flipX' | 'flipY'>, flipsX?: boolean, flipsY?: boolean): Partial<Pick<SceneNode, 'flipX' | 'flipY'>>;
|
|
61
68
|
declare function computeConstrainedResizeChanges(graph: ResizeGraph, rootId: string, rootBefore: Pick<Rect, 'width' | 'height'>, rootAfter: Pick<Rect, 'width' | 'height'>, originals: ReadonlyMap<string, ResizeSnapshot>): Map<string, Partial<SceneNode>>;
|
|
62
69
|
//#endregion
|
|
63
|
-
export { ConstrainedRect, ResizeSnapshot, collectResizeDescendants, computeConstrainedResizeChanges, constrainedChildRect, createResizeSnapshot, flipChanges, layoutConstrainedChildRect, resizedChildRect, scaleVectorNetworkForResize, scaledChildRect, scaledGeometryChanges, scaledPathTextChanges, shapeGeometryChanges };
|
|
70
|
+
export { ConstrainedRect, ConstraintLimits, ResizeSnapshot, collectResizeDescendants, computeConstrainedResizeChanges, constrainedChildRect, createResizeSnapshot, flipChanges, layoutConstrainedChildRect, resizedChildRect, scaleVectorNetworkForResize, scaledChildRect, scaledGeometryChanges, scaledPathTextChanges, shapeGeometryChanges };
|
|
64
71
|
//# sourceMappingURL=resize.d.ts.map
|
package/dist/resize.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resize.d.ts","names":[],"sources":["../src/resize.ts"],"mappings":";;;;;;;;;KAmBY,iBAAiB,KAC3B;UAiBQ;EACR,QAAQ,aAAa;;;KAeX,kBAAkB;EAAS;EAAkB;;;iBAyDzC,iBACd,QAAQ,MACR,MAAM,KAAK,2BACX,YAAY,gBACZ,UAAU,iBACT;
|
|
1
|
+
{"version":3,"file":"resize.d.ts","names":[],"sources":["../src/resize.ts"],"mappings":";;;;;;;;;KAmBY,iBAAiB,KAC3B;UAiBQ;EACR,QAAQ,aAAa;;;KAeX,kBAAkB;EAAS;EAAkB;;;iBAyDzC,iBACd,QAAQ,MACR,MAAM,KAAK,2BACX,YAAY,gBACZ,UAAU,iBACT;;UAyBc;EACf;EACA;EACA;EACA;;KAGG,mBACH,OAAO,MACP,cAAc,KAAK,2BACnB,aAAa,KAAK,2BAClB,YAAY,gBACZ,UAAU,gBACV,6BACA,SAAS,qBACN;;;;;cAmEQ,sBAAoB;;;;;;cAOpB,4BAA0B;iBAEvB,gBACd,OAAO,MACP,cAAc,KAAK,2BACnB,aAAa,KAAK,4BACjB;iBAIa,4BACd,eAAe,sBACf,uBACA,wBACA,eACA,iBACC;;iBA8Ba,qBAAqB,MAAM,YAAY;;;;;;;iBAoDvC,sBACd,MAAM,KACJ,kJAUF,mBACA,oBACA,eACA,iBACC,QAAQ;;;;;;;;iBA0CK,qBACd,MAAM,WACN,eACA,iBACC,KAAK,QAAQ;KAkBX,iBAAiB,KAAK;;iBAGX,sBACd,MAAM,gBACN,YACA,aACC,KAAK,QAAQ;iBAmBA,yBACd,OAAO,aACP,iBACC,YAAY;;;;;iBAwBC,YACd,MAAM,KAAK,+BACX,SAAS,KAAK,+BACd,kBACA,mBACC,QAAQ,KAAK;iBASA,gCACd,OAAO,aACP,gBACA,YAAY,KAAK,2BACjB,WAAW,KAAK,2BAChB,WAAW,oBAAoB,kBAC9B,YAAY,QAAQ"}
|
package/dist/resize.js
CHANGED
|
@@ -114,18 +114,30 @@ function keepLockedRatio(x, y, horizontal, vertical, aspectRatio) {
|
|
|
114
114
|
y
|
|
115
115
|
};
|
|
116
116
|
}
|
|
117
|
+
/** A placed axis stopped at the layer's own min or max, its constraint's edge kept in place. */
|
|
118
|
+
function limitedAxis(placed, constraint, min, max) {
|
|
119
|
+
const size = Math.min(max ?? Infinity, Math.max(min ?? -Infinity, placed.size));
|
|
120
|
+
if (size === placed.size) return placed;
|
|
121
|
+
const limited = resizedInPlace(placed, size, constraint);
|
|
122
|
+
return placed.flipped ? {
|
|
123
|
+
...limited,
|
|
124
|
+
flipped: true
|
|
125
|
+
} : limited;
|
|
126
|
+
}
|
|
117
127
|
/** Places a child by its constraints, snapping a scaled position to `scaleStep` when it is set. */
|
|
118
128
|
function childRectPlacer(scaleStep, allowFlips = true) {
|
|
119
|
-
return (child, parentBefore, parentAfter, horizontal, vertical, aspectRatio = null) => {
|
|
129
|
+
return (child, parentBefore, parentAfter, horizontal, vertical, aspectRatio = null, limits = {}) => {
|
|
120
130
|
const { x, y } = keepLockedRatio(constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal, scaleStep, allowFlips), constrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical, scaleStep, allowFlips), horizontal, vertical, aspectRatio);
|
|
131
|
+
const limitedX = limitedAxis(x, horizontal, limits.minWidth, limits.maxWidth);
|
|
132
|
+
const limitedY = limitedAxis(y, vertical, limits.minHeight, limits.maxHeight);
|
|
121
133
|
const rect = {
|
|
122
|
-
x:
|
|
123
|
-
y:
|
|
124
|
-
width:
|
|
125
|
-
height:
|
|
134
|
+
x: limitedX.position,
|
|
135
|
+
y: limitedY.position,
|
|
136
|
+
width: limitedX.size,
|
|
137
|
+
height: limitedY.size
|
|
126
138
|
};
|
|
127
|
-
if (
|
|
128
|
-
if (
|
|
139
|
+
if (limitedX.flipped) rect.flipsX = true;
|
|
140
|
+
if (limitedY.flipped) rect.flipsY = true;
|
|
129
141
|
return rect;
|
|
130
142
|
};
|
|
131
143
|
}
|
|
@@ -305,7 +317,7 @@ function computeConstrainedResizeChanges(graph, rootId, rootBefore, rootAfter, o
|
|
|
305
317
|
compute(childId, original, child);
|
|
306
318
|
continue;
|
|
307
319
|
}
|
|
308
|
-
const { flipsX, flipsY, ...box } = scalesChildren ? scaledChildRect(original, parentBefore, parentAfter) : constrainedChildRect(original, parentBefore, parentAfter, child.horizontalConstraint, child.verticalConstraint, enforcedAspectRatio(child));
|
|
320
|
+
const { flipsX, flipsY, ...box } = scalesChildren ? scaledChildRect(original, parentBefore, parentAfter) : constrainedChildRect(original, parentBefore, parentAfter, child.horizontalConstraint, child.verticalConstraint, enforcedAspectRatio(child), child);
|
|
309
321
|
const childChanges = {
|
|
310
322
|
...box,
|
|
311
323
|
...flipChanges(original, child, flipsX, flipsY),
|
package/dist/resize.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resize.js","names":[],"sources":["../src/resize.ts"],"sourcesContent":["import {\n copyDerivedGlyphs,\n copyGeometryPaths,\n copyStroke,\n copyStrokes,\n scaleGeometryPaths\n} from './copy'\nimport { enforcedAspectRatio } from './layout/aspect-ratio'\nimport type { Rect } from './primitives'\nimport { followsPath } from './text/path'\nimport type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'\nimport { cloneVectorNetwork } from './vector-network'\n\n/**\n * Drag-start state a live resize re-scales from. Path text needs more than the\n * layout rect: its OUTSIDE stroke silhouettes and glyph outlines are baked\n * geometry that must scale with the node, and textPathBox is the layout box the\n * glyphs were reflowed against.\n */\nexport type ResizeSnapshot = Pick<\n SceneNode,\n | 'type'\n | 'x'\n | 'y'\n | 'width'\n | 'height'\n | 'flipX'\n | 'flipY'\n | 'vectorNetwork'\n | 'fillGeometry'\n | 'strokeGeometry'\n | 'derivedTextGlyphs'\n | 'strokes'\n | 'textPathData'\n | 'textPathBox'\n>\n\ninterface ResizeGraph {\n getNode(id: string): SceneNode | undefined\n}\n\nconst CONSTRAINT_CONTAINER_TYPES = new Set([\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE',\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\ntype AxisPlacement = { position: number; size: number; flipped?: boolean }\n\n/** A child's box after its parent resizes, and the axes on which it turned over. */\nexport type ConstrainedRect = Rect & { flipsX?: boolean; flipsY?: boolean }\n\n/**\n * Where a constraint places a child on one axis when its parent goes from `parentBefore` to\n * `parentAfter`, as Figma does: Right and Left & right move or grow it by the change in the\n * parent's size rounded to whole pixels, Center by the change in its rounded half, and Scale by\n * the exact ratio. The child's own box is never rounded, so a resize to the same size changes\n * nothing. Left & right that would leave no size keeps the axis as it was; past zero, the child\n * turns over and its box runs back from the edge it was pinned to, as the layer is mirrored in\n * Figma. `scaleStep` snaps a scaled position to that fraction of a pixel.\n */\nfunction constrainedAxis(\n position: number,\n size: number,\n parentBefore: number,\n parentAfter: number,\n constraint: ConstraintType,\n scaleStep = 0,\n allowFlips = true\n): AxisPlacement {\n const delta = Math.round(parentAfter) - Math.round(parentBefore)\n if (constraint === 'MAX') return { position: position + delta, size }\n if (constraint === 'CENTER') {\n return { position: position + Math.round(parentAfter / 2) - Math.round(parentBefore / 2), size }\n }\n if (constraint === 'STRETCH') {\n const stretched = size + delta\n if (!allowFlips) return { position, size: Math.abs(stretched) }\n if (stretched === 0) return { position, size }\n if (stretched > 0) return { position, size: stretched }\n return { position: position + stretched, size: -stretched, flipped: true }\n }\n if (constraint === 'SCALE' && parentBefore > 0) {\n const scale = parentAfter / parentBefore\n const scaled = position * scale\n return {\n position: scaleStep > 0 ? Math.round(scaled / scaleStep) * scaleStep : scaled,\n size: size * scale\n }\n }\n return { position, size }\n}\n\nconst FLEXIBLE_CONSTRAINTS: ReadonlySet<ConstraintType> = new Set(['STRETCH', 'SCALE'])\n\n/** The axis at `size`, keeping the edge or centre its constraint pins where it was placed. */\nfunction resizedInPlace(\n placed: AxisPlacement,\n size: number,\n constraint: ConstraintType\n): AxisPlacement {\n if (constraint === 'MAX') return { position: placed.position + placed.size - size, size }\n if (constraint === 'CENTER') return { position: placed.position + (placed.size - size) / 2, size }\n return { position: placed.position, size }\n}\n\n/** Keep a placed box's constrained edges or center when its content determines its size. */\nexport function resizedChildRect(\n placed: Rect,\n size: Pick<Rect, 'width' | 'height'>,\n horizontal: ConstraintType,\n vertical: ConstraintType\n): Rect {\n const x = resizedInPlace({ position: placed.x, size: placed.width }, size.width, horizontal)\n const y = resizedInPlace({ position: placed.y, size: placed.height }, size.height, vertical)\n return { x: x.position, y: y.position, width: x.size, height: y.size }\n}\n\n/**\n * A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis\n * sizes the other. With both axes following the parent, or neither, the ratio gives way.\n */\nfunction keepLockedRatio(\n x: AxisPlacement,\n y: AxisPlacement,\n horizontal: ConstraintType,\n vertical: ConstraintType,\n aspectRatio: number | null\n): { x: AxisPlacement; y: AxisPlacement } {\n const flexibleX = FLEXIBLE_CONSTRAINTS.has(horizontal)\n if (aspectRatio === null || flexibleX === FLEXIBLE_CONSTRAINTS.has(vertical)) return { x, y }\n return flexibleX\n ? { x, y: resizedInPlace(y, x.size / aspectRatio, vertical) }\n : { x: resizedInPlace(x, y.size * aspectRatio, horizontal), y }\n}\n\ntype ChildRectPlacer = (\n child: Rect,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>,\n horizontal: ConstraintType,\n vertical: ConstraintType,\n aspectRatio?: number | null\n) => ConstrainedRect\n\n/** Places a child by its constraints, snapping a scaled position to `scaleStep` when it is set. */\nfunction childRectPlacer(scaleStep: number, allowFlips = true): ChildRectPlacer {\n return (child, parentBefore, parentAfter, horizontal, vertical, aspectRatio = null) => {\n const { x, y } = keepLockedRatio(\n constrainedAxis(\n child.x,\n child.width,\n parentBefore.width,\n parentAfter.width,\n horizontal,\n scaleStep,\n allowFlips\n ),\n constrainedAxis(\n child.y,\n child.height,\n parentBefore.height,\n parentAfter.height,\n vertical,\n scaleStep,\n allowFlips\n ),\n horizontal,\n vertical,\n aspectRatio\n )\n const rect: ConstrainedRect = { x: x.position, y: y.position, width: x.size, height: y.size }\n if (x.flipped) rect.flipsX = true\n if (y.flipped) rect.flipsY = true\n return rect\n }\n}\n\n/**\n * A child's box after its parent is resized, by a handle or `resize()`, keeping a locked aspect\n * ratio as Figma does.\n */\nexport const constrainedChildRect = childRectPlacer(0)\n\n/**\n * Where a child goes when layout resizes its parent, as Figma places a layer that ignores auto\n * layout when its Hug frame grows (measured on desktop 126): as `constrainedChildRect`, except\n * that a scaled position lands on 1/128 of a pixel.\n */\nexport const layoutConstrainedChildRect = childRectPlacer(1 / 128, false)\n\nexport function scaledChildRect(\n child: Rect,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>\n): Rect {\n return constrainedChildRect(child, parentBefore, parentAfter, 'SCALE', 'SCALE')\n}\n\nexport function scaleVectorNetworkForResize(\n vectorNetwork: VectorNetwork | null,\n originalWidth: number,\n originalHeight: number,\n width: number,\n height: number\n): VectorNetwork | null {\n if (!vectorNetwork || (originalWidth <= 0 && originalHeight <= 0)) return null\n\n // A flat side, as a straight line's, has nothing to scale along it.\n const scaleX = originalWidth > 0 ? width / originalWidth : 1\n const scaleY = originalHeight > 0 ? height / originalHeight : 1\n if (scaleX === 1 && scaleY === 1) return null\n\n return {\n vertices: vectorNetwork.vertices.map((vertex) => ({\n ...vertex,\n x: vertex.x * scaleX,\n y: vertex.y * scaleY\n })),\n segments: vectorNetwork.segments.map((segment) => ({\n ...segment,\n tangentStart: {\n x: segment.tangentStart.x * scaleX,\n y: segment.tangentStart.y * scaleY\n },\n tangentEnd: {\n x: segment.tangentEnd.x * scaleX,\n y: segment.tangentEnd.y * scaleY\n }\n })),\n regions: vectorNetwork.regions\n }\n}\n\n/** Snapshot one node's resize-relevant state (rect + geometry that must scale with it). */\nexport function createResizeSnapshot(node: SceneNode): ResizeSnapshot {\n return {\n type: node.type,\n x: node.x,\n y: node.y,\n width: node.width,\n height: node.height,\n flipX: node.flipX,\n flipY: node.flipY,\n vectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null,\n fillGeometry: copyGeometryPaths(node.fillGeometry),\n strokeGeometry: copyGeometryPaths(node.strokeGeometry),\n derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs),\n strokes: copyStrokes(node.strokes),\n textPathData: node.textPathData ? structuredClone(node.textPathData) : null,\n textPathBox: node.textPathBox ? { ...node.textPathBox } : null\n }\n}\n\nfunction scaleDerivedGlyphs(\n glyphs: DerivedTextGlyph[] | null,\n sx: number,\n sy: number\n): DerivedTextGlyph[] | null {\n if (!glyphs?.length) return glyphs\n return glyphs.map((g) => ({\n ...g,\n x: g.x * sx,\n y: g.y * sy,\n scaleX: (g.scaleX ?? 1) * sx,\n scaleY: (g.scaleY ?? 1) * sy,\n commandsBlob: new Uint8Array(g.commandsBlob)\n }))\n}\n\nfunction hasPath(orig: Pick<ResizeSnapshot, 'vectorNetwork'>): boolean {\n return (orig.vectorNetwork?.segments.length ?? 0) > 0\n}\n\nfunction scaleStrokes(strokes: Stroke[], sx: number, sy: number): Stroke[] {\n if (strokes.length === 0) return strokes\n // Weight is a scalar; average scale is the usual 2D → 1D compromise.\n const weightScale = (Math.abs(sx) + Math.abs(sy)) / 2\n return strokes.map((s) => ({ ...copyStroke(s), weight: s.weight * weightScale }))\n}\n\n/**\n * All geometry that must track a width/height change. Historically only\n * vectorNetwork + fillGeometry were updated — path-text strokeGeometry and\n * glyphs stayed at the pre-resize size, so shrinking a sticker made the white\n * OUTSIDE outlines look massively thick (DomeSticker resize bug).\n */\nexport function scaledGeometryChanges(\n orig: Pick<\n ResizeSnapshot,\n | 'type'\n | 'vectorNetwork'\n | 'fillGeometry'\n | 'strokeGeometry'\n | 'derivedTextGlyphs'\n | 'strokes'\n | 'textPathData'\n | 'textPathBox'\n >,\n origWidth: number,\n origHeight: number,\n width: number,\n height: number\n): Partial<SceneNode> {\n if (origWidth <= 0 || origHeight <= 0) return {}\n const sx = width / origWidth\n const sy = height / origHeight\n if (sx === 1 && sy === 1) return {}\n\n const changes: Partial<SceneNode> = {}\n const resizedVN = scaleVectorNetworkForResize(\n orig.vectorNetwork,\n origWidth,\n origHeight,\n width,\n height\n )\n if (resizedVN) changes.vectorNetwork = resizedVN\n\n if (orig.fillGeometry.length > 0) {\n changes.fillGeometry = scaleGeometryPaths(orig.fillGeometry, sx, sy)\n }\n // A stroke keeps its weight through a resize, as in Figma, so a saved stroke outline goes where\n // the stroke can be drawn again at its weight: from a path, or from a shape's own outline.\n // Text and a vector with only its outline keep scaling the outline, which is all they have.\n const outlineOnly = orig.type === 'TEXT' || (orig.type === 'VECTOR' && !hasPath(orig))\n if (orig.strokeGeometry.length > 0) {\n changes.strokeGeometry = outlineOnly ? scaleGeometryPaths(orig.strokeGeometry, sx, sy) : []\n }\n Object.assign(changes, scaledPathTextChanges(orig, sx, sy))\n // Glyphs scaled as a picture take their strokes along; any other stroke keeps its weight, as\n // Figma reports it, even where only a scaled outline can draw it.\n if (orig.strokes.length > 0 && followsPath(orig)) {\n changes.strokes = scaleStrokes(orig.strokes, sx, sy)\n }\n return changes\n}\n\n/**\n * The saved outlines a size change invalidates on a layer drawn from its live box: its fill\n * outline follows the box, and its saved stroke outline goes, so the stroke is drawn again at its\n * weight through the live shape. A vector and text draw from outlines of their own, which scaling\n * keeps. Without this, a layer that came from a `.fig` with frame outlines keeps drawing the old\n * box after layout, the Plugin API or an instance sync resizes it.\n */\nexport function shapeGeometryChanges(\n node: SceneNode,\n width: number,\n height: number\n): Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry'> {\n if (node.type === 'VECTOR' || node.type === 'TEXT') return {}\n if (node.fillGeometry.length === 0 && node.strokeGeometry.length === 0) return {}\n // A box with no extent has no outline to scale from; the live shape draws both again.\n if (node.width <= 0 || node.height <= 0) return { fillGeometry: [], strokeGeometry: [] }\n const changes = scaledGeometryChanges(\n createResizeSnapshot(node),\n node.width,\n node.height,\n width,\n height\n )\n const geometry: Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry'> = {}\n if (changes.fillGeometry) geometry.fillGeometry = changes.fillGeometry\n if (changes.strokeGeometry) geometry.strokeGeometry = changes.strokeGeometry\n return geometry\n}\n\ntype PathTextFields = Pick<SceneNode, 'derivedTextGlyphs' | 'textPathData' | 'textPathBox'>\n\n/** The baked glyphs and layout box of path text, scaled with the layer; nothing for other text. */\nexport function scaledPathTextChanges(\n orig: PathTextFields,\n sx: number,\n sy: number\n): Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> {\n if (!followsPath(orig)) return {}\n const changes: Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> = {\n derivedTextGlyphs: scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy)\n }\n // Keep the layout/selection box in sync with the scaled glyphs. reflow\n // overrides this when it applies; this covers the fallback where reflow\n // returns null (no path data) so the box doesn't carry a stale size.\n if (orig.textPathBox) {\n changes.textPathBox = {\n x: orig.textPathBox.x * sx,\n y: orig.textPathBox.y * sy,\n width: orig.textPathBox.width * sx,\n height: orig.textPathBox.height * sy\n }\n }\n return changes\n}\n\nexport function collectResizeDescendants(\n graph: ResizeGraph,\n rootId: string\n): Map<string, ResizeSnapshot> | null {\n const root = graph.getNode(rootId)\n if (!root || !CONSTRAINT_CONTAINER_TYPES.has(root.type)) return null\n const snapshots = new Map<string, ResizeSnapshot>()\n\n const collect = (parentId: string) => {\n const parent = graph.getNode(parentId)\n if (!parent) return\n for (const childId of parent.childIds) {\n const child = graph.getNode(childId)\n if (!child) continue\n snapshots.set(childId, createResizeSnapshot(child))\n collect(childId)\n }\n }\n\n collect(rootId)\n return snapshots.size > 0 ? snapshots : null\n}\n\n/**\n * The flips a child takes when its constraints place it from `from`, written only where they\n * differ from the ones it has now, so a drag that crosses back undoes its own turn.\n */\nexport function flipChanges(\n from: Pick<SceneNode, 'flipX' | 'flipY'>,\n current: Pick<SceneNode, 'flipX' | 'flipY'>,\n flipsX = false,\n flipsY = false\n): Partial<Pick<SceneNode, 'flipX' | 'flipY'>> {\n const changes: Partial<Pick<SceneNode, 'flipX' | 'flipY'>> = {}\n const flipX = from.flipX !== flipsX\n const flipY = from.flipY !== flipsY\n if (flipX !== current.flipX) changes.flipX = flipX\n if (flipY !== current.flipY) changes.flipY = flipY\n return changes\n}\n\nexport function computeConstrainedResizeChanges(\n graph: ResizeGraph,\n rootId: string,\n rootBefore: Pick<Rect, 'width' | 'height'>,\n rootAfter: Pick<Rect, 'width' | 'height'>,\n originals: ReadonlyMap<string, ResizeSnapshot>\n): Map<string, Partial<SceneNode>> {\n const changes = new Map<string, Partial<SceneNode>>()\n\n const compute = (\n parentId: string,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>\n ) => {\n const parent = graph.getNode(parentId)\n if (!parent) return\n const scalesChildren = parent.type === 'GROUP' || parent.type === 'BOOLEAN_OPERATION'\n for (const childId of parent.childIds) {\n const original = originals.get(childId)\n const child = graph.getNode(childId)\n if (!original || !child) continue\n const isInFlow = parent.layoutMode !== 'NONE' && child.layoutPositioning !== 'ABSOLUTE'\n if (isInFlow) {\n compute(childId, original, child)\n continue\n }\n const rect: ConstrainedRect = scalesChildren\n ? scaledChildRect(original, parentBefore, parentAfter)\n : constrainedChildRect(\n original,\n parentBefore,\n parentAfter,\n child.horizontalConstraint,\n child.verticalConstraint,\n enforcedAspectRatio(child)\n )\n const { flipsX, flipsY, ...box } = rect\n const childChanges: Partial<SceneNode> = {\n ...box,\n ...flipChanges(original, child, flipsX, flipsY),\n ...scaledGeometryChanges(original, original.width, original.height, box.width, box.height)\n }\n changes.set(childId, childChanges)\n // The final pass sees layout containers after Yoga has resolved HUG/FILL sizing.\n compute(childId, original, child.layoutMode === 'NONE' ? box : child)\n }\n }\n\n compute(rootId, rootBefore, rootAfter)\n return changes\n}\n"],"mappings":";;;;;AAyCA,MAAM,6CAA6B,IAAI,IAAI;CACzC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;AAgBD,SAAS,gBACP,UACA,MACA,cACA,aACA,YACA,YAAY,GACZ,aAAa,MACE;CACf,MAAM,QAAQ,KAAK,MAAM,WAAW,IAAI,KAAK,MAAM,YAAY;CAC/D,IAAI,eAAe,OAAO,OAAO;EAAE,UAAU,WAAW;EAAO;CAAK;CACpE,IAAI,eAAe,UACjB,OAAO;EAAE,UAAU,WAAW,KAAK,MAAM,cAAc,CAAC,IAAI,KAAK,MAAM,eAAe,CAAC;EAAG;CAAK;CAEjG,IAAI,eAAe,WAAW;EAC5B,MAAM,YAAY,OAAO;EACzB,IAAI,CAAC,YAAY,OAAO;GAAE;GAAU,MAAM,K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A,cACA,gBACG;EACH,MAAM,SAAS,MAAM,QAAQ,QAAQ;EACrC,IAAI,CAAC,QAAQ;EACb,MAAM,iBAAiB,OAAO,SAAS,WAAW,OAAO,SAAS;EAClE,KAAK,MAAM,WAAW,OAAO,UAAU;GACrC,MAAM,WAAW,UAAU,IAAI,OAAO;GACtC,MAAM,QAAQ,MAAM,QAAQ,OAAO;GACnC,IAAI,CAAC,YAAY,CAAC,OAAO;GAEzB,IADiB,OAAO,eAAe,UAAU,MAAM,sBAAsB,YAC/D;IACZ,QAAQ,SAAS,UAAU,KAAK;IAChC;GACF;GAWA,MAAM,EAAE,QAAQ,QAAQ,GAAG,QAVG,iBAC1B,gBAAgB,UAAU,cAAc,WAAW,IACnD,qBACE,UACA,cACA,aACA,MAAM,sBACN,MAAM,oBACN,oBAAoB,KAAK,CAC3B;GAEJ,MAAM,eAAmC;IACvC,GAAG;IACH,GAAG,YAAY,UAAU,OAAO,QAAQ,MAAM;IAC9C,GAAG,sBAAsB,UAAU,SAAS,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI,MAAM;GAC3F;GACA,QAAQ,IAAI,SAAS,YAAY;GAEjC,QAAQ,SAAS,UAAU,MAAM,eAAe,SAAS,MAAM,KAAK;EACtE;CACF;CAEA,QAAQ,QAAQ,YAAY,SAAS;CACrC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"resize.js","names":[],"sources":["../src/resize.ts"],"sourcesContent":["import {\n copyDerivedGlyphs,\n copyGeometryPaths,\n copyStroke,\n copyStrokes,\n scaleGeometryPaths\n} from './copy'\nimport { enforcedAspectRatio } from './layout/aspect-ratio'\nimport type { Rect } from './primitives'\nimport { followsPath } from './text/path'\nimport type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'\nimport { cloneVectorNetwork } from './vector-network'\n\n/**\n * Drag-start state a live resize re-scales from. Path text needs more than the\n * layout rect: its OUTSIDE stroke silhouettes and glyph outlines are baked\n * geometry that must scale with the node, and textPathBox is the layout box the\n * glyphs were reflowed against.\n */\nexport type ResizeSnapshot = Pick<\n SceneNode,\n | 'type'\n | 'x'\n | 'y'\n | 'width'\n | 'height'\n | 'flipX'\n | 'flipY'\n | 'vectorNetwork'\n | 'fillGeometry'\n | 'strokeGeometry'\n | 'derivedTextGlyphs'\n | 'strokes'\n | 'textPathData'\n | 'textPathBox'\n>\n\ninterface ResizeGraph {\n getNode(id: string): SceneNode | undefined\n}\n\nconst CONSTRAINT_CONTAINER_TYPES = new Set([\n 'FRAME',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE',\n 'GROUP',\n 'BOOLEAN_OPERATION'\n])\n\ntype AxisPlacement = { position: number; size: number; flipped?: boolean }\n\n/** A child's box after its parent resizes, and the axes on which it turned over. */\nexport type ConstrainedRect = Rect & { flipsX?: boolean; flipsY?: boolean }\n\n/**\n * Where a constraint places a child on one axis when its parent goes from `parentBefore` to\n * `parentAfter`, as Figma does: Right and Left & right move or grow it by the change in the\n * parent's size rounded to whole pixels, Center by the change in its rounded half, and Scale by\n * the exact ratio. The child's own box is never rounded, so a resize to the same size changes\n * nothing. Left & right that would leave no size keeps the axis as it was; past zero, the child\n * turns over and its box runs back from the edge it was pinned to, as the layer is mirrored in\n * Figma. `scaleStep` snaps a scaled position to that fraction of a pixel.\n */\nfunction constrainedAxis(\n position: number,\n size: number,\n parentBefore: number,\n parentAfter: number,\n constraint: ConstraintType,\n scaleStep = 0,\n allowFlips = true\n): AxisPlacement {\n const delta = Math.round(parentAfter) - Math.round(parentBefore)\n if (constraint === 'MAX') return { position: position + delta, size }\n if (constraint === 'CENTER') {\n return { position: position + Math.round(parentAfter / 2) - Math.round(parentBefore / 2), size }\n }\n if (constraint === 'STRETCH') {\n const stretched = size + delta\n if (!allowFlips) return { position, size: Math.abs(stretched) }\n if (stretched === 0) return { position, size }\n if (stretched > 0) return { position, size: stretched }\n return { position: position + stretched, size: -stretched, flipped: true }\n }\n if (constraint === 'SCALE' && parentBefore > 0) {\n const scale = parentAfter / parentBefore\n const scaled = position * scale\n return {\n position: scaleStep > 0 ? Math.round(scaled / scaleStep) * scaleStep : scaled,\n size: size * scale\n }\n }\n return { position, size }\n}\n\nconst FLEXIBLE_CONSTRAINTS: ReadonlySet<ConstraintType> = new Set(['STRETCH', 'SCALE'])\n\n/** The axis at `size`, keeping the edge or centre its constraint pins where it was placed. */\nfunction resizedInPlace(\n placed: AxisPlacement,\n size: number,\n constraint: ConstraintType\n): AxisPlacement {\n if (constraint === 'MAX') return { position: placed.position + placed.size - size, size }\n if (constraint === 'CENTER') return { position: placed.position + (placed.size - size) / 2, size }\n return { position: placed.position, size }\n}\n\n/** Keep a placed box's constrained edges or center when its content determines its size. */\nexport function resizedChildRect(\n placed: Rect,\n size: Pick<Rect, 'width' | 'height'>,\n horizontal: ConstraintType,\n vertical: ConstraintType\n): Rect {\n const x = resizedInPlace({ position: placed.x, size: placed.width }, size.width, horizontal)\n const y = resizedInPlace({ position: placed.y, size: placed.height }, size.height, vertical)\n return { x: x.position, y: y.position, width: x.size, height: y.size }\n}\n\n/**\n * A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis\n * sizes the other. With both axes following the parent, or neither, the ratio gives way.\n */\nfunction keepLockedRatio(\n x: AxisPlacement,\n y: AxisPlacement,\n horizontal: ConstraintType,\n vertical: ConstraintType,\n aspectRatio: number | null\n): { x: AxisPlacement; y: AxisPlacement } {\n const flexibleX = FLEXIBLE_CONSTRAINTS.has(horizontal)\n if (aspectRatio === null || flexibleX === FLEXIBLE_CONSTRAINTS.has(vertical)) return { x, y }\n return flexibleX\n ? { x, y: resizedInPlace(y, x.size / aspectRatio, vertical) }\n : { x: resizedInPlace(x, y.size * aspectRatio, horizontal), y }\n}\n\n/** The limits a layer's own size fields put on an automatic resize. */\nexport interface ConstraintLimits {\n minWidth?: number | null\n maxWidth?: number | null\n minHeight?: number | null\n maxHeight?: number | null\n}\n\ntype ChildRectPlacer = (\n child: Rect,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>,\n horizontal: ConstraintType,\n vertical: ConstraintType,\n aspectRatio?: number | null,\n limits?: ConstraintLimits\n) => ConstrainedRect\n\n/** A placed axis stopped at the layer's own min or max, its constraint's edge kept in place. */\nfunction limitedAxis(\n placed: AxisPlacement,\n constraint: ConstraintType,\n min: number | null | undefined,\n max: number | null | undefined\n): AxisPlacement {\n const size = Math.min(max ?? Infinity, Math.max(min ?? -Infinity, placed.size))\n if (size === placed.size) return placed\n const limited = resizedInPlace(placed, size, constraint)\n return placed.flipped ? { ...limited, flipped: true } : limited\n}\n\n/** Places a child by its constraints, snapping a scaled position to `scaleStep` when it is set. */\nfunction childRectPlacer(scaleStep: number, allowFlips = true): ChildRectPlacer {\n return (\n child,\n parentBefore,\n parentAfter,\n horizontal,\n vertical,\n aspectRatio = null,\n limits = {}\n ) => {\n const { x, y } = keepLockedRatio(\n constrainedAxis(\n child.x,\n child.width,\n parentBefore.width,\n parentAfter.width,\n horizontal,\n scaleStep,\n allowFlips\n ),\n constrainedAxis(\n child.y,\n child.height,\n parentBefore.height,\n parentAfter.height,\n vertical,\n scaleStep,\n allowFlips\n ),\n horizontal,\n vertical,\n aspectRatio\n )\n const limitedX = limitedAxis(x, horizontal, limits.minWidth, limits.maxWidth)\n const limitedY = limitedAxis(y, vertical, limits.minHeight, limits.maxHeight)\n const rect: ConstrainedRect = {\n x: limitedX.position,\n y: limitedY.position,\n width: limitedX.size,\n height: limitedY.size\n }\n if (limitedX.flipped) rect.flipsX = true\n if (limitedY.flipped) rect.flipsY = true\n return rect\n }\n}\n\n/**\n * A child's box after its parent is resized, by a handle or `resize()`, keeping a locked aspect\n * ratio as Figma does.\n */\nexport const constrainedChildRect = childRectPlacer(0)\n\n/**\n * Where a child goes when layout resizes its parent, as Figma places a layer that ignores auto\n * layout when its Hug frame grows (measured on desktop 126): as `constrainedChildRect`, except\n * that a scaled position lands on 1/128 of a pixel.\n */\nexport const layoutConstrainedChildRect = childRectPlacer(1 / 128, false)\n\nexport function scaledChildRect(\n child: Rect,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>\n): Rect {\n return constrainedChildRect(child, parentBefore, parentAfter, 'SCALE', 'SCALE')\n}\n\nexport function scaleVectorNetworkForResize(\n vectorNetwork: VectorNetwork | null,\n originalWidth: number,\n originalHeight: number,\n width: number,\n height: number\n): VectorNetwork | null {\n if (!vectorNetwork || (originalWidth <= 0 && originalHeight <= 0)) return null\n\n // A flat side, as a straight line's, has nothing to scale along it.\n const scaleX = originalWidth > 0 ? width / originalWidth : 1\n const scaleY = originalHeight > 0 ? height / originalHeight : 1\n if (scaleX === 1 && scaleY === 1) return null\n\n return {\n vertices: vectorNetwork.vertices.map((vertex) => ({\n ...vertex,\n x: vertex.x * scaleX,\n y: vertex.y * scaleY\n })),\n segments: vectorNetwork.segments.map((segment) => ({\n ...segment,\n tangentStart: {\n x: segment.tangentStart.x * scaleX,\n y: segment.tangentStart.y * scaleY\n },\n tangentEnd: {\n x: segment.tangentEnd.x * scaleX,\n y: segment.tangentEnd.y * scaleY\n }\n })),\n regions: vectorNetwork.regions\n }\n}\n\n/** Snapshot one node's resize-relevant state (rect + geometry that must scale with it). */\nexport function createResizeSnapshot(node: SceneNode): ResizeSnapshot {\n return {\n type: node.type,\n x: node.x,\n y: node.y,\n width: node.width,\n height: node.height,\n flipX: node.flipX,\n flipY: node.flipY,\n vectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null,\n fillGeometry: copyGeometryPaths(node.fillGeometry),\n strokeGeometry: copyGeometryPaths(node.strokeGeometry),\n derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs),\n strokes: copyStrokes(node.strokes),\n textPathData: node.textPathData ? structuredClone(node.textPathData) : null,\n textPathBox: node.textPathBox ? { ...node.textPathBox } : null\n }\n}\n\nfunction scaleDerivedGlyphs(\n glyphs: DerivedTextGlyph[] | null,\n sx: number,\n sy: number\n): DerivedTextGlyph[] | null {\n if (!glyphs?.length) return glyphs\n return glyphs.map((g) => ({\n ...g,\n x: g.x * sx,\n y: g.y * sy,\n scaleX: (g.scaleX ?? 1) * sx,\n scaleY: (g.scaleY ?? 1) * sy,\n commandsBlob: new Uint8Array(g.commandsBlob)\n }))\n}\n\nfunction hasPath(orig: Pick<ResizeSnapshot, 'vectorNetwork'>): boolean {\n return (orig.vectorNetwork?.segments.length ?? 0) > 0\n}\n\nfunction scaleStrokes(strokes: Stroke[], sx: number, sy: number): Stroke[] {\n if (strokes.length === 0) return strokes\n // Weight is a scalar; average scale is the usual 2D → 1D compromise.\n const weightScale = (Math.abs(sx) + Math.abs(sy)) / 2\n return strokes.map((s) => ({ ...copyStroke(s), weight: s.weight * weightScale }))\n}\n\n/**\n * All geometry that must track a width/height change. Historically only\n * vectorNetwork + fillGeometry were updated — path-text strokeGeometry and\n * glyphs stayed at the pre-resize size, so shrinking a sticker made the white\n * OUTSIDE outlines look massively thick (DomeSticker resize bug).\n */\nexport function scaledGeometryChanges(\n orig: Pick<\n ResizeSnapshot,\n | 'type'\n | 'vectorNetwork'\n | 'fillGeometry'\n | 'strokeGeometry'\n | 'derivedTextGlyphs'\n | 'strokes'\n | 'textPathData'\n | 'textPathBox'\n >,\n origWidth: number,\n origHeight: number,\n width: number,\n height: number\n): Partial<SceneNode> {\n if (origWidth <= 0 || origHeight <= 0) return {}\n const sx = width / origWidth\n const sy = height / origHeight\n if (sx === 1 && sy === 1) return {}\n\n const changes: Partial<SceneNode> = {}\n const resizedVN = scaleVectorNetworkForResize(\n orig.vectorNetwork,\n origWidth,\n origHeight,\n width,\n height\n )\n if (resizedVN) changes.vectorNetwork = resizedVN\n\n if (orig.fillGeometry.length > 0) {\n changes.fillGeometry = scaleGeometryPaths(orig.fillGeometry, sx, sy)\n }\n // A stroke keeps its weight through a resize, as in Figma, so a saved stroke outline goes where\n // the stroke can be drawn again at its weight: from a path, or from a shape's own outline.\n // Text and a vector with only its outline keep scaling the outline, which is all they have.\n const outlineOnly = orig.type === 'TEXT' || (orig.type === 'VECTOR' && !hasPath(orig))\n if (orig.strokeGeometry.length > 0) {\n changes.strokeGeometry = outlineOnly ? scaleGeometryPaths(orig.strokeGeometry, sx, sy) : []\n }\n Object.assign(changes, scaledPathTextChanges(orig, sx, sy))\n // Glyphs scaled as a picture take their strokes along; any other stroke keeps its weight, as\n // Figma reports it, even where only a scaled outline can draw it.\n if (orig.strokes.length > 0 && followsPath(orig)) {\n changes.strokes = scaleStrokes(orig.strokes, sx, sy)\n }\n return changes\n}\n\n/**\n * The saved outlines a size change invalidates on a layer drawn from its live box: its fill\n * outline follows the box, and its saved stroke outline goes, so the stroke is drawn again at its\n * weight through the live shape. A vector and text draw from outlines of their own, which scaling\n * keeps. Without this, a layer that came from a `.fig` with frame outlines keeps drawing the old\n * box after layout, the Plugin API or an instance sync resizes it.\n */\nexport function shapeGeometryChanges(\n node: SceneNode,\n width: number,\n height: number\n): Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry'> {\n if (node.type === 'VECTOR' || node.type === 'TEXT') return {}\n if (node.fillGeometry.length === 0 && node.strokeGeometry.length === 0) return {}\n // A box with no extent has no outline to scale from; the live shape draws both again.\n if (node.width <= 0 || node.height <= 0) return { fillGeometry: [], strokeGeometry: [] }\n const changes = scaledGeometryChanges(\n createResizeSnapshot(node),\n node.width,\n node.height,\n width,\n height\n )\n const geometry: Pick<Partial<SceneNode>, 'fillGeometry' | 'strokeGeometry'> = {}\n if (changes.fillGeometry) geometry.fillGeometry = changes.fillGeometry\n if (changes.strokeGeometry) geometry.strokeGeometry = changes.strokeGeometry\n return geometry\n}\n\ntype PathTextFields = Pick<SceneNode, 'derivedTextGlyphs' | 'textPathData' | 'textPathBox'>\n\n/** The baked glyphs and layout box of path text, scaled with the layer; nothing for other text. */\nexport function scaledPathTextChanges(\n orig: PathTextFields,\n sx: number,\n sy: number\n): Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> {\n if (!followsPath(orig)) return {}\n const changes: Pick<Partial<SceneNode>, 'derivedTextGlyphs' | 'textPathBox'> = {\n derivedTextGlyphs: scaleDerivedGlyphs(orig.derivedTextGlyphs, sx, sy)\n }\n // Keep the layout/selection box in sync with the scaled glyphs. reflow\n // overrides this when it applies; this covers the fallback where reflow\n // returns null (no path data) so the box doesn't carry a stale size.\n if (orig.textPathBox) {\n changes.textPathBox = {\n x: orig.textPathBox.x * sx,\n y: orig.textPathBox.y * sy,\n width: orig.textPathBox.width * sx,\n height: orig.textPathBox.height * sy\n }\n }\n return changes\n}\n\nexport function collectResizeDescendants(\n graph: ResizeGraph,\n rootId: string\n): Map<string, ResizeSnapshot> | null {\n const root = graph.getNode(rootId)\n if (!root || !CONSTRAINT_CONTAINER_TYPES.has(root.type)) return null\n const snapshots = new Map<string, ResizeSnapshot>()\n\n const collect = (parentId: string) => {\n const parent = graph.getNode(parentId)\n if (!parent) return\n for (const childId of parent.childIds) {\n const child = graph.getNode(childId)\n if (!child) continue\n snapshots.set(childId, createResizeSnapshot(child))\n collect(childId)\n }\n }\n\n collect(rootId)\n return snapshots.size > 0 ? snapshots : null\n}\n\n/**\n * The flips a child takes when its constraints place it from `from`, written only where they\n * differ from the ones it has now, so a drag that crosses back undoes its own turn.\n */\nexport function flipChanges(\n from: Pick<SceneNode, 'flipX' | 'flipY'>,\n current: Pick<SceneNode, 'flipX' | 'flipY'>,\n flipsX = false,\n flipsY = false\n): Partial<Pick<SceneNode, 'flipX' | 'flipY'>> {\n const changes: Partial<Pick<SceneNode, 'flipX' | 'flipY'>> = {}\n const flipX = from.flipX !== flipsX\n const flipY = from.flipY !== flipsY\n if (flipX !== current.flipX) changes.flipX = flipX\n if (flipY !== current.flipY) changes.flipY = flipY\n return changes\n}\n\nexport function computeConstrainedResizeChanges(\n graph: ResizeGraph,\n rootId: string,\n rootBefore: Pick<Rect, 'width' | 'height'>,\n rootAfter: Pick<Rect, 'width' | 'height'>,\n originals: ReadonlyMap<string, ResizeSnapshot>\n): Map<string, Partial<SceneNode>> {\n const changes = new Map<string, Partial<SceneNode>>()\n\n const compute = (\n parentId: string,\n parentBefore: Pick<Rect, 'width' | 'height'>,\n parentAfter: Pick<Rect, 'width' | 'height'>\n ) => {\n const parent = graph.getNode(parentId)\n if (!parent) return\n const scalesChildren = parent.type === 'GROUP' || parent.type === 'BOOLEAN_OPERATION'\n for (const childId of parent.childIds) {\n const original = originals.get(childId)\n const child = graph.getNode(childId)\n if (!original || !child) continue\n const isInFlow = parent.layoutMode !== 'NONE' && child.layoutPositioning !== 'ABSOLUTE'\n if (isInFlow) {\n compute(childId, original, child)\n continue\n }\n const rect: ConstrainedRect = scalesChildren\n ? scaledChildRect(original, parentBefore, parentAfter)\n : constrainedChildRect(\n original,\n parentBefore,\n parentAfter,\n child.horizontalConstraint,\n child.verticalConstraint,\n enforcedAspectRatio(child),\n child\n )\n const { flipsX, flipsY, ...box } = rect\n const childChanges: Partial<SceneNode> = {\n ...box,\n ...flipChanges(original, child, flipsX, flipsY),\n ...scaledGeometryChanges(original, original.width, original.height, box.width, box.height)\n }\n changes.set(childId, childChanges)\n // The final pass sees layout containers after Yoga has resolved HUG/FILL sizing.\n compute(childId, original, child.layoutMode === 'NONE' ? box : child)\n }\n }\n\n compute(rootId, rootBefore, rootAfter)\n return changes\n}\n"],"mappings":";;;;;AAyCA,MAAM,6CAA6B,IAAI,IAAI;CACzC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;AAgBD,SAAS,gBACP,UACA,MACA,cACA,aACA,YACA,YAAY,GACZ,aAAa,MACE;CACf,MAAM,QAAQ,KAAK,MAAM,WAAW,IAAI,KAAK,MAAM,YAAY;CAC/D,IAAI,eAAe,OAAO,OAAO;EAAE,UAAU,WAAW;EAAO;CAAK;CACpE,IAAI,eAAe,UACjB,OAAO;EAAE,UAAU,WAAW,KAAK,MAAM,cAAc,CAAC,IAAI,KAAK,MAAM,eAAe,CAAC;EAAG;CAAK;CAEjG,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eAAe,SAAS,MAAM,KAAK;EACtE;CACF;CAEA,QAAQ,QAAQ,YAAY,SAAS;CACrC,OAAO;AACT"}
|
package/dist/slots/content.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { InstanceOverrideState } from "../instances/overrides.js";
|
|
1
2
|
import { SceneGraph } from "../graph.js";
|
|
2
3
|
import { SceneNode } from "../types.js";
|
|
3
4
|
//#region src/slots/content.d.ts
|
|
@@ -28,6 +29,50 @@ declare function slotScope(graph: SceneGraph, parentId: string): SlotScope;
|
|
|
28
29
|
declare function claimSlotContent(graph: SceneGraph, scope: Extract<SlotScope, {
|
|
29
30
|
kind: 'slot';
|
|
30
31
|
}>): void;
|
|
32
|
+
/**
|
|
33
|
+
* What claiming a slot changes besides the edited layer, so one undo step can put it all back:
|
|
34
|
+
* the instance's assignment and override state, and the copies' component addresses.
|
|
35
|
+
*/
|
|
36
|
+
interface SlotClaimSnapshot {
|
|
37
|
+
instanceId: string;
|
|
38
|
+
assignments: SceneNode['componentPropertyAssignments'];
|
|
39
|
+
editedFields: string[];
|
|
40
|
+
overrides: InstanceOverrideState;
|
|
41
|
+
componentIds: Map<string, string | null>;
|
|
42
|
+
nestedOverrides: Map<string, InstanceOverrideState>;
|
|
43
|
+
}
|
|
44
|
+
/** The state `claimSlotContent` would replace, or null when the instance already owns the slot. */
|
|
45
|
+
declare function snapshotSlotClaim(graph: SceneGraph, scope: Extract<SlotScope, {
|
|
46
|
+
kind: 'slot';
|
|
47
|
+
}>): SlotClaimSnapshot | null;
|
|
48
|
+
/** Undo a claim: the instance stops owning the slot and its copies follow the component again. */
|
|
49
|
+
declare function restoreSlotClaim(graph: SceneGraph, snapshot: SlotClaimSnapshot): void;
|
|
50
|
+
/**
|
|
51
|
+
* The instance guard's refusal. Commands catch this one class to explain the refusal; every other
|
|
52
|
+
* error keeps propagating as a real failure.
|
|
53
|
+
*/
|
|
54
|
+
declare class InstanceGuardError extends Error {
|
|
55
|
+
readonly method: string;
|
|
56
|
+
constructor(method: string, refusal: string);
|
|
57
|
+
}
|
|
58
|
+
declare function childPlacementRefusal(graph: SceneGraph, parentId: string, method: string): string | null;
|
|
59
|
+
/** Refuse a new child under the locked part of an instance, as Figma's appendChild does. */
|
|
60
|
+
declare function assertChildPlacement(graph: SceneGraph, parentId: string, method: string): void;
|
|
61
|
+
/** Why grouping or moving these layers there would be refused, or null when it is allowed. */
|
|
62
|
+
declare function groupPlacementRefusal(graph: SceneGraph, parentId: string, memberIds: readonly string[], method: string): string | null;
|
|
63
|
+
/** Refuse grouping layers under the locked part, or pulling locked layers out of it. */
|
|
64
|
+
declare function assertGroupPlacement(graph: SceneGraph, parentId: string, memberIds: readonly string[], method: string): void;
|
|
65
|
+
/** Why moving this layer out of its parent would be refused, or null when it is allowed. */
|
|
66
|
+
declare function nodeMovementRefusal(graph: SceneGraph, nodeId: string, method: string): string | null;
|
|
67
|
+
/** Refuse moving a layer out of the locked part of an instance, as Figma does. */
|
|
68
|
+
declare function assertNodeMovable(graph: SceneGraph, nodeId: string, method: string): void;
|
|
69
|
+
/**
|
|
70
|
+
* The slot scope a layer sits inside, walking out past a locked frame such as a nested instance:
|
|
71
|
+
* an edit anywhere below the slot is still content the instance put there.
|
|
72
|
+
*/
|
|
73
|
+
declare function enclosingSlotScope(graph: SceneGraph, fromId: string): Extract<SlotScope, {
|
|
74
|
+
kind: 'slot';
|
|
75
|
+
}> | null;
|
|
31
76
|
/** Return the slot to its component's content: the instance stops owning it. */
|
|
32
77
|
declare function resetSlotContent(graph: SceneGraph, scope: Extract<SlotScope, {
|
|
33
78
|
kind: 'slot';
|
|
@@ -37,5 +82,5 @@ declare function clearSlotContent(graph: SceneGraph, scope: Extract<SlotScope, {
|
|
|
37
82
|
kind: 'slot';
|
|
38
83
|
}>): void;
|
|
39
84
|
//#endregion
|
|
40
|
-
export { SlotScope, claimSlotContent, clearSlotContent, resetSlotContent, slotScope };
|
|
85
|
+
export { InstanceGuardError, SlotClaimSnapshot, SlotScope, assertChildPlacement, assertGroupPlacement, assertNodeMovable, childPlacementRefusal, claimSlotContent, clearSlotContent, enclosingSlotScope, groupPlacementRefusal, nodeMovementRefusal, resetSlotContent, restoreSlotClaim, slotScope, snapshotSlotClaim };
|
|
41
86
|
//# sourceMappingURL=content.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content.d.ts","names":[],"sources":["../../src/slots/content.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"content.d.ts","names":[],"sources":["../../src/slots/content.ts"],"mappings":";;;;;;;;;;;KAqBY;EACN;;EACA;EAAc,OAAO;EAAW,UAAU;EAAW;;EACrD;EAAgB,OAAO;;iBAiBb,UAAU,OAAO,YAAY,mBAAmB;;;;;;iBAiChD,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa;;;;;;UAkCb;EACf;EACA,aAAa;EACb;EACA,WAAW;EACX,cAAc;EACd,iBAAiB,YAAY;;;iBAIf,kBACd,OAAO,YACP,OAAO,QAAQ;EAAa;KAC3B;;iBAuBa,iBAAiB,OAAO,YAAY,UAAU;;;;;cAsBjD,2BAA2B;WAE3B;EAAA,YAAA,gBACT;;iBAsBY,sBACd,OAAO,YACP,kBACA;;iBAUc,qBAAqB,OAAO,YAAY,kBAAkB;;iBAQ1D,sBACd,OAAO,YACP,kBACA,8BACA;;iBAkBc,qBACd,OAAO,YACP,kBACA,8BACA;;iBAec,oBACd,OAAO,YACP,gBACA;;iBAUc,kBAAkB,OAAO,YAAY,gBAAgB;;;;;iBAarD,mBACd,OAAO,YACP,iBACC,QAAQ;EAAa;;;iBA0BR,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa;;;iBAgBd,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa"}
|