@moondraft/import 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +2 -2
- package/SOURCE.md +229 -4
- package/dist/adapter/convert.d.ts +24 -2
- package/dist/adapter/convert.js +669 -160
- package/dist/adapter/figma-descriptions.d.ts +7 -0
- package/dist/adapter/figma-descriptions.js +34 -0
- package/dist/adapter/figma-grids.d.ts +12 -0
- package/dist/adapter/figma-grids.js +175 -0
- package/dist/adapter/figma-handoff.d.ts +12 -0
- package/dist/adapter/figma-handoff.js +167 -0
- package/dist/adapter/figma-hyperlinks.d.ts +13 -0
- package/dist/adapter/figma-hyperlinks.js +77 -0
- package/dist/adapter/figma.d.ts +4 -1
- package/dist/adapter/figma.js +14 -4
- package/dist/adapter/file-components.d.ts +9 -3
- package/dist/adapter/file-components.js +122 -32
- package/dist/adapter/file-resources.js +316 -27
- package/dist/adapter/image-crop.d.ts +18 -0
- package/dist/adapter/image-crop.js +30 -0
- package/dist/adapter/link.d.ts +5 -1
- package/dist/adapter/link.js +308 -104
- package/dist/adapter/payload.js +1 -1
- package/dist/adapter/variables.d.ts +2 -1
- package/dist/adapter/variables.js +5 -2
- package/dist/figma.js +167 -33
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/report.d.ts +28 -1
- package/dist/report.js +102 -29
- package/dist/serialize.d.ts +7 -0
- package/dist/serialize.js +79 -0
- package/dist/taco/figma-import/container/kiwiContainer.d.ts +3 -0
- package/dist/taco/figma-import/container/kiwiContainer.js +1 -1
- package/dist/taco/figma-import/import/carry.d.ts +14 -1
- package/dist/taco/figma-import/import/carry.js +34 -1
- package/dist/taco/figma-import/import/componentProps.d.ts +10 -4
- package/dist/taco/figma-import/import/componentProps.js +29 -13
- package/dist/taco/figma-import/import/componentSets.d.ts +2 -0
- package/dist/taco/figma-import/import/componentSets.js +1 -1
- package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
- package/dist/taco/figma-import/import/converters/exportSettings.js +49 -0
- package/dist/taco/figma-import/import/converters/frame.js +8 -0
- package/dist/taco/figma-import/import/converters/gradient.d.ts +2 -0
- package/dist/taco/figma-import/import/converters/gradient.js +3 -1
- package/dist/taco/figma-import/import/converters/group.d.ts +2 -4
- package/dist/taco/figma-import/import/converters/group.js +6 -15
- package/dist/taco/figma-import/import/converters/image.d.ts +1 -1
- package/dist/taco/figma-import/import/converters/image.js +22 -11
- package/dist/taco/figma-import/import/converters/layout.d.ts +3 -4
- package/dist/taco/figma-import/import/converters/layout.js +40 -21
- package/dist/taco/figma-import/import/converters/rectangle.d.ts +1 -1
- package/dist/taco/figma-import/import/converters/rectangle.js +1 -1
- package/dist/taco/figma-import/import/converters/section.d.ts +2 -3
- package/dist/taco/figma-import/import/converters/section.js +3 -9
- package/dist/taco/figma-import/import/converters/shared.d.ts +7 -4
- package/dist/taco/figma-import/import/converters/shared.js +15 -5
- package/dist/taco/figma-import/import/converters/text.d.ts +14 -1
- package/dist/taco/figma-import/import/converters/text.js +143 -12
- package/dist/taco/figma-import/import/converters/vector.d.ts +36 -15
- package/dist/taco/figma-import/import/converters/vector.js +214 -73
- package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +19 -3
- package/dist/taco/figma-import/import/converters/vectorNetwork.js +147 -29
- package/dist/taco/figma-import/import/instances.d.ts +25 -4
- package/dist/taco/figma-import/import/instances.js +324 -117
- package/dist/taco/figma-import/import/styles.d.ts +2 -0
- package/dist/taco/figma-import/import/styles.js +6 -0
- package/dist/taco/figma-import/import/variables.d.ts +3 -2
- package/dist/taco/figma-import/import/variables.js +37 -30
- package/dist/taco/figma-import/import/variantTrees.d.ts +1 -1
- package/dist/taco/figma-import/import/variantTrees.js +44 -4
- package/dist/taco/figma-import/import/walk.d.ts +53 -5
- package/dist/taco/figma-import/import/walk.js +273 -106
- package/dist/taco/figma-import/kiwi/message.d.ts +4 -2
- package/dist/taco/figma-import/kiwi/message.js +13 -11
- package/dist/taco/model/codec.d.ts +1 -1
- package/dist/taco/model/codec.js +37 -7
- package/dist/taco/model/component-evaluation.d.ts +2 -0
- package/dist/taco/model/component-evaluation.js +7 -0
- package/dist/taco/model/instance-resolver.d.ts +6 -2
- package/dist/taco/model/instance-resolver.js +48 -18
- package/dist/taco/model/sha256.js +13 -8
- package/dist/taco/model/types.d.ts +23 -1
- package/package.json +3 -2
package/dist/adapter/payload.js
CHANGED
|
@@ -50,7 +50,7 @@ export function toPayload(converted, options = {}) {
|
|
|
50
50
|
const size = doc.assets?.[a.id];
|
|
51
51
|
assets[a.id] = { src: `data:${a.mimeType};base64,${a.data}`, ...(size?.w !== undefined ? { w: size.w } : {}), ...(size?.h !== undefined ? { h: size.h } : {}) };
|
|
52
52
|
}
|
|
53
|
-
const payload = { format: clipboard.FORMAT, version: clipboard.VERSION, client: options.client ?? 'moondraft-import', roots, nodes, assets, ...(Object.keys(mains).length ? { mains } : {}) };
|
|
53
|
+
const payload = { format: clipboard.FORMAT, version: clipboard.VERSION, client: options.client ?? 'moondraft-import', roots, nodes, assets, ...(doc.shared?.length && { shared: doc.shared }), ...(Object.keys(mains).length ? { mains } : {}) };
|
|
54
54
|
return { payload, report };
|
|
55
55
|
}
|
|
56
56
|
const base64 = (bytes) => { let s = ''; for (let i = 0; i < bytes.length; i += 0x8000)
|
|
@@ -22,13 +22,14 @@ export interface VariableCollection {
|
|
|
22
22
|
}
|
|
23
23
|
/** A resolved scalar variable value. */
|
|
24
24
|
export type VariableValue = number | boolean | string;
|
|
25
|
+
type Aliases = ReadonlyMap<string, ReadonlyMap<string, string>>;
|
|
25
26
|
type Modes = Record<string, string>;
|
|
26
27
|
/**
|
|
27
28
|
* Builds a resolver for variables and aliases in the source model.
|
|
28
29
|
* @param collections - Source collections indexed by ID.
|
|
29
30
|
* @returns A resolver that takes a variable name or ID and optional collection modes.
|
|
30
31
|
*/
|
|
31
|
-
export declare function variableResolver(collections?: Record<string, VariableCollection>): (name: string, modes?: Modes) => VariableValue | undefined;
|
|
32
|
+
export declare function variableResolver(collections?: Record<string, VariableCollection>): (name: string, modes?: Modes, aliases?: Aliases) => VariableValue | undefined;
|
|
32
33
|
/**
|
|
33
34
|
* The collections as taco's expression evaluator reads them (it follows no aliases, and reads a chosen mode only when
|
|
34
35
|
* the collection's modes table has it): each collection with a modes table (made from the modes it names when it has
|
|
@@ -39,11 +39,14 @@ function lookup(collections) {
|
|
|
39
39
|
return resolve(byId.get(target) ?? byName.get(target), modes, seen);
|
|
40
40
|
return plainValue(value) ? value : undefined;
|
|
41
41
|
}
|
|
42
|
-
function resolve(entry, modes, seen) {
|
|
42
|
+
function resolve(entry, modes, seen, aliases) {
|
|
43
43
|
if (!entry || seen.has(entry.id))
|
|
44
44
|
return undefined;
|
|
45
45
|
seen.add(entry.id);
|
|
46
46
|
const values = entry.variable.values ?? {}, mode = modeOf(entry, modes), fallback = entry.collection.defaultModeId;
|
|
47
|
+
const target = mode !== undefined && aliases?.get(entry.id)?.get(mode);
|
|
48
|
+
if (target)
|
|
49
|
+
return resolve(byId.get(target), modes, seen, aliases);
|
|
47
50
|
const value = mode !== undefined && Object.hasOwn(values, mode) ? values[mode] : fallback !== undefined && Object.hasOwn(values, fallback) ? values[fallback] : undefined;
|
|
48
51
|
return plain(value, modes, seen);
|
|
49
52
|
}
|
|
@@ -56,7 +59,7 @@ function lookup(collections) {
|
|
|
56
59
|
*/
|
|
57
60
|
export function variableResolver(collections = {}) {
|
|
58
61
|
const { byName, byId, resolve } = lookup(collections);
|
|
59
|
-
return (name, modes = {}) => resolve(byName.get(name) ?? byId.get(name), modes, new Set());
|
|
62
|
+
return (name, modes = {}, aliases) => resolve(byName.get(name) ?? byId.get(name), modes, new Set(), aliases);
|
|
60
63
|
}
|
|
61
64
|
const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
62
65
|
// Whether `value` is one taco's evaluator reads as a variable of `type` (it reads a colour from a hex string and a
|
package/dist/figma.js
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import { clipboard, createCore } from '@moondraft/editor/core';
|
|
2
|
-
import { figmaDocument,
|
|
2
|
+
import { figmaDocument, toPayload } from './adapter/index.js';
|
|
3
|
+
import { base64 } from './adapter/figma.js';
|
|
3
4
|
import { fileComponents } from './adapter/file-components.js';
|
|
5
|
+
import { keepDescription } from './adapter/figma-descriptions.js';
|
|
6
|
+
import { figmaLayoutGrids, gridSources } from './adapter/figma-grids.js';
|
|
7
|
+
import { figmaHandoff, handoffSources } from './adapter/figma-handoff.js';
|
|
8
|
+
import { figmaHyperlinks } from './adapter/figma-hyperlinks.js';
|
|
9
|
+
import { isObject } from './taco/figma-import/import/fields.js';
|
|
4
10
|
import { sha256Hex } from './taco/model/sha256.js';
|
|
5
11
|
import { expandedRadiusRoots, fileResources } from './adapter/file-resources.js';
|
|
6
|
-
import { readFileMessage } from './taco/figma-import/import/walk.js';
|
|
7
|
-
import { allPages } from './adapter/convert.js';
|
|
8
|
-
import { convertEntries,
|
|
12
|
+
import { readFileMessage, walkMessage } from './taco/figma-import/import/walk.js';
|
|
13
|
+
import { allPages, figmaClipboardPage } from './adapter/convert.js';
|
|
14
|
+
import { convertEntries, droppedFeatures, figmaReportLayers, grouped, readerCount } from './report.js';
|
|
9
15
|
import { checkAbort } from './figma-file.js';
|
|
10
|
-
import {
|
|
16
|
+
import { readFigFile, readFigmaClipboardHtml } from './taco/figma-import/index.js';
|
|
11
17
|
/**
|
|
12
18
|
* Checks for the markers Figma adds to clipboard HTML.
|
|
13
19
|
* @param html - Clipboard HTML to inspect.
|
|
@@ -18,17 +24,24 @@ export const holdsFigmaData = (html) => html.includes('(figmeta)') && html.inclu
|
|
|
18
24
|
export const MISSING_IMAGES = clipboard.MISSING_IMAGE_REPORT;
|
|
19
25
|
const STAND_IN = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
20
26
|
const ids = () => { let next = 0; return () => `f${++next}`; };
|
|
21
|
-
function reportOf(result, converted, extra =
|
|
22
|
-
const bySource =
|
|
23
|
-
const
|
|
24
|
-
const
|
|
27
|
+
function reportOf(result, converted, features, extra, file = false) {
|
|
28
|
+
const { bySource, pages, fonts, derive } = figmaReportLayers(converted.doc, file);
|
|
29
|
+
const dropped = [];
|
|
30
|
+
for (const { figmaId, what } of features) {
|
|
31
|
+
const layer = result.layerIds[figmaId];
|
|
32
|
+
if (layer === undefined)
|
|
33
|
+
continue;
|
|
34
|
+
const ids = bySource.get(layer);
|
|
35
|
+
dropped.push({ kind: 'left-out', what, count: 1, ...(ids?.length && { ids }) });
|
|
36
|
+
}
|
|
37
|
+
const pageIds = new Map(result.pages.map((page, i) => [page.figmaId, pages[i]]));
|
|
25
38
|
const reader = result.report.filter(entry => entry.nodeType !== 'CANVAS' || entry.reason === 'variable mode').map((entry) => {
|
|
26
39
|
const layer = result.layerIds[entry.nodeId];
|
|
27
40
|
const pageId = pageIds.get(entry.nodeId);
|
|
28
41
|
const ids = pageId ? [pageId] : layer === undefined ? undefined : bySource.get(layer);
|
|
29
|
-
return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out',
|
|
42
|
+
return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry.reason), ...(ids && { ids }) };
|
|
30
43
|
});
|
|
31
|
-
return grouped([...reader, ...convertEntries(converted.report, true), ...extra]);
|
|
44
|
+
return { report: grouped([...reader, ...dropped, ...convertEntries(converted.report, true), ...extra, ...fonts]), derive };
|
|
32
45
|
}
|
|
33
46
|
/**
|
|
34
47
|
* Imports Figma clipboard HTML as editable layers.
|
|
@@ -37,16 +50,40 @@ function reportOf(result, converted, extra = []) {
|
|
|
37
50
|
* @throws An error if the input contains no readable Figma layers.
|
|
38
51
|
*/
|
|
39
52
|
export function readFigmaClipboard(html) {
|
|
40
|
-
const { message } = readFigmaClipboardHtml(html), missing = new Set();
|
|
41
|
-
const result =
|
|
53
|
+
const { meta, message } = readFigmaClipboardHtml(html), missing = new Set();
|
|
54
|
+
const { result, sources } = walkMessage(message, {
|
|
42
55
|
idSource: ids(), roots: 'clipboard-selection', bindVariables: false, textStyles: false,
|
|
43
56
|
images: (hash) => { missing.add(`figma-image-${hash}`); return { bytes: STAND_IN, mimeType: 'image/png' }; },
|
|
44
|
-
});
|
|
45
|
-
const
|
|
57
|
+
}, false, tree => new Set([...handoffSources(tree), ...gridSources(tree)]));
|
|
58
|
+
const instanceSources = new Map();
|
|
59
|
+
const converted = figmaClipboardPage(figmaDocument(result, 'Pasted'), instanceSources);
|
|
60
|
+
const extra = figmaHandoff(result, sources, converted.doc, { instanceSources });
|
|
61
|
+
extra.push(...figmaHyperlinks(result, sources, converted.doc, { instanceSources }));
|
|
62
|
+
let fileKey = meta.fileKey;
|
|
63
|
+
for (const entry of figmaLayoutGrids(sources, converted.doc, { instanceSources,
|
|
64
|
+
fileId: () => fileKey ||= sha256Hex(new TextEncoder().encode(html)) }))
|
|
65
|
+
extra.push(entry);
|
|
66
|
+
const definitions = new Map(result.components.map(c => [c.id, c.rootId]));
|
|
67
|
+
const sourceOfRoot = new Map();
|
|
68
|
+
for (const [guid, component] of Object.entries(result.componentIds)) {
|
|
69
|
+
const root = definitions.get(component), node = sources.tree.nodes.get(guid);
|
|
70
|
+
if (root && node && (!sourceOfRoot.has(root) || node.change.isStateGroup === true))
|
|
71
|
+
sourceOfRoot.set(root, node);
|
|
72
|
+
}
|
|
73
|
+
for (const model of converted.doc.models) {
|
|
74
|
+
if (model.kind !== 'frame' || model.component !== model.id)
|
|
75
|
+
continue;
|
|
76
|
+
const source = sourceOfRoot.get(model.sourceId ?? '');
|
|
77
|
+
if (source)
|
|
78
|
+
keepDescription(source, model, extra);
|
|
79
|
+
}
|
|
80
|
+
const { payload } = toPayload(converted);
|
|
46
81
|
const assetIds = [...missing].filter((id) => Object.hasOwn(payload.assets, id));
|
|
47
82
|
for (const id of assetIds)
|
|
48
83
|
delete payload.assets[id];
|
|
49
|
-
|
|
84
|
+
if (assetIds.length)
|
|
85
|
+
extra.push({ kind: 'left-out', what: MISSING_IMAGES, count: assetIds.length, assetIds });
|
|
86
|
+
return { payload, report: reportOf(result, converted, droppedFeatures(message.nodeChanges), extra).report };
|
|
50
87
|
}
|
|
51
88
|
/**
|
|
52
89
|
* Reads a saved Figma design file on the calling thread.
|
|
@@ -63,34 +100,131 @@ export function readFigmaFile(bytes, options = {}) {
|
|
|
63
100
|
checkAbort(signal);
|
|
64
101
|
}
|
|
65
102
|
checkpoint('decode', 0, 1);
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
103
|
+
const { doc, images, report, total, derive } = convertFile(bytes, () => {
|
|
104
|
+
checkpoint('decode', 1, 1);
|
|
105
|
+
checkpoint('convert', 0);
|
|
106
|
+
});
|
|
107
|
+
// Use the same derived pass as editor.load so saved literals include mode choices and nested property assignments.
|
|
108
|
+
let document = doc;
|
|
109
|
+
if (derive) {
|
|
110
|
+
const core = createCore({ trackLayout: false });
|
|
111
|
+
// Conversion owns these records. Linking can share override entries, which the
|
|
112
|
+
// editor updates in place while installing derived properties and resource values.
|
|
113
|
+
for (const model of doc.models)
|
|
114
|
+
if (model.kind === 'frame' && model.overrides)
|
|
115
|
+
model.overrides = core.doc.owned(model.overrides, undefined, true);
|
|
116
|
+
core.prepareOwnedLoad(doc)();
|
|
117
|
+
document = core.toJSON();
|
|
118
|
+
}
|
|
119
|
+
// Only surviving assets need data URLs. Keep their encoded strings out of the layout and linking passes.
|
|
120
|
+
for (const [id, asset] of Object.entries(document.assets ?? {}))
|
|
121
|
+
asset.src += base64(images[id].bytes);
|
|
122
|
+
checkpoint('convert', total, total);
|
|
123
|
+
return { document, report };
|
|
124
|
+
}
|
|
125
|
+
// Derived instance entries describe Figma's layout. Their path, box and stored line
|
|
126
|
+
// heights are the inputs to instanceFields. Authored overrides are read separately.
|
|
127
|
+
function compactFileRecord(field, change) {
|
|
128
|
+
if (field !== 'nodeChanges' || !isObject(change))
|
|
129
|
+
return;
|
|
130
|
+
// History and plugin payloads have no converted fields. Only authored overrides
|
|
131
|
+
// use parameterConsumptionMap, and those are nested under symbolData.
|
|
132
|
+
for (const key of ['editInfo', 'libraryMoveHistory', 'pluginData', 'parameterConsumptionMap'])
|
|
133
|
+
if (Object.hasOwn(change, key))
|
|
134
|
+
change[key] = undefined;
|
|
135
|
+
if (Array.isArray(change.derivedSymbolData)) {
|
|
136
|
+
for (const [i, entry] of change.derivedSymbolData.entries()) {
|
|
137
|
+
if (!isObject(entry))
|
|
138
|
+
continue;
|
|
139
|
+
const layout = {};
|
|
140
|
+
for (const key of ['guidPath', 'size', 'transform'])
|
|
141
|
+
if (entry[key] !== undefined)
|
|
142
|
+
layout[key] = entry[key];
|
|
143
|
+
const text = entry.derivedTextData;
|
|
144
|
+
if (isObject(text))
|
|
145
|
+
layout.derivedTextData = text.baselines === undefined ? {} : { baselines: text.baselines };
|
|
146
|
+
else if (text !== undefined)
|
|
147
|
+
layout.derivedTextData = text;
|
|
148
|
+
change.derivedSymbolData[i] = layout;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
// Text import uses glyph advances only for list markers (glyphs without a character).
|
|
152
|
+
const text = change.derivedTextData;
|
|
153
|
+
if (isObject(text)) {
|
|
154
|
+
const metrics = {};
|
|
155
|
+
if (text.baselines !== undefined)
|
|
156
|
+
metrics.baselines = text.baselines;
|
|
157
|
+
if (text.fontMetaData !== undefined)
|
|
158
|
+
metrics.fontMetaData = text.fontMetaData;
|
|
159
|
+
if (Array.isArray(text.glyphs))
|
|
160
|
+
metrics.glyphs = text.glyphs.filter(glyph => isObject(glyph) && glyph.firstCharacter === undefined);
|
|
161
|
+
change.derivedTextData = metrics;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function readFileSource(bytes, decoded) {
|
|
165
|
+
const file = readFigFile(bytes, { onRootArrayItem: compactFileRecord });
|
|
166
|
+
decoded();
|
|
69
167
|
const result = readFileMessage(file.message, {
|
|
70
168
|
idSource: ids(), roots: 'pages',
|
|
71
169
|
images: (hash) => { const bytes = file.images.get(hash); return bytes ? { bytes } : undefined; },
|
|
72
170
|
});
|
|
73
|
-
|
|
74
|
-
|
|
171
|
+
return { result, key: file.meta?.fileKey || file.message.fileKey };
|
|
172
|
+
}
|
|
173
|
+
function convertFile(bytes, decoded) {
|
|
174
|
+
const { result, key } = readFileSource(bytes, decoded);
|
|
175
|
+
// Geometry and overrides now live on the converted nodes. Release their wire
|
|
176
|
+
// representations while collecting diagnostics in source order. Resource and
|
|
177
|
+
// metadata adapters still see the original paint lists and all other fields.
|
|
178
|
+
const releasedFields = ['derivedTextData', 'derivedSymbolData', 'symbolData', 'fillGeometry', 'strokeGeometry',
|
|
179
|
+
'vectorData'];
|
|
180
|
+
function* sources() {
|
|
181
|
+
for (const node of result.sources.tree.nodes.values()) {
|
|
182
|
+
const change = node.change;
|
|
183
|
+
for (const field of releasedFields)
|
|
184
|
+
if (Object.hasOwn(change, field))
|
|
185
|
+
change[field] = undefined;
|
|
186
|
+
yield change;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const features = [...droppedFeatures(sources())];
|
|
190
|
+
const geometry = figmaDocument(result, undefined, () => '');
|
|
191
|
+
if (result.sources.variables)
|
|
192
|
+
geometry.variableAliases = result.sources.variables.aliases;
|
|
193
|
+
geometry.instanceBoxes = result.sources.instanceBoxes;
|
|
194
|
+
geometry.instanceFillSizes = result.sources.instanceFillSizes;
|
|
75
195
|
const expandedRadii = expandedRadiusRoots(result);
|
|
76
196
|
for (const id of expandedRadii.keys())
|
|
77
197
|
geometry.nodes[id] = { ...geometry.nodes[id], fileExpanded: true };
|
|
78
198
|
for (const layer of result.sources.styleLayers.values())
|
|
79
199
|
geometry.nodes[layer.id] = { ...layer, fileStyle: true };
|
|
80
200
|
const converted = allPages(geometry, {
|
|
81
|
-
assetSrc: (_id, asset) => `data:${asset.mimeType};base64
|
|
201
|
+
assetSrc: (_id, asset) => `data:${asset.mimeType};base64,`,
|
|
82
202
|
});
|
|
83
203
|
const extra = [];
|
|
84
|
-
const occurrences = fileComponents(result, converted.doc, extra);
|
|
85
|
-
let
|
|
86
|
-
|
|
204
|
+
const { occurrences, setSources } = fileComponents(result, converted.doc, converted.nestedBooleans, extra);
|
|
205
|
+
let fileKey = key;
|
|
206
|
+
const fileId = () => String(fileKey ||= sha256Hex(bytes));
|
|
207
|
+
fileResources(result, converted.doc, occurrences, converted.expanded, expandedRadii, extra, fileId);
|
|
208
|
+
for (const layer of converted.doc.models) {
|
|
209
|
+
if (layer.kind !== 'frame')
|
|
210
|
+
continue;
|
|
211
|
+
for (const path of converted.omittedLinks.get(layer.id) ?? []) {
|
|
212
|
+
// An explicitly painted occurrence keeps its resolved links in its own palette.
|
|
213
|
+
if (!layer.overrides?.[path]?.styles)
|
|
214
|
+
extra.push({ kind: 'left-out', what: 'instance text link override not kept', count: 1, ids: [layer.id + ';' + path] });
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
for (const entry of figmaHyperlinks(result, result.sources, converted.doc, { setSources }))
|
|
218
|
+
extra.push(entry);
|
|
219
|
+
for (const entry of figmaHandoff(result, result.sources, converted.doc, { setSources }))
|
|
220
|
+
extra.push(entry);
|
|
221
|
+
for (const entry of figmaLayoutGrids(result.sources, converted.doc, { setSources, fileId }))
|
|
222
|
+
extra.push(entry);
|
|
87
223
|
const reader = result.report.filter(e => !e.reason.startsWith('variable bindings left out, their values kept:'));
|
|
88
|
-
const report = reportOf({ ...result, report: reader }, converted,
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
checkpoint('convert', total, total);
|
|
95
|
-
return { document, report };
|
|
224
|
+
const { report, derive } = reportOf({ ...result, report: reader }, converted, features, extra, true);
|
|
225
|
+
const images = result.assets;
|
|
226
|
+
for (const id of Object.keys(images))
|
|
227
|
+
if (!Object.hasOwn(converted.doc.assets ?? {}, id))
|
|
228
|
+
delete images[id];
|
|
229
|
+
return { doc: converted.doc, images, report, derive, total: result.pages.length };
|
|
96
230
|
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/report.d.ts
CHANGED
|
@@ -1,10 +1,37 @@
|
|
|
1
1
|
import type { ImportReportEntry } from '@moondraft/editor/core';
|
|
2
2
|
import type { DocumentJSON } from '@moondraft/editor/schema';
|
|
3
3
|
import type { ConvertReport } from './adapter/convert.ts';
|
|
4
|
-
/**
|
|
4
|
+
/** The most layer IDs a grouped entry keeps as examples. */
|
|
5
|
+
export declare const EXAMPLE_IDS = 5;
|
|
6
|
+
/** The occurrence count a reader summary carries in its reason (`… (3 times, first here)`), moved into `count`. */
|
|
7
|
+
export declare function readerCount(reason: string): {
|
|
8
|
+
what: string;
|
|
9
|
+
count: number;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Groups entries by kind and description, summing counts and keeping up to `EXAMPLE_IDS` unique layer IDs. Entries
|
|
13
|
+
* that are not fonts also group when their descriptions differ only in quoted names, numbers or upper-case enum values;
|
|
14
|
+
* the grouped description lists each varying part's values in order of appearance.
|
|
15
|
+
*/
|
|
5
16
|
export declare function grouped(entries: Iterable<ImportReportEntry>): ImportReportEntry[];
|
|
17
|
+
/** Report descriptions of Figma features the importer leaves out without converting any part of them. */
|
|
18
|
+
export declare const DROPPED_FEATURES: {
|
|
19
|
+
readonly interactions: 'prototype interactions are not imported';
|
|
20
|
+
};
|
|
21
|
+
/** Unsupported features in source order. Linking supplies their final layer IDs later. */
|
|
22
|
+
export declare function droppedFeatures(changes: Iterable<unknown> | undefined): Generator<{
|
|
23
|
+
figmaId: string;
|
|
24
|
+
what: "prototype interactions are not imported";
|
|
25
|
+
}, void, unknown>;
|
|
6
26
|
/** Builds a lookup from reader IDs to their converted layers. */
|
|
7
27
|
export declare function layersBySource(document: DocumentJSON): Map<string, string[]>;
|
|
28
|
+
/** Collect file diagnostics and strip reader IDs before handing the models to the editor. */
|
|
29
|
+
export declare function figmaReportLayers(document: DocumentJSON, file: boolean): {
|
|
30
|
+
bySource: Map<string, string[]>;
|
|
31
|
+
pages: string[];
|
|
32
|
+
fonts: ImportReportEntry[];
|
|
33
|
+
derive: boolean;
|
|
34
|
+
};
|
|
8
35
|
/** Turns adapter diagnostics into import reports. */
|
|
9
36
|
export declare function convertEntries(report: ConvertReport, details?: boolean): ImportReportEntry[];
|
|
10
37
|
/**
|
package/dist/report.js
CHANGED
|
@@ -1,35 +1,106 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** The most layer IDs a grouped entry keeps as examples. */
|
|
2
|
+
export const EXAMPLE_IDS = 5;
|
|
3
|
+
/** The most distinct values a grouped entry lists in place of one varying part of its description. */
|
|
4
|
+
const LISTED = 3;
|
|
5
|
+
// The parts of a description that vary between entries of one kind: quoted names (with escaped quotes inside), Figma
|
|
6
|
+
// node IDs, numbers and Figma's upper-case enum values ("fill 2 blend mode LINEAR_BURN", "override field \"size\"").
|
|
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 };
|
|
13
|
+
}
|
|
14
|
+
/** Lists a part's distinct values: all of them up to `LISTED`, then the first ones and how many more. */
|
|
15
|
+
function listed(values) {
|
|
16
|
+
return values.length <= LISTED ? values.join(', ') : `${values.slice(0, LISTED).join(', ')} and ${values.length - LISTED} more`;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Groups entries by kind and description, summing counts and keeping up to `EXAMPLE_IDS` unique layer IDs. Entries
|
|
20
|
+
* that are not fonts also group when their descriptions differ only in quoted names, numbers or upper-case enum values;
|
|
21
|
+
* the grouped description lists each varying part's values in order of appearance.
|
|
22
|
+
*/
|
|
2
23
|
export function grouped(entries) {
|
|
3
24
|
const out = new Map();
|
|
4
25
|
for (const e of entries) {
|
|
5
|
-
const
|
|
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) ?? []);
|
|
6
29
|
if (had) {
|
|
7
|
-
had.count += e.count;
|
|
8
|
-
if (e.
|
|
9
|
-
(had.
|
|
30
|
+
had.entry.count += e.count;
|
|
31
|
+
if (e.assetIds)
|
|
32
|
+
(had.entry.assetIds ??= []).push(...e.assetIds);
|
|
33
|
+
had.parts?.forEach((values, i) => values.add(parts[i]));
|
|
10
34
|
}
|
|
11
35
|
else
|
|
12
|
-
out.set(key, { ...e, ...(e.
|
|
36
|
+
out.set(key, { entry: { ...e, ...(e.assetIds && { assetIds: [...e.assetIds] }) }, ids: new Set(), parts: parts && parts.map(p => new Set([p])) });
|
|
37
|
+
const { ids } = out.get(key);
|
|
38
|
+
for (const id of e.ids ?? [])
|
|
39
|
+
if (ids.size < EXAMPLE_IDS)
|
|
40
|
+
ids.add(id);
|
|
41
|
+
}
|
|
42
|
+
return [...out.values()].map(({ entry, ids, parts }) => {
|
|
43
|
+
if (parts?.some(values => values.size > 1)) {
|
|
44
|
+
let i = 0;
|
|
45
|
+
entry.what = entry.what.replace(VARYING, () => listed([...parts[i++]]));
|
|
46
|
+
}
|
|
47
|
+
if (entry.assetIds)
|
|
48
|
+
entry.assetIds = [...new Set(entry.assetIds)];
|
|
49
|
+
if (ids.size)
|
|
50
|
+
entry.ids = [...ids];
|
|
51
|
+
else
|
|
52
|
+
delete entry.ids;
|
|
53
|
+
return entry;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/** Report descriptions of Figma features the importer leaves out without converting any part of them. */
|
|
57
|
+
export const DROPPED_FEATURES = {
|
|
58
|
+
interactions: 'prototype interactions are not imported',
|
|
59
|
+
};
|
|
60
|
+
const present = (value) => Array.isArray(value) ? value.some(item => item?.isDeleted !== true) : typeof value === 'string' && value.trim() !== '';
|
|
61
|
+
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) {
|
|
64
|
+
for (const change of changes ?? []) {
|
|
65
|
+
const n = change, figmaId = guidOf(n?.guid);
|
|
66
|
+
if (figmaId === undefined)
|
|
67
|
+
continue;
|
|
68
|
+
if (present(n.prototypeInteractions))
|
|
69
|
+
yield { figmaId, what: DROPPED_FEATURES.interactions };
|
|
13
70
|
}
|
|
14
|
-
for (const e of out.values())
|
|
15
|
-
if (e.ids)
|
|
16
|
-
e.ids = [...new Set(e.ids)];
|
|
17
|
-
return [...out.values()];
|
|
18
71
|
}
|
|
19
72
|
/** Builds a lookup from reader IDs to their converted layers. */
|
|
20
73
|
export function layersBySource(document) {
|
|
21
74
|
const ids = new Map();
|
|
75
|
+
for (const model of document.models)
|
|
76
|
+
indexLayer(ids, model);
|
|
77
|
+
return ids;
|
|
78
|
+
}
|
|
79
|
+
function indexLayer(ids, model) {
|
|
80
|
+
if (model.sourceId === undefined)
|
|
81
|
+
return;
|
|
82
|
+
const found = ids.get(model.sourceId);
|
|
83
|
+
if (found)
|
|
84
|
+
found.push(model.id);
|
|
85
|
+
else
|
|
86
|
+
ids.set(model.sourceId, [model.id]);
|
|
87
|
+
}
|
|
88
|
+
/** Collect file diagnostics and strip reader IDs before handing the models to the editor. */
|
|
89
|
+
export function figmaReportLayers(document, file) {
|
|
90
|
+
const bySource = new Map(), pages = [], fonts = [];
|
|
91
|
+
let derive = !!document.shared;
|
|
22
92
|
for (const model of document.models) {
|
|
23
|
-
|
|
24
|
-
if (
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
93
|
+
indexLayer(bySource, model);
|
|
94
|
+
if (model.kind === 'page')
|
|
95
|
+
pages.push(model.id);
|
|
96
|
+
if (file) {
|
|
97
|
+
collectFaces(model, fonts);
|
|
98
|
+
delete model.sourceId;
|
|
99
|
+
if (model.kind === 'frame' && (model.variantSet || model.props))
|
|
100
|
+
derive = true;
|
|
101
|
+
}
|
|
31
102
|
}
|
|
32
|
-
return
|
|
103
|
+
return { bySource, pages, fonts, derive };
|
|
33
104
|
}
|
|
34
105
|
/** Turns adapter diagnostics into import reports. */
|
|
35
106
|
export function convertEntries(report, details = false) {
|
|
@@ -52,18 +123,20 @@ export function convertEntries(report, details = false) {
|
|
|
52
123
|
*/
|
|
53
124
|
export function fontEntries(document) {
|
|
54
125
|
const entries = [];
|
|
126
|
+
for (const m of document.models)
|
|
127
|
+
collectFaces(m, entries);
|
|
128
|
+
return entries;
|
|
129
|
+
}
|
|
130
|
+
function collectFaces(m, entries) {
|
|
55
131
|
function faces(styles, id) {
|
|
56
132
|
for (const what of new Set(styles?.map(s => s.family + '/' + s.style)))
|
|
57
133
|
entries.push({ kind: 'font', what, count: 1, ids: [id] });
|
|
58
134
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
faces(override.styles, m.id + ';' + path);
|
|
67
|
-
}
|
|
68
|
-
return entries;
|
|
135
|
+
if (m.kind === 'page')
|
|
136
|
+
return;
|
|
137
|
+
if (m.styles)
|
|
138
|
+
faces(m.styles, m.id);
|
|
139
|
+
for (const [path, override] of Object.entries(m.overrides ?? {}))
|
|
140
|
+
if (override.styles)
|
|
141
|
+
faces(override.styles, m.id + ';' + path);
|
|
69
142
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { DocumentJSON } from '@moondraft/editor/schema';
|
|
2
|
+
/**
|
|
3
|
+
* Writes the compact JSON of an imported document in chunks suitable for a file or stream.
|
|
4
|
+
* @param document - The plain document returned by the importer.
|
|
5
|
+
* @returns Strings in JSON.stringify order, with one layer or resource encoded at a time.
|
|
6
|
+
*/
|
|
7
|
+
export declare function serializeImportDocument(document: DocumentJSON): Generator<string>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
const CHUNK = 64 * 1024;
|
|
2
|
+
// Keep large image URLs out of the encoder's temporary strings. Align chunk boundaries so
|
|
3
|
+
// JSON.stringify leaves valid surrogate pairs together and escapes lone surrogates as usual.
|
|
4
|
+
function* assetFields(asset) {
|
|
5
|
+
yield '{';
|
|
6
|
+
let separator = '';
|
|
7
|
+
for (const [key, value] of Object.entries(asset)) {
|
|
8
|
+
if (value === undefined)
|
|
9
|
+
continue;
|
|
10
|
+
yield separator + JSON.stringify(key) + ':';
|
|
11
|
+
separator = ',';
|
|
12
|
+
if (typeof value !== 'string' || value.length <= CHUNK) {
|
|
13
|
+
yield JSON.stringify(value);
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
yield '"';
|
|
17
|
+
for (let start = 0; start < value.length;) {
|
|
18
|
+
let end = Math.min(start + CHUNK, value.length);
|
|
19
|
+
const last = value.charCodeAt(end - 1);
|
|
20
|
+
if (end < value.length && last >= 0xd800 && last <= 0xdbff)
|
|
21
|
+
end--;
|
|
22
|
+
const piece = value.slice(start, end);
|
|
23
|
+
yield /["\\\u0000-\u001f\ud800-\udfff]/.test(piece) ? JSON.stringify(piece).slice(1, -1) : piece;
|
|
24
|
+
start = end;
|
|
25
|
+
}
|
|
26
|
+
yield '"';
|
|
27
|
+
}
|
|
28
|
+
yield '}';
|
|
29
|
+
}
|
|
30
|
+
function* documentParts(document) {
|
|
31
|
+
yield '{';
|
|
32
|
+
let comma = '';
|
|
33
|
+
for (const [key, value] of Object.entries(document)) {
|
|
34
|
+
if (value === undefined)
|
|
35
|
+
continue;
|
|
36
|
+
yield comma + JSON.stringify(key) + ':';
|
|
37
|
+
comma = ',';
|
|
38
|
+
let separator = '';
|
|
39
|
+
if (Array.isArray(value)) {
|
|
40
|
+
yield '[';
|
|
41
|
+
for (const item of value) {
|
|
42
|
+
yield separator + (JSON.stringify(item) ?? 'null');
|
|
43
|
+
separator = ',';
|
|
44
|
+
}
|
|
45
|
+
yield ']';
|
|
46
|
+
}
|
|
47
|
+
else if (key === 'assets' && document.assets) {
|
|
48
|
+
yield '{';
|
|
49
|
+
for (const [id, asset] of Object.entries(document.assets)) {
|
|
50
|
+
if (asset === undefined)
|
|
51
|
+
continue;
|
|
52
|
+
yield separator + JSON.stringify(id) + ':';
|
|
53
|
+
yield* assetFields(asset);
|
|
54
|
+
separator = ',';
|
|
55
|
+
}
|
|
56
|
+
yield '}';
|
|
57
|
+
}
|
|
58
|
+
else
|
|
59
|
+
yield JSON.stringify(value);
|
|
60
|
+
}
|
|
61
|
+
yield '}';
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Writes the compact JSON of an imported document in chunks suitable for a file or stream.
|
|
65
|
+
* @param document - The plain document returned by the importer.
|
|
66
|
+
* @returns Strings in JSON.stringify order, with one layer or resource encoded at a time.
|
|
67
|
+
*/
|
|
68
|
+
export function* serializeImportDocument(document) {
|
|
69
|
+
let chunk = '';
|
|
70
|
+
for (const part of documentParts(document)) {
|
|
71
|
+
chunk += part;
|
|
72
|
+
if (chunk.length >= CHUNK) {
|
|
73
|
+
yield chunk;
|
|
74
|
+
chunk = '';
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (chunk)
|
|
78
|
+
yield chunk;
|
|
79
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type RootArrayItem } from "../kiwi/message.ts";
|
|
1
2
|
import type { KiwiObject, KiwiSchema } from "../kiwi/types.ts";
|
|
2
3
|
/**
|
|
3
4
|
* The 8-byte names a Kiwi container may start with: Figma design files and
|
|
@@ -23,6 +24,8 @@ export interface KiwiContainer {
|
|
|
23
24
|
readonly message: KiwiObject;
|
|
24
25
|
}
|
|
25
26
|
export interface KiwiContainerOptions {
|
|
27
|
+
/** Allows a file importer to compact each decoded root array item before reading the next. */
|
|
28
|
+
readonly onRootArrayItem?: RootArrayItem;
|
|
26
29
|
/** Defaults to `FIGMA_READ_LIMITS.maxDecompressedChunkBytes`. */
|
|
27
30
|
readonly maxDecompressedChunkBytes?: number;
|
|
28
31
|
}
|
|
@@ -56,6 +56,6 @@ export function readKiwiContainer(bytes, options = {}) {
|
|
|
56
56
|
throw new FigmaReadError("too-few-chunks", `the container has ${chunks.length} chunk${chunks.length === 1 ? "" : "s"}, but needs a schema and a message`, at);
|
|
57
57
|
}
|
|
58
58
|
const schema = decodeKiwiSchema(decompressChunk(chunks[0], chunkOffsets[0], maxBytes));
|
|
59
|
-
const message = decodeKiwiMessage(schema, FIGMA_MESSAGE_ROOT_TYPE, decompressChunk(chunks[1], chunkOffsets[1], maxBytes));
|
|
59
|
+
const message = decodeKiwiMessage(schema, FIGMA_MESSAGE_ROOT_TYPE, decompressChunk(chunks[1], chunkOffsets[1], maxBytes), options.onRootArrayItem);
|
|
60
60
|
return { header: { magic, version }, chunks, schema, message };
|
|
61
61
|
}
|