@moondraft/import 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +2 -2
  3. package/SOURCE.md +343 -4
  4. package/dist/adapter/convert.d.ts +26 -2
  5. package/dist/adapter/convert.js +817 -217
  6. package/dist/adapter/figma-descriptions.d.ts +7 -0
  7. package/dist/adapter/figma-descriptions.js +34 -0
  8. package/dist/adapter/figma-grids.d.ts +12 -0
  9. package/dist/adapter/figma-grids.js +175 -0
  10. package/dist/adapter/figma-handoff.d.ts +34 -0
  11. package/dist/adapter/figma-handoff.js +188 -0
  12. package/dist/adapter/figma-hyperlinks.d.ts +13 -0
  13. package/dist/adapter/figma-hyperlinks.js +77 -0
  14. package/dist/adapter/figma.d.ts +4 -1
  15. package/dist/adapter/figma.js +15 -4
  16. package/dist/adapter/file-components.d.ts +10 -3
  17. package/dist/adapter/file-components.js +126 -33
  18. package/dist/adapter/file-resources.js +545 -47
  19. package/dist/adapter/file-typography.d.ts +6 -0
  20. package/dist/adapter/file-typography.js +44 -0
  21. package/dist/adapter/image-crop.d.ts +18 -0
  22. package/dist/adapter/image-crop.js +30 -0
  23. package/dist/adapter/link.d.ts +12 -1
  24. package/dist/adapter/link.js +380 -113
  25. package/dist/adapter/payload.js +3 -3
  26. package/dist/adapter/variables.d.ts +2 -1
  27. package/dist/adapter/variables.js +5 -2
  28. package/dist/figma-file.d.ts +1 -0
  29. package/dist/figma-file.js +1 -0
  30. package/dist/figma.d.ts +1 -0
  31. package/dist/figma.js +191 -35
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.js +1 -0
  34. package/dist/report.d.ts +59 -1
  35. package/dist/report.js +176 -30
  36. package/dist/serialize.d.ts +7 -0
  37. package/dist/serialize.js +79 -0
  38. package/dist/taco/figma-import/container/kiwiContainer.d.ts +3 -0
  39. package/dist/taco/figma-import/container/kiwiContainer.js +1 -1
  40. package/dist/taco/figma-import/figFile.js +3 -0
  41. package/dist/taco/figma-import/import/carry.d.ts +14 -1
  42. package/dist/taco/figma-import/import/carry.js +34 -1
  43. package/dist/taco/figma-import/import/componentProps.d.ts +10 -4
  44. package/dist/taco/figma-import/import/componentProps.js +29 -13
  45. package/dist/taco/figma-import/import/componentSets.d.ts +2 -0
  46. package/dist/taco/figma-import/import/componentSets.js +1 -1
  47. package/dist/taco/figma-import/import/converters/effects.d.ts +3 -13
  48. package/dist/taco/figma-import/import/converters/effects.js +4 -34
  49. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  50. package/dist/taco/figma-import/import/converters/exportSettings.js +75 -0
  51. package/dist/taco/figma-import/import/converters/frame.d.ts +1 -1
  52. package/dist/taco/figma-import/import/converters/frame.js +15 -6
  53. package/dist/taco/figma-import/import/converters/gradient.d.ts +2 -0
  54. package/dist/taco/figma-import/import/converters/gradient.js +3 -1
  55. package/dist/taco/figma-import/import/converters/grid.d.ts +12 -0
  56. package/dist/taco/figma-import/import/converters/grid.js +97 -0
  57. package/dist/taco/figma-import/import/converters/group.d.ts +2 -4
  58. package/dist/taco/figma-import/import/converters/group.js +6 -15
  59. package/dist/taco/figma-import/import/converters/image.d.ts +2 -1
  60. package/dist/taco/figma-import/import/converters/image.js +60 -16
  61. package/dist/taco/figma-import/import/converters/layout.d.ts +8 -7
  62. package/dist/taco/figma-import/import/converters/layout.js +66 -37
  63. package/dist/taco/figma-import/import/converters/rectangle.d.ts +1 -1
  64. package/dist/taco/figma-import/import/converters/rectangle.js +3 -3
  65. package/dist/taco/figma-import/import/converters/section.d.ts +2 -3
  66. package/dist/taco/figma-import/import/converters/section.js +5 -11
  67. package/dist/taco/figma-import/import/converters/shared.d.ts +9 -5
  68. package/dist/taco/figma-import/import/converters/shared.js +23 -10
  69. package/dist/taco/figma-import/import/converters/text.d.ts +38 -1
  70. package/dist/taco/figma-import/import/converters/text.js +248 -32
  71. package/dist/taco/figma-import/import/converters/vector.d.ts +36 -15
  72. package/dist/taco/figma-import/import/converters/vector.js +214 -73
  73. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +19 -3
  74. package/dist/taco/figma-import/import/converters/vectorNetwork.js +147 -29
  75. package/dist/taco/figma-import/import/instances.d.ts +32 -5
  76. package/dist/taco/figma-import/import/instances.js +613 -130
  77. package/dist/taco/figma-import/import/styles.d.ts +2 -0
  78. package/dist/taco/figma-import/import/styles.js +6 -0
  79. package/dist/taco/figma-import/import/types.d.ts +8 -0
  80. package/dist/taco/figma-import/import/variables.d.ts +5 -2
  81. package/dist/taco/figma-import/import/variables.js +65 -31
  82. package/dist/taco/figma-import/import/variantTrees.d.ts +1 -1
  83. package/dist/taco/figma-import/import/variantTrees.js +46 -4
  84. package/dist/taco/figma-import/import/walk.d.ts +62 -7
  85. package/dist/taco/figma-import/import/walk.js +328 -122
  86. package/dist/taco/figma-import/kiwi/message.d.ts +4 -2
  87. package/dist/taco/figma-import/kiwi/message.js +59 -15
  88. package/dist/taco/model/codec.d.ts +2 -2
  89. package/dist/taco/model/codec.js +72 -8
  90. package/dist/taco/model/component-evaluation.d.ts +2 -0
  91. package/dist/taco/model/component-evaluation.js +7 -0
  92. package/dist/taco/model/instance-resolver.d.ts +6 -2
  93. package/dist/taco/model/instance-resolver.js +50 -18
  94. package/dist/taco/model/sha256.js +13 -8
  95. package/dist/taco/model/types.d.ts +57 -5
  96. package/dist/taco/model/types.js +4 -0
  97. package/dist/taco/svg-import/style/computed.js +1 -0
  98. package/package.json +3 -2
@@ -6,8 +6,9 @@
6
6
  // frame naming the main, with no children, whose overrides (by layer path, SPEC 19.3) hold what its expanded layers
7
7
  // show unlike the main's. The effective records (the main's layers with those overrides applied) equal the expanded
8
8
  // ones in every field the renderer draws, so the page looks the same; an instance whose expansion differs in a field
9
- // that takes no override (a path's network, a stroke's position or weight, a layer the main lacks, the root's own
10
- // fills) stays expanded, and so do the instances inside it, which are linked on their own when they can be. A stroke's
9
+ // that takes no override (a path's network change beyond layout, a stroke's position or weight, a layer the main lacks, the root's own
10
+ // fills) stays expanded, and so do the instances inside it, which are linked on their own when they can be; the
11
+ // import report gives each one's reason (expansionReason). A stroke's
11
12
  // other colour is a paint override (the renderer draws a stroke's paint in place of its compact colour).
12
13
  // - A component whose root is on the page has it as its main. Any other gets a hidden main under '@components' (core's
13
14
  // parent of mains that are not drawn): a copy of its largest expanded instance with every layer its other expansions
@@ -30,6 +31,8 @@
30
31
  // instance whose layers draw outside it, a 114 px logo in a 29 px frame that does not clip or a card's shadow that
31
32
  // reaches well past it, stays expanded); its text body field carries the text's box (see difference).
32
33
  // The markers are removed whether or not anything is linked.
34
+ import { supportsTextField } from './file-typography.js';
35
+ import { Properties, TextStyleSchema } from '@moondraft/editor/schema';
33
36
  import { instanceLayout, legacyAuto, netBounds, sizingOf } from '@moondraft/editor/core';
34
37
  /** The converter's markers on the expanded models (instanceOf, mainOf, and setOf: an instance's variant set name). */
35
38
  export const MARKERS = ['instanceOf', 'mainOf', 'setOf', 'variant'];
@@ -41,23 +44,52 @@ const componentOf = (vk) => vk.split('\u0000')[0];
41
44
  */
42
45
  export const unmark = (m) => { for (const k of MARKERS)
43
46
  delete m[k]; };
47
+ /** Plain descriptions of the fields an expansion can differ in (difference, match), for the import report. */
48
+ const FIELD_WORDS = {
49
+ fills: 'fills', stroke: 'stroke', 'look.stroke': 'stroke position, cap or join', strokeWidth: 'stroke weight',
50
+ 'look.stroke.paint': 'stroke paint', effects: 'shadows or blurs', clip: 'clipping', layout: 'auto layout settings',
51
+ net: 'vector network', kind: 'layer type', result: 'boolean result', 'radius bindings': 'corner radius bindings',
52
+ };
53
+ /**
54
+ * Describes in plain words why an instance stays expanded, from linking's reason for it (LinkCounts.unlinked).
55
+ * @param reason - Linking's reason.
56
+ * @returns What the report says after "expanded instance: ".
57
+ */
58
+ export function expansionReason(reason) {
59
+ const fixed = {
60
+ 'used once': 'its component has no main on the page and no other instance', 'no main': 'its component has no main',
61
+ 'not a frame': 'it is not a frame', 'content outside the instance': 'its content draws outside its box',
62
+ 'inside its main': 'it is inside its own main', 'layer order': 'its layers are in another order than its main\'s',
63
+ 'a layer the main lacks': 'it has a layer its main lacks', 'conflicting bound swaps': 'one swap property selects different mains in it',
64
+ net: 'a vector network its main\'s layout does not give',
65
+ };
66
+ if (fixed[reason])
67
+ return fixed[reason];
68
+ if (reason.startsWith('root ')) {
69
+ const k = reason.slice(5);
70
+ return `its own ${FIELD_WORDS[k] ?? k}, unlike its main's`;
71
+ }
72
+ return `a layer's ${FIELD_WORDS[reason] ?? reason}, unlike its main's`;
73
+ }
44
74
  /** Keys that draw nothing, or name the node and its place: never compared. */
45
75
  const IGNORED = new Set(['id', 'parent', 'children', 'z', 'order', 'sourceId', 'fileInstance', 'fileSlotHost', 'fileFills', 'name', 'component', 'overrides', 'instanceOf', 'mainOf', 'setOf', 'variant',
46
76
  'layoutData', 'keepSize', 'remeasured', 'storedHeight', 'storedRow', 'storedBox', 'boxScale', 'locked', 'runs', 'styleAt', 'fill', 'look']);
47
77
  /** An instance's own record (SPEC 19.2): the rest of an instance's appearance is its main root's. */
48
78
  const OWN = new Set(['t', 'w', 'h', 'opacity', 'visible', 'blend', 'mask', 'exports']);
49
- const same = (a, b) => {
79
+ const same = (a, b, tolerance = 0) => {
50
80
  if (a === b)
51
81
  return true;
82
+ if (tolerance && typeof a === 'number' && typeof b === 'number')
83
+ return Math.abs(a - b) < tolerance;
52
84
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null || Array.isArray(a) !== Array.isArray(b))
53
85
  return false;
54
86
  const ka = Object.keys(a).filter((k) => a[k] !== undefined), kb = Object.keys(b).filter((k) => b[k] !== undefined);
55
- return ka.length === kb.length && ka.every((k) => same(a[k], b[k]));
87
+ return ka.length === kb.length && ka.every((k) => same(a[k], b[k], tolerance));
56
88
  };
57
89
  /** What a layer fills with: its look's fills, else its compact fill as one solid paint (the renderer draws both so). */
58
90
  const fillsOf = (m) => m.look?.fills ?? (m.fill ? [{ k: 'solid', c: m.fill }] : []);
59
91
  /** A text's style index per UTF-16 unit, from styleAt or the file's runs ([length, style]). */
60
- function styleAtOf(m) {
92
+ export function styleAtOf(m) {
61
93
  if (m.styleAt)
62
94
  return m.styleAt;
63
95
  const at = [];
@@ -70,6 +102,44 @@ function styleAtOf(m) {
70
102
  }
71
103
  return at;
72
104
  }
105
+ // The editor peer must resolve a run's paint before an instance can inherit its main's colour source.
106
+ export const supportsRunPaint = 'fillStyle' in TextStyleSchema.properties;
107
+ const supportsFrameOverrides = 'layoutData.flow' in Properties;
108
+ const linkedTextColor = (style) => style.fileFillStyle ? supportsRunPaint : !!style.fileTextColor;
109
+ /** Can this occurrence inherit the main's fitted runs, including their colour sources? */
110
+ function inheritsTextRuns(occurrence, main, runs, mainRuns, nativeFile) {
111
+ const bound = occurrence.styles.some((style) => linkedTextColor(style) || style.fileTypography);
112
+ // A link alone cannot own a native instance palette. Wording with its own unbound formatting can.
113
+ if (!bound && !(nativeFile && occurrence.content === main.content &&
114
+ [...occurrence.styles, ...main.styles].some(style => style.link || style.figmaHyperlink)))
115
+ return false;
116
+ let differentLink = false;
117
+ const matched = new Map();
118
+ const last = Math.min(main.content.length, mainRuns.length) - 1;
119
+ // An empty text still has an insertion style in slot zero.
120
+ for (let i = 0; i < Math.max(1, runs.length); i++) {
121
+ const slot = runs[i] ?? 0, from = runs.length ? mainRuns[Math.min(i, last)] ?? 0 : 0;
122
+ if (matched.get(slot) === from)
123
+ continue;
124
+ const style = occurrence.styles[slot], inherited = main.styles[from];
125
+ // A shared variable can draw a different literal in the occurrence's mode.
126
+ if (!inherited)
127
+ return false;
128
+ const { fileOwnTypography: _own, ...fitted } = style;
129
+ if (linkedTextColor(style))
130
+ fitted.color = inherited.color;
131
+ for (const [field, ref] of Object.entries(style.fileTypography ?? {}))
132
+ if (ref && supportsTextField(field) && ref === inherited.fileTypography?.[field])
133
+ fitted[field] = inherited[field];
134
+ if (!same(fitted, inherited)) {
135
+ if (!nativeFile || !same({ ...fitted, link: inherited.link, figmaHyperlink: inherited.figmaHyperlink }, inherited))
136
+ return false;
137
+ differentLink = true;
138
+ }
139
+ matched.set(slot, from);
140
+ }
141
+ return differentLink ? 'link-only' : bound;
142
+ }
73
143
  /** One override record applied to a copy of a record, as core applies it (components.ts applyOverride: a stored box is
74
144
  * the instance's layout's alone). */
75
145
  function applied(record, over) {
@@ -77,6 +147,15 @@ function applied(record, over) {
77
147
  for (const [key, value] of Object.entries(over)) {
78
148
  if (key === 'storedBox')
79
149
  continue;
150
+ if (key === 'layoutData.gridCell') {
151
+ out.layoutData = { ...out.layoutData, gridCell: { ...out.layoutData?.gridCell, ...value } };
152
+ continue;
153
+ }
154
+ if (key === 'layoutData.flow') {
155
+ const flow = value, data = out.layoutData;
156
+ out.layoutData = { ...data, layout: { ...data?.layout, ...flow }, padding: { ...data?.layout?.padding, ...data?.padding, ...flow.padding } };
157
+ continue;
158
+ }
80
159
  if (!key.includes('.')) {
81
160
  out[key] = value;
82
161
  continue;
@@ -98,7 +177,7 @@ function applied(record, over) {
98
177
  }
99
178
  /** The keys of a record that differ from another's as one override (null: none), or the key that takes no override
100
179
  * (a string). own: whether the record is a layer's (its own keys take overrides) or a root's (they are the instance's). */
101
- function difference(E, R, own, rootOverride = false) {
180
+ function difference(E, R, own, rootOverride = false, omitLink) {
102
181
  const rec = {};
103
182
  for (const k of new Set([...Object.keys(E), ...Object.keys(R)])) {
104
183
  if (IGNORED.has(k) || same(E[k], R[k]))
@@ -114,27 +193,50 @@ function difference(E, R, own, rootOverride = false) {
114
193
  rec.w = E.w;
115
194
  rec.h = E.h;
116
195
  }
196
+ // Layout owns a stretched path's network override. keep() checks it against the
197
+ // main laid out with all sibling overrides and stored boxes before accepting the link.
198
+ else if (k === 'net' && E.kind === 'path' && own)
199
+ rec.net = E.net;
200
+ else if (k === 'clip') {
201
+ if (!!E.clip !== !!R.clip) {
202
+ if (!supportsFrameOverrides)
203
+ return 'clip';
204
+ rec.clip = !!E.clip;
205
+ }
206
+ }
117
207
  else if (k === 'radius' || k === 'smoothing') {
118
- if (!same(E.radius ?? 0, R.radius ?? 0) || !same(E.smoothing ?? 0, R.smoothing ?? 0)) {
119
- rec.radius = E.radius ?? 0;
120
- rec.smoothing = E.smoothing ?? 0;
208
+ if (!same(E[k] ?? 0, R[k] ?? 0)) {
209
+ rec[k] = E[k] ?? 0;
210
+ // Older peers encode both values in the corners field.
211
+ if (!supportsFrameOverrides)
212
+ Object.assign(rec, { radius: E.radius ?? 0, smoothing: E.smoothing ?? 0 });
121
213
  }
122
214
  }
123
215
  else if (k === 'content' || k === 'styles' || k === 'para')
124
216
  continue; // the text body, below
217
+ // A text's own line limit and ellipsis; null takes away its main's.
218
+ else if (k === 'maxLines' || k === 'truncate')
219
+ rec[k] = E[k] ?? null;
125
220
  else if ((k === 'stroke' || k === 'strokeWidth') && E.kind !== 'text')
126
221
  continue; // the stroke, below
127
222
  else
128
223
  return k;
129
224
  }
130
225
  if (E.kind === 'text') {
131
- const body = (m) => [m.content, m.styles, styleAtOf(m), m.para ?? []];
132
- const [a, b] = [body(E), body(R)];
226
+ const runs = styleAtOf(E), mainRuns = styleAtOf(R), para = E.para ?? [];
133
227
  // The renderer's text body field carries the text's box, taken from the main's layer with this record applied
134
228
  // (wire.ts overrideBase), and replaces an inner instance's whole body, box included: a text's size and body go
135
229
  // together, so neither an inner size nor the main's box shows through.
136
- if (!a.every((v, i) => same(v, b[i])) || rec.w !== undefined)
137
- Object.assign(rec, { content: a[0], styles: a[1], styleAt: a[2], para: a[3], w: E.w, h: E.h });
230
+ const inheritsPalette = inheritsTextRuns(E, R, runs, mainRuns, omitLink !== undefined);
231
+ if (inheritsPalette === 'link-only')
232
+ omitLink?.();
233
+ if (E.content !== R.content || rec.w !== undefined || !same(para, R.para ?? [])
234
+ || (!inheritsPalette && (!same(E.styles, R.styles) || !same(runs, mainRuns)))) {
235
+ Object.assign(rec, { content: E.content, para, w: E.w, h: E.h });
236
+ // A plain body owns its palette and indices together. A character-only override can inherit both.
237
+ if (!inheritsPalette)
238
+ Object.assign(rec, { styles: E.styles, styleAt: runs });
239
+ }
138
240
  }
139
241
  if (E.kind !== 'text') {
140
242
  if (!same(fillsOf(E), fillsOf(R))) {
@@ -142,13 +244,18 @@ function difference(E, R, own, rootOverride = false) {
142
244
  return 'fills';
143
245
  rec['look.fills'] = fillsOf(E);
144
246
  }
145
- if (!same(E.strokeWidth, R.strokeWidth))
146
- return 'strokeWidth';
147
247
  if (!same(E.stroke, R.stroke) && (!E.stroke || !R.stroke))
148
248
  return 'stroke';
149
- const { paint: pe, ...se } = E.look?.stroke ?? {}, { paint: pr, ...sr } = R.look?.stroke ?? {};
249
+ const { paint: pe, sides: es, ...se } = E.look?.stroke ?? {}, { paint: pr, sides: rs, ...sr } = R.look?.stroke ?? {};
150
250
  if (!same(se, sr) || !!E.look?.stroke !== !!R.look?.stroke)
151
251
  return 'look.stroke';
252
+ if ((es || rs) && E.stroke && R.stroke) {
253
+ const sides = es ?? Array(4).fill(E.strokeWidth);
254
+ if (!same(sides, rs ?? Array(4).fill(R.strokeWidth)))
255
+ rec['look.stroke.sides'] = sides;
256
+ }
257
+ else if (!same(E.strokeWidth, R.strokeWidth))
258
+ return 'strokeWidth';
152
259
  // What a drawn stroke paints with: its look's paint, else its compact colour as one solid paint (the renderer
153
260
  // draws a paint in place of the compact colour), so an expansion's other colour is a paint override.
154
261
  const strokePaint = (m, p) => p ?? (m.stroke ? { k: 'solid', c: m.stroke } : undefined);
@@ -169,8 +276,11 @@ function difference(E, R, own, rootOverride = false) {
169
276
  if (!['fills', 'stroke', 'shadows', 'layerBlur', 'backgroundBlur'].includes(k) && !same(E.look?.[k], R.look?.[k]))
170
277
  return `look.${k}`;
171
278
  }
172
- if (!own && !rootOverride && Object.keys(rec).length)
173
- return Object.keys(rec)[0];
279
+ if (!own && !rootOverride) {
280
+ const unsupported = Object.keys(rec).find(k => k !== 'clip' && k !== 'smoothing');
281
+ if (unsupported)
282
+ return unsupported;
283
+ }
174
284
  return Object.keys(rec).length ? rec : null;
175
285
  }
176
286
  // Core lays an instance out again (a resize of it, an edit of its main, an override that hides a layer or changes a
@@ -190,6 +300,12 @@ function dataOverride(own = {}, main = {}) {
190
300
  for (const k of new Set([...Object.keys(own), ...Object.keys(main)])) {
191
301
  if (same(own[k], main[k]))
192
302
  continue;
303
+ if (k === 'gridCell' && own[k]) {
304
+ if (Object.keys(main[k] ?? {}).some(field => !(field in own[k])))
305
+ return { layoutData: own };
306
+ out['layoutData.gridCell'] = Object.fromEntries(Object.entries(own[k]).filter(([field, v]) => v !== main[k]?.[field]));
307
+ continue;
308
+ }
193
309
  if (own[k] === undefined && !(k in NEUTRAL))
194
310
  return { layoutData: own };
195
311
  out[`layoutData.${k}`] = own[k] ?? NEUTRAL[k];
@@ -201,18 +317,48 @@ function withData(data, over) {
201
317
  if (!over)
202
318
  return data;
203
319
  let out = over.layoutData ?? data;
204
- for (const [k, v] of Object.entries(over))
205
- if (k.startsWith('layoutData.'))
320
+ for (const [k, v] of Object.entries(over)) {
321
+ if (k === 'layoutData.gridCell')
322
+ out = { ...out, gridCell: { ...out?.gridCell, ...v } };
323
+ else if (k.startsWith('layoutData.'))
206
324
  out = { ...out, [k.slice(11)]: v };
325
+ }
207
326
  return out;
208
327
  }
209
- /** of an instance's content, its main root's auto layout and padding (an instance whose content's differ stays
210
- * expanded: an override of the instance's layoutData would not reach its main's content on the renderer's side); */
211
- const contentInputs = (m) => [m.layoutData?.layout, m.layoutData?.padding];
328
+ /** The axes on which layer E fills its auto layout parent P (Figma's layout grow or stretch) where P does not hug. */
329
+ const fillsIn = (E, P) => ['width', 'height'].filter((axis) => E.layoutData?.resizing?.[axis] === 'fill'
330
+ && sizingOf(P?.layoutData, axis) !== 'hug' && !!P?.layoutData?.layout && P.layoutData.layout.kind !== 'absolute');
331
+ /** The content settings this frame changes relative to its component, including individual padding sides. */
332
+ function flowOverride(own = {}, main = {}, fills = []) {
333
+ const a = own.layout ?? {}, b = main.layout ?? {};
334
+ const flow = {};
335
+ const defaults = { kind: 'absolute', columnTracks: [], rowTracks: [], columnGap: 0, rowGap: 0, gap: 0, align: 'start', justify: 'start', wrap: false,
336
+ wrapGap: a.gap ?? 0, alignContent: 'auto', widthSizing: 'fixed', heightSizing: 'fixed', strokesIncluded: false };
337
+ for (const [key, fallback] of Object.entries(defaults)) {
338
+ if (!same(a[key] ?? fallback, b[key] ?? fallback))
339
+ flow[key] = a[key] ?? fallback;
340
+ }
341
+ // Hug/Fixed can be carried in sizing even when the stack itself is identical.
342
+ if (a.kind && a.kind !== 'absolute')
343
+ for (const axis of ['width', 'height']) {
344
+ const local = sizingOf(own, axis), inherited = sizingOf(main, axis);
345
+ // Core reads a flow's sizing as the frame's own, over its fill and stored sizing (components.ts
346
+ // withInstanceSpacing): none where it shows the main's, nor where it fills its parent (Figma's fill wins there).
347
+ if (local !== inherited && !fills.includes(axis))
348
+ flow[axis + 'Sizing'] = local;
349
+ else
350
+ delete flow[axis + 'Sizing'];
351
+ }
352
+ const pad = { ...a.padding, ...own.padding }, base = { ...b.padding, ...main.padding };
353
+ const sides = Object.fromEntries(['top', 'right', 'bottom', 'left'].filter(k => (pad[k] ?? 0) !== (base[k] ?? 0)).map(k => [k, pad[k] ?? 0]));
354
+ if (Object.keys(sides).length)
355
+ flow.padding = sides;
356
+ return Object.keys(flow).length ? { 'layoutData.flow': flow } : {};
357
+ }
212
358
  /** of an instance in its parent (P), its own layoutData as linking gives it: no auto layout (its main's), and a size
213
359
  * that hugs held ('fixed': it has no children to hug), so a parent that hugs it lays out as it did. */
214
360
  function instanceData(E, P) {
215
- const { layout: _layout, box: _box, ...data } = E.layoutData ?? {};
361
+ const { layout: _layout, padding: _padding, box: _box, ...data } = E.layoutData ?? {};
216
362
  const fixed = (o) => o && Object.fromEntries(Object.entries(o).map(([k, v]) => [k, v === 'hug' ? 'fixed' : v]));
217
363
  // The axes it hugged are recorded (heldHug), so that a swap in the editor hugs them again.
218
364
  const held = ['width', 'height'].filter((a) => data.sizing?.[a] === 'hug' || data.resizing?.[a] === 'hug');
@@ -222,10 +368,20 @@ function instanceData(E, P) {
222
368
  data.sizing = fixed(data.sizing);
223
369
  if (data.resizing)
224
370
  data.resizing = fixed(data.resizing);
225
- const auto = ['horizontal', 'vertical'].includes(E.layoutData?.layout?.kind);
371
+ const auto = ['horizontal', 'vertical', 'grid'].includes(E.layoutData?.layout?.kind);
226
372
  for (const axis of ['width', 'height'])
227
373
  if (auto && sizingOf(E.layoutData, axis) === 'fill' && sizingOf(P?.layoutData, axis) === 'hug')
228
374
  data.sizing = { ...data.sizing, [axis]: 'fixed' };
375
+ // Figma's fill (layout grow, stretch) wins over the frame's own Fixed sizing: the occurrence fills there (a navigation
376
+ // list across a fixed header), as its main's layer does.
377
+ for (const axis of auto ? fillsIn(E, P) : [])
378
+ if (data.sizing?.[axis] === 'fixed') {
379
+ const { [axis]: _held, ...rest } = data.sizing;
380
+ if (Object.keys(rest).length)
381
+ data.sizing = rest;
382
+ else
383
+ delete data.sizing;
384
+ }
229
385
  return data;
230
386
  }
231
387
  /** How far core's layout of a linked instance may place a layer from its expanded box (px; 1e-4 of the linear part)
@@ -255,7 +411,7 @@ export function linkComponents(doc) {
255
411
  return linkWithLayers(doc, false).counts;
256
412
  }
257
413
  /** @internal Links components and tracks where their expanded layers went for import reports. */
258
- export function linkWithLayers(doc, trackLayers = true) {
414
+ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile = false) {
259
415
  // Variant sets (convert.ts markSet): one hidden main per variant used, so each instance's main is its own variant
260
416
  // and its overrides are its own changes alone; but a showcase of a set (each variant once or twice) costs a main per
261
417
  // variant. So per set: the page is linked both ways and a set keeps a main per variant where that stores no more
@@ -264,32 +420,43 @@ export function linkWithLayers(doc, trackLayers = true) {
264
420
  // grew the models 13%, 3 grows them 4% (39583 to 41158) and still cuts the override keys by 23%; 6 kept the models
265
421
  // level but cut the keys by 19% only. The used-once rule stays per component: a variant's main used once is kept
266
422
  // when its set is used more than once, so every variant of a set can be swapped to.
267
- const sets = new Set(doc.models.filter((m) => m.setOf && m.variant).map((m) => m.instanceOf));
268
- const run = (each, report = false) => {
423
+ const sets = new Set(), placed = new Set();
424
+ for (const model of doc.models) {
425
+ if (model.setOf && model.variant)
426
+ sets.add(model.instanceOf);
427
+ if (model.mainOf !== undefined && model.kind === 'frame')
428
+ placed.add(model.mainOf);
429
+ }
430
+ const run = (each, compareCosts, report = false) => {
269
431
  const skip = new Set();
270
432
  for (;;) {
271
- const d = { models: structuredClone(doc.models) }, aliases = new Map();
272
- const { once, ...r } = linkOnce(d, skip, each, report ? aliases : undefined);
433
+ const d = { models: doc.models }, aliases = new Map();
434
+ const { once, omittedLinks, expandedReasons, ...r } = linkOnce(d, skip, each, compareCosts, report ? aliases : undefined, swapBinding, nativeFile);
273
435
  if (!once.length)
274
- return { d, r, aliases };
436
+ return { d, r, aliases, omittedLinks, expandedReasons };
275
437
  for (const comp of once)
276
438
  skip.add(comp);
277
439
  }
278
440
  };
279
441
  let chosen = new Set();
280
- if (sets.size) {
281
- const shared = run(new Set()).r.cost, split = run(sets).r.cost;
442
+ // A placed main wins in both trials. With all sets placed the costs tie.
443
+ if ([...sets].every(set => placed.has(set)))
444
+ chosen = sets;
445
+ else {
446
+ const shared = run(new Set(), true).r.cost, split = run(sets, true).r.cost;
282
447
  const W = 3, of = (m, c) => { const [n, k] = m.get(c) ?? [0, 0]; return n * W + k; };
283
448
  chosen = new Set([...sets].filter((c) => of(split, c) <= of(shared, c)));
284
449
  }
285
- const { d, r: { cost: _cost, ...r }, aliases } = run(chosen, trackLayers);
286
- doc.models = d.models;
450
+ const { d, r: { cost: _cost, ...r }, aliases, omittedLinks, expandedReasons } = run(chosen, false, trackLayers);
451
+ // Detach only the linked output. Trial passes and discarded expansions never need deep copies.
452
+ doc.models = nativeFile ? d.models : structuredClone(d.models);
287
453
  const counts = { ...r, variantSets: chosen.size, sharedSets: sets.size - chosen.size };
288
- return { counts, aliases };
454
+ return { counts, aliases, omittedLinks, expandedReasons };
289
455
  }
290
456
  /** linkComponents with no hidden main for the components in `skip`; also returns the components whose hidden main is
291
457
  * used once (once). */
292
- function linkOnce(doc, skip, each = new Set(), aliases) {
458
+ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFile = false) {
459
+ const omittedLinks = new Map();
293
460
  const recordAlias = (from, to) => {
294
461
  if (!aliases)
295
462
  return;
@@ -300,18 +467,15 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
300
467
  };
301
468
  // The hidden main an expanded instance takes: its component's, or its variant's for a set in `each`.
302
469
  const variantKey = (m) => (each.has(m.instanceOf) && m.setOf && m.variant ? `${m.instanceOf}\u0000${m.variant}` : m.instanceOf);
303
- const byId = new Map(doc.models.map((m) => [m.id, m])), kids = new Map();
304
- for (const m of doc.models) {
305
- const p = m.parent ?? '';
306
- if (!kids.has(p))
307
- kids.set(p, []);
308
- kids.get(p).push(m.id);
309
- }
310
- const kidsOf = (id) => kids.get(id) ?? [];
311
- const size = (id) => 1 + kidsOf(id).reduce((n, c) => n + size(c), 0);
312
- const before = doc.models.length;
470
+ // Each trial replaces records in its own index. Input records and their nested values stay read-only.
471
+ const byId = new Map(), kids = new Map();
313
472
  const mains = new Map(), instances = new Map();
314
473
  for (const m of doc.models) {
474
+ byId.set(m.id, m);
475
+ const parent = m.parent ?? '';
476
+ if (!kids.has(parent))
477
+ kids.set(parent, []);
478
+ kids.get(parent).push(m.id);
315
479
  if (m.mainOf !== undefined && !mains.has(m.mainOf) && m.kind === 'frame')
316
480
  mains.set(m.mainOf, m.id);
317
481
  if (m.instanceOf !== undefined) {
@@ -321,16 +485,17 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
321
485
  instances.get(k).push(m.id);
322
486
  }
323
487
  }
488
+ const kidsOf = (id) => kids.get(id) ?? [];
489
+ const size = (id) => 1 + kidsOf(id).reduce((n, c) => n + size(c), 0);
490
+ const before = doc.models.length;
324
491
  // Whether the layers under a frame draw outside its box, with their drop shadows and layer blurs where they reach
325
492
  // further than SLACK, as the renderer reaches them (the offset plus 1.5 blur and the spread; crates/scn-core
326
- // derived.rs effect_reach, with the spread shadow_spread draws: below 0 only on a frame with square corners);
327
- // clipping frames bound their own children.
328
- const square = (m) => m.kind === 'frame' && (Array.isArray(m.radius) ? m.radius.every((r) => !r) : !m.radius);
493
+ // derived.rs effect_reach); clipping frames bound their own children.
329
494
  const reach = (m) => {
330
495
  const blur = 1.5 * (m.look?.layerBlur?.radius ?? 0), out = [blur, blur, blur, blur]; // left, top, right, bottom
331
496
  for (const s of m.look?.shadows ?? [])
332
497
  if (!s.inner && s.c?.[3] !== 0) {
333
- const spread = square(m) ? s.spread ?? 0 : Math.max(0, s.spread ?? 0), x = s.x ?? 0, y = s.y ?? 0;
498
+ const spread = s.spread ?? 0, x = s.x ?? 0, y = s.y ?? 0;
334
499
  const e = 1.5 * (s.blur ?? 0) + spread;
335
500
  out[0] = Math.max(out[0], e - x);
336
501
  out[1] = Math.max(out[1], e - y);
@@ -380,18 +545,29 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
380
545
  // and the expansion adds nothing (it stays expanded), so the main holds no layer twice.
381
546
  function plan(e, u) {
382
547
  const ek = kidsOf(e), uk = kidsOf(u), K = (x) => key(byId.get(x)), n = ek.length, m = uk.length;
383
- const L = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));
384
- for (let i = n - 1; i >= 0; i--)
385
- for (let j = m - 1; j >= 0; j--)
386
- L[i][j] = K(ek[i]) === K(uk[j]) ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
387
548
  const list = [], added = new Map();
388
549
  let i = 0, j = 0;
550
+ while (i < n && j < m && K(ek[i]) === K(uk[j])) {
551
+ list.push(uk[j++]);
552
+ i++;
553
+ }
554
+ // The common prefix is already paired. Only allocate an LCS table for an ambiguous suffix.
555
+ const start = i, L = [];
556
+ if (i < n && j < m) {
557
+ for (let x = i; x <= n; x++)
558
+ L[x - start] = new Int32Array(m - start + 1);
559
+ for (let x = n - 1; x >= i; x--)
560
+ for (let y = m - 1; y >= j; y--) {
561
+ const row = L[x - start], below = L[x - start + 1], col = y - start;
562
+ row[col] = K(ek[x]) === K(uk[y]) ? below[col + 1] + 1 : Math.max(below[col], row[col + 1]);
563
+ }
564
+ }
389
565
  while (i < n) {
390
566
  if (j < m && K(ek[i]) === K(uk[j])) {
391
567
  list.push(uk[j++]);
392
568
  i++;
393
569
  }
394
- else if (j >= m || L[i + 1][j] >= L[i][j + 1]) {
570
+ else if (j >= m || L[i - start + 1][j - start] >= L[i - start][j - start + 1]) {
395
571
  const k = K(ek[i]);
396
572
  added.set(k, (added.get(k) ?? 0) + 1);
397
573
  list.push({ copy: ek[i++] });
@@ -399,16 +575,30 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
399
575
  else
400
576
  list.push(uk[j++]);
401
577
  }
402
- list.push(...uk.slice(j));
403
- const count = (ids, k) => ids.filter((x) => K(x) === k).length;
404
- for (const [k, a] of added)
405
- if (count(uk, k) + a > count(ek, k))
406
- return null;
578
+ while (j < m)
579
+ list.push(uk[j++]);
580
+ if (added.size) {
581
+ const remaining = new Map();
582
+ for (const id of ek) {
583
+ const k = K(id);
584
+ remaining.set(k, (remaining.get(k) ?? 0) + 1);
585
+ }
586
+ for (const id of uk) {
587
+ const k = K(id);
588
+ remaining.set(k, (remaining.get(k) ?? 0) - 1);
589
+ }
590
+ for (const [k, count] of added)
591
+ if (count > remaining.get(k))
592
+ return null;
593
+ }
407
594
  const subs = [];
408
595
  let last = -1;
409
596
  for (const c of ek) {
410
- last = list.findIndex((x, p) => p > last && K(typeof x === 'string' ? x : x.copy) === K(c));
411
- const x = list[last];
597
+ const k = K(c);
598
+ let x;
599
+ do {
600
+ x = list[++last];
601
+ } while (K(typeof x === 'string' ? x : x.copy) !== k);
412
602
  if (typeof x !== 'string')
413
603
  continue;
414
604
  const sub = plan(c, x);
@@ -457,77 +647,124 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
457
647
  const isInstance = (m) => m?.kind === 'frame' && m.component !== undefined && m.component !== m.id;
458
648
  // A main's effective tree: per layer, its path (from the main's child down), what it shows and its children.
459
649
  const trees = new Map();
460
- const reroot = (n, prefix, overrides) => ({ path: `${prefix};${n.path}`, rec: overrides?.[n.path] ? applied(n.rec, overrides[n.path]) : n.rec, kids: n.kids.map((k) => reroot(k, prefix, overrides)), instance: n.instance, main: n.main, rootOverride: n.rootOverride, data: withData(n.data, overrides?.[n.path]) });
650
+ function swappedNode(n, main) {
651
+ ensure(main);
652
+ return { ...n, main, rec: n.recordOf(main), kids: n.childrenOf(main) };
653
+ }
654
+ function reroot(n, prefix, overrides) {
655
+ const over = overrides?.[n.path];
656
+ if (n.instance && over?.component && over.component !== n.main)
657
+ n = swappedNode(n, over.component);
658
+ // Keep each holder's overrides in scope when a later placement chooses another main.
659
+ const underHolder = (child) => reroot(child, prefix, overrides);
660
+ return { ...n, path: `${prefix};${n.path}`, rec: over ? applied(n.rec, over) : n.rec,
661
+ ...(n.instance && over && { recordOf: (main) => applied(n.recordOf(main), over) }),
662
+ ...(n.instance && { childrenOf: (main) => n.childrenOf(main).map(underHolder) }),
663
+ kids: n.kids.map(underHolder), data: withData(n.data, over) };
664
+ }
461
665
  function tree(main) {
462
666
  if (trees.has(main))
463
667
  return trees.get(main);
464
- const build = (id, path) => {
668
+ const build = (id, path, inDefinition = true) => {
465
669
  const m = byId.get(id);
466
670
  if (!isInstance(m))
467
- return { path, rec: m, kids: kidsOf(id).map((c) => build(c, `${path};${c}`)) };
468
- const M = byId.get(m.component), rec = { ...(m.fileInstance && { fileInstance: m.fileInstance }), ...Object.fromEntries(Object.entries(M).filter(([k]) => !OWN.has(k))), ...Object.fromEntries(Object.entries(m).filter(([k]) => OWN.has(k))) };
469
- return { path, rec: m.overrides?.[''] ? applied(rec, m.overrides['']) : rec, main: m.component, rootOverride: m.overrides?.[''], instance: true, data: m.layoutData ?? {}, kids: tree(m.component).map((n) => reroot(n, path, m.overrides)) };
671
+ return { path, rec: m, kids: kidsOf(id).map((c) => build(c, `${path};${c}`, inDefinition && !m.fileInstance)) };
672
+ const own = Object.fromEntries(Object.entries(m).filter(([key]) => OWN.has(key) || key === 'fileInstance'));
673
+ const recordOf = (main) => {
674
+ const root = Object.fromEntries(Object.entries(byId.get(main)).filter(([key]) => !OWN.has(key)));
675
+ const rec = { ...root, ...own };
676
+ return m.overrides?.[''] ? applied(rec, m.overrides['']) : rec;
677
+ };
678
+ const childrenOf = (main) => tree(main).map((child) => reroot(child, path, m.overrides));
679
+ const binding = inDefinition && m.fileInstance && swapBinding?.(m.fileInstance);
680
+ return { path, binding, rec: recordOf(m.component), main: m.component, recordOf, instance: true, data: m.layoutData ?? {}, childrenOf, kids: childrenOf(m.component) };
470
681
  };
471
682
  const t = kidsOf(main).map((c) => build(c, c));
472
683
  trees.set(main, t);
473
684
  return t;
474
685
  }
686
+ // A group's fill allocation can resize a descendant path through scale constraints.
687
+ function fillsPath(path) {
688
+ for (let m = path; m; m = byId.get(m.parent)) {
689
+ if ((m === path || m.group) && (sizingOf(m.layoutData, 'width') === 'fill' || sizingOf(m.layoutData, 'height') === 'fill'))
690
+ return true;
691
+ }
692
+ return false;
693
+ }
475
694
  // Fills `out` with the overrides that make main-tree node list `mk` show concrete children `ek`, inside an instance
476
695
  // expanded at `size`, and `geometry` with each matched layer's expanded record, its main's and the box to store if
477
696
  // core's layout does not give the expanded one; a reason if none can.
478
- function match(ek, mk, out, size, geometry, fills) {
479
- const at = new Map(), used = new Set();
480
- mk.forEach((n, i) => { const k = key(n.rec); if (!at.has(k))
481
- at.set(k, []); at.get(k).push(i); });
482
- let last = -1;
697
+ function match(ek, mk, out, size, geometry, linkPaths, fills, bound = new Map()) {
698
+ const used = new Set();
699
+ let next = 0;
483
700
  for (const id of ek) {
484
- const E = byId.get(id), k = key(E), i = at.get(k)?.find((j) => j > last);
485
- if (i === undefined)
486
- return at.has(k) ? 'layer order' : 'a layer the main lacks';
487
- last = i;
488
- used.add(i);
489
- const n = mk[i];
701
+ const E = byId.get(id), k = key(E);
702
+ while (next < mk.length && key(mk[next].rec) !== k)
703
+ next++;
704
+ if (next === mk.length)
705
+ return mk.some((n) => key(n.rec) === k) ? 'layer order' : 'a layer the main lacks';
706
+ used.add(next);
707
+ const n = mk[next++];
490
708
  let R = n.rec, children = n.kids;
491
709
  const swap = E.fileInstance && n.instance && mains.get(E.instanceOf);
710
+ if (n.binding && swap) {
711
+ // A property on one occurrence selects the same main for every layer bound to it.
712
+ if (bound.has(n.binding) && bound.get(n.binding) !== swap)
713
+ return 'conflicting bound swaps';
714
+ bound.set(n.binding, swap);
715
+ }
492
716
  if (swap && swap !== n.main) {
493
- ensure(swap);
494
- const root = byId.get(swap);
495
- R = { ...(n.rootOverride ? applied(root, n.rootOverride) : root), ...Object.fromEntries(Object.entries(R).filter(([key]) => OWN.has(key))) };
496
- children = tree(swap).map((child) => reroot(child, n.path, undefined));
717
+ const swapped = swappedNode(n, swap);
718
+ R = swapped.rec;
719
+ children = swapped.kids;
497
720
  out[n.path] = { component: swap };
498
721
  }
499
722
  if (E.kind !== R.kind)
500
723
  return 'kind';
501
724
  // A nested instance's appearance is its main's (the renderer draws its template root): only its own keys differ.
502
- const d = difference(E, R, true);
725
+ const d = difference(E, R, true, false, linkPaths && (() => linkPaths.add(n.path)));
503
726
  if (typeof d === 'string')
504
727
  return d;
728
+ const fillPath = E.kind === 'path' && fillsPath(E);
729
+ if (d?.net && !fillPath)
730
+ return 'net';
505
731
  if (n.instance && !E.fileInstance) {
506
732
  const own = difference(E, R, false);
507
733
  if (typeof own === 'string')
508
734
  return own;
509
735
  }
510
- if (n.instance && !same(contentInputs(E), contentInputs(R)))
736
+ const inputs = n.instance ? flowOverride(E.layoutData, R.layoutData, fillsIn(E, byId.get(E.parent))) : {};
737
+ if (!supportsFrameOverrides && inputs['layoutData.flow'])
511
738
  return 'layout';
512
- const inputs = {};
513
739
  if (n.instance)
514
740
  Object.assign(inputs, dataOverride(instanceData(E, byId.get(E.parent)), n.data));
515
741
  else {
516
742
  const a = layerInputs(E), b = layerInputs(R);
517
- for (const k of Object.keys(a))
518
- if (!same(a[k], b[k]))
519
- Object.assign(inputs, k === 'layoutData' ? dataOverride(a[k], b[k]) : { [k]: a[k] });
520
- if ('storedHeight' in inputs || 'storedRow' in inputs)
743
+ // Resizing a parametric path scales its box and network together.
744
+ // Use the main's box as the input to the same resize during layout.
745
+ if (fillPath && E.shape && a.layoutData.box && b.layoutData.box)
746
+ a.layoutData = { ...a.layoutData, box: b.layoutData.box };
747
+ if (E.kind === 'frame' && supportsFrameOverrides) {
748
+ const { layout: _a, padding: _ap, ...own } = a.layoutData;
749
+ const { layout: _b, padding: _bp, ...base } = b.layoutData;
750
+ Object.assign(inputs, dataOverride(own, base), flowOverride(a.layoutData, b.layoutData));
751
+ }
752
+ else
753
+ Object.assign(inputs, dataOverride(a.layoutData, b.layoutData));
754
+ if (a.keepSize !== b.keepSize)
755
+ inputs.keepSize = a.keepSize;
756
+ if (a.storedHeight !== b.storedHeight || a.storedRow !== b.storedRow) {
521
757
  Object.assign(inputs, { storedHeight: a.storedHeight, storedRow: a.storedRow });
758
+ }
522
759
  }
523
760
  // The box the expansion has where it differs from the main's, kept (keep) where core's layout of the instance does
524
761
  // not give it.
525
- geometry.set(n.path, { E, R, box: { ...(d && 't' in d && { t: d.t }), ...(d && 'w' in d && { w: d.w, h: d.h }), at: size } });
762
+ geometry.set(n.path, { E, R, fillPath, box: { ...(d && 't' in d && { t: d.t }), ...(d && 'w' in d && { w: d.w, h: d.h }), at: size } });
526
763
  if (d || Object.keys(inputs).length)
527
764
  out[n.path] = { ...out[n.path], ...d, ...inputs };
528
765
  if (E.fileSlotHost && fills?.includes(E.fileSlotHost))
529
766
  continue;
530
- const r = match(kidsOf(id), children, out, size, geometry, fills);
767
+ const r = match(kidsOf(id), children, out, size, geometry, linkPaths, fills, n.instance ? undefined : bound);
531
768
  if (r)
532
769
  return r;
533
770
  }
@@ -565,11 +802,18 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
565
802
  I.overrides[path] = { ...I.overrides[path], storedBox: g.box };
566
803
  added = true;
567
804
  }
568
- if (!added)
805
+ if (!added) {
806
+ for (const [path, { E, R, fillPath }] of geometry) {
807
+ // The direct resize and a resize through the main may differ by roundoff.
808
+ if (fillPath && !same(E.net, laid.get(path)?.net ?? R.net, 1e-6))
809
+ return 'net';
810
+ }
569
811
  return;
812
+ }
570
813
  }
571
814
  }
572
- const state = new Map(), reasons = new Map();
815
+ // Per instance left expanded (by its id in the output): its first difference from its main.
816
+ const state = new Map(), reasons = new Map(), expandedReasons = new Map();
573
817
  let linked = 0;
574
818
  const ensure = (main) => { if (state.has(main))
575
819
  return; state.set(main, 'busy'); for (const c of [...kidsOf(main)])
@@ -589,15 +833,31 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
589
833
  const root = difference(E, M, false, !!E.fileInstance);
590
834
  if (typeof root === 'string')
591
835
  return `root ${root}`;
592
- if (!same(contentInputs(E), contentInputs(M)))
593
- return 'root layout';
594
836
  const overrides = {}, geometry = new Map();
595
- if (root)
596
- overrides[''] = root;
597
- const r = match(kidsOf(id), tree(main), overrides, { width: E.w, height: E.h }, geometry, E.fileFills);
837
+ const content = flowOverride(E.layoutData, M.layoutData, fillsIn(E, byId.get(E.parent)));
838
+ if (!supportsFrameOverrides && content['layoutData.flow'])
839
+ return 'root layout';
840
+ if (root || Object.keys(content).length)
841
+ overrides[''] = { ...root, ...content };
842
+ const linkPaths = nativeFile ? new Set() : undefined;
843
+ const r = match(kidsOf(id), tree(main), overrides, { width: E.w, height: E.h }, geometry, linkPaths, E.fileFills);
598
844
  if (r)
599
845
  return r;
600
846
  const data = instanceData(E, byId.get(E.parent));
847
+ const flow = content['layoutData.flow'];
848
+ for (const axis of ['width', 'height'])
849
+ if (flow?.[axis + 'Sizing'] && flow[axis + 'Sizing'] !== 'fill') {
850
+ if (data.sizing) {
851
+ delete data.sizing[axis];
852
+ if (!Object.keys(data.sizing).length)
853
+ delete data.sizing;
854
+ }
855
+ if (data.heldHug) {
856
+ data.heldHug = data.heldHug.filter((held) => held !== axis);
857
+ if (!data.heldHug.length)
858
+ delete data.heldHug;
859
+ }
860
+ }
601
861
  const I = { id, kind: 'frame', parent: E.parent, ...(E.sourceId !== undefined && { sourceId: E.sourceId }), name: E.name, t: E.t, opacity: E.opacity ?? 1, w: E.w, h: E.h, component: main };
602
862
  if (E.fileInstance)
603
863
  I.fileInstance = E.fileInstance;
@@ -607,7 +867,9 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
607
867
  if (Object.keys(data).length)
608
868
  I.layoutData = data;
609
869
  I.overrides = overrides;
610
- keep(I, geometry);
870
+ const mismatch = keep(I, geometry);
871
+ if (mismatch)
872
+ return mismatch;
611
873
  if (!Object.keys(overrides).length)
612
874
  delete I.overrides;
613
875
  if (aliases)
@@ -616,6 +878,8 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
616
878
  byId.set(id, I);
617
879
  kids.delete(id);
618
880
  views.delete(id);
881
+ if (linkPaths?.size)
882
+ omittedLinks.set(id, linkPaths);
619
883
  linked++;
620
884
  return null;
621
885
  }
@@ -628,6 +892,7 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
628
892
  if (!r)
629
893
  return;
630
894
  reasons.set(r, (reasons.get(r) ?? 0) + 1);
895
+ expandedReasons.set(id, r);
631
896
  }
632
897
  for (const c of [...kidsOf(id)])
633
898
  walk(c);
@@ -643,28 +908,29 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
643
908
  visit(m.component);
644
909
  } for (const c of kidsOf(id))
645
910
  visit(c); };
646
- for (const c of kidsOf(''))
647
- visit(c);
911
+ if (hidden.size)
912
+ for (const c of kidsOf(''))
913
+ visit(c);
648
914
  // Used once: a component (all its variants together) one instance uses; a variant used once of a component used
649
915
  // more keeps its main, so that every instance of a set is an instance of its own variant (the panel's variants).
650
916
  const uses = new Map();
651
917
  for (const [id, vk] of hidden)
652
918
  uses.set(componentOf(vk), (uses.get(componentOf(vk)) ?? 0) + (used.get(id) ?? 0));
653
919
  const once = [...hidden].filter(([id, vk]) => used.get(id) === 1 && uses.get(componentOf(vk)) === 1).map(([, vk]) => vk);
654
- for (const id of hidden.keys())
655
- if (!used.has(id))
656
- kids.set('@components', kidsOf('@components').filter((c) => c !== id));
920
+ if (hidden.size)
921
+ kids.set('@components', kidsOf('@components').filter((id) => !hidden.has(id) || used.has(id)));
657
922
  for (const id of mains.values()) {
658
923
  const m = byId.get(id);
659
924
  if (m && (!hidden.has(id) || used.has(id)))
660
- m.component = id;
925
+ byId.set(id, { ...m, component: id });
661
926
  }
662
927
  // What each component stores: its used hidden mains, its instances with their override keys, its expansions left.
663
928
  const cost = new Map(), add = (c, n, k = 0) => { const v = cost.get(c) ?? [0, 0]; cost.set(c, [v[0] + n, v[1] + k]); };
664
929
  const keysOf = (I) => Object.values(I.overrides ?? {}).reduce((n, r) => n + Object.keys(r).length, 0);
665
- for (const [id, vk] of hidden)
666
- if (used.has(id))
667
- add(componentOf(vk), size(id));
930
+ if (compareCosts)
931
+ for (const [id, vk] of hidden)
932
+ if (used.has(id))
933
+ add(componentOf(vk), size(id));
668
934
  const tally = (id) => {
669
935
  const m = byId.get(id);
670
936
  if (isInstance(m) && hidden.has(m.component))
@@ -674,15 +940,16 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
674
940
  for (const c of kidsOf(id))
675
941
  tally(c);
676
942
  };
677
- for (const c of kidsOf(''))
678
- tally(c);
943
+ if (compareCosts)
944
+ for (const c of kidsOf(''))
945
+ tally(c);
679
946
  const models = [];
680
- const emit = (id) => { const m = byId.get(id); unmark(m); delete m.fileSlotHost; delete m.fileFills; models.push(m); for (const c of kidsOf(id))
947
+ const emit = (id) => { const m = { ...byId.get(id) }; unmark(m); delete m.fileSlotHost; delete m.fileFills; models.push(m); for (const c of kidsOf(id))
681
948
  emit(c); };
682
949
  for (const c of kidsOf(''))
683
950
  emit(c);
684
951
  for (const c of kidsOf('@components'))
685
952
  emit(c);
686
953
  doc.models = models;
687
- return { cost, before, after: models.length, linked, mains: mains.size - hidden.size, hidden: [...hidden.keys()].filter((id) => used.has(id)).length, unlinked: reasons, once };
954
+ return { omittedLinks, expandedReasons, cost, before, after: models.length, linked, mains: mains.size - hidden.size, hidden: [...hidden.keys()].filter((id) => used.has(id)).length, unlinked: reasons, once };
688
955
  }