@moondraft/import 0.1.0 → 0.2.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 (84) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +2 -2
  3. package/SOURCE.md +229 -4
  4. package/dist/adapter/convert.d.ts +24 -2
  5. package/dist/adapter/convert.js +669 -160
  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 +12 -0
  11. package/dist/adapter/figma-handoff.js +167 -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 +14 -4
  16. package/dist/adapter/file-components.d.ts +9 -3
  17. package/dist/adapter/file-components.js +122 -32
  18. package/dist/adapter/file-resources.js +316 -27
  19. package/dist/adapter/image-crop.d.ts +18 -0
  20. package/dist/adapter/image-crop.js +30 -0
  21. package/dist/adapter/link.d.ts +5 -1
  22. package/dist/adapter/link.js +308 -104
  23. package/dist/adapter/payload.js +1 -1
  24. package/dist/adapter/variables.d.ts +2 -1
  25. package/dist/adapter/variables.js +5 -2
  26. package/dist/figma.js +167 -33
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.js +1 -0
  29. package/dist/report.d.ts +28 -1
  30. package/dist/report.js +102 -29
  31. package/dist/serialize.d.ts +7 -0
  32. package/dist/serialize.js +79 -0
  33. package/dist/taco/figma-import/container/kiwiContainer.d.ts +3 -0
  34. package/dist/taco/figma-import/container/kiwiContainer.js +1 -1
  35. package/dist/taco/figma-import/import/carry.d.ts +14 -1
  36. package/dist/taco/figma-import/import/carry.js +34 -1
  37. package/dist/taco/figma-import/import/componentProps.d.ts +10 -4
  38. package/dist/taco/figma-import/import/componentProps.js +29 -13
  39. package/dist/taco/figma-import/import/componentSets.d.ts +2 -0
  40. package/dist/taco/figma-import/import/componentSets.js +1 -1
  41. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  42. package/dist/taco/figma-import/import/converters/exportSettings.js +49 -0
  43. package/dist/taco/figma-import/import/converters/frame.js +8 -0
  44. package/dist/taco/figma-import/import/converters/gradient.d.ts +2 -0
  45. package/dist/taco/figma-import/import/converters/gradient.js +3 -1
  46. package/dist/taco/figma-import/import/converters/group.d.ts +2 -4
  47. package/dist/taco/figma-import/import/converters/group.js +6 -15
  48. package/dist/taco/figma-import/import/converters/image.d.ts +1 -1
  49. package/dist/taco/figma-import/import/converters/image.js +22 -11
  50. package/dist/taco/figma-import/import/converters/layout.d.ts +3 -4
  51. package/dist/taco/figma-import/import/converters/layout.js +40 -21
  52. package/dist/taco/figma-import/import/converters/rectangle.d.ts +1 -1
  53. package/dist/taco/figma-import/import/converters/rectangle.js +1 -1
  54. package/dist/taco/figma-import/import/converters/section.d.ts +2 -3
  55. package/dist/taco/figma-import/import/converters/section.js +3 -9
  56. package/dist/taco/figma-import/import/converters/shared.d.ts +7 -4
  57. package/dist/taco/figma-import/import/converters/shared.js +15 -5
  58. package/dist/taco/figma-import/import/converters/text.d.ts +14 -1
  59. package/dist/taco/figma-import/import/converters/text.js +143 -12
  60. package/dist/taco/figma-import/import/converters/vector.d.ts +36 -15
  61. package/dist/taco/figma-import/import/converters/vector.js +214 -73
  62. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +19 -3
  63. package/dist/taco/figma-import/import/converters/vectorNetwork.js +147 -29
  64. package/dist/taco/figma-import/import/instances.d.ts +25 -4
  65. package/dist/taco/figma-import/import/instances.js +324 -117
  66. package/dist/taco/figma-import/import/styles.d.ts +2 -0
  67. package/dist/taco/figma-import/import/styles.js +6 -0
  68. package/dist/taco/figma-import/import/variables.d.ts +3 -2
  69. package/dist/taco/figma-import/import/variables.js +37 -30
  70. package/dist/taco/figma-import/import/variantTrees.d.ts +1 -1
  71. package/dist/taco/figma-import/import/variantTrees.js +44 -4
  72. package/dist/taco/figma-import/import/walk.d.ts +53 -5
  73. package/dist/taco/figma-import/import/walk.js +273 -106
  74. package/dist/taco/figma-import/kiwi/message.d.ts +4 -2
  75. package/dist/taco/figma-import/kiwi/message.js +13 -11
  76. package/dist/taco/model/codec.d.ts +1 -1
  77. package/dist/taco/model/codec.js +37 -7
  78. package/dist/taco/model/component-evaluation.d.ts +2 -0
  79. package/dist/taco/model/component-evaluation.js +7 -0
  80. package/dist/taco/model/instance-resolver.d.ts +6 -2
  81. package/dist/taco/model/instance-resolver.js +48 -18
  82. package/dist/taco/model/sha256.js +13 -8
  83. package/dist/taco/model/types.d.ts +23 -1
  84. package/package.json +3 -2
@@ -6,7 +6,7 @@
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
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
10
  // fills) stays expanded, and so do the instances inside it, which are linked on their own when they can be. A stroke's
11
11
  // other colour is a paint override (the renderer draws a stroke's paint in place of its compact colour).
12
12
  // - A component whose root is on the page has it as its main. Any other gets a hidden main under '@components' (core's
@@ -30,6 +30,7 @@
30
30
  // 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
31
  // reaches well past it, stays expanded); its text body field carries the text's box (see difference).
32
32
  // The markers are removed whether or not anything is linked.
33
+ import { Properties, TextStyleSchema } from '@moondraft/editor/schema';
33
34
  import { instanceLayout, legacyAuto, netBounds, sizingOf } from '@moondraft/editor/core';
34
35
  /** The converter's markers on the expanded models (instanceOf, mainOf, and setOf: an instance's variant set name). */
35
36
  export const MARKERS = ['instanceOf', 'mainOf', 'setOf', 'variant'];
@@ -46,18 +47,20 @@ const IGNORED = new Set(['id', 'parent', 'children', 'z', 'order', 'sourceId', '
46
47
  'layoutData', 'keepSize', 'remeasured', 'storedHeight', 'storedRow', 'storedBox', 'boxScale', 'locked', 'runs', 'styleAt', 'fill', 'look']);
47
48
  /** An instance's own record (SPEC 19.2): the rest of an instance's appearance is its main root's. */
48
49
  const OWN = new Set(['t', 'w', 'h', 'opacity', 'visible', 'blend', 'mask', 'exports']);
49
- const same = (a, b) => {
50
+ const same = (a, b, tolerance = 0) => {
50
51
  if (a === b)
51
52
  return true;
53
+ if (tolerance && typeof a === 'number' && typeof b === 'number')
54
+ return Math.abs(a - b) < tolerance;
52
55
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null || Array.isArray(a) !== Array.isArray(b))
53
56
  return false;
54
57
  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]));
58
+ return ka.length === kb.length && ka.every((k) => same(a[k], b[k], tolerance));
56
59
  };
57
60
  /** What a layer fills with: its look's fills, else its compact fill as one solid paint (the renderer draws both so). */
58
61
  const fillsOf = (m) => m.look?.fills ?? (m.fill ? [{ k: 'solid', c: m.fill }] : []);
59
62
  /** A text's style index per UTF-16 unit, from styleAt or the file's runs ([length, style]). */
60
- function styleAtOf(m) {
63
+ export function styleAtOf(m) {
61
64
  if (m.styleAt)
62
65
  return m.styleAt;
63
66
  const at = [];
@@ -70,6 +73,39 @@ function styleAtOf(m) {
70
73
  }
71
74
  return at;
72
75
  }
76
+ // The editor peer must resolve a run's paint before an instance can inherit its main's colour source.
77
+ export const supportsRunPaint = 'fillStyle' in TextStyleSchema.properties;
78
+ const supportsFrameOverrides = 'layoutData.flow' in Properties;
79
+ const linkedTextColor = (style) => style.fileFillStyle ? supportsRunPaint : !!style.fileTextColor;
80
+ /** Can this occurrence inherit the main's fitted runs, including their colour sources? */
81
+ function inheritsTextRuns(occurrence, main, runs, mainRuns, nativeFile) {
82
+ const bound = occurrence.styles.some(linkedTextColor);
83
+ // A link alone cannot own a native instance palette. Wording with its own unbound formatting can.
84
+ if (!bound && !(nativeFile && occurrence.content === main.content &&
85
+ [...occurrence.styles, ...main.styles].some(style => style.link || style.figmaHyperlink)))
86
+ return false;
87
+ let differentLink = false;
88
+ const matched = new Map();
89
+ const last = Math.min(main.content.length, mainRuns.length) - 1;
90
+ // An empty text still has an insertion style in slot zero.
91
+ for (let i = 0; i < Math.max(1, runs.length); i++) {
92
+ const slot = runs[i] ?? 0, from = runs.length ? mainRuns[Math.min(i, last)] ?? 0 : 0;
93
+ if (matched.get(slot) === from)
94
+ continue;
95
+ const style = occurrence.styles[slot], inherited = main.styles[from];
96
+ // A shared variable can draw a different literal in the occurrence's mode.
97
+ if (!inherited)
98
+ return false;
99
+ const fitted = linkedTextColor(style) ? { ...style, color: inherited.color } : style;
100
+ if (!same(fitted, inherited)) {
101
+ if (!nativeFile || !same({ ...fitted, link: inherited.link, figmaHyperlink: inherited.figmaHyperlink }, inherited))
102
+ return false;
103
+ differentLink = true;
104
+ }
105
+ matched.set(slot, from);
106
+ }
107
+ return differentLink ? 'link-only' : bound;
108
+ }
73
109
  /** One override record applied to a copy of a record, as core applies it (components.ts applyOverride: a stored box is
74
110
  * the instance's layout's alone). */
75
111
  function applied(record, over) {
@@ -77,6 +113,11 @@ function applied(record, over) {
77
113
  for (const [key, value] of Object.entries(over)) {
78
114
  if (key === 'storedBox')
79
115
  continue;
116
+ if (key === 'layoutData.flow') {
117
+ const flow = value, data = out.layoutData;
118
+ out.layoutData = { ...data, layout: { ...data?.layout, ...flow }, padding: { ...data?.layout?.padding, ...data?.padding, ...flow.padding } };
119
+ continue;
120
+ }
80
121
  if (!key.includes('.')) {
81
122
  out[key] = value;
82
123
  continue;
@@ -98,7 +139,7 @@ function applied(record, over) {
98
139
  }
99
140
  /** The keys of a record that differ from another's as one override (null: none), or the key that takes no override
100
141
  * (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) {
142
+ function difference(E, R, own, rootOverride = false, omitLink) {
102
143
  const rec = {};
103
144
  for (const k of new Set([...Object.keys(E), ...Object.keys(R)])) {
104
145
  if (IGNORED.has(k) || same(E[k], R[k]))
@@ -114,27 +155,51 @@ function difference(E, R, own, rootOverride = false) {
114
155
  rec.w = E.w;
115
156
  rec.h = E.h;
116
157
  }
158
+ // Layout owns a stretched path's network override. keep() checks it against the
159
+ // main laid out with all sibling overrides and stored boxes before accepting the link.
160
+ else if (k === 'net' && E.kind === 'path' && own)
161
+ rec.net = E.net;
162
+ else if (k === 'clip') {
163
+ if (!!E.clip !== !!R.clip) {
164
+ if (!supportsFrameOverrides)
165
+ return 'clip';
166
+ rec.clip = !!E.clip;
167
+ }
168
+ }
117
169
  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;
170
+ if (!same(E[k] ?? 0, R[k] ?? 0)) {
171
+ rec[k] = E[k] ?? 0;
172
+ // Older peers encode both values in the corners field.
173
+ if (!supportsFrameOverrides)
174
+ Object.assign(rec, { radius: E.radius ?? 0, smoothing: E.smoothing ?? 0 });
121
175
  }
122
176
  }
123
177
  else if (k === 'content' || k === 'styles' || k === 'para')
124
178
  continue; // the text body, below
179
+ // An instance cannot override a text's line limit or ellipsis, so a linked instance shows its main's rather than
180
+ // losing its link over them.
181
+ else if (k === 'maxLines' || k === 'truncate')
182
+ continue;
125
183
  else if ((k === 'stroke' || k === 'strokeWidth') && E.kind !== 'text')
126
184
  continue; // the stroke, below
127
185
  else
128
186
  return k;
129
187
  }
130
188
  if (E.kind === 'text') {
131
- const body = (m) => [m.content, m.styles, styleAtOf(m), m.para ?? []];
132
- const [a, b] = [body(E), body(R)];
189
+ const runs = styleAtOf(E), mainRuns = styleAtOf(R), para = E.para ?? [];
133
190
  // The renderer's text body field carries the text's box, taken from the main's layer with this record applied
134
191
  // (wire.ts overrideBase), and replaces an inner instance's whole body, box included: a text's size and body go
135
192
  // 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 });
193
+ const inheritsPalette = inheritsTextRuns(E, R, runs, mainRuns, omitLink !== undefined);
194
+ if (inheritsPalette === 'link-only')
195
+ omitLink?.();
196
+ if (E.content !== R.content || rec.w !== undefined || !same(para, R.para ?? [])
197
+ || (!inheritsPalette && (!same(E.styles, R.styles) || !same(runs, mainRuns)))) {
198
+ Object.assign(rec, { content: E.content, para, w: E.w, h: E.h });
199
+ // A plain body owns its palette and indices together. A character-only override can inherit both.
200
+ if (!inheritsPalette)
201
+ Object.assign(rec, { styles: E.styles, styleAt: runs });
202
+ }
138
203
  }
139
204
  if (E.kind !== 'text') {
140
205
  if (!same(fillsOf(E), fillsOf(R))) {
@@ -142,13 +207,18 @@ function difference(E, R, own, rootOverride = false) {
142
207
  return 'fills';
143
208
  rec['look.fills'] = fillsOf(E);
144
209
  }
145
- if (!same(E.strokeWidth, R.strokeWidth))
146
- return 'strokeWidth';
147
210
  if (!same(E.stroke, R.stroke) && (!E.stroke || !R.stroke))
148
211
  return 'stroke';
149
- const { paint: pe, ...se } = E.look?.stroke ?? {}, { paint: pr, ...sr } = R.look?.stroke ?? {};
212
+ const { paint: pe, sides: es, ...se } = E.look?.stroke ?? {}, { paint: pr, sides: rs, ...sr } = R.look?.stroke ?? {};
150
213
  if (!same(se, sr) || !!E.look?.stroke !== !!R.look?.stroke)
151
214
  return 'look.stroke';
215
+ if ((es || rs) && E.stroke && R.stroke) {
216
+ const sides = es ?? Array(4).fill(E.strokeWidth);
217
+ if (!same(sides, rs ?? Array(4).fill(R.strokeWidth)))
218
+ rec['look.stroke.sides'] = sides;
219
+ }
220
+ else if (!same(E.strokeWidth, R.strokeWidth))
221
+ return 'strokeWidth';
152
222
  // What a drawn stroke paints with: its look's paint, else its compact colour as one solid paint (the renderer
153
223
  // draws a paint in place of the compact colour), so an expansion's other colour is a paint override.
154
224
  const strokePaint = (m, p) => p ?? (m.stroke ? { k: 'solid', c: m.stroke } : undefined);
@@ -169,8 +239,11 @@ function difference(E, R, own, rootOverride = false) {
169
239
  if (!['fills', 'stroke', 'shadows', 'layerBlur', 'backgroundBlur'].includes(k) && !same(E.look?.[k], R.look?.[k]))
170
240
  return `look.${k}`;
171
241
  }
172
- if (!own && !rootOverride && Object.keys(rec).length)
173
- return Object.keys(rec)[0];
242
+ if (!own && !rootOverride) {
243
+ const unsupported = Object.keys(rec).find(k => k !== 'clip' && k !== 'smoothing');
244
+ if (unsupported)
245
+ return unsupported;
246
+ }
174
247
  return Object.keys(rec).length ? rec : null;
175
248
  }
176
249
  // Core lays an instance out again (a resize of it, an edit of its main, an override that hides a layer or changes a
@@ -206,13 +279,33 @@ function withData(data, over) {
206
279
  out = { ...out, [k.slice(11)]: v };
207
280
  return out;
208
281
  }
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];
282
+ /** The content settings this frame changes relative to its component, including individual padding sides. */
283
+ function flowOverride(own = {}, main = {}) {
284
+ const a = own.layout ?? {}, b = main.layout ?? {};
285
+ const flow = {};
286
+ const defaults = { kind: 'absolute', gap: 0, align: 'start', justify: 'start', wrap: false,
287
+ wrapGap: a.gap ?? 0, alignContent: 'auto', widthSizing: 'fixed', heightSizing: 'fixed', strokesIncluded: false };
288
+ for (const [key, fallback] of Object.entries(defaults)) {
289
+ if (!same(a[key] ?? fallback, b[key] ?? fallback))
290
+ flow[key] = a[key] ?? fallback;
291
+ }
292
+ // Hug/Fixed can be carried in sizing even when the stack itself is identical.
293
+ if (a.kind && a.kind !== 'absolute')
294
+ for (const axis of ['width', 'height']) {
295
+ const local = sizingOf(own, axis), inherited = sizingOf(main, axis);
296
+ if (local !== inherited)
297
+ flow[axis + 'Sizing'] = local;
298
+ }
299
+ const pad = { ...a.padding, ...own.padding }, base = { ...b.padding, ...main.padding };
300
+ const sides = Object.fromEntries(['top', 'right', 'bottom', 'left'].filter(k => (pad[k] ?? 0) !== (base[k] ?? 0)).map(k => [k, pad[k] ?? 0]));
301
+ if (Object.keys(sides).length)
302
+ flow.padding = sides;
303
+ return Object.keys(flow).length ? { 'layoutData.flow': flow } : {};
304
+ }
212
305
  /** of an instance in its parent (P), its own layoutData as linking gives it: no auto layout (its main's), and a size
213
306
  * that hugs held ('fixed': it has no children to hug), so a parent that hugs it lays out as it did. */
214
307
  function instanceData(E, P) {
215
- const { layout: _layout, box: _box, ...data } = E.layoutData ?? {};
308
+ const { layout: _layout, padding: _padding, box: _box, ...data } = E.layoutData ?? {};
216
309
  const fixed = (o) => o && Object.fromEntries(Object.entries(o).map(([k, v]) => [k, v === 'hug' ? 'fixed' : v]));
217
310
  // The axes it hugged are recorded (heldHug), so that a swap in the editor hugs them again.
218
311
  const held = ['width', 'height'].filter((a) => data.sizing?.[a] === 'hug' || data.resizing?.[a] === 'hug');
@@ -255,7 +348,7 @@ export function linkComponents(doc) {
255
348
  return linkWithLayers(doc, false).counts;
256
349
  }
257
350
  /** @internal Links components and tracks where their expanded layers went for import reports. */
258
- export function linkWithLayers(doc, trackLayers = true) {
351
+ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile = false) {
259
352
  // Variant sets (convert.ts markSet): one hidden main per variant used, so each instance's main is its own variant
260
353
  // and its overrides are its own changes alone; but a showcase of a set (each variant once or twice) costs a main per
261
354
  // 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 +357,43 @@ export function linkWithLayers(doc, trackLayers = true) {
264
357
  // grew the models 13%, 3 grows them 4% (39583 to 41158) and still cuts the override keys by 23%; 6 kept the models
265
358
  // level but cut the keys by 19% only. The used-once rule stays per component: a variant's main used once is kept
266
359
  // 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) => {
360
+ const sets = new Set(), placed = new Set();
361
+ for (const model of doc.models) {
362
+ if (model.setOf && model.variant)
363
+ sets.add(model.instanceOf);
364
+ if (model.mainOf !== undefined && model.kind === 'frame')
365
+ placed.add(model.mainOf);
366
+ }
367
+ const run = (each, compareCosts, report = false) => {
269
368
  const skip = new Set();
270
369
  for (;;) {
271
- const d = { models: structuredClone(doc.models) }, aliases = new Map();
272
- const { once, ...r } = linkOnce(d, skip, each, report ? aliases : undefined);
370
+ const d = { models: doc.models }, aliases = new Map();
371
+ const { once, omittedLinks, ...r } = linkOnce(d, skip, each, compareCosts, report ? aliases : undefined, swapBinding, nativeFile);
273
372
  if (!once.length)
274
- return { d, r, aliases };
373
+ return { d, r, aliases, omittedLinks };
275
374
  for (const comp of once)
276
375
  skip.add(comp);
277
376
  }
278
377
  };
279
378
  let chosen = new Set();
280
- if (sets.size) {
281
- const shared = run(new Set()).r.cost, split = run(sets).r.cost;
379
+ // A placed main wins in both trials. With all sets placed the costs tie.
380
+ if ([...sets].every(set => placed.has(set)))
381
+ chosen = sets;
382
+ else {
383
+ const shared = run(new Set(), true).r.cost, split = run(sets, true).r.cost;
282
384
  const W = 3, of = (m, c) => { const [n, k] = m.get(c) ?? [0, 0]; return n * W + k; };
283
385
  chosen = new Set([...sets].filter((c) => of(split, c) <= of(shared, c)));
284
386
  }
285
- const { d, r: { cost: _cost, ...r }, aliases } = run(chosen, trackLayers);
286
- doc.models = d.models;
387
+ const { d, r: { cost: _cost, ...r }, aliases, omittedLinks } = run(chosen, false, trackLayers);
388
+ // Detach only the linked output. Trial passes and discarded expansions never need deep copies.
389
+ doc.models = nativeFile ? d.models : structuredClone(d.models);
287
390
  const counts = { ...r, variantSets: chosen.size, sharedSets: sets.size - chosen.size };
288
- return { counts, aliases };
391
+ return { counts, aliases, omittedLinks };
289
392
  }
290
393
  /** linkComponents with no hidden main for the components in `skip`; also returns the components whose hidden main is
291
394
  * used once (once). */
292
- function linkOnce(doc, skip, each = new Set(), aliases) {
395
+ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFile = false) {
396
+ const omittedLinks = new Map();
293
397
  const recordAlias = (from, to) => {
294
398
  if (!aliases)
295
399
  return;
@@ -300,18 +404,15 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
300
404
  };
301
405
  // The hidden main an expanded instance takes: its component's, or its variant's for a set in `each`.
302
406
  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;
407
+ // Each trial replaces records in its own index. Input records and their nested values stay read-only.
408
+ const byId = new Map(), kids = new Map();
313
409
  const mains = new Map(), instances = new Map();
314
410
  for (const m of doc.models) {
411
+ byId.set(m.id, m);
412
+ const parent = m.parent ?? '';
413
+ if (!kids.has(parent))
414
+ kids.set(parent, []);
415
+ kids.get(parent).push(m.id);
315
416
  if (m.mainOf !== undefined && !mains.has(m.mainOf) && m.kind === 'frame')
316
417
  mains.set(m.mainOf, m.id);
317
418
  if (m.instanceOf !== undefined) {
@@ -321,6 +422,9 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
321
422
  instances.get(k).push(m.id);
322
423
  }
323
424
  }
425
+ const kidsOf = (id) => kids.get(id) ?? [];
426
+ const size = (id) => 1 + kidsOf(id).reduce((n, c) => n + size(c), 0);
427
+ const before = doc.models.length;
324
428
  // Whether the layers under a frame draw outside its box, with their drop shadows and layer blurs where they reach
325
429
  // further than SLACK, as the renderer reaches them (the offset plus 1.5 blur and the spread; crates/scn-core
326
430
  // derived.rs effect_reach, with the spread shadow_spread draws: below 0 only on a frame with square corners);
@@ -380,18 +484,29 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
380
484
  // and the expansion adds nothing (it stays expanded), so the main holds no layer twice.
381
485
  function plan(e, u) {
382
486
  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
487
  const list = [], added = new Map();
388
488
  let i = 0, j = 0;
489
+ while (i < n && j < m && K(ek[i]) === K(uk[j])) {
490
+ list.push(uk[j++]);
491
+ i++;
492
+ }
493
+ // The common prefix is already paired. Only allocate an LCS table for an ambiguous suffix.
494
+ const start = i, L = [];
495
+ if (i < n && j < m) {
496
+ for (let x = i; x <= n; x++)
497
+ L[x - start] = new Int32Array(m - start + 1);
498
+ for (let x = n - 1; x >= i; x--)
499
+ for (let y = m - 1; y >= j; y--) {
500
+ const row = L[x - start], below = L[x - start + 1], col = y - start;
501
+ row[col] = K(ek[x]) === K(uk[y]) ? below[col + 1] + 1 : Math.max(below[col], row[col + 1]);
502
+ }
503
+ }
389
504
  while (i < n) {
390
505
  if (j < m && K(ek[i]) === K(uk[j])) {
391
506
  list.push(uk[j++]);
392
507
  i++;
393
508
  }
394
- else if (j >= m || L[i + 1][j] >= L[i][j + 1]) {
509
+ else if (j >= m || L[i - start + 1][j - start] >= L[i - start][j - start + 1]) {
395
510
  const k = K(ek[i]);
396
511
  added.set(k, (added.get(k) ?? 0) + 1);
397
512
  list.push({ copy: ek[i++] });
@@ -399,16 +514,30 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
399
514
  else
400
515
  list.push(uk[j++]);
401
516
  }
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;
517
+ while (j < m)
518
+ list.push(uk[j++]);
519
+ if (added.size) {
520
+ const remaining = new Map();
521
+ for (const id of ek) {
522
+ const k = K(id);
523
+ remaining.set(k, (remaining.get(k) ?? 0) + 1);
524
+ }
525
+ for (const id of uk) {
526
+ const k = K(id);
527
+ remaining.set(k, (remaining.get(k) ?? 0) - 1);
528
+ }
529
+ for (const [k, count] of added)
530
+ if (count > remaining.get(k))
531
+ return null;
532
+ }
407
533
  const subs = [];
408
534
  let last = -1;
409
535
  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];
536
+ const k = K(c);
537
+ let x;
538
+ do {
539
+ x = list[++last];
540
+ } while (K(typeof x === 'string' ? x : x.copy) !== k);
412
541
  if (typeof x !== 'string')
413
542
  continue;
414
543
  const sub = plan(c, x);
@@ -457,77 +586,124 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
457
586
  const isInstance = (m) => m?.kind === 'frame' && m.component !== undefined && m.component !== m.id;
458
587
  // A main's effective tree: per layer, its path (from the main's child down), what it shows and its children.
459
588
  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]) });
589
+ function swappedNode(n, main) {
590
+ ensure(main);
591
+ return { ...n, main, rec: n.recordOf(main), kids: n.childrenOf(main) };
592
+ }
593
+ function reroot(n, prefix, overrides) {
594
+ const over = overrides?.[n.path];
595
+ if (n.instance && over?.component && over.component !== n.main)
596
+ n = swappedNode(n, over.component);
597
+ // Keep each holder's overrides in scope when a later placement chooses another main.
598
+ const underHolder = (child) => reroot(child, prefix, overrides);
599
+ return { ...n, path: `${prefix};${n.path}`, rec: over ? applied(n.rec, over) : n.rec,
600
+ ...(n.instance && over && { recordOf: (main) => applied(n.recordOf(main), over) }),
601
+ ...(n.instance && { childrenOf: (main) => n.childrenOf(main).map(underHolder) }),
602
+ kids: n.kids.map(underHolder), data: withData(n.data, over) };
603
+ }
461
604
  function tree(main) {
462
605
  if (trees.has(main))
463
606
  return trees.get(main);
464
- const build = (id, path) => {
607
+ const build = (id, path, inDefinition = true) => {
465
608
  const m = byId.get(id);
466
609
  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)) };
610
+ return { path, rec: m, kids: kidsOf(id).map((c) => build(c, `${path};${c}`, inDefinition && !m.fileInstance)) };
611
+ const own = Object.fromEntries(Object.entries(m).filter(([key]) => OWN.has(key) || key === 'fileInstance'));
612
+ const recordOf = (main) => {
613
+ const root = Object.fromEntries(Object.entries(byId.get(main)).filter(([key]) => !OWN.has(key)));
614
+ const rec = { ...root, ...own };
615
+ return m.overrides?.[''] ? applied(rec, m.overrides['']) : rec;
616
+ };
617
+ const childrenOf = (main) => tree(main).map((child) => reroot(child, path, m.overrides));
618
+ const binding = inDefinition && m.fileInstance && swapBinding?.(m.fileInstance);
619
+ return { path, binding, rec: recordOf(m.component), main: m.component, recordOf, instance: true, data: m.layoutData ?? {}, childrenOf, kids: childrenOf(m.component) };
470
620
  };
471
621
  const t = kidsOf(main).map((c) => build(c, c));
472
622
  trees.set(main, t);
473
623
  return t;
474
624
  }
625
+ // A group's fill allocation can resize a descendant path through scale constraints.
626
+ function fillsPath(path) {
627
+ for (let m = path; m; m = byId.get(m.parent)) {
628
+ if ((m === path || m.group) && (sizingOf(m.layoutData, 'width') === 'fill' || sizingOf(m.layoutData, 'height') === 'fill'))
629
+ return true;
630
+ }
631
+ return false;
632
+ }
475
633
  // Fills `out` with the overrides that make main-tree node list `mk` show concrete children `ek`, inside an instance
476
634
  // expanded at `size`, and `geometry` with each matched layer's expanded record, its main's and the box to store if
477
635
  // 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;
636
+ function match(ek, mk, out, size, geometry, linkPaths, fills, bound = new Map()) {
637
+ const used = new Set();
638
+ let next = 0;
483
639
  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];
640
+ const E = byId.get(id), k = key(E);
641
+ while (next < mk.length && key(mk[next].rec) !== k)
642
+ next++;
643
+ if (next === mk.length)
644
+ return mk.some((n) => key(n.rec) === k) ? 'layer order' : 'a layer the main lacks';
645
+ used.add(next);
646
+ const n = mk[next++];
490
647
  let R = n.rec, children = n.kids;
491
648
  const swap = E.fileInstance && n.instance && mains.get(E.instanceOf);
649
+ if (n.binding && swap) {
650
+ // A property on one occurrence selects the same main for every layer bound to it.
651
+ if (bound.has(n.binding) && bound.get(n.binding) !== swap)
652
+ return 'conflicting bound swaps';
653
+ bound.set(n.binding, swap);
654
+ }
492
655
  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));
656
+ const swapped = swappedNode(n, swap);
657
+ R = swapped.rec;
658
+ children = swapped.kids;
497
659
  out[n.path] = { component: swap };
498
660
  }
499
661
  if (E.kind !== R.kind)
500
662
  return 'kind';
501
663
  // 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);
664
+ const d = difference(E, R, true, false, linkPaths && (() => linkPaths.add(n.path)));
503
665
  if (typeof d === 'string')
504
666
  return d;
667
+ const fillPath = E.kind === 'path' && fillsPath(E);
668
+ if (d?.net && !fillPath)
669
+ return 'net';
505
670
  if (n.instance && !E.fileInstance) {
506
671
  const own = difference(E, R, false);
507
672
  if (typeof own === 'string')
508
673
  return own;
509
674
  }
510
- if (n.instance && !same(contentInputs(E), contentInputs(R)))
675
+ const inputs = n.instance ? flowOverride(E.layoutData, R.layoutData) : {};
676
+ if (!supportsFrameOverrides && inputs['layoutData.flow'])
511
677
  return 'layout';
512
- const inputs = {};
513
678
  if (n.instance)
514
679
  Object.assign(inputs, dataOverride(instanceData(E, byId.get(E.parent)), n.data));
515
680
  else {
516
681
  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)
682
+ // Resizing a parametric path scales its box and network together.
683
+ // Use the main's box as the input to the same resize during layout.
684
+ if (fillPath && E.shape && a.layoutData.box && b.layoutData.box)
685
+ a.layoutData = { ...a.layoutData, box: b.layoutData.box };
686
+ if (E.kind === 'frame' && supportsFrameOverrides) {
687
+ const { layout: _a, padding: _ap, ...own } = a.layoutData;
688
+ const { layout: _b, padding: _bp, ...base } = b.layoutData;
689
+ Object.assign(inputs, dataOverride(own, base), flowOverride(a.layoutData, b.layoutData));
690
+ }
691
+ else
692
+ Object.assign(inputs, dataOverride(a.layoutData, b.layoutData));
693
+ if (a.keepSize !== b.keepSize)
694
+ inputs.keepSize = a.keepSize;
695
+ if (a.storedHeight !== b.storedHeight || a.storedRow !== b.storedRow) {
521
696
  Object.assign(inputs, { storedHeight: a.storedHeight, storedRow: a.storedRow });
697
+ }
522
698
  }
523
699
  // The box the expansion has where it differs from the main's, kept (keep) where core's layout of the instance does
524
700
  // 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 } });
701
+ 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
702
  if (d || Object.keys(inputs).length)
527
703
  out[n.path] = { ...out[n.path], ...d, ...inputs };
528
704
  if (E.fileSlotHost && fills?.includes(E.fileSlotHost))
529
705
  continue;
530
- const r = match(kidsOf(id), children, out, size, geometry, fills);
706
+ const r = match(kidsOf(id), children, out, size, geometry, linkPaths, fills, n.instance ? undefined : bound);
531
707
  if (r)
532
708
  return r;
533
709
  }
@@ -565,8 +741,14 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
565
741
  I.overrides[path] = { ...I.overrides[path], storedBox: g.box };
566
742
  added = true;
567
743
  }
568
- if (!added)
744
+ if (!added) {
745
+ for (const [path, { E, R, fillPath }] of geometry) {
746
+ // The direct resize and a resize through the main may differ by roundoff.
747
+ if (fillPath && !same(E.net, laid.get(path)?.net ?? R.net, 1e-6))
748
+ return 'net';
749
+ }
569
750
  return;
751
+ }
570
752
  }
571
753
  }
572
754
  const state = new Map(), reasons = new Map();
@@ -589,15 +771,31 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
589
771
  const root = difference(E, M, false, !!E.fileInstance);
590
772
  if (typeof root === 'string')
591
773
  return `root ${root}`;
592
- if (!same(contentInputs(E), contentInputs(M)))
593
- return 'root layout';
594
774
  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);
775
+ const content = flowOverride(E.layoutData, M.layoutData);
776
+ if (!supportsFrameOverrides && content['layoutData.flow'])
777
+ return 'root layout';
778
+ if (root || Object.keys(content).length)
779
+ overrides[''] = { ...root, ...content };
780
+ const linkPaths = nativeFile ? new Set() : undefined;
781
+ const r = match(kidsOf(id), tree(main), overrides, { width: E.w, height: E.h }, geometry, linkPaths, E.fileFills);
598
782
  if (r)
599
783
  return r;
600
784
  const data = instanceData(E, byId.get(E.parent));
785
+ const flow = content['layoutData.flow'];
786
+ for (const axis of ['width', 'height'])
787
+ if (flow?.[axis + 'Sizing'] && flow[axis + 'Sizing'] !== 'fill') {
788
+ if (data.sizing) {
789
+ delete data.sizing[axis];
790
+ if (!Object.keys(data.sizing).length)
791
+ delete data.sizing;
792
+ }
793
+ if (data.heldHug) {
794
+ data.heldHug = data.heldHug.filter((held) => held !== axis);
795
+ if (!data.heldHug.length)
796
+ delete data.heldHug;
797
+ }
798
+ }
601
799
  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
800
  if (E.fileInstance)
603
801
  I.fileInstance = E.fileInstance;
@@ -607,7 +805,9 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
607
805
  if (Object.keys(data).length)
608
806
  I.layoutData = data;
609
807
  I.overrides = overrides;
610
- keep(I, geometry);
808
+ const mismatch = keep(I, geometry);
809
+ if (mismatch)
810
+ return mismatch;
611
811
  if (!Object.keys(overrides).length)
612
812
  delete I.overrides;
613
813
  if (aliases)
@@ -616,6 +816,8 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
616
816
  byId.set(id, I);
617
817
  kids.delete(id);
618
818
  views.delete(id);
819
+ if (linkPaths?.size)
820
+ omittedLinks.set(id, linkPaths);
619
821
  linked++;
620
822
  return null;
621
823
  }
@@ -643,28 +845,29 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
643
845
  visit(m.component);
644
846
  } for (const c of kidsOf(id))
645
847
  visit(c); };
646
- for (const c of kidsOf(''))
647
- visit(c);
848
+ if (hidden.size)
849
+ for (const c of kidsOf(''))
850
+ visit(c);
648
851
  // Used once: a component (all its variants together) one instance uses; a variant used once of a component used
649
852
  // more keeps its main, so that every instance of a set is an instance of its own variant (the panel's variants).
650
853
  const uses = new Map();
651
854
  for (const [id, vk] of hidden)
652
855
  uses.set(componentOf(vk), (uses.get(componentOf(vk)) ?? 0) + (used.get(id) ?? 0));
653
856
  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));
857
+ if (hidden.size)
858
+ kids.set('@components', kidsOf('@components').filter((id) => !hidden.has(id) || used.has(id)));
657
859
  for (const id of mains.values()) {
658
860
  const m = byId.get(id);
659
861
  if (m && (!hidden.has(id) || used.has(id)))
660
- m.component = id;
862
+ byId.set(id, { ...m, component: id });
661
863
  }
662
864
  // What each component stores: its used hidden mains, its instances with their override keys, its expansions left.
663
865
  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
866
  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));
867
+ if (compareCosts)
868
+ for (const [id, vk] of hidden)
869
+ if (used.has(id))
870
+ add(componentOf(vk), size(id));
668
871
  const tally = (id) => {
669
872
  const m = byId.get(id);
670
873
  if (isInstance(m) && hidden.has(m.component))
@@ -674,15 +877,16 @@ function linkOnce(doc, skip, each = new Set(), aliases) {
674
877
  for (const c of kidsOf(id))
675
878
  tally(c);
676
879
  };
677
- for (const c of kidsOf(''))
678
- tally(c);
880
+ if (compareCosts)
881
+ for (const c of kidsOf(''))
882
+ tally(c);
679
883
  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))
884
+ 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
885
  emit(c); };
682
886
  for (const c of kidsOf(''))
683
887
  emit(c);
684
888
  for (const c of kidsOf('@components'))
685
889
  emit(c);
686
890
  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 };
891
+ return { omittedLinks, cost, before, after: models.length, linked, mains: mains.size - hidden.size, hidden: [...hidden.keys()].filter((id) => used.has(id)).length, unlinked: reasons, once };
688
892
  }