@moondraft/import 0.2.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/SOURCE.md +138 -1
  3. package/dist/adapter/convert.d.ts +2 -0
  4. package/dist/adapter/convert.js +192 -85
  5. package/dist/adapter/figma-handoff.d.ts +24 -2
  6. package/dist/adapter/figma-handoff.js +39 -18
  7. package/dist/adapter/figma.js +2 -1
  8. package/dist/adapter/file-components.d.ts +20 -1
  9. package/dist/adapter/file-components.js +91 -12
  10. package/dist/adapter/file-resources.d.ts +5 -0
  11. package/dist/adapter/file-resources.js +286 -40
  12. package/dist/adapter/file-typography.d.ts +6 -0
  13. package/dist/adapter/file-typography.js +44 -0
  14. package/dist/adapter/link.d.ts +8 -1
  15. package/dist/adapter/link.js +219 -105
  16. package/dist/adapter/payload.js +2 -2
  17. package/dist/adapter/variables.d.ts +1 -1
  18. package/dist/figma-file.d.ts +1 -0
  19. package/dist/figma-file.js +1 -0
  20. package/dist/figma.d.ts +1 -0
  21. package/dist/figma.js +41 -19
  22. package/dist/report.d.ts +37 -6
  23. package/dist/report.js +91 -18
  24. package/dist/taco/figma-import/figFile.js +3 -0
  25. package/dist/taco/figma-import/import/carry.d.ts +11 -1
  26. package/dist/taco/figma-import/import/carry.js +8 -0
  27. package/dist/taco/figma-import/import/converters/effects.d.ts +3 -13
  28. package/dist/taco/figma-import/import/converters/effects.js +4 -34
  29. package/dist/taco/figma-import/import/converters/exportSettings.js +26 -0
  30. package/dist/taco/figma-import/import/converters/frame.d.ts +1 -1
  31. package/dist/taco/figma-import/import/converters/frame.js +8 -7
  32. package/dist/taco/figma-import/import/converters/grid.d.ts +12 -0
  33. package/dist/taco/figma-import/import/converters/grid.js +97 -0
  34. package/dist/taco/figma-import/import/converters/group.d.ts +1 -0
  35. package/dist/taco/figma-import/import/converters/group.js +5 -2
  36. package/dist/taco/figma-import/import/converters/image.d.ts +1 -0
  37. package/dist/taco/figma-import/import/converters/image.js +38 -5
  38. package/dist/taco/figma-import/import/converters/layout.d.ts +5 -3
  39. package/dist/taco/figma-import/import/converters/layout.js +26 -16
  40. package/dist/taco/figma-import/import/converters/rectangle.js +2 -2
  41. package/dist/taco/figma-import/import/converters/section.js +2 -2
  42. package/dist/taco/figma-import/import/converters/shared.d.ts +2 -1
  43. package/dist/taco/figma-import/import/converters/shared.js +8 -5
  44. package/dist/taco/figma-import/import/converters/text.d.ts +24 -0
  45. package/dist/taco/figma-import/import/converters/text.js +121 -31
  46. package/dist/taco/figma-import/import/instances.d.ts +19 -3
  47. package/dist/taco/figma-import/import/instances.js +337 -60
  48. package/dist/taco/figma-import/import/types.d.ts +8 -0
  49. package/dist/taco/figma-import/import/variables.d.ts +2 -0
  50. package/dist/taco/figma-import/import/variables.js +28 -1
  51. package/dist/taco/figma-import/import/variantTrees.js +2 -0
  52. package/dist/taco/figma-import/import/walk.d.ts +9 -2
  53. package/dist/taco/figma-import/import/walk.js +69 -30
  54. package/dist/taco/figma-import/kiwi/message.js +52 -10
  55. package/dist/taco/model/codec.d.ts +1 -1
  56. package/dist/taco/model/codec.js +40 -6
  57. package/dist/taco/model/instance-resolver.js +3 -1
  58. package/dist/taco/model/types.d.ts +36 -6
  59. package/dist/taco/model/types.js +4 -0
  60. package/dist/taco/svg-import/style/computed.js +1 -0
  61. package/package.json +3 -3
@@ -1,9 +1,13 @@
1
1
  import * as editorSchema from '@moondraft/editor/schema';
2
2
  import { STYLES, VARIABLES } from '@moondraft/editor/schema';
3
- import { textColor } from '../taco/figma-import/import/converters/text.js';
3
+ import { typographyVariable } from '../taco/figma-import/import/variables.js';
4
+ import { TEXT_VARIABLE_FIELDS, textColor } from '../taco/figma-import/import/converters/text.js';
5
+ import { applyFileTypography, supportsTextField, supportsTypographyBindings } from './file-typography.js';
6
+ import { variableResolver } from './variables.js';
4
7
  import { styleAtOf, supportsRunPaint } from './link.js';
5
8
  import { guidText, isObject } from '../taco/figma-import/import/fields.js';
6
9
  import { isDetachedStyle, STYLE_REFERENCE_FIELDS } from '../taco/figma-import/import/styles.js';
10
+ import { withBindingEntries, withOverrides } from '../taco/figma-import/import/instances.js';
7
11
  import { layerPathKey, parseLayerPath } from '../taco/model/index.js';
8
12
  import { rgba, runStyle } from './convert.js';
9
13
  import { keepDescription } from './figma-descriptions.js';
@@ -73,6 +77,7 @@ const hasUniformStroke = (change) => change.borderStrokeWeightsIndependent === f
73
77
  change.strokeWeight !== undefined && !change.borderStrokeWeightsIndependent;
74
78
  const fields = {
75
79
  WIDTH: 'w', HEIGHT: 'h', STROKE_WEIGHT: 'strokeWidth', OPACITY: 'opacity', VISIBLE: 'visible', TEXT_DATA: 'content',
80
+ GRID_COLUMN_GAP: 'layoutData.layout.columnGap', GRID_ROW_GAP: 'layoutData.layout.rowGap',
76
81
  STACK_SPACING: 'layoutData.layout.gap', STACK_COUNTER_SPACING: 'layoutData.layout.wrapGap',
77
82
  CORNER_RADIUS: 'radius', RECTANGLE_TOP_LEFT_CORNER_RADIUS: 'radius.0', RECTANGLE_TOP_RIGHT_CORNER_RADIUS: 'radius.1',
78
83
  RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS: 'radius.2', RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS: 'radius.3',
@@ -134,6 +139,28 @@ function paintsAndEffects(change, m, bind, indices) {
134
139
  }
135
140
  }
136
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
+ }
137
164
  function radiusBindings(change) {
138
165
  const bindings = new Map();
139
166
  for (const e of change.variableConsumptionMap?.entries ?? []) {
@@ -200,10 +227,12 @@ function layerFields(change, m, bind) {
200
227
  for (const { variableField, variableData } of entries) {
201
228
  if (isStrokeSideBinding(variableField))
202
229
  continue; // Installed per side.
203
- if (variableField === 'FONT_SIZE' && m.styles)
230
+ if (Object.hasOwn(TEXT_VARIABLE_FIELDS, variableField) && m.styles)
204
231
  continue; // Installed per range below.
205
232
  if (variableField === 'TEXT_DATA' && variableData === undefined)
206
233
  continue; // An empty entry names no variable.
234
+ if (variableField === 'VARIANT_PROPERTIES')
235
+ continue; // Installed per variant property (install).
207
236
  let path = Object.hasOwn(fields, variableField) ? fields[variableField] : undefined;
208
237
  if (path?.startsWith('radius') && ['frame', 'rect'].includes(m.kind))
209
238
  continue; // Installed per effective corner.
@@ -213,7 +242,36 @@ function layerFields(change, m, bind) {
213
242
  || path === 'strokeWidth' && (!m.stroke || m.component && m.component !== m.id)
214
243
  || path && m.bind?.[path])
215
244
  path = undefined;
216
- bind(path, variableData, path === 'visible' ? 'boolean' : path === 'content' ? 'string' : 'number');
245
+ // Figma binds visibility to a boolean variable through IS_TRUTHY(variable).
246
+ const truthy = path === 'visible' && variableData?.dataType === 'EXPRESSION' && variableData.value?.expressionValue;
247
+ const data = truthy && truthy.expressionFunction === 'IS_TRUTHY' && truthy.expressionArguments?.length === 1 ? truthy.expressionArguments[0] : variableData;
248
+ bind(path, data, path === 'visible' ? 'boolean' : path === 'content' ? 'string' : 'number');
249
+ }
250
+ }
251
+ /**
252
+ * Binds an instance's variant choices: Figma's RESOLVE_VARIANT expression maps variant property names to string or
253
+ * boolean variables. Each becomes `component.<property id>` on the instance (or its occurrence entry `into`); an
254
+ * expression of another kind, a property its set does not declare, or a layer that is not an instance is reported.
255
+ */
256
+ function variantFields(change, m, into, records, bind, lost) {
257
+ for (const { variableField, variableData } of change.variableConsumptionMap?.entries ?? []) {
258
+ if (variableField !== 'VARIANT_PROPERTIES' || variableData === undefined)
259
+ continue;
260
+ const expression = variableData.dataType === 'EXPRESSION' ? variableData.value?.expressionValue : undefined;
261
+ const main = m.component && m.component !== m.id ? records.get(into.component ?? m.component) : undefined;
262
+ const props = main?.variant ? records.get(main.parent)?.variantSet?.props : undefined;
263
+ const choices = expression?.expressionFunction === 'RESOLVE_VARIANT' ? expression.expressionArguments?.[0]?.value?.mapValue?.values : undefined;
264
+ if (!props || !Array.isArray(choices)) {
265
+ lost();
266
+ continue;
267
+ }
268
+ for (const { key, value } of choices) {
269
+ const prop = props.find((p) => p.kind === 'variant' && p.name === key);
270
+ if (prop)
271
+ bind('component.' + prop.id, value, value?.resolvedDataType === 'BOOLEAN' ? 'boolean' : 'string');
272
+ else
273
+ lost();
274
+ }
217
275
  }
218
276
  }
219
277
  // Linking compares painted instances with their mains. A mode difference in that comparison is derived:
@@ -271,6 +329,7 @@ function sameStyleValue(style, literal) {
271
329
  return false;
272
330
  return Object.keys({ ...style, ...literal }).every(k => k === 'o' ? (style.o ?? 1) === (literal.o ?? 1) : sameStyleValue(style[k], literal[k]));
273
331
  }
332
+ const TYPOGRAPHY_FIELDS = ['size', 'family', 'style', 'weight', 'lineHeight', 'letterSpacing'];
274
333
  /** Writes the shared resources, layer references and mode choices of a saved file.
275
334
  * @param result - Reader output retaining the source relationships.
276
335
  * @param doc - Converted layers to associate with their definitions.
@@ -299,22 +358,31 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
299
358
  byKey.set(record.type + '/' + record.key, record);
300
359
  shared.push(record);
301
360
  }
302
- const textDefinitions = new Map();
361
+ const textStyleBindings = new Map();
362
+ const resolveLiteral = supportsTypographyBindings ? undefined : variableResolver(result.variableCollections);
303
363
  for (const [node, use] of textStyleUses) {
304
364
  const { id, style: text } = use.shared;
305
- const { color, ...value } = runStyle(text);
306
- textDefinitions.set(id, value);
365
+ const literal = runStyle(text);
307
366
  styleUsers.set(id, []);
308
367
  const fields = node.change.variableConsumptionMap?.entries ?? [];
309
- for (const e of fields)
310
- if (e.variableField !== 'FONT_SIZE')
368
+ const aliases = {};
369
+ for (const { variableField, variableData } of fields) {
370
+ const field = Object.hasOwn(TEXT_VARIABLE_FIELDS, variableField) && TEXT_VARIABLE_FIELDS[variableField][0];
371
+ const alias = field && typographyVariable(variables, variableField, variableData, node.id);
372
+ if (field && alias)
373
+ aliases[field] = alias;
374
+ if (!field || !alias || !supportsTextField(field))
311
375
  report.push({ kind: 'left-out', what: 'variable binding', count: 1, ids: [id] });
312
- const entry = fields.find((e) => e.variableField === 'FONT_SIZE');
313
- const size = entry && variables.positiveLengthOf(entry.variableData, node.id);
314
- if (entry && !size)
315
- report.push({ kind: 'left-out', what: 'variable binding', count: 1, ids: [id] });
316
- style(node, { ...identity(node), id, parent: STYLES, kind: 'style', type: 'text',
317
- value: size ? { ...value, size: { alias: size } } : value });
376
+ }
377
+ textStyleBindings.set(id, aliases);
378
+ const percentTracking = node.change.letterSpacing?.units === 'PERCENT';
379
+ applyFileTypography(literal, aliases, percentTracking, id => resolveLiteral?.(id, {}, variables?.aliases));
380
+ const { color, ...value } = literal;
381
+ const definition = { ...value };
382
+ for (const [field, alias] of Object.entries(aliases))
383
+ if (supportsTextField(field))
384
+ Object.assign(definition, { [field]: { alias } });
385
+ style(node, { ...identity(node), id, parent: STYLES, kind: 'style', type: 'text', value: definition });
318
386
  }
319
387
  function variableAt(path, data, type, id) {
320
388
  const variable = variables.variableOf(data, id);
@@ -348,9 +416,15 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
348
416
  function palette(entry, id, occurrence = false) {
349
417
  if (!entry.styles)
350
418
  return;
419
+ const inherited = {};
420
+ if (occurrence)
421
+ for (const source of occurrenceSources(id, false))
422
+ Object.assign(inherited, source?.vars);
423
+ const reaches = occurrence ? inheritedReach(entry, id) : () => undefined;
351
424
  // Expanded palettes may be shared by several linked records. Strip reader metadata on a copy.
352
- entry.styles = entry.styles.map((source, i) => {
353
- const { fileFontSize, fileTextColor, filePlainTextColor, fileFillStyle, filePlainFillStyle, ...s } = source;
425
+ const original = entry.styles;
426
+ entry.styles = original.map((source, i) => {
427
+ const { fileTypography = {}, fileOwnTypography = {}, fileTextColor, filePlainTextColor, fileFillStyle, filePlainFillStyle, ...s } = source;
354
428
  const { textStyle, color, paintOpacity, link: _link, figmaHyperlink: _pending, ...local } = s;
355
429
  const style = definitions.get(fileFillStyle ?? filePlainFillStyle);
356
430
  if (style) {
@@ -389,18 +463,160 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
389
463
  }
390
464
  if (textStyle)
391
465
  styleUsers.get(textStyle)?.push(id);
392
- const styleSize = textStyles.get(textStyle)?.value.size;
393
- const inherited = typeof styleSize === 'object' && styleSize.alias === fileFontSize;
394
- if (textStyle && (JSON.stringify(local) !== JSON.stringify(textDefinitions.get(textStyle)) || (fileFontSize || fileFontSize === null && typeof styleSize === 'object') && !inherited)) {
466
+ const definition = textStyles.get(textStyle)?.value;
467
+ const refs = Object.entries(fileTypography);
468
+ const sharedRefs = textStyleBindings.get(textStyle);
469
+ const sameSources = refs.every(([field, ref]) => ref === null || sharedRefs?.[field] === ref) &&
470
+ Object.entries(sharedRefs ?? {}).every(([field, ref]) => ref === fileTypography[field]);
471
+ if (textStyle && (!sameSources || !sameStyleValue(definition, local))) {
395
472
  delete s.textStyle;
396
473
  report.push({ kind: 'approximated', what: 'text style with local formatting', count: 1, ids: [id] });
397
474
  }
398
- if (fileFontSize === null)
399
- report.push({ kind: 'left-out', what: 'variable binding', count: 1, ids: [id] });
400
- else if (fileFontSize && !(inherited && s.textStyle))
401
- (entry.vars ??= {})['styles.' + i + '.size'] = fileFontSize;
475
+ for (const [field, ref] of refs) {
476
+ if (!supportsTextField(field)) {
477
+ if (!s.textStyle || !ref || sharedRefs?.[field] !== ref)
478
+ lost('variable binding', id);
479
+ }
480
+ else if (ref === null)
481
+ lost('variable binding', id);
482
+ // An occurrence's own binding stays its own, even to the main's variable, so a later main rebind leaves it.
483
+ else if (!s.textStyle && (reaches(i, field) !== ref || fileOwnTypography[field] === ref))
484
+ (entry.vars ??= {})[`styles.${i}.${field}`] = ref;
485
+ }
402
486
  return s;
403
487
  });
488
+ // A plain occurrence value masks the main's source on each own slot that source reaches, including an
489
+ // equal-valued override. A slot the main's range binding crosses keeps its value unmasked (reported by the editor).
490
+ if (occurrence)
491
+ for (let i = 0; i < original.length; i++)
492
+ for (const field of TYPOGRAPHY_FIELDS) {
493
+ const path = `styles.${i}.${field}`;
494
+ if (reaches(i, field) && !entry.vars?.[path] && !original[i]?.fileTypography?.[field])
495
+ (entry.vars ??= {})[path] = null;
496
+ }
497
+ if (occurrence)
498
+ followInheritedPaint(entry, id, inherited);
499
+ }
500
+ /** The main's typography reference that reaches each own slot of an occurrence palette, the way the editor maps it
501
+ * (core/components.ts inheritRunBindings): a binding over the whole inherited text reaches every slot; a range binding
502
+ * reaches a slot only if it covers all of that slot's characters, and none when the occurrence has its own text. */
503
+ function inheritedReach(entry, id) {
504
+ const { vars, at: baseAt, content } = inheritedTypography(id);
505
+ const ownContent = 'content' in entry && entry.content !== content;
506
+ const reach = runReach(vars, baseAt, styleAtOf(entry), ownContent);
507
+ return (slot, field) => reach.get(field)?.get(slot) ?? undefined;
508
+ }
509
+ /** Per typography field and own slot, the reference `inherited` (keyed by the slots of `before`) gives all of the
510
+ * slot's characters in `after`, or `null` once they differ (a crossing). O(the text) per field. */
511
+ function runReach(inherited, before, after, ownContent) {
512
+ const at = (runs, c) => runs.length ? runs[Math.min(c, runs.length - 1)] : 0;
513
+ const out = new Map();
514
+ for (const field of TYPOGRAPHY_FIELDS) {
515
+ const refAt = (c) => inherited[`styles.${at(before, c)}.${field}`];
516
+ let whole = refAt(0), bound = whole !== undefined;
517
+ for (let c = 1; c < Math.max(before.length, 1) && (whole !== undefined || !bound); c++) {
518
+ const ref = refAt(c);
519
+ if (ref !== whole)
520
+ whole = undefined;
521
+ if (ref !== undefined)
522
+ bound = true;
523
+ }
524
+ if (!bound)
525
+ continue;
526
+ const slots = new Map(), seen = new Set();
527
+ out.set(field, slots);
528
+ if (whole !== undefined) {
529
+ for (let c = 0; c < Math.max(after.length, 1); c++)
530
+ slots.set(at(after, c), whole);
531
+ continue;
532
+ }
533
+ if (ownContent)
534
+ continue;
535
+ for (let c = 0; c < Math.max(after.length, 1); c++) {
536
+ const s = at(after, c), ref = refAt(c) ?? null;
537
+ if (!seen.has(s)) {
538
+ seen.add(s);
539
+ slots.set(s, ref);
540
+ }
541
+ else if (slots.get(s) !== ref)
542
+ slots.set(s, null);
543
+ }
544
+ }
545
+ return out;
546
+ }
547
+ /** The typography bindings an occurrence inherits beneath its own level, keyed by the slots of the innermost level
548
+ * that styles it, with that level's runs and text. Mapped level by level from the main layer out, as the editor
549
+ * resolves nested instances (core/components.ts applyOverride): each level that brings its own palette takes the
550
+ * bindings below it by character; its own bindings and masks then replace them on its slots. */
551
+ function inheritedTypography(id) {
552
+ let vars = {}, at = [], content, styled = false;
553
+ const run = /^styles\.(\d+)\.(size|family|style|weight|lineHeight|letterSpacing)$/;
554
+ const own = (source) => {
555
+ for (const [path, ref] of Object.entries(source.vars ?? {})) {
556
+ if (!run.test(path))
557
+ continue;
558
+ if (ref)
559
+ vars[path] = ref;
560
+ else
561
+ delete vars[path];
562
+ }
563
+ };
564
+ for (const source of occurrenceSources(id, false)) {
565
+ if (!source)
566
+ continue;
567
+ if (styled && source.styles) {
568
+ const after = styleAtOf(source), reach = runReach(vars, at, after, 'content' in source && source.content !== content);
569
+ vars = {};
570
+ own(source);
571
+ for (const [field, slots] of reach)
572
+ for (const [slot, ref] of slots) {
573
+ const path = `styles.${slot}.${field}`;
574
+ if (ref && !source.styles[slot]?.textStyle && !Object.hasOwn(source.vars ?? {}, path))
575
+ vars[path] = ref;
576
+ }
577
+ at = after;
578
+ }
579
+ else {
580
+ own(source);
581
+ if (source.styles)
582
+ at = styleAtOf(source);
583
+ }
584
+ if ('content' in source)
585
+ content = source.content;
586
+ styled ||= !!source.styles;
587
+ }
588
+ return { vars, at, content };
589
+ }
590
+ // Fields a typography token also decides when it resolves (shared.ts resolveTypography, resizedStyle).
591
+ const resolvedWith = {
592
+ family: ['faceId'], style: ['weight', 'italic', 'faceId', 'variations'], weight: ['style', 'faceId', 'variations'],
593
+ size: ['lineHeight', 'letterSpacing'], lineHeight: ['lineHeightMode'], letterSpacing: [],
594
+ };
595
+ /** An occurrence palette that differs from the inherited one only in its own typography tokens stays derived, as the
596
+ * editor's own binding writes it, so the main's text colour source keeps drawing it. */
597
+ function followInheritedPaint(entry, id, inherited) {
598
+ let base;
599
+ for (const source of occurrenceSources(id, false))
600
+ if (source?.styles)
601
+ base = source;
602
+ const bound = Object.entries(entry.vars ?? {}).flatMap(([path, ref]) => {
603
+ const match = ref ? /^styles\.(\d+)\.(size|family|style|weight|lineHeight|letterSpacing)$/.exec(path) : null;
604
+ return match ? [[Number(match[1]), match[2]]] : [];
605
+ });
606
+ if (!base || !bound.length || entry.styles.length !== base.styles.length)
607
+ return;
608
+ if (!Object.entries(inherited).some(([path, ref]) => ref && /^styles\.\d+\.color$/.test(path)) && !base.styles.some((s) => s.fillStyle))
609
+ return;
610
+ if (entry.styleAt && !sameStyleValue(entry.styleAt, styleAtOf(base)))
611
+ return;
612
+ const free = entry.styles.map(() => new Set(['color', 'paintOpacity', 'fillStyle']));
613
+ for (const [slot, field] of bound)
614
+ for (const key of [field, ...resolvedWith[field]])
615
+ free[slot].add(key);
616
+ const derived = entry.styles.every((run, i) => Object.keys({ ...run, ...base.styles[i] })
617
+ .every(key => free[i].has(key) || sameStyleValue(run[key], base.styles[i][key])));
618
+ if (derived)
619
+ entry.sharedFields = ['styles'];
404
620
  }
405
621
  const lost = (what, id) => report.push({ kind: 'left-out', what, count: 1, ids: [id] });
406
622
  const isInstance = (m) => m.component && m.component !== m.id;
@@ -560,7 +776,7 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
560
776
  }
561
777
  return false;
562
778
  }
563
- // 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.
564
780
  const masked = [];
565
781
  const styled = {
566
782
  fillStyle: ['look.fills'],
@@ -644,6 +860,11 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
644
860
  delete lists[list]; // Variable-backed paints in a named style are authored on its definition.
645
861
  }
646
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]);
647
868
  const rootEntry = instance && !virtual ? m.overrides?.[''] ?? {} : into;
648
869
  if (['frame', 'rect'].includes(m.kind))
649
870
  installRadius(change, m, root, rootEntry, id, virtual);
@@ -669,11 +890,12 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
669
890
  into.content ??= expanded.get(id)?.content ?? m.content;
670
891
  }
671
892
  layerFields(change, m, bind);
893
+ variantFields(change, m, into, records, bind, () => lost('variable binding', id));
672
894
  paintsAndEffects(lists, paint, bind, result.sources);
673
895
  for (const range of change.textData?.styleOverrideTable ?? []) {
674
896
  const glyphPaint = textColor(range.fillPaints ?? []).paint;
675
897
  for (const field of range.variableConsumptionMap?.entries ?? [])
676
- if (field.variableField !== 'FONT_SIZE')
898
+ if (!Object.hasOwn(TEXT_VARIABLE_FIELDS, field.variableField))
677
899
  lost('variable binding', id);
678
900
  for (const fill of range.fillPaints ?? []) {
679
901
  if (fill.colorVar && fill !== glyphPaint)
@@ -716,6 +938,17 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
716
938
  const layers = doc.models;
717
939
  const mainLayers = new Map(layers.filter(m => m.component === m.id).map(m => [m.sourceId, m]));
718
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
+ }
719
952
  function expandedFields(m, change) {
720
953
  const source = layerSource.get(m.sourceId);
721
954
  if (expandedRadii.has(m.sourceId) && source.node.type === 'instance') {
@@ -756,19 +989,17 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
756
989
  }
757
990
  }
758
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.
759
995
  const path = [m.sourceId];
760
- for (let parent = records.get(m.parent); parent; parent = records.get(parent.parent)) {
761
- if (expandedRadii.has(parent.sourceId)) {
762
- const own = result.sources.occurrenceFields.get(parent.sourceId)?.get(layerPathKey(path));
763
- if (own) {
764
- change = { ...change, ...own };
765
- for (const [ref, list] of STYLE_REFERENCE_FIELDS)
766
- if (list in own && !(ref in own))
767
- delete change[ref];
768
- }
769
- }
770
- if (layerSource.get(parent.sourceId)?.node.type === 'instance')
771
- 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);
772
1003
  }
773
1004
  return change;
774
1005
  }
@@ -776,8 +1007,9 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
776
1007
  palette(m, m.id);
777
1008
  const source = layerSource.get(m.sourceId);
778
1009
  if (source)
779
- 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);
780
1011
  }
1012
+ const nestedPalettes = [];
781
1013
  for (const m of layers) {
782
1014
  const authored = occurrences.get(m.id);
783
1015
  const paths = new Set([...Object.keys(m.overrides ?? {}), ...authored?.keys() ?? []]);
@@ -787,6 +1019,11 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
787
1019
  const target = path ? records.get(path.split(';').at(-1)) : m;
788
1020
  if (target?.kind === 'text' && change) {
789
1021
  const textData = change.textData;
1022
+ // The linker packs a full body for formatting. An instance that only changes typography still follows the main's wording.
1023
+ if (entry.styles && textData?.characters === undefined && entry.content === target.content &&
1024
+ (Object.values(TEXT_VARIABLE_FIELDS).some(([, name]) => name in change) ||
1025
+ change.variableConsumptionMap?.entries?.some((e) => Object.hasOwn(TEXT_VARIABLE_FIELDS, e.variableField))))
1026
+ delete entry.content;
790
1027
  const painted = [change, ...(textData?.styleOverrideTable ?? [])].filter(fields => fields.fillPaints !== undefined || fields.styleIdForFill !== undefined);
791
1028
  // Even an explicitly painted run that looks identical to its main is a plain override.
792
1029
  const layer = expanded.get(id);
@@ -808,7 +1045,13 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
808
1045
  }
809
1046
  }
810
1047
  }
811
- palette(entry, id, true);
1048
+ if (entry.styles) {
1049
+ const depth = path.split(';').length;
1050
+ if (depth === 1)
1051
+ palette(entry, id, true);
1052
+ else
1053
+ (nestedPalettes[depth] ??= []).push([entry, id]);
1054
+ }
812
1055
  if (path && target && !isInstance(target)) {
813
1056
  inheritedLiterals(entry, target, change ?? {}, expanded.get(id));
814
1057
  if (!change && Object.keys(target.vars ?? {}).some(key => key.startsWith('radius.')))
@@ -822,7 +1065,10 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
822
1065
  delete m.overrides[path];
823
1066
  }
824
1067
  }
825
- // A style override replaces the slot as Figma does: bindings the occurrence inherits there no longer apply.
1068
+ // Install inner bindings before comparing an enclosing palette with the sources it inherits.
1069
+ nestedPalettes.forEach(level => { for (const [entry, id] of level)
1070
+ palette(entry, id, true); });
1071
+ // A style or paint override replaces the slot as Figma does: bindings the occurrence inherits there no longer apply.
826
1072
  for (const [entry, id, slot] of masked)
827
1073
  for (const path of inheritedBindings(id))
828
1074
  if (styled[slot].some(p => path.startsWith(p + '.')) && !Object.hasOwn(entry.vars ?? {}, path))
@@ -0,0 +1,6 @@
1
+ import type { TextStyle } from '@moondraft/editor/schema';
2
+ import type { VariableValue } from './variables.ts';
3
+ export declare const supportsTypographyBindings: boolean;
4
+ export declare const supportsTextField: (field: string) => boolean;
5
+ /** Keeps the drawn metrics and, on an older peer, the literal face in the selected mode. */
6
+ export declare function applyFileTypography(style: TextStyle, refs: Readonly<Record<string, string | null>>, percentTracking: boolean, resolve: (id: string) => VariableValue | undefined): void;
@@ -0,0 +1,44 @@
1
+ import * as editor from '@moondraft/editor/core';
2
+ import { fontStyleWeight } from '../taco/figma-import/import/converters/text.js';
3
+ // Font size bindings predate the peer’s typography binding lookup.
4
+ export const supportsTypographyBindings = 'bindingField' in editor && !!editor.bindingField('styles.0.family');
5
+ export const supportsTextField = (field) => field === 'size' || supportsTypographyBindings;
6
+ /** Keeps the drawn metrics and, on an older peer, the literal face in the selected mode. */
7
+ export function applyFileTypography(style, refs, percentTracking, resolve) {
8
+ if (!supportsTypographyBindings) {
9
+ const family = refs.family && resolve(refs.family), name = refs.style && resolve(refs.style);
10
+ const weight = refs.weight && resolve(refs.weight);
11
+ if (typeof family === 'string')
12
+ style.family = family;
13
+ if (typeof name === 'string') {
14
+ const metrics = fontStyleWeight(name);
15
+ style.style = name;
16
+ style.weight = metrics.fontWeight ?? 400;
17
+ style.italic = metrics.italic;
18
+ }
19
+ if (typeof weight === 'number') {
20
+ style.weight = weight;
21
+ if (!name)
22
+ style.style = editor.fontStyleName(weight, style.italic);
23
+ }
24
+ if ((name || weight) && style.variations?.wght !== undefined)
25
+ style.variations = { ...style.variations, wght: style.weight };
26
+ }
27
+ if (refs.lineHeight) {
28
+ const pixels = resolve(refs.lineHeight);
29
+ if (typeof pixels === 'number')
30
+ style.lineHeight = pixels;
31
+ if (supportsTypographyBindings)
32
+ style.lineHeightMode = 'px';
33
+ }
34
+ if (refs.letterSpacing && (percentTracking || !supportsTypographyBindings)) {
35
+ const spacing = resolve(refs.letterSpacing);
36
+ if (typeof spacing === 'number') {
37
+ const boundSize = percentTracking && refs.size ? resolve(refs.size) : undefined;
38
+ const size = typeof boundSize === 'number' ? boundSize : style.size;
39
+ style.letterSpacing = percentTracking ? spacing * size / 100 : spacing;
40
+ }
41
+ if (percentTracking)
42
+ style.letterSpacingMode = 'percent';
43
+ }
44
+ }
@@ -5,6 +5,12 @@ export declare const MARKERS: string[];
5
5
  * @param m - Converted model to update.
6
6
  */
7
7
  export declare const unmark: (m: any) => void;
8
+ /**
9
+ * Describes in plain words why an instance stays expanded, from linking's reason for it (LinkCounts.unlinked).
10
+ * @param reason - Linking's reason.
11
+ * @returns What the report says after "expanded instance: ".
12
+ */
13
+ export declare function expansionReason(reason: string): string;
8
14
  /** A text's style index per UTF-16 unit, from styleAt or the file's runs ([length, style]). */
9
15
  export declare function styleAtOf(m: any): any;
10
16
  export declare const supportsRunPaint: boolean;
@@ -42,8 +48,9 @@ export declare function linkComponents(doc: {
42
48
  /** @internal Links components and tracks where their expanded layers went for import reports. */
43
49
  export declare function linkWithLayers(doc: {
44
50
  models: any[];
45
- }, trackLayers?: boolean, swapBinding?: (source: string) => string | undefined, nativeFile?: boolean): {
51
+ }, trackLayers?: boolean, binding?: (source: string, field: 'componentId' | 'characters', main?: string) => string | undefined, nativeFile?: boolean): {
46
52
  counts: LinkCounts;
47
53
  aliases: Map<string, string[]>;
48
54
  omittedLinks: Map<string, Set<string>>;
55
+ expandedReasons: Map<string, string>;
49
56
  };