@moondraft/import 0.0.0-stage → 0.1.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 +7 -0
- package/LICENSE +34 -0
- package/README.md +36 -2
- package/SOURCE.md +169 -0
- package/dist/adapter/convert.d.ts +122 -0
- package/dist/adapter/convert.js +2302 -0
- package/dist/adapter/figma.d.ts +9 -0
- package/dist/adapter/figma.js +30 -0
- package/dist/adapter/file-components.d.ts +14 -0
- package/dist/adapter/file-components.js +262 -0
- package/dist/adapter/file-resources.d.ts +29 -0
- package/dist/adapter/file-resources.js +562 -0
- package/dist/adapter/index.d.ts +6 -0
- package/dist/adapter/index.js +9 -0
- package/dist/adapter/link.d.ts +45 -0
- package/dist/adapter/link.js +688 -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 +44 -0
- package/dist/adapter/variables.js +103 -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 +96 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +49 -0
- package/dist/report.d.ts +15 -0
- package/dist/report.js +69 -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 +38 -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 +11 -0
- package/dist/taco/figma-import/import/carry.js +33 -0
- package/dist/taco/figma-import/import/componentProps.d.ts +84 -0
- package/dist/taco/figma-import/import/componentProps.js +313 -0
- package/dist/taco/figma-import/import/componentSets.d.ts +83 -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/frame.d.ts +21 -0
- package/dist/taco/figma-import/import/converters/frame.js +55 -0
- package/dist/taco/figma-import/import/converters/gradient.d.ts +72 -0
- package/dist/taco/figma-import/import/converters/gradient.js +106 -0
- package/dist/taco/figma-import/import/converters/group.d.ts +21 -0
- package/dist/taco/figma-import/import/converters/group.js +39 -0
- package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
- package/dist/taco/figma-import/import/converters/image.js +83 -0
- package/dist/taco/figma-import/import/converters/layout.d.ts +34 -0
- package/dist/taco/figma-import/import/converters/layout.js +168 -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 +9 -0
- package/dist/taco/figma-import/import/converters/section.js +35 -0
- package/dist/taco/figma-import/import/converters/shared.d.ts +68 -0
- package/dist/taco/figma-import/import/converters/shared.js +362 -0
- package/dist/taco/figma-import/import/converters/text.d.ts +41 -0
- package/dist/taco/figma-import/import/converters/text.js +576 -0
- package/dist/taco/figma-import/import/converters/vector.d.ts +84 -0
- package/dist/taco/figma-import/import/converters/vector.js +468 -0
- package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +98 -0
- package/dist/taco/figma-import/import/converters/vectorNetwork.js +385 -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 +163 -0
- package/dist/taco/figma-import/import/instances.js +1323 -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 +46 -0
- package/dist/taco/figma-import/import/styles.js +42 -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 +136 -0
- package/dist/taco/figma-import/import/variables.js +762 -0
- package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
- package/dist/taco/figma-import/import/variantTrees.js +480 -0
- package/dist/taco/figma-import/import/walk.d.ts +159 -0
- package/dist/taco/figma-import/import/walk.js +1297 -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 +10 -0
- package/dist/taco/figma-import/kiwi/message.js +145 -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 +5635 -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 +94 -0
- package/dist/taco/model/component-evaluation.js +548 -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 +372 -0
- package/dist/taco/model/instance-resolver.js +1748 -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 +74 -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 +2347 -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 +54 -4
|
@@ -0,0 +1,3506 @@
|
|
|
1
|
+
import { resolveLinearCalls } from "./linear-call.js";
|
|
2
|
+
import { checkSceneNode, layerOverrideFieldNames } from "./codec.js";
|
|
3
|
+
import { isAgentHiddenNodeField, withoutAgentHiddenFields } from "./agent-hidden-fields.js";
|
|
4
|
+
import { computableFieldsOf, effectivePropertyValue } from "./component-properties.js";
|
|
5
|
+
import { expressionFieldContext } from "./component-expressions.js";
|
|
6
|
+
import { checkComponentValidity, invalidCombinationProblem } from "./component-validity.js";
|
|
7
|
+
import { checkExpressionSource } from "./expressions/check.js";
|
|
8
|
+
import { expressionNameProblem, formatExpressionName, normalizeExpressionName } from "./expressions/names.js";
|
|
9
|
+
import { BARE_OVER_KEY, buildNodes, ComponentCallError, componentLayers, componentNames, componentPropertyList, expressionBacktickHint, CONNECTOR_END_FORMS, toolShorthand, INSTANCE_OVER_ARGUMENT, INSTANCE_PROPS_ARGUMENT, layerReferenceText, layerSyntaxReader, modelFieldsOf, NodeBuildError, OVERRIDE_TEXT_STYLE_FIELDS, overridePaths, overridesFromSyntax, pathNetworkOf, placedPath, propertyInProps, propertyValueFromSyntax, readVariables, readLayerReference, resolveLayerCall, ShortArgumentError, shortNamesOf, componentAtPath, INSTANCE_SLOTS_ARGUMENT, mapSlotContents, slotContentCalls, slotContentOf, slotSummaryRefusal, slotPropertiesOf, } from "./node-builder.js";
|
|
10
|
+
import { connectorAnchorPoint } from "./connector-geometry.js";
|
|
11
|
+
import { getNodeBounds } from "./geometry.js";
|
|
12
|
+
import { resolvedShownComponents } from "./override-remap.js";
|
|
13
|
+
import { withAxisSizing } from "./layout/node-sizing.js";
|
|
14
|
+
import { componentPropertyId, isValuedComponentProperty } from "./types.js";
|
|
15
|
+
import { vectorNetworkFromSvgPathData, vectorNetworkToStrokePathData } from "./vector-network.js";
|
|
16
|
+
import { findVariable, locatedVariableValue, nodeSupportsVariableProperty, variableSupportsProperty } from "./variables.js";
|
|
17
|
+
import { withVariableValue } from "./variable-modes.js";
|
|
18
|
+
import { isVariableReference, readVariableArgument, variableArgumentProperties, variableCall, variableNameFor, variableReference, VariableReferenceError, withBoundVariables, } from "./variable-references.js";
|
|
19
|
+
/*
|
|
20
|
+
* The layer syntax as the single text parameter `do` of three agent tools, `read`, `build` and
|
|
21
|
+
* `edit`, written so that it needs no JSON escapes inside the JSON string that carries it (the `"tool"`
|
|
22
|
+
* spelling of `NodeBuildOptions.syntax`: single quotes, a quote inside written twice, no backslash, `;` between
|
|
23
|
+
* rules). This file holds the parts that need no editor: the printer (layers to source), the build command
|
|
24
|
+
* (`in #parent at:0; ...`) and the edit rules (`set <matcher> { k:v, -k }`, `add`, `move`, `remove`, `replace`, `convert`), which
|
|
25
|
+
* expand into the model's own `node.patch`, `node.replace`, `node.move` and `node.remove` operations, `node.build` and `component.convert`.
|
|
26
|
+
* A call may name a component (`button(text:'Buy')`, `forms.text()`; see `componentNames` in node-builder.ts), which
|
|
27
|
+
* `node.build` receives as `instance(componentId:..., ...)`.
|
|
28
|
+
* A host turns them into tools (`@taco-design/layer-syntax-tools`).
|
|
29
|
+
*/
|
|
30
|
+
/** A text of the tools that cannot be read or carried out; the message says what to write instead. */
|
|
31
|
+
export class LayerSyntaxError extends Error {
|
|
32
|
+
missingLayerId;
|
|
33
|
+
/**
|
|
34
|
+
* @param missingLayerId For "There is no layer #id in the scope", the id: a caller that can look outside the scope
|
|
35
|
+
* (in the components) may say where the layer is instead.
|
|
36
|
+
*/
|
|
37
|
+
constructor(message, missingLayerId) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.missingLayerId = missingLayerId;
|
|
40
|
+
this.name = "LayerSyntaxError";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
44
|
+
const clone = (value) => structuredClone(value);
|
|
45
|
+
function deepEqual(left, right) {
|
|
46
|
+
if (left === right)
|
|
47
|
+
return true;
|
|
48
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
49
|
+
return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => deepEqual(item, right[index]));
|
|
50
|
+
}
|
|
51
|
+
if (!isRecord(left) || !isRecord(right))
|
|
52
|
+
return false;
|
|
53
|
+
const keys = Object.keys(left);
|
|
54
|
+
return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && deepEqual(left[key], right[key]));
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* A document with no layers and no styles, for building a layer only to compare it with one read: the printer
|
|
58
|
+
* never relies on a value it gives, as every value that depends on the document's styles is printed.
|
|
59
|
+
*/
|
|
60
|
+
const STAND_IN_DOCUMENT = {
|
|
61
|
+
nodes: {}, theme: { textStyles: {}, defaultTextStyleId: "", codeStyles: {}, defaultCodeStyleId: "stand-in-code-style" },
|
|
62
|
+
};
|
|
63
|
+
const PLAIN_CONTEXT = { document: STAND_IN_DOCUMENT, names: componentNames(STAND_IN_DOCUMENT) };
|
|
64
|
+
/** The stand-in document with `components` and the layers of theirs that were read. */
|
|
65
|
+
function syntaxContext(components, variables) {
|
|
66
|
+
if (variables !== undefined && Object.keys(variables).length > 0) {
|
|
67
|
+
const plain = syntaxContext(components);
|
|
68
|
+
const document = { ...plain.document, theme: { ...plain.document.theme, variableCollections: variables } };
|
|
69
|
+
return { document, names: plain.names };
|
|
70
|
+
}
|
|
71
|
+
if (components === undefined || components.definitions.length === 0)
|
|
72
|
+
return PLAIN_CONTEXT;
|
|
73
|
+
const nodes = {};
|
|
74
|
+
const put = (table, key, value) => Object.defineProperty(table, key, { value, enumerable: true, writable: true, configurable: true });
|
|
75
|
+
const visit = (id, depth) => {
|
|
76
|
+
if (depth > 1000)
|
|
77
|
+
throw new LayerSyntaxError(`The layers of a component are nested more than 1000 deep at #${id}.`);
|
|
78
|
+
const node = components.node(id);
|
|
79
|
+
if (node === undefined || Object.hasOwn(nodes, id))
|
|
80
|
+
return;
|
|
81
|
+
put(nodes, id, node);
|
|
82
|
+
for (const child of "children" in node && Array.isArray(node.children) ? node.children : [])
|
|
83
|
+
visit(child, depth + 1);
|
|
84
|
+
};
|
|
85
|
+
const table = {};
|
|
86
|
+
for (const definition of components.definitions) {
|
|
87
|
+
put(table, definition.id, definition);
|
|
88
|
+
visit(definition.rootId, 0);
|
|
89
|
+
}
|
|
90
|
+
const document = { ...STAND_IN_DOCUMENT, nodes, components: table };
|
|
91
|
+
return { document, names: componentNames(document) };
|
|
92
|
+
}
|
|
93
|
+
/** A component call refused, as a LayerSyntaxError naming `where`. */
|
|
94
|
+
function componentRefusal(error, where) {
|
|
95
|
+
if (error instanceof ComponentCallError)
|
|
96
|
+
throw new LayerSyntaxError(`${where}: ${error.message}`);
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
// Values
|
|
101
|
+
// A word may hold dots between its parts, as a component's call name does (icon.plus).
|
|
102
|
+
const WORD = /^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/;
|
|
103
|
+
const KEY = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
104
|
+
const COLOUR = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
|
105
|
+
const RESERVED_WORDS = new Set(["true", "false", "null", "all", "set", "in", "at"]);
|
|
106
|
+
/**
|
|
107
|
+
* The order to print an object's keys in, for an object whose keys must not come out in property order: JavaScript
|
|
108
|
+
* lists keys that are whole numbers ("2", "10") first and by value, whatever order they were added in.
|
|
109
|
+
*/
|
|
110
|
+
const PRINT_KEY_ORDER = new WeakMap();
|
|
111
|
+
/** The objects whose keys print bare with dots between names (`over:{Button.Label:{...}}`), as the tool spelling reads such a key as one word. */
|
|
112
|
+
const DOTTED_KEYS = new WeakSet();
|
|
113
|
+
/** Values that print as a text already written: a slot list, `( ... )` with the calls of its layers. */
|
|
114
|
+
const PRINTED_TEXT = new WeakMap();
|
|
115
|
+
/** A value that prints as `text`. */
|
|
116
|
+
function printedText(text) {
|
|
117
|
+
const value = Object.freeze([]);
|
|
118
|
+
PRINTED_TEXT.set(value, text);
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* A value in the tool spelling: a colour and a lower-case word bare, any other string in single quotes with
|
|
123
|
+
* a quote inside written twice, lists in `(...)` and objects in `{...}`. It never prints a double quote or a
|
|
124
|
+
* backslash: a string holding a backslash is refused, as this syntax has no way to write one.
|
|
125
|
+
*/
|
|
126
|
+
export function printLayerValue(value, where = "a value") {
|
|
127
|
+
const text = value !== null && typeof value === "object" ? PRINTED_TEXT.get(value) : undefined;
|
|
128
|
+
if (text !== undefined)
|
|
129
|
+
return text;
|
|
130
|
+
if (isVariableReference(value)) {
|
|
131
|
+
if (value.var.includes("\\"))
|
|
132
|
+
throw new LayerSyntaxError(`${where} names a variable whose name holds a backslash, which the layer syntax cannot write.`);
|
|
133
|
+
return variableCall(value.var);
|
|
134
|
+
}
|
|
135
|
+
if (typeof value === "string") {
|
|
136
|
+
if (value.includes("\\"))
|
|
137
|
+
throw new LayerSyntaxError(`${where} holds a backslash, which this syntax cannot write; read it as JSON instead.`);
|
|
138
|
+
if (COLOUR.test(value) || (WORD.test(value) && !RESERVED_WORDS.has(value)))
|
|
139
|
+
return value;
|
|
140
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
141
|
+
}
|
|
142
|
+
if (typeof value === "number") {
|
|
143
|
+
if (!Number.isFinite(value))
|
|
144
|
+
throw new LayerSyntaxError(`${where} is ${String(value)}, which is not a number the syntax can write.`);
|
|
145
|
+
return String(value);
|
|
146
|
+
}
|
|
147
|
+
if (typeof value === "boolean")
|
|
148
|
+
return String(value);
|
|
149
|
+
if (Array.isArray(value))
|
|
150
|
+
return `(${value.map((item, index) => printLayerValue(item, `${where}[${index}]`)).join(", ")})`;
|
|
151
|
+
if (isRecord(value)) {
|
|
152
|
+
const gradient = gradientCallOf(value);
|
|
153
|
+
if (gradient !== undefined)
|
|
154
|
+
return gradient;
|
|
155
|
+
return `{${(PRINT_KEY_ORDER.get(value) ?? Object.keys(value)).map((key) => [key, value[key]]).map(([key, item]) => `${(KEY.test(key) || (DOTTED_KEYS.has(value) && BARE_OVER_KEY.test(key))) && !RESERVED_WORDS.has(key) ? key : printLayerValue(key, `a key of ${where}`)}:`
|
|
156
|
+
+ `${printLayerValue(item, `${where}.${key}`)}`).join(", ")}}`;
|
|
157
|
+
}
|
|
158
|
+
throw new LayerSyntaxError(`${where} is ${value === null ? "null" : typeof value}, which the syntax cannot write.`);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* A radial gradient paint as the tool spelling writes it, `radial(#fff, (#000, 0.8))`,
|
|
162
|
+
* when that call reads back as exactly this paint; undefined otherwise (another field
|
|
163
|
+
* such as opacity, a centre, or a stop that is not a colour and an offset). Stops spread evenly print as colours alone.
|
|
164
|
+
*/
|
|
165
|
+
function gradientCallOf(paint) {
|
|
166
|
+
if (paint.kind !== "radial-gradient")
|
|
167
|
+
return undefined;
|
|
168
|
+
const keys = ["kind", "stops"];
|
|
169
|
+
if (Object.keys(paint).length !== keys.length || !keys.every((key) => Object.hasOwn(paint, key)))
|
|
170
|
+
return undefined;
|
|
171
|
+
const stops = paint.stops;
|
|
172
|
+
if (!Array.isArray(stops) || stops.length < 2)
|
|
173
|
+
return undefined;
|
|
174
|
+
const plain = stops.every((stop) => isRecord(stop) && Object.keys(stop).length === 2 && typeof stop.color === "string" && COLOUR.test(stop.color)
|
|
175
|
+
&& typeof stop.offset === "number" && stop.offset >= 0 && stop.offset <= 1);
|
|
176
|
+
if (!plain)
|
|
177
|
+
return undefined;
|
|
178
|
+
// Spread evenly as the reader spreads stops written as colours alone: index / (count - 1), the same division.
|
|
179
|
+
const even = stops.every((stop, index) => stop.offset === index / (stops.length - 1));
|
|
180
|
+
const written = stops.map((stop) => even ? stop.color : `(${stop.color}, ${String(stop.offset)})`);
|
|
181
|
+
return `radial(${written.join(", ")})`;
|
|
182
|
+
}
|
|
183
|
+
/** A value in the default spelling of `node.build` (JSON strings), to send a source the tools read to the editor. */
|
|
184
|
+
function defaultSpelling(value) {
|
|
185
|
+
if (isVariableReference(value))
|
|
186
|
+
return `var(${JSON.stringify(value.var)})`;
|
|
187
|
+
const content = slotContentOf(value);
|
|
188
|
+
if (content !== undefined) {
|
|
189
|
+
return `(${[...content.calls.map((call) => spellingWithPlaces([call]).source), ...(content.hostId === undefined ? [] : [JSON.stringify(content.hostId)])].join(", ")})`;
|
|
190
|
+
}
|
|
191
|
+
if (typeof value === "string")
|
|
192
|
+
return JSON.stringify(value);
|
|
193
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
194
|
+
return String(value);
|
|
195
|
+
if (Array.isArray(value))
|
|
196
|
+
return `(${value.map(defaultSpelling).join(", ")})`;
|
|
197
|
+
return `{${Object.entries(value).map(([key, item]) => `${JSON.stringify(key)}:${defaultSpelling(item)}`).join(", ")}}`;
|
|
198
|
+
}
|
|
199
|
+
/** `calls` in the default spelling, separated by `, ` as a `node.build` source, with the written place of each call and argument in it. */
|
|
200
|
+
function spellingWithPlaces(calls) {
|
|
201
|
+
const places = [];
|
|
202
|
+
let source = "";
|
|
203
|
+
const write = (call) => {
|
|
204
|
+
places.push({ spelledColumn: source.length + 1, line: call.line, column: call.column });
|
|
205
|
+
source += `${call.name}(`;
|
|
206
|
+
call.arguments.filter((argument) => argument.remove !== true).forEach((argument, index) => {
|
|
207
|
+
if (index > 0)
|
|
208
|
+
source += ", ";
|
|
209
|
+
places.push({ spelledColumn: source.length + 1, line: argument.line, column: argument.column });
|
|
210
|
+
source += `${argument.name ?? ""}${argument.name === undefined ? "" : ":"}${defaultSpelling(argument.value)}`;
|
|
211
|
+
});
|
|
212
|
+
source += ")";
|
|
213
|
+
if (call.children === undefined)
|
|
214
|
+
return;
|
|
215
|
+
source += "[";
|
|
216
|
+
call.children.forEach((child, index) => { if (index > 0)
|
|
217
|
+
source += ", "; write(child); });
|
|
218
|
+
source += "]";
|
|
219
|
+
};
|
|
220
|
+
calls.forEach((call, index) => { if (index > 0)
|
|
221
|
+
source += ", "; write(call); });
|
|
222
|
+
return { source, places };
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* `refusal`, an editor refusal of `node.build` sources re-spelled on one line, with each place it names in them
|
|
226
|
+
* (`at line 1, column 532`, `Line 1, column 532:`) turned back into the line and column of the text as written:
|
|
227
|
+
* `sources` holds the places of each source the change sent. A place that no source has, or that more than one has
|
|
228
|
+
* (one change with several sources), is left out, so that the call it names is what the refusal points to.
|
|
229
|
+
*/
|
|
230
|
+
export function writtenPlaces(refusal, sources) {
|
|
231
|
+
const placeAt = (column) => {
|
|
232
|
+
const found = sources.flatMap((places) => places.filter((place) => place.spelledColumn === column));
|
|
233
|
+
return found.length === 1 ? found[0] : undefined;
|
|
234
|
+
};
|
|
235
|
+
return refusal
|
|
236
|
+
.replace(/ at line 1, column (\d+)(?=:)/g, (_, column) => {
|
|
237
|
+
const place = placeAt(Number(column));
|
|
238
|
+
return place === undefined ? "" : ` at line ${place.line}, column ${place.column}`;
|
|
239
|
+
})
|
|
240
|
+
.replace(/\bLine 1, column (\d+): /g, (_, column) => {
|
|
241
|
+
const place = placeAt(Number(column));
|
|
242
|
+
return place === undefined ? "" : `Line ${place.line}, column ${place.column}: `;
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/** The same value as a filter compares it: colours in lower case. */
|
|
246
|
+
const comparable = (value) => {
|
|
247
|
+
const printed = printLayerValue(value);
|
|
248
|
+
return COLOUR.test(printed) ? printed.toLowerCase() : printed;
|
|
249
|
+
};
|
|
250
|
+
const asValue = (value) => value === undefined || value === null ? undefined : value;
|
|
251
|
+
/** The one paint of a solid colour as its colour, else the paint as stored. */
|
|
252
|
+
const paintValue = (paint) => {
|
|
253
|
+
if (isRecord(paint) && paint.kind === "solid" && typeof paint.color === "string" && Object.keys(paint).length === 2)
|
|
254
|
+
return paint.color;
|
|
255
|
+
return asValue(paint);
|
|
256
|
+
};
|
|
257
|
+
const deleteIn = (node, path) => {
|
|
258
|
+
const [first, ...rest] = path;
|
|
259
|
+
if (first === undefined || !Object.hasOwn(node, first))
|
|
260
|
+
return;
|
|
261
|
+
if (rest.length === 0) {
|
|
262
|
+
delete node[first];
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (!isRecord(node[first]))
|
|
266
|
+
return;
|
|
267
|
+
const inner = { ...node[first] };
|
|
268
|
+
deleteIn(inner, rest);
|
|
269
|
+
node[first] = inner;
|
|
270
|
+
};
|
|
271
|
+
const readIn = (node, path) => path.reduce((value, key) => isRecord(value) ? value[key] : undefined, node);
|
|
272
|
+
const atPath = (path, read) => ({ path, read, remove: (node) => deleteIn(node, path) });
|
|
273
|
+
const FILL = atPath(["style", "fills"], (node) => {
|
|
274
|
+
const fills = readIn(node, ["style", "fills"]);
|
|
275
|
+
if (!Array.isArray(fills))
|
|
276
|
+
return undefined;
|
|
277
|
+
if (fills.length === 1)
|
|
278
|
+
return paintValue(fills[0]);
|
|
279
|
+
return fills.map((paint) => paintValue(paint));
|
|
280
|
+
});
|
|
281
|
+
/** A stroke of `{paint, width}` alone: its colour when its width is 1, else `(colour, width)`. */
|
|
282
|
+
const strokeValue = (stroke) => {
|
|
283
|
+
if (!isRecord(stroke) || Object.keys(stroke).some((key) => key !== "paint" && key !== "width"))
|
|
284
|
+
return undefined;
|
|
285
|
+
const colour = paintValue(stroke.paint);
|
|
286
|
+
if (typeof colour !== "string" || typeof stroke.width !== "number")
|
|
287
|
+
return undefined;
|
|
288
|
+
return stroke.width === 1 ? colour : [colour, stroke.width];
|
|
289
|
+
};
|
|
290
|
+
const STROKE = atPath(["style", "strokes"], (node) => {
|
|
291
|
+
const strokes = readIn(node, ["style", "strokes"]);
|
|
292
|
+
return Array.isArray(strokes) && strokes.length === 1 ? strokeValue(strokes[0]) : undefined;
|
|
293
|
+
});
|
|
294
|
+
const RADIUS = atPath(["style", "cornerRadius"], (node) => {
|
|
295
|
+
const radius = readIn(node, ["style", "cornerRadius"]);
|
|
296
|
+
return typeof radius === "number" ? radius : undefined;
|
|
297
|
+
});
|
|
298
|
+
/** Shadows as `(x, y, blur, spread, #colour)`, with `inner` after the colour for an inner shadow; several as a list of them. */
|
|
299
|
+
/**
|
|
300
|
+
* `d` of a path: its points as SVG path data, when building that data again makes the same points, ids and all (as a path
|
|
301
|
+
* built by d or imported from an SVG file has them); undefined for any other path, which prints its vectorNetwork.
|
|
302
|
+
*/
|
|
303
|
+
const PATH_DATA = atPath(["vectorNetwork"], (node) => {
|
|
304
|
+
if (!isRecord(node.vectorNetwork))
|
|
305
|
+
return undefined;
|
|
306
|
+
try {
|
|
307
|
+
const data = vectorNetworkToStrokePathData(node.vectorNetwork);
|
|
308
|
+
return data !== "" && deepEqual(vectorNetworkFromSvgPathData(data, pathWindingOf(node) ?? "nonzero"), node.vectorNetwork) ? data : undefined;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return undefined;
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
/** The winding rule of a path's one region; undefined for none, several, or a rule that is not a string. */
|
|
315
|
+
function pathWindingOf(node) {
|
|
316
|
+
const regions = isRecord(node.vectorNetwork) ? node.vectorNetwork.regions : undefined;
|
|
317
|
+
const rule = Array.isArray(regions) && regions.length === 1 && isRecord(regions[0]) ? regions[0].windingRule : undefined;
|
|
318
|
+
return rule === "nonzero" || rule === "evenodd" ? rule : undefined;
|
|
319
|
+
}
|
|
320
|
+
/** `winding` of a path printed by `d`: evenodd when its region has that rule; `d` builds nonzero. */
|
|
321
|
+
const PATH_WINDING = atPath(["vectorNetwork"], (node) => pathWindingOf(node) === "evenodd" && PATH_DATA.read(node) !== undefined ? "evenodd" : undefined);
|
|
322
|
+
/** `stroke` of a path: its one stroke as `stroke` writes it, its join left to `join`. */
|
|
323
|
+
const PATH_STROKE = atPath(["style", "strokes"], (node) => {
|
|
324
|
+
const strokes = readIn(node, ["style", "strokes"]);
|
|
325
|
+
if (!Array.isArray(strokes) || strokes.length !== 1 || !isRecord(strokes[0]))
|
|
326
|
+
return undefined;
|
|
327
|
+
const { join: _join, ...stroke } = strokes[0];
|
|
328
|
+
return strokeValue(stroke);
|
|
329
|
+
});
|
|
330
|
+
/** `cap` of a path: the end both its open ends have. */
|
|
331
|
+
const PATH_CAP = {
|
|
332
|
+
path: ["startCap"],
|
|
333
|
+
read: (node) => typeof node.startCap === "string" && node.startCap === node.endCap ? node.startCap : undefined,
|
|
334
|
+
remove: (node) => { delete node.startCap; delete node.endCap; },
|
|
335
|
+
};
|
|
336
|
+
/**
|
|
337
|
+
* `join` of a path: the join every one of its strokes has. Its path names no field the printer may take out of `style`
|
|
338
|
+
* (the strokes stay in a style written by name, so that join has strokes to write into).
|
|
339
|
+
*/
|
|
340
|
+
const STROKE_JOIN = {
|
|
341
|
+
path: ["style", "strokes", "join"],
|
|
342
|
+
read: (node) => {
|
|
343
|
+
const strokes = readIn(node, ["style", "strokes"]);
|
|
344
|
+
if (!Array.isArray(strokes) || strokes.length === 0 || !strokes.every(isRecord))
|
|
345
|
+
return undefined;
|
|
346
|
+
const join = strokes[0].join;
|
|
347
|
+
return typeof join === "string" && strokes.every((stroke) => stroke.join === join) ? join : undefined;
|
|
348
|
+
},
|
|
349
|
+
remove: (node) => {
|
|
350
|
+
const strokes = readIn(node, ["style", "strokes"]);
|
|
351
|
+
if (!Array.isArray(strokes))
|
|
352
|
+
return;
|
|
353
|
+
node.style = { ...node.style, strokes: strokes.map((stroke) => {
|
|
354
|
+
if (!isRecord(stroke))
|
|
355
|
+
return stroke;
|
|
356
|
+
const { join: _join, ...rest } = stroke;
|
|
357
|
+
return rest;
|
|
358
|
+
}) };
|
|
359
|
+
},
|
|
360
|
+
};
|
|
361
|
+
const SHADOW = atPath(["style", "shadows"], (node) => {
|
|
362
|
+
const shadows = readIn(node, ["style", "shadows"]);
|
|
363
|
+
if (!Array.isArray(shadows) || shadows.length === 0)
|
|
364
|
+
return undefined;
|
|
365
|
+
const written = shadows.map((shadow) => {
|
|
366
|
+
if (!isRecord(shadow) || Object.keys(shadow).length !== 6 || (shadow.kind !== "drop" && shadow.kind !== "inner"))
|
|
367
|
+
return undefined;
|
|
368
|
+
const { x, y, blur, spread, color } = shadow;
|
|
369
|
+
if (![x, y, blur, spread].every((item) => typeof item === "number") || typeof color !== "string")
|
|
370
|
+
return undefined;
|
|
371
|
+
return [x, y, blur, spread, color, ...(shadow.kind === "inner" ? ["inner"] : [])];
|
|
372
|
+
});
|
|
373
|
+
if (written.some((item) => item === undefined))
|
|
374
|
+
return undefined;
|
|
375
|
+
return written.length === 1 ? written[0] : written;
|
|
376
|
+
});
|
|
377
|
+
const layoutReader = (field) => atPath(["layout", field], (node) => asValue(readIn(node, ["layout", field])));
|
|
378
|
+
const PAD = atPath(["layout", "padding"], (node) => {
|
|
379
|
+
const padding = readIn(node, ["layout", "padding"]);
|
|
380
|
+
if (!isRecord(padding))
|
|
381
|
+
return undefined;
|
|
382
|
+
const { top, right, bottom, left } = padding;
|
|
383
|
+
if (Object.keys(padding).length !== 4 || ![top, right, bottom, left].every((side) => typeof side === "number"))
|
|
384
|
+
return undefined;
|
|
385
|
+
if (top === right && top === bottom && top === left)
|
|
386
|
+
return top;
|
|
387
|
+
if (top === bottom && right === left)
|
|
388
|
+
return [top, right];
|
|
389
|
+
return [top, right, bottom, left];
|
|
390
|
+
});
|
|
391
|
+
/** The single run of a text of one paragraph, or undefined. */
|
|
392
|
+
const singleRun = (node) => {
|
|
393
|
+
const paragraphs = node.paragraphs;
|
|
394
|
+
if (!Array.isArray(paragraphs) || paragraphs.length !== 1 || !isRecord(paragraphs[0]))
|
|
395
|
+
return undefined;
|
|
396
|
+
const runs = paragraphs[0].runs;
|
|
397
|
+
return Array.isArray(runs) && runs.length === 1 && isRecord(runs[0]) ? runs[0] : undefined;
|
|
398
|
+
};
|
|
399
|
+
const runOverride = (field) => ({
|
|
400
|
+
path: ["paragraphs"],
|
|
401
|
+
read: (node) => asValue(readIn(singleRun(node) ?? {}, ["overrides", field])),
|
|
402
|
+
// Removes the override from every run, as a run's colour, size or weight is written for the text as a whole.
|
|
403
|
+
remove: (node) => {
|
|
404
|
+
if (!Array.isArray(node.paragraphs))
|
|
405
|
+
return;
|
|
406
|
+
node.paragraphs = node.paragraphs.map((paragraph) => !isRecord(paragraph) || !Array.isArray(paragraph.runs) ? paragraph : {
|
|
407
|
+
...paragraph,
|
|
408
|
+
runs: paragraph.runs.map((run) => {
|
|
409
|
+
if (!isRecord(run) || !isRecord(run.overrides) || !Object.hasOwn(run.overrides, field))
|
|
410
|
+
return run;
|
|
411
|
+
const { [field]: _removed, ...overrides } = run.overrides;
|
|
412
|
+
const { overrides: _old, ...rest } = run;
|
|
413
|
+
return Object.keys(overrides).length === 0 ? rest : { ...rest, overrides };
|
|
414
|
+
}),
|
|
415
|
+
});
|
|
416
|
+
},
|
|
417
|
+
});
|
|
418
|
+
const TEXT_ALIGN = {
|
|
419
|
+
path: ["paragraphs"],
|
|
420
|
+
read: (node) => Array.isArray(node.paragraphs) && node.paragraphs.length === 1 ? asValue(readIn(node.paragraphs[0], ["align"])) : undefined,
|
|
421
|
+
remove: (node) => {
|
|
422
|
+
if (Array.isArray(node.paragraphs)) {
|
|
423
|
+
node.paragraphs = node.paragraphs.map((paragraph) => {
|
|
424
|
+
if (!isRecord(paragraph))
|
|
425
|
+
return paragraph;
|
|
426
|
+
const { align: _removed, ...rest } = paragraph;
|
|
427
|
+
return rest;
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
},
|
|
431
|
+
};
|
|
432
|
+
const TEXT_CONTENT = {
|
|
433
|
+
path: ["paragraphs"],
|
|
434
|
+
read: (node) => {
|
|
435
|
+
const text = singleRun(node)?.text;
|
|
436
|
+
return typeof text === "string" && text !== "" ? text : undefined;
|
|
437
|
+
},
|
|
438
|
+
remove: () => { throw new LayerSyntaxError("the characters of a text cannot be removed; write text:'' for an empty text."); },
|
|
439
|
+
};
|
|
440
|
+
const fieldReader = (field) => atPath([field], (node) => asValue(node[field]));
|
|
441
|
+
/** Whether a connector end is attached to a layer. */
|
|
442
|
+
const isAttached = (end) => isRecord(end) && end.nodeId !== undefined;
|
|
443
|
+
const isAttachedConnector = (node) => node.type === "connector" && (isAttached(node.start) || isAttached(node.end));
|
|
444
|
+
/** An attached connector end as `from:` and `to:` write it, `#card.right`; undefined for one no form writes. */
|
|
445
|
+
function attachedEndValue(end) {
|
|
446
|
+
const { nodeId, side, anchor, point, x: _x, y: _y, ...rest } = end;
|
|
447
|
+
if (typeof nodeId !== "string" || Object.keys(rest).length > 0 || [side, anchor, point].filter((place) => place !== undefined).length > 1)
|
|
448
|
+
return undefined;
|
|
449
|
+
if (side !== undefined)
|
|
450
|
+
return typeof side === "string" ? layerReferenceText({ id: nodeId, place: side }) : undefined;
|
|
451
|
+
if (anchor !== undefined) {
|
|
452
|
+
if (!isRecord(anchor) || Object.keys(anchor).length !== 2 || (anchor.kind !== "vertex" && anchor.kind !== "edge") || typeof anchor.index !== "number")
|
|
453
|
+
return undefined;
|
|
454
|
+
return layerReferenceText({ id: nodeId, place: anchor.kind, numbers: [String(anchor.index)] });
|
|
455
|
+
}
|
|
456
|
+
if (point !== undefined) {
|
|
457
|
+
if (!isRecord(point) || Object.keys(point).length !== 2 || typeof point.x !== "number" || typeof point.y !== "number")
|
|
458
|
+
return undefined;
|
|
459
|
+
return layerReferenceText({ id: nodeId, place: "point", numbers: [String(point.x), String(point.y)] });
|
|
460
|
+
}
|
|
461
|
+
return layerReferenceText({ id: nodeId });
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* `from:` or `to:` of a connector with an attached end: the attached end as `#card.right`, a free end as `(x, y)` in
|
|
465
|
+
* the parent's coordinates. A connector with two free ends prints as x, y, w and h. `-from` and `-to` let the end go
|
|
466
|
+
* of its layer, where it was last placed.
|
|
467
|
+
*/
|
|
468
|
+
const connectorEndReader = (which) => ({
|
|
469
|
+
path: [which],
|
|
470
|
+
read: (node) => {
|
|
471
|
+
const end = node[which], frame = node.frame;
|
|
472
|
+
if (!isRecord(end) || !isAttachedConnector(node))
|
|
473
|
+
return undefined;
|
|
474
|
+
if (isAttached(end))
|
|
475
|
+
return attachedEndValue(end);
|
|
476
|
+
if (!isRecord(frame) || typeof frame.x !== "number" || typeof frame.y !== "number" || typeof end.x !== "number" || typeof end.y !== "number")
|
|
477
|
+
return undefined;
|
|
478
|
+
return [frame.x + end.x, frame.y + end.y];
|
|
479
|
+
},
|
|
480
|
+
remove: (node) => {
|
|
481
|
+
if (!isRecord(node[which]))
|
|
482
|
+
return;
|
|
483
|
+
const { nodeId: _nodeId, side: _side, anchor: _anchor, point: _point, ...free } = node[which];
|
|
484
|
+
node[which] = free;
|
|
485
|
+
},
|
|
486
|
+
});
|
|
487
|
+
/**
|
|
488
|
+
* Refuses a connector whose ends the model refuses (a side that is not one, a fraction past 1, an index that is not a
|
|
489
|
+
* whole number), with the model's reason and the forms of a connector end; the model judges the rest of the layer.
|
|
490
|
+
*/
|
|
491
|
+
function checkConnectorEnds(node, where) {
|
|
492
|
+
if (node.type !== "connector")
|
|
493
|
+
return;
|
|
494
|
+
for (const which of ["start", "end"]) {
|
|
495
|
+
const end = node[which];
|
|
496
|
+
if (isRecord(end) && end.nodeId !== undefined && end.nodeId === node.id) {
|
|
497
|
+
const name = which === "start" ? "from" : "to";
|
|
498
|
+
throw new LayerSyntaxError(`${where}: ${name}:${attachedEndValue(end) ?? `#${String(end.nodeId)}`} attaches the connector to itself, which the editor `
|
|
499
|
+
+ `does not draw. Attach it to another layer, or write ${name}:(<x>, <y>) for a free end in the parent's coordinates.`);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
const problem = checkSceneNode(node).find((entry) => /^\$\.(?:start|end)(?:\.|$)/.test(entry.path));
|
|
503
|
+
if (problem === undefined)
|
|
504
|
+
return;
|
|
505
|
+
const which = problem.path.startsWith("$.start") ? "start" : "end";
|
|
506
|
+
const end = node[which];
|
|
507
|
+
const shown = isRecord(end) ? attachedEndValue(end) : undefined;
|
|
508
|
+
throw new LayerSyntaxError(`${where}: ${which === "start" ? "from" : "to"}${shown === undefined ? "" : `:${shown}`} is refused: ${problem.message} `
|
|
509
|
+
+ `(${problem.path.replace("$.", "")}). Write ${CONNECTOR_END_FORMS}.`);
|
|
510
|
+
}
|
|
511
|
+
/** The anchors of a kind that `target` has, from index 0: how many there are. */
|
|
512
|
+
function anchorCount(target, kind) {
|
|
513
|
+
let count = 0;
|
|
514
|
+
while (count < 10_000 && connectorAnchorPoint(target, { kind, index: count }) !== undefined)
|
|
515
|
+
count += 1;
|
|
516
|
+
return count;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Why the connector end `attachment` cannot attach to `target`, the layer it names, or undefined when it can: a layer
|
|
520
|
+
* without a frame (a path), which the editor cannot place an end on and so does not draw the connector; or a corner or
|
|
521
|
+
* edge (`vertex(n)`, `edge(n)`) the layer does not have, which the editor would place as an automatic end instead.
|
|
522
|
+
*/
|
|
523
|
+
export function connectorAttachmentRefusal(attachment, target) {
|
|
524
|
+
const { where, which, end } = attachment;
|
|
525
|
+
const shown = `${which}:${attachedEndValue(end) ?? `#${end.nodeId}`}`;
|
|
526
|
+
const id = layerReferenceText({ id: end.nodeId });
|
|
527
|
+
const kind = target.type === "shape" ? target.shape : target.type;
|
|
528
|
+
if (!("frame" in target) || target.frame === undefined) {
|
|
529
|
+
return `${where}: ${shown} attaches to the ${kind} ${id}, which has no frame for a connector end to attach to, so the editor would not `
|
|
530
|
+
+ `draw the connector. Attach it to a layer with a frame (a rect, frame, text, ellipse, polygon, star, image or group).`;
|
|
531
|
+
}
|
|
532
|
+
const anchor = end.anchor;
|
|
533
|
+
if (!isRecord(anchor) || (anchor.kind !== "vertex" && anchor.kind !== "edge") || typeof anchor.index !== "number")
|
|
534
|
+
return undefined;
|
|
535
|
+
if (connectorAnchorPoint(target, { kind: anchor.kind, index: anchor.index }) !== undefined)
|
|
536
|
+
return undefined;
|
|
537
|
+
const ranges = ["vertex", "edge"].flatMap((kind) => {
|
|
538
|
+
const count = anchorCount(target, kind);
|
|
539
|
+
return count === 0 ? [] : [count === 1 ? `${kind}(0)` : `${kind}(0) to ${kind}(${count - 1})`];
|
|
540
|
+
});
|
|
541
|
+
return `${where}: ${shown} names ${anchor.kind === "vertex" ? "a corner" : "an edge"} the ${kind} ${id} does not have`
|
|
542
|
+
+ (ranges.length === 0 ? `; it has no corners or edges to attach to. Write ${CONNECTOR_END_FORMS}.` : `; it takes ${ranges.join(" and ")}.`);
|
|
543
|
+
}
|
|
544
|
+
/** The attached ends of a connector, as `ConnectorAttachment`s named by `where`. */
|
|
545
|
+
function connectorAttachments(node, where, ends = ["start", "end"]) {
|
|
546
|
+
if (node.type !== "connector")
|
|
547
|
+
return [];
|
|
548
|
+
return ends.flatMap((which) => {
|
|
549
|
+
const end = node[which];
|
|
550
|
+
return isRecord(end) && typeof end.nodeId === "string"
|
|
551
|
+
? [{ where, which: which === "start" ? "from" : "to", end: end }] : [];
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
/** Throws the refusal of the first attachment whose target `targetOf` knows and refuses; answers the others. */
|
|
555
|
+
function checkKnownAttachments(attachments, targetOf) {
|
|
556
|
+
const unknown = [];
|
|
557
|
+
for (const attachment of attachments) {
|
|
558
|
+
const target = targetOf(attachment.end.nodeId);
|
|
559
|
+
if (target === undefined) {
|
|
560
|
+
unknown.push(attachment);
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
const refusal = connectorAttachmentRefusal(attachment, target);
|
|
564
|
+
if (refusal !== undefined)
|
|
565
|
+
throw new LayerSyntaxError(refusal);
|
|
566
|
+
}
|
|
567
|
+
return unknown;
|
|
568
|
+
}
|
|
569
|
+
const CONNECTOR_START = connectorEndReader("start");
|
|
570
|
+
const CONNECTOR_END = connectorEndReader("end");
|
|
571
|
+
/**
|
|
572
|
+
* A connector with an attached end, with what the editor sets again each time it draws it left out: the editor fits
|
|
573
|
+
* its frame to the line it routes and writes where each attached end landed (`connectorFrames.ts` of the web app),
|
|
574
|
+
* so only where the ends attach and where a free end is (in the parent's coordinates) say what the connector is.
|
|
575
|
+
*/
|
|
576
|
+
function withoutPlacedConnectorEnds(node) {
|
|
577
|
+
if (!isAttachedConnector(node) || !isRecord(node.frame))
|
|
578
|
+
return node;
|
|
579
|
+
const frame = node.frame;
|
|
580
|
+
const placed = (end) => {
|
|
581
|
+
if (!isRecord(end))
|
|
582
|
+
return end;
|
|
583
|
+
const { x, y, ...rest } = end;
|
|
584
|
+
if (isAttached(end))
|
|
585
|
+
return rest;
|
|
586
|
+
return { ...rest, x: typeof x === "number" && typeof frame.x === "number" ? frame.x + x : x, y: typeof y === "number" && typeof frame.y === "number" ? frame.y + y : y };
|
|
587
|
+
};
|
|
588
|
+
return { ...node, frame: { ...frame, x: 0, y: 0, width: 0, height: 0 }, start: placed(node.start), end: placed(node.end) };
|
|
589
|
+
}
|
|
590
|
+
/** The readers of a shorthand's own short arguments and content. */
|
|
591
|
+
function readersOf(shorthand) {
|
|
592
|
+
switch (shorthand.name) {
|
|
593
|
+
case "text": return { text: TEXT_CONTENT, size: runOverride("fontSize"), weight: runOverride("fontWeight"), color: runOverride("color"),
|
|
594
|
+
font: runOverride("fontFamily"), align: TEXT_ALIGN };
|
|
595
|
+
case "code": return { source: fieldReader("source"), size: fieldReader("fontSize"), font: fieldReader("fontFamily") };
|
|
596
|
+
case "hflex":
|
|
597
|
+
case "vflex": return { fill: FILL, stroke: STROKE, radius: RADIUS, shadow: SHADOW, gap: layoutReader("gap"), pad: PAD,
|
|
598
|
+
align: layoutReader("align"), justify: layoutReader("justify") };
|
|
599
|
+
case "rect":
|
|
600
|
+
case "frame": return { fill: FILL, stroke: STROKE, radius: RADIUS, shadow: SHADOW };
|
|
601
|
+
case "ellipse":
|
|
602
|
+
case "polygon":
|
|
603
|
+
case "star": return { fill: FILL, stroke: STROKE, shadow: SHADOW };
|
|
604
|
+
case "path": return { d: PATH_DATA, fill: FILL, stroke: PATH_STROKE, shadow: SHADOW, cap: PATH_CAP, join: STROKE_JOIN, winding: PATH_WINDING };
|
|
605
|
+
case "line": return { stroke: STROKE };
|
|
606
|
+
case "image":
|
|
607
|
+
case "video": return { asset: fieldReader("assetId") };
|
|
608
|
+
case "connector": return { stroke: atPath(["stroke"], (node) => strokeValue(node.stroke)), from: CONNECTOR_START, to: CONNECTOR_END };
|
|
609
|
+
default: return {};
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
// ---------------------------------------------------------------------------
|
|
613
|
+
// Which shorthand prints a layer
|
|
614
|
+
/** The shorthands that can print a layer, best first: the head a reader sees, then others that make the same kind. */
|
|
615
|
+
function headsOf(node) {
|
|
616
|
+
switch (node.type) {
|
|
617
|
+
case "shape": {
|
|
618
|
+
const shape = node.shape;
|
|
619
|
+
return [shape === "rectangle" ? "rect" : String(shape)];
|
|
620
|
+
}
|
|
621
|
+
case "frame": {
|
|
622
|
+
const kind = isRecord(node.layout) ? node.layout.kind : undefined;
|
|
623
|
+
// A frame with free layout and no style is what hflex makes with its layout written: frame always fills it.
|
|
624
|
+
return kind === "horizontal" ? ["hflex", "vflex", "frame"] : kind === "vertical" ? ["vflex", "hflex", "frame"] : ["frame", "hflex"];
|
|
625
|
+
}
|
|
626
|
+
default: return [String(node.type)];
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
/** The shorthand a matcher names a layer by: the first of `headsOf`. */
|
|
630
|
+
export function layerSyntaxHead(node) {
|
|
631
|
+
return headsOf(node)[0];
|
|
632
|
+
}
|
|
633
|
+
function shorthandNamed(name) {
|
|
634
|
+
const shorthand = toolShorthand(name);
|
|
635
|
+
if (shorthand === undefined)
|
|
636
|
+
throw new LayerSyntaxError(`There is no shorthand ${name}.`);
|
|
637
|
+
return shorthand;
|
|
638
|
+
}
|
|
639
|
+
const builtInHead = (head) => {
|
|
640
|
+
const shorthand = shorthandNamed(head);
|
|
641
|
+
return { head, shorthand, readers: readersOf(shorthand), modelFields: modelFieldsOf(shorthand) };
|
|
642
|
+
};
|
|
643
|
+
/** The component of an instance, when the context knows it. */
|
|
644
|
+
const componentOfInstance = (node, context) => node.type === "instance" && typeof node.componentId === "string" ? context.names.byId(node.componentId) : undefined;
|
|
645
|
+
/** The head a matcher and a refusal name a layer by: an instance by its component's call name, when it has one. */
|
|
646
|
+
function headOf(node, context) {
|
|
647
|
+
const component = componentOfInstance(node, context);
|
|
648
|
+
return (component === undefined ? undefined : context.names.callNameOf(component)) ?? headsOf(node)[0];
|
|
649
|
+
}
|
|
650
|
+
/** The calls that can print a layer, best first: an instance by its component's call name, then by its model fields. */
|
|
651
|
+
function printHeadsOf(node, context) {
|
|
652
|
+
const component = componentOfInstance(node, context);
|
|
653
|
+
const callName = component === undefined ? undefined : context.names.callNameOf(component);
|
|
654
|
+
if (component === undefined || callName === undefined)
|
|
655
|
+
return headsOf(node).map(builtInHead);
|
|
656
|
+
return [componentHead(component, callName, context), builtInHead("instance")];
|
|
657
|
+
}
|
|
658
|
+
/** A prop's stored value as the syntax writes it, or undefined when no value of the prop's kind writes it. */
|
|
659
|
+
function printedPropertyValue(property, value, names) {
|
|
660
|
+
switch (property.kind) {
|
|
661
|
+
case "boolean": return typeof value === "boolean" ? value : undefined;
|
|
662
|
+
case "number": return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
663
|
+
case "text":
|
|
664
|
+
case "color": return typeof value === "string" ? value : undefined;
|
|
665
|
+
case "enum": return property.options.find((option) => option.id === value)?.name;
|
|
666
|
+
case "instance": {
|
|
667
|
+
const component = typeof value === "string" ? names.byId(value) : undefined;
|
|
668
|
+
return component === undefined ? undefined : names.callNameOf(component);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
/** Removes a prop's value from an instance, and `propertyValues` when it is left empty, as the model leaves it out. */
|
|
673
|
+
function removePropertyValue(node, propertyId) {
|
|
674
|
+
if (!isRecord(node.propertyValues) || !Object.hasOwn(node.propertyValues, propertyId))
|
|
675
|
+
return;
|
|
676
|
+
const { [propertyId]: _removed, ...rest } = node.propertyValues;
|
|
677
|
+
if (Object.keys(rest).length === 0)
|
|
678
|
+
delete node.propertyValues;
|
|
679
|
+
else
|
|
680
|
+
node.propertyValues = rest;
|
|
681
|
+
}
|
|
682
|
+
/** One override as the syntax writes it: the short names of `over:{...}` first, then the fields they do not write, by their model names. */
|
|
683
|
+
function printedLayerOverride(override) {
|
|
684
|
+
const printed = {};
|
|
685
|
+
const rest = { ...override };
|
|
686
|
+
if (typeof rest.characters === "string") {
|
|
687
|
+
printed.text = rest.characters;
|
|
688
|
+
delete rest.characters;
|
|
689
|
+
}
|
|
690
|
+
if (isRecord(rest.textStyle)) {
|
|
691
|
+
const style = { ...rest.textStyle };
|
|
692
|
+
for (const [short, field] of Object.entries(OVERRIDE_TEXT_STYLE_FIELDS)) {
|
|
693
|
+
if (style[field] === undefined || style[field] === null)
|
|
694
|
+
continue;
|
|
695
|
+
printed[short] = style[field];
|
|
696
|
+
delete style[field];
|
|
697
|
+
}
|
|
698
|
+
if (Object.keys(style).length === 0)
|
|
699
|
+
delete rest.textStyle;
|
|
700
|
+
else
|
|
701
|
+
rest.textStyle = style;
|
|
702
|
+
}
|
|
703
|
+
if (Array.isArray(rest.fills)) {
|
|
704
|
+
printed.fill = rest.fills.length === 1 ? paintValue(rest.fills[0]) : rest.fills.map((paint) => paintValue(paint));
|
|
705
|
+
delete rest.fills;
|
|
706
|
+
}
|
|
707
|
+
const stroke = Array.isArray(rest.strokes) && rest.strokes.length === 1 ? strokeValue(rest.strokes[0]) : undefined;
|
|
708
|
+
if (stroke !== undefined) {
|
|
709
|
+
printed.stroke = stroke;
|
|
710
|
+
delete rest.strokes;
|
|
711
|
+
}
|
|
712
|
+
for (const key of ["visible", "opacity"])
|
|
713
|
+
if (rest[key] !== undefined) {
|
|
714
|
+
printed[key] = rest[key];
|
|
715
|
+
delete rest[key];
|
|
716
|
+
}
|
|
717
|
+
for (const [key, value] of Object.entries(rest))
|
|
718
|
+
if (value !== undefined)
|
|
719
|
+
printed[key] = value;
|
|
720
|
+
return printed;
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Where the layer a stored override key names comes in the component's layers, depth-first as the layers panel shows
|
|
724
|
+
* them: for each part of the key (a path of ids through nested instances, joined by `;`), its index among the layers of
|
|
725
|
+
* the component it is in. A part whose layer is not among the layers read has no index, and that key comes after the
|
|
726
|
+
* keys whose layers are known there.
|
|
727
|
+
*/
|
|
728
|
+
function overrideKeyOrder(key, component, context) {
|
|
729
|
+
const order = [];
|
|
730
|
+
let current = component;
|
|
731
|
+
for (const part of key.split(";")) {
|
|
732
|
+
const layers = current === undefined ? [] : componentLayers(context.document, current);
|
|
733
|
+
const index = layers.findIndex((layer) => layer.id === part);
|
|
734
|
+
if (index < 0) {
|
|
735
|
+
order.push(Number.POSITIVE_INFINITY);
|
|
736
|
+
break;
|
|
737
|
+
}
|
|
738
|
+
order.push(index);
|
|
739
|
+
const layer = layers[index];
|
|
740
|
+
current = layer.type === "instance" ? context.names.byId(layer.componentId) : undefined;
|
|
741
|
+
}
|
|
742
|
+
return order;
|
|
743
|
+
}
|
|
744
|
+
/** Compares two key orders part by part; a shorter order that the longer one starts with comes first. */
|
|
745
|
+
function compareKeyOrders(a, b) {
|
|
746
|
+
for (let index = 0; index < Math.min(a.length, b.length); index += 1) {
|
|
747
|
+
if (a[index] !== b[index])
|
|
748
|
+
return a[index] < b[index] ? -1 : 1;
|
|
749
|
+
}
|
|
750
|
+
return a.length - b.length;
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* An instance's overrides as `over:{...}` writes them, in the order of the component's layers (depth-first, as they
|
|
754
|
+
* appear), not the order they were stored in: each under the name of its layer, or the names on the way to a layer of a
|
|
755
|
+
* nested instance joined by `.` (`Button.Label`), when that names no other layer, else as `'#<path>'`, the stored key.
|
|
756
|
+
*/
|
|
757
|
+
function printedOverrides(node, component, context) {
|
|
758
|
+
if (!isRecord(node.overrides) || Object.keys(node.overrides).length === 0)
|
|
759
|
+
return undefined;
|
|
760
|
+
const paths = overridePaths(context.document, component);
|
|
761
|
+
const byKey = new Map(paths.map((path) => [path.key, path.name]));
|
|
762
|
+
const named = new Map();
|
|
763
|
+
for (const path of paths)
|
|
764
|
+
named.set(path.name, (named.get(path.name) ?? 0) + 1);
|
|
765
|
+
const printed = {};
|
|
766
|
+
const order = [];
|
|
767
|
+
const entries = Object.entries(node.overrides).map(([key, override]) => ({ key, override, order: overrideKeyOrder(key, component, context) }))
|
|
768
|
+
.sort((a, b) => compareKeyOrders(a.order, b.order)).map(({ key, override }) => [key, override]);
|
|
769
|
+
for (const [key, override] of entries) {
|
|
770
|
+
if (!isRecord(override))
|
|
771
|
+
return undefined;
|
|
772
|
+
const name = byKey.get(key);
|
|
773
|
+
const printedKey = name !== undefined && !name.startsWith("#") && named.get(name) === 1 ? name : `#${key}`;
|
|
774
|
+
Object.defineProperty(printed, printedKey, { value: printedLayerOverride(override), enumerable: true, writable: true, configurable: true });
|
|
775
|
+
order.push(printedKey);
|
|
776
|
+
}
|
|
777
|
+
PRINT_KEY_ORDER.set(printed, order);
|
|
778
|
+
DOTTED_KEYS.add(printed);
|
|
779
|
+
return printed;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* The call of an instance by its component's call name: its props by name (those named like another argument, or not
|
|
783
|
+
* named by a word, in `props:{...}`), then `over:{...}` for its overrides, besides the arguments and model fields of every instance but
|
|
784
|
+
* `componentId`, `propertyValues` and `overrides`, which the head, the props and `over` write.
|
|
785
|
+
*/
|
|
786
|
+
function componentHead(component, callName, context) {
|
|
787
|
+
const instance = shorthandNamed("instance");
|
|
788
|
+
const properties = (component.properties ?? []).filter(isValuedComponentProperty);
|
|
789
|
+
const readers = {};
|
|
790
|
+
const stored = (node, property) => isRecord(node.propertyValues) ? node.propertyValues[property.id] : undefined;
|
|
791
|
+
// A call reads only a word before ":" as an argument's name, so a prop goes in props:{...} unless its name is one.
|
|
792
|
+
const inCall = (property) => !propertyInProps(property) && KEY.test(property.name);
|
|
793
|
+
for (const property of properties.filter(inCall)) {
|
|
794
|
+
readers[property.name] = {
|
|
795
|
+
path: ["propertyValues", property.id],
|
|
796
|
+
read: (node) => {
|
|
797
|
+
const value = stored(node, property);
|
|
798
|
+
return value === undefined ? undefined : printedPropertyValue(property, value, context.names);
|
|
799
|
+
},
|
|
800
|
+
remove: (node) => removePropertyValue(node, property.id),
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
const inProps = properties.filter((property) => !inCall(property));
|
|
804
|
+
if (inProps.length > 0) {
|
|
805
|
+
readers[INSTANCE_PROPS_ARGUMENT] = {
|
|
806
|
+
path: ["propertyValues"],
|
|
807
|
+
read: (node) => {
|
|
808
|
+
const printed = {};
|
|
809
|
+
for (const property of inProps) {
|
|
810
|
+
const value = stored(node, property);
|
|
811
|
+
const shown = value === undefined ? undefined : printedPropertyValue(property, value, context.names);
|
|
812
|
+
if (shown !== undefined)
|
|
813
|
+
printed[property.name] = shown;
|
|
814
|
+
}
|
|
815
|
+
return Object.keys(printed).length === 0 ? undefined : printed;
|
|
816
|
+
},
|
|
817
|
+
remove: (node) => inProps.forEach((property) => removePropertyValue(node, property.id)),
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
readers[INSTANCE_OVER_ARGUMENT] = { path: ["overrides"], read: (node) => printedOverrides(node, component, context), remove: (node) => { delete node.overrides; } };
|
|
821
|
+
const shorthand = { ...instance, name: callName, short: Object.fromEntries(Object.keys(readers).map((name) => [name, () => undefined])) };
|
|
822
|
+
return { head: callName, shorthand, readers,
|
|
823
|
+
modelFields: modelFieldsOf(instance).filter((field) => field !== "componentId" && field !== "overrides" && field !== "propertyValues") };
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* A prop as a line of `printLayerComponents` shows it: an enum as the list of its option names, the default first; a
|
|
827
|
+
* text always in single quotes, so that it reads apart from a call name; an instance swap as the call name of its
|
|
828
|
+
* default component; any other kind as its default.
|
|
829
|
+
*/
|
|
830
|
+
function componentPropertyShown(property, names, where) {
|
|
831
|
+
switch (property.kind) {
|
|
832
|
+
case "enum": {
|
|
833
|
+
const fallback = property.options.find((option) => option.id === property.defaultValue);
|
|
834
|
+
if (fallback === undefined)
|
|
835
|
+
throw new LayerSyntaxError(`${where}: its default ${property.defaultValue} is not one of its options.`);
|
|
836
|
+
return printLayerValue([fallback.name, ...property.options.filter((option) => option !== fallback).map((option) => option.name)], where);
|
|
837
|
+
}
|
|
838
|
+
case "text":
|
|
839
|
+
if (property.defaultValue.includes("\\"))
|
|
840
|
+
throw new LayerSyntaxError(`${where} holds a backslash, which this syntax cannot write; read it as JSON instead.`);
|
|
841
|
+
return `'${property.defaultValue.replaceAll("'", "''")}'`;
|
|
842
|
+
case "instance": {
|
|
843
|
+
const component = names.byId(property.defaultValue);
|
|
844
|
+
const callName = component === undefined ? undefined : names.callNameOf(component);
|
|
845
|
+
if (callName === undefined)
|
|
846
|
+
throw new LayerSyntaxError(`${where}: its default, the component ${property.defaultValue}, has no call name.`);
|
|
847
|
+
return callName;
|
|
848
|
+
}
|
|
849
|
+
default:
|
|
850
|
+
return printLayerValue(property.defaultValue, where);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* The components of a document as the layer syntax calls them, one line each in the form of a call: its call name, then
|
|
855
|
+
* its props by name with their defaults (an enum as its options, the default first; a prop named like another argument
|
|
856
|
+
* of an instance, or whose name is not a word, in `props:{...}`), as `forms.button(type:(normal, danger), text:'Button')`. A component that no call
|
|
857
|
+
* name names alone (its name has no letter or digit, or another component has the same call name) gets a line of its
|
|
858
|
+
* own saying so, with its id for `instance(componentId:...)`. Empty without components.
|
|
859
|
+
*/
|
|
860
|
+
export function printLayerComponents(definitions) {
|
|
861
|
+
const { names } = syntaxContext({ definitions, node: () => undefined });
|
|
862
|
+
return definitions.map((component) => {
|
|
863
|
+
const callName = names.callNameOf(component);
|
|
864
|
+
if (callName === undefined) {
|
|
865
|
+
return `${printLayerValue(component.name, "a component name")} (id ${component.id}) has no call name of its own: `
|
|
866
|
+
+ `write instance(componentId:${printLayerValue(component.id, "a component id")}, propertyValues:{...}).`;
|
|
867
|
+
}
|
|
868
|
+
const properties = (component.properties ?? []).filter(isValuedComponentProperty);
|
|
869
|
+
const shown = (property) => componentPropertyShown(property, names, `the prop ${property.name} of ${callName}`);
|
|
870
|
+
const key = (name) => KEY.test(name) && !RESERVED_WORDS.has(name) ? name : printLayerValue(name, `a prop name of ${callName}`);
|
|
871
|
+
// A call reads only a word before ":" as an argument's name, so a prop goes in props:{...} unless its name is one;
|
|
872
|
+
// a prop named valid goes there too, as valid: is the component's validity expression.
|
|
873
|
+
const inCall = (property) => !propertyInProps(property) && KEY.test(property.name) && property.name !== VALIDITY_KEY;
|
|
874
|
+
try {
|
|
875
|
+
const args = properties.filter(inCall).map((property) => `${property.name}:${shown(property)}`);
|
|
876
|
+
const inProps = properties.filter((property) => !inCall(property));
|
|
877
|
+
if (inProps.length > 0)
|
|
878
|
+
args.push(`${INSTANCE_PROPS_ARGUMENT}:{${inProps.map((property) => `${key(property.name)}:${shown(property)}`).join(", ")}}`);
|
|
879
|
+
// A slot is filled with slots:{Name:( ... )}; the line shows each as Name:slot.
|
|
880
|
+
args.push(...slotPropertiesOf(component).map((property) => `${key(property.name)}:slot`));
|
|
881
|
+
if (component.validity !== undefined) {
|
|
882
|
+
if (component.validity.includes("\\")) {
|
|
883
|
+
throw new LayerSyntaxError(`the validity expression of ${callName} holds a backslash, which this syntax cannot write; read it as JSON instead.`);
|
|
884
|
+
}
|
|
885
|
+
args.push(`${VALIDITY_KEY}:'${component.validity.replaceAll("'", "''")}'`);
|
|
886
|
+
}
|
|
887
|
+
return `${callName}(${args.join(", ")})`;
|
|
888
|
+
}
|
|
889
|
+
catch (error) {
|
|
890
|
+
// One prop the syntax cannot show leaves the other components listed; the line says what is wrong.
|
|
891
|
+
if (error instanceof LayerSyntaxError)
|
|
892
|
+
return `${callName}: ${error.message}`;
|
|
893
|
+
throw error;
|
|
894
|
+
}
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
const isAutoLayoutFrame = (node) => node.type === "frame" && isRecord(node.layout) && node.layout.kind !== "absolute";
|
|
898
|
+
/** How a layer's width or height is sized: a number of its own, `fill` (its auto layout parent's space) or `hug` (its content). */
|
|
899
|
+
function sizingOf(node, axis, context) {
|
|
900
|
+
if (readIn(node, ["resizing", axis]) === "fill")
|
|
901
|
+
return "fill";
|
|
902
|
+
if (node.type === "instance" && instanceHugs(node, axis, context))
|
|
903
|
+
return "hug";
|
|
904
|
+
if (node.type === "frame" && isAutoLayoutFrame(node) && readIn(node, ["layout", axis === "width" ? "widthSizing" : "heightSizing"]) === "hug")
|
|
905
|
+
return "hug";
|
|
906
|
+
if (node.type === "text" || node.type === "code") {
|
|
907
|
+
if (node.autoResize === "width-and-height")
|
|
908
|
+
return "hug";
|
|
909
|
+
if (node.autoResize === "height" && axis === "height")
|
|
910
|
+
return "hug";
|
|
911
|
+
}
|
|
912
|
+
return "fixed";
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* The layer with the numbers layout decides set to 0: x and y of a layer its parent's auto layout places, and a
|
|
916
|
+
* width or height that fills or hugs. Building places and sizes those again when layout settles the change, so a
|
|
917
|
+
* printed layer leaves them out and the round trip compares the rest.
|
|
918
|
+
*/
|
|
919
|
+
function withoutLayoutNumbers(given, parent, context, mask = given) {
|
|
920
|
+
const node = withoutPlacedConnectorEnds(given);
|
|
921
|
+
if (!isRecord(node.frame))
|
|
922
|
+
return node;
|
|
923
|
+
const frame = { ...node.frame };
|
|
924
|
+
if (parent === true && mask.layoutPositioning !== "absolute") {
|
|
925
|
+
frame.x = 0;
|
|
926
|
+
frame.y = 0;
|
|
927
|
+
}
|
|
928
|
+
if (sizingOf(mask, "width", context) !== "fixed" || mask.type === "group")
|
|
929
|
+
frame.width = 0;
|
|
930
|
+
if (sizingOf(mask, "height", context) !== "fixed" || mask.type === "group")
|
|
931
|
+
frame.height = 0;
|
|
932
|
+
return { ...node, frame };
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Whether an instance hugs on `axis`: its component's root has auto layout and hugs there (or its override under the
|
|
936
|
+
* root's path says so), so that layout sets the instance's size, as it does a flex's.
|
|
937
|
+
*/
|
|
938
|
+
function instanceHugs(node, axis, context) {
|
|
939
|
+
const component = typeof node.componentId === "string" ? context.names.byId(node.componentId) : undefined;
|
|
940
|
+
const root = component === undefined ? undefined : context.document.nodes[component.rootId];
|
|
941
|
+
if (root === undefined || !isAutoLayoutFrame(root))
|
|
942
|
+
return false;
|
|
943
|
+
const field = axis === "width" ? "widthSizing" : "heightSizing";
|
|
944
|
+
return (readIn(node, ["overrides", String(root.id), "sizing", axis]) ?? readIn(root, ["layout", field])) === "hug";
|
|
945
|
+
}
|
|
946
|
+
// ---------------------------------------------------------------------------
|
|
947
|
+
// The printer
|
|
948
|
+
/** The arguments a call prints for a layer, in order, before its model fields. */
|
|
949
|
+
function shortArgumentsOf(node, { shorthand, readers }, parent, context) {
|
|
950
|
+
const args = new Map();
|
|
951
|
+
const takes = new Set(shortNamesOf(shorthand));
|
|
952
|
+
args.set("id", node.id);
|
|
953
|
+
args.set("name", node.name);
|
|
954
|
+
if (shorthand.content !== undefined) {
|
|
955
|
+
const content = readers[shorthand.content]?.read(node);
|
|
956
|
+
if (content !== undefined)
|
|
957
|
+
args.set(shorthand.content, content);
|
|
958
|
+
}
|
|
959
|
+
const frame = isRecord(node.frame) ? node.frame : undefined;
|
|
960
|
+
const placedByLayout = parent === true && node.layoutPositioning !== "absolute";
|
|
961
|
+
if (frame !== undefined && !placedByLayout) {
|
|
962
|
+
for (const axis of ["x", "y"])
|
|
963
|
+
if (takes.has(axis) && typeof frame[axis] === "number" && frame[axis] !== 0)
|
|
964
|
+
args.set(axis, frame[axis]);
|
|
965
|
+
}
|
|
966
|
+
// A path printed by d whose transform only moves it: x and y are the top-left corner of its bounds, as build reads them.
|
|
967
|
+
const transform = Array.isArray(node.transform) ? node.transform : undefined;
|
|
968
|
+
if (args.has("d") && !placedByLayout && transform !== undefined && transform[0] === 1 && transform[1] === 0 && transform[2] === 0
|
|
969
|
+
&& transform[3] === 1 && (transform[4] !== 0 || transform[5] !== 0)) {
|
|
970
|
+
const bounds = getNodeBounds(node);
|
|
971
|
+
args.set("x", bounds.x);
|
|
972
|
+
args.set("y", bounds.y);
|
|
973
|
+
}
|
|
974
|
+
if (frame !== undefined) {
|
|
975
|
+
for (const [short, axis] of [["w", "width"], ["h", "height"]]) {
|
|
976
|
+
if (!takes.has(short))
|
|
977
|
+
continue;
|
|
978
|
+
const sizing = sizingOf(node, axis, context);
|
|
979
|
+
if (sizing === "fill")
|
|
980
|
+
args.set(short, "fill");
|
|
981
|
+
else if (sizing === "hug") {
|
|
982
|
+
// A text and a flex hug unless told otherwise; a code block hugs when asked.
|
|
983
|
+
if (shorthand.name === "code" && (axis === "width" || node.autoResize === "height"))
|
|
984
|
+
args.set(short, "hug");
|
|
985
|
+
}
|
|
986
|
+
else if (typeof frame[axis] === "number")
|
|
987
|
+
args.set(short, frame[axis]);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
for (const name of Object.keys(shorthand.short)) {
|
|
991
|
+
const value = readers[name]?.read(node);
|
|
992
|
+
if (value !== undefined)
|
|
993
|
+
args.set(name, value);
|
|
994
|
+
}
|
|
995
|
+
if (typeof node.opacity === "number" && node.opacity !== 1)
|
|
996
|
+
args.set("opacity", node.opacity);
|
|
997
|
+
// An instance's overrides print last, after everything about the instance itself.
|
|
998
|
+
const over = args.get(INSTANCE_OVER_ARGUMENT);
|
|
999
|
+
if (over !== undefined && shorthand.kind.type === "instance") {
|
|
1000
|
+
args.delete(INSTANCE_OVER_ARGUMENT);
|
|
1001
|
+
args.set(INSTANCE_OVER_ARGUMENT, over);
|
|
1002
|
+
}
|
|
1003
|
+
return args;
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Whether the layer holds the value of the variable `id` where `property` writes it, so that binding it again by
|
|
1007
|
+
* name writes nothing else: the variable is in the document, fits the property and the layer, and writing its value
|
|
1008
|
+
* in its active mode (as the editor does) leaves the layer as it is.
|
|
1009
|
+
*/
|
|
1010
|
+
function holdsBoundValue(node, property, id, context) {
|
|
1011
|
+
const { theme } = context.document;
|
|
1012
|
+
const located = typeof id === "string" ? findVariable(theme, id) : undefined;
|
|
1013
|
+
if (located === undefined || !variableSupportsProperty(located.variable, property))
|
|
1014
|
+
return undefined;
|
|
1015
|
+
const value = locatedVariableValue(located);
|
|
1016
|
+
const layer = node;
|
|
1017
|
+
if (value === undefined || !nodeSupportsVariableProperty(layer, property))
|
|
1018
|
+
return false;
|
|
1019
|
+
return deepEqual(withVariableValue(theme, layer, property, value), node);
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* The bindings of `node` printed by the variables' names: an argument that writes a bound property, with the
|
|
1023
|
+
* variable's value, prints as `var('…')`, and every other binding goes into `variableBindings:{<property>:var('…')}`;
|
|
1024
|
+
* a binding to a variable the document lacks, that no name gives, or whose value the layer does not hold, prints as
|
|
1025
|
+
* the stored id, which builds the same binding without writing a value.
|
|
1026
|
+
*/
|
|
1027
|
+
function printBindings(node, args, fields, context) {
|
|
1028
|
+
if (!isRecord(node.variableBindings))
|
|
1029
|
+
return;
|
|
1030
|
+
const { theme } = context.document;
|
|
1031
|
+
const left = new Map(Object.entries(node.variableBindings));
|
|
1032
|
+
const named = (property, id) => typeof id === "string" && holdsBoundValue(node, property, id, context) === true ? variableNameFor(theme, id) : undefined;
|
|
1033
|
+
for (const [argument, value] of [...args]) {
|
|
1034
|
+
const properties = variableArgumentProperties(String(node.type), argument);
|
|
1035
|
+
const id = properties === undefined ? undefined : left.get(properties[0]);
|
|
1036
|
+
if (properties === undefined || properties.some((property) => left.get(property) !== id))
|
|
1037
|
+
continue;
|
|
1038
|
+
const name = named(properties[0], id);
|
|
1039
|
+
if (name === undefined || properties.some((property) => named(property, id) !== name))
|
|
1040
|
+
continue;
|
|
1041
|
+
let read;
|
|
1042
|
+
try {
|
|
1043
|
+
read = readVariableArgument(theme, String(node.type), argument, name);
|
|
1044
|
+
}
|
|
1045
|
+
catch (error) {
|
|
1046
|
+
if (error instanceof VariableReferenceError)
|
|
1047
|
+
continue;
|
|
1048
|
+
throw error;
|
|
1049
|
+
}
|
|
1050
|
+
if (printLayerValue(value) !== printLayerValue(read.value))
|
|
1051
|
+
continue;
|
|
1052
|
+
args.set(argument, variableReference(name));
|
|
1053
|
+
for (const property of properties)
|
|
1054
|
+
left.delete(property);
|
|
1055
|
+
}
|
|
1056
|
+
if (left.size === 0)
|
|
1057
|
+
return;
|
|
1058
|
+
const bindings = {};
|
|
1059
|
+
for (const [property, id] of left) {
|
|
1060
|
+
const name = named(property, id);
|
|
1061
|
+
Object.defineProperty(bindings, property, { value: name === undefined ? id : variableReference(name), enumerable: true, writable: true, configurable: true });
|
|
1062
|
+
}
|
|
1063
|
+
fields.set("variableBindings", bindings);
|
|
1064
|
+
}
|
|
1065
|
+
/** A value of `from:` or `to:`: a layer reference bare, as `#card.right`, so that it reads back as the same value. */
|
|
1066
|
+
const printArgument = (name, value, where) => {
|
|
1067
|
+
const reference = (name === "from" || name === "to") && typeof value === "string" ? readLayerReference(value) : undefined;
|
|
1068
|
+
return reference !== undefined && layerReferenceText(reference) === value ? value : printLayerValue(value, `${name} of ${where}`);
|
|
1069
|
+
};
|
|
1070
|
+
const callText = (printed, children, where) => {
|
|
1071
|
+
const args = [...printed.args].map(([name, value]) => `${name}:${printArgument(name, value, where)}`);
|
|
1072
|
+
const fields = [...printed.fields].map(([name, value]) => `${name}:${printLayerValue(value, `${name} of ${where}`)}`);
|
|
1073
|
+
return `${printed.head}(${[...args, ...fields, ...printed.removes.map((name) => `-${name}`)].join(", ")})${children ?? ""}`;
|
|
1074
|
+
};
|
|
1075
|
+
/** The node one call (without children) builds, in the stand-in document. */
|
|
1076
|
+
function buildOne(text, context) {
|
|
1077
|
+
const built = buildNodes(context.document, text, { syntax: "tool" });
|
|
1078
|
+
const subtree = built.subtrees[0];
|
|
1079
|
+
return subtree.nodes[subtree.rootId];
|
|
1080
|
+
}
|
|
1081
|
+
/** The fields that differ between a layer and what a call builds, the layout numbers and the children left out. */
|
|
1082
|
+
function differingFields(node, built, parent, context) {
|
|
1083
|
+
const left = withoutLayoutNumbers(node, parent, context);
|
|
1084
|
+
const right = withoutLayoutNumbers(built, parent, context, node);
|
|
1085
|
+
const differ = [], missing = [];
|
|
1086
|
+
for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) {
|
|
1087
|
+
if (key === "children" || key === "type" || key === "shape")
|
|
1088
|
+
continue;
|
|
1089
|
+
if (!Object.hasOwn(left, key))
|
|
1090
|
+
missing.push(key);
|
|
1091
|
+
else if (!deepEqual(left[key], right[key]))
|
|
1092
|
+
differ.push(key);
|
|
1093
|
+
}
|
|
1094
|
+
return { differ, missing };
|
|
1095
|
+
}
|
|
1096
|
+
/** The value of `field` to write by name, without what the short arguments in `args` write into it. */
|
|
1097
|
+
function fieldWithoutShorts(node, field, args, readers) {
|
|
1098
|
+
let value = clone(node[field]);
|
|
1099
|
+
for (const name of args.keys()) {
|
|
1100
|
+
const path = readers[name]?.path;
|
|
1101
|
+
if (path === undefined || path[0] !== field || path.length < 2 || !isRecord(value))
|
|
1102
|
+
continue;
|
|
1103
|
+
const holder = { [field]: value };
|
|
1104
|
+
deleteIn(holder, path);
|
|
1105
|
+
value = holder[field];
|
|
1106
|
+
}
|
|
1107
|
+
return value;
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Short arguments printed even where the call's constructor writes the same value, so that a default the agent never
|
|
1111
|
+
* wrote shows: the gap and padding of a flex frame.
|
|
1112
|
+
*/
|
|
1113
|
+
const ALWAYS_PRINTED = { hflex: ["gap", "pad"], vflex: ["gap", "pad"] };
|
|
1114
|
+
/** `args` without each short argument that the call's constructor already writes as the layer holds it, but for `kept`. */
|
|
1115
|
+
function withoutDefaults(args, differences, kept = []) {
|
|
1116
|
+
const order = [...args.keys()];
|
|
1117
|
+
for (const [name, value] of [...args]) {
|
|
1118
|
+
if (name === "id" || name === "name" || kept.includes(name))
|
|
1119
|
+
continue;
|
|
1120
|
+
args.delete(name);
|
|
1121
|
+
const { differ, missing, refused } = differences();
|
|
1122
|
+
if (differ.length > 0 || missing.length > 0 || refused !== undefined)
|
|
1123
|
+
args.set(name, value);
|
|
1124
|
+
}
|
|
1125
|
+
return new Map(order.filter((name) => args.has(name)).map((name) => [name, args.get(name)]));
|
|
1126
|
+
}
|
|
1127
|
+
/** How one layer prints, as a call without children; throws when no shorthand builds it again. */
|
|
1128
|
+
function printedCallOf(node, parent, context) {
|
|
1129
|
+
const where = `#${String(node.id)}`;
|
|
1130
|
+
const reasons = [];
|
|
1131
|
+
for (const candidate of printHeadsOf(node, context)) {
|
|
1132
|
+
const { head, shorthand, readers } = candidate;
|
|
1133
|
+
const takesChildren = shorthand.takesChildren;
|
|
1134
|
+
const args = shortArgumentsOf(node, candidate, parent, context);
|
|
1135
|
+
const fields = new Map();
|
|
1136
|
+
printBindings(node, args, fields, context);
|
|
1137
|
+
const modelFields = new Set(candidate.modelFields);
|
|
1138
|
+
const shortNames = new Set(shortNamesOf(shorthand));
|
|
1139
|
+
const removes = [];
|
|
1140
|
+
// A polygon's call needs its pointCount, whatever its value.
|
|
1141
|
+
if (shorthand.kind.type === "shape" && shorthand.kind.shape === "polygon" && typeof node.pointCount === "number")
|
|
1142
|
+
fields.set("pointCount", node.pointCount);
|
|
1143
|
+
const differences = () => {
|
|
1144
|
+
let built;
|
|
1145
|
+
try {
|
|
1146
|
+
built = buildOne(callText({ head, args, fields, removes }, undefined, where), context);
|
|
1147
|
+
}
|
|
1148
|
+
catch (error) {
|
|
1149
|
+
// A call the builder refuses (as w left out of a text with a fixed height) cannot print the layer.
|
|
1150
|
+
if (error instanceof NodeBuildError)
|
|
1151
|
+
return { differ: [], missing: [], refused: error.message };
|
|
1152
|
+
throw error;
|
|
1153
|
+
}
|
|
1154
|
+
return { ...differingFields(node, built, parent, context), refused: undefined };
|
|
1155
|
+
};
|
|
1156
|
+
// Rounds: model fields for what the short arguments do not write, and -name for what the constructor writes and the
|
|
1157
|
+
// layer lacks; then short arguments dropped where a model field is still written over.
|
|
1158
|
+
let failed;
|
|
1159
|
+
for (let round = 0; round < 4; round += 1) {
|
|
1160
|
+
const { differ, missing, refused: refusal } = differences();
|
|
1161
|
+
if (refusal !== undefined) {
|
|
1162
|
+
failed = `the builder refuses the call: ${refusal}`;
|
|
1163
|
+
break;
|
|
1164
|
+
}
|
|
1165
|
+
if (differ.length === 0 && missing.length === 0)
|
|
1166
|
+
return { head, takesChildren, args: withoutDefaults(args, () => differences(), ALWAYS_PRINTED[shorthand.name]), fields, removes };
|
|
1167
|
+
if (round === 3) {
|
|
1168
|
+
failed = `${head} cannot write ${[...differ, ...missing].join(", ")} of ${where} as it is`;
|
|
1169
|
+
break;
|
|
1170
|
+
}
|
|
1171
|
+
const cannot = [...differ.filter((field) => !modelFields.has(field)), ...missing.filter((field) => !modelFields.has(field) || shortNames.has(field))][0];
|
|
1172
|
+
if (cannot !== undefined) {
|
|
1173
|
+
failed = `${head} cannot write ${cannot} by its model name`;
|
|
1174
|
+
break;
|
|
1175
|
+
}
|
|
1176
|
+
removes.push(...missing.filter((field) => !removes.includes(field)));
|
|
1177
|
+
for (const field of differ) {
|
|
1178
|
+
// A model field with the name of a short argument (a connector's stroke) is written through that argument, as it is stored.
|
|
1179
|
+
if (shortNames.has(field)) {
|
|
1180
|
+
args.set(field, clone(node[field]));
|
|
1181
|
+
continue;
|
|
1182
|
+
}
|
|
1183
|
+
if (round >= 1) {
|
|
1184
|
+
// A short argument still writes over the field: write the field whole, without the arguments that write into it.
|
|
1185
|
+
for (const [name, reader] of Object.entries(readers))
|
|
1186
|
+
if (reader.path[0] === field)
|
|
1187
|
+
args.delete(name);
|
|
1188
|
+
if (field === "frame")
|
|
1189
|
+
for (const name of ["x", "y", "w", "h"])
|
|
1190
|
+
args.delete(name);
|
|
1191
|
+
fields.set(field, clone(node[field]));
|
|
1192
|
+
}
|
|
1193
|
+
else {
|
|
1194
|
+
fields.set(field, fieldWithoutShorts(node, field, args, readers));
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
reasons.push(failed ?? `${head} does not build ${where}`);
|
|
1199
|
+
}
|
|
1200
|
+
throw new LayerSyntaxError(`${where} cannot be printed in the layer syntax: ${reasons.join("; ")}.`);
|
|
1201
|
+
}
|
|
1202
|
+
/** `node` without the `fontAssetId` of each run `runs` lists; `node` itself when it lists none. */
|
|
1203
|
+
function withoutDefaultFontAssets(node, runs) {
|
|
1204
|
+
if (node?.type !== "text" || runs === undefined || runs.length === 0)
|
|
1205
|
+
return node;
|
|
1206
|
+
const listed = new Set(runs.map(({ paragraph, run }) => `${paragraph}:${run}`));
|
|
1207
|
+
return { ...node, paragraphs: node.paragraphs.map((paragraph, paragraphIndex) => ({ ...paragraph, runs: paragraph.runs.map((run, runIndex) => {
|
|
1208
|
+
if (!listed.has(`${paragraphIndex}:${runIndex}`) || run.overrides?.fontAssetId === undefined)
|
|
1209
|
+
return run;
|
|
1210
|
+
const { fontAssetId: _bound, ...overrides } = run.overrides;
|
|
1211
|
+
return { ...run, overrides };
|
|
1212
|
+
}) })) };
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* The layer `rootId` and the layers inside it as layer source in the tool spelling, on one line: one call
|
|
1216
|
+
* per layer, `id` and `name` first, then the short arguments, then each other field that differs from what the call
|
|
1217
|
+
* makes, by its model name, so that every layer prints and building the text makes the same layers
|
|
1218
|
+
* (`build(print(x))` equals x, but for the x and y that auto layout places and the sizes that fill or hug, which
|
|
1219
|
+
* layout sets again, and the `fontAssetId` of each run `defaultFontAssetRuns` lists, which the editor binds again).
|
|
1220
|
+
* `parentAutoLayout` says whether the parent of `rootId` places it with auto layout, when known. `insideComponent` is the
|
|
1221
|
+
* component whose layers `rootId` is among, when known, so that a slot frame prints its slot's name; without it a slot
|
|
1222
|
+
* frame outside a printed component root prints its slot's name only when one component alone has a slot with its id.
|
|
1223
|
+
* With `components`, an instance prints by its component's call name, its props by name and its overrides in
|
|
1224
|
+
* `over:{...}` (`button(id:b1, name:'Buy', text:'Buy', over:{Label:{color:#ffffff}})`); without, or where that does not
|
|
1225
|
+
* build it again, by its model fields (`instance(componentId:..., ...)`).
|
|
1226
|
+
* Throws a LayerSyntaxError for a layer not read, a string with a backslash, or a layer the check finds is not built again.
|
|
1227
|
+
*/
|
|
1228
|
+
export function printLayerSource(given, rootId, options = {}) {
|
|
1229
|
+
const context = syntaxContext(options.components, options.variables);
|
|
1230
|
+
// The font assets the editor binds again are left out of the print, and so of the check that it builds the layers again.
|
|
1231
|
+
const marks = given.defaultFontAssetRuns;
|
|
1232
|
+
const source = marks === undefined ? given : { node: (id) => withoutDefaultFontAssets(given.node(id), marks(id)) };
|
|
1233
|
+
const definitions = options.components?.definitions ?? [];
|
|
1234
|
+
const byRoot = new Map(definitions.map((definition) => [definition.rootId, definition]));
|
|
1235
|
+
// The component a slot frame printed outside its component's root belongs to, for the check to build it in.
|
|
1236
|
+
let checkScope = options.insideComponent;
|
|
1237
|
+
const visit = (id, parent, depth, slotDepth, scope) => {
|
|
1238
|
+
if (depth > 1000)
|
|
1239
|
+
throw new LayerSyntaxError("The layers are nested more than 1000 deep.");
|
|
1240
|
+
const node = source.node(id);
|
|
1241
|
+
if (node === undefined)
|
|
1242
|
+
throw new LayerSyntaxError(`#${id} was not read, so it cannot be printed; read it on its own.`);
|
|
1243
|
+
const inside = byRoot.get(id) ?? scope;
|
|
1244
|
+
let shown = node;
|
|
1245
|
+
if (node.type === "frame" && typeof node.slot === "string") {
|
|
1246
|
+
// A slot frame prints the name of its slot, slot:Content, which builds back to the slot's id in its component.
|
|
1247
|
+
const owners = inside !== undefined ? [inside] : definitions.filter((definition) => slotPropertiesOf(definition).some((property) => property.id === node.slot));
|
|
1248
|
+
const property = owners.length === 1 ? slotPropertiesOf(owners[0]).find((candidate) => candidate.id === node.slot) : undefined;
|
|
1249
|
+
if (property !== undefined) {
|
|
1250
|
+
shown = { ...node, slot: property.name };
|
|
1251
|
+
if (inside === undefined)
|
|
1252
|
+
checkScope ??= owners[0];
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
const slots = node.type === "instance" && isRecord(node.slots) && Object.keys(node.slots).length > 0 ? node.slots : undefined;
|
|
1256
|
+
if (slots !== undefined) {
|
|
1257
|
+
const { slots: _slots, ...rest } = shown;
|
|
1258
|
+
shown = rest;
|
|
1259
|
+
}
|
|
1260
|
+
// The person's own fields are not shown to an agent (`AGENT_HIDDEN_NODE_FIELDS`).
|
|
1261
|
+
shown = withoutAgentHiddenFields(shown);
|
|
1262
|
+
let printed = printedCallOf(shown, parent, context);
|
|
1263
|
+
if (slots !== undefined) {
|
|
1264
|
+
const list = (hostId) => {
|
|
1265
|
+
if (typeof hostId !== "string")
|
|
1266
|
+
throw new LayerSyntaxError(`#${id} lists a slot host that is not an id, so it cannot be printed.`);
|
|
1267
|
+
const host = source.node(hostId);
|
|
1268
|
+
if (host === undefined)
|
|
1269
|
+
throw new LayerSyntaxError(`#${hostId}, a slot host of #${id}, was not read, so #${id} cannot be printed; read it on its own.`);
|
|
1270
|
+
const hostText = layerReferenceText({ id: hostId });
|
|
1271
|
+
const content = Array.isArray(host.children) ? host.children : [];
|
|
1272
|
+
if (content.length === 0)
|
|
1273
|
+
return printedText(`(${hostText})`);
|
|
1274
|
+
// At depth 0 a filled slot shows how many layers it holds and its host, which build in #<host id> builds into.
|
|
1275
|
+
if (slotDepth <= 0 || content.some((child) => source.node(child) === undefined)) {
|
|
1276
|
+
return printedText(`(${content.length} ${content.length === 1 ? "layer" : "layers"}, ${hostText})`);
|
|
1277
|
+
}
|
|
1278
|
+
return printedText(`(${[...content.map((child) => visit(child, isAutoLayoutFrame(host), depth + 1, slotDepth - 1, scope)), hostText].join(", ")})`);
|
|
1279
|
+
};
|
|
1280
|
+
printed = withSlotArguments(printed, node, slots, list, context);
|
|
1281
|
+
}
|
|
1282
|
+
const children = Array.isArray(node.children) && printed.takesChildren === true
|
|
1283
|
+
? `[${node.children.map((child) => visit(child, isAutoLayoutFrame(node), depth + 1, slotDepth, inside)).join(", ")}]` : undefined;
|
|
1284
|
+
return callText(printed, children, `#${id}`);
|
|
1285
|
+
};
|
|
1286
|
+
const text = visit(rootId, options.parentAutoLayout, 0, options.slotDepth ?? 0, options.insideComponent);
|
|
1287
|
+
checkRoundTrip(source, rootId, text, options.parentAutoLayout, context, checkScope);
|
|
1288
|
+
return text;
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* `printed` with the slots an instance fills: by its component's call name, its own as `slots:{Name:( ... )}` and those
|
|
1292
|
+
* of its nested instances in `over:{Path:{slots:{Name:( ... )}}}`; by its model fields, as
|
|
1293
|
+
* `slots:{'<path>':{'<slot id>':( ... )}}`. `list` prints the content of one host.
|
|
1294
|
+
*/
|
|
1295
|
+
function withSlotArguments(printed, node, slots, list, context) {
|
|
1296
|
+
const where = `#${String(node.id)}`;
|
|
1297
|
+
const component = componentOfInstance(node, context);
|
|
1298
|
+
const byName = component !== undefined && printed.head !== "instance";
|
|
1299
|
+
const own = {};
|
|
1300
|
+
const nested = {};
|
|
1301
|
+
for (const [pathKey, byProperty] of Object.entries(slots)) {
|
|
1302
|
+
if (!isRecord(byProperty))
|
|
1303
|
+
throw new LayerSyntaxError(`${where} cannot be printed in the layer syntax: its slots under ${JSON.stringify(pathKey)} are not an object.`);
|
|
1304
|
+
const owner = !byName ? undefined : pathKey === "" ? component : componentAtPath(context.document, component, pathKey.split(";"));
|
|
1305
|
+
const entries = {};
|
|
1306
|
+
for (const [propertyId, hostId] of Object.entries(byProperty)) {
|
|
1307
|
+
const key = owner === undefined ? propertyId : slotPropertiesOf(owner).find((property) => property.id === propertyId)?.name;
|
|
1308
|
+
if (key === undefined)
|
|
1309
|
+
throw new LayerSyntaxError(`${where} cannot be printed in the layer syntax: it fills ${propertyId}, which is not a slot of its component.`);
|
|
1310
|
+
Object.defineProperty(entries, key, { value: list(hostId), enumerable: true, writable: true, configurable: true });
|
|
1311
|
+
}
|
|
1312
|
+
if (!byName || pathKey === "") {
|
|
1313
|
+
if (byName)
|
|
1314
|
+
Object.assign(own, entries);
|
|
1315
|
+
else
|
|
1316
|
+
Object.defineProperty(own, pathKey, { value: entries, enumerable: true, writable: true, configurable: true });
|
|
1317
|
+
}
|
|
1318
|
+
else
|
|
1319
|
+
Object.defineProperty(nested, pathKey, { value: entries, enumerable: true, writable: true, configurable: true });
|
|
1320
|
+
}
|
|
1321
|
+
const args = new Map([...printed.args].filter(([name]) => name !== INSTANCE_OVER_ARGUMENT));
|
|
1322
|
+
if (Object.keys(own).length > 0)
|
|
1323
|
+
args.set(INSTANCE_SLOTS_ARGUMENT, own);
|
|
1324
|
+
const over = printed.args.get(INSTANCE_OVER_ARGUMENT);
|
|
1325
|
+
if (Object.keys(nested).length > 0) {
|
|
1326
|
+
// Each nested instance by the key over:{...} names it by: its names on the way, or '#<path>' where they name another layer too.
|
|
1327
|
+
const paths = overridePaths(context.document, component);
|
|
1328
|
+
const named = new Map();
|
|
1329
|
+
for (const path of paths)
|
|
1330
|
+
named.set(path.name, (named.get(path.name) ?? 0) + 1);
|
|
1331
|
+
const merged = isRecord(over) ? { ...over } : {};
|
|
1332
|
+
const order = [...(isRecord(over) ? PRINT_KEY_ORDER.get(over) ?? Object.keys(over) : [])];
|
|
1333
|
+
for (const [pathKey, entries] of Object.entries(nested)) {
|
|
1334
|
+
const name = paths.find((path) => path.key === pathKey)?.name;
|
|
1335
|
+
const key = name !== undefined && !name.startsWith("#") && named.get(name) === 1 ? name : `#${pathKey}`;
|
|
1336
|
+
const before = merged[key];
|
|
1337
|
+
Object.defineProperty(merged, key, { value: { ...(isRecord(before) ? before : {}), [INSTANCE_SLOTS_ARGUMENT]: entries },
|
|
1338
|
+
enumerable: true, writable: true, configurable: true });
|
|
1339
|
+
if (!order.includes(key))
|
|
1340
|
+
order.push(key);
|
|
1341
|
+
}
|
|
1342
|
+
PRINT_KEY_ORDER.set(merged, order);
|
|
1343
|
+
DOTTED_KEYS.add(merged);
|
|
1344
|
+
args.set(INSTANCE_OVER_ARGUMENT, merged);
|
|
1345
|
+
}
|
|
1346
|
+
else if (over !== undefined)
|
|
1347
|
+
args.set(INSTANCE_OVER_ARGUMENT, over);
|
|
1348
|
+
return { ...printed, args };
|
|
1349
|
+
}
|
|
1350
|
+
/** The box around the layers inside a layer, in its coordinates, or undefined when it holds none. */
|
|
1351
|
+
function contentBox(children) {
|
|
1352
|
+
if (children.length === 0)
|
|
1353
|
+
return undefined;
|
|
1354
|
+
const boxes = children.map((child) => getNodeBounds(child));
|
|
1355
|
+
const left = Math.min(...boxes.map((box) => box.x)), top = Math.min(...boxes.map((box) => box.y));
|
|
1356
|
+
const right = Math.max(...boxes.map((box) => box.x + box.width)), bottom = Math.max(...boxes.map((box) => box.y + box.height));
|
|
1357
|
+
return { x: left, y: top, width: right - left, height: bottom - top };
|
|
1358
|
+
}
|
|
1359
|
+
/** A frame with free layout: its layers keep their x and y, so `fit` can size it to them. */
|
|
1360
|
+
const placesFreely = (node) => node.type === "frame" && !isAutoLayoutFrame(node);
|
|
1361
|
+
const shownNumber = (value) => String(Math.round(value * 100) / 100);
|
|
1362
|
+
/**
|
|
1363
|
+
* A line for each frame with free layout, `rootId` or inside it, whose layers overflow it or leave space that is not
|
|
1364
|
+
* the same on every side: the box around its layers and the space on each side, so that an agent sees the real
|
|
1365
|
+
* bounds instead of guessing them. Frames for which `skip` is true (a page root) and frames whose layers were not all
|
|
1366
|
+
* read get no line.
|
|
1367
|
+
*/
|
|
1368
|
+
export function layerContentNotes(source, rootId, options = {}) {
|
|
1369
|
+
const notes = [];
|
|
1370
|
+
const visit = (id, depth) => {
|
|
1371
|
+
if (depth > 1000)
|
|
1372
|
+
throw new LayerSyntaxError("The layers are nested more than 1000 deep.");
|
|
1373
|
+
const node = source.node(id);
|
|
1374
|
+
if (node === undefined || !Array.isArray(node.children))
|
|
1375
|
+
return;
|
|
1376
|
+
const children = node.children.map((child) => source.node(child));
|
|
1377
|
+
if (placesFreely(node) && options.skip?.(id) !== true && isRecord(node.frame) && children.every((child) => child !== undefined)) {
|
|
1378
|
+
const box = contentBox(children);
|
|
1379
|
+
const { width, height } = node.frame;
|
|
1380
|
+
if (box !== undefined) {
|
|
1381
|
+
const space = { left: box.x, top: box.y, right: width - box.x - box.width, bottom: height - box.y - box.height };
|
|
1382
|
+
const shown = Object.values(space).map(shownNumber);
|
|
1383
|
+
if (shown.some((side) => side !== shown[0])) {
|
|
1384
|
+
const overflows = Object.entries(space).filter(([, value]) => Number(shownNumber(value)) < 0).map(([side]) => side);
|
|
1385
|
+
notes.push(`#${id} is ${shownNumber(width)}x${shownNumber(height)}; its layers take x:${shownNumber(box.x)} y:${shownNumber(box.y)} `
|
|
1386
|
+
+ `w:${shownNumber(box.width)} h:${shownNumber(box.height)}, leaving left ${shown[0]}, top ${shown[1]}, right ${shown[2]}, bottom ${shown[3]}`
|
|
1387
|
+
+ `${overflows.length === 0 ? "" : ` (they overflow on the ${overflows.join(", ")})`}. set #${id} { fit:<padding> } sizes it to them with even padding.`);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
for (const child of node.children)
|
|
1392
|
+
visit(child, depth + 1);
|
|
1393
|
+
};
|
|
1394
|
+
visit(rootId, 0);
|
|
1395
|
+
return notes;
|
|
1396
|
+
}
|
|
1397
|
+
/** Builds `text` again and compares every layer with the one read; throws naming the first layer and fields that differ. */
|
|
1398
|
+
function checkRoundTrip(source, rootId, text, parentAutoLayout, context, scope) {
|
|
1399
|
+
const built = buildNodes(context.document, text, { syntax: "tool", keepSlotSummaries: true, ...(scope === undefined ? {} : { component: scope.id }) }).subtrees[0];
|
|
1400
|
+
const compare = (id, parent) => {
|
|
1401
|
+
const node = source.node(id);
|
|
1402
|
+
const again = built.nodes[id];
|
|
1403
|
+
// The fields an agent is not shown are not printed (see printLayerSource), so they are not compared.
|
|
1404
|
+
const left = withoutLayoutNumbers(withoutAgentHiddenFields(node), parent, context);
|
|
1405
|
+
const right = again === undefined ? undefined : withoutLayoutNumbers(again, parent, context, node);
|
|
1406
|
+
if (right === undefined || !deepEqual(left, right)) {
|
|
1407
|
+
const fields = right === undefined ? ["the layer"] : [...new Set([...Object.keys(left), ...Object.keys(right)])].filter((key) => !deepEqual(left[key], right[key]));
|
|
1408
|
+
throw new LayerSyntaxError(`#${id} cannot be printed in the layer syntax: building it again gives another ${fields.join(", ")}.`);
|
|
1409
|
+
}
|
|
1410
|
+
for (const child of Array.isArray(node.children) ? node.children : [])
|
|
1411
|
+
compare(child, isAutoLayoutFrame(node));
|
|
1412
|
+
// A slot host printed with its layers: the build makes it from the component's slot frame, so only its layers are compared.
|
|
1413
|
+
for (const byProperty of node.type === "instance" && isRecord(node.slots) ? Object.values(node.slots) : []) {
|
|
1414
|
+
for (const hostId of isRecord(byProperty) ? Object.values(byProperty) : []) {
|
|
1415
|
+
const host = typeof hostId === "string" ? source.node(hostId) : undefined;
|
|
1416
|
+
const hostAgain = typeof hostId === "string" ? built.nodes[hostId] : undefined;
|
|
1417
|
+
if (host === undefined || hostAgain === undefined)
|
|
1418
|
+
continue;
|
|
1419
|
+
if (!deepEqual(host.children, hostAgain.children)) {
|
|
1420
|
+
throw new LayerSyntaxError(`#${id} cannot be printed in the layer syntax: building it again gives other layers in its slot host #${String(hostId)}.`);
|
|
1421
|
+
}
|
|
1422
|
+
for (const child of Array.isArray(host.children) ? host.children : [])
|
|
1423
|
+
compare(child, isAutoLayoutFrame(host));
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
};
|
|
1427
|
+
compare(rootId, parentAutoLayout);
|
|
1428
|
+
}
|
|
1429
|
+
// ---------------------------------------------------------------------------
|
|
1430
|
+
// Reading the place and the ids of the tools
|
|
1431
|
+
/** Reads a layer id at the reader: `#id`, or `#'id'` for an id with other characters. */
|
|
1432
|
+
function readId(reader, what) {
|
|
1433
|
+
const token = reader.peek();
|
|
1434
|
+
if (token.kind !== "colour")
|
|
1435
|
+
throw reader.expected(what);
|
|
1436
|
+
reader.next();
|
|
1437
|
+
if (token.text !== "#")
|
|
1438
|
+
return token.text.slice(1);
|
|
1439
|
+
const quoted = reader.peek();
|
|
1440
|
+
if (quoted.kind !== "string")
|
|
1441
|
+
throw reader.expected(`an id after #, as #card or #'1:2'`);
|
|
1442
|
+
reader.next();
|
|
1443
|
+
return quoted.value;
|
|
1444
|
+
}
|
|
1445
|
+
const isWord = (token, text) => token.kind === "word" && token.text === text;
|
|
1446
|
+
const skipSeparator = (reader) => {
|
|
1447
|
+
if (reader.isPunctuation(reader.peek(), ";") || reader.isPunctuation(reader.peek(), ","))
|
|
1448
|
+
reader.next();
|
|
1449
|
+
};
|
|
1450
|
+
/** A syntax refusal as a LayerSyntaxError, with the right form after it. */
|
|
1451
|
+
function refused(error, form) {
|
|
1452
|
+
if (error instanceof NodeBuildError)
|
|
1453
|
+
throw new LayerSyntaxError(`${error.message}${/[.:]$/.test(error.message) ? "" : "."}${form === "" ? "" : ` ${form}`}`);
|
|
1454
|
+
throw error;
|
|
1455
|
+
}
|
|
1456
|
+
/** The ids of a `read` text: one or more `#id`, separated by spaces, commas or `;`. */
|
|
1457
|
+
export function readLayerIds(text) {
|
|
1458
|
+
const form = "Write the layers to read as #<id>, for example #card, or several as #card #title; or components, to list the components.";
|
|
1459
|
+
try {
|
|
1460
|
+
const reader = layerSyntaxReader(text, "tool");
|
|
1461
|
+
const ids = [];
|
|
1462
|
+
while (reader.peek().kind !== "end") {
|
|
1463
|
+
ids.push(readId(reader, "a layer id such as #card"));
|
|
1464
|
+
skipSeparator(reader);
|
|
1465
|
+
}
|
|
1466
|
+
if (ids.length === 0)
|
|
1467
|
+
throw new LayerSyntaxError(`There is no layer to read. ${form}`);
|
|
1468
|
+
return ids;
|
|
1469
|
+
}
|
|
1470
|
+
catch (error) {
|
|
1471
|
+
return refused(error, form);
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* The ids of the components a `build` or `edit` text calls by name (any word before `(` that names a component) or names
|
|
1476
|
+
* by id (`componentId:'<id>'` of an `instance(...)`), so
|
|
1477
|
+
* that a host reads their layers before it reads the text with `readLayerBuild` or `planLayerEdit`. A text that cannot
|
|
1478
|
+
* be read gives the components found before the place it cannot be read: the read of the text refuses it.
|
|
1479
|
+
*/
|
|
1480
|
+
export function layerSyntaxComponentIds(text, definitions) {
|
|
1481
|
+
const { names } = syntaxContext({ definitions, node: () => undefined });
|
|
1482
|
+
const ids = new Set();
|
|
1483
|
+
let reader;
|
|
1484
|
+
try {
|
|
1485
|
+
reader = layerSyntaxReader(text, "tool");
|
|
1486
|
+
}
|
|
1487
|
+
catch {
|
|
1488
|
+
return [];
|
|
1489
|
+
}
|
|
1490
|
+
for (let at = 0; reader.peek(at).kind !== "end"; at += 1) {
|
|
1491
|
+
const token = reader.peek(at);
|
|
1492
|
+
// instance(componentId:'<id>', ...) names its component by id.
|
|
1493
|
+
const value = reader.peek(at + 2);
|
|
1494
|
+
if (isWord(token, "componentId") && reader.isPunctuation(reader.peek(at + 1), ":") && value.kind === "string"
|
|
1495
|
+
&& definitions.some((definition) => definition.id === value.value)) {
|
|
1496
|
+
ids.add(value.value);
|
|
1497
|
+
continue;
|
|
1498
|
+
}
|
|
1499
|
+
if (token.kind !== "word" || !reader.isPunctuation(reader.peek(at + 1), "("))
|
|
1500
|
+
continue;
|
|
1501
|
+
try {
|
|
1502
|
+
const resolved = names.resolve(token.text);
|
|
1503
|
+
if (resolved?.kind === "component")
|
|
1504
|
+
ids.add(resolved.component.id);
|
|
1505
|
+
}
|
|
1506
|
+
catch {
|
|
1507
|
+
// A name of several components names none; the read of the text refuses it.
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
return [...ids];
|
|
1511
|
+
}
|
|
1512
|
+
/** The refusal of connector ends attached to layers the document does not have, with the forms to write. */
|
|
1513
|
+
export function connectorTargetRefusal(missing) {
|
|
1514
|
+
return `There is no layer ${missing.map((id) => layerReferenceText({ id })).join(", ")} for a connector end to attach to. `
|
|
1515
|
+
+ "Write from: and to: with the id of a layer on the same page (read the layers to find ids), "
|
|
1516
|
+
+ "as to:#card.left, or a free end in the parent's coordinates, as to:(300, 40).";
|
|
1517
|
+
}
|
|
1518
|
+
const BUILD_FORM = "Write where the layers go first, then the layers: in #<parent id> at:<index>; <layers>, "
|
|
1519
|
+
+ "as in #card at:0; text(text:'Plans', size:24). Leave out at: to put them on top. "
|
|
1520
|
+
+ "In a slot of an instance, write in #<instance id> slot:<slot name>; <layers>.";
|
|
1521
|
+
/**
|
|
1522
|
+
* Reads a `build` text, `in #parent [at:index]; <layers>`, checks its layers as `buildNodes` would (without the
|
|
1523
|
+
* document, so a rule about the parent is the editor's to refuse), and gives them in the default spelling for a
|
|
1524
|
+
* `node.build`. Refusals name the line and column of the text as written.
|
|
1525
|
+
*/
|
|
1526
|
+
export function readLayerBuild(text, options = {}) {
|
|
1527
|
+
let layersStart = 0;
|
|
1528
|
+
let parentId, index, slot;
|
|
1529
|
+
try {
|
|
1530
|
+
const reader = layerSyntaxReader(text, "tool");
|
|
1531
|
+
if (!isWord(reader.peek(), "in"))
|
|
1532
|
+
throw new LayerSyntaxError(`A build says where its layers go. ${BUILD_FORM}`);
|
|
1533
|
+
reader.next();
|
|
1534
|
+
parentId = readId(reader, "the parent's id after in, as in #card");
|
|
1535
|
+
for (;;) {
|
|
1536
|
+
if (isWord(reader.peek(), "at") && index === undefined) {
|
|
1537
|
+
reader.next();
|
|
1538
|
+
reader.expect(":", "\":\" after at");
|
|
1539
|
+
const at = reader.peek();
|
|
1540
|
+
if (at.kind !== "number" || !Number.isInteger(at.value) || at.value < 0)
|
|
1541
|
+
throw reader.expected("an index of 0 or more after at:", at);
|
|
1542
|
+
reader.next();
|
|
1543
|
+
index = at.value;
|
|
1544
|
+
}
|
|
1545
|
+
else if (isWord(reader.peek(), "slot") && slot === undefined) {
|
|
1546
|
+
// in #<instance id> slot:Content; builds into the instance's slot Content.
|
|
1547
|
+
reader.next();
|
|
1548
|
+
reader.expect(":", "\":\" after slot");
|
|
1549
|
+
const name = reader.peek();
|
|
1550
|
+
if (name.kind !== "word" && name.kind !== "string")
|
|
1551
|
+
throw reader.expected("the slot's name after slot:, as slot:Content", name);
|
|
1552
|
+
reader.next();
|
|
1553
|
+
slot = name.kind === "word" ? name.text : String(name.value);
|
|
1554
|
+
}
|
|
1555
|
+
else
|
|
1556
|
+
break;
|
|
1557
|
+
}
|
|
1558
|
+
skipSeparator(reader);
|
|
1559
|
+
if (reader.peek().kind === "end")
|
|
1560
|
+
throw new LayerSyntaxError(`The build has no layers after its place. ${BUILD_FORM}`);
|
|
1561
|
+
layersStart = reader.peek().start;
|
|
1562
|
+
}
|
|
1563
|
+
catch (error) {
|
|
1564
|
+
refused(error, BUILD_FORM);
|
|
1565
|
+
}
|
|
1566
|
+
const { source, removals, attachedTo, attachments, layers, places } = readNewLayers(only(text, layersStart), syntaxContext(options.components, options.variables));
|
|
1567
|
+
return { parentId, ...(index === undefined ? {} : { index }), ...(slot === undefined ? {} : { slot }), source, removals, attachedTo, attachments, layers, places };
|
|
1568
|
+
}
|
|
1569
|
+
/**
|
|
1570
|
+
* `text` blanked out but for `start` to `end`, line breaks kept: a part of a text cut out this way keeps the lines and
|
|
1571
|
+
* columns of the text as written, for refusals.
|
|
1572
|
+
*/
|
|
1573
|
+
const only = (text, start, end = text.length) => text.slice(0, start).replace(/[^\n]/g, " ") + text.slice(start, end) + text.slice(end).replace(/[^\n]/g, " ");
|
|
1574
|
+
/** The layers the ends of a connector attach to. */
|
|
1575
|
+
const connectorTargets = (node) => node.type !== "connector" ? []
|
|
1576
|
+
: [node.start, node.end].flatMap((end) => isRecord(end) && typeof end.nodeId === "string" ? [end.nodeId] : []);
|
|
1577
|
+
/**
|
|
1578
|
+
* Reads new layers (the rest of `text` blanked out) and checks them as `buildNodes` would, without the document but
|
|
1579
|
+
* for `parent` when it is given, so that a layer an auto layout parent places is refused its x and y as a build refuses
|
|
1580
|
+
* them. Refusals name the line and column of the text as written.
|
|
1581
|
+
*/
|
|
1582
|
+
/** The ids `calls` give their layers, at any depth, in the layers inside them and in slot lists too. */
|
|
1583
|
+
function idsOfCalls(calls) {
|
|
1584
|
+
return calls.flatMap((call) => {
|
|
1585
|
+
const id = call.arguments.find((argument) => argument.name === "id")?.value;
|
|
1586
|
+
return [...(typeof id === "string" ? [id] : []), ...idsOfCalls(call.children ?? []), ...idsOfCalls(slotContentCalls(call))];
|
|
1587
|
+
});
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* The slot `written` names on an instance of the component `componentId`: one of its own slots by name, or a slot of an
|
|
1591
|
+
* instance nested in it as `<layer>.<slot>`, the layer named as `over:{...}` names it (`Footer.Actions`, or
|
|
1592
|
+
* `Card.Footer.Actions` deeper). Throws a LayerSyntaxError that lists every slot it has when none matches. With the
|
|
1593
|
+
* stored `instance`, a nested instance's slots are those of the component it shows, as the instance's overrides and
|
|
1594
|
+
* props swap it (`components` holds that component's layers too); without it, those of the component stored.
|
|
1595
|
+
*/
|
|
1596
|
+
export function layerSlotTarget(written, componentId, components, shown, instance) {
|
|
1597
|
+
const context = syntaxContext(components);
|
|
1598
|
+
const component = context.names.byId(componentId);
|
|
1599
|
+
if (component === undefined)
|
|
1600
|
+
throw new LayerSyntaxError(`The component of ${shown} is not known here, so its slots cannot be named.`);
|
|
1601
|
+
const shownAt = shownComponentsOf(context, component, instance);
|
|
1602
|
+
const slots = [
|
|
1603
|
+
...slotPropertiesOf(component).map((property) => ({ name: property.name, id: property.id, path: [] })),
|
|
1604
|
+
...overridePaths(context.document, component).flatMap(({ key, name }) => {
|
|
1605
|
+
const nested = shownAt(key.split(";"));
|
|
1606
|
+
return nested === undefined ? [] : slotPropertiesOf(nested).map((property) => ({ name: `${name}.${property.name}`, id: property.id, path: key.split(";") }));
|
|
1607
|
+
}),
|
|
1608
|
+
];
|
|
1609
|
+
const found = slots.filter((slot) => slot.name === written);
|
|
1610
|
+
if (found.length > 1) {
|
|
1611
|
+
throw new LayerSyntaxError(`${printLayerValue(written)} names ${found.length} slots of ${shown}; give the layers on the way distinct names, or build in the slot's host by its id.`);
|
|
1612
|
+
}
|
|
1613
|
+
const slot = found[0] ?? slots.find((candidate) => candidate.path.length === 0 && candidate.id === written);
|
|
1614
|
+
if (slot === undefined) {
|
|
1615
|
+
throw new LayerSyntaxError(`${shown} has no slot ${printLayerValue(written)}; `
|
|
1616
|
+
+ (slots.length === 0 ? "neither its component nor an instance inside it has slots." : `its slots are ${slots.slice(0, 20).map((candidate) => printLayerValue(candidate.name)).join(", ")}.`));
|
|
1617
|
+
}
|
|
1618
|
+
return { propertyId: slot.id, path: slot.path };
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* For an instance of `component`, the component the nested instance at a path shows: with the stored `instance`, the
|
|
1622
|
+
* one its resolved layers show, as its overrides and props swap it; otherwise, or when it does not resolve, the stored
|
|
1623
|
+
* one. Undefined for a path whose stored layer is not an instance. The instance resolves once, on the first path asked.
|
|
1624
|
+
*/
|
|
1625
|
+
function shownComponentsOf(context, component, instance) {
|
|
1626
|
+
let resolvedAt;
|
|
1627
|
+
return (path) => {
|
|
1628
|
+
const stored = componentAtPath(context.document, component, path);
|
|
1629
|
+
if (stored === undefined || instance?.type !== "instance" || typeof instance.id !== "string" || instance.componentId !== component.id)
|
|
1630
|
+
return stored;
|
|
1631
|
+
if (resolvedAt === undefined) {
|
|
1632
|
+
// The stand-in document has no pages; the instance resolves with no variable modes, as on a page that sets none.
|
|
1633
|
+
const document = { ...context.document, pages: context.document.pages ?? {},
|
|
1634
|
+
nodes: { ...context.document.nodes, [instance.id]: instance } };
|
|
1635
|
+
resolvedAt = resolvedShownComponents(document, instance.id);
|
|
1636
|
+
}
|
|
1637
|
+
const shownId = resolvedAt(path);
|
|
1638
|
+
return (shownId === undefined ? undefined : context.names.byId(shownId)) ?? stored;
|
|
1639
|
+
};
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* `call` in the shorthands' terms, as the default spelling writes it: a component call as instance(componentId:...),
|
|
1643
|
+
* and -fill as fill:(), no fills, which the build writes itself.
|
|
1644
|
+
*/
|
|
1645
|
+
function inShorthandTerms(document, call) {
|
|
1646
|
+
const inTerms = resolveLayerCall(document, call);
|
|
1647
|
+
const takesFill = toolShorthand(inTerms.name)?.short.fill !== undefined;
|
|
1648
|
+
const args = inTerms.arguments.map((argument) => takesFill && argument.remove === true && argument.name === "fill"
|
|
1649
|
+
? { name: argument.name, value: [], text: argument.text, line: argument.line, column: argument.column } : argument);
|
|
1650
|
+
// The layers of a slot are calls too, written in the same terms.
|
|
1651
|
+
const withSlots = args.map((argument) => {
|
|
1652
|
+
const value = mapSlotContents(argument.value, (content) => ({ ...content, calls: content.calls.map((inside) => inShorthandTerms(document, inside)) }));
|
|
1653
|
+
return value === argument.value ? argument : { ...argument, value };
|
|
1654
|
+
});
|
|
1655
|
+
return { ...inTerms, arguments: withSlots, ...(inTerms.children === undefined ? {} : { children: inTerms.children.map((child) => inShorthandTerms(document, child)) }) };
|
|
1656
|
+
}
|
|
1657
|
+
function readNewLayers(text, context, parent) {
|
|
1658
|
+
let calls;
|
|
1659
|
+
let checked;
|
|
1660
|
+
try {
|
|
1661
|
+
const document = parent === undefined ? context.document
|
|
1662
|
+
: { ...context.document, nodes: { ...context.document.nodes, [String(parent.id)]: parent } };
|
|
1663
|
+
checked = checkedBuild(buildNodes(document, text, { syntax: "tool", ...(parent === undefined ? {} : { parentId: String(parent.id) }) }));
|
|
1664
|
+
const reader = layerSyntaxReader(text, "tool");
|
|
1665
|
+
calls = [];
|
|
1666
|
+
while (reader.peek().kind !== "end") {
|
|
1667
|
+
calls.push(inShorthandTerms(document, reader.call()));
|
|
1668
|
+
skipSeparator(reader);
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
catch (error) {
|
|
1672
|
+
if (error instanceof ComponentCallError)
|
|
1673
|
+
throw new LayerSyntaxError(error.message);
|
|
1674
|
+
return refused(error, "");
|
|
1675
|
+
}
|
|
1676
|
+
return newLayersOf(calls, checked);
|
|
1677
|
+
}
|
|
1678
|
+
/**
|
|
1679
|
+
* The layers of a slot, `written` as calls inside `slots:{Name:( ... )}`, read and checked as `readNewLayers` reads new
|
|
1680
|
+
* layers: built from their default spelling, with refusals naming the lines and columns of the text as written.
|
|
1681
|
+
*/
|
|
1682
|
+
function readSlotLayers(written, context) {
|
|
1683
|
+
let places = [];
|
|
1684
|
+
const placeOf = (column) => places.find((place) => place.spelledColumn === column);
|
|
1685
|
+
try {
|
|
1686
|
+
const calls = written.map((call) => inShorthandTerms(context.document, call));
|
|
1687
|
+
places = spellingWithPlaces(calls).places;
|
|
1688
|
+
// () empties the slot: no layers to check.
|
|
1689
|
+
const checked = calls.length === 0 ? { targets: new Set(), attachments: [], built: new Map() } : checkedBuild(buildNodes(context.document, spellingWithPlaces(calls).source), (line, column) => {
|
|
1690
|
+
const place = line === 1 ? placeOf(column) : undefined;
|
|
1691
|
+
return place === undefined ? undefined : { line: place.line, column: place.column };
|
|
1692
|
+
});
|
|
1693
|
+
return newLayersOf(calls, checked);
|
|
1694
|
+
}
|
|
1695
|
+
catch (error) {
|
|
1696
|
+
if (error instanceof ComponentCallError || error instanceof NodeBuildError) {
|
|
1697
|
+
throw new LayerSyntaxError(writtenPlaces(`${error.message}${/[.:]$/.test(error.message) ? "" : "."}`, [places]));
|
|
1698
|
+
}
|
|
1699
|
+
throw error;
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
/**
|
|
1703
|
+
* Checks the connector ends of the layers `built` makes. `placeOf` turns the place of a call in the source built into
|
|
1704
|
+
* the place in the text as written, when the source was re-spelled.
|
|
1705
|
+
*/
|
|
1706
|
+
function checkedBuild(built, placeOf = (line, column) => ({ line, column })) {
|
|
1707
|
+
const targets = new Set();
|
|
1708
|
+
let attachments = [];
|
|
1709
|
+
const builtNodes = new Map();
|
|
1710
|
+
for (const subtree of built.subtrees) {
|
|
1711
|
+
for (const node of Object.values(subtree.nodes)) {
|
|
1712
|
+
const made = built.calls.find((entry) => entry.id === node.id);
|
|
1713
|
+
const place = made === undefined ? undefined : placeOf(made.line, made.column);
|
|
1714
|
+
const where = made === undefined ? `#${String(node.id)}` : place === undefined ? `In ${made.call}` : `Line ${place.line}, column ${place.column}, in ${made.call}`;
|
|
1715
|
+
checkConnectorEnds(node, where);
|
|
1716
|
+
connectorTargets(node).forEach((id) => targets.add(id));
|
|
1717
|
+
attachments.push(...connectorAttachments(node, where));
|
|
1718
|
+
builtNodes.set(String(node.id), node);
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
// An end attached to a layer of the same build is checked against it here; the others when the host reads their layers.
|
|
1722
|
+
attachments = checkKnownAttachments(attachments, (id) => builtNodes.get(id));
|
|
1723
|
+
return { targets, attachments, built: builtNodes };
|
|
1724
|
+
}
|
|
1725
|
+
/** New layers from their calls, in the shorthands' terms, and their build checked: the removals, the ids and each call's source. */
|
|
1726
|
+
function newLayersOf(calls, { targets, attachments, built }) {
|
|
1727
|
+
const removals = [];
|
|
1728
|
+
const ids = [];
|
|
1729
|
+
const layers = [];
|
|
1730
|
+
const collect = (call) => {
|
|
1731
|
+
const id = call.arguments.find((argument) => argument.name === "id")?.value;
|
|
1732
|
+
if (typeof id === "string")
|
|
1733
|
+
ids.push(id);
|
|
1734
|
+
const remove = call.arguments.filter((argument) => argument.remove === true).map((argument) => argument.name);
|
|
1735
|
+
if (remove.length > 0) {
|
|
1736
|
+
if (typeof id !== "string") {
|
|
1737
|
+
throw new LayerSyntaxError(`Line ${call.line}, column ${call.column}: -${remove[0]} leaves a field out of a new layer, which needs the layer's id: add id:'<new id>' to ${call.name}(...).`);
|
|
1738
|
+
}
|
|
1739
|
+
removals.push({ nodeId: id, remove });
|
|
1740
|
+
}
|
|
1741
|
+
(call.children ?? []).forEach(collect);
|
|
1742
|
+
slotContentCalls(call).forEach(collect);
|
|
1743
|
+
};
|
|
1744
|
+
for (const call of calls) {
|
|
1745
|
+
const before = removals.length;
|
|
1746
|
+
collect(call);
|
|
1747
|
+
layers.push({ ...spellingWithPlaces([call]), removals: removals.slice(before) });
|
|
1748
|
+
}
|
|
1749
|
+
return { ...spellingWithPlaces(calls), removals, count: calls.length, ids, attachedTo: [...targets].filter((id) => !ids.includes(id)), attachments,
|
|
1750
|
+
built: new Map([...built].filter(([id]) => ids.includes(id))), layers };
|
|
1751
|
+
}
|
|
1752
|
+
/** Reads an `edit` text: `[in #scope;]` then rules, as `set ...; add ...; move ...`. */
|
|
1753
|
+
export function readLayerEdit(text) {
|
|
1754
|
+
try {
|
|
1755
|
+
const reader = layerSyntaxReader(text, "tool");
|
|
1756
|
+
if (!isWord(reader.peek(), "in"))
|
|
1757
|
+
return { rules: text };
|
|
1758
|
+
reader.next();
|
|
1759
|
+
const scopeId = readId(reader, "the id of the layer to edit in, as in #card");
|
|
1760
|
+
skipSeparator(reader);
|
|
1761
|
+
const start = reader.peek().start;
|
|
1762
|
+
return { scopeId, rules: only(text, start) };
|
|
1763
|
+
}
|
|
1764
|
+
catch (error) {
|
|
1765
|
+
return refused(error, `Write in #<layer id>; before the rules to look in one layer only. ${RULE_FORM}`);
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
/** The verbs of Boolean operations, which combine the shapes of layers into one path. */
|
|
1769
|
+
const BOOLEAN_VERBS = ["union", "subtract", "intersect", "exclude"];
|
|
1770
|
+
const isBooleanVerb = (verb) => BOOLEAN_VERBS.includes(verb);
|
|
1771
|
+
/** How a matcher writes the layers inside a layer, for the forms of the rules. */
|
|
1772
|
+
const STEPS_FORM = "#card > text is a text directly inside #card, #card text one at any depth inside it.";
|
|
1773
|
+
const SET_FORM = "Write set <layer> { field:value, -field }, where <layer> is #<id> or a call such as text(name:'Title'), "
|
|
1774
|
+
+ `with all before it for every match: set all text(size:12) { size:14 }. ${STEPS_FORM}`;
|
|
1775
|
+
const ADD_FORM = "Write add <parent> at:<index> [<layers>] to put new layers inside a layer (leave out at: to put them on top), "
|
|
1776
|
+
+ "or add after:<layer> [<layers>] or add before:<layer> [<layers>] to put them next to one: add #card at:0 [text(text:'New')].";
|
|
1777
|
+
const MOVE_FORM = "Write move <layer> before:<layer>, move <layer> after:<layer>, move <layer> in:<parent> at:<index> "
|
|
1778
|
+
+ "(leave out at: to put it on top) or move <layer> at:<index> within its parent: move #badge in:#header at:0.";
|
|
1779
|
+
const REMOVE_FORM = "Write remove <layer>, or remove all <layer> for every match: remove all text(size:9).";
|
|
1780
|
+
const REPLACE_FORM = "Write replace <layer> [<layers>]; the new layers go where the layer was, with new ids: replace #badge [rect(w:8, h:8)].";
|
|
1781
|
+
const CONVERT_FORM = "Write convert <frame> to component(name:'<name>'); the frame becomes the component's root and an instance of it "
|
|
1782
|
+
+ "takes its place (leave out (name:...) to name it after the frame): convert #buy to component(name:'Button'). "
|
|
1783
|
+
+ "Add replace #<copy> #<copy> to turn copies of the frame into instances too: convert #buy to component replace #buy-2 #buy-3.";
|
|
1784
|
+
/** The key of a prop rule, and of the components list, that holds a component's validity expression. */
|
|
1785
|
+
const VALIDITY_KEY = "valid";
|
|
1786
|
+
const VALIDITY_FORM = "prop #<root> { valid:'not (Disabled and Hover)' } lets the component's instances take only the combinations of its "
|
|
1787
|
+
+ "enum and boolean props the expression is true for (the defaults must be one); -valid removes it, so every combination is valid. "
|
|
1788
|
+
+ "A prop named valid is written in quotes, 'valid':false.";
|
|
1789
|
+
const PROP_FORM = "Write prop <component root> { Name:false, Label:'Text', Size:(small, large), -Old } with the root held, as in #card; "
|
|
1790
|
+
+ "prop #card { Hover:false }: true or false makes a boolean prop, a string a text prop, and options in parentheses an enum prop, the default "
|
|
1791
|
+
+ "first. A prop the component has takes the new default (an enum's by an option's name, Size:large); -Name removes one. A layer inside the "
|
|
1792
|
+
+ "component reads a prop with set #<layer> { expressions:{visible:'Hover', characters:'Label'} }. A name that is not a word goes in quotes, "
|
|
1793
|
+
+ "'Primary / Hover':false, and an expression writes it in backticks, visible:'`Primary / Hover`'.";
|
|
1794
|
+
const OUTLINE_FORM = "Write outline <layer>, or outline all <layer> for every match, as the first rules of an edit; each stroke becomes a filled path "
|
|
1795
|
+
+ "just above the layer, which stays without its strokes when it shows something else and goes otherwise: outline #arrow.";
|
|
1796
|
+
const BOOLEAN_FORM = "Write union #<id> #<id>, subtract, intersect or exclude with two or more layer ids, as the first rule of an edit; "
|
|
1797
|
+
+ "their shapes become one path that takes the first layer's id, place and style, and the other layers go: union #left #right. "
|
|
1798
|
+
+ "subtract takes every later layer away from the first.";
|
|
1799
|
+
const RULE_FORM = "Write rules such as set <layer> { field:value, -field }, add <parent> at:<index> [<layers>], add after:<layer> [<layers>], "
|
|
1800
|
+
+ "move <layer> before:<layer>, move <layer> in:<parent> at:<index>, remove <layer>, replace <layer> [<layers>], "
|
|
1801
|
+
+ "convert <frame> to component(name:'<name>'), prop <component root> { Name:false }, outline <layer> or union #<id> #<id>, separated by ;. "
|
|
1802
|
+
+ `<layer> is #<id> or a call such as text(name:'Title'), with all before it for every match. ${STEPS_FORM}`;
|
|
1803
|
+
const FORMS = { set: SET_FORM, add: ADD_FORM, move: MOVE_FORM, remove: REMOVE_FORM, replace: REPLACE_FORM, convert: CONVERT_FORM,
|
|
1804
|
+
prop: PROP_FORM, outline: OUTLINE_FORM, union: BOOLEAN_FORM, subtract: BOOLEAN_FORM, intersect: BOOLEAN_FORM, exclude: BOOLEAN_FORM };
|
|
1805
|
+
const PLACE_WORDS = new Set(["at", "before", "after", "in"]);
|
|
1806
|
+
/** A syntax refusal at `token`, with its line and column, to which the rule's form is added. */
|
|
1807
|
+
const refusalAt = (token, message) => new NodeBuildError("syntax", `Line ${token.line}, column ${token.column}: ${message}`, token.line, token.column);
|
|
1808
|
+
/**
|
|
1809
|
+
* The words that end a matcher where a step after a space could start: a verb starts the next rule, and `to` follows
|
|
1810
|
+
* the frame of convert. After `>` they are steps, so that a component called so can still be matched.
|
|
1811
|
+
*/
|
|
1812
|
+
const MATCHER_END_WORDS = new Set(["set", "add", "move", "remove", "replace", "convert", "prop", "outline", ...BOOLEAN_VERBS, "to"]);
|
|
1813
|
+
/** Reads one step of a matcher at the reader; `after` is the word before it, for a refusal. */
|
|
1814
|
+
function readStep(reader, after) {
|
|
1815
|
+
if (reader.peek().kind === "colour")
|
|
1816
|
+
return { id: readId(reader, "a layer"), filters: [] };
|
|
1817
|
+
const name = reader.peek();
|
|
1818
|
+
let head;
|
|
1819
|
+
const filters = [];
|
|
1820
|
+
if (name.kind === "word")
|
|
1821
|
+
head = name.text;
|
|
1822
|
+
else if (!reader.isPunctuation(name, "*"))
|
|
1823
|
+
throw reader.expected(`#<id> or a kind of layer such as text(...) after ${after}`);
|
|
1824
|
+
reader.next();
|
|
1825
|
+
if (reader.isPunctuation(reader.peek(), "(")) {
|
|
1826
|
+
reader.next();
|
|
1827
|
+
while (!reader.isPunctuation(reader.peek(), ")")) {
|
|
1828
|
+
const key = reader.peek();
|
|
1829
|
+
if (key.kind !== "word" && key.kind !== "string")
|
|
1830
|
+
throw reader.expected("a field to match, as name:'Title'");
|
|
1831
|
+
reader.next();
|
|
1832
|
+
reader.expect(":");
|
|
1833
|
+
filters.push({ key: String(key.value), value: reader.value() });
|
|
1834
|
+
if (reader.isPunctuation(reader.peek(), ","))
|
|
1835
|
+
reader.next();
|
|
1836
|
+
else if (!reader.isPunctuation(reader.peek(), ")"))
|
|
1837
|
+
throw reader.expected("\",\" or \")\"");
|
|
1838
|
+
}
|
|
1839
|
+
reader.next();
|
|
1840
|
+
}
|
|
1841
|
+
return { ...(head === undefined ? {} : { head }), filters };
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* Reads a matcher at the reader, `[all] <step> { [>] <step> }`; `after` is the word before it, for a refusal. A step
|
|
1845
|
+
* after a space is a kind of layer or `*`; a word with `:` after it (a place such as at:), a verb and `to` end the matcher.
|
|
1846
|
+
*/
|
|
1847
|
+
function readMatcher(reader, text, after) {
|
|
1848
|
+
const start = reader.peek();
|
|
1849
|
+
const all = isWord(start, "all");
|
|
1850
|
+
if (all)
|
|
1851
|
+
reader.next();
|
|
1852
|
+
const first = reader.peek().start;
|
|
1853
|
+
const steps = [readStep(reader, after)];
|
|
1854
|
+
const child = [];
|
|
1855
|
+
let lastStart = first, lastStep = first, spaceStep;
|
|
1856
|
+
for (;;) {
|
|
1857
|
+
const next = reader.peek();
|
|
1858
|
+
const isChild = reader.isPunctuation(next, ">");
|
|
1859
|
+
const startsStep = isChild || next.kind === "colour" || reader.isPunctuation(next, "*")
|
|
1860
|
+
|| (next.kind === "word" && !MATCHER_END_WORDS.has(next.text) && !reader.isPunctuation(reader.peek(1), ":"));
|
|
1861
|
+
if (!startsStep)
|
|
1862
|
+
break;
|
|
1863
|
+
const before = text.slice(first, next.start).trim();
|
|
1864
|
+
lastStart = next.start;
|
|
1865
|
+
if (isChild)
|
|
1866
|
+
reader.next();
|
|
1867
|
+
const step = reader.peek();
|
|
1868
|
+
if (step.kind === "colour") {
|
|
1869
|
+
const id = step.text === "#" ? "#<id>" : step.text;
|
|
1870
|
+
throw refusalAt(step, `${id} comes after ${before}; an id names one layer, so it is the first step of a matcher (${id} > text) `
|
|
1871
|
+
+ "or the whole matcher, and two layers take a rule each");
|
|
1872
|
+
}
|
|
1873
|
+
if (isWord(step, "all"))
|
|
1874
|
+
throw refusalAt(step, `all goes once, before the whole matcher, as all ${before} text`);
|
|
1875
|
+
child.push(isChild);
|
|
1876
|
+
lastStep = step.start;
|
|
1877
|
+
if (!isChild)
|
|
1878
|
+
spaceStep ??= step;
|
|
1879
|
+
steps.push(readStep(reader, isChild ? ">" : before));
|
|
1880
|
+
}
|
|
1881
|
+
const last = steps[steps.length - 1];
|
|
1882
|
+
if (all && steps.length === 1 && last.id !== undefined) {
|
|
1883
|
+
throw refusalAt(start, `all matches every layer of a kind, and #${last.id} names one layer: write #${last.id} alone, or all #${last.id} text for the texts inside it`);
|
|
1884
|
+
}
|
|
1885
|
+
const within = steps.slice(0, -1).map((step, index) => ({ step, child: child[index] }));
|
|
1886
|
+
return { text: text.slice(start.start, reader.peek().start).trim(), all, ...last, within, ...(spaceStep === undefined ? {} : { spaceStep }),
|
|
1887
|
+
...(within.length === 0 ? {} : { withinText: text.slice(first, lastStart).trim(), lastText: text.slice(lastStep, reader.peek().start).trim() }) };
|
|
1888
|
+
}
|
|
1889
|
+
const atPlace = (reader) => {
|
|
1890
|
+
const word = reader.peek();
|
|
1891
|
+
return word.kind === "word" && PLACE_WORDS.has(word.text) && reader.isPunctuation(reader.peek(1), ":");
|
|
1892
|
+
};
|
|
1893
|
+
/** Reads the places at the reader: `at:<index>`, `before:<layer>`, `after:<layer>`, `in:<layer>`, each once. */
|
|
1894
|
+
function readPlaces(reader, text, form) {
|
|
1895
|
+
const places = [];
|
|
1896
|
+
while (atPlace(reader)) {
|
|
1897
|
+
const word = reader.next().text;
|
|
1898
|
+
reader.next();
|
|
1899
|
+
if (places.some((place) => place.kind === word))
|
|
1900
|
+
throw new LayerSyntaxError(`${word}: is written twice. ${form}`);
|
|
1901
|
+
if (word === "at") {
|
|
1902
|
+
const at = reader.peek();
|
|
1903
|
+
if (at.kind !== "number" || !Number.isInteger(at.value) || at.value < 0)
|
|
1904
|
+
throw reader.expected("an index of 0 or more after at:", at);
|
|
1905
|
+
reader.next();
|
|
1906
|
+
places.push({ kind: "at", index: at.value });
|
|
1907
|
+
}
|
|
1908
|
+
else {
|
|
1909
|
+
const matcher = readMatcher(reader, text, `${word}:`);
|
|
1910
|
+
if (matcher.all)
|
|
1911
|
+
throw new LayerSyntaxError(`${word}: names one layer; leave out all. ${form}`);
|
|
1912
|
+
places.push({ kind: word, matcher });
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
return places;
|
|
1916
|
+
}
|
|
1917
|
+
/** Reads the new layers of an `add` or `replace` at the reader, `[<layers>]`, as their text with the rest blanked out. */
|
|
1918
|
+
function readLayersText(reader, text, verb, matcher) {
|
|
1919
|
+
if (!reader.isPunctuation(reader.peek(), "[")) {
|
|
1920
|
+
// New layers written without [...] read as a step of the matcher before them: name the first such step.
|
|
1921
|
+
const token = matcher?.spaceStep ?? reader.peek();
|
|
1922
|
+
throw new LayerSyntaxError(`Line ${token.line}, column ${token.column}: ${verb} needs its new layers in [...], found ${token.kind === "end" ? "the end" : JSON.stringify(token.text)}. ${FORMS[verb]}`);
|
|
1923
|
+
}
|
|
1924
|
+
const open = reader.next();
|
|
1925
|
+
if (reader.isPunctuation(reader.peek(), "]"))
|
|
1926
|
+
throw new LayerSyntaxError(`Line ${open.line}, column ${open.column}: there is no layer in [...]. ${FORMS[verb]}`);
|
|
1927
|
+
while (!reader.isPunctuation(reader.peek(), "]")) {
|
|
1928
|
+
if (reader.peek().kind === "end")
|
|
1929
|
+
throw reader.expected("\"]\" after the new layers");
|
|
1930
|
+
reader.call();
|
|
1931
|
+
skipSeparator(reader);
|
|
1932
|
+
}
|
|
1933
|
+
const close = reader.next();
|
|
1934
|
+
return only(text, open.end, close.start);
|
|
1935
|
+
}
|
|
1936
|
+
const matcherOf = (place) => place.kind === "at" ? undefined : place.matcher;
|
|
1937
|
+
const placesOf = (places) => places.map((place) => place.kind).sort().join(" ");
|
|
1938
|
+
/**
|
|
1939
|
+
* The `{ key:value, -key }` of a set (`what` is "field") or a prop (`what` is "prop"), from its `{` to after its `}`: the
|
|
1940
|
+
* writes in order, each marked when its value is a bare word, and the keys to remove.
|
|
1941
|
+
*/
|
|
1942
|
+
function readFields(reader, what) {
|
|
1943
|
+
reader.expect("{", `"{" with the ${what}s to set`);
|
|
1944
|
+
const writes = [];
|
|
1945
|
+
const removes = [];
|
|
1946
|
+
let validity;
|
|
1947
|
+
while (!reader.isPunctuation(reader.peek(), "}")) {
|
|
1948
|
+
const removal = reader.isPunctuation(reader.peek(), "-");
|
|
1949
|
+
if (removal)
|
|
1950
|
+
reader.next();
|
|
1951
|
+
const key = reader.peek();
|
|
1952
|
+
if (key.kind !== "word" && key.kind !== "string")
|
|
1953
|
+
throw reader.expected(removal ? `a ${what} name after -` : `a ${what} name, or -${what} to remove one`);
|
|
1954
|
+
reader.next();
|
|
1955
|
+
if (what === "prop" && key.kind === "word" && key.value === VALIDITY_KEY) {
|
|
1956
|
+
// valid (a word) is the component's validity expression; a prop named valid is written in quotes, 'valid':false.
|
|
1957
|
+
if (validity !== undefined)
|
|
1958
|
+
throw new LayerSyntaxError(`${VALIDITY_KEY} is written once in a prop rule. ${VALIDITY_FORM}`);
|
|
1959
|
+
if (removal)
|
|
1960
|
+
validity = null;
|
|
1961
|
+
else {
|
|
1962
|
+
reader.expect(":", `":" after ${VALIDITY_KEY}, or -${VALIDITY_KEY} to remove it`);
|
|
1963
|
+
const value = reader.peek();
|
|
1964
|
+
if (value.kind !== "string")
|
|
1965
|
+
throw new LayerSyntaxError(`${VALIDITY_KEY} takes its expression in quotes. ${VALIDITY_FORM}`);
|
|
1966
|
+
validity = String(reader.value());
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
else if (removal)
|
|
1970
|
+
removes.push(String(key.value));
|
|
1971
|
+
else {
|
|
1972
|
+
if (reader.isPunctuation(reader.peek(), "-") || isWord(reader.peek(), "null"))
|
|
1973
|
+
throw reader.expected("a value");
|
|
1974
|
+
reader.expect(":", `":" after ${String(key.value)}, or -${String(key.value)} to remove it`);
|
|
1975
|
+
const valueToken = reader.peek();
|
|
1976
|
+
if (isWord(valueToken, "null"))
|
|
1977
|
+
throw new LayerSyntaxError(`null is not a value: write -${String(key.value)} to remove ${String(key.value)}.`);
|
|
1978
|
+
const word = valueToken.kind === "word" && typeof valueToken.value === "string";
|
|
1979
|
+
writes.push({ key: String(key.value), value: reader.argumentValue(String(key.value)), word });
|
|
1980
|
+
}
|
|
1981
|
+
if (reader.isPunctuation(reader.peek(), ","))
|
|
1982
|
+
reader.next();
|
|
1983
|
+
else if (!reader.isPunctuation(reader.peek(), "}"))
|
|
1984
|
+
throw reader.expected("\",\" or \"}\"");
|
|
1985
|
+
}
|
|
1986
|
+
reader.next();
|
|
1987
|
+
return validity === undefined ? { writes, removes } : { writes, removes, validity };
|
|
1988
|
+
}
|
|
1989
|
+
function readRules(text) {
|
|
1990
|
+
let form = RULE_FORM;
|
|
1991
|
+
try {
|
|
1992
|
+
const reader = layerSyntaxReader(text, "tool");
|
|
1993
|
+
const rules = [];
|
|
1994
|
+
while (reader.peek().kind !== "end") {
|
|
1995
|
+
const verb = reader.peek();
|
|
1996
|
+
if (verb.kind !== "word" || !Object.hasOwn(FORMS, verb.text))
|
|
1997
|
+
throw reader.expected("a rule such as set #card { gap:16 } or add #card [text(text:'New')]");
|
|
1998
|
+
reader.next();
|
|
1999
|
+
form = FORMS[verb.text];
|
|
2000
|
+
switch (verb.text) {
|
|
2001
|
+
case "set": {
|
|
2002
|
+
const matcher = readMatcher(reader, text, "set");
|
|
2003
|
+
const { writes, removes } = readFields(reader, "field");
|
|
2004
|
+
if (reader.isPunctuation(reader.peek(), "["))
|
|
2005
|
+
throw new LayerSyntaxError(`set changes fields; add layers with add ${matcher.text} [...].`);
|
|
2006
|
+
rules.push({ verb: "set", matcher, writes, removes });
|
|
2007
|
+
break;
|
|
2008
|
+
}
|
|
2009
|
+
case "prop": {
|
|
2010
|
+
const matcher = readMatcher(reader, text, "prop");
|
|
2011
|
+
if (matcher.all)
|
|
2012
|
+
throw new LayerSyntaxError(`prop changes the props of one component; leave out all. ${PROP_FORM}`);
|
|
2013
|
+
rules.push({ verb: "prop", matcher, ...readFields(reader, "prop") });
|
|
2014
|
+
break;
|
|
2015
|
+
}
|
|
2016
|
+
case "add": {
|
|
2017
|
+
const parent = atPlace(reader) ? undefined : readMatcher(reader, text, "add");
|
|
2018
|
+
const places = readPlaces(reader, text, ADD_FORM);
|
|
2019
|
+
const shape = placesOf(places);
|
|
2020
|
+
const fits = parent === undefined ? ["before", "after", "in", "at in"].includes(shape) : ["", "at"].includes(shape);
|
|
2021
|
+
if (!fits) {
|
|
2022
|
+
throw new LayerSyntaxError(parent === undefined && shape === "at"
|
|
2023
|
+
? `add at: needs the layer to add into before it. ${ADD_FORM}`
|
|
2024
|
+
: `add takes a parent with at:, or one place next to a layer, not ${[...(parent === undefined ? [] : [parent.text]), ...places.map((place) => `${place.kind}:`)].join(" and ")}. ${ADD_FORM}`);
|
|
2025
|
+
}
|
|
2026
|
+
rules.push({ verb: "add", ...(parent === undefined ? {} : { parent }), places, layers: readLayersText(reader, text, "add", places.length === 0 ? parent : matcherOf(places[places.length - 1])) });
|
|
2027
|
+
break;
|
|
2028
|
+
}
|
|
2029
|
+
case "move": {
|
|
2030
|
+
const matcher = readMatcher(reader, text, "move");
|
|
2031
|
+
if (matcher.all)
|
|
2032
|
+
throw new LayerSyntaxError(`move moves one layer; leave out all and write a move for each. ${MOVE_FORM}`);
|
|
2033
|
+
const places = readPlaces(reader, text, MOVE_FORM);
|
|
2034
|
+
if (!["before", "after", "in", "at in", "at"].includes(placesOf(places))) {
|
|
2035
|
+
throw new LayerSyntaxError(places.length === 0 ? `move needs a place for ${matcher.text}. ${MOVE_FORM}`
|
|
2036
|
+
: `move takes one place, or in: with at:, not ${places.map((place) => `${place.kind}:`).join(" and ")}. ${MOVE_FORM}`);
|
|
2037
|
+
}
|
|
2038
|
+
rules.push({ verb: "move", matcher, places });
|
|
2039
|
+
break;
|
|
2040
|
+
}
|
|
2041
|
+
case "remove":
|
|
2042
|
+
rules.push({ verb: "remove", matcher: readMatcher(reader, text, "remove") });
|
|
2043
|
+
break;
|
|
2044
|
+
case "outline":
|
|
2045
|
+
rules.push({ verb: "outline", matcher: readMatcher(reader, text, "outline") });
|
|
2046
|
+
break;
|
|
2047
|
+
case "replace": {
|
|
2048
|
+
const matcher = readMatcher(reader, text, "replace");
|
|
2049
|
+
rules.push({ verb: "replace", matcher, layers: readLayersText(reader, text, "replace", matcher) });
|
|
2050
|
+
break;
|
|
2051
|
+
}
|
|
2052
|
+
case "convert": {
|
|
2053
|
+
const matcher = readMatcher(reader, text, "convert");
|
|
2054
|
+
if (matcher.all)
|
|
2055
|
+
throw new LayerSyntaxError(`convert turns one frame into a component; leave out all. ${CONVERT_FORM}`);
|
|
2056
|
+
if (!isWord(reader.peek(), "to"))
|
|
2057
|
+
throw reader.expected("to component after the frame");
|
|
2058
|
+
reader.next();
|
|
2059
|
+
if (!isWord(reader.peek(), "component"))
|
|
2060
|
+
throw reader.expected("component after to");
|
|
2061
|
+
reader.next();
|
|
2062
|
+
let name;
|
|
2063
|
+
if (reader.isPunctuation(reader.peek(), "(")) {
|
|
2064
|
+
reader.next();
|
|
2065
|
+
if (!isWord(reader.peek(), "name"))
|
|
2066
|
+
throw reader.expected("name:'<name>' in component(...)");
|
|
2067
|
+
reader.next();
|
|
2068
|
+
reader.expect(":");
|
|
2069
|
+
const value = reader.value();
|
|
2070
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
2071
|
+
throw new LayerSyntaxError(`The component's name is a string that is not empty, as name:'Button'. ${CONVERT_FORM}`);
|
|
2072
|
+
name = value;
|
|
2073
|
+
if (reader.isPunctuation(reader.peek(), ",") && isWord(reader.peek(1), "props")) {
|
|
2074
|
+
throw new LayerSyntaxError(`convert takes only the name; give the component props in a later call, with its root held: `
|
|
2075
|
+
+ `in ${matcher.text}; prop ${matcher.text} { checked:false }. ${PROP_FORM}`);
|
|
2076
|
+
}
|
|
2077
|
+
reader.expect(")", "\")\" after the name");
|
|
2078
|
+
}
|
|
2079
|
+
// replace #b #c: copies of the frame that become instances of the component in their places.
|
|
2080
|
+
const replace = [];
|
|
2081
|
+
if (isWord(reader.peek(), "replace")) {
|
|
2082
|
+
reader.next();
|
|
2083
|
+
while (reader.peek().kind === "colour")
|
|
2084
|
+
replace.push(readId(reader, "a copy"));
|
|
2085
|
+
if (replace.length === 0)
|
|
2086
|
+
throw reader.expected("#<copy id> after replace");
|
|
2087
|
+
if (reader.isPunctuation(reader.peek(), "[")) {
|
|
2088
|
+
throw new LayerSyntaxError(`replace after convert takes copies of the frame, not new layers; to replace a layer with new layers, put ; before replace. ${CONVERT_FORM}`);
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
rules.push({ verb: "convert", matcher, ...(name === undefined ? {} : { name }), replace });
|
|
2092
|
+
break;
|
|
2093
|
+
}
|
|
2094
|
+
case "union":
|
|
2095
|
+
case "subtract":
|
|
2096
|
+
case "intersect":
|
|
2097
|
+
case "exclude": {
|
|
2098
|
+
const ids = [];
|
|
2099
|
+
while (reader.peek().kind === "colour")
|
|
2100
|
+
ids.push(readId(reader, "a layer"));
|
|
2101
|
+
if (ids.length < 2)
|
|
2102
|
+
throw reader.expected(`two or more #<layer id> after ${verb.text}`);
|
|
2103
|
+
rules.push({ verb: verb.text, ids });
|
|
2104
|
+
break;
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
if (!reader.isPunctuation(reader.peek(), ";") && !reader.isPunctuation(reader.peek(), ",") && reader.peek().kind !== "end"
|
|
2108
|
+
&& !(reader.peek().kind === "word" && Object.hasOwn(FORMS, reader.peek().text))) {
|
|
2109
|
+
throw reader.expected("; and the next rule, or the end");
|
|
2110
|
+
}
|
|
2111
|
+
skipSeparator(reader);
|
|
2112
|
+
form = RULE_FORM;
|
|
2113
|
+
}
|
|
2114
|
+
if (rules.length === 0)
|
|
2115
|
+
throw new LayerSyntaxError(`There is no rule. ${RULE_FORM}`);
|
|
2116
|
+
return rules;
|
|
2117
|
+
}
|
|
2118
|
+
catch (error) {
|
|
2119
|
+
return refused(error, form);
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
/**
|
|
2123
|
+
* The value a filter compares for `key` of a layer, or undefined when it has none. A prop of an instance compares the
|
|
2124
|
+
* value it takes, its default when the instance stores none, as the syntax writes it (an enum's option by name).
|
|
2125
|
+
*/
|
|
2126
|
+
function filterValue(node, key, context) {
|
|
2127
|
+
const shorthand = shorthandNamed(headsOf(node)[0]);
|
|
2128
|
+
const frame = isRecord(node.frame) ? node.frame : {};
|
|
2129
|
+
switch (key) {
|
|
2130
|
+
case "id":
|
|
2131
|
+
case "name":
|
|
2132
|
+
case "opacity": return node[key];
|
|
2133
|
+
case "x":
|
|
2134
|
+
case "y": return frame[key];
|
|
2135
|
+
case "w":
|
|
2136
|
+
case "h": {
|
|
2137
|
+
const sizing = sizingOf(node, key === "w" ? "width" : "height", context);
|
|
2138
|
+
return sizing === "fixed" ? frame[key === "w" ? "width" : "height"] : sizing;
|
|
2139
|
+
}
|
|
2140
|
+
default: {
|
|
2141
|
+
const property = componentOfInstance(node, context)?.properties?.filter(isValuedComponentProperty).find((candidate) => candidate.name === key);
|
|
2142
|
+
if (property !== undefined) {
|
|
2143
|
+
const stored = isRecord(node.propertyValues) ? node.propertyValues[property.id] : undefined;
|
|
2144
|
+
return printedPropertyValue(property, effectivePropertyValue(property, stored), context.names);
|
|
2145
|
+
}
|
|
2146
|
+
const reader = readersOf(shorthand)[key];
|
|
2147
|
+
if (reader !== undefined)
|
|
2148
|
+
return reader.read(node);
|
|
2149
|
+
// A matcher cannot test a field an agent is not shown (`AGENT_HIDDEN_NODE_FIELDS`).
|
|
2150
|
+
return Object.hasOwn(node, key) && !isAgentHiddenNodeField(key) ? node[key] : undefined;
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
}
|
|
2154
|
+
/** A layer's head and id with its name and content, as a refusal lists it. */
|
|
2155
|
+
function listed(node, context) {
|
|
2156
|
+
const head = headOf(node, context);
|
|
2157
|
+
const content = shorthandNamed(headsOf(node)[0]).content;
|
|
2158
|
+
const contentValue = content === undefined ? undefined : filterValue(node, content, context);
|
|
2159
|
+
const parts = [`name:${printLayerValue(String(node.name))}`];
|
|
2160
|
+
if (typeof contentValue === "string")
|
|
2161
|
+
parts.push(`${content}:${printLayerValue(contentValue.length > 40 ? `${contentValue.slice(0, 40)}...` : contentValue)}`);
|
|
2162
|
+
return `#${String(node.id)} ${head}(${parts.join(", ")})`;
|
|
2163
|
+
}
|
|
2164
|
+
const LIST_LIMIT = 8;
|
|
2165
|
+
/** How many characters to insert, delete or replace to turn `a` into `b` (the Levenshtein distance). */
|
|
2166
|
+
function editDistance(a, b) {
|
|
2167
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
2168
|
+
for (let i = 1; i <= a.length; i += 1) {
|
|
2169
|
+
const row = [i];
|
|
2170
|
+
for (let j = 1; j <= b.length; j += 1) {
|
|
2171
|
+
row[j] = Math.min(previous[j] + 1, row[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
2172
|
+
}
|
|
2173
|
+
previous = row;
|
|
2174
|
+
}
|
|
2175
|
+
return previous[b.length];
|
|
2176
|
+
}
|
|
2177
|
+
/** The longest unknown id `closestId` looks for a like id of; a longer one is not an id mistyped. */
|
|
2178
|
+
const CLOSEST_ID_LIMIT = 100;
|
|
2179
|
+
/**
|
|
2180
|
+
* The id of `ids` fewest edits away from `id`, the first of those tied; undefined when there is none, or `id` is longer
|
|
2181
|
+
* than 100 characters, so that the work stays small for any id an edit sends.
|
|
2182
|
+
*/
|
|
2183
|
+
function closestId(id, ids) {
|
|
2184
|
+
if (id.length > CLOSEST_ID_LIMIT)
|
|
2185
|
+
return undefined;
|
|
2186
|
+
let best, bestDistance = Infinity;
|
|
2187
|
+
for (const candidate of ids) {
|
|
2188
|
+
// The difference in length is the fewest edits a candidate can be away, so one that cannot beat the best is skipped.
|
|
2189
|
+
if (Math.abs(candidate.length - id.length) >= bestDistance || candidate.length > id.length + 64)
|
|
2190
|
+
continue;
|
|
2191
|
+
const distance = editDistance(id, candidate);
|
|
2192
|
+
if (distance < bestDistance) {
|
|
2193
|
+
best = candidate;
|
|
2194
|
+
bestDistance = distance;
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
return best;
|
|
2198
|
+
}
|
|
2199
|
+
/** Deep merge as `node.patch` merges: objects merge, any other value replaces. */
|
|
2200
|
+
function merged(previous, value) {
|
|
2201
|
+
if (!isRecord(previous) || !isRecord(value))
|
|
2202
|
+
return clone(value);
|
|
2203
|
+
const result = { ...previous };
|
|
2204
|
+
for (const [key, item] of Object.entries(value))
|
|
2205
|
+
result[key] = merged(previous[key], item);
|
|
2206
|
+
return result;
|
|
2207
|
+
}
|
|
2208
|
+
/** Whether `next` leaves out a key that `previous` holds at some depth of objects, which `node.patch` cannot remove. */
|
|
2209
|
+
function losesNestedKey(previous, next) {
|
|
2210
|
+
if (!isRecord(previous) || !isRecord(next))
|
|
2211
|
+
return false;
|
|
2212
|
+
return Object.keys(previous).some((key) => !Object.hasOwn(next, key) || losesNestedKey(previous[key], next[key]));
|
|
2213
|
+
}
|
|
2214
|
+
/**
|
|
2215
|
+
* Drops each binding of `after` that `before` held the value of and `after` no longer holds (a set wrote over the
|
|
2216
|
+
* field it drives), as the editor detaches a variable from a field the person edits; `kept` are bound by
|
|
2217
|
+
* the change itself.
|
|
2218
|
+
*/
|
|
2219
|
+
function dropOverwrittenBindings(before, after, kept, context) {
|
|
2220
|
+
if (!isRecord(after.variableBindings))
|
|
2221
|
+
return;
|
|
2222
|
+
const bindings = { ...after.variableBindings };
|
|
2223
|
+
let dropped = false;
|
|
2224
|
+
for (const [property, id] of Object.entries(after.variableBindings)) {
|
|
2225
|
+
if (kept.has(property))
|
|
2226
|
+
continue;
|
|
2227
|
+
if (holdsBoundValue(before, property, id, context) === true && holdsBoundValue(after, property, id, context) !== true) {
|
|
2228
|
+
delete bindings[property];
|
|
2229
|
+
dropped = true;
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
if (!dropped)
|
|
2233
|
+
return;
|
|
2234
|
+
if (Object.keys(bindings).length === 0)
|
|
2235
|
+
delete after.variableBindings;
|
|
2236
|
+
else
|
|
2237
|
+
after.variableBindings = bindings;
|
|
2238
|
+
}
|
|
2239
|
+
/**
|
|
2240
|
+
* Writes one `key:value` of a set into a copy of a layer. `var('name')` writes the variable's value and binds the
|
|
2241
|
+
* property; a value written over a bound field drops that binding.
|
|
2242
|
+
*/
|
|
2243
|
+
function write(node, key, value, where, context) {
|
|
2244
|
+
const { theme } = context.document;
|
|
2245
|
+
const before = clone(node);
|
|
2246
|
+
const bound = new Map();
|
|
2247
|
+
try {
|
|
2248
|
+
const plain = readVariables(theme, key, value, String(node.type), bound);
|
|
2249
|
+
writeValue(node, key, plain, where, context);
|
|
2250
|
+
dropOverwrittenBindings(before, node, new Set(bound.keys()), context);
|
|
2251
|
+
if (bound.size > 0)
|
|
2252
|
+
Object.assign(node, withBoundVariables(theme, node, bound));
|
|
2253
|
+
}
|
|
2254
|
+
catch (error) {
|
|
2255
|
+
if (error instanceof VariableReferenceError)
|
|
2256
|
+
throw new LayerSyntaxError(`${where}: ${error.message}`);
|
|
2257
|
+
throw error;
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
/**
|
|
2261
|
+
* The writes of a set on a path in the order build applies them, whatever order they are written in: `d` first, as it
|
|
2262
|
+
* draws the points again, then `w` and `h`, which scale those points, then `x` and `y`, which move them. The other writes
|
|
2263
|
+
* keep their order.
|
|
2264
|
+
*/
|
|
2265
|
+
function inPathOrder(writes) {
|
|
2266
|
+
const rank = (key) => key === "d" ? 0 : key === "w" || key === "h" ? 1 : key === "x" || key === "y" ? 2 : 0;
|
|
2267
|
+
return [...writes].sort((left, right) => rank(left.key) - rank(right.key));
|
|
2268
|
+
}
|
|
2269
|
+
/** Writes one plain `key:value` of a set into a copy of a layer. */
|
|
2270
|
+
function writeValue(node, key, value, where, context) {
|
|
2271
|
+
const component = componentOfInstance(node, context);
|
|
2272
|
+
if (component !== undefined && writeInstance(node, component, key, value, where, context))
|
|
2273
|
+
return;
|
|
2274
|
+
const shorthand = shorthandNamed(headsOf(node)[0]);
|
|
2275
|
+
const shortNames = shortNamesOf(shorthand);
|
|
2276
|
+
const modelFields = modelFieldsOf(shorthand);
|
|
2277
|
+
const frame = isRecord(node.frame) ? { ...node.frame } : undefined;
|
|
2278
|
+
if (key === "id")
|
|
2279
|
+
throw new LayerSyntaxError(`${where}: the id of a layer cannot change.`);
|
|
2280
|
+
if (shortNames.includes(key)) {
|
|
2281
|
+
if (key === "name" || key === "opacity") {
|
|
2282
|
+
node[key] = value;
|
|
2283
|
+
return;
|
|
2284
|
+
}
|
|
2285
|
+
// d draws a path's points again where its transform puts them; x, y, w and h move and scale them as build does.
|
|
2286
|
+
if (shorthand.name === "path" && (key === "d" || key === "x" || key === "y" || key === "w" || key === "h")) {
|
|
2287
|
+
try {
|
|
2288
|
+
Object.assign(node, key === "d" ? { vectorNetwork: pathNetworkOf(value) }
|
|
2289
|
+
: placedPath(node.vectorNetwork, node.transform, { [key]: value }));
|
|
2290
|
+
}
|
|
2291
|
+
catch (error) {
|
|
2292
|
+
if (error instanceof ShortArgumentError)
|
|
2293
|
+
throw new LayerSyntaxError(`${where}: ${error.message}`);
|
|
2294
|
+
throw error;
|
|
2295
|
+
}
|
|
2296
|
+
return;
|
|
2297
|
+
}
|
|
2298
|
+
if (key === "x" || key === "y") {
|
|
2299
|
+
if (frame === undefined)
|
|
2300
|
+
throw new LayerSyntaxError(`${where} has no frame, so it takes no ${key}.`);
|
|
2301
|
+
node.frame = { ...frame, [key]: value };
|
|
2302
|
+
return;
|
|
2303
|
+
}
|
|
2304
|
+
if (key === "w" || key === "h") {
|
|
2305
|
+
writeSize(node, shorthand, key, value, where, context);
|
|
2306
|
+
return;
|
|
2307
|
+
}
|
|
2308
|
+
if (key === shorthand.content) {
|
|
2309
|
+
if (shorthand.name === "code") {
|
|
2310
|
+
node.source = value;
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
if (singleRun(node) === undefined) {
|
|
2314
|
+
throw new LayerSyntaxError(`${where} has more than one paragraph or run, so text cannot write all of it; write paragraphs:(...) as the model stores them.`);
|
|
2315
|
+
}
|
|
2316
|
+
const paragraph = node.paragraphs[0];
|
|
2317
|
+
node.paragraphs = [{ ...paragraph, runs: [{ ...paragraph.runs[0], text: value }] }];
|
|
2318
|
+
return;
|
|
2319
|
+
}
|
|
2320
|
+
try {
|
|
2321
|
+
shorthand.short[key](node, value);
|
|
2322
|
+
}
|
|
2323
|
+
catch (error) {
|
|
2324
|
+
if (error instanceof ShortArgumentError)
|
|
2325
|
+
throw new LayerSyntaxError(`${where}: ${error.message}`);
|
|
2326
|
+
throw error;
|
|
2327
|
+
}
|
|
2328
|
+
return;
|
|
2329
|
+
}
|
|
2330
|
+
if (modelFields.includes(key)) {
|
|
2331
|
+
node[key] = merged(node[key], key === "style" ? resolveLinearCalls(value, node) : value);
|
|
2332
|
+
return;
|
|
2333
|
+
}
|
|
2334
|
+
throw new LayerSyntaxError(`${where}: ${shorthand.name} has no field ${key}. It takes ${[...shortNames, ...modelFields.filter((name) => !shortNames.includes(name))].join(", ")}.`);
|
|
2335
|
+
}
|
|
2336
|
+
/** Writes `w` or `h` as the builder reads them: a number fixes the size, fill fills the auto layout parent, hug fits the content. */
|
|
2337
|
+
function writeSize(node, shorthand, key, value, where, context) {
|
|
2338
|
+
const axis = key === "w" ? "width" : "height";
|
|
2339
|
+
const sizingField = key === "w" ? "widthSizing" : "heightSizing";
|
|
2340
|
+
const frame = { ...node.frame };
|
|
2341
|
+
const isFlex = isAutoLayoutFrame(node);
|
|
2342
|
+
const resizing = isRecord(node.resizing) ? { ...node.resizing } : {};
|
|
2343
|
+
if (value === "hug") {
|
|
2344
|
+
if (isFlex)
|
|
2345
|
+
node.layout = { ...node.layout, [sizingField]: "hug" };
|
|
2346
|
+
// h:hug on a text that already hugs both ways keeps its width hugging: only the height is named.
|
|
2347
|
+
else if (node.type === "text" || node.type === "code")
|
|
2348
|
+
node.autoResize = key === "w" || node.autoResize === "width-and-height" ? "width-and-height" : "height";
|
|
2349
|
+
else
|
|
2350
|
+
throw new LayerSyntaxError(`${where}: a ${shorthand.name} cannot hug its content; give ${key} a number or fill.`);
|
|
2351
|
+
delete resizing[axis];
|
|
2352
|
+
}
|
|
2353
|
+
else if (value === "fill") {
|
|
2354
|
+
resizing[axis] = "fill";
|
|
2355
|
+
if (isFlex)
|
|
2356
|
+
node.layout = { ...node.layout, [sizingField]: "fixed" };
|
|
2357
|
+
}
|
|
2358
|
+
else {
|
|
2359
|
+
node.frame = { ...frame, [axis]: value };
|
|
2360
|
+
delete resizing[axis];
|
|
2361
|
+
if (isFlex)
|
|
2362
|
+
node.layout = { ...node.layout, [sizingField]: "fixed" };
|
|
2363
|
+
// An instance whose component root hugs keeps a number only as Fixed, its override of the root's sizing.
|
|
2364
|
+
if (node.type === "instance") {
|
|
2365
|
+
const { overrides } = withAxisSizing(context.document, node, axis, "fixed");
|
|
2366
|
+
if (overrides === undefined)
|
|
2367
|
+
delete node.overrides;
|
|
2368
|
+
else
|
|
2369
|
+
node.overrides = overrides;
|
|
2370
|
+
}
|
|
2371
|
+
}
|
|
2372
|
+
if (value !== "hug" && (node.type === "text" || node.type === "code")) {
|
|
2373
|
+
if (key === "w" && node.autoResize === "width-and-height") {
|
|
2374
|
+
node.autoResize = "height";
|
|
2375
|
+
if (node.type === "text")
|
|
2376
|
+
node.wrap = "word";
|
|
2377
|
+
}
|
|
2378
|
+
if (key === "h")
|
|
2379
|
+
node.autoResize = "none";
|
|
2380
|
+
}
|
|
2381
|
+
if (Object.keys(resizing).length === 0)
|
|
2382
|
+
delete node.resizing;
|
|
2383
|
+
else
|
|
2384
|
+
node.resizing = resizing;
|
|
2385
|
+
}
|
|
2386
|
+
/**
|
|
2387
|
+
* Writes what only an instance of a known component takes: a prop by name, `props:{...}`, and `over:{...}`, whose
|
|
2388
|
+
* overrides merge into those stored as `node.patch` merges. False for any other key, which every instance takes.
|
|
2389
|
+
*/
|
|
2390
|
+
function writeInstance(node, component, key, value, where, context) {
|
|
2391
|
+
const properties = (component.properties ?? []).filter(isValuedComponentProperty);
|
|
2392
|
+
const writeProperty = (property, item) => {
|
|
2393
|
+
try {
|
|
2394
|
+
node.propertyValues = { ...(isRecord(node.propertyValues) ? node.propertyValues : {}),
|
|
2395
|
+
[property.id]: propertyValueFromSyntax(component, property, item, context.names) };
|
|
2396
|
+
}
|
|
2397
|
+
catch (error) {
|
|
2398
|
+
componentRefusal(error, where);
|
|
2399
|
+
}
|
|
2400
|
+
};
|
|
2401
|
+
if (key === INSTANCE_OVER_ARGUMENT) {
|
|
2402
|
+
let overrides;
|
|
2403
|
+
try {
|
|
2404
|
+
overrides = overridesFromSyntax(context.document, component, value, context.names);
|
|
2405
|
+
}
|
|
2406
|
+
catch (error) {
|
|
2407
|
+
return componentRefusal(error, where);
|
|
2408
|
+
}
|
|
2409
|
+
node.overrides = merged(node.overrides, overrides);
|
|
2410
|
+
return true;
|
|
2411
|
+
}
|
|
2412
|
+
if (key === INSTANCE_PROPS_ARGUMENT) {
|
|
2413
|
+
if (!isRecord(value))
|
|
2414
|
+
throw new LayerSyntaxError(`${where}: props takes props by name, as props:{name:'Ada'}.`);
|
|
2415
|
+
for (const [name, item] of Object.entries(value)) {
|
|
2416
|
+
const property = properties.find((candidate) => candidate.name === name);
|
|
2417
|
+
if (property === undefined)
|
|
2418
|
+
throw new LayerSyntaxError(`${where}: ${headOf(node, context)} has no prop ${name}; ${componentPropertyList(component, context.names)}.`);
|
|
2419
|
+
writeProperty(property, item);
|
|
2420
|
+
}
|
|
2421
|
+
return true;
|
|
2422
|
+
}
|
|
2423
|
+
const property = properties.find((candidate) => candidate.name === key && !propertyInProps(candidate));
|
|
2424
|
+
if (property !== undefined) {
|
|
2425
|
+
writeProperty(property, value);
|
|
2426
|
+
return true;
|
|
2427
|
+
}
|
|
2428
|
+
if (key === "w" || key === "h" || key === "x" || key === "y" || key === "id" || key === "name" || key === "opacity"
|
|
2429
|
+
|| modelFieldsOf(shorthandNamed("instance")).includes(key))
|
|
2430
|
+
return false;
|
|
2431
|
+
throw new LayerSyntaxError(`${where}: ${headOf(node, context)} has no field or prop ${key}; ${componentPropertyList(component, context.names)}; `
|
|
2432
|
+
+ `it also takes id, name, x, y, w, h, opacity, over:{<layer name>:{...}} and its model fields by name.`);
|
|
2433
|
+
}
|
|
2434
|
+
/**
|
|
2435
|
+
* Removes one `-key` of a set from a copy of a layer, and the bindings of the properties whose fields it removes: each
|
|
2436
|
+
* is dropped because its field is gone, whatever value the layer is left with (a layer with no stroke left would
|
|
2437
|
+
* still count as holding a stroke colour, as writing one changes nothing there).
|
|
2438
|
+
*/
|
|
2439
|
+
function remove(node, key, where, context) {
|
|
2440
|
+
const properties = removeValue(node, key, where, context);
|
|
2441
|
+
if (properties.length === 0 || !isRecord(node.variableBindings))
|
|
2442
|
+
return;
|
|
2443
|
+
const bindings = { ...node.variableBindings };
|
|
2444
|
+
for (const property of properties)
|
|
2445
|
+
delete bindings[property];
|
|
2446
|
+
if (Object.keys(bindings).length === 0)
|
|
2447
|
+
delete node.variableBindings;
|
|
2448
|
+
else
|
|
2449
|
+
node.variableBindings = bindings;
|
|
2450
|
+
}
|
|
2451
|
+
/** The bindable properties whose fields removing a model field of that name removes, beyond those of a short argument. */
|
|
2452
|
+
const REMOVED_FIELD_PROPERTIES = {
|
|
2453
|
+
stroke: ["strokeColor", "strokeWidth"],
|
|
2454
|
+
style: ["fillColor", "strokeColor", "strokeWidth", "cornerRadius"],
|
|
2455
|
+
layout: ["gap", "wrapGap", "columnGap", "rowGap", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft"],
|
|
2456
|
+
visible: ["visibility"],
|
|
2457
|
+
codeStyleOverrides: ["lineHeight", "letterSpacing"],
|
|
2458
|
+
};
|
|
2459
|
+
/** The bindable properties whose fields `-key` removes from a layer of `kind`: those its argument binds, and those of the field. */
|
|
2460
|
+
function propertiesRemovedWith(kind, key) {
|
|
2461
|
+
return [...new Set([...variableArgumentProperties(kind, key) ?? [], ...Object.hasOwn(REMOVED_FIELD_PROPERTIES, key) ? REMOVED_FIELD_PROPERTIES[key] : []])];
|
|
2462
|
+
}
|
|
2463
|
+
/** Removes `-key` from a copy of a layer; answers the bindable properties whose fields it removed. */
|
|
2464
|
+
function removeValue(node, key, where, context) {
|
|
2465
|
+
const component = componentOfInstance(node, context);
|
|
2466
|
+
if (component !== undefined) {
|
|
2467
|
+
const property = component.properties?.find((candidate) => candidate.name === key && isValuedComponentProperty(candidate) && !propertyInProps(candidate));
|
|
2468
|
+
// -size gives the prop back its default, -props every prop, -over every override.
|
|
2469
|
+
if (property !== undefined) {
|
|
2470
|
+
removePropertyValue(node, property.id);
|
|
2471
|
+
return [];
|
|
2472
|
+
}
|
|
2473
|
+
if (key === INSTANCE_PROPS_ARGUMENT) {
|
|
2474
|
+
delete node.propertyValues;
|
|
2475
|
+
return [];
|
|
2476
|
+
}
|
|
2477
|
+
if (key === INSTANCE_OVER_ARGUMENT) {
|
|
2478
|
+
delete node.overrides;
|
|
2479
|
+
return [];
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
const shorthand = shorthandNamed(headsOf(node)[0]);
|
|
2483
|
+
if (["id", "name", "x", "y", "w", "h"].includes(key) || key === shorthand.content) {
|
|
2484
|
+
throw new LayerSyntaxError(`${where}: ${key} cannot be removed; write ${key}:<value> instead.`);
|
|
2485
|
+
}
|
|
2486
|
+
const removed = propertiesRemovedWith(String(node.type), key);
|
|
2487
|
+
const reader = readersOf(shorthand)[key];
|
|
2488
|
+
if (reader !== undefined) {
|
|
2489
|
+
reader.remove(node);
|
|
2490
|
+
return removed;
|
|
2491
|
+
}
|
|
2492
|
+
// Every layer holds an opacity: removing it gives back the 1 a new layer starts with.
|
|
2493
|
+
if (key === "opacity") {
|
|
2494
|
+
node.opacity = 1;
|
|
2495
|
+
return removed;
|
|
2496
|
+
}
|
|
2497
|
+
if (modelFieldsOf(shorthand).includes(key)) {
|
|
2498
|
+
delete node[key];
|
|
2499
|
+
return removed;
|
|
2500
|
+
}
|
|
2501
|
+
throw new LayerSyntaxError(`${where}: ${shorthand.name} has no field ${key} to remove.`);
|
|
2502
|
+
}
|
|
2503
|
+
/**
|
|
2504
|
+
* The kind of layer a matcher's head names: a shorthand (`instance` for every instance), or a component, whose instances
|
|
2505
|
+
* it matches; undefined for `*`, and for a head that names nothing, which matches no layer. A head that names several
|
|
2506
|
+
* components is refused listing their call names.
|
|
2507
|
+
*/
|
|
2508
|
+
function matcherKind(step, text, context) {
|
|
2509
|
+
if (step.head === undefined)
|
|
2510
|
+
return undefined;
|
|
2511
|
+
try {
|
|
2512
|
+
return context.names.resolve(step.head) ?? { kind: "shorthand", shorthand: { name: step.head } };
|
|
2513
|
+
}
|
|
2514
|
+
catch (error) {
|
|
2515
|
+
return componentRefusal(error, text);
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
/** Whether a layer is of the kind a step names. */
|
|
2519
|
+
const ofMatcherKind = (node, kind) => kind === undefined
|
|
2520
|
+
|| (kind.kind === "component" ? node.type === "instance" && node.componentId === kind.component.id
|
|
2521
|
+
: kind.shorthand.name === "instance" ? node.type === "instance"
|
|
2522
|
+
: headsOf(node)[0] === kind.shorthand.name || (kind.shorthand.name === "frame" && node.type === "frame"));
|
|
2523
|
+
/** Whether a layer holds every filter of a step, each compared with the printed value. */
|
|
2524
|
+
const holdsFilters = (node, step, context, componentOf) => step.filters.every(({ key, value }) => {
|
|
2525
|
+
const held = filterValue(node, key, context);
|
|
2526
|
+
// A slot frame matches its slot's name in its own component, as read prints it, as well as the slot's id.
|
|
2527
|
+
if (key === "slot" && node.type === "frame" && typeof held === "string" && typeof value === "string" && value !== held) {
|
|
2528
|
+
const component = componentOf(String(node.id));
|
|
2529
|
+
return component !== undefined && slotPropertiesOf(component).some((property) => property.id === held && property.name === value);
|
|
2530
|
+
}
|
|
2531
|
+
return held !== undefined && comparable(held) === comparable(value);
|
|
2532
|
+
});
|
|
2533
|
+
/** What works today in place of changing the slots of an instance inside an instance, or of a layer with none, in an edit. */
|
|
2534
|
+
const SLOTS_IN_EDIT = "only an instance has slots: set #<instance id> { slots:{Name:( ... )} } changes its own, "
|
|
2535
|
+
+ "and set #<instance id> { over:{Layer:{slots:{Name:( ... )}}} } those of an instance inside it.";
|
|
2536
|
+
/** How many layers deep a parent chain may go before the plan stops, as a document cannot be. */
|
|
2537
|
+
const PARENT_CHAIN_LIMIT = 100_000;
|
|
2538
|
+
/** What a prop's default may be, for a refusal. */
|
|
2539
|
+
/** How prop and option names are written, for a refusal. */
|
|
2540
|
+
const PROP_NAMES = "Any other name can name a prop or an option: here a name that is not a word goes in quotes, as "
|
|
2541
|
+
+ "'Primary / Hover':false or Size:('大', '小'), and an expression writes a name bare when it is a Unicode identifier (size == .大) "
|
|
2542
|
+
+ "and otherwise in backticks (`Primary / Hover` == .`On`, state == .`2x`, `if` for a name spelled like a keyword).";
|
|
2543
|
+
const PROP_DEFAULTS = "A prop's default is true or false (a boolean prop), a string in quotes (a text prop) or its options in parentheses, "
|
|
2544
|
+
+ "the default first (an enum prop), as Size:(small, large); a prop the component has takes an option's name, as Size:large.";
|
|
2545
|
+
/**
|
|
2546
|
+
* The properties `component` has after a prop rule's `writes` and `removes`: a write of a prop it has keeps the prop's id
|
|
2547
|
+
* and its other settings when the kind stays (an enum's options keep their ids by name), and a new prop goes last, with an
|
|
2548
|
+
* id from its name. Names are compared and stored in NFC. Refuses a name no prop or option can have (empty, over 256
|
|
2549
|
+
* characters, or holding a control, line break or bidirectional formatting character), a value that is no default and a
|
|
2550
|
+
* removal of a prop the component does not have, naming the props.
|
|
2551
|
+
*/
|
|
2552
|
+
function propertiesAfter(component, writes, removes, where, names) {
|
|
2553
|
+
const properties = [...(component.properties ?? [])];
|
|
2554
|
+
const listed = () => componentPropertyList({ ...component, properties }, names);
|
|
2555
|
+
// A name as the syntax reads it back: a word as it is, any other in quotes.
|
|
2556
|
+
const written = (name) => KEY.test(name) && !RESERVED_WORDS.has(name) ? name : name.includes("\\") ? JSON.stringify(name) : printLayerValue(name);
|
|
2557
|
+
for (const removed of removes) {
|
|
2558
|
+
const name = normalizeExpressionName(removed);
|
|
2559
|
+
const index = properties.findIndex((property) => property.name === name);
|
|
2560
|
+
if (index < 0)
|
|
2561
|
+
throw new LayerSyntaxError(`${where}: there is no prop ${name} to remove; ${listed()}.`);
|
|
2562
|
+
properties.splice(index, 1);
|
|
2563
|
+
}
|
|
2564
|
+
const freshId = (taken, base) => {
|
|
2565
|
+
for (let count = 1;; count += 1) {
|
|
2566
|
+
const id = count === 1 ? base : `${base}-${count}`;
|
|
2567
|
+
if (!taken.some((entry) => entry.id === id))
|
|
2568
|
+
return id;
|
|
2569
|
+
}
|
|
2570
|
+
};
|
|
2571
|
+
for (const { key: writtenKey, value, word } of writes) {
|
|
2572
|
+
const problem = expressionNameProblem(writtenKey);
|
|
2573
|
+
if (problem !== undefined) {
|
|
2574
|
+
throw new LayerSyntaxError(`${where}: ${written(writtenKey)} cannot name a prop: ${problem}. ${PROP_NAMES}`);
|
|
2575
|
+
}
|
|
2576
|
+
const key = normalizeExpressionName(writtenKey);
|
|
2577
|
+
const index = properties.findIndex((property) => property.name === key);
|
|
2578
|
+
const existing = index < 0 ? undefined : properties[index];
|
|
2579
|
+
const base = { id: existing?.id ?? componentPropertyId(freshId(properties, `prop-${key}`)), name: key,
|
|
2580
|
+
...(existing?.description === undefined ? {} : { description: existing.description }) };
|
|
2581
|
+
let next;
|
|
2582
|
+
// A string in quotes that names an option of an enum prop picks it, as a word does: an option whose name is not a word is written so.
|
|
2583
|
+
const quotedOption = typeof value === "string" && !word && existing?.kind === "enum"
|
|
2584
|
+
&& existing.options.some((candidate) => candidate.name === normalizeExpressionName(value));
|
|
2585
|
+
if (typeof value === "boolean")
|
|
2586
|
+
next = existing?.kind === "boolean" ? { ...existing, defaultValue: value } : { ...base, kind: "boolean", defaultValue: value };
|
|
2587
|
+
else if (typeof value === "string" && !word && !quotedOption)
|
|
2588
|
+
next = existing?.kind === "text" ? { ...existing, defaultValue: value } : { ...base, kind: "text", defaultValue: value };
|
|
2589
|
+
else if (typeof value === "string" && existing?.kind === "enum") {
|
|
2590
|
+
const wanted = normalizeExpressionName(value);
|
|
2591
|
+
const option = existing.options.find((candidate) => candidate.name === wanted);
|
|
2592
|
+
if (option === undefined) {
|
|
2593
|
+
const optionNames = existing.options.map((candidate) => written(candidate.name));
|
|
2594
|
+
throw new LayerSyntaxError(`${where}: ${written(key)} is one of ${optionNames.join(", ")}; write ${written(key)}:${optionNames[0]}, `
|
|
2595
|
+
+ `or list the options again, the default first: ${written(key)}:(${[written(wanted), ...optionNames].join(", ")}).`);
|
|
2596
|
+
}
|
|
2597
|
+
next = { ...existing, defaultValue: option.id };
|
|
2598
|
+
}
|
|
2599
|
+
else if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string")) {
|
|
2600
|
+
const bad = value.find((name) => expressionNameProblem(name) !== undefined);
|
|
2601
|
+
if (bad !== undefined) {
|
|
2602
|
+
throw new LayerSyntaxError(`${where}: ${written(bad)} cannot name an option of ${written(key)}: ${expressionNameProblem(bad)}. ${PROP_NAMES}`);
|
|
2603
|
+
}
|
|
2604
|
+
const optionNames = value.map(normalizeExpressionName);
|
|
2605
|
+
const twice = optionNames.find((name, index) => optionNames.indexOf(name) !== index);
|
|
2606
|
+
if (twice !== undefined)
|
|
2607
|
+
throw new LayerSyntaxError(`${where}: ${written(key)} lists the option ${written(twice)} twice.`);
|
|
2608
|
+
const kept = existing?.kind === "enum" ? existing.options : [];
|
|
2609
|
+
const options = [];
|
|
2610
|
+
for (const name of optionNames)
|
|
2611
|
+
options.push({ id: kept.find((option) => option.name === name)?.id ?? freshId([...kept, ...options], `option-${name}`), name });
|
|
2612
|
+
next = existing?.kind === "enum" ? { ...existing, options, defaultValue: options[0].id } : { ...base, kind: "enum", options, defaultValue: options[0].id };
|
|
2613
|
+
}
|
|
2614
|
+
else {
|
|
2615
|
+
const shown = typeof value === "string" ? value : printLayerValue(value, "a value");
|
|
2616
|
+
throw new LayerSyntaxError(`${where}: ${key}:${shown} is no default for a prop${word ? ` (a word; a text's default is in quotes, ${key}:'${shown}')` : ""}. ${PROP_DEFAULTS}`);
|
|
2617
|
+
}
|
|
2618
|
+
if (index < 0)
|
|
2619
|
+
properties.push(next);
|
|
2620
|
+
else
|
|
2621
|
+
properties[index] = next;
|
|
2622
|
+
}
|
|
2623
|
+
return properties;
|
|
2624
|
+
}
|
|
2625
|
+
/**
|
|
2626
|
+
* The operations of edit rules in a scope, separated by `;`, `,` or line breaks:
|
|
2627
|
+
* - `set <layer> { k:v, -k }` writes fields: each write goes through the writer of its short argument, or is merged
|
|
2628
|
+
* into the model field of that name as `node.patch` merges; what is not written is kept, and `-key` removes.
|
|
2629
|
+
* - `add <parent> [at:<index>] [<layers>]`, `add before:<layer> [<layers>]` and `add after:<layer> [<layers>]` put new
|
|
2630
|
+
* layers inside a layer (on top without at:) or next to one, as a `node.build` the editor reads.
|
|
2631
|
+
* - `move <layer> before:<layer>`, `after:<layer>`, `in:<parent> [at:<index>]` or `at:<index>` is a `node.move`.
|
|
2632
|
+
* - `remove <layer>` is a `node.remove`; `replace <layer> [<layers>]` a `node.remove` and a `node.build` in its place.
|
|
2633
|
+
* - `outline <layer>` (or `outline all <layer>`) is a `node.outlineStroke` of the layers, which must come before every other
|
|
2634
|
+
* rule (outline rules one after another make one); later rules cannot match the layers or the layers inside them.
|
|
2635
|
+
* - `union #a #b ...` (or `subtract`, `intersect`, `exclude`) is a `node.boolean` of the layers, which must be the first rule
|
|
2636
|
+
* and the only Boolean one; later rules cannot match the layers.
|
|
2637
|
+
* - `convert <frame> to component(name:'<name>') [replace #<copy> ...]` is a `component.convert`: the frame becomes a
|
|
2638
|
+
* component's root and the editor puts an instance of it in its place, and in the place of each copy; later rules of the
|
|
2639
|
+
* same edit cannot match the frame, the copies or the layers inside them. The frame may be one an earlier rule adds.
|
|
2640
|
+
* A matcher is `#id`, or a kind of layer as the printer names it (`*` for any) with filters compared with the printed
|
|
2641
|
+
* values (`text(size:12)`); it must match exactly one layer, or one or more after `all` (set, add, remove, replace).
|
|
2642
|
+
* Rules apply in order to a working copy; a later rule cannot match a layer an earlier one adds. The sets between two
|
|
2643
|
+
* rules that change layers inside layers become one `node.patch` per layer, or a `node.replace` where a field inside an
|
|
2644
|
+
* object is removed. Throws a LayerSyntaxError for a text it cannot read, an empty or ambiguous match (listing the
|
|
2645
|
+
* layers and the right form), a field the layer does not take and a place that cannot be.
|
|
2646
|
+
*/
|
|
2647
|
+
export function planLayerEdit(text, scope) {
|
|
2648
|
+
const rules = readRules(text);
|
|
2649
|
+
// A prop rule changes a component's props for the rules after it: their sets and matchers read the new ones.
|
|
2650
|
+
let context = syntaxContext(scope.components, scope.variables);
|
|
2651
|
+
const working = new Map();
|
|
2652
|
+
const current = (id) => working.get(id) ?? scope.node(id);
|
|
2653
|
+
// The layers in scope in document order, and the parent of each but the roots.
|
|
2654
|
+
const inScope = [];
|
|
2655
|
+
const parentOf = new Map();
|
|
2656
|
+
const childrenOf = (id) => {
|
|
2657
|
+
const children = current(id)?.children;
|
|
2658
|
+
return Array.isArray(children) ? children : undefined;
|
|
2659
|
+
};
|
|
2660
|
+
const seen = new Set();
|
|
2661
|
+
const walk = (id) => {
|
|
2662
|
+
if (seen.has(id))
|
|
2663
|
+
return;
|
|
2664
|
+
seen.add(id);
|
|
2665
|
+
if (current(id) === undefined)
|
|
2666
|
+
return;
|
|
2667
|
+
inScope.push(id);
|
|
2668
|
+
for (const child of childrenOf(id) ?? []) {
|
|
2669
|
+
if (seen.size > 100_000)
|
|
2670
|
+
throw new LayerSyntaxError("The scope holds more than 100000 layers; edit inside one frame with in #<frame>.");
|
|
2671
|
+
if (current(child) !== undefined)
|
|
2672
|
+
parentOf.set(child, id);
|
|
2673
|
+
walk(child);
|
|
2674
|
+
}
|
|
2675
|
+
};
|
|
2676
|
+
scope.roots.forEach(walk);
|
|
2677
|
+
const removed = new Set(), given = new Set(), addedTo = new Set(), attached = new Set();
|
|
2678
|
+
const attachments = [];
|
|
2679
|
+
const addedLayers = new Map();
|
|
2680
|
+
// The ends `set` rules attach, by connector and end: a later rule that writes the same end again replaces it.
|
|
2681
|
+
const setEnds = new Map();
|
|
2682
|
+
const operations = [];
|
|
2683
|
+
const outlined = new Set();
|
|
2684
|
+
const combined = new Set();
|
|
2685
|
+
const buildPlaces = [];
|
|
2686
|
+
const props = new Map();
|
|
2687
|
+
const converted = new Set();
|
|
2688
|
+
const changed = [], moved = [], removedLayers = [], touched = new Set();
|
|
2689
|
+
const setOn = [];
|
|
2690
|
+
let pending = new Map(), placeholders = 0;
|
|
2691
|
+
/** Refuses `#id`, a step of a matcher that names no layer in the scope now, saying why. */
|
|
2692
|
+
const missingId = (id, layers) => {
|
|
2693
|
+
if (outlined.has(id)) {
|
|
2694
|
+
throw new LayerSyntaxError(`#${id} is outlined by an earlier rule of this edit, which makes new layers of it. Send that rule in a call after this one.`);
|
|
2695
|
+
}
|
|
2696
|
+
if (combined.has(id)) {
|
|
2697
|
+
throw new LayerSyntaxError(`#${id} is combined by an earlier rule of this edit, which makes a new path of it. Send that rule in a call after this one.`);
|
|
2698
|
+
}
|
|
2699
|
+
if (converted.has(id)) {
|
|
2700
|
+
throw new LayerSyntaxError(`#${id} becomes a component by an earlier rule of this edit, so it is no longer in ${scope.shown}. Send that rule in a call after this one.`);
|
|
2701
|
+
}
|
|
2702
|
+
if (given.has(id)) {
|
|
2703
|
+
throw new LayerSyntaxError(`#${id} is a layer this edit adds, and a rule other than convert cannot match a layer added in the same call. Send that rule in a call after this one.`);
|
|
2704
|
+
}
|
|
2705
|
+
if (removed.has(id))
|
|
2706
|
+
throw new LayerSyntaxError(`#${id} is removed by an earlier rule of this edit.`);
|
|
2707
|
+
const closest = closestId(id, layers.map((node) => String(node.id)));
|
|
2708
|
+
throw new LayerSyntaxError(`There is no layer #${id} in ${scope.shown}${closest === undefined ? "" : `; the closest id there is #${closest}`}. `
|
|
2709
|
+
+ "Read the layers to find their ids.", id);
|
|
2710
|
+
};
|
|
2711
|
+
/** The layers `matcher` matches now; an empty match, and several where one is needed, are refused with `forms`. */
|
|
2712
|
+
const find = (matcher, forms) => {
|
|
2713
|
+
const layers = inScope.filter((id) => !removed.has(id)).map((id) => current(id));
|
|
2714
|
+
for (const id of [matcher.id, ...matcher.within.map(({ step }) => step.id)]) {
|
|
2715
|
+
if (id !== undefined && !layers.some((node) => node.id === id))
|
|
2716
|
+
missingId(id, layers);
|
|
2717
|
+
}
|
|
2718
|
+
if (matcher.id !== undefined)
|
|
2719
|
+
return layers.filter((node) => node.id === matcher.id);
|
|
2720
|
+
const kind = matcherKind(matcher, matcher.text, context);
|
|
2721
|
+
const ofKind = layers.filter((node) => ofMatcherKind(node, kind));
|
|
2722
|
+
const holding = ofKind.filter((node) => holdsFilters(node, matcher, context, componentAround));
|
|
2723
|
+
// The steps before the last, from the inside out: a layer of step i + 1 is directly inside one of step i after >,
|
|
2724
|
+
// and at any depth inside one after a space.
|
|
2725
|
+
const kinds = matcher.within.map(({ step }) => matcherKind(step, matcher.text, context));
|
|
2726
|
+
const known = new Map();
|
|
2727
|
+
const placed = (id, index) => {
|
|
2728
|
+
const { step, child } = matcher.within[index];
|
|
2729
|
+
const remembered = known.get(`${index}\u0000${id}`);
|
|
2730
|
+
if (remembered !== undefined)
|
|
2731
|
+
return remembered;
|
|
2732
|
+
let found = false, steps = 0;
|
|
2733
|
+
for (let at = parentOf.get(id); at !== undefined && !found; at = child ? undefined : parentOf.get(at)) {
|
|
2734
|
+
if (++steps > PARENT_CHAIN_LIMIT)
|
|
2735
|
+
throw new LayerSyntaxError(`The layers above #${id} go on past ${PARENT_CHAIN_LIMIT}; the document is broken.`);
|
|
2736
|
+
const node = current(at);
|
|
2737
|
+
found = (step.id !== undefined ? node.id === step.id : ofMatcherKind(node, kinds[index]) && holdsFilters(node, step, context, componentAround))
|
|
2738
|
+
&& (index === 0 || placed(at, index - 1));
|
|
2739
|
+
}
|
|
2740
|
+
known.set(`${index}\u0000${id}`, found);
|
|
2741
|
+
return found;
|
|
2742
|
+
};
|
|
2743
|
+
const matches = matcher.within.length === 0 ? holding : holding.filter((node) => placed(String(node.id), matcher.within.length - 1));
|
|
2744
|
+
if (matches.length === 0) {
|
|
2745
|
+
const write = ` Write ${forms.one("#<id>")} with one of their ids, or filters they hold.`;
|
|
2746
|
+
if (holding.length > 0) {
|
|
2747
|
+
// Layers of the kind are there, but not where the steps before put them.
|
|
2748
|
+
const shown = holding.slice(0, LIST_LIMIT).map((node) => listed(node, context));
|
|
2749
|
+
const more = holding.length > LIST_LIMIT ? `, and ${holding.length - LIST_LIMIT} more` : "";
|
|
2750
|
+
const where = `${matcher.within.at(-1).child ? "directly " : ""}inside ${matcher.withinText}`;
|
|
2751
|
+
const first = matcher.within[0].step.id;
|
|
2752
|
+
// #title text(name:'Title') copied from a list of layers names #title itself, not a text inside it.
|
|
2753
|
+
const itself = matcher.within.length === 1 && first !== undefined && holding.some((node) => node.id === first)
|
|
2754
|
+
? ` #${first} itself matches ${matcher.lastText}: a space or > between two steps means inside, so write #${first} alone.` : "";
|
|
2755
|
+
throw new LayerSyntaxError(`No layer in ${scope.shown} matches ${matcher.text}. Layers there that the last step matches, none of them ${where}: `
|
|
2756
|
+
+ `${shown.join(", ")}${more}.${itself}${write}`);
|
|
2757
|
+
}
|
|
2758
|
+
const shown = ofKind.slice(0, LIST_LIMIT).map((node) => listed(node, context));
|
|
2759
|
+
const more = ofKind.length > LIST_LIMIT ? `, and ${ofKind.length - LIST_LIMIT} more` : "";
|
|
2760
|
+
throw new LayerSyntaxError(`No layer in ${scope.shown} matches ${matcher.text}. `
|
|
2761
|
+
+ (shown.length === 0 ? `There is no ${matcher.head ?? "layer"} there.` : `Layers of that kind there: ${shown.join(", ")}${more}.`) + write);
|
|
2762
|
+
}
|
|
2763
|
+
if (matches.length > 1 && !matcher.all) {
|
|
2764
|
+
const ids = matches.slice(0, LIST_LIMIT).map((node) => `#${String(node.id)}`);
|
|
2765
|
+
const more = matches.length > LIST_LIMIT ? `, and ${matches.length - LIST_LIMIT} more` : "";
|
|
2766
|
+
throw new LayerSyntaxError(`${matches.length} layers match ${matcher.text}: ${ids.join(", ")}${more}. `
|
|
2767
|
+
+ `Write one of them (${forms.one(ids[0])})${forms.all === undefined ? "" : ` or all of them (${forms.all(matcher.text)})`}.`);
|
|
2768
|
+
}
|
|
2769
|
+
return matches;
|
|
2770
|
+
};
|
|
2771
|
+
const findOne = (matcher, forms) => String(find(matcher, forms)[0].id);
|
|
2772
|
+
/** The parent of `id`, which `what` needs; refused when it is outside the scope. */
|
|
2773
|
+
const parentFor = (id, what) => {
|
|
2774
|
+
const parent = parentOf.get(id);
|
|
2775
|
+
if (parent !== undefined)
|
|
2776
|
+
return parent;
|
|
2777
|
+
throw new LayerSyntaxError(scope.shown === "the document"
|
|
2778
|
+
? `#${id} is the root of a page, which has no parent, so ${what} cannot be done.`
|
|
2779
|
+
: `#${id} is the layer this edit looks in, and its parent is outside it, so ${what} cannot be done. Edit in its parent with in #<parent id>; first.`);
|
|
2780
|
+
};
|
|
2781
|
+
/** The layers inside `id`, refused when it is a layer that holds none. */
|
|
2782
|
+
const holderFor = (id) => {
|
|
2783
|
+
const children = childrenOf(id);
|
|
2784
|
+
if (children !== undefined)
|
|
2785
|
+
return children;
|
|
2786
|
+
throw new LayerSyntaxError(`#${id} is a ${headOf(current(id), context)} and holds no layers. Write add after:#${id} [...] to put layers next to it.`);
|
|
2787
|
+
};
|
|
2788
|
+
const setChildren = (id, children) => { working.set(id, { ...current(id), children }); };
|
|
2789
|
+
const removeLayer = (id) => {
|
|
2790
|
+
const parent = parentFor(id, `remove #${id}`);
|
|
2791
|
+
operations.push({ type: "node.remove", nodeId: id });
|
|
2792
|
+
setChildren(parent, childrenOf(parent).filter((child) => child !== id));
|
|
2793
|
+
const mark = (at) => {
|
|
2794
|
+
removed.add(at);
|
|
2795
|
+
for (const child of childrenOf(at) ?? [])
|
|
2796
|
+
if (current(child) !== undefined && !removed.has(child))
|
|
2797
|
+
mark(child);
|
|
2798
|
+
};
|
|
2799
|
+
mark(id);
|
|
2800
|
+
removedLayers.push(id);
|
|
2801
|
+
touched.add(parent);
|
|
2802
|
+
};
|
|
2803
|
+
const addLayers = (parentId, index, text) => {
|
|
2804
|
+
const children = holderFor(parentId);
|
|
2805
|
+
if (index > children.length) {
|
|
2806
|
+
throw new LayerSyntaxError(`#${parentId} holds ${children.length} layer${children.length === 1 ? "" : "s"}, so at: takes 0 to ${children.length}.`);
|
|
2807
|
+
}
|
|
2808
|
+
const layers = readNewLayers(text, context, current(parentId));
|
|
2809
|
+
operations.push({ type: "node.build", parentId: parentId, index, source: layers.source });
|
|
2810
|
+
buildPlaces.push(layers.places);
|
|
2811
|
+
for (const { nodeId, remove } of layers.removals)
|
|
2812
|
+
operations.push({ type: "node.patch", nodeId, fields: {}, remove: [...remove] });
|
|
2813
|
+
layers.ids.forEach((id) => given.add(id));
|
|
2814
|
+
layers.attachedTo.forEach((id) => attached.add(id));
|
|
2815
|
+
attachments.push(...layers.attachments);
|
|
2816
|
+
layers.built.forEach((node, id) => addedLayers.set(id, node));
|
|
2817
|
+
// The editor gives the new layers their ids; until then they hold their places by names no layer can have.
|
|
2818
|
+
const added = Array.from({ length: layers.count }, () => `\u0000added-${++placeholders}`);
|
|
2819
|
+
setChildren(parentId, [...children.slice(0, index), ...added, ...children.slice(index)]);
|
|
2820
|
+
addedTo.add(parentId);
|
|
2821
|
+
touched.add(parentId);
|
|
2822
|
+
};
|
|
2823
|
+
/** Refuses new layers with ids for more than one place: the ids would repeat. */
|
|
2824
|
+
const oncePerId = (text, matches, verb) => {
|
|
2825
|
+
if (matches.length < 2)
|
|
2826
|
+
return;
|
|
2827
|
+
const ids = readNewLayers(text, context).ids;
|
|
2828
|
+
if (ids.length > 0) {
|
|
2829
|
+
throw new LayerSyntaxError(`${verb} all puts the new layers in ${matches.length} places, so an id such as id:'${ids[0]}' would repeat; leave out the ids of the new layers.`);
|
|
2830
|
+
}
|
|
2831
|
+
};
|
|
2832
|
+
/** The sets since the last rule that changed layers inside layers, as one operation per layer. */
|
|
2833
|
+
const flush = () => {
|
|
2834
|
+
for (const [id, before] of pending) {
|
|
2835
|
+
const after = working.get(id);
|
|
2836
|
+
const fields = {};
|
|
2837
|
+
const removedFields = [];
|
|
2838
|
+
let replace = false;
|
|
2839
|
+
for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
2840
|
+
if (!Object.hasOwn(after, key))
|
|
2841
|
+
removedFields.push(key);
|
|
2842
|
+
else if (!deepEqual(before[key], after[key])) {
|
|
2843
|
+
fields[key] = after[key];
|
|
2844
|
+
if (losesNestedKey(before[key], after[key]))
|
|
2845
|
+
replace = true;
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
if (Object.keys(fields).length === 0 && removedFields.length === 0)
|
|
2849
|
+
continue;
|
|
2850
|
+
if (replace && addedTo.has(id)) {
|
|
2851
|
+
throw new LayerSyntaxError(`#${id} has new layers from an earlier rule of this edit, so this set, which removes a field inside an object, `
|
|
2852
|
+
+ `cannot be written; write set #${id} before the add.`);
|
|
2853
|
+
}
|
|
2854
|
+
if (!changed.includes(id))
|
|
2855
|
+
changed.push(id);
|
|
2856
|
+
touched.add(id);
|
|
2857
|
+
operations.push(replace
|
|
2858
|
+
? { type: "node.replace", node: after }
|
|
2859
|
+
: { type: "node.patch", nodeId: id, fields, ...(removedFields.length === 0 ? {} : { remove: removedFields }) });
|
|
2860
|
+
}
|
|
2861
|
+
pending = new Map();
|
|
2862
|
+
// After the sets, so that a node.replace of an instance does not write back a slot host the change removes.
|
|
2863
|
+
operations.push(...slotChanges);
|
|
2864
|
+
slotChanges = [];
|
|
2865
|
+
};
|
|
2866
|
+
/** The slot changes of the sets since the last flush: a host's node.remove, or a node.build into a slot. */
|
|
2867
|
+
let slotChanges = [];
|
|
2868
|
+
/** The host that fills the slot `propertyId` of the instance, or of its nested instance at `path`, if any. */
|
|
2869
|
+
const hostAt = (node, path, propertyId) => {
|
|
2870
|
+
const byPath = isRecord(node.slots) ? node.slots[path.join(";")] : undefined;
|
|
2871
|
+
const host = isRecord(byPath) ? byPath[propertyId] : undefined;
|
|
2872
|
+
return typeof host === "string" ? host : undefined;
|
|
2873
|
+
};
|
|
2874
|
+
const slotChanged = (id) => {
|
|
2875
|
+
if (!changed.includes(id))
|
|
2876
|
+
changed.push(id);
|
|
2877
|
+
touched.add(id);
|
|
2878
|
+
};
|
|
2879
|
+
/**
|
|
2880
|
+
* The slots the sets of this edit changed, by instance, path and slot property: the host the slot has once the
|
|
2881
|
+
* operations so far are applied (undefined when it has none, or its host is removed), and the build queued into it,
|
|
2882
|
+
* with the places of its source and its removals. A later set of the same slot starts from this, not from the stored
|
|
2883
|
+
* instance, and drops the build an earlier set queued.
|
|
2884
|
+
*/
|
|
2885
|
+
const slotStates = new Map();
|
|
2886
|
+
const slotKey = (id, path, propertyId) => [id, path.join(";"), propertyId].join("\u0000");
|
|
2887
|
+
const slotStateOf = (id, node, path, propertyId) => slotStates.get(slotKey(id, path, propertyId)) ?? { host: hostAt(node, path, propertyId) };
|
|
2888
|
+
/** Takes back the build an earlier set of this edit queued into a slot, wherever it is now. */
|
|
2889
|
+
const dropQueued = (state) => {
|
|
2890
|
+
const without = (list, item) => {
|
|
2891
|
+
const at = item === undefined ? -1 : list.indexOf(item);
|
|
2892
|
+
if (at >= 0)
|
|
2893
|
+
list.splice(at, 1);
|
|
2894
|
+
};
|
|
2895
|
+
for (const operation of [state.build, ...(state.after ?? [])]) {
|
|
2896
|
+
without(slotChanges, operation);
|
|
2897
|
+
without(operations, operation);
|
|
2898
|
+
}
|
|
2899
|
+
without(buildPlaces, state.places);
|
|
2900
|
+
if (state.layers !== undefined) {
|
|
2901
|
+
state.layers.ids.forEach((layerId) => given.delete(layerId));
|
|
2902
|
+
state.layers.attachments.forEach((attachment) => without(attachments, attachment));
|
|
2903
|
+
state.layers.built.forEach((_, layerId) => addedLayers.delete(layerId));
|
|
2904
|
+
}
|
|
2905
|
+
};
|
|
2906
|
+
/** Resets the slot `propertyId` of the instance `id` (or of its nested instance at `path`) to the component's own layers. */
|
|
2907
|
+
const resetSlot = (id, node, path, propertyId) => {
|
|
2908
|
+
const state = slotStateOf(id, node, path, propertyId);
|
|
2909
|
+
dropQueued(state);
|
|
2910
|
+
if (state.host !== undefined) {
|
|
2911
|
+
slotChanges.push({ type: "node.remove", nodeId: state.host });
|
|
2912
|
+
slotChanged(id);
|
|
2913
|
+
}
|
|
2914
|
+
slotStates.set(slotKey(id, path, propertyId), { host: undefined });
|
|
2915
|
+
};
|
|
2916
|
+
/**
|
|
2917
|
+
* `slots:{Name:( ... ), Name:(), Name:default}` of a set on the instance `id`, for its own slots (`path` empty) or, from
|
|
2918
|
+
* `over:{Path:{slots:{...}}}`, for those of its nested instance at `path`, an instance of `component`: each slot named is
|
|
2919
|
+
* filled with the layers written (the editor empties it, giving it a host when it has none, and builds them in the host),
|
|
2920
|
+
* emptied, or reset to the component's own layers by removing its host. `several` is true when the set matches more
|
|
2921
|
+
* than one layer, so that layers written with ids would repeat them.
|
|
2922
|
+
*/
|
|
2923
|
+
const setSlots = (id, node, value, where, { component, path, several }) => {
|
|
2924
|
+
const properties = slotPropertiesOf(component);
|
|
2925
|
+
const head = context.names.callNameOf(component) ?? component.name;
|
|
2926
|
+
const example = `slots:{${properties[0] === undefined ? "Content" : printLayerValue(properties[0].name)}:(text(text:'Hi'))}`;
|
|
2927
|
+
const form = `${where}: slots takes the slots of ${head} by name, each with its layers in ( ... ), () for none, or default for the component's own: ${example}.`;
|
|
2928
|
+
if (!isRecord(value) || slotContentOf(value) !== undefined)
|
|
2929
|
+
throw new LayerSyntaxError(form);
|
|
2930
|
+
for (const [name, item] of Object.entries(value)) {
|
|
2931
|
+
const property = properties.find((candidate) => candidate.name === name) ?? properties.find((candidate) => candidate.id === name);
|
|
2932
|
+
if (property === undefined) {
|
|
2933
|
+
throw new LayerSyntaxError(properties.length === 0 ? `${where}: ${head} has no slots, so slots:{...} has nothing to fill.`
|
|
2934
|
+
: `${where}: ${head} has no slot ${printLayerValue(name)}; its slots are ${properties.map((candidate) => printLayerValue(candidate.name)).join(", ")}.`);
|
|
2935
|
+
}
|
|
2936
|
+
const state = slotStateOf(id, node, path, property.id);
|
|
2937
|
+
if (item === "default") {
|
|
2938
|
+
resetSlot(id, node, path, property.id);
|
|
2939
|
+
continue;
|
|
2940
|
+
}
|
|
2941
|
+
const content = slotContentOf(item);
|
|
2942
|
+
if (content === undefined)
|
|
2943
|
+
throw new LayerSyntaxError(form);
|
|
2944
|
+
if (content.summary !== undefined) {
|
|
2945
|
+
// The slot as read printed it, unchanged.
|
|
2946
|
+
if (content.hostId === state.host && state.build === undefined)
|
|
2947
|
+
continue;
|
|
2948
|
+
throw new LayerSyntaxError(`${where}: ${slotSummaryRefusal(content.summary, content.hostId)}`);
|
|
2949
|
+
}
|
|
2950
|
+
if (several) {
|
|
2951
|
+
const repeated = idsOfCalls(content.calls)[0];
|
|
2952
|
+
if (repeated !== undefined) {
|
|
2953
|
+
throw new LayerSyntaxError(`${where}: set all fills the slot ${printLayerValue(name)} of every layer it matches, so an id such as id:'${repeated}' `
|
|
2954
|
+
+ "would repeat; leave out the ids of the slot's layers.");
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
let layers;
|
|
2958
|
+
try {
|
|
2959
|
+
layers = readSlotLayers(content.calls, context);
|
|
2960
|
+
}
|
|
2961
|
+
catch (error) {
|
|
2962
|
+
if (error instanceof LayerSyntaxError)
|
|
2963
|
+
throw new LayerSyntaxError(`${where}: ${error.message}`);
|
|
2964
|
+
throw error;
|
|
2965
|
+
}
|
|
2966
|
+
dropQueued(state);
|
|
2967
|
+
const build = { type: "node.build", parentId: id, index: 0, source: layers.source,
|
|
2968
|
+
slot: { instanceId: id, propertyId: property.id, ...(path.length === 0 ? {} : { path: [...path] }) }, emptySlot: true };
|
|
2969
|
+
const after = layers.removals.map(({ nodeId, remove }) => ({ type: "node.patch", nodeId, fields: {}, remove: [...remove] }));
|
|
2970
|
+
buildPlaces.push(layers.places);
|
|
2971
|
+
slotChanges.push(build, ...after);
|
|
2972
|
+
layers.ids.forEach((layerId) => given.add(layerId));
|
|
2973
|
+
layers.attachedTo.forEach((layerId) => attached.add(layerId));
|
|
2974
|
+
attachments.push(...layers.attachments);
|
|
2975
|
+
layers.built.forEach((built, layerId) => addedLayers.set(layerId, built));
|
|
2976
|
+
slotStates.set(slotKey(id, path, property.id), { host: state.host, build, places: layers.places, after, layers });
|
|
2977
|
+
slotChanged(id);
|
|
2978
|
+
}
|
|
2979
|
+
};
|
|
2980
|
+
/**
|
|
2981
|
+
* `over:{...}` of a set on the instance `id` where a layer's changes hold `slots:{...}`: those fill the slots of that
|
|
2982
|
+
* nested instance (`setSlots`); the rest of `over` is written as before.
|
|
2983
|
+
*/
|
|
2984
|
+
const setOver = (id, node, value, where, several) => {
|
|
2985
|
+
const component = componentOfInstance(node, context);
|
|
2986
|
+
if (component === undefined)
|
|
2987
|
+
throw new LayerSyntaxError(`${where}: the component of this instance is not known here, so its slots cannot be named.`);
|
|
2988
|
+
const rest = {};
|
|
2989
|
+
const shownAt = shownComponentsOf(context, component, node);
|
|
2990
|
+
for (const [key, changes] of Object.entries(value)) {
|
|
2991
|
+
if (!isRecord(changes) || slotContentOf(changes) !== undefined || !Object.hasOwn(changes, INSTANCE_SLOTS_ARGUMENT)) {
|
|
2992
|
+
Object.defineProperty(rest, key, { value: changes, enumerable: true, writable: true, configurable: true });
|
|
2993
|
+
continue;
|
|
2994
|
+
}
|
|
2995
|
+
const { [INSTANCE_SLOTS_ARGUMENT]: filled, ...others } = changes;
|
|
2996
|
+
let path;
|
|
2997
|
+
try {
|
|
2998
|
+
path = Object.keys(overridesFromSyntax(context.document, component, { [key]: {} }, context.names))[0].split(";");
|
|
2999
|
+
}
|
|
3000
|
+
catch (error) {
|
|
3001
|
+
if (error instanceof ComponentCallError)
|
|
3002
|
+
throw new LayerSyntaxError(`${where}: ${error.message}`);
|
|
3003
|
+
throw error;
|
|
3004
|
+
}
|
|
3005
|
+
const nested = shownAt(path);
|
|
3006
|
+
if (nested === undefined)
|
|
3007
|
+
throw new LayerSyntaxError(`${where}: ${printLayerValue(key)} is not an instance, so it has no slots to fill.`);
|
|
3008
|
+
setSlots(id, node, filled, `${where} ${printLayerValue(key)}`, { component: nested, path, several });
|
|
3009
|
+
if (Object.keys(others).length > 0)
|
|
3010
|
+
Object.defineProperty(rest, key, { value: others, enumerable: true, writable: true, configurable: true });
|
|
3011
|
+
}
|
|
3012
|
+
if (Object.keys(rest).length > 0)
|
|
3013
|
+
write(node, INSTANCE_OVER_ARGUMENT, rest, where, context);
|
|
3014
|
+
};
|
|
3015
|
+
/** `-slots` of a set on the instance `id`: every slot it fills, its own and those of the instances inside it, is reset. */
|
|
3016
|
+
const resetSlots = (id, node) => {
|
|
3017
|
+
const slots = new Map();
|
|
3018
|
+
for (const [pathKey, byProperty] of isRecord(node.slots) ? Object.entries(node.slots) : []) {
|
|
3019
|
+
const path = pathKey === "" ? [] : pathKey.split(";");
|
|
3020
|
+
for (const propertyId of isRecord(byProperty) ? Object.keys(byProperty) : [])
|
|
3021
|
+
slots.set(slotKey(id, path, propertyId), { path, propertyId });
|
|
3022
|
+
}
|
|
3023
|
+
// The slots an earlier set of this edit filled, which the stored instance does not show yet.
|
|
3024
|
+
for (const key of slotStates.keys()) {
|
|
3025
|
+
const [instanceId, pathKey, propertyId] = key.split("\u0000");
|
|
3026
|
+
if (instanceId === id)
|
|
3027
|
+
slots.set(key, { path: pathKey === "" ? [] : pathKey.split(";"), propertyId });
|
|
3028
|
+
}
|
|
3029
|
+
for (const { path, propertyId } of slots.values())
|
|
3030
|
+
resetSlot(id, node, path, propertyId);
|
|
3031
|
+
};
|
|
3032
|
+
/**
|
|
3033
|
+
* `fit:<padding>` of a set on `node`, a copy of the frame `id`: the frame takes the size of the box around its layers
|
|
3034
|
+
* plus the padding on every side, and its layers move by the same amount so that the padding is even. The frame keeps
|
|
3035
|
+
* its x and y.
|
|
3036
|
+
*/
|
|
3037
|
+
const fit = (id, node, value, where) => {
|
|
3038
|
+
if (!placesFreely(node)) {
|
|
3039
|
+
throw new LayerSyntaxError(`${where} is a ${headOf(node, context)}, and fit sizes only a frame with free layout. `
|
|
3040
|
+
+ (isAutoLayoutFrame(node) ? "An auto layout frame fits its layers with w:hug, h:hug and pad:<padding>." : "Write w: and h: instead."));
|
|
3041
|
+
}
|
|
3042
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
3043
|
+
throw new LayerSyntaxError(`${where}: fit takes the padding, a number of 0 or more, as fit:16.`);
|
|
3044
|
+
}
|
|
3045
|
+
const ids = childrenOf(id) ?? [];
|
|
3046
|
+
if (ids.some((child) => current(child) === undefined)) {
|
|
3047
|
+
throw new LayerSyntaxError(`${where} has layers an earlier rule of this edit adds, whose size is not known yet; send fit in a call after this one.`);
|
|
3048
|
+
}
|
|
3049
|
+
const box = contentBox(ids.map((child) => current(child)));
|
|
3050
|
+
if (box === undefined)
|
|
3051
|
+
throw new LayerSyntaxError(`${where} holds no layers, so there is nothing to fit it to.`);
|
|
3052
|
+
write(node, "w", box.width + 2 * value, where, context);
|
|
3053
|
+
write(node, "h", box.height + 2 * value, where, context);
|
|
3054
|
+
const dx = value - box.x, dy = value - box.y;
|
|
3055
|
+
if (dx === 0 && dy === 0)
|
|
3056
|
+
return;
|
|
3057
|
+
for (const child of ids) {
|
|
3058
|
+
const before = current(child);
|
|
3059
|
+
if (!pending.has(child))
|
|
3060
|
+
pending.set(child, clone(before));
|
|
3061
|
+
const moved = clone(before);
|
|
3062
|
+
if (Array.isArray(moved.transform) && !isRecord(moved.frame)) {
|
|
3063
|
+
const transform = moved.transform;
|
|
3064
|
+
moved.transform = [transform[0], transform[1], transform[2], transform[3], transform[4] + dx, transform[5] + dy];
|
|
3065
|
+
}
|
|
3066
|
+
else {
|
|
3067
|
+
const frame = moved.frame;
|
|
3068
|
+
moved.frame = { ...frame, x: frame.x + dx, y: frame.y + dy };
|
|
3069
|
+
}
|
|
3070
|
+
working.set(child, moved);
|
|
3071
|
+
}
|
|
3072
|
+
};
|
|
3073
|
+
/**
|
|
3074
|
+
* The expressions and conditions of the layers of `component` (its root `rootId` and the layers inside it, as earlier
|
|
3075
|
+
* rules of this edit leave them) that read one of the props `names`, each as a set writes it.
|
|
3076
|
+
*/
|
|
3077
|
+
const propertyUses = (rootId, component, names, after) => {
|
|
3078
|
+
const uses = [];
|
|
3079
|
+
const visit = (at, depth) => {
|
|
3080
|
+
if (depth > PARENT_CHAIN_LIMIT)
|
|
3081
|
+
throw new Error(`The layers of #${rootId} go more than ${PARENT_CHAIN_LIMIT} deep.`);
|
|
3082
|
+
const node = current(at);
|
|
3083
|
+
if (node === undefined || removed.has(at))
|
|
3084
|
+
return;
|
|
3085
|
+
const sources = [
|
|
3086
|
+
...(isRecord(node.expressions) ? Object.entries(node.expressions) : []).flatMap(([field, source]) => typeof source === "string" ? [[field, source]] : []),
|
|
3087
|
+
...(typeof node.condition === "string" ? [["condition", node.condition]] : []),
|
|
3088
|
+
];
|
|
3089
|
+
for (const [field, source] of sources) {
|
|
3090
|
+
const fieldContext = expressionFieldContext(context.document, component, node, field);
|
|
3091
|
+
if (fieldContext === undefined)
|
|
3092
|
+
continue;
|
|
3093
|
+
const checked = checkExpressionSource(source, fieldContext.expected, fieldContext.environment);
|
|
3094
|
+
if (!checked.references.some((reference) => reference.kind === "property" && names.has(reference.name)))
|
|
3095
|
+
continue;
|
|
3096
|
+
const written = field === "condition" ? `condition:${printLayerValue(source)}` : `expressions:{${field}:${printLayerValue(source)}}`;
|
|
3097
|
+
if (after === undefined) {
|
|
3098
|
+
uses.push({ layer: at, written });
|
|
3099
|
+
continue;
|
|
3100
|
+
}
|
|
3101
|
+
// With `after`, a use counts only when it checks now and would not against the props `after` has.
|
|
3102
|
+
const next = expressionFieldContext(context.document, after, node, field);
|
|
3103
|
+
const again = next === undefined ? undefined : checkExpressionSource(source, next.expected, next.environment);
|
|
3104
|
+
if (checked.ok && again !== undefined && !again.ok)
|
|
3105
|
+
uses.push({ layer: at, written, error: again.errors[0].message.replace(/\.$/, "") });
|
|
3106
|
+
}
|
|
3107
|
+
for (const child of childrenOf(at) ?? [])
|
|
3108
|
+
visit(child, depth + 1);
|
|
3109
|
+
};
|
|
3110
|
+
visit(rootId, 0);
|
|
3111
|
+
return uses;
|
|
3112
|
+
};
|
|
3113
|
+
/** The component whose root is the layer `id` or a layer above it in the scope, if any. */
|
|
3114
|
+
const componentAround = (id) => {
|
|
3115
|
+
const byRoot = new Map(Object.values(context.document.components ?? {}).map((component) => [String(component.rootId), component]));
|
|
3116
|
+
let steps = 0;
|
|
3117
|
+
for (let at = id; at !== undefined; at = parentOf.get(at)) {
|
|
3118
|
+
if (++steps > PARENT_CHAIN_LIMIT)
|
|
3119
|
+
throw new Error(`The parents of #${id} go more than ${PARENT_CHAIN_LIMIT} deep.`);
|
|
3120
|
+
const component = byRoot.get(at);
|
|
3121
|
+
if (component !== undefined)
|
|
3122
|
+
return component;
|
|
3123
|
+
// Above a root of the scope, the component the host found by the layer's parents.
|
|
3124
|
+
if (!parentOf.has(at) && scope.roots.includes(at))
|
|
3125
|
+
return scope.insideComponent === undefined ? undefined : context.names.byId(scope.insideComponent.id) ?? scope.insideComponent;
|
|
3126
|
+
}
|
|
3127
|
+
return undefined;
|
|
3128
|
+
};
|
|
3129
|
+
/**
|
|
3130
|
+
* The slot property id `slot:Name` binds the frame `id` to in a set: the slot of the component around it with that
|
|
3131
|
+
* name (or that id). Refuses a frame outside a component and a name the component has no slot of.
|
|
3132
|
+
*/
|
|
3133
|
+
const slotIdInEdit = (id, written, where) => {
|
|
3134
|
+
const component = componentAround(id);
|
|
3135
|
+
if (component === undefined)
|
|
3136
|
+
throw new LayerSyntaxError(`${where}: only a frame inside a component can show a slot, and #${id} is in none.`);
|
|
3137
|
+
const slots = slotPropertiesOf(component);
|
|
3138
|
+
const found = slots.find((property) => property.name === written) ?? slots.find((property) => property.id === written);
|
|
3139
|
+
if (found !== undefined)
|
|
3140
|
+
return found.id;
|
|
3141
|
+
const head = context.names.callNameOf(component) ?? component.name;
|
|
3142
|
+
throw new LayerSyntaxError(`${where}: ${head} has no slot ${printLayerValue(written)}`
|
|
3143
|
+
+ `${slots.length === 0 ? "" : `; its slots are ${slots.map((property) => printLayerValue(property.name)).join(", ")}`}. `
|
|
3144
|
+
+ `A build of a frame with slot:${printLayerValue(written)} inside the component adds the slot.`);
|
|
3145
|
+
};
|
|
3146
|
+
/**
|
|
3147
|
+
* Refuses an expression or a condition a set writes on `node`, a layer of a component in the scope, that does not check
|
|
3148
|
+
* against the component's props: the refusal gives the checker's reason and the props. `var("Collection/Name")` checks
|
|
3149
|
+
* against the variables of the scope (`LayerEditScope.variables`, which the tools read for every name a text gives in
|
|
3150
|
+
* `var(...)`), so a variable that is not there is refused too.
|
|
3151
|
+
*/
|
|
3152
|
+
const checkExpressions = (id, before, node, where) => {
|
|
3153
|
+
const written = (field) => {
|
|
3154
|
+
const value = field === "condition" ? node.condition : isRecord(node.expressions) ? node.expressions[field] : undefined;
|
|
3155
|
+
const was = field === "condition" ? before.condition : isRecord(before.expressions) ? before.expressions[field] : undefined;
|
|
3156
|
+
return typeof value === "string" && value !== was ? value : undefined;
|
|
3157
|
+
};
|
|
3158
|
+
const fields = [...(isRecord(node.expressions) ? Object.keys(node.expressions) : []), "condition"];
|
|
3159
|
+
if (!fields.some((field) => written(field) !== undefined))
|
|
3160
|
+
return;
|
|
3161
|
+
const component = componentAround(id);
|
|
3162
|
+
if (component === undefined)
|
|
3163
|
+
return;
|
|
3164
|
+
for (const field of fields) {
|
|
3165
|
+
const source = written(field);
|
|
3166
|
+
if (source === undefined)
|
|
3167
|
+
continue;
|
|
3168
|
+
const shown = field === "condition" ? `condition:${printLayerValue(source)}` : `expressions:{${field}:${printLayerValue(source)}}`;
|
|
3169
|
+
if (String(component.rootId) === id && (field === "visible" || field === "opacity" || field === "condition")) {
|
|
3170
|
+
throw new LayerSyntaxError(`${where} is the root of component '${component.name}', which cannot compute ${field}: each instance sets its own. `
|
|
3171
|
+
+ "Compute it on a layer inside the root.");
|
|
3172
|
+
}
|
|
3173
|
+
const fieldContext = expressionFieldContext(context.document, component, node, field);
|
|
3174
|
+
if (fieldContext === undefined) {
|
|
3175
|
+
throw new LayerSyntaxError(`${where}: a ${headOf(node, context)} cannot compute ${field}; it computes ${computableFieldsOf(node).join(", ")}.`);
|
|
3176
|
+
}
|
|
3177
|
+
const checked = checkExpressionSource(source, fieldContext.expected, fieldContext.environment);
|
|
3178
|
+
if (checked.ok)
|
|
3179
|
+
continue;
|
|
3180
|
+
const error = checked.errors[0];
|
|
3181
|
+
throw new LayerSyntaxError(`${where}: ${shown} does not check: ${error.message.replace(/\.$/, "")}${error.hint === undefined ? "" : ` (${error.hint.replace(/\.$/, "")})`}; `
|
|
3182
|
+
+ `${componentPropertyList(component, context.names, "expression")}; prop #${String(component.rootId)} { ... } adds one.${expressionBacktickHint(component)}`);
|
|
3183
|
+
}
|
|
3184
|
+
};
|
|
3185
|
+
for (const rule of rules) {
|
|
3186
|
+
if (rule.verb === "set") {
|
|
3187
|
+
const matches = find(rule.matcher, { one: (id) => `set ${id} { ... }`, all: (matcher) => `set all ${matcher} { ... }` });
|
|
3188
|
+
for (const match of matches) {
|
|
3189
|
+
const id = String(match.id);
|
|
3190
|
+
if (!setOn.includes(id))
|
|
3191
|
+
setOn.push(id);
|
|
3192
|
+
if (!pending.has(id))
|
|
3193
|
+
pending.set(id, clone(match));
|
|
3194
|
+
const node = clone(match);
|
|
3195
|
+
const where = `#${id}`;
|
|
3196
|
+
for (const { key, value } of node.type === "shape" && node.shape === "path" ? inPathOrder(rule.writes) : rule.writes) {
|
|
3197
|
+
if (key === "fit")
|
|
3198
|
+
fit(id, node, value, where);
|
|
3199
|
+
else if (key === "slots" && node.type === "instance") {
|
|
3200
|
+
const component = componentOfInstance(node, context);
|
|
3201
|
+
if (component === undefined)
|
|
3202
|
+
throw new LayerSyntaxError(`${where}: the component of this instance is not known here, so its slots cannot be named.`);
|
|
3203
|
+
setSlots(id, node, value, where, { component, path: [], several: matches.length > 1 });
|
|
3204
|
+
}
|
|
3205
|
+
else if (key === INSTANCE_OVER_ARGUMENT && node.type === "instance" && isRecord(value)
|
|
3206
|
+
&& Object.values(value).some((changes) => isRecord(changes) && Object.hasOwn(changes, INSTANCE_SLOTS_ARGUMENT))) {
|
|
3207
|
+
setOver(id, node, value, where, matches.length > 1);
|
|
3208
|
+
}
|
|
3209
|
+
else if (key === "slots" || (key === INSTANCE_OVER_ARGUMENT && isRecord(value)
|
|
3210
|
+
&& Object.values(value).some((changes) => isRecord(changes) && Object.hasOwn(changes, INSTANCE_SLOTS_ARGUMENT)))) {
|
|
3211
|
+
throw new LayerSyntaxError(`${where}: ${SLOTS_IN_EDIT}`);
|
|
3212
|
+
}
|
|
3213
|
+
else if (key === "slot" && node.type === "frame" && typeof value === "string")
|
|
3214
|
+
node.slot = slotIdInEdit(id, value, where);
|
|
3215
|
+
else
|
|
3216
|
+
write(node, key, value, where, context);
|
|
3217
|
+
}
|
|
3218
|
+
for (const key of rule.removes) {
|
|
3219
|
+
if (key === "slots" && node.type === "instance")
|
|
3220
|
+
resetSlots(id, node);
|
|
3221
|
+
else if (key === "slots")
|
|
3222
|
+
throw new LayerSyntaxError(`${where}: ${SLOTS_IN_EDIT}`);
|
|
3223
|
+
else
|
|
3224
|
+
remove(node, key, where, context);
|
|
3225
|
+
}
|
|
3226
|
+
checkExpressions(id, match, node, where);
|
|
3227
|
+
if (!deepEqual([match.start, match.end], [node.start, node.end]))
|
|
3228
|
+
checkConnectorEnds(node, where);
|
|
3229
|
+
for (const which of ["start", "end"].filter((end) => !deepEqual(match[end], node[end]))) {
|
|
3230
|
+
setEnds.delete(`${id}\u0000${which}`);
|
|
3231
|
+
for (const attachment of connectorAttachments(node, where, [which]))
|
|
3232
|
+
setEnds.set(`${id}\u0000${which}`, attachment);
|
|
3233
|
+
}
|
|
3234
|
+
const before = connectorTargets(match);
|
|
3235
|
+
connectorTargets(node).filter((target) => !before.includes(target)).forEach((target) => attached.add(target));
|
|
3236
|
+
working.set(id, node);
|
|
3237
|
+
}
|
|
3238
|
+
continue;
|
|
3239
|
+
}
|
|
3240
|
+
flush();
|
|
3241
|
+
switch (rule.verb) {
|
|
3242
|
+
case "add": {
|
|
3243
|
+
const at = rule.places.find((place) => place.kind === "at")?.index;
|
|
3244
|
+
const next = rule.places.find((place) => place.kind !== "at");
|
|
3245
|
+
if (next === undefined || next.kind === "in") {
|
|
3246
|
+
const parents = rule.parent !== undefined
|
|
3247
|
+
? find(rule.parent, { one: (id) => `add ${id} [...]`, all: (matcher) => `add all ${matcher} [...]` })
|
|
3248
|
+
: find(next.matcher, { one: (id) => `add in:${id} [...]` });
|
|
3249
|
+
oncePerId(rule.layers, parents, "add");
|
|
3250
|
+
for (const parent of parents) {
|
|
3251
|
+
const id = String(parent.id);
|
|
3252
|
+
addLayers(id, at ?? holderFor(id).length, rule.layers);
|
|
3253
|
+
}
|
|
3254
|
+
}
|
|
3255
|
+
else {
|
|
3256
|
+
const neighbour = findOne(next.matcher, { one: (id) => `add ${next.kind}:${id} [...]` });
|
|
3257
|
+
const parent = parentFor(neighbour, `add ${next.kind}:#${neighbour}`);
|
|
3258
|
+
addLayers(parent, childrenOf(parent).indexOf(neighbour) + (next.kind === "after" ? 1 : 0), rule.layers);
|
|
3259
|
+
}
|
|
3260
|
+
break;
|
|
3261
|
+
}
|
|
3262
|
+
case "move": {
|
|
3263
|
+
const id = findOne(rule.matcher, { one: (id) => `move ${id} ...` });
|
|
3264
|
+
const from = parentFor(id, `move #${id}`);
|
|
3265
|
+
const without = (parent) => holderFor(parent).filter((child) => child !== id);
|
|
3266
|
+
const at = rule.places.find((place) => place.kind === "at")?.index;
|
|
3267
|
+
const next = rule.places.find((place) => place.kind !== "at");
|
|
3268
|
+
let to, index;
|
|
3269
|
+
if (next === undefined || next.kind === "in") {
|
|
3270
|
+
to = next === undefined ? from : findOne(next.matcher, { one: (target) => `move #${id} in:${target}` });
|
|
3271
|
+
const children = without(to);
|
|
3272
|
+
index = at ?? children.length;
|
|
3273
|
+
if (index > children.length) {
|
|
3274
|
+
throw new LayerSyntaxError(`#${to} holds ${children.length} other layer${children.length === 1 ? "" : "s"}, so at: takes 0 to ${children.length}.`);
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3277
|
+
else {
|
|
3278
|
+
const neighbour = findOne(next.matcher, { one: (target) => `move #${id} ${next.kind}:${target}` });
|
|
3279
|
+
if (neighbour === id)
|
|
3280
|
+
throw new LayerSyntaxError(`#${id} cannot be moved ${next.kind} itself. ${MOVE_FORM}`);
|
|
3281
|
+
to = parentFor(neighbour, `move #${id} ${next.kind}:#${neighbour}`);
|
|
3282
|
+
index = without(to).indexOf(neighbour) + (next.kind === "after" ? 1 : 0);
|
|
3283
|
+
}
|
|
3284
|
+
let steps = 0;
|
|
3285
|
+
for (let at = to; at !== undefined; at = parentOf.get(at)) {
|
|
3286
|
+
if (++steps > PARENT_CHAIN_LIMIT)
|
|
3287
|
+
throw new Error(`The parents of #${to} go more than ${PARENT_CHAIN_LIMIT} deep.`);
|
|
3288
|
+
if (at === id)
|
|
3289
|
+
throw new LayerSyntaxError(`#${to} is inside #${id}, so #${id} cannot be moved into it.`);
|
|
3290
|
+
}
|
|
3291
|
+
if (to === from && childrenOf(from).indexOf(id) === index)
|
|
3292
|
+
break;
|
|
3293
|
+
operations.push({ type: "node.move", nodeId: id, newParentId: to, index });
|
|
3294
|
+
setChildren(from, without(from));
|
|
3295
|
+
const children = [...childrenOf(to)];
|
|
3296
|
+
children.splice(index, 0, id);
|
|
3297
|
+
setChildren(to, children);
|
|
3298
|
+
parentOf.set(id, to);
|
|
3299
|
+
if (!moved.includes(id))
|
|
3300
|
+
moved.push(id);
|
|
3301
|
+
touched.add(from).add(to);
|
|
3302
|
+
break;
|
|
3303
|
+
}
|
|
3304
|
+
case "remove":
|
|
3305
|
+
for (const match of find(rule.matcher, { one: (id) => `remove ${id}`, all: (matcher) => `remove all ${matcher}` })) {
|
|
3306
|
+
// A layer inside one this rule removed already went with it.
|
|
3307
|
+
if (!removed.has(String(match.id)))
|
|
3308
|
+
removeLayer(String(match.id));
|
|
3309
|
+
}
|
|
3310
|
+
break;
|
|
3311
|
+
case "outline": {
|
|
3312
|
+
const first = operations[0];
|
|
3313
|
+
const before = operations.length === 0 ? undefined : operations.length === 1 && first.type === "node.outlineStroke" ? first : null;
|
|
3314
|
+
if (before === null) {
|
|
3315
|
+
throw new LayerSyntaxError(`outline reads the layers as they are before the edit, so it must come before the other rules; send those after it. ${OUTLINE_FORM}`);
|
|
3316
|
+
}
|
|
3317
|
+
const ids = find(rule.matcher, { one: (id) => `outline ${id}`, all: (matcher) => `outline all ${matcher}` }).map((match) => String(match.id));
|
|
3318
|
+
const earlier = before?.ids ?? [];
|
|
3319
|
+
operations.splice(0, 1, { type: "node.outlineStroke", ids: [...earlier, ...ids.filter((id) => !earlier.includes(id))] });
|
|
3320
|
+
// The layers are outlined into new layers the editor names; until then no later rule may match them or the layers inside them.
|
|
3321
|
+
const mark = (at) => {
|
|
3322
|
+
outlined.add(at);
|
|
3323
|
+
removed.add(at);
|
|
3324
|
+
for (const child of childrenOf(at) ?? [])
|
|
3325
|
+
if (current(child) !== undefined && !removed.has(child))
|
|
3326
|
+
mark(child);
|
|
3327
|
+
};
|
|
3328
|
+
for (const id of ids) {
|
|
3329
|
+
if (outlined.has(id))
|
|
3330
|
+
continue;
|
|
3331
|
+
touched.add(id).add(parentFor(id, `outline #${id}`));
|
|
3332
|
+
mark(id);
|
|
3333
|
+
}
|
|
3334
|
+
break;
|
|
3335
|
+
}
|
|
3336
|
+
case "convert": {
|
|
3337
|
+
// A frame an earlier rule of this edit adds is converted by its id: the editor reads it once it is built, and
|
|
3338
|
+
// refuses it there when it is not a frame.
|
|
3339
|
+
const added = rule.matcher.id !== undefined && given.has(rule.matcher.id) && !removed.has(rule.matcher.id)
|
|
3340
|
+
&& !inScope.includes(rule.matcher.id);
|
|
3341
|
+
const id = added ? rule.matcher.id : findOne(rule.matcher, { one: (id) => `convert ${id} to component(name:'<name>')` });
|
|
3342
|
+
if (!added) {
|
|
3343
|
+
const node = current(id);
|
|
3344
|
+
parentFor(id, `convert #${id}`);
|
|
3345
|
+
if (node.type !== "frame") {
|
|
3346
|
+
throw new LayerSyntaxError(`#${id} is a ${headOf(node, context)}, and only a frame can become a component; put it in a frame first. ${CONVERT_FORM}`);
|
|
3347
|
+
}
|
|
3348
|
+
}
|
|
3349
|
+
const copies = rule.replace.map((copy) => {
|
|
3350
|
+
const copyId = findOne({ text: `#${copy}`, id: copy, all: false, filters: [], within: [] }, { one: (one) => `convert #${id} to component replace ${one}` });
|
|
3351
|
+
if (copyId === id)
|
|
3352
|
+
throw new LayerSyntaxError(`#${id} is the frame this rule converts; replace lists other copies of it. ${CONVERT_FORM}`);
|
|
3353
|
+
const node = current(copyId);
|
|
3354
|
+
if (node.type !== "frame") {
|
|
3355
|
+
throw new LayerSyntaxError(`#${copyId} is a ${headOf(node, context)}, so it is no copy of the frame #${id}; replace lists frames that look like it. ${CONVERT_FORM}`);
|
|
3356
|
+
}
|
|
3357
|
+
parentFor(copyId, `replace #${copyId}`);
|
|
3358
|
+
let steps = 0;
|
|
3359
|
+
for (let at = parentOf.get(copyId); at !== undefined; at = parentOf.get(at)) {
|
|
3360
|
+
if (++steps > PARENT_CHAIN_LIMIT)
|
|
3361
|
+
throw new Error(`The parents of #${copyId} go more than ${PARENT_CHAIN_LIMIT} deep.`);
|
|
3362
|
+
if (at === id)
|
|
3363
|
+
throw new LayerSyntaxError(`#${copyId} is inside #${id}, the frame this rule converts, so it cannot become an instance of it.`);
|
|
3364
|
+
}
|
|
3365
|
+
return copyId;
|
|
3366
|
+
});
|
|
3367
|
+
if (new Set(copies).size !== copies.length)
|
|
3368
|
+
throw new LayerSyntaxError(`replace lists a copy twice. ${CONVERT_FORM}`);
|
|
3369
|
+
operations.push({ type: "component.convert", nodeId: id, ...(rule.name === undefined ? {} : { name: rule.name }),
|
|
3370
|
+
...(copies.length === 0 ? {} : { replace: copies }) });
|
|
3371
|
+
// The frame and the copies leave the scope; until the editor names their instances, names no layer can have hold their places.
|
|
3372
|
+
const mark = (at) => {
|
|
3373
|
+
converted.add(at);
|
|
3374
|
+
removed.add(at);
|
|
3375
|
+
for (const child of childrenOf(at) ?? [])
|
|
3376
|
+
if (current(child) !== undefined && !removed.has(child))
|
|
3377
|
+
mark(child);
|
|
3378
|
+
};
|
|
3379
|
+
for (const layer of added ? copies : [id, ...copies]) {
|
|
3380
|
+
const parent = parentFor(layer, `convert #${layer}`);
|
|
3381
|
+
setChildren(parent, childrenOf(parent).map((child) => child === layer ? `\u0000converted-${++placeholders}` : child));
|
|
3382
|
+
touched.add(parent);
|
|
3383
|
+
mark(layer);
|
|
3384
|
+
}
|
|
3385
|
+
if (added)
|
|
3386
|
+
converted.add(id);
|
|
3387
|
+
break;
|
|
3388
|
+
}
|
|
3389
|
+
case "prop": {
|
|
3390
|
+
const id = findOne(rule.matcher, { one: (one) => `prop ${one} { ... }` });
|
|
3391
|
+
const component = Object.values(context.document.components ?? {}).find((candidate) => String(candidate.rootId) === id);
|
|
3392
|
+
if (component === undefined) {
|
|
3393
|
+
throw new LayerSyntaxError(`#${id} is not the root of a component, and prop changes a component's props; read components lists each component's root. ${PROP_FORM}`);
|
|
3394
|
+
}
|
|
3395
|
+
const properties = propertiesAfter(component, rule.writes, rule.removes, `prop #${id}`, context.names);
|
|
3396
|
+
const validity = rule.validity === undefined ? component.validity : rule.validity ?? undefined;
|
|
3397
|
+
const validityChanged = validity !== component.validity;
|
|
3398
|
+
if (deepEqual(properties, component.properties ?? []) && !validityChanged)
|
|
3399
|
+
break;
|
|
3400
|
+
// The validity expression must check against the props as they will be, and hold for their defaults.
|
|
3401
|
+
if (validity !== undefined) {
|
|
3402
|
+
const after = { ...component, properties, validity };
|
|
3403
|
+
const checked = checkComponentValidity(after);
|
|
3404
|
+
const variantProps = properties.filter((property) => property.kind === "enum" || property.kind === "boolean")
|
|
3405
|
+
.map((property) => formatExpressionName(property.name));
|
|
3406
|
+
const change = validityChanged ? "" : " Change it in the same rule, with valid:'...', or remove it with -valid.";
|
|
3407
|
+
if (!checked.ok) {
|
|
3408
|
+
throw new LayerSyntaxError(`prop #${id}: the validity expression ${printLayerValue(validity, "an expression")} does not check: ${checked.errors[0].message}. `
|
|
3409
|
+
+ `It is a boolean expression that reads only enum and boolean props (${variantProps.length === 0 ? "the component has none" : variantProps.join(", ")}).${change}`);
|
|
3410
|
+
}
|
|
3411
|
+
const problem = invalidCombinationProblem(after, {});
|
|
3412
|
+
if (problem !== undefined)
|
|
3413
|
+
throw new LayerSyntaxError(`prop #${id}: the defaults must be a valid combination, but ${problem}.${change}`);
|
|
3414
|
+
}
|
|
3415
|
+
// A prop removed, or of another kind now, would leave the expressions that read it reading nothing.
|
|
3416
|
+
const gone = (component.properties ?? []).filter((property) => properties.find((candidate) => candidate.id === property.id)?.kind !== property.kind);
|
|
3417
|
+
const uses = gone.length === 0 ? [] : propertyUses(id, component, new Set(gone.map((property) => property.name)));
|
|
3418
|
+
if (uses.length > 0) {
|
|
3419
|
+
const shown = uses.slice(0, LIST_LIMIT).map(({ layer, written }) => `#${layer} ${written}`).join(", ");
|
|
3420
|
+
throw new LayerSyntaxError(`prop #${id}: ${gone.map((property) => property.name).join(" and ")} ${uses.length === 1 ? "is" : "are"} read by ${shown}`
|
|
3421
|
+
+ `${uses.length > LIST_LIMIT ? ` and ${uses.length - LIST_LIMIT} more` : ""}. Removing a prop or changing its kind would leave them reading nothing, `
|
|
3422
|
+
+ `so change them first, with sets before this rule in the same edit: set #${uses[0].layer} { -expressions } removes a layer's expressions `
|
|
3423
|
+
+ "(write back those to keep in a set after it), and -condition its condition.");
|
|
3424
|
+
}
|
|
3425
|
+
// An enum whose options change may leave a match or a comparison naming an option it no longer has, or a match
|
|
3426
|
+
// without else not covering one it gains: the expressions that check now and would not then are refused too.
|
|
3427
|
+
const reoptioned = (component.properties ?? []).filter((property) => {
|
|
3428
|
+
const next = properties.find((candidate) => candidate.id === property.id);
|
|
3429
|
+
return property.kind === "enum" && next?.kind === "enum" && !deepEqual(property.options, next.options);
|
|
3430
|
+
});
|
|
3431
|
+
const broken = reoptioned.length === 0 ? []
|
|
3432
|
+
: propertyUses(id, component, new Set(reoptioned.map((property) => property.name)), { ...component, properties });
|
|
3433
|
+
if (broken.length > 0) {
|
|
3434
|
+
const shown = broken.slice(0, LIST_LIMIT).map(({ layer, written, error }) => `#${layer} ${written} (${error})`).join(", ");
|
|
3435
|
+
throw new LayerSyntaxError(`prop #${id}: with the new options of ${reoptioned.map((property) => property.name).join(" and ")}, ${shown}`
|
|
3436
|
+
+ `${broken.length > LIST_LIMIT ? ` and ${broken.length - LIST_LIMIT} more` : ""} would no longer check. Change them first, with sets before `
|
|
3437
|
+
+ `this rule in the same edit, as set #${broken[0].layer} { expressions:{...} } with each option the prop keeps, or else => ... to end a match.`);
|
|
3438
|
+
}
|
|
3439
|
+
operations.push({ type: "component.set-properties", componentId: component.id, properties,
|
|
3440
|
+
...(validityChanged ? { validity: validity ?? null } : {}) });
|
|
3441
|
+
const { properties: _old, validity: _oldValidity, ...rest } = component;
|
|
3442
|
+
const definitions = { ...(context.document.components ?? {}), [component.id]: {
|
|
3443
|
+
...rest, ...(properties.length === 0 ? {} : { properties }), ...(validity === undefined ? {} : { validity })
|
|
3444
|
+
} };
|
|
3445
|
+
const document = { ...context.document, components: definitions };
|
|
3446
|
+
context = { document, names: componentNames(document) };
|
|
3447
|
+
const all = Object.values(definitions);
|
|
3448
|
+
props.set(id, { rootId: id, call: printLayerComponents(all)[all.findIndex((candidate) => candidate.id === component.id)] });
|
|
3449
|
+
touched.add(id);
|
|
3450
|
+
break;
|
|
3451
|
+
}
|
|
3452
|
+
case "union":
|
|
3453
|
+
case "subtract":
|
|
3454
|
+
case "intersect":
|
|
3455
|
+
case "exclude": {
|
|
3456
|
+
if (operations.length > 0) {
|
|
3457
|
+
throw new LayerSyntaxError(`${rule.verb} reads the layers as they are before the edit, so it must be the first rule, and an edit takes one; send the others after it. ${BOOLEAN_FORM}`);
|
|
3458
|
+
}
|
|
3459
|
+
const ids = rule.ids.map((id) => findOne({ text: `#${id}`, id, all: false, filters: [], within: [] }, { one: (one) => `${rule.verb} ${one}` }));
|
|
3460
|
+
if (new Set(ids).size !== ids.length)
|
|
3461
|
+
throw new LayerSyntaxError(`${rule.verb} names a layer twice. ${BOOLEAN_FORM}`);
|
|
3462
|
+
operations.push({ type: "node.boolean", ids: ids, op: rule.verb });
|
|
3463
|
+
// The layers become one new path; until the editor makes it, no later rule may match them.
|
|
3464
|
+
for (const id of ids) {
|
|
3465
|
+
touched.add(id).add(parentFor(id, `${rule.verb} #${id}`));
|
|
3466
|
+
combined.add(id);
|
|
3467
|
+
removed.add(id);
|
|
3468
|
+
}
|
|
3469
|
+
break;
|
|
3470
|
+
}
|
|
3471
|
+
case "replace": {
|
|
3472
|
+
const found = find(rule.matcher, { one: (id) => `replace ${id} [...]`, all: (matcher) => `replace all ${matcher} [...]` });
|
|
3473
|
+
// A match inside another match, in the layers as earlier rules left them, goes with that match.
|
|
3474
|
+
const ids = new Set(found.map((match) => String(match.id)));
|
|
3475
|
+
const insideAnother = (id) => {
|
|
3476
|
+
let steps = 0;
|
|
3477
|
+
for (let at = parentOf.get(id); at !== undefined; at = parentOf.get(at)) {
|
|
3478
|
+
if (++steps > PARENT_CHAIN_LIMIT)
|
|
3479
|
+
throw new Error(`The parents of #${id} go more than ${PARENT_CHAIN_LIMIT} deep.`);
|
|
3480
|
+
if (ids.has(at))
|
|
3481
|
+
return true;
|
|
3482
|
+
}
|
|
3483
|
+
return false;
|
|
3484
|
+
};
|
|
3485
|
+
const matches = found.filter((match) => !insideAnother(String(match.id)));
|
|
3486
|
+
oncePerId(rule.layers, matches, "replace");
|
|
3487
|
+
for (const match of matches) {
|
|
3488
|
+
const id = String(match.id);
|
|
3489
|
+
const parent = parentFor(id, `replace #${id}`);
|
|
3490
|
+
const index = childrenOf(parent).indexOf(id);
|
|
3491
|
+
removeLayer(id);
|
|
3492
|
+
addLayers(parent, index, rule.layers);
|
|
3493
|
+
}
|
|
3494
|
+
break;
|
|
3495
|
+
}
|
|
3496
|
+
}
|
|
3497
|
+
}
|
|
3498
|
+
flush();
|
|
3499
|
+
const attachedTo = [...attached].filter((id) => !given.has(id) && scope.node(id) === undefined);
|
|
3500
|
+
// An end attached to a layer in the scope (as the edit leaves it) or to a layer the edit adds, in any rule, is checked
|
|
3501
|
+
// against it here; the others when the host reads their layers.
|
|
3502
|
+
const unchecked = checkKnownAttachments([...attachments, ...setEnds.values()], (id) => addedLayers.get(id) ?? (working.get(id) ?? scope.node(id)));
|
|
3503
|
+
const unchanged = setOn.filter((id) => !changed.includes(id) && !removed.has(id));
|
|
3504
|
+
return { operations, props: [...props.values()], changed, unchanged, moved, removed: removedLayers, touched: [...touched], attachedTo,
|
|
3505
|
+
attachments: unchecked, buildPlaces };
|
|
3506
|
+
}
|