@moondraft/import 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.4.0 — 2026-11-28
6
+
7
+ - The peer dependency on `@moondraft/editor` is now `>=0.6.0 <0.7.0`. Install the editor 0.6.0 or later in the
8
+ 0.6 line.
9
+
10
+ - A Figma instance left expanded into plain layers keeps the fills and strokes the instance overrides, also on layers inside nested and swapped instances: before, it showed its main's paints where the main's style or variable binding was installed. An override's size bindings and variable modes are added to the main's, and a plain paint over a nested instance's colour variable drops that variable, linked or expanded.
11
+ - Figma text layers and groups keep their drop shadows, inner shadows, layer blur and background blur; editor 0.6.0 draws them.
12
+ - Figma instances stay linked to their mains far more often: a path that the instance's resize scales by its constraints, and content that draws outside the instance's box, no longer expand the instance into plain layers, so main edits, property references and variable bindings keep reaching it. The import report gives the reason for each instance still expanded ("expanded instance: …"). A linked instance inside an expanded one keeps the paints, styles and bindings the expanded instance overrides on its layers.
13
+ - A Figma instance left expanded keeps a text property's assigned wording where an override only restyles the bound text (its letter spacing, font or paint): before, the text showed the component's default wording in the new style.
14
+ - A linked Figma instance keeps a text override on a text bound to a text property: the wording is assigned to the property, so it no longer shows the property's default. An instance whose texts bound to one property show different wording stays expanded, so each keeps its own; this counts only texts of the instance's own component, not those of an instance left expanded inside its main.
15
+
5
16
  ## 0.3.0 — 2026-11-27
6
17
 
7
18
  - The peer dependency on `@moondraft/editor` is now `>=0.5.0 <0.6.0`. Install the editor 0.5.0 or later in the
package/SOURCE.md CHANGED
@@ -479,6 +479,12 @@ an object written that way with more than a few fields as a hash table; the copy
479
479
  takes about a fifth of the memory, which cuts the decoded tree of a layer-heavy file by about 100 MB. Values are
480
480
  unchanged.
481
481
 
482
+ ### `patches/0049-text-group-effects.patch`
483
+
484
+ Text layers and groups keep their shadows, layer blur and background blur. Taco's text and group nodes have no
485
+ style, so `nodeEffects` reads them as it does for shapes and `carryEffects` (carry.ts) carries them in
486
+ `metadata.figma.effects`, with `shadowBehind` indexing into its shadows; "effects are not imported yet" is no longer
487
+ reported for them. The adapter writes them to the layer's `look`, and the renderer draws a text's from its glyphs.
482
488
 
483
489
  ### `patches/0050-kiwi-shared-structs.patch`
484
490
 
@@ -506,3 +512,20 @@ reaches, whether or not a deeper override path goes through it. A property value
506
512
  component does not declare goes to the shallowest nested instances whose shown component (after swaps) declares it,
507
513
  read against that component, but only where the instance's `derivedSymbolData` lays out a layer bound to that property
508
514
  inside the nested instance (Figma ignores a stale value); any other such value is still reported.
515
+
516
+ ### `patches/0053-bound-text-style-overrides.patch`
517
+
518
+ An override that restyles a text bound to a text property (its letter spacing, font or paint) without wording of its own
519
+ (no `textData`) keeps the property's assigned value. Such an override converts to full `paragraphs`, which carried the
520
+ text's stored wording and so showed the component's default over the assigned value wherever the instance stays
521
+ expanded. The assigned characters now replace that wording in the override's formatting, as they already did for an
522
+ assignment with links; every text assignment is kept for this, a value passed down from a holder yielding to the
523
+ nested instance's own. An override with its own wording or links is left as it is. `convert-instance.test.ts` covers
524
+ this, marked "Moondraft patch 0053".
525
+
526
+ ### `patches/0054-export-override-merges.patch`
527
+
528
+ `withOverrides` and `withBindingEntries` are exported, so that the adapter merges the overrides it applies to a layer
529
+ of an expanded instance (`src/adapter/file-resources.ts`) as an override is converted for a linked one: a field the
530
+ override sets drops the main's binding of it, and the override's bindings replace only the main's of the same fields.
531
+ The functions themselves are unchanged.
@@ -30,6 +30,7 @@ import { withoutTextMeasurement } from '../taco/model/text-reads.js';
30
30
  import { createInstanceResolveCache, resolveComponent, resolveInstance } from '../taco/model/instance-resolver.js';
31
31
  import { applyFileTypography } from './file-typography.js';
32
32
  import { linkWithLayers, unmark } from './link.js';
33
+ import { boundTextExpression, layerComponents } from './file-components.js';
33
34
  const supportsGrid = 'layoutData.gridCell' in editorSchema.Properties;
34
35
  // Figma stores float32 sizes. Comparing after layout or instance scaling can
35
36
  // also include rounding from the arithmetic that produced the two sizes.
@@ -923,6 +924,11 @@ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
923
924
  for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius', 'cornerSmoothing'])
924
925
  if (o[k] !== undefined)
925
926
  style[k] = o[k];
927
+ // A .fig text layer's or group's shadows and blurs, which Taco's model keeps on shapes and frames only
928
+ // (metadata.figma.effects, taco patch 0049).
929
+ if ((n.type === 'text' || n.type === 'group') && figma?.effects)
930
+ for (const [k, v] of Object.entries(figma.effects))
931
+ style[k] ??= v;
926
932
  if (L) {
927
933
  // The resolver writes a bound or computed radius as one cornerRadius; a layer that stores per-corner radii keeps
928
934
  // them as four equal ones, as the converter writes them.
@@ -2685,6 +2691,7 @@ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
2685
2691
  s.lineHeight = +(s.size * trimmed).toFixed(3);
2686
2692
  approximate('leading trim (cap height) taken from a box at the cap height');
2687
2693
  }
2694
+ appearance(m, { shadows: style.shadows, layerBlur: style.layerBlur, backgroundBlur: style.backgroundBlur }, 'text', n.metadata?.figma);
2688
2695
  models.push(m);
2689
2696
  return m;
2690
2697
  }
@@ -2820,7 +2827,16 @@ function convert(doc, pages, options, explicit, file, deferHyperlinks = false) {
2820
2827
  // Drop the resolver, trial layouts and pre-layout geometry before indexing linked layers.
2821
2828
  const { out, affected, nestedBooleans, counts, depth, files } = expand(doc, pages, options, explicit, file, deferHyperlinks);
2822
2829
  const models = out.models;
2823
- const linked = options.link === false ? null : linkWithLayers(out, true, file && (id => doc.nodes[id]?.expressions?.componentId), !!file);
2830
+ // A text's expression counts where the file's components bind it (file-components.ts).
2831
+ let owners;
2832
+ const binding = (id, field, main) => {
2833
+ const expression = doc.nodes[id]?.expressions?.[field];
2834
+ if (field !== 'characters')
2835
+ return expression;
2836
+ owners ??= layerComponents(Object.values(doc.components), (id) => doc.nodes[id]?.children);
2837
+ return boundTextExpression(expression, owners.get(id), main);
2838
+ };
2839
+ const linked = options.link === false ? null : linkWithLayers(out, true, file && binding, !!file);
2824
2840
  if (linked && !explicit) {
2825
2841
  // Clipboard mains synthesized from expansions get their presets from the source definition. A variant set's main
2826
2842
  // is the set's root showing one variant, a frame of the root's: the main is that variant, so it takes the
@@ -7,6 +7,24 @@ import type { NestedBooleanAssignments } from './convert.ts';
7
7
  * @internal
8
8
  */
9
9
  export type FileMessage = ReturnType<typeof readFileMessage>;
10
+ /** Per source layer, the component whose properties its expressions bind to (fileComponents): each layer of a
11
+ * component's tree, a later component's tree winning.
12
+ * @internal
13
+ */
14
+ export declare function layerComponents<C extends {
15
+ rootId: string;
16
+ }>(components: Iterable<C>, children: (id: string) => readonly string[] | undefined): Map<string, C>;
17
+ /** The expression a source layer's text takes from a component property where fileComponents binds it: a property,
18
+ * other than a variant or slot, of the component it is a layer of, in that component's main (`main`, its root).
19
+ * @internal
20
+ */
21
+ export declare function boundTextExpression(expression: string | undefined, component: {
22
+ rootId: string;
23
+ properties?: readonly {
24
+ name: string;
25
+ kind: string;
26
+ }[];
27
+ } | undefined, main: string | undefined): string | undefined;
10
28
  /** Installs local property IDs, their bindings, instance assignments and slot content.
11
29
  * @param result - Original Figma component declarations and placements.
12
30
  * @param doc - Linked document, with source IDs for the original nodes.
@@ -1,8 +1,35 @@
1
1
  import { definitions as propertyDefinitions, effectiveRecord, isInstance, ownerOf, resolveVirtual, splitVirtual } from '@moondraft/editor/core';
2
2
  import { guidText } from '../taco/figma-import/import/fields.js';
3
- import { formatExpressionName, parseLayerPath } from '../taco/model/index.js';
3
+ import { formatExpressionName, layerPathKey, parseLayerPath } from '../taco/model/index.js';
4
4
  import { keepDescription } from './figma-descriptions.js';
5
+ import { withOverrideFields } from './file-resources.js';
5
6
  import { expansionReason } from './link.js';
7
+ /** Per source layer, the component whose properties its expressions bind to (fileComponents): each layer of a
8
+ * component's tree, a later component's tree winning.
9
+ * @internal
10
+ */
11
+ export function layerComponents(components, children) {
12
+ const of = new Map();
13
+ for (const c of components) {
14
+ const pending = [c.rootId];
15
+ while (pending.length) {
16
+ const id = pending.pop();
17
+ of.set(id, c);
18
+ for (const child of children(id) ?? [])
19
+ pending.push(child);
20
+ }
21
+ }
22
+ return of;
23
+ }
24
+ /** The expression a source layer's text takes from a component property where fileComponents binds it: a property,
25
+ * other than a variant or slot, of the component it is a layer of, in that component's main (`main`, its root).
26
+ * @internal
27
+ */
28
+ export function boundTextExpression(expression, component, main) {
29
+ const p = expression === undefined || component === undefined || component.rootId !== main ? undefined
30
+ : component.properties?.find(p => formatExpressionName(p.name) === expression);
31
+ return p && p.kind !== 'enum' && p.kind !== 'slot' ? expression : undefined;
32
+ }
6
33
  /** Installs local property IDs, their bindings, instance assignments and slot content.
7
34
  * @param result - Original Figma component declarations and placements.
8
35
  * @param doc - Linked document, with source IDs for the original nodes.
@@ -120,7 +147,6 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
120
147
  definitions.set(member.componentId, refs);
121
148
  }
122
149
  }
123
- const sourceComponent = new Map();
124
150
  for (const c of result.components) {
125
151
  const main = mains.get(c.id);
126
152
  main.key = c.key;
@@ -136,14 +162,8 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
136
162
  if (value !== shared.default)
137
163
  report.push({ kind: 'approximated', what: 'variant member property default', count: 1, ids: [main.id] });
138
164
  }
139
- const pending = [c.rootId];
140
- while (pending.length) {
141
- const id = pending.pop(), layer = source.get(id);
142
- sourceComponent.set(id, c);
143
- for (const child of layer.children ?? [])
144
- pending.push(child);
145
- }
146
165
  }
166
+ const sourceComponent = layerComponents(result.components, id => source.get(id).children);
147
167
  const componentOfMain = (id) => componentOfRoot.get(byId.get(id)?.sourceId);
148
168
  function values(component, assignments, id) {
149
169
  const refs = definitions.get(component);
@@ -169,6 +189,28 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
169
189
  }).join(';');
170
190
  }
171
191
  const occurrences = new Map();
192
+ // A linked instance inside an expanded one also shows what the expanded instances above it override through it
193
+ // (paints, styles, bindings), as a layer of the expansion does (file-resources expandedFields): their fields join its
194
+ // own at each of its paths, the outer instance's winning.
195
+ function throughExpanded(m, own) {
196
+ let fields = own;
197
+ const path = [m.sourceId];
198
+ for (let parent = byId.get(m.parent); parent; parent = byId.get(parent.parent)) {
199
+ if (source.get(parent.sourceId)?.type !== 'instance')
200
+ continue;
201
+ const outer = parent.component ? undefined : result.sources.occurrenceFields.get(parent.sourceId), prefix = layerPathKey(path);
202
+ for (const [key, over] of outer ?? []) {
203
+ if (key !== prefix && !key.startsWith(prefix + ';'))
204
+ continue;
205
+ const inner = key.slice(prefix.length + 1);
206
+ if (fields === own)
207
+ fields = new Map(own);
208
+ fields.set(inner, withOverrideFields(fields.get(inner) ?? {}, over));
209
+ }
210
+ path.unshift(parent.sourceId);
211
+ }
212
+ return fields;
213
+ }
172
214
  const instanceOverrides = new Map();
173
215
  const hosts = new Set(result.nodes.filter(n => n.type === 'frame' && n.slotHost).map(n => n.id));
174
216
  const usedHosts = new Set();
@@ -230,7 +272,7 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
230
272
  report.push({ kind: 'approximated', what: reason ? `expanded instance: ${expansionReason(reason)}` : 'expanded instance', count: 1, ids: [m.id] });
231
273
  continue;
232
274
  }
233
- const fields = result.sources.occurrenceFields.get(n.id);
275
+ const fields = throughExpanded(m, result.sources.occurrenceFields.get(n.id));
234
276
  if (fields)
235
277
  occurrences.set(m.id, new Map([...fields].map(([key, change]) => [overridePath(key), change])));
236
278
  // The editor resolves a stored bound swap from the enclosing main or set's declaration.
@@ -321,6 +363,40 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
321
363
  (owner.props ??= {})[binding] = entry.component;
322
364
  }
323
365
  }
366
+ // A linked occurrence whose text, bound to a text property, shows other wording than the property gives it there (a
367
+ // Figma text override, not an assignment) assigns that wording to the property: core derives a bound text's content
368
+ // from its property and drops the override. Wording the property already gives stays as it is. What it gives is read
369
+ // from the converted overrides, not from assignments this loop adds, so the order of the instances does not matter.
370
+ // Linking leaves expanded an occurrence whose texts bound to one property show different wording (link.ts match).
371
+ for (const holder of models) {
372
+ if (!isInstance(holder))
373
+ continue;
374
+ for (const [path, entry] of Object.entries(holder.overrides ?? {})) {
375
+ if (typeof entry.content !== 'string')
376
+ continue;
377
+ const target = resolveVirtual(get, holder.id + ';' + path, true);
378
+ const binding = target?.layer.bind?.content;
379
+ if (!target || !binding)
380
+ continue;
381
+ const at = target.levels.at(-1)[1], ownerPath = target.parts.slice(1, at + 1).join(';');
382
+ if (binding in ((at === 0 ? holder : holder.overrides[ownerPath])?.props ?? {}))
383
+ continue;
384
+ // An enclosing main's assignment to the occurrence or its own wording of the text, outermost first, else the default.
385
+ let given;
386
+ for (const [level, j] of target.levels.slice(1)) {
387
+ const assigned = j === at ? level.props : level.overrides?.[target.parts.slice(j + 1, at + 1).join(';')]?.props;
388
+ given = assigned?.[binding] ?? level.overrides?.[target.parts.slice(j + 1).join(';')]?.content;
389
+ if (typeof given === 'string')
390
+ break;
391
+ }
392
+ const shown = at === 0 ? holder.component : resolveVirtual(get, holder.id + ';' + ownerPath, true)?.component;
393
+ given ??= propertyDefinitions(ownerOf(get, get(shown))).find(p => p.id === binding)?.default;
394
+ if (given === entry.content)
395
+ continue;
396
+ const owner = at === 0 ? holder : (holder.overrides[ownerPath] ??= {});
397
+ (owner.props ??= {})[binding] = entry.content;
398
+ }
399
+ }
324
400
  // A flattened ancestor can also leave an assignment inside a surviving linked instance.
325
401
  // Apply inherited paths before the longer paths of the instances that use them.
326
402
  for (const [id, inherited] of [...nestedBooleans].filter(([id]) => id.includes(';')).sort(([a], [b]) => a.length - b.length)) {
@@ -9,6 +9,11 @@ type Corner = {
9
9
  specific: boolean;
10
10
  };
11
11
  };
12
+ type Change = Record<string, any>;
13
+ /** `change` with an enclosing instance's override fields (`own`) merged in: its plain fields replace the change's
14
+ * (unbinding the fields they set), and its bindings and modes replace only those of the same fields and collections.
15
+ * A list of paints in the override drops the change's style of that slot unless the override names one. */
16
+ export declare function withOverrideFields(change: Change, own: Change): Change;
12
17
  /** Finds instance roots that need their own radius bindings. Native instance roots take bindings from their main.
13
18
  * @param result - File definitions and original instance fields.
14
19
  * @returns The effective corners for each root that must remain an expanded frame.
@@ -7,6 +7,7 @@ import { variableResolver } from './variables.js';
7
7
  import { styleAtOf, supportsRunPaint } from './link.js';
8
8
  import { guidText, isObject } from '../taco/figma-import/import/fields.js';
9
9
  import { isDetachedStyle, STYLE_REFERENCE_FIELDS } from '../taco/figma-import/import/styles.js';
10
+ import { withBindingEntries, withOverrides } from '../taco/figma-import/import/instances.js';
10
11
  import { layerPathKey, parseLayerPath } from '../taco/model/index.js';
11
12
  import { rgba, runStyle } from './convert.js';
12
13
  import { keepDescription } from './figma-descriptions.js';
@@ -138,6 +139,28 @@ function paintsAndEffects(change, m, bind, indices) {
138
139
  }
139
140
  }
140
141
  }
142
+ /** A `variableModeBySetMap` with the choices of an override's own map (`over`) in place of those for the same collections in `map`. */
143
+ function withModeEntries(map, over) {
144
+ const entriesOf = (value) => isObject(value) && Array.isArray(value.entries) ? value.entries : [];
145
+ const collectionOf = (entry) => JSON.stringify(entry?.variableSetID);
146
+ const named = new Set(entriesOf(over).map(collectionOf));
147
+ return { ...isObject(map) && map, ...isObject(over) && over,
148
+ entries: [...entriesOf(map).filter(entry => !named.has(collectionOf(entry))), ...entriesOf(over)] };
149
+ }
150
+ /** `change` with an enclosing instance's override fields (`own`) merged in: its plain fields replace the change's
151
+ * (unbinding the fields they set), and its bindings and modes replace only those of the same fields and collections.
152
+ * A list of paints in the override drops the change's style of that slot unless the override names one. */
153
+ export function withOverrideFields(change, own) {
154
+ const { variableConsumptionMap: map, variableModeBySetMap: modes, ...plain } = own;
155
+ const unbound = withOverrides(change, plain, plain.styleIdForText !== undefined);
156
+ const merged = { ...unbound,
157
+ ...map !== undefined && { variableConsumptionMap: withBindingEntries(unbound.variableConsumptionMap, map) },
158
+ ...modes !== undefined && { variableModeBySetMap: withModeEntries(unbound.variableModeBySetMap, modes) } };
159
+ for (const [ref, list] of STYLE_REFERENCE_FIELDS)
160
+ if (list in own && !(ref in own))
161
+ delete merged[ref];
162
+ return merged;
163
+ }
141
164
  function radiusBindings(change) {
142
165
  const bindings = new Map();
143
166
  for (const e of change.variableConsumptionMap?.entries ?? []) {
@@ -753,7 +776,7 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
753
776
  }
754
777
  return false;
755
778
  }
756
- // Occurrence entries that name a style, masked once every entry holds its own bindings.
779
+ // Occurrence entries that name a style or set a paint list, masked once every entry holds its own bindings.
757
780
  const masked = [];
758
781
  const styled = {
759
782
  fillStyle: ['look.fills'],
@@ -837,6 +860,11 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
837
860
  delete lists[list]; // Variable-backed paints in a named style are authored on its definition.
838
861
  }
839
862
  }
863
+ // A paint list replaces the slot as a style does: a binding an inner instance gave the old paints goes with them.
864
+ if (virtual && !instance && m.kind !== 'text')
865
+ for (const [list, slot] of [['fillPaints', 'fillStyle'], ['strokePaints', 'strokeStyle']])
866
+ if (change[list] !== undefined)
867
+ masked.push([into, id, slot]);
840
868
  const rootEntry = instance && !virtual ? m.overrides?.[''] ?? {} : into;
841
869
  if (['frame', 'rect'].includes(m.kind))
842
870
  installRadius(change, m, root, rootEntry, id, virtual);
@@ -910,6 +938,17 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
910
938
  const layers = doc.models;
911
939
  const mainLayers = new Map(layers.filter(m => m.component === m.id).map(m => [m.sourceId, m]));
912
940
  const mains = new Map(result.components.map(c => [c.id, mainLayers.get(c.rootId)]));
941
+ // Only a layer of an expanded instance has an instance above it; the walk up for overrides stops where that ends.
942
+ const instanceSource = (m) => layerSource.get(m.sourceId)?.node.type === 'instance';
943
+ const inside = new Map();
944
+ function insideInstance(m) {
945
+ let known = inside.get(m.id);
946
+ if (known === undefined) {
947
+ const parent = records.get(m.parent);
948
+ inside.set(m.id, known = instanceSource(m) || !!parent && insideInstance(parent));
949
+ }
950
+ return known;
951
+ }
913
952
  function expandedFields(m, change) {
914
953
  const source = layerSource.get(m.sourceId);
915
954
  if (expandedRadii.has(m.sourceId) && source.node.type === 'instance') {
@@ -950,19 +989,17 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
950
989
  }
951
990
  }
952
991
  }
992
+ // A layer under an expanded instance shows what the instances above it override (paints, styles, bindings),
993
+ // the innermost first so that an outer instance's override wins.
994
+ // An override's bindings and modes replace only the main's of the same fields and collections, as on a linked instance.
953
995
  const path = [m.sourceId];
954
- for (let parent = records.get(m.parent); parent; parent = records.get(parent.parent)) {
955
- if (expandedRadii.has(parent.sourceId)) {
956
- const own = result.sources.occurrenceFields.get(parent.sourceId)?.get(layerPathKey(path));
957
- if (own) {
958
- change = { ...change, ...own };
959
- for (const [ref, list] of STYLE_REFERENCE_FIELDS)
960
- if (list in own && !(ref in own))
961
- delete change[ref];
962
- }
963
- }
964
- if (layerSource.get(parent.sourceId)?.node.type === 'instance')
965
- path.unshift(parent.sourceId);
996
+ for (let parent = records.get(m.parent); parent && insideInstance(parent); parent = records.get(parent.parent)) {
997
+ if (!instanceSource(parent))
998
+ continue;
999
+ const own = result.sources.occurrenceFields.get(parent.sourceId)?.get(layerPathKey(path));
1000
+ if (own)
1001
+ change = withOverrideFields(change, own);
1002
+ path.unshift(parent.sourceId);
966
1003
  }
967
1004
  return change;
968
1005
  }
@@ -970,7 +1007,7 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
970
1007
  palette(m, m.id);
971
1008
  const source = layerSource.get(m.sourceId);
972
1009
  if (source)
973
- install(expandedRadii.size ? expandedFields(m, source.figma.change) : source.figma.change, m, m, m.id);
1010
+ install(expandedFields(m, source.figma.change), m, m, m.id);
974
1011
  }
975
1012
  const nestedPalettes = [];
976
1013
  for (const m of layers) {
@@ -1031,7 +1068,7 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
1031
1068
  // Install inner bindings before comparing an enclosing palette with the sources it inherits.
1032
1069
  nestedPalettes.forEach(level => { for (const [entry, id] of level)
1033
1070
  palette(entry, id, true); });
1034
- // A style override replaces the slot as Figma does: bindings the occurrence inherits there no longer apply.
1071
+ // A style or paint override replaces the slot as Figma does: bindings the occurrence inherits there no longer apply.
1035
1072
  for (const [entry, id, slot] of masked)
1036
1073
  for (const path of inheritedBindings(id))
1037
1074
  if (styled[slot].some(p => path.startsWith(p + '.')) && !Object.hasOwn(entry.vars ?? {}, path))
@@ -48,7 +48,7 @@ export declare function linkComponents(doc: {
48
48
  /** @internal Links components and tracks where their expanded layers went for import reports. */
49
49
  export declare function linkWithLayers(doc: {
50
50
  models: any[];
51
- }, trackLayers?: boolean, swapBinding?: (source: string) => string | undefined, nativeFile?: boolean): {
51
+ }, trackLayers?: boolean, binding?: (source: string, field: 'componentId' | 'characters', main?: string) => string | undefined, nativeFile?: boolean): {
52
52
  counts: LinkCounts;
53
53
  aliases: Map<string, string[]>;
54
54
  omittedLinks: Map<string, Set<string>>;
@@ -6,9 +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 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
9
+ // that takes no override (a path's network that core's layout of the instance does not give, a stroke's position or
10
+ // weight, a layer the main lacks, the root's own fills) stays expanded, and so do the instances inside it, which are
11
+ // linked on their own when they can be; the import report gives each one's reason (expansionReason). A stroke's
12
12
  // other colour is a paint override (the renderer draws a stroke's paint in place of its compact colour).
13
13
  // - A component whose root is on the page has it as its main. Any other gets a hidden main under '@components' (core's
14
14
  // parent of mains that are not drawn): a copy of its largest expanded instance with every layer its other expansions
@@ -22,14 +22,18 @@
22
22
  // differ, beside the transforms and sizes the page was linked with (settle.mjs makes those the editor's own). Core
23
23
  // lays an instance out again (packages/editor/src/core/layout/layout.ts instanceLayout) only when it or its main
24
24
  // changes, and the transforms and sizes it writes then are its output alone; where that layout, run here, does not
25
- // give a layer's linked box (within 0.01 px), the box is stored too (storedBox, with the instance's size), and core's
26
- // layout starts from it until the main edits that layer's box.
25
+ // give a layer's linked box (within 0.01 px), the box is stored too, whole (storedBox: transform and size, with the
26
+ // instance's size), and core's layout starts from it until the main edits that layer's box. A layer an auto layout
27
+ // places where the expansion holds its main's box (Figma stated none) stores none and shows the layout's place.
27
28
  // - An instance has no children to hug: where its expanded root is an auto layout filling a parent that hugs it, the
28
29
  // parent hugged that root's content (layout.mjs natural), so the instance keeps its size there ('fixed') and the
29
30
  // parent lays out as it did.
30
- // - What the renderer does differently from core is avoided: it culls an instance's content by the instance's box (an
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
32
- // reaches well past it, stays expanded); its text body field carries the text's box (see difference).
31
+ // - A path's network that the instance's resize reshapes (scale or stretch constraints, a fill) is layout's output, as
32
+ // its box is: linked where core's layout of the instance gives it (keep, within EPSILON), and stored beside the
33
+ // boxes, so a later edit of the main's network reaches the instance scaled.
34
+ // - Content that draws outside the instance's box links too: the renderer bounds an instance by its content's paint
35
+ // (crates/scn-core instances.rs instance_subtree_bounds). Its text body field carries the text's box (see
36
+ // difference).
33
37
  // The markers are removed whether or not anything is linked.
34
38
  import { supportsTextField } from './file-typography.js';
35
39
  import { Properties, TextStyleSchema } from '@moondraft/editor/schema';
@@ -58,10 +62,12 @@ const FIELD_WORDS = {
58
62
  export function expansionReason(reason) {
59
63
  const fixed = {
60
64
  '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',
65
+ 'not a frame': 'it is not a frame',
62
66
  'inside its main': 'it is inside its own main', 'layer order': 'its layers are in another order than its main\'s',
63
67
  'a layer the main lacks': 'it has a layer its main lacks', 'conflicting bound swaps': 'one swap property selects different mains in it',
68
+ 'conflicting bound text': 'texts bound to one text property show different wording in it',
64
69
  net: 'a vector network its main\'s layout does not give',
70
+ 'partial box': 'a layer with a width but no height, or the reverse, whose box its main\'s layout does not give',
65
71
  };
66
72
  if (fixed[reason])
67
73
  return fixed[reason];
@@ -193,7 +199,7 @@ function difference(E, R, own, rootOverride = false, omitLink) {
193
199
  rec.w = E.w;
194
200
  rec.h = E.h;
195
201
  }
196
- // Layout owns a stretched path's network override. keep() checks it against the
202
+ // Layout owns a resized path's network override. keep() checks it against the
197
203
  // main laid out with all sibling overrides and stored boxes before accepting the link.
198
204
  else if (k === 'net' && E.kind === 'path' && own)
199
205
  rec.net = E.net;
@@ -387,18 +393,44 @@ function instanceData(E, P) {
387
393
  /** How far core's layout of a linked instance may place a layer from its expanded box (px; 1e-4 of the linear part)
388
394
  * before the box is stored. */
389
395
  const EPSILON = 0.01;
390
- /** How far (px) a layer's shadow or blur may reach past its box and still count as inside it (overflows). The renderer
391
- * bounds an instance by its own box and its root's effects, not its content's: a card's 56 px shadow tail inside a
392
- * Modal instance was cut 22 px below it, while the HeroUI pages' tails of up to 8 px drew as expanded. */
393
- const SLACK = 8;
394
- /** Whether core's layout of an instance (laid: its output for the layer, absent where it shows its main's R) gives the
395
- * expanded record E's transform and size. */
396
- function gives(laid, { E, R }) {
397
- const t = laid?.t ?? R.t ?? [1, 0, 0, 1, 0, 0], e = E.t ?? [1, 0, 0, 1, 0, 0];
398
- if (t.some((v, i) => Math.abs(v - e[i]) > (i < 4 ? 1e-4 : EPSILON)))
396
+ const IDENTITY = [1, 0, 0, 1, 0, 0];
397
+ const nearT = (a, b) => !(a ?? IDENTITY).some((v, i) => Math.abs(v - (b ?? IDENTITY)[i]) > (i < 4 ? 1e-4 : EPSILON));
398
+ const near = (a, b) => a === b || (a !== undefined && b !== undefined && Math.abs(a - b) <= EPSILON);
399
+ /** Whether the expanded record E (in its parent P) has a box of its own: a transform or a size other than its main's
400
+ * layer R shows (as Figma's derived entry for a layer gives its box whole, a part it leaves out being its main's). A
401
+ * layer of an auto layout at its main's size is one Figma stated no size for where its main's box no longer fits its
402
+ * parent's width (outside: a layer that fills its parent at its main's width in a narrower parent, a layer past the end
403
+ * of a narrower parent) or Figma laid it out anew (layoutData.relaid, rehug: a nested instance re-hugging its text): the instance's
404
+ * auto layout sizes and places it, as a load's layout of the expanded layers does, whatever place the expansion gives
405
+ * it. That layout moves no other layer: one that still fits, a group (its box is its layers') and one outside a flow
406
+ * (its constraints act only on a resize) keep their boxes, so each has one. */
407
+ function states(E, R, P) {
408
+ const flows = ['horizontal', 'vertical', 'grid'].includes(P?.layoutData?.layout?.kind) && E.layoutData?.layoutPositioning !== 'absolute';
409
+ const free = flows && !E.group && (outside(E, P) || !!E.layoutData?.relaid || !!E.layoutData?.rehug);
410
+ return !free || !near(E.w, R.w) || !near(E.h, R.h);
411
+ }
412
+ /** Whether layer E's box (unrotated) reaches past either side of its parent P's width. Only the width: a load's layout
413
+ * of the expanded layers keeps one past its parent's bottom where it was (a third line in a two-line box). */
414
+ function outside(E, P) {
415
+ const t = E.t ?? IDENTITY;
416
+ if (!P || P.w === undefined || !nearT([...t.slice(0, 4), 0, 0], IDENTITY) || E.w === undefined)
399
417
  return false;
400
- const size = (k) => (laid && k in laid ? laid[k] : R[k]);
401
- return ['w', 'h'].every((k) => E[k] === size(k) || (E[k] !== undefined && size(k) !== undefined && Math.abs(E[k] - size(k)) <= EPSILON));
418
+ return t[4] < -EPSILON || t[4] + E.w > P.w + EPSILON;
419
+ }
420
+ /** Whether core's layout of an instance (laid: its output for the layer, absent where it shows its main's R) gives
421
+ * the expanded record E's transform and size, where E has a box of its own (own). */
422
+ function gives(laid, { E, R, own }) {
423
+ if (!own)
424
+ return true;
425
+ return nearT(laid?.t ?? R.t, E.t) && ['w', 'h'].every((k) => near(E[k], laid && k in laid ? laid[k] : R[k]));
426
+ }
427
+ /** The box stored for a layer whose own box the instance's layout does not give (keep): E's transform and size, whole,
428
+ * at the instance's size `at`. A stored box holds both sizes or neither, so a layer with a width but no height, or the
429
+ * reverse, has none (undefined): the instance stays expanded. */
430
+ function wholeBox(E, at) {
431
+ if (('w' in E) !== ('h' in E))
432
+ return undefined;
433
+ return { t: [...(E.t ?? IDENTITY)], ...('w' in E && { w: E.w, h: E.h }), at };
402
434
  }
403
435
  /** Links the instances of a converted page (its models, in file order) to their mains, in place. Returns counts.
404
436
  * A hidden main only one instance would use (not a main on the page) costs more than that instance's expansion, so
@@ -411,7 +443,7 @@ export function linkComponents(doc) {
411
443
  return linkWithLayers(doc, false).counts;
412
444
  }
413
445
  /** @internal Links components and tracks where their expanded layers went for import reports. */
414
- export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile = false) {
446
+ export function linkWithLayers(doc, trackLayers = true, binding, nativeFile = false) {
415
447
  // Variant sets (convert.ts markSet): one hidden main per variant used, so each instance's main is its own variant
416
448
  // and its overrides are its own changes alone; but a showcase of a set (each variant once or twice) costs a main per
417
449
  // variant. So per set: the page is linked both ways and a set keeps a main per variant where that stores no more
@@ -431,7 +463,7 @@ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile
431
463
  const skip = new Set();
432
464
  for (;;) {
433
465
  const d = { models: doc.models }, aliases = new Map();
434
- const { once, omittedLinks, expandedReasons, ...r } = linkOnce(d, skip, each, compareCosts, report ? aliases : undefined, swapBinding, nativeFile);
466
+ const { once, omittedLinks, expandedReasons, ...r } = linkOnce(d, skip, each, compareCosts, report ? aliases : undefined, binding, nativeFile);
435
467
  if (!once.length)
436
468
  return { d, r, aliases, omittedLinks, expandedReasons };
437
469
  for (const comp of once)
@@ -455,7 +487,7 @@ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile
455
487
  }
456
488
  /** linkComponents with no hidden main for the components in `skip`; also returns the components whose hidden main is
457
489
  * used once (once). */
458
- function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFile = false) {
490
+ function linkOnce(doc, skip, each, compareCosts, aliases, binding, nativeFile = false) {
459
491
  const omittedLinks = new Map();
460
492
  const recordAlias = (from, to) => {
461
493
  if (!aliases)
@@ -488,41 +520,6 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
488
520
  const kidsOf = (id) => kids.get(id) ?? [];
489
521
  const size = (id) => 1 + kidsOf(id).reduce((n, c) => n + size(c), 0);
490
522
  const before = doc.models.length;
491
- // Whether the layers under a frame draw outside its box, with their drop shadows and layer blurs where they reach
492
- // further than SLACK, as the renderer reaches them (the offset plus 1.5 blur and the spread; crates/scn-core
493
- // derived.rs effect_reach); clipping frames bound their own children.
494
- const reach = (m) => {
495
- const blur = 1.5 * (m.look?.layerBlur?.radius ?? 0), out = [blur, blur, blur, blur]; // left, top, right, bottom
496
- for (const s of m.look?.shadows ?? [])
497
- if (!s.inner && s.c?.[3] !== 0) {
498
- const spread = s.spread ?? 0, x = s.x ?? 0, y = s.y ?? 0;
499
- const e = 1.5 * (s.blur ?? 0) + spread;
500
- out[0] = Math.max(out[0], e - x);
501
- out[1] = Math.max(out[1], e - y);
502
- out[2] = Math.max(out[2], e + x);
503
- out[3] = Math.max(out[3], e + y);
504
- }
505
- return out.map((v) => (v > SLACK ? v : 0));
506
- };
507
- const mul = (A, B) => [A[0] * B[0] + A[2] * B[1], A[1] * B[0] + A[3] * B[1], A[0] * B[2] + A[2] * B[3], A[1] * B[2] + A[3] * B[3], A[0] * B[4] + A[2] * B[5] + A[4], A[1] * B[4] + A[3] * B[5] + A[5]];
508
- function overflows(root) {
509
- const R = byId.get(root), stack = kidsOf(root).map((c) => [c, byId.get(c).t]);
510
- while (stack.length) {
511
- const [id, T] = stack.pop(), m = byId.get(id);
512
- if (m.visible === false)
513
- continue;
514
- const b = m.kind === 'path' ? netBounds(m.net) : { x: 0, y: 0, width: m.w ?? 0, height: m.h ?? 0 }, [l, t, r, u] = reach(m);
515
- for (const [x, y] of [[b.x - l, b.y - t], [b.x + b.width + r, b.y - t], [b.x - l, b.y + b.height + u], [b.x + b.width + r, b.y + b.height + u]]) {
516
- const X = T[0] * x + T[2] * y + T[4], Y = T[1] * x + T[3] * y + T[5];
517
- if (X < -0.5 || Y < -0.5 || X > R.w + 0.5 || Y > R.h + 0.5)
518
- return true;
519
- }
520
- if (!m.clip)
521
- for (const c of kidsOf(id))
522
- stack.push([c, mul(T, byId.get(c).t)]);
523
- }
524
- return false;
525
- }
526
523
  const key = (m) => m.fileInstance ?? m.sourceId ?? `~${m.kind}~${m.name ?? ''}`;
527
524
  // Hidden mains (taken before anything is linked): a copy of each component's largest expansion, with every layer
528
525
  // another expansion has and it lacks, hidden (see union).
@@ -634,22 +631,21 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
634
631
  root.name = vk === comp ? E0.setOf : `${E0.setOf}/${E0.variant}`;
635
632
  unmark(root);
636
633
  root.mainOf = comp;
637
- // An expansion that stays expanded whatever its main (its layers draw outside it, or in another order) adds nothing.
638
- for (const id of frames.slice(1))
639
- if (byId.get(id).clip || !overflows(id)) {
640
- const p = plan(id, root.id);
641
- if (p)
642
- union(root.id, p);
643
- }
634
+ // An expansion that stays expanded whatever its main (its layers in another order) adds nothing.
635
+ for (const id of frames.slice(1)) {
636
+ const p = plan(id, root.id);
637
+ if (p)
638
+ union(root.id, p);
639
+ }
644
640
  mains.set(vk, root.id);
645
641
  hidden.set(root.id, vk);
646
642
  }
647
643
  const isInstance = (m) => m?.kind === 'frame' && m.component !== undefined && m.component !== m.id;
648
644
  // A main's effective tree: per layer, its path (from the main's child down), what it shows and its children.
649
- const trees = new Map();
645
+ const trees = new Map(), laidOut = new WeakMap();
650
646
  function swappedNode(n, main) {
651
647
  ensure(main);
652
- return { ...n, main, rec: n.recordOf(main), kids: n.childrenOf(main) };
648
+ return { ...n, main, rec: n.recordOf(main), raw: undefined, kids: n.childrenOf(main) };
653
649
  }
654
650
  function reroot(n, prefix, overrides) {
655
651
  const over = overrides?.[n.path];
@@ -657,7 +653,18 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
657
653
  n = swappedNode(n, over.component);
658
654
  // Keep each holder's overrides in scope when a later placement chooses another main.
659
655
  const underHolder = (child) => reroot(child, prefix, overrides);
660
- return { ...n, path: `${prefix};${n.path}`, rec: over ? applied(n.rec, over) : n.rec,
656
+ // raw: what it shows with the boxes its holders' links had before keep gave them the layout's (laidOut): what the
657
+ // expansion of an instance around it holds where Figma stated no box of its own.
658
+ const was = over && laidOut.get(over), rawOver = was && { ...over };
659
+ if (rawOver)
660
+ for (const k of ['t', 'w', 'h']) {
661
+ if (k in was)
662
+ rawOver[k] = was[k];
663
+ else
664
+ delete rawOver[k];
665
+ }
666
+ const raw = rawOver ? applied(n.raw ?? n.rec, rawOver) : over && n.raw ? applied(n.raw, over) : n.raw;
667
+ return { ...n, path: `${prefix};${n.path}`, rec: over ? applied(n.rec, over) : n.rec, raw,
661
668
  ...(n.instance && over && { recordOf: (main) => applied(n.recordOf(main), over) }),
662
669
  ...(n.instance && { childrenOf: (main) => n.childrenOf(main).map(underHolder) }),
663
670
  kids: n.kids.map(underHolder), data: withData(n.data, over) };
@@ -665,10 +672,15 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
665
672
  function tree(main) {
666
673
  if (trees.has(main))
667
674
  return trees.get(main);
675
+ const mainSource = byId.get(main)?.sourceId;
668
676
  const build = (id, path, inDefinition = true) => {
669
677
  const m = byId.get(id);
670
- if (!isInstance(m))
671
- return { path, rec: m, kids: kidsOf(id).map((c) => build(c, `${path};${c}`, inDefinition && !m.fileInstance)) };
678
+ if (!isInstance(m)) {
679
+ // The property a text of the main's own takes its wording from (match); texts of an instance left expanded in
680
+ // the main belong to its component.
681
+ const textProperty = inDefinition && m.kind === 'text' && m.sourceId !== undefined ? binding?.(m.sourceId, 'characters', mainSource) : undefined;
682
+ return { path, rec: m, ...(textProperty && { textProperty }), kids: kidsOf(id).map((c) => build(c, `${path};${c}`, inDefinition && !m.fileInstance)) };
683
+ }
672
684
  const own = Object.fromEntries(Object.entries(m).filter(([key]) => OWN.has(key) || key === 'fileInstance'));
673
685
  const recordOf = (main) => {
674
686
  const root = Object.fromEntries(Object.entries(byId.get(main)).filter(([key]) => !OWN.has(key)));
@@ -676,8 +688,8 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
676
688
  return m.overrides?.[''] ? applied(rec, m.overrides['']) : rec;
677
689
  };
678
690
  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) };
691
+ const swapProperty = inDefinition && m.fileInstance && binding?.(m.fileInstance, 'componentId');
692
+ return { path, binding: swapProperty, rec: recordOf(m.component), main: m.component, recordOf, instance: true, data: m.layoutData ?? {}, childrenOf, kids: childrenOf(m.component) };
681
693
  };
682
694
  const t = kidsOf(main).map((c) => build(c, c));
683
695
  trees.set(main, t);
@@ -721,13 +733,20 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
721
733
  }
722
734
  if (E.kind !== R.kind)
723
735
  return 'kind';
736
+ // Core shows one property's value in every text bound to it on an occurrence: texts that show different wording
737
+ // keep it only expanded.
738
+ const textProperty = E.kind === 'text' && n.textProperty;
739
+ if (textProperty) {
740
+ const k = 'characters\0' + textProperty;
741
+ if (bound.has(k) && bound.get(k) !== E.content)
742
+ return 'conflicting bound text';
743
+ bound.set(k, E.content);
744
+ }
724
745
  // A nested instance's appearance is its main's (the renderer draws its template root): only its own keys differ.
725
746
  const d = difference(E, R, true, false, linkPaths && (() => linkPaths.add(n.path)));
726
747
  if (typeof d === 'string')
727
748
  return d;
728
749
  const fillPath = E.kind === 'path' && fillsPath(E);
729
- if (d?.net && !fillPath)
730
- return 'net';
731
750
  if (n.instance && !E.fileInstance) {
732
751
  const own = difference(E, R, false);
733
752
  if (typeof own === 'string')
@@ -757,9 +776,8 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
757
776
  Object.assign(inputs, { storedHeight: a.storedHeight, storedRow: a.storedRow });
758
777
  }
759
778
  }
760
- // The box the expansion has where it differs from the main's, kept (keep) where core's layout of the instance does
761
- // not give it.
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 } });
779
+ // The expansion's box, kept whole (keep) where core's layout of the instance does not give what it states.
780
+ geometry.set(n.path, { E, R, fillPath, net: fillPath || !!d?.net, own: states(E, R === n.rec ? n.raw ?? R : R, byId.get(E.parent)), at: size });
763
781
  if (d || Object.keys(inputs).length)
764
782
  out[n.path] = { ...out[n.path], ...d, ...inputs };
765
783
  if (E.fileSlotHost && fills?.includes(E.fileSlotHost))
@@ -788,9 +806,9 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
788
806
  };
789
807
  // Stores the boxes (storedBox) of instance I's layers that core's layout of it (layout.ts instanceLayout: from the
790
808
  // main at its size, with its other overrides, resized to the instance's) does not give, within EPSILON. A box only
791
- // constraints or auto layout give is not stored, so a later edit of the main reaches it. A stored box changes how
792
- // the others lay out (the instance then starts at the imported size), so they are checked again with it until none
793
- // is added.
809
+ // constraints or auto layout give, or one an auto layout places where the expansion holds its main's, is not
810
+ // stored, so a later edit of the main reaches it. A stored box changes how the others lay out (the instance then starts at the imported size), so
811
+ // they are checked again with it until none is added.
794
812
  function keep(I, geometry) {
795
813
  const stored = new Set(), get = (x) => (x === I.id ? { ...I, children: [] } : view(x));
796
814
  for (let round = 0; round <= geometry.size; round++) {
@@ -799,15 +817,50 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
799
817
  for (const [path, g] of geometry)
800
818
  if (!stored.has(path) && !gives(laid.get(path), g)) {
801
819
  stored.add(path);
802
- I.overrides[path] = { ...I.overrides[path], storedBox: g.box };
820
+ const box = wholeBox(g.E, g.at);
821
+ if (!box)
822
+ return 'partial box';
823
+ I.overrides[path] = { ...I.overrides[path], storedBox: box };
803
824
  added = true;
804
825
  }
805
826
  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))
827
+ for (const [path, { E, R, fillPath, net }] of geometry) {
828
+ // The direct resize and a resize through the main may differ by roundoff; Figma's stored network of a
829
+ // constraint-scaled path is single precision, so it differs from core's by up to EPSILON.
830
+ if (net && !same(E.net, laid.get(path)?.net ?? R.net, fillPath ? 1e-6 : EPSILON))
809
831
  return 'net';
810
832
  }
833
+ // A layer with no box of its own (states) whose main's box no longer fits its parent (outside) shows on load
834
+ // the place the instance's auto layout gives it, and the size on an axis it fills, as the expanded layers do
835
+ // after a load's layout (a layer that fills its parent at its main's width in a narrower parent, a layer past the
836
+ // end of a narrower parent). A size it hugs waits for the measure of its texts (this layout has none), and so does the
837
+ // place of one whose parent or a sibling it does not fill would show another size than this layout gave it
838
+ // (settled).
839
+ const box = (path) => { const { R } = geometry.get(path); return { t: R.t, w: R.w, h: R.h, ...laid.get(path) }; };
840
+ const fills = (E, k) => sizingOf(E.layoutData, k === 'w' ? 'width' : 'height') === 'fill';
841
+ const sized = (path) => { const g = path ? geometry.get(path) : undefined; return !g || ['w', 'h'].every((k) => (!g.own && fills(g.E, k)) || near(g.E[k], box(path)[k])); };
842
+ const parentOf = (path) => path.slice(0, Math.max(0, path.lastIndexOf(';'))), siblings = new Map();
843
+ for (const path of geometry.keys()) {
844
+ const p = parentOf(path);
845
+ if (!siblings.has(p))
846
+ siblings.set(p, []);
847
+ siblings.get(p).push(path);
848
+ }
849
+ const settled = (path) => sized(parentOf(path)) && siblings.get(parentOf(path)).every(sized);
850
+ for (const [path, g] of geometry) {
851
+ const o = I.overrides[path], L = box(path);
852
+ if (g.own || o?.storedBox || !outside(g.E, byId.get(g.E.parent)) || gives(L, { ...g, own: true }) || !settled(path))
853
+ continue;
854
+ const shown = { ...o }, was = Object.fromEntries(['t', 'w', 'h'].filter((k) => o && k in o).map((k) => [k, o[k]]));
855
+ for (const k of ['t', 'w', 'h']) {
856
+ if (L[k] === undefined || (k !== 't' && !fills(g.E, k)))
857
+ continue;
858
+ if (k in shown || !(k === 't' ? nearT(L.t, g.R.t) : near(L[k], g.R[k])))
859
+ shown[k] = k === 't' ? [...L.t] : L[k];
860
+ }
861
+ I.overrides[path] = shown;
862
+ laidOut.set(shown, was);
863
+ }
811
864
  return;
812
865
  }
813
866
  }
@@ -824,8 +877,6 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
824
877
  return skip.has(variantKey(E)) ? 'used once' : 'no main';
825
878
  if (E.kind !== 'frame')
826
879
  return 'not a frame';
827
- if (!E.clip && overflows(id))
828
- return 'content outside the instance';
829
880
  if (state.get(main) === 'busy')
830
881
  return 'inside its main';
831
882
  ensure(main);
@@ -17,7 +17,17 @@ export declare function withImageCrop(_key: string, value: unknown): unknown;
17
17
  /** Moves a mark to a copy of the marked object. */
18
18
  export declare function moveMark(from: object, to: object): void;
19
19
  /** Adds `data` to the layer's `metadata.figma`. */
20
- export declare function carry(node: SceneNode, data: NonNullable<SceneNode["metadata"]>): void;
20
+ export declare function carry(node: {
21
+ metadata?: SceneNode["metadata"];
22
+ }, data: NonNullable<SceneNode["metadata"]>): void;
23
+ /** Carries the shadows and blurs of a text layer or group (`metadata.figma.effects`), with their shadow marks. */
24
+ export declare function carryEffects<T extends {
25
+ metadata?: SceneNode["metadata"];
26
+ }>(node: T, effects: {
27
+ readonly shadows?: readonly object[];
28
+ readonly layerBlur?: number;
29
+ readonly backgroundBlur?: number;
30
+ }): T;
21
31
  /** Clears a layer's constraints where Figma does not apply them. */
22
32
  export declare function clearConstraints(node: SceneNode): void;
23
33
  /** Carries the marks on a converted layer's shadows and fills into its metadata. */
@@ -36,6 +36,14 @@ export function carry(node, data) {
36
36
  const had = typeof figma === "object" && figma !== null && !Array.isArray(figma) ? figma : {};
37
37
  Object.assign(node, { metadata: { ...metadata, figma: { ...had, ...data } } });
38
38
  }
39
+ /** Carries the shadows and blurs of a text layer or group (`metadata.figma.effects`), with their shadow marks. */
40
+ export function carryEffects(node, effects) {
41
+ if (Object.keys(effects).length === 0)
42
+ return node;
43
+ const behind = (effects.shadows ?? []).flatMap((shadow, index) => marks.get(shadow)?.behind === true ? [index] : []);
44
+ carry(node, { effects: JSON.parse(JSON.stringify(effects)), ...(behind.length > 0 ? { shadowBehind: behind } : {}) });
45
+ return node;
46
+ }
39
47
  /** Clears a layer's constraints where Figma does not apply them. */
40
48
  export function clearConstraints(node) {
41
49
  if ("constraints" in node)
@@ -15,5 +15,6 @@ import type { FigmaNodeConverter } from "../walk.ts";
15
15
  *
16
16
  * A Taco group follows its layers' constraints (see `NodeBase.constraints`).
17
17
  * The adapter reads the group's own constraints from its Figma metadata.
18
+ * Moondraft patch: its shadows and blurs are carried there too (`carryEffects`).
18
19
  */
19
20
  export declare const convertGroup: FigmaNodeConverter;
@@ -1,4 +1,5 @@
1
- import { carry } from "../carry.js";
1
+ import { carry, carryEffects } from "../carry.js";
2
+ import { nodeEffects } from "./effects.js";
2
3
  import { framedBase } from "./shared.js";
3
4
  /**
4
5
  * A Figma group (a FRAME that `convertFrame` finds to be a group) as a Taco
@@ -16,9 +17,10 @@ import { framedBase } from "./shared.js";
16
17
  *
17
18
  * A Taco group follows its layers' constraints (see `NodeBase.constraints`).
18
19
  * The adapter reads the group's own constraints from its Figma metadata.
20
+ * Moondraft patch: its shadows and blurs are carried there too (`carryEffects`).
19
21
  */
20
22
  export const convertGroup = (node, walk) => {
21
- const base = framedBase(node, walk, "Group");
23
+ const base = framedBase(node, walk, "Group", true);
22
24
  if (base === null)
23
25
  return null;
24
26
  // `framedBase` sets no variable bindings; a group's type allows no width or height binding.
@@ -26,5 +28,6 @@ export const convertGroup = (node, walk) => {
26
28
  const group = { ...fields, type: "group", children: walk.convertChildren() };
27
29
  if (constraints !== undefined)
28
30
  carry(group, { groupConstraints: { ...constraints } });
31
+ carryEffects(group, nodeEffects(node, walk));
29
32
  return group;
30
33
  };
@@ -1,5 +1,7 @@
1
1
  import { field, guidText, isObject } from "../fields.js";
2
2
  import { isDetachedStyle, styleBackedList } from "../styles.js";
3
+ import { carryEffects } from "../carry.js";
4
+ import { nodeEffects } from "./effects.js";
3
5
  import { framedBase, hexColor, readNumbers } from "./shared.js";
4
6
  import { sizeLimitsOf } from "./layout.js";
5
7
  const ALIGN = { LEFT: "left", CENTER: "center", RIGHT: "right", JUSTIFIED: "justify" };
@@ -45,9 +47,12 @@ export const KEPT_LINE_HEIGHT_FIELD = "tacoKeptLineHeight";
45
47
  export const convertText = (node, walk) => {
46
48
  const where = `node ${node.id}`;
47
49
  const change = node.change;
48
- const base = framedBase(node, walk, "Text");
49
- if (base === null)
50
+ const framed = framedBase(node, walk, "Text", true);
51
+ if (framed === null)
50
52
  return null;
53
+ // Moondraft patch: the layer's shadows and blurs are carried in its metadata (`carryEffects`); the renderer casts
54
+ // them from the glyphs.
55
+ const base = carryEffects(framed, nodeEffects(node, walk));
51
56
  // Taco text has no strokes yet, so a text stroke is reported rather than dropped.
52
57
  if ((styleBackedList(change, "strokePaints", walk.styleList, where)?.length ?? 0) > 0)
53
58
  walk.report("property-left-out", "text strokes are not imported yet");
@@ -37,6 +37,16 @@ export interface StoredFigmaBox {
37
37
  }
38
38
  /** The component bindings the model drops from a layer the override is applied to, so the override must write each again. */
39
39
  export declare function bindingsDroppedBy(override: Readonly<Record<string, unknown>>): Set<string>;
40
+ /**
41
+ * `change` with the `overridden` fields merged in and without the component's bindings of the fields they change:
42
+ * Figma unbinds a field that an override sets, so the instance takes the override's value, not the component's variable.
43
+ */
44
+ export declare function withOverrides(change: FigmaObject, overridden: Readonly<Record<string, unknown>>, replacesTextStyle: boolean): FigmaObject;
45
+ /**
46
+ * A `variableConsumptionMap` with the entries of an override's own map (`over`) in place of those of the same field in
47
+ * `map`, the component layer's.
48
+ */
49
+ export declare function withBindingEntries(map: unknown, over: unknown): FigmaObject;
40
50
  /**
41
51
  * Writes `null` in each override for a binding the model would keep from a nested instance's own override (`mergeOverrides`
42
52
  * in the model) of a field the override sets plainly. Runs once every instance has its overrides, since the nested instances
@@ -43,7 +43,7 @@ function overriddenBindingFields(name, value, before) {
43
43
  * `change` with the `overridden` fields merged in and without the component's bindings of the fields they change:
44
44
  * Figma unbinds a field that an override sets, so the instance takes the override's value, not the component's variable.
45
45
  */
46
- function withOverrides(change, overridden, replacesTextStyle) {
46
+ export function withOverrides(change, overridden, replacesTextStyle) {
47
47
  const merged = { ...change, ...overridden };
48
48
  const unbound = new Set(Object.entries(overridden).flatMap(([name, value]) => overriddenBindingFields(name, value, change[name])));
49
49
  if (replacesTextStyle)
@@ -110,7 +110,7 @@ function parameterMapExtras(parameterMap, variableMap) {
110
110
  * A `variableConsumptionMap` with the entries of an override's own map (`over`) in place of those of the same field in
111
111
  * `map`, the component layer's.
112
112
  */
113
- function withBindingEntries(map, over) {
113
+ export function withBindingEntries(map, over) {
114
114
  const entriesOf = (value) => isObject(value) && Array.isArray(value["entries"]) ? value["entries"] : [];
115
115
  const fieldOf = (entry) => isObject(entry) ? entry["variableField"] : undefined;
116
116
  const overEntries = entriesOf(over);
@@ -738,13 +738,13 @@ export function instanceFields(instance, component, self, context) {
738
738
  const where = `node ${instance.id}`;
739
739
  const overrides = {};
740
740
  const overrideAt = (key) => (overrides[key] ??= {});
741
- const assignedLinks = new Map();
742
- const captureLinks = (shown, path) => (id, data, text) => {
743
- const key = `${path}/${id}`, table = data["styleOverrideTable"];
744
- if (Array.isArray(table) && table.some(row => isObject(row) && Object.hasOwn(row, "hyperlink")))
745
- assignedLinks.set(key, { shown, path, id, text, data });
746
- else
747
- assignedLinks.delete(key);
741
+ const assignedTexts = new Map();
742
+ // Each text property value at a path, for the texts bound to it that an override restyles. As in `propertyValues`,
743
+ // the last value wins, except that one passed down from a holder (`below`) yields to any other.
744
+ const captureTexts = (shown, path, below = false) => (id, data, text) => {
745
+ const key = `${path}/${id}`;
746
+ if (!below || !assignedTexts.has(key))
747
+ assignedTexts.set(key, { shown, path, id, text, data });
748
748
  };
749
749
  const componentIdOf = (symbolId) => context.component(symbolId)?.componentId;
750
750
  const swapsKept = new Set();
@@ -1068,7 +1068,7 @@ export function instanceFields(instance, component, self, context) {
1068
1068
  }
1069
1069
  }
1070
1070
  for (const [key, { shown: nested, list: values }] of below) {
1071
- const read = assignedPropertyValues(values, nested.properties, nested.variantDefs, componentIdOf, leftOutValue(nested, key), at, context.report, captureLinks(nested, key));
1071
+ const read = assignedPropertyValues(values, nested.properties, nested.variantDefs, componentIdOf, leftOutValue(nested, key), at, context.report, captureTexts(nested, key, true));
1072
1072
  const override = overrideAt(key);
1073
1073
  if (Object.keys(read).length > 0)
1074
1074
  override["propertyValues"] = { ...read, ...override["propertyValues"] };
@@ -1284,7 +1284,7 @@ export function instanceFields(instance, component, self, context) {
1284
1284
  insideLeftOut.add(entry);
1285
1285
  if (shown === undefined || shown === INSIDE_LEFT_OUT)
1286
1286
  continue;
1287
- const values = assignedPropertyValues(assignNestedValues(field(entry, name, "list", at), shown, keys, at), shown.properties, shown.variantDefs, componentIdOf, leftOutValue(shown, target.key), at, context.report, captureLinks(shown, target.key));
1287
+ const values = assignedPropertyValues(assignNestedValues(field(entry, name, "list", at), shown, keys, at), shown.properties, shown.variantDefs, componentIdOf, leftOutValue(shown, target.key), at, context.report, captureTexts(shown, target.key));
1288
1288
  if (Object.keys(values).length > 0)
1289
1289
  gathered.override["propertyValues"] = { ...gathered.override["propertyValues"], ...values };
1290
1290
  // Each swap-bound layer the values reach shows the value over a swap made below this instance (`shownAt`).
@@ -1522,10 +1522,10 @@ export function instanceFields(instance, component, self, context) {
1522
1522
  return found;
1523
1523
  };
1524
1524
  // The property values this instance gives its component, read here for the slot frames they show or hide.
1525
- const propertyValues = assignedPropertyValues(assignNestedValues(field(instance.change, "componentPropAssignments", "list", where), component, [], where), component.properties, component.variantDefs, componentIdOf, leftOutValue(component, ""), where, context.report, captureLinks(component, ""));
1526
- for (const { shown, path, id, text, data } of assignedLinks.values()) {
1525
+ const propertyValues = assignedPropertyValues(assignNestedValues(field(instance.change, "componentPropAssignments", "list", where), component, [], where), component.properties, component.variantDefs, componentIdOf, leftOutValue(component, ""), where, context.report, captureTexts(component, ""));
1526
+ for (const { shown, path, id, text, data } of assignedTexts.values()) {
1527
1527
  const table = new Map();
1528
- for (const row of data["styleOverrideTable"]) {
1528
+ for (const row of Array.isArray(data["styleOverrideTable"]) ? data["styleOverrideTable"] : []) {
1529
1529
  if (isObject(row) && typeof row["styleID"] === "number" && row["styleID"] !== 0 && Object.hasOwn(row, "hyperlink"))
1530
1530
  table.set(row["styleID"], hyperlinkOf(row["hyperlink"], context.report));
1531
1531
  }
@@ -1538,13 +1538,14 @@ export function instanceFields(instance, component, self, context) {
1538
1538
  if (!isObject(ref) || propertyByFigmaId(shown.properties, guidText(ref["defID"], where))?.definition.id !== id)
1539
1539
  continue;
1540
1540
  const key = layerPathKey([...prefix, node.id]);
1541
- const at = overrideAt(key), fields = pending.get(key)?.fields;
1542
- // A paint override can produce full paragraphs too. Use their formatting for the
1543
- // assignment unless the occurrence actually overrode its text body or links.
1544
- if (at["characters"] !== undefined || (at["paragraphs"] !== undefined &&
1545
- (fields?.["textData"] !== undefined || fields?.["hyperlink"] !== undefined)))
1541
+ // An override that restyles the text (its letter spacing or font, say, or a paint) can produce full paragraphs,
1542
+ // which carry the component's wording. Use their formatting for the assignment unless the occurrence actually
1543
+ // overrode its text body or links. Without them, only an assignment's links need writing.
1544
+ const fields = pending.get(key)?.fields, source = overrides[key]?.["paragraphs"];
1545
+ if (overrides[key]?.["characters"] !== undefined || (source === undefined ? table.size === 0
1546
+ : fields?.["textData"] !== undefined || fields?.["hyperlink"] !== undefined))
1546
1547
  continue;
1547
- const source = at["paragraphs"];
1548
+ const at = overrideAt(key);
1548
1549
  let i = 0, applied = false;
1549
1550
  const paragraphs = paragraphsFromCharacters(text, source ?? node.paragraphs).map(paragraph => {
1550
1551
  const runs = paragraph.runs.flatMap(run => {
@@ -1567,7 +1568,7 @@ export function instanceFields(instance, component, self, context) {
1567
1568
  ++i; // The paragraph break also consumes a Figma character style ID.
1568
1569
  return { ...paragraph, runs };
1569
1570
  });
1570
- if (applied)
1571
+ if (applied || source !== undefined)
1571
1572
  at["paragraphs"] = paragraphs;
1572
1573
  }
1573
1574
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondraft/import",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Editable SVG and Figma import for Moondraft.",
6
6
  "sideEffects": false,
@@ -38,7 +38,7 @@
38
38
  "license": "SEE LICENSE IN LICENSE",
39
39
  "repository": {
40
40
  "type": "git",
41
- "url": "git+https://github.com/chengluyu/design-core-renderer-rust-k3.git",
41
+ "url": "git+https://github.com/chengluyu/moondraft.git",
42
42
  "directory": "packages/import"
43
43
  },
44
44
  "files": [
@@ -52,6 +52,6 @@
52
52
  "access": "public"
53
53
  },
54
54
  "peerDependencies": {
55
- "@moondraft/editor": ">=0.5.0 <0.6.0"
55
+ "@moondraft/editor": ">=0.6.0 <0.7.0"
56
56
  }
57
57
  }