@open-pencil/scene-graph 0.17.0-beta.3 → 0.17.0-beta.5
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/arrays.d.ts +17 -0
- package/dist/arrays.d.ts.map +1 -0
- package/dist/arrays.js +38 -0
- package/dist/arrays.js.map +1 -0
- package/dist/buffered-events.js +1 -1
- package/dist/buffered-events.js.map +1 -1
- package/dist/clipping.d.ts +7 -1
- package/dist/clipping.d.ts.map +1 -1
- package/dist/clipping.js +23 -19
- package/dist/clipping.js.map +1 -1
- package/dist/components/index.d.ts +2 -2
- package/dist/components/index.js +2 -2
- package/dist/components/properties.d.ts +1 -3
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +2 -9
- package/dist/components/properties.js.map +1 -1
- package/dist/corners.d.ts +22 -0
- package/dist/corners.d.ts.map +1 -0
- package/dist/corners.js +52 -0
- package/dist/corners.js.map +1 -0
- package/dist/css/grid.d.ts +4 -1
- package/dist/css/grid.d.ts.map +1 -1
- package/dist/css/grid.js +16 -7
- package/dist/css/grid.js.map +1 -1
- package/dist/css/index.d.ts +2 -2
- package/dist/css/index.js +2 -2
- package/dist/css/values.d.ts +6 -1
- package/dist/css/values.d.ts.map +1 -1
- package/dist/font-style.d.ts +2 -1
- package/dist/font-style.d.ts.map +1 -1
- package/dist/font-style.js +31 -6
- package/dist/font-style.js.map +1 -1
- package/dist/geometry.d.ts +68 -3
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +155 -5
- package/dist/geometry.js.map +1 -1
- package/dist/gradient.d.ts +9 -2
- package/dist/gradient.d.ts.map +1 -1
- package/dist/gradient.js +29 -1
- package/dist/gradient.js.map +1 -1
- package/dist/graph.d.ts +4 -0
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +30 -4
- package/dist/graph.js.map +1 -1
- package/dist/group-bounds.d.ts.map +1 -1
- package/dist/group-bounds.js +4 -3
- package/dist/group-bounds.js.map +1 -1
- package/dist/guides.d.ts +11 -2
- package/dist/guides.d.ts.map +1 -1
- package/dist/guides.js +30 -1
- package/dist/guides.js.map +1 -1
- package/dist/hit-test.d.ts.map +1 -1
- package/dist/hit-test.js +57 -5
- package/dist/hit-test.js.map +1 -1
- package/dist/icons/fit.d.ts +17 -0
- package/dist/icons/fit.d.ts.map +1 -0
- package/dist/icons/fit.js +21 -0
- package/dist/icons/fit.js.map +1 -0
- package/dist/icons/glyph.d.ts.map +1 -1
- package/dist/icons/glyph.js +5 -4
- package/dist/icons/glyph.js.map +1 -1
- package/dist/icons/index.d.ts +2 -1
- package/dist/icons/index.js +2 -1
- package/dist/images.d.ts +14 -4
- package/dist/images.d.ts.map +1 -1
- package/dist/images.js +45 -5
- package/dist/images.js.map +1 -1
- package/dist/instances/assignments.js +39 -6
- package/dist/instances/assignments.js.map +1 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +39 -2
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/kept-overrides.js +2 -2
- package/dist/instances/kept-overrides.js.map +1 -1
- package/dist/instances/matching.js +68 -0
- package/dist/instances/matching.js.map +1 -0
- package/dist/instances/overrides.d.ts +4 -1
- package/dist/instances/overrides.d.ts.map +1 -1
- package/dist/instances/overrides.js +13 -1
- package/dist/instances/overrides.js.map +1 -1
- package/dist/instances/protection.js +67 -0
- package/dist/instances/protection.js.map +1 -0
- package/dist/instances/swap.js +7 -5
- package/dist/instances/swap.js.map +1 -1
- package/dist/instances/sync.js +10 -116
- package/dist/instances/sync.js.map +1 -1
- package/dist/layout/guides.d.ts +17 -1
- package/dist/layout/guides.d.ts.map +1 -1
- package/dist/layout/guides.js +31 -11
- package/dist/layout/guides.js.map +1 -1
- package/dist/layout/index.d.ts +4 -2
- package/dist/layout/index.js +4 -2
- package/dist/layout/limits.d.ts +40 -0
- package/dist/layout/limits.d.ts.map +1 -0
- package/dist/layout/limits.js +54 -0
- package/dist/layout/limits.js.map +1 -0
- package/dist/layout/sizing.d.ts.map +1 -1
- package/dist/layout/sizing.js +0 -1
- package/dist/layout/sizing.js.map +1 -1
- package/dist/layout/spacing.d.ts +10 -0
- package/dist/layout/spacing.d.ts.map +1 -0
- package/dist/layout/spacing.js +12 -0
- package/dist/layout/spacing.js.map +1 -0
- package/dist/masks.d.ts +28 -0
- package/dist/masks.d.ts.map +1 -0
- package/dist/masks.js +53 -0
- package/dist/masks.js.map +1 -0
- package/dist/matrix.d.ts +2 -1
- package/dist/matrix.d.ts.map +1 -1
- package/dist/matrix.js +14 -1
- package/dist/matrix.js.map +1 -1
- package/dist/node-defaults.d.ts +9 -1
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +16 -1
- package/dist/node-defaults.js.map +1 -1
- package/dist/outline/flatten.d.ts.map +1 -1
- package/dist/outline/flatten.js +24 -17
- package/dist/outline/flatten.js.map +1 -1
- package/dist/outline/hit.d.ts +2 -8
- package/dist/outline/hit.d.ts.map +1 -1
- package/dist/outline/hit.js +16 -25
- package/dist/outline/hit.js.map +1 -1
- package/dist/outline/index.d.ts +3 -3
- package/dist/outline/index.js +3 -3
- package/dist/outline/shapes.d.ts +3 -1
- package/dist/outline/shapes.d.ts.map +1 -1
- package/dist/outline/shapes.js +18 -39
- package/dist/outline/shapes.js.map +1 -1
- package/dist/paints/index.d.ts +3 -1
- package/dist/paints/index.js +3 -1
- package/dist/paints/pattern.d.ts +13 -0
- package/dist/paints/pattern.d.ts.map +1 -0
- package/dist/paints/pattern.js +47 -0
- package/dist/paints/pattern.js.map +1 -0
- package/dist/paints/shows.d.ts +11 -0
- package/dist/paints/shows.d.ts.map +1 -0
- package/dist/paints/shows.js +16 -0
- package/dist/paints/shows.js.map +1 -0
- package/dist/paths/arc.d.ts +32 -0
- package/dist/paths/arc.d.ts.map +1 -0
- package/dist/paths/arc.js +49 -0
- package/dist/paths/arc.js.map +1 -0
- package/dist/paths/index.d.ts +5 -0
- package/dist/paths/index.js +5 -0
- package/dist/paths/network.d.ts +43 -0
- package/dist/paths/network.d.ts.map +1 -0
- package/dist/paths/network.js +249 -0
- package/dist/paths/network.js.map +1 -0
- package/dist/paths/sink.d.ts +20 -0
- package/dist/paths/sink.d.ts.map +1 -0
- package/dist/paths/sink.js +32 -0
- package/dist/paths/sink.js.map +1 -0
- package/dist/paths/smooth-corners.d.ts +25 -0
- package/dist/paths/smooth-corners.d.ts.map +1 -0
- package/dist/paths/smooth-corners.js +196 -0
- package/dist/paths/smooth-corners.js.map +1 -0
- package/dist/plugin-data/fields.d.ts +4 -0
- package/dist/plugin-data/fields.d.ts.map +1 -1
- package/dist/plugin-data/fields.js +2 -0
- package/dist/plugin-data/fields.js.map +1 -1
- package/dist/polygon.d.ts +1 -3
- package/dist/polygon.d.ts.map +1 -1
- package/dist/polygon.js +1 -16
- package/dist/polygon.js.map +1 -1
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +5 -5
- package/dist/resize.js.map +1 -1
- package/dist/scaling/node.d.ts.map +1 -1
- package/dist/scaling/node.js +25 -3
- package/dist/scaling/node.js.map +1 -1
- package/dist/text/auto-resize.d.ts +15 -0
- package/dist/text/auto-resize.d.ts.map +1 -0
- package/dist/text/auto-resize.js +23 -0
- package/dist/text/auto-resize.js.map +1 -0
- package/dist/text/index.d.ts +4 -3
- package/dist/text/index.js +4 -3
- package/dist/text/lengths.d.ts +6 -1
- package/dist/text/lengths.d.ts.map +1 -1
- package/dist/text/lengths.js +10 -1
- package/dist/text/lengths.js.map +1 -1
- package/dist/text/overflow.d.ts +14 -5
- package/dist/text/overflow.d.ts.map +1 -1
- package/dist/text/overflow.js +24 -6
- package/dist/text/overflow.js.map +1 -1
- package/dist/text/path.js +10 -0
- package/dist/text/path.js.map +1 -0
- package/dist/text/picture.js +5 -5
- package/dist/text/picture.js.map +1 -1
- package/dist/transfer/dependencies.d.ts.map +1 -1
- package/dist/transfer/dependencies.js +3 -2
- package/dist/transfer/dependencies.js.map +1 -1
- package/dist/transfer/nodes.js +2 -1
- package/dist/transfer/nodes.js.map +1 -1
- package/dist/types.d.ts +21 -8
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/variables/index.d.ts +4 -3
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +4 -3
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/lookup.d.ts +20 -0
- package/dist/variables/lookup.d.ts.map +1 -0
- package/dist/variables/lookup.js +34 -0
- package/dist/variables/lookup.js.map +1 -0
- package/dist/variables/paints.d.ts +35 -4
- package/dist/variables/paints.d.ts.map +1 -1
- package/dist/variables/paints.js +67 -16
- package/dist/variables/paints.js.map +1 -1
- package/dist/variables/resolution.d.ts +3 -1
- package/dist/variables/resolution.d.ts.map +1 -1
- package/dist/variables/resolution.js +8 -3
- package/dist/variables/resolution.js.map +1 -1
- package/dist/variables/subtree.js +1 -1
- package/dist/variables/subtree.js.map +1 -1
- package/dist/vector-network.d.ts.map +1 -1
- package/dist/vector-network.js +12 -76
- package/dist/vector-network.js.map +1 -1
- package/package.json +25 -1
- package/src/arrays.ts +37 -0
- package/src/buffered-events.ts +2 -1
- package/src/clipping.ts +11 -8
- package/src/components/properties.ts +1 -13
- package/src/corners.ts +93 -0
- package/src/css/grid.ts +21 -7
- package/src/css/index.ts +1 -1
- package/src/font-style.ts +38 -4
- package/src/geometry.ts +219 -6
- package/src/gradient.ts +23 -1
- package/src/graph.ts +22 -4
- package/src/group-bounds.ts +7 -3
- package/src/guides.ts +26 -1
- package/src/hit-test.ts +68 -10
- package/src/icons/fit.ts +24 -0
- package/src/icons/glyph.ts +5 -4
- package/src/icons/index.ts +1 -0
- package/src/images.ts +67 -7
- package/src/instances/assignments.ts +65 -7
- package/src/instances/index.ts +53 -4
- package/src/instances/kept-overrides.ts +2 -5
- package/src/instances/matching.ts +101 -0
- package/src/instances/overrides.ts +18 -0
- package/src/instances/protection.ts +103 -0
- package/src/instances/swap.ts +11 -9
- package/src/instances/sync.ts +11 -184
- package/src/layout/guides.ts +42 -9
- package/src/layout/index.ts +2 -0
- package/src/layout/limits.ts +64 -0
- package/src/layout/sizing.ts +0 -2
- package/src/layout/spacing.ts +11 -0
- package/src/masks.ts +51 -0
- package/src/matrix.ts +15 -2
- package/src/node-defaults.ts +23 -3
- package/src/outline/flatten.ts +30 -18
- package/src/outline/hit.ts +16 -33
- package/src/outline/index.ts +2 -2
- package/src/outline/shapes.ts +19 -36
- package/src/paints/index.ts +2 -0
- package/src/paints/pattern.ts +45 -0
- package/src/paints/shows.ts +13 -0
- package/src/paths/arc.ts +59 -0
- package/src/paths/index.ts +4 -0
- package/src/paths/network.ts +334 -0
- package/src/paths/sink.ts +50 -0
- package/src/paths/smooth-corners.ts +356 -0
- package/src/plugin-data/fields.ts +2 -0
- package/src/polygon.ts +0 -17
- package/src/resize.ts +6 -7
- package/src/scaling/node.ts +29 -3
- package/src/text/auto-resize.ts +25 -0
- package/src/text/index.ts +1 -0
- package/src/text/lengths.ts +11 -0
- package/src/text/overflow.ts +32 -6
- package/src/text/path.ts +13 -0
- package/src/text/picture.ts +5 -5
- package/src/transfer/dependencies.ts +3 -2
- package/src/transfer/nodes.ts +2 -1
- package/src/types.ts +25 -8
- package/src/variables/index.ts +1 -0
- package/src/variables/lookup.ts +31 -0
- package/src/variables/paints.ts +101 -20
- package/src/variables/resolution.ts +14 -2
- package/src/variables/subtree.ts +1 -1
- package/src/vector-network.ts +17 -138
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assignments.js","names":[],"sources":["../../src/instances/assignments.ts"],"sourcesContent":["// What enclosing instances assign the component properties that drive a copy's layers.\nimport type { SceneGraph } from '../graph'\nimport type { ComponentPropertyReferenceField, SceneNode } from '../types'\n\n/** SLOT_CONTENT is absent because it drives children, which `ownsSlotContent` keeps instead. */\nconst PROPERTY_REFERENCE_FIELDS: Partial<Record<ComponentPropertyReferenceField, string>> = {\n VISIBLE: 'visible',\n TEXT: 'text',\n INSTANCE_SWAP: 'componentId'\n}\n\n/** Instance links are expected to be shallow; the cap only stops a cycle from hanging sync. */\nconst INSTANCE_CHAIN_LIMIT = 16\n\n/**\n * Whether this instance's component, or the set it is a variant of, is where `propertyId` is\n * defined. Only a set counts: a component nested in an ordinary component defines its own\n * properties, not the outer one's.\n */\nfunction definesProperty(graph: SceneGraph, instance: SceneNode, propertyId: string): boolean {\n // An instance of an instance links through to the component, so follow the chain to it.\n let component = instance.componentId ? graph.nodes.get(instance.componentId) : undefined\n for (let hops = 0; component?.type === 'INSTANCE' && hops < INSTANCE_CHAIN_LIMIT; hops++) {\n component = component.componentId ? graph.nodes.get(component.componentId) : undefined\n }\n const parent = component?.parentId ? graph.nodes.get(component.parentId) : undefined\n const set = parent?.type === 'COMPONENT_SET' ? parent : undefined\n return [component, set]\n .flatMap((node) => node?.componentPropertyDefinitions ?? [])\n .some((definition) => definition.id === propertyId)\n}\n\n/**\n * What the nearest enclosing instance assigns `propertyId`, if any does. An instance assigns its\n * children, not itself, so the walk starts at the parent. A property id belongs to the component\n * that defines it, so the walk stops at an instance of that component even when it assigns\n * nothing; otherwise an outer instance's unrelated property of the same id wins.\n */\nfunction enclosingAssignment(\n graph: SceneGraph,\n node: SceneNode,\n propertyId: string\n): string | undefined {\n let current = node.parentId ? graph.nodes.get(node.parentId) : undefined\n while (current) {\n if (current.type === 'INSTANCE') {\n if (Object.hasOwn(current.componentPropertyAssignments, propertyId))\n return current.componentPropertyAssignments[propertyId]\n if (definesProperty(graph, current, propertyId)) return undefined\n }\n current = current.parentId ? graph.nodes.get(current.parentId) : undefined\n }\n return undefined\n}\n\nfunction hasEnclosingAssignment(graph: SceneGraph, node: SceneNode, propertyId: string): boolean {\n return enclosingAssignment(graph, node, propertyId) !== undefined\n}\n\n/**\n * A component can gain a property-driven layer after an instance of it exists. Pass 4 leaves a\n * driven field alone, so the fresh clone has to take the enclosing instance's assignment here or\n * it keeps the component's default while every other instance layer shows the assigned value.\n */\nexport function applyEnclosingAssignments(graph: SceneGraph, clone: SceneNode): void {\n for (const reference of clone.componentPropertyReferences) {\n const field = PROPERTY_REFERENCE_FIELDS[reference.field]\n if (!field) continue\n const value = enclosingAssignment(graph, clone, reference.propertyId)\n if (value === undefined) continue\n if (field === 'visible') graph.updateNode(clone.id, { visible: value === 'true' })\n else if (field === 'text') graph.updateNode(clone.id, { text: value })\n else if (field === 'componentId' && clone.type === 'INSTANCE' && graph.nodes.has(value)) {\n graph.swapInstanceComponent(clone.id, value)\n }\n }\n for (const child of graph.getChildren(clone.id)) applyEnclosingAssignments(graph, child)\n}\n\n/**\n * Fields a component property drives on this child. The component states the default, but\n * an enclosing instance's assignment decides the value, so synchronising must not copy the\n * default over it — a page loaded later would otherwise reset the instance to the default.\n */\nexport function propertyDrivenFields(\n graph: SceneGraph,\n instChild: SceneNode,\n compChild: SceneNode\n): Set<string> {\n const driven = new Set<string>()\n for (const reference of compChild.componentPropertyReferences) {\n const field = PROPERTY_REFERENCE_FIELDS[reference.field]\n if (field && hasEnclosingAssignment(graph, instChild, reference.propertyId)) driven.add(field)\n }\n return driven\n}\n\n/**\n * The text and visibility enclosing assignments give an existing child whose layer a property\n * drives. A layer linked to a property after the instance was made would otherwise keep what it\n * showed before, since synchronising leaves driven fields alone.\n */\nexport function assignedFieldValues(\n graph: SceneGraph,\n instChild: SceneNode,\n compChild: SceneNode\n): Partial<SceneNode> {\n const values: Partial<SceneNode> = {}\n for (const reference of compChild.componentPropertyReferences) {\n const value = enclosingAssignment(graph, instChild, reference.propertyId)\n if (value === undefined) continue\n if (reference.field === 'TEXT' && instChild.type === 'TEXT') values.text = value\n else if (reference.field === 'VISIBLE') values.visible = value === 'true'\n }\n return values\n}\n"],"mappings":";;AAKA,MAAM,4BAAsF;CAC1F,SAAS;CACT,MAAM;CACN,eAAe;AACjB;;AAGA,MAAM,uBAAuB;;;;;;AAO7B,SAAS,gBAAgB,OAAmB,UAAqB,YAA6B;CAE5F,IAAI,YAAY,SAAS,cAAc,MAAM,MAAM,IAAI,SAAS,WAAW,IAAI,KAAA;CAC/E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,CAAC;OAChE,IAAI,UAAU,iBAAiB,MAAM,SAAS,cAAc,MAAM,MAAM,IAAI,KAAK,GACpF,MAAM,sBAAsB,MAAM,IAAI,KAAK;CAE/C;CACA,KAAK,MAAM,SAAS,MAAM,YAAY,MAAM,EAAE,GAAG,0BAA0B,OAAO,KAAK;AACzF;;;;;;AAOA,SAAgB,qBACd,OACA,WACA,WACa;CACb,MAAM,yBAAS,IAAI,IAAY;CAC/B,KAAK,MAAM,aAAa,UAAU,6BAA6B;EAC7D,MAAM,QAAQ,0BAA0B,UAAU;EAClD,IAAI,SAAS,uBAAuB,OAAO,WAAW,UAAU,UAAU,GAAG,OAAO,IAAI,KAAK;CAC/F;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,oBACd,OACA,WACA,WACoB;CACpB,MAAM,SAA6B,CAAC;CACpC,KAAK,MAAM,aAAa,UAAU,6BAA6B;EAC7D,MAAM,QAAQ,oBAAoB,OAAO,WAAW,UAAU,UAAU;EACxE,IAAI,UAAU,KAAA,GAAW;EACzB,IAAI,UAAU,UAAU,UAAU,UAAU,SAAS,QAAQ,OAAO,OAAO;OACtE,IAAI,UAAU,UAAU,WAAW,OAAO,UAAU,UAAU;CACrE;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"assignments.js","names":[],"sources":["../../src/instances/assignments.ts"],"sourcesContent":["// What enclosing instances assign the component properties that drive a copy's layers.\nimport type { SceneGraph } from '../graph'\nimport type { ComponentPropertyReferenceField, SceneNode } from '../types'\nimport { assignmentOverrideField } from './overrides'\n\n/** SLOT_CONTENT is absent because it drives children, which `ownsSlotContent` keeps instead. */\nconst PROPERTY_REFERENCE_FIELDS: Partial<Record<ComponentPropertyReferenceField, string>> = {\n VISIBLE: 'visible',\n TEXT: 'text',\n INSTANCE_SWAP: 'componentId'\n}\n\n/** Instance links are expected to be shallow; the cap only stops a cycle from hanging sync. */\nconst INSTANCE_CHAIN_LIMIT = 16\n\n/**\n * Whether this instance's component, or the set it is a variant of, is where `propertyId` is\n * defined. Only a set counts: a component nested in an ordinary component defines its own\n * properties, not the outer one's.\n */\nfunction definesProperty(graph: SceneGraph, instance: SceneNode, propertyId: string): boolean {\n // An instance of an instance links through to the component, so follow the chain to it.\n let component = instance.componentId ? graph.nodes.get(instance.componentId) : undefined\n for (let hops = 0; component?.type === 'INSTANCE' && hops < INSTANCE_CHAIN_LIMIT; hops++) {\n component = component.componentId ? graph.nodes.get(component.componentId) : undefined\n }\n const parent = component?.parentId ? graph.nodes.get(component.parentId) : undefined\n const set = parent?.type === 'COMPONENT_SET' ? parent : undefined\n return [component, set]\n .flatMap((node) => node?.componentPropertyDefinitions ?? [])\n .some((definition) => definition.id === propertyId)\n}\n\ninterface Assignment {\n /** The instance whose assignment it is. */\n instance: SceneNode\n value: string\n}\n\n/**\n * What the nearest enclosing instance assigns `propertyId`, if any does. An instance assigns its\n * children, not itself, so the walk starts at the parent. A property id belongs to the component\n * that defines it, so the walk stops at an instance of that component even when it assigns\n * nothing; otherwise an outer instance's unrelated property of the same id wins.\n */\nfunction findEnclosingAssignment(\n graph: SceneGraph,\n node: SceneNode,\n propertyId: string\n): Assignment | undefined {\n let current = node.parentId ? graph.nodes.get(node.parentId) : undefined\n while (current) {\n if (current.type === 'INSTANCE') {\n if (Object.hasOwn(current.componentPropertyAssignments, propertyId))\n return { instance: current, value: current.componentPropertyAssignments[propertyId] }\n if (definesProperty(graph, current, propertyId)) return undefined\n }\n current = current.parentId ? graph.nodes.get(current.parentId) : undefined\n }\n return undefined\n}\n\nfunction enclosingAssignment(\n graph: SceneGraph,\n node: SceneNode,\n propertyId: string\n): string | undefined {\n return findEnclosingAssignment(graph, node, propertyId)?.value\n}\n\n/** The instances around `node`, nearest first. */\nfunction enclosingInstances(graph: SceneGraph, node: SceneNode): SceneNode[] {\n const instances: SceneNode[] = []\n if (node.parentId)\n graph.closest(node.parentId, (ancestor) => {\n if (ancestor.type === 'INSTANCE') instances.push(ancestor)\n return false\n })\n return instances\n}\n\n/** The outermost of `instances` that records `field` as an edit of `node`, or -1. */\nfunction outermostEdit(instances: SceneNode[], node: SceneNode, field: string): number {\n return instances.findLastIndex((instance) =>\n instance.instanceOverrides.descendants.get(node.id)?.has(field)\n )\n}\n\n/**\n * Whether a text edit of `layer` outranks the assignment that drives it. As in Figma, the edit\n * made in the outer instance wins, and at the same level the assignment does. An assignment is\n * made where an override of it is recorded, or else by the instance that holds it.\n */\nfunction textEditOutranks(\n graph: SceneGraph,\n layer: SceneNode,\n propertyId: string,\n assignment: Assignment\n): boolean {\n const instances = enclosingInstances(graph, layer)\n const textLevel = outermostEdit(instances, layer, 'text')\n if (textLevel < 0) return false\n const overridden = outermostEdit(\n instances,\n assignment.instance,\n assignmentOverrideField(propertyId)\n )\n const assignmentLevel = overridden < 0 ? instances.indexOf(assignment.instance) : overridden\n return textLevel > assignmentLevel\n}\n\nfunction hasEnclosingAssignment(graph: SceneGraph, node: SceneNode, propertyId: string): boolean {\n return enclosingAssignment(graph, node, propertyId) !== undefined\n}\n\n/**\n * A component can gain a property-driven layer after an instance of it exists. Pass 4 leaves a\n * driven field alone, so the fresh clone has to take the enclosing instance's assignment here or\n * it keeps the component's default while every other instance layer shows the assigned value.\n */\nexport function applyEnclosingAssignments(graph: SceneGraph, clone: SceneNode): void {\n for (const reference of clone.componentPropertyReferences) {\n const field = PROPERTY_REFERENCE_FIELDS[reference.field]\n if (!field) continue\n const value = enclosingAssignment(graph, clone, reference.propertyId)\n if (value === undefined) continue\n if (field === 'visible') graph.updateNode(clone.id, { visible: value === 'true' })\n else if (field === 'text') graph.updateNode(clone.id, { text: value })\n else if (field === 'componentId' && clone.type === 'INSTANCE' && graph.nodes.has(value)) {\n graph.swapInstanceComponent(clone.id, value)\n }\n }\n for (const child of graph.getChildren(clone.id)) applyEnclosingAssignments(graph, child)\n}\n\n/**\n * Fields a component property drives on this child. The component states the default, but\n * an enclosing instance's assignment decides the value, so synchronising must not copy the\n * default over it — a page loaded later would otherwise reset the instance to the default.\n */\nexport function propertyDrivenFields(\n graph: SceneGraph,\n instChild: SceneNode,\n compChild: SceneNode\n): Set<string> {\n const driven = new Set<string>()\n for (const reference of compChild.componentPropertyReferences) {\n const field = PROPERTY_REFERENCE_FIELDS[reference.field]\n if (field && hasEnclosingAssignment(graph, instChild, reference.propertyId)) driven.add(field)\n }\n return driven\n}\n\n/**\n * The text and visibility enclosing assignments give an existing child whose layer a property\n * drives. A layer linked to a property after the instance was made would otherwise keep what it\n * showed before, since synchronising leaves driven fields alone.\n */\nexport function assignedFieldValues(\n graph: SceneGraph,\n instChild: SceneNode,\n compChild: SceneNode\n): Partial<SceneNode> {\n const values: Partial<SceneNode> = {}\n for (const reference of compChild.componentPropertyReferences) {\n const assignment = findEnclosingAssignment(graph, instChild, reference.propertyId)\n if (!assignment) continue\n if (reference.field === 'TEXT' && instChild.type === 'TEXT') {\n if (!textEditOutranks(graph, instChild, reference.propertyId, assignment))\n values.text = assignment.value\n } else if (reference.field === 'VISIBLE') values.visible = assignment.value === 'true'\n }\n return values\n}\n"],"mappings":";;;AAMA,MAAM,4BAAsF;CAC1F,SAAS;CACT,MAAM;CACN,eAAe;AACjB;;AAGA,MAAM,uBAAuB;;;;;;AAO7B,SAAS,gBAAgB,OAAmB,UAAqB,YAA6B;CAE5F,IAAI,YAAY,SAAS,cAAc,MAAM,MAAM,IAAI,SAAS,WAAW,IAAI,KAAA;CAC/E,KAAK,IAAI,OAAO,GAAG,WAAW,SAAS,cAAc,OAAO,sBAAsB,QAChF,YAAY,UAAU,cAAc,MAAM,MAAM,IAAI,UAAU,WAAW,IAAI,KAAA;CAE/E,MAAM,SAAS,WAAW,WAAW,MAAM,MAAM,IAAI,UAAU,QAAQ,IAAI,KAAA;CAC3E,MAAM,MAAM,QAAQ,SAAS,kBAAkB,SAAS,KAAA;CACxD,OAAO,CAAC,WAAW,GAAG,CAAC,CACpB,SAAS,SAAS,MAAM,gCAAgC,CAAC,CAAC,CAAC,CAC3D,MAAM,eAAe,WAAW,OAAO,UAAU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
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/instances/index.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/instances/index.ts"],"mappings":";;;;;;;iBA+CgB,2BAA2B,WAAW,YAAY,QAAQ;iBAM1D,eACd,OAAO,YACP,qBACA,kBACA,YAAW,QAAQ,aAClB;iBAoBa,yBACd,OAAO,YACP,oBACA,qBACA,OAAM;UAmCS;;;;;;EAMf;;iBAgBc,sBACd,OAAO,YACP,oBACA,uBACE,aAAoB;iBAwDR,cAAc,OAAO,YAAY;;;;;iBAQjC,sBAAsB,OAAO,YAAY,cAAc;;iBAOvD,aAAa,OAAO,YAAY;iBAsChC,eAAe,OAAO,YAAY;iBAwDlC,iBAAiB,OAAO,YAAY,qBAAqB;iBAMzD,aAAa,OAAO,YAAY,sBAAsB;;;;iBActD,oBAAoB,OAAO,YAAY,gBAAgB;iBAMvD,uBACd,OAAO,YACP,gBACA,QAAQ"}
|
package/dist/instances/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { clearInstanceOverrides, getInstanceOverride, hasInstanceOverride as hasInstanceOverride$1, setInstanceOverride } from "./overrides.js";
|
|
1
|
+
import { clearInstanceOverrides, cloneInstanceOverrideState, getInstanceOverride, hasInstanceOverride as hasInstanceOverride$1, setInstanceOverride } from "./overrides.js";
|
|
2
2
|
import { findInstanceAncestor, instanceMainComponent } from "./main-component.js";
|
|
3
3
|
import { detachOwnedSlotContent, restoreOwnedSlotContent } from "../slots/frames.js";
|
|
4
4
|
import { applyBoundPaintColorsIn, keepCopyBoundPaints } from "../variables/paints.js";
|
|
@@ -6,7 +6,9 @@ import { keepOwnContentSize } from "./content-size.js";
|
|
|
6
6
|
import { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from "./copies.js";
|
|
7
7
|
import { canCreateInstance, createsComponentCycle, cycleSafeParent } from "./cycles.js";
|
|
8
8
|
import { INSTANCE_FOLLOWED_FIELDS, INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS, INSTANCE_SYNC_TEXT_PROPS } from "./fields.js";
|
|
9
|
-
import { bindingProtection,
|
|
9
|
+
import { bindingProtection, enclosingInstanceOverrideFields, isProtectedSyncField, syncBindingFields } from "./protection.js";
|
|
10
|
+
import { walkInstanceSources } from "./source-walk.js";
|
|
11
|
+
import { cloneChildrenWithMapping, copyProp, sourceInTargetCoordinates, syncChildren, updateSyncedProps } from "./sync.js";
|
|
10
12
|
import { followComponentLayers } from "./swap.js";
|
|
11
13
|
//#region src/instances/index.ts
|
|
12
14
|
function copyInstanceComponentProps(component) {
|
|
@@ -140,11 +142,46 @@ function syncInstancesOf(graph, componentId, instances) {
|
|
|
140
142
|
function detachInstance(graph, instanceId) {
|
|
141
143
|
const node = graph.nodes.get(instanceId);
|
|
142
144
|
if (node?.type !== "INSTANCE") return;
|
|
145
|
+
for (const nested of outermostNestedInstances(graph, node)) adoptNestedOverrides(graph, node, nested);
|
|
143
146
|
if (node.componentId) graph.instanceIndex.get(node.componentId)?.delete(instanceId);
|
|
144
147
|
node.type = "FRAME";
|
|
145
148
|
node.componentId = null;
|
|
146
149
|
clearInstanceOverrides(node.instanceOverrides);
|
|
147
150
|
}
|
|
151
|
+
const OWNER_ONLY_FIELDS = /* @__PURE__ */ new Set(["componentId", "sourceComponentId"]);
|
|
152
|
+
function outermostNestedInstances(graph, instance) {
|
|
153
|
+
return graph.getChildren(instance.id).flatMap((child) => child.type === "INSTANCE" ? [child] : outermostNestedInstances(graph, child));
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* An instance a detached one holds stands on its own once that one is a frame, and so must what
|
|
157
|
+
* makes it differ from its component. Cloned in, it kept the overrides of the instance it copies,
|
|
158
|
+
* under that instance's layers; those, and the ones the detached instance recorded on its layers,
|
|
159
|
+
* now go under its own.
|
|
160
|
+
*/
|
|
161
|
+
function adoptNestedOverrides(graph, detached, nested) {
|
|
162
|
+
const ownLayer = /* @__PURE__ */ new Map();
|
|
163
|
+
walkInstanceSources(graph, nested, (source, target) => {
|
|
164
|
+
ownLayer.set(source.id, target.id);
|
|
165
|
+
return true;
|
|
166
|
+
});
|
|
167
|
+
const { self, descendants: kept } = cloneInstanceOverrideState(nested.instanceOverrides);
|
|
168
|
+
const outer = cloneInstanceOverrideState(detached.instanceOverrides).descendants;
|
|
169
|
+
const descendants = /* @__PURE__ */ new Map();
|
|
170
|
+
const claim = (layerId, fields) => {
|
|
171
|
+
const merged = descendants.get(layerId);
|
|
172
|
+
if (!merged) descendants.set(layerId, fields);
|
|
173
|
+
else for (const [field, value] of fields) merged.set(field, value);
|
|
174
|
+
};
|
|
175
|
+
for (const [layerId, fields] of kept) if (ownLayer.has(layerId)) claim(ownLayer.get(layerId) ?? layerId, fields);
|
|
176
|
+
for (const [layerId, fields] of kept) if (!ownLayer.has(layerId)) claim(layerId, fields);
|
|
177
|
+
for (const [layerId, fields] of outer) if (layerId === nested.id) {
|
|
178
|
+
for (const [field, value] of fields) if (!OWNER_ONLY_FIELDS.has(field)) self.set(field, value);
|
|
179
|
+
} else if (graph.isDescendant(layerId, nested.id)) claim(layerId, fields);
|
|
180
|
+
graph.updateNode(nested.id, { instanceOverrides: {
|
|
181
|
+
self,
|
|
182
|
+
descendants
|
|
183
|
+
} });
|
|
184
|
+
}
|
|
148
185
|
function getMainComponent(graph, instanceId) {
|
|
149
186
|
const node = graph.nodes.get(instanceId);
|
|
150
187
|
if (!node?.componentId) return void 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/index.ts"],"sourcesContent":["import type { NodeCloneMode } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport {\n detachOwnedSlotContent,\n restoreOwnedSlotContent,\n type ParkedSlotContent\n} from '../slots/frames'\nimport type { SceneNode } from '../types'\nimport { applyBoundPaintColorsIn, keepCopyBoundPaints } from '../variables/paints'\nimport { keepOwnContentSize } from './content-size'\nimport { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from './copies'\nimport { canCreateInstance } from './cycles'\nimport { INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_PROPS } from './fields'\nimport { findInstanceAncestor, instanceMainComponent } from './main-component'\nimport {\n clearInstanceOverrides,\n getInstanceOverride,\n hasInstanceOverride as hasNodeInstanceOverride,\n setInstanceOverride\n} from './overrides'\nimport { followComponentLayers } from './swap'\nimport {\n bindingProtection,\n cloneChildrenWithMapping,\n copyProp,\n enclosingInstanceOverrideFields,\n isProtectedSyncField,\n sourceInTargetCoordinates,\n syncBindingFields,\n syncChildren,\n updateSyncedProps\n} from './sync'\n\nexport { canCreateInstance, createsComponentCycle, cycleSafeParent } from './cycles'\nexport { findInstanceAncestor, instanceMainComponent } from './main-component'\nexport {\n INSTANCE_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_FIELDS,\n INSTANCE_SYNC_PROPS,\n INSTANCE_SYNC_TEXT_PROPS\n} from './fields'\n\nexport function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {\n const props: Partial<SceneNode> = {}\n for (const key of INSTANCE_SYNC_PROPS) copyProp(props, component, key)\n return props\n}\n\nexport function createInstance(\n graph: SceneGraph,\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n): SceneNode | null {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))\n return null\n\n const props: Partial<SceneNode> = {\n ...copyInstanceComponentProps(component),\n name: component.name\n }\n\n // The component checked above is the one the instance shows, whatever `overrides` holds.\n const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })\n\n cloneChildrenWithMapping(graph, component.id, instance.id)\n // A copy shows its bound paints in its own context, not as its component's paints hold them.\n applyBoundPaintColorsIn(graph, instance.id)\n\n return instance\n}\n\nexport function populateInstanceChildren(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || !component || instance.type !== 'INSTANCE') return\n cloneChildrenWithMapping(graph, componentId, instanceId, mode)\n}\n\n/**\n * A nested instance's link to the enclosing component's record is its `componentId` when it\n * was populated by cloning. A swap replaces that field, so keep the correspondence as the\n * owner's `sourceComponentId` override and record the swap itself; materialized documents\n * already carry the correspondence and only gain the swap.\n */\nfunction recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {\n const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined\n if (!owner) return\n const existing = getInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId'\n )\n if (typeof existing !== 'string' && instance.componentId)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId',\n instance.componentId\n )\n setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, 'componentId', componentId)\n graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })\n}\n\nexport interface SwapInstanceOptions {\n /**\n * Keep the instance's name even when it is its old component's. A swap otherwise renames such\n * an instance after the new component, as Figma does; a view that only shows another variant,\n * such as preview, keeps names so layer paths stay the same.\n */\n keepName?: boolean\n}\n\nfunction namedAfter(\n graph: SceneGraph,\n instance: SceneNode,\n component: SceneNode\n): SceneNode | undefined {\n const main = instanceMainComponent(graph, instance)\n const set = main?.parentId ? graph.nodes.get(main.parentId) : undefined\n if (set?.type === 'COMPONENT_SET' && component.parentId === set.id) {\n return main\n }\n return instance.componentId ? graph.nodes.get(instance.componentId) : undefined\n}\n\nexport function swapInstanceComponent(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n { keepName = false }: SwapInstanceOptions = {}\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return\n if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return\n\n const previousComponent = namedAfter(graph, instance, component)\n recordNestedSwap(graph, instance, componentId)\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const updates: Partial<SceneNode> = {\n componentId,\n ...ownSyncedProps(graph, instance, source).updates\n }\n\n if (!keepName && (!previousComponent || instance.name === previousComponent.name))\n updates.name = component.name\n\n keepCopyBoundPaints(graph, instance, updates)\n const slotContent = detachOwnedSlotContent(graph, instance)\n graph.updateNode(instanceId, updates)\n followComponentLayers(graph, instance, component, parkedContent(slotContent))\n restoreOwnedSlotContent(graph, instance, slotContent)\n}\n\nconst NOTHING_PARKED: ReadonlySet<string> = new Set()\n\nfunction parkedContent(parked: ParkedSlotContent): ReadonlySet<string> {\n if (parked.slots.length === 0) {\n return NOTHING_PARKED\n }\n return new Set(parked.slots.flatMap((slot) => slot.content))\n}\n\n/** What an instance takes from its component, and which fields it keeps as its own. */\nfunction ownSyncedProps(\n graph: SceneGraph,\n instance: SceneNode,\n source: SceneNode\n): { updates: Partial<SceneNode>; kept: (field: string) => boolean } {\n const enclosing = enclosingInstanceOverrideFields(graph, instance)\n enclosing.push(new Set(instance.instanceOverrides.self.keys()))\n const protectedField = bindingProtection(enclosing)\n const updates: Partial<SceneNode> = {}\n syncBindingFields(instance, source, updates, protectedField)\n const kept = (key: string) => isProtectedSyncField(instance, key, protectedField)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key !== 'boundVariables' && !kept(key)) {\n copyProp(updates, source, key)\n }\n }\n return { updates, kept }\n}\n\nconst syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()\n\nexport function syncInstances(graph: SceneGraph, componentId: string): void {\n syncInstancesOf(graph, componentId, getInstances(graph, componentId))\n}\n\n/**\n * Syncs each component's instances, in order, as one edit: the copies they remove stay\n * restorable together for as long as undo keeps that edit.\n */\nexport function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {\n groupCopyRemovals(graph, () => {\n for (const id of componentIds) syncInstances(graph, id)\n })\n}\n\n/** Syncs one instance from its component, as `syncInstances` does for every instance. */\nexport function syncInstance(graph: SceneGraph, instanceId: string): void {\n const instance = graph.nodes.get(instanceId)\n if (instance?.type !== 'INSTANCE' || !instance.componentId) return\n syncInstancesOf(graph, instance.componentId, [instance])\n}\n\nfunction syncInstancesOf(\n graph: SceneGraph,\n componentId: string,\n instances: Iterable<SceneNode>\n): void {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT') return\n let syncing = syncingComponentsByGraph.get(graph)\n if (!syncing) {\n syncing = new Set()\n syncingComponentsByGraph.set(graph, syncing)\n }\n if (syncing.has(componentId)) return\n syncing.add(componentId)\n try {\n groupCopyRemovals(graph, (removals) => {\n for (const instance of instances) {\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const { updates, kept } = ownSyncedProps(graph, instance, source)\n // An instance that hugs its layers sizes to what it shows, not to the component.\n keepOwnContentSize(graph, updates, instance, source)\n updateSyncedProps(graph, instance, updates, kept)\n const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)\n syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)\n removeLeftoverCopies(graph, context, removals)\n }\n })\n } finally {\n syncing.delete(componentId)\n }\n}\n\nexport function detachInstance(graph: SceneGraph, instanceId: string): void {\n const node = graph.nodes.get(instanceId)\n if (node?.type !== 'INSTANCE') return\n if (node.componentId) {\n graph.instanceIndex.get(node.componentId)?.delete(instanceId)\n }\n node.type = 'FRAME'\n node.componentId = null\n clearInstanceOverrides(node.instanceOverrides)\n}\n\nexport function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {\n const node = graph.nodes.get(instanceId)\n if (!node?.componentId) return undefined\n return graph.nodes.get(node.componentId)\n}\n\nexport function getInstances(graph: SceneGraph, componentId: string): SceneNode[] {\n const ids = graph.instanceIndex.get(componentId)\n if (!ids) return []\n const instances: SceneNode[] = []\n for (const id of ids) {\n const node = graph.nodes.get(id)\n if (node) instances.push(node)\n }\n return instances\n}\n\n/**\n * True when a node field is protected from instance synchronization.\n */\nexport function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return false\n return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\nexport function recordInstanceOverride(\n graph: SceneGraph,\n nodeId: string,\n fields: Iterable<string>\n): void {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return\n\n const relevant = [...fields].filter((field) =>\n (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field)\n )\n\n if (relevant.length === 0) return\n\n graph.willChangeNode(instance)\n for (const field of relevant)\n setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })\n}\n"],"mappings":";;;;;;;;;;;AA2CA,SAAgB,2BAA2B,WAA0C;CACnF,MAAM,QAA4B,CAAC;CACnC,KAAK,MAAM,OAAO,qBAAqB,SAAS,OAAO,WAAW,GAAG;CACrE,OAAO;AACT;AAEA,SAAgB,eACd,OACA,aACA,UACA,YAAgC,CAAC,GACf;CAClB,MAAM,YAAY,MAAM,MAAM,IAAI,WAAW;CAC7C,IAAI,WAAW,SAAS,eAAe,CAAC,kBAAkB,OAAO,aAAa,QAAQ,GACpF,OAAO;CAET,MAAM,QAA4B;EAChC,GAAG,2BAA2B,SAAS;EACvC,MAAM,UAAU;CAClB;CAGA,MAAM,WAAW,MAAM,WAAW,YAAY,UAAU;EAAE,GAAG;EAAO,GAAG;EAAW;CAAY,CAAC;CAE/F,yBAAyB,OAAO,UAAU,IAAI,SAAS,EAAE;CAEzD,wBAAwB,OAAO,SAAS,EAAE;CAE1C,OAAO;AACT;AAEA,SAAgB,yBACd,OACA,YACA,aACA,OAAsB,QAChB;CACN,MAAM,WAAW,MAAM,MAAM,IAAI,UAAU;CAC3C,MAAM,YAAY,MAAM,MAAM,IAAI,WAAW;CAC7C,IAAI,CAAC,YA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AAI,CAAC,MAAM,aAAa,OAAO,KAAA;CAC/B,OAAO,MAAM,MAAM,IAAI,KAAK,WAAW;AACzC;AAEA,SAAgB,aAAa,OAAmB,aAAkC;CAChF,MAAM,MAAM,MAAM,cAAc,IAAI,WAAW;CAC/C,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,MAAM,YAAyB,CAAC;CAChC,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,OAAO,MAAM,MAAM,IAAI,EAAE;EAC/B,IAAI,MAAM,UAAU,KAAK,IAAI;CAC/B;CACA,OAAO;AACT;;;;AAKA,SAAgB,oBAAoB,OAAmB,QAAgB,OAAwB;CAC7F,MAAM,WAAW,qBAAqB,OAAO,MAAM;CACnD,IAAI,CAAC,UAAU,OAAO;CACtB,OAAOA,sBAAwB,SAAS,mBAAmB,SAAS,IAAI,QAAQ,KAAK;AACvF;AAEA,SAAgB,uBACd,OACA,QACA,QACM;CACN,MAAM,WAAW,qBAAqB,OAAO,MAAM;CACnD,IAAI,CAAC,UAAU;CAEf,MAAM,WAAW,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,UAClC,yBAA+C,SAAS,KAAK,CAChE;CAEA,IAAI,SAAS,WAAW,GAAG;CAE3B,MAAM,eAAe,QAAQ;CAC7B,KAAK,MAAM,SAAS,UAClB,oBAAoB,SAAS,mBAAmB,SAAS,IAAI,QAAQ,KAAK;CAC5E,MAAM,WAAW,SAAS,IAAI,EAAE,mBAAmB,SAAS,kBAAkB,CAAC;AACjF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["hasNodeInstanceOverride"],"sources":["../../src/instances/index.ts"],"sourcesContent":["import type { NodeCloneMode } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport {\n detachOwnedSlotContent,\n restoreOwnedSlotContent,\n type ParkedSlotContent\n} from '../slots/frames'\nimport type { SceneNode } from '../types'\nimport { applyBoundPaintColorsIn, keepCopyBoundPaints } from '../variables/paints'\nimport { keepOwnContentSize } from './content-size'\nimport { createInstanceSyncContext, groupCopyRemovals, removeLeftoverCopies } from './copies'\nimport { canCreateInstance } from './cycles'\nimport { INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_PROPS } from './fields'\nimport { findInstanceAncestor, instanceMainComponent } from './main-component'\nimport {\n clearInstanceOverrides,\n cloneInstanceOverrideState,\n getInstanceOverride,\n hasInstanceOverride as hasNodeInstanceOverride,\n setInstanceOverride\n} from './overrides'\nimport {\n bindingProtection,\n enclosingInstanceOverrideFields,\n isProtectedSyncField,\n syncBindingFields\n} from './protection'\nimport { walkInstanceSources } from './source-walk'\nimport { followComponentLayers } from './swap'\nimport {\n cloneChildrenWithMapping,\n copyProp,\n sourceInTargetCoordinates,\n syncChildren,\n updateSyncedProps\n} from './sync'\n\nexport { canCreateInstance, createsComponentCycle, cycleSafeParent } from './cycles'\nexport { findInstanceAncestor, instanceMainComponent } from './main-component'\nexport {\n INSTANCE_FOLLOWED_FIELDS,\n INSTANCE_OVERRIDE_FIELDS,\n INSTANCE_SYNC_FIELDS,\n INSTANCE_SYNC_PROPS,\n INSTANCE_SYNC_TEXT_PROPS\n} from './fields'\n\nexport function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {\n const props: Partial<SceneNode> = {}\n for (const key of INSTANCE_SYNC_PROPS) copyProp(props, component, key)\n return props\n}\n\nexport function createInstance(\n graph: SceneGraph,\n componentId: string,\n parentId: string,\n overrides: Partial<SceneNode> = {}\n): SceneNode | null {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT' || !canCreateInstance(graph, componentId, parentId))\n return null\n\n const props: Partial<SceneNode> = {\n ...copyInstanceComponentProps(component),\n name: component.name\n }\n\n // The component checked above is the one the instance shows, whatever `overrides` holds.\n const instance = graph.createNode('INSTANCE', parentId, { ...props, ...overrides, componentId })\n\n cloneChildrenWithMapping(graph, component.id, instance.id)\n // A copy shows its bound paints in its own context, not as its component's paints hold them.\n applyBoundPaintColorsIn(graph, instance.id)\n\n return instance\n}\n\nexport function populateInstanceChildren(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n mode: NodeCloneMode = 'deep'\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || !component || instance.type !== 'INSTANCE') return\n cloneChildrenWithMapping(graph, componentId, instanceId, mode)\n}\n\n/**\n * A nested instance's link to the enclosing component's record is its `componentId` when it\n * was populated by cloning. A swap replaces that field, so keep the correspondence as the\n * owner's `sourceComponentId` override and record the swap itself; materialized documents\n * already carry the correspondence and only gain the swap.\n */\nfunction recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: string): void {\n const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : undefined\n if (!owner) return\n const existing = getInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId'\n )\n if (typeof existing !== 'string' && instance.componentId)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n instance.id,\n 'sourceComponentId',\n instance.componentId\n )\n setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, 'componentId', componentId)\n graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })\n}\n\nexport interface SwapInstanceOptions {\n /**\n * Keep the instance's name even when it is its old component's. A swap otherwise renames such\n * an instance after the new component, as Figma does; a view that only shows another variant,\n * such as preview, keeps names so layer paths stay the same.\n */\n keepName?: boolean\n}\n\nfunction namedAfter(\n graph: SceneGraph,\n instance: SceneNode,\n component: SceneNode\n): SceneNode | undefined {\n const main = instanceMainComponent(graph, instance)\n const set = main?.parentId ? graph.nodes.get(main.parentId) : undefined\n if (set?.type === 'COMPONENT_SET' && component.parentId === set.id) {\n return main\n }\n return instance.componentId ? graph.nodes.get(instance.componentId) : undefined\n}\n\nexport function swapInstanceComponent(\n graph: SceneGraph,\n instanceId: string,\n componentId: string,\n { keepName = false }: SwapInstanceOptions = {}\n): void {\n const instance = graph.nodes.get(instanceId)\n const component = graph.nodes.get(componentId)\n if (!instance || component?.type !== 'COMPONENT' || instance.type !== 'INSTANCE') return\n if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return\n\n const previousComponent = namedAfter(graph, instance, component)\n recordNestedSwap(graph, instance, componentId)\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const updates: Partial<SceneNode> = {\n componentId,\n ...ownSyncedProps(graph, instance, source).updates\n }\n\n if (!keepName && (!previousComponent || instance.name === previousComponent.name))\n updates.name = component.name\n\n keepCopyBoundPaints(graph, instance, updates)\n const slotContent = detachOwnedSlotContent(graph, instance)\n graph.updateNode(instanceId, updates)\n followComponentLayers(graph, instance, component, parkedContent(slotContent))\n restoreOwnedSlotContent(graph, instance, slotContent)\n}\n\nconst NOTHING_PARKED: ReadonlySet<string> = new Set()\n\nfunction parkedContent(parked: ParkedSlotContent): ReadonlySet<string> {\n if (parked.slots.length === 0) {\n return NOTHING_PARKED\n }\n return new Set(parked.slots.flatMap((slot) => slot.content))\n}\n\n/** What an instance takes from its component, and which fields it keeps as its own. */\nfunction ownSyncedProps(\n graph: SceneGraph,\n instance: SceneNode,\n source: SceneNode\n): { updates: Partial<SceneNode>; kept: (field: string) => boolean } {\n const enclosing = enclosingInstanceOverrideFields(graph, instance)\n enclosing.push(new Set(instance.instanceOverrides.self.keys()))\n const protectedField = bindingProtection(enclosing)\n const updates: Partial<SceneNode> = {}\n syncBindingFields(instance, source, updates, protectedField)\n const kept = (key: string) => isProtectedSyncField(instance, key, protectedField)\n for (const key of INSTANCE_SYNC_PROPS) {\n if (key !== 'boundVariables' && !kept(key)) {\n copyProp(updates, source, key)\n }\n }\n return { updates, kept }\n}\n\nconst syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()\n\nexport function syncInstances(graph: SceneGraph, componentId: string): void {\n syncInstancesOf(graph, componentId, getInstances(graph, componentId))\n}\n\n/**\n * Syncs each component's instances, in order, as one edit: the copies they remove stay\n * restorable together for as long as undo keeps that edit.\n */\nexport function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {\n groupCopyRemovals(graph, () => {\n for (const id of componentIds) syncInstances(graph, id)\n })\n}\n\n/** Syncs one instance from its component, as `syncInstances` does for every instance. */\nexport function syncInstance(graph: SceneGraph, instanceId: string): void {\n const instance = graph.nodes.get(instanceId)\n if (instance?.type !== 'INSTANCE' || !instance.componentId) return\n syncInstancesOf(graph, instance.componentId, [instance])\n}\n\nfunction syncInstancesOf(\n graph: SceneGraph,\n componentId: string,\n instances: Iterable<SceneNode>\n): void {\n const component = graph.nodes.get(componentId)\n if (component?.type !== 'COMPONENT') return\n let syncing = syncingComponentsByGraph.get(graph)\n if (!syncing) {\n syncing = new Set()\n syncingComponentsByGraph.set(graph, syncing)\n }\n if (syncing.has(componentId)) return\n syncing.add(componentId)\n try {\n groupCopyRemovals(graph, (removals) => {\n for (const instance of instances) {\n const source = sourceInTargetCoordinates(component, instance.componentScale)\n const { updates, kept } = ownSyncedProps(graph, instance, source)\n // An instance that hugs its layers sizes to what it shows, not to the component.\n keepOwnContentSize(graph, updates, instance, source)\n updateSyncedProps(graph, instance, updates, kept)\n const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)\n syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)\n removeLeftoverCopies(graph, context, removals)\n }\n })\n } finally {\n syncing.delete(componentId)\n }\n}\n\nexport function detachInstance(graph: SceneGraph, instanceId: string): void {\n const node = graph.nodes.get(instanceId)\n if (node?.type !== 'INSTANCE') return\n for (const nested of outermostNestedInstances(graph, node))\n adoptNestedOverrides(graph, node, nested)\n if (node.componentId) {\n graph.instanceIndex.get(node.componentId)?.delete(instanceId)\n }\n node.type = 'FRAME'\n node.componentId = null\n clearInstanceOverrides(node.instanceOverrides)\n}\n\n// A swap's bookkeeping belongs to the instance enclosing the swapped one, never to the swapped one.\nconst OWNER_ONLY_FIELDS = new Set(['componentId', 'sourceComponentId'])\n\nfunction outermostNestedInstances(graph: SceneGraph, instance: SceneNode): SceneNode[] {\n return graph\n .getChildren(instance.id)\n .flatMap((child) =>\n child.type === 'INSTANCE' ? [child] : outermostNestedInstances(graph, child)\n )\n}\n\n/**\n * An instance a detached one holds stands on its own once that one is a frame, and so must what\n * makes it differ from its component. Cloned in, it kept the overrides of the instance it copies,\n * under that instance's layers; those, and the ones the detached instance recorded on its layers,\n * now go under its own.\n */\nfunction adoptNestedOverrides(graph: SceneGraph, detached: SceneNode, nested: SceneNode): void {\n const ownLayer = new Map<string, string>()\n walkInstanceSources(graph, nested, (source, target) => {\n ownLayer.set(source.id, target.id)\n return true\n })\n const { self, descendants: kept } = cloneInstanceOverrideState(nested.instanceOverrides)\n const outer = cloneInstanceOverrideState(detached.instanceOverrides).descendants\n const descendants = new Map<string, Map<string, unknown>>()\n const claim = (layerId: string, fields: Map<string, unknown>): void => {\n const merged = descendants.get(layerId)\n if (!merged) descendants.set(layerId, fields)\n else for (const [field, value] of fields) merged.set(field, value)\n }\n // What was recorded on its own layers is more recent than what it copied, so it is laid on top.\n for (const [layerId, fields] of kept)\n if (ownLayer.has(layerId)) claim(ownLayer.get(layerId) ?? layerId, fields)\n for (const [layerId, fields] of kept) if (!ownLayer.has(layerId)) claim(layerId, fields)\n for (const [layerId, fields] of outer) {\n if (layerId === nested.id) {\n for (const [field, value] of fields) if (!OWNER_ONLY_FIELDS.has(field)) self.set(field, value)\n } else if (graph.isDescendant(layerId, nested.id)) claim(layerId, fields)\n }\n graph.updateNode(nested.id, { instanceOverrides: { self, descendants } })\n}\n\nexport function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {\n const node = graph.nodes.get(instanceId)\n if (!node?.componentId) return undefined\n return graph.nodes.get(node.componentId)\n}\n\nexport function getInstances(graph: SceneGraph, componentId: string): SceneNode[] {\n const ids = graph.instanceIndex.get(componentId)\n if (!ids) return []\n const instances: SceneNode[] = []\n for (const id of ids) {\n const node = graph.nodes.get(id)\n if (node) instances.push(node)\n }\n return instances\n}\n\n/**\n * True when a node field is protected from instance synchronization.\n */\nexport function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: string): boolean {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return false\n return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n}\n\nexport function recordInstanceOverride(\n graph: SceneGraph,\n nodeId: string,\n fields: Iterable<string>\n): void {\n const instance = findInstanceAncestor(graph, nodeId)\n if (!instance) return\n\n const relevant = [...fields].filter((field) =>\n (INSTANCE_OVERRIDE_FIELDS as readonly string[]).includes(field)\n )\n\n if (relevant.length === 0) return\n\n graph.willChangeNode(instance)\n for (const field of relevant)\n setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)\n graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })\n}\n"],"mappings":";;;;;;;;;;;;;AA+CA,SAAgB,2BAA2B,WAA0C;CACnF,MAAM,QAA4B,CAAC;CACnC,KAAK,MAAM,OAAO,qBAAqB,SAAS,OAAO,WAAW,GAAG;CACrE,OAAO;AACT;AAEA,SAAgB,eACd,OACA,aACA,UACA,YAAgC,CAAC,GACf;CAClB,MAAM,YAAY,MAAM,MAAM,IAAI,WAAW;CAC7C,IAAI,WAAW,SAAS,eAAe,CAAC,kBAAkB,OAAO,aAAa,QAAQ,GACpF,OAAO;CAET,MAAM,QAA4B;EAChC,GAAG,2BAA2B,SAAS;EACvC,MAAM,UAAU;CAClB;CAGA,MAAM,WAAW,MAAM,WAAW,YAAY,UAAU;EAAE,GAAG;EAAO,GAAG;EAAW;CAAY,CAAC;CAE/F,yBAAyB,OAAO,UAAU,IAAI,SAAS,EAAE;CAEzD,wBAAwB,OAAO,SAAS,EAAE;CAE1C,OAAO;AACT;AAEA,SAAgB,yBACd,OACA,YACA,aACA,OAAsB,QAChB;CACN,MAAM,WAAW,MAAM,MAAM,IAAI,UAAU;CAC3C,MAAM,YAAY,MAAM,MAAM,IAAI,WAAW;CAC7C,IAAI,CAAC,YAAY,CAAC,aAAa,SAAS,SAAS,YAAY;CAC7D,yBAAyB,OAAO,aAAa,YAAY,IAAI;AAC/D;;;;;;;AAQ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,OAAO,MAAM,MAAM,IAAI,UAAU;CACvC,IAAI,CAAC,MAAM,aAAa,OAAO,KAAA;CAC/B,OAAO,MAAM,MAAM,IAAI,KAAK,WAAW;AACzC;AAEA,SAAgB,aAAa,OAAmB,aAAkC;CAChF,MAAM,MAAM,MAAM,cAAc,IAAI,WAAW;CAC/C,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,MAAM,YAAyB,CAAC;CAChC,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,OAAO,MAAM,MAAM,IAAI,EAAE;EAC/B,IAAI,MAAM,UAAU,KAAK,IAAI;CAC/B;CACA,OAAO;AACT;;;;AAKA,SAAgB,oBAAoB,OAAmB,QAAgB,OAAwB;CAC7F,MAAM,WAAW,qBAAqB,OAAO,MAAM;CACnD,IAAI,CAAC,UAAU,OAAO;CACtB,OAAOA,sBAAwB,SAAS,mBAAmB,SAAS,IAAI,QAAQ,KAAK;AACvF;AAEA,SAAgB,uBACd,OACA,QACA,QACM;CACN,MAAM,WAAW,qBAAqB,OAAO,MAAM;CACnD,IAAI,CAAC,UAAU;CAEf,MAAM,WAAW,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,UAClC,yBAA+C,SAAS,KAAK,CAChE;CAEA,IAAI,SAAS,WAAW,GAAG;CAE3B,MAAM,eAAe,QAAQ;CAC7B,KAAK,MAAM,SAAS,UAClB,oBAAoB,SAAS,mBAAmB,SAAS,IAAI,QAAQ,KAAK;CAC5E,MAAM,WAAW,SAAS,IAAI,EAAE,mBAAmB,SAAS,kBAAkB,CAAC;AACjF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { overriddenBindingField } from "./overrides.js";
|
|
1
|
+
import { overriddenAssignmentId, overriddenBindingField } from "./overrides.js";
|
|
2
2
|
import { instanceMainComponent } from "./main-component.js";
|
|
3
|
-
import {
|
|
3
|
+
import { reapplyComponentPropertyAssignments } from "../components/properties.js";
|
|
4
4
|
import { omit } from "es-toolkit/object";
|
|
5
5
|
import { isEqual } from "es-toolkit/predicate";
|
|
6
6
|
//#region src/instances/kept-overrides.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kept-overrides.js","names":[],"sources":["../../src/instances/kept-overrides.ts"],"sourcesContent":["// Overrides a variant switch keeps for the layers it removes, to give back to the next copies.\nimport { omit } from 'es-toolkit/object'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport {\n overriddenAssignmentId,\n reapplyComponentPropertyAssignments\n} from '../components/properties'\nimport type { SceneGraph } from '../graph'\nimport type { SceneNode } from '../types'\nimport { instanceMainComponent } from './main-component'\nimport { overriddenBindingField } from './overrides'\n\n/** Where a switch runs: the switched instance and the instances enclosing the layers it changes. */\nexport interface OverrideScope {\n graph: SceneGraph\n instance: SceneNode\n owners: readonly SceneNode[]\n /** Reports an owner before its override maps are written into. */\n willChange(owner: SceneNode): void\n}\n\n/**\n * An instance that holds overrides on a layer: one enclosing the switch, by ID, or one inside\n * the removed copy, by its path, since a new copy of it gets a new ID.\n */\ntype OwnerRef = { id: string } | { path: string }\n\n/** What one owner overrides on a layer, with the values the layer showed. */\ninterface KeptOverrides {\n owner: OwnerRef\n /** The owner's own fields, for a nested instance's overrides on itself. */\n self: boolean\n fields: Map<string, unknown>\n values: Partial<SceneNode>\n /** Bindings the overrides claim, with their unit scales; an absent variable claims none. */\n bindings: Record<string, { variableId: string | undefined; scale: number | undefined }>\n /** Set when the overrides claim every binding, as removing a variable records. */\n allBindings?: { boundVariables: SceneNode['boundVariables']; scales: Scales }\n /** The component a nested instance was switched to, which its new copy is switched to again. */\n swappedTo?: string\n /** Property values the overrides claim on a nested instance. */\n assignments: Record<string, string>\n}\n\ntype Scales = SceneNode['variableBindingScales']\n\n/** Override fields that link a copy to its layer, which a new copy gets from its own layer. */\nconst LINK_FIELDS: ReadonlySet<string> = new Set(['sourceComponentId', 'componentId'])\n\n/**\n * Overrides on layers a switch removed, by switched instance and then by the layer's path from\n * it: each step's name and its order among the same-named layers beside it, the way a switch\n * pairs layers. Figma brings them back when the instance switches to a variant that draws the\n * layer again, though its saved records keep none of them while the layer is gone (desktop\n * 126), so they live with the open document only.\n */\nconst keptByGraph = new WeakMap<SceneGraph, Map<string, Map<string, KeptOverrides[]>>>()\n\nfunction keptFor(scope: OverrideScope, create: true): Map<string, KeptOverrides[]>\nfunction keptFor(scope: OverrideScope, create: false): Map<string, KeptOverrides[]> | undefined\nfunction keptFor(scope: OverrideScope, create: boolean) {\n let byInstance = keptByGraph.get(scope.graph)\n if (!byInstance && create) {\n byInstance = new Map()\n keptByGraph.set(scope.graph, byInstance)\n }\n let byPath = byInstance?.get(scope.instance.id)\n if (!byPath && byInstance && create) {\n byPath = new Map()\n byInstance.set(scope.instance.id, byPath)\n }\n return byPath\n}\n\n/** A layer's path from the switched instance, by names and their order among namesakes. */\nfunction layerPath(scope: OverrideScope, node: SceneNode): string | undefined {\n const steps: string[] = []\n let current = node\n while (current.id !== scope.instance.id) {\n const parent: SceneNode | undefined = current.parentId\n ? scope.graph.getNode(current.parentId)\n : undefined\n if (!parent) return undefined\n let ordinal = 0\n for (const id of parent.childIds) {\n if (id === current.id) break\n if (scope.graph.getNode(id)?.name === current.name) ordinal++\n }\n steps.push(`${current.name}\\u0000${ordinal}`)\n current = parent\n }\n return steps.reverse().join('\\u0001')\n}\n\nfunction snapshot(\n graph: SceneGraph,\n node: SceneNode,\n owner: OwnerRef,\n self: boolean,\n fields: ReadonlyMap<string, unknown>\n): KeptOverrides | undefined {\n const kept = new Map([...fields].filter(([field]) => !LINK_FIELDS.has(field)))\n // A swap is kept as the component it shows; the new copy records it again when switched.\n const swappedTo =\n fields.has('componentId') && node.type === 'INSTANCE'\n ? instanceMainComponent(graph, node)?.id\n : undefined\n if (kept.size === 0 && !swappedTo) return undefined\n const values: Partial<SceneNode> = {}\n const bindings: KeptOverrides['bindings'] = {}\n const assignments: Record<string, string> = {}\n for (const field of kept.keys()) {\n const binding = overriddenBindingField(field)\n const assigned = overriddenAssignmentId(field)\n if (assigned !== undefined) {\n if (Object.hasOwn(node.componentPropertyAssignments, assigned))\n assignments[assigned] = node.componentPropertyAssignments[assigned]\n } else if (binding !== null) {\n bindings[binding] = {\n variableId: node.boundVariables[binding],\n scale: node.variableBindingScales[binding]\n }\n } else if (field in node && field !== 'boundVariables') {\n Object.assign(values, { [field]: structuredClone(node[field as keyof SceneNode]) })\n }\n }\n const allBindings = kept.has('boundVariables')\n ? {\n boundVariables: { ...node.boundVariables },\n scales: { ...node.variableBindingScales }\n }\n : undefined\n return { owner, self, fields: kept, values, bindings, allBindings, swappedTo, assignments }\n}\n\n/** Takes the overrides on a layer off its owners, outer ones and those inside the removed copy. */\nfunction takeOverrides(\n scope: OverrideScope,\n node: SceneNode,\n inner: readonly SceneNode[]\n): KeptOverrides[] {\n const taken: KeptOverrides[] = []\n for (const owner of scope.owners) {\n const fields = owner.instanceOverrides.descendants.get(node.id)\n if (!fields) continue\n scope.willChange(owner)\n owner.instanceOverrides.descendants.delete(node.id)\n const kept = snapshot(scope.graph, node, { id: owner.id }, false, fields)\n if (kept) taken.push(kept)\n }\n for (const owner of inner) {\n const fields = owner.instanceOverrides.descendants.get(node.id)\n const path = layerPath(scope, owner)\n const kept = fields && path ? snapshot(scope.graph, node, { path }, false, fields) : undefined\n if (kept) taken.push(kept)\n }\n const ownPath = node.type === 'INSTANCE' ? layerPath(scope, node) : undefined\n const own = ownPath\n ? snapshot(scope.graph, node, { path: ownPath }, true, node.instanceOverrides.self)\n : undefined\n if (own) taken.push(own)\n return taken\n}\n\n/**\n * Keeps what is overridden on a copy and its layers before a switch removes it. A layer\n * removed with nothing overridden clears what an earlier removal kept for its path, so a value\n * the user reset does not come back.\n */\nexport function keepOverrides(\n scope: OverrideScope,\n copy: SceneNode,\n inner: readonly SceneNode[] = []\n): void {\n const path = layerPath(scope, copy)\n const taken = takeOverrides(scope, copy, inner)\n if (path && taken.length > 0) keptFor(scope, true).set(path, taken)\n else if (path) keptFor(scope, false)?.delete(path)\n const owners = copy.type === 'INSTANCE' ? [...inner, copy] : inner\n for (const child of scope.graph.getChildren(copy.id)) keepOverrides(scope, child, owners)\n}\n\nfunction ownerOf(scope: OverrideScope, ref: OwnerRef): SceneNode | undefined {\n if ('id' in ref) return scope.owners.find((owner) => owner.id === ref.id)\n let current: SceneNode | undefined = scope.instance\n for (const step of ref.path.split('\\u0001')) {\n const [name, ordinal] = step.split('\\u0000')\n current = current\n ? scope.graph.getChildren(current.id).filter((child) => child.name === name)[Number(ordinal)]\n : undefined\n }\n return current?.type === 'INSTANCE' ? current : undefined\n}\n\n/**\n * Switches a nested instance switched to another variant again first, so what is kept for it\n * and its layers lands on what it then shows. Returns the node as it then stands.\n */\nfunction switchAsKept(scope: OverrideScope, copy: SceneNode, kept: readonly KeptOverrides[]) {\n const swappedTo = kept.find((entry) => entry.swappedTo)?.swappedTo\n if (\n swappedTo &&\n copy.type === 'INSTANCE' &&\n scope.graph.getNode(swappedTo) &&\n instanceMainComponent(scope.graph, copy)?.id !== swappedTo\n ) {\n scope.graph.swapInstanceComponent(copy.id, swappedTo)\n }\n return scope.graph.getNode(copy.id) ?? copy\n}\n\n/** The bindings and unit scales a layer shows with the kept bindings applied over its own. */\nfunction keptBindings(node: SceneNode, kept: readonly KeptOverrides[]) {\n let boundVariables: Record<string, string> = { ...node.boundVariables }\n let scales: Scales = { ...node.variableBindingScales }\n for (const { bindings, allBindings } of kept) {\n if (allBindings) {\n boundVariables = { ...allBindings.boundVariables }\n scales = { ...allBindings.scales }\n }\n for (const [field, { variableId, scale }] of Object.entries(bindings)) {\n boundVariables = variableId\n ? { ...boundVariables, [field]: variableId }\n : omit(boundVariables, [field])\n scales = scale !== undefined ? { ...scales, [field]: scale } : omit(scales, [field])\n }\n }\n return { boundVariables, scales }\n}\n\nfunction giveOverrides(scope: OverrideScope, copy: SceneNode, saved: readonly KeptOverrides[]) {\n // What an owner no longer standing around the copy overrode is not given back at all.\n const resolved = saved.flatMap((entry) => {\n const owner = ownerOf(scope, entry.owner)\n return owner ? [{ entry, owner }] : []\n })\n const kept = resolved.map(({ entry }) => entry)\n const node = switchAsKept(scope, copy, kept)\n const values: Partial<SceneNode> = {}\n for (const { entry, owner } of resolved) {\n const { self, fields, values: shown } = entry\n scope.willChange(owner)\n const own = self\n ? owner.instanceOverrides.self\n : owner.instanceOverrides.descendants.get(node.id)\n const merged = new Map([...(own ?? []), ...fields])\n if (self) owner.instanceOverrides.self = merged\n else owner.instanceOverrides.descendants.set(node.id, merged)\n Object.assign(values, structuredClone(shown))\n }\n const { boundVariables, scales } = keptBindings(node, kept)\n if (!isEqual(boundVariables, node.boundVariables)) values.boundVariables = boundVariables\n if (!isEqual(scales, node.variableBindingScales)) values.variableBindingScales = scales\n const assignments: Record<string, string> = Object.assign(\n {},\n ...kept.map((entry) => entry.assignments)\n )\n const assigns = Object.keys(assignments).length > 0\n if (assigns) {\n values.componentPropertyAssignments = { ...node.componentPropertyAssignments, ...assignments }\n }\n if (Object.keys(values).length > 0) scope.graph.updateNode(node.id, values)\n // The values a nested instance is given show in its layers, as a matched copy's do.\n if (assigns) reapplyComponentPropertyAssignments(scope.graph, node.id)\n}\n\n/** Gives a copy just placed, and its layers, what an earlier switch kept for their paths. */\nexport function restoreOverrides(scope: OverrideScope, copy: SceneNode): void {\n const kept = keptFor(scope, false)\n if (!kept?.size) return\n const restore = (node: SceneNode) => {\n const path = layerPath(scope, node)\n const found = path ? kept.get(path) : undefined\n // Kept, not taken: undoing this switch and switching again gives them back once more.\n if (found) giveOverrides(scope, node, found)\n for (const child of scope.graph.getChildren(node.id)) restore(child)\n }\n restore(copy)\n}\n"],"mappings":";;;;;;;AAgDA,MAAM,8BAAmC,IAAI,IAAI,CAAC,qBAAqB,aAAa,CAAC;;;;;;;;AASrF,MAAM,8BAAc,IAAI,QAA+D;AAIvF,SAAS,QAAQ,OAAsB,QAAiB;CACtD,IAAI,aAAa,YAAY,IAAI,MAAM,KAAK;CAC5C,IAAI,CAAC,cAAc,QAAQ;EACzB,6BAAa,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S,IAAI,IAAI,CAAC,GAAI,OAAO,CAAC,GAAI,GAAG,MAAM,CAAC;EAClD,IAAI,MAAM,MAAM,kBAAkB,OAAO;OACpC,MAAM,kBAAkB,YAAY,IAAI,KAAK,IAAI,MAAM;EAC5D,OAAO,OAAO,QAAQ,gBAAgB,KAAK,CAAC;CAC9C;CACA,MAAM,EAAE,gBAAgB,WAAW,aAAa,MAAM,IAAI;CAC1D,IAAI,CAAC,QAAQ,gBAAgB,KAAK,cAAc,GAAG,OAAO,iBAAiB;CAC3E,IAAI,CAAC,QAAQ,QAAQ,KAAK,qBAAqB,GAAG,OAAO,wBAAwB;CACjF,MAAM,cAAsC,OAAO,OACjD,CAAC,GACD,GAAG,KAAK,KAAK,UAAU,MAAM,WAAW,CAC1C;CACA,MAAM,UAAU,OAAO,KAAK,WAAW,CAAC,CAAC,SAAS;CAClD,IAAI,SACF,OAAO,+BAA+B;EAAE,GAAG,KAAK;EAA8B,GAAG;CAAY;CAE/F,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,GAAG,MAAM,MAAM,WAAW,KAAK,IAAI,MAAM;CAE1E,IAAI,SAAS,oCAAoC,MAAM,OAAO,KAAK,EAAE;AACvE;;AAGA,SAAgB,iBAAiB,OAAsB,MAAuB;CAC5E,MAAM,OAAO,QAAQ,OAAO,KAAK;CACjC,IAAI,CAAC,MAAM,MAAM;CACjB,MAAM,WAAW,SAAoB;EACnC,MAAM,OAAO,UAAU,OAAO,IAAI;EAClC,MAAM,QAAQ,OAAO,KAAK,IAAI,IAAI,IAAI,KAAA;EAEtC,IAAI,OAAO,cAAc,OAAO,MAAM,KAAK;EAC3C,KAAK,MAAM,SAAS,MAAM,MAAM,YAAY,KAAK,EAAE,GAAG,QAAQ,KAAK;CACrE;CACA,QAAQ,IAAI;AACd"}
|
|
1
|
+
{"version":3,"file":"kept-overrides.js","names":[],"sources":["../../src/instances/kept-overrides.ts"],"sourcesContent":["// Overrides a variant switch keeps for the layers it removes, to give back to the next copies.\nimport { omit } from 'es-toolkit/object'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport { reapplyComponentPropertyAssignments } from '../components/properties'\nimport type { SceneGraph } from '../graph'\nimport type { SceneNode } from '../types'\nimport { instanceMainComponent } from './main-component'\nimport { overriddenAssignmentId, overriddenBindingField } from './overrides'\n\n/** Where a switch runs: the switched instance and the instances enclosing the layers it changes. */\nexport interface OverrideScope {\n graph: SceneGraph\n instance: SceneNode\n owners: readonly SceneNode[]\n /** Reports an owner before its override maps are written into. */\n willChange(owner: SceneNode): void\n}\n\n/**\n * An instance that holds overrides on a layer: one enclosing the switch, by ID, or one inside\n * the removed copy, by its path, since a new copy of it gets a new ID.\n */\ntype OwnerRef = { id: string } | { path: string }\n\n/** What one owner overrides on a layer, with the values the layer showed. */\ninterface KeptOverrides {\n owner: OwnerRef\n /** The owner's own fields, for a nested instance's overrides on itself. */\n self: boolean\n fields: Map<string, unknown>\n values: Partial<SceneNode>\n /** Bindings the overrides claim, with their unit scales; an absent variable claims none. */\n bindings: Record<string, { variableId: string | undefined; scale: number | undefined }>\n /** Set when the overrides claim every binding, as removing a variable records. */\n allBindings?: { boundVariables: SceneNode['boundVariables']; scales: Scales }\n /** The component a nested instance was switched to, which its new copy is switched to again. */\n swappedTo?: string\n /** Property values the overrides claim on a nested instance. */\n assignments: Record<string, string>\n}\n\ntype Scales = SceneNode['variableBindingScales']\n\n/** Override fields that link a copy to its layer, which a new copy gets from its own layer. */\nconst LINK_FIELDS: ReadonlySet<string> = new Set(['sourceComponentId', 'componentId'])\n\n/**\n * Overrides on layers a switch removed, by switched instance and then by the layer's path from\n * it: each step's name and its order among the same-named layers beside it, the way a switch\n * pairs layers. Figma brings them back when the instance switches to a variant that draws the\n * layer again, though its saved records keep none of them while the layer is gone (desktop\n * 126), so they live with the open document only.\n */\nconst keptByGraph = new WeakMap<SceneGraph, Map<string, Map<string, KeptOverrides[]>>>()\n\nfunction keptFor(scope: OverrideScope, create: true): Map<string, KeptOverrides[]>\nfunction keptFor(scope: OverrideScope, create: false): Map<string, KeptOverrides[]> | undefined\nfunction keptFor(scope: OverrideScope, create: boolean) {\n let byInstance = keptByGraph.get(scope.graph)\n if (!byInstance && create) {\n byInstance = new Map()\n keptByGraph.set(scope.graph, byInstance)\n }\n let byPath = byInstance?.get(scope.instance.id)\n if (!byPath && byInstance && create) {\n byPath = new Map()\n byInstance.set(scope.instance.id, byPath)\n }\n return byPath\n}\n\n/** A layer's path from the switched instance, by names and their order among namesakes. */\nfunction layerPath(scope: OverrideScope, node: SceneNode): string | undefined {\n const steps: string[] = []\n let current = node\n while (current.id !== scope.instance.id) {\n const parent: SceneNode | undefined = current.parentId\n ? scope.graph.getNode(current.parentId)\n : undefined\n if (!parent) return undefined\n let ordinal = 0\n for (const id of parent.childIds) {\n if (id === current.id) break\n if (scope.graph.getNode(id)?.name === current.name) ordinal++\n }\n steps.push(`${current.name}\\u0000${ordinal}`)\n current = parent\n }\n return steps.reverse().join('\\u0001')\n}\n\nfunction snapshot(\n graph: SceneGraph,\n node: SceneNode,\n owner: OwnerRef,\n self: boolean,\n fields: ReadonlyMap<string, unknown>\n): KeptOverrides | undefined {\n const kept = new Map([...fields].filter(([field]) => !LINK_FIELDS.has(field)))\n // A swap is kept as the component it shows; the new copy records it again when switched.\n const swappedTo =\n fields.has('componentId') && node.type === 'INSTANCE'\n ? instanceMainComponent(graph, node)?.id\n : undefined\n if (kept.size === 0 && !swappedTo) return undefined\n const values: Partial<SceneNode> = {}\n const bindings: KeptOverrides['bindings'] = {}\n const assignments: Record<string, string> = {}\n for (const field of kept.keys()) {\n const binding = overriddenBindingField(field)\n const assigned = overriddenAssignmentId(field)\n if (assigned !== undefined) {\n if (Object.hasOwn(node.componentPropertyAssignments, assigned))\n assignments[assigned] = node.componentPropertyAssignments[assigned]\n } else if (binding !== null) {\n bindings[binding] = {\n variableId: node.boundVariables[binding],\n scale: node.variableBindingScales[binding]\n }\n } else if (field in node && field !== 'boundVariables') {\n Object.assign(values, { [field]: structuredClone(node[field as keyof SceneNode]) })\n }\n }\n const allBindings = kept.has('boundVariables')\n ? {\n boundVariables: { ...node.boundVariables },\n scales: { ...node.variableBindingScales }\n }\n : undefined\n return { owner, self, fields: kept, values, bindings, allBindings, swappedTo, assignments }\n}\n\n/** Takes the overrides on a layer off its owners, outer ones and those inside the removed copy. */\nfunction takeOverrides(\n scope: OverrideScope,\n node: SceneNode,\n inner: readonly SceneNode[]\n): KeptOverrides[] {\n const taken: KeptOverrides[] = []\n for (const owner of scope.owners) {\n const fields = owner.instanceOverrides.descendants.get(node.id)\n if (!fields) continue\n scope.willChange(owner)\n owner.instanceOverrides.descendants.delete(node.id)\n const kept = snapshot(scope.graph, node, { id: owner.id }, false, fields)\n if (kept) taken.push(kept)\n }\n for (const owner of inner) {\n const fields = owner.instanceOverrides.descendants.get(node.id)\n const path = layerPath(scope, owner)\n const kept = fields && path ? snapshot(scope.graph, node, { path }, false, fields) : undefined\n if (kept) taken.push(kept)\n }\n const ownPath = node.type === 'INSTANCE' ? layerPath(scope, node) : undefined\n const own = ownPath\n ? snapshot(scope.graph, node, { path: ownPath }, true, node.instanceOverrides.self)\n : undefined\n if (own) taken.push(own)\n return taken\n}\n\n/**\n * Keeps what is overridden on a copy and its layers before a switch removes it. A layer\n * removed with nothing overridden clears what an earlier removal kept for its path, so a value\n * the user reset does not come back.\n */\nexport function keepOverrides(\n scope: OverrideScope,\n copy: SceneNode,\n inner: readonly SceneNode[] = []\n): void {\n const path = layerPath(scope, copy)\n const taken = takeOverrides(scope, copy, inner)\n if (path && taken.length > 0) keptFor(scope, true).set(path, taken)\n else if (path) keptFor(scope, false)?.delete(path)\n const owners = copy.type === 'INSTANCE' ? [...inner, copy] : inner\n for (const child of scope.graph.getChildren(copy.id)) keepOverrides(scope, child, owners)\n}\n\nfunction ownerOf(scope: OverrideScope, ref: OwnerRef): SceneNode | undefined {\n if ('id' in ref) return scope.owners.find((owner) => owner.id === ref.id)\n let current: SceneNode | undefined = scope.instance\n for (const step of ref.path.split('\\u0001')) {\n const [name, ordinal] = step.split('\\u0000')\n current = current\n ? scope.graph.getChildren(current.id).filter((child) => child.name === name)[Number(ordinal)]\n : undefined\n }\n return current?.type === 'INSTANCE' ? current : undefined\n}\n\n/**\n * Switches a nested instance switched to another variant again first, so what is kept for it\n * and its layers lands on what it then shows. Returns the node as it then stands.\n */\nfunction switchAsKept(scope: OverrideScope, copy: SceneNode, kept: readonly KeptOverrides[]) {\n const swappedTo = kept.find((entry) => entry.swappedTo)?.swappedTo\n if (\n swappedTo &&\n copy.type === 'INSTANCE' &&\n scope.graph.getNode(swappedTo) &&\n instanceMainComponent(scope.graph, copy)?.id !== swappedTo\n ) {\n scope.graph.swapInstanceComponent(copy.id, swappedTo)\n }\n return scope.graph.getNode(copy.id) ?? copy\n}\n\n/** The bindings and unit scales a layer shows with the kept bindings applied over its own. */\nfunction keptBindings(node: SceneNode, kept: readonly KeptOverrides[]) {\n let boundVariables: Record<string, string> = { ...node.boundVariables }\n let scales: Scales = { ...node.variableBindingScales }\n for (const { bindings, allBindings } of kept) {\n if (allBindings) {\n boundVariables = { ...allBindings.boundVariables }\n scales = { ...allBindings.scales }\n }\n for (const [field, { variableId, scale }] of Object.entries(bindings)) {\n boundVariables = variableId\n ? { ...boundVariables, [field]: variableId }\n : omit(boundVariables, [field])\n scales = scale !== undefined ? { ...scales, [field]: scale } : omit(scales, [field])\n }\n }\n return { boundVariables, scales }\n}\n\nfunction giveOverrides(scope: OverrideScope, copy: SceneNode, saved: readonly KeptOverrides[]) {\n // What an owner no longer standing around the copy overrode is not given back at all.\n const resolved = saved.flatMap((entry) => {\n const owner = ownerOf(scope, entry.owner)\n return owner ? [{ entry, owner }] : []\n })\n const kept = resolved.map(({ entry }) => entry)\n const node = switchAsKept(scope, copy, kept)\n const values: Partial<SceneNode> = {}\n for (const { entry, owner } of resolved) {\n const { self, fields, values: shown } = entry\n scope.willChange(owner)\n const own = self\n ? owner.instanceOverrides.self\n : owner.instanceOverrides.descendants.get(node.id)\n const merged = new Map([...(own ?? []), ...fields])\n if (self) owner.instanceOverrides.self = merged\n else owner.instanceOverrides.descendants.set(node.id, merged)\n Object.assign(values, structuredClone(shown))\n }\n const { boundVariables, scales } = keptBindings(node, kept)\n if (!isEqual(boundVariables, node.boundVariables)) values.boundVariables = boundVariables\n if (!isEqual(scales, node.variableBindingScales)) values.variableBindingScales = scales\n const assignments: Record<string, string> = Object.assign(\n {},\n ...kept.map((entry) => entry.assignments)\n )\n const assigns = Object.keys(assignments).length > 0\n if (assigns) {\n values.componentPropertyAssignments = { ...node.componentPropertyAssignments, ...assignments }\n }\n if (Object.keys(values).length > 0) scope.graph.updateNode(node.id, values)\n // The values a nested instance is given show in its layers, as a matched copy's do.\n if (assigns) reapplyComponentPropertyAssignments(scope.graph, node.id)\n}\n\n/** Gives a copy just placed, and its layers, what an earlier switch kept for their paths. */\nexport function restoreOverrides(scope: OverrideScope, copy: SceneNode): void {\n const kept = keptFor(scope, false)\n if (!kept?.size) return\n const restore = (node: SceneNode) => {\n const path = layerPath(scope, node)\n const found = path ? kept.get(path) : undefined\n // Kept, not taken: undoing this switch and switching again gives them back once more.\n if (found) giveOverrides(scope, node, found)\n for (const child of scope.graph.getChildren(node.id)) restore(child)\n }\n restore(copy)\n}\n"],"mappings":";;;;;;;AA6CA,MAAM,8BAAmC,IAAI,IAAI,CAAC,qBAAqB,aAAa,CAAC;;;;;;;;AASrF,MAAM,8BAAc,IAAI,QAA+D;AAIvF,SAAS,QAAQ,OAAsB,QAAiB;CACtD,IAAI,aAAa,YAAY,IAAI,MAAM,KAAK;CAC5C,IAAI,CAAC,cAAc,QAAQ;EACzB,6BAAa,IAAI,IAAI;EACrB,YAAY,IAAI,MAAM,OAAO,UAAU;CACzC;CACA,IAAI,SAAS,YAAY,IAAI,MAAM,SAAS,EAAE;CAC9C,IAAI,CAAC,UAAU,cAAc,QAAQ;EACnC,yBAAS,IAAI,IAAI;EACjB,WAAW,IAAI,MAAM,SAAS,IAA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CAC9C;CACA,MAAM,EAAE,gBAAgB,WAAW,aAAa,MAAM,IAAI;CAC1D,IAAI,CAAC,QAAQ,gBAAgB,KAAK,cAAc,GAAG,OAAO,iBAAiB;CAC3E,IAAI,CAAC,QAAQ,QAAQ,KAAK,qBAAqB,GAAG,OAAO,wBAAwB;CACjF,MAAM,cAAsC,OAAO,OACjD,CAAC,GACD,GAAG,KAAK,KAAK,UAAU,MAAM,WAAW,CAC1C;CACA,MAAM,UAAU,OAAO,KAAK,WAAW,CAAC,CAAC,SAAS;CAClD,IAAI,SACF,OAAO,+BAA+B;EAAE,GAAG,KAAK;EAA8B,GAAG;CAAY;CAE/F,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,GAAG,MAAM,MAAM,WAAW,KAAK,IAAI,MAAM;CAE1E,IAAI,SAAS,oCAAoC,MAAM,OAAO,KAAK,EAAE;AACvE;;AAGA,SAAgB,iBAAiB,OAAsB,MAAuB;CAC5E,MAAM,OAAO,QAAQ,OAAO,KAAK;CACjC,IAAI,CAAC,MAAM,MAAM;CACjB,MAAM,WAAW,SAAoB;EACnC,MAAM,OAAO,UAAU,OAAO,IAAI;EAClC,MAAM,QAAQ,OAAO,KAAK,IAAI,IAAI,IAAI,KAAA;EAEtC,IAAI,OAAO,cAAc,OAAO,MAAM,KAAK;EAC3C,KAAK,MAAM,SAAS,MAAM,MAAM,YAAY,KAAK,EAAE,GAAG,QAAQ,KAAK;CACrE;CACA,QAAQ,IAAI;AACd"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { copiedComponentLayerId, hasInstanceOverride, setInstanceOverride } from "./overrides.js";
|
|
2
|
+
//#region src/instances/matching.ts
|
|
3
|
+
/** Links a copy to the component layer it matched, reporting each changed node and its owner. */
|
|
4
|
+
function linkMatchedChild(graph, context, instParentId, instChild, compChildId) {
|
|
5
|
+
const { overrides } = context;
|
|
6
|
+
const recorded = hasInstanceOverride(overrides, instParentId, instChild.id, "sourceComponentId");
|
|
7
|
+
if (instChild.type === "INSTANCE" || recorded) {
|
|
8
|
+
const owner = graph.nodes.get(context.instanceId);
|
|
9
|
+
graph.willChangeNode(owner);
|
|
10
|
+
setInstanceOverride(overrides, instParentId, instChild.id, "sourceComponentId", compChildId);
|
|
11
|
+
if (owner) graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides });
|
|
12
|
+
}
|
|
13
|
+
if (instChild.type !== "INSTANCE") graph.updateNode(instChild.id, { componentId: compChildId });
|
|
14
|
+
}
|
|
15
|
+
/** Children no link pairs, matched by type and name where the counts leave no doubt. */
|
|
16
|
+
function matchFallbackChildren(graph, compParent, instParent, instParentId, context, instChildMap, usedInstChildIds) {
|
|
17
|
+
const fallbackByType = /* @__PURE__ */ new Map();
|
|
18
|
+
const remainingCandidateCount = /* @__PURE__ */ new Map();
|
|
19
|
+
const unmatchedComponentCount = /* @__PURE__ */ new Map();
|
|
20
|
+
for (const compChildId of compParent.childIds) {
|
|
21
|
+
if (instChildMap.has(compChildId)) continue;
|
|
22
|
+
const child = graph.nodes.get(compChildId);
|
|
23
|
+
if (child) unmatchedComponentCount.set(child.type, (unmatchedComponentCount.get(child.type) ?? 0) + 1);
|
|
24
|
+
}
|
|
25
|
+
for (const childId of instParent.childIds) {
|
|
26
|
+
const child = graph.nodes.get(childId);
|
|
27
|
+
if (!child || usedInstChildIds.has(child.id)) continue;
|
|
28
|
+
remainingCandidateCount.set(child.type, (remainingCandidateCount.get(child.type) ?? 0) + 1);
|
|
29
|
+
let byName = fallbackByType.get(child.type);
|
|
30
|
+
if (!byName) {
|
|
31
|
+
byName = /* @__PURE__ */ new Map();
|
|
32
|
+
fallbackByType.set(child.type, byName);
|
|
33
|
+
}
|
|
34
|
+
const queue = byName.get(child.name);
|
|
35
|
+
if (queue) queue.push(child);
|
|
36
|
+
else byName.set(child.name, [child]);
|
|
37
|
+
}
|
|
38
|
+
for (const compChildId of compParent.childIds) {
|
|
39
|
+
if (instChildMap.has(compChildId)) continue;
|
|
40
|
+
const compChild = graph.nodes.get(compChildId);
|
|
41
|
+
if (!compChild) continue;
|
|
42
|
+
const candidatesByName = fallbackByType.get(compChild.type);
|
|
43
|
+
const candidateCount = remainingCandidateCount.get(compChild.type) ?? 0;
|
|
44
|
+
if (candidateCount > (unmatchedComponentCount.get(compChild.type) ?? 0)) continue;
|
|
45
|
+
const match = candidatesByName?.get(compChild.name)?.shift();
|
|
46
|
+
if (!match) continue;
|
|
47
|
+
remainingCandidateCount.set(compChild.type, candidateCount - 1);
|
|
48
|
+
instChildMap.set(compChildId, match);
|
|
49
|
+
usedInstChildIds.add(match.id);
|
|
50
|
+
linkMatchedChild(graph, context, instParentId, match, compChildId);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Children already linked to a component child by sourceComponentId or componentId. */
|
|
54
|
+
function matchLinkedChildren(graph, instParent, instParentId, overrides, compChildIdSet, instChildMap, usedInstChildIds) {
|
|
55
|
+
for (const childId of instParent.childIds) {
|
|
56
|
+
const child = graph.nodes.get(childId);
|
|
57
|
+
if (!child) continue;
|
|
58
|
+
const mappedComponentId = copiedComponentLayerId(overrides, instParentId, child);
|
|
59
|
+
if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {
|
|
60
|
+
instChildMap.set(mappedComponentId, child);
|
|
61
|
+
usedInstChildIds.add(child.id);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
export { matchFallbackChildren, matchLinkedChildren };
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=matching.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"matching.js","names":[],"sources":["../../src/instances/matching.ts"],"sourcesContent":["// Pairing an instance's children with its component's before a sync copies fields across.\nimport type { SceneGraph } from '../graph'\nimport type { SceneNode } from '../types'\nimport type { InstanceSyncContext } from './copies'\nimport {\n copiedComponentLayerId,\n hasInstanceOverride,\n setInstanceOverride,\n type InstanceOverrideState\n} from './overrides'\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 = hasInstanceOverride(overrides, instParentId, instChild.id, 'sourceComponentId')\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\n/** Children no link pairs, matched by type and name where the counts leave no doubt. */\nexport function 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\n/** Children already linked to a component child by sourceComponentId or componentId. */\nexport function matchLinkedChildren(\n graph: SceneGraph,\n instParent: SceneNode,\n instParentId: string,\n overrides: InstanceOverrideState,\n compChildIdSet: ReadonlySet<string>,\n instChildMap: Map<string, SceneNode>,\n usedInstChildIds: Set<string>\n): void {\n for (const childId of instParent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child) continue\n const mappedComponentId = copiedComponentLayerId(overrides, instParentId, child)\n if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {\n instChildMap.set(mappedComponentId, child)\n usedInstChildIds.add(child.id)\n }\n }\n}\n"],"mappings":";;;AAYA,SAAS,iBACP,OACA,SACA,cACA,WACA,aACM;CACN,MAAM,EAAE,cAAc;CACtB,MAAM,WAAW,oBAAoB,WAAW,cAAc,UAAU,IAAI,mBAAmB;CAC/F,IAAI,UAAU,SAAS,cAAc,UAAU;EAC7C,MAAM,QAAQ,MAAM,MAAM,IAAI,QAAQ,UAAU;EAChD,MAAM,eAAe,KAAK;EAC1B,oBAAoB,WAAW,cAAc,UAAU,IAAI,qBAAqB,WAAW;EAC3F,IAAI,OAAO,MAAM,WAAW,MAAM,IAAI,EAAE,mBAAmB,MAAM,kBAAkB,CAAC;CACtF;CACA,IAAI,UAAU,SAAS,YAAY,MAAM,WAAW,UAAU,IAAI,EAAE,aAAa,YAAY,CAAC;AAChG;;AAGA,SAAgB,sBACd,OACA,YACA,YACA,cACA,SACA,cACA,kBACM;CACN,MAAM,iCAAiB,IAAI,IAAiD;CAC5E,MAAM,0CAA0B,IAAI,IAA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7B,iBAAiB,OAAO,SAAS,cAAc,OAAO,WAAW;CACnE;AACF;;AAGA,SAAgB,oBACd,OACA,YACA,cACA,WACA,gBACA,cACA,kBACM;CACN,KAAK,MAAM,WAAW,WAAW,UAAU;EACzC,MAAM,QAAQ,MAAM,MAAM,IAAI,OAAO;EACrC,IAAI,CAAC,OAAO;EACZ,MAAM,oBAAoB,uBAAuB,WAAW,cAAc,KAAK;EAC/E,IAAI,qBAAqB,eAAe,IAAI,iBAAiB,GAAG;GAC9D,aAAa,IAAI,mBAAmB,KAAK;GACzC,iBAAiB,IAAI,MAAM,EAAE;EAC/B;CACF;AACF"}
|
|
@@ -27,7 +27,10 @@ interface InstanceOverrideReferenceMapper {
|
|
|
27
27
|
node: (id: string) => string;
|
|
28
28
|
variable: (id: string) => string;
|
|
29
29
|
collection?: (id: string) => string | undefined;
|
|
30
|
+
property?: (id: string) => string | undefined;
|
|
30
31
|
}
|
|
32
|
+
declare function assignmentOverrideField(propertyId: string): string;
|
|
33
|
+
declare function overriddenAssignmentId(field: string): string | undefined;
|
|
31
34
|
declare function variableModeOverrideField(collectionId: string): InstanceOverrideField;
|
|
32
35
|
declare function variableModeOverrideCollection(field: InstanceOverrideField): string | undefined;
|
|
33
36
|
/** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */
|
|
@@ -47,5 +50,5 @@ declare function deleteInstanceOverride(state: InstanceOverrideState, instanceId
|
|
|
47
50
|
declare function clearInstanceOverrides(state: InstanceOverrideState): void;
|
|
48
51
|
declare function forEachInstanceOverride(state: InstanceOverrideState, callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void): void;
|
|
49
52
|
//#endregion
|
|
50
|
-
export { InstanceOverrideField, InstanceOverrideReferenceMapper, InstanceOverrideState, SerializedInstanceOverrideState, SerializedOverrideValue, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, overriddenBindingField, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideCollection, variableModeOverrideField };
|
|
53
|
+
export { InstanceOverrideField, InstanceOverrideReferenceMapper, InstanceOverrideState, SerializedInstanceOverrideState, SerializedOverrideValue, assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, overriddenAssignmentId, overriddenBindingField, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideCollection, variableModeOverrideField };
|
|
51
54
|
//# sourceMappingURL=overrides.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"overrides.d.ts","names":[],"sources":["../../src/instances/overrides.ts"],"mappings":";KAAY;UAEK;EACf,MAAM,IAAI;EACV,aAAa,YAAY,IAAI;;;;;;iBASf,qBAAqB,gBAAgB;;iBAKrC,uBAAuB,OAAO;iBAM9B,+BAA+B;UAI9B;EACf;EACA;;UAGe;EACf,MAAM,OAAO,uBAAuB;EACpC,aAAa,eAAe,OAAO,uBAAuB;;iBAiC5C,+BACd,OAAO,wBACN;iBAUa,iCAAiC,iBAAiB;iBAgBlD,2BAA2B,OAAO,wBAAwB;UAYzD;EACf,OAAO;EACP,WAAW;EACX,cAAc;;
|
|
1
|
+
{"version":3,"file":"overrides.d.ts","names":[],"sources":["../../src/instances/overrides.ts"],"mappings":";KAAY;UAEK;EACf,MAAM,IAAI;EACV,aAAa,YAAY,IAAI;;;;;;iBASf,qBAAqB,gBAAgB;;iBAKrC,uBAAuB,OAAO;iBAM9B,+BAA+B;UAI9B;EACf;EACA;;UAGe;EACf,MAAM,OAAO,uBAAuB;EACpC,aAAa,eAAe,OAAO,uBAAuB;;iBAiC5C,+BACd,OAAO,wBACN;iBAUa,iCAAiC,iBAAiB;iBAgBlD,2BAA2B,OAAO,wBAAwB;UAYzD;EACf,OAAO;EACP,WAAW;EACX,cAAc;EACd,YAAY;;iBAKE,wBAAwB;iBAIxB,uBAAuB;iBAQvB,0BAA0B,uBAAuB;iBAIjD,+BAA+B,OAAO;;iBAOtC,2BACd,OAAO,uBACP,YAAY,kCACX;iBAoCa,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO;;;;;iBASO,uBACd,OAAO,uBACP,oBACA;EAAQ;EAAY;;iBAMN,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO;iBAMO,oBACd,OAAO,uBACP,oBACA,gBACA,OAAO,uBACP;iBAWc,uBACd,OAAO,uBACP,oBACA,gBACA,OAAO;iBAQO,uBAAuB,OAAO;iBAK9B,wBACd,OAAO,uBACP,WAAW,gBAAgB,OAAO,uBAAuB"}
|
|
@@ -79,6 +79,13 @@ function cloneInstanceOverrideState(state) {
|
|
|
79
79
|
descendants: new Map([...state.descendants].map(([id, fields]) => [id, new Map([...fields].map(([field, value]) => [field, structuredClone(value)]))]))
|
|
80
80
|
};
|
|
81
81
|
}
|
|
82
|
+
const ASSIGNMENT_OVERRIDE_PREFIX = "componentPropertyAssignments/";
|
|
83
|
+
function assignmentOverrideField(propertyId) {
|
|
84
|
+
return `${ASSIGNMENT_OVERRIDE_PREFIX}${propertyId}`;
|
|
85
|
+
}
|
|
86
|
+
function overriddenAssignmentId(field) {
|
|
87
|
+
return field.startsWith(ASSIGNMENT_OVERRIDE_PREFIX) ? field.slice(29) : void 0;
|
|
88
|
+
}
|
|
82
89
|
const VARIABLE_MODE_FIELD_PREFIX = "variableModes/";
|
|
83
90
|
function variableModeOverrideField(collectionId) {
|
|
84
91
|
return `${VARIABLE_MODE_FIELD_PREFIX}${collectionId}`;
|
|
@@ -95,6 +102,11 @@ function remapInstanceOverrideState(state, references) {
|
|
|
95
102
|
return value;
|
|
96
103
|
};
|
|
97
104
|
const remapField = (field) => {
|
|
105
|
+
const property = overriddenAssignmentId(field);
|
|
106
|
+
if (property !== void 0 && references.property) {
|
|
107
|
+
const mapped = references.property(property);
|
|
108
|
+
return mapped === void 0 ? void 0 : assignmentOverrideField(mapped);
|
|
109
|
+
}
|
|
98
110
|
const collection = variableModeOverrideCollection(field);
|
|
99
111
|
if (collection === void 0 || !references.collection) return field;
|
|
100
112
|
const mapped = references.collection(collection);
|
|
@@ -153,6 +165,6 @@ function forEachInstanceOverride(state, callback) {
|
|
|
153
165
|
for (const [nodeId, fields] of state.descendants) for (const [field, value] of fields) callback(nodeId, field, value);
|
|
154
166
|
}
|
|
155
167
|
//#endregion
|
|
156
|
-
export { bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, overriddenBindingField, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideCollection, variableModeOverrideField };
|
|
168
|
+
export { assignmentOverrideField, bindingOverrideField, clearInstanceOverrides, cloneInstanceOverrideState, copiedComponentLayerId, createInstanceOverrideState, deleteInstanceOverride, deserializeInstanceOverrideState, forEachInstanceOverride, getInstanceOverride, hasInstanceOverride, overriddenAssignmentId, overriddenBindingField, remapInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride, variableModeOverrideCollection, variableModeOverrideField };
|
|
157
169
|
|
|
158
170
|
//# sourceMappingURL=overrides.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"overrides.js","names":[],"sources":["../../src/instances/overrides.ts"],"sourcesContent":["export type InstanceOverrideField = string\n\nexport interface InstanceOverrideState {\n self: Map<InstanceOverrideField, unknown>\n descendants: Map<string, Map<InstanceOverrideField, unknown>>\n}\n\nconst BINDING_OVERRIDE_PREFIX = 'boundVariables/'\n\n/**\n * The override field that claims a layer's binding of `field`, which keeps that binding, or its\n * absence, through a sync. `boundVariables` alone claims every binding of the layer.\n */\nexport function bindingOverrideField(field: string): InstanceOverrideField {\n return `${BINDING_OVERRIDE_PREFIX}${field}`\n}\n\n/** The binding field an override field claims, or null for an override of anything else. */\nexport function overriddenBindingField(field: InstanceOverrideField): string | null {\n return field.startsWith(BINDING_OVERRIDE_PREFIX)\n ? field.slice(BINDING_OVERRIDE_PREFIX.length)\n : null\n}\n\nexport function createInstanceOverrideState(): InstanceOverrideState {\n return { self: new Map(), descendants: new Map() }\n}\n\nexport interface SerializedOverrideValue {\n defined: boolean\n value?: unknown\n}\n\nexport interface SerializedInstanceOverrideState {\n self: Array<[InstanceOverrideField, SerializedOverrideValue]>\n descendants: Array<[string, Array<[InstanceOverrideField, SerializedOverrideValue]>]>\n}\n\nfunction serializeOverrideValue(value: unknown): SerializedOverrideValue {\n return value === undefined ? { defined: false } : { defined: true, value }\n}\n\nfunction deserializeOverrideValue(value: unknown): { valid: boolean; value: unknown } {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return { valid: false, value: undefined }\n }\n if (!('defined' in value) || typeof value.defined !== 'boolean') {\n return { valid: false, value: undefined }\n }\n if (value.defined) {\n return 'value' in value\n ? { valid: true, value: value['value'] }\n : { valid: false, value: undefined }\n }\n return { valid: true, value: undefined }\n}\n\nfunction deserializeEntries(value: unknown): Map<InstanceOverrideField, unknown> {\n const result = new Map<InstanceOverrideField, unknown>()\n if (!Array.isArray(value)) return result\n for (const entry of value) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue\n const decoded = deserializeOverrideValue(entry[1])\n if (decoded.valid) result.set(entry[0], decoded.value)\n }\n return result\n}\n\nexport function serializeInstanceOverrideState(\n state: InstanceOverrideState\n): SerializedInstanceOverrideState {\n return {\n self: [...state.self].map(([field, value]) => [field, serializeOverrideValue(value)]),\n descendants: [...state.descendants].map(([nodeId, fields]) => [\n nodeId,\n [...fields].map(([field, value]) => [field, serializeOverrideValue(value)])\n ])\n }\n}\n\nexport function deserializeInstanceOverrideState(state: unknown): InstanceOverrideState {\n if (!state || typeof state !== 'object' || Array.isArray(state)) {\n return createInstanceOverrideState()\n }\n const self =\n 'self' in state ? deserializeEntries(state.self) : new Map<InstanceOverrideField, unknown>()\n const descendants = new Map<string, Map<InstanceOverrideField, unknown>>()\n if ('descendants' in state && Array.isArray(state.descendants)) {\n for (const entry of state.descendants) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue\n descendants.set(entry[0], deserializeEntries(entry[1]))\n }\n }\n return { self, descendants }\n}\n\nexport function cloneInstanceOverrideState(state: InstanceOverrideState): InstanceOverrideState {\n return {\n self: new Map([...state.self].map(([field, value]) => [field, structuredClone(value)])),\n descendants: new Map(\n [...state.descendants].map(([id, fields]) => [\n id,\n new Map([...fields].map(([field, value]) => [field, structuredClone(value)]))\n ])\n )\n }\n}\n\nexport interface InstanceOverrideReferenceMapper {\n node: (id: string) => string\n variable: (id: string) => string\n collection?: (id: string) => string | undefined\n}\n\nconst VARIABLE_MODE_FIELD_PREFIX = 'variableModes/'\n\nexport function variableModeOverrideField(collectionId: string): InstanceOverrideField {\n return `${VARIABLE_MODE_FIELD_PREFIX}${collectionId}`\n}\n\nexport function variableModeOverrideCollection(field: InstanceOverrideField): string | undefined {\n return field.startsWith(VARIABLE_MODE_FIELD_PREFIX)\n ? field.slice(VARIABLE_MODE_FIELD_PREFIX.length)\n : undefined\n}\n\n/** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */\nexport function remapInstanceOverrideState(\n state: InstanceOverrideState,\n references: InstanceOverrideReferenceMapper\n): InstanceOverrideState {\n const remapValue = (field: string, value: unknown): unknown => {\n if (typeof value !== 'string') return structuredClone(value)\n if (field === 'componentId' || field === 'sourceComponentId') return references.node(value)\n if (overriddenBindingField(field) !== null) return references.variable(value)\n return value\n }\n const remapField = (field: string): string | undefined => {\n const collection = variableModeOverrideCollection(field)\n if (collection === undefined || !references.collection) {\n return field\n }\n const mapped = references.collection(collection)\n return mapped === undefined ? undefined : variableModeOverrideField(mapped)\n }\n const fields = (entries: ReadonlyMap<string, unknown>) =>\n new Map(\n [...entries].flatMap(([field, value]) => {\n const mapped = remapField(field)\n return mapped === undefined ? [] : [[mapped, remapValue(field, value)] as const]\n })\n )\n const descendants = new Map<string, Map<string, unknown>>()\n for (const [id, entries] of state.descendants) {\n const mapped = references.node(id)\n if (descendants.has(mapped)) throw new Error(`Duplicate remapped override target ${mapped}`)\n descendants.set(mapped, fields(entries))\n }\n return { self: fields(state.self), descendants }\n}\n\nexport function getInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): unknown {\n return nodeId === instanceId ? state.self.get(field) : state.descendants.get(nodeId)?.get(field)\n}\n\n/**\n * The component layer a layer of an instance copies: the one its instance recorded for it, as\n * a swapped nested instance keeps, or else the one it was cloned from.\n */\nexport function copiedComponentLayerId(\n state: InstanceOverrideState,\n instanceId: string,\n node: { id: string; componentId: string | null }\n): string | undefined {\n const recorded = getInstanceOverride(state, instanceId, node.id, 'sourceComponentId')\n return typeof recorded === 'string' ? recorded : (node.componentId ?? undefined)\n}\n\nexport function hasInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): boolean {\n const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)\n return fields?.has(field) ?? false\n}\n\nexport function setInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField,\n value: unknown = true\n): void {\n if (nodeId === instanceId) {\n state.self.set(field, value)\n return\n }\n const fields = state.descendants.get(nodeId) ?? new Map<string, unknown>()\n fields.set(field, value)\n state.descendants.set(nodeId, fields)\n}\n\nexport function deleteInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): boolean {\n const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)\n if (!fields?.delete(field)) return false\n if (nodeId !== instanceId && fields.size === 0) state.descendants.delete(nodeId)\n return true\n}\n\nexport function clearInstanceOverrides(state: InstanceOverrideState): void {\n state.self.clear()\n state.descendants.clear()\n}\n\nexport function forEachInstanceOverride(\n state: InstanceOverrideState,\n callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void\n): void {\n for (const [field, value] of state.self) callback('', field, value)\n for (const [nodeId, fields] of state.descendants) {\n for (const [field, value] of fields) callback(nodeId, field, value)\n }\n}\n"],"mappings":";AAOA,MAAM,0BAA0B;;;;;AAMhC,SAAgB,qBAAqB,OAAsC;CACzE,OAAO,GAAG,0BAA0B;AACtC;;AAGA,SAAgB,uBAAuB,OAA6C;CAClF,OAAO,MAAM,WAAW,uBAAuB,IAC3C,MAAM,MAAM,EAA8B,IAC1C;AACN;AAEA,SAAgB,8BAAqD;CACnE,OAAO;EAAE,sBAAM,IAAI,IAAI;EAAG,6BAAa,IAAI,IAAI;CAAE;AACnD;AAYA,SAAS,uBAAuB,OAAyC;CACvE,OAAO,UAAU,KAAA,IAAY,EAAE,SAAS,MAAM,IAAI;EAAE,SAAS;EAAM;CAAM;AAC3E;AAEA,SAAS,yBAAyB,OAAoD;CACpF,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO;EAAE,OAAO;EAAO,OAAO,KAAA;CAAU;CAE1C,IAAI,EAAE,aAAa,UAAU,OAAO,MAAM,YAAY,WACpD,OAAO;EAAE,OAAO;EAAO,OAAO,KAAA;CAAU;CAE1C,IAAI,MAAM,SACR,OAAO,WAAW,QACd;EAAE,OAAO;EAAM,OAAO,MAAM;CAAS,IACrC;EAAE,OAAO;EAAO,OAAO,KAAA;CAAU;CAEvC,OAAO;EAAE,OAAO;EAAM,OAAO,KAAA;CAAU;AACzC;AAEA,SAAS,mBAAmB,OAAqD;CAC/E,MAAM,yBAAS,IAAI,IAAoC;CACvD,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO;CAClC,KAAK,MAAM,SAAS,OAAO;EACzB,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,KAAK,OAAO,MAAM,OAA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AAC,QAAQ,WAAW,MAAM,aACnC,KAAK,MAAM,CAAC,OAAO,UAAU,QAAQ,SAAS,QAAQ,OAAO,KAAK;AAEtE"}
|
|
1
|
+
{"version":3,"file":"overrides.js","names":[],"sources":["../../src/instances/overrides.ts"],"sourcesContent":["export type InstanceOverrideField = string\n\nexport interface InstanceOverrideState {\n self: Map<InstanceOverrideField, unknown>\n descendants: Map<string, Map<InstanceOverrideField, unknown>>\n}\n\nconst BINDING_OVERRIDE_PREFIX = 'boundVariables/'\n\n/**\n * The override field that claims a layer's binding of `field`, which keeps that binding, or its\n * absence, through a sync. `boundVariables` alone claims every binding of the layer.\n */\nexport function bindingOverrideField(field: string): InstanceOverrideField {\n return `${BINDING_OVERRIDE_PREFIX}${field}`\n}\n\n/** The binding field an override field claims, or null for an override of anything else. */\nexport function overriddenBindingField(field: InstanceOverrideField): string | null {\n return field.startsWith(BINDING_OVERRIDE_PREFIX)\n ? field.slice(BINDING_OVERRIDE_PREFIX.length)\n : null\n}\n\nexport function createInstanceOverrideState(): InstanceOverrideState {\n return { self: new Map(), descendants: new Map() }\n}\n\nexport interface SerializedOverrideValue {\n defined: boolean\n value?: unknown\n}\n\nexport interface SerializedInstanceOverrideState {\n self: Array<[InstanceOverrideField, SerializedOverrideValue]>\n descendants: Array<[string, Array<[InstanceOverrideField, SerializedOverrideValue]>]>\n}\n\nfunction serializeOverrideValue(value: unknown): SerializedOverrideValue {\n return value === undefined ? { defined: false } : { defined: true, value }\n}\n\nfunction deserializeOverrideValue(value: unknown): { valid: boolean; value: unknown } {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return { valid: false, value: undefined }\n }\n if (!('defined' in value) || typeof value.defined !== 'boolean') {\n return { valid: false, value: undefined }\n }\n if (value.defined) {\n return 'value' in value\n ? { valid: true, value: value['value'] }\n : { valid: false, value: undefined }\n }\n return { valid: true, value: undefined }\n}\n\nfunction deserializeEntries(value: unknown): Map<InstanceOverrideField, unknown> {\n const result = new Map<InstanceOverrideField, unknown>()\n if (!Array.isArray(value)) return result\n for (const entry of value) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue\n const decoded = deserializeOverrideValue(entry[1])\n if (decoded.valid) result.set(entry[0], decoded.value)\n }\n return result\n}\n\nexport function serializeInstanceOverrideState(\n state: InstanceOverrideState\n): SerializedInstanceOverrideState {\n return {\n self: [...state.self].map(([field, value]) => [field, serializeOverrideValue(value)]),\n descendants: [...state.descendants].map(([nodeId, fields]) => [\n nodeId,\n [...fields].map(([field, value]) => [field, serializeOverrideValue(value)])\n ])\n }\n}\n\nexport function deserializeInstanceOverrideState(state: unknown): InstanceOverrideState {\n if (!state || typeof state !== 'object' || Array.isArray(state)) {\n return createInstanceOverrideState()\n }\n const self =\n 'self' in state ? deserializeEntries(state.self) : new Map<InstanceOverrideField, unknown>()\n const descendants = new Map<string, Map<InstanceOverrideField, unknown>>()\n if ('descendants' in state && Array.isArray(state.descendants)) {\n for (const entry of state.descendants) {\n if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') continue\n descendants.set(entry[0], deserializeEntries(entry[1]))\n }\n }\n return { self, descendants }\n}\n\nexport function cloneInstanceOverrideState(state: InstanceOverrideState): InstanceOverrideState {\n return {\n self: new Map([...state.self].map(([field, value]) => [field, structuredClone(value)])),\n descendants: new Map(\n [...state.descendants].map(([id, fields]) => [\n id,\n new Map([...fields].map(([field, value]) => [field, structuredClone(value)]))\n ])\n )\n }\n}\n\nexport interface InstanceOverrideReferenceMapper {\n node: (id: string) => string\n variable: (id: string) => string\n collection?: (id: string) => string | undefined\n property?: (id: string) => string | undefined\n}\n\nconst ASSIGNMENT_OVERRIDE_PREFIX = 'componentPropertyAssignments/'\n\nexport function assignmentOverrideField(propertyId: string): string {\n return `${ASSIGNMENT_OVERRIDE_PREFIX}${propertyId}`\n}\n\nexport function overriddenAssignmentId(field: string): string | undefined {\n return field.startsWith(ASSIGNMENT_OVERRIDE_PREFIX)\n ? field.slice(ASSIGNMENT_OVERRIDE_PREFIX.length)\n : undefined\n}\n\nconst VARIABLE_MODE_FIELD_PREFIX = 'variableModes/'\n\nexport function variableModeOverrideField(collectionId: string): InstanceOverrideField {\n return `${VARIABLE_MODE_FIELD_PREFIX}${collectionId}`\n}\n\nexport function variableModeOverrideCollection(field: InstanceOverrideField): string | undefined {\n return field.startsWith(VARIABLE_MODE_FIELD_PREFIX)\n ? field.slice(VARIABLE_MODE_FIELD_PREFIX.length)\n : undefined\n}\n\n/** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */\nexport function remapInstanceOverrideState(\n state: InstanceOverrideState,\n references: InstanceOverrideReferenceMapper\n): InstanceOverrideState {\n const remapValue = (field: string, value: unknown): unknown => {\n if (typeof value !== 'string') return structuredClone(value)\n if (field === 'componentId' || field === 'sourceComponentId') return references.node(value)\n if (overriddenBindingField(field) !== null) return references.variable(value)\n return value\n }\n const remapField = (field: string): string | undefined => {\n const property = overriddenAssignmentId(field)\n if (property !== undefined && references.property) {\n const mapped = references.property(property)\n return mapped === undefined ? undefined : assignmentOverrideField(mapped)\n }\n const collection = variableModeOverrideCollection(field)\n if (collection === undefined || !references.collection) {\n return field\n }\n const mapped = references.collection(collection)\n return mapped === undefined ? undefined : variableModeOverrideField(mapped)\n }\n const fields = (entries: ReadonlyMap<string, unknown>) =>\n new Map(\n [...entries].flatMap(([field, value]) => {\n const mapped = remapField(field)\n return mapped === undefined ? [] : [[mapped, remapValue(field, value)] as const]\n })\n )\n const descendants = new Map<string, Map<string, unknown>>()\n for (const [id, entries] of state.descendants) {\n const mapped = references.node(id)\n if (descendants.has(mapped)) throw new Error(`Duplicate remapped override target ${mapped}`)\n descendants.set(mapped, fields(entries))\n }\n return { self: fields(state.self), descendants }\n}\n\nexport function getInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): unknown {\n return nodeId === instanceId ? state.self.get(field) : state.descendants.get(nodeId)?.get(field)\n}\n\n/**\n * The component layer a layer of an instance copies: the one its instance recorded for it, as\n * a swapped nested instance keeps, or else the one it was cloned from.\n */\nexport function copiedComponentLayerId(\n state: InstanceOverrideState,\n instanceId: string,\n node: { id: string; componentId: string | null }\n): string | undefined {\n const recorded = getInstanceOverride(state, instanceId, node.id, 'sourceComponentId')\n return typeof recorded === 'string' ? recorded : (node.componentId ?? undefined)\n}\n\nexport function hasInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): boolean {\n const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)\n return fields?.has(field) ?? false\n}\n\nexport function setInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField,\n value: unknown = true\n): void {\n if (nodeId === instanceId) {\n state.self.set(field, value)\n return\n }\n const fields = state.descendants.get(nodeId) ?? new Map<string, unknown>()\n fields.set(field, value)\n state.descendants.set(nodeId, fields)\n}\n\nexport function deleteInstanceOverride(\n state: InstanceOverrideState,\n instanceId: string,\n nodeId: string,\n field: InstanceOverrideField\n): boolean {\n const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)\n if (!fields?.delete(field)) return false\n if (nodeId !== instanceId && fields.size === 0) state.descendants.delete(nodeId)\n return true\n}\n\nexport function clearInstanceOverrides(state: InstanceOverrideState): void {\n state.self.clear()\n state.descendants.clear()\n}\n\nexport function forEachInstanceOverride(\n state: InstanceOverrideState,\n callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void\n): void {\n for (const [field, value] of state.self) callback('', field, value)\n for (const [nodeId, fields] of state.descendants) {\n for (const [field, value] of fields) callback(nodeId, field, value)\n }\n}\n"],"mappings":";AAOA,MAAM,0BAA0B;;;;;AAMhC,SAAgB,qBAAqB,OAAsC;CACzE,OAAO,GAAG,0BAA0B;AACtC;;AAGA,SAAgB,uBAAuB,OAA6C;CAClF,OAAO,MAAM,WAAW,uBAAuB,IAC3C,MAAM,MAAM,EAA8B,IAC1C;AACN;AAEA,SAAgB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CAAC,OAAO,UAAU,QAAQ,SAAS,QAAQ,OAAO,KAAK;AAEtE"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { effectBindingTarget, paintBindingTarget } from "../variables/fields.js";
|
|
2
|
+
import { bindingOverrideField, overriddenBindingField } from "./overrides.js";
|
|
3
|
+
import { ownsSelfFillField } from "./main-component.js";
|
|
4
|
+
import { isEmptyObject } from "es-toolkit/predicate";
|
|
5
|
+
//#region src/instances/protection.ts
|
|
6
|
+
/** Protection for a copy that keeps nothing of its own. */
|
|
7
|
+
const NOTHING_PROTECTED = (_field) => false;
|
|
8
|
+
function bindingProtection(scopes) {
|
|
9
|
+
const fields = /* @__PURE__ */ new Set();
|
|
10
|
+
for (const scope of scopes) {
|
|
11
|
+
const perField = [...scope].some((field) => overriddenBindingField(field) !== null);
|
|
12
|
+
for (const field of scope) if (field !== "boundVariables" || !perField) fields.add(field);
|
|
13
|
+
}
|
|
14
|
+
return (field) => {
|
|
15
|
+
if (fields.has(field)) return true;
|
|
16
|
+
const binding = overriddenBindingField(field);
|
|
17
|
+
if (binding === null) return false;
|
|
18
|
+
const paint = paintBindingTarget(binding);
|
|
19
|
+
if (paint) return fields.has(paint.list);
|
|
20
|
+
return fields.has("effects") && effectBindingTarget(binding) !== null;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function isUnbound(node) {
|
|
24
|
+
return isEmptyObject(node.boundVariables) && isEmptyObject(node.variableBindingScales);
|
|
25
|
+
}
|
|
26
|
+
function syncBindingFields(target, source, updates, protectedField) {
|
|
27
|
+
if (protectedField("boundVariables") || isUnbound(source) && isUnbound(target)) return;
|
|
28
|
+
const bindings = { ...source.boundVariables };
|
|
29
|
+
const scales = { ...source.variableBindingScales };
|
|
30
|
+
for (const field of /* @__PURE__ */ new Set([
|
|
31
|
+
...Object.keys(source.boundVariables),
|
|
32
|
+
...Object.keys(target.boundVariables),
|
|
33
|
+
...Object.keys(target.variableBindingScales)
|
|
34
|
+
])) {
|
|
35
|
+
if (!protectedField(bindingOverrideField(field))) continue;
|
|
36
|
+
if (!Object.hasOwn(target.boundVariables, field)) Reflect.deleteProperty(bindings, field);
|
|
37
|
+
else bindings[field] = target.boundVariables[field];
|
|
38
|
+
if (target.variableBindingScales[field] === void 0) Reflect.deleteProperty(scales, field);
|
|
39
|
+
else scales[field] = target.variableBindingScales[field];
|
|
40
|
+
}
|
|
41
|
+
updates.boundVariables = bindings;
|
|
42
|
+
updates.variableBindingScales = scales;
|
|
43
|
+
}
|
|
44
|
+
function isProtectedSyncField(node, key, protectedField) {
|
|
45
|
+
return protectedField(key) || key in node.boundVariables && (protectedField("boundVariables") || protectedField(bindingOverrideField(key)));
|
|
46
|
+
}
|
|
47
|
+
function enclosingInstanceOverrideFields(graph, node) {
|
|
48
|
+
const fields = [];
|
|
49
|
+
if (!node.parentId) return fields;
|
|
50
|
+
graph.closest(node.parentId, (ancestor) => {
|
|
51
|
+
if (ancestor.type === "INSTANCE") fields.push(new Set(ancestor.instanceOverrides.descendants.get(node.id)?.keys()));
|
|
52
|
+
return false;
|
|
53
|
+
});
|
|
54
|
+
return fields;
|
|
55
|
+
}
|
|
56
|
+
/** The fields a copy keeps: its own overrides and those of every instance around it. */
|
|
57
|
+
function childBindingProtection(graph, child, overrides) {
|
|
58
|
+
const fields = enclosingInstanceOverrideFields(graph, child);
|
|
59
|
+
fields.push(new Set(overrides.descendants.get(child.id)?.keys()));
|
|
60
|
+
if (child.instanceOverrides.self.size === 0 && fields.every((scope) => scope.size === 0)) return NOTHING_PROTECTED;
|
|
61
|
+
const protectedField = bindingProtection(fields);
|
|
62
|
+
return (field) => protectedField(field) || ownsSelfFillField(child, field);
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
export { NOTHING_PROTECTED, bindingProtection, childBindingProtection, enclosingInstanceOverrideFields, isProtectedSyncField, syncBindingFields };
|
|
66
|
+
|
|
67
|
+
//# sourceMappingURL=protection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"protection.js","names":[],"sources":["../../src/instances/protection.ts"],"sourcesContent":["// What an instance's copy keeps through a sync: the fields it, or an instance around it, overrides.\nimport { isEmptyObject } from 'es-toolkit/predicate'\n\nimport type { SceneGraph } from '../graph'\nimport type { SceneNode } from '../types'\nimport { effectBindingTarget, paintBindingTarget } from '../variables/fields'\nimport { ownsSelfFillField } from './main-component'\nimport {\n bindingOverrideField,\n overriddenBindingField,\n type InstanceOverrideState\n} from './overrides'\n\n/** Protection for a copy that keeps nothing of its own. */\nexport const NOTHING_PROTECTED = (_field: string): boolean => false\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 and effects 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 if (paint) return fields.has(paint.list)\n return fields.has('effects') && effectBindingTarget(binding) !== null\n }\n}\n\nfunction isUnbound(node: SceneNode): boolean {\n return isEmptyObject(node.boundVariables) && isEmptyObject(node.variableBindingScales)\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') || (isUnbound(source) && isUnbound(target))) {\n return\n }\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\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 enclosingInstanceOverrideFields(graph: SceneGraph, node: SceneNode): Set<string>[] {\n const fields: Set<string>[] = []\n if (!node.parentId) return fields\n graph.closest(node.parentId, (ancestor) => {\n if (ancestor.type === 'INSTANCE') {\n fields.push(new Set(ancestor.instanceOverrides.descendants.get(node.id)?.keys()))\n }\n return false\n })\n return fields\n}\n\n/** The fields a copy keeps: its own overrides and those of every instance around it. */\nexport function 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 if (child.instanceOverrides.self.size === 0 && fields.every((scope) => scope.size === 0)) {\n return NOTHING_PROTECTED\n }\n const protectedField = bindingProtection(fields)\n return (field: string) => protectedField(field) || ownsSelfFillField(child, field)\n}\n"],"mappings":";;;;;;AAcA,MAAa,qBAAqB,WAA4B;AAE9D,SAAgB,kBAAkB,QAA2D;CAC3F,MAAM,yBAAS,IAAI,IAAY;CAC/B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,UAAU,uBAAuB,KAAK,MAAM,IAAI;EAClF,KAAK,MAAM,SAAS,OAClB,IAAI,UAAU,oBAAoB,CAAC,UAAU,OAAO,IAAI,KAAK;CAEjE;CACA,QAAQ,UAAU;EAChB,IAAI,OAAO,IAAI,KAAK,GAAG,OAAO;EAE9B,MAAM,UAAU,uBAAuB,KAAK;EAC5C,IAAI,YAAY,MAAM,OAAO;EAC7B,MAAM,QAAQ,mBAAmB,OAAO;EACxC,IAAI,OAAO,OAAO,OAAO,IAAI,MAAM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