@moondraft/import 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/LICENSE +34 -0
- package/README.md +36 -2
- package/SOURCE.md +394 -0
- package/dist/adapter/convert.d.ts +144 -0
- package/dist/adapter/convert.js +2811 -0
- package/dist/adapter/figma-descriptions.d.ts +7 -0
- package/dist/adapter/figma-descriptions.js +34 -0
- package/dist/adapter/figma-grids.d.ts +12 -0
- package/dist/adapter/figma-grids.js +175 -0
- package/dist/adapter/figma-handoff.d.ts +12 -0
- package/dist/adapter/figma-handoff.js +167 -0
- package/dist/adapter/figma-hyperlinks.d.ts +13 -0
- package/dist/adapter/figma-hyperlinks.js +77 -0
- package/dist/adapter/figma.d.ts +12 -0
- package/dist/adapter/figma.js +40 -0
- package/dist/adapter/file-components.d.ts +20 -0
- package/dist/adapter/file-components.js +352 -0
- package/dist/adapter/file-resources.d.ts +29 -0
- package/dist/adapter/file-resources.js +851 -0
- package/dist/adapter/image-crop.d.ts +18 -0
- package/dist/adapter/image-crop.js +30 -0
- package/dist/adapter/index.d.ts +6 -0
- package/dist/adapter/index.js +9 -0
- package/dist/adapter/link.d.ts +49 -0
- package/dist/adapter/link.js +892 -0
- package/dist/adapter/payload.d.ts +31 -0
- package/dist/adapter/payload.js +78 -0
- package/dist/adapter/shapes.d.ts +31 -0
- package/dist/adapter/shapes.js +75 -0
- package/dist/adapter/variables.d.ts +45 -0
- package/dist/adapter/variables.js +106 -0
- package/dist/figma-file.d.ts +38 -0
- package/dist/figma-file.js +97 -0
- package/dist/figma-worker.d.ts +11 -0
- package/dist/figma-worker.js +12 -0
- package/dist/figma.d.ts +26 -0
- package/dist/figma.js +230 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +50 -0
- package/dist/report.d.ts +42 -0
- package/dist/report.js +142 -0
- package/dist/serialize.d.ts +7 -0
- package/dist/serialize.js +79 -0
- package/dist/svg.d.ts +33 -0
- package/dist/svg.js +44 -0
- package/dist/syntax.d.ts +8 -0
- package/dist/syntax.js +19 -0
- package/dist/taco/figma-import/clipboard.d.ts +25 -0
- package/dist/taco/figma-import/clipboard.js +87 -0
- package/dist/taco/figma-import/clipboardSize.d.ts +31 -0
- package/dist/taco/figma-import/clipboardSize.js +107 -0
- package/dist/taco/figma-import/container/compression.d.ts +9 -0
- package/dist/taco/figma-import/container/compression.js +174 -0
- package/dist/taco/figma-import/container/error.d.ts +15 -0
- package/dist/taco/figma-import/container/error.js +19 -0
- package/dist/taco/figma-import/container/kiwiContainer.d.ts +41 -0
- package/dist/taco/figma-import/container/kiwiContainer.js +61 -0
- package/dist/taco/figma-import/container/limits.d.ts +22 -0
- package/dist/taco/figma-import/container/limits.js +22 -0
- package/dist/taco/figma-import/container/zip.d.ts +14 -0
- package/dist/taco/figma-import/container/zip.js +154 -0
- package/dist/taco/figma-import/figFile.d.ts +34 -0
- package/dist/taco/figma-import/figFile.js +91 -0
- package/dist/taco/figma-import/figFileDocument.d.ts +25 -0
- package/dist/taco/figma-import/figFileDocument.js +100 -0
- package/dist/taco/figma-import/import/blobs.d.ts +10 -0
- package/dist/taco/figma-import/import/blobs.js +23 -0
- package/dist/taco/figma-import/import/carry.d.ts +24 -0
- package/dist/taco/figma-import/import/carry.js +66 -0
- package/dist/taco/figma-import/import/componentProps.d.ts +90 -0
- package/dist/taco/figma-import/import/componentProps.js +329 -0
- package/dist/taco/figma-import/import/componentSets.d.ts +85 -0
- package/dist/taco/figma-import/import/componentSets.js +647 -0
- package/dist/taco/figma-import/import/converters/effects.d.ts +31 -0
- package/dist/taco/figma-import/import/converters/effects.js +127 -0
- package/dist/taco/figma-import/import/converters/ellipse.d.ts +7 -0
- package/dist/taco/figma-import/import/converters/ellipse.js +54 -0
- package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
- package/dist/taco/figma-import/import/converters/exportSettings.js +49 -0
- package/dist/taco/figma-import/import/converters/frame.d.ts +21 -0
- package/dist/taco/figma-import/import/converters/frame.js +63 -0
- package/dist/taco/figma-import/import/converters/gradient.d.ts +74 -0
- package/dist/taco/figma-import/import/converters/gradient.js +108 -0
- package/dist/taco/figma-import/import/converters/group.d.ts +19 -0
- package/dist/taco/figma-import/import/converters/group.js +30 -0
- package/dist/taco/figma-import/import/converters/image.d.ts +13 -0
- package/dist/taco/figma-import/import/converters/image.js +94 -0
- package/dist/taco/figma-import/import/converters/layout.d.ts +33 -0
- package/dist/taco/figma-import/import/converters/layout.js +187 -0
- package/dist/taco/figma-import/import/converters/line.d.ts +11 -0
- package/dist/taco/figma-import/import/converters/line.js +40 -0
- package/dist/taco/figma-import/import/converters/rectangle.d.ts +3 -0
- package/dist/taco/figma-import/import/converters/rectangle.js +11 -0
- package/dist/taco/figma-import/import/converters/section.d.ts +8 -0
- package/dist/taco/figma-import/import/converters/section.js +29 -0
- package/dist/taco/figma-import/import/converters/shared.d.ts +71 -0
- package/dist/taco/figma-import/import/converters/shared.js +372 -0
- package/dist/taco/figma-import/import/converters/text.d.ts +54 -0
- package/dist/taco/figma-import/import/converters/text.js +707 -0
- package/dist/taco/figma-import/import/converters/vector.d.ts +105 -0
- package/dist/taco/figma-import/import/converters/vector.js +609 -0
- package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +114 -0
- package/dist/taco/figma-import/import/converters/vectorNetwork.js +503 -0
- package/dist/taco/figma-import/import/fields.d.ts +15 -0
- package/dist/taco/figma-import/import/fields.js +29 -0
- package/dist/taco/figma-import/import/instances.d.ts +184 -0
- package/dist/taco/figma-import/import/instances.js +1530 -0
- package/dist/taco/figma-import/import/nestingCycles.d.ts +86 -0
- package/dist/taco/figma-import/import/nestingCycles.js +488 -0
- package/dist/taco/figma-import/import/slots.d.ts +56 -0
- package/dist/taco/figma-import/import/slots.js +96 -0
- package/dist/taco/figma-import/import/styles.d.ts +48 -0
- package/dist/taco/figma-import/import/styles.js +48 -0
- package/dist/taco/figma-import/import/tree.d.ts +66 -0
- package/dist/taco/figma-import/import/tree.js +194 -0
- package/dist/taco/figma-import/import/types.d.ts +232 -0
- package/dist/taco/figma-import/import/types.js +33 -0
- package/dist/taco/figma-import/import/variables.d.ts +137 -0
- package/dist/taco/figma-import/import/variables.js +769 -0
- package/dist/taco/figma-import/import/variantTrees.d.ts +20 -0
- package/dist/taco/figma-import/import/variantTrees.js +520 -0
- package/dist/taco/figma-import/import/walk.d.ts +207 -0
- package/dist/taco/figma-import/import/walk.js +1464 -0
- package/dist/taco/figma-import/index.d.ts +22 -0
- package/dist/taco/figma-import/index.js +13 -0
- package/dist/taco/figma-import/kiwi/byteReader.d.ts +37 -0
- package/dist/taco/figma-import/kiwi/byteReader.js +151 -0
- package/dist/taco/figma-import/kiwi/error.d.ts +14 -0
- package/dist/taco/figma-import/kiwi/error.js +29 -0
- package/dist/taco/figma-import/kiwi/limits.d.ts +18 -0
- package/dist/taco/figma-import/kiwi/limits.js +18 -0
- package/dist/taco/figma-import/kiwi/message.d.ts +12 -0
- package/dist/taco/figma-import/kiwi/message.js +147 -0
- package/dist/taco/figma-import/kiwi/schema.d.ts +42 -0
- package/dist/taco/figma-import/kiwi/schema.js +206 -0
- package/dist/taco/figma-import/kiwi/types.d.ts +46 -0
- package/dist/taco/figma-import/kiwi/types.js +18 -0
- package/dist/taco/model/agent-hidden-fields.d.ts +20 -0
- package/dist/taco/model/agent-hidden-fields.js +29 -0
- package/dist/taco/model/asset-users.d.ts +23 -0
- package/dist/taco/model/asset-users.js +128 -0
- package/dist/taco/model/auto-layout-lines.d.ts +32 -0
- package/dist/taco/model/auto-layout-lines.js +70 -0
- package/dist/taco/model/codec.d.ts +444 -0
- package/dist/taco/model/codec.js +5665 -0
- package/dist/taco/model/color.d.ts +11 -0
- package/dist/taco/model/color.js +61 -0
- package/dist/taco/model/comment-operations.d.ts +102 -0
- package/dist/taco/model/comment-operations.js +227 -0
- package/dist/taco/model/component-evaluation.d.ts +96 -0
- package/dist/taco/model/component-evaluation.js +555 -0
- package/dist/taco/model/component-expressions.d.ts +242 -0
- package/dist/taco/model/component-expressions.js +1082 -0
- package/dist/taco/model/component-properties.d.ts +111 -0
- package/dist/taco/model/component-properties.js +339 -0
- package/dist/taco/model/component-samples.d.ts +83 -0
- package/dist/taco/model/component-samples.js +290 -0
- package/dist/taco/model/component-validity.d.ts +85 -0
- package/dist/taco/model/component-validity.js +397 -0
- package/dist/taco/model/components.d.ts +155 -0
- package/dist/taco/model/components.js +505 -0
- package/dist/taco/model/connector-ends.d.ts +20 -0
- package/dist/taco/model/connector-ends.js +188 -0
- package/dist/taco/model/connector-geometry.d.ts +74 -0
- package/dist/taco/model/connector-geometry.js +293 -0
- package/dist/taco/model/corner-radii.d.ts +26 -0
- package/dist/taco/model/corner-radii.js +47 -0
- package/dist/taco/model/derivations.d.ts +81 -0
- package/dist/taco/model/derivations.js +151 -0
- package/dist/taco/model/export-settings.d.ts +53 -0
- package/dist/taco/model/export-settings.js +156 -0
- package/dist/taco/model/expressions/ast.d.ts +153 -0
- package/dist/taco/model/expressions/ast.js +6 -0
- package/dist/taco/model/expressions/cache.d.ts +23 -0
- package/dist/taco/model/expressions/cache.js +43 -0
- package/dist/taco/model/expressions/check.d.ts +72 -0
- package/dist/taco/model/expressions/check.js +517 -0
- package/dist/taco/model/expressions/completion.d.ts +61 -0
- package/dist/taco/model/expressions/completion.js +421 -0
- package/dist/taco/model/expressions/evaluate.d.ts +32 -0
- package/dist/taco/model/expressions/evaluate.js +519 -0
- package/dist/taco/model/expressions/forms.d.ts +84 -0
- package/dist/taco/model/expressions/forms.js +200 -0
- package/dist/taco/model/expressions/index.d.ts +14 -0
- package/dist/taco/model/expressions/index.js +17 -0
- package/dist/taco/model/expressions/lexer.d.ts +42 -0
- package/dist/taco/model/expressions/lexer.js +213 -0
- package/dist/taco/model/expressions/library.d.ts +33 -0
- package/dist/taco/model/expressions/library.js +117 -0
- package/dist/taco/model/expressions/names.d.ts +43 -0
- package/dist/taco/model/expressions/names.js +99 -0
- package/dist/taco/model/expressions/parser.d.ts +15 -0
- package/dist/taco/model/expressions/parser.js +438 -0
- package/dist/taco/model/expressions/rename.d.ts +34 -0
- package/dist/taco/model/expressions/rename.js +46 -0
- package/dist/taco/model/expressions/source.d.ts +15 -0
- package/dist/taco/model/expressions/source.js +161 -0
- package/dist/taco/model/expressions/types.d.ts +119 -0
- package/dist/taco/model/expressions/types.js +102 -0
- package/dist/taco/model/expressions/values.d.ts +97 -0
- package/dist/taco/model/expressions/values.js +160 -0
- package/dist/taco/model/geometry-limits.d.ts +16 -0
- package/dist/taco/model/geometry-limits.js +67 -0
- package/dist/taco/model/geometry.d.ts +47 -0
- package/dist/taco/model/geometry.js +193 -0
- package/dist/taco/model/group-bounds.d.ts +38 -0
- package/dist/taco/model/group-bounds.js +144 -0
- package/dist/taco/model/id-table.d.ts +37 -0
- package/dist/taco/model/id-table.js +80 -0
- package/dist/taco/model/index.d.ts +25 -0
- package/dist/taco/model/index.js +27 -0
- package/dist/taco/model/instance-resolver.d.ts +376 -0
- package/dist/taco/model/instance-resolver.js +1778 -0
- package/dist/taco/model/layer-syntax.d.ts +340 -0
- package/dist/taco/model/layer-syntax.js +3506 -0
- package/dist/taco/model/layout/constraints.d.ts +84 -0
- package/dist/taco/model/layout/constraints.js +445 -0
- package/dist/taco/model/layout/frame-layout.d.ts +46 -0
- package/dist/taco/model/layout/frame-layout.js +618 -0
- package/dist/taco/model/layout/node-sizing.d.ts +163 -0
- package/dist/taco/model/layout/node-sizing.js +486 -0
- package/dist/taco/model/legacy-connector-caps.d.ts +15 -0
- package/dist/taco/model/legacy-connector-caps.js +70 -0
- package/dist/taco/model/linear-call.d.ts +48 -0
- package/dist/taco/model/linear-call.js +58 -0
- package/dist/taco/model/new-nodes.d.ts +145 -0
- package/dist/taco/model/new-nodes.js +277 -0
- package/dist/taco/model/node-builder.d.ts +449 -0
- package/dist/taco/model/node-builder.js +2294 -0
- package/dist/taco/model/node-table-watch.d.ts +36 -0
- package/dist/taco/model/node-table-watch.js +63 -0
- package/dist/taco/model/node-transform.d.ts +39 -0
- package/dist/taco/model/node-transform.js +79 -0
- package/dist/taco/model/node-users-index.d.ts +10 -0
- package/dist/taco/model/node-users-index.js +82 -0
- package/dist/taco/model/operation-references.d.ts +80 -0
- package/dist/taco/model/operation-references.js +399 -0
- package/dist/taco/model/operations.d.ts +610 -0
- package/dist/taco/model/operations.js +2882 -0
- package/dist/taco/model/overlay-table.d.ts +71 -0
- package/dist/taco/model/overlay-table.js +171 -0
- package/dist/taco/model/override-remap.d.ts +69 -0
- package/dist/taco/model/override-remap.js +230 -0
- package/dist/taco/model/parent-table.d.ts +53 -0
- package/dist/taco/model/parent-table.js +193 -0
- package/dist/taco/model/problem-collector.d.ts +27 -0
- package/dist/taco/model/problem-collector.js +101 -0
- package/dist/taco/model/sha256.d.ts +10 -0
- package/dist/taco/model/sha256.js +79 -0
- package/dist/taco/model/shape-geometry.d.ts +96 -0
- package/dist/taco/model/shape-geometry.js +368 -0
- package/dist/taco/model/shared-node-table.d.ts +97 -0
- package/dist/taco/model/shared-node-table.js +546 -0
- package/dist/taco/model/slots.d.ts +113 -0
- package/dist/taco/model/slots.js +281 -0
- package/dist/taco/model/stroke-settings.d.ts +37 -0
- package/dist/taco/model/stroke-settings.js +90 -0
- package/dist/taco/model/svg-path-import.d.ts +89 -0
- package/dist/taco/model/svg-path-import.js +219 -0
- package/dist/taco/model/text-measurement.d.ts +142 -0
- package/dist/taco/model/text-measurement.js +846 -0
- package/dist/taco/model/text-reads.d.ts +66 -0
- package/dist/taco/model/text-reads.js +128 -0
- package/dist/taco/model/text-sizer.d.ts +358 -0
- package/dist/taco/model/text-sizer.js +996 -0
- package/dist/taco/model/theme-users.d.ts +59 -0
- package/dist/taco/model/theme-users.js +312 -0
- package/dist/taco/model/thumbnail.d.ts +15 -0
- package/dist/taco/model/thumbnail.js +34 -0
- package/dist/taco/model/types.d.ts +2369 -0
- package/dist/taco/model/types.js +366 -0
- package/dist/taco/model/unknown-property.d.ts +5 -0
- package/dist/taco/model/unknown-property.js +7 -0
- package/dist/taco/model/validated-documents.d.ts +22 -0
- package/dist/taco/model/validated-documents.js +22 -0
- package/dist/taco/model/variable-modes.d.ts +61 -0
- package/dist/taco/model/variable-modes.js +438 -0
- package/dist/taco/model/variable-references.d.ts +54 -0
- package/dist/taco/model/variable-references.js +183 -0
- package/dist/taco/model/variables.d.ts +24 -0
- package/dist/taco/model/variables.js +151 -0
- package/dist/taco/model/vector-network.d.ts +34 -0
- package/dist/taco/model/vector-network.js +411 -0
- package/dist/taco/svg-import/import-svg.d.ts +36 -0
- package/dist/taco/svg-import/import-svg.js +729 -0
- package/dist/taco/svg-import/index.d.ts +3 -0
- package/dist/taco/svg-import/index.js +3 -0
- package/dist/taco/svg-import/limits/limits.d.ts +79 -0
- package/dist/taco/svg-import/limits/limits.js +160 -0
- package/dist/taco/svg-import/paint/gradients.d.ts +64 -0
- package/dist/taco/svg-import/paint/gradients.js +429 -0
- package/dist/taco/svg-import/paint/paint.d.ts +32 -0
- package/dist/taco/svg-import/paint/paint.js +162 -0
- package/dist/taco/svg-import/paths/paths.d.ts +58 -0
- package/dist/taco/svg-import/paths/paths.js +205 -0
- package/dist/taco/svg-import/public-types.d.ts +279 -0
- package/dist/taco/svg-import/public-types.js +56 -0
- package/dist/taco/svg-import/report/report.d.ts +44 -0
- package/dist/taco/svg-import/report/report.js +79 -0
- package/dist/taco/svg-import/reuse/reuse.d.ts +99 -0
- package/dist/taco/svg-import/reuse/reuse.js +840 -0
- package/dist/taco/svg-import/shapes/shapes.d.ts +35 -0
- package/dist/taco/svg-import/shapes/shapes.js +386 -0
- package/dist/taco/svg-import/structure/effects.d.ts +26 -0
- package/dist/taco/svg-import/structure/effects.js +618 -0
- package/dist/taco/svg-import/structure/image.d.ts +24 -0
- package/dist/taco/svg-import/structure/image.js +495 -0
- package/dist/taco/svg-import/structure/walk.d.ts +85 -0
- package/dist/taco/svg-import/structure/walk.js +544 -0
- package/dist/taco/svg-import/style/color.d.ts +40 -0
- package/dist/taco/svg-import/style/color.js +275 -0
- package/dist/taco/svg-import/style/computed.d.ts +214 -0
- package/dist/taco/svg-import/style/computed.js +1534 -0
- package/dist/taco/svg-import/style/css.d.ts +127 -0
- package/dist/taco/svg-import/style/css.js +541 -0
- package/dist/taco/svg-import/style/media.d.ts +25 -0
- package/dist/taco/svg-import/style/media.js +307 -0
- package/dist/taco/svg-import/style/properties.d.ts +43 -0
- package/dist/taco/svg-import/style/properties.js +135 -0
- package/dist/taco/svg-import/style/selector-reach.d.ts +30 -0
- package/dist/taco/svg-import/style/selector-reach.js +169 -0
- package/dist/taco/svg-import/style/selector-validity.d.ts +14 -0
- package/dist/taco/svg-import/style/selector-validity.js +307 -0
- package/dist/taco/svg-import/text/text.d.ts +29 -0
- package/dist/taco/svg-import/text/text.js +545 -0
- package/dist/taco/svg-import/transform/matrix.d.ts +111 -0
- package/dist/taco/svg-import/transform/matrix.js +229 -0
- package/dist/taco/svg-import/tree/element-data.d.ts +52 -0
- package/dist/taco/svg-import/tree/element-data.js +155 -0
- package/dist/taco/svg-import/tree/elements.d.ts +36 -0
- package/dist/taco/svg-import/tree/elements.js +121 -0
- package/dist/taco/svg-import/units/length.d.ts +43 -0
- package/dist/taco/svg-import/units/length.js +125 -0
- package/dist/taco/svg-import/units/viewbox.d.ts +35 -0
- package/dist/taco/svg-import/units/viewbox.js +77 -0
- package/package.json +55 -4
|
@@ -0,0 +1,2882 @@
|
|
|
1
|
+
import { clampGeometry } from "./geometry-limits.js";
|
|
2
|
+
import { unknownPropertyMessage } from "./unknown-property.js";
|
|
3
|
+
import { derivations, isFrozenNodeMap, MAX_DERIVATION_STEPS, rememberFrozenNodeMap } from "./derivations.js";
|
|
4
|
+
import { keepAssetUsers, nodesUsingAsset } from "./asset-users.js";
|
|
5
|
+
import { keepThemeUsers, nodesUsingThemeChange } from "./theme-users.js";
|
|
6
|
+
import { connectorsAttachedTo, keepConnectorEnds } from "./connector-ends.js";
|
|
7
|
+
import { fullyValidatedDocuments } from "./validated-documents.js";
|
|
8
|
+
import { attempt, checkAt, collectedProblemCount, isCollectingProblems } from "./problem-collector.js";
|
|
9
|
+
import { ModelError, MODEL_PROBLEM_LIMIT, checkSceneNode, collectModelProblems, limitModelProblems, assertAsset, assertChangedDocument, assertDocumentTheme, assertSceneNode, canonicalJson, cloneJson, deepFreeze, differsInPositionOnly, jsonCodecStats, positionFieldOf, registerDesignOperationCheck, snapshotDocument, } from "./codec.js";
|
|
10
|
+
import { LAYER_PATH_SEPARATOR, isContainerNode, ownedChildIds, isPageCanvasBackground, pageTagsProblem, } from "./types.js";
|
|
11
|
+
import { resolveTextStyle } from "./text-measurement.js";
|
|
12
|
+
import { fitGroupToChildren, nodeDepth } from "./group-bounds.js";
|
|
13
|
+
import { derivedParents, keptParents, parentMapOf, recordChangedNodes, recordParents } from "./parent-table.js";
|
|
14
|
+
import { componentOwningNode, componentReferencesOf, layerPathKey, parseLayerPath, virtualNodeId } from "./components.js";
|
|
15
|
+
import { resolveInstance } from "./instance-resolver.js";
|
|
16
|
+
import { stretchWhereHuggingReplacements } from "./layout/node-sizing.js";
|
|
17
|
+
import { entryOf, putEntry } from "./id-table.js";
|
|
18
|
+
import { getNodeBounds } from "./geometry.js";
|
|
19
|
+
import { canBeThumbnail } from "./thumbnail.js";
|
|
20
|
+
import { nodeTableWatch, nodeTableWithStats } from "./node-table-watch.js";
|
|
21
|
+
import { isSharedNodeTable, sealSharedTable, shareTableIdentity, sharedNodeTableStats, sharedTableCopy, sharedTableDifferences, sharedTableDraft, tableEntries, tableKeys, tableValues } from "./shared-node-table.js";
|
|
22
|
+
import { isSealedOverlay, overlayParts, overlayTable, overlayTableReading, sealOverlay } from "./overlay-table.js";
|
|
23
|
+
import { applyCommentOperation, assertCommentOperationShape, isCommentOperation, } from "./comment-operations.js";
|
|
24
|
+
/**
|
|
25
|
+
* The `type` of every design `DocumentOperation`, in the order the list
|
|
26
|
+
* above gives them. `assertOperation` accepts exactly these and the
|
|
27
|
+
* `COMMENT_OPERATION_TYPES`, which are applied apart from the undo history.
|
|
28
|
+
*/
|
|
29
|
+
export const DOCUMENT_OPERATION_TYPES = Object.freeze([
|
|
30
|
+
"document.set-title", "document.set-metadata", "document.set-thumbnail",
|
|
31
|
+
"node.insert", "node.remove", "node.move", "node.replace", "node.patch",
|
|
32
|
+
"page.insert", "page.remove", "page.move", "page.replace",
|
|
33
|
+
"theme.replace", "asset.put", "asset.remove",
|
|
34
|
+
"component.insert", "component.remove", "component.replace",
|
|
35
|
+
]);
|
|
36
|
+
// Fails to compile when an operation type is missing from the list.
|
|
37
|
+
const everyOperationTypeListed = true;
|
|
38
|
+
void everyOperationTypeListed;
|
|
39
|
+
const createMutableChanges = () => ({
|
|
40
|
+
documentChanged: false,
|
|
41
|
+
themeChanged: false,
|
|
42
|
+
changedNodeIds: new Set(),
|
|
43
|
+
insertedNodeIds: new Set(),
|
|
44
|
+
removedNodeIds: new Set(),
|
|
45
|
+
changedPageIds: new Set(),
|
|
46
|
+
changedAssetIds: new Set(),
|
|
47
|
+
changedComponentIds: new Set(),
|
|
48
|
+
changedCommentThreadIds: new Set(),
|
|
49
|
+
});
|
|
50
|
+
export const modelApplyStats = {
|
|
51
|
+
documentDiffs: 0,
|
|
52
|
+
/** Node entries `diffDocuments` compared. */
|
|
53
|
+
diffNodesCompared: 0,
|
|
54
|
+
operationDeserializes: 0,
|
|
55
|
+
positionMapContainersVisited: 0,
|
|
56
|
+
/** Node maps `node.replace`, `node.patch` and `node.move` copied. */
|
|
57
|
+
replaceNodeMapCopies: 0,
|
|
58
|
+
/** Diffs that read every node entry of both documents to find the ones not shared. */
|
|
59
|
+
diffWholeNodeMapScans: 0,
|
|
60
|
+
/** Layout views (`laidOut`) that read every node of the document to find its texts. */
|
|
61
|
+
laidOutWholeDocumentScans: 0,
|
|
62
|
+
/** Layout views (`laidOut`) that refitted every instance of the shown pages instead of keeping the earlier view's refit. */
|
|
63
|
+
laidOutWholeInstanceRefits: 0,
|
|
64
|
+
/** Operations `deserializeOperations` checked with `assertOperation`. */
|
|
65
|
+
operationChecks: 0,
|
|
66
|
+
/** Edited documents `applyOperations` checked with `assertChangedDocument`. */
|
|
67
|
+
changedDocumentChecks: 0,
|
|
68
|
+
/** Text layout keys (`textLayoutKey`) the layout views worked out. */
|
|
69
|
+
laidOutTextLayoutKeys: 0,
|
|
70
|
+
/** Layout views that refitted every component instance (the component cascade) instead of keeping an earlier view's sizes. */
|
|
71
|
+
laidOutInstanceRefits: 0,
|
|
72
|
+
/** Stored texts the layout views checked against their drawn size (and corrected where it differs). */
|
|
73
|
+
laidOutTextsChecked: 0,
|
|
74
|
+
/** Layers of a layout view's text index that listed their texts by font asset (on a font asset change). */
|
|
75
|
+
laidOutFontAssetListings: 0,
|
|
76
|
+
/**
|
|
77
|
+
* Layout views made by a pass over every text an earlier view corrected, because the view could not be made by
|
|
78
|
+
* writing the edit over the earlier view, counted by the reason it could not (`viewFromEarlierView`).
|
|
79
|
+
*/
|
|
80
|
+
laidOutCorrectionPasses: {},
|
|
81
|
+
/** Layers a layout view made from an earlier one wrote again as stored, with the subtree around an edit it could not write over that view alone. */
|
|
82
|
+
laidOutResetLayers: 0,
|
|
83
|
+
/** Indexes of the nodes that use each asset made by reading every node (`nodesUsingAsset`). */
|
|
84
|
+
assetUsersWholeDocumentScans: 0,
|
|
85
|
+
/** Indexes of the nodes that use each part of the theme made by reading every node (`nodesUsingThemeChange`). */
|
|
86
|
+
themeUsersWholeDocumentScans: 0,
|
|
87
|
+
};
|
|
88
|
+
export function resetModelApplyStats() {
|
|
89
|
+
modelApplyStats.documentDiffs = 0;
|
|
90
|
+
modelApplyStats.diffNodesCompared = 0;
|
|
91
|
+
modelApplyStats.operationDeserializes = 0;
|
|
92
|
+
modelApplyStats.positionMapContainersVisited = 0;
|
|
93
|
+
modelApplyStats.replaceNodeMapCopies = 0;
|
|
94
|
+
modelApplyStats.diffWholeNodeMapScans = 0;
|
|
95
|
+
modelApplyStats.laidOutWholeDocumentScans = 0;
|
|
96
|
+
modelApplyStats.laidOutWholeInstanceRefits = 0;
|
|
97
|
+
modelApplyStats.operationChecks = 0;
|
|
98
|
+
modelApplyStats.changedDocumentChecks = 0;
|
|
99
|
+
modelApplyStats.laidOutTextLayoutKeys = 0;
|
|
100
|
+
modelApplyStats.laidOutInstanceRefits = 0;
|
|
101
|
+
modelApplyStats.laidOutTextsChecked = 0;
|
|
102
|
+
modelApplyStats.assetUsersWholeDocumentScans = 0;
|
|
103
|
+
modelApplyStats.themeUsersWholeDocumentScans = 0;
|
|
104
|
+
modelApplyStats.laidOutFontAssetListings = 0;
|
|
105
|
+
modelApplyStats.laidOutCorrectionPasses = {};
|
|
106
|
+
modelApplyStats.laidOutResetLayers = 0;
|
|
107
|
+
}
|
|
108
|
+
/** The frozen `ChangeSet` returned whenever nothing changed. */
|
|
109
|
+
export const EMPTY_CHANGE_SET = deepFreeze({
|
|
110
|
+
documentChanged: false,
|
|
111
|
+
themeChanged: false,
|
|
112
|
+
changedNodeIds: [],
|
|
113
|
+
insertedNodeIds: [],
|
|
114
|
+
removedNodeIds: [],
|
|
115
|
+
changedPageIds: [],
|
|
116
|
+
changedAssetIds: [],
|
|
117
|
+
changedComponentIds: [],
|
|
118
|
+
changedCommentThreadIds: [],
|
|
119
|
+
});
|
|
120
|
+
const sorted = (values) => [...values].sort();
|
|
121
|
+
function freezeChanges(changes) {
|
|
122
|
+
if (!changes.documentChanged) {
|
|
123
|
+
return EMPTY_CHANGE_SET;
|
|
124
|
+
}
|
|
125
|
+
return deepFreeze({
|
|
126
|
+
documentChanged: true,
|
|
127
|
+
themeChanged: changes.themeChanged,
|
|
128
|
+
changedNodeIds: sorted(changes.changedNodeIds),
|
|
129
|
+
insertedNodeIds: sorted(changes.insertedNodeIds),
|
|
130
|
+
removedNodeIds: sorted(changes.removedNodeIds),
|
|
131
|
+
changedPageIds: sorted(changes.changedPageIds),
|
|
132
|
+
changedAssetIds: sorted(changes.changedAssetIds),
|
|
133
|
+
changedComponentIds: sorted(changes.changedComponentIds),
|
|
134
|
+
changedCommentThreadIds: sorted(changes.changedCommentThreadIds),
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
function mergeChanges(target, source) {
|
|
138
|
+
target.documentChanged ||= source.documentChanged;
|
|
139
|
+
target.themeChanged ||= source.themeChanged;
|
|
140
|
+
source.changedNodeIds.forEach((id) => target.changedNodeIds.add(id));
|
|
141
|
+
source.insertedNodeIds.forEach((id) => target.insertedNodeIds.add(id));
|
|
142
|
+
source.removedNodeIds.forEach((id) => target.removedNodeIds.add(id));
|
|
143
|
+
source.changedPageIds.forEach((id) => target.changedPageIds.add(id));
|
|
144
|
+
source.changedAssetIds.forEach((id) => target.changedAssetIds.add(id));
|
|
145
|
+
source.changedComponentIds.forEach((id) => target.changedComponentIds.add(id));
|
|
146
|
+
source.changedCommentThreadIds.forEach((id) => target.changedCommentThreadIds.add(id));
|
|
147
|
+
}
|
|
148
|
+
function normalizeReinserts(changes) {
|
|
149
|
+
for (const id of [...changes.insertedNodeIds]) {
|
|
150
|
+
if (!changes.removedNodeIds.has(id))
|
|
151
|
+
continue;
|
|
152
|
+
changes.insertedNodeIds.delete(id);
|
|
153
|
+
changes.removedNodeIds.delete(id);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const definedKeys = (value) => Object.keys(value).filter((key) => value[key] !== undefined);
|
|
157
|
+
/**
|
|
158
|
+
* Reports whether two JSON values carry the same content, ignoring key order
|
|
159
|
+
* and `undefined` entries exactly as the canonical JSON codec does.
|
|
160
|
+
*
|
|
161
|
+
* Documents reuse every unchanged part, so comparing by identity first settles
|
|
162
|
+
* most calls without reading the values. Serializing both sides instead would
|
|
163
|
+
* make each comparison cost as much as the whole document.
|
|
164
|
+
*/
|
|
165
|
+
function same(left, right) {
|
|
166
|
+
if (left === right)
|
|
167
|
+
return true;
|
|
168
|
+
if (left === undefined ||
|
|
169
|
+
right === undefined ||
|
|
170
|
+
typeof left !== "object" ||
|
|
171
|
+
typeof right !== "object" ||
|
|
172
|
+
left === null ||
|
|
173
|
+
right === null) {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
177
|
+
return (Array.isArray(left) &&
|
|
178
|
+
Array.isArray(right) &&
|
|
179
|
+
left.length === right.length &&
|
|
180
|
+
left.every((entry, index) => same(entry, right[index])));
|
|
181
|
+
}
|
|
182
|
+
const leftRecord = left;
|
|
183
|
+
const rightRecord = right;
|
|
184
|
+
const leftKeys = definedKeys(leftRecord);
|
|
185
|
+
if (leftKeys.length !== definedKeys(rightRecord).length) {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
// An entry named `__proto__` that only the left side has must not be compared with what every object inherits.
|
|
189
|
+
return leftKeys.every((key) => Object.hasOwn(rightRecord, key) && same(leftRecord[key], rightRecord[key]));
|
|
190
|
+
}
|
|
191
|
+
function addPaintAssets(paints, add) {
|
|
192
|
+
for (const paint of paints ?? [])
|
|
193
|
+
if (paint.kind === "image")
|
|
194
|
+
add(paint.assetId);
|
|
195
|
+
}
|
|
196
|
+
/** Adds the assets a frame or shape paints through an image fill or stroke. */
|
|
197
|
+
function addVisualStyleAssets(document, node, add) {
|
|
198
|
+
const style = node.style;
|
|
199
|
+
const shared = style?.styleId === undefined ? undefined : entryOf(document.theme.nodeStyles, style.styleId);
|
|
200
|
+
addPaintAssets(style?.fills ?? shared?.fills, add);
|
|
201
|
+
for (const stroke of style?.strokes ?? shared?.strokes ?? [])
|
|
202
|
+
addPaintAssets([stroke.paint], add);
|
|
203
|
+
if (node.type === "shape" && node.shape === "path") {
|
|
204
|
+
for (const region of node.vectorNetwork.regions)
|
|
205
|
+
addPaintAssets(region.fills, add);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* The assets `node` shows or draws with: an image or video layer's asset, an image fill or stroke (in its style, its
|
|
210
|
+
* shared style or a path's regions), an instance override, or a font of its text or code. Each is listed once; the
|
|
211
|
+
* list is empty for a node that uses none. It reads the node and the theme, and no asset entry, so the list holds
|
|
212
|
+
* while those stay the same, whatever assets the document gains or loses.
|
|
213
|
+
*/
|
|
214
|
+
export function assetsUsedByNode(document, node) {
|
|
215
|
+
const found = new Set();
|
|
216
|
+
const add = (assetId) => {
|
|
217
|
+
found.add(assetId);
|
|
218
|
+
};
|
|
219
|
+
if (node.type === "image" || node.type === "video") {
|
|
220
|
+
add(node.assetId);
|
|
221
|
+
}
|
|
222
|
+
else if (node.type === "instance") {
|
|
223
|
+
for (const override of Object.values(node.overrides ?? {})) {
|
|
224
|
+
const shared = typeof override.styleId === "string" ? entryOf(document.theme.nodeStyles, override.styleId) : undefined;
|
|
225
|
+
if (override.imageAssetId !== undefined && override.imageAssetId !== null)
|
|
226
|
+
add(override.imageAssetId);
|
|
227
|
+
addPaintAssets(override.fills, add);
|
|
228
|
+
for (const stroke of override.strokes ?? [])
|
|
229
|
+
addPaintAssets([stroke.paint], add);
|
|
230
|
+
addPaintAssets(shared?.fills, add);
|
|
231
|
+
for (const stroke of shared?.strokes ?? [])
|
|
232
|
+
addPaintAssets([stroke.paint], add);
|
|
233
|
+
if (override.textStyleId !== undefined || override.textStyle !== undefined) {
|
|
234
|
+
addTextStyleAssets(document, override.textStyleId ?? undefined, override.textStyle, add);
|
|
235
|
+
}
|
|
236
|
+
if (override.paragraphs !== undefined)
|
|
237
|
+
addParagraphAssets(document, override.paragraphs, add);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
else if (node.type === "frame" || node.type === "shape") {
|
|
241
|
+
addVisualStyleAssets(document, node, add);
|
|
242
|
+
}
|
|
243
|
+
else if (node.type === "code") {
|
|
244
|
+
const styleId = node.codeStyleId ?? document.theme.defaultCodeStyleId;
|
|
245
|
+
const fontAssetId = entryOf(document.theme.codeStyles, styleId)?.fontAssetId;
|
|
246
|
+
if (fontAssetId !== undefined)
|
|
247
|
+
add(fontAssetId);
|
|
248
|
+
}
|
|
249
|
+
else if (node.type === "text") {
|
|
250
|
+
addParagraphAssets(document, node.paragraphs, add);
|
|
251
|
+
}
|
|
252
|
+
return [...found];
|
|
253
|
+
}
|
|
254
|
+
/** True when `node` shows or draws with the asset `assetId` (`assetsUsedByNode`). */
|
|
255
|
+
export function nodeUsesAsset(document, node, assetId) {
|
|
256
|
+
return assetsUsedByNode(document, node).includes(assetId);
|
|
257
|
+
}
|
|
258
|
+
function addTextStyleAssets(document, styleId, overrides, add) {
|
|
259
|
+
const style = resolveTextStyle(document, styleId, overrides);
|
|
260
|
+
if (style.fontAssetId !== undefined)
|
|
261
|
+
add(style.fontAssetId);
|
|
262
|
+
for (const assetId of style.fontFallbackAssetIds ?? [])
|
|
263
|
+
add(assetId);
|
|
264
|
+
}
|
|
265
|
+
/** Adds the font assets the runs and list markers of the paragraphs resolve to. */
|
|
266
|
+
function addParagraphAssets(document, paragraphs, add) {
|
|
267
|
+
for (const paragraph of paragraphs) {
|
|
268
|
+
if (paragraph.runs.length === 0)
|
|
269
|
+
addTextStyleAssets(document, undefined, undefined, add);
|
|
270
|
+
for (const run of paragraph.runs)
|
|
271
|
+
addTextStyleAssets(document, run.styleId, run.overrides, add);
|
|
272
|
+
const marker = paragraph.list?.marker;
|
|
273
|
+
if (marker === undefined)
|
|
274
|
+
continue;
|
|
275
|
+
const firstRun = paragraph.runs[0];
|
|
276
|
+
addTextStyleAssets(document, marker.styleId ?? firstRun?.styleId, marker.overrides ?? firstRun?.overrides, add);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** Refuses an operation; `parts` are the parts of the document the refusal depends on (`ModelError.parts`). */
|
|
280
|
+
function operationError(message, path = "$operations", parts) {
|
|
281
|
+
throw new ModelError("INVALID_SCHEMA", message, path, parts === undefined ? undefined : { parts });
|
|
282
|
+
}
|
|
283
|
+
function requireRecord(value, path) {
|
|
284
|
+
if (typeof value !== "object" ||
|
|
285
|
+
value === null ||
|
|
286
|
+
Array.isArray(value) ||
|
|
287
|
+
Object.getPrototypeOf(value) !== Object.prototype) {
|
|
288
|
+
operationError("Expected an object", path);
|
|
289
|
+
}
|
|
290
|
+
return value;
|
|
291
|
+
}
|
|
292
|
+
function requireOnlyKeys(value, allowed, path) {
|
|
293
|
+
const allowedKeys = new Set(allowed);
|
|
294
|
+
for (const key of Object.keys(value)) {
|
|
295
|
+
if (!allowedKeys.has(key)) {
|
|
296
|
+
attempt((candidate, candidatePath) => {
|
|
297
|
+
operationError(unknownPropertyMessage(candidate, allowed), candidatePath);
|
|
298
|
+
}, key, `${path}.${key}`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function requireString(value, path, allowEmpty = false) {
|
|
303
|
+
if (typeof value !== "string" || (!allowEmpty && value.length === 0)) {
|
|
304
|
+
operationError("Expected a string", path);
|
|
305
|
+
}
|
|
306
|
+
return value;
|
|
307
|
+
}
|
|
308
|
+
function requireAnyString(value, path) {
|
|
309
|
+
return requireString(value, path, true);
|
|
310
|
+
}
|
|
311
|
+
function requireIndex(value, path) {
|
|
312
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
|
|
313
|
+
operationError("Expected a non-negative integer", path);
|
|
314
|
+
}
|
|
315
|
+
return value;
|
|
316
|
+
}
|
|
317
|
+
/** Checks a subtree, and returns its root ID when that ID passed its own checks. */
|
|
318
|
+
function validateSubtree(value, path) {
|
|
319
|
+
// Nothing in a subtree that is not an object can be checked, so this one throws.
|
|
320
|
+
const subtree = requireRecord(value, path);
|
|
321
|
+
requireOnlyKeys(subtree, ["rootId", "nodes"], path);
|
|
322
|
+
const before = collectedProblemCount();
|
|
323
|
+
let rootId = attempt(requireString, subtree.rootId, `${path}.rootId`);
|
|
324
|
+
const nodes = attempt(requireRecord, subtree.nodes, `${path}.nodes`);
|
|
325
|
+
if (nodes === undefined)
|
|
326
|
+
return rootId;
|
|
327
|
+
if (rootId !== undefined && entryOf(nodes, rootId) === undefined) {
|
|
328
|
+
attempt((_, candidatePath) => operationError("Subtree root is missing from its node map", candidatePath), rootId, `${path}.rootId`);
|
|
329
|
+
rootId = undefined;
|
|
330
|
+
}
|
|
331
|
+
// The nodes that passed their own checks; only their children are read below.
|
|
332
|
+
const wellFormed = [];
|
|
333
|
+
for (const [key, node] of tableEntries(nodes)) {
|
|
334
|
+
const nodeBefore = collectedProblemCount();
|
|
335
|
+
attempt((candidate) => {
|
|
336
|
+
// The node's problems are at its place in the subtree, so two nodes with the same problem stay two.
|
|
337
|
+
checkAt(assertSceneNode, candidate, `${path}.nodes.${key}`);
|
|
338
|
+
// An ID that failed its own check in `assertSceneNode` is one problem; it is not also compared with its key.
|
|
339
|
+
const id = candidate.id;
|
|
340
|
+
const idPassed = typeof id === "string" && id.length > 0 && !id.includes(LAYER_PATH_SEPARATOR);
|
|
341
|
+
if (idPassed && id !== key) {
|
|
342
|
+
operationError("Node key must match node.id", `${path}.nodes.${key}.id`);
|
|
343
|
+
}
|
|
344
|
+
}, node, `${path}.nodes.${key}`);
|
|
345
|
+
if (collectedProblemCount() === nodeBefore)
|
|
346
|
+
wellFormed.push(key);
|
|
347
|
+
}
|
|
348
|
+
// A bad node does not hide the child problems of the others.
|
|
349
|
+
const parents = new Map();
|
|
350
|
+
for (const parentId of wellFormed) {
|
|
351
|
+
const node = entryOf(nodes, parentId);
|
|
352
|
+
const localChildren = new Set();
|
|
353
|
+
ownedChildIds(node).forEach((childId, index) => attempt((_, childPath) => {
|
|
354
|
+
if (localChildren.has(childId))
|
|
355
|
+
operationError(`Duplicate child ${childId}`, childPath);
|
|
356
|
+
localChildren.add(childId);
|
|
357
|
+
if (entryOf(nodes, childId) === undefined)
|
|
358
|
+
operationError(`Missing subtree node ${childId}`, childPath);
|
|
359
|
+
if (parents.has(childId))
|
|
360
|
+
operationError(`Node ${childId} has more than one parent`, childPath);
|
|
361
|
+
parents.set(childId, parentId);
|
|
362
|
+
}, childId, `${path}.nodes.${parentId}.children[${index}]`));
|
|
363
|
+
}
|
|
364
|
+
if (rootId === undefined)
|
|
365
|
+
return undefined;
|
|
366
|
+
if (parents.has(rootId)) {
|
|
367
|
+
attempt((_, candidatePath) => operationError("Subtree root cannot have a parent inside the subtree", candidatePath), rootId, `${path}.rootId`);
|
|
368
|
+
return undefined;
|
|
369
|
+
}
|
|
370
|
+
// The walk from the root needs every node to be well formed and every child to exist. It stops at the
|
|
371
|
+
// first cycle, and the count of unreachable nodes is taken after it, so each of these two throws stays one problem.
|
|
372
|
+
if (collectedProblemCount() > before)
|
|
373
|
+
return rootId;
|
|
374
|
+
const visited = new Set();
|
|
375
|
+
const active = new Set();
|
|
376
|
+
const visit = (id) => {
|
|
377
|
+
if (active.has(id))
|
|
378
|
+
operationError(`Subtree contains a cycle at ${id}`, `${path}.nodes.${id}`);
|
|
379
|
+
if (visited.has(id))
|
|
380
|
+
return;
|
|
381
|
+
active.add(id);
|
|
382
|
+
visited.add(id);
|
|
383
|
+
const node = entryOf(nodes, id);
|
|
384
|
+
ownedChildIds(node).forEach(visit);
|
|
385
|
+
active.delete(id);
|
|
386
|
+
};
|
|
387
|
+
// A problem in the tree's shape is not a problem with the root ID, so it is recorded here.
|
|
388
|
+
attempt(() => {
|
|
389
|
+
visit(rootId);
|
|
390
|
+
if (visited.size !== tableKeys(nodes).length) {
|
|
391
|
+
operationError("Subtree contains unreachable nodes", `${path}.nodes`);
|
|
392
|
+
}
|
|
393
|
+
}, nodes, `${path}.nodes`);
|
|
394
|
+
return rootId;
|
|
395
|
+
}
|
|
396
|
+
/** Checks a component definition, and returns its root ID when that ID passed its own check. */
|
|
397
|
+
function validateComponentDefinition(value, path) {
|
|
398
|
+
const component = requireRecord(value, path);
|
|
399
|
+
requireOnlyKeys(component, ["id", "key", "name", "description", "rootId", "properties", "validity", "metadata"], path);
|
|
400
|
+
attempt(requireString, component.id, `${path}.id`);
|
|
401
|
+
attempt(requireString, component.key, `${path}.key`);
|
|
402
|
+
attempt(requireString, component.name, `${path}.name`);
|
|
403
|
+
if (component.description !== undefined) {
|
|
404
|
+
attempt(requireAnyString, component.description, `${path}.description`);
|
|
405
|
+
}
|
|
406
|
+
const rootId = attempt(requireString, component.rootId, `${path}.rootId`);
|
|
407
|
+
// The document check after the operation checks the expression against the properties.
|
|
408
|
+
if (component.validity !== undefined)
|
|
409
|
+
attempt(requireAnyString, component.validity, `${path}.validity`);
|
|
410
|
+
if (component.metadata !== undefined) {
|
|
411
|
+
attempt(requireRecord, component.metadata, `${path}.metadata`);
|
|
412
|
+
}
|
|
413
|
+
return rootId;
|
|
414
|
+
}
|
|
415
|
+
function validatePage(value, path) {
|
|
416
|
+
const page = requireRecord(value, path);
|
|
417
|
+
requireOnlyKeys(page, ["id", "name", "rootId", "guides", "variableModes", "canvasBackground", "tags", "removable", "metadata"], path);
|
|
418
|
+
attempt(requireString, page.id, `${path}.id`);
|
|
419
|
+
attempt(requireString, page.name, `${path}.name`);
|
|
420
|
+
attempt(requireString, page.rootId, `${path}.rootId`);
|
|
421
|
+
// The document check after the operation validates each guide.
|
|
422
|
+
if (page.guides !== undefined && !Array.isArray(page.guides)) {
|
|
423
|
+
attempt((_, candidatePath) => operationError("Expected an array", candidatePath), page.guides, `${path}.guides`);
|
|
424
|
+
}
|
|
425
|
+
if (page.canvasBackground !== undefined && !isPageCanvasBackground(page.canvasBackground)) {
|
|
426
|
+
attempt((_, candidatePath) => operationError("Expected # and six hexadecimal digits, such as #1e1e1e", candidatePath), page.canvasBackground, `${path}.canvasBackground`);
|
|
427
|
+
}
|
|
428
|
+
if (page.tags !== undefined) {
|
|
429
|
+
const problem = pageTagsProblem(page.tags);
|
|
430
|
+
if (problem !== null)
|
|
431
|
+
attempt((_, candidatePath) => operationError(problem, candidatePath), page.tags, `${path}.tags`);
|
|
432
|
+
}
|
|
433
|
+
if (page.removable !== undefined && page.removable !== false) {
|
|
434
|
+
attempt((_, candidatePath) => operationError("Expected false, or no removable at all for a page that can be deleted", candidatePath), page.removable, `${path}.removable`);
|
|
435
|
+
}
|
|
436
|
+
if (page.metadata !== undefined) {
|
|
437
|
+
attempt(requireRecord, page.metadata, `${path}.metadata`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Checks the shape of one operation: its `type`, its exact keys, and any
|
|
442
|
+
* node, page, theme or asset it carries. Whether it fits a particular
|
|
443
|
+
* document is only checked by `applyOperations`. Throws a `ModelError`.
|
|
444
|
+
*/
|
|
445
|
+
export function assertOperation(value) {
|
|
446
|
+
// These three throw: a value that is not JSON, not an object, or has no type has no fields to check.
|
|
447
|
+
canonicalJson(value);
|
|
448
|
+
const operation = requireRecord(value, "$operation");
|
|
449
|
+
const type = requireString(operation.type, "$operation.type");
|
|
450
|
+
switch (type) {
|
|
451
|
+
case "document.set-title":
|
|
452
|
+
requireOnlyKeys(operation, ["type", "title"], "$operation");
|
|
453
|
+
attempt(requireAnyString, operation.title, "$operation.title");
|
|
454
|
+
return;
|
|
455
|
+
case "document.set-metadata":
|
|
456
|
+
requireOnlyKeys(operation, ["type", "metadata"], "$operation");
|
|
457
|
+
if (operation.metadata !== null) {
|
|
458
|
+
attempt(requireRecord, operation.metadata, "$operation.metadata");
|
|
459
|
+
}
|
|
460
|
+
return;
|
|
461
|
+
case "document.set-thumbnail":
|
|
462
|
+
requireOnlyKeys(operation, ["type", "nodeId"], "$operation");
|
|
463
|
+
if (operation.nodeId !== null)
|
|
464
|
+
attempt(requireString, operation.nodeId, "$operation.nodeId");
|
|
465
|
+
return;
|
|
466
|
+
case "node.insert":
|
|
467
|
+
requireOnlyKeys(operation, ["type", "parentId", "index", "subtree", "slot"], "$operation");
|
|
468
|
+
attempt(requireString, operation.parentId, "$operation.parentId");
|
|
469
|
+
attempt(requireIndex, operation.index, "$operation.index");
|
|
470
|
+
attempt(validateSubtree, operation.subtree, "$operation.subtree");
|
|
471
|
+
if (operation.slot !== undefined) {
|
|
472
|
+
attempt((value, path) => {
|
|
473
|
+
const slot = requireRecord(value, path);
|
|
474
|
+
requireOnlyKeys(slot, ["instanceId", "path", "propertyId"], path);
|
|
475
|
+
attempt(requireString, slot.instanceId, `${path}.instanceId`);
|
|
476
|
+
attempt(requireString, slot.propertyId, `${path}.propertyId`);
|
|
477
|
+
if (slot.path !== undefined) {
|
|
478
|
+
attempt((entries, entriesPath) => {
|
|
479
|
+
if (!Array.isArray(entries))
|
|
480
|
+
operationError("A slot path must be a list of node IDs", entriesPath);
|
|
481
|
+
entries.forEach((entry, index) => attempt(requireString, entry, `${entriesPath}[${index}]`));
|
|
482
|
+
}, slot.path, `${path}.path`);
|
|
483
|
+
}
|
|
484
|
+
}, operation.slot, "$operation.slot");
|
|
485
|
+
}
|
|
486
|
+
return;
|
|
487
|
+
case "node.remove":
|
|
488
|
+
requireOnlyKeys(operation, ["type", "nodeId"], "$operation");
|
|
489
|
+
attempt(requireString, operation.nodeId, "$operation.nodeId");
|
|
490
|
+
return;
|
|
491
|
+
case "node.move":
|
|
492
|
+
requireOnlyKeys(operation, ["type", "nodeId", "newParentId", "index"], "$operation");
|
|
493
|
+
attempt(requireString, operation.nodeId, "$operation.nodeId");
|
|
494
|
+
attempt(requireString, operation.newParentId, "$operation.newParentId");
|
|
495
|
+
attempt(requireIndex, operation.index, "$operation.index");
|
|
496
|
+
return;
|
|
497
|
+
case "node.replace":
|
|
498
|
+
requireOnlyKeys(operation, ["type", "node"], "$operation");
|
|
499
|
+
attempt(assertSceneNode, operation.node, "$");
|
|
500
|
+
return;
|
|
501
|
+
case "node.patch": {
|
|
502
|
+
requireOnlyKeys(operation, ["type", "nodeId", "fields", "remove"], "$operation");
|
|
503
|
+
attempt(requireString, operation.nodeId, "$operation.nodeId");
|
|
504
|
+
// A failed fields record is one problem; remove is still checked, against no written fields.
|
|
505
|
+
const fields = attempt(requireRecord, operation.fields, "$operation.fields") ?? {};
|
|
506
|
+
for (const field of Object.keys(fields)) {
|
|
507
|
+
if (UNPATCHABLE_FIELDS.has(field)) {
|
|
508
|
+
attempt((_, candidatePath) => operationError(`node.patch cannot change a node's ${field}`, candidatePath), fields[field], `$operation.fields.${field}`);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (operation.remove !== undefined) {
|
|
512
|
+
const remove = attempt((candidate, candidatePath) => Array.isArray(candidate)
|
|
513
|
+
? candidate : operationError("Expected an array of field names", candidatePath), operation.remove, "$operation.remove") ?? [];
|
|
514
|
+
const removed = new Set();
|
|
515
|
+
remove.forEach((field, index) => attempt((candidate, candidatePath) => {
|
|
516
|
+
const name = requireString(candidate, candidatePath);
|
|
517
|
+
if (UNPATCHABLE_FIELDS.has(name) || name === "children") {
|
|
518
|
+
operationError(`node.patch cannot remove a node's ${name}`, candidatePath);
|
|
519
|
+
}
|
|
520
|
+
if (Object.hasOwn(fields, name)) {
|
|
521
|
+
operationError(`${name} is both written and removed`, candidatePath);
|
|
522
|
+
}
|
|
523
|
+
if (removed.has(name))
|
|
524
|
+
operationError(`${name} is removed twice`, candidatePath);
|
|
525
|
+
removed.add(name);
|
|
526
|
+
}, field, `$operation.remove.${index}`));
|
|
527
|
+
}
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
case "page.insert":
|
|
531
|
+
requireOnlyKeys(operation, ["type", "index", "page", "subtree"], "$operation");
|
|
532
|
+
attempt(requireIndex, operation.index, "$operation.index");
|
|
533
|
+
attempt(validatePage, operation.page, "$operation.page");
|
|
534
|
+
attempt(validateSubtree, operation.subtree, "$operation.subtree");
|
|
535
|
+
return;
|
|
536
|
+
case "page.remove":
|
|
537
|
+
case "page.move":
|
|
538
|
+
requireOnlyKeys(operation, type === "page.move" ? ["type", "pageId", "index"] : ["type", "pageId"], "$operation");
|
|
539
|
+
attempt(requireString, operation.pageId, "$operation.pageId");
|
|
540
|
+
if (type === "page.move") {
|
|
541
|
+
attempt(requireIndex, operation.index, "$operation.index");
|
|
542
|
+
}
|
|
543
|
+
return;
|
|
544
|
+
case "page.replace":
|
|
545
|
+
requireOnlyKeys(operation, ["type", "page"], "$operation");
|
|
546
|
+
attempt(validatePage, operation.page, "$operation.page");
|
|
547
|
+
return;
|
|
548
|
+
case "theme.replace":
|
|
549
|
+
requireOnlyKeys(operation, ["type", "theme"], "$operation");
|
|
550
|
+
attempt(assertDocumentTheme, operation.theme, "$");
|
|
551
|
+
return;
|
|
552
|
+
case "asset.put": {
|
|
553
|
+
requireOnlyKeys(operation, ["type", "asset"], "$operation");
|
|
554
|
+
attempt(assertAsset, operation.asset, "$");
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
case "asset.remove":
|
|
558
|
+
requireOnlyKeys(operation, ["type", "assetId"], "$operation");
|
|
559
|
+
attempt(requireString, operation.assetId, "$operation.assetId");
|
|
560
|
+
return;
|
|
561
|
+
case "component.insert": {
|
|
562
|
+
requireOnlyKeys(operation, ["type", "component", "subtree"], "$operation");
|
|
563
|
+
const componentRootId = attempt(validateComponentDefinition, operation.component, "$operation.component");
|
|
564
|
+
const subtreeRootId = attempt(validateSubtree, operation.subtree, "$operation.subtree");
|
|
565
|
+
// A root ID that failed its own check is not compared; problems elsewhere do not hide this one.
|
|
566
|
+
if (componentRootId !== undefined && subtreeRootId !== undefined && componentRootId !== subtreeRootId) {
|
|
567
|
+
operationError("Component root must match subtree root", "$operation.subtree.rootId");
|
|
568
|
+
}
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
case "component.remove":
|
|
572
|
+
requireOnlyKeys(operation, ["type", "componentId"], "$operation");
|
|
573
|
+
attempt(requireString, operation.componentId, "$operation.componentId");
|
|
574
|
+
return;
|
|
575
|
+
case "component.replace":
|
|
576
|
+
requireOnlyKeys(operation, ["type", "component"], "$operation");
|
|
577
|
+
attempt(validateComponentDefinition, operation.component, "$operation.component");
|
|
578
|
+
return;
|
|
579
|
+
default:
|
|
580
|
+
if (isCommentOperation({ type })) {
|
|
581
|
+
assertCommentOperationShape(operation);
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
operationError(`Unknown operation type ${type}`, "$operation.type");
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
registerDesignOperationCheck(assertOperation);
|
|
588
|
+
/**
|
|
589
|
+
* Checks one operation as `assertOperation` does, with the same checks, but
|
|
590
|
+
* returns every problem instead of throwing the first: each field and each
|
|
591
|
+
* node of a subtree is checked, and a value that failed counts once, without
|
|
592
|
+
* the problems inside it. Empty when `assertOperation` accepts it; otherwise
|
|
593
|
+
* the first problem is the error it throws. Problems inside a node of a
|
|
594
|
+
* subtree are at its place there (`$operation.subtree.nodes.n1.rotation`), and
|
|
595
|
+
* those of the node of a `node.replace` at its own paths (`$.rotation`), as
|
|
596
|
+
* `assertOperation` reports them. At most
|
|
597
|
+
* `limit` (`MODEL_PROBLEM_LIMIT` when omitted), then "and N more".
|
|
598
|
+
*/
|
|
599
|
+
export function checkOperation(value, limit) {
|
|
600
|
+
return collectModelProblems(() => assertOperation(value), limit);
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Operations `deserializeOperations` returned: checked by `assertOperation`
|
|
604
|
+
* and frozen all the way down, so checking them again would give the same
|
|
605
|
+
* answer. Only passes are kept.
|
|
606
|
+
*/
|
|
607
|
+
const checkedOperations = new WeakSet();
|
|
608
|
+
/**
|
|
609
|
+
* Reads a list of operations from a JSON string or a parsed value, checks
|
|
610
|
+
* each with `assertOperation`, and returns a deeply frozen copy. Throws a
|
|
611
|
+
* `ModelError` (`INVALID_JSON` for a string that does not parse).
|
|
612
|
+
*
|
|
613
|
+
* An operation this function returned before is taken as it is, unchecked:
|
|
614
|
+
* it is frozen, so it cannot have changed since its check; only the list
|
|
615
|
+
* is new. So an edit that passes through
|
|
616
|
+
* several steps (planning, then the store, then `applyOperations`) checks
|
|
617
|
+
* each operation once.
|
|
618
|
+
*/
|
|
619
|
+
export function deserializeOperations(input) {
|
|
620
|
+
modelApplyStats.operationDeserializes += 1;
|
|
621
|
+
let raw;
|
|
622
|
+
if (typeof input === "string") {
|
|
623
|
+
try {
|
|
624
|
+
raw = JSON.parse(input);
|
|
625
|
+
}
|
|
626
|
+
catch (error) {
|
|
627
|
+
throw new ModelError("INVALID_JSON", "Could not parse operations JSON", "$", {
|
|
628
|
+
cause: error,
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
else {
|
|
633
|
+
raw = input;
|
|
634
|
+
}
|
|
635
|
+
if (!Array.isArray(raw)) {
|
|
636
|
+
operationError("Operations must be an array");
|
|
637
|
+
}
|
|
638
|
+
// Indexed loops, not `every` or `map`: those skip holes, and a caller's
|
|
639
|
+
// array can replace them with methods of its own. Each entry is read once,
|
|
640
|
+
// and the result is always a new list of what was read, so an entry that
|
|
641
|
+
// is a getter cannot give one operation to the check and another later.
|
|
642
|
+
// A list with holes is refused here.
|
|
643
|
+
const keepChecked = !isCollectingProblems();
|
|
644
|
+
const operations = new Array(raw.length);
|
|
645
|
+
for (let index = 0; index < raw.length; index += 1) {
|
|
646
|
+
if (!(index in raw)) {
|
|
647
|
+
throw new ModelError("INVALID_JSON", "Sparse arrays are not supported", `$[${index}]`);
|
|
648
|
+
}
|
|
649
|
+
const operation = raw[index];
|
|
650
|
+
if (checkedOperations.has(operation)) {
|
|
651
|
+
operations[index] = operation;
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
modelApplyStats.operationChecks += 1;
|
|
655
|
+
assertOperation(operation);
|
|
656
|
+
const copy = deepFreeze(clampGeometry(JSON.parse(canonicalJson(operation))));
|
|
657
|
+
// A check that collects problems instead of throwing can let a bad
|
|
658
|
+
// operation through, so what it passes is not kept as checked.
|
|
659
|
+
if (keepChecked)
|
|
660
|
+
checkedOperations.add(copy);
|
|
661
|
+
operations[index] = copy;
|
|
662
|
+
}
|
|
663
|
+
return Object.freeze(operations);
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Takes `node.replace` operations the model made itself, each a node of a
|
|
667
|
+
* frozen, checked document with a new frame (the layout view's text
|
|
668
|
+
* corrections, `laidOut`, and the layout that follows them), as read by
|
|
669
|
+
* `deserializeOperations`: each is frozen all the way down and is then
|
|
670
|
+
* taken as it is, without the check and the copy. A view corrects every
|
|
671
|
+
* shown text of a page at once, and the copies cost more than laying the
|
|
672
|
+
* page out. Applying them still checks the nodes they write
|
|
673
|
+
* (`assertChangedDocument`). Any other operation is left to the full read.
|
|
674
|
+
* Not for operations read from an agent, a file, a paste or history.
|
|
675
|
+
*/
|
|
676
|
+
export function readAsMadeByModel(operations) {
|
|
677
|
+
if (isCollectingProblems())
|
|
678
|
+
return operations;
|
|
679
|
+
let read;
|
|
680
|
+
operations.forEach((operation, index) => {
|
|
681
|
+
if (operation.type !== "node.replace" || checkedOperations.has(operation))
|
|
682
|
+
return;
|
|
683
|
+
const copy = deepFreeze({ type: "node.replace", node: clampGeometry(canonicalNewParts(operation.node)) });
|
|
684
|
+
checkedOperations.add(copy);
|
|
685
|
+
(read ??= [...operations])[index] = copy;
|
|
686
|
+
});
|
|
687
|
+
return read === undefined ? operations : Object.freeze(read);
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* `value` as `canonicalJson` would write it and a read would give it back
|
|
691
|
+
* (keys sorted, no `undefined` entries, -0 as 0), copied only where it
|
|
692
|
+
* differs: a frozen part already written that way, as every part of a
|
|
693
|
+
* document read from JSON is, is kept as it is.
|
|
694
|
+
*/
|
|
695
|
+
function canonicalNewParts(value) {
|
|
696
|
+
if (typeof value === "number")
|
|
697
|
+
return value === 0 ? 0 : value;
|
|
698
|
+
if (typeof value !== "object" || value === null || isCanonicalFrozen(value))
|
|
699
|
+
return value;
|
|
700
|
+
if (Array.isArray(value))
|
|
701
|
+
return value.map(canonicalNewParts);
|
|
702
|
+
const copy = {};
|
|
703
|
+
for (const key of Object.keys(value).sort()) {
|
|
704
|
+
const entry = value[key];
|
|
705
|
+
if (entry !== undefined)
|
|
706
|
+
putEntry(copy, key, canonicalNewParts(entry));
|
|
707
|
+
}
|
|
708
|
+
return copy;
|
|
709
|
+
}
|
|
710
|
+
/** Frozen values found written as `canonicalJson` writes them; they cannot change. */
|
|
711
|
+
const canonicalFrozen = new WeakSet();
|
|
712
|
+
/** Whether `value` is frozen and written as `canonicalJson` writes it, all the way down. */
|
|
713
|
+
function isCanonicalFrozen(value) {
|
|
714
|
+
if (canonicalFrozen.has(value))
|
|
715
|
+
return true;
|
|
716
|
+
if (!Object.isFrozen(value))
|
|
717
|
+
return false;
|
|
718
|
+
const keys = Object.keys(value);
|
|
719
|
+
const isArray = Array.isArray(value);
|
|
720
|
+
for (let index = 0; index < keys.length; index += 1) {
|
|
721
|
+
if (!isArray && index > 0 && keys[index - 1] >= keys[index])
|
|
722
|
+
return false;
|
|
723
|
+
const entry = value[keys[index]];
|
|
724
|
+
if (entry === undefined || Object.is(entry, -0))
|
|
725
|
+
return false;
|
|
726
|
+
if (typeof entry === "object" && entry !== null && !isCanonicalFrozen(entry))
|
|
727
|
+
return false;
|
|
728
|
+
}
|
|
729
|
+
canonicalFrozen.add(value);
|
|
730
|
+
return true;
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Checks each operation with `assertOperation` and writes the list as JSON
|
|
734
|
+
* with sorted keys. `indentation` is passed to `JSON.stringify`.
|
|
735
|
+
*/
|
|
736
|
+
export function serializeOperations(operations, indentation = 0) {
|
|
737
|
+
operations.forEach(assertOperation);
|
|
738
|
+
return canonicalJson(operations, indentation);
|
|
739
|
+
}
|
|
740
|
+
function collectSubtreeIds(document, rootId) {
|
|
741
|
+
const result = [];
|
|
742
|
+
const visit = (id) => {
|
|
743
|
+
const node = entryOf(document.nodes, id);
|
|
744
|
+
if (node === undefined) {
|
|
745
|
+
operationError(`Missing node ${id}`, "$operations", [{ kind: "node", id: id }]);
|
|
746
|
+
}
|
|
747
|
+
result.push(id);
|
|
748
|
+
ownedChildIds(node).forEach(visit);
|
|
749
|
+
};
|
|
750
|
+
visit(rootId);
|
|
751
|
+
return result;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* The IDs of a node and all its descendants. Empty when the node does not
|
|
755
|
+
* exist.
|
|
756
|
+
*/
|
|
757
|
+
export function getSubtreeNodeIds(document, rootId) {
|
|
758
|
+
if (entryOf(document.nodes, rootId) === undefined) {
|
|
759
|
+
return new Set();
|
|
760
|
+
}
|
|
761
|
+
return new Set(collectSubtreeIds(document, rootId));
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Copies a node and its descendants into a `SerializedSubtree`, ready for a
|
|
765
|
+
* `node.insert` or `page.insert` operation. Throws a `ModelError` when the
|
|
766
|
+
* node does not exist.
|
|
767
|
+
*/
|
|
768
|
+
export function serializeSubtree(document, rootId) {
|
|
769
|
+
const ids = collectSubtreeIds(document, rootId);
|
|
770
|
+
const nodes = {};
|
|
771
|
+
ids.forEach((id) => {
|
|
772
|
+
const node = entryOf(document.nodes, id);
|
|
773
|
+
if (node !== undefined) {
|
|
774
|
+
putEntry(nodes, id, node);
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
return deepFreeze({ rootId, nodes });
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* The parent of `nodeId` in `document`. In a batch, read from the batch's
|
|
781
|
+
* parent table (`batchParents`), so a batch of moves and removals reads each
|
|
782
|
+
* parent in one step instead of reading every node per operation. Outside a
|
|
783
|
+
* batch, read from the table kept for a frozen map (`parentMapOf`), or else
|
|
784
|
+
* from the first container that lists the node, so one operation on a map
|
|
785
|
+
* that has no table does not build a table of every node.
|
|
786
|
+
*/
|
|
787
|
+
function parentOf(document, nodeId, batch) {
|
|
788
|
+
if (batch !== undefined)
|
|
789
|
+
return batchParents(document, batch).get(nodeId);
|
|
790
|
+
if (isFrozenNodeMap(document.nodes))
|
|
791
|
+
return parentMapOf(document.nodes).get(nodeId);
|
|
792
|
+
for (const node of tableValues(document.nodes)) {
|
|
793
|
+
if (ownedChildIds(node).includes(nodeId))
|
|
794
|
+
return node.id;
|
|
795
|
+
}
|
|
796
|
+
return undefined;
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* The parent table of `document.nodes` for this batch. The batch starts
|
|
800
|
+
* with the table of the map it starts from (`startBatch`) and keeps it up
|
|
801
|
+
* to date through every operation (`applyInBatch`), so this builds a table
|
|
802
|
+
* only when that chain was broken.
|
|
803
|
+
*/
|
|
804
|
+
function batchParents(document, batch) {
|
|
805
|
+
if (batch.parents?.nodes === document.nodes)
|
|
806
|
+
return batch.parents;
|
|
807
|
+
const table = parentMapOf(document.nodes);
|
|
808
|
+
batch.parents = new BatchParents(document.nodes, () => table);
|
|
809
|
+
return batch.parents;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* The parents of one node map: the table of the map the batch started from,
|
|
813
|
+
* read only when a parent is first asked for, and the parents that the
|
|
814
|
+
* operations of the batch have changed since.
|
|
815
|
+
*/
|
|
816
|
+
class BatchParents {
|
|
817
|
+
/** The parent of each node whose parent changed; `null` for a node that has none now. */
|
|
818
|
+
changed = new Map();
|
|
819
|
+
base;
|
|
820
|
+
/** The node map this table describes. */
|
|
821
|
+
nodes;
|
|
822
|
+
readBase;
|
|
823
|
+
constructor(nodes, readBase) {
|
|
824
|
+
this.nodes = nodes;
|
|
825
|
+
this.readBase = readBase;
|
|
826
|
+
}
|
|
827
|
+
get(id) {
|
|
828
|
+
const parent = this.changed.get(id);
|
|
829
|
+
if (parent !== undefined)
|
|
830
|
+
return parent ?? undefined;
|
|
831
|
+
this.base ??= this.readBase();
|
|
832
|
+
return this.base.get(id);
|
|
833
|
+
}
|
|
834
|
+
has(id) {
|
|
835
|
+
return this.get(id) !== undefined;
|
|
836
|
+
}
|
|
837
|
+
/** Records that `nodes`, made from this table's map, has `id` under `parentId`. */
|
|
838
|
+
move(nodes, id, parentId) {
|
|
839
|
+
this.nodes = nodes;
|
|
840
|
+
this.changed.set(id, parentId);
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Records `next`, made from this table's map by an operation that wrote,
|
|
844
|
+
* inserted or removed only the nodes `touched`. As in `derivedParents`,
|
|
845
|
+
* only those nodes and their children can have a new parent, so the work
|
|
846
|
+
* grows with them, not with the map.
|
|
847
|
+
*/
|
|
848
|
+
follow(next, touched) {
|
|
849
|
+
const previous = this.nodes;
|
|
850
|
+
for (const id of touched) {
|
|
851
|
+
if (entryOf(next, id) === undefined)
|
|
852
|
+
this.changed.set(id, null);
|
|
853
|
+
const before = entryOf(previous, id);
|
|
854
|
+
if (before !== undefined) {
|
|
855
|
+
for (const childId of ownedChildIds(before))
|
|
856
|
+
this.changed.set(childId, null);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
for (const id of touched) {
|
|
860
|
+
const after = entryOf(next, id);
|
|
861
|
+
if (after !== undefined) {
|
|
862
|
+
for (const childId of ownedChildIds(after))
|
|
863
|
+
this.changed.set(childId, id);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
this.nodes = next;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
/** A batch that starts from `nodes`, whose parent table it reads only when asked. */
|
|
870
|
+
function startBatch(nodes, parents = () => parentMapOf(nodes), share = false) {
|
|
871
|
+
return { owned: undefined, parents: new BatchParents(nodes, parents), share };
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* `applyOne` in `batch`, keeping the batch's parent table up to date: a
|
|
875
|
+
* replacement or a move updates it itself, and for any other operation that
|
|
876
|
+
* makes a new node map the table follows the nodes the operation touched.
|
|
877
|
+
*/
|
|
878
|
+
function applyInBatch(document, operation, batch) {
|
|
879
|
+
const parents = batch.parents?.nodes === document.nodes ? batch.parents : undefined;
|
|
880
|
+
const result = applyOne(document, operation, batch);
|
|
881
|
+
if (parents !== undefined && parents.nodes === document.nodes && result.document.nodes !== document.nodes) {
|
|
882
|
+
parents.follow(result.document.nodes, touchedNodeIds(result.changes));
|
|
883
|
+
}
|
|
884
|
+
return result;
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* The node map of `document` to write into: the batch's own map when the
|
|
888
|
+
* document has it, otherwise a copy that the batch then owns, counted in
|
|
889
|
+
* `modelApplyStats.replaceNodeMapCopies`.
|
|
890
|
+
*/
|
|
891
|
+
function writableNodes(document, batch) {
|
|
892
|
+
if (batch !== undefined && batch.owned === document.nodes) {
|
|
893
|
+
return document.nodes;
|
|
894
|
+
}
|
|
895
|
+
let nodes;
|
|
896
|
+
if (batch?.share === true) {
|
|
897
|
+
nodes = overlayTable(document.nodes);
|
|
898
|
+
}
|
|
899
|
+
else {
|
|
900
|
+
const copiesBefore = sharedNodeTableStats.wholeCopies;
|
|
901
|
+
const draft = sharedTableDraft(document.nodes);
|
|
902
|
+
nodes = draft;
|
|
903
|
+
if (nodeTableWatch.wrap !== null) {
|
|
904
|
+
nodes = nodeTableWatch.wrap(draft);
|
|
905
|
+
shareTableIdentity(nodes, draft);
|
|
906
|
+
}
|
|
907
|
+
modelApplyStats.replaceNodeMapCopies += sharedNodeTableStats.wholeCopies - copiesBefore;
|
|
908
|
+
}
|
|
909
|
+
if (batch !== undefined) {
|
|
910
|
+
batch.owned = nodes;
|
|
911
|
+
// A copy has the parents of the map it copies.
|
|
912
|
+
if (batch.parents?.nodes === document.nodes)
|
|
913
|
+
batch.parents.nodes = nodes;
|
|
914
|
+
}
|
|
915
|
+
return nodes;
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* A table of `nodes` to write into, for a step that only replaces nodes: an
|
|
919
|
+
* overlay over the same table when `nodes` is one (`shareNodeTable`), so
|
|
920
|
+
* the step does not copy the input's table after all, else a copy.
|
|
921
|
+
*/
|
|
922
|
+
function nodeTableToWrite(nodes) {
|
|
923
|
+
return overlayParts(nodes) === undefined ? sharedTableDraft(nodes) : overlayTable(nodes);
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* A table to write into that reads as `nodes` with every entry of `entries`
|
|
927
|
+
* put over it, in their order: what `{ ...nodes, ...entries }` makes,
|
|
928
|
+
* costing as much as `entries` (`sharedTableDraft`).
|
|
929
|
+
*/
|
|
930
|
+
function nodeTableWithEntries(nodes, entries) {
|
|
931
|
+
const table = sharedTableDraft(nodes);
|
|
932
|
+
for (const [id, node] of Object.entries(entries))
|
|
933
|
+
putEntry(table, id, node);
|
|
934
|
+
return table;
|
|
935
|
+
}
|
|
936
|
+
function replaceChildren(node, children) {
|
|
937
|
+
if (!isContainerNode(node)) {
|
|
938
|
+
operationError(`Node ${node.id} is not a container`, "$operations", [{ kind: "node", id: node.id }]);
|
|
939
|
+
}
|
|
940
|
+
return { ...node, children };
|
|
941
|
+
}
|
|
942
|
+
/** Fields no `node.patch` may write or remove. */
|
|
943
|
+
const UNPATCHABLE_FIELDS = new Set(["id", "type"]);
|
|
944
|
+
const isPlainRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
|
|
945
|
+
/** Merges named object fields; arrays and other values replace the stored value. */
|
|
946
|
+
function mergePatchFields(previous, fields) {
|
|
947
|
+
return Object.fromEntries([
|
|
948
|
+
...Object.entries(previous),
|
|
949
|
+
...Object.entries(fields).map(([field, value]) => {
|
|
950
|
+
const stored = Object.hasOwn(previous, field) ? previous[field] : undefined;
|
|
951
|
+
return [field, isPlainRecord(stored) && isPlainRecord(value) ? mergePatchFields(stored, value) : value];
|
|
952
|
+
}),
|
|
953
|
+
]);
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* The node a patch leaves on `previous`: `fields` merged into it and the
|
|
957
|
+
* names in `remove` deleted, leaving out a field or a removal at a path in
|
|
958
|
+
* `refused`. Every problem of that node is at the patch's own path: a
|
|
959
|
+
* removed field at its place in `remove` (`$operation.remove.0`), any other
|
|
960
|
+
* at `$operation.fields` (`$operation.fields.opacity` for `$.opacity`). Each
|
|
961
|
+
* names the patched node `nodeId` among its parts.
|
|
962
|
+
*/
|
|
963
|
+
function patchedNodeProblems(previous, fields, remove, nodeId, refused = new Set()) {
|
|
964
|
+
const node = mergePatchFields({ ...previous }, Object.fromEntries(Object.entries(fields).filter(([field]) => !refused.has(`$operation.fields.${field}`))));
|
|
965
|
+
const removedAt = new Map();
|
|
966
|
+
remove.forEach((field, index) => {
|
|
967
|
+
if (typeof field !== "string" || refused.has(`$operation.remove.${index}`))
|
|
968
|
+
return;
|
|
969
|
+
delete node[field];
|
|
970
|
+
removedAt.set(field, index);
|
|
971
|
+
});
|
|
972
|
+
const problems = checkSceneNode(node, Infinity).map((problem) => {
|
|
973
|
+
const field = /^\$\.([^.[]+)/.exec(problem.path)?.[1];
|
|
974
|
+
const index = field === undefined ? undefined : removedAt.get(field);
|
|
975
|
+
const path = index === undefined
|
|
976
|
+
? `$operation.fields${problem.path.slice(1)}`
|
|
977
|
+
: `$operation.remove.${index}${problem.path.slice(2 + field.length)}`;
|
|
978
|
+
return { ...problem, path, parts: [{ kind: "node", id: nodeId }, ...(problem.parts ?? [])] };
|
|
979
|
+
});
|
|
980
|
+
return { node, problems };
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* The node a `node.patch` leaves: the stored node with `fields` merged into
|
|
984
|
+
* it and `remove` deleted. It is checked with `checkSceneNode`; its problems
|
|
985
|
+
* are reported at the patch's own paths (`$operation.fields...`), all of them
|
|
986
|
+
* in the `problems` of one `ModelError`, never thrown as anything else.
|
|
987
|
+
*/
|
|
988
|
+
function patchedNode(document, operation) {
|
|
989
|
+
return patchedStoredNode(entryOf(document.nodes, operation.nodeId), operation);
|
|
990
|
+
}
|
|
991
|
+
/** `patchedNode` of the stored node `previous`. */
|
|
992
|
+
function patchedStoredNode(previous, operation) {
|
|
993
|
+
if (previous === undefined) {
|
|
994
|
+
operationError(`Missing node ${operation.nodeId}`, "$operation.nodeId", [{ kind: "node", id: operation.nodeId }]);
|
|
995
|
+
}
|
|
996
|
+
const { node, problems } = patchedNodeProblems(previous, operation.fields, operation.remove ?? [], operation.nodeId);
|
|
997
|
+
const [first] = problems;
|
|
998
|
+
if (first !== undefined) {
|
|
999
|
+
throw new ModelError(first.code, first.message, first.path, { problems: limitModelProblems(problems) });
|
|
1000
|
+
}
|
|
1001
|
+
return node;
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Checks a `node.patch` as `checkOperation` does, and then the node it
|
|
1005
|
+
* leaves on `document` as `checkSceneNode` does, and returns every problem
|
|
1006
|
+
* of both: those of the node at the patch's own paths (`$operation.fields.opacity`
|
|
1007
|
+
* for a written field, `$operation.remove.0` for a removed one). A field or
|
|
1008
|
+
* removal the first check refused is left out of the node, so it counts once.
|
|
1009
|
+
* The node is not checked when the patch names no stored node or its fields
|
|
1010
|
+
* are not an object. Empty when applying the patch to `document` would not
|
|
1011
|
+
* be refused for the shape of a value. At most `limit` (`MODEL_PROBLEM_LIMIT`
|
|
1012
|
+
* when omitted), then "and N more".
|
|
1013
|
+
*/
|
|
1014
|
+
export function checkNodePatch(document, value, limit = MODEL_PROBLEM_LIMIT) {
|
|
1015
|
+
const problems = checkOperation(value, Infinity);
|
|
1016
|
+
if (!isPlainRecord(value) || value.type !== "node.patch" || typeof value.nodeId !== "string" || !isPlainRecord(value.fields)) {
|
|
1017
|
+
return limitModelProblems(problems, limit);
|
|
1018
|
+
}
|
|
1019
|
+
const previous = entryOf(document.nodes, value.nodeId);
|
|
1020
|
+
if (previous === undefined)
|
|
1021
|
+
return limitModelProblems(problems, limit);
|
|
1022
|
+
const refused = new Set(problems.map((problem) => problem.path));
|
|
1023
|
+
const remove = Array.isArray(value.remove) ? value.remove : [];
|
|
1024
|
+
const merged = patchedNodeProblems(previous, value.fields, remove, value.nodeId, refused).problems;
|
|
1025
|
+
return limitModelProblems([...problems, ...merged], limit);
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Refuses a `node.replace` of `previous`, the stored node, by `node`, as
|
|
1029
|
+
* `applyOperations` does: the node must exist and keep its type and its
|
|
1030
|
+
* children. Returns `previous`.
|
|
1031
|
+
*/
|
|
1032
|
+
/** The slot host fields the component cascade owns: it writes them to follow the slot frame. */
|
|
1033
|
+
const SLOT_HOST_GEOMETRY_FIELDS = ["frame", "rotation", "flipX", "flipY", "layout"];
|
|
1034
|
+
/**
|
|
1035
|
+
* Refuses the operations when one of them writes a slot host's `frame`,
|
|
1036
|
+
* `rotation`, flips or `layout`: the component cascade sets those to follow
|
|
1037
|
+
* the slot frame, so a person or an agent edits the slot frame's override on
|
|
1038
|
+
* the instance instead. Only `node.replace` and `node.patch` of a host
|
|
1039
|
+
* stored in `document` are read; a host the operations insert is theirs to
|
|
1040
|
+
* place. Call it on the operations a person or an agent wrote, before
|
|
1041
|
+
* `settle` adds the layout and cascade writes of its own, which may move a
|
|
1042
|
+
* host; never on settled operations, an inverse or a replay. Neither
|
|
1043
|
+
* `applyOperations` nor `settle` calls it, so loading, undo, journal replay,
|
|
1044
|
+
* merges and settling settled operations take any valid write.
|
|
1045
|
+
* @since 0.37.0
|
|
1046
|
+
*/
|
|
1047
|
+
export function assertNoSlotHostGeometryWrite(document, operations) {
|
|
1048
|
+
const written = new Map();
|
|
1049
|
+
for (const operation of operations) {
|
|
1050
|
+
if (operation.type !== "node.replace" && operation.type !== "node.patch")
|
|
1051
|
+
continue;
|
|
1052
|
+
const id = operation.type === "node.replace" ? operation.node.id : operation.nodeId;
|
|
1053
|
+
const stored = entryOf(document.nodes, id);
|
|
1054
|
+
if (stored?.type !== "frame" || stored.slotHost !== true)
|
|
1055
|
+
continue;
|
|
1056
|
+
const next = operation.type === "node.replace" ? operation.node : patchedStoredNode(written.get(id) ?? stored, operation);
|
|
1057
|
+
written.set(id, next);
|
|
1058
|
+
refuseSlotHostGeometryWrite(stored, next);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
/** Refuses a write to the fields of a slot host that the component cascade owns. */
|
|
1062
|
+
function refuseSlotHostGeometryWrite(previous, node) {
|
|
1063
|
+
if (previous.type !== "frame" || previous.slotHost !== true)
|
|
1064
|
+
return;
|
|
1065
|
+
const record = (value) => value;
|
|
1066
|
+
const field = SLOT_HOST_GEOMETRY_FIELDS.find((name) => !same(record(previous)[name], record(node)[name]));
|
|
1067
|
+
if (field === undefined)
|
|
1068
|
+
return;
|
|
1069
|
+
operationError(`Slot host ${previous.id} cannot be given another ${field}: a slot host follows its slot frame in the component. Edit the slot frame's override on the instance instead`, "$operations", [{ kind: "node", id: previous.id }]);
|
|
1070
|
+
}
|
|
1071
|
+
function checkedReplacement(previous, node) {
|
|
1072
|
+
if (previous === undefined) {
|
|
1073
|
+
operationError(`Missing node ${node.id}`, "$operations", [{ kind: "node", id: node.id }]);
|
|
1074
|
+
}
|
|
1075
|
+
if (previous.type !== node.type) {
|
|
1076
|
+
operationError("node.replace cannot change a node's type", "$operations", [{ kind: "node", id: node.id }]);
|
|
1077
|
+
}
|
|
1078
|
+
if (isContainerNode(previous) &&
|
|
1079
|
+
isContainerNode(node) &&
|
|
1080
|
+
!same(previous.children, node.children)) {
|
|
1081
|
+
operationError("Use node insertion, removal, or movement to change children", "$operations", [{ kind: "node", id: node.id }]);
|
|
1082
|
+
}
|
|
1083
|
+
if (previous.type === "instance" && node.type === "instance" && !sameIdSet(ownedChildIds(previous), ownedChildIds(node))) {
|
|
1084
|
+
operationError("node.replace cannot add or remove an instance's slot hosts; insert a host with node.insert and slot, or remove it with node.remove", "$operations", [{ kind: "node", id: node.id }]);
|
|
1085
|
+
}
|
|
1086
|
+
return previous;
|
|
1087
|
+
}
|
|
1088
|
+
/** Whether two lists of IDs hold the same IDs, in any order. */
|
|
1089
|
+
function sameIdSet(left, right) {
|
|
1090
|
+
if (left === right)
|
|
1091
|
+
return true;
|
|
1092
|
+
if (left.length !== right.length)
|
|
1093
|
+
return false;
|
|
1094
|
+
const ids = new Set(left);
|
|
1095
|
+
return right.every((id) => ids.has(id));
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* `node` with its stored `aspectRatio` kept in step with its lock, as Figma
|
|
1099
|
+
* does: turning the lock on stores the ratio of the node's size at that
|
|
1100
|
+
* moment (unless the edit writes one), and turning it off drops the ratio.
|
|
1101
|
+
* While the lock stays on, an edit that writes no ratio keeps the one
|
|
1102
|
+
* `previous` has, so resizing a locked node keeps it. `nodePatchesAsReplacements`
|
|
1103
|
+
* writes its replacements through this too, so they store what
|
|
1104
|
+
* `applyOperations` stores for the patches.
|
|
1105
|
+
*/
|
|
1106
|
+
function withLockedAspectRatio(previous, node) {
|
|
1107
|
+
const locked = node.aspectRatioLocked === true;
|
|
1108
|
+
if (!locked) {
|
|
1109
|
+
if (node.aspectRatio === undefined)
|
|
1110
|
+
return node;
|
|
1111
|
+
const { aspectRatio: _dropped, ...unlocked } = node;
|
|
1112
|
+
return unlocked;
|
|
1113
|
+
}
|
|
1114
|
+
if (node.aspectRatio !== undefined || node.type === "connector")
|
|
1115
|
+
return node;
|
|
1116
|
+
if (previous.aspectRatioLocked === true) {
|
|
1117
|
+
return previous.aspectRatio === undefined ? node : { ...node, aspectRatio: previous.aspectRatio };
|
|
1118
|
+
}
|
|
1119
|
+
const bounds = getNodeBounds(node);
|
|
1120
|
+
const ratio = bounds.width / bounds.height;
|
|
1121
|
+
return Number.isFinite(ratio) && ratio > 0 ? { ...node, aspectRatio: ratio } : node;
|
|
1122
|
+
}
|
|
1123
|
+
function replaceNode(document, requested, changes, batch) {
|
|
1124
|
+
const previous = checkedReplacement(entryOf(document.nodes, requested.id), requested);
|
|
1125
|
+
const node = withLockedAspectRatio(previous, requested);
|
|
1126
|
+
if (same(previous, node)) {
|
|
1127
|
+
return { document, changes };
|
|
1128
|
+
}
|
|
1129
|
+
changes.documentChanged = true;
|
|
1130
|
+
changes.changedNodeIds.add(node.id);
|
|
1131
|
+
// A replacement keeps every node's children, so the parents stay as they were.
|
|
1132
|
+
const nodes = writableNodes(document, batch);
|
|
1133
|
+
putEntry(nodes, node.id, node);
|
|
1134
|
+
return {
|
|
1135
|
+
document: { ...document, nodes },
|
|
1136
|
+
inverse: { type: "node.replace", node: previous },
|
|
1137
|
+
changes,
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* `operations` with every `node.patch` written as the `node.replace` it
|
|
1142
|
+
* amounts to where it runs, so code that reads the nodes an edit writes only
|
|
1143
|
+
* has to know `node.replace`. The list comes back as it is when it holds no
|
|
1144
|
+
* patch. Throws a `ModelError` exactly when `applyOperations` refuses
|
|
1145
|
+
* `operations`: the result is checked by `applyOperations`, document-wide
|
|
1146
|
+
* rules such as references to styles and components included.
|
|
1147
|
+
*/
|
|
1148
|
+
export function nodePatchesAsReplacements(input, operations) {
|
|
1149
|
+
if (!operations.some((operation) => operation.type === "node.patch")) {
|
|
1150
|
+
applyOperations(input, operations);
|
|
1151
|
+
return operations;
|
|
1152
|
+
}
|
|
1153
|
+
let document = Object.isFrozen(input) ? input : snapshotDocument(input);
|
|
1154
|
+
// The nodes the replacements since the last other operation wrote. A
|
|
1155
|
+
// patch reads the node there before the stored one, so a run of patches
|
|
1156
|
+
// and replacements, the common edit, copies no node table.
|
|
1157
|
+
const pending = new Map();
|
|
1158
|
+
const batch = startBatch(document.nodes);
|
|
1159
|
+
const writePending = () => {
|
|
1160
|
+
for (const node of pending.values()) {
|
|
1161
|
+
document = applyInBatch(document, { type: "node.replace", node }, batch).document;
|
|
1162
|
+
}
|
|
1163
|
+
pending.clear();
|
|
1164
|
+
};
|
|
1165
|
+
const safeOperations = deserializeOperations(operations);
|
|
1166
|
+
const written = safeOperations.map((operation) => {
|
|
1167
|
+
if (operation.type === "node.patch" || operation.type === "node.replace") {
|
|
1168
|
+
const id = operation.type === "node.patch" ? operation.nodeId : operation.node.id;
|
|
1169
|
+
const stored = pending.get(id) ?? entryOf(document.nodes, id);
|
|
1170
|
+
const requested = operation.type === "node.patch"
|
|
1171
|
+
? patchedStoredNode(stored, operation)
|
|
1172
|
+
: (checkedReplacement(stored, operation.node), operation.node);
|
|
1173
|
+
// As `replaceNode` writes it, so a later patch of the same node starts from what `applyOperations` stores.
|
|
1174
|
+
const node = stored === undefined ? requested : withLockedAspectRatio(stored, requested);
|
|
1175
|
+
pending.set(id, node);
|
|
1176
|
+
return operation.type === "node.patch" || node !== requested ? { type: "node.replace", node } : operation;
|
|
1177
|
+
}
|
|
1178
|
+
writePending();
|
|
1179
|
+
document = applyInBatch(document, operation, batch).document;
|
|
1180
|
+
return operation;
|
|
1181
|
+
});
|
|
1182
|
+
const result = applyOperations(input, written);
|
|
1183
|
+
// A patch is applied as the replacement it amounts to, so the result is
|
|
1184
|
+
// the one `applyOperations` gives for `operations` too.
|
|
1185
|
+
rememberResult(input, safeOperations, isSealedOverlay(input.nodes), result);
|
|
1186
|
+
return written;
|
|
1187
|
+
}
|
|
1188
|
+
/** Convert legacy patches against each preceding operation, including commits outside the current head. */
|
|
1189
|
+
export function legacyNodePatchesAsReplacements(document, operations) {
|
|
1190
|
+
let current = Object.isFrozen(document) ? document : snapshotDocument(document);
|
|
1191
|
+
const batch = startBatch(current.nodes);
|
|
1192
|
+
const written = deserializeOperations(operations).map((operation) => {
|
|
1193
|
+
let replacement = operation;
|
|
1194
|
+
if (operation.type === "node.patch") {
|
|
1195
|
+
const previous = entryOf(current.nodes, operation.nodeId);
|
|
1196
|
+
if (previous !== undefined) {
|
|
1197
|
+
const node = { ...previous, ...operation.fields };
|
|
1198
|
+
for (const field of operation.remove ?? [])
|
|
1199
|
+
delete node[field];
|
|
1200
|
+
replacement = { type: "node.replace", node: node };
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
current = applyInBatch(current, replacement, batch).document;
|
|
1204
|
+
return replacement;
|
|
1205
|
+
});
|
|
1206
|
+
applyOperations(document, written);
|
|
1207
|
+
return written;
|
|
1208
|
+
}
|
|
1209
|
+
/** Where `hostId` is in `slots`: its nested instance path key and slot property ID. */
|
|
1210
|
+
function slotEntryOf(slots, hostId) {
|
|
1211
|
+
for (const [pathKey, byProperty] of Object.entries(slots ?? {})) {
|
|
1212
|
+
for (const [propertyId, id] of Object.entries(byProperty)) {
|
|
1213
|
+
if (id === hostId)
|
|
1214
|
+
return { pathKey, propertyId: propertyId };
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
return undefined;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* `slots` with the entry at `pathKey` and `propertyId` set to `hostId`, or
|
|
1221
|
+
* dropped when `hostId` is undefined. Empty maps are left out; undefined
|
|
1222
|
+
* when nothing is left.
|
|
1223
|
+
* @since 0.37.0
|
|
1224
|
+
*/
|
|
1225
|
+
export function slotsWithEntry(slots, pathKey, propertyId, hostId) {
|
|
1226
|
+
const byProperty = { ...(slots?.[pathKey] ?? {}) };
|
|
1227
|
+
if (hostId === undefined)
|
|
1228
|
+
delete byProperty[propertyId];
|
|
1229
|
+
else
|
|
1230
|
+
byProperty[propertyId] = hostId;
|
|
1231
|
+
const next = { ...(slots ?? {}) };
|
|
1232
|
+
if (Object.keys(byProperty).length === 0)
|
|
1233
|
+
delete next[pathKey];
|
|
1234
|
+
else
|
|
1235
|
+
next[pathKey] = byProperty;
|
|
1236
|
+
return Object.keys(next).length === 0 ? undefined : next;
|
|
1237
|
+
}
|
|
1238
|
+
/** `instance` with `slots` as given, the field left out when undefined. */
|
|
1239
|
+
function withSlots(instance, slots) {
|
|
1240
|
+
const { slots: _slots, ...rest } = instance;
|
|
1241
|
+
return slots === undefined ? rest : { ...rest, slots };
|
|
1242
|
+
}
|
|
1243
|
+
/** `node.insert` with `slot`: adds a slot host subtree and the instance's entry for it. */
|
|
1244
|
+
function insertSlotHost(document, operation, slot, changes) {
|
|
1245
|
+
const instance = entryOf(document.nodes, slot.instanceId);
|
|
1246
|
+
if (instance?.type !== "instance") {
|
|
1247
|
+
operationError(`Missing instance ${slot.instanceId} to hold a slot host`, "$operation.slot.instanceId", [{ kind: "node", id: slot.instanceId }]);
|
|
1248
|
+
}
|
|
1249
|
+
if (operation.parentId !== slot.instanceId || operation.index !== 0) {
|
|
1250
|
+
operationError("A slot host is inserted with parentId set to the slot's instance and index 0", "$operation.parentId", [{ kind: "node", id: operation.parentId }]);
|
|
1251
|
+
}
|
|
1252
|
+
const host = entryOf(operation.subtree.nodes, operation.subtree.rootId);
|
|
1253
|
+
if (host === undefined)
|
|
1254
|
+
operationError("Subtree root is missing");
|
|
1255
|
+
if (host.type !== "frame" || host.slotHost !== true) {
|
|
1256
|
+
operationError(`Node ${host.id} is not a slot host: insert a frame with slotHost true into a slot`, "$operation.subtree", [{ kind: "node", id: host.id }]);
|
|
1257
|
+
}
|
|
1258
|
+
const path = slot.path ?? [];
|
|
1259
|
+
const pathKey = path.length === 0 ? "" : layerPathKey(path);
|
|
1260
|
+
if (path.length > 0 && parseLayerPath(pathKey) === null)
|
|
1261
|
+
operationError("A slot path must be node IDs without \";\"", "$operation.slot.path");
|
|
1262
|
+
if (instance.slots?.[pathKey]?.[slot.propertyId] !== undefined) {
|
|
1263
|
+
operationError(`Instance ${instance.id} already fills slot ${slot.propertyId}${pathKey === "" ? "" : ` at ${pathKey}`}`, "$operation.slot", [{ kind: "node", id: instance.id }]);
|
|
1264
|
+
}
|
|
1265
|
+
for (const node of Object.values(operation.subtree.nodes)) {
|
|
1266
|
+
if (entryOf(document.nodes, node.id) !== undefined) {
|
|
1267
|
+
operationError(`Node ${node.id} already exists`, `$operation.subtree.nodes.${node.id}.id`, [{ kind: "node", id: node.id }]);
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
const nodes = nodeTableWithEntries(document.nodes, operation.subtree.nodes);
|
|
1271
|
+
putEntry(nodes, instance.id, withSlots(instance, slotsWithEntry(instance.slots, pathKey, slot.propertyId, host.id)));
|
|
1272
|
+
changes.documentChanged = true;
|
|
1273
|
+
changes.changedNodeIds.add(instance.id);
|
|
1274
|
+
for (const node of Object.values(operation.subtree.nodes)) {
|
|
1275
|
+
changes.changedNodeIds.add(node.id);
|
|
1276
|
+
changes.insertedNodeIds.add(node.id);
|
|
1277
|
+
}
|
|
1278
|
+
return {
|
|
1279
|
+
document: { ...document, nodes },
|
|
1280
|
+
inverse: { type: "node.remove", nodeId: host.id },
|
|
1281
|
+
changes,
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* The components an instance may show at `path` inside `instance`. Each step
|
|
1286
|
+
* of the path must be a stored instance inside the component shown at the
|
|
1287
|
+
* step before (found up its parent chain, which ends at that component's
|
|
1288
|
+
* root). A step shows the component a swap override names, the outermost
|
|
1289
|
+
* instance's first, then the nested instances' along the path, as
|
|
1290
|
+
* `resolveInstance` merges them; its stored component is kept as well, as an
|
|
1291
|
+
* expression may compute the swap. Empty when the path does not resolve.
|
|
1292
|
+
*/
|
|
1293
|
+
function componentsShownAt(document, parents, instance, path) {
|
|
1294
|
+
let shown = [instance.componentId];
|
|
1295
|
+
for (let depth = 1; depth <= path.length; depth += 1) {
|
|
1296
|
+
const stepId = path[depth - 1];
|
|
1297
|
+
const nested = entryOf(document.nodes, stepId);
|
|
1298
|
+
if (nested?.type !== "instance")
|
|
1299
|
+
return [];
|
|
1300
|
+
const roots = new Set(shown.map((componentId) => entryOf(document.components, componentId)?.rootId));
|
|
1301
|
+
let ancestor = parents.get(stepId);
|
|
1302
|
+
while (ancestor !== undefined && !roots.has(ancestor))
|
|
1303
|
+
ancestor = parents.get(ancestor);
|
|
1304
|
+
if (ancestor === undefined)
|
|
1305
|
+
return [];
|
|
1306
|
+
// The outermost holder's swap wins: the outer instance, then each nested instance along the path.
|
|
1307
|
+
const holders = [[instance, path.slice(0, depth)]];
|
|
1308
|
+
for (let index = 0; index < depth - 1; index += 1) {
|
|
1309
|
+
const holder = entryOf(document.nodes, path[index]);
|
|
1310
|
+
holders.push([holder?.type === "instance" ? holder : undefined, path.slice(index + 1, depth)]);
|
|
1311
|
+
}
|
|
1312
|
+
const swap = holders.map(([holder, key]) => entryOf(holder?.overrides, layerPathKey(key))?.componentId)
|
|
1313
|
+
.find((componentId) => componentId !== undefined);
|
|
1314
|
+
shown = swap === undefined || swap === nested.componentId ? [nested.componentId] : [swap, nested.componentId];
|
|
1315
|
+
}
|
|
1316
|
+
return shown;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* The component the instance `instanceId` shows at the nested path `path`
|
|
1320
|
+
* once resolved (swaps and computed components applied), or undefined when
|
|
1321
|
+
* it shows no nested instance there or cannot be resolved.
|
|
1322
|
+
*/
|
|
1323
|
+
function resolvedComponentAt(document, instanceId, path) {
|
|
1324
|
+
if (path.length === 0)
|
|
1325
|
+
return undefined;
|
|
1326
|
+
try {
|
|
1327
|
+
return resolveInstance(document, instanceId).layers.get(virtualNodeId(instanceId, path))?.instance?.componentId;
|
|
1328
|
+
}
|
|
1329
|
+
catch {
|
|
1330
|
+
return undefined;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Refuses a `node.insert` with `slot` whose host is still in place after the
|
|
1335
|
+
* batch when the path does not name nested instances inside the component,
|
|
1336
|
+
* or the component shown at the slot's path has no slot property with that
|
|
1337
|
+
* ID. It is checked against the batch's result, not when the operation runs,
|
|
1338
|
+
* so undoing a removed slot property (its host first, then the property) is
|
|
1339
|
+
* accepted. Each check walks the path's parent chains only.
|
|
1340
|
+
*/
|
|
1341
|
+
function refuseSlotsWithoutProperty(document, parents, operations) {
|
|
1342
|
+
for (const operation of operations) {
|
|
1343
|
+
if (operation.type !== "node.insert" || operation.slot === undefined)
|
|
1344
|
+
continue;
|
|
1345
|
+
const { instanceId, path = [], propertyId } = operation.slot;
|
|
1346
|
+
const instance = entryOf(document.nodes, instanceId);
|
|
1347
|
+
if (instance?.type !== "instance")
|
|
1348
|
+
continue;
|
|
1349
|
+
const pathKey = path.length === 0 ? "" : layerPathKey(path);
|
|
1350
|
+
if (instance.slots?.[pathKey]?.[propertyId] !== operation.subtree.rootId)
|
|
1351
|
+
continue;
|
|
1352
|
+
const shown = componentsShownAt(document, parents, instance, path);
|
|
1353
|
+
const hasSlotProperty = (componentId) => componentId !== undefined
|
|
1354
|
+
&& entryOf(document.components, componentId)?.properties?.some((property) => property.id === propertyId && property.kind === "slot") === true;
|
|
1355
|
+
// The stored components and swap overrides along the path decide most
|
|
1356
|
+
// fills without resolving; an expression may still compute the component
|
|
1357
|
+
// a nested instance shows, so before refusing, the instance is resolved
|
|
1358
|
+
// as `materializeSlotPlan` reads it (this one instance, not the document).
|
|
1359
|
+
if (shown.some(hasSlotProperty) || hasSlotProperty(resolvedComponentAt(document, instanceId, path)))
|
|
1360
|
+
continue;
|
|
1361
|
+
if (shown.length === 0) {
|
|
1362
|
+
operationError(`Slot path ${pathKey} does not name nested instances inside instance ${instanceId}'s component`, "$operation.slot.path", [{ kind: "node", id: instanceId }]);
|
|
1363
|
+
}
|
|
1364
|
+
operationError(`Instance ${instanceId} has no slot property ${propertyId}${pathKey === "" ? "" : ` at ${pathKey}`} to fill`, "$operation.slot.propertyId", [{ kind: "node", id: instanceId }]);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
/** `node.remove` of a slot host: removes it with its content and drops the instance's entry for it. */
|
|
1368
|
+
function removeSlotHost(document, instance, hostId, changes) {
|
|
1369
|
+
const entry = slotEntryOf(instance.slots, hostId);
|
|
1370
|
+
if (entry === undefined) {
|
|
1371
|
+
operationError(`Instance ${instance.id} does not list ${hostId} in its slots`, "$operations", [{ kind: "node", id: hostId }, { kind: "node", id: instance.id }]);
|
|
1372
|
+
}
|
|
1373
|
+
const subtree = serializeSubtree(document, hostId);
|
|
1374
|
+
const removedIds = Object.keys(subtree.nodes);
|
|
1375
|
+
const nodes = sharedTableCopy(document.nodes);
|
|
1376
|
+
removedIds.forEach((id) => delete nodes[id]);
|
|
1377
|
+
putEntry(nodes, instance.id, withSlots(instance, slotsWithEntry(instance.slots, entry.pathKey, entry.propertyId, undefined)));
|
|
1378
|
+
changes.documentChanged = true;
|
|
1379
|
+
changes.changedNodeIds.add(instance.id);
|
|
1380
|
+
removedIds.forEach((id) => {
|
|
1381
|
+
changes.changedNodeIds.add(id);
|
|
1382
|
+
changes.removedNodeIds.add(id);
|
|
1383
|
+
});
|
|
1384
|
+
const path = entry.pathKey === "" ? undefined : parseLayerPath(entry.pathKey) ?? undefined;
|
|
1385
|
+
return {
|
|
1386
|
+
document: { ...document, nodes },
|
|
1387
|
+
inverse: {
|
|
1388
|
+
type: "node.insert",
|
|
1389
|
+
parentId: instance.id,
|
|
1390
|
+
index: 0,
|
|
1391
|
+
subtree,
|
|
1392
|
+
slot: { instanceId: instance.id, ...(path === undefined ? {} : { path }), propertyId: entry.propertyId },
|
|
1393
|
+
},
|
|
1394
|
+
changes,
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
function applyOne(document, operation, batch) {
|
|
1398
|
+
const changes = createMutableChanges();
|
|
1399
|
+
if (isCommentOperation(operation)) {
|
|
1400
|
+
const result = applyCommentOperation(document, operation);
|
|
1401
|
+
if (result.threadId === undefined)
|
|
1402
|
+
return { document, changes };
|
|
1403
|
+
changes.documentChanged = true;
|
|
1404
|
+
changes.changedCommentThreadIds.add(result.threadId);
|
|
1405
|
+
return { document: result.document, ...(result.inverse === undefined ? {} : { inverse: result.inverse }), changes };
|
|
1406
|
+
}
|
|
1407
|
+
switch (operation.type) {
|
|
1408
|
+
case "document.set-title": {
|
|
1409
|
+
if (document.title === operation.title) {
|
|
1410
|
+
return { document, changes };
|
|
1411
|
+
}
|
|
1412
|
+
changes.documentChanged = true;
|
|
1413
|
+
return {
|
|
1414
|
+
document: { ...document, title: operation.title },
|
|
1415
|
+
inverse: { type: "document.set-title", title: document.title },
|
|
1416
|
+
changes,
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
case "document.set-metadata": {
|
|
1420
|
+
if (same(document.metadata ?? null, operation.metadata)) {
|
|
1421
|
+
return { document, changes };
|
|
1422
|
+
}
|
|
1423
|
+
changes.documentChanged = true;
|
|
1424
|
+
let next;
|
|
1425
|
+
if (operation.metadata === null) {
|
|
1426
|
+
const { metadata: _metadata, ...withoutMetadata } = document;
|
|
1427
|
+
next = withoutMetadata;
|
|
1428
|
+
}
|
|
1429
|
+
else {
|
|
1430
|
+
next = { ...document, metadata: operation.metadata };
|
|
1431
|
+
}
|
|
1432
|
+
return {
|
|
1433
|
+
document: next,
|
|
1434
|
+
inverse: {
|
|
1435
|
+
type: "document.set-metadata",
|
|
1436
|
+
metadata: document.metadata ?? null,
|
|
1437
|
+
},
|
|
1438
|
+
changes,
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
case "document.set-thumbnail": {
|
|
1442
|
+
if ((document.thumbnailNodeId ?? null) === operation.nodeId) {
|
|
1443
|
+
return { document, changes };
|
|
1444
|
+
}
|
|
1445
|
+
if (operation.nodeId !== null && !canBeThumbnail(document, operation.nodeId)) {
|
|
1446
|
+
operationError(`Only a top-level frame can be the thumbnail, not ${operation.nodeId}`, "$operation.nodeId", [
|
|
1447
|
+
{ kind: "node", id: operation.nodeId },
|
|
1448
|
+
]);
|
|
1449
|
+
}
|
|
1450
|
+
changes.documentChanged = true;
|
|
1451
|
+
let next;
|
|
1452
|
+
if (operation.nodeId === null) {
|
|
1453
|
+
const { thumbnailNodeId: _thumbnail, ...withoutThumbnail } = document;
|
|
1454
|
+
next = withoutThumbnail;
|
|
1455
|
+
}
|
|
1456
|
+
else {
|
|
1457
|
+
next = { ...document, thumbnailNodeId: operation.nodeId };
|
|
1458
|
+
}
|
|
1459
|
+
return {
|
|
1460
|
+
document: next,
|
|
1461
|
+
inverse: { type: "document.set-thumbnail", nodeId: document.thumbnailNodeId ?? null },
|
|
1462
|
+
changes,
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
case "node.insert": {
|
|
1466
|
+
if (operation.slot !== undefined)
|
|
1467
|
+
return insertSlotHost(document, operation, operation.slot, changes);
|
|
1468
|
+
const parent = entryOf(document.nodes, operation.parentId);
|
|
1469
|
+
if (parent === undefined || !isContainerNode(parent)) {
|
|
1470
|
+
operationError(`Missing container ${operation.parentId}`, "$operation.parentId", [{ kind: "node", id: operation.parentId }]);
|
|
1471
|
+
}
|
|
1472
|
+
if (operation.index > parent.children.length) {
|
|
1473
|
+
operationError("Insertion index is outside the parent", "$operation.index", [{ kind: "node", id: operation.parentId }]);
|
|
1474
|
+
}
|
|
1475
|
+
const subtreeNodes = Object.values(operation.subtree.nodes);
|
|
1476
|
+
if (entryOf(operation.subtree.nodes, operation.subtree.rootId) === undefined) {
|
|
1477
|
+
operationError("Subtree root is missing");
|
|
1478
|
+
}
|
|
1479
|
+
subtreeNodes.forEach((node) => {
|
|
1480
|
+
if (entryOf(document.nodes, node.id) !== undefined) {
|
|
1481
|
+
operationError(`Node ${node.id} already exists`, `$operation.subtree.nodes.${node.id}.id`, [{ kind: "node", id: node.id }]);
|
|
1482
|
+
}
|
|
1483
|
+
});
|
|
1484
|
+
const children = [...parent.children];
|
|
1485
|
+
children.splice(operation.index, 0, operation.subtree.rootId);
|
|
1486
|
+
const nodes = nodeTableWithEntries(document.nodes, operation.subtree.nodes);
|
|
1487
|
+
putEntry(nodes, parent.id, replaceChildren(parent, children));
|
|
1488
|
+
changes.documentChanged = true;
|
|
1489
|
+
changes.changedNodeIds.add(parent.id);
|
|
1490
|
+
subtreeNodes.forEach((node) => {
|
|
1491
|
+
changes.changedNodeIds.add(node.id);
|
|
1492
|
+
changes.insertedNodeIds.add(node.id);
|
|
1493
|
+
});
|
|
1494
|
+
return {
|
|
1495
|
+
document: { ...document, nodes },
|
|
1496
|
+
inverse: { type: "node.remove", nodeId: operation.subtree.rootId },
|
|
1497
|
+
changes,
|
|
1498
|
+
};
|
|
1499
|
+
}
|
|
1500
|
+
case "node.remove": {
|
|
1501
|
+
const node = entryOf(document.nodes, operation.nodeId);
|
|
1502
|
+
if (node === undefined) {
|
|
1503
|
+
operationError(`Missing node ${operation.nodeId}`, "$operations", [{ kind: "node", id: operation.nodeId }]);
|
|
1504
|
+
}
|
|
1505
|
+
const parentId = parentOf(document, operation.nodeId, batch);
|
|
1506
|
+
if (parentId === undefined) {
|
|
1507
|
+
operationError("A page or component root cannot be removed with node.remove", "$operations", [{ kind: "node", id: operation.nodeId }]);
|
|
1508
|
+
}
|
|
1509
|
+
const parent = entryOf(document.nodes, parentId);
|
|
1510
|
+
if (parent?.type === "instance")
|
|
1511
|
+
return removeSlotHost(document, parent, operation.nodeId, changes);
|
|
1512
|
+
if (parent === undefined || !isContainerNode(parent)) {
|
|
1513
|
+
operationError(`Missing parent ${parentId}`, "$operations", [{ kind: "node", id: operation.nodeId }, { kind: "node", id: parentId }]);
|
|
1514
|
+
}
|
|
1515
|
+
const index = parent.children.indexOf(operation.nodeId);
|
|
1516
|
+
const subtree = serializeSubtree(document, operation.nodeId);
|
|
1517
|
+
const removedIds = Object.keys(subtree.nodes);
|
|
1518
|
+
const nodes = sharedTableCopy(document.nodes);
|
|
1519
|
+
removedIds.forEach((id) => delete nodes[id]);
|
|
1520
|
+
putEntry(nodes, parentId, replaceChildren(parent, parent.children.filter((id) => id !== operation.nodeId)));
|
|
1521
|
+
changes.documentChanged = true;
|
|
1522
|
+
changes.changedNodeIds.add(parentId);
|
|
1523
|
+
removedIds.forEach((id) => {
|
|
1524
|
+
changes.changedNodeIds.add(id);
|
|
1525
|
+
changes.removedNodeIds.add(id);
|
|
1526
|
+
});
|
|
1527
|
+
return {
|
|
1528
|
+
document: { ...document, nodes },
|
|
1529
|
+
inverse: { type: "node.insert", parentId, index, subtree },
|
|
1530
|
+
changes,
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
case "node.move": {
|
|
1534
|
+
const node = entryOf(document.nodes, operation.nodeId);
|
|
1535
|
+
if (node === undefined) {
|
|
1536
|
+
operationError(`Missing node ${operation.nodeId}`, "$operations", [{ kind: "node", id: operation.nodeId }]);
|
|
1537
|
+
}
|
|
1538
|
+
const oldParentId = parentOf(document, operation.nodeId, batch);
|
|
1539
|
+
if (oldParentId === undefined) {
|
|
1540
|
+
operationError("A page or component root cannot be moved with node.move", "$operations", [{ kind: "node", id: operation.nodeId }]);
|
|
1541
|
+
}
|
|
1542
|
+
const oldParent = entryOf(document.nodes, oldParentId);
|
|
1543
|
+
const newParent = entryOf(document.nodes, operation.newParentId);
|
|
1544
|
+
if (oldParent === undefined ||
|
|
1545
|
+
!isContainerNode(oldParent) ||
|
|
1546
|
+
newParent === undefined ||
|
|
1547
|
+
!isContainerNode(newParent)) {
|
|
1548
|
+
operationError("Move requires existing container parents", "$operations", [
|
|
1549
|
+
{ kind: "node", id: operation.nodeId }, { kind: "node", id: oldParentId }, { kind: "node", id: operation.newParentId },
|
|
1550
|
+
]);
|
|
1551
|
+
}
|
|
1552
|
+
const subtreeIds = collectSubtreeIds(document, operation.nodeId);
|
|
1553
|
+
if (subtreeIds.includes(operation.newParentId)) {
|
|
1554
|
+
operationError("A node cannot be moved into its own subtree", "$operations", [{ kind: "node", id: operation.nodeId }, { kind: "node", id: operation.newParentId }]);
|
|
1555
|
+
}
|
|
1556
|
+
const oldIndex = oldParent.children.indexOf(operation.nodeId);
|
|
1557
|
+
const destinationLength = oldParentId === operation.newParentId
|
|
1558
|
+
? oldParent.children.length - 1
|
|
1559
|
+
: newParent.children.length;
|
|
1560
|
+
if (operation.index > destinationLength) {
|
|
1561
|
+
operationError("Move index is outside the destination parent", "$operations", [
|
|
1562
|
+
{ kind: "node", id: operation.nodeId }, { kind: "node", id: oldParentId }, { kind: "node", id: operation.newParentId },
|
|
1563
|
+
]);
|
|
1564
|
+
}
|
|
1565
|
+
if (oldParentId === operation.newParentId && oldIndex === operation.index) {
|
|
1566
|
+
return { document, changes };
|
|
1567
|
+
}
|
|
1568
|
+
const parents = batch === undefined ? undefined : batchParents(document, batch);
|
|
1569
|
+
const nodes = writableNodes(document, batch);
|
|
1570
|
+
if (oldParentId === operation.newParentId) {
|
|
1571
|
+
const children = oldParent.children.filter((id) => id !== operation.nodeId);
|
|
1572
|
+
children.splice(operation.index, 0, operation.nodeId);
|
|
1573
|
+
putEntry(nodes, oldParentId, replaceChildren(oldParent, children));
|
|
1574
|
+
}
|
|
1575
|
+
else {
|
|
1576
|
+
putEntry(nodes, oldParentId, replaceChildren(oldParent, oldParent.children.filter((id) => id !== operation.nodeId)));
|
|
1577
|
+
const children = [...newParent.children];
|
|
1578
|
+
children.splice(operation.index, 0, operation.nodeId);
|
|
1579
|
+
putEntry(nodes, operation.newParentId, replaceChildren(newParent, children));
|
|
1580
|
+
}
|
|
1581
|
+
parents?.move(nodes, operation.nodeId, operation.newParentId);
|
|
1582
|
+
changes.documentChanged = true;
|
|
1583
|
+
changes.changedNodeIds.add(oldParentId);
|
|
1584
|
+
changes.changedNodeIds.add(operation.newParentId);
|
|
1585
|
+
subtreeIds.forEach((id) => changes.changedNodeIds.add(id));
|
|
1586
|
+
return {
|
|
1587
|
+
document: { ...document, nodes },
|
|
1588
|
+
inverse: {
|
|
1589
|
+
type: "node.move",
|
|
1590
|
+
nodeId: operation.nodeId,
|
|
1591
|
+
newParentId: oldParentId,
|
|
1592
|
+
index: oldIndex,
|
|
1593
|
+
},
|
|
1594
|
+
changes,
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
case "node.replace":
|
|
1598
|
+
return replaceNode(document, operation.node, changes, batch);
|
|
1599
|
+
case "node.patch":
|
|
1600
|
+
return replaceNode(document, patchedNode(document, operation), changes, batch);
|
|
1601
|
+
case "page.insert": {
|
|
1602
|
+
if (operation.index > document.pageOrder.length) {
|
|
1603
|
+
operationError("Page insertion index is outside pageOrder");
|
|
1604
|
+
}
|
|
1605
|
+
if (entryOf(document.pages, operation.page.id) !== undefined) {
|
|
1606
|
+
operationError(`Page ${operation.page.id} already exists`, "$operations", [{ kind: "page", id: operation.page.id }]);
|
|
1607
|
+
}
|
|
1608
|
+
if (operation.page.rootId !== operation.subtree.rootId) {
|
|
1609
|
+
operationError("Page root must match subtree root");
|
|
1610
|
+
}
|
|
1611
|
+
for (const id of Object.keys(operation.subtree.nodes)) {
|
|
1612
|
+
if (entryOf(document.nodes, id) !== undefined) {
|
|
1613
|
+
operationError(`Node ${id} already exists`, "$operations", [{ kind: "node", id: id }]);
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
const pageOrder = [...document.pageOrder];
|
|
1617
|
+
pageOrder.splice(operation.index, 0, operation.page.id);
|
|
1618
|
+
changes.documentChanged = true;
|
|
1619
|
+
changes.changedPageIds.add(operation.page.id);
|
|
1620
|
+
const insertedIds = Object.keys(operation.subtree.nodes);
|
|
1621
|
+
insertedIds.forEach((id) => {
|
|
1622
|
+
changes.changedNodeIds.add(id);
|
|
1623
|
+
changes.insertedNodeIds.add(id);
|
|
1624
|
+
});
|
|
1625
|
+
return {
|
|
1626
|
+
document: {
|
|
1627
|
+
...document,
|
|
1628
|
+
pageOrder,
|
|
1629
|
+
pages: { ...document.pages, [operation.page.id]: operation.page },
|
|
1630
|
+
nodes: nodeTableWithEntries(document.nodes, operation.subtree.nodes),
|
|
1631
|
+
},
|
|
1632
|
+
inverse: { type: "page.remove", pageId: operation.page.id },
|
|
1633
|
+
changes,
|
|
1634
|
+
};
|
|
1635
|
+
}
|
|
1636
|
+
case "page.remove": {
|
|
1637
|
+
const page = entryOf(document.pages, operation.pageId);
|
|
1638
|
+
if (page === undefined) {
|
|
1639
|
+
operationError(`Missing page ${operation.pageId}`, "$operations", [{ kind: "page", id: operation.pageId }]);
|
|
1640
|
+
}
|
|
1641
|
+
const index = document.pageOrder.indexOf(operation.pageId);
|
|
1642
|
+
const subtree = serializeSubtree(document, page.rootId);
|
|
1643
|
+
const nodes = sharedTableCopy(document.nodes);
|
|
1644
|
+
const removedIds = Object.keys(subtree.nodes);
|
|
1645
|
+
removedIds.forEach((id) => delete nodes[id]);
|
|
1646
|
+
const pages = { ...document.pages };
|
|
1647
|
+
delete pages[operation.pageId];
|
|
1648
|
+
changes.documentChanged = true;
|
|
1649
|
+
changes.changedPageIds.add(operation.pageId);
|
|
1650
|
+
removedIds.forEach((id) => {
|
|
1651
|
+
changes.changedNodeIds.add(id);
|
|
1652
|
+
changes.removedNodeIds.add(id);
|
|
1653
|
+
});
|
|
1654
|
+
const inverse = { type: "page.insert", index, page, subtree };
|
|
1655
|
+
return {
|
|
1656
|
+
document: {
|
|
1657
|
+
...document,
|
|
1658
|
+
pageOrder: document.pageOrder.filter((id) => id !== operation.pageId),
|
|
1659
|
+
pages,
|
|
1660
|
+
nodes,
|
|
1661
|
+
},
|
|
1662
|
+
inverse,
|
|
1663
|
+
changes,
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
case "page.move": {
|
|
1667
|
+
const oldIndex = document.pageOrder.indexOf(operation.pageId);
|
|
1668
|
+
if (oldIndex < 0) {
|
|
1669
|
+
operationError(`Missing page ${operation.pageId}`, "$operations", [{ kind: "page", id: operation.pageId }]);
|
|
1670
|
+
}
|
|
1671
|
+
if (operation.index >= document.pageOrder.length) {
|
|
1672
|
+
operationError("Page move index is outside pageOrder");
|
|
1673
|
+
}
|
|
1674
|
+
if (oldIndex === operation.index) {
|
|
1675
|
+
return { document, changes };
|
|
1676
|
+
}
|
|
1677
|
+
const pageOrder = document.pageOrder.filter((id) => id !== operation.pageId);
|
|
1678
|
+
pageOrder.splice(operation.index, 0, operation.pageId);
|
|
1679
|
+
changes.documentChanged = true;
|
|
1680
|
+
changes.changedPageIds.add(operation.pageId);
|
|
1681
|
+
return {
|
|
1682
|
+
document: { ...document, pageOrder },
|
|
1683
|
+
inverse: { type: "page.move", pageId: operation.pageId, index: oldIndex },
|
|
1684
|
+
changes,
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
case "page.replace": {
|
|
1688
|
+
const previous = entryOf(document.pages, operation.page.id);
|
|
1689
|
+
if (previous === undefined) {
|
|
1690
|
+
operationError(`Missing page ${operation.page.id}`, "$operations", [{ kind: "page", id: operation.page.id }]);
|
|
1691
|
+
}
|
|
1692
|
+
if (previous.rootId !== operation.page.rootId) {
|
|
1693
|
+
operationError("page.replace cannot change rootId", "$operations", [{ kind: "page", id: operation.page.id }]);
|
|
1694
|
+
}
|
|
1695
|
+
if (same(previous, operation.page)) {
|
|
1696
|
+
return { document, changes };
|
|
1697
|
+
}
|
|
1698
|
+
changes.documentChanged = true;
|
|
1699
|
+
changes.changedPageIds.add(operation.page.id);
|
|
1700
|
+
return {
|
|
1701
|
+
document: {
|
|
1702
|
+
...document,
|
|
1703
|
+
pages: { ...document.pages, [operation.page.id]: operation.page },
|
|
1704
|
+
},
|
|
1705
|
+
inverse: { type: "page.replace", page: previous },
|
|
1706
|
+
changes,
|
|
1707
|
+
};
|
|
1708
|
+
}
|
|
1709
|
+
case "theme.replace": {
|
|
1710
|
+
if (same(document.theme, operation.theme)) {
|
|
1711
|
+
return { document, changes };
|
|
1712
|
+
}
|
|
1713
|
+
// The nodes that use a part of the theme that changed are added to the changes once every operation ran
|
|
1714
|
+
// (`addThemeUsers`).
|
|
1715
|
+
changes.documentChanged = true;
|
|
1716
|
+
changes.themeChanged = true;
|
|
1717
|
+
return {
|
|
1718
|
+
document: { ...document, theme: operation.theme },
|
|
1719
|
+
inverse: { type: "theme.replace", theme: document.theme },
|
|
1720
|
+
changes,
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
case "asset.put": {
|
|
1724
|
+
const previous = entryOf(document.assets, operation.asset.id);
|
|
1725
|
+
if (same(previous, operation.asset)) {
|
|
1726
|
+
return { document, changes };
|
|
1727
|
+
}
|
|
1728
|
+
// The nodes that use the asset are added to the changes once every operation ran (`addAssetUsers`).
|
|
1729
|
+
changes.documentChanged = true;
|
|
1730
|
+
changes.changedAssetIds.add(operation.asset.id);
|
|
1731
|
+
return {
|
|
1732
|
+
document: {
|
|
1733
|
+
...document,
|
|
1734
|
+
assets: { ...document.assets, [operation.asset.id]: operation.asset },
|
|
1735
|
+
},
|
|
1736
|
+
inverse: previous === undefined
|
|
1737
|
+
? { type: "asset.remove", assetId: operation.asset.id }
|
|
1738
|
+
: { type: "asset.put", asset: previous },
|
|
1739
|
+
changes,
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
case "asset.remove": {
|
|
1743
|
+
const previous = entryOf(document.assets, operation.assetId);
|
|
1744
|
+
if (previous === undefined) {
|
|
1745
|
+
operationError(`Missing asset ${operation.assetId}`, "$operations", [{ kind: "asset", id: operation.assetId }]);
|
|
1746
|
+
}
|
|
1747
|
+
const assets = { ...document.assets };
|
|
1748
|
+
delete assets[operation.assetId];
|
|
1749
|
+
changes.documentChanged = true;
|
|
1750
|
+
changes.changedAssetIds.add(operation.assetId);
|
|
1751
|
+
return {
|
|
1752
|
+
document: { ...document, assets },
|
|
1753
|
+
inverse: { type: "asset.put", asset: previous },
|
|
1754
|
+
changes,
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
case "component.insert": {
|
|
1758
|
+
const { component, subtree } = operation;
|
|
1759
|
+
if (entryOf(document.components, component.id) !== undefined) {
|
|
1760
|
+
operationError(`Component ${component.id} already exists`, "$operations", [{ kind: "component", id: component.id }]);
|
|
1761
|
+
}
|
|
1762
|
+
for (const id of Object.keys(subtree.nodes)) {
|
|
1763
|
+
if (entryOf(document.nodes, id) !== undefined) {
|
|
1764
|
+
operationError(`Node ${id} already exists`, "$operations", [{ kind: "node", id: id }]);
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
changes.documentChanged = true;
|
|
1768
|
+
changes.changedComponentIds.add(component.id);
|
|
1769
|
+
const insertedIds = Object.keys(subtree.nodes);
|
|
1770
|
+
insertedIds.forEach((id) => {
|
|
1771
|
+
changes.changedNodeIds.add(id);
|
|
1772
|
+
changes.insertedNodeIds.add(id);
|
|
1773
|
+
});
|
|
1774
|
+
return {
|
|
1775
|
+
document: {
|
|
1776
|
+
...document,
|
|
1777
|
+
nodes: nodeTableWithEntries(document.nodes, subtree.nodes),
|
|
1778
|
+
components: { ...(document.components ?? {}), [component.id]: component },
|
|
1779
|
+
},
|
|
1780
|
+
inverse: { type: "component.remove", componentId: component.id },
|
|
1781
|
+
changes,
|
|
1782
|
+
};
|
|
1783
|
+
}
|
|
1784
|
+
case "component.remove": {
|
|
1785
|
+
const component = entryOf(document.components, operation.componentId);
|
|
1786
|
+
if (component === undefined) {
|
|
1787
|
+
operationError(`Missing component ${operation.componentId}`, "$operations", [{ kind: "component", id: operation.componentId }]);
|
|
1788
|
+
}
|
|
1789
|
+
for (const node of tableValues(document.nodes)) {
|
|
1790
|
+
if (componentReferencesOf(node).includes(operation.componentId)) {
|
|
1791
|
+
throw new ModelError("INVALID_SCHEMA", `Component ${operation.componentId} is still used by ${node.id}`, "$operations", {
|
|
1792
|
+
parts: [{ kind: "component", id: operation.componentId }, { kind: "node", id: node.id }],
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
const subtree = serializeSubtree(document, component.rootId);
|
|
1797
|
+
const removedIds = Object.keys(subtree.nodes);
|
|
1798
|
+
const nodes = sharedTableCopy(document.nodes);
|
|
1799
|
+
removedIds.forEach((id) => delete nodes[id]);
|
|
1800
|
+
const components = { ...document.components };
|
|
1801
|
+
delete components[operation.componentId];
|
|
1802
|
+
changes.documentChanged = true;
|
|
1803
|
+
changes.changedComponentIds.add(operation.componentId);
|
|
1804
|
+
removedIds.forEach((id) => {
|
|
1805
|
+
changes.changedNodeIds.add(id);
|
|
1806
|
+
changes.removedNodeIds.add(id);
|
|
1807
|
+
});
|
|
1808
|
+
const { components: _components, ...withoutComponents } = document;
|
|
1809
|
+
return {
|
|
1810
|
+
document: Object.keys(components).length === 0
|
|
1811
|
+
? { ...withoutComponents, nodes }
|
|
1812
|
+
: { ...document, nodes, components },
|
|
1813
|
+
inverse: { type: "component.insert", component, subtree },
|
|
1814
|
+
changes,
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
case "component.replace": {
|
|
1818
|
+
const previous = entryOf(document.components, operation.component.id);
|
|
1819
|
+
if (previous === undefined) {
|
|
1820
|
+
operationError(`Missing component ${operation.component.id}`, "$operations", [{ kind: "component", id: operation.component.id }]);
|
|
1821
|
+
}
|
|
1822
|
+
if (previous.rootId !== operation.component.rootId) {
|
|
1823
|
+
operationError("component.replace cannot change rootId", "$operations", [{ kind: "component", id: operation.component.id }]);
|
|
1824
|
+
}
|
|
1825
|
+
if (previous.key !== operation.component.key) {
|
|
1826
|
+
operationError("component.replace cannot change key", "$operations", [{ kind: "component", id: operation.component.id }]);
|
|
1827
|
+
}
|
|
1828
|
+
if (same(previous, operation.component)) {
|
|
1829
|
+
return { document, changes };
|
|
1830
|
+
}
|
|
1831
|
+
changes.documentChanged = true;
|
|
1832
|
+
changes.changedComponentIds.add(operation.component.id);
|
|
1833
|
+
return {
|
|
1834
|
+
document: {
|
|
1835
|
+
...document,
|
|
1836
|
+
components: { ...document.components, [operation.component.id]: operation.component },
|
|
1837
|
+
},
|
|
1838
|
+
inverse: { type: "component.replace", component: previous },
|
|
1839
|
+
changes,
|
|
1840
|
+
};
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
/**
|
|
1845
|
+
* Keeps every group touched by a transaction fitted to its children. The
|
|
1846
|
+
* refit is part of the same transaction, so its inverse is recorded and one
|
|
1847
|
+
* undo restores both the edit and the previous group frame. A group whose
|
|
1848
|
+
* last child was removed or moved out is removed, as in Figma.
|
|
1849
|
+
*/
|
|
1850
|
+
/** Whether each frozen node map holds a group. A drag previews many edits of one document. */
|
|
1851
|
+
/** The inverse of an edit that changes nothing, shared by every such result. */
|
|
1852
|
+
const EMPTY_INVERSE_OPERATIONS = Object.freeze([]);
|
|
1853
|
+
const nodesHoldGroup = new WeakMap();
|
|
1854
|
+
function holdsGroup(nodes) {
|
|
1855
|
+
let holds = nodesHoldGroup.get(nodes);
|
|
1856
|
+
if (holds === undefined) {
|
|
1857
|
+
holds = tableValues(nodes).some((node) => node.type === "group");
|
|
1858
|
+
if (isFrozenNodeMap(nodes))
|
|
1859
|
+
nodesHoldGroup.set(nodes, holds);
|
|
1860
|
+
}
|
|
1861
|
+
return holds;
|
|
1862
|
+
}
|
|
1863
|
+
/**
|
|
1864
|
+
* Keeps for the frozen `next`, made from the frozen `previous` by writing,
|
|
1865
|
+
* inserting or removing only the nodes `touched`, whether it holds a group,
|
|
1866
|
+
* when that follows from what `previous` holds: a group only comes or goes
|
|
1867
|
+
* with a touched node. Otherwise `holdsGroup` reads `next` when asked.
|
|
1868
|
+
*/
|
|
1869
|
+
function recordHoldsGroup(previous, next, touched) {
|
|
1870
|
+
const before = nodesHoldGroup.get(previous);
|
|
1871
|
+
if (before === undefined)
|
|
1872
|
+
return;
|
|
1873
|
+
let touchedGroupBefore = false;
|
|
1874
|
+
let touchedGroupAfter = false;
|
|
1875
|
+
for (const id of touched) {
|
|
1876
|
+
if (entryOf(previous, id)?.type === "group")
|
|
1877
|
+
touchedGroupBefore = true;
|
|
1878
|
+
if (entryOf(next, id)?.type === "group")
|
|
1879
|
+
touchedGroupAfter = true;
|
|
1880
|
+
}
|
|
1881
|
+
if (touchedGroupAfter)
|
|
1882
|
+
nodesHoldGroup.set(next, true);
|
|
1883
|
+
else if (!touchedGroupBefore)
|
|
1884
|
+
nodesHoldGroup.set(next, before);
|
|
1885
|
+
}
|
|
1886
|
+
/** Every node an edit wrote, inserted or removed, from its change sets. */
|
|
1887
|
+
function touchedNodeIds(changes) {
|
|
1888
|
+
return new Set([...changes.changedNodeIds, ...changes.insertedNodeIds, ...changes.removedNodeIds]);
|
|
1889
|
+
}
|
|
1890
|
+
function fitChangedGroups(original, document, changes, inverseOperations) {
|
|
1891
|
+
// Every node the operations did not write is a node of `original`.
|
|
1892
|
+
const hasGroup = holdsGroup(original.nodes) ||
|
|
1893
|
+
[...changes.changedNodeIds].some((id) => entryOf(document.nodes, id)?.type === "group");
|
|
1894
|
+
if (!hasGroup)
|
|
1895
|
+
return document;
|
|
1896
|
+
const parents = derivedParents(original.nodes, parentMapOf(original.nodes), document.nodes, touchedNodeIds(changes));
|
|
1897
|
+
const affected = new Set();
|
|
1898
|
+
for (const changedId of changes.changedNodeIds) {
|
|
1899
|
+
let current = entryOf(document.nodes, changedId) === undefined
|
|
1900
|
+
? undefined
|
|
1901
|
+
: changedId;
|
|
1902
|
+
while (current !== undefined && !affected.has(current)) {
|
|
1903
|
+
if (entryOf(document.nodes, current)?.type === "group")
|
|
1904
|
+
affected.add(current);
|
|
1905
|
+
current = parents.get(current);
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
if (affected.size === 0)
|
|
1909
|
+
return document;
|
|
1910
|
+
const ordered = [...affected]
|
|
1911
|
+
.map((id) => ({ id, depth: nodeDepth(parents, id) }))
|
|
1912
|
+
.sort((left, right) => right.depth - left.depth);
|
|
1913
|
+
let next = document;
|
|
1914
|
+
let pendingNodes = null;
|
|
1915
|
+
const flushPending = () => {
|
|
1916
|
+
if (pendingNodes === null)
|
|
1917
|
+
return;
|
|
1918
|
+
next = { ...next, nodes: pendingNodes };
|
|
1919
|
+
pendingNodes = null;
|
|
1920
|
+
};
|
|
1921
|
+
const replaceNode = (node) => {
|
|
1922
|
+
const previous = entryOf(pendingNodes ?? next.nodes, node.id);
|
|
1923
|
+
if (previous === undefined)
|
|
1924
|
+
operationError(`Missing node ${node.id}`, "$operations", [{ kind: "node", id: node.id }]);
|
|
1925
|
+
if (same(previous, node))
|
|
1926
|
+
return;
|
|
1927
|
+
pendingNodes ??= nodeTableToWrite(next.nodes);
|
|
1928
|
+
putEntry(pendingNodes, node.id, node);
|
|
1929
|
+
inverseOperations.unshift({ type: "node.replace", node: previous });
|
|
1930
|
+
changes.changedNodeIds.add(node.id);
|
|
1931
|
+
};
|
|
1932
|
+
for (const { id } of ordered) {
|
|
1933
|
+
const nodes = pendingNodes ?? next.nodes;
|
|
1934
|
+
const group = entryOf(nodes, id);
|
|
1935
|
+
if (group?.type !== "group")
|
|
1936
|
+
continue;
|
|
1937
|
+
const before = entryOf(original.nodes, id);
|
|
1938
|
+
const emptied = group.children.length === 0
|
|
1939
|
+
&& before?.type === "group"
|
|
1940
|
+
&& before.children.length > 0
|
|
1941
|
+
&& parents.has(id);
|
|
1942
|
+
if (emptied) {
|
|
1943
|
+
flushPending();
|
|
1944
|
+
// Groups go deepest first and a refit keeps children, so `parents`
|
|
1945
|
+
// still holds the parent of every node left.
|
|
1946
|
+
const removal = applyOne(next, { type: "node.remove", nodeId: id }, startBatch(next.nodes, () => parents));
|
|
1947
|
+
next = removal.document;
|
|
1948
|
+
if (removal.inverse !== undefined)
|
|
1949
|
+
inverseOperations.unshift(removal.inverse);
|
|
1950
|
+
mergeChanges(changes, removal.changes);
|
|
1951
|
+
continue;
|
|
1952
|
+
}
|
|
1953
|
+
const fitted = fitGroupToChildren(nodes, group);
|
|
1954
|
+
if (fitted === null)
|
|
1955
|
+
continue;
|
|
1956
|
+
fitted.children.forEach(replaceNode);
|
|
1957
|
+
replaceNode(fitted.group);
|
|
1958
|
+
}
|
|
1959
|
+
flushPending();
|
|
1960
|
+
return next;
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* Keeps the rule that no node has a stretching constraint on an axis it
|
|
1964
|
+
* hugs, for every node these operations bring to break it
|
|
1965
|
+
* (`stretchWhereHuggingReplacements`): each such node is replaced by itself
|
|
1966
|
+
* with Left or Top on that axis, and the inverse operations put the
|
|
1967
|
+
* constraint back. An axis that already hugged and stretched in `original`
|
|
1968
|
+
* is left as the operations wrote it, so they can be reversed exactly.
|
|
1969
|
+
*/
|
|
1970
|
+
function removeStretchWhereHugging(original, document, changes, inverseOperations) {
|
|
1971
|
+
const replacements = stretchWhereHuggingReplacements(original, document, changes.changedNodeIds);
|
|
1972
|
+
if (replacements.length === 0)
|
|
1973
|
+
return document;
|
|
1974
|
+
const nodes = nodeTableToWrite(document.nodes);
|
|
1975
|
+
for (const node of replacements) {
|
|
1976
|
+
inverseOperations.unshift({ type: "node.replace", node: entryOf(nodes, node.id) });
|
|
1977
|
+
putEntry(nodes, node.id, node);
|
|
1978
|
+
changes.changedNodeIds.add(node.id);
|
|
1979
|
+
}
|
|
1980
|
+
return { ...document, nodes };
|
|
1981
|
+
}
|
|
1982
|
+
/**
|
|
1983
|
+
* Adds to `changedComponentIds` every component one of whose layers is in
|
|
1984
|
+
* `changedNodeIds`, before or after the edit (a layer moved out of a
|
|
1985
|
+
* component changes that component too).
|
|
1986
|
+
*/
|
|
1987
|
+
function markChangedComponents(previous, current, parentsAfter, changes) {
|
|
1988
|
+
if (previous.components === undefined && current.components === undefined)
|
|
1989
|
+
return;
|
|
1990
|
+
const parentsBefore = parentMapOf(previous.nodes);
|
|
1991
|
+
for (const id of changes.changedNodeIds) {
|
|
1992
|
+
const before = componentOwningNode(previous, id, parentsBefore);
|
|
1993
|
+
if (before !== undefined)
|
|
1994
|
+
changes.changedComponentIds.add(before.id);
|
|
1995
|
+
const after = componentOwningNode(current, id, parentsAfter);
|
|
1996
|
+
if (after !== undefined)
|
|
1997
|
+
changes.changedComponentIds.add(after.id);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
/** `end` as a free end at the place it has: without its node and the spot named on that node. */
|
|
2001
|
+
function freeConnectorEnd(end) {
|
|
2002
|
+
const { nodeId: _nodeId, side: _side, anchor: _anchor, point: _point, ...free } = end;
|
|
2003
|
+
return free;
|
|
2004
|
+
}
|
|
2005
|
+
/**
|
|
2006
|
+
* Keeps the rule that a connector end names a node that exists, for the
|
|
2007
|
+
* nodes these operations removed: every connector end attached to a removed
|
|
2008
|
+
* node (one the operations name, anything inside it, or a group removed
|
|
2009
|
+
* because it was left with no children) becomes a free end at the `x` and `y`
|
|
2010
|
+
* it has, and the inverse operations attach it again. An end on a node that
|
|
2011
|
+
* was removed and put back is left alone, and so is an end that names a node
|
|
2012
|
+
* the document never had, which the validation that follows refuses.
|
|
2013
|
+
*/
|
|
2014
|
+
function freeEndsOnRemovedNodes(original, document, changes, inverseOperations) {
|
|
2015
|
+
if (changes.removedNodeIds.size === 0)
|
|
2016
|
+
return document;
|
|
2017
|
+
const gone = (end) => (end.nodeId !== undefined && changes.removedNodeIds.has(end.nodeId) && entryOf(document.nodes, end.nodeId) === undefined);
|
|
2018
|
+
// The connectors attached to a removed node: those attached to it before
|
|
2019
|
+
// the edit (kept in an index, `connectorsAttachedTo`), and those the edit
|
|
2020
|
+
// wrote, which are all in `changedNodeIds`.
|
|
2021
|
+
const candidates = new Set(connectorsAttachedTo(original, changes.removedNodeIds));
|
|
2022
|
+
changes.changedNodeIds.forEach((id) => candidates.add(id));
|
|
2023
|
+
let nodes = null;
|
|
2024
|
+
for (const id of candidates) {
|
|
2025
|
+
const node = entryOf(document.nodes, id);
|
|
2026
|
+
if (node?.type !== "connector" || !(gone(node.start) || gone(node.end)))
|
|
2027
|
+
continue;
|
|
2028
|
+
nodes ??= sharedTableDraft(document.nodes);
|
|
2029
|
+
putEntry(nodes, node.id, {
|
|
2030
|
+
...node,
|
|
2031
|
+
start: gone(node.start) ? freeConnectorEnd(node.start) : node.start,
|
|
2032
|
+
end: gone(node.end) ? freeConnectorEnd(node.end) : node.end,
|
|
2033
|
+
});
|
|
2034
|
+
inverseOperations.unshift({ type: "node.replace", node });
|
|
2035
|
+
changes.changedNodeIds.add(node.id);
|
|
2036
|
+
}
|
|
2037
|
+
return nodes === null ? document : { ...document, nodes };
|
|
2038
|
+
}
|
|
2039
|
+
/**
|
|
2040
|
+
* Runs `operations` on `input`, and the steps that follow them in the same
|
|
2041
|
+
* edit (groups refitted or removed, connector ends on removed nodes freed,
|
|
2042
|
+
* stretching constraints dropped where a node hugs). Everything that changes which nodes exist happens here, so
|
|
2043
|
+
* `applyOperations` and `nodeIdsRemovedBy` cannot disagree about it. The
|
|
2044
|
+
* result is not validated.
|
|
2045
|
+
*/
|
|
2046
|
+
function runOperations(input, operations, steps, safeOperations = deserializeOperations(operations), share = false) {
|
|
2047
|
+
// A frozen document was produced and validated by this package, so it is
|
|
2048
|
+
// taken as valid. Anything else is validated while it is copied.
|
|
2049
|
+
const document = Object.isFrozen(input) ? input : snapshotDocument(input);
|
|
2050
|
+
let next = document;
|
|
2051
|
+
const inverseOperations = [];
|
|
2052
|
+
const changes = createMutableChanges();
|
|
2053
|
+
// Each step is kept when steps are asked for, so none may be written over.
|
|
2054
|
+
const batch = steps === undefined
|
|
2055
|
+
? startBatch(document.nodes, undefined, share && safeOperations.every((operation) => SHARING_OPERATION_TYPES.has(operation.type)))
|
|
2056
|
+
: undefined;
|
|
2057
|
+
steps?.push(next);
|
|
2058
|
+
for (const operation of safeOperations) {
|
|
2059
|
+
const result = batch === undefined ? applyOne(next, operation) : applyInBatch(next, operation, batch);
|
|
2060
|
+
next = result.document;
|
|
2061
|
+
steps?.push(next);
|
|
2062
|
+
if (result.inverse !== undefined) {
|
|
2063
|
+
inverseOperations.unshift(result.inverse);
|
|
2064
|
+
}
|
|
2065
|
+
mergeChanges(changes, result.changes);
|
|
2066
|
+
}
|
|
2067
|
+
if (changes.themeChanged)
|
|
2068
|
+
addThemeUsers(document, next, changes);
|
|
2069
|
+
if (changes.documentChanged) {
|
|
2070
|
+
next = fitChangedGroups(document, next, changes, inverseOperations);
|
|
2071
|
+
next = freeEndsOnRemovedNodes(document, next, changes, inverseOperations);
|
|
2072
|
+
next = removeStretchWhereHugging(document, next, changes, inverseOperations);
|
|
2073
|
+
}
|
|
2074
|
+
for (const id of changes.changedNodeIds) {
|
|
2075
|
+
const node = next.nodes[id];
|
|
2076
|
+
if (node === undefined)
|
|
2077
|
+
continue;
|
|
2078
|
+
const bounded = clampGeometry(node);
|
|
2079
|
+
if (bounded !== node)
|
|
2080
|
+
next = { ...next, nodes: nodeTableWith(next.nodes, new Map([[id, bounded]])) };
|
|
2081
|
+
}
|
|
2082
|
+
return { document, next, inverseOperations, changes };
|
|
2083
|
+
}
|
|
2084
|
+
/**
|
|
2085
|
+
* The document each of `operations` is applied to, and the one the last
|
|
2086
|
+
* leaves: entry `i` is `input` with the operations before `i` applied, so
|
|
2087
|
+
* there is one more entry than there are operations. None has the steps
|
|
2088
|
+
* that follow the operations in the same edit (groups refitted or removed,
|
|
2089
|
+
* connector ends freed), and none is validated or frozen; do not change
|
|
2090
|
+
* them. Use it to learn what an operation sees, for example which layers a
|
|
2091
|
+
* removal deletes once earlier operations moved some out.
|
|
2092
|
+
*
|
|
2093
|
+
* It throws a `ModelError` when an operation does not fit the document.
|
|
2094
|
+
*/
|
|
2095
|
+
export function documentsBeforeEachOperation(input, operations) {
|
|
2096
|
+
const steps = [];
|
|
2097
|
+
runOperations(input, operations, steps);
|
|
2098
|
+
return steps;
|
|
2099
|
+
}
|
|
2100
|
+
/**
|
|
2101
|
+
* The IDs of the nodes that are in `input` and gone once `operations` have
|
|
2102
|
+
* run, in the order `input.nodes` lists them. That is every node the
|
|
2103
|
+
* operations remove themselves (`node.remove`, `page.remove` and
|
|
2104
|
+
* `component.remove`, each with everything inside) and every group removed
|
|
2105
|
+
* because the edit left it with no children. A node that is removed and put
|
|
2106
|
+
* back by the same operations is not listed. The IDs come in the order the
|
|
2107
|
+
* operations remove the nodes, and finding them reads only those nodes, not
|
|
2108
|
+
* every node of the document.
|
|
2109
|
+
*
|
|
2110
|
+
* It runs the same steps as `applyOperations` but does not validate the
|
|
2111
|
+
* result and returns no document. Use it to learn what an edit removes
|
|
2112
|
+
* before applying it, for example to let go of the connector ends attached
|
|
2113
|
+
* to those nodes, without which `applyOperations` would refuse the edit.
|
|
2114
|
+
*
|
|
2115
|
+
* It throws a `ModelError` when an operation does not fit the document.
|
|
2116
|
+
*/
|
|
2117
|
+
export function nodeIdsRemovedBy(input, operations) {
|
|
2118
|
+
const { document, next, changes } = runOperations(input, operations);
|
|
2119
|
+
if (next.nodes === document.nodes)
|
|
2120
|
+
return [];
|
|
2121
|
+
// Every node gone is among the nodes the run removed, so only those are read.
|
|
2122
|
+
const removed = [];
|
|
2123
|
+
for (const id of changes.removedNodeIds) {
|
|
2124
|
+
if (entryOf(document.nodes, id) !== undefined && entryOf(next.nodes, id) === undefined)
|
|
2125
|
+
removed.push(id);
|
|
2126
|
+
}
|
|
2127
|
+
return removed;
|
|
2128
|
+
}
|
|
2129
|
+
/**
|
|
2130
|
+
* A change was refused because it would delete a page that must not be
|
|
2131
|
+
* deleted (`Page.removable` is `false`). Nothing was changed. `pages` lists
|
|
2132
|
+
* every such page the change would delete, in the order it deletes them.
|
|
2133
|
+
* The `code` is `PAGE_NOT_REMOVABLE` and the message names the pages.
|
|
2134
|
+
* @since 0.29.0
|
|
2135
|
+
*/
|
|
2136
|
+
export class PageNotRemovableError extends ModelError {
|
|
2137
|
+
/** The pages that must stay, as they are in the document. */
|
|
2138
|
+
pages;
|
|
2139
|
+
constructor(pages) {
|
|
2140
|
+
const names = pages.map((page) => JSON.stringify(page.name)).join(", ");
|
|
2141
|
+
super("PAGE_NOT_REMOVABLE", pages.length === 1
|
|
2142
|
+
? `The page ${names} cannot be deleted`
|
|
2143
|
+
: `The pages ${names} cannot be deleted`, `$.pages.${pages[0]?.id ?? ""}`);
|
|
2144
|
+
this.pages = pages;
|
|
2145
|
+
this.name = "PageNotRemovableError";
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
/**
|
|
2149
|
+
* The pages `operations` would delete from `document` although they must not
|
|
2150
|
+
* be deleted: each page that a `page.remove` names while its `removable` is
|
|
2151
|
+
* `false`. The operations are read in order, so a page counts as it is when
|
|
2152
|
+
* its `page.remove` is reached: one that an earlier operation of the same
|
|
2153
|
+
* list made removable (a `page.replace` without `removable`) is not listed,
|
|
2154
|
+
* and one that an earlier operation made non-removable is. A `page.remove`
|
|
2155
|
+
* of a page that does not exist is skipped here; applying it fails.
|
|
2156
|
+
*
|
|
2157
|
+
* `DocumentStore.dispatch` and `DocumentStore.preview` refuse a change for
|
|
2158
|
+
* which this is not empty. `applyOperations` does not ask, because it also
|
|
2159
|
+
* runs the inverse of an insertion when history is walked back.
|
|
2160
|
+
* @since 0.29.0
|
|
2161
|
+
*/
|
|
2162
|
+
export function nonRemovablePagesRemovedBy(document, operations) {
|
|
2163
|
+
// Only pages these operations wrote or removed; `null` is a removed page.
|
|
2164
|
+
const written = new Map();
|
|
2165
|
+
const refused = [];
|
|
2166
|
+
for (const operation of operations) {
|
|
2167
|
+
switch (operation.type) {
|
|
2168
|
+
case "page.insert":
|
|
2169
|
+
case "page.replace":
|
|
2170
|
+
written.set(operation.page.id, operation.page);
|
|
2171
|
+
break;
|
|
2172
|
+
case "page.remove": {
|
|
2173
|
+
const page = written.has(operation.pageId)
|
|
2174
|
+
? written.get(operation.pageId)
|
|
2175
|
+
: entryOf(document.pages, operation.pageId);
|
|
2176
|
+
if (page !== undefined && page !== null && page.removable === false)
|
|
2177
|
+
refused.push(page);
|
|
2178
|
+
written.set(operation.pageId, null);
|
|
2179
|
+
break;
|
|
2180
|
+
}
|
|
2181
|
+
default:
|
|
2182
|
+
break;
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
return refused;
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* Throws a `PageNotRemovableError` when `operations` would delete a page of
|
|
2189
|
+
* `document` that must not be deleted (`nonRemovablePagesRemovedBy`).
|
|
2190
|
+
* @since 0.29.0
|
|
2191
|
+
*/
|
|
2192
|
+
export function assertNoNonRemovablePageRemoved(document, operations) {
|
|
2193
|
+
const pages = nonRemovablePagesRemovedBy(document, operations);
|
|
2194
|
+
if (pages.length > 0)
|
|
2195
|
+
throw new PageNotRemovableError(pages);
|
|
2196
|
+
}
|
|
2197
|
+
/**
|
|
2198
|
+
* Applies `operations` in order and returns the new document, the inverse
|
|
2199
|
+
* operations, and a `ChangeSet`. It never changes the input.
|
|
2200
|
+
*
|
|
2201
|
+
* After the operations run, every group that contains a changed node, at any
|
|
2202
|
+
* depth, is refitted to its children, and a group left with no children is removed; the inverse
|
|
2203
|
+
* operations undo that too. A connector end attached to a node that is gone
|
|
2204
|
+
* after that (a removed node, anything inside it, or such a group) becomes a
|
|
2205
|
+
* free end at the `x` and `y` it has, so removing a connector's target is
|
|
2206
|
+
* never refused; the inverse operations attach the end again. Then every changed node, and every instance of a
|
|
2207
|
+
* component whose root's sizing changed, loses a stretching constraint
|
|
2208
|
+
* (Left and right, Top and bottom, Scale) on an axis it hugs: it becomes
|
|
2209
|
+
* Left or Top, and the inverse operations put it back. That is done only
|
|
2210
|
+
* where the operations bring it: an axis of a node that already hugged and
|
|
2211
|
+
* stretched in the input document (one stored before this rule) is left as
|
|
2212
|
+
* the operations write it. The result is then
|
|
2213
|
+
* validated. A document that
|
|
2214
|
+
* is not frozen is first validated and copied with `snapshotDocument`.
|
|
2215
|
+
*
|
|
2216
|
+
* All or nothing: if any operation does not fit the document, or the result
|
|
2217
|
+
* is invalid, it throws a `ModelError` and returns nothing.
|
|
2218
|
+
*
|
|
2219
|
+
* The last few results on frozen documents are kept, four in all, so the
|
|
2220
|
+
* same operations applied to the same document again (`settle` previews an
|
|
2221
|
+
* edit before the edit is applied) return the same frozen result without
|
|
2222
|
+
* copying the node table again. The operations are read
|
|
2223
|
+
* (`deserializeOperations`) before a kept result is looked for, so they are
|
|
2224
|
+
* checked on every call, and a kept result is returned only for operations
|
|
2225
|
+
* that read the same: the result depends on nothing else than the frozen
|
|
2226
|
+
* document, the read operations and `options`, so it is the result the call
|
|
2227
|
+
* would make.
|
|
2228
|
+
*/
|
|
2229
|
+
export function applyOperations(input, operations, options = {}) {
|
|
2230
|
+
const moved = options.movedStoredNodes === true && Object.isFrozen(input);
|
|
2231
|
+
const safeOperations = moved ? readMovesOfStoredNodes(input, operations) : deserializeOperations(operations);
|
|
2232
|
+
// A document whose table is shared passes that on: what is applied to a
|
|
2233
|
+
// preview step (its layout view) does not copy the table either.
|
|
2234
|
+
const share = options.shareNodeTable ?? isSealedOverlay(input.nodes);
|
|
2235
|
+
const remembered = Object.isFrozen(input) ? recentResultOf(input, safeOperations, share) : undefined;
|
|
2236
|
+
if (remembered !== undefined)
|
|
2237
|
+
return remembered;
|
|
2238
|
+
const result = appliedOperations(input, operations, safeOperations, share, moved);
|
|
2239
|
+
rememberResult(input, safeOperations, share, result);
|
|
2240
|
+
return result;
|
|
2241
|
+
}
|
|
2242
|
+
/**
|
|
2243
|
+
* Reads `operations` as `deserializeOperations` does, but a `node.replace`
|
|
2244
|
+
* that only moves a node of the frozen `input` (`differsInPositionOnly`) is
|
|
2245
|
+
* read without checking the fields it keeps: its copy holds the stored
|
|
2246
|
+
* node's own frozen values, in the stored node's key order, and a new frozen
|
|
2247
|
+
* frame (or path transform) with a zero written as `0`, so it equals the
|
|
2248
|
+
* copy a full read makes (which also sorts every key) value for value. The
|
|
2249
|
+
* other operations are read by `deserializeOperations`, in
|
|
2250
|
+
* their order, so an invalid one throws the error it would throw there.
|
|
2251
|
+
*/
|
|
2252
|
+
function readMovesOfStoredNodes(input, operations) {
|
|
2253
|
+
if (!Array.isArray(operations))
|
|
2254
|
+
return deserializeOperations(operations);
|
|
2255
|
+
const read = new Array(operations.length);
|
|
2256
|
+
const others = [];
|
|
2257
|
+
operations.forEach((operation, index) => {
|
|
2258
|
+
const moved = readMoveOfStoredNode(input, operation);
|
|
2259
|
+
if (moved === undefined)
|
|
2260
|
+
others.push(index);
|
|
2261
|
+
else
|
|
2262
|
+
read[index] = moved;
|
|
2263
|
+
});
|
|
2264
|
+
if (others.length > 0) {
|
|
2265
|
+
const checked = deserializeOperations(others.map((index) => operations[index]));
|
|
2266
|
+
others.forEach((index, position) => { read[index] = checked[position]; });
|
|
2267
|
+
}
|
|
2268
|
+
return Object.freeze(read);
|
|
2269
|
+
}
|
|
2270
|
+
/** The frozen copy of `operation` when it only moves a node of `input` (see `readMovesOfStoredNodes`). */
|
|
2271
|
+
function readMoveOfStoredNode(input, operation) {
|
|
2272
|
+
if (typeof operation !== "object" || operation === null)
|
|
2273
|
+
return undefined;
|
|
2274
|
+
const prototype = Object.getPrototypeOf(operation);
|
|
2275
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
2276
|
+
return undefined;
|
|
2277
|
+
const candidate = operation;
|
|
2278
|
+
if (candidate.type !== "node.replace" || Reflect.ownKeys(candidate).length !== 2)
|
|
2279
|
+
return undefined;
|
|
2280
|
+
const node = candidate.node;
|
|
2281
|
+
if (typeof node !== "object" || node === null || typeof node.id !== "string")
|
|
2282
|
+
return undefined;
|
|
2283
|
+
const stored = entryOf(input.nodes, node.id);
|
|
2284
|
+
if (stored === undefined || !differsInPositionOnly(stored, node))
|
|
2285
|
+
return undefined;
|
|
2286
|
+
jsonCodecStats.positionOnlyChecks += 1;
|
|
2287
|
+
// JSON writes -0 as 0.
|
|
2288
|
+
const zeroed = (value) => (value === 0 ? 0 : value);
|
|
2289
|
+
const field = positionFieldOf(stored);
|
|
2290
|
+
const moved = node[field];
|
|
2291
|
+
let position;
|
|
2292
|
+
if (field === "transform") {
|
|
2293
|
+
const [a, b, c, d, e, f] = moved;
|
|
2294
|
+
position = Object.freeze([zeroed(a), zeroed(b), zeroed(c), zeroed(d), zeroed(e), zeroed(f)]);
|
|
2295
|
+
}
|
|
2296
|
+
else {
|
|
2297
|
+
const { x, y } = moved;
|
|
2298
|
+
const storedFrame = stored.frame;
|
|
2299
|
+
position = Object.freeze({ height: storedFrame.height, width: storedFrame.width, x: zeroed(x), y: zeroed(y) });
|
|
2300
|
+
}
|
|
2301
|
+
const copy = {};
|
|
2302
|
+
for (const key of Object.keys(stored)) {
|
|
2303
|
+
copy[key] = key === field ? position : stored[key];
|
|
2304
|
+
}
|
|
2305
|
+
return Object.freeze({ type: "node.replace", node: Object.freeze(copy) });
|
|
2306
|
+
}
|
|
2307
|
+
/**
|
|
2308
|
+
* A sealed node table that reads as `nodes` with `written` put over it, and
|
|
2309
|
+
* shares the entries of `nodes` (`sharedTableDraft`, in O(1) and the writes
|
|
2310
|
+
* when `nodes` is a shared table), for a view laid out again from `nodes` by
|
|
2311
|
+
* a few edits. The parents and whether it holds a group are taken from
|
|
2312
|
+
* `nodes`, so those edits read no node they do not write; the parents only
|
|
2313
|
+
* when no entry of `written` changes a list of children.
|
|
2314
|
+
*
|
|
2315
|
+
* With `ownFamily`, the table is a copy of every entry of `nodes` instead
|
|
2316
|
+
* (`sharedTableCopy`), starting a family of its own: tables of two families
|
|
2317
|
+
* are read by turns without moving each other's head.
|
|
2318
|
+
*/
|
|
2319
|
+
export function sharedNodeTable(nodes, written = [], ownFamily = false) {
|
|
2320
|
+
const draft = (ownFamily ? sharedTableCopy(nodes) : sharedTableDraft(nodes));
|
|
2321
|
+
let sameChildren = true;
|
|
2322
|
+
for (const [id, node] of written) {
|
|
2323
|
+
const before = entryOf(nodes, id);
|
|
2324
|
+
if (before === undefined || !sameChildList(before, node))
|
|
2325
|
+
sameChildren = false;
|
|
2326
|
+
draft[id] = node;
|
|
2327
|
+
}
|
|
2328
|
+
const table = sealSharedTable(draft);
|
|
2329
|
+
if (sameChildren)
|
|
2330
|
+
recordParents(table, parentMapOf(nodes));
|
|
2331
|
+
recordHoldsGroup(nodes, table, written.map(([id]) => id));
|
|
2332
|
+
return table;
|
|
2333
|
+
}
|
|
2334
|
+
/** Whether two entries of one node list the same children (none for both, or the same IDs in the same order). */
|
|
2335
|
+
function sameChildList(left, right) {
|
|
2336
|
+
const leftChildren = "children" in left ? left.children : undefined;
|
|
2337
|
+
const rightChildren = "children" in right ? right.children : undefined;
|
|
2338
|
+
if (leftChildren === rightChildren)
|
|
2339
|
+
return true;
|
|
2340
|
+
if (leftChildren === undefined || rightChildren === undefined || leftChildren.length !== rightChildren.length)
|
|
2341
|
+
return false;
|
|
2342
|
+
return leftChildren.every((id, index) => id === rightChildren[index]);
|
|
2343
|
+
}
|
|
2344
|
+
/**
|
|
2345
|
+
* A frozen node table that reads as `nodes` with `entries` put over it, in
|
|
2346
|
+
* their order, for a view of a document that draws some nodes otherwise
|
|
2347
|
+
* (such as an editor's workspace around a page). When `nodes` is shared
|
|
2348
|
+
* (`ApplyOperationsOptions.shareNodeTable`), or `options.share` asks for it,
|
|
2349
|
+
* the result reads `nodes` for every other entry and costs as much as
|
|
2350
|
+
* `entries`; otherwise it is a frozen copy, as
|
|
2351
|
+
* `Object.freeze({ ...nodes, ...entries })` makes. A shared table lists its
|
|
2352
|
+
* entries one at a time (see `tableValues`), so share one that is read by ID.
|
|
2353
|
+
*/
|
|
2354
|
+
export function nodeTableWith(nodes, entries, options = {}) {
|
|
2355
|
+
const shared = options.share === true || isSealedOverlay(nodes);
|
|
2356
|
+
const table = (shared ? overlayTable(nodes) : sharedTableDraft(nodes));
|
|
2357
|
+
for (const [id, node] of entries) {
|
|
2358
|
+
putEntry(table, id, node);
|
|
2359
|
+
nodeTableWithStats.entriesPut += 1;
|
|
2360
|
+
}
|
|
2361
|
+
const result = shared ? sealOverlay(table) : sealSharedTable(table);
|
|
2362
|
+
rememberFrozenNodeMap(result);
|
|
2363
|
+
return result;
|
|
2364
|
+
}
|
|
2365
|
+
/**
|
|
2366
|
+
* A frozen node table that reads as `nodes` with the entries of `written`
|
|
2367
|
+
* put over it, reading `written` itself rather than a copy: it costs the
|
|
2368
|
+
* same at any size of either, so a view of a document that draws many nodes
|
|
2369
|
+
* otherwise (such as instances expanded into their layers) passes the same
|
|
2370
|
+
* `written` again when an edit changed none of them. `written` must not
|
|
2371
|
+
* change once passed. Read it by ID; listing every entry goes through a
|
|
2372
|
+
* Proxy one entry at a time. With `sameParents`, the entries of `written`
|
|
2373
|
+
* give no node a parent other than the one it has in `nodes` (none for a
|
|
2374
|
+
* node `nodes` lacks), so the table keeps the parents of `nodes`
|
|
2375
|
+
* (`parentMapOf`) instead of reading every node for them.
|
|
2376
|
+
* @since 0.37.0
|
|
2377
|
+
*/
|
|
2378
|
+
export function nodeTableReading(nodes, written, options = {}) {
|
|
2379
|
+
const table = overlayTableReading(nodes, written);
|
|
2380
|
+
rememberFrozenNodeMap(table);
|
|
2381
|
+
if (options.sameParents === true)
|
|
2382
|
+
recordParents(table, parentMapOf(nodes));
|
|
2383
|
+
return table;
|
|
2384
|
+
}
|
|
2385
|
+
/**
|
|
2386
|
+
* The most results of `applyOperations` kept, over all documents. Each holds
|
|
2387
|
+
* a node table of its own, so the number is fixed: documents kept in undo
|
|
2388
|
+
* history do not keep results of their own.
|
|
2389
|
+
*/
|
|
2390
|
+
const RECENT_RESULTS = 4;
|
|
2391
|
+
/** The last results of `applyOperations` on frozen documents, the most recently used first. */
|
|
2392
|
+
const recentResults = [];
|
|
2393
|
+
/**
|
|
2394
|
+
* The kept result of the read operations `safeOperations` on the frozen
|
|
2395
|
+
* `input`, when the same operations, compared by value, were applied to it
|
|
2396
|
+
* lately; it becomes the most recently used. Comparing costs as much as
|
|
2397
|
+
* reading the operations, not as much as the document.
|
|
2398
|
+
*/
|
|
2399
|
+
function recentResultOf(input, safeOperations, share) {
|
|
2400
|
+
const index = recentResults.findIndex((entry) => (entry.input === input &&
|
|
2401
|
+
entry.share === share &&
|
|
2402
|
+
entry.operations.length === safeOperations.length &&
|
|
2403
|
+
entry.operations.every((operation, position) => same(operation, safeOperations[position]))));
|
|
2404
|
+
if (index < 0)
|
|
2405
|
+
return undefined;
|
|
2406
|
+
const [entry] = recentResults.splice(index, 1);
|
|
2407
|
+
recentResults.unshift(entry);
|
|
2408
|
+
return entry.result;
|
|
2409
|
+
}
|
|
2410
|
+
/**
|
|
2411
|
+
* Keeps `result` as the result of the read operations `safeOperations` on
|
|
2412
|
+
* `input`, when `input` is frozen and so cannot change, and no equal
|
|
2413
|
+
* operations on it are kept already. Every part of the result is frozen, so
|
|
2414
|
+
* callers can share it.
|
|
2415
|
+
*/
|
|
2416
|
+
function rememberResult(input, safeOperations, share, result) {
|
|
2417
|
+
if (!Object.isFrozen(input) || recentResultOf(input, safeOperations, share) !== undefined)
|
|
2418
|
+
return;
|
|
2419
|
+
recentResults.unshift({ input, operations: safeOperations, share, result });
|
|
2420
|
+
recentResults.length = Math.min(recentResults.length, RECENT_RESULTS);
|
|
2421
|
+
}
|
|
2422
|
+
/**
|
|
2423
|
+
* Adds to `changes` the nodes that use an asset the operations changed, in
|
|
2424
|
+
* `before` or in `after`, so readers of the changes (and the check of the
|
|
2425
|
+
* edited document) see them. A node that uses it in one and not the other
|
|
2426
|
+
* differs between the two, and is listed already; any other one is the same
|
|
2427
|
+
* entry in both with the same theme, so the users in `before` are the rest
|
|
2428
|
+
* (`nodesUsingAsset`). After a theme change `changes` must list the nodes
|
|
2429
|
+
* that use a part of the theme that changed (`addThemeUsers`): what any other
|
|
2430
|
+
* node uses is the same in both, so the users in `before` are the rest here
|
|
2431
|
+
* too.
|
|
2432
|
+
*/
|
|
2433
|
+
function addAssetUsers(before, _after, changes) {
|
|
2434
|
+
if (changes.changedAssetIds.size === 0)
|
|
2435
|
+
return;
|
|
2436
|
+
for (const assetId of changes.changedAssetIds) {
|
|
2437
|
+
for (const id of nodesUsingAsset(before, assetId))
|
|
2438
|
+
changes.changedNodeIds.add(id);
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
/**
|
|
2442
|
+
* Adds to `changes` the nodes that use a part of the theme that differs
|
|
2443
|
+
* between `before` and `after` (`nodesUsingThemeChange`), so the steps that
|
|
2444
|
+
* follow, the check of the edited document and readers of the changes see
|
|
2445
|
+
* them, and no other node. A node that the operations wrote is listed
|
|
2446
|
+
* already; any other one is the same entry in both documents, so the users
|
|
2447
|
+
* in `before` are the rest.
|
|
2448
|
+
*/
|
|
2449
|
+
function addThemeUsers(before, after, changes) {
|
|
2450
|
+
for (const id of nodesUsingThemeChange(before, before.theme, after.theme))
|
|
2451
|
+
changes.changedNodeIds.add(id);
|
|
2452
|
+
}
|
|
2453
|
+
function appliedOperations(input, operations, safeOperations, share, movedStoredNodes) {
|
|
2454
|
+
const { document, next, inverseOperations, changes: combinedChanges } = runOperations(input, operations, undefined, safeOperations, share);
|
|
2455
|
+
if (!combinedChanges.documentChanged || sameAtChangedNodes(document, next, combinedChanges.changedNodeIds)) {
|
|
2456
|
+
return { document, inverseOperations: EMPTY_INVERSE_OPERATIONS, changes: EMPTY_CHANGE_SET };
|
|
2457
|
+
}
|
|
2458
|
+
addAssetUsers(document, next, combinedChanges);
|
|
2459
|
+
const touched = touchedNodeIds(combinedChanges);
|
|
2460
|
+
const nextParents = derivedParents(document.nodes, parentMapOf(document.nodes), next.nodes, touched);
|
|
2461
|
+
refuseSlotsWithoutProperty(next, nextParents, safeOperations);
|
|
2462
|
+
markChangedComponents(document, next, nextParents, combinedChanges);
|
|
2463
|
+
// Only the entities these operations wrote can have an invalid shape. Rules
|
|
2464
|
+
// that span entities are still checked across the whole document.
|
|
2465
|
+
modelApplyStats.changedDocumentChecks += 1;
|
|
2466
|
+
assertChangedDocument(next, {
|
|
2467
|
+
nodeIds: combinedChanges.changedNodeIds,
|
|
2468
|
+
pageIds: combinedChanges.changedPageIds,
|
|
2469
|
+
assetIds: combinedChanges.changedAssetIds,
|
|
2470
|
+
componentIds: combinedChanges.changedComponentIds,
|
|
2471
|
+
themeChanged: combinedChanges.themeChanged,
|
|
2472
|
+
commentThreadsChanged: combinedChanges.changedCommentThreadIds.size > 0,
|
|
2473
|
+
previous: document,
|
|
2474
|
+
movedStoredNodes,
|
|
2475
|
+
assetUsersWritten: true,
|
|
2476
|
+
themeUsersWritten: true,
|
|
2477
|
+
});
|
|
2478
|
+
const frozenDocument = freezeWrittenParts(next, combinedChanges.changedNodeIds);
|
|
2479
|
+
recordParents(frozenDocument.nodes, nextParents);
|
|
2480
|
+
if (frozenDocument.nodes !== document.nodes)
|
|
2481
|
+
recordChangedNodes(frozenDocument.nodes, [...combinedChanges.changedNodeIds]);
|
|
2482
|
+
recordHoldsGroup(document.nodes, frozenDocument.nodes, touched);
|
|
2483
|
+
// An edit of a document known to be valid passed the check above, so the
|
|
2484
|
+
// result is valid too, and readers that check whole documents (such as an
|
|
2485
|
+
// accessibility snapshot after every edit) need not walk it again.
|
|
2486
|
+
if (fullyValidatedDocuments.has(document))
|
|
2487
|
+
fullyValidatedDocuments.add(frozenDocument);
|
|
2488
|
+
const insertedOrRemovedNodeIds = Object.freeze([
|
|
2489
|
+
...new Set([...combinedChanges.insertedNodeIds, ...combinedChanges.removedNodeIds]),
|
|
2490
|
+
]);
|
|
2491
|
+
normalizeReinserts(combinedChanges);
|
|
2492
|
+
const changes = freezeChanges(combinedChanges);
|
|
2493
|
+
derivations.set(frozenDocument, {
|
|
2494
|
+
base: new WeakRef(document),
|
|
2495
|
+
changedNodeIds: changes.changedNodeIds,
|
|
2496
|
+
insertedOrRemovedNodeIds,
|
|
2497
|
+
});
|
|
2498
|
+
keepAssetUsers(document, frozenDocument, true);
|
|
2499
|
+
keepThemeUsers(document, frozenDocument);
|
|
2500
|
+
keepConnectorEnds(document, frozenDocument);
|
|
2501
|
+
return {
|
|
2502
|
+
document: frozenDocument,
|
|
2503
|
+
inverseOperations: deepFreeze(inverseOperations),
|
|
2504
|
+
changes,
|
|
2505
|
+
};
|
|
2506
|
+
}
|
|
2507
|
+
/**
|
|
2508
|
+
* Whether `next`, made from the frozen `document` by operations that wrote
|
|
2509
|
+
* the nodes `changedNodeIds` (and no others), has the same content. Only the
|
|
2510
|
+
* written nodes are compared; every other node is the same object in both.
|
|
2511
|
+
*/
|
|
2512
|
+
function sameAtChangedNodes(document, next, changedNodeIds) {
|
|
2513
|
+
for (const id of changedNodeIds) {
|
|
2514
|
+
if (!same(entryOf(document.nodes, id), entryOf(next.nodes, id)))
|
|
2515
|
+
return false;
|
|
2516
|
+
}
|
|
2517
|
+
return same({ ...document, nodes: undefined }, { ...next, nodes: undefined });
|
|
2518
|
+
}
|
|
2519
|
+
/** The operation types `ApplyOperationsOptions.shareNodeTable` applies to: none adds or removes a node. */
|
|
2520
|
+
const SHARING_OPERATION_TYPES = new Set(["node.replace", "node.patch"]);
|
|
2521
|
+
/**
|
|
2522
|
+
* Freezes the document operations made from a frozen one. Nodes they did not
|
|
2523
|
+
* write are the frozen nodes of the input, so only the written nodes, the
|
|
2524
|
+
* node map, and the other parts of the document are read.
|
|
2525
|
+
*/
|
|
2526
|
+
function freezeWrittenParts(next, changedNodeIds) {
|
|
2527
|
+
for (const id of changedNodeIds)
|
|
2528
|
+
deepFreeze(entryOf(next.nodes, id));
|
|
2529
|
+
for (const [key, value] of Object.entries(next)) {
|
|
2530
|
+
// A shared table (`shareNodeTable`) is a Proxy, which cannot be frozen: it is sealed.
|
|
2531
|
+
if (key === "nodes") {
|
|
2532
|
+
rememberFrozenNodeMap(isSharedNodeTable(value) ? sealSharedTable(value) : overlayParts(value) === undefined ? Object.freeze(value) : sealOverlay(value));
|
|
2533
|
+
}
|
|
2534
|
+
else
|
|
2535
|
+
deepFreeze(value);
|
|
2536
|
+
}
|
|
2537
|
+
return Object.freeze(next);
|
|
2538
|
+
}
|
|
2539
|
+
/**
|
|
2540
|
+
* `document` with each of `nodes` in place of the node with its ID, and
|
|
2541
|
+
* `addedAssets` added to its assets: what `{ ...document, nodes: { ...document.nodes, ...nodes },
|
|
2542
|
+
* assets: { ...document.assets, ...addedAssets } }` makes. For a change made
|
|
2543
|
+
* while a document opens, such as binding its text to this computer's fonts,
|
|
2544
|
+
* that must not be an undo step or settle any layout.
|
|
2545
|
+
*
|
|
2546
|
+
* When `document` is known to be valid and frozen (from
|
|
2547
|
+
* `deserializeCheckedDocument`, or an edit of such a document), only the
|
|
2548
|
+
* written nodes and added assets, and the tree and references around them, are
|
|
2549
|
+
* checked (`assertChangedDocument`), and the result is frozen and known to be
|
|
2550
|
+
* valid too, so `new DocumentStore` takes it without checking it again. Any
|
|
2551
|
+
* other document gets the same result without a check, unfrozen, and is
|
|
2552
|
+
* checked in full when it opens.
|
|
2553
|
+
*
|
|
2554
|
+
* Throws a `ModelError` when a node is not in `document`, an added asset's ID
|
|
2555
|
+
* is, or the result is not valid.
|
|
2556
|
+
*/
|
|
2557
|
+
export function writeOpeningChanges(document, nodes, addedAssets = []) {
|
|
2558
|
+
for (const node of nodes) {
|
|
2559
|
+
if (entryOf(document.nodes, node.id) === undefined) {
|
|
2560
|
+
throw new ModelError("INVALID_TREE", `Node ${node.id} is not in the document`, `$.nodes.${node.id}`, { parts: [{ kind: "node", id: node.id }] });
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
for (const asset of addedAssets) {
|
|
2564
|
+
if (entryOf(document.assets, asset.id) !== undefined) {
|
|
2565
|
+
throw new ModelError("INVALID_SCHEMA", `Asset ${asset.id} is already in the document`, `$.assets.${asset.id}`, { parts: [{ kind: "asset", id: asset.id }] });
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
if (nodes.length === 0 && addedAssets.length === 0)
|
|
2569
|
+
return document;
|
|
2570
|
+
const checked = fullyValidatedDocuments.has(document);
|
|
2571
|
+
// A checked result holds only plain data it owns, so the written parts are copied before they are frozen.
|
|
2572
|
+
const written = nodes.map((node) => clampGeometry(checked ? cloneJson(node) : node));
|
|
2573
|
+
const added = checked ? addedAssets.map((asset) => cloneJson(asset)) : addedAssets;
|
|
2574
|
+
const nodeTable = checked ? nodeTableToWrite(document.nodes) : { ...document.nodes };
|
|
2575
|
+
for (const node of written)
|
|
2576
|
+
putEntry(nodeTable, node.id, node);
|
|
2577
|
+
const assets = { ...document.assets };
|
|
2578
|
+
for (const asset of added)
|
|
2579
|
+
putEntry(assets, asset.id, asset);
|
|
2580
|
+
const next = { ...document, nodes: nodeTable, assets };
|
|
2581
|
+
if (!checked)
|
|
2582
|
+
return next;
|
|
2583
|
+
const nodeIds = new Set(written.map((node) => node.id));
|
|
2584
|
+
assertChangedDocument(next, {
|
|
2585
|
+
nodeIds,
|
|
2586
|
+
pageIds: new Set(),
|
|
2587
|
+
assetIds: new Set(added.map((asset) => asset.id)),
|
|
2588
|
+
componentIds: new Set(),
|
|
2589
|
+
themeChanged: false,
|
|
2590
|
+
previous: document,
|
|
2591
|
+
// An asset that was not in `document` is used by no node but the written ones, which are checked.
|
|
2592
|
+
assetUsersWritten: true,
|
|
2593
|
+
});
|
|
2594
|
+
const frozen = freezeWrittenParts(next, nodeIds);
|
|
2595
|
+
fullyValidatedDocuments.add(frozen);
|
|
2596
|
+
return frozen;
|
|
2597
|
+
}
|
|
2598
|
+
/**
|
|
2599
|
+
* The nodes whose entries can differ between two documents that came, through
|
|
2600
|
+
* `applyOperations`, from one common document: every node either side changed
|
|
2601
|
+
* on its way from there. Undefined when no common document is found within
|
|
2602
|
+
* `MAX_DERIVATION_STEPS` steps, and the caller compares every node.
|
|
2603
|
+
*
|
|
2604
|
+
* Previews of a drag are each applied to the same committed document, so two
|
|
2605
|
+
* previews have that document in common and differ at most in the nodes the
|
|
2606
|
+
* two moves wrote, however large the document is.
|
|
2607
|
+
*/
|
|
2608
|
+
function nodesThatMayDiffer(previous, current, nodesOf = (derivation) => derivation.changedNodeIds) {
|
|
2609
|
+
// Each document `previous` came from, with the change lists on the way to it.
|
|
2610
|
+
const fromPrevious = new Map();
|
|
2611
|
+
let document = previous;
|
|
2612
|
+
let path = [];
|
|
2613
|
+
for (let step = 0; document !== undefined; step += 1) {
|
|
2614
|
+
fromPrevious.set(document, path);
|
|
2615
|
+
const derivation = derivations.get(document);
|
|
2616
|
+
if (derivation === undefined || step === MAX_DERIVATION_STEPS)
|
|
2617
|
+
break;
|
|
2618
|
+
path = [...path, nodesOf(derivation)];
|
|
2619
|
+
document = derivation.base.deref();
|
|
2620
|
+
}
|
|
2621
|
+
document = current;
|
|
2622
|
+
const fromCurrent = [];
|
|
2623
|
+
for (let step = 0; document !== undefined; step += 1) {
|
|
2624
|
+
const common = fromPrevious.get(document);
|
|
2625
|
+
if (common !== undefined) {
|
|
2626
|
+
const ids = new Set();
|
|
2627
|
+
for (const list of [...common, ...fromCurrent])
|
|
2628
|
+
for (const id of list)
|
|
2629
|
+
ids.add(id);
|
|
2630
|
+
return ids;
|
|
2631
|
+
}
|
|
2632
|
+
const derivation = derivations.get(document);
|
|
2633
|
+
if (derivation === undefined || step === MAX_DERIVATION_STEPS)
|
|
2634
|
+
return undefined;
|
|
2635
|
+
fromCurrent.push(nodesOf(derivation));
|
|
2636
|
+
document = derivation.base.deref();
|
|
2637
|
+
}
|
|
2638
|
+
return undefined;
|
|
2639
|
+
}
|
|
2640
|
+
/**
|
|
2641
|
+
* The IDs of every node whose entry can differ between two documents, read
|
|
2642
|
+
* from the edits that made them (`applyOperations`, `recordDerivedNodes`)
|
|
2643
|
+
* without reading any node; the list may hold nodes whose entry is the same
|
|
2644
|
+
* object in both. Code that keeps an index per document can update it from
|
|
2645
|
+
* these instead of comparing every node. Undefined when neither document
|
|
2646
|
+
* came from the other or from a common document within a few recorded
|
|
2647
|
+
* steps; the caller then reads the whole document.
|
|
2648
|
+
* @since 0.33.0
|
|
2649
|
+
*/
|
|
2650
|
+
export function nodesChangedBetween(previous, current) {
|
|
2651
|
+
if (previous === current || previous.nodes === current.nodes)
|
|
2652
|
+
return new Set();
|
|
2653
|
+
return nodesThatMayDiffer(previous, current);
|
|
2654
|
+
}
|
|
2655
|
+
/**
|
|
2656
|
+
* The IDs of every node that may have been inserted or removed on the way
|
|
2657
|
+
* between two documents, a node removed and put back included (it then
|
|
2658
|
+
* comes last in the node table's order), read from the edits that made them
|
|
2659
|
+
* as `nodesChangedBetween` reads them. A node only written in place is left
|
|
2660
|
+
* out, so code that keeps nodes in table order can keep its order when none
|
|
2661
|
+
* of its nodes are listed. Where an edit kept no such record, every node it
|
|
2662
|
+
* changed is listed. Undefined when `nodesChangedBetween` is.
|
|
2663
|
+
* @since 0.35.0
|
|
2664
|
+
*/
|
|
2665
|
+
export function nodesInsertedOrRemovedBetween(previous, current) {
|
|
2666
|
+
if (previous === current || previous.nodes === current.nodes)
|
|
2667
|
+
return new Set();
|
|
2668
|
+
return nodesThatMayDiffer(previous, current, (derivation) => derivation.insertedOrRemovedNodeIds ?? derivation.changedNodeIds);
|
|
2669
|
+
}
|
|
2670
|
+
/**
|
|
2671
|
+
* Records that the frozen document `derived` holds the node entries of
|
|
2672
|
+
* `base`, the very same objects, at every ID except `changedNodeIds`. Code
|
|
2673
|
+
* that builds a document from another outside `applyOperations` (such as a
|
|
2674
|
+
* renderer view that swaps a few nodes for drawn stand-ins) calls this so
|
|
2675
|
+
* that `diffDocuments` reads only those nodes when it compares documents
|
|
2676
|
+
* built this way, as it does for edits. When a parent table is kept for
|
|
2677
|
+
* `base`, the table of `derived` is derived from it too, reading only those
|
|
2678
|
+
* nodes and their children. Listing too few nodes makes later diffs miss
|
|
2679
|
+
* changes; nothing is recorded when `derived` is not frozen.
|
|
2680
|
+
*/
|
|
2681
|
+
export function recordDerivedNodes(derived, base, changedNodeIds) {
|
|
2682
|
+
if (!Object.isFrozen(derived) || !isFrozenNodeMap(derived.nodes) || derived === base)
|
|
2683
|
+
return;
|
|
2684
|
+
derivations.set(derived, { base: new WeakRef(base), changedNodeIds: Object.freeze([...changedNodeIds]) });
|
|
2685
|
+
keepAssetUsers(base, derived);
|
|
2686
|
+
keepThemeUsers(base, derived);
|
|
2687
|
+
keepConnectorEnds(base, derived);
|
|
2688
|
+
// The parent table of `derived` follows from the one kept for `base` the
|
|
2689
|
+
// way an edit's does, so a diff that asks for it reads only those nodes.
|
|
2690
|
+
const baseParents = keptParents(base.nodes);
|
|
2691
|
+
if (baseParents !== undefined && keptParents(derived.nodes) === undefined && derived.nodes !== base.nodes) {
|
|
2692
|
+
recordParents(derived.nodes, derivedParents(base.nodes, baseParents, derived.nodes, changedNodeIds));
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
/**
|
|
2696
|
+
* `diffDocuments` results for pairs of frozen documents, by previous then
|
|
2697
|
+
* current document. A frozen document cannot change, so its diff with another
|
|
2698
|
+
* stays the same; one drag preview is compared with the one before it by
|
|
2699
|
+
* several steps of the renderer update, and each gets the first result.
|
|
2700
|
+
*/
|
|
2701
|
+
const documentDiffs = new WeakMap();
|
|
2702
|
+
/**
|
|
2703
|
+
* Works out the `ChangeSet` between two valid documents, for changes that
|
|
2704
|
+
* did not come from `applyOperations` (such as undo or checkout in
|
|
2705
|
+
* `DocumentStore`). Parts shared by identity are skipped without reading.
|
|
2706
|
+
*/
|
|
2707
|
+
export function diffDocuments(previous, current) {
|
|
2708
|
+
if (previous === current)
|
|
2709
|
+
return EMPTY_CHANGE_SET;
|
|
2710
|
+
// Only frozen documents are remembered: an unfrozen one could change later.
|
|
2711
|
+
const remember = Object.isFrozen(previous) && isFrozenNodeMap(previous.nodes) &&
|
|
2712
|
+
Object.isFrozen(current) && isFrozenNodeMap(current.nodes);
|
|
2713
|
+
const known = remember ? documentDiffs.get(previous)?.get(current) : undefined;
|
|
2714
|
+
if (known !== undefined)
|
|
2715
|
+
return known;
|
|
2716
|
+
const changes = compareDocuments(previous, current);
|
|
2717
|
+
if (remember) {
|
|
2718
|
+
let byCurrent = documentDiffs.get(previous);
|
|
2719
|
+
if (byCurrent === undefined) {
|
|
2720
|
+
byCurrent = new WeakMap();
|
|
2721
|
+
documentDiffs.set(previous, byCurrent);
|
|
2722
|
+
}
|
|
2723
|
+
byCurrent.set(current, changes);
|
|
2724
|
+
}
|
|
2725
|
+
return changes;
|
|
2726
|
+
}
|
|
2727
|
+
/**
|
|
2728
|
+
* The nodes whose entries are not the same object in both node maps. Edits
|
|
2729
|
+
* reuse every node they do not write, so only these can differ in content.
|
|
2730
|
+
*/
|
|
2731
|
+
function nodesNotShared(previous, current) {
|
|
2732
|
+
modelApplyStats.diffWholeNodeMapScans += 1;
|
|
2733
|
+
// Both tables are listed before either is read, each once, so two shared
|
|
2734
|
+
// tables far apart in one family are not made the head by turns.
|
|
2735
|
+
const previousEntries = tableEntries(previous);
|
|
2736
|
+
const previousIds = new Set();
|
|
2737
|
+
for (const [id] of previousEntries)
|
|
2738
|
+
previousIds.add(id);
|
|
2739
|
+
const currentIds = tableKeys(current);
|
|
2740
|
+
const ids = new Set();
|
|
2741
|
+
for (const [id, node] of previousEntries) {
|
|
2742
|
+
if (node !== entryOf(current, id))
|
|
2743
|
+
ids.add(id);
|
|
2744
|
+
}
|
|
2745
|
+
for (const id of currentIds) {
|
|
2746
|
+
if (!previousIds.has(id))
|
|
2747
|
+
ids.add(id);
|
|
2748
|
+
}
|
|
2749
|
+
return ids;
|
|
2750
|
+
}
|
|
2751
|
+
function compareDocuments(previous, current) {
|
|
2752
|
+
modelApplyStats.documentDiffs += 1;
|
|
2753
|
+
const changes = createMutableChanges();
|
|
2754
|
+
changes.documentChanged = true;
|
|
2755
|
+
changes.themeChanged = previous.theme !== current.theme && !same(previous.theme, current.theme);
|
|
2756
|
+
// Unchanged maps are reused rather than rebuilt, so identity rules out a
|
|
2757
|
+
// whole category of changes without reading any entry. When both documents
|
|
2758
|
+
// came from one document through `applyOperations`, only the nodes changed
|
|
2759
|
+
// on the way can differ, so only those are read. Failing that, when both
|
|
2760
|
+
// node tables are shared tables of one family, only the entries written
|
|
2761
|
+
// between them can differ, and those are read with both tables' entries;
|
|
2762
|
+
// otherwise only the nodes that are not the same object in both.
|
|
2763
|
+
let nodeIds;
|
|
2764
|
+
let sharedPairs;
|
|
2765
|
+
if (previous.nodes === current.nodes) {
|
|
2766
|
+
nodeIds = new Set();
|
|
2767
|
+
}
|
|
2768
|
+
else {
|
|
2769
|
+
const derived = nodesThatMayDiffer(previous, current);
|
|
2770
|
+
if (derived !== undefined) {
|
|
2771
|
+
nodeIds = derived;
|
|
2772
|
+
}
|
|
2773
|
+
else {
|
|
2774
|
+
sharedPairs = sharedTableDifferences(previous.nodes, current.nodes);
|
|
2775
|
+
nodeIds = sharedPairs === undefined
|
|
2776
|
+
? nodesNotShared(previous.nodes, current.nodes)
|
|
2777
|
+
: new Set(sharedPairs.keys());
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
modelApplyStats.diffNodesCompared += nodeIds.size;
|
|
2781
|
+
for (const id of nodeIds) {
|
|
2782
|
+
const pair = sharedPairs?.get(id);
|
|
2783
|
+
const before = pair === undefined ? entryOf(previous.nodes, id) : pair[0];
|
|
2784
|
+
const after = pair === undefined ? entryOf(current.nodes, id) : pair[1];
|
|
2785
|
+
if (!same(before, after)) {
|
|
2786
|
+
changes.changedNodeIds.add(id);
|
|
2787
|
+
if (before === undefined)
|
|
2788
|
+
changes.insertedNodeIds.add(id);
|
|
2789
|
+
if (after === undefined)
|
|
2790
|
+
changes.removedNodeIds.add(id);
|
|
2791
|
+
}
|
|
2792
|
+
}
|
|
2793
|
+
if (changes.changedNodeIds.size === 0 &&
|
|
2794
|
+
same({ ...previous, nodes: undefined }, { ...current, nodes: undefined })) {
|
|
2795
|
+
// No node differs, and neither does anything outside the nodes.
|
|
2796
|
+
return EMPTY_CHANGE_SET;
|
|
2797
|
+
}
|
|
2798
|
+
if (changes.changedNodeIds.size > 0) {
|
|
2799
|
+
const positionsAmong = (document, side) => {
|
|
2800
|
+
const result = new Map();
|
|
2801
|
+
for (const id of changes.changedNodeIds) {
|
|
2802
|
+
// The entries already read for the shared tables, when there are.
|
|
2803
|
+
const pair = sharedPairs?.get(id);
|
|
2804
|
+
const node = pair === undefined ? entryOf(document.nodes, id) : pair[side];
|
|
2805
|
+
if (node === undefined || !isContainerNode(node))
|
|
2806
|
+
continue;
|
|
2807
|
+
modelApplyStats.positionMapContainersVisited += 1;
|
|
2808
|
+
node.children.forEach((childId, index) => {
|
|
2809
|
+
result.set(childId, { parentId: node.id, index });
|
|
2810
|
+
});
|
|
2811
|
+
}
|
|
2812
|
+
return result;
|
|
2813
|
+
};
|
|
2814
|
+
const previousPositions = positionsAmong(previous, 0);
|
|
2815
|
+
const currentPositions = positionsAmong(current, 1);
|
|
2816
|
+
const positionedIds = new Set([
|
|
2817
|
+
...previousPositions.keys(),
|
|
2818
|
+
...currentPositions.keys(),
|
|
2819
|
+
]);
|
|
2820
|
+
for (const id of positionedIds) {
|
|
2821
|
+
if (entryOf(previous.nodes, id) === undefined || entryOf(current.nodes, id) === undefined)
|
|
2822
|
+
continue;
|
|
2823
|
+
const before = previousPositions.get(id);
|
|
2824
|
+
const after = currentPositions.get(id);
|
|
2825
|
+
if (before?.parentId !== after?.parentId ||
|
|
2826
|
+
before?.index !== after?.index) {
|
|
2827
|
+
getSubtreeNodeIds(previous, id).forEach((nodeId) => changes.changedNodeIds.add(nodeId));
|
|
2828
|
+
getSubtreeNodeIds(current, id).forEach((nodeId) => changes.changedNodeIds.add(nodeId));
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
// A node that is the same entry in both documents changes with the theme only when it uses a part that changed.
|
|
2833
|
+
if (changes.themeChanged)
|
|
2834
|
+
addThemeUsers(previous, current, changes);
|
|
2835
|
+
const pageIds = new Set([...Object.keys(previous.pages), ...Object.keys(current.pages)]);
|
|
2836
|
+
if (previous.pages !== current.pages) {
|
|
2837
|
+
for (const id of pageIds) {
|
|
2838
|
+
if (!same(entryOf(previous.pages, id), entryOf(current.pages, id))) {
|
|
2839
|
+
changes.changedPageIds.add(id);
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
const previousPageIndex = new Map(previous.pageOrder.map((id, index) => [id, index]));
|
|
2844
|
+
const currentPageIndex = new Map(current.pageOrder.map((id, index) => [id, index]));
|
|
2845
|
+
for (const id of pageIds) {
|
|
2846
|
+
if (previousPageIndex.get(id) !== currentPageIndex.get(id)) {
|
|
2847
|
+
changes.changedPageIds.add(id);
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2850
|
+
if (previous.components !== current.components) {
|
|
2851
|
+
const componentIds = new Set([
|
|
2852
|
+
...Object.keys(previous.components ?? {}),
|
|
2853
|
+
...Object.keys(current.components ?? {}),
|
|
2854
|
+
]);
|
|
2855
|
+
for (const id of componentIds) {
|
|
2856
|
+
if (!same(entryOf(previous.components, id), entryOf(current.components, id))) {
|
|
2857
|
+
changes.changedComponentIds.add(id);
|
|
2858
|
+
}
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
if (previous.assets !== current.assets) {
|
|
2862
|
+
const assetIds = new Set([...Object.keys(previous.assets), ...Object.keys(current.assets)]);
|
|
2863
|
+
for (const id of assetIds) {
|
|
2864
|
+
if (!same(entryOf(previous.assets, id), entryOf(current.assets, id)))
|
|
2865
|
+
changes.changedAssetIds.add(id);
|
|
2866
|
+
}
|
|
2867
|
+
// The nodes that use a changed asset; the users of a changed part of the theme are listed already.
|
|
2868
|
+
addAssetUsers(previous, current, changes);
|
|
2869
|
+
}
|
|
2870
|
+
if (previous.commentThreads !== current.commentThreads) {
|
|
2871
|
+
const previousThreads = new Map(previous.commentThreads.map((thread) => [thread.id, thread]));
|
|
2872
|
+
const currentThreads = new Map(current.commentThreads.map((thread) => [thread.id, thread]));
|
|
2873
|
+
for (const id of new Set([...previousThreads.keys(), ...currentThreads.keys()])) {
|
|
2874
|
+
if (!same(previousThreads.get(id), currentThreads.get(id)))
|
|
2875
|
+
changes.changedCommentThreadIds.add(id);
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
2878
|
+
// After the asset loop, so layers that changed only through an asset
|
|
2879
|
+
// still mark their component.
|
|
2880
|
+
markChangedComponents(previous, current, parentMapOf(current.nodes), changes);
|
|
2881
|
+
return freezeChanges(changes);
|
|
2882
|
+
}
|