@moondraft/import 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/SOURCE.md +115 -1
  3. package/dist/adapter/convert.d.ts +2 -0
  4. package/dist/adapter/convert.js +175 -84
  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 +2 -1
  9. package/dist/adapter/file-components.js +5 -2
  10. package/dist/adapter/file-resources.js +234 -25
  11. package/dist/adapter/file-typography.d.ts +6 -0
  12. package/dist/adapter/file-typography.js +44 -0
  13. package/dist/adapter/link.d.ts +7 -0
  14. package/dist/adapter/link.js +87 -24
  15. package/dist/adapter/payload.js +2 -2
  16. package/dist/adapter/variables.d.ts +1 -1
  17. package/dist/figma-file.d.ts +1 -0
  18. package/dist/figma-file.js +1 -0
  19. package/dist/figma.d.ts +1 -0
  20. package/dist/figma.js +41 -19
  21. package/dist/report.d.ts +37 -6
  22. package/dist/report.js +91 -18
  23. package/dist/taco/figma-import/figFile.js +3 -0
  24. package/dist/taco/figma-import/import/converters/effects.d.ts +3 -13
  25. package/dist/taco/figma-import/import/converters/effects.js +4 -34
  26. package/dist/taco/figma-import/import/converters/exportSettings.js +26 -0
  27. package/dist/taco/figma-import/import/converters/frame.d.ts +1 -1
  28. package/dist/taco/figma-import/import/converters/frame.js +8 -7
  29. package/dist/taco/figma-import/import/converters/grid.d.ts +12 -0
  30. package/dist/taco/figma-import/import/converters/grid.js +97 -0
  31. package/dist/taco/figma-import/import/converters/image.d.ts +1 -0
  32. package/dist/taco/figma-import/import/converters/image.js +38 -5
  33. package/dist/taco/figma-import/import/converters/layout.d.ts +5 -3
  34. package/dist/taco/figma-import/import/converters/layout.js +26 -16
  35. package/dist/taco/figma-import/import/converters/rectangle.js +2 -2
  36. package/dist/taco/figma-import/import/converters/section.js +2 -2
  37. package/dist/taco/figma-import/import/converters/shared.d.ts +2 -1
  38. package/dist/taco/figma-import/import/converters/shared.js +8 -5
  39. package/dist/taco/figma-import/import/converters/text.d.ts +24 -0
  40. package/dist/taco/figma-import/import/converters/text.js +114 -29
  41. package/dist/taco/figma-import/import/instances.d.ts +9 -3
  42. package/dist/taco/figma-import/import/instances.js +319 -43
  43. package/dist/taco/figma-import/import/types.d.ts +8 -0
  44. package/dist/taco/figma-import/import/variables.d.ts +2 -0
  45. package/dist/taco/figma-import/import/variables.js +28 -1
  46. package/dist/taco/figma-import/import/variantTrees.js +2 -0
  47. package/dist/taco/figma-import/import/walk.d.ts +9 -2
  48. package/dist/taco/figma-import/import/walk.js +69 -30
  49. package/dist/taco/figma-import/kiwi/message.js +52 -10
  50. package/dist/taco/model/codec.d.ts +1 -1
  51. package/dist/taco/model/codec.js +40 -6
  52. package/dist/taco/model/instance-resolver.js +3 -1
  53. package/dist/taco/model/types.d.ts +36 -6
  54. package/dist/taco/model/types.js +4 -0
  55. package/dist/taco/svg-import/style/computed.js +1 -0
  56. package/package.json +2 -2
package/dist/report.js CHANGED
@@ -5,11 +5,45 @@ const LISTED = 3;
5
5
  // The parts of a description that vary between entries of one kind: quoted names (with escaped quotes inside), Figma
6
6
  // node IDs, numbers and Figma's upper-case enum values ("fill 2 blend mode LINEAR_BURN", "override field \"size\"").
7
7
  // Entries that differ only in these parts group.
8
- const VARYING = /"(?:[^"\\]|\\.)*"|\b\d+:\d+\b|-?\b\d+(?:\.\d+)?\b|\b[A-Z][A-Z\d]*_[A-Z\d_]*\b|\b[A-Z]{2,}[A-Z\d]*\b/g;
9
- /** The occurrence count a reader summary carries in its reason (`… (3 times, first here)`), moved into `count`. */
10
- export function readerCount(reason) {
11
- const counted = / \((\d+) times, first here\)$/.exec(reason);
12
- return counted ? { what: reason.slice(0, counted.index), count: Number(counted[1]) } : { what: reason, count: 1 };
8
+ const QUOTED = /"(?:[^"\\]|\\.)*"/y;
9
+ const UNQUOTED = /\b\d+:\d+\b|-?\b\d+(?:\.\d+)?\b|\b[A-Z][A-Z\d]*_[A-Z\d_]*\b|\b[A-Z]{2,}[A-Z\d]*\b/g;
10
+ /**
11
+ * Splits a description into its varying parts and the literal text around them (`literals` has one more item). A
12
+ * quote with no closing quote after it is literal text, and so is every quote after it, so the scan stays linear.
13
+ */
14
+ function varying(what) {
15
+ const literals = [], parts = [];
16
+ let literal = '', at = 0;
17
+ const unquoted = (end) => {
18
+ const text = what.slice(at, end);
19
+ let last = 0;
20
+ for (const m of text.matchAll(UNQUOTED)) {
21
+ literals.push(literal + text.slice(last, m.index));
22
+ parts.push(m[0]);
23
+ literal = '';
24
+ last = m.index + m[0].length;
25
+ }
26
+ literal += text.slice(last);
27
+ at = end;
28
+ };
29
+ for (let quote = what.indexOf('"'); quote !== -1; quote = what.indexOf('"', at)) {
30
+ QUOTED.lastIndex = quote;
31
+ const m = QUOTED.exec(what);
32
+ if (!m)
33
+ break;
34
+ unquoted(quote);
35
+ literals.push(literal);
36
+ parts.push(m[0]);
37
+ literal = '';
38
+ at = quote + m[0].length;
39
+ }
40
+ unquoted(what.length);
41
+ literals.push(literal);
42
+ return { literals, parts };
43
+ }
44
+ /** A reader entry's description and its occurrence count, which the reader gives as a field when it is more than one. */
45
+ export function readerCount(entry) {
46
+ return { what: entry.reason, count: entry.count ?? 1 };
13
47
  }
14
48
  /** Lists a part's distinct values: all of them up to `LISTED`, then the first ones and how many more. */
15
49
  function listed(values) {
@@ -23,9 +57,9 @@ function listed(values) {
23
57
  export function grouped(entries) {
24
58
  const out = new Map();
25
59
  for (const e of entries) {
26
- const template = e.kind === 'font' ? e.what : e.what.replace(VARYING, '\u0001');
27
- const key = `${e.kind}\u0000${template}`, had = out.get(key);
28
- const parts = e.kind === 'font' ? null : (e.what.match(VARYING) ?? []);
60
+ const split = e.kind === 'font' ? null : varying(e.what);
61
+ const key = `${e.kind}\u0000${split ? split.literals.join('\u0001') : e.what}`, had = out.get(key);
62
+ const parts = split && split.parts;
29
63
  if (had) {
30
64
  had.entry.count += e.count;
31
65
  if (e.assetIds)
@@ -41,8 +75,8 @@ export function grouped(entries) {
41
75
  }
42
76
  return [...out.values()].map(({ entry, ids, parts }) => {
43
77
  if (parts?.some(values => values.size > 1)) {
44
- let i = 0;
45
- entry.what = entry.what.replace(VARYING, () => listed([...parts[i++]]));
78
+ const { literals } = varying(entry.what);
79
+ entry.what = literals.map((text, i) => i < parts.length ? text + listed([...parts[i]]) : text).join('');
46
80
  }
47
81
  if (entry.assetIds)
48
82
  entry.assetIds = [...new Set(entry.assetIds)];
@@ -59,14 +93,48 @@ export const DROPPED_FEATURES = {
59
93
  };
60
94
  const present = (value) => Array.isArray(value) ? value.some(item => item?.isDeleted !== true) : typeof value === 'string' && value.trim() !== '';
61
95
  const guidOf = (value) => Number.isInteger(value?.sessionID) && Number.isInteger(value?.localID) ? `${value.sessionID}:${value.localID}` : undefined;
62
- /** Unsupported features in source order. Linking supplies their final layer IDs later. */
63
- export function* droppedFeatures(changes) {
96
+ /**
97
+ * Describes what a Figma layer the import left out loses with it. That layer has no layer of its own in the result to
98
+ * point to, so the description names it.
99
+ * @param what - What is lost.
100
+ * @param name - The Figma layer's name, or its type when it has none.
101
+ * @returns The description.
102
+ */
103
+ export const onLeftOutLayer = (what, name) => `${what} for the left-out layer ${JSON.stringify(name)}`;
104
+ /**
105
+ * Lists the Figma nodes the import left out with no imported copy. The reader's omitted subtrees also hold content
106
+ * that is imported elsewhere, such as a slot's content frame, which is imported as the content of the instances that
107
+ * fill the slot; a node that is imported, or holds a node that is, is not left out.
108
+ * @param sources - The reader's tree, its omitted subtrees and the nodes it imported.
109
+ * @returns The Figma IDs of the left-out nodes.
110
+ */
111
+ export function leftOutIds(sources) {
112
+ const ids = new Set(), pending = [...sources.omittedSubtrees];
113
+ while (pending.length) {
114
+ const node = pending.pop();
115
+ if (ids.has(node.id))
116
+ continue;
117
+ ids.add(node.id);
118
+ pending.push(...node.children);
119
+ }
120
+ for (const { figma } of sources.imported)
121
+ for (let at = figma; at && ids.delete(at.id); at = at.parentId === undefined ? undefined : sources.tree.nodes.get(at.parentId))
122
+ ;
123
+ return ids;
124
+ }
125
+ /**
126
+ * Unsupported features in source order. Linking supplies their final layer IDs later, except on left-out layers,
127
+ * whose entries name the layer instead.
128
+ */
129
+ export function* droppedFeatures(changes, leftOut) {
64
130
  for (const change of changes ?? []) {
65
131
  const n = change, figmaId = guidOf(n?.guid);
66
132
  if (figmaId === undefined)
67
133
  continue;
134
+ const named = leftOut.has(figmaId);
68
135
  if (present(n.prototypeInteractions))
69
- yield { figmaId, what: DROPPED_FEATURES.interactions };
136
+ yield { figmaId, leftOut: named,
137
+ what: named ? onLeftOutLayer(DROPPED_FEATURES.interactions, typeof n.name === 'string' && n.name ? n.name : String(n.type)) : DROPPED_FEATURES.interactions };
70
138
  }
71
139
  }
72
140
  /** Builds a lookup from reader IDs to their converted layers. */
@@ -87,20 +155,25 @@ function indexLayer(ids, model) {
87
155
  }
88
156
  /** Collect file diagnostics and strip reader IDs before handing the models to the editor. */
89
157
  export function figmaReportLayers(document, file) {
90
- const bySource = new Map(), pages = [], fonts = [];
158
+ const bySource = new Map(), pages = [];
91
159
  let derive = !!document.shared;
92
- for (const model of document.models) {
160
+ const models = document.models;
161
+ for (const [i, layer] of models.entries()) {
162
+ let model = layer;
93
163
  indexLayer(bySource, model);
94
164
  if (model.kind === 'page')
95
165
  pages.push(model.id);
96
166
  if (file) {
97
- collectFaces(model, fonts);
98
- delete model.sourceId;
167
+ // A copy without the reader ID: deleting a field leaves V8 a slow, larger hash table for the record.
168
+ if (Object.hasOwn(model, 'sourceId')) {
169
+ const { sourceId: _, ...rest } = model;
170
+ models[i] = model = rest;
171
+ }
99
172
  if (model.kind === 'frame' && (model.variantSet || model.props))
100
173
  derive = true;
101
174
  }
102
175
  }
103
- return { bySource, pages, fonts, derive };
176
+ return { bySource, pages, derive };
104
177
  }
105
178
  /** Turns adapter diagnostics into import reports. */
106
179
  export function convertEntries(report, details = false) {
@@ -40,6 +40,9 @@ export function readFigFile(bytes, options = {}) {
40
40
  }
41
41
  const images = new Map();
42
42
  for (const [name, data] of entries) {
43
+ const video = /^videos\/([0-9a-f]{40})(?:\.(?:mp4|webm|mov))?$/i.exec(name);
44
+ if (video)
45
+ images.set(video[1].toLowerCase(), data);
43
46
  if (name.startsWith(IMAGES_FOLDER) && name.length > IMAGES_FOLDER.length && !name.endsWith("/")) {
44
47
  images.set(name.slice(IMAGES_FOLDER.length), data);
45
48
  }
@@ -1,16 +1,6 @@
1
1
  import type { VisualStyle } from "../../../model/index.ts";
2
2
  import type { FigmaTreeNode } from "../tree.ts";
3
3
  import type { NodeWalk } from "../walk.ts";
4
- /**
5
- * True when the renderer draws a node with `style` as a plain rectangle, the
6
- * only shape whose drop shadow it shrinks for a negative spread
7
- * (`drawShadowedRect` in packages/render-core/cpp/skia/skia_adapter.cc); every
8
- * other shape's drop shadow ignores a negative spread (`buildPreparedShadows`).
9
- * Frames are drawn so when their corners are square; rectangles also need at
10
- * most one plain solid fill or a stroke with unequal per-side weights, or they are drawn as a path
11
- * (`compileRectangle` and `needsRegionFillPaints` in packages/render-core/src/page-compiler.ts).
12
- */
13
- export declare function drawnAsPlainRectangle(style: VisualStyle, isFrame: boolean): boolean;
14
4
  /**
15
5
  * The node's Figma `effects` as Taco shadows, layer blur and background blur,
16
6
  * shadows in Figma's order; a node with an effect style takes the style's
@@ -25,7 +15,7 @@ export declare function drawnAsPlainRectangle(style: VisualStyle, isFrame: boole
25
15
  * (src/converter/style.py, `convert_effects`), absent offset, radius and
26
16
  * spread are 0. Taco has no hidden shadow or blur, one layer blur and one
27
17
  * background blur, and at most 16 shadows; what does not fit is reported.
28
- * A drop shadow keeps a negative spread only when `plainRectangle` is true
29
- * (see `drawnAsPlainRectangle`); elsewhere it is drawn with spread 0 and reported.
18
+ * Moondraft patch: a negative spread is kept on every shape; the renderer
19
+ * shrinks drop shadows and grows inner shadows' holes by it.
30
20
  */
31
- export declare function nodeEffects(node: FigmaTreeNode, walk: NodeWalk, plainRectangle?: boolean): Pick<VisualStyle, "shadows" | "layerBlur" | "backgroundBlur">;
21
+ export declare function nodeEffects(node: FigmaTreeNode, walk: NodeWalk): Pick<VisualStyle, "shadows" | "layerBlur" | "backgroundBlur">;
@@ -7,27 +7,6 @@ const MAX_SHADOWS = 16;
7
7
  // Prototype-free, so an effect type such as "constructor" finds no entry.
8
8
  const SHADOW_KINDS = Object.assign(Object.create(null), { DROP_SHADOW: "drop", INNER_SHADOW: "inner" });
9
9
  const BLUR_KINDS = Object.assign(Object.create(null), { FOREGROUND_BLUR: "layerBlur", BACKGROUND_BLUR: "backgroundBlur" });
10
- /**
11
- * True when the renderer draws a node with `style` as a plain rectangle, the
12
- * only shape whose drop shadow it shrinks for a negative spread
13
- * (`drawShadowedRect` in packages/render-core/cpp/skia/skia_adapter.cc); every
14
- * other shape's drop shadow ignores a negative spread (`buildPreparedShadows`).
15
- * Frames are drawn so when their corners are square; rectangles also need at
16
- * most one plain solid fill or a stroke with unequal per-side weights, or they are drawn as a path
17
- * (`compileRectangle` and `needsRegionFillPaints` in packages/render-core/src/page-compiler.ts).
18
- */
19
- export function drawnAsPlainRectangle(style, isFrame) {
20
- const square = (style.cornerRadius ?? 0) === 0 && Object.values(style.cornerRadii ?? {}).every((radius) => radius === 0);
21
- if (!square || isFrame)
22
- return square;
23
- // A stroke with unequal per-side weights makes the rectangle a container, whatever its fills (`hasSidedStroke`).
24
- const sidedStroke = style.strokes?.some(({ sides }) => sides !== undefined
25
- && !(sides.right === sides.top && sides.bottom === sides.top && sides.left === sides.top)) ?? false;
26
- if (sidedStroke)
27
- return true;
28
- const fills = style.fills ?? [];
29
- return fills.length <= 1 && fills.every((paint) => paint.kind === "solid" && paint.visible !== false && (paint.blendMode ?? "normal") === "normal");
30
- }
31
10
  /**
32
11
  * The node's Figma `effects` as Taco shadows, layer blur and background blur,
33
12
  * shadows in Figma's order; a node with an effect style takes the style's
@@ -42,10 +21,10 @@ export function drawnAsPlainRectangle(style, isFrame) {
42
21
  * (src/converter/style.py, `convert_effects`), absent offset, radius and
43
22
  * spread are 0. Taco has no hidden shadow or blur, one layer blur and one
44
23
  * background blur, and at most 16 shadows; what does not fit is reported.
45
- * A drop shadow keeps a negative spread only when `plainRectangle` is true
46
- * (see `drawnAsPlainRectangle`); elsewhere it is drawn with spread 0 and reported.
24
+ * Moondraft patch: a negative spread is kept on every shape; the renderer
25
+ * shrinks drop shadows and grows inner shadows' holes by it.
47
26
  */
48
- export function nodeEffects(node, walk, plainRectangle = false) {
27
+ export function nodeEffects(node, walk) {
49
28
  const where = `node ${node.id}`;
50
29
  const shadows = [];
51
30
  const boundZeroBlurs = new Map();
@@ -91,7 +70,7 @@ export function nodeEffects(node, walk, plainRectangle = false) {
91
70
  const offset = field(effect, "offset", "object", at) ?? {};
92
71
  const x = field(offset, "x", "number", `${at} offset`) ?? 0;
93
72
  const y = field(offset, "y", "number", `${at} offset`) ?? 0;
94
- let spread = field(effect, "spread", "number", at) ?? 0;
73
+ const spread = field(effect, "spread", "number", at) ?? 0;
95
74
  const colorObject = field(effect, "color", "object", at);
96
75
  const color = colorObject && readNumbers(colorObject, ["r", "g", "b", "a"], `${at} color`);
97
76
  if (!color)
@@ -101,15 +80,6 @@ export function nodeEffects(node, walk, plainRectangle = false) {
101
80
  // Moondraft patch (../carry.ts): Moondraft knocks a drop shadow out under the node's fill, as Figma does unless
102
81
  // showShadowBehindNode is set; such a shadow is marked, and the see-through fill is no longer reported.
103
82
  const behind = shadowKind === "drop" && field(effect, "showShadowBehindNode", "boolean", at) === true;
104
- if (shadowKind === "inner" && spread < 0) {
105
- // The renderer grows an inner shadow only inward and treats a negative spread as 0.
106
- walk.report("approximated", `${label} (${type}) spread ${String(spread)} is below 0; Taco draws inner shadows with spread 0`);
107
- spread = 0;
108
- }
109
- if (shadowKind === "drop" && spread < 0 && !plainRectangle) {
110
- walk.report("approximated", `${label} (${type}) spread ${String(spread)} is below 0; Taco shrinks drop shadows only on square-cornered rectangles and frames, so spread 0 is used`);
111
- spread = 0;
112
- }
113
83
  const shadow = { kind: shadowKind, x, y, blur: radius, spread, color: hexColor(color) };
114
84
  if (behind)
115
85
  markShadowBehind(shadow);
@@ -1,5 +1,26 @@
1
1
  import { defaultExportQuality, exportConstraintProblem, exportSuffixProblem, MAX_EXPORT_SETTINGS } from "../../../model/export-settings.js";
2
2
  import { isObject } from "../fields.js";
3
+ /**
4
+ * Figma row fields with no counterpart in a Taco row, each with the formats it
5
+ * affects and the value that changes the file: a row whose field holds
6
+ * another value (Figma's own default included) exports as Taco would anyway.
7
+ */
8
+ const UNKEPT_FIELDS = [
9
+ { field: "svgOutlineText", formats: ["svg"], kept: (value) => value !== false },
10
+ { field: "svgDataName", formats: ["svg"], kept: (value) => value !== true },
11
+ { field: "svgForceStrokeMasks", formats: ["svg"], kept: (value) => value !== true },
12
+ { field: "useAbsoluteBounds", formats: ["png", "jpeg", "svg", "pdf"], kept: (value) => value !== true },
13
+ { field: "colorProfile", formats: ["png", "jpeg", "svg", "pdf"], kept: (value) => value === undefined || value === "DOCUMENT" },
14
+ { field: "quality", formats: ["jpeg", "pdf"], kept: (value) => value === undefined },
15
+ { field: "useBicubicSampler", formats: ["png", "jpeg", "pdf"], kept: (value) => value !== false },
16
+ { field: "pdfPrint", formats: ["pdf"], kept: (value) => value !== true },
17
+ ];
18
+ /**
19
+ * Rows whose unkept fields are reported: the editor keeps the first 32 rows,
20
+ * and the adapter reports each later row whole, so its fields are not
21
+ * reported again.
22
+ */
23
+ const FIELD_REPORTED_ROWS = 32;
3
24
  /** Reads the export rows stored by a layer or by an instance's root override. */
4
25
  export function exportSettingsOf(value, report) {
5
26
  if (value === undefined)
@@ -37,6 +58,11 @@ export function exportSettingsOf(value, report) {
37
58
  report("property-left-out", "an export setting beyond the reader's list limit is left out");
38
59
  continue;
39
60
  }
61
+ if (settings.length < FIELD_REPORTED_ROWS)
62
+ for (const { field, formats, kept } of UNKEPT_FIELDS) {
63
+ if (formats.includes(format) && !kept(row[field]))
64
+ report("property-left-out", `an export setting's ${field} is left out`);
65
+ }
40
66
  settings.push({
41
67
  format, constraint: { type: unit, value: amount }, suffix,
42
68
  quality: defaultExportQuality(format),
@@ -2,7 +2,7 @@ import { type FigmaObject } from "../fields.ts";
2
2
  import type { FigmaNodeConverter } from "../walk.ts";
3
3
  /**
4
4
  * A Figma FRAME as a Taco frame, with its HORIZONTAL or VERTICAL auto layout
5
- * as a stack (see `stackLayoutOf`) and free layout otherwise. Frames clip unless
5
+ * as a stack (see `autoLayoutOf`) and free layout otherwise. Frames clip unless
6
6
  * `frameMaskDisabled` is true (grida, packages/grida-canvas-io-figma/lib.ts:4246).
7
7
  * Figma stores a group as a FRAME. `resizeToFit` alone does not prove it, so a
8
8
  * FRAME counts as a group only when it also clips (`frameMaskDisabled` is
@@ -1,13 +1,13 @@
1
1
  import { carry } from "../carry.js";
2
2
  import { field } from "../fields.js";
3
3
  import { gridStyleReference } from "../styles.js";
4
- import { drawnAsPlainRectangle, nodeEffects } from "./effects.js";
5
- import { stackLayoutOf } from "./layout.js";
4
+ import { nodeEffects } from "./effects.js";
5
+ import { autoLayoutOf } from "./layout.js";
6
6
  import { convertGroup } from "./group.js";
7
7
  import { framedBase, visualStyle } from "./shared.js";
8
8
  /**
9
9
  * A Figma FRAME as a Taco frame, with its HORIZONTAL or VERTICAL auto layout
10
- * as a stack (see `stackLayoutOf`) and free layout otherwise. Frames clip unless
10
+ * as a stack (see `autoLayoutOf`) and free layout otherwise. Frames clip unless
11
11
  * `frameMaskDisabled` is true (grida, packages/grida-canvas-io-figma/lib.ts:4246).
12
12
  * Figma stores a group as a FRAME. `resizeToFit` alone does not prove it, so a
13
13
  * FRAME counts as a group only when it also clips (`frameMaskDisabled` is
@@ -18,7 +18,7 @@ import { framedBase, visualStyle } from "./shared.js";
18
18
  * fields is still a component or an instance, so it imports as a frame.
19
19
  */
20
20
  export const convertFrame = (node, walk) => {
21
- const stackMode = field(node.change, "stackMode", "string", `node ${node.id}`);
21
+ field(node.change, "stackMode", "string", `node ${node.id}`);
22
22
  // The paint lists are checked here, so a malformed list is refused rather than read as "not a group".
23
23
  for (const name of ["fillPaints", "strokePaints", "backgroundPaints"])
24
24
  field(node.change, name, "list", `node ${node.id}`);
@@ -28,16 +28,17 @@ export const convertFrame = (node, walk) => {
28
28
  if (base === null)
29
29
  return null;
30
30
  const visual = visualStyle(node, walk);
31
- const style = { ...visual, ...nodeEffects(node, walk, drawnAsPlainRectangle(visual, true)) };
31
+ const style = { ...visual, ...nodeEffects(node, walk) };
32
32
  const frame = {
33
33
  ...base,
34
34
  type: "frame",
35
35
  children: walk.convertChildren(),
36
- layout: stackLayoutOf(node.change, walk.report) ?? { kind: "absolute" },
36
+ // An instance can inherit the track IDs its sizing refers to. Report grid fields once the main is known.
37
+ layout: autoLayoutOf(node.change, walk.report, node.type === "INSTANCE" ? () => { } : undefined) ?? { kind: "absolute" },
37
38
  clipContent: node.change["frameMaskDisabled"] !== true,
38
39
  ...(Object.keys(style).length > 0 ? { style } : {}),
39
40
  };
40
- if ((frame.layout.kind === "horizontal" || frame.layout.kind === "vertical") && node.change["bordersTakeSpace"] === true) {
41
+ if (frame.layout.kind !== "absolute" && node.change["bordersTakeSpace"] === true) {
41
42
  carry(frame, { strokesIncluded: true });
42
43
  }
43
44
  return frame;
@@ -0,0 +1,12 @@
1
+ import type { GridTrack } from "../../../model/types.ts";
2
+ import { type FigmaObject } from "../fields.ts";
3
+ type Lost = (field: string) => void;
4
+ export declare const gridChildFields: Set<string>;
5
+ export declare function reportUnknownGridFields(change: FigmaObject, lost: Lost): void;
6
+ /** Join sizing records to the ordered GUIDs. Children reference this same order by ID. */
7
+ export declare function gridAxis(change: FigmaObject, name: "gridRows" | "gridColumns", lost: Lost): {
8
+ indices: Map<string, number>;
9
+ tracks: GridTrack[];
10
+ };
11
+ export declare function gridCell(change: FigmaObject, rows: Map<string, number>, columns: Map<string, number>, lost: Lost, override?: boolean): Record<string, string | number>;
12
+ export {};
@@ -0,0 +1,97 @@
1
+ import { isObject } from "../fields.js";
2
+ const guid = (v) => isObject(v) && Number.isInteger(v.sessionID) && Number.isInteger(v.localID)
3
+ ? `${v.sessionID}:${v.localID}` : undefined;
4
+ const frameFields = ["gridColumns", "gridRows", "gridColumnsSizing", "gridRowsSizing", "gridRowGap", "gridColumnGap"];
5
+ export const gridChildFields = new Set(["gridColumnAnchor", "gridRowAnchor", "gridColumnSpan", "gridRowSpan", "gridChildHorizontalAlign", "gridChildVerticalAlign"]);
6
+ const knownFields = new Set([...frameFields, ...gridChildFields]);
7
+ export function reportUnknownGridFields(change, lost) {
8
+ for (const name of Object.keys(change))
9
+ if (name.startsWith("grid") && !knownFields.has(name))
10
+ lost(name);
11
+ }
12
+ function entries(raw, field, lost) {
13
+ if (raw === undefined)
14
+ return [];
15
+ if (isObject(raw) && Array.isArray(raw.entries))
16
+ return raw.entries;
17
+ lost(field);
18
+ return [];
19
+ }
20
+ function trackSize(raw) {
21
+ if (!isObject(raw))
22
+ return;
23
+ if (raw.type === "HUG")
24
+ return { kind: "auto" };
25
+ const n = raw.value;
26
+ if (raw.type === "FLEX" && (n === undefined || typeof n === "number" && Number.isFinite(n) && n > 0))
27
+ return { kind: "fill", weight: n ?? 1 };
28
+ if (raw.type === "FIXED" && typeof n === "number" && Number.isFinite(n) && n >= 0)
29
+ return { kind: "fixed", size: n };
30
+ }
31
+ /** Join sizing records to the ordered GUIDs. Children reference this same order by ID. */
32
+ export function gridAxis(change, name, lost) {
33
+ const order = new Map();
34
+ for (const e of entries(change[name], name, lost)) {
35
+ const id = isObject(e) && guid(e.id);
36
+ if (!id || !isObject(e) || typeof e.position !== "string" || order.has(id)) {
37
+ lost(name);
38
+ continue;
39
+ }
40
+ order.set(id, e.position);
41
+ }
42
+ const ids = [...order.keys()].sort((a, b) => order.get(a) < order.get(b) ? -1 : order.get(a) > order.get(b) ? 1 : 0);
43
+ const indices = new Map(ids.map((id, index) => [id, index]));
44
+ const tracks = Array.from({ length: Math.max(1, ids.length) }, () => ({ kind: "fill" }));
45
+ const field = name + "Sizing";
46
+ for (const e of entries(change[field], field, lost)) {
47
+ const id = isObject(e) && guid(e.id), i = id ? indices.get(id) : undefined;
48
+ if (i === undefined || !isObject(e) || !isObject(e.trackSize)) {
49
+ lost(field);
50
+ continue;
51
+ }
52
+ const { minSizing, maxSizing } = e.trackSize;
53
+ const min = trackSize(minSizing), max = trackSize(maxSizing);
54
+ if (minSizing !== undefined && (!min || max && JSON.stringify(min) !== JSON.stringify(max)))
55
+ lost(field + ".minSizing");
56
+ if (maxSizing !== undefined && !max)
57
+ lost(field + ".maxSizing");
58
+ if (!min && !max && minSizing === undefined && maxSizing === undefined)
59
+ lost(field);
60
+ tracks[i] = max ?? min ?? tracks[i];
61
+ }
62
+ return { indices, tracks };
63
+ }
64
+ export function gridCell(change, rows, columns, lost, override = false) {
65
+ if (!override && change.stackMode !== "GRID")
66
+ reportUnknownGridFields(change, lost);
67
+ const cell = {};
68
+ for (const [name, ids, align, key] of [["Row", rows, "Vertical", "alignY"], ["Column", columns, "Horizontal", "alignX"]]) {
69
+ const axis = name.toLowerCase(), anchorField = "grid" + name + "Anchor", anchor = change[anchorField];
70
+ if (anchor !== undefined) {
71
+ const id = guid(anchor), i = id && ids.get(id);
72
+ if (typeof i === "number" && i <= 65535)
73
+ cell[axis] = i;
74
+ else
75
+ lost(anchorField);
76
+ }
77
+ const spanField = "grid" + name + "Span", span = change[spanField];
78
+ if (span !== undefined) {
79
+ if (typeof span === "number" && Number.isInteger(span) && span > 0 && span <= 65535)
80
+ cell[axis + "Span"] = span;
81
+ else
82
+ lost(spanField);
83
+ }
84
+ const field = "gridChild" + align + "Align", value = change[field];
85
+ if (value === "MIN" || (override && value === "AUTO"))
86
+ cell[key] = "start";
87
+ else if (value === "CENTER")
88
+ cell[key] = "center";
89
+ else if (value === "MAX")
90
+ cell[key] = "end";
91
+ else if (value === "STRETCH")
92
+ cell[key] = "stretch";
93
+ else if (value !== undefined && value !== "AUTO")
94
+ lost(field);
95
+ }
96
+ return cell;
97
+ }
@@ -3,6 +3,7 @@ import { type FigmaObject } from "../fields.ts";
3
3
  import type { NodeWalk } from "../walk.ts";
4
4
  /** The MIME type of PNG, JPEG, GIF and WebP bytes, read from their first bytes; `undefined` for anything else. */
5
5
  export declare function sniffImageMimeType(bytes: Uint8Array): string | undefined;
6
+ export declare function sniffVideoMimeType(bytes: Uint8Array): string | undefined;
6
7
  export declare function hexText(bytes: Uint8Array): string;
7
8
  /**
8
9
  * A Figma IMAGE paint as a Taco image paint whose asset the host supplied
@@ -14,6 +14,13 @@ export function sniffImageMimeType(bytes) {
14
14
  return "image/webp";
15
15
  return undefined;
16
16
  }
17
+ export function sniffVideoMimeType(bytes) {
18
+ if (bytes[0] === 0x1a && bytes[1] === 0x45 && bytes[2] === 0xdf && bytes[3] === 0xa3)
19
+ return "video/webm";
20
+ if (String.fromCharCode(...bytes.subarray(4, 8)) === "ftyp")
21
+ return String.fromCharCode(...bytes.subarray(8, 12)) === "qt " ? "video/quicktime" : "video/mp4";
22
+ return undefined;
23
+ }
17
24
  export function hexText(bytes) {
18
25
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
19
26
  }
@@ -52,13 +59,39 @@ function imageFit(paint, at) {
52
59
  * and image adjustments (`paintFilter`, `filterColorAdjust`) are reported, not kept.
53
60
  */
54
61
  export function imagePaint(paint, at, label, walk, fill) {
55
- const image = field(paint, "image", "object", at);
56
- const hash = image?.["hash"];
57
- if (!(hash instanceof Uint8Array) || hash.length === 0)
58
- return "the image paint has no image hash";
62
+ const isVideo = paint.type === "VIDEO";
59
63
  const width = field(paint, "originalImageWidth", "number", at);
60
64
  const height = field(paint, "originalImageHeight", "number", at);
61
- const asset = walk.image(hexText(hash), width !== undefined && height !== undefined ? { width, height } : undefined);
65
+ const size = width !== undefined && height !== undefined ? { width, height } : undefined;
66
+ const read = (name) => {
67
+ const ref = field(paint, name, "object", at), hash = ref?.hash;
68
+ if (!(hash instanceof Uint8Array) || !hash.length)
69
+ return "the image paint has no image hash";
70
+ const bytes = isVideo && typeof ref?.dataBlob === "number" ? walk.blob(ref.dataBlob) : undefined;
71
+ return walk.image(hexText(hash), size, bytes ? { bytes } : undefined);
72
+ };
73
+ let asset = read("image");
74
+ if (isVideo) {
75
+ if (!asset || typeof asset === "string" || asset.placeholder) {
76
+ const thumbnail = read("imageThumbnail");
77
+ if (thumbnail && typeof thumbnail !== "string")
78
+ asset = thumbnail;
79
+ }
80
+ const poster = asset && typeof asset !== "string" && !asset.placeholder ? asset : undefined;
81
+ const hash = field(paint, "video", "object", at)?.hash;
82
+ const clip = hash instanceof Uint8Array && hash.length ? walk.image(hexText(hash), size, { video: true, ...(poster && { poster }) }) : undefined;
83
+ if (clip && typeof clip !== "string") {
84
+ asset = clip;
85
+ if (!clip.poster)
86
+ walk.report("property-left-out", `${label}: no poster supplied on this video fill`);
87
+ }
88
+ else if (poster)
89
+ walk.report("approximated", `${label}: video media unavailable, kept its poster as an image`);
90
+ else if (!asset || typeof asset === "string")
91
+ return "video media and poster unavailable";
92
+ else
93
+ walk.report("property-left-out", `${label}: video media and poster unavailable`);
94
+ }
62
95
  if (asset === null || typeof asset === "string")
63
96
  return asset;
64
97
  const { fit, approximated, tile, crop } = imageFit(paint, at);
@@ -1,15 +1,17 @@
1
- import type { FrameNode, FramedNodeBase, NodeResizing, SceneNode, StackAutoLayout, TextNode } from "../../../model/index.ts";
1
+ import type { FrameNode, FramedNodeBase, NodeResizing, SceneNode, TextNode } from "../../../model/index.ts";
2
2
  import { type FigmaObject } from "../fields.ts";
3
3
  import type { FigmaImportReportKind } from "../types.ts";
4
4
  type Report = (kind: FigmaImportReportKind, reason: string) => void;
5
5
  /**
6
- * A Figma HORIZONTAL or VERTICAL auto layout as a Taco stack, or `undefined`
6
+ * A Figma grid or stack as a Taco auto layout, or `undefined`
7
7
  * for free layout. The walk turns the stack off again unless every child in
8
8
  * the flow was imported and is visible (see `stackBlocker`). An absent
9
9
  * `stackPrimarySizing` hugs and an absent `stackCounterSizing` is fixed, as
10
10
  * measured on real Figma files.
11
11
  */
12
- export declare function stackLayoutOf(change: FigmaObject, report: Report): StackAutoLayout | undefined;
12
+ export declare function autoLayoutOf(change: FigmaObject, report: Report, lost?: (field: string) => void): Exclude<FrameNode["layout"], {
13
+ kind: "absolute";
14
+ }> | undefined;
13
15
  /** `minSize` and `maxSize` as Taco size limits; Figma writes 0 for an unset limit. */
14
16
  export declare function sizeLimitsOf(change: FigmaObject): NodeResizing;
15
17
  /**
@@ -1,4 +1,5 @@
1
1
  import { getVectorNetworkBounds } from "../../../model/index.js";
2
+ import { gridAxis, reportUnknownGridFields } from "./grid.js";
2
3
  import { carry, clearConstraints } from "../carry.js";
3
4
  import { isObject } from "../fields.js";
4
5
  /**
@@ -29,40 +30,49 @@ const JUSTIFY = {
29
30
  const ALIGN = { MIN: "start", CENTER: "center", MAX: "end" };
30
31
  const SIZING = { FIXED: "fixed", RESIZE_TO_FIT: "hug", RESIZE_TO_FIT_WITH_IMPLICIT_SIZE: "hug" };
31
32
  /**
32
- * A Figma HORIZONTAL or VERTICAL auto layout as a Taco stack, or `undefined`
33
+ * A Figma grid or stack as a Taco auto layout, or `undefined`
33
34
  * for free layout. The walk turns the stack off again unless every child in
34
35
  * the flow was imported and is visible (see `stackBlocker`). An absent
35
36
  * `stackPrimarySizing` hugs and an absent `stackCounterSizing` is fixed, as
36
37
  * measured on real Figma files.
37
38
  */
38
- export function stackLayoutOf(change, report) {
39
+ export function autoLayoutOf(change, report, lost = (field) => report("property-left-out", `grid layout field ${field}`)) {
39
40
  const mode = change["stackMode"];
40
- if (mode === "GRID") {
41
- report("property-left-out", "grid auto layout is not imported yet; children keep their positions");
42
- return undefined;
43
- }
44
- if (mode !== "HORIZONTAL" && mode !== "VERTICAL")
41
+ if (mode !== "GRID" && mode !== "HORIZONTAL" && mode !== "VERTICAL")
45
42
  return undefined;
46
43
  const vertical = mode === "VERTICAL";
47
- const justify = enumField(change, "stackPrimaryAlignItems", JUSTIFY);
48
- if (justify === null)
49
- report("property-left-out", `stackPrimaryAlignItems ${String(change["stackPrimaryAlignItems"])} is not imported; children pack from the start`);
50
- const align = enumField(change, "stackCounterAlignItems", ALIGN);
51
- if (align === null)
52
- report("approximated", `stackCounterAlignItems ${String(change["stackCounterAlignItems"])} is imported as start`);
53
- const primary = enumField(change, "stackPrimarySizing", SIZING) ?? "hug";
54
- const counter = enumField(change, "stackCounterSizing", SIZING) ?? "fixed";
55
44
  // Figma's file omits a padding field that is 0, on every side: a missing
56
45
  // `stackPaddingRight` or `stackPaddingBottom` is 0, not a copy of the left or
57
46
  // top padding. Only the legacy single `stackPadding` stands in for all four.
58
47
  const all = numberField(change, "stackPadding") ?? 0;
59
48
  const left = numberField(change, "stackHorizontalPadding") ?? all;
60
49
  const top = numberField(change, "stackVerticalPadding") ?? all;
50
+ const padding = { left, right: numberField(change, "stackPaddingRight") ?? all, top, bottom: numberField(change, "stackPaddingBottom") ?? all };
51
+ const primary = enumField(change, "stackPrimarySizing", SIZING) ?? (mode === "GRID" ? "fixed" : "hug");
52
+ const counter = enumField(change, "stackCounterSizing", SIZING) ?? "fixed";
53
+ if (mode === "GRID") {
54
+ reportUnknownGridFields(change, lost);
55
+ const rows = gridAxis(change, "gridRows", lost), columns = gridAxis(change, "gridColumns", lost);
56
+ function gap(field) {
57
+ const value = numberField(change, field);
58
+ if (value === undefined && change[field] !== undefined)
59
+ lost(field);
60
+ return value ?? 0;
61
+ }
62
+ return { kind: "grid", columns: columns.tracks.length, columnTracks: columns.tracks, rowTracks: rows.tracks,
63
+ columnGap: gap("gridColumnGap"), rowGap: gap("gridRowGap"), padding, heightSizing: counter, widthSizing: primary };
64
+ }
65
+ const justify = enumField(change, "stackPrimaryAlignItems", JUSTIFY);
66
+ if (justify === null)
67
+ report("property-left-out", `stackPrimaryAlignItems ${String(change["stackPrimaryAlignItems"])} is not imported; children pack from the start`);
68
+ const align = enumField(change, "stackCounterAlignItems", ALIGN);
69
+ if (align === null)
70
+ report("approximated", `stackCounterAlignItems ${String(change["stackCounterAlignItems"])} is imported as start`);
61
71
  const wrapGap = numberField(change, "stackCounterSpacing");
62
72
  return {
63
73
  kind: vertical ? "vertical" : "horizontal",
64
74
  gap: numberField(change, "stackSpacing") ?? 0,
65
- padding: { left, right: numberField(change, "stackPaddingRight") ?? all, top, bottom: numberField(change, "stackPaddingBottom") ?? all },
75
+ padding,
66
76
  align: align ?? "start",
67
77
  justify: justify ?? "start",
68
78
  ...(change["stackWrap"] === "WRAP"