@open-pencil/scene-graph 0.15.1 → 0.16.0-beta.2
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/LICENSE +21 -0
- package/README.md +1 -1
- package/dist/chunks/behaviours/kinds.js +273 -0
- package/dist/chunks/behaviours/kinds.js.map +1 -0
- package/dist/chunks/behaviours/layers.js +607 -0
- package/dist/chunks/behaviours/layers.js.map +1 -0
- package/dist/chunks/behaviours/spec.js +181 -0
- package/dist/chunks/behaviours/spec.js.map +1 -0
- package/dist/chunks/buffered-events.js +57 -0
- package/dist/chunks/buffered-events.js.map +1 -0
- package/dist/chunks/color/contrast.js +57 -0
- package/dist/chunks/color/contrast.js.map +1 -0
- package/dist/chunks/{components/properties.js → color/index.js} +577 -522
- package/dist/chunks/color/index.js.map +1 -0
- package/dist/chunks/comments/document.js +32 -0
- package/dist/chunks/comments/document.js.map +1 -0
- package/dist/chunks/comments/list.js +182 -0
- package/dist/chunks/comments/list.js.map +1 -0
- package/dist/chunks/comments/merge.js +58 -0
- package/dist/chunks/comments/merge.js.map +1 -0
- package/dist/chunks/components/exposure.js +2291 -0
- package/dist/chunks/components/exposure.js.map +1 -0
- package/dist/chunks/components/variants.js +32 -0
- package/dist/chunks/components/variants.js.map +1 -0
- package/dist/chunks/coordinate.js +93 -55
- package/dist/chunks/coordinate.js.map +1 -1
- package/dist/chunks/css/grid.js +94 -0
- package/dist/chunks/css/grid.js.map +1 -0
- package/dist/chunks/css/index.js +160 -0
- package/dist/chunks/css/index.js.map +1 -0
- package/dist/chunks/fields/geometry.js +14 -0
- package/dist/chunks/fields/geometry.js.map +1 -0
- package/dist/chunks/group-bounds.js +104 -0
- package/dist/chunks/group-bounds.js.map +1 -0
- package/dist/chunks/icons/glyph.js +147 -0
- package/dist/chunks/icons/glyph.js.map +1 -0
- package/dist/chunks/index.js +1724 -663
- package/dist/chunks/index.js.map +1 -1
- package/dist/color.d.ts +72 -0
- package/dist/color.d.ts.map +1 -0
- package/dist/color.js +3 -0
- package/dist/constants.d.ts +2 -2
- package/dist/constants.js +2 -2
- package/dist/constants2.d.ts +3 -1
- package/dist/constants2.d.ts.map +1 -1
- package/dist/coordinate.d.ts +2 -448
- package/dist/coordinate.js +2 -2
- package/dist/copy.d.ts +1 -1
- package/dist/copy.js +1 -1
- package/dist/css.d.ts +39 -0
- package/dist/css.d.ts.map +1 -0
- package/dist/css.js +3 -0
- package/dist/geometry.d.ts +1 -1
- package/dist/geometry.js +1 -1
- package/dist/gradient.d.ts +51 -0
- package/dist/gradient.d.ts.map +1 -0
- package/dist/gradient.js +132 -0
- package/dist/gradient.js.map +1 -0
- package/dist/guides.d.ts +2 -2
- package/dist/guides.js +39 -0
- package/dist/guides.js.map +1 -0
- package/dist/hit-test.d.ts +2 -9
- package/dist/hit-test.js +176 -34
- package/dist/hit-test.js.map +1 -1
- package/dist/index.d.ts +4 -8
- package/dist/index.js +19 -5
- package/dist/instances.d.ts +2 -2
- package/dist/instances.js +2 -2
- package/dist/layout.d.ts +2 -0
- package/dist/layout.js +4 -0
- package/dist/node-defaults.d.ts +2 -8
- package/dist/node-defaults.js +2 -2
- package/dist/order-keys.d.ts +39 -0
- package/dist/order-keys.d.ts.map +1 -0
- package/dist/order-keys.js +136 -0
- package/dist/order-keys.js.map +1 -0
- package/dist/parse-path.d.ts +7 -1
- package/dist/parse-path.d.ts.map +1 -1
- package/dist/parse-path.js +6 -2
- package/dist/parse-path.js.map +1 -1
- package/dist/polygon.d.ts +53 -0
- package/dist/polygon.d.ts.map +1 -0
- package/dist/polygon.js +205 -0
- package/dist/polygon.js.map +1 -0
- package/dist/preview.d.ts +1 -1
- package/dist/random.d.ts +7 -0
- package/dist/random.d.ts.map +1 -0
- package/dist/random.js +2 -0
- package/dist/resize.d.ts +11 -2
- package/dist/resize.d.ts.map +1 -1
- package/dist/resize.js +2 -184
- package/dist/snap.d.ts +1 -1
- package/dist/text-direction.d.ts +13 -0
- package/dist/text-direction.d.ts.map +1 -0
- package/dist/text-direction.js +31 -0
- package/dist/text-direction.js.map +1 -0
- package/dist/text-picture.d.ts +1 -1
- package/dist/text-picture.d.ts.map +1 -1
- package/dist/text.d.ts +2 -0
- package/dist/text.js +3 -0
- package/dist/types.d.ts +2121 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -1
- package/dist/types2.d.ts +2 -2
- package/dist/undo.d.ts +2 -2
- package/dist/undo.js +2 -2
- package/dist/undo2.d.ts +29 -1
- package/dist/undo2.d.ts.map +1 -1
- package/dist/variables.d.ts +2 -29
- package/dist/variables.js +2 -2
- package/dist/variant-properties.d.ts +9 -1
- package/dist/variant-properties.d.ts.map +1 -1
- package/dist/variant-properties.js +36 -1
- package/dist/variant-properties.js.map +1 -1
- package/dist/vector-network.d.ts +1 -1
- package/dist/vector-network.js +1 -1
- package/package.json +60 -9
- package/src/behaviours/kinds.ts +185 -0
- package/src/behaviours/layers.ts +51 -0
- package/src/behaviours/model.ts +192 -0
- package/src/behaviours/schema.ts +58 -0
- package/src/behaviours/spec.ts +223 -0
- package/src/buffered-events.ts +64 -0
- package/src/color/contrast.ts +31 -0
- package/src/color/index.ts +88 -0
- package/src/color/management.ts +210 -0
- package/src/color/normalize.ts +7 -0
- package/src/color/okhcl.ts +201 -0
- package/src/comments/document.ts +51 -0
- package/src/comments/list.ts +52 -0
- package/src/comments/merge.ts +63 -0
- package/src/comments/threads.ts +156 -0
- package/src/components/exposure.ts +61 -0
- package/src/components/properties.ts +18 -15
- package/src/components/variants.ts +53 -0
- package/src/constants.ts +2 -0
- package/src/coordinate.ts +100 -43
- package/src/copy.ts +17 -6
- package/src/css/grid.ts +70 -0
- package/src/css/index.ts +9 -0
- package/src/css/layout.ts +53 -0
- package/src/css/shadows.ts +68 -0
- package/src/css/values.ts +42 -0
- package/src/export-format.ts +12 -0
- package/src/fields/geometry.ts +11 -0
- package/src/fields/text.ts +35 -0
- package/src/gradient.ts +166 -0
- package/src/group-bounds.ts +131 -0
- package/src/guides.ts +39 -0
- package/src/hit-test.ts +262 -46
- package/src/icons/glyph.ts +128 -0
- package/src/icons/model.ts +54 -0
- package/src/icons/schema.ts +18 -0
- package/src/index.ts +347 -57
- package/src/instance-overrides.ts +27 -0
- package/src/instances/content-size.ts +58 -0
- package/src/instances/copies.ts +239 -0
- package/src/instances/cycles.ts +73 -0
- package/src/instances/fields.ts +143 -0
- package/src/instances/main-component.ts +19 -0
- package/src/instances/placement.ts +29 -0
- package/src/instances/source-walk.ts +41 -0
- package/src/instances/sync.ts +600 -0
- package/src/instances/vector-geometry.ts +81 -0
- package/src/instances.ts +125 -330
- package/src/layout/aspect-ratio.ts +51 -0
- package/src/{layout-guides.ts → layout/guides.ts} +41 -12
- package/src/layout/index.ts +4 -0
- package/src/layout/keywords.ts +73 -0
- package/src/layout/sizing.ts +196 -0
- package/src/mutation-impact.ts +25 -10
- package/src/node-defaults.ts +50 -2
- package/src/order-keys.ts +162 -0
- package/src/parse-path.ts +10 -2
- package/src/plugin-data/field.ts +131 -0
- package/src/plugin-data/fields.ts +246 -0
- package/src/polygon.ts +211 -0
- package/src/preview.ts +1 -1
- package/src/random.ts +28 -0
- package/src/resize.ts +99 -12
- package/src/scaling/index.ts +2 -0
- package/src/scaling/node.ts +164 -0
- package/src/scaling/tree.ts +50 -0
- package/src/shaders/model.ts +98 -0
- package/src/shaders/schema.ts +48 -0
- package/src/shared-styles.ts +5 -2
- package/src/slots/authoring.ts +101 -0
- package/src/slots/content.ts +124 -0
- package/src/slots/frames.ts +160 -0
- package/src/slots/limits.ts +49 -0
- package/src/text/direction.ts +55 -0
- package/src/text/index.ts +3 -0
- package/src/text/lists.ts +138 -0
- package/src/text/paragraphs.ts +241 -0
- package/src/{text-picture.ts → text/picture.ts} +21 -29
- package/src/text/references.ts +50 -0
- package/src/transfer/apply.ts +84 -0
- package/src/transfer/history.ts +49 -0
- package/src/transfer/identity.ts +16 -0
- package/src/transfer/index.ts +6 -0
- package/src/transfer/nodes.ts +120 -0
- package/src/transfer/plan.ts +130 -0
- package/src/transfer/references.ts +9 -0
- package/src/transfer/remove.ts +39 -0
- package/src/transfer/validation.ts +59 -0
- package/src/transfer/variables.ts +82 -0
- package/src/types.ts +257 -13
- package/src/undo.ts +54 -2
- package/src/variables/bindings.ts +224 -0
- package/src/variables/fields.ts +43 -0
- package/src/variables/token.ts +14 -0
- package/src/variables/units.ts +15 -0
- package/src/variables.ts +118 -69
- package/src/variant-properties.ts +50 -0
- package/dist/chunks/components/properties.js.map +0 -1
- package/dist/chunks/export-scale.js +0 -19
- package/dist/chunks/export-scale.js.map +0 -1
- package/dist/coordinate.d.ts.map +0 -1
- package/dist/coordinate2.d.ts +0 -2
- package/dist/guides2.d.ts +0 -11
- package/dist/guides2.d.ts.map +0 -1
- package/dist/hit-test.d.ts.map +0 -1
- package/dist/layout-guides.d.ts +0 -2
- package/dist/layout-guides.js +0 -2
- package/dist/layout-guides2.d.ts +0 -16
- package/dist/layout-guides2.d.ts.map +0 -1
- package/dist/node-defaults.d.ts.map +0 -1
- package/dist/preview2.d.ts +0 -12
- package/dist/preview2.d.ts.map +0 -1
- package/dist/resize.js.map +0 -1
- package/dist/variables.d.ts.map +0 -1
- package/dist/vector-network2.d.ts +0 -32
- package/dist/vector-network2.d.ts.map +0 -1
- package/src/instance-overrides.test.ts +0 -67
|
@@ -0,0 +1,2291 @@
|
|
|
1
|
+
import { clearInstanceOverrides, cloneNodeProps, cloneVectorNetwork, copyDerivedGlyphs, copyEffects, copyFills, copyGeometryPaths, copyStroke, copyStrokes, copyStyleRuns, getInstanceOverride, hasInstanceOverride as hasInstanceOverride$1, scaleGeometryPaths, setInstanceOverride, transformVectorNetwork } from "../color/index.js";
|
|
2
|
+
import { randomHex } from "../comments/list.js";
|
|
3
|
+
import { isEqual } from "es-toolkit/predicate";
|
|
4
|
+
//#region src/fields/text.ts
|
|
5
|
+
/** Fields shared by shaping, paragraph measurement, and auto-width invalidation. */
|
|
6
|
+
const TEXT_METRIC_FIELDS = [
|
|
7
|
+
"text",
|
|
8
|
+
"fontSize",
|
|
9
|
+
"fontFamily",
|
|
10
|
+
"fontWeight",
|
|
11
|
+
"italic",
|
|
12
|
+
"letterSpacing",
|
|
13
|
+
"styleRuns",
|
|
14
|
+
"fontVariations",
|
|
15
|
+
"fontFeatures",
|
|
16
|
+
"textParagraphs",
|
|
17
|
+
"listSpacing",
|
|
18
|
+
"paragraphSpacing",
|
|
19
|
+
"paragraphIndent",
|
|
20
|
+
"hangingList"
|
|
21
|
+
];
|
|
22
|
+
const TEXT_SHAPING_FIELDS = [
|
|
23
|
+
...TEXT_METRIC_FIELDS,
|
|
24
|
+
"lineHeight",
|
|
25
|
+
"textCase",
|
|
26
|
+
"textDirection",
|
|
27
|
+
"textAlignHorizontal",
|
|
28
|
+
"textAlignVertical"
|
|
29
|
+
];
|
|
30
|
+
const TEXT_LAYOUT_FIELDS = [
|
|
31
|
+
"width",
|
|
32
|
+
"height",
|
|
33
|
+
"textAutoResize",
|
|
34
|
+
"maxLines"
|
|
35
|
+
];
|
|
36
|
+
//#endregion
|
|
37
|
+
//#region src/layout/sizing.ts
|
|
38
|
+
function primaryAxis(mode) {
|
|
39
|
+
return mode === "VERTICAL" ? "VERTICAL" : "HORIZONTAL";
|
|
40
|
+
}
|
|
41
|
+
/** The auto-layout parent that sizes a node's fill, or `undefined` when nothing does. */
|
|
42
|
+
function fillingParent(parent, node) {
|
|
43
|
+
if (!parent || parent.layoutMode === "NONE" || node.layoutPositioning === "ABSOLUTE") return void 0;
|
|
44
|
+
return parent;
|
|
45
|
+
}
|
|
46
|
+
function graphParent(graph, node) {
|
|
47
|
+
return node.parentId ? graph.getNode(node.parentId) : void 0;
|
|
48
|
+
}
|
|
49
|
+
function fills(parent, node, axis) {
|
|
50
|
+
if (parent.layoutMode === "NONE") return false;
|
|
51
|
+
if (axis === primaryAxis(parent.layoutMode)) return node.layoutGrow > 0;
|
|
52
|
+
if (node.layoutAlignSelf === "STRETCH") return true;
|
|
53
|
+
return node.layoutAlignSelf === "AUTO" && parent.layoutMode !== "GRID" && parent.counterAxisAlign === "STRETCH";
|
|
54
|
+
}
|
|
55
|
+
function ownSizingField(node, axis) {
|
|
56
|
+
if (node.layoutMode === "NONE") return void 0;
|
|
57
|
+
return axis === primaryAxis(node.layoutMode) ? "primaryAxisSizing" : "counterAxisSizing";
|
|
58
|
+
}
|
|
59
|
+
function textHugs(autoResize, axis) {
|
|
60
|
+
if (autoResize === "WIDTH_AND_HEIGHT") return true;
|
|
61
|
+
return axis === "VERTICAL" && autoResize === "HEIGHT";
|
|
62
|
+
}
|
|
63
|
+
function hugs(node, axis) {
|
|
64
|
+
if (node.type === "TEXT") return textHugs(node.textAutoResize, axis);
|
|
65
|
+
const field = ownSizingField(node, axis);
|
|
66
|
+
return field !== void 0 && node[field] === "HUG";
|
|
67
|
+
}
|
|
68
|
+
/** The node's sizing along `axis`: fill from its parent, else its own hug, else fixed. */
|
|
69
|
+
function layoutSizing(graph, node, axis) {
|
|
70
|
+
return layoutSizingInParent(graphParent(graph, node), node, axis);
|
|
71
|
+
}
|
|
72
|
+
/** `layoutSizing` for code that holds the parent rather than the graph. */
|
|
73
|
+
function layoutSizingInParent(parentNode, node, axis) {
|
|
74
|
+
const parent = fillingParent(parentNode, node);
|
|
75
|
+
if (parent && fills(parent, node, axis)) return "FILL";
|
|
76
|
+
if (hugs(node, axis) && (parent || node.layoutMode !== "NONE")) return "HUG";
|
|
77
|
+
return "FIXED";
|
|
78
|
+
}
|
|
79
|
+
/** The sizings this node accepts on either axis, in Figma's order. */
|
|
80
|
+
function layoutSizingOptions(graph, node) {
|
|
81
|
+
return [
|
|
82
|
+
"FIXED",
|
|
83
|
+
"HUG",
|
|
84
|
+
"FILL"
|
|
85
|
+
].filter((value) => layoutSizingError(graph, node, value) === void 0);
|
|
86
|
+
}
|
|
87
|
+
/** Figma's reason for refusing `value` on this node, or `undefined` when it applies. */
|
|
88
|
+
function layoutSizingError(graph, node, value) {
|
|
89
|
+
const parent = graphParent(graph, node);
|
|
90
|
+
const inAutoLayout = parent !== void 0 && parent.layoutMode !== "NONE";
|
|
91
|
+
if (!inAutoLayout && node.layoutMode === "NONE") return "node must be an auto-layout frame or a child of an auto-layout frame";
|
|
92
|
+
if (value === "FILL") {
|
|
93
|
+
if (!inAutoLayout) return "FILL can only be set on children of auto-layout frames";
|
|
94
|
+
if (node.layoutPositioning === "ABSOLUTE") return "FILL cannot be set on absolute positioned auto-layout children";
|
|
95
|
+
}
|
|
96
|
+
if (value === "HUG" && node.layoutMode === "NONE" && node.type !== "TEXT") return "HUG can only be set on auto-layout frames or text children of auto-layout frames";
|
|
97
|
+
}
|
|
98
|
+
/** The text auto-resize that hugs the content along the axes given. */
|
|
99
|
+
function textAutoResizeFor(hugsWidth, hugsHeight) {
|
|
100
|
+
if (hugsWidth && hugsHeight) return "WIDTH_AND_HEIGHT";
|
|
101
|
+
return hugsHeight ? "HEIGHT" : "NONE";
|
|
102
|
+
}
|
|
103
|
+
function textSizingUpdates(graph, node, axis, value) {
|
|
104
|
+
const other = axis === "HORIZONTAL" ? "VERTICAL" : "HORIZONTAL";
|
|
105
|
+
const hugsAxis = value === "HUG";
|
|
106
|
+
const hugsOther = layoutSizing(graph, node, other) === "HUG";
|
|
107
|
+
const autoResize = axis === "HORIZONTAL" ? textAutoResizeFor(hugsAxis, hugsOther) : textAutoResizeFor(hugsOther, hugsAxis);
|
|
108
|
+
if (autoResize === "NONE" && node.textAutoResize === "TRUNCATE") return {};
|
|
109
|
+
return autoResize === node.textAutoResize ? {} : { textAutoResize: autoResize };
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The fields that set the node's sizing along `axis` to `value`, as Figma's setter writes
|
|
113
|
+
* them. A value Figma refuses yields no updates; `layoutSizingError` says why.
|
|
114
|
+
*/
|
|
115
|
+
function layoutSizingUpdates(graph, node, axis, value) {
|
|
116
|
+
if (layoutSizingError(graph, node, value) !== void 0) return {};
|
|
117
|
+
const updates = {};
|
|
118
|
+
const parent = fillingParent(graphParent(graph, node), node);
|
|
119
|
+
if (parent && parent.layoutMode !== "NONE") {
|
|
120
|
+
const fill = value === "FILL";
|
|
121
|
+
if (axis === primaryAxis(parent.layoutMode)) {
|
|
122
|
+
if (fill !== node.layoutGrow > 0) updates.layoutGrow = fill ? 1 : 0;
|
|
123
|
+
} else if (fill && node.layoutAlignSelf !== "STRETCH") updates.layoutAlignSelf = "STRETCH";
|
|
124
|
+
else if (!fill && fills(parent, node, axis)) updates.layoutAlignSelf = parent.layoutMode !== "GRID" && parent.counterAxisAlign === "STRETCH" ? "MIN" : "AUTO";
|
|
125
|
+
}
|
|
126
|
+
const field = ownSizingField(node, axis);
|
|
127
|
+
if (field) {
|
|
128
|
+
const own = value === "HUG" ? "HUG" : "FIXED";
|
|
129
|
+
if (node[field] !== own) updates[field] = own;
|
|
130
|
+
}
|
|
131
|
+
if (node.type === "TEXT") Object.assign(updates, textSizingUpdates(graph, node, axis, value));
|
|
132
|
+
return updates;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The fields that make a child fill `axis` of a parent laid out as `parentLayout`, for a node
|
|
136
|
+
* an importer builds before it joins the graph. Under a parent without auto layout, such as a
|
|
137
|
+
* staging parent the node leaves when placed, both are set, so it fills whichever axis its
|
|
138
|
+
* eventual parent stacks along.
|
|
139
|
+
*/
|
|
140
|
+
function fillSizingFields(parentLayout, axis) {
|
|
141
|
+
if (parentLayout === "NONE") return {
|
|
142
|
+
layoutGrow: 1,
|
|
143
|
+
layoutAlignSelf: "STRETCH"
|
|
144
|
+
};
|
|
145
|
+
return axis === primaryAxis(parentLayout) ? { layoutGrow: 1 } : { layoutAlignSelf: "STRETCH" };
|
|
146
|
+
}
|
|
147
|
+
/** An auto-layout frame's own sizing when it hugs or fixes its width and height. */
|
|
148
|
+
function autoLayoutSizingFields(direction, width, height) {
|
|
149
|
+
const horizontal = primaryAxis(direction) === "HORIZONTAL";
|
|
150
|
+
return {
|
|
151
|
+
primaryAxisSizing: horizontal ? width : height,
|
|
152
|
+
counterAxisSizing: horizontal ? height : width
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
//#region src/instances/content-size.ts
|
|
157
|
+
const METRIC_FIELDS = new Set(TEXT_METRIC_FIELDS);
|
|
158
|
+
/**
|
|
159
|
+
* The axes along which a copy sizes itself to its own content rather than to its component,
|
|
160
|
+
* judged by the state the copy is about to have.
|
|
161
|
+
*/
|
|
162
|
+
function contentSizedAxes(graph, current, source, updates) {
|
|
163
|
+
const copy = {
|
|
164
|
+
...current,
|
|
165
|
+
...updates
|
|
166
|
+
};
|
|
167
|
+
if (copy.type === "TEXT") {
|
|
168
|
+
if (copy.text === source.text) return {
|
|
169
|
+
width: false,
|
|
170
|
+
height: false
|
|
171
|
+
};
|
|
172
|
+
const mode = copy.textAutoResize;
|
|
173
|
+
return {
|
|
174
|
+
width: mode === "WIDTH_AND_HEIGHT",
|
|
175
|
+
height: mode === "WIDTH_AND_HEIGHT" || mode === "HEIGHT"
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
if (copy.layoutMode === "NONE") return {
|
|
179
|
+
width: false,
|
|
180
|
+
height: false
|
|
181
|
+
};
|
|
182
|
+
return {
|
|
183
|
+
width: layoutSizing(graph, copy, "HORIZONTAL") === "HUG",
|
|
184
|
+
height: layoutSizing(graph, copy, "VERTICAL") === "HUG"
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Keeps a copy's own size along the axes it sizes to its own content, as Figma sizes a badge to
|
|
189
|
+
* its count and the layers it shows rather than to the component's placeholder. Layout measures
|
|
190
|
+
* those axes; the component's size there would be stale.
|
|
191
|
+
*/
|
|
192
|
+
function keepOwnContentSize(graph, updates, copy, source) {
|
|
193
|
+
const axes = contentSizedAxes(graph, copy, source, updates);
|
|
194
|
+
if (axes.width) Reflect.deleteProperty(updates, "width");
|
|
195
|
+
if (axes.height) Reflect.deleteProperty(updates, "height");
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Drops the size a text copy kept from the file once a metric reaches it from the component, so
|
|
199
|
+
* layout measures its characters again instead of trusting the size Figma saved for the old style.
|
|
200
|
+
*/
|
|
201
|
+
function remeasureChangedText(updates, copy) {
|
|
202
|
+
if (copy.type !== "TEXT" || !copy.derivedLayout) return;
|
|
203
|
+
if (Object.keys(updates).some((key) => METRIC_FIELDS.has(key))) updates.derivedLayout = null;
|
|
204
|
+
}
|
|
205
|
+
//#endregion
|
|
206
|
+
//#region src/instances/main-component.ts
|
|
207
|
+
/**
|
|
208
|
+
* The main component an instance shows. An instance nested in another instance points at the
|
|
209
|
+
* instance it was cloned from, so follow those links to the component.
|
|
210
|
+
*/
|
|
211
|
+
function instanceMainComponent(graph, instance) {
|
|
212
|
+
const seen = /* @__PURE__ */ new Set();
|
|
213
|
+
let current = instance.componentId ? graph.getNode(instance.componentId) : void 0;
|
|
214
|
+
while (current?.type === "INSTANCE" && current.componentId && !seen.has(current.id)) {
|
|
215
|
+
seen.add(current.id);
|
|
216
|
+
current = graph.getNode(current.componentId);
|
|
217
|
+
}
|
|
218
|
+
return current?.type === "COMPONENT" ? current : void 0;
|
|
219
|
+
}
|
|
220
|
+
//#endregion
|
|
221
|
+
//#region src/slots/frames.ts
|
|
222
|
+
/** The slot property a frame holds the content of, if it is a slot. */
|
|
223
|
+
function slotPropertyId(node) {
|
|
224
|
+
return node.componentPropertyReferences.find((reference) => reference.field === "SLOT_CONTENT")?.propertyId;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Whether this slot frame's children belong to its instance rather than its component: the
|
|
228
|
+
* nearest enclosing instance assigns the slot. Such content is never synced from the component.
|
|
229
|
+
*/
|
|
230
|
+
function ownsSlotContent(graph, node, propertyId = slotPropertyId(node)) {
|
|
231
|
+
if (!propertyId) return false;
|
|
232
|
+
let owner = node.parentId ? graph.nodes.get(node.parentId) : void 0;
|
|
233
|
+
while (owner && owner.type !== "INSTANCE") owner = owner.parentId ? graph.nodes.get(owner.parentId) : void 0;
|
|
234
|
+
return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId);
|
|
235
|
+
}
|
|
236
|
+
/** The name of a slot property as the instance's component (or the component's set) defines it. */
|
|
237
|
+
function slotName(graph, instance, propertyId) {
|
|
238
|
+
const component = instanceMainComponent(graph, instance);
|
|
239
|
+
return [component, component?.parentId ? graph.nodes.get(component.parentId) : void 0].flatMap((node) => node?.componentPropertyDefinitions ?? []).find((definition) => definition.id === propertyId && definition.type === "SLOT")?.name;
|
|
240
|
+
}
|
|
241
|
+
/** An instance's slot frames, without entering nested instances, whose slots are their own. */
|
|
242
|
+
function instanceSlotFrames(graph, instance) {
|
|
243
|
+
const frames = [];
|
|
244
|
+
const visit = (node) => {
|
|
245
|
+
for (const childId of node.childIds) {
|
|
246
|
+
const child = graph.nodes.get(childId);
|
|
247
|
+
if (!child) continue;
|
|
248
|
+
if (slotPropertyId(child)) frames.push(child);
|
|
249
|
+
else if (child.type !== "INSTANCE") visit(child);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
visit(instance);
|
|
253
|
+
return frames;
|
|
254
|
+
}
|
|
255
|
+
/** Instances directly inside this one: not inside another nested instance or a slot. */
|
|
256
|
+
function nestedInstances(graph, owner) {
|
|
257
|
+
const found = [];
|
|
258
|
+
const visit = (node) => {
|
|
259
|
+
for (const childId of node.childIds) {
|
|
260
|
+
const child = graph.nodes.get(childId);
|
|
261
|
+
if (!child || slotPropertyId(child)) continue;
|
|
262
|
+
if (child.type === "INSTANCE") found.push(child);
|
|
263
|
+
else visit(child);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
visit(owner);
|
|
267
|
+
return found;
|
|
268
|
+
}
|
|
269
|
+
/** The nested instance a name path leads to from `root`, matched by layer name as Figma does. */
|
|
270
|
+
function instanceAtPath(graph, root, path) {
|
|
271
|
+
let current = root;
|
|
272
|
+
for (const name of path) current = current && nestedInstances(graph, current).find((node) => node.name === name);
|
|
273
|
+
return current;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Park the slot content an instance and the instances nested in it own, by slot name and the
|
|
277
|
+
* nested instance's name path, directly under the instance, so its component can be replaced.
|
|
278
|
+
* Figma keeps that content when a variant switch or swap leads to slots of the same names.
|
|
279
|
+
*/
|
|
280
|
+
function detachOwnedSlotContent(graph, instance) {
|
|
281
|
+
const parked = {
|
|
282
|
+
slots: [],
|
|
283
|
+
propertyIds: []
|
|
284
|
+
};
|
|
285
|
+
const visit = (owner, path) => {
|
|
286
|
+
for (const nested of nestedInstances(graph, owner)) visit(nested, [...path, nested.name]);
|
|
287
|
+
for (const frame of instanceSlotFrames(graph, owner)) {
|
|
288
|
+
const propertyId = slotPropertyId(frame);
|
|
289
|
+
if (!propertyId || !Object.hasOwn(owner.componentPropertyAssignments, propertyId)) continue;
|
|
290
|
+
if (owner.id === instance.id) parked.propertyIds.push(propertyId);
|
|
291
|
+
const name = slotName(graph, owner, propertyId);
|
|
292
|
+
const key = [...path, name].join("\0");
|
|
293
|
+
if (!name || parked.slots.some((slot) => [...slot.path, slot.name].join("\0") === key)) continue;
|
|
294
|
+
const content = [...frame.childIds];
|
|
295
|
+
for (const id of content) graph.reorderChild(id, instance.id, instance.childIds.length);
|
|
296
|
+
parked.slots.push({
|
|
297
|
+
path,
|
|
298
|
+
name,
|
|
299
|
+
content
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
visit(instance, []);
|
|
304
|
+
return parked;
|
|
305
|
+
}
|
|
306
|
+
/** Move parked content into the slots of the same names and paths, and reassign them. */
|
|
307
|
+
function restoreOwnedSlotContent(graph, instance, parked) {
|
|
308
|
+
if (parked.slots.length === 0 && parked.propertyIds.length === 0) return;
|
|
309
|
+
graph.updateNode(instance.id, { componentPropertyAssignments: Object.fromEntries(Object.entries(instance.componentPropertyAssignments).filter(([id]) => !parked.propertyIds.includes(id))) });
|
|
310
|
+
for (const slot of parked.slots) {
|
|
311
|
+
const owner = instanceAtPath(graph, instance, slot.path);
|
|
312
|
+
const frame = owner && instanceSlotFrames(graph, owner).find((candidate) => {
|
|
313
|
+
const propertyId = slotPropertyId(candidate);
|
|
314
|
+
return !!propertyId && slotName(graph, owner, propertyId) === slot.name;
|
|
315
|
+
});
|
|
316
|
+
const propertyId = frame && slotPropertyId(frame);
|
|
317
|
+
if (!owner || !frame || !propertyId || Object.hasOwn(owner.componentPropertyAssignments, propertyId)) {
|
|
318
|
+
for (const id of slot.content) graph.deleteNode(id);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
for (const id of Array.from(frame.childIds)) graph.deleteNode(id);
|
|
322
|
+
for (const [index, id] of slot.content.entries()) graph.reorderChild(id, frame.id, index);
|
|
323
|
+
graph.updateNode(owner.id, { componentPropertyAssignments: {
|
|
324
|
+
...owner.componentPropertyAssignments,
|
|
325
|
+
[propertyId]: ""
|
|
326
|
+
} });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
//#endregion
|
|
330
|
+
//#region src/undo.ts
|
|
331
|
+
/** How many edits undo keeps by default. */
|
|
332
|
+
const DEFAULT_HISTORY_LIMIT = 200;
|
|
333
|
+
var UndoManager = class {
|
|
334
|
+
undoStack = [];
|
|
335
|
+
redoStack = [];
|
|
336
|
+
batches = [];
|
|
337
|
+
settlers = /* @__PURE__ */ new Set();
|
|
338
|
+
limit;
|
|
339
|
+
onChange;
|
|
340
|
+
constructor(options = {}) {
|
|
341
|
+
this.limit = options.limit ?? 200;
|
|
342
|
+
this.onChange = options.onChange;
|
|
343
|
+
}
|
|
344
|
+
apply(entry) {
|
|
345
|
+
this.execute(entry);
|
|
346
|
+
}
|
|
347
|
+
execute(entry) {
|
|
348
|
+
entry.forward();
|
|
349
|
+
this.record(entry);
|
|
350
|
+
}
|
|
351
|
+
push(entry) {
|
|
352
|
+
this.record(entry);
|
|
353
|
+
}
|
|
354
|
+
record(entry) {
|
|
355
|
+
const batch = this.currentBatch;
|
|
356
|
+
if (batch) {
|
|
357
|
+
batch.entries.push(entry);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
this.pushUndoEntry(entry);
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Records an entry as a step of its own, outside the batches being built, such as an agent's
|
|
364
|
+
* edit made while a colour picker is open. Batches settle first, so the step follows the
|
|
365
|
+
* changes they hold so far.
|
|
366
|
+
*/
|
|
367
|
+
pushStep(entry) {
|
|
368
|
+
this.settle();
|
|
369
|
+
this.pushUndoEntry(entry);
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Registers a hook that commits an edit still being coalesced, such as a run of picker changes.
|
|
373
|
+
* Undo and redo run every hook first, so they act on the newest change.
|
|
374
|
+
*/
|
|
375
|
+
onBeforeHistory(settle) {
|
|
376
|
+
this.settlers.add(settle);
|
|
377
|
+
return () => this.settlers.delete(settle);
|
|
378
|
+
}
|
|
379
|
+
settle() {
|
|
380
|
+
for (const settle of this.settlers) settle();
|
|
381
|
+
}
|
|
382
|
+
undo() {
|
|
383
|
+
this.settle();
|
|
384
|
+
const entry = this.undoStack.pop();
|
|
385
|
+
if (!entry) return null;
|
|
386
|
+
entry.inverse();
|
|
387
|
+
this.redoStack.push(entry);
|
|
388
|
+
this.onChange?.();
|
|
389
|
+
return entry.label;
|
|
390
|
+
}
|
|
391
|
+
redo() {
|
|
392
|
+
this.settle();
|
|
393
|
+
const entry = this.redoStack.pop();
|
|
394
|
+
if (!entry) return null;
|
|
395
|
+
entry.forward();
|
|
396
|
+
this.undoStack.push(entry);
|
|
397
|
+
this.onChange?.();
|
|
398
|
+
return entry.label;
|
|
399
|
+
}
|
|
400
|
+
beginBatch(label, coalesceKey) {
|
|
401
|
+
this.batches.push({
|
|
402
|
+
label,
|
|
403
|
+
entries: [],
|
|
404
|
+
coalesceKey
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
commitBatch() {
|
|
408
|
+
const batch = this.batches.pop();
|
|
409
|
+
if (!batch || batch.entries.length === 0) return;
|
|
410
|
+
const entry = this.createBatchEntry(batch);
|
|
411
|
+
const parentBatch = this.currentBatch;
|
|
412
|
+
if (parentBatch) parentBatch.entries.push(entry);
|
|
413
|
+
else this.pushUndoEntry(entry);
|
|
414
|
+
}
|
|
415
|
+
runBatch(label, fn, coalesceKey) {
|
|
416
|
+
this.beginBatch(label, coalesceKey);
|
|
417
|
+
try {
|
|
418
|
+
const result = fn();
|
|
419
|
+
this.commitBatch();
|
|
420
|
+
return result;
|
|
421
|
+
} catch (error) {
|
|
422
|
+
this.rollbackBatch();
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
rollbackBatch() {
|
|
427
|
+
const batch = this.batches.pop();
|
|
428
|
+
if (!batch) return;
|
|
429
|
+
for (const entry of batch.entries.toReversed()) entry.inverse();
|
|
430
|
+
}
|
|
431
|
+
/** Abandon provisional history without replaying it or changing committed undo/redo entries. */
|
|
432
|
+
discardBatches() {
|
|
433
|
+
this.batches = [];
|
|
434
|
+
}
|
|
435
|
+
clear() {
|
|
436
|
+
this.undoStack = [];
|
|
437
|
+
this.redoStack = [];
|
|
438
|
+
this.discardBatches();
|
|
439
|
+
this.onChange?.();
|
|
440
|
+
}
|
|
441
|
+
get isBatching() {
|
|
442
|
+
return this.batches.length > 0;
|
|
443
|
+
}
|
|
444
|
+
/** Committed history, or changes in an open batch that a settling hook commits first. */
|
|
445
|
+
get canUndo() {
|
|
446
|
+
if (this.undoStack.length > 0) return true;
|
|
447
|
+
return this.settlers.size > 0 && this.batches.some((batch) => batch.entries.length > 0);
|
|
448
|
+
}
|
|
449
|
+
get canRedo() {
|
|
450
|
+
return this.redoStack.length > 0;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* The entry `depth` steps below the top of the undo stack, so a caller that pushed entries
|
|
454
|
+
* can tell whether they are still the most recent ones.
|
|
455
|
+
*/
|
|
456
|
+
peekUndo(depth = 0) {
|
|
457
|
+
return this.undoStack.at(-1 - depth);
|
|
458
|
+
}
|
|
459
|
+
/** The entry `depth` steps below the top of the redo stack, the next one Redo applies at 0. */
|
|
460
|
+
peekRedo(depth = 0) {
|
|
461
|
+
return this.redoStack.at(-1 - depth);
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Whether `entry` is applied (on the undo stack) or undone (on the redo stack); null once it
|
|
465
|
+
* left the history, trimmed or dropped when an edit cleared Redo.
|
|
466
|
+
*/
|
|
467
|
+
stateOf(entry) {
|
|
468
|
+
if (this.undoStack.includes(entry)) return "applied";
|
|
469
|
+
if (this.redoStack.includes(entry)) return "undone";
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
get undoLabel() {
|
|
473
|
+
return this.undoStack.at(-1)?.label ?? null;
|
|
474
|
+
}
|
|
475
|
+
get redoLabel() {
|
|
476
|
+
return this.redoStack.at(-1)?.label ?? null;
|
|
477
|
+
}
|
|
478
|
+
get currentBatch() {
|
|
479
|
+
return this.batches.at(-1) ?? null;
|
|
480
|
+
}
|
|
481
|
+
createBatchEntry(batch) {
|
|
482
|
+
return {
|
|
483
|
+
label: batch.label,
|
|
484
|
+
forward: () => batch.entries.forEach((entry) => entry.forward()),
|
|
485
|
+
inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()),
|
|
486
|
+
coalesceKey: batch.coalesceKey
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
pushUndoEntry(entry) {
|
|
490
|
+
const previous = this.undoStack.at(-1);
|
|
491
|
+
if (entry.coalesceKey && previous?.coalesceKey === entry.coalesceKey) this.undoStack[this.undoStack.length - 1] = {
|
|
492
|
+
...entry,
|
|
493
|
+
inverse: previous.inverse
|
|
494
|
+
};
|
|
495
|
+
else this.undoStack.push(entry);
|
|
496
|
+
this.redoStack = [];
|
|
497
|
+
this.trimUndoStack();
|
|
498
|
+
this.onChange?.();
|
|
499
|
+
}
|
|
500
|
+
trimUndoStack() {
|
|
501
|
+
if (!Number.isFinite(this.limit) || this.limit <= 0) return;
|
|
502
|
+
const overflow = this.undoStack.length - this.limit;
|
|
503
|
+
if (overflow > 0) this.undoStack.splice(0, overflow);
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
//#endregion
|
|
507
|
+
//#region src/instances/copies.ts
|
|
508
|
+
function createInstanceSyncContext(instanceId, overrides) {
|
|
509
|
+
return {
|
|
510
|
+
instanceId,
|
|
511
|
+
overrides,
|
|
512
|
+
matched: /* @__PURE__ */ new Set(),
|
|
513
|
+
leftovers: /* @__PURE__ */ new Set()
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
/** The component layer a copy in the instance stands for. */
|
|
517
|
+
function copiedLayerId(node, context) {
|
|
518
|
+
const source = node.type === "INSTANCE" ? getInstanceOverride(context.overrides, context.instanceId, node.id, "sourceComponentId") : void 0;
|
|
519
|
+
return typeof source === "string" ? source : node.componentId ?? void 0;
|
|
520
|
+
}
|
|
521
|
+
/** Whether sync goes inside a copy: not into slot content, a swapped instance, or an instance. */
|
|
522
|
+
function syncsInside(graph, node, context) {
|
|
523
|
+
if (node.type === "INSTANCE") return false;
|
|
524
|
+
if (hasInstanceOverride$1(context.overrides, context.instanceId, node.id, "componentId")) return false;
|
|
525
|
+
const layer = node.componentId ? graph.nodes.get(node.componentId) : void 0;
|
|
526
|
+
return !layer || !ownsSlotContent(graph, node, slotPropertyId(layer));
|
|
527
|
+
}
|
|
528
|
+
function copiesOf(graph, context) {
|
|
529
|
+
if (context.copies) return context.copies;
|
|
530
|
+
const copies = /* @__PURE__ */ new Map();
|
|
531
|
+
const visit = (parent) => {
|
|
532
|
+
for (const id of parent.childIds) {
|
|
533
|
+
const child = graph.nodes.get(id);
|
|
534
|
+
if (!child) continue;
|
|
535
|
+
const layerId = copiedLayerId(child, context);
|
|
536
|
+
if (layerId) copies.set(layerId, [...copies.get(layerId) ?? [], child]);
|
|
537
|
+
if (syncsInside(graph, child, context)) visit(child);
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
const instance = graph.nodes.get(context.instanceId);
|
|
541
|
+
if (instance) visit(instance);
|
|
542
|
+
context.copies = copies;
|
|
543
|
+
return copies;
|
|
544
|
+
}
|
|
545
|
+
/** A copy of `layerId` the sync has not placed yet, which a moved layer takes along. */
|
|
546
|
+
function unplacedCopy(graph, context, layerId, instParentId) {
|
|
547
|
+
return copiesOf(graph, context).get(layerId)?.find((copy) => !context.matched.has(copy.id) && graph.nodes.has(copy.id) && copy.id !== instParentId && !graph.isDescendant(instParentId, copy.id));
|
|
548
|
+
}
|
|
549
|
+
/** Whether any layer in the component subtree at `layerId` already has a copy to move. */
|
|
550
|
+
function hasUnplacedCopiesBelow(graph, context, layerId) {
|
|
551
|
+
const copies = copiesOf(graph, context);
|
|
552
|
+
if (copies.size === 0) return false;
|
|
553
|
+
return (graph.nodes.get(layerId)?.childIds ?? []).some((id) => copies.get(id)?.some((copy) => !context.matched.has(copy.id)) || hasUnplacedCopiesBelow(graph, context, id));
|
|
554
|
+
}
|
|
555
|
+
const removedCopies = /* @__PURE__ */ new WeakMap();
|
|
556
|
+
function removedCopyStore(graph) {
|
|
557
|
+
let store = removedCopies.get(graph);
|
|
558
|
+
if (!store) {
|
|
559
|
+
store = {
|
|
560
|
+
byInstance: /* @__PURE__ */ new Map(),
|
|
561
|
+
removals: []
|
|
562
|
+
};
|
|
563
|
+
removedCopies.set(graph, store);
|
|
564
|
+
}
|
|
565
|
+
return store;
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Keeps one edit's removed copies restorable. Only as many edits as undo keeps are kept, so
|
|
569
|
+
* copies no undo can bring back are forgotten, oldest first.
|
|
570
|
+
*/
|
|
571
|
+
function keepCopyRemovals(graph, removals) {
|
|
572
|
+
if (removals.keys.length === 0) return;
|
|
573
|
+
const store = removedCopyStore(graph);
|
|
574
|
+
store.removals.push(removals);
|
|
575
|
+
while (store.removals.length > 200) {
|
|
576
|
+
const oldest = store.removals.shift();
|
|
577
|
+
for (const [instanceId, layerId] of oldest?.keys ?? []) {
|
|
578
|
+
const copies = store.byInstance.get(instanceId);
|
|
579
|
+
if (!copies || copies.get(layerId)?.removals !== oldest) continue;
|
|
580
|
+
copies.delete(layerId);
|
|
581
|
+
if (copies.size === 0) store.byInstance.delete(instanceId);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
const activeRemovals = /* @__PURE__ */ new WeakMap();
|
|
586
|
+
/**
|
|
587
|
+
* Runs `fn` with every copy the syncs inside it remove kept as one group: one edit's syncs, however
|
|
588
|
+
* many components they reach, take one place in the history of removals.
|
|
589
|
+
*/
|
|
590
|
+
function groupCopyRemovals(graph, fn) {
|
|
591
|
+
const active = activeRemovals.get(graph);
|
|
592
|
+
if (active) return fn(active);
|
|
593
|
+
const removals = { keys: [] };
|
|
594
|
+
activeRemovals.set(graph, removals);
|
|
595
|
+
try {
|
|
596
|
+
return fn(removals);
|
|
597
|
+
} finally {
|
|
598
|
+
activeRemovals.delete(graph);
|
|
599
|
+
keepCopyRemovals(graph, removals);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Brings back the copy of `layerId` the sync removed from this instance, with the same layers
|
|
604
|
+
* and overrides, as Figma restores an instance's override when the layer's deletion is undone.
|
|
605
|
+
*/
|
|
606
|
+
function restoreRemovedCopy(graph, context, layerId, instParentId) {
|
|
607
|
+
const store = removedCopyStore(graph);
|
|
608
|
+
const removed = store.byInstance.get(context.instanceId);
|
|
609
|
+
const entry = removed?.get(layerId);
|
|
610
|
+
if (!removed || !entry) return void 0;
|
|
611
|
+
removed.delete(layerId);
|
|
612
|
+
if (removed.size === 0) store.byInstance.delete(context.instanceId);
|
|
613
|
+
const root = entry.nodes.at(0);
|
|
614
|
+
if (!root || entry.nodes.some((node) => graph.nodes.has(node.id))) return void 0;
|
|
615
|
+
for (const node of entry.nodes) {
|
|
616
|
+
const { id, type, parentId, childIds: _childIds, ...props } = structuredClone(node);
|
|
617
|
+
graph.createNodeWithId(id, type, id === root.id ? instParentId : parentId, props);
|
|
618
|
+
}
|
|
619
|
+
for (const [id, fields] of entry.overrides) context.overrides.descendants.set(id, new Map(fields));
|
|
620
|
+
return graph.nodes.get(root.id);
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Deletes the copies the sync left over: ones whose layer left the component, was deleted, or
|
|
624
|
+
* now has another copy. Copies the instance owns, such as slot content, are never reached.
|
|
625
|
+
*/
|
|
626
|
+
function removeLeftoverCopies(graph, context, removals) {
|
|
627
|
+
const store = removedCopyStore(graph);
|
|
628
|
+
for (const id of context.leftovers) {
|
|
629
|
+
const node = graph.nodes.get(id);
|
|
630
|
+
const layerId = node ? copiedLayerId(node, context) : void 0;
|
|
631
|
+
if (!node || !layerId || context.matched.has(id)) continue;
|
|
632
|
+
const nodes = [];
|
|
633
|
+
const collect = (current) => {
|
|
634
|
+
nodes.push(structuredClone(current));
|
|
635
|
+
for (const childId of current.childIds) {
|
|
636
|
+
const child = graph.nodes.get(childId);
|
|
637
|
+
if (child) collect(child);
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
collect(node);
|
|
641
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
642
|
+
for (const removed of nodes) {
|
|
643
|
+
const fields = context.overrides.descendants.get(removed.id);
|
|
644
|
+
if (fields) overrides.set(removed.id, new Map(fields));
|
|
645
|
+
context.overrides.descendants.delete(removed.id);
|
|
646
|
+
}
|
|
647
|
+
let copies = store.byInstance.get(context.instanceId);
|
|
648
|
+
if (!copies) {
|
|
649
|
+
copies = /* @__PURE__ */ new Map();
|
|
650
|
+
store.byInstance.set(context.instanceId, copies);
|
|
651
|
+
}
|
|
652
|
+
copies.set(layerId, {
|
|
653
|
+
nodes,
|
|
654
|
+
overrides,
|
|
655
|
+
removals
|
|
656
|
+
});
|
|
657
|
+
removals.keys.push([context.instanceId, layerId]);
|
|
658
|
+
graph.deleteNode(id);
|
|
659
|
+
}
|
|
660
|
+
context.leftovers.clear();
|
|
661
|
+
}
|
|
662
|
+
//#endregion
|
|
663
|
+
//#region src/instances/cycles.ts
|
|
664
|
+
/** Components at or above `parentId`, counting the component each enclosing instance shows. */
|
|
665
|
+
function enclosingComponents(graph, parentId) {
|
|
666
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
667
|
+
graph.closest(parentId, (node) => {
|
|
668
|
+
if (node.type === "COMPONENT") ancestors.add(node.id);
|
|
669
|
+
if (node.type === "INSTANCE") {
|
|
670
|
+
const main = instanceMainComponent(graph, node);
|
|
671
|
+
if (main) ancestors.add(main.id);
|
|
672
|
+
}
|
|
673
|
+
return false;
|
|
674
|
+
});
|
|
675
|
+
return ancestors;
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Whether moving `nodeId` under `parentId` would make a component contain itself: its layers,
|
|
679
|
+
* followed through instances into their components, reach a component at or above the parent.
|
|
680
|
+
* Both components and instances above the parent count: an instance's layers are its
|
|
681
|
+
* component's, so a swap inside one may not bring that component back in.
|
|
682
|
+
*/
|
|
683
|
+
function createsComponentCycle(graph, nodeId, parentId) {
|
|
684
|
+
const ancestors = enclosingComponents(graph, parentId);
|
|
685
|
+
if (ancestors.size === 0) return false;
|
|
686
|
+
const visited = /* @__PURE__ */ new Set();
|
|
687
|
+
function reachesAncestor(id) {
|
|
688
|
+
if (ancestors.has(id)) return true;
|
|
689
|
+
if (visited.has(id)) return false;
|
|
690
|
+
visited.add(id);
|
|
691
|
+
const node = graph.getNode(id);
|
|
692
|
+
if (!node) return false;
|
|
693
|
+
if (node.type === "INSTANCE" && node.componentId && reachesAncestor(node.componentId)) return true;
|
|
694
|
+
return node.childIds.some(reachesAncestor);
|
|
695
|
+
}
|
|
696
|
+
return reachesAncestor(nodeId);
|
|
697
|
+
}
|
|
698
|
+
/** Whether placing this definition's instance under `parentId` would make a component contain itself. */
|
|
699
|
+
function canCreateInstance(graph, componentId, parentId) {
|
|
700
|
+
if (graph.getNode(componentId)?.type !== "COMPONENT") return false;
|
|
701
|
+
return !createsComponentCycle(graph, componentId, parentId);
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* `parentId`, or its nearest ancestor that can hold these layers or instances of these
|
|
705
|
+
* components without a component containing itself. Figma pastes an instance next to its own
|
|
706
|
+
* component, not in it.
|
|
707
|
+
*/
|
|
708
|
+
function cycleSafeParent(graph, parentId, nodeIds) {
|
|
709
|
+
return graph.closest(parentId, (node) => (node.id === parentId || node.type !== "COMPONENT_SET") && nodeIds.every((id) => !createsComponentCycle(graph, id, node.id)))?.id ?? parentId;
|
|
710
|
+
}
|
|
711
|
+
//#endregion
|
|
712
|
+
//#region src/instances/fields.ts
|
|
713
|
+
const INSTANCE_SYNC_TEXT_PROPS = [
|
|
714
|
+
"name",
|
|
715
|
+
"text",
|
|
716
|
+
"fontSize",
|
|
717
|
+
"fontWeight",
|
|
718
|
+
"fontFamily",
|
|
719
|
+
"italic",
|
|
720
|
+
"textDirection",
|
|
721
|
+
"letterSpacing",
|
|
722
|
+
"lineHeight",
|
|
723
|
+
"textCase",
|
|
724
|
+
"textDecoration",
|
|
725
|
+
"textDecorationStyle",
|
|
726
|
+
"textDecorationThickness",
|
|
727
|
+
"textUnderlineOffset",
|
|
728
|
+
"textDecorationFills",
|
|
729
|
+
"textDecorationSkipInk",
|
|
730
|
+
"textAlignHorizontal",
|
|
731
|
+
"textAlignVertical",
|
|
732
|
+
"textAutoResize",
|
|
733
|
+
"textTruncation",
|
|
734
|
+
"maxLines",
|
|
735
|
+
"leadingTrim",
|
|
736
|
+
"paragraphSpacing",
|
|
737
|
+
"paragraphIndent",
|
|
738
|
+
"listSpacing",
|
|
739
|
+
"hangingList",
|
|
740
|
+
"fontVariations",
|
|
741
|
+
"fontFeatures",
|
|
742
|
+
"styleRuns",
|
|
743
|
+
"textParagraphs"
|
|
744
|
+
];
|
|
745
|
+
/** Fields that belong to another one: overriding the owner keeps them too. */
|
|
746
|
+
const INSTANCE_SYNC_FIELD_OWNERS = {
|
|
747
|
+
styleRuns: "text",
|
|
748
|
+
textParagraphs: "text"
|
|
749
|
+
};
|
|
750
|
+
const INSTANCE_SYNC_PROPS = [
|
|
751
|
+
"width",
|
|
752
|
+
"height",
|
|
753
|
+
"minWidth",
|
|
754
|
+
"maxWidth",
|
|
755
|
+
"minHeight",
|
|
756
|
+
"maxHeight",
|
|
757
|
+
"targetAspectRatio",
|
|
758
|
+
"fills",
|
|
759
|
+
"strokes",
|
|
760
|
+
"effects",
|
|
761
|
+
"opacity",
|
|
762
|
+
"cornerRadius",
|
|
763
|
+
"topLeftRadius",
|
|
764
|
+
"topRightRadius",
|
|
765
|
+
"bottomRightRadius",
|
|
766
|
+
"bottomLeftRadius",
|
|
767
|
+
"independentCorners",
|
|
768
|
+
"layoutMode",
|
|
769
|
+
"layoutDirection",
|
|
770
|
+
"layoutWrap",
|
|
771
|
+
"primaryAxisAlign",
|
|
772
|
+
"counterAxisAlign",
|
|
773
|
+
"primaryAxisSizing",
|
|
774
|
+
"counterAxisSizing",
|
|
775
|
+
"itemSpacing",
|
|
776
|
+
"counterAxisSpacing",
|
|
777
|
+
"paddingTop",
|
|
778
|
+
"paddingRight",
|
|
779
|
+
"paddingBottom",
|
|
780
|
+
"paddingLeft",
|
|
781
|
+
"gridTemplateColumns",
|
|
782
|
+
"gridTemplateRows",
|
|
783
|
+
"gridColumnGap",
|
|
784
|
+
"gridRowGap",
|
|
785
|
+
"gridPosition",
|
|
786
|
+
"clipsContent",
|
|
787
|
+
"counterAxisAlignContent",
|
|
788
|
+
"itemReverseZIndex",
|
|
789
|
+
"strokesIncludedInLayout",
|
|
790
|
+
"layoutGrids",
|
|
791
|
+
"blendMode",
|
|
792
|
+
"cornerSmoothing",
|
|
793
|
+
"strokeWeight",
|
|
794
|
+
"strokeAlign",
|
|
795
|
+
"strokeCap",
|
|
796
|
+
"strokeJoin",
|
|
797
|
+
"strokeMiterLimit",
|
|
798
|
+
"dashPattern",
|
|
799
|
+
"independentStrokeWeights",
|
|
800
|
+
"borderTopWeight",
|
|
801
|
+
"borderRightWeight",
|
|
802
|
+
"borderBottomWeight",
|
|
803
|
+
"borderLeftWeight",
|
|
804
|
+
"boundVariables",
|
|
805
|
+
"variableModes",
|
|
806
|
+
"fillStyleId",
|
|
807
|
+
"strokeStyleId",
|
|
808
|
+
"textStyleId",
|
|
809
|
+
"effectStyleId",
|
|
810
|
+
"gridStyleId"
|
|
811
|
+
];
|
|
812
|
+
/** How a layer inside an instance sits in its parent and whether it is locked, which its overrides may change. */
|
|
813
|
+
const INSTANCE_SYNC_CHILD_PROPS = [
|
|
814
|
+
"layoutGrow",
|
|
815
|
+
"layoutAlignSelf",
|
|
816
|
+
"locked"
|
|
817
|
+
];
|
|
818
|
+
/**
|
|
819
|
+
* Where a component's layer sits and how it is shaped, which Figma refuses to override in an
|
|
820
|
+
* instance ("This property cannot be overridden in an instance"), so its copies always follow.
|
|
821
|
+
* A layer in an auto layout flow takes its position from the layout instead.
|
|
822
|
+
*/
|
|
823
|
+
const INSTANCE_FOLLOWED_FIELDS = [
|
|
824
|
+
"x",
|
|
825
|
+
"y",
|
|
826
|
+
"rotation",
|
|
827
|
+
"flipX",
|
|
828
|
+
"flipY",
|
|
829
|
+
"horizontalConstraint",
|
|
830
|
+
"verticalConstraint",
|
|
831
|
+
"layoutPositioning",
|
|
832
|
+
"isMask",
|
|
833
|
+
"maskType",
|
|
834
|
+
"arcData",
|
|
835
|
+
"pointCount",
|
|
836
|
+
"starInnerRadius"
|
|
837
|
+
];
|
|
838
|
+
/** Fields an edit to a layer inside an instance records as that instance's override. */
|
|
839
|
+
const INSTANCE_OVERRIDE_FIELDS = [
|
|
840
|
+
...INSTANCE_SYNC_PROPS,
|
|
841
|
+
...INSTANCE_SYNC_TEXT_PROPS,
|
|
842
|
+
...INSTANCE_SYNC_CHILD_PROPS,
|
|
843
|
+
"visible"
|
|
844
|
+
];
|
|
845
|
+
/** Fields a component's layer gives the copies of it in every instance. */
|
|
846
|
+
const INSTANCE_SYNC_FIELDS = [...INSTANCE_OVERRIDE_FIELDS, ...INSTANCE_FOLLOWED_FIELDS];
|
|
847
|
+
//#endregion
|
|
848
|
+
//#region src/text/paragraphs.ts
|
|
849
|
+
/** The style of a paragraph with no entry: not in a list. */
|
|
850
|
+
const PLAIN_PARAGRAPH = Object.freeze({
|
|
851
|
+
listType: "NONE",
|
|
852
|
+
indentation: 0
|
|
853
|
+
});
|
|
854
|
+
/** Figma nests list items at most this deep. */
|
|
855
|
+
const MAX_LIST_INDENTATION = 5;
|
|
856
|
+
/** The paragraphs of `text`: one per line ending at a newline, and one after the last. */
|
|
857
|
+
function textParagraphRanges(text) {
|
|
858
|
+
const ranges = [];
|
|
859
|
+
let start = 0;
|
|
860
|
+
for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", start)) {
|
|
861
|
+
ranges.push({
|
|
862
|
+
start,
|
|
863
|
+
end: index
|
|
864
|
+
});
|
|
865
|
+
start = index + 1;
|
|
866
|
+
}
|
|
867
|
+
ranges.push({
|
|
868
|
+
start,
|
|
869
|
+
end: text.length
|
|
870
|
+
});
|
|
871
|
+
return ranges;
|
|
872
|
+
}
|
|
873
|
+
/** The paragraph holding character `index`; a newline belongs to the paragraph it ends. */
|
|
874
|
+
function paragraphIndexAt(text, index) {
|
|
875
|
+
let paragraph = 0;
|
|
876
|
+
const end = Math.min(index, text.length);
|
|
877
|
+
for (let at = text.indexOf("\n"); at !== -1 && at < end; at = text.indexOf("\n", at + 1)) paragraph++;
|
|
878
|
+
return paragraph;
|
|
879
|
+
}
|
|
880
|
+
function paragraphStyleAt(paragraphs, paragraph) {
|
|
881
|
+
return paragraphs[paragraph] ?? PLAIN_PARAGRAPH;
|
|
882
|
+
}
|
|
883
|
+
const TEXT_PARAGRAPH_SPACING_FIELDS = [
|
|
884
|
+
"listSpacing",
|
|
885
|
+
"paragraphSpacing",
|
|
886
|
+
"paragraphIndent"
|
|
887
|
+
];
|
|
888
|
+
/** A paragraph's spacing: its own value, or the text's when it sets none. */
|
|
889
|
+
function paragraphSpacingAt(node, paragraph, field) {
|
|
890
|
+
return paragraphStyleAt(node.textParagraphs, paragraph)[field] ?? node[field];
|
|
891
|
+
}
|
|
892
|
+
/** Whether a paragraph sets any spacing of its own. */
|
|
893
|
+
function hasParagraphSpacing(style) {
|
|
894
|
+
return TEXT_PARAGRAPH_SPACING_FIELDS.some((field) => style[field] !== void 0);
|
|
895
|
+
}
|
|
896
|
+
/** A paragraph style with its own `field` set, or following the text again for `undefined`. */
|
|
897
|
+
function withParagraphSpacing(style, field, value) {
|
|
898
|
+
const { [field]: _previous, ...rest } = style;
|
|
899
|
+
return value === void 0 ? rest : {
|
|
900
|
+
...rest,
|
|
901
|
+
[field]: value
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
/** Every paragraph's `field`, or `null` when they differ. */
|
|
905
|
+
function sharedParagraphSpacing(node, field, first = 0, last = paragraphCount(node.text) - 1) {
|
|
906
|
+
const value = paragraphSpacingAt(node, first, field);
|
|
907
|
+
for (let index = first + 1; index <= last; index++) if (paragraphSpacingAt(node, index, field) !== value) return null;
|
|
908
|
+
return value;
|
|
909
|
+
}
|
|
910
|
+
/** Paragraph styles with no paragraph setting its own `field`, as setting the text's does. */
|
|
911
|
+
function paragraphStylesWithoutSpacing(paragraphs, field) {
|
|
912
|
+
return trimParagraphStyles(paragraphs.map((style) => withParagraphSpacing(style, field, void 0)), paragraphs.length);
|
|
913
|
+
}
|
|
914
|
+
/** Whether any paragraph of the node is a list item. */
|
|
915
|
+
function hasTextList(node) {
|
|
916
|
+
return node.textParagraphs.some((paragraph) => paragraph.listType !== "NONE");
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Paragraph styles for `count` paragraphs, without the plain paragraphs at the end, so text
|
|
920
|
+
* without lists, indentation, or paragraph spacing of its own keeps none.
|
|
921
|
+
*/
|
|
922
|
+
function trimParagraphStyles(paragraphs, count) {
|
|
923
|
+
const styles = paragraphs.slice(0, count).map((paragraph) => ({ ...paragraph }));
|
|
924
|
+
while (styles.length > 0) {
|
|
925
|
+
const last = styles[styles.length - 1];
|
|
926
|
+
if (last.listType !== "NONE" || last.indentation !== 0 || hasParagraphSpacing(last)) break;
|
|
927
|
+
styles.pop();
|
|
928
|
+
}
|
|
929
|
+
return styles;
|
|
930
|
+
}
|
|
931
|
+
/** How many paragraphs `text` has: one more than its newlines. */
|
|
932
|
+
function paragraphCount(text) {
|
|
933
|
+
let count = 1;
|
|
934
|
+
for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) count++;
|
|
935
|
+
return count;
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Paragraph styles after replacing `text[start, end)` with `inserted`, as Figma keeps them: the
|
|
939
|
+
* paragraph the edit starts in keeps its style, paragraphs a deleted newline joins to it are
|
|
940
|
+
* dropped, and paragraphs an inserted newline starts take its style.
|
|
941
|
+
*/
|
|
942
|
+
function paragraphStylesAfterEdit(paragraphs, text, start, end, inserted) {
|
|
943
|
+
if (paragraphs.length === 0) return [];
|
|
944
|
+
const first = paragraphIndexAt(text, start);
|
|
945
|
+
const last = paragraphIndexAt(text, end);
|
|
946
|
+
const style = paragraphStyleAt(paragraphs, first);
|
|
947
|
+
const added = paragraphCount(inserted) - 1;
|
|
948
|
+
return trimParagraphStyles([
|
|
949
|
+
...Array.from({ length: first }, (_, index) => paragraphStyleAt(paragraphs, index)),
|
|
950
|
+
...Array.from({ length: added + 1 }, () => style),
|
|
951
|
+
...paragraphs.slice(last + 1)
|
|
952
|
+
], paragraphCount(text) - (last - first) + added);
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* Paragraph styles with every paragraph that `text[start, end)` touches changed by `change`,
|
|
956
|
+
* as a range setter changes whole paragraphs.
|
|
957
|
+
*/
|
|
958
|
+
function paragraphStylesInRange(paragraphs, text, start, end, change) {
|
|
959
|
+
const count = paragraphCount(text);
|
|
960
|
+
const first = paragraphIndexAt(text, start);
|
|
961
|
+
const last = end > start ? paragraphIndexAt(text, end - 1) : first;
|
|
962
|
+
return trimParagraphStyles(Array.from({ length: count }, (_, index) => {
|
|
963
|
+
const style = paragraphStyleAt(paragraphs, index);
|
|
964
|
+
return index >= first && index <= last ? change(style) : style;
|
|
965
|
+
}), count);
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* A paragraph style with its list type set. A list item is nested at least one level, and a
|
|
969
|
+
* paragraph leaving a list keeps no indentation.
|
|
970
|
+
*/
|
|
971
|
+
function withListType(style, listType) {
|
|
972
|
+
if (listType === "NONE") return {
|
|
973
|
+
...style,
|
|
974
|
+
listType,
|
|
975
|
+
indentation: 0
|
|
976
|
+
};
|
|
977
|
+
return {
|
|
978
|
+
...style,
|
|
979
|
+
listType,
|
|
980
|
+
indentation: clampListIndentation(style.indentation)
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
/** A paragraph style with its nesting set, kept in the range a list item allows. */
|
|
984
|
+
function withIndentation(style, indentation) {
|
|
985
|
+
if (style.listType === "NONE") return {
|
|
986
|
+
...style,
|
|
987
|
+
indentation: Math.max(0, Math.min(5, Math.round(indentation)))
|
|
988
|
+
};
|
|
989
|
+
return {
|
|
990
|
+
...style,
|
|
991
|
+
indentation: clampListIndentation(indentation)
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
function clampListIndentation(indentation) {
|
|
995
|
+
return Math.max(1, Math.min(5, Math.round(indentation)));
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* Paragraph styles after `before` became `after` through one edit, found as the text between
|
|
999
|
+
* their common start and end, for editors that replace the text rather than report the edit.
|
|
1000
|
+
*/
|
|
1001
|
+
function paragraphStylesAfterTextChange(paragraphs, before, after) {
|
|
1002
|
+
if (paragraphs.length === 0 || before === after) return paragraphs.map((style) => ({ ...style }));
|
|
1003
|
+
let prefix = 0;
|
|
1004
|
+
const shorter = Math.min(before.length, after.length);
|
|
1005
|
+
while (prefix < shorter && before[prefix] === after[prefix]) prefix++;
|
|
1006
|
+
let suffix = 0;
|
|
1007
|
+
while (suffix < shorter - prefix && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]) suffix++;
|
|
1008
|
+
return paragraphStylesAfterEdit(paragraphs, before, prefix, before.length - suffix, after.slice(prefix, after.length - suffix));
|
|
1009
|
+
}
|
|
1010
|
+
//#endregion
|
|
1011
|
+
//#region src/scaling/node.ts
|
|
1012
|
+
function scaledOptional(value, scale) {
|
|
1013
|
+
return value == null ? null : value * scale;
|
|
1014
|
+
}
|
|
1015
|
+
function scaledStrokes(strokes, scale) {
|
|
1016
|
+
return strokes.map((stroke) => ({
|
|
1017
|
+
...structuredClone(stroke),
|
|
1018
|
+
weight: stroke.weight * scale,
|
|
1019
|
+
dashPattern: stroke.dashPattern?.map((value) => value * scale)
|
|
1020
|
+
}));
|
|
1021
|
+
}
|
|
1022
|
+
function scaledEffects(effects, scale) {
|
|
1023
|
+
return effects.map((effect) => ({
|
|
1024
|
+
...structuredClone(effect),
|
|
1025
|
+
offset: {
|
|
1026
|
+
x: effect.offset.x * scale,
|
|
1027
|
+
y: effect.offset.y * scale
|
|
1028
|
+
},
|
|
1029
|
+
radius: effect.radius * scale,
|
|
1030
|
+
spread: effect.spread * scale
|
|
1031
|
+
}));
|
|
1032
|
+
}
|
|
1033
|
+
function scaledFills(fills, scale) {
|
|
1034
|
+
return fills.map((fill) => ({
|
|
1035
|
+
...structuredClone(fill),
|
|
1036
|
+
scale: fill.scale == null ? void 0 : fill.scale * scale,
|
|
1037
|
+
spacing: fill.spacing == null ? void 0 : fill.spacing * scale,
|
|
1038
|
+
patternSpacing: fill.patternSpacing ? {
|
|
1039
|
+
x: fill.patternSpacing.x * scale,
|
|
1040
|
+
y: fill.patternSpacing.y * scale
|
|
1041
|
+
} : void 0,
|
|
1042
|
+
noiseSize: fill.noiseSize ? {
|
|
1043
|
+
x: fill.noiseSize.x * scale,
|
|
1044
|
+
y: fill.noiseSize.y * scale
|
|
1045
|
+
} : void 0
|
|
1046
|
+
}));
|
|
1047
|
+
}
|
|
1048
|
+
function scaledStyleRuns(styleRuns, scale) {
|
|
1049
|
+
return styleRuns.map((run) => ({
|
|
1050
|
+
...structuredClone(run),
|
|
1051
|
+
style: {
|
|
1052
|
+
...structuredClone(run.style),
|
|
1053
|
+
fontSize: run.style.fontSize == null ? void 0 : run.style.fontSize * scale,
|
|
1054
|
+
letterSpacing: run.style.letterSpacing == null ? void 0 : run.style.letterSpacing * scale,
|
|
1055
|
+
lineHeight: scaledOptional(run.style.lineHeight ?? null, scale),
|
|
1056
|
+
textDecorationThickness: scaledOptional(run.style.textDecorationThickness ?? null, scale),
|
|
1057
|
+
textUnderlineOffset: scaledOptional(run.style.textUnderlineOffset ?? null, scale)
|
|
1058
|
+
}
|
|
1059
|
+
}));
|
|
1060
|
+
}
|
|
1061
|
+
function scaledParagraphStyles(paragraphs, scale) {
|
|
1062
|
+
return paragraphs.map((style) => {
|
|
1063
|
+
const scaled = { ...style };
|
|
1064
|
+
for (const field of TEXT_PARAGRAPH_SPACING_FIELDS) {
|
|
1065
|
+
const value = style[field];
|
|
1066
|
+
if (value !== void 0) scaled[field] = value * scale;
|
|
1067
|
+
}
|
|
1068
|
+
return scaled;
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
function scaledLayoutGrids(grids, scale) {
|
|
1072
|
+
return grids.map((grid) => ({
|
|
1073
|
+
...structuredClone(grid),
|
|
1074
|
+
offset: grid.offset == null ? void 0 : grid.offset * scale,
|
|
1075
|
+
sectionSize: grid.sectionSize == null ? void 0 : grid.sectionSize * scale,
|
|
1076
|
+
gutterSize: grid.gutterSize == null ? void 0 : grid.gutterSize * scale
|
|
1077
|
+
}));
|
|
1078
|
+
}
|
|
1079
|
+
function scaledGridTracks(tracks, scale) {
|
|
1080
|
+
return tracks.map((track) => ({
|
|
1081
|
+
...track,
|
|
1082
|
+
value: track.sizing === "FIXED" ? track.value * scale : track.value
|
|
1083
|
+
}));
|
|
1084
|
+
}
|
|
1085
|
+
function scaledVectorNetwork(node, scale) {
|
|
1086
|
+
if (!node.vectorNetwork) return null;
|
|
1087
|
+
const network = cloneVectorNetwork(node.vectorNetwork);
|
|
1088
|
+
for (const vertex of network.vertices) {
|
|
1089
|
+
vertex.x *= scale;
|
|
1090
|
+
vertex.y *= scale;
|
|
1091
|
+
}
|
|
1092
|
+
for (const segment of network.segments) {
|
|
1093
|
+
segment.tangentStart.x *= scale;
|
|
1094
|
+
segment.tangentStart.y *= scale;
|
|
1095
|
+
segment.tangentEnd.x *= scale;
|
|
1096
|
+
segment.tangentEnd.y *= scale;
|
|
1097
|
+
}
|
|
1098
|
+
return network;
|
|
1099
|
+
}
|
|
1100
|
+
function scaleNodeChanges(node, scale, scalePosition) {
|
|
1101
|
+
return {
|
|
1102
|
+
x: scalePosition ? node.x * scale : node.x,
|
|
1103
|
+
y: scalePosition ? node.y * scale : node.y,
|
|
1104
|
+
width: node.width * scale,
|
|
1105
|
+
height: node.height * scale,
|
|
1106
|
+
minWidth: scaledOptional(node.minWidth, scale),
|
|
1107
|
+
maxWidth: scaledOptional(node.maxWidth, scale),
|
|
1108
|
+
minHeight: scaledOptional(node.minHeight, scale),
|
|
1109
|
+
maxHeight: scaledOptional(node.maxHeight, scale),
|
|
1110
|
+
cornerRadius: node.cornerRadius * scale,
|
|
1111
|
+
topLeftRadius: node.topLeftRadius * scale,
|
|
1112
|
+
topRightRadius: node.topRightRadius * scale,
|
|
1113
|
+
bottomRightRadius: node.bottomRightRadius * scale,
|
|
1114
|
+
bottomLeftRadius: node.bottomLeftRadius * scale,
|
|
1115
|
+
fontSize: node.fontSize * scale,
|
|
1116
|
+
letterSpacing: node.letterSpacing * scale,
|
|
1117
|
+
lineHeight: scaledOptional(node.lineHeight, scale),
|
|
1118
|
+
textDecorationThickness: scaledOptional(node.textDecorationThickness, scale),
|
|
1119
|
+
textUnderlineOffset: scaledOptional(node.textUnderlineOffset, scale),
|
|
1120
|
+
styleRuns: scaledStyleRuns(node.styleRuns, scale),
|
|
1121
|
+
listSpacing: node.listSpacing * scale,
|
|
1122
|
+
paragraphSpacing: node.paragraphSpacing * scale,
|
|
1123
|
+
paragraphIndent: node.paragraphIndent * scale,
|
|
1124
|
+
textParagraphs: scaledParagraphStyles(node.textParagraphs, scale),
|
|
1125
|
+
itemSpacing: node.itemSpacing * scale,
|
|
1126
|
+
counterAxisSpacing: node.counterAxisSpacing * scale,
|
|
1127
|
+
paddingTop: node.paddingTop * scale,
|
|
1128
|
+
paddingRight: node.paddingRight * scale,
|
|
1129
|
+
paddingBottom: node.paddingBottom * scale,
|
|
1130
|
+
paddingLeft: node.paddingLeft * scale,
|
|
1131
|
+
gridColumnGap: node.gridColumnGap * scale,
|
|
1132
|
+
gridRowGap: node.gridRowGap * scale,
|
|
1133
|
+
gridTemplateColumns: scaledGridTracks(node.gridTemplateColumns, scale),
|
|
1134
|
+
gridTemplateRows: scaledGridTracks(node.gridTemplateRows, scale),
|
|
1135
|
+
strokes: scaledStrokes(node.strokes, scale),
|
|
1136
|
+
strokeWeight: node.strokeWeight * scale,
|
|
1137
|
+
dashPattern: node.dashPattern.map((value) => value * scale),
|
|
1138
|
+
borderTopWeight: node.borderTopWeight * scale,
|
|
1139
|
+
borderRightWeight: node.borderRightWeight * scale,
|
|
1140
|
+
borderBottomWeight: node.borderBottomWeight * scale,
|
|
1141
|
+
borderLeftWeight: node.borderLeftWeight * scale,
|
|
1142
|
+
strokeMiterLimit: node.strokeMiterLimit,
|
|
1143
|
+
effects: scaledEffects(node.effects, scale),
|
|
1144
|
+
fills: scaledFills(node.fills, scale),
|
|
1145
|
+
layoutGrids: scaledLayoutGrids(node.layoutGrids, scale),
|
|
1146
|
+
vectorNetwork: scaledVectorNetwork(node, scale),
|
|
1147
|
+
fillGeometry: scaleGeometryPaths(node.fillGeometry, scale, scale),
|
|
1148
|
+
strokeGeometry: scaleGeometryPaths(node.strokeGeometry, scale, scale)
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
//#endregion
|
|
1152
|
+
//#region src/variables/fields.ts
|
|
1153
|
+
const NUMERIC_FIELDS = /* @__PURE__ */ new Set([
|
|
1154
|
+
"opacity",
|
|
1155
|
+
"width",
|
|
1156
|
+
"height",
|
|
1157
|
+
"minWidth",
|
|
1158
|
+
"maxWidth",
|
|
1159
|
+
"minHeight",
|
|
1160
|
+
"maxHeight",
|
|
1161
|
+
"x",
|
|
1162
|
+
"y",
|
|
1163
|
+
"rotation",
|
|
1164
|
+
"cornerRadius",
|
|
1165
|
+
"topLeftRadius",
|
|
1166
|
+
"topRightRadius",
|
|
1167
|
+
"bottomLeftRadius",
|
|
1168
|
+
"bottomRightRadius",
|
|
1169
|
+
"strokeWeight",
|
|
1170
|
+
"borderTopWeight",
|
|
1171
|
+
"borderBottomWeight",
|
|
1172
|
+
"borderLeftWeight",
|
|
1173
|
+
"borderRightWeight",
|
|
1174
|
+
"fontSize",
|
|
1175
|
+
"letterSpacing",
|
|
1176
|
+
"lineHeight",
|
|
1177
|
+
"paddingLeft",
|
|
1178
|
+
"paddingRight",
|
|
1179
|
+
"paddingTop",
|
|
1180
|
+
"paddingBottom",
|
|
1181
|
+
"itemSpacing",
|
|
1182
|
+
"counterAxisSpacing",
|
|
1183
|
+
"gridRowGap",
|
|
1184
|
+
"gridColumnGap"
|
|
1185
|
+
]);
|
|
1186
|
+
function isNumericVariableBindingField(field) {
|
|
1187
|
+
return NUMERIC_FIELDS.has(field);
|
|
1188
|
+
}
|
|
1189
|
+
/** Text content and font family are the string-valued bindings a node accepts. */
|
|
1190
|
+
const STRING_BINDING_FIELDS = /* @__PURE__ */ new Set(["text", "fontFamily"]);
|
|
1191
|
+
/** Visibility is the only boolean-valued binding a node accepts. */
|
|
1192
|
+
const BOOLEAN_BINDING_FIELDS = /* @__PURE__ */ new Set(["visible"]);
|
|
1193
|
+
//#endregion
|
|
1194
|
+
//#region src/variables/units.ts
|
|
1195
|
+
function scaleVariableBindingUnits(node, factor) {
|
|
1196
|
+
const variableBindingScales = { ...node.variableBindingScales };
|
|
1197
|
+
const variableAssignmentScales = { ...node.variableAssignmentScales };
|
|
1198
|
+
for (const field of NUMERIC_FIELDS) {
|
|
1199
|
+
if (field === "opacity" || field === "rotation") continue;
|
|
1200
|
+
if (field in node.boundVariables) variableBindingScales[field] = (variableBindingScales[field] ?? 1) * factor;
|
|
1201
|
+
if (node.type === "INSTANCE") variableAssignmentScales[field] = (variableAssignmentScales[field] ?? 1) * factor;
|
|
1202
|
+
}
|
|
1203
|
+
return {
|
|
1204
|
+
variableBindingScales,
|
|
1205
|
+
variableAssignmentScales
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
//#endregion
|
|
1209
|
+
//#region src/layout/aspect-ratio.ts
|
|
1210
|
+
/** The value Figma's `lockAspectRatio()` stores: the size the layer has when it is locked. */
|
|
1211
|
+
function lockedAspectRatioTarget(width, height) {
|
|
1212
|
+
return {
|
|
1213
|
+
x: width,
|
|
1214
|
+
y: height
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
/** Whether the lock can change: a layer inside an instance keeps its component's, as in Figma. */
|
|
1218
|
+
function aspectRatioLockEditable(graph, node) {
|
|
1219
|
+
return !node.parentId || !graph.closest(node.parentId, (layer) => layer.type === "INSTANCE");
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* The width-to-height ratio a resize keeps, or `null` when the layer's proportions are free.
|
|
1223
|
+
* Text that sizes itself to its content keeps the lock without following it, as in Figma.
|
|
1224
|
+
*/
|
|
1225
|
+
function enforcedAspectRatio(node) {
|
|
1226
|
+
const target = node.targetAspectRatio;
|
|
1227
|
+
if (!target || !(target.x > 0) || !(target.y > 0)) return null;
|
|
1228
|
+
if (node.type === "TEXT" && node.textAutoResize !== "NONE") return null;
|
|
1229
|
+
return target.x / target.y;
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* A resize that ignores a locked ratio, such as Figma's plugin `resize()` or a Control-drag,
|
|
1233
|
+
* keeps the lock and stores the new size as the ratio to keep.
|
|
1234
|
+
*/
|
|
1235
|
+
function recapturedAspectRatio(node, width, height) {
|
|
1236
|
+
if (!node.targetAspectRatio) return {};
|
|
1237
|
+
if (node.targetAspectRatio.x === width && node.targetAspectRatio.y === height) return {};
|
|
1238
|
+
return { targetAspectRatio: lockedAspectRatioTarget(width, height) };
|
|
1239
|
+
}
|
|
1240
|
+
/** The size that keeps `ratio` when one axis is set to `value`. */
|
|
1241
|
+
function sizeKeepingAspectRatio(ratio, axis, value) {
|
|
1242
|
+
return axis === "width" ? {
|
|
1243
|
+
width: value,
|
|
1244
|
+
height: value / ratio
|
|
1245
|
+
} : {
|
|
1246
|
+
width: value * ratio,
|
|
1247
|
+
height: value
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
//#endregion
|
|
1251
|
+
//#region src/resize.ts
|
|
1252
|
+
const CONSTRAINT_CONTAINER_TYPES = /* @__PURE__ */ new Set([
|
|
1253
|
+
"FRAME",
|
|
1254
|
+
"COMPONENT",
|
|
1255
|
+
"COMPONENT_SET",
|
|
1256
|
+
"INSTANCE",
|
|
1257
|
+
"GROUP",
|
|
1258
|
+
"BOOLEAN_OPERATION"
|
|
1259
|
+
]);
|
|
1260
|
+
function constrainedAxis(position, size, parentBefore, parentAfter, constraint) {
|
|
1261
|
+
const delta = parentAfter - parentBefore;
|
|
1262
|
+
if (constraint === "MAX") return {
|
|
1263
|
+
position: position + delta,
|
|
1264
|
+
size
|
|
1265
|
+
};
|
|
1266
|
+
if (constraint === "CENTER") return {
|
|
1267
|
+
position: position + delta / 2,
|
|
1268
|
+
size
|
|
1269
|
+
};
|
|
1270
|
+
if (constraint === "STRETCH") return {
|
|
1271
|
+
position,
|
|
1272
|
+
size: Math.max(1, size + delta)
|
|
1273
|
+
};
|
|
1274
|
+
if (constraint === "SCALE" && parentBefore > 0) {
|
|
1275
|
+
const scale = parentAfter / parentBefore;
|
|
1276
|
+
return {
|
|
1277
|
+
position: position * scale,
|
|
1278
|
+
size: Math.max(1, size * scale)
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
return {
|
|
1282
|
+
position,
|
|
1283
|
+
size
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
const FLEXIBLE_CONSTRAINTS = /* @__PURE__ */ new Set(["STRETCH", "SCALE"]);
|
|
1287
|
+
/** The axis at `size`, keeping the edge or centre its constraint pins where it was placed. */
|
|
1288
|
+
function resizedInPlace(placed, size, constraint) {
|
|
1289
|
+
if (constraint === "MAX") return {
|
|
1290
|
+
position: placed.position + placed.size - size,
|
|
1291
|
+
size
|
|
1292
|
+
};
|
|
1293
|
+
if (constraint === "CENTER") return {
|
|
1294
|
+
position: placed.position + (placed.size - size) / 2,
|
|
1295
|
+
size
|
|
1296
|
+
};
|
|
1297
|
+
return {
|
|
1298
|
+
position: placed.position,
|
|
1299
|
+
size
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis
|
|
1304
|
+
* sizes the other. With both axes following the parent, or neither, the ratio gives way.
|
|
1305
|
+
*/
|
|
1306
|
+
function keepLockedRatio(x, y, horizontal, vertical, aspectRatio) {
|
|
1307
|
+
const flexibleX = FLEXIBLE_CONSTRAINTS.has(horizontal);
|
|
1308
|
+
if (aspectRatio === null || flexibleX === FLEXIBLE_CONSTRAINTS.has(vertical)) return {
|
|
1309
|
+
x,
|
|
1310
|
+
y
|
|
1311
|
+
};
|
|
1312
|
+
return flexibleX ? {
|
|
1313
|
+
x,
|
|
1314
|
+
y: resizedInPlace(y, x.size / aspectRatio, vertical)
|
|
1315
|
+
} : {
|
|
1316
|
+
x: resizedInPlace(x, y.size * aspectRatio, horizontal),
|
|
1317
|
+
y
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
/** A child's box after its parent resizes, keeping a locked aspect ratio as Figma does. */
|
|
1321
|
+
function constrainedChildRect(child, parentBefore, parentAfter, horizontal, vertical, aspectRatio = null) {
|
|
1322
|
+
let x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal);
|
|
1323
|
+
let y = constrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical);
|
|
1324
|
+
({x, y} = keepLockedRatio(x, y, horizontal, vertical, aspectRatio));
|
|
1325
|
+
return {
|
|
1326
|
+
x: Math.round(x.position),
|
|
1327
|
+
y: Math.round(y.position),
|
|
1328
|
+
width: Math.round(x.size),
|
|
1329
|
+
height: Math.round(y.size)
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
function layoutConstrainedAxis(position, size, parentBefore, parentAfter, constraint) {
|
|
1333
|
+
const delta = Math.round(parentAfter) - Math.round(parentBefore);
|
|
1334
|
+
if (constraint === "MAX") return {
|
|
1335
|
+
position: position + delta,
|
|
1336
|
+
size
|
|
1337
|
+
};
|
|
1338
|
+
if (constraint === "CENTER") return {
|
|
1339
|
+
position: position + Math.round(parentAfter / 2) - Math.round(parentBefore / 2),
|
|
1340
|
+
size
|
|
1341
|
+
};
|
|
1342
|
+
if (constraint === "STRETCH") return {
|
|
1343
|
+
position,
|
|
1344
|
+
size: Math.abs(size + delta)
|
|
1345
|
+
};
|
|
1346
|
+
if (constraint === "SCALE" && parentBefore > 0) {
|
|
1347
|
+
const scale = parentAfter / parentBefore;
|
|
1348
|
+
return {
|
|
1349
|
+
position: Math.round(position * scale * 128) / 128,
|
|
1350
|
+
size: size * scale
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1353
|
+
return {
|
|
1354
|
+
position,
|
|
1355
|
+
size
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Where a child goes when layout resizes its parent, as Figma places a layer that ignores auto
|
|
1360
|
+
* layout when its Hug frame grows (measured on desktop 126): Right and Left & right move or grow
|
|
1361
|
+
* it by the change in the parent's size rounded to whole pixels, Center by the change in its
|
|
1362
|
+
* rounded half, and Scale by the exact ratio, its position to 1/128 of a pixel. Sizes are not
|
|
1363
|
+
* rounded, so applying a run of changes one at a time lands where applying them at once does.
|
|
1364
|
+
*/
|
|
1365
|
+
function layoutConstrainedChildRect(child, parentBefore, parentAfter, horizontal, vertical, aspectRatio = null) {
|
|
1366
|
+
const placed = keepLockedRatio(layoutConstrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal), layoutConstrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical), horizontal, vertical, aspectRatio);
|
|
1367
|
+
return {
|
|
1368
|
+
x: placed.x.position,
|
|
1369
|
+
y: placed.y.position,
|
|
1370
|
+
width: placed.x.size,
|
|
1371
|
+
height: placed.y.size
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
function scaledChildRect(child, parentBefore, parentAfter) {
|
|
1375
|
+
return constrainedChildRect(child, parentBefore, parentAfter, "SCALE", "SCALE");
|
|
1376
|
+
}
|
|
1377
|
+
function scaleVectorNetworkForResize(vectorNetwork, originalWidth, originalHeight, width, height) {
|
|
1378
|
+
if (!vectorNetwork || originalWidth <= 0 || originalHeight <= 0) return null;
|
|
1379
|
+
const scaleX = width / originalWidth;
|
|
1380
|
+
const scaleY = height / originalHeight;
|
|
1381
|
+
if (scaleX === 1 && scaleY === 1) return null;
|
|
1382
|
+
return {
|
|
1383
|
+
vertices: vectorNetwork.vertices.map((vertex) => ({
|
|
1384
|
+
...vertex,
|
|
1385
|
+
x: vertex.x * scaleX,
|
|
1386
|
+
y: vertex.y * scaleY
|
|
1387
|
+
})),
|
|
1388
|
+
segments: vectorNetwork.segments.map((segment) => ({
|
|
1389
|
+
...segment,
|
|
1390
|
+
tangentStart: {
|
|
1391
|
+
x: segment.tangentStart.x * scaleX,
|
|
1392
|
+
y: segment.tangentStart.y * scaleY
|
|
1393
|
+
},
|
|
1394
|
+
tangentEnd: {
|
|
1395
|
+
x: segment.tangentEnd.x * scaleX,
|
|
1396
|
+
y: segment.tangentEnd.y * scaleY
|
|
1397
|
+
}
|
|
1398
|
+
})),
|
|
1399
|
+
regions: vectorNetwork.regions
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
/** Snapshot one node's resize-relevant state (rect + geometry that must scale with it). */
|
|
1403
|
+
function createResizeSnapshot(node) {
|
|
1404
|
+
return {
|
|
1405
|
+
x: node.x,
|
|
1406
|
+
y: node.y,
|
|
1407
|
+
width: node.width,
|
|
1408
|
+
height: node.height,
|
|
1409
|
+
vectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null,
|
|
1410
|
+
fillGeometry: copyGeometryPaths(node.fillGeometry),
|
|
1411
|
+
strokeGeometry: copyGeometryPaths(node.strokeGeometry),
|
|
1412
|
+
derivedTextGlyphs: copyDerivedGlyphs(node.derivedTextGlyphs),
|
|
1413
|
+
strokes: copyStrokes(node.strokes),
|
|
1414
|
+
textPathData: node.textPathData ? structuredClone(node.textPathData) : null,
|
|
1415
|
+
textPathBox: node.textPathBox ? { ...node.textPathBox } : null
|
|
1416
|
+
};
|
|
1417
|
+
}
|
|
1418
|
+
function scaleDerivedGlyphs(glyphs, sx, sy) {
|
|
1419
|
+
if (!glyphs?.length) return glyphs;
|
|
1420
|
+
return glyphs.map((g) => ({
|
|
1421
|
+
...g,
|
|
1422
|
+
x: g.x * sx,
|
|
1423
|
+
y: g.y * sy,
|
|
1424
|
+
scaleX: (g.scaleX ?? 1) * sx,
|
|
1425
|
+
scaleY: (g.scaleY ?? 1) * sy,
|
|
1426
|
+
commandsBlob: new Uint8Array(g.commandsBlob)
|
|
1427
|
+
}));
|
|
1428
|
+
}
|
|
1429
|
+
function scaleStrokes(strokes, sx, sy) {
|
|
1430
|
+
if (strokes.length === 0) return strokes;
|
|
1431
|
+
const weightScale = (Math.abs(sx) + Math.abs(sy)) / 2;
|
|
1432
|
+
return strokes.map((s) => ({
|
|
1433
|
+
...copyStroke(s),
|
|
1434
|
+
weight: s.weight * weightScale
|
|
1435
|
+
}));
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* All geometry that must track a width/height change. Historically only
|
|
1439
|
+
* vectorNetwork + fillGeometry were updated — path-text strokeGeometry and
|
|
1440
|
+
* glyphs stayed at the pre-resize size, so shrinking a sticker made the white
|
|
1441
|
+
* OUTSIDE outlines look massively thick (DomeSticker resize bug).
|
|
1442
|
+
*/
|
|
1443
|
+
function scaledGeometryChanges(orig, origWidth, origHeight, width, height) {
|
|
1444
|
+
if (origWidth <= 0 || origHeight <= 0) return {};
|
|
1445
|
+
const sx = width / origWidth;
|
|
1446
|
+
const sy = height / origHeight;
|
|
1447
|
+
if (sx === 1 && sy === 1) return {};
|
|
1448
|
+
const changes = {};
|
|
1449
|
+
const resizedVN = scaleVectorNetworkForResize(orig.vectorNetwork, origWidth, origHeight, width, height);
|
|
1450
|
+
if (resizedVN) changes.vectorNetwork = resizedVN;
|
|
1451
|
+
if (orig.fillGeometry.length > 0) changes.fillGeometry = scaleGeometryPaths(orig.fillGeometry, sx, sy);
|
|
1452
|
+
if (orig.strokeGeometry.length > 0) changes.strokeGeometry = scaleGeometryPaths(orig.strokeGeometry, sx, sy);
|
|
1453
|
+
const glyphs = orig.derivedTextGlyphs ?? [];
|
|
1454
|
+
const pathText = !!orig.textPathData || !!orig.textPathBox || glyphs.some((glyph) => (glyph.rotation ?? 0) !== 0);
|
|
1455
|
+
if (glyphs.length > 0 && pathText) {
|
|
1456
|
+
changes.derivedTextGlyphs = scaleDerivedGlyphs(glyphs, sx, sy);
|
|
1457
|
+
if (orig.textPathBox) changes.textPathBox = {
|
|
1458
|
+
x: orig.textPathBox.x * sx,
|
|
1459
|
+
y: orig.textPathBox.y * sy,
|
|
1460
|
+
width: orig.textPathBox.width * sx,
|
|
1461
|
+
height: orig.textPathBox.height * sy
|
|
1462
|
+
};
|
|
1463
|
+
}
|
|
1464
|
+
if (orig.strokes.length > 0) changes.strokes = scaleStrokes(orig.strokes, sx, sy);
|
|
1465
|
+
return changes;
|
|
1466
|
+
}
|
|
1467
|
+
function collectResizeDescendants(graph, rootId) {
|
|
1468
|
+
const root = graph.getNode(rootId);
|
|
1469
|
+
if (!root || !CONSTRAINT_CONTAINER_TYPES.has(root.type)) return null;
|
|
1470
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
1471
|
+
const collect = (parentId) => {
|
|
1472
|
+
const parent = graph.getNode(parentId);
|
|
1473
|
+
if (!parent) return;
|
|
1474
|
+
for (const childId of parent.childIds) {
|
|
1475
|
+
const child = graph.getNode(childId);
|
|
1476
|
+
if (!child) continue;
|
|
1477
|
+
snapshots.set(childId, createResizeSnapshot(child));
|
|
1478
|
+
collect(childId);
|
|
1479
|
+
}
|
|
1480
|
+
};
|
|
1481
|
+
collect(rootId);
|
|
1482
|
+
return snapshots.size > 0 ? snapshots : null;
|
|
1483
|
+
}
|
|
1484
|
+
function computeConstrainedResizeChanges(graph, rootId, rootBefore, rootAfter, originals) {
|
|
1485
|
+
const changes = /* @__PURE__ */ new Map();
|
|
1486
|
+
const compute = (parentId, parentBefore, parentAfter) => {
|
|
1487
|
+
const parent = graph.getNode(parentId);
|
|
1488
|
+
if (!parent) return;
|
|
1489
|
+
const scalesChildren = parent.type === "GROUP" || parent.type === "BOOLEAN_OPERATION";
|
|
1490
|
+
for (const childId of parent.childIds) {
|
|
1491
|
+
const original = originals.get(childId);
|
|
1492
|
+
const child = graph.getNode(childId);
|
|
1493
|
+
if (!original || !child) continue;
|
|
1494
|
+
if (parent.layoutMode !== "NONE" && child.layoutPositioning !== "ABSOLUTE") {
|
|
1495
|
+
compute(childId, original, child);
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
const rect = scalesChildren ? scaledChildRect(original, parentBefore, parentAfter) : constrainedChildRect(original, parentBefore, parentAfter, child.horizontalConstraint, child.verticalConstraint, enforcedAspectRatio(child));
|
|
1499
|
+
const childChanges = {
|
|
1500
|
+
...rect,
|
|
1501
|
+
...scaledGeometryChanges(original, original.width, original.height, rect.width, rect.height)
|
|
1502
|
+
};
|
|
1503
|
+
changes.set(childId, childChanges);
|
|
1504
|
+
compute(childId, original, child.layoutMode === "NONE" ? rect : child);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
compute(rootId, rootBefore, rootAfter);
|
|
1508
|
+
return changes;
|
|
1509
|
+
}
|
|
1510
|
+
//#endregion
|
|
1511
|
+
//#region src/instances/placement.ts
|
|
1512
|
+
/** The fields that say where a copy sits in its parent. */
|
|
1513
|
+
const PLACEMENT_FIELDS = /* @__PURE__ */ new Set([
|
|
1514
|
+
"x",
|
|
1515
|
+
"y",
|
|
1516
|
+
"width",
|
|
1517
|
+
"height"
|
|
1518
|
+
]);
|
|
1519
|
+
/**
|
|
1520
|
+
* The component's layer placed in the copy's parent: where its constraints put it when the
|
|
1521
|
+
* instance's frame has another size than the component's, as Figma resizes an instance.
|
|
1522
|
+
*/
|
|
1523
|
+
function placedByConstraints(source, compParent, instParent, factor) {
|
|
1524
|
+
const before = {
|
|
1525
|
+
width: compParent.width * factor,
|
|
1526
|
+
height: compParent.height * factor
|
|
1527
|
+
};
|
|
1528
|
+
if (before.width === instParent.width && before.height === instParent.height) return source;
|
|
1529
|
+
const rect = layoutConstrainedChildRect(source, before, instParent, source.horizontalConstraint, source.verticalConstraint, enforcedAspectRatio(source));
|
|
1530
|
+
return {
|
|
1531
|
+
...source,
|
|
1532
|
+
...rect
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
1535
|
+
//#endregion
|
|
1536
|
+
//#region src/instances/vector-geometry.ts
|
|
1537
|
+
/** How far apart two paths' points may be and still count as one path, in pixels. */
|
|
1538
|
+
const PATH_TOLERANCE = .001;
|
|
1539
|
+
/** The stroke fields a vector's stroke outline is drawn from. */
|
|
1540
|
+
const STROKE_OUTLINE_FIELDS = [
|
|
1541
|
+
"strokes",
|
|
1542
|
+
"strokeWeight",
|
|
1543
|
+
"strokeAlign",
|
|
1544
|
+
"strokeCap",
|
|
1545
|
+
"strokeJoin",
|
|
1546
|
+
"strokeMiterLimit",
|
|
1547
|
+
"dashPattern"
|
|
1548
|
+
];
|
|
1549
|
+
const near = (a, b) => Math.abs(a - b) <= PATH_TOLERANCE;
|
|
1550
|
+
/** Whether two paths are one, up to the float error that files and scaling leave. */
|
|
1551
|
+
function samePath(a, b) {
|
|
1552
|
+
if (!a || !b) return a === b;
|
|
1553
|
+
if (a.vertices.length !== b.vertices.length || a.segments.length !== b.segments.length) return false;
|
|
1554
|
+
const sameVertices = a.vertices.every((vertex, index) => {
|
|
1555
|
+
const { x, y, ...rest } = vertex;
|
|
1556
|
+
const { x: otherX, y: otherY, ...otherRest } = b.vertices[index];
|
|
1557
|
+
return near(x, otherX) && near(y, otherY) && isEqual(rest, otherRest);
|
|
1558
|
+
});
|
|
1559
|
+
const sameSegments = a.segments.every((segment, index) => {
|
|
1560
|
+
const other = b.segments[index];
|
|
1561
|
+
return segment.start === other.start && segment.end === other.end && near(segment.tangentStart.x, other.tangentStart.x) && near(segment.tangentStart.y, other.tangentStart.y) && near(segment.tangentEnd.x, other.tangentEnd.x) && near(segment.tangentEnd.y, other.tangentEnd.y);
|
|
1562
|
+
});
|
|
1563
|
+
return sameVertices && sameSegments && isEqual(a.regions, b.regions);
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Gives a vector's copy its component's path, which Figma refuses to override in an instance
|
|
1567
|
+
* ("vector-data"), so every edit to the path reaches the copies, drawn at the size the copy ends
|
|
1568
|
+
* up with. A copy whose path already matches keeps its own outlines, which may differ from the
|
|
1569
|
+
* component's where the instance overrides its fills or strokes. A changed path brings the
|
|
1570
|
+
* component's outlines with it, the stroke's only while the copy strokes as the component does;
|
|
1571
|
+
* otherwise the canvas draws the stroke from the new path.
|
|
1572
|
+
*/
|
|
1573
|
+
function followVectorGeometry(updates, copy, source) {
|
|
1574
|
+
if (source.type !== "VECTOR") return;
|
|
1575
|
+
const width = updates.width ?? copy.width;
|
|
1576
|
+
const height = updates.height ?? copy.height;
|
|
1577
|
+
const sx = source.width > 0 ? width / source.width : 1;
|
|
1578
|
+
const sy = source.height > 0 ? height / source.height : 1;
|
|
1579
|
+
const scaled = sx !== 1 || sy !== 1;
|
|
1580
|
+
const scaledNetwork = (network) => scaled ? transformVectorNetwork([
|
|
1581
|
+
sx,
|
|
1582
|
+
0,
|
|
1583
|
+
0,
|
|
1584
|
+
0,
|
|
1585
|
+
sy,
|
|
1586
|
+
0,
|
|
1587
|
+
0,
|
|
1588
|
+
0,
|
|
1589
|
+
1
|
|
1590
|
+
], network) : cloneVectorNetwork(network);
|
|
1591
|
+
const network = source.vectorNetwork ? scaledNetwork(source.vectorNetwork) : null;
|
|
1592
|
+
if (samePath(copy.vectorNetwork, network)) return;
|
|
1593
|
+
const outlines = (paths) => scaled ? scaleGeometryPaths(paths, sx, sy) : copyGeometryPaths(paths);
|
|
1594
|
+
const strokesAlike = STROKE_OUTLINE_FIELDS.every((field) => isEqual(updates[field] ?? copy[field], source[field]));
|
|
1595
|
+
updates.vectorNetwork = network;
|
|
1596
|
+
updates.fillGeometry = outlines(source.fillGeometry);
|
|
1597
|
+
updates.strokeGeometry = strokesAlike ? outlines(source.strokeGeometry) : [];
|
|
1598
|
+
}
|
|
1599
|
+
//#endregion
|
|
1600
|
+
//#region src/instances/sync.ts
|
|
1601
|
+
function setSceneProp(target, key, value) {
|
|
1602
|
+
target[key] = value;
|
|
1603
|
+
}
|
|
1604
|
+
function copyProp(target, source, key) {
|
|
1605
|
+
if (key === "fills") setSceneProp(target, key, copyFills(source.fills));
|
|
1606
|
+
else if (key === "strokes") setSceneProp(target, key, copyStrokes(source.strokes));
|
|
1607
|
+
else if (key === "effects") setSceneProp(target, key, copyEffects(source.effects));
|
|
1608
|
+
else if (key === "styleRuns") setSceneProp(target, key, copyStyleRuns(source.styleRuns));
|
|
1609
|
+
else if (key === "boundVariables") {
|
|
1610
|
+
setSceneProp(target, key, { ...source.boundVariables });
|
|
1611
|
+
setSceneProp(target, "variableBindingScales", { ...source.variableBindingScales });
|
|
1612
|
+
} else if (key === "variableModes") setSceneProp(target, key, { ...source.variableModes });
|
|
1613
|
+
else if (key === "gridPosition") setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null);
|
|
1614
|
+
else if (key === "targetAspectRatio") setSceneProp(target, key, source.targetAspectRatio ? { ...source.targetAspectRatio } : null);
|
|
1615
|
+
else {
|
|
1616
|
+
const value = source[key];
|
|
1617
|
+
setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value);
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
function bindingProtection(scopes) {
|
|
1621
|
+
const fields = /* @__PURE__ */ new Set();
|
|
1622
|
+
for (const scope of scopes) {
|
|
1623
|
+
const perField = [...scope].some((field) => field.startsWith("boundVariables/"));
|
|
1624
|
+
for (const field of scope) if (field !== "boundVariables" || !perField) fields.add(field);
|
|
1625
|
+
}
|
|
1626
|
+
return (field) => fields.has(field);
|
|
1627
|
+
}
|
|
1628
|
+
function syncBindingFields(target, source, updates, protectedField) {
|
|
1629
|
+
if (protectedField("boundVariables")) return;
|
|
1630
|
+
const bindings = { ...source.boundVariables };
|
|
1631
|
+
const scales = { ...source.variableBindingScales };
|
|
1632
|
+
for (const field of /* @__PURE__ */ new Set([
|
|
1633
|
+
...Object.keys(source.boundVariables),
|
|
1634
|
+
...Object.keys(target.boundVariables),
|
|
1635
|
+
...Object.keys(target.variableBindingScales)
|
|
1636
|
+
])) {
|
|
1637
|
+
if (!protectedField(`boundVariables/${field}`)) continue;
|
|
1638
|
+
if (!Object.hasOwn(target.boundVariables, field)) Reflect.deleteProperty(bindings, field);
|
|
1639
|
+
else bindings[field] = target.boundVariables[field];
|
|
1640
|
+
if (target.variableBindingScales[field] === void 0) Reflect.deleteProperty(scales, field);
|
|
1641
|
+
else scales[field] = target.variableBindingScales[field];
|
|
1642
|
+
}
|
|
1643
|
+
updates.boundVariables = bindings;
|
|
1644
|
+
updates.variableBindingScales = scales;
|
|
1645
|
+
}
|
|
1646
|
+
function isProtectedSyncField(node, key, protectedField) {
|
|
1647
|
+
return protectedField(key) || key in node.boundVariables && (protectedField("boundVariables") || protectedField(`boundVariables/${key}`));
|
|
1648
|
+
}
|
|
1649
|
+
function sourceInTargetCoordinates(source, targetScale) {
|
|
1650
|
+
const factor = targetScale / source.componentScale;
|
|
1651
|
+
if (!Number.isFinite(factor) || factor <= 0) throw new Error("Invalid component coordinate scale");
|
|
1652
|
+
if (factor === 1) return source;
|
|
1653
|
+
return {
|
|
1654
|
+
...source,
|
|
1655
|
+
...scaleNodeChanges(source, factor, true),
|
|
1656
|
+
...scaleVariableBindingUnits(source, factor)
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
/** The fields a copy takes from its component's layer, placed in the copy's parent. */
|
|
1660
|
+
function copySyncedFields(updates, copy, source, { compParent, instParent, factor, skip }) {
|
|
1661
|
+
const placedByLayout = instParent.layoutMode !== "NONE" && source.layoutPositioning !== "ABSOLUTE";
|
|
1662
|
+
const placed = placedByLayout ? source : placedByConstraints(source, compParent, instParent, factor);
|
|
1663
|
+
for (const key of INSTANCE_SYNC_FIELDS) {
|
|
1664
|
+
if (key === "boundVariables") continue;
|
|
1665
|
+
if (placedByLayout && (key === "x" || key === "y")) continue;
|
|
1666
|
+
if (skip(key)) continue;
|
|
1667
|
+
const owner = INSTANCE_SYNC_FIELD_OWNERS[key];
|
|
1668
|
+
if (owner && skip(owner)) continue;
|
|
1669
|
+
const from = PLACEMENT_FIELDS.has(key) ? placed : source;
|
|
1670
|
+
if (isEqual(copy[key], from[key])) continue;
|
|
1671
|
+
copyProp(updates, from, key);
|
|
1672
|
+
}
|
|
1673
|
+
followVectorGeometry(updates, copy, source);
|
|
1674
|
+
remeasureChangedText(updates, copy);
|
|
1675
|
+
}
|
|
1676
|
+
function updateSyncedProps(graph, target, updates) {
|
|
1677
|
+
const changed = Object.fromEntries(Object.entries(updates).filter(([key, value]) => !isEqual(target[key], value)));
|
|
1678
|
+
if (Object.keys(changed).length) graph.updateNode(target.id, changed);
|
|
1679
|
+
}
|
|
1680
|
+
function cloneChildInCoordinates(graph, src, sourceParent, targetParent, mode = "deep") {
|
|
1681
|
+
const componentScale = src.componentScale * targetParent.componentScale / sourceParent.componentScale;
|
|
1682
|
+
return graph.createNode(src.type, targetParent.id, {
|
|
1683
|
+
...cloneNodeProps(sourceInTargetCoordinates(src, componentScale), src.id, mode),
|
|
1684
|
+
componentScale
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
function cloneChildrenWithMapping(graph, sourceParentId, destParentId, mode = "deep") {
|
|
1688
|
+
if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return;
|
|
1689
|
+
const sourceParent = graph.nodes.get(sourceParentId);
|
|
1690
|
+
const targetParent = graph.nodes.get(destParentId);
|
|
1691
|
+
if (!sourceParent || !targetParent) return;
|
|
1692
|
+
for (const childId of sourceParent.childIds) {
|
|
1693
|
+
const src = graph.nodes.get(childId);
|
|
1694
|
+
if (!src) continue;
|
|
1695
|
+
const clone = cloneChildInCoordinates(graph, src, sourceParent, targetParent, mode);
|
|
1696
|
+
if (src.childIds.length > 0) cloneChildrenWithMapping(graph, childId, clone.id, mode);
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
function enclosingInstanceOverrideFields(graph, node) {
|
|
1700
|
+
const fields = [];
|
|
1701
|
+
let parent = node.parentId ? graph.nodes.get(node.parentId) : void 0;
|
|
1702
|
+
while (parent) {
|
|
1703
|
+
if (parent.type === "INSTANCE") fields.push(new Set(parent.instanceOverrides.descendants.get(node.id)?.keys()));
|
|
1704
|
+
parent = parent.parentId ? graph.nodes.get(parent.parentId) : void 0;
|
|
1705
|
+
}
|
|
1706
|
+
return fields;
|
|
1707
|
+
}
|
|
1708
|
+
/** SLOT_CONTENT is absent because it drives children, which `ownsSlotContent` keeps instead. */
|
|
1709
|
+
const PROPERTY_REFERENCE_FIELDS = {
|
|
1710
|
+
VISIBLE: "visible",
|
|
1711
|
+
TEXT: "text",
|
|
1712
|
+
INSTANCE_SWAP: "componentId"
|
|
1713
|
+
};
|
|
1714
|
+
/** Instance links are expected to be shallow; the cap only stops a cycle from hanging sync. */
|
|
1715
|
+
const INSTANCE_CHAIN_LIMIT = 16;
|
|
1716
|
+
/**
|
|
1717
|
+
* Whether this instance's component, or the set it is a variant of, is where `propertyId` is
|
|
1718
|
+
* defined. Only a set counts: a component nested in an ordinary component defines its own
|
|
1719
|
+
* properties, not the outer one's.
|
|
1720
|
+
*/
|
|
1721
|
+
function definesProperty(graph, instance, propertyId) {
|
|
1722
|
+
let component = instance.componentId ? graph.nodes.get(instance.componentId) : void 0;
|
|
1723
|
+
for (let hops = 0; component?.type === "INSTANCE" && hops < INSTANCE_CHAIN_LIMIT; hops++) component = component.componentId ? graph.nodes.get(component.componentId) : void 0;
|
|
1724
|
+
const parent = component?.parentId ? graph.nodes.get(component.parentId) : void 0;
|
|
1725
|
+
const set = parent?.type === "COMPONENT_SET" ? parent : void 0;
|
|
1726
|
+
return [component, set].flatMap((node) => node?.componentPropertyDefinitions ?? []).some((definition) => definition.id === propertyId);
|
|
1727
|
+
}
|
|
1728
|
+
/**
|
|
1729
|
+
* What the nearest enclosing instance assigns `propertyId`, if any does. A property id belongs
|
|
1730
|
+
* to the component that defines it, so the walk stops at an instance of that component even
|
|
1731
|
+
* when it assigns nothing; otherwise an outer instance's unrelated property of the same id wins.
|
|
1732
|
+
*/
|
|
1733
|
+
function enclosingAssignment(graph, node, propertyId) {
|
|
1734
|
+
let current = node;
|
|
1735
|
+
while (current) {
|
|
1736
|
+
if (current.type === "INSTANCE") {
|
|
1737
|
+
if (Object.hasOwn(current.componentPropertyAssignments, propertyId)) return current.componentPropertyAssignments[propertyId];
|
|
1738
|
+
if (definesProperty(graph, current, propertyId)) return void 0;
|
|
1739
|
+
}
|
|
1740
|
+
current = current.parentId ? graph.nodes.get(current.parentId) : void 0;
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
function hasEnclosingAssignment(graph, node, propertyId) {
|
|
1744
|
+
return enclosingAssignment(graph, node, propertyId) !== void 0;
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* A component can gain a property-driven layer after an instance of it exists. Pass 4 leaves a
|
|
1748
|
+
* driven field alone, so the fresh clone has to take the enclosing instance's assignment here or
|
|
1749
|
+
* it keeps the component's default while every other instance layer shows the assigned value.
|
|
1750
|
+
*/
|
|
1751
|
+
function applyEnclosingAssignments(graph, clone) {
|
|
1752
|
+
for (const reference of clone.componentPropertyReferences) {
|
|
1753
|
+
const field = PROPERTY_REFERENCE_FIELDS[reference.field];
|
|
1754
|
+
if (!field) continue;
|
|
1755
|
+
const value = enclosingAssignment(graph, clone, reference.propertyId);
|
|
1756
|
+
if (value === void 0) continue;
|
|
1757
|
+
if (field === "visible") graph.updateNode(clone.id, { visible: value === "true" });
|
|
1758
|
+
else if (field === "text") graph.updateNode(clone.id, { text: value });
|
|
1759
|
+
else if (field === "componentId" && clone.type === "INSTANCE" && graph.nodes.has(value)) graph.swapInstanceComponent(clone.id, value);
|
|
1760
|
+
}
|
|
1761
|
+
for (const child of graph.getChildren(clone.id)) applyEnclosingAssignments(graph, child);
|
|
1762
|
+
}
|
|
1763
|
+
/**
|
|
1764
|
+
* Fields a component property drives on this child. The component states the default, but
|
|
1765
|
+
* an enclosing instance's assignment decides the value, so synchronising must not copy the
|
|
1766
|
+
* default over it — a page loaded later would otherwise reset the instance to the default.
|
|
1767
|
+
*/
|
|
1768
|
+
function propertyDrivenFields(graph, instChild, compChild) {
|
|
1769
|
+
const driven = /* @__PURE__ */ new Set();
|
|
1770
|
+
for (const reference of compChild.componentPropertyReferences) {
|
|
1771
|
+
const field = PROPERTY_REFERENCE_FIELDS[reference.field];
|
|
1772
|
+
if (field && hasEnclosingAssignment(graph, instChild, reference.propertyId)) driven.add(field);
|
|
1773
|
+
}
|
|
1774
|
+
return driven;
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* The text and visibility enclosing assignments give an existing child whose layer a property
|
|
1778
|
+
* drives. A layer linked to a property after the instance was made would otherwise keep what it
|
|
1779
|
+
* showed before, since synchronising leaves driven fields alone.
|
|
1780
|
+
*/
|
|
1781
|
+
function assignedFieldValues(graph, instChild, compChild) {
|
|
1782
|
+
const values = {};
|
|
1783
|
+
for (const reference of compChild.componentPropertyReferences) {
|
|
1784
|
+
const value = enclosingAssignment(graph, instChild, reference.propertyId);
|
|
1785
|
+
if (value === void 0) continue;
|
|
1786
|
+
if (reference.field === "TEXT" && instChild.type === "TEXT") values.text = value;
|
|
1787
|
+
else if (reference.field === "VISIBLE") values.visible = value === "true";
|
|
1788
|
+
}
|
|
1789
|
+
return values;
|
|
1790
|
+
}
|
|
1791
|
+
function childBindingProtection(graph, child, overrides) {
|
|
1792
|
+
const fields = enclosingInstanceOverrideFields(graph, child);
|
|
1793
|
+
fields.push(new Set(overrides.descendants.get(child.id)?.keys()));
|
|
1794
|
+
return bindingProtection(fields);
|
|
1795
|
+
}
|
|
1796
|
+
function linkMatchedChild(overrides, instParentId, instChild, compChildId) {
|
|
1797
|
+
if (instChild.type === "INSTANCE") setInstanceOverride(overrides, instParentId, instChild.id, "sourceComponentId", compChildId);
|
|
1798
|
+
else instChild.componentId = compChildId;
|
|
1799
|
+
}
|
|
1800
|
+
function matchFallbackChildren(graph, compParent, instParent, instParentId, overrides, instChildMap, usedInstChildIds) {
|
|
1801
|
+
const fallbackByType = /* @__PURE__ */ new Map();
|
|
1802
|
+
const remainingCandidateCount = /* @__PURE__ */ new Map();
|
|
1803
|
+
const unmatchedComponentCount = /* @__PURE__ */ new Map();
|
|
1804
|
+
for (const compChildId of compParent.childIds) {
|
|
1805
|
+
if (instChildMap.has(compChildId)) continue;
|
|
1806
|
+
const child = graph.nodes.get(compChildId);
|
|
1807
|
+
if (child) unmatchedComponentCount.set(child.type, (unmatchedComponentCount.get(child.type) ?? 0) + 1);
|
|
1808
|
+
}
|
|
1809
|
+
for (const childId of instParent.childIds) {
|
|
1810
|
+
const child = graph.nodes.get(childId);
|
|
1811
|
+
if (!child || usedInstChildIds.has(child.id)) continue;
|
|
1812
|
+
remainingCandidateCount.set(child.type, (remainingCandidateCount.get(child.type) ?? 0) + 1);
|
|
1813
|
+
let byName = fallbackByType.get(child.type);
|
|
1814
|
+
if (!byName) {
|
|
1815
|
+
byName = /* @__PURE__ */ new Map();
|
|
1816
|
+
fallbackByType.set(child.type, byName);
|
|
1817
|
+
}
|
|
1818
|
+
const queue = byName.get(child.name);
|
|
1819
|
+
if (queue) queue.push(child);
|
|
1820
|
+
else byName.set(child.name, [child]);
|
|
1821
|
+
}
|
|
1822
|
+
for (const compChildId of compParent.childIds) {
|
|
1823
|
+
if (instChildMap.has(compChildId)) continue;
|
|
1824
|
+
const compChild = graph.nodes.get(compChildId);
|
|
1825
|
+
if (!compChild) continue;
|
|
1826
|
+
const candidatesByName = fallbackByType.get(compChild.type);
|
|
1827
|
+
const candidateCount = remainingCandidateCount.get(compChild.type) ?? 0;
|
|
1828
|
+
if (candidateCount > (unmatchedComponentCount.get(compChild.type) ?? 0)) continue;
|
|
1829
|
+
const match = candidatesByName?.get(compChild.name)?.shift();
|
|
1830
|
+
if (!match) continue;
|
|
1831
|
+
remainingCandidateCount.set(compChild.type, candidateCount - 1);
|
|
1832
|
+
instChildMap.set(compChildId, match);
|
|
1833
|
+
usedInstChildIds.add(match.id);
|
|
1834
|
+
linkMatchedChild(overrides, instParentId, match, compChildId);
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
function sortInstanceChildren(graph, instParent, instParentId, compChildOrder, overrides) {
|
|
1838
|
+
const orderMap = /* @__PURE__ */ new Map();
|
|
1839
|
+
for (let i = 0; i < compChildOrder.length; i++) orderMap.set(compChildOrder[i], i);
|
|
1840
|
+
const ranks = /* @__PURE__ */ new Map();
|
|
1841
|
+
for (let index = 0; index < instParent.childIds.length; index++) {
|
|
1842
|
+
const childId = instParent.childIds[index];
|
|
1843
|
+
const node = graph.nodes.get(childId);
|
|
1844
|
+
const source = node ? getInstanceOverride(overrides, instParentId, node.id, "sourceComponentId") : void 0;
|
|
1845
|
+
const mapped = typeof source === "string" ? source : node?.componentId;
|
|
1846
|
+
const componentIndex = mapped ? orderMap.get(mapped) : void 0;
|
|
1847
|
+
ranks.set(childId, componentIndex ?? compChildOrder.length + index);
|
|
1848
|
+
}
|
|
1849
|
+
instParent.childIds.toSorted((left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0)).forEach((childId, index) => {
|
|
1850
|
+
if (instParent.childIds[index] !== childId) graph.insertChildAt(childId, instParentId, index);
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
/** True when syncing `compParentId` into `instParentId` would form a cycle. */
|
|
1854
|
+
function isCyclicSync(graph, compParentId, instParentId) {
|
|
1855
|
+
return compParentId === instParentId || graph.isDescendant(instParentId, compParentId);
|
|
1856
|
+
}
|
|
1857
|
+
/** Children already linked to a component child by sourceComponentId or componentId. */
|
|
1858
|
+
function matchLinkedChildren(graph, instParent, instParentId, overrides, compChildIdSet, instChildMap, usedInstChildIds) {
|
|
1859
|
+
for (const childId of instParent.childIds) {
|
|
1860
|
+
const child = graph.nodes.get(childId);
|
|
1861
|
+
if (!child) continue;
|
|
1862
|
+
const sourceComponentId = getInstanceOverride(overrides, instParentId, child.id, "sourceComponentId");
|
|
1863
|
+
const mappedComponentId = typeof sourceComponentId === "string" ? sourceComponentId : child.componentId;
|
|
1864
|
+
if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {
|
|
1865
|
+
instChildMap.set(mappedComponentId, child);
|
|
1866
|
+
usedInstChildIds.add(child.id);
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* Pass 3 of a sync: bring along the copy of a layer moved here inside the component, bring back
|
|
1872
|
+
* one the sync removed when its layer returns, or clone a layer the instance has no copy of. A
|
|
1873
|
+
* clone takes its own subtree unless copies the instance has belong in it, which the recursion
|
|
1874
|
+
* moves in instead. Children left unmatched are the sync's to remove once it finishes.
|
|
1875
|
+
*/
|
|
1876
|
+
function placeMissingChildren(graph, compParent, instParent, instChildMap, usedInstChildIds, context) {
|
|
1877
|
+
for (const child of instChildMap.values()) context.matched.add(child.id);
|
|
1878
|
+
for (const compChildId of compParent.childIds) {
|
|
1879
|
+
if (instChildMap.has(compChildId)) continue;
|
|
1880
|
+
const moved = unplacedCopy(graph, context, compChildId, instParent.id) ?? restoreRemovedCopy(graph, context, compChildId, instParent.id);
|
|
1881
|
+
if (moved) {
|
|
1882
|
+
graph.insertChildAt(moved.id, instParent.id, instParent.childIds.length);
|
|
1883
|
+
instChildMap.set(compChildId, moved);
|
|
1884
|
+
usedInstChildIds.add(moved.id);
|
|
1885
|
+
context.matched.add(moved.id);
|
|
1886
|
+
continue;
|
|
1887
|
+
}
|
|
1888
|
+
const src = graph.nodes.get(compChildId);
|
|
1889
|
+
if (!src) continue;
|
|
1890
|
+
const clone = cloneChildInCoordinates(graph, src, compParent, instParent);
|
|
1891
|
+
if (src.childIds.length > 0 && !hasUnplacedCopiesBelow(graph, context, compChildId)) cloneChildrenWithMapping(graph, compChildId, clone.id);
|
|
1892
|
+
applyEnclosingAssignments(graph, clone);
|
|
1893
|
+
instChildMap.set(compChildId, clone);
|
|
1894
|
+
usedInstChildIds.add(clone.id);
|
|
1895
|
+
context.matched.add(clone.id);
|
|
1896
|
+
}
|
|
1897
|
+
for (const childId of instParent.childIds) if (!usedInstChildIds.has(childId)) context.leftovers.add(childId);
|
|
1898
|
+
}
|
|
1899
|
+
function syncChildren(graph, compParentId, instParentId, overrides, context = createInstanceSyncContext(instParentId, overrides)) {
|
|
1900
|
+
if (isCyclicSync(graph, compParentId, instParentId)) return;
|
|
1901
|
+
const compParent = graph.nodes.get(compParentId);
|
|
1902
|
+
const instParent = graph.nodes.get(instParentId);
|
|
1903
|
+
if (!compParent || !instParent) return;
|
|
1904
|
+
const instChildMap = /* @__PURE__ */ new Map();
|
|
1905
|
+
const usedInstChildIds = /* @__PURE__ */ new Set();
|
|
1906
|
+
matchLinkedChildren(graph, instParent, instParentId, overrides, new Set(compParent.childIds), instChildMap, usedInstChildIds);
|
|
1907
|
+
matchFallbackChildren(graph, compParent, instParent, instParentId, overrides, instChildMap, usedInstChildIds);
|
|
1908
|
+
placeMissingChildren(graph, compParent, instParent, instChildMap, usedInstChildIds, context);
|
|
1909
|
+
for (const compChildId of compParent.childIds) {
|
|
1910
|
+
const compChild = graph.nodes.get(compChildId);
|
|
1911
|
+
const instChild = instChildMap.get(compChildId);
|
|
1912
|
+
if (!compChild || !instChild) continue;
|
|
1913
|
+
const protectedField = childBindingProtection(graph, instChild, overrides);
|
|
1914
|
+
const driven = propertyDrivenFields(graph, instChild, compChild);
|
|
1915
|
+
const componentScale = compChild.componentScale * instParent.componentScale / compParent.componentScale;
|
|
1916
|
+
const source = sourceInTargetCoordinates(compChild, componentScale);
|
|
1917
|
+
const updates = {
|
|
1918
|
+
componentScale,
|
|
1919
|
+
componentPropertyReferences: structuredClone(compChild.componentPropertyReferences)
|
|
1920
|
+
};
|
|
1921
|
+
syncBindingFields(instChild, source, updates, protectedField);
|
|
1922
|
+
copySyncedFields(updates, instChild, source, {
|
|
1923
|
+
compParent,
|
|
1924
|
+
instParent,
|
|
1925
|
+
factor: componentScale / compChild.componentScale,
|
|
1926
|
+
skip: (key) => driven.has(key) || isProtectedSyncField(instChild, key, protectedField)
|
|
1927
|
+
});
|
|
1928
|
+
Object.assign(updates, assignedFieldValues(graph, instChild, compChild));
|
|
1929
|
+
keepOwnContentSize(graph, updates, instChild, source);
|
|
1930
|
+
updateSyncedProps(graph, instChild, updates);
|
|
1931
|
+
if (compChild.childIds.length > 0 && !hasInstanceOverride$1(overrides, instParentId, instChild.id, "componentId") && !ownsSlotContent(graph, instChild, slotPropertyId(compChild))) syncChildren(graph, compChildId, instChild.id, overrides, context);
|
|
1932
|
+
}
|
|
1933
|
+
sortInstanceChildren(graph, instParent, instParentId, compParent.childIds, overrides);
|
|
1934
|
+
}
|
|
1935
|
+
//#endregion
|
|
1936
|
+
//#region src/instances.ts
|
|
1937
|
+
function copyInstanceComponentProps(component) {
|
|
1938
|
+
const props = {};
|
|
1939
|
+
for (const key of INSTANCE_SYNC_PROPS) copyProp(props, component, key);
|
|
1940
|
+
return props;
|
|
1941
|
+
}
|
|
1942
|
+
function createInstance(graph, componentId, parentId, overrides = {}) {
|
|
1943
|
+
const component = graph.nodes.get(componentId);
|
|
1944
|
+
if (component?.type !== "COMPONENT" || !canCreateInstance(graph, componentId, parentId)) return null;
|
|
1945
|
+
const props = {
|
|
1946
|
+
...copyInstanceComponentProps(component),
|
|
1947
|
+
name: component.name
|
|
1948
|
+
};
|
|
1949
|
+
const instance = graph.createNode("INSTANCE", parentId, {
|
|
1950
|
+
...props,
|
|
1951
|
+
...overrides,
|
|
1952
|
+
componentId
|
|
1953
|
+
});
|
|
1954
|
+
cloneChildrenWithMapping(graph, component.id, instance.id);
|
|
1955
|
+
return instance;
|
|
1956
|
+
}
|
|
1957
|
+
function populateInstanceChildren(graph, instanceId, componentId, mode = "deep") {
|
|
1958
|
+
const instance = graph.nodes.get(instanceId);
|
|
1959
|
+
const component = graph.nodes.get(componentId);
|
|
1960
|
+
if (!instance || !component || instance.type !== "INSTANCE") return;
|
|
1961
|
+
cloneChildrenWithMapping(graph, componentId, instanceId, mode);
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* A nested instance's link to the enclosing component's record is its `componentId` when it
|
|
1965
|
+
* was populated by cloning. A swap replaces that field, so keep the correspondence as the
|
|
1966
|
+
* owner's `sourceComponentId` override and record the swap itself; materialized documents
|
|
1967
|
+
* already carry the correspondence and only gain the swap.
|
|
1968
|
+
*/
|
|
1969
|
+
function recordNestedSwap(graph, instance, componentId) {
|
|
1970
|
+
const owner = instance.parentId ? findInstanceAncestor(graph, instance.parentId) : void 0;
|
|
1971
|
+
if (!owner) return;
|
|
1972
|
+
if (typeof getInstanceOverride(owner.instanceOverrides, owner.id, instance.id, "sourceComponentId") !== "string" && instance.componentId) setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, "sourceComponentId", instance.componentId);
|
|
1973
|
+
setInstanceOverride(owner.instanceOverrides, owner.id, instance.id, "componentId", componentId);
|
|
1974
|
+
graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides });
|
|
1975
|
+
}
|
|
1976
|
+
function swapInstanceComponent(graph, instanceId, componentId, { keepName = false } = {}) {
|
|
1977
|
+
const instance = graph.nodes.get(instanceId);
|
|
1978
|
+
const component = graph.nodes.get(componentId);
|
|
1979
|
+
if (!instance || component?.type !== "COMPONENT" || instance.type !== "INSTANCE") return;
|
|
1980
|
+
if (instance.parentId && !canCreateInstance(graph, componentId, instance.parentId)) return;
|
|
1981
|
+
const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : void 0;
|
|
1982
|
+
recordNestedSwap(graph, instance, componentId);
|
|
1983
|
+
const updates = { componentId };
|
|
1984
|
+
const source = sourceInTargetCoordinates(component, instance.componentScale);
|
|
1985
|
+
for (const key of INSTANCE_SYNC_PROPS) {
|
|
1986
|
+
if (hasInstanceOverride$1(instance.instanceOverrides, instance.id, instance.id, key)) continue;
|
|
1987
|
+
copyProp(updates, source, key);
|
|
1988
|
+
}
|
|
1989
|
+
if (!keepName && (!previousComponent || instance.name === previousComponent.name)) updates.name = component.name;
|
|
1990
|
+
const childIds = Array.from(instance.childIds);
|
|
1991
|
+
const slotContent = detachOwnedSlotContent(graph, instance);
|
|
1992
|
+
for (const childId of childIds) graph.deleteNode(childId);
|
|
1993
|
+
graph.updateNode(instanceId, updates);
|
|
1994
|
+
cloneChildrenWithMapping(graph, componentId, instanceId);
|
|
1995
|
+
restoreOwnedSlotContent(graph, instance, slotContent);
|
|
1996
|
+
}
|
|
1997
|
+
const syncingComponentsByGraph = /* @__PURE__ */ new WeakMap();
|
|
1998
|
+
function syncInstances(graph, componentId) {
|
|
1999
|
+
syncInstancesOf(graph, componentId, getInstances(graph, componentId));
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* Syncs each component's instances, in order, as one edit: the copies they remove stay
|
|
2003
|
+
* restorable together for as long as undo keeps that edit.
|
|
2004
|
+
*/
|
|
2005
|
+
function syncInstancesTogether(graph, componentIds) {
|
|
2006
|
+
groupCopyRemovals(graph, () => {
|
|
2007
|
+
for (const id of componentIds) syncInstances(graph, id);
|
|
2008
|
+
});
|
|
2009
|
+
}
|
|
2010
|
+
/** Syncs one instance from its component, as `syncInstances` does for every instance. */
|
|
2011
|
+
function syncInstance(graph, instanceId) {
|
|
2012
|
+
const instance = graph.nodes.get(instanceId);
|
|
2013
|
+
if (instance?.type !== "INSTANCE" || !instance.componentId) return;
|
|
2014
|
+
syncInstancesOf(graph, instance.componentId, [instance]);
|
|
2015
|
+
}
|
|
2016
|
+
function syncInstancesOf(graph, componentId, instances) {
|
|
2017
|
+
const component = graph.nodes.get(componentId);
|
|
2018
|
+
if (component?.type !== "COMPONENT") return;
|
|
2019
|
+
let syncing = syncingComponentsByGraph.get(graph);
|
|
2020
|
+
if (!syncing) {
|
|
2021
|
+
syncing = /* @__PURE__ */ new Set();
|
|
2022
|
+
syncingComponentsByGraph.set(graph, syncing);
|
|
2023
|
+
}
|
|
2024
|
+
if (syncing.has(componentId)) return;
|
|
2025
|
+
syncing.add(componentId);
|
|
2026
|
+
try {
|
|
2027
|
+
groupCopyRemovals(graph, (removals) => {
|
|
2028
|
+
for (const instance of instances) {
|
|
2029
|
+
const enclosing = enclosingInstanceOverrideFields(graph, instance);
|
|
2030
|
+
enclosing.push(new Set(instance.instanceOverrides.self.keys()));
|
|
2031
|
+
const protectedField = bindingProtection(enclosing);
|
|
2032
|
+
const source = sourceInTargetCoordinates(component, instance.componentScale);
|
|
2033
|
+
const updates = {};
|
|
2034
|
+
syncBindingFields(instance, source, updates, protectedField);
|
|
2035
|
+
for (const key of INSTANCE_SYNC_PROPS) {
|
|
2036
|
+
if (key === "boundVariables") continue;
|
|
2037
|
+
if (isProtectedSyncField(instance, key, protectedField)) continue;
|
|
2038
|
+
copyProp(updates, source, key);
|
|
2039
|
+
}
|
|
2040
|
+
keepOwnContentSize(graph, updates, instance, source);
|
|
2041
|
+
updateSyncedProps(graph, instance, updates);
|
|
2042
|
+
const context = createInstanceSyncContext(instance.id, instance.instanceOverrides);
|
|
2043
|
+
syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context);
|
|
2044
|
+
removeLeftoverCopies(graph, context, removals);
|
|
2045
|
+
}
|
|
2046
|
+
});
|
|
2047
|
+
} finally {
|
|
2048
|
+
syncing.delete(componentId);
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
function detachInstance(graph, instanceId) {
|
|
2052
|
+
const node = graph.nodes.get(instanceId);
|
|
2053
|
+
if (node?.type !== "INSTANCE") return;
|
|
2054
|
+
if (node.componentId) graph.instanceIndex.get(node.componentId)?.delete(instanceId);
|
|
2055
|
+
node.type = "FRAME";
|
|
2056
|
+
node.componentId = null;
|
|
2057
|
+
clearInstanceOverrides(node.instanceOverrides);
|
|
2058
|
+
}
|
|
2059
|
+
function getMainComponent(graph, instanceId) {
|
|
2060
|
+
const node = graph.nodes.get(instanceId);
|
|
2061
|
+
if (!node?.componentId) return void 0;
|
|
2062
|
+
return graph.nodes.get(node.componentId);
|
|
2063
|
+
}
|
|
2064
|
+
function getInstances(graph, componentId) {
|
|
2065
|
+
const ids = graph.instanceIndex.get(componentId);
|
|
2066
|
+
if (!ids) return [];
|
|
2067
|
+
const instances = [];
|
|
2068
|
+
for (const id of ids) {
|
|
2069
|
+
const node = graph.nodes.get(id);
|
|
2070
|
+
if (node) instances.push(node);
|
|
2071
|
+
}
|
|
2072
|
+
return instances;
|
|
2073
|
+
}
|
|
2074
|
+
/** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */
|
|
2075
|
+
function findInstanceAncestor(graph, nodeId) {
|
|
2076
|
+
let current = graph.nodes.get(nodeId);
|
|
2077
|
+
while (current) {
|
|
2078
|
+
if (current.type === "INSTANCE") return current;
|
|
2079
|
+
current = current.parentId ? graph.nodes.get(current.parentId) : void 0;
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
/**
|
|
2083
|
+
* True when a node field is protected from instance synchronization.
|
|
2084
|
+
*/
|
|
2085
|
+
function hasInstanceOverride(graph, nodeId, field) {
|
|
2086
|
+
const instance = findInstanceAncestor(graph, nodeId);
|
|
2087
|
+
if (!instance) return false;
|
|
2088
|
+
return hasInstanceOverride$1(instance.instanceOverrides, instance.id, nodeId, field);
|
|
2089
|
+
}
|
|
2090
|
+
function recordInstanceOverride(graph, nodeId, fields) {
|
|
2091
|
+
const instance = findInstanceAncestor(graph, nodeId);
|
|
2092
|
+
if (!instance) return;
|
|
2093
|
+
const relevant = [...fields].filter((field) => INSTANCE_OVERRIDE_FIELDS.includes(field));
|
|
2094
|
+
if (relevant.length === 0) return;
|
|
2095
|
+
for (const field of relevant) setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field);
|
|
2096
|
+
graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides });
|
|
2097
|
+
}
|
|
2098
|
+
//#endregion
|
|
2099
|
+
//#region src/instances/source-walk.ts
|
|
2100
|
+
/**
|
|
2101
|
+
* Walk an instance's layers beside the component layers they copy, matched the way instance
|
|
2102
|
+
* sync matches them. `visit` returns whether to continue into that pair's children. With
|
|
2103
|
+
* `strict`, two layers claiming one source throw instead of the later one winning.
|
|
2104
|
+
*/
|
|
2105
|
+
function walkInstanceSources(graph, instance, visit, strict = false) {
|
|
2106
|
+
if (instance.type !== "INSTANCE" || !instance.componentId) return;
|
|
2107
|
+
const component = graph.getNode(instance.componentId);
|
|
2108
|
+
if (!component) return;
|
|
2109
|
+
const walk = (sourceParent, instanceParent) => {
|
|
2110
|
+
const bySource = /* @__PURE__ */ new Map();
|
|
2111
|
+
for (const child of graph.getChildren(instanceParent.id)) {
|
|
2112
|
+
const mapped = getInstanceOverride(instance.instanceOverrides, instance.id, child.id, "sourceComponentId");
|
|
2113
|
+
const sourceId = typeof mapped === "string" ? mapped : child.componentId;
|
|
2114
|
+
if (!sourceId) continue;
|
|
2115
|
+
if (strict && bySource.has(sourceId)) throw new Error(`Ambiguous component-property target ${sourceId}`);
|
|
2116
|
+
bySource.set(sourceId, child);
|
|
2117
|
+
}
|
|
2118
|
+
for (const sourceId of sourceParent.childIds) {
|
|
2119
|
+
const source = graph.getNode(sourceId);
|
|
2120
|
+
const target = bySource.get(sourceId);
|
|
2121
|
+
if (source && target && visit(source, target)) walk(source, target);
|
|
2122
|
+
}
|
|
2123
|
+
};
|
|
2124
|
+
walk(component, instance);
|
|
2125
|
+
}
|
|
2126
|
+
//#endregion
|
|
2127
|
+
//#region src/components/properties.ts
|
|
2128
|
+
function componentPropertyOwners(graph, instance) {
|
|
2129
|
+
if (instance.type !== "INSTANCE") return [];
|
|
2130
|
+
const component = instanceMainComponent(graph, instance);
|
|
2131
|
+
if (!component) return [];
|
|
2132
|
+
const parent = component.parentId ? graph.getNode(component.parentId) : null;
|
|
2133
|
+
return parent?.type === "COMPONENT_SET" ? [parent, component] : [component];
|
|
2134
|
+
}
|
|
2135
|
+
function componentPropertyDefinitions(graph, instance) {
|
|
2136
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
2137
|
+
for (const owner of componentPropertyOwners(graph, instance)) for (const definition of owner.componentPropertyDefinitions) if (!definitions.has(definition.id)) definitions.set(definition.id, definition);
|
|
2138
|
+
return [...definitions.values()];
|
|
2139
|
+
}
|
|
2140
|
+
function resolveComponentPropertyValue(graph, value) {
|
|
2141
|
+
const direct = graph.getNode(value);
|
|
2142
|
+
if (direct?.type === "COMPONENT") return direct;
|
|
2143
|
+
if (direct?.type === "COMPONENT_SET") {
|
|
2144
|
+
const componentId = direct.childIds.find((id) => graph.getNode(id)?.type === "COMPONENT");
|
|
2145
|
+
return componentId ? graph.getNode(componentId) ?? null : null;
|
|
2146
|
+
}
|
|
2147
|
+
for (const node of graph.getAllNodes()) if (node.type === "COMPONENT" && (node.componentKey === value || node.sourceLibraryKey === value || node.source.id === value)) return node;
|
|
2148
|
+
return null;
|
|
2149
|
+
}
|
|
2150
|
+
function findComponentPropertyTarget(graph, instance, propertyId) {
|
|
2151
|
+
return findComponentPropertyTargets(graph, instance, propertyId)[0] ?? null;
|
|
2152
|
+
}
|
|
2153
|
+
function findComponentPropertyTargets(graph, instance, propertyId) {
|
|
2154
|
+
const targets = [];
|
|
2155
|
+
walkInstanceSources(graph, instance, (source, target) => {
|
|
2156
|
+
const reference = source.componentPropertyReferences.find((candidate) => candidate.propertyId === propertyId);
|
|
2157
|
+
if (reference) targets.push({
|
|
2158
|
+
node: target,
|
|
2159
|
+
field: reference.field,
|
|
2160
|
+
source
|
|
2161
|
+
});
|
|
2162
|
+
return true;
|
|
2163
|
+
}, true);
|
|
2164
|
+
return targets;
|
|
2165
|
+
}
|
|
2166
|
+
function applyTextProperty(graph, owner, targets, value) {
|
|
2167
|
+
for (const item of targets) {
|
|
2168
|
+
if (item.field !== "TEXT" || item.node.type !== "TEXT") continue;
|
|
2169
|
+
graph.updateNode(item.node.id, { text: value });
|
|
2170
|
+
if (findInstanceAncestor(graph, item.node.id)) setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "text", value);
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
function applyBooleanProperty(graph, owner, targets, value) {
|
|
2174
|
+
for (const item of targets) {
|
|
2175
|
+
if (item.field !== "VISIBLE") continue;
|
|
2176
|
+
const instance = findInstanceAncestor(graph, item.node.id);
|
|
2177
|
+
graph.updateNode(item.node.id, { visible: value === "true" });
|
|
2178
|
+
if (instance) setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "visible", value === "true");
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
function applyInstanceSwapProperty(graph, owner, targets, target) {
|
|
2182
|
+
for (const item of targets) {
|
|
2183
|
+
if (item.field !== "INSTANCE_SWAP" || item.node.type !== "INSTANCE") continue;
|
|
2184
|
+
graph.swapInstanceComponent(item.node.id, target.id);
|
|
2185
|
+
setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "name", target.name);
|
|
2186
|
+
setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "componentId", target.id);
|
|
2187
|
+
setInstanceOverride(owner.instanceOverrides, owner.id, item.node.id, "sourceComponentId", item.source.id);
|
|
2188
|
+
graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides });
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
function applyComponentPropertyValue(graph, instanceId, definition, value) {
|
|
2192
|
+
const instance = graph.getNode(instanceId);
|
|
2193
|
+
if (instance?.type !== "INSTANCE") return null;
|
|
2194
|
+
if (definition.type === "VARIANT") return null;
|
|
2195
|
+
const targets = findComponentPropertyTargets(graph, instance, definition.id);
|
|
2196
|
+
const target = definition.type === "INSTANCE_SWAP" ? resolveComponentPropertyValue(graph, value) : null;
|
|
2197
|
+
if (definition.type === "INSTANCE_SWAP" && !target) return null;
|
|
2198
|
+
if (definition.type === "TEXT") applyTextProperty(graph, instance, targets, value);
|
|
2199
|
+
else if (definition.type === "BOOLEAN") applyBooleanProperty(graph, instance, targets, value);
|
|
2200
|
+
else if (target) applyInstanceSwapProperty(graph, instance, targets, target);
|
|
2201
|
+
graph.updateNode(instance.id, { componentPropertyAssignments: {
|
|
2202
|
+
...instance.componentPropertyAssignments,
|
|
2203
|
+
[definition.id]: definition.type === "INSTANCE_SWAP" && target ? target.id : value
|
|
2204
|
+
} });
|
|
2205
|
+
return definition.type === "INSTANCE_SWAP" ? target : instance;
|
|
2206
|
+
}
|
|
2207
|
+
function componentSubtree(graph, componentId) {
|
|
2208
|
+
const component = graph.getNode(componentId);
|
|
2209
|
+
if (!component) return [];
|
|
2210
|
+
const nodes = [component];
|
|
2211
|
+
const visit = (node) => {
|
|
2212
|
+
for (const child of graph.getChildren(node.id)) {
|
|
2213
|
+
nodes.push(child);
|
|
2214
|
+
visit(child);
|
|
2215
|
+
}
|
|
2216
|
+
};
|
|
2217
|
+
visit(component);
|
|
2218
|
+
return nodes;
|
|
2219
|
+
}
|
|
2220
|
+
function componentInstances(graph, componentId) {
|
|
2221
|
+
return [...graph.getAllNodes()].filter((node) => node.type === "INSTANCE" && node.componentId === componentId);
|
|
2222
|
+
}
|
|
2223
|
+
function removePropertyFromNode(graph, node, propertyId) {
|
|
2224
|
+
if (node.componentPropertyReferences.some((reference) => reference.propertyId === propertyId)) graph.updateNode(node.id, { componentPropertyReferences: node.componentPropertyReferences.filter((reference) => reference.propertyId !== propertyId) });
|
|
2225
|
+
if (node.type === "INSTANCE" && propertyId in node.componentPropertyAssignments) graph.updateNode(node.id, { componentPropertyAssignments: Object.fromEntries(Object.entries(node.componentPropertyAssignments).filter(([id]) => id !== propertyId)) });
|
|
2226
|
+
}
|
|
2227
|
+
function removeComponentProperty(graph, ownerId, propertyId) {
|
|
2228
|
+
const owner = graph.getNode(ownerId);
|
|
2229
|
+
if (!owner || owner.type !== "COMPONENT" && owner.type !== "COMPONENT_SET") return false;
|
|
2230
|
+
graph.updateNode(owner.id, { componentPropertyDefinitions: owner.componentPropertyDefinitions.filter((definition) => definition.id !== propertyId) });
|
|
2231
|
+
const nodes = [
|
|
2232
|
+
...componentSubtree(graph, owner.id),
|
|
2233
|
+
...componentInstances(graph, owner.id),
|
|
2234
|
+
...owner.type === "COMPONENT_SET" ? owner.childIds.flatMap((id) => [...componentSubtree(graph, id), ...componentInstances(graph, id)]) : []
|
|
2235
|
+
];
|
|
2236
|
+
for (const node of nodes) removePropertyFromNode(graph, node, propertyId);
|
|
2237
|
+
return true;
|
|
2238
|
+
}
|
|
2239
|
+
/** A new component property ID, in the `prop:` form the editor, plugin API, and design JSX share. */
|
|
2240
|
+
function createComponentPropertyId() {
|
|
2241
|
+
return `prop:${randomHex(8)}`;
|
|
2242
|
+
}
|
|
2243
|
+
//#endregion
|
|
2244
|
+
//#region src/components/exposure.ts
|
|
2245
|
+
/**
|
|
2246
|
+
* Instances a component can expose: those in its own layers, not inside another instance,
|
|
2247
|
+
* whose content belongs to that instance's component.
|
|
2248
|
+
*/
|
|
2249
|
+
function exposableInstances(graph, componentId) {
|
|
2250
|
+
const found = [];
|
|
2251
|
+
const visit = (parentId) => {
|
|
2252
|
+
for (const child of graph.getChildren(parentId)) if (child.type === "INSTANCE") found.push(child);
|
|
2253
|
+
else visit(child.id);
|
|
2254
|
+
};
|
|
2255
|
+
visit(componentId);
|
|
2256
|
+
return found;
|
|
2257
|
+
}
|
|
2258
|
+
/**
|
|
2259
|
+
* The layers of an instance that stand for exposed nested instances of its component, in
|
|
2260
|
+
* layer order. Each is matched to its source the way instance sync matches children.
|
|
2261
|
+
*/
|
|
2262
|
+
function exposedInstances(graph, instance) {
|
|
2263
|
+
const found = [];
|
|
2264
|
+
walkInstanceSources(graph, instance, (source, target) => {
|
|
2265
|
+
if (source.type !== "INSTANCE") return true;
|
|
2266
|
+
if (source.isExposedInstance) found.push(target);
|
|
2267
|
+
return false;
|
|
2268
|
+
});
|
|
2269
|
+
return found;
|
|
2270
|
+
}
|
|
2271
|
+
const OWNER_TYPES = /* @__PURE__ */ new Set([
|
|
2272
|
+
"INSTANCE",
|
|
2273
|
+
"COMPONENT",
|
|
2274
|
+
"COMPONENT_SET"
|
|
2275
|
+
]);
|
|
2276
|
+
/**
|
|
2277
|
+
* Whether an instance may be exposed, under Figma's rules: it sits in a component's own layers
|
|
2278
|
+
* (an instance's copy follows its source) and its component has properties or exposes nested
|
|
2279
|
+
* instances itself.
|
|
2280
|
+
*/
|
|
2281
|
+
function instanceExposureIssue(graph, instance) {
|
|
2282
|
+
const owner = instance.parentId ? graph.closest(instance.parentId, (node) => OWNER_TYPES.has(node.type)) : void 0;
|
|
2283
|
+
if (!owner) return "not-in-component";
|
|
2284
|
+
if (owner.type === "INSTANCE") return "not-primary";
|
|
2285
|
+
const component = instanceMainComponent(graph, instance);
|
|
2286
|
+
return componentPropertyDefinitions(graph, instance).length > 0 || !!component && exposableInstances(graph, component.id).some((node) => node.isExposedInstance) ? null : "nothing-to-expose";
|
|
2287
|
+
}
|
|
2288
|
+
//#endregion
|
|
2289
|
+
export { BOOLEAN_BINDING_FIELDS, DEFAULT_HISTORY_LIMIT, INSTANCE_FOLLOWED_FIELDS, INSTANCE_OVERRIDE_FIELDS, INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS, INSTANCE_SYNC_TEXT_PROPS, MAX_LIST_INDENTATION, NUMERIC_FIELDS, PLAIN_PARAGRAPH, STRING_BINDING_FIELDS, TEXT_LAYOUT_FIELDS, TEXT_METRIC_FIELDS, TEXT_PARAGRAPH_SPACING_FIELDS, TEXT_SHAPING_FIELDS, UndoManager, applyComponentPropertyValue, aspectRatioLockEditable, autoLayoutSizingFields, canCreateInstance, cloneChildrenWithMapping, collectResizeDescendants, componentPropertyDefinitions, componentPropertyOwners, computeConstrainedResizeChanges, constrainedChildRect, copyInstanceComponentProps, createComponentPropertyId, createInstance, createResizeSnapshot, createsComponentCycle, cycleSafeParent, detachInstance, detachOwnedSlotContent, enforcedAspectRatio, exposableInstances, exposedInstances, fillSizingFields, findComponentPropertyTarget, findComponentPropertyTargets, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, hasParagraphSpacing, hasTextList, instanceExposureIssue, instanceMainComponent, instanceSlotFrames, isNumericVariableBindingField, layoutConstrainedChildRect, layoutSizing, layoutSizingError, layoutSizingInParent, layoutSizingOptions, layoutSizingUpdates, lockedAspectRatioTarget, ownsSlotContent, paragraphCount, paragraphIndexAt, paragraphSpacingAt, paragraphStyleAt, paragraphStylesAfterEdit, paragraphStylesAfterTextChange, paragraphStylesInRange, paragraphStylesWithoutSpacing, populateInstanceChildren, recapturedAspectRatio, recordInstanceOverride, removeComponentProperty, resolveComponentPropertyValue, restoreOwnedSlotContent, scaleNodeChanges, scaleVariableBindingUnits, scaleVectorNetworkForResize, scaledChildRect, scaledGeometryChanges, sharedParagraphSpacing, sizeKeepingAspectRatio, slotPropertyId, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, textAutoResizeFor, textParagraphRanges, trimParagraphStyles, withIndentation, withListType, withParagraphSpacing };
|
|
2290
|
+
|
|
2291
|
+
//# sourceMappingURL=exposure.js.map
|