@moondraft/import 0.0.0-stage → 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 +36 -0
- package/LICENSE +34 -0
- package/README.md +36 -2
- package/SOURCE.md +394 -0
- package/dist/adapter/convert.d.ts +144 -0
- package/dist/adapter/convert.js +2811 -0
- 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 +12 -0
- package/dist/adapter/figma.js +40 -0
- package/dist/adapter/file-components.d.ts +20 -0
- package/dist/adapter/file-components.js +352 -0
- package/dist/adapter/file-resources.d.ts +29 -0
- package/dist/adapter/file-resources.js +851 -0
- package/dist/adapter/image-crop.d.ts +18 -0
- package/dist/adapter/image-crop.js +30 -0
- package/dist/adapter/index.d.ts +6 -0
- package/dist/adapter/index.js +9 -0
- package/dist/adapter/link.d.ts +49 -0
- package/dist/adapter/link.js +892 -0
- package/dist/adapter/payload.d.ts +31 -0
- package/dist/adapter/payload.js +78 -0
- package/dist/adapter/shapes.d.ts +31 -0
- package/dist/adapter/shapes.js +75 -0
- package/dist/adapter/variables.d.ts +45 -0
- package/dist/adapter/variables.js +106 -0
- package/dist/figma-file.d.ts +38 -0
- package/dist/figma-file.js +97 -0
- package/dist/figma-worker.d.ts +11 -0
- package/dist/figma-worker.js +12 -0
- package/dist/figma.d.ts +26 -0
- package/dist/figma.js +230 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +50 -0
- package/dist/report.d.ts +42 -0
- package/dist/report.js +142 -0
- package/dist/serialize.d.ts +7 -0
- package/dist/serialize.js +79 -0
- package/dist/svg.d.ts +33 -0
- package/dist/svg.js +44 -0
- package/dist/syntax.d.ts +8 -0
- package/dist/syntax.js +19 -0
- package/dist/taco/figma-import/clipboard.d.ts +25 -0
- package/dist/taco/figma-import/clipboard.js +87 -0
- package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
- package/dist/taco/figma-import/clipboardSize.js +107 -0
- package/dist/taco/figma-import/container/compression.d.ts +9 -0
- package/dist/taco/figma-import/container/compression.js +174 -0
- package/dist/taco/figma-import/container/error.d.ts +15 -0
- package/dist/taco/figma-import/container/error.js +19 -0
- package/dist/taco/figma-import/container/kiwiContainer.d.ts +41 -0
- package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
- package/dist/taco/figma-import/container/limits.d.ts +22 -0
- package/dist/taco/figma-import/container/limits.js +22 -0
- package/dist/taco/figma-import/container/zip.d.ts +14 -0
- package/dist/taco/figma-import/container/zip.js +154 -0
- package/dist/taco/figma-import/figFile.d.ts +34 -0
- package/dist/taco/figma-import/figFile.js +91 -0
- package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
- package/dist/taco/figma-import/figFileDocument.js +100 -0
- package/dist/taco/figma-import/import/blobs.d.ts +10 -0
- package/dist/taco/figma-import/import/blobs.js +23 -0
- package/dist/taco/figma-import/import/carry.d.ts +24 -0
- package/dist/taco/figma-import/import/carry.js +66 -0
- package/dist/taco/figma-import/import/componentProps.d.ts +90 -0
- package/dist/taco/figma-import/import/componentProps.js +329 -0
- package/dist/taco/figma-import/import/componentSets.d.ts +85 -0
- package/dist/taco/figma-import/import/componentSets.js +647 -0
- package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
- package/dist/taco/figma-import/import/converters/effects.js +127 -0
- package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
- package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
- 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.d.ts +21 -0
- package/dist/taco/figma-import/import/converters/frame.js +63 -0
- package/dist/taco/figma-import/import/converters/gradient.d.ts +74 -0
- package/dist/taco/figma-import/import/converters/gradient.js +108 -0
- package/dist/taco/figma-import/import/converters/group.d.ts +19 -0
- package/dist/taco/figma-import/import/converters/group.js +30 -0
- package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
- package/dist/taco/figma-import/import/converters/image.js +94 -0
- package/dist/taco/figma-import/import/converters/layout.d.ts +33 -0
- package/dist/taco/figma-import/import/converters/layout.js +187 -0
- package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
- package/dist/taco/figma-import/import/converters/line.js +40 -0
- package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
- package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
- package/dist/taco/figma-import/import/converters/section.d.ts +8 -0
- package/dist/taco/figma-import/import/converters/section.js +29 -0
- package/dist/taco/figma-import/import/converters/shared.d.ts +71 -0
- package/dist/taco/figma-import/import/converters/shared.js +372 -0
- package/dist/taco/figma-import/import/converters/text.d.ts +54 -0
- package/dist/taco/figma-import/import/converters/text.js +707 -0
- package/dist/taco/figma-import/import/converters/vector.d.ts +105 -0
- package/dist/taco/figma-import/import/converters/vector.js +609 -0
- package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +114 -0
- package/dist/taco/figma-import/import/converters/vectorNetwork.js +503 -0
- package/dist/taco/figma-import/import/fields.d.ts +15 -0
- package/dist/taco/figma-import/import/fields.js +29 -0
- package/dist/taco/figma-import/import/instances.d.ts +184 -0
- package/dist/taco/figma-import/import/instances.js +1530 -0
- package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
- package/dist/taco/figma-import/import/nestingCycles.js +488 -0
- package/dist/taco/figma-import/import/slots.d.ts +56 -0
- package/dist/taco/figma-import/import/slots.js +96 -0
- package/dist/taco/figma-import/import/styles.d.ts +48 -0
- package/dist/taco/figma-import/import/styles.js +48 -0
- package/dist/taco/figma-import/import/tree.d.ts +66 -0
- package/dist/taco/figma-import/import/tree.js +194 -0
- package/dist/taco/figma-import/import/types.d.ts +232 -0
- package/dist/taco/figma-import/import/types.js +33 -0
- package/dist/taco/figma-import/import/variables.d.ts +137 -0
- package/dist/taco/figma-import/import/variables.js +769 -0
- package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
- package/dist/taco/figma-import/import/variantTrees.js +520 -0
- package/dist/taco/figma-import/import/walk.d.ts +207 -0
- package/dist/taco/figma-import/import/walk.js +1464 -0
- package/dist/taco/figma-import/index.d.ts +22 -0
- package/dist/taco/figma-import/index.js +13 -0
- package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
- package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
- package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
- package/dist/taco/figma-import/kiwi/error.js +29 -0
- package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
- package/dist/taco/figma-import/kiwi/limits.js +18 -0
- package/dist/taco/figma-import/kiwi/message.d.ts +12 -0
- package/dist/taco/figma-import/kiwi/message.js +147 -0
- package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
- package/dist/taco/figma-import/kiwi/schema.js +206 -0
- package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
- package/dist/taco/figma-import/kiwi/types.js +18 -0
- package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
- package/dist/taco/model/agent-hidden-fields.js +29 -0
- package/dist/taco/model/asset-users.d.ts +23 -0
- package/dist/taco/model/asset-users.js +128 -0
- package/dist/taco/model/auto-layout-lines.d.ts +32 -0
- package/dist/taco/model/auto-layout-lines.js +70 -0
- package/dist/taco/model/codec.d.ts +444 -0
- package/dist/taco/model/codec.js +5665 -0
- package/dist/taco/model/color.d.ts +11 -0
- package/dist/taco/model/color.js +61 -0
- package/dist/taco/model/comment-operations.d.ts +102 -0
- package/dist/taco/model/comment-operations.js +227 -0
- package/dist/taco/model/component-evaluation.d.ts +96 -0
- package/dist/taco/model/component-evaluation.js +555 -0
- package/dist/taco/model/component-expressions.d.ts +242 -0
- package/dist/taco/model/component-expressions.js +1082 -0
- package/dist/taco/model/component-properties.d.ts +111 -0
- package/dist/taco/model/component-properties.js +339 -0
- package/dist/taco/model/component-samples.d.ts +83 -0
- package/dist/taco/model/component-samples.js +290 -0
- package/dist/taco/model/component-validity.d.ts +85 -0
- package/dist/taco/model/component-validity.js +397 -0
- package/dist/taco/model/components.d.ts +155 -0
- package/dist/taco/model/components.js +505 -0
- package/dist/taco/model/connector-ends.d.ts +20 -0
- package/dist/taco/model/connector-ends.js +188 -0
- package/dist/taco/model/connector-geometry.d.ts +74 -0
- package/dist/taco/model/connector-geometry.js +293 -0
- package/dist/taco/model/corner-radii.d.ts +26 -0
- package/dist/taco/model/corner-radii.js +47 -0
- package/dist/taco/model/derivations.d.ts +81 -0
- package/dist/taco/model/derivations.js +151 -0
- package/dist/taco/model/export-settings.d.ts +53 -0
- package/dist/taco/model/export-settings.js +156 -0
- package/dist/taco/model/expressions/ast.d.ts +153 -0
- package/dist/taco/model/expressions/ast.js +6 -0
- package/dist/taco/model/expressions/cache.d.ts +23 -0
- package/dist/taco/model/expressions/cache.js +43 -0
- package/dist/taco/model/expressions/check.d.ts +72 -0
- package/dist/taco/model/expressions/check.js +517 -0
- package/dist/taco/model/expressions/completion.d.ts +61 -0
- package/dist/taco/model/expressions/completion.js +421 -0
- package/dist/taco/model/expressions/evaluate.d.ts +32 -0
- package/dist/taco/model/expressions/evaluate.js +519 -0
- package/dist/taco/model/expressions/forms.d.ts +84 -0
- package/dist/taco/model/expressions/forms.js +200 -0
- package/dist/taco/model/expressions/index.d.ts +14 -0
- package/dist/taco/model/expressions/index.js +17 -0
- package/dist/taco/model/expressions/lexer.d.ts +42 -0
- package/dist/taco/model/expressions/lexer.js +213 -0
- package/dist/taco/model/expressions/library.d.ts +33 -0
- package/dist/taco/model/expressions/library.js +117 -0
- package/dist/taco/model/expressions/names.d.ts +43 -0
- package/dist/taco/model/expressions/names.js +99 -0
- package/dist/taco/model/expressions/parser.d.ts +15 -0
- package/dist/taco/model/expressions/parser.js +438 -0
- package/dist/taco/model/expressions/rename.d.ts +34 -0
- package/dist/taco/model/expressions/rename.js +46 -0
- package/dist/taco/model/expressions/source.d.ts +15 -0
- package/dist/taco/model/expressions/source.js +161 -0
- package/dist/taco/model/expressions/types.d.ts +119 -0
- package/dist/taco/model/expressions/types.js +102 -0
- package/dist/taco/model/expressions/values.d.ts +97 -0
- package/dist/taco/model/expressions/values.js +160 -0
- package/dist/taco/model/geometry-limits.d.ts +16 -0
- package/dist/taco/model/geometry-limits.js +67 -0
- package/dist/taco/model/geometry.d.ts +47 -0
- package/dist/taco/model/geometry.js +193 -0
- package/dist/taco/model/group-bounds.d.ts +38 -0
- package/dist/taco/model/group-bounds.js +144 -0
- package/dist/taco/model/id-table.d.ts +37 -0
- package/dist/taco/model/id-table.js +80 -0
- package/dist/taco/model/index.d.ts +25 -0
- package/dist/taco/model/index.js +27 -0
- package/dist/taco/model/instance-resolver.d.ts +376 -0
- package/dist/taco/model/instance-resolver.js +1778 -0
- package/dist/taco/model/layer-syntax.d.ts +340 -0
- package/dist/taco/model/layer-syntax.js +3506 -0
- package/dist/taco/model/layout/constraints.d.ts +84 -0
- package/dist/taco/model/layout/constraints.js +445 -0
- package/dist/taco/model/layout/frame-layout.d.ts +46 -0
- package/dist/taco/model/layout/frame-layout.js +618 -0
- package/dist/taco/model/layout/node-sizing.d.ts +163 -0
- package/dist/taco/model/layout/node-sizing.js +486 -0
- package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
- package/dist/taco/model/legacy-connector-caps.js +70 -0
- package/dist/taco/model/linear-call.d.ts +48 -0
- package/dist/taco/model/linear-call.js +58 -0
- package/dist/taco/model/new-nodes.d.ts +145 -0
- package/dist/taco/model/new-nodes.js +277 -0
- package/dist/taco/model/node-builder.d.ts +449 -0
- package/dist/taco/model/node-builder.js +2294 -0
- package/dist/taco/model/node-table-watch.d.ts +36 -0
- package/dist/taco/model/node-table-watch.js +63 -0
- package/dist/taco/model/node-transform.d.ts +39 -0
- package/dist/taco/model/node-transform.js +79 -0
- package/dist/taco/model/node-users-index.d.ts +10 -0
- package/dist/taco/model/node-users-index.js +82 -0
- package/dist/taco/model/operation-references.d.ts +80 -0
- package/dist/taco/model/operation-references.js +399 -0
- package/dist/taco/model/operations.d.ts +610 -0
- package/dist/taco/model/operations.js +2882 -0
- package/dist/taco/model/overlay-table.d.ts +71 -0
- package/dist/taco/model/overlay-table.js +171 -0
- package/dist/taco/model/override-remap.d.ts +69 -0
- package/dist/taco/model/override-remap.js +230 -0
- package/dist/taco/model/parent-table.d.ts +53 -0
- package/dist/taco/model/parent-table.js +193 -0
- package/dist/taco/model/problem-collector.d.ts +27 -0
- package/dist/taco/model/problem-collector.js +101 -0
- package/dist/taco/model/sha256.d.ts +10 -0
- package/dist/taco/model/sha256.js +79 -0
- package/dist/taco/model/shape-geometry.d.ts +96 -0
- package/dist/taco/model/shape-geometry.js +368 -0
- package/dist/taco/model/shared-node-table.d.ts +97 -0
- package/dist/taco/model/shared-node-table.js +546 -0
- package/dist/taco/model/slots.d.ts +113 -0
- package/dist/taco/model/slots.js +281 -0
- package/dist/taco/model/stroke-settings.d.ts +37 -0
- package/dist/taco/model/stroke-settings.js +90 -0
- package/dist/taco/model/svg-path-import.d.ts +89 -0
- package/dist/taco/model/svg-path-import.js +219 -0
- package/dist/taco/model/text-measurement.d.ts +142 -0
- package/dist/taco/model/text-measurement.js +846 -0
- package/dist/taco/model/text-reads.d.ts +66 -0
- package/dist/taco/model/text-reads.js +128 -0
- package/dist/taco/model/text-sizer.d.ts +358 -0
- package/dist/taco/model/text-sizer.js +996 -0
- package/dist/taco/model/theme-users.d.ts +59 -0
- package/dist/taco/model/theme-users.js +312 -0
- package/dist/taco/model/thumbnail.d.ts +15 -0
- package/dist/taco/model/thumbnail.js +34 -0
- package/dist/taco/model/types.d.ts +2369 -0
- package/dist/taco/model/types.js +366 -0
- package/dist/taco/model/unknown-property.d.ts +5 -0
- package/dist/taco/model/unknown-property.js +7 -0
- package/dist/taco/model/validated-documents.d.ts +22 -0
- package/dist/taco/model/validated-documents.js +22 -0
- package/dist/taco/model/variable-modes.d.ts +61 -0
- package/dist/taco/model/variable-modes.js +438 -0
- package/dist/taco/model/variable-references.d.ts +54 -0
- package/dist/taco/model/variable-references.js +183 -0
- package/dist/taco/model/variables.d.ts +24 -0
- package/dist/taco/model/variables.js +151 -0
- package/dist/taco/model/vector-network.d.ts +34 -0
- package/dist/taco/model/vector-network.js +411 -0
- package/dist/taco/svg-import/import-svg.d.ts +36 -0
- package/dist/taco/svg-import/import-svg.js +729 -0
- package/dist/taco/svg-import/index.d.ts +3 -0
- package/dist/taco/svg-import/index.js +3 -0
- package/dist/taco/svg-import/limits/limits.d.ts +79 -0
- package/dist/taco/svg-import/limits/limits.js +160 -0
- package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
- package/dist/taco/svg-import/paint/gradients.js +429 -0
- package/dist/taco/svg-import/paint/paint.d.ts +32 -0
- package/dist/taco/svg-import/paint/paint.js +162 -0
- package/dist/taco/svg-import/paths/paths.d.ts +58 -0
- package/dist/taco/svg-import/paths/paths.js +205 -0
- package/dist/taco/svg-import/public-types.d.ts +279 -0
- package/dist/taco/svg-import/public-types.js +56 -0
- package/dist/taco/svg-import/report/report.d.ts +44 -0
- package/dist/taco/svg-import/report/report.js +79 -0
- package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
- package/dist/taco/svg-import/reuse/reuse.js +840 -0
- package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
- package/dist/taco/svg-import/shapes/shapes.js +386 -0
- package/dist/taco/svg-import/structure/effects.d.ts +26 -0
- package/dist/taco/svg-import/structure/effects.js +618 -0
- package/dist/taco/svg-import/structure/image.d.ts +24 -0
- package/dist/taco/svg-import/structure/image.js +495 -0
- package/dist/taco/svg-import/structure/walk.d.ts +85 -0
- package/dist/taco/svg-import/structure/walk.js +544 -0
- package/dist/taco/svg-import/style/color.d.ts +40 -0
- package/dist/taco/svg-import/style/color.js +275 -0
- package/dist/taco/svg-import/style/computed.d.ts +214 -0
- package/dist/taco/svg-import/style/computed.js +1534 -0
- package/dist/taco/svg-import/style/css.d.ts +127 -0
- package/dist/taco/svg-import/style/css.js +541 -0
- package/dist/taco/svg-import/style/media.d.ts +25 -0
- package/dist/taco/svg-import/style/media.js +307 -0
- package/dist/taco/svg-import/style/properties.d.ts +43 -0
- package/dist/taco/svg-import/style/properties.js +135 -0
- package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
- package/dist/taco/svg-import/style/selector-reach.js +169 -0
- package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
- package/dist/taco/svg-import/style/selector-validity.js +307 -0
- package/dist/taco/svg-import/text/text.d.ts +29 -0
- package/dist/taco/svg-import/text/text.js +545 -0
- package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
- package/dist/taco/svg-import/transform/matrix.js +229 -0
- package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
- package/dist/taco/svg-import/tree/element-data.js +155 -0
- package/dist/taco/svg-import/tree/elements.d.ts +36 -0
- package/dist/taco/svg-import/tree/elements.js +121 -0
- package/dist/taco/svg-import/units/length.d.ts +43 -0
- package/dist/taco/svg-import/units/length.js +125 -0
- package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
- package/dist/taco/svg-import/units/viewbox.js +77 -0
- package/package.json +55 -4
package/dist/figma.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { clipboard, createCore } from '@moondraft/editor/core';
|
|
2
|
+
import { figmaDocument, toPayload } from './adapter/index.js';
|
|
3
|
+
import { base64 } from './adapter/figma.js';
|
|
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';
|
|
10
|
+
import { sha256Hex } from './taco/model/sha256.js';
|
|
11
|
+
import { expandedRadiusRoots, fileResources } from './adapter/file-resources.js';
|
|
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';
|
|
15
|
+
import { checkAbort } from './figma-file.js';
|
|
16
|
+
import { readFigFile, readFigmaClipboardHtml } from './taco/figma-import/index.js';
|
|
17
|
+
/**
|
|
18
|
+
* Checks for the markers Figma adds to clipboard HTML.
|
|
19
|
+
* @param html - Clipboard HTML to inspect.
|
|
20
|
+
* @returns Whether both Figma markers are present.
|
|
21
|
+
*/
|
|
22
|
+
export const holdsFigmaData = (html) => html.includes('(figmeta)') && html.includes('(figma)');
|
|
23
|
+
/** Report description for images whose bytes are unavailable on the clipboard. */
|
|
24
|
+
export const MISSING_IMAGES = clipboard.MISSING_IMAGE_REPORT;
|
|
25
|
+
const STAND_IN = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
26
|
+
const ids = () => { let next = 0; return () => `f${++next}`; };
|
|
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]]));
|
|
38
|
+
const reader = result.report.filter(entry => entry.nodeType !== 'CANVAS' || entry.reason === 'variable mode').map((entry) => {
|
|
39
|
+
const layer = result.layerIds[entry.nodeId];
|
|
40
|
+
const pageId = pageIds.get(entry.nodeId);
|
|
41
|
+
const ids = pageId ? [pageId] : layer === undefined ? undefined : bySource.get(layer);
|
|
42
|
+
return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry.reason), ...(ids && { ids }) };
|
|
43
|
+
});
|
|
44
|
+
return { report: grouped([...reader, ...dropped, ...convertEntries(converted.report, true), ...extra, ...fonts]), derive };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Imports Figma clipboard HTML as editable layers.
|
|
48
|
+
* @param html - Clipboard HTML containing Figma data.
|
|
49
|
+
* @returns Paste payload and conversion report.
|
|
50
|
+
* @throws An error if the input contains no readable Figma layers.
|
|
51
|
+
*/
|
|
52
|
+
export function readFigmaClipboard(html) {
|
|
53
|
+
const { meta, message } = readFigmaClipboardHtml(html), missing = new Set();
|
|
54
|
+
const { result, sources } = walkMessage(message, {
|
|
55
|
+
idSource: ids(), roots: 'clipboard-selection', bindVariables: false, textStyles: false,
|
|
56
|
+
images: (hash) => { missing.add(`figma-image-${hash}`); return { bytes: STAND_IN, mimeType: 'image/png' }; },
|
|
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);
|
|
81
|
+
const assetIds = [...missing].filter((id) => Object.hasOwn(payload.assets, id));
|
|
82
|
+
for (const id of assetIds)
|
|
83
|
+
delete payload.assets[id];
|
|
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 };
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Reads a saved Figma design file on the calling thread.
|
|
90
|
+
* @param bytes - Saved Figma design file.
|
|
91
|
+
* @param options - Cancellation and progress options.
|
|
92
|
+
* @returns All public pages in file order, editable component and resource records, images and a report of font faces and conversion losses.
|
|
93
|
+
* @throws The abort reason or a file read or conversion error.
|
|
94
|
+
*/
|
|
95
|
+
export function readFigmaFile(bytes, options = {}) {
|
|
96
|
+
const { signal, progress } = options;
|
|
97
|
+
function checkpoint(stage, done, total) {
|
|
98
|
+
checkAbort(signal);
|
|
99
|
+
progress?.({ stage, done, ...(total !== undefined && { total }) });
|
|
100
|
+
checkAbort(signal);
|
|
101
|
+
}
|
|
102
|
+
checkpoint('decode', 0, 1);
|
|
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();
|
|
167
|
+
const result = readFileMessage(file.message, {
|
|
168
|
+
idSource: ids(), roots: 'pages',
|
|
169
|
+
images: (hash) => { const bytes = file.images.get(hash); return bytes ? { bytes } : undefined; },
|
|
170
|
+
});
|
|
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;
|
|
195
|
+
const expandedRadii = expandedRadiusRoots(result);
|
|
196
|
+
for (const id of expandedRadii.keys())
|
|
197
|
+
geometry.nodes[id] = { ...geometry.nodes[id], fileExpanded: true };
|
|
198
|
+
for (const layer of result.sources.styleLayers.values())
|
|
199
|
+
geometry.nodes[layer.id] = { ...layer, fileStyle: true };
|
|
200
|
+
const converted = allPages(geometry, {
|
|
201
|
+
assetSrc: (_id, asset) => `data:${asset.mimeType};base64,`,
|
|
202
|
+
});
|
|
203
|
+
const extra = [];
|
|
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);
|
|
223
|
+
const reader = result.report.filter(e => !e.reason.startsWith('variable bindings left out, their values kept:'));
|
|
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 };
|
|
230
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Importer } from '@moondraft/editor/core';
|
|
2
|
+
import { type SvgParse } from './taco/svg-import/public-types.ts';
|
|
3
|
+
import type { OpenFigmaOptions } from './figma-file.ts';
|
|
4
|
+
export type { ImportDocument, ImportEnv, ImportInput, ImportPayload, ImportProgress, ImportRead, ImportReportEntry, Importer } from '@moondraft/editor/core';
|
|
5
|
+
export { openFigmaFile, type OpenFigmaOptions, type WorkerLike } from './figma-file.ts';
|
|
6
|
+
/** Options for registering an SVG importer. */
|
|
7
|
+
export interface SvgImporterOptions {
|
|
8
|
+
/** Parses markup into an element tree (default: the browser's DOMParser). */
|
|
9
|
+
parseSvg?: SvgParse;
|
|
10
|
+
}
|
|
11
|
+
/** SVG files (image/svg+xml, or a .svg name) and SVG markup pasted as text, as editable layers. A file over the
|
|
12
|
+
* importer's byte cap (DEFAULT_SVG_IMPORT_LIMITS.inputBytes) is refused before it is read.
|
|
13
|
+
* @param options - Parser configuration.
|
|
14
|
+
* @returns An importer that produces editable layer payloads.
|
|
15
|
+
*/
|
|
16
|
+
export declare function svgImporter(options?: SvgImporterOptions): Importer;
|
|
17
|
+
/** Options for registering a Figma importer. */
|
|
18
|
+
export interface FigmaImporterOptions {
|
|
19
|
+
/** Factory for a dedicated worker. Defaults to a module worker when available. Pass null to read on this thread. */
|
|
20
|
+
worker?: OpenFigmaOptions['worker'];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Imports Figma clipboard HTML as editable layers and .fig files as full documents.
|
|
24
|
+
* @param options - Worker configuration for file imports.
|
|
25
|
+
* @returns An importer for Figma files and clipboard content.
|
|
26
|
+
*/
|
|
27
|
+
export declare function figmaImporter(options?: FigmaImporterOptions): Importer;
|
|
28
|
+
export { payloadFromSyntax } from './syntax.ts';
|
|
29
|
+
export { serializeImportDocument } from './serialize.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { DEFAULT_SVG_IMPORT_LIMITS } from './taco/svg-import/public-types.js';
|
|
2
|
+
import { checkAbort } from './figma-file.js';
|
|
3
|
+
export { openFigmaFile } from './figma-file.js';
|
|
4
|
+
const SVG_TEXT = /^\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)*(?:<!doctype[^>]*>\s*)?<svg[\s>]/i;
|
|
5
|
+
const nameOf = (file) => file?.name ?? '';
|
|
6
|
+
const bytesOf = async (file) => new Uint8Array(await file.arrayBuffer());
|
|
7
|
+
const mb = (n) => `${Math.round(n / 1024 / 1024)} MB`;
|
|
8
|
+
/** SVG files (image/svg+xml, or a .svg name) and SVG markup pasted as text, as editable layers. A file over the
|
|
9
|
+
* importer's byte cap (DEFAULT_SVG_IMPORT_LIMITS.inputBytes) is refused before it is read.
|
|
10
|
+
* @param options - Parser configuration.
|
|
11
|
+
* @returns An importer that produces editable layer payloads.
|
|
12
|
+
*/
|
|
13
|
+
export function svgImporter(options = {}) {
|
|
14
|
+
const cap = DEFAULT_SVG_IMPORT_LIMITS.inputBytes;
|
|
15
|
+
return {
|
|
16
|
+
name: 'SVG',
|
|
17
|
+
accepts: ({ file, html, text }) => (file ? /svg/i.test(file.type) || /\.svg$/i.test(nameOf(file)) : !html?.trim() && !!text && SVG_TEXT.test(text)),
|
|
18
|
+
async read(input, env) {
|
|
19
|
+
const file = input.file;
|
|
20
|
+
if (file && file.size > cap)
|
|
21
|
+
throw new Error(`${nameOf(file) || 'the file'} is ${mb(file.size)}, over the ${mb(cap)} an SVG may have`);
|
|
22
|
+
const { readSvg } = await import('./svg.js'), markup = file ? await file.text() : input.text ?? '';
|
|
23
|
+
checkAbort(env.signal);
|
|
24
|
+
const name = nameOf(file).replace(/\.svg$/i, '');
|
|
25
|
+
return readSvg(markup, { fonts: env.fonts, ...(name ? { name } : {}), ...(options.parseSvg ? { parseSvg: options.parseSvg } : {}) });
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Imports Figma clipboard HTML as editable layers and .fig files as full documents.
|
|
31
|
+
* @param options - Worker configuration for file imports.
|
|
32
|
+
* @returns An importer for Figma files and clipboard content.
|
|
33
|
+
*/
|
|
34
|
+
export function figmaImporter(options = {}) {
|
|
35
|
+
const holds = (html) => !!html && html.includes('(figmeta)') && html.includes('(figma)');
|
|
36
|
+
return {
|
|
37
|
+
name: 'Figma',
|
|
38
|
+
accepts: ({ file, html }) => (file ? /\.fig$/i.test(nameOf(file)) : holds(html)),
|
|
39
|
+
async read(input, env) {
|
|
40
|
+
if (!input.file)
|
|
41
|
+
return (await import('./figma.js')).readFigmaClipboard(input.html ?? '');
|
|
42
|
+
const { openFigmaFile } = await import('./figma-file.js');
|
|
43
|
+
return openFigmaFile(await bytesOf(input.file), {
|
|
44
|
+
signal: env.signal, progress: env.progress, ...(options.worker !== undefined ? { worker: options.worker } : {}),
|
|
45
|
+
});
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export { payloadFromSyntax } from './syntax.js';
|
|
50
|
+
export { serializeImportDocument } from './serialize.js';
|
package/dist/report.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ImportReportEntry } from '@moondraft/editor/core';
|
|
2
|
+
import type { DocumentJSON } from '@moondraft/editor/schema';
|
|
3
|
+
import type { ConvertReport } from './adapter/convert.ts';
|
|
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
|
+
*/
|
|
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>;
|
|
26
|
+
/** Builds a lookup from reader IDs to their converted layers. */
|
|
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
|
+
};
|
|
35
|
+
/** Turns adapter diagnostics into import reports. */
|
|
36
|
+
export declare function convertEntries(report: ConvertReport, details?: boolean): ImportReportEntry[];
|
|
37
|
+
/**
|
|
38
|
+
* Collects each distinct face used by a text layer or an instance override.
|
|
39
|
+
* @param document - Converted document with its layer and override IDs.
|
|
40
|
+
* @returns One occurrence per face and layer, ready to group with other report entries.
|
|
41
|
+
*/
|
|
42
|
+
export declare function fontEntries(document: DocumentJSON): ImportReportEntry[];
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
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
|
+
*/
|
|
23
|
+
export function grouped(entries) {
|
|
24
|
+
const out = new Map();
|
|
25
|
+
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) ?? []);
|
|
29
|
+
if (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]));
|
|
34
|
+
}
|
|
35
|
+
else
|
|
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 };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Builds a lookup from reader IDs to their converted layers. */
|
|
73
|
+
export function layersBySource(document) {
|
|
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;
|
|
92
|
+
for (const model of document.models) {
|
|
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
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return { bySource, pages, fonts, derive };
|
|
104
|
+
}
|
|
105
|
+
/** Turns adapter diagnostics into import reports. */
|
|
106
|
+
export function convertEntries(report, details = false) {
|
|
107
|
+
const entries = (counts, category, kind, prefix = '') => [...counts].map(([what, count]) => {
|
|
108
|
+
const ids = report.layerIds.get(`${category}:${what}`);
|
|
109
|
+
return { kind, what: prefix + what, count, ...(ids?.length && { ids }) };
|
|
110
|
+
});
|
|
111
|
+
return [
|
|
112
|
+
...entries(report.dropped, 'dropped', 'left-out'),
|
|
113
|
+
...(details ? [
|
|
114
|
+
...entries(report.approximations, 'note', 'approximated'),
|
|
115
|
+
...entries(report.expressionErrors, 'expression', 'left-out', 'Expression error: '),
|
|
116
|
+
] : []),
|
|
117
|
+
];
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Collects each distinct face used by a text layer or an instance override.
|
|
121
|
+
* @param document - Converted document with its layer and override IDs.
|
|
122
|
+
* @returns One occurrence per face and layer, ready to group with other report entries.
|
|
123
|
+
*/
|
|
124
|
+
export function fontEntries(document) {
|
|
125
|
+
const entries = [];
|
|
126
|
+
for (const m of document.models)
|
|
127
|
+
collectFaces(m, entries);
|
|
128
|
+
return entries;
|
|
129
|
+
}
|
|
130
|
+
function collectFaces(m, entries) {
|
|
131
|
+
function faces(styles, id) {
|
|
132
|
+
for (const what of new Set(styles?.map(s => s.family + '/' + s.style)))
|
|
133
|
+
entries.push({ kind: 'font', what, count: 1, ids: [id] });
|
|
134
|
+
}
|
|
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);
|
|
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
|
+
}
|
package/dist/svg.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ImportEnv, ImportPayload } from '@moondraft/editor/core';
|
|
2
|
+
import { type SvgMeasureText, type SvgParse } from './taco/svg-import/index.ts';
|
|
3
|
+
/** Options for reading editable layers from SVG. */
|
|
4
|
+
export interface SvgReadOptions {
|
|
5
|
+
/** The root layer's name (default: the SVG's <title>, else "SVG"). */
|
|
6
|
+
name?: string;
|
|
7
|
+
/** Parses markup into an element tree (default: the browser's DOMParser). */
|
|
8
|
+
parseSvg?: SvgParse;
|
|
9
|
+
/** Loaded faces used to choose a family from the SVG's list. With no faces, Inter is treated as available. If no family matches, the first requested family is kept. */
|
|
10
|
+
fonts?: ImportEnv['fonts'];
|
|
11
|
+
/** Measures a text run (default: an estimate from Inter's average advance and its ascent and descent). */
|
|
12
|
+
measureText?: SvgMeasureText;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Parses SVG with the browser's XML parser.
|
|
16
|
+
* @param text - SVG markup.
|
|
17
|
+
* @returns The document element, which may be a parser error element.
|
|
18
|
+
*/
|
|
19
|
+
export declare const domParseSvg: SvgParse;
|
|
20
|
+
/**
|
|
21
|
+
* Estimates a text run's metrics from Inter's average advance, ascent and descent.
|
|
22
|
+
* @param run - Text and font sizing for the run.
|
|
23
|
+
* @returns The estimated width, ascent and descent.
|
|
24
|
+
*/
|
|
25
|
+
export declare const estimateText: SvgMeasureText;
|
|
26
|
+
/** Imports SVG markup as a paste payload, with what was approximated or left out. Throws when the importer refuses
|
|
27
|
+
* (over DEFAULT_SVG_IMPORT_LIMITS.inputBytes, not well-formed, not an SVG). The markup goes through importSvgMarkup,
|
|
28
|
+
* which counts its bytes against the cap and imports nested data-URI SVG images.
|
|
29
|
+
* @param markup - SVG markup.
|
|
30
|
+
* @param options - Parser, font and measurement settings.
|
|
31
|
+
* @returns Paste payload and report of conversion losses and font faces used by imported text.
|
|
32
|
+
*/
|
|
33
|
+
export declare function readSvg(markup: string, options?: SvgReadOptions): ImportPayload;
|
package/dist/svg.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { svgDocument, toDocument, toPayload } from './adapter/index.js';
|
|
2
|
+
import { convertEntries, fontEntries, grouped, layersBySource } from './report.js';
|
|
3
|
+
import { importSvgMarkup, isSvgImportRefusal } from './taco/svg-import/index.js';
|
|
4
|
+
/**
|
|
5
|
+
* Parses SVG with the browser's XML parser.
|
|
6
|
+
* @param text - SVG markup.
|
|
7
|
+
* @returns The document element, which may be a parser error element.
|
|
8
|
+
*/
|
|
9
|
+
export const domParseSvg = (text) => {
|
|
10
|
+
if (typeof DOMParser === 'undefined')
|
|
11
|
+
throw new Error('no SVG parser here: pass parseSvg');
|
|
12
|
+
return new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Estimates a text run's metrics from Inter's average advance, ascent and descent.
|
|
16
|
+
* @param run - Text and font sizing for the run.
|
|
17
|
+
* @returns The estimated width, ascent and descent.
|
|
18
|
+
*/
|
|
19
|
+
export const estimateText = (run) => {
|
|
20
|
+
const { text, fontSize, letterSpacing } = run, length = [...text].length;
|
|
21
|
+
return { width: length * fontSize * 0.55 + Math.max(0, length - 1) * letterSpacing, ascent: fontSize * 0.97, descent: fontSize * 0.24 };
|
|
22
|
+
};
|
|
23
|
+
/** Imports SVG markup as a paste payload, with what was approximated or left out. Throws when the importer refuses
|
|
24
|
+
* (over DEFAULT_SVG_IMPORT_LIMITS.inputBytes, not well-formed, not an SVG). The markup goes through importSvgMarkup,
|
|
25
|
+
* which counts its bytes against the cap and imports nested data-URI SVG images.
|
|
26
|
+
* @param markup - SVG markup.
|
|
27
|
+
* @param options - Parser, font and measurement settings.
|
|
28
|
+
* @returns Paste payload and report of conversion losses and font faces used by imported text.
|
|
29
|
+
*/
|
|
30
|
+
export function readSvg(markup, options = {}) {
|
|
31
|
+
const fonts = options.fonts ?? [], families = new Set(fonts.map((f) => f.family.toLowerCase()));
|
|
32
|
+
const fontAvailable = (family) => (families.size ? families.has(family.toLowerCase()) : /^inter$/i.test(family));
|
|
33
|
+
let next = 0;
|
|
34
|
+
const result = importSvgMarkup(markup, { parseSvg: options.parseSvg ?? domParseSvg, idSource: () => `s${++next}`, fontAvailable, measureText: options.measureText ?? estimateText, ...(options.name !== undefined ? { name: options.name } : {}) });
|
|
35
|
+
if (isSvgImportRefusal(result))
|
|
36
|
+
throw new Error(result.message);
|
|
37
|
+
const converted = toDocument(svgDocument(result, options.name ?? result.root.name), 0);
|
|
38
|
+
const { payload, report } = toPayload(converted), bySource = layersBySource(converted.doc);
|
|
39
|
+
const taco = result.report.filter((e) => e.kind !== 'auto-layout').map((e) => {
|
|
40
|
+
const ids = e.nodeId === undefined ? undefined : bySource.get(e.nodeId);
|
|
41
|
+
return { kind: e.kind, what: e.what, count: 1, ...(ids && { ids }) };
|
|
42
|
+
});
|
|
43
|
+
return { payload, report: grouped([...taco, ...convertEntries(report), ...fontEntries(converted.doc)]) };
|
|
44
|
+
}
|