@yuzhouu/canvas-kit 0.1.9 → 0.1.11
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/README.md +204 -101
- package/_vendor/canvas-core/bindings/bindingUtil.d.ts +23 -0
- package/_vendor/canvas-core/bindings/terminalPorts.d.ts +67 -0
- package/_vendor/canvas-core/editor/bindingReactionScope.d.ts +7 -0
- package/_vendor/canvas-core/editor/cameraPanSession.d.ts +9 -0
- package/_vendor/canvas-core/editor/canvasPanInteraction.d.ts +2 -0
- package/_vendor/canvas-core/editor/commands.d.ts +16 -4
- package/_vendor/canvas-core/editor/createEditorWithPlugins.d.ts +6 -0
- package/_vendor/canvas-core/editor/editor.d.ts +44 -31
- package/_vendor/canvas-core/editor/editorComputedHelpers.d.ts +5 -2
- package/_vendor/canvas-core/editor/historyManager.d.ts +24 -6
- package/_vendor/canvas-core/editor/index.d.ts +2 -2
- package/_vendor/canvas-core/editor/interactions.d.ts +41 -8
- package/_vendor/canvas-core/editor/managers/bindingManager.d.ts +2 -6
- package/_vendor/canvas-core/editor/managers/inputsManager.d.ts +3 -0
- package/_vendor/canvas-core/editor/managers/interactionTransientManager.d.ts +0 -26
- package/_vendor/canvas-core/editor/managers/queryManager.d.ts +26 -1
- package/_vendor/canvas-core/editor/managers/selectionLayoutManager.d.ts +5 -0
- package/_vendor/canvas-core/editor/managers/selectionOverlayManager.d.ts +1 -0
- package/_vendor/canvas-core/editor/managers/shapeEditingManager.d.ts +4 -0
- package/_vendor/canvas-core/editor/managers/shapeGeometryManager.d.ts +3 -2
- package/_vendor/canvas-core/editor/managers/shapeHierarchyManager.d.ts +7 -2
- package/_vendor/canvas-core/editor/managers/shapeReparenting.d.ts +3 -2
- package/_vendor/canvas-core/editor/managers/snapCalculations.d.ts +4 -1
- package/_vendor/canvas-core/editor/managers/snapGeometry.d.ts +2 -1
- package/_vendor/canvas-core/editor/managers/snapTypes.d.ts +1 -0
- package/_vendor/canvas-core/editor/managers/spatialIndexManager.d.ts +1 -0
- package/_vendor/canvas-core/editor/operationManager.d.ts +74 -0
- package/_vendor/canvas-core/editor/queries/shapeTransforms.d.ts +32 -12
- package/_vendor/canvas-core/editor/selection.d.ts +19 -5
- package/_vendor/canvas-core/editor/selectionOverlay.d.ts +7 -4
- package/_vendor/canvas-core/editor/selectionResizeCapabilities.d.ts +9 -0
- package/_vendor/canvas-core/editor/shapeTransformSpace.d.ts +6 -0
- package/_vendor/canvas-core/exports/svg.d.ts +3 -3
- package/_vendor/canvas-core/geometry/contentCutout.d.ts +8 -0
- package/_vendor/canvas-core/geometry/index.d.ts +1 -0
- package/_vendor/canvas-core/geometry/mat.d.ts +6 -2
- package/_vendor/canvas-core/geometry/polygon.d.ts +7 -0
- package/_vendor/canvas-core/geometry/vec.d.ts +0 -2
- package/_vendor/canvas-core/index.d.ts +21 -23
- package/_vendor/canvas-core/plugins/editorRuntimePlugin.d.ts +4 -10
- package/_vendor/canvas-core/plugins/editorRuntimeRegistry.d.ts +19 -0
- package/_vendor/canvas-core/plugins/index.d.ts +2 -1
- package/_vendor/canvas-core/schema/records.d.ts +2 -7
- package/_vendor/canvas-core/schema/snapshots.d.ts +10 -19
- package/_vendor/canvas-core/shapes/colors.d.ts +3 -3
- package/_vendor/canvas-core/shapes/shapeUtil.d.ts +97 -13
- package/_vendor/canvas-core/tools/select/selectToolHelpers.d.ts +18 -8
- package/_vendor/canvas-core/tools/select/states/draggingPluginInteractionState.d.ts +16 -0
- package/_vendor/canvas-core/tools/select/states/index.d.ts +1 -1
- package/_vendor/canvas-core/tools/select/states/pointingSelectionHandleInteractionState.d.ts +3 -2
- package/_vendor/canvas-core/tools/select/states/pointingShapeState.d.ts +1 -1
- package/_vendor/canvas-core/tools/select/states/resizingState.d.ts +1 -1
- package/_vendor/canvas-core/tools/select/states/rotatingState.d.ts +1 -1
- package/_vendor/canvas-core/tools/select/states/selectStateNode.d.ts +6 -2
- package/_vendor/canvas-core/tools/select/states/translatingState.d.ts +1 -1
- package/_vendor/canvas-plugin-sdk/actionRegistry.d.ts +7 -0
- package/_vendor/{canvas-core/surfaces → canvas-plugin-sdk}/actions.d.ts +21 -6
- package/_vendor/canvas-plugin-sdk/capability.d.ts +16 -0
- package/_vendor/canvas-plugin-sdk/chrome.d.ts +52 -0
- package/_vendor/canvas-plugin-sdk/chromeRegistry.d.ts +15 -0
- package/_vendor/{canvas-core/surfaces → canvas-plugin-sdk}/contextMenu.d.ts +25 -30
- package/_vendor/canvas-plugin-sdk/contextMenuRegistry.d.ts +11 -0
- package/_vendor/canvas-plugin-sdk/exportRegistry.d.ts +9 -0
- package/_vendor/canvas-plugin-sdk/exports.d.ts +26 -0
- package/_vendor/canvas-plugin-sdk/importRegistry.d.ts +10 -0
- package/_vendor/canvas-plugin-sdk/imports.d.ts +38 -0
- package/_vendor/canvas-plugin-sdk/index.d.ts +18 -0
- package/_vendor/canvas-plugin-sdk/lifecycle.d.ts +31 -0
- package/_vendor/canvas-plugin-sdk/plugin.d.ts +76 -0
- package/_vendor/canvas-plugin-sdk/pluginUi.d.ts +37 -0
- package/_vendor/canvas-plugin-sdk/productApi.d.ts +28 -0
- package/_vendor/canvas-plugin-sdk/services.d.ts +20 -0
- package/_vendor/{canvas-core/surfaces → canvas-plugin-sdk}/toolbar.d.ts +48 -5
- package/_vendor/canvas-plugin-sdk/toolbarRegistry.d.ts +18 -0
- package/_vendor/canvas-react/components/CanvasView.d.ts +2 -2
- package/_vendor/canvas-react/components/canvasKeyboardEvents.d.ts +13 -0
- package/_vendor/canvas-react/components/useCanvasDomEvents.d.ts +4 -3
- package/_vendor/canvas-react/contextMenuRequest.d.ts +19 -0
- package/_vendor/canvas-react/host/canvasRenderPlugin.d.ts +22 -5
- package/_vendor/canvas-react/host/canvasRenderRuntime.d.ts +13 -0
- package/_vendor/canvas-react/host/domEventGuards.d.ts +3 -3
- package/_vendor/canvas-react/host/index.d.ts +3 -9
- package/_vendor/canvas-react/host/overlayRegistry.d.ts +3 -3
- package/_vendor/canvas-react/host/rendererRegistry.d.ts +7 -4
- package/_vendor/canvas-react/index.d.ts +1 -0
- package/_vendor/plugin-arrow/api.d.ts +33 -0
- package/_vendor/plugin-arrow/arrowGeometry.d.ts +7 -4
- package/_vendor/plugin-arrow/arrowHeadGeometry.d.ts +8 -0
- package/_vendor/plugin-arrow/arrowShapeUtil.d.ts +7 -4
- package/_vendor/plugin-arrow/arrowTerminalCommands.d.ts +2 -2
- package/_vendor/plugin-arrow/canvasRender.d.ts +2 -2
- package/_vendor/plugin-arrow/editorRuntime.d.ts +2 -2
- package/_vendor/plugin-arrow/feature.d.ts +2 -3
- package/_vendor/plugin-arrow/index.d.ts +5 -2
- package/_vendor/plugin-arrow/productRuntime.d.ts +2 -0
- package/_vendor/plugin-builtin-clipboard/clipboardChromeContributions.d.ts +2 -0
- package/{features/clipboard → _vendor/plugin-builtin-clipboard}/clipboardContextMenuContributions.d.ts +1 -1
- package/{features/clipboard → _vendor/plugin-builtin-clipboard}/clipboardContribution.d.ts +2 -2
- package/{features/clipboard → _vendor/plugin-builtin-clipboard}/clipboardService.d.ts +3 -3
- package/_vendor/plugin-builtin-clipboard/index.d.ts +3 -0
- package/_vendor/plugin-builtin-clipboard/plugin.d.ts +1 -0
- package/_vendor/plugin-builtin-export/blobDataUrl.d.ts +1 -0
- package/_vendor/plugin-builtin-export/canvasExportApi.d.ts +43 -0
- package/_vendor/plugin-builtin-export/index.d.ts +8 -0
- package/_vendor/plugin-builtin-export/plugin.d.ts +5 -0
- package/_vendor/plugin-builtin-export/pngExport.d.ts +15 -0
- package/{features/export → _vendor/plugin-builtin-export}/svgExport.d.ts +9 -2
- package/_vendor/plugin-builtin-import-host/CanvasImportHost.d.ts +3 -0
- package/_vendor/plugin-builtin-import-host/capability.d.ts +1 -0
- package/_vendor/plugin-builtin-import-host/index.d.ts +2 -0
- package/_vendor/plugin-builtin-import-host/plugin.d.ts +1 -0
- package/_vendor/plugin-builtin-tool-actions/capability.d.ts +1 -0
- package/_vendor/plugin-builtin-tool-actions/index.d.ts +2 -0
- package/_vendor/plugin-builtin-tool-actions/plugin.d.ts +1 -0
- package/_vendor/plugin-builtin-tool-actions/toolActions.d.ts +2 -0
- package/_vendor/plugin-connector/canvasRender.d.ts +2 -0
- package/_vendor/plugin-connector/connectorBindingUtil.d.ts +28 -0
- package/_vendor/plugin-connector/connectorBindings.d.ts +8 -0
- package/_vendor/plugin-connector/connectorGeometry.d.ts +70 -0
- package/_vendor/plugin-connector/connectorHandles.d.ts +12 -0
- package/_vendor/plugin-connector/connectorInteractions.d.ts +3 -0
- package/_vendor/plugin-connector/connectorMarker.d.ts +7 -0
- package/_vendor/plugin-connector/connectorModel.d.ts +43 -0
- package/_vendor/plugin-connector/connectorPortInteraction.d.ts +13 -0
- package/_vendor/plugin-connector/connectorPorts.d.ts +23 -0
- package/_vendor/plugin-connector/connectorRuntime.d.ts +62 -0
- package/_vendor/plugin-connector/connectorShapeUtil.d.ts +29 -0
- package/_vendor/plugin-connector/connectorTool.d.ts +4 -0
- package/_vendor/plugin-connector/constants.d.ts +17 -0
- package/_vendor/plugin-connector/editorRuntime.d.ts +7 -0
- package/_vendor/plugin-connector/feature.d.ts +4 -0
- package/_vendor/plugin-connector/index.d.ts +18 -0
- package/_vendor/plugin-connector/orthogonalRoute.d.ts +9 -0
- package/_vendor/plugin-connector/productRuntime.d.ts +2 -0
- package/_vendor/plugin-connector/quickConnect.d.ts +28 -0
- package/_vendor/plugin-connector/types.d.ts +51 -0
- package/_vendor/plugin-draw/DrawShapeRenderer.d.ts +5 -2
- package/_vendor/plugin-draw/canvasRender.d.ts +2 -2
- package/_vendor/plugin-draw/drawGeometry.d.ts +4 -7
- package/_vendor/plugin-draw/drawPath.d.ts +7 -1
- package/_vendor/plugin-draw/drawShapeUtil.d.ts +2 -2
- package/_vendor/plugin-draw/editorRuntime.d.ts +3 -3
- package/_vendor/plugin-draw/feature.d.ts +2 -3
- package/_vendor/plugin-draw/index.d.ts +4 -3
- package/_vendor/plugin-draw/productRuntime.d.ts +2 -0
- package/_vendor/plugin-eraser/canvasRender.d.ts +2 -2
- package/_vendor/plugin-eraser/editorRuntime.d.ts +2 -2
- package/_vendor/plugin-eraser/eraserRuntime.d.ts +12 -0
- package/_vendor/plugin-eraser/feature.d.ts +2 -3
- package/_vendor/plugin-eraser/index.d.ts +4 -2
- package/_vendor/plugin-eraser/productRuntime.d.ts +2 -0
- package/_vendor/plugin-frame/api.d.ts +19 -0
- package/_vendor/plugin-frame/canvasRender.d.ts +5 -5
- package/_vendor/plugin-frame/editorRuntime.d.ts +2 -2
- package/_vendor/plugin-frame/feature.d.ts +2 -3
- package/_vendor/plugin-frame/frameShapeUtil.d.ts +12 -2
- package/_vendor/plugin-frame/index.d.ts +5 -2
- package/_vendor/plugin-frame/productRuntime.d.ts +2 -0
- package/_vendor/plugin-geo/api.d.ts +27 -0
- package/_vendor/plugin-geo/canvasRender.d.ts +5 -5
- package/_vendor/plugin-geo/editorRuntime.d.ts +3 -3
- package/_vendor/plugin-geo/feature.d.ts +2 -3
- package/_vendor/plugin-geo/geoShapeUtil.d.ts +1 -1
- package/_vendor/plugin-geo/geoStrokeStyle.d.ts +2 -0
- package/_vendor/plugin-geo/geoTools.d.ts +1 -1
- package/_vendor/plugin-geo/index.d.ts +8 -5
- package/_vendor/plugin-geo/productRuntime.d.ts +2 -0
- package/_vendor/plugin-geo/types.d.ts +5 -1
- package/_vendor/plugin-group/canvasRender.d.ts +3 -4
- package/_vendor/plugin-group/editorRuntime.d.ts +2 -2
- package/_vendor/plugin-group/feature.d.ts +2 -3
- package/_vendor/plugin-group/groupContributions.d.ts +7 -0
- package/_vendor/plugin-group/groupShapeUtil.d.ts +24 -5
- package/_vendor/plugin-group/index.d.ts +4 -2
- package/_vendor/plugin-group/productRuntime.d.ts +2 -0
- package/_vendor/plugin-image/canvasRender.d.ts +2 -2
- package/_vendor/plugin-image/cropRuntime.d.ts +1 -1
- package/_vendor/plugin-image/cropSession.d.ts +5 -3
- package/_vendor/plugin-image/editorRuntime.d.ts +2 -4
- package/_vendor/plugin-image/feature.d.ts +2 -3
- package/_vendor/plugin-image/imageHostActionContract.d.ts +1 -1
- package/_vendor/plugin-image/imageShapeUtil.d.ts +3 -3
- package/_vendor/plugin-image/index.d.ts +5 -4
- package/_vendor/plugin-image/productRuntime.d.ts +4 -0
- package/_vendor/plugin-image/runtimeShared.d.ts +1 -1
- package/_vendor/plugin-image/smudge.d.ts +6 -2
- package/_vendor/plugin-image/smudgeRuntime.d.ts +1 -1
- package/_vendor/plugin-image/styleRuntime.d.ts +6 -1
- package/_vendor/plugin-image/toolbarRuntime.d.ts +1 -1
- package/_vendor/plugin-laser/canvasRender.d.ts +2 -2
- package/_vendor/plugin-laser/editorRuntime.d.ts +2 -2
- package/_vendor/plugin-laser/feature.d.ts +2 -3
- package/_vendor/plugin-laser/index.d.ts +4 -2
- package/_vendor/plugin-laser/laserRuntime.d.ts +18 -0
- package/_vendor/plugin-laser/productRuntime.d.ts +2 -0
- package/_vendor/plugin-packaging/api.d.ts +74 -0
- package/_vendor/plugin-packaging/canvasRender.d.ts +2 -0
- package/_vendor/plugin-packaging/editorRuntime.d.ts +2 -0
- package/_vendor/plugin-packaging/feature.d.ts +2 -0
- package/_vendor/plugin-packaging/index.d.ts +19 -0
- package/_vendor/plugin-packaging/packagingArtwork.d.ts +5 -0
- package/_vendor/plugin-packaging/packagingDxf.d.ts +9 -0
- package/_vendor/plugin-packaging/packagingGeometry.d.ts +74 -0
- package/_vendor/plugin-packaging/packagingInteractions.d.ts +2 -0
- package/_vendor/plugin-packaging/packagingPdfExporter.d.ts +25 -0
- package/_vendor/plugin-packaging/packagingRuntime.d.ts +11 -0
- package/_vendor/plugin-packaging/packagingShapeUtil.d.ts +34 -0
- package/_vendor/plugin-packaging/packagingStyle.d.ts +10 -0
- package/_vendor/plugin-packaging/packagingSvgExporter.d.ts +7 -0
- package/_vendor/plugin-packaging/productRuntime.d.ts +2 -0
- package/_vendor/plugin-packaging/types.d.ts +168 -0
- package/_vendor/plugin-packaging/validation.d.ts +3 -0
- package/_vendor/plugin-path/PathDraftOverlay.d.ts +1 -0
- package/_vendor/plugin-path/PathEditInsertPreviewOverlay.d.ts +1 -0
- package/_vendor/plugin-path/PathShapeRenderer.d.ts +15 -0
- package/_vendor/plugin-path/canvasRender.d.ts +2 -0
- package/_vendor/plugin-path/editorRuntime.d.ts +7 -0
- package/_vendor/plugin-path/feature.d.ts +2 -0
- package/_vendor/plugin-path/index.d.ts +8 -0
- package/_vendor/plugin-path/pathBoolean.d.ts +13 -0
- package/_vendor/plugin-path/pathDraft.d.ts +10 -0
- package/_vendor/plugin-path/pathEditPreview.d.ts +11 -0
- package/_vendor/plugin-path/pathEditSelection.d.ts +24 -0
- package/_vendor/plugin-path/pathEditSnap.d.ts +6 -0
- package/_vendor/plugin-path/pathGeometry.d.ts +74 -0
- package/_vendor/plugin-path/pathHandles.d.ts +18 -0
- package/_vendor/plugin-path/pathHistory.d.ts +13 -0
- package/_vendor/plugin-path/pathInteractions.d.ts +7 -0
- package/_vendor/plugin-path/pathShapeUtil.d.ts +30 -0
- package/_vendor/plugin-path/pathSvg.d.ts +3 -0
- package/_vendor/plugin-path/pathTool.d.ts +42 -0
- package/_vendor/plugin-path/productRuntime.d.ts +15 -0
- package/_vendor/plugin-path/types.d.ts +36 -0
- package/_vendor/plugin-text/api.d.ts +20 -0
- package/_vendor/plugin-text/canvasRender.d.ts +6 -3
- package/_vendor/plugin-text/capabilities.d.ts +2 -0
- package/_vendor/plugin-text/editorRuntime.d.ts +3 -3
- package/_vendor/plugin-text/feature.d.ts +4 -4
- package/_vendor/plugin-text/geoLabelBindingUtil.d.ts +6 -3
- package/_vendor/plugin-text/host/RichTextEditingBox.d.ts +4 -1
- package/_vendor/plugin-text/host/TiptapTextEditor.d.ts +6 -3
- package/_vendor/plugin-text/host/initialTextBackground.d.ts +2 -0
- package/_vendor/plugin-text/host/richTextRendering.d.ts +1 -2
- package/_vendor/plugin-text/host/textEditingBoxStyle.d.ts +1 -1
- package/_vendor/plugin-text/host/textEntryFocus.d.ts +2 -1
- package/_vendor/plugin-text/host/textFormattingApi.d.ts +16 -0
- package/_vendor/plugin-text/host/textMeasurement.d.ts +10 -2
- package/_vendor/plugin-text/host/textShapeRendererRuntime.d.ts +3 -1
- package/_vendor/plugin-text/host/tiptapTextEditorController.d.ts +4 -1
- package/_vendor/plugin-text/index.d.ts +11 -4
- package/_vendor/plugin-text/pathLabelBindingUtil.d.ts +55 -0
- package/_vendor/plugin-text/productRuntime.d.ts +6 -0
- package/_vendor/plugin-text/richTextUtils.d.ts +9 -2
- package/_vendor/plugin-text/shapeWideTextFormatting.d.ts +12 -0
- package/_vendor/plugin-text/textFonts.d.ts +6 -3
- package/_vendor/plugin-text/textFormatting.d.ts +47 -0
- package/_vendor/plugin-text/textFormattingSession.d.ts +6 -0
- package/_vendor/plugin-text/textLabelHelpers.d.ts +32 -6
- package/_vendor/plugin-text/textLinkPopoverPresentation.d.ts +18 -0
- package/_vendor/plugin-text/textShapeHelpers.d.ts +1 -0
- package/_vendor/plugin-text/textShapeUtil.d.ts +9 -5
- package/_vendor/plugin-text/textTypes.d.ts +1 -0
- package/_vendor/signals/core.d.ts +1 -0
- package/_vendor/signals/effect.d.ts +0 -4
- package/_vendor/signals/index.d.ts +2 -2
- package/_vendor/store/history.d.ts +1 -1
- package/_vendor/store/store.d.ts +6 -0
- package/browser/indexedDb.d.ts +10 -10
- package/browser/persistence.d.ts +6 -38
- package/chrome/floating/CanvasKitFloatingPortal.d.ts +6 -0
- package/chrome/floating/useCanvasKitFloatingPosition.d.ts +11 -0
- package/chrome/toolbar/CanvasKitFloatingToolbarLayer.d.ts +1 -1
- package/chrome/toolbar/FloatingSelectionToolbarPageSpace.d.ts +5 -3
- package/chrome/toolbar/toolbarLabels.d.ts +1 -1
- package/chrome/toolbar/useToolbarSurfaces.d.ts +11 -16
- package/chrome/types.d.ts +15 -17
- package/chrome/useCanvasKitChromeContext.d.ts +12 -15
- package/chrome/useChromeSurfaces.d.ts +12 -0
- package/chrome/useContextMenuSurface.d.ts +4 -4
- package/chrome/useHistoryControls.d.ts +3 -3
- package/chrome/usePageControls.d.ts +3 -3
- package/controller/canvasKitController.d.ts +5 -16
- package/core/index.d.ts +4 -6
- package/core/product-controller/canvasProductController.d.ts +42 -12
- package/core/product-controller/index.d.ts +1 -1
- package/core/runtime/productAssets.d.ts +4 -2
- package/core/runtime/productEditor.d.ts +1 -1
- package/core/runtime/productServices.d.ts +11 -21
- package/core/runtime/runtimeContracts.d.ts +17 -0
- package/es-DocrZgUh.mjs +2 -0
- package/features/context-menu/contextMenuRuntime.d.ts +4 -4
- package/features/image/asset/imageAssetService.d.ts +2 -3
- package/features/image/asset/imageBlobStore.d.ts +7 -2
- package/features/image/asset/imageFileHelpers.d.ts +0 -6
- package/features/image/asset/svgImageAssetInliner.d.ts +1 -1
- package/features/image/controller/imageProductController.d.ts +2 -2
- package/features/image/imageHostPlugin.d.ts +1 -0
- package/features/image/import/ImageImportController.d.ts +3 -1
- package/features/image/index.d.ts +1 -3
- package/features/image/smudge/imageSmudgeHostActions.d.ts +2 -2
- package/features/image/toolbar/imageHostActions.d.ts +17 -7
- package/features/image/toolbar/imageToolbarHostBridge.d.ts +1 -1
- package/features/text/link/TextLinkHoverPopover.d.ts +6 -0
- package/features/text/textHostPlugin.d.ts +5 -0
- package/features/text/textSvgAssetInliner.d.ts +3 -0
- package/features/text/textSvgAssetPlugin.d.ts +2 -0
- package/index.css +1 -1
- package/index.d.ts +36 -12
- package/index.mjs +111 -96
- package/package.json +12 -9
- package/plugins/standardCanvasKitPlugins.d.ts +16 -0
- package/react/CanvasKitRoot.d.ts +10 -5
- package/react/useCanvasKitControllerLifecycle.d.ts +8 -0
- package/react/useCanvasKitRuntime.d.ts +2 -4
- package/runtime/canvasKitCommandExecutor.d.ts +13 -0
- package/runtime/canvasKitPluginContracts.d.ts +34 -0
- package/runtime/canvasKitPluginSetup.d.ts +32 -0
- package/runtime/canvasKitResourceScope.d.ts +5 -0
- package/runtime/canvasKitRuntime.d.ts +48 -19
- package/runtime/canvasKitRuntimeContracts.d.ts +34 -0
- package/runtime/persistenceCoordinator.d.ts +33 -0
- package/_vendor/canvas-core/editor/createEditorWithRuntimePlugins.d.ts +0 -6
- package/_vendor/canvas-core/editor/middleMousePanInteraction.d.ts +0 -2
- package/_vendor/canvas-core/schema/snapshotSupport.d.ts +0 -43
- package/_vendor/canvas-core/tools/select/states/draggingSelectionHandleInteractionState.d.ts +0 -15
- package/_vendor/canvas-react/host/actionRegistry.d.ts +0 -15
- package/_vendor/canvas-react/host/canvasRenderPluginHost.d.ts +0 -2
- package/_vendor/canvas-react/host/canvasRenderPluginHostManifest.d.ts +0 -2
- package/_vendor/canvas-react/host/canvasRenderPluginHostRuntime.d.ts +0 -3
- package/_vendor/canvas-react/host/canvasRenderPluginHostTypes.d.ts +0 -104
- package/_vendor/canvas-react/host/canvasRenderPluginHostValidation.d.ts +0 -11
- package/_vendor/canvas-react/host/contextMenuRegistry.d.ts +0 -17
- package/_vendor/canvas-react/host/extension.d.ts +0 -37
- package/_vendor/canvas-react/host/toolbarRegistry.d.ts +0 -20
- package/_vendor/plugin-text/arrowLabelBindingUtil.d.ts +0 -42
- package/_vendor/plugin-text/host/RichTextLinkPopover.d.ts +0 -14
- package/_vendor/plugin-text/host/RichTextToolbar.d.ts +0 -8
- package/_vendor/plugin-text/host/richTextBubbleMenuPositionSync.d.ts +0 -7
- package/browser/localSnapshotRestore.d.ts +0 -13
- package/builtins/controller/createBuiltInCanvasController.d.ts +0 -16
- package/builtins/controller/layerController.d.ts +0 -9
- package/builtins/controller/shapeCreationController.d.ts +0 -83
- package/builtins/extensions.d.ts +0 -18
- package/builtins/index.d.ts +0 -5
- package/chrome/useSvgExport.d.ts +0 -15
- package/core/api/apiRegistry.d.ts +0 -12
- package/core/runtime/productDefinition.d.ts +0 -33
- package/core/runtime/productHost.d.ts +0 -20
- package/features/actions/actionRuntime.d.ts +0 -21
- package/features/clipboard/clipboardHostExtension.d.ts +0 -2
- package/features/image/imageHostExtension.d.ts +0 -10
- package/features/image/import/useImageImport.d.ts +0 -16
- package/features/keyboard/keyboardShortcutHostExtension.d.ts +0 -2
- package/features/keyboard/useCanvasKitKeyboardShortcuts.d.ts +0 -6
- package/features/persistence/CanvasKitPersistenceNotice.d.ts +0 -4
- package/features/persistence/persistenceHostExtension.d.ts +0 -2
- package/features/selection/selectionActions.d.ts +0 -20
- package/features/selection/selectionContextMenuContributions.d.ts +0 -2
- package/features/selection/selectionHostExtension.d.ts +0 -2
- package/features/selection/selectionToolbarContributions.d.ts +0 -2
- package/features/tool/toolActions.d.ts +0 -2
- package/features/tool/toolContextMenuContributions.d.ts +0 -2
- package/features/tool/toolHostExtension.d.ts +0 -2
- package/features/tool/toolToolbarContributions.d.ts +0 -2
- package/features/view/viewActions.d.ts +0 -5
- package/features/view/viewContextMenuContributions.d.ts +0 -2
- package/features/view/viewHostExtension.d.ts +0 -2
- package/host/defaultHostExtensions.d.ts +0 -2
- package/product/canvasKitProduct.d.ts +0 -51
- package/react/useCanvasKitController.d.ts +0 -5
- package/react/useCanvasKitStartup.d.ts +0 -9
- package/runtime/canvasKitHostContracts.d.ts +0 -135
- package/runtime/canvasKitHostFeatureHooks.d.ts +0 -12
- package/runtime/canvasKitRuntimePlan.d.ts +0 -50
package/index.mjs
CHANGED
|
@@ -1,96 +1,111 @@
|
|
|
1
|
-
function e(){return fm}function t(){return++fm}function n(e){Sm={child:e,parentSet:new Set,below:Sm}}function i(){if(!Sm)throw new Error("Cannot stop dependency capture because no capture is active");const e=Sm;return Sm=e.below,e.parentSet}function o(e){Sm&&(Sm.parentSet.add(e),e.children.add(Sm.child))}function r(e){function t(e){for(const o of e)if(!i.has(o))if(i.add(o),"effect"===o.type)n.add(o);else if("computed"===o.type){const e=o.source;e&&t(e.children)}}const n=new Set,i=new Set;for(const o of e)t(o.children);for(const o of n)o.notify()}function s(e,t,n){return new ym(e,t,n?.isEqual)}function a(e,t,n){return new xm(e,t,n?.isEqual)}function d(e={}){return{id:Cm,typeName:"document",scope:"document",meta:{...e}}}function l(){return{id:Tm,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function c(e=Tm){return{id:Em,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...Bm}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function u(e){return!!e&&"page"===e.typeName}function h(e){return!!e&&"document"===e.typeName}function p(e){return!!e&&"shape"===e.typeName}function g(e){return!!e&&"session"===e.typeName}function f(e){return!!e&&"binding"===e.typeName}function m(e){return!!e&&"asset"===e.typeName}function S(e){return"document"===e.scope}function y(e){return{kind:"theme",slot:e}}function b(e){return{kind:"custom",value:e}}function x(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&Rm.includes(e.slot)}function I(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function v(e){return"string"==typeof e||x(e)||I(e)}function w(e){return Am[e]}function P(e,t){if(x(e))return e;if(I(e))return e;if("string"!=typeof e)return t;const n=e.trim().toLowerCase();if("transparent"===n)return"transparent";const i=Fm[n];return i?y(i):e}function k(e){return"string"==typeof e?e:"custom"===e.kind?e.value:`var(${w(e.slot)}, ${Lm[e.slot]})`}function C(e,t){if("string"==typeof e)return e;if("custom"===e.kind)return e.value;const n=w(e.slot),i=Lm[e.slot];return t?.(n,i)??i}function T(e){return"string"==typeof e?"transparent"===e.trim().toLowerCase():"custom"===e.kind&&"transparent"===e.value.trim().toLowerCase()}function E(e,t){return e===t||!(!e||!t)&&("string"==typeof e||"string"==typeof t?e===t:e.kind===t.kind&&("theme"===e.kind?e.slot===t.slot:e.value===t.value))}function B(e,t,n){let i=e.computeShapeExportPageBounds(t);if(!U(i))return i;for(const o of((e,t,n)=>{const i=[];for(const o of R(e,t,n)){const t=L(e,o);t&&U(t)&&i.push(t)}return i})(e,t,n)){const e=F(i,o);if(!e)return null;i=e}return i}function M(e,t,n,i,o){const r=[];for(const s of R(e,t,n)){const t=A(e,s,i,o);t&&r.push(t)}return r}function R(e,t,n){const i=[],o=new Set;let r=t.parentId;for(;r.startsWith("shape:");){const t=r;if(o.has(t))break;o.add(t);const s=e.getShape(t);if(!s)break;n.has(s.id)&&i.push(s),r=s.parentId}return i.reverse()}function A(e,t,n,i){if(n.has(t.id))return n.get(t.id)??null;const o=e.getShapeUtil(t).getChildExportClipLocalBounds(t);if(!o||!U(o))return n.set(t.id,null),null;const r=i.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:o.x,y:o.y,width:o.w,height:o.h,transform:e.computeShapeExportToPageTransform(t).toSvgString()}}]});return n.set(t.id,r),r}function L(e,t){const n=e.getShapeUtil(t).getChildExportClipLocalBounds(t);if(!n||!U(n))return null;const i=e.computeShapeExportToPageTransform(t);return Pm.FromPoints([new wm(n.minX,n.minY),new wm(n.maxX,n.minY),new wm(n.maxX,n.maxY),new wm(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))}function F(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return o<n||r<i?null:new Pm(n,i,o-n,r-i)}function $(e){if("string"==typeof e)return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">");const t=(e=>{const t=[];for(const[n,i]of Object.entries(e))null!=i&&!1!==i&&t.push(`${n}="${D("number"==typeof i?z(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map($).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function U(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function D(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function z(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function _(e){return e[Um]}function H({editor:e,exporters:t,shapeIds:n}){const i=Array.from(n),o=e.getShapeExportTraversalIds(i),r=[];for(const c of o){const n=e.getShape(c);n?(N(e.computeShapeExportPageBounds(n))||r.push({kind:"missing-bounds",id:n.id,canRepair:!1}),t.get(n.type)||r.push({kind:"missing-exporter",id:n.id,canRepair:!1})):r.push({kind:"missing-shape",id:c,canRepair:!1})}const s=new Set(o),a=new Set;for(const c of _(e).getAll().filter(f)){if(!s.has(c.fromId)&&!s.has(c.toId))continue;const t=e.getShape(c.fromId),n=e.getShape(c.toId);t&&n?e.bindings.canBind(c)?(e.bindings.getConflictingBindings(c).some(e=>a.has(e.id))&&r.push({kind:"duplicate-exclusive-binding",id:c.id,canRepair:!0}),a.add(c.id)):r.push({kind:"invalid-binding",id:c.id,canRepair:!0}):r.push({kind:"missing-binding-endpoint",id:c.id,canRepair:!0})}const d=r.filter(e=>e.canRepair).length,l=r.length-d;return{requestedShapeIds:i,issues:r,repairableIssueCount:d,fatalIssueCount:l,canExport:0===l}}function N(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function O(e){return e.added.length>0||e.updated.length>0||e.removed.length>0}function W(e){return e instanceof Map?new Map(e):new Map(Array.from(e,e=>[e.id,e]))}function Y(e,t){const n=W(e),i=W(t),o={added:[],updated:[],removed:[]};for(const[r,s]of n){const e=i.get(r);e?e!==s&&o.updated.push({before:s,after:e}):o.removed.push(s)}for(const[r,s]of i)n.has(r)||o.added.push(s);return o}function X(e){return{added:[...e.removed],updated:e.updated.map(e=>({before:e.after,after:e.before})),removed:[...e.added]}}function K(e,t){const n=new Map,i=new Map,o=new Map;for(const s of e.added)n.set(s.id,s);for(const s of e.updated)i.set(s.after.id,s);for(const s of e.removed)o.set(s.id,s);for(const s of t.added){const e=o.get(s.id);if(e){o.delete(s.id),i.set(s.id,{before:e,after:s});continue}const t=i.get(s.id);t?i.set(s.id,{before:t.before,after:s}):n.set(s.id,s)}for(const s of t.updated){if(n.get(s.after.id)){n.set(s.after.id,s.after);continue}const e=o.get(s.after.id);if(e){o.delete(s.after.id),i.set(s.after.id,{before:e,after:s.after});continue}const t=i.get(s.after.id);i.set(s.after.id,t?{before:t.before,after:s.after}:{before:s.before,after:s.after})}for(const s of t.removed){if(n.get(s.id)){n.delete(s.id);continue}const e=i.get(s.id);e?(i.delete(s.id),o.set(s.id,e.before)):o.set(s.id,s)}const r={added:[],updated:[],removed:[]};for(const s of n.values())r.added.push(s);for(const s of i.values())s.before!==s.after&&r.updated.push(s);for(const s of o.values())r.removed.push(s);return r}function V(e,t){return{id:e.id,forward:K(e.forward,t),parentIds:e.parentIds}}function q(e,t){return{forward:t,inverse:X(t),label:e}}function j(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function G(e,t,n){const i=e.getShape(t);if(!i)return;const o=e.getContainingParentIdForShapeRecord(i);o&&o!==i.parentId&&e.commands.reparentShapes({ids:[t],parentId:o},n)}function Z(e,t,n){const i=n?.source??"user";_(e).atomic(()=>{const n=[],o=[];for(const i of t){const t=e.getShape(i.id);if(!t)continue;const r=i.x??t.x,s=i.y??t.y,a=i.rotation??t.rotation,d=i.scaleX??t.scaleX,l=i.scaleY??t.scaleY,c=void 0===i.opacity?t.opacity:Q(i.opacity,t.opacity),u=i.isHidden??t.isHidden,h=i.isLocked??t.isLocked,p=i.parentId??t.parentId,g=i.index??t.index,f=void 0===i.meta?t.meta:{...i.meta};if(!e.canUseShapeParent(p,t.id))throw new Error(`Invalid parent id for shape ${t.id}`);if(!i.props&&void 0===i.meta&&r===t.x&&s===t.y&&a===t.rotation&&d===t.scaleX&&l===t.scaleY&&c===t.opacity&&u===t.isHidden&&h===t.isLocked&&p===t.parentId&&g===t.index)continue;const m=e.shapeUtils.get(t.type),S={...t,x:r,y:s,rotation:a,scaleX:d,scaleY:l,opacity:c,isHidden:u,isLocked:h,parentId:p,index:g,props:i.props?m.validateProps({...t.props,...i.props}):t.props,meta:f};n.push(S),o.push({before:t,after:S})}0!==n.length&&(_(e).put(n,i),e.bindings.handleShapeChanges(o,i),((e,t,n)=>{const i=new Set(t.map(e=>e.after.id)),o=new Set;for(const r of t)ee(e,r.before,o),ee(e,r.after,o);J(e,o,n,i)})(e,o,i))},i)}function Q(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function J(e,t,n,i=new Set){const o=[],r=[];for(const s of t){if(i.has(s))continue;const t=e.getShape(s);if(!t||0!==t.rotation||1!==t.scaleX||1!==t.scaleY)continue;const n=e.getDescendantPageBounds(t.id);if(!n)continue;const a=t.props;if("number"!=typeof a.w||"number"!=typeof a.h)continue;if(t.x===n.x&&t.y===n.y&&a.w===n.w&&a.h===n.h)continue;const d=e.shapeUtils.get(t.type),l={...t,x:n.x,y:n.y,props:d.validateProps({...a,w:n.w,h:n.h})};o.push(l),r.push({before:t,after:l})}0!==o.length&&(_(e).put(o,n),e.bindings.handleShapeChanges(r,n))}function ee(e,t,n){const i=new Set([t.id]);let o=t.parentId;for(;o.startsWith("shape:");){const t=e.getShape(o);if(!t||i.has(t.id))return;i.add(t.id),e.getShapeUtil(t).isTransformDescendantContainer(t)&&n.add(t.id),o=t.parentId}}function te(e,t,n){const i=n?.source??"user",o=e.getShapeIdsIncludingDescendants(t),r=((e,t)=>{const n=new Set;for(const i of t){const t=e.getShape(i);t&&ee(e,t,n)}return n})(e,o),s=new Set(o),a=e.getUnreferencedAssetIdsAfterShapeDelete(o);_(e).atomic(()=>{e.sideEffects.runBeforeDelete("shape",o,i),_(e).remove(o,i),a.length>0&&_(e).remove(a,i);const t=((e,t,n,i)=>{const o=[],r=[...t].sort((t,n)=>e.getDescendantShapeIds(n).length-e.getDescendantShapeIds(t).length);for(let s=0;s<r.length;s+=1){const t=r[s];if(!t||n.has(t))continue;const a=e.getShape(t),d=a?e.getChildShapeIds(a.id).filter(t=>!n.has(t)&&!!e.getShape(t)):[];if(!a||!e.getShapeUtil(a).isTransformDescendantContainer(a)||d.length>0)continue;const l=new Set;ee(e,a,l);for(const e of l)r.push(e);e.sideEffects.runBeforeDelete("shape",[a.id],i),_(e).remove([a.id],i),n.add(a.id),o.push(a.id)}return o})(e,r,s,i);J(e,r,i,s),e.sideEffects.runAfterDelete("shape",[...o,...t],i)},i)}function ne(e,t){return e.bindings.canBind(t)}function ie(e){return Math.min(8,Math.max(.1,e))}function oe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function re(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function se(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||i.x!==o.x||i.y!==o.y)return!1}return!0}function ae(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y&&e.w===t.w&&e.h===t.h:e===t)}function de(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function le(e,t){return e.culledCount===t.culledCount&&e.visibleCount===t.visibleCount&&e.retainedCount===t.retainedCount&&e.retainedBaseCount===t.retainedBaseCount&&e.culledRangeCount===t.culledRangeCount&&e.culledRangeSpan===t.culledRangeSpan&&e.culledRangesSummary===t.culledRangesSummary&&e.retainedBaseRangeCount===t.retainedBaseRangeCount&&e.retainedBaseRangeSpan===t.retainedBaseRangeSpan&&e.retainedBaseRangesSummary===t.retainedBaseRangesSummary&&e.retainedRangeCount===t.retainedRangeCount&&e.retainedRangeSpan===t.retainedRangeSpan&&e.retainedRangesSummary===t.retainedRangesSummary&&e.retainedChangeCount===t.retainedChangeCount&&e.retainedAddedCount===t.retainedAddedCount&&e.retainedRemovedCount===t.retainedRemovedCount&&e.selectedOutsideCulledCount===t.selectedOutsideCulledCount}function ce(e,t){return e.selectionFrameActive===t.selectionFrameActive&&e.selectionHandlesActive===t.selectionHandlesActive&&e.bindingPreviewActive===t.bindingPreviewActive&&e.brushBoxActive===t.brushBoxActive&&e.selectionFrameChangeCount===t.selectionFrameChangeCount&&e.selectionHandlesChangeCount===t.selectionHandlesChangeCount&&e.resizeHandleCount===t.resizeHandleCount&&e.rotateHandleCount===t.rotateHandleCount&&e.terminalHandleCount===t.terminalHandleCount&&e.middleHandleCount===t.middleHandleCount&&e.customHandleCount===t.customHandleCount&&e.boundsSummary===t.boundsSummary&&e.rotation===t.rotation&&e.strokeWidth===t.strokeWidth}function ue(e,t,n){const i=new Set([e.id]);let o=e.parentId;for(;o.startsWith("shape:");){const e=o;if(i.has(e))return null;i.add(e);const n=t.get(e);if(!n)return null;o=n.parentId}return n.has(o)?o:null}function he(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o)return!1;if(i.id!==o.id||i.shape!==o.shape||i.isSelected!==o.isSelected||!ae(i.bounds,o.bounds))return!1}return!0}function pe(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ge(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function fe(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)&&e.every((e,n)=>fe(e,t[n]));const n=e,i=t,o=Object.keys(n),r=Object.keys(i);return o.length===r.length&&o.every(e=>Object.prototype.hasOwnProperty.call(i,e)&&fe(n[e],i[e]))}function me(e){const t=(e=>{const t=new Set(e.getSelectedShapeIds());return 0===t.size?[]:e.getCurrentPageShapeIds().filter(e=>t.has(e)).filter(n=>!((e,t,n)=>{const i=new Set([t]);let o=e.getShape(t);for(;o?.parentId.startsWith("shape:");){const t=o.parentId;if(n.has(t))return!0;if(i.has(t))return!1;i.add(t),o=e.getShape(t)}return!1})(e,n,t))})(e);if(0===t.length)return null;const n=((e,t)=>{const n=e.getShapeExportTraversalIds(t),i=new Set(n);return e.getCurrentPageShapeIds().filter(e=>i.has(e))})(e,t),i=new Set(n),o=n.map(t=>e.getShape(t)).filter(e=>!!e).map(Ce);return 0===o.length?null:{type:"land/clipboard",version:1,source:{app:"land"},rootShapeIds:t,records:{shapes:o,bindings:ye(e,o,i),assets:be(e,o)},bounds:xe(e,n)}}function Se(e,t){const{payload:n}=t;if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"land/clipboard"===t.type&&1===t.version&&!!t.records&&Array.isArray(t.rootShapeIds)&&Array.isArray(t.records.shapes)&&Array.isArray(t.records.bindings)&&Array.isArray(t.records.assets)})(n)||0===n.records.shapes.length)return[];const i=t.source??"user",o=e.getCurrentPageId(),r=(e=>{const t=e.payload.bounds;return e.pagePoint?e.pagePoint.sub(new wm(t.x+t.w/2,t.y+t.h/2)):e.offset??Om})(t),s=new Map,a=new Map,d=[];_(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=e.createAssetRecord({type:t.type,props:ke(t.props),meta:ke(t.meta)});return s.set(t.id,n.id),n});t.length>0&&e.commands.createAssetsFromRecords(t,{source:i});const d=n.records.shapes.map(t=>{const n=((e,t)=>Pe(e,t))(t.props,s),i=e.createShapeRecord({type:t.type,x:t.x+r.x,y:t.y+r.y,props:n,parentId:o,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,meta:ke(t.meta)});return a.set(t.id,i.id),{original:t,draft:i}}).map(({original:e,draft:t})=>({...t,parentId:Ie(e.parentId,a,o)}));d.length>0&&e.commands.createShapesFromRecords(d,{source:i});for(const o of n.records.bindings){const t=a.get(o.fromId),n=a.get(o.toId);t&&n&&e.commands.createBinding({type:o.type,fromId:t,toId:n,props:ke(o.props),meta:ke(o.meta)},{source:i})}},i);for(const l of n.rootShapeIds){const e=a.get(l);e&&d.push(e)}return d.length>0&&e.commands.setSelectedShapeIds(d,{source:i}),d}function ye(e,t,n){const i=[],o=new Set;for(const r of t)for(const t of e.getBindingsForShape(r.id))o.has(t.id)||n.has(t.fromId)&&n.has(t.toId)&&(o.add(t.id),i.push(Ce(t)));return i}function be(e,t){const n=[],i=new Set;for(const o of t)for(const t of ve(o)){if(i.has(t))continue;const o=e.getAsset(t);o&&(i.add(t),n.push(Ce(o)))}return n}function xe(e,t){const n=(e=>{if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,o=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),i=Math.max(i,r.maxX),o=Math.max(o,r.maxY);return new Pm(t,n,i-t,o-n)})(t.map(t=>e.getShapePageBounds(t)).filter(e=>!!e))??new Pm(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function Ie(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function ve(e){const t=[],n=new Set,i=ge(e);return i&&(n.add(i),t.push(i)),we(e.props,n,t),t}function we(e,t,n){if(Te(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)we(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))we(i,t,n)}function Pe(e,t){if(Te(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>Pe(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[i,o]of Object.entries(e))n[i]=Pe(o,t);return n}function ke(e){return Ce(e)}function Ce(e){if(Array.isArray(e))return e.map(Ce);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=Ce(i);return t}function Te(e){return"string"==typeof e&&e.startsWith("asset:")}function Ee(e,t,n,i,o="document"){if(t>n)throw new Ym(`Unsupported ${o} snapshot schema version: ${t} is newer than ${n}`);let r=e;for(let s=t;s<n;s+=1){const e=i.find(e=>e.fromVersion===s);if(!e)throw new Ym(`No ${o} snapshot migration from schema version ${s}`);r=e.up(r)}return r}function Be(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Me(e,t){return"string"==typeof e?e:t}function Re(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ae(e,t){return"boolean"==typeof e?e:t}function Le(e){return Be(e)?e:{}}function Fe(e){return Be(e)?{x:Re(e.x,Bm.x),y:Re(e.y,Bm.y),z:Math.min(8,Math.max(.1,Re(e.z,Bm.z)))}:null}function $e(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function Ue(e,t){if(!Be(e))throw new Ym(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=Re(n,NaN);if(!Number.isFinite(i)||i<1)throw new Ym(`Unsupported ${t} snapshot schema version: ${String(n)}`);if(!Array.isArray(e.records))throw new Ym(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:1,records:Ee(e.records,i,1,"document"===t?Xm:Km,t)}}function De(e,t){const n=e.find(h)??d(),i=e.filter(e=>"page"===e.typeName),o=e.filter(e=>"shape"===e.typeName),r=e.filter(f),s=e.filter(m),a=(i.length>0?[...i].sort((e,t)=>e.index.localeCompare(t.index)):[l()]).map((e,t)=>({...e,index:String(t+1).padStart(4,"0")})),c=a[0]?.id??"page:default",u=new Set(a.map(e=>e.id)),p=[...o].sort((e,t)=>e.index.localeCompare(t.index)),g=new Map(p.map(e=>[e.id,e])),S=p.map((e,n)=>{const i=(({pageIds:e,parentId:t,shapeById:n,shapeId:i,shapeUtils:o})=>{if(t.startsWith("page:"))return e.has(t);if(t===i)return!1;const r=n.get(t);if(!r)return!1;if(!o.get(r.type).canReceiveChildren(r))return!1;const s=new Set([i]);let a=r.parentId;for(;a.startsWith("shape:");){const e=a;if(s.has(e))return!1;s.add(e);const t=n.get(e);if(!t)return!1;if(!o.get(t.type).canReceiveChildren(t))return!1;a=t.parentId}return e.has(a)})({pageIds:u,parentId:e.parentId,shapeById:g,shapeId:e.id,shapeUtils:t})?e.parentId:c,o={...e,parentId:i,index:e.index||String(n+1).padStart(6,"0")};return t.get(o.type).repairLoadedShape(o)??o}),y=new Set(S.map(e=>e.id)),b=r.filter(e=>y.has(e.fromId)&&y.has(e.toId));return[n,...a,...s,...S,...b]}function ze(e,t,n){const i=Ue(e,"document"),o=new Set,r=[];return i.records.forEach((e,i)=>{if(!Be(e))throw new Ym("Invalid document record: expected object");if("string"!=typeof e.id)throw new Ym("Invalid document record id");if(o.has(e.id))throw new Ym(`Duplicate document record id: ${e.id}`);if(o.add(e.id),"document"!==e.typeName)if("page"!==e.typeName)if("shape"!==e.typeName)if("binding"!==e.typeName){if("asset"!==e.typeName)throw new Ym(`Unsupported document record type: ${String(e.typeName)}`);r.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new Ym("Invalid asset record id");if("string"!=typeof e.type)throw new Ym("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:Be(e.props)?e.props:{},meta:Le(e.meta)}})(e))}else r.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new Ym("Invalid binding record id");if("string"!=typeof e.type)throw new Ym("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new Ym(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new Ym(`Invalid to id for binding ${e.id}`);const n=e.type,i=t.get(n);return{id:e.id,typeName:"binding",scope:"document",type:n,fromId:e.fromId,toId:e.toId,props:i.validateProps(e.props),meta:Le(e.meta)}})(e,n));else r.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new Ym("Invalid shape record id");if("string"!=typeof e.type)throw new Ym("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new Ym(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:Me(e.index,String(n+1).padStart(6,"0")),x:Re(e.x,0),y:Re(e.y,0),rotation:Re(e.rotation,0),scaleX:Re(e.scaleX,1),scaleY:Re(e.scaleY,1),opacity:Math.min(1,Math.max(0,Re(e.opacity,1))),isHidden:Ae(e.isHidden,!1),isLocked:Ae(e.isLocked,!1),meta:Le(e.meta),type:e.type,props:t.get(e.type).validateProps(e.props)}})(e,t,i));else r.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("page:"))throw new Ym("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:Me(e.name,`Page ${t+1}`),index:Me(e.index,String(t+1).padStart(4,"0")),meta:Le(e.meta)}})(e,i));else r.push((e=>{if("document:main"!==e.id)throw new Ym("Invalid document metadata record id");return{id:Cm,typeName:"document",scope:"document",meta:Le(e.meta)}})(e))}),{schemaVersion:1,records:De(r,t)}}function _e(e){const t=Ue(e,"session").records[0];if(!Be(t))return{schemaVersion:1,records:[c()]};const n=c(),i="string"==typeof t.currentPageId&&t.currentPageId.startsWith("page:")?t.currentPageId:n.currentPageId,o=(e=>{if(!Be(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Fe(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),r=(e=>{if(!Be(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,$e(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:Me(t.activeToolId,n.activeToolId),isToolLocked:"boolean"==typeof t.isToolLocked?t.isToolLocked:n.isToolLocked,editingShapeId:null,shapeEditingSession:null,pageCameraById:Object.keys(o).length>0?o:n.pageCameraById,pageSelectedShapeIdsById:Object.keys(r).length>0?r:n.pageSelectedShapeIdsById,meta:Le(t.meta)}]}}function He(){return wm.Zero()}function Ne(e,t,n){if(n<=0)return He();const i=t.x-e.x,o=t.y-e.y;return 0===i&&0===o?He():new wm(i/n,o/n)}function Oe(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function We(e){return{...e,anchorPagePoint:e.anchorPagePoint.clone(),boundaryPagePoint:e.boundaryPagePoint.clone()}}function Ye(e,t){return e.terminal===t.terminal&&re(e.anchorPagePoint,t.anchorPagePoint)&&re(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function Xe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!Ye(i,o))return!1}return!0}function Ke(e,t){return Ye(e,t)&&e.ownerShapeId===t.ownerShapeId&&(e.targetShapeId??null)===(t.targetShapeId??null)}function Ve(e,t){return t.getExportBounds(e)}function qe(e,t){return t.getLocalToPageTransform(e)}function je(e,t){const n=Ze(e,t);return km.Translate(n.x,n.y).compose(km.Rotate(e.rotation)).compose(km.Scale(e.scaleX,e.scaleY)).compose(km.Translate(-n.x,-n.y))}function Ge(e,t){return qe(e,t)}function Ze(e,t){return t.getBounds(e).center}function Qe(e,t,n){return je(e,n).applyToPoint(t)}function Je(e,t,n){if(0===e.scaleX||0===e.scaleY){const i=Ze(e,n),o=t.sub(i).rot(-e.rotation);return i.add(new wm(0===e.scaleX?0:o.x/e.scaleX,0===e.scaleY?0:o.y/e.scaleY))}return je(e,n).invert().applyToPoint(t)}function et(e,t){return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(n=>Qe(e,n,t))}function tt(e,t){const n=et(e,t),i=((e,t)=>{const n=t.getBounds(e);return[new wm(n.minX,n.minY),new wm(n.maxX,n.minY),new wm(n.maxX,n.maxY),new wm(n.minX,n.maxY)].map(n=>Qe(e,n,t))})(e,t);return{bounds:Pm.FromPoints(n),center:Ze(e,t),corners:i,outlineVertices:n}}function nt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function it(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function ot(e,t,n){const i=e.get(t);if(!i)return!1;const o=i.indexOf(n);if(o<0)return!1;if(1===i.length)return e.delete(t),!0;const r=i.slice();return r.splice(o,1),e.set(t,r),!0}function rt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function st(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function at(e,t,n){return"to"===e?t.toId===n.toId?t.fromId===n.fromId?t.id.localeCompare(n.id):t.fromId.localeCompare(n.fromId):t.toId.localeCompare(n.toId):st(t,n)}function dt(e,t,n,i,o){const r=e.get(t);if(!r)return e.set(t,[n.id]),!0;if(r.includes(n.id))return!1;const s=r.slice();return s.splice(((e,t,n,i)=>{for(let o=0;o<e.length;o+=1){const r=i(e[o]);if(r&&at(n,t,r)<0)return o}return e.length})(r,n,i,o),0,n.id),e.set(t,s),!0}function lt(e,t,n,i){const o=e.get(t);if(!o)return void e.set(t,[n.id]);if(o.includes(n.id))return;let r=o.length;for(let a=0;a<o.length;a+=1){const e=i(o[a]);if(void 0!==e&&e.localeCompare(n.index)>0){r=a;break}}const s=o.slice();s.splice(r,0,n.id),e.set(t,s)}function ct(e,t,n){ot(e,t,n)}function ut(e){return p(e.before)&&p(e.after)}function ht(e){return f(e.before)&&f(e.after)}function pt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!re(i,o))return!1}return!0}function gt(e,t){return pt(e.outlineVertices,t.outlineVertices)&&ae(e.pageBounds,t.pageBounds)&&ae(e.frameBounds,t.frameBounds)&&e.rotation===t.rotation&&re(e.rotationCenter,t.rotationCenter)&&re(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function ft(e){let t=(e=>{let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t})(e);for(;t<=-Math.PI/2;)t+=Math.PI;for(;t>Math.PI/2;)t-=Math.PI;return Math.abs(t)<Gm?0:t}function mt(e,t){const n=e.selectedShapeIdsSignal.get();if(0===n.length)return{outlineVertices:[],pageBounds:null,frameBounds:null,rotation:0,rotationCenter:null,selectionAnchorPagePoint:null,hasRotation:!1,hasCompatibleRotation:!0};const i=[],o=[],r=[];let s=1/0,a=1/0,d=-1/0,l=-1/0;for(const S of n){const n=e.getShapeSignal(S).get();if(!n)continue;const c=e.getShapeUtil(n),u=c.getSelectionPagePoints(n);if(u&&o.push(...u),!c.contributesToSelectionFrame(n,{editor:e}))continue;r.push(n);const h=t(S);h&&(i.push(...h.outlineVertices),s=Math.min(s,h.bounds.minX),a=Math.min(a,h.bounds.minY),d=Math.max(d,h.bounds.maxX),l=Math.max(l,h.bounds.maxY))}const c=Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(d)&&Number.isFinite(l)?new Pm(s,a,d-s,l-a):null,u=!(r.length>0)||function(e){if(0===e.length)return!0;const t=ft(e[0]?.rotation??0);return e.every(e=>{return n=t,Math.abs(ft(e.rotation)-ft(n))<Gm;var n})}(r),h=((e,t)=>0!==e.length&&t?ft(e[0]?.rotation??0):0)(r,u),p=r.some(e=>Math.abs(ft(e.rotation))>Gm),g=c?.center??null,f=0===i.length?null:Math.abs(h)<Gm||!g?Pm.FromPoints(i):Pm.FromPoints(i.map(e=>wm.RotWith(e,g,-h))),m=o.length>0?Pm.FromPoints(o):null;return{outlineVertices:i,pageBounds:c,frameBounds:f,rotation:h,rotationCenter:g,selectionAnchorPagePoint:f&&g?Math.abs(h)<Gm?new wm(f.center.x,f.minY):wm.RotWith(new wm(f.center.x,f.minY),g,h):m?new wm(m.center.x,m.minY):null,hasRotation:p,hasCompatibleRotation:u}}function St(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y&&e.w===t.w&&e.h===t.h:e===t)}function yt(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function bt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!yt(i,o))return!1}return!0}function xt(e,t){return e===t||(e&&t?e.a===t.a&&e.b===t.b&&e.c===t.c&&e.d===t.d&&e.e===t.e&&e.f===t.f:e===t)}function It(e,t){return e===t||(e&&t?St(e.bounds,t.bounds)&&yt(e.center,t.center)&&bt(e.corners,t.corners)&&bt(e.outlineVertices,t.outlineVertices):e===t)}function vt(e){return e?e.clone():e}function wt(e){return e?e.clone():e}function Pt(e){return e?.map(e=>e.clone())}function kt(e){if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,o=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),i=Math.max(i,r.maxX),o=Math.max(o,r.maxY);return new Pm(t,n,i-t,o-n)}function Ct(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function Tt(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return o<n||r<i?null:new Pm(n,i,o-n,r-i)}function Et(e,t){return t.canReceiveChildren(e)&&!t.isTransformDescendantContainer(e)}function Bt(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*o.y-a.y*o.x)/s;return d>=0&&d<=1&&l>=0&&l<=1?d:null}function Mt(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new wm(n.minX,n.minY),new wm(n.maxX,n.minY),new wm(n.maxX,n.maxY),new wm(n.minX,n.maxY)];for(let o=0;o<i.length;o+=1){const n=i[o],r=i[(o+1)%i.length];if(n&&r&&null!==Bt(e,t,n,r))return!0}return!1}function Rt(e,t){return Pm.FromPoints([new wm(e.minX,e.minY),new wm(e.maxX,e.minY),new wm(e.maxX,e.maxY),new wm(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function At(e){return"top_left"===e||"left"===e||"bottom_left"===e}function Lt(e){return"top_right"===e||"right"===e||"bottom_right"===e}function Ft(e){return"top_left"===e||"top"===e||"top_right"===e}function $t(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function Ut(e){return At(e)!==Lt(e)&&Ft(e)!==$t(e)}function Dt({handleId:e,scaleX:t,scaleY:n}){const i=At(e)?t<0?"right":"left":Lt(e)?t<0?"left":"right":null,o=Ft(e)?n<0?"bottom":"top":$t(e)?n<0?"top":"bottom":null;return"top"===o&&"left"===i?"top_left":"top"===o&&"right"===i?"top_right":"bottom"===o&&"right"===i?"bottom_right":"bottom"===o&&"left"===i?"bottom_left":o||i||e}function zt({axis:e,startBounds:t,bounds:n,handleId:i,scale:o,isResizingFromCenter:r}){const s=Math.sign(o??1)||1;return r?s:"x"===e?At(i)?n.minX>=t.maxX?-1:1:Lt(i)?n.maxX<=t.minX?-1:1:s:Ft(i)?n.minY>=t.maxY?-1:1:$t(i)?n.maxY<=t.minY?-1:1:s}function _t({requestedBounds:e,handleId:t,actualWidth:n,actualHeight:i,scaleX:o,scaleY:r,isResizingFromCenter:s}){return new Pm(s?e.center.x-n/2:At(t)?o<0?e.minX:e.maxX-n:Lt(t)?o<0?e.maxX-n:e.minX:e.center.x-n/2,s?e.center.y-i/2:Ft(t)?r<0?e.minY:e.maxY-i:$t(t)?r<0?e.maxY-i:e.minY:e.center.y-i/2,n,i)}function Ht({bounds:e,startBounds:t,handleId:n,aspectRatio:i,isResizingFromCenter:o,scaleX:r,scaleY:s}){if(i<=0)return{bounds:e,scaleX:r??e.w/Math.max(1,t.w),scaleY:s??e.h/Math.max(1,t.h)};let a=e.w,d=e.h;const l=Math.sign(r??1)||1,c=Math.sign(s??1)||1;switch(n){case"left":case"right":d=a/i;break;case"top":case"bottom":a=d*i;break;default:{const e=a/Math.max(1,t.w),n=d/Math.max(1,t.h);Math.abs(e)>Math.abs(n)?d=a/i:a=d*i;break}}if(o){const e=t.center;return{bounds:new Pm(e.x-a/2,e.y-d/2,a,d),scaleX:l*(a/Math.max(1,t.w)),scaleY:c*(d/Math.max(1,t.h))}}let u;switch(n){case"top_left":u=new Pm(l<0?e.minX:e.maxX-a,c<0?e.minY:e.maxY-d,a,d);break;case"top_right":u=new Pm(l<0?e.maxX-a:e.minX,c<0?e.minY:e.maxY-d,a,d);break;case"bottom_right":u=new Pm(l<0?e.maxX-a:e.minX,c<0?e.maxY-d:e.minY,a,d);break;case"bottom_left":u=new Pm(l<0?e.minX:e.maxX-a,c<0?e.maxY-d:e.minY,a,d);break;case"top":u=new Pm(t.center.x-a/2,c<0?t.maxY:t.maxY-d,a,d);break;case"right":u=new Pm(l<0?t.minX-a:t.minX,t.center.y-d/2,a,d);break;case"bottom":u=new Pm(t.center.x-a/2,c<0?t.minY-d:t.minY,a,d);break;case"left":u=new Pm(l<0?t.maxX:t.maxX-a,t.center.y-d/2,a,d)}return{bounds:u,scaleX:l*(a/Math.max(1,t.w)),scaleY:c*(d/Math.max(1,t.h))}}function Nt(e,t){return e.x===t.x&&e.y===t.y}function Ot(e){return[new wm(e.minX,e.minY),new wm(e.center.x,e.minY),new wm(e.maxX,e.minY),new wm(e.minX,e.center.y),e.center,new wm(e.maxX,e.center.y),new wm(e.minX,e.maxY),new wm(e.center.x,e.maxY),new wm(e.maxX,e.maxY)]}function Wt(e,t){return"x"===t?e.x:e.y}function Yt(e,t){return"x"===t?e.minX:e.minY}function Xt(e,t){return"x"===t?e.maxX:e.maxY}function Kt(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function Vt(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function qt(e,t){return null!==Vt(e,t)}function jt(e,t){return new Pm(e.x+t.x,e.y+t.y,e.w,e.h)}function Gt(e,t,n){return jt(e,((e,t)=>"x"===e?new wm(t,0):new wm(0,t))(t,n))}function Zt(e){return[new wm(e.minX,e.minY),new wm(e.maxX,e.minY),new wm(e.maxX,e.maxY),new wm(e.minX,e.maxY)]}function Qt(e,t,n){const i=n.sub(t),o=i.len2();if(o<=1e-8)return e.dist2(t);const r=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/o));return e.dist2(new wm(t.x+i.x*r,t.y+i.y*r))}function Jt(e,t,n){const i=n.sub(t),o=i.len2();if(o<=1e-8)return t.clone();const r=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/o));return new wm(t.x+i.x*r,t.y+i.y*r)}function en(e,t){if(0===t.length)return null;if(1===t.length){const n=t[0].clone();return{point:n,distanceSquared:e.dist2(n)}}let n=null,i=Number.POSITIVE_INFINITY;const o=2===t.length?1:t.length;for(let r=0;r<o;r+=1){const o=t[r],s=t[(r+1)%t.length];if(!o||!s)continue;const a=Qt(e,o,s);a>=i||(i=a,n=Jt(e,o,s))}return n?{point:n,distanceSquared:i}:null}function tn(e){const t=[],n=new Set;for(const i of e){const e=`${i.x.toFixed(8)}:${i.y.toFixed(8)}`;n.has(e)||(n.add(e),t.push(i))}return t}function nn(e){const t=e.map(e=>({value:e.point.x,point:e})),n=e.map(e=>({value:e.point.y,point:e}));return t.sort(on),n.sort(on),{x:t,y:n}}function on(e,t){return e.value-t.value||e.point.id.localeCompare(t.point.id)}function rn(e,t,n,i){const o=((e,t)=>"x"===t?e.x:e.y)(e,t),r=[];for(let s=((e,t)=>{let n=0,i=e.length;for(;n<i;){const o=Math.floor((n+i)/2),r=e[o];r&&r.value<t?n=o+1:i=o}return n})(o,n);s<o.length;s+=1){const e=o[s];if(!e||e.value>i)break;r.push(e.point)}return r}function sn(e){return e.weight??(e.kind?eS[e.kind]:0)}function an(e,t){return`points:${e}:${[...t].sort().join("|")}`}function dn(e,t,n){if(!t)return!0;const i=(e=>Math.min(.2*e,1.5))(n);return e.distance<t.distance-1e-8?!(t.weight>e.weight+1e-8&&t.distance-e.distance<=i):e.distance<=t.distance+i&&e.weight>t.weight+1e-8}function ln(e,t,n,i,o={}){const r=o.releaseThreshold??i,s=Math.max(i,r),a=o.switchDistance??0;let d=null,l=null;for(const g of t){const t=Wt(g,e),a=rn(n,e,t-s,t+s);o.stats&&(o.stats.candidatePointCount+=a.length);for(const n of a){const s=Wt(n.point,e)-t,a=Math.abs(s),c={offset:s,distance:a,weight:sn(n),fromPrevious:!1};if(a<=i&&dn(c,d,i)&&(d=c),o.previousCandidatePointIds?.has(n.id)&&a<=r){const e={...c,fromPrevious:!0};dn(e,l,r)&&(l=e)}}}const c=l&&(!d||d.distance+a>=l.distance)?l:d;if(!c)return null;const u=c.fromPrevious&&c.distance>i?r:i,h=[];for(const g of t){const t=Wt(g,e),i=rn(n,e,t-u,t+u);for(const n of i){const i=Wt(n.point,e)-t;Math.abs(i)>u||Math.abs(i-c.offset)>1e-8||h.push({selectionPoint:g,candidatePoint:n.point,candidatePointId:n.id,candidateNodeId:n.nodeId})}}o.stats&&(o.stats.matchedPointCount+=h.length);const p=Array.from(new Set(h.map(e=>e.candidatePointId)));return h.length>0?{type:"points",id:an(e,p),nudge:c.offset,distance:c.distance,weight:c.weight,candidatePointIds:p,pairs:h}:null}function cn(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new wm(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new wm(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new wm(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new wm(t.minX,t.maxY))}return n}function un(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>Yt(e.bounds,t)-Yt(n.bounds,t)),o=[];for(let r=0;r<i.length;r+=1){const e=i[r];if(!e)continue;let s=Number.POSITIVE_INFINITY;for(let a=r+1;a<i.length;a+=1){const r=i[a];if(!r)continue;const d=Xt(e.bounds,t),l=Yt(r.bounds,t);if(l>s+1e-8)break;if(d>=l)continue;const c=Vt(Kt(e.bounds,t),Kt(r.bounds,t));c&&(s=l,o.push({direction:n,startNode:e,endNode:r,length:l-d,breadthIntersection:c}))}}return o}function hn(e,t,n,i){const o=Vt(Kt(t.bounds,i),Kt(n.bounds,i));return o?{direction:e,startNode:t,endNode:n,length:Yt(n.bounds,i)-Xt(t.bounds,i),breadthIntersection:o}:null}function pn(e,t){return[e,t.direction,t.startNode.id,t.endNode.id,t.length.toFixed(8)].join(":")}function gn(e,t,n,i,o={}){const r=Kt(t,e),s=((e,t)=>"x"===t?e.w:e.h)(t,e),a=o.releaseThreshold??i,d=o.switchDistance??0;let l=i+1,c=null,u=null;const h=(e,t,n)=>{const r=Math.abs(e);0!==t.length&&(r<=i&&r<l-1e-8&&(l=r,c={type:"gaps",id:n,nudge:e,distance:r,gaps:t}),o.previousSnapId===n&&r<=a&&(!u||r<u.distance-1e-8)&&(u={type:"gaps",id:n,nudge:e,distance:r,gaps:t}))},p=n=>({id:"selection",bounds:Gt(t,e,n)});for(const g of n){if(s<=g.length&&qt(r,g.breadthIntersection)){const n=Xt(g.startNode.bounds,e)+(g.length-s)/2-Yt(t,e),i=p(n);h(n,[hn(g.direction,g.startNode,i,e),hn(g.direction,i,g.endNode,e)].filter(e=>null!==e),`${pn(e,g)}:center`)}const n=Xt(g.endNode.bounds,e)+g.length-Yt(t,e),i=p(n);if(qt(Kt(i.bounds,e),g.breadthIntersection)){const t=hn(g.direction,g.endNode,i,e);h(n,t?[g,t]:[],`${pn(e,g)}:after`)}const o=Yt(g.startNode.bounds,e)-g.length-Xt(t,e),a=p(o);if(qt(Kt(a.bounds,e),g.breadthIntersection)){const t=hn(g.direction,a,g.startNode,e);h(o,t?[t,g]:[],`${pn(e,g)}:before`)}}return u&&(!c||c.distance+d>=u.distance)?u:c}function fn(e,t,n={}){if(!e)return t;if(!t)return e;const i=n.switchDistance??0;return"points"===n.previousSnap?.type&&n.previousSnap.id===e.id?Math.abs(t.nudge)+i<Math.abs(e.nudge)?t:e:"gaps"===n.previousSnap?.type&&n.previousSnap.id===t.id?Math.abs(e.nudge)+i<Math.abs(t.nudge)?e:t:Math.abs(e.nudge)<=Math.abs(t.nudge)?e:t}function mn(e,t){return e===t||e.length===t.length&&e.every((e,n)=>{const i=t[n];return!(!i||e.type!==i.type)&&("points"===e.type&&"points"===i.type?((e,t)=>e.id===t.id&&e.axis===t.axis&&e.rotation===t.rotation&&Nt(e.rotationCenter,t.rotationCenter)&&Nt(e.line[0],t.line[0])&&Nt(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&Nt(e,i)}))(e,i):"gaps"===e.type&&"gaps"===i.type&&function(e,t){return e.id===t.id&&e.direction===t.direction&&e.rotation===t.rotation&&Nt(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>Nt(e.startEdge[0],t.startEdge[0])&&Nt(e.startEdge[1],t.startEdge[1])&&Nt(e.endEdge[0],t.endEdge[0])&&Nt(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function Sn(e){return"horizontal"===e.direction?{startEdge:[new wm(e.startNode.bounds.maxX,e.startNode.bounds.minY),new wm(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new wm(e.endNode.bounds.minX,e.endNode.bounds.minY),new wm(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new wm(e.startNode.bounds.minX,e.startNode.bounds.maxY),new wm(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new wm(e.endNode.bounds.minX,e.endNode.bounds.minY),new wm(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function yn(e,t,n,i){const o=tn([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),r=vn(e,o);return{id:wn(e,r,o),type:"points",axis:e,line:r,points:o,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function bn(e,t,n,i){return xn(e,t,n).map(t=>yn(e,t,n,i))}function xn(e,t,n){const i=new Map;for(const o of t.pairs){const t=Wt(o.selectionPoint.add(n),e).toFixed(8),r=i.get(t);r?r.push(o):i.set(t,[o])}return Array.from(i.values()).map(e=>({type:"points",id:t.id,nudge:t.nudge,distance:t.distance,weight:t.weight,candidatePointIds:Array.from(new Set(e.map(e=>e.candidatePointId))),pairs:e}))}function In(e,t,n){return"x"===e?[new wm(t,n.minY),new wm(t,n.maxY)]:[new wm(n.minX,t),new wm(n.maxX,t)]}function vn(e,t){if(0===t.length)return[wm.Zero(),wm.Zero()];let n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const s of t)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y);return"x"===e?[new wm(n,o),new wm(n,r)]:[new wm(n,o),new wm(i,o)]}function wn(e,t,n){return`points:${e}:line:${t.map(e=>`${e.x.toFixed(4)},${e.y.toFixed(4)}`).join("|")}:points:${n.map(e=>`${e.x.toFixed(4)},${e.y.toFixed(4)}`).join("|")}`}function Pn(e,t,n,i,o,r){return xn(e,t,n).map(t=>((e,t,n,i,o,r)=>{const s=yn(e,t,n,i),a=t.pairs[0],d=Wt(a?.selectionPoint.add(n)??o.center,e),l=new Map(r.map(e=>[e.id,e.bounds])),c=[],u=new Set;for(const g of t.pairs){if(u.has(g.candidateNodeId))continue;u.add(g.candidateNodeId);const t=l.get(g.candidateNodeId);t&&c.push(...In(e,d,t))}const h=tn([...s.points,...In(e,d,o),...c]),p=vn(e,tn([...In(e,d,o),...c]));return{...s,id:wn(e,p,h),line:p,points:h}})(e,t,n,i,o,r))}function kn(e){return{id:wn("x",[e,e],[e]),type:"points",axis:"x",line:[e.clone(),e.clone()],points:[e.clone()],rotation:0,rotationCenter:e.clone()}}function Cn(e,t,n){const i="x"===e?new wm(n.x,t.y):new wm(t.x,n.y),o=tn([n.clone(),i]),r=vn(e,o);return{id:wn(e,r,o),type:"points",axis:e,line:r,points:o,rotation:0,rotationCenter:wm.Zero()}}function Tn(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new wm(0,n.y):new wm(n.x,0),o=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:jt(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:jt(e.endNode.bounds,i)}:e.endNode}));return{id:`gaps:${o.map(e=>`${e.startNode.id}:${e.endNode.id}:${e.length.toFixed(4)}`).join("|")}`,type:"gaps",direction:o[0]?.direction??"horizontal",gaps:o.map(Sn),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function En(e){return"points"===e.type?{...e,line:[e.line[0].clone(),e.line[1].clone()],points:e.points.map(e=>e.clone()),rotationCenter:e.rotationCenter.clone()}:{...e,gaps:e.gaps.map(e=>({startEdge:[e.startEdge[0].clone(),e.startEdge[1].clone()],endEdge:[e.endEdge[0].clone(),e.endEdge[1].clone()]})),rotationCenter:e.rotationCenter.clone()}}function Bn(e,t){return 0===t.rotation?e.clone():wm.RotWith(e,t.rotationCenter,-t.rotation)}function Mn(e,t){return 0===t.rotation?e.clone():wm.RotWith(e,t.rotationCenter,t.rotation)}function Rn(e,t){return Mn(e,t)}function An(e,t,n,i,o){return 0===n?i:i+(e-t)/n*o}function Ln({point:e,fromBounds:t,toBounds:n}){return new wm(An(e.x,t.minX,t.w,n.minX,n.w),An(e.y,t.minY,t.h,n.minY,n.h))}function Fn({axis:e,bounds:t,point:n}){return"horizontal"===e?new wm(t.minX+t.maxX-n.x,n.y):new wm(n.x,t.minY+t.maxY-n.y)}function $n({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new Pm(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new Pm(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function Un(e){return{point:e.point,kind:e.kind??"custom",weight:e.weight}}function Dn(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function zn(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y&&e.w===t.w&&e.h===t.h:e===t)}function _n(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o)return!1;if(!(i.id===o.id&&i.usesSelectionPathOverlay===o.usesSelectionPathOverlay&&Dn(i.startPagePoint,o.startPagePoint)&&Dn(i.endPagePoint,o.endPagePoint)&&Dn(i.middlePagePoint,o.middlePagePoint)&&Xe(i.bindingSegments,o.bindingSegments)&&i.path===o.path))return!1}return!0}function Hn(e,t){return e===t||(e&&t?zn(e.bounds,t.bounds)&&e.rotation===t.rotation&&Dn(e.rotationCenter,t.rotationCenter)&&e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius:e===t)}function Nn(e,t){return e===t||(e&&t?zn(e.bounds,t.bounds)&&e.rotation===t.rotation&&Dn(e.rotationCenter,t.rotationCenter):e===t)}function On(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Nn(e[n]??null,t[n]??null))return!1;return!0}function Wn(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function Yn(e,t){return e.id===t.id&&Dn(e.point,t.point)&&zn(e.bounds,t.bounds)}function Xn(e,t){return e.id===t.id&&Dn(e.point,t.point)&&zn(e.bounds,t.bounds)}function Kn(e,t){return e.terminal===t.terminal&&Dn(e.point,t.point)&&zn(e.bounds,t.bounds)}function Vn(e,t){return Dn(e.point,t.point)&&zn(e.bounds,t.bounds)}function qn(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Dn(e.point,t.point)&&zn(e.bounds,t.bounds)}function jn(e,t){return e.id===t.id&&Dn(e.point,t.point)}function Gn(e,t){return e.id===t.id&&Dn(e.point,t.point)}function Zn(e,t){return e.terminal===t.terminal&&Dn(e.point,t.point)}function Qn(e,t){return Dn(e.point,t.point)}function Jn(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Dn(e.point,t.point)}function ei(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1){const o=e[i],r=t[i];if(!o||!r||!n(o,r))return!1}return!0}function ti({bounds:e,rotateOffset:t,referenceRotation:n,frameRotation:i}){return((e,t)=>{const n=Math.round((e-t)/Math.PI);return 1===Math.abs(n%2)})(n,i)?new wm(e.maxX+t,e.minY-t):new wm(e.minX-t,e.maxY+t)}function ni(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&ei(e.resizeHandles,t.resizeHandles,Yn)&&ei(e.rotateHandles,t.rotateHandles,Xn)&&ei(e.terminalHandles,t.terminalHandles,Kn)&&ei(e.middleHandles,t.middleHandles,Vn)&&ei(e.customHandles,t.customHandles,qn):e===t)}function ii(e,t){return e===t||(e&&t?ei(e.resizeHandleAnchors,t.resizeHandleAnchors,jn)&&ei(e.rotateHandleAnchors,t.rotateHandleAnchors,Gn)&&ei(e.terminalHandleAnchors,t.terminalHandleAnchors,Zn)&&ei(e.middleHandleAnchors,t.middleHandleAnchors,Qn)&&ei(e.customHandleAnchors,t.customHandleAnchors,Jn):e===t)}function oi(e,t){return e===t||(e&&t?e.resizeHandleCount===t.resizeHandleCount&&e.rotateHandleCount===t.rotateHandleCount&&e.terminalHandleCount===t.terminalHandleCount&&e.middleHandleCount===t.middleHandleCount&&e.customHandleCount===t.customHandleCount:e===t)}function ri(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function si(e,t,n,i,o){const r=e.map(e=>i(e)),s=e.every(e=>o(e)),a=r.flatMap(e=>e.terminalHandleAnchors),d=r.flatMap(e=>e.middleHandleAnchors),l=r.flatMap(e=>e.customHandleAnchors??[]),c=a.length>0||d.length>0||l.length>0;if(!t)return{resizeHandleAnchors:[],rotateHandleAnchors:[],terminalHandleAnchors:a,middleHandleAnchors:d,customHandleAnchors:l};const{bounds:u,rotation:h,rotationCenter:p,hasCompatibleRotation:g}=t,f=e[0]?.rotation??h,m=8/n,S=14/n,y=u.w<2*m,b=u.h<2*m,x=e=>0===h?e:wm.RotWith(e,p,h),I=new wm(u.minX,u.minY),v=new wm(u.center.x,u.minY),w=new wm(u.maxX,u.minY),P=new wm(u.maxX,u.center.y),k=new wm(u.maxX,u.maxY),C=new wm(u.center.x,u.maxY),T=new wm(u.minX,u.maxY),E=new wm(u.minX,u.center.y);return{resizeHandleAnchors:s&&!c&&g?[{kind:"resize",id:"top_left",point:x(I)},...y?[]:[{kind:"resize",id:"top",point:x(v)}],...y&&b?[]:[{kind:"resize",id:"top_right",point:x(w)}],...b?[]:[{kind:"resize",id:"right",point:x(P)}],...y||b?[]:[{kind:"resize",id:"bottom_right",point:x(k)}],...y?[]:[{kind:"resize",id:"bottom",point:x(C)}],...y||b?[]:[{kind:"resize",id:"bottom_left",point:x(T)}],...b?[]:[{kind:"resize",id:"left",point:x(E)}]]:[],rotateHandleAnchors:!s||c||!g||y||b?[]:[{kind:"rotate",id:"bottom_left_rotate",point:x(ti({bounds:u,rotateOffset:S,referenceRotation:f,frameRotation:h}))}],terminalHandleAnchors:a,middleHandleAnchors:d,customHandleAnchors:l}}function ai(e,t){const n=8/t,i=n/2,o=e=>new Pm(e.x-i,e.y-i,n,n);return{resizeHandles:e.resizeHandleAnchors.map(e=>({...e,bounds:o(e.point)})),rotateHandles:e.rotateHandleAnchors.map(e=>({...e,bounds:o(e.point)})),terminalHandles:e.terminalHandleAnchors.map(e=>({...e,bounds:o(e.point)})),middleHandles:e.middleHandleAnchors.map(e=>({...e,bounds:o(e.point)})),customHandles:e.customHandleAnchors.map(e=>({...e,bounds:o(e.point)}))}}function di(e){const t=e.getSelectedShapes();if(0===t.length)return null;if(t.some(e=>e.isLocked))return null;const n=t[0]?.parentId;if(!n)return null;if(t.some(e=>e.parentId!==n))return null;const i=e.getChildShapes(n),o=new Set(t.map(e=>e.id)),r=i.map((e,t)=>o.has(e.id)?t:-1).filter(e=>e>=0);return r.length!==t.length?null:{parentId:n,selectedCount:t.length,count:i.length,canMoveBackward:r.some(e=>e>0&&!o.has(i[e-1].id)),canMoveForward:r.some(e=>e<i.length-1&&!o.has(i[e+1].id))}}function li(e){const t=e.getSelectedShapes();if(1!==t.length)return null;const[n]=t;if(!n||n.isLocked)return null;const i=e.getChildShapes(n.parentId),o=i.findIndex(e=>e.id===n.id);return o<0?null:{parentId:n.parentId,index:o,count:i.length,canMoveBackward:o>0,canMoveForward:o<i.length-1}}function ci(e,t){const n=t.map(t=>e.getShape(t)).filter(e=>!!e);if(0===n.length)return null;if(n.some(t=>t.isLocked||e.isShapeHidden(t.id)))return null;const i=n[0]?.parentId;if(!i)return null;if(n.some(e=>e.parentId!==i))return null;const o=e.getChildShapes(i),r=new Set(n.map(e=>e.id)),s=o.map((e,t)=>r.has(e.id)?t:-1).filter(e=>e>=0);return s.length!==n.length?null:{parentId:i,selectedCount:n.length,count:o.length,canMoveBackward:s.some(e=>e>0&&!r.has(o[e-1].id)),canMoveForward:s.some(e=>e<o.length-1&&!r.has(o[e+1].id))}}function ui(e,t,n,i="user"){const o=ci(e,t);if(!o)return!1;const r=e.getChildShapes(o.parentId),s=new Set(t),a=[...r];let d=!1;if("backward"===n)for(let l=1;l<a.length;l+=1){const e=a[l],t=a[l-1];e&&t&&s.has(e.id)&&!s.has(t.id)&&(a[l-1]=e,a[l]=t,d=!0)}else for(let l=a.length-2;l>=0;l-=1){const e=a[l],t=a[l+1];e&&t&&s.has(e.id)&&!s.has(t.id)&&(a[l]=t,a[l+1]=e,d=!0)}return!!d&&(e.cancelInteractionForCommand(),e.commands.updateShapes(a.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:i}),!0)}function hi(e,t,n,i="user"){const o=ci(e,t);if(!o)return!1;const r=e.getChildShapes(o.parentId),s=new Set(t),a=[],d=[];for(const c of r)s.has(c.id)?a.push(c):d.push(c);if(a.length!==s.size)return!1;if(!("back"===n?o.canMoveBackward:o.canMoveForward))return!1;const l="back"===n?[...a,...d]:[...d,...a];return e.cancelInteractionForCommand(),e.commands.updateShapes(l.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:i}),!0}function pi(e,t,n){if(t.startsWith("page:"))return!!e.getPage(t);const i=e.getShape(t);if(!i)return!1;if(n){if(i.id===n)return!1;if(e.getDescendantShapeIds(n).includes(i.id))return!1}return e.getShapeUtil(i).canReceiveChildren(i)}function gi(e,t,n,i,o){const r=((e,t,n,i)=>{const o=new Set(n),r=e.getChildShapes(t.parentId).filter(e=>!o.has(e.id));let s=r.length;if(t.beforeId){const e=r.findIndex(e=>e.id===t.beforeId);if(-1===e)return null;s=e}return r.splice(s,0,...i),r.map((n,i)=>({id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+1)}))})(e,t,n,i);return!!r&&(e.cancelInteractionForCommand(),e.commands.updateShapes(r,{source:o}),!0)}function fi(e){const t="string"==typeof e?{key:e}:e;return{key:yi(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}}function mi(e){const t=fi(e),n=[];var i;return t.accelKey?n.push("⌘"):(t.ctrlKey&&n.push("Ctrl"),t.metaKey&&n.push("Meta")),t.altKey&&n.push("Alt"),t.shiftKey&&n.push("Shift"),n.push(1===(i=t.key).length?i.toUpperCase():i),n.join("")}function Si(e,t){return!(yi(t.key)!==e.key||t.altKey!==e.altKey||t.shiftKey!==e.shiftKey||void 0!==e.accelKey&&t.accelKey!==e.accelKey||void 0!==e.ctrlKey&&t.ctrlKey!==e.ctrlKey||void 0!==e.metaKey&&t.metaKey!==e.metaKey||void 0===e.accelKey&&void 0===e.ctrlKey&&void 0===e.metaKey&&t.accelKey)}function yi(e){return e.toLowerCase()}function bi(e){return[e.key,e.altKey?"alt":null,e.ctrlKey?"ctrl":null,e.metaKey?"meta":null,e.shiftKey?"shift":null,e.accelKey?"accel":null].filter(Boolean).join("+")}function xi(e,t,n){return Math.min(n,Math.max(t,e))}function Ii(e){return 0===e.length?"none":e.map(e=>`${e.start}-${e.end-1}`).join(", ")}function vi(e,t=0){if(0===e.length)return[];const n=[...e].sort((e,t)=>e.start-t.start),i=[];for(const o of n){const e=i[i.length-1];!e||o.start>e.end+t?i.push({...o}):e.end=Math.max(e.end,o.end)}return i}function wi(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function Pi(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function ki(e,t,n=0){return vi(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n)}function Ci(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function Ti(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:Ci(e,t)}}function Ei(e,t,n){return e.dist(((e,t,n)=>{const i=t.sub(e),o=n.sub(e),r=i.x*i.x+i.y*i.y;if(0===r)return e;const s=Math.max(0,Math.min(1,(o.x*i.x+o.y*i.y)/r));return new wm(e.x+i.x*s,e.y+i.y*s)})(t,n,e))}function Bi(e,t,n,i){return((e,t,n,i)=>{const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*o.y-a.y*o.x)/s;return d>=0&&d<=1&&l>=0&&l<=1})(e,t,n,i)?0:Math.min(Ei(e,n,i),Ei(t,n,i),Ei(n,e,t),Ei(i,e,t))}function Mi(e){const t=Ue(e,"document"),n=new Set,i=new Set,o=new Set;for(const r of t.records)Ri(r)&&"string"==typeof r.type&&("shape"===r.typeName?n.add(r.type):"binding"===r.typeName?i.add(r.type):"asset"===r.typeName&&o.add(r.type));return{shapeTypes:Li(n),bindingTypes:Li(i),assetTypes:Li(o)}}function Ri(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ai(e,t){return e.filter(e=>!t.has(e))}function Li(e){return[...e].sort((e,t)=>e.localeCompare(t))}function Fi(e){return[new wm(e.minX,e.minY),new wm(e.maxX,e.minY),new wm(e.maxX,e.maxY),new wm(e.minX,e.maxY)]}function $i(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*o.y-a.y*o.x)/s;return d>=0&&d<=1&&l>=0&&l<=1?d:null}function Ui(e,t,n){const i=n.center,o=t.sub(i).rot(-e.rotation);return i.add(new wm(0===e.scaleX?0:o.x/e.scaleX,0===e.scaleY?0:o.y/e.scaleY))}function Di(e,t,n){const i=e[t];return"number"==typeof i&&Number.isFinite(i)?i:n}function zi(e){return Math.min(1,Math.max(0,(96-e)/96))}function _i(e,t,n){if(t.w<=0||t.h<=0||n<=0)return wm.Zero();const i=Math.min(n,32),o=zi(e.x),r=zi(t.w-e.x),s=zi(e.y),a=1.25*(r-o)*i,d=1.25*(zi(t.h-e.y)-s)*i;return 0===a&&0===d?wm.Zero():new wm(a,d)}function Hi(e,t,n){const i=e.inputs.state.get();if("dragging"!==i.dragPhase||!i.currentPagePoint)return null;let o=i.currentPagePoint;if(!i.currentScreenPoint)return"apply_after_scroll"===n?null:{pagePoint:o,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey};const r=_i(i.currentScreenPoint,e.viewportScreenSizeSignal.get(),t.elapsed),s=0!==r.x||0!==r.y;return s||"always_apply"===n?(s&&(e.panCamera(r),o=e.screenToPage(i.currentScreenPoint)),{pagePoint:o,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey}):null}function Ni(e,t){const n=(e=>{const t=e.inputs.state.get();return"dragging"===t.dragPhase&&t.currentPagePoint?{pagePoint:t.currentPagePoint,shiftKey:t.shiftKey,altKey:t.altKey,accelKey:t.accelKey,ctrlKey:t.ctrlKey}:null})(e);n&&t(n)}function Oi(e,t,n){const i=new Set(n);if(i.has(t))return t;const o=Wi(e,t);for(const s of o)if(i.has(s.ancestorId))return s.childId;const r=o[0]?.ancestorId;return r&&n.some(t=>((e,t)=>Wi(e,t)[0]?.ancestorId??null)(e,t)===r)?t:o[o.length-1]?.ancestorId??t}function Wi(e,t){const n=[];let i=e.getShape(t),o=t;const r=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(r.has(t))return n;r.add(t);const s=e.getShape(t);if(!s)return n;e.getShapeUtil(s).isTransformDescendantContainer(s)&&n.push({ancestorId:s.id,childId:o}),o=s.id,i=s}return n}function Yi({shiftKey:e,accelKey:t}){return e||t}function Xi({ctrlKey:e}){return e}function Ki(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function Vi(e,t){return Math.round(e/t)*t}function qi(e,t,n,i,o,r,s,a,d,l,c){const u=ji(d,l),h=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=Ln({point:new wm(e.minX,e.minY),fromBounds:t,toBounds:n}),o=Ln({point:new wm(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new Pm(Math.min(i.x,o.x),Math.min(i.y,o.y),Math.abs(o.x-i.x),Math.abs(o.y-i.y))})({bounds:t.localBounds,fromBounds:n,toBounds:i}),p=Mn(h.center,u),g=e.getShapeUtil(t.shape).resizeSelectionBounds(t.shape,{handleId:s,pageCenter:p,selectionLocalBounds:h,scaleX:o,scaleY:r,isResizingFromCenter:a,selectionRotation:l,selectionRotationCenter:d});c.id=t.shape.id,c.x=g.x,c.y=g.y,c.rotation=g.rotation??t.rotation,c.scaleX=g.scaleX,c.scaleY=g.scaleY,c.props=g.props}function ji(e,t){return{rotation:t,rotationCenter:e}}function Gi(e,t,n,i,o,r,s,a,d,l,c){const u=ji(d,l),h=Mn(Zi({point:t.startLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u),p=Mn(Zi({point:t.endLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u),g=e.getShapeUtil(t.shape).updateSelectionPagePoints(t.shape,{pagePoints:[h,p]});c.id=t.shape.id,c.x=g.x,c.y=g.y,c.rotation=g.rotation,c.scaleX=g.scaleX,c.scaleY=g.scaleY,c.props=g.props}function Zi({point:e,startBounds:t,scaleX:n,scaleY:i,handleId:o,isResizingFromCenter:r}){const s=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:At(t)?e.maxX:Lt(t)?e.minX:e.center.x)({startBounds:t,handleId:o,isResizingFromCenter:r}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:Ft(t)?e.maxY:$t(t)?e.minY:e.center.y)({startBounds:t,handleId:o,isResizingFromCenter:r});return new wm(s+(e.x-s)*n,a+(e.y-a)*i)}function Qi(e,t,n){const i=1===t.length;let o=null;for(const r of t){const t=e.getShapeUtil(r).getSelectionResizeAspectRatioLock(r,{editor:e,handleId:n,isOnlySelected:i});if(null!==t){if(null!==o&&o!==t)return null;o=t}}return o}function Ji(e,t,n,i){const o=e.localBounds.center,r=Rn(new wm(e.x+o.x,e.y+o.y),{rotation:n,rotationCenter:t});i.id=e.id,i.x=r.x-o.x,i.y=r.y-o.y,i.rotation=e.rotation+n}function eo(e,t,n,i,o){const r=e.getShapeUtil(t.shape).updateSelectionPagePoints(t.shape,{pagePoints:[Rn(t.startPagePoint,{rotation:i,rotationCenter:n}),Rn(t.endPagePoint,{rotation:i,rotationCenter:n})]});o.id=t.shape.id,o.x=r.x,o.y=r.y,o.rotation=r.rotation,o.scaleX=r.scaleX,o.scaleY=r.scaleY,o.props=r.props}function to(e,t){let n=null;for(const i of t){const t=e.getShape(i);if(!t)return null;if(n){if(t.parentId!==n)return null}else n=t.parentId}return n}function no(e,t,n){const i=n?e.getContainingShapeParentIdAtPoint(t,n):e.getContainingShapeParentId(t);if(!i)return null;const o=to(e,t);if(n||!o||!o.startsWith("shape:")||i===o)return i;const r=e.getShape(o);return r&&e.getShapeUtil(r).canReceiveChildren(r)&&t.every(t=>{const n=e.getShapeContainment(r.id,t);return"inside"===n||"intersecting"===n})?o:i}function io(e,t,n){const i=no(e,t,n);i&&t.some(t=>e.getShape(t)?.parentId!==i)&&e.commands.reparentShapes({ids:[...t],parentId:i})}function oo(e,t,n,i={}){let o=!0;return(e=>{const r=new Im(e,()=>{t.get(),o&&!1===i.fireImmediately?o=!1:(o=!1,n())},void 0);return r.attach(),()=>r.detach()})(e)}function ro(e=[]){const t=new VS;return t.registerCanvasRenderPlugins(e),t}function so(e,t){return(e.order??0)-(t.order??0)}function ao(e=[]){const t=new GS;return t.registerCanvasRenderPlugins(e),t}function lo(){return Vf(QS)}function co(e=[]){const t=new JS;return t.registerCanvasRenderPlugins(e),t}function uo(e,t){return`${e}:${t}`}function ho(e,t){const n=e.get(t);if(n)return n;const i=[];return e.set(t,i),i}function po(e,t,n){e.push(t),e.sort((e,t)=>{const i=(e.order??0)-(t.order??0);return 0!==i?i:(n.get(e.id)??0)-(n.get(t.id)??0)})}function go(e,t){if(!e)return;const n=e.findIndex(e=>e.id===t);-1!==n&&e.splice(n,1)}function fo(e=[]){const t=new ey;return t.registerEditorRuntimePlugins(e),t}function mo(e,t,n){const i=(e.order??0)-(t.order??0);return 0===i&&e.id&&t.id?(n?.get(e.id)??0)-(n?.get(t.id)??0):i}function So(e=[]){const t=new ty;return t.registerEditorRuntimePlugins(e),t}function yo(e,t){return t?ny:k(e)}function bo(e){if(!e.createFeature&&!e.addExtensions)throw new Error(`Land extension "${e.name}" must define createFeature() or addExtensions().`);return new iy(e,e.addOptions?.()??{})}function xo(e,t){return Io(e,t)}function Io(e,t){const n={...e};for(const[i,o]of Object.entries(t)){const t=e[i];n[i]=vo(t)&&vo(o)?Io(t,o):o}return n}function vo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wo(e){const{extensionName:t,feature:n,source:i}=e;return{id:n.id,extensionName:t,source:i,editorRuntimePluginIds:n.editorRuntimePlugins.map(e=>e.id),canvasRenderPluginIds:n.canvasRenderPlugins.map(e=>e.id),interactionHandlerIds:n.editorRuntimePlugins.flatMap(e=>(e.interactionHandlers??[]).map(e=>e.id)),canvasActionIds:n.editorRuntimePlugins.flatMap(e=>(e.canvasActions??[]).map(e=>e.id)),toolbarContributionIds:n.editorRuntimePlugins.flatMap(e=>(e.toolbarContributions??[]).map(e=>e.id)),toolbarContributions:n.editorRuntimePlugins.flatMap(e=>(e.toolbarContributions??[]).map(e=>({id:e.id,surface:e.surface,placement:e.placement??"context",actionIds:[...e.actionIds]}))),contextMenuContributionIds:n.editorRuntimePlugins.flatMap(e=>(e.contextMenuContributions??[]).map(e=>e.id)),contextMenuContributions:n.editorRuntimePlugins.flatMap(e=>(e.contextMenuContributions??[]).map(e=>({id:e.id,target:e.target,actionIds:[...e.actionIds]}))),domEventGuardIds:n.canvasRenderPlugins.flatMap(e=>(e.domEventGuards??[]).map(e=>e.id)),canvasOverlayIds:n.canvasRenderPlugins.flatMap(e=>(e.canvasOverlays??[]).map(e=>e.id)),selectionCustomHandleRendererTypes:n.canvasRenderPlugins.flatMap(e=>(e.selectionCustomHandleRenderers??[]).map(e=>e.type)),canvasProviderIds:n.canvasRenderPlugins.flatMap(e=>(e.canvasProviders??[]).map(e=>e.id)),canvasComponentIds:n.canvasRenderPlugins.flatMap(e=>(e.canvasComponents??[]).map(e=>e.id)),shapeTypes:[...n.shapeTypes]}}function Po({editorRuntimePlugins:e,canvasRenderPlugins:t,knownHostActionIds:n,rendererRegistry:i,resolvedFeatures:o}){const r=[],s=o.map(({feature:e})=>e.id),a=e.map(e=>e.id),d=t.map(e=>e.id),l=e.flatMap(e=>(e.interactionHandlers??[]).map(e=>e.id)),c=e.flatMap(e=>(e.canvasActions??[]).map(e=>e.id)),u=e.flatMap(e=>(e.toolbarContributions??[]).map(e=>e.id)),h=e.flatMap(e=>(e.contextMenuContributions??[]).map(e=>e.id)),p=new Set([...n,...c]),g=t.flatMap(e=>(e.domEventGuards??[]).map(e=>e.id)),f=t.flatMap(e=>(e.canvasOverlays??[]).map(e=>e.id)),m=t.flatMap(e=>(e.selectionCustomHandleRenderers??[]).map(e=>e.type)),S=t.flatMap(e=>(e.canvasProviders??[]).map(e=>e.id)),y=t.flatMap(e=>(e.canvasComponents??[]).map(e=>e.id)),b=new Set(e.flatMap(e=>(e.shapeUtils??[]).map(e=>e.type))),x=new Set(e.flatMap(e=>(e.shapeSvgExporters??[]).map(e=>e.type))),I=new Map(e.flatMap(e=>(e.shapeCapabilities??[]).map(e=>[e.type,e]))),v=new Set(i.getRegisteredShapeTypes());ko({code:"duplicate-feature-id",ids:s,issues:r,messagePrefix:"Duplicate feature id"}),ko({code:"duplicate-editor-runtime-plugin-id",ids:a,issues:r,messagePrefix:"Duplicate editor runtime plugin id"}),ko({code:"duplicate-canvas-render-plugin-id",ids:d,issues:r,messagePrefix:"Duplicate canvas render plugin id"}),ko({code:"duplicate-interaction-handler-id",ids:l,issues:r,messagePrefix:"Duplicate interaction handler id"}),ko({code:"duplicate-canvas-action-id",ids:c,issues:r,messagePrefix:"Duplicate canvas action id"}),ko({code:"duplicate-toolbar-contribution-id",ids:u,issues:r,messagePrefix:"Duplicate toolbar contribution id"}),ko({code:"duplicate-context-menu-contribution-id",ids:h,issues:r,messagePrefix:"Duplicate context menu contribution id"}),(({resolvedFeatures:e,issues:t,knownCanvasActionIds:n})=>{for(const{feature:i}of e)for(const e of i.editorRuntimePlugins)for(const o of e.toolbarContributions??[])for(const r of o.actionIds)n.has(r)||t.push({severity:"error",code:"missing-canvas-action",featureId:i.id,pluginId:e.id,shapeType:null,message:`Toolbar contribution ${o.id} references missing action ${r}.`})})({resolvedFeatures:o,issues:r,knownCanvasActionIds:p}),(({resolvedFeatures:e,issues:t,knownCanvasActionIds:n})=>{for(const{feature:i}of e)for(const e of i.editorRuntimePlugins)for(const o of e.contextMenuContributions??[])for(const r of o.actionIds)n.has(r)||t.push({severity:"error",code:"missing-context-menu-action",featureId:i.id,pluginId:e.id,shapeType:null,message:`Context menu contribution ${o.id} references missing action ${r}.`})})({resolvedFeatures:o,issues:r,knownCanvasActionIds:p}),ko({code:"duplicate-dom-event-guard-id",ids:g,issues:r,messagePrefix:"Duplicate DOM event guard id"}),ko({code:"duplicate-canvas-overlay-id",ids:f,issues:r,messagePrefix:"Duplicate canvas overlay id"}),ko({code:"duplicate-selection-custom-handle-renderer",ids:m,issues:r,messagePrefix:"Duplicate selection custom handle renderer"}),ko({code:"duplicate-canvas-provider-id",ids:S,issues:r,messagePrefix:"Duplicate canvas render plugin provider id"}),ko({code:"duplicate-canvas-component-id",ids:y,issues:r,messagePrefix:"Duplicate canvas render plugin component id"});const w=o.flatMap(({feature:e})=>{const t=0===e.shapeTypes.length&&e.editorRuntimePlugins.some(e=>(e.toolbarContributions??[]).some(e=>"tool"===e.surface)||void 0!==e.setup);return 0===e.editorRuntimePlugins.length&&r.push({severity:"error",code:"missing-editor-runtime-plugin",featureId:e.id,pluginId:null,shapeType:null,message:`Feature ${e.id} does not include an editor runtime plugin.`}),0!==e.canvasRenderPlugins.length||t||r.push({severity:"error",code:"missing-canvas-render-plugin",featureId:e.id,pluginId:null,shapeType:null,message:`Feature ${e.id} does not include a canvas render plugin.`}),0!==e.shapeTypes.length||t||r.push({severity:"error",code:"missing-shape-type",featureId:e.id,pluginId:null,shapeType:null,message:`Feature ${e.id} does not declare shape types.`}),e.shapeTypes.map(t=>{const n=I.get(t)??null,i=b.has(t),o=x.has(t),s=v.has(t),a=i&&o?"supported":"missing";return n||r.push({severity:"error",code:"missing-shape-capability",featureId:e.id,pluginId:null,shapeType:t,message:`Shape type ${t} does not have a core capability entry.`}),i||r.push({severity:"error",code:"missing-shape-util",featureId:e.id,pluginId:null,shapeType:t,message:`Shape type ${t} does not have a core shape util.`}),"supported"!==n?.reactRenderer||s||r.push({severity:"error",code:"missing-canvas-renderer",featureId:e.id,pluginId:null,shapeType:t,message:`Shape type ${t} declares React renderer support but no canvas renderer registered.`}),o||r.push({severity:"warning",code:"missing-svg-exporter",featureId:e.id,pluginId:null,shapeType:t,message:`Shape type ${t} does not have an SVG exporter.`}),{featureId:e.id,shapeType:t,hasCapability:null!==n,hasShapeUtil:i,hasSvgExporter:o,hasCanvasRenderer:s,exportSupport:a}})}),P=r.filter(e=>"error"===e.severity).length;return{verdict:0===P?"pass":"fail",issueCount:r.length,errorCount:P,warningCount:r.length-P,issues:r,featureIds:s,editorRuntimePluginIds:a,canvasRenderPluginIds:d,interactionHandlerIds:l,canvasActionIds:c,toolbarContributionIds:u,contextMenuContributionIds:h,domEventGuardIds:g,canvasOverlayIds:f,selectionCustomHandleRendererTypes:m,canvasProviderIds:S,canvasComponentIds:y,registeredRendererTypes:Array.from(v),shapeSummaries:w}}function ko({code:e,ids:t,issues:n,messagePrefix:i}){const o=new Map;for(const r of t)o.set(r,(o.get(r)??0)+1);for(const[r,s]of o)s>1&&n.push({severity:"error",code:e,featureId:null,pluginId:r,shapeType:null,message:`${i}: ${r}.`})}function Co(e,t={}){const n=t.knownHostActionIds??[],i=t.source??"built-in",o=function(e){const t=[],n=new Set;let i=0;const o=e=>{if(n.has(e))throw new Error(`Circular Land extension bundle detected at "${e.name}".`);n.add(e),t.push({extension:e,index:i}),i+=1;for(const t of e.getExtensions())o(t);n.delete(e)};for(const s of e)o(s);const r=(e=>{const t=new Set,n=new Set;for(const i of e)t.has(i)?n.add(i):t.add(i);return[...n]})(t.map(({extension:e})=>e.name));if(r.length>0)throw new Error(`Duplicate Land extension names: ${r.join(", ")}.`);return t.sort((e,t)=>t.extension.priority-e.extension.priority||e.index-t.index).map(({extension:e})=>({extension:e,feature:e.createFeature()}))}(e).flatMap(({extension:e,feature:t})=>t?[{extensionName:e.name,feature:t,source:i}]:[]),r=(e=>e.flatMap(({feature:e})=>e.editorRuntimePlugins))(o),s=(e=>e.flatMap(({feature:e})=>e.canvasRenderPlugins))(o),a=(e=>e.flatMap(e=>[...e.canvasProviders??[]]))(s),d=(e=>e.flatMap(e=>[...e.canvasComponents??[]]))(s),l=o.map(wo),c=(e=>e.filter(({source:e})=>"built-in"!==e).flatMap(({feature:e})=>[...e.editorRuntimePlugins.map(e=>e.id),...e.canvasRenderPlugins.map(e=>e.id)]))(o),u=((e=[])=>{const t=new KS;return t.registerEditorRuntimePlugins(e),t})(r),h=ro(s);return{editorRuntimePlugins:r,canvasRenderPlugins:s,canvasProviders:a,canvasComponents:d,actionRegistry:u,rendererRegistry:h,overlayRegistry:ao(s),domEventGuardRegistry:co(s),toolbarRegistry:fo(r),contextMenuRegistry:So(r),manifest:l,validation:Po({editorRuntimePlugins:r,canvasRenderPlugins:s,knownHostActionIds:n,rendererRegistry:h,resolvedFeatures:o}),externalPluginIds:c}}function To(e){const t=e.trim();if(!t)return null;const n=(e=>/^[a-z][a-z0-9+.-]*:/i.test(e))(t)?t:`https://${t}`;return Eo(n)?n:null}function Eo(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol||"mailto:"===t.protocol}catch{return!1}}function Bo(e){Eo(e)&&window.open(e,"_blank","noopener,noreferrer")}function Mo(e){return{type:"doc",content:e.split("\n").map(e=>({type:"paragraph",content:e.length>0?[{type:"text",text:e}]:[]}))}}function Ro(e){return e.content.map(e=>Do(e)).join("\n")}function Ao(e){if(!e||"object"!=typeof e)return Mo("");const t=e,n=Array.isArray(t.content)?t.content.map(e=>No(e,0)).filter(e=>null!==e):[];return{type:"doc",attrs:Wo(t.attrs),content:n}}function Lo(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>_o(e)).join("")??"";return`<p style="margin:0">${t.length>0?t:"<br>"}</p>`})(e)).join("")}function Fo(e){return"text"===e.type&&"string"==typeof e.text}function $o(e){if(!e||0===e.length)return;const t={};for(const n of e)switch(n.type){case"bold":case"strong":t.fontWeight=700;break;case"italic":case"em":t.fontStyle="italic";break;case"strike":case"s":t.textDecorationLine="line-through"}return Object.keys(t).length>0?t:void 0}function Uo(e){if(e&&0!==e.length)for(const t of e){if("link"!==t.type)continue;const e=t.attrs?.href;return"string"==typeof e?e:void 0}}function Do(e){return Fo(e)?e.text:e.content?.map(e=>Do(e)).join("")??""}function zo(e){const t=[];return void 0!==e.fontWeight&&t.push(`font-weight:${String(e.fontWeight)}`),void 0!==e.fontStyle&&t.push(`font-style:${e.fontStyle}`),void 0!==e.textDecorationLine&&t.push(`text-decoration-line:${e.textDecorationLine}`),t.join(";")}function _o(e){if(Fo(e)){const n=$o(e.marks),i=Uo(e.marks),o=Ho(e.text),r=n?`<span style="${zo(n)}">${o}</span>`:o;return i&&Eo(i)?`<a href="${t=i,Ho(t).replaceAll('"',""")}" target="_blank" rel="noopener noreferrer">${r}</a>`:n?r:o}var t;return e.content?.map(e=>_o(e)).join("")??""}function Ho(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function No(e,t){if(!e||"object"!=typeof e)return null;const n=e,i="string"==typeof n.type?n.type:"paragraph",o=Array.isArray(n.content)?n.content.map(e=>function(e,t){if(!e||"object"!=typeof e||t>8)return null;const n=e;if("text"===n.type){const e=(e=>({type:"text",text:"string"==typeof e.text?e.text:"",marks:Array.isArray(e.marks)?e.marks.map(Oo).filter(e=>null!==e):void 0}))(n);return e.text.length>0?e:null}return No(n,t)}(e,t+1)).filter(e=>null!==e):[];return{type:i,attrs:Wo(n.attrs),content:o}}function Oo(e){if(!e||"object"!=typeof e)return null;const t=e;if("string"!=typeof t.type)return null;if("link"===t.type){const e=Wo(t.attrs),n=e?.href;return"string"==typeof n&&Eo(n)?{type:"link",attrs:{...e,href:n}}:null}return{type:t.type,attrs:Wo(t.attrs)}}function Wo(e){if(!e||"object"!=typeof e)return;const t=Object.entries(e).map(([e,t])=>[e,Yo(t)]).filter(e=>void 0!==e[1]);return t.length>0?Object.fromEntries(t):void 0}function Yo(e,t=0){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(!(t>8)){if(Array.isArray(e))return e.map(e=>Yo(e,t+1)).filter(e=>void 0!==e);if(e&&"object"==typeof e){const n=Object.entries(e).map(([e,n])=>[e,Yo(n,t+1)]).filter(e=>void 0!==e[1]);return Object.fromEntries(n)}}}function Xo(e,t){return e.content.map((e,n)=>((e,t,n,i)=>{const o=Ko(e,t,n,i);
|
|
2
|
-
return
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
return
|
|
10
|
-
return
|
|
11
|
-
return
|
|
12
|
-
return
|
|
13
|
-
return
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
return
|
|
17
|
-
return nm("pattern",{id:`land-canvas-grid-${i}`,width:o,height:o,patternUnits:"userSpaceOnUse",children:nm("circle",{cx:r.x,cy:r.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:s})},i)})}),Zy.map(({step:e})=>nm("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function Br(e,t,n){return n?"grabbing":"hand"===e?t?"grabbing":"grab":"select"===e?void 0:"crosshair"}function Mr({canvasComponents:e,canvasProviders:t,domEventGuardRegistry:n,onContextMenuRequest:i,overlayRegistry:o,rendererRegistry:r,showGrid:s=!1}={}){const a=nr(),d=Zf(()=>r??ro(),[r]),l=Zf(()=>o??ao(),[o]),c=Zf(()=>n??co(),[n]),u=ir(a.toolStateSignal).activeToolId,h=ir(a.shapeEditingStateSignal).session,{containerRef:p,handlers:g,isPointerActive:f,isMiddleButtonPanning:m,surfaceCursor:S}=function({activeDomEventGuards:e,activeToolId:t,editor:n,onContextMenuRequest:i,shapeEditingSession:o}){const r=Qf(null),s=Qf(null),a=Qf(null),d=Qf(null),l=Qf(null),c=Qf(null),u=Qf(null),[h,p]=Jf(!1),[g,f]=Jf(!1),[m,S]=Jf(void 0);qf(()=>{("select"!==t||o)&&n.setHoveredShapeId(null)},[t,n,o]);const y=Kf(()=>{null!==l.current&&(cancelAnimationFrame(l.current),l.current=null),c.current=null},[]),b=Kf(e=>{if(null===a.current)return void y();const t=c.current??e;c.current=e,n.dispatch({type:"tick",timestamp:e,elapsed:e-t}),l.current=requestAnimationFrame(b)},[n,y]),x=Kf(()=>{null===l.current&&(c.current=null,l.current=requestAnimationFrame(b))},[b]);return qf(()=>{const i=r.current;if(!i)return;const l=()=>{const e=i.getBoundingClientRect(),t={left:e.left,top:e.top};return s.current=t,t},c=()=>s.current??l(),h=e=>{const r=i.getBoundingClientRect();if(!e||e.x<r.left||e.x>r.right||e.y<r.top||e.y>r.bottom||null!==a.current||"select"!==t||o)return void n.setHoveredShapeId(null);const s=c(),d=new wm(e.x-s.left,e.y-s.top),l=n.hitTestShape(n.screenToPage(d));n.setHoveredShapeId(l?.id??null)},g=(t,o)=>"handled"===e.handle({name:t,event:o,editor:n,container:i}),m=()=>{if(!o)return void S(void 0);const t=u.current;S(t?e.getCursor({clientPoint:t,element:document.elementFromPoint(t.x,t.y),editor:n,container:i}):void 0)},b=(e,t)=>{if(!r.current)return;const i=Cr(t,c());n.dispatch(wr(e,t,i,n.screenToPage(i)))},x=()=>{n.setViewportScreenSize({w:i.clientWidth,h:i.clientHeight})};l(),x();const I=e=>{if(g("key_down",e))return;if(n.getShapeEditingSession())return!xr(e.target)&&n.handleInteractionEvent(Pr("key_down",e))?(e.preventDefault(),void e.stopPropagation()):void(xr(e.target)||"Escape"!==e.key||e.altKey||e.ctrlKey||e.metaKey?xr(e.target)||"Enter"!==e.key||!e.metaKey&&!e.ctrlKey||n.completeEditing("user"):n.cancelEditing("user"));if(xr(e.target))return;const t=n.shortcuts.getTargetForEvent(kr(e));t&&"action"!==t.type&&e.preventDefault(),n.dispatch(Pr("key_down",e))},v=e=>{g("key_up",e)||n.getShapeEditingSession()||xr(e.target)||n.dispatch(Pr("key_up",e))},w=()=>{a.current=null,d.current=null,p(!1),f(!1),n.setHoveredShapeId(null),y(),n.dispatch({type:"cancel",reason:"blur"})},P=e=>{if(g("wheel",e))return;e.preventDefault();const t=Cr(e,c()),i=n.screenToPage(t);n.dispatch(((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new wm(e.deltaX,e.deltaY),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}))(e,t,i))},k=e=>{if(u.current={x:e.clientX,y:e.clientY},h(u.current),m(),e.pointerId!==a.current){const t=Cr(e,c());if(n.inputs.setCurrentPointerPoint({timestamp:e.timeStamp,screenPoint:t,pagePoint:n.screenToPage(t),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}),g("pointer_move",e))return;if(!((e,t)=>{const n=t.getBoundingClientRect();return e.clientX>=n.left&&e.clientX<=n.right&&e.clientY>=n.top&&e.clientY<=n.bottom})(e,i)||xr(e.target))return;return void b("pointer_move",e)}const t={clientX:e.clientX,clientY:e.clientY,buttons:e.buttons,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey};var o,r;r=t,(o=d.current)&&o.clientX===r.clientX&&o.clientY===r.clientY&&o.buttons===r.buttons&&o.shiftKey===r.shiftKey&&o.altKey===r.altKey&&o.ctrlKey===r.ctrlKey&&o.metaKey===r.metaKey||(d.current=t,b("pointer_move",e))},C=(e,t)=>{t.pointerId===a.current&&(a.current=null,d.current=null,p(!1),f(!1),y(),i.hasPointerCapture(t.pointerId)&&i.releasePointerCapture(t.pointerId),b(e,t),"pointer_up"===e?h(u.current):n.setHoveredShapeId(null))},T=()=>{u.current=null,n.setHoveredShapeId(null),m()},E=e=>{u.current={x:e.clientX,y:e.clientY},window.setTimeout(m,0),e.pointerId===a.current?C("pointer_up",e):g("pointer_up",e)},B=e=>{u.current={x:e.clientX,y:e.clientY},m(),e.pointerId===a.current?C("pointer_cancel",e):g("pointer_cancel",e)},M=new ResizeObserver(()=>{l(),x()});window.addEventListener("keydown",I),window.addEventListener("keyup",v),window.addEventListener("blur",w),window.addEventListener("scroll",l,{passive:!0,capture:!0}),window.addEventListener("pointermove",k,{passive:!0}),window.addEventListener("pointerup",E),window.addEventListener("pointercancel",B),i.addEventListener("pointerleave",T),i.addEventListener("wheel",P,{passive:!1}),M.observe(i);const R=window.requestAnimationFrame(m);return()=>{y(),p(!1),f(!1),n.setHoveredShapeId(null),window.cancelAnimationFrame(R),window.removeEventListener("keydown",I),window.removeEventListener("keyup",v),window.removeEventListener("blur",w),window.removeEventListener("scroll",l,!0),window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",E),window.removeEventListener("pointercancel",B),i.removeEventListener("pointerleave",T),i.removeEventListener("wheel",P),M.disconnect()}},[e,t,n,o,y]),{containerRef:r,handlers:{onPointerDown:Kf(t=>{const i=r.current;if(!i)return;if(u.current={x:t.clientX,y:t.clientY},2===t.button)return void i.focus();if("handled"===e.handle({name:"pointer_down",event:t.nativeEvent,editor:n,container:i}))return;if(xr(t.target))return;t.preventDefault(),i.focus(),i.setPointerCapture(t.pointerId);const o=i.getBoundingClientRect();s.current={left:o.left,top:o.top},a.current=t.pointerId,p(!0),f(1===t.button),d.current=null,x();const l=Cr(t,s.current);n.setHoveredShapeId(null),n.dispatch(wr("pointer_down",t,l,n.screenToPage(l)))},[e,n,x]),onAuxClick:Kf(e=>{1!==e.button||xr(e.target)||(e.preventDefault(),e.stopPropagation())},[]),onContextMenu:Kf(e=>{const t=r.current;if(!t||!i||xr(e.target))return;if(e.preventDefault(),e.stopPropagation(),n.getShapeEditingSession())return;t.focus(),null!==a.current&&(t.hasPointerCapture(a.current)&&t.releasePointerCapture(a.current),a.current=null,d.current=null,p(!1),f(!1),y(),n.dispatch({type:"cancel",reason:"pointer_cancel"}));const o=t.getBoundingClientRect();s.current={left:o.left,top:o.top};const l=Cr(e,s.current),c=n.screenToPage(l),u=n.hitTestShape(c);let h;if(u){const e=n.getSelectedShapeIds(),t=e.includes(u.id);t||n.commands.setSelectedShapeIds([u.id],{source:"user"}),h={anchor:{screenPoint:l,pagePoint:c},target:{type:"selection",selectedShapeIds:t?e:[u.id]}}}else h={anchor:{screenPoint:l,pagePoint:c},target:{type:"canvas"}};i(h)},[n,i,y])},isPointerActive:h,isMiddleButtonPanning:g,surfaceCursor:m}}({activeDomEventGuards:c,activeToolId:u,editor:a,onContextMenuRequest:i,shapeEditingSession:h});
|
|
18
|
-
return
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
nm(as,{children:"Text"}),
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
return nm("button",{type:"button","aria-label":n,"aria-pressed":a,title:`${n} (${i})`,disabled:d,"data-ui":o,onPointerDown:e=>{e.preventDefault(),e.stopPropagation(),e.isTrusted&&(l(),s.current=!0)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation(),s.current?s.current=!1:l()},style:{...ub,background:a?"var(--accent)":"transparent",color:a?"var(--accent-foreground)":"var(--muted-foreground)",cursor:d?"not-allowed":"pointer",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:"var(--toolbar-button-font-size)",fontStyle:"italic"===t?"italic":void 0,fontWeight:"bold"===t?700:600,lineHeight:1,opacity:d?.45:1,pointerEvents:"auto",textDecoration:"strike"===t?"line-through":void 0},children:r})}function rs({editor:e,onEdit:t}){const n=Qf(!1),i=e.isActive("link"),o=e.isDestroyed||void 0===e.schema.marks.link,r=()=>{o||t()};
|
|
27
|
-
return nm("button",{type:"button","aria-label":"Link","aria-pressed":i,title:"Link",disabled:o,"data-ui":"text-link-button",onPointerDown:e=>{e.preventDefault(),e.stopPropagation(),r(),n.current=!0},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation(),n.current?n.current=!1:r()},style:{...ub,background:i?"var(--accent)":"transparent",color:i?"var(--accent-foreground)":"var(--muted-foreground)",cursor:o?"not-allowed":"pointer",opacity:o?.45:1},children:nm(py,{size:14,strokeWidth:2})})}function ss({editor:e,onDone:t}){const[n,i]=Jf((e=>{const t=e.getAttributes("link").href;return"string"==typeof t?t:void 0})(e)??""),[o,r]=Jf(!1);
|
|
28
|
-
return
|
|
29
|
-
nm(as,{children:"Link"}),
|
|
30
|
-
nm(ds,{}),
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
return
|
|
35
|
-
return
|
|
36
|
-
return
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
nm("div",{"data-ui":"text-editor-host-slot","data-shape-id":e.id,"data-active":a?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:d}),n?nm("div",{"aria-hidden":"true","data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 2px ${ny}`,inset:0,pointerEvents:"none",position:"absolute"}}):null]})}function bs(e,t,n){if(!e||0===t.length)return e??[];const[i,...o]=t;return e.map((e,t)=>t!==i?e:o.length>0?{...e,content:bs(e.content,o,n)}:{...e,marks:xs(e.marks,n)})}function xs(e,t){const n=e?.filter(e=>"link"!==e.type)??[];return t?[...n,{type:"link",attrs:{href:t,target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}}]:n.length>0?n:void 0}function Is(e){return Lr(e)}function vs(e,t,n){const i=e.getBindingsToShape(t).find(e=>e.type===n);if(!i)return null;const o=e.getShape(i.fromId);return Ar(o)?o:null}function ws(e,t){const n=Fr(e);e.history.mark(t.historyMarkId);const i=$r(e,{x:t.layout.x,y:t.layout.y,parentId:t.owner.parentId,index:t.index,rotation:t.layout.rotation,props:{...n,...t.layout.props,autoSize:!1,textAlign:"middle"}},"user");return e.commands.createBinding({type:t.bindingType,fromId:i.id,toId:t.owner.id,props:t.bindingProps},{source:"user"}),i}function Ps(e,t){const n=e.getShape(t);if(!Ar(n))return null;const i=e.getBindingsFromShape(t).find(e=>e.type in wb);if(!i)return null;const o=i.type;return{label:n,ownerId:i.toId,bindingType:o,behavior:wb[o]}}function ks(e,t,n){e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:n.isExisting?n.editMarkId:n.createMarkId,reuseExistingMark:!n.isExisting},"user")}function Cs(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ts(e){return Math.max(.01,e.props.scale)}function Es(e){return e.props.w*Ts(e)}function Bs(e){return e.props.h*Ts(e)}function Ms(e){return new Pm(0,0,Es(e),Bs(e))}function Rs(e){return"left"===e||"right"===e}function As(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>Ls(e))??[];return{tag:"p",attrs:{style:"margin:0"},children:t.length>0?t:[{tag:"br"}]}})(e))}function Ls(e){if(Fo(e)){const t=(e=>{const t=$o(e.marks);return t?zo(t):void 0})(e);return t?{tag:"span",attrs:{style:t},children:[e.text]}:e.text}return{tag:"span",children:e.content?.map(e=>Ls(e))??[]}}function Fs(e,t,n){return[`color:${t.resolveColor(e.props.color)}`,`font-family:${Nr(e.props.font,n)}`,`font-size:${Or(e.props.size)}px`,`line-height:${Wr(e.props.size)}px`,`text-align:${Xr(e.props.textAlign)}`,"white-space:pre-wrap","overflow-wrap:break-word","box-sizing:border-box",`width:${e.props.w}px`,`height:${e.props.h}px`,`transform:scale(${e.props.scale})`,"transform-origin:top left"].join(";")}function $s(e){return"shape"===e?.typeName&&"arrow"===e.type}function Us(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Ds(e,t,n){const i=e.computeShapePageCenter(n),o=((e,t)=>e.getShapeUtil(t).getSelectionOverlayInfo(t,{editor:e}).middlePagePoint?.clone()??null)(e,n)??(e=>{const t=e.props,n=zs(t.start),i=zs(t.end),o=_s(t.bend)??0;if(!n||!i)return null;const r=wm.Med(n,i).add(i.sub(n).len()?i.sub(n).per().normalize().mul(-o):new wm(0,o)),s=new wm(e.x+(e=>_s(e.props.w)??1)(e)/2,e.y+(e=>_s(e.props.h)??1)(e)/2),a=new wm(e.x+r.x,e.y+r.y);if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return a;const d=a.sub(s);return s.add(new wm(d.x*e.scaleX,d.y*e.scaleY).rot(e.rotation))})(n)??i,r=Math.max(24,120);return{x:o.x-r*t.props.scale/2,y:o.y-t.props.h*t.props.scale/2,rotation:n.rotation,props:{w:r}}}function zs(e){if(!e||"object"!=typeof e)return null;const t=e;return"number"==typeof t.x&&Number.isFinite(t.x)&&"number"==typeof t.y&&Number.isFinite(t.y)?new wm(t.x,t.y):null}function _s(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function Hs(e){return"shape"===e?.typeName&&"geo"===e.type}function Ns(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Os(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Ws(e,t){const n=e.props[t];return"number"==typeof n&&Number.isFinite(n)?n:null}function Ys(e,t){const n=Ws(e,"h");return!n||t.props.ownerBaseHeight<=0||n===t.props.ownerBaseHeight?null:{...e,props:{...e.props,h:t.props.ownerBaseHeight}}}function Xs(e,t,n){const i=e.computeShapeLocalBounds(n),o=e.computeShapePageCenter(n),r=Math.max(16,i.w-32);return{x:o.x-r*t.props.scale/2,y:o.y-t.props.h*t.props.scale/2,rotation:n.rotation,props:{w:r}}}function Ks(){let e=null;const t=()=>{e=null};return{id:"land.text.interactions",editorEvent:{handleEvent(n,i){if("select"!==n.getActiveToolId())return"continue";if("pointer"===i.type&&"pointer_up"===i.name)return((e,t,n,i)=>{if(!n||n.pointerId!==t.pointerId)return i(),"continue";if(i(),(t.clickCount??1)>=2)return"continue";const o=t.pagePoint.x-n.originPagePoint.x,r=t.pagePoint.y-n.originPagePoint.y;if(o*o+r*r>9)return"continue";const s=e.getShape(n.shapeId);return s&&Ar(s)&&e.canEditShape(s)?(e.startEditingShape({shapeId:s.id,entryMode:"placeCaret",caretPagePoint:t.pagePoint,markId:Rb,preserveInteraction:!0},"user"),"continue"):"continue"})(n,i,e,()=>{e=null});if("pointer"===i.type&&"pointer_cancel"===i.name)return t(),"continue";if(!n.isActiveToolInInitialState())return"continue";if("keyboard"===i.type&&"key_down"===i.name){if(n.getShapeEditingSession())return"continue";if("Enter"!==i.key||i.altKey||i.accelKey)return"continue";const e=n.getSelectedShapeIds(),[t]=n.getSelectedShapes();return 1===e.length&&t&&Ar(t)&&n.canEditShape(t)?(n.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:Rb},"user"),"handled"):"continue"}return"click"===i.type&&"double_click"===i.name?(t(),((e,t)=>{const n=e.hitTestShape(t.pagePoint);return n?Ar(n)?e.canEditShape(n)?(e.startEditingShape({shapeId:n.id,entryMode:"selectAll",markId:Rb},"user"),"handled"):"continue":"geo"===n.type?((e,t)=>{if(t.isLocked)return"continue";const n=vs(e,t.id,vb);return ks(e,n??((e,t)=>{const n=Xs(e,Vs(t,{...Fr(e),autoSize:!1,textAlign:"middle"}),t);return ws(e,{bindingType:vb,owner:t,historyMarkId:$b,index:`${t.index}${Bb}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})})(e,t),{editMarkId:Fb,createMarkId:$b,isExisting:!!n}),"handled"})(e,n):(e=>"arrow"===e.type)(n)?((e,t)=>{if(t.isLocked)return"continue";const n=vs(e,t.id,Ib);return ks(e,n??((e,t)=>{const n=Ds(e,Vs(t,{...Fr(e),autoSize:!1,textAlign:"middle"}),t);return ws(e,{bindingType:Ib,owner:t,historyMarkId:Lb,index:`${t.index}${Tb}`,layout:n,bindingProps:{labelPosition:.5}})})(e,t),{editMarkId:Ab,createMarkId:Lb,isExisting:!!n}),"handled"})(e,n):"continue":"continue"})(n,i)):"pointer"===i.type&&"pointer_down"===i.name?(t(),((t,n)=>{const i=t.hitTestShape(n.pagePoint);if(!i||!Ar(i)||!t.canEditShape(i))return"continue";const o=t.getShapeEditingSession();return o&&o.shapeId!==i.id?t.completeEditing("user")?(t.startEditingShape({shapeId:i.id,entryMode:"placeCaret",caretPagePoint:n.pagePoint,markId:Rb,preserveInteraction:!0},"user"),"handled"):"handled":(!o&&(n.clickCount??1)<2&&((e,t)=>{const n=e.getSelectedShapeIds();if(1!==n.length)return!1;if(n[0]===t)return!0;const i=Ps(e,t);return!!i&&i.behavior.canPlaceCaretWhenOwnerSelected&&n[0]===i.ownerId})(t,i.id)&&(e={pointerId:n.pointerId,shapeId:i.id,originPagePoint:{x:n.pagePoint.x,y:n.pagePoint.y}}),"continue")})(n,i)):"continue"}}}}function Vs(e,t){return{id:"shape:draft",typeName:"shape",scope:"document",type:"text",parentId:e.parentId,index:`${e.index}.label`,x:0,y:0,rotation:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:t}}function qs({fontCatalog:e=jo()}={}){return{id:"land.text",shapeCapabilities:[{type:"text",schemaProps:["richText","w","h","autoSize","scale","font","size","color","textAlign"],reactRenderer:"partial",toolbarEntry:"supported",notes:["Text shape util, SVG fallback, React renderer, rich editing runtime, creation tool, and selected-text style toolbar live in the text plugin package. React rendering remains partial while product-grade rich text rendering and measurement continue to mature."]}],shapeUtils:[new kb],shapeSvgExporters:[new Cb(e)],bindingUtils:[new Mb,new Eb],interactionHandlers:[Ks()],canvasActions:[{id:"text.edit",isVisible:e=>1===e.selection.count&&"text"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return"text"===t?.type&&!t.isLocked},run({context:e}){const[t]=e.selection.selectedShapes;"text"!==t?.type||t.isLocked||e.editor.startEditingShape({shapeId:t.id,entryMode:"focusEnd"},"user")}},Qs("color",e),Qs("font",e),Qs("size",e),Qs("textAlign",e),Js("color",e),Js("font",e),Js("size",e),Js("textAlign",e)],toolbarContributions:[{id:"text.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[YS],getGroups:e=>[{id:"text.tools",items:[{kind:"button",id:"text.tool.text",actionId:YS,value:"text",label:"Text",shortcut:e.editor.shortcuts.getToolShortcutLabel("text"),icon:"type",dataUi:"text-tool-button"}]}]},Gs(e),js(e)],contextMenuContributions:[{id:"text.shape-context-menu",target:"selection",order:35,actionIds:["text.edit"],when:e=>1===e.selection.count&&"text"===e.selection.singleShapeType,getSections:()=>[{id:"text.context-menu",title:"Text",items:[{kind:"command",id:"text.edit",actionId:"text.edit",label:"Edit text",icon:"type",dataUi:"context-menu-edit-text-button"}]}]}],setup(e){e.tools.register("text",e=>new yb(e),{shortcut:"t"})}}}function js(e){return{id:"text.selection-toolbar",surface:"selection",order:20,actionIds:["text.set-color","text.set-font","text.set-size","text.set-textAlign"],when:e=>"text"===e.selection.commonShapeType,getGroups:()=>Zs({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"})}}function Gs(e){return{id:"text.default-style.tool-toolbar",surface:"tool",order:51,actionIds:["text.default-color","text.default-font","text.default-size","text.default-textAlign"],when:e=>"text"===e.tool.activeToolId,getGroups:()=>Zs({colorActionId:"text.default-color",fontActionId:"text.default-font",fontCatalog:e,sizeActionId:"text.default-size",textAlignActionId:"text.default-textAlign",dataUiPrefix:"text-default"})}}function Zs({colorActionId:e,fontActionId:t,fontCatalog:n,sizeActionId:i,textAlignActionId:o,dataUiPrefix:r}){return[{id:`${r}.style-color`,items:[{kind:"swatches",id:`${r}.color`,actionId:e,label:"Color",options:Ub.map(e=>({...e,dataUi:`${r}-color-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-font`,items:[{kind:"segmented",id:`${r}.font`,actionId:t,options:n.fontOptions.map(e=>({value:e.id,label:e.label,dataUi:`${r}-font-${e.id}-button`}))}]},{id:`${r}.style-size`,items:[{kind:"stepper",id:`${r}.size`,actionId:i,label:"Size",options:Db.map(e=>({value:e.value,label:e.label,dataUi:`${r}-size-${e.id}-button`}))}]},{id:`${r}.style-align`,items:[{kind:"segmented",id:`${r}.align`,actionId:o,options:zb.map(e=>({...e,dataUi:`${r}-align-${e.value}-button`}))}]}]}function Qs(e,t){return{id:`text.set-${e}`,isVisible:e=>"text"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:t=>((e,t)=>{let n;for(const i of e){if("text"!==i.type)continue;const e=i.props[t];if(void 0!==n){if("color"===t?!E(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:n,value:i}){const o=ea(e,i,t);if(void 0===o)return;const r=n.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:o}}));0!==r.length&&n.editor.commands.updateShapes(r,{source:"user"})}}}function Js(e,t){return{id:`text.default-${e}`,isVisible:e=>"text"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("text")[e],run({context:n,value:i}){const o=ea(e,i,t);void 0!==o&&n.editor.updateDefaultShapeProps("text",{[e]:o})}}}function ea(e,t,n){if("color"===e)return v(t)?P(t,y("text-slate")):void 0;if("font"===e){if("string"!=typeof t)return;return((e,t)=>"default"===t||Zo(t)&&e.fontsById.has(t))(n,t)?t:void 0}if("size"===e){if("number"!=typeof t||!Number.isFinite(t))return;return Db.some(e=>e.value===t)?t:void 0}return"string"==typeof t&&zb.some(e=>e.value===t)?t:void 0}function ta({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){
|
|
40
|
-
return nm("div",{"data-ui":n,className:na("land-canvas__floating-toolbar-layer",t),children:e})}function na(...e){return e.filter(Boolean).join(" ")}function ia(e){qf(()=>{const t=e.current;if(!t)return;const n=e=>{(e=>e.scrollHeight>e.clientHeight)(t)||vr(e,t)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",n,{passive:!1}),()=>{t.removeEventListener("wheel",n)}},[e])}function oa({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",offset:i=8,surfaces:o}){const r=o.floatingSelectionToolbarPageAnchor;return o.showFloatingSelectionToolbar&&r?nm(ra,{anchor:r,className:t,dataUi:n,editor:o.context.editor,offset:i,children:e}):null}function ra({anchor:e,children:t,className:n,dataUi:i,editor:o,offset:r}){const s=Qf(null);return ia(s),Gf(()=>oo("PageAnchoredChromeSurface.scale",o.cameraZoomSignal,()=>{const e=s.current;if(!e)return;const t=o.cameraZoomSignal.get();e.style.transform=`scale(${1/t}) translateY(calc(-100% - ${r}px))`}),[o,r]),nm(or,{dataUi:`${i}-page-space`,className:sa("land-canvas__floating-selection-page-space",n),children:nm("div",{ref:s,"data-ui":i,className:"land-canvas__floating-selection-anchor",style:{left:e.x,top:e.y,transformOrigin:"0 0",willChange:"transform"},children:t})})}function sa(...e){return e.filter(Boolean).join(" ")}function aa(e,t={}){const n=t.enabled??!0,i=t.pageId,o=Kf(t=>n?e.subscribe(t):()=>{},[n,e]),r=Kf(()=>n?e.getSnapshot(i):Hb,[n,i,e]);return em(o,r,r)}function da(e){return Math.max(0,Math.min(1,e))}function la(e,t,n){const i=e.getShapeUtil(t);return Qe(t,((e,t,n)=>{const i=e.computeShapeBounds(t);return new wm(i.minX+i.w*n.x,i.minY+i.h*n.y)})(e,t,n),i)}function ca(e,t,n,i){return((e,t,n,i)=>e.getShapeUtil(t).resolveBindingPoint(t,{rawPagePoint:n,oppositePagePoint:i}))(e,t,la(e,t,n),i)}function ua(e,t){const n="start"===t?e.props.start:e.props.end;return((e,t)=>{if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return t;const n=new wm(e.x+e.props.w/2,e.y+e.props.h/2),i=t.sub(n);return n.add(new wm(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))})(e,new wm(e.x+n.x,e.y+n.y))}function ha(e){return"start"===e?"end":"start"}function pa(e,t,n){const i=((e,t)=>{const n=Sa(e.x,t.x),i=Sa(e.y,t.y);return{x:n.origin,y:i.origin,w:n.size,h:i.size,start:{x:n.startOffset,y:i.startOffset},end:{x:n.endOffset,y:i.endOffset}}})(t,n);return{...e,x:i.x,y:i.y,rotation:0,scaleX:1,scaleY:1,props:{...e.props,w:i.w,h:i.h,start:i.start,end:i.end,bend:e.props.bend}}}function ga(e,t,n){return pa(e,"start"===t?n:ua(e,"start"),"end"===t?n:ua(e,"end"))}function fa(e){return ba(new wm(e.props.start.x,e.props.start.y).add(new wm(e.x,e.y)),new wm(e.props.end.x,e.props.end.y).add(new wm(e.x,e.y)),e.props.bend)}function ma(e,t,n){const i=wm.Med(e,t),o=t.sub(e);if(o.len()<1e-6)return 0;const r=o.per().normalize();return-Ba(n.sub(i),r)}function Sa(e,t){const n=Math.min(e,t),i=Math.max(e,t);return Math.abs(i-n)<1e-6?{origin:n-.5,size:1,startOffset:.5,endOffset:.5}:{origin:n,size:i-n,startOffset:e-n,endOffset:t-n}}function ya(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function ba(e,t,n){const i=function(e,t=0){return((e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t)(e,t)}(n,0),o=((e,t,n)=>{const i=wm.Med(e,t),o=t.sub(e),r=o.len()?o.per().normalize():new wm(0,-1);return i.add(r.mul(-n))})(e,t,i),r=((e,t,n)=>{const i=((e,t,n)=>{const i=-2*(e.x*(t.y-n.y)-e.y*(t.x-n.x)+t.x*n.y-n.x*t.y);if(Math.abs(i)<1e-6)return null;const o=((e.x*e.x+e.y*e.y)*(n.y-t.y)+(t.x*t.x+t.y*t.y)*(e.y-n.y)+(n.x*n.x+n.y*n.y)*(t.y-e.y))/i,r=((e.x*e.x+e.y*e.y)*(t.x-n.x)+(t.x*t.x+t.y*t.y)*(n.x-e.x)+(n.x*n.x+n.y*n.y)*(e.x-t.x))/i;return Number.isFinite(o)&&Number.isFinite(r)?new wm(o,r):null})(e,t,n);if(!i)return null;const o=i.dist(e);if(o<1e-6)return null;const r=((l=n).x-(a=e).x)*((d=t).y-a.y)-(d.x-a.x)*(l.y-a.y)<0?1:0,s=((e,t,n)=>{const i=e.dist(n),o=n.dist(t),r=t.dist(e);return o<1e-6||r<1e-6?0:2*Math.acos(Math.max(-1,Math.min(1,(o*o+r*r-i*i)/(2*o*r))))})(e,t,n);var a,d,l;if(!Number.isFinite(s))return null;const c=Math.PI>s?1:0,u=(Nb-s)*(r?1:-1);return{center:i,radius:o,largeArcFlag:c,sweepFlag:r,size:u,length:Math.abs(u*o)}})(e,o,t),s=Math.abs(i)<1e-6||null===r||0===r.length||!Number.isFinite(r.length)||!Number.isFinite(r.radius),a=s?[e,t]:Ia(e,t,r,24),d=s||null===r?`M ${ya(e.x)} ${ya(e.y)} L ${ya(t.x)} ${ya(t.y)}`:`M ${ya(e.x)} ${ya(e.y)} A ${ya(r.radius)} ${ya(r.radius)} 0 ${r.largeArcFlag} ${r.sweepFlag} ${ya(t.x)} ${ya(t.y)}`,l={start:{terminal:"start",point:e,handle:e},end:{terminal:"end",point:t,handle:t},middle:o,bend:i,points:a,bounds:Pm.FromPoints(a),path:d};return s?{type:"straight",...l,arc:null}:{type:"curved",...l,arc:r}}function xa({start:e,end:t,middle:n,bend:i,arc:o,startHandle:r=e,endHandle:s=t}){const a=va(e,t,o);if(Math.abs(a)<1e-6||!Number.isFinite(a)||!Number.isFinite(o.radius)||o.radius<1e-6){const o=ba(e,t,0);return{...o,start:{...o.start,handle:r},end:{...o.end,handle:s},middle:n,bend:i}}const d={center:o.center,radius:o.radius,largeArcFlag:Math.abs(a)>Math.PI?1:0,sweepFlag:o.sweepFlag,size:a,length:Math.abs(a*o.radius)},l=Ia(e,t,d,24),c=`M ${ya(e.x)} ${ya(e.y)} A ${ya(d.radius)} ${ya(d.radius)} 0 ${d.largeArcFlag} ${d.sweepFlag} ${ya(t.x)} ${ya(t.y)}`;return{type:"curved",start:{terminal:"start",point:e,handle:r},end:{terminal:"end",point:t,handle:s},middle:n,arc:d,bend:i,points:l,bounds:Pm.FromPoints(l),path:c}}function Ia(e,t,n,i){const o=[],r=wm.Angle(n.center,e),s=va(e,t,n);for(let a=0;a<=i;a++)o.push(Ca(n.center,n.radius,r+s*(a/i)));return o}function va(e,t,n){return i=wm.Angle(n.center,e),o=wm.Angle(n.center,t),n.sweepFlag?((o-i)%Nb+Nb)%Nb:-((i-o)%Nb+Nb)%Nb;var i,o}function wa(e,t,n,i){const o=wm.Angle(n.center,e),r=va(e,t,n);return Ca(n.center,n.radius,o+r*i)}function Pa({terminal:e,handlePagePoint:t,boundaryPagePoint:n,fullInfo:i}){if(t.dist(n)<1e-6)return null;const o="start"===e?i.arc.sweepFlag:(e=>e?0:1)(i.arc.sweepFlag),r={center:i.arc.center,radius:i.arc.radius,sweepFlag:o};return xa({start:t,end:n,middle:wa(t,n,r,.5),bend:i.bend,arc:r}).path}function ka(e,t,n){const i=((e,t,n)=>{if(e.length<2||n<1e-6)return[];const i=[],o=2===e.length?1:e.length;for(let r=0;r<o;r+=1){const o=e[r],s=e[(r+1)%e.length];if(o&&s)for(const e of Ta(t,n,o,s))i.some(t=>t.dist(e)<1e-6)||i.push(e)}return i})(e,t.arc.center,t.arc.radius);if(0===i.length)return null;const o=Math.abs(va(t.start.handle,t.end.handle,t.arc));if(o<1e-6)return null;const r=i.map(e=>({point:e,measure:Math.abs(va(t.start.handle,e,t.arc))})).filter(({measure:e})=>e>=-1e-6&&e<=o+1e-6);return 0===r.length?null:(r.sort((e,t)=>e.measure-t.measure),"start"===n?r[0]?.point??null:r[r.length-1]?.point??null)}function Ca(e,t,n){return e.add(new wm(Math.cos(n)*t,Math.sin(n)*t))}function Ta(e,t,n,i){const o=i.sub(n),r=n.sub(e),s=o.len2();if(s<1e-6)return[];const a=2*Ba(r,o),d=a*a-4*s*(r.len2()-t*t);if(d<-1e-6)return[];const l=Math.sqrt(Math.max(0,d));return[(-a-l)/(2*s),(-a+l)/(2*s)].filter(e=>e>=-1e-6&&e<=1.000001).map(e=>n.add(o.mul(Math.max(0,Math.min(1,e)))))}function Ea(e,t,n){const i=n.sub(t),o=i.x*i.x+i.y*i.y;if(0===o)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,Ba(r,i)/o)),a=t.add(i.mul(s));return e.dist(a)}function Ba(e,t){return e.x*t.x+e.y*t.y}function Ma(e){return!!e&&"shape"===e.typeName&&"arrow"===e.type}function Ra(e){return!!e&&"binding"===e.typeName&&"arrow"===e.type}function Aa(e,t,n){const i=ua(t,n),o=((e,t,n)=>e.getBindingsFromShape(t.id).find(e=>Ra(e)&&e.props.terminal===n)??null)(e,t,n);if(!o)return{terminal:n,binding:null,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0};const r=e.getShape(o.toId);return!r||Ma(r)?{terminal:n,binding:o,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0}:{terminal:n,binding:o,target:r,handlePagePoint:la(e,r,o.props.normalizedAnchor),boundaryPagePoint:i,isArcBoundaryPoint:!1}}function La(e,t){const n=Aa(e,t,"start"),i=Aa(e,t,"end"),o=ba(n.handlePagePoint,i.handlePagePoint,t.props.bend);return"curved"===o.type&&(Ua(e,n,o,"start"),Ua(e,i,o,"end")),{info:"curved"!==o.type||!n.isArcBoundaryPoint&&n.binding||!i.isArcBoundaryPoint&&i.binding?$a(ba(n.boundaryPagePoint,i.boundaryPagePoint,t.props.bend),n.handlePagePoint,i.handlePagePoint):xa({start:n.boundaryPagePoint,end:i.boundaryPagePoint,middle:wa(n.boundaryPagePoint,i.boundaryPagePoint,o.arc,.5),bend:t.props.bend,arc:o.arc,startHandle:n.handlePagePoint,endHandle:i.handlePagePoint}),fullInfo:o,bindingSegments:[Da(n,o),Da(i,o)].filter(e=>null!==e)}}function Fa(e,t){return((e,t)=>{const n=e.start.point.add(t),i=e.end.point.add(t),o=e.middle.add(t),r=e.start.handle.add(t),s=e.end.handle.add(t);return"curved"===e.type?xa({start:n,end:i,middle:o,bend:e.bend,arc:{center:e.arc.center.add(t),radius:e.arc.radius,sweepFlag:e.arc.sweepFlag},startHandle:r,endHandle:s}):$a(ba(n,i,e.bend),r,s)})(La(e,t).info,new wm(-t.x,-t.y))}function $a(e,t,n){return{...e,start:{...e.start,handle:t},end:{...e.end,handle:n}}}function Ua(e,t,n,i){if(!t.target)return void(t.isArcBoundaryPoint=!0);const o=ka(e.getShapePageOutlineVertices(t.target.id),n,i);o?(t.boundaryPagePoint=o,t.isArcBoundaryPoint=!0):t.isArcBoundaryPoint=!1}function Da(e,t){if(!e.binding)return null;const n=((e,t)=>({terminal:e.terminal,anchorPagePoint:e.handlePagePoint,boundaryPagePoint:e.boundaryPagePoint,guidePath:"curved"===t.type&&e.isArcBoundaryPoint?Pa({terminal:e.terminal,handlePagePoint:e.handlePagePoint,boundaryPagePoint:e.boundaryPagePoint,fullInfo:t}):null}))(e,t);return{terminal:n.terminal,anchorPagePoint:n.anchorPagePoint,boundaryPagePoint:n.boundaryPagePoint,guidePath:n.guidePath}}function za(e,{arrow:t,terminal:n,target:i,anchorPagePoint:o,fallbackBoundaryPagePoint:r}){const s=((e,t,n)=>Aa(e,t,n).handlePagePoint)(e,t,ha(n)),a=ba("start"===n?o:s,"end"===n?o:s,t.props.bend);if("curved"!==a.type)return{terminal:n,anchorPagePoint:o,boundaryPagePoint:r,guidePath:null};const d=ka(e.getShapePageOutlineVertices(i.id),a,n);return d?{terminal:n,anchorPagePoint:o,boundaryPagePoint:d,guidePath:Pa({terminal:n,handlePagePoint:o,boundaryPagePoint:d,fullInfo:a})}:{terminal:n,anchorPagePoint:o,boundaryPagePoint:r,guidePath:null}}function _a(e,t){const n=e.getShapePageBounds(t.id)??e.computeShapePageBounds(t);return n.w*n.h}function Ha(e,t){return e.getShapeUtil(t).canReceiveChildren(t)}function Na(e,t){return!(!t||Ma(t))&&e.getShapeUtil(t).canReceiveTerminalBinding(t,{editor:e})}function Oa(e,t,n){const i=Ha(e,t),o=Ha(e,n);if(i!==o)return i?1:-1;if(i&&o){const i=_a(e,t)-_a(e,n);if(Math.abs(i)>1e-6)return i}return 0}function Wa(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ya(e){if(e)return{shapes:[e]}}function Xa(e,t){const n=e&&"object"==typeof e?e:void 0;return{x:Ka(n?.x,t.x),y:Ka(n?.y,t.y)}}function Ka(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Va(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o));return e.dist(t.add(i.mul(s)))}function qa(e,t,n,i){return((e,t,n,i)=>{const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*o.y-a.y*o.x)/s;return d>=0&&d<=1&&l>=0&&l<=1})(e,t,n,i)?0:Math.min(Va(e,n,i),Va(t,n,i),Va(n,e,t),Va(i,e,t))}function ja(e,t,n="user"){const[i]=e.commands.createShapes([{type:"arrow",x:t.startPagePoint.x,y:t.startPagePoint.y,parentId:t.parentId,props:t.props,meta:t.meta}],{source:n});if(!Ma(i))throw new Error("Failed to create arrow shape");const o=pa(i,t.startPagePoint,t.endPagePoint);e.commands.updateShapes([{id:i.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}),t.startBinding&&e.commands.createBinding({type:"arrow",fromId:o.id,toId:t.startBinding.targetShapeId,props:{terminal:"start",normalizedAnchor:t.startBinding.normalizedAnchor}},{source:n}),t.endBinding&&e.commands.createBinding({type:"arrow",fromId:o.id,toId:t.endBinding.targetShapeId,props:{terminal:"end",normalizedAnchor:t.endBinding.normalizedAnchor}},{source:n});const r=e.getShape(o.id);if(!Ma(r))throw new Error("Failed to create arrow shape");return r}function Ga(e,t,n,i,o="user"){if(!t)return e.setBindingPreview(i.preview),null;let r=null;return r=((e,t,n)=>{const i=e.getShape(t.shapeId);if(!Ma(i))return null;const o=ga(i,t.terminal,t.pagePoint);e.commands.updateShapes([{id:i.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n});const r=e.bindings.getBindingsFromShape(i.id).find(e=>Ra(e)&&e.props.terminal===t.terminal)??null;t.binding?Ra(r)?e.commands.updateBinding({id:r.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n}):(r&&e.commands.deleteBinding(r.id,{source:n}),e.commands.createBinding({type:"arrow",fromId:i.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n})):r&&(e.commands.deleteBinding(r.id,{source:n}),e.commands.updateShapes([{id:i.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}));const s=e.getShape(i.id);return Ma(s)?s:o})(e,{shapeId:t,terminal:n,pagePoint:i.pagePoint,binding:i.binding},o),e.setBindingPreview(i.preview),r}function Za(e,{terminal:t,rawPagePoint:n,oppositePagePoint:i,excludeShapeId:o,ignoreTargets:r=!1}){if(r)return{pagePoint:n.clone(),binding:null,preview:null};const s=function(e,t,n,i){const o=((e,t)=>{let n=null;for(const i of t)(!n||Oa(e,i,n)<0)&&(n=i);return n})(e,e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget",filter:t=>t.id!==i?.excludeShapeId&&Na(e,t)}));if(!o)return null;const r=((e,t,n)=>{const i=Je(t,n,e.getShapeUtil(t)),o=e.computeShapeBounds(t),r=o.h<=1e-6?.5:(i.y-o.minY)/o.h;return{x:da(o.w<=1e-6?.5:(i.x-o.minX)/o.w),y:da(r)}})(e,o,t);return{targetShape:o,normalizedAnchor:r,resolvedPagePoint:ca(e,o,r,n),rawPagePoint:t.clone()}}(e,n,i,{excludeShapeId:o});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:Ja(s),preview:ed(t,s)}}function Qa(e,{arrow:t,terminal:n,rawPagePoint:i,ignoreTargets:o=!1}){const r=Za(e,{terminal:n,rawPagePoint:i,oppositePagePoint:ua(t,ha(n)),excludeShapeId:t.id,ignoreTargets:o});if(!r.preview)return r;const s=((e,{arrow:t,terminal:n,rawPagePoint:i,preview:o})=>{const r=e.getShape(o.targetShapeId);if(!r||Ma(r))return o;const s=za(e,{arrow:t,terminal:n,target:r,anchorPagePoint:i,fallbackBoundaryPagePoint:o.resolvedPagePoint});return{...o,resolvedPagePoint:s.boundaryPagePoint,guidePath:s.guidePath}})(e,{arrow:t,terminal:n,rawPagePoint:i,preview:r.preview});return{...r,pagePoint:s.resolvedPagePoint,preview:s}}function Ja(e){return e?{targetShapeId:e.targetShape.id,normalizedAnchor:e.normalizedAnchor}:null}function ed(e,t){return t?{terminal:e,targetShapeId:t.targetShape.id,rawPagePoint:t.rawPagePoint,resolvedPagePoint:t.resolvedPagePoint}:null}function td(){return{createSession:(e,{handle:t,shape:n})=>Ma(n)?"binding_terminal"===t.kind?(({handle:e,shapeId:t,terminal:n})=>({shapeId:t,historyMark:"select.binding_terminal_drag",handleSnapMode:"point",handleSnapContext:{shapeId:t,handle:e},shouldClearBindingPreviewOnExit:!0,update({editor:e,pagePoint:i,accelKey:o,source:r}){const s=e.getShape(t);if(!Ma(s))return{status:"stop",finalPagePoint:null};const a=Qa(e,{arrow:s,terminal:n,rawPagePoint:i,ignoreTargets:o}),d=Ga(e,s.id,n,a,r);return{status:"continue",finalPagePoint:d?ua(d,n):a.pagePoint}}}))({handle:t,shapeId:n.id,terminal:t.terminal}):"binding_middle"===t.kind?function({shapeId:e}){return{shapeId:e,historyMark:"select.binding_middle_drag",update({editor:t,pagePoint:n,accelKey:i,source:o}){const r=t.getShape(e);if(!Ma(r))return"stop";const s=((e,t)=>({start:Aa(e,t,"start").handlePagePoint,end:Aa(e,t,"end").handlePagePoint}))(t,r),a=(({bend:e,bypassSnap:t,zoom:n})=>t?e:Math.abs(e)*n<=6?0:e)({bend:ma(s.start,s.end,n),bypassSnap:i,zoom:t.cameraZoomSignal.get()});return t.commands.updateShapes([{id:r.id,props:{bend:a}}],{source:o}),"continue"}}}({shapeId:n.id}):null:null}}function nd({strokeActionId:e,strokeWidthActionId:t,headStartActionId:n,headEndActionId:i,dataUiPrefix:o}){return[{id:`${o}.style-stroke`,items:[{kind:"swatches",id:`${o}.stroke`,actionId:e,label:"Stroke",options:jb.map(e=>({...e,dataUi:`${o}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${o}.style-stroke-width`,items:[{kind:"stepper",id:`${o}.stroke-width`,actionId:t,label:"Stroke width",dataUi:`${o}-stroke-width-control`,options:Gb.map(e=>({...e,dataUi:`${o}-stroke-width-${e.value}-button`}))}]},{id:`${o}.head-start`,items:[{kind:"segmented",id:`${o}.head-start`,actionId:n,options:Zb.map(e=>({...e,label:`Start head: ${e.label}`,dataUi:`${o}-start-head-${e.value}-button`}))}]},{id:`${o}.head-end`,items:[{kind:"segmented",id:`${o}.head-end`,actionId:i,options:Zb.map(e=>({...e,label:`End head: ${e.label}`,dataUi:`${o}-end-head-${e.value}-button`}))}]}]}function id(e){return{id:`arrow.set-${e}`,isVisible:e=>"arrow"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:t=>((e,t)=>{let n;for(const i of e){if("arrow"!==i.type)continue;const e=i.props[t];if(void 0!==n){if("stroke"===t?!E(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=rd(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(e=>"arrow"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function od(e){return{id:`arrow.default-${e}`,isVisible:e=>"arrow"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("arrow")[e],run({context:t,value:n}){const i=rd(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("arrow",{[e]:i})}}}function rd(e,t){return"strokeWidth"===e?"number"==typeof t&&Gb.some(e=>e.value===t)?t:void 0:"stroke"===e?v(t)?P(t,y("stroke-slate")):void 0:Zb.some(e=>e.value===t)?t:void 0}function sd(e,t){return{tag:"marker",attrs:{markerWidth:12,markerHeight:12,viewBox:"0 0 24 24",refX:"start"===e?2:22,refY:12,orient:"auto",markerUnits:"strokeWidth"},children:[{tag:"path",attrs:{d:"start"===e?"M8.9,8 L2,12 L8.9,16":"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:t,"stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}}]}}function ad({shape:e,editor:t,isHovered:n,isSelected:i}){const o=e.id.replace(/[^a-zA-Z0-9_-]/g,"-"),r=`arrow-head-start-${o}`,s=`arrow-head-end-${o}`,a=Fa(t,e),d=yo(e.props.stroke,n);
|
|
41
|
-
return im("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,overflow:"visible",children:[im("defs",{children:[nm("marker",{id:r,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"2",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:nm("path",{d:"M8.9,8 L2,12 L8.9,16",fill:"none",stroke:d,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),nm("marker",{id:s,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"22",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:nm("path",{d:"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:d,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),nm("path",{d:a.path,fill:"none",stroke:d,strokeWidth:e.props.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round",markerStart:"arrow"===e.props.headStart?`url(#${r})`:void 0,markerEnd:"arrow"===e.props.headEnd?`url(#${s})`:void 0,opacity:i?.92:1})]})}function dd(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function ld(e,t,n){return Math.max(t,Math.min(n,e))}function cd(e){return e?640:480}function ud(e,t){return e.x===t.x&&e.y===t.y&&e.pressure===t.pressure&&e.segment===t.segment}function hd(e){return new wm(e.x,e.y)}function pd(e){return{x:e.x,y:e.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}}function gd(e){const t=[];for(const n of e)t.push(...n.points.map(pd));return t}function fd(e){if(void 0!==e&&Number.isFinite(e))return ld(e,.05,1)}function md(e,t){const n=[];for(let i=1;i<e.length-1;i+=1){if(t&&Sd(e,i))continue;const o=e[i],r=e[i-1],s=e[i+1];o&&r&&s&&n.push({index:i,score:yd(o,r,s)})}return n.sort((e,t)=>e.score-t.score||e.index-t.index),n}function Sd(e,t){return"straight"===e[t]?.segment||"straight"===e[t+1]?.segment}function yd(e,t,n){const i=((e,t,n)=>{const i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(0===r){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}const s=ld(((e.x-t.x)*i+(e.y-t.y)*o)/r,0,1),a=e.x-(t.x+i*s),d=e.y-(t.y+o*s);return a*a+d*d})(e,t,n),o=((e,t,n)=>{if(void 0===e.pressure)return 0;return 8*Math.abs(e.pressure-((t.pressure??e.pressure)+(n.pressure??e.pressure))/2)})(e,t,n);return i+o*o}function bd(e){if(0===e.length)return null;if(1===e.length){const t=e[0];return`M ${dd(t.x)} ${dd(t.y)}`}if(2===e.length){const t=e[0],n=e[1];return[`M ${dd(t.x)} ${dd(t.y)}`,`L ${dd(n.x)} ${dd(n.y)}`].join(" ")}const t=[],n=e[0];t.push(`M ${dd(n.x)} ${dd(n.y)}`);for(let i=1;i<e.length;i+=1){const n=e[i];if(!n)continue;if("straight"===n.segment){t.push(`L ${dd(n.x)} ${dd(n.y)}`);continue}const o=e[i+1];if(!o||"straight"===o.segment){if(xd(e,i)){const o=e[i-1];t.push(`Q ${dd(o.x)} ${dd(o.y)} ${dd(n.x)} ${dd(n.y)}`)}else t.push(`L ${dd(n.x)} ${dd(n.y)}`);continue}const r=wm.Med(hd(n),hd(o));t.push(`Q ${dd(n.x)} ${dd(n.y)} ${dd(r.x)} ${dd(r.y)}`)}return t.join(" ")}function xd(e,t){return t>=2&&"straight"!==e[t-1]?.segment&&"straight"!==e[t-2]?.segment}function Id(e){if(e.length<3)return(e=>{if(0===e.length)return null;const[t,...n]=e;return t?[`M ${dd(t.x)} ${dd(t.y)}`,...n.map(e=>`L ${dd(e.x)} ${dd(e.y)}`),"Z"].join(" "):null})(e);const t=e[0],n=e[e.length-1];if(!t||!n)return null;const i=wm.Med(n,t),o=[`M ${dd(i.x)} ${dd(i.y)}`];for(let r=0;r<e.length;r+=1){const t=e[r],n=e[(r+1)%e.length];if(!t||!n)continue;const i=wm.Med(t,n);o.push(`Q ${dd(t.x)} ${dd(t.y)} ${dd(i.x)} ${dd(i.y)}`)}return o.push("Z"),o.join(" ")}function vd(e){return e.map(pd)}function wd(e){return e.map(Pd)}function Pd(e){return(e=>({points:e.points.map(pd)}))(e)}function kd(e,t,n){return e.map(e=>({x:e.x+t,y:e.y+n,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}))}function Cd(e,t,n){return e.map(e=>({points:kd(e.points,t,n)}))}function Td(e,t){return e.map((e,n)=>({points:e.points.map((e,i)=>{const o=t(hd(e),n,i);return{x:o.x,y:o.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}})}))}function Ed(e,t,n){const i=0===t.w?1:t.w,o=0===t.h?1:t.h,r=0===n.w?1:n.w,s=0===n.h?1:n.h;return e.map(e=>({x:n.minX+(e.x-t.minX)/i*r,y:n.minY+(e.y-t.minY)/o*s,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}))}function Bd(e,t,n){return e.map(e=>({points:Ed(e.points,t,n)}))}function Md(e){return{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}}function Rd(e,t){const n=Md(t);return Td(e,e=>Bn(e,n))}function Ad(e,t){const n=Md(t);return Td(e,e=>Mn(e,n))}function Ld(e,t){return Td(e,e=>Fn({axis:t.axis,bounds:t.selectionMirrorBounds,point:e}))}function Fd(e,t,n){return Math.max(t,Math.min(n,e))}function $d(e,t,n){return e+(t-e)*n}function Ud(e,t,n){if(e.length<=1)return new wm(1,0);if(n&&e.length>=3){const n=e[t],i=e[(t+1)%e.length],o=n.sub(e[(t-1+e.length)%e.length]).uni(),r=i.sub(n).uni(),s=o.add(r);return s.len2()>1e-6?s.uni():r.len2()>0?r:o.len2()>0?o:new wm(1,0)}const i=e[t],o=e[t+1]??i,r=i.sub(e[t-1]??i).uni(),s=o.sub(i).uni();if(0===t)return s.len2()>0?s:new wm(1,0);if(t===e.length-1)return r.len2()>0?r:new wm(1,0);const a=r.add(s);return a.len2()>1e-6?a.uni():s.len2()>0?s:r.len2()>0?r:new wm(1,0)}function Dd(e,t){return e.x*t.x+e.y*t.y}function zd(e,t,n,i,o={}){if(0===e.length)return[];const r=((e,t)=>{const n=Math.max(e+1,1.6);return{baseRadius:n,minRadius:Math.max(.6,.32*n),minRadiusScale:t?.5:.48,maxRadiusScale:t?1.22:1.24,startTaper:Math.max(1.8*e,2.5),endTaper:Math.max(2.3*e,3.5),simulatePressure:!t}})(t,n),s=e.map(hd),a=[0];let d=0;for(let u=1;u<s.length;u+=1)d+=s[u].dist(s[u-1]),a.push(d);let l=null;const c=e.map((e,n)=>{const c=a[n]??0,u=0===n?0:s[n].dist(s[n-1]),h=function(e,t,n,i,o,r,s,a){if(n.simulatePressure)return(({distanceFromPrevious:e,previousPressure:t,runningLength:n,totalLength:i,strokeWidth:o,isClosed:r})=>{const s=Fd(e/Math.max(1.5*o,1),0,1),a=Fd(1-s,Jb,1),d=null===t?$d(.5,a,.275):$d(t,a,.275*Math.max(s,.36));if(r)return Fd(d,Jb,1);const l=Fd(n/Math.max(1.8*o,1),0,1),c=Fd((i-n)/Math.max(2.6*o,1),0,1);return Fd(d*$d(.72,1,Math.min(l,c)),Jb,1)})({distanceFromPrevious:o,previousPressure:t,runningLength:r,totalLength:s,strokeWidth:i,isClosed:a});const d="number"==typeof e.pressure&&Number.isFinite(e.pressure)?Fd(e.pressure,.05,1):t??.55;return null===t?d:$d(t,d,.68)}(e,l,r,t,u,c,d,i);l=h;const p=o.taperEnd??!0,g=i||s.length<=1?1:Math.min(o.taperStart??1?Fd(c/r.startTaper,0,1):1,p?Fd((d-c)/r.endTaper,0,1):1),f=$d(r.minRadiusScale,r.maxRadiusScale,h),m=Math.max(r.minRadius,r.baseRadius*f*$d(.7,1,g));return{point:s[n],direction:Ud(s,n,i),pressure:h,radius:m,runningLength:c}});return d<.5*r.baseRadius?c.map(e=>({...e,radius:Math.max(e.radius,.92*r.baseRadius)})):c}function _d(e,t){const n=e[e.length-1];n&&n.dist2(t)<.04?e[e.length-1]=t:e.push(t)}function Hd(e,t,n){const i=e.dist(t);if(0===i)return[];const o=wm.Angle(e,t),r=[];for(let s=1;s<n;s+=1){const t=o-Math.PI*(s/n);r.push(new wm(e.x+Math.cos(t)*i,e.y+Math.sin(t)*i))}return r}function Nd(e,t,n){const i=e[e.length-1];!i||i.dist2(t)>n?_d(e,t):e[e.length-1]=t}function Od(e){return{...e}}function Wd(e,t,n){return e.map(e=>new wm(e.x+t,e.y+n))}function Yd(e,t,n){return e.map(e=>Wd(e,t,n))}function Xd({segments:e,outlineVertices:t,outlinePolygons:n,strokeWidth:i,sampling:o,isClosed:r}){const s=gd(e),a=s.map(hd),d=a.length>0?Pm.FromPoints(a):new Pm(0,0,1,1),l=t.length>0?Pm.FromPoints([...t]):d.expand(Math.max(i/2,1)),c=r&&s.length>=3?(e=>{if(e.length<3)return null;const t=bd(e);return t?`${t} Z`:null})(s):null,u=void 0!==n?(e=>{const t=e.map(e=>Id(e)).filter(e=>null!==e);return t.length>0?t.join(" "):null})(n):Id(t);return{normalizedSegments:wd(e),normalizedPoints:vd(s),pointBounds:d,path:u,selectionPath:c??bd(s),fillPath:c,localBounds:l,renderBounds:l.clone(),outlineVertices:t.map(e=>e.clone()),outlinePolygons:n?n.map(e=>e.map(e=>e.clone())):[t.map(e=>e.clone())],sampling:Od(o)}}function Kd(e,t,n,i){const o=(({strokeWidth:e,isPen:t})=>[e,t?"pen":"pointer"].join(":"))({strokeWidth:n,isPen:i}),r=ex.get(e),s=r?.get(o);if(s)return{normalizedSegment:Pd(s.normalizedSegment),sampling:Od(s.sampling)};const a=((e,t)=>{if(e.length<=1)return{points:e.map(pd),rawPointCount:e.length,sampledPointCount:e.length,maxPointCount:t.maxPointCount,reduced:!1,capped:!1};const n=[pd(e[0])],i=t.minPointDistance*t.minPointDistance;let o=hd(e[0]),r=fd(e[0].pressure);for(let d=1;d<e.length;d+=1){const s=e[d];if(!s)continue;const a=hd(s),l=fd(s.pressure),c=d===e.length-1,u="straight"===s.segment,h=c||u?a:wm.Lrp(o,a,t.positionBlend),p=u?l:void 0===l?void 0:void 0===r?l:r+(l-r)*t.pressureBlend;o=h,r=p;const g=void 0===p?{x:h.x,y:h.y,...void 0===s.segment?null:{segment:s.segment}}:{x:h.x,y:h.y,pressure:p,...void 0===s.segment?null:{segment:s.segment}},f=n[n.length-1];if(!f){n.push(g);continue}const m=g.x-f.x,S=g.y-f.y,y=Math.abs((g.pressure??0)-(f.pressure??0));if(m*m+S*S<i){if(u){if(ud(f,g))continue;n.push(g);continue}(y>.08||c)&&(n[n.length-1]=g)}else n.push(g)}const s=n.length>t.maxPointCount,a=function(e,t){const n=Math.max(2,Math.floor(t));if(e.length<=n)return e.map(pd);const i=((e,t)=>{let n=md(e,!0);return n.length<t&&(n=md(e,!1)),new Set(n.slice(0,t).map(e=>e.index))})(e,e.length-n);return e.filter((e,t)=>!i.has(t)).map(pd)}(n,t.maxPointCount);return{points:a,rawPointCount:e.length,sampledPointCount:a.length,maxPointCount:t.maxPointCount,reduced:a.length<e.length,capped:s}})(e.points,t),d={normalizedSegment:{points:vd(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},l=r??new Map;return l.set(o,{normalizedSegment:Pd(d.normalizedSegment),sampling:Od(d.sampling)}),r||ex.set(e,l),d}function Vd(e,t,n=!1,i=!1){const o=((e,t)=>({minPointDistance:t?Math.max(.35,.18*e):Math.max(.55,.28*e),positionBlend:t?.68:.66,pressureBlend:t?.68:.45,maxPointCount:cd(t)}))(t,n),r=[],s=[],a=e.filter(e=>e.points.length>0);for(let h=0;h<a.length;h+=1){const e=Kd(a[h],o,t,n);r.push(Pd(e.normalizedSegment)),s.push(Od(e.sampling))}const d=function(e,t,n={}){if(0===e.length)return[];if(1===e.length)return((e,t)=>{const n=[];for(let i=0;i<16;i+=1){const o=2*Math.PI*i/16;n.push(new wm(e.x+Math.cos(o)*t,e.y+Math.sin(o)*t))}return n})(e[0].point,e[0].radius);const i=[],o=[];let r=.12;for(const l of e)r=Math.max(r,.38*l.radius);const s=r**2;let a=null;for(let l=0;l<e.length;l+=1){const t=e[l],n=t.direction,r=(e[l+1]??t).direction,d=Dd(n,r);let c=0===l||l===e.length-1?n.per().uni():wm.Lrp(r,n,d).per().uni();c.len2()<1e-6&&(c=a??new wm(0,1)),a=c,Nd(i,t.point.add(c.mul(t.radius)),s),Nd(o,t.point.sub(c.mul(t.radius)),s)}if(t&&e.length>=3){const e=[];for(const t of i)_d(e,t);for(let t=o.length-1;t>=0;t-=1)_d(e,o[t]);return e}const d=[];for(const l of i)_d(d,l);if(n.capEnd??1){const t=e[e.length-1];for(const e of Hd(t.point,i[i.length-1],8))_d(d,e)}for(let l=o.length-1;l>=0;l-=1)_d(d,o[l]);if(n.capStart??1){const t=e[0];for(const e of Hd(t.point,o[0],8))_d(d,e)}return d}(zd(gd(r),t,n,i),i),l=(u=o.maxPointCount,{rawPointCount:(c=s).reduce((e,t)=>e+t.rawPointCount,0),sampledPointCount:c.reduce((e,t)=>e+t.sampledPointCount,0),sampledPointLimit:u,reduced:c.some(e=>e.reduced),capped:c.some(e=>e.capped)});var c,u;return Xd({segments:r,outlineVertices:d,outlinePolygons:d.length>0?[d]:[],strokeWidth:t,sampling:l,isClosed:i})}function qd(e){return e.segments}function jd(e,t,n){return((e,t)=>{const n=Math.max(0,e.w-t.left-t.right),i=Math.max(0,e.h-t.top-t.bottom);return new Pm(e.x+t.left,e.y+t.top,n,i)})(n,{left:e.minX-t.minX,right:t.maxX-e.maxX,top:e.minY-t.minY,bottom:t.maxY-e.maxY})}function Gd(e,t){return new wm(e.x+t.localBounds.center.x,e.y+t.localBounds.center.y)}function Zd(e,t,n){if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return t;const i=t.sub(n);return n.add(new wm(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))}function Qd(e){const t=e,n=tx.get(t);if(n)return n;const i=Vd(qd(e.props),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed);return tx.set(t,i),i}function Jd(e,t,n=!1,i=!1){return((e,t,n=!1,i=!1)=>{const o=Vd(e,t,n,i),r=o.pointBounds,s=Vd(Td(o.normalizedSegments,e=>new wm(e.x-r.x,e.y-r.y)),t,n,i);return{x:r.x,y:r.y,segments:s.normalizedSegments,pointBounds:s.pointBounds,localBounds:s.localBounds,renderBounds:s.renderBounds,path:s.path,selectionPath:s.selectionPath,fillPath:s.fillPath,outlineVertices:s.outlineVertices,outlinePolygons:s.outlinePolygons,sampling:s.sampling}})(e,t,n,i)}function el(e){const t=e,n=nx.get(t);if(n)return n;const i=((e,t,n,i,o)=>Xd({segments:Cd(e.normalizedSegments,n,i),outlineVertices:Wd(e.outlineVertices,n,i),outlinePolygons:Yd(e.outlinePolygons,n,i),strokeWidth:t,sampling:e.sampling,isClosed:o}))(Qd(e),e.props.strokeWidth,e.x,e.y,e.props.isClosed);return nx.set(t,i),i}function tl(e){const t=Gd(e,Qd(e));return Td((e=>Cd(qd(e.props),e.x,e.y))(e),n=>Zd(e,n,t))}function nl(e){const t=e,n=ix.get(t);if(n)return n;if(0===e.rotation&&1===e.scaleX&&1===e.scaleY){const n=el(e);return ix.set(t,n),n}const i=Qd(e),o=Gd(e,i),r=Xd({segments:Td(i.normalizedSegments,t=>Zd(e,new wm(t.x+e.x,t.y+e.y),o)),outlineVertices:i.outlineVertices.map(t=>Zd(e,new wm(t.x+e.x,t.y+e.y),o)),outlinePolygons:i.outlinePolygons.map(t=>t.map(t=>Zd(e,new wm(t.x+e.x,t.y+e.y),o))),strokeWidth:e.props.strokeWidth,sampling:i.sampling,isClosed:e.props.isClosed});return ix.set(t,r),r}function il(e){return wd(e)}function ol(e,t,n,i){return{x:e.x-t.x,y:e.y-t.y,...i&&n>0?{pressure:n}:null}}function rl(e){return{x:e.x,y:e.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}}function sl(e){const t=al(e.segments),n=t[t.length-1];return n?n.points.map(rl):[]}function al(e){return e.length>0?[...e]:[{points:[]}]}function dl(e){return{segments:il(al(e))}}function ll(e,t){const n=e.getCurrentPageId();let i=null,o=1/0,r=-1;const s=e.getCurrentPageShapeIds();for(let a=0;a<s.length;a+=1){const n=e.getShape(s[a]);if(!n||e.isShapeHidden(n.id))continue;const d=e.getShapeUtil(n);if(!d.canReceiveChildren(n)||d.isTransformDescendantContainer(n))continue;if(!e.canUseShapeParent(n.id))continue;if(!e.isPagePointInShapeClip(n.id,t))continue;const l=d.getChildClipLocalBounds(n)??d.getLocalBounds(n),c=e.computeShapeLocalToPageTransform(n).invert().applyToPoint(t);if(!l.containsPoint(c))continue;const u=e.computeShapePageBounds(n),h=u.w*u.h;(!i||h<o||h===o&&a>r)&&(i=n,o=h,r=a)}return i?.id??n}function cl(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return e.dist(t);const r=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/o)),s=new wm(t.x+i.x*r,t.y+i.y*r);return e.dist(s)}function ul(e,t,n,i){return((e,t,n,i)=>{const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*o.y-a.y*o.x)/s;return d>=0&&d<=1&&l>=0&&l<=1})(e,t,n,i)?0:Math.min(cl(e,n,i),cl(t,n,i),cl(n,e,t),cl(i,e,t))}function hl(e,t){let n=!1;for(let i=0,o=t.length-1;i<t.length;o=i,i+=1){const r=t[i],s=t[o];r&&s&&r.y>e.y!=s.y>e.y&&e.x<(s.x-r.x)*(e.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n}function pl(e,t){if(0===t.length)return Number.POSITIVE_INFINITY;let n=Number.POSITIVE_INFINITY;for(let i=0;i<t.length;i+=1){const o=t[i],r=t[(i+1)%t.length];o&&r&&(n=Math.min(n,cl(e,o,r)))}return n}function gl(e,t,n,i){if(0===n.length)return!1;if(hl(e,n)||hl(t,n))return!0;for(let o=0;o<n.length;o+=1){const r=n[o],s=n[(o+1)%n.length];if(r&&s&&ul(e,t,r,s)<=i)return!0}return!1}function fl(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function ml(e){if(!e||"object"!=typeof e)return null;const t=e,n=fl(t.x,NaN),i=fl(t.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(i))return null;const o=fl(t.pressure,NaN);return t.x!==n||t.y!==i||void 0!==t.pressure&&t.pressure!==o||void 0!==t.segment&&"straight"!==t.segment?{x:n,y:i,...Number.isFinite(o)?{pressure:o}:null,..."straight"===t.segment?{segment:"straight"}:null}:e}function Sl(e){if(!e||"object"!=typeof e)return null;const t=e,n=((e,t)=>{if(!Array.isArray(e))return t;let n=!1;const i=[];for(const o of e){const e=ml(o);e?(n=n||e!==o,i.push(e)):n=!0}return 0===i.length?t:n?i:e})(t.points,[]);return 0===n.length?null:n===t.points?e:{points:n}}function yl(e,t){if(!Array.isArray(e))return t;let n=!1;const i=[];for(const o of e){const e=Sl(o);e?(n=n||e!==o,i.push(e)):n=!0}return 0===i.length?t:n?i:e}function bl(e){return p(e)&&"draw"===e.type}function xl({closedActionId:e,fillActionId:t,strokeActionId:n,strokeWidthActionId:i,dataUiPrefix:o}){return[{id:`${o}.style-closed`,items:[{kind:"segmented",id:`${o}.closed`,actionId:e,options:px.map(e=>({...e,dataUi:`${o}-${e.value}-button`}))}]},{id:`${o}.style-fill`,items:[{kind:"swatches",id:`${o}.fill`,actionId:t,label:"Fill",options:ux.map(e=>({...e,dataUi:`${o}-fill-${e.label.toLowerCase()}-button`}))}]},{id:`${o}.style-stroke`,items:[{kind:"swatches",id:`${o}.stroke`,actionId:n,label:"Stroke",options:cx.map(e=>({...e,dataUi:`${o}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${o}.style-stroke-width`,items:[{kind:"stepper",id:`${o}.stroke-width`,actionId:i,label:"Stroke width",dataUi:`${o}-stroke-width-control`,options:hx.map(e=>({...e,dataUi:`${o}-stroke-width-${e.value}-button`}))}]}]}function Il(e){return{id:`draw.set-${e}`,isVisible:e=>"draw"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:t=>((e,t)=>{let n;for(const i of e){if("draw"!==i.type)continue;const e=i.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!E(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=kl(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(bl).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function vl(e){return{id:`draw.default-${e}`,isVisible:e=>"draw"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("draw")[e],run({context:t,value:n}){const i=kl(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("draw",{[e]:i})}}}function wl(e){let t;for(const n of e){if("draw"!==n.type)continue;const e=n.props.isClosed;if(void 0!==t){if(t!==e)return null}else t=e}return void 0===t?null:t?"closed":"open"}function Pl(e){return"closed"===e||"open"!==e&&null}function kl(e,t){return"strokeWidth"===e?"number"==typeof t&&hx.some(e=>e.value===t)?t:void 0:v(t)?P(t,"fill"===e?"transparent":y("stroke-slate")):void 0}function Cl({shape:e,isHovered:t=!1,stroke:n=e.props.stroke,strokeWidth:i=e.props.strokeWidth}){const{fillPath:o,renderBounds:r,path:s,selectionPath:a}=Qd({props:{...e.props,strokeWidth:i}});if(!s&&!a)return null;const d=yo(n,t);
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
return
|
|
47
|
-
return
|
|
48
|
-
return nm(Yc,{shape:e,isHovered:t,isSelected:n})}function Yc({shape:e,isHovered:t=!1,isSelected:n=!1}){const{h:i,w:o}=e.props,r=t||n,s=yo("#64748b",t);
|
|
49
|
-
return nm("svg",{width:"100%",height:"100%",viewBox:`0 0 ${o} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:r?nm("rect",{x:.5,y:.5,width:Math.max(o-1,0),height:Math.max(i-1,0),fill:"none",stroke:s,strokeDasharray:"4 4",strokeWidth:1,vectorEffect:"non-scaling-stroke"}):null})}function Xc(e){return Math.min(1,Math.max(0,e))}function Kc(e,t,n){return Math.min(n,Math.max(t,e))}function Vc(e){return!!e&&"object"==typeof e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function qc(e,t){const n=Xc(e),i=Xc(t);let o=Math.min(n,i),r=Math.max(n,i);return r-o<II&&(o=Math.max(0,Math.min(.9999,(o+r)/2-5e-5)),r=o+II),{min:o,max:r}}function jc(e){if(!e||"object"!=typeof e)return null;const t=e;if(!Vc(t.topLeft)||!Vc(t.bottomRight))return null;const n=qc(t.topLeft.x,t.bottomRight.x),i=qc(t.topLeft.y,t.bottomRight.y);return{topLeft:{x:n.min,y:i.min},bottomRight:{x:n.max,y:i.max}}}function Gc(e){const t=jc(e);if(!t)return null;const n=t.topLeft.x,i=t.topLeft.y,o=t.bottomRight.x,r=t.bottomRight.y;return{left:n,top:i,right:o,bottom:r,width:o-n,height:r-i}}function Zc(e){return Gc(e)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function Qc(e,t){return Math.abs(e.left-t.left)<=vI&&Math.abs(e.top-t.top)<=vI&&Math.abs(e.right-t.right)<=vI&&Math.abs(e.bottom-t.bottom)<=vI}function Jc(e){return(e=>Math.abs(e.left)<=vI&&Math.abs(e.top)<=vI&&Math.abs(1-e.right)<=vI&&Math.abs(1-e.bottom)<=vI)(e)?null:jc({topLeft:{x:e.left,y:e.top},bottomRight:{x:e.right,y:e.bottom}})}function eu({centerX:e,centerY:t,height:n,width:i}){const o=Kc(i,II,1),r=Kc(n,II,1),s=Kc(e-o/2,0,1-o),a=Kc(t-r/2,0,1-r);return{left:s,top:a,right:s+o,bottom:a+r,width:o,height:r}}function tu(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function nu({crop:e,shape:t}){const n=Zc(e);return{w:t.props.w/n.width,h:t.props.h/n.height}}function iu(e,t){return t===ou(e.id)}function ou(e){return`${kI}${e}`}function ru({localToPage:e,shape:t}){const n=t.props.w,i=t.props.h,o=(0+n)/2,r=(0+i)/2,s={top_left:new wm(0,0),top:new wm(o,0),top_right:new wm(n,0),right:new wm(n,r),bottom_right:new wm(n,i),bottom:new wm(o,i),bottom_left:new wm(0,i),left:new wm(0,r)};return EI.map(t=>{return{kind:"custom",type:wI,id:t,point:e.applyToPoint(s[t]),cursor:(n=t,TI[n])};var n})}function su({change:e,crop:t,shape:n}){const i=nu({crop:t,shape:n}),o=t.bottomRight.x-t.topLeft.x,r=t.bottomRight.y-t.topLeft.y,s=Kc(t.topLeft.x-e.x/i.w,0,1-o),a=Kc(t.topLeft.y-e.y/i.h,0,1-r),d=jc({topLeft:{x:s,y:a},bottomRight:{x:s+o,y:a+r}});return d?{id:n.id,props:{crop:d}}:null}function au(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function du(e){BI.delete(e)}function lu(e){const t=NI.get(e);if(t)return t;const n=new HI(e);return NI.set(e,n),n}function cu(e){return`${$I}${e}`}function uu(e,t){return t===cu(e.id)}function hu(e){const t="number"==typeof e?.size&&Number.isFinite(e.size)?e.size:DI,n="number"==typeof e?.opacity&&Number.isFinite(e.opacity)?e.opacity:_I??.45;return{size:Math.min(128,Math.max(1,t)),color:"string"==typeof e?.color&&e.color.trim().length>0?e.color:zI,opacity:Math.min(1,Math.max(0,n))}}function pu({brush:e,editor:t,shape:n}){return lu(t).start(n,e)}function gu(e){lu(e).cancel()}function fu(e,t){return lu(e).updateBrush(t)}function mu(e){return lu(e).getActiveSession()}function Su(e,t){lu(e).addPoint(t)}function yu(e){lu(e).endStroke()}async function bu(e,t){return lu(e).requestConfirm(t)}function xu(e){return{x:e.x,y:e.y,...void 0===e.pressure?{}:{pressure:e.pressure}}}function Iu(e){return m(e)&&"image"===e.type}function vu(e){return p(e)&&"image"===e.type}function wu(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return null;const[t]=e.selection.selectedShapes;return vu(t)?t:null}function Pu(e){const t=wu(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!iu(t,n.markId))}function ku(e){const t=wu(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!uu(t,n.markId))}function Cu(){return[{id:fI,isVisible:e=>!!wu(e)&&!Pu(e),isEnabled(e){const t=wu(e);return!!t&&!t.isLocked},getValue:e=>Pu(e),run({context:e}){const t=wu(e);if(!t||t.isLocked)return;const n=e.editor.getShapeEditingSession();n?.shapeId===t.id&&iu(t,n.markId)?e.editor.completeEditing("user"):e.editor.startEditingShape({shapeId:t.id,markId:ou(t.id),entryMode:"focusEnd"},"user")&&(e=>{BI.set(e.id,{...e,props:{...e.props,crop:e.props.crop?{topLeft:{...e.props.crop.topLeft},bottomRight:{...e.props.crop.bottomRight}}:null},meta:{...e.meta}})})(t)}},{id:mI,isVisible:e=>Pu(e),isEnabled:e=>Pu(e),run({context:e}){const t=wu(e);t&&e.editor.completeEditing("user")&&du(t.id)}},{id:SI,isVisible:e=>Pu(e),isEnabled(e){const t=wu(e);return!!t&&!t.isLocked},run({context:e,value:t}){const n=wu(e);if(!n||n.isLocked||-1!==t&&1!==t)return;const i=(({direction:e,shape:t})=>{const n=Zc(t.props.crop),i=tu(n),o=Kc("in"===e?.8:1.25,Math.max(II/n.width,II/n.height),Math.min(1/n.width,1/n.height)),r=eu({centerX:i.x,centerY:i.y,width:n.width*o,height:n.height*o});return Qc(n,r)?null:{id:t.id,props:{crop:Jc(r)}}})({direction:1===t?"in":"out",shape:n});i&&e.editor.commands.updateShapes([i],{source:"user"})}},{id:yI,isVisible:e=>Pu(e),isEnabled(e){const t=wu(e);return!!t&&!t.isLocked},getValue(e){const t=wu(e);return t?(e=>{const t=e.props.w/e.props.h;for(const n of CI)if(Math.abs(t-n.ratio)<=.01)return n.value;return null})(t):null},run({context:e,value:t}){const n=wu(e);if(!n||n.isLocked||"string"!=typeof t)return;const i=CI.find(e=>e.value===t);if(!i)return;const o=function({preset:e,shape:t}){const n=tu(Zc(t.props.crop)),i=nu({crop:t.props.crop,shape:t}),o=CI.find(t=>t.value===e)?.ratio??null;if(!o)return null;const r=o*(i.h/i.w);let s=1,a=s/r;return a>1&&(a=1,s=a*r),(({nextRect:e,shape:t})=>{const n=Zc(t.props.crop);if(Qc(n,e))return null;const i=nu({crop:t.props.crop,shape:t}),o=new wm((e.left-n.left)*i.w,(e.top-n.top)*i.h).rot(t.rotation);return{id:t.id,x:t.x+o.x,y:t.y+o.y,props:{w:e.width*i.w,h:e.height*i.h,crop:Jc(e)}}})({nextRect:eu({centerX:n.x,centerY:n.y,width:s,height:a}),shape:t})}({preset:i.value,shape:n});o&&e.editor.commands.updateShapes([o],{source:"user"})}},{id:bI,isVisible:e=>Pu(e),isEnabled(e){const t=wu(e);return!!t&&!t.isLocked&&!!t.props.crop},run({context:e}){const t=wu(e);if(!t||t.isLocked)return;const n=(({baselineShape:e,shape:t})=>{const n=e.x,i=e.y,o=e.props.w,r=e.props.h,s=jc(e.props.crop);return Math.abs(t.x-n)<=vI&&Math.abs(t.y-i)<=vI&&Math.abs(t.props.w-o)<=vI&&Math.abs(t.props.h-r)<=vI&&(null===t.props.crop&&null===s||null!==t.props.crop&&null!==s&&Math.abs(t.props.crop.topLeft.x-s.topLeft.x)<=vI&&Math.abs(t.props.crop.topLeft.y-s.topLeft.y)<=vI&&Math.abs(t.props.crop.bottomRight.x-s.bottomRight.x)<=vI&&Math.abs(t.props.crop.bottomRight.y-s.bottomRight.y)<=vI)?null:{id:t.id,x:n,y:i,props:{w:o,h:r,crop:s}}})({baselineShape:(i=t.id,BI.get(i)??null??t),shape:t});var i;n&&e.editor.commands.updateShapes([n],{source:"user"})}}]}function Tu(){return{createSession(e,{handle:t,shape:n,originPagePoint:i}){return vu(n)&&"custom"===t.kind&&"image.crop"===t.type&&(o=t.id,EI.some(e=>e===o))?function({handleId:e,shapeId:t,startPagePoint:n,startPageToLocal:i,startShape:o,startCrop:r}){return{shapeId:t,historyMark:"image.crop.handle",update({editor:s,pagePoint:a,source:d}){if(!vu(s.getShape(t)))return"stop";const l=(({handleId:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:o,currentPagePoint:r})=>{const s=jc(i)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=nu({crop:s,shape:n});if(a.w<8||a.h<8)return null;const d=t.applyToPoint(o),l=t.applyToPoint(r).sub(d);if(0===l.x&&0===l.y)return null;const c={x:s.topLeft.x*a.w,y:s.topLeft.y*a.h,w:(s.bottomRight.x-s.topLeft.x)*a.w,h:(s.bottomRight.y-s.topLeft.y)*a.h},u=c.x+c.w,h=c.y+c.h;let p=c.x,g=c.y,f=c.w,m=c.h;(e=>"top_left"===e||"left"===e||"bottom_left"===e)(e)?(p=Kc(p+l.x,0,u-8),f=u-p):(e=>"top_right"===e||"right"===e||"bottom_right"===e)(e)&&(f=Kc(u+l.x,c.x+8,a.w)-p),(e=>"top_left"===e||"top"===e||"top_right"===e)(e)?(g=Kc(g+l.y,0,h-8),m=h-g):(e=>"bottom_left"===e||"bottom"===e||"bottom_right"===e)(e)&&(m=Kc(h+l.y,c.y+8,a.h)-g);const S=jc({topLeft:{x:p/a.w,y:g/a.h},bottomRight:{x:(p+f)/a.w,y:(g+m)/a.h}});if(!S)return null;const y=new wm(p-s.topLeft.x*a.w,g-s.topLeft.y*a.h).rot(n.rotation);return{id:n.id,x:n.x+y.x,y:n.y+y.y,props:{w:f,h:m,crop:S}}})({handleId:e,currentPagePoint:a,pageToLocal:i,shape:o,startCrop:r,startPagePoint:n});return l?(s.commands.updateShapes([l],{source:d}),"continue"):"continue"}}}({handleId:t.id,shapeId:n.id,startPagePoint:i,startPageToLocal:e.computeShapeLocalToPageTransform(n).invert(),startShape:n,startCrop:n.props.crop}):null;var o}}}function Eu(){let e=null;const t=()=>{e=null};return{id:"land.image.crop.interactions",editorEvent:{handleEvent(n,i){if("keyboard"===i.type)return((e,t)=>{if("key_down"!==t.name)return"continue";const n=Bu(e);if(!n)return"continue";if("Escape"===t.key&&!t.altKey&&!t.accelKey)return e.cancelEditing("user")&&du(n.id),"handled";if("Enter"===t.key&&!t.altKey&&!t.accelKey)return e.completeEditing("user")&&du(n.id),"handled";const i=(e=>{if(e.altKey||e.accelKey)return null;const t=e.shiftKey?10:1;switch(e.key){case"ArrowLeft":return new wm(t,0);case"ArrowRight":return new wm(-t,0);case"ArrowUp":return new wm(0,t);case"ArrowDown":return new wm(0,-t);default:return null}})(t);if(i){const t=(({pageDelta:e,shape:t,startCrop:n})=>{const i=jc(n);return!i||e.equals(wm.Zero())?null:su({change:e.rot(-t.rotation),crop:i,shape:t})})({pageDelta:i,shape:n,startCrop:n.props.crop});return t&&e.commands.updateShapes([t],{source:"user"}),"handled"}return"continue"})(n,i);if("pointer"!==i.type)return"continue";if("pointer_cancel"===i.name)return e?.hasDragged&&n.history.bailToMark(PI),t(),"continue";if("pointer_down"===i.name){if(t(),0!==i.button||"select"!==n.getActiveToolId()||!n.isActiveToolInInitialState())return"continue";if(n.hitTestSelectionHandle(i.pagePoint))return"continue";const o=Bu(n);return o?((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n.pagePoint);return i.x>=0&&i.y>=0&&i.x<=t.props.w&&i.y<=t.props.h})(n,o,i)?(e={pointerId:i.pointerId,shapeId:o.id,startCrop:o.props.crop,startPagePoint:i.pagePoint.clone(),startPageToLocal:n.computeShapeLocalToPageTransform(o).invert(),startShape:o,hasDragged:!1},"handled"):n.completeEditing("user")?(du(o.id),n.dispatch(i),"handled"):"continue":"continue"}return e&&i.pointerId===e.pointerId?"pointer_move"===i.name?(Mu(n,i,e),"handled"):"pointer_up"===i.name?(Mu(n,i,e),e.hasDragged&&n.history.squashToMark(PI,"shape.edit"),t(),"handled"):"continue":"continue"}},selectionHandle:Tu()}}function Bu(e){const[t]=e.getSelectedShapes();if(!vu(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&iu(t,n.markId)?t:null}function Mu(e,t,n){if(!n.hasDragged){if(n.startPagePoint.dist2(t.pagePoint)<9)return;e.history.mark(PI),n.hasDragged=!0}if(!vu(e.getShape(n.shapeId)))return;const i=(({currentPagePoint:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:o,shiftKey:r})=>{const s=jc(i);if(!s)return null;const a=t.applyToPoint(o);let d=t.applyToPoint(e).sub(a);return r&&(d=Math.abs(d.x)<Math.abs(d.y)?new wm(0,d.y):new wm(d.x,0)),0===d.x&&0===d.y?null:su({change:d,crop:s,shape:n})})({currentPagePoint:t.pagePoint,pageToLocal:n.startPageToLocal,shape:n.startShape,shiftKey:t.shiftKey,startCrop:n.startCrop,startPagePoint:n.startPagePoint});i&&e.commands.updateShapes([i],{source:"user"})}function Ru(e){return{id:e,isVisible:()=>!1,isEnabled:()=>!1,run(){throw new Error(`Image toolbar action ${e} requires a host implementation.`)}}}function Au(e,t=0){return Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t)}function Lu({cornerRadius:e,h:t,w:n}){return Math.min(Au(e),Math.max(0,n)/2,Math.max(0,t)/2)}function Fu(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function $u(){let e=null;const t=t=>{e=null,yu(t)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(n,i){if("keyboard"===i.type)return((e,t)=>"key_down"!==t.name?"continue":Uu(e)?"Escape"!==t.key||t.altKey||t.accelKey?("Enter"!==t.key||t.altKey||t.accelKey||bu(e,{replace:!0}),"handled"):(gu(e),"handled"):"continue")(n,i);if("cancel"===i.type)return Uu(n)?(t(n),gu(n),"handled"):"continue";if("pointer"!==i.type)return"continue";const o=Uu(n);if(!o)return t(n),"continue";if("pointer_down"===i.name){if(t(n),0!==i.button)return 1===i.button?"continue":"handled";const r=zu(n,o,i.pagePoint),s=_u(r,o);return e={mode:s?"draw":"pan",originCamera:s?null:n.getCurrentCamera(),originScreenPoint:s?null:i.screenPoint.clone(),pointerId:i.pointerId},s&&Su(n,{x:r.x,y:r.y,pressure:i.pressure}),"handled"}return e&&e.pointerId===i.pointerId?"pointer_move"===i.name?("draw"===e.mode&&1&i.buttons?Du(n,o,i):"pan"===e.mode&&e.originCamera&&e.originScreenPoint&&1&i.buttons?Hu(n,i,e):yu(n),"handled"):"pointer_up"===i.name?("draw"===e.mode?Du(n,o,i):"pan"===e.mode&&Hu(n,i,e),t(n),"handled"):"pointer_cancel"===i.name?(t(n),"handled"):"handled":"handled"}}}}function Uu(e){const[t]=e.getSelectedShapes();if(!vu(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&uu(t,n.markId)?t:null}function Du(e,t,n){const i=zu(e,t,n.pagePoint);_u(i,t)?Su(e,{x:i.x,y:i.y,pressure:n.pressure}):yu(e)}function zu(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function _u(e,t){return e.x>=0&&e.y>=0&&e.x<=t.props.w&&e.y<=t.props.h}function Hu(e,t,n){if(!n.originCamera||!n.originScreenPoint)return;const i=t.screenPoint.sub(n.originScreenPoint),o=n.originCamera.z;e.setCamera({x:n.originCamera.x-i.x/o,y:n.originCamera.y-i.y/o},{source:"user"})}function Nu({dataUiPrefix:e}){return{kind:"text-input",id:`${e}.corner-radius`,actionId:xI,label:"Corner radius",placeholder:"0",dataUi:`${e}-corner-radius-control`}}function Ou({editor:e,isHovered:t,shape:n,shapeEditingSession:i}){const{altText:o,assetId:r,crop:s,h:a,w:d}=n.props,l=r?e.resolveAssetUrl(r):null,c=Lu({cornerRadius:n.props.cornerRadius,h:a,w:d}),u=((e,t)=>em(t=>((e,t)=>lu(e).subscribe(t))(e,t),()=>((e,t)=>lu(e).getSnapshot(t))(e,t),()=>null))(e,n.id);if(!l)return nm("div",{"data-ui":"image-shape-missing-asset",style:{alignItems:"center",background:"#f1f5f9",border:`1px solid ${t?ny:"#cbd5e1"}`,borderRadius:c,boxSizing:"border-box",color:"#64748b",display:"flex",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:12,height:a,justifyContent:"center",overflow:"hidden",width:d},children:"Missing image"});const h=(({crop:e,shapeHeight:t,shapeWidth:n})=>{const i=Gc(e);if(!i)return null;const o=n/i.width,r=t/i.height;return{imageX:-i.left*o,imageY:-i.top*r,imageWidth:o,imageHeight:r,rect:i}})({crop:s,shapeHeight:a,shapeWidth:d});if(h){const e=i?.shapeId===n.id&&iu(n,i.markId),r={display:"block",height:h.imageHeight,left:h.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:h.imageY,userSelect:"none",width:h.imageWidth};
|
|
50
|
-
return im("div",{"data-ui":"image-shape",style:{display:"block",height:a,overflow:e?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:d},children:[e?nm("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:l,style:{...r,opacity:.1}}):null,
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
return
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
nm(Xu,{cornerRadius:c,isVisible:t})]})}function Wu({shape:e,session:t}){return t&&t.shapeId===e.id&&0!==t.strokes.length?nm("svg",{"aria-hidden":"true","data-ui":"image-smudge-preview",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",height:e.props.h,inset:0,overflow:"hidden",pointerEvents:"none",position:"absolute",width:e.props.w},children:t.strokes.map(e=>nm(Yu,{stroke:e},e.id))}):null}function Yu({stroke:e}){const t=e.points[0];if(!t)return null;const n=e.brush.color??"#ffff00",i=e.brush.opacity??.45,o=e.brush.size;if(1===e.points.length)return nm("circle",{cx:t.x,cy:t.y,r:o/2,fill:n,opacity:i});const r=(e=>{const[t,...n]=e.points;return t?[`M ${qu(t.x)} ${qu(t.y)}`,...n.map(e=>`L ${qu(e.x)} ${qu(e.y)}`)].join(" "):null})(e);return r?nm("path",{d:r,fill:"none",opacity:i,stroke:n,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o}):null}function Xu({cornerRadius:e,isVisible:t}){return t?nm("div",{"aria-hidden":"true","data-ui":"image-hover-outline",style:{borderRadius:e,boxShadow:`inset 0 0 0 2px ${ny}`,inset:0,pointerEvents:"none",position:"absolute"}}):null}function Ku({handle:e,strokeWidth:t}){const{x:n,y:i,w:o,h:r,center:s}=e.bounds,a=1.35*Math.max(o,r),d=Math.max(2.5*t,2),l={fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeLinecap:"butt",strokeLinejoin:"miter",strokeWidth:d,pointerEvents:"none"},c=(({id:e,extension:t,outwardOffset:n,centerX:i,centerY:o})=>{switch(e){case"top_left":return{kind:"corner",points:[Vu(i-n,o+t),Vu(i-n,o-n),Vu(i+t,o-n)].join(" ")};case"top":return{kind:"edge",x1:i-t,y1:o-n,x2:i+t,y2:o-n};case"top_right":return{kind:"corner",points:[Vu(i-t,o-n),Vu(i+n,o-n),Vu(i+n,o+t)].join(" ")};case"right":return{kind:"edge",x1:i+n,y1:o-t,x2:i+n,y2:o+t};case"bottom_right":return{kind:"corner",points:[Vu(i+n,o-t),Vu(i+n,o+n),Vu(i-t,o+n)].join(" ")};case"bottom":return{kind:"edge",x1:i-t,y1:o+n,x2:i+t,y2:o+n};case"bottom_left":return{kind:"corner",points:[Vu(i+t,o+n),Vu(i-n,o+n),Vu(i-n,o-t)].join(" ")};case"left":return{kind:"edge",x1:i-n,y1:o-t,x2:i-n,y2:o+t};default:return{kind:"edge",x1:i,y1:o,x2:i,y2:o}}})({id:e.id,extension:a,outwardOffset:d/2,centerX:s.x,centerY:s.y});
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
return im("g",{"data-ui":"path-draft-overlay",pointerEvents:"none",children:[c.previewPath?nm("path",{"data-ui":"path-draft-preview-segment",d:c.previewPath,fill:"none",stroke:Tv,strokeWidth:Math.max(d,1/o.z),strokeDasharray:`${6/o.z} ${4/o.z}`,strokeLinecap:"round",strokeLinejoin:"round"}):null,c.committedNodes.map(e=>nm(Sp,{point:mp(e),size:a,strokeWidth:d,variant:"committed"},e.id)),h?nm(Sp,{point:u,size:a,strokeWidth:d,variant:"candidate"}):null]})}function mp(e){return new wm(e.x,e.y)}function Sp({point:e,size:t,strokeWidth:n,variant:i}){const o=t/2;
|
|
60
|
-
return
|
|
61
|
-
return
|
|
62
|
-
|
|
63
|
-
return
|
|
64
|
-
return
|
|
65
|
-
return
|
|
66
|
-
return nm("circle",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,cx:e.point.x,cy:e.point.y,r:Math.max(e.bounds.w,e.bounds.h)/2,fill:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.92)",stroke:"rgba(255,255,255,0.96)",strokeWidth:n?1.5*t:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}function wp(e,t){const n=nr();ir(n.shapeEditingSessionSignal);const i=(e=>{const t=Pv.get(e);return t?up(t):null})(n),o=bh(e,t);return!!i&&!!o&&i.subpathId===o.subpathId&&i.nodeId===o.nodeId}function Pp(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6}function kp(e){return jh(e.shape,e.localToPage).filter(e=>e.closed&&e.nodes.length>=3).map(e=>(e=>{const t=[];for(const n of e){const e=[n.x,n.y],i=t[t.length-1];i&&Pp(i,e)||t.push(e)}return t.length>1&&Pp(t[0],t[t.length-1])&&t.pop(),t.length>=3?t:null})(Yh(e).points)).filter(e=>null!==e).map(e=>[e])}function Cp(e){const t=e.length>1&&Pp(e[0],e[e.length-1])?e.slice(0,-1):e;return t.length<3?null:{id:`boolean-subpath:${Bv+=1}`,closed:!0,nodes:t.map(([e,t])=>({id:`boolean-node:${Mv+=1}`,x:e,y:t,kind:"corner"}))}}function Tp(e){const t=e.getShapeEditingSession();if(!t)return null;const n=e.getShape(t.shapeId);return vh(n)?n:null}function Ep(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function Bp(e){xh(e,null)}function Mp(e){Bp(e),dp(e,null)}function Rp(e,t,n,i){const o=sp(t.props.subpaths,n,i);e.commands.updateShapes([{id:t.id,props:{subpaths:o}}],{source:"user"}),dp(e,null)}function Ap(e,t,n){const i=n?e.len():t?.len()??e.len();if(0===i)return null;const o=e.normalize().mul(-i);return{dx:o.x,dy:o.y}}function Lp(){return{id:"land.path.interactions",editorEvent:{handleEvent(e,t){if("pointer"===t.type&&"pointer_up"===t.name&&Bp(e),"pointer"===t.type&&"pointer_cancel"===t.name&&Bp(e),"click"===t.type&&"double_click"===t.name&&"up"===t.phase){Mp(e);const n=e.hitTestShape(t.pagePoint);if(vh(n))return e.startEditingShape({shapeId:n.id,markId:"path.edit",entryMode:"focusEnd"},"user"),"handled"}if("cancel"===t.type)return Mp(e),"continue";if("keyboard"===t.type&&"key_down"===t.name)return function(e,t){if(t.altKey||t.ctrlKey||t.metaKey)return!1;const n=ap(e);if(!n||n.shape.isLocked)return!1;const i=t.key.toLowerCase();return"backspace"===i||"delete"===i?(Rp(e,n.shape,n.selection.subpathId,n.selection.nodeId),!0):"c"===i?(((e,t,n,i)=>{const o=tp(t.props.subpaths,n,i);if(!o||o.in||o.out)return;const r=ip(t.props.subpaths,n,i);e.commands.updateShapes([{id:t.id,props:{subpaths:r}}],{source:"user"});const s=e.getShape(t.id);vh(s)&&lp(e,s,n,i)})(e,n.shape,n.selection.subpathId,n.selection.nodeId),!0):"x"===i&&(((e,t,n,i)=>{const o=tp(t.props.subpaths,n,i);if(!o||!o.in&&!o.out)return;const r=op(t.props.subpaths,n,i);e.commands.updateShapes([{id:t.id,props:{subpaths:r}}],{source:"user"});const s=e.getShape(t.id);vh(s)&&lp(e,s,n,i)})(e,n.shape,n.selection.subpathId,n.selection.nodeId),!0)}(e,t)?"handled":"continue";if("pointer"===t.type&&"pointer_move"===t.name)return"mouse"!==t.pointerType||0!==t.buttons||t.altKey?Bp(e):((e,t)=>{const n=Tp(e);if(!n||"select"!==e.getActiveToolId()||!e.isActiveToolInInitialState())return void Bp(e);if("custom"===e.hitTestSelectionHandle(t.pagePoint)?.kind)return void Bp(e);const i=Ep(e,n,t.pagePoint),o=Jh(n.props.subpaths,i,7/e.getCurrentCamera().z);if(!o)return void Bp(e);const r=e.computeShapeLocalToPageTransform(n);xh(e,{shapeId:n.id,subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,pagePoint:r.applyToPoint(o.point)})})(e,t),"continue";if("pointer"===t.type&&"pointer_down"===t.name&&t.altKey){Mp(e);const n=Tp(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind&&"path.node"===i.type){const t=bh(i.type,i.id);if("path.node"===t?.type)return Rp(e,n,t.subpathId,t.nodeId),"handled"}}if("pointer"===t.type&&"pointer_down"===t.name&&0===t.button&&!t.altKey){Bp(e);const n=Tp(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind){const t=bh(i.type,i.id);return t?lp(e,n,t.subpathId,t.nodeId):dp(e,null),"continue"}const o=Ep(e,n,t.pagePoint),r=Jh(n.props.subpaths,o,7/e.getCurrentCamera().z);if(!r)return dp(e,null),"continue";e.history.mark(Rv);const s=`insert-node:${Av+=1}`,a=function(e,t,n){return e.map(e=>{if(e.id!==t.subpathId)return Lh(e);const i=e.nodes.findIndex(e=>e.id===t.startNodeId);if(i<0)return Lh(e);const o=(i+1)%e.nodes.length,r=e.nodes[i],s=e.nodes[o];if(!r||!s||s.id!==t.endNodeId)return Lh(e);const a=((e,t,n,i)=>{if(!Nh(e,t)){const o=_h($h(e),$h(t),n);return{start:Ah(e),node:{id:i,x:o.x,y:o.y,kind:"corner"},end:Ah(t)}}const[o,r,s,a]=Hh(e,t),d=_h(o,r,n),l=_h(r,s,n),c=_h(s,a,n),u=_h(d,l,n),h=_h(l,c,n),p=_h(u,h,n);return{start:{...Ah(e),out:rp(d.sub(o))},node:{id:i,x:p.x,y:p.y,kind:"smooth",in:rp(u.sub(p)),out:rp(h.sub(p))},end:{...Ah(t),in:rp(c.sub(a))}}})(r,s,t.t,n),d=e.nodes.map(Ah);return d[i]=a.start,d[o]=a.end,d.splice(i+1,0,a.node),{...e,nodes:d}})}(n.props.subpaths,r,s);e.commands.updateShapes([{id:n.id,props:{subpaths:a}}],{source:"user"});const d=e.getShape(n.id);return vh(d)&&lp(e,d,r.subpathId,s),e.history.squashToMark(Rv,"shape.edit"),"continue"}return"continue"}},selectionHandle:{createSession(e,{handle:t,shape:n,originPagePoint:i}){if(!vh(n)||"custom"!==t.kind)return null;const o=bh(t.type,t.id);if(!o)return null;if(e.getShapeEditingSession()?.shapeId!==n.id)return null;const r=n,s="path.node"===o.type?tp(r.props.subpaths,o.subpathId,o.nodeId):null,a=Ep(e,r,i);return{shapeId:n.id,historyMark:"path.handle",handleSnapMode:"point",allowSelfSnap:!0,update({editor:e,pagePoint:t,source:i}){if(!vh(e.getShape(n.id)))return"stop";const d=Ep(e,r,t),l="path.node"===o.type?s?np(r.props.subpaths,o.subpathId,o.nodeId,e=>((e,t)=>({...e,x:e.x+t.x,y:e.y+t.y}))(e,d.sub(a))):Fh(r.props.subpaths):np(r.props.subpaths,o.subpathId,o.nodeId,e=>((e,t,n)=>{const i=$h(e),o={...e},r=n.sub(i);return"in"===t?(o.in={dx:r.x,dy:r.y},"corner"!==e.kind&&(o.out=Ap(r,e.out?Dh(e).sub(i):null,"symmetric"===e.kind))):(o.out={dx:r.x,dy:r.y},"corner"!==e.kind&&(o.in=Ap(r,e.in?Uh(e).sub(i):null,"symmetric"===e.kind))),o})(e,o.handle,d));if(e.commands.updateShapes([{id:n.id,props:{subpaths:l}}],{source:i}),"path.node"===o.type){const t=e.getShape(n.id);vh(t)&&lp(e,t,o.subpathId,o.nodeId)}return"continue"}}}}}}function Fp(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function $p(e){if(!e||"object"!=typeof e)return null;const t=e,n=Fp(t.dx,NaN),i=Fp(t.dy,NaN);return Number.isFinite(n)&&Number.isFinite(i)?t.dx===n&&t.dy===i?e:{dx:n,dy:i}:null}function Up(e,t){if(!Array.isArray(e))return t;const n=e.map((e,t)=>function(e,t){if(!e||"object"!=typeof e)return null;const n=e,i=Array.isArray(n.nodes)?n.nodes.map((e,t)=>((e,t)=>{if(!e||"object"!=typeof e)return null;const n=e,i=Fp(n.x,NaN),o=Fp(n.y,NaN);return Number.isFinite(i)&&Number.isFinite(o)?{id:"string"==typeof n.id?n.id:`node:${t}`,x:i,y:o,kind:(r=n.kind,"string"==typeof r&&bv.includes(r)?n.kind:"corner"),in:$p(n.in),out:$p(n.out)}:null;var r})(e,t)).filter(e=>null!==e):[];return 0===i.length?null:{id:"string"==typeof n.id?n.id:`subpath:${t}`,closed:"boolean"==typeof n.closed&&n.closed,nodes:i}}(e,t)).filter(e=>null!==e);return n.length>0?n:t}function Dp(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return e.dist2(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o));return e.dist2(t.add(i.mul(s)))}function zp(e,t){const n=t($h(e)),i=e.in?t(Uh(e)):null,o=e.out?t(Dh(e)):null;return{...Ah(e),x:n.x,y:n.y,in:i?{dx:i.x-n.x,dy:i.y-n.y}:null,out:o?{dx:o.x-n.x,dy:o.y-n.y}:null}}function _p(){return`node:${$v+=1}`}function Hp(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function Np(e,t){return t.previewNodeId?e.map(e=>e.id===t.subpathId?{...e,nodes:e.nodes.filter(e=>e.id!==t.previewNodeId)}:e):Fh(e)}function Op(e,t){return ep(e.props.subpaths,t.subpathId)?.nodes.filter(e=>e.id!==t.previewNodeId).length??0}function Wp({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,fillRuleActionId:i,dataUiPrefix:o}){return[{id:`${o}.style-fill`,items:[{kind:"swatches",id:`${o}.fill`,actionId:e,label:"Fill",options:qv.map(e=>({...e,dataUi:`${o}-fill-${e.label.toLowerCase()}-button`}))}]},{id:`${o}.style-stroke`,items:[{kind:"swatches",id:`${o}.stroke`,actionId:t,label:"Stroke",options:jv.map(e=>({...e,dataUi:`${o}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${o}.style-stroke-width`,items:[{kind:"stepper",id:`${o}.stroke-width`,actionId:n,label:"Stroke width",dataUi:`${o}-stroke-width-control`,options:Gv.map(e=>({...e,dataUi:`${o}-stroke-width-${e.value}-button`}))}]},{id:`${o}.fill-rule`,items:[{kind:"segmented",id:`${o}.fill-rule`,actionId:i,options:Zv.map(e=>({...e,dataUi:`${o}-fill-rule-${e.value}-button`}))}]}]}function Yp(e){return{id:`path.set-${e}`,isVisible:e=>"path"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:t=>((e,t)=>{let n;for(const i of e){if(!vh(i))continue;const e=i.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!E(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=qp(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(vh).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));o.length>0&&t.editor.commands.updateShapes(o,{source:"user"})}}}function Xp(e){return{id:`path.default-${e}`,isVisible:e=>"path"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("path")[e],run({context:t,value:n}){const i=qp(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("path",{[e]:i})}}}function Kp(e){return{id:`path.boolean.${e}`,isVisible:e=>"path"===e.selection.commonShapeType,isEnabled:e=>Vp(e).length>=2,run({context:t}){const n=Vp(t),i=n[0];if(!i||n.length<2)return;const o=((e,t,n)=>{const i=function(e,t){const n=t.map(kp).filter(e=>e.length>0);return 0===n.length?[]:((e,t)=>{const[n,...i]=t;if(!n)return[];if(0===i.length)return n;switch(e){case"union":return(0,Ev.union)(n,...i);case"subtract":return(0,Ev.difference)(n,...i);case"intersect":return(0,Ev.intersection)(n,...i);case"xor":return(0,Ev.xor)(n,...i)}})(e,n).flatMap(e=>e).map(Cp).filter(e=>null!==e)}(e,t);return 0===i.length?null:qh(i,{...n,fillRule:"evenodd"})})(e,n.map(e=>({shape:e,localToPage:t.editor.computeShapeLocalToPageTransform(e)})),{fill:i.props.fill,stroke:i.props.stroke,strokeWidth:i.props.strokeWidth});if(!o)return;const r=`path.boolean.${e}`;t.editor.history.mark(r);const[s]=t.editor.commands.createShapes([{type:"path",x:o.x,y:o.y,parentId:i.parentId,props:{...i.props,subpaths:o.subpaths,fillRule:"evenodd"}}],{source:"user"});t.editor.commands.deleteShapes(n.map(e=>e.id),{source:"user"}),s&&t.editor.commands.setSelectedShapeIds([s.id],{source:"system"}),t.editor.history.squashToMark(r,"shape.boolean")}}}function Vp(e){return e.selection.selectedShapes.filter(vh).filter(e=>!e.isLocked).filter(e=>e.props.subpaths.some(e=>e.closed&&e.nodes.length>=3))}function qp(e,t){return"strokeWidth"===e?"number"==typeof t&&Gv.some(e=>e.value===t)?t:void 0:v(t)?P(t,y("fill"===e?"fill-blue":"stroke-slate")):void 0}function jp({childIds:e,depth:t,editor:n,index:i,pageId:o,shape:r}){return{id:r.id,parentId:r.parentId,pageId:o,type:r.type,childIds:e,siblingIndex:i,depth:t,displayName:r.type,canReceiveChildren:n.canUseShapeParent(r.id),isHidden:r.isHidden,isLocked:r.isLocked,isEffectivelyHidden:n.isShapeHidden(r.id),isEffectivelyLocked:n.isShapeOrAncestorLocked(r.id)}}function Gp(e,t){let n=0,i=e.getShape(t);const o=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(o.has(t))break;o.add(t),i=e.getShape(t),n+=1}return n}function Zp(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function Qp(e){const t=e.getDocumentMetadataRecord();return{id:t?.id??"document:main",meta:{...t?.meta??{}}}}function Jp(e,t){return{id:t.id,type:t.type,parentId:t.parentId,pageId:e.getShapePageId(t.id),index:t.index,x:t.x,y:t.y,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,props:{...t.props},meta:{...t.meta}}}function eg(e){return{id:e.id,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function tg(e,t){const n=e.sessionSignal.get(),i=n.activeToolId;t.assertToolId(i);const o=i,r=e.getPages().map(t=>({pageId:t.id,selectedShapeIds:[...e.getSelectedShapeIds(t.id)],camera:{...e.getCamera(t.id)}}));return{currentPageId:n.currentPageId,activeToolId:o,isToolLocked:n.isToolLocked,pages:r}}function ng(e,t){const n=e.getActiveToolId();t.assertToolId(n);const i=n;return{productId:t.productId,document:Qp(e),pageId:e.getCurrentPageId(),activeToolId:i,selectedShapeIds:[...e.getSelectedShapeIds()],shapeCount:e.getCurrentPageShapeIds().length,session:tg(e,t)}}function ig(e){return{...e,selectedShapeIds:[...e.selectedShapeIds],session:{...e.session,pages:e.session.pages.map(e=>({...e,selectedShapeIds:[...e.selectedShapeIds],camera:{...e.camera}}))},document:{...e.document,meta:{...e.document.meta}}}}function og(e){return{...e,meta:{...e.meta}}}function rg(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function sg(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}function ag(e,t){e.includes(t)||e.push(t)}function dg(e,t){return e.added.some(e=>e.scope===t)||e.updated.some(e=>e.before.scope===t||e.after.scope===t)||e.removed.some(e=>e.scope===t)}function lg(e){const{apis:t,editor:n}=e;return{apis:t,snapshot:()=>ng(n,e),subscribe(t){let i=ig(ng(n,e));return n.listen(o=>{const r=dg(o.diff,"document"),s=dg(o.diff,"session");if(!r&&!s)return;const a=s?ng(n,e):((e,t,n,{hasDocumentMetadataChange:i})=>{return{productId:n.productId,document:i?Qp(e):og(t.document),pageId:t.pageId,activeToolId:t.activeToolId,selectedShapeIds:[...t.selectedShapeIds],shapeCount:e.getCurrentPageShapeIds().length,session:(o=t.session,{...o,pages:o.pages.map(e=>({...e,selectedShapeIds:[...e.selectedShapeIds],camera:{...e.camera}}))})};var o})(n,i,e,{hasDocumentMetadataChange:(d=o.diff,d.added.some(e=>"document"===e.typeName)||d.updated.some(e=>"document"===e.before.typeName||"document"===e.after.typeName)||d.removed.some(e=>"document"===e.typeName))});var d;const l=function(e,t){const n=[];return e.pageId!==t.pageId&&n.push("pageId"),e.activeToolId!==t.activeToolId&&n.push("activeToolId"),rg(e.selectedShapeIds,t.selectedShapeIds)||n.push("selectedShapeIds"),e.shapeCount!==t.shapeCount&&n.push("shapeCount"),((e,t)=>{if(e.currentPageId!==t.currentPageId||e.activeToolId!==t.activeToolId||e.isToolLocked!==t.isToolLocked||e.pages.length!==t.pages.length)return!1;for(let n=0;n<e.pages.length;n+=1){const i=e.pages[n],o=t.pages[n];if(i.pageId!==o.pageId||!rg(i.selectedShapeIds,o.selectedShapeIds)||!sg(i.camera,o.camera))return!1}return!0})(e.session,t.session)||n.push("session"),n}(i,a);if(r&&ag(l,"document"),s&&ag(l,"session"),0===l.length)return void(i=ig(a));const c=i;i=ig(a);try{t({source:o.source,changes:l,snapshot:a,previousSnapshot:c})}catch(u){(e=>{const t=globalThis.reportError;"function"!=typeof t?console.error(e):t(e)})(u)}})},clearHistory(){n.history.clear()},canUndo:()=>n.historyStateSignal.get().canUndo,canRedo:()=>n.historyStateSignal.get().canRedo,undo:()=>n.undo(),redo:()=>n.redo(),getDocument:()=>Qp(n),updateDocumentMeta:e=>(n.updateDocumentMeta(e,"user"),Qp(n)),select(e){n.commands.setSelectedShapeIds(e,{source:"user"})},selectAll(){n.selectAllCurrentPage("user")},deleteSelection(){n.deleteSelection("user")},deleteShapes(e){n.deleteShapesById(e,"user")},getShape(e){const t=n.getShape(e);return t?Jp(n,t):null},getShapes:e=>(e?e.map(e=>n.getShape(e)).filter(e=>!!e):n.getPages().flatMap(e=>n.getShapesForPage(e.id))).map(e=>Jp(n,e)),updateShapes(e){const t=e.filter(e=>{const t=n.getShape(e.id);return!!t&&function(e,t){return!(!t.props&&void 0===t.meta)||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(i=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):i))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,i}(t,e)}).map(eg);return 0===t.length?[]:(n.commands.updateShapes(t,{source:"user"}),t.map(e=>e.id))},updateShapeMeta(e,t){const i=n.getShape(e);return i?(n.commands.updateShapes([{id:e,meta:{...i.meta,...t}}],{source:"user"}),e):null},duplicateSelection:()=>n.duplicateSelection(),centerOnShape(e){const t=n.getShapePageId(e);if(!t)return!1;t!==n.getCurrentPageId()&&n.commands.setCurrentPageId(t,{source:"user"});const i=n.getShapeSubtreePageBounds(e);if(!i)return!1;const o=n.viewportScreenSizeSignal.get();if(o.w<=0||o.h<=0)return!1;const r=n.getCurrentCamera();return n.commands.setCamera({pageId:t,camera:{x:i.center.x-o.w/(2*r.z),y:i.center.y-o.h/(2*r.z),z:r.z}},{source:"user"}),!0},getLayerTree:e=>(({editor:e,pageId:t=e.getCurrentPageId()})=>{const n=[],i=(o,r)=>{e.getChildShapes(o).forEach((o,s)=>{const a=e.getChildShapeIds(o.id);n.push(jp({childIds:a,depth:r,editor:e,index:s,pageId:t,shape:o})),i(o.id,r+1)})};return i(t,0),n})({editor:n,pageId:e??n.getCurrentPageId()}),getLayerNode:e=>(({editor:e,id:t})=>{const n=e.getShape(t),i=n?e.getShapePageId(n.id):null;if(!n||!i)return null;const o=e.getChildShapeIds(n.parentId);return jp({childIds:e.getChildShapeIds(n.id),depth:Gp(e,n.id),editor:e,index:o.indexOf(n.id),pageId:i,shape:n})})({editor:n,id:e}),setShapesHidden:(e,t)=>n.setShapesHidden(e,t,"user"),setShapesLocked:(e,t)=>n.setShapesLocked(e,t,"user"),groupShapes:e=>n.groupShapes(e,"user")?.id??null,ungroupShapes:e=>n.ungroupShapes(e,"user"),moveShapesInParentOrder:(e,t)=>n.moveShapesInParentOrder(e,t,"user"),moveShapesToParentOrderEdge:(e,t)=>n.moveShapesToParentOrderEdge(e,t,"user"),moveShapesToLayerPlacement:(e,t)=>n.moveShapesToParentPlacementResult({ids:e,parentId:t.parentId,beforeId:t.beforeId},"user"),getLayerActionState:e=>({canGroup:n.canGroupShapes(e),canUngroup:n.canUngroupShapes(e),canMoveBackward:n.canMoveShapesInParentOrder(e,"backward"),canMoveForward:n.canMoveShapesInParentOrder(e,"forward")}),setTool(e){if(!n.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);n.setActiveTool(e,"user")},setCamera(e,t){n.commands.setCamera({pageId:t,camera:e},{source:"user"})},resetView(){n.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},getPages:()=>n.getPages().map(Zp),createPage:e=>Zp(n.createPageAndSelect(e?{name:e.name,meta:e.meta?{...e.meta}:void 0}:void 0,"user")),renamePage(e,t){n.renamePage(e,t,"user")},updatePageMeta:(e,t)=>n.updatePageMeta(e,t,"user")?.id??null,deletePage:e=>n.deletePage(e,"user"),selectPage(e){n.selectPage(e,"user")},exportSelectionSvg:()=>n.getSvgString(n.getSelectedShapeIds(),{padding:16})?.svg??null,exportPageSvg:()=>n.getSvgString(n.getCurrentPageShapeIds(),{padding:16})?.svg??null}}function cg(e,t,n){const i=e.getDefaultShapeProps("geo"),[o]=e.commands.createShapes([{type:"geo",x:n.x,y:n.y,meta:n.meta?{...n.meta}:void 0,props:{...i,geo:t,w:n.w??i.w,h:n.h??i.h,fill:n.fill??i.fill,stroke:n.stroke??i.stroke,strokeWidth:n.strokeWidth??i.strokeWidth,cornerRadiusPercent:n.cornerRadiusPercent??i.cornerRadiusPercent}}],{source:"user"});return o&&"geo"===o.type?{id:o.id,type:o.type}:null}function ug(e){return{create(t){const n=e.getDefaultShapeProps("arrow"),i=ja(e,{startPagePoint:new wm(t.start.x,t.start.y),endPagePoint:new wm(t.end.x,t.end.y),startBinding:t.startBinding?{targetShapeId:t.startBinding.targetShapeId,normalizedAnchor:t.startBinding.normalizedAnchor}:null,endBinding:t.endBinding?{targetShapeId:t.endBinding.targetShapeId,normalizedAnchor:t.endBinding.normalizedAnchor}:null,meta:t.meta?{...t.meta}:void 0,props:{...n,bend:t.bend??n.bend,stroke:t.stroke??n.stroke,strokeWidth:t.strokeWidth??n.strokeWidth,headStart:t.headStart??n.headStart,headEnd:t.headEnd??n.headEnd}});return{id:i.id,type:i.type}}}}function hg(e){return{createRectangle:t=>cg(e,"rectangle",t),createEllipse:t=>cg(e,"ellipse",t),createDiamond:t=>cg(e,"diamond",t),createTriangle:t=>cg(e,"triangle",t),createHexagon:t=>cg(e,"hexagon",t),createStar:t=>cg(e,"star",t)}}function pg(e){return{create(t){const n=e.getDefaultShapeProps("text"),[i]=e.commands.createShapes([{type:"text",x:t.x,y:t.y,meta:t.meta?{...t.meta}:void 0,props:{...n,w:t.w??n.w,h:t.h??n.h,font:t.font??n.font,color:t.color??n.color,size:t.size??n.size,textAlign:t.textAlign??n.textAlign,richText:Mo(t.text)}}],{source:"user"});return i&&"text"===i.type?{id:i.id,type:i.type}:null}}}function gg(e){return{create(t){const n=e.getDefaultShapeProps("frame"),[i]=e.commands.createShapes([{type:"frame",x:t.x,y:t.y,meta:t.meta?{...t.meta}:void 0,props:{...n,w:t.w??n.w,h:t.h??n.h,name:t.name??n.name,fill:t.fill??n.fill,stroke:t.stroke??n.stroke,strokeWidth:t.strokeWidth??n.strokeWidth}}],{source:"user"});return i&&"frame"===i.type?{id:i.id,type:i.type}:null},moveShapesToFrame(t,n){const i=e.getShape(n);if(!i||"frame"!==i.type)return[];const o=t.filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked});return 0===o.length?[]:(e.commands.reparentShapes({ids:o,parentId:n},{source:"user"}),o)}}}function fg(e,t){const n=e.getShape(t.id);if("geo"===t.type){const e=(n?.props)?.geo;return{...t,displayName:mg(e),geoKind:e}}if("image"===t.type){const i=n?.props,o=i?.assetId??null,r=((o?e.getAsset(o):void 0)?.props)?.name,s=i?.altText?.trim();return{...t,displayName:r||s||"Image",imageAssetId:o,imageThumbnailSrc:o?e.resolveAssetUrl(o):null}}if("text"===t.type){const e=n?.props,i=e?.richText?Ro(e.richText).replace(/\s+/g," ").trim():"";return{...t,displayName:i.length>0?i:"Text"}}if("frame"!==t.type)return t;const i=(n?.props)?.name;return{...t,displayName:i&&i.length>0?i:"Frame"}}function mg(e){switch(e){case"diamond":return"Diamond";case"ellipse":return"Ellipse";case"hexagon":return"Hexagon";case"rectangle":return"Rectangle";case"star":return"Star";case"triangle":return"Triangle";default:return"Shape"}}function Sg(e){const t=lg(e),n={arrow:ug(i=e.editor),geo:hg(i),text:pg(i),frame:gg(i)};var i;return{...t,...n,getLayerTree:n=>t.getLayerTree(n).map(t=>fg(e.editor,t)),getLayerNode(n){const i=t.getLayerNode(n);return i?fg(e.editor,i):null}}}function yg(e){if(!(e=>tw.has(e))(e)){if("geo"===e)throw new Error(`Unknown canvas kit tool "${e}". "geo" is a shape type, not a tool id. Use one of the geo tool ids such as "rectangle", "ellipse", or "triangle". Available tool ids: ${nw}.`);throw new Error(`Unknown canvas kit tool "${e}". Available tool ids: ${nw}.`)}}function bg(e){return xg({...e,assertToolId:e.assertToolId??yg})}function xg(e){const t={...Sg(e)};return(({apis:e,controller:t,slots:n})=>{for(const i of n){if(i.key in t)throw new Error(`Canvas kit controller slot conflicts with existing key: ${i.key}`);Object.defineProperty(t,i.key,{enumerable:!0,get:()=>e.get(i.token)})}})({apis:e.apis,controller:t,slots:e.controllerSlots}),t}function Ig({editor:e,toolState:t,selectionState:n}){return{editor:e,selection:{selectedShapeIds:e.getSelectedShapeIds(),selectedShapes:e.getSelectedShapes(),count:n.count,singleShapeType:n.singleShapeType,commonShapeType:n.commonShapeType,canResetRotation:n.canResetSelectionRotation,isMixedFrameAndPointHandleSelection:n.isMixedFrameAndPointHandleSelection},tool:{activeToolId:t.activeToolId,isToolLocked:t.isToolLocked}}}function vg(e,t){const n=Kf(n=>t?oo("useOptionalValue",e,n,{fireImmediately:!1}):()=>{},[t,e]),i=Kf(()=>t?e.get():null,[t,e]);return em(n,i,i)}function wg({assetInliners:e=[],editor:t,themeRootRef:n}){const[i,o]=Jf(null);return{status:i,exportSvg:Kf(async i=>{const r=await async function({assetInliners:e=[],editor:t,padding:n=16,resolveThemeColor:i,shapeIds:o}){const r=t.repairExportIntegrity(o),s=t.getSvgString(o,{padding:n,resolveThemeColor:i}),a=t.getExportIntegrityReport(o),d=(({capabilityManifest:e,integrity:t})=>{const n=(e=>{const t=Object.entries(e).filter(e=>"number"==typeof e[1]);return 0===t.length?"none":t.map(([e,t])=>`${e} ${t}`).join(", ")})((e=>{const t={};for(const n of e.issues)t[n.kind]=(t[n.kind]??0)+1;return t})(t));return 0===t.fatalIssueCount&&0===t.issues.length?{tone:"success",title:"SVG export ready",details:`${t.requestedShapeIds.length} shape(s) ready. Issues: ${n}.`,integrity:t,capabilityManifest:e}:t.canExport?{tone:"warning",title:"SVG export repaired",details:`${t.requestedShapeIds.length} shape(s) exportable. Issues: ${n}.`,integrity:t,capabilityManifest:e}:{tone:"error",title:"SVG export blocked",details:`Fatal export issue(s): ${n}.`,integrity:t,capabilityManifest:e}})({capabilityManifest:t.getShapeCapabilityManifest(),integrity:a});if((r.before.issues.length>0||a.issues.length>0)&&console.warn("SVG export integrity report",{before:r.before,after:r.after,final:a}),!s)return{status:d,svg:null,exportedShapeIds:[],skippedShapes:[]};s.skippedShapes.length>0&&console.warn("Skipped shapes during SVG export",s.skippedShapes);let l=s.svg;for(const c of e)l=await c.inline({editor:t,exportedShapeIds:s.exportedShapeIds,svg:l});return{status:d,svg:l,exportedShapeIds:s.exportedShapeIds,skippedShapes:s.skippedShapes}}({assetInliners:e,editor:t,resolveThemeColor:(e,t)=>((e,t,n)=>e&&"undefined"!=typeof window&&window.getComputedStyle(e).getPropertyValue(t).trim()||n)(n?.current,e,t),shapeIds:i});return o(r.status),r},[e,t,n])}}function Pg({editor:e,hostFeatures:t,services:n}){return t.flatMap(t=>t.svgAssetInliners?.({editor:e,services:n})??[])}function kg(e,t){for(const n of e)n.onBeforeCommand?.(t)}function Cg(e,t){for(const n of e)n.onAfterCommand?.(t)}function Tg({apis:e,controller:t,activeContextMenu:n,chromeSlots:i,editor:o,grid:r,hostFeatures:s,onActiveContextMenuChange:a,persistence:d,pluginHostRuntime:l,services:c,themeRootRef:u}){const h=ir(o.currentPageIdSignal),p=ir(o.currentPageShapeIdsSignal),g=ir(o.selectedShapeIdsSignal),f=ir(o.selectionStateSignal),m=(({editor:e,hostFeatures:t})=>{const n=ir(e.historyStateSignal);return{canUndo:n.canUndo,canRedo:n.canRedo,undo(){kg(t,{commandId:"history.undo",editor:e}),e.undo()},redo(){kg(t,{commandId:"history.redo",editor:e}),e.redo()}}})({editor:o,hostFeatures:s}),S=(({editor:e,hostFeatures:t})=>{const n=ir(e.pageStateSignal);return{pages:n.pages,currentPage:n.currentPage,currentPageId:n.currentPageId,canDeleteCurrentPage:n.canDeleteCurrentPage,createPage(){kg(t,{commandId:"page.create",editor:e}),e.createPageAndSelect(void 0,"user")},deleteCurrentPage(){n.currentPage&&(kg(t,{commandId:"page.delete-current",editor:e}),e.deletePage(n.currentPage.id,"user"))},renameCurrentPage(i){n.currentPage&&(kg(t,{commandId:"page.rename-current",editor:e}),e.renamePage(n.currentPage.id,i,"user"))},selectPage(n){kg(t,{commandId:"page.select",editor:e}),e.selectPage(n,"user")}}})({editor:o,hostFeatures:s}),y=(e=>{const t=ir(e.cameraZoomSignal);return{zoom:t,label:`${Math.round(100*t)}%`,zoomIn(){e.zoomAtViewportCenter(-120,"system")},zoomOut(){e.zoomAtViewportCenter(120,"system")},resetZoom(){e.resetZoom("user")}}})(o),b=function({editor:e,activeContextMenu:t,pluginHostRuntime:n}){const i=null!==t,o=vg(e.selectionStateSignal,i),r=vg(e.toolStateSignal,i);return Zf(()=>{if(!t||!o||!r)return{context:null,activeContextMenu:null,sections:[]};const i=(({editor:e,menu:t})=>{const n=e.toolStateSignal.get();return{...Ig({editor:e,selectionState:e.selectionStateSignal.get(),toolState:n}),menu:t}})({editor:e,menu:t}),s=((e,t)=>"canvas"===e.type?"canvas":t.getSelectedShapeIds().length>0?"selection":"shape")(t.target,e);return{context:i,activeContextMenu:t,sections:n.contextMenuRegistry.getSections(s,i)}},[e,t,n,o,r])}({editor:o,activeContextMenu:n,pluginHostRuntime:l}),x=(({canShowContextToolbarDuringEditing:e,editor:t,pluginHostRuntime:n})=>{const i=ir(t.toolStateSignal),o=ir(t.selectionStateSignal),r=ir(t.shapeEditingStateSignal),s=ir(t.queries.selectionPageBoundsSignal),a=ir(t.selectionTranslationActiveSignal),d="select"===i.activeToolId,l=d?o.count:0,c=Ig({editor:t,selectionState:o,toolState:i}),u=!r.session||(e?.(c)??!1),h=d&&o.count>0,p=h?n.toolbarRegistry.getGroups("selection",c,{placement:"context"}):iw,g=h?n.toolbarRegistry.getGroups("selection",c,{placement:"floating"}):iw,f=d&&s&&g.length>0?{x:s.minX,y:s.minY}:null,m=(u||null!==r.session&&g.length>0)&&!a&&o.count>0&&g.length>0&&!!f,S=n.toolbarRegistry.getGroups("tool",c,{placement:"context"}),y=n.toolbarRegistry.getGroups("tool",c,{placement:"chrome"}),b=d&&o.count>0?p:S,x=u&&b.length>0,I=((e,t)=>{for(const n of e)for(const e of n.items)if("button"===e.kind&&"editor.tool.set-active-tool"===e.actionId&&e.value===t)return e.label;return t})(S,i.activeToolId),v=d&&o.count>0?(({commonShapeType:e,count:t,isMixedFrameAndPointHandleSelection:n,singleShapeType:i})=>{const o=i??e;if(!o)return n?"Mixed selection":`${t} selected`;const r=t>1?` (${t})`:"";return"geo"===o?`Shape${r}`:"text"===o?`Text${r}`:`${o.charAt(0).toUpperCase()}${o.slice(1)}${r}`})({commonShapeType:o.commonShapeType,count:l,isMixedFrameAndPointHandleSelection:o.isMixedFrameAndPointHandleSelection,singleShapeType:o.singleShapeType}):I;return{context:c,activeToolId:i.activeToolId,activeToolLabel:I,isToolLocked:i.isToolLocked,selectionCount:l,hasMixedSelectionRotation:o.hasMixedSelectionRotation,toolChromeToolbarGroups:y,contextToolbarGroups:b,floatingSelectionToolbarGroups:g,floatingSelectionToolbarPageAnchor:f,contextToolbarTitle:v,showContextToolbar:x,showFloatingSelectionToolbar:m}})({canShowContextToolbarDuringEditing:e=>((e,t)=>e.some(e=>e.canShowToolbarDuringEditing?.(t)))(s,e),editor:o,pluginHostRuntime:l}),I=wg({assetInliners:Pg({editor:o,hostFeatures:s,services:c}),editor:o,themeRootRef:u}),v=Zf(()=>{let e,n=[],i=[];return{getSnapshot(r){const s=r??o.getCurrentPageId(),a=((e,t)=>{const n=[];for(const i of e.getShapesForPage(t)){n.push(i);const t=i.props.assetId;"string"==typeof t&&t.startsWith("asset:")&&n.push(e.getAsset(t)??null)}return n})(o,s);return e===s&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0})(n,a)||(e=s,n=a,i=t.getLayerTree(s)),i},subscribe:e=>oo("CanvasKitLayerTree.records",o.store.recordsSignal,e,{fireImmediately:!1})}},[t,o]),w=Zf(()=>({getActionState({actionId:e,context:t}){const n=l.actionRegistry.getAction(e);return n?{value:n.getValue?.(t),isEnabled:n.isEnabled?.(t)??!0,isVisible:n.isVisible?.(t)??!0}:null},runAction({actionId:e,context:t,value:n}){const i=l.actionRegistry.getAction(e);i&&!1!==i.isVisible?.(t)&&!1!==i.isEnabled?.(t)&&(kg(s,{commandId:e,context:t,editor:t.editor}),i.run({context:t,value:void 0!==n?n:i.getValue?.(t)??null}),Cg(s,{commandId:e,context:t,editor:t.editor}))}}),[s,l]),P={controller:t,contextMenu:{activeContextMenu:n,onActiveContextMenuChange:a,runAction({actionId:e,context:t,value:n}){kg(s,{commandId:e,context:t,editor:t.editor}),(({actionId:e,context:t,pluginHostRuntime:n,value:i})=>{const o=n.actionRegistry.getAction(e);o&&!1!==o.isVisible?.(t)&&!1!==o.isEnabled?.(t)&&o.run({context:t,value:void 0!==i?i:o.getValue?.(t)??null})})({actionId:e,context:t,pluginHostRuntime:l,value:n}),Cg(s,{commandId:e,context:t,editor:t.editor})},surface:b},currentPageId:h,currentPageShapeIds:p,history:m,layerTree:v,pages:S,persistence:d,selection:f,selectedShapeIds:g,svgExport:I,toolbarRuntime:w,toolbarSurfaces:x,grid:r,zoom:y};return(({apis:e,chrome:t,slots:n})=>{for(const i of n){if(i.key in t)throw new Error(`Canvas kit chrome slot conflicts with existing key: ${i.key}`);Object.defineProperty(t,i.key,{enumerable:!0,get:()=>e.get(i.token)})}})({apis:e,chrome:P,slots:i}),P}function Eg({apis:e,config:t,controllerSlots:n,editor:i,pluginHostRuntime:o,productId:r,services:s}){const a=Zf(()=>({apis:e,controllerSlots:n,editor:i,pluginHostRuntime:o,productId:r,services:s}),[e,n,i,o,r,s]),d=Zf(()=>bg(a),[a]);return(({controller:e,exposeOnWindow:t=!1,windowKey:n,onDispose:i,onReady:o})=>{const r=jf(e=>{o?.(e)}),s=jf(()=>{i?.()});qf(()=>{const i=window;return t&&n&&(i[n]=e),r(e),()=>{t&&n&&i[n]===e&&delete i[n],s()}},[e,t,n])})({controller:d,exposeOnWindow:t.exposeControllerOnWindow,onDispose:t.onControllerDispose,onReady:t.onControllerReady,windowKey:t.windowKey}),d}function Bg({assetResolverTokens:e,services:t}){return e.map(e=>t.get(e)).filter(e=>!!e)}function Mg(e){return{id:e}}function Rg(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}async function Ag(e,t){for(const n of e)await n(t)}function Lg(e,t){const n=new Set,i=new Set;for(const o of e)n.has(o)?i.add(o):n.add(o);if(i.size>0)throw new Error(`Duplicate ${t}: ${[...i].join(", ")}.`)}function Fg(e){return[...e].sort((e,t)=>(e.order??0)-(t.order??0))}function $g(e){const{config:t,documentMeta:n,id:i,persistence:o,shouldSkipStoredSnapshots:r}=e,s=function(e){const t=(e=>{const t=[],n=new Set,i=e=>{if(n.has(e))throw new Error(`Circular Land extension bundle detected at "${e.name}".`);n.add(e),t.push(e.name);for(const t of e.getExtensions())i(t);n.delete(e)};for(const o of e)i(o);return Lg(t,"canvas extension name"),new Set(t)})(e.canvasExtensions),n=(({hostExtensions:e})=>{const t=[],n=new Set;let i=0;const o=e=>{if(n.has(e))throw new Error(`Circular canvas-kit host extension bundle detected at "${e.id}".`);n.add(e),t.push({extension:e,index:i}),i+=1;for(const t of e.getExtensions?.()??[])o(t);n.delete(e)};for(const r of e)o(r);return Lg(t.map(({extension:e})=>e.id),"host extension id"),t.sort((e,t)=>(t.extension.priority??0)-(e.extension.priority??0)||e.index-t.index).map(({extension:e})=>e)})({hostExtensions:e.hostExtensions}),i=n.map(n=>n.createFeature({canvasExtensionNames:t,persistence:e.persistence,productId:e.id})).filter(e=>!!e).sort((e,t)=>(t.priority??0)-(e.priority??0));(({canvasExtensionNames:e,hostFeatures:t})=>{for(const n of t){const t=(n.requiresCanvasExtensions??[]).filter(t=>!e.has(t));if(t.length>0)throw new Error(`Host feature "${n.id}" requires missing canvas extension(s): ${t.join(", ")}.`)}})({canvasExtensionNames:t,hostFeatures:i}),Lg(i.map(e=>e.id),"host feature id");const o=i.flatMap(e=>e.services??[]),r=i.flatMap(e=>e.assetResolverTokens??[]),s=i.flatMap(e=>e.actions??[]),a=i.flatMap(e=>e.createActions?[e.createActions]:[]),d=i.flatMap(e=>e.actionShortcuts??[]),l=i.flatMap(e=>e.toolbarContributions??[]),c=i.flatMap(e=>e.contextMenuContributions??[]),u=i.flatMap(e=>e.apis??[]),h=i.flatMap(e=>e.controllerSlots??[]),p=i.flatMap(e=>e.chromeSlots??[]),g=Fg(i.flatMap(e=>e.providers??[])),f=Fg(i.flatMap(e=>e.components??[])),m=(e=>{const t={controller:[],chrome:[],workspace:[]};for(const n of e)switch(n.slot){case"controller":t.controller.push(n);break;case"chrome":t.chrome.push(n);break;case"workspace":t.workspace.push(n)}return t})(f);return Lg(o.map(e=>e.token.id),"product service token"),Lg(u.map(e=>e.token.id),"product API token"),Lg(u.map(e=>e.id),"product API contribution id"),Lg(h.map(e=>e.key),"controller slot key"),Lg(p.map(e=>e.key),"chrome slot key"),Lg(l.map(e=>e.id),"host toolbar contribution id"),Lg(c.map(e=>e.id),"host context-menu contribution id"),Lg(f.map(e=>e.id),"host component id"),Lg(g.map(e=>e.id),"host provider id"),{canvasExtensions:e.canvasExtensions,canvasExtensionNames:t,hostExtensions:n,hostFeatures:i,services:o,assetResolverTokens:r,actions:s,actionFactories:a,actionShortcuts:d,toolbarContributions:l,contextMenuContributions:c,apis:u,controllerSlots:h,chromeSlots:p,providers:g,components:f,componentsBySlot:m,runtimeInitializers:i.flatMap(e=>e.onRuntimeInitialize?[e.onRuntimeInitialize]:[]),beforeStartupHooks:i.flatMap(e=>e.onBeforeStartup?[e.onBeforeStartup]:[]),afterRestoreHooks:i.flatMap(e=>e.onAfterRestore?[e.onAfterRestore]:[]),beforeReadyHooks:i.flatMap(e=>e.onBeforeReady?[e.onBeforeReady]:[]),runtimeDisposeHooks:i.flatMap(e=>e.onRuntimeDispose?[e.onRuntimeDispose]:[])}}(e),a=(({factories:e,productId:t})=>{const n=new Map,i=[],o=(e,t)=>{const o=n.get(e.token.id);if(o)return o;const r=e.create(t);return n.set(e.token.id,r),e.dispose&&i.push(()=>e.dispose?.(r)),r};for(const r of e)o(r,{productId:t});return{get:e=>n.get(e.id)??null,dispose(){const e=i.splice(0).reverse();try{for(const n of e)try{n()}catch(t){Rg(t)}}finally{n.clear()}}}})({factories:s.services,productId:i}),d=(({plan:e,productId:t,services:n})=>{const i=e.actionFactories.flatMap(e=>e({productId:t,services:n})),o=[...e.actions,...i];Lg(o.map(e=>e.id),"host action id");const{actionFactories:r,...s}=e;return{...s,actions:o,knownHostActionIds:o.map(e=>e.id)}})({plan:s,productId:i,services:a}),l=Co(d.canvasExtensions,{knownHostActionIds:d.knownHostActionIds});let c=null;const u=function(e){const t=((e={})=>{const{editorRuntimePlugins:t=[],...n}=e,i={shapeUtils:(o=t).flatMap(e=>e.shapeUtils??[]),shapeSvgExporters:o.flatMap(e=>e.shapeSvgExporters??[]),bindingUtils:o.flatMap(e=>e.bindingUtils??[]),shapeCapabilities:o.flatMap(e=>e.shapeCapabilities??[])};var o;const r=new mS({...n,shapeUtils:i.shapeUtils,shapeSvgExporters:i.shapeSvgExporters,bindingUtils:i.bindingUtils,shapeCapabilities:i.shapeCapabilities});return((e,t)=>{for(const n of t){for(const t of n.interactionHandlers??[])e.interactions.register(t);n.setup?.(e)}})(r,t),r})({documentMeta:e.documentMeta,editorRuntimePlugins:e.editorRuntimePlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new WS(e),{shortcut:"v"}),t.tools.register("hand",e=>new xS(e),{shortcut:"h"}),t.tools.setToolLocked(t.isToolLocked()),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t}({documentMeta:n,editorRuntimePlugins:l.editorRuntimePlugins,resolveAssetUrl:e=>c?(({assetResolverTokens:e,assetId:t,editor:n,services:i})=>{for(const o of Bg({assetResolverTokens:e,services:i})){const e=o.resolveAssetUrl(n,t);if(e)return e}return null})({assetResolverTokens:d.assetResolverTokens,assetId:e,editor:c,services:a}):null});c=u;const h=(()=>{const e=new Map;return{register(t,n){if(e.has(t.id))throw new Error(`Product API already registered: ${t.id}`);e.set(t.id,n)},get:t=>e.get(t.id)??null}})();(({apis:e,editor:t,plan:n,pluginHostRuntime:i,productId:o,services:r})=>{for(const s of n.actions)i.actionRegistry.registerHostAction(s);for(const{actionId:s,shortcut:a}of n.actionShortcuts)t.shortcuts.registerActionShortcut(s,a);for(const s of n.toolbarContributions)i.toolbarRegistry.registerContribution(s);for(const s of n.contextMenuContributions)i.contextMenuRegistry.registerContribution(s);for(const s of n.apis){const n=s.create({apis:e,editor:t,pluginHostRuntime:i,productId:o,services:r});null!==n&&e.register(s.token,n)}})({apis:h,editor:u,plan:d,pluginHostRuntime:l,productId:i,services:a});for(const p of d.runtimeInitializers)p({apis:h,editor:u,pluginHostRuntime:l,productId:i,services:a});return e.warnOnPluginRegistrationConflicts&&(({duplicateContextMenuContributionIds:e,duplicateCanvasActionIds:t,duplicateToolbarContributionIds:n,productId:i})=>{Ug({ids:t,kind:"canvas-action",message:`[land] Duplicate canvas action ids for product ${i}. The later registrations were ignored.`,productId:i}),Ug({ids:n,kind:"toolbar-contribution",message:`[land] Duplicate toolbar contribution ids for product ${i}. The later registrations were ignored.`,productId:i}),Ug({ids:e,kind:"context-menu-contribution",message:`[land] Duplicate context menu contribution ids for product ${i}. The later registrations were ignored.`,productId:i})})({duplicateContextMenuContributionIds:l.contextMenuRegistry.getDuplicateContributionIds(),duplicateCanvasActionIds:l.actionRegistry.getDuplicateActionIds(),duplicateToolbarContributionIds:l.toolbarRegistry.getDuplicateContributionIds(),productId:i}),e.seedDocument?.(bg({apis:h,controllerSlots:d.controllerSlots,editor:u,pluginHostRuntime:l,productId:i,services:a})),{apis:h,assetResolverTokens:d.assetResolverTokens,config:t,editor:u,hostExtensions:d.hostExtensions,persistence:o,plan:d,pluginHostRuntime:l,productId:i,services:a,shouldSkipStoredSnapshots:r}}function Ug({ids:e,kind:t,message:n,productId:i}){if(0===e.length)return;const o=`${i}:${t}:${e.join(",")}`;rw.has(o)||(rw.add(o),console.warn(n,e))}function Dg({product:e}){const t=(e=>{const t=e,[n,i]=Jf(null),o=n?.product===t?n.runtime:null;return qf(()=>{const e=$g(t);return i({product:t,runtime:e}),()=>{try{for(const t of e.plan.runtimeDisposeHooks)t({editor:e.editor,productId:e.productId,services:e.services})}catch(t){console.warn("Could not run canvas kit runtime dispose hooks.",t)}finally{e.services.dispose()}}},[t]),o})(e),[n,i]=Jf(null),[o,r]=Jf(!1),{isReady:s,persistence:a}=function(e){const[{readyRuntime:t,status:n},i]=Jf(ow),[o,r]=Jf(!1),s=!!e?.persistence?.restore&&!e.shouldSkipStoredSnapshots?.();qf(()=>{if(!e)return void i(ow);const{assetResolverTokens:t,editor:n,persistence:o,plan:r,productId:a,services:d}=e;let l=!1,c=null;const u=()=>{l=!0,c?.()},h=(t,r)=>{l||(i({readyRuntime:e,status:t}),r&&(c=o?.start?.(n)??null))};return s?(i(ow),(async()=>{let e=null,i=!0;try{await Ag(r.beforeStartupHooks,{editor:n,persistence:o,productId:a,services:d});const s=await(o?.restore?.(n));i="disabled"!==s?.autoPersistence,e=s?.status??null,await(async({assetResolverTokens:e,editor:t,services:n})=>{await Promise.all(Bg({assetResolverTokens:e,services:n}).map(e=>e.preloadForEditor?.(t)))})({assetResolverTokens:t,editor:n,services:d}),await(async({assetResolverTokens:e,editor:t,services:n})=>{await Promise.all(Bg({assetResolverTokens:e,services:n}).map(e=>e.cleanupAfterRestore?.(t)))})({assetResolverTokens:t,editor:n,services:d}),await Ag(r.afterRestoreHooks,{editor:n,persistence:o,productId:a,services:d})}catch(s){if(l)return;console.warn("Could not restore persisted canvas snapshot.",s)}try{await Ag(r.beforeReadyHooks,{editor:n,persistence:o,productId:a,services:d})}catch(s){if(l)return;console.warn("Could not run canvas kit before-ready hooks.",s)}h(e,i)})(),u):((async()=>{try{await Ag(r.beforeStartupHooks,{editor:n,persistence:o,productId:a,services:d}),await Ag(r.beforeReadyHooks,{editor:n,persistence:o,productId:a,services:d})}catch(e){if(l)return;console.warn("Could not run canvas kit startup hooks.",e)}h(null,!0)})(),u)},[e,s]);const a=Kf(async()=>{if(e?.persistence?.discardUnsupportedRecords){r(!0);try{const t=await e.persistence.discardUnsupportedRecords(e.editor);i(e=>({...e,status:t?.status??null}))}catch(t){console.warn("Could not discard unsupported persisted records.",t)}finally{r(!1)}}},[e]);return{isReady:t===e,persistence:{discardUnsupportedRecords:n&&e?.persistence?.discardUnsupportedRecords?a:null,isDiscardingUnsupportedRecords:o,status:n}}}(t),d=Zf(()=>({isVisible:o,setIsVisible:r}),[o]);if(qf(()=>{i(null)},[e]),!t)return null;const{editor:l,pluginHostRuntime:c}=t;
|
|
67
|
-
return nm(Iy.Provider,{value:l,children:nm(zg,{runtime:t,canvas:s?nm(Mr,{canvasComponents:c.canvasComponents,canvasProviders:c.canvasProviders,domEventGuardRegistry:c.domEventGuardRegistry,onContextMenuRequest:i,overlayRegistry:c.overlayRegistry,rendererRegistry:c.rendererRegistry,showGrid:o}):null,activeContextMenu:n,onActiveContextMenuChange:i,isReady:s,persistence:a,grid:d})})}function zg({canvas:e,activeContextMenu:t,grid:n,isReady:i,onActiveContextMenuChange:o,persistence:r,runtime:s}){const{apis:a,config:d,editor:l,plan:c,pluginHostRuntime:u,productId:h,services:p}=s,g=d.renderChrome,f=Qf(null),m=Tg({apis:a,controller:Eg({apis:a,config:d,controllerSlots:c.controllerSlots,editor:l,pluginHostRuntime:u,productId:h,services:p}),activeContextMenu:t,chromeSlots:c.chromeSlots,editor:l,grid:n,hostFeatures:c.hostFeatures,onActiveContextMenuChange:o,persistence:r,pluginHostRuntime:u,services:p,themeRootRef:f}),S={editor:l,pluginHostRuntime:u,services:p},y={...S,grid:n,isReady:i,persistence:r},b={...S,chrome:m,themeRootRef:f},x=nm("div",{ref:f,"data-ui":"app-shell","data-canvas-kit":h,className:"land-canvas-kit__shell",children:nm("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:i?im(tm,{children:[e,_g(c.componentsBySlot.controller,S),g?.(m),_g(c.componentsBySlot.chrome,b),_g(c.componentsBySlot.workspace,y)]}):null})});return c.providers.reduceRight((e,t)=>nm(t.component,{children:e},t.id),x)}function _g(e,t){return e.map(e=>nm(e.component,{...t},e.id))}function Hg(e,t){const n=e.getDocumentSnapshot();if(0===t.length)return n;const i=new Set(n.records.map(e=>e.id)),o=t.filter(Ng).filter(e=>!i.has(e.id));return{...n,records:[...n.records,...o]}}function Ng(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&"string"==typeof e.id}function Og(){return"undefined"==typeof indexedDB?Promise.resolve(null):(dw||(dw=new Promise((e,t)=>{const n=indexedDB.open("land.canvas.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(sw),e.objectStoreNames.contains("imageBlobs")||e.createObjectStore(aw)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),dw=null}),e(t)}),n.addEventListener("error",()=>{dw=null,t(n.error)})})),dw)}async function Wg(e,t){if(0===t.length)return[];const n=await Og();return n?new Promise((i,o)=>{const r=n.transaction(e,"readonly"),s=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>i(a)),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),t.forEach((e,t)=>{const n=s.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>o(n.error))})}):null}async function Yg(e,t){if(0===t.length)return;const n=await Og();n&&await new Promise((i,o)=>{const r=n.transaction(e,"readwrite"),s=r.objectStore(e);r.addEventListener("complete",()=>i()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error));for(const[e,n]of t)s.put(n,e)})}function Xg(e={}){let t=[];return{async restore(n){const{documentSnapshot:i,sessionSnapshot:o}=await(async(e={})=>{const[t,n]=await(async e=>(await Wg("snapshots",e)??e.map(()=>null)).map(jg))([Vg(e),qg(e)]);return{documentSnapshot:t,sessionSnapshot:n}})(e),r=function(e,{documentSnapshot:t,sessionSnapshot:n}){let i=null,o=[];if(t){const n=((e,t)=>{const n=(({bindingUtils:e,renderableShapeTypes:t,shapeUtils:n})=>({modelShapeTypes:new Set([...n.values()].map(e=>e.type)),modelBindingTypes:new Set([...e.values()].map(e=>e.type)),renderableShapeTypes:t?new Set(t):void 0}))({bindingUtils:e.bindingUtils,shapeUtils:e.shapeUtils}),i=(({requirements:e,support:t})=>({modelShapeTypes:Ai(e.shapeTypes,t.modelShapeTypes),modelBindingTypes:Ai(e.bindingTypes,t.modelBindingTypes),renderableShapeTypes:t.renderableShapeTypes?Ai(e.shapeTypes,t.renderableShapeTypes):[]}))({requirements:Mi(t),support:n});if(0===i.modelShapeTypes.length&&0===i.modelBindingTypes.length)return{kind:"full",snapshot:t};const o=(({snapshot:e,support:t})=>{const n=Ue(e,"document"),i=new Set,o=new Set,r=new Set,s=new Set,a=[];for(const l of n.records)Ri(l)&&"shape"===l.typeName&&"string"==typeof l.type&&!t.modelShapeTypes.has(l.type)&&("string"==typeof l.id&&l.id.startsWith("shape:")&&i.add(l.id),o.add(l.type));const d=n.records.filter(e=>{if(!Ri(e))return!0;if("shape"===e.typeName&&"string"==typeof e.type)return!!t.modelShapeTypes.has(e.type)||(a.push(e),!1);if("binding"===e.typeName&&"string"==typeof e.type){const n=t.modelBindingTypes.has(e.type),o=!i.has(e.fromId)&&!i.has(e.toId);return!(!n||!o)||("string"==typeof e.id&&e.id.startsWith("binding:")&&r.add(e.id),s.add(e.type),a.push(e),!1)}return!0});return{snapshot:{schemaVersion:n.schemaVersion,records:d},removedShapeIds:Li(i),removedShapeTypes:Li(o),removedBindingIds:Li(r),removedBindingTypes:Li(s),removedRecords:a}})({snapshot:t,support:n});return{kind:"partial",snapshot:o.snapshot,removedBindingIds:o.removedBindingIds,removedBindingTypes:o.removedBindingTypes,removedShapeIds:o.removedShapeIds,removedShapeTypes:o.removedShapeTypes,preservedRecords:o.removedRecords,unsupportedBindingTypes:i.modelBindingTypes,unsupportedShapeTypes:i.modelShapeTypes}})(e,t);"partial"===n.kind&&(r=n,console.warn("[land] Restored a persisted canvas snapshot with unsupported document records preserved for round-trip persistence.",{removedBindingIds:r.removedBindingIds,removedBindingTypes:r.removedBindingTypes,removedShapeIds:r.removedShapeIds,removedShapeTypes:r.removedShapeTypes,unsupportedBindingTypes:r.unsupportedBindingTypes,unsupportedShapeTypes:r.unsupportedShapeTypes}),o=n.preservedRecords,i={kind:"preserving-unsupported-records",preservedRecordCount:n.preservedRecords.length,unsupportedBindingTypes:n.unsupportedBindingTypes,unsupportedShapeTypes:n.unsupportedShapeTypes}),e.loadDocumentSnapshot(n.snapshot,{source:"system"})}var r;return n&&e.loadSessionSnapshot(n,{source:"system"}),e.history.clear(),{autoPersistence:"enabled",preservedUnsupportedRecords:o,status:i}}(n,{documentSnapshot:i,sessionSnapshot:o});return t=r.preservedUnsupportedRecords??[],r},start(n){const i=new lw(n,{getDocumentSnapshot:()=>Hg(n,t),options:e});return i.start(),()=>i.stop()},flushSnapshot:n=>Kg(n,e,{documentSnapshot:Hg(n,t)}),discardUnsupportedRecords:async n=>(await Kg(n,e),t=[],{autoPersistence:"enabled",status:null})}}async function Kg(e,t={},{documentSnapshot:n=e.getDocumentSnapshot()}={}){const i=JSON.stringify(n),o=JSON.stringify(e.getSessionSnapshot());await Yg(sw,[[Vg(t),i],[qg(t),o]])}function Vg(e){return e.storageNamespace?`${e.storageNamespace}.document`:"land.canvas.document"}function qg(e){return e.storageNamespace?`${e.storageNamespace}.session`:"land.canvas.session"}function jg(e){if("string"!=typeof e)return null;try{return JSON.parse(e)}catch{return null}}function Gg(e){return e.get(cw)}async function Zg({context:e,services:t}){const n=Gg(t);if(!n)return null;const i=e.editor.createClipboardPayloadFromSelection();return i?(await n.write(i),i):null}async function Qg({atMenuPoint:e=!1,context:t,services:n}){const i=Gg(n);if(!i)return;const o=await i.read();o&&t.editor.pasteClipboardPayload({payload:o,pagePoint:Jg({atMenuPoint:e,context:t}),source:"user"})}function Jg({atMenuPoint:e,context:t}){return e&&ef(t)?t.menu.anchor.pagePoint:t.editor.inputs.state.get().currentPagePoint??t.editor.viewportPageBoundsSignal.get()?.center??void 0}function ef(e){return"menu"in e}async function tf(e){const t=await(async(e,t)=>(await Wg(e,[t]))?.[0]??null)(aw,e);return t instanceof Blob?t:null}async function nf(e){const t=await tf(e);return t?new Promise((e,n)=>{const i=new FileReader;i.addEventListener("load",()=>{e("string"==typeof i.result?i.result:null)}),i.addEventListener("error",()=>{n(i.error)}),i.readAsDataURL(t)}):null}async function of(e){await(async(e,t)=>{const n=await Og();n&&await new Promise((i,o)=>{const r=n.transaction(e,"readwrite"),s=r.objectStore(e);r.addEventListener("complete",()=>i()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),s.delete(t)})})(aw,e)}function rf(e,t){const n=e.getAsset(t);if(!Iu(n)||"local"!==n.props.source.kind)return null;const{storageKey:i}=n.props.source;return i.length>0?i:null}function sf(e){const t=new Set;for(const n of e.getAssets())Iu(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&t.add(n.props.source.storageKey);return t}function af(e){return new Promise((t,n)=>{const i=new Image;i.addEventListener("load",()=>{t({width:i.naturalWidth||i.width,height:i.naturalHeight||i.height})}),i.addEventListener("error",()=>{n(new Error("Could not decode image file."))}),i.src=e})}async function df(e){const t=cf(e)?e:e.blob,n=(cf(e),e.name),i=cf(e)?e.type:e.mimeType||e.blob.type,o=URL.createObjectURL(t),r=await af(o).finally(()=>{URL.revokeObjectURL(o)}),{storageKey:s}=await async function(e){const t="undefined"!=typeof crypto&&"randomUUID"in crypto?`${Sw}${crypto.randomUUID()}`:`${Sw}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for image storage.");return await Yg(aw,[[t,e]]),{storageKey:t}}(t);return{name:n||"Image",source:{kind:"local",storageKey:s,...!cf(e)&&e.originalUrl?{originalUrl:e.originalUrl}:{}},mimeType:i||"image/png",fileSize:t.size,width:r.width,height:r.height}}async function lf({name:e,url:t}){const n=await fetch(t);if(!n.ok)throw new Error(`Could not download image URL (${n.status}).`);const i=await n.blob();return df({blob:i,name:e||uf(t)||"Image",mimeType:i.type||n.headers.get("content-type")||void 0,originalUrl:t})}function cf(e){return"undefined"!=typeof File&&e instanceof File}function uf(e){try{const t=new URL(e).pathname.split("/").filter(Boolean).at(-1);return t?decodeURIComponent(t):null}catch{return null}}function hf(e){if(!e)return null;const t=(e=>{for(const t of e)if(t.type.startsWith("image/"))return t;return null})(e.files);if(t)return t;for(const n of Array.from(e.items)){if("file"!==n.kind||!n.type.startsWith("image/"))continue;const e=n.getAsFile();if(e?.type.startsWith("image/"))return e}return null}function pf(e,t){return function(e,t,n){return e.screenToPage(((e,t=Ir())=>{if(!t)return new wm(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new wm(e.clientX-n.left,e.clientY-n.top)})(t,n))}(e,t)}function gf({filename:e,url:t}){const n=document.createElement("a");n.href=t,n.download=e,n.click()}async function ff({blob:e,filename:t}){const n=URL.createObjectURL(e);try{gf({filename:t,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function mf(e,t){return e.commands.createAsset({type:"image",props:{w:t.width,h:t.height,name:t.name,source:t.source,mimeType:t.mimeType,fileSize:t.fileSize,isAnimated:"image/gif"===t.mimeType}},{source:"user"})}function Sf(e,t){return e.getDocumentSnapshot().records.some(e=>"shape"===e.typeName&&e.props.assetId===t)}async function yf({editor:e,imageObjectUrls:t,pagePoint:n,size:i,flushSnapshot:o,source:r,strategy:s="auto"}){if("file"===r.type)return Cf(r.file)?xf({editor:e,imageObjectUrls:t,input:await df(r.file),pagePoint:n,size:i,flushSnapshot:o}):null;if("blob"===r.type)return Cf(r.blob)?xf({editor:e,imageObjectUrls:t,input:await df(r),pagePoint:n,size:i,flushSnapshot:o}):null;if("copy"===s)return xf({editor:e,imageObjectUrls:t,input:await lf(r),pagePoint:n,size:i,flushSnapshot:o});if("link"===s)return bf({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:i,flushSnapshot:o,copyInBackground:!1});try{return await bf({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:i,flushSnapshot:o,copyInBackground:!0})}catch{return xf({editor:e,imageObjectUrls:t,input:await lf(r),pagePoint:n,size:i,flushSnapshot:o})}}async function bf({copyInBackground:e,editor:t,flushSnapshot:n,imageObjectUrls:i,pagePoint:o,size:r,source:s}){const a=await(async({name:e,url:t})=>{const n=await af(t);return{name:e||uf(t)||"Image",source:{kind:"remote",url:t},mimeType:null,width:n.width,height:n.height}})(s),d={kind:"remote",url:s.url,...e?{copyState:{status:"pending-local-copy"}}:{}},l=await xf({editor:t,imageObjectUrls:i,input:{...a,source:d},pagePoint:o,size:r,flushSnapshot:n,altText:s.altText}),c=l?t.getShape(l):null,u=vu(c)?c.props.assetId:null;return e&&u&&If({assetId:u,editor:t,flushSnapshot:n,imageObjectUrls:i,source:s}),l}async function xf({editor:e,imageObjectUrls:t,input:n,pagePoint:i,size:o,flushSnapshot:r,altText:s}){const a="local"===n.source.kind?n.source.storageKey:null;a&&await t.preload(a);let d=null;try{const t=mf(e,n);d=t.id;const a=o??(({height:e,width:t})=>{const n=Math.min(1,360/Math.max(t,e));return{w:Math.max(24,Math.round(t*n)),h:Math.max(24,Math.round(e*n))}})({width:t.props.w,height:t.props.h}),l=e.viewportPageBoundsSignal.get(),c=i??l?.center??e.screenToPage(new wm(360,240)),[u]=e.commands.createShapes([{type:"image",x:Math.round(c.x-a.w/2),y:Math.round(c.y-a.h/2),props:{...a,assetId:t.id,crop:null,altText:s??n.name}}],{source:"user"});return u?(e.commands.setSelectedShapeIds([u.id],{source:"user"}),await(r?.(e)),u.id):null}catch(l){throw d&&e.commands.deleteAsset(d,{source:"system"}),a&&(t.release(a),await of(a)),l}}async function If({assetId:e,editor:t,flushSnapshot:n,imageObjectUrls:i,source:o}){try{const r=await lf(o),s="local"===r.source.kind?r.source.storageKey:null;if(!s)return;await i.preload(s);const a=t.getAsset(e);if(!Iu(a)||"remote"!==a.props.source.kind||a.props.source.url!==o.url||!Sf(t,e))return i.release(s),void(await of(s));t.commands.updateAsset({id:e,props:{w:r.width,h:r.height,name:r.name,source:r.source,mimeType:r.mimeType,fileSize:r.fileSize,isAnimated:"image/gif"===r.mimeType}},{source:"system"}),await(n?.(t))}catch(r){await(async({assetId:e,editor:t,error:n,flushSnapshot:i,url:o})=>{const r=t.getAsset(e);Iu(r)&&"remote"===r.props.source.kind&&r.props.source.url===o&&(t.commands.updateAsset({id:e,props:{source:{kind:"remote",url:o,copyState:{status:"copy-failed",errorMessage:Tf(n)}}}},{source:"system"}),await(i?.(t)))})({assetId:e,editor:t,error:r,flushSnapshot:n,url:o.url})}}async function vf({editor:e,file:t,imageObjectUrls:n,flushSnapshot:i}){if(!Cf(t))return;const[o]=e.getSelectedShapes();if(!vu(o)||o.isLocked)return;const r=await df(t);await Pf({editor:e,flushSnapshot:i,imageObjectUrls:n,input:r,nextProps:{crop:null,altText:r.name},shape:o})}async function wf({editor:e,imageObjectUrls:t}){const[n]=e.getSelectedShapes();if(!vu(n)||!n.props.assetId)return;const i=e.getAsset(n.props.assetId);if(!Iu(i))return;const o="string"==typeof i.props.name&&i.props.name.length>0?i.props.name:"land-image";if("remote"===i.props.source.kind)return void(await(async({filename:e,url:t})=>{try{const n=await fetch(t);if(!n.ok)throw new Error(`Could not download image URL (${n.status}).`);await ff({blob:await n.blob(),filename:e})}catch(n){console.warn("Could not download remote image; opening URL instead.",n),(e=>{const t=document.createElement("a");t.href=e,t.rel="noreferrer",t.target="_blank",t.click()})(t)}})({filename:o,url:i.props.source.url}));const r=i.props.source.storageKey;if(!r)return;const s=await tf(r);if(s)return void(await ff({blob:s,filename:o}));const a=t.resolve(r);a&&gf({filename:o,url:a})}async function Pf({editor:e,flushSnapshot:t,imageObjectUrls:n,input:i,nextProps:o,shape:r}){const s=r.props.assetId,a="local"===i.source.kind?i.source.storageKey:null;a&&await n.preload(a);let d=null;try{const n=mf(e,i);d=n.id,e.commands.updateShapes([{id:r.id,props:{assetId:n.id,...o}}],{source:"user"}),e.commands.setSelectedShapeIds([r.id],{source:"user"}),await(t?.(e))}catch(l){if(d){const t=e.getShape(r.id);vu(t)&&t.props.assetId===d&&e.commands.updateShapes([{id:r.id,props:{assetId:s}}],{source:"system"}),e.commands.deleteAsset(d,{source:"system"})}throw a&&(n.release(a),await of(a)),l}if(s&&!Sf(e,s)){e.commands.deleteAsset(s,{source:"user"});try{await(t?.(e))}catch{}}}async function kf(e){try{const t=await fetch(e);if(!t.ok)return null;const n=await t.blob();return Cf(n)?n:null}catch{return null}}function Cf(e){return!e.type||e.type.startsWith("image/")}function Tf(e){return e instanceof Error?e.message:String(e)}function Ef({flushSnapshot:e}={}){return{token:bw,create(){const t=function(){const e=new Map,t=new Map,n=async n=>{const i=e.get(n);if(i)return i;const o=t.get(n);if(o)return o;const r=tf(n).then(t=>{if(!t)return null;const i=URL.createObjectURL(t);return e.set(n,i),i}).finally(()=>{t.delete(n)});return t.set(n,r),r};return{async preloadForEditor(e){await Promise.all(Array.from(sf(e)).map(e=>n(e)))},preload:n,resolve:t=>e.get(t)??null,resolveAssetUrl(t,n){const i=((e,t)=>{const n=e.getAsset(t);return Iu(n)&&"remote"===n.props.source.kind&&n.props.source.url.length>0?n.props.source.url:null})(t,n);if(i)return i;const o=rf(t,n);return o?e.get(o)??null:null},release(n){const i=e.get(n);i&&(URL.revokeObjectURL(i),e.delete(n)),t.delete(n)},releaseAll(){for(const t of e.values())URL.revokeObjectURL(t);e.clear(),t.clear()}}}(),n=new Set,i=(i,o)=>{if(n.has(o))return;const r=i.getAsset(o);Iu(r)&&"remote"===r.props.source.kind&&"pending-local-copy"===r.props.source.copyState?.status&&(n.add(o),If({assetId:o,editor:i,flushSnapshot:e,imageObjectUrls:t,source:{type:"url",url:r.props.source.url,name:r.props.name}}).finally(()=>{n.delete(o)}))};return{objectUrls:t,async cleanupAfterRestore(e){try{await(async({editor:e,objectUrls:t})=>{const n=sf(e),i=await async function(){return(await(async e=>{const t=await Og();return t?new Promise((n,i)=>{const o=t.transaction(e,"readonly"),r=o.objectStore(e).getAllKeys();o.addEventListener("abort",()=>i(o.error)),o.addEventListener("error",()=>i(o.error)),r.addEventListener("success",()=>{n([...r.result])}),r.addEventListener("error",()=>i(r.error))}):null})("imageBlobs"))?.map(String)??[]}(),o=[];for(const r of i)n.has(r)||(t?.release(r),await of(r),o.push(r));return o})({editor:e,objectUrls:t})}catch(n){console.warn("Could not clean up unreferenced image blobs.",n)}finally{(e=>{for(const t of e.getAssets())Iu(t)&&i(e,t.id)})(e)}},preloadForEditor:e=>t.preloadForEditor(e),resolveAssetUrl:(e,n)=>(i(e,n),t.resolveAssetUrl(e,n))}},dispose(e){e.objectUrls.releaseAll()}}}function Bf(e,t){if("undefined"!=typeof OffscreenCanvas){const n=new OffscreenCanvas(e,t),i=n.getContext("2d");if(!i)throw new Error("Could not create image smudge canvas context.");return{context:i,toBlob:e=>n.convertToBlob({type:e})}}const n=document.createElement("canvas");n.width=e,n.height=t;const i=n.getContext("2d");if(!i)throw new Error("Could not create image smudge canvas context.");return{context:i,toBlob:e=>new Promise((t,i)=>{n.toBlob(e=>{e?t(e):i(new Error("Could not encode image smudge canvas."))},e)})}}function Mf({context:e,crop:t,imageHeight:n,imageWidth:i,mask:o,shape:r,strokes:s}){if(0===s.length)return;const a=Zc(t),d={x:a.left*i,y:a.top*n,w:a.width*i,h:a.height*n},l=d.w/r.props.w,c=d.h/r.props.h,u=(Math.abs(l)+Math.abs(c))/2;e.save(),e.beginPath(),e.rect(d.x,d.y,d.w,d.h),e.clip(),e.lineCap="round",e.lineJoin="round";for(const h of s){const t=h.points[0];if(!t)continue;const n=Af(h.brush.opacity),i=Math.max(1,h.brush.size*u),r=h.brush.color??"#ffff00";e.globalAlpha=n,e.strokeStyle=o?"#ffffff":r,e.fillStyle=o?"#ffffff":r,e.lineWidth=i;const s=Rf({cropPixelRect:d,point:t,scaleX:l,scaleY:c});if(1!==h.points.length){e.beginPath(),e.moveTo(s.x,s.y);for(const t of h.points.slice(1)){const n=Rf({cropPixelRect:d,point:t,scaleX:l,scaleY:c});e.lineTo(n.x,n.y)}e.stroke()}else e.beginPath(),e.arc(s.x,s.y,i/2,0,2*Math.PI),e.fill()}e.restore()}function Rf({cropPixelRect:e,point:t,scaleX:n,scaleY:i}){return{x:e.x+t.x*n,y:e.y+t.y*i}}function Af(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):.45}function Lf(e){const t=e.trim();if(!t)return"Image smudged.png";const n=t.lastIndexOf(".");return n<=0?`${t} smudged.png`:`${t.slice(0,n)} smudged.png`}function Ff({editor:e,flushSnapshot:t,services:n}){const i=n.get(bw);if(!i)return null;const o={start(t){const n=t?.shapeId?e.getShape(t.shapeId):e.getSelectedShapes()[0];return!(!vu(n)||n.isLocked||!n.props.assetId)&&pu({brush:t?.brush,editor:e,shape:n})},setBrush:t=>fu(e,t),cancel(){gu(e)},confirm:n=>async function({editor:e,imageObjectUrls:t,flushSnapshot:n,replace:i=!0}){const o=mu(e);if(!o)return null;const r=e.getShape(o.shapeId);if(!vu(r)||r.isLocked||!r.props.assetId)return null;const s=e.getAsset(r.props.assetId);if(!Iu(s))return null;const a=r.props.assetId,d=await(async({asset:e,imageObjectUrls:t})=>{if("remote"===e.props.source.kind)return kf(e.props.source.url);const n=e.props.source.storageKey,i=await tf(n);if(i)return i;const o=t.resolve(n);return o?kf(o):null})({asset:s,imageObjectUrls:t});if(!d)return null;const l=(e=>e.map(e=>({id:e.id,brush:{...e.brush},points:e.points.map(xu)})))(o.strokes),{imageBlob:c,maskBlob:u,height:h,width:p}=await(async({crop:e,shape:t,sourceBlob:n,strokes:i})=>{const o=await(async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{source:t,width:t.width,height:t.height,dispose(){t.close()}}}const t=URL.createObjectURL(e),n=new Image;return n.decoding="async",n.src=t,"function"==typeof n.decode?await n.decode():await new Promise((e,t)=>{n.onload=()=>e(),n.onerror=()=>t(new Error("Could not decode image."))}),{source:n,width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,dispose(){URL.revokeObjectURL(t)}}})(n);try{const n=o.width,r=o.height,s=Bf(n,r);s.context.drawImage(o.source,0,0,n,r),Mf({context:s.context,crop:e,imageHeight:r,imageWidth:n,mask:!1,shape:t,strokes:i});const a=Bf(n,r);return Mf({context:a.context,crop:e,imageHeight:r,imageWidth:n,mask:!0,shape:t,strokes:i}),{imageBlob:await s.toBlob("image/png"),maskBlob:await a.toBlob("image/png"),width:n,height:r}}finally{o.dispose()}})({crop:r.props.crop,shape:r,sourceBlob:d,strokes:l}),g={shapeId:r.id,sourceAssetId:a,imageBlob:c,maskBlob:u,width:p,height:h,crop:r.props.crop?{topLeft:{...r.props.crop.topLeft},bottomRight:{...r.props.crop.bottomRight}}:null,strokes:l};if(i){const i=e.getShape(r.id);if(!vu(i)||i.isLocked||i.props.assetId!==a)return null;await(async({blob:e,editor:t,flushSnapshot:n,imageObjectUrls:i,name:o,shape:r})=>{await Pf({editor:t,flushSnapshot:n,imageObjectUrls:i,input:await df({blob:e,name:o}),nextProps:{},shape:r})})({blob:c,editor:e,flushSnapshot:n,imageObjectUrls:t,name:Lf(s.props.name),shape:i})}return(e=>{lu(e).complete()})(e),g}({editor:e,flushSnapshot:t,imageObjectUrls:i.objectUrls,replace:n?.replace??!0}),isActive:()=>!!mu(e)};return(e=>{lu(e).registerConfirmHandler(e=>o.confirm(e))})(e),{insertImage:({source:n,pagePoint:o,size:r,strategy:s})=>yf({editor:e,imageObjectUrls:i.objectUrls,source:n,pagePoint:o,size:r,strategy:s,flushSnapshot:t}),async replaceSelectedImage({file:n}){if(!n.type.startsWith("image/"))return!1;const[o]=e.getSelectedShapes();return!(!vu(o)||o.isLocked||(await vf({editor:e,file:n,imageObjectUrls:i.objectUrls,flushSnapshot:t}),0))},downloadSelectedImageOriginal:()=>wf({editor:e,imageObjectUrls:i.objectUrls}),smudge:o}}function $f(e){return{async inline({editor:t,exportedShapeIds:n,svg:i}){let o=i;const r=new Set;for(const s of n){const n=t.getShape(s);if(!vu(n)||!n.props.assetId)continue;const i=n.props.assetId;if(r.has(i))continue;r.add(i);const a=rf(t,i);if(!a)continue;const d=e.objectUrls.resolve(a)??await e.objectUrls.preload(a);if(!d)continue;const l=await nf(a);l&&(o=o.split(d).join(l))}return o}}}function Uf({editor:e,flushSnapshot:t,services:n}){const i=n.get(bw);return i?nm(yw,{editor:e,hostBridge:n.get(vw)??void 0,imageAssetService:i,flushSnapshot:t}):null}function Df({persistence:e}){const{discardUnsupportedRecords:t,isDiscardingUnsupportedRecords:n,status:i}=e;if(!i)return null;const o=[...i.unsupportedShapeTypes,...i.unsupportedBindingTypes].join(", ");
|
|
68
|
-
return
|
|
69
|
-
return nm(Df,{persistence:e})}function _f(e){const[t]=e.selection.selectedShapes;return!(1!==e.selection.count||!t?.parentId.startsWith("shape:"))&&"frame"===e.editor.getShape(t.parentId)?.type}function Hf(e){return Math.min(1,Math.max(0,e))}function Nf(e={}){const t=((e={})=>({renderChrome:e.chrome,exposeControllerOnWindow:e.exposeControllerOnWindow??!1,onControllerDispose:e.onControllerDispose,onControllerReady:e.onControllerReady,windowKey:e.windowKey??"landCanvasKit"}))(e),n=(e=>void 0!==e.persistence?e.persistence:Xg({storageNamespace:e.storageNamespace??"land.canvasKit"}))(e),i=((e={})=>Jv.filter(([t])=>!1!==e[t]).map(([t,n])=>{if("text"===t){const t=e.text;return"object"==typeof t?_b.configure(t):n}return n}))(e.builtInExtensions??{}),o=[{id:"canvas-kit.keyboard-shortcuts",createFeature:()=>({id:"canvas-kit.keyboard-shortcuts",components:[{id:"canvas-kit.keyboard-shortcuts",slot:"controller",order:0,component:ww}]})},{id:"canvas-kit.clipboard",createFeature:()=>({id:"canvas-kit.clipboard",services:[{token:cw,create(){let e=null;return{async write(t){e=t},read:async()=>e,getMemoryPayload:()=>e}}}],createActions:({services:e})=>function(e){return[{id:uw,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!Gg(e),run({context:t}){Zg({context:t,services:e})}},{id:hw,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!Gg(e),run({context:t}){(async({context:e,services:t})=>{await Zg({context:e,services:t})&&e.editor.deleteSelection("user")})({context:t,services:e})}},{id:pw,isVisible:()=>!!Gg(e)?.getMemoryPayload(),isEnabled:()=>!!Gg(e)?.getMemoryPayload(),run({context:t}){Qg({context:t,services:e})}},{id:gw,isVisible:t=>ef(t)&&!!Gg(e)?.getMemoryPayload(),isEnabled:t=>ef(t)&&!!Gg(e)?.getMemoryPayload(),run({context:t}){ef(t)&&Qg({context:t,services:e,atMenuPoint:!0})}}]}(e),actionShortcuts:fw,contextMenuContributions:mw})},{id:"canvas-kit.tool",createFeature:()=>({id:"canvas-kit.tool",actions:Nw,toolbarContributions:Ww,contextMenuContributions:Ow})},{id:"canvas-kit.selection",createFeature:()=>({id:"canvas-kit.selection",actions:zw,actionShortcuts:Dw,toolbarContributions:Hw,contextMenuContributions:_w})},{id:"canvas-kit.view",createFeature:()=>({id:"canvas-kit.view",actions:Vw,contextMenuContributions:qw})},{id:"canvas-kit.persistence",createFeature:()=>({id:"canvas-kit.persistence",components:[{id:"canvas-kit.persistence-notice",slot:"workspace",order:1e3,component:zf}]})},{id:"canvas-kit.image",createFeature({canvasExtensionNames:e,persistence:t}){const n=[{key:"image",token:xw}];if(!e.has("image"))return{id:"canvas-kit.image",controllerSlots:n};const i=t?.flushSnapshot;return{id:"canvas-kit.image",requiresCanvasExtensions:["image"],services:[Ef({flushSnapshot:i}),{token:vw,create:()=>new Iw}],assetResolverTokens:[bw],createActions({services:e}){const t=e.get(bw),n=e.get(vw);return t&&n?(({hostBridge:e,imageObjectUrls:t})=>[{id:gI,run(){e.openInsertFilePicker()}},{id:hI,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return vu(t)&&!t.isLocked},run(){e.openReplaceFilePicker()}},{id:pI,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;if(!vu(t)||!t.props.assetId)return!1;const n=e.editor.getAsset(t.props.assetId);return!(!Iu(n)||"remote"!==n.props.source.kind&&!rf(e.editor,t.props.assetId))},run({context:e}){wf({editor:e.editor,imageObjectUrls:t})}}])({hostBridge:n,imageObjectUrls:t.objectUrls}):[]},apis:[{id:"canvas-kit.image",token:xw,create:({editor:e,services:t})=>Ff({editor:e,flushSnapshot:i,services:t})}],controllerSlots:n,canShowToolbarDuringEditing:e=>Pu(e)||ku(e),onBeforeCommand({commandId:e,context:t,editor:n}){var i;(!t||"image.smudge"!==(i=e)&&"image.smudge.cancel"!==i&&"image.smudge.confirm"!==i&&"image.smudge.brush-size"!==i&&"image.smudge.brush-color"!==i)&&(e=>{lu(e).cancelIfActive()})(t?.editor??n)},svgAssetInliners({services:e}){const t=e.get(bw);return t?[$f(t)]:[]},components:[{id:"canvas-kit.image-import",slot:"controller",order:100,component:e=>nm(Uf,{...e,flushSnapshot:i})}]}}},...e.hostExtensions??[]];return{[jw]:void 0,canvasExtensions:i,documentMeta:e.documentMeta?{...e.documentMeta}:void 0,id:e.id??"canvas-kit",config:t,hostExtensions:o,persistence:n,seedDocument:e.seedDocument,shouldSkipStoredSnapshots:e.shouldSkipStoredSnapshots,warnOnPluginRegistrationConflicts:e.warnOnPluginRegistrationConflicts??!1}}import{createContext as Of,createElement as Wf,forwardRef as Yf,memo as Xf,useCallback as Kf,useContext as Vf,useEffect as qf,useEffectEvent as jf,useLayoutEffect as Gf,useMemo as Zf,useRef as Qf,useState as Jf,useSyncExternalStore as em}from"react";import{Fragment as tm,jsx as nm,jsxs as im}from"react/jsx-runtime";import{createPortal as om}from"react-dom";import{EditorContent as rm,useEditor as sm}from"@tiptap/react";import{mergeAttributes as am}from"@tiptap/core";import{Bold as dm}from"@tiptap/extension-bold";import{Italic as lm}from"@tiptap/extension-italic";import{Link as cm}from"@tiptap/extension-link";import{Strike as um}from"@tiptap/extension-strike";import hm from"@tiptap/starter-kit";import{BubbleMenu as pm}from"@tiptap/react/menus";var gm=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),fm=0,mm=null,Sm=null,ym=class{name;current;isEqual;lastChangedEpoch;children=new Set;constructor(t,n,i){this.name=t,this.current=n,this.isEqual=i,this.lastChangedEpoch=e()}get(){return o(this),this.current}__unsafe__getWithoutCapture(){return this.current}__unsafe__setWithoutNotify(e){this.current=e}set(n){const i=this.current;return(this.isEqual?this.isEqual(i,n):Object.is(i,n))?i:(((e,t)=>{mm&&!mm.initialAtomValues.has(e)&&mm.initialAtomValues.set(e,t)})(this,i),t(),this.lastChangedEpoch=e(),this.current=n,(e=>{mm||r([e])})(this),n)}update(e){return this.set(e(this.current))}},bm=Symbol("UNINITIALIZED"),xm=class{name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch;children=new Set;state=bm;parents=[];parentEpochs=[];constructor(t,n,i){this.name=t,this.derive=n,this.isEqual=i,this.lastChangedEpoch=e(),this.lastCheckedEpoch=-1}get(){return o(this),this.__unsafe__getWithoutCapture()}__unsafe__getWithoutCapture(){if(this.lastCheckedEpoch===e())return this.state;if(this.state!==bm&&!this.haveParentsChanged())return this.lastCheckedEpoch=e(),this.state;let o,r;n(this.selfAsChild);try{o=this.derive(this.state===bm?bm:this.state)}finally{r=i()}for(const e of this.parents)r.has(e)||e.children.delete(this.selfAsChild);this.parents=[...r],this.parentEpochs=this.parents.map(e=>e.lastChangedEpoch);for(const e of this.parents)e.children.add(this.selfAsChild);return this.state!==bm&&(this.isEqual?this.isEqual(this.state,o):Object.is(this.state,o))||(this.state=o,t(),this.lastChangedEpoch=e()),this.lastCheckedEpoch=e(),this.state}get selfAsChild(){return this._selfAsChild||(this._selfAsChild={type:"computed",notify:()=>{},source:this}),this._selfAsChild}_selfAsChild=null;haveParentsChanged(){for(let e=0;e<this.parents.length;e++){const t=this.parents[e];if(t.__unsafe__getWithoutCapture(),t.lastChangedEpoch!==this.parentEpochs[e])return!0}return!1}},Im=class{name;fn;type="effect";parents=[];parentEpochs=[];lastReactedEpoch=-1;isActive=!1;scheduleEffect;constructor(e,t,n){this.name=e,this.fn=t,this.scheduleEffect=n?.scheduleEffect}selfAsChild={type:"effect",notify:()=>this.maybeSchedule()};attach(){this.isActive=!0,this.execute()}detach(){this.isActive=!1;for(const e of this.parents)e.children.delete(this.selfAsChild);this.parents=[],this.parentEpochs=[]}maybeSchedule(){this.isActive&&this.lastReactedEpoch!==e()&&(this.haveParentsChanged()?this.scheduleEffect?this.scheduleEffect(()=>this.execute()):this.execute():this.lastReactedEpoch=e())}execute(){if(this.isActive){for(const e of this.parents)e.children.delete(this.selfAsChild);n(this.selfAsChild);try{this.fn()}finally{const t=i();this.parents=[...t],this.parentEpochs=this.parents.map(e=>e.lastChangedEpoch);for(const e of this.parents)e.children.add(this.selfAsChild);this.lastReactedEpoch=e()}}}haveParentsChanged(){for(let e=0;e<this.parents.length;e++){const t=this.parents[e];if(t.__unsafe__getWithoutCapture(),t.lastChangedEpoch!==this.parentEpochs[e])return!0}return!1}},vm=class{registry=new Map;register(e){this.registry.set(e.type,e)}values(){return this.registry.values()}get(e){const t=this.registry.get(e);if(!t)throw new Error(`Missing binding util for type "${e}"`);return t}},wm=class e{x;y;constructor(e,t){this.x=e,this.y=t}add(t){return new e(this.x+t.x,this.y+t.y)}sub(t){return new e(this.x-t.x,this.y-t.y)}mul(t){return new e(this.x*t,this.y*t)}div(t){return new e(this.x/t,this.y/t)}len2(){return this.x*this.x+this.y*this.y}len(){return Math.sqrt(this.len2())}dist2(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}dist(e){return Math.sqrt(this.dist2(e))}rot(t){const n=Math.cos(t),i=Math.sin(t);return new e(this.x*n-this.y*i,this.x*i+this.y*n)}per(){return new e(-this.y,this.x)}uni(){return this.normalize()}normalize(){const t=this.len();return 0===t?new e(0,0):this.div(t)}equals(e){return this.x===e.x&&this.y===e.y}clone(){return new e(this.x,this.y)}static From(t,n){return new e(t,n)}static Zero(){return new e(0,0)}static Med(t,n){return new e((t.x+n.x)/2,(t.y+n.y)/2)}static Lrp(t,n,i){return new e(t.x+(n.x-t.x)*i,t.y+(n.y-t.y)*i)}static Dist(e,t){return e.dist(t)}static Dist2(e,t){return e.dist2(t)}static Angle(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}static Nudge(e,t,n){const i=t.sub(e),o=i.len();return 0===o?e.clone():e.add(i.mul(n/o))}static RotWith(t,n,i){const o=t.x-n.x,r=t.y-n.y,s=Math.cos(i),a=Math.sin(i);return new e(n.x+o*s-r*a,n.y+o*a+r*s)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}},Pm=class e{x;y;w;h;constructor(e,t,n,i){this.x=e,this.y=t,this.w=n,this.h=i}get minX(){return this.x}get minY(){return this.y}get maxX(){return this.x+this.w}get maxY(){return this.y+this.h}get center(){return new wm(this.x+this.w/2,this.y+this.h/2)}containsPoint(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}containsBox(e){return e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return this.minX<e.maxX&&this.maxX>e.minX&&this.minY<e.maxY&&this.maxY>e.minY}expand(t){return new e(this.x-t,this.y-t,this.w+2*t,this.h+2*t)}clone(){return new e(this.x,this.y,this.w,this.h)}static FromPoints(t){let n=1/0,i=1/0,o=-1/0,r=-1/0;for(const e of t)n=Math.min(n,e.x),i=Math.min(i,e.y),o=Math.max(o,e.x),r=Math.max(r,e.y);return new e(n,i,o-n,r-i)}},km=class e{a;b;c;d;e;f;constructor(e,t,n,i,o,r){this.a=e,this.b=t,this.c=n,this.d=i,this.e=o,this.f=r}static Identity(){return new e(1,0,0,1,0,0)}static Translate(t,n){return new e(1,0,0,1,t,n)}static Rotate(t){const n=Math.cos(t),i=Math.sin(t);return new e(n,i,-i,n,0,0)}static Scale(t,n){return new e(t,0,0,n,0,0)}compose(t){return new e(this.a*t.a+this.c*t.b,this.b*t.a+this.d*t.b,this.a*t.c+this.c*t.d,this.b*t.c+this.d*t.d,this.a*t.e+this.c*t.f+this.e,this.b*t.e+this.d*t.f+this.f)}applyToPoint(e){return new wm(this.a*e.x+this.c*e.y+this.e,this.b*e.x+this.d*e.y+this.f)}invert(){const t=this.a*this.d-this.b*this.c;if(0===t)return e.Identity();const n=1/t;return new e(this.d*n,-this.b*n,-this.c*n,this.a*n,(this.c*this.f-this.d*this.e)*n,(this.b*this.e-this.a*this.f)*n)}toCssString(){return`matrix(${this.a},${this.b},${this.c},${this.d},${this.e},${this.f})`}toSvgString(){return`matrix(${this.a} ${this.b} ${this.c} ${this.d} ${this.e} ${this.f})`}static ForShape(t,n,i,o=1,r=1){const s=e.Translate(t,n),a=0===i?e.Identity():e.Rotate(i),d=1===o&&1===r?e.Identity():e.Scale(o,r);return s.compose(a).compose(d)}},Cm="document:main",Tm="page:default",Em="session:main",Bm={x:0,y:0,z:1},Mm=class{registry=new Map;register(e){this.registry.set(e.type,e)}has(e){return this.registry.has(e)}values(){return this.registry.values()}get(e){const t=this.registry.get(e);if(!t)throw new Error(`Missing shape util for type "${e}"`);return t}},Rm=["fill-blue","fill-green","fill-red","fill-amber","fill-white","fill-slate","stroke-blue","stroke-green","stroke-red","stroke-orange","stroke-slate","stroke-muted","text-slate","text-blue","text-green","text-red"],Am=Object.fromEntries(Rm.map(e=>[e,`--land-shape-${e}`])),Lm={"fill-blue":"#dbeafe","fill-green":"#dcfce7","fill-red":"#fee2e2","fill-amber":"#fff7ed","fill-white":"#f8fafc","fill-slate":"#e2e8f0","stroke-blue":"#1d4ed8","stroke-green":"#15803d","stroke-red":"#dc2626","stroke-orange":"#ea580c","stroke-slate":"#334155","stroke-muted":"#94a3b8","text-slate":"#0f172a","text-blue":"#1d4ed8","text-green":"#15803d","text-red":"#dc2626"},Fm={"#dbeafe":"fill-blue","#eff6ff":"fill-blue","#dcfce7":"fill-green","#f0fdf4":"fill-green","#fee2e2":"fill-red","#fff7ed":"fill-amber","#f8fafc":"fill-white","#e2e8f0":"fill-slate","#1d4ed8":"stroke-blue","#2563eb":"stroke-blue","#15803d":"stroke-green","#16a34a":"stroke-green","#dc2626":"stroke-red","#ea580c":"stroke-orange","#334155":"stroke-slate","#94a3b8":"stroke-muted","#0f172a":"text-slate"},$m=class{registry=new Map;register(e){this.registry.set(e.type,e)}get(e){return this.registry.get(e)??null}has(e){return this.registry.has(e)}unregister(e){return this.registry.delete(e)}values(){return this.registry.values()}},Um=Symbol("editorStore"),Dm=class{marks=new Map;undoStack=[];redoStack=[];_state=s("store.history.state",{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0});state=this._state;clear(){this.marks.clear(),this.undoStack.length=0,this.redoStack.length=0,this.publishState()}mark(e){this.marks.set(e,((e,t=[])=>({id:e,forward:{added:[],updated:[],removed:[]},parentIds:t}))(e,[...this.marks.keys()]))}append(e){if(O(e))if(this.marks.size>0)for(const[t,n]of this.marks.entries())this.marks.set(t,V(n,e));else this.undoStack.push(q("change",e)),this.redoStack.length=0,this.publishState()}bailToMark(e){const t=this.marks.get(e);if(!t)return null;if(this.marks.delete(e),!O(t.forward))return null;const n=X(t.forward);for(const i of t.parentIds){const e=this.marks.get(i);e&&this.marks.set(i,V(e,n))}return n}squashToMark(e,t=e){const n=this.marks.get(e);if(!n)return null;if(this.marks.delete(e),!O(n.forward))return null;if(n.parentIds.some(e=>this.marks.has(e)))return null;const i=q(t,n.forward);return this.undoStack.push(i),this.redoStack.length=0,this.publishState(),i}undo(){const e=this.undoStack.pop()??null;return e?(this.redoStack.push(e),this.publishState(),e):null}redo(){const e=this.redoStack.pop()??null;return e?(this.undoStack.push(e),this.publishState(),e):null}getEntries(){return this.undoStack}publishState(){this._state.set({canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length})}},zm=class{recordsSignal;recordSignals=new Map;listeners=new Set;transactionDepth=0;draftRecords=null;pendingSource="system";constructor(e){this.recordsSignal=s("store.records",new Map(e.map(e=>[e.id,e])))}get(e){return this.getReadableRecords().get(e)}getRecordSignal(e){let t=this.recordSignals.get(e);return t||(t=a(`store.record.${e}`,()=>(this.recordsSignal.get(),this.get(e))),this.recordSignals.set(e,t)),t}getAll(){return Array.from(this.getReadableRecords().values())}getByScope(e){return this.getAll().filter(t=>"scope"in t&&t.scope===e)}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}atomic(e,t="system"){const n=0===this.transactionDepth;let i;n&&(this.draftRecords=new Map(this.recordsSignal.get()),this.pendingSource=t),this.transactionDepth+=1;try{e()}catch(o){i=o}if(this.transactionDepth-=1,n){const e=this.recordsSignal.get(),t=this.draftRecords,n=this.pendingSource;this.draftRecords=null,this.pendingSource="system";const o=t?Y(e,t):{added:[],updated:[],removed:[]};if(!i&&t&&O(o)){this.recordsSignal.set(t);const e={source:n,diff:o};for(const t of this.listeners)t(e)}}if(i)throw i}put(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)t.get(n.id)!==n&&t.set(n.id,n)},t)}remove(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)if(!t.delete(n))continue},t)}replaceAll(e,t="system"){const n=new Map(e.map(e=>[e.id,e])),i=Y(this.recordsSignal.get(),n);if(!O(i))return;this.recordsSignal.set(n);const o={source:t,diff:i};for(const r of this.listeners)r(o)}applyDiff(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e.added)t.set(n.id,n);for(const n of e.updated)t.set(n.after.id,n.after);for(const n of e.removed)t.delete(n.id)},t)}getMutableRecords(){if(!this.draftRecords)throw new Error("Store mutations must run inside store.atomic");return this.draftRecords}getReadableRecords(){return this.draftRecords??this.recordsSignal.get()}},_m=class{editor;buffer=new Dm;state=this.buffer.state;constructor(e){this.editor=e,_(this.editor).listen(e=>{this.handleStoreChange(e)})}clear(){this.buffer.clear()}mark(e){this.buffer.mark(e)}bailToMark(e){const t=this.buffer.bailToMark(e);t&&(_(this.editor).applyDiff(t,"history"),this.editor.syncAfterDocumentRestore())}squashToMark(e,t=e){this.buffer.squashToMark(e,t)}undo(){const e=this.buffer.undo();return!!e&&(_(this.editor).applyDiff(e.inverse,"history"),this.editor.syncAfterDocumentRestore(),!0)}redo(){const e=this.buffer.redo();return!!e&&(_(this.editor).applyDiff(e.forward,"history"),this.editor.syncAfterDocumentRestore(),!0)}getEntries(){return this.buffer.getEntries()}handleStoreChange(e){const t={added:(n=e.diff).added.filter(i=S),updated:n.updated.filter(e=>i(e.before)&&i(e.after)),removed:n.removed.filter(i)};var n,i;O(t)&&"user"===e.source&&this.buffer.append(t)}},Hm=class{editor;constructor(e){this.editor=e}getBindingsFromShape(e){return this.editor.queries.getBindingIdsFromShape(e).map(e=>this.editor.queries.getBinding(e)).filter(e=>!!e)}getBindingsToShape(e){return this.editor.queries.getBindingIdsToShape(e).map(e=>this.editor.queries.getBinding(e)).filter(e=>!!e)}getBindingsForShape(e){return this.editor.queries.getBindingIdsForShape(e).map(e=>this.editor.queries.getBinding(e)).filter(e=>!!e)}getConflictingBindings(e){const t=this.getExclusiveBindingKey(e);return t?this.getAllBindings().filter(n=>n.id!==e.id&&n.type===e.type&&this.getExclusiveBindingKey(n)===t):[]}canBind(e){const t=this.editor.getShape(e.fromId),n=this.editor.getShape(e.toId);return!(!t||!n)&&(this.editor.getBindingUtil(e).canBind?.(this.editor,e,{fromShape:t,toShape:n})??!0)}syncCreatedBinding(e,t){const n=this.editor.getBindingUtil(e).onBindingCreate?.(this.editor,e);this.applyEffect(n,t,e.id)}syncUpdatedBinding(e,t,n){const i=this.editor.getBindingUtil(t).onBindingUpdate?.(this.editor,e,t);this.applyEffect(i,n,t.id)}repairLoadedBindings(e){_(this.editor).atomic(()=>{const t=new Set;for(const n of this.getAllBindings()){const i=this.editor.getShape(n.fromId),o=this.editor.getShape(n.toId);if(!i||!o){_(this.editor).remove([n.id],e);continue}if(!this.canBind(n)){_(this.editor).remove([n.id],e);continue}const r=this.getExclusiveBindingKey(n);if(r){if(t.has(r)){_(this.editor).remove([n.id],e);continue}t.add(r)}const s=this.editor.getBindingUtil(n).onBindingLoad?.(this.editor,n);this.applyEffect(s,e,n.id)}},e)}handleShapeChanges(e,t,n){if(0!==e.length)for(const i of e)for(const e of this.getBindingsForShape(i.after.id)){if(n?.skipBindingIds?.has(e.id))continue;const o=e.fromId===i.after.id?"from":"to",r=this.editor.getBindingUtil(e).onAfterShapeChange?.(this.editor,e,{before:i.before,after:i.after,role:o});this.applyEffect(r,t,e.id)}}cleanupBindingsForDeletedShapes(e,t){if(0===e.length)return;const n=new Set(e),i=new Set;for(const o of e){const e=this.editor.getShape(o);if(e)for(const r of this.getBindingsForShape(o)){if(i.has(r.id))continue;i.add(r.id);const s=r.fromId===o?"from":"to";if("to"===s&&n.has(r.fromId)){_(this.editor).remove([r.id],t);continue}const a=this.editor.getBindingUtil(r).onBeforeDeleteShape?.(this.editor,r,{shape:e,role:s});this.applyEffect(a,t,r.id)}}}cleanupBindings(e,t){for(const n of e){const e=this.editor.getBinding(n);if(!e)continue;const i=this.editor.getBindingUtil(e).onBeforeDeleteBinding?.(this.editor,e);this.applyEffect(i,t,e.id)}}applyEffect(e,t,n){if(e){if(e.bindings&&e.bindings.length>0&&_(this.editor).put(e.bindings,t),e.shapes&&e.shapes.length>0){const i=e.shapes.flatMap(e=>{const t=this.editor.getShape(e.id);return t?[{before:t,after:e}]:[]});_(this.editor).put(e.shapes,t),this.handleShapeChanges(i,t,n?{skipBindingIds:new Set([n])}:void 0)}if(e.deleteShapeIds&&e.deleteShapeIds.length>0){const n=this.editor.getShapeIdsIncludingDescendants(e.deleteShapeIds);this.cleanupBindingsForDeletedShapes(n,t),_(this.editor).remove(Array.from(new Set(n)),t),this.editor.removeShapeIdsFromSelection(n,t),this.editor.removeShapeIdsFromEditingSession(n,t)}e.deleteBindingIds&&e.deleteBindingIds.length>0&&_(this.editor).remove(Array.from(new Set(e.deleteBindingIds)),t)}}getAllBindings(){return this.editor.queries.getBindings()}getExclusiveBindingKey(e){const t=this.editor.getBindingUtil(e).getExclusiveBindingKey?.(e);return t?`${e.type}:${t}`:null}},Nm=class{editor;_viewportScreenSizeSignal=s("editor.viewportScreenSize",{w:0,h:0});viewportScreenSizeSignal=this._viewportScreenSizeSignal;constructor(e){this.editor=e}getCurrentCamera(){return this.editor.currentCameraSignal.get()}getCamera(e=this.editor.getCurrentPageId()){return this.editor.sessionSignal.get().pageCameraById[e]??Bm}pageToScreen(e,t=this.editor.getCurrentPageId()){const n=this.getCamera(t);return new e.constructor((e.x-n.x)*n.z,(e.y-n.y)*n.z)}screenToPage(e,t=this.editor.getCurrentPageId()){const n=this.getCamera(t);return new e.constructor(e.x/n.z+n.x,e.y/n.z+n.y)}setCamera(e,t){const n=t?.source??"system",i=t?.pageId??this.editor.getCurrentPageId(),o=this.getCamera(i),r={x:"number"==typeof e.x?e.x:o.x,y:"number"==typeof e.y?e.y:o.y,z:ie("number"==typeof e.z?e.z:o.z)};this.editor.updateSession({pageCameraById:{...this.editor.sessionSignal.get().pageCameraById,[i]:r}},n)}panCamera(e,t="system"){const n=this.getCurrentCamera();this.setCamera({x:n.x+e.x/n.z,y:n.y+e.y/n.z},{source:t})}zoomCameraAtScreenPoint(e,t,n="system"){const i=ie(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=ie(t),o=this.screenToPage(e);this.setCamera({x:o.x-e.x/i,y:o.y-e.y/i,z:i},{source:n})}zoomAtViewportCenter(e,t="system"){const n=this.viewportScreenSizeSignal.get(),i=new wm(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new wm(t.w/2,t.h/2),i=this.screenToPage(n);this.editor.commands.setCamera({camera:{x:i.x-n.x,y:i.y-n.y,z:1}},{source:e})}setViewportScreenSize(e){const t={w:Math.max(0,e.w),h:Math.max(0,e.h)},n=this._viewportScreenSizeSignal.get();n.w===t.w&&n.h===t.h||this._viewportScreenSizeSignal.set(t)}},Om=new wm(24,24),Wm=class{editor;constructor(e){this.editor=e}createPayloadFromSelection(){return me(this.editor)}pastePayload(e){return this.editor.cancelInteractionForCommand(),Se(this.editor,e)}duplicateSelection(e={}){return this.editor.cancelInteractionForCommand(),((e,t={})=>{const n=me(e);return n?Se(e,{payload:n,offset:t.offset??Om,source:t.source}):[]})(this.editor,e)}},Ym=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},Xm=[],Km=[],Vm=class{editor;constructor(e){this.editor=e}buildInitialRecords(e,t,n={}){const i=this.parseInitialDocumentSnapshot(e,n),o=this.parseInitialSessionSnapshot(t);return[...i.records.length?i.records:[d(n),l()],o.records[0]??c()]}getDocumentSnapshot(){const e=this.editor.store.getAll();return{schemaVersion:1,records:[e.find(h)??d(),...this.editor.getPages(),...e.filter(m).sort((e,t)=>e.id.localeCompare(t.id)),...e.filter(p).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index):e.parentId.localeCompare(t.parentId)),...e.filter(f).sort((e,t)=>e.id.localeCompare(t.id))]}}getSessionSnapshot(){return{schemaVersion:1,records:[this.editor.sessionSignal.get()]}}loadDocumentSnapshot(e,t){const n=t?.source??"system",i=ze(e,this.editor.shapeUtils,this.editor.bindingUtils);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n});const o=this.editor.sessionSignal.get();_(this.editor).replaceAll([...i.records,o],n),this.syncAfterDocumentSnapshotLoad(n)}loadSessionSnapshot(e,t){const n=t?.source??"system",i=_e(e).records[0]??c(),o=_(this.editor).getAll().filter(S);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),_(this.editor).replaceAll([...o,i],n),this.ensureSessionIntegrity(),this.editor.syncToolStateFromSession(n)}syncAfterDocumentRestore(){this.ensureSessionIntegrity(),this.editor.syncShapeCounter(),this.editor.syncPageCounter(),this.editor.syncBindingCounter(),this.editor.syncAssetCounter()}ensureSessionIntegrity(){const e=_(this.editor),t=e.getAll(),n=t.filter(u).sort((e,t)=>e.index.localeCompare(t.index)),i=n[0]?.id??"page:default",o=new Set(n.map(e=>e.id)),r=t.filter(p),s=new Set(r.map(e=>e.id)),a=new Map(r.map(e=>[e.id,e])),d=new Map;for(const c of r)d.set(c.id,ue(c,a,o)??i);const l=t.find(e=>e.id===Em),h=g(l)?l:c(i),f={...h,currentPageId:o.has(h.currentPageId)?h.currentPageId:i,pageCameraById:this.repairCameraByPage(h.pageCameraById,o),pageSelectedShapeIdsById:this.repairSelectionByPage(h.pageSelectedShapeIdsById,o,s,d)};e.put([f],"system")}syncAfterDocumentSnapshotLoad(e){this.syncAfterDocumentRestore(),this.editor.history.clear(),this.editor.bindings.repairLoadedBindings(e)}repairCameraByPage(e,t){const n={};for(const i of t){const t=e[i]??Bm;n[i]={x:Number.isFinite(t.x)?t.x:Bm.x,y:Number.isFinite(t.y)?t.y:Bm.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:Bm.z))}}return n}repairSelectionByPage(e,t,n,i){const o={};for(const r of t)o[r]=Array.from(new Set((e[r]??[]).filter(e=>n.has(e)&&i.get(e)===r)));return o}parseInitialDocumentSnapshot(e,t){if(!e)return{schemaVersion:1,records:[d(t),l()]};try{return ze(e,this.editor.shapeUtils,this.editor.bindingUtils)}catch(n){if(!(n instanceof Ym))throw n;return{schemaVersion:1,records:[d(t),l()]}}}parseInitialSessionSnapshot(e){if(!e)return{schemaVersion:1,records:[c()]};try{return _e(e)}catch(t){if(!(t instanceof Ym))throw t;return{schemaVersion:1,records:[c()]}}}},qm=class{state=s("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:He(),screenVelocity:He(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1});setCurrentPointerPoint(e){this.state.update(t=>{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.shiftKey===e.shiftKey&&t.altKey===e.altKey&&t.ctrlKey===e.ctrlKey&&t.metaKey===e.metaKey&&t.accelKey===e.accelKey)return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,o=t.currentTimestamp??e.timestamp,r=e.timestamp-o;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:o,currentTimestamp:e.timestamp,pageVelocity:Ne(n,e.pagePoint,r),screenVelocity:Ne(i,e.screenPoint,r),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}})}handleEvent(e){switch(e.type){case"pointer":return void this.handlePointerEvent(e);case"keyboard":return void this.handleKeyboardEvent(e);case"wheel":return void this.handleWheelEvent(e);case"cancel":return void this.resetPointer()}}resetPointer(){this.state.update(e=>({...e,originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:He(),screenVelocity:He(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle"}))}handlePointerEvent(e){this.state.update(t=>{switch(e.name){case"pointer_down":return{...t,originPagePoint:e.pagePoint,currentPagePoint:e.pagePoint,previousPagePoint:e.pagePoint,originScreenPoint:e.screenPoint,currentScreenPoint:e.screenPoint,previousScreenPoint:e.screenPoint,currentTimestamp:e.timestamp,previousTimestamp:e.timestamp,pageVelocity:He(),screenVelocity:He(),pointerId:e.pointerId,pointerType:e.pointerType,buttons:e.buttons,isPointing:!0,isDragging:!1,dragPhase:"pointing",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey};case"pointer_move":{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.buttons===e.buttons&&Oe(t,e))return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,o=t.isDragging||(t.originPagePoint??e.pagePoint).dist2(e.pagePoint)>=9,r=t.currentTimestamp??e.timestamp,s=e.timestamp-r;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:r,currentTimestamp:e.timestamp,pageVelocity:Ne(n,e.pagePoint,s),screenVelocity:Ne(i,e.screenPoint,s),buttons:e.buttons,isDragging:o,dragPhase:o?"dragging":"pointing",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}case"pointer_up":case"pointer_cancel":return{...t,previousPagePoint:t.currentPagePoint,previousScreenPoint:t.currentScreenPoint,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:t.currentTimestamp,currentTimestamp:e.timestamp,pageVelocity:He(),screenVelocity:He(),buttons:e.buttons,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}})}handleKeyboardEvent(e){this.state.update(t=>Oe(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}handleWheelEvent(e){this.state.update(t=>Oe(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},jm=class{editor;_brushBoxSignal=s("editor.brushBox",null);brushBoxSignal=this._brushBoxSignal;brushBoxActiveSignal=a("editor.brushBoxActive",()=>null!==this._brushBoxSignal.get());_erasingShapeIdsSignal=s("editor.erasingShapeIds",[]);erasingShapeIdsSignal=this._erasingShapeIdsSignal;erasingShapeIdsActiveSignal=a("editor.erasingShapeIdsActive",()=>this._erasingShapeIdsSignal.get().length>0);_eraserTrailSignal=s("editor.eraserTrail",[]);eraserTrailSignal=this._eraserTrailSignal;eraserTrailActiveSignal=a("editor.eraserTrailActive",()=>this._eraserTrailSignal.get().length>1);_laserTrailSignal=s("editor.laserTrail",null);laserTrailSignal=this._laserTrailSignal;laserTrailActiveSignal=a("editor.laserTrailActive",()=>null!==this._laserTrailSignal.get());nextLaserSessionId=1;_bindingPreviewSignal=s("editor.bindingPreview",null);bindingPreviewSignal=this._bindingPreviewSignal;bindingPreviewActiveSignal=a("editor.bindingPreviewActive",()=>null!==this._bindingPreviewSignal.get());_terminalBindingGuidesSignal=s("editor.terminalBindingGuides",[]);terminalBindingGuidesSignal=this._terminalBindingGuidesSignal;_dropTargetShapeIdSignal=s("editor.dropTargetShapeId",null);dropTargetShapeIdSignal=this._dropTargetShapeIdSignal;_hoveredShapeIdSignal=s("editor.hoveredShapeId",null);hoveredShapeIdSignal=this._hoveredShapeIdSignal;_selectionTranslationActiveSignal=s("editor.selectionTranslationActive",!1);selectionTranslationActiveSignal=this._selectionTranslationActiveSignal;terminalBindingResolver=(e,t)=>(({rawPagePoint:e})=>({pagePoint:e.clone(),binding:null,preview:null}))(t);constructor(e){this.editor=e}setBrushBox(e){ae(this._brushBoxSignal.get(),e)||this._brushBoxSignal.set(e?e.clone():null)}getErasingShapeIds(){return[...this._erasingShapeIdsSignal.get()]}setErasingShapeIds(e){const t=Array.from(new Set(e));oe(this._erasingShapeIdsSignal.get(),t)||this._erasingShapeIdsSignal.set(t)}clearErasingShapeIds(){this.setErasingShapeIds([])}getEraserTrail(){return this._eraserTrailSignal.get().map(e=>e.clone())}setEraserTrail(e){se(this._eraserTrailSignal.get(),e)||this._eraserTrailSignal.set(e.map(e=>e.clone()))}clearEraserTrail(){this.setEraserTrail([])}startLaserTrail(){const e=this.nextLaserSessionId++;return this._laserTrailSignal.set({sessionId:e,phase:"active",points:[]}),e}setLaserTrail(e,t){const n=this._laserTrailSignal.get();n&&n.sessionId===e&&("active"===n.phase&&se(n.points,t)||this._laserTrailSignal.set({sessionId:e,phase:"active",points:t.map(e=>e.clone())}))}finishLaserTrail(e){const t=this._laserTrailSignal.get();t&&t.sessionId===e&&"ending"!==t.phase&&this._laserTrailSignal.set({...t,phase:"ending"})}clearLaserTrail(e){const t=this._laserTrailSignal.get();t&&t.sessionId===e&&this._laserTrailSignal.set(null)}setBindingPreview(e){var t,n;(t=this._bindingPreviewSignal.get())===(n=e)||(t&&n?t.terminal===n.terminal&&t.targetShapeId===n.targetShapeId&&re(t.rawPagePoint,n.rawPagePoint)&&re(t.resolvedPagePoint,n.resolvedPagePoint)&&(t.guidePath??null)===(n.guidePath??null):t===n)||this._bindingPreviewSignal.set(e?{...e,rawPagePoint:e.rawPagePoint.clone(),resolvedPagePoint:e.resolvedPagePoint.clone()}:null)}setTerminalBindingGuides(e){const t=e??[];((e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!Ke(i,o))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(We))}setDropTargetShapeId(e){this._dropTargetShapeIdSignal.get()!==e&&this._dropTargetShapeIdSignal.set(e)}setHoveredShapeId(e){this._hoveredShapeIdSignal.get()!==e&&this._hoveredShapeIdSignal.set(e)}setSelectionTranslationActive(e){this._selectionTranslationActiveSignal.get()!==e&&this._selectionTranslationActiveSignal.set(e)}setSnapIndicators(e){e?this.editor.snaps.setIndicators(e):this.editor.snaps.clearIndicators()}setTerminalBindingResolver(e){this.terminalBindingResolver=e}resolveTerminalBinding(e){return this.terminalBindingResolver(this.editor,e)}clearSelectionTransients(){this.setBrushBox(null),this.clearErasingShapeIds(),this.clearEraserTrail(),this.setBindingPreview(null),this.setTerminalBindingGuides(null),this.setDropTargetShapeId(null),this.setHoveredShapeId(null),this.setSelectionTranslationActive(!1),this.setSnapIndicators(null)}},Gm=.001,Zm=class{editor;stateSignal;currentPageShapeIdsSignal;currentPageShapesSignal;selectionGeometrySignal;selectionPageOutlineVerticesSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionHasRotationSignal;selectionRotationSignal;selectionRotationCenterSignal;selectionHasCompatibleRotationSignal;selectionAnchorPagePointSignal;stateAtom;shapeQuerySignals=new Map;constructor(e){this.editor=e;const t=_(this.editor);this.stateAtom=s("editor.query.state",(e=>{const t=e.filter(u).sort((e,t)=>e.index.localeCompare(t.index)),n=e.filter(p).sort((e,t)=>e.parentId===t.parentId?((e,t)=>e.index.localeCompare(t.index))(e,t):e.parentId.localeCompare(t.parentId)),i=e.filter(f).sort(st),o=new Map,r=new Map,s=new Map,a=new Map(n.map(e=>[e.id,e])),d=new Map,l=new Map,c=new Map,h=new Map;for(const u of n)nt(r,u.parentId,u.id);const g=(e,t)=>{for(const n of r.get(t)??[]){const t=a.get(n);t&&(nt(o,e,t.id),s.set(t.id,e),g(e,t.id))}};for(const u of t)g(u.id,u.id);for(const u of i)d.set(u.id,u),it(l,u.fromId,u.id),it(c,u.toId,u.id),it(h,u.fromId,u.id),it(h,u.toId,u.id);return{pageShapeIdsByPage:o,childShapeIdsByParent:r,pageIdByShape:s,bindingById:d,bindingIdsByFromShape:l,bindingIdsByToShape:c,relatedBindingIdsByShape:h}})(Array.from(t.recordsSignal.get().values()))),this.stateSignal=this.stateAtom,t.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=a("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(this.editor.getCurrentPageId()),{isEqual:rt}),this.currentPageShapesSignal=a("editor.query.currentPageShapes",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.getShapeSignal(e).get()).filter(e=>!!e));const n=((e,t)=>{const n=a("editor.query.selectionGeometry",()=>mt(e,t),{isEqual:gt}),i=a("editor.query.selectionPageOutlineVertices",()=>n.get().outlineVertices,{isEqual:pt}),o=a("editor.query.selectionPageBounds",()=>n.get().pageBounds,{isEqual:ae}),r=a("editor.query.selectionFrameBounds",()=>n.get().frameBounds,{isEqual:ae}),s=a("editor.query.selectionRotation",()=>n.get().rotation);return{geometry:n,pageOutlineVertices:i,pageBounds:o,frameBounds:r,hasRotation:a("editor.query.selectionHasRotation",()=>n.get().hasRotation),rotation:s,rotationCenter:a("editor.query.selectionRotationCenter",()=>n.get().rotationCenter,{isEqual:re}),hasCompatibleRotation:a("editor.query.selectionHasCompatibleRotation",()=>n.get().hasCompatibleRotation),selectionAnchorPagePoint:a("editor.query.selectionAnchorPagePoint",()=>n.get().selectionAnchorPagePoint,{isEqual:re})}})(this.editor,e=>this.getShapeGeometrySnapshot(e));this.selectionGeometrySignal=n.geometry,this.selectionPageOutlineVerticesSignal=n.pageOutlineVertices,this.selectionPageBoundsSignal=n.pageBounds,this.selectionFrameBoundsSignal=n.frameBounds,this.selectionRotationSignal=n.rotation,this.selectionHasRotationSignal=n.hasRotation,this.selectionRotationCenterSignal=n.rotationCenter,this.selectionHasCompatibleRotationSignal=n.hasCompatibleRotation,this.selectionAnchorPagePointSignal=n.selectionAnchorPagePoint}getShapeIdsForPage(e){return[...this.getShapeIdsForPageSnapshot(e)]}getShapesForPage(e){return this.getShapeIdsForPageSnapshot(e).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getChildShapeIds(e){return[...this.getChildShapeIdsSnapshot(e)]}getChildShapes(e){return this.getChildShapeIdsSnapshot(e).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getDescendantShapeIds(e){const t=[],n=e=>{for(const i of this.getChildShapeIdsSnapshot(e))t.push(i),n(i)};return n(e),t}getPageIdForShape(e){return this.stateSignal.get().pageIdByShape.get(e)??null}getPageIdForShapeParent(e){return e.startsWith("page:")?this.editor.getPage(e)?e:null:this.getPageIdForShape(e)}getDescendantPageBounds(e){const t=[];for(const n of this.getDescendantShapeIds(e)){const e=this.getShapePageBounds(n);e&&t.push(e)}return kt(t)}getShapeSubtreePageBounds(e){const t=[],n=this.getShapePageBounds(e);n&&t.push(n);for(const i of this.getDescendantShapeIds(e)){const e=this.getShapePageBounds(i);e&&t.push(e)}return kt(t)}getShapeContainment(e,t){const n=this.editor.getShape(e);if(!n)return null;const i=this.getShapeGeometrySnapshot(e),o=this.getShapeGeometrySnapshot(t);if(!i||!o)return null;const r=this.editor.getShapeUtil(n),s=r.getLocalBounds(n),a=r.getLocalToPageTransform(n).invert();return o.outlineVertices.length>0&&o.outlineVertices.every(e=>s.containsPoint(a.applyToPoint(e)))?"inside":i.bounds.intersects(o.bounds)?"intersecting":"outside"}getContainingShapeParentId(e){const t=Array.from(new Set(e));if(0===t.length)return null;const n=t.map(e=>this.editor.getShape(e)).filter(e=>!!e);if(n.length!==t.length)return null;const i=this.getPageIdForShape(n[0].id);if(!i)return null;if(n.some(e=>this.getPageIdForShape(e.id)!==i))return null;const o=new Set;for(const l of n){o.add(l.id);for(const e of this.getDescendantShapeIds(l.id))o.add(e)}let r=null,s=1/0,a=-1;const d=this.stateSignal.get().pageShapeIdsByPage.get(i)??[];for(let l=0;l<d.length;l+=1){const e=d[l];if(o.has(e))continue;const t=this.editor.getShape(e);if(!t)continue;if(!Et(t,this.editor.getShapeUtil(t)))continue;if(!n.every(e=>this.editor.canUseShapeParent(t.id,e.id)))continue;if(!n.every(e=>"inside"===this.getShapeContainment(t.id,e.id)))continue;const i=this.getShapePageBounds(t.id);if(!i)continue;const c=i.w*i.h;(!r||c<s||c===s&&l>a)&&(r=t,s=c,a=l)}return r?.id??i}getContainingShapeParentIdAtPoint(e,t){const n=Array.from(new Set(e));if(0===n.length)return null;const i=n.map(e=>this.editor.getShape(e)).filter(e=>!!e);if(i.length!==n.length)return null;const o=this.getPageIdForShape(i[0].id);if(!o)return null;if(i.some(e=>this.getPageIdForShape(e.id)!==o))return null;const r=new Set;for(const c of i){r.add(c.id);for(const e of this.getDescendantShapeIds(c.id))r.add(e)}let s=null,a=1/0,d=-1;const l=this.stateSignal.get().pageShapeIdsByPage.get(o)??[];for(let c=0;c<l.length;c+=1){const e=l[c];if(r.has(e))continue;const n=this.editor.getShape(e);if(!n||this.editor.isShapeHidden(n.id))continue;const o=this.editor.getShapeUtil(n);if(!Et(n,o))continue;if(!i.every(e=>this.editor.canUseShapeParent(n.id,e.id)))continue;if(!this.editor.isPagePointInShapeClip(n.id,t))continue;const u=o.getLocalBounds(n),h=o.getLocalToPageTransform(n).invert();if(!u.containsPoint(h.applyToPoint(t)))continue;const p=this.getShapePageBounds(n.id);if(!p)continue;const g=p.w*p.h;(!s||g<a||g===a&&c>d)&&(s=n,a=g,d=c)}return s?.id??o}getContainingParentIdForShapeRecord(e){const t=this.getPageIdForShapeParent(e.parentId);if(!t)return null;const n=tt(e,this.editor.getShapeUtil(e));let i=null,o=1/0,r=-1;const s=this.stateSignal.get().pageShapeIdsByPage.get(t)??[];for(let a=0;a<s.length;a+=1){const t=this.editor.getShape(s[a]);if(!t||t.id===e.id)continue;const d=this.editor.getShapeUtil(t);if(!Et(t,d))continue;if(!this.editor.canUseShapeParent(t.id,e.id))continue;const l=this.getShapePageBounds(t.id);if(!l)continue;const c=d.getLocalBounds(t),u=d.getLocalToPageTransform(t).invert();if(!(n.outlineVertices.length>0&&n.outlineVertices.every(e=>c.containsPoint(u.applyToPoint(e)))))continue;const h=l.w*l.h;(!i||h<o||h===o&&a>r)&&(i=t,o=h,r=a)}return i?.id??t}getShapeClipAncestorIds(e){return[...this.getShapeClipAncestorIdsSignal(e).get()]}getShapeClipAncestorIdsSignal(e){return this.getShapeQuerySignals(e).clipAncestorIds}isPagePointInShapeClip(e,t){const n=this.editor.getShape(e);if(!n)return!1;for(const i of this.getShapeClipAncestorsForShape(n,e=>this.editor.getShape(e))){const e=this.editor.getShapeUtil(i),n=e.getChildClipLocalBounds(i);if(!n||!Ct(n))continue;const o=e.getLocalToPageTransform(i).invert().applyToPoint(t);if(!n.containsPoint(o))return!1}return!0}getShapeClippedPageBounds(e){let t=this.getShapePageBounds(e);if(!t)return null;for(const n of this.getShapeClipAncestors(e)){const e=this.getShapeChildClipPageBounds(n);if(!e)continue;const i=Tt(t,e);if(!i)return null;t=i}return t}getShapeClipAncestors(e){const t=this.editor.getShape(e);return t?this.getShapeClipAncestorsForShape(t,e=>this.editor.getShape(e)):[]}getShapeClipAncestorsForShape(e,t){const n=[],i=new Set;let o=e.parentId;for(;o.startsWith("shape:");){const e=o;if(i.has(e))break;i.add(e);const r=t(e);if(!r)break;const s=this.editor.getShapeUtil(r).getChildClipLocalBounds(r);s&&Ct(s)&&n.push(r),o=r.parentId}return n.reverse()}getShapeChildClipPageBounds(e){const t=this.editor.getShapeUtil(e),n=t.getChildClipLocalBounds(e);return n&&Ct(n)?(i=n,o=t.getLocalToPageTransform(e),Pm.FromPoints([new wm(i.minX,i.minY),new wm(i.maxX,i.minY),new wm(i.maxX,i.maxY),new wm(i.minX,i.maxY)].map(e=>o.applyToPoint(e)))):null;var i,o}getShapeIdsForPageSnapshot(e){return this.stateSignal.get().pageShapeIdsByPage.get(e)??[]}getChildShapeIdsSnapshot(e){return this.stateSignal.get().childShapeIdsByParent.get(e)??[]}handleStoreChange(e){for(const n of(e=>e.diff.removed.filter(p).map(e=>e.id))(e))this.shapeQuerySignals.delete(n);const t=_(this.editor);this.stateAtom.update(n=>((e,t,n)=>{const i=t.diff.added.filter(p),o=t.diff.updated.filter(ut),r=t.diff.removed.filter(p),s=t.diff.added.filter(f),a=t.diff.updated.filter(ht),d=t.diff.removed.filter(f),l=i.length>0||r.length>0||o.some(({before:e,after:t})=>e.parentId!==t.parentId||e.index!==t.index),c=s.length>0||d.length>0||a.some(({before:e,after:t})=>e.fromId!==t.fromId||e.toId!==t.toId),h=s.length>0||d.length>0||a.length>0;if(!l&&!h)return e;const g={pageShapeIdsByPage:new Map(e.pageShapeIdsByPage),childShapeIdsByParent:new Map(e.childShapeIdsByParent),pageIdByShape:new Map(e.pageIdByShape),bindingById:new Map(e.bindingById),bindingIdsByFromShape:new Map(e.bindingIdsByFromShape),bindingIdsByToShape:new Map(e.bindingIdsByToShape),relatedBindingIdsByShape:new Map(e.relatedBindingIdsByShape)};let m=!1;if(l){const t=e=>{const t=n(e);return p(t)?t.index:void 0},s=new Set,a=e=>{let t=e;const i=new Set;for(;t&&!i.has(t);){i.add(t);const e=n(t);if(!e)return null;if(u(e))return e.id;if(!p(e))return null;t=e.parentId}return null};for(const n of r){ct(g.childShapeIdsByParent,n.parentId,n.id);const t=e.pageIdByShape.get(n.id);t&&s.add(t)}for(const{before:n,after:i}of o){if(n.parentId===i.parentId&&n.index===i.index)continue;ct(g.childShapeIdsByParent,n.parentId,n.id),lt(g.childShapeIdsByParent,i.parentId,i,t);const o=e.pageIdByShape.get(n.id);o&&s.add(o);const r=a(i.parentId);r&&s.add(r)}for(const e of i)lt(g.childShapeIdsByParent,e.parentId,e,t);for(const e of i){const t=a(e.parentId);t&&s.add(t)}if(s.size>0){const t=new Map(e.pageShapeIdsByPage),i=new Map(e.pageIdByShape);for(const[n,r]of e.pageIdByShape)s.has(r)&&i.delete(n);const o=(e,t)=>{const r=[];for(const s of g.childShapeIdsByParent.get(t)??[])n(s)&&(r.push(s),i.set(s,e),r.push(...o(e,s)));return r};for(const e of s){const n=o(e,e);n.length>0?t.set(e,n):t.delete(e)}g.pageShapeIdsByPage=t,g.pageIdByShape=i}m=!0}if(h){for(const e of d)m=g.bindingById.delete(e.id)||m;if(c){for(const e of d)m=ot(g.bindingIdsByFromShape,e.fromId,e.id)||m,m=ot(g.bindingIdsByToShape,e.toId,e.id)||m,m=ot(g.relatedBindingIdsByShape,e.fromId,e.id)||m,m=ot(g.relatedBindingIdsByShape,e.toId,e.id)||m;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(m=ot(g.bindingIdsByFromShape,e.fromId,e.id)||m,m=ot(g.bindingIdsByToShape,e.toId,e.id)||m,m=ot(g.relatedBindingIdsByShape,e.fromId,e.id)||m,m=ot(g.relatedBindingIdsByShape,e.toId,e.id)||m)}for(const e of s)g.bindingById.set(e.id,e),m=!0;for(const{after:e}of a)g.bindingById.set(e.id,e),m=!0;if(c){for(const e of s)m=dt(g.bindingIdsByFromShape,e.fromId,e,"from",e=>g.bindingById.get(e))||m,m=dt(g.bindingIdsByToShape,e.toId,e,"to",e=>g.bindingById.get(e))||m,m=dt(g.relatedBindingIdsByShape,e.fromId,e,"related",e=>g.bindingById.get(e))||m,m=dt(g.relatedBindingIdsByShape,e.toId,e,"related",e=>g.bindingById.get(e))||m;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(m=dt(g.bindingIdsByFromShape,t.fromId,t,"from",e=>g.bindingById.get(e))||m,m=dt(g.bindingIdsByToShape,t.toId,t,"to",e=>g.bindingById.get(e))||m,m=dt(g.relatedBindingIdsByShape,t.fromId,t,"related",e=>g.bindingById.get(e))||m,m=dt(g.relatedBindingIdsByShape,t.toId,t,"related",e=>g.bindingById.get(e))||m)}}return m?g:e})(n,e,e=>t.get(e)))}getShapeQuerySignals(e){let t=this.shapeQuerySignals.get(e);if(!t){const n=a(`editor.query.shapeBounds.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return this.editor.getShapeUtil(t).getBounds(t)},{isEqual:St}),i=a(`editor.query.shapeGeometry.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return tt(t,this.editor.getShapeUtil(t))},{isEqual:It});t={bounds:n,geometry:i,positionedToPageTransform:a(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return je(t,this.editor.getShapeUtil(t))},{isEqual:xt}),pageBounds:a(`editor.query.shapePageBounds.${e}`,()=>i.get()?.bounds,{isEqual:St}),clipAncestorIds:a(`editor.query.shapeClipAncestorIds.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();return t?this.getShapeClipAncestorsForShape(t,e=>this.editor.getShapeSignal(e).get()).map(e=>e.id):[]},{isEqual:rt})},this.shapeQuerySignals.set(e,t)}return t}getShapeGeometrySnapshot(e){return this.getShapeQuerySignals(e).geometry.get()}getShapePageBoundsSignal(e){return this.getShapeQuerySignals(e).pageBounds}getShapeGeometry(e){return(e=>{if(e)return{bounds:e.bounds.clone(),center:e.center.clone(),corners:e.corners.map(e=>e.clone()),outlineVertices:e.outlineVertices.map(e=>e.clone())}})(this.getShapeGeometrySnapshot(e))}getShapePositionedToPageTransform(e){return(t=this.getShapeQuerySignals(e).positionedToPageTransform.get())?new km(t.a,t.b,t.c,t.d,t.e,t.f):void 0;var t}getShapePageBounds(e){return vt(this.getShapePageBoundsSignal(e).get())??void 0}getShapeBounds(e){return vt(this.getShapeQuerySignals(e).bounds.get())??void 0}getShapePageCenter(e){return wt(this.getShapeGeometrySnapshot(e)?.center)??void 0}getShapePageCorners(e){return Pt(this.getShapeGeometrySnapshot(e)?.corners)}getShapePageOutlineVertices(e){return Pt(this.getShapeGeometrySnapshot(e)?.outlineVertices)}getSelectionPageOutlineVertices(){return Pt(this.selectionPageOutlineVerticesSignal.get())??[]}getSelectionPageBounds(){return vt(this.selectionPageBoundsSignal.get())??null}getSelectionFrameBounds(){return vt(this.selectionFrameBoundsSignal.get())??null}getSelectionRotation(){return this.selectionRotationSignal.get()}getSelectionHasRotation(){return this.selectionHasRotationSignal.get()}getSelectionRotationCenter(){return wt(this.selectionRotationCenterSignal.get())??null}getSelectionHasCompatibleRotation(){return this.selectionHasCompatibleRotationSignal.get()}getSelectionAnchorPagePoint(){return wt(this.selectionAnchorPagePointSignal.get())??null}getBinding(e){return this.stateSignal.get().bindingById.get(e)}getBindings(){return Array.from(this.stateSignal.get().bindingById.values()).sort(st)}getBindingIdsFromShape(e){return this.stateSignal.get().bindingIdsByFromShape.get(e)??[]}getBindingIdsToShape(e){return this.stateSignal.get().bindingIdsByToShape.get(e)??[]}getBindingIdsForShape(e){return this.stateSignal.get().relatedBindingIdsByShape.get(e)??[]}getBindingsFromShape(e){return this.getBindingIdsFromShape(e).map(e=>this.getBinding(e)).filter(e=>!!e)}getBindingsToShape(e){return this.getBindingIdsToShape(e).map(e=>this.getBinding(e)).filter(e=>!!e)}getBindingsForShape(e){return this.getBindingIdsForShape(e).map(e=>this.getBinding(e)).filter(e=>!!e)}},Qm=class{entries;cellSize;cells=new Map;order=new Map;constructor(e){this.entries=e,this.cellSize=(e=>{if(0===e.length)return 256;let t=0;for(const n of e)t+=Math.max(n.queryBounds.w,n.queryBounds.h);return Math.max(16,Math.round(t/e.length)||256)})(e);for(let t=0;t<e.length;t+=1){const n=e[t];n&&(this.order.set(n,t),this.insert(n))}}cellKey(e,t){return`${e}:${t}`}insert(e){const t=Math.floor(e.queryBounds.minX/this.cellSize),n=Math.floor(e.queryBounds.minY/this.cellSize),i=Math.floor(e.queryBounds.maxX/this.cellSize),o=Math.floor(e.queryBounds.maxY/this.cellSize);for(let r=n;r<=o;r+=1)for(let n=t;n<=i;n+=1){const t=this.cellKey(n,r),i=this.cells.get(t);i?i.push(e):this.cells.set(t,[e])}}search(e){const t=Math.floor(e.minX/this.cellSize),n=Math.floor(e.minY/this.cellSize),i=Math.floor(e.maxX/this.cellSize),o=Math.floor(e.maxY/this.cellSize);if((i-t+1)*(o-n+1)>this.entries.length)return this.entries.filter(t=>t.queryBounds.intersects(e));const r=new Set,s=[];for(let a=n;a<=o;a+=1)for(let n=t;n<=i;n+=1){const t=this.cells.get(this.cellKey(n,a));if(t)for(const n of t)r.has(n)||(r.add(n),n.queryBounds.intersects(e)&&s.push(n))}return s.length>1&&s.sort((e,t)=>(this.order.get(e)??0)-(this.order.get(t)??0)),s}},Jm=class{editor;queries;pageIndexSignals=new Map;constructor(e,t){this.editor=e,this.queries=t}getShapesInBounds(e,t){return this.getShapeIdsInBounds(e,t).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getShapeIdsInBounds(e,t){return this.getPageIndex(t?.pageId).search(e).filter(t=>t.shapeBounds.intersects(e)).map(e=>e.shapeId)}getShapesInViewport(e,t){return this.getShapesInBounds(e,t)}getShapeIdsInViewport(e,t){return this.getShapeIdsInBounds(e,t)}getShapeAtPoint(e,t){return this.getShapesAtPoint(e,t)[0]??null}getShapesAtPoint(e,t){const n=this.getPageIndex(t?.pageId).search((e=>new Pm(e.x-.5,e.y-.5,1,1))(e)),i=[];for(let o=n.length-1;o>=0;o-=1){const r=n[o];if(!r?.pointHitTestBounds.containsPoint(e))continue;const s=this.editor.getShape(r.shapeId);if(!s)continue;if(t?.filter&&!t.filter(s))continue;const a=this.editor.getShapeUtil(s),d=Je(s,e,a),l={editor:this.editor,pagePoint:e,positionedPoint:d};("bindingTarget"===t?.hitTest?a.hitTestBindingTarget(s,d,l):a.hitTest(s,d,l))&&i.push(s)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,o=((e,t,n)=>Pm.FromPoints([e,t]).expand(Math.max(.5,n)))(e,t,i),r=this.getPageIndex(n?.pageId).search(o),s=[];for(let a=r.length-1;a>=0;a-=1){const o=r[a];if(!o)continue;const d=this.queries.getShapeClippedPageBounds(o.shapeId);if(!d||!Mt(e,t,d.expand(i)))continue;const l=this.editor.getShape(o.shapeId);if(!l)continue;if(n?.filter&&!n.filter(l))continue;const c=this.editor.getShapeUtil(l),u=Je(l,e,c),h=Je(l,t,c);c.hitTestLineSegment(l,{editor:this.editor,pageStart:e,pageEnd:t,positionedStart:u,positionedEnd:h,margin:i})&&s.push(l)}return s}getPageIndexSignal(e){let t=this.pageIndexSignals.get(e);return t||(t=a(`editor.spatialIndex.page.${e}`,()=>{const t=this.queries.stateSignal.get().pageShapeIdsByPage.get(e)??[],n=[];for(const e of t){const t=this.editor.getShapeSignal(e).get();if(!t)continue;const i=this.editor.getShapeUtil(t),o=this.queries.getShapePageBoundsSignal(e).get();if(!o)continue;const r=Rt(i.getPointHitTestBounds(t,{editor:this.editor}),je(t,i)),s=Pm.FromPoints([new wm(o.minX,o.minY),new wm(o.maxX,o.maxY),new wm(r.minX,r.minY),new wm(r.maxX,r.maxY)]);n.push({shapeId:e,shapeBounds:o,queryBounds:s,pointHitTestBounds:r})}return new Qm(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.getCurrentPageId()){return this.getPageIndexSignal(e).get()}},eS={corner:0,edge_midpoint:1,center:2,custom:3},tS=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],nS=class{editor;constructor(e){this.editor=e}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createHandleSnapshot({context:e,currentPagePoint:t,allowSelfSnap:n=!1,excludedShapeIds:i=[]}){const o=this.editor.getShape(e.shapeId),r=new Set(this.editor.getShapeIdsIncludingDescendants([e.shapeId]));this.collectBindingDrivenExcludedShapeIds([e.shapeId],r);for(const c of i)r.add(c);const s=[],a=[],d=this.getSnapScopeParentId([e.shapeId]),l=this.getCandidateShapeIds({excludedShapeIds:r,scopeParentId:d});o&&n&&this.collectSelfHandleSnapGeometry({shape:o,context:e,currentPagePoint:t,points:s,outlines:a});for(const c of l){const e=this.editor.getShape(c);e&&this.collectHandleSnapGeometry({shape:e,points:s,outlines:a})}return{points:s,outlines:a,scopeParentId:d,candidateShapeIds:l}}collectHandleSnapGeometry({shape:e,points:t,outlines:n}){const i=this.editor.getShapeUtil(e);if(!i.canSnap(e))return;const o=this.editor.getShapeClippedPageBounds(e.id);if(!o)return;const r=this.editor.computeShapeLocalToPageTransform(e),s=i.getHandleSnapGeometry(e);for(const c of s.points??[]){const n=Un(c),i=r.applyToPoint(n.point);this.editor.isPagePointInShapeClip(e.id,i)&&t.push({id:`${e.id}:point:${t.length}`,nodeId:e.id,point:i,kind:n.kind,weight:n.weight})}const a=s.outline;if(null===a)return;const d=this.editor.getShapeClipAncestorIds(e.id).length>0?Zt(o):(a??(l=i.getLocalBounds(e),[new wm(l.minX,l.minY),new wm(l.maxX,l.minY),new wm(l.maxX,l.maxY),new wm(l.minX,l.maxY)])).map(e=>r.applyToPoint(e));var l;d.length>0&&n.push({id:e.id,points:d})}collectSelfHandleSnapGeometry({shape:e,context:t,currentPagePoint:n,points:i,outlines:o}){const r=this.editor.getShapeUtil(e);if(!r.canSnap(e))return;const s=this.editor.getShapeClippedPageBounds(e.id);if(!s)return;const a=r.getHandleSnapGeometry(e),d=this.editor.computeShapeLocalToPageTransform(e),l={...t,currentPagePoint:n.clone()};for(const h of a.getSelfSnapPoints?.(l)??[]){const t=Un(h),n=d.applyToPoint(t.point);this.editor.isPagePointInShapeClip(e.id,n)&&i.push({id:`${e.id}:self-point:${i.length}`,nodeId:e.id,point:n,kind:t.kind,weight:t.weight})}const c=a.getSelfSnapOutline?.(l)??null;if(!c)return;const u=this.editor.getShapeClipAncestorIds(e.id).length>0?Zt(s):c.map(e=>d.applyToPoint(e));u.length>0&&o.push({id:e.id,points:u})}createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=Array.from(e),i=new Set(this.editor.getShapeIdsIncludingDescendants(n));this.collectBindingDrivenExcludedShapeIds(n,i);const o=[],r=[],s={rotation:t.rotation,rotationCenter:t.rotationCenter},a=this.getSnapScopeParentId(n),d=this.getCandidateShapeIds({excludedShapeIds:i,scopeParentId:a});for(const l of d){const e=this.editor.getShape(l);if(!e)continue;const n=this.editor.getShapeUtil(e);if(!n.canSnap(e))continue;const i=this.editor.getShapeClippedPageBounds(e.id);if(!i)continue;const a=(this.editor.getShapeClipAncestorIds(e.id).length>0?Zt(i):this.editor.getShapePageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():Bn(e,s));if(0===a.length)continue;const d=Pm.FromPoints(a);r.push({id:e.id,bounds:d});const c=n.getBoundsSnapGeometry(e).points,u=[];if(void 0===c)Ot(d).forEach((e,t)=>{u.push({point:e,kind:tS[t]??"custom"})});else{const n=this.editor.computeShapeLocalToPageTransform(e);for(const i of c){const o=Un(i),r=n.applyToPoint(o.point);this.editor.isPagePointInShapeClip(e.id,r)&&u.push({point:0===t.rotation?r:Bn(r,s),kind:o.kind,weight:o.weight})}}u.forEach((t,n)=>{o.push({id:`${e.id}:${n}`,nodeId:e.id,point:t.point,kind:t.kind,weight:t.weight})})}return{points:o,pointIndex:nn(o),nodes:r,coordinateSpace:{rotation:t.rotation,rotationCenter:t.rotationCenter.clone()},scopeParentId:a,candidateShapeIds:d}}collectBindingDrivenExcludedShapeIds(e,t){const n=new Set,i=[...e];for(;i.length>0;){const e=i.pop();if(!e||n.has(e))continue;n.add(e);const o=this.editor.getShape(e);if(o)for(const n of this.editor.getBindingsForShape(e)){const r=n.fromId===e?"from":n.toId===e?"to":null;if(!r)continue;const s=this.editor.getBindingUtil(n).getGeometryDependentShapeIds?.(this.editor,n,{shape:o,role:r})??[];for(const e of s)for(const n of this.editor.getShapeIdsIncludingDescendants([e]))t.has(n)||(t.add(n),i.push(n))}}}getSnapScopeParentId(e){let t=null;for(const n of e){const e=this.editor.getShape(n);if(e)if(t){if(e.parentId!==t)return this.editor.getCurrentPageId()}else t=e.parentId}return t??this.editor.getCurrentPageId()}getCandidateShapeIds({excludedShapeIds:e,scopeParentId:t}){const n=this.editor.getCurrentPageId(),i=this.editor.renderViewportPageBoundsSignal.get(),o=new Set;t?.startsWith("shape:")&&o.add(t);const r=t??n;for(const s of this.editor.getChildShapeIds(r))o.add(s);return(null===i?Array.from(o):this.editor.getShapeIdsInBounds(i,{pageId:n}).filter(e=>o.has(e))).filter(n=>{if(e.has(n))return!1;const o=this.editor.getShape(n);if(!o||o.parentId!==r)return n===t;const s=this.editor.getShapeClippedPageBounds(n);return!!s&&(!i||s.intersects(i))})}},iS=class{gapCache=new WeakMap;_indicatorsSignal=s("editor.snapIndicators",[]);indicatorsSignal=this._indicatorsSignal;activeSignal=a("editor.snapIndicatorsActive",()=>this._indicatorsSignal.get().length>0);snapshots;axisSnapMemory={x:null,y:null};constructor(e){this.snapshots=new nS(e)}setIndicators(e){const t=e.map(En);mn(this._indicatorsSignal.get(),t)||this._indicatorsSignal.set(t)}clearIndicators(){this._indicatorsSignal.get().length>0&&this._indicatorsSignal.set([]),this.clearAxisSnapMemory()}clearAxisSnapMemory(){this.axisSnapMemory.x=null,this.axisSnapMemory.y=null}getSwitchDistance(e){return Math.min(.25*e,2)}getReleaseThreshold(e){return 1.5*e}updateAxisSnapMemory(e,t){this.axisSnapMemory[e]=t?{type:t.type,id:t.id,candidatePointIds:"points"===t.type?t.candidatePointIds:void 0}:null}writeDebugState(e){const t=globalThis;t.__LAND_LAST_SNAP_DEBUG__=e,t.__LAND_SNAP_DEBUG__&&t.console?.debug?.("[land:snap]",e)}getNow(){return globalThis.performance?.now?.()??Date.now()}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=this.snapshots.createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t});return this.gapCache.set(n,{x:un(n.nodes,"x"),y:un(n.nodes,"y")}),n}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.snapshots.createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t})}createHandleSnapshot(e){return this.snapshots.createHandleSnapshot(e)}snapTranslate(e){const t=this.getNow(),n=jt(e.initialSelectionBounds,e.dragDelta),i=(o=Ot(e.initialSelectionBounds),r=e.dragDelta,o.map(e=>e.add(r)));var o,r;const s=this.gapCache.get(e.snapshot)??{x:un(e.snapshot.nodes,"x"),y:un(e.snapshot.nodes,"y")},a=this.getReleaseThreshold(e.threshold),d=this.getSwitchDistance(e.threshold),l=this.axisSnapMemory.x,c=this.axisSnapMemory.y,u={candidatePointCount:0,matchedPointCount:0},h="y"===e.lockedAxis?null:fn(ln("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:a,switchDistance:d,stats:u}),gn("x",n,s.x,e.threshold,{previousSnapId:"gaps"===l?.type?l.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:l,switchDistance:d}),p="x"===e.lockedAxis?null:fn(ln("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:a,switchDistance:d,stats:u}),gn("y",n,s.y,e.threshold,{previousSnapId:"gaps"===c?.type?c.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:c,switchDistance:d}),g=new wm(h?.nudge??0,p?.nudge??0),f=[];return"points"===h?.type?f.push(...bn("x",h,g,e.snapshot.coordinateSpace)):"gaps"===h?.type&&f.push(Tn(h,e.snapshot.coordinateSpace,g)),"points"===p?.type?f.push(...bn("y",p,g,e.snapshot.coordinateSpace)):"gaps"===p?.type&&f.push(Tn(p,e.snapshot.coordinateSpace,g)),this.setIndicators(f),this.updateAxisSnapMemory("x",h),this.updateAxisSnapMemory("y",p),this.writeDebugState({operation:"translate",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:u.candidatePointCount,candidateGapCount:("y"===e.lockedAxis?0:s.x.length)+("x"===e.lockedAxis?0:s.y.length),matchedPointCount:u.matchedPointCount,xSnapId:h?.id??null,ySnapId:p?.id??null,indicatorCount:f.length}),{nudge:g,indicators:f}}snapResize(e){const t=this.getNow(),n=Dt({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),i=cn(n,e.resizedSelectionBounds),o="top"===n||"bottom"===n,r="left"===n||"right"===n,s=this.getReleaseThreshold(e.threshold),a=this.getSwitchDistance(e.threshold),d=this.axisSnapMemory.x,l=this.axisSnapMemory.y,c={candidatePointCount:0,matchedPointCount:0},u=o?null:ln("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:s,switchDistance:a,stats:c}),h=r?null:ln("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:s,switchDistance:a,stats:c}),p={x:null!==u,y:null!==h},g=new wm(u?.nudge??0,h?.nudge??0);if(e.isAspectRatioLocked&&Ut(n)&&(0!==g.x||0!==g.y)){const t=u&&h?Math.abs(g.x)<Math.abs(g.y)?"x":"y":u?"x":"y",i=0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h;"x"===t?(p.y=!1,g.y=g.x/i,"bottom_left"!==n&&"top_right"!==n||(g.y=-g.y)):(p.x=!1,g.x=g.y*i,"bottom_left"!==n&&"top_right"!==n||(g.x=-g.x))}const f=function(e,t){const n=Dt({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY});let i=e.resizedSelectionBounds.minX,o=e.resizedSelectionBounds.maxX,r=e.resizedSelectionBounds.minY,s=e.resizedSelectionBounds.maxY;e.isResizingFromCenter?(At(n)?(i+=t.x,o-=t.x):Lt(n)&&(i-=t.x,o+=t.x),Ft(n)?(r+=t.y,s-=t.y):$t(n)&&(r-=t.y,s+=t.y)):(At(n)?i+=t.x:Lt(n)&&(o+=t.x),Ft(n)?r+=t.y:$t(n)&&(s+=t.y));const a=(({minX:e,minY:t,maxX:n,maxY:i})=>{const o=Math.min(e,n),r=Math.min(t,i),s=Math.max(e,n),a=Math.max(t,i);return new Pm(o,r,Math.max(1,s-o),Math.max(1,a-r))})({minX:i,minY:r,maxX:o,maxY:s});if(!e.isAspectRatioLocked){const t=(({startBounds:e,bounds:t,handleId:n,scaleX:i,scaleY:o,isResizingFromCenter:r=!1})=>{const s=zt({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:r}),a=zt({axis:"y",startBounds:e,bounds:t,handleId:n,scale:o,isResizingFromCenter:r});return{scaleX:At(n)||Lt(n)?s*(t.w/Math.max(1,e.w)):i??1,scaleY:Ft(n)||$t(n)?a*(t.h/Math.max(1,e.h)):o??1}})({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter});return{bounds:a,scaleX:t.scaleX,scaleY:t.scaleY}}return Ht({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,aspectRatio:0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h,isResizingFromCenter:e.isResizingFromCenter,scaleX:e.scaleX,scaleY:e.scaleY})}(e,g),{bounds:m}=f,S=cn("any",m),y=[];if(p.x){const t=ln("x",S,e.snapshot.pointIndex,1e-8,{stats:c});t&&y.push(...Pn("x",t,wm.Zero(),e.snapshot.coordinateSpace,m,e.snapshot.nodes))}if(p.y){const t=ln("y",S,e.snapshot.pointIndex,1e-8,{stats:c});t&&y.push(...Pn("y",t,wm.Zero(),e.snapshot.coordinateSpace,m,e.snapshot.nodes))}return this.setIndicators(y),this.updateAxisSnapMemory("x",p.x?u:null),this.updateAxisSnapMemory("y",p.y?h:null),this.writeDebugState({operation:"resize",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:c.candidatePointCount,candidateGapCount:0,matchedPointCount:c.matchedPointCount,xSnapId:p.x?u?.id??null:null,ySnapId:p.y?h?.id??null:null,indicatorCount:y.length}),{nudge:g,bounds:m,scaleX:f.scaleX,scaleY:f.scaleY,indicators:y}}snapHandle(e){const t=this.getNow();if("none"===e.mode)return this.clearIndicators(),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null;const n="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return n?(this.setIndicators(n.indicators),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:n.indicators.length,indicatorCount:n.indicators.length}),n):(this.clearIndicators(),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null)}snapHandlePoint(e){let t=null,n=e.threshold*e.threshold;for(const o of e.snapshot.points){const i=e.pagePoint.dist2(o.point);i>n||(n=i,t=o.point)}if(!t)for(const o of e.snapshot.outlines){const i=en(e.pagePoint,o.points);!i||i.distanceSquared>n||(n=i.distanceSquared,t=i.point)}if(!t)return null;const i=t.clone();return{snappedPagePoint:i,nudge:i.sub(e.pagePoint),indicators:[kn(i)]}}snapHandleAlign(e){let t=null,n=null,i=e.threshold,o=e.threshold;for(const d of e.snapshot.points){const r=Math.abs(d.point.x-e.pagePoint.x);r<=i&&(i=r,t=d.point);const s=Math.abs(d.point.y-e.pagePoint.y);s<=o&&(o=s,n=d.point)}if(!t&&!n)return null;const r=new wm(t?t.x-e.pagePoint.x:0,n?n.y-e.pagePoint.y:0),s=e.pagePoint.add(r),a=[];return t&&a.push(Cn("x",s,t)),n&&a.push(Cn("y",s,n)),{snappedPagePoint:s,nudge:r,indicators:a}}},oS=class{beforeDelete=new Map;afterDelete=new Map;registerBeforeDeleteHandler(e,t){return this.register(this.beforeDelete,e,t)}registerAfterDeleteHandler(e,t){return this.register(this.afterDelete,e,t)}runBeforeDelete(e,t,n){if(0!==t.length)for(const i of this.beforeDelete.get(e)??[])i(t,n)}runAfterDelete(e,t,n){if(0!==t.length)for(const i of this.afterDelete.get(e)??[])i(t,n)}register(e,t,n){const i=e.get(t);return i?i.push(n):e.set(t,[n]),()=>{const i=e.get(t);if(!i)return;const o=i.indexOf(n);o>=0&&i.splice(o,1)}}},rS=class{editor;constructor(e){this.editor=e}align(e,t="user"){const n=this.getAlignableEntries();if(n.length<2)return!1;const i=Pm.FromPoints(n.flatMap(e=>[new wm(e.bounds.minX,e.bounds.minY),new wm(e.bounds.maxX,e.bounds.maxY)])),o=n.map(({shape:t,bounds:n})=>{let o=0,r=0;switch(e){case"left":o=i.minX-n.minX;break;case"right":o=i.maxX-n.maxX;break;case"horizontal-center":o=i.center.x-n.center.x;break;case"top":r=i.minY-n.minY;break;case"bottom":r=i.maxY-n.maxY;break;case"vertical-center":r=i.center.y-n.center.y}return{id:t.id,x:t.x+o,y:t.y+r}});return this.editor.commands.updateShapes(o,{source:t}),!0}distribute(e,t="user"){const n=this.getAlignableEntries();if(n.length<3)return!1;const i="horizontal"===e,o=e=>i?e.w:e.h,r=e=>i?e.minX:e.minY,s=i?"x":"y",a=[...n].sort((e,t)=>e.bounds.center[s]-t.bounds.center[s]),d=a[0].bounds,l=a[a.length-1].bounds,c=((i?l.maxX:l.maxY)-r(d)-a.reduce((e,t)=>e+o(t.bounds),0))/(a.length-1);let u=r(d);const h=a.map(({shape:e,bounds:t},n)=>{const s=0===n||n===a.length-1?r(t):u,d=s-r(t);return u=s+o(t)+c,i?{id:e.id,x:e.x+d}:{id:e.id,y:e.y+d}});return this.editor.commands.updateShapes(h,{source:t}),!0}getCurrentPageBounds(e=this.editor.getCurrentPageId()){return this.boundsOfShapeIds(this.editor.getCurrentPageShapeIds())}zoomToBounds(e,t){const n=this.editor.viewportScreenSizeSignal.get();if(n.w<=0||n.h<=0||!de(e))return!1;if(e.w<=0&&e.h<=0)return!1;const i=t?.padding??64,o=Math.max(1,n.w-2*i),r=Math.max(1,n.h-2*i),s=ie(Math.min(e.w>0?o/e.w:1/0,e.h>0?r/e.h:1/0,t?.maxZoom??1)),a=e.center;return this.editor.setCamera({x:a.x-n.w/2/s,y:a.y-n.h/2/s,z:s},{source:t?.source??"user"}),!0}zoomToFit(e){const t=this.getCurrentPageBounds();return!!t&&this.zoomToBounds(t,e)}zoomToSelection(e){const t=this.boundsOfShapeIds(this.editor.getSelectedShapeIds());return!!t&&this.zoomToBounds(t,e)}boundsOfShapeIds(e){const t=[];for(const i of e){const e=this.editor.getShapePageBounds(i);e&&de(e)&&t.push(new wm(e.minX,e.minY),new wm(e.maxX,e.maxY))}if(0===t.length)return null;const n=Pm.FromPoints(t);return de(n)?n:null}getAlignableEntries(){const e=this.editor.getCurrentPageId(),t=[];for(const n of this.editor.getSelectedShapeIds()){const i=this.editor.getShape(n);if(!i||i.isLocked||i.parentId!==e)continue;const o=this.editor.getShapePageBounds(n);o&&de(o)&&t.push({shape:i,bounds:o})}return t}},sS=class{editor;constructor(e){this.editor=e}setSelectedShapeIds(e,t){const n=this.editor,i=t?.pageId??n.getCurrentPageId(),o=t?.source??"user",r=((e,t)=>{const n=new Set(t);return t.filter(t=>{const i=e.getShape(t);if(!i)return!1;let o=i.parentId;const r=new Set([t]);for(;o.startsWith("shape:");){const t=o;if(r.has(t))return!0;if(n.has(t))return!1;r.add(t);const i=e.getShape(t);if(!i)return!0;o=i.parentId}return!0})})(n,Array.from(new Set(e.filter(e=>n.getShapePageId(e)===i&&!n.isShapeHidden(e))))),s=n.sessionSignal.get(),a=s.pageSelectedShapeIdsById[i]??[];n.getShapeEditingSession()&&!n.completeEditing(o)||oe(a,r)||(n.setBindingPreview(null),n.setSnapIndicators(null),n.updateSession({pageSelectedShapeIdsById:{...s.pageSelectedShapeIdsById,[i]:r}},o))}removeShapeIdsFromSelection(e,t="system"){if(0===e.length)return;const n=this.editor,i=new Set(e),o=n.sessionSignal.get(),r={};for(const s of n.getPages())r[s.id]=(o.pageSelectedShapeIdsById[s.id]??[]).filter(e=>!i.has(e));n.updateSession({pageSelectedShapeIdsById:r},t)}selectAllCurrentPage(e="user"){const t=this.editor,n=t.getCurrentPageId(),i=t.getCurrentPageShapeIds().map(e=>t.getShape(e)).filter(e=>!!e&&e.parentId===n&&!t.isShapeHidden(e.id)).map(e=>e.id);t.commands.setSelectedShapeIds(i,{source:e})}},aS=class{editor;frameGeometrySignal;companionFrameGeometriesSignal;pathSignal;bindingSegmentsSignal;frameStyleSignal;frameSignal;handleAnchorsSignal;handlesSignal;handleCountsSignal;overlaySignal;debugStateSignal;debugStateSnapshotSignal;constructor(e){this.editor=e,this.frameGeometrySignal=a("editor.selectionOverlayFrameGeometry",()=>{const t=e.selectedShapeOverlayItemsSignal.get();if(0===t.length)return null;if(ri(t))return null;const n=e.getSelectionFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:Nn}),this.companionFrameGeometriesSignal=a("editor.selectionOverlayCompanionFrameGeometries",()=>{if("select"!==e.toolStateSignal.get().activeToolId)return[];const t=[];for(const n of e.selectedShapesSignal.get())for(const i of e.getBindingsForShape(n.id))t.push(...e.getBindingUtil(i).getSelectionCompanionFrameGeometries?.(e,i,{selectedShape:n})??[]);return t},{isEqual:On}),this.pathSignal=a("editor.selectionOverlayPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return ri(t)?t[0]?.path??null:null}),this.bindingSegmentsSignal=a("editor.selectionOverlayBindingSegments",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return ri(t)?[...t[0]?.bindingSegments??[]]:[]},{isEqual:Xe}),this.frameStyleSignal=a("editor.selectionOverlayFrameStyle",()=>{const t=e.cameraZoomSignal.get();return{strokeWidth:2/t,cornerRadius:3/t}},{isEqual:Wn}),this.frameSignal=a("editor.selectionOverlayFrame",()=>{const e=this.frameGeometrySignal.get();if(!e)return null;const t=this.frameStyleSignal.get();return{...e,...t}},{isEqual:Hn}),this.handleAnchorsSignal=a("editor.selectionOverlayHandleAnchors",()=>{if("select"!==e.toolStateSignal.get().activeToolId)return null;const t=e.selectedShapesSignal.get();if(0===t.length)return null;const n=e.getSelectionFrame(),i=e.cameraZoomSignal.get(),o=1===t.length;return si(t,n,i,t=>e.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:o,editor:e}),t=>e.getShapeUtil(t).canUseSelectionFrameHandles(t,{editor:e}))},{isEqual:ii}),this.handlesSignal=a("editor.selectionOverlayHandles",()=>{const t=this.handleAnchorsSignal.get();if(!t)return null;const n=e.cameraZoomSignal.get(),{resizeHandles:i,rotateHandles:o,terminalHandles:r,middleHandles:s,customHandles:a}=ai(t,n);return{resizeHandles:i,rotateHandles:o,terminalHandles:r,middleHandles:s,customHandles:a,strokeWidth:2/n}},{isEqual:ni}),this.handleCountsSignal=a("editor.selectionOverlayHandleCounts",()=>{const e=this.handleAnchorsSignal.get();return e?{resizeHandleCount:e.resizeHandleAnchors.length,rotateHandleCount:e.rotateHandleAnchors.length,terminalHandleCount:e.terminalHandleAnchors.length,middleHandleCount:e.middleHandleAnchors.length,customHandleCount:e.customHandleAnchors.length}:null},{isEqual:oi}),this.overlaySignal=a("editor.selectionOverlay",()=>{const e=this.frameSignal.get(),t=this.handlesSignal.get();return e&&t?{...e,...t}:null}),this.debugStateSnapshotSignal=a("editor.overlayDebugState.snapshot",t=>{const n=this.frameSignal.get(),i=this.handleCountsSignal.get(),o=t!==bm?t:null,r=!o||!Hn(o.frame,n),s=!o||!oi(o.handleCounts,i);return{metrics:{selectionFrameActive:null!==n,selectionHandlesActive:null!==i,bindingPreviewActive:e.bindingPreviewActiveSignal.get(),brushBoxActive:e.brushBoxActiveSignal.get(),selectionFrameChangeCount:(o?.metrics.selectionFrameChangeCount??0)+(r?1:0),selectionHandlesChangeCount:(o?.metrics.selectionHandlesChangeCount??0)+(s?1:0),resizeHandleCount:i?.resizeHandleCount??0,rotateHandleCount:i?.rotateHandleCount??0,terminalHandleCount:i?.terminalHandleCount??0,middleHandleCount:i?.middleHandleCount??0,customHandleCount:i?.customHandleCount??0,boundsSummary:(a=n?.bounds??null,a?`${Math.round(a.x)},${Math.round(a.y)},${Math.round(a.w)},${Math.round(a.h)}`:"none"),rotation:n?.rotation??null,strokeWidth:n?.strokeWidth??null},frame:n,handleCounts:i};var a},{isEqual:(e,t)=>ce(e.metrics,t.metrics)}),this.debugStateSignal=a("editor.overlayDebugState.public",()=>this.debugStateSnapshotSignal.get().metrics,{isEqual:ce})}},dS=class{editor;entryRequestAtom=s("editor.shapeEditingEntryRequest",null);entryRequestSignal=this.entryRequestAtom;nextEntryRequestId=1;constructor(e){this.editor=e}canEditShape(e){const t="string"==typeof e?this.editor.getShape(e):e;return!!t&&!t.isLocked&&this.editor.getShapeUtil(t).canEdit(t)}start(e,t="user"){const n=this.editor.getShape(e.shapeId);if(!n||!this.canEditShape(n))return null;const i=this.editor.getShapeEditingSession();if(i?.shapeId===n.id){const o={...i,entryMode:e.entryMode??i.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:i.caretPagePoint};return this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:o},t),this.publishEntryRequest({shapeId:n.id,entryMode:o.entryMode,caretPagePoint:o.caretPagePoint}),o}e.preserveInteraction||this.editor.cancelInteractionForCommand(),this.end({runEditEnd:!0,source:t});const o=e.markId??`editing:${n.id}`;e.reuseExistingMark||this.editor.history.mark(o);const r={shapeId:n.id,markId:o,entryMode:e.entryMode??"focusEnd",caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0,isComposing:!1};return this.editor.commands.setSelectedShapeIds([n.id],{source:t}),this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:r},t),this.publishEntryRequest({shapeId:n.id,entryMode:r.entryMode,caretPagePoint:r.caretPagePoint}),r}complete(e="user"){const t=this.editor.getShapeEditingSession();return!!t&&!t.isComposing&&(this.end({runEditEnd:!0,source:e}),this.editor.history.squashToMark(t.markId,"shape.edit"),!0)}cancel(e="user"){const t=this.editor.getShapeEditingSession();return!!t&&!t.isComposing&&(this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},e),this.editor.history.bailToMark(t.markId),!0)}setComposition(e,t="system"){const n=this.editor.getShapeEditingSession();n&&n.isComposing!==e&&this.editor.updateSession({shapeEditingSession:{...n,isComposing:e}},t)}consumeEntryRequest(e){const t=this.entryRequestAtom.get();t&&t.id===e&&this.entryRequestAtom.set(null)}removeShapeIds(e,t="system"){const n=this.editor.getShapeEditingSession();n&&e.includes(n.shapeId)&&this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},t)}end(e){const t=this.editor.getShapeEditingSession();if(!t)return;this.entryRequestAtom.set(null);const n=this.editor.getShape(t.shapeId);if(this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},e.source),!e.runEditEnd||!n)return;const i=this.editor.getShapeUtil(n).onEditEnd(n,{editor:this.editor});i?.deleteShapeIds&&i.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(i.deleteShapeIds,{source:e.source})}publishEntryRequest(e){this.entryRequestAtom.set({id:this.nextEntryRequestId++,shapeId:e.shapeId,entryMode:e.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0})}},lS=class{editor;constructor(e){this.editor=e}computeShapeBounds(e){return this.editor.getShapeUtil(e).getBounds(e)}computeShapeLocalBounds(e){return((e,t)=>t.getLocalBounds(e))(e,this.editor.getShapeUtil(e))}computeShapeRenderBounds(e){return((e,t)=>t.getRenderBounds(e))(e,this.editor.getShapeUtil(e))}computeShapeExportBounds(e){return Ve(e,this.editor.getShapeUtil(e))}computeShapeLocalToPageTransform(e){return qe(e,this.editor.getShapeUtil(e))}computeShapeRenderToPageTransform(e){return((e,t)=>qe(e,t))(e,this.editor.getShapeUtil(e))}computeShapeExportToPageTransform(e){return Ge(e,this.editor.getShapeUtil(e))}computeShapePageBounds(e){return((e,t)=>Pm.FromPoints(et(e,t)))(e,this.editor.getShapeUtil(e))}computeShapeExportPageBounds(e){return((e,t)=>{const n=Ve(e,t),i=Ge(e,t);return Pm.FromPoints([new wm(n.minX,n.minY),new wm(n.maxX,n.minY),new wm(n.maxX,n.maxY),new wm(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))})(e,this.editor.getShapeUtil(e))}computeShapeGeometry(e){return tt(e,this.editor.getShapeUtil(e))}computeShapePositionedToPageTransform(e){return je(e,this.editor.getShapeUtil(e))}computeShapePageCenter(e){return this.computeShapeGeometry(e).center}computeShapePageCorners(e){return this.computeShapeGeometry(e).corners}computeShapePageOutlineVertices(e){return this.computeShapeGeometry(e).outlineVertices}getShapeBounds(e){return this.editor.queries.getShapeBounds(e)??null}getShapePageBounds(e){return this.editor.queries.getShapePageBounds(e)??null}getShapeGeometry(e){return this.editor.queries.getShapeGeometry(e)??null}getShapePositionedToPageTransform(e){return this.editor.queries.getShapePositionedToPageTransform(e)??null}getShapePageCenter(e){return this.editor.queries.getShapePageCenter(e)??null}getShapePageCorners(e){return this.editor.queries.getShapePageCorners(e)??null}getShapePageOutlineVertices(e){return this.editor.queries.getShapePageOutlineVertices(e)??[]}getSelectionPageBounds(){return this.editor.queries.getSelectionPageBounds()}getSelectionFrame(){const e=this.editor.queries.getSelectionFrameBounds(),t=this.editor.queries.getSelectionRotationCenter();return e&&t?{bounds:e,rotation:this.editor.queries.getSelectionRotation(),rotationCenter:t,hasCompatibleRotation:this.editor.queries.getSelectionHasCompatibleRotation()}:null}isPointInSelectionBounds(e){const t=this.getSelectionFrame();if(!t)return!1;const n=this.getSelectionFrameLocalBoundsPoint(e);return!!n&&t.bounds.containsPoint(n)}getSelectionFrameLocalBoundsPoint(e){const t=this.getSelectionFrame();return t?Bn(e,t):null}getSelectionPageOutlineVertices(){return this.editor.queries.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.editor.queries.getSelectionAnchorPagePoint()}},cS=class{editor;constructor(e){this.editor=e}get store(){return _(this.editor)}getSelectionParentOrderState(){return di(this.editor)}getSelectionGroupState(){const e=this.editor,t=e.getSelectedShapes();if(t.length<1)return null;if(t.some(t=>t.isLocked||e.hasLockedDescendant(t.id)))return null;const n=t[0]?.parentId;if(!n)return null;if(t.some(e=>e.parentId!==n))return null;const i=e.getChildShapes(n),o=new Set(t.map(e=>e.id)),r=i.filter(e=>o.has(e.id)).map(e=>e.id);if(r.length!==t.length)return null;const s=e.getSelectionPageBounds();return s&&de(s)?{parentId:n,shapeIds:r,bounds:s}:null}canGroupSelection(){return null!==this.getSelectionGroupState()}getGroupStateForShapeIds(e){const t=this.editor,n=Array.from(new Set(e)),i=n.map(e=>t.getShape(e)).filter(e=>!!e);if(i.length<1||i.length!==n.length)return null;if(i.some(e=>e.isLocked||t.hasLockedDescendant(e.id)||t.isShapeHidden(e.id)))return null;const o=i[0]?.parentId;if(!o)return null;if(i.some(e=>e.parentId!==o))return null;const r=t.getChildShapes(o),s=new Set(n),a=r.filter(e=>s.has(e.id)).map(e=>e.id);if(a.length!==n.length)return null;const d=a.map(e=>t.getShapePageBounds(e)).filter(e=>!!e).flatMap(e=>[new wm(e.minX,e.minY),new wm(e.maxX,e.minY),new wm(e.maxX,e.maxY),new wm(e.minX,e.maxY)]),l=d.length>0?Pm.FromPoints(d):null;return l&&de(l)?{parentId:o,shapeIds:a,bounds:l}:null}groupShapesFromState(e,t){const n=this.editor,i=n.getChildShapes(e.parentId),o=new Set(e.shapeIds),r=i.findIndex(e=>o.has(e.id));if(r<0)return null;n.cancelInteractionForCommand();const s=[];return this.store.atomic(()=>{const[a]=n.commands.createShapes([{type:"group",x:e.bounds.x,y:e.bounds.y,parentId:e.parentId,index:n.createShapeIndex(r+1),props:{w:e.bounds.w,h:e.bounds.h}}],{source:t});if(!a)return;s.push(a);const d=[];let l=!1;for(const e of i)o.has(e.id)?l||(d.push(a),l=!0):d.push(e);const c=e.shapeIds.map(e=>n.getShape(e)).filter(e=>!!e);n.commands.updateShapes([...d.map((e,t)=>({id:e.id,index:n.createShapeIndex(t+1)})),...c.map((e,t)=>({id:e.id,parentId:a.id,index:n.createShapeIndex(t+1)}))],{source:t})},t),s[0]??null}canGroupShapes(e){return null!==this.getGroupStateForShapeIds(e)}groupShapes(e,t="user"){const n=this.getGroupStateForShapeIds(e);return n?this.groupShapesFromState(n,t):null}groupSelection(e="user"){const t=this.editor,n=this.groupShapes(t.getSelectedShapeIds(),e);return n&&t.commands.setSelectedShapeIds([n.id],{source:e}),n}getUngroupableSelectedShapeIds(){return this.getUngroupableShapeIds(this.editor.getSelectedShapeIds())}getUngroupableShapeIds(e){const t=this.editor;return e.map(e=>t.getShape(e)).filter(e=>!!e).filter(e=>t.getShapeUtil(e).canUngroupChildren(e)).filter(e=>!e.isLocked&&!t.hasLockedDescendant(e.id)&&t.getChildShapeIds(e.id).length>0).map(e=>e.id)}canUngroupSelection(){return this.getUngroupableSelectedShapeIds().length>0}canUngroupShapes(e){return this.getUngroupableShapeIds(e).length>0}ungroupShapes(e,t="user"){const n=this.editor,i=new Set(this.getOutermostUngroupableShapeIds(e));if(0===i.size)return[];const o=e.map(e=>n.getShape(e)).filter(e=>!!e);n.cancelInteractionForCommand();const r=[],s=new Set;return this.store.atomic(()=>{const e=[],a=[];for(const t of o){if(!i.has(t.id)){s.has(t.id)||(s.add(t.id),r.push(t.id));continue}const o=n.getShape(t.id);if(!o)continue;const d=n.getChildShapes(o.id),l=n.getChildShapes(o.parentId),c=new Set(d.map(e=>e.id)),u=[];let h=!1;for(const e of l)e.id!==o.id?c.has(e.id)||u.push(e):(u.push(...d),h=!0);h||u.push(...d),e.push(...u.map((e,t)=>({id:e.id,parentId:c.has(e.id)?o.parentId:e.parentId,index:n.createShapeIndex(t+1)})));for(const e of d)s.has(e.id)||(s.add(e.id),r.push(e.id));a.push(o.id)}e.length>0&&n.commands.updateShapes(e,{source:t}),this.removeUngroupedContainerShapes(a,t)},t),r.length>0&&n.commands.setSelectedShapeIds(r,{source:t}),r}ungroupSelection(e="user"){return this.ungroupShapes(this.editor.getSelectedShapeIds(),e)}getOutermostUngroupableShapeIds(e){const t=this.getUngroupableShapeIds(e),n=new Set(t);return t.filter(e=>!this.isShapeDescendantOfAny(e,n))}isShapeDescendantOfAny(e,t){let n=this.editor.getShape(e);const i=new Set;for(;n?.parentId.startsWith("shape:");){const e=n.parentId;if(t.has(e))return!0;if(i.has(e))return!1;i.add(e),n=this.editor.getShape(e)}return!1}removeUngroupedContainerShapes(e,t){if(0===e.length)return;const n=this.editor,i=[...e];n.sideEffects.runBeforeDelete("shape",i,t),this.store.remove(i,t),n.sideEffects.runAfterDelete("shape",i,t)}getSelectionSiblingOrderState(){return li(this.editor)}canMoveSelectionWithinParent(e){return((e,t)=>{const n=li(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveSelectionInParentOrder(e){return((e,t)=>{const n=di(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveShapesInParentOrder(e,t){return((e,t,n)=>{const i=ci(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this.editor,e,t)}moveShapesInParentOrder(e,t,n="user"){return ui(this.editor,e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return hi(this.editor,e,t,n)}moveSelectionWithinParent(e,t="user"){return((e,t,n="user")=>{const i=e.getSelectedShapes();if(1!==i.length)return!1;const[o]=i;if(!o||o.isLocked)return!1;const r=li(e);if(!r)return!1;const s=e.getChildShapes(r.parentId),a=r.index;if(s[a]?.id!==o.id)return!1;const d="backward"===t?a-1:a+1;if(d<0||d>=s.length)return!1;const l=[...s],[c]=l.splice(a,1);return!!c&&(l.splice(d,0,c),e.cancelInteractionForCommand(),e.commands.updateShapes(l.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:n}),!0)})(this.editor,e,t)}moveShapesToParentPlacement(e,t="user"){return((e,t,n="user")=>{const i=Array.from(new Set(t.ids));if(0===i.length)return!1;const o=i.map(t=>e.getShape(t)).filter(e=>!!e);return o.length===i.length&&!o.some(t=>t.isLocked||e.isShapeHidden(t.id))&&!i.some(n=>!pi(e,t.parentId,n))&&gi(e,t,i,o,n)})(this.editor,e,t)}moveShapesToParentPlacementResult(e,t="user"){return((e,t,n="user")=>{const i=Array.from(new Set(t.ids));if(0===i.length)return{ok:!1,reason:"notFound"};const o=i.map(t=>e.getShape(t)).filter(e=>!!e);if(o.length!==i.length)return{ok:!1,reason:"notFound"};for(const r of o){if(r.isLocked)return{ok:!1,reason:"locked"};if(e.isShapeHidden(r.id))return{ok:!1,reason:"hidden"}}for(const r of i){const n=t.parentId;if(n.startsWith("page:")){if(!e.getPage(n))return{ok:!1,reason:"invalidParent"}}else{const t=e.getShape(n);if(!t)return{ok:!1,reason:"invalidParent"};if(t.id===r||e.getDescendantShapeIds(r).includes(t.id))return{ok:!1,reason:"cycle"};if(!e.getShapeUtil(t).canReceiveChildren(t))return{ok:!1,reason:"invalidParent"}}}return gi(e,t,i,o,n)?{ok:!0,movedIds:i}:{ok:!1,reason:"invalidBeforeId"}})(this.editor,e,t)}moveSelectionInParentOrder(e,t="user"){return((e,t,n="user")=>ui(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}moveSelectionToParentOrderEdge(e,t="user"){return((e,t,n="user")=>hi(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}isShapeOrAncestorLocked(e){const t=this.editor,n=new Set;let i=t.getShape(e);for(;i;){if(i.isLocked)return!0;if(!i.parentId.startsWith("shape:"))return!1;const e=i.parentId;if(n.has(e))return!1;n.add(e),i=t.getShape(e)}return!1}hasLockedDescendant(e){const t=this.editor;return t.getDescendantShapeIds(e).some(e=>t.getShape(e)?.isLocked??!1)}getOutermostSelectableShapeId(e){const t=this.editor;let n=e,i=t.getShape(e);const o=new Set([e]);for(;i?.parentId.startsWith("shape:");){const e=i.parentId;if(o.has(e))break;o.add(e);const r=t.getShape(e);if(!r)break;t.getShapeUtil(r).isTransformDescendantContainer(r)&&(n=r.id),i=r}return n}getShapeIdsIncludingDescendants(e){const t=[],n=new Set;for(const i of e)if(!n.has(i)){n.add(i),t.push(i);for(const e of this.editor.getDescendantShapeIds(i))n.has(e)||(n.add(e),t.push(e))}return t}getShapeIdsForSelectionTransform(e){return this.getShapeIdsForSelectionDescendantTransform(e,e=>this.editor.getShapeUtil(e).isTransformDescendantContainer(e))}getShapeIdsForSelectionRotation(e){return this.getShapeIdsForSelectionDescendantTransform(e,e=>this.editor.getShapeUtil(e).shouldRotateDescendants(e))}getSelectionTransformTargetShapes(){return this.getShapeIdsForSelectionTransform(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getSelectionRotationTargetShapes(){return this.getShapeIdsForSelectionRotation(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getShapeExportTraversalIds(e){const t=this.editor,n=this.getShapeIdsIncludingDescendants(e).filter(e=>!t.isShapeHidden(e)),i=new Set(n);for(const o of n)for(const e of t.getBindingsForShape(o)){const o=t.getBindingUtil(e).getExportShapeIds?.(t,e);for(const e of o??[])for(const t of this.getShapeIdsIncludingDescendants([e]))i.has(t)||(i.add(t),n.push(t))}return n}getShapeIdsInContainerBounds(e,t={}){const n=this.editor,i=n.getShapePageId(e),o=n.getShapePageBounds(e);return i&&o?n.getShapeIdsInBounds(o,{pageId:i}).filter(i=>{if(i===e)return!1;const o=n.getShapeContainment(e,i);return"inside"===o||t.includeIntersecting&&"intersecting"===o}):[]}canUseShapeParent(e,t){return pi(this.editor,e,t)}isShapeOrAncestorInSet(e,t){let n=this.editor.getShape(e);const i=new Set;for(;n;){if(t.has(n.id))return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(i.has(e))return!1;i.add(e),n=this.editor.getShape(e)}return!1}isShapeDescendantOf(e,t){let n=this.editor.getShape(e);const i=new Set;for(;n?.parentId.startsWith("shape:");){const e=n.parentId;if(e===t)return!0;if(i.has(e))return!1;i.add(e),n=this.editor.getShape(e)}return!1}getShapeIdsForSelectionDescendantTransform(e,t){const n=this.editor,i=[],o=new Set;for(const r of e){const e=n.getShape(r);if(!e||o.has(e.id)||e.isLocked)continue;const s=t(e);if((!s||!this.hasLockedDescendant(e.id))&&(o.add(e.id),i.push(e.id),s))for(const t of n.getDescendantShapeIds(e.id)){if(o.has(t))continue;const e=n.getShape(t);e&&!e.isLocked&&(o.add(e.id),i.push(e.id))}}return i}},uS=class{bindings=new Map;bindingIds=[];register(e){const t=this.bindingIds.indexOf(e.id);t>=0&&this.bindingIds.splice(t,1);const n=fi(e.shortcut);this.bindingIds.push(e.id),this.bindings.set(e.id,{id:e.id,shortcut:n,target:e.target,label:e.label??mi(n)})}registerActionShortcut(e,t){this.register({id:`action:${e}`,shortcut:t,target:{type:"action",actionId:e}})}registerEditorShortcut(e,t){const n=fi(t);this.register({id:`editor:${e}:${bi(n)}`,shortcut:n,target:{type:"editor",command:e}})}registerToolShortcut(e,t){this.register({id:`tool:${e}`,shortcut:t,target:{type:"tool",toolId:e}})}unregister(e){const t=this.bindingIds.indexOf(e);t>=0&&this.bindingIds.splice(t,1),this.bindings.delete(e)}getBinding(e){const t=this.bindings.get(e);return t?{id:t.id,shortcut:t.shortcut,target:t.target,label:t.label}:null}getTargetForEvent(e){return this.getBindingForEvent(e)?.target??null}getActionIdForEvent(e){const t=this.getTargetForEvent(e);return"action"===t?.type?t.actionId:null}getToolIdForEvent(e){const t=this.getTargetForEvent(e);return"tool"===t?.type?t.toolId:null}getActionShortcutLabel(e){return this.getBindingLabel(`action:${e}`)}getToolShortcutLabel(e){return this.getBindingLabel(`tool:${e}`)}getBindingForEvent(e){for(let t=this.bindingIds.length-1;t>=0;t--){const n=this.bindings.get(this.bindingIds[t]);if(n&&Si(n.shortcut,e))return n}return null}getBindingLabel(e){return this.bindings.get(e)?.label}},hS=class{editor;shapeRenderOrderByIdSignal;culledShapeIdsSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;renderVisibleShapeIdSetSignal;renderItemsSignal;renderHostDebugStateSignal;retainedBaseShapeWindowSnapshotSignal;retainedShapeWindowSnapshotSignal;renderHostDebugStateSnapshotSignal;constructor(e){this.editor=e,this.shapeRenderOrderByIdSignal=a("editor.shapeRenderOrderById",()=>{const t=new Map;for(const[n,i]of e.currentPageShapeIdsSignal.get().entries())t.set(i,n);return t}),this.culledShapeIdsSignal=a("editor.culledShapeIds",()=>{const t=e.getCurrentPageId(),n=e.renderViewportPageBoundsSignal.get();return n?e.spatialIndex.getShapeIdsInViewport(n,{pageId:t}):e.currentPageShapeIdsSignal.get()},{isEqual:oe}),this.retainedBaseShapeWindowSnapshotSignal=a("editor.retainedBaseShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),o=ki(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(t!==bm&&t&&t.viewportReady&&o.length>0){const e=((e,t)=>{if(e.length!==t.length||0===t.length)return null;const n=t.map((n,i)=>{const o=e[i];if(!o)return null;if(o.end+2<n.start||o.start>n.end+2)return null;const r=i>0?t[i-1]:null,s=i<t.length-1?t[i+1]:null,a=s?s.start-3:1/0,d={start:Math.min(n.start,Math.max(r?r.end+3:-1/0,o.start)),end:Math.max(n.end,Math.min(a,o.end))};return d.end-d.start>n.end-n.start+4?null:d});if(n.some(e=>null===e))return null;const i=n;if(vi(i).length!==t.length)return null;const o=Pi(t);return Pi(i)>o+12?null:i})(vi(t.ranges.map(e=>({...e}))),o);if(e)return Ti(n,e,{viewportReady:i})}return Ti(n,o,{viewportReady:i})},{isEqual:(e,t)=>oe(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=a("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:pe}),this.selectedShapeIdsOutsideCulledSignal=a("editor.selectedShapeIdsOutsideCulled",()=>{const t=e.selectedShapeIdsSignal.get();if(0===t.length)return[];const n=this.culledShapeIdSetSignal.get();return t.filter(e=>!n.has(e))},{isEqual:oe}),this.selectedShapeIdsOutsideCulledSetSignal=a("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:pe}),this.renderVisibleShapeIdsSignal=a("editor.renderVisibleShapeIds",()=>{if(0===this.selectedShapeIdsOutsideCulledSignal.get().length)return this.culledShapeIdsSignal.get();const t=this.culledShapeIdSetSignal.get(),n=this.selectedShapeIdsOutsideCulledSetSignal.get();return e.currentPageShapeIdsSignal.get().filter(e=>t.has(e)||n.has(e))},{isEqual:oe}),this.retainedShapeWindowSnapshotSignal=a("editor.retainedShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),o=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,r=(s=o.length)<=0?0:xi(Math.ceil(.5*s),12,96);var s;const a=((e,t,n,i)=>{if(0===e.length)return[];const o=new Map;for(const[a,d]of e.entries())o.set(d,a);const r=vi(t.map(e=>o.get(e)).filter(e=>void 0!==e).sort((e,t)=>e-t).map(e=>({start:e,end:e+1})),2),s=[];if(r.length>0){const t=xi(Math.ceil(i/(2*r.length)),8,32);for(const[n,i]of r.entries()){const o=n>0?r[n-1]:null,a=n<r.length-1?r[n+1]:null,d=a?a.start-i.end:1/0,l=wi(o?i.start-o.end:1/0,t),c=wi(d,t+4);s.push({start:Math.max(0,i.start-l),end:Math.min(e.length,i.end+c)})}}for(const a of n){const e=o.get(a);void 0!==e&&s.push({start:e,end:e+1})}return 0===s.length?[]:vi(s,2)})(n,o,this.selectedShapeIdsOutsideCulledSetSignal.get(),r);if(i&&t!==bm&&t&&t.viewportReady&&t.ranges.length>0&&a.length>0){const e=vi(t.ranges.map(e=>({...e})));if(((e,t)=>{if(0===t.length)return!0;if(0===e.length)return!1;let n=0;for(const i of t){for(;n<e.length;){const t=e[n];if(t&&i.start>=t.start&&i.end<=t.end)break;if(!(t&&i.end>t.end))return!1;n+=1}if(n>=e.length)return!1}return!0})(e,a))return Ti(n,e,{viewportReady:i});const o=((e,t,n)=>{const i=t.map((n,i)=>{const o={...n};for(const t of e)t.end+6<n.start||t.start>n.end+6||(o.start=Math.min(o.start,t.start),o.end=Math.max(o.end,t.end));const r=i>0?t[i-1]:null,s=i<t.length-1?t[i+1]:null,a=s?s.start-3:1/0;return{start:Math.min(n.start,Math.max(r?r.end+3:-1/0,o.start)),end:Math.max(n.end,Math.min(a,o.end))}});if(vi(i).length!==t.length)return null;const o=Pi(t);return Pi(i)>o+n?null:i})(e,a,r);if(o)return Ti(n,o,{viewportReady:i})}return Ti(n,a,{viewportReady:i})},{isEqual:(e,t)=>oe(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=a("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:oe}),this.renderVisibleShapeIdSetSignal=a("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:pe}),this.renderItemsSignal=a("editor.renderItems",()=>{const t=e.selectedShapeIdSetSignal.get(),n=[];for(const i of this.renderVisibleShapeIdsSignal.get()){const o=e.getShapeSignal(i).get(),r=e.queries.getShapePageBoundsSignal(i).get();o&&!o.isHidden&&r&&n.push({id:o.id,shape:o,bounds:r,isSelected:t.has(o.id)})}return n},{isEqual:he}),this.renderHostDebugStateSnapshotSignal=a("editor.renderHostDebugState.snapshot",t=>{const n=this.culledShapeIdsSignal.get(),i=this.renderVisibleShapeIdsSignal.get(),o=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,r=this.retainedShapeIdsSignal.get(),s=this.selectedShapeIdsOutsideCulledSignal.get(),a=this.getPageIndexById(e.currentPageShapeIdsSignal.get()),d=ki(n,a),l=ki(r,a),c=ki(o,a),u=((e,t)=>{if(0===e.length)return{changed:t.length,added:t.length,removed:0};if(0===t.length)return{changed:e.length,added:0,removed:e.length};const n=new Set(e),i=new Set(t);let o=0,r=0;for(const s of i)n.has(s)||(o+=1);for(const s of n)i.has(s)||(r+=1);return{changed:o+r,added:o,removed:r}})(t===bm?[]:t.retainedShapeIds,r);return{metrics:{culledCount:n.length,visibleCount:i.length,retainedCount:r.length,retainedBaseCount:o.length,culledRangeCount:d.length,culledRangeSpan:Pi(d),culledRangesSummary:Ii(d),retainedBaseRangeCount:c.length,retainedBaseRangeSpan:Pi(c),retainedBaseRangesSummary:Ii(c),retainedRangeCount:l.length,retainedRangeSpan:Pi(l),retainedRangesSummary:Ii(l),retainedChangeCount:u.changed,retainedAddedCount:u.added,retainedRemovedCount:u.removed,selectedOutsideCulledCount:s.length},retainedShapeIds:r.slice()}},{isEqual:(e,t)=>le(e.metrics,t.metrics)}),this.renderHostDebugStateSignal=a("editor.renderHostDebugState.public",()=>this.renderHostDebugStateSnapshotSignal.get().metrics,{isEqual:le})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},pS=class{editor;activeToolId=s("tools.activeToolId","select");isToolLocked=s("tools.isToolLocked",!1);registry=new Map;activeTool=null;constructor(e){this.editor=e}register(e,t,n={}){this.registry.set(e,t),n.shortcut&&this.editor.shortcuts.registerToolShortcut(e,n.shortcut)}hasTool(e){return this.registry.has(e)}setActiveTool(e,t="tool_switch"){const n=this.registry.get(e);if(!n)throw new Error(`Unknown tool "${e}"`);this.activeTool&&this.activeToolId.get()===e||(this.activeTool&&(this.activeTool.dispatch({type:"cancel",reason:t}),this.activeTool.exit({reason:t}),this.editor.inputs.resetPointer(),this.editor.clearSelectionTransients()),this.activeToolId.set(e),this.activeTool=n(this.editor),this.activeTool.enter())}dispatch(e){this.activeTool?.dispatch(e)}cancel(e){this.activeTool?.dispatch({type:"cancel",reason:e})}setToolLocked(e){this.isToolLocked.set(e)}isActiveToolInInitialState(){return this.activeTool?.isInInitialState()??!0}},gS=class{handlers=[];registeredIds=new Set;register(e){this.registeredIds.has(e.id)||(this.handlers.push(e),this.registeredIds.add(e.id))}getHandlers(){return this.handlers}handleEvent(e,t){for(const n of this.handlers)if("handled"===n.editorEvent?.handleEvent(e,t))return"handled";return"continue"}createSelectionHandleSession(e,t){for(const n of this.handlers){const i=n.selectionHandle?.createSession(e,t);if(i)return i}return null}},fS=class{interactions;handlers=[];constructor(e){this.interactions=e}register(e){this.handlers.push(e)}createSession(e,t){const n=this.interactions?.createSelectionHandleSession(e,t)??null;if(n)return n;for(const i of this.handlers){const n=i.createSession(e,t);if(n)return n}return null}},mS=class{store;[Um];inputs=new qm;snapshots=new Vm(this);clipboard=new Wm(this);shortcuts=new uS;tools=new pS(this);camera=new Nm(this);selection=new sS(this);selectionLayout=new rS(this);editing=new dS(this);geometry=new lS(this);hierarchy=new cS(this);shapeUtils=new Mm;shapeSvgExporters=new $m;bindingUtils=new vm;interactions=new gS;selectionHandleInteractions=new fS(this.interactions);queries;bindings;spatialIndex;snaps;renderWindow;selectionOverlay;transients=new jm(this);history;sideEffects=new oS;commands;shapeCapabilityDefinitions;brushBoxSignal=this.transients.brushBoxSignal;brushBoxActiveSignal=this.transients.brushBoxActiveSignal;erasingShapeIdsSignal=this.transients.erasingShapeIdsSignal;erasingShapeIdsActiveSignal=this.transients.erasingShapeIdsActiveSignal;eraserTrailSignal=this.transients.eraserTrailSignal;eraserTrailActiveSignal=this.transients.eraserTrailActiveSignal;laserTrailSignal=this.transients.laserTrailSignal;laserTrailActiveSignal=this.transients.laserTrailActiveSignal;bindingPreviewSignal=this.transients.bindingPreviewSignal;bindingPreviewActiveSignal=this.transients.bindingPreviewActiveSignal;terminalBindingGuidesSignal=this.transients.terminalBindingGuidesSignal;dropTargetShapeIdSignal=this.transients.dropTargetShapeIdSignal;hoveredShapeIdSignal=this.transients.hoveredShapeIdSignal;selectionTranslationActiveSignal=this.transients.selectionTranslationActiveSignal;snapIndicatorsSignal;snapIndicatorsActiveSignal;get viewportScreenSizeSignal(){return this.camera.viewportScreenSizeSignal}shapeEditingEntryRequestSignal=this.editing.entryRequestSignal;_shapeDefaultPropsByTypeSignal=s("editor.shapeDefaultPropsByType",new Map);shapeDefaultPropsByTypeSignal=this._shapeDefaultPropsByTypeSignal;nextShapeNumber=1;nextPageNumber=1;nextBindingNumber=1;nextAssetNumber=1;assetUrlResolver=()=>null;get _internalStore(){return _(this)}sessionSignal=a("editor.session",()=>{const e=this._internalStore.getRecordSignal(Em).get();if(!g(e))throw new Error("Missing session record");return e});currentPageIdSignal=a("editor.currentPageId",()=>this.sessionSignal.get().currentPageId);currentPageShapeIdsSignal;currentPageShapesSignal;culledShapeIdsSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionAnchorPagePointSignal;pagesSignal=a("editor.pages",()=>Array.from(this._internalStore.recordsSignal.get().values()).filter(u).sort((e,t)=>e.index.localeCompare(t.index)));currentPageSignal=a("editor.currentPage",()=>{const e=this.currentPageIdSignal.get();return this.pagesSignal.get().find(t=>t.id===e)??null});pageStateSignal=a("editor.pageState",()=>{const e=this.pagesSignal.get(),t=this.currentPageIdSignal.get(),n=e.find(e=>e.id===t)??null;return{pages:e,currentPageId:t,currentPage:n,canDeleteCurrentPage:e.length>1&&null!==n}});toolStateSignal=a("editor.toolState",()=>{const e=this.sessionSignal.get();return{activeToolId:e.activeToolId,isToolLocked:e.isToolLocked}});editingShapeIdSignal=a("editor.editingShapeId",()=>this.sessionSignal.get().editingShapeId);shapeEditingSessionSignal=a("editor.shapeEditingSession",()=>this.sessionSignal.get().shapeEditingSession);shapeEditingStateSignal=a("editor.shapeEditingState",()=>({editingShapeId:this.editingShapeIdSignal.get(),session:this.shapeEditingSessionSignal.get()}));currentCameraSignal=a("editor.currentCamera",()=>this.sessionSignal.get().pageCameraById[this.currentPageIdSignal.get()]??Bm);selectedShapeIdsSignal=a("editor.selectedShapeIds",()=>{const e=this.sessionSignal.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:oe});selectionCountSignal=a("editor.selectionCount",()=>this.selectedShapeIdsSignal.get().length);selectedShapeIdSetSignal=a("editor.selectedShapeIdSet",()=>new Set(this.selectedShapeIdsSignal.get()),{isEqual:pe});selectedShapesSignal=a("editor.selectedShapes",()=>this.selectedShapeIdsSignal.get().map(e=>this.getShapeSignal(e).get()).filter(e=>!!e));selectedShapeOverlayItemsSignal=a("editor.selectedShapeOverlayItems",()=>"select"!==this.toolStateSignal.get().activeToolId?[]:this.selectedShapeIdsSignal.get().map(e=>this.getShapeSignal(e).get()).filter(e=>!!e).map(e=>{const t=this.getShapeUtil(e).getSelectionOverlayInfo(e,{editor:this});return{id:e.id,usesSelectionPathOverlay:t.usesSelectionPathOverlay,startPagePoint:t.startPagePoint,endPagePoint:t.endPagePoint,middlePagePoint:t.middlePagePoint,path:t.path,bindingSegments:t.bindingSegments??[]}}),{isEqual:_n});selectionStateSignal=a("editor.selectionState",()=>{const e=this.selectedShapeIdsSignal.get(),t=1===e.length?this.getShapeSignal(e[0]).get()??null:null,n=this.selectedShapesSignal.get(),i=(e=>{let t=null;for(const n of e)if(null!==t){if(t!==n.type)return null}else t=n.type;return t})(n),o=1===n.length,r=n.map(e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:o,editor:this})).some(e=>e.terminalHandleAnchors.length>0||e.middleHandleAnchors.length>0||(e.customHandleAnchors?.length??0)>0),s=n.some(e=>this.getShapeUtil(e).contributesToSelectionFrame(e,{editor:this})),a=r&&s,d=t?this.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:o,editor:this}):null,l=1===e.length&&!!d&&(d.terminalHandleAnchors.length>0||(d.customHandleAnchors?.length??0)>0),c=this.queries.selectionHasRotationSignal.get();return{count:e.length,singleShapeType:t?.type??null,commonShapeType:i,hasPointHandleSelection:r,hasFrameSelection:s,isMixedFrameAndPointHandleSelection:a,canDragPointHandles:l,hasSelectionRotation:c,hasMixedSelectionRotation:!this.queries.selectionHasCompatibleRotationSignal.get(),canResetSelectionRotation:c&&s,frameBounds:this.selectionFrameBoundsSignal.get(),frameRotation:this.queries.selectionRotationSignal.get(),frameRotationCenter:this.queries.selectionRotationCenterSignal.get(),selectionAnchorPagePoint:this.selectionAnchorPagePointSignal.get()}});pageTransformSignal=a("editor.pageTransform",()=>{const e=this.currentCameraSignal.get();return km.Scale(e.z,e.z).compose(km.Translate(-e.x,-e.y))});cameraZoomSignal=a("editor.cameraZoom",()=>this.currentCameraSignal.get().z);viewportPageBoundsSignal=a("editor.viewportPageBounds",()=>{const{w:e,h:t}=this.viewportScreenSizeSignal.get();if(e<=0||t<=0)return null;const n=this.currentCameraSignal.get();return new Pm(n.x,n.y,e/n.z,t/n.z)});renderViewportPageBoundsSignal=a("editor.renderViewportPageBounds",e=>{const t=this.viewportPageBoundsSignal.get();return t?e!==bm&&e&&(i=t).minX>=(n=e).minX&&i.maxX<=n.maxX&&i.minY>=n.minY&&i.maxY<=n.maxY?e:t.expand(160/this.cameraZoomSignal.get()):null;var n,i},{isEqual:ae});renderItemsSignal;renderHostDebugStateSignal;historyStateSignal;shapeRenderOrderByIdSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdSetSignal;shapeSignals=new Map;shapeSelectedSignals=new Map;shapeRenderOrderSignals=new Map;shapeRenderVisibleSignals=new Map;shapeDocumentVisibleSignals=new Map;shapeEditingSessionSignals=new Map;shapeDropTargetSignals=new Map;shapeHoveredSignals=new Map;shapeErasingSignals=new Map;shapeSelectedDescendantTransformAncestorSignals=new Map;lastPointerDownForClickCount=null;lastPointerUpForClickCount=null;currentPointerClickCount=1;selectionOverlayFrameGeometrySignal;selectionOverlayCompanionFrameGeometriesSignal;selectionOverlayPathSignal;selectionOverlayBindingSegmentsSignal;selectionOverlayFrameStyleSignal;selectionOverlayFrameSignal;selectionOverlayHandleAnchorsSignal;selectionOverlayHandlesSignal;selectionOverlayHandleCountsSignal;selectionOverlaySignal;overlayDebugStateSignal;constructor(e={}){this.shapeCapabilityDefinitions=e.shapeCapabilities??[],e.resolveAssetUrl&&(this.assetUrlResolver=e.resolveAssetUrl);for(const i of e.shapeUtils??[])this.shapeUtils.register(i);for(const i of e.shapeSvgExporters??[])this.shapeSvgExporters.register(i);for(const i of e.bindingUtils??[])this.bindingUtils.register(i);const t=new zm(this.snapshots.buildInitialRecords(e.documentSnapshot??null,e.sessionSnapshot??null,e.documentMeta??{}));var n;((e,t)=>{e[Um]=t})(this,t),this.store=t,this.snapshots.ensureSessionIntegrity(),this.queries=new Zm(this),this.bindings=new Hm(this),this.spatialIndex=new Jm(this,this.queries),this.snaps=new iS(this),this.snapIndicatorsSignal=this.snaps.indicatorsSignal,this.snapIndicatorsActiveSignal=this.snaps.activeSignal,this.currentPageShapeIdsSignal=this.queries.currentPageShapeIdsSignal,this.currentPageShapesSignal=this.queries.currentPageShapesSignal,this.selectionPageBoundsSignal=this.queries.selectionPageBoundsSignal,this.selectionFrameBoundsSignal=this.queries.selectionFrameBoundsSignal,this.selectionAnchorPagePointSignal=this.queries.selectionAnchorPagePointSignal,this.selectionOverlay=new aS(this),this.selectionOverlayFrameGeometrySignal=this.selectionOverlay.frameGeometrySignal,this.selectionOverlayCompanionFrameGeometriesSignal=this.selectionOverlay.companionFrameGeometriesSignal,this.selectionOverlayPathSignal=this.selectionOverlay.pathSignal,this.selectionOverlayBindingSegmentsSignal=this.selectionOverlay.bindingSegmentsSignal,this.selectionOverlayFrameStyleSignal=this.selectionOverlay.frameStyleSignal,this.selectionOverlayFrameSignal=this.selectionOverlay.frameSignal,this.selectionOverlayHandleAnchorsSignal=this.selectionOverlay.handleAnchorsSignal,this.selectionOverlayHandlesSignal=this.selectionOverlay.handlesSignal,this.selectionOverlayHandleCountsSignal=this.selectionOverlay.handleCountsSignal,this.selectionOverlaySignal=this.selectionOverlay.overlaySignal,this.overlayDebugStateSignal=this.selectionOverlay.debugStateSignal,this.renderWindow=new hS(this),this.shapeRenderOrderByIdSignal=this.renderWindow.shapeRenderOrderByIdSignal,this.culledShapeIdsSignal=this.renderWindow.culledShapeIdsSignal,this.culledShapeIdSetSignal=this.renderWindow.culledShapeIdSetSignal,this.selectedShapeIdsOutsideCulledSignal=this.renderWindow.selectedShapeIdsOutsideCulledSignal,this.selectedShapeIdsOutsideCulledSetSignal=this.renderWindow.selectedShapeIdsOutsideCulledSetSignal,this.renderVisibleShapeIdsSignal=this.renderWindow.renderVisibleShapeIdsSignal,this.retainedShapeIdsSignal=this.renderWindow.retainedShapeIdsSignal,this.renderVisibleShapeIdSetSignal=this.renderWindow.renderVisibleShapeIdSetSignal,this.renderItemsSignal=this.renderWindow.renderItemsSignal,this.renderHostDebugStateSignal=this.renderWindow.renderHostDebugStateSignal,this.syncShapeCounter(),this.syncPageCounter(),this.syncBindingCounter(),this.syncAssetCounter(),this.bindings.repairLoadedBindings("system"),this.history=new _m(this),this.historyStateSignal=this.history.state,this.commands=(n=this,{createPage:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.createPageRecord(t);let r=o;return _(e).atomic(()=>{const t=j([...e.getPages(),o]);r=t.find(e=>e.id===o.id)??o,_(e).put(t,i),e.ensurePageSessionState(r.id,i)},i),r})(n,e,t),deletePage:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getPages();if(o.length<=1)return!1;const r=o.findIndex(e=>e.id===t);if(r<0)return!1;const s=e.getShapesForPage(t).map(e=>e.id),a=j(o.filter(e=>e.id!==t)),d=o[r+1]?.id??o[r-1]?.id??o[0]?.id,l=e.getCurrentPageId()===t&&d?d:e.getCurrentPageId();return _(e).atomic(()=>{s.length>0&&te(e,s,n),_(e).remove([t],i),e.removePageSessionState(t,l,i),_(e).put(a,i)},i),!0})(n,e,t),renamePage(e,t){((e,t,n)=>{const i=n?.source??"user",o=e.getPage(t.id);if(!o)return;const r=t.name.trim();r&&r!==o.name&&_(e).atomic(()=>{_(e).put([{...o,name:r}],i)},i)})(n,e,t)},updateDocumentMeta:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getDocumentMetadataRecord()??d(),r={...o,meta:{...o.meta,...t.patch}};return _(e).atomic(()=>{_(e).put([r],i)},i),r})(n,e,t),updatePageMeta:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getPage(t.id);if(!o)return null;const r={...o,meta:{...o.meta,...t.patch}};return _(e).atomic(()=>{_(e).put([r],i)},i),r})(n,e,t),movePage(e,t){((e,t,n)=>{const i=n?.source??"user",o=e.getPages(),r=o.findIndex(e=>e.id===t.id);if(r<0)return;const s=Math.max(0,Math.min(t.toIndex,o.length-1));if(r===s)return;const a=[...o],[d]=a.splice(r,1);d&&(a.splice(s,0,d),_(e).atomic(()=>{_(e).put(j(a),i)},i))})(n,e,t)},createShapes:(e,t)=>((e,t,n)=>{const i=[],o=n?.source??"user";return _(e).atomic(()=>{const n=t.map(t=>{const n=e.createShapeRecord(t);if("user"!==o||t.parentId)return n;const i=e.getContainingParentIdForShapeRecord(n);return i&&i!==n.parentId?{...n,parentId:i}:n});i.push(...n),_(e).put(n,o)},o),i})(n,e,t),createShapesFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(_(e).atomic(()=>{_(e).put(t,i)},i),t)})(n,e,t),updateShapes(e,t){Z(n,e,t)},reparentShapes(e,t){((e,t,n)=>{const i=((e,t)=>{const n=Array.from(new Set(t.ids)).map(t=>e.getShape(t)).filter(e=>!!e&&e.parentId!==t.parentId);if(0===n.length)return[];const i=e.getChildShapes(t.parentId).reduce((e,t)=>{const n=Number.parseInt(t.index,10);return Number.isFinite(n)?Math.max(e,n):e},0);return n.map((n,o)=>({id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+o+1)}))})(e,t);0!==i.length&&Z(e,i,n)})(n,e,t)},deleteShapes(e,t){te(n,e,t)},createAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.createAssetRecord(t);return _(e).atomic(()=>{_(e).put([o],i)},i),o})(n,e,t),createAssetsFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(_(e).atomic(()=>{_(e).put(t,i)},i),t)})(n,e,t),updateAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getAsset(t.id);if(!o)return null;const r={...o,props:t.props?{...o.props,...t.props}:o.props,meta:t.meta??o.meta};return _(e).atomic(()=>{_(e).put([r],i)},i),r})(n,e,t),deleteAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return!!e.getAsset(t)&&(_(e).atomic(()=>{_(e).remove([t],i)},i),!0)})(n,e,t),createBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.createBindingRecord(t);if(!ne(e,o))throw new Error(`Invalid binding endpoints for ${o.type} binding`);return _(e).atomic(()=>{const t=e.bindings.getConflictingBindings(o).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),_(e).put([o],i),e.bindings.syncCreatedBinding(o,i)},i),o})(n,e,t),updateBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getBinding(t.id);if(!o)return null;const r=e.getBindingUtil(o),s={...o,fromId:t.fromId??o.fromId,toId:t.toId??o.toId,props:t.props?r.validateProps({...o.props,...t.props}):o.props,meta:t.meta??o.meta};if(!ne(e,s))throw new Error(`Invalid binding endpoints for ${s.type} binding`);return _(e).atomic(()=>{const t=e.bindings.getConflictingBindings(s).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),_(e).put([s],i),e.bindings.syncUpdatedBinding(o,s,i)},i),s})(n,e,t),deleteBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getBinding(t);return!!o&&(_(e).atomic(()=>{e.bindings.cleanupBindings([o.id],i),_(e).remove([o.id],i)},i),!0)})(n,e,t),setCurrentPageId(e,t){((e,t,n)=>{e.setCurrentPage(t,n?.source??"system")})(n,e,t)},setCamera(e,t){((e,t,n)=>{e.setCamera(t.camera,{pageId:t.pageId,source:n?.source??"system"})})(n,e,t)},setSelectedShapeIds(e,t){((e,t,n)=>{e.setSelectedShapeIds(t,{source:n?.source??"user"})})(n,e,t)},setActiveTool(e,t){((e,t,n)=>{const i=n?.source??"system";e.completeEditing(i),e.tools.setActiveTool(t),e.updateSession({activeToolId:t},i)})(n,e,t)},setToolLocked(e,t){((e,t,n)=>{const i=n?.source??"system";e.tools.setToolLocked(t),e.updateSession({isToolLocked:t},i)})(n,e,t)}}),this.registerBuiltInInteractions(),this.registerBuiltInShortcuts(),this.registerBuiltInSideEffects()}registerBuiltInInteractions(){this.interactions.register((()=>{let e=null;const t=()=>{e=null};return{id:"land.camera.middle-mouse-pan",editorEvent:{handleEvent:(n,i)=>"cancel"===i.type?(t(),"continue"):"pointer"!==i.type||"mouse"!==i.pointerType?"continue":"pointer_down"===i.name?(t(),1!==i.button?"continue":(n.resetPointerClickTracking(),e={pointerId:i.pointerId,originScreenPoint:i.screenPoint.clone(),originCamera:n.getCurrentCamera()},"handled")):e&&i.pointerId===e.pointerId?"pointer_move"===i.name?4&i.buttons?(((e,t,n)=>{const i=t.screenPoint.sub(n.originScreenPoint),o=n.originCamera.z;e.setCamera({x:n.originCamera.x-i.x/o,y:n.originCamera.y-i.y/o},{source:"user"})})(n,i,e),"handled"):(t(),"handled"):"pointer_up"===i.name||"pointer_cancel"===i.name?(t(),"handled"):"continue":"continue"}}})())}registerBuiltInShortcuts(){this.shortcuts.registerEditorShortcut("move-selection-backward",{key:"ArrowDown",altKey:!0}),this.shortcuts.registerEditorShortcut("move-selection-forward",{key:"ArrowUp",altKey:!0}),this.shortcuts.registerEditorShortcut("undo",{key:"z",accelKey:!0}),this.shortcuts.registerEditorShortcut("redo",{key:"z",accelKey:!0,shiftKey:!0}),this.shortcuts.registerEditorShortcut("delete-selection","Backspace"),this.shortcuts.registerEditorShortcut("delete-selection","Delete"),this.shortcuts.registerEditorShortcut("reset-interaction","Escape")}registerBuiltInSideEffects(){this.sideEffects.registerBeforeDeleteHandler("shape",(e,t)=>{this.bindings.cleanupBindingsForDeletedShapes(e,t)}),this.sideEffects.registerAfterDeleteHandler("shape",(e,t)=>{this.removeShapeIdsFromSelection(e,t),this.removeShapeIdsFromEditingSession(e,t)})}dispatch(e){const t=this.normalizeEvent(e);if(this.inputs.handleEvent(t),"keyboard"===t.type&&"key_down"===t.name){const e=this.shortcuts.getTargetForEvent(t);if(e&&this.runKeyboardShortcutTarget(e))return}if("wheel"!==t.type){if("cancel"===t.type)return this.interactions.handleEvent(this,t),void this.cancelInteractionAndClearTransients(t.reason);if("pointer"===t.type&&"pointer_cancel"===t.name)return this.interactions.handleEvent(this,t),void this.cancelInteractionAndClearTransients("pointer_cancel");if("handled"!==this.interactions.handleEvent(this,t)&&(this.tools.dispatch(t),"pointer"===t.type&&"pointer_up"===t.name)){const e=this.getDoubleClickEvent(t);e&&"handled"!==this.interactions.handleEvent(this,e)&&this.tools.dispatch(e)}}else this.handleWheelEvent(t)}handleInteractionEvent(e){const t=this.normalizeEvent(e);return this.inputs.handleEvent(t),"handled"===this.interactions.handleEvent(this,t)}runKeyboardShortcutTarget(e){switch(e.type){case"action":return!1;case"editor":return this.runEditorKeyboardShortcut(e.command);case"tool":return this.commands.setActiveTool(e.toolId,{source:"system"}),!0}}runEditorKeyboardShortcut(e){switch(e){case"delete-selection":return this.deleteSelection("user"),!0;case"move-selection-backward":return this.moveSelectionWithinParent("backward","user");case"move-selection-forward":return this.moveSelectionWithinParent("forward","user");case"redo":return this.redo(),!0;case"reset-interaction":return this.tools.isActiveToolInInitialState()&&"select"!==this.getActiveToolId()?this.commands.setActiveTool("select",{source:"system"}):this.cancelInteractionAndClearTransients("escape"),!0;case"undo":return this.undo(),!0}}normalizeEvent(e){if("pointer"!==e.type)return e;if("pointer_up"===e.name){const t=e.clickCount===this.currentPointerClickCount?e:{...e,clickCount:this.currentPointerClickCount};return this.lastPointerUpForClickCount={timestamp:t.timestamp,screenPoint:t.screenPoint.clone()},t}if("pointer_down"!==e.name)return e;const t=this.lastPointerDownForClickCount,n=this.lastPointerUpForClickCount,i=t&&n&&n.timestamp>=t.timestamp&&e.timestamp-n.timestamp<=250&&n.screenPoint.dist2(e.screenPoint)<=1600?2:1;return this.lastPointerDownForClickCount={timestamp:e.timestamp,screenPoint:e.screenPoint.clone()},this.currentPointerClickCount=i,e.clickCount===i?e:{...e,clickCount:i}}getDoubleClickEvent(e){return(e.clickCount??1)<2||this.currentPointerClickCount<2?null:{type:"click",name:"double_click",phase:"up",timestamp:e.timestamp,pointerId:e.pointerId,button:e.button,buttons:e.buttons,pointerType:e.pointerType,screenPoint:e.screenPoint.clone(),pagePoint:e.pagePoint.clone(),pressure:e.pressure,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}listen(e){return this.store.listen(t=>e(t))}getRenderItems(){return this.renderItemsSignal.get()}getPages(){return this.pagesSignal.get()}getDocumentMetadataRecord(){const e=this._internalStore.get(Cm);return h(e)?e:void 0}getCurrentPageId(){return this.currentPageIdSignal.get()}getActiveToolId(){return this.sessionSignal.get().activeToolId}isToolLocked(){return this.sessionSignal.get().isToolLocked}isActiveToolInInitialState(){return this.tools.isActiveToolInInitialState()}getEditingShapeId(){return this.editingShapeIdSignal.get()}getShapeEditingSession(){return this.shapeEditingSessionSignal.get()}getShapeEditingEntryRequest(){return this.shapeEditingEntryRequestSignal.get()}resetPointerClickTracking(){this.lastPointerDownForClickCount=null,this.lastPointerUpForClickCount=null,this.currentPointerClickCount=1}getCurrentPageShapeIds(){return this.currentPageShapeIdsSignal.get()}getPage(e){const t=this._internalStore.get(e);return u(t)?t:void 0}getCurrentCamera(){return this.camera.getCurrentCamera()}undo(){return this.cancelInteractionForCommand(),this.history.undo()}redo(){return this.cancelInteractionForCommand(),this.history.redo()}createPageAndSelect(e,t="user"){const n=this.commands.createPage(e,{source:t});return this.commands.setCurrentPageId(n.id,{source:t}),n}selectPage(e,t="user"){this.commands.setCurrentPageId(e,{source:t})}renamePage(e,t,n="user"){this.commands.renamePage({id:e,name:t},{source:n})}updateDocumentMeta(e,t="user"){return this.commands.updateDocumentMeta({patch:e},{source:t})}updatePageMeta(e,t,n="user"){return this.commands.updatePageMeta({id:e,patch:t},{source:n})}deletePage(e,t="user"){return this.cancelInteractionForCommand(),this.commands.deletePage(e,{source:t})}setActiveTool(e,t="system"){this.commands.setActiveTool(e,{source:t})}setToolLocked(e,t="system"){this.commands.setToolLocked(e,{source:t})}toggleToolLocked(e="system"){this.setToolLocked(!this.isToolLocked(),e)}getCamera(e=this.getCurrentPageId()){return this.camera.getCamera(e)}pageToScreen(e,t=this.getCurrentPageId()){return this.camera.pageToScreen(e,t)}screenToPage(e,t=this.getCurrentPageId()){return this.camera.screenToPage(e,t)}getSelectedShapeIds(e=this.getCurrentPageId()){return e===this.getCurrentPageId()?this.selectedShapeIdsSignal.get():this.sessionSignal.get().pageSelectedShapeIdsById[e]??[]}isShapeHidden(e){const t=new Set;let n=this.getShape(e);for(;n;){if(n.isHidden)return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(t.has(e))return!1;t.add(e),n=this.getShape(e)}return!1}getSelectedShapes(){return this.selectedShapesSignal.get()}getDefaultShapeProps(e){const t=this.shapeUtils.get(e),n=this._shapeDefaultPropsByTypeSignal.get().get(e)??{};return t.validateProps({...t.getDefaultProps(),...n})}updateDefaultShapeProps(e,t){const n=this.shapeUtils.get(e),i=this._shapeDefaultPropsByTypeSignal.get().get(e)??{},o=n.validateProps({...n.getDefaultProps(),...i,...t}),r=n.validateProps(n.getDefaultProps()),s={};for(const[d,l]of Object.entries(o))r[d]!==l&&(s[d]=l);if(((e,t)=>{if(e===t)return!0;const n=Object.entries(e),i=Object.entries(t);if(n.length!==i.length)return!1;for(const[o,r]of n)if(!fe(r,t[o]))return!1;return!0})(i,s))return;const a=new Map(this._shapeDefaultPropsByTypeSignal.get());0===Object.keys(s).length?a.delete(e):a.set(e,s),this._shapeDefaultPropsByTypeSignal.set(a)}getSelectionParentOrderState(){return this.hierarchy.getSelectionParentOrderState()}getSelectionGroupState(){return this.hierarchy.getSelectionGroupState()}canGroupSelection(){return this.hierarchy.canGroupSelection()}canGroupShapes(e){return this.hierarchy.canGroupShapes(e)}groupShapes(e,t="user"){return this.hierarchy.groupShapes(e,t)}groupSelection(e="user"){return this.hierarchy.groupSelection(e)}getUngroupableSelectedShapeIds(){return this.hierarchy.getUngroupableSelectedShapeIds()}getUngroupableShapeIds(e){return this.hierarchy.getUngroupableShapeIds(e)}canUngroupSelection(){return this.hierarchy.canUngroupSelection()}canUngroupShapes(e){return this.hierarchy.canUngroupShapes(e)}ungroupShapes(e,t="user"){return this.hierarchy.ungroupShapes(e,t)}ungroupSelection(e="user"){return this.hierarchy.ungroupSelection(e)}getSelectionSiblingOrderState(){return this.hierarchy.getSelectionSiblingOrderState()}canMoveSelectionWithinParent(e){return this.hierarchy.canMoveSelectionWithinParent(e)}canMoveSelectionInParentOrder(e){return this.hierarchy.canMoveSelectionInParentOrder(e)}canMoveShapesInParentOrder(e,t){return this.hierarchy.canMoveShapesInParentOrder(e,t)}moveShapesInParentOrder(e,t,n="user"){return this.hierarchy.moveShapesInParentOrder(e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return this.hierarchy.moveShapesToParentOrderEdge(e,t,n)}moveSelectionWithinParent(e,t="user"){return this.hierarchy.moveSelectionWithinParent(e,t)}alignSelection(e,t="user"){return this.cancelInteractionForCommand(),this.selectionLayout.align(e,t)}distributeSelection(e,t="user"){return this.cancelInteractionForCommand(),this.selectionLayout.distribute(e,t)}moveShapesToParentPlacement(e,t="user"){return this.hierarchy.moveShapesToParentPlacement(e,t)}moveShapesToParentPlacementResult(e,t="user"){return this.hierarchy.moveShapesToParentPlacementResult(e,t)}moveSelectionInParentOrder(e,t="user"){return this.hierarchy.moveSelectionInParentOrder(e,t)}moveSelectionToParentOrderEdge(e,t="user"){return this.hierarchy.moveSelectionToParentOrderEdge(e,t)}canEditShape(e){return this.editing.canEditShape(e)}startEditingShape(e,t="user"){return this.editing.start(e,t)}completeEditing(e="user"){return this.editing.complete(e)}cancelEditing(e="user"){return this.editing.cancel(e)}setShapeEditingComposition(e,t="system"){this.editing.setComposition(e,t)}consumeShapeEditingEntryRequest(e){this.editing.consumeEntryRequest(e)}deleteSelection(e="user"){this.deleteShapesById(this.getSelectedShapeIds(),e)}deleteShapesById(e,t="user"){const n=Array.from(new Set(e));0!==n.length&&(this.cancelInteractionForCommand(),this.commands.deleteShapes(n,{source:t}))}setShapesHidden(e,t,n="user"){const i=Array.from(new Set(e.filter(e=>{const n=this.getShape(e);return!!n&&n.isHidden!==t})));return 0===i.length?[]:(this.cancelInteractionForCommand(),this.commands.updateShapes(i.map(e=>({id:e,isHidden:t})),{source:n}),t&&(this.removeShapeIdsFromSelection(this.getShapeIdsIncludingDescendants(i),n),this.removeShapeIdsFromEditingSession(this.getShapeIdsIncludingDescendants(i),n)),i)}setShapesLocked(e,t,n="user"){const i=Array.from(new Set(e.filter(e=>{const n=this.getShape(e);return!!n&&n.isLocked!==t})));return 0===i.length?[]:(this.cancelInteractionForCommand(),this.commands.updateShapes(i.map(e=>({id:e,isLocked:t})),{source:n}),t&&(this.removeShapeIdsFromSelection(this.getShapeIdsIncludingDescendants(i),n),this.removeShapeIdsFromEditingSession(this.getShapeIdsIncludingDescendants(i),n)),i)}createClipboardPayloadFromSelection(){return this.clipboard.createPayloadFromSelection()}pasteClipboardPayload(e){return this.clipboard.pastePayload(e)}duplicateSelection(e={}){return this.clipboard.duplicateSelection(e)}selectAllCurrentPage(e="user"){this.cancelInteractionForCommand(),this.selection.selectAllCurrentPage(e)}resetSelectionRotation(e="user"){((e,t="user")=>{const n=e.getSelectedShapes().filter(t=>e.getShapeUtil(t).contributesToSelectionFrame(t,{editor:e}));0!==n.length&&e.commands.updateShapes(n.map(e=>({id:e.id,rotation:0})),{source:t})})(this,e)}flipSelection(e,t="user"){const n=function(e,t){const n=e.getSelectionTransformTargetShapes(),i=e.getSelectionFrame()??((e,t)=>{const n=t.flatMap(t=>e.getShapeUtil(t).getSelectionPagePoints(t)??[]);if(0===n.length)return null;const i=Pm.FromPoints(n);return{bounds:i,rotation:0,rotationCenter:i.center,hasCompatibleRotation:!0}})(e,n);return i&&0!==n.length?n.map(n=>((e,t,n,i)=>{const o=e.getShapeUtil(t),r=o.getSelectionPagePoints(t);if(!r&&!o.contributesToSelectionFrame(t,{editor:e}))return null;const s=(({points:e,transform:t})=>0===e.length?null:Pm.FromPoints(e.map(e=>Bn(e,t))))({points:r?[...r]:o.getPositionedOutlineVertices(t).map(n=>e.computeShapePositionedToPageTransform(t).applyToPoint(n)),transform:n});return s?o.flipSelectionBounds(t,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:$n({axis:i,bounds:s,selectionBounds:n.bounds}),selectionRotation:n.rotation,selectionRotationCenter:n.rotationCenter}):null})(e,n,i,t)).filter(e=>null!==e):[]}(this,e);0!==n.length&&(this.cancelInteractionForCommand(),this.commands.updateShapes(n,{source:t}))}getShape(e){const t=this._internalStore.get(e);return p(t)?t:void 0}getAsset(e){const t=this._internalStore.get(e);return m(t)?t:void 0}getAssets(){return this._internalStore.getAll().filter(m).sort((e,t)=>e.id.localeCompare(t.id))}resolveAssetUrl(e){return this.assetUrlResolver(e)}getUnreferencedAssetIdsAfterShapeDelete(e){if(0===e.length)return[];const t=new Set(e),n=new Set,i=new Set;for(const o of this._internalStore.getAll().filter(p)){const e=ge(o);e&&(t.has(o.id)?n.add(e):i.add(e))}return this.getAssets().map(e=>e.id).filter(e=>n.has(e)&&!i.has(e))}getShapeSignal(e){let t=this.shapeSignals.get(e);return t||(t=a(`editor.shape.${e}`,()=>{const t=this._internalStore.getRecordSignal(e).get();return p(t)?t:void 0}),this.shapeSignals.set(e,t)),t}getShapeSelectedSignal(e){let t=this.shapeSelectedSignals.get(e);return t||(t=a(`editor.shapeSelected.${e}`,()=>this.selectedShapeIdSetSignal.get().has(e)),this.shapeSelectedSignals.set(e,t)),t}getShapeRenderOrderSignal(e){let t=this.shapeRenderOrderSignals.get(e);return t||(t=a(`editor.shapeRenderOrder.${e}`,()=>this.shapeRenderOrderByIdSignal.get().get(e)??-1),this.shapeRenderOrderSignals.set(e,t)),t}getShapeRenderVisibleSignal(e){let t=this.shapeRenderVisibleSignals.get(e);return t||(t=a(`editor.shapeRenderVisible.${e}`,()=>{const t=this.getShapeClipAncestorIdsSignal(e).get().length>0;return this.renderVisibleShapeIdSetSignal.get().has(e)&&!this.isShapeHidden(e)&&(!t||null!==this.getShapeClippedPageBounds(e))}),this.shapeRenderVisibleSignals.set(e,t)),t}getShapeDocumentVisibleSignal(e){let t=this.shapeDocumentVisibleSignals.get(e);return t||(t=a(`editor.shapeDocumentVisible.${e}`,()=>{const t=this.getShapeSignal(e).get();return!!t&&!this.isShapeHidden(t.id)}),this.shapeDocumentVisibleSignals.set(e,t)),t}getShapeEditingSessionForShapeSignal(e){let t=this.shapeEditingSessionSignals.get(e);return t||(t=a(`editor.shapeEditingSessionForShape.${e}`,()=>{const t=this.shapeEditingSessionSignal.get();return t?.shapeId===e?t:null}),this.shapeEditingSessionSignals.set(e,t)),t}getShapeDropTargetSignal(e){let t=this.shapeDropTargetSignals.get(e);return t||(t=a(`editor.shapeDropTarget.${e}`,()=>this.dropTargetShapeIdSignal.get()===e),this.shapeDropTargetSignals.set(e,t)),t}getShapeHoveredSignal(e){let t=this.shapeHoveredSignals.get(e);return t||(t=a(`editor.shapeHovered.${e}`,()=>this.hoveredShapeIdSignal.get()===e),this.shapeHoveredSignals.set(e,t)),t}getShapeErasingSignal(e){let t=this.shapeErasingSignals.get(e);return t||(t=a(`editor.shapeErasing.${e}`,()=>{const t=new Set(this.erasingShapeIdsSignal.get());return this.hierarchy.isShapeOrAncestorInSet(e,t)}),this.shapeErasingSignals.set(e,t)),t}getShapeSelectedDescendantTransformAncestorSignal(e){let t=this.shapeSelectedDescendantTransformAncestorSignals.get(e);return t||(t=a(`editor.shapeSelectedDescendantTransformAncestor.${e}`,()=>{if(this.getShapeSelectedSignal(e).get())return!1;const t=this.getShapeSignal(e).get();return!(!t||!this.getShapeUtil(t).isTransformDescendantContainer(t))&&this.selectedShapeIdsSignal.get().some(t=>this.hierarchy.isShapeDescendantOf(t,e))}),this.shapeSelectedDescendantTransformAncestorSignals.set(e,t)),t}getBinding(e){const t=this._internalStore.get(e);return f(t)?t:void 0}getShapesForPage(e){return this.queries.getShapesForPage(e)}getBindingsFromShape(e){return this.queries.getBindingsFromShape(e)}getBindingsToShape(e){return this.queries.getBindingsToShape(e)}getBindingsForShape(e){return this.queries.getBindingsForShape(e)}getChildShapeIds(e){return this.queries.getChildShapeIds(e)}getChildShapes(e){return this.queries.getChildShapes(e)}getDescendantShapeIds(e){return this.queries.getDescendantShapeIds(e)}getDescendantPageBounds(e){return this.queries.getDescendantPageBounds(e)}getShapeSubtreePageBounds(e){return this.queries.getShapeSubtreePageBounds(e)}getShapePageId(e){return this.queries.getPageIdForShape(e)}isShapeOrAncestorLocked(e){return this.hierarchy.isShapeOrAncestorLocked(e)}hasLockedDescendant(e){return this.hierarchy.hasLockedDescendant(e)}getOutermostSelectableShapeId(e){return this.hierarchy.getOutermostSelectableShapeId(e)}getShapeIdsIncludingDescendants(e){return this.hierarchy.getShapeIdsIncludingDescendants(e)}getShapeIdsForSelectionTransform(e){return this.hierarchy.getShapeIdsForSelectionTransform(e)}getShapeIdsForSelectionRotation(e){return this.hierarchy.getShapeIdsForSelectionRotation(e)}getSelectionTransformTargetShapes(){return this.hierarchy.getSelectionTransformTargetShapes()}getSelectionRotationTargetShapes(){return this.hierarchy.getSelectionRotationTargetShapes()}getShapeExportTraversalIds(e){return this.hierarchy.getShapeExportTraversalIds(e)}getShapeContainment(e,t){return this.queries.getShapeContainment(e,t)}getContainingShapeParentId(e){return this.queries.getContainingShapeParentId(e)}getContainingShapeParentIdAtPoint(e,t){return this.queries.getContainingShapeParentIdAtPoint(e,t)}getContainingParentIdForShapeRecord(e){return this.queries.getContainingParentIdForShapeRecord(e)}getShapeClipAncestorIds(e){return this.queries.getShapeClipAncestorIds(e)}getShapeClipAncestorIdsSignal(e){return this.queries.getShapeClipAncestorIdsSignal(e)}isPagePointInShapeClip(e,t){return this.queries.isPagePointInShapeClip(e,t)}getShapeClippedPageBounds(e){return this.queries.getShapeClippedPageBounds(e)}getShapeIdsInContainerBounds(e,t={}){return this.hierarchy.getShapeIdsInContainerBounds(e,t)}canUseShapeParent(e,t){return this.hierarchy.canUseShapeParent(e,t)}getShapeUtil(e){return this.shapeUtils.get(e.type)}getBindingUtil(e){return this.bindingUtils.get(e.type)}computeShapeBounds(e){return this.geometry.computeShapeBounds(e)}computeShapeLocalBounds(e){return this.geometry.computeShapeLocalBounds(e)}computeShapeRenderBounds(e){return this.geometry.computeShapeRenderBounds(e)}computeShapeExportBounds(e){return this.geometry.computeShapeExportBounds(e)}computeShapeLocalToPageTransform(e){return this.geometry.computeShapeLocalToPageTransform(e)}computeShapeRenderToPageTransform(e){return this.geometry.computeShapeRenderToPageTransform(e)}computeShapeExportToPageTransform(e){return this.geometry.computeShapeExportToPageTransform(e)}computeShapePageBounds(e){return this.geometry.computeShapePageBounds(e)}computeShapeExportPageBounds(e){return this.geometry.computeShapeExportPageBounds(e)}computeShapeGeometry(e){return this.geometry.computeShapeGeometry(e)}computeShapePositionedToPageTransform(e){return this.geometry.computeShapePositionedToPageTransform(e)}computeShapePageCenter(e){return this.geometry.computeShapePageCenter(e)}computeShapePageCorners(e){return this.geometry.computeShapePageCorners(e)}computeShapePageOutlineVertices(e){return this.geometry.computeShapePageOutlineVertices(e)}getShapeBounds(e){return this.geometry.getShapeBounds(e)}getShapePageBounds(e){return this.geometry.getShapePageBounds(e)}getShapeGeometry(e){return this.geometry.getShapeGeometry(e)}getShapePositionedToPageTransform(e){return this.geometry.getShapePositionedToPageTransform(e)}getShapePageCenter(e){return this.geometry.getShapePageCenter(e)}getShapePageCorners(e){return this.geometry.getShapePageCorners(e)}getShapePageOutlineVertices(e){return this.geometry.getShapePageOutlineVertices(e)}getSelectionPageBounds(){return this.geometry.getSelectionPageBounds()}getSelectionFrame(){return this.geometry.getSelectionFrame()}isPointInSelectionBounds(e){return this.geometry.isPointInSelectionBounds(e)}getSelectionFrameLocalBoundsPoint(e){return this.geometry.getSelectionFrameLocalBoundsPoint(e)}getSelectionPageOutlineVertices(){return this.geometry.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.geometry.getSelectionAnchorPagePoint()}hitTestSelectionHandle(e){const t=this.selectedShapesSignal.get(),n=this.getSelectionFrame();if(0===t.length)return null;const i=1===t.length,{terminalHandles:o,middleHandles:r,customHandles:s,rotateHandles:a,resizeHandles:d}=((e,t,n,i,o)=>ai(si(e,t,n,i,o),n))(t,n,this.getCurrentCamera().z,e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:i,editor:this}),e=>this.getShapeUtil(e).canUseSelectionFrameHandles(e,{editor:this}));for(const l of r)if(l.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return l;for(const l of o)if(l.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return l;for(const l of s)if(l.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return l;for(const l of d)if(l.bounds.containsPoint(e))return l;for(const l of a)if(l.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return l;return null}setBrushBox(e){this.transients.setBrushBox(e)}getErasingShapeIds(){return this.transients.getErasingShapeIds()}setErasingShapeIds(e){this.transients.setErasingShapeIds(e)}clearErasingShapeIds(){this.transients.clearErasingShapeIds()}getEraserTrail(){return this.transients.getEraserTrail()}setEraserTrail(e){this.transients.setEraserTrail(e)}clearEraserTrail(){this.transients.clearEraserTrail()}startLaserTrail(){return this.transients.startLaserTrail()}setLaserTrail(e,t){this.transients.setLaserTrail(e,t)}finishLaserTrail(e){this.transients.finishLaserTrail(e)}clearLaserTrail(e){this.transients.clearLaserTrail(e)}setBindingPreview(e){this.transients.setBindingPreview(e)}setTerminalBindingGuides(e){this.transients.setTerminalBindingGuides(e)}setDropTargetShapeId(e){this.transients.setDropTargetShapeId(e)}setHoveredShapeId(e){this.transients.setHoveredShapeId(e)}setSelectionTranslationActive(e){this.transients.setSelectionTranslationActive(e)}setSnapIndicators(e){this.transients.setSnapIndicators(e)}setTerminalBindingResolver(e){this.transients.setTerminalBindingResolver(e)}resolveTerminalBinding(e){return this.transients.resolveTerminalBinding(e)}clearSelectionTransients(){this.transients.clearSelectionTransients()}hitTestShape(e){return this.hitTestShapesAtPoint(e)[0]??null}hitTestShapesAtPoint(e,t){return this.spatialIndex.getShapesAtPoint(e,{...t,filter:n=>!this.isShapeHidden(n.id)&&this.isPagePointInShapeClip(n.id,e)&&(t?.filter?.(n)??!0)})}hitTestShapesByLineSegment(e,t,n){return this.spatialIndex.getShapesHitByLineSegment(e,t,{...n,filter:e=>!this.isShapeHidden(e.id)&&(n?.filter?.(e)??!0)})}getShapeIdsInBounds(e,t){return this.spatialIndex.getShapeIdsInBounds(e,t).filter(e=>!this.isShapeHidden(e))}getShapesInBounds(e,t){return this.spatialIndex.getShapesInBounds(e,t).filter(e=>!this.isShapeHidden(e.id))}getShapesInViewport(e,t){return this.spatialIndex.getShapesInViewport(e,t).filter(e=>!this.isShapeHidden(e.id))}getDocumentSnapshot(){return this.snapshots.getDocumentSnapshot()}getSessionSnapshot(){return this.snapshots.getSessionSnapshot()}getSvgString(e=this.getSelectedShapeIds(),t){return function(e,t,n,i={}){const o=Array.from(t),r=e.getShapeExportTraversalIds(o),s=new Set(r),a=[],d=[];for(const b of r){const t=e.getShape(b);t?d.push(t):a.push({id:b,reason:"missing-shape"})}if(0===d.length)return null;const l=[];for(const b of d){const t=B(e,b,s);t&&(U(t)?l.push(t):a.push({id:b.id,reason:"missing-bounds"}))}if(0===l.length)return null;const c=(e=>{let t=1/0,n=1/0,i=-1/0,o=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),i=Math.max(i,r.maxX),o=Math.max(o,r.maxY);return new Pm(t,n,i-t,o-n)})(l).expand(i.padding??16),u=[],h={editor:e,bounds:c,addDef(e){const t=`land-svg-def-${u.length+1}`;return u.push({...e,attrs:{...e.attrs,id:t}}),t},resolveAssetUrl:t=>e.resolveAssetUrl(t),resolveColor:e=>C(e,i.resolveThemeColor)},p=[],g=[],f=new Map;for(const b of d){const t=n.get(b.type);if(!t){a.push({id:b.id,reason:"missing-exporter"});continue}const i=t.toSvg(b,h);if(!i){a.push({id:b.id,reason:"empty-output"});continue}if(!U(e.computeShapeExportBounds(b))){a.push({id:b.id,reason:"missing-bounds"});continue}const o=e.computeShapeExportToPageTransform(b);p.push(b.id);const r=M(e,b,s,f,h);let d={tag:"g",attrs:{transform:o.toSvgString(),opacity:1===b.opacity?void 0:b.opacity},children:[i]};for(let e=r.length-1;e>=0;e-=1)d={tag:"g",attrs:{"clip-path":`url(#${r[e]})`},children:[d]};g.push(d)}if(0===p.length)return null;const m=Math.max(1,c.w),S=Math.max(1,c.h),y=[];return u.length>0&&y.push({tag:"defs",children:u}),i.background&&y.push({tag:"rect",attrs:{x:c.x,y:c.y,width:c.w,height:c.h,fill:i.background}}),y.push(...g),{svg:$({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:m,height:S,viewBox:`${z(c.x)} ${z(c.y)} ${z(m)} ${z(S)}`},children:y}),bounds:c,width:m,height:S,requestedShapeIds:o,exportedShapeIds:p,skippedShapes:a}}(this,e,this.shapeSvgExporters,t)}getExportIntegrityReport(e=this.getSelectedShapeIds()){return H({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}repairExportIntegrity(e=this.getSelectedShapeIds()){return(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),o=H({editor:e,exporters:t,shapeIds:i});o.repairableIssueCount>0&&e.bindings.repairLoadedBindings("system");const r=H({editor:e,exporters:t,shapeIds:i});return{before:o,after:r,repaired:o.issues.length!==r.issues.length}})({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}getShapeCapabilityManifest(){return(({definitions:e,exporters:t,shapeUtils:n})=>{const i=e.map(e=>{const i=n.has(e.type)?"supported":"missing",o=t.has(e.type)?"supported":"missing",r="supported"===i&&"supported"===o?"supported":"missing";return{...e,shapeUtil:i,svgExporter:o,exportSupport:r}});return{entries:i,supportedExportTypes:i.filter(e=>"supported"===e.exportSupport).map(e=>e.type),missingExporterTypes:i.filter(e=>"supported"!==e.svgExporter).map(e=>e.type)}})({definitions:this.shapeCapabilityDefinitions,exporters:this.shapeSvgExporters,shapeUtils:this.shapeUtils})}createPageRecord(e){const t=this.nextPageNumber;return{id:this.createPageId(t),typeName:"page",scope:"document",name:e?.name??`Page ${t}`,index:e?.index??this.createPageIndex(t),meta:e?.meta??{}}}loadDocumentSnapshot(e,t){this.snapshots.loadDocumentSnapshot(e,t)}loadSessionSnapshot(e,t){this.snapshots.loadSessionSnapshot(e,t)}syncAfterDocumentRestore(){this.snapshots.syncAfterDocumentRestore()}cancelInteractionForCommand(){this.cancelInteractionAndClearTransients("command")}cancelInteractionAndClearTransients(e){this.tools.cancel(e),this.inputs.resetPointer(),this.clearSelectionTransients()}syncToolStateFromSession(e){const{activeToolId:t,isToolLocked:n}=this.sessionSignal.get();this.tools.hasTool(t)?this.tools.setActiveTool(t,"restore"):(this.tools.setActiveTool("select","restore"),this.updateSession({activeToolId:"select"},e)),this.tools.setToolLocked(n)}createShapeRecord(e){const t=e.parentId??this.sessionSignal.get().currentPageId;if(!this.canUseShapeParent(t))throw new Error("Invalid parent id for shape");const n=this.nextShapeNumber,i=this.createShapeId(n),o=this.shapeUtils.get(e.type).validateProps({...this.getDefaultShapeProps(e.type),...e.props});return{id:i,typeName:"shape",scope:"document",type:e.type,parentId:t,index:e.index??this.createShapeIndex(n),x:e.x,y:e.y,rotation:e.rotation??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,opacity:e.opacity??1,isHidden:e.isHidden??!1,isLocked:e.isLocked??!1,props:o,meta:e.meta??{}}}createBindingRecord(e){const t=e.id??this.createBindingId(this.nextBindingNumber),n=this.bindingUtils.get(e.type),i=n.validateProps({...n.getDefaultProps(),...e.props});return{id:t,typeName:"binding",scope:"document",type:e.type,fromId:e.fromId,toId:e.toId,props:i,meta:e.meta??{}}}createAssetRecord(e){return{id:e.id??this.createAssetId(this.nextAssetNumber),typeName:"asset",scope:"document",type:e.type,props:e.props??{},meta:e.meta??{}}}updateSession(e,t="system"){const n=this.sessionSignal.get();this._internalStore.put([{...n,...e}],t)}setCurrentPage(e,t="system"){if(!this.getPage(e))return;e!==this.getCurrentPageId()&&(this.cancelInteractionAndClearTransients("page_switch"),this.completeEditing(t));const n=this.sessionSignal.get();this.updateSession({currentPageId:e,pageCameraById:{...n.pageCameraById,[e]:n.pageCameraById[e]??{...Bm}},pageSelectedShapeIdsById:{...n.pageSelectedShapeIdsById,[e]:n.pageSelectedShapeIdsById[e]??[]}},t)}setSelectedShapeIds(e,t){this.selection.setSelectedShapeIds(e,t)}removeShapeIdsFromSelection(e,t="system"){this.selection.removeShapeIdsFromSelection(e,t)}removeShapeIdsFromEditingSession(e,t="system"){this.editing.removeShapeIds(e,t)}ensurePageSessionState(e,t="system"){const n=this.sessionSignal.get(),i=n.pageCameraById[e]??{...Bm},o=n.pageSelectedShapeIdsById[e]??[];this.updateSession({pageCameraById:{...n.pageCameraById,[e]:i},pageSelectedShapeIdsById:{...n.pageSelectedShapeIdsById,[e]:o}},t)}removePageSessionState(e,t,n="system"){const i=this.sessionSignal.get(),o={...i.pageCameraById},r={...i.pageSelectedShapeIdsById};delete o[e],delete r[e],this.updateSession({currentPageId:t,pageCameraById:o,pageSelectedShapeIdsById:r},n)}setCamera(e,t){this.camera.setCamera(e,t)}panCamera(e,t="system"){this.camera.panCamera(e,t)}zoomCameraAtScreenPoint(e,t,n="system"){this.camera.zoomCameraAtScreenPoint(e,t,n)}zoomCameraToScreenPoint(e,t,n="system"){this.camera.zoomCameraToScreenPoint(e,t,n)}zoomAtViewportCenter(e,t="system"){this.camera.zoomAtViewportCenter(e,t)}resetZoom(e="user"){this.camera.resetZoom(e)}setViewportScreenSize(e){this.camera.setViewportScreenSize(e)}getCurrentPageBounds(e=this.getCurrentPageId()){return this.selectionLayout.getCurrentPageBounds(e)}zoomToBounds(e,t){return this.selectionLayout.zoomToBounds(e,t)}zoomToFit(e){return this.selectionLayout.zoomToFit(e)}zoomToSelection(e){return this.selectionLayout.zoomToSelection(e)}createShapeId(e){const t=`shape:${e}`;return this.nextShapeNumber+=1,t}createShapeIndex(e){return String(e).padStart(6,"0")}createBindingId(e){const t=`binding:${e}`;return this.nextBindingNumber+=1,t}createAssetId(e){const t=`asset:${e}`;return this.nextAssetNumber+=1,t}syncShapeCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!p(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextShapeNumber=e+1}syncPageCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!u(t))continue;const n=t.id.split(":")[1]??"",i=Number("default"===n?1:n);Number.isFinite(i)&&(e=Math.max(e,i))}this.nextPageNumber=e+1}syncBindingCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!f(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextBindingNumber=e+1}syncAssetCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!m(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextAssetNumber=e+1}createPageId(e){const t=`page:${e}`;return this.nextPageNumber+=1,t}createPageIndex(e){return String(e).padStart(4,"0")}handleWheelEvent(e){if(e.ctrlKey){const t=this.getCurrentCamera(),n=e.delta.y,i=(Math.abs(n)>10?10*Math.sign(n):n)/100;return void this.zoomCameraToScreenPoint(e.screenPoint,t.z-1*i*t.z)}this.panCamera(e.delta)}},SS=class{getLocalBounds(e){const t=this.getBounds(e);return new Pm(t.x-e.x,t.y-e.y,t.w,t.h)}getRenderBounds(e){return this.getLocalBounds(e)}getPointHitTestBounds(e,t){return this.getBounds(e)}getExportBounds(e){return this.getRenderBounds(e)}getChildClipLocalBounds(e){return null}getChildExportClipLocalBounds(e){return this.getChildClipLocalBounds(e)}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=this.getSelectionResizeLocalBounds(e);if(0!==n.x||0!==n.y)throw new Error(`Shape util "${this.type}" must implement resizeSelectionBounds for non-origin local bounds`);const i=t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,o=this.validateProps({...e.props,w:t.selectionLocalBounds.w,h:t.selectionLocalBounds.h}),r=Di(o,"w",t.selectionLocalBounds.w),s=Di(o,"h",t.selectionLocalBounds.h),a=Mn(_t({requestedBounds:t.selectionLocalBounds,handleId:t.handleId,actualWidth:r,actualHeight:s,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,{rotation:t.selectionRotation,rotationCenter:t.selectionRotationCenter});return{id:e.id,x:a.x-r/2,y:a.y-s/2,rotation:i,scaleX:t.scaleX<0?-e.scaleX:e.scaleX,scaleY:t.scaleY<0?-e.scaleY:e.scaleY,props:o}}getSelectionResizeAspectRatioLock(e,t){return null}flipSelectionBounds(e,t){const n=this.getSelectionPagePoints(e);if(n){const i=n.map(e=>{const n=0===t.selectionRotation?e.clone():wm.RotWith(e,t.selectionRotationCenter,-t.selectionRotation),i=Fn({axis:t.axis,bounds:t.selectionBounds,point:n});return 0===t.selectionRotation?i:wm.RotWith(i,t.selectionRotationCenter,t.selectionRotation)});return this.updateSelectionPagePoints(e,{pagePoints:[i[0],i[1]]})}const i=this.getSelectionResizeLocalBounds(e),o=0===t.selectionRotation?t.selectionLocalBounds.center:wm.RotWith(t.selectionLocalBounds.center,t.selectionRotationCenter,t.selectionRotation);return{id:e.id,x:o.x-i.center.x,y:o.y-i.center.y,rotation:2*t.selectionRotation-e.rotation,scaleX:"horizontal"===t.axis?-e.scaleX:e.scaleX,scaleY:"vertical"===t.axis?-e.scaleY:e.scaleY}}updateSelectionPagePoints(e,t){throw new Error(`Shape util "${this.type}" must implement updateSelectionPagePoints before selection can transform point-defined geometry`)}getSelectionPagePoints(e){return null}contributesToSelectionFrame(e,t){return!0}canUseSelectionFrameHandles(e,t){return!0}getSelectionTargetId(e,t){return e.id}getTranslateTargetId(e,t){return e.id}isTransformDescendantContainer(e){return!1}shouldRotateDescendants(e){return this.isTransformDescendantContainer(e)}canUngroupChildren(e){return!1}canStartTranslateFromSelectionBounds(e,t){return!0}canSnap(e){return!0}getBoundsSnapGeometry(e){return{}}getHandleSnapGeometry(e){return{outline:Fi(this.getLocalBounds(e))}}getPositionedOutlineVertices(e){const t=this.getBounds(e);return[new wm(t.minX,t.minY),new wm(t.maxX,t.minY),new wm(t.maxX,t.maxY),new wm(t.minX,t.maxY)]}getSelectionHandleAnchors(e,t){return{terminalHandleAnchors:[],middleHandleAnchors:[]}}getSelectionOverlayInfo(e,t){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,bindingSegments:[]}}isWrappedByBrush(e,t){return 0===t.pageOutlineVertices.length?!!t.pageBounds&&t.brushBounds.containsBox(t.pageBounds):t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return!t.isWrapping||this.isWrappedByBrush(e,t)}getLocalToPageTransform(e){const t=this.getLocalBounds(e).center;return km.Translate(e.x+t.x,e.y+t.y).compose(km.Rotate(e.rotation)).compose(km.Scale(e.scaleX,e.scaleY)).compose(km.Translate(-t.x,-t.y))}canEdit(e){return!1}canReceiveChildren(e){return!1}canReceiveTerminalBinding(e,t){return!1}repairLoadedShape(e){return null}onEditEnd(e,t){}hitTest(e,t,n){return this.getBounds(e).containsPoint(t)}hitTestBindingTarget(e,t,n){return this.hitTest(e,t,n)}hitTestLineSegment(e,t){return((e,t,n)=>{if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=Fi(n);for(let o=0;o<i.length;o+=1){const n=i[o],r=i[(o+1)%i.length];if(n&&r&&null!==$i(e,t,n,r))return!0}return!1})(t.positionedStart,t.positionedEnd,this.getBounds(e).expand(t.margin))}resolveBindingPoint(e,t){const n=this.getBounds(e),i=((e,t,n)=>{if(n.length<2)return null;let i=Number.POSITIVE_INFINITY;const o=t.sub(e);for(let r=0;r<n.length;r+=1){const o=n[r],s=n[(r+1)%n.length]??n[0];if(!o||!s)continue;const a=$i(e,t,o,s);null===a||a<=1e-6||a>=i||(i=a)}return Number.isFinite(i)?e.add(o.mul(i)):null})(Ui(e,t.rawPagePoint,n),Ui(e,t.oppositePagePoint,n),this.getPositionedOutlineVertices(e));return i?((e,t,n)=>{const i=n.center,o=t.sub(i);return i.add(new wm(o.x*e.scaleX,o.y*e.scaleY).rot(e.rotation))})(e,i,n):t.rawPagePoint}},yS=class{},bS=class{editor;id;parent;children=new Map;currentChild=null;initial=null;constructor(e,t,n){this.editor=e,this.id=t,this.parent=n}addChild(e){this.children.set(e.id,e)}enter(e){if(this.onEnter(e),!this.initial)return;const t=this.children.get(this.initial);if(!t)throw new Error(`Missing child state "${this.initial}" on "${this.id}"`);this.currentChild=t,t.enter(e)}exit(e){this.currentChild&&(this.currentChild.exit(e),this.currentChild=null),this.onExit(e)}transition(e,t){if(!this.parent){const n=this.children.get(e);if(!n)throw new Error(`Missing root child state "${e}" on tool "${this.id}"`);if(this.currentChild===n)return;return this.currentChild?.exit(t),this.currentChild=n,void n.enter(t)}this.parent.transition(e,t)}isInInitialState(){return!this.currentChild||!!this.initial&&this.currentChild.id===this.initial&&this.currentChild.isInInitialState()}dispatch(e){if(this.currentChild)this.currentChild.dispatch(e);else switch(e.type){case"pointer":return void this.handlePointerEvent(e);case"click":return void this.handleClickEvent(e);case"keyboard":return void this.handleKeyboardEvent(e);case"wheel":return void this.onWheel(e);case"tick":return void this.onTick(e);case"cancel":return void this.onCancel(e)}}onEnter(e){}onExit(e){}onPointerDown(e){}onPointerMove(e){}onPointerUp(e){}onDoubleClick(e){}onCancel(e){}onKeyDown(e){}onKeyUp(e){}onWheel(e){}onTick(e){}handlePointerEvent(e){switch(e.name){case"pointer_down":return void this.onPointerDown(e);case"pointer_move":return void this.onPointerMove(e);case"pointer_up":return void this.onPointerUp(e);case"pointer_cancel":return void this.onCancel({type:"cancel",reason:"pointer_cancel"})}}handleClickEvent(e){"double_click"!==e.name||this.onDoubleClick(e)}handleKeyboardEvent(e){"key_down"!==e.name?this.onKeyUp(e):this.onKeyDown(e)}},xS=class extends bS{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new IS(e,this)),this.addChild(new vS(e,this))}},IS=class extends bS{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",{originScreenPoint:e.screenPoint.clone(),originCamera:this.editor.getCurrentCamera()})}},vS=class extends bS{info=null;constructor(e,t){super(e,"panning",t)}onEnter(e){this.info=e}onPointerMove(e){if(!this.info)return;const t=e.screenPoint.sub(this.info.originScreenPoint),n=this.info.originCamera.z;this.editor.setCamera({x:this.info.originCamera.x-t.x/n,y:this.info.originCamera.y-t.y/n},{source:"user"})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}onExit(){this.info=null}},wS=Math.PI/180*15,PS=Math.PI/2,kS=Math.PI/180*5,CS="select.translate",TS="select.resize",ES="select.rotate",BS=class extends bS{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},MS=class extends BS{onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&this.onDragThresholdExceeded(e)}},RS=class extends BS{onInfoEnter(){this.info&&this.editor.history.mark(this.getHistoryMark(this.info)),this.onDragStart()}onDragStart(){}onPointerMove(e){this.apply(e)}onTick(e){if(!this.info)return;const t=Hi(this.editor,e,this.tickMode);t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Ni(this.editor,e=>this.apply(e))}},AS=class extends BS{constructor(e,t){super(e,"brushing",t)}onInfoEnter(){if(!this.info)return;const e=this.editor.inputs.state.get();this.updateBrush(this.info.originPagePoint,this.info.additiveSelection,Xi(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,Yi(e),Xi(e))}onTick(e){if(!this.info)return;const t=Hi(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,Yi(t),Xi(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,Yi(e),Xi(e)),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}updateBrush(e,t,n){if(!this.info)return;const i=((e,t)=>{const n=Math.min(e.x,t.x),i=Math.min(e.y,t.y),o=Math.max(e.x,t.x),r=Math.max(e.y,t.y);return new Pm(n,i,o-n,r-i)})(this.info.originPagePoint,e),o=((e,t)=>{const n=[],i=new Set;for(const o of t){const t=e.getOutermostSelectableShapeId(o);i.has(t)||(i.add(t),n.push(t))}return n})(this.editor,this.editor.getShapeIdsInBounds(i).filter(e=>((e,t,n,i)=>{const o=e.getShape(n);return!(!o||!((e,t)=>{const n=e.getShape(t);return!!n&&!e.getShapeUtil(n).isTransformDescendantContainer(n)})(e,o.id))&&e.getShapeUtil(o).canSelectByBrush(o,{brushBounds:t,isWrapping:i,pageOutlineVertices:e.getShapePageOutlineVertices(o.id),pageBounds:e.getShapePageBounds(o.id)})})(this.editor,i,e,n))),r=t?((e,t)=>{const n=new Set(e);for(const i of t)n.has(i)?n.delete(i):n.add(i);return Array.from(n)})(this.info.previousSelection,o):o;this.editor.setBrushBox(i),this.editor.commands.setSelectedShapeIds(r,{source:"system"})}updateBrushFromInputs(){Ni(this.editor,e=>this.updateBrush(e.pagePoint,Yi(e),Xi(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},LS=class extends RS{tickMode="apply_after_scroll";constructor(e,t){super(e,"dragging_selection_handle_interaction",t)}getHistoryMark(e){return e.session.historyMark}onPointerUp(e){this.apply(e),this.complete()}onCancel(){const e=this.info?.previousSelection;(e=>{if(mm)return void e();const t={initialAtomValues:new Map};mm=t;try{e(),r(t.initialAtomValues.keys())}catch(n){for(const[e,i]of t.initialAtomValues)e.__unsafe__setWithoutNotify(i);throw n}finally{mm=null}})(()=>{e&&this.editor.commands.setSelectedShapeIds(e,{source:"system"}),this.info&&(this.editor.clearSelectionTransients(),this.editor.history.bailToMark(this.info.session.historyMark))}),this.transition("idle")}onInfoExit(){this.info?.session.shouldClearBindingPreviewOnExit&&this.editor.setBindingPreview(null),this.editor.setSnapIndicators(null)}apply({pagePoint:e,accelKey:t}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastAccelKey=t;const n=this.info.session.handleSnapMode??"none",i=this.info.snapSnapshot,o=!t&&"none"!==n&&null!==i,r=o&&i?this.editor.snaps.snapHandle({mode:n,pagePoint:e,snapshot:i,threshold:8/this.editor.getCurrentCamera().z}):null;o||this.editor.snaps.clearIndicators();const s=r?.snappedPagePoint??e,a=this.info.session.update({editor:this.editor,pagePoint:s,accelKey:t,source:"user"}),d="string"==typeof a?a:a.status,l="string"==typeof a?s:a.finalPagePoint;!r||!l||l.dist2(r.snappedPagePoint)<=1e-6||this.editor.snaps.clearIndicators(),"stop"===d&&this.transition("idle")}complete(){this.info&&(this.editor.setSnapIndicators(null),this.editor.history.squashToMark(this.info.session.historyMark)),this.transition("idle")}},FS=class extends bS{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.editor.getSelectedShapeIds(),n=this.editor.hitTestSelectionHandle(e.pagePoint);if("rotate"===n?.kind)return void this.transition("pointing_rotate_handle",{originPagePoint:e.pagePoint.clone(),previousSelection:t});if("resize"===n?.kind)return void this.transition("pointing_resize_handle",{handleId:n.id,originPagePoint:e.pagePoint.clone(),cursorHandleOffset:e.pagePoint.sub(n.point),previousSelection:t});if(n){const i=this.editor.getSelectedShapes()[0]??null;if(i){const o=this.editor.selectionHandleInteractions.createSession(this.editor,{handle:n,shape:i,originPagePoint:e.pagePoint.clone()});if(o){const i=o.handleSnapMode??"none";return void this.transition("pointing_selection_handle_interaction",{originPagePoint:e.pagePoint.clone(),previousSelection:t,session:o,snapSnapshot:"none"===i?null:this.editor.snaps.createHandleSnapshot({context:o.handleSnapContext??{shapeId:o.shapeId,handle:n},currentPagePoint:e.pagePoint,allowSelfSnap:o.allowSelfSnap??!1,excludedShapeIds:o.excludedSnapShapeIds})})}}}const i=this.editor.hitTestShape(e.pagePoint);if(i){const n=this.editor.getShapeUtil(i).getSelectionTargetId(i,{editor:this.editor}),o=this.editor.getShapeUtil(i).getTranslateTargetId(i,{editor:this.editor}),r=Yi(e),s=Oi(this.editor,n,t),a=r?null:((e,t,n)=>{const i=new Set(n);for(const o of Wi(e,t))if(i.has(o.ancestorId))return o.ancestorId;return null})(this.editor,n,t),d=r?null:a?s:null,l=Oi(this.editor,o,t);return void this.transition("pointing_shape",{shapeId:s,translateTargetId:null===d?l:a??l,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:r,wasSelected:t.includes(s),fromSelectionBounds:!1,quickClickSelectionTargetId:d})}if(!Yi(e)&&t.length>0){const n=this.editor.getSelectedShapes()[0];if(n&&this.editor.getShapeUtil(n).canStartTranslateFromSelectionBounds(n,{editor:this.editor})&&this.editor.isPointInSelectionBounds(e.pagePoint))return void this.transition("pointing_shape",{shapeId:n.id,translateTargetId:n.id,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:!1,wasSelected:!0,fromSelectionBounds:!0,quickClickSelectionTargetId:null})}this.transition("pointing_canvas",{originPagePoint:e.pagePoint.clone(),previousSelection:t,additiveSelection:Yi(e)})}},$S=class extends MS{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:Yi(e)})}onPointerUp(e){Yi(e)||this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.transition("idle")}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.transition("idle")}},US=class extends MS{constructor(e,t){super(e,"pointing_resize_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");const t=this.editor.getSelectionTransformTargetShapes(),n=(({shapes:e,selectionFrame:t,getShapeSelectionResizePageOutlineVertices:n,getShapeSelectionPagePoints:i})=>{const o={rotation:t.rotation,rotationCenter:t.rotationCenter},r=[],s=[];for(const a of e){const e=i(a);e?s.push({shape:a,startLocalPagePoint:Bn(e[0],o),endLocalPagePoint:Bn(e[1],o)}):r.push({shape:a,localBounds:Pm.FromPoints(n(a).map(e=>Bn(e,o))),rotation:a.rotation})}return{startBounds:t.bounds.clone(),rotation:t.rotation,rotationCenter:t.rotationCenter.clone(),aspectRatio:0===t.bounds.h?1:t.bounds.w/t.bounds.h,shapes:r,pointShapes:s}})({shapes:t,selectionFrame:e,getShapeSelectionResizePageOutlineVertices:e=>function(e,t){const n=e.getShapeUtil(t).getSelectionResizeLocalBounds(t),i=e.computeShapeLocalToPageTransform(t);return(e=>[new wm(e.minX,e.minY),new wm(e.maxX,e.minY),new wm(e.maxX,e.maxY),new wm(e.minX,e.maxY)])(n).map(e=>i.applyToPoint(e))}(this.editor,e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e)});var i,o;this.transition("resizing",{...this.info,startBounds:n.startBounds,rotation:n.rotation,rotationCenter:n.rotationCenter,aspectRatio:n.aspectRatio,snapSnapshot:this.editor.snaps.createResizeSnapshot({resizingShapeIds:t.map(e=>e.id),coordinateSpace:{rotation:n.rotation,rotationCenter:n.rotationCenter}}),shapes:n.shapes,pointShapes:n.pointShapes,updates:(i=n.shapes,o=n.pointShapes,[...i.map(e=>({id:e.shape.id,rotation:e.rotation})),...o.map(e=>({id:e.shape.id}))]),aspectRatioLockOverride:Qi(this.editor,t,this.info.handleId),lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},DS=class extends MS{constructor(e,t){super(e,"pointing_rotate_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");const t=(({shapes:e,selectionFrame:t,getShapeLocalBounds:n,getShapeSelectionPagePoints:i})=>{const o=[],r=[];for(const s of e){const e=i(s);e?r.push({shape:s,startPagePoint:e[0],endPagePoint:e[1]}):o.push({id:s.id,x:s.x,y:s.y,localBounds:n(s),rotation:s.rotation})}return{center:t.rotationCenter.clone(),initialSelectionRotation:t.rotation,shapes:o,pointShapes:r}})({shapes:this.editor.getSelectionRotationTargetShapes(),selectionFrame:e,getShapeLocalBounds:e=>this.editor.computeShapeLocalBounds(e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e)});var n,i;this.transition("rotating",{...this.info,center:t.center,startAngle:wm.Angle(t.center,this.info.originPagePoint),initialSelectionRotation:t.initialSelectionRotation,shapes:t.shapes,pointShapes:t.pointShapes,updates:(n=t.shapes,i=t.pointShapes,[...n.map(e=>({id:e.id,x:e.x,y:e.y,rotation:e.rotation})),...i.map(e=>({id:e.shape.id}))]),lastPointerX:NaN,lastPointerY:NaN,lastShiftKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},zS=class extends MS{constructor(e,t){super(e,"pointing_selection_handle_interaction",t)}onDragThresholdExceeded(){this.info&&this.transition("dragging_selection_handle_interaction",{...this.info,lastPagePointX:NaN,lastPagePointY:NaN,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},_S=class extends MS{constructor(e,t){super(e,"pointing_shape",t)}onInfoEnter(){this.info&&(this.info.quickClickSelectionTargetId||(this.info.additiveSelection?this.info.wasSelected||this.editor.commands.setSelectedShapeIds([...this.info.previousSelection,this.info.shapeId],{source:"system"}):this.info.wasSelected||this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"})))}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectedShapes(),t=this.info.wasSelected?e.map(e=>e.id):[this.info.translateTargetId];this.info.wasSelected||1!==t.length||t[0]===this.info.shapeId||this.editor.commands.setSelectedShapeIds(t,{source:"system"});const n=this.editor.getSelectionFrame(),i=((e,t)=>{const n=t.filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked&&!e.hasLockedDescendant(n.id)});return e.getShapeIdsIncludingDescendants(n).map(t=>e.getShape(t)).filter(e=>!!e&&!e.isLocked).map(e=>({id:e.id,x:e.x,y:e.y}))})(this.editor,t),o=i.map(e=>e.id),r=n?.hasCompatibleRotation?n.rotation:0,s=n?.rotationCenter.clone()??wm.Zero(),a=n?.hasCompatibleRotation?n.bounds.clone():this.editor.getSelectionPageBounds();var d;this.transition("translating",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,selectedShapeIds:t,startBounds:a,snapSnapshot:this.editor.snaps.createTranslateSnapshot({movingShapeIds:o,coordinateSpace:{rotation:r,rotationCenter:s}}),snapRotation:r,selectedShapes:i,updates:(d=i,d.map(e=>({id:e.id,x:e.x,y:e.y}))),lockedAxis:null,lastDeltaX:NaN,lastDeltaY:NaN})}onPointerUp(e){if(this.info?.quickClickSelectionTargetId){const t=((e,t)=>t.timestamp-e.originTimestamp<=250)(this.info,e);t&&this.editor.commands.setSelectedShapeIds([this.info.quickClickSelectionTargetId],{source:"system"}),t&&(e.clickCount??1)>=2||this.editor.resetPointerClickTracking()}else Yi(e)&&this.info?.wasSelected?this.editor.commands.setSelectedShapeIds(this.info.previousSelection.filter(e=>e!==this.info?.shapeId),{source:"system"}):this.info&&!this.info.additiveSelection&&this.info.wasSelected&&!this.info.fromSelectionBounds&&this.info.previousSelection.length>1&&this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"});this.transition("idle")}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.transition("idle")}},HS=class extends RS{tickMode="apply_after_scroll_or_without_screen_point";constructor(e,t){super(e,"resizing",t)}getHistoryMark(){return TS}onDragStart(){this.editor.setSnapIndicators(null)}onPointerUp(){this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:i}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&i===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=i;const o=ji(this.info.rotationCenter,this.info.rotation),r=Bn(e.sub(this.info.cursorHandleOffset),o),s=this.info.aspectRatioLockOverride??t,a=function({startBounds:e,handleId:t,pagePoint:n,isAspectRatioLocked:i,isResizingFromCenter:o,aspectRatio:r}){const s=o?(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.center,o=n.x-i.x,r=n.y-i.y,s=Math.max(Math.abs(o),.5),a=Math.max(Math.abs(r),.5),d=At(t)||Lt(t)?o*(At(t)?-2:2)/Math.max(1,e.w):1,l=Ft(t)||$t(t)?r*(Ft(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new Pm(e.minX,i.y-a,e.w,2*a),scaleX:d,scaleY:l};case"left":case"right":return{bounds:new Pm(i.x-s,e.minY,2*s,e.h),scaleX:d,scaleY:l};default:return{bounds:new Pm(i.x-s,i.y-a,2*s,2*a),scaleX:d,scaleY:l}}})({startBounds:e,handleId:t,pagePoint:n}):(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.minX,o=e.maxX,r=e.minY,s=e.maxY;let a=At(t)?i:o,d=At(t)?o:i,l=Ft(t)?r:s,c=Ft(t)?s:r;At(t)||Lt(t)?a=n.x:(a=o,d=i),Ft(t)||$t(t)?l=n.y:(l=s,c=r);const u=a-d,h=l-c,p=At(t)?d-a:u,g=Ft(t)?c-l:h,f=At(t)||Lt(t)?p/Math.max(1,e.w):1,m=Ft(t)||$t(t)?g/Math.max(1,e.h):1;return{bounds:new Pm(Math.min(a,d),Math.min(l,c),Math.max(1,Math.abs(u)),Math.max(1,Math.abs(h))),scaleX:f,scaleY:m}})({startBounds:e,handleId:t,pagePoint:n});return i?Ht({bounds:s.bounds,startBounds:e,handleId:t,aspectRatio:r,isResizingFromCenter:o,scaleX:s.scaleX,scaleY:s.scaleY}):s}({startBounds:this.info.startBounds,handleId:this.info.handleId,pagePoint:r,isAspectRatioLocked:s,isResizingFromCenter:n,aspectRatio:this.info.aspectRatio}),d=!i&&this.info.snapSnapshot.points.length>0,l=d?this.editor.snaps.snapResize({handleId:this.info.handleId,initialSelectionBounds:this.info.startBounds,resizedSelectionBounds:a.bounds,scaleX:a.scaleX,scaleY:a.scaleY,snapshot:this.info.snapSnapshot,threshold:8/this.editor.getCurrentCamera().z,isAspectRatioLocked:s,isResizingFromCenter:n}):a;d||this.editor.snaps.clearIndicators();for(let c=0;c<this.info.shapes.length;c+=1){const e=this.info.shapes[c],t=this.info.updates[c];e&&t&&qi(this.editor,e,this.info.startBounds,l.bounds,l.scaleX,l.scaleY,this.info.handleId,n,this.info.rotationCenter,this.info.rotation,t)}for(let c=0;c<this.info.pointShapes.length;c+=1){const e=this.info.pointShapes[c],t=this.info.updates[this.info.shapes.length+c];e&&t&&Gi(this.editor,e,this.info.startBounds,0,l.scaleX,l.scaleY,this.info.handleId,n,this.info.rotationCenter,this.info.rotation,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.setSnapIndicators(null),this.editor.history.squashToMark(TS),this.transition("idle")}cancel(){this.editor.setSnapIndicators(null),this.editor.history.bailToMark(TS),this.transition("idle")}},NS=class extends RS{tickMode="apply_after_scroll";constructor(e,t){super(e,"rotating",t)}getHistoryMark(){return ES}onPointerUp(){this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;if(e.x===this.info.lastPointerX&&e.y===this.info.lastPointerY&&t===this.info.lastShiftKey&&n===this.info.lastAccelKey)return;this.info.lastPointerX=e.x,this.info.lastPointerY=e.y,this.info.lastShiftKey=t,this.info.lastAccelKey=n;let i=Ki(wm.Angle(this.info.center,e)-this.info.startAngle);if(t)i=Vi(i,wS);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=Vi(e,PS),n=Ki(t-e);Math.abs(n)<=kS&&(i=Ki(t-this.info.initialSelectionRotation))}for(let o=0;o<this.info.shapes.length;o+=1){const e=this.info.shapes[o],t=this.info.updates[o];e&&t&&Ji(e,this.info.center,i,t)}for(let o=0;o<this.info.pointShapes.length;o+=1){const e=this.info.pointShapes[o],t=this.info.updates[this.info.shapes.length+o];e&&t&&eo(this.editor,e,this.info.center,i,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.history.squashToMark(ES),this.transition("idle")}cancel(){this.editor.history.bailToMark(ES),this.transition("idle")}},OS=class extends RS{tickMode="always_apply";constructor(e,t){super(e,"translating",t)}getHistoryMark(){return CS}onDragStart(){this.editor.setSelectionTranslationActive(!0),this.editor.setSnapIndicators(null)}onPointerUp(e){this.complete(e.pagePoint)}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.setSelectionTranslationActive(!1),this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;const i=e.x-this.info.originPagePoint.x,o=e.y-this.info.originPagePoint.y;t?this.info.lockedAxis||0===i&&0===o||(this.info.lockedAxis=Math.abs(i)>=Math.abs(o)?"x":"y"):this.info.lockedAxis=null;let r=i,s=o;"x"===this.info.lockedAxis?s=0:"y"===this.info.lockedAxis&&(r=0);const a=this.info.startBounds;if(!n&&a&&(this.info.snapSnapshot.points.length>0||this.info.snapSnapshot.nodes.length>0)&&this.editor.inputs.state.get().screenVelocity.len()<.5&&a){const e=this.info.snapRotation,t=8/this.editor.getCurrentCamera().z,n=0===e?new wm(r,s):new wm(r,s).rot(-e),{nudge:i}=this.editor.snaps.snapTranslate({lockedAxis:this.info.lockedAxis,initialSelectionBounds:a,dragDelta:n,snapshot:this.info.snapSnapshot,threshold:t}),o=0===e?i:i.rot(e);r+="y"===this.info.lockedAxis?0:o.x,s+="x"===this.info.lockedAxis?0:o.y}else this.editor.snaps.clearIndicators();if(r!==this.info.lastDeltaX||s!==this.info.lastDeltaY){this.info.lastDeltaX=r,this.info.lastDeltaY=s;for(let e=0;e<this.info.selectedShapes.length;e+=1){const t=this.info.selectedShapes[e],n=this.info.updates[e];t&&n&&(n.x=t.x+r,n.y=t.y+s)}this.editor.commands.updateShapes(this.info.updates)}io(this.editor,this.info.selectedShapeIds,e),((e,t,n)=>{const i=no(e,t,n);if(i===to(e,t))return void e.setDropTargetShapeId(null);const o=i?e.getShape(i):null;e.setDropTargetShapeId(o?.id??null)})(this.editor,this.info.selectedShapeIds,e)}complete(e){this.info&&io(this.editor,this.info.selectedShapeIds,e),this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.squashToMark(CS),this.transition("idle")}cancel(){this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.bailToMark(CS),this.transition("idle")}},WS=class extends bS{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new FS(e,this)),this.addChild(new $S(e,this)),this.addChild(new AS(e,this)),this.addChild(new _S(e,this)),this.addChild(new OS(e,this)),this.addChild(new US(e,this)),this.addChild(new HS(e,this)),this.addChild(new DS(e,this)),this.addChild(new NS(e,this)),this.addChild(new zS(e,this)),this.addChild(new LS(e,this))}},YS="editor.tool.set-active-tool",XS="editor.tool.toggle-locked",KS=class{actions=new Map;hostActionIds=new Set;duplicateActionIds=new Set;registerAction(e,t={}){!this.actions.has(e.id)||t.replace?this.actions.set(e.id,e):this.duplicateActionIds.add(e.id)}registerHostAction(e){this.hostActionIds.add(e.id),this.registerAction(e,{replace:!0})}registerEditorRuntimePlugins(e){for(const t of e)for(const e of t.canvasActions??[])this.registerAction(e)}getAction(e){return this.actions.get(e)??null}getHostActionIds(){return[...this.hostActionIds]}getDuplicateActionIds(){return[...this.duplicateActionIds]}},VS=class{registry=new Map;registeredPluginIds=new Set;registerShapeRenderer(e){this.registry.set(e.type,e)}getShapeRenderer(e){return this.registry.get(e)??null}hasShapeRenderer(e){return this.registry.has(e)}getRegisteredShapeTypes(){return[...this.registry.keys()]}registerCanvasRenderPlugins(e){const t=e.filter(e=>!this.registeredPluginIds.has(e.id));for(const n of t){for(const e of n.shapeRenderers??[])this.registerShapeRenderer(e);this.registeredPluginIds.add(n.id)}}},qS=ro(),jS=Of(qS),GS=class{selectionCustomHandleRenderers=new Map;canvasOverlays=new Map;registeredPluginIds=new Set;registerCanvasOverlay(e){this.canvasOverlays.set(e.id,e)}getCanvasOverlay(e){return this.canvasOverlays.get(e)??null}hasCanvasOverlay(e){return this.canvasOverlays.has(e)}getCanvasOverlays(e){return[...this.canvasOverlays.values()].filter(t=>!e||(e=>e.layer??"above-host")(t)===e).sort(so)}getRegisteredCanvasOverlayIds(){return[...this.canvasOverlays.keys()]}registerSelectionCustomHandleRenderer(e){this.selectionCustomHandleRenderers.set(e.type,e)}getSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.get(e)??null}hasSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.has(e)}getRegisteredSelectionCustomHandleTypes(){return[...this.selectionCustomHandleRenderers.keys()]}registerCanvasRenderPlugins(e){const t=e.filter(e=>!this.registeredPluginIds.has(e.id));for(const n of t){for(const e of n.canvasOverlays??[])this.registerCanvasOverlay(e);for(const e of n.selectionCustomHandleRenderers??[])this.registerSelectionCustomHandleRenderer(e);this.registeredPluginIds.add(n.id)}}},ZS=ao(),QS=Of(ZS),JS=class{guards=[];registeredGuardIds=new Set;register(e){this.registeredGuardIds.has(e.id)||(this.guards.push(e),this.registeredGuardIds.add(e.id))}registerCanvasRenderPlugins(e){for(const t of e)for(const e of t.domEventGuards??[])this.register(e)}getGuards(){return this.guards}handle(e){for(const t of this.guards)if("handled"===t.handle(e))return"handled";return"continue"}getCursor(e){for(const t of this.guards){const n=t.getCursor?.(e);if(void 0!==n)return n}}},ey=class{contributions=new Map;contributionsBySurface=new Map;contributionsBySurfaceAndPlacement=new Map;contributionIndexes=new Map;duplicateContributionIds=new Set;nextContributionIndex=0;registerContribution(e,t={}){const n=this.contributions.get(e.id);!n||t.replace?(n&&this.removeFromIndexes(n),this.contributions.set(e.id,e),this.contributionIndexes.has(e.id)||(this.contributionIndexes.set(e.id,this.nextContributionIndex),this.nextContributionIndex+=1),this.addToIndexes(e)):this.duplicateContributionIds.add(e.id)}registerEditorRuntimePlugins(e){for(const t of e)for(const e of t.toolbarContributions??[])this.registerContribution(e)}getDuplicateContributionIds(){return[...this.duplicateContributionIds]}getGroups(e,t,n={}){return(n.placement?this.contributionsBySurfaceAndPlacement.get(uo(e,n.placement))??[]:this.contributionsBySurface.get(e)??[]).filter(e=>e.when?.(t)??!0).flatMap(e=>[...e.getGroups(t)].sort((e,t)=>(e.order??0)-(t.order??0)))}addToIndexes(e){po(ho(this.contributionsBySurface,e.surface),e,this.contributionIndexes),po(ho(this.contributionsBySurfaceAndPlacement,uo(e.surface,e.placement??"context")),e,this.contributionIndexes)}removeFromIndexes(e){go(this.contributionsBySurface.get(e.surface),e.id),go(this.contributionsBySurfaceAndPlacement.get(uo(e.surface,e.placement??"context")),e.id)}},ty=class{contributions=new Map;contributionsByTarget=new Map;contributionIndexes=new Map;duplicateContributionIds=new Set;nextContributionIndex=0;registerContribution(e,t={}){const n=this.contributions.get(e.id);!n||t.replace?(n&&this.removeFromIndex(n),this.contributions.set(e.id,e),this.contributionIndexes.has(e.id)||(this.contributionIndexes.set(e.id,this.nextContributionIndex),this.nextContributionIndex+=1),this.addToIndex(e)):this.duplicateContributionIds.add(e.id)}registerEditorRuntimePlugins(e){for(const t of e)for(const e of t.contextMenuContributions??[])this.registerContribution(e)}getDuplicateContributionIds(){return[...this.duplicateContributionIds]}getSections(e,t){return(e=>{const t=[],n=new Map;for(const i of e){const e=n.get(i.id);if(void 0===e){n.set(i.id,t.length),t.push({...i,items:[...i.items]});continue}const o=t[e];t[e]={...o,title:o.title??i.title,items:[...o.items,...i.items]}}return t})((({anyContributions:e,contributionIndexes:t,target:n,targetContributions:i})=>"any"===n||0===i.length?e:0===e.length?i:[...i,...e].sort((e,n)=>mo(e,n,t)))({anyContributions:this.contributionsByTarget.get("any")??[],contributionIndexes:this.contributionIndexes,target:e,targetContributions:this.contributionsByTarget.get(e)??[]}).filter(e=>e.when?.(t)??!0).flatMap(e=>[...e.getSections(t)].sort((e,t)=>(e.order??0)-(t.order??0))))}addToIndex(e){((e,t,n)=>{e.push(t),e.sort((e,t)=>mo(e,t,n))})(((e,t)=>{const n=e.get(t);if(n)return n;const i=[];return e.set(t,i),i})(this.contributionsByTarget,e.target),e,this.contributionIndexes)}removeFromIndex(e){((e,t)=>{if(!e)return;const n=e.findIndex(e=>e.id===t);-1!==n&&e.splice(n,1)})(this.contributionsByTarget.get(e.target),e.id)}},ny="var(--land-selection, #2563eb)",iy=class e{config;name;options;priority;constructor(e,t){this.config=e,this.name=e.name,this.options=Object.freeze(t),this.priority=e.priority??100}configure(t){return new e(this.config,xo(this.options,t??{}))}createFeature(){return this.config.createFeature?.(this.options)??null}getExtensions(){return this.config.addExtensions?.(this.options)??[]}},oy=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),ry=e=>{const t=(e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()))(e);return t.charAt(0).toUpperCase()+t.slice(1)},sy={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},ay=e=>{for(const t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0;return!1},dy=Of({}),ly=Yf(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:i,className:o="",children:r,iconNode:s,...a},d)=>{const{size:l=24,strokeWidth:c=2,absoluteStrokeWidth:u=!1,color:h="currentColor",className:p=""}=Vf(dy)??{},g=i??u?24*Number(n??c)/Number(t??l):n??c;return Wf("svg",{ref:d,...sy,width:t??l??sy.width,height:t??l??sy.height,stroke:e??h,strokeWidth:g,className:oy("lucide",p,o),...!r&&!ay(a)&&{"aria-hidden":"true"},...a},[...s.map(([e,t])=>Wf(e,t)),...Array.isArray(r)?r:[r]])}),cy=(e,t)=>{const n=Yf(({className:n,...i},o)=>{return Wf(ly,{ref:o,iconNode:t,className:oy(`lucide-${r=ry(e),r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,`lucide-${e}`,n),...i});var r});return n.displayName=ry(e),n},uy=cy("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),hy=cy("external-link",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]),py=cy("link-2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]),gy=cy("pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]]),fy=cy("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),my={display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto",width:"var(--toolbar-control-size)",height:"var(--toolbar-control-size)",border:"var(--chrome-control-border-width) solid transparent",borderRadius:"var(--chrome-control-radius)",background:"transparent",color:"var(--muted-foreground)",cursor:"pointer",padding:0},Sy={minWidth:0,maxWidth:260,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:0,background:"transparent",color:"var(--chrome-foreground)",cursor:"pointer",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:"var(--toolbar-title-font-size)",lineHeight:"var(--toolbar-title-line-height)",padding:"0 var(--toolbar-title-padding-inline)"},yy="default",by={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}},xy=new WeakMap,Iy=Of(null),vy=Xf(()=>ir(nr().retainedShapeIdsSignal).map(e=>nm(Py,{shapeId:e},e))),wy=Xf(()=>{const e=nr(),t=ir(e.currentPageShapeIdsSignal),n=ir(e.retainedShapeIdsSignal),i=ir(e.renderVisibleShapeIdsSignal),o=ir(e.shapeRenderOrderByIdSignal),r=new Set(i),s=n.map(e=>o.get(e)??-1),a=n.filter(e=>r.has(e)).map(e=>o.get(e)??-1),d=n.filter(e=>!r.has(e)),l={pageShapeCount:t.length,mountedCount:n.length,visibleCount:i.length,hiddenRetainedCount:d.length,minRenderOrder:s.length>0?Math.min(...s):null,maxRenderOrder:s.length>0?Math.max(...s):null,mountedRenderOrderSeq:s.join(","),visibleRenderOrderSeq:a.join(","),firstMountedShapeId:n[0]??null,lastMountedShapeId:n[n.length-1]??null,hiddenRetainedShapeIds:d};
|
|
70
|
-
return
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
return
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
return
|
|
78
|
-
return
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
return im("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${s} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[nm("path",{"data-ui":"snap-indicator-line",d:`M ${o.x} ${o.y} L ${r.x} ${r.y}`,fill:"none",stroke:Ny,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,o)=>nm("path",{"data-ui":"snap-indicator-cross",d:`M ${t.x-n} ${t.y-n} L ${t.x+n} ${t.y+n} M ${t.x-n} ${t.y+n} L ${t.x+n} ${t.y-n}`,fill:"none",stroke:Ny,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${o}`))]})}),Xy=Xf(({indicator:e,zoom:t})=>{if(0===e.gaps.length)return null;const n="horizontal"===e.direction;let i=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY];for(const c of e.gaps){const e=yr(i,[n?c.startEdge[0].y:c.startEdge[0].x,n?c.startEdge[1].y:c.startEdge[1].x]);e&&(i=e);const t=yr(i,[n?c.endEdge[0].y:c.endEdge[0].x,n?c.endEdge[1].y:c.endEdge[1].x]);t&&(i=t)}if(!Number.isFinite(i[0])||!Number.isFinite(i[1]))return null;const o=(i[0]+i[1])/2,r=3.5/t,s=2*r,a=[];for(const{startEdge:c,endEdge:u}of e.gaps)if(n){a.push(`M ${c[0].x} ${o-s} L ${c[1].x} ${o+s}`,`M ${u[0].x} ${o-s} L ${u[1].x} ${o+s}`,`M ${c[0].x} ${o} L ${u[0].x} ${o}`);const e=(c[0].x+u[0].x)/2;a.push(`M ${e} ${o-r} L ${e} ${o+r}`)}else{a.push(`M ${o-s} ${c[0].y} L ${o+s} ${c[1].y}`,`M ${o-s} ${u[0].y} L ${o+s} ${u[1].y}`,`M ${o} ${c[0].y} L ${o} ${u[0].y}`);const e=(c[0].y+u[0].y)/2;a.push(`M ${o-r} ${e} L ${o+r} ${e}`)}const d=180*e.rotation/Math.PI,l=0===e.rotation?void 0:`rotate(${d} ${e.rotationCenter.x} ${e.rotationCenter.y})`;
|
|
88
|
-
return
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
nm(Oy,{}),
|
|
92
|
-
|
|
93
|
-
nm(Ty,{}),
|
|
94
|
-
|
|
95
|
-
nm(Hy,{}),
|
|
96
|
-
nm(qy,{layer:"above-host"})]})),qy=Xf(({layer:e})=>{const t=lo().getCanvasOverlays(e);return 0===t.length?null:nm(tm,{children:t.map(({id:e,component:t})=>nm(t,{},e))})}),jy="canvas-surface",Gy=`[data-ui="${jy}"]`,Zy=[{min:-1,mid:.15,step:64},{min:.05,mid:.375,step:16},{min:.15,mid:1,step:4},{min:.7,mid:2.5,step:1}],Qy=14,Jy=16,eb=20,tb=28,nb=16,ib={[Qy]:20,[Jy]:24,[eb]:28,[tb]:36},ob=class{ownerDocument;element;constructor(e){this.ownerDocument=e,this.element=e.createElement("div"),this.element.setAttribute("aria-hidden","true"),this.element.style.position="absolute",this.element.style.left="-10000px",this.element.style.top="0",this.element.style.visibility="hidden",this.element.style.pointerEvents="none",e.body.appendChild(this.element)}measureHtml(e,t){const n=this.prepareElement(t);return n.innerHTML=e,this.measurePreparedElement(n)}measureElement(e,t,n){const i=this.prepareElement(t);return i.replaceChildren(...Array.from(e.childNodes).map(e=>e.cloneNode(!0))),Gr(i,"whiteSpace",n?.whiteSpace),Gr(i,"overflowWrap",n?.overflowWrap),Gr(i,"lineHeight",n?.lineHeight),Gr(i,"letterSpacing",n?.letterSpacing),Gr(i,"textAlign",n?.textAlign),this.measurePreparedElement(i)}prepareElement(e){const t=this.element;return t.removeAttribute("contenteditable"),t.className="",t.textContent="",e?.shape&&e.fontCatalog&&((e,t,n)=>{e.className="land-text-editor__content",e.dir="auto",e.style.color=k(t.props.color),e.style.fontFamily=Nr(t.props.font,n),e.style.fontSize=`${Or(t.props.size)}px`,e.style.lineHeight=`${Wr(t.props.size)}px`,e.style.textAlign=Xr(t.props.textAlign)})(t,e.shape,e.fontCatalog),t.style.position="absolute",t.style.left="-10000px",t.style.top="0",t.style.visibility="hidden",t.style.pointerEvents="none",t.style.width="number"==typeof e?.width?`${e.width}px`:"max-content",t.style.minWidth="0",t.style.height="auto",t.style.minHeight="0",t.style.maxHeight="none",t.style.maxWidth="number"==typeof e?.width?`${e.width}px`:"none",t}measurePreparedElement(e){return e.querySelectorAll("p").forEach(e=>{e instanceof HTMLElement&&(e.style.margin="0")}),[e,...Array.from(e.querySelectorAll("*")).filter(e=>e instanceof HTMLElement)].reduce((e,t)=>{const n=t.getBoundingClientRect();return{w:Math.max(e.w,n.width,t.scrollWidth,t.offsetWidth),h:Math.max(e.h,n.height,t.scrollHeight,t.offsetHeight)}},{w:0,h:0})}},rb=new WeakMap,sb="land.rich-text-bubble-menu",ab="updatePosition",db=[{id:"bold",label:"Bold",shortcut:"B",dataUi:"text-bold-button",content:"B"},{id:"italic",label:"Italic",shortcut:"I",dataUi:"text-italic-button",content:"I"},{id:"strike",label:"Strikethrough",shortcut:"S",dataUi:"text-strike-button",content:"S"}],lb={padding:"0 var(--toolbar-title-padding-inline)",color:"var(--chrome-foreground)",fontFamily:'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:"var(--toolbar-title-font-size)",fontWeight:500,lineHeight:"var(--toolbar-title-line-height)",whiteSpace:"nowrap"},cb={width:"var(--toolbar-separator-width)",height:"var(--toolbar-separator-height)",background:"var(--border)",margin:"0 var(--toolbar-separator-margin-inline)"},ub={display:"inline-flex",alignItems:"center",justifyContent:"center",width:"var(--toolbar-control-size)",height:"var(--toolbar-control-size)",border:"var(--chrome-control-border-width) solid transparent",borderRadius:"var(--chrome-control-radius)",padding:0,pointerEvents:"auto"},hb={...ub,background:"transparent",color:"var(--muted-foreground)",cursor:"pointer"},pb=cm.extend({inclusive:!1,renderHTML({HTMLAttributes:e}){const{href:t,target:n,rel:i,...o}=e;return["span",am(o,{"data-rich-text-link-href":t,style:"text-decoration-line: underline;"}),0]}}),gb=[hm.configure({bold:!1,italic:!1,strike:!1}),dm.extend({keepOnSplit:!0}),lm.extend({keepOnSplit:!0}),um.extend({keepOnSplit:!0}),pb.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})],fb=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),mb={id:"land.text.dom-events",handle({event:e,name:t}){if(!fb.has(t))return"continue";const n=e.target;return n instanceof HTMLElement&&n.closest('[data-ui="text-editing-box"]')?"handled":"continue"},getCursor:({element:e})=>e?.closest('[data-ui="text-editing-box"]')?"text":void 0},Sb="text.create",yb=class extends bS{constructor(e){super(e,"text"),this.initial="idle",this.addChild(new bb(e,this)),this.addChild(new xb(e,this))}},bb=class extends bS{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("pointing",{originPagePoint:e.pagePoint.clone(),shapeId:null,didCreateShape:!1})}},xb=class extends bS{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e,this.editor.history.mark(Sb)}onPointerMove(e){this.updateFixedWidthShape(e.pagePoint)}onPointerUp(e){if(!this.info)return void this.transition("idle");const t=null!==this.info.shapeId?this.editor.getShape(this.info.shapeId):this.createTextShape(e.pagePoint);if(!Ar(t))return this.editor.history.bailToMark(Sb),void this.transition("idle");this.info.didCreateShape=!0,G(this.editor,t.id,{source:"user"}),this.editor.isToolLocked()||(this.transition("idle"),this.editor.commands.setActiveTool("select",{source:"system"})),this.editor.startEditingShape({shapeId:t.id,entryMode:"focusEnd",markId:Sb,reuseExistingMark:!0,preserveInteraction:!0},"user"),this.editor.isToolLocked()&&this.transition("idle")}onCancel(){this.info?.didCreateShape||this.editor.history.bailToMark(Sb),this.transition("idle")}onExit(){this.info=null}updateFixedWidthShape(e){if(!this.info)return;const t=((e,t,n)=>{const i=Math.abs(t.x-e.x);return e.dist(t)<4||i<8?null:{x:Math.min(e.x,t.x),y:e.y-n.h/2,props:{...Is(n),w:Math.max(16,i),autoSize:!1}}})(this.info.originPagePoint,e,this.getDefaultTextProps());if(t){if(!this.info.shapeId){const e=this.createTextShapeAt(t);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:t.x,y:t.y,props:{w:t.props.w,h:t.props.h,autoSize:!1}}],{source:"user"})}}createTextShape(e){return this.createTextShapeAt(((e,t)=>({x:e.x,y:e.y-t.h/2,props:Is(t)}))(e,this.getDefaultTextProps()))}createTextShapeAt({x:e,y:t,props:n}){const i=$r(this.editor,{x:e,y:t,props:n},"user");return this.editor.commands.setSelectedShapeIds([i.id],{source:"system"}),i}getDefaultTextProps(){return Fr(this.editor)}},Ib="arrow-label",vb="geo-label",wb={[Ib]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!0,canUseSelectionFrameHandles:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[vb]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!1,canUseSelectionFrameHandles:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}},Pb=["start","middle","end"],kb=class extends SS{type="text";getDefaultProps(){return{richText:Mo(""),w:16,h:Yr(nb),autoSize:!0,scale:1,font:yy,size:nb,color:y("text-slate"),textAlign:"start"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{richText:Ao(t.richText),w:Math.max(1,Cs(t.w,n.w)),h:Math.max(1,Cs(t.h,n.h)),autoSize:"boolean"==typeof t.autoSize?t.autoSize:n.autoSize,scale:Math.max(.01,Cs(t.scale,n.scale)),font:Zo(t.font)?t.font:n.font,size:Hr(t.size,n.size),color:P(t.color,n.color),textAlign:(i=t.textAlign,"string"==typeof i&&Pb.includes(i)?t.textAlign:n.textAlign)};var i}getBounds(e){return(e=>new Pm(e.x,e.y,Es(e),Bs(e)))(e)}getLocalBounds(e){return Ms(e)}getRenderBounds(e){return Ms(e)}getExportBounds(e){return Ms(e)}canReceiveTerminalBinding(e){return!0}canEdit(e){return!0}contributesToSelectionFrame(e,t){return n=t.editor,i=e.id,Ps(n,i)?.behavior.contributesToSelectionFrame??null??!0;var n,i}canUseSelectionFrameHandles(e,t){return n=t.editor,i=e.id,Ps(n,i)?.behavior.canUseSelectionFrameHandles??null??!0;var n,i}getSelectionTargetId(e,t){return((e,t)=>{const n=Ps(e,t);return n?"owner"===n.behavior.selectionTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}getTranslateTargetId(e,t){return((e,t)=>{const n=Ps(e,t);return n?"owner"===n.behavior.translateTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}resizeSelectionBounds(e,t){const n={};Rs(t.handleId)?(n.w=Math.max(16,t.selectionLocalBounds.w/Ts(e)),n.autoSize=!1):n.scale=Math.max(.01,e.props.scale*((e,t)=>{const n=t.selectionLocalBounds.w/Math.max(1,Es(e)),i=t.selectionLocalBounds.h/Math.max(1,Bs(e));switch(t.handleId){case"left":case"right":return n;case"top":case"bottom":return i;default:return Math.max(n,i)}})(e,t));const i=n.scale??Ts(e),o=(n.w??e.props.w)*i,r=e.props.h*i,s=((e,t)=>0===t.selectionRotation?e.clone():wm.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(_t({handleId:t.handleId,requestedBounds:t.selectionLocalBounds,actualWidth:o,actualHeight:r,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,t);return{id:e.id,x:s.x-o/2,y:s.y-r/2,rotation:t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,scaleX:t.scaleX<0?-e.scaleX:e.scaleX,scaleY:t.scaleY<0?-e.scaleY:e.scaleY,props:n}}getSelectionResizeAspectRatioLock(e,t){return t.isOnlySelected?!Rs(t.handleId):null}onEditEnd(e){if(!(Ro(e.props.richText).trim().length>0))return{deleteShapeIds:[e.id]}}},Cb=class{fontCatalog;type="text";constructor(e){this.fontCatalog=e}toSvg(e,t){return 0===Ro(e.props.richText).trim().length?null:{tag:"foreignObject",attrs:{x:0,y:0,width:e.props.w*e.props.scale,height:e.props.h*e.props.scale},children:[{tag:"div",attrs:{xmlns:"http://www.w3.org/1999/xhtml",dir:"auto",style:Fs(e,t,this.fontCatalog)},children:As(e.props.richText)}]}}},Tb=".label",Eb=class extends yS{type=Ib;getDefaultProps(){return{labelPosition:.5}}validateProps(e){const t=this.getDefaultProps();return{labelPosition:Us((e&&"object"==typeof e?e:{}).labelPosition,t.labelPosition)}}canBind(e,t,n){return Ar(n.fromShape)&&$s(n.toShape)}getExclusiveBindingKey(e){return e.toId}onBindingCreate(e,t){return this.syncLabelPosition(e,t)}onBindingUpdate(e,t,n){return this.syncLabelPosition(e,n)}onBindingLoad(e,t){return this.syncLabelPosition(e,t)}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return this.syncLabelPosition(e,t)}onBeforeDeleteShape(e,t,n){return"from"===n.role?{deleteBindingIds:[t.id]}:{deleteShapeIds:[t.fromId],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){return{deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}getSelectionCompanionFrameGeometries(e,t,n){if(t.toId!==n.selectedShape.id)return[];if(!0!==((e,t)=>Ps(e,t)?.behavior.showsCompanionFrameWhenOwnerSelected??null)(e,t.fromId))return[];const i=e.getShape(t.fromId),o=e.getShape(t.toId);if(!Ar(i)||!$s(o))return[];const r=e.computeShapeGeometry(i);return[{bounds:r.bounds,rotation:i.rotation,rotationCenter:r.center}]}syncLabelPosition(e,t){if(n=t,"binding"!==n?.typeName||"arrow-label"!==n.type)return;var n;const i=e.getShape(t.fromId),o=e.getShape(t.toId);if(!Ar(i)||!$s(o))return{deleteBindingIds:[t.id]};const r=((e,t,n)=>{const i=Ds(e,t,n),o=n.parentId,r=`${n.index}${Tb}`,s=!1,a="middle";return t.x===i.x&&t.y===i.y&&t.rotation===i.rotation&&t.parentId===o&&t.index===r&&t.props.w===i.props.w&&t.props.autoSize===s&&t.props.textAlign===a?null:{id:t.id,x:i.x,y:i.y,rotation:i.rotation,parentId:o,index:r,props:{w:i.props.w,autoSize:s,textAlign:a}}})(e,i,o);return r?{shapes:[{...i,...r,props:{...i.props,...r.props}}]}:void 0}},Bb=".label",Mb=class extends yS{type=vb;getDefaultProps(){return{normalizedAnchor:{x:.5,y:.5},ownerBaseHeight:0}}validateProps(e){const t=this.getDefaultProps(),n=e&&"object"==typeof e?e:{},i=n.normalizedAnchor&&"object"==typeof n.normalizedAnchor?n.normalizedAnchor:t.normalizedAnchor;return{normalizedAnchor:{x:Ns(i.x,t.normalizedAnchor.x),y:Ns(i.y,t.normalizedAnchor.y)},ownerBaseHeight:Os(n.ownerBaseHeight,t.ownerBaseHeight)}}canBind(e,t,n){return Ar(n.fromShape)&&Hs(n.toShape)}getExclusiveBindingKey(e){return e.toId}onBindingCreate(e,t){return this.syncLabelPosition(e,t)}onBindingUpdate(e,t,n){return this.syncLabelPosition(e,n,t.toId===n.toId?void 0:{role:"to"})}onBindingLoad(e,t){return this.syncLabelPosition(e,t)}getGeometryDependentShapeIds(e,t,n){return"from"===n.role?[t.toId]:[t.fromId]}onAfterShapeChange(e,t,n){return this.syncLabelPosition(e,t,n)}onBeforeDeleteShape(e,t,n){if("from"===n.role){const n=e.getShape(t.toId),i=n?Ys(n,t):null;return{shapes:i?[i]:void 0,deleteBindingIds:[t.id]}}return{deleteShapeIds:[t.fromId],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.toId),i=n?Ys(n,t):null;return{shapes:i?[i]:void 0,deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}syncLabelPosition(e,t,n){if(i=t,"binding"!==i?.typeName||"geo-label"!==i.type)return;var i;const o=e.getShape(t.fromId),r=e.getShape(t.toId);if(!Ar(o)||!Hs(r))return{deleteBindingIds:[t.id]};const s=((e,t,n)=>{const i=Ws(t,"h")??1;return"to"===n?.role?i:e.props.ownerBaseHeight>0?e.props.ownerBaseHeight:i})(t,r,n),a=t.props.ownerBaseHeight===s?null:{...t,props:{...t.props,ownerBaseHeight:s}},d=function(e,t,n){const i=Ws(e,"h");if(!i)return null;const o=Math.max(n,(e=>Math.max(1,e.props.h*e.props.scale+32))(t));return i===o?null:{...e,props:{...e.props,h:o}}}(r,o,s),l=((e,t,n)=>{const i=Xs(e,t,n),o=n.parentId,r=`${n.index}${Bb}`,s=!1,a="middle";return t.x===i.x&&t.y===i.y&&t.rotation===i.rotation&&t.parentId===o&&t.index===r&&t.props.w===i.props.w&&t.props.autoSize===s&&t.props.textAlign===a?null:{id:t.id,x:i.x,y:i.y,rotation:i.rotation,parentId:o,index:r,props:{w:i.props.w,autoSize:s,textAlign:a}}})(e,o,d??r),c=[];return d&&c.push(d),l&&c.push({...o,...l,props:{...o.props,...l.props}}),c.length>0||a?{shapes:c.length>0?c:void 0,bindings:a?[a]:void 0}:void 0}},Rb="text.edit",Ab="arrow-label.edit",Lb="arrow-label.create",Fb="geo-label.edit",$b="geo-label.create",Ub=[{value:y("text-slate"),label:"Slate",color:"var(--land-shape-text-slate)"},{value:y("text-blue"),label:"Blue",color:"var(--land-shape-text-blue)"},{value:y("text-green"),label:"Green",color:"var(--land-shape-text-green)"},{value:y("text-red"),label:"Red",color:"var(--land-shape-text-red)"}],Db=[{id:"s",value:14,label:"S"},{id:"m",value:16,label:"M"},{id:"l",value:20,label:"L"},{id:"xl",value:28,label:"XL"}],zb=[{value:"start",label:"Align left",icon:"align-left"},{value:"middle",label:"Align center",icon:"align-center"},{value:"end",label:"Align right",icon:"align-right"}],_b=bo({name:"text",addOptions:qo,createFeature:(e=qo())=>{const t=Go(e);return{id:"land.text.bundle",editorRuntimePlugins:[qs({fontCatalog:t})],canvasRenderPlugins:[ms({fontCatalog:t})],shapeTypes:["text"]}}}),Hb=[],Nb=2*Math.PI,Ob=class extends yS{type="arrow";getDefaultProps(){return{terminal:"start",normalizedAnchor:{x:.5,y:.5}}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps(),i=t.normalizedAnchor&&"object"==typeof t.normalizedAnchor?t.normalizedAnchor:n.normalizedAnchor;return{terminal:"end"===t.terminal?"end":n.terminal,normalizedAnchor:{x:Math.min(1,Math.max(0,Wa(i.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,Wa(i.y,n.normalizedAnchor.y)))}}}canBind(e,t,n){return Ma(n.fromShape)&&Na(e,n.toShape)}getExclusiveBindingKey(e){return`${e.fromId}:${e.props.terminal}`}onBindingCreate(e,t){return Ya(this.syncArrowTerminal(e,t))}onBindingUpdate(e,t,n){return Ya(this.syncArrowTerminal(e,n))}onBindingLoad(e,t){return Ya(this.syncArrowTerminal(e,t))}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return Ya(this.syncArrowTerminal(e,t))}onBeforeDeleteShape(e,t,n){if("from"===n.role)return{deleteBindingIds:[t.id]};const i=e.getShape(t.fromId);if(!Ma(i))return{deleteBindingIds:[t.id]};const o=this.resolveTerminalPagePoint(e,t);return{shapes:[o?ga(i,t.props.terminal,o):i],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.fromId);if(!Ma(n))return{deleteBindingIds:[t.id]};const i=this.resolveTerminalPagePoint(e,t);return{shapes:[i?ga(n,t.props.terminal,i):n],deleteBindingIds:[t.id]}}syncArrowTerminal(e,t){if(!Ra(t))return null;const n=e.getShape(t.fromId);if(!Ma(n))return null;const i=this.resolveTerminalPagePoint(e,t);return i?ua(n,t.props.terminal).dist(i)<1e-6?null:ga(n,t.props.terminal,i):null}resolveTerminalPagePoint(e,t){if(!Ra(t))return null;const n=e.getShape(t.fromId),i=e.getShape(t.toId);if(!Ma(n)||!i||Ma(i))return null;const o=ua(n,ha(t.props.terminal)),r=ca(e,i,t.props.normalizedAnchor,o);return za(e,{arrow:n,terminal:t.props.terminal,target:i,anchorPagePoint:la(e,i,t.props.normalizedAnchor),fallbackBoundaryPagePoint:r}).boundaryPagePoint}},Wb=class extends SS{type="arrow";getDefaultProps(){return{w:160,h:48,start:{x:8,y:24},end:{x:152,y:24},bend:0,stroke:y("stroke-slate"),strokeWidth:2,headStart:"none",headEnd:"arrow"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,Ka(t.w,n.w)),h:Math.max(1,Ka(t.h,n.h)),start:Xa(t.start,n.start),end:Xa(t.end,n.end),bend:Ka(t.bend,n.bend),stroke:P(t.stroke,n.stroke),strokeWidth:Math.max(1,Ka(t.strokeWidth,n.strokeWidth)),headStart:"arrow"===t.headStart?"arrow":"none",headEnd:"none"===t.headEnd?"none":"arrow"}}getBounds(e){const t=fa(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}getPointHitTestBounds(e,t){const n=t?.editor?La(t.editor,e).info:fa(e),i=Math.max(8,e.props.strokeWidth+4);return n.bounds.expand(i)}getLocalBounds(e){return new Pm(0,0,e.props.w,e.props.h)}getExportBounds(e){const t=(e=>ba(new wm(e.props.start.x,e.props.start.y),new wm(e.props.end.x,e.props.end.y),e.props.bend))(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}repairLoadedShape(e){return 0===e.rotation&&1===e.scaleX&&1===e.scaleY?null:pa(e,ua(e,"start"),ua(e,"end"))}updateSelectionPagePoints(e,t){const n=pa(e,t.pagePoints[0],t.pagePoints[1]);return{id:e.id,x:n.x,y:n.y,rotation:n.rotation,scaleX:n.scaleX,scaleY:n.scaleY,props:{w:n.props.w,h:n.props.h,start:n.props.start,end:n.props.end}}}isWrappedByBrush(e,t){return t.brushBounds.containsPoint(ua(e,"start"))&&t.brushBounds.containsPoint(ua(e,"end"))}getSelectionPagePoints(e){return[ua(e,"start"),ua(e,"end")]}contributesToSelectionFrame(e,t){return t.editor.getSelectedShapeIds().length>1}canUseSelectionFrameHandles(e,t){return t.editor.getSelectedShapeIds().length>1}canStartTranslateFromSelectionBounds(e,t){return t.editor.getSelectedShapeIds().length>1}getSelectionHandleAnchors(e,t){if(!t.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=La(t.editor,e).info;return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.start.handle},{kind:"binding_terminal",terminal:"end",point:n.end.handle}],middleHandleAnchors:n.middle?[{kind:"binding_middle",point:n.middle}]:[]}}getSelectionOverlayInfo(e,t){const n=La(t.editor,e),i=n.info;return{usesSelectionPathOverlay:!0,startPagePoint:i.start.point,endPagePoint:i.end.point,middlePagePoint:i.middle,path:i.path,bindingSegments:n.bindingSegments}}hitTest(e,t,n){return((e,t)=>{let n=1/0;for(let i=0;i<e.points.length-1;i++)n=Math.min(n,Ea(t,e.points[i],e.points[i+1]));return Number.isFinite(n)?n:t.dist(e.start.point)})(n?.editor?La(n.editor,e).info:fa(e),n?.pagePoint??t)<=Math.max(8,e.props.strokeWidth+4)}hitTestLineSegment(e,t){const n=t.editor?La(t.editor,e).info:fa(e),i=Math.max(8,e.props.strokeWidth+4,t.margin),o=t.editor?t.pageStart:t.positionedStart,r=t.editor?t.pageEnd:t.positionedEnd;if(1===n.points.length)return Va(n.points[0],o,r)<=i;for(let s=0;s<n.points.length-1;s+=1){const e=n.points[s],t=n.points[s+1];if(e&&t&&qa(o,r,e,t)<=i)return!0}return!1}},Yb="arrow.create",Xb=class extends bS{constructor(e){super(e,"arrow"),this.initial="idle",this.addChild(new Kb(e,this)),this.addChild(new Vb(e,this))}},Kb=class extends bS{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.editor.getDefaultShapeProps("arrow"),n=((e,{terminal:t,rawPagePoint:n,ignoreTargets:i=!1})=>Za(e,{terminal:t,rawPagePoint:n,oppositePagePoint:n.add(new wm(1,0)),ignoreTargets:i}))(this.editor,{terminal:"start",rawPagePoint:e.pagePoint,ignoreTargets:e.accelKey});this.transition("creating",{startPagePoint:n.pagePoint,currentPagePoint:n.pagePoint.clone(),shapeId:null,startBinding:n.binding,props:t})}},Vb=class extends bS{info=null;constructor(e,t){super(e,"creating",t)}onEnter(e){if(this.info=e,!this.info)return;this.editor.history.mark(Yb);const t=ja(this.editor,{startPagePoint:this.info.startPagePoint,endPagePoint:this.info.startPagePoint,startBinding:this.info.startBinding,props:{stroke:this.info.props.stroke,strokeWidth:this.info.props.strokeWidth,headStart:this.info.props.headStart,headEnd:this.info.props.headEnd}},"user");this.info.shapeId=t.id,this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),this.editor.setBindingPreview(null),this.updateCreationBindingGuides(t)}onPointerMove(e){this.updateShape(e.pagePoint)}onTick(e){if(!this.info)return;const t=this.editor.inputs.state.get();if("dragging"!==t.dragPhase||!t.currentPagePoint||!t.currentScreenPoint)return;const n=_i(t.currentScreenPoint,this.editor.viewportScreenSizeSignal.get(),e.elapsed);0===n.x&&0===n.y||(this.editor.panCamera(n),this.updateShape(this.editor.screenToPage(t.currentScreenPoint)))}onPointerUp(e){if(this.info){if(this.updateShape(e.pagePoint),!this.info.shapeId||this.info.startPagePoint.dist(this.info.currentPagePoint)<4)return this.editor.history.bailToMark(Yb),void this.transition("idle");G(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(Yb),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})}else this.transition("idle")}onCancel(){this.editor.history.bailToMark(Yb),this.transition("idle")}onExit(){this.editor.setTerminalBindingGuides(null),this.info=null}updateShape(e){if(!this.info)return;this.info.currentPagePoint=e.clone();const t=this.info.shapeId,n=t?this.editor.getShape(t):null,i=Ma(n)?Qa(this.editor,{arrow:n,terminal:"end",rawPagePoint:e,ignoreTargets:this.editor.inputs.state.get().accelKey}):Za(this.editor,{terminal:"end",rawPagePoint:e,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey}),o=Ga(this.editor,t,"end",this.info.startBinding&&i.binding?.targetShapeId===this.info.startBinding.targetShapeId?{pagePoint:e,binding:null,preview:null}:i,"user")??(t?this.editor.getShape(t):null);this.updateCreationBindingGuides(Ma(o)?o:null)}updateCreationBindingGuides(e){if(!e)return void this.editor.setTerminalBindingGuides(null);const t=new Map(this.editor.getBindingsFromShape(e.id).filter(Ra).map(e=>[e.props.terminal,e.toId])),n=La(this.editor,e).bindingSegments.map(n=>({...n,ownerShapeId:e.id,targetShapeId:t.get(n.terminal)??null}));this.editor.setTerminalBindingGuides(n)}},qb=class{type="arrow";toSvg(e,t){const n=t.resolveColor(e.props.stroke),i="arrow"===e.props.headStart?`url(#${t.addDef(sd("start",n))})`:void 0,o="arrow"===e.props.headEnd?`url(#${t.addDef(sd("end",n))})`:void 0;return{tag:"path",attrs:{d:Fa(t.editor,e).path,fill:"none",stroke:n,"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":i,"marker-end":o}}}},jb=[{value:y("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:y("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:y("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:y("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],Gb=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Zb=[{value:"none",label:"None",icon:"minus"},{value:"arrow",label:"Arrow",icon:"arrow-right"}],Qb=bo({name:"arrow",createFeature:()=>({id:"land.arrow.bundle",editorRuntimePlugins:[{id:"land.arrow",shapeCapabilities:[{type:"arrow",schemaProps:["w","h","start","end","bend","stroke","strokeWidth","headStart","headEnd"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Binding support lives in arrow binding records, not arrow props."]}],shapeUtils:[new Wb],shapeSvgExporters:[new qb],bindingUtils:[new Ob],interactionHandlers:[{id:"land.arrow.interactions",selectionHandle:td()}],canvasActions:[id("stroke"),id("strokeWidth"),id("headStart"),id("headEnd"),od("stroke"),od("strokeWidth"),od("headStart"),od("headEnd")],toolbarContributions:[{id:"arrow.tool-toolbar",surface:"tool",placement:"chrome",order:40,actionIds:[YS],getGroups:e=>[{id:"arrow.tools",items:[{kind:"button",id:"arrow.tool.arrow",actionId:YS,value:"arrow",label:"Arrow",shortcut:e.editor.shortcuts.getToolShortcutLabel("arrow"),icon:"arrow-right",dataUi:"arrow-tool-button"}]}]},{id:"arrow.default-style.tool-toolbar",surface:"tool",order:41,actionIds:["arrow.default-stroke","arrow.default-strokeWidth","arrow.default-headStart","arrow.default-headEnd"],when:e=>"arrow"===e.tool.activeToolId,getGroups:()=>nd({strokeActionId:"arrow.default-stroke",strokeWidthActionId:"arrow.default-strokeWidth",headStartActionId:"arrow.default-headStart",headEndActionId:"arrow.default-headEnd",dataUiPrefix:"arrow-default"})},{id:"arrow.selection-toolbar",surface:"selection",order:20,actionIds:["arrow.set-stroke","arrow.set-strokeWidth","arrow.set-headStart","arrow.set-headEnd"],when:e=>"arrow"===e.selection.commonShapeType,getGroups:()=>nd({strokeActionId:"arrow.set-stroke",strokeWidthActionId:"arrow.set-strokeWidth",headStartActionId:"arrow.set-headStart",headEndActionId:"arrow.set-headEnd",dataUiPrefix:"arrow"})}],setup(e){e.setTerminalBindingResolver(Za),e.tools.register("arrow",e=>new Xb(e),{shortcut:"a"})}}],canvasRenderPlugins:[{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:ad}]}],shapeTypes:["arrow"]})}),Jb=.08,ex=new WeakMap,tx=new WeakMap,nx=new WeakMap,ix=new WeakMap,ox="draw.create",rx=class extends bS{constructor(e){super(e,"draw"),this.initial="idle",this.addChild(new sx(e,this)),this.addChild(new ax(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("draw")}},sx=class extends bS{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.parent.getDefaultProps();var n,i;this.transition("drawing",{originPagePoint:e.pagePoint.clone(),parentId:ll(this.editor,e.pagePoint),shapeId:null,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,isClosed:t.isClosed,isPen:"pen"===e.pointerType,pointGuard:(n=t.strokeWidth,i="pen"===e.pointerType,i?{minPointDistance:Math.max(.12,.08*n),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.3,.14*n),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[ol(e.pagePoint,e.pagePoint,e.pressure,"pen"===e.pointerType)]}]})}},ax=class extends bS{tool;info=null;pendingUpdateFrame=null;constructor(e,t){super(e,"drawing",t),this.tool=t}onEnter(e){this.info=e,this.editor.clearSelectionTransients(),this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.editor.history.mark(ox)}onPointerMove(e){this.appendPoint(e,!1)}onPointerUp(e){this.appendPoint(e,!0),this.flushShapeUpdate();const t=this.info?.shapeId??null;if(!t)return this.editor.history.bailToMark(ox),void this.transition("idle");this.info?.parentId.startsWith("shape:")||G(this.editor,t,{source:"user"}),this.editor.history.squashToMark(ox),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.editor.history.bailToMark(ox),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.info=null}appendPoint(e,t){if(!this.info)return;const n=ol(e.pagePoint,this.info.originPagePoint,e.pressure,this.info.isPen);if(e.shiftKey?this.appendStraightSegmentPoint(n):(this.exitStraightSegmentMode(),this.info.preserveStraightEndpointOnNextFreePoint?this.appendDistinctCurrentPoint(n)&&(this.info.preserveStraightEndpointOnNextFreePoint=!1):this.appendGuardedCurrentPoint(n)),this.splitCurrentSegmentAtLimit(),!this.info.shapeId){const n=this.info.originPagePoint.dist(e.pagePoint);if(!t&&n<2)return;const i=this.createShape();return void(this.info.shapeId=i.id)}this.scheduleShapeUpdate()}scheduleShapeUpdate(){var e;null===this.pendingUpdateFrame&&(this.pendingUpdateFrame=(e=()=>{this.pendingUpdateFrame=null,this.flushShapeUpdate()},"function"==typeof requestAnimationFrame?{type:"animation",id:requestAnimationFrame(e)}:{type:"timeout",id:setTimeout(e,16)}))}cancelScheduledShapeUpdate(){var e;null!==this.pendingUpdateFrame&&("animation"!==(e=this.pendingUpdateFrame).type?clearTimeout(e.id):cancelAnimationFrame(e.id),this.pendingUpdateFrame=null)}flushShapeUpdate(){this.cancelScheduledShapeUpdate(),this.info?.shapeId&&this.editor.commands.updateShapes([{id:this.info.shapeId,props:dl(this.info.segments)}],{source:"user"})}createShape(){const e=this.tool.getDefaultProps(),t=((e,t)=>t&&e.canUseShapeParent(t)?t:e.getCurrentPageId())(this.editor,this.info?.parentId);this.info&&(this.info.parentId=t);const[n]=this.editor.commands.createShapes([{type:"draw",x:this.info?.originPagePoint.x??0,y:this.info?.originPagePoint.y??0,...t.startsWith("shape:")?{parentId:t}:{},props:{...e,stroke:this.info?.stroke??e.stroke,strokeWidth:this.info?.strokeWidth??e.strokeWidth,fill:this.info?.fill??e.fill,isClosed:this.info?.isClosed??e.isClosed,...dl(this.info?.segments??[]),isPen:this.info?.isPen??!1}}],{source:"user"});if(!n||"draw"!==n.type)throw new Error("Failed to create draw shape");return n}appendStraightSegmentPoint(e){if(!this.info)return;this.info.preserveStraightEndpointOnNextFreePoint=!1;const t=sl(this.info),n=t[t.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return void this.replaceCurrentSegmentPoints([{...e,segment:"straight"}]);this.info.straightSegmentAnchorPoint=rl(n)}const i={...e,segment:"straight"};this.replaceCurrentSegmentPoints("straight"!==n?.segment?[...t,i]:[...t.slice(0,-1),i])}exitStraightSegmentMode(){this.info?.straightSegmentAnchorPoint&&(this.info.straightSegmentAnchorPoint=null,this.info.preserveStraightEndpointOnNextFreePoint=!0)}appendDistinctCurrentPoint(e){if(!this.info)return!1;const t=sl(this.info),n=t[t.length-1];return!(n&&(i=n).x===(o=e).x&&i.y===o.y&&i.pressure===o.pressure&&i.segment===o.segment||(this.replaceCurrentSegmentPoints([...t,rl(e)]),0));var i,o}appendGuardedCurrentPoint(e){if(!this.info)return;const t=sl(this.info).map(rl);(function(e,t,n){const i=pd(t),o=e[e.length-1];if(!o)return void e.push(i);if(ud(o,i))return;const r=((e,t)=>{if(e<=t.softMaxPointCount)return t.minPointDistance;const n=ld((e-t.softMaxPointCount)/Math.max(t.hardMaxPointCount-t.softMaxPointCount,1),0,1);return t.minPointDistance*(1+n*t.maxDistanceMultiplier)})(e.length,n),s=i.x-o.x,a=i.y-o.y,d=Math.abs((i.pressure??0)-(o.pressure??0));s*s+a*a<r*r&&d<n.pressureDeltaThreshold?e[e.length-1]=i:e.push(i)})(t,e,this.info.pointGuard),this.replaceCurrentSegmentPoints(t)}replaceCurrentSegmentPoints(e){if(!this.info)return;const t=al(this.info.segments);this.info.segments=[...t.slice(0,-1),{points:e.map(rl)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const e=cd(this.info.isPen);let t=al(this.info.segments),n=t[t.length-1];for(;n.points.length>e;){const i=n.points.slice(0,e).map(rl),o=i[i.length-1],r=n.points.slice(e).map(rl);if(!o||0===r.length)break;const s={points:[rl(o),...r]};t=[...t.slice(0,-1),{points:i},s],n=s}this.info.segments=t}},dx=class extends SS{type="draw";getDefaultProps(){return{segments:(e=[{x:0,y:0},{x:24,y:12}],[{points:e.map(pd)}]),stroke:y("stroke-slate"),strokeWidth:4,fill:"transparent",isClosed:!1,isPen:!1};var e}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{segments:yl(t.segments,n.segments),stroke:P(t.stroke,n.stroke),strokeWidth:Math.max(4,fl(t.strokeWidth,n.strokeWidth)),fill:P(t.fill,n.fill),isClosed:"boolean"==typeof t.isClosed?t.isClosed:n.isClosed,isPen:"boolean"==typeof t.isPen?t.isPen:n.isPen}}getBounds(e){const t=Qd(e);return new Pm(e.x+t.localBounds.x,e.y+t.localBounds.y,t.localBounds.w,t.localBounds.h)}getLocalBounds(e){return Qd(e).localBounds}getRenderBounds(e){return Qd(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}canReceiveTerminalBinding(e){return!0}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=function(e,t){let n=(({segments:e,strokeWidth:t,isPen:n,isClosed:i,targetSelectionStrokeBounds:o})=>{let r=wd(e);for(let s=0;s<2;s+=1){const e=Vd(r,t,n,i),s=jd(e.pointBounds,e.localBounds,o);r=Bd(r,e.pointBounds,s)}return r})({segments:Rd(tl(e),t),strokeWidth:e.props.strokeWidth,isPen:e.props.isPen??!1,isClosed:e.props.isClosed,targetSelectionStrokeBounds:t.targetSelectionStrokeBounds});return t.scaleX<0&&(n=Ld(n,{axis:"horizontal",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),t.scaleY<0&&(n=Ld(n,{axis:"vertical",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),Jd(Ad(n,t),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed)}(e,{targetSelectionStrokeBounds:t.selectionLocalBounds,scaleX:t.scaleX,scaleY:t.scaleY,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter});return{id:e.id,x:n.x,y:n.y,rotation:0,scaleX:1,scaleY:1,props:{segments:il(n.segments)}}}flipSelectionBounds(e,t){const n=((e,t)=>Jd(Ad(Ld(Rd(tl(e),t),t),t),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed))(e,{axis:t.axis,selectionMirrorBounds:t.selectionBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter});return{id:e.id,x:n.x,y:n.y,rotation:0,scaleX:1,scaleY:1,props:{segments:il(n.segments)}}}getSelectionOverlayInfo(e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null}}isWrappedByBrush(e,t){return nl(e).outlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return!!this.isWrappedByBrush(e,t)||!t.isWrapping&&(e=>{const t=new wm(e.minX,e.minY),n=new wm(e.maxX,e.minY),i=new wm(e.maxX,e.maxY),o=new wm(e.minX,e.maxY);return[[t,n],[n,i],[i,o],[o,t]]})(t.brushBounds).some(([t,n])=>this.hitTestLineSegment(e,{pageStart:t,pageEnd:n,positionedStart:t,positionedEnd:n,margin:0}))}getPositionedOutlineVertices(e){return el(e).outlineVertices}hitTest(e,t){return function(e,t,n,i={}){if(i.isClosed&&void 0!==i.fill&&!T(i.fill)&&e.normalizedPoints.length>=3&&hl(n,e.normalizedPoints.map(hd)))return!0;if(i.isClosed&&((e,t)=>{if(0===t.length)return Number.POSITIVE_INFINITY;if(1===t.length)return e.dist(hd(t[0]));let n=Number.POSITIVE_INFINITY;for(let i=1;i<t.length;i+=1){const o=t[i-1],r=t[i];o&&r&&(n=Math.min(n,cl(e,hd(o),hd(r))))}return t.length>=3&&(n=Math.min(n,cl(e,hd(t[t.length-1]),hd(t[0])))),n})(n,e.normalizedPoints)<=Math.max(4,.5*t))return!0;if(0===e.outlineVertices.length)return!1;for(const o of e.outlinePolygons){if(hl(n,o))return!0;if(pl(n,o)<=Math.max(4,.5*t))return!0}return!1}(el(e),e.props.strokeWidth,t,{fill:e.props.fill,isClosed:e.props.isClosed})}hitTestLineSegment(e,t){return((e,t,n,i,o={})=>{const r=Math.max(4,.5*t,o.margin??0);return!!(o.isClosed&&void 0!==o.fill&&!T(o.fill)&&e.normalizedPoints.length>=3&&gl(n,i,e.normalizedPoints.map(hd),r))||0!==e.outlineVertices.length&&e.outlinePolygons.some(e=>gl(n,i,e,r))})(nl(e),e.props.strokeWidth,t.pageStart,t.pageEnd,{fill:e.props.fill,isClosed:e.props.isClosed,margin:t.margin})}repairLoadedShape(e){const t=Qd(e);if(0===t.pointBounds.x&&0===t.pointBounds.y&&0===e.rotation&&1===e.scaleX&&1===e.scaleY)return null;const n=(e=>Jd(tl(e),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed))(e);return{...e,x:n.x,y:n.y,rotation:0,scaleX:1,scaleY:1,props:{...e.props,segments:il(n.segments)}}}},lx=class{type="draw";toSvg(e,t){const n=Qd(e);if(!n.path&&!n.selectionPath)return null;const i=[];return n.fillPath&&!T(e.props.fill)&&i.push({tag:"path",attrs:{d:n.fillPath,fill:t.resolveColor(e.props.fill),stroke:"none"}}),e.props.isClosed&&n.selectionPath?i.push({tag:"path",attrs:{d:n.selectionPath,fill:"none",stroke:t.resolveColor(e.props.stroke),"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}):n.path&&i.push({tag:"path",attrs:{d:n.path,fill:t.resolveColor(e.props.stroke),stroke:"none"}}),{tag:"g",children:i}}},cx=[{value:y("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:y("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:y("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:y("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],ux=[{value:"transparent",label:"None",color:"transparent"},{value:y("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:y("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:y("fill-red"),label:"Red",color:"var(--land-shape-fill-red)"},{value:y("fill-white"),label:"White",color:"var(--land-shape-fill-white)"}],hx=[{value:4,label:"4"},{value:6,label:"6"},{value:8,label:"8"},{value:10,label:"10"}],px=[{value:"open",label:"Open"},{value:"closed",label:"Closed"}],gx=bo({name:"draw",createFeature:()=>({id:"land.draw.bundle",editorRuntimePlugins:[{id:"land.draw",shapeCapabilities:[{type:"draw",schemaProps:["segments","stroke","strokeWidth","fill","isClosed","isPen"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Draw stores raw segments as document truth and derives a shared freehand stroke geometry for render, hit test, brush wrap, and SVG export."]}],shapeUtils:[new dx],shapeSvgExporters:[new lx],canvasActions:[{id:"draw.set-closed",isVisible:e=>"draw"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>wl(e.selection.selectedShapes),run({context:e,value:t}){const n=Pl(t);if(null===n)return;const i=e.selection.selectedShapes.filter(bl).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{isClosed:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},Il("fill"),Il("stroke"),Il("strokeWidth"),{id:"draw.default-closed",isVisible:e=>"draw"===e.tool.activeToolId,getValue:e=>e.editor.getDefaultShapeProps("draw").isClosed?"closed":"open",run({context:e,value:t}){const n=Pl(t);null!==n&&e.editor.updateDefaultShapeProps("draw",{isClosed:n})}},vl("fill"),vl("stroke"),vl("strokeWidth")],toolbarContributions:[{id:"draw.tool-toolbar",surface:"tool",placement:"chrome",order:45,actionIds:[YS],getGroups:e=>[{id:"draw.tools",items:[{kind:"button",id:"draw.tool.draw",actionId:YS,value:"draw",label:"Draw",shortcut:e.editor.shortcuts.getToolShortcutLabel("draw"),icon:"pencil",dataUi:"draw-tool-button"}]}]},{id:"draw.default-style.tool-toolbar",surface:"tool",order:46,actionIds:["draw.default-closed","draw.default-fill","draw.default-stroke","draw.default-strokeWidth"],when:e=>"draw"===e.tool.activeToolId,getGroups:()=>xl({closedActionId:"draw.default-closed",fillActionId:"draw.default-fill",strokeActionId:"draw.default-stroke",strokeWidthActionId:"draw.default-strokeWidth",dataUiPrefix:"draw-default"})},{id:"draw.selection-toolbar",surface:"selection",order:20,actionIds:["draw.set-closed","draw.set-fill","draw.set-stroke","draw.set-strokeWidth"],when:e=>"draw"===e.selection.commonShapeType,getGroups:()=>xl({closedActionId:"draw.set-closed",fillActionId:"draw.set-fill",strokeActionId:"draw.set-stroke",strokeWidthActionId:"draw.set-strokeWidth",dataUiPrefix:"draw"})}],contextMenuContributions:[{id:"draw.shape-context-menu",target:"selection",order:35,actionIds:["draw.set-closed"],when:e=>"draw"===e.selection.commonShapeType,getSections(e){const t="closed"===wl(e.selection.selectedShapes)?"open":"closed";return[{id:"draw.context-menu",title:"Draw",items:[{kind:"command",id:"draw.toggle-closed",actionId:"draw.set-closed",value:t,label:"closed"===t?"Close freehand":"Open freehand",icon:"pencil",dataUi:"context-menu-toggle-draw-closed-button"}]}]}}],setup(e){e.tools.register("draw",e=>new rx(e),{shortcut:"p"})}}],canvasRenderPlugins:[{id:"land.draw.react",shapeRenderers:[{type:"draw",component:Tl}]}],shapeTypes:["draw"]})}),fx=class extends bS{constructor(e){super(e,"eraser"),this.initial="idle",this.addChild(new mx(e,this)),this.addChild(new Sx(e,this)),this.addChild(new yx(e,this))}onExit(){Dl(this.editor)}},mx=class extends bS{constructor(e,t){super(e,"idle",t)}onEnter(){Dl(this.editor)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={originPagePoint:t.pagePoint.clone(),previousPagePoint:t.pagePoint.clone(),protectedContainerIds:Ml(e,t.pagePoint),erasingShapeIds:new Set,trail:[t.pagePoint.clone()]};return Ll(e,n,t),Ul(e,n),n})(this.editor,e))}},Sx=class extends bS{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&(Fl(this.editor,this.info,e),$l(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),Ul(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(e){this.info&&(Ll(this.editor,this.info,e),Ul(this.editor,this.info),zl(this.editor,this.info)),this.transition("idle")}onCancel(){Dl(this.editor),this.transition("idle")}onExit(){this.info=null}},yx=class extends bS{info=null;constructor(e,t){super(e,"erasing",t)}onEnter(e){this.info=e}onPointerMove(e){this.update(e)}onPointerUp(e){this.update(e),this.info&&zl(this.editor,this.info),this.transition("idle")}onCancel(){Dl(this.editor),this.transition("idle")}onExit(){this.info=null}update(e){this.info&&(Fl(this.editor,this.info,e),$l(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),Ul(this.editor,this.info))}},bx=Xf(()=>ir(nr().eraserTrailActiveSignal)?nm(xx,{}):null),xx=Xf(()=>{const e=nr(),t=ir(e.eraserTrailSignal),n=ir(e.cameraZoomSignal),i=Math.max(n,1e-4),o=(()=>{const[e,t]=Jf(()=>_l());return qf(()=>{if("undefined"==typeof window)return;let e=0;const n=i=>{t(i),e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(e)}},[]),e})(),r=Qf({samples:[],sourceLength:0}),s=Math.max(o,_l());((e,t,n,i)=>{if(Nl(e,i),t.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),t.length===e.sourceLength)return;const o=e.sourceLength,r=t.length-o,s=e.samples[e.samples.length-1]?.time??i-Ex*r;for(let a=o;a<t.length;a++){const d=t[a];Hl(e,{x:d.x,y:d.y},n,Ql(s,i,(a-o+1)/r))}e.sourceLength=t.length,Nl(e,i)})(r.current,t,i,s);const a=function(e,t){const n=Ol(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),i=[e[0]];for(let o=1;o<e.length;o++)i.push(Zl(i[i.length-1],e[o],n));return i})(n.length>vx?n.slice(-48):n,kx)}(r.current.samples,s);if(0===a.length)return null;const d=(c=Px/i,0===(l=a).length||c<=0?null:1===l.length?tc(Yl(l[0],c/2,Tx))??"":tc((e=>{if(0===e.length)return[];if(1===e.length)return Yl(e[0].point,Math.max(e[0].radius,.01),Tx);const t=[],n=[];for(const a of e){const e=Vl(a.direction);ec(t,jl(a.point,Gl(e,a.radius))),ec(n,ql(a.point,Gl(e,a.radius)))}const i=[];for(const a of t)ec(i,a);const o=e[e.length-1],r=Vl(o.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const o=[];for(let r=1;r<Cx;r++){const s=r/Cx;o.push(ql(e,ql(Gl(t,Math.sin(Math.PI*s)*i),Gl(n,-Math.cos(Math.PI*s)*i))))}return o})({center:o.point,direction:o.direction,normal:r,radius:o.radius});for(const a of s)ec(i,a);for(let a=n.length-1;a>=0;a--)ec(i,n[a]);return i})(((e,t)=>{const n=(e=>{const t=[0];for(let n=1;n<e.length;n++)t.push(t[n-1]+Xl(e[n-1],e[n]));return t})(e),i=Math.max(t,n[n.length-1]??0);return e.map((o,r)=>{const s=n[r]??0,a=Jl(s/i,0,1);return{point:o,direction:Wl(e,r),radius:t/2*a,runningLength:s}})})(l,c))));var l,c;return d?nm("g",{"data-ui":"eraser-trail-overlay",children:nm("path",{"data-ui":"eraser-trail-scribble",d:d,fill:Ix})}):null}),Ix="rgba(142, 142, 142, 0.16)",vx=48,wx=1,Px=12,kx=.32,Cx=8,Tx=13,Ex=16,Bx=8,Mx=180,Rx=180,Ax=680,Lx=bo({name:"eraser",createFeature:()=>({id:"land.eraser.bundle",editorRuntimePlugins:[{id:"land.eraser",toolbarContributions:[{id:"eraser.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[YS],getGroups:e=>[{id:"eraser.tools",items:[{kind:"button",id:"eraser.tool.eraser",actionId:YS,value:"eraser",label:"Eraser",shortcut:e.editor.shortcuts.getToolShortcutLabel("eraser"),icon:"eraser",dataUi:"eraser-tool-button"}]}]}],setup(e){e.tools.register("eraser",e=>new fx(e),{shortcut:"e"})}}],canvasRenderPlugins:[{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",layer:"below-host",component:bx}]}],shapeTypes:[]})}),Fx=class extends SS{type="frame";getDefaultProps(){return{w:640,h:360,name:"Frame",fill:"transparent",stroke:y("stroke-muted"),strokeWidth:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,rc(t.w,n.w)),h:Math.max(1,rc(t.h,n.h)),name:"string"==typeof t.name&&t.name.length>0?t.name:n.name,fill:P(t.fill,n.fill),stroke:P(t.stroke,n.stroke),strokeWidth:Math.max(0,rc(t.strokeWidth,n.strokeWidth))}}getBounds(e){return new Pm(e.x,e.y,e.props.w,e.props.h)}getPointHitTestBounds(e){return this.getBounds(e).expand(3)}canReceiveChildren(e){return!0}canReceiveTerminalBinding(e){return!0}shouldRotateDescendants(e){return!0}getChildClipLocalBounds(e){return this.getLocalBounds(e)}canSelectByBrush(e,t){return super.isWrappedByBrush(e,t)}hitTest(e,t){return sc(this.getBounds(e),t,6)}hitTestBindingTarget(e,t){return this.getBounds(e).containsPoint(t)}hitTestLineSegment(e,t){return((e,t,n,i)=>{const o=i/2;if(sc(e,t,i)||sc(e,n,i))return!0;const r=[new wm(e.minX,e.minY),new wm(e.maxX,e.minY),new wm(e.maxX,e.maxY),new wm(e.minX,e.maxY)];for(let s=0;s<r.length;s+=1){const e=r[s],i=r[(s+1)%r.length];if(e&&i&&Bi(t,n,e,i)<=o)return!0}return!1})(this.getBounds(e),t.positionedStart,t.positionedEnd,Math.max(6,t.margin))}},$x="frame.create",Ux=class extends bS{constructor(e){super(e,"frame"),this.initial="idle",this.addChild(new Dx(e,this)),this.addChild(new zx(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("frame")}},Dx=class extends bS{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("creating",{originPagePoint:e.pagePoint.clone(),currentPagePoint:e.pagePoint.clone(),shapeId:null,shiftKey:e.shiftKey})}},zx=class extends bS{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark($x)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.editor.history.squashToMark($x),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark($x),this.transition("idle")}onExit(){this.info=null}updateShape(e,t,n=!1){if(!this.info)return;this.info.currentPagePoint=e.clone(),this.info.shiftKey=t;const i=this.info.originPagePoint.dist(e);if(!this.info.shapeId&&i<4){if(!n)return;const t=(o=e,r=this.tool.getDefaultProps(),new Pm(o.x-r.w/2,o.y-r.h/2,r.w,r.h)),i=this.createShape(t);return void(this.info.shapeId=i.id)}var o,r;const s=((e,t,n,i)=>{let o=t.x-e.x,r=t.y-e.y;if(n){const e=i.w/i.h,t=Math.abs(o),n=Math.abs(r);0===n||t/Math.max(n,1)>=e?r=t/e*(r<0?-1:1):o=n*e*(o<0?-1:1)}const s=new wm(e.x+o,e.y+r);return new Pm(Math.min(e.x,s.x),Math.min(e.y,s.y),Math.max(Math.abs(s.x-e.x),1),Math.max(Math.abs(s.y-e.y),1))})(this.info.originPagePoint,e,t,this.tool.getDefaultProps());if(!this.info.shapeId){const e=this.createShape(s);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:s.x,y:s.y,props:{w:s.w,h:s.h}}],{source:"user"})}createShape(e){const[t]=this.editor.commands.createShapes([{type:"frame",x:e.x,y:e.y,props:{...this.tool.getDefaultProps(),w:e.w,h:e.h}}],{source:"user"});if(!t||"frame"!==t.type)throw new Error("Failed to create frame shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},_x=class{type="frame";toSvg(e,t){const{fill:n,stroke:i,strokeWidth:o,w:r,h:s,name:a}=e.props,d=t.resolveColor(i),l=o/2;return{tag:"g",children:[{tag:"rect",attrs:{x:l,y:l,width:Math.max(r-o,0),height:Math.max(s-o,0),fill:t.resolveColor(n),stroke:d,"stroke-width":o,"stroke-linejoin":"round","stroke-linecap":"round"}},{tag:"text",attrs:{x:12,y:18,fill:d,"font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":600},children:[a]}]}}},Hx=[{value:"transparent",label:"None",color:"transparent"},{value:y("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:y("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:y("fill-amber"),label:"Amber",color:"var(--land-shape-fill-amber)"}],Nx=[{value:y("stroke-muted"),label:"Slate",color:"var(--land-shape-stroke-muted)"},{value:y("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:y("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:y("stroke-orange"),label:"Orange",color:"var(--land-shape-stroke-orange)"}],Ox=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Wx=bo({name:"frame",createFeature:()=>({id:"land.frame.bundle",editorRuntimePlugins:[{id:"land.frame",shapeCapabilities:[{type:"frame",schemaProps:["w","h","name","fill","stroke","strokeWidth"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Frame renderer, SVG exporter, creation tool, selected-frame style toolbar, selected-child order badge, and minimal single-child sibling reorder controls live in the frame plugin package. ParentId-based child query, child-index ordering, containing-parent query, clipped query bounds, point-in-clip checks, host clipping, select-drag containment, export descendant traversal, and clipped child export have preflights. Richer hover/drag reorder UI remains deferred."]}],shapeUtils:[new Fx],shapeSvgExporters:[new _x],canvasActions:[ac("fill"),ac("stroke"),ac("strokeWidth"),dc("fill"),dc("stroke"),dc("strokeWidth"),{id:"frame.rename",isVisible:e=>1===e.selection.count&&"frame"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return"frame"===t?.type&&!t.isLocked},getValue(e){const[t]=e.selection.selectedShapes;return"frame"===t?.type?t.props.name:null},run({context:e,value:t}){const[n]=e.selection.selectedShapes;"frame"===n?.type&&"string"==typeof t&&e.editor.commands.updateShapes([{id:n.id,props:{name:t}}],{source:"user"})}},cc("backward"),cc("forward")],toolbarContributions:[{id:"frame.tool-toolbar",surface:"tool",placement:"chrome",order:60,actionIds:[YS],getGroups:e=>[{id:"frame.tools",items:[{kind:"button",id:"frame.tool.frame",actionId:YS,value:"frame",label:"Frame",shortcut:e.editor.shortcuts.getToolShortcutLabel("frame"),icon:"frame",dataUi:"frame-tool-button"}]}]},{id:"frame.default-style.tool-toolbar",surface:"tool",order:61,actionIds:["frame.default-fill","frame.default-stroke","frame.default-strokeWidth"],when:e=>"frame"===e.tool.activeToolId,getGroups:()=>lc({fillActionId:"frame.default-fill",strokeActionId:"frame.default-stroke",strokeWidthActionId:"frame.default-strokeWidth",dataUiPrefix:"frame-default"})},{id:"frame.selection-toolbar",surface:"selection",order:20,actionIds:["frame.set-fill","frame.set-stroke","frame.set-strokeWidth","frame.rename"],when:e=>"frame"===e.selection.commonShapeType,getGroups:e=>[...1===e.selection.count?[{id:"frame.name",items:[{kind:"text-input",id:"frame.name",actionId:"frame.rename",label:"Frame name",placeholder:"Frame",dataUi:"frame-name-input"}]}]:[],...lc({fillActionId:"frame.set-fill",strokeActionId:"frame.set-stroke",strokeWidthActionId:"frame.set-strokeWidth",dataUiPrefix:"frame"})]},{id:"frame.child-order.selection-toolbar",surface:"selection",order:30,actionIds:["frame.child-order.backward","frame.child-order.forward"],when:e=>"frame"===hc(e),getGroups(e){const t=e.editor.getSelectionSiblingOrderState();return[{id:"frame.child-order",items:[...t?[{kind:"badge",id:"frame.child-order-status",label:`${t.index+1} / ${t.count}`,dataUi:"frame-child-order-status"}]:[],{kind:"button",id:"frame.child-order.backward",actionId:"frame.child-order.backward",label:"Send backward",icon:"move-down",dataUi:"frame-child-send-backward-button"},{kind:"button",id:"frame.child-order.forward",actionId:"frame.child-order.forward",label:"Bring forward",icon:"move-up",dataUi:"frame-child-bring-forward-button"}]}]}}],contextMenuContributions:[{id:"frame.child-order.context-menu",target:"selection",order:40,actionIds:["frame.child-order.backward","frame.child-order.forward"],when:e=>"frame"===hc(e),getSections(e){const t=e.editor.getSelectionSiblingOrderState();return[{id:"frame.child-order-context-menu",title:"Frame child",items:[...t?[{kind:"badge",id:"frame.child-order-status",label:`${t.index+1} / ${t.count}`,dataUi:"context-menu-frame-child-order-status"}]:[],{kind:"command",id:"frame.child-order.forward",actionId:"frame.child-order.forward",label:"Bring forward",icon:"move-up",dataUi:"context-menu-frame-child-bring-forward-button"},{kind:"command",id:"frame.child-order.backward",actionId:"frame.child-order.backward",label:"Send backward",icon:"move-down",dataUi:"context-menu-frame-child-send-backward-button"}]}]}}],setup(e){e.tools.register("frame",e=>new Ux(e),{shortcut:"f"})}}],canvasRenderPlugins:[{id:"land.frame.react",shapeRenderers:[{type:"frame",component:pc}]}],shapeTypes:["frame"]})}),Yx="geo.create",Xx=class extends bS{geo;constructor(e,t,n){super(e,t),this.geo=n,this.initial="idle",this.addChild(new Kx(e,this)),this.addChild(new Vx(e,this))}getDefaultProps(){return{...this.editor.getDefaultShapeProps("geo"),geo:this.geo}}onEnter(){this.editor.updateDefaultShapeProps("geo",{geo:this.geo})}},Kx=class extends bS{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("creating",{originPagePoint:e.pagePoint.clone(),currentPagePoint:e.pagePoint.clone(),shapeId:null,shiftKey:e.shiftKey})}},Vx=class extends bS{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(Yx)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.info.shapeId&&G(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(Yx),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(Yx),this.transition("idle")}onExit(){this.info=null}updateShape(e,t,n=!1){if(!this.info)return;this.info.currentPagePoint=e.clone(),this.info.shiftKey=t;const i=this.info.originPagePoint.dist(e);if(!this.info.shapeId&&i<4){if(!n)return;const t=(o=e,r=this.tool.getDefaultProps(),new Pm(o.x-r.w/2,o.y-r.h/2,r.w,r.h)),i=this.createShape(t);return void(this.info.shapeId=i.id)}var o,r;const s=((e,t,n)=>{let i=t.x-e.x,o=t.y-e.y;if(n){const e=Math.max(Math.abs(i),Math.abs(o));i=(i<0?-1:1)*e,o=(o<0?-1:1)*e}const r=new wm(e.x+i,e.y+o);return new Pm(Math.min(e.x,r.x),Math.min(e.y,r.y),Math.max(Math.abs(r.x-e.x),1),Math.max(Math.abs(r.y-e.y),1))})(this.info.originPagePoint,e,t);if(!this.info.shapeId){const e=this.createShape(s);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:s.x,y:s.y,props:{w:s.w,h:s.h}}],{source:"user"})}createShape(e){const[t]=this.editor.commands.createShapes([{type:"geo",x:e.x,y:e.y,props:{...this.tool.getDefaultProps(),w:e.w,h:e.h}}],{source:"user"});if(!t)throw new Error("Failed to create geo shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},qx=class extends Xx{constructor(e){super(e,"rectangle","rectangle")}},jx=class extends Xx{constructor(e){super(e,"ellipse","ellipse")}},Gx=class extends Xx{constructor(e){super(e,"diamond","diamond")}},Zx=class extends Xx{constructor(e){super(e,"triangle","triangle")}},Qx=class extends Xx{constructor(e){super(e,"hexagon","hexagon")}},Jx=class extends Xx{constructor(e){super(e,"star","star")}},eI=["rectangle","ellipse","diamond","triangle","hexagon","star"],tI=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],nI=class extends SS{type="geo";getDefaultProps(){return{w:160,h:108,geo:"rectangle",fill:y("fill-slate"),stroke:y("stroke-slate"),strokeWidth:2,cornerRadiusPercent:12}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,kc(t.w,n.w)),h:Math.max(24,kc(t.h,n.h)),geo:Pc(t.geo)?t.geo:n.geo,fill:P(t.fill,n.fill),stroke:P(t.stroke,n.stroke),strokeWidth:Math.max(1,kc(t.strokeWidth,n.strokeWidth)),cornerRadiusPercent:mc(t.cornerRadiusPercent,n.cornerRadiusPercent)}}getBounds(e){return new Pm(e.x,e.y,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getPositionedOutlineVertices(e){return fc(this.getBounds(e),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}getHandleSnapGeometry(e){return{points:Ac(e),outline:Rc(e)}}hitTest(e,t){const n=this.getBounds(e);switch(e.props.geo){case"ellipse":{const e=n.w/2,i=n.h/2;if(e<=0||i<=0)return!1;const o=t.x-n.center.x,r=t.y-n.center.y;return o*o/(e*e)+r*r/(i*i)<=1}case"diamond":case"triangle":case"hexagon":case"star":return bc(t,yc(n,e.props.geo));default:return bc(t,yc(n,"rectangle",{cornerRadiusPercent:e.props.cornerRadiusPercent}))}}hitTestLineSegment(e,t){const n=this.getBounds(e);switch(e.props.geo){case"ellipse":return((e,t,n,i)=>{const o=e.center,r=e.w/2+i,s=e.h/2+i;if(r<=0||s<=0)return!1;const a=n.sub(t),d=t.sub(o),l=a.x/r,c=a.y/s,u=d.x/r,h=d.y/s,p=l*l+c*c,g=2*(u*l+h*c),f=u*u+h*h-1;if(f<=0)return!0;const m=g*g-4*p*f;if(0===p||m<0)return!1;const S=Math.sqrt(m),y=(-g-S)/(2*p),b=(-g+S)/(2*p);return y>=0&&y<=1||b>=0&&b<=1})(n,t.positionedStart,t.positionedEnd,t.margin);case"rectangle":case"diamond":case"triangle":case"hexagon":case"star":{const i=yc(n,e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent});return this.hitTest(e,t.positionedStart)||this.hitTest(e,t.positionedEnd)||((e,t,n,i)=>{if(n.length<3)return!1;for(let o=0;o<n.length;o+=1){const r=n[o],s=n[(o+1)%n.length];if(r&&s&&Ec(e,t,r,s)<=i)return!0}return!1})(t.positionedStart,t.positionedEnd,i,t.margin)}default:return super.hitTestLineSegment(e,t)}}resolveBindingPoint(e,t){const n=function(e,t,n){const i=new Pm(e.x,e.y,e.props.w,e.props.h);switch(e.props.geo){case"ellipse":return((e,t,n)=>{const i=e.w/2,o=e.h/2;if(i<=0||o<=0)return null;const r=t.sub(e.center),s=n.sub(t),a=s.x/i,d=s.y/o,l=r.x/i,c=r.y/o,u=a*a+d*d,h=2*(l*a+c*d),p=h*h-4*u*(l*l+c*c-1);if(0===u||p<0)return null;const g=Math.sqrt(p),f=[(-h-g)/(2*u),(-h+g)/(2*u)].filter(e=>e>1e-6&&e<=1).sort((e,t)=>e-t)[0];return void 0===f?null:t.add(s.mul(f))})(i,t,n);case"rectangle":return Mc(t,n,yc(i,e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent}));default:return Mc(t,n,yc(i,e.props.geo))}}(e,Je(e,t.rawPagePoint,this),Je(e,t.oppositePagePoint,this));return n?Qe(e,n,this):t.rawPagePoint}},iI=class{type="geo";toSvg(e,t){const{geo:n,fill:i,stroke:o,strokeWidth:r,w:s,h:a}=e.props,d=r/2,l=Math.max(s-r,0),c=Math.max(a-r,0),u={fill:t.resolveColor(i),stroke:t.resolveColor(o),"stroke-width":r,"stroke-linejoin":"round","stroke-linecap":"round"};if("ellipse"===n)return{tag:"ellipse",attrs:{...u,cx:s/2,cy:a/2,rx:l/2,ry:c/2}};if("rectangle"!==n){const e=yc(new Pm(d,d,l,c),n).map(e=>`${_c(e.x)},${_c(e.y)}`).join(" ");return{tag:"polygon",attrs:{...u,points:e}}}const h=Sc({cornerRadiusPercent:e.props.cornerRadiusPercent,w:l,h:c});return{tag:"rect",attrs:{...u,x:d,y:d,width:l,height:c,rx:h,ry:h}}}},oI=[{value:y("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:y("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:y("fill-red"),label:"Red",color:"var(--land-shape-fill-red)"},{value:y("fill-white"),label:"White",color:"var(--land-shape-fill-white)"}],rI=[{value:y("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:y("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:y("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:y("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],sI=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],aI=[{value:"rectangle",label:"Rectangle",icon:"square",dataUiPrefix:"rectangle"},{value:"ellipse",label:"Ellipse",icon:"circle",dataUiPrefix:"ellipse"},{value:"diamond",label:"Diamond",icon:"diamond",dataUiPrefix:"diamond"},{value:"triangle",label:"Triangle",icon:"triangle",dataUiPrefix:"triangle"},{value:"hexagon",label:"Hexagon",icon:"hexagon",dataUiPrefix:"hexagon"},{value:"star",label:"Star",icon:"star",dataUiPrefix:"star"}],dI=bo({name:"geo",createFeature:()=>({id:"land.geo.bundle",editorRuntimePlugins:[{id:"land.geo",shapeCapabilities:[{type:"geo",schemaProps:["w","h","geo","fill","stroke","strokeWidth","cornerRadiusPercent"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Toolbar covers built-in geo variants through geo props."]}],shapeUtils:[new nI],shapeSvgExporters:[new iI],canvasActions:[{id:"geo.set-kind",isVisible:e=>"geo"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>Uc(e.selection.selectedShapes),run({context:e,value:t}){if(!Pc(t))return;const n=e.selection.selectedShapes.filter(wc).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{geo:t}}));0!==n.length&&e.editor.commands.updateShapes(n,{source:"user"})}},Lc("fill"),Lc("stroke"),Lc("strokeWidth"),{id:"geo.set-cornerRadiusPercent",isVisible:e=>"rectangle"===Uc(e.selection.selectedShapes),isEnabled:e=>e.selection.selectedShapes.some(e=>wc(e)&&"rectangle"===e.props.geo&&!e.isLocked),getValue:e=>(e=>{let t;for(const n of e){if(!wc(n)||"rectangle"!==n.props.geo)continue;const e=mc(n.props.cornerRadiusPercent);if(void 0!==t){if(t!==e)return null}else t=e}return t??null})(e.selection.selectedShapes),run({context:e,value:t}){if("number"!=typeof t||!Number.isFinite(t))return;const n=mc(t),i=e.selection.selectedShapes.filter(wc).filter(e=>"rectangle"===e.props.geo&&!e.isLocked).map(e=>({id:e.id,props:{cornerRadiusPercent:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},Fc("fill"),Fc("stroke"),Fc("strokeWidth")],toolbarContributions:[{id:"geo.tool-toolbar",surface:"tool",placement:"chrome",order:20,actionIds:[YS],getGroups:e=>[{id:"geo.tools",items:[{kind:"segmented",id:"geo.tool-picker",actionId:YS,options:aI.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-tool-option`}))}]}]},{id:"geo.default-style.tool-toolbar",surface:"tool",order:21,actionIds:["geo.default-fill","geo.default-stroke","geo.default-strokeWidth"],when:e=>zc(e.tool.activeToolId),getGroups:()=>$c({fillActionId:"geo.default-fill",strokeActionId:"geo.default-stroke",strokeWidthActionId:"geo.default-strokeWidth",dataUiPrefix:"geo-default"})},{id:"geo.selection-toolbar",surface:"selection",order:20,actionIds:["geo.set-kind","geo.set-fill","geo.set-stroke","geo.set-strokeWidth","geo.set-cornerRadiusPercent"],when:e=>"geo"===e.selection.commonShapeType,getGroups(e){const t=Uc(e.selection.selectedShapes);return[{id:"geo.shape-kind",items:[{kind:"segmented",id:"geo.shape-kind",actionId:"geo.set-kind",options:aI.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-shape-button`}))}]},...$c({fillActionId:"geo.set-fill",strokeActionId:"geo.set-stroke",strokeWidthActionId:"geo.set-strokeWidth",dataUiPrefix:"geo"}),..."rectangle"===t?[(n="geo",{id:`${n}.style-corner-radius-percent`,items:[{kind:"slider",id:`${n}.corner-radius-percent`,actionId:"geo.set-cornerRadiusPercent",label:"Corner radius %",min:0,max:50,step:1,dataUi:`${n}-corner-radius-percent-control`}]})]:[]];var n}}],setup(e){e.tools.register("rectangle",e=>new qx(e),{shortcut:"r"}),e.tools.register("ellipse",e=>new jx(e),{shortcut:"o"}),e.tools.register("diamond",e=>new Gx(e),{shortcut:"d"}),e.tools.register("triangle",e=>new Zx(e)),e.tools.register("hexagon",e=>new Qx(e)),e.tools.register("star",e=>new Jx(e))}}],canvasRenderPlugins:[{id:"land.geo.react",shapeRenderers:[{type:"geo",component:Hc}]}],shapeTypes:["geo"]})}),lI=class extends SS{type="group";getDefaultProps(){return{w:1,h:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Oc(t.w,n.w),h:Oc(t.h,n.h)}}getBounds(e){return new Pm(e.x,e.y,e.props.w,e.props.h)}hitTest(e,t){return!1}isTransformDescendantContainer(e){return!0}canUngroupChildren(e){return!0}canReceiveChildren(e){return!0}},cI=class{type="group";toSvg(e){return{tag:"g"}}},uI=bo({name:"group",createFeature:()=>({id:"land.group.bundle",editorRuntimePlugins:[{id:"land.group",shapeCapabilities:[{type:"group",schemaProps:["w","h"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Group is a transparent parent shape. The editor core handles group/ungroup commands, descendant-aware selection transforms, group hit selection bubbling, selected-group child hit selection, descendant export traversal, and child movement through existing parentId queries."]}],shapeUtils:[new lI],shapeSvgExporters:[new cI]}],canvasRenderPlugins:[{id:"land.group.react",shapeRenderers:[{type:"group",component:Wc}]}],shapeTypes:["group"]})}),hI="image.replace",pI="image.download-original",gI="image.insert",fI="image.crop",mI="image.crop.done",SI="image.crop.zoom",yI="image.crop.aspect-ratio",bI="image.crop.reset",xI="image.corner-radius",II=1e-4,vI=1e-4,wI="image.crop",PI="image.crop.translate",kI="image.crop:edit:",CI=[{label:"1:1",value:"1:1",ratio:1},{label:"4:3",value:"4:3",ratio:4/3},{label:"16:9",value:"16:9",ratio:16/9}],TI={top_left:"nwse-resize",top:"ns-resize",top_right:"nesw-resize",right:"ew-resize",bottom_right:"nwse-resize",bottom:"ns-resize",bottom_left:"nesw-resize",left:"ew-resize"},EI=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],BI=new Map,MI="image.smudge",RI="image.smudge.cancel",AI="image.smudge.confirm",LI="image.smudge.brush-size",FI="image.smudge.brush-color",$I="image.smudge:edit:",UI="#ffff00",DI=24,zI=UI,_I=.45,HI=class{editor;confirmHandler=null;session=null;subscribers=new Set;constructor(e){this.editor=e}start(e,t){if(e.isLocked)return!1;const n=cu(e.id),i=this.editor.getShapeEditingSession();if(i&&(i.shapeId!==e.id||i.markId!==n))return!1;if(this.session&&i?.shapeId===e.id&&uu(e,i.markId))return this.session={...this.session,brush:hu({...this.session.brush,...t})},this.notify(),!0;this.clear();const o=this.editor.startEditingShape({shapeId:e.id,markId:n,entryMode:"focusEnd"},"user");return!(!o||o.shapeId!==e.id||o.markId!==n||(this.session={shapeId:e.id,brush:hu(t),strokes:[],activeStrokeId:null,nextStrokeIndex:1},this.notify(),0))}cancel(){const e=this.session?.shapeId??null;this.clear();const t=this.editor.getShapeEditingSession();e&&t?.shapeId===e&&t.markId===cu(e)&&this.editor.cancelEditing("user")}complete(){const e=this.session?.shapeId??null;this.clear();const t=this.editor.getShapeEditingSession();e&&t?.shapeId===e&&t.markId===cu(e)&&this.editor.completeEditing("user")}cancelIfActive(){return!!this.getActiveSession()&&(this.cancel(),!0)}clearForShape(e){this.session?.shapeId===e&&this.clear()}updateBrush(e){if(!this.getActiveSession()||!this.session)return!1;const t=hu({...this.session.brush,...e});return t.size===this.session.brush.size&&t.color===this.session.brush.color&&t.opacity===this.session.brush.opacity||(this.session={...this.session,brush:t},this.notify()),!0}getSnapshot(e){const t=this.getActiveSession();return t&&t.shapeId===e?t:null}getActiveSession(){if(!this.session)return null;const e=this.editor.getShape(this.session.shapeId),t=this.editor.getShapeEditingSession();return e&&t&&t.shapeId===this.session.shapeId&&t.markId===cu(this.session.shapeId)?this.session:(this.clear(),null)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}beginStroke(e){if(!this.session)return;const t=`${this.session.shapeId}:smudge:${this.session.nextStrokeIndex}`,n={id:t,points:[xu(e)],brush:{...this.session.brush}};this.session={...this.session,activeStrokeId:t,nextStrokeIndex:this.session.nextStrokeIndex+1,strokes:[...this.session.strokes,n]},this.notify()}addPoint(e){this.session&&(this.session.activeStrokeId?this.appendPoint(e):this.beginStroke(e))}appendPoint(e){if(!this.session?.activeStrokeId)return;const t=this.session.activeStrokeId,n=this.session.strokes.map(n=>{if(n.id!==t)return n;const i=n.points[n.points.length-1];return i&&Math.hypot(i.x-e.x,i.y-e.y)<.5?n:{...n,points:[...n.points,xu(e)]}});this.session={...this.session,strokes:n},this.notify()}endStroke(){this.session?.activeStrokeId&&(this.session={...this.session,activeStrokeId:null},this.notify())}registerConfirmHandler(e){return this.confirmHandler=e,()=>{this.confirmHandler===e&&(this.confirmHandler=null)}}requestConfirm(e){return this.confirmHandler?this.confirmHandler(e):Promise.resolve(null)}clear(){this.session&&(this.session=null,this.notify())}notify(){for(const e of this.subscribers)e()}},NI=new WeakMap,OI=class extends SS{type="image";getDefaultProps(){return{w:240,h:180,assetId:null,crop:null,cornerRadius:0,altText:""}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,Fu(t.w,n.w)),h:Math.max(24,Fu(t.h,n.h)),assetId:(i=t.assetId,"string"==typeof i&&i.startsWith("asset:")?t.assetId:null),crop:jc(t.crop),cornerRadius:Au(t.cornerRadius,n.cornerRadius),altText:"string"==typeof t.altText?t.altText:n.altText};var i}getBounds(e){return new Pm(e.x,e.y,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getSelectionResizeAspectRatioLock(e,t){return!(!t.isOnlySelected||!Ut(t.handleId))||null}canEdit(e){return!0}onEditEnd(e,t){var n;n=e.id,lu(t.editor).clearForShape(n)}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const i=t.editor.getShapeEditingSession();return i&&i.shapeId===e.id&&iu(e,i.markId)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:ru({crop:e.props.crop,localToPage:t.editor.computeShapeLocalToPageTransform(e),shape:e})}:n}},WI=class{type="image";toSvg(e,t){const{assetId:n,altText:i,crop:o,h:r,w:s}=e.props;if(!n)return null;const a=t.resolveAssetUrl(n);if(!a)return null;const d=Gc(o),l=d?{tag:"svg",attrs:{x:0,y:0,width:s,height:r,viewBox:(c=d,[au(c.left),au(c.top),au(c.width),au(c.height)].join(" ")),preserveAspectRatio:"none",overflow:"hidden"},children:[{tag:"image",attrs:{href:a,x:0,y:0,width:1,height:1,preserveAspectRatio:"none","aria-label":i||void 0}}]}:{tag:"image",attrs:{href:a,width:s,height:r,preserveAspectRatio:"none","aria-label":i||void 0}};var c;const u=Lu({cornerRadius:e.props.cornerRadius,h:r,w:s});return u<=0?l:{tag:"g",attrs:{"clip-path":`url(#${t.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:0,y:0,width:s,height:r,rx:u,ry:u}}]})})`},children:[l]}}},YI={id:"land.image.crop.dom-events",handle:()=>"continue",getCursor({clientPoint:e,editor:t,element:n,container:i}){const o=(e=>{const[t]=e.getSelectedShapes();if(!vu(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&iu(t,n.markId)?t:null})(t);if(!o)return;if(n?.closest('[data-selection-custom-handle-type="image.crop"]'))return;if(!e)return;const r=i.getBoundingClientRect(),s=new wm(e.x-r.left,e.y-r.top);return ju(t,o,t.screenToPage(s))?0!==t.inputs.state.get().buttons?"grabbing":"grab":void 0}},XI={id:"land.image.smudge.dom-events",handle:()=>"continue",getCursor({clientPoint:e,container:t,editor:n}){const i=(e=>{const[t]=e.getSelectedShapes();if(!vu(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&uu(t,n.markId)?t:null})(n);if(!i||!e)return;const o=t.getBoundingClientRect(),r=new wm(e.x-o.left,e.y-o.top);return ju(n,i,n.screenToPage(r))?"crosshair":0!==n.inputs.state.get().buttons?"grabbing":"grab"}},KI=bo({name:"image",createFeature:()=>({id:"land.image.bundle",editorRuntimePlugins:[{id:"land.image",shapeCapabilities:[{type:"image",schemaProps:["w","h","assetId","crop","cornerRadius","altText"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Image shape util, SVG exporter, and React renderer live in @land/plugin-image. Asset records store serializable metadata plus a local or remote source; File/Blob/object URL/download behavior stays in the web host."]}],shapeUtils:[new OI],shapeSvgExporters:[new WI],interactionHandlers:[Eu(),$u()],canvasActions:[Ru(gI),Ru(hI),Ru(pI),...Cu(),{id:MI,isVisible:e=>!!wu(e)&&!Pu(e)&&!ku(e),isEnabled(e){const t=wu(e);return!!t&&!t.isLocked&&!!t.props.assetId},getValue:e=>ku(e),run({context:e}){const t=wu(e);t&&!t.isLocked&&t.props.assetId&&pu({editor:e.editor,shape:t})}},{id:LI,isVisible:e=>ku(e),isEnabled:e=>ku(e),getValue:e=>mu(e.editor)?.brush.size??24,run({context:e,value:t}){fu(e.editor,{size:t})}},{id:FI,isVisible:e=>ku(e),isEnabled:e=>ku(e),getValue(e){const t=mu(e.editor)?.brush;return{color:t?.color??"#ffff00",opacity:t?.opacity??.45}},run({context:e,value:t}){fu(e.editor,{color:t.color,opacity:t.opacity})}},{id:RI,isVisible:e=>ku(e),isEnabled:e=>ku(e),run({context:e}){gu(e.editor)}},{id:AI,isVisible:e=>ku(e),isEnabled:e=>ku(e),run({context:e}){bu(e.editor,{replace:!0})}},{id:xI,isVisible:e=>"image"===e.selection.commonShapeType,isEnabled:e=>e.selection.selectedShapes.some(e=>vu(e)&&!e.isLocked),getValue:e=>(e=>{let t;for(const n of e){if(!vu(n))continue;const e=Au(n.props.cornerRadius);if(void 0!==t){if(t!==e)return null}else t=e}return void 0===t?null:(e=>Number(e.toFixed(2)).toString())(t)})(e.selection.selectedShapes),run({context:e,value:t}){const n=(e=>{if("string"!=typeof e)return null;const t=e.trim();if(0===t.length)return null;const n=Number(t);return Number.isFinite(n)?Au(n):null})(t);if(null===n)return;const i=e.selection.selectedShapes.filter(vu).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{cornerRadius:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}}],toolbarContributions:[{id:"image.tool-toolbar",surface:"tool",placement:"chrome",order:55,actionIds:[gI],getGroups:()=>[{id:"image.tools",items:[{kind:"button",id:gI,actionId:gI,label:"Image",icon:"image-plus",dataUi:"insert-image-tool-button"}]}]},{id:"image.selection-toolbar",surface:"selection",order:30,actionIds:[fI,mI,SI,yI,bI,MI,FI,LI,RI,AI,xI,hI,pI],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups(e){const t=[];return ku(e)?[{id:"image.smudge-color",order:5,items:[{kind:"color-input",id:FI,actionId:FI,label:"Brush color",fallback:UI,includeAlpha:!0,opacityFallback:.45,dataUi:"image-smudge-brush-color-input"}]},{id:"image.smudge-brush",order:10,items:[{kind:"slider",id:LI,actionId:LI,label:"Brush size",min:1,max:128,step:1,dataUi:"image-smudge-brush-size-slider"}]},{id:"image.smudge-actions",order:20,items:[{kind:"button",id:RI,actionId:RI,label:"Cancel smudge",icon:"x",dataUi:"cancel-image-smudge-button"},{kind:"button",id:AI,actionId:AI,label:"Confirm smudge",icon:"check",dataUi:"confirm-image-smudge-button"}]}]:(Pu(e)&&t.push({id:"image.crop-zoom",order:10,items:[{kind:"stepper",id:"image.crop.zoom-stepper",actionId:SI,label:"Zoom",options:[{value:-1,label:"-",dataUi:"image-crop-zoom-out-button"},{value:1,label:"+",dataUi:"image-crop-zoom-in-button"}]}]},{id:"image.crop-aspect",order:20,items:[{kind:"segmented",id:"image.crop.aspect-ratio-segmented",actionId:yI,options:CI.map(e=>({value:e.value,label:e.label,dataUi:`image-crop-aspect-${e.value.replace(":","-")}-button`}))}]},{id:"image.crop-actions",order:30,items:[{kind:"button",id:bI,actionId:bI,label:"Reset crop",icon:"rotate-ccw",dataUi:"reset-image-crop-button"}]}),t.push((({dataUiPrefix:e,id:t,order:n})=>({id:t,order:n,items:[Nu({dataUiPrefix:e})]}))({dataUiPrefix:"image",id:"image.style-corner-radius",order:35})),t.push({id:"image.asset",order:40,items:[{kind:"button",id:fI,actionId:fI,label:"Crop image",icon:"crop",dataUi:"crop-image-button"},{kind:"button",id:MI,actionId:MI,label:"Smudge image",icon:"pencil",dataUi:"smudge-image-button"},{kind:"button",id:mI,actionId:mI,label:"Done cropping",icon:"check",dataUi:"done-cropping-button"},{kind:"button",id:hI,actionId:hI,label:"Replace image",icon:"image-plus",dataUi:"replace-image-button"},{kind:"button",id:pI,actionId:pI,label:"Download original",icon:"download",dataUi:"download-image-original-button"}]}),t)}},{id:"image.floating-selection-toolbar",surface:"selection",placement:"floating",order:30,actionIds:[fI,mI,SI,yI,bI,MI,FI,LI,RI,AI,xI,hI,pI],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups:e=>ku(e)?[{id:"image.floating-smudge-color",order:5,items:[{kind:"color-input",id:"image.floating-smudge.brush-color",actionId:FI,label:"Brush color",fallback:UI,includeAlpha:!0,opacityFallback:.45,dataUi:"floating-image-smudge-brush-color-input"}]},{id:"image.floating-smudge-brush",order:10,items:[{kind:"slider",id:"image.floating-smudge.brush-size",actionId:LI,label:"Brush size",min:1,max:128,step:1,dataUi:"floating-image-smudge-brush-size-slider"}]},{id:"image.floating-smudge-actions",order:20,items:[{kind:"button",id:"image.floating-smudge.cancel",actionId:RI,label:"Cancel smudge",icon:"x",dataUi:"floating-cancel-image-smudge-button"},{kind:"button",id:"image.floating-smudge.confirm",actionId:AI,label:"Confirm smudge",icon:"check",dataUi:"floating-confirm-image-smudge-button"}]}]:Pu(e)?[{id:"image.floating-crop-zoom",order:10,items:[{kind:"stepper",id:"image.floating-crop.zoom-stepper",actionId:SI,label:"Zoom",options:[{value:-1,label:"-",dataUi:"floating-image-crop-zoom-out-button"},{value:1,label:"+",dataUi:"floating-image-crop-zoom-in-button"}]}]},{id:"image.floating-crop-aspect",order:20,items:[{kind:"segmented",id:"image.floating-crop.aspect-ratio-segmented",actionId:yI,options:CI.map(e=>({value:e.value,label:e.label,dataUi:`floating-image-crop-aspect-${e.value.replace(":","-")}-button`}))}]},{id:"image.floating-crop-corner-radius",order:35,items:[Nu({dataUiPrefix:"floating-image-crop"})]},{id:"image.floating-crop-actions",order:30,items:[{kind:"button",id:"image.floating-crop.done",actionId:mI,label:"Done cropping",icon:"check",dataUi:"floating-done-cropping-button"},{kind:"button",id:"image.floating-crop.reset",actionId:bI,label:"Reset crop",icon:"rotate-ccw",dataUi:"floating-reset-image-crop-button"}]}]:[{id:"image.floating-corner-radius",order:10,items:[Nu({dataUiPrefix:"floating-image"})]},{id:"image.floating-asset",order:20,items:[{kind:"button",id:"image.floating.crop",actionId:fI,label:"Crop image",icon:"crop",dataUi:"floating-crop-image-button"},{kind:"button",id:"image.floating.smudge",actionId:MI,label:"Smudge image",icon:"pencil",dataUi:"floating-smudge-image-button"},{kind:"button",id:"image.floating.replace",actionId:hI,label:"Replace image",icon:"image-plus",dataUi:"floating-replace-image-button"},{kind:"button",id:"image.floating.download",actionId:pI,label:"Download original",icon:"download",dataUi:"floating-download-image-original-button"}]}]}],contextMenuContributions:[{id:"image.shape-context-menu",target:"selection",order:30,actionIds:[fI,MI,hI,pI],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getSections:()=>[{id:"image.asset-context-menu",title:"Image",items:[{kind:"command",id:fI,actionId:fI,label:"Crop image",icon:"crop",dataUi:"context-menu-crop-image-button"},{kind:"command",id:MI,actionId:MI,label:"Smudge image",icon:"pencil",dataUi:"context-menu-smudge-image-button"},{kind:"command",id:hI,actionId:hI,label:"Replace image",icon:"image-plus",dataUi:"context-menu-replace-image-button"},{kind:"command",id:pI,actionId:pI,label:"Download original",icon:"download",dataUi:"context-menu-download-image-original-button"}]}]}]}],canvasRenderPlugins:[{id:"land.image.react",domEventGuards:[YI,XI],selectionCustomHandleRenderers:[{type:wI,component:Ku}],shapeRenderers:[{type:"image",component:Ou}]}],shapeTypes:["image"]})}),VI=class extends bS{constructor(e){super(e,"laser"),this.initial="idle",this.addChild(new qI(e,this)),this.addChild(new jI(e,this)),this.addChild(new GI(e,this))}},qI=class extends bS{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={sessionId:e.startLaserTrail(),originPagePoint:t.pagePoint.clone(),trail:[t.pagePoint.clone()]};return Zu(e,n),n})(this.editor,e))}},jI=class extends bS{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&(Gu(this.info,e.pagePoint),Zu(this.editor,this.info),this.transition("drawing",this.info))}onPointerUp(){this.info&&this.editor.finishLaserTrail(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&this.editor.finishLaserTrail(this.info.sessionId),this.transition("idle")}onExit(){this.info&&this.editor.finishLaserTrail(this.info.sessionId),this.info=null}},GI=class extends bS{info=null;constructor(e,t){super(e,"drawing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&(Gu(this.info,e.pagePoint),Zu(this.editor,this.info))}onPointerUp(){this.info&&this.editor.finishLaserTrail(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&this.editor.finishLaserTrail(this.info.sessionId),this.transition("idle")}onExit(){this.info&&this.editor.finishLaserTrail(this.info.sessionId),this.info=null}},ZI=Xf(()=>ir(nr().laserTrailActiveSignal)?nm(QI,{}):null),QI=Xf(()=>{const e=nr(),t=ir(e.laserTrailSignal),n=ir(e.cameraZoomSignal),i=Math.max(n,1e-4),o=(()=>{const[e,t]=Jf(()=>Qu());return qf(()=>{if("undefined"==typeof window)return;let e=0;const n=i=>{t(i),e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(e)}},[]),e})(),r=Qf({sessionId:0,samples:[],sourceLength:0}),s=Math.max(o,Qu());let a,d=[];t&&(((e,t,n,i)=>{t.sessionId!==e.sessionId&&(e.sessionId=t.sessionId,e.samples=[],e.sourceLength=0);const o=t.points;if(eh(e,i),o.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),o.length===e.sourceLength)return;const r=e.sourceLength,s=o.length-r,a=e.samples[e.samples.length-1]?.time??i-dv*s;for(let d=r;d<o.length;d++){const t=o[d];Ju(e,{x:t.x,y:t.y},n,uh(a,i,(d-r+1)/s))}e.sourceLength=o.length,eh(e,i)})(r.current,t,i,s),d=function(e,t){const n=th(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),i=[e[0]];for(let o=1;o<e.length;o++)i.push(ch(i[i.length-1],e[o],n));return i})(n.length>nv?n.slice(-64):n,rv)}(r.current.samples,s),a=r.current.samples[r.current.samples.length-1]?.time);const l="ending"===t?.phase,c=0===d.length,u=l&&c?t.sessionId:null;if(qf(()=>{null!==u&&e.clearLaserTrail(u)},[e,u]),!t||c)return null;const h=l&&void 0!==a?hh(1-(s-a)/pv,0,1):1,p=(f=ov/i,0===(g=d).length||f<=0?null:1===g.length?gh(ih(g[0],f/2,av))??"":gh((e=>{if(0===e.length)return[];if(1===e.length)return ih(e[0].point,Math.max(e[0].radius,.01),av);const t=[],n=[];for(const a of e){const e=sh(a.direction);ph(t,dh(a.point,lh(e,a.radius))),ph(n,ah(a.point,lh(e,a.radius)))}const i=[];for(const a of t)ph(i,a);const o=e[e.length-1],r=sh(o.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const o=[];for(let r=1;r<sv;r++){const s=r/sv;o.push(ah(e,ah(lh(t,Math.sin(Math.PI*s)*i),lh(n,-Math.cos(Math.PI*s)*i))))}return o})({center:o.point,direction:o.direction,normal:r,radius:o.radius});for(const a of s)ph(i,a);for(let a=n.length-1;a>=0;a--)ph(i,n[a]);return i})(((e,t)=>{const n=(e=>{const t=[0];for(let n=1;n<e.length;n++)t.push(t[n-1]+oh(e[n-1],e[n]));return t})(e),i=Math.max(t,n[n.length-1]??0);return e.map((o,r)=>{const s=n[r]??0,a=hh(s/i,0,1);return{point:o,direction:nh(e,r),radius:t/2*a,runningLength:s}})})(g,f))));var g,f;return p?im("g",{"data-ui":"laser-trail-overlay",style:{opacity:h},children:[nm("path",{"data-ui":"laser-trail-glow",d:p,fill:ev,style:{filter:`blur(${tv/i}px)`}}),nm("path",{"data-ui":"laser-trail-beam",d:p,fill:JI})]}):null}),JI="rgb(255, 38, 38)",ev="rgba(255, 48, 48, 0.55)",tv=4,nv=64,iv=1,ov=12,rv=.32,sv=8,av=13,dv=16,lv=8,cv=600,uv=300,hv=1400,pv=400,gv=bo({name:"laser",createFeature:()=>({id:"land.laser.bundle",editorRuntimePlugins:[{id:"land.laser",toolbarContributions:[{id:"laser.tool-toolbar",surface:"tool",placement:"chrome",order:55,actionIds:[YS],getGroups:e=>[{id:"laser.tools",items:[{kind:"button",id:"laser.tool.laser",actionId:YS,value:"laser",label:"Laser",shortcut:e.editor.shortcuts.getToolShortcutLabel("laser"),icon:"wand",dataUi:"laser-tool-button"}]}]}],setup(e){e.tools.register("laser",e=>new VI(e),{shortcut:"l"})}}],canvasRenderPlugins:[{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",layer:"below-host",component:ZI}]}],shapeTypes:[]})}),fv="path.node",mv="path.control",Sv=new WeakMap,yv=["nonzero","evenodd"],bv=["corner","smooth","symmetric"],xv=1e-6,Iv=1/3,vv=Math.PI/8,wv=new WeakMap,Pv=new WeakMap,kv="land.path.draftSubpathId",Cv="land.path.previewNodeId",Tv="var(--land-selection, #2563eb)",Ev=gm((e,t)=>{var n,i;n=e,i=function(){function e(e,t){return e>t?1:e<t?-1:0}function t(e,t,n){for(var i=new c(null,null),o=i,r=i;;){var s=n(e,t.key);if(s<0){if(null===t.left)break;if(n(e,t.left.key)<0&&(t.left=(a=t.left).right,a.right=t,null===(t=a).left))break;r.left=t,r=t,t=t.left}else{if(!(s>0))break;if(null===t.right)break;var a;if(n(e,t.right.key)>0&&(t.right=(a=t.right).left,a.left=t,null===(t=a).right))break;o.right=t,o=t,t=t.right}}return o.right=t.left,r.left=t.right,t.left=i.right,t.right=i.left,t}function n(e,n,i,o){var r=new c(e,n);if(null===i)return r.left=r.right=null,r;var s=o(e,(i=t(e,i,o)).key);return s<0?(r.left=i.left,r.right=i,i.left=null):s>=0&&(r.right=i.right,r.left=i,i.right=null),r}function i(e,n,i){var o=null,r=null;if(n){var s=i((n=t(e,n,i)).key,e);0===s?(o=n.left,r=n.right):s<0?(r=n.right,n.right=null,o=n):(o=n.left,n.left=null,r=n)}return{left:o,right:r}}function o(e,t,n,i,r){if(e){i(t+(n?"└── ":"├── ")+r(e)+"\n");var s=t+(n?" ":"│ ");e.left&&o(e.left,s,!1,i,r),e.right&&o(e.right,s,!0,i,r)}}function r(e,t,n,i){var o=i-n;if(o>0){var s=n+Math.floor(o/2),a=new c(e[s],t[s]);return a.left=r(e,t,n,s),a.right=r(e,t,s+1,i),a}return null}function s(e,t,n){var i=n-t;if(i>0){var o=t+Math.floor(i/2),r=s(e,t,o),a=e.head;return a.left=r,e.head=e.head.next,a.right=s(e,o+1,n),a}return null}function a(e,t,n,i,o){if(!(n>=i)){for(var r=e[n+i>>1],s=n-1,d=i+1;;){do{s++}while(o(e[s],r)<0);do{d--}while(o(e[d],r)>0);if(s>=d)break;var l=e[s];e[s]=e[d],e[d]=l,l=t[s],t[s]=t[d],t[d]=l}a(e,t,n,d,o),a(e,t,d+1,i,o)}}function d(e,t,n,i,o){let r,s,a,d,l=t[0],c=i[0],u=0,h=0;c>l==c>-l?(r=l,l=t[++u]):(r=c,c=i[++h]);let p=0;if(u<e&&h<n)for(c>l==c>-l?(s=l+r,a=r-(s-l),l=t[++u]):(s=c+r,a=r-(s-c),c=i[++h]),r=s,0!==a&&(o[p++]=a);u<e&&h<n;)c>l==c>-l?(s=r+l,d=s-r,a=r-(s-d)+(l-d),l=t[++u]):(s=r+c,d=s-r,a=r-(s-d)+(c-d),c=i[++h]),r=s,0!==a&&(o[p++]=a);for(;u<e;)s=r+l,d=s-r,a=r-(s-d)+(l-d),l=t[++u],r=s,0!==a&&(o[p++]=a);for(;h<n;)s=r+c,d=s-r,a=r-(s-d)+(c-d),c=i[++h],r=s,0!==a&&(o[p++]=a);return 0===r&&0!==p||(o[p++]=r),p}function l(e){return new Float64Array(e)}var c=function(e,t){this.next=null,this.key=e,this.data=t,this.left=null,this.right=null},u=function(){function d(t){void 0===t&&(t=e),this._root=null,this._size=0,this._comparator=t}return d.prototype.insert=function(e,t){return this._size++,this._root=n(e,t,this._root,this._comparator)},d.prototype.add=function(e,n){var i=new c(e,n);null===this._root&&(i.left=i.right=null,this._size++,this._root=i);var o=this._comparator,r=t(e,this._root,o),s=o(e,r.key);return 0===s?this._root=r:(s<0?(i.left=r.left,i.right=r,r.left=null):s>0&&(i.right=r.right,i.left=r,r.right=null),this._size++,this._root=i),this._root},d.prototype.remove=function(e){this._root=this._remove(e,this._root,this._comparator)},d.prototype._remove=function(e,n,i){var o;return null===n?null:0===i(e,(n=t(e,n,i)).key)?(null===n.left?o=n.right:(o=t(e,n.left,i)).right=n.right,this._size--,o):n},d.prototype.pop=function(){var e=this._root;if(e){for(;e.left;)e=e.left;return this._root=t(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null},d.prototype.findStatic=function(e){for(var t=this._root,n=this._comparator;t;){var i=n(e,t.key);if(0===i)return t;t=i<0?t.left:t.right}return null},d.prototype.find=function(e){return this._root&&(this._root=t(e,this._root,this._comparator),0!==this._comparator(e,this._root.key))?null:this._root},d.prototype.contains=function(e){for(var t=this._root,n=this._comparator;t;){var i=n(e,t.key);if(0===i)return!0;t=i<0?t.left:t.right}return!1},d.prototype.forEach=function(e,t){for(var n=this._root,i=[],o=!1;!o;)null!==n?(i.push(n),n=n.left):0!==i.length?(n=i.pop(),e.call(t,n),n=n.right):o=!0;return this},d.prototype.range=function(e,t,n,i){for(var o=[],r=this._comparator,s=this._root;0!==o.length||s;)if(s)o.push(s),s=s.left;else{if(r((s=o.pop()).key,t)>0)break;if(r(s.key,e)>=0&&n.call(i,s))return this;s=s.right}return this},d.prototype.keys=function(){var e=[];return this.forEach(t=>e.push(t.key)),e},d.prototype.values=function(){var e=[];return this.forEach(t=>e.push(t.data)),e},d.prototype.min=function(){return this._root?this.minNode(this._root).key:null},d.prototype.max=function(){return this._root?this.maxNode(this._root).key:null},d.prototype.minNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.left;)e=e.left;return e},d.prototype.maxNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.right;)e=e.right;return e},d.prototype.at=function(e){for(var t=this._root,n=!1,i=0,o=[];!n;)if(t)o.push(t),t=t.left;else if(o.length>0){if(t=o.pop(),i===e)return t;i++,t=t.right}else n=!0;return null},d.prototype.next=function(e){var t=this._root,n=null;if(e.right){for(n=e.right;n.left;)n=n.left;return n}for(var i=this._comparator;t;){var o=i(e.key,t.key);if(0===o)break;o<0?(n=t,t=t.left):t=t.right}return n},d.prototype.prev=function(e){var t=this._root,n=null;if(null!==e.left){for(n=e.left;n.right;)n=n.right;return n}for(var i=this._comparator;t;){var o=i(e.key,t.key);if(0===o)break;o<0?t=t.left:(n=t,t=t.right)}return n},d.prototype.clear=function(){return this._root=null,this._size=0,this},d.prototype.toList=function(){return(()=>{for(var e=this._root,t=[],n=!1,i=new c(null,null),o=i;!n;)e?(t.push(e),e=e.left):t.length>0?e=(e=o=o.next=t.pop()).right:n=!0;return o.next=null,i.next})()},d.prototype.load=function(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=!1);var i=e.length,o=this._comparator;if(n&&a(e,t,0,i-1,o),null===this._root)this._root=r(e,t,0,i),this._size=i;else{var d=((e,t,n)=>{for(var i=new c(null,null),o=i,r=e,s=t;null!==r&&null!==s;)n(r.key,s.key)<0?(o.next=r,r=r.next):(o.next=s,s=s.next),o=o.next;return null!==r?o.next=r:null!==s&&(o.next=s),i.next})(this.toList(),((e,t)=>{for(var n=new c(null,null),i=n,o=0;o<e.length;o++)i=i.next=new c(e[o],t[o]);return i.next=null,n.next})(e,t),o);this._root=s({head:d},0,i=this._size+i)}return this},d.prototype.isEmpty=function(){return null===this._root},Object.defineProperty(d.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(d.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),d.prototype.toString=function(e){void 0===e&&(e=e=>String(e.key));var t=[];return o(this._root,"",!0,e=>t.push(e),e),t.join("")},d.prototype.update=function(e,o,r){var s=this._comparator,a=i(e,this._root,s),d=a.left,l=a.right;s(e,o)<0?l=n(o,r,l,s):d=n(o,r,d,s),this._root=((e,n,i)=>null===n?e:(null===e||((n=t(e.key,n,i)).left=e),n))(d,l,s)},d.prototype.split=function(e){return i(e,this._root,this._comparator)},d.prototype[Symbol.iterator]=function(){var e,t,n;return function(e,t){function n(n){return s=>(n=>{if(i)throw new TypeError("Generator is already executing.");for(;a;)try{if(i=1,o&&(r=2&n[0]?o.return:n[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,n[1])).done)return r;switch(o=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,o=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==n[0]&&2!==n[0])){a=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){a.label=n[1];break}if(6===n[0]&&a.label<r[1]){a.label=r[1],r=n;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(n);break}r[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}catch(s){n=[6,s],o=0}finally{i=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}})([n,s])}var i,o,r,s,a={label:0,sent:()=>{if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s}(this,function(i){switch(i.label){case 0:e=this._root,t=[],n=!1,i.label=1;case 1:return n?[3,6]:null===e?[3,2]:(t.push(e),e=e.left,[3,5]);case 2:return 0===t.length?[3,4]:[4,e=t.pop()];case 3:return i.sent(),e=e.right,[3,5];case 4:n=!0,i.label=5;case 5:return[3,1];case 6:return[2]}})},d}();const h=(e,t)=>e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y,p=(e,t)=>t.ur.x<e.ll.x||e.ur.x<t.ll.x||t.ur.y<e.ll.y||e.ur.y<t.ll.y?null:{ll:{x:e.ll.x<t.ll.x?t.ll.x:e.ll.x,y:e.ll.y<t.ll.y?t.ll.y:e.ll.y},ur:{x:e.ur.x<t.ur.x?e.ur.x:t.ur.x,y:e.ur.y<t.ur.y?e.ur.y:t.ur.y}};let g=Number.EPSILON;void 0===g&&(g=Math.pow(2,-52));const f=g*g,m=(e,t)=>{if(-g<e&&e<g&&-g<t&&t<g)return 0;const n=e-t;return n*n<f*e*t?0:e<t?-1:1};class S{constructor(){this.tree=new u,this.round(0)}round(e){const t=this.tree.add(e),n=this.tree.prev(t);if(null!==n&&0===m(t.key,n.key))return this.tree.remove(e),n.key;const i=this.tree.next(t);return null!==i&&0===m(t.key,i.key)?(this.tree.remove(e),i.key):e}}const y=new class{constructor(){this.reset()}reset(){this.xRounder=new S,this.yRounder=new S}round(e,t){return{x:this.xRounder.round(e),y:this.yRounder.round(t)}}},b=134217729,x=l(4),I=l(8),v=l(12),w=l(16),P=l(4),k=(e,t)=>e.x*t.y-e.y*t.x,C=(e,t)=>e.x*t.x+e.y*t.y,T=(e,t,n)=>{const i=function(e,t,n,i,o,r){const s=(t-r)*(n-o),a=(e-o)*(i-r),l=s-a,c=Math.abs(s+a);return Math.abs(l)>=33306690738754716e-32*c?l:-((e,t,n,i,o,r,s)=>{let a,l,c,u,h,p,g,f,m,S,y,k,C,T,E,B,M,R;const A=e-o,L=n-o,F=t-r,$=i-r;T=A*$,p=b*A,g=p-(p-A),f=A-g,p=b*$,m=p-(p-$),S=$-m,E=f*S-(T-g*m-f*m-g*S),B=F*L,p=b*F,g=p-(p-F),f=F-g,p=b*L,m=p-(p-L),S=L-m,M=f*S-(B-g*m-f*m-g*S),y=E-M,h=E-y,x[0]=E-(y+h)+(h-M),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-B,h=C-y,x[1]=C-(y+h)+(h-B),R=k+y,h=R-k,x[2]=k-(R-h)+(y-h),x[3]=R;let U=((e,t)=>{let n=t[0];for(let i=1;i<4;i++)n+=t[i];return n})(0,x),D=22204460492503146e-32*s;if(U>=D||-U>=D)return U;if(h=e-A,a=e-(A+h)+(h-o),h=n-L,c=n-(L+h)+(h-o),h=t-F,l=t-(F+h)+(h-r),h=i-$,u=i-($+h)+(h-r),0===a&&0===l&&0===c&&0===u)return U;if(D=11093356479670487e-47*s+33306690738754706e-32*Math.abs(U),U+=A*u+$*a-(F*c+L*l),U>=D||-U>=D)return U;T=a*$,p=b*a,g=p-(p-a),f=a-g,p=b*$,m=p-(p-$),S=$-m,E=f*S-(T-g*m-f*m-g*S),B=l*L,p=b*l,g=p-(p-l),f=l-g,p=b*L,m=p-(p-L),S=L-m,M=f*S-(B-g*m-f*m-g*S),y=E-M,h=E-y,P[0]=E-(y+h)+(h-M),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-B,h=C-y,P[1]=C-(y+h)+(h-B),R=k+y,h=R-k,P[2]=k-(R-h)+(y-h),P[3]=R;const z=d(4,x,4,P,I);T=A*u,p=b*A,g=p-(p-A),f=A-g,p=b*u,m=p-(p-u),S=u-m,E=f*S-(T-g*m-f*m-g*S),B=F*c,p=b*F,g=p-(p-F),f=F-g,p=b*c,m=p-(p-c),S=c-m,M=f*S-(B-g*m-f*m-g*S),y=E-M,h=E-y,P[0]=E-(y+h)+(h-M),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-B,h=C-y,P[1]=C-(y+h)+(h-B),R=k+y,h=R-k,P[2]=k-(R-h)+(y-h),P[3]=R;const _=d(z,I,4,P,v);return T=a*u,p=b*a,g=p-(p-a),f=a-g,p=b*u,m=p-(p-u),S=u-m,E=f*S-(T-g*m-f*m-g*S),B=l*c,p=b*l,g=p-(p-l),f=l-g,p=b*c,m=p-(p-c),S=c-m,M=f*S-(B-g*m-f*m-g*S),y=E-M,h=E-y,P[0]=E-(y+h)+(h-M),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-B,h=C-y,P[1]=C-(y+h)+(h-B),R=k+y,h=R-k,P[2]=k-(R-h)+(y-h),P[3]=R,w[d(_,v,4,P,w)-1]})(e,t,n,i,o,r,c)}(e.x,e.y,t.x,t.y,n.x,n.y);return i>0?-1:i<0?1:0},E=e=>Math.sqrt(C(e,e)),B=(e,t,n)=>{const i={x:t.x-e.x,y:t.y-e.y},o={x:n.x-e.x,y:n.y-e.y};return k(o,i)/E(o)/E(i)},M=(e,t,n)=>{const i={x:t.x-e.x,y:t.y-e.y},o={x:n.x-e.x,y:n.y-e.y};return C(o,i)/E(o)/E(i)},R=(e,t,n)=>0===t.y?null:{x:e.x+t.x/t.y*(n-e.y),y:n},A=(e,t,n)=>0===t.x?null:{x:n,y:e.y+t.y/t.x*(n-e.x)};class L{static compare(e,t){const n=L.comparePoints(e.point,t.point);return 0!==n?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:$.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x<t.x?-1:e.x>t.x?1:e.y<t.y?-1:e.y>t.y?1:0}constructor(e,t){void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,i=t.length;n<i;n++){const e=t[n];this.point.events.push(e),e.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let t=0;t<e;t++){const n=this.point.events[t];if(void 0===n.segment.consumedBy)for(let i=t+1;i<e;i++){const e=this.point.events[i];void 0===e.consumedBy&&n.otherSE.point.events===e.otherSE.point.events&&n.segment.consume(e.segment)}}}getAvailableLinkedEvents(){const e=[];for(let t=0,n=this.point.events.length;t<n;t++){const n=this.point.events[t];n!==this&&!n.segment.ringOut&&n.segment.isInResult()&&e.push(n)}return e}getLeftmostComparator(e){const t=new Map,n=n=>{const i=n.otherSE;t.set(n,{sine:B(this.point,e.point,i.point),cosine:M(this.point,e.point,i.point)})};return(e,i)=>{t.has(e)||n(e),t.has(i)||n(i);const{sine:o,cosine:r}=t.get(e),{sine:s,cosine:a}=t.get(i);return o>=0&&s>=0?r<a?1:r>a?-1:0:o<0&&s<0?r<a?-1:r>a?1:0:s<o?-1:s>o?1:0}}}let F=0;class ${static compare(e,t){const n=e.leftSE.point.x,i=t.leftSE.point.x,o=e.rightSE.point.x,r=t.rightSE.point.x;if(r<n)return 1;if(o<i)return-1;const s=e.leftSE.point.y,a=t.leftSE.point.y,d=e.rightSE.point.y,l=t.rightSE.point.y;if(n<i){if(a<s&&a<d)return 1;if(a>s&&a>d)return-1;const n=e.comparePoint(t.leftSE.point);if(n<0)return 1;if(n>0)return-1;const i=t.comparePoint(e.rightSE.point);return 0!==i?i:-1}if(n>i){if(s<a&&s<l)return-1;if(s>a&&s>l)return 1;const n=t.comparePoint(e.leftSE.point);if(0!==n)return n;const i=e.comparePoint(t.rightSE.point);return i<0?1:i>0?-1:1}if(s<a)return-1;if(s>a)return 1;if(o<r){const n=t.comparePoint(e.rightSE.point);if(0!==n)return n}if(o>r){const n=e.comparePoint(t.rightSE.point);if(n<0)return 1;if(n>0)return-1}if(o!==r){const e=d-s,t=o-n,c=l-a,u=r-i;if(e>t&&c<u)return 1;if(e<t&&c>u)return-1}return o>r?1:o<r||d<l?-1:d>l?1:e.id<t.id?-1:e.id>t.id?1:0}constructor(e,t,n,i){this.id=++F,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=n,this.windings=i}static fromRing(e,t,n){let i,o,r;const s=L.comparePoints(e,t);if(s<0)i=e,o=t,r=1;else{if(!(s>0))throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);i=t,o=e,r=-1}return new $(new L(i,!0),new L(o,!1),[n],[r])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<t?e:t},ur:{x:this.rightSE.point.x,y:e>t?e:t}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const t=this.leftSE.point,n=this.rightSE.point,i=this.vector();if(t.x===n.x)return e.x===t.x?0:e.x<t.x?1:-1;if(e.x===t.x+(e.y-t.y)/i.y*i.x)return 0;const o=t.y+(e.x-t.x)/i.x*i.y;return e.y===o?0:e.y<o?-1:1}getIntersection(e){const t=this.bbox(),n=e.bbox(),i=p(t,n);if(null===i)return null;const o=this.leftSE.point,r=this.rightSE.point,s=e.leftSE.point,a=e.rightSE.point,d=h(t,s)&&0===this.comparePoint(s),l=h(n,o)&&0===e.comparePoint(o),c=h(t,a)&&0===this.comparePoint(a),u=h(n,r)&&0===e.comparePoint(r);if(l&&d)return u&&!c?r:!u&&c?a:null;if(l)return c&&o.x===a.x&&o.y===a.y?null:o;if(d)return u&&r.x===s.x&&r.y===s.y?null:s;if(u&&c)return null;if(u)return r;if(c)return a;const g=((e,t,n,i)=>{if(0===t.x)return A(n,i,e.x);if(0===i.x)return A(e,t,n.x);if(0===t.y)return R(n,i,e.y);if(0===i.y)return R(e,t,n.y);const o=k(t,i);if(0==o)return null;const r={x:n.x-e.x,y:n.y-e.y},s=k(r,t)/o,a=k(r,i)/o;return{x:(e.x+a*t.x+(n.x+s*i.x))/2,y:(e.y+a*t.y+(n.y+s*i.y))/2}})(o,this.vector(),s,e.vector());return null===g?null:h(i,g)?y.round(g.x,g.y):null}split(e){const t=[],n=void 0!==e.events,i=new L(e,!0),o=new L(e,!1),r=this.rightSE;this.replaceRightSE(o),t.push(o),t.push(i);const s=new $(i,r,this.rings.slice(),this.windings.slice());return L.comparePoints(s.leftSE.point,s.rightSE.point)>0&&s.swapEvents(),L.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(i.checkForConsuming(),o.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t<n;t++)this.windings[t]*=-1}consume(e){let t=this,n=e;for(;t.consumedBy;)t=t.consumedBy;for(;n.consumedBy;)n=n.consumedBy;const i=$.compare(t,n);if(0!==i){if(i>0){const e=t;t=n,n=e}if(t.prev===n){const e=t;t=n,n=e}for(let e=0,i=n.rings.length;e<i;e++){const i=n.rings[e],o=n.windings[e],r=t.rings.indexOf(i);-1===r?(t.rings.push(i),t.windings.push(o)):t.windings[r]+=o}n.rings=null,n.windings=null,n.consumedBy=t,n.leftSE.consumedBy=t.leftSE,n.rightSE.consumedBy=t.rightSE}}prevInResult(){return void 0!==this._prevInResult||(this._prevInResult=this.prev?this.prev.isInResult()?this.prev:this.prev.prevInResult():null),this._prevInResult}beforeState(){return void 0!==this._beforeState||(this._beforeState=this.prev?(this.prev.consumedBy||this.prev).afterState():{rings:[],windings:[],multiPolys:[]}),this._beforeState}afterState(){if(void 0!==this._afterState)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const t=this._afterState.rings,n=this._afterState.windings,i=this._afterState.multiPolys;for(let s=0,a=this.rings.length;s<a;s++){const e=this.rings[s],i=this.windings[s],o=t.indexOf(e);-1===o?(t.push(e),n.push(i)):n[o]+=i}const o=[],r=[];for(let s=0,a=t.length;s<a;s++){if(0===n[s])continue;const e=t[s],i=e.poly;if(-1===r.indexOf(i))if(e.isExterior)o.push(i);else{-1===r.indexOf(i)&&r.push(i);const t=o.indexOf(e.poly);-1!==t&&o.splice(t,1)}}for(let s=0,a=o.length;s<a;s++){const e=o[s].multiPoly;-1===i.indexOf(e)&&i.push(e)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(void 0!==this._isInResult)return this._isInResult;const e=this.beforeState().multiPolys,t=this.afterState().multiPolys;switch(X.type){case"union":this._isInResult=0===e.length!=(0===t.length);break;case"intersection":{let n,i;e.length<t.length?(n=e.length,i=t.length):(n=t.length,i=e.length),this._isInResult=i===X.numMultiPolys&&n<i;break}case"xor":{const n=Math.abs(e.length-t.length);this._isInResult=n%2==1;break}case"difference":{const n=e=>1===e.length&&e[0].isSubject;this._isInResult=n(e)!==n(t);break}default:throw new Error(`Unrecognized operation type found ${X.type}`)}return this._isInResult}}class U{constructor(e,t,n){if(!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=n,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=y.round(e[0][0],e[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let r=1,s=e.length;r<s;r++){if("number"!=typeof e[r][0]||"number"!=typeof e[r][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let t=y.round(e[r][0],e[r][1]);t.x===o.x&&t.y===o.y||(this.segments.push($.fromRing(o,t,this)),t.x<this.bbox.ll.x&&(this.bbox.ll.x=t.x),t.y<this.bbox.ll.y&&(this.bbox.ll.y=t.y),t.x>this.bbox.ur.x&&(this.bbox.ur.x=t.x),t.y>this.bbox.ur.y&&(this.bbox.ur.y=t.y),o=t)}i.x===o.x&&i.y===o.y||this.segments.push($.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let t=0,n=this.segments.length;t<n;t++){const n=this.segments[t];e.push(n.leftSE),e.push(n.rightSE)}return e}}class D{constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new U(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let n=1,i=e.length;n<i;n++){const t=new U(e[n],this,!1);t.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=t.bbox.ur.y),this.interiorRings.push(t)}this.multiPoly=t}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let t=0,n=this.interiorRings.length;t<n;t++){const n=this.interiorRings[t].getSweepEvents();for(let t=0,i=n.length;t<i;t++)e.push(n[t])}return e}}class z{constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{"number"==typeof e[0][0][0]&&(e=[e])}catch(n){}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let i=0,o=e.length;i<o;i++){const t=new D(e[i],this);t.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=t.bbox.ur.y),this.polys.push(t)}this.isSubject=t}getSweepEvents(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const n=this.polys[t].getSweepEvents();for(let t=0,i=n.length;t<i;t++)e.push(n[t])}return e}}class _{static factory(e){const t=[];for(let n=0,i=e.length;n<i;n++){const i=e[n];if(!i.isInResult()||i.ringOut)continue;let o=null,r=i.leftSE,s=i.rightSE;const a=[r],d=r.point,l=[];for(;o=r,r=s,a.push(r),r.point!==d;)for(;;){const e=r.getAvailableLinkedEvents();if(0===e.length){const e=a[0].point,t=a[a.length-1].point;throw new Error(`Unable to complete output ring starting at [${e.x}, ${e.y}]. Last matching segment found ends at [${t.x}, ${t.y}].`)}if(1===e.length){s=e[0].otherSE;break}let n=null;for(let t=0,o=l.length;t<o;t++)if(l[t].point===r.point){n=t;break}if(null!==n){const e=l.splice(n)[0],i=a.splice(e.index);i.unshift(i[0].otherSE),t.push(new _(i.reverse()));continue}l.push({index:a.length,point:r.point});const i=r.getLeftmostComparator(o);s=e.sort(i)[0].otherSE;break}t.push(new _(a))}return t}constructor(e){this.events=e;for(let t=0,n=e.length;t<n;t++)e[t].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const t=[e];for(let s=1,a=this.events.length-1;s<a;s++){const n=this.events[s].point;0!==T(n,e,this.events[s+1].point)&&(t.push(n),e=n)}if(1===t.length)return null;0===T(t[0],e,t[1])&&t.shift(),t.push(t[0]);const n=this.isExteriorRing()?1:-1,i=this.isExteriorRing()?0:t.length-1,o=this.isExteriorRing()?t.length:-1,r=[];for(let s=i;s!=o;s+=n)r.push([t[s].x,t[s].y]);return r}isExteriorRing(){if(void 0===this._isExteriorRing){const e=this.enclosingRing();this._isExteriorRing=!e||!e.isExteriorRing()}return this._isExteriorRing}enclosingRing(){return void 0===this._enclosingRing&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const t=this.events[i];L.compare(e,t)>0&&(e=t)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return n.ringOut.enclosingRing()!==t.ringOut?t.ringOut:t.ringOut.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}}class H{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(null===e[0])return null;for(let t=0,n=this.interiorRings.length;t<n;t++){const n=this.interiorRings[t].getGeom();null!==n&&e.push(n)}return e}}class N{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const n=this.polys[t].getGeom();null!==n&&e.push(n)}return e}_composePolys(e){const t=[];for(let n=0,i=e.length;n<i;n++){const i=e[n];if(!i.poly)if(i.isExteriorRing())t.push(new H(i));else{const e=i.enclosingRing();e.poly||t.push(new H(e)),e.poly.addInterior(i)}}return t}}class O{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.compare;this.queue=e,this.tree=new u(t),this.segments=[]}process(e){const t=e.segment,n=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(t),n;const i=e.isLeft?this.tree.add(t):this.tree.find(t);if(!i)throw new Error(`Unable to find segment #${t.id} [${t.leftSE.point.x}, ${t.leftSE.point.y}] -> [${t.rightSE.point.x}, ${t.rightSE.point.y}] in SweepLine tree.`);let o,r,s=i,a=i;for(;void 0===o;)s=this.tree.prev(s),null===s?o=null:void 0===s.key.consumedBy&&(o=s.key);for(;void 0===r;)a=this.tree.next(a),null===a?r=null:void 0===a.key.consumedBy&&(r=a.key);if(e.isLeft){let i=null;if(o){const e=o.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(i=e),!o.isAnEndpoint(e))){const t=this._splitSafely(o,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}}let s=null;if(r){const e=r.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(s=e),!r.isAnEndpoint(e))){const t=this._splitSafely(r,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}}if(null!==i||null!==s){let e=null;e=null===i?s:null===s||L.comparePoints(i,s)<=0?i:s,this.queue.remove(t.rightSE),n.push(t.rightSE);const o=t.split(e);for(let t=0,i=o.length;t<i;t++)n.push(o[t])}n.length>0?(this.tree.remove(t),n.push(e)):(this.segments.push(t),t.prev=o)}else{if(o&&r){const e=o.getIntersection(r);if(null!==e){if(!o.isAnEndpoint(e)){const t=this._splitSafely(o,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}if(!r.isAnEndpoint(e)){const t=this._splitSafely(r,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}}}this.tree.remove(t)}return n}_splitSafely(e,t){this.tree.remove(e);const n=e.rightSE;this.queue.remove(n);const i=e.split(t);return i.push(n),void 0===e.consumedBy&&this.tree.add(e),i}}const W="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,Y="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6,X=new class{run(e,t,n){X.type=e,y.reset();const i=[new z(t,!0)];for(let d=0,l=n.length;d<l;d++)i.push(new z(n[d],!1));if(X.numMultiPolys=i.length,"difference"===X.type){const e=i[0];let t=1;for(;t<i.length;)null!==p(i[t].bbox,e.bbox)?t++:i.splice(t,1)}if("intersection"===X.type)for(let d=0,l=i.length;d<l;d++){const e=i[d];for(let t=d+1,n=i.length;t<n;t++)if(null===p(e.bbox,i[t].bbox))return[]}const o=new u(L.compare);for(let d=0,l=i.length;d<l;d++){const e=i[d].getSweepEvents();for(let t=0,n=e.length;t<n;t++)if(o.insert(e[t]),o.size>W)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const r=new O(o);let s=o.size,a=o.pop();for(;a;){const e=a.key;if(o.size===s){const t=e.segment;throw new Error(`Unable to pop() ${e.isLeft?"left":"right"} SweepEvent [${e.point.x}, ${e.point.y}] from segment #${t.id} [${t.leftSE.point.x}, ${t.leftSE.point.y}] -> [${t.rightSE.point.x}, ${t.rightSE.point.y}] from queue.`)}if(o.size>W)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(r.segments.length>Y)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const t=r.process(e);for(let n=0,i=t.length;n<i;n++){const e=t[n];void 0===e.consumedBy&&o.insert(e)}s=o.size,a=o.pop()}return y.reset(),new N(_.factory(r.segments)).getGeom()}};return{union:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return X.run("union",e,n)},intersection:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return X.run("intersection",e,n)},xor:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return X.run("xor",e,n)},difference:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return X.run("difference",e,n)}}},"object"==typeof e&&void 0!==t?t.exports=i():"function"==typeof define&&define.amd?define(i):(n="undefined"!=typeof globalThis?globalThis:n||self).polygonClipping=i()})(),Bv=1,Mv=1,Rv="path.insert-node",Av=1,Lv=class extends SS{type="path";getDefaultProps(){return{subpaths:[{id:"subpath:default",closed:!1,nodes:[{id:"node:0",x:0,y:0,kind:"corner"},{id:"node:1",x:96,y:0,kind:"corner"}]}],fill:"transparent",stroke:y("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{subpaths:(i=Up(t.subpaths,n.subpaths),i.map(e=>({...e,nodes:e.nodes.filter(e=>Mh(e.x)&&Mh(e.y))})).filter(e=>e.nodes.length>0).map(Lh)),fill:P(t.fill,n.fill),stroke:P(t.stroke,n.stroke),strokeWidth:Math.max(1,Fp(t.strokeWidth,n.strokeWidth)),fillRule:wh(t.fillRule)?t.fillRule:n.fillRule};var i}getBounds(e){const t=Xh(e).localBounds;return new Pm(e.x+t.x,e.y+t.y,t.w,t.h)}getLocalBounds(e){return Xh(e).localBounds}getRenderBounds(e){return Xh(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}getSelectionResizeLocalBounds(e){return Xh(e).pointBounds}resizeSelectionBounds(e,t){const n=jh(e,this.getLocalToPageTransform(e)).map(e=>({...e,nodes:e.nodes.map(e=>zp(e,e=>((e,t)=>0===t.selectionRotation?e:wm.RotWith(e,t.selectionRotationCenter,-t.selectionRotation))(e,t)))})),i=qh(((e,t)=>{const n=Xh(e).pointBounds,i=0===n.w?1:t.w/Math.max(n.w,1e-6),o=0===n.h?1:t.h/Math.max(n.h,1e-6);return Vh(e.props.subpaths,e=>new wm(0===n.w?t.center.x:t.x+(e.x-n.x)*i,0===n.h?t.center.y:t.y+(e.y-n.y)*o))})({...e,x:0,y:0,rotation:0,scaleX:1,scaleY:1,props:{...e.props,subpaths:n}},t.selectionLocalBounds).map(e=>({...e,nodes:e.nodes.map(e=>zp(e,e=>((e,t)=>0===t.selectionRotation?e:wm.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(e,t)))})),e.props);return{id:e.id,x:i.x,y:i.y,rotation:0,scaleX:1,scaleY:1,props:{subpaths:i.subpaths}}}getPositionedOutlineVertices(e){return Xh(e).outlineVertices.map(t=>new wm(e.x+t.x,e.y+t.y))}getHandleSnapGeometry(e){return{points:e.props.subpaths.flatMap(e=>e.nodes.flatMap(e=>[{point:$h(e),kind:"custom"},...e.in?[{point:Uh(e),kind:"custom"}]:[],...e.out?[{point:Dh(e),kind:"custom"}]:[]])),outline:Xh(e).outlineVertices}}canReceiveTerminalBinding(e){return!0}canEdit(e){return!0}canUseSelectionFrameHandles(e,t){return t.editor.getShapeEditingSession()?.shapeId!==e.id}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const i=t.editor.getShapeEditingSession();if(!i||i.shapeId!==e.id)return n;const o=t.editor.computeShapeLocalToPageTransform(e);return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=[{kind:"custom",type:fv,id:(i=e.id,r=t.id,["node",i,r].map(encodeURIComponent).join("|")),point:o.applyToPoint($h(t)),cursor:"grab"}];var i,r;return t.in&&n.push({kind:"custom",type:mv,id:yh(e.id,t.id,"in"),point:o.applyToPoint(Uh(t)),cursor:"grab"}),t.out&&n.push({kind:"custom",type:mv,id:yh(e.id,t.id,"out"),point:o.applyToPoint(Dh(t)),cursor:"grab"}),n}))}}getSelectionOverlayInfo(e,t){const n=t.editor.getShapeEditingSession();return n&&n.shapeId===e.id?{usesSelectionPathOverlay:!0,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:Gh(e,t.editor.computeShapeLocalToPageTransform(e)),bindingSegments:[]}:{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,bindingSegments:[]}}hitTest(e,t,n){const i=new wm(t.x-e.x,t.y-e.y),o=Xh(e);return!T(e.props.fill)&&((e,t,n)=>{let i=0,o=0;for(const r of e)if(r.closed&&!(r.points.length<3))for(let e=0;e<r.points.length;e+=1){const n=r.points[e],s=r.points[(e+1)%r.points.length];n&&s&&(n.y<=t.y&&s.y>t.y||n.y>t.y&&s.y<=t.y)&&n.x+(t.y-n.y)/(s.y-n.y)*(s.x-n.x)>t.x&&(o+=1,i+=s.y>n.y?1:-1)}return"evenodd"===n?o%2==1:0!==i})(o.flattenedSubpaths,i,e.props.fillRule)||((e,t,n)=>{const i=n*n;for(const o of e)for(let e=1;e<o.points.length;e+=1){const n=o.points[e-1],r=o.points[e];if(n&&r&&Qh(t,n,r)<=i)return!0}return!1})(o.flattenedSubpaths,i,e.props.strokeWidth/2+6)}hitTestLineSegment(e,t){const n=new wm(t.positionedStart.x-e.x,t.positionedStart.y-e.y),i=new wm(t.positionedEnd.x-e.x,t.positionedEnd.y-e.y),o=t.margin+e.props.strokeWidth/2;return Xh(e).flattenedSubpaths.some(e=>((e,t,n,i)=>{const o=i*i;for(let r=1;r<n.length;r+=1){const i=n[r-1],s=n[r];if(i&&s&&(Dp(i,e,t)<=o||Dp(s,e,t)<=o||Dp(e,i,s)<=o||Dp(t,i,s)<=o))return!0}return!1})(n,i,e.points,o))}isWrappedByBrush(e,t){const n=t.pageOutlineVertices;return 0===n.length?!!t.pageBounds&&t.brushBounds.containsBox(t.pageBounds):n.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return t.isWrapping?this.isWrappedByBrush(e,t):t.pageBounds?.intersects(t.brushBounds)??!1}onEditEnd(e){if(e.props.subpaths.every(e=>e.nodes.length<2))return{deleteShapeIds:[e.id]}}},Fv="path.create",$v=1,Uv=1,Dv=class extends bS{draft=null;constructor(e){super(e,"path"),this.initial="idle",this.addChild(new zv(e,this)),this.addChild(new _v(e,this))}onEnter(){this.editor.clearSelectionTransients()}onExit(){this.draft&&(this.canFinishDraft()?this.finishDraft({switchToSelect:!1}):this.cancelDraft())}startOrExtend(e){if(!this.draft){this.editor.history.mark(Fv);const t=this.editor.getDefaultShapeProps("path"),n=`subpath:${Uv+=1}`,i=_p(),[o]=this.editor.commands.createShapes([{type:"path",x:e.x,y:e.y,meta:pp({},{subpathId:n,previewNodeId:null}),props:{...t,subpaths:[{id:n,closed:!1,nodes:[{id:i,x:0,y:0,kind:"corner"}]}]}}],{source:"user"});if(!o)throw new Error("Failed to create path shape");return this.editor.commands.setSelectedShapeIds([o.id],{source:"system"}),this.draft={shapeId:o.id,subpathId:n,lastNodeId:i,createdShape:!0,previewNodeId:null},{shapeId:o.id,subpathId:n,nodeId:i,originPagePoint:e.clone()}}const t=this.editor.getShape(this.draft.shapeId);if(!vh(t))return this.cancelDraft(),null;if(function(e,t,n,i,o){const r=((e,t,n)=>{const i=ep(t.props.subpaths,n)?.nodes[0];return i?e.computeShapeLocalToPageTransform(t).applyToPoint(new wm(i.x,i.y)):null})(e,t,n),s=ep(t.props.subpaths,n),a=s?.nodes.filter(e=>e.id!==i).length??0;return!(!r||!s||a<3)&&r.dist(o)<=10/e.getCurrentCamera().z}(this.editor,t,this.draft.subpathId,this.draft.previewNodeId,e)){const e=this.draft;return this.editor.commands.updateShapes([{id:t.id,meta:gp(t.meta),props:{subpaths:Np(t.props.subpaths,e).map(t=>t.id===e.subpathId?{...t,closed:!0}:t)}}],{source:"user"}),this.finishDraft(),null}const n=Hp(this.editor,t,e),i=this.draft.previewNodeId??_p(),o=t.props.subpaths.map(e=>e.id===this.draft?.subpathId?this.draft.previewNodeId?{...e,nodes:e.nodes.map(e=>e.id===this.draft?.previewNodeId?{id:i,x:n.x,y:n.y,kind:"corner"}:e)}:{...e,nodes:[...e.nodes,{id:i,x:n.x,y:n.y,kind:"corner"}]}:e);return this.editor.commands.updateShapes([{id:t.id,meta:pp(t.meta,{subpathId:this.draft.subpathId,previewNodeId:null}),props:{subpaths:o}}],{source:"user"}),this.draft={...this.draft,lastNodeId:i,previewNodeId:null},{shapeId:t.id,subpathId:this.draft.subpathId,nodeId:i,originPagePoint:e.clone()}}updateNodeDrag(e,t){const n=this.editor.getShape(e.shapeId);if(!vh(n))return;const i=Hp(this.editor,n,e.originPagePoint),o=Hp(this.editor,n,t),r=np(n.props.subpaths,e.subpathId,e.nodeId,e=>((e,t,n)=>{const i=n.sub(t);return i.len()<3?e:{...e,kind:"symmetric",in:{dx:-i.x,dy:-i.y},out:{dx:i.x,dy:i.y}}})(e,i,o));this.editor.commands.updateShapes([{id:n.id,meta:pp(n.meta,{subpathId:e.subpathId,previewNodeId:this.draft?.previewNodeId??null}),props:{subpaths:r}}],{source:"user"})}updatePreview(e){if(!this.draft)return;const t=this.editor.getShape(this.draft.shapeId);if(!vh(t)||Op(t,this.draft)<1)return;const n=Hp(this.editor,t,e),i=this.draft.previewNodeId??_p(),o=t.props.subpaths.map(e=>e.id!==this.draft?.subpathId?e:this.draft.previewNodeId?{...e,nodes:e.nodes.map(e=>e.id===this.draft?.previewNodeId?{id:i,x:n.x,y:n.y,kind:"corner"}:e)}:{...e,nodes:[...e.nodes,{id:i,x:n.x,y:n.y,kind:"corner"}]});this.editor.commands.updateShapes([{id:t.id,meta:pp(t.meta,{subpathId:this.draft.subpathId,previewNodeId:i}),props:{subpaths:o}}],{source:"user"}),this.draft={...this.draft,previewNodeId:i}}canFinishDraft(){if(!this.draft)return!1;const e=this.editor.getShape(this.draft.shapeId);return!!vh(e)&&Op(e,this.draft)>=2}finishDraft(e={}){if(!this.draft)return;const t=e.switchToSelect??!0,n=this.editor.getShape(this.draft.shapeId);if(vh(n)){const e=Np(n.props.subpaths,this.draft),t=qh(jh({...n,props:{...n.props,subpaths:e}},this.editor.computeShapeLocalToPageTransform(n)),n.props);this.editor.commands.updateShapes([{id:n.id,x:t.x,y:t.y,rotation:0,scaleX:1,scaleY:1,meta:gp(n.meta),props:{subpaths:t.subpaths}}],{source:"user"}),this.draft.createdShape&&G(this.editor,n.id,{source:"user"})}this.editor.history.squashToMark(Fv,"shape.create"),this.draft=null,t&&!this.editor.isToolLocked()&&this.editor.commands.setActiveTool("select",{source:"system"})}cancelDraft(){this.draft&&(this.editor.history.bailToMark(Fv),this.draft=null)}hasDraft(){return null!==this.draft}},zv=class extends bS{tool;constructor(e,t){super(e,"idle",t),this.tool=t}onPointerDown(e){if(0!==e.button)return;const t=this.tool.startOrExtend(e.pagePoint);t&&this.transition("dragging_node",t)}onPointerMove(e){this.tool.updatePreview(e.pagePoint)}onKeyDown(e){"Enter"===e.key&&this.tool.hasDraft()?this.tool.finishDraft():"Escape"===e.key&&this.tool.hasDraft()&&this.tool.cancelDraft()}},_v=class extends bS{tool;info=null;constructor(e,t){super(e,"dragging_node",t),this.tool=t}onEnter(e){this.info=e}onPointerMove(e){this.info&&this.tool.updateNodeDrag(this.info,e.pagePoint)}onPointerUp(e){this.info&&this.tool.updateNodeDrag(this.info,e.pagePoint),this.transition("idle")}onCancel(){this.tool.cancelDraft(),this.transition("idle")}onExit(){this.info=null}},Hv="path.edit",Nv="path.boolean.union",Ov="path.boolean.subtract",Wv="path.boolean.intersect",Yv="path.boolean.xor",Xv="path.node.delete",Kv="path.node.make-curve",Vv="path.node.remove-handles",qv=[{value:"transparent",label:"None",color:"transparent"},{value:y("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:y("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:y("fill-red"),label:"Red",color:"var(--land-shape-fill-red)"},{value:y("fill-white"),label:"White",color:"var(--land-shape-fill-white)"}],jv=[{value:y("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:y("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:y("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:y("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],Gv=[{value:1,label:"1"},{value:2,label:"2"},{value:3,label:"3"},{value:5,label:"5"},{value:8,label:"8"}],Zv=[{value:"nonzero",label:"Nonzero"},{value:"evenodd",label:"Even odd"}],Qv=class{type="path";toSvg(e,t){const n=Xh(e);return n.path?{tag:"path",attrs:{d:n.path,fill:"transparent"===e.props.fill?"none":t.resolveColor(e.props.fill),"fill-rule":e.props.fillRule,"clip-rule":e.props.fillRule,stroke:t.resolveColor(e.props.stroke),"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}:null}},Jv=[["geo",dI],["draw",gx],["arrow",Qb],["eraser",Lx],["laser",gv],["path",bo({name:"path",createFeature:()=>({id:"land.path.bundle",editorRuntimePlugins:[{id:"land.path",shapeCapabilities:[{type:"path",schemaProps:["subpaths","fill","stroke","strokeWidth","fillRule"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Path owns editable Bezier node geometry, multi-subpath fill rules, SVG export, and destructive polygon-clipping boolean materialization."]}],shapeUtils:[new Lv],shapeSvgExporters:[new Qv],interactionHandlers:[Lp()],canvasActions:[Yp("fill"),Yp("stroke"),Yp("strokeWidth"),{id:"path.set-fillRule",isVisible:e=>"path"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>(e=>{let t=null;for(const n of e)if(vh(n))if(null!==t){if(t!==n.props.fillRule)return null}else t=n.props.fillRule;return t})(e.selection.selectedShapes),run({context:e,value:t}){if(!wh(t))return;const n=e.selection.selectedShapes.filter(vh).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{fillRule:t}}));n.length>0&&e.editor.commands.updateShapes(n,{source:"user"})}},Xp("fill"),Xp("stroke"),Xp("strokeWidth"),{id:"path.default-fillRule",isVisible:e=>"path"===e.tool.activeToolId,getValue:e=>e.editor.getDefaultShapeProps("path").fillRule,run({context:e,value:t}){wh(t)&&e.editor.updateDefaultShapeProps("path",{fillRule:t})}},{id:Hv,isVisible:e=>1===e.selection.count&&"path"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return vh(t)&&!t.isLocked},run({context:e}){const[t]=e.selection.selectedShapes;vh(t)&&(dp(e.editor,null),e.editor.startEditingShape({shapeId:t.id,markId:"path.edit",entryMode:"focusEnd"},"user"))}},{id:Xv,isVisible:e=>!!ap(e.editor),isEnabled(e){const t=ap(e.editor);return!!t&&!t.shape.isLocked},run({context:e}){const t=ap(e.editor);if(!t||t.shape.isLocked)return;const n=sp(t.shape.props.subpaths,t.selection.subpathId,t.selection.nodeId);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"}),dp(e.editor,null)}},{id:Kv,isVisible:e=>!!ap(e.editor),isEnabled(e){const t=ap(e.editor);return!(!t||t.shape.isLocked||t.node.in||t.node.out)},run({context:e}){const t=ap(e.editor);if(!t||t.shape.isLocked)return;const n=ip(t.shape.props.subpaths,t.selection.subpathId,t.selection.nodeId);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"});const i=e.editor.getShape(t.shape.id);vh(i)&&lp(e.editor,i,t.selection.subpathId,t.selection.nodeId)}},{id:Vv,isVisible:e=>!!ap(e.editor),isEnabled(e){const t=ap(e.editor);return!(!t||t.shape.isLocked||!t.node.in&&!t.node.out)},run({context:e}){const t=ap(e.editor);if(!t||t.shape.isLocked)return;const n=op(t.shape.props.subpaths,t.selection.subpathId,t.selection.nodeId);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"});const i=e.editor.getShape(t.shape.id);vh(i)&&lp(e.editor,i,t.selection.subpathId,t.selection.nodeId)}},Kp("union"),Kp("subtract"),Kp("intersect"),Kp("xor")],toolbarContributions:[{id:"path.tool-toolbar",surface:"tool",placement:"chrome",order:47,actionIds:[YS],getGroups:e=>[{id:"path.tools",items:[{kind:"button",id:"path.tool.path",actionId:YS,value:"path",label:"Path",shortcut:e.editor.shortcuts.getToolShortcutLabel("path"),icon:"pen-tool",dataUi:"path-tool-button"}]}]},{id:"path.default-style.tool-toolbar",surface:"tool",order:48,actionIds:["path.default-fill","path.default-stroke","path.default-strokeWidth","path.default-fillRule"],when:e=>"path"===e.tool.activeToolId,getGroups:()=>Wp({fillActionId:"path.default-fill",strokeActionId:"path.default-stroke",strokeWidthActionId:"path.default-strokeWidth",fillRuleActionId:"path.default-fillRule",dataUiPrefix:"path-default"})},{id:"path.selection-toolbar",surface:"selection",order:22,actionIds:[Hv,"path.set-fill","path.set-stroke","path.set-strokeWidth","path.set-fillRule",Nv,Ov,Wv,Yv],when:e=>"path"===e.selection.commonShapeType,getGroups(e){const t=[{id:"path.edit",items:[{kind:"button",id:"path.edit",actionId:Hv,label:"Edit",icon:"square-pen",dataUi:"path-edit-button"}]},...Wp({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",fillRuleActionId:"path.set-fillRule",dataUiPrefix:"path"})];return Vp(e).length>=2&&t.push({id:"path.boolean",items:[{kind:"button",id:"path.boolean.union",actionId:Nv,label:"Union",icon:"group",dataUi:"path-boolean-union-button"},{kind:"button",id:"path.boolean.subtract",actionId:Ov,label:"Subtract",icon:"minus",dataUi:"path-boolean-subtract-button"},{kind:"button",id:"path.boolean.intersect",actionId:Wv,label:"Intersect",icon:"crop",dataUi:"path-boolean-intersect-button"},{kind:"button",id:"path.boolean.xor",actionId:Yv,label:"Exclude",icon:"ungroup",dataUi:"path-boolean-xor-button"}]}),t}},{id:"path.floating-selection-toolbar",surface:"selection",placement:"floating",order:22,actionIds:[Hv,Xv,Kv,Vv,"path.set-fill","path.set-stroke","path.set-strokeWidth","path.set-fillRule",Nv,Ov,Wv,Yv],when:e=>!("path"!==e.selection.commonShapeType||e.editor.getShapeEditingSession()&&!ap(e.editor)),getGroups(e){if(ap(e.editor))return[{id:"path.floating-node-edit",items:[{kind:"button",id:"path.floating-node.delete",actionId:Xv,label:"Delete node",shortcut:"⌫",icon:"remove-node",dataUi:"floating-path-node-delete-button"}]},{id:"path.floating-node-convert",items:[{kind:"button",id:"path.floating-node.remove-handles",actionId:Vv,label:"Corner point",shortcut:"X",icon:"to-corner",dataUi:"floating-path-node-remove-handles-button"},{kind:"button",id:"path.floating-node.make-curve",actionId:Kv,label:"Curve point",shortcut:"C",icon:"to-curve",dataUi:"floating-path-node-make-curve-button"}]}];const t=[{id:"path.floating-edit",items:[{kind:"button",id:"path.floating-edit",actionId:Hv,label:"Edit",icon:"square-pen",dataUi:"floating-path-edit-button"}]},...Wp({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",fillRuleActionId:"path.set-fillRule",dataUiPrefix:"floating-path"})];return Vp(e).length>=2&&t.push({id:"path.floating-boolean",items:[{kind:"button",id:"path.floating-boolean.union",actionId:Nv,label:"Union",icon:"group",dataUi:"floating-path-boolean-union-button"},{kind:"button",id:"path.floating-boolean.subtract",actionId:Ov,label:"Subtract",icon:"minus",dataUi:"floating-path-boolean-subtract-button"},{kind:"button",id:"path.floating-boolean.intersect",actionId:Wv,label:"Intersect",icon:"crop",dataUi:"floating-path-boolean-intersect-button"},{kind:"button",id:"path.floating-boolean.xor",actionId:Yv,label:"Exclude",icon:"ungroup",dataUi:"floating-path-boolean-xor-button"}]}),t}}],contextMenuContributions:[{id:"path.context-menu",target:"selection",order:38,actionIds:[Hv,Nv,Ov,Wv,Yv],when:e=>"path"===e.selection.commonShapeType,getSections(e){const t=[{kind:"command",id:"path.edit",actionId:Hv,label:"Edit path",icon:"square-pen",dataUi:"path-context-edit"}];return Vp(e).length>=2&&t.push({kind:"command",id:"path.boolean.union",actionId:Nv,label:"Union paths",icon:"group",dataUi:"path-context-boolean-union"},{kind:"command",id:"path.boolean.subtract",actionId:Ov,label:"Subtract paths",icon:"minus",dataUi:"path-context-boolean-subtract"},{kind:"command",id:"path.boolean.intersect",actionId:Wv,label:"Intersect paths",icon:"crop",dataUi:"path-context-boolean-intersect"},{kind:"command",id:"path.boolean.xor",actionId:Yv,label:"Exclude paths",icon:"ungroup",dataUi:"path-context-boolean-xor"}),[{id:"path.context",title:"Path",items:t}]}}],setup(e){e.tools.register("path",e=>new Dv(e),{shortcut:"b"})}}],canvasRenderPlugins:[{id:"land.path.react",canvasOverlays:[{id:"land.path.draft-overlay",component:fp,layer:"above-host",order:20},{id:"land.path.edit-insert-preview-overlay",component:Ph,layer:"above-host",order:21}],shapeRenderers:[{type:"path",component:xp}],selectionCustomHandleRenderers:[{type:fv,component:Ip},{type:mv,component:vp}]}],shapeTypes:["path"]})})],["image",KI],["text",_b],["frame",Wx],["group",uI]],ew=["select","hand","rectangle","ellipse","diamond","triangle","hexagon","star","arrow","draw","path","text","frame","eraser","laser"],tw=new Set(ew),nw=ew.map(e=>`"${e}"`).join(", "),iw=[],ow={readyRuntime:null,status:null},rw=new Set,sw="snapshots",aw="imageBlobs",dw=null,lw=class e{editor;static SAVE_DELAY_MS=200;getDocumentSnapshot;options;unsubscribe=null;saveTimeoutId=null;hasPendingSave=!1;isSaving=!1;saveAgainAfterCurrentSave=!1;constructor(e,{getDocumentSnapshot:t,options:n={}}={}){this.editor=e,this.getDocumentSnapshot=t??(()=>e.getDocumentSnapshot()),this.options=n}start(){this.unsubscribe||(this.unsubscribe=this.editor.listen(()=>{this.scheduleSave()}),document.addEventListener("visibilitychange",this.flushWhenHidden),window.addEventListener("pagehide",this.flushWhenPageIsLeaving),window.addEventListener("beforeunload",this.flushWhenPageIsLeaving))}stop(){this.flush(),this.unsubscribe?.(),this.unsubscribe=null,document.removeEventListener("visibilitychange",this.flushWhenHidden),window.removeEventListener("pagehide",this.flushWhenPageIsLeaving),window.removeEventListener("beforeunload",this.flushWhenPageIsLeaving)}flush(){this.hasPendingSave&&(this.cancelScheduledSave(),this.save())}save(){this.isSaving?this.saveAgainAfterCurrentSave=!0:(this.isSaving=!0,this.hasPendingSave=!1,this.saveAgainAfterCurrentSave=!1,Kg(this.editor,this.options,{documentSnapshot:this.getDocumentSnapshot()}).catch(e=>{console.warn("Could not persist canvas snapshot.",e)}).finally(()=>{this.isSaving=!1,(this.saveAgainAfterCurrentSave||this.hasPendingSave)&&this.save()}))}scheduleSave(){this.hasPendingSave=!0,null===this.saveTimeoutId&&(this.saveTimeoutId=window.setTimeout(()=>{this.saveTimeoutId=null,this.flush()},e.SAVE_DELAY_MS))}cancelScheduledSave(){null!==this.saveTimeoutId&&(window.clearTimeout(this.saveTimeoutId),this.saveTimeoutId=null)}flushWhenHidden=()=>{"hidden"===document.visibilityState&&this.flush()};flushWhenPageIsLeaving=()=>{this.flush()}},cw=Mg("canvas-kit.clipboard-service"),uw="system.clipboard.copy",hw="system.clipboard.cut",pw="system.clipboard.paste",gw="system.clipboard.paste-at-point",fw=[{actionId:uw,shortcut:{key:"c",accelKey:!0}},{actionId:hw,shortcut:{key:"x",accelKey:!0}},{actionId:pw,shortcut:{key:"v",accelKey:!0}}],mw=[{id:"system.selection-clipboard-context-menu",target:"selection",order:1e3,actionIds:[uw,hw],getSections:e=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:uw,actionId:uw,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(uw),dataUi:"context-menu-copy-selection-button"},{kind:"command",id:hw,actionId:hw,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(hw),dataUi:"context-menu-cut-selection-button"}]}]},{id:"system.canvas-clipboard-context-menu",target:"canvas",order:1e3,actionIds:[gw],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:gw,actionId:gw,label:"Paste here",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(pw),dataUi:"context-menu-paste-here-button"}]}]}],Sw="image-blob:",yw=Xf(({editor:e,hostBridge:t,imageAssetService:n,flushSnapshot:i})=>{const o=Qf(null),r=Qf(null),{insertImageFromFile:s,replaceSelectedImage:a}=(({editor:e,imageAssetService:t,flushSnapshot:n})=>({insertImageFromFile:Kf(async({file:i,pagePoint:o,size:r})=>yf({editor:e,imageObjectUrls:t.objectUrls,source:{type:"file",file:i},pagePoint:o,size:r,flushSnapshot:n}),[e,t,n]),replaceSelectedImage:Kf(i=>vf({editor:e,file:i,imageObjectUrls:t.objectUrls,flushSnapshot:n}),[e,t,n])}))({editor:e,imageAssetService:n,flushSnapshot:i});return qf(()=>{if(t)return t.register({openInsertFilePicker(){o.current?.click()},openReplaceFilePicker(){r.current?.click()}})},[t]),qf(()=>{const t=t=>{if(e.shapeEditingStateSignal.get().session)return;if(xr(t.target))return;const n=hf(t.clipboardData);n&&(t.preventDefault(),s({file:n}))},n=t=>{var n;e.shapeEditingStateSignal.get().session||xr(t.target)||(n=t.dataTransfer)&&Array.from(n.items).some(e=>"file"===e.kind&&e.type.startsWith("image/"))&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy"))},i=t=>{if(e.shapeEditingStateSignal.get().session)return;if(xr(t.target))return;const n=hf(t.dataTransfer);n&&(t.preventDefault(),s({file:n,pagePoint:pf(e,t)}))};return window.addEventListener("paste",t),window.addEventListener("dragover",n),window.addEventListener("drop",i),()=>{window.removeEventListener("paste",t),window.removeEventListener("dragover",n),window.removeEventListener("drop",i)}},[e,s]),im(tm,{children:[nm("input",{ref:o,type:"file",accept:"image/*",hidden:!0,"data-ui":"insert-image-file-input",onChange:e=>{const t=e.currentTarget.files?.[0]??null;e.currentTarget.value="",t&&s({file:t})}}),nm("input",{ref:r,type:"file",accept:"image/*",hidden:!0,"data-ui":"replace-image-file-input",onChange:e=>{const t=e.currentTarget.files?.[0]??null;e.currentTarget.value="",t&&a(t)}})]})}),bw=Mg("plugin-image.asset-service"),xw={id:"plugin-image.product-controller"},Iw=class{handlers=null;register(e){return this.handlers=e,()=>{this.handlers===e&&(this.handlers=null)}}openInsertFilePicker(){this.handlers?.openInsertFilePicker()}openReplaceFilePicker(){this.handlers?.openReplaceFilePicker()}},vw=Mg("plugin-image.toolbar-host-bridge"),ww=Xf(({editor:e,pluginHostRuntime:t})=>((({editor:e,pluginHostRuntime:t})=>{qf(()=>{const n=n=>{if(e.getShapeEditingSession()||xr(n.target))return;const i=e.shortcuts.getActionIdForEvent({key:n.key,shiftKey:n.shiftKey,altKey:n.altKey,ctrlKey:n.ctrlKey,metaKey:n.metaKey,accelKey:n.metaKey||n.ctrlKey});if(!i)return;const o=Ig({editor:e,selectionState:e.selectionStateSignal.get(),toolState:e.toolStateSignal.get()}),r=t.actionRegistry.getAction(i);r&&!1!==r.isVisible?.(o)&&!1!==r.isEnabled?.(o)&&(n.preventDefault(),n.stopPropagation(),(({context:e,pluginHostRuntime:t,actionId:n})=>{const i=t.actionRegistry.getAction(n);i&&!1!==i.isVisible?.(e)&&!1!==i.isEnabled?.(e)&&i.run({context:e,value:i.getValue?.(e)??null})})({actionId:i,context:o,pluginHostRuntime:t}))};return window.addEventListener("keydown",n,!0),()=>{window.removeEventListener("keydown",n,!0)}},[e,t])})({editor:e,pluginHostRuntime:t}),null)),Pw="system.selection.delete",kw="system.selection.duplicate",Cw="system.selection.group",Tw="system.selection.select-all",Ew="system.selection.ungroup",Bw="system.selection.reset-rotation",Mw="system.selection.flip-horizontal",Rw="system.selection.flip-vertical",Aw="system.selection.send-to-back",Lw="system.selection.send-backward",Fw="system.selection.bring-forward",$w="system.selection.bring-to-front",Uw="system.selection.set-opacity",Dw=[{actionId:kw,shortcut:{key:"d",accelKey:!0}},{actionId:Tw,shortcut:{key:"a",accelKey:!0}},{actionId:Cw,shortcut:{key:"g",accelKey:!0}},{actionId:Ew,shortcut:{key:"g",accelKey:!0,shiftKey:!0}}],zw=[{id:kw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.duplicateSelection({source:"user"})}},{id:Tw,isEnabled:e=>e.editor.getCurrentPageShapeIds().length>0,run({context:e}){e.editor.selectAllCurrentPage("user")}},{id:Cw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.editor.canGroupSelection(),run({context:e}){e.editor.groupSelection("user")}},{id:Ew,isVisible:e=>e.editor.canUngroupSelection(),isEnabled:e=>e.editor.canUngroupSelection(),run({context:e}){e.editor.ungroupSelection("user")}},{id:Bw,isVisible:e=>e.selection.canResetRotation,run({context:e}){e.editor.resetSelectionRotation("user")}},{id:Mw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("horizontal","user")}},{id:Rw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("vertical","user")}},{id:Aw,isVisible:e=>e.selection.count>0&&!_f(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("back","user")}},{id:Lw,isVisible:e=>e.selection.count>0&&!_f(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionInParentOrder("backward","user")}},{id:Fw,isVisible:e=>e.selection.count>0&&!_f(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionInParentOrder("forward","user")}},{id:$w,isVisible:e=>e.selection.count>0&&!_f(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("front","user")}},{id:Uw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,getValue:e=>(e=>{const[t]=e.selection.selectedShapes;if(!t)return 1;const n=Hf(t.opacity);return e.selection.selectedShapes.every(e=>Hf(e.opacity)===n)?n:null})(e),run({context:e,value:t}){if("number"!=typeof t||!Number.isFinite(t))return;const n=Hf(t),i=e.selection.selectedShapes.filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},{id:Pw,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.deleteSelection("user")}}],_w=[{id:"system.selection-context-menu",target:"selection",order:1010,actionIds:[kw,Cw,Ew,Bw,Mw,Rw,$w,Fw,Lw,Aw,Pw],getSections(e){const t=e.selection.count>0&&!_f(e),n=[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:kw,actionId:kw,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(kw),dataUi:"context-menu-duplicate-selection-button"},{kind:"separator",id:"system.selection-clipboard-separator"},{kind:"command",id:Cw,actionId:Cw,label:"Group",icon:"group",dataUi:"context-menu-group-selection-button"},{kind:"command",id:Ew,actionId:Ew,label:"Ungroup",icon:"ungroup",dataUi:"context-menu-ungroup-selection-button"},{kind:"command",id:Pw,actionId:Pw,label:"Delete selection",icon:"trash-2",tone:"destructive",dataUi:"context-menu-delete-selection-button"}]}];return(e.selection.canResetRotation||e.selection.count>0)&&n.push({id:"system.selection-transform",title:"Transform",order:20,items:[{kind:"command",id:Bw,actionId:Bw,label:"Reset rotation",icon:"rotate-ccw",dataUi:"context-menu-reset-rotation-button"},{kind:"command",id:Mw,actionId:Mw,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"context-menu-flip-horizontal-button"},{kind:"command",id:Rw,actionId:Rw,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"context-menu-flip-vertical-button"}]}),t&&n.push({id:"system.selection-arrange",title:"Arrange",order:30,items:[{kind:"command",id:$w,actionId:$w,label:"Bring to front",icon:"chevrons-up",dataUi:"context-menu-bring-to-front-button"},{kind:"command",id:Fw,actionId:Fw,label:"Bring forward",icon:"move-up",dataUi:"context-menu-bring-forward-button"},{kind:"command",id:Lw,actionId:Lw,label:"Send backward",icon:"move-down",dataUi:"context-menu-send-backward-button"},{kind:"command",id:Aw,actionId:Aw,label:"Send to back",icon:"chevrons-down",dataUi:"context-menu-send-to-back-button"}]}),n}},{id:"system.canvas-selection-context-menu",target:"canvas",order:1005,actionIds:[Tw],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:Tw,actionId:Tw,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(Tw),dataUi:"context-menu-select-all-button"}]}]}],Hw=[{id:"system.selection-toolbar",surface:"selection",order:1e3,actionIds:[Bw,Mw,Rw,Aw,Lw,Fw,$w,Uw,Cw,Ew,Pw],getGroups(e){const t=e.selection.count>0&&!_f(e);return[{id:"system.selection-opacity",items:[{kind:"slider",id:"system.selection-opacity",actionId:Uw,label:"Opacity",min:0,max:1,step:.01,dataUi:"selection-opacity-slider"}]},{id:"system.selection-actions",items:[...e.selection.canResetRotation?[{kind:"button",id:Bw,actionId:Bw,label:e.selection.isMixedFrameAndPointHandleSelection?"Reset shape rotation":"Reset rotation",icon:"rotate-ccw",dataUi:"reset-selection-rotation-button"},{kind:"separator",id:"system.selection.reset-delete-separator"}]:[],{kind:"button",id:Mw,actionId:Mw,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"flip-selection-horizontal-button"},{kind:"button",id:Rw,actionId:Rw,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"flip-selection-vertical-button"},{kind:"separator",id:"system.selection.flip-order-separator"},...t?[{kind:"button",id:Aw,actionId:Aw,label:"Send to back",icon:"chevrons-down",dataUi:"send-selection-to-back-button"},{kind:"button",id:Lw,actionId:Lw,label:"Send backward",icon:"move-down",dataUi:"send-selection-backward-button"},{kind:"button",id:Fw,actionId:Fw,label:"Bring forward",icon:"move-up",dataUi:"bring-selection-forward-button"},{kind:"button",id:$w,actionId:$w,label:"Bring to front",icon:"chevrons-up",dataUi:"bring-selection-to-front-button"},{kind:"separator",id:"system.selection.order-delete-separator"}]:[],{kind:"button",id:Cw,actionId:Cw,label:"Group",icon:"group",dataUi:"group-selection-button"},{kind:"button",id:Ew,actionId:Ew,label:"Ungroup",icon:"ungroup",dataUi:"ungroup-selection-button"},{kind:"separator",id:"system.selection.group-delete-separator"},{kind:"button",id:Pw,actionId:Pw,label:"Delete selection",icon:"trash-2",dataUi:"delete-selection-toolbar-button"}]}]}}],Nw=[{id:YS,getValue:e=>e.tool.activeToolId,run({context:e,value:t}){"string"==typeof t&&e.editor.tools.hasTool(t)&&e.editor.setActiveTool(t,"system")}},{id:XS,getValue:e=>e.tool.isToolLocked,run({context:e}){e.editor.toggleToolLocked("system")}}],Ow=[{id:"system.canvas-tool-context-menu",target:"canvas",order:1020,actionIds:[YS],getSections:e=>[{id:"system.canvas-tools",title:"Tools",order:20,items:[{kind:"command",id:"system.canvas.select-tool",actionId:YS,value:"select",label:"Select tool",icon:"mouse-pointer-2",shortcut:e.editor.shortcuts.getToolShortcutLabel("select"),dataUi:"context-menu-select-tool-button"},{kind:"command",id:"system.canvas.hand-tool",actionId:YS,value:"hand",label:"Hand tool",icon:"hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),dataUi:"context-menu-hand-tool-button"}]}]}],Ww=[{id:"system.select-tool-toolbar",surface:"tool",placement:"chrome",order:0,actionIds:[YS],getGroups:e=>[{id:"system.select-tool",items:[{kind:"button",id:"system.select-tool",actionId:YS,value:"select",label:"Select",shortcut:e.editor.shortcuts.getToolShortcutLabel("select"),icon:"mouse-pointer-2",dataUi:"select-tool-button"},{kind:"button",id:"system.hand-tool",actionId:YS,value:"hand",label:"Hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),icon:"hand",dataUi:"hand-tool-button"}]}]},{id:"system.tool-lock-toolbar",surface:"tool",placement:"chrome",order:1e3,actionIds:[XS],getGroups:e=>[{id:"system.tool-lock",items:[{kind:"separator",id:"system.tool-lock-separator"},{kind:"button",id:"system.tool-lock",actionId:XS,value:!0,label:e.tool.isToolLocked?"Unlock tool":"Lock tool",icon:"lock",dataUi:"tool-lock-button"}]}]}],Yw="system.view.zoom-in",Xw="system.view.zoom-out",Kw="system.view.reset-zoom",Vw=[{id:Yw,run({context:e}){e.editor.zoomAtViewportCenter(-120,"system")}},{id:Xw,run({context:e}){e.editor.zoomAtViewportCenter(120,"system")}},{id:Kw,run({context:e}){e.editor.resetZoom("user")}}],qw=[{id:"system.canvas-view-context-menu",target:"canvas",order:1010,actionIds:[Yw,Xw,Kw],getSections:()=>[{id:"system.canvas-view",title:"View",order:10,items:[{kind:"command",id:Yw,actionId:Yw,label:"Zoom in",icon:"plus",dataUi:"context-menu-zoom-in-button"},{kind:"command",id:Xw,actionId:Xw,label:"Zoom out",icon:"minus",dataUi:"context-menu-zoom-out-button"},{kind:"command",id:Kw,actionId:Kw,label:"Reset zoom",icon:"rotate-ccw",dataUi:"context-menu-reset-zoom-button"}]}]}],jw=Symbol("CanvasKitProduct");export{ew as CANVAS_KIT_TOOL_IDS,ta as CanvasKitFloatingToolbarLayer,Dg as CanvasKitRoot,yy as DEFAULT_TEXT_FONT,oa as FloatingSelectionToolbarPageSpace,by as HOST_TEXT_FONT,bg as createCanvasKitController,xg as createCanvasKitControllerWithTools,b as createCustomShapeColor,qo as createDefaultTextExtensionOptions,jo as createDefaultTextFontCatalog,y as createThemeShapeColor,Nf as defineCanvasKit,w as getThemeColorTokenName,xw as imageProductControllerToken,I as isCustomShapeColorRef,x as isThemeShapeColorRef,C as resolveShapeColor,k as shapeColorToCssColor,aa as useCanvasKitLayerTree,ia as useCanvasKitWheelCapture};
|
|
1
|
+
function e(){return kC}function t(){return++kC}function n(e){if(CC)return void e();const t={initialAtomValues:new Map};CC=t;try{e(),s(t.initialAtomValues.keys())}catch(n){for(const[e,o]of t.initialAtomValues)e.__unsafe__setWithoutNotify(o);throw n}finally{CC=null}}function o(e){TC={child:e,parentSet:new Set,below:TC}}function i(){if(!TC)throw new Error("Cannot stop dependency capture because no capture is active");const e=TC;return TC=e.below,e.parentSet}function r(e){TC&&(TC.parentSet.add(e),e.children.add(TC.child))}function s(e){function t(e){for(const i of e)if(!o.has(i))if(o.add(i),"effect"===i.type)n.add(i);else if("computed"===i.type){const e=i.source;e&&t(e.children)}}const n=new Set,o=new Set;for(const i of e)t(i.children);for(const i of n)i.notify()}function a(e,t,n){return new MC(e,t,n?.isEqual)}function d(e,t,n){return new BC(e,t,n?.isEqual)}function l(e){return{id:e}}function c(e={}){return{id:DC,typeName:"document",scope:"document",meta:{...e}}}function u(){return{id:zC,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function p(e=zC){return{id:UC,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...NC}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function h(e){return!!e&&"page"===e.typeName}function g(e){return!!e&&"document"===e.typeName}function f(e){return!!e&&"shape"===e.typeName}function m(e){return!!e&&"session"===e.typeName}function y(e){return!!e&&"binding"===e.typeName}function S(e){return!!e&&"asset"===e.typeName}function b(e){return"document"===e.scope}function x(e,t,n){const o=t.sub(e),i=n.sub(e),r=o.x*o.x+o.y*o.y;if(0===r)return e;const s=Math.max(0,Math.min(1,(i.x*o.x+i.y*o.y)/r));return new $C(e.x+o.x*s,e.y+o.y*s)}function w(e,t,n){return e.dist(x(t,n,e))}function I(e,t,n,o){const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d>=0&&d<=1&&l>=0&&l<=1}function P(e,t,n,o){return I(e,t,n,o)?0:Math.min(w(e,n,o),w(t,n,o),w(n,e,t),w(o,e,t))}function v(e){return e.length>=3&&e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y))}function k(e){const t=e.filter(v).flatMap(e=>e);return t.length>0?LC.FromPoints(t):null}function C(e,t){if(!v(t))return!1;let n=!1;for(let o=0;o<t.length;o+=1){const i=t[o],r=t[(o+t.length-1)%t.length];if(w(e,r,i)<=1e-8)return!0;i.y>e.y!=r.y>e.y&&e.x<(r.x-i.x)*(e.y-i.y)/(r.y-i.y)+i.x&&(n=!n)}return n}function T(e,t){return t.some(t=>C(e,t))}function M(e,t,n,o=0){if(!v(n))return!1;if(C(e,n)||C(t,n))return!0;for(let i=0;i<n.length;i+=1)if(P(e,t,n[i],n[(i+1)%n.length])<=Math.max(0,o))return!0;return!1}function E(e){return{kind:"theme",slot:e}}function B(e){return{kind:"custom",value:e}}function A(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&XC.includes(e.slot)}function R(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function $(e){return A(e)||R(e)}function L(e){return YC[e]}function F(e,t){return $(e)?e:t}function O(e){return"custom"===e.kind?e.value:`var(${L(e.slot)}, ${HC[e.slot]})`}function D(e,t){if("custom"===e.kind)return e.value;const n=L(e.slot),o=HC[e.slot];return t?.(n,o)??o}function z(e){if("custom"!==e.kind)return!1;const t=e.value.trim().toLowerCase();return"transparent"===t||/^#[0-9a-f]{6}00$/.test(t)}function U(e,t){return e===t||!(!e||!t)&&e.kind===t.kind&&("theme"===e.kind?e.slot===t.slot:e.value===t.value)}function N(e,t,n){const o=new Set;let i=n.parentId;for(;i.startsWith("shape:");){const n=i;if(n===t)return!0;if(o.has(n))return!1;o.add(n);const r=e.getShape(n);if(!r)return!1;i=r.parentId}return!1}function W(e,t,n){let o=e.computeShapeExportPageBounds(t);if(!j(o))return o;for(const i of((e,t,n)=>{const o=[];for(const i of X(e,t,n)){const t=H(e,i);t&&j(t)&&o.push(t)}return o})(e,t,n)){const e=K(o,i);if(!e)return null;o=e}return o}function X(e,t,n){const o=[],i=new Set;let r=t.parentId;for(;r.startsWith("shape:");){const t=r;if(i.has(t))break;i.add(t);const s=e.getShape(t);if(!s)break;n.has(s.id)&&o.push(s),r=s.parentId}return o.reverse()}function Y(e,t,n,o){if(n.has(t.id))return n.get(t.id)??null;const i=e.getShapeUtil(t),r=i.getChildExportClipLocalPolygons(t);if(!r||!k(r))return n.set(t.id,null),null;const s=e.computeShapeExportToPageTransform(t).toSvgString(),a=i.getChildExportClipLocalBounds(t),[d]=r,l=1===r.length&&d&&a&&((e,t)=>{const n=[new $C(t.minX,t.minY),new $C(t.maxX,t.minY),new $C(t.maxX,t.maxY),new $C(t.minX,t.maxY)];return e.length===n.length&&e.every((e,t)=>e.equals(n[t]))})(d,a)?[{tag:"rect",attrs:{x:a.x,y:a.y,width:a.w,height:a.h,transform:s}}]:r.map(e=>({tag:"path",attrs:{d:_(e),transform:s}})),c=o.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:l});return n.set(t.id,c),c}function H(e,t){const n=e.getShapeUtil(t).getChildExportClipLocalPolygons(t);if(!n||!k(n))return null;const o=e.computeShapeExportToPageTransform(t);return k(n.map(e=>e.map(e=>o.applyToPoint(e))))}function _(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).concat("Z").join(" ")}function K(e,t){const n=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return i<n||r<o?null:new LC(n,o,i-n,r-o)}function q(e){if("string"==typeof e)return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">");const t=(e=>{const t=[];for(const[n,o]of Object.entries(e))null!=o&&!1!==o&&t.push(`${n}="${V("number"==typeof o?G(o):String(o))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(q).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function j(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function V(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function G(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Z(e){return e[KC]}function Q({editor:e,exporters:t,shapeIds:n}){const o=Array.from(n),i=e.getShapeExportTraversalIds(o),r=[];for(const c of i){const n=e.getShape(c);n?(J(e.computeShapeExportPageBounds(n))||r.push({kind:"missing-bounds",id:n.id,canRepair:!1}),t.get(n.type)||r.push({kind:"missing-exporter",id:n.id,canRepair:!1})):r.push({kind:"missing-shape",id:c,canRepair:!1})}const s=new Set(i),a=new Set;for(const c of Z(e).getAll().filter(y)){if(!s.has(c.fromId)&&!s.has(c.toId))continue;const t=e.getShape(c.fromId),n=e.getShape(c.toId);t&&n?e.bindings.canBind(c)?(e.bindings.getConflictingBindings(c).some(e=>a.has(e.id))&&r.push({kind:"duplicate-exclusive-binding",id:c.id,canRepair:!0}),a.add(c.id)):r.push({kind:"invalid-binding",id:c.id,canRepair:!0}):r.push({kind:"missing-binding-endpoint",id:c.id,canRepair:!0})}const d=r.filter(e=>e.canRepair).length,l=r.length-d;return{requestedShapeIds:o,issues:r,repairableIssueCount:d,fatalIssueCount:l,canExport:0===l}}function J(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function ee(e){return e.added.length>0||e.updated.length>0||e.removed.length>0}function te(e){return e instanceof Map?new Map(e):new Map(Array.from(e,e=>[e.id,e]))}function ne(e,t){const n=te(e),o=te(t),i={added:[],updated:[],removed:[]};for(const[r,s]of n){const e=o.get(r);e?e!==s&&i.updated.push({before:s,after:e}):i.removed.push(s)}for(const[r,s]of o)n.has(r)||i.added.push(s);return i}function oe(e){return{added:[...e.removed],updated:e.updated.map(e=>({before:e.after,after:e.before})),removed:[...e.added]}}function ie(e,t){const n=new Map,o=new Map,i=new Map;for(const s of e.added)n.set(s.id,s);for(const s of e.updated)o.set(s.after.id,s);for(const s of e.removed)i.set(s.id,s);for(const s of t.added){const e=i.get(s.id);if(e){i.delete(s.id),o.set(s.id,{before:e,after:s});continue}const t=o.get(s.id);t?o.set(s.id,{before:t.before,after:s}):n.set(s.id,s)}for(const s of t.updated){if(n.get(s.after.id)){n.set(s.after.id,s.after);continue}const e=i.get(s.after.id);if(e){i.delete(s.after.id),o.set(s.after.id,{before:e,after:s.after});continue}const t=o.get(s.after.id);o.set(s.after.id,t?{before:t.before,after:s.after}:{before:s.before,after:s.after})}for(const s of t.removed){if(n.get(s.id)){n.delete(s.id);continue}const e=o.get(s.id);e?(o.delete(s.id),i.set(s.id,e.before)):i.set(s.id,s)}const r={added:[],updated:[],removed:[]};for(const s of n.values())r.added.push(s);for(const s of o.values())s.before!==s.after&&r.updated.push(s);for(const s of i.values())r.removed.push(s);return r}function re(e,t){return{id:e.id,forward:ie(e.forward,t),parentIds:e.parentIds}}function se(e,t){return{forward:t,inverse:oe(t),label:e}}function ae(e){return void 0!==e&&e<0?-1:1}function de(e,t){if(void 0===t)return e;const n=2*Math.PI;return e+Math.round((t-e)/n)*n}function le(e,t){const n=2*Math.PI,o=((e-t+Math.PI)%n+n)%n-Math.PI;return Math.abs(o)}function ce(e,t,n={}){if(!(e=>[e.a,e.b,e.c,e.d,e.e,e.f].every(Number.isFinite))(e)||![t.x,t.y,t.w,t.h].every(Number.isFinite))return null;const o=Number.isFinite(n.epsilon)?Math.max(0,n.epsilon??0):1e-8,i=Math.hypot(e.a,e.b),r=Math.hypot(e.c,e.d),s=e.determinant(),a=({rotation:n,skewX:o,scaleX:i,scaleY:r})=>{const s=t.center,a=e.applyToPoint(s),d={x:a.x-s.x,y:a.y-s.y,rotation:n,skewX:o,scaleX:i,scaleY:r};return Object.values(d).every(Number.isFinite)?d:null},d=o*Math.max(1,i,r),l=i<=d,c=r<=d;if(l||c){if(l&&c)return a({rotation:n.preferredRotation??0,skewX:0,scaleX:0,scaleY:0});if(l){const t=r*ae(n.preferredScaleYSign);return a({rotation:de(Math.atan2(-e.c/t,e.d/t),n.preferredRotation),skewX:0,scaleX:0,scaleY:t})}const t=i*ae(n.preferredScaleXSign);return a({rotation:de(Math.atan2(e.b/t,e.a/t),n.preferredRotation),skewX:0,scaleX:t,scaleY:0})}if(Math.abs(s)<=o*i*r)return null;const u=Math.atan2(e.b,e.a),p=Math.cos(u),h=Math.sin(u),g=p*e.a+h*e.b,f=-h*e.c+p*e.d,m=Math.atan((p*e.c+h*e.d)/f),y=[{rotation:de(u,n.preferredRotation),scaleX:g,scaleY:f},{rotation:de(u+Math.PI,n.preferredRotation),scaleX:-g,scaleY:-f}],S=ae(n.preferredScaleXSign),b=ae(n.preferredScaleYSign),x=e=>{let t=0;return void 0!==n.preferredScaleXSign&&ae(e.scaleX)===S&&(t+=1),void 0!==n.preferredScaleYSign&&ae(e.scaleY)===b&&(t+=1),{signMatches:t,rotationDistance:void 0===n.preferredRotation?0:le(e.rotation,n.preferredRotation)}},w=x(y[0]),I=x(y[1]),P=I.signMatches>w.signMatches||I.signMatches===w.signMatches&&I.rotationDistance<w.rotationDistance?y[1]:y[0];return((e,t,n,o,i,r)=>{const s=Math.cos(t),a=Math.sin(t),d=Math.tan(n),l=[s*o,a*o,(s*d-a)*i,(a*d+s)*i],c=[e.a,e.b,e.c,e.d],u=r*Math.max(1,...c.map(e=>Math.abs(e)));return c.every((e,t)=>Math.abs(e-(l[t]??e))<=u)})(e,P.rotation,m,P.scaleX,P.scaleY,o)?a({rotation:P.rotation,skewX:m,scaleX:P.scaleX,scaleY:P.scaleY}):null}function ue(e,t){return t.getExportBounds(e)}function pe(e,t,n=FC.Identity()){return n.compose(t.getLocalToPageTransform(e))}function he(e,t,n=FC.Identity()){const o=t.getLocalBounds(e).center,i=new $C(e.x+o.x,e.y+o.y),r=FC.Translate(i.x,i.y).compose(FC.Rotate(e.rotation)).compose(FC.SkewX(e.skewX)).compose(FC.Scale(e.scaleX,e.scaleY)).compose(FC.Translate(-i.x,-i.y));return n.compose(r)}function ge(e,t,n=FC.Identity()){return pe(e,t,n)}function fe(e,t,n=FC.Identity()){return pe(e,t,n).applyToPoint(t.getLocalBounds(e).center)}function me(e,t,n,o=FC.Identity()){const i=he(e,n,o).tryInvert();if(i)return i.applyToPoint(t);const r=n.getLocalBounds(e).center,s=new $C(e.x+r.x,e.y+r.y),a=o.tryInvert();if(!a)return s;const d=a.applyToPoint(t).sub(s).rot(-e.rotation),l=Math.tan(e.skewX);return s.add(new $C(0===e.scaleX?0:(d.x-l*d.y)/e.scaleX,0===e.scaleY?0:d.y/e.scaleY))}function ye(e,t,n=FC.Identity()){const o=he(e,t,n);return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(e=>o.applyToPoint(e))}function Se(e,t,n=FC.Identity()){const o=ye(e,t,n),i=((e,t,n=FC.Identity())=>{const o=t.getLocalBounds(e),i=pe(e,t,n);return[new $C(o.minX,o.minY),new $C(o.maxX,o.minY),new $C(o.maxX,o.maxY),new $C(o.minX,o.maxY)].map(e=>i.applyToPoint(e))})(e,t,n);return{bounds:LC.FromPoints(o),center:fe(e,t,n),corners:i,outlineVertices:o}}function be(e,t,n){const o=n.startsWith("shape:")?e.getShape(n):null,i=(o?e.computeShapeLocalToPageTransform(o):FC.Identity()).tryInvert();if(!i)return null;const r=e.computeShapeLocalToPageTransform(t);return ce(i.compose(r),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})}function xe(e,t,n,...o){const i=GC.get(e),r=new Set(i?.suppressedBindingIds??VC),s=r.size;for(const a of t)r.add(a);if(r.size===s)return we(n);GC.set(e,{suppressedBindingIds:r});try{return we(n)}finally{i?GC.set(e,i):GC.delete(e)}}function we(e){const t=e();if(("object"==typeof(n=t)&&null!==n||"function"==typeof n)&&"function"==typeof n.then)throw new Error("Binding reaction scope callbacks must be synchronous");var n;return t}function Ie(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function Pe(e,t,n){const o=e.getShape(t);if(!o)return;const i=e.getContainingParentIdForShapeRecord(o);i&&i!==o.parentId&&e.commands.reparentShapes({ids:[t],parentId:i},n)}function ve(e,t,n){const o=n?.source??"user";xe(e,n?.suppressBindingIds??[],()=>((e,t,n)=>{Z(e).atomic(()=>{const o=[],i=[];for(const n of t){const t=e.getShape(n.id);if(!t)continue;const r=n.x??t.x,s=n.y??t.y,a=n.rotation??t.rotation,d=n.skewX??t.skewX,l=n.scaleX??t.scaleX,c=n.scaleY??t.scaleY,u=void 0===n.opacity?t.opacity:Me(n.opacity,t.opacity),p=n.isHidden??t.isHidden,h=n.isLocked??t.isLocked,g=n.parentId??t.parentId,f=n.index??t.index,m=void 0===n.meta?t.meta:{...n.meta};if(!n.props&&void 0===n.meta&&r===t.x&&s===t.y&&a===t.rotation&&d===t.skewX&&l===t.scaleX&&c===t.scaleY&&u===t.opacity&&p===t.isHidden&&h===t.isLocked&&g===t.parentId&&f===t.index)continue;const y=e.shapeUtils.get(t.type),S={...t,x:r,y:s,rotation:a,skewX:d,scaleX:l,scaleY:c,opacity:u,isHidden:p,isLocked:h,parentId:g,index:f,props:n.props?y.validateProps({...t.props,...n.props}):t.props,meta:m};o.push(S),i.push({before:t,after:S})}0!==o.length&&(ke(e,o),Z(e).put(o,n),i.some(({before:e,after:t})=>e.parentId!==t.parentId)&&Ce(e,n),e.bindings.handleShapeChanges(i,n),((e,t,n)=>{const o=new Set,i=new Set;for(const s of t)Re(e,s.before,o),Re(e,s.after,o),s.before.parentId!==s.after.parentId&&s.before.parentId.startsWith("shape:")&&i.add(s.before.parentId),e.getShapeUtil(s.after).shouldResizeDescendants(s.after)&&o.add(s.after.id);const r=new Set;Le(e,i,r,n),Ee(e,o,n,r)})(e,i,n))},n)})(e,t,o))}function ke(e,t){const n=new Set;for(const i of t){if(n.has(i.id))throw new Error(`Duplicate shape id ${i.id}`);n.add(i.id)}const o=new Map(Z(e).getAll().filter(f).map(e=>[e.id,e]));for(const i of t)o.set(i.id,i);for(const i of t){const t=new Set([i.id]);let n=i;for(;n.parentId.startsWith("shape:");){const r=n.parentId;if(t.has(r))throw new Error(`Shape parent cycle includes ${i.id}`);t.add(r);const s=o.get(r);if(!s)throw new Error(`Missing parent ${r} for shape ${n.id}`);if(!e.getShapeUtil(s).canReceiveChild(s,n))throw new Error(`Shape ${r} cannot receive shape ${n.id}`);n=s}if(!e.getPage(n.parentId))throw new Error(`Missing page parent ${n.parentId} for shape ${n.id}`)}}function Ce(e,t){const n=e.getSessionRecord();let o=!1;const i={};for(const[r,s]of Object.entries(n.pageSelectedShapeIdsById)){const t=r,n=s??[],a=Array.from(new Set(n)).filter(n=>Te(e,n)===t&&!e.isShapeHidden(n)),d=new Set(a),l=a.filter(t=>{let n=e.getShape(t);const o=new Set([t]);for(;n?.parentId.startsWith("shape:");){const t=n.parentId;if(o.has(t))return!0;if(d.has(t))return!1;o.add(t),n=e.getShape(t)}return!0});i[t]=l,l.length!==n.length&&(o=!0)}o&&e.updateSession({pageSelectedShapeIdsById:i},t)}function Te(e,t){let n=e.getShape(t);const o=new Set;for(;n?.parentId.startsWith("shape:");){const t=n.parentId;if(o.has(t))return null;o.add(t),n=e.getShape(t)}return n&&e.getPage(n.parentId)?n.parentId:null}function Me(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Ee(e,t,n,o=new Set){const i=[...t].sort((t,n)=>Be(e,n)-Be(e,t));for(const r of i){if(o.has(r))continue;const t=e.getShape(r);if(!t)continue;const i=e.getShapeUtil(t);if(!i.shouldResizeDescendants(t))continue;const s=Ae(e,t.id);if(0===s.length)continue;const a=s.flatMap(t=>e.getShapeUtil(t).getPositionedOutlineVertices(t).map(n=>he(t,e.getShapeUtil(t)).applyToPoint(n)));if(0===a.length)continue;const d=LC.FromPoints(a),l=i.getResizeToFitDescendantsProps(t,d);if(!l)continue;const c=i.validateProps(l),u={...t,props:c},p=ce(i.getLocalToPageTransform(t).compose(FC.Translate(d.x,d.y)),i.getLocalBounds(u),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(!p)continue;const h=[...s.map(e=>({before:e,after:{...e,x:e.x-d.x,y:e.y-d.y}})),{before:t,after:{...t,...p,props:c}}].filter(({before:e,after:t})=>{return!((n=e).x===(o=t).x&&n.y===o.y&&n.rotation===o.rotation&&n.skewX===o.skewX&&n.scaleX===o.scaleX&&n.scaleY===o.scaleY&&((e,t)=>{if(e===t)return!0;const n=Object.entries(e),o=Object.entries(t);return n.length===o.length&&n.every(([e,n])=>Object.is(n,t[e]))})(n.props,o.props));var n,o});0!==h.length&&(Z(e).put(h.map(e=>e.after),n),e.bindings.handleShapeChanges(h,n))}}function Be(e,t){let n=0,o=e.getShape(t);const i=new Set;for(;o?.parentId.startsWith("shape:");){const t=o.parentId;if(i.has(t))break;i.add(t),n+=1,o=e.getShape(t)}return n}function Ae(e,t){return Z(e).getAll().filter(f).filter(e=>e.parentId===t).sort((e,t)=>e.index.localeCompare(t.index))}function Re(e,t,n){const o=new Set([t.id]);let i=t.parentId;for(;i.startsWith("shape:");){const t=e.getShape(i);if(!t||o.has(t.id))return;o.add(t.id),e.getShapeUtil(t).shouldResizeDescendants(t)&&n.add(t.id),i=t.parentId}}function $e(e,t){const n=new Set;for(const o of t){const t=e.getShape(o);t&&Re(e,t,n)}return n}function Le(e,t,n,o){const i=[],r=[...t].sort((t,n)=>e.getDescendantShapeIds(n).length-e.getDescendantShapeIds(t).length);for(let s=0;s<r.length;s+=1){const t=r[s];if(!t||n.has(t))continue;const a=e.getShape(t);if(!a)continue;const d=e.getShapeUtil(a).getMinimumChildCount(a);if(d<=0)continue;const l=Ae(e,a.id).filter(e=>!n.has(e.id)),c=new Set(l.map(e=>e.id));if(new Set(l.map(t=>{const n=e.bindings.getShapeHierarchyRootId(t.id);return c.has(n)?n:t.id})).size>=d)continue;const u=Ae(e,a.parentId).filter(e=>!n.has(e.id)).flatMap(e=>e.id===a.id?l.map(e=>e.id):[e.id]),p=new Map(u.map((t,n)=>[t,e.createShapeIndex(n+1)])),h=[];let g=!0;for(const n of l){if(!e.canUseShapeParent(a.parentId,n.id)){g=!1;break}const t=be(e,n,a.parentId);if(!t){g=!1;break}h.push({before:n,after:{...n,...t,parentId:a.parentId,index:p.get(n.id)??a.index}})}if(!g)continue;const f=new Set;Re(e,a,f);for(const e of f)r.push(e);const m=new Set(h.map(e=>e.after.id)),y=u.flatMap(t=>{if(m.has(t))return[];const n=e.getShape(t),o=p.get(t);return n&&o&&n.index!==o?[{before:n,after:{...n,index:o}}]:[]}),S=[...h,...y];S.length>0&&(Z(e).put(S.map(e=>e.after),o),e.bindings.handleShapeChanges(S,o));const b=e.getSelectedShapeIds();if(b.includes(a.id)){const t=Array.from(new Set(h.map(t=>{const n=e.bindings.getShapeHierarchyRootId(t.after.id);return m.has(n)?n:t.after.id})));e.commands.setSelectedShapeIds(b.flatMap(e=>e===a.id?t:[e]),{source:o})}e.sideEffects.runBeforeDelete("shape",[a.id],o),Z(e).remove([a.id],o),e.sideEffects.runAfterDelete("shape",[a.id],o),n.add(a.id),i.push(a.id)}return i}function Fe(e,t,n){const o=((e,t)=>{const n=Array.from(new Set(t.ids)).map(t=>e.getShape(t)).filter(e=>!!e&&e.parentId!==t.parentId);if(0===n.length)return[];const o=Ae(e,t.parentId).reduce((e,t)=>{const n=Number.parseInt(t.index,10);return Number.isFinite(n)?Math.max(e,n):e},0),i=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,r=new Map;for(const s of n){if(!e.canUseShapeParent(t.parentId,s.id))return null;const n=be(e,s,t.parentId);if(!n)return null;r.set(s.id,n)}return n.map((n,s)=>{const a=i?e.getShapeUtil(i).getChildPlacementMeta(i,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:e.createShapeIndex(o+s+1),...r.get(n.id),meta:a===n.meta?void 0:a}})})(e,t);return!!o&&(0===o.length||ve(e,o,n),!0)}function Oe(e,t,n){const o=n?.source??"user",i=e.getShapeIdsIncludingDescendants(t),r=$e(e,i),s=new Set(i),a=e.getUnreferencedAssetIdsAfterShapeDelete(i);e.prepareShapeIdsForRemoval(i,o),Z(e).atomic(()=>{e.sideEffects.runBeforeDelete("shape",i,o),Z(e).remove(i,o),a.length>0&&Z(e).remove(a,o),Le(e,r,s,o),Ee(e,r,o,s),e.sideEffects.runAfterDelete("shape",i,o)},o)}function De(e,t){return e.bindings.canBind(t)}function ze(e,t,n){for(const o of t){const t=e.getShape(o);t?.parentId.startsWith("shape:")&&n.add(t.parentId)}}function Ue(e){return{added:[...e.added],updated:e.updated.filter(({before:e,after:t})=>!Ne(e,t)),removed:[...e.removed]}}function Ne(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>Ne(e,t[n]));if("object"!=typeof e||"object"!=typeof t)return!1;const n=e,o=t,i=Object.keys(n),r=Object.keys(o);return i.length===r.length&&i.every(e=>Object.prototype.hasOwnProperty.call(o,e)&&Ne(n[e],o[e]))}function We(e){return JSON.parse(JSON.stringify(e))}function Xe(e){return JSON.parse(JSON.stringify(e))}function Ye(e){const t=globalThis.reportError;"function"==typeof t&&t(e)}function He(e,t,n){const o=[...t].sort((e,t)=>e.id.localeCompare(t.id)),i=new Set([e]);let r=e;for(;;){let t=null;for(const e of o){if(e.fromId!==r&&e.toId!==r)continue;const o=n(e).getShapeHierarchyRootId?.(e,r);if(o&&o!==r){t=o;break}}if(!t)return r;if(i.has(t))return e;i.add(t),r=t}}function _e({before:e,after:t}){return e.parentId!==t.parentId||e.x!==t.x||e.y!==t.y||e.rotation!==t.rotation||e.skewX!==t.skewX||e.scaleX!==t.scaleX||e.scaleY!==t.scaleY||e.props!==t.props}function Ke(e){return Math.min(8,Math.max(.1,e))}function qe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function je(e,t){return e.count===t.count&&e.singleShapeType===t.singleShapeType&&e.commonShapeType===t.commonShapeType&&e.canFlipSelection===t.canFlipSelection&&e.hasPointHandleSelection===t.hasPointHandleSelection&&e.hasFrameSelection===t.hasFrameSelection&&e.isMixedFrameAndPointHandleSelection===t.isMixedFrameAndPointHandleSelection&&e.canDragPointHandles===t.canDragPointHandles&&e.hasSelectionRotation===t.hasSelectionRotation&&e.hasMixedSelectionRotation===t.hasMixedSelectionRotation&&e.canResetSelectionRotation===t.canResetSelectionRotation}function Ve(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Ge(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function Ze(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i||o.x!==i.x||o.y!==i.y)return!1}return!0}function Qe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i||!Ze(o,i))return!1}return!0}function Je(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y&&e.w===t.w&&e.h===t.h:e===t)}function et(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function tt(e,t){return e.culledCount===t.culledCount&&e.visibleCount===t.visibleCount&&e.retainedCount===t.retainedCount&&e.retainedBaseCount===t.retainedBaseCount&&e.culledRangeCount===t.culledRangeCount&&e.culledRangeSpan===t.culledRangeSpan&&e.culledRangesSummary===t.culledRangesSummary&&e.retainedBaseRangeCount===t.retainedBaseRangeCount&&e.retainedBaseRangeSpan===t.retainedBaseRangeSpan&&e.retainedBaseRangesSummary===t.retainedBaseRangesSummary&&e.retainedRangeCount===t.retainedRangeCount&&e.retainedRangeSpan===t.retainedRangeSpan&&e.retainedRangesSummary===t.retainedRangesSummary&&e.retainedChangeCount===t.retainedChangeCount&&e.retainedAddedCount===t.retainedAddedCount&&e.retainedRemovedCount===t.retainedRemovedCount&&e.selectedOutsideCulledCount===t.selectedOutsideCulledCount}function nt(e,t){return e.selectionFrameActive===t.selectionFrameActive&&e.selectionHandlesActive===t.selectionHandlesActive&&e.bindingPreviewActive===t.bindingPreviewActive&&e.brushBoxActive===t.brushBoxActive&&e.selectionFrameChangeCount===t.selectionFrameChangeCount&&e.selectionHandlesChangeCount===t.selectionHandlesChangeCount&&e.resizeHandleCount===t.resizeHandleCount&&e.rotateHandleCount===t.rotateHandleCount&&e.terminalHandleCount===t.terminalHandleCount&&e.middleHandleCount===t.middleHandleCount&&e.customHandleCount===t.customHandleCount&&e.boundsSummary===t.boundsSummary&&e.rotation===t.rotation&&e.strokeWidth===t.strokeWidth}function ot(e,t,n){const o=new Set([e.id]);let i=e.parentId;for(;i.startsWith("shape:");){const e=i;if(o.has(e))return null;o.add(e);const n=t.get(e);if(!n)return null;i=n.parentId}return n.has(i)?i:null}function it(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i)return!1;if(o.id!==i.id||o.shape!==i.shape||o.isSelected!==i.isSelected||!Je(o.bounds,i.bounds))return!1}return!0}function rt(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function st(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function at(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)&&e.every((e,n)=>at(e,t[n]));const n=e,o=t,i=Object.keys(n),r=Object.keys(o);return i.length===r.length&&i.every(e=>Object.prototype.hasOwnProperty.call(o,e)&&at(n[e],o[e]))}function dt(e){const t=(e=>{const t=new Set(e.getSelectedShapeIds());return 0===t.size?[]:e.getCurrentPageShapeIds().filter(e=>t.has(e)).filter(n=>!((e,t,n)=>{const o=new Set([t]);let i=e.getShape(t);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(n.has(t))return!0;if(o.has(t))return!1;o.add(t),i=e.getShape(t)}return!1})(e,n,t))})(e);if(0===t.length)return null;const n=((e,t)=>{const n=((e,t)=>{const n=e.getShapeIdsIncludingDescendants(t),o=new Set(n);for(let i=0;i<n.length;i+=1){const t=n[i];if(t)for(const i of e.getBindingsForShape(t)){const t=e.getBindingUtil(i).getExportShapeIds?.(e,i);for(const i of t??[])for(const t of e.getShapeIdsIncludingDescendants([i]))o.has(t)||(o.add(t),n.push(t))}}return n})(e,t),o=new Set(n);return e.getCurrentPageShapeIds().filter(e=>o.has(e))})(e,t),o=new Set(n),i=new Set;for(const l of n){const t=e.getShape(l);if(!(!t||t.parentId.startsWith("shape:")&&o.has(t.parentId)||ct(e,t,o))){i.add(t.id);for(const n of e.getDescendantShapeIds(t.id))i.add(n)}}const r=n.filter(e=>!i.has(e)),s=new Set(r),a=r.map(t=>e.getShape(t)).filter(e=>!!e).flatMap(t=>{const n=ct(e,t,s);return n?[n]:[]});if(0===a.length)return null;const d=t.filter(e=>s.has(e));return 0===d.length?null:{type:"land/clipboard",version:1,source:{app:"land"},rootShapeIds:d,records:{shapes:a,bindings:ut(e,a,s),assets:pt(e,a)},bounds:ht(e,r)}}function lt(e,t){const{payload:n}=t;if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"land/clipboard"===t.type&&1===t.version&&!!t.records&&Array.isArray(t.rootShapeIds)&&Array.isArray(t.records.shapes)&&Array.isArray(t.records.bindings)&&Array.isArray(t.records.assets)})(n)||0===n.records.shapes.length)return[];const o=t.source??"user",i=e.getCurrentPageId(),r=(e=>{const t=e.payload.bounds;return e.pagePoint?e.pagePoint.sub(new $C(t.x+t.w/2,t.y+t.h/2)):e.offset??oT})(t),s=new Map,a=new Map,d=[],l=new Set(n.records.shapes.map(e=>e.id)),c=new Set(n.records.shapes.filter(e=>!e.parentId.startsWith("shape:")||!l.has(e.parentId)).map(e=>e.id));Z(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=e.createAssetRecord({type:t.type,props:St(t.props),meta:St(t.meta)});return s.set(t.id,n.id),n});t.length>0&&e.commands.createAssetsFromRecords(t,{source:o});const d=n.records.shapes.map(t=>{const n=((e,t)=>yt(e,t))(t.props,s),o=c.has(t.id),d=e.createShapeRecord({type:t.type,x:t.x+(o?r.x:0),y:t.y+(o?r.y:0),props:n,parentId:i,rotation:t.rotation,skewX:t.skewX,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,meta:St(t.meta)});return a.set(t.id,d.id),{original:t,draft:d}}).map(({original:e,draft:t})=>({...t,parentId:gt(e.parentId,a,i)}));d.length>0&&e.commands.createShapesFromRecords(d,{source:o});for(const i of n.records.bindings){const t=a.get(i.fromId),n=a.get(i.toId);t&&n&&e.commands.createBinding({type:i.type,fromId:t,toId:n,props:St(i.props),meta:St(i.meta)},{source:o})}},o);for(const u of n.rootShapeIds){const e=a.get(u);e&&d.push(e)}return d.length>0&&e.commands.setSelectedShapeIds(d,{source:o}),d}function ct(e,t,n){if(!e.getShapeUtil(t).canCopyToClipboard(t,{editor:e,copiedShapeIds:n}))return null;const o=bt(t);if(t.parentId.startsWith("shape:")&&n.has(t.parentId))return o;const i=e.computeShapeLocalBounds(t),r=ce(e.computeShapeLocalToPageTransform(t),i,{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return r?{...o,parentId:e.getShapePageId(t.id)??o.parentId,...r}:null}function ut(e,t,n){const o=[],i=new Set;for(const r of t)for(const t of e.getBindingsForShape(r.id))i.has(t.id)||n.has(t.fromId)&&n.has(t.toId)&&(i.add(t.id),o.push(bt(t)));return o}function pt(e,t){const n=[],o=new Set;for(const i of t)for(const t of ft(i)){if(o.has(t))continue;const i=e.getAsset(t);i&&(o.add(t),n.push(bt(i)))}return n}function ht(e,t){const n=(e=>{if(0===e.length)return null;let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),o=Math.max(o,r.maxX),i=Math.max(i,r.maxY);return new LC(t,n,o-t,i-n)})(t.map(t=>e.getShapePageBounds(t)).filter(e=>!!e))??new LC(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function gt(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function ft(e){const t=[],n=new Set,o=st(e);return o&&(n.add(o),t.push(o)),mt(e.props,n,t),t}function mt(e,t,n){if(xt(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const o of e)mt(o,t,n);else if(e&&"object"==typeof e)for(const o of Object.values(e))mt(o,t,n)}function yt(e,t){if(xt(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>yt(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[o,i]of Object.entries(e))n[o]=yt(i,t);return n}function St(e){return bt(e)}function bt(e){if(Array.isArray(e))return e.map(bt);if(!e||"object"!=typeof e)return e;const t={};for(const[n,o]of Object.entries(e))t[n]=bt(o);return t}function xt(e){return"string"==typeof e&&e.startsWith("asset:")}function wt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function It(e,t){return"string"==typeof e?e:t}function Pt(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function vt(e,t){return"boolean"==typeof e?e:t}function kt(e){return wt(e)?e:{}}function Ct(e){return wt(e)?{x:Pt(e.x,NC.x),y:Pt(e.y,NC.y),z:Math.min(8,Math.max(.1,Pt(e.z,NC.z)))}:null}function Tt(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function Mt(e,t){if(!wt(e))throw new rT(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,o=Pt(n,NaN),i="document"===t?2:1;if(o!==i)throw new rT(`Unsupported ${t} snapshot schema version: expected ${i}, received ${String(n)}`);if(!Array.isArray(e.records))throw new rT(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:o,records:e.records}}function Et(e,t,n){const o=e.find(g)??c(),i=e.filter(e=>"page"===e.typeName),r=e.filter(e=>"shape"===e.typeName),s=e.filter(y),a=e.filter(S),d=(i.length>0?[...i].sort((e,t)=>e.index.localeCompare(t.index)):[u()]).map((e,t)=>({...e,index:String(t+1).padStart(4,"0")})),l=d[0]?.id??"page:default",p=new Set(d.map(e=>e.id)),h=[...r].sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),f=new Map(h.map(e=>[e.id,e])),m=new Map,b=new Set,x=((e,t,n,o)=>{const i=new Map(e.map(e=>[e.id,e])),r=t.filter(e=>{const t=i.get(e.fromId),n=i.get(e.toId);if(!t||!n)return!1;const r=o.get(e.type);return!!r.getShapeHierarchyRootId&&(r.canUseShapeHierarchy?.(e,{fromShape:t,toShape:n})??!1)});let s=!0;for(;s;){s=!1;for(const e of[...i.values()]){const t=n.get(e.type),a=t.getMinimumChildCount(e);if(a<=0)continue;const d=[...i.values()].filter(t=>t.parentId===e.id).sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),l=new Set(d.map(e=>e.id));if(new Set(d.map(e=>{const t=He(e.id,r,e=>o.get(e.type));return l.has(t)?t:e.id})).size>=a)continue;if(0===d.length){i.delete(e.id),s=!0;break}const c=[...i.values()].filter(t=>t.parentId===e.parentId).sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)).flatMap(t=>t.id===e.id?d.map(e=>e.id):[t.id]),u=new Map(c.map((e,t)=>[e,String(t+1).padStart(6,"0")])),p=t.getLocalToPageTransform(e),h=[];for(const o of d){if(e.parentId.startsWith("shape:")&&!Bt(i,n,e.parentId,o)){h.length=0;break}const t=n.get(o.type),r=ce(p.compose(t.getLocalToPageTransform(o)),t.getLocalBounds(o),{preferredRotation:o.rotation,preferredScaleXSign:o.scaleX,preferredScaleYSign:o.scaleY});if(!r){h.length=0;break}h.push({...o,...r,parentId:e.parentId,index:u.get(o.id)??e.index})}if(h.length===d.length){for(const e of h)i.set(e.id,e);for(const e of c){const t=i.get(e),n=u.get(e);t&&n&&t.index!==n&&i.set(t.id,{...t,index:n})}i.delete(e.id),s=!0;break}}}return e.flatMap(e=>{const t=i.get(e.id);return t?[t]:[]})})(h.map((e,n)=>{const o=(e=>{const n=m.get(e.id);if(n)return n;const o=[{stage:"enter",shape:e}];for(;o.length>0;){const e=o[o.length-1];if("waiting-for-parent"===e.stage){m.set(e.shape.id,e.parent.id),b.delete(e.shape.id),o.pop();continue}const n=e.shape;if(m.has(n.id)){o.pop();continue}if(b.add(n.id),n.parentId.startsWith("page:")){m.set(n.id,p.has(n.parentId)?n.parentId:l),b.delete(n.id),o.pop();continue}const i=f.get(n.parentId);i&&!b.has(i.id)&&t.get(i.type).canReceiveChild(i,n)?(o[o.length-1]={stage:"waiting-for-parent",shape:n,parent:i},m.has(i.id)||o.push({stage:"enter",shape:i})):(m.set(n.id,l),b.delete(n.id),o.pop())}return m.get(e.id)??l})(e),i={...e,parentId:o,index:e.index||String(n+1).padStart(6,"0")};return t.get(i.type).repairLoadedShape(i)??i}),s,t,n),w=new Set(x.map(e=>e.id)),I=s.filter(e=>w.has(e.fromId)&&w.has(e.toId));return[o,...d,...a,...x,...I]}function Bt(e,t,n,o){const i=e.get(n);return!!i&&t.get(i.type).canReceiveChild(i,o)}function At(e,t,n){const o=Mt(e,"document"),i=new Set,r=[];return o.records.forEach((e,o)=>{if(!wt(e))throw new rT("Invalid document record: expected object");if("string"!=typeof e.id)throw new rT("Invalid document record id");if(i.has(e.id))throw new rT(`Duplicate document record id: ${e.id}`);if(i.add(e.id),"document"!==e.typeName)if("page"!==e.typeName)if("shape"!==e.typeName)if("binding"!==e.typeName){if("asset"!==e.typeName)throw new rT(`Unsupported document record type: ${String(e.typeName)}`);r.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new rT("Invalid asset record id");if("string"!=typeof e.type)throw new rT("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:wt(e.props)?e.props:{},meta:kt(e.meta)}})(e))}else r.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new rT("Invalid binding record id");if("string"!=typeof e.type)throw new rT("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new rT(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new rT(`Invalid to id for binding ${e.id}`);const n=e.type,o=t.get(n);return{id:e.id,typeName:"binding",scope:"document",type:n,fromId:e.fromId,toId:e.toId,props:o.validateProps(e.props),meta:kt(e.meta)}})(e,n));else r.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new rT("Invalid shape record id");if("string"!=typeof e.type)throw new rT("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new rT(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:It(e.index,String(n+1).padStart(6,"0")),x:Pt(e.x,0),y:Pt(e.y,0),rotation:Pt(e.rotation,0),skewX:Pt(e.skewX,0),scaleX:Pt(e.scaleX,1),scaleY:Pt(e.scaleY,1),opacity:Math.min(1,Math.max(0,Pt(e.opacity,1))),isHidden:vt(e.isHidden,!1),isLocked:vt(e.isLocked,!1),meta:kt(e.meta),type:e.type,props:t.get(e.type).validateProps(e.props)}})(e,t,o));else r.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("page:"))throw new rT("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:It(e.name,`Page ${t+1}`),index:It(e.index,String(t+1).padStart(4,"0")),meta:kt(e.meta)}})(e,o));else r.push((e=>{if("document:main"!==e.id)throw new rT("Invalid document metadata record id");return{id:DC,typeName:"document",scope:"document",meta:kt(e.meta)}})(e))}),{schemaVersion:2,records:Et(r,t,n)}}function Rt(e){const t=Mt(e,"session").records[0];if(!wt(t))return{schemaVersion:1,records:[p()]};const n=p(),o="string"==typeof t.currentPageId&&t.currentPageId.startsWith("page:")?t.currentPageId:n.currentPageId,i=(e=>{if(!wt(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Ct(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),r=(e=>{if(!wt(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Tt(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:o,activeToolId:It(t.activeToolId,n.activeToolId),isToolLocked:"boolean"==typeof t.isToolLocked?t.isToolLocked:n.isToolLocked,editingShapeId:null,shapeEditingSession:null,pageCameraById:Object.keys(i).length>0?i:n.pageCameraById,pageSelectedShapeIdsById:Object.keys(r).length>0?r:n.pageSelectedShapeIdsById,meta:kt(t.meta)}]}}function $t(){return $C.Zero()}function Lt(e,t,n){if(n<=0)return $t();const o=t.x-e.x,i=t.y-e.y;return 0===o&&0===i?$t():new $C(o/n,i/n)}function Ft(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function Ot(e){return{...e,anchorPagePoint:e.anchorPagePoint.clone(),boundaryPagePoint:e.boundaryPagePoint.clone()}}function Dt(e,t){return e.terminal===t.terminal&&Ge(e.anchorPagePoint,t.anchorPagePoint)&&Ge(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function zt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i||!Dt(o,i))return!1}return!0}function Ut(e,t){return Dt(e,t)&&e.ownerShapeId===t.ownerShapeId&&(e.targetShapeId??null)===(t.targetShapeId??null)}function Nt(e,t,n){const o=e.get(t);o?o.push(n):e.set(t,[n])}function Wt(e,t,n){const o=e.get(t);o?o.push(n):e.set(t,[n])}function Xt(e,t,n){const o=e.get(t);if(!o)return!1;const i=o.indexOf(n);if(i<0)return!1;if(1===o.length)return e.delete(t),!0;const r=o.slice();return r.splice(i,1),e.set(t,r),!0}function Yt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Ht(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function _t(e,t,n){return"to"===e?t.toId===n.toId?t.fromId===n.fromId?t.id.localeCompare(n.id):t.fromId.localeCompare(n.fromId):t.toId.localeCompare(n.toId):Ht(t,n)}function Kt(e,t,n,o,i){const r=e.get(t);if(!r)return e.set(t,[n.id]),!0;if(r.includes(n.id))return!1;const s=r.slice();return s.splice(((e,t,n,o)=>{for(let i=0;i<e.length;i+=1){const r=o(e[i]);if(r&&_t(n,t,r)<0)return i}return e.length})(r,n,o,i),0,n.id),e.set(t,s),!0}function qt(e,t,n,o){const i=e.get(t);if(!i)return void e.set(t,[n.id]);if(i.includes(n.id))return;let r=i.length;for(let a=0;a<i.length;a+=1){const e=o(i[a]);if(void 0!==e&&e.localeCompare(n.index)>0){r=a;break}}const s=i.slice();s.splice(r,0,n.id),e.set(t,s)}function jt(e,t,n){Xt(e,t,n)}function Vt(e){return f(e.before)&&f(e.after)}function Gt(e){return y(e.before)&&y(e.after)}function Zt(e,t){const n=ce(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return n?{...t,...n}:null}function Qt(e,t,n,o){const i=e.getShapeUtil(t),r={...n,x:o.x??n.x,y:o.y??n.y,rotation:o.rotation??n.rotation,skewX:o.skewX??n.skewX,scaleX:o.scaleX??n.scaleX,scaleY:o.scaleY??n.scaleY,props:o.props?i.validateProps({...n.props,...o.props}):n.props},s=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,a=(s?e.computeShapeLocalToPageTransform(s):FC.Identity()).tryInvert();if(!a)return null;const d=ce(a.compose(i.getLocalToPageTransform(r)),i.getLocalBounds(r),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return d?{id:t.id,...d,props:o.props}:null}function Jt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i||!Ge(o,i))return!1}return!0}function en(e,t){return Jt(e.outlineVertices,t.outlineVertices)&&Je(e.pageBounds,t.pageBounds)&&Je(e.frameBounds,t.frameBounds)&&e.rotation===t.rotation&&Ge(e.rotationCenter,t.rotationCenter)&&Ge(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function tn(e){let t=(e=>{let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t})(e);for(;t<=-Math.PI/2;)t+=Math.PI;for(;t>Math.PI/2;)t-=Math.PI;return Math.abs(t)<lT?0:t}function nn(e,t){const n=e.computeShapeLocalToPageTransform(t);return Math.atan2(n.b,n.a)}function on(e,t){const n=e.selectedShapeIdsSignal.get();if(0===n.length)return{outlineVertices:[],pageBounds:null,frameBounds:null,rotation:0,rotationCenter:null,selectionAnchorPagePoint:null,hasRotation:!1,hasCompatibleRotation:!0};const o=[],i=[],r=[];let s=1/0,a=1/0,d=-1/0,l=-1/0;for(const y of n){const n=e.getShapeSignal(y).get();if(!n)continue;const c=e.getShapeUtil(n),u=Zt(e,n),p=u?c.getSelectionPagePoints(u):null;if(p&&i.push(...p),!c.contributesToSelectionFrame(n,{editor:e}))continue;r.push(n);const h=t(y);if(!h)continue;const g=c.getSelectionFramePositionedOutlineVertices(n,{editor:e}),f=g?(()=>{const t=e.computeShapePositionedToPageTransform(n);return g.map(e=>t.applyToPoint(e))})():h.outlineVertices;o.push(...f);for(const e of f)s=Math.min(s,e.x),a=Math.min(a,e.y),d=Math.max(d,e.x),l=Math.max(l,e.y)}const c=Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(d)&&Number.isFinite(l)?new LC(s,a,d-s,l-a):null,u=!(r.length>0)||function(e,t){if(0===t.length)return!0;const n=t[0],o=tn(n?nn(e,n):0);return t.every(t=>{return n=nn(e,t),i=o,Math.abs(tn(n)-tn(i))<lT;var n,i})}(e,r),p=((e,t,n)=>{if(0===t.length||!n)return 0;const o=t[0];return tn(o?nn(e,o):0)})(e,r,u),h=((e,t)=>t.some(t=>Math.abs(tn(nn(e,t)))>lT))(e,r),g=c?.center??null,f=0===o.length?null:Math.abs(p)<lT||!g?LC.FromPoints(o):LC.FromPoints(o.map(e=>$C.RotWith(e,g,-p))),m=i.length>0?LC.FromPoints(i):null;return{outlineVertices:o,pageBounds:c,frameBounds:f,rotation:p,rotationCenter:g,selectionAnchorPagePoint:f&&g?Math.abs(p)<lT?new $C(f.center.x,f.minY):$C.RotWith(new $C(f.center.x,f.minY),g,p):m?new $C(m.center.x,m.minY):null,hasRotation:h,hasCompatibleRotation:u}}function rn(e,t){return e.length===t.length&&e.every((e,n)=>{const o=t[n];return!!o&&e.id===o.id&&e.parentId===o.parentId&&e.type===o.type})}function sn(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y&&e.w===t.w&&e.h===t.h:e===t)}function an(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function dn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i||!an(o,i))return!1}return!0}function ln(e,t){return e===t||e.length===t.length&&e.every((e,n)=>e===t[n])}function cn(e,t){return e===t||(e&&t?e.a===t.a&&e.b===t.b&&e.c===t.c&&e.d===t.d&&e.e===t.e&&e.f===t.f:e===t)}function un(e,t){return e===t||(e&&t?sn(e.bounds,t.bounds)&&an(e.center,t.center)&&dn(e.corners,t.corners)&&dn(e.outlineVertices,t.outlineVertices):e===t)}function pn(e){return e?e.clone():e}function hn(e){return e?e.clone():e}function gn(e){return e?.map(e=>e.clone())}function fn(e){return e?new FC(e.a,e.b,e.c,e.d,e.e,e.f):void 0}function mn(e){if(0===e.length)return null;let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),o=Math.max(o,r.maxX),i=Math.max(i,r.maxY);return new LC(t,n,o-t,i-n)}function yn(e,t){const n=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return i<n||r<o?null:new LC(n,o,i-n,r-o)}function Sn(e,t){return t.canAutomaticallyReceiveChildren(e)}function bn(e,t,n,o){const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d>=0&&d<=1&&l>=0&&l<=1?d:null}function xn(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const o=[new $C(n.minX,n.minY),new $C(n.maxX,n.minY),new $C(n.maxX,n.maxY),new $C(n.minX,n.maxY)];for(let i=0;i<o.length;i+=1){const n=o[i],r=o[(i+1)%o.length];if(n&&r&&null!==bn(e,t,n,r))return!0}return!1}function wn(e,t){return LC.FromPoints([new $C(e.minX,e.minY),new $C(e.maxX,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function In(e){return"top_left"===e||"left"===e||"bottom_left"===e}function Pn(e){return"top_right"===e||"right"===e||"bottom_right"===e}function vn(e){return"top_left"===e||"top"===e||"top_right"===e}function kn(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function Cn({handleId:e,scaleX:t,scaleY:n}){const o=In(e)?t<0?"right":"left":Pn(e)?t<0?"left":"right":null,i=vn(e)?n<0?"bottom":"top":kn(e)?n<0?"top":"bottom":null;return"top"===i&&"left"===o?"top_left":"top"===i&&"right"===o?"top_right":"bottom"===i&&"right"===o?"bottom_right":"bottom"===i&&"left"===o?"bottom_left":i||o||e}function Tn({axis:e,startBounds:t,bounds:n,handleId:o,scale:i,isResizingFromCenter:r}){const s=Math.sign(i??1)||1;return r?s:"x"===e?In(o)?n.minX>=t.maxX?-1:1:Pn(o)?n.maxX<=t.minX?-1:1:s:vn(o)?n.minY>=t.maxY?-1:1:kn(o)?n.maxY<=t.minY?-1:1:s}function Mn({requestedBounds:e,handleId:t,actualWidth:n,actualHeight:o,scaleX:i,scaleY:r,isResizingFromCenter:s}){return new LC(s?e.center.x-n/2:In(t)?i<0?e.minX:e.maxX-n:Pn(t)?i<0?e.maxX-n:e.minX:e.center.x-n/2,s?e.center.y-o/2:vn(t)?r<0?e.minY:e.maxY-o:kn(t)?r<0?e.maxY-o:e.minY:e.center.y-o/2,n,o)}function En({bounds:e,startBounds:t,handleId:n,aspectRatio:o,isResizingFromCenter:i,scaleX:r,scaleY:s}){if(o<=0)return{bounds:e,scaleX:r??e.w/Math.max(1,t.w),scaleY:s??e.h/Math.max(1,t.h)};let a=e.w,d=e.h;const l=Math.sign(r??1)||1,c=Math.sign(s??1)||1;switch(n){case"left":case"right":d=a/o;break;case"top":case"bottom":a=d*o;break;default:{const e=a/Math.max(1,t.w),n=d/Math.max(1,t.h);Math.abs(e)>Math.abs(n)?d=a/o:a=d*o;break}}if(i){const e=t.center;return{bounds:new LC(e.x-a/2,e.y-d/2,a,d),scaleX:l*(a/Math.max(1,t.w)),scaleY:c*(d/Math.max(1,t.h))}}let u;switch(n){case"top_left":u=new LC(l<0?e.minX:e.maxX-a,c<0?e.minY:e.maxY-d,a,d);break;case"top_right":u=new LC(l<0?e.maxX-a:e.minX,c<0?e.minY:e.maxY-d,a,d);break;case"bottom_right":u=new LC(l<0?e.maxX-a:e.minX,c<0?e.maxY-d:e.minY,a,d);break;case"bottom_left":u=new LC(l<0?e.minX:e.maxX-a,c<0?e.maxY-d:e.minY,a,d);break;case"top":u=new LC(t.center.x-a/2,c<0?t.maxY:t.maxY-d,a,d);break;case"right":u=new LC(l<0?t.minX-a:t.minX,t.center.y-d/2,a,d);break;case"bottom":u=new LC(t.center.x-a/2,c<0?t.minY-d:t.minY,a,d);break;case"left":u=new LC(l<0?t.maxX:t.maxX-a,t.center.y-d/2,a,d)}return{bounds:u,scaleX:l*(a/Math.max(1,t.w)),scaleY:c*(d/Math.max(1,t.h))}}function Bn(e,t){return e.x===t.x&&e.y===t.y}function An(e){return[new $C(e.minX,e.minY),new $C(e.center.x,e.minY),new $C(e.maxX,e.minY),new $C(e.minX,e.center.y),e.center,new $C(e.maxX,e.center.y),new $C(e.minX,e.maxY),new $C(e.center.x,e.maxY),new $C(e.maxX,e.maxY)]}function Rn(e,t){return"x"===t?e.x:e.y}function $n(e,t){return"x"===t?e.minX:e.minY}function Ln(e,t){return"x"===t?e.maxX:e.maxY}function Fn(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function On(e,t){const n=Math.max(e[0],t[0]),o=Math.min(e[1],t[1]);return n<=o?[n,o]:null}function Dn(e,t){return null!==On(e,t)}function zn(e,t){return new LC(e.x+t.x,e.y+t.y,e.w,e.h)}function Un(e,t,n){return zn(e,((e,t)=>"x"===e?new $C(t,0):new $C(0,t))(t,n))}function Nn(e){return[new $C(e.minX,e.minY),new $C(e.maxX,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)]}function Wn(e,t,n){const o=n.sub(t),i=o.len2();if(i<=1e-8)return e.dist2(t);const r=Math.max(0,Math.min(1,((e.x-t.x)*o.x+(e.y-t.y)*o.y)/i));return e.dist2(new $C(t.x+o.x*r,t.y+o.y*r))}function Xn(e,t,n){const o=n.sub(t),i=o.len2();if(i<=1e-8)return t.clone();const r=Math.max(0,Math.min(1,((e.x-t.x)*o.x+(e.y-t.y)*o.y)/i));return new $C(t.x+o.x*r,t.y+o.y*r)}function Yn(e,t){if(0===t.length)return null;if(1===t.length){const n=t[0].clone();return{point:n,distanceSquared:e.dist2(n)}}let n=null,o=Number.POSITIVE_INFINITY;const i=2===t.length?1:t.length;for(let r=0;r<i;r+=1){const i=t[r],s=t[(r+1)%t.length];if(!i||!s)continue;const a=Wn(e,i,s);a>=o||(o=a,n=Xn(e,i,s))}return n?{point:n,distanceSquared:o}:null}function Hn(e){const t=[],n=new Set;for(const o of e){const e=`${o.x.toFixed(8)}:${o.y.toFixed(8)}`;n.has(e)||(n.add(e),t.push(o))}return t}function _n(e){const t=e.map(e=>({value:e.point.x,point:e})),n=e.map(e=>({value:e.point.y,point:e}));return t.sort(Kn),n.sort(Kn),{x:t,y:n}}function Kn(e,t){return e.value-t.value||e.point.id.localeCompare(t.point.id)}function qn(e,t,n,o){const i=((e,t)=>"x"===t?e.x:e.y)(e,t),r=[];for(let s=((e,t)=>{let n=0,o=e.length;for(;n<o;){const i=Math.floor((n+o)/2),r=e[i];r&&r.value<t?n=i+1:o=i}return n})(i,n);s<i.length;s+=1){const e=i[s];if(!e||e.value>o)break;r.push(e.point)}return r}function jn(e){return e.weight??(e.kind?gT[e.kind]:0)}function Vn(e,t){return`points:${e}:${[...t].sort().join("|")}`}function Gn(e,t,n){if(!t)return!0;const o=(e=>Math.min(.2*e,1.5))(n);return e.distance<t.distance-1e-8?!(t.weight>e.weight+1e-8&&t.distance-e.distance<=o):e.distance<=t.distance+o&&e.weight>t.weight+1e-8}function Zn(e,t,n,o,i={}){const r=i.releaseThreshold??o,s=Math.max(o,r),a=i.switchDistance??0;let d=null,l=null;for(const g of t){const t=Rn(g,e),a=qn(n,e,t-s,t+s);i.stats&&(i.stats.candidatePointCount+=a.length);for(const n of a){const s=Rn(n.point,e)-t,a=Math.abs(s),c={offset:s,distance:a,weight:jn(n),fromPrevious:!1};if(a<=o&&Gn(c,d,o)&&(d=c),i.previousCandidatePointIds?.has(n.id)&&a<=r){const e={...c,fromPrevious:!0};Gn(e,l,r)&&(l=e)}}}const c=l&&(!d||d.distance+a>=l.distance)?l:d;if(!c)return null;const u=c.fromPrevious&&c.distance>o?r:o,p=[];for(const[g,f]of t.entries()){const t=Rn(f,e),o=qn(n,e,t-u,t+u);for(const n of o){const o=Rn(n.point,e)-t;Math.abs(o)>u||Math.abs(o-c.offset)>1e-8||p.push({selectionPoint:f,selectionPointKind:i.selectionPointKinds?.[g],candidatePoint:n.point,candidatePointKind:n.kind,candidatePointId:n.id,candidateNodeId:n.nodeId})}}i.stats&&(i.stats.matchedPointCount+=p.length);const h=Array.from(new Set(p.map(e=>e.candidatePointId)));return p.length>0?{type:"points",id:Vn(e,h),nudge:c.offset,distance:c.distance,weight:c.weight,candidatePointIds:h,pairs:p}:null}function Qn(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new $C(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new $C(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new $C(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new $C(t.minX,t.maxY))}return n}function Jn(e,t){const n="x"===t?"horizontal":"vertical",o=[...e].sort((e,n)=>$n(e.bounds,t)-$n(n.bounds,t)),i=[];for(let r=0;r<o.length;r+=1){const e=o[r];if(!e)continue;let s=Number.POSITIVE_INFINITY;for(let a=r+1;a<o.length;a+=1){const r=o[a];if(!r)continue;const d=Ln(e.bounds,t),l=$n(r.bounds,t);if(l>s+1e-8)break;if(d>=l)continue;const c=On(Fn(e.bounds,t),Fn(r.bounds,t));c&&(s=l,i.push({direction:n,startNode:e,endNode:r,length:l-d,breadthIntersection:c}))}}return i}function eo(e,t,n,o){const i=On(Fn(t.bounds,o),Fn(n.bounds,o));return i?{direction:e,startNode:t,endNode:n,length:$n(n.bounds,o)-Ln(t.bounds,o),breadthIntersection:i}:null}function to(e,t){return[e,t.direction,t.startNode.id,t.endNode.id,t.length.toFixed(8)].join(":")}function no(e,t,n,o,i={}){const r=Fn(t,e),s=((e,t)=>"x"===t?e.w:e.h)(t,e),a=i.releaseThreshold??o,d=i.switchDistance??0;let l=o+1,c=null,u=null;const p=(e,t,n)=>{const r=Math.abs(e);0!==t.length&&(r<=o&&r<l-1e-8&&(l=r,c={type:"gaps",id:n,nudge:e,distance:r,gaps:t}),i.previousSnapId===n&&r<=a&&(!u||r<u.distance-1e-8)&&(u={type:"gaps",id:n,nudge:e,distance:r,gaps:t}))},h=n=>({id:"selection",bounds:Un(t,e,n)});for(const g of n){if(s<=g.length&&Dn(r,g.breadthIntersection)){const n=Ln(g.startNode.bounds,e)+(g.length-s)/2-$n(t,e),o=h(n);p(n,[eo(g.direction,g.startNode,o,e),eo(g.direction,o,g.endNode,e)].filter(e=>null!==e),`${to(e,g)}:center`)}const n=Ln(g.endNode.bounds,e)+g.length-$n(t,e),o=h(n);if(Dn(Fn(o.bounds,e),g.breadthIntersection)){const t=eo(g.direction,g.endNode,o,e);p(n,t?[g,t]:[],`${to(e,g)}:after`)}const i=$n(g.startNode.bounds,e)-g.length-Ln(t,e),a=h(i);if(Dn(Fn(a.bounds,e),g.breadthIntersection)){const t=eo(g.direction,a,g.startNode,e);p(i,t?[t,g]:[],`${to(e,g)}:before`)}}return u&&(!c||c.distance+d>=u.distance)?u:c}function oo(e,t,n={}){if(!e)return t;if(!t)return e;const o=n.switchDistance??0;return"points"===n.previousSnap?.type&&n.previousSnap.id===e.id?Math.abs(t.nudge)+o<Math.abs(e.nudge)?t:e:"gaps"===n.previousSnap?.type&&n.previousSnap.id===t.id?Math.abs(e.nudge)+o<Math.abs(t.nudge)?e:t:Math.abs(e.nudge)<=Math.abs(t.nudge)?e:t}function io(e,t){return e===t||e.length===t.length&&e.every((e,n)=>{const o=t[n];return!(!o||e.type!==o.type)&&("points"===e.type&&"points"===o.type?((e,t)=>e.id===t.id&&e.axis===t.axis&&e.rotation===t.rotation&&Bn(e.rotationCenter,t.rotationCenter)&&Bn(e.line[0],t.line[0])&&Bn(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const o=t.points[n];return!!o&&Bn(e,o)}))(e,o):"gaps"===e.type&&"gaps"===o.type&&function(e,t){return e.id===t.id&&e.direction===t.direction&&e.rotation===t.rotation&&Bn(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const o=t.gaps[n];return!!o&&((e,t)=>Bn(e.startEdge[0],t.startEdge[0])&&Bn(e.startEdge[1],t.startEdge[1])&&Bn(e.endEdge[0],t.endEdge[0])&&Bn(e.endEdge[1],t.endEdge[1]))(e,o)})}(e,o))})}function ro(e){return"horizontal"===e.direction?{startEdge:[new $C(e.startNode.bounds.maxX,e.startNode.bounds.minY),new $C(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new $C(e.endNode.bounds.minX,e.endNode.bounds.minY),new $C(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new $C(e.startNode.bounds.minX,e.startNode.bounds.maxY),new $C(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new $C(e.endNode.bounds.minX,e.endNode.bounds.minY),new $C(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function so(e,t,n,o){const i=t.pairs.some(({candidatePointKind:e,selectionPointKind:t})=>"center"===e&&"center"===t),r=Hn([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),s=Hn([...t.pairs.filter(({selectionPointKind:e})=>"center"===e).map(({selectionPoint:e})=>e.add(n)),...t.pairs.filter(({candidatePointKind:e})=>"center"===e).map(({candidatePoint:e})=>e.clone())]),a=i?s:r,d=i?s:Hn([...t.pairs.filter(({selectionPointKind:e})=>"center"!==e&&"edge_midpoint"!==e).map(({selectionPoint:e})=>e.add(n)),...t.pairs.filter(({candidatePointKind:e})=>"center"!==e&&"edge_midpoint"!==e).map(({candidatePoint:e})=>e.clone())]),l=uo(e,a);return{id:po(e,l,d),type:"points",axis:e,line:l,points:d,rotation:o.rotation,rotationCenter:o.rotationCenter.clone()}}function ao(e,t,n,o){return lo(e,t,n).map(t=>so(e,t,n,o))}function lo(e,t,n){const o=new Map;for(const i of t.pairs){const t=Rn(i.selectionPoint.add(n),e).toFixed(8),r=o.get(t);r?r.push(i):o.set(t,[i])}return Array.from(o.values()).map(e=>({type:"points",id:t.id,nudge:t.nudge,distance:t.distance,weight:t.weight,candidatePointIds:Array.from(new Set(e.map(e=>e.candidatePointId))),pairs:e}))}function co(e,t,n){return"x"===e?[new $C(t,n.minY),new $C(t,n.maxY)]:[new $C(n.minX,t),new $C(n.maxX,t)]}function uo(e,t){if(0===t.length)return[$C.Zero(),$C.Zero()];let n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const s of t)n=Math.min(n,s.x),o=Math.max(o,s.x),i=Math.min(i,s.y),r=Math.max(r,s.y);return"x"===e?[new $C(n,i),new $C(n,r)]:[new $C(n,i),new $C(o,i)]}function po(e,t,n){return`points:${e}:line:${t.map(e=>`${e.x.toFixed(4)},${e.y.toFixed(4)}`).join("|")}:points:${n.map(e=>`${e.x.toFixed(4)},${e.y.toFixed(4)}`).join("|")}`}function ho(e,t,n,o,i,r){return lo(e,t,n).map(t=>((e,t,n,o,i,r)=>{const s=so(e,t,n,o),a=t.pairs[0],d=Rn(a?.selectionPoint.add(n)??i.center,e),l=new Map(r.map(e=>[e.id,e.bounds])),c=[],u=new Set;for(const g of t.pairs){if(u.has(g.candidateNodeId))continue;u.add(g.candidateNodeId);const t=l.get(g.candidateNodeId);t&&c.push(...co(e,d,t))}const p=Hn([...s.points,...co(e,d,i),...c]),h=uo(e,Hn([...co(e,d,i),...c]));return{...s,id:po(e,h,p),line:h,points:p}})(e,t,n,o,i,r))}function go(e,t,n){const o="x"===e?new $C(n.x,t.y):new $C(t.x,n.y),i=Hn([n.clone(),o]),r=uo(e,i);return{id:po(e,r,i),type:"points",axis:e,line:r,points:i,rotation:0,rotationCenter:$C.Zero()}}function fo(e,t,n){const o="horizontal"===e.gaps[0]?.direction?new $C(0,n.y):new $C(n.x,0),i=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:zn(e.startNode.bounds,o)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:zn(e.endNode.bounds,o)}:e.endNode}));return{id:`gaps:${i.map(e=>`${e.startNode.id}:${e.endNode.id}:${e.length.toFixed(4)}`).join("|")}`,type:"gaps",direction:i[0]?.direction??"horizontal",gaps:i.map(ro),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function mo(e){return"points"===e.type?{...e,line:[e.line[0].clone(),e.line[1].clone()],points:e.points.map(e=>e.clone()),rotationCenter:e.rotationCenter.clone()}:{...e,gaps:e.gaps.map(e=>({startEdge:[e.startEdge[0].clone(),e.startEdge[1].clone()],endEdge:[e.endEdge[0].clone(),e.endEdge[1].clone()]})),rotationCenter:e.rotationCenter.clone()}}function yo(e,t){return 0===t.rotation?e.clone():$C.RotWith(e,t.rotationCenter,-t.rotation)}function So(e,t){return 0===t.rotation?e.clone():$C.RotWith(e,t.rotationCenter,t.rotation)}function bo(e,t){return So(e,t)}function xo(e,t,n,o,i){return 0===n?o:o+(e-t)/n*i}function wo({point:e,fromBounds:t,toBounds:n}){return new $C(xo(e.x,t.minX,t.w,n.minX,n.w),xo(e.y,t.minY,t.h,n.minY,n.h))}function Io({axis:e,bounds:t,point:n}){return"horizontal"===e?new $C(t.minX+t.maxX-n.x,n.y):new $C(n.x,t.minY+t.maxY-n.y)}function Po({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new LC(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new LC(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function vo(e){return{point:e.point,kind:e.kind??"custom",weight:e.weight}}function ko(e){const t=e.sourcePointOffsets;return t&&t.length>0?t.map(t=>e.pagePoint.add(t)):[e.pagePoint]}function Co(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&Math.abs(((e,t)=>{let n=(e-t)%Math.PI;return n<=-Math.PI/2&&(n+=Math.PI),n>Math.PI/2&&(n-=Math.PI),n})(e,t))<.001}function To(e,t,n){return t.every(t=>{const o=e.computeShapeLocalToPageTransform(t);return Co(Math.atan2(o.b,o.a),n)})}function Mo(e,t,n,o){const i=1===t.length,r=(s=t.map(t=>e.getShapeUtil(t).getAllowedSelectionResizeModes(t,{editor:e,handleId:n,isOnlyResizeTarget:i})),yT.filter(e=>s.every(t=>t.includes(e))));var s;return o?r:r.filter(e=>"free"!==e)}function Eo(e,t,n){if(0===t.length)return[];const o=1===t.length,i=t.map(t=>e.getShapeUtil(t).getSelectionResizeHandleIds(t,{editor:e,isOnlyResizeTarget:o})),r=To(e,t,n);return fT.filter(n=>i.every(e=>e.includes(n))&&Mo(e,t,n,r).length>0)}function Bo(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function Ao(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y&&e.w===t.w&&e.h===t.h:e===t)}function Ro(e,t){return e===t||(e&&t?e.localPath===t.localPath&&((e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]))(e.localDecorationPaths,t.localDecorationPaths)&&Ao(e.localBounds,t.localBounds)&&((e,t)=>e.a===t.a&&e.b===t.b&&e.c===t.c&&e.d===t.d&&e.e===t.e&&e.f===t.f)(e.localToPage,t.localToPage)&&e.strokeWidth===t.strokeWidth&&e.strokeDasharray===t.strokeDasharray:e===t)}function $o(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i)return!1;if(!(o.id===i.id&&o.usesSelectionPathOverlay===i.usesSelectionPathOverlay&&Bo(o.startPagePoint,i.startPagePoint)&&Bo(o.endPagePoint,i.endPagePoint)&&Bo(o.middlePagePoint,i.middlePagePoint)&&Ro(o.pathStyle,i.pathStyle)&&zt(o.bindingSegments,i.bindingSegments)&&o.path===i.path&&o.pageClipPath===i.pageClipPath))return!1}return!0}function Lo(e,t){return e===t||(e&&t?Ao(e.bounds,t.bounds)&&e.rotation===t.rotation&&Bo(e.rotationCenter,t.rotationCenter)&&e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius:e===t)}function Fo(e,t){return e===t||(e&&t?Ao(e.bounds,t.bounds)&&e.rotation===t.rotation&&Bo(e.rotationCenter,t.rotationCenter):e===t)}function Oo(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Fo(e[n]??null,t[n]??null))return!1;return!0}function Do(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function zo(e,t){return e.id===t.id&&Bo(e.point,t.point)&&Ao(e.bounds,t.bounds)}function Uo(e,t){return e.id===t.id&&Bo(e.point,t.point)&&Ao(e.bounds,t.bounds)}function No(e,t){return e.terminal===t.terminal&&Bo(e.point,t.point)&&Ao(e.bounds,t.bounds)}function Wo(e,t){return Bo(e.point,t.point)&&Ao(e.bounds,t.bounds)}function Xo(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Bo(e.point,t.point)&&Ao(e.bounds,t.bounds)}function Yo(e,t){return e.id===t.id&&Bo(e.point,t.point)}function Ho(e,t){return e.id===t.id&&Bo(e.point,t.point)}function _o(e,t){return e.terminal===t.terminal&&Bo(e.point,t.point)}function Ko(e,t){return Bo(e.point,t.point)}function qo(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Bo(e.point,t.point)}function jo(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let o=0;o<e.length;o+=1){const i=e[o],r=t[o];if(!i||!r||!n(i,r))return!1}return!0}function Vo({bounds:e,rotateOffset:t,referenceRotation:n,frameRotation:o}){return((e,t)=>{const n=Math.round((e-t)/Math.PI);return 1===Math.abs(n%2)})(n,o)?new $C(e.maxX+t,e.minY-t):new $C(e.minX-t,e.maxY+t)}function Go(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&jo(e.resizeHandles,t.resizeHandles,zo)&&jo(e.rotateHandles,t.rotateHandles,Uo)&&jo(e.terminalHandles,t.terminalHandles,No)&&jo(e.middleHandles,t.middleHandles,Wo)&&jo(e.customHandles,t.customHandles,Xo):e===t)}function Zo(e,t){return e===t||(e&&t?jo(e.resizeHandleAnchors,t.resizeHandleAnchors,Yo)&&jo(e.rotateHandleAnchors,t.rotateHandleAnchors,Ho)&&jo(e.terminalHandleAnchors,t.terminalHandleAnchors,_o)&&jo(e.middleHandleAnchors,t.middleHandleAnchors,Ko)&&jo(e.customHandleAnchors,t.customHandleAnchors,qo):e===t)}function Qo(e,t){return e===t||(e&&t?e.resizeHandleCount===t.resizeHandleCount&&e.rotateHandleCount===t.rotateHandleCount&&e.terminalHandleCount===t.terminalHandleCount&&e.middleHandleCount===t.middleHandleCount&&e.customHandleCount===t.customHandleCount:e===t)}function Jo(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function ei(e,t,n,o,i,r,s){const a=e.map(e=>o(e)),d=e.every(e=>i(e)),l=e.every(e=>r(e)),c=new Set(s),u=a.flatMap(e=>e.terminalHandleAnchors),p=a.flatMap(e=>e.middleHandleAnchors),h=a.flatMap(e=>e.customHandleAnchors??[]),g=u.length>0||p.length>0||h.length>0;if(!t)return{resizeHandleAnchors:[],rotateHandleAnchors:[],terminalHandleAnchors:u,middleHandleAnchors:p,customHandleAnchors:h};const{bounds:f,rotation:m,rotationCenter:y,hasCompatibleRotation:S}=t,b=e[0]?.rotation??m,x=8/n,w=14/n,I=f.w<2*x,P=f.h<2*x,v=e=>0===m?e:$C.RotWith(e,y,m),k=new $C(f.minX,f.minY),C=new $C(f.center.x,f.minY),T=new $C(f.maxX,f.minY),M=new $C(f.maxX,f.center.y),E=new $C(f.maxX,f.maxY),B=new $C(f.center.x,f.maxY),A=new $C(f.minX,f.maxY),R=new $C(f.minX,f.center.y);return{resizeHandleAnchors:d&&!g&&S?[{kind:"resize",id:"top_left",point:v(k)},...I?[]:[{kind:"resize",id:"top",point:v(C)}],...I&&P?[]:[{kind:"resize",id:"top_right",point:v(T)}],...P?[]:[{kind:"resize",id:"right",point:v(M)}],...I||P?[]:[{kind:"resize",id:"bottom_right",point:v(E)}],...I?[]:[{kind:"resize",id:"bottom",point:v(B)}],...I||P?[]:[{kind:"resize",id:"bottom_left",point:v(A)}],...P?[]:[{kind:"resize",id:"left",point:v(R)}]].filter(e=>c.has(e.id)):[],rotateHandleAnchors:!l||g||!S||I||P?[]:[{kind:"rotate",id:"bottom_left_rotate",point:v(Vo({bounds:f,rotateOffset:w,referenceRotation:b,frameRotation:m}))}],terminalHandleAnchors:u,middleHandleAnchors:p,customHandleAnchors:h}}function ti(e,t){const n=8/t,o=n/2,i=e=>new LC(e.x-o,e.y-o,n,n);return{resizeHandles:e.resizeHandleAnchors.map(e=>({...e,bounds:i(e.point)})),rotateHandles:e.rotateHandleAnchors.map(e=>({...e,bounds:i(e.point)})),terminalHandles:e.terminalHandleAnchors.map(e=>({...e,bounds:i(e.point)})),middleHandles:e.middleHandleAnchors.map(e=>({...e,bounds:i(e.point)})),customHandles:e.customHandleAnchors.map(e=>({...e,bounds:i(e.point)}))}}function ni(e){const t=e.getSelectedShapes();if(0===t.length)return null;if(t.some(e=>e.isLocked))return null;const n=t[0]?.parentId;if(!n)return null;if(t.some(e=>e.parentId!==n))return null;const o=e.getChildShapes(n),i=new Set(t.map(e=>e.id)),r=o.map((e,t)=>i.has(e.id)?t:-1).filter(e=>e>=0);return r.length!==t.length?null:{parentId:n,selectedCount:t.length,count:o.length,canMoveBackward:r.some(e=>e>0&&!i.has(o[e-1].id)),canMoveForward:r.some(e=>e<o.length-1&&!i.has(o[e+1].id))}}function oi(e){const t=e.getSelectedShapes();if(1!==t.length)return null;const[n]=t;if(!n||n.isLocked)return null;const o=e.getChildShapes(n.parentId),i=o.findIndex(e=>e.id===n.id);return i<0?null:{parentId:n.parentId,index:i,count:o.length,canMoveBackward:i>0,canMoveForward:i<o.length-1}}function ii(e,t){const n=t.map(t=>e.getShape(t)).filter(e=>!!e);if(0===n.length)return null;if(n.some(t=>t.isLocked||e.isShapeHidden(t.id)))return null;const o=n[0]?.parentId;if(!o)return null;if(n.some(e=>e.parentId!==o))return null;const i=e.getChildShapes(o),r=new Set(n.map(e=>e.id)),s=i.map((e,t)=>r.has(e.id)?t:-1).filter(e=>e>=0);return s.length!==n.length?null:{parentId:o,selectedCount:n.length,count:i.length,canMoveBackward:s.some(e=>e>0&&!r.has(i[e-1].id)),canMoveForward:s.some(e=>e<i.length-1&&!r.has(i[e+1].id))}}function ri(e,t,n,o="user"){const i=ii(e,t);if(!i)return!1;const r=e.getChildShapes(i.parentId),s=new Set(t),a=[...r];let d=!1;if("backward"===n)for(let l=1;l<a.length;l+=1){const e=a[l],t=a[l-1];e&&t&&s.has(e.id)&&!s.has(t.id)&&(a[l-1]=e,a[l]=t,d=!0)}else for(let l=a.length-2;l>=0;l-=1){const e=a[l],t=a[l+1];e&&t&&s.has(e.id)&&!s.has(t.id)&&(a[l]=t,a[l+1]=e,d=!0)}return!!d&&(e.cancelInteractionForCommand(),e.commands.updateShapes(a.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:o}),!0)}function si(e,t,n,o="user"){const i=ii(e,t);if(!i)return!1;const r=e.getChildShapes(i.parentId),s=new Set(t),a=[],d=[];for(const c of r)s.has(c.id)?a.push(c):d.push(c);if(a.length!==s.size)return!1;if(!("back"===n?i.canMoveBackward:i.canMoveForward))return!1;const l="back"===n?[...a,...d]:[...d,...a];return e.cancelInteractionForCommand(),e.commands.updateShapes(l.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:o}),!0}function ai(e){const t="string"==typeof e?{key:e}:e;return{key:ci(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}}function di(e){const t=ai(e),n=[];var o;return t.accelKey?n.push("⌘"):(t.ctrlKey&&n.push("Ctrl"),t.metaKey&&n.push("Meta")),t.altKey&&n.push("Alt"),t.shiftKey&&n.push("Shift"),n.push(1===(o=t.key).length?o.toUpperCase():o),n.join("")}function li(e,t){return!(ci(t.key)!==e.key||t.altKey!==e.altKey||t.shiftKey!==e.shiftKey||void 0!==e.accelKey&&t.accelKey!==e.accelKey||void 0!==e.ctrlKey&&t.ctrlKey!==e.ctrlKey||void 0!==e.metaKey&&t.metaKey!==e.metaKey||void 0===e.accelKey&&void 0===e.ctrlKey&&void 0===e.metaKey&&t.accelKey)}function ci(e){return e.toLowerCase()}function ui(e){return[e.key,e.altKey?"alt":null,e.ctrlKey?"ctrl":null,e.metaKey?"meta":null,e.shiftKey?"shift":null,e.accelKey?"accel":null].filter(Boolean).join("+")}function pi(e,t,n){return Math.min(n,Math.max(t,e))}function hi(e){return 0===e.length?"none":e.map(e=>`${e.start}-${e.end-1}`).join(", ")}function gi(e,t=0){if(0===e.length)return[];const n=[...e].sort((e,t)=>e.start-t.start),o=[];for(const i of n){const e=o[o.length-1];!e||i.start>e.end+t?o.push({...i}):e.end=Math.max(e.end,i.end)}return o}function fi(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function mi(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function yi(e,t,n=0){return gi(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n)}function Si(e,t){const n=[];for(const o of t)n.push(...e.slice(o.start,o.end));return n}function bi(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:Si(e,t)}}function xi(e,t){return{originScreenPoint:t.clone(),originCamera:e.getCurrentCamera()}}function wi(e,t,n){const o=n.sub(t.originScreenPoint),i=t.originCamera.z;e.setCamera({x:t.originCamera.x-o.x/i,y:t.originCamera.y-o.y/i},{source:"user"})}function Ii(e){let t=null;for(const o of e.splice(0).reverse())try{o()}catch(n){t??=n}return t}function Pi({outputBounds:e,cutoutLocalPolygons:t,localToOutput:n}){const o=t.filter(e=>e.length>=3);return 0===o.length?null:[vi((i=e.expand(100),[new $C(i.minX,i.minY),new $C(i.maxX,i.minY),new $C(i.maxX,i.maxY),new $C(i.minX,i.maxY)])),...o.map(e=>vi(e,n))].join(" ");var i}function vi(e,t){const n=t?e.map(e=>t.applyToPoint(e)):e,o=n[0];return o?[`M ${ki(o.x)} ${ki(o.y)}`,...n.slice(1).map(e=>`L ${ki(e.x)} ${ki(e.y)}`),"Z"].join(" "):""}function ki(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Ci(e,t){return e.getShapeUtil(t).getTerminalBindingPorts(t,{editor:e}).flatMap(n=>{const o=Mi(e,t,n);return o?[o]:[]})}function Ti(e,t,n){const o=e.getShapeUtil(t).getTerminalBindingPorts(t,{editor:e}).find(e=>e.id===n);return o?Mi(e,t,o):null}function Mi(e,t,n){const o=e.getShapeUtil(t),i=o.getLocalBounds(t),r=e.computeShapeLocalToPageTransform(t),s=((e,t)=>{const n=e.determinant();return!Number.isFinite(n)||Math.abs(n)<1e-12?$C.Zero():new $C((e.d*t.x-e.b*t.y)/n,(-e.c*t.x+e.a*t.y)/n).normalize()})(r,new $C(n.outwardNormal.x,n.outwardNormal.y));if(s.len2()<1e-12)return null;const a=new $C(i.x+i.w*n.normalizedAnchor.x,i.y+i.h*n.normalizedAnchor.y),d=r.applyToPoint(a),l=Math.max(64,i.w*r.getMaximumLinearScale(),i.h*r.getMaximumLinearScale()),c=o.resolveBindingPoint(t,{editor:e,rawPagePoint:d.add(s.mul(l)),oppositePagePoint:d.sub(s.mul(l))});return{id:n.id,normalizedAnchor:{...n.normalizedAnchor},pagePoint:c,pageOutwardNormal:s}}function Ei(e){return[new $C(e.minX,e.minY),new $C(e.maxX,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)]}function Bi(e,t,n,o){const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d>=0&&d<=1&&l>=0&&l<=1?d:null}function Ai(e,t,n){const o=e[t];return"number"==typeof o&&Number.isFinite(o)?o:n}function Ri(e){return Math.min(1,Math.max(0,(96-e)/96))}function $i(e,t,n){if(t.w<=0||t.h<=0||n<=0)return $C.Zero();const o=Math.min(n,32),i=Ri(e.x),r=Ri(t.w-e.x),s=Ri(e.y),a=1.25*(r-i)*o,d=1.25*(Ri(t.h-e.y)-s)*o;return 0===a&&0===d?$C.Zero():new $C(a,d)}function Li(e,t,n){const o=e.inputs.state.get();if("dragging"!==o.dragPhase||!o.currentPagePoint)return null;let i=o.currentPagePoint;if(!o.currentScreenPoint)return"apply_after_scroll"===n?null:{pagePoint:i,shiftKey:o.shiftKey,altKey:o.altKey,accelKey:o.accelKey,ctrlKey:o.ctrlKey};const r=$i(o.currentScreenPoint,e.viewportScreenSizeSignal.get(),t.elapsed),s=0!==r.x||0!==r.y;return s||"always_apply"===n?(s&&(e.panCamera(r),i=e.screenToPage(o.currentScreenPoint)),{pagePoint:i,shiftKey:o.shiftKey,altKey:o.altKey,accelKey:o.accelKey,ctrlKey:o.ctrlKey}):null}function Fi(e,t){const n=(e=>{const t=e.inputs.state.get();return"dragging"===t.dragPhase&&t.currentPagePoint?{pagePoint:t.currentPagePoint,shiftKey:t.shiftKey,altKey:t.altKey,accelKey:t.accelKey,ctrlKey:t.ctrlKey}:null})(e);n&&t(n)}function Oi(e,t,n){const o=new Set(n);if(o.has(t))return t;const i=Di(e,t);for(const s of i)if(o.has(s.ancestorId))return s.childId;const r=i[0]?.ancestorId;return r&&n.some(t=>((e,t)=>Di(e,t)[0]?.ancestorId??null)(e,t)===r)?t:i[i.length-1]?.ancestorId??t}function Di(e,t){const n=[];let o=e.getShape(t),i=t;const r=new Set([t]);for(;o?.parentId.startsWith("shape:");){const t=o.parentId;if(r.has(t))return n;r.add(t);const s=e.getShape(t);if(!s)return n;e.getShapeUtil(s).isSelectionTransformContainer(s)&&n.push({ancestorId:s.id,childId:i}),i=s.id,o=s}return n}function zi({shiftKey:e,accelKey:t}){return e||t}function Ui({ctrlKey:e}){return e}function Ni(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function Wi(e,t){return Math.round(e/t)*t}function Xi(e,t,n,o,i,r,s,a,d,l,c,u){const p=Yi(l,c),h=(({bounds:e,fromBounds:t,toBounds:n})=>{const o=wo({point:new $C(e.minX,e.minY),fromBounds:t,toBounds:n}),i=wo({point:new $C(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new LC(Math.min(o.x,i.x),Math.min(o.y,i.y),Math.abs(i.x-o.x),Math.abs(i.y-o.y))})({bounds:t.localBounds,fromBounds:n,toBounds:o}),g=So(h.center,p),f=e.getShapeUtil(t.pageShape),m=Co(t.pageShape.rotation,c),y=m?h:(()=>{const e=f.getSelectionResizeLocalBounds(t.pageShape),n=e.w*Math.abs(i),o=e.h*Math.abs(r);return new LC(g.x-n/2,g.y-o/2,n,o)})(),S=f.resizeSelectionBounds(t.pageShape,{handleId:s,isOnlyResizeTarget:a,pageCenter:g,selectionLocalBounds:y,scaleX:i,scaleY:r,isResizingFromCenter:d,selectionRotation:m?c:t.pageShape.rotation,selectionRotationCenter:m?l:g}),b=Qt(e,t.shape,t.pageShape,S);b&&Object.assign(u,b)}function Yi(e,t){return{rotation:t,rotationCenter:e}}function Hi(e,t,n,o,i,r,s,a,d,l,c){const u=Yi(d,l),p=So(_i({point:t.startLocalPagePoint,startBounds:n,scaleX:i,scaleY:r,handleId:s,isResizingFromCenter:a}),u),h=So(_i({point:t.endLocalPagePoint,startBounds:n,scaleX:i,scaleY:r,handleId:s,isResizingFromCenter:a}),u),g=t.middleLocalPagePoint?So(_i({point:t.middleLocalPagePoint,startBounds:n,scaleX:i,scaleY:r,handleId:s,isResizingFromCenter:a}),u):void 0,f=e.getShapeUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[p,h],pageMiddlePoint:g}),m=Qt(e,t.shape,t.pageShape,f);m&&Object.assign(c,m)}function _i({point:e,startBounds:t,scaleX:n,scaleY:o,handleId:i,isResizingFromCenter:r}){const s=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:In(t)?e.maxX:Pn(t)?e.minX:e.center.x)({startBounds:t,handleId:i,isResizingFromCenter:r}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:vn(t)?e.maxY:kn(t)?e.minY:e.center.y)({startBounds:t,handleId:i,isResizingFromCenter:r});return new $C(s+(e.x-s)*n,a+(e.y-a)*o)}function Ki(e,t,n,o,i){const r=t.localBounds.center,s=bo(new $C(t.pageShape.x+r.x,t.pageShape.y+r.y),{rotation:o,rotationCenter:n}),a=Qt(e,t.shape,t.pageShape,{id:t.shape.id,x:s.x-r.x,y:s.y-r.y,rotation:t.rotation+o});a&&Object.assign(i,a)}function qi(e,t,n,o,i){const r=e.getShapeUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[bo(t.startPagePoint,{rotation:o,rotationCenter:n}),bo(t.endPagePoint,{rotation:o,rotationCenter:n})],pageMiddlePoint:t.middlePagePoint?bo(t.middlePagePoint,{rotation:o,rotationCenter:n}):void 0}),s=Qt(e,t.shape,t.pageShape,r);s&&Object.assign(i,s)}function ji(e,t){let n=null;for(const o of t){const t=e.getShape(o);if(!t)return null;if(n){if(t.parentId!==n)return null}else n=t.parentId}return n}function Vi(e,t,n){const o=n?e.getContainingShapeParentIdAtPoint(t,n):e.getContainingShapeParentId(t);if(!o)return null;const i=ji(e,t);if(!i||!i.startsWith("shape:")||o===i)return o;const r=e.getShape(i);return r&&e.getShapeUtil(r).canReceiveChildren(r)?e.getShapeUtil(r).canAutomaticallyReceiveChildren(r)?n?o:t.every(t=>{const n=e.getShapeContainment(r.id,t);return"inside"===n||"intersecting"===n})?i:o:i:o}function Gi(e,t,n){const o=Vi(e,t,n);o&&t.some(t=>e.getShape(t)?.parentId!==o)&&e.commands.reparentShapes({ids:[...t],parentId:o})}function Zi(e,t,n,o={}){let i=!0;return(e=>{const r=new AC(e,()=>{t.get(),i&&!1===o.fireImmediately?i=!1:(i=!1,n())},void 0);return r.attach(),()=>r.detach()})(e)}function Qi(e,t){return e.getAvailability?.(t)??"enabled"}function Ji({editor:e,toolState:t,selectionState:n}){return{editor:e,selection:{selectedShapeIds:e.getSelectedShapeIds(),selectedShapes:e.getSelectedShapes(),count:n.count,singleShapeType:n.singleShapeType,commonShapeType:n.commonShapeType,canFlip:n.canFlipSelection,canResetRotation:n.canResetSelectionRotation,isMixedFrameAndPointHandleSelection:n.isMixedFrameAndPointHandleSelection},tool:{activeToolId:t.activeToolId,isToolLocked:t.isToolLocked}}}function er(e=[]){const t=new sM;for(const n of e)t.registerAction(n);return t}function tr(e){return{id:e,kind:"value"}}function nr(e){return!(!e||"object"!=typeof e)&&("string"==typeof e.id&&("api"===e.kind||"service"===e.kind||"value"===e.kind))}function or(e){return Object.freeze({id:e})}function ir(e=[]){return new dM(e)}function rr(e,t){const n=new Set;for(const o of e){if(n.has(o))throw new Error(`Duplicate ${t} id: ${o}.`);n.add(o)}}function sr(e,t,n){const o=(e.order??0)-(t.order??0);return 0===o&&e.id&&t.id?(n?.get(e.id)??0)-(n?.get(t.id)??0):o}function ar(e=[]){const t=new lM;for(const n of e)t.registerContribution(n);return t}function dr(e=[]){return new cM(e)}function lr(e=[]){return new uM(e)}function cr(e,t){return pr(e).some(e=>e.provides?.some(e=>e.id===t.id))}function ur(e){const t=pr(e);return hr(t.map(({id:e})=>e),"canvas plugin id"),hr(t.flatMap(e=>(e.provides??[]).map(({id:e})=>e)),"canvas plugin capability provider"),(e=>{const t=new Map(e.map(e=>[e.id,e])),n=new Map(e.flatMap(e=>(e.provides??[]).map(t=>[t.id,e]))),o=[],i=new Set,r=new Set,s=e=>{if(!r.has(e.id)){if(i.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);i.add(e.id);for(const o of e.requires??[]){const i=nr(o)?n.get(o.id):t.get(o.id);if(!i){const t=nr(o)?`capability "${o.id}"`:`plugin "${o.id}"`;throw new Error(`Canvas plugin "${e.id}" requires missing ${t}.`)}s(i)}i.delete(e.id),r.add(e.id),o.push(e)}};for(const a of e)s(a);return o})(t)}function pr(e){return e.flat(1/0)}function hr(e,t){const n=new Set;for(const o of e){if(n.has(o))throw new Error(`Duplicate ${t}: ${o}.`);n.add(o)}}function gr(e){return{id:e,kind:"api"}}function fr(e){return{id:e,kind:"service"}}function mr(e){return Object.freeze({id:e})}function yr(e,t={}){const n=new Set,o=new Set,i=[];for(const r of e){for(const e of r.groups){const s=Sr(t.dedupeActionIdsAcrossSources?e.items.filter(e=>!("actionId"in e&&n.has(e.actionId))):e.items);if(0===s.length)continue;const a=r.groupIdPrefix?`${r.groupIdPrefix}.${e.id}`:e.id;if(o.has(a))throw new Error(`Duplicate merged toolbar group id: ${a}.`);o.add(a),i.push({...e,id:a,items:s})}if(t.dedupeActionIdsAcrossSources)for(const e of r.groups)for(const t of e.items)"actionId"in t&&n.add(t.actionId)}return i}function Sr(e){const t=[];for(const n of e)("separator"!==n.kind||0!==t.length&&"separator"!==t.at(-1)?.kind)&&t.push(n);return"separator"===t.at(-1)?.kind&&t.pop(),t}function br(e,t){const n=new Set;for(const o of e){if(n.has(o))throw new Error(`Duplicate ${t} id: ${o}.`);n.add(o)}}function xr(e=[]){const t=new fM;for(const n of e)t.registerContribution(n);return t}function wr(){const e=Nk(mM);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function Ir(e){const t=Uk(t=>Zi("useValue",e,t,{fireImmediately:!1}),[e]),n=Uk(()=>e.get(),[e]);return jk(t,n,n)}function Pr({children:e,className:t,dataUi:n}){const o=wr(),i=Kk(null);return Hk(()=>Zi("PageSpace.transform",o.pageTransformSignal,()=>{const e=i.current;e&&(e.style.transform=o.pageTransformSignal.get().toCssString())}),[o]),Gk("div",{ref:i,"data-ui":n,className:t,style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transformOrigin:"0 0"},children:e})}function vr(e=[]){const t=new yM;return t.registerCanvasRenderPlugins(e),t}function kr(){return Nk(bM)}function Cr(){const e="undefined"!=typeof window&&"1"===new URLSearchParams(window.location.search).get("renderHostDebug");
|
|
2
|
+
return Zk("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:[Gk(Pr,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:Gk(wM,{})}),e?Gk(IM,{}):null]})}function Tr(e,t,n){const o=new Set;let i=t.parentId;for(;i.startsWith("shape:");){const t=i;if(t===e)return!0;if(o.has(t))return!1;o.add(t);const r=n.get(t);if(!r)return!1;i=r.parentId}return!1}function Mr({Component:e,editor:t,shape:n}){
|
|
3
|
+
return Gk("div",{"aria-hidden":"true","data-ui":"shape-hover-decoration",style:{position:"absolute",inset:0,pointerEvents:"none"},children:Gk(e,{shape:n,editor:t,strokeWidth:2/Ir(t.cameraZoomSignal)})})}function Er(){
|
|
4
|
+
return Gk("div",{"data-ui":"transform-descendant-ancestor-boundary",style:{position:"absolute",inset:0,border:"1px dashed #64748b",pointerEvents:"none"}})}function Br(){
|
|
5
|
+
return Gk("div",{"data-ui":"shape-drop-target-label",style:{position:"absolute",left:10,top:10,display:"flex",alignItems:"center",height:24,padding:"0 10px",borderRadius:999,background:"#2563eb",color:"white",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:12,fontWeight:700,lineHeight:"24px",boxShadow:"0 10px 24px rgba(37, 99, 235, 0.24)",whiteSpace:"nowrap",pointerEvents:"none"},children:"Drop into container"})}function Ar({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?Gk(Vk,{children:e}):t.reduceRight((e,t)=>Gk(Rr,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function Rr({ancestorId:e,children:t,shapeElementToPage:n}){const o=wr(),i=Ir(o.getShapeSignal(e));if(!i)return Gk(Vk,{children:t});const r=((e,t,n)=>{const o=e.getShapeUtil(t).getChildClipLocalPolygons(t);if(!o)return null;const i=e.computeShapeRenderToPageTransform(t),r=n.tryInvert();if(!r)return null;const s=o.filter(e=>e.length>=3).map(e=>e.map(e=>r.applyToPoint(i.applyToPoint(e)))).filter(e=>e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y)));return 0===s.length?null:1===s.length?`polygon(${s[0].map(Fr).join(", ")})`:`path("${s.map(Lr).join(" ")}")`})(o,i,n);return r?Gk("div",{"data-ui":"shape-clip-boundary","data-clip-ancestor-id":e,style:{position:"absolute",inset:0,width:"100%",height:"100%",clipPath:r,WebkitClipPath:r,overflow:"visible"},children:t}):Gk(Vk,{children:t})}function $r(e,t,n){const o=e.computeShapeRenderBounds(t),i=n.compose(FC.Translate(o.x,o.y));return{left:0,top:0,width:o.w,height:o.h,transform:i.toCssString(),transformOrigin:"0 0",elementToPage:i}}function Lr(e){return e.map((e,t)=>`${0===t?"M":"L"} ${Or(e.x)} ${Or(e.y)}`).concat("Z").join(" ")}function Fr(e){return`${Or(e.x)}px ${Or(e.y)}px`}function Or(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Dr(e,t){return(e.order??0)-(t.order??0)}function zr(e=[]){const t=new CM;return t.registerCanvasRenderPlugins(e),t}function Ur(){return Nk(MM)}function Nr(e,t){return"binding-preview"===e?{underlay:{"data-binding-preview-segment-underlay":t},segment:{"data-binding-preview-segment":t}}:"terminal-binding-guide"===e?{underlay:{"data-terminal-binding-guide-underlay":t},segment:{"data-terminal-binding-guide":t}}:{underlay:{"data-selection-binding-segment-underlay":t},segment:{"data-selection-binding-segment":t}}}function Wr({start:e,end:t,startInset:n,endInset:o,strokeWidth:i,dashSize:r,gapSize:s,kind:a,terminal:d}){const l=(({start:e,end:t,startInset:n,endInset:o})=>{const i=t.x-e.x,r=t.y-e.y,s=Math.hypot(i,r);if(s<1e-6)return null;const a=Math.max(0,s/2-.001),d=Math.min(n,a),l=Math.min(o,a),c=i/s,u=r/s;return{start:{x:e.x+c*d,y:e.y+u*d},end:{x:t.x-c*l,y:t.y-u*l}}})({start:e,end:t,startInset:n,endInset:o});if(!l)return null;const c=Nr(a,d);
|
|
6
|
+
return Zk("g",{style:{pointerEvents:"none"},children:[Gk("line",{...c.underlay,x1:l.start.x,y1:l.start.y,x2:l.end.x,y2:l.end.y,fill:"none",stroke:BM,strokeLinecap:"round",strokeWidth:2.2*i}),Gk("line",{...c.segment,x1:l.start.x,y1:l.start.y,x2:l.end.x,y2:l.end.y,fill:"none",stroke:EM,strokeDasharray:`${r} ${s}`,strokeLinecap:"round",strokeWidth:i})]})}function Xr({path:e,strokeWidth:t,dashSize:n,gapSize:o,kind:i,terminal:r}){const s=Nr(i,r);
|
|
7
|
+
return Zk("g",{style:{pointerEvents:"none"},children:[Gk("path",{...s.underlay,d:e,fill:"none",stroke:BM,strokeLinecap:"round",strokeWidth:2.2*t}),Gk("path",{...s.segment,d:e,fill:"none",stroke:EM,strokeDasharray:`${n} ${o}`,strokeLinecap:"round",strokeWidth:t})]})}function Yr({editor:e,shape:t,stroke:n,fill:o,strokeWidth:i}){const r=e.getShapePageOutlineVertices(t.id);return 0===r.length?null:Gk("polygon",{points:r.map(e=>`${e.x},${e.y}`).join(" "),fill:o,stroke:n,strokeWidth:i,strokeLinejoin:"round",strokeLinecap:"round"})}function Hr({frame:e,handleId:t,zoom:n}){const o=((e,t)=>{const{bounds:n}=e;switch(t){case"top":return{x1:n.minX,y1:n.minY,x2:n.maxX,y2:n.minY};case"right":return{x1:n.maxX,y1:n.minY,x2:n.maxX,y2:n.maxY};case"bottom":return{x1:n.minX,y1:n.maxY,x2:n.maxX,y2:n.maxY};case"left":return{x1:n.minX,y1:n.minY,x2:n.minX,y2:n.maxY};default:return null}})(e,t);return o?Gk("line",{"data-selection-resize-border":t,x1:o.x1,y1:o.y1,x2:o.x2,y2:o.y2,fill:"none",stroke:"transparent",strokeWidth:12/n,strokeLinecap:"butt",style:{cursor:_r(t,e.rotation),pointerEvents:"stroke"}}):null}function _r(e,t){const n=(((e=>{switch(e){case"top_left":case"bottom_right":return Math.PI/4;case"top":case"bottom":return Math.PI/2;case"top_right":case"bottom_left":return 3*Math.PI/4;case"right":case"left":return 0}})(e)+t)%Math.PI+Math.PI)%Math.PI/(Math.PI/4);return XM[Math.round(n)%XM.length]??"default"}function Kr({handle:e,strokeWidth:t}){
|
|
8
|
+
return Gk("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,"data-selection-custom-handle-visual":"default",x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:3,ry:3,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}function qr({dataPrefix:e,pathStyle:t,stroke:n,strokeWidth:o}){
|
|
9
|
+
return Zk(Vk,{children:[Gk("path",{"data-selection-overlay":e,d:t.localPath,fill:"none",stroke:n,strokeWidth:o,strokeDasharray:t.strokeDasharray,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"}),t.localDecorationPaths.map((t,i)=>Gk("path",{"data-selection-overlay":`${e}-decoration`,d:t,fill:"none",stroke:n,strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"},`${i}:${t}`))]})}function jr(e,t){const n=Math.max(e[0],t[0]),o=Math.min(e[1],t[1]);return n<=o?[n,o]:null}function Vr(){
|
|
10
|
+
return Gk("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:Gk(Pr,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:Gk(JM,{})})})}function Gr(e=[]){const t=new tE;return t.registerCanvasRenderPlugins(e),t}function Zr(e){const t=(e=>e instanceof HTMLElement?e:null)(e);return!!t&&(!!t.isContentEditable||!!t.closest('[contenteditable="true"]')||t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)}function Qr(e){return(e??("undefined"==typeof document?null:document))?.querySelector(oE)??null}function Jr(e,t,n){return e.screenToPage(((e,t=Qr())=>{if(!t)return new $C(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new $C(e.clientX-n.left,e.clientY-n.top)})(t,n))}function es(e,t){return{type:"keyboard",name:e,...ns(t),code:t.code}}function ts(e,t,n){e.getShapeEditingSession()?n||e.handleInteractionEvent(es("key_up",t)):n||e.dispatch(es("key_up",t))}function ns(e){return{key:e.key,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}}function os(e){return"Space"===e.code}function is(e,t){const n=t.ownerDocument;return e===n||e===n.body||e===n.documentElement||e instanceof Node&&t.contains(e)}function rs(e,t,n,o){return{type:"pointer",name:e,timestamp:t.timeStamp,pointerId:t.pointerId,button:t.button,buttons:t.buttons,pointerType:(i=t.pointerType,"touch"===i||"pen"===i?i:"mouse"),clickCount:t.detail,screenPoint:n,pagePoint:o,pressure:t.pressure,shiftKey:t.shiftKey,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,accelKey:t.metaKey||t.ctrlKey};var i}function ss(e,t){return new $C(e.clientX-t.left,e.clientY-t.top)}function as(e,t){return e instanceof Node&&t.contains(e)}function ds(e,t){return(e%t+t)%t}function ls(){const e=Ir(wr().currentCameraSignal);
|
|
11
|
+
return Zk("svg",{"data-ui":"canvas-background","aria-hidden":"true",className:"land-canvas__grid-background",xmlns:"http://www.w3.org/2000/svg",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},children:[Gk("defs",{children:iE.map(({min:t,mid:n,step:o})=>{const i=15*o*e.z,r=((e,t)=>({x:ds(.5-e.x*e.z,t),y:ds(.5-e.y*e.z,t)}))(e,i),s=e.z<n?(a=((e,[t,n],[o,i])=>o+(e-t)/(n-t)*(i-o))(e.z,[t,n],[0,1]),Math.max(0,Math.min(1,a))):1;var a;
|
|
12
|
+
return Gk("pattern",{id:`land-canvas-grid-${o}`,width:i,height:i,patternUnits:"userSpaceOnUse",children:Gk("circle",{cx:r.x,cy:r.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:s})},o)})}),iE.map(({step:e})=>Gk("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function cs(e,t,n,o){return n||"hand"===e&&t?"grabbing":o||"hand"===e?"grab":"select"===e?void 0:"crosshair"}function us({canvasComponents:e,canvasProviders:t,domEventGuardRegistry:n,onContextMenuRequest:o,overlayRegistry:i,rendererRegistry:r,showGrid:s=!1}={}){const a=wr(),d=_k(()=>r??vr(),[r]),l=_k(()=>i??zr(),[i]),c=_k(()=>n??Gr(),[n]),u=Ir(a.toolStateSignal).activeToolId,p=Ir(a.shapeEditingStateSignal).session,h=Ir(a.inputs.isSpacePressed)&&null===p,{containerRef:g,handlers:f,isPointerActive:m,isCameraPanning:y,surfaceCursor:S}=function({activeDomEventGuards:e,activeToolId:t,editor:n,onContextMenuRequest:o,shapeEditingSession:i}){const r=Kk(null),s=Kk(null),a=Kk(null),d=Kk(null),l=Kk(null),c=Kk(null),u=Kk(null),[p,h]=qk(!1),[g,f]=qk(!1),[m,y]=qk(void 0),S=null!==i;Wk(()=>{("select"!==t||S)&&n.setHoveredShapeId(null)},[t,n,S]);const b=Uk(()=>{null!==l.current&&(cancelAnimationFrame(l.current),l.current=null),c.current=null},[]),x=Uk(e=>{if(null===a.current)return void b();const t=c.current??e;c.current=e,n.dispatch({type:"tick",timestamp:e,elapsed:e-t}),l.current=requestAnimationFrame(x)},[n,b]),w=Uk(()=>{null===l.current&&(c.current=null,l.current=requestAnimationFrame(x))},[x]);return Wk(()=>{const o=r.current;if(!o)return;let i=null;const l=()=>{const e=o.getBoundingClientRect(),t={left:e.left,top:e.top};return s.current=t,t},c=()=>s.current??l(),p=()=>{null!==i&&(window.cancelAnimationFrame(i),i=null)},g=({clientPoint:e,target:i})=>{if(p(),!e||null!==a.current||"select"!==t||S)return void n.setHoveredShapeId(null);const r=o.getBoundingClientRect();if(!as(i,o)||e.x<r.left||e.x>r.right||e.y<r.top||e.y>r.bottom)return void n.setHoveredShapeId(null);const s=c(),d=new $C(e.x-s.left,e.y-s.top),l=n.hitTestShape(n.screenToPage(d));if(!l)return void n.setHoveredShapeId(null);const u=n.getShapeUtil(l).getHoverTargetId(l,{editor:n});n.setHoveredShapeId(n.getOutermostSelectableShapeId(u))},m=()=>{const e=u.current;g({clientPoint:e,target:e?document.elementFromPoint(e.x,e.y):null})},x=()=>{null===i&&(i=window.requestAnimationFrame(()=>{i=null,m()}))},w=(t,i)=>"handled"===e.handle({name:t,event:i,editor:n,container:o}),I=()=>{if(!S)return void y(void 0);const t=u.current;y(t?e.getCursor({clientPoint:t,element:document.elementFromPoint(t.x,t.y),editor:n,container:o}):void 0)},P=(e,t)=>{if(!r.current)return;const o=ss(t,c());n.dispatch(rs(e,t,o,n.screenToPage(o)))},v=()=>{n.setViewportScreenSize({w:o.clientWidth,h:o.clientHeight})};l(),v();const k=e=>{if(w("key_down",e))return;if(n.getShapeEditingSession()){const t=Zr(e.target);return t||"Escape"!==e.key||e.altKey||e.ctrlKey||e.metaKey?!t&&n.handleInteractionEvent(es("key_down",e))?(e.preventDefault(),void e.stopPropagation()):void(t||"Enter"!==e.key||!e.metaKey&&!e.ctrlKey||n.completeEditing("user")):(e.preventDefault(),e.stopPropagation(),n.cancelInteractionAndClearTransients("escape"),void(n.getShapeEditingSession()&&n.cancelEditing("user")))}if(Zr(e.target))return;if(os(e)){if(!is(e.target,o))return;e.preventDefault()}const t=n.shortcuts.getTargetForEvent(ns(e));t&&"action"!==t.type&&e.preventDefault(),n.dispatch(es("key_down",e))},C=e=>{if(os(e)&&n.inputs.pressedKeyCodes.get().has(e.code)&&!n.getShapeEditingSession())return e.preventDefault(),void ts(n,e,!1);w("key_up",e)||os(e)&&!is(e.target,o)||ts(n,e,Zr(e.target))},T=()=>{a.current=null,d.current=null,h(!1),f(!1),n.setHoveredShapeId(null),b(),n.dispatch({type:"cancel",reason:"blur"})},M=e=>{if(w("wheel",e))return;e.preventDefault();const t={x:e.clientX,y:e.clientY};u.current=t;const o=ss(e,c()),i=n.screenToPage(o);n.dispatch(((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new $C(e.deltaX,e.deltaY),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}))(e,o,i)),g({clientPoint:t,target:document.elementFromPoint(t.x,t.y)})},E=e=>{if(u.current={x:e.clientX,y:e.clientY},g({clientPoint:u.current,target:e.target}),I(),e.pointerId!==a.current){const t=ss(e,c());if(n.inputs.setCurrentPointerPoint({timestamp:e.timeStamp,screenPoint:t,pagePoint:n.screenToPage(t),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}),w("pointer_move",e))return;if(!((e,t)=>{const n=t.getBoundingClientRect();return e.clientX>=n.left&&e.clientX<=n.right&&e.clientY>=n.top&&e.clientY<=n.bottom})(e,o)||!as(e.target,o)||Zr(e.target))return;return void P("pointer_move",e)}const t={clientX:e.clientX,clientY:e.clientY,buttons:e.buttons,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey};var i,r;r=t,(i=d.current)&&i.clientX===r.clientX&&i.clientY===r.clientY&&i.buttons===r.buttons&&i.shiftKey===r.shiftKey&&i.altKey===r.altKey&&i.ctrlKey===r.ctrlKey&&i.metaKey===r.metaKey||(d.current=t,P("pointer_move",e))},B=(e,t)=>{t.pointerId===a.current&&(a.current=null,d.current=null,h(!1),f(!1),b(),o.hasPointerCapture(t.pointerId)&&o.releasePointerCapture(t.pointerId),P(e,t),"pointer_up"===e?m():n.setHoveredShapeId(null))},A=()=>{u.current=null,n.setHoveredShapeId(null),I()},R=e=>{u.current={x:e.clientX,y:e.clientY},window.setTimeout(I,0),e.pointerId===a.current?B("pointer_up",e):w("pointer_up",e)},$=e=>{u.current={x:e.clientX,y:e.clientY},I(),e.pointerId===a.current?B("pointer_cancel",e):w("pointer_cancel",e)},L=new ResizeObserver(()=>{l(),v(),x()}),F=()=>{l(),x()},O=n.listen(x);window.addEventListener("keydown",k),window.addEventListener("keyup",C),window.addEventListener("blur",T),window.addEventListener("scroll",F,{passive:!0,capture:!0}),window.addEventListener("pointermove",E,{passive:!0}),window.addEventListener("pointerup",R),window.addEventListener("pointercancel",$),o.addEventListener("pointerleave",A),o.addEventListener("wheel",M,{passive:!1}),L.observe(o);const D=window.requestAnimationFrame(I);return x(),()=>{b(),p(),O(),h(!1),f(!1),n.setHoveredShapeId(null),window.cancelAnimationFrame(D),window.removeEventListener("keydown",k),window.removeEventListener("keyup",C),window.removeEventListener("blur",T),window.removeEventListener("scroll",F,!0),window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",R),window.removeEventListener("pointercancel",$),o.removeEventListener("pointerleave",A),o.removeEventListener("wheel",M),L.disconnect()}},[e,t,n,S,b]),{containerRef:r,handlers:{onPointerDown:Uk(t=>{const o=r.current;if(!o)return;if(u.current={x:t.clientX,y:t.clientY},2===t.button)return void o.focus();if("handled"===e.handle({name:"pointer_down",event:t.nativeEvent,editor:n,container:o}))return;if(Zr(t.target))return;t.preventDefault(),o.focus(),o.setPointerCapture(t.pointerId);const i=o.getBoundingClientRect();s.current={left:i.left,top:i.top},a.current=t.pointerId,h(!0),f(1===t.button||0===t.button&&n.inputs.isSpacePressed.get()&&!n.getShapeEditingSession()),d.current=null,w();const l=ss(t,s.current);n.setHoveredShapeId(null),n.dispatch(rs("pointer_down",t,l,n.screenToPage(l)))},[e,n,w]),onAuxClick:Uk(e=>{1!==e.button||Zr(e.target)||(e.preventDefault(),e.stopPropagation())},[]),onContextMenu:Uk(e=>{const t=r.current;if(!t||!o||Zr(e.target))return;e.preventDefault(),e.stopPropagation();const i=t.getBoundingClientRect();if(s.current={left:i.left,top:i.top},null!==a.current){const o=a.current;t.hasPointerCapture(o)&&t.releasePointerCapture(o),a.current=null,d.current=null,h(!1),f(!1),b();const i=ss(e,s.current);n.dispatch({type:"pointer",name:"pointer_cancel",timestamp:e.timeStamp,pointerId:o,button:e.button,buttons:0,pointerType:n.inputs.state.get().pointerType??"mouse",screenPoint:i,pagePoint:n.screenToPage(i),pressure:0,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey,clickCount:e.detail})}if(n.getShapeEditingSession())return;t.focus();const l=ss(e,s.current),c=n.screenToPage(l),u=n.hitTestShape(c);let p;if(u){const e=n.getSelectedShapeIds(),t=e.find(e=>e===u.id||n.getDescendantShapeIds(e).includes(u.id))??n.getOutermostSelectableShapeId(u.id),o=e.includes(t);o||n.commands.setSelectedShapeIds([t],{source:"user"}),p={anchor:{screenPoint:l,pagePoint:c},target:{type:"selection",selectedShapeIds:o?e:[t]}}}else p={anchor:{screenPoint:l,pagePoint:c},target:{type:"canvas"}};o(p)},[n,o,b])},isPointerActive:p,isCameraPanning:g,surfaceCursor:m}}({activeDomEventGuards:c,activeToolId:u,editor:a,onContextMenuRequest:o,shapeEditingSession:p});
|
|
13
|
+
return Zk("div",{ref:g,"data-ui":nE,className:"land-canvas__surface",tabIndex:0,style:{cursor:S??cs(u,m,y,h)},...f,children:[s?Gk(ls,{}):null,Gk(bM.Provider,{value:d,children:Gk(MM.Provider,{value:l,children:Zk(ps,{providers:t,children:[
|
|
14
|
+
Gk(Cr,{}),e?.map(({id:e,component:t})=>Gk(t,{},e)),
|
|
15
|
+
Gk(Vr,{})]})})})]})}function ps({children:e,providers:t}){
|
|
16
|
+
return Gk(Vk,{children:t?.reduceRight((e,{id:t,component:n})=>Gk(n,{children:e},t),e)??e})}function hs(e){const t=e.trim();if(!t)return null;const n=(e=>/^[a-z][a-z0-9+.-]*:/i.test(e))(t)?t:`https://${t}`;return gs(n)?n:null}function gs(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol||"mailto:"===t.protocol}catch{return!1}}function fs(e){gs(e)&&window.open(e,"_blank","noopener,noreferrer")}function ms(e){return{type:"doc",content:e.split("\n").map(e=>({type:"paragraph",content:e.length>0?[{type:"text",text:e}]:[]}))}}function ys(e){return e.content.map(e=>vs(e)).join("\n")}function Ss(e){if(!e||"object"!=typeof e)return ms("");const t=e,n=Array.isArray(t.content)?t.content.map(e=>Es(e,0)).filter(e=>null!==e):[];return{type:"doc",attrs:Ds(t.attrs),content:n}}function bs(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>Cs(e)).join("")??"",n=ws(e);return`<p style="${n?`margin:0;text-align:${n}`:"margin:0"}">${t.length>0?t:"<br>"}</p>`})(e)).join("")}function xs(e){return"text"===e.type&&"string"==typeof e.text}function ws(e){if("paragraph"===e.type)return Os(e.attrs?.textAlign)}function Is(e,t){const n=e?.some(e=>"code"===e.type)?void 0:t;if(!(e&&0!==e.length||n))return;const o=n?{backgroundColor:n}:{},i=new Set;for(const r of e??[])switch(r.type){case"bold":case"strong":o.fontWeight=700;break;case"italic":case"em":o.fontStyle="italic";break;case"strike":case"s":i.add("line-through");break;case"underline":case"u":i.add("underline");break;case"textStyle":{const e=Rs(r.attrs);void 0!==e?.color&&(o.color=e.color),void 0!==e?.backgroundColor&&(o.backgroundColor=e.backgroundColor),void 0!==e?.fontFamily&&(o.fontFamily=e.fontFamily),void 0!==e?.fontSize&&(o.fontSize=e.fontSize),void 0!==e?.lineHeight&&(o.lineHeight=e.lineHeight);break}}return i.size>0&&(o.textDecorationLine=["line-through","underline"].filter(e=>i.has(e)).join(" ")),Object.keys(o).length>0?o:void 0}function Ps(e){if(e&&0!==e.length)for(const t of e){if("link"!==t.type)continue;const e=t.attrs?.href;return"string"==typeof e?e:void 0}}function vs(e){return xs(e)?e.text:e.content?.map(e=>vs(e)).join("")??""}function ks(e){const t=[];return void 0!==e.color&&t.push(`color:${e.color}`),void 0!==e.backgroundColor&&t.push(`background-color:${e.backgroundColor}`),void 0!==e.fontFamily&&t.push(`font-family:${e.fontFamily}`),void 0!==e.fontSize&&t.push(`font-size:${e.fontSize}`),void 0!==e.fontWeight&&t.push(`font-weight:${String(e.fontWeight)}`),void 0!==e.fontStyle&&t.push(`font-style:${e.fontStyle}`),void 0!==e.lineHeight&&t.push(`line-height:${e.lineHeight}`),void 0!==e.textDecorationLine&&t.push(`text-decoration-line:${e.textDecorationLine}`),t.join(";")}function Cs(e){if(xs(e)){const t=Is(e.marks),n=Ps(e.marks),o=Ts(e.text),i=t?`<span style="${Ms(ks(t))}">${o}</span>`:o;return n&&gs(n)?`<a href="${Ms(n)}" target="_blank" rel="noopener noreferrer">${i}</a>`:t?i:o}return e.content?.map(e=>Cs(e)).join("")??""}function Ts(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function Ms(e){return Ts(e).replaceAll('"',""")}function Es(e,t){if(!e||"object"!=typeof e)return null;const n=e,o="string"==typeof n.type?n.type:"paragraph",i=Array.isArray(n.content)?n.content.map(e=>function(e,t){if(!e||"object"!=typeof e||t>8)return null;const n=e;if("text"===n.type){const e=(e=>({type:"text",text:"string"==typeof e.text?e.text:"",marks:Array.isArray(e.marks)?e.marks.map(Bs).filter(e=>null!==e):void 0}))(n);return e.text.length>0?e:null}return Es(n,t)}(e,t+1)).filter(e=>null!==e):[];return{type:o,attrs:As(o,n.attrs),content:i}}function Bs(e){if(!e||"object"!=typeof e)return null;const t=e;if("string"!=typeof t.type)return null;if("link"===t.type){const e=Ds(t.attrs),n=e?.href;return"string"==typeof n&&gs(n)?{type:"link",attrs:{...e,href:n}}:null}if("textStyle"===t.type){const e=Rs(t.attrs);return e?{type:"textStyle",attrs:e}:null}return{type:t.type,attrs:Ds(t.attrs)}}function As(e,t){const n=Ds(t);if("paragraph"!==e)return n;const o={...n};delete o.textAlign;const i=t&&"object"==typeof t&&!Array.isArray(t)?Os(t.textAlign):void 0;return void 0!==i&&(o.textAlign=i),Object.keys(o).length>0?o:void 0}function Rs(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e,n={color:$s(t.color,128),backgroundColor:$s(t.backgroundColor,128),fontFamily:$s(t.fontFamily,256),fontSize:Ls(t.fontSize),lineHeight:Fs(t.lineHeight)},o=Object.entries(n).filter(e=>void 0!==e[1]);return o.length>0?Object.fromEntries(o):void 0}function $s(e,t){if("string"!=typeof e)return;const n=e.trim();return 0===n.length||n.length>t||rE.test(n)||sE.test(n)?void 0:n}function Ls(e){const t="string"==typeof e?aE.exec(e.trim()):null;if(!t||"px"!==t[2]?.toLowerCase())return;const n=Number(t[1]);return n>=1&&n<=512?`${String(n)}px`:void 0}function Fs(e){const t="string"==typeof e?aE.exec(e.trim()):null;if(!t)return;const n=Number(t[1]),o=t[2]?.toLowerCase()??"";return("px"===o?n>=1&&n<=1024:"%"===o?n>=50&&n<=1e3:n>=.5&&n<=10)?`${String(n)}${o}`:void 0}function Os(e){return"left"===e||"center"===e||"right"===e?e:void 0}function Ds(e){if(!e||"object"!=typeof e)return;const t=Object.entries(e).map(([e,t])=>[e,zs(t)]).filter(e=>void 0!==e[1]);return t.length>0?Object.fromEntries(t):void 0}function zs(e,t=0){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(!(t>8)){if(Array.isArray(e))return e.map(e=>zs(e,t+1)).filter(e=>void 0!==e);if(e&&"object"==typeof e){const n=Object.entries(e).map(([e,n])=>[e,zs(n,t+1)]).filter(e=>void 0!==e[1]);return Object.fromEntries(n)}}}function Us(e){return f(e)&&"text"===e.type}function Ns(e){return{richText:e.richText,w:e.w,h:e.h,autoSize:e.autoSize,scale:e.scale,font:e.font,size:e.size,color:e.color,backgroundColor:e.backgroundColor,textAlign:e.textAlign}}function Ws(e){return Ns(e.getDefaultShapeProps("text"))}function Xs(e,t,n="user"){const o={...Ws(e),...t.props,richText:t.props?.richText??ms("")},[i]=e.commands.createShapes([{type:"text",x:t.x,y:t.y,parentId:t.parentId,index:t.index,rotation:t.rotation,skewX:t.skewX,scaleX:t.scaleX,scaleY:t.scaleY,meta:t.meta,props:{richText:o.richText,w:o.w,h:o.h,autoSize:o.autoSize,scale:o.scale,font:o.font,size:o.size,color:o.color,backgroundColor:o.backgroundColor,textAlign:o.textAlign}}],{source:n});if(!Us(i))throw new Error("Failed to create text shape");return i}function Ys(e,t){return e?Math.min(e.paddingInline,Math.max(0,(t-1)/2)):0}function Hs(e,t){return ce(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})?.rotation??t.rotation}function _s(e,t,n,o){const i=e.getShapeUtil(t),r=ce(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(!r)return null;const s={...t,...r,x:o.x,y:o.y,rotation:o.rotation,props:i.validateProps({...t.props,...o.props})},a=n.startsWith("shape:")?e.getShape(n):null;if(n.startsWith("shape:")&&!a)return null;const d=(a?e.computeShapeLocalToPageTransform(a):FC.Identity()).tryInvert();return d?ce(d.compose(i.getLocalToPageTransform(s)),i.getLocalBounds(s),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY}):null}function Ks(e,t,n){const o=e.getBindingsToShape(t).find(e=>e.type===n);if(!o)return null;const i=e.getShape(o.fromId);return Us(i)?i:null}function qs(e,t){const n={...Ws(e),...t.layout.props,autoSize:!1,textAlign:"middle"},o=_s(e,{id:"shape:draft-label",typeName:"shape",scope:"document",type:"text",parentId:t.owner.parentId,index:t.index,x:0,y:0,rotation:0,skewX:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:n},t.owner.parentId,t.layout);if(!o)return null;const i=e.operations.begin({kind:t.historyMarkId,label:"shape.create",source:"user",history:"record"});try{const i=Xs(e,{x:o.x,y:o.y,parentId:t.owner.parentId,index:t.index,rotation:o.rotation,skewX:o.skewX,scaleX:o.scaleX,scaleY:o.scaleY,props:n},"user");return e.commands.createBinding({type:t.bindingType,fromId:i.id,toId:t.owner.id,props:t.bindingProps},{source:"user"}),i}catch(r){throw i.cancel(),r}}function js(e,t){const n=e.getShape(t);if(!Us(n))return null;const o=e.getBindingsFromShape(t).find(e=>e.type in cE);if(!o)return null;const i=o.type;return{label:n,ownerId:o.toId,bindingType:i,behavior:cE[i]}}function Vs(e,t,n,o){if("path-label"===o)return{minWidth:24,maxWidth:120,paddingInline:4.25};const i=Math.max(.01,t.props.scale);return{minWidth:16,maxWidth:Math.max(16,e.computeShapeLocalBounds(n).w/i),paddingInline:16}}function Gs(e,t){const n=js(e,t.id);if(!n)return null;const o=e.getShape(n.ownerId);return o?Vs(e,t,o,n.bindingType):null}function Zs(e,t,n){e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:n.isExisting?n.editMarkId:n.createMarkId,reuseActiveOperation:!n.isExisting},"user")}function Qs(e,t,n){return e.content.map((e,o)=>((e,t,n,o)=>{const i=Js(e,t,n,"codeBlock"===e.type?void 0:o);
|
|
17
|
+
return Gk("p",{style:{margin:0,textAlign:ws(e)},children:i.length>0?i:Gk("br",{})},t)})(e,`block:${o}`,t,n))}function Js(e,t,n,o){return e.content?.map((e,i)=>((e,t,n,o)=>{if(xs(e)){const i=Is(e.marks,o),r=Ps(e.marks);return r&&gs(r)?Gk("span",{"data-rich-text-link":"true","data-rich-text-link-href":r,onPointerEnter:e=>{n?.onPointerEnter?.({href:r,element:e.currentTarget})},onPointerLeave:()=>{n?.onPointerLeave?.()},style:{...i,cursor:n?"pointer":void 0,pointerEvents:n?"auto":"none",textDecorationLine:ea(i?.textDecorationLine)},children:e.text},t):Gk("span",{style:i,children:e.text},t)}return Js(e,t,n,"codeBlock"===e.type?void 0:o)})(e,`${t}:${i}`,n,o))??[]}function ea(e){const t=new Set(e?.split(/\s+/u)??[]);return t.add("underline"),["line-through","underline"].filter(e=>t.has(e)).join(" ")}function ta(){return{defaultFont:pE,defaultFontLabel:"Default",fonts:[]}}function na(){return oa(ta())}function oa(e){const t=new Map;for(const n of e.fonts)ia(n.id)&&"default"!==n.id&&t.set(n.id,n);return{defaultFont:e.defaultFont,defaultFontLabel:e.defaultFontLabel,fontOptions:[{id:uE,label:e.defaultFontLabel,cssFamily:e.defaultFont.cssFamily,source:e.defaultFont.source},...t.values()],fontsById:t}}function ia(e){return"string"==typeof e&&e.trim().length>0}function ra(e,t){return"default"===t?e.defaultFont:e.fontsById.get(t)??e.defaultFont}function sa(e,t,n){const o=ra(t,e),i=n??("undefined"==typeof document?void 0:document);if(!i||!aa(o.source))return Promise.resolve();const r=(e=>{const{source:t}=e;return t&&"system"!==t.kind?"stylesheet"===t.kind?`${e.id}:stylesheet:${t.cssUrl}`:`${e.id}:font-face:${t.family}:${String(t.src)}`:e.id})(o),s=(e=>{const t=hE.get(e);if(t)return t;const n=new Map;return hE.set(e,n),n})(i),a=s.get(r);if(a)return a;const d=(async(e,t)=>{const{source:n}=t;if(aa(n))return"stylesheet"===n.kind?(await((e,t,n)=>Array.from(e.querySelectorAll("link[data-land-text-font]")).find(e=>e.dataset.landTextFont===t.id)?Promise.resolve():new Promise(o=>{const i=e.createElement("link");i.rel="stylesheet",i.href=n.cssUrl,i.dataset.landTextFont=t.id;const r=()=>o();i.addEventListener("load",r,{once:!0}),i.addEventListener("error",r,{once:!0}),(e.head??e.documentElement).appendChild(i)}))(e,t,n),void(await da(e,n))):(await(async(e,t)=>{const{fonts:n}=e,o=e.defaultView?.FontFace;if(!n||!o)return;if(Array.from(n).filter(e=>e.family===t.family&&"loaded"===e.status).length>0)return;const i=await new o(t.family,t.src,t.descriptors).load();n.add(i)})(e,n),void(await da(e,n)))})(i,o).catch(()=>{s.delete(r)});return s.set(r,d),d}function aa(e){return!!e&&"system"!==e.kind}async function da(e,t){const{fonts:n}=e;if(!n)return;const o=(e=>{if(e.weights)return e.weights;if("font-face"===e.kind){const t=e.descriptors?.weight;if("string"==typeof t&&/^\d+$/.test(t))return[Number(t)]}return[400]})(t),i=t.sampleText??"Aa";await Promise.all(o.map(e=>n.load(`${e} 16px "${t.family}"`,i)))}function la(e){return gE.get(e)?.api??null}function ca(e){const t=gE.get(e);if(t)return t;const n={api:null,disposeApiSubscription:null,listeners:new Set};return gE.set(e,n),n}function ua(e){for(const t of e.listeners)t()}function pa(e,t){const n=fE[t];let o=!1,i=!1;return fa(e.content,(e,t)=>{"text"!==e.type||!e.text||t.insideCodeBlock||e.marks?.some(e=>"code"===e.type)||(e.marks?.some(e=>n.includes(e.type))?o=!0:i=!0)}),o&&i?"mixed":o}function ha(e){const t=[];if(fa(e.content,(e,n)=>{if("text"!==e.type||!e.text||n.insideCodeBlock||e.marks?.some(e=>"code"===e.type))return;const o=(e.marks?.find(e=>"textStyle"===e.type))?.attrs?.backgroundColor;t.push("string"==typeof o&&o.length>0?o:null)}),0===t.length)return null;const n=t[0]??null;return t.every(e=>e===n)?n:"mixed"}function ga(e){if("paragraph"!==e.type||void 0===e.attrs?.textAlign)return e;const t={...e.attrs};return delete t.textAlign,{...e,attrs:Object.keys(t).length>0?t:void 0}}function fa(e,t,n=!1){for(const o of e)t(o,{insideCodeBlock:n}),o.content&&fa(o.content,t,n||"codeBlock"===o.type)}function ma(e,t,n=!1){let o=!1;return{nodes:e.map(e=>{const i=t(e,{insideCodeBlock:n}),r=i.content;if(!r)return i!==e&&(o=!0),i;const s=ma(r,t,n||"codeBlock"===i.type);return s.changed?(o=!0,{...i,content:s.nodes}):(i!==e&&(o=!0),i)}),changed:o}}function ya(e){try{return e.view.dom.isConnected}catch{return!1}}function Sa(e){!e.isDestroyed&&ya(e)&&(e.view.dom.focus(),e.view.focus())}function ba(e){if(!ya(e))return{type:null,text:null};const t=(e=>{if(!e)return{type:null,text:null};const t=window.getSelection();if(!t||0===t.rangeCount)return{type:t?.type??null,text:null};const n=t.anchorNode,o=t.focusNode,i=e instanceof HTMLElement?e:e.parentElement,r=!!n&&!!o&&null!==i&&i.contains(n)&&i.contains(o);return{type:r?t.type:null,text:r?t.toString():null}})(e.view.dom);if(null!==t.type)return t;const n=e.state.selection;return{type:n.empty?"Caret":"Range",text:n.empty?"":e.state.doc.textBetween(n.from,n.to,"\n")}}function xa(e,t=xE){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function wa(e,t){return ra(t,e).cssFamily}function Ia(e){return xa(e)}function Pa(e){const t=xa(e);return wE[t]??Math.ceil(1.4*t)}function va(e,t=1){return Math.max(1,Math.ceil(Pa(e)*t))}function ka(e){switch(e){case"middle":return"center";case"end":return"right";default:return"left"}}function Ca(e,t,n,o){return 0===ys(e).trim().length?Ta(t,o):Ma(t,(i=bs(e),r={...Ea(t,o),shape:t,fontCatalog:n},Ba(document).measureHtml(i,r)),o);var i,r}function Ta(e,t){const n=t?t.minWidth:e.props.autoSize?16:e.props.w,o=va(e.props.size);if(e.props.w!==n||e.props.h!==o)return{w:n,h:o}}function Ma(e,t,n){const o=n?Math.min(n.maxWidth,Math.max(n.minWidth,Math.ceil(t.w+2*n.paddingInline))):e.props.autoSize?Math.max(16,Math.ceil(t.w)):e.props.w,i=Math.max(va(e.props.size),Math.ceil(t.h));if(o!==e.props.w||i!==e.props.h)return{w:o,h:i}}function Ea(e,t){if(t){const e=Ys(t,t.maxWidth);return{maxWidth:Math.max(1,t.maxWidth-2*e)}}return e.props.autoSize?{}:{width:e.props.w}}function Ba(e){const t=PE.get(e);if(t)return t;const n=new IE(e);return PE.set(e,n),n}function Aa(e,t,n){n&&"normal"!==n&&"auto"!==n&&(e.style[t]=n)}function Ra(e,t,n){if(t.isDestroyed()||!t.isConnected())return;const o=t.measure(n);o&&La(e,n,o,"user")}function $a(e,t,n,o="system"){const i=Ca(t.props.richText,t,n,Gs(e,t));i&&La(e,t,i,o)}function La(e,t,n,o){const i=e.getShape(t.id);Us(i)&&i.props.w===n.w&&i.props.h===n.h||e.commands.updateShapes([{id:t.id,props:n}],{source:o})}function Fa({editor:e,fontCatalog:t,landEditor:n,shapeId:o}){const i=()=>{const e=n.getShape(o);return Us(e)?e:null},r={shapeId:o,getSnapshot(){if(e.isDestroyed)return null;const n=i();return n?(({editor:e,fontCatalog:t,shape:n})=>{const o=e.state.selection,i=(e=>{const{selection:t,doc:n}=e.state;return t.empty?{from:0,to:n.content.size}:{from:t.from,to:t.to}})(e),r=o.empty?"shape":"selection",s=D(n.props.color),a=z(n.props.backgroundColor)?null:D(n.props.backgroundColor),d=n.props.textAlign;return{shapeId:n.id,target:r,bold:Wa(e,i,"bold"),italic:Wa(e,i,"italic"),strike:Wa(e,i,"strike"),underline:Wa(e,i,"underline"),color:Xa(e,i,"color",s),backgroundColor:Xa(e,i,"backgroundColor",0===e.state.doc.textContent.length?a:null),font:Ka(Xa(e,i,"fontFamily",n.props.font),e=>((e,t)=>t.fontOptions.find(t=>t.cssFamily===e)?.id??e)(e,t)),size:Ka(Xa(e,i,"fontSize",n.props.size),e=>((e,t)=>{if("number"==typeof e)return e;const n=Number.parseFloat(e);return Number.isFinite(n)&&n>0?n:t})(e,n.props.size)),textAlign:Ya(e,i,d),linkHref:Ha(e),canSetLink:!o.empty||e.isActive("link")}})({editor:e,fontCatalog:t,shape:n}):null},subscribe(t){if(e.isDestroyed)return()=>{};const i=()=>t();e.on("transaction",i),e.on("focus",i),e.on("blur",i);const r=Zi(`TextFormattingApi(${o})`,n.getShapeSignal(o),i,{fireImmediately:!1});return()=>{r(),e.off("transaction",i),e.off("focus",i),e.off("blur",i)}},focus(){e.isDestroyed||e.commands.focus()},toggle:t=>((e,t,n)=>{if(e.isDestroyed||void 0===e.schema.marks[t])return!1;const o=e.state.selection;if(!o.empty)return e.chain().focus().toggleMark(t).run();const i=!0!==n?.[t];if(0===e.state.doc.textContent.length){const n=e.chain().focus();return(i?n.setMark(t):n.unsetMark(t)).run()}let r=e.chain().focus().selectAll();return r=i?r.setMark(t):r.unsetMark(t),r=r.setTextSelection(Na(o)),r=i?r.setMark(t):r.unsetMark(t),r.run()})(e,t,r.getSnapshot()),setColor(t){if(null!==t&&!qa(t))return!1;const o=i();return!!o&&(({editor:e,landEditor:t,shape:n,color:o})=>{if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;if(!e.state.selection.empty)return null===o?e.chain().focus().unsetColor().run():e.chain().focus().setColor(o).run();const i=Da(e,"color");return null!==o&&Ua(t,n,{color:B(o)}),i||null!==o})({editor:e,landEditor:n,shape:o,color:t})},setBackgroundColor(t){if(null!==t&&!qa(t))return!1;const o=i();return!!o&&(({editor:e,landEditor:t,shape:n,color:o})=>{if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;const i=e.state.selection,r=e=>null===o?e.unsetBackgroundColor():e.setBackgroundColor(o);if(!i.empty)return Ua(t,n,{backgroundColor:B("transparent")}),r(e.chain().focus()).run();const s=r(r(e.chain().focus().selectAll()).setTextSelection(Na(i))).run();return Ua(t,n,{backgroundColor:B(o??"transparent")}),s})({editor:e,landEditor:n,shape:o,color:t})},setFont(o){const r=i();if(!r)return!1;if(null===o)return Oa({editor:e,font:null,fontFamily:null,landEditor:n,shape:r});const s=t.fontOptions.find(e=>e.id===o);return!!s&&(sa(o,t).then(()=>{const e=i();e&&$a(n,e,t,"system")}),Oa({editor:e,fontFamily:s.cssFamily,font:o,landEditor:n,shape:r}))},setSize(t){const o=null===t?null:Math.round(1e3*t)/1e3;if(null!==t&&(!Number.isFinite(t)||t<1||t>512||null===o||Math.abs(t-o)>Number.EPSILON*Math.max(1,Math.abs(t))))return!1;const r=i();return!!r&&(({editor:e,landEditor:t,shape:n,size:o})=>{if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;const i=e.state.selection,r=null===o?null:`${o}px`,s=null===o?null:`${Pa(o)}px`;if(!i.empty)return(a=e.chain().focus(),null===r||null===s?a.unsetFontSize().unsetLineHeight():a.setFontSize(r).setLineHeight(s)).run();var a;const d=(e=>{const t=e.state.selection;let n=e.chain().focus();return e.state.doc.textContent.length>0&&(n=n.selectAll()),za(n.unsetFontSize().unsetLineHeight().setTextSelection(Na(t)).unsetFontSize().unsetLineHeight()).run()})(e);return null!==o&&Ua(t,n,{size:o}),d||null!==o})({editor:e,landEditor:n,shape:r,size:o})},setTextAlign(t){const o=i();return!!o&&(({editor:e,landEditor:t,shape:n,align:o})=>{if(e.isDestroyed)return!1;const i=(e=>{switch(e){case"middle":return"center";case"end":return"right";default:return"left"}})(o),r=e.state.selection;if(!r.empty)return e.chain().focus().setTextAlign(i).run();const s=e.chain().focus().selectAll().unsetTextAlign().setTextSelection(Na(r)).run();return Ua(t,n,{textAlign:o}),s||n.props.textAlign!==o})({editor:e,landEditor:n,shape:o,align:t})},setLink(t){if(e.isDestroyed||void 0===e.schema.marks.link)return!1;const n=null===t?null:hs(t);if(null!==t&&null===n)return!1;const{empty:o}=e.state.selection,i=e.isActive("link");if(null===n)return!!i&&e.chain().focus().extendMarkRange("link").unsetLink().run();if(o&&!i)return!1;const r=e.chain().focus();return(o?r.extendMarkRange("link"):r).setLink({href:n}).run()},clearFormatting(){if(e.isDestroyed)return!1;const t=i();t&&Ua(n,t,{backgroundColor:B("transparent")});const o=e.state.selection;return o.empty?e.chain().focus().selectAll().unsetAllMarks().unsetTextAlign().setTextSelection(Na(o)).command(({tr:e})=>(e.setStoredMarks([]),!0)).run():e.chain().focus().unsetAllMarks().unsetTextAlign().run()},getUnsafeTiptapEditor:()=>e.isDestroyed?null:e};return r}function Oa({editor:e,font:t,fontFamily:n,landEditor:o,shape:i}){if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;if(!e.state.selection.empty)return null===n?e.chain().focus().unsetFontFamily().run():e.chain().focus().setFontFamily(n).run();const r=Da(e,"fontFamily");return null!==t&&o&&i&&Ua(o,i,{font:t}),r||null!==t}function Da(e,t){const n=e.state.selection;let o=e.chain().focus();return e.state.doc.textContent.length>0&&(o=o.selectAll()),o="color"===t?o.unsetColor():o.unsetFontFamily(),o=o.setTextSelection(Na(n)),o="color"===t?o.unsetColor():o.unsetFontFamily(),za(o).run()}function za(e){return e.command(({state:e,tr:t})=>{const n=e.schema.marks.textStyle;if(!n)return!0;const o=(t.storedMarks??e.storedMarks)?.find(e=>e.type===n);return o&&Object.values(o.attrs).every(e=>null==e||""===e)&&t.removeStoredMark(n),!0})}function Ua(e,t,n){e.commands.updateShapes([{id:t.id,props:n}],{source:"user"})}function Na(e){return e.from===e.to?e.from:{from:e.from,to:e.to}}function Wa(e,t,n){if(!e.schema.marks[n])return!1;const o=[];return e.state.doc.nodesBetween(t.from,t.to,(e,t,i)=>{const r=i?.type.schema.marks[n];e.isText&&r&&i?.type.allowsMarkType(r)&&!e.marks.some(e=>"code"===e.type.name)&&o.push(e.marks.some(e=>e.type.name===n))}),0===o.length?(e.state.storedMarks??e.state.selection.$from.marks()).some(e=>e.type.name===n):_a(o)??!1}function Xa(e,t,n,o){const i=[];if(e.state.doc.nodesBetween(t.from,t.to,(e,t,r)=>{if(!e.isText)return;if("backgroundColor"===n&&(e.marks.some(e=>"code"===e.type.name)||"codeBlock"===r?.type.name))return;const s=e.marks.find(e=>"textStyle"===e.type.name)?.attrs[n];i.push("string"==typeof s&&s.length>0?s:o)}),0===i.length){const t=(e.state.storedMarks??e.state.selection.$from.marks()).find(e=>"textStyle"===e.type.name)?.attrs[n];return"string"==typeof t&&t.length>0?t:o}return _a(i)}function Ya(e,t,n){const o=[];return e.state.doc.nodesBetween(t.from,t.to,e=>{e.isTextblock&&o.push(((e,t)=>{switch(e){case"center":return"middle";case"right":return"end";case"left":return"start";default:return t}})(e.attrs.textAlign,n))}),_a(o)??n}function Ha(e){const t=e.getAttributes("link").href;return"string"==typeof t&&t.length>0?t:null}function _a(e){if(0===e.length)return null;const t=e[0];return e.every(e=>Object.is(e,t))?t:"mixed"}function Ka(e,t){return null===e?null:"mixed"===e?"mixed":t(e)}function qa(e){const t=e.trim();return t.length>0&&t.length<=128&&!vE.test(t)&&!kE.test(t)}function ja({shapeId:e,editor:t,fontCatalog:n,landEditor:o}){return{shapeId:e,formatting:Fa({editor:t,fontCatalog:n,landEditor:o,shapeId:e}),isDestroyed:()=>t.isDestroyed,isConnected:()=>!t.isDestroyed&&ya(t),isFocused:()=>!t.isDestroyed&&ya(t)&&t.view.dom.contains(document.activeElement),getValue:()=>Ss(t.getJSON()),setValue(e){t.commands.setContent(e)},focus(){Sa(t)},focusEnd(){!t.isDestroyed&&ya(t)&&t.commands.focus("end")},focusSelectAll(){!t.isDestroyed&&ya(t)&&(Sa(t),t.chain().focus().selectAll().run())},focusAtPagePoint(e,n){((e,t,n)=>{Sa(t);const o=e.pageToScreen(new $C(n.x,n.y)),i=t.view.posAtCoords({left:o.x,top:o.y})?.pos;i?t.chain().focus().setTextSelection(i).run():t.chain().focus().selectAll().run()})(e,t,n)},getSelectionSnapshot:()=>t.isDestroyed||!ya(t)?{type:null,text:null}:ba(t),collapseSelectionAtClientPoint(e,n){!t.isDestroyed&&ya(t)&&"Range"===ba(t).type&&((e,t,n)=>{if(e.isDestroyed||!ya(e))return;const o=e.view.posAtCoords({left:t,top:n})?.pos;"number"!=typeof o?e.commands.focus("end"):e.chain().focus().setTextSelection(o).run()})(t,e,n)},measure(e){if(!t.isDestroyed&&ya(t))return function(e,t,n,o){if(0===e.getText().trim().length)return Ta(t,o);const i=((e,t)=>{const n=e.ownerDocument.defaultView?.getComputedStyle(e);return Ba(e.ownerDocument).measureElement(e,t,n)})(e.view.dom,{shape:t,fontCatalog:n,...Ea(t,o)});return!o&&e.view.dom.scrollHeight>t.props.h+1&&(i.h=Math.max(i.h,e.view.dom.scrollHeight)),Ma(t,i,o)}(t,e,n,Gs(o,e))},onCompositionStateChange(e){if(t.isDestroyed)return()=>{};const n=t.view.dom,o=()=>e(!0),i=()=>e(!1);return n.addEventListener("compositionstart",o),n.addEventListener("compositionend",i),()=>{n.removeEventListener("compositionstart",o),n.removeEventListener("compositionend",i),e(!1)}}}}function Va({landEditor:e,shape:t,fontCatalog:n,initialRichText:o,className:i,editorStyle:r,formattingToolbar:s,onTiptapEditorChange:a,onReady:d,onDispose:l,onRichTextChange:c}){const u=Kk(null),p=z(t.props.backgroundColor)?null:D(t.props.backgroundColor),h=p&&o.content.length>0?((e,t)=>{const n=ma(e.content,(e,n)=>{if("text"!==e.type||!e.text||n.insideCodeBlock||e.marks?.some(e=>"code"===e.type))return e;const o=e.marks??[],i=o.findIndex(e=>"textStyle"===e.type);if(i<0)return{...e,marks:[...o,{type:"textStyle",attrs:{backgroundColor:t}}]};const r=o[i]?.attrs?.backgroundColor;return"string"==typeof r&&r.length>0?e:{...e,marks:o.map((e,n)=>n===i?{...e,attrs:{...e.attrs,backgroundColor:t}}:e)}});return n.changed?Ss({...e,content:n.nodes}):e})(o,p):o,g=Uk(o=>{const i=u.current;if(i?.editor===o)return i.controller;const r=ja({shapeId:t.id,editor:o,fontCatalog:n,landEditor:e});return u.current={editor:o,controller:r},r},[n,e,t.id]),f=Jk({extensions:TE,content:h,autofocus:!1,editable:!0,immediatelyRender:!0,shouldRerenderOnTransaction:!1,editorProps:{attributes:{"data-ui":"rich-text-editor",class:"land-text-editor__content",dir:"auto"},handleKeyDown:(t,n)=>(n.stopPropagation(),!(n.isComposing||("Escape"===n.key?(n.preventDefault(),e.cancelEditing("user"),0):"Enter"!==n.key||!n.metaKey&&!n.ctrlKey||(n.preventDefault(),e.completeEditing("user"),0))))},onUpdate:({editor:e})=>{const t=g(e);c({editor:e,controller:t,richText:t.getValue()})}},[t.id]);return Wk(()=>{if(!f||f.isDestroyed)return;const n=g(f),o={shapeId:t.id,editor:f,controller:n,formatting:n.formatting},i={shapeId:t.id,formatting:n.formatting},r=!1===s?()=>{}:((e,t)=>{const n=ca(e);return n.disposeApiSubscription?.(),n.api=t,n.disposeApiSubscription=t.subscribe(()=>{ua(n)}),ua(n),()=>{n.api===t&&(n.disposeApiSubscription?.(),n.disposeApiSubscription=null,n.api=null,ua(n))}})(e,n.formatting);return d(o),a?.(i),()=>{r(),u.current?.editor===f&&(u.current=null),l(o),a?.(null)}},[g,s,e,l,d,a,t.id,f]),Gk(Qk,{editor:f,className:i,style:r})}function Ga({editor:e,controller:t,shapeId:n,request:o,onApplied:i,attempt:r=0}){if(!t.isDestroyed())if(t.isConnected())(({editor:e,controller:t,shapeId:n,request:o,onApplied:i})=>{if(!t.isDestroyed())t.focus(),o&&o.shapeId===n?"selectAll"===o.entryMode?(window.requestAnimationFrame(()=>{!t.isDestroyed()&&t.isConnected()&&t.focusSelectAll()}),e.consumeShapeEditingEntryRequest(o.id),i?.(o)):"placeCaret"===o.entryMode&&o.caretPagePoint?(t.focusAtPagePoint(e,o.caretPagePoint),e.consumeShapeEditingEntryRequest(o.id),i?.(o)):(t.focusEnd(),e.consumeShapeEditingEntryRequest(o.id),i?.(o)):(t.focusEnd(),i?.(o))})({editor:e,controller:t,shapeId:n,request:o,onApplied:i});else{if(r>=4)return;window.requestAnimationFrame(()=>{Ga({editor:e,controller:t,shapeId:n,request:o,onApplied:i,attempt:r+1})})}}function Za({shapeId:e,markId:t,fontCatalog:n,formattingToolbar:o,onTiptapEditorChange:i}){const r=wr(),s=Ir(r.getShapeSignal(e)),a=Ir(r.shapeEditingStateSignal).session;return Us(s)&&a?.shapeId===s.id?Gk(Qa,{shape:s,session:a,fontCatalog:n,formattingToolbar:o,onTiptapEditorChange:i},`${s.id}:${t}`):null}function Qa({shape:e,session:t,fontCatalog:n,formattingToolbar:o,onTiptapEditorChange:i}){const r=wr(),s=Kk(e.props.richText),a=(e=>{const t=Kk(e);return Wk(()=>{t.current=e},[e]),t})(e),d=Ir(r.shapeEditingEntryRequestSignal),l=Kk(null),[c,u]=qk(null),[p,h]=qk(null),g=Uk(({editor:e,controller:t})=>{u(e.isDestroyed?null:e),h(t)},[]),f=Uk(({editor:e,controller:t})=>{u(t=>t===e?null:t),h(e=>e===t?null:e)},[]),m=function({editor:e,shape:t,tiptapEditor:n,richTextController:o,latestShapeRef:i,fontCatalog:r}){const s=Kk(t.props.richText),a=Kk(!1),d=Kk(null),l=Uk(({controller:n,richText:o})=>{if(a.current||!n.isConnected())return;const l=Ss(o);s.current=l,((e,t,n,o,i="user")=>{const r=e.getShape(t);Us(r)&&e.commands.updateShapes([{id:r.id,props:{richText:n,..."number"==typeof o?.w?{w:o.w}:null,..."number"==typeof o?.h?{h:o.h}:null}}],{source:i})})(e,t.id,l,n.measure(i.current)??Ca(l,i.current,r,Gs(e,i.current)),"user"),((e,t,n,o)=>{null!==o.current&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>{o.current=null,Ra(e,t,n.current)},0)})(e,n,i,d)},[e,r,i,t.id]);return Wk(()=>()=>{null!==d.current&&(window.clearTimeout(d.current),d.current=null)},[]),Hk(()=>{n&&o&&!n.isDestroyed&&o.isConnected()&&Ra(e,o,t)},[e,o,t,n]),Wk(()=>{if(!n||!o||!o.isConnected())return;const e=t.props.richText;e!==s.current&&(JSON.stringify(s.current)!==JSON.stringify(e)?(a.current=!0,o.setValue(e),s.current=e,a.current=!1):s.current=e)},[o,t.props.richText,n]),Wk(()=>{if(o)return o.onCompositionStateChange(t=>{e.setShapeEditingComposition(t,"system")})},[e,o]),Wk(()=>{if(!o||!o.isConnected())return;let n=!1;return sa(t.props.font,r).then(()=>{!n&&o.isConnected()&&Ra(e,o,i.current)}),()=>{n=!0}},[e,r,i,o,t.props.font]),l}({editor:r,shape:e,tiptapEditor:c,richTextController:p,latestShapeRef:a,fontCatalog:n}),y=Uk(()=>{c&&((e,t)=>{!(!t||e.isDestroyed||e.state.doc.textContent.length>0||e.getAttributes("textStyle").backgroundColor===t)&&e.commands.setBackgroundColor(t)})(c,z(e.props.backgroundColor)?null:D(e.props.backgroundColor))},[e.props.backgroundColor,c]);(({editor:e,shapeId:t,session:n,tiptapEditor:o,richTextController:i,entryRequest:r,consumedEntryRequestIdRef:s,onEntryFocusApplied:a})=>{const d=Kk(null),l=Kk(null);Wk(()=>{if(!i||i.isDestroyed()||!i.isConnected())return;let e=!1,t=null,n=0;const o=()=>{e||i.isDestroyed()||null===s.current&&(i.isFocused()||(i.focus(),n+=1,i.isFocused()||n>=4||(t=window.setTimeout(o,16))))},r=window.requestAnimationFrame(()=>{o()});return()=>{e=!0,window.cancelAnimationFrame(r),null!==t&&window.clearTimeout(t)}},[s,i,t]),Wk(()=>{o&&!o.isDestroyed&&i&&null===s.current&&l.current!==n.markId&&(l.current=n.markId,window.setTimeout(()=>{Ga({editor:e,controller:i,shapeId:t,request:{id:-1,shapeId:n.shapeId,entryMode:n.entryMode,caretPagePoint:n.caretPagePoint},onApplied:a})},0))},[s,e,i,n.caretPagePoint,n.entryMode,n.markId,n.shapeId,t,o,a]),Wk(()=>{o&&!o.isDestroyed&&i&&r&&r.shapeId===t&&s.current!==r.id&&Ga({editor:e,controller:i,shapeId:t,request:r,onApplied(e){e&&(s.current=e.id),a?.()}})},[s,e,r,i,t,o,a]),Wk(()=>{if(!o||!i||o.isDestroyed||!i.isConnected())return;const t=i;"selectAll"===n.entryMode&&window.requestAnimationFrame(()=>{"Range"!==t.getSelectionSnapshot().type&&t.focusSelectAll()});const r=d.current,s=n.caretPagePoint;if("placeCaret"===n.entryMode&&s&&(r?.markId!==n.markId||r.entryMode!==n.entryMode)){d.current={markId:n.markId,entryMode:n.entryMode};const o={x:s.x,y:s.y};window.requestAnimationFrame(()=>{Ga({editor:e,controller:t,shapeId:n.shapeId,request:{id:-1,shapeId:n.shapeId,entryMode:"placeCaret",caretPagePoint:o},onApplied:a})})}},[e,n.caretPagePoint,n.entryMode,n.markId,n.shapeId,i,o,a])})({editor:r,shapeId:e.id,session:t,tiptapEditor:c,richTextController:p,entryRequest:d,consumedEntryRequestIdRef:l,onEntryFocusApplied:y});const S=(({editor:e,shapeId:t,richTextController:n})=>{const o=Kk(null);return{onPointerDownCapture:Uk(i=>{if(i.stopPropagation(),0!==i.button||1!==i.detail||!n||n.isDestroyed())return void(o.current=null);const r=e.getShapeEditingSession();o.current=r&&r.shapeId===t&&!r.isComposing&&"Range"===n.getSelectionSnapshot().type?{pointerId:i.pointerId,clientX:i.clientX,clientY:i.clientY,moved:!1}:null},[e,n,t]),onPointerMoveCapture:Uk(e=>{const t=o.current;if(!t||t.pointerId!==e.pointerId)return;const n=e.clientX-t.clientX,i=e.clientY-t.clientY;n*n+i*i>=16&&(t.moved=!0)},[]),onPointerUpCapture:Uk(i=>{const r=o.current;if(o.current=null,!r||r.pointerId!==i.pointerId||r.moved||!n||n.isDestroyed())return;const s=e.getShapeEditingSession();if(!s||s.shapeId!==t||s.isComposing)return;const a=i.clientX,d=i.clientY;window.setTimeout(()=>{n.isDestroyed()||"Range"!==n.getSelectionSnapshot().type||n.collapseSelectionAtClientPoint(a,d)},0)},[e,n,t]),onPointerCancel:Uk(()=>{o.current=null},[])}})({editor:r,shapeId:e.id,richTextController:p}),b=((e,t,n=0)=>_k(()=>({color:O(e.props.color),fontFamily:wa(e.props.font,t),fontSize:Ia(e.props.size),lineHeight:`${Pa(e.props.size)}px`,textAlign:ka(e.props.textAlign),pointerEvents:"auto",userSelect:"text",cursor:"text",boxSizing:"border-box",position:"absolute",inset:0,width:"100%",height:"100%",paddingInline:n}),[e.props.color,e.props.font,e.props.size,e.props.textAlign,t,n]))(e,n,Ys(Gs(r,e),e.props.w)),x=Uk(e=>{if(!e.ctrlKey&&!e.metaKey)return;const t=(e=>{const t=e.target;return t instanceof Element?t.closest("[data-rich-text-link-href]")?.getAttribute("data-rich-text-link-href")??null:null})(e.nativeEvent);t&&c&&!c.isDestroyed&&(e.preventDefault(),e.stopPropagation(),fs(t))},[c]);
|
|
18
|
+
return Gk("div",{"data-ui":"text-editing-box","data-shape-id":e.id,"data-mount-target-kind":"shape",onPointerDown:e=>{e.stopPropagation()},onClickCapture:x,onPointerDownCapture:S.onPointerDownCapture,onPointerMoveCapture:S.onPointerMoveCapture,onPointerUpCapture:S.onPointerUpCapture,onPointerCancel:S.onPointerCancel,onContextMenu:e=>{e.stopPropagation()},onDragStart:e=>{e.preventDefault()},style:b,children:Gk(Va,{landEditor:r,shape:e,fontCatalog:n,initialRichText:s.current,className:"land-text-editor__content",formattingToolbar:o,editorStyle:{height:"100%",minHeight:"100%"},onReady:g,onDispose:f,onTiptapEditorChange:i,onRichTextChange:m})})}function Ja({children:e,presenter:t}){
|
|
19
|
+
return Gk(ME.Provider,{value:t,children:e})}function ed(e,t){const n=new Set;for(const o of e){if(n.has(o))throw new Error(`Duplicate ${t}: ${o}.`);n.add(o)}}function td({fontCatalog:e=na(),formattingToolbar:t,onTiptapEditorChange:n}={}){return{id:"land.text.react",domEventGuards:[BE],canvasComponents:[{id:"land.text.default-font-preload",component:()=>Gk(nd,{fontCatalog:e})}],shapeRenderers:[{type:"text",hoverComponent:id,component:o=>Gk(od,{...o,fontCatalog:e,formattingToolbar:t,onTiptapEditorChange:n})}]}}function nd({fontCatalog:e}){return Wk(()=>{sa(uE,e)},[e]),null}function od({shape:e,editor:t,fontCatalog:n,formattingToolbar:o,onTiptapEditorChange:i}){const[r,s]=qk(null),a=Kk(null),d=Ir(t.selectedShapeIdsSignal),l=Nk(ME),{hasEditingSession:c,isEditingThisShape:u,editingHost:p}=function(e,t,n,o,i){const r=Ir(e.shapeEditingStateSignal).session,s=r?.shapeId===t.id,a=r&&s?Gk(Za,{shapeId:r.shapeId,markId:r.markId,fontCatalog:n,formattingToolbar:o,onTiptapEditorChange:i},r.shapeId+":"+r.markId):null;return(({editor:e,shape:t,isEditingThisShape:n,fontCatalog:o})=>{Hk(()=>{if(n)return;$a(e,t,o);let i=!1;return sa(t.props.font,o).then(()=>{if(i)return;const n=e.getShape(t.id);Us(n)&&n.props.font===t.props.font&&$a(e,n,o)}),()=>{i=!0}},[e,o,n,t,t.props.autoSize,t.props.font,t.props.richText,t.props.scale,t.props.size,t.props.textAlign,t.props.w])})({editor:e,shape:t,isEditingThisShape:s,fontCatalog:n}),{hasEditingSession:null!==r,isEditingThisShape:s,editingHost:a}}(t,e,n,o,i),h=Ys(Gs(t,e),e.props.w),g=null!==l&&(({isEditing:e,isOnlySelected:t})=>!e&&!t)({isEditing:c,isOnlySelected:1===d.length&&d[0]===e.id}),f=Uk(()=>{null!==a.current&&(window.clearTimeout(a.current),a.current=null)},[]),m=Uk(()=>{f(),a.current=window.setTimeout(()=>{s(null),a.current=null},160)},[f]);return Wk(()=>()=>{f()},[f]),Wk(()=>{g||(f(),s(null))},[g,f]),Zk("div",{"data-editing-hidden":u?"true":void 0,style:{position:"relative",boxSizing:"border-box",width:e.props.w,minHeight:e.props.h,transform:`scale(${e.props.scale})`,transformOrigin:"top left",color:O(e.props.color),fontFamily:wa(e.props.font,n),fontSize:Ia(e.props.size),lineHeight:`${Pa(e.props.size)}px`,textAlign:ka(e.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none"},children:[
|
|
20
|
+
Gk("div",{style:{boxSizing:"border-box",opacity:u?0:void 0,paddingInline:h,width:"100%"},children:Qs(e.props.richText,g?{onPointerEnter({href:e,element:t}){f(),s({anchorElement:t,href:e})},onPointerLeave(){m()}}:void 0,z(e.props.backgroundColor)?void 0:O(e.props.backgroundColor))}),g&&r&&l?Gk(l,{anchorElement:r.anchorElement,href:r.href,onOpen:()=>{fs(r.href)},onPopoverPointerEnter:f,onPopoverPointerLeave:m}):null,
|
|
21
|
+
Gk("div",{"data-ui":"text-editor-host-slot","data-shape-id":e.id,"data-active":u?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:p})]})}function id({strokeWidth:e}){
|
|
22
|
+
return Gk("div",{"data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 ${e}px ${xM}`,inset:0,position:"absolute"}})}function rd(e){return Ns(e)}function sd(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function ad(e){return Math.max(.01,e.props.scale)}function dd(e){return e.props.w*ad(e)}function ld(e){return e.props.h*ad(e)}function cd(e){return new LC(0,0,dd(e),ld(e))}function ud(e){return"left"===e||"right"===e}function pd(e,t){return e.content.map(e=>((e,t)=>{const n="codeBlock"===e.type?void 0:t,o=e.content?.map(e=>hd(e,n))??[],i=ws(e);return{tag:"p",attrs:{style:i?`margin:0;text-align:${i}`:"margin:0"},children:o.length>0?o:[{tag:"br"}]}})(e,t))}function hd(e,t){if(xs(e)){const n=((e,t)=>{const n=Is(e.marks,t);return n?ks(n):void 0})(e,t);return n?{tag:"span",attrs:{style:n},children:[e.text]}:e.text}return{tag:"span",children:e.content?.map(n=>hd(n,"codeBlock"===e.type?void 0:t))??[]}}function gd(e,t,n,o){return[`color:${t.resolveColor(e.props.color)}`,`font-family:${wa(e.props.font,n)}`,`font-size:${Ia(e.props.size)}px`,`line-height:${Pa(e.props.size)}px`,`text-align:${ka(e.props.textAlign)}`,"white-space:pre-wrap","overflow-wrap:break-word","box-sizing:border-box",`padding-inline:${o}px`,`width:${e.props.w}px`,`height:${e.props.h}px`,`transform:scale(${e.props.scale})`,"transform-origin:top left"].join(";")}function fd(e){return"binding"===e?.typeName&&"path-label"===e.type}function md(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function yd(e,t,n,o=.5){const i=Sd(e,n),r=i?bd(e,t,i):{start:0,end:1},s=Math.min(r.end,Math.max(r.start,o)),a=i?.getPointAt(s)??e.computeShapePageCenter(n),d=Vs(e,t,n,dE),l=Math.min(d.maxWidth,Math.max(d.minWidth,t.props.w));return{x:a.x-l*t.props.scale/2,y:a.y-t.props.h*t.props.scale/2,rotation:Hs(e,n),props:{w:l}}}function Sd(e,t){return e.getShapeUtil(t).getLabelPathGeometry(t,{editor:e})}function bd(e,t,n){if(n.length<=1e-6)return{start:.5,end:.5};const o=e.getShapePageBounds(t.id);if(!o)return{start:0,end:1};const i=Math.hypot(o.w,o.h)/2,r=Math.min(.5,(i+8)/n.length);return{start:r,end:1-r}}function xd(e){return"shape"===e?.typeName&&"geo"===e.type}function wd(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Id(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Pd(e,t){const n=e.props[t];return"number"==typeof n&&Number.isFinite(n)?n:null}function vd(e,t){const n=Pd(e,"h");return!n||t.props.ownerBaseHeight<=0||n===t.props.ownerBaseHeight?null:{...e,props:{...e.props,h:t.props.ownerBaseHeight}}}function kd(e,t,n){const o=e.computeShapePageCenter(n),i=Vs(e,t,n,lE),r=Math.min(i.maxWidth,Math.max(i.minWidth,t.props.w));return{x:o.x-r*t.props.scale/2,y:o.y-t.props.h*t.props.scale/2,rotation:Hs(e,n),props:{w:r}}}function Cd(){let e=null,t=null;const n=()=>{e=null,t=null};return{id:"land.text.interactions",editorEvent:{handleEvent(o,i){if("cancel"===i.type)return n(),"continue";if("select"!==o.getActiveToolId())return"continue";if("pointer"===i.type&&"pointer_up"===i.name)return((e,t,n,o)=>{if(!n||n.pointerId!==t.pointerId)return o(),"continue";if(o(),(t.clickCount??1)>=2)return"continue";const i=t.pagePoint.x-n.originPagePoint.x,r=t.pagePoint.y-n.originPagePoint.y;if(i*i+r*r>9)return"continue";const s=e.getShape(n.shapeId);s&&Us(s)&&e.canEditShape(s)&&e.startEditingShape({shapeId:s.id,entryMode:"placeCaret",caretPagePoint:t.pagePoint,markId:XE,preserveInteraction:!0},"user")})(o,i,e,()=>{e=null}),((e,t,n,o)=>{if(!n||n.pointerId!==t.pointerId)return o(),"continue";if(o(),(t.clickCount??1)>=2)return"continue";const i=t.pagePoint.x-n.originPagePoint.x,r=t.pagePoint.y-n.originPagePoint.y;if(i*i+r*r>9)return"continue";const s=e.getShape(n.shapeId),a=e.getSelectedShapeIds();if(!s||!Td(s)||s.isLocked||e.getShapeEditingSession()||1!==a.length||a[0]!==s.id||Ks(e,s.id,"geo-label"))return"continue";const d=Ed(e,s);return d&&Zs(e,d,{editMarkId:KE,createMarkId:qE,isExisting:!1}),"continue"})(o,i,t,()=>{t=null});if("pointer"===i.type&&"pointer_cancel"===i.name)return n(),"continue";if(!o.isActiveToolInInitialState())return"continue";if("keyboard"===i.type&&"key_down"===i.name){if(o.getShapeEditingSession())return"continue";if("Enter"!==i.key||i.altKey||i.accelKey)return"continue";const e=o.getSelectedShapeIds(),[t]=o.getSelectedShapes();return 1===e.length&&t&&Us(t)&&o.canEditShape(t)?(o.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:XE},"user"),"handled"):"continue"}if("click"===i.type&&"double_click"===i.name)return n(),((e,t)=>{const n=e.hitTestShape(t.pagePoint);return n?Us(n)?e.canEditShape(n)?(e.startEditingShape({shapeId:n.id,entryMode:"selectAll",markId:XE},"user"),"handled"):"continue":Td(n)?((e,t)=>{if(t.isLocked)return"continue";const n=Ks(e,t.id,lE),o=n??Ed(e,t);return o?(Zs(e,o,{editMarkId:KE,createMarkId:qE,isExisting:!!n}),"handled"):"handled"})(e,n):Sd(e,n)?((e,t,n)=>{if(t.isLocked)return"continue";const o=Ks(e,t.id,dE),i=o??((e,t,n)=>{const o=Sd(e,t);if(!o)return null;const i=Bd(t,{...Ws(e),autoSize:!1,textAlign:"middle"}),r=o.getNearestPosition(n,{hintPosition:o.defaultPosition}),s=yd(e,i,t,r),a=qs(e,{bindingType:dE,owner:t,historyMarkId:HE,index:`${t.index}${zE}`,layout:s,bindingProps:{labelPosition:r}});if(!a)return null;const d=e.getShape(a.id),l=e.getBindingsFromShape(a.id).find(fd);if(!Us(d)||!l)return a;const c=Md({editor:e,label:d,pathGeometry:o,pagePoint:n,hintPosition:r,snapToDefault:!1});return Math.abs(c-r)>1e-6&&e.commands.updateBinding({id:l.id,props:{labelPosition:c}},{source:"user"}),a})(e,t,n);return i?(Zs(e,i,{editMarkId:YE,createMarkId:HE,isExisting:!!o}),"handled"):"handled"})(e,n,t.pagePoint):"continue":"continue"})(o,i);if("pointer"===i.type&&"pointer_down"===i.name){n();const r=((t,n)=>{const o=t.hitTestShape(n.pagePoint);if(!o||!Us(o)||!t.canEditShape(o))return"continue";const i=t.getShapeEditingSession();return i&&i.shapeId!==o.id?t.completeEditing("user")?(t.startEditingShape({shapeId:o.id,entryMode:"placeCaret",caretPagePoint:n.pagePoint,markId:XE,preserveInteraction:!0},"user"),"handled"):"handled":(!i&&(n.clickCount??1)<2&&((e,t)=>{const n=e.getSelectedShapeIds();if(1!==n.length)return!1;if(n[0]===t)return!0;const o=js(e,t);return!!o&&o.behavior.canPlaceCaretWhenOwnerSelected&&n[0]===o.ownerId})(t,o.id)&&(e={pointerId:n.pointerId,shapeId:o.id,originPagePoint:{x:n.pagePoint.x,y:n.pagePoint.y}}),"continue")})(o,i);return"handled"===r||e?r:((e,n)=>{const o=e.hitTestShape(n.pagePoint),i=e.getSelectedShapeIds();return!o||!Td(o)||o.isLocked||e.getShapeEditingSession()||n.shiftKey||n.altKey||n.accelKey||(n.clickCount??1)>=2||1!==i.length||i[0]!==o.id||Ks(e,o.id,"geo-label")||(t={pointerId:n.pointerId,shapeId:o.id,originPagePoint:{x:n.pagePoint.x,y:n.pagePoint.y}}),"continue"})(o,i)}return"continue"}},shapePointer:{createSession:(e,t)=>((e,t)=>{if(t.event.shiftKey||t.event.accelKey||e.getShapeEditingSession()||!Us(t.shape))return null;const n=e.getBindingsFromShape(t.shape.id).find(fd);if(!n||n.toId!==t.selectionTargetId)return null;const o=e.getShape(n.toId),i=e.getShapePageBounds(t.shape.id);if(!o||!i||e.isShapeOrAncestorLocked(o.id)||!Sd(e,o))return null;const r=i.center.sub(t.originPagePoint);return{shapeId:o.id,historyMark:_E,onDragStart({editor:e}){e.commands.setSelectedShapeIds([o.id],{source:"system"})},update({editor:e,pagePoint:t,source:o}){const i=e.getBinding(n.id),s=e.getShape(n.fromId),a=e.getShape(n.toId);if(!fd(i)||!Us(s)||!a)return"stop";const d=Sd(e,a);if(!d)return"stop";const l=Md({editor:e,label:s,pathGeometry:d,pagePoint:t.add(r),hintPosition:i.props.labelPosition,snapToDefault:!0});return Math.abs(l-i.props.labelPosition)>1e-6&&e.commands.updateBinding({id:i.id,props:{labelPosition:l}},{source:o}),{status:"continue",finalPagePoint:d.getPointAt(l)}}}})(e,t)}}}function Td(e){return"geo"===e.type}function Md({editor:e,label:t,pathGeometry:n,pagePoint:o,hintPosition:i,snapToDefault:r}){let s=n.getNearestPosition(o,{hintPosition:i});if(r){const t=n.defaultPosition,o=n.getPointAt(t),i=n.getPointAt(s),r=Math.max(e.cameraZoomSignal.get(),1e-4);i.dist(o)*r<=10&&(s=t)}const a=bd(e,t,n);return Math.min(a.end,Math.max(a.start,s))}function Ed(e,t){const n=kd(e,Bd(t,{...Ws(e),autoSize:!1,textAlign:"middle"}),t);return qs(e,{bindingType:lE,owner:t,historyMarkId:qE,index:`${t.index}${NE}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})}function Bd(e,t){return{id:"shape:draft",typeName:"shape",scope:"document",type:"text",parentId:e.parentId,index:`${e.index}.label`,x:0,y:0,rotation:0,skewX:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:t}}function Ad({fontCatalog:e=na()}={}){return{id:"land.text",shapeCapabilities:[{type:"text",schemaProps:["richText","w","h","autoSize","scale","font","size","color","backgroundColor","textAlign"],reactRenderer:"partial",toolbarEntry:"supported",notes:["Text shape util, SVG fallback, React renderer, rich editing runtime, creation tool, and selected-text style toolbar live in the text plugin package. React rendering remains partial while product-grade rich text rendering and measurement continue to mature."]}],shapeUtils:[new OE],shapeSvgExporters:[new DE(e)],bindingUtils:[new WE,new UE],interactionHandlers:[Cd()],setup(e){e.tools.register("text",e=>new RE(e),{shortcut:"t"})}}}function Rd({fontCatalog:e=na(),selectionFormattingToolbar:t=!0}={}){return n=>{n.capabilities.provide(GE,e),n.apis.add(VE),n.actions.add({id:"text.edit",getAvailability(e){if(1!==e.selection.count||"text"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;return"text"!==t?.type||t.isLocked?"disabled":"enabled"},run({context:e}){const[t]=e.selection.selectedShapes;"text"!==t?.type||t.isLocked||e.editor.startEditingShape({shapeId:t.id,entryMode:"focusEnd"},"user")}},Dd("color",e),{id:"text.set-background-color",getAvailability:e=>Ud(e),getValue(e){const t=Wd(e);return t?Yd(t.backgroundColor):(e=>{let t,n=!1;for(const o of e){if("text"!==o.type)continue;n=!0;const e=ha(o.props.richText);if("mixed"===e)return"mixed";const i=o.props,r=null!==e||z(i.backgroundColor)?e:D(i.backgroundColor);if(void 0===t)t=r;else if(t!==r)return"mixed"}return n?Yd(t??null):null})(e.selection.selectedShapes)},run({context:e,value:t}){const n=Hd(t);if(!n)return;const o=z(n)?null:D(n);if(zd(e))return void Nd(e)?.setBackgroundColor(o);const i=e.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).flatMap(e=>{const t=((e,t)=>{const n=ma(e.content,(e,n)=>{if("text"!==e.type||!e.text||n.insideCodeBlock||e.marks?.some(e=>"code"===e.type))return e;const o=e.marks??[],i=o.findIndex(e=>"textStyle"===e.type);if(i<0)return null===t?e:{...e,marks:[...o,{type:"textStyle",attrs:{backgroundColor:t}}]};const r=o[i];if((r?.attrs?.backgroundColor??null)===t)return e;const s={...r?.attrs};null===t?delete s.backgroundColor:s.backgroundColor=t;const a=Object.keys(s).length>0?o.map((e,t)=>t===i?{...e,attrs:s}:e):o.filter((e,t)=>t!==i);return{...e,marks:a.length>0?a:void 0}});return n.changed?Ss({...e,content:n.nodes}):e})(e.props.richText,o),i=!U(e.props.backgroundColor,n);return t!==e.props.richText||i?[{id:e.id,props:{backgroundColor:n,...t===e.props.richText?null:{richText:t}}}]:[]});i.length>0&&e.editor.commands.updateShapes(i,{source:"user"})}},Dd("font",e),Dd("size",e),Dd("textAlign",e),...tB.map(e=>{return{id:`text.toggle-${t=e.format}`,getAvailability:e=>Ud(e),getValue(e){const n=Wd(e);return n?n[t]:Xd(e.selection.selectedShapes,t)},run({context:e}){if(zd(e))return void Nd(e)?.toggle(t);const n=!0!==Xd(e.selection.selectedShapes,t),o=e.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).flatMap(e=>{const o=((e,t,n)=>{const o=fE[t],i=ma(e.content,(e,i)=>{if("text"!==e.type||!e.text)return e;const r=e.marks??[],s=r.filter(e=>o.includes(e.type));if(n&&(i.insideCodeBlock||r.some(e=>"code"===e.type)))return e;if(n&&1===s.length&&s[0]?.type===t)return e;const a=r.filter(e=>!o.includes(e.type)),d=n?[...a,{type:t}]:a;return r.length===d.length&&r.every((e,t)=>e===d[t])?e:{...e,marks:d.length>0?d:void 0}});return i.changed?Ss({...e,content:i.nodes}):e})(e.props.richText,t,n);return o===e.props.richText?[]:[{id:e.id,props:{richText:o}}]});o.length>0&&e.editor.commands.updateShapes(o,{source:"user"})}};var t}),{id:nB,getAvailability:e=>Ud(e),getValue:()=>!1,run({context:e}){if(zd(e))return void Nd(e)?.clearFormatting();const t=e.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).flatMap(e=>{const t=(e=>{const t=ma(e.content,e=>"text"===e.type&&e.marks&&e.marks.length>0?{...e,marks:void 0}:ga(e));return t.changed?Ss({...e,content:t.nodes}):e})(e.props.richText),n=B("transparent"),o=!U(e.props.backgroundColor,n);return t!==e.props.richText||o?[{id:e.id,props:{backgroundColor:n,...t===e.props.richText?null:{richText:t}}}]:[]});t.length>0&&e.editor.commands.updateShapes(t,{source:"user"})}},{id:oB,getAvailability:e=>1!==e.selection.count||"text"!==e.selection.commonShapeType?"inapplicable":Wd(e)?.canSetLink?"enabled":"disabled",getValue(e){const t=Wd(e)?.linkHref;return"string"==typeof t&&"mixed"!==t?t:""},run({context:e,value:t}){if("string"!=typeof t)return;const n=Nd(e);if(!n)return;if(0===t.trim().length)return void n.setLink(null);const o=hs(t);o&&n.setLink(o)}},_d("color",e),{id:"text.default-background-color",getAvailability:e=>"text"===e.tool.activeToolId?"enabled":"inapplicable",getValue:e=>e.editor.getDefaultShapeProps("text").backgroundColor,run({context:e,value:t}){const n=Hd(t);n&&e.editor.updateDefaultShapeProps("text",{backgroundColor:n})}},_d("font",e),_d("size",e),_d("textAlign",e)),n.toolbar.add({id:"text.tool-toolbar",channel:gM.toolSwitcher,order:50,actionIds:[pM],getGroups:e=>[{id:"text.tools",items:[{kind:"button",id:"text.tool.text",actionId:pM,value:"text",label:"Text",shortcut:e.editor.shortcuts.getToolShortcutLabel("text"),icon:"type",dataUi:"text-tool-button"}]}]},(e=>({id:"text.default-style.tool-toolbar",channel:gM.toolOptions,order:51,actionIds:["text.default-color","text.default-background-color","text.default-font","text.default-size","text.default-textAlign"],when:e=>"text"===e.tool.activeToolId,getGroups(){const[t,n,o,i]=Od({colorActionId:"text.default-color",fontActionId:"text.default-font",fontCatalog:e,sizeActionId:"text.default-size",textAlignActionId:"text.default-textAlign",dataUiPrefix:"text-default"});return[t,Fd("text-default","text.default-background-color"),n,o,i]}}))(e),...t?[$d(e),Ld(e)]:[]),n.contextMenu.add({id:"text.shape-context-menu",target:"selection",order:35,actionIds:["text.edit"],when:e=>1===e.selection.count&&"text"===e.selection.singleShapeType,getSections:()=>[{id:"text.context-menu",title:"Text",items:[{kind:"command",id:"text.edit",actionId:"text.edit",label:"Edit text",icon:"type",dataUi:"context-menu-edit-text-button"}]}]})}}function $d(e){return{id:"text.selection-toolbar",channel:gM.selectionQuickActions,order:20,actionIds:["text.set-color","text.set-background-color","text.set-font","text.set-size","text.set-textAlign",...tB.map(e=>e.actionId),nB,oB],subscribe:(e,t)=>((e,t)=>{const n=ca(e);return n.listeners.add(t),()=>{n.listeners.delete(t)}})(e,t),when:e=>1===e.selection.count&&"text"===e.selection.commonShapeType,getGroups(){const[t,n,o,i]=Od({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"});return[t,Fd("text"),n,o,{id:"text.inline-emphasis",items:tB.slice(0,2).map(e=>({kind:"button",id:e.actionId,actionId:e.actionId,label:e.label,icon:e.icon,dataUi:e.dataUi}))},{id:"text.inline-decoration",presentation:"overflow",items:tB.slice(2).map(e=>({kind:"button",id:e.actionId,actionId:e.actionId,label:e.label,icon:e.icon,dataUi:e.dataUi}))},{...i,presentation:"overflow"},{id:"text.clear-formatting",presentation:"overflow",items:[{kind:"button",id:nB,actionId:nB,label:"Clear formatting",icon:"remove-formatting",dataUi:"selected-text-clear-formatting-button"}]},{id:"text.link",presentation:"overflow",items:[{kind:"text-input",id:"text.link",actionId:oB,label:"Link",icon:"link",presentation:"popover",placeholder:"Link URL",validate:e=>0===e.trim().length||null!==hs(e),dataUi:"text-link-button"}]}]}}}function Ld(e){return{id:"text.multi-selection-toolbar",channel:gM.selectionProperties,order:20,actionIds:["text.set-color","text.set-background-color","text.set-font","text.set-size","text.set-textAlign"],when:e=>e.selection.count>1&&"text"===e.selection.commonShapeType&&null===e.editor.shapeEditingStateSignal.get().session,getGroups(){const[t,n,o,i]=Od({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"});return[t,Fd("text"),{...n,presentation:"overflow"},{...o,presentation:"overflow"},{...i,presentation:"overflow"}]}}}function Fd(e,t="text.set-background-color"){return{id:`${e}.style-background-color`,items:[{kind:"color-input",id:`${e}.background-color`,actionId:t,label:"Background",fallback:"#fef08a",presets:QE.map(t=>({...t,dataUi:`${e}-background-color-${t.id}-button`})),dataUi:`${e}.background-color`}]}}function Od({colorActionId:e,fontActionId:t,fontCatalog:n,sizeActionId:o,textAlignActionId:i,dataUiPrefix:r}){return[{id:`${r}.style-color`,items:[{kind:"color-input",id:`${r}.color`,actionId:e,label:"Color",fallback:"#0f172a",presets:ZE.map(e=>({...e,dataUi:`${r}-color-${e.id}-button`})),dataUi:`${r}.color`}]},{id:`${r}.style-font`,items:[{kind:"segmented",id:`${r}.font`,actionId:t,options:n.fontOptions.map(e=>({value:e.id,label:e.label,dataUi:`${r}-font-${e.id}-button`}))}]},{id:`${r}.style-size`,items:[{kind:"stepper",id:`${r}.size`,actionId:o,label:"Size",options:JE.map(e=>({value:e.value,label:e.label,dataUi:`${r}-size-${e.id}-button`}))}]},{id:`${r}.style-align`,items:[{kind:"segmented",id:`${r}.align`,actionId:i,options:eB.map(e=>({...e,dataUi:`${r}-align-${e.value}-button`}))}]}]}function Dd(e,t){return{id:`text.set-${e}`,getAvailability:e=>Ud(e),getValue(t){const n=Wd(t);return n?n[e]:((e,t)=>{let n;for(const o of e){if("text"!==o.type)continue;const e=o.props[t];if(void 0!==n){if("color"===t?!U(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e)},run({context:n,value:o}){const i=Kd(e,o,t);if(void 0===i)return;if(zd(n)){const t=Nd(n);if(!t)return;return void("color"===e?t.setColor(D(i)):"font"===e?t.setFont(i):"size"===e?t.setSize(i):t.setTextAlign(i))}const r=n.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).map(t=>{const n=((e,t)=>{const n=ma(e.content,e=>{if("textAlign"===t)return ga(e);if("text"!==e.type||!e.marks)return e;let n=!1;const o=e.marks.flatMap(e=>{if("textStyle"!==e.type||!e.attrs)return[e];const o={...e.attrs};let i=!1;const r="size"===t?["fontSize","lineHeight"]:"font"===t?["fontFamily"]:["color"];for(const t of r)t in o&&(delete o[t],i=!0);return i?(n=!0,Object.keys(o).length>0?[{...e,attrs:o}]:[]):[e]});return n?{...e,marks:o.length>0?o:void 0}:e});return n.changed?Ss({...e,content:n.nodes}):e})(t.props.richText,e);return{id:t.id,props:{[e]:i,...n===t.props.richText?null:{richText:n}}}});0!==r.length&&n.editor.commands.updateShapes(r,{source:"user"})}}}function zd(e){return null!==e.editor.shapeEditingStateSignal.get().session}function Ud(e){return"text"!==e.selection.commonShapeType?"inapplicable":(zd(e)?null!==Wd(e):e.selection.selectedShapes.some(e=>"text"===e.type&&!e.isLocked))?"enabled":"disabled"}function Nd(e){const t=e.editor.shapeEditingStateSignal.get().session,n=la(e.editor);return t&&n?.shapeId===t.shapeId?n:null}function Wd(e){const t=e.editor.shapeEditingStateSignal.get().session,n=(o=e.editor,la(o)?.getSnapshot()??null);var o;return t&&n?.shapeId===t.shapeId?n:null}function Xd(e,t){let n;for(const o of e){if("text"!==o.type)continue;const e=pa(o.props.richText,t);if("mixed"===e)return null;if(void 0===n)n=e;else if(n!==e)return null}return n??!1}function Yd(e){return"mixed"===e?e:B(e??"transparent")}function Hd(e){if($(e))return F(e,B("transparent"))}function _d(e,t){return{id:`text.default-${e}`,getAvailability:e=>"text"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("text")[e],run({context:n,value:o}){const i=Kd(e,o,t);void 0!==i&&n.editor.updateDefaultShapeProps("text",{[e]:i})}}}function Kd(e,t,n){if("color"===e)return $(t)?F(t,E("text-slate")):void 0;if("font"===e){if("string"!=typeof t)return;return((e,t)=>"default"===t||ia(t)&&e.fontsById.has(t))(n,t)?t:void 0}if("size"===e){if("number"!=typeof t||!Number.isFinite(t))return;return JE.some(e=>e.value===t)?t:void 0}return"string"==typeof t&&eB.some(e=>e.value===t)?t:void 0}function qd(e={}){const t={...ta(),...e},n=oa(t);return{id:"text",provides:[jE,GE],editor:Ad({fontCatalog:n}),render:td({fontCatalog:n,formattingToolbar:t.formattingToolbar,onTiptapEditorChange:t.onTiptapEditorChange}),setup:Rd({fontCatalog:n,selectionFormattingToolbar:!1!==t.formattingToolbar})}}function jd(e){return Math.max(0,Math.min(1,e))}function Vd(e,t,n){return e.computeShapePositionedToPageTransform(t).applyToPoint(((e,t,n)=>{const o=e.computeShapePositionedBounds(t);return new $C(o.minX+o.w*n.x,o.minY+o.h*n.y)})(e,t,n))}function Gd(e,t,n,o){return((e,t,n,o)=>e.getShapeUtil(t).resolveBindingPoint(t,{editor:e,rawPagePoint:n,oppositePagePoint:o}))(e,t,Vd(e,t,n),o)}function Zd(e,t){const n="start"===t?e.props.start:e.props.end;return((e,t)=>{if(0===e.rotation&&0===e.skewX&&1===e.scaleX&&1===e.scaleY)return t;const n=new $C(e.x+e.props.w/2,e.y+e.props.h/2),o=t.sub(n),i=new $C(o.x*e.scaleX,o.y*e.scaleY);return n.add(new $C(i.x+Math.tan(e.skewX)*i.y,i.y).rot(e.rotation))})(e,new $C(e.x+n.x,e.y+n.y))}function Qd(e,t,n){const o="start"===n?t.props.start:t.props.end;return e.computeShapeLocalToPageTransform(t).applyToPoint(new $C(o.x,o.y))}function Jd(e){return"start"===e?"end":"start"}function el(e,t,n,o){const i=e.computeShapeLocalToPageTransform(t).tryInvert();if(!i)return null;const r=nl(i.applyToPoint(n),i.applyToPoint(o)),s=e.getShapeUtil(t),a={...t,props:{...t.props,w:r.w,h:r.h,start:r.start,end:r.end}},d=ce(s.getLocalToPageTransform(t).compose(FC.Translate(r.x,r.y)),s.getLocalBounds(a),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return d?{...a,...d}:null}function tl(e,t,n,o){return el(e,t,"start"===n?o:Qd(e,t,"start"),"end"===n?o:Qd(e,t,"end"))}function nl(e,t){const n=ll(e.x,t.x),o=ll(e.y,t.y);return{x:n.origin,y:o.origin,w:n.size,h:o.size,start:{x:n.startOffset,y:o.startOffset},end:{x:n.endOffset,y:o.endOffset}}}function ol(e){return ul(new $C(e.props.start.x,e.props.start.y).add(new $C(e.x,e.y)),new $C(e.props.end.x,e.props.end.y).add(new $C(e.x,e.y)),e.props.bend)}function il(e){return ul(new $C(e.props.start.x,e.props.start.y),new $C(e.props.end.x,e.props.end.y),e.props.bend)}function rl(e,t,n){const o=$C.Med(e,t),i=t.sub(e);if(i.len()<1e-6)return 0;const r=i.per().normalize();return-Sl(n.sub(o),r)}function sl(e,t,n,o=.5){if(!t||t.length<=1e-6)return dl(o);let i=0,r=dl(o),s=1/0;for(let a=0;a<t.segmentLengths.length;a+=1){const d=e[a],l=t.segmentLengths[a],c=e[a+1].sub(d),u=l<=1e-6?0:dl(Sl(n.sub(d),c)/c.len2()),p=d.add(c.mul(u)),h=(i+l*u)/t.length,g=p.dist2(n),f=g<s-1e-8,m=Math.abs(g-s)<=1e-8&&Math.abs(h-o)<Math.abs(r-o);(f||m)&&(s=g,r=h),i+=l}return dl(r)}function al(e,t){const n=dl(e),o=dl(t);return n<=.5?o*n*2:o+(1-o)*(n-.5)*2}function dl(e){return Math.max(0,Math.min(1,e))}function ll(e,t){const n=Math.min(e,t),o=Math.max(e,t);return Math.abs(o-n)<1e-6?{origin:n-.5,size:1,startOffset:.5,endOffset:.5}:{origin:n,size:o-n,startOffset:e-n,endOffset:t-n}}function cl(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function ul(e,t,n){const o=function(e,t=0){return((e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t)(e,t)}(n,0),i=((e,t,n)=>{const o=$C.Med(e,t),i=t.sub(e),r=i.len()?i.per().normalize():new $C(0,-1);return o.add(r.mul(-n))})(e,t,o),r=((e,t,n)=>{const o=((e,t,n)=>{const o=-2*(e.x*(t.y-n.y)-e.y*(t.x-n.x)+t.x*n.y-n.x*t.y);if(Math.abs(o)<1e-6)return null;const i=((e.x*e.x+e.y*e.y)*(n.y-t.y)+(t.x*t.x+t.y*t.y)*(e.y-n.y)+(n.x*n.x+n.y*n.y)*(t.y-e.y))/o,r=((e.x*e.x+e.y*e.y)*(t.x-n.x)+(t.x*t.x+t.y*t.y)*(n.x-e.x)+(n.x*n.x+n.y*n.y)*(e.x-t.x))/o;return Number.isFinite(i)&&Number.isFinite(r)?new $C(i,r):null})(e,t,n);if(!o)return null;const i=o.dist(e);if(i<1e-6)return null;const r=((l=n).x-(a=e).x)*((d=t).y-a.y)-(d.x-a.x)*(l.y-a.y)<0?1:0,s=((e,t,n)=>{const o=e.dist(n),i=n.dist(t),r=t.dist(e);return i<1e-6||r<1e-6?0:2*Math.acos(Math.max(-1,Math.min(1,(i*i+r*r-o*o)/(2*i*r))))})(e,t,n);var a,d,l;if(!Number.isFinite(s))return null;const c=Math.PI>s?1:0,u=(rB-s)*(r?1:-1);return{center:o,radius:i,largeArcFlag:c,sweepFlag:r,size:u,length:Math.abs(u*i)}})(e,i,t),s=Math.abs(o)<1e-6||null===r||0===r.length||!Number.isFinite(r.length)||!Number.isFinite(r.radius),a=s?[e,t]:hl(e,t,r,24),d=s||null===r?`M ${cl(e.x)} ${cl(e.y)} L ${cl(t.x)} ${cl(t.y)}`:`M ${cl(e.x)} ${cl(e.y)} A ${cl(r.radius)} ${cl(r.radius)} 0 ${r.largeArcFlag} ${r.sweepFlag} ${cl(t.x)} ${cl(t.y)}`,l={start:{terminal:"start",point:e,handle:e},end:{terminal:"end",point:t,handle:t},middle:i,bend:o,points:a,bounds:LC.FromPoints(a),path:d};return s?{type:"straight",...l,arc:null}:{type:"curved",...l,arc:r}}function pl({start:e,end:t,middle:n,bend:o,arc:i,startHandle:r=e,endHandle:s=t}){const a=gl(e,t,i);if(Math.abs(a)<1e-6||!Number.isFinite(a)||!Number.isFinite(i.radius)||i.radius<1e-6){const i=ul(e,t,0);return{...i,start:{...i.start,handle:r},end:{...i.end,handle:s},middle:n,bend:o}}const d={center:i.center,radius:i.radius,largeArcFlag:Math.abs(a)>Math.PI?1:0,sweepFlag:i.sweepFlag,size:a,length:Math.abs(a*i.radius)},l=hl(e,t,d,24),c=`M ${cl(e.x)} ${cl(e.y)} A ${cl(d.radius)} ${cl(d.radius)} 0 ${d.largeArcFlag} ${d.sweepFlag} ${cl(t.x)} ${cl(t.y)}`;return{type:"curved",start:{terminal:"start",point:e,handle:r},end:{terminal:"end",point:t,handle:s},middle:n,arc:d,bend:o,points:l,bounds:LC.FromPoints(l),path:c}}function hl(e,t,n,o){const i=[],r=$C.Angle(n.center,e),s=gl(e,t,n);for(let a=0;a<=o;a++)i.push(ml(n.center,n.radius,r+s*(a/o)));return i}function gl(e,t,n){return o=$C.Angle(n.center,e),i=$C.Angle(n.center,t),n.sweepFlag?((i-o)%rB+rB)%rB:-((o-i)%rB+rB)%rB;var o,i}function fl(e,t,n,o){const i=$C.Angle(n.center,e),r=gl(e,t,n);return ml(n.center,n.radius,i+r*o)}function ml(e,t,n){return e.add(new $C(Math.cos(n)*t,Math.sin(n)*t))}function yl(e,t,n){const o=n.sub(t),i=o.x*o.x+o.y*o.y;if(0===i)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,Sl(r,o)/i)),a=t.add(o.mul(s));return e.dist(a)}function Sl(e,t){return e.x*t.x+e.y*t.y}function bl(e){return!!e&&"shape"===e.typeName&&"arrow"===e.type}function xl(e){return!!e&&"binding"===e.typeName&&"arrow"===e.type}function wl(e,t,n){return e.getBindingsFromShape(t.id).find(e=>xl(e)&&e.props.terminal===n)??null}function Il(e,t,n){const o=Qd(e,t,n),i=wl(e,t,n);if(!i)return{terminal:n,binding:null,target:null,handlePagePoint:o,boundaryPagePoint:o,isArcBoundaryPoint:!0};const r=e.getShape(i.toId);return!r||bl(r)?{terminal:n,binding:i,target:null,handlePagePoint:o,boundaryPagePoint:o,isArcBoundaryPoint:!0}:{terminal:n,binding:i,target:r,handlePagePoint:Vd(e,r,i.props.normalizedAnchor),boundaryPagePoint:o,isArcBoundaryPoint:!1}}function Pl(e,t){const n=Il(e,t,"start"),o=Il(e,t,"end"),i=Tl(e,t,n.handlePagePoint,o.handlePagePoint);return"curved"===i.type&&(Rl(e,n,i,"start"),Rl(e,o,i,"end")),{info:Ml(i,n,o),fullInfo:i,bindingSegments:[$l(n,i),$l(o,i)].filter(e=>null!==e)}}function vl(e,t){if(!wl(e,t,"start")&&!wl(e,t,"end"))return il(t);const n=e.computeShapeLocalToPageTransform(t).tryInvert();return n?((e,t,n)=>{const o=Cl(t.info,n);if("curved"!==t.info.type)return o;const i=ul(n.applyToPoint(t.fullInfo.start.point),n.applyToPoint(t.fullInfo.end.point),e.props.bend);if("curved"!==i.type)return o;const r=n.applyToPoint(t.info.start.point),s=n.applyToPoint(t.info.end.point),a=((e,t,n)=>{const o=t.sub(e);if(o.len2()<1e-12)return null;const i=$C.Med(e,t),r=o.per().normalize(),s=n.sub(i);return i.add(r.mul(s.x*r.x+s.y*r.y))})(r,s,i.arc.center);if(!a)return o;const d={center:a,radius:a.dist(r),sweepFlag:i.arc.sweepFlag},l=fl(r,s,d,.5);return pl({start:r,end:s,middle:l,bend:rl(r,s,l),arc:d,startHandle:n.applyToPoint(t.info.start.handle),endHandle:n.applyToPoint(t.info.end.handle)})})(t,Pl(e,t),n):ul(new $C(t.props.start.x,t.props.start.y),new $C(t.props.end.x,t.props.end.y),t.props.bend)}function kl(e,t,n){return{...e,start:{...e.start,handle:t},end:{...e.end,handle:n}}}function Cl(e,t){const n=e=>t.applyToPoint(e),o=n(e.start.point),i=n(e.end.point),r=n(e.middle),s=e.points.map(n),a=s.map((e,t)=>`${0===t?"M":"L"} ${Al(e.x)} ${Al(e.y)}`).join(" "),d={start:{...e.start,point:o,handle:n(e.start.handle)},end:{...e.end,point:i,handle:n(e.end.handle)},middle:r,bend:rl(o,i,r),points:s,bounds:LC.FromPoints(s),path:a};if("straight"===e.type)return{...e,...d};const l=n(e.arc.center),c={...e.arc,center:l,radius:l.dist(o),sweepFlag:t.determinant()<0?1===e.arc.sweepFlag?0:1:e.arc.sweepFlag};return(e=>{const t=Math.hypot(e.a,e.b),n=Math.hypot(e.c,e.d),o=Math.max(1,t,n);return Math.abs(t-n)<=1e-8*o&&Math.abs(e.a*e.c+e.b*e.d)<=1e-8*o*o})(t)?pl({start:o,end:i,middle:r,bend:d.bend,arc:c,startHandle:d.start.handle,endHandle:d.end.handle}):{...e,...d,arc:c}}function Tl(e,t,n,o){const i=e.computeShapeLocalToPageTransform(t),r=i.tryInvert();return r?Cl(ul(r.applyToPoint(n),r.applyToPoint(o),t.props.bend),i):ul(n,o,t.props.bend)}function Ml(e,t,n){if(t.boundaryPagePoint.dist2(e.start.point)<1e-10&&n.boundaryPagePoint.dist2(e.end.point)<1e-10)return kl(e,t.handlePagePoint,n.handlePagePoint);if("straight"===e.type)return kl(ul(t.boundaryPagePoint,n.boundaryPagePoint,0),t.handlePagePoint,n.handlePagePoint);if(e.path.includes(" A "))return pl({start:t.boundaryPagePoint,end:n.boundaryPagePoint,middle:fl(t.boundaryPagePoint,n.boundaryPagePoint,e.arc,.5),bend:e.bend,arc:e.arc,startHandle:t.handlePagePoint,endHandle:n.handlePagePoint});const o=El(e.points,t.boundaryPagePoint),i=El(e.points,n.boundaryPagePoint),r=[t.boundaryPagePoint];for(let a=Math.floor(o)+1;a<=Math.floor(i);a+=1){const t=e.points[a];t&&a<i&&r.push(t)}r.push(n.boundaryPagePoint);const s=(e=>{if(0===e.length)return $C.Zero();const t=[];let n=0;for(let i=0;i<e.length-1;i+=1){const o=e[i].dist(e[i+1]);t.push(o),n+=o}let o=n/2;for(let i=0;i<t.length;i+=1){const n=t[i];if(o<=n){const t=e[i];return t.add(e[i+1].sub(t).mul(0===n?0:o/n))}o-=n}return e[e.length-1]})(r);return{...e,start:{...e.start,point:t.boundaryPagePoint,handle:t.handlePagePoint},end:{...e.end,point:n.boundaryPagePoint,handle:n.handlePagePoint},middle:s,points:r,bounds:LC.FromPoints(r),path:Bl(r),bend:rl(t.boundaryPagePoint,n.boundaryPagePoint,s)}}function El(e,t){let n=0,o=1/0;for(let i=0;i<e.length-1;i+=1){const r=e[i],s=e[i+1].sub(r),a=s.len2(),d=0===a?0:Math.max(0,Math.min(1,((t.x-r.x)*s.x+(t.y-r.y)*s.y)/a)),l=r.add(s.mul(d)).dist2(t);l<o&&(o=l,n=i+d)}return n}function Bl(e){return e.map((e,t)=>`${0===t?"M":"L"} ${Al(e.x)} ${Al(e.y)}`).join(" ")}function Al(e){return Number(e.toFixed(3)).toString()}function Rl(e,t,n,o){if(!t.target)return void(t.isArcBoundaryPoint=!0);const i=Ol(e.getShapePageOutlineVertices(t.target.id),n,o);i?(t.boundaryPagePoint=i,t.isArcBoundaryPoint=!0):t.isArcBoundaryPoint=!1}function $l(e,t){if(!e.binding)return null;const n=((e,t)=>({terminal:e.terminal,anchorPagePoint:e.handlePagePoint,boundaryPagePoint:e.boundaryPagePoint,guidePath:"curved"===t.type&&e.isArcBoundaryPoint?Fl(e.terminal,e.handlePagePoint,e.boundaryPagePoint,t):null}))(e,t);return{terminal:n.terminal,anchorPagePoint:n.anchorPagePoint,boundaryPagePoint:n.boundaryPagePoint,guidePath:n.guidePath}}function Ll(e,{arrow:t,terminal:n,target:o,anchorPagePoint:i,fallbackBoundaryPagePoint:r}){const s=((e,t,n)=>Il(e,t,n).handlePagePoint)(e,t,Jd(n)),a=Tl(e,t,"start"===n?i:s,"end"===n?i:s);if("curved"!==a.type)return{terminal:n,anchorPagePoint:i,boundaryPagePoint:r,guidePath:null};const d=Ol(e.getShapePageOutlineVertices(o.id),a,n);return d?{terminal:n,anchorPagePoint:i,boundaryPagePoint:d,guidePath:Fl(n,i,d,a)}:{terminal:n,anchorPagePoint:i,boundaryPagePoint:r,guidePath:null}}function Fl(e,t,n,o){if(o.path.includes(" A "))return(({terminal:e,handlePagePoint:t,boundaryPagePoint:n,fullInfo:o})=>{if(t.dist(n)<1e-6)return null;const i="start"===e?o.arc.sweepFlag:(e=>e?0:1)(o.arc.sweepFlag),r={center:o.arc.center,radius:o.arc.radius,sweepFlag:i};return pl({start:t,end:n,middle:fl(t,n,r,.5),bend:o.bend,arc:r}).path})({terminal:e,handlePagePoint:t,boundaryPagePoint:n,fullInfo:o});const i=El(o.points,n),r=[t];if("start"===e)for(let s=1;s<=Math.floor(i);s+=1){const e=o.points[s];e&&s<i&&r.push(e)}else for(let s=o.points.length-2;s>=Math.ceil(i);s-=1){const e=o.points[s];e&&s>i&&r.push(e)}return r.push(n),Bl(r)}function Ol(e,t,n){const o=[];for(let i=0;i<t.points.length-1;i+=1){const n=t.points[i],r=t.points[i+1];for(let t=0;t<e.length;t+=1){const s=e[t],a=e[(t+1)%e.length];if(!s||!a)continue;const d=Dl(n,r,s,a);d&&o.push({point:d.point,position:i+d.t})}}return 0===o.length?null:(o.sort((e,t)=>e.position-t.position),"start"===n?o[0].point:o[o.length-1].point)}function Dl(e,t,n,o){const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<1e-9)return null;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d<-1e-9||d>1.000000001||l<-1e-9||l>1.000000001?null:{point:e.add(i.mul(Math.max(0,Math.min(1,d)))),t:Math.max(0,Math.min(1,d))}}function zl(e,t){const n=e.getShapePageBounds(t.id)??e.computeShapePageBounds(t);return n.w*n.h}function Ul(e,t){return e.getShapeUtil(t).canReceiveChildren(t)}function Nl(e,t){return!(!t||bl(t))&&e.getShapeUtil(t).canReceiveTerminalBinding(t,{editor:e})}function Wl(e,t,n){const o=Ul(e,t),i=Ul(e,n);if(o!==i)return o?1:-1;if(o&&i){const o=zl(e,t)-zl(e,n);if(Math.abs(o)>1e-6)return o}return 0}function Xl(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Yl(e){if(e)return{shapes:[e]}}function Hl(e,t,n="user"){if(t.parentId?.startsWith("shape:")){const n=e.getShape(t.parentId);if(!n||!e.computeShapeLocalToPageTransform(n).tryInvert())throw new Error("Cannot create an arrow inside a singular parent transform")}const[o]=e.commands.createShapes([{type:"arrow",x:t.startPagePoint.x,y:t.startPagePoint.y,parentId:t.parentId,props:t.props,meta:t.meta}],{source:n,autoReparent:!1});if(!bl(o))throw new Error("Failed to create arrow shape");const i=el(e,o,t.startPagePoint,t.endPagePoint);if(!i)throw new Error("Cannot create an arrow inside a singular parent transform");e.commands.updateShapes([{id:o.id,x:i.x,y:i.y,rotation:i.rotation,skewX:i.skewX,scaleX:i.scaleX,scaleY:i.scaleY,props:{...i.props}}],{source:n}),t.startBinding&&e.commands.createBinding({type:"arrow",fromId:i.id,toId:t.startBinding.targetShapeId,props:{terminal:"start",normalizedAnchor:t.startBinding.normalizedAnchor}},{source:n}),t.endBinding&&e.commands.createBinding({type:"arrow",fromId:i.id,toId:t.endBinding.targetShapeId,props:{terminal:"end",normalizedAnchor:t.endBinding.normalizedAnchor}},{source:n});const r=e.getShape(i.id);if(!bl(r))throw new Error("Failed to create arrow shape");return r}function _l(e,t,n,o,i="user"){if(!t)return e.setBindingPreview(o.preview),null;let r=null;return r=((e,t,n)=>{const o=e.getShape(t.shapeId);if(!bl(o))return null;const i=tl(e,o,t.terminal,t.pagePoint);if(!i)return null;e.commands.updateShapes([{id:o.id,x:i.x,y:i.y,rotation:i.rotation,skewX:i.skewX,scaleX:i.scaleX,scaleY:i.scaleY,props:{...i.props}}],{source:n});const r=e.getBindingsFromShape(o.id).find(e=>xl(e)&&e.props.terminal===t.terminal)??null;t.binding?xl(r)?e.commands.updateBinding({id:r.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n}):(r&&e.commands.deleteBinding(r.id,{source:n}),e.commands.createBinding({type:"arrow",fromId:o.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n})):r&&(e.commands.deleteBinding(r.id,{source:n}),e.commands.updateShapes([{id:o.id,x:i.x,y:i.y,rotation:i.rotation,skewX:i.skewX,scaleX:i.scaleX,scaleY:i.scaleY,props:{...i.props}}],{source:n}));const s=e.getShape(o.id);return bl(s)?s:i})(e,{shapeId:t,terminal:n,pagePoint:o.pagePoint,binding:o.binding},i),e.setBindingPreview(o.preview),r}function Kl(e,t){const n=[];return"arrow"===t.headStart&&n.push(jl(e,"start",t.strokeWidth)),"arrow"===t.headEnd&&n.push(jl(e,"end",t.strokeWidth)),{path:n.length>0?n.map(ql).join(" "):null,points:n.flat()}}function ql([e,t,n]){return[`M ${Vl(e.x)} ${Vl(e.y)}`,`L ${Vl(t.x)} ${Vl(t.y)}`,`L ${Vl(n.x)} ${Vl(n.y)}`].join(" ")}function jl(e,t,n){const o=e[t].point,i=((e,t)=>{if("curved"===e.type){const n=e[t].point.sub(e.arc.center).per().mul(1===e.arc.sweepFlag?1:-1).normalize();if(n.len2()>0)return n}const n=e.end.point.sub(e.start.point).normalize();return n.len2()>0?n:new $C(1,0)})(e,t),r=3.45*n*("start"===t?1:-1),s=i.per().mul(2*n),a=o.add(i.mul(r));return[a.sub(s),o,a.add(s)]}function Vl(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Gl(e,t){const n=e&&"object"==typeof e?e:void 0;return{x:Zl(n?.x,t.x),y:Zl(n?.y,t.y)}}function Zl(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ql(e,t,n){const o=n.sub(t),i=o.len2();if(0===i)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/i));return e.dist(t.add(o.mul(s)))}function Jl(e,t,n,o){return((e,t,n,o)=>{const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d>=0&&d<=1&&l>=0&&l<=1})(e,t,n,o)?0:Math.min(Ql(e,n,o),Ql(t,n,o),Ql(n,e,t),Ql(o,e,t))}function ec(e,{terminal:t,rawPagePoint:n,oppositePagePoint:o,excludeShapeId:i,ignoreTargets:r=!1}){if(r)return{pagePoint:n.clone(),binding:null,preview:null};const s=function(e,t,n,o){const i=((e,t)=>{let n=null;for(const o of t)(!n||Wl(e,o,n)<0)&&(n=o);return n})(e,e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget",filter:t=>t.id!==o?.excludeShapeId&&Nl(e,t)}));if(!i)return null;const r=((e,t,n)=>{const o=e.computeShapePositionedToPageTransform(t).tryInvert(),i=e.computeShapePositionedBounds(t);if(!o)return{x:.5,y:.5};const r=o.applyToPoint(n),s=i.h<=1e-6?.5:(r.y-i.minY)/i.h;return{x:jd(i.w<=1e-6?.5:(r.x-i.minX)/i.w),y:jd(s)}})(e,i,t);return{targetShape:i,normalizedAnchor:r,resolvedPagePoint:Gd(e,i,r,n),rawPagePoint:t.clone()}}(e,n,o,{excludeShapeId:i});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:nc(s),preview:oc(t,s)}}function tc(e,{arrow:t,terminal:n,rawPagePoint:o,ignoreTargets:i=!1}){const r=ec(e,{terminal:n,rawPagePoint:o,oppositePagePoint:Qd(e,t,Jd(n)),excludeShapeId:t.id,ignoreTargets:i});if(!r.preview)return r;const s=((e,{arrow:t,terminal:n,rawPagePoint:o,preview:i})=>{const r=e.getShape(i.targetShapeId);if(!r||bl(r))return i;const s=Ll(e,{arrow:t,terminal:n,target:r,anchorPagePoint:o,fallbackBoundaryPagePoint:i.resolvedPagePoint});return{...i,resolvedPagePoint:s.boundaryPagePoint,guidePath:s.guidePath}})(e,{arrow:t,terminal:n,rawPagePoint:o,preview:r.preview});return{...r,pagePoint:s.resolvedPagePoint,preview:s}}function nc(e){return e?{targetShapeId:e.targetShape.id,normalizedAnchor:e.normalizedAnchor}:null}function oc(e,t){return t?{terminal:e,targetShapeId:t.targetShape.id,rawPagePoint:t.rawPagePoint,resolvedPagePoint:t.resolvedPagePoint}:null}function ic(e,t){return{tag:"marker",attrs:{markerWidth:12,markerHeight:12,viewBox:"0 0 24 24",refX:"start"===e?2:22,refY:12,orient:"auto",markerUnits:"strokeWidth"},children:[{tag:"path",attrs:{d:"start"===e?"M8.9,8 L2,12 L8.9,16":"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:t,"stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}}]}}function rc({strokeActionId:e,strokeWidthActionId:t,directionActionId:n,dataUiPrefix:o}){return[{id:`${o}.style-stroke`,items:[{kind:"color-input",id:`${o}.stroke`,actionId:e,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:uB.map(e=>({...e,dataUi:`${o}-stroke-${e.id}-button`})),dataUi:`${o}.stroke`}]},{id:`${o}.style-stroke-width`,items:[{kind:"text-input",id:`${o}.stroke-width`,actionId:t,label:"Stroke width",placeholder:"2",suffix:"Px",validate:pc,dataUi:`${o}-stroke-width-control`}]},{id:`${o}.direction`,items:[{kind:"segmented",id:`${o}.direction`,actionId:n,options:pB.map(e=>({...e,label:`Arrow direction: ${e.label}`,dataUi:`${o}-direction-${e.value}-button`}))}]}]}function sc(e){return{id:`arrow.set-${e}`,getAvailability:e=>"arrow"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const o of e){if("arrow"!==o.type)continue;const e=o.props[t];if(void 0!==n){if("stroke"===t?!U(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const o=dc(e,n);if(void 0===o)return;const i=t.selection.selectedShapes.filter(e=>"arrow"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:o}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function ac(e){return{id:`arrow.default-${e}`,getAvailability:e=>"arrow"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("arrow")[e],run({context:t,value:n}){const o=dc(e,n);void 0!==o&&t.editor.updateDefaultShapeProps("arrow",{[e]:o})}}}function dc(e,t){return"strokeWidth"===e?uc(t):"stroke"===e&&$(t)?F(t,E("stroke-slate")):void 0}function lc(e,t){return"arrow"===e&&"arrow"===t?"both":"arrow"===e?"start":"arrow"===t?"end":"none"}function cc(e){if(!pB.some(t=>t.value===e))return null;switch(e){case"both":return{headStart:"arrow",headEnd:"arrow"};case"start":return{headStart:"arrow",headEnd:"none"};case"end":return{headStart:"none",headEnd:"arrow"};case"none":return{headStart:"none",headEnd:"none"}}}function uc(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function pc(e){return void 0!==uc(e)}function hc({dataUi:e,editor:t,idPrefix:n,shape:o,stroke:i,strokeWidth:r,vectorEffect:s}){const a=`${n}-content-clip-${o.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,d=vl(t,o),l=Kl(d,o.props),c=Ir(t.getShapeContentCutoutLocalPolygonsSignal(o.id)),u=Pi({outputBounds:d.bounds,cutoutLocalPolygons:c});
|
|
23
|
+
return Zk("svg",{"data-ui":e,width:"100%",height:"100%",viewBox:`0 0 ${o.props.w} ${o.props.h}`,overflow:"visible",children:[u?Gk("defs",{children:Gk("clipPath",{id:a,clipPathUnits:"userSpaceOnUse",children:Gk("path",{d:u,clipRule:"evenodd",fillRule:"evenodd"})})}):null,Zk("g",{clipPath:u?`url(#${a})`:void 0,children:[Gk("path",{"data-arrow-path":"body",d:d.path,fill:"none",stroke:i,strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:s}),l.path?Gk("path",{"data-arrow-path":"heads",d:l.path,fill:"none",stroke:i,strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:s}):null]})]})}function gc(e){return/^\s*$/.test(e)?"Frame":e}function fc(e){return new LC(0,-34,e.props.w,e.props.h+34)}function mc(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function yc(e,t,n){const o=n/2;return!!e.expand(o).containsPoint(t)&&(Math.abs(t.x-e.minX)<=o||Math.abs(t.x-e.maxX)<=o||Math.abs(t.y-e.minY)<=o||Math.abs(t.y-e.maxY)<=o)}function Sc(e){return{id:`frame.set-${e}`,getAvailability:e=>"frame"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const o of e){if("frame"!==o.type)continue;const e=o.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!U(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const o=Ic(e,n);if(void 0===o)return;const i=t.selection.selectedShapes.filter(e=>"frame"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:o}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function bc(e){return{id:`frame.default-${e}`,getAvailability:e=>"frame"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("frame")[e],run({context:t,value:n}){const o=Ic(e,n);void 0!==o&&t.editor.updateDefaultShapeProps("frame",{[e]:o})}}}function xc({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:o}){return[{id:`${o}.style-fill`,items:[{kind:"color-input",id:`${o}.fill`,actionId:e,label:"Fill",fallback:"#f8fafc",presets:bB.map(e=>({...e,dataUi:`${o}-fill-${e.id}-button`})),dataUi:`${o}.fill`}]},{id:`${o}.style-stroke`,items:[{kind:"color-input",id:`${o}.stroke`,actionId:t,label:"Stroke",previewStyle:"outline",fallback:"#94a3b8",presets:xB.map(e=>({...e,dataUi:`${o}-stroke-${e.id}-button`})),dataUi:`${o}.stroke`}]},{id:`${o}.style-stroke-width`,items:[{kind:"text-input",id:`${o}.stroke-width`,actionId:n,label:"Stroke width",placeholder:"1",suffix:"Px",validate:vc,dataUi:`${o}-stroke-width-control`}]}]}function wc(e){return{id:`frame.child-order.${e}`,getAvailability:t=>"frame"!==kc(t)?"inapplicable":t.editor.canMoveSelectionWithinParent(e)?"enabled":"disabled",run({context:t}){t.editor.moveSelectionWithinParent(e,"user")}}}function Ic(e,t){return"strokeWidth"===e?Pc(t):$(t)?F(t,"fill"===e?B("transparent"):E("stroke-muted")):void 0}function Pc(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function vc(e){return void 0!==Pc(e)}function kc(e){const[t]=e.selection.selectedShapes;return 1===e.selection.count&&t?.parentId.startsWith("shape:")?e.editor.getShape(t.parentId)?.type??null:null}function Cc({shape:e,hideName:t=!1}){const{fill:n,h:o,name:i,stroke:r,strokeWidth:s,w:a}=e.props,d=s/2,l=Math.max(a-s,0),c=Math.max(o-s,0),u=gc(i),p=fc(e);
|
|
24
|
+
return Zk("svg",{width:"100%",height:"100%",viewBox:`${p.x} ${p.y} ${p.w} ${p.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[Gk("rect",{x:d,y:d,width:l,height:c,fill:O(n),stroke:O(r),strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"}),t?null:Gk("text",{x:0,y:-8,fill:O(r),fontFamily:IB,fontSize:12,fontWeight:400,style:{userSelect:"none"},children:u})]})}function Tc({editor:e,shape:t,isEditing:n}){const o=Kk(null),i=Ir(e.cameraZoomSignal),r=Ir(e.getShapeLocalToPageTransformSignal(t.id)),s=Math.max(i,1e-4),a=Math.min(1/s,3.5),d=(e=>{const t=2*Math.PI;return Math.floor(2*((e%t+t)%t+Math.PI/4)/Math.PI%4)})(r?Math.atan2(r.b,r.a):0),l=0===d||2===d?t.props.w:t.props.h,c=((e,t)=>{switch(t){case 0:return"";case 1:return`translate(0px, ${e.props.h}px) rotate(270deg)`;case 2:return`translate(${e.props.w}px, ${e.props.h}px) rotate(180deg)`;case 3:return`translate(${e.props.w}px, 0px) rotate(90deg)`}})(t,d),u=gc(t.props.name);Wk(()=>{const e=o.current;n&&e&&(e.focus(),e.select())},[n]);const p=Uk(()=>{e.canEditShape(t)&&e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:"frame.edit"},"user")},[e,t]),h=Uk(n=>{e.commands.updateShapes([{id:t.id,props:{name:n.currentTarget.value}}],{source:"user"})},[e,t.id]),g=Uk(t=>{e.completeEditing("user")},[e]),f=Uk(t=>{e.setShapeEditingComposition(!0,"system")},[e]),m=Uk(t=>{e.setShapeEditingComposition(!1,"system")},[e]),y=Uk(t=>{if(t.stopPropagation(),!t.nativeEvent.isComposing)return"Enter"===t.key?(t.preventDefault(),void e.completeEditing("user")):void("Escape"===t.key&&(t.preventDefault(),e.cancelEditing("user")))},[e]),S=Uk(e=>{e.stopPropagation()},[]),b=Uk(e=>{e.stopPropagation(),n||p()},[n,p]);
|
|
25
|
+
return Gk("div",{style:{height:0,left:0,overflow:"visible",pointerEvents:"none",position:"absolute",top:34,width:0},children:Gk("div",{"data-ui":"frame-canvas-heading","data-shape-id":t.id,role:n?void 0:"button","aria-label":n?void 0:`Edit frame name: ${u}`,onClick:b,onPointerDown:S,style:{alignItems:"center",bottom:0,cursor:t.isLocked?"default":"text",display:"flex",fontFamily:IB,fontSize:12,fontWeight:400,maxWidth:l*s+16,minWidth:32,overflow:n?"visible":"hidden",paddingBottom:4,pointerEvents:t.isLocked?"none":"auto",position:"absolute",transform:`${c} scale(${a}) translateX(-7px)`,transformOrigin:"0 100%",userSelect:"none",whiteSpace:"pre"},children:Gk("div",{style:{alignItems:"center",background:"var(--land-canvas-bg, white)",borderRadius:4,boxShadow:"inset 0 0 0 1px var(--land-canvas-bg, white)",color:"var(--land-text-primary, #0f172a)",display:"flex",height:24,pointerEvents:"auto",width:"100%"},children:Zk("div",{style:{background:n?"var(--land-surface-bg, white)":void 0,borderRadius:4,boxShadow:n?"inset 0 0 0 1.5px var(--land-selection, #2563eb)":void 0,color:n?"transparent":"inherit",height:n?"100%":void 0,minWidth:n?32:void 0,overflow:n?"visible":"hidden",padding:"0 6px",pointerEvents:"auto",position:"relative",textOverflow:"ellipsis",whiteSpace:"pre",width:n?"auto":void 0},children:[Gk("input",{ref:o,"data-ui":"frame-canvas-name-input","data-shape-id":t.id,"aria-label":"Frame name",value:t.props.name,autoComplete:"off",disabled:!n,readOnly:!n,spellCheck:!1,onBlur:g,onChange:h,onCompositionStart:f,onCompositionEnd:m,onKeyDown:y,onPointerDown:S,style:{background:"none",border:0,borderRadius:4,boxSizing:"border-box",color:"var(--land-text-primary, #0f172a)",cursor:"text",display:n?void 0:"none",font:"inherit",height:"100%",inset:0,lineHeight:"24px",minWidth:0,outline:0,padding:"0 6px",position:"absolute",userSelect:"text",width:"100%"}}),u+String.fromCharCode(8203)]})})})})}function Mc(e,t,n){const o=e.getDefaultShapeProps("geo"),[i]=e.commands.createShapes([{type:"geo",x:n.x,y:n.y,meta:n.meta?{...n.meta}:void 0,props:{...o,geo:t,w:n.w??o.w,h:n.h??o.h,fill:n.fill??o.fill,stroke:n.stroke??o.stroke,strokeStyle:n.strokeStyle??o.strokeStyle,strokeWidth:n.strokeWidth??o.strokeWidth,cornerRadiusPercent:n.cornerRadiusPercent??o.cornerRadiusPercent}}],{source:"user"});return i&&"geo"===i.type?{id:i.id,type:i.type}:null}function Ec(e,t,n={}){return"ellipse"===t?((e,t=32)=>{const n=[];for(let o=0;o<t;o+=1){const i=o/t*Math.PI*2;n.push(new $C(e.center.x+e.w/2*Math.cos(i),e.center.y+e.h/2*Math.sin(i)))}return n})(e):Rc(e,t,n)}function Bc(e,t=12){return Math.min(50,Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t))}function Ac({cornerRadiusPercent:e=12,h:t,w:n}){return Math.min(Math.max(0,n),Math.max(0,t))*Bc(e)/100}function Rc(e,t,n={}){switch(t){case"rhombus":return[new $C(e.center.x,e.minY),new $C(e.maxX,e.center.y),new $C(e.center.x,e.maxY),new $C(e.minX,e.center.y)];case"triangle":return[new $C(e.center.x,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)];case"hexagon":return[new $C(e.minX+.25*e.w,e.minY),new $C(e.maxX-.25*e.w,e.minY),new $C(e.maxX,e.center.y),new $C(e.maxX-.25*e.w,e.maxY),new $C(e.minX+.25*e.w,e.maxY),new $C(e.minX,e.center.y)];case"star":return(e=>{const t=[];for(let n=0;n<10;n+=1){const e=-Math.PI/2+n*Math.PI/5,o=n%2==0?1:.48;t.push(new $C(Math.cos(e)*o,Math.sin(e)*o))}return((e,t)=>{const n=LC.FromPoints([...e]);return 0===n.w||0===n.h?[t.center]:e.map(e=>new $C(t.minX+(e.x-n.minX)/n.w*t.w,t.minY+(e.y-n.minY)/n.h*t.h))})(t,e)})(e);case"rectangle":return((e,t=Ac(e),n=4)=>{const o=Math.min(Math.max(0,t),Math.max(0,e.w)/2,Math.max(0,e.h)/2);if(0===o)return Fc(e);const i=[];return Lc(i,{centerX:e.maxX-o,centerY:e.minY+o,radius:o,startAngle:-Math.PI/2,endAngle:0,segments:n}),Lc(i,{centerX:e.maxX-o,centerY:e.maxY-o,radius:o,startAngle:0,endAngle:Math.PI/2,segments:n}),Lc(i,{centerX:e.minX+o,centerY:e.maxY-o,radius:o,startAngle:Math.PI/2,endAngle:Math.PI,segments:n}),Lc(i,{centerX:e.minX+o,centerY:e.minY+o,radius:o,startAngle:Math.PI,endAngle:3*Math.PI/2,segments:n}),i})(e,Ac({cornerRadiusPercent:n.cornerRadiusPercent,w:e.w,h:e.h}));default:return Fc(e)}}function $c(e,t){if(t.length<3)return!1;let n=!1;for(let o=0,i=t.length-1;o<t.length;i=o,o+=1){const r=t[o],s=t[i];if(r&&s){if(Oc(e,r,s)<=1e-6)return!0;r.y>e.y!=s.y>e.y&&e.x<(s.x-r.x)*(e.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}}return n}function Lc(e,{centerX:t,centerY:n,endAngle:o,radius:i,segments:r,startAngle:s}){const a=Math.max(1,Math.floor(r));for(let d=0;d<=a;d+=1){const r=s+d/a*(o-s);e.push(new $C(t+Math.cos(r)*i,n+Math.sin(r)*i))}}function Fc(e){return[new $C(e.minX,e.minY),new $C(e.maxX,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)]}function Oc(e,t,n){const o=n.sub(t),i=o.len2();if(0===i)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/i));return e.dist(t.add(o.mul(s)))}function Dc(e){return f(e)&&"geo"===e.type}function zc(e){return"string"==typeof e&&OB.includes(e)}function Uc(e){return"string"==typeof e&&DB.includes(e)}function Nc(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Wc(e,t){return e.x*t.y-e.y*t.x}function Xc(e,t,n){const o=n.sub(t),i=o.len2();if(0===i)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/i));return e.dist(t.add(o.mul(s)))}function Yc(e,t,n,o){return Hc(e,t,n,o)?0:Math.min(Xc(e,n,o),Xc(t,n,o),Xc(n,e,t),Xc(o,e,t))}function Hc(e,t,n,o){const i=t.sub(e),r=o.sub(n),s=Wc(i,r);if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=Wc(a,r)/s,l=Wc(a,i)/s;return d<0||d>1||l<0||l>1?null:{point:e.add(i.mul(d)),t:d}}function _c(e,t,n){let o=null;for(let i=0;i<n.length;i+=1){const r=n[i],s=n[(i+1)%n.length]??n[0];if(!r||!s)continue;const a=Hc(e,t,r,s);!a||a.t<=1e-6||(!o||a.t<o.t)&&(o=a)}return o?.point??null}function Kc(e){return Ec(new LC(0,0,e.props.w,e.props.h),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}function qc(e){const t=new LC(0,0,e.props.w,e.props.h);return[new $C(t.minX,t.minY),new $C(t.center.x,t.minY),new $C(t.maxX,t.minY),new $C(t.minX,t.center.y),t.center,new $C(t.maxX,t.center.y),new $C(t.minX,t.maxY),new $C(t.center.x,t.maxY),new $C(t.maxX,t.maxY)].map((e,t)=>({point:e,kind:zB[t]??"custom"}))}function jc(e,t){switch(e){case"dashed":return`${4*t} ${2*t}`;case"dotted":return"0 "+2*t;default:return}}function Vc(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Gc(e){return{id:`geo.set-${e}`,getAvailability:e=>"geo"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const o of e){if("geo"!==o.type)continue;const e=o.props[t];if(void 0!==n){if(!("fill"===t||"stroke"===t?U(n,e):n===e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const o=ou(e,n);if(void 0===o)return;const i=t.selection.selectedShapes.filter(Dc).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:o}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function Zc(e){return{id:`geo.default-${e}`,getAvailability:e=>ru(e.tool.activeToolId)?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("geo")[e],run({context:t,value:n}){const o=ou(e,n);void 0!==o&&t.editor.updateDefaultShapeProps("geo",{[e]:o})}}}function Qc({fillActionId:e,strokeActionId:t,strokeStyleActionId:n,strokeWidthActionId:o,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"color-input",id:`${i}.fill`,actionId:e,label:"Fill",fallback:"#e2e8f0",presets:UB.map(e=>({...e,dataUi:`${i}-fill-${e.id}-button`})),dataUi:`${i}.fill`}]},{id:`${i}.style-stroke`,items:[{kind:"color-input",id:`${i}.stroke`,actionId:t,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:NB.map(e=>({...e,dataUi:`${i}-stroke-${e.id}-button`})),dataUi:`${i}.stroke`}]},{id:`${i}.stroke-style`,presentation:"overflow",items:[{kind:"segmented",id:`${i}.stroke-style`,actionId:n,options:WB.map(e=>({...e,dataUi:`${i}-stroke-style-${e.value}-button`}))}]},{id:`${i}.style-stroke-width`,items:[{kind:"text-input",id:`${i}.stroke-width`,actionId:o,label:"Stroke width",placeholder:"2",suffix:"Px",validate:nu,dataUi:`${i}-stroke-width-control`}]}]}function Jc(e){let t=null;for(const n of e)if(Dc(n))if(null!==t){if(t!==n.props.geo)return null}else t=n.props.geo;return t}function eu(e){if("string"!=typeof e||0===e.trim().length)return null;const t=Number(e);return Number.isFinite(t)?t:null}function tu(e){const t=eu(e);return null!==t&&t>=0&&t<=50}function nu(e){return void 0!==iu(e)}function ou(e,t){return"strokeWidth"===e?iu(t):"strokeStyle"===e?Uc(t)?t:void 0:$(t)?F(t,E("fill"===e?"fill-slate":"stroke-slate")):void 0}function iu(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function ru(e){return XB.some(t=>t.value===e)}function su({shape:e,fill:t=e.props.fill,stroke:n=e.props.stroke,strokeStyle:o=e.props.strokeStyle,strokeWidth:i=e.props.strokeWidth}){const{geo:r}=e.props,s="none"===o?0:i,a=s/2,d=Math.max(e.props.w-s,0),l=Math.max(e.props.h-s,0),c=Ac({cornerRadiusPercent:e.props.cornerRadiusPercent,w:d,h:l}),u="ellipse"===r||"rectangle"===r?null:Rc(new LC(a,a,d,l),r).map(e=>`${e.x},${e.y}`).join(" "),p={fill:O(t),stroke:"none"===o?"none":O(n),strokeWidth:s,strokeDasharray:jc(o,i),strokeLinejoin:"round",strokeLinecap:"round"};
|
|
26
|
+
return Gk("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:"ellipse"===r?Gk("ellipse",{...p,cx:e.props.w/2,cy:e.props.h/2,rx:d/2,ry:l/2}):"rectangle"!==r?Gk("polygon",{...p,points:u??""}):Gk("rect",{...p,x:a,y:a,width:d,height:l,rx:c,ry:c})})}function au(e,t){if(!Object.isFrozen(e))return du(e,t);const n=e,o=KB.get(n),i=o?.[t];if(i)return i;const r=du(e,t);return KB.set(n,{...o,[t]:r}),r}function du(e,t){const n=(e=>JSON.parse(JSON.stringify(e)))(e),o=n.surfaces[t].prepress,i=new Map(n.points.map(e=>[e.id,new $C(e.x,e.y)])),r=new Map,s=new Map;for(const b of n.edges){const e=i.get(b.fromPointId),t=i.get(b.toPointId);if(!e||!t)throw new Error(`Packaging edge "${b.id}" references a missing point.`);const n=Su(b,e,t);r.set(b.id,n),s.set(b.id,n.path)}const a=new Map,d=new Map,l=new Map,c=new Map,u=new Map,p=new Set;for(const b of n.faces){const e=cu(b.outer,r),t=bu(b.outer,r),n=(b.holes??[]).map(e=>{for(const t of e.edges)p.add(t.edgeId);return cu(e,r)}),o=(b.holes??[]).map(e=>bu(e,r)),i=uu(b.outer,r),s=(b.holes??[]).map(e=>uu(e,r)),h=e.length>0?LC.FromPoints(e):new LC(0,0,0,0),g=Xu(e,n,h);a.set(b.id,{face:b,bounds:h,center:g,outerPath:i,holePaths:s,outer:e,holes:n,outerEdges:t,holeEdges:o}),d.set(b.id,i),l.set(b.id,[[e,...n]]),c.set(b.id,[...s]),u.set(b.id,g)}const h=[...i.values(),...Array.from(r.values()).flatMap(e=>[...Yu(e.bounds),...e.extrema])],g=h.length>0?LC.FromPoints(h):new LC(0,0,0,0),f=(e=>{const t=[...e.values()].flatMap(e=>e.outerEdges.filter(e=>"cut"===e.edge.operation).flatMap(e=>Yu(e.bounds)));return t.length>0?LC.FromPoints(t):null})(a),m=new Map((o?.bleedContours??[]).map(e=>[e.id,lu(e.contour,e)])),y=LC.FromPoints([...Yu(g),...Array.from(m.values()).flatMap(e=>e.samples.map(e=>e.clone()))]),S=new Map((o?.safeZones??[]).map(e=>[e.id,lu(e.contour,e)]));return{bounds:g,outerBounds:y,dielineBounds:f,pointsById:i,edgesById:r,facesById:a,facePaths:d,facePolygons:l,holePaths:c,edgePaths:s,faceCenters:u,snapPoints:Lu({bounds:g,pointsById:i,edgesById:r,faceCenters:u}),spatialIndex:Fu(a),holeEdgeIds:p,bleedContoursById:m,safeZonesById:S}}function lu(e,t){const n=new $C(e.start.x,e.start.y);let o=n;const i=[`M ${Hu(n)}`],r=[n.clone()],s=[n.clone()];for(const a of e.segments){const e=new $C(a.to.x,a.to.y),t=Pu(a),n=Iu(t,o,e),d="line"===t.type?[o.clone(),e.clone()]:xu(n),l=vu(t,o,e);i.push(Cu(t,e)),r.push(...d.slice(1)),s.push(e.clone(),...l),o=e}return r.length>1&&r[0].dist2(r[r.length-1])<=_B&&r.pop(),i.push("Z"),{source:t??e,path:i.join(" "),samples:r,bounds:LC.FromPoints(s)}}function cu(e,t){const n=[];for(const o of e.edges){const e=t.get(o.edgeId);if(!e)throw new Error(`Packaging loop references missing edge "${o.edgeId}".`);const i="forward"===o.direction?e.samples:[...e.samples].reverse();for(let t=0;t<i.length;t+=1)n.length>0&&0===t||n.push(i[t].clone())}return n.length>1&&n[0].dist2(n[n.length-1])<=_B&&n.pop(),n}function uu(e,t){const n=e.edges[0];if(!n)return"";const o=t.get(n.edgeId);if(!o)throw new Error(`Packaging loop references missing edge "${n.edgeId}".`);const i=[`M ${Hu("forward"===n.direction?o.from:o.to)}`];for(const r of e.edges){const e=t.get(r.edgeId);if(!e)throw new Error(`Packaging loop references missing edge "${r.edgeId}".`);i.push(ku(e,r))}return i.push("Z"),i.join(" ")}function pu(e,t){const n=e.spatialIndex.searchPoint(t);for(let o=n.length-1;o>=0;o-=1){const i=e.facesById.get(n[o]);if(i&&(Du(t,i)||hu(t,i)))return i}return null}function hu(e,t){return Ou(e,t.outer)&&!t.holes.some(t=>Ou(e,t))}function gu(e,t){if(0===t.length)return[];const n=LC.FromPoints([...t]),o=[];for(const i of e.spatialIndex.searchBounds(n)){const n=e.facesById.get(i);n&&zu(t,n)&&o.push(i)}return o}function fu(e,t){if(!e)return[];const[n,o,i,r]=(e=>[new $C(e.minX,e.minY),new $C(e.maxX,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)])(e),s=Math.max(0,t.horizontalLength),a=Math.max(0,t.verticalLength);return[`M ${_u(n.x-s,n.y)} L ${Hu(n)} L ${_u(n.x,n.y-a)}`,`M ${_u(o.x+s,o.y)} L ${Hu(o)} L ${_u(o.x,o.y-a)}`,`M ${_u(i.x+s,i.y)} L ${Hu(i)} L ${_u(i.x,i.y+a)}`,`M ${_u(r.x-s,r.y)} L ${Hu(r)} L ${_u(r.x,r.y+a)}`]}function mu(e,t){const[n,o]=(()=>{switch(e){case"crease":case"score":case"construction":return[3,2];default:return[2,3]}})();return`${Ku(t*n)} ${Ku(t*o)}`}function yu(e){const[t,n,o,i,r,s]=e,a=t*i-n*o;return!Number.isFinite(a)||Math.abs(a)<=_B?null:[i/a,-n/a,-o/a,t/a,(o*s-i*r)/a,(n*r-t*s)/a]}function Su(e,t,n){const o=Iu(e.geometry,t,n),i="line"===e.geometry.type?[t.clone(),n.clone()]:xu(o),r=vu(e.geometry,t,n),s=LC.FromPoints([t,n,...r]);return{edge:e,from:t.clone(),to:n.clone(),path:`M ${Hu(t)} ${Cu(e.geometry,n)}`,bounds:s,midpoint:o(.5),extrema:r,samples:i,pointAt:o}}function bu(e,t){return e.edges.map(e=>{const n=t.get(e.edgeId);if(!n)throw new Error(`Packaging loop references missing edge "${e.edgeId}".`);return n})}function xu(e){const t=e(0),n=[t];return wu(e,0,t,1,e(1),0,n),n}function wu(e,t,n,o,i,r,s){const a=o-t,d=e(t+.25*a),l=t+.5*a,c=e(l),u=e(t+.75*a),p=.0025000000000000005;Wu(d,n,i)<=p&&Wu(c,n,i)<=p&&Wu(u,n,i)<=p||r>=12?s.push(i):(wu(e,t,n,l,c,r+1,s),wu(e,l,c,o,i,r+1,s))}function Iu(e,t,n){switch(e.type){case"line":return e=>((e,t,n)=>new $C(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n))(t,n,e);case"quadratic":{const o=new $C(e.control.x,e.control.y);return e=>Bu(t,o,n,e)}case"cubic":{const o=new $C(e.control1.x,e.control1.y),i=new $C(e.control2.x,e.control2.y);return e=>Au(t,o,i,n,e)}case"arc":{const o=Tu(t,n,e);return e=>((e,t)=>Mu(e,e.startAngle+e.deltaAngle*t))(o,e)}}}function Pu(e){switch(e.type){case"line":return{type:"line"};case"quadratic":return{type:"quadratic",control:e.control};case"cubic":return{type:"cubic",control1:e.control1,control2:e.control2};case"arc":return{type:"arc",radiusX:e.radiusX,radiusY:e.radiusY,rotation:e.rotation,largeArc:e.largeArc,sweep:e.sweep}}}function vu(e,t,n){switch(e.type){case"line":return[];case"quadratic":{const o=new $C(e.control.x,e.control.y),i=new Set;return Ru(t.x,o.x,n.x,i),Ru(t.y,o.y,n.y,i),[...i].map(e=>Bu(t,o,n,e))}case"cubic":{const o=new $C(e.control1.x,e.control1.y),i=new $C(e.control2.x,e.control2.y),r=new Set;for(const e of $u(t.x,o.x,i.x,n.x))r.add(e);for(const e of $u(t.y,o.y,i.y,n.y))r.add(e);return[...r].map(e=>Au(t,o,i,n,e))}case"arc":{const o=Tu(t,n,e),{radiusX:i,radiusY:r,rotation:s}=o;return[Math.atan2(-r*Math.sin(s),i*Math.cos(s)),Math.atan2(-r*Math.sin(s),i*Math.cos(s))+Math.PI,Math.atan2(r*Math.cos(s),i*Math.sin(s)),Math.atan2(r*Math.cos(s),i*Math.sin(s))+Math.PI].filter(e=>((e,t,n)=>n>=0?Eu(e-t)<=n+_B:Eu(t-e)<=-n+_B)(e,o.startAngle,o.deltaAngle)).map(e=>Mu(o,e))}}}function ku(e,t){if("forward"===t.direction)return Cu(e.edge.geometry,e.to);const n=e.edge.geometry;switch(n.type){case"line":return`L ${Hu(e.from)}`;case"quadratic":return`Q ${_u(n.control.x,n.control.y)} ${Hu(e.from)}`;case"cubic":return`C ${_u(n.control2.x,n.control2.y)} ${_u(n.control1.x,n.control1.y)} ${Hu(e.from)}`;case"arc":return`A ${Ku(n.radiusX)} ${Ku(n.radiusY)} ${Ku(n.rotation)} ${n.largeArc?1:0} ${n.sweep?0:1} ${Hu(e.from)}`}}function Cu(e,t){switch(e.type){case"line":return`L ${Hu(t)}`;case"quadratic":return`Q ${_u(e.control.x,e.control.y)} ${Hu(t)}`;case"cubic":return`C ${_u(e.control1.x,e.control1.y)} ${_u(e.control2.x,e.control2.y)} ${Hu(t)}`;case"arc":return`A ${Ku(e.radiusX)} ${Ku(e.radiusY)} ${Ku(e.rotation)} ${e.largeArc?1:0} ${e.sweep?1:0} ${Hu(t)}`}}function Tu(e,t,n){const o=n.rotation*Math.PI/180,i=Math.cos(o),r=Math.sin(o),s=(e.x-t.x)/2,a=(e.y-t.y)/2,d=i*s+r*a,l=-r*s+i*a;let c=Math.abs(n.radiusX),u=Math.abs(n.radiusY);const p=d*d/(c*c)+l*l/(u*u);if(p>1){const e=Math.sqrt(p);c*=e,u*=e}const h=c*c,g=u*u,f=Math.max(0,h*g-h*l*l-g*d*d),m=h*l*l+g*d*d,y=m<=_B?0:(n.largeArc===n.sweep?-1:1)*Math.sqrt(f/m),S=y*(c*l/u),b=y*(-u*d/c),x=new $C(i*S-r*b+(e.x+t.x)/2,r*S+i*b+(e.y+t.y)/2),w=new $C((d-S)/c,(l-b)/u),I=new $C((-d-S)/c,(-l-b)/u),P=Math.atan2(w.y,w.x);let v=((e,t)=>Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y))(w,I);return!n.sweep&&v>0?v-=HB:n.sweep&&v<0&&(v+=HB),{center:x,radiusX:c,radiusY:u,rotation:o,startAngle:P,deltaAngle:v}}function Mu(e,t){const n=Math.cos(e.rotation),o=Math.sin(e.rotation),i=Math.cos(t),r=Math.sin(t);return new $C(e.center.x+e.radiusX*i*n-e.radiusY*r*o,e.center.y+e.radiusX*i*o+e.radiusY*r*n)}function Eu(e){return(e%HB+HB)%HB}function Bu(e,t,n,o){const i=1-o;return new $C(i*i*e.x+2*i*o*t.x+o*o*n.x,i*i*e.y+2*i*o*t.y+o*o*n.y)}function Au(e,t,n,o,i){const r=1-i;return new $C(r*r*r*e.x+3*r*r*i*t.x+3*r*i*i*n.x+i*i*i*o.x,r*r*r*e.y+3*r*r*i*t.y+3*r*i*i*n.y+i*i*i*o.y)}function Ru(e,t,n,o){const i=e-2*t+n;if(Math.abs(i)<=_B)return;const r=(e-t)/i;r>_B&&r<.999999999&&o.add(r)}function $u(e,t,n,o){const i=3*t-e-3*n+o,r=2*(e-2*t+n),s=t-e;if(Math.abs(i)<=_B){if(Math.abs(r)<=_B)return[];const e=-s/r;return e>_B&&e<.999999999?[e]:[]}const a=r*r-4*i*s;if(a<0)return[];const d=Math.sqrt(a);return[(-r+d)/(2*i),(-r-d)/(2*i)].filter(e=>e>_B&&e<.999999999)}function Lu({bounds:e,pointsById:t,edgesById:n,faceCenters:o}){const i=[];for(const r of Yu(e))i.push({point:r.clone(),kind:"corner",weight:100});for(const r of t.values())i.push({point:r.clone(),kind:"custom",weight:20});for(const r of n.values())if(i.push({point:r.midpoint.clone(),kind:"edge_midpoint",weight:10}),"arc"===r.edge.geometry.type)for(const e of r.extrema)i.push({point:e.clone(),kind:"custom",weight:12});for(const r of o.values())i.push({point:r.clone(),kind:"center",weight:5});return(e=>{const t=new Map;for(const n of e){const e=`${n.point.x.toFixed(8)}:${n.point.y.toFixed(8)}`,o=t.get(e);(!o||(n.weight??0)>(o.weight??0))&&t.set(e,n)}return[...t.values()]})(i)}function Fu(e){const t=[...e.values()].map(e=>({id:e.face.id,bounds:e.bounds}));return{searchPoint:e=>t.filter(t=>t.bounds.containsPoint(e)).map(e=>e.id),searchBounds:e=>t.filter(t=>t.bounds.intersects(e)).map(e=>e.id)}}function Ou(e,t){if(t.length<3)return!1;let n=!1;for(let o=0,i=t.length-1;o<t.length;i=o,o+=1){const r=t[o],s=t[i];if(Wu(e,s,r)<=_B)return!0;r.y>e.y!=s.y>e.y&&e.x<(s.x-r.x)*(e.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n}function Du(e,t){return[t.outerEdges,...t.holeEdges].some(t=>t.some(t=>t.samples.slice(1).some((n,o)=>Wu(e,t.samples[o],n)<=.0025000010000000004)))}function zu(e,t){if(e.some(e=>hu(e,t)))return!0;if(t.outer.some(t=>Ou(t,e)))return!0;for(let n=0;n<e.length;n+=1){const o=e[n],i=e[(n+1)%e.length];for(let e=0;e<t.outer.length;e+=1)if(Uu(o,i,t.outer[e],t.outer[(e+1)%t.outer.length]))return!0}return!1}function Uu(e,t,n,o){const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<=_B)return Wu(e,n,o)<=_B||Wu(t,n,o)<=_B||Wu(n,e,t)<=_B||Wu(o,e,t)<=_B;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d>=-1e-9&&d<=1.000000001&&l>=-1e-9&&l<=1.000000001}function Nu(e,t,n,o){return Uu(e,t,n,o)?0:Math.min(Wu(e,n,o),Wu(t,n,o),Wu(n,e,t),Wu(o,e,t))}function Wu(e,t,n){const o=n.sub(t),i=o.len2();if(i<=_B)return e.dist2(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/i));return e.dist2(t.add(o.mul(s)))}function Xu(e,t,n){const o=(e=>{if(e.length<3)return null;let t=0,n=0,o=0;for(let i=0;i<e.length;i+=1){const r=e[i],s=e[(i+1)%e.length],a=r.x*s.y-s.x*r.y;t+=a,n+=(r.x+s.x)*a,o+=(r.y+s.y)*a}return Math.abs(t)<=_B?null:new $C(n/(3*t),o/(3*t))})(e)??n.center,i=n=>Ou(n,e)&&!t.some(e=>Ou(n,e));if(i(o))return o;const r=[];for(let s=0;s<9;s+=1)for(let e=0;e<9;e+=1)r.push(new $C(n.minX+(e+.5)/9*n.w,n.minY+(s+.5)/9*n.h));return r.sort((e,t)=>e.dist2(o)-t.dist2(o)),r.find(i)?.clone()??e[0]?.clone()??n.center}function Yu(e){return[new $C(e.minX,e.minY),new $C(e.maxX,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)]}function Hu(e){return _u(e.x,e.y)}function _u(e,t){return`${Ku(e)} ${Ku(t)}`}function Ku(e){return Number(e.toFixed(6)).toString()}function qu(e){return e.runtime.require(qB)}function ju(e){const t=e.meta[jB];return"outside"===t||"inside"===t?t:null}function Vu(e){if(e&&"object"==typeof e&&eA.has(e))return e;const t=Ip(e,"PackagingDocument");if(Tp(t,["schemaVersion","id","revision","name","unit","coordinateSystem","points","edges","faces","surfaces"],["sheetBounds","source","meta"],"PackagingDocument"),1!==t.schemaVersion&&Mp("PackagingDocument.schemaVersion must equal 1."),vp(t.id,"PackagingDocument.id"),vp(t.revision,"PackagingDocument.revision"),vp(t.name,"PackagingDocument.name"),GB.has(t.unit)||Mp("PackagingDocument.unit is invalid."),"top-left-y-down"!==t.coordinateSystem&&Mp('PackagingDocument.coordinateSystem must equal "top-left-y-down".'),void 0!==t.sheetBounds){const e=Ip(t.sheetBounds,"PackagingDocument.sheetBounds");Tp(e,["x","y","w","h"],[],"PackagingDocument.sheetBounds"),kp(e.x,"PackagingDocument.sheetBounds.x"),kp(e.y,"PackagingDocument.sheetBounds.y"),Cp(e.w,"PackagingDocument.sheetBounds.w"),Cp(e.h,"PackagingDocument.sheetBounds.h")}const n=Pp(t.points,"PackagingDocument.points"),o=new Set;for(let c=0;c<n.length;c+=1){const e=Ip(n[c],`PackagingDocument.points[${c}]`);Tp(e,["id","x","y"],[],`PackagingDocument.points[${c}]`);const t=wp(e.id,o,`PackagingDocument.points[${c}].id`);kp(e.x,`Packaging point "${t}".x`),kp(e.y,`Packaging point "${t}".y`)}const i=Pp(t.edges,"PackagingDocument.edges"),r=new Set;for(let c=0;c<i.length;c+=1)Zu(i[c],c,r,o);const s=Pp(t.faces,"PackagingDocument.faces"),a=new Set;for(let c=0;c<s.length;c+=1)Qu(s[c],c,a,r);if(((e,t,n)=>{const o=Ip(e,"PackagingDocument.surfaces");Tp(o,[...QB],[],"PackagingDocument.surfaces");for(const i of QB){const e=`PackagingDocument.surfaces.${i}`,r=Ip(o[i],e);Tp(r,[],["prepress","meta"],e),void 0!==r.prepress&&Ju(r.prepress,t,n,`${e}.prepress`),void 0!==r.meta&&Sp(r.meta,`${e}.meta`)}})(t.surfaces,r,a),void 0!==t.source){const e=Ip(t.source,"PackagingDocument.source");Tp(e,[],["provider","externalId","revision"],"PackagingDocument.source");for(const t of["provider","externalId","revision"])void 0!==e[t]&&vp(e[t],`PackagingDocument.source.${t}`)}void 0!==t.meta&&Sp(t.meta,"PackagingDocument.meta");const d=e;(e=>{const t=new Map(e.edges.map(e=>[e.id,e])),n=du(e,"outside");for(const o of e.faces){lp(o.outer,o,"outer",t,n.edgesById);const e=n.facesById.get(o.id);e||Mp(`Packaging face "${o.id}" could not be compiled.`);for(let i=0;i<(o.holes?.length??0);i+=1){lp(o.holes[i],o,`holes[${i}]`,t,n.edgesById);const r=e.holes[i];r.every(t=>mp(t,e.outer))||Mp(`Packaging face "${o.id}" hole ${i} must be inside its outer loop.`),hp(r,e.outer)&&Mp(`Packaging face "${o.id}" hole ${i} intersects its outer loop.`);for(let t=0;t<i;t+=1){const n=e.holes[t];(hp(r,n)||mp(r[0],n)||mp(n[0],r))&&Mp(`Packaging face "${o.id}" holes ${t} and ${i} overlap.`)}}}})(d);for(const c of QB)op(d,c);const l=(e=>xp(e))(Gu(d));return eA.add(l),l}function Gu(e){return JSON.parse(JSON.stringify(e))}function Zu(e,t,n,o){const i=`PackagingDocument.edges[${t}]`,r=Ip(e,i);Tp(r,["id","fromPointId","toPointId","geometry","operation"],["visible","meta"],i);const s=wp(r.id,n,`${i}.id`);vp(r.fromPointId,`${i}.fromPointId`),vp(r.toPointId,`${i}.toPointId`),o.has(r.fromPointId)||Mp(`Packaging edge "${s}" references missing point "${String(r.fromPointId)}".`),o.has(r.toPointId)||Mp(`Packaging edge "${s}" references missing point "${String(r.toPointId)}".`),ZB.has(r.operation)||Mp(`Packaging edge "${s}" has an invalid operation.`),void 0!==r.visible&&"boolean"!=typeof r.visible&&Mp(`Packaging edge "${s}".visible must be a boolean.`),void 0!==r.meta&&Sp(r.meta,`Packaging edge "${s}".meta`);const a=Ip(r.geometry,`Packaging edge "${s}".geometry`);switch(a.type){case"line":Tp(a,["type"],[],`Packaging edge "${s}".geometry`);break;case"quadratic":Tp(a,["type","control"],[],`Packaging edge "${s}".geometry`),yp(a.control,`Packaging edge "${s}".geometry.control`);break;case"cubic":Tp(a,["type","control1","control2"],[],`Packaging edge "${s}".geometry`),yp(a.control1,`Packaging edge "${s}".geometry.control1`),yp(a.control2,`Packaging edge "${s}".geometry.control2`);break;case"arc":Tp(a,["type","radiusX","radiusY","rotation","largeArc","sweep"],[],`Packaging edge "${s}".geometry`),Cp(a.radiusX,`Packaging edge "${s}".geometry.radiusX`),Cp(a.radiusY,`Packaging edge "${s}".geometry.radiusY`),kp(a.rotation,`Packaging edge "${s}".geometry.rotation`),"boolean"==typeof a.largeArc&&"boolean"==typeof a.sweep||Mp(`Packaging edge "${s}" arc flags must be boolean values.`),r.fromPointId===r.toPointId&&Mp(`Packaging arc edge "${s}" must have distinct endpoints.`);break;default:Mp(`Packaging edge "${s}" has an invalid geometry type.`)}}function Qu(e,t,n,o){const i=`PackagingDocument.faces[${t}]`,r=Ip(e,i);Tp(r,["id","outer"],["name","role","holes","artworkFrame","meta"],i);const s=wp(r.id,n,`${i}.id`);for(const a of["name","role"])void 0!==r[a]&&"string"!=typeof r[a]&&Mp(`Packaging face "${s}".${a} must be a string.`);if(np(r.outer,`Packaging face "${s}".outer`,o),void 0!==r.holes&&Pp(r.holes,`Packaging face "${s}".holes`).forEach((e,t)=>np(e,`Packaging face "${s}".holes[${t}]`,o)),void 0!==r.artworkFrame){const e=Ip(r.artworkFrame,`Packaging face "${s}".artworkFrame`);Tp(e,["uvToDocument"],[],`Packaging face "${s}".artworkFrame`);const t=Pp(e.uvToDocument,`Packaging face "${s}".artworkFrame.uvToDocument`);6!==t.length&&Mp(`Packaging face "${s}" artworkFrame matrix must contain 6 numbers.`),t.forEach((e,t)=>kp(e,`Packaging face "${s}" artworkFrame[${t}]`)),yu(t)||Mp(`Packaging face "${s}" artworkFrame matrix must be invertible.`)}void 0!==r.meta&&Sp(r.meta,`Packaging face "${s}".meta`)}function Ju(e,t,n,o){const i=Ip(e,o);Tp(i,["bleedContours","safeZones"],[],o);const r=new Set;Pp(i.bleedContours,`${o}.bleedContours`).forEach((e,n)=>{const i=`${o}.bleedContours[${n}]`,s=Ip(e,i);Tp(s,["id","cutEdgeIds","minimumBleed","contour"],["name","meta"],i);const a=wp(s.id,r,`${i}.id`);ep(s.name,`${i}.name`),Cp(s.minimumBleed,`${i}.minimumBleed`);const d=Pp(s.cutEdgeIds,`${i}.cutEdgeIds`);0===d.length&&Mp(`Packaging bleed contour "${a}" must reference at least one cut edge.`);const l=new Set;d.forEach((e,n)=>{vp(e,`${i}.cutEdgeIds[${n}]`),t.has(e)||Mp(`Packaging bleed contour "${a}" references missing edge "${String(e)}".`),l.has(e)&&Mp(`Packaging bleed contour "${a}" references edge "${String(e)}" more than once.`),l.add(e)}),tp(s.contour,`${i}.contour`),void 0!==s.meta&&Sp(s.meta,`${i}.meta`)}),Pp(i.safeZones,`${o}.safeZones`).forEach((e,t)=>{const i=`${o}.safeZones[${t}]`,s=Ip(e,i);Tp(s,["id","faceId","minimumClearance","contour"],["name","meta"],i);const a=wp(s.id,r,`${i}.id`);ep(s.name,`${i}.name`),vp(s.faceId,`${i}.faceId`),n.has(s.faceId)||Mp(`Packaging safe zone "${a}" references missing face "${String(s.faceId)}".`),Cp(s.minimumClearance,`${i}.minimumClearance`),tp(s.contour,`${i}.contour`),void 0!==s.meta&&Sp(s.meta,`${i}.meta`)})}function ep(e,t){void 0!==e&&vp(e,t)}function tp(e,t){const n=Ip(e,t);Tp(n,["start","segments"],[],t),yp(n.start,`${t}.start`);const o=Pp(n.segments,`${t}.segments`);o.length<2&&Mp(`${t} must contain at least 2 segments plus its implicit closing segment.`),o.forEach((e,n)=>{const o=`${t}.segments[${n}]`,i=Ip(e,o);switch(i.type){case"line":Tp(i,["type","to"],[],o),yp(i.to,`${o}.to`);break;case"quadratic":Tp(i,["type","control","to"],[],o),yp(i.control,`${o}.control`),yp(i.to,`${o}.to`);break;case"cubic":Tp(i,["type","control1","control2","to"],[],o),yp(i.control1,`${o}.control1`),yp(i.control2,`${o}.control2`),yp(i.to,`${o}.to`);break;case"arc":Tp(i,["type","radiusX","radiusY","rotation","largeArc","sweep","to"],[],o),Cp(i.radiusX,`${o}.radiusX`),Cp(i.radiusY,`${o}.radiusY`),kp(i.rotation,`${o}.rotation`),"boolean"!=typeof i.largeArc&&Mp(`${o}.largeArc must be a boolean.`),"boolean"!=typeof i.sweep&&Mp(`${o}.sweep must be a boolean.`),yp(i.to,`${o}.to`);break;default:Mp(`${o}.type is invalid.`)}})}function np(e,t,n){const o=Ip(e,t);Tp(o,["edges"],[],t);const i=Pp(o.edges,`${t}.edges`);i.length<3&&Mp(`${t} must contain at least 3 directed edges.`);const r=new Set;i.forEach((e,o)=>{const i=Ip(e,`${t}.edges[${o}]`);Tp(i,["edgeId","direction"],[],`${t}.edges[${o}]`),vp(i.edgeId,`${t}.edges[${o}].edgeId`),n.has(i.edgeId)||Mp(`${t} references missing edge "${String(i.edgeId)}".`),r.has(i.edgeId)&&Mp(`${t} references edge "${String(i.edgeId)}" more than once.`),r.add(i.edgeId),"forward"!==i.direction&&"reverse"!==i.direction&&Mp(`${t}.edges[${o}].direction is invalid.`)})}function op(e,t){const n=e.surfaces[t].prepress;if(!n)return;const o=new Map(e.edges.map(e=>[e.id,e])),i=du(e,t);for(const r of n.bleedContours){const e=i.bleedContoursById.get(r.id);e||Mp(`Packaging bleed contour "${r.id}" could not be compiled.`),ip(0,e.samples,`Packaging bleed contour "${r.id}"`);for(const t of r.cutEdgeIds){"cut"!==o.get(t).operation&&Mp(`Packaging bleed contour "${r.id}" edge "${t}" must use the cut operation.`);const n=i.edgesById.get(t);n.samples.every(t=>mp(t,e.samples))||Mp(`Packaging bleed contour "${r.id}" must enclose cut edge "${t}".`),rp(n.samples,e.samples)+JB<r.minimumBleed*r.minimumBleed&&Mp(`Packaging bleed contour "${r.id}" does not provide its minimum bleed around cut edge "${t}".`)}}for(const r of n.safeZones){const e=i.safeZonesById.get(r.id),t=i.facesById.get(r.faceId);e&&t||Mp(`Packaging safe zone "${r.id}" could not be compiled.`),ip(0,e.samples,`Packaging safe zone "${r.id}"`),e.samples.every(e=>mp(e,t.outer)&&!t.holes.some(t=>mp(e,t)))||Mp(`Packaging safe zone "${r.id}" must stay inside face "${r.faceId}" and outside its holes.`),[t.outer,...t.holes].some(t=>sp(e.samples,t)+JB<r.minimumClearance*r.minimumClearance)&&Mp(`Packaging safe zone "${r.id}" does not provide its minimum clearance from the cut or crease boundary of face "${r.faceId}".`)}}function ip(e,t,n){(t.length<3||Math.abs(up(t))<=JB)&&Mp(`${n} must form a non-zero closed area.`),pp(t)&&Mp(`${n} must not self-intersect.`)}function rp(e,t){let n=Number.POSITIVE_INFINITY;for(let o=0;o<e.length-1;o+=1)for(let i=0;i<t.length;i+=1)n=Math.min(n,ap(e[o],e[o+1],t[i],t[(i+1)%t.length]));return n}function sp(e,t){let n=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o+=1)for(let i=0;i<t.length;i+=1)n=Math.min(n,ap(e[o],e[(o+1)%e.length],t[i],t[(i+1)%t.length]));return n}function ap(e,t,n,o){return gp(e,t,n,o)?0:Math.min(dp(e,n,o),dp(t,n,o),dp(n,e,t),dp(o,e,t))}function dp(e,t,n){const o=n.sub(t),i=o.len2();if(i<=JB)return e.dist2(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/i));return e.dist2(t.add(o.mul(s)))}function lp(e,t,n,o,i){for(let s=0;s<e.edges.length;s+=1){const i=cp(e.edges[s],o),r=cp(e.edges[(s+1)%e.edges.length],o);i.end!==r.start&&Mp(`Packaging face "${t.id}" ${n} is not continuous between edges "${e.edges[s].edgeId}" and "${e.edges[(s+1)%e.edges.length].edgeId}".`)}const r=((e,t)=>{const n=[];for(const o of e.edges){const e=t.get(o.edgeId);("forward"===o.direction?e.samples:[...e.samples].reverse()).forEach((e,t)=>{(0===n.length||t>0)&&n.push(e)})}return n.length>1&&n[0].dist2(n[n.length-1])<=JB&&n.pop(),n})(e,i);Math.abs(up(r))<=JB&&Mp(`Packaging face "${t.id}" ${n} must form a non-zero area.`),pp(r)&&Mp(`Packaging face "${t.id}" ${n} must not self-intersect.`)}function cp(e,t){const n=t.get(e.edgeId);return"forward"===e.direction?{start:n.fromPointId,end:n.toPointId}:{start:n.toPointId,end:n.fromPointId}}function up(e){let t=0;for(let n=0;n<e.length;n+=1){const o=e[n],i=e[(n+1)%e.length];t+=o.x*i.y-i.x*o.y}return t/2}function pp(e){for(let t=0;t<e.length;t+=1){const n=e[t],o=e[(t+1)%e.length];for(let i=t+1;i<e.length;i+=1)if(i!==t&&i!==t+1&&(0!==t||i!==e.length-1)&&gp(n,o,e[i],e[(i+1)%e.length]))return!0}return!1}function hp(e,t){for(let n=0;n<e.length;n+=1)for(let o=0;o<t.length;o+=1)if(gp(e[n],e[(n+1)%e.length],t[o],t[(o+1)%t.length]))return!0;return!1}function gp(e,t,n,o){const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<=JB)return fp(e,n,o)||fp(t,n,o)||fp(n,e,t)||fp(o,e,t);const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d>=-1e-8&&d<=1.00000001&&l>=-1e-8&&l<=1.00000001}function fp(e,t,n){const o=n.sub(t),i=e.sub(t);if(Math.abs(o.x*i.y-o.y*i.x)>JB)return!1;const r=i.x*o.x+i.y*o.y;return r>=-1e-8&&r<=o.len2()+JB}function mp(e,t){let n=!1;for(let o=0,i=t.length-1;o<t.length;i=o,o+=1){const r=t[o],s=t[i];r.y>e.y!=s.y>e.y&&e.x<(s.x-r.x)*(e.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n}function yp(e,t){const n=Ip(e,t);Tp(n,["x","y"],[],t),kp(n.x,`${t}.x`),kp(n.y,`${t}.y`)}function Sp(e,t){Ip(e,t),bp(e,t,new WeakSet)}function bp(e,t,n){if(null!==e&&"string"!=typeof e&&"boolean"!=typeof e)if("number"!=typeof e){if("object"!=typeof e&&Mp(`${t} must contain only JSON values.`),n.has(e)&&Mp(`${t} must not contain circular references.`),n.add(e),Array.isArray(e))e.forEach((e,o)=>bp(e,`${t}[${o}]`,n));else{const o=Object.getPrototypeOf(e);o!==Object.prototype&&null!==o&&Mp(`${t} must contain only plain JSON objects.`);for(const[i,r]of Object.entries(e))bp(r,`${t}.${i}`,n)}n.delete(e)}else kp(e,t)}function xp(e){if(!e||"object"!=typeof e||Object.isFrozen(e))return e;for(const t of Object.values(e))xp(t);return Object.freeze(e)}function wp(e,t,n){vp(e,n);const o=e;return t.has(o)&&Mp(`Duplicate ${n.split(".").at(-1)??"id"} "${o}" at ${n}.`),t.add(o),o}function Ip(e,t){e&&"object"==typeof e&&!Array.isArray(e)||Mp(`${t} must be an object.`);const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n&&Mp(`${t} must be a plain object.`),e}function Pp(e,t){return Array.isArray(e)||Mp(`${t} must be an array.`),e}function vp(e,t){"string"==typeof e&&0!==e.trim().length||Mp(`${t} must be a non-empty string.`)}function kp(e,t){"number"==typeof e&&Number.isFinite(e)||Mp(`${t} must be a finite number.`)}function Cp(e,t){kp(e,t),e<=0&&Mp(`${t} must be greater than zero.`)}function Tp(e,t,n,o){const i=new Set([...t,...n]);for(const r of t)Object.prototype.hasOwnProperty.call(e,r)||Mp(`${o}.${r} is required.`);for(const r of Object.keys(e))i.has(r)||Mp(`${o}.${r} is not part of Packaging schema version 1.`)}function Mp(e){throw new Error(e)}function Ep(e,t=Bp(e)){const n=e.props.showBleed?t.outerBounds:t.bounds,o=[new $C(n.minX,n.minY),new $C(n.maxX,n.minY),new $C(n.maxX,n.maxY),new $C(n.minX,n.maxY)];if(e.props.showSafeZones)for(const i of t.safeZonesById.values())o.push(...i.samples.map(e=>e.clone()));return LC.FromPoints(o)}function Bp(e){return au(e.props.document,e.props.viewSide)}function Ap(e,t){return Object.prototype.hasOwnProperty.call(e.props.faceFillOverrides,t)?e.props.faceFillOverrides[t]:e.props.faceFill}function Rp(e,t,n){
|
|
27
|
+
return Zk("g",{"data-packaging-layer":"dieline",children:[$p(e,iA,VB.cutStroke,n,t),$p(e,rA,VB.creaseStroke,n,t,!0),$p(e,sA,VB.annotationStroke,n,t,!0)]})}function $p(e,t,n,o,i,r=!1){return e.filter(e=>t.has(e.edge.operation)).map(e=>Gk("path",{"data-packaging-edge-id":e.edge.id,"data-packaging-edge-operation":e.edge.operation,"data-packaging-hole-outline":i.has(e.edge.id)?"true":void 0,d:e.path,...Fp(n,o),strokeDasharray:r?mu(e.edge.operation,o):void 0,strokeLinecap:r?"butt":"round"},e.edge.id))}function Lp(e,t){return e/Math.max(t,1)}function Fp(e,t){return{fill:"none",stroke:O(e),strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"}}function Op(e){return`${e.x} ${e.y} ${Math.max(e.w,1)} ${Math.max(e.h,1)}`}function Dp(e){return"packaging"===e?.type}function zp(e,t,n=[...e.edgesById.values()].filter(e=>!1!==e.edge.visible)){return[...Up(n,aA,VB.cutStroke,VB.lineWidth,t,e.holeEdgeIds),...Up(n,dA,VB.creaseStroke,VB.lineWidth,t,e.holeEdgeIds,!0),...Up(n,lA,VB.annotationStroke,VB.lineWidth,t,e.holeEdgeIds,!0)]}function Up(e,t,n,o,i,r,s=!1){return e.filter(e=>t.has(e.edge.operation)).map(e=>({tag:"path",attrs:{d:e.path,...Np(i,n,o),"stroke-dasharray":s?mu(e.edge.operation,o):void 0,"stroke-linecap":s?"butt":"round","data-packaging-edge-id":e.edge.id,"data-packaging-edge-operation":e.edge.operation,"data-packaging-hole-outline":!!r.has(e.edge.id)||void 0}}))}function Np(e,t,n){return{fill:"none",stroke:e.resolveColor(t),"stroke-width":n,"stroke-linecap":"round","stroke-linejoin":"round","vector-effect":"non-scaling-stroke"}}function Wp(e,t=1){switch(e){case"mm":return 2.834645669291339;case"cm":return 28.34645669291339;case"m":return 2834.645669291339;case"in":return cA;case"pt":return 1;case"px":return.75;case"unitless":return Hp(t,1,"Packaging PDF unitless points per unit")}}function Xp({page:e,path:t,style:n,pathOrigin:o,pointsPerUnit:i,lineWidthPoints:r,pdfLib:s}){e.drawSvgPath(t,{x:o.x,y:o.y,scale:i,borderColor:s.cmyk(...n.color),borderWidth:r/i,borderDashArray:n.dashArrayPoints?.map(e=>e/i),borderLineCap:n.dashArrayPoints?s.LineCapStyle.Butt:s.LineCapStyle.Round})}function Yp(e,t){return"unitless"===e?14.173228346456694/t:5*Wp("mm")/t}function Hp(e,t,n){const o=e??t;if(!Number.isFinite(o)||o<=0)throw new Error(`${n} must be a positive finite number.`);return o}function _p(e,t,n){const o=e??t;if(!Number.isFinite(o)||o<0)throw new Error(`${n} must be a non-negative finite number.`);return o}function Kp(e,t){return`${e.normalize("NFKC").replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/[. ]+$/g,"").trim()||"packaging"}-${t}-dieline.pdf`}function qp(e,t={}){if(e.startsWith("AutoCAD Binary DXF"))throw new Error("Binary DXF files are not supported. Save the drawing as ASCII DXF and try again.");const n=(e=>{const t=e.replace(/^\uFEFF/,"").split(/\r?\n/),n=[];for(let o=0;o+1<t.length;o+=2){const e=t[o].trim();if(0===e.length&&0===t[o+1].trim().length)continue;const i=Number(e);if(!Number.isInteger(i))throw new Error(`Invalid DXF group code at line ${o+1}.`);n.push({code:i,value:t[o+1].trim()})}if(0===n.length)throw new Error("The DXF file is empty.");return n})(e),o=jp(n,"HEADER"),i=jp(n,"TABLES"),r=jp(n,"ENTITIES");if(0===r.length)throw new Error("The DXF file does not contain an ENTITIES section.");const s=(e=>{const t=oh(e,"$INSUNITS");if(null===t)return null;const n=Number(t);return Number.isFinite(n)?n:null})(o)??0,a=oh(o,"$ACADVER"),d=(e=>{switch(e){case 1:return{unit:"in",scale:1};case 2:return{unit:"in",scale:12};case 3:return{unit:"in",scale:63360};case 4:return{unit:"mm",scale:1};case 5:return{unit:"cm",scale:1};case 6:return{unit:"m",scale:1};case 7:return{unit:"m",scale:1e3};case 8:return{unit:"in",scale:1e-6};case 9:return{unit:"in",scale:.001};case 10:return{unit:"in",scale:36};case 11:return{unit:"mm",scale:1e-7};case 12:return{unit:"mm",scale:1e-6};case 13:return{unit:"mm",scale:.001};case 14:return{unit:"m",scale:.1};case 15:return{unit:"m",scale:10};case 16:return{unit:"m",scale:100};case 21:return{unit:"in",scale:12.000024000048};default:return{unit:"unitless",scale:1}}})(s),l=(e=>{const t=new Map;for(const n of Vp(e)){if("LAYER"!==n.type)continue;const e=ih(n,2)??"0";t.set(e,{name:e,lineType:ih(n,6)??"Continuous"})}return t})(i),c=Vp(r);if(c.length>5e4)throw new Error(`The DXF file contains more than ${5e4.toLocaleString()} entities.`);const u=new Set,p=(({records:e,layers:t,unitMapping:n,options:o,ignoredEntityTypes:i})=>{const r=[];for(let s=0;s<e.length;s+=1){const a=e[s];if("POLYLINE"===a.type){const i=[];let d=s+1;for(;d<e.length&&"VERTEX"===e[d].type;){const t=ah(e[d]);t&&i.push(t),d+=1}const l=rh(a,70)??0;r.push(...Zp({record:a,vertices:i,isClosed:!!(1&l),layers:t,unitMapping:n,options:o})),s="SEQEND"===e[d]?.type?d:d-1;continue}const d=Gp({record:a,layers:t,unitMapping:n,options:o});d?r.push(...d):bh(a.type)&&i.add(a.type)}return r})({records:c,layers:l,unitMapping:d,options:t,ignoredEntityTypes:u});if(0===p.length){const e=[...u].sort().join(", ");throw new Error(e.length>0?`The DXF file does not contain supported dieline geometry. Ignored entity types: ${e}.`:"The DXF file does not contain supported dieline geometry.")}const h=p.length>2e3,g=h?p:(e=>{const t=e.flatMap(e=>[e.from,e.to]),n=e.map(()=>[0,1]);for(let i=0;i<e.length;i+=1){const o=e[i];if("line"===o.geometry.type)for(const e of t){const t=lh(e,o.from,o.to);null!==t&&t>fA&&t<.999999&&n[i].push(t)}}for(let i=0;i<e.length;i+=1){const t=e[i];if("line"===t.geometry.type)for(let o=i+1;o<e.length;o+=1){const r=e[o];if("line"!==r.geometry.type)continue;const s=ch(t.from,t.to,r.from,r.to);s&&(s.left>fA&&s.left<.999999&&n[i].push(s.left),s.right>fA&&s.right<.999999&&n[o].push(s.right))}}const o=[];for(let i=0;i<e.length;i+=1){const t=e[i];if("line"!==t.geometry.type){o.push(t);continue}const r=[...new Set(n[i].map(e=>Sh(e)))].sort((e,t)=>e-t);for(let e=0;e<r.length-1;e+=1){const n=hh(t.from,t.to,r[e]),i=hh(t.from,t.to,r[e+1]);gh(n,i)||o.push({...t,sourceId:2===r.length?t.sourceId:`${t.sourceId}:${e+1}`,from:n,to:i,samples:[n,i]})}}return o})(p);(e=>{let t=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY;for(const i of e)for(const e of i.samples)t=Math.min(t,e.x),n=Math.min(n,e.y);const o=e=>({x:Sh(e.x-t),y:Sh(e.y-n)});for(const i of e)i.from=o(i.from),i.to=o(i.to),i.samples=i.samples.map(o),"quadratic"===i.geometry.type?i.geometry.control=o(i.geometry.control):"cubic"===i.geometry.type&&(i.geometry.control1=o(i.geometry.control1),i.geometry.control2=o(i.geometry.control2))})(g);const{points:f,edges:m,samplesByEdgeId:y}=(e=>{const t=(()=>{const e=[],t=new Map;return{points:e,add(n){const o=Math.round(n.x/fA),i=Math.round(n.y/fA);for(let d=-1;d<=1;d+=1)for(let r=-1;r<=1;r+=1)for(const s of t.get(`${o+d}:${i+r}`)??[]){const t=e[s];if(Math.hypot(t.x-n.x,t.y-n.y)<=fA)return t.id}const r=`dxf-point:${e.length+1}`,s=e.length;e.push({id:r,x:Sh(n.x),y:Sh(n.y)});const a=`${o}:${i}`;return t.set(a,[...t.get(a)??[],s]),r}}})(),n=[],o=new Map;return e.forEach((e,i)=>{const r=t.add(e.from),s=t.add(e.to);if(r===s)return;const a=`dxf-edge:${i+1}`;n.push({id:a,fromPointId:r,toPointId:s,geometry:e.geometry,operation:e.operation,meta:{dxfHandle:e.sourceId,dxfEntityType:e.sourceType,layer:e.layer,lineType:e.lineType}}),o.set(a,e.samples)}),{points:t.points,edges:n,samplesByEdgeId:o}})(g),S=h?[]:(({edges:e,samplesByEdgeId:t})=>{const n=e.filter(e=>"annotation"!==e.operation&&"construction"!==e.operation&&"custom"!==e.operation),o=new Map,i=new Map;for(const a of n){const e=t.get(a.id);if(!e||e.length<2)continue;const n=[...e],r=[...e].reverse(),s={key:`${a.id}:forward`,reverseKey:`${a.id}:reverse`,edgeId:a.id,fromPointId:a.fromPointId,toPointId:a.toPointId,direction:"forward",angle:uh(n),samples:n},d={key:`${a.id}:reverse`,reverseKey:`${a.id}:forward`,edgeId:a.id,fromPointId:a.toPointId,toPointId:a.fromPointId,direction:"reverse",angle:uh(r),samples:r};for(const t of[s,d]){o.set(t.key,t);const e=i.get(t.fromPointId)??[];e.push(t),i.set(t.fromPointId,e)}}for(const a of i.values())a.sort((e,t)=>e.angle-t.angle||e.key.localeCompare(t.key));const r=new Set,s=[];for(const a of o.values()){if(r.has(a.key))continue;const e=[],t=new Set;let n=a;for(;n&&!t.has(n.key)&&e.length<=o.size;){e.push(n),t.add(n.key);const o=i.get(n.toPointId)??[],r=n.reverseKey,s=o.findIndex(e=>e.key===r);n=s<0?void 0:o[(s-1+o.length)%o.length]}for(const o of t)r.add(o);if(n?.key!==a.key||e.length<3)continue;if(new Set(e.map(e=>e.edgeId)).size!==e.length)continue;const d=e.flatMap((e,t)=>0===t?[...e.samples]:e.samples.slice(1));d.length>1&&gh(d[0],d[d.length-1])&&d.pop(),ph(d)<=mA||s.push({id:`dxf-face:${s.length+1}`,name:`Face ${s.length+1}`,outer:{edges:e.map(e=>({edgeId:e.edgeId,direction:e.direction}))},meta:{source:"dxf-inferred"}})}return s})({edges:m,samplesByEdgeId:y}),b=(e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)})(e),x=(e=>{const t=e?.trim();return t?t.replace(/\.dxf$/i,""):null})(t.fileName),w={schemaVersion:1,id:t.documentId??`packaging-document:dxf:${b}`,revision:t.revision??`dxf:${b}`,name:x??"Imported DXF",unit:d.unit,coordinateSystem:"top-left-y-down",points:f,edges:m,faces:S,surfaces:{outside:{},inside:{}},source:{provider:"dxf",...x?{externalId:x}:{},...a?{revision:a}:{}},meta:{dxf:{...a?{acadVersion:a}:{},unitsCode:s,importedEntityCount:xh(c),importedEdgeCount:m.length,inferredFaceCount:S.length,ignoredEntityTypes:[...u].sort(),layers:[...new Set(g.map(e=>e.layer))].sort(),...h?{topologyInferenceLimited:!0}:{}}}};try{return Vu(w)}catch(I){if(0===S.length)throw I;return Vu({...w,faces:[],meta:{...w.meta,dxf:{...w.meta?.dxf,inferredFaceCount:0,faceInferenceSkipped:!0}}})}}function jp(e,t){let n=null;const o=[];for(let i=0;i<e.length;i+=1){const r=e[i];if(0===r.code&&"SECTION"===r.value){const t=e[i+1];n=2===t?.code?t.value:null,i+=2===t?.code?1:0;continue}0!==r.code||"ENDSEC"!==r.value?n===t&&o.push(r):n=null}return o}function Vp(e){const t=[];let n=null;for(const o of e)0===o.code?(n&&t.push(n),n={type:o.value.toUpperCase(),pairs:[]}):n&&n.pairs.push(o);return n&&t.push(n),t}function Gp({record:e,layers:t,unitMapping:n,options:o}){const i=ih(e,5)??`${e.type.toLowerCase()}`,r=ih(e,8)??"0",s=t.get(r)??{name:r,lineType:ih(e,6)??"Continuous"},a=ih(e,6)??s.lineType,d=nh({layer:s.name,lineType:a,options:o}),l=e=>({x:e.x*n.scale,y:-e.y*n.scale}),c={sourceId:i,sourceType:e.type,layer:s.name,lineType:a,operation:d};switch(e.type){case"LINE":{const t=sh(e,10,20),n=sh(e,11,21);if(!t||!n||gh(t,n))return[];const o=l(t),i=l(n);return[{...c,from:o,to:i,geometry:{type:"line"},samples:[o,i]}]}case"ARC":{const t=sh(e,10,20),o=rh(e,40),i=rh(e,50),r=rh(e,51);if(!t||!yh(o)||null===i||null===r)return[];const s=mh(i),a=fh(mh(r)-s);return a<=fA?[]:[Jp({...c,center:t,radiusX:o,radiusY:o,rotation:0,start:s,delta:a,transform:l,scale:n.scale})]}case"CIRCLE":{const t=sh(e,10,20),o=rh(e,40);return t&&yh(o)?[0,1,2,3].map(e=>Jp({...c,sourceId:`${i}:${e+1}`,center:t,radiusX:o,radiusY:o,rotation:0,start:e*Math.PI/2,delta:Math.PI/2,transform:l,scale:n.scale})):[]}case"ELLIPSE":{const t=sh(e,10,20),o=sh(e,11,21),r=rh(e,40);if(!t||!o||!yh(r))return[];const s=Math.hypot(o.x,o.y);if(!yh(s))return[];const a=Math.atan2(o.y,o.x),d=rh(e,41)??0;let u=fh((rh(e,42)??gA)-d);u<=fA&&(u=gA);const p=u>=gA-fA?4:1;return Array.from({length:p},(e,o)=>Jp({...c,sourceId:1===p?i:`${i}:${o+1}`,center:t,radiusX:s,radiusY:s*r,rotation:a,start:d+u*o/p,delta:u/p,transform:l,scale:n.scale}))}case"LWPOLYLINE":return Zp({record:e,vertices:dh(e),isClosed:!!(1&(rh(e,70)??0)),layers:t,unitMapping:n,options:o});default:return null}}function Zp({record:e,vertices:t,isClosed:n,layers:o,unitMapping:i,options:r}){if(t.length<2)return[];const s=ih(e,5)??e.type.toLowerCase(),a=ih(e,8)??"0",d=o.get(a)??{name:a,lineType:ih(e,6)??"Continuous"},l=ih(e,6)??d.lineType,c=nh({layer:d.name,lineType:l,options:r}),u=e=>({x:e.x*i.scale,y:-e.y*i.scale}),p=n?t.length:t.length-1,h=[];for(let g=0;g<p;g+=1){const n=t[g],o=t[(g+1)%t.length];if(gh(n,o))continue;const r={sourceId:`${s}:${g+1}`,sourceType:e.type,layer:d.name,lineType:l,operation:c};if(Math.abs(n.bulge)<=fA){const e=u(n),t=u(o);h.push({...r,from:e,to:t,geometry:{type:"line"},samples:[e,t]});continue}h.push(Qp({...r,from:n,to:o,bulge:n.bulge,transform:u,scale:i.scale}))}return h}function Qp({from:e,to:t,bulge:n,transform:o,scale:i,...r}){const s=t.x-e.x,a=t.y-e.y,d=Math.hypot(s,a),l=d*(1-n*n)/(4*n),c={x:(e.x+t.x)/2-a/d*l,y:(e.y+t.y)/2+s/d*l},u=Math.atan2(e.y-c.y,e.x-c.x),p=4*Math.atan(n),h=d*(1+n*n)/(4*Math.abs(n));return{...r,from:o(e),to:o(t),geometry:{type:"arc",radiusX:h*i,radiusY:h*i,rotation:0,largeArc:Math.abs(p)>Math.PI,sweep:p<0},samples:eh({center:c,radiusX:h,radiusY:h,rotation:0,start:u,delta:p,transform:o})}}function Jp({center:e,radiusX:t,radiusY:n,rotation:o,start:i,delta:r,transform:s,scale:a,...d}){const l=th({center:e,radiusX:t,radiusY:n,rotation:o,angle:i}),c=th({center:e,radiusX:t,radiusY:n,rotation:o,angle:i+r});return{...d,from:s(l),to:s(c),geometry:{type:"arc",radiusX:t*a,radiusY:n*a,rotation:(u=-o,180*u/Math.PI),largeArc:Math.abs(r)>Math.PI,sweep:r<0},samples:eh({center:e,radiusX:t,radiusY:n,rotation:o,start:i,delta:r,transform:s})};var u}function eh({center:e,radiusX:t,radiusY:n,rotation:o,start:i,delta:r,transform:s}){const a=Math.max(4,Math.ceil(Math.abs(r)/(Math.PI/12)));return Array.from({length:a+1},(d,l)=>s(th({center:e,radiusX:t,radiusY:n,rotation:o,angle:i+r*l/a})))}function th({center:e,radiusX:t,radiusY:n,rotation:o,angle:i}){const r=Math.cos(o),s=Math.sin(o);return{x:e.x+t*Math.cos(i)*r-n*Math.sin(i)*s,y:e.y+t*Math.cos(i)*s+n*Math.sin(i)*r}}function nh({layer:e,lineType:t,options:n}){const o=n.operationByLayer?.[e];if(o)return o;const i=`${e} ${t}`.toLocaleLowerCase();return/perforat|\bperf\b|点断|齿线/.test(i)?"perforation":/half[ _-]*cut|半切/.test(i)?"half-cut":/kiss[ _-]*cut|吻切/.test(i)?"kiss-cut":/\bscore\b|压线/.test(i)?"score":/crease|fold|dash|bend|折线|折痕|压痕/.test(i)?"crease":/construction|guide|辅助|参考/.test(i)?"construction":/annotation|dimension|text|mark|注释|标注/.test(i)?"annotation":/cut|knife|dieline|die[ _-]*line|solid|刀线|模切/.test(i)?"cut":/continuous|bylayer|byblock/.test(t.toLocaleLowerCase())?n.defaultOperation??"cut":"crease"}function oh(e,t){for(let n=0;n<e.length;n+=1)if(9===e[n].code&&e[n].value===t)return e[n+1]?.value??null;return null}function ih(e,t){return e.pairs.find(e=>e.code===t)?.value??null}function rh(e,t){const n=ih(e,t);if(null===n)return null;const o=Number(n);return Number.isFinite(o)?o:null}function sh(e,t,n){const o=rh(e,t),i=rh(e,n);return null===o||null===i?null:{x:o,y:i}}function ah(e){const t=sh(e,10,20);return t?{...t,bulge:rh(e,42)??0}:null}function dh(e){const t=[];for(const n of e.pairs)if(10===n.code){const e=Number(n.value);Number.isFinite(e)&&t.push({x:e,y:0,bulge:0})}else if(20===n.code&&t.length>0){const e=Number(n.value);Number.isFinite(e)&&(t[t.length-1].y=e)}else if(42===n.code&&t.length>0){const e=Number(n.value);Number.isFinite(e)&&(t[t.length-1].bulge=e)}return t}function lh(e,t,n){const o=n.x-t.x,i=n.y-t.y,r=o*o+i*i;if(r<=1e-12)return null;const s=((e.x-t.x)*o+(e.y-t.y)*i)/r;if(s<-1e-6||s>1.000001)return null;const a=hh(t,n,s);return Math.hypot(a.x-e.x,a.y-e.y)<=fA?Math.max(0,Math.min(1,s)):null}function ch(e,t,n,o){const i=t.x-e.x,r=t.y-e.y,s=o.x-n.x,a=o.y-n.y,d=i*a-r*s;if(Math.abs(d)<=fA)return null;const l=n.x-e.x,c=n.y-e.y,u=(l*a-c*s)/d,p=(l*r-c*i)/d;return u>=-1e-6&&u<=1.000001&&p>=-1e-6&&p<=1.000001?{left:u,right:p}:null}function uh(e){const t=e[0],n=e.find(e=>!gh(e,t))??e[1];return fh(Math.atan2(n.y-t.y,n.x-t.x))}function ph(e){let t=0;for(let n=0;n<e.length;n+=1){const o=e[n],i=e[(n+1)%e.length];t+=o.x*i.y-i.x*o.y}return t/2}function hh(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function gh(e,t){return Math.hypot(e.x-t.x,e.y-t.y)<=fA}function fh(e){return(e%gA+gA)%gA}function mh(e){return e*Math.PI/180}function yh(e){return null!==e&&Number.isFinite(e)&&e>0}function Sh(e){return Math.round(1e9*e)/1e9}function bh(e){return!yA.has(e)&&"VERTEX"!==e&&"SEQEND"!==e&&"ENDSEC"!==e}function xh(e){return e.filter(e=>yA.has(e.type)).length}function wh(e){return"packaging"===e?.type}function Ih(e,t){return{id:e,getAvailability:e=>"packaging"!==e.selection.commonShapeType?"inapplicable":e.selection.selectedShapes.some(e=>Ch(e)&&!e.isLocked&&kh(e,t))?"enabled":"disabled",getValue:e=>Ph(e.selection.selectedShapes,t),run({context:e,value:n}){const o="boolean"==typeof n?n:!0!==Ph(e.selection.selectedShapes,t),i=e.selection.selectedShapes.filter(Ch).filter(e=>!e.isLocked&&kh(e,t)).map(e=>({id:e.id,props:{[t]:o}}));i.length>0&&e.editor.commands.updateShapes(i,{source:"user"})}}}function Ph(e,t){let n;for(const o of e){if(!Ch(o))continue;const e=o.props[t];if(void 0===n)n=e;else if(n!==e)return null}return n??null}function vh(e){let t;for(const n of e){if(!Ch(n))continue;const e="inside"===n.props.viewSide;if(void 0===t)t=e;else if(t!==e)return null}return t??null}function kh(e,t){return"showSafeZones"===t?(e=>(e.props.document.surfaces[e.props.viewSide].prepress?.safeZones.length??0)>0)(e):"dielineOnTop"===t||(e=>(e.props.document.surfaces[e.props.viewSide].prepress?.bleedContours.length??0)>0)(e)}function Ch(e){return"packaging"===e.type}function Th({editor:e,getHostElement:t,imports:n}){return Wk(()=>{const o=o=>{if(!Bh(t(),o)||e.shapeEditingStateSignal.get().session||Zr(o.target))return;const i=Eh({source:"clipboard",dataTransfer:o.clipboardData});n.canImport(i)&&(o.preventDefault(),n.import(i,{editor:e}).catch($h))},i=o=>{!Bh(t(),o)||e.shapeEditingStateSignal.get().session||Zr(o.target)||n.canImportPreview(Mh(o.dataTransfer))&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="copy"))},r=o=>{const i=Bh(t(),o);if(!i||e.shapeEditingStateSignal.get().session||Zr(o.target))return;const r=n.canImportPreview(Mh(o.dataTransfer)),s=Eh({source:"drop",dataTransfer:o.dataTransfer,pagePoint:Jr(e,o,i)});n.canImport(s)?(o.preventDefault(),n.import(s,{editor:e}).catch($h)):r&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))};return window.addEventListener("paste",o),window.addEventListener("dragover",i),window.addEventListener("drop",r),()=>{window.removeEventListener("paste",o),window.removeEventListener("dragover",i),window.removeEventListener("drop",r)}},[e,t,n]),null}function Mh(e){return e?{source:"drop",dataTypes:Array.from(e.types),fileTypes:Array.from(e.items).filter(e=>"file"===e.kind).map(e=>e.type).filter(Boolean)}:{source:"drop",dataTypes:[],fileTypes:[]}}function Eh({dataTransfer:e,pagePoint:t,source:n}){const o=e?.getData("text/plain")||void 0,i=e?.getData("text/html")||void 0,r=[...(e?.getData("text/uri-list")||void 0)?.split(/\r?\n/).filter(e=>e&&!e.startsWith("#"))??[],...o&&Rh(o.trim())?[o.trim()]:[]];return{source:n,files:Ah(e),text:o,html:i,...r.length>0?{urls:r}:{},pagePoint:t}}function Bh(e,t){if(!e)return null;const n=(t.target instanceof Element?t.target:document.activeElement)?.closest(oE);return n instanceof HTMLElement&&e.contains(n)?n:null}function Ah(e){if(!e)return[];const t=Array.from(e.files);return t.length>0?t:Array.from(e.items).flatMap(e=>{if("file"!==e.kind)return[];const t=e.getAsFile();return t?[t]:[]})}function Rh(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return e.startsWith("data:image/")}}function $h(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function Lh(e){return e.get($A)}async function Fh({context:e,services:t}){const n=Lh(t);if(!n)return null;const o=e.editor.createClipboardPayloadFromSelection();return o?(await n.write(o),o):null}async function Oh({atMenuPoint:e=!1,context:t,services:n}){const o=Lh(n);if(!o)return;const i=await o.read();i&&t.editor.pasteClipboardPayload({payload:i,pagePoint:Dh({atMenuPoint:e,context:t}),source:"user"})}function Dh({atMenuPoint:e,context:t}){return e&&zh(t)?t.menu.anchor.pagePoint:t.editor.inputs.state.get().currentPagePoint??t.editor.viewportPageBoundsSignal.get()?.center??void 0}function zh(e){return"menu"in e}function Uh({children:e}){const[t,n]=qk(null),o=Uk(e=>{n(e)},[]),i=_k(()=>({registerTarget:o,target:t}),[o,t]);
|
|
28
|
+
return Gk(HA.Provider,{value:i,children:e})}function Nh(){const{registerTarget:e}=Xh();
|
|
29
|
+
return Gk("div",{ref:e,className:"land-canvas__floating-portal-host","data-ui":"canvas-kit-floating-portal-host"})}function Wh(){return Xh().target}function Xh(){const e=Nk(HA);if(!e)throw new Error("CanvasKit floating content must be rendered inside CanvasKitRoot.");return e}function Yh({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const o=Wh();return o?fC(Gk("div",{"data-ui":n,className:Hh("land-canvas__floating-toolbar-layer",t),children:e}),o):null}function Hh(...e){return e.filter(Boolean).join(" ")}function _h(e){Wk(()=>{const t=e.current;if(!t)return;const n=e=>{(e=>e.scrollHeight>e.clientHeight)(t)||function(e,t){const n=(e=>{const t=e?.getRootNode();return t instanceof Document||t instanceof ShadowRoot?Qr(t):Qr()})(t);return!!n&&(n.dispatchEvent(new WheelEvent("wheel",{altKey:e.altKey,bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,composed:!0,ctrlKey:e.ctrlKey,deltaMode:e.deltaMode,deltaX:e.deltaX,deltaY:e.deltaY,deltaZ:e.deltaZ,metaKey:e.metaKey,screenX:e.screenX,screenY:e.screenY,shiftKey:e.shiftKey,view:window})),!0)}(e,t)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",n,{passive:!1}),()=>{t.removeEventListener("wheel",n)}},[e])}function Kh(e,t,n){return KA(e,_A(t,n))}function qh(e,t){return"function"==typeof e?e(t):e}function jh(e){return e.split("-")[0]}function Vh(e){return e.split("-")[1]}function Gh(e){return"x"===e?"y":"x"}function Zh(e){return"y"===e?"height":"width"}function Qh(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function Jh(e){return Gh(Qh(e))}function eg(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function tg(e){const t=jh(e);return GA[t]+e.slice(t.length)}function ng(e){const{x:t,y:n,width:o,height:i}=e;return{width:o,height:i,top:n,left:t,right:t+o,bottom:n+i,x:t,y:n}}function og(e,t,n){let{reference:o,floating:i}=e;const r=Qh(t),s=Jh(t),a=Zh(s),d=jh(t),l="y"===r,c=o.x+o.width/2-i.width/2,u=o.y+o.height/2-i.height/2,p=o[a]/2-i[a]/2;let h;switch(d){case"top":h={x:c,y:o.y-i.height};break;case"bottom":h={x:c,y:o.y+o.height};break;case"right":h={x:o.x+o.width,y:u};break;case"left":h={x:o.x-i.width,y:u};break;default:h={x:o.x,y:o.y}}switch(Vh(t)){case"start":h[s]-=p*(n&&l?-1:1);break;case"end":h[s]+=p*(n&&l?-1:1)}return h}async function ig(e,t){var n;void 0===t&&(t={});const{x:o,y:i,platform:r,rects:s,elements:a,strategy:d}=e,{boundary:l="clippingAncestors",rootBoundary:c="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=qh(t,e),g=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(h),f=a[p?"floating"===u?"reference":"floating":u],m=ng(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(f)))||n?f:f.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:l,rootBoundary:c,strategy:d})),y="floating"===u?{x:o,y:i,width:s.floating.width,height:s.floating.height}:s.reference,S=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),b=await(null==r.isElement?void 0:r.isElement(S))&&await(null==r.getScale?void 0:r.getScale(S))||{x:1,y:1},x=ng(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:S,strategy:d}):y);return{top:(m.top-x.top+g.top)/b.y,bottom:(x.bottom-m.bottom+g.bottom)/b.y,left:(m.left-x.left+g.left)/b.x,right:(x.right-m.right+g.right)/b.x}}function rg(){return"undefined"!=typeof window}function sg(e){return lg(e)?(e.nodeName||"").toLowerCase():"#document"}function ag(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function dg(e){var t;return null==(t=(lg(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function lg(e){return!!rg()&&(e instanceof Node||e instanceof ag(e).Node)}function cg(e){return!!rg()&&(e instanceof Element||e instanceof ag(e).Element)}function ug(e){return!!rg()&&(e instanceof HTMLElement||e instanceof ag(e).HTMLElement)}function pg(e){return!(!rg()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof ag(e).ShadowRoot)}function hg(e){const{overflow:t,overflowX:n,overflowY:o,display:i}=bg(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+n)&&"inline"!==i&&"contents"!==i}function gg(e){return/^(table|td|th)$/.test(sg(e))}function fg(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function mg(e){const t=cg(e)?bg(e):e;return iR(t.transform)||iR(t.translate)||iR(t.scale)||iR(t.rotate)||iR(t.perspective)||!yg()&&(iR(t.backdropFilter)||iR(t.filter))||nR.test(t.willChange||"")||oR.test(t.contain||"")}function yg(){return null==mC&&(mC="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),mC}function Sg(e){return/^(html|body|#document)$/.test(sg(e))}function bg(e){return ag(e).getComputedStyle(e)}function xg(e){return cg(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function wg(e){if("html"===sg(e))return e;const t=e.assignedSlot||e.parentNode||pg(e)&&e.host||dg(e);return pg(t)?t.host:t}function Ig(e){const t=wg(e);return Sg(t)?e.ownerDocument?e.ownerDocument.body:e.body:ug(t)&&hg(t)?t:Ig(t)}function Pg(e,t,n){var o;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Ig(e),r=i===(null==(o=e.ownerDocument)?void 0:o.body),s=ag(i);if(r){const e=vg(s);return t.concat(s,s.visualViewport||[],hg(i)?i:[],e&&n?Pg(e):[])}return t.concat(i,Pg(i,[],n))}function vg(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function kg(e){const t=bg(e);let n=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const i=ug(e),r=i?e.offsetWidth:n,s=i?e.offsetHeight:o,a=qA(n)!==r||qA(o)!==s;return a&&(n=r,o=s),{width:n,height:o,$:a}}function Cg(e){return cg(e)?e:e.contextElement}function Tg(e){const t=Cg(e);if(!ug(t))return VA(1);const n=t.getBoundingClientRect(),{width:o,height:i,$:r}=kg(t);let s=(r?qA(n.width):n.width)/o,a=(r?qA(n.height):n.height)/i;return s&&Number.isFinite(s)||(s=1),a&&Number.isFinite(a)||(a=1),{x:s,y:a}}function Mg(e){const t=ag(e);return yg()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:rR}function Eg(e,t,n,o){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),r=Cg(e);let s=VA(1);t&&(o?cg(o)&&(s=Tg(o)):s=Tg(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==ag(e))&&t))(r,n,o)?Mg(r):VA(0);let d=(i.left+a.x)/s.x,l=(i.top+a.y)/s.y,c=i.width/s.x,u=i.height/s.y;if(r){const e=ag(r),t=o&&cg(o)?ag(o):o;let n=e,i=vg(n);for(;i&&o&&t!==n;){const e=Tg(i),t=i.getBoundingClientRect(),o=bg(i),r=t.left+(i.clientLeft+parseFloat(o.paddingLeft))*e.x,s=t.top+(i.clientTop+parseFloat(o.paddingTop))*e.y;d*=e.x,l*=e.y,c*=e.x,u*=e.y,d+=r,l+=s,n=ag(i),i=vg(n)}}return ng({width:c,height:u,x:d,y:l})}function Bg(e,t){const n=xg(e).scrollLeft;return t?t.left+n:Eg(dg(e)).left+n}function Ag(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Bg(e,n),y:n.top+t.scrollTop}}function Rg(e,t,n){let o;if("viewport"===t)o=((e,t)=>{const n=ag(e),o=dg(e),i=n.visualViewport;let r=o.clientWidth,s=o.clientHeight,a=0,d=0;if(i){r=i.width,s=i.height;const e=yg();(!e||e&&"fixed"===t)&&(a=i.offsetLeft,d=i.offsetTop)}const l=Bg(o);if(l<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),i="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,s=Math.abs(o.clientWidth-t.clientWidth-i);s<=25&&(r-=s)}else l<=25&&(r+=l);return{width:r,height:s,x:a,y:d}})(e,n);else if("document"===t)o=(e=>{const t=dg(e),n=xg(e),o=e.ownerDocument.body,i=KA(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),r=KA(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let s=-n.scrollLeft+Bg(e);const a=-n.scrollTop;return"rtl"===bg(o).direction&&(s+=KA(t.clientWidth,o.clientWidth)-i),{width:i,height:r,x:s,y:a}})(dg(e));else if(cg(t))o=((e,t)=>{const n=Eg(e,!0,"fixed"===t),o=n.top+e.clientTop,i=n.left+e.clientLeft,r=ug(e)?Tg(e):VA(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:i*r.x,y:o*r.y}})(t,n);else{const n=Mg(e);o={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ng(o)}function $g(e,t){const n=wg(e);return!(n===t||!cg(n)||Sg(n))&&("fixed"===bg(n).position||$g(n,t))}function Lg(e,t){const n=t.get(e);if(n)return n;let o=Pg(e,[],!1).filter(e=>cg(e)&&"body"!==sg(e)),i=null;const r="fixed"===bg(e).position;let s=r?wg(e):e;for(;cg(s)&&!Sg(s);){const t=bg(s),n=mg(s);n||"fixed"!==t.position||(i=null),(r?!n&&!i:!n&&"static"===t.position&&i&&("absolute"===i.position||"fixed"===i.position)||hg(s)&&!n&&$g(e,s))?o=o.filter(e=>e!==s):i=t,s=wg(s)}return t.set(e,o),o}function Fg(e,t,n){function o(){l.x=Bg(r)}const i=ug(t),r=dg(t),s="fixed"===n,a=Eg(e,!0,s,t);let d={scrollLeft:0,scrollTop:0};const l=VA(0);if(i||!i&&!s)if(("body"!==sg(t)||hg(r))&&(d=xg(t)),i){const e=Eg(t,!0,s,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&o();s&&!i&&r&&o();const c=!r||i||s?VA(0):Ag(r,d);return{x:a.left+d.scrollLeft-l.x-c.x,y:a.top+d.scrollTop-l.y-c.y,width:a.width,height:a.height}}function Og(e){return"static"===bg(e).position}function Dg(e,t){if(!ug(e)||"fixed"===bg(e).position)return null;if(t)return t(e);let n=e.offsetParent;return dg(e)===n&&(n=n.ownerDocument.body),n}function zg(e,t){const n=ag(e);if(fg(e))return n;if(!ug(e)){let t=wg(e);for(;t&&!Sg(t);){if(cg(t)&&!Og(t))return t;t=wg(t)}return n}let o=Dg(e,t);for(;o&&gg(o)&&Og(o);)o=Dg(o,t);return o&&Sg(o)&&Og(o)&&!mg(o)?n:o||(e=>{let t=wg(e);for(;ug(t)&&!Sg(t);){if(mg(t))return t;if(fg(t))return null;t=wg(t)}return null})(e)||n}function Ug(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Ng({editor:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:o,offset:i,placement:r}){Wk(()=>{const s=o(),a=n.current;if(!s||!a)return;let d=!1,l=0;a.style.visibility="hidden";const c=()=>{const e=++l,n=Wg("--toolbar-floating-shift-padding",8),o=i??Wg("--toolbar-floating-offset",38),c={top:Wg("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((e,t,n)=>{const o={platform:sR,...n},i={...o.platform,_c:new Map};return(async(e,t,n)=>{const{placement:o="bottom",strategy:i="absolute",middleware:r=[],platform:s}=n,a=s.detectOverflow?s:{...s,detectOverflow:ig},d=await(null==s.isRTL?void 0:s.isRTL(t));let l=await s.getElementRects({reference:e,floating:t,strategy:i}),{x:c,y:u}=og(l,o,d),p=o,h=0;const g={};for(let f=0;f<r.length;f++){const n=r[f];if(!n)continue;const{name:m,fn:y}=n,{x:S,y:b,data:x,reset:w}=await y({x:c,y:u,initialPlacement:o,placement:p,strategy:i,middlewareData:g,rects:l,platform:a,elements:{reference:e,floating:t}});c=null!=S?S:c,u=null!=b?b:u,g[m]={...g[m],...x},w&&h<50&&(h++,"object"==typeof w&&(w.placement&&(p=w.placement),w.rects&&(l=!0===w.rects?await s.getElementRects({reference:e,floating:t,strategy:i}):w.rects),({x:c,y:u}=og(l,p,d))),f=-1)}return{x:c,y:u,placement:p,strategy:i,middlewareData:g}})(e,t,{...o,platform:i})})(s,a,{strategy:"fixed",placement:r,middleware:[aR(o),lR({fallbackPlacements:[...t],padding:c}),dR({padding:c})]}).then(({placement:t,x:n,y:o})=>{d||e!==l||(a.dataset.placement=t,a.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(o)}px, 0)`,a.style.visibility="visible")})},u=function(e,t,n,o){void 0===o&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:s="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:d=!1}=o,l=Cg(e),c=i||r?[...l?Pg(l):[],...t?Pg(t):[]]:[];c.forEach(e=>{i&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=l&&a?((e,t)=>{function n(){var e;clearTimeout(o),null==(e=i)||e.disconnect(),i=null}let o,i=null;const r=dg(e);return function s(a,d){function l(t){const n=t[0].intersectionRatio;if(n!==d){if(!m)return s();n?s(!1,n):o=setTimeout(()=>{s(!1,1e-7)},1e3)}1!==n||Ug(c,e.getBoundingClientRect())||s(),m=!1}void 0===a&&(a=!1),void 0===d&&(d=1),n();const c=e.getBoundingClientRect(),{left:u,top:p,width:h,height:g}=c;if(a||t(),!h||!g)return;const f={rootMargin:-jA(p)+"px "+-jA(r.clientWidth-(u+h))+"px "+-jA(r.clientHeight-(p+g))+"px "+-jA(u)+"px",threshold:KA(0,_A(1,d))||1};let m=!0;try{i=new IntersectionObserver(l,{...f,root:r.ownerDocument})}catch(y){i=new IntersectionObserver(l,f)}i.observe(e)}(!0),n})(l,n):null;let p,h=-1,g=null;s&&(g=new ResizeObserver(e=>{let[o]=e;o&&o.target===l&&g&&t&&(g.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=g)||e.observe(t)})),n()}),l&&!d&&g.observe(l),t&&g.observe(t));let f=d?Eg(e):null;return d&&function t(){const o=Eg(e);f&&!Ug(f,o)&&n(),f=o,p=requestAnimationFrame(t)}(),n(),()=>{var e;c.forEach(e=>{i&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=g)||e.disconnect(),g=null,d&&cancelAnimationFrame(p)}}(s,a,c,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),p=Zi("CanvasKitFloatingPosition.pageTransform",e.pageTransformSignal,c,{fireImmediately:!1});return c(),()=>{d=!0,a.style.visibility="hidden",u(),p()}},[e,t,n,o,i,r])}function Wg(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const o=Number.parseFloat(n);return Number.isFinite(o)?n.endsWith("rem")?16*o:o:t}function Xg({children:e,className:t,context:n,dataUi:o="floating-selection-toolbar-slot",horizontalAlign:i="start",offset:r,visible:s=!0}){return s?Gk(Yg,{editor:n.editor,className:t,dataUi:o,offset:r,horizontalAlign:i,children:e}):null}function Yg({children:e,className:t,dataUi:n,editor:o,horizontalAlign:i,offset:r}){return Ir(o.selectionTranslationActiveSignal)?null:Gk(Hg,{className:t,dataUi:n,editor:o,horizontalAlign:i,offset:r,children:e})}function Hg({children:e,className:t,dataUi:n,editor:o,horizontalAlign:i,offset:r}){const s=Ir(o.queries.selectionPageBoundsSignal);return s?Gk(_g,{anchor:{x:s.minX,y:s.minY,width:s.w,height:s.h},className:t,dataUi:n,editor:o,horizontalAlign:i,offset:r,children:e}):null}function _g({anchor:e,children:t,className:n,dataUi:o,editor:i,horizontalAlign:r,offset:s}){const a=Kk(null),d=Kk(null);_h(d);const l=Uk(()=>a.current,[e.height,e.width,e.x,e.y]);return Ng({editor:i,fallbackPlacements:"center"===r?uR:cR,floatingRef:d,getReferenceElement:l,offset:s,placement:"center"===r?"top":"top-start"}),Zk(Vk,{children:[Gk(Pr,{dataUi:`${o}-page-space`,className:"land-canvas__floating-selection-page-space",children:Gk("div",{ref:a,"aria-hidden":"true",style:{position:"absolute",left:e.x,top:e.y,width:e.width,height:e.height,pointerEvents:"none"}})}),Gk("div",{ref:d,"data-ui":o,className:Kg("land-canvas__floating-selection-anchor",n),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:t})]})}function Kg(...e){return e.filter(Boolean).join(" ")}function qg(e){return e}function jg({presenter:e}){function t({children:t}){
|
|
30
|
+
return Gk(Ja,{presenter:e,children:t})}return{id:"canvas-kit.text",requires:[jE],setup(e){e.ui.addProviders({id:"canvas-kit.text-link-popover-presenter",component:t})}}}function Vg(e){return t=>Gk(Gg,{...t,icons:e})}function Gg({icons:e,...t}){const n=Wh();return n?fC(Gk(Zg,{...t,icons:e}),n):null}function Zg({icons:e,...t}){const{anchorElement:n,href:o,onOpen:i,onPopoverPointerEnter:r,onPopoverPointerLeave:s}=t,a=wr(),d=Kk(null),l=Uk(()=>n,[n]);return _h(d),Ng({editor:a,fallbackPlacements:pR,floatingRef:d,getReferenceElement:l,offset:8,placement:"top"}),Zk("div",{ref:d,"aria-label":"Link preview",className:"land-canvas-kit__text-link-popover","data-ui":"rich-text-link-popover",role:"toolbar",onPointerEnter:r,onPointerLeave:s,onPointerDown:e=>{e.stopPropagation()},onClick:e=>{e.stopPropagation()},children:[Gk("button",{"aria-label":"Open link",className:"land-canvas-kit__text-link-popover-icon-button",title:"Open link",type:"button",onClick:i,children:e.open}),Gk("button",{"aria-label":`Open ${o}`,className:"land-canvas-kit__text-link-popover-link",title:o,type:"button",onClick:i,children:o})]})}function Qg(e,t={}){const n=t.enabled??!0,o=t.pageId,i=Uk(t=>n?e.subscribe(t):()=>{},[n,e]),r=Uk(()=>n?e.getSnapshot(o):hR,[n,o,e]);return jk(i,r,r)}function Jg({childIds:e,depth:t,editor:n,index:o,pageId:i,shape:r}){return{id:r.id,parentId:r.parentId,pageId:i,type:r.type,childIds:e,siblingIndex:o,depth:t,canReceiveChildren:n.canUseShapeParent(r.id),isHidden:r.isHidden,isLocked:r.isLocked,isEffectivelyHidden:n.isShapeHidden(r.id),isEffectivelyLocked:n.isShapeOrAncestorLocked(r.id)}}function ef(e,t){let n=0,o=e.getShape(t);const i=new Set([t]);for(;o?.parentId.startsWith("shape:");){const t=o.parentId;if(i.has(t))break;i.add(t),o=e.getShape(t),n+=1}return n}function tf(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function nf(e){const t=e.getDocumentMetadataRecord();return{id:t?.id??"document:main",meta:{...t?.meta??{}}}}function of(e,t){return{id:t.id,type:t.type,parentId:t.parentId,pageId:e.getShapePageId(t.id),index:t.index,x:t.x,y:t.y,rotation:t.rotation,skewX:t.skewX,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,props:{...t.props},meta:{...t.meta}}}function rf(e){return{id:e.id,x:e.x,y:e.y,rotation:e.rotation,skewX:e.skewX,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function sf(e,t){const n=e.sessionSignal.get(),o=n.activeToolId;t.assertToolId(o);const i=o,r=e.getPages().map(t=>({pageId:t.id,selectedShapeIds:[...e.getSelectedShapeIds(t.id)],camera:{...e.getCamera(t.id)}}));return{currentPageId:n.currentPageId,activeToolId:i,isToolLocked:n.isToolLocked,meta:{...n.meta},pages:r}}function af(e,t){const n=e.getActiveToolId();t.assertToolId(n);const o=n;return{productId:t.productId,document:nf(e),pageId:e.getCurrentPageId(),activeToolId:o,selectedShapeIds:[...e.getSelectedShapeIds()],shapeCount:e.getCurrentPageShapeIds().length,session:sf(e,t)}}function df(e){return{...e,selectedShapeIds:[...e.selectedShapeIds],session:{...e.session,meta:{...e.session.meta},pages:e.session.pages.map(e=>({...e,selectedShapeIds:[...e.selectedShapeIds],camera:{...e.camera}}))},document:{...e.document,meta:{...e.document.meta}}}}function lf(e){return{...e,meta:{...e.meta}}}function cf(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function uf(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}function pf(e,t){e.includes(t)||e.push(t)}function hf(e,t){return e.added.some(e=>e.scope===t)||e.updated.some(e=>e.before.scope===t||e.after.scope===t)||e.removed.some(e=>e.scope===t)}function gf(e){const t=globalThis.reportError;"function"!=typeof t?console.error(e):t(e)}function ff(e){return{added:e.diff.added.filter(e=>"shape"===e.typeName).map(e=>e.id),updated:e.diff.updated.filter(e=>"shape"===e.after.typeName).map(e=>e.after.id),removed:e.diff.removed.filter(e=>"shape"===e.typeName).map(e=>e.id)}}function mf(e){const{apis:t,editor:n}=e;return{apis:t,snapshot:()=>af(n,e),subscribe(t,o){let i=df(af(n,e));if("committed"===o?.delivery)return n.operations.subscribe(n=>{const o=function(e,t){const n=e.snapshot.records,o=e.sessionSnapshot.records[0];if(!o)throw new Error("Editor commit is missing its session snapshot.");const i=o.activeToolId;t.assertToolId(i);const r=i,s=n.filter(e=>"page"===e.typeName).sort((e,t)=>e.index.localeCompare(t.index)),a=n.filter(e=>"shape"===e.typeName),d=new Map(a.map(e=>[e.id,e])),l=new Set(s.map(e=>e.id)),c=o.currentPageId,u=[...o.pageSelectedShapeIdsById[c]??[]],p=n.find(e=>"document"===e.typeName);return{productId:t.productId,document:{id:p?.id??"document:main",meta:{...p?.meta??{}}},pageId:c,activeToolId:r,selectedShapeIds:u,shapeCount:a.filter(e=>((e,t,n)=>{const o=new Set([e.id]);let i=e.parentId;for(;i.startsWith("shape:");){const e=i;if(o.has(e))return null;o.add(e);const n=t.get(e);if(!n)return null;i=n.parentId}return n.has(i)?i:null})(e,d,l)===c).length,session:{currentPageId:c,activeToolId:r,isToolLocked:o.isToolLocked,meta:{...o.meta},pages:s.map(e=>({pageId:e.id,selectedShapeIds:[...o.pageSelectedShapeIdsById[e.id]??[]],camera:{...o.pageCameraById[e.id]??NC}}))}}}(n,e),r=["document"];o.shapeCount!==i.shapeCount&&r.push("shapeCount"),i=df(o);try{t({delivery:"committed",source:n.source,commit:{id:n.id,revision:n.revision,kind:n.kind,label:n.label},changes:r,affectedShapeIds:ff(n),snapshot:o})}catch(s){gf(s)}});const r=o?.scope??"all";return n.listen(o=>{const s=hf(o.diff,"document"),a=hf(o.diff,"session");if(!s&&!a||"document"===r&&!s||"session"===r&&!a)return;const d=a?af(n,e):((e,t,n,{hasDocumentMetadataChange:o})=>{return{productId:n.productId,document:o?nf(e):lf(t.document),pageId:t.pageId,activeToolId:t.activeToolId,selectedShapeIds:[...t.selectedShapeIds],shapeCount:e.getCurrentPageShapeIds().length,session:(i=t.session,{...i,meta:{...i.meta},pages:i.pages.map(e=>({...e,selectedShapeIds:[...e.selectedShapeIds],camera:{...e.camera}}))})};var i})(n,i,e,{hasDocumentMetadataChange:(l=o.diff,l.added.some(e=>"document"===e.typeName)||l.updated.some(e=>"document"===e.before.typeName||"document"===e.after.typeName)||l.removed.some(e=>"document"===e.typeName))});var l;let c=((e,t)=>{const n=[];return e.pageId!==t.pageId&&n.push("pageId"),e.activeToolId!==t.activeToolId&&n.push("activeToolId"),cf(e.selectedShapeIds,t.selectedShapeIds)||n.push("selectedShapeIds"),e.shapeCount!==t.shapeCount&&n.push("shapeCount"),function(e,t){if(e.currentPageId!==t.currentPageId||e.activeToolId!==t.activeToolId||e.isToolLocked!==t.isToolLocked||!((e,t)=>{const n=Object.keys(e),o=Object.keys(t);return n.length===o.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))})(e.meta,t.meta)||e.pages.length!==t.pages.length)return!1;for(let n=0;n<e.pages.length;n+=1){const o=e.pages[n],i=t.pages[n];if(o.pageId!==i.pageId||!cf(o.selectedShapeIds,i.selectedShapeIds)||!uf(o.camera,i.camera))return!1}return!0}(e.session,t.session)||n.push("session"),n})(i,d);if(s&&pf(c,"document"),a&&pf(c,"session"),c=((e,t)=>"all"===t?e:e.filter("document"===t?e=>"document"===e||"shapeCount"===e:e=>"document"!==e))(c,r),0===c.length)return void(i=df(d));const u=i;i=df(d);try{t({delivery:"realtime",source:o.source,changes:c,snapshot:d,previousSnapshot:u})}catch(p){gf(p)}})},clearHistory(){n.history.clear()},canUndo:()=>n.historyStateSignal.get().canUndo,canRedo:()=>n.historyStateSignal.get().canRedo,undo:()=>n.undo(),redo:()=>n.redo(),getDocument:()=>nf(n),updateDocumentMeta:e=>(n.updateDocumentMeta(e,"user"),nf(n)),updateSessionMeta(t){const o=n.getSessionRecord();return n.updateSession({meta:{...o.meta,...t}},"user"),sf(n,e)},select(e){n.commands.setSelectedShapeIds(e,{source:"user"})},selectAll(){n.selectAllCurrentPage("user")},deleteSelection(){n.deleteSelection("user")},deleteShapes(e){n.deleteShapesById(e,"user")},getAsset(e){const t=n.getAsset(e);return t?(e=>({id:e.id,type:e.type,props:{...e.props},meta:{...e.meta}}))(t):null},resolveAssetUrl:e=>n.resolveAssetUrl(e),getShape(e){const t=n.getShape(e);return t?of(n,t):null},getShapes:e=>(e?e.map(e=>n.getShape(e)).filter(e=>!!e):n.getPages().flatMap(e=>n.getShapesForPage(e.id))).map(e=>of(n,e)),updateShapes(e){const t=e.filter(e=>{const t=n.getShape(e.id);return!!t&&function(e,t){return!(!t.props&&void 0===t.meta)||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.skewX??e.skewX)!==e.skewX||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(o=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):o))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,o}(t,e)}).map(rf);return 0===t.length?[]:(n.commands.updateShapes(t,{source:"user"}),t.map(e=>e.id))},updateShapeMeta(e,t){const o=n.getShape(e);return o?(n.commands.updateShapes([{id:e,meta:{...o.meta,...t}}],{source:"user"}),e):null},duplicateSelection:()=>n.duplicateSelection(),centerOnShape(e){const t=n.getShapePageId(e);if(!t)return!1;t!==n.getCurrentPageId()&&n.commands.setCurrentPageId(t,{source:"user"});const o=n.getShapeSubtreePageBounds(e);if(!o)return!1;const i=n.viewportScreenSizeSignal.get();if(i.w<=0||i.h<=0)return!1;const r=n.getCurrentCamera();return n.commands.setCamera({pageId:t,camera:{x:o.center.x-i.w/(2*r.z),y:o.center.y-i.h/(2*r.z),z:r.z}},{source:"user"}),!0},getLayerTree:e=>(({editor:e,pageId:t=e.getCurrentPageId()})=>{const n=[],o=(i,r)=>{e.getChildShapes(i).forEach((i,s)=>{const a=e.getChildShapeIds(i.id);n.push(Jg({childIds:a,depth:r,editor:e,index:s,pageId:t,shape:i})),o(i.id,r+1)})};return o(t,0),n})({editor:n,pageId:e??n.getCurrentPageId()}),getLayerNode:e=>(({editor:e,id:t})=>{const n=e.getShape(t),o=n?e.getShapePageId(n.id):null;if(!n||!o)return null;const i=e.getChildShapeIds(n.parentId);return Jg({childIds:e.getChildShapeIds(n.id),depth:ef(e,n.id),editor:e,index:i.indexOf(n.id),pageId:o,shape:n})})({editor:n,id:e}),setShapesHidden:(e,t)=>n.setShapesHidden(e,t,"user"),setShapesLocked:(e,t)=>n.setShapesLocked(e,t,"user"),groupShapes:e=>n.groupShapes(e,"user")?.id??null,ungroupShapes:e=>n.ungroupShapes(e,"user"),moveShapesInParentOrder:(e,t)=>n.moveShapesInParentOrder(e,t,"user"),moveShapesToParentOrderEdge:(e,t)=>n.moveShapesToParentOrderEdge(e,t,"user"),moveShapesToLayerPlacement:(e,t)=>n.moveShapesToParentPlacementResult({ids:e,parentId:t.parentId,beforeId:t.beforeId},"user"),getLayerActionState:e=>({canGroup:n.canGroupShapes(e),canUngroup:n.canUngroupShapes(e),canMoveBackward:n.canMoveShapesInParentOrder(e,"backward"),canMoveForward:n.canMoveShapesInParentOrder(e,"forward")}),setTool(e){if(!n.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);n.setActiveTool(e,"user")},setCamera(e,t){n.commands.setCamera({pageId:t,camera:e},{source:"user"})},resetView(){n.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},getPages:()=>n.getPages().map(tf),createPage:e=>tf(n.createPageAndSelect(e?{name:e.name,meta:e.meta?{...e.meta}:void 0}:void 0,"user")),renamePage(e,t){n.renamePage(e,t,"user")},updatePageMeta:(e,t)=>n.updatePageMeta(e,t,"user")?.id??null,deletePage:e=>n.deletePage(e,"user"),selectPage(e){n.selectPage(e,"user")}}}function yf(e){if(!(e=>fR.has(e))(e)){if("geo"===e)throw new Error(`Unknown canvas kit tool "${e}". "geo" is a shape type, not a tool id. Use one of the geo tool ids such as "rectangle", "ellipse", or "triangle". Available tool ids: ${mR}.`);throw new Error(`Unknown canvas kit tool "${e}". Available tool ids: ${mR}.`)}}function Sf(e){return bf({...e,assertToolId:e.assertToolId??yf})}function bf(e){return{...mf(e)}}function xf(e,t){const n=Uk(n=>t?Zi("useOptionalValue",e,n,{fireImmediately:!1}):()=>{},[t,e]),o=Uk(()=>t?e.get():null,[t,e]);return jk(n,o,o)}function wf(e){return new Promise((t,n)=>{const o=new FileReader;o.addEventListener("load",()=>{t("string"==typeof o.result?o.result:null)}),o.addEventListener("error",()=>{n(o.error)}),o.readAsDataURL(e)})}async function If({assetInliners:e=[],editor:t,padding:n=16,resolveThemeColor:o,shapeIds:i}){const r=t.repairExportIntegrity(i),s=t.getShapeCapabilityManifest();let a,d=t.getExportIntegrityReport(i);try{a=await(async({assetInliners:e,editor:t,padding:n,resolveThemeColor:o,shapeIds:i})=>{for(let s=0;s<3;s+=1){const s=t.store.recordsSignal.get();try{for(const n of e)await(n.prepare?.({editor:t,requestedShapeIds:i}))}catch(r){if(t.store.recordsSignal.get()!==s)continue;throw r}if(t.store.recordsSignal.get()!==s)continue;const a=t.getSvgString(i,{padding:n,resolveThemeColor:o}),d=a?.exportedShapeIds.flatMap(e=>{const n=t.getShape(e);return n?[n]:[]})??[];if(t.store.recordsSignal.get()===s)return{exportedShapes:d,result:a}}throw new Error("The document changed repeatedly during SVG export.")})({assetInliners:e,editor:t,padding:n,resolveThemeColor:o,shapeIds:i})}catch(h){return d=t.getExportIntegrityReport(i),Pf({capabilityManifest:s,cause:h,integrity:d})}d=t.getExportIntegrityReport(i);const l=(({capabilityManifest:e,integrity:t})=>{const n=(e=>{const t=Object.entries(e).filter(e=>"number"==typeof e[1]);return 0===t.length?"none":t.map(([e,t])=>`${e} ${t}`).join(", ")})((e=>{const t={};for(const n of e.issues)t[n.kind]=(t[n.kind]??0)+1;return t})(t));return 0===t.fatalIssueCount&&0===t.issues.length?{tone:"success",title:"SVG export ready",details:`${t.requestedShapeIds.length} shape(s) ready. Issues: ${n}.`,integrity:t,capabilityManifest:e}:t.canExport?{tone:"warning",title:"SVG export repaired",details:`${t.requestedShapeIds.length} shape(s) exportable. Issues: ${n}.`,integrity:t,capabilityManifest:e}:{tone:"error",title:"SVG export blocked",details:`Fatal export issue(s): ${n}.`,integrity:t,capabilityManifest:e}})({capabilityManifest:s,integrity:d});(r.before.issues.length>0||d.issues.length>0)&&console.warn("SVG export integrity report",{before:r.before,after:r.after,final:d});const{exportedShapes:c,result:u}=a;if(!u)return{status:{...l,tone:"error",title:"SVG export blocked",details:`${l.details} No exportable SVG content was produced.`},svg:null,width:null,height:null,exportedShapeIds:[],skippedShapes:[]};u.skippedShapes.length>0&&console.warn("Skipped shapes during SVG export",u.skippedShapes);let p=u.svg;try{for(const n of e)p=await n.inline({editor:t,exportedShapes:c,exportedShapeIds:u.exportedShapeIds,svg:p});(e=>{const t=new Set,n=/\burl\(\s*(["']?)(.*?)\1\s*\)/giu,o=Array.from(e.matchAll(/<([a-z][\w:-]*)\b([^>]*)>/giu));for(const r of o){const e=vf(r[1]??""),n=Cf(r[2]??"");for(const o of kf(e)){const e=n.get(o)?.trim();if(!e)continue;const i="srcset"===o?Tf(e):[e];for(const n of i)Mf(n)||t.add(n)}}const i=[...o.map(e=>e[0]),...Array.from(e.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/giu),e=>e[1]??"")];for(const r of i){for(const e of r.matchAll(n)){const n=e[2]?.trim();n&&!Mf(n)&&t.add(n)}/@import\b/iu.test(r)&&t.add("CSS @import"),/\blocal\(/iu.test(r)&&t.add("CSS local() font source")}if(t.size>0)throw new Error(`${t.size} external SVG resource(s) remain after embedding.`)})(p)}catch(h){return Pf({capabilityManifest:s,cause:h,exportedShapeIds:u.exportedShapeIds,integrity:d,skippedShapes:u.skippedShapes})}return{status:l,svg:p,width:u.width,height:u.height,exportedShapeIds:u.exportedShapeIds,skippedShapes:u.skippedShapes}}function Pf({capabilityManifest:e,cause:t,exportedShapeIds:n=[],integrity:o,skippedShapes:i=[]}){const r=t instanceof Error&&t.message.trim().length>0?t.message:"An SVG resource could not be embedded.";return console.warn("SVG resource embedding failed",t),{status:{tone:"error",title:"SVG export blocked",details:`Resource embedding failed: ${r}`,integrity:o,capabilityManifest:e},svg:null,width:null,height:null,exportedShapeIds:n,skippedShapes:i}}function vf(e){return(e.split(":").pop()??e).toLowerCase()}function kf(e){const t=yR[e]??[];return bR.has(e)?t:[...SR,...t]}function Cf(e){const t=new Map;for(const n of e.matchAll(/([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gu)){const e=n[1]?.toLowerCase(),o=n[2]??n[3]??n[4];e&&void 0!==o&&t.set(e,o)}return t}function Tf(e){const t=[];let n=0;for(;n<e.length;){for(;n<e.length&&(","===e[n]||/\s/u.test(e[n]??""));)n+=1;if(n>=e.length)break;const o="data:"===e.slice(n,n+5).toLowerCase(),i=n;for(;n<e.length&&!/\s/u.test(e[n]??"")&&(o||","!==e[n]);)n+=1;let r=e.slice(i,n);const s=o&&r.endsWith(",");if(s&&(r=r.replace(/,+$/u,"")),r&&t.push(r),!s)for(;n<e.length&&","!==e[n];)n+=1}return t}function Mf(e){return e.startsWith("#")||/^data:/iu.test(e)}function Ef(e){return new Promise((t,n)=>{e.toBlob(e=>{e?t(e):n(new Error("The browser did not produce a PNG blob."))},"image/png")})}function Bf(e,t){return{...e,title:"success"===e.tone?"PNG export ready":"warning"===e.tone?"PNG export repaired":"PNG export blocked",details:t?`${e.details} ${t}`:e.details}}function Af({editor:e,exportRegistry:t}){let n=!1;const o=o=>(async()=>{if(n)throw new Error("An export is already in progress.");n=!0;try{return await t.export(o.format,{editor:e,shapeIds:$f(e,o),options:o.options})}finally{n=!1}})();return{getFormats:()=>t.getFormats(),export:o,exportPng:async e=>(await o({...Rf(e),format:"png",options:e})).result,exportSvg:async e=>(await o({...Rf(e),format:"svg",options:e})).result}}function Rf(e){return e.scope?{scope:e.scope}:{shapeIds:e.shapeIds}}function $f(e,t){if("selection"===t.scope)return e.getSelectedShapeIds();if("page"===t.scope)return e.getCurrentPageShapeIds();if(!t.shapeIds)throw new Error("Canvas export requires a scope or shapeIds.");return t.shapeIds}function Lf({svgAssetInliners:e}){return{id:"canvas-kit.export",provides:[IR],setup(t){t.exports.add((({assetInliners:e})=>({id:"canvas-kit.export.svg",format:"svg",label:"SVG",mimeType:"image/svg+xml;charset=utf-8",fileExtension:"svg",async export({editor:t,options:n,shapeIds:o}){const i=n??{},r=await If({assetInliners:e,editor:t,padding:i.padding,resolveThemeColor:i.appearance?.resolveThemeColor,shapeIds:o});return{data:r.svg,result:r,status:r.status}}}))({assetInliners:e}),(({assetInliners:e})=>({id:"canvas-kit.export.png",format:"png",label:"PNG",mimeType:"image/png",fileExtension:"png",async export({editor:t,options:n,shapeIds:o}){const i=n??{},r=await async function({background:e,pixelRatio:t=2,...n}){const o=await If(n);if(!o.svg||null===o.width||null===o.height)return{status:"error"===o.status.tone?Bf(o.status):{...o.status,tone:"error",title:"PNG export blocked",details:`${o.status.details} No exportable SVG content was produced.`},blob:null,width:null,height:null,exportedShapeIds:o.exportedShapeIds,skippedShapes:o.skippedShapes};try{const n=await(async({background:e,height:t,pixelRatio:n,svg:o,width:i})=>{const r=Math.ceil(i*n),s=Math.ceil(t*n);if((({height:e,pixelRatio:t,sourceHeight:n,sourceWidth:o,width:i})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(o)||o<=0||!Number.isFinite(n)||n<=0)throw new Error("PNG dimensions and pixel ratio must be positive numbers.");if(i>xR||e>xR||i*e>wR)throw new Error(`PNG dimensions ${i}×${e} exceed the browser export limit.`)})({height:s,pixelRatio:n,sourceHeight:t,sourceWidth:i,width:r}),"undefined"==typeof document||"undefined"==typeof Image||"undefined"==typeof FileReader)throw new Error("PNG export requires a browser environment.");const a=await wf(new Blob([o],{type:"image/svg+xml;charset=utf-8"}));if(!a)throw new Error("The exported SVG could not be encoded as a data URL.");const d=await(c=a,new Promise((e,t)=>{const n=new Image;n.onload=()=>e(n),n.onerror=()=>t(new Error("The exported SVG could not be decoded.")),n.src=c})),l=document.createElement("canvas");var c;l.width=r,l.height=s;const u=l.getContext("2d");if(!u)throw new Error("A 2D canvas context is unavailable.");return e&&(u.fillStyle=e,u.fillRect(0,0,r,s)),u.drawImage(d,0,0,r,s),{blob:await Ef(l),width:r,height:s}})({background:e,height:o.height,pixelRatio:t,svg:o.svg,width:o.width});return{status:Bf(o.status,`${n.width}×${n.height} px.`),blob:n.blob,width:n.width,height:n.height,exportedShapeIds:o.exportedShapeIds,skippedShapes:o.skippedShapes}}catch(i){console.warn("PNG rasterization failed",i);const e=i instanceof Error&&i.message.trim().length>0?i.message:"The SVG could not be rasterized.";return{status:{...o.status,tone:"error",title:"PNG export blocked",details:`Rasterization failed: ${e}`},blob:null,width:null,height:null,exportedShapeIds:o.exportedShapeIds,skippedShapes:o.skippedShapes}}}({assetInliners:e,background:i.background,editor:t,padding:i.padding,pixelRatio:i.pixelRatio,resolveThemeColor:i.appearance?.resolveThemeColor,shapeIds:o});return{data:r.blob,result:r,status:r.status}}}))({assetInliners:e})),t.apis.add({token:IR,create:({editor:e,exportRegistry:t})=>Af({editor:e,exportRegistry:t})})}}}function Ff({controller:e,activeContextMenu:t,grid:n,onActiveContextMenuChange:o,actionRegistry:i,canShowPropertiesDuringEditing:r,chromeRegistry:s,contextMenuRegistry:a,editor:d,executeCommand:l,toolbarRegistry:c}){const u=Ir(d.currentPageIdSignal),p=Ir(d.currentPageShapeIdsSignal),h=Ir(d.sessionSignal).meta,g=Ir(d.selectedShapeIdsSignal),f=Ir(d.selectionMetadataSignal),m=(({editor:e,executeCommand:t})=>{const n=Ir(e.historyStateSignal);return{canUndo:n.canUndo,canRedo:n.canRedo,undo(){t({commandId:"history.undo",run(){e.undo()}})},redo(){t({commandId:"history.redo",run(){e.redo()}})}}})({editor:d,executeCommand:l}),y=(({editor:e,executeCommand:t})=>{const n=Ir(e.pageStateSignal);return{pages:n.pages,currentPage:n.currentPage,currentPageId:n.currentPageId,canDeleteCurrentPage:n.canDeleteCurrentPage,createPage(){t({commandId:"page.create",run(){e.createPageAndSelect(void 0,"user")}})},deleteCurrentPage(){if(!n.currentPage)return;const o=n.currentPage.id;t({commandId:"page.delete-current",run(){e.deletePage(o,"user")}})},renameCurrentPage(o){if(!n.currentPage)return;const i=n.currentPage.id;t({commandId:"page.rename-current",run(){e.renamePage(i,o,"user")}})},selectPage(n){t({commandId:"page.select",run(){e.selectPage(n,"user")}})}}})({editor:d,executeCommand:l}),S=(e=>{const t=Ir(e.cameraZoomSignal);return{zoom:t,label:`${Math.round(100*t)}%`,zoomIn(){e.zoomAtViewportCenter(-120,"system")},zoomOut(){e.zoomAtViewportCenter(120,"system")},resetZoom(){e.resetZoom("user")}}})(d),b=function({editor:e,activeContextMenu:t,contextMenuRegistry:n}){const o=null!==t,i=xf(e.selectionStateSignal,o),r=xf(e.toolStateSignal,o);return _k(()=>{if(!t||!i||!r)return{context:null,activeContextMenu:null,sections:[]};const o=(({editor:e,menu:t})=>{const n=e.toolStateSignal.get();return{...Ji({editor:e,selectionState:e.selectionStateSignal.get(),toolState:n}),menu:t}})({editor:e,menu:t}),s=((e,t)=>"canvas"===e.type?"canvas":t.getSelectedShapeIds().length>0?"selection":"shape")(t.target,e);return{context:o,activeContextMenu:t,sections:n.getSections(s,o)}},[e,t,n,i,r])}({editor:d,activeContextMenu:t,contextMenuRegistry:a}),x=function({canShowPropertiesDuringEditing:e,editor:t,toolbarRegistry:n}){const o=Uk(e=>n.subscribeToState(t,e),[t,n]),i=Uk(()=>n.getStateRevision(),[n]);jk(o,i,i);const r=_k(()=>n.getChannels(),[n]),s=Ir(t.toolStateSignal),a=Ir(t.selectionMetadataSignal);(e=>{const t=Uk(t=>Zi("useToolbarSelectionShapeState",e.selectedShapesSignal,t,{fireImmediately:!1}),[e]),n=_k(()=>{let t=[];return()=>{const n=e.getSelectedShapes().map(e=>[e.id,e.type,e.parentId,e.index,e.rotation,e.skewX,e.scaleX,e.scaleY,e.opacity,e.isHidden,e.isLocked,e.props,e.meta]);return((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i)return!1;for(let e=0;e<o.length;e+=1)if(!Object.is(o[e],i[e]))return!1}return!0})(t,n)||(t=n),t}},[e]);jk(t,n,n)})(t);const d=Ir(t.shapeEditingStateSignal),l="select"===s.activeToolId,c=l?a.count:0,u=Ji({editor:t,selectionState:a,toolState:s}),p=null!==d.session,h=!p||(e?.(u)??!1),g=new Map,f=e=>{const t=g.get(e.id);if(t)return t;const o=n.getGroups(e,u);return g.set(e.id,o),o},m=((e,t)=>{for(const n of e)for(const e of n.items)if("button"===e.kind&&"editor.tool.set-active-tool"===e.actionId&&e.value===t)return e.label;return t})(f(gM.toolSwitcher),s.activeToolId),y=(({commonShapeType:e,count:t,isMixedFrameAndPointHandleSelection:n,singleShapeType:o})=>{const i=o??e;if(!i)return n?"Mixed selection":`${t} selected`;const r=t>1?` (${t})`:"";return"geo"===i?`Shape${r}`:"text"===i?`Text${r}`:`${i.charAt(0).toUpperCase()}${i.slice(1)}${r}`})({commonShapeType:a.commonShapeType,count:c,isMixedFrameAndPointHandleSelection:a.isMixedFrameAndPointHandleSelection,singleShapeType:a.singleShapeType});return{context:u,channels:r,getGroups:f,isSurfaceActive:e=>"tool"===e||l&&a.count>0,activeToolId:s.activeToolId,activeToolLabel:m,isToolLocked:s.isToolLocked,isEditing:p,canShowPropertiesDuringEditing:h,selectionCount:c,hasMixedSelectionRotation:a.hasMixedSelectionRotation,selectionLabel:y}}({canShowPropertiesDuringEditing:r,editor:d,toolbarRegistry:c}),w=(({context:e,editor:t,registry:n})=>{const o=Uk(e=>n.subscribeToState(t,e),[t,n]),i=Uk(()=>n.getStateRevision(),[n]);return _k(()=>{const t=new Map;return{context:e,channels:n.getChannels(),getSections(o){const i=t.get(o.id);if(i)return i;const r=n.getSections(o,e);return t.set(o.id,r),r}}},[e,n,jk(o,i,i)])})({context:x.context,editor:d,registry:s}),I=e.apis.get(IR);if(!I)throw new Error("Canvas export API is unavailable.");const P=_k(()=>{let t,n=[],o=[];return{getSnapshot(i){const r=i??d.getCurrentPageId(),s=((e,t)=>[...e.getShapesForPage(t),...e.getAssets()])(d,r);return t===r&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0})(n,s)||(t=r,n=s,o=e.getLayerTree(r)),o},subscribe:e=>Zi("CanvasKitLayerTree.records",d.store.recordsSignal,e,{fireImmediately:!1})}},[e,d]),v=_k(()=>({getActionState({actionId:e,context:t}){const n=i.getAction(e);if(!n)return null;const o=Qi(n,t);return{value:n.getValue?.(t),isEnabled:"enabled"===o,isVisible:"inapplicable"!==o}},runAction({actionId:e,context:t,value:n}){const o=i.getAction(e);o&&"enabled"===Qi(o,t)&&l({commandId:e,context:t,run(){o.run({context:t,value:void 0!==n?n:o.getValue?.(t)??null})}})}}),[i,l]);return{controller:e,chromeSurfaces:w,contextMenu:{activeContextMenu:t,onActiveContextMenuChange:o,runAction({actionId:e,context:t,value:n}){l({commandId:e,context:t,run(){(({actionRegistry:e,actionId:t,context:n,value:o})=>{const i=e.getAction(t);i&&"enabled"===Qi(i,n)&&i.run({context:n,value:void 0!==o?o:i.getValue?.(n)??null})})({actionRegistry:i,actionId:e,context:t,value:n})}})},surface:b},currentPageId:u,currentPageShapeIds:p,sessionMeta:h,history:m,layerTree:P,pages:y,selection:f,selectedShapeIds:g,exportApi:I,toolbarRuntime:v,toolbarSurfaces:x,grid:n,zoom:S}}function Of(){return"undefined"==typeof indexedDB?Promise.resolve(null):(kR||(kR=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(PR),e.objectStoreNames.contains("imageBlobs")||e.createObjectStore(vR)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),kR=null}),e(t)}),n.addEventListener("error",()=>{kR=null,t(n.error)})})),kR)}async function Df(e,t){if(0===t.length)return[];const n=await Of();return n?new Promise((o,i)=>{const r=n.transaction(e,"readonly"),s=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>o(a)),r.addEventListener("abort",()=>i(r.error)),r.addEventListener("error",()=>i(r.error)),t.forEach((e,t)=>{const n=s.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>i(n.error))})}):null}async function zf(e,t){if(0===t.length)return;const n=await Of();n&&await new Promise((o,i)=>{const r=n.transaction(e,"readwrite"),s=r.objectStore(e);r.addEventListener("complete",()=>o()),r.addEventListener("abort",()=>i(r.error)),r.addEventListener("error",()=>i(r.error));for(const[e,n]of t)s.put(n,e)})}async function Uf(e,t){const n=[];null!==e.documentSnapshot&&n.push([Nf(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([Wf(t),e.sessionSnapshot]),0!==n.length&&await zf(PR,n)}function Nf(e){return e.storageNamespace?`${e.storageNamespace}.document`:"canvas-kit.document"}function Wf(e){return e.storageNamespace?`${e.storageNamespace}.session`:"canvas-kit.session"}function Xf(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function Yf({assetResolverTokens:e,services:t}){return e.map(e=>t.get(e)).filter(e=>!!e)}function Hf(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function _f(e){const[t]=e.selection.selectedShapes;return!(1!==e.selection.count||!t?.parentId.startsWith("shape:"))&&"frame"===e.editor.getShape(t.parentId)?.type}function Kf(e){return Math.min(1,Math.max(0,e))}function qf(e){return f(e)&&"connector"===e.type}function jf(e){return y(e)&&"connector"===e.type}function Vf(e,t){let n=null,o=null;for(const i of e.getBindingsFromShape(t))jf(i)&&("start"===i.props.terminal?n=i:o=i);return{start:n,end:o}}function Gf(e,t){return e.getBindingsFromShape(t).filter(jf)}function Zf(e,t){const n=Qf(e),o=Qf(t);let i;if(n&&(n.needsWinding=lm(n,t.point)),o&&(o.needsWinding=lm(o,e.point)),n||o)if(n&&o){if(void 0!==e.obstacleId&&e.obstacleId===t.obstacleId)return i=((e,t,n,o)=>{const i=Sm(e.bounds,t.bounds),r=Math.max(36,36),s=new LC(i.minX-r,i.minY-r,i.w+2*r,i.h+2*r),a=Jf(e,s),d=Jf(t,s);return((e,t)=>{const n=e.filter(e=>!((e,t)=>{for(let n=1;n<e.length;n+=1){const o=e[n-1],i=e[n];if(Math.abs(o.y-i.y)<f$){if(o.y>t.minY+f$&&o.y<t.maxY-f$&&Math.max(o.x,i.x)>t.minX+f$&&Math.min(o.x,i.x)<t.maxX-f$)return!0}else if(o.x>t.minX+f$&&o.x<t.maxX-f$&&Math.max(o.y,i.y)>t.minY+f$&&Math.min(o.y,i.y)<t.maxY-f$)return!0}return!1})(e,t)&&!(e=>{for(let t=1;t<e.length;t+=1)for(let n=t+2;n<e.length;n+=1)if(dm(e[t-1],e[t],e[n-1],e[n]))return!0;return!1})(e));return[...n.length>0?n:e].sort(om)[0]})([bm([n,...em(a,e.side,d,t.side,s),o]),bm([n,...em(d,t.side,a,e.side,s).reverse(),o])],i)})(n,o,e.point,t.point),bm(i);i=n.needsWinding&&o.needsWinding?um(n,o,e.point,t.point):n.needsWinding?cm(n,o,e.point,t.point):o.needsWinding?cm(o,n,t.point,e.point).reverse():((e,t,n,o)=>{if(hm(n,o))return[n,o];if(e.axis===t.axis){if("horizontal"===e.axis){const i=(e.point.x+t.point.x)/2;return[n,new $C(i,n.y),new $C(i,o.y),o]}const i=(e.point.y+t.point.y)/2;return[n,new $C(n.x,i),new $C(o.x,i),o]}return"horizontal"===e.axis?[n,new $C(o.x,n.y),o]:[n,new $C(n.x,o.y),o]})(n,o,e.point,t.point)}else{const r=n??o,s=n?e.point:t.point,a=n?t.point:e.point;i=r.needsWinding?((e,t,n)=>{const{bounds:o,neighborPoint:i}=e;if("horizontal"===e.axis){if(n.y<o.minY||n.y>o.maxY)return[t,i,new $C(i.x,n.y),n];const e=n.y+t.y>o.minY+o.maxY?o.maxY+36:o.minY-36;return[t,i,new $C(i.x,e),new $C(n.x,e),n]}if(n.x<o.minX||n.x>o.maxX)return[t,i,new $C(n.x,i.y),n];const r=n.x+t.x>o.minX+o.maxX?o.maxX+36:o.minX-36;return[t,i,new $C(r,i.y),new $C(r,n.y),n]})(r,s,a):((e,t,n)=>{if(hm(t,n))return[t,n];const o=n.sub(t);if("horizontal"===e.axis){if(Math.abs(o.x)<=Math.abs(o.y))return[t,new $C(n.x,t.y),n];const e=t.x+o.x/2;return[t,new $C(e,t.y),new $C(e,n.y),n]}if(Math.abs(o.x)>Math.abs(o.y))return[t,new $C(t.x,n.y),n];const i=t.y+o.y/2;return[t,new $C(t.x,i),new $C(n.x,i),n]})(r,s,a),n||i.reverse()}else i=((e,t)=>{if(hm(e,t))return[e,t];const n=t.sub(e);if(Math.abs(n.x)>Math.abs(n.y)){const o=e.x+n.x/2;return[e,new $C(o,e.y),new $C(o,t.y),t]}const o=e.y+n.y/2;return[e,new $C(e.x,o),new $C(t.x,o),t]})(e.point,t.point);return bm(i)}function Qf(e){if(!e.obstacleBounds)return null;const t=(e=>Math.abs(e.x)>=Math.abs(e.y)?"horizontal":"vertical")(e.direction),n=((e,t)=>"horizontal"===t?new $C(e.x>=0?1:-1,0):new $C(0,e.y>=0?1:-1))(e.direction,t);return{point:e.point,neighborPoint:e.point.add(n.mul(36)),bounds:e.obstacleBounds,axis:t,side:pm(n,t),needsWinding:!1}}function Jf(e,t){switch(e.side){case"top":return new $C(e.point.x,t.minY);case"right":return new $C(t.maxX,e.point.y);case"bottom":return new $C(e.point.x,t.maxY);case"left":return new $C(t.minX,e.point.y)}}function em(e,t,n,o,i){const r=2*(i.w+i.h);if(r<=f$)return[e,n];const s=tm(e,t,i),a=nm(tm(n,o,i)-s,r),d=[e],l=[{position:0,point:new $C(i.minX,i.minY)},{position:i.w,point:new $C(i.maxX,i.minY)},{position:i.w+i.h,point:new $C(i.maxX,i.maxY)},{position:2*i.w+i.h,point:new $C(i.minX,i.maxY)}].map(e=>({...e,travel:nm(e.position-s,r)})).filter(e=>e.travel>f$&&e.travel<a-f$).sort((e,t)=>e.travel-t.travel);return d.push(...l.map(e=>e.point)),d.push(n),d}function tm(e,t,n){switch(t){case"top":return e.x-n.minX;case"right":return n.w+e.y-n.minY;case"bottom":return n.w+n.h+n.maxX-e.x;case"left":return 2*n.w+n.h+n.maxY-e.y}}function nm(e,t){return(e%t+t)%t}function om(e,t){const n=im(e)-im(t);if(0!==n)return n;const o=rm(e)-rm(t);return Math.abs(o)>f$?o:am(sm(e),sm(t))}function im(e){let t=0;for(let n=1;n<e.length-1;n+=1){const o=e[n].sub(e[n-1]),i=e[n+1].sub(e[n]);Math.abs(o.x*i.y-o.y*i.x)>f$&&(t+=1)}return t}function rm(e){let t=0;for(let n=1;n<e.length;n+=1){const o=e[n-1],i=e[n];t+=Math.abs(i.x-o.x)+Math.abs(i.y-o.y)}return t}function sm(e){const t=e.flatMap(e=>[e.x,e.y]),n=[...e].reverse().flatMap(e=>[e.x,e.y]);return am(t,n)<=0?t:n}function am(e,t){const n=Math.min(e.length,t.length);for(let o=0;o<n;o+=1){const n=e[o]-t[o];if(Math.abs(n)>f$)return n}return e.length-t.length}function dm(e,t,n,o){const i=Math.abs(e.y-t.y)<f$,r=Math.abs(n.y-o.y)<f$;if(i&&r)return Math.abs(e.y-n.y)<f$&&Math.max(Math.min(e.x,t.x),Math.min(n.x,o.x))<=Math.min(Math.max(e.x,t.x),Math.max(n.x,o.x))+f$;if(!i&&!r)return Math.abs(e.x-n.x)<f$&&Math.max(Math.min(e.y,t.y),Math.min(n.y,o.y))<=Math.min(Math.max(e.y,t.y),Math.max(n.y,o.y))+f$;const s=i?e:n,a=i?t:o,d=i?n:e,l=i?o:t;return d.x>=Math.min(s.x,a.x)-f$&&d.x<=Math.max(s.x,a.x)+f$&&s.y>=Math.min(d.y,l.y)-f$&&s.y<=Math.max(d.y,l.y)+f$}function lm(e,t){return!((e,t)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)(t,e.bounds)&&(n=e.neighborPoint.sub(e.point),o=t.sub(e.point),n.x*o.x+n.y*o.y<=0);var n,o}function cm(e,t,n,o){const i=e.neighborPoint,r=Sm(e.bounds,t.bounds);if("horizontal"===e.axis){if("horizontal"===t.axis&&((e,t)=>e.y<t.minY||e.y>t.maxY)(o,e.bounds))return[n,i,new $C(i.x,o.y),o];if("horizontal"===t.axis){const r=o.y+n.y>e.bounds.minY+e.bounds.maxY?e.bounds.maxY+36:e.bounds.minY-36,s=mm(e.bounds,t.bounds);return[n,i,new $C(i.x,r),new $C(s,r),new $C(s,o.y),o]}if(fm(e.bounds,t.bounds)){const r=ym(e.bounds,t.bounds);return[n,i,new $C(i.x,r),new $C(o.x,r),o]}const s=t.neighborPoint.y>o.y?r.maxY+36:r.minY-36;return[n,i,new $C(i.x,s),new $C(o.x,s),o]}if("horizontal"===t.axis&&((e,t)=>e.x<t.minX||e.x>t.maxX)(o,e.bounds))return[n,i,new $C(o.x,i.y),o];if("vertical"===t.axis){if(gm(e.bounds,t.bounds)){const r=mm(e.bounds,t.bounds);return[n,i,new $C(r,i.y),new $C(r,o.y),o]}const s=t.neighborPoint.x>o.x?r.maxX+36:r.minX-36;return[n,i,new $C(s,i.y),new $C(s,o.y),o]}const s=o.x+n.x>e.bounds.minX+e.bounds.maxX?e.bounds.maxX+36:e.bounds.minX-36,a=ym(e.bounds,t.bounds);return[n,i,new $C(s,i.y),new $C(s,a),new $C(o.x,a),o]}function um(e,t,n,o){const i=e.neighborPoint,r=t.neighborPoint,s=Sm(e.bounds,t.bounds);if("horizontal"===e.axis&&"horizontal"===t.axis){if(Math.abs(n.x-o.x)<f$&&Math.abs(i.x-r.x)<f$)return[n,i,r,o];let a,d,l;return fm(e.bounds,t.bounds)?(a=i.x,d=r.x,l=ym(e.bounds,t.bounds)):i.x>n.x?(a=s.maxX+36,d=s.minX-36,l=s.minY-36):(a=s.minX-36,d=s.maxX+36,l=s.maxY+36),[n,new $C(a,n.y),new $C(a,l),new $C(d,l),new $C(d,o.y),o]}if(e.axis!==t.axis){if("horizontal"===e.axis){const e=i.x>n.x?s.maxX+36:s.minX-36,t=r.y>o.y?s.maxY+36:s.minY-36;return[n,new $C(e,n.y),new $C(e,t),new $C(o.x,t),o]}return um(t,e,o,n).reverse()}if(Math.abs(n.y-o.y)<f$&&Math.abs(i.y-r.y)<f$)return[n,i,r,o];let a,d,l;return gm(e.bounds,t.bounds)?(a=i.y,d=r.y,l=mm(e.bounds,t.bounds)):i.y>n.y?(a=s.maxY+36,d=s.minY-36,l=s.maxX+36):(a=s.minY-36,d=s.maxY+36,l=s.minX-36),[n,new $C(n.x,a),new $C(l,a),new $C(l,d),new $C(o.x,d),o]}function pm(e,t){return"horizontal"===t?e.x>=0?"right":"left":e.y>=0?"bottom":"top"}function hm(e,t){return Math.abs(e.x-t.x)<f$||Math.abs(e.y-t.y)<f$}function gm(e,t){return e.maxX<=t.minX||t.maxX<=e.minX}function fm(e,t){return e.maxY<=t.minY||t.maxY<=e.minY}function mm(e,t){return t.minX>=e.maxX?e.maxX+(t.minX-e.maxX)/2:t.maxX+(e.minX-t.maxX)/2}function ym(e,t){return t.minY>=e.maxY?e.maxY+(t.minY-e.maxY)/2:t.maxY+(e.minY-t.maxY)/2}function Sm(e,t){const n=Math.min(e.minX,t.minX),o=Math.min(e.minY,t.minY),i=Math.max(e.maxX,t.maxX),r=Math.max(e.maxY,t.maxY);return new LC(n,o,i-n,r-o)}function bm(e){const t=[];for(const n of e){const e=t[t.length-1];if(e&&e.dist(n)<f$)continue;const o=t[t.length-2];o&&e&&(Math.abs(o.x-e.x)<f$&&Math.abs(e.x-n.x)<f$||Math.abs(o.y-e.y)<f$&&Math.abs(e.y-n.y)<f$)?t[t.length-1]=n:t.push(n)}return t}function xm(e,t){const n=e.computeShapePositionedToPageTransform(t);return e.getShapeUtil(t).getTerminalBindingOutlines(t,{editor:e}).map(e=>({points:e.points.map(e=>n.applyToPoint(e)),closed:e.closed})).filter(e=>e.points.length>0)}function wm(e,t,n,o){const i=km(e,t,n);if(!i)return null;const r=((e,t)=>[...e].sort((e,n)=>e.pagePoint.dist(t)-n.pagePoint.dist(t)||e.id.localeCompare(n.id))[0]??null)(Ci(e,t),i.point),s=r?km(e,t,r.pagePoint):null;if(r&&s&&s.distance<=1e-4&&r.pagePoint.dist(i.point)<=o)return{port:r,borderDistance:i.distance};const a=((e,t,n)=>{const o=e.computeShapePositionedToPageTransform(t).tryInvert(),i=e.computeShapePositionedBounds(t);if(!o)return{x:.5,y:.5};const r=o.applyToPoint(n);return{x:Tm(i.w<=1e-6?.5:(r.x-i.minX)/i.w),y:Tm(i.h<=1e-6?.5:(r.y-i.minY)/i.h)}})(e,t,i.point);return{port:{id:Cm(a),normalizedAnchor:a,pagePoint:i.point,pageOutwardNormal:i.outwardNormal},borderDistance:i.distance}}function Im(e,t,n){if(!n.normalizedAnchor||!n.portId.startsWith(m$))return Ti(e,t,n.portId);const o=km(e,t,((e,t,n)=>{const o=e.computeShapePositionedBounds(t);return e.computeShapePositionedToPageTransform(t).applyToPoint(new $C(o.minX+o.w*n.x,o.minY+o.h*n.y))})(e,t,n.normalizedAnchor));return o?{id:n.portId,normalizedAnchor:{...n.normalizedAnchor},pagePoint:o.point,pageOutwardNormal:o.outwardNormal}:null}function Pm(e){return e.id.startsWith(m$)?{kind:"border",normalizedAnchor:{...e.normalizedAnchor}}:{kind:"port",portId:e.id}}function vm(e,t){return{terminal:e,portId:t.id,...t.id.startsWith(m$)?{normalizedAnchor:{...t.normalizedAnchor}}:{}}}function km(e,t,n){const o=xm(e,t);if(0===o.length)return null;const i=e.getShapePageCenter(t.id)??n;let r=null,s=0;for(const a of o){if(1===a.points.length){const e=a.points[0],t=e.sub(i).normalize(),o={point:e.clone(),outwardNormal:t.len2()>0?t:new $C(1,0),distance:e.dist(n),index:s};(!r||o.distance<r.distance)&&(r=o),s+=1;continue}const e=a.closed?a.points.length:a.points.length-1;for(let t=0;t<e;t+=1){const e=a.points[t],o=a.points[(t+1)%a.points.length];if(!e||!o)continue;const d=x(e,o,n),l=d.dist(n),c=o.sub(e);if(c.len2()<=1e-12)continue;let u=new $C(-c.y,c.x).normalize();const p=d.sub(i);u.x*p.x+u.y*p.y<0&&(u=u.mul(-1)),(!r||l<r.distance||l===r.distance&&s<r.index)&&(r={point:d,outwardNormal:u,distance:l,index:s}),s+=1}}return r}function Cm(e){return`${m$}${e.x.toFixed(6)}:${e.y.toFixed(6)}`}function Tm(e){return Math.max(0,Math.min(1,e))}function Mm(e){return 3.5+(Math.max(0,e)<=1?2:0)}function Em(e){const t=Math.max(0,e);return t*Mm(t)}function Bm(e){const t=Math.max(0,e);return t*(Mm(t)-.5)}function Am(e,t,n=1){return("start"===e?2:22)+2*("start"===e?1:-1)*Mm(t)*Math.max(0,n)}function Rm(e,t,n=1){const o="start"===e?2:22,i="start"===e?1:-1,r=2*(Mm(t)-.5)*Math.max(0,n),s=o+i*r;return`M${s},${12-r} L${o},12 L${s},${12+r} M${Am(e,t,n)},12 L${o},12`}function $m(e,t){const n=Math.max(0,Math.min(1,t)),o=1-n;return"line"===e.type?e.start.add(e.end.sub(e.start).mul(n)):"quadratic"===e.type?e.start.mul(o*o).add(e.control.mul(2*o*n)).add(e.end.mul(n*n)):e.start.mul(o*o*o).add(e.control1.mul(3*o*o*n)).add(e.control2.mul(3*o*n*n)).add(e.end.mul(n*n*n))}function Lm(e,t,n,o,i){if("line"===e.type)return n+(o-n)*i;let r=n+(o-n)*i;for(let s=0;s<8;s+=1){const i=$m(e,r),s=Fm(e,r),a=i.sub(t),d=s.len2()+ay(a,Om(e,r));if(Math.abs(d)<=b$)break;const l=Math.max(n,Math.min(o,r-ay(a,s)/d));if(Math.abs(l-r)<=1e-10){r=l;break}r=l}return[n,r,o].reduce((n,o)=>$m(e,o).dist2(t)<$m(e,n).dist2(t)?o:n,r)}function Fm(e,t){const n=1-t;return"quadratic"===e.type?e.control.sub(e.start).mul(2*n).add(e.end.sub(e.control).mul(2*t)):e.control1.sub(e.start).mul(3*n*n).add(e.control2.sub(e.control1).mul(6*n*t)).add(e.end.sub(e.control2).mul(3*t*t))}function Om(e,t){if("quadratic"===e.type)return e.end.sub(e.control.mul(2)).add(e.start).mul(2);const n=1-t;return e.control2.sub(e.control1.mul(2)).add(e.start).mul(6*n).add(e.end.sub(e.control2.mul(2)).add(e.control1).mul(6*t))}function Dm(e){return Math.max(0,Math.min(1,e))}function zm(e){const t=e.tryInvert();return t?({point:n,direction:o,along:i,perpendicular:r})=>{const s=t.applyToPoint(n),a=uy(t,n,o);if(a.len()<=b$)return Jm({point:n,direction:o,along:i,perpendicular:r});const d=new $C(-a.y,a.x),l=a.mul(i).add(d.mul(r));return e.applyToPoint(s.add(l)).sub(n)}:Jm}function Um(e,t){const n=Vf(e,t.id),o=n.start?e.getShape(n.start.toId):null,i=n.end?e.getShape(n.end.toId):null,r=o&&n.start?Im(e,o,n.start.props):null,s=i&&n.end?Im(e,i,n.end.props):null,a=e.computeShapeLocalToPageTransform(t),d=o?e.getShapePageBounds(o.id)??void 0:void 0,l=i?e.getShapePageBounds(i.id)??void 0:void 0,c=r&&n.start?n.start.toId:void 0,u=s&&n.end?n.end.toId:void 0,p=(({transform:e,startPoint:t,startNormal:n,startObstacleId:o,startObstacleBounds:i,endPoint:r,endNormal:s,endObstacleId:a,endObstacleBounds:d})=>[e.a,e.b,e.c,e.d,e.e,e.f,...Nm(t),...Nm(n),o??"",...Wm(i),...Nm(r),...Nm(s),a??"",...Wm(d)])({transform:a,startPoint:r?.pagePoint,startNormal:r?.pageOutwardNormal,startObstacleId:c,startObstacleBounds:d,endPoint:s?.pagePoint,endNormal:s?.pageOutwardNormal,endObstacleId:u,endObstacleBounds:l}),h=y$.get(t);if(h&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0})(h.signature,p))return h.info;const g=t.props.curveWaypoints.map(e=>a.applyToPoint(new $C(e.x,e.y))),f=t.props.orthogonalBends.map(e=>a.applyToPoint(new $C(e.x,e.y))),m=a.applyToPoint(new $C(t.props.start.x,t.props.start.y)),y=a.applyToPoint(new $C(t.props.end.x,t.props.end.y)),S=r?.pagePoint??m,b=s?.pagePoint??y,x=b.sub(S).normalize(),w=S.sub(b).normalize(),I=Ym({start:r?{point:r.pagePoint,outwardNormal:r.pageOutwardNormal,obstacleId:c,obstacleBounds:d}:{point:S,outwardNormal:x.len()>b$?x:new $C(1,0)},end:s?{point:s.pagePoint,outwardNormal:s.pageOutwardNormal,obstacleId:u,obstacleBounds:l}:{point:b,outwardNormal:w.len()>b$?w:new $C(-1,0)},routing:t.props.routing,cornerRadius:t.props.cornerRadius,headStart:t.props.headStart,headEnd:t.props.headEnd,strokeWidth:t.props.strokeWidth,terminalOffsetMapper:zm(a),curveWaypoints:g,orthogonalBends:f});return y$.set(t,{signature:p,info:I}),I}function Nm(e){return e?[1,e.x,e.y]:[0,0,0]}function Wm(e){return e?[1,e.x,e.y,e.w,e.h]:[0,0,0,0,0]}function Xm(e,t){const n=Um(e,t),o=e.computeShapeLocalToPageTransform(t).tryInvert();return o?ly(n,o):n}function Ym({start:e,end:t,routing:n,cornerRadius:o,headStart:i="none",headEnd:r="none",strokeWidth:s=2,terminalOffsetMapper:a=Jm,curveWaypoints:d=[],orthogonalBends:l=[]}){return"curved"===n?((e,t,n,o)=>{const i=[e.point,...n.map(e=>e.clone()),t.point],r=((e,t,n)=>{const o=((e,t,n)=>{if(e.length<2)return[];const o=e.map(e=>({point:e,incoming:$C.Zero(),outgoing:$C.Zero()}));if(o[0].outgoing=oy(t,e[1]),o[o.length-1].incoming=oy(n,e[e.length-2]),e.length>2){const t=(e=>{const t=[];for(let n=0;n<e.length-1;n+=1){let o=e[n],i=e[n+1];o<i?i=o+(i-o)/2:o=i+(o-i)/2,t.push([o*S$,i*S$])}return t})(e.slice(1).map((t,n)=>t.dist(e[n])));for(let e=1;e<o.length-1;e+=1){const n=o[e],i=iy(n.point,o[e-1].point,o[e+1].point),r=o[e-1].point.sub(n.point),s=dy(i.bisector,r)*dy(i.bisector,i.normal)>0?1:-1,[a,d]=t[e-1];n.incoming=i.normal.mul(s*a),n.outgoing=i.normal.mul(-s*d)}for(let e=1;e<o.length-1;e+=1){const n=o[e-1],i=o[e],r=o[e+1],s=iy(i.point,n.point.add(n.outgoing),r.point.add(r.incoming)),a=i.point.add(s.normal),d=i.point.sub(s.normal),l=a.dist(n.point)+d.dist(r.point)<a.dist(r.point)+d.dist(n.point)?1:-1,[c,u]=t[e-1];i.incoming=s.normal.mul(l*c),i.outgoing=s.normal.mul(-l*u)}}return o.slice(1).map((e,t)=>{const n=o[t];return{type:"cubic",start:n.point,control1:n.point.add(n.outgoing),control2:e.point.add(e.incoming),end:e.point}})})(e,t,n);if(2!==e.length||1!==o.length)return o;const i=o[0],r=i.end.sub(i.start),s=r.len();if(s<=b$)return o;const a=r.normalize(),d=Math.abs(dy(a,i.control1.sub(i.start))),l=Math.abs(dy(a,i.control2.sub(i.start)));if(d>b$||l>b$)return o;const c=(Math.abs(r.x)>Math.abs(r.y)?new $C(Math.sign(r.x),0):new $C(0,Math.sign(r.y))).mul(s*S$);return[{...i,control1:i.start.add(c),control2:i.end.sub(c)}]})(i,e,t),s=r[0],a=r[r.length-1],d=(u=r,p=Km(e,s?ty(s):ey(e,t.point),o.headStart,o),h=Km(t,a?ny(a).mul(-1):ey(t,e.point),o.headEnd,o),u.length<=1?Hm(u[0]?qm(u[0]):0,p,h):{start:_m(qm(u[0]),p),end:_m(qm(u[u.length-1]),h)}),l=Gm(e,s?ty(s):ey(e,t.point),o.headStart,o.strokeWidth,o.terminalOffsetMapper,d.start),c=Gm(t,a?ny(a).mul(-1):ey(t,e.point),o.headEnd,o.strokeWidth,o.terminalOffsetMapper,d.end);var u,p,h;return Zm({start:e,end:t,segments:r.map((n,o,i)=>{const r=0===o?l.routePoint.sub(e.point):$C.Zero(),s=o===i.length-1?c.routePoint.sub(t.point):$C.Zero();return{...n,start:n.start.add(r),control1:n.control1.add(r),control2:n.control2.add(s),end:n.end.add(s)}}),markerSegments:[...l.markerSegments,...c.markerSegments],startArrowScale:d.start,endArrowScale:d.end,routePoints:i})})(e,t,d,{headStart:i,headEnd:r,strokeWidth:s,terminalOffsetMapper:a}):"orthogonal"===n?((e,t,n,o,i)=>{const r=my(e.outwardNormal),s=my(t.outwardNormal),a=((e,t,n,o,i)=>Vm([...Vm(e,t,n)].reverse(),o,i).reverse())(((e,t,n,o,i)=>{if(0===i.length)return null;const r=i.map(e=>e.clone()),s=r[0],a=r[r.length-1];if(!s||!a)return null;0!==n.x?s.y=e.y:s.x=e.x,0!==o.x?a.y=t.y:a.x=t.x;const d=fy([e,...r,t]);if(d.length<2)return null;for(let l=1;l<d.length;l+=1){const e=d[l-1],t=d[l];if(e.x!==t.x&&e.y!==t.y)return null}return d})(e.point,t.point,r,s,o)??Zf({...e,direction:r},{...t,direction:s}),e,r,t,s),d=jm(a,e,"start",r),l=jm(a,t,"end",s),c=(g=a,f=Km(e,d,i.headStart,i),m=Km(t,l,i.headEnd,i),g.length<=2?Hm(g[0]?.dist(g[g.length-1])??0,f,m):{start:_m(g[0].dist(g[1]),f),end:_m(g[g.length-2].dist(g[g.length-1]),m)}),u=Gm(e,d,i.headStart,i.strokeWidth,i.terminalOffsetMapper,c.start),p=Gm(t,l,i.headEnd,i.strokeWidth,i.terminalOffsetMapper,c.end),h=a.map(e=>e.clone());var g,f,m;return h.length>0&&(h[0]=u.routePoint,h[h.length-1]=p.routePoint),Zm({start:e,end:t,segments:gy(h,n).segments,markerSegments:[...u.markerSegments,...p.markerSegments],startArrowScale:c.start,endArrowScale:c.end,routePoints:a,startTangent:d,endTangent:l.mul(-1)})})(e,t,o,l,{headStart:i,headEnd:r,strokeWidth:s,terminalOffsetMapper:a}):((e,t,n)=>{const o=t.point.sub(e.point).normalize(),i=o.len()>b$?o:ey(e,t.point),r=o.len()>b$?o.mul(-1):ey(t,e.point),s=Hm(e.point.dist(t.point),Km(e,i,n.headStart,n),Km(t,r,n.headEnd,n)),a=Gm(e,i,n.headStart,n.strokeWidth,n.terminalOffsetMapper,s.start),d=Gm(t,r,n.headEnd,n.strokeWidth,n.terminalOffsetMapper,s.end);return Zm({start:e,end:t,segments:[{type:"line",start:a.routePoint,end:d.routePoint}],markerSegments:[...a.markerSegments,...d.markerSegments],startArrowScale:s.start,endArrowScale:s.end,routePoints:[e.point,t.point]})})(e,t,{headStart:i,headEnd:r,strokeWidth:s,terminalOffsetMapper:a})}function Hm(e,t,n){const o=t+n;if(o<=b$)return{start:0,end:0};const i=Math.min(1,Math.max(0,e-.01)/o);return{start:t>0?i:0,end:n>0?i:0}}function _m(e,t){return t<=b$?0:Math.min(1,Math.max(0,e-.01)/t)}function Km(e,t,n,o){return"arrow"!==n?0:o.terminalOffsetMapper({point:e.point,direction:t,along:3+Em(o.strokeWidth),perpendicular:0}).len()}function qm(e){const t=Qm(e,"cubic"===e.type?16:"quadratic"===e.type?8:1);return t.slice(1).reduce((e,n,o)=>e+n.dist(t[o]),0)}function jm(e,t,n,o){if(t.obstacleBounds||e.length<2)return o;const i="start"===n?e[1].sub(e[0]):e[e.length-2].sub(e[e.length-1]);return i.len()>b$?my(i):o}function Vm(e,t,n){if(!t.obstacleBounds||e.length<2)return[...e];const o=e[1],i=o.sub(e[0]);if(i.len()<=b$)return[...e];if(Math.abs(dy(i,n))<=b$&&i.x*n.x+i.y*n.y>0)return[...e];const r=t.point.add(n.mul(36)),s=0!==n.x?new $C(r.x,o.y):new $C(o.x,r.y);return fy([t.point,r,s,...e.slice(1)])}function Gm(e,t,n,o,i,r){if("arrow"!==n||r<=0)return{tipPoint:e.point,routePoint:e.point,markerSegments:[]};const s=t.normalize().len()>b$?t.normalize():ey(e,e.point),a=(t,n=0)=>i({point:e.point,direction:s,along:t,perpendicular:n}),d=e.point.add(a(3*r)),l=e.point.add(a((3+Em(o))*r)),c=Bm(o)*r,u=3*r;return{tipPoint:d,routePoint:l,markerSegments:[{type:"line",start:e.point.add(a(u+c,c)),end:d},{type:"line",start:d,end:e.point.add(a(u+c,-c))},{type:"line",start:l,end:d}]}}function Zm({start:e,end:t,segments:n,markerSegments:o,startArrowScale:i,endArrowScale:r,routePoints:s,startTangent:a,endTangent:d}){const l=[];n.forEach((e,t)=>{const n="cubic"===e.type?((e,t,n,o)=>{const i=[];for(let r=0;r<=16;r+=1){const s=r/16,a=1-s;i.push(e.mul(a*a*a).add(t.mul(3*a*a*s)).add(n.mul(3*a*s*s)).add(o.mul(s*s*s)))}return i})(e.start,e.control1,e.control2,e.end):"quadratic"===e.type?Qm(e,8):[e.start,e.end];l.push(...0===t?n:n.slice(1))});const c=n[0],u=n[n.length-1],p=[...cy(n),...o.flatMap(e=>[e.start,e.end]),e.point,t.point];return{path:py(n),startPagePoint:e.point,endPagePoint:t.point,startTangent:a??(c?ty(c):t.point.sub(e.point).normalize()),endTangent:d??(u?ny(u):t.point.sub(e.point).normalize()),startArrowScale:i,endArrowScale:r,pageBounds:LC.FromPoints(p),segments:n,markerSegments:o,points:l,routePoints:s}}function Qm(e,t){return Array.from({length:t+1},(n,o)=>$m(e,o/t))}function Jm({direction:e,along:t,perpendicular:n}){const o=e.normalize(),i=new $C(-o.y,o.x);return o.mul(t).add(i.mul(n))}function ey(e,t){const n=e.outwardNormal.normalize();return n.len()>b$?n:t.sub(e.point).normalize()}function ty(e){return"line"===e.type?e.end.sub(e.start).normalize():("cubic"===e.type?e.control1:e.control).sub(e.start).normalize()}function ny(e){return"line"===e.type?e.end.sub(e.start).normalize():e.end.sub("cubic"===e.type?e.control2:e.control).normalize()}function oy(e,t){const n=t.sub(e.point).normalize(),o=e.outwardNormal.normalize(),i=o.len()>b$?o:n,r=t.sub(e.point),s=Math.abs(ay(r,i)),a=r.len();if(a<b$)return $C.Zero();const d=s<.001?Math.min(150,a):Math.min(Math.max(s,100),a);return i.mul(d*S$)}function iy(e,t,n){const o=t.dist(e),i=e.dist(n);if(o<b$||i<b$)return{normal:$C.Zero(),bisector:$C.Zero()};const r=o/(o+i),s=t.add(n.sub(t).mul(r)),a=e.sub(s),d=a.len();if(d<b$)return{normal:$C.Zero(),bisector:$C.Zero()};const l=a.div(d);return{normal:new $C(-l.y,l.x),bisector:a}}function ry(e){const t=[];for(const n of e){const e=new Set([0,1]);for(const t of sy(n.start.x,n.control1.x,n.control2.x,n.end.x))e.add(t);for(const t of sy(n.start.y,n.control1.y,n.control2.y,n.end.y))e.add(t);for(const o of e)t.push($m(n,o))}return t}function sy(e,t,n,o){const i=3*(3*t-e-3*n+o),r=2*(3*e-6*t+3*n),s=-3*e+3*t;if(Math.abs(i)<b$){if(Math.abs(r)<b$)return[];const e=-s/r;return e>0&&e<1?[e]:[]}const a=r*r-4*i*s;if(a<0)return[];const d=Math.sqrt(a);return[(-r+d)/(2*i),(-r-d)/(2*i)].filter(e=>e>0&&e<1)}function ay(e,t){return e.x*t.x+e.y*t.y}function dy(e,t){return e.x*t.y-e.y*t.x}function ly(e,t){const n=e=>t.applyToPoint(e),o=e.segments.map(e=>"line"===e.type?{type:"line",start:n(e.start),end:n(e.end)}:"quadratic"===e.type?{type:"quadratic",start:n(e.start),control:n(e.control),end:n(e.end)}:{type:"cubic",start:n(e.start),control1:n(e.control1),control2:n(e.control2),end:n(e.end)}),i=e.markerSegments.map(e=>({type:"line",start:n(e.start),end:n(e.end)})),r=e.points.map(n),s=n(e.startPagePoint),a=n(e.endPagePoint),d=[...cy(o),...i.flatMap(e=>[e.start,e.end]),s,a];return{...e,path:py(o),startPagePoint:s,endPagePoint:a,startTangent:uy(t,e.startPagePoint,e.startTangent),endTangent:uy(t,e.endPagePoint,e.endTangent),pageBounds:LC.FromPoints(d.length>0?d:r),segments:o,markerSegments:i,points:r,routePoints:e.routePoints.map(n)}}function cy(e){const t=[];for(const n of e)"cubic"===n.type?t.push(...ry([n])):"quadratic"===n.type?t.push(n.start,n.control,n.end):t.push(n.start,n.end);return t}function uy(e,t,n){return e.applyToPoint(t.add(n)).sub(e.applyToPoint(t)).normalize()}function py(e){const t=e[0];if(!t)return"";const n=[`M ${yy(t.start)}`];for(const o of e)n.push("line"===o.type?`L ${yy(o.end)}`:"quadratic"===o.type?`Q ${yy(o.control)} ${yy(o.end)}`:`C ${yy(o.control1)} ${yy(o.control2)} ${yy(o.end)}`);return n.join(" ")}function hy(e){const t=[];for(let n=0;n<e.length;n+=1){const o=e[n],i=e[n+1];i&&o.end.equals(i.start)?(t.push(`M ${yy(o.start)} L ${yy(o.end)} L ${yy(i.end)}`),n+=1):t.push(`M ${yy(o.start)} L ${yy(o.end)}`)}return t.join(" ")}function gy(e,t){if(e.length<2)return{path:"",segments:[],points:[...e]};if(2===e.length||t<=0){const t=e.slice(1).map((t,n)=>({type:"line",start:e[n],end:t}));return{path:py(t),segments:t,points:[...e]}}const n=[],o=[e[0]];let i=e[0];for(let s=1;s<e.length-1;s+=1){const r=e[s-1],a=e[s],d=e[s+1],l=Math.min(Math.max(0,t),r.dist(a)/2,a.dist(d)/2),c=$C.Nudge(a,r,l),u=$C.Nudge(a,d,l);i.equals(c)||(n.push({type:"line",start:i,end:c}),o.push(c)),n.push({type:"quadratic",start:c,control:a,end:u}),o.push(a,u),i=u}const r=e[e.length-1];return i.equals(r)||(n.push({type:"line",start:i,end:r}),o.push(r)),{path:py(n),segments:n,points:o}}function fy(e){const t=(e=>{const t=[];for(const n of e)t[t.length-1]?.equals(n)||t.push(n);return t})(e);if(t.length<=2)return t;const n=[t[0]];for(let o=1;o<t.length-1;o+=1){const e=n[n.length-1],i=t[o],r=t[o+1];e.x===i.x&&i.x===r.x||e.y===i.y&&i.y===r.y||n.push(i)}return n.push(t[t.length-1]),n}function my(e){return Math.abs(e.x)>=Math.abs(e.y)?new $C(e.x>=0?1:-1,0):new $C(0,e.y>=0?1:-1)}function yy(e){return`${Sy(e.x)} ${Sy(e.y)}`}function Sy(e){return Number(e.toFixed(3)).toString()}function by(e){return`waypoint:${e}`}function xy(e,t){return`segment:${e}:${t}`}function wy(e,t){const n=new RegExp(`^${t}:(\\d+)$`).exec(e);if(!n)return null;const o=Number(n[1]);return Number.isSafeInteger(o)?o:null}function Iy(e){const t=/^segment:(\d+):(horizontal|vertical)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isSafeInteger(n)?{index:n,axis:t[2]}:null}function Py(e){return e.runtime.require(P$)}function vy(e,t){return{kind:"bound",shapeId:e,attachment:Pm(t)}}function ky(e,t){if("free"===t.kind)return{draft:t,pagePoint:t.pagePoint.clone(),shape:null,port:null};const n=e.getShape(t.shapeId);if(!n||qf(n)||e.isShapeHidden(n.id)||null===e.getShapeClippedPageBounds(n.id)||!e.getShapeUtil(n).canReceiveTerminalBinding(n,{editor:e}))return null;const o=((e,t,n)=>"port"===n.kind?Ti(e,t,n.portId):Im(e,t,{portId:Cm(n.normalizedAnchor),normalizedAnchor:n.normalizedAnchor}))(e,n,t.attachment);return o?{draft:t,pagePoint:o.pagePoint.clone(),shape:n,port:o,obstacleBounds:e.getShapePageBounds(n.id)??void 0}:null}function Cy(e,t,n,o){const i=ky(e,t),r=ky(e,n);if(!i||!r)return"missing_endpoint";if(i.shape&&e.isShapeOrAncestorLocked(i.shape.id))return"locked_source";const s=e.getCurrentPageId(),a=i.shape?e.getShapePageId(i.shape.id):s,d=r.shape?e.getShapePageId(r.shape.id):s;if(!a||a!==d||a!==s)return"cross_page";if(i.shape&&i.port&&r.shape&&r.port){if(Dy(i.shape.id,i.port.id,r.shape.id,r.port.id))return"same_attachment";if(Oy(e,i.shape.id,i.port.id,r.shape.id,r.port.id,o))return"duplicate"}return Uy(e,i,r)?null:"invalid_parent"}function Ty(e,t,n="user"){if(Cy(e,t.start,t.end))return null;const o=ky(e,t.start),i=ky(e,t.end);if(!o||!i)return null;const r=Uy(e,o,i);if(!r)return null;const s={...e.getDefaultShapeProps("connector"),...t.props},a=Wy({editor:e,parentId:r,start:Ly(o,i,"start"),end:Ly(i,o,"end"),props:s}),d=e.operations.begin({kind:"connector.commit",label:"shape.create",source:n,history:"user"===n?"record":"ignore"});try{const r=e.commands.createShapes([a],{source:n,autoReparent:!1})[0];if(!qf(r))return d.cancel(),null;if(o.shape&&o.port&&Fy(e,r.id,"start",{shape:o.shape,port:o.port},n),i.shape&&i.port&&Fy(e,r.id,"end",{shape:i.shape,port:i.port},n),"none"!==t.selectionAfter){const o=Array.isArray(t.selectionAfter)?[...t.selectionAfter]:[r.id];e.commands.setSelectedShapeIds(o,{source:n})}const s=e.getShape(r.id);return qf(s)?(d.commit(),s):(d.cancel(),null)}catch(l){throw d.isActive&&d.cancel(),l}}function My(e,t){return By(e,t)}function Ey(e,t,n,o){return By(e,t,{[n]:o})}function By(e,t,n={}){const o=Vf(e,t.id),i=e.computeShapeLocalToPageTransform(t),r=i.applyToPoint(new $C(t.props.start.x,t.props.start.y)),s=i.applyToPoint(new $C(t.props.end.x,t.props.end.y)),a=Ay(e,o.start),d=Ay(e,o.end),l=n.start??a?.port.pagePoint??r,c=n.end??d?.port.pagePoint??s,u=!n.start&&a?Ry(e,a):$y(l,c,"start"),p=!n.end&&d?Ry(e,d):$y(c,l,"end"),h=a&&d?zy(e,a.shape,d.shape):t.parentId;if(!h||!e.canUseShapeParent(h))return null;const g=Wy({editor:e,parentId:h,start:u,end:p,props:t.props,manualPageGeometry:{curveWaypoints:t.props.curveWaypoints.map(e=>i.applyToPoint(new $C(e.x,e.y))),orthogonalBends:t.props.orthogonalBends.map(e=>i.applyToPoint(new $C(e.x,e.y)))}});return{...t,parentId:h,x:g.x,y:g.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{...t.props,...g.props}}}function Ay(e,t){if(!t)return null;const n=e.getShape(t.toId);if(!n)return null;const o=Im(e,n,t.props);return o?{shape:n,port:o}:null}function Ry(e,t){return{point:t.port.pagePoint,outwardNormal:t.port.pageOutwardNormal,obstacleId:t.shape.id,obstacleBounds:e.getShapePageBounds(t.shape.id)??void 0}}function $y(e,t,n){const o=t.sub(e).normalize();return{point:e,outwardNormal:o.len()>0?o:new $C("start"===n?1:-1,0)}}function Ly(e,t,n){return e.shape&&e.port?{point:e.pagePoint,outwardNormal:e.port.pageOutwardNormal,obstacleId:e.shape.id,obstacleBounds:e.obstacleBounds}:$y(e.pagePoint,t.pagePoint,n)}function Fy(e,t,n,o,i){e.commands.createBinding({type:"connector",fromId:t,toId:o.shape.id,props:vm(n,o.port)},{source:i})}function Oy(e,t,n,o,i,r){for(const s of e.getCurrentPageShapeIds()){if(s===r)continue;const a=e.getShape(s);if(!qf(a))continue;const d=Vf(e,a.id);if(d.start?.toId===t&&d.start.props.portId===n&&d.end?.toId===o&&d.end.props.portId===i)return!0}return!1}function Dy(e,t,n,o){return e===n&&t===o}function zy(e,t,n){const o=e.getShapePageId(t.id);if(!o||o!==e.getShapePageId(n.id))return null;const i=new Set(Xy(e,n));for(const r of Xy(e,t))if(i.has(r)&&e.canUseShapeParent(r))return r;return o}function Uy(e,t,n){if(t.shape&&n.shape)return zy(e,t.shape,n.shape);const o=e.getCurrentPageId(),i=t.shape??n.shape,r=t.shape?n.pagePoint:t.pagePoint;if(i){for(const t of Xy(e,i)){if(!t.startsWith("shape:"))return t;const n=e.getShape(t);if(n&&Ny(e,n,[r]))return n.id}return e.getShapePageId(i.id)??o}let s=null;const a=new Map(e.getCurrentPageShapeIds().map((e,t)=>[e,t]));for(const d of e.getCurrentPageShapeIds()){const o=e.getShape(d);if(!o||qf(o)||!Ny(e,o,[t.pagePoint,n.pagePoint]))continue;const i=e.getShapePageBounds(o.id);if(!i)continue;const r={shape:o,area:i.w*i.h,order:a.get(o.id)??-1};(!s||r.area<s.area||r.area===s.area&&r.order>s.order)&&(s=r)}return s?.shape.id??o}function Ny(e,t,n){if(e.isShapeHidden(t.id)||e.isShapeOrAncestorLocked(t.id)||null===e.getShapeClippedPageBounds(t.id))return!1;const o=e.getShapeUtil(t);if(!o.canReceiveChildren(t)||!o.canAutomaticallyReceiveChildren(t))return!1;const i=e.computeShapeLocalToPageTransform(t).tryInvert();if(!i)return!1;const r=o.getChildClipLocalPolygons(t),s=o.getLocalBounds(t);return n.every(n=>{if(!e.isPagePointInShapeClip(t.id,n))return!1;const o=i.applyToPoint(n);return r?T(o,r):s.containsPoint(o)})}function Wy({editor:e,parentId:t,start:n,end:o,props:i,manualPageGeometry:r}){const s=r?.curveWaypoints??[],a=r?.orthogonalBends??[],d=t.startsWith("shape:")?e.getShape(t):null,l=d?e.computeShapeLocalToPageTransform(d):FC.Identity(),c=Ym({start:n,end:o,routing:i.routing,cornerRadius:i.cornerRadius,headStart:i.headStart,headEnd:i.headEnd,strokeWidth:i.strokeWidth,terminalOffsetMapper:zm(l),curveWaypoints:s,orthogonalBends:a}),u=((e,t,n)=>{const o=t.startsWith("shape:")?e.getShape(t):null,i=(o?e.computeShapeLocalToPageTransform(o):FC.Identity()).tryInvert();return i?{bounds:LC.FromPoints(n.map(e=>i.applyToPoint(e))),pageToParent:i}:null})(e,t,[n.point,...c.points,o.point]),p=u?.pageToParent??FC.Identity(),h=u?.bounds??c.pageBounds,g=p.applyToPoint(n.point),f=p.applyToPoint(o.point);return{type:"connector",parentId:t,x:h.x,y:h.y,props:{...i,w:Math.max(1,h.w),h:Math.max(1,h.h),start:{x:g.x-h.x,y:g.y-h.y},end:{x:f.x-h.x,y:f.y-h.y},curveWaypoints:s.map(e=>{const t=p.applyToPoint(e);return{x:t.x-h.x,y:t.y-h.y}}),orthogonalBends:a.map(e=>{const t=p.applyToPoint(e);return{x:t.x-h.x,y:t.y-h.y}})}}}function Xy(e,t){const n=[],o=new Set;let i=t.parentId;for(;i.startsWith("shape:");){const t=i;if(o.has(t))break;o.add(t),n.push(t);const r=e.getShape(t);if(!r)break;i=r.parentId}return n.push(i),n}function Yy(e,t){return e.pagePoint.add(e.pageOutwardNormal.mul(20/Math.max(t,1e-4)))}function Hy(e,t,n){const o=e.pageOutwardNormal.normalize(),i=t.sub(e.pagePoint),r=1e-6/Math.max(n,1e-4);return o.len2()>0&&i.x*o.x+i.y*o.y<-r?Number.POSITIVE_INFINITY:w(t,e.pagePoint,Yy(e,n))}function _y(e,t,n={}){const o=e.cameraZoomSignal.get(),i=12/Math.max(o,1e-4),r=i+("target"===n.mode?0:20/Math.max(o,1e-4)),s=e.getShapesInBounds(new LC(t.x-r,t.y-r,2*r,2*r),n.pageId?{pageId:n.pageId}:void 0);let a=null,d=null,l=i,c=Number.POSITIVE_INFINITY;for(const u of s){if(n.excludeShapeIds?.has(u.id)||qf(u)||e.isShapeHidden(u.id)||null===e.getShapeClippedPageBounds(u.id))continue;const r=Ci(e,u);if("target"===n.mode){if(0===r.length)continue;const o=wm(e,u,t,i);if(!o)continue;const{borderDistance:s,port:p}=o,h=u.id===n.allowInteriorShapeId&&e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget",pageId:n.pageId??void 0,filter:e=>e.id===u.id}).length>0;if(s>i&&h){d={shape:u,port:p};continue}if(s>l||s>i)continue;const g=p.pagePoint.dist(t);(s<l||s===l&&g<c||s===l&&g===c&&`${u.index}:${u.id}:${p.id}`<`${a?.shape.index}:${a?.shape.id}:${a?.port.id}`)&&(a={shape:u,port:p},l=s,c=g);continue}for(const e of r){const n=Hy(e,t,o);(n<l||n===l&&`${u.index}:${u.id}:${e.id}`<`${a?.shape.index}:${a?.shape.id}:${a?.port.id}`)&&(a={shape:u,port:e},l=n)}}return a??d}function Ky(e,t,n){const o=((e,t)=>{const n=[],o=new Set;for(const i of e.getCurrentPageShapeIds()){const r=e.getShape(i);if(!qf(r))continue;const s=Vf(e,r.id),a=s.start?.toId===t.shape.id&&s.start.props.portId===t.port.id?s.end:s.end?.toId===t.shape.id&&s.end.props.portId===t.port.id?s.start:null;if(!a)continue;const d=e.getShape(a.toId);!d||o.has(d.id)||qf(d)||e.isShapeHidden(d.id)||null===e.getShapeClippedPageBounds(d.id)||(o.add(d.id),n.push(d))}return n})(e,t),i=new Set(o.map(e=>e.id)),r=((e,t)=>{const n=t.port.pageOutwardNormal.normalize(),o=t.port.pagePoint.add(n.mul(320)),i=LC.FromPoints([t.port.pagePoint,o]).expand(160),r=e.getShapePageId(t.shape.id);if(!r)return[];const s=new Map(e.getCurrentPageShapeIds().map((e,t)=>[e,t])),a=e.getShapesInBounds(i,{pageId:r}).filter(n=>n.id!==t.shape.id&&!qf(n)&&!e.isShapeHidden(n.id)&&null!==e.getShapeClippedPageBounds(n.id)&&e.getShapeUtil(n).canReceiveTerminalBinding(n,{editor:e})).flatMap(o=>{const i=e.getShapePageCenter(o.id);if(!i)return[];const r=i.sub(t.port.pagePoint),a=Zy(r,n),d=Math.abs((l=r).x*(c=n).y-l.y*c.x);var l,c;const u=r.len();if(a<=0||a>320||d>160)return[];const p=((e,t,n)=>[...Ci(e,t)].sort((e,t)=>{const o=n.sub(e.pagePoint).normalize(),i=n.sub(t.pagePoint).normalize(),r=Zy(e.pageOutwardNormal,o);return Zy(t.pageOutwardNormal,i)-r||e.pagePoint.dist(n)-t.pagePoint.dist(n)||e.id.localeCompare(t.id)})[0]??null)(e,o,t.port.pagePoint);return p?[{shape:o,port:p,distance:u,forward:a,cross:d,order:s.get(o.id)??1/0}]:[]});return a.sort((e,t)=>e.distance-t.distance||e.cross-t.cross||e.forward-t.forward||e.order-t.order||e.shape.id.localeCompare(t.shape.id)||e.port.id.localeCompare(t.port.id)),a.map(({shape:e,port:t})=>({shape:e,port:t}))})(e,t);for(const l of r)if(!i.has(l.shape.id)&&!Oy(e,t.shape.id,t.port.id,l.shape.id,l.port.id))return{kind:"connect",target:l};const s=((e,t,n,o)=>{const i=t.shape.parentId,r=Gy(e,t.shape),s=i.startsWith("shape:")?e.getShape(i):null,a=s?e.computeShapeLocalToPageTransform(s):FC.Identity(),d=t.port.pageOutwardNormal.normalize(),l=new $C(r.w/2,r.h/2),c=a.applyToPoint(l),u=a.applyToPoint(l.add(new $C(r.w/2,0))),p=a.applyToPoint(l.add(new $C(0,r.h/2))),h=Math.abs(Zy(u.sub(c),d))+Math.abs(Zy(p.sub(c),d)),g=t.port.pagePoint.add(d.mul(96+h)),f=n.createNode({editor:e,sourceShape:t.shape,sourcePortId:t.port.id,pageCenter:g,parentId:i});return 0===o.length?f:(({branchTargets:e,editor:t,input:n,source:o})=>{const i=Vy(t,n),r=t.computeShapePageCenter(i),s=new $C(-o.port.pageOutwardNormal.y,o.port.pageOutwardNormal.x).normalize();if(0===s.len2())return n;const a=Zy(o.port.pagePoint,s),d=jy(t,i,s,a),l=(d.max-d.min)/2,c=((e,t)=>{const n=e.map(({min:e,max:n})=>({min:e-48-t,max:n+48+t})).sort((e,t)=>e.min-t.min||e.max-t.max),o=[];for(const s of n){const e=o[o.length-1];!e||s.min>e.max+1e-6?o.push({...s}):e.max=Math.max(e.max,s.max)}const i=o.find(({min:e,max:t})=>e<-1e-6&&t>1e-6);if(!i)return 0;const r=e.reduce((e,t)=>e+(t.min+t.max)/2,0);return[i.min,i.max].sort((e,t)=>Math.abs(r+e)-Math.abs(r+t)||Math.abs(e)-Math.abs(t)||t-e)[0]})(e.map(e=>jy(t,e,s,a)),l)-(Zy(r,s)-a);if(Math.abs(c)<=1e-6)return n;const u=n.parentId??o.shape.parentId,p=u.startsWith("shape:")?t.getShape(u):null,h=(p?t.computeShapeLocalToPageTransform(p):FC.Identity()).tryInvert();if(!h)return n;const g=r.add(s.mul(c)),f=h.applyToPoint(r),m=h.applyToPoint(g).sub(f);return{...n,x:n.x+m.x,y:n.y+m.y}})({branchTargets:o,editor:e,input:f,source:t})})(e,t,n,o),a=Vy(e,s),d=qy(e,a,t.port);return d?{kind:"create",nodeInput:s,previewShape:a,targetPort:d}:null}function qy(e,t,n){const o=n.pageOutwardNormal.normalize();return[...Ci(e,t)].sort((e,t)=>Zy(e.pageOutwardNormal.normalize(),o)-Zy(t.pageOutwardNormal.normalize(),o)||e.pagePoint.dist(n.pagePoint)-t.pagePoint.dist(n.pagePoint)||e.id.localeCompare(t.id))[0]??null}function jy(e,t,n,o){const i=e.computeShapePageCorners(t).map(e=>Zy(e,n)-o);return{min:Math.min(...i),max:Math.max(...i)}}function Vy(e,t){const n={id:"shape:connector-quick-create-preview",typeName:"shape",scope:"document",type:t.type,parentId:t.parentId??e.getCurrentPageId(),index:t.index??"preview",x:t.x,y:t.y,rotation:t.rotation??0,skewX:t.skewX??0,scaleX:t.scaleX??1,scaleY:t.scaleY??1,opacity:t.opacity??1,isHidden:t.isHidden??!1,isLocked:t.isLocked??!1,props:{...e.getDefaultShapeProps(t.type),...t.props},meta:t.meta??{}};return{...n,props:e.getShapeUtil(n).validateProps(n.props)}}function Gy(e,t){return Dc(t)?{w:t.props.w,h:t.props.h,geo:t.props.geo,fill:t.props.fill,stroke:t.props.stroke,strokeStyle:t.props.strokeStyle,strokeWidth:t.props.strokeWidth,cornerRadiusPercent:t.props.cornerRadiusPercent}:e.getDefaultShapeProps("geo")}function Zy(e,t){return e.x*t.x+e.y*t.y}function Qy(e){const t={visibleShapes:[],sourceShapeIds:new Set,targetShapeId:null,highlightedPortId:null};if(e.getShapeEditingSession()||e.inputs.isSpacePressed.get())return t;const n=Py(e).previewSignal.get();if(n){const t=new Map;for(const i of[n.start,n.end]){if(!i.shapeId)continue;const n=e.getShape(i.shapeId);n&&Jy(e,n,"target")&&t.set(n.id,n)}const o=n[n.movingTerminal];return{visibleShapes:[...t.values()],sourceShapeIds:new Set,targetShapeId:o.shapeId,highlightedPortId:o.portId}}const o=e.getActiveToolId();let i=null;if("select"===o){const t=e.getSelectedShapes();i=1===t.length?t[0]??null:null}else if("connector"===o){const t=e.hoveredShapeIdSignal.get();i=t?e.getShape(t)??null:null}return i&&Jy(e,i,"source")?{visibleShapes:[i],sourceShapeIds:new Set([i.id]),targetShapeId:null,highlightedPortId:null}:t}function Jy(e,t,n){return!qf(t)&&!e.isShapeHidden(t.id)&&null!==e.getShapeClippedPageBounds(t.id)&&("target"===n||!e.isShapeOrAncestorLocked(t.id))&&e.getShapeUtil(t).canReceiveTerminalBinding(t,{editor:e})&&Ci(e,t).length>0}function eS({handle:e,strokeWidth:t}){
|
|
31
|
+
return Gk("circle",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,cx:e.point.x,cy:e.point.y,r:Math.max(e.bounds.w,e.bounds.h)/2,fill:"rgba(255,255,255,0.98)",stroke:"var(--land-selection, #2563eb)",strokeWidth:t,style:{cursor:e.cursor??"move",pointerEvents:"auto"}})}function tS({handle:e}){const t=.75*Math.max(e.bounds.w,e.bounds.h),n=.36*Math.max(e.bounds.w,e.bounds.h);
|
|
32
|
+
return Zk("g",{children:[Gk("circle",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,cx:e.point.x,cy:e.point.y,r:t,fill:"transparent",style:{cursor:e.cursor??"move",pointerEvents:"all"}}),Gk("circle",{cx:e.point.x,cy:e.point.y,r:n,fill:"rgba(96, 165, 250, 0.72)",pointerEvents:"none"})]})}function nS({handle:e,strokeWidth:t}){const n=Iy(e.id);if(!n)return null;const o=Math.max(e.bounds.w,e.bounds.h),i="horizontal"===n.axis,r=1.35*o+2*t,s=.4*o,a=i?r:s,d=i?s:r,l=1.8*o;
|
|
33
|
+
return Zk("g",{children:[Gk("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:e.point.x-l/2,y:e.point.y-l/2,width:l,height:l,fill:"transparent",style:{cursor:e.cursor??"grab",pointerEvents:"all"}}),Gk("rect",{x:e.point.x-a/2,y:e.point.y-d/2,width:a,height:d,rx:Math.min(a,d)/2,ry:Math.min(a,d)/2,fill:"rgba(255,255,255,0.98)",stroke:"var(--land-selection, #2563eb)",strokeWidth:t,pointerEvents:"none"})]})}function oS({shape:e,editor:t}){
|
|
34
|
+
return Gk(rS,{shape:e,editor:t,idPrefix:"connector",stroke:O(e.props.stroke),strokeWidth:e.props.strokeWidth})}function iS({shape:e,editor:t,strokeWidth:n}){
|
|
35
|
+
return Gk(rS,{dataUi:"connector-hover-outline",shape:e,editor:t,idPrefix:"connector-hover",stroke:xM,strokeWidth:n,vectorEffect:"non-scaling-stroke"})}function rS({dataUi:e,editor:t,idPrefix:n,shape:o,stroke:i,strokeWidth:r,vectorEffect:s}){const a=`${n}-content-clip-${o.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,d=Xm(t,o),l=hy(d.markerSegments),c=t.computeShapeRenderBounds(o),u=Ir(t.getShapeContentCutoutLocalPolygonsSignal(o.id)),p=Pi({outputBounds:d.pageBounds,cutoutLocalPolygons:u});
|
|
36
|
+
return Zk("svg",{"data-ui":e,width:"100%",height:"100%",viewBox:`${c.x} ${c.y} ${c.w} ${c.h}`,overflow:"visible",children:[p?Gk("defs",{children:Gk("clipPath",{id:a,clipPathUnits:"userSpaceOnUse",children:Gk("path",{d:p,clipRule:"evenodd",fillRule:"evenodd"})})}):null,Zk("g",{clipPath:p?`url(#${a})`:void 0,children:[Gk("path",{"data-connector-path":"body",d:d.path,fill:"none",stroke:i,strokeWidth:r,strokeDasharray:"dashed"===o.props.strokeStyle?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:s}),l?Gk("path",{"data-connector-path":"markers",d:l,fill:"none",stroke:i,strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:s}):null]})]})}function sS({shape:e,zoom:t}){const n=wr(),o=Ir(n.inputs.state);if(!o.currentPagePoint||o.accelKey)return null;const i=12/t,r=wm(n,e,o.currentPagePoint,i);return!r||r.borderDistance>i?null:Gk(aS,{point:r.port.pagePoint,zoom:t})}function aS({point:e,zoom:t}){
|
|
37
|
+
return Gk("circle",{"data-ui":"connector-border-snap-preview",cx:e.x,cy:e.y,r:5/t,fill:"var(--land-selection, #2563eb)",stroke:"#ffffff",strokeWidth:1.5/t,pointerEvents:"none"})}function dS({start:e,end:t,zoom:n}){const o=4/n,i=1/n;
|
|
38
|
+
return Gk("g",{"data-ui":"connector-creation-terminal-handles",pointerEvents:"none",children:[{terminal:"start",point:e},{terminal:"end",point:t}].map(({terminal:e,point:t})=>Gk("circle",{"data-connector-creation-terminal":e,cx:t.x,cy:t.y,r:o,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:i},e))})}function lS({editor:e,shape:t,port:n,zoom:o,highlighted:i,targetMode:r,quickCreateNodeFactory:s}){const[a,d]=qk(!1),l=r?n.pagePoint:Yy(n,o),c=4/o,u=12/o,p=15/o,h=12/o,g=l.sub(n.pageOutwardNormal.mul(u)),f=180*Math.atan2(n.pageOutwardNormal.y,n.pageOutwardNormal.x)/Math.PI;
|
|
39
|
+
return Zk("g",{"data-ui":"connector-port","data-connector-port":"true","data-connector-port-shape-id":t.id,"data-connector-port-id":n.id,"data-connector-port-target":r?"true":void 0,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[a&&!r?Gk(cS,{editor:e,source:{shape:t,port:n},quickCreateNodeFactory:s,zoom:o}):null,
|
|
40
|
+
Gk("line",{"data-connector-port-hit-area":"true",x1:n.pagePoint.x,y1:n.pagePoint.y,x2:l.x,y2:l.y,stroke:"transparent",strokeWidth:2*h,strokeLinecap:"butt",pointerEvents:"stroke",cursor:"crosshair"}),
|
|
41
|
+
Gk("circle",{cx:l.x,cy:l.y,r:h,fill:"transparent",pointerEvents:"all",cursor:"crosshair"}),
|
|
42
|
+
Gk("circle",{"data-connector-port-idle":"true",cx:l.x,cy:l.y,r:i?1.2*c:c,fill:i?"var(--land-selection, #2563eb)":"rgba(37, 99, 235, 0.28)",pointerEvents:"none"}),r?null:Zk("g",{"data-connector-port-hover-preview":"true",pointerEvents:"none",children:[
|
|
43
|
+
Gk("line",{x1:n.pagePoint.x,y1:n.pagePoint.y,x2:g.x,y2:g.y,stroke:"var(--land-selection, #2563eb)",strokeWidth:1.5/o,strokeLinecap:"round"}),
|
|
44
|
+
Gk("circle",{cx:l.x,cy:l.y,r:u,fill:"var(--land-selection, #2563eb)"}),
|
|
45
|
+
Gk(g$,{"data-connector-port-hover-arrow":"true",x:l.x-p/2,y:l.y-p/2,width:p,height:p,color:"#ffffff",strokeWidth:2.4,transform:`rotate(${f} ${l.x} ${l.y})`})]})]})}function cS({editor:e,source:t,quickCreateNodeFactory:n,zoom:o}){const i=Ky(e,t,n);if(!i)return null;const r=e.getDefaultShapeProps("connector"),s=(e=>"connect"===e.kind?e.target:{shape:e.previewShape,port:e.targetPort})(i),a="create"===i.kind?t.shape.parentId:zy(e,t.shape,s.shape);if(!a)return null;const d=a.startsWith("shape:")?e.getShape(a):null,l=d?e.computeShapeLocalToPageTransform(d):FC.Identity(),c=Ym({start:{point:t.port.pagePoint,outwardNormal:t.port.pageOutwardNormal,obstacleId:t.shape.id,obstacleBounds:e.getShapePageBounds(t.shape.id)??void 0},end:{point:s.port.pagePoint,outwardNormal:s.port.pageOutwardNormal,obstacleId:s.shape.id,obstacleBounds:"create"===i.kind?e.computeShapePageBounds(s.shape):e.getShapePageBounds(s.shape.id)??void 0},routing:r.routing,cornerRadius:r.cornerRadius,headStart:r.headStart,headEnd:r.headEnd,strokeWidth:r.strokeWidth,terminalOffsetMapper:zm(l),curveWaypoints:[],orthogonalBends:[]}),u=O(r.stroke);
|
|
46
|
+
return Zk("g",{"data-ui":"connector-port-quick-connect-preview","data-connector-port-quick-connect-kind":i.kind,pointerEvents:"none",children:[Zk("g",{opacity:.58,children:[Gk("path",{"data-ui":"connector-port-quick-connect-path",d:c.path,fill:"none",stroke:u,strokeWidth:r.strokeWidth,strokeDasharray:"dashed"===r.strokeStyle?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round"}),c.markerSegments.length>0?Gk("path",{"data-ui":"connector-port-quick-connect-markers",d:c.markerSegments.map(e=>`M ${e.start.x} ${e.start.y} L ${e.end.x} ${e.end.y}`).join(" "),fill:"none",stroke:u,strokeWidth:r.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round"}):null]}),"create"===i.kind?Gk(uS,{editor:e,shape:i.previewShape,zoom:o}):null]})}function uS({editor:e,shape:t,zoom:n}){const o=kr().getShapeRenderer(t.type)?.component,i=e.computeShapeRenderBounds(t),r=e.computeShapeLocalToPageTransform(t).compose(FC.Translate(i.x,i.y)),s=hS(e,t);
|
|
47
|
+
return Zk("g",{"data-ui":"connector-port-quick-create-shape",children:[o?Gk("foreignObject",{"data-ui":"connector-port-quick-create-shape-content",width:i.w,height:i.h,overflow:"visible",opacity:.52,transform:r.toSvgString(),children:Gk("div",{style:{height:"100%",overflow:"visible",pointerEvents:"none",width:"100%"},children:Gk(pS,{Renderer:o,editor:e,shape:t})})}):s?Gk("path",{"data-ui":"connector-port-quick-create-shape-fallback",d:s,fill:"rgba(37, 99, 235, 0.1)",stroke:"none"}):null,s?Gk("path",{"data-ui":"connector-port-quick-create-shape-outline",d:s,fill:"none",stroke:"var(--land-selection, #2563eb)",strokeWidth:1.5/n,strokeDasharray:`${5/n} ${4/n}`,strokeLinecap:"round",strokeLinejoin:"round"}):null]})}function pS({Renderer:e,editor:t,shape:n}){
|
|
48
|
+
return Gk(e,{editor:t,isSelected:!1,shape:n,shapeEditingSession:null})}function hS(e,t){const n=[];for(const o of xm(e,t)){const[e,...t]=o.points;if(e){n.push(`M ${e.x} ${e.y}`);for(const e of t)n.push(`L ${e.x} ${e.y}`);o.closed&&o.points.length>2&&n.push("Z")}}return n.length>0?n.join(" "):null}function gS(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(0,Math.min(1,e)):.5}function fS(e){return{id:"land.connector.interactions",editorEvent:{handleEvent(t,n){const o=Py(t),i=o.pointerSession;if("cancel"===n.type)return i?.cancel(n.reason),t.setHoveredShapeId(null),i?"handled":"continue";if(i){if("tick"===n.type){const e=t.inputs.state.get();if(i.preview.isDragging&&e.pointerId===i.pointerId&&e.currentScreenPoint){const o=$i(e.currentScreenPoint,t.viewportScreenSizeSignal.get(),n.elapsed);0===o.x&&0===o.y||(t.panCamera(o),i.update(e.currentScreenPoint,t.screenToPage(e.currentScreenPoint),e.accelKey))}return"handled"}return"pointer"!==n.type||n.pointerId!==i.pointerId||("pointer_move"===n.name?i.update(n.screenPoint,n.pagePoint,n.accelKey):"pointer_up"===n.name?i.complete(n.screenPoint,n.pagePoint,n.accelKey):"pointer_cancel"===n.name&&i.cancel("pointer_cancel")),"handled"}if("pointer"!==n.type)return"continue";if("pointer_move"===n.name&&"connector"===t.getActiveToolId())return t.setHoveredShapeId(((e,t)=>{const n=e.hitTestShape(t),o=n?e.getShapeUtil(n).getHoverTargetId(n,{editor:e}):null,i=o?e.getShape(o)??null:null;return i&&Jy(e,i,"source")?i:null})(t,n.pagePoint)?.id??null),"continue";if("pointer_down"!==n.name||0!==n.button||t.inputs.isSpacePressed.get()||t.getShapeEditingSession())return"continue";const r=t.getActiveToolId();let s=null;if("select"===r){const e=((e,t)=>{const n=Qy(e),o=Math.max(e.cameraZoomSignal.get(),1e-4),i=12/o;let r=null;for(const s of n.visibleShapes)if(n.sourceShapeIds.has(s.id))for(const n of Ci(e,s)){const e=Hy(n,t,o);e<=i+1e-6&&(!r||e<r.distance||e===r.distance&&`${s.index}:${s.id}:${n.id}`<`${r.shape.index}:${r.shape.id}:${r.port.id}`)&&(r={shape:s,port:n,distance:e})}return r?{shape:r.shape,port:r.port}:null})(t,n.pagePoint);e&&(s={kind:"port",clickBehavior:"quick-connect",start:vy(e.shape.id,e.port)})}else"connector"===r&&(s={kind:"canvas",clickBehavior:"cancel",start:mS(t,n)});if(!s)return"continue";const a=new T$(t,s,n.screenPoint,n.pointerId,e);return o.setPointerSession(a),"handled"}},selectionHandle:{createSession:(e,{handle:t,shape:n})=>qf(n)?"binding_terminal"===t.kind?((e,t,n)=>{if(!qf(e.getShape(t)))return null;const o=n.terminal,i="start"===o?"end":"start";let r=null;return{shapeId:t,historyMark:C$,shouldClearBindingPreviewOnExit:!0,onDragStart(){Py(e).setSelectionHandlesHidden(!0)},update({pagePoint:n,accelKey:s,source:a}){const d=Vf(e,t)[i],l=s?null:_y(e,n,{allowInteriorShapeId:d?.toId,mode:"target",pageId:d?e.getShapePageId(d.toId):e.getCurrentPageId()});if(l&&d&&Dy(l.shape.id,l.port.id,d.toId,d.props.portId))return{status:"continue",finalPagePoint:l?.port.pagePoint};const c=l,u=!!c&&(d&&"start"===o?Oy(e,c.shape.id,c.port.id,d.toId,d.props.portId,t):!!d&&Oy(e,d.toId,d.props.portId,c.shape.id,c.port.id,t));r=c&&!u?c:null;let p=Vf(e,t)[o];!r&&p&&(e.commands.deleteBinding(p.id,{source:a}),p=null);const h=e.getShape(t);if(!qf(h))return{status:"stop"};const g=d?e.getShape(d.toId):null,f=g&&d?Im(e,g,d.props):null,m=g&&f?ky(e,vy(g.id,f)):null,y=r?.port.pagePoint??(!l&&m?SS(e,m,n,h.props.routing,s):n),S=Ey(e,h,o,y);S&&((e,t,n)=>{const o=new Set(Gf(e,t.id).map(e=>e.id));e.commands.updateShapes([{id:t.id,parentId:t.parentId,x:t.x,y:t.y,rotation:t.rotation,skewX:t.skewX,scaleX:t.scaleX,scaleY:t.scaleY,props:t.props}],{source:n,suppressBindingIds:o})})(e,S,a),r&&(p=Vf(e,t)[o],p?p.toId===r.shape.id&&p.props.portId===r.port.id||e.commands.updateBinding({id:p.id,toId:r.shape.id,props:vm(o,r.port)},{source:a}):e.commands.createBinding({type:"connector",fromId:t,toId:r.shape.id,props:vm(o,r.port)},{source:a}));const b=Vf(e,t)[i],x=b?e.getShape(b.toId):null,w=x&&b?Im(e,x,b.props):null;if(x&&w){const n=e.getShape(t);qf(n)&&((e,t,n,o,i,r,s)=>{const a=e.getShape(t.id),d=qf(a)?a:t,l=e.computeShapeLocalToPageTransform(d),c=vy(o,i),u=r?vy(r.shape.id,r.port):{kind:"free",pagePoint:s.clone()},p=ky(e,c),h=ky(e,u);if(!p||!h)return void Py(e).setPreview(null);const g="start"===n?h:p,f="end"===n?h:p;Py(e).setPreview({kind:"rebind",start:yS(g,f,"start"),end:yS(f,g,"end"),isDragging:!0,movingTerminal:n,geometry:PS(d.props,l,{curveWaypoints:d.props.curveWaypoints.map(e=>l.applyToPoint(new $C(e.x,e.y))),orthogonalBends:d.props.orthogonalBends.map(e=>l.applyToPoint(new $C(e.x,e.y)))})})})(e,n,o,x.id,w,r,y)}else Py(e).setPreview(null);return{status:"continue",finalPagePoint:y}},onCancel(){const t=Py(e);t.setPreview(null),t.setSelectionHandlesHidden(!1)},onComplete(){const t=Py(e);t.setPreview(null),t.setSelectionHandlesHidden(!1)}}})(e,n.id,t):"custom"===t.kind?((e,t,n)=>{const o=Um(e,t);if("connector.curve-waypoint"===n.type&&"curved"===t.props.routing){const i=wy(n.id,"waypoint"),r=o.routePoints.slice(1,-1).map(e=>e.clone());return null!==i&&r[i]?xS(e,t.id,(n,o)=>{const s=r.map(e=>e.clone());s[i]=n.clone(),wS(e,t.id,"curveWaypoints",s,o)},n=>{wS(e,t.id,"curveWaypoints",r.filter((e,t)=>t!==i),n)}):null}if("connector.curve-insert"===n.type&&"curved"===t.props.routing){const i=wy(n.id,"segment"),r=o.routePoints.slice(1,-1).map(e=>e.clone());return null===i||i>r.length?null:xS(e,t.id,(n,o)=>{const s=r.map(e=>e.clone());s.splice(i,0,n.clone()),wS(e,t.id,"curveWaypoints",s,o)})}if("connector.orthogonal-segment"===n.type&&"orthogonal"===t.props.routing){const i=Iy(n.id);if(!i||!o.routePoints[i.index+1])return null;const r=o.routePoints.map(e=>e.clone()),s=e.computeShapeLocalToPageTransform(t),a=t.props.orthogonalBends.map(e=>s.applyToPoint(new $C(e.x,e.y)));return xS(e,t.id,(n,o)=>{const s=((e,t,n,o,i)=>{const r=e[t];if(!r)return o;const s="horizontal"===n?o.y:o.x,a=["horizontal"===n?r.y:r.x],d=e[t-1];t>=2&&d&&a.push("horizontal"===n?d.y:d.x);const l=e[t+2];t<=e.length-4&&l&&a.push("horizontal"===n?l.y:l.x);const c=a.reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e);return Math.abs(c-s)>i?o:"horizontal"===n?new $C(o.x,c):new $C(c,o.y)})(r,i.index,i.axis,n,8/Math.max(e.cameraZoomSignal.get(),1e-4)),d=r[i.index],l=("horizontal"===i.axis?s.y===d.y:s.x===d.x)?a:fy(((e,t,n,o)=>{const i=e[t],r=e[t+1];if(!i||!r)return e.map(e=>e.clone());if(("horizontal"===n?o.y:o.x)===("horizontal"===n?i.y:i.x))return e.map(e=>e.clone());const s=e=>"horizontal"===n?new $C(e.x,o.y):new $C(o.x,e.y),a=e.length-2;if(0===t){const t=IS(i,r);return[i.clone(),t,s(t),s(r),...e.slice(2).map(e=>e.clone())]}if(t===a){const t=IS(r,i);return[...e.slice(0,-2).map(e=>e.clone()),s(i),s(t),t,r.clone()]}const d=e.map(e=>e.clone());return d[t]=s(i),d[t+1]=s(r),d})(r,i.index,i.axis,s)).slice(1,-1);wS(e,t.id,"orthogonalBends",l,o)})}return null})(e,n,t):null:null}}}function mS(e,t){if(t.accelKey)return{kind:"free",pagePoint:t.pagePoint.clone()};const n=_y(e,t.pagePoint,{mode:"target",pageId:e.getCurrentPageId()})??_y(e,t.pagePoint,{pageId:e.getCurrentPageId()});return!n||e.isShapeOrAncestorLocked(n.shape.id)?{kind:"free",pagePoint:t.pagePoint.clone()}:vy(n.shape.id,n.port)}function yS(e,t,n){const o=Ly(e,t,n);return{draft:e.draft,pagePoint:e.pagePoint.clone(),pageOutwardNormal:o.outwardNormal.clone(),shapeId:e.shape?.id??null,portId:e.port?.id??null,obstacleBounds:e.obstacleBounds}}function SS(e,t,n,o,i){if("orthogonal"!==o||i||!t.port)return n.clone();const r=t.port.pageOutwardNormal,s=n.sub(t.pagePoint);if(s.x*r.x+s.y*r.y<=0)return n.clone();const a=Math.abs(r.x)>=Math.abs(r.y),d=a?s.y:s.x,l=8/Math.max(e.cameraZoomSignal.get(),1e-4);return Math.abs(d)>l?n.clone():a?new $C(n.x,t.pagePoint.y):new $C(t.pagePoint.x,n.y)}function bS(e,t,n){const o=Uy(e,t,n);if(!o?.startsWith("shape:"))return FC.Identity();const i=e.getShape(o);return i?e.computeShapeLocalToPageTransform(i):FC.Identity()}function xS(e,t,n,o){const i={shapeId:t,historyMark:"connector.adjust",onDragStart(){Py(e).setSelectionHandlesHidden(!0)},update:({pagePoint:e,source:t})=>(n(e,t),{status:"continue",finalPagePoint:e}),onCancel(){Py(e).setSelectionHandlesHidden(!1)},onComplete(){Py(e).setSelectionHandlesHidden(!1)}};return o&&(i.onDoubleClick=({source:e})=>o(e)),i}function wS(e,t,n,o,i){const r=e.getShape(t);if(!qf(r))return;const s=e.computeShapeLocalToPageTransform(r).tryInvert();if(!s)return;const a={...r.props,[n]:o.map(e=>{const t=s.applyToPoint(e);return{x:t.x,y:t.y}})},d=My(e,{...r,props:a});if(!d)return;const l=Vf(e,r.id),c=new Set([l.start?.id,l.end?.id].filter(e=>!!e));e.commands.updateShapes([{id:r.id,parentId:d.parentId,x:d.x,y:d.y,rotation:d.rotation,skewX:d.skewX,scaleX:d.scaleX,scaleY:d.scaleY,props:d.props}],{source:i,suppressBindingIds:c})}function IS(e,t){const n=t.sub(e),o=n.len();return 0===o?e.clone():e.add(n.mul(Math.min(24,o/2)/o))}function PS(e,t,n={curveWaypoints:[],orthogonalBends:[]}){return{routing:e.routing,cornerRadius:e.cornerRadius,headStart:e.headStart,headEnd:e.headEnd,stroke:e.stroke,strokeWidth:e.strokeWidth,strokeStyle:e.strokeStyle,...n,localToPageTransform:t}}function vS(e,t,n=-1/0){return"number"==typeof e&&Number.isFinite(e)?Math.max(n,e):t}function kS(e,t){const n=e&&"object"==typeof e?e:{};return{x:vS(n.x,t.x),y:vS(n.y,t.y)}}function CS(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e;return"number"==typeof t.x&&Number.isFinite(t.x)&&"number"==typeof t.y&&Number.isFinite(t.y)?[{x:t.x,y:t.y}]:[]}):[]}function TS(e,t,n){const o=t.sub(e).normalize();return{point:e,outwardNormal:o.len()>0?o:new $C("start"===n?1:-1,0)}}function MS(e,t){const n=Math.max(e.cameraZoomSignal.get(),1e-4),o=e.computeShapePositionedToPageTransform(t).getMaximumLinearScale();return Math.max(12/n,t.props.strokeWidth*o/2)}function ES(e,t){let n=1/0;for(let o=1;o<e.length;o+=1)n=Math.min(n,BS(t,e[o-1],e[o]));return n}function BS(e,t,n){const o=n.sub(t),i=o.len2();if(0===i)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/i));return e.dist(t.add(o.mul(s)))}function AS(e,t,n,o){return Math.min(BS(e,n,o),BS(t,n,o),BS(n,e,t),BS(o,e,t))}function RS(e,t,n,o){return{tag:"marker",attrs:{markerWidth:12,markerHeight:12,viewBox:"0 0 24 24",refX:Am(e,n,o),refY:12,orient:"auto",markerUnits:"strokeWidth"},children:[{tag:"path",attrs:{d:Rm(e,n,o),fill:"none",stroke:t,"stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}}]}}function $S(e){const t=["routing","stroke","strokeWidth","strokeStyle"];e.actions.add(...t.map(FS),{id:"connector.set-direction",getAvailability:e=>"connector"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:e=>(e=>{let t;for(const n of e){if("connector"!==n.type)continue;const e=n.props,o=zS(e.headStart,e.headEnd);if(void 0===t)t=o;else if(t!==o)return null}return t??null})(e.selection.selectedShapes),run({context:e,value:t}){const n=US(t);if(!n)return;const o=e.selection.selectedShapes.filter(e=>"connector"===e.type).filter(e=>!e.isLocked).map(e=>({id:e.id,props:n}));o.length>0&&e.editor.commands.updateShapes(o,{source:"user"})}},...t.map(OS),{id:"connector.default-direction",getAvailability:e=>"connector"===e.tool.activeToolId?"enabled":"inapplicable",getValue(e){const t=e.editor.getDefaultShapeProps("connector");return zS(t.headStart,t.headEnd)},run({context:e,value:t}){const n=US(t);n&&e.editor.updateDefaultShapeProps("connector",n)}}),e.toolbar.add({id:"connector.tool-toolbar",channel:gM.toolSwitcher,order:35,actionIds:[pM],getGroups:()=>[{id:"connector.tools",items:[{kind:"button",id:"connector.tool.connector",actionId:pM,value:"connector",label:"Connector",icon:"arrow-right",dataUi:"connector-tool-button"}]}]},{id:"connector.default-style.tool-toolbar",channel:gM.toolOptions,order:36,actionIds:U$,subscribe:(e,t)=>Zi("connector.defaultStyleToolbar",e.shapeDefaultPropsByTypeSignal,t,{fireImmediately:!1}),when:e=>"connector"===e.tool.activeToolId,getGroups:()=>LS("connector.default","connector-default")},{id:"connector.selection-toolbar",channel:gM.selectionProperties,order:20,actionIds:z$,when:e=>"connector"===e.selection.commonShapeType,getGroups:()=>LS("connector.set","connector")},{id:"connector.floating-selection-toolbar",channel:gM.selectionQuickActions,order:20,actionIds:z$,when:e=>"connector"===e.selection.commonShapeType,getGroups:()=>LS("connector.set","connector-floating")})}function LS(e,t){return[{id:`${t}.routing`,items:[{kind:"segmented",id:`${t}.routing`,actionId:`${e}-routing`,options:F$.map(e=>({...e,dataUi:`${t}-routing-${e.value}-button`}))}]},{id:`${t}.stroke`,items:[{kind:"color-input",id:`${t}.stroke`,actionId:`${e}-stroke`,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:L$.map(e=>({...e,dataUi:`${t}-stroke-${e.id}-button`})),dataUi:`${t}.stroke`}]},{id:`${t}.stroke-width`,items:[{kind:"text-input",id:`${t}.stroke-width`,actionId:`${e}-strokeWidth`,label:"Stroke width",placeholder:"2",suffix:"Px",validate:WS,dataUi:`${t}-stroke-width-control`}]},{id:`${t}.stroke-style`,presentation:"overflow",items:[{kind:"segmented",id:`${t}.stroke-style`,actionId:`${e}-strokeStyle`,options:O$.map(e=>({...e,dataUi:`${t}-stroke-style-${e.value}-button`}))}]},{id:`${t}.direction`,items:[{kind:"segmented",id:`${t}.direction`,actionId:`${e}-direction`,options:D$.map(e=>({...e,label:`Arrow direction: ${e.label}`,dataUi:`${t}-direction-${e.value}-button`}))}]}]}function FS(e){return{id:`connector.set-${e}`,getAvailability:e=>"connector"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const o of e){if("connector"!==o.type)continue;const e=o.props[t];if(void 0===n)n=e;else if("stroke"===t?!U(n,e):n!==e)return null}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const o=DS(e,n);if(void 0===o)return;const i=t.selection.selectedShapes.filter(e=>"connector"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:o}}));i.length>0&&t.editor.commands.updateShapes(i,{source:"user"})}}}function OS(e){return{id:`connector.default-${e}`,getAvailability:e=>"connector"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("connector")[e],run({context:t,value:n}){const o=DS(e,n);void 0!==o&&t.editor.updateDefaultShapeProps("connector",{[e]:o})}}}function DS(e,t){return"stroke"===e?$(t)?F(t,E("stroke-slate")):void 0:"strokeWidth"===e?NS(t):"routing"===e?F$.some(e=>e.value===t)?t:void 0:"strokeStyle"===e&&O$.some(e=>e.value===t)?t:void 0}function zS(e,t){return"arrow"===e&&"arrow"===t?"both":"arrow"===e?"start":"arrow"===t?"end":"none"}function US(e){if(!D$.some(t=>t.value===e))return null;switch(e){case"both":return{headStart:"arrow",headEnd:"arrow"};case"start":return{headStart:"arrow",headEnd:"none"};case"end":return{headStart:"none",headEnd:"arrow"};case"none":return{headStart:"none",headEnd:"none"}}}function NS(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function WS(e){return void 0!==NS(e)}function XS(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function YS(e,t,n){return Math.max(t,Math.min(n,e))}function HS(e){return e?640:480}function _S(e,t){return e.x===t.x&&e.y===t.y&&e.pressure===t.pressure&&e.segment===t.segment}function KS(e){return new $C(e.x,e.y)}function qS(e){return{x:e.x,y:e.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}}function jS(e){const t=[];for(const n of e)t.push(...n.points.map(qS));return t}function VS(e){if(void 0!==e&&Number.isFinite(e))return YS(e,.05,1)}function GS(e,t){const n=[];for(let o=1;o<e.length-1;o+=1){if(t&&ZS(e,o))continue;const i=e[o],r=e[o-1],s=e[o+1];i&&r&&s&&n.push({index:o,score:QS(i,r,s)})}return n.sort((e,t)=>e.score-t.score||e.index-t.index),n}function ZS(e,t){return"straight"===e[t]?.segment||"straight"===e[t+1]?.segment}function QS(e,t,n){const o=((e,t,n)=>{const o=n.x-t.x,i=n.y-t.y,r=o*o+i*i;if(0===r){const n=e.x-t.x,o=e.y-t.y;return n*n+o*o}const s=YS(((e.x-t.x)*o+(e.y-t.y)*i)/r,0,1),a=e.x-(t.x+o*s),d=e.y-(t.y+i*s);return a*a+d*d})(e,t,n),i=((e,t,n)=>{if(void 0===e.pressure)return 0;return 8*Math.abs(e.pressure-((t.pressure??e.pressure)+(n.pressure??e.pressure))/2)})(e,t,n);return o+i*i}function JS(e){if(0===e.length)return null;if(1===e.length){const t=e[0];return`M ${XS(t.x)} ${XS(t.y)}`}if(2===e.length){const t=e[0],n=e[1];return[`M ${XS(t.x)} ${XS(t.y)}`,`L ${XS(n.x)} ${XS(n.y)}`].join(" ")}const t=[],n=e[0];t.push(`M ${XS(n.x)} ${XS(n.y)}`);for(let o=1;o<e.length;o+=1){const n=e[o];if(!n)continue;if("straight"===n.segment){t.push(`L ${XS(n.x)} ${XS(n.y)}`);continue}const i=e[o+1];if(!i||"straight"===i.segment){if(eb(e,o)){const i=e[o-1];t.push(`Q ${XS(i.x)} ${XS(i.y)} ${XS(n.x)} ${XS(n.y)}`)}else t.push(`L ${XS(n.x)} ${XS(n.y)}`);continue}const r=$C.Med(KS(n),KS(i));t.push(`Q ${XS(n.x)} ${XS(n.y)} ${XS(r.x)} ${XS(r.y)}`)}return t.join(" ")}function eb(e,t){return t>=2&&"straight"!==e[t-1]?.segment&&"straight"!==e[t-2]?.segment}function tb(e){if(e.length<3)return(e=>{if(0===e.length)return null;const[t,...n]=e;return t?[`M ${XS(t.x)} ${XS(t.y)}`,...n.map(e=>`L ${XS(e.x)} ${XS(e.y)}`),"Z"].join(" "):null})(e);const t=e[0],n=e[e.length-1];if(!t||!n)return null;const o=$C.Med(n,t),i=[`M ${XS(o.x)} ${XS(o.y)}`];for(let r=0;r<e.length;r+=1){const t=e[r],n=e[(r+1)%e.length];if(!t||!n)continue;const o=$C.Med(t,n);i.push(`Q ${XS(t.x)} ${XS(t.y)} ${XS(o.x)} ${XS(o.y)}`)}return i.push("Z"),i.join(" ")}function nb(e){return e.map(qS)}function ob(e){return e.map(ib)}function ib(e){return(e=>({points:e.points.map(qS)}))(e)}function rb(e,t,n){return e.map(e=>({x:e.x+t,y:e.y+n,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}))}function sb(e,t,n){return e.map(e=>({points:rb(e.points,t,n)}))}function ab(e,t){return e.map((e,n)=>({points:e.points.map((e,o)=>{const i=t(KS(e),n,o);return{x:i.x,y:i.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}})}))}function db(e,t,n){const o=0===t.w?1:t.w,i=0===t.h?1:t.h,r=0===n.w?1:n.w,s=0===n.h?1:n.h;return e.map(e=>({x:n.minX+(e.x-t.minX)/o*r,y:n.minY+(e.y-t.minY)/i*s,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}))}function lb(e,t,n){return e.map(e=>({points:db(e.points,t,n)}))}function cb(e){return{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}}function ub(e,t){const n=cb(t);return ab(e,e=>yo(e,n))}function pb(e,t){const n=cb(t);return ab(e,e=>So(e,n))}function hb(e,t){return ab(e,e=>Io({axis:t.axis,bounds:t.selectionMirrorBounds,point:e}))}function gb(e,t,n){return Math.max(t,Math.min(n,e))}function fb(e,t,n){return e+(t-e)*n}function mb(e,t,n){if(e.length<=1)return new $C(1,0);if(n&&e.length>=3){const n=e[t],o=e[(t+1)%e.length],i=n.sub(e[(t-1+e.length)%e.length]).normalize(),r=o.sub(n).normalize(),s=i.add(r);return s.len2()>1e-6?s.normalize():r.len2()>0?r:i.len2()>0?i:new $C(1,0)}const o=e[t],i=e[t+1]??o,r=o.sub(e[t-1]??o).normalize(),s=i.sub(o).normalize();if(0===t)return s.len2()>0?s:new $C(1,0);if(t===e.length-1)return r.len2()>0?r:new $C(1,0);const a=r.add(s);return a.len2()>1e-6?a.normalize():s.len2()>0?s:r.len2()>0?r:new $C(1,0)}function yb(e,t){return e.x*t.x+e.y*t.y}function Sb(e,t,n,o,i={}){if(0===e.length)return[];const r=((e,t)=>{const n=Math.max(e+1,1.6);return{baseRadius:n,minRadius:Math.max(.6,.32*n),minRadiusScale:t?.5:.48,maxRadiusScale:t?1.22:1.24,startTaper:Math.max(1.8*e,2.5),endTaper:Math.max(2.3*e,3.5),simulatePressure:!t}})(t,n),s=e.map(KS),a=[0];let d=0;for(let u=1;u<s.length;u+=1)d+=s[u].dist(s[u-1]),a.push(d);let l=null;const c=e.map((e,n)=>{const c=a[n]??0,u=0===n?0:s[n].dist(s[n-1]),p=function(e,t,n,o,i,r,s,a){if(n.simulatePressure)return(({distanceFromPrevious:e,previousPressure:t,runningLength:n,totalLength:o,strokeWidth:i,isClosed:r})=>{const s=gb(e/Math.max(1.5*i,1),0,1),a=gb(1-s,W$,1),d=null===t?fb(.5,a,.275):fb(t,a,.275*Math.max(s,.36));if(r)return gb(d,W$,1);const l=gb(n/Math.max(1.8*i,1),0,1),c=gb((o-n)/Math.max(2.6*i,1),0,1);return gb(d*fb(.72,1,Math.min(l,c)),W$,1)})({distanceFromPrevious:i,previousPressure:t,runningLength:r,totalLength:s,strokeWidth:o,isClosed:a});const d="number"==typeof e.pressure&&Number.isFinite(e.pressure)?gb(e.pressure,.05,1):t??.55;return null===t?d:fb(t,d,.68)}(e,l,r,t,u,c,d,o);l=p;const h=i.taperEnd??!0,g=o||s.length<=1?1:Math.min(i.taperStart??1?gb(c/r.startTaper,0,1):1,h?gb((d-c)/r.endTaper,0,1):1),f=fb(r.minRadiusScale,r.maxRadiusScale,p),m=Math.max(r.minRadius,r.baseRadius*f*fb(.7,1,g));return{point:s[n],direction:mb(s,n,o),pressure:p,radius:m,runningLength:c}});return d<.5*r.baseRadius?c.map(e=>({...e,radius:Math.max(e.radius,.92*r.baseRadius)})):c}function bb(e,t){const n=e[e.length-1];n&&n.dist2(t)<.04?e[e.length-1]=t:e.push(t)}function xb(e,t,n){const o=e.dist(t);if(0===o)return[];const i=$C.Angle(e,t),r=[];for(let s=1;s<n;s+=1){const t=i-Math.PI*(s/n);r.push(new $C(e.x+Math.cos(t)*o,e.y+Math.sin(t)*o))}return r}function wb(e,t,n,o={}){const i=e[e.length-1];(!i||!0===o.force||i.dist2(t)>n)&&bb(e,t)}function Ib(e){return{...e}}function Pb(e,t,n){return e.map(e=>new $C(e.x+t,e.y+n))}function vb(e,t,n){return e.map(e=>Pb(e,t,n))}function kb({segments:e,outlineVertices:t,outlinePolygons:n,strokeWidth:o,sampling:i,isClosed:r}){const s=jS(e),a=s.map(KS),d=a.length>0?LC.FromPoints(a):new LC(0,0,1,1),l=t.length>0?LC.FromPoints([...t]):d.expand(Math.max(o/2,1)),c=r&&s.length>=3?(e=>{if(e.length<3)return null;const t=JS(e);return t?`${t} Z`:null})(s):null,u=void 0!==n?(e=>{const t=e.map(e=>tb(e)).filter(e=>null!==e);return t.length>0?t.join(" "):null})(n):tb(t);return{normalizedSegments:ob(e),normalizedPoints:nb(s),pointBounds:d,path:u,selectionPath:c??JS(s),fillPath:c,localBounds:l,renderBounds:l.clone(),outlineVertices:t.map(e=>e.clone()),outlinePolygons:n?n.map(e=>e.map(e=>e.clone())):[t.map(e=>e.clone())],sampling:Ib(i)}}function Cb(e,t,n,o){const i=(({strokeWidth:e,isPen:t})=>[e,t?"pen":"pointer"].join(":"))({strokeWidth:n,isPen:o}),r=X$.get(e),s=r?.get(i);if(s)return{normalizedSegment:ib(s.normalizedSegment),sampling:Ib(s.sampling)};const a=((e,t)=>{if(e.length<=1)return{points:e.map(qS),rawPointCount:e.length,sampledPointCount:e.length,maxPointCount:t.maxPointCount,reduced:!1,capped:!1};const n=[qS(e[0])],o=t.minPointDistance*t.minPointDistance;let i=KS(e[0]),r=VS(e[0].pressure);for(let d=1;d<e.length;d+=1){const s=e[d];if(!s)continue;const a=KS(s),l=VS(s.pressure),c=d===e.length-1,u="straight"===s.segment,p=c||u?a:$C.Lrp(i,a,t.positionBlend),h=u?l:void 0===l?void 0:void 0===r?l:r+(l-r)*t.pressureBlend;i=p,r=h;const g=void 0===h?{x:p.x,y:p.y,...void 0===s.segment?null:{segment:s.segment}}:{x:p.x,y:p.y,pressure:h,...void 0===s.segment?null:{segment:s.segment}},f=n[n.length-1];if(!f){n.push(g);continue}const m=g.x-f.x,y=g.y-f.y,S=Math.abs((g.pressure??0)-(f.pressure??0));if(m*m+y*y<o){if(u){if(_S(f,g))continue;n.push(g);continue}(S>.08||c)&&(n[n.length-1]=g)}else n.push(g)}const s=n.length>t.maxPointCount,a=function(e,t){const n=Math.max(2,Math.floor(t));if(e.length<=n)return e.map(qS);const o=((e,t)=>{let n=GS(e,!0);return n.length<t&&(n=GS(e,!1)),new Set(n.slice(0,t).map(e=>e.index))})(e,e.length-n);return e.filter((e,t)=>!o.has(t)).map(qS)}(n,t.maxPointCount);return{points:a,rawPointCount:e.length,sampledPointCount:a.length,maxPointCount:t.maxPointCount,reduced:a.length<e.length,capped:s}})(e.points,t),d={normalizedSegment:{points:nb(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},l=r??new Map;return l.set(i,{normalizedSegment:ib(d.normalizedSegment),sampling:Ib(d.sampling)}),r||X$.set(e,l),d}function Tb(e,t,n=!1,o=!1){const i=((e,t)=>({minPointDistance:t?Math.max(.35,.18*e):Math.max(.55,.28*e),positionBlend:t?.68:.66,pressureBlend:t?.68:.45,maxPointCount:HS(t)}))(t,n),r=[],s=[],a=e.filter(e=>e.points.length>0);for(let p=0;p<a.length;p+=1){const e=Cb(a[p],i,t,n);r.push(ib(e.normalizedSegment)),s.push(Ib(e.sampling))}const d=function(e,t,n={}){if(0===e.length)return[];if(1===e.length)return((e,t)=>{const n=[];for(let o=0;o<16;o+=1){const i=2*Math.PI*o/16;n.push(new $C(e.x+Math.cos(i)*t,e.y+Math.sin(i)*t))}return n})(e[0].point,e[0].radius);const o=[],i=[];let r=.12;for(const l of e)r=Math.max(r,.38*l.radius);const s=r**2;let a=null;for(let l=0;l<e.length;l+=1){const t=e[l],n=t.direction,r=(e[l+1]??t).direction,d=yb(n,r);let c=0===l||l===e.length-1?n.per().normalize():$C.Lrp(r,n,d).per().normalize();c.len2()<1e-6&&(c=a??new $C(0,1)),a=c,wb(o,t.point.add(c.mul(t.radius)),s,{force:l===e.length-1}),wb(i,t.point.sub(c.mul(t.radius)),s,{force:l===e.length-1})}if(t&&e.length>=3){const e=[];for(const t of o)bb(e,t);for(let t=i.length-1;t>=0;t-=1)bb(e,i[t]);return e}const d=[];for(const l of o)bb(d,l);if(n.capEnd??1){const t=e[e.length-1];for(const e of xb(t.point,o[o.length-1],8))bb(d,e)}for(let l=i.length-1;l>=0;l-=1)bb(d,i[l]);if(n.capStart??1){const t=e[0];for(const e of xb(t.point,i[0],8))bb(d,e)}return d}(Sb(jS(r),t,n,o),o),l=(u=i.maxPointCount,{rawPointCount:(c=s).reduce((e,t)=>e+t.rawPointCount,0),sampledPointCount:c.reduce((e,t)=>e+t.sampledPointCount,0),sampledPointLimit:u,reduced:c.some(e=>e.reduced),capped:c.some(e=>e.capped)});var c,u;return kb({segments:r,outlineVertices:d,outlinePolygons:d.length>0?[d]:[],strokeWidth:t,sampling:l,isClosed:o})}function Mb(e){return e.segments}function Eb(e,t,n){return((e,t)=>{const n=Math.max(0,e.w-t.left-t.right),o=Math.max(0,e.h-t.top-t.bottom);return new LC(e.x+t.left,e.y+t.top,n,o)})(n,{left:e.minX-t.minX,right:t.maxX-e.maxX,top:e.minY-t.minY,bottom:t.maxY-e.maxY})}function Bb(e){const t=e,n=Y$.get(t);if(n)return n;const o=Tb(Mb(e.props),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed);return Y$.set(t,o),o}function Ab(e,t,n=!1,o=!1){return((e,t,n=!1,o=!1)=>{const i=Tb(e,t,n,o),r=i.pointBounds,s=Tb(ab(i.normalizedSegments,e=>new $C(e.x-r.x,e.y-r.y)),t,n,o);return{x:r.x,y:r.y,segments:s.normalizedSegments,pointBounds:s.pointBounds,localBounds:s.localBounds,renderBounds:s.renderBounds,path:s.path,selectionPath:s.selectionPath,fillPath:s.fillPath,outlineVertices:s.outlineVertices,outlinePolygons:s.outlinePolygons,sampling:s.sampling}})(e,t,n,o)}function Rb(e){const t=e,n=H$.get(t);if(n)return n;const o=((e,t,n,o,i)=>kb({segments:sb(e.normalizedSegments,n,o),outlineVertices:Pb(e.outlineVertices,n,o),outlinePolygons:vb(e.outlinePolygons,n,o),strokeWidth:t,sampling:e.sampling,isClosed:i}))(Bb(e),e.props.strokeWidth,e.x,e.y,e.props.isClosed);return H$.set(t,o),o}function $b(e){const t=((e,t)=>new $C(e.x+t.localBounds.center.x,e.y+t.localBounds.center.y))(e,Bb(e));return ab((e=>sb(Mb(e.props),e.x,e.y))(e),n=>((e,t,n)=>{if(0===e.rotation&&0===e.skewX&&1===e.scaleX&&1===e.scaleY)return t;const o=t.sub(n),i=new $C(o.x*e.scaleX,o.y*e.scaleY);return n.add(new $C(i.x+Math.tan(e.skewX)*i.y,i.y).rot(e.rotation))})(e,n,t))}function Lb(e){return ob(e)}function Fb(e,t,n,o){return{x:e.x-t.x,y:e.y-t.y,...o&&n>0?{pressure:n}:null}}function Ob(e){return{x:e.x,y:e.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}}function Db(e){const t=zb(e.segments),n=t[t.length-1];return n?n.points.map(Ob):[]}function zb(e){return e.length>0?[...e]:[{points:[]}]}function Ub(e){return{segments:Lb(zb(e))}}function Nb(e,t,n){const o=n.sub(t),i=o.len2();if(0===i)return e.dist(t);const r=Math.max(0,Math.min(1,((e.x-t.x)*o.x+(e.y-t.y)*o.y)/i)),s=new $C(t.x+o.x*r,t.y+o.y*r);return e.dist(s)}function Wb(e,t,n,o){return((e,t,n,o)=>{const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d>=0&&d<=1&&l>=0&&l<=1})(e,t,n,o)?0:Math.min(Nb(e,n,o),Nb(t,n,o),Nb(n,e,t),Nb(o,e,t))}function Xb(e,t){let n=!1;for(let o=0,i=t.length-1;o<t.length;i=o,o+=1){const r=t[o],s=t[i];r&&s&&r.y>e.y!=s.y>e.y&&e.x<(s.x-r.x)*(e.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n}function Yb(e,t){if(0===t.length)return Number.POSITIVE_INFINITY;let n=Number.POSITIVE_INFINITY;for(let o=0;o<t.length;o+=1){const i=t[o],r=t[(o+1)%t.length];i&&r&&(n=Math.min(n,Nb(e,i,r)))}return n}function Hb(e,t,n,o){if(0===n.length)return!1;if(Xb(e,n)||Xb(t,n))return!0;for(let i=0;i<n.length;i+=1){const r=n[i],s=n[(i+1)%n.length];if(r&&s&&Wb(e,t,r,s)<=o)return!0}return!1}function _b(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Kb(e){if(!e||"object"!=typeof e)return null;const t=e,n=_b(t.x,NaN),o=_b(t.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(o))return null;const i=_b(t.pressure,NaN);return t.x!==n||t.y!==o||void 0!==t.pressure&&t.pressure!==i||void 0!==t.segment&&"straight"!==t.segment?{x:n,y:o,...Number.isFinite(i)?{pressure:i}:null,..."straight"===t.segment?{segment:"straight"}:null}:e}function qb(e){if(!e||"object"!=typeof e)return null;const t=e,n=((e,t)=>{if(!Array.isArray(e))return t;let n=!1;const o=[];for(const i of e){const e=Kb(i);e?(n=n||e!==i,o.push(e)):n=!0}return 0===o.length?t:n?o:e})(t.points,[]);return 0===n.length?null:n===t.points?e:{points:n}}function jb(e,t){if(!Array.isArray(e))return t;let n=!1;const o=[];for(const i of e){const e=qb(i);e?(n=n||e!==i,o.push(e)):n=!0}return 0===o.length?t:n?o:e}function Vb(e){return f(e)&&"draw"===e.type}function Gb(e){return{id:`draw.set-${e}`,getAvailability:e=>"draw"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const o of e){if("draw"!==o.type)continue;const e=o.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!U(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const o=ex(e,n);if(void 0===o)return;const i=t.selection.selectedShapes.filter(Vb).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:o}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function Zb(e){return{id:`draw.default-${e}`,getAvailability:e=>"draw"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("draw")[e],run({context:t,value:n}){const o=ex(e,n);void 0!==o&&t.editor.updateDefaultShapeProps("draw",{[e]:o})}}}function Qb(e){let t;for(const n of e){if("draw"!==n.type)continue;const e=n.props.isClosed;if(void 0!==t){if(t!==e)return null}else t=e}return void 0===t?null:t?"closed":"open"}function Jb(e){return"closed"===e||"open"!==e&&null}function ex(e,t){return"strokeWidth"===e?tx(t):$(t)?F(t,"fill"===e?B("transparent"):E("stroke-slate")):void 0}function tx(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function nx(e){return void 0!==tx(e)}function ox({shape:e,stroke:t=e.props.stroke,strokeWidth:n=e.props.strokeWidth}){const{fillPath:o,renderBounds:i,path:r,selectionPath:s}=Bb({props:{...e.props,strokeWidth:n}});if(!r&&!s)return null;const a=O(t);
|
|
49
|
+
return Zk("svg",{width:"100%",height:"100%",viewBox:`${i.x} ${i.y} ${Math.max(i.w,1)} ${Math.max(i.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[o&&!z(e.props.fill)?Gk("path",{d:o,fill:O(e.props.fill),stroke:"none"}):null,e.props.isClosed&&s?Gk("path",{d:s,fill:"none",stroke:a,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}):r?Gk("path",{d:r,fill:a,stroke:"none"}):null]})}function ix({shape:e,strokeWidth:t}){const{path:n,renderBounds:o,selectionPath:i}=Bb(e),r=i??n;return r?Gk("svg",{"data-ui":"draw-hover-outline",width:"100%",height:"100%",viewBox:`${o.x} ${o.y} ${Math.max(o.w,1)} ${Math.max(o.h,1)}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Gk("path",{d:r,fill:"none",stroke:xM,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function rx(e){return e.runtime.require(Q$)}function sx(e){return 4/e.getCurrentCamera().z}function ax(e,t,n,o){const i=[new $C(t.minX,t.minY),new $C(t.maxX,t.minY),new $C(t.maxX,t.maxY),new $C(t.minX,t.maxY)].map(e=>n.applyToPoint(e));let r=0,s=Number.POSITIVE_INFINITY;for(let a=0;a<i.length;a+=1){const t=i[a],n=i[(a+1)%i.length].sub(t),o=e.sub(t),d=n.x*o.y-n.y*o.x;if(Math.abs(d)<=1e-8)return!1;const l=Math.sign(d);if(0===r)r=l;else if(l!==r)return!1;const c=n.len2(),u=0===c?0:Math.max(0,Math.min(1,(o.x*n.x+o.y*n.y)/c));s=Math.min(s,e.dist(t.add(n.mul(u))))}return s>o}function dx(e,t){const n=new Set,o=sx(e);for(const i of e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget"})){const r=e.getShapeUtil(i);if(!r.canReceiveChildren(i))continue;const s=r.getChildClipLocalBounds(i);s&&ax(t,s,e.computeShapeLocalToPageTransform(i),o)&&n.add(i.id)}return n}function lx(e,t,n){return n.protectedContainerIds.has(t.id)||e.isShapeOrAncestorLocked(t.id)||e.getShapeUtil(t).canReceiveChildren(t)&&e.hasLockedDescendant(t.id)?null:t.id}function cx(e,t,n,o){const i=o.topMostOnly?n.slice(0,1):n;for(const r of i){const n=lx(e,r,t);n&&t.erasingShapeIds.add(n)}}function ux(e,t,n){cx(e,t,e.hitTestShapesAtPoint(n.pagePoint),{topMostOnly:n.accelKey})}function px(e,t,n){cx(e,t,e.hitTestShapesByLineSegment(t.previousPagePoint,n.pagePoint,{margin:sx(e)}),{topMostOnly:n.accelKey})}function hx(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function gx(e,t){rx(e).setPreview(Array.from(t.erasingShapeIds),t.trail)}function fx(e){rx(e).clear()}function mx(e,t){const n=Array.from(t.erasingShapeIds);fx(e),0!==n.length&&e.commands.deleteShapes(n,{source:"user"})}function yx(){return"undefined"==typeof performance?Date.now():performance.now()}function Sx(e,t,n,o){const i=e.samples[e.samples.length-1];if(!i)return void e.samples.push({...t,time:o,velocity:0});const r=aL/n,s=Px(i,t);if(s<r)return void(e.samples[e.samples.length-1]={...i,...t,time:o});const a=s*n/Math.max(hL,o-i.time);e.samples.push({...t,time:o,velocity:Bx(i.velocity,a,.68)})}function bx(e,t){e.samples=xx(e.samples,t)}function xx(e,t){const n=e[e.length-1];if(!n)return[];const o=t-Ax(gL+n.velocity*fL,gL,mL);if(n.time<o)return[];const i=e.findIndex(e=>e.time>=o);if(-1===i)return[];const r=e.slice(i),s=e[i-1],a=r[0];return s&&a.time>o?[(d=s,l=a,c=Ax((o-s.time)/(a.time-s.time),0,1),{...Ex(d,l,c),time:Bx(d.time,l.time,c),velocity:Bx(d.velocity,l.velocity,c)}),...r]:r;var d,l,c}function wx(e,t){if(e.length<=1)return{x:1,y:0};const n=e[t-1]??e[t],o=e[t+1]??e[t];return(e=>{const t=Math.sqrt(e.x*e.x+e.y*e.y);return t<=0?{x:1,y:0}:{x:e.x/t,y:e.y/t}})(0===t?Tx(o,e[t]):Tx(t===e.length-1?e[t]:o,n))}function Ix(e,t,n){const o=[];for(let i=0;i<n;i++){const r=2*Math.PI*i/n;o.push({x:e.x+Math.cos(r)*t,y:e.y+Math.sin(r)*t})}return o}function Px(e,t){return Math.sqrt(vx(e,t))}function vx(e,t){const n=e.x-t.x,o=e.y-t.y;return n*n+o*o}function kx(e){return{x:-e.y,y:e.x}}function Cx(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Tx(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Mx(e,t){return{x:e.x*t,y:e.y*t}}function Ex(e,t,n){return{x:Bx(e.x,t.x,n),y:Bx(e.y,t.y,n)}}function Bx(e,t,n){return e+(t-e)*n}function Ax(e,t,n){return Math.max(t,Math.min(n,e))}function Rx(e,t){const n=e[e.length-1];!n||vx(n,t)>.04?e.push(t):e[e.length-1]=t}function $x(e){if(e.length<2)return null;if(2===e.length)return`M ${Fx(e[0])} L ${Fx(e[1])} Z`;const t=[`M ${Fx(Lx(e[0],e[1]))}`];for(let n=1;n<e.length;n++){const o=e[n],i=e[(n+1)%e.length];t.push(`Q ${Fx(o)} ${Fx(Lx(o,i))}`)}return t.push("Z"),t.join(" ")}function Lx(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function Fx(e){return`${Ox(e.x)},${Ox(e.y)}`}function Ox(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function Dx(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function zx({shape:e,isSelected:t=!1}){const{h:n,w:o}=e.props,i=O(B("#64748b"));
|
|
50
|
+
return Gk("svg",{width:"100%",height:"100%",viewBox:`0 0 ${o} ${n}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:t?Gk("rect",{x:.5,y:.5,width:Math.max(o-1,0),height:Math.max(n-1,0),fill:"none",stroke:i,strokeDasharray:"4 4",strokeWidth:1,vectorEffect:"non-scaling-stroke"}):null})}function Ux(e){return Math.min(1,Math.max(0,e))}function Nx(e,t,n){return Math.min(n,Math.max(t,e))}function Wx(e){return!!e&&"object"==typeof e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function Xx(e,t){const n=Ux(e),o=Ux(t);let i=Math.min(n,o),r=Math.max(n,o);return r-i<LL&&(i=Math.max(0,Math.min(.9999,(i+r)/2-5e-5)),r=i+LL),{min:i,max:r}}function Yx(e){if(!e||"object"!=typeof e)return null;const t=e;if(!Wx(t.topLeft)||!Wx(t.bottomRight))return null;const n=Xx(t.topLeft.x,t.bottomRight.x),o=Xx(t.topLeft.y,t.bottomRight.y);return{topLeft:{x:n.min,y:o.min},bottomRight:{x:n.max,y:o.max}}}function Hx(e){const t=Yx(e);if(!t)return null;const n=t.topLeft.x,o=t.topLeft.y,i=t.bottomRight.x,r=t.bottomRight.y;return{left:n,top:o,right:i,bottom:r,width:i-n,height:r-o}}function _x(e){return Hx(e)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function Kx(e,t){return Math.abs(e.left-t.left)<=FL&&Math.abs(e.top-t.top)<=FL&&Math.abs(e.right-t.right)<=FL&&Math.abs(e.bottom-t.bottom)<=FL}function qx(e){return(e=>Math.abs(e.left)<=FL&&Math.abs(e.top)<=FL&&Math.abs(1-e.right)<=FL&&Math.abs(1-e.bottom)<=FL)(e)?null:Yx({topLeft:{x:e.left,y:e.top},bottomRight:{x:e.right,y:e.bottom}})}function jx({centerX:e,centerY:t,height:n,width:o}){const i=Nx(o,LL,1),r=Nx(n,LL,1),s=Nx(e-i/2,0,1-i),a=Nx(t-r/2,0,1-r);return{left:s,top:a,right:s+i,bottom:a+r,width:i,height:r}}function Vx(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function Gx({crop:e,shape:t}){const n=_x(e);return{w:t.props.w/n.width,h:t.props.h/n.height}}function Zx(e,t){return t===Qx(e.id)}function Qx(e){return`${DL}${e}`}function Jx({localToPage:e,shape:t}){const n=t.props.w,o=t.props.h,i=(0+n)/2,r=(0+o)/2,s={top_left:new $C(0,0),top:new $C(i,0),top_right:new $C(n,0),right:new $C(n,r),bottom_right:new $C(n,o),bottom:new $C(i,o),bottom_left:new $C(0,o),left:new $C(0,r)};return NL.map(t=>{return{kind:"custom",type:OL,id:t,point:e.applyToPoint(s[t]),cursor:(n=t,UL[n])};var n})}function ew({change:e,crop:t,shape:n}){const o=Gx({crop:t,shape:n}),i=t.bottomRight.x-t.topLeft.x,r=t.bottomRight.y-t.topLeft.y,s=Nx(t.topLeft.x-e.x/o.w,0,1-i),a=Nx(t.topLeft.y-e.y/o.h,0,1-r),d=Yx({topLeft:{x:s,y:a},bottomRight:{x:s+i,y:a+r}});return d?{id:n.id,props:{crop:d}}:null}function tw(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function nw(e,t){const n=WL.get(e);n&&(n.delete(t),0===n.size&&WL.delete(e))}function ow(e){return e.activeStroke?{...e,strokes:[...e.strokes,e.activeStroke],activeStroke:null,redoStrokes:[]}:e}function iw(e){const t=eF.get(e);if(t)return t;const n=new JL(e);return eF.set(e,n),n}function rw(e){return`${jL}${e}`}function sw(e,t){return t===rw(e.id)}function aw(e){const t="number"==typeof e?.size&&Number.isFinite(e.size)?e.size:GL,n="number"==typeof e?.opacity&&Number.isFinite(e.opacity)?e.opacity:QL??.45;return{size:Math.min(128,Math.max(1,t)),color:"string"==typeof e?.color&&e.color.trim().length>0?e.color:ZL,opacity:Math.min(1,Math.max(0,n))}}function dw({brush:e,editor:t,shape:n}){return iw(t).start(n,e)}function lw(e){iw(e).cancel()}function cw(e){iw(e).complete()}function uw(e,t){return iw(e).updateBrush(t)}function pw(e){return iw(e).getActiveSession()}async function hw(e,t){return iw(e).requestConfirm(t)}function gw(e){return{x:e.x,y:e.y,...void 0===e.pressure?{}:{pressure:e.pressure}}}function fw(e){return S(e)&&"image"===e.type}function mw(e){return f(e)&&"image"===e.type}function yw(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return null;const[t]=e.selection.selectedShapes;return mw(t)?t:null}function Sw(e){const t=yw(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!Zx(t,n.markId))}function bw(e){const t=yw(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!sw(t,n.markId))}function xw(){return[{id:ML,getAvailability(e){const t=yw(e);return!t||Sw(e)?"inapplicable":t.isLocked?"disabled":"enabled"},getValue:e=>Sw(e),run({context:e}){const t=yw(e);if(!t||t.isLocked)return;const n=e.editor.getShapeEditingSession();n?.shapeId===t.id&&Zx(t,n.markId)?e.editor.completeEditing("user"):e.editor.startEditingShape({shapeId:t.id,markId:Qx(t.id),entryMode:"focusEnd"},"user")&&((e,t)=>{const n=WL.get(e)??new Map;WL.set(e,n),n.set(t.id,{...t,props:{...t.props,crop:t.props.crop?{topLeft:{...t.props.crop.topLeft},bottomRight:{...t.props.crop.bottomRight}}:null},meta:{...t.meta}})})(e.editor,t)}},{id:EL,getAvailability:e=>Sw(e)?"enabled":"inapplicable",run({context:e}){const t=yw(e);t&&e.editor.completeEditing("user")&&nw(e.editor,t.id)}},{id:BL,getAvailability(e){if(!Sw(e))return"inapplicable";const t=yw(e);return t&&!t.isLocked?"enabled":"disabled"},run({context:e,value:t}){const n=yw(e);if(!n||n.isLocked||-1!==t&&1!==t)return;const o=(({direction:e,shape:t})=>{const n=_x(t.props.crop),o=Vx(n),i=Nx("in"===e?.8:1.25,Math.max(LL/n.width,LL/n.height),Math.min(1/n.width,1/n.height)),r=jx({centerX:o.x,centerY:o.y,width:n.width*i,height:n.height*i});return Kx(n,r)?null:{id:t.id,props:{crop:qx(r)}}})({direction:1===t?"in":"out",shape:n});o&&e.editor.commands.updateShapes([o],{source:"user"})}},{id:AL,getAvailability(e){if(!Sw(e))return"inapplicable";const t=yw(e);return t&&!t.isLocked?"enabled":"disabled"},getValue(e){const t=yw(e);return t?(e=>{const t=e.props.w/e.props.h;for(const n of zL)if(Math.abs(t-n.ratio)<=.01)return n.value;return null})(t):null},run({context:e,value:t}){const n=yw(e);if(!n||n.isLocked||"string"!=typeof t)return;const o=zL.find(e=>e.value===t);if(!o)return;const i=function({preset:e,shape:t}){const n=Vx(_x(t.props.crop)),o=Gx({crop:t.props.crop,shape:t}),i=zL.find(t=>t.value===e)?.ratio??null;if(!i)return null;const r=i*(o.h/o.w);let s=1,a=s/r;return a>1&&(a=1,s=a*r),(({nextRect:e,shape:t})=>{const n=_x(t.props.crop);if(Kx(n,e))return null;const o=Gx({crop:t.props.crop,shape:t}),i=new $C((e.left-n.left)*o.w,(e.top-n.top)*o.h).rot(t.rotation);return{id:t.id,x:t.x+i.x,y:t.y+i.y,props:{w:e.width*o.w,h:e.height*o.h,crop:qx(e)}}})({nextRect:jx({centerX:n.x,centerY:n.y,width:s,height:a}),shape:t})}({preset:o.value,shape:n});i&&e.editor.commands.updateShapes([i],{source:"user"})}},{id:RL,getAvailability(e){if(!Sw(e))return"inapplicable";const t=yw(e);return t&&!t.isLocked&&t.props.crop?"enabled":"disabled"},run({context:e}){const t=yw(e);if(!t||t.isLocked)return;const n=(({baselineShape:e,shape:t})=>{const n=e.x,o=e.y,i=e.props.w,r=e.props.h,s=Yx(e.props.crop);return Math.abs(t.x-n)<=FL&&Math.abs(t.y-o)<=FL&&Math.abs(t.props.w-i)<=FL&&Math.abs(t.props.h-r)<=FL&&(null===t.props.crop&&null===s||null!==t.props.crop&&null!==s&&Math.abs(t.props.crop.topLeft.x-s.topLeft.x)<=FL&&Math.abs(t.props.crop.topLeft.y-s.topLeft.y)<=FL&&Math.abs(t.props.crop.bottomRight.x-s.bottomRight.x)<=FL&&Math.abs(t.props.crop.bottomRight.y-s.bottomRight.y)<=FL)?null:{id:t.id,x:n,y:o,props:{w:i,h:r,crop:s}}})({baselineShape:(o=e.editor,i=t.id,WL.get(o)?.get(i)??null??t),shape:t});var o,i;n&&e.editor.commands.updateShapes([n],{source:"user"})}}]}function ww(e,t=0){return Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t)}function Iw({cornerRadius:e,h:t,w:n}){return Math.min(ww(e),Math.max(0,n)/2,Math.max(0,t)/2)}function Pw({dataUiPrefix:e}){return{kind:"text-input",id:`${e}.corner-radius`,actionId:$L,label:"Corner radius",icon:"border-corner-pill",placeholder:"0",suffix:"Px",validate:vw,dataUi:`${e}-corner-radius-control`}}function vw(e){const t=e.trim();if(0===t.length)return!1;const n=Number(t);return Number.isFinite(n)&&n>=0}function kw(){return{createSession(e,{handle:t,shape:n,originPagePoint:o}){return mw(n)&&"custom"===t.kind&&"image.crop"===t.type&&(i=t.id,NL.some(e=>e===i))?function({handleId:e,shapeId:t,startPagePoint:n,startPageToLocal:o,startShape:i,startCrop:r}){return{shapeId:t,historyMark:"image.crop.handle",update({editor:s,pagePoint:a,source:d}){if(!mw(s.getShape(t)))return"stop";const l=(({handleId:e,pageToLocal:t,shape:n,startCrop:o,startPagePoint:i,currentPagePoint:r})=>{const s=Yx(o)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=Gx({crop:s,shape:n});if(a.w<8||a.h<8)return null;const d=t.applyToPoint(i),l=t.applyToPoint(r).sub(d);if(0===l.x&&0===l.y)return null;const c={x:s.topLeft.x*a.w,y:s.topLeft.y*a.h,w:(s.bottomRight.x-s.topLeft.x)*a.w,h:(s.bottomRight.y-s.topLeft.y)*a.h},u=c.x+c.w,p=c.y+c.h;let h=c.x,g=c.y,f=c.w,m=c.h;(e=>"top_left"===e||"left"===e||"bottom_left"===e)(e)?(h=Nx(h+l.x,0,u-8),f=u-h):(e=>"top_right"===e||"right"===e||"bottom_right"===e)(e)&&(f=Nx(u+l.x,c.x+8,a.w)-h),(e=>"top_left"===e||"top"===e||"top_right"===e)(e)?(g=Nx(g+l.y,0,p-8),m=p-g):(e=>"bottom_left"===e||"bottom"===e||"bottom_right"===e)(e)&&(m=Nx(p+l.y,c.y+8,a.h)-g);const y=Yx({topLeft:{x:h/a.w,y:g/a.h},bottomRight:{x:(h+f)/a.w,y:(g+m)/a.h}});if(!y)return null;const S=new $C(h-s.topLeft.x*a.w,g-s.topLeft.y*a.h).rot(n.rotation);return{id:n.id,x:n.x+S.x,y:n.y+S.y,props:{w:f,h:m,crop:y}}})({handleId:e,currentPagePoint:a,pageToLocal:o,shape:i,startCrop:r,startPagePoint:n});return l?(s.commands.updateShapes([l],{source:d}),"continue"):"continue"}}}({handleId:t.id,shapeId:n.id,startPagePoint:o,startPageToLocal:e.computeShapeLocalToPageTransform(n).invert(),startShape:n,startCrop:n.props.crop}):null;var i}}}function Cw(e){const[t]=e.getSelectedShapes();if(!mw(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Zx(t,n.markId)?t:null}function Tw(e,t,n){if(!n.hasDragged){if(n.startPagePoint.dist2(t.pagePoint)<9)return;n.operation=e.operations.begin({kind:"image.crop.translate",label:"shape.edit",source:"user",history:"record"}),n.hasDragged=!0}if(!mw(e.getShape(n.shapeId)))return;const o=(({currentPagePoint:e,pageToLocal:t,shape:n,startCrop:o,startPagePoint:i,shiftKey:r})=>{const s=Yx(o);if(!s)return null;const a=t.applyToPoint(i);let d=t.applyToPoint(e).sub(a);return r&&(d=Math.abs(d.x)<Math.abs(d.y)?new $C(0,d.y):new $C(d.x,0)),0===d.x&&0===d.y?null:ew({change:d,crop:s,shape:n})})({currentPagePoint:t.pagePoint,pageToLocal:n.startPageToLocal,shape:n.startShape,shiftKey:t.shiftKey,startCrop:n.startCrop,startPagePoint:n.startPagePoint});o&&e.commands.updateShapes([o],{source:"user"})}function Mw(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ew(e){return"key_down"===e.name&&"Enter"===e.key&&!e.altKey&&!e.accelKey}function Bw(e){return"key_down"===e.name&&"z"===e.key.toLowerCase()&&e.accelKey&&!e.altKey}function Aw(e){const[t]=e.getSelectedShapes();if(!mw(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&sw(t,n.markId)?t:null}function Rw(e,t,n){const o=$w(e,t,n.pagePoint);return!!Lw(o,t)&&(((e,t)=>{iw(e).appendPoint(t)})(e,{x:o.x,y:o.y,pressure:n.pressure}),!0)}function $w(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function Lw(e,t){return e.x>=0&&e.y>=0&&e.x<=t.props.w&&e.y<=t.props.h}function Fw(e,t,n){if(!n.originCamera||!n.originScreenPoint)return;const o=t.screenPoint.sub(n.originScreenPoint),i=n.originCamera.z;e.setCamera({x:n.originCamera.x-o.x/i,y:n.originCamera.y-o.y/i},{source:"user"})}function Ow({shape:e,session:t}){return t&&t.shapeId===e.id&&0!==t.strokes.length?Gk("svg",{"aria-hidden":"true","data-ui":"image-smudge-preview",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",height:e.props.h,inset:0,overflow:"hidden",pointerEvents:"none",position:"absolute",width:e.props.w},children:t.strokes.map(e=>Gk(Dw,{stroke:e},e.id))}):null}function Dw({stroke:e}){const t=e.points[0];if(!t)return null;const n=e.brush.color??"#ffff00",o=e.brush.opacity??.45,i=e.brush.size;if(1===e.points.length)return Gk("circle",{cx:t.x,cy:t.y,r:i/2,fill:n,opacity:o});const r=(e=>{const[t,...n]=e.points;return t?[`M ${Uw(t.x)} ${Uw(t.y)}`,...n.map(e=>`L ${Uw(e.x)} ${Uw(e.y)}`)].join(" "):null})(e);return r?Gk("path",{d:r,fill:"none",opacity:o,stroke:n,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:i}):null}function zw(e,t){return`${e},${t}`}function Uw(e){return Number.isFinite(e)?Number(e.toFixed(2)).toString():"0"}function Nw(e,t,n){const o=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n);return o.x>=0&&o.y>=0&&o.x<=t.props.w&&o.y<=t.props.h}function Ww(e){return e.runtime.require(rF)}function Xw(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function Yw(e,t){Ww(e).set(t.sessionId,t.trail)}function Hw(){return"undefined"==typeof performance?Date.now():performance.now()}function _w(e,t,n,o){const i=e.samples[e.samples.length-1];if(!i)return void e.samples.push({...t,time:o,velocity:0});const r=mF/n,s=Gw(i,t);if(s<r)return void(e.samples[e.samples.length-1]={...i,...t,time:o});const a=s*n/Math.max(IF,o-i.time);e.samples.push({...t,time:o,velocity:oI(i.velocity,a,.68)})}function Kw(e,t){e.samples=qw(e.samples,t)}function qw(e,t){const n=e[e.length-1];if(!n)return[];const o=t-iI(PF+n.velocity*vF,PF,kF);if(n.time<o)return[];const i=e.findIndex(e=>e.time>=o);if(-1===i)return[];const r=e.slice(i),s=e[i-1],a=r[0];return s&&a.time>o?[(d=s,l=a,c=iI((o-s.time)/(a.time-s.time),0,1),{...nI(d,l,c),time:oI(d.time,l.time,c),velocity:oI(d.velocity,l.velocity,c)}),...r]:r;var d,l,c}function jw(e,t){if(e.length<=1)return{x:1,y:0};const n=e[t-1]??e[t],o=e[t+1]??e[t];return(e=>{const t=Math.sqrt(e.x*e.x+e.y*e.y);return t<=0?{x:1,y:0}:{x:e.x/t,y:e.y/t}})(0===t?eI(o,e[t]):eI(t===e.length-1?e[t]:o,n))}function Vw(e,t,n){const o=[];for(let i=0;i<n;i++){const r=2*Math.PI*i/n;o.push({x:e.x+Math.cos(r)*t,y:e.y+Math.sin(r)*t})}return o}function Gw(e,t){return Math.sqrt(Zw(e,t))}function Zw(e,t){const n=e.x-t.x,o=e.y-t.y;return n*n+o*o}function Qw(e){return{x:-e.y,y:e.x}}function Jw(e,t){return{x:e.x+t.x,y:e.y+t.y}}function eI(e,t){return{x:e.x-t.x,y:e.y-t.y}}function tI(e,t){return{x:e.x*t,y:e.y*t}}function nI(e,t,n){return{x:oI(e.x,t.x,n),y:oI(e.y,t.y,n)}}function oI(e,t,n){return e+(t-e)*n}function iI(e,t,n){return Math.max(t,Math.min(n,e))}function rI(e,t){const n=e[e.length-1];!n||Zw(n,t)>.04?e.push(t):e[e.length-1]=t}function sI(e){if(e.length<2)return null;if(2===e.length)return`M ${dI(e[0])} L ${dI(e[1])} Z`;const t=[`M ${dI(aI(e[0],e[1]))}`];for(let n=1;n<e.length;n++){const o=e[n],i=e[(n+1)%e.length];t.push(`Q ${dI(o)} ${dI(aI(o,i))}`)}return t.push("Z"),t.join(" ")}function aI(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function dI(e){return`${lI(e.x)},${lI(e.y)}`}function lI(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function cI(e,t,n){return["control",n,e,t].map(encodeURIComponent).join("|")}function uI(e,t){const n=t.split("|").map(e=>{try{return decodeURIComponent(e)}catch{return""}});return"path.node"===e&&3===n.length&&"node"===n[0]?{type:MF,subpathId:n[1],nodeId:n[2]}:"path.control"!==e||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:EF,handle:n[1],subpathId:n[2],nodeId:n[3]}}function pI(e,t){t?BF.set(e,hI(t)):BF.delete(e)}function hI(e){return{...e,pagePoint:e.pagePoint.clone()}}function gI(e){return f(e)&&"path"===e.type}function fI(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function mI(e){return new $C(e.x,e.y)}function yI(e,t){const n=mI(t);if(!((e,t)=>!!e.out||!!t.in)(e,t))return`L ${fI(n.x)} ${fI(n.y)}`;const o=(e=>{const t=mI(e);return e.out?t.add(new $C(e.out.dx,e.out.dy)):t})(e),i=(e=>{const t=mI(e);return e.in?t.add(new $C(e.in.dx,e.in.dy)):t})(t);return["C",fI(o.x),fI(o.y),fI(i.x),fI(i.y),fI(n.x),fI(n.y)].join(" ")}function SI(e){const t=e.nodes[0];if(!t)return null;const n=[`M ${fI(t.x)} ${fI(t.y)}`];for(let o=1;o<e.nodes.length;o+=1){const t=e.nodes[o-1],i=e.nodes[o];t&&i&&n.push(yI(t,i))}if(e.closed&&e.nodes.length>1){const o=e.nodes[e.nodes.length-1];o&&n.push(yI(o,t)),n.push("Z")}return n.join(" ")}function bI(e){const t=e.map(SI).filter(e=>null!==e);return t.length>0?t.join(" "):null}function xI(e){return Number.isFinite(e)}function wI(e){return{dx:e.dx,dy:e.dy}}function II(e){return{id:e.id,x:e.x,y:e.y,kind:e.kind,...e.in?{in:wI(e.in)}:null,...e.out?{out:wI(e.out)}:null}}function PI(e){return{id:e.id,closed:e.closed,nodes:e.nodes.map(II)}}function vI(e){return e.map(PI)}function kI(e){return new $C(e.x,e.y)}function CI(e){const t=kI(e);return e.in?t.add(new $C(e.in.dx,e.in.dy)):t}function TI(e){const t=kI(e);return e.out?t.add(new $C(e.out.dx,e.out.dy)):t}function MI(e,t,n,o,i){const r=1-i,s=r*r*r,a=3*r*r*i,d=3*r*i*i,l=i*i*i;return new $C(e.x*s+t.x*a+n.x*d+o.x*l,e.y*s+t.y*a+n.y*d+o.y*l)}function EI(e,t,n){return new $C(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n)}function BI(e,t){return[kI(e),TI(e),CI(t),kI(t)]}function AI(e,t){return!!e.out||!!t.in}function RI(e,t,n){return AI(e,t)?MI(...BI(e,t),n):EI(kI(e),kI(t),n)}function $I(e,t,n){const o=kI(t),i=TI(t),r=CI(n),s=kI(n);if(t.out||n.in)for(let a=1;a<=18;a+=1)e.push(MI(o,i,r,s,a/18));else e.push(s)}function LI(e){const t=e.nodes[0];if(!t)return{id:e.id,closed:e.closed,points:[]};const n=[kI(t)];for(let o=1;o<e.nodes.length;o+=1){const t=e.nodes[o-1],i=e.nodes[o];t&&i&&$I(n,t,i)}if(e.closed&&e.nodes.length>1){const o=e.nodes[e.nodes.length-1];o&&$I(n,o,t)}return{id:e.id,closed:e.closed,points:n}}function FI(e){const t=e.props,n=OF.get(t);if(n)return n;const o=OI(e.props);return OF.set(t,o),o}function OI(e){const t=e.subpaths.map(LI),n=t.flatMap(e=>e.points),o=e.subpaths.flatMap(e=>e.nodes.flatMap(e=>[kI(e),...e.in?[CI(e)]:[],...e.out?[TI(e)]:[]])),i=o.length>0?LC.FromPoints(o):new LC(0,0,1,1),r=Math.max(e.strokeWidth/2,1),s=n.length>0?LC.FromPoints(n).expand(r):i.expand(r),a=new LC(s.x,s.y,Math.max(s.w,1),Math.max(s.h,1));return{path:bI(e.subpaths),pointBounds:i,localBounds:s,renderBounds:a,outlineVertices:n.map(e=>e.clone()),flattenedSubpaths:t}}function DI(e,t){return e.map(e=>({...e,nodes:e.nodes.map(e=>((e,t)=>{const n=t(kI(e)),o=e.in?t(CI(e)):null,i=e.out?t(TI(e)):null;return{...e,x:n.x,y:n.y,...o?{in:{dx:o.x-n.x,dy:o.y-n.y}}:{in:null},...i?{out:{dx:i.x-n.x,dy:i.y-n.y}}:{out:null}}})(e,t))}))}function zI(e,t){const n=OI({...t,subpaths:vI(e)}).pointBounds,o=Number.isFinite(n.x)?n.x:0,i=Number.isFinite(n.y)?n.y:0,r=((e,t,n)=>DI(e,e=>new $C(e.x+t,e.y+n)))(e,-o,-i);return{x:o,y:i,subpaths:r,geometry:OI({...t,subpaths:r})}}function UI(e,t){return DI(e.props.subpaths,e=>t.applyToPoint(e))}function NI(e,t){return bI(UI(e,t))}function WI(e,t,n){const o=n.sub(t),i=o.len2();if(0===i)return{distanceSquared:e.dist2(t),t:0};const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/i)),a=t.add(o.mul(s));return{distanceSquared:e.dist2(a),t:s}}function XI(e,t,n){return WI(e,t,n).distanceSquared}function YI(e,t,n){const o=n*n;let i=null;for(const r of e){if(r.nodes.length<2)continue;const e=r.closed?r.nodes.length:r.nodes.length-1;for(let n=0;n<e;n+=1){const e=r.nodes[n],s=r.nodes[(n+1)%r.nodes.length];if(!e||!s)continue;const a=AI(e,s)?32:1;let d=kI(e);for(let n=1;n<=a;n+=1){const l=RI(e,s,n/a),c=WI(t,d,l),u=(n-1+c.t)/a;u>.02&&u<.98&&c.distanceSquared<=o&&(!i||c.distanceSquared<i.distanceSquared)&&(i={subpathId:r.id,startNodeId:e.id,endNodeId:s.id,t:u,point:RI(e,s,u),distanceSquared:c.distanceSquared}),d=l}}}return i?{subpathId:i.subpathId,startNodeId:i.startNodeId,endNodeId:i.endNodeId,t:i.t,point:i.point.clone(),distance:Math.sqrt(i.distanceSquared)}:null}function HI(e,t){return e.find(e=>e.id===t)??null}function _I(e,t,n){return HI(e,t)?.nodes.find(e=>e.id===n)??null}function KI(e,t,n,o){return e.map(e=>e.id!==t?PI(e):{...e,nodes:e.nodes.map(e=>e.id===n?o(II(e)):II(e))})}function qI(e,t,n){const o=ZI(t);return 0===o.size?vI(e):e.map(e=>{const t=o.get(e.id);return t?{...e,nodes:e.nodes.map(e=>t.has(e.id)?n(II(e)):II(e))}:PI(e)})}function jI(e,t,n){return e.map(e=>{if(e.id!==t)return PI(e);const o=e.nodes.findIndex(e=>e.id===n),i=e.nodes[o];if(!i)return PI(e);const r=o>0?e.nodes[o-1]:e.closed?e.nodes[e.nodes.length-1]:null,s=o<e.nodes.length-1?e.nodes[o+1]:e.closed?e.nodes[0]:null,a=kI(i),d=((e,t,n)=>{const o=t?kI(t):null,i=n?kI(n):null;if(o&&i){const t=i.sub(o);if(t.len()<=$F)return null;const n=t.normalize();return((e,t)=>{const n=Math.abs(e.x*t.y-e.y*t.x),o=e.len()*t.len();return o<=$F||n/o<=.001})(o.sub(e),i.sub(e))?n.rot(FF):n}const r=i?i.sub(e):o?e.sub(o):null;return!r||r.len()<=$F?null:r.normalize().rot(FF)})(a,r,s),l=e.nodes.map(II);return l[o]={...II(i),kind:"smooth",in:r&&d?lP(d.mul(-a.dist(kI(r))*LF)):null,out:s&&d?lP(d.mul(a.dist(kI(s))*LF)):null},{...e,nodes:l}})}function VI(e,t,n){return KI(e,t,n,e=>({...e,kind:"corner",in:null,out:null}))}function GI(e,t,n,o=t.at(-1)??null){if(!(e=>{const t=new Set;for(const n of e){if(!n.id||t.has(n.id))return!1;t.add(n.id);const e=new Set;for(const t of n.nodes){if(!t.id||e.has(t.id))return!1;e.add(t.id)}}return!0})(e))return null;const i=(e=>{const t=new Set,n=[];for(const o of e){const e=JSON.stringify([o.subpathId,o.nodeId]);t.has(e)||(t.add(e),n.push({subpathId:o.subpathId,nodeId:o.nodeId}))}return n})(t);if(i.length<2)return null;let r;switch(n){case"merge":r=((e,t)=>{const n=QI(t);if(null!==n)return((e,t,n)=>{const o=e.findIndex(e=>e.id===t),i=e[o];if(!i)return null;const r=((e,t)=>{const n=t.map(t=>e.nodes.findIndex(e=>e.id===t.nodeId));if(n.some(e=>e<0))return null;const o=Array.from(new Set(n)).sort((e,t)=>e-t);if(o.length!==t.length)return null;if(!e.closed)return o.every((e,t)=>0===t||e===o[t-1]+1)?o:null;if(o.length===e.nodes.length)return o;const i=o.flatMap((t,n)=>(t+1)%e.nodes.length===o[(n+1)%o.length]?[]:[n]);if(1!==i.length)return null;const r=(i[0]+1)%o.length;return[...o.slice(r),...o.slice(0,r)]})(i,n);if(!r||r.length<2)return null;const s=new Set(r),a=r.map(e=>i.nodes[e]),d=r[0],l=a[0],c=a[a.length-1],u=a.reduce((e,t)=>e.add(kI(t)),$C.Zero()).div(a.length),p={...II(l),x:u.x,y:u.y,kind:"corner",in:rP(l.in,kI(l),u),out:rP(c.out,kI(c),u)},h=i.nodes.flatMap((e,t)=>s.has(t)?t===d?[p]:[]:[II(e)]),g=i.closed&&h.length>=3;return i.closed&&!g&&iP(h),{subpaths:aP(e,o,[{...i,closed:g,nodes:h}]),selectedNodes:[{subpathId:t,nodeId:p.id}]}})(e,n,t);const o=JI(e,t);return o?((e,t)=>{const[n,o]=t,i=tP(n),r=nP(o),s=i[i.length-1],a=r[0],d=kI(s).add(kI(a)).div(2),l={...II(s),x:d.x,y:d.y,kind:"corner",in:rP(s.in,kI(s),d),out:rP(a.out,kI(a),d)},{nodes:c}=sP(r.slice(1),new Set([...i.slice(0,-1).map(e=>e.id),l.id]),"merged"),u={...n.subpath,closed:!1,nodes:[...i.slice(0,-1),l,...c]};return{subpaths:dP(e,t,u),selectedNodes:[{subpathId:u.id,nodeId:l.id}]}})(e,o):null})(e,i);break;case"join":r=((e,t)=>{if(2!==t.length)return null;const n=QI(t);if(null!==n)return((e,t,n)=>{const o=e.findIndex(e=>e.id===t),i=e[o];if(!i||i.closed||i.nodes.length<3)return null;const r=new Set([i.nodes[0].id,i.nodes[i.nodes.length-1].id]);if(2!==n.length||n.some(e=>!r.has(e.nodeId)))return null;const s=i.nodes.map(II);return s[0]={...s[0],kind:"corner",in:null},s[s.length-1]={...s[s.length-1],kind:"corner",out:null},{subpaths:aP(e,o,[{...i,closed:!0,nodes:s}]),selectedNodes:n.map(e=>({...e}))}})(e,n,t);const o=JI(e,t);return o?((e,t)=>{const[n,o]=t,i=tP(n),{nodes:r,nodeIdMap:s}=sP(nP(o),new Set(i.map(e=>e.id)),"joined"),a=r[0];i[i.length-1]={...i[i.length-1],kind:"corner",out:null},r[0]={...a,kind:"corner",in:null};const d={...n.subpath,closed:!1,nodes:[...i,...r]};return{subpaths:dP(e,t,d),selectedNodes:[{subpathId:d.id,nodeId:n.node.id},{subpathId:d.id,nodeId:s.get(o.node.id)??o.node.id}]}})(e,o):null})(e,i);break;case"separate":r=((e,t)=>{if(2!==t.length)return null;const n=QI(t);if(null===n)return null;const o=e.findIndex(e=>e.id===n),i=e[o];if(!i||i.nodes.length<2)return null;const r=((e,t)=>{const[n,o]=t.map(t=>e.nodes.findIndex(e=>e.id===t.nodeId));return void 0===n||void 0===o||n<0||o<0?-1:o===n+1?n:n===o+1?o:e.closed?n===e.nodes.length-1&&0===o?n:o===e.nodes.length-1&&0===n?o:-1:-1})(i,t);if(r<0)return null;if(i.closed){const n=[...i.nodes.slice(r+1).map(II),...i.nodes.slice(0,r+1).map(II)];return iP(n),{subpaths:aP(e,o,[{...i,closed:!1,nodes:n}]),selectedNodes:t.map(e=>({...e}))}}const s=i.nodes.slice(0,r+1).map(II),a=i.nodes.slice(r+1).map(II);iP(s),iP(a);const d=s.length>=2?{...i,closed:!1,nodes:s}:null,l=((e,t)=>{const n=new Set(e.map(e=>e.id));if(!n.has(t))return t;let o=2;for(;n.has(`${t}:${o}`);)o+=1;return`${t}:${o}`})(e,`${i.id}:split`),c=a.length>=2?{...i,id:l,closed:!1,nodes:a}:null,u=[d,c].filter(e=>null!==e),p=new Set(s.map(e=>e.id)),h=new Set(a.map(e=>e.id)),g=t.flatMap(e=>d&&p.has(e.nodeId)?[{subpathId:d.id,nodeId:e.nodeId}]:c&&h.has(e.nodeId)?[{subpathId:c.id,nodeId:e.nodeId}]:[]);return{subpaths:aP(e,o,u),selectedNodes:g}})(e,i)}if(!r)return null;const s=o?i.findIndex(e=>{return(t=e).subpathId===(n=o).subpathId&&t.nodeId===n.nodeId;var t,n}):-1;return{...r,primaryNode:r.selectedNodes[s]??r.selectedNodes.at(-1)??null}}function ZI(e){const t=new Map;for(const n of e){const e=t.get(n.subpathId)??new Set;e.add(n.nodeId),t.set(n.subpathId,e)}return t}function QI(e){const t=e[0];return t&&e.every(e=>e.subpathId===t.subpathId)?t.subpathId:null}function JI(e,t){if(2!==t.length)return null;const n=eP(e,t[0]),o=eP(e,t[1]);return n&&o&&n.subpathIndex!==o.subpathIndex?[n,o]:null}function eP(e,t){const n=e.findIndex(e=>e.id===t.subpathId),o=e[n];if(!o||o.closed)return null;const i=o.nodes.findIndex(e=>e.id===t.nodeId),r=o.nodes[i];return!r||0!==i&&i!==o.nodes.length-1?null:{subpath:o,subpathIndex:n,endpoint:0===i?"start":"end",node:r}}function tP(e){return"end"===e.endpoint?e.subpath.nodes.map(II):oP(e.subpath.nodes)}function nP(e){return"start"===e.endpoint?e.subpath.nodes.map(II):oP(e.subpath.nodes)}function oP(e){return[...e].reverse().map(e=>({...II(e),in:e.out?wI(e.out):null,out:e.in?wI(e.in):null}))}function iP(e){0!==e.length&&(e[0]={...e[0],kind:"corner",in:null},e[e.length-1]={...e[e.length-1],kind:"corner",out:null})}function rP(e,t,n){return e?lP(t.add(new $C(e.dx,e.dy)).sub(n)):null}function sP(e,t,n){const o=new Map;return{nodes:e.map(e=>{let i=e.id;if(t.has(i)){let o=1,r=`${i}:${n}`;for(;t.has(r);)o+=1,r=`${e.id}:${n}:${o}`;i=r}return t.add(i),o.set(e.id,i),{...II(e),id:i}}),nodeIdMap:o}}function aP(e,t,n){return e.flatMap((e,o)=>o===t?n.map(PI):[PI(e)])}function dP(e,t,n){const o=Math.min(t[0].subpathIndex,t[1].subpathIndex),i=new Set([t[0].subpathIndex,t[1].subpathIndex]);return e.flatMap((e,t)=>t===o?[n]:i.has(t)?[]:[PI(e)])}function lP(e){return e.len2()<=1e-12?null:{dx:e.x,dy:e.y}}function cP(e){const t=DF.get(e);return t?(e=>({shapeId:e.shapeId,nodes:e.nodes.map(e=>({...e})),primary:{...e.primary}}))(t):null}function uP(e){const t=DF.get(e);if(!t)return null;if(e.getShapeEditingSession()?.shapeId!==t.shapeId)return null;const n=e.getShape(t.shapeId);if(!gI(n))return null;const o=t.nodes.flatMap(e=>{const t=HI(n.props.subpaths,e.subpathId)?.nodes.find(t=>t.id===e.nodeId);return t?[{ref:{...e},node:t}]:[]});if(0===o.length)return null;const i=o.some(({ref:e})=>SP(e,t.primary))?t.primary:o[o.length-1].ref;return{selection:{shapeId:n.id,nodes:o.map(({ref:e})=>({...e})),primary:{...i}},shape:n,entries:o}}function pP(e){const t=DF.get(e);DF.delete(e),e.getShapeEditingSession()?.shapeId===t?.shapeId&&yP(e,null)}function hP(e,t,n,o){const i={subpathId:n,nodeId:o};gP(e,t,[i],i)}function gP(e,t,n,o=n.at(-1)??null){const i=((e,t,n)=>{const o=(e=>{const t=new Set,n=[];for(const o of e){const e=JSON.stringify([o.subpathId,o.nodeId]);t.has(e)||(t.add(e),n.push({...o}))}return n})(t).filter(t=>null!==mP(e,t));if(0===o.length)return null;const i=(n&&o.find(e=>SP(e,n)))??o[o.length-1];return{shapeId:e.id,nodes:o,primary:{...i}}})(t,n,o);if(!i)return void pP(e);DF.set(e,i);const r=mP(t,i.primary);yP(e,r?e.computeShapeLocalToPageTransform(t).applyToPoint(kI(r)):null)}function fP(e,t,n){return e.nodes.some(e=>e.subpathId===t&&e.nodeId===n)}function mP(e,t){return HI(e.props.subpaths,t.subpathId)?.nodes.find(e=>e.id===t.nodeId)??null}function yP(e,t){const n=e.getShapeEditingSession();n&&e.updateSession({shapeEditingSession:{...n,caretPagePoint:t?{x:t.x,y:t.y}:void 0}},"system")}function SP(e,t){return e.subpathId===t.subpathId&&e.nodeId===t.nodeId}function bP(e){const t=e.meta[zF],n=e.meta[UF];return{subpathId:"string"==typeof t?t:null,previewNodeId:"string"==typeof n?n:null}}function xP(e,t){const n=wP(e);return t.subpathId&&(n[zF]=t.subpathId),t.previewNodeId&&(n[UF]=t.previewNodeId),n}function wP(e){const t={...e};return delete t[zF],delete t[UF],t}function IP({node:e,showIn:t,size:n,strokeWidth:o}){const i=kI(e);
|
|
51
|
+
return Zk(Vk,{children:[t&&e.in?Gk(PP,{anchor:i,point:CI(e),size:n,strokeWidth:o,variant:"in"}):null,e.out?Gk(PP,{anchor:i,point:TI(e),size:n,strokeWidth:o,variant:"out"}):null]})}function PP({anchor:e,point:t,size:n,strokeWidth:o,variant:i}){const r=n/2;
|
|
52
|
+
return Zk("g",{"data-ui":"path-draft-curve-handle","data-path-draft-curve-handle":i,children:[Gk("line",{"data-ui":"path-draft-control-line",x1:e.x,y1:e.y,x2:t.x,y2:t.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:o}),Gk("rect",{"data-ui":"path-draft-control-handle",x:t.x-r,y:t.y-r,width:n,height:n,fill:WF,stroke:NF,strokeWidth:o})]})}function vP({point:e,size:t,strokeWidth:n,variant:o}){const i=t/2;
|
|
53
|
+
return Gk("rect",{"data-ui":"path-draft-control-point","data-path-draft-control-point":o,x:e.x-i,y:e.y-i,width:t,height:t,rx:2,ry:2,fill:"candidate"===o?"rgba(219, 234, 254, 0.98)":WF,stroke:NF,strokeWidth:n})}function kP({shape:e,shapeEditingSession:t=null,fill:n=e.props.fill,stroke:o=e.props.stroke,strokeWidth:i=e.props.strokeWidth}){const{renderBounds:r}=FI({props:{...e.props,strokeWidth:i}}),s=TP(e);if(!s)return null;const a=t?.shapeId===e.id;
|
|
54
|
+
return Zk("svg",{width:"100%",height:"100%",viewBox:`${r.x} ${r.y} ${Math.max(r.w,1)} ${Math.max(r.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[z(n)?null:Gk("path",{d:s,fill:O(n),fillRule:e.props.fillRule,clipRule:e.props.fillRule,stroke:"none"}),
|
|
55
|
+
Gk("path",{d:s,fill:"none",stroke:O(o),strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round"}),a?Gk(MP,{shape:e}):null]})}function CP({shape:e,strokeWidth:t}){const{renderBounds:n}=FI(e),o=TP(e);return o?Gk("svg",{"data-ui":"path-hover-outline",width:"100%",height:"100%",viewBox:`${n.x} ${n.y} ${Math.max(n.w,1)} ${Math.max(n.h,1)}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Gk("path",{d:o,fill:"none",stroke:xM,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function TP(e){const t=(e=>bP(e).previewNodeId)(e);return bI(((e,t)=>t?e.map(e=>({...e,nodes:e.nodes.filter(e=>e.id!==t).map(e=>({...e}))})).filter(e=>e.nodes.length>0):e.map(e=>({...e,nodes:e.nodes.map(e=>({...e}))})))(e.props.subpaths,t))}function MP({shape:e}){
|
|
56
|
+
return Gk(Vk,{children:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=kI(t),o=[];if(t.in){const i=CI(t);o.push(Gk("line",{x1:n.x,y1:n.y,x2:i.x,y2:i.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${e.id}:${t.id}:in`))}if(t.out){const i=TI(t);o.push(Gk("line",{x1:n.x,y1:n.y,x2:i.x,y2:i.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${e.id}:${t.id}:out`))}return o}))})}function EP(e,t){const n=wr();Ir(n.shapeEditingSessionSignal);const o=cP(n),i=uI(e,t);return!!o&&!!i&&fP(o,i.subpathId,i.nodeId)}function BP(e,t,n){const o=vI(t.props.subpaths),i="create"===n?bP(t):null;return{subpaths:o,draftMeta:i,selection:cP(e),signature:JSON.stringify({subpaths:o,draftMeta:i})}}function AP(e){return JSON.stringify((e=>({...e,meta:{...e.meta},props:{...e.props,fill:{...e.props.fill},stroke:{...e.props.stroke},subpaths:vI(e.props.subpaths)}}))(e))}function RP(e){const t=YF.get(e);if(t)return t;const n=new XF(e);return YF.set(e,n),n}function $P(e,t,n,o){return RP(e).start(t,n,o)}function LP(e,t){return RP(e).record(t)}function FP(e,t,n){return RP(e).end(t,n)}function OP(e){return HF.get(e)??!1}function DP(e){return((e,t)=>{const n=e.getShapeEditingSession(),o=n?e.getShape(n.shapeId):null;return!(!n||!gI(o))&&(OP(e)===t||(HF.set(e,t),t||e.snaps.clearIndicators(),e.updateSession({shapeEditingSession:{...n}},"system")),t)})(e,!OP(e))}function zP(e){HF.delete(e),e.snaps.clearIndicators()}function UP(e){const t=e.getShapeEditingSession();if(!t)return null;const n=e.getShape(t.shapeId);return gI(n)?n:null}function NP(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function WP(e){pI(e,null)}function XP(e){WP(e),pP(e)}function YP(e){return e.shiftKey}function HP(e){return JSON.stringify([e.subpathId,e.nodeId])}function _P(e,t){const n=jF.get(e);if(!n)return;if(t.pointerId!==n.pointerId)return;const o=e.getShape(n.shapeId);if(!gI(o))return void KP(e);if(!n.isActive&&!((e,t)=>e.dist2(t)>=9)(n.originScreenPoint,t.screenPoint))return;n.isActive=!0;const i=((e,t)=>{const n=Math.min(e.x,t.x),o=Math.min(e.y,t.y),i=Math.max(e.x,t.x),r=Math.max(e.y,t.y);return new LC(n,o,i-n,r-o)})(n.originPagePoint,t.pagePoint),r=((e,t,n)=>{const o=e.computeShapeLocalToPageTransform(t);return t.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const i=o.applyToPoint(kI(t));return n.containsPoint(i)?[{subpathId:e.id,nodeId:t.id}]:[]}))})(e,o,i),s=YP(t)?((e,t)=>{const n=new Map(e.map(e=>[HP(e),{...e}]));for(const o of t){const e=HP(o);n.has(e)?n.delete(e):n.set(e,{...o})}return Array.from(n.values())})(n.previousEntries,r):r;e.setBrushBox(i),gP(e,o,s,s.at(-1)??null)}function KP(e){const t=jF.get(e);if(!t)return;const n=e.getShape(t.shapeId);gI(n)&&e.getShapeEditingSession()?.shapeId===t.shapeId?gP(e,n,t.previousEntries,t.previousPrimary):pP(e),jF.delete(e),e.setBrushBox(null)}function qP(e,t,n,o){const i=e.getShape(t);gI(i)&&gP(e,i,n,o)}function jP(e){return e.filter(e=>e.nodes.length>=2)}function VP(e,t){e.completeEditing("user"),e.getShape(t.id)&&e.operations.run({kind:"path.shape-delete",label:"shape.delete",source:"user",history:"record"},()=>{e.commands.deleteShapes([t.id],{source:"user"})})}function GP(e,t,n){const o=jP(((e,t)=>{const n=ZI(t);return 0===n.size?vI(e):e.map(e=>{const t=n.get(e.id);if(!t)return PI(e);const o=e.nodes.filter(e=>!t.has(e.id)).map(II),i=e.closed&&o.length>=3;return e.closed&&!i&&iP(o),{...e,closed:i,nodes:o}}).filter(e=>e.nodes.length>0)})(t.props.subpaths,n));0!==o.length?(e.commands.updateShapes([{id:t.id,props:{subpaths:o}}],{source:"user"}),pP(e),LP(e,t.id)):VP(e,t)}function ZP(e,t){const n=uP(e);if(!n||n.shape.isLocked)return!1;const{shape:o,selection:i}=n,r=GI(o.props.subpaths,i.nodes,t,i.primary);if(!r)return!1;const s=jP(r.subpaths);return 0===s.length?(VP(e,o),!0):(e.operations.run({kind:"path.node-operation",label:"shape.edit",source:"user",history:"record"},()=>{e.commands.updateShapes([{id:o.id,props:{subpaths:s}}],{source:"user"}),qP(e,o.id,r.selectedNodes,r.primaryNode)}),LP(e,o.id),!0)}function QP(e,t){const n=UP(e);if(n&&e.isActiveToolInInitialState()&&("Enter"===t.key||"Escape"===t.key)&&!t.altKey&&!t.ctrlKey&&!t.metaKey&&!t.accelKey)return e.completeEditing("user");if(!(n||"Enter"!==t.key||t.altKey||t.ctrlKey||t.metaKey||t.accelKey))return(e=>{if(e.getShapeEditingSession()||"select"!==e.getActiveToolId()||!e.isActiveToolInInitialState())return!1;const t=e.getSelectedShapeIds(),[n]=e.getSelectedShapes();return!(1!==t.length||!gI(n)||!e.canEditShape(n)||(XP(e),zP(e),!e.startEditingShape({shapeId:n.id,markId:_F,entryMode:"focusEnd"},"user")))})(e);if(n&&t.accelKey&&"z"===t.key.toLowerCase()&&!t.altKey)return t.shiftKey?e.redo():e.undo();if(t.accelKey&&("'"===t.key||"Quote"===t.code)&&n&&!n.isLocked)return DP(e),e.inputs.state.get().isPointing&&e.tools.dispatch(t),!0;if(t.accelKey&&"j"===t.key.toLowerCase()&&!t.altKey&&n&&!n.isLocked)return ZP(e,"merge");const o=(e=>{if(e.altKey||e.ctrlKey||e.metaKey||e.accelKey)return null;const t=e.shiftKey?10:1;switch(e.key){case"ArrowLeft":return new $C(-t,0);case"ArrowRight":return new $C(t,0);case"ArrowUp":return new $C(0,-t);case"ArrowDown":return new $C(0,t);default:return null}})(t);if(o)return function(e,t){const n=uP(e);if(!n||n.shape.isLocked)return!1;const{shape:o,selection:i}=n,r=((e,t,n)=>{const o=e.computeShapeLocalToPageTransform(t).invert(),i=o.applyToPoint(new $C(0,0));return o.applyToPoint(n).sub(i)})(e,o,t),s=qI(o.props.subpaths,i.nodes,e=>tv(e,r));return e.operations.run({kind:"path.node-nudge",label:"shape.edit",source:"user",history:"record"},()=>{e.commands.updateShapes([{id:o.id,props:{subpaths:s}}],{source:"user"}),qP(e,o.id,i.nodes,i.primary)}),LP(e,o.id),!0}(e,o);if(t.altKey||t.ctrlKey||t.metaKey||t.accelKey)return!1;const i=uP(e);if(!i||i.shape.isLocked)return!1;const r=t.key.toLowerCase();return"backspace"===r||"delete"===r?(GP(e,i.shape,i.selection.nodes),!0):"c"===r?((e,t,n)=>{const o=n.filter(e=>{const n=_I(t.props.subpaths,e.subpathId,e.nodeId);return!!n&&!n.in&&!n.out});if(0===o.length)return!1;const i=o.reduce((e,t)=>jI(e,t.subpathId,t.nodeId),t.props.subpaths);return e.commands.updateShapes([{id:t.id,props:{subpaths:i}}],{source:"user"}),qP(e,t.id,n,n.at(-1)??null),LP(e,t.id),!0})(e,i.shape,i.selection.nodes):"x"===r?(((e,t,n)=>{const o=n.reduce((e,t)=>VI(e,t.subpathId,t.nodeId),t.props.subpaths);e.commands.updateShapes([{id:t.id,props:{subpaths:o}}],{source:"user"}),qP(e,t.id,n,n.at(-1)??null),LP(e,t.id)})(e,i.shape,i.selection.nodes),!0):"j"===r?ZP(e,"join"):"k"===r&&ZP(e,"separate")}function JP(e,t,n){const o=n?e.len():t?.len()??e.len();if(0===o)return null;const i=e.normalize().mul(-o);return{dx:i.x,dy:i.y}}function ev(e,t){const n=t.sub(e),o=n.len();if(0===o)return t.clone();const i=Math.round(Math.atan2(n.y,n.x)/KF)*KF;return e.add(new $C(Math.cos(i)*o,Math.sin(i)*o))}function tv(e,t){return{...e,x:e.x+t.x,y:e.y+t.y}}function nv(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function ov(e){if(!e||"object"!=typeof e)return null;const t=e,n=nv(t.dx,NaN),o=nv(t.dy,NaN);return Number.isFinite(n)&&Number.isFinite(o)?t.dx===n&&t.dy===o?e:{dx:n,dy:o}:null}function iv(e,t){if(!Array.isArray(e))return t;const n=new Set,o=e.map((e,t)=>function(e,t,n){if(!e||"object"!=typeof e)return null;const o=e,i=new Set,r=Array.isArray(o.nodes)?o.nodes.map((e,t)=>((e,t,n)=>{if(!e||"object"!=typeof e)return null;const o=e,i=nv(o.x,NaN),r=nv(o.y,NaN);return Number.isFinite(i)&&Number.isFinite(r)?{id:rv("string"==typeof o.id&&o.id.length>0?o.id:`node:${t}`,n),x:i,y:r,kind:(s=o.kind,"string"==typeof s&&RF.includes(s)?o.kind:"corner"),in:ov(o.in),out:ov(o.out)}:null;var s})(e,t,i)).filter(e=>null!==e):[];return 0===r.length?null:{id:rv("string"==typeof o.id&&o.id.length>0?o.id:`subpath:${t}`,n),closed:"boolean"==typeof o.closed&&o.closed,nodes:r}}(e,t,n)).filter(e=>null!==e);return o.length>0?o:t}function rv(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}:${n}`);)n+=1;const o=`${e}:${n}`;return t.add(o),o}function sv(e,t,n){const o=n.sub(t),i=o.len2();if(0===i)return e.dist2(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/i));return e.dist2(t.add(o.mul(s)))}function av(e,t,n,o){const i=t.sub(e),r=o.sub(n),s=i.x*r.y-i.y*r.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=(a.x*r.y-a.y*r.x)/s,l=(a.x*i.y-a.y*i.x)/s;return d>=0&&d<=1&&l>=0&&l<=1?d:null}function dv(e,t){const n=t(kI(e)),o=e.in?t(CI(e)):null,i=e.out?t(TI(e)):null;return{...II(e),x:n.x,y:n.y,in:o?{dx:o.x-n.x,dy:o.y-n.y}:null,out:i?{dx:i.x-n.x,dy:i.y-n.y}:null}}function lv(){return`node:${ZF+=1}`}function cv(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function uv(e,t,n,o){const i=(HI(t.props.subpaths,n)?.nodes.filter(e=>e.id!==o))?.at(-1);return i?e.computeShapeLocalToPageTransform(t).applyToPoint(new $C(i.x,i.y)):null}function pv(e,t){const n=t.sub(e),o=n.len();if(0===o)return t.clone();const i=Math.round(Math.atan2(n.y,n.x)/GF)*GF;return e.add(new $C(Math.cos(i)*o,Math.sin(i)*o))}function hv(e,t){return t.previewNodeId?e.map(e=>e.id===t.subpathId?{...e,nodes:e.nodes.filter(e=>e.id!==t.previewNodeId)}:e):vI(e)}function gv(e,t){return HI(e.props.subpaths,t.subpathId)?.nodes.filter(e=>e.id!==t.previewNodeId).length??0}function fv(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6}function mv(e){return UI(e.shape,e.localToPage).filter(e=>e.closed&&e.nodes.length>=3).map(e=>(e=>{const t=[];for(const n of e){const e=[n.x,n.y],o=t[t.length-1];o&&fv(o,e)||t.push(e)}return t.length>1&&fv(t[0],t[t.length-1])&&t.pop(),t.length>=3?t:null})(LI(e).points)).filter(e=>null!==e).map(e=>[e])}function yv(e){const t=e.length>1&&fv(e[0],e[e.length-1])?e.slice(0,-1):e;return t.length<3?null:{id:`boolean-subpath:${iO+=1}`,closed:!0,nodes:t.map(([e,t])=>({id:`boolean-node:${rO+=1}`,x:e,y:t,kind:"corner"}))}}function Sv(){return{id:"path.floating-node-snap",items:[{kind:"button",id:"path.floating-node.snap",actionId:dO,label:"Snap nodes",shortcut:"Mod+'",icon:"magnet",dataUi:"floating-path-node-snap-button"}]}}function bv(){return{id:"path.floating-edit-session",items:[{kind:"button",id:"path.floating-edit.done",actionId:aO,label:"Done editing",icon:"check",dataUi:"floating-path-edit-done-button"}]}}function xv({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:o}){return[{id:`${o}.style-fill`,items:[{kind:"color-input",id:`${o}.fill`,actionId:e,label:"Fill",fallback:"#f8fafc",presets:bO.map(e=>({...e,dataUi:`${o}-fill-${e.id}-button`})),dataUi:`${o}.fill`}]},{id:`${o}.style-stroke`,items:[{kind:"color-input",id:`${o}.stroke`,actionId:t,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:xO.map(e=>({...e,dataUi:`${o}-stroke-${e.id}-button`})),dataUi:`${o}.stroke`}]},{id:`${o}.style-stroke-width`,items:[{kind:"text-input",id:`${o}.stroke-width`,actionId:n,label:"Stroke width",placeholder:"3",suffix:"Px",validate:Mv,dataUi:`${o}-stroke-width-control`}]}]}function wv(e){return{id:`path.set-${e}`,getAvailability:e=>"path"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const o of e){if(!gI(o))continue;const e=o.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!U(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const o=Cv(e,n);if(void 0===o)return;const i=t.selection.selectedShapes.filter(gI).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:o}}));i.length>0&&t.editor.commands.updateShapes(i,{source:"user"})}}}function Iv(e){return{id:`path.default-${e}`,getAvailability:e=>"path"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("path")[e],run({context:t,value:n}){const o=Cv(e,n);void 0!==o&&t.editor.updateDefaultShapeProps("path",{[e]:o})}}}function Pv(e,t){return{id:e,getAvailability(e){const n=uP(e.editor);return n?!n.shape.isLocked&&((e,t,n)=>null!==GI(e,t,n))(n.shape.props.subpaths,n.selection.nodes,t)?"enabled":"disabled":"inapplicable"},run({context:e}){const n=uP(e.editor);n&&!n.shape.isLocked&&ZP(e.editor,t)}}}function vv(e){return{id:`path.boolean.${e}`,getAvailability:e=>"path"!==e.selection.commonShapeType?"inapplicable":kv(e).length>=2?"enabled":"disabled",run({context:t}){const n=kv(t),o=n[0];if(!o||n.length<2)return;const i=((e,t,n)=>{const o=function(e,t){const n=t.map(mv).filter(e=>e.length>0);return 0===n.length?[]:((e,t)=>{const[n,...o]=t;if(!n)return[];if(0===o.length)return n;switch(e){case"union":return(0,oO.union)(n,...o);case"subtract":return(0,oO.difference)(n,...o);case"intersect":return(0,oO.intersection)(n,...o);case"xor":return(0,oO.xor)(n,...o)}})(e,n).flatMap(e=>e).map(yv).filter(e=>null!==e)}(e,t);return 0===o.length?null:zI(o,{...n,fillRule:"evenodd"})})(e,n.map(e=>({shape:e,localToPage:t.editor.computeShapeLocalToPageTransform(e)})),{fill:o.props.fill,stroke:o.props.stroke,strokeWidth:o.props.strokeWidth});i&&t.editor.operations.run({kind:`path.boolean.${e}`,label:"shape.boolean",source:"user",history:"record"},()=>{const[e]=t.editor.commands.createShapes([{type:"path",x:i.x,y:i.y,parentId:o.parentId,props:{...o.props,subpaths:i.subpaths,fillRule:"evenodd"}}],{source:"user"});t.editor.commands.deleteShapes(n.map(e=>e.id),{source:"user"}),e&&t.editor.commands.setSelectedShapeIds([e.id],{source:"system"})})}}}function kv(e){return e.selection.selectedShapes.filter(gI).filter(e=>!e.isLocked).filter(e=>e.props.subpaths.some(e=>e.closed&&e.nodes.length>=3))}function Cv(e,t){return"strokeWidth"===e?Tv(t):$(t)?F(t,E("fill"===e?"fill-blue":"stroke-slate")):void 0}function Tv(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function Mv(e){return void 0!==Tv(e)}async function Ev(e){const t=await(async(e,t)=>(await Df(e,[t]))?.[0]??null)(vR,e);return t instanceof Blob?t:null}async function Bv(e){await(async(e,t)=>{const n=await Of();n&&await new Promise((o,i)=>{const r=n.transaction(e,"readwrite"),s=r.objectStore(e);r.addEventListener("complete",()=>o()),r.addEventListener("abort",()=>i(r.error)),r.addEventListener("error",()=>i(r.error)),s.delete(t)})})(vR,e)}function Av(e,t){const n=e.getAsset(t);if(!fw(n)||"local"!==n.props.source.kind)return null;const{storageKey:o}=n.props.source;return o.length>0?o:null}function Rv(e){const t=new Set;for(const n of e.getAssets())fw(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&t.add(n.props.source.storageKey);return t}function $v(e){return new Promise((t,n)=>{const o=new Image;o.addEventListener("load",()=>{t({width:o.naturalWidth||o.width,height:o.naturalHeight||o.height})}),o.addEventListener("error",()=>{n(new Error("Could not decode image file."))}),o.src=e})}async function Lv(e){const t=Ov(e)?e:e.blob,n=(Ov(e),e.name),o=Ov(e)?e.type:e.mimeType||e.blob.type,i=URL.createObjectURL(t),r=await $v(i).finally(()=>{URL.revokeObjectURL(i)}),{storageKey:s}=await async function(e){const t="undefined"!=typeof crypto&&"randomUUID"in crypto?`${IO}${crypto.randomUUID()}`:`${IO}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for image storage.");return await zf(vR,[[t,e]]),{storageKey:t}}(t);return{name:n||"Image",source:{kind:"local",storageKey:s,...!Ov(e)&&e.originalUrl?{originalUrl:e.originalUrl}:{}},mimeType:o||"image/png",fileSize:t.size,width:r.width,height:r.height}}async function Fv({name:e,url:t}){const n=await fetch(t);if(!n.ok)throw new Error(`Could not download image URL (${n.status}).`);const o=await n.blob();return Lv({blob:o,name:e||Dv(t)||"Image",mimeType:o.type||n.headers.get("content-type")||void 0,originalUrl:t})}function Ov(e){return"undefined"!=typeof File&&e instanceof File}function Dv(e){try{const t=new URL(e).pathname.split("/").filter(Boolean).at(-1);return t?decodeURIComponent(t):null}catch{return null}}function zv(e){for(const t of e)if(t.type.startsWith("image/"))return t;return null}function Uv({filename:e,url:t}){const n=document.createElement("a");n.href=t,n.download=e,n.click()}async function Nv({blob:e,filename:t}){const n=URL.createObjectURL(e);try{Uv({filename:t,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function Wv(e,t){return e.commands.createAsset({type:"image",props:{w:t.width,h:t.height,name:t.name,source:t.source,mimeType:t.mimeType,fileSize:t.fileSize,isAnimated:"image/gif"===t.mimeType}},{source:"user"})}function Xv(e,t){return e.getDocumentSnapshot().records.some(e=>"shape"===e.typeName&&e.props.assetId===t)}async function Yv({editor:e,imageObjectUrls:t,pagePoint:n,size:o,flushSnapshot:i,source:r,strategy:s="auto"}){if("file"===r.type)return Jv(r.file)?_v({editor:e,imageObjectUrls:t,input:await Lv(r.file),pagePoint:n,size:o,flushSnapshot:i}):null;if("blob"===r.type)return Jv(r.blob)?_v({editor:e,imageObjectUrls:t,input:await Lv(r),pagePoint:n,size:o,flushSnapshot:i}):null;if("copy"===s)return _v({editor:e,imageObjectUrls:t,input:await Fv(r),pagePoint:n,size:o,flushSnapshot:i});if("link"===s)return Hv({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:o,flushSnapshot:i,copyInBackground:!1});try{return await Hv({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:o,flushSnapshot:i,copyInBackground:!0})}catch{return _v({editor:e,imageObjectUrls:t,input:await Fv(r),pagePoint:n,size:o,flushSnapshot:i})}}async function Hv({copyInBackground:e,editor:t,flushSnapshot:n,imageObjectUrls:o,pagePoint:i,size:r,source:s}){const a=await(async({name:e,url:t})=>{const n=await $v(t);return{name:e||Dv(t)||"Image",source:{kind:"remote",url:t},mimeType:null,width:n.width,height:n.height}})(s),d={kind:"remote",url:s.url,...e?{copyState:{status:"pending-local-copy"}}:{}},l=await _v({editor:t,imageObjectUrls:o,input:{...a,source:d},pagePoint:i,size:r,flushSnapshot:n,altText:s.altText}),c=l?t.getShape(l):null,u=mw(c)?c.props.assetId:null;return e&&u&&Kv({assetId:u,editor:t,flushSnapshot:n,imageObjectUrls:o,source:s}),l}async function _v({editor:e,imageObjectUrls:t,input:n,pagePoint:o,size:i,flushSnapshot:r,altText:s}){const a="local"===n.source.kind?n.source.storageKey:null;a&&await t.preload(a);let d=null;try{const t=Wv(e,n);d=t.id;const a=i??(({height:e,width:t})=>{const n=Math.min(1,360/Math.max(t,e));return{w:Math.max(24,Math.round(t*n)),h:Math.max(24,Math.round(e*n))}})({width:t.props.w,height:t.props.h}),l=e.viewportPageBoundsSignal.get(),c=o??l?.center??e.screenToPage(new $C(360,240)),[u]=e.commands.createShapes([{type:"image",x:Math.round(c.x-a.w/2),y:Math.round(c.y-a.h/2),props:{...a,assetId:t.id,crop:null,altText:s??n.name}}],{source:"user"});return u?(e.commands.setSelectedShapeIds([u.id],{source:"user"}),await(r?.()),u.id):null}catch(l){throw d&&e.commands.deleteAsset(d,{source:"system"}),a&&(t.release(a),await Bv(a)),l}}async function Kv({assetId:e,editor:t,flushSnapshot:n,imageObjectUrls:o,source:i}){try{const r=await Fv(i),s="local"===r.source.kind?r.source.storageKey:null;if(!s)return;await o.preload(s);const a=t.getAsset(e);if(!fw(a)||"remote"!==a.props.source.kind||a.props.source.url!==i.url||!Xv(t,e))return o.release(s),void(await Bv(s));t.commands.updateAsset({id:e,props:{w:r.width,h:r.height,name:r.name,source:r.source,mimeType:r.mimeType,fileSize:r.fileSize,isAnimated:"image/gif"===r.mimeType}},{source:"system"}),await(n?.())}catch(r){await(async({assetId:e,editor:t,error:n,flushSnapshot:o,url:i})=>{const r=t.getAsset(e);fw(r)&&"remote"===r.props.source.kind&&r.props.source.url===i&&(t.commands.updateAsset({id:e,props:{source:{kind:"remote",url:i,copyState:{status:"copy-failed",errorMessage:ek(n)}}}},{source:"system"}),await(o?.()))})({assetId:e,editor:t,error:r,flushSnapshot:n,url:i.url})}}async function qv({editor:e,file:t,imageObjectUrls:n,flushSnapshot:o}){if(!Jv(t))return;const[i]=e.getSelectedShapes();if(!mw(i)||i.isLocked)return;const r=await Lv(t);await Vv({editor:e,flushSnapshot:o,imageObjectUrls:n,input:r,nextProps:{crop:null,altText:r.name},shape:i})}async function jv({editor:e,imageObjectUrls:t}){const[n]=e.getSelectedShapes();if(!mw(n)||!n.props.assetId)return;const o=e.getAsset(n.props.assetId);if(!fw(o))return;const i="string"==typeof o.props.name&&o.props.name.length>0?o.props.name:"land-image";if("remote"===o.props.source.kind)return void(await(async({filename:e,url:t})=>{try{const n=await fetch(t);if(!n.ok)throw new Error(`Could not download image URL (${n.status}).`);await Nv({blob:await n.blob(),filename:e})}catch(n){console.warn("Could not download remote image; opening URL instead.",n),(e=>{const t=document.createElement("a");t.href=e,t.rel="noreferrer",t.target="_blank",t.click()})(t)}})({filename:i,url:o.props.source.url}));const r=o.props.source.storageKey;if(!r)return;const s=await Ev(r);if(s)return void(await Nv({blob:s,filename:i}));const a=t.resolve(r);a&&Uv({filename:i,url:a})}async function Vv({canCommit:e,editor:t,flushSnapshot:n,imageObjectUrls:o,input:i,nextProps:r,shape:s}){const a=s.props.assetId,d="local"===i.source.kind?i.source.storageKey:null;try{d&&await o.preload(d)}catch(h){throw await Zv({imageObjectUrls:o,storageKey:d}),h}const l=t.getShape(s.id);if(!mw(l)||l.isLocked||l.props.assetId!==a||e&&!e())return await Zv({imageObjectUrls:o,storageKey:d}),null;const c=`image.asset.replace:${s.id}:${PO++}`,u=t.operations.begin({kind:c,label:"image.asset.replace",source:"user",history:"record"});let p;try{const e=Wv(t,i);t.commands.updateShapes([{id:s.id,props:{assetId:e.id,...r}}],{source:"user"}),a&&!Xv(t,a)&&t.commands.deleteAsset(a,{source:"user"}),u.commit(),p={assetId:e.id,storageKey:d}}catch(h){throw u.isActive&&u.cancel(),await Zv({imageObjectUrls:o,storageKey:d}),h}return await Gv({flushSnapshot:n,operation:"image replacement"}),p}async function Gv({flushSnapshot:e,operation:t}){if(e)try{await e()}catch(n){console.warn(`Could not persist ${t}; the local change remains available.`,n)}}async function Zv({imageObjectUrls:e,storageKey:t}){t&&(e.release(t),await Bv(t))}async function Qv(e){try{const t=await fetch(e);if(!t.ok)return null;const n=await t.blob();return Jv(n)?n:null}catch{return null}}function Jv(e){return!e.type||e.type.startsWith("image/")}function ek(e){return e instanceof Error?e.message:String(e)}function tk(e){const t=globalThis.reportError;"function"!=typeof t?console.error(e):t(e)}function nk({flushSnapshot:e}={}){return{token:kO,create(){const t=function(){const e=new Map,t=new Map;let n=0,o=!1;const i=async(i,r={})=>{if(r.signal?.throwIfAborted(),o)return null;const s=e.get(i);if(s)return s;const a=t.get(i);if(a)return a;const d=n,l=Ev(i).then(t=>{if(r.signal?.throwIfAborted(),!t||o||d!==n)return null;const s=URL.createObjectURL(t);return e.set(i,s),s}).finally(()=>{t.delete(i)});return t.set(i,l),l};return{async preloadForEditor(e,t={}){t.signal?.throwIfAborted(),await Promise.all(Array.from(Rv(e)).map(e=>i(e,t)))},preload:i,resolve:t=>e.get(t)??null,resolveAssetUrl(t,n){const o=((e,t)=>{const n=e.getAsset(t);return fw(n)&&"remote"===n.props.source.kind&&n.props.source.url.length>0?n.props.source.url:null})(t,n);if(o)return o;const i=Av(t,n);return i?e.get(i)??null:null},release(n){const o=e.get(n);o&&(URL.revokeObjectURL(o),e.delete(n)),t.delete(n)},releaseAll(){o=!0,n+=1;for(const t of e.values())URL.revokeObjectURL(t);e.clear(),t.clear()}}}(),n=new Set,o=(o,i)=>{if(n.has(i))return;const r=o.getAsset(i);fw(r)&&"remote"===r.props.source.kind&&"pending-local-copy"===r.props.source.copyState?.status&&(n.add(i),Kv({assetId:i,editor:o,flushSnapshot:e,imageObjectUrls:t,source:{type:"url",url:r.props.source.url,name:r.props.name}}).finally(()=>{n.delete(i)}))};return{objectUrls:t,async cleanupAfterRestore(e,{signal:n}){n.throwIfAborted(),await(async({editor:e,objectUrls:t})=>{const n=Rv(e),o=await async function(){return(await(async e=>{const t=await Of();return t?new Promise((n,o)=>{const i=t.transaction(e,"readonly"),r=i.objectStore(e).getAllKeys();i.addEventListener("abort",()=>o(i.error)),i.addEventListener("error",()=>o(i.error)),r.addEventListener("success",()=>{n([...r.result])}),r.addEventListener("error",()=>o(r.error))}):null})("imageBlobs"))?.map(String)??[]}(),i=[];for(const r of o)n.has(r)||(t?.release(r),await Bv(r),i.push(r));return i})({editor:e,objectUrls:t}),n.throwIfAborted(),(e=>{for(const t of e.getAssets())fw(t)&&o(e,t.id)})(e)},preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>(o(e,n),t.resolveAssetUrl(e,n))}},dispose(e){e.objectUrls.releaseAll()}}}function ok(e,t,n,o){if(pw(e)!==t)return!1;const i=e.getShape(t.shapeId);return mw(i)&&!i.isLocked&&i.props.assetId===n&&((e,t)=>{if(e.props.w!==t.props.w||e.props.h!==t.props.h)return!1;const n=e.props.crop,o=t.props.crop;return n&&o?n.topLeft.x===o.topLeft.x&&n.topLeft.y===o.topLeft.y&&n.bottomRight.x===o.bottomRight.x&&n.bottomRight.y===o.bottomRight.y:n===o})(i,o)}function ik(e,t){if("undefined"!=typeof OffscreenCanvas){const n=new OffscreenCanvas(e,t),o=n.getContext("2d");if(!o)throw new Error("Could not create image smudge canvas context.");return{context:o,toBlob:e=>n.convertToBlob({type:e})}}const n=document.createElement("canvas");n.width=e,n.height=t;const o=n.getContext("2d");if(!o)throw new Error("Could not create image smudge canvas context.");return{context:o,toBlob:e=>new Promise((t,o)=>{n.toBlob(e=>{e?t(e):o(new Error("Could not encode image smudge canvas."))},e)})}}function rk({context:e,crop:t,imageHeight:n,imageWidth:o,mask:i,shape:r,strokes:s}){if(0===s.length)return;const a=_x(t),d={x:a.left*o,y:a.top*n,w:a.width*o,h:a.height*n},l=d.w/r.props.w,c=d.h/r.props.h,u=(Math.abs(l)+Math.abs(c))/2;e.save(),e.beginPath(),e.rect(d.x,d.y,d.w,d.h),e.clip(),e.lineCap="round",e.lineJoin="round";for(const p of s){const t=p.points[0];if(!t)continue;const n=ak(p.brush.opacity),o=Math.max(1,p.brush.size*u),r=p.brush.color??"#ffff00";e.globalAlpha=n,e.strokeStyle=i?"#ffffff":r,e.fillStyle=i?"#ffffff":r,e.lineWidth=o;const s=sk({cropPixelRect:d,point:t,scaleX:l,scaleY:c});if(1!==p.points.length){e.beginPath(),e.moveTo(s.x,s.y);for(const t of p.points.slice(1)){const n=sk({cropPixelRect:d,point:t,scaleX:l,scaleY:c});e.lineTo(n.x,n.y)}e.stroke()}else e.beginPath(),e.arc(s.x,s.y,o/2,0,2*Math.PI),e.fill()}e.restore()}function sk({cropPixelRect:e,point:t,scaleX:n,scaleY:o}){return{x:e.x+t.x*n,y:e.y+t.y*o}}function ak(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):.45}function dk(e){const t=e.trim();if(!t)return"Image smudged.png";const n=t.lastIndexOf(".");return n<=0?`${t} smudged.png`:`${t.slice(0,n)} smudged.png`}function lk({editor:e,flushSnapshot:t,services:n}){const o=n.get(kO);if(!o)return null;const i={start(t){const n=t?.shapeId?e.getShape(t.shapeId):e.getSelectedShapes()[0];return!(!mw(n)||n.isLocked||!n.props.assetId)&&dw({brush:t?.brush,editor:e,shape:n})},setBrush:t=>uw(e,t),cancel(){lw(e)},confirm:n=>async function({editor:e,imageObjectUrls:t,flushSnapshot:n,replace:o=!0}){const i=pw(e);if(!i)return null;const r=(e=>e.map(e=>({id:e.id,brush:{...e.brush},points:e.points.map(gw)})))(i.strokes);if(0===r.length)return cw(e),null;if(CO.has(i))return null;CO.add(i);try{return await(async({editor:e,imageObjectUrls:t,flushSnapshot:n,replace:o,session:i,strokes:r})=>{const s=e.getShape(i.shapeId);if(!mw(s)||s.isLocked||!s.props.assetId)return null;const a=e.getAsset(s.props.assetId);if(!fw(a))return null;const d=s.props.assetId,l=await(async({asset:e,imageObjectUrls:t})=>{if("remote"===e.props.source.kind)return Qv(e.props.source.url);const n=e.props.source.storageKey,o=await Ev(n);if(o)return o;const i=t.resolve(n);return i?Qv(i):null})({asset:a,imageObjectUrls:t});if(!l)return null;if(!ok(e,i,d,s)||e.getAsset(d)!==a)return null;const{imageBlob:c,maskBlob:u,height:p,width:h}=await(async({crop:e,shape:t,sourceBlob:n,strokes:o})=>{const i=await(async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{source:t,width:t.width,height:t.height,dispose(){t.close()}}}const t=URL.createObjectURL(e),n=new Image;return n.decoding="async",n.src=t,"function"==typeof n.decode?await n.decode():await new Promise((e,t)=>{n.onload=()=>e(),n.onerror=()=>t(new Error("Could not decode image."))}),{source:n,width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,dispose(){URL.revokeObjectURL(t)}}})(n);try{const n=i.width,r=i.height,s=ik(n,r);s.context.drawImage(i.source,0,0,n,r),rk({context:s.context,crop:e,imageHeight:r,imageWidth:n,mask:!1,shape:t,strokes:o});const a=ik(n,r);return rk({context:a.context,crop:e,imageHeight:r,imageWidth:n,mask:!0,shape:t,strokes:o}),{imageBlob:await s.toBlob("image/png"),maskBlob:await a.toBlob("image/png"),width:n,height:r}}finally{i.dispose()}})({crop:s.props.crop,shape:s,sourceBlob:l,strokes:r});if(!ok(e,i,d,s)||e.getAsset(d)!==a)return null;const g={shapeId:s.id,sourceAssetId:d,imageBlob:c,maskBlob:u,width:h,height:p,crop:s.props.crop?{topLeft:{...s.props.crop.topLeft},bottomRight:{...s.props.crop.bottomRight}}:null,strokes:r};if(o){const o=await(async({blob:e,canCommit:t,editor:n,flushSnapshot:o,imageObjectUrls:i,name:r,shape:s})=>Vv({editor:n,flushSnapshot:o,imageObjectUrls:i,input:await Lv({blob:e,name:r}),nextProps:{},shape:s,canCommit:t}))({blob:c,canCommit:()=>ok(e,i,d,s)&&e.getAsset(d)===a,editor:e,imageObjectUrls:t,name:dk(a.props.name),shape:s});if(!o)return null;if(!ok(e,i,o.assetId,s)){const n=pw(e),r=e.getShape(i.shapeId);return n?.shapeId===i.shapeId&&mw(r)&&r.props.assetId===o.assetId&&lw(e),await(async({assetId:e,editor:t,imageObjectUrls:n,storageKey:o})=>{!o||e&&t.getAsset(e)||(n.release(o),await Bv(o))})({assetId:o.assetId,editor:e,imageObjectUrls:t,storageKey:o.storageKey}),null}return cw(e),await Gv({flushSnapshot:n,operation:"image smudge confirmation"}),g}return cw(e),g})({editor:e,flushSnapshot:n,imageObjectUrls:t,replace:o,session:i,strokes:r})}finally{CO.delete(i)}}({editor:e,flushSnapshot:t,imageObjectUrls:o.objectUrls,replace:n?.replace??!0}),isActive:()=>!!pw(e)};return(e=>{iw(e).registerConfirmHandler(e=>i.confirm(e))})(e),{insertImage:({source:n,pagePoint:i,size:r,strategy:s})=>Yv({editor:e,imageObjectUrls:o.objectUrls,source:n,pagePoint:i,size:r,strategy:s,flushSnapshot:t}),async replaceSelectedImage({file:n}){if(!n.type.startsWith("image/"))return!1;const[i]=e.getSelectedShapes();return!(!mw(i)||i.isLocked||(await qv({editor:e,file:n,imageObjectUrls:o.objectUrls,flushSnapshot:t}),0))},downloadSelectedImageOriginal:()=>jv({editor:e,imageObjectUrls:o.objectUrls}),smudge:i}}function ck(e,t){const n=new Map;for(const o of t){if(!mw(o)||!o.props.assetId)continue;const t=e.getAsset(o.props.assetId);if(!fw(t))throw new Error(`Image asset "${o.props.assetId}" is unavailable.`);n.set(t.id,t)}return n}async function uk(e,t){const{source:n}=e.props;if("local"===n.kind){const o=await(async e=>{const t=await Ev(e);return t?wf(t):null})(n.storageKey);if(!o)throw new Error(`Could not embed local image asset "${e.id}".`);return{href:t,dataUrl:o}}if(t.startsWith("data:"))return{href:t,dataUrl:t};let o;try{o=await fetch(t)}catch(r){throw new Error(`Could not download image asset "${e.id}".`,{cause:r})}if(!o.ok)throw new Error(`Could not download image asset "${e.id}" (${o.status}).`);const i=await wf(await o.blob());if(!i)throw new Error(`Could not embed remote image asset "${e.id}".`);return{href:t,dataUrl:i}}function pk(e,t){return"local"===e.props.source.kind?t.objectUrls.resolve(e.props.source.storageKey):e.props.source.url}function hk(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function gk({editor:e,flushSnapshot:t,imports:n,services:o}){const i=o.get(kO);return i?Gk(vO,{editor:e,hostBridge:o.get(EO)??void 0,imageAssetService:i,imports:n,flushSnapshot:t}):null}function fk(e){return e.startsWith("data:image/")||/\.(?:avif|bmp|gif|jpe?g|png|svg|webp)(?:[?#].*)?$/i.test(e)}async function mk(e,t,n){const o=Array.from(e.matchAll(/\burl\(\s*(["']?)(.*?)\1\s*\)/giu),e=>e[2]?.trim()).filter(e=>!!e),i=new Map;for(const r of new Set(o)){if(r.startsWith("data:")||r.startsWith("#"))continue;const e=wk(r,t).href,o=await xk(await(await bk(e,n)).blob(),n);i.set(r,o)}return e.replace(/\burl\(\s*(["']?)(.*?)\1\s*\)/giu,(e,t,n)=>{const o=i.get(n.trim());return o?`url(${t}${o}${t})`:e})}function yk(e){const t=String.raw`\blocal\(\s*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^)]*)\s*\)`;return e.replace(new RegExp(`${t}\\s*,\\s*`,"giu"),"").replace(new RegExp(`\\s*,\\s*${t}`,"giu"),"").replace(new RegExp(t,"giu"),"")}function Sk(e,t){if(!/\burl\(\s*["']?data:/iu.test(e))throw new Error(`Font resource "${t}" has no embeddable source.`);return e}async function bk(e,t){let n;try{n=await fetch(e)}catch(o){throw new Error(`Could not download font resource "${t}".`,{cause:o})}if(!n.ok)throw new Error(`Could not download font resource "${t}" (${n.status}).`);return n}async function xk(e,t){const n=await wf(e);if(!n)throw new Error(`Could not embed font resource "${t}".`);return n}function wk(e,t){try{return t?new URL(e,t):new URL(e,globalThis.location?.href)}catch(n){throw new Error(`Could not resolve font resource URL "${e}".`,{cause:n})}}function Ik(e={}){const t=AO.filter(([t])=>!1!==e[t]).map(([t,n])=>{if("text"===t){const t=e.text;return"object"==typeof t?qd(t):n}return n});return ur(t),[...t,TR,YA,r$,JR,p$,...!1===e.image?[]:[BO],...!1===e.text?[]:[{id:"canvas-kit.text-svg-assets",requires:[GE],setup(e){const t=e.capabilities.get(GE);if(!t)throw new Error("Text font catalog capability is unavailable.");e.assets.addSvgInliners(function(e){return{async inline({exportedShapes:t,svg:n}){const o=t.filter(Us),i=o.map(e=>ys(e.props.richText)).join(""),r=new Set(o.map(e=>e.props.font)),s=[e.defaultFont,...e.fontsById.values()].filter(t=>(({definition:e,isDefault:t,svg:n,usedFontIds:o})=>{return!!e.source&&"system"!==e.source.kind&&(t&&o.has("default")||o.has(e.id)||n.includes(`font-family:${i=e.cssFamily,i.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}`));var i})({definition:t,isDefault:t===e.defaultFont,svg:n,usedFontIds:r})),a=(await Promise.all(s.map(e=>(async(e,t)=>{const{source:n}=e;if(!n||"system"===n.kind)return"";if("stylesheet"===n.kind){const o=((e,t)=>{const n=wk(e);if(t.length>0&&"fonts.googleapis.com"===n.hostname&&!n.searchParams.has("text")){const e=Array.from(new Set(t)).join("");encodeURIComponent(e).length<=1500&&n.searchParams.set("text",e)}return n.href})(n.cssUrl,t),i=await bk(o,e.id);return Sk(yk(await mk(await i.text(),i.url||o,e.id)),e.id)}return(async(e,t)=>{const n="string"==typeof e.src?Sk(yk(await mk(e.src,void 0,t)),t):`url("${await xk(new Blob([e.src],{type:"application/octet-stream"}),t)}")`,o=(e=>e?[["ascent-override",e.ascentOverride],["descent-override",e.descentOverride],["font-display",e.display],["font-feature-settings",e.featureSettings],["line-gap-override",e.lineGapOverride],["font-stretch",e.stretch],["font-style",e.style],["unicode-range",e.unicodeRange],["font-weight",e.weight]].flatMap(([e,t])=>t?[`;${e}:${t}`]:[]).join(""):"")(e.descriptors);return`@font-face{font-family:${i=e.family,`"${i.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`};src:${n}${o}}`;var i})(n,e.id)})(e,i)))).filter(e=>e.length>0);return a.length>0?((e,t)=>{const n=e.match(/^<svg\b[^>]*>/u);if(!n)throw new Error("Could not embed font resources in the generated SVG.");const o=`<style type="text/css">${i=t,i.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}</style>`;var i;return`${n[0]}${o}${e.slice(n[0].length)}`})(n,a.join("\n")):n}}}(t))}}]]}function Pk(e,t){const n=new Set;for(const o of e){if(n.has(o))throw new Error(`Duplicate ${t}: ${o}.`);n.add(o)}}function vk(e){return[...e].sort((e,t)=>(e.order??0)-(t.order??0))}function kk(e){try{e()}catch(t){const e=globalThis.reportError;try{e?e(t):console.error(t)}catch(n){console.error(n)}}}function Ck(e={}){const t=e.id??"canvas-kit",n=(e=>void 0!==e.persistence?e.persistence:function(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await(async(e={})=>{const[t,n]=await(async e=>(await Df("snapshots",e)??e.map(()=>null)).map(Xf))([Nf(e),Wf(e)]);return{documentSnapshot:t,sessionSnapshot:n}})(e);return t.throwIfAborted(),n},saveDocument:t=>Uf({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>Uf({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}({storageNamespace:e.storageNamespace??"land.canvasKit"}))(e),o=[],i=e.plugins??Ik(),r=!cr(i,IR),s=(e=>{const t=ur(e),n=[],o=[];for(const i of t)i.editor&&n.push(i.editor),i.render&&o.push(i.render);return hr(n.map(({id:e})=>e),"editor plugin id"),hr(o.map(({id:e})=>e),"render plugin id"),{plugins:t,pluginIds:t.map(({id:e})=>e),editorPlugins:n,renderPlugins:o,shapeTypes:Array.from(new Set(n.flatMap(e=>(e.shapeCapabilities??[]).map(({type:e})=>e))))}})([[[...cr(i,AA)?[]:[RA],...cr(i,MA)?[]:[BA],...r?[Lf({svgAssetInliners:o})]:[]],i]]),a=(({factories:e=[],productId:t})=>{const n=new Map,o=[],i=()=>{const e=o.splice(0).reverse();try{for(const n of e)try{n()}catch(t){Hf(t)}}finally{n.clear()}},r=(e,t)=>{if(n.has(e.token.id))throw new Error(`Duplicate product service token: ${e.token.id}.`);const i=e.create(t);return n.set(e.token.id,i),e.dispose&&o.push(()=>e.dispose?.(i)),i};try{for(const n of e)r(n,{productId:t})}catch(s){throw i(),s}return{add:e=>r(e,{productId:t}),get:e=>n.get(e.id)??null,dispose(){i()}}})({productId:t}),d=(()=>{const e=[];let t=!1;return{defer(n){t?kk(n):e.push(n)},dispose(){if(!t){t=!0;for(const t of e.splice(0).reverse())kk(t)}}}})();d.defer(()=>a.dispose());let l=null;const c=[];try{const i=(ed((u=s.renderPlugins).map(({id:e})=>e),"canvas render plugin id"),ed(u.flatMap(({shapeRenderers:e=[]})=>e.map(({type:e})=>e)),"shape renderer type"),ed(u.flatMap(({canvasOverlays:e=[]})=>e.map(({id:e})=>e)),"canvas overlay id"),ed(u.flatMap(({selectionCustomHandleRenderers:e=[]})=>e.map(({type:e})=>e)),"selection handle renderer type"),ed(u.flatMap(({domEventGuards:e=[]})=>e.map(({id:e})=>e)),"DOM event guard id"),ed(u.flatMap(({canvasProviders:e=[]})=>e.map(({id:e})=>e)),"canvas provider id"),ed(u.flatMap(({canvasComponents:e=[]})=>e.map(({id:e})=>e)),"canvas component id"),ed(u.flatMap(({shapeOpacityModifiers:e=[]})=>e.map(({id:e})=>e)),"shape opacity modifier id"),{plugins:u,canvasProviders:u.flatMap(({canvasProviders:e=[]})=>e),canvasComponents:u.flatMap(({canvasComponents:e=[]})=>e),rendererRegistry:vr(u),overlayRegistry:zr(u),domEventGuardRegistry:Gr(u)});l=(e=>{const t=function(e={}){const{plugins:t=[],...n}=e,o=(e=>({shapeUtils:e.flatMap(e=>e.shapeUtils??[]),shapeSvgExporters:e.flatMap(e=>e.shapeSvgExporters??[]),bindingUtils:e.flatMap(e=>e.bindingUtils??[]),shapeCapabilities:e.flatMap(e=>e.shapeCapabilities??[])}))(t),i=new FT({...n,shapeUtils:o.shapeUtils,shapeSvgExporters:o.shapeSvgExporters,bindingUtils:o.bindingUtils,shapeCapabilities:o.shapeCapabilities});try{return i.runtime.onDispose(((e,t)=>{const n=[];try{for(const o of t){for(const n of o.interactionHandlers??[])e.interactions.register(n);const t=o.setup?.(e);t&&n.push(t)}}catch(o){throw Ii(n),o}return()=>{const e=Ii(n);if(null!==e)throw e}})(i,t)),i}catch(r){try{i.dispose()}catch{}throw r}}({documentMeta:e.documentMeta,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new rM(e),{shortcut:"v"}),t.tools.register("hand",e=>new UT(e),{shortcut:"h"}),t.tools.setToolLocked(t.isToolLocked()),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({documentMeta:e.documentMeta?{...e.documentMeta}:void 0,editorPlugins:s.editorPlugins,resolveAssetUrl:e=>l?(({assetResolverTokens:e,assetId:t,editor:n,services:o})=>{for(const i of Yf({assetResolverTokens:e,services:o})){const e=i.resolveAssetUrl(n,t);if(e)return e}return null})({assetResolverTokens:c,assetId:e,editor:l,services:a}):null});const r=l;d.defer(()=>r.dispose());const p=n?new $O(l,n):null,h=l.getDocumentSnapshot(),g=l.getSessionSnapshot(),f=function({assetResolverTokens:e,defer:t,editor:n,persistence:o,productId:i,services:r,svgAssetInliners:s}){const a=[],d=[],l=[],c=[],u=[],p=[],h=[],g=[],f=[],m=[],y=[],S=[],b=new Map,x=new Map,w=new Map,I=[],P=[];let v=null,k=!1;const C=()=>{if(k)throw new Error("Canvas plugin setup is already sealed.")},T=()=>{if(!v)throw new Error("Canvas plugin registration is only available during setup.");return v},M={get:e=>b.has(e.id)?b.get(e.id):null,provide(e,t){C();const n=T();if(b.has(e.id))throw new Error(`Duplicate canvas plugin capability: ${e.id}.`);b.set(e.id,t),x.set(e.id,n.id)}},E={actions:{add(...e){C(),a.push(...e)},addShortcuts(...e){C(),d.push(...e)}},apis:{add(e){C(),g.push({api:e,pluginId:T().id})}},capabilities:M,chrome:{add(...e){C(),u.push(...e)}},assets:{addResolver(t){C(),e.push(t)},addSvgInliners(...e){C(),s.push(...e)}},contextMenu:{add(...e){C(),c.push(...e)}},editor:n,exports:{add(...e){C(),h.push(...e)}},imports:{add(...e){C(),p.push(...e)}},lifecycle:{beforeCommand(e){C(),m.push(e)},beforeReady(e){C(),f.push(e)},defer(e){C(),t(e)}},persistence:o,productId:i,services:{add(e){C();const t=r.add(e);return w.set(e.token.id,T().id),t},get:e=>r.get(e)},toolbar:{add(...e){C(),l.push(...e)}},ui:{addComponents(...e){C(),S.push(...e)},addProviders(...e){C(),y.push(...e)},allowPropertiesDuringEditing(e){C(),P.push(e)}}};return{install(e){if(C(),I.push(...(e.provides??[]).map(t=>({pluginId:e.id,token:t}))),e.setup){v=e;try{if(void 0!==e.setup(E))throw new Error(`Canvas plugin "${e.id}" setup must register cleanup with lifecycle.defer().`)}finally{v=null}}},seal(){C(),k=!0,Pk(a.map(({id:e})=>e),"canvas action id"),Pk(l.map(({id:e})=>e),"toolbar contribution id"),Pk(u.map(({id:e})=>e),"chrome contribution id"),Pk(c.map(({id:e})=>e),"context-menu contribution id"),Pk(p.map(({id:e})=>e),"canvas import contribution id"),Pk(h.map(({id:e})=>e),"canvas export contribution id"),Pk(h.map(({format:e})=>e),"canvas export format"),Pk(S.map(({id:e})=>e),"component id"),Pk(y.map(({id:e})=>e),"provider id"),Pk(g.map(({api:e})=>e.token.id),"product API token"),Pk(d.map(({actionId:e})=>e),"action shortcut action id"),((e,t,n,o,i)=>{const r=t.map(({actionId:e})=>e).filter(t=>!e.has(t));if(r.length>0)throw new Error(`Action shortcuts reference missing action(s): ${r.join(", ")}.`);for(const s of[...n,...o,...i]){const t=s.actionIds.filter(t=>!e.has(t));if(t.length>0)throw new Error(`Contribution "${s.id}" references missing action(s): ${t.join(", ")}.`)}})(new Set(a.map(({id:e})=>e)),d,u,c,l),(({apiDefinitions:e,capabilityValueProviders:t,declaredCapabilities:n,serviceProviders:o})=>{const i=new Map(e.map(({api:e,pluginId:t})=>[e.token.id,t]));for(const{pluginId:r,token:s}of n)if(("api"===s.kind?i.get(s.id):"service"===s.kind?o.get(s.id):t.get(s.id))!==r)throw new Error(`Canvas plugin "${r}" did not register declared capability "${s.id}".`)})({apiDefinitions:g,capabilityValueProviders:x,declaredCapabilities:I,serviceProviders:w});for(const{actionId:e,shortcut:i}of d)n.shortcuts.registerActionShortcut(e,i);const t=(()=>{const e=new Map;return{register(t,n){if(e.has(t.id))throw new Error(`Duplicate product API token: ${t.id}.`);e.set(t.id,n)},get:t=>e.get(t.id)??null}})(),o={apis:t,capabilities:M,editor:n,exportRegistry:dr(h),productId:i,services:r};for(const{api:e}of g){const n=e.create(o);null!==n&&t.register(e.token,n)}return{actionRegistry:er(a),apis:t,assetResolverTokens:[...e],beforeCommandHooks:[...m],beforeReadyHooks:[...f],components:vk(S),chromeRegistry:ir(u),contextMenuRegistry:ar(c),importRegistry:lr(p),providers:vk(y),toolbarRegistry:xr(l),canShowPropertiesDuringEditing:e=>P.some(t=>t(e))}}}}({assetResolverTokens:c,defer(e){d.defer(e)},editor:l,persistence:p,productId:t,services:a,svgAssetInliners:o});for(const e of s.plugins)f.install(e);const m=f.seal(),y=Sf({apis:m.apis,editor:l,productId:t,services:a}),S=(({editor:e,hooks:t})=>n=>{for(const o of t)o({commandId:n.commandId,context:n.context,editor:e});return n.run()})({editor:l,hooks:m.beforeCommandHooks}),b={canvasRuntime:i,actionRegistry:m.actionRegistry,chromeRegistry:m.chromeRegistry,toolbarRegistry:m.toolbarRegistry,contextMenuRegistry:m.contextMenuRegistry,importRegistry:m.importRegistry,executeCommand:S,providers:m.providers,components:m.components,chrome:e.chrome,canShowPropertiesDuringEditing:m.canShowPropertiesDuringEditing},x={abortController:new AbortController,assetResolverTokens:c,beforeReadyHooks:m.beforeReadyHooks,cleanDocumentSnapshot:h,cleanSessionSnapshot:g,controller:y,editor:l,mountedOwner:null,persistence:n,persistenceCoordinator:p,productId:t,resources:d,render:b,seedDocument:e.seedDocument,services:a,shouldSkipStoredSnapshots:e.shouldSkipStoredSnapshots,startPromise:null,state:"created"},w={controller:y,start:()=>(e=>{if("disposing"===e.state||"disposed"===e.state)return Promise.reject(new Error("Cannot start a disposing or disposed CanvasKitRuntime."));if(e.startPromise)return e.startPromise;e.state="starting";const t=(async e=>{const{assetResolverTokens:t,beforeReadyHooks:n,editor:o,persistence:i,persistenceCoordinator:r,productId:s,services:a}=e,d=e.abortController.signal,l=[],c=e=>(async(e,t,n)=>{t.throwIfAborted();try{return await new Promise((n,o)=>{const i=()=>o(t.reason);t.addEventListener("abort",i,{once:!0}),Promise.resolve().then(e).then(n,o).finally(()=>{t.removeEventListener("abort",i)})})}catch(o){t.throwIfAborted(),n.push(o)}})(e,d,l),u=e.shouldSkipStoredSnapshots?.()??!1;let p,h=!1,g={documentSnapshot:null,sessionSnapshot:null};if(!u&&i?.load){const e=await c(()=>i.load({signal:d}));e&&(g=e,h=!0)}if(d.throwIfAborted(),Bk(e),null!==g.documentSnapshot)try{o.loadDocumentSnapshot(g.documentSnapshot,{source:"system"}),p="restored"}catch(y){d.throwIfAborted(),l.push(y),Bk(e),p=Mk(e)}else p=Mk(e);d.throwIfAborted();let f=!1;if(null!==g.sessionSnapshot)try{o.loadSessionSnapshot(g.sessionSnapshot,{source:"system"}),f=!0}catch(y){d.throwIfAborted(),l.push(y),o.loadSessionSnapshot(e.cleanSessionSnapshot,{source:"system"})}o.history.clear();const m={assetResolverTokens:t,editor:o,services:a,signal:d};await c(()=>(async({assetResolverTokens:e,editor:t,signal:n,services:o})=>{await Promise.all(Yf({assetResolverTokens:e,services:o}).map(e=>e.preloadForEditor?.(t,{signal:n})))})(m)),h&&await c(()=>(async({assetResolverTokens:e,editor:t,signal:n,services:o})=>{await Promise.all(Yf({assetResolverTokens:e,services:o}).map(e=>e.cleanupAfterRestore?.(t,{signal:n})))})(m));for(const S of n)d.throwIfAborted(),await c(()=>S({editor:o,persistence:r,productId:s,services:a,signal:d,startup:{documentSource:p,sessionRestored:f,warnings:[...l]}}));return d.throwIfAborted(),!u&&r&&(r.start(),e.resources.defer(()=>r.stop())),d.throwIfAborted(),{documentSource:p,sessionRestored:f,warnings:[...l]}})(e).then(t=>(e.abortController.signal.throwIfAborted(),e.state="ready",t)).catch(t=>{throw"disposing"!==e.state&&"disposed"!==e.state&&(e.state="failed"),t});return e.startPromise=t,t})(x),dispose(){(e=>{"disposing"!==e.state&&"disposed"!==e.state&&(e.state="disposing",e.abortController.abort(),e.resources.dispose(),e.state="disposed")})(x)}};return LO.set(w,x),w}catch(p){throw d.dispose(),p}var u}function Tk(e){const t=LO.get(e);if(!t)throw new Error("CanvasKitRoot received a runtime that was not created by createCanvasKitRuntime().");return t}function Mk(e){return e.seedDocument?(e.seedDocument(e.controller),"seeded"):"empty"}function Ek(e){if("ready"!==e.state)throw new Error(`CanvasKitRoot requires a ready runtime; received runtime in "${e.state}" state. Call and await runtime.start() before rendering.`)}function Bk(e){e.editor.loadDocumentSnapshot(e.cleanDocumentSnapshot,{source:"system"}),e.editor.loadSessionSnapshot(e.cleanSessionSnapshot,{source:"system"})}function Ak({runtime:e,onControllerReady:t,onControllerDispose:n,exposeControllerOnWindow:o=!1,windowKey:i="landCanvasKit"}){const r=Tk(e);Ek(r);const[s]=qk(()=>({})),[a,d]=qk(null);return Hk(()=>(((e,t)=>{const n=Tk(e);if(Ek(n),n.mountedOwner&&n.mountedOwner!==t)throw new Error("A CanvasKitRuntime can only be mounted by one CanvasKitRoot at a time.");n.mountedOwner=t})(e,s),d(e),()=>{((e,t)=>{const n=Tk(e);n.mountedOwner===t&&(n.mountedOwner=null)})(e,s)}),[s,e]),a!==e?null:Gk(Rk,{exposeControllerOnWindow:o,internals:r,onControllerDispose:n,onControllerReady:t,windowKey:i})}function Rk({exposeControllerOnWindow:e=!1,internals:t,onControllerDispose:n,onControllerReady:o,windowKey:i="landCanvasKit"}){const[r,s]=qk(null),[a,d]=qk(!1),l=Kk(null),c=Uk(()=>l.current,[]),u=_k(()=>({isVisible:a,setIsVisible:d}),[a]),{render:p}=t,h={actionRegistry:p.actionRegistry,editor:t.editor,executeCommand:p.executeCommand,getHostElement:c,imports:p.importRegistry,services:t.services};(({controller:e,exposeControllerOnWindow:t,onControllerDispose:n,onControllerReady:o,windowKey:i})=>{const r=Xk(e=>{o?.(e)}),s=Xk(()=>{n?.()});Wk(()=>(r(e),()=>{s()}),[e]),Wk(()=>{if(!t)return;const n=window;return n[i]=e,()=>{n[i]===e&&delete n[i]}},[e,t,i])})({controller:t.controller,exposeControllerOnWindow:e,onControllerDispose:n,onControllerReady:o,windowKey:i});const g=Gk("div",{ref:l,"data-ui":"app-shell","data-canvas-kit":t.productId,className:"land-canvas-kit__shell",children:Zk("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
|
|
57
|
+
Gk(us,{canvasComponents:p.canvasRuntime.canvasComponents,canvasProviders:p.canvasRuntime.canvasProviders,domEventGuardRegistry:p.canvasRuntime.domEventGuardRegistry,onContextMenuRequest:s,overlayRegistry:p.canvasRuntime.overlayRegistry,rendererRegistry:p.canvasRuntime.rendererRegistry,showGrid:u.isVisible}),p.components.map(e=>Gk(e.component,{...h},e.id)),p.chrome?Gk($k,{activeContextMenu:r,grid:u,internals:t,onActiveContextMenuChange:s}):null,
|
|
58
|
+
Gk(Nh,{})]})});
|
|
59
|
+
return Gk(mM.Provider,{value:t.editor,children:Gk(Uh,{children:(f=p.providers,m=g,f.reduceRight((e,t)=>Gk(t.component,{children:e},t.id),m))})});var f,m}function $k({activeContextMenu:e,grid:t,internals:n,onActiveContextMenuChange:o}){const{render:i}=n,r=Ff({actionRegistry:i.actionRegistry,activeContextMenu:e,canShowPropertiesDuringEditing:i.canShowPropertiesDuringEditing,chromeRegistry:i.chromeRegistry,contextMenuRegistry:i.contextMenuRegistry,controller:n.controller,editor:n.editor,executeCommand:i.executeCommand,grid:t,onActiveContextMenuChange:o,toolbarRegistry:i.toolbarRegistry});return i.chrome?.(r)??null}function Lk(e){const[t,n]=qk(null);return Wk(()=>{let t=!0,o=null;n({options:e,state:FO});try{o=Ck(e)}catch(i){return t&&n({options:e,state:{status:"error",error:i}}),()=>{t=!1}}return o.start().then(i=>{t&&o&&n({options:e,state:{status:"ready",runtime:o,startup:i}})},i=>{t&&o&&(o.dispose(),n({options:e,state:{status:"error",error:i}}))}),()=>{t=!1,o?.dispose()}},[e]),t?.options===e?t.state:FO}import{createContext as Fk,createElement as Ok,forwardRef as Dk,memo as zk,useCallback as Uk,useContext as Nk,useEffect as Wk,useEffectEvent as Xk,useId as Yk,useLayoutEffect as Hk,useMemo as _k,useRef as Kk,useState as qk,useSyncExternalStore as jk}from"react";import{Fragment as Vk,jsx as Gk,jsxs as Zk}from"react/jsx-runtime";import{EditorContent as Qk,useEditor as Jk}from"@tiptap/react";import{mergeAttributes as eC}from"@tiptap/core";import{Bold as tC}from"@tiptap/extension-bold";import{Italic as nC}from"@tiptap/extension-italic";import{Link as oC}from"@tiptap/extension-link";import{Strike as iC}from"@tiptap/extension-strike";import{TextAlign as rC}from"@tiptap/extension-text-align";import{BackgroundColor as sC,Color as aC,FontFamily as dC,FontSize as lC,LineHeight as cC,TextStyle as uC}from"@tiptap/extension-text-style";import{Underline as pC}from"@tiptap/extension-underline";import{Selection as hC}from"@tiptap/extensions/selection";import gC from"@tiptap/starter-kit";import{createPortal as fC}from"react-dom";var mC,yC=Object.create,SC=Object.defineProperty,bC=Object.getOwnPropertyDescriptor,xC=Object.getOwnPropertyNames,wC=Object.getPrototypeOf,IC=Object.prototype.hasOwnProperty,PC=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),vC=(e,t,n)=>(n=null!=e?yC(wC(e)):{},((e,t,n,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var i,r=xC(t),s=0,a=r.length;s<a;s++)IC.call(e,i=r[s])||void 0===i||SC(e,i,{get:(e=>t[e]).bind(null,i),enumerable:!(o=bC(t,i))||o.enumerable});return e})(!t&&e&&e.__esModule?n:SC(n,"default",{value:e,enumerable:!0}),e)),kC=0,CC=null,TC=null,MC=class{name;current;isEqual;lastChangedEpoch;children=new Set;constructor(t,n,o){this.name=t,this.current=n,this.isEqual=o,this.lastChangedEpoch=e()}get(){return r(this),this.current}__unsafe__getWithoutCapture(){return this.current}__unsafe__setWithoutNotify(e){this.current=e}set(n){const o=this.current;return(this.isEqual?this.isEqual(o,n):Object.is(o,n))?o:(((e,t)=>{CC&&!CC.initialAtomValues.has(e)&&CC.initialAtomValues.set(e,t)})(this,o),t(),this.lastChangedEpoch=e(),this.current=n,(e=>{CC||s([e])})(this),n)}update(e){return this.set(e(this.current))}},EC=Symbol("UNINITIALIZED"),BC=class{name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch;children=new Set;state=EC;parents=[];parentEpochs=[];constructor(t,n,o){this.name=t,this.derive=n,this.isEqual=o,this.lastChangedEpoch=e(),this.lastCheckedEpoch=-1}get(){return r(this),this.__unsafe__getWithoutCapture()}__unsafe__getWithoutCapture(){if(this.lastCheckedEpoch===e())return this.state;if(this.state!==EC&&!this.haveParentsChanged())return this.lastCheckedEpoch=e(),this.state;let n,r;o(this.selfAsChild);try{n=this.derive(this.state===EC?EC:this.state)}finally{r=i()}for(const e of this.parents)r.has(e)||e.children.delete(this.selfAsChild);this.parents=[...r],this.parentEpochs=this.parents.map(e=>e.lastChangedEpoch);for(const e of this.parents)e.children.add(this.selfAsChild);return this.state!==EC&&(this.isEqual?this.isEqual(this.state,n):Object.is(this.state,n))||(this.state=n,t(),this.lastChangedEpoch=e()),this.lastCheckedEpoch=e(),this.state}get selfAsChild(){return this._selfAsChild||(this._selfAsChild={type:"computed",notify:()=>{},source:this}),this._selfAsChild}_selfAsChild=null;haveParentsChanged(){for(let e=0;e<this.parents.length;e++){const t=this.parents[e];if(t.__unsafe__getWithoutCapture(),t.lastChangedEpoch!==this.parentEpochs[e])return!0}return!1}},AC=class{name;fn;type="effect";parents=[];parentEpochs=[];lastReactedEpoch=-1;isActive=!1;scheduleEffect;constructor(e,t,n){this.name=e,this.fn=t,this.scheduleEffect=n?.scheduleEffect}selfAsChild={type:"effect",notify:()=>this.maybeSchedule()};attach(){this.isActive=!0,this.execute()}detach(){this.isActive=!1;for(const e of this.parents)e.children.delete(this.selfAsChild);this.parents=[],this.parentEpochs=[]}maybeSchedule(){this.isActive&&this.lastReactedEpoch!==e()&&(this.haveParentsChanged()?this.scheduleEffect?this.scheduleEffect(()=>this.execute()):this.execute():this.lastReactedEpoch=e())}execute(){if(this.isActive){for(const e of this.parents)e.children.delete(this.selfAsChild);o(this.selfAsChild);try{this.fn()}finally{const t=i();this.parents=[...t],this.parentEpochs=this.parents.map(e=>e.lastChangedEpoch);for(const e of this.parents)e.children.add(this.selfAsChild);this.lastReactedEpoch=e()}}}haveParentsChanged(){for(let e=0;e<this.parents.length;e++){const t=this.parents[e];if(t.__unsafe__getWithoutCapture(),t.lastChangedEpoch!==this.parentEpochs[e])return!0}return!1}},RC=class{registry=new Map;register(e){this.registry.set(e.type,e)}values(){return this.registry.values()}get(e){const t=this.registry.get(e);if(!t)throw new Error(`Missing binding util for type "${e}"`);return t}},$C=class e{x;y;constructor(e,t){this.x=e,this.y=t}add(t){return new e(this.x+t.x,this.y+t.y)}sub(t){return new e(this.x-t.x,this.y-t.y)}mul(t){return new e(this.x*t,this.y*t)}div(t){return new e(this.x/t,this.y/t)}len2(){return this.x*this.x+this.y*this.y}len(){return Math.sqrt(this.len2())}dist2(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}dist(e){return Math.sqrt(this.dist2(e))}rot(t){const n=Math.cos(t),o=Math.sin(t);return new e(this.x*n-this.y*o,this.x*o+this.y*n)}per(){return new e(-this.y,this.x)}normalize(){const t=this.len();return 0===t?new e(0,0):this.div(t)}equals(e){return this.x===e.x&&this.y===e.y}clone(){return new e(this.x,this.y)}static From(t,n){return new e(t,n)}static Zero(){return new e(0,0)}static Med(t,n){return new e((t.x+n.x)/2,(t.y+n.y)/2)}static Lrp(t,n,o){return new e(t.x+(n.x-t.x)*o,t.y+(n.y-t.y)*o)}static Dist(e,t){return e.dist(t)}static Dist2(e,t){return e.dist2(t)}static Angle(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}static Nudge(e,t,n){const o=t.sub(e),i=o.len();return 0===i?e.clone():e.add(o.mul(n/i))}static RotWith(t,n,o){const i=t.x-n.x,r=t.y-n.y,s=Math.cos(o),a=Math.sin(o);return new e(n.x+i*s-r*a,n.y+i*a+r*s)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}},LC=class e{x;y;w;h;constructor(e,t,n,o){this.x=e,this.y=t,this.w=n,this.h=o}get minX(){return this.x}get minY(){return this.y}get maxX(){return this.x+this.w}get maxY(){return this.y+this.h}get center(){return new $C(this.x+this.w/2,this.y+this.h/2)}containsPoint(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}containsBox(e){return e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return this.minX<e.maxX&&this.maxX>e.minX&&this.minY<e.maxY&&this.maxY>e.minY}expand(t){return new e(this.x-t,this.y-t,this.w+2*t,this.h+2*t)}clone(){return new e(this.x,this.y,this.w,this.h)}static FromPoints(t){let n=1/0,o=1/0,i=-1/0,r=-1/0;for(const e of t)n=Math.min(n,e.x),o=Math.min(o,e.y),i=Math.max(i,e.x),r=Math.max(r,e.y);return new e(n,o,i-n,r-o)}},FC=class e{a;b;c;d;e;f;constructor(e,t,n,o,i,r){this.a=e,this.b=t,this.c=n,this.d=o,this.e=i,this.f=r}static Identity(){return new e(1,0,0,1,0,0)}static Translate(t,n){return new e(1,0,0,1,t,n)}static Rotate(t){const n=Math.cos(t),o=Math.sin(t);return new e(n,o,-o,n,0,0)}static SkewX(t){return new e(1,0,Math.tan(t),1,0,0)}static Scale(t,n){return new e(t,0,0,n,0,0)}compose(t){return new e(this.a*t.a+this.c*t.b,this.b*t.a+this.d*t.b,this.a*t.c+this.c*t.d,this.b*t.c+this.d*t.d,this.a*t.e+this.c*t.f+this.e,this.b*t.e+this.d*t.f+this.f)}applyToPoint(e){return new $C(this.a*e.x+this.c*e.y+this.e,this.b*e.x+this.d*e.y+this.f)}determinant(){return this.a*this.d-this.b*this.c}getMaximumLinearScale(){const e=this.a*this.a+this.b*this.b+this.c*this.c+this.d*this.d,t=this.determinant(),n=Math.max(0,e*e-4*t*t);return Math.sqrt((e+Math.sqrt(n))/2)}tryInvert(t=0){const n=this.determinant(),o=Number.isFinite(t)?Math.max(0,t):0;if(!Number.isFinite(n)||Math.abs(n)<=o)return null;const i=1/n;return new e(this.d*i,-this.b*i,-this.c*i,this.a*i,(this.c*this.f-this.d*this.e)*i,(this.b*this.e-this.a*this.f)*i)}invert(){return this.tryInvert()??e.Identity()}toCssString(){return`matrix(${this.a},${this.b},${this.c},${this.d},${this.e},${this.f})`}toSvgString(){return`matrix(${this.a} ${this.b} ${this.c} ${this.d} ${this.e} ${this.f})`}static ForShape(t,n,o,i=1,r=1,s=0){const a=e.Translate(t,n),d=0===o?e.Identity():e.Rotate(o),l=0===s?e.Identity():e.SkewX(s),c=1===i&&1===r?e.Identity():e.Scale(i,r);return a.compose(d).compose(l).compose(c)}},OC=class{values=new Map;disposers=[];isDisposed=!1;revision=a("editor.runtime.revision",0);revisionSignal=this.revision;notify(){this.revision.set(this.revision.get()+1)}provide(e,t,n){if(this.isDisposed)throw new Error("Cannot provide an editor runtime after disposal.");if(this.values.has(e.id))throw new Error(`Editor runtime already provided: ${e.id}`);return this.values.set(e.id,t),n&&this.disposers.push(()=>n(t)),t}get(e){return this.values.get(e.id)??null}require(e){const t=this.get(e);if(null===t)throw new Error(`Missing editor runtime: ${e.id}`);return t}onDispose(e){this.isDisposed?e():this.disposers.push(e)}dispose(){if(this.isDisposed)return;this.isDisposed=!0;let e=null;try{for(const n of this.disposers.splice(0).reverse())try{n()}catch(t){e??=t}}finally{this.values.clear()}if(null!==e)throw e}},DC="document:main",zC="page:default",UC="session:main",NC={x:0,y:0,z:1},WC=class{registry=new Map;register(e){this.registry.set(e.type,e)}has(e){return this.registry.has(e)}values(){return this.registry.values()}get(e){const t=this.registry.get(e);if(!t)throw new Error(`Missing shape util for type "${e}"`);return t}},XC=["fill-blue","fill-green","fill-red","fill-amber","fill-white","fill-slate","stroke-blue","stroke-green","stroke-red","stroke-orange","stroke-slate","stroke-muted","text-slate","text-blue","text-green","text-red"],YC=Object.fromEntries(XC.map(e=>[e,`--land-shape-${e}`])),HC={"fill-blue":"#dbeafe","fill-green":"#dcfce7","fill-red":"#fee2e2","fill-amber":"#fff7ed","fill-white":"#f8fafc","fill-slate":"#e2e8f0","stroke-blue":"#1d4ed8","stroke-green":"#15803d","stroke-red":"#dc2626","stroke-orange":"#ea580c","stroke-slate":"#334155","stroke-muted":"#94a3b8","text-slate":"#0f172a","text-blue":"#1d4ed8","text-green":"#15803d","text-red":"#dc2626"},_C=class{registry=new Map;register(e){this.registry.set(e.type,e)}get(e){return this.registry.get(e)??null}has(e){return this.registry.has(e)}unregister(e){return this.registry.delete(e)}values(){return this.registry.values()}},KC=Symbol("editorStore"),qC=class{marks=new Map;undoStack=[];redoStack=[];_state=a("store.history.state",{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0});state=this._state;clear(){this.marks.clear(),this.undoStack.length=0,this.redoStack.length=0,this.publishState()}mark(e){this.marks.set(e,((e,t=[])=>({id:e,forward:{added:[],updated:[],removed:[]},parentIds:t}))(e,[...this.marks.keys()]))}append(e,t="change"){if(ee(e))if(this.marks.size>0)for(const[n,o]of this.marks.entries())this.marks.set(n,re(o,e));else this.undoStack.push(se(t,e)),this.redoStack.length=0,this.publishState()}bailToMark(e){const t=this.marks.get(e);if(!t)return null;if(this.marks.delete(e),!ee(t.forward))return null;const n=oe(t.forward);for(const o of t.parentIds){const e=this.marks.get(o);e&&this.marks.set(o,re(e,n))}return n}squashToMark(e,t=e){const n=this.marks.get(e);if(!n)return null;if(this.marks.delete(e),!ee(n.forward))return null;if(n.parentIds.some(e=>this.marks.has(e)))return null;const o=se(t,n.forward);return this.undoStack.push(o),this.redoStack.length=0,this.publishState(),o}undo(){const e=this.undoStack.pop()??null;return e?(this.redoStack.push(e),this.publishState(),e):null}redo(){const e=this.redoStack.pop()??null;return e?(this.undoStack.push(e),this.publishState(),e):null}getEntries(){return this.undoStack}publishState(){this._state.set({canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length})}},jC=class{recordsSignal;draftRevisionSignal;recordSignals=new Map;listeners=new Set;transactionDepth=0;draftRecords=null;pendingSource="system";constructor(e){this.recordsSignal=a("store.records",new Map(e.map(e=>[e.id,e]))),this.draftRevisionSignal=a("store.draftRevision",0)}get(e){return this.getReadableRecords().get(e)}getActiveAtomicOperationRevision(){return this.transactionDepth>0?this.draftRevisionSignal.get():null}getActiveAtomicOperationSnapshot(){if(!this.draftRecords||0===this.transactionDepth)throw new Error("Store.getActiveAtomicOperationSnapshot() requires an active atomic operation.");return Array.from(this.draftRecords.values())}getRecordSignal(e){let t=this.recordSignals.get(e);return t||(t=d(`store.record.${e}`,()=>(this.recordsSignal.get(),this.draftRevisionSignal.get(),this.get(e))),this.recordSignals.set(e,t)),t}getAll(){if("computed"===TC?.child.type)throw new Error("Store.getAll() cannot run while deriving a computed signal. Read a keyed record or indexed query signal instead.");return Array.from(this.getReadableRecords().values())}getByScope(e){return this.getAll().filter(t=>"scope"in t&&t.scope===e)}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}atomic(e,t="system"){if(0===this.transactionDepth){let o=[];if(n(()=>{o=this.runAtomic(e,t)}),o.length>0)throw o[0];return}this.runAtomic(e,t)}runAtomic(e,t){const n=0===this.transactionDepth;let o;n&&(this.draftRecords=new Map(this.recordsSignal.get()),this.pendingSource=t),this.transactionDepth+=1;try{e()}catch(i){o=i}if(this.transactionDepth-=1,n||this.bumpDraftRevision(),n){const e=this.recordsSignal.get(),t=this.draftRecords,n=this.pendingSource;this.draftRecords=null,this.pendingSource="system",this.bumpDraftRevision();const i=t?ne(e,t):{added:[],updated:[],removed:[]};if(!o&&t&&ee(i))return this.recordsSignal.set(t),this.notifyListeners({source:n,diff:i})}if(o)throw o;return[]}put(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)t.get(n.id)!==n&&t.set(n.id,n)},t)}remove(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)if(!t.delete(n))continue},t)}replaceAll(e,t="system"){const n=new Map(e.map(e=>[e.id,e])),o=ne(this.recordsSignal.get(),n);if(!ee(o))return;this.recordsSignal.set(n);const i=this.notifyListeners({source:t,diff:o});if(i.length>0)throw i[0]}applyDiff(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e.added)t.set(n.id,n);for(const n of e.updated)t.set(n.after.id,n.after);for(const n of e.removed)t.delete(n.id)},t)}getMutableRecords(){if(!this.draftRecords)throw new Error("Store mutations must run inside store.atomic");return this.draftRecords}getReadableRecords(){return this.draftRecords??this.recordsSignal.get()}bumpDraftRevision(){this.draftRevisionSignal.set(this.draftRevisionSignal.get()+1)}notifyListeners(e){const t=[];for(const o of this.listeners)try{o(e)}catch(n){t.push(n)}return t}},VC=new Set,GC=new WeakMap,ZC=class{editor;buffer=new qC;scopeActivations=[];_state=a("editor.history.state",this.buffer.state.__unsafe__getWithoutCapture());state=this._state;constructor(e){this.editor=e,this.editor.operations.subscribe(e=>{this.handleCommit(e)})}clear(){this.buffer.clear(),this.publishEffectiveState()}activateScope(e){const t={scope:e,unsubscribe:()=>{},isActive:!0};return t.unsubscribe=e.subscribe(()=>{t.isActive&&this.publishEffectiveState()}),this.scopeActivations.push(t),this.publishEffectiveState(),()=>{this.deactivateActivation(t)}}deactivateScope(e){for(let t=this.scopeActivations.length-1;t>=0;t--){const n=this.scopeActivations[t];if(n.scope===e)return this.deactivateActivation(n),!0}return!1}getActiveScope(){return this.scopeActivations.at(-1)?.scope??null}undo(){const e=this.getActiveScope();if(e){const t=e.undo();return this.publishEffectiveState(),t}const t=this.buffer.undo();return!!t&&(this.editor.operations.run({kind:"history.undo",label:t.label,source:"history",history:"ignore"},()=>{Z(this.editor).applyDiff(t.inverse,"history"),this.editor.syncAfterDocumentRestore()}),this.publishEffectiveState(),!0)}redo(){const e=this.getActiveScope();if(e){const t=e.redo();return this.publishEffectiveState(),t}const t=this.buffer.redo();return!!t&&(this.editor.operations.run({kind:"history.redo",label:t.label,source:"history",history:"ignore"},()=>{Z(this.editor).applyDiff(t.forward,"history"),this.editor.syncAfterDocumentRestore()}),this.publishEffectiveState(),!0)}getEntries(){return this.buffer.getEntries()}handleCommit(e){"record"===e.history&&"user"===e.source&&(this.buffer.append(e.diff,e.label),this.publishEffectiveState())}deactivateActivation(e){if(!e.isActive)return;e.isActive=!1;const t=this.scopeActivations.indexOf(e);t>=0&&this.scopeActivations.splice(t,1);try{e.unsubscribe()}finally{this.publishEffectiveState()}}publishEffectiveState(){const e=this.getActiveScope(),t=e?{canUndo:(n=e.getState()).canUndo,canRedo:n.canRedo,undoDepth:n.undoDepth??(n.canUndo?1:0),redoDepth:n.redoDepth??(n.canRedo?1:0)}:this.buffer.state.__unsafe__getWithoutCapture();var n,o,i;((o=this._state.__unsafe__getWithoutCapture()).canUndo!==(i=t).canUndo||o.canRedo!==i.canRedo||o.undoDepth!==i.undoDepth||o.redoDepth!==i.redoDepth)&&this._state.set({...t})}},QC=class{manager;state;constructor(e,t){this.manager=e,this.state=t}get id(){return this.state.id}get kind(){return this.state.kind}get source(){return this.state.source}get isActive(){return"active"===this.state.status}commit(){return this.manager.commit(this.state)}cancel(){this.manager.cancel(this.state)}},JC=class{editor;stack=[];commitListeners=new Set;commitQueue=[];nextOperationId=1;revision=0;isPublishing=!1;constructor(e){this.editor=e,Z(e).listen(e=>this.handleStoreChange(e))}begin(e){const t=e.source??"user",n=this.getActiveState(),o={id:"operation:"+this.nextOperationId++,kind:e.kind,label:e.label??e.kind,source:t,history:e.history??("user"===t?"record":"ignore"),parent:n,diff:{added:[],updated:[],removed:[]},status:"active",handle:void 0};return o.handle=new QC(this,o),this.stack.push(o),o.handle}run(e,t){const n=this.begin(e);try{const e=t();return n.commit(),e}catch(o){throw n.isActive&&n.cancel(),o}}getActive(){return this.getActiveState()?.handle??null}subscribe(e){return this.commitListeners.add(e),()=>{this.commitListeners.delete(e)}}commit(e){this.assertTopActive(e);const t=Ue(e.diff);if(this.stack.pop(),e.status="committed",e.parent)return e.parent.diff=ie(e.parent.diff,t),null;if(!ee(t))return null;const n={id:e.id,revision:++this.revision,kind:e.kind,label:e.label,source:e.source,history:e.history,diff:t,snapshot:We(this.editor.getDocumentSnapshot()),sessionSnapshot:Xe(this.editor.getSessionSnapshot())};return this.enqueueCommit(n),n}cancel(e){this.assertTopActive(e);const t=Ue(e.diff);ee(t)&&(Z(this.editor).applyDiff(oe(t),e.source),this.editor.syncAfterDocumentRestore()),this.stack.pop(),e.status="cancelled"}handleStoreChange(e){const t=((e,t)=>({added:e.added.filter(t),updated:e.updated.filter(e=>t(e.before)&&t(e.after)),removed:e.removed.filter(t)}))(e.diff,b);if(!ee(t))return;const n=this.getActiveState();if(n)return void(n.diff=ie(n.diff,t));const o=Ue(t);ee(o)&&this.enqueueCommit({id:"operation:"+this.nextOperationId++,revision:++this.revision,kind:"editor.change",label:"change",source:e.source,history:"user"===e.source?"record":"ignore",diff:o,snapshot:We(this.editor.getDocumentSnapshot()),sessionSnapshot:Xe(this.editor.getSessionSnapshot())})}getActiveState(){return this.stack.at(-1)??null}assertTopActive(e){if("active"!==e.status)throw new Error(`Editor operation "${e.kind}" is no longer active.`);if(this.getActiveState()!==e)throw new Error(`Editor operation "${e.kind}" must be completed in LIFO order.`)}enqueueCommit(e){if(this.commitQueue.push(e),!this.isPublishing){this.isPublishing=!0;try{for(;this.commitQueue.length>0;){const e=this.commitQueue.shift();for(const n of this.commitListeners)try{n(e)}catch(t){Ye(t)}}}finally{this.isPublishing=!1}}}},eT=class{},tT=class{editor;constructor(e){this.editor=e}getConflictingBindings(e){const t=this.getExclusiveBindingKey(e);return t?this.getAllBindings().filter(n=>n.id!==e.id&&n.type===e.type&&this.getExclusiveBindingKey(n)===t):[]}canBind(e){const t=this.editor.getShape(e.fromId),n=this.editor.getShape(e.toId);return!(!t||!n)&&(this.editor.getBindingUtil(e).canBind?.(this.editor,e,{fromShape:t,toShape:n})??!0)}syncCreatedBinding(e,t){const n=this.editor.getBindingUtil(e).onBindingCreate?.(this.editor,e);this.applyEffect(n,t,e.id)}syncUpdatedBinding(e,t,n){const o=this.editor.getBindingUtil(t).onBindingUpdate?.(this.editor,e,t);this.applyEffect(o,n,t.id)}repairLoadedBindings(e){Z(this.editor).atomic(()=>{const t=new Set;for(const n of this.getAllBindings()){const o=this.editor.getShape(n.fromId),i=this.editor.getShape(n.toId);if(!o||!i){this.applyEffect(this.editor.getBindingUtil(n).onInvalidBindingLoad?.(this.editor,n),e,n.id),Z(this.editor).remove([n.id],e);continue}if(!this.canBind(n)){this.applyEffect(this.editor.getBindingUtil(n).onInvalidBindingLoad?.(this.editor,n),e,n.id),Z(this.editor).remove([n.id],e);continue}const r=this.getExclusiveBindingKey(n);if(r){if(t.has(r)){Z(this.editor).remove([n.id],e);continue}t.add(r)}const s=this.editor.getBindingUtil(n).onBindingLoad?.(this.editor,n);this.applyEffect(s,e,n.id)}},e)}handleShapeChanges(e,t){if(0===e.length)return;const n=(o=this.editor,GC.get(o)?.suppressedBindingIds??VC);var o;const i=new Set(e.map(e=>e.after.id)),r=new Set,s=new Set,a=(e,o,i,a)=>{for(const d of this.editor.queries.getBindingsForShape(e.id)){if(n.has(d.id))continue;if("ancestry"===a&&s.has(d.id))continue;const l=`${d.id}:${e.id}:${a}`;if(r.has(l))continue;r.add(l),"self"===a&&s.add(d.id);const c=d.fromId===e.id?"from":"to",u=this.editor.getBindingUtil(d).onAfterShapeChange?.(this.editor,d,{before:o,after:i,role:c,reason:a});this.applyEffect(u,t,d.id)}};for(const d of e)a(d.after,d.before,d.after,"self");for(const d of e)if(_e(d))for(const e of this.editor.getDescendantShapeIds(d.after.id)){if(i.has(e))continue;const t=this.editor.getShape(e);t&&a(t,t,t,"ancestry")}}getShapeHierarchyRootId(e){const t=He(e,this.getAllBindings(),e=>this.editor.getBindingUtil(e));return this.editor.getShape(t)?t:e}cleanupBindingsForDeletedShapes(e,t){if(0===e.length)return;const n=new Set(e),o=new Set;for(const i of e){const e=this.editor.getShape(i);if(e)for(const r of this.editor.queries.getBindingsForShape(i)){if(o.has(r.id))continue;o.add(r.id);const s=r.fromId===i?"from":"to";if("to"===s&&n.has(r.fromId)){Z(this.editor).remove([r.id],t);continue}const a=this.editor.getBindingUtil(r).onBeforeDeleteShape?.(this.editor,r,{shape:e,role:s});this.applyEffect(a,t,r.id)}}}cleanupBindings(e,t){for(const n of e){const e=this.editor.getBinding(n);if(!e)continue;const o=this.editor.getBindingUtil(e).onBeforeDeleteBinding?.(this.editor,e);this.applyEffect(o,t,e.id)}}applyEffect(e,t,n){if(!e)return;const o=new Set(e.suppressBindingIds??[]);n&&o.add(n),xe(this.editor,o,()=>{e.deleteBindingIds&&e.deleteBindingIds.length>0&&Z(this.editor).remove(Array.from(new Set(e.deleteBindingIds)),t),e.bindings&&e.bindings.length>0&&Z(this.editor).put(e.bindings,t),e.shapes&&e.shapes.length>0&&this.editor.commands.updateShapes(e.shapes.map(e=>({id:e.id,x:e.x,y:e.y,rotation:e.rotation,skewX:e.skewX,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props,meta:e.meta})),{source:t}),e.deleteShapeIds&&e.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(Array.from(new Set(e.deleteShapeIds)),{source:t})})}getAllBindings(){return Z(this.editor).getAll().filter(y).sort((e,t)=>e.id.localeCompare(t.id))}getExclusiveBindingKey(e){const t=this.editor.getBindingUtil(e).getExclusiveBindingKey?.(e);return t?`${e.type}:${t}`:null}},nT=class{editor;_viewportScreenSizeSignal=a("editor.viewportScreenSize",{w:0,h:0});viewportScreenSizeSignal=this._viewportScreenSizeSignal;constructor(e){this.editor=e}getCurrentCamera(){return this.editor.currentCameraSignal.get()}getCamera(e=this.editor.getCurrentPageId()){return this.editor.sessionSignal.get().pageCameraById[e]??NC}pageToScreen(e,t=this.editor.getCurrentPageId()){const n=this.getCamera(t);return new e.constructor((e.x-n.x)*n.z,(e.y-n.y)*n.z)}screenToPage(e,t=this.editor.getCurrentPageId()){const n=this.getCamera(t);return new e.constructor(e.x/n.z+n.x,e.y/n.z+n.y)}setCamera(e,t){const n=t?.source??"system",o=t?.pageId??this.editor.getCurrentPageId(),i=this.getCamera(o),r={x:"number"==typeof e.x?e.x:i.x,y:"number"==typeof e.y?e.y:i.y,z:Ke("number"==typeof e.z?e.z:i.z)};this.editor.updateSession({pageCameraById:{...this.editor.sessionSignal.get().pageCameraById,[o]:r}},n)}panCamera(e,t="system"){const n=this.getCurrentCamera();this.setCamera({x:n.x+e.x/n.z,y:n.y+e.y/n.z},{source:t})}zoomCameraAtScreenPoint(e,t,n="system"){const o=Ke(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,o,n)}zoomCameraToScreenPoint(e,t,n="system"){const o=Ke(t),i=this.screenToPage(e);this.setCamera({x:i.x-e.x/o,y:i.y-e.y/o,z:o},{source:n})}zoomAtViewportCenter(e,t="system"){const n=this.viewportScreenSizeSignal.get(),o=new $C(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(o,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new $C(t.w/2,t.h/2),o=this.screenToPage(n);this.editor.commands.setCamera({camera:{x:o.x-n.x,y:o.y-n.y,z:1}},{source:e})}setViewportScreenSize(e){const t={w:Math.max(0,e.w),h:Math.max(0,e.h)},n=this._viewportScreenSizeSignal.get();n.w===t.w&&n.h===t.h||this._viewportScreenSizeSignal.set(t)}},oT=new $C(24,24),iT=class{editor;constructor(e){this.editor=e}createPayloadFromSelection(){return dt(this.editor)}pastePayload(e){return this.editor.cancelInteractionForCommand(),lt(this.editor,e)}duplicateSelection(e={}){return this.editor.cancelInteractionForCommand(),((e,t={})=>{const n=dt(e);return n?lt(e,{payload:n,offset:t.offset??oT,source:t.source}):[]})(this.editor,e)}},rT=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},sT=class{editor;constructor(e){this.editor=e}buildInitialRecords(e,t,n={}){const o=this.parseInitialDocumentSnapshot(e,n),i=this.parseInitialSessionSnapshot(t);return[...o.records.length?o.records:[c(n),u()],i.records[0]??p()]}getDocumentSnapshot(){const e=this.editor.store.getAll();return{schemaVersion:2,records:[e.find(g)??c(),...this.editor.getPages(),...e.filter(S).sort((e,t)=>e.id.localeCompare(t.id)),...e.filter(f).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index):e.parentId.localeCompare(t.parentId)),...e.filter(y).sort((e,t)=>e.id.localeCompare(t.id))]}}getSessionSnapshot(){return{schemaVersion:1,records:[this.editor.sessionSignal.get()]}}loadDocumentSnapshot(e,t){const n=t?.source??"system",o=At(e,this.editor.shapeUtils,this.editor.bindingUtils);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),this.editor.editing.cancelOperation();const i=this.editor.sessionSignal.get();Z(this.editor).replaceAll([...o.records,i],n),this.syncAfterDocumentSnapshotLoad(n)}loadSessionSnapshot(e,t){const n=t?.source??"system",o=Rt(e).records[0]??p(),i=Z(this.editor).getAll().filter(b);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),this.editor.editing.cancelOperation(),Z(this.editor).replaceAll([...i,o],n),this.ensureSessionIntegrity(),this.editor.syncToolStateFromSession(n)}syncAfterDocumentRestore(){this.ensureSessionIntegrity(),this.editor.syncShapeCounter(),this.editor.syncPageCounter(),this.editor.syncBindingCounter(),this.editor.syncAssetCounter()}ensureSessionIntegrity(){const e=Z(this.editor),t=e.getAll(),n=t.filter(h).sort((e,t)=>e.index.localeCompare(t.index)),o=n[0]?.id??"page:default",i=new Set(n.map(e=>e.id)),r=t.filter(f),s=new Set(r.map(e=>e.id)),a=new Map(r.map(e=>[e.id,e])),d=new Map;for(const p of r)d.set(p.id,ot(p,a,i)??o);const l=t.find(e=>e.id===UC),c=m(l)?l:p(o),u={...c,currentPageId:i.has(c.currentPageId)?c.currentPageId:o,pageCameraById:this.repairCameraByPage(c.pageCameraById,i),pageSelectedShapeIdsById:this.repairSelectionByPage(c.pageSelectedShapeIdsById,i,s,d)};e.put([u],"system")}syncAfterDocumentSnapshotLoad(e){this.syncAfterDocumentRestore(),this.editor.history.clear(),this.editor.bindings.repairLoadedBindings(e)}repairCameraByPage(e,t){const n={};for(const o of t){const t=e[o]??NC;n[o]={x:Number.isFinite(t.x)?t.x:NC.x,y:Number.isFinite(t.y)?t.y:NC.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:NC.z))}}return n}repairSelectionByPage(e,t,n,o){const i={};for(const r of t)i[r]=Array.from(new Set((e[r]??[]).filter(e=>n.has(e)&&o.get(e)===r)));return i}parseInitialDocumentSnapshot(e,t){if(!e)return{schemaVersion:2,records:[c(t),u()]};try{return At(e,this.editor.shapeUtils,this.editor.bindingUtils)}catch(n){if(!(n instanceof rT))throw n;return{schemaVersion:2,records:[c(t),u()]}}}parseInitialSessionSnapshot(e){if(!e)return{schemaVersion:1,records:[p()]};try{return Rt(e)}catch(t){if(!(t instanceof rT))throw t;return{schemaVersion:1,records:[p()]}}}},aT=class{pressedKeyCodes=a("inputs.pressedKeyCodes",new Set);isSpacePressed=d("inputs.isSpacePressed",()=>this.pressedKeyCodes.get().has("Space"));state=a("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:$t(),screenVelocity:$t(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1});setCurrentPointerPoint(e){this.state.update(t=>{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.shiftKey===e.shiftKey&&t.altKey===e.altKey&&t.ctrlKey===e.ctrlKey&&t.metaKey===e.metaKey&&t.accelKey===e.accelKey)return t;const n=t.currentPagePoint??e.pagePoint,o=t.currentScreenPoint??e.screenPoint,i=t.currentTimestamp??e.timestamp,r=e.timestamp-i;return{...t,previousPagePoint:n,previousScreenPoint:o,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:i,currentTimestamp:e.timestamp,pageVelocity:Lt(n,e.pagePoint,r),screenVelocity:Lt(o,e.screenPoint,r),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}})}handleEvent(e){switch(e.type){case"pointer":return void this.handlePointerEvent(e);case"keyboard":return void this.handleKeyboardEvent(e);case"wheel":return void this.handleWheelEvent(e);case"cancel":return this.resetPointer(),void("blur"!==e.reason&&"dispose"!==e.reason||this.resetKeyboard())}}resetPointer(){this.state.update(e=>({...e,originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:$t(),screenVelocity:$t(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle"}))}handlePointerEvent(e){this.state.update(t=>{switch(e.name){case"pointer_down":return{...t,originPagePoint:e.pagePoint,currentPagePoint:e.pagePoint,previousPagePoint:e.pagePoint,originScreenPoint:e.screenPoint,currentScreenPoint:e.screenPoint,previousScreenPoint:e.screenPoint,currentTimestamp:e.timestamp,previousTimestamp:e.timestamp,pageVelocity:$t(),screenVelocity:$t(),pointerId:e.pointerId,pointerType:e.pointerType,buttons:e.buttons,isPointing:!0,isDragging:!1,dragPhase:"pointing",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey};case"pointer_move":{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.buttons===e.buttons&&Ft(t,e))return t;const n=t.currentPagePoint??e.pagePoint,o=t.currentScreenPoint??e.screenPoint,i=t.isDragging||(t.originPagePoint??e.pagePoint).dist2(e.pagePoint)>=9,r=t.currentTimestamp??e.timestamp,s=e.timestamp-r;return{...t,previousPagePoint:n,previousScreenPoint:o,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:r,currentTimestamp:e.timestamp,pageVelocity:Lt(n,e.pagePoint,s),screenVelocity:Lt(o,e.screenPoint,s),buttons:e.buttons,isDragging:i,dragPhase:i?"dragging":"pointing",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}case"pointer_up":case"pointer_cancel":return{...t,previousPagePoint:t.currentPagePoint,previousScreenPoint:t.currentScreenPoint,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:t.currentTimestamp,currentTimestamp:e.timestamp,pageVelocity:$t(),screenVelocity:$t(),buttons:e.buttons,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}})}handleKeyboardEvent(e){this.pressedKeyCodes.update(t=>{const n="key_down"===e.name;if(t.has(e.code)===n)return t;const o=new Set(t);return n?o.add(e.code):o.delete(e.code),o}),this.state.update(t=>Ft(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}resetKeyboard(){this.pressedKeyCodes.get().size>0&&this.pressedKeyCodes.set(new Set),this.state.update(e=>e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||e.accelKey?{...e,shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1}:e)}handleWheelEvent(e){this.state.update(t=>Ft(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},dT=class{editor;_brushBoxSignal=a("editor.brushBox",null);brushBoxSignal=this._brushBoxSignal;brushBoxActiveSignal=d("editor.brushBoxActive",()=>null!==this._brushBoxSignal.get());_bindingPreviewSignal=a("editor.bindingPreview",null);bindingPreviewSignal=this._bindingPreviewSignal;bindingPreviewActiveSignal=d("editor.bindingPreviewActive",()=>null!==this._bindingPreviewSignal.get());_terminalBindingGuidesSignal=a("editor.terminalBindingGuides",[]);terminalBindingGuidesSignal=this._terminalBindingGuidesSignal;_dropTargetShapeIdSignal=a("editor.dropTargetShapeId",null);dropTargetShapeIdSignal=this._dropTargetShapeIdSignal;_hoveredShapeIdSignal=a("editor.hoveredShapeId",null);hoveredShapeIdSignal=this._hoveredShapeIdSignal;_selectionTranslationActiveSignal=a("editor.selectionTranslationActive",!1);selectionTranslationActiveSignal=this._selectionTranslationActiveSignal;terminalBindingResolver=(e,t)=>(({rawPagePoint:e})=>({pagePoint:e.clone(),binding:null,preview:null}))(t);constructor(e){this.editor=e}setBrushBox(e){Je(this._brushBoxSignal.get(),e)||this._brushBoxSignal.set(e?e.clone():null)}setBindingPreview(e){var t,n;(t=this._bindingPreviewSignal.get())===(n=e)||(t&&n?t.terminal===n.terminal&&t.targetShapeId===n.targetShapeId&&Ge(t.rawPagePoint,n.rawPagePoint)&&Ge(t.resolvedPagePoint,n.resolvedPagePoint)&&(t.guidePath??null)===(n.guidePath??null):t===n)||this._bindingPreviewSignal.set(e?{...e,rawPagePoint:e.rawPagePoint.clone(),resolvedPagePoint:e.resolvedPagePoint.clone()}:null)}setTerminalBindingGuides(e){const t=e??[];((e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const o=e[n],i=t[n];if(!o||!i||!Ut(o,i))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(Ot))}setDropTargetShapeId(e){this._dropTargetShapeIdSignal.get()!==e&&this._dropTargetShapeIdSignal.set(e)}setHoveredShapeId(e){this._hoveredShapeIdSignal.get()!==e&&this._hoveredShapeIdSignal.set(e)}setSelectionTranslationActive(e){this._selectionTranslationActiveSignal.get()!==e&&this._selectionTranslationActiveSignal.set(e)}setSnapIndicators(e){e?this.editor.snaps.setIndicators(e):this.editor.snaps.clearIndicators()}setTerminalBindingResolver(e){this.terminalBindingResolver=e}resolveTerminalBinding(e){return this.terminalBindingResolver(this.editor,e)}clearSelectionTransients(){this.setBrushBox(null),this.setBindingPreview(null),this.setTerminalBindingGuides(null),this.setDropTargetShapeId(null),this.setHoveredShapeId(null),this.setSelectionTranslationActive(!1),this.setSnapIndicators(null)}},lT=.001,cT=class{editor;stateSignal;currentPageShapeIdsSignal;currentPageShapesSignal;currentPageShapeHierarchySignal;selectionGeometrySignal;selectionPageOutlineVerticesSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionHasRotationSignal;selectionRotationSignal;selectionRotationCenterSignal;selectionHasCompatibleRotationSignal;selectionAnchorPagePointSignal;stateAtom;shapeQuerySignals=new Map;bindingsFromShapeSignals=new Map;bindingsToShapeSignals=new Map;bindingsForShapeSignals=new Map;draftBindingIndex=null;constructor(e){this.editor=e;const t=Z(this.editor);this.stateAtom=a("editor.query.state",(e=>{const t=e.filter(h).sort((e,t)=>e.index.localeCompare(t.index)),n=e.filter(f).sort((e,t)=>e.parentId===t.parentId?((e,t)=>e.index.localeCompare(t.index))(e,t):e.parentId.localeCompare(t.parentId)),o=e.filter(y).sort(Ht),i=new Map,r=new Map,s=new Map,a=new Map(n.map(e=>[e.id,e])),d=new Map,l=new Map,c=new Map,u=new Map;for(const h of n)Nt(r,h.parentId,h.id);const p=(e,t)=>{for(const n of r.get(t)??[]){const t=a.get(n);t&&(Nt(i,e,t.id),s.set(t.id,e),p(e,t.id))}};for(const h of t)p(h.id,h.id);for(const h of o)d.set(h.id,h),Wt(l,h.fromId,h.id),Wt(c,h.toId,h.id),Wt(u,h.fromId,h.id),Wt(u,h.toId,h.id);return{pageShapeIdsByPage:i,childShapeIdsByParent:r,pageIdByShape:s,bindingById:d,bindingIdsByFromShape:l,bindingIdsByToShape:c,relatedBindingIdsByShape:u}})(Array.from(t.recordsSignal.get().values()))),this.stateSignal=this.stateAtom,t.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=d("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(this.editor.getCurrentPageId()),{isEqual:Yt}),this.currentPageShapesSignal=d("editor.query.currentPageShapes",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.getShapeSignal(e).get()).filter(e=>!!e)),this.currentPageShapeHierarchySignal=d("editor.query.currentPageShapeHierarchy",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.getShapeSignal(e).get()).filter(e=>!!e).map(e=>({id:e.id,parentId:e.parentId,type:e.type})),{isEqual:rn});const n=((e,t)=>{const n=d("editor.query.selectionGeometry",()=>on(e,t),{isEqual:en}),o=d("editor.query.selectionPageOutlineVertices",()=>n.get().outlineVertices,{isEqual:Jt}),i=d("editor.query.selectionPageBounds",()=>n.get().pageBounds,{isEqual:Je}),r=d("editor.query.selectionFrameBounds",()=>n.get().frameBounds,{isEqual:Je}),s=d("editor.query.selectionRotation",()=>n.get().rotation);return{geometry:n,pageOutlineVertices:o,pageBounds:i,frameBounds:r,hasRotation:d("editor.query.selectionHasRotation",()=>n.get().hasRotation),rotation:s,rotationCenter:d("editor.query.selectionRotationCenter",()=>n.get().rotationCenter,{isEqual:Ge}),hasCompatibleRotation:d("editor.query.selectionHasCompatibleRotation",()=>n.get().hasCompatibleRotation),selectionAnchorPagePoint:d("editor.query.selectionAnchorPagePoint",()=>n.get().selectionAnchorPagePoint,{isEqual:Ge})}})(this.editor,e=>this.getShapeGeometrySnapshot(e));this.selectionGeometrySignal=n.geometry,this.selectionPageOutlineVerticesSignal=n.pageOutlineVertices,this.selectionPageBoundsSignal=n.pageBounds,this.selectionFrameBoundsSignal=n.frameBounds,this.selectionRotationSignal=n.rotation,this.selectionHasRotationSignal=n.hasRotation,this.selectionRotationCenterSignal=n.rotationCenter,this.selectionHasCompatibleRotationSignal=n.hasCompatibleRotation,this.selectionAnchorPagePointSignal=n.selectionAnchorPagePoint}getShapeIdsForPage(e){return[...this.getShapeIdsForPageSnapshot(e)]}getShapesForPage(e){return this.getShapeIdsForPageSnapshot(e).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getChildShapeIds(e){return[...this.getChildShapeIdsSnapshot(e)]}getChildShapes(e){return this.getChildShapeIdsSnapshot(e).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getDescendantShapeIds(e){const t=[],n=new Set,o=e=>{for(const i of this.getChildShapeIdsSnapshot(e))n.has(i)||(n.add(i),t.push(i),o(i))};return o(e),t}getPageIdForShape(e){return this.stateSignal.get().pageIdByShape.get(e)??null}getPageIdForShapeParent(e){return e.startsWith("page:")?this.editor.getPage(e)?e:null:this.getPageIdForShape(e)}getDescendantPageBounds(e){const t=[];for(const n of this.getDescendantShapeIds(e)){const e=this.getShapePageBounds(n);e&&t.push(e)}return mn(t)}getShapeSubtreePageBounds(e){const t=[],n=this.getShapePageBounds(e);n&&t.push(n);for(const o of this.getDescendantShapeIds(e)){const e=this.getShapePageBounds(o);e&&t.push(e)}return mn(t)}getShapeContainment(e,t){const n=this.editor.getShape(e);if(!n)return null;const o=this.getShapeGeometrySnapshot(e),i=this.getShapeGeometrySnapshot(t);if(!o||!i)return null;const r=this.editor.getShapeUtil(n).getLocalBounds(n),s=this.getShapeQuerySignals(e).localToPageTransform.get()?.tryInvert();return s&&i.outlineVertices.length>0&&i.outlineVertices.every(e=>r.containsPoint(s.applyToPoint(e)))?"inside":o.bounds.intersects(i.bounds)?"intersecting":"outside"}getContainingShapeParentId(e){const t=Array.from(new Set(e));if(0===t.length)return null;const n=t.map(e=>this.editor.getShape(e)).filter(e=>!!e);if(n.length!==t.length)return null;const o=this.getPageIdForShape(n[0].id);if(!o)return null;if(n.some(e=>this.getPageIdForShape(e.id)!==o))return null;const i=new Set;for(const l of n){i.add(l.id);for(const e of this.getDescendantShapeIds(l.id))i.add(e)}let r=null,s=1/0,a=-1;const d=this.stateSignal.get().pageShapeIdsByPage.get(o)??[];for(let l=0;l<d.length;l+=1){const e=d[l];if(i.has(e))continue;const t=this.editor.getShape(e);if(!t||this.editor.isShapeHidden(t.id)||this.editor.isShapeOrAncestorLocked(t.id))continue;if(!Sn(t,this.editor.getShapeUtil(t)))continue;if(!n.every(e=>this.editor.canUseShapeParent(t.id,e.id)))continue;if(!n.every(e=>"inside"===this.getShapeContainment(t.id,e.id)))continue;const o=this.getShapePageBounds(t.id);if(!o)continue;const c=o.w*o.h;(!r||c<s||c===s&&l>a)&&(r=t,s=c,a=l)}return r?.id??o}getContainingShapeParentIdAtPoint(e,t){const n=Array.from(new Set(e));if(0===n.length)return null;const o=n.map(e=>this.editor.getShape(e)).filter(e=>!!e);if(o.length!==n.length)return null;const i=this.getPageIdForShape(o[0].id);if(!i)return null;if(o.some(e=>this.getPageIdForShape(e.id)!==i))return null;const r=new Set;for(const c of o){r.add(c.id);for(const e of this.getDescendantShapeIds(c.id))r.add(e)}let s=null,a=1/0,d=-1;const l=this.stateSignal.get().pageShapeIdsByPage.get(i)??[];for(let c=0;c<l.length;c+=1){const e=l[c];if(r.has(e))continue;const n=this.editor.getShape(e);if(!n||this.editor.isShapeHidden(n.id)||this.editor.isShapeOrAncestorLocked(n.id))continue;const i=this.editor.getShapeUtil(n);if(!Sn(n,i))continue;if(!o.every(e=>this.editor.canUseShapeParent(n.id,e.id)))continue;if(!this.editor.isPagePointInShapeClip(n.id,t))continue;const u=i.getLocalBounds(n),p=this.getShapeQuerySignals(n.id).localToPageTransform.get()?.tryInvert();if(!p||!u.containsPoint(p.applyToPoint(t)))continue;const h=this.getShapePageBounds(n.id);if(!h)continue;const g=h.w*h.h;(!s||g<a||g===a&&c>d)&&(s=n,a=g,d=c)}return s?.id??i}getContainingParentIdForShapeRecord(e){const t=(e=>{const t=new Set;let n=e;for(;n.startsWith("shape:");){const e=n;if(t.has(e))return null;t.add(e);const o=this.editor.getShape(e);if(!o)return null;n=o.parentId}return this.editor.getPage(n)?n:null})(e.parentId);if(!t)return null;const n=this.getShapeParentToPageTransformSnapshot(e.parentId,e=>this.editor.getShape(e));if(!n)return null;const o=Se(e,this.editor.getShapeUtil(e),n);let i=null,r=1/0,s=-1;const a=new Map;for(const u of Z(this.editor).getAll().filter(f)){const e=a.get(u.parentId)??[];e.push(u),a.set(u.parentId,e)}for(const u of a.values())u.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));const d=[],l=new Set,c=e=>{for(const t of a.get(e)??[])l.has(t.id)||(l.add(t.id),d.push(t),c(t.id))};c(t);for(let u=0;u<d.length;u+=1){const t=d[u];if(!t||t.id===e.id||this.editor.isShapeHidden(t.id)||this.editor.isShapeOrAncestorLocked(t.id))continue;const n=this.editor.getShapeUtil(t);if(!Sn(t,n))continue;if(!this.editor.canUseShapeParent(t.id,e.id))continue;const a=this.editor.computeShapePageBounds(t),l=n.getLocalBounds(t),c=this.editor.computeShapeLocalToPageTransform(t).tryInvert();if(!(c&&o.outlineVertices.length>0&&o.outlineVertices.every(e=>l.containsPoint(c.applyToPoint(e)))))continue;const p=a.w*a.h;(!i||p<r||p===r&&u>s)&&(i=t,r=p,s=u)}return i?.id??t}getShapeClipAncestorIds(e){return[...this.getShapeClipAncestorIdsSignal(e).get()]}getShapeClipAncestorIdsSignal(e){return this.getShapeQuerySignals(e).clipAncestorIds}isPagePointInShapeClip(e,t){const n=this.editor.getShape(e);if(!n)return!1;for(const o of this.getShapeClipAncestorsForShape(n,e=>this.editor.getShape(e))){const e=this.editor.getShapeUtil(o).getChildClipLocalPolygons(o);if(!e||!k(e))continue;const n=this.getShapeQuerySignals(o.id).localToPageTransform.get()?.tryInvert();if(!n)return!1;if(!T(n.applyToPoint(t),e))return!1}return!0}getShapeClippedPageBounds(e){let t=this.getShapePageBounds(e);if(!t)return null;for(const n of this.getShapeClipAncestors(e)){const e=this.getShapeChildClipPageBounds(n);if(!e)continue;const o=yn(t,e);if(!o)return null;t=o}return t}getShapeClipAncestors(e){const t=this.editor.getShape(e);return t?this.getShapeClipAncestorsForShape(t,e=>this.editor.getShape(e)):[]}getShapeClipAncestorsForShape(e,t){const n=[],o=new Set;let i=e.parentId;for(;i.startsWith("shape:");){const e=i;if(o.has(e))break;o.add(e);const r=t(e);if(!r)break;const s=this.editor.getShapeUtil(r).getChildClipLocalPolygons(r);s&&k(s)&&n.push(r),i=r.parentId}return n.reverse()}getShapeChildClipPageBounds(e){const t=this.editor.getShapeUtil(e).getChildClipLocalPolygons(e),n=t?k(t):null;if(!n)return null;const o=this.getShapeQuerySignals(e.id).localToPageTransform.get();return o?(r=o,LC.FromPoints([new $C((i=n).minX,i.minY),new $C(i.maxX,i.minY),new $C(i.maxX,i.maxY),new $C(i.minX,i.maxY)].map(e=>r.applyToPoint(e)))):null;var i,r}getShapeIdsForPageSnapshot(e){return this.stateSignal.get().pageShapeIdsByPage.get(e)??[]}getChildShapeIdsSnapshot(e){return this.stateSignal.get().childShapeIdsByParent.get(e)??[]}handleStoreChange(e){const t=Z(this.editor),o=this.stateAtom.get(),i=((e,t,n)=>{const o=t.diff.added.filter(f),i=t.diff.updated.filter(Vt),r=t.diff.removed.filter(f),s=t.diff.added.filter(y),a=t.diff.updated.filter(Gt),d=t.diff.removed.filter(y),l=o.length>0||r.length>0||i.some(({before:e,after:t})=>e.parentId!==t.parentId||e.index!==t.index),c=s.length>0||d.length>0||a.some(({before:e,after:t})=>e.fromId!==t.fromId||e.toId!==t.toId),u=s.length>0||d.length>0||a.length>0;if(!l&&!u)return e;const p={pageShapeIdsByPage:new Map(e.pageShapeIdsByPage),childShapeIdsByParent:new Map(e.childShapeIdsByParent),pageIdByShape:new Map(e.pageIdByShape),bindingById:new Map(e.bindingById),bindingIdsByFromShape:new Map(e.bindingIdsByFromShape),bindingIdsByToShape:new Map(e.bindingIdsByToShape),relatedBindingIdsByShape:new Map(e.relatedBindingIdsByShape)};let g=!1;if(l){const t=e=>{const t=n(e);return f(t)?t.index:void 0},s=new Set,a=e=>{let t=e;const o=new Set;for(;t&&!o.has(t);){o.add(t);const e=n(t);if(!e)return null;if(h(e))return e.id;if(!f(e))return null;t=e.parentId}return null};for(const n of r){jt(p.childShapeIdsByParent,n.parentId,n.id);const t=e.pageIdByShape.get(n.id);t&&s.add(t)}for(const{before:n,after:o}of i){if(n.parentId===o.parentId&&n.index===o.index)continue;jt(p.childShapeIdsByParent,n.parentId,n.id),qt(p.childShapeIdsByParent,o.parentId,o,t);const i=e.pageIdByShape.get(n.id);i&&s.add(i);const r=a(o.parentId);r&&s.add(r)}for(const e of o)qt(p.childShapeIdsByParent,e.parentId,e,t);for(const e of o){const t=a(e.parentId);t&&s.add(t)}if(s.size>0){const t=new Map(e.pageShapeIdsByPage),o=new Map(e.pageIdByShape);for(const[n,r]of e.pageIdByShape)s.has(r)&&o.delete(n);const i=(e,t)=>{const r=[];for(const s of p.childShapeIdsByParent.get(t)??[])n(s)&&(r.push(s),o.set(s,e),r.push(...i(e,s)));return r};for(const e of s){const n=i(e,e);n.length>0?t.set(e,n):t.delete(e)}p.pageShapeIdsByPage=t,p.pageIdByShape=o}g=!0}if(u){for(const e of d)g=p.bindingById.delete(e.id)||g;if(c){for(const e of d)g=Xt(p.bindingIdsByFromShape,e.fromId,e.id)||g,g=Xt(p.bindingIdsByToShape,e.toId,e.id)||g,g=Xt(p.relatedBindingIdsByShape,e.fromId,e.id)||g,g=Xt(p.relatedBindingIdsByShape,e.toId,e.id)||g;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(g=Xt(p.bindingIdsByFromShape,e.fromId,e.id)||g,g=Xt(p.bindingIdsByToShape,e.toId,e.id)||g,g=Xt(p.relatedBindingIdsByShape,e.fromId,e.id)||g,g=Xt(p.relatedBindingIdsByShape,e.toId,e.id)||g)}for(const e of s)p.bindingById.set(e.id,e),g=!0;for(const{after:e}of a)p.bindingById.set(e.id,e),g=!0;if(c){for(const e of s)g=Kt(p.bindingIdsByFromShape,e.fromId,e,"from",e=>p.bindingById.get(e))||g,g=Kt(p.bindingIdsByToShape,e.toId,e,"to",e=>p.bindingById.get(e))||g,g=Kt(p.relatedBindingIdsByShape,e.fromId,e,"related",e=>p.bindingById.get(e))||g,g=Kt(p.relatedBindingIdsByShape,e.toId,e,"related",e=>p.bindingById.get(e))||g;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(g=Kt(p.bindingIdsByFromShape,t.fromId,t,"from",e=>p.bindingById.get(e))||g,g=Kt(p.bindingIdsByToShape,t.toId,t,"to",e=>p.bindingById.get(e))||g,g=Kt(p.relatedBindingIdsByShape,t.fromId,t,"related",e=>p.bindingById.get(e))||g,g=Kt(p.relatedBindingIdsByShape,t.toId,t,"related",e=>p.bindingById.get(e))||g)}}return g?p:e})(o,e,e=>t.get(e));i!==o&&n(()=>{this.stateAtom.set(i),this.updateCachedBindingSignals(e,i)});for(const n of(e=>e.diff.removed.filter(f).map(e=>e.id))(e))this.shapeQuerySignals.delete(n)}updateCachedBindingSignals(e,t){const n=new Set,o=new Set,i=new Set,r=e=>{y(e)&&(n.add(e.fromId),o.add(e.toId),i.add(e.fromId),i.add(e.toId))};for(const s of e.diff.added)r(s);for(const s of e.diff.removed)r(s);for(const s of e.diff.updated)r(s.before),r(s.after);for(const s of n)this.bindingsFromShapeSignals.get(s)?.set(this.getBindingsFromState(t,s));for(const s of o)this.bindingsToShapeSignals.get(s)?.set(this.getBindingsToState(t,s));for(const s of i)this.bindingsForShapeSignals.get(s)?.set(this.getBindingsForState(t,s))}getShapeLocalToPageTransformSnapshot(e,t){const n=[],o=new Set;let i=e;for(;i;){if(o.has(i.id))return;if(o.add(i.id),n.push(i),i.parentId.startsWith("page:")){if(!this.editor.getPage(i.parentId))return;break}if(i=t(i.parentId),!i)return}let r=FC.Identity();for(let s=n.length-1;s>=0;s-=1){const e=n[s];e&&(r=pe(e,this.editor.getShapeUtil(e),r))}return r}getShapeParentToPageTransformSnapshot(e,t){if(e.startsWith("page:"))return this.editor.getPage(e)?FC.Identity():void 0;const n=t(e);return n?this.getShapeLocalToPageTransformSnapshot(n,t):void 0}getShapeQuerySignals(e){let t=this.shapeQuerySignals.get(e);if(!t){const n=d(`editor.query.shapePositionedBounds.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return this.editor.getShapeUtil(t).getPositionedBounds(t)},{isEqual:sn}),o=d(`editor.query.shapeLocalToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();return t?this.getShapeLocalToPageTransformSnapshot(t,e=>this.editor.getShapeSignal(e).get()):void 0},{isEqual:cn}),i=d(`editor.query.shapeGeometry.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(!t)return;const n=this.getShapeParentToPageTransformSnapshot(t.parentId,e=>this.editor.getShapeSignal(e).get());return n?Se(t,this.editor.getShapeUtil(t),n):void 0},{isEqual:un});t={positionedBounds:n,geometry:i,localToPageTransform:o,positionedToPageTransform:d(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(!t)return;const n=this.getShapeParentToPageTransformSnapshot(t.parentId,e=>this.editor.getShapeSignal(e).get());return n?he(t,this.editor.getShapeUtil(t),n):void 0},{isEqual:cn}),pageBounds:d(`editor.query.shapePageBounds.${e}`,()=>i.get()?.bounds,{isEqual:sn}),clipAncestorIds:d(`editor.query.shapeClipAncestorIds.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();return t?this.getShapeClipAncestorsForShape(t,e=>this.editor.getShapeSignal(e).get()).map(e=>e.id):[]},{isEqual:Yt})},this.shapeQuerySignals.set(e,t)}return t}getShapeGeometrySnapshot(e){return this.getShapeQuerySignals(e).geometry.get()}getShapePageBoundsSignal(e){return this.getShapeQuerySignals(e).pageBounds}getShapeLocalToPageTransformSignal(e){return this.getShapeQuerySignals(e).localToPageTransform}getShapeGeometry(e){return(e=>{if(e)return{bounds:e.bounds.clone(),center:e.center.clone(),corners:e.corners.map(e=>e.clone()),outlineVertices:e.outlineVertices.map(e=>e.clone())}})(this.getShapeGeometrySnapshot(e))}getShapeLocalToPageTransform(e){return fn(this.getShapeLocalToPageTransformSignal(e).get())}getShapeParentToPageTransform(e){return e.startsWith("page:")?this.editor.getPage(e)?FC.Identity():void 0:fn(this.getShapeQuerySignals(e).localToPageTransform.get())}getShapePageToParentTransform(e){return this.getShapeParentToPageTransform(e)?.tryInvert()??void 0}getShapePositionedToPageTransform(e){return fn(this.getShapeQuerySignals(e).positionedToPageTransform.get())}getShapePageBounds(e){return pn(this.getShapePageBoundsSignal(e).get())??void 0}getShapePositionedBounds(e){return pn(this.getShapeQuerySignals(e).positionedBounds.get())??void 0}getShapePageCenter(e){return hn(this.getShapeGeometrySnapshot(e)?.center)??void 0}getShapePageCorners(e){return gn(this.getShapeGeometrySnapshot(e)?.corners)}getShapePageOutlineVertices(e){return gn(this.getShapeGeometrySnapshot(e)?.outlineVertices)}getSelectionPageOutlineVertices(){return gn(this.selectionPageOutlineVerticesSignal.get())??[]}getSelectionPageBounds(){return pn(this.selectionPageBoundsSignal.get())??null}getSelectionFrameBounds(){return pn(this.selectionFrameBoundsSignal.get())??null}getSelectionRotation(){return this.selectionRotationSignal.get()}getSelectionHasRotation(){return this.selectionHasRotationSignal.get()}getSelectionRotationCenter(){return hn(this.selectionRotationCenterSignal.get())??null}getSelectionHasCompatibleRotation(){return this.selectionHasCompatibleRotationSignal.get()}getSelectionAnchorPagePoint(){return hn(this.selectionAnchorPagePointSignal.get())??null}getBinding(e){return this.stateSignal.get().bindingById.get(e)}getBindings(){return Array.from(this.stateSignal.get().bindingById.values()).sort(Ht)}getBindingIdsFromShape(e){return this.stateSignal.get().bindingIdsByFromShape.get(e)??[]}getBindingIdsToShape(e){return this.stateSignal.get().bindingIdsByToShape.get(e)??[]}getBindingIdsForShape(e){return this.stateSignal.get().relatedBindingIdsByShape.get(e)??[]}getBindingsFromShape(e){const t=this.getDraftBindingIndex();return t?[...t.bindingsFromShape.get(e)??[]]:[...this.getBindingsFromShapeSignal(e).get()]}getBindingsFromShapeSignal(e){let t=this.bindingsFromShapeSignals.get(e);return t||(t=a(`editor.query.bindingsFromShape.${e}`,this.getBindingsFromState(this.stateAtom.__unsafe__getWithoutCapture(),e),{isEqual:ln}),this.bindingsFromShapeSignals.set(e,t)),t}getBindingsToShape(e){const t=this.getDraftBindingIndex();return t?[...t.bindingsToShape.get(e)??[]]:[...this.getBindingsToShapeSignal(e).get()]}getBindingsToShapeSignal(e){let t=this.bindingsToShapeSignals.get(e);return t||(t=a(`editor.query.bindingsToShape.${e}`,this.getBindingsToState(this.stateAtom.__unsafe__getWithoutCapture(),e),{isEqual:ln}),this.bindingsToShapeSignals.set(e,t)),t}getBindingsForShape(e){const t=this.getDraftBindingIndex();return t?[...t.bindingsForShape.get(e)??[]]:[...this.getBindingsForShapeSignal(e).get()]}getBindingsForShapeSignal(e){let t=this.bindingsForShapeSignals.get(e);return t||(t=a(`editor.query.bindingsForShape.${e}`,this.getBindingsForState(this.stateAtom.__unsafe__getWithoutCapture(),e),{isEqual:ln}),this.bindingsForShapeSignals.set(e,t)),t}getBindingsFromState(e,t){return this.getBindingsForIds(e,e.bindingIdsByFromShape.get(t))}getBindingsToState(e,t){return this.getBindingsForIds(e,e.bindingIdsByToShape.get(t))}getBindingsForState(e,t){return this.getBindingsForIds(e,e.relatedBindingIdsByShape.get(t))}getBindingsForIds(e,t){return t&&0!==t.length?t.map(t=>e.bindingById.get(t)).filter(e=>!!e):[]}getDraftBindingIndex(){const e=Z(this.editor),t=e.getActiveAtomicOperationRevision();if(null===t)return null;if(this.draftBindingIndex?.revision===t)return this.draftBindingIndex;const n=e.getActiveAtomicOperationSnapshot().filter(y),o=new Map,i=new Map,r=new Map,s=(e,t,n)=>{const o=e.get(t);o?o.push(n):e.set(t,[n])};for(const a of n)s(o,a.fromId,a),s(i,a.toId,a),s(r,a.fromId,a),a.toId!==a.fromId&&s(r,a.toId,a);for(const a of[o,i,r])for(const e of a.values())e.sort(Ht);return this.draftBindingIndex={revision:t,bindingsFromShape:o,bindingsToShape:i,bindingsForShape:r},this.draftBindingIndex}},uT=class{entries;cellSize;cells=new Map;order=new Map;constructor(e){this.entries=e,this.cellSize=(e=>{if(0===e.length)return 256;let t=0;for(const n of e)t+=Math.max(n.queryBounds.w,n.queryBounds.h);return Math.max(16,Math.round(t/e.length)||256)})(e);for(let t=0;t<e.length;t+=1){const n=e[t];n&&(this.order.set(n,t),this.insert(n))}}cellKey(e,t){return`${e}:${t}`}insert(e){const t=Math.floor(e.queryBounds.minX/this.cellSize),n=Math.floor(e.queryBounds.minY/this.cellSize),o=Math.floor(e.queryBounds.maxX/this.cellSize),i=Math.floor(e.queryBounds.maxY/this.cellSize);for(let r=n;r<=i;r+=1)for(let n=t;n<=o;n+=1){const t=this.cellKey(n,r),o=this.cells.get(t);o?o.push(e):this.cells.set(t,[e])}}search(e){const t=Math.floor(e.minX/this.cellSize),n=Math.floor(e.minY/this.cellSize),o=Math.floor(e.maxX/this.cellSize),i=Math.floor(e.maxY/this.cellSize);if((o-t+1)*(i-n+1)>this.entries.length)return this.entries.filter(t=>t.queryBounds.intersects(e));const r=new Set,s=[];for(let a=n;a<=i;a+=1)for(let n=t;n<=o;n+=1){const t=this.cells.get(this.cellKey(n,a));if(t)for(const n of t)r.has(n)||(r.add(n),n.queryBounds.intersects(e)&&s.push(n))}return s.length>1&&s.sort((e,t)=>(this.order.get(e)??0)-(this.order.get(t)??0)),s}},pT=class{editor;queries;pageIndexSignals=new Map;constructor(e,t){this.editor=e,this.queries=t}getShapesInBounds(e,t){return this.getShapeIdsInBounds(e,t).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getShapeIdsInBounds(e,t){return this.getPageIndex(t?.pageId).search(e).filter(t=>t.shapeBounds.intersects(e)).map(e=>e.shapeId)}getShapesInViewport(e,t){return this.getShapesInBounds(e,t)}getShapeIdsInViewport(e,t){return this.getShapeIdsInBounds(e,t)}getShapeAtPoint(e,t){return this.getShapesAtPoint(e,t)[0]??null}getShapesAtPoint(e,t){const n=this.getPageIndex(t?.pageId).search((e=>new LC(e.x-.5,e.y-.5,1,1))(e)),o=[];for(let i=n.length-1;i>=0;i-=1){const r=n[i];if(!r?.pointHitTestBounds.containsPoint(e))continue;const s=this.editor.getShape(r.shapeId);if(!s)continue;if(t?.filter&&!t.filter(s))continue;const a=this.editor.getShapeUtil(s),d=this.queries.getShapeParentToPageTransform(s.parentId);if(!d)continue;const l=me(s,e,a,d),c={editor:this.editor,pagePoint:e,positionedPoint:l};("bindingTarget"===t?.hitTest?a.hitTestBindingTarget(s,l,c):a.hitTest(s,l,c))&&o.push(s)}return o}getShapesHitByLineSegment(e,t,n){const o=n?.margin??0,i=((e,t,n)=>LC.FromPoints([e,t]).expand(Math.max(.5,n)))(e,t,o),r=this.getPageIndex(n?.pageId).search(i),s=[];for(let a=r.length-1;a>=0;a-=1){const i=r[a];if(!i)continue;const d=this.queries.getShapeClippedPageBounds(i.shapeId);if(!d||!xn(e,t,d.expand(o)))continue;if(!this.doesLineSegmentIntersectShapeClip(i.shapeId,e,t,o))continue;const l=this.editor.getShape(i.shapeId);if(!l)continue;if(n?.filter&&!n.filter(l))continue;const c=this.editor.getShapeUtil(l),u=this.queries.getShapeParentToPageTransform(l.parentId);if(!u)continue;const p=me(l,e,c,u),h=me(l,t,c,u),g=this.queries.getShapePositionedToPageTransform(l.id)?.tryInvert(),f=g?o*g.getMaximumLinearScale():o;c.hitTestLineSegment(l,{editor:this.editor,pageStart:e,pageEnd:t,pageMargin:o,positionedStart:p,positionedEnd:h,positionedMargin:f})&&s.push(l)}return s}doesLineSegmentIntersectShapeClip(e,t,n,o){for(const i of this.queries.getShapeClipAncestorIds(e)){const e=this.editor.getShape(i);if(!e)return!1;const r=this.editor.getShapeUtil(e).getChildClipLocalPolygons(e);if(!r)continue;const s=this.editor.computeShapeLocalToPageTransform(e).tryInvert();if(!s)return!1;const a=o*Math.sqrt(s.a*s.a+s.b*s.b+s.c*s.c+s.d*s.d),d=s.applyToPoint(t),l=s.applyToPoint(n);if(!r.some(e=>M(d,l,e,a)))return!1}return!0}getPageIndexSignal(e){let t=this.pageIndexSignals.get(e);return t||(t=d(`editor.spatialIndex.page.${e}`,()=>{const t=this.queries.stateSignal.get().pageShapeIdsByPage.get(e)??[],n=[];for(const e of t){const t=this.editor.getShapeSignal(e).get();if(!t)continue;const o=this.editor.getShapeUtil(t),i=this.queries.getShapePageBoundsSignal(e).get();if(!i)continue;const r=this.queries.getShapePositionedToPageTransform(e);if(!r)continue;const s=wn(o.getPointHitTestBounds(t,{editor:this.editor}),r),a=LC.FromPoints([new $C(i.minX,i.minY),new $C(i.maxX,i.maxY),new $C(s.minX,s.minY),new $C(s.maxX,s.maxY)]);n.push({shapeId:e,shapeBounds:i,queryBounds:a,pointHitTestBounds:s})}return new uT(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.getCurrentPageId()){return this.getPageIndexSignal(e).get()}},hT=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],gT={corner:0,edge_midpoint:1,center:2,custom:3},fT=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],mT=["top_left","top_right","bottom_right","bottom_left"],yT=["free","aspect_ratio_locked"],ST=["free"],bT=["aspect_ratio_locked"],xT=class{editor;constructor(e){this.editor=e}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createHandleSnapshot({context:e,currentPagePoint:t,allowSelfSnap:n=!1,excludedShapeIds:o=[]}){const i=this.editor.getShape(e.shapeId),r=new Set(this.editor.getShapeIdsIncludingDescendants([e.shapeId]));this.collectBindingDrivenExcludedShapeIds([e.shapeId],r);for(const c of o)r.add(c);const s=[],a=[],d=this.getSnapScopeParentId([e.shapeId]),l=this.getCandidateShapeIds({excludedShapeIds:r,scopeParentId:d});i&&n&&this.collectSelfHandleSnapGeometry({shape:i,context:e,currentPagePoint:t,points:s,outlines:a});for(const c of l){const e=this.editor.getShape(c);e&&this.collectHandleSnapGeometry({shape:e,points:s,outlines:a})}return{points:s,outlines:a,scopeParentId:d,candidateShapeIds:l}}collectHandleSnapGeometry({shape:e,points:t,outlines:n}){const o=this.editor.getShapeUtil(e);if(!o.canSnap(e,{editor:this.editor}))return;const i=this.editor.getShapeClippedPageBounds(e.id);if(!i)return;const r=this.editor.computeShapeLocalToPageTransform(e),s=o.getHandleSnapGeometry(e);for(const c of s.points??[]){const n=vo(c),o=r.applyToPoint(n.point);this.editor.isPagePointInShapeClip(e.id,o)&&t.push({id:`${e.id}:point:${t.length}`,nodeId:e.id,point:o,kind:n.kind,weight:n.weight})}const a=s.outline;if(null===a)return;const d=this.editor.getShapeClipAncestorIds(e.id).length>0?Nn(i):(a??(l=o.getLocalBounds(e),[new $C(l.minX,l.minY),new $C(l.maxX,l.minY),new $C(l.maxX,l.maxY),new $C(l.minX,l.maxY)])).map(e=>r.applyToPoint(e));var l;d.length>0&&n.push({id:e.id,points:d})}collectSelfHandleSnapGeometry({shape:e,context:t,currentPagePoint:n,points:o,outlines:i}){const r=this.editor.getShapeUtil(e);if(!r.canSnap(e,{editor:this.editor}))return;const s=this.editor.getShapeClippedPageBounds(e.id);if(!s)return;const a=r.getHandleSnapGeometry(e),d=this.editor.computeShapeLocalToPageTransform(e),l={...t,currentPagePoint:n.clone()};for(const p of a.getSelfSnapPoints?.(l)??[]){const t=vo(p),n=d.applyToPoint(t.point);this.editor.isPagePointInShapeClip(e.id,n)&&o.push({id:`${e.id}:self-point:${o.length}`,nodeId:e.id,point:n,kind:t.kind,weight:t.weight})}const c=a.getSelfSnapOutline?.(l)??null;if(!c)return;const u=this.editor.getShapeClipAncestorIds(e.id).length>0?Nn(s):c.map(e=>d.applyToPoint(e));u.length>0&&i.push({id:e.id,points:u})}createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=Array.from(e),o=new Set(this.editor.getShapeIdsIncludingDescendants(n));this.collectBindingDrivenExcludedShapeIds(n,o);const i=[],r=[],s={rotation:t.rotation,rotationCenter:t.rotationCenter},a=this.getSnapScopeParentId(n),d=this.getCandidateShapeIds({excludedShapeIds:o,scopeParentId:a});for(const l of d){const e=this.editor.getShape(l);if(!e)continue;const n=this.editor.getShapeUtil(e);if(!n.canSnap(e,{editor:this.editor}))continue;const o=this.editor.getShapeClippedPageBounds(e.id);if(!o)continue;const a=(this.editor.getShapeClipAncestorIds(e.id).length>0?Nn(o):this.editor.getShapePageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():yo(e,s));if(0===a.length)continue;const d=LC.FromPoints(a);r.push({id:e.id,bounds:d});const c=n.getBoundsSnapGeometry(e).points,u=[];if(void 0===c)An(d).forEach((e,t)=>{u.push({point:e,kind:hT[t]??"custom"})});else{const n=this.editor.computeShapeLocalToPageTransform(e);for(const o of c){const i=vo(o),r=n.applyToPoint(i.point);this.editor.isPagePointInShapeClip(e.id,r)&&u.push({point:0===t.rotation?r:yo(r,s),kind:i.kind,weight:i.weight})}}u.forEach((t,n)=>{i.push({id:`${e.id}:${n}`,nodeId:e.id,point:t.point,kind:t.kind,weight:t.weight})})}return{points:i,pointIndex:_n(i),nodes:r,coordinateSpace:{rotation:t.rotation,rotationCenter:t.rotationCenter.clone()},scopeParentId:a,candidateShapeIds:d}}collectBindingDrivenExcludedShapeIds(e,t){const n=new Set,o=[...e];for(;o.length>0;){const e=o.pop();if(!e||n.has(e))continue;n.add(e);const i=this.editor.getShape(e);if(i)for(const n of this.editor.getBindingsForShape(e)){const r=n.fromId===e?"from":n.toId===e?"to":null;if(!r)continue;const s=this.editor.getBindingUtil(n).getGeometryDependentShapeIds?.(this.editor,n,{shape:i,role:r})??[];for(const e of s)for(const n of this.editor.getShapeIdsIncludingDescendants([e]))t.has(n)||(t.add(n),o.push(n))}}}getSnapScopeParentId(e){let t=null;for(const n of e){const e=this.editor.getShape(n);if(e)if(t){if(e.parentId!==t)return this.editor.getCurrentPageId()}else t=e.parentId}return t??this.editor.getCurrentPageId()}getCandidateShapeIds({excludedShapeIds:e,scopeParentId:t}){const n=this.editor.getCurrentPageId(),o=this.editor.renderViewportPageBoundsSignal.get(),i=new Set;if(t?.startsWith("shape:")){const e=this.editor.getShape(t);e&&this.editor.getShapeUtil(e).canSnapChildrenToSelf(e)&&i.add(e.id)}const r=t??n;for(const s of this.editor.getChildShapeIds(r))i.add(s);return(null===o?Array.from(i):this.editor.getShapeIdsInBounds(o,{pageId:n}).filter(e=>i.has(e))).filter(n=>{if(e.has(n))return!1;const i=this.editor.getShape(n);if(!i||i.parentId!==r)return n===t;const s=this.editor.getShapeClippedPageBounds(n);return!!s&&(!o||s.intersects(o))})}},wT=class{gapCache=new WeakMap;_indicatorsSignal=a("editor.snapIndicators",[]);indicatorsSignal=this._indicatorsSignal;activeSignal=d("editor.snapIndicatorsActive",()=>this._indicatorsSignal.get().length>0);snapshots;axisSnapMemory={x:null,y:null};constructor(e){this.snapshots=new xT(e)}setIndicators(e){const t=e.map(mo);io(this._indicatorsSignal.get(),t)||this._indicatorsSignal.set(t)}clearIndicators(){this._indicatorsSignal.get().length>0&&this._indicatorsSignal.set([]),this.clearAxisSnapMemory()}clearAxisSnapMemory(){this.axisSnapMemory.x=null,this.axisSnapMemory.y=null}getSwitchDistance(e){return Math.min(.25*e,2)}getReleaseThreshold(e){return 1.5*e}updateAxisSnapMemory(e,t){this.axisSnapMemory[e]=t?{type:t.type,id:t.id,candidatePointIds:"points"===t.type?t.candidatePointIds:void 0}:null}writeDebugState(e){const t=globalThis;t.__LAND_LAST_SNAP_DEBUG__=e,t.__LAND_SNAP_DEBUG__&&t.console?.debug?.("[land:snap]",e)}getNow(){return globalThis.performance?.now?.()??Date.now()}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=this.snapshots.createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t});return this.gapCache.set(n,{x:Jn(n.nodes,"x"),y:Jn(n.nodes,"y")}),n}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.snapshots.createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t})}createHandleSnapshot(e){return this.snapshots.createHandleSnapshot(e)}snapTranslate(e){const t=this.getNow(),n=zn(e.initialSelectionBounds,e.dragDelta),o=(i=An(e.initialSelectionBounds),r=e.dragDelta,i.map(e=>e.add(r)));var i,r;const s=this.gapCache.get(e.snapshot)??{x:Jn(e.snapshot.nodes,"x"),y:Jn(e.snapshot.nodes,"y")},a=this.getReleaseThreshold(e.threshold),d=this.getSwitchDistance(e.threshold),l=this.axisSnapMemory.x,c=this.axisSnapMemory.y,u={candidatePointCount:0,matchedPointCount:0},p="y"===e.lockedAxis?null:oo(Zn("x",o,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:hT,switchDistance:d,stats:u}),no("x",n,s.x,e.threshold,{previousSnapId:"gaps"===l?.type?l.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:l,switchDistance:d}),h="x"===e.lockedAxis?null:oo(Zn("y",o,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:hT,switchDistance:d,stats:u}),no("y",n,s.y,e.threshold,{previousSnapId:"gaps"===c?.type?c.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:c,switchDistance:d}),g=new $C(p?.nudge??0,h?.nudge??0),f=[];return"points"===p?.type?f.push(...ao("x",p,g,e.snapshot.coordinateSpace)):"gaps"===p?.type&&f.push(fo(p,e.snapshot.coordinateSpace,g)),"points"===h?.type?f.push(...ao("y",h,g,e.snapshot.coordinateSpace)):"gaps"===h?.type&&f.push(fo(h,e.snapshot.coordinateSpace,g)),this.setIndicators(f),this.updateAxisSnapMemory("x",p),this.updateAxisSnapMemory("y",h),this.writeDebugState({operation:"translate",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:u.candidatePointCount,candidateGapCount:("y"===e.lockedAxis?0:s.x.length)+("x"===e.lockedAxis?0:s.y.length),matchedPointCount:u.matchedPointCount,xSnapId:p?.id??null,ySnapId:h?.id??null,indicatorCount:f.length}),{nudge:g,indicators:f}}snapResize(e){const t=this.getNow(),n=Cn({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),o=Qn(n,e.resizedSelectionBounds),i="top"===n||"bottom"===n,r="left"===n||"right"===n,s=this.getReleaseThreshold(e.threshold),a=this.getSwitchDistance(e.threshold),d=this.axisSnapMemory.x,l=this.axisSnapMemory.y,c={candidatePointCount:0,matchedPointCount:0},u=i?null:Zn("x",o,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:s,switchDistance:a,stats:c}),p=r?null:Zn("y",o,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:s,switchDistance:a,stats:c}),h={x:null!==u,y:null!==p},g=new $C(u?.nudge??0,p?.nudge??0);if(e.isAspectRatioLocked&&In(f=n)!==Pn(f)&&vn(f)!==kn(f)&&(0!==g.x||0!==g.y)){const t=u&&p?Math.abs(g.x)<Math.abs(g.y)?"x":"y":u?"x":"y",o=0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h;"x"===t?(h.y=!1,g.y=g.x/o,"bottom_left"!==n&&"top_right"!==n||(g.y=-g.y)):(h.x=!1,g.x=g.y*o,"bottom_left"!==n&&"top_right"!==n||(g.x=-g.x))}var f;const m=function(e,t){const n=Cn({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY});let o=e.resizedSelectionBounds.minX,i=e.resizedSelectionBounds.maxX,r=e.resizedSelectionBounds.minY,s=e.resizedSelectionBounds.maxY;e.isResizingFromCenter?(In(n)?(o+=t.x,i-=t.x):Pn(n)&&(o-=t.x,i+=t.x),vn(n)?(r+=t.y,s-=t.y):kn(n)&&(r-=t.y,s+=t.y)):(In(n)?o+=t.x:Pn(n)&&(i+=t.x),vn(n)?r+=t.y:kn(n)&&(s+=t.y));const a=(({minX:e,minY:t,maxX:n,maxY:o})=>{const i=Math.min(e,n),r=Math.min(t,o),s=Math.max(e,n),a=Math.max(t,o);return new LC(i,r,Math.max(1,s-i),Math.max(1,a-r))})({minX:o,minY:r,maxX:i,maxY:s});if(!e.isAspectRatioLocked){const t=(({startBounds:e,bounds:t,handleId:n,scaleX:o,scaleY:i,isResizingFromCenter:r=!1})=>{const s=Tn({axis:"x",startBounds:e,bounds:t,handleId:n,scale:o,isResizingFromCenter:r}),a=Tn({axis:"y",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:r});return{scaleX:In(n)||Pn(n)?s*(t.w/Math.max(1,e.w)):o??1,scaleY:vn(n)||kn(n)?a*(t.h/Math.max(1,e.h)):i??1}})({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter});return{bounds:a,scaleX:t.scaleX,scaleY:t.scaleY}}return En({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,aspectRatio:0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h,isResizingFromCenter:e.isResizingFromCenter,scaleX:e.scaleX,scaleY:e.scaleY})}(e,g),{bounds:y}=m,S=Qn("any",y),b=[];if(h.x){const t=Zn("x",S,e.snapshot.pointIndex,1e-8,{stats:c});t&&b.push(...ho("x",t,$C.Zero(),e.snapshot.coordinateSpace,y,e.snapshot.nodes))}if(h.y){const t=Zn("y",S,e.snapshot.pointIndex,1e-8,{stats:c});t&&b.push(...ho("y",t,$C.Zero(),e.snapshot.coordinateSpace,y,e.snapshot.nodes))}return this.setIndicators(b),this.updateAxisSnapMemory("x",h.x?u:null),this.updateAxisSnapMemory("y",h.y?p:null),this.writeDebugState({operation:"resize",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:c.candidatePointCount,candidateGapCount:0,matchedPointCount:c.matchedPointCount,xSnapId:h.x?u?.id??null:null,ySnapId:h.y?p?.id??null:null,indicatorCount:b.length}),{nudge:g,bounds:y,scaleX:m.scaleX,scaleY:m.scaleY,indicators:b}}snapHandle(e){const t=this.getNow();if("none"===e.mode)return this.clearIndicators(),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null;const n="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return n?(this.setIndicators(n.indicators),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:n.indicators.length,indicatorCount:n.indicators.length}),n):(this.clearIndicators(),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null)}snapHandlePoint(e){const t=ko(e);let n=null,o=null,i=e.threshold*e.threshold;for(const a of t)for(const t of e.snapshot.points){const e=a.dist2(t.point);e>i||(i=e,n=t.point,o=a)}if(!n)for(const a of t)for(const t of e.snapshot.outlines){const e=Yn(a,t.points);!e||e.distanceSquared>i||(i=e.distanceSquared,n=e.point,o=a)}if(!n||!o)return null;const r=n.sub(o);return{snappedPagePoint:e.pagePoint.add(r),nudge:r,indicators:[(s=n,{id:po("x",[s,s],[s]),type:"points",axis:"x",line:[s.clone(),s.clone()],points:[s.clone()],rotation:0,rotationCenter:s.clone()})]};var s}snapHandleAlign(e){const t=ko(e);let n=null,o=null,i=null,r=null,s=e.threshold,a=e.threshold;for(const u of t)for(const t of e.snapshot.points){const e=Math.abs(t.point.x-u.x);e<=s&&(s=e,n=t.point,i=u);const d=Math.abs(t.point.y-u.y);d<=a&&(a=d,o=t.point,r=u)}if(!n&&!o)return null;const d=new $C(n&&i?n.x-i.x:0,o&&r?o.y-r.y:0),l=e.pagePoint.add(d),c=[];return n&&i&&c.push(go("x",i.add(d),n)),o&&r&&c.push(go("y",r.add(d),o)),{snappedPagePoint:l,nudge:d,indicators:c}}},IT=class{beforeDelete=new Map;afterDelete=new Map;registerBeforeDeleteHandler(e,t){return this.register(this.beforeDelete,e,t)}registerAfterDeleteHandler(e,t){return this.register(this.afterDelete,e,t)}runBeforeDelete(e,t,n){if(0!==t.length)for(const o of this.beforeDelete.get(e)??[])o(t,n)}runAfterDelete(e,t,n){if(0!==t.length)for(const o of this.afterDelete.get(e)??[])o(t,n)}register(e,t,n){const o=e.get(t);return o?o.push(n):e.set(t,[n]),()=>{const o=e.get(t);if(!o)return;const i=o.indexOf(n);i>=0&&o.splice(i,1)}}},PT=class{editor;constructor(e){this.editor=e}canAlign(){return this.canLayoutSelection(2)}align(e,t="user"){const n=this.getAlignableEntries();if(n.length<2)return!1;const o=this.getPageToParentTransform(n[0].shape.parentId);if(!o)return!1;const i=LC.FromPoints(n.flatMap(e=>[new $C(e.bounds.minX,e.bounds.minY),new $C(e.bounds.maxX,e.bounds.maxY)])),r=n.map(({shape:t,bounds:n})=>{let r=0,s=0;switch(e){case"left":r=i.minX-n.minX;break;case"right":r=i.maxX-n.maxX;break;case"horizontal-center":r=i.center.x-n.center.x;break;case"top":s=i.minY-n.minY;break;case"bottom":s=i.maxY-n.maxY;break;case"vertical-center":s=i.center.y-n.center.y}const a=this.pageDeltaToParentDelta(o,new $C(r,s));return{id:t.id,x:t.x+a.x,y:t.y+a.y}});return this.editor.commands.updateShapes(r,{source:t}),!0}canDistribute(){return this.canLayoutSelection(3)}distribute(e,t="user"){const n=this.getAlignableEntries();if(n.length<3)return!1;const o=this.getPageToParentTransform(n[0].shape.parentId);if(!o)return!1;const i="horizontal"===e,r=e=>i?e.w:e.h,s=e=>i?e.minX:e.minY,a=i?"x":"y",d=[...n].sort((e,t)=>e.bounds.center[a]-t.bounds.center[a]),l=d[0].bounds,c=d[d.length-1].bounds,u=((i?c.maxX:c.maxY)-s(l)-d.reduce((e,t)=>e+r(t.bounds),0))/(d.length-1);let p=s(l);const h=d.map(({shape:e,bounds:t},n)=>{const a=0===n||n===d.length-1?s(t):p,l=a-s(t);p=a+r(t)+u;const c=this.pageDeltaToParentDelta(o,i?new $C(l,0):new $C(0,l));return{id:e.id,x:e.x+c.x,y:e.y+c.y}});return this.editor.commands.updateShapes(h,{source:t}),!0}getCurrentPageBounds(e=this.editor.getCurrentPageId()){return this.boundsOfShapeIds(this.editor.getCurrentPageShapeIds())}zoomToBounds(e,t){const n=this.editor.viewportScreenSizeSignal.get();if(n.w<=0||n.h<=0||!et(e))return!1;if(e.w<=0&&e.h<=0)return!1;const o=t?.padding??64,i=Math.max(1,n.w-2*o),r=Math.max(1,n.h-2*o),s=Ke(Math.min(e.w>0?i/e.w:1/0,e.h>0?r/e.h:1/0,t?.maxZoom??1)),a=e.center;return this.editor.setCamera({x:a.x-n.w/2/s,y:a.y-n.h/2/s,z:s},{source:t?.source??"user"}),!0}zoomToFit(e){const t=this.getCurrentPageBounds();return!!t&&this.zoomToBounds(t,e)}zoomToSelection(e){const t=this.boundsOfShapeIds(this.editor.getSelectedShapeIds());return!!t&&this.zoomToBounds(t,e)}boundsOfShapeIds(e){const t=[];for(const o of e){const e=this.editor.getShapePageBounds(o);e&&et(e)&&t.push(new $C(e.minX,e.minY),new $C(e.maxX,e.maxY))}if(0===t.length)return null;const n=LC.FromPoints(t);return et(n)?n:null}canLayoutSelection(e){const t=this.getAlignableEntries();return t.length>=e&&null!==this.getPageToParentTransform(t[0].shape.parentId)}getAlignableEntries(){const e=this.editor.getSelectedShapeIds().map(e=>this.editor.getShape(e)).filter(e=>!!e&&!this.editor.isShapeOrAncestorLocked(e.id)),t=e[0]?.parentId;if(!t||e.some(e=>e.parentId!==t))return[];const n=[];for(const o of e){const e=this.editor.getShapePageBounds(o.id);e&&et(e)&&n.push({shape:o,bounds:e})}return n}getPageToParentTransform(e){const t=e.startsWith("shape:")?this.editor.getShape(e):null;return t?this.editor.computeShapeLocalToPageTransform(t).tryInvert():FC.Identity()}pageDeltaToParentDelta(e,t){const n=e.applyToPoint($C.Zero());return e.applyToPoint(t).sub(n)}},vT=class{editor;constructor(e){this.editor=e}setSelectedShapeIds(e,t){const n=this.editor,o=t?.pageId??n.getCurrentPageId(),i=t?.source??"user",r=((e,t)=>{const n=new Set(t);return t.filter(t=>{const o=e.getShape(t);if(!o)return!1;let i=o.parentId;const r=new Set([t]);for(;i.startsWith("shape:");){const t=i;if(r.has(t))return!0;if(n.has(t))return!1;r.add(t);const o=e.getShape(t);if(!o)return!0;i=o.parentId}return!0})})(n,Array.from(new Set(e.filter(e=>n.getShapePageId(e)===o&&!n.isShapeHidden(e))))),s=n.getSessionRecord(),a=s.pageSelectedShapeIdsById[o]??[];n.getShapeEditingSession()&&!n.completeEditing(i)||Ve(a,r)||(n.setBindingPreview(null),n.setSnapIndicators(null),n.updateSession({pageSelectedShapeIdsById:{...s.pageSelectedShapeIdsById,[o]:r}},i))}removeShapeIdsFromSelection(e,t="system"){if(0===e.length)return;const n=this.editor,o=new Set(e),i=n.getSessionRecord(),r={};for(const s of n.getPages())r[s.id]=(i.pageSelectedShapeIdsById[s.id]??[]).filter(e=>!o.has(e));n.updateSession({pageSelectedShapeIdsById:r},t)}selectAllCurrentPage(e="user"){const t=this.editor,n=t.getCurrentPageId(),o=t.getCurrentPageShapeIds().map(e=>t.getShape(e)).filter(e=>!!e&&e.parentId===n&&!t.isShapeHidden(e.id)).map(e=>e.id);t.commands.setSelectedShapeIds(o,{source:e})}},kT=class{editor;frameGeometrySignal;companionFrameGeometriesSignal;pathSignal;pageClipPathSignal;bindingSegmentsSignal;frameStyleSignal;frameSignal;handleAnchorsSignal;handlesSignal;handleCountsSignal;overlaySignal;debugStateSignal;debugStateSnapshotSignal;constructor(e){this.editor=e,this.frameGeometrySignal=d("editor.selectionOverlayFrameGeometry",()=>{const t=e.selectedShapeOverlayItemsSignal.get();if(0===t.length)return null;if(Jo(t))return null;const n=e.getSelectionFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:Fo}),this.companionFrameGeometriesSignal=d("editor.selectionOverlayCompanionFrameGeometries",()=>{if("select"!==e.toolStateSignal.get().activeToolId)return[];const t=[];for(const n of e.selectedShapesSignal.get())for(const o of e.getBindingsForShape(n.id))t.push(...e.getBindingUtil(o).getSelectionCompanionFrameGeometries?.(e,o,{selectedShape:n})??[]);return t},{isEqual:Oo}),this.pathSignal=d("editor.selectionOverlayPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return Jo(t)?t[0]?.path??null:null}),this.pageClipPathSignal=d("editor.selectionOverlayPageClipPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return Jo(t)?t[0]?.pageClipPath??null:null}),this.bindingSegmentsSignal=d("editor.selectionOverlayBindingSegments",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return Jo(t)?[...t[0]?.bindingSegments??[]]:[]},{isEqual:zt}),this.frameStyleSignal=d("editor.selectionOverlayFrameStyle",()=>{const t=e.cameraZoomSignal.get();return{strokeWidth:2/t,cornerRadius:3/t}},{isEqual:Do}),this.frameSignal=d("editor.selectionOverlayFrame",()=>{const e=this.frameGeometrySignal.get();if(!e)return null;const t=this.frameStyleSignal.get();return{...e,...t}},{isEqual:Lo}),this.handleAnchorsSignal=d("editor.selectionOverlayHandleAnchors",()=>{if("select"!==e.toolStateSignal.get().activeToolId)return null;const t=e.selectedShapesSignal.get();if(0===t.length)return null;const n=e.getSelectionFrame(),o=e.cameraZoomSignal.get(),i=1===t.length,r=e.canResizeSelection(),s=e.canRotateSelection();return ei(t,n,o,t=>e.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:i,editor:e}),t=>r&&e.getShapeUtil(t).canUseSelectionResizeHandles(t,{editor:e}),t=>s&&e.getShapeUtil(t).canUseSelectionRotateHandle(t,{editor:e}),Eo(e,e.getSelectionResizeTargetShapes(),n?.rotation??0))},{isEqual:Zo}),this.handlesSignal=d("editor.selectionOverlayHandles",()=>{const t=this.handleAnchorsSignal.get();if(!t)return null;const n=e.cameraZoomSignal.get(),{resizeHandles:o,rotateHandles:i,terminalHandles:r,middleHandles:s,customHandles:a}=ti(t,n);return{resizeHandles:o,rotateHandles:i,terminalHandles:r,middleHandles:s,customHandles:a,strokeWidth:2/n}},{isEqual:Go}),this.handleCountsSignal=d("editor.selectionOverlayHandleCounts",()=>{const e=this.handleAnchorsSignal.get();return e?{resizeHandleCount:e.resizeHandleAnchors.length,rotateHandleCount:e.rotateHandleAnchors.length,terminalHandleCount:e.terminalHandleAnchors.length,middleHandleCount:e.middleHandleAnchors.length,customHandleCount:e.customHandleAnchors.length}:null},{isEqual:Qo}),this.overlaySignal=d("editor.selectionOverlay",()=>{const e=this.frameSignal.get(),t=this.handlesSignal.get();return e&&t?{...e,...t}:null}),this.debugStateSnapshotSignal=d("editor.overlayDebugState.snapshot",t=>{const n=this.frameSignal.get(),o=this.handleCountsSignal.get(),i=t!==EC?t:null,r=!i||!Lo(i.frame,n),s=!i||!Qo(i.handleCounts,o);return{metrics:{selectionFrameActive:null!==n,selectionHandlesActive:null!==o,bindingPreviewActive:e.bindingPreviewActiveSignal.get(),brushBoxActive:e.brushBoxActiveSignal.get(),selectionFrameChangeCount:(i?.metrics.selectionFrameChangeCount??0)+(r?1:0),selectionHandlesChangeCount:(i?.metrics.selectionHandlesChangeCount??0)+(s?1:0),resizeHandleCount:o?.resizeHandleCount??0,rotateHandleCount:o?.rotateHandleCount??0,terminalHandleCount:o?.terminalHandleCount??0,middleHandleCount:o?.middleHandleCount??0,customHandleCount:o?.customHandleCount??0,boundsSummary:(a=n?.bounds??null,a?`${Math.round(a.x)},${Math.round(a.y)},${Math.round(a.w)},${Math.round(a.h)}`:"none"),rotation:n?.rotation??null,strokeWidth:n?.strokeWidth??null},frame:n,handleCounts:o};var a},{isEqual:(e,t)=>nt(e.metrics,t.metrics)}),this.debugStateSignal=d("editor.overlayDebugState.public",()=>this.debugStateSnapshotSignal.get().metrics,{isEqual:nt})}},CT=class{editor;entryRequestAtom=a("editor.shapeEditingEntryRequest",null);entryRequestSignal=this.entryRequestAtom;nextEntryRequestId=1;operation=null;constructor(e){this.editor=e}canEditShape(e){const t="string"==typeof e?this.editor.getShape(e):e;return!!t&&!t.isLocked&&this.editor.getShapeUtil(t).canEdit(t)}start(e,t="user"){let n=this.editor.getShape(e.shapeId);if(!n||!this.canEditShape(n))return null;const o=this.editor.getShapeEditingSession();if(o?.shapeId===n.id){const i={...o,entryMode:e.entryMode??o.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:o.caretPagePoint};return this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:i},t),this.publishEntryRequest({shapeId:n.id,entryMode:i.entryMode,caretPagePoint:i.caretPagePoint}),i}if(e.preserveInteraction||this.editor.cancelInteractionForCommand(),this.editor.getShapeEditingSession()&&!this.complete(t))return null;if(n=this.editor.getShape(e.shapeId),!n||!this.canEditShape(n))return null;const i=e.markId??`editing:${n.id}`;if(e.reuseActiveOperation){const e=this.editor.operations.getActive();if(!e||e.source!==t)throw new Error("Shape editing can only reuse an active operation with the same source.");this.operation=e}else this.operation=this.editor.operations.begin({kind:i,label:"shape.edit",source:"user",history:"record"});const r={shapeId:n.id,markId:i,entryMode:e.entryMode??"focusEnd",caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0,isComposing:!1};return this.editor.commands.setSelectedShapeIds([n.id],{source:t}),this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:r},t),this.publishEntryRequest({shapeId:n.id,entryMode:r.entryMode,caretPagePoint:r.caretPagePoint}),r}complete(e="user"){const t=this.editor.getShapeEditingSession();return!!t&&!t.isComposing&&(this.end({runEditEnd:!0,source:e}),this.commitOperation(),!0)}cancel(e="user"){const t=this.editor.getShapeEditingSession();return!!t&&!t.isComposing&&(this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},e),this.cancelOperation(),!0)}setComposition(e,t="system"){const n=this.editor.getShapeEditingSession();n&&n.isComposing!==e&&this.editor.updateSession({shapeEditingSession:{...n,isComposing:e}},t)}consumeEntryRequest(e){const t=this.entryRequestAtom.get();t&&t.id===e&&this.entryRequestAtom.set(null)}removeShapeIds(e,t="system"){const n=this.editor.getShapeEditingSession();n&&e.includes(n.shapeId)&&(this.end({runEditEnd:!1,source:t}),this.commitOperation())}prepareForShapeRemoval(e,t="system"){const n=this.editor.getShapeEditingSession();if(!n||!e.includes(n.shapeId))return;this.editor.isActiveToolInInitialState()||this.editor.cancelInteractionForCommand();const o=this.editor.getShapeEditingSession();o&&e.includes(o.shapeId)&&(this.end({runEditEnd:!1,source:t}),this.commitOperation())}end(e){const t=this.editor.getShapeEditingSession();if(!t)return;this.entryRequestAtom.set(null);const n=this.editor.getShape(t.shapeId);if(this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},e.source),!e.runEditEnd||!n)return;const o=this.editor.getShapeUtil(n).onEditEnd(n,{editor:this.editor});o?.deleteShapeIds&&o.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(o.deleteShapeIds,{source:e.source})}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}commitOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.commit()}publishEntryRequest(e){this.entryRequestAtom.set({id:this.nextEntryRequestId++,shapeId:e.shapeId,entryMode:e.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0})}},TT=class{editor;constructor(e){this.editor=e}computeParentToPageTransform(e,t=new Set([e.id])){if(!e.parentId.startsWith("shape:"))return FC.Identity();const n=this.editor.getShape(e.parentId);if(!n||t.has(n.id))return FC.Identity();const o=new Set(t);return o.add(n.id),pe(n,this.editor.getShapeUtil(n),this.computeParentToPageTransform(n,o))}computeShapePositionedBounds(e){return this.editor.getShapeUtil(e).getPositionedBounds(e)}computeShapeLocalBounds(e){return((e,t)=>t.getLocalBounds(e))(e,this.editor.getShapeUtil(e))}computeShapeRenderBounds(e){return((e,t)=>t.getRenderBounds(e))(e,this.editor.getShapeUtil(e))}computeShapeExportBounds(e){return ue(e,this.editor.getShapeUtil(e))}computeShapeLocalToPageTransform(e){return pe(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeRenderToPageTransform(e){return((e,t,n=FC.Identity())=>pe(e,t,n))(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeExportToPageTransform(e){return ge(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePageBounds(e){return((e,t,n=FC.Identity())=>LC.FromPoints(ye(e,t,n)))(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeExportPageBounds(e){return((e,t,n=FC.Identity())=>{const o=ue(e,t),i=ge(e,t,n);return LC.FromPoints([new $C(o.minX,o.minY),new $C(o.maxX,o.minY),new $C(o.maxX,o.maxY),new $C(o.minX,o.maxY)].map(e=>i.applyToPoint(e)))})(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeGeometry(e){return Se(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePositionedToPageTransform(e){return he(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePageCenter(e){return this.computeShapeGeometry(e).center}computeShapePageCorners(e){return this.computeShapeGeometry(e).corners}computeShapePageOutlineVertices(e){return this.computeShapeGeometry(e).outlineVertices}getShapePositionedBounds(e){return this.editor.queries.getShapePositionedBounds(e)??null}getShapePageBounds(e){return this.editor.queries.getShapePageBounds(e)??null}getShapeGeometry(e){return this.editor.queries.getShapeGeometry(e)??null}getShapePositionedToPageTransform(e){return this.editor.queries.getShapePositionedToPageTransform(e)??null}getShapePageCenter(e){return this.editor.queries.getShapePageCenter(e)??null}getShapePageCorners(e){return this.editor.queries.getShapePageCorners(e)??null}getShapePageOutlineVertices(e){return this.editor.queries.getShapePageOutlineVertices(e)??[]}getSelectionPageBounds(){return this.editor.queries.getSelectionPageBounds()}getSelectionFrame(){const e=this.editor.queries.getSelectionFrameBounds(),t=this.editor.queries.getSelectionRotationCenter();return e&&t?{bounds:e,rotation:this.editor.queries.getSelectionRotation(),rotationCenter:t,hasCompatibleRotation:this.editor.queries.getSelectionHasCompatibleRotation()}:null}isPointInSelectionBounds(e){const t=this.getSelectionFrame();if(!t)return!1;const n=this.getSelectionFrameLocalBoundsPoint(e);return!!n&&t.bounds.containsPoint(n)}getSelectionFrameLocalBoundsPoint(e){const t=this.getSelectionFrame();return t?yo(e,t):null}getSelectionPageOutlineVertices(){return this.editor.queries.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.editor.queries.getSelectionAnchorPagePoint()}},MT=class extends Error{},ET=class{editor;constructor(e){this.editor=e}get store(){return Z(this.editor)}getSelectionParentOrderState(){return ni(this.editor)}getSelectionGroupState(){return this.getGroupStateForShapeIds(this.editor.getSelectedShapeIds())}canGroupSelection(){return null!==this.getSelectionGroupState()}getGroupStateForShapeIds(e){const t=this.editor,n=Array.from(new Set(e.map(e=>t.bindings.getShapeHierarchyRootId(e)))),o=n.map(e=>t.getShape(e)).filter(e=>!!e);if(o.length!==n.length)return null;const i=new Set(n),r=o.filter(e=>!this.isShapeDescendantOfAny(e.id,i));if(r.length<2)return null;if(r.some(e=>t.isShapeOrAncestorLocked(e.id)||t.hasLockedDescendant(e.id)||t.isShapeHidden(e.id)))return null;const s=r[0]?.parentId;if(!s)return null;if(r.some(e=>e.parentId!==s))return null;const a=t.getChildShapes(s),d=new Set(r.map(e=>e.id)),l=a.filter(e=>d.has(e.id)).map(e=>e.id);if(l.length!==r.length)return null;const c=s.startsWith("shape:")?t.getShape(s):null,u=c?t.computeShapeLocalToPageTransform(c).tryInvert():null;if(c&&!u)return null;const p=l.flatMap(e=>t.getShapePageOutlineVertices(e).map(e=>u?u.applyToPoint(e):e)),h=p.length>0?LC.FromPoints(p):null;if(!h||!et(h))return null;const g={parentId:s,shapeIds:l,parentLocalBounds:h};return this.getGroupingShapeCreateInput(g)?g:null}getGroupingShapeCreateInput(e){let t=null;for(const n of this.editor.shapeUtils.values()){const o=n.getGroupingShapeCreateInput({parentId:e.parentId,parentLocalBounds:e.parentLocalBounds});if(o){if(o.type!==n.type)throw new Error(`Shape util "${n.type}" created grouping type "${o.type}" instead of its registered type`);if(o.parentId!==e.parentId)throw new Error(`Shape util "${n.type}" must preserve the requested grouping parent`);if(t)throw new Error(`Multiple shape utils define grouping creation: "${t.shapeUtilType}" and "${n.type}"`);t={shapeInput:o,shapeUtilType:n.type}}}return t?.shapeInput??null}groupShapesFromState(e,t){const n=this.editor,o=this.getGroupingShapeCreateInput(e);if(!o)return null;const i=n.getChildShapes(e.parentId),r=new Set(e.shapeIds);let s;for(const l of i)r.has(l.id)&&(s=l);if(!s)return null;n.cancelInteractionForCommand();let a=null;try{this.store.atomic(()=>{const[d]=n.commands.createShapes([o],{source:t,deferMinimumChildRepair:!0});if(!d)throw new MT;if(a=d.id,!n.commands.reparentShapes({ids:e.shapeIds,parentId:d.id},{source:t}))throw new MT;const l=[];for(const e of i)r.has(e.id)?e.id===s.id&&l.push(d.id):l.push(e.id);n.commands.updateShapes([...l.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)})),...e.shapeIds.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)}))],{source:t})},t)}catch(d){if(d instanceof MT)return null;throw d}return a?n.getShape(a)??null:null}canGroupShapes(e){return null!==this.getGroupStateForShapeIds(e)}groupShapes(e,t="user"){const n=this.getGroupStateForShapeIds(e);return n?this.groupShapesFromState(n,t):null}groupSelection(e="user"){const t=this.editor,n=this.groupShapes(t.getSelectedShapeIds(),e);return n&&t.commands.setSelectedShapeIds([n.id],{source:e}),n}getUngroupableSelectedShapeIds(){return this.getUngroupableShapeIds(this.editor.getSelectedShapeIds())}getUngroupableShapeIds(e){const t=this.editor;return e.map(e=>t.getShape(e)).filter(e=>!!e).filter(e=>t.getShapeUtil(e).canUngroupChildren(e)).filter(e=>!t.isShapeOrAncestorLocked(e.id)&&!t.hasLockedDescendant(e.id)&&!t.isShapeHidden(e.id)&&t.getChildShapeIds(e.id).length>0&&t.getChildShapes(e.id).every(n=>t.canUseShapeParent(e.parentId,n.id)&&!!be(t,n,e.parentId))).map(e=>e.id)}canUngroupSelection(){return this.getUngroupableSelectedShapeIds().length>0}canUngroupShapes(e){return this.getUngroupableShapeIds(e).length>0}ungroupShapes(e,t="user"){const n=this.editor,o=Array.from(new Set(e)),i=new Set(this.getOutermostUngroupableShapeIds(o));if(0===i.size)return[];const r=o.map(e=>n.getShape(e)).filter(e=>!!e),s=r.filter(e=>i.has(e.id)).map(e=>({group:e,children:n.getChildShapes(e.id)}));if(s.some(e=>e.children.some(t=>!be(n,t,e.group.parentId))))return[];const a=new Map(s.map(e=>[e.group.id,e])),d=new Set(s.map(e=>e.group.parentId)),l=new Map;for(const h of d){const e=[];for(const t of n.getChildShapes(h)){const n=a.get(t.id);n?e.push(...n.children.map(e=>e.id)):e.push(t.id)}l.set(h,e)}n.cancelInteractionForCommand();const c=[],u=new Set;try{this.store.atomic(()=>{const e=[];for(const o of r){if(!i.has(o.id)){u.has(o.id)||(u.add(o.id),c.push(o.id));continue}const e=a.get(o.id);if(!e)continue;if(!n.commands.reparentShapes({ids:e.children.map(e=>e.id),parentId:e.group.parentId},{source:t}))throw new MT;const r=new Set(e.children.map(e=>e.id));for(const t of e.children){const e=n.bindings.getShapeHierarchyRootId(t.id),o=r.has(e)?e:t.id;u.has(o)||(u.add(o),c.push(o))}}for(const t of l.values())e.push(...t.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)})));e.length>0&&n.commands.updateShapes(e,{source:t}),this.removeUngroupedContainerShapes(s.map(e=>e.group.id),t)},t)}catch(p){if(p instanceof MT)return[];throw p}return c.length>0&&n.commands.setSelectedShapeIds(c,{source:t}),c}ungroupSelection(e="user"){return this.ungroupShapes(this.editor.getSelectedShapeIds(),e)}getOutermostUngroupableShapeIds(e){const t=this.getUngroupableShapeIds(e),n=new Set(t);return t.filter(e=>!this.isShapeDescendantOfAny(e,n))}isShapeDescendantOfAny(e,t){let n=this.editor.getShape(e);const o=new Set;for(;n?.parentId.startsWith("shape:");){const e=n.parentId;if(t.has(e))return!0;if(o.has(e))return!1;o.add(e),n=this.editor.getShape(e)}return!1}removeUngroupedContainerShapes(e,t){if(0===e.length)return;const n=this.editor,o=Array.from(new Set(e)).filter(e=>n.getShape(e));0!==o.length&&(n.sideEffects.runBeforeDelete("shape",o,t),this.store.remove(o,t),n.sideEffects.runAfterDelete("shape",o,t))}getSelectionSiblingOrderState(){return oi(this.editor)}canMoveSelectionWithinParent(e){return((e,t)=>{const n=oi(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveSelectionInParentOrder(e){return((e,t)=>{const n=ni(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveShapesInParentOrder(e,t){return((e,t,n)=>{const o=ii(e,t);return"backward"===n?o?.canMoveBackward??!1:o?.canMoveForward??!1})(this.editor,e,t)}moveShapesInParentOrder(e,t,n="user"){return ri(this.editor,e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return si(this.editor,e,t,n)}moveSelectionWithinParent(e,t="user"){return((e,t,n="user")=>{const o=e.getSelectedShapes();if(1!==o.length)return!1;const[i]=o;if(!i||i.isLocked)return!1;const r=oi(e);if(!r)return!1;const s=e.getChildShapes(r.parentId),a=r.index;if(s[a]?.id!==i.id)return!1;const d="backward"===t?a-1:a+1;if(d<0||d>=s.length)return!1;const l=[...s],[c]=l.splice(a,1);return!!c&&(l.splice(d,0,c),e.cancelInteractionForCommand(),e.commands.updateShapes(l.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:n}),!0)})(this.editor,e,t)}moveShapesToParentPlacementResult(e,t="user"){return function(e,t,n="user"){const o=Array.from(new Set(t.ids));if(0===o.length)return{ok:!1,reason:"notFound"};const i=o.map(t=>e.getShape(t)).filter(e=>!!e);if(i.length!==o.length)return{ok:!1,reason:"notFound"};for(const s of i){if(s.isLocked)return{ok:!1,reason:"locked"};if(e.isShapeHidden(s.id))return{ok:!1,reason:"hidden"}}for(const s of o){const n=t.parentId;if(n.startsWith("page:")){if(!e.getPage(n))return{ok:!1,reason:"invalidParent"}}else{const t=e.getShape(n);if(!t)return{ok:!1,reason:"invalidParent"};if(t.id===s||e.getDescendantShapeIds(s).includes(t.id))return{ok:!1,reason:"cycle"};if(!e.canUseShapeParent(t.id,s))return{ok:!1,reason:"invalidParent"}}}const r=((e,t,n,o,i)=>{const r=((e,t,n,o)=>{const i=new Set(n),r=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,s=Z(e).getAll().filter(e=>f(e)&&e.parentId===t.parentId).filter(e=>!i.has(e.id));s.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));let a=s.length;if(t.beforeId){const e=s.findIndex(e=>e.id===t.beforeId);if(-1===e)return{ok:!1,reason:"invalidBeforeId"};a=e}s.splice(a,0,...o);const d=new Map;for(const l of o){if(l.parentId===t.parentId)continue;const n=be(e,l,t.parentId);if(!n)return{ok:!1,reason:"unsupportedTransform"};d.set(l.id,n)}return{ok:!0,updates:s.map((n,o)=>{const i=n.parentId!==t.parentId&&r?e.getShapeUtil(r).getChildPlacementMeta(r,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:e.createShapeIndex(o+1),...d.get(n.id),meta:i===n.meta?void 0:i}})}})(e,t,n,o);return r.ok?(e.cancelInteractionForCommand(),e.commands.updateShapes(r.updates,{source:i}),r):r})(e,t,o,i,n);return r.ok?{ok:!0,movedIds:o}:{ok:!1,reason:r.reason}}(this.editor,e,t)}moveSelectionInParentOrder(e,t="user"){return((e,t,n="user")=>ri(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}moveSelectionToParentOrderEdge(e,t="user"){return((e,t,n="user")=>si(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}isShapeOrAncestorLocked(e){const t=this.editor,n=new Set;let o=t.getShape(e);for(;o;){if(o.isLocked)return!0;if(!o.parentId.startsWith("shape:"))return!1;const e=o.parentId;if(n.has(e))return!1;n.add(e),o=t.getShape(e)}return!1}hasLockedDescendant(e){const t=this.editor;return t.getDescendantShapeIds(e).some(e=>t.getShape(e)?.isLocked??!1)}getOutermostSelectableShapeId(e){const t=this.editor;let n=e,o=t.getShape(e);const i=new Set([e]);for(;o?.parentId.startsWith("shape:");){const e=o.parentId;if(i.has(e))break;i.add(e);const r=t.getShape(e);if(!r)break;t.getShapeUtil(r).isSelectionTransformContainer(r)&&(n=r.id),o=r}return n}getShapeIdsIncludingDescendants(e){const t=[],n=new Set;for(const o of e)if(!n.has(o)){n.add(o),t.push(o);for(const e of this.editor.getDescendantShapeIds(o))n.has(e)||(n.add(e),t.push(e))}return t}getShapeIdsForSelectionTransform(e){return this.getOutermostUnlockedShapeIds(e)}getShapeIdsForSelectionRotation(e){return this.getOutermostUnlockedShapeIds(e)}getSelectionTransformTargetShapes(){return this.getShapeIdsForSelectionTransform(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}canResizeSelection(){const e=this.editor,t=this.getSelectionTransformAffectedShapes(),n=1===t.length;return t.length>0&&t.every(t=>e.getShapeUtil(t).canParticipateInSelectionResize(t,{editor:e,isOnlyAffectedShape:n}))}canFlipSelection(){const e=this.editor,t=this.getSelectionTransformAffectedShapes(),n=1===t.length;return t.length>0&&t.every(t=>e.getShapeUtil(t).canParticipateInSelectionFlip(t,{editor:e,isOnlyAffectedShape:n}))}canRotateSelection(){const e=this.editor,t=this.getSelectionTransformAffectedShapes(),n=1===t.length;return t.length>0&&t.every(t=>e.getShapeUtil(t).canParticipateInSelectionRotation(t,{editor:e,isOnlyAffectedShape:n}))}getSelectionResizeTargetShapes(){const e=this.editor,t=[],n=new Set,o=i=>{if(!n.has(i.id))if(n.add(i.id),e.getShapeUtil(i).shouldResizeDescendants(i))for(const t of e.getChildShapes(i.id))o(t);else t.push(i)};for(const i of this.getOutermostUnlockedShapeIds(e.getSelectedShapeIds())){const t=e.getShape(i);t&&o(t)}return t}getSelectionRotationTargetShapes(){return this.getShapeIdsForSelectionRotation(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getSelectionTransformAffectedShapes(){const e=this.editor,t=this.getOutermostUnlockedShapeIds(e.getSelectedShapeIds());return this.getShapeIdsIncludingDescendants(t).map(t=>e.getShapeSignal(t).get()).filter(e=>!!e)}getShapeExportTraversalIds(e){const t=this.editor,n=this.getShapeIdsIncludingDescendants(e).filter(e=>!t.isShapeHidden(e)),o=new Set(n);for(const i of n)for(const e of t.getBindingsForShape(i)){const i=t.getBindingUtil(e).getExportShapeIds?.(t,e);for(const e of i??[])for(const i of this.getShapeIdsIncludingDescendants([e]))o.has(i)||t.isShapeHidden(i)||(o.add(i),n.push(i))}return n}getShapeIdsInContainerBounds(e,t={}){const n=this.editor,o=n.getShapePageId(e),i=n.getShapePageBounds(e);return o&&i?n.getShapeIdsInBounds(i,{pageId:o}).filter(o=>{if(o===e)return!1;const i=n.getShapeContainment(e,o);return"inside"===i||t.includeIntersecting&&"intersecting"===i}):[]}canUseShapeParent(e,t){return((e,t,n)=>{if(t.startsWith("page:"))return!!e.getPage(t);const o=e.getShape(t);if(!o)return!1;if(n){const t=e.getShape(n);return!!t&&o.id!==n&&!e.getDescendantShapeIds(n).includes(o.id)&&e.getShapeUtil(o).canReceiveChild(o,t)}return e.getShapeUtil(o).canReceiveChildren(o)})(this.editor,e,t)}isShapeOrAncestorInSet(e,t){let n=this.editor.getShape(e);const o=new Set;for(;n;){if(t.has(n.id))return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(o.has(e))return!1;o.add(e),n=this.editor.getShape(e)}return!1}isShapeDescendantOf(e,t){let n=this.editor.getShape(e);const o=new Set;for(;n?.parentId.startsWith("shape:");){const e=n.parentId;if(e===t)return!0;if(o.has(e))return!1;o.add(e),n=this.editor.getShape(e)}return!1}getOutermostUnlockedShapeIds(e){const t=this.editor,n=Array.from(new Set(e)),o=new Set(n);return n.filter(e=>{const n=t.getShape(e);return!(!n||t.isShapeOrAncestorLocked(n.id)||t.hasLockedDescendant(n.id)||this.isShapeDescendantOfAny(n.id,o))})}},BT=class{bindings=new Map;bindingIds=[];register(e){const t=this.bindingIds.indexOf(e.id);t>=0&&this.bindingIds.splice(t,1);const n=ai(e.shortcut);this.bindingIds.push(e.id),this.bindings.set(e.id,{id:e.id,shortcut:n,target:e.target,label:e.label??di(n)})}registerActionShortcut(e,t){this.register({id:`action:${e}`,shortcut:t,target:{type:"action",actionId:e}})}registerEditorShortcut(e,t){const n=ai(t);this.register({id:`editor:${e}:${ui(n)}`,shortcut:n,target:{type:"editor",command:e}})}registerToolShortcut(e,t){this.register({id:`tool:${e}`,shortcut:t,target:{type:"tool",toolId:e}})}unregister(e){const t=this.bindingIds.indexOf(e);t>=0&&this.bindingIds.splice(t,1),this.bindings.delete(e)}getBinding(e){const t=this.bindings.get(e);return t?{id:t.id,shortcut:t.shortcut,target:t.target,label:t.label}:null}getTargetForEvent(e){return this.getBindingForEvent(e)?.target??null}getActionIdForEvent(e){const t=this.getTargetForEvent(e);return"action"===t?.type?t.actionId:null}getToolIdForEvent(e){const t=this.getTargetForEvent(e);return"tool"===t?.type?t.toolId:null}getActionShortcutLabel(e){return this.getBindingLabel(`action:${e}`)}getToolShortcutLabel(e){return this.getBindingLabel(`tool:${e}`)}getBindingForEvent(e){for(let t=this.bindingIds.length-1;t>=0;t--){const n=this.bindings.get(this.bindingIds[t]);if(n&&li(n.shortcut,e))return n}return null}getBindingLabel(e){return this.bindings.get(e)?.label}},AT=class{editor;shapeRenderOrderByIdSignal;culledShapeIdsSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;renderVisibleShapeIdSetSignal;renderItemsSignal;renderHostDebugStateSignal;retainedBaseShapeWindowSnapshotSignal;retainedShapeWindowSnapshotSignal;renderHostDebugStateSnapshotSignal;constructor(e){this.editor=e,this.shapeRenderOrderByIdSignal=d("editor.shapeRenderOrderById",()=>{const t=new Map;for(const[n,o]of e.currentPageShapeIdsSignal.get().entries())t.set(o,n);return t}),this.culledShapeIdsSignal=d("editor.culledShapeIds",()=>{const t=e.getCurrentPageId(),n=e.renderViewportPageBoundsSignal.get();return n?e.spatialIndex.getShapeIdsInViewport(n,{pageId:t}):e.currentPageShapeIdsSignal.get()},{isEqual:Ve}),this.retainedBaseShapeWindowSnapshotSignal=d("editor.retainedBaseShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),o=null!==e.viewportPageBoundsSignal.get(),i=yi(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(t!==EC&&t&&t.viewportReady&&i.length>0){const e=((e,t)=>{if(e.length!==t.length||0===t.length)return null;const n=t.map((n,o)=>{const i=e[o];if(!i)return null;if(i.end+2<n.start||i.start>n.end+2)return null;const r=o>0?t[o-1]:null,s=o<t.length-1?t[o+1]:null,a=s?s.start-3:1/0,d={start:Math.min(n.start,Math.max(r?r.end+3:-1/0,i.start)),end:Math.max(n.end,Math.min(a,i.end))};return d.end-d.start>n.end-n.start+4?null:d});if(n.some(e=>null===e))return null;const o=n;if(gi(o).length!==t.length)return null;const i=mi(t);return mi(o)>i+12?null:o})(gi(t.ranges.map(e=>({...e}))),i);if(e)return bi(n,e,{viewportReady:o})}return bi(n,i,{viewportReady:o})},{isEqual:(e,t)=>Ve(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=d("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:rt}),this.selectedShapeIdsOutsideCulledSignal=d("editor.selectedShapeIdsOutsideCulled",()=>{const t=e.selectedShapeIdsSignal.get();if(0===t.length)return[];const n=this.culledShapeIdSetSignal.get();return t.filter(e=>!n.has(e))},{isEqual:Ve}),this.selectedShapeIdsOutsideCulledSetSignal=d("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:rt}),this.renderVisibleShapeIdsSignal=d("editor.renderVisibleShapeIds",()=>{if(0===this.selectedShapeIdsOutsideCulledSignal.get().length)return this.culledShapeIdsSignal.get();const t=this.culledShapeIdSetSignal.get(),n=this.selectedShapeIdsOutsideCulledSetSignal.get();return e.currentPageShapeIdsSignal.get().filter(e=>t.has(e)||n.has(e))},{isEqual:Ve}),this.retainedShapeWindowSnapshotSignal=d("editor.retainedShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),o=null!==e.viewportPageBoundsSignal.get(),i=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,r=(s=i.length)<=0?0:pi(Math.ceil(.5*s),12,96);var s;const a=((e,t,n,o)=>{if(0===e.length)return[];const i=new Map;for(const[a,d]of e.entries())i.set(d,a);const r=gi(t.map(e=>i.get(e)).filter(e=>void 0!==e).sort((e,t)=>e-t).map(e=>({start:e,end:e+1})),2),s=[];if(r.length>0){const t=pi(Math.ceil(o/(2*r.length)),8,32);for(const[n,o]of r.entries()){const i=n>0?r[n-1]:null,a=n<r.length-1?r[n+1]:null,d=a?a.start-o.end:1/0,l=fi(i?o.start-i.end:1/0,t),c=fi(d,t+4);s.push({start:Math.max(0,o.start-l),end:Math.min(e.length,o.end+c)})}}for(const a of n){const e=i.get(a);void 0!==e&&s.push({start:e,end:e+1})}return 0===s.length?[]:gi(s,2)})(n,i,this.selectedShapeIdsOutsideCulledSetSignal.get(),r);if(o&&t!==EC&&t&&t.viewportReady&&t.ranges.length>0&&a.length>0){const e=gi(t.ranges.map(e=>({...e})));if(((e,t)=>{if(0===t.length)return!0;if(0===e.length)return!1;let n=0;for(const o of t){for(;n<e.length;){const t=e[n];if(t&&o.start>=t.start&&o.end<=t.end)break;if(!(t&&o.end>t.end))return!1;n+=1}if(n>=e.length)return!1}return!0})(e,a))return bi(n,e,{viewportReady:o});const i=((e,t,n)=>{const o=t.map((n,o)=>{const i={...n};for(const t of e)t.end+6<n.start||t.start>n.end+6||(i.start=Math.min(i.start,t.start),i.end=Math.max(i.end,t.end));const r=o>0?t[o-1]:null,s=o<t.length-1?t[o+1]:null,a=s?s.start-3:1/0;return{start:Math.min(n.start,Math.max(r?r.end+3:-1/0,i.start)),end:Math.max(n.end,Math.min(a,i.end))}});if(gi(o).length!==t.length)return null;const i=mi(t);return mi(o)>i+n?null:o})(e,a,r);if(i)return bi(n,i,{viewportReady:o})}return bi(n,a,{viewportReady:o})},{isEqual:(e,t)=>Ve(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=d("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:Ve}),this.renderVisibleShapeIdSetSignal=d("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:rt}),this.renderItemsSignal=d("editor.renderItems",()=>{const t=e.selectedShapeIdSetSignal.get(),n=[];for(const o of this.renderVisibleShapeIdsSignal.get()){const i=e.getShapeSignal(o).get(),r=e.queries.getShapePageBoundsSignal(o).get();i&&!i.isHidden&&r&&n.push({id:i.id,shape:i,bounds:r,isSelected:t.has(i.id)})}return n},{isEqual:it}),this.renderHostDebugStateSnapshotSignal=d("editor.renderHostDebugState.snapshot",t=>{const n=this.culledShapeIdsSignal.get(),o=this.renderVisibleShapeIdsSignal.get(),i=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,r=this.retainedShapeIdsSignal.get(),s=this.selectedShapeIdsOutsideCulledSignal.get(),a=this.getPageIndexById(e.currentPageShapeIdsSignal.get()),d=yi(n,a),l=yi(r,a),c=yi(i,a),u=((e,t)=>{if(0===e.length)return{changed:t.length,added:t.length,removed:0};if(0===t.length)return{changed:e.length,added:0,removed:e.length};const n=new Set(e),o=new Set(t);let i=0,r=0;for(const s of o)n.has(s)||(i+=1);for(const s of n)o.has(s)||(r+=1);return{changed:i+r,added:i,removed:r}})(t===EC?[]:t.retainedShapeIds,r);return{metrics:{culledCount:n.length,visibleCount:o.length,retainedCount:r.length,retainedBaseCount:i.length,culledRangeCount:d.length,culledRangeSpan:mi(d),culledRangesSummary:hi(d),retainedBaseRangeCount:c.length,retainedBaseRangeSpan:mi(c),retainedBaseRangesSummary:hi(c),retainedRangeCount:l.length,retainedRangeSpan:mi(l),retainedRangesSummary:hi(l),retainedChangeCount:u.changed,retainedAddedCount:u.added,retainedRemovedCount:u.removed,selectedOutsideCulledCount:s.length},retainedShapeIds:r.slice()}},{isEqual:(e,t)=>tt(e.metrics,t.metrics)}),this.renderHostDebugStateSignal=d("editor.renderHostDebugState.public",()=>this.renderHostDebugStateSnapshotSignal.get().metrics,{isEqual:tt})}getPageIndexById(e){const t=new Map;for(const[n,o]of e.entries())t.set(o,n);return t}},RT=class{editor;activeToolId=a("tools.activeToolId","select");isToolLocked=a("tools.isToolLocked",!1);registry=new Map;activeTool=null;constructor(e){this.editor=e}register(e,t,n={}){this.registry.set(e,t),n.shortcut&&this.editor.shortcuts.registerToolShortcut(e,n.shortcut)}hasTool(e){return this.registry.has(e)}setActiveTool(e,t="tool_switch"){const n=this.registry.get(e);if(!n)throw new Error(`Unknown tool "${e}"`);this.activeTool&&this.activeToolId.get()===e||(this.activeTool&&(this.editor.cancelInteractionAndClearTransients(t),this.activeTool.exit({reason:t})),this.activeToolId.set(e),this.activeTool=n(this.editor),this.activeTool.enter())}dispatch(e){this.activeTool?.dispatch(e)}cancel(e){this.activeTool?.dispatch({type:"cancel",reason:e})}setToolLocked(e){this.isToolLocked.set(e)}isActiveToolInInitialState(){return this.activeTool?.isInInitialState()??!0}},$T=class{handlers=[];registeredIds=new Set;register(e){this.registeredIds.has(e.id)||(this.handlers.push(e),this.registeredIds.add(e.id))}getHandlers(){return this.handlers}handleEvent(e,t){for(const n of this.handlers)if("handled"===n.editorEvent?.handleEvent(e,t))return"handled";return"continue"}broadcastEvent(e,t){let n="continue";for(const o of this.handlers)"handled"===o.editorEvent?.handleEvent(e,t)&&(n="handled");return n}createSelectionHandleSession(e,t){for(const n of this.handlers){const o=n.selectionHandle?.createSession(e,t);if(o)return o}return null}createShapePointerSession(e,t){for(const n of this.handlers){const o=n.shapePointer?.createSession(e,t);if(o)return o}return null}},LT=class{interactions;handlers=[];constructor(e){this.interactions=e}register(e){this.handlers.push(e)}createSession(e,t){const n=this.interactions?.createSelectionHandleSession(e,t)??null;if(n)return n;for(const o of this.handlers){const n=o.createSession(e,t);if(n)return n}return null}},FT=class{store;[KC];inputs=new aT;snapshots=new sT(this);clipboard=new iT(this);shortcuts=new BT;tools=new RT(this);camera=new nT(this);selection=new vT(this);selectionLayout=new PT(this);editing=new CT(this);geometry=new TT(this);hierarchy=new ET(this);shapeUtils=new WC;shapeSvgExporters=new _C;bindingUtils=new RC;interactions=new $T;selectionHandleInteractions=new LT(this.interactions);runtime=new OC;queries;bindings;spatialIndex;snaps;renderWindow;selectionOverlay;transients=new dT(this);history;operations;sideEffects=new IT;commands;shapeCapabilityDefinitions;brushBoxSignal=this.transients.brushBoxSignal;brushBoxActiveSignal=this.transients.brushBoxActiveSignal;bindingPreviewSignal=this.transients.bindingPreviewSignal;bindingPreviewActiveSignal=this.transients.bindingPreviewActiveSignal;terminalBindingGuidesSignal=this.transients.terminalBindingGuidesSignal;dropTargetShapeIdSignal=this.transients.dropTargetShapeIdSignal;hoveredShapeIdSignal=this.transients.hoveredShapeIdSignal;selectionTranslationActiveSignal=this.transients.selectionTranslationActiveSignal;snapIndicatorsSignal;snapIndicatorsActiveSignal;get viewportScreenSizeSignal(){return this.camera.viewportScreenSizeSignal}shapeEditingEntryRequestSignal=this.editing.entryRequestSignal;_shapeDefaultPropsByTypeSignal=a("editor.shapeDefaultPropsByType",new Map);shapeDefaultPropsByTypeSignal=this._shapeDefaultPropsByTypeSignal;nextShapeNumber=1;nextPageNumber=1;nextBindingNumber=1;nextAssetNumber=1;assetUrlResolver=()=>null;get _internalStore(){return Z(this)}sessionSignal=d("editor.session",()=>{const e=this._internalStore.getRecordSignal(UC).get();if(!m(e))throw new Error("Missing session record");return e});getSessionRecord(){const e=this._internalStore.get(UC);if(!m(e))throw new Error("Missing session record");return e}currentPageIdSignal=d("editor.currentPageId",()=>this.sessionSignal.get().currentPageId);currentPageShapeIdsSignal;currentPageShapesSignal;currentPageShapeHierarchySignal;culledShapeIdsSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionAnchorPagePointSignal;pagesSignal=d("editor.pages",()=>Array.from(this._internalStore.recordsSignal.get().values()).filter(h).sort((e,t)=>e.index.localeCompare(t.index)),{isEqual:qe});currentPageSignal=d("editor.currentPage",()=>{const e=this.currentPageIdSignal.get();return this.pagesSignal.get().find(t=>t.id===e)??null});pageStateSignal=d("editor.pageState",()=>{const e=this.pagesSignal.get(),t=this.currentPageIdSignal.get(),n=e.find(e=>e.id===t)??null;return{pages:e,currentPageId:t,currentPage:n,canDeleteCurrentPage:e.length>1&&null!==n}});toolStateSignal=d("editor.toolState",()=>{const e=this.sessionSignal.get();return{activeToolId:e.activeToolId,isToolLocked:e.isToolLocked}});editingShapeIdSignal=d("editor.editingShapeId",()=>this.sessionSignal.get().editingShapeId);shapeEditingSessionSignal=d("editor.shapeEditingSession",()=>this.sessionSignal.get().shapeEditingSession);shapeEditingStateSignal=d("editor.shapeEditingState",()=>({editingShapeId:this.editingShapeIdSignal.get(),session:this.shapeEditingSessionSignal.get()}));currentCameraSignal=d("editor.currentCamera",()=>this.sessionSignal.get().pageCameraById[this.currentPageIdSignal.get()]??NC);selectedShapeIdsSignal=d("editor.selectedShapeIds",()=>{const e=this.sessionSignal.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:Ve});selectionCountSignal=d("editor.selectionCount",()=>this.selectedShapeIdsSignal.get().length);selectedShapeIdSetSignal=d("editor.selectedShapeIdSet",()=>new Set(this.selectedShapeIdsSignal.get()),{isEqual:rt});selectedShapesSignal=d("editor.selectedShapes",()=>this.selectedShapeIdsSignal.get().map(e=>this.getShapeSignal(e).get()).filter(e=>!!e));selectionCanFlipSignal=d("editor.selectionCanFlip",()=>this.hierarchy.canFlipSelection());selectedShapeOverlayItemsSignal=d("editor.selectedShapeOverlayItems",()=>"select"!==this.toolStateSignal.get().activeToolId?[]:this.selectedShapeIdsSignal.get().map(e=>this.getShapeSignal(e).get()).filter(e=>!!e).map(e=>{const t=this.getShapeUtil(e).getSelectionOverlayInfo(e,{editor:this});return{id:e.id,usesSelectionPathOverlay:t.usesSelectionPathOverlay,startPagePoint:t.startPagePoint,endPagePoint:t.endPagePoint,middlePagePoint:t.middlePagePoint,path:t.path,pathStyle:t.pathStyle,pageClipPath:t.pageClipPath??null,bindingSegments:t.bindingSegments??[]}}),{isEqual:$o});selectionStateSignal=d("editor.selectionState",()=>{const e=this.selectedShapeIdsSignal.get(),t=1===e.length?this.getShapeSignal(e[0]).get()??null:null,n=this.selectedShapesSignal.get(),o=(e=>{let t=null;for(const n of e)if(null!==t){if(t!==n.type)return null}else t=n.type;return t})(n),i=1===n.length,r=n.map(e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:i,editor:this})).some(e=>e.terminalHandleAnchors.length>0||e.middleHandleAnchors.length>0||(e.customHandleAnchors?.length??0)>0),s=n.some(e=>this.getShapeUtil(e).contributesToSelectionFrame(e,{editor:this})),a=r&&s,d=t?this.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:i,editor:this}):null,l=1===e.length&&!!d&&(d.terminalHandleAnchors.length>0||(d.customHandleAnchors?.length??0)>0),c=this.queries.selectionHasRotationSignal.get();return{count:e.length,singleShapeType:t?.type??null,commonShapeType:o,canFlipSelection:this.selectionCanFlipSignal.get(),hasPointHandleSelection:r,hasFrameSelection:s,isMixedFrameAndPointHandleSelection:a,canDragPointHandles:l,hasSelectionRotation:c,hasMixedSelectionRotation:!this.queries.selectionHasCompatibleRotationSignal.get(),canResetSelectionRotation:c&&s,frameBounds:this.selectionFrameBoundsSignal.get(),frameRotation:this.queries.selectionRotationSignal.get(),frameRotationCenter:this.queries.selectionRotationCenterSignal.get(),selectionAnchorPagePoint:this.selectionAnchorPagePointSignal.get()}});selectionMetadataSignal=d("editor.selectionMetadata",()=>{const e=this.selectionStateSignal.get();return{count:e.count,singleShapeType:e.singleShapeType,commonShapeType:e.commonShapeType,canFlipSelection:e.canFlipSelection,hasPointHandleSelection:e.hasPointHandleSelection,hasFrameSelection:e.hasFrameSelection,isMixedFrameAndPointHandleSelection:e.isMixedFrameAndPointHandleSelection,canDragPointHandles:e.canDragPointHandles,hasSelectionRotation:e.hasSelectionRotation,hasMixedSelectionRotation:e.hasMixedSelectionRotation,canResetSelectionRotation:e.canResetSelectionRotation}},{isEqual:je});pageTransformSignal=d("editor.pageTransform",()=>{const e=this.currentCameraSignal.get();return FC.Scale(e.z,e.z).compose(FC.Translate(-e.x,-e.y))});cameraZoomSignal=d("editor.cameraZoom",()=>this.currentCameraSignal.get().z);viewportPageBoundsSignal=d("editor.viewportPageBounds",()=>{const{w:e,h:t}=this.viewportScreenSizeSignal.get();if(e<=0||t<=0)return null;const n=this.currentCameraSignal.get();return new LC(n.x,n.y,e/n.z,t/n.z)});renderViewportPageBoundsSignal=d("editor.renderViewportPageBounds",e=>{const t=this.viewportPageBoundsSignal.get();return t?e!==EC&&e&&(o=t).minX>=(n=e).minX&&o.maxX<=n.maxX&&o.minY>=n.minY&&o.maxY<=n.maxY?e:t.expand(160/this.cameraZoomSignal.get()):null;var n,o},{isEqual:Je});renderItemsSignal;renderHostDebugStateSignal;historyStateSignal;shapeRenderOrderByIdSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdSetSignal;shapeSignals=new Map;shapeContentCutoutLocalPolygonSignals=new Map;shapeSelectedSignals=new Map;shapeRenderOrderSignals=new Map;shapeRenderVisibleSignals=new Map;shapeDocumentVisibleSignals=new Map;shapeEffectiveOpacitySignals=new Map;shapeEditingSessionSignals=new Map;shapeDropTargetSignals=new Map;shapeHoveredSignals=new Map;shapeSelectedDescendantTransformAncestorSignals=new Map;lastPointerDownForClickCount=null;lastPointerUpForClickCount=null;currentPointerClickCount=1;selectionOverlayFrameGeometrySignal;selectionOverlayCompanionFrameGeometriesSignal;selectionOverlayPathSignal;selectionOverlayPageClipPathSignal;selectionOverlayBindingSegmentsSignal;selectionOverlayFrameStyleSignal;selectionOverlayFrameSignal;selectionOverlayHandleAnchorsSignal;selectionOverlayHandlesSignal;selectionOverlayHandleCountsSignal;selectionOverlaySignal;overlayDebugStateSignal;constructor(e={}){this.shapeCapabilityDefinitions=e.shapeCapabilities??[],e.resolveAssetUrl&&(this.assetUrlResolver=e.resolveAssetUrl);for(const o of e.shapeUtils??[])this.shapeUtils.register(o);for(const o of e.shapeSvgExporters??[])this.shapeSvgExporters.register(o);for(const o of e.bindingUtils??[])this.bindingUtils.register(o);const t=new jC(this.snapshots.buildInitialRecords(e.documentSnapshot??null,e.sessionSnapshot??null,e.documentMeta??{}));var n;((e,t)=>{e[KC]=t})(this,t),this.store=t,this.snapshots.ensureSessionIntegrity(),this.queries=new cT(this),this.bindings=new tT(this),this.spatialIndex=new pT(this,this.queries),this.snaps=new wT(this),this.snapIndicatorsSignal=this.snaps.indicatorsSignal,this.snapIndicatorsActiveSignal=this.snaps.activeSignal,this.currentPageShapeIdsSignal=this.queries.currentPageShapeIdsSignal,this.currentPageShapesSignal=this.queries.currentPageShapesSignal,this.currentPageShapeHierarchySignal=this.queries.currentPageShapeHierarchySignal,this.selectionPageBoundsSignal=this.queries.selectionPageBoundsSignal,this.selectionFrameBoundsSignal=this.queries.selectionFrameBoundsSignal,this.selectionAnchorPagePointSignal=this.queries.selectionAnchorPagePointSignal,this.selectionOverlay=new kT(this),this.selectionOverlayFrameGeometrySignal=this.selectionOverlay.frameGeometrySignal,this.selectionOverlayCompanionFrameGeometriesSignal=this.selectionOverlay.companionFrameGeometriesSignal,this.selectionOverlayPathSignal=this.selectionOverlay.pathSignal,this.selectionOverlayPageClipPathSignal=this.selectionOverlay.pageClipPathSignal,this.selectionOverlayBindingSegmentsSignal=this.selectionOverlay.bindingSegmentsSignal,this.selectionOverlayFrameStyleSignal=this.selectionOverlay.frameStyleSignal,this.selectionOverlayFrameSignal=this.selectionOverlay.frameSignal,this.selectionOverlayHandleAnchorsSignal=this.selectionOverlay.handleAnchorsSignal,this.selectionOverlayHandlesSignal=this.selectionOverlay.handlesSignal,this.selectionOverlayHandleCountsSignal=this.selectionOverlay.handleCountsSignal,this.selectionOverlaySignal=this.selectionOverlay.overlaySignal,this.overlayDebugStateSignal=this.selectionOverlay.debugStateSignal,this.renderWindow=new AT(this),this.shapeRenderOrderByIdSignal=this.renderWindow.shapeRenderOrderByIdSignal,this.culledShapeIdsSignal=this.renderWindow.culledShapeIdsSignal,this.culledShapeIdSetSignal=this.renderWindow.culledShapeIdSetSignal,this.selectedShapeIdsOutsideCulledSignal=this.renderWindow.selectedShapeIdsOutsideCulledSignal,this.selectedShapeIdsOutsideCulledSetSignal=this.renderWindow.selectedShapeIdsOutsideCulledSetSignal,this.renderVisibleShapeIdsSignal=this.renderWindow.renderVisibleShapeIdsSignal,this.retainedShapeIdsSignal=this.renderWindow.retainedShapeIdsSignal,this.renderVisibleShapeIdSetSignal=this.renderWindow.renderVisibleShapeIdSetSignal,this.renderItemsSignal=this.renderWindow.renderItemsSignal,this.renderHostDebugStateSignal=this.renderWindow.renderHostDebugStateSignal,this.syncShapeCounter(),this.syncPageCounter(),this.syncBindingCounter(),this.syncAssetCounter(),this.operations=new JC(this),this.history=new ZC(this),this.historyStateSignal=this.history.state,this.commands=(n=this,{createPage:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.createPageRecord(t);let r=i;return Z(e).atomic(()=>{const t=Ie([...e.getPages(),i]);r=t.find(e=>e.id===i.id)??i,Z(e).put(t,o),e.ensurePageSessionState(r.id,o)},o),r})(n,e,t),deletePage:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.getPages();if(i.length<=1)return!1;const r=i.findIndex(e=>e.id===t);if(r<0)return!1;const s=e.getShapesForPage(t).map(e=>e.id),a=Ie(i.filter(e=>e.id!==t)),d=i[r+1]?.id??i[r-1]?.id??i[0]?.id,l=e.getCurrentPageId()===t&&d?d:e.getCurrentPageId();return Z(e).atomic(()=>{s.length>0&&Oe(e,s,n),Z(e).remove([t],o),e.removePageSessionState(t,l,o),Z(e).put(a,o)},o),!0})(n,e,t),renamePage(e,t){((e,t,n)=>{const o=n?.source??"user",i=e.getPage(t.id);if(!i)return;const r=t.name.trim();r&&r!==i.name&&Z(e).atomic(()=>{Z(e).put([{...i,name:r}],o)},o)})(n,e,t)},updateDocumentMeta:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.getDocumentMetadataRecord()??c(),r={...i,meta:{...i.meta,...t.patch}};return Z(e).atomic(()=>{Z(e).put([r],o)},o),r})(n,e,t),updatePageMeta:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.getPage(t.id);if(!i)return null;const r={...i,meta:{...i.meta,...t.patch}};return Z(e).atomic(()=>{Z(e).put([r],o)},o),r})(n,e,t),movePage(e,t){((e,t,n)=>{const o=n?.source??"user",i=e.getPages(),r=i.findIndex(e=>e.id===t.id);if(r<0)return;const s=Math.max(0,Math.min(t.toIndex,i.length-1));if(r===s)return;const a=[...i],[d]=a.splice(r,1);d&&(a.splice(s,0,d),Z(e).atomic(()=>{Z(e).put(Ie(a),o)},o))})(n,e,t)},createShapes:(e,t)=>((e,t,n)=>{const o=[],i=n?.source??"user";return Z(e).atomic(()=>{const r=t.map(t=>e.createShapeRecord(t)),s=new Map(r.map(e=>[e.id,e])),a=r.map(t=>{if(!t.parentId.startsWith("shape:"))return t;const n=s.get(t.parentId)??e.getShape(t.parentId);if(!n)return t;const o=e.getShapeUtil(n).getChildPlacementMeta(n,t,{editor:e,reason:"create"});return o===t.meta?t:{...t,meta:o}});if(ke(e,a),Z(e).put(a,i),"user"===i&&!1!==n?.autoReparent){const o=new Map;for(let n=0;n<a.length;n+=1){const i=a[n],r=t[n];if(!i||!r||r.parentId)continue;const s=e.getContainingParentIdForShapeRecord(i);s&&s!==i.parentId&&o.set(i.id,s)}((e,t)=>{const n=new Set;for(const o of e.keys()){const i=[],r=new Map;let s=o;for(;s;){const o=r.get(s);if(void 0!==o){for(const e of i.slice(o))n.add(e);break}r.set(s,i.length),i.push(s);const a=e.get(s);s=a?.startsWith("shape:")&&t.has(a)?a:null}}for(const o of n)e.delete(o)})(o,new Set(a.map(e=>e.id)));const i=new Map;for(const e of a){const t=o.get(e.id);if(!t)continue;const n=i.get(t)??[];n.push(e.id),i.set(t,n)}for(const[t,r]of i)Fe(e,{ids:r,parentId:t},n)}const d=$e(e,a.map(e=>e.id)),l=new Set;if(!n?.deferMinimumChildRepair){const t=new Set;for(const n of a){const o=e.getShape(n.id);o&&e.getShapeUtil(o).getMinimumChildCount(o)>0&&t.add(o.id)}Le(e,t,l,i)}Ee(e,d,i,l),o.push(...a.map(t=>e.getShape(t.id)).filter(e=>!!e))},i),o})(n,e,t),createShapesFromRecords:(e,t)=>((e,t,n)=>{const o=n?.source??"user";if(0===t.length)return[];for(const i of t)if(e.getShape(i.id))throw new Error(`Shape ${i.id} already exists`);return ke(e,t),Z(e).atomic(()=>{Z(e).put(t,o),Ce(e,o);const n=$e(e,t.map(e=>e.id));for(const o of t){const t=e.getShape(o.id);t&&e.getShapeUtil(t).getMinimumChildCount(t)>0&&n.add(t.id)}const i=new Set;Le(e,n,i,o),Ee(e,n,o,i)},o),t.map(t=>e.getShape(t.id)).filter(e=>!!e)})(n,e,t),updateShapes(e,t){ve(n,e,t)},reparentShapes:(e,t)=>Fe(n,e,t),deleteShapes(e,t){Oe(n,e,t)},createAsset:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.createAssetRecord(t);return Z(e).atomic(()=>{Z(e).put([i],o)},o),i})(n,e,t),createAssetsFromRecords:(e,t)=>((e,t,n)=>{const o=n?.source??"user";return 0===t.length?[]:(Z(e).atomic(()=>{Z(e).put(t,o)},o),t)})(n,e,t),updateAsset:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.getAsset(t.id);if(!i)return null;const r={...i,props:t.props?{...i.props,...t.props}:i.props,meta:t.meta??i.meta};return Z(e).atomic(()=>{Z(e).put([r],o)},o),r})(n,e,t),deleteAsset:(e,t)=>((e,t,n)=>{const o=n?.source??"user";return!!e.getAsset(t)&&(Z(e).atomic(()=>{Z(e).remove([t],o)},o),!0)})(n,e,t),createBinding:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.createBindingRecord(t);if(!De(e,i))throw new Error(`Invalid binding endpoints for ${i.type} binding`);const r=new Set;return ze(e,[i.fromId,i.toId],r),Z(e).atomic(()=>{const t=e.bindings.getConflictingBindings(i).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,o),Z(e).put([i],o),e.bindings.syncCreatedBinding(i,o),ze(e,[i.fromId,i.toId],r),Le(e,r,new Set,o)},o),i})(n,e,t),updateBinding:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.getBinding(t.id);if(!i)return null;const r=e.getBindingUtil(i),s={...i,fromId:t.fromId??i.fromId,toId:t.toId??i.toId,props:t.props?r.validateProps({...i.props,...t.props}):i.props,meta:t.meta??i.meta};if(!De(e,s))throw new Error(`Invalid binding endpoints for ${s.type} binding`);const a=new Set;return ze(e,[i.fromId,i.toId,s.fromId,s.toId],a),Z(e).atomic(()=>{const t=e.bindings.getConflictingBindings(s).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,o),Z(e).put([s],o),e.bindings.syncUpdatedBinding(i,s,o),ze(e,[i.fromId,i.toId,s.fromId,s.toId],a),Le(e,a,new Set,o)},o),s})(n,e,t),deleteBinding:(e,t)=>((e,t,n)=>{const o=n?.source??"user",i=e.getBinding(t);return!!i&&(Z(e).atomic(()=>{e.bindings.cleanupBindings([i.id],o),Z(e).remove([i.id],o)},o),!0)})(n,e,t),setCurrentPageId(e,t){((e,t,n)=>{e.setCurrentPage(t,n?.source??"system")})(n,e,t)},setCamera(e,t){((e,t,n)=>{e.setCamera(t.camera,{pageId:t.pageId,source:n?.source??"system"})})(n,e,t)},setSelectedShapeIds(e,t){((e,t,n)=>{e.setSelectedShapeIds(t,{source:n?.source??"user"})})(n,e,t)},setActiveTool(e,t){((e,t,n)=>{const o=n?.source??"system";e.tools.setActiveTool(t),e.completeEditing(o),e.updateSession({activeToolId:t},o)})(n,e,t)},setToolLocked(e,t){((e,t,n)=>{const o=n?.source??"system";e.tools.setToolLocked(t),e.updateSession({isToolLocked:t},o)})(n,e,t)}}),this.bindings.repairLoadedBindings("system"),this.registerBuiltInInteractions(),this.registerBuiltInShortcuts(),this.registerBuiltInSideEffects()}registerBuiltInInteractions(){this.interactions.register(function(){let e=!1,t=null;const n=()=>{t=null};return{id:"land.camera.canvas-pan",editorEvent:{handleEvent(o,i){if("cancel"===i.type)return"blur"!==i.reason&&"dispose"!==i.reason||(e=!1),n(),"continue";if("keyboard"===i.type&&(e=>"Space"===e.code)(i)){if("key_up"===i.name){const t=e;return e=!1,t?"handled":"continue"}return o.getShapeEditingSession()?"continue":(e=!0,"handled")}if("pointer"!==i.type||"mouse"!==i.pointerType)return"continue";if("pointer_down"===i.name){n();const r=((e,{allowLeftButton:t})=>1===e.button?4:t&&0===e.button?1:null)(i,{allowLeftButton:o.inputs.isSpacePressed.get()&&!o.getShapeEditingSession()});return null===r?"continue":(o.resetPointerClickTracking(),0===i.button&&(e=!0),t={pointerId:i.pointerId,buttons:r,camera:xi(o,i.screenPoint)},"handled")}return t&&i.pointerId===t.pointerId?"pointer_move"===i.name?0===(i.buttons&t.buttons)?(n(),"handled"):(wi(o,t.camera,i.screenPoint),"handled"):"pointer_up"===i.name||"pointer_cancel"===i.name?(n(),"handled"):"continue":"continue"}}}}())}registerBuiltInShortcuts(){this.shortcuts.registerEditorShortcut("move-selection-backward",{key:"ArrowDown",altKey:!0}),this.shortcuts.registerEditorShortcut("move-selection-forward",{key:"ArrowUp",altKey:!0}),this.shortcuts.registerEditorShortcut("undo",{key:"z",accelKey:!0}),this.shortcuts.registerEditorShortcut("redo",{key:"z",accelKey:!0,shiftKey:!0}),this.shortcuts.registerEditorShortcut("delete-selection","Backspace"),this.shortcuts.registerEditorShortcut("delete-selection","Delete"),this.shortcuts.registerEditorShortcut("reset-interaction","Escape")}registerBuiltInSideEffects(){this.sideEffects.registerBeforeDeleteHandler("shape",(e,t)=>{this.bindings.cleanupBindingsForDeletedShapes(e,t)}),this.sideEffects.registerAfterDeleteHandler("shape",(e,t)=>{this.removeShapeIdsFromSelection(e,t),this.removeShapeIdsFromEditingSession(e,t)})}dispatch(e){const t=this.normalizeEvent(e);if(this.inputs.handleEvent(t),"keyboard"===t.type&&"key_down"===t.name){const e=this.shortcuts.getTargetForEvent(t);if(e&&this.runKeyboardShortcutTarget(e))return}if("wheel"!==t.type)if("cancel"!==t.type){if("pointer"===t.type&&"pointer_cancel"===t.name)return this.interactions.broadcastEvent(this,t),void this.cancelInteractionAndClearTransients("pointer_cancel",{notifyInteractionHandlers:!1});if("handled"!==this.interactions.handleEvent(this,t)&&(this.tools.dispatch(t),"pointer"===t.type&&"pointer_up"===t.name)){const e=this.getDoubleClickEvent(t);e&&"handled"!==this.interactions.handleEvent(this,e)&&this.tools.dispatch(e)}}else this.cancelInteractionAndClearTransients(t.reason);else this.handleWheelEvent(t)}handleInteractionEvent(e){const t=this.normalizeEvent(e);return this.inputs.handleEvent(t),"handled"===this.interactions.handleEvent(this,t)}runKeyboardShortcutTarget(e){switch(e.type){case"action":return!1;case"editor":return this.runEditorKeyboardShortcut(e.command);case"tool":return this.commands.setActiveTool(e.toolId,{source:"system"}),!0}}runEditorKeyboardShortcut(e){switch(e){case"delete-selection":return!this.getShapeEditingSession()&&(this.deleteSelection("user"),!0);case"move-selection-backward":return this.moveSelectionWithinParent("backward","user");case"move-selection-forward":return this.moveSelectionWithinParent("forward","user");case"redo":return this.redo(),!0;case"reset-interaction":return"handled"===this.interactions.broadcastEvent(this,{type:"cancel",reason:"escape"})?(this.tools.cancel("escape"),this.inputs.resetPointer(),this.clearSelectionTransients(),!0):(this.tools.isActiveToolInInitialState()&&"select"!==this.getActiveToolId()?this.commands.setActiveTool("select",{source:"system"}):this.cancelInteractionAndClearTransients("escape"),!0);case"undo":return this.undo(),!0}}normalizeEvent(e){if("pointer"!==e.type)return e;if("pointer_up"===e.name){const t=e.clickCount===this.currentPointerClickCount?e:{...e,clickCount:this.currentPointerClickCount};return this.lastPointerUpForClickCount={timestamp:t.timestamp,screenPoint:t.screenPoint.clone()},t}if("pointer_down"!==e.name)return e;const t=this.lastPointerDownForClickCount,n=this.lastPointerUpForClickCount,o=t&&n&&n.timestamp>=t.timestamp&&e.timestamp-n.timestamp<=250&&n.screenPoint.dist2(e.screenPoint)<=1600?2:1;return this.lastPointerDownForClickCount={timestamp:e.timestamp,screenPoint:e.screenPoint.clone()},this.currentPointerClickCount=o,e.clickCount===o?e:{...e,clickCount:o}}getDoubleClickEvent(e){return(e.clickCount??1)<2||this.currentPointerClickCount<2?null:{type:"click",name:"double_click",phase:"up",timestamp:e.timestamp,pointerId:e.pointerId,button:e.button,buttons:e.buttons,pointerType:e.pointerType,screenPoint:e.screenPoint.clone(),pagePoint:e.pagePoint.clone(),pressure:e.pressure,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}listen(e){return this.store.listen(t=>e(t))}getRenderItems(){return this.renderItemsSignal.get()}getPages(){return this.pagesSignal.get()}getDocumentMetadataRecord(){const e=this._internalStore.get(DC);return g(e)?e:void 0}getCurrentPageId(){return this.currentPageIdSignal.get()}getActiveToolId(){return this.sessionSignal.get().activeToolId}isToolLocked(){return this.sessionSignal.get().isToolLocked}isActiveToolInInitialState(){return this.tools.isActiveToolInInitialState()}getEditingShapeId(){return this.editingShapeIdSignal.get()}getShapeEditingSession(){return this.shapeEditingSessionSignal.get()}getShapeEditingEntryRequest(){return this.shapeEditingEntryRequestSignal.get()}resetPointerClickTracking(){this.lastPointerDownForClickCount=null,this.lastPointerUpForClickCount=null,this.currentPointerClickCount=1}getCurrentPageShapeIds(){return this.currentPageShapeIdsSignal.get()}getPage(e){const t=this._internalStore.get(e);return h(t)?t:void 0}getCurrentCamera(){return this.camera.getCurrentCamera()}undo(){return this.history.getActiveScope()||this.cancelInteractionForCommand(),this.history.undo()}redo(){return this.history.getActiveScope()||this.cancelInteractionForCommand(),this.history.redo()}createPageAndSelect(e,t="user"){const n=this.commands.createPage(e,{source:t});return this.commands.setCurrentPageId(n.id,{source:t}),n}selectPage(e,t="user"){this.commands.setCurrentPageId(e,{source:t})}renamePage(e,t,n="user"){this.commands.renamePage({id:e,name:t},{source:n})}updateDocumentMeta(e,t="user"){return this.commands.updateDocumentMeta({patch:e},{source:t})}updatePageMeta(e,t,n="user"){return this.commands.updatePageMeta({id:e,patch:t},{source:n})}deletePage(e,t="user"){return this.cancelInteractionForCommand(),this.commands.deletePage(e,{source:t})}setActiveTool(e,t="system"){this.commands.setActiveTool(e,{source:t})}setToolLocked(e,t="system"){this.commands.setToolLocked(e,{source:t})}toggleToolLocked(e="system"){this.setToolLocked(!this.isToolLocked(),e)}getCamera(e=this.getCurrentPageId()){return this.camera.getCamera(e)}pageToScreen(e,t=this.getCurrentPageId()){return this.camera.pageToScreen(e,t)}screenToPage(e,t=this.getCurrentPageId()){return this.camera.screenToPage(e,t)}getSelectedShapeIds(e=this.getCurrentPageId()){return this.getSessionRecord().pageSelectedShapeIdsById[e]??[]}isShapeHidden(e){const t=new Set;let n=this.getShape(e);for(;n;){if(n.isHidden)return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(t.has(e))return!1;t.add(e);const o=this.getShape(e);if(!o)return!1;if(!this.getShapeUtil(o).isChildVisible(o,n,{editor:this}))return!0;n=o}return!1}getSelectedShapes(){return this.selectedShapesSignal.get()}getDefaultShapeProps(e){const t=this.shapeUtils.get(e),n=this._shapeDefaultPropsByTypeSignal.get().get(e)??{};return t.validateProps({...t.getDefaultProps(),...n})}updateDefaultShapeProps(e,t){const n=this.shapeUtils.get(e),o=this._shapeDefaultPropsByTypeSignal.get().get(e)??{},i=n.validateProps({...n.getDefaultProps(),...o,...t}),r=n.validateProps(n.getDefaultProps()),s={};for(const[d,l]of Object.entries(i))r[d]!==l&&(s[d]=l);if(((e,t)=>{if(e===t)return!0;const n=Object.entries(e),o=Object.entries(t);if(n.length!==o.length)return!1;for(const[i,r]of n)if(!at(r,t[i]))return!1;return!0})(o,s))return;const a=new Map(this._shapeDefaultPropsByTypeSignal.get());0===Object.keys(s).length?a.delete(e):a.set(e,s),this._shapeDefaultPropsByTypeSignal.set(a)}getSelectionParentOrderState(){return this.hierarchy.getSelectionParentOrderState()}getSelectionGroupState(){return this.hierarchy.getSelectionGroupState()}canGroupSelection(){return this.hierarchy.canGroupSelection()}canGroupShapes(e){return this.hierarchy.canGroupShapes(e)}groupShapes(e,t="user"){return this.hierarchy.groupShapes(e,t)}groupSelection(e="user"){return this.hierarchy.groupSelection(e)}getUngroupableSelectedShapeIds(){return this.hierarchy.getUngroupableSelectedShapeIds()}getUngroupableShapeIds(e){return this.hierarchy.getUngroupableShapeIds(e)}canUngroupSelection(){return this.hierarchy.canUngroupSelection()}canUngroupShapes(e){return this.hierarchy.canUngroupShapes(e)}ungroupShapes(e,t="user"){return this.hierarchy.ungroupShapes(e,t)}ungroupSelection(e="user"){return this.hierarchy.ungroupSelection(e)}getSelectionSiblingOrderState(){return this.hierarchy.getSelectionSiblingOrderState()}canMoveSelectionWithinParent(e){return this.hierarchy.canMoveSelectionWithinParent(e)}canMoveSelectionInParentOrder(e){return this.hierarchy.canMoveSelectionInParentOrder(e)}canMoveShapesInParentOrder(e,t){return this.hierarchy.canMoveShapesInParentOrder(e,t)}moveShapesInParentOrder(e,t,n="user"){return this.hierarchy.moveShapesInParentOrder(e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return this.hierarchy.moveShapesToParentOrderEdge(e,t,n)}moveSelectionWithinParent(e,t="user"){return this.hierarchy.moveSelectionWithinParent(e,t)}canAlignSelection(){return this.selectionLayout.canAlign()}alignSelection(e,t="user"){return this.cancelInteractionForCommand(),this.selectionLayout.align(e,t)}canDistributeSelection(){return this.selectionLayout.canDistribute()}distributeSelection(e,t="user"){return this.cancelInteractionForCommand(),this.selectionLayout.distribute(e,t)}moveShapesToParentPlacementResult(e,t="user"){return this.hierarchy.moveShapesToParentPlacementResult(e,t)}moveSelectionInParentOrder(e,t="user"){return this.hierarchy.moveSelectionInParentOrder(e,t)}moveSelectionToParentOrderEdge(e,t="user"){return this.hierarchy.moveSelectionToParentOrderEdge(e,t)}canEditShape(e){return this.editing.canEditShape(e)}startEditingShape(e,t="user"){return this.editing.start(e,t)}completeEditing(e="user"){return this.editing.complete(e)}cancelEditing(e="user"){return this.editing.cancel(e)}setShapeEditingComposition(e,t="system"){this.editing.setComposition(e,t)}consumeShapeEditingEntryRequest(e){this.editing.consumeEntryRequest(e)}deleteSelection(e="user"){this.deleteShapesById(this.getSelectedShapeIds(),e)}deleteShapesById(e,t="user"){const n=Array.from(new Set(e));0!==n.length&&(this.cancelInteractionForCommand(),this.commands.deleteShapes(n,{source:t}))}setShapesHidden(e,t,n="user"){const o=Array.from(new Set(e.filter(e=>{const n=this.getShape(e);return!!n&&n.isHidden!==t})));return 0===o.length?[]:(this.cancelInteractionForCommand(),this.commands.updateShapes(o.map(e=>({id:e,isHidden:t})),{source:n}),t&&(this.removeShapeIdsFromSelection(this.getShapeIdsIncludingDescendants(o),n),this.removeShapeIdsFromEditingSession(this.getShapeIdsIncludingDescendants(o),n)),o)}setShapesLocked(e,t,n="user"){const o=Array.from(new Set(e.filter(e=>{const n=this.getShape(e);return!!n&&n.isLocked!==t})));return 0===o.length?[]:(this.cancelInteractionForCommand(),this.commands.updateShapes(o.map(e=>({id:e,isLocked:t})),{source:n}),t&&(this.removeShapeIdsFromSelection(this.getShapeIdsIncludingDescendants(o),n),this.removeShapeIdsFromEditingSession(this.getShapeIdsIncludingDescendants(o),n)),o)}createClipboardPayloadFromSelection(){return this.clipboard.createPayloadFromSelection()}pasteClipboardPayload(e){return this.clipboard.pastePayload(e)}duplicateSelection(e={}){return this.clipboard.duplicateSelection(e)}selectAllCurrentPage(e="user"){this.cancelInteractionForCommand(),this.selection.selectAllCurrentPage(e)}resetSelectionRotation(e="user"){((e,t="user")=>{if(!e.canRotateSelection())return;const n=e.getSelectedShapes().filter(t=>e.getShapeUtil(t).contributesToSelectionFrame(t,{editor:e}));if(0===n.length)return;const o=n.flatMap(t=>{const n=Zt(e,t);if(!n)return[];const o=Qt(e,t,n,{id:t.id,rotation:0});return o?[o]:[]});o.length>0&&e.commands.updateShapes(o,{source:t})})(this,e)}flipSelection(e,t="user"){const n=function(e,t){if(!e.canFlipSelection())return[];const n=e.getSelectionTransformTargetShapes(),o=e.getSelectionFrame()??((e,t)=>{const n=t.flatMap(t=>{const n=Zt(e,t);return n?e.getShapeUtil(t).getSelectionPagePoints(n)??[]:[]});if(0===n.length)return null;const o=LC.FromPoints(n);return{bounds:o,rotation:0,rotationCenter:o.center,hasCompatibleRotation:!0}})(e,n);return o&&0!==n.length?n.map(n=>((e,t,n,o)=>{const i=e.getShapeUtil(t),r=Zt(e,t);if(!r)return null;const s=i.getSelectionPagePoints(r);if(!s&&!i.contributesToSelectionFrame(t,{editor:e}))return null;const a=(({points:e,transform:t})=>0===e.length?null:LC.FromPoints(e.map(e=>yo(e,t))))({points:s?[...s]:i.getPositionedOutlineVertices(t).map(n=>e.computeShapePositionedToPageTransform(t).applyToPoint(n)),transform:n});return a?Qt(e,t,r,i.flipSelectionBounds(r,{axis:o,selectionBounds:n.bounds,selectionLocalBounds:Po({axis:o,bounds:a,selectionBounds:n.bounds}),selectionRotation:n.rotation,selectionRotationCenter:n.rotationCenter})):null})(e,n,o,t)).filter(e=>null!==e):[]}(this,e);0!==n.length&&(this.cancelInteractionForCommand(),this.commands.updateShapes(n,{source:t}))}getShape(e){const t=this._internalStore.get(e);return f(t)?t:void 0}getAsset(e){const t=this._internalStore.get(e);return S(t)?t:void 0}getAssets(){return this._internalStore.getAll().filter(S).sort((e,t)=>e.id.localeCompare(t.id))}resolveAssetUrl(e){return this.assetUrlResolver(e)}getUnreferencedAssetIdsAfterShapeDelete(e){if(0===e.length)return[];const t=new Set(e),n=new Set,o=new Set;for(const i of this._internalStore.getAll().filter(f)){const e=st(i);e&&(t.has(i.id)?n.add(e):o.add(e))}return this.getAssets().map(e=>e.id).filter(e=>n.has(e)&&!o.has(e))}getShapeSignal(e){let t=this.shapeSignals.get(e);return t||(t=d(`editor.shape.${e}`,()=>{const t=this._internalStore.getRecordSignal(e).get();return f(t)?t:void 0}),this.shapeSignals.set(e,t)),t}getShapeContentCutoutLocalPolygonsSignal(e){let t=this.shapeContentCutoutLocalPolygonSignals.get(e);return t||(t=d(`editor.shapeContentCutouts.${e}`,()=>{const t=this.getShapeSignal(e).get();return t?this.queries.getBindingsToShapeSignal(e).get().flatMap(e=>{const n=this.getShapeSignal(e.fromId).get();return n?this.getBindingUtil(e).getTargetShapeContentCutoutLocalPolygons?.(this,e,{fromShape:n,toShape:t})??[]:[]}):[]},{isEqual:Qe}),this.shapeContentCutoutLocalPolygonSignals.set(e,t)),t}getShapeLocalToPageTransformSignal(e){return this.queries.getShapeLocalToPageTransformSignal(e)}getShapeSelectedSignal(e){let t=this.shapeSelectedSignals.get(e);return t||(t=d(`editor.shapeSelected.${e}`,()=>this.selectedShapeIdSetSignal.get().has(e)),this.shapeSelectedSignals.set(e,t)),t}getShapeRenderOrderSignal(e){let t=this.shapeRenderOrderSignals.get(e);return t||(t=d(`editor.shapeRenderOrder.${e}`,()=>this.shapeRenderOrderByIdSignal.get().get(e)??-1),this.shapeRenderOrderSignals.set(e,t)),t}getShapeRenderVisibleSignal(e){let t=this.shapeRenderVisibleSignals.get(e);return t||(t=d(`editor.shapeRenderVisible.${e}`,()=>{const t=this.getShapeClipAncestorIdsSignal(e).get().length>0;return this.renderVisibleShapeIdSetSignal.get().has(e)&&this.getShapeDocumentVisibleSignal(e).get()&&(!t||null!==this.getShapeClippedPageBounds(e))}),this.shapeRenderVisibleSignals.set(e,t)),t}getShapeDocumentVisibleSignal(e){let t=this.shapeDocumentVisibleSignals.get(e);return t||(t=d(`editor.shapeDocumentVisible.${e}`,()=>{const t=new Set([e]);let n=this.getShapeSignal(e).get();if(!n)return!1;for(;n;){if(n.isHidden)return!1;if(!n.parentId.startsWith("shape:"))return!0;const e=n.parentId;if(t.has(e))return!0;t.add(e);const o=this.getShapeSignal(e).get();if(!o)return!0;if(!this.getShapeUtil(o).isChildVisible(o,n,{editor:this}))return!1;n=o}return!0}),this.shapeDocumentVisibleSignals.set(e,t)),t}getShapeEffectiveOpacitySignal(e){let t=this.shapeEffectiveOpacitySignals.get(e);return t||(t=d(`editor.shapeEffectiveOpacity.${e}`,()=>{const t=new Set([e]);let n=1,o=this.getShapeSignal(e).get();for(;o&&(n*=o.opacity,o.parentId.startsWith("shape:"));){const e=o.parentId;if(t.has(e))break;t.add(e),o=this.getShapeSignal(e).get()}return n}),this.shapeEffectiveOpacitySignals.set(e,t)),t}getShapeEditingSessionForShapeSignal(e){let t=this.shapeEditingSessionSignals.get(e);return t||(t=d(`editor.shapeEditingSessionForShape.${e}`,()=>{const t=this.shapeEditingSessionSignal.get();return t?.shapeId===e?t:null}),this.shapeEditingSessionSignals.set(e,t)),t}getShapeDropTargetSignal(e){let t=this.shapeDropTargetSignals.get(e);return t||(t=d(`editor.shapeDropTarget.${e}`,()=>this.dropTargetShapeIdSignal.get()===e),this.shapeDropTargetSignals.set(e,t)),t}getShapeHoveredSignal(e){let t=this.shapeHoveredSignals.get(e);return t||(t=d(`editor.shapeHovered.${e}`,()=>{const t=this.hoveredShapeIdSignal.get();if(!t)return!1;const n=this.getShapeSignal(e).get();return!!n&&this.getShapeUtil(n).getHoverDecorationTargetId(n,{editor:this})===t}),this.shapeHoveredSignals.set(e,t)),t}getShapeSelectedDescendantTransformAncestorSignal(e){let t=this.shapeSelectedDescendantTransformAncestorSignals.get(e);return t||(t=d(`editor.shapeSelectedDescendantTransformAncestor.${e}`,()=>{if(this.getShapeSelectedSignal(e).get())return!1;const t=this.getShapeSignal(e).get();return!(!t||!this.getShapeUtil(t).isSelectionTransformContainer(t))&&this.selectedShapeIdsSignal.get().some(t=>this.hierarchy.isShapeDescendantOf(t,e))}),this.shapeSelectedDescendantTransformAncestorSignals.set(e,t)),t}getBinding(e){const t=this._internalStore.get(e);return y(t)?t:void 0}getShapesForPage(e){return this.queries.getShapesForPage(e)}getBindingsFromShape(e){return this.queries.getBindingsFromShape(e)}getBindingsFromShapeSignal(e){return this.queries.getBindingsFromShapeSignal(e)}getBindingsToShape(e){return this.queries.getBindingsToShape(e)}getBindingsToShapeSignal(e){return this.queries.getBindingsToShapeSignal(e)}getBindingsForShape(e){return this.queries.getBindingsForShape(e)}getBindingsForShapeSignal(e){return this.queries.getBindingsForShapeSignal(e)}getChildShapeIds(e){return this.queries.getChildShapeIds(e)}getChildShapes(e){return this.queries.getChildShapes(e)}getDescendantShapeIds(e){return this.queries.getDescendantShapeIds(e)}getDescendantPageBounds(e){return this.queries.getDescendantPageBounds(e)}getShapeSubtreePageBounds(e){return this.queries.getShapeSubtreePageBounds(e)}getShapePageId(e){return this.queries.getPageIdForShape(e)}isShapeOrAncestorLocked(e){return this.hierarchy.isShapeOrAncestorLocked(e)}hasLockedDescendant(e){return this.hierarchy.hasLockedDescendant(e)}getOutermostSelectableShapeId(e){return this.hierarchy.getOutermostSelectableShapeId(e)}getShapeIdsIncludingDescendants(e){return this.hierarchy.getShapeIdsIncludingDescendants(e)}getShapeIdsForSelectionTransform(e){return this.hierarchy.getShapeIdsForSelectionTransform(e)}getShapeIdsForSelectionRotation(e){return this.hierarchy.getShapeIdsForSelectionRotation(e)}getSelectionTransformTargetShapes(){return this.hierarchy.getSelectionTransformTargetShapes()}canResizeSelection(){return this.hierarchy.canResizeSelection()}canFlipSelection(){return this.selectionCanFlipSignal.get()}canRotateSelection(){return this.hierarchy.canRotateSelection()}getSelectionResizeTargetShapes(){return this.hierarchy.getSelectionResizeTargetShapes()}getSelectionRotationTargetShapes(){return this.hierarchy.getSelectionRotationTargetShapes()}getShapeExportTraversalIds(e){return this.hierarchy.getShapeExportTraversalIds(e)}getShapeContainment(e,t){return this.queries.getShapeContainment(e,t)}getContainingShapeParentId(e){return this.queries.getContainingShapeParentId(e)}getContainingShapeParentIdAtPoint(e,t){return this.queries.getContainingShapeParentIdAtPoint(e,t)}getContainingParentIdForShapeRecord(e){return this.queries.getContainingParentIdForShapeRecord(e)}getShapeClipAncestorIds(e){return this.queries.getShapeClipAncestorIds(e)}getShapeClipAncestorIdsSignal(e){return this.queries.getShapeClipAncestorIdsSignal(e)}isPagePointInShapeClip(e,t){return this.queries.isPagePointInShapeClip(e,t)}getShapeClippedPageBounds(e){return this.queries.getShapeClippedPageBounds(e)}getShapeIdsInContainerBounds(e,t={}){return this.hierarchy.getShapeIdsInContainerBounds(e,t)}canUseShapeParent(e,t){return this.hierarchy.canUseShapeParent(e,t)}getShapeUtil(e){return this.shapeUtils.get(e.type)}getBindingUtil(e){return this.bindingUtils.get(e.type)}computeShapePositionedBounds(e){return this.geometry.computeShapePositionedBounds(e)}computeShapeLocalBounds(e){return this.geometry.computeShapeLocalBounds(e)}computeShapeRenderBounds(e){return this.geometry.computeShapeRenderBounds(e)}computeShapeExportBounds(e){return this.geometry.computeShapeExportBounds(e)}computeShapeLocalToPageTransform(e){return this.geometry.computeShapeLocalToPageTransform(e)}computeShapeRenderToPageTransform(e){return this.geometry.computeShapeRenderToPageTransform(e)}computeShapeExportToPageTransform(e){return this.geometry.computeShapeExportToPageTransform(e)}computeShapePageBounds(e){return this.geometry.computeShapePageBounds(e)}computeShapeExportPageBounds(e){return this.geometry.computeShapeExportPageBounds(e)}computeShapeGeometry(e){return this.geometry.computeShapeGeometry(e)}computeShapePositionedToPageTransform(e){return this.geometry.computeShapePositionedToPageTransform(e)}computeShapePageCenter(e){return this.geometry.computeShapePageCenter(e)}computeShapePageCorners(e){return this.geometry.computeShapePageCorners(e)}computeShapePageOutlineVertices(e){return this.geometry.computeShapePageOutlineVertices(e)}getShapePositionedBounds(e){return this.geometry.getShapePositionedBounds(e)}getShapePageBounds(e){return this.geometry.getShapePageBounds(e)}getShapeGeometry(e){return this.geometry.getShapeGeometry(e)}getShapePositionedToPageTransform(e){return this.geometry.getShapePositionedToPageTransform(e)}getShapePageCenter(e){return this.geometry.getShapePageCenter(e)}getShapePageCorners(e){return this.geometry.getShapePageCorners(e)}getShapePageOutlineVertices(e){return this.geometry.getShapePageOutlineVertices(e)}getSelectionPageBounds(){return this.geometry.getSelectionPageBounds()}getSelectionFrame(){return this.geometry.getSelectionFrame()}isPointInSelectionBounds(e){return this.geometry.isPointInSelectionBounds(e)}getSelectionFrameLocalBoundsPoint(e){return this.geometry.getSelectionFrameLocalBoundsPoint(e)}getSelectionPageOutlineVertices(){return this.geometry.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.geometry.getSelectionAnchorPagePoint()}hitTestSelectionHandle(e){const t=this.selectedShapesSignal.get(),n=this.getSelectionFrame();if(0===t.length)return null;const o=1===t.length,i=this.canResizeSelection(),r=this.canRotateSelection(),{terminalHandles:s,middleHandles:a,customHandles:d,rotateHandles:l,resizeHandles:c}=((e,t,n,o,i,r,s)=>ti(ei(e,t,n,o,i,r,s),n))(t,n,this.getCurrentCamera().z,e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:o,editor:this}),e=>i&&this.getShapeUtil(e).canUseSelectionResizeHandles(e,{editor:this}),e=>r&&this.getShapeUtil(e).canUseSelectionRotateHandle(e,{editor:this}),Eo(this,this.getSelectionResizeTargetShapes(),n?.rotation??0));for(const u of a)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of s)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of d)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of c)if(u.bounds.containsPoint(e))return u;if(n){const t=((e,t,n,o)=>{const i=new Set(n.map(e=>e.id)),r=yo(e,t),{bounds:s}=t,a=[];r.x>=s.minX&&r.x<=s.maxX&&(i.has("top")&&a.push({id:"top",distance:Math.abs(r.y-s.minY)}),i.has("bottom")&&a.push({id:"bottom",distance:Math.abs(r.y-s.maxY)})),r.y>=s.minY&&r.y<=s.maxY&&(i.has("right")&&a.push({id:"right",distance:Math.abs(r.x-s.maxX)}),i.has("left")&&a.push({id:"left",distance:Math.abs(r.x-s.minX)}));const d=a.filter(e=>e.distance<=o).sort((e,t)=>e.distance-t.distance)[0];return d?{kind:"resize",id:d.id,point:e.clone(),bounds:new LC(e.x-o,e.y-o,2*o,2*o)}:null})(e,n,c,6/this.getCurrentCamera().z);if(t)return t}for(const u of l)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;return null}setBrushBox(e){this.transients.setBrushBox(e)}setBindingPreview(e){this.transients.setBindingPreview(e)}setTerminalBindingGuides(e){this.transients.setTerminalBindingGuides(e)}setDropTargetShapeId(e){this.transients.setDropTargetShapeId(e)}setHoveredShapeId(e){this.transients.setHoveredShapeId(e)}setSelectionTranslationActive(e){this.transients.setSelectionTranslationActive(e)}setSnapIndicators(e){this.transients.setSnapIndicators(e)}setTerminalBindingResolver(e){this.transients.setTerminalBindingResolver(e)}resolveTerminalBinding(e){return this.transients.resolveTerminalBinding(e)}clearSelectionTransients(){this.transients.clearSelectionTransients()}hitTestShape(e){return this.hitTestShapesAtPoint(e)[0]??null}hitTestShapesAtPoint(e,t){return this.spatialIndex.getShapesAtPoint(e,{...t,filter:n=>!this.isShapeHidden(n.id)&&this.isPagePointInShapeClip(n.id,e)&&(t?.filter?.(n)??!0)})}hitTestShapesByLineSegment(e,t,n){return this.spatialIndex.getShapesHitByLineSegment(e,t,{...n,filter:e=>!this.isShapeHidden(e.id)&&(n?.filter?.(e)??!0)})}getShapeIdsInBounds(e,t){return this.spatialIndex.getShapeIdsInBounds(e,t).filter(e=>!this.isShapeHidden(e))}getShapesInBounds(e,t){return this.spatialIndex.getShapesInBounds(e,t).filter(e=>!this.isShapeHidden(e.id))}getShapesInViewport(e,t){return this.spatialIndex.getShapesInViewport(e,t).filter(e=>!this.isShapeHidden(e.id))}getDocumentSnapshot(){return this.snapshots.getDocumentSnapshot()}getSessionSnapshot(){return this.snapshots.getSessionSnapshot()}getSvgString(e=this.getSelectedShapeIds(),t){return function(e,t,n,o={}){const i=Array.from(t),r=e.getShapeExportTraversalIds(i),s=new Set(r),a=[],d=[];for(const I of r){const t=e.getShape(I);t?d.push(t):a.push({id:I,reason:"missing-shape"})}if(0===d.length)return null;const l=[];for(const I of d){if(!e.getShapeUtil(I).contributesToExportBounds(I))continue;const t=W(e,I,s);t&&(j(t)?l.push(t):a.push({id:I.id,reason:"missing-bounds"}))}if(0===l.length)return null;const c=(e=>{let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),o=Math.max(o,r.maxX),i=Math.max(i,r.maxY);return new LC(t,n,o-t,i-n)})(l).expand(o.padding??16),u=[],p={editor:e,bounds:c,addDef(e){const t=`land-svg-def-${u.length+1}`;return u.push({...e,attrs:{...e.attrs,id:t}}),t},resolveAssetUrl:t=>e.resolveAssetUrl(t),resolveColor:e=>D(e,o.resolveThemeColor)},h=[],g=[],f=new Map,m=[],y=(t,n)=>{const o=e.computeShapeExportToPageTransform(t),i=((e,t)=>{let n=t.opacity,o=t.parentId;const i=new Set([t.id]);for(;o.startsWith("shape:");){const t=o;if(i.has(t))break;i.add(t);const r=e.getShape(t);if(!r)break;n*=r.opacity,o=r.parentId}return n})(e,t),r=((e,t,n,o,i)=>{const r=[];for(const s of X(e,t,n)){const t=Y(e,s,o,i);t&&r.push(t)}return r})(e,t,s,f,p);let a={tag:"g",attrs:{transform:o.toSvgString(),opacity:1===i?void 0:i},children:[n]};for(let e=r.length-1;e>=0;e-=1)a={tag:"g",attrs:{"clip-path":`url(#${r[e]})`},children:[a]};g.push(a)},S=e=>{const t=n.get(e.type)?.toSvgForeground?.(e,p);t&&y(e,t)};for(const I of d){for(;m.length>0&&!N(e,m[m.length-1].id,I);)S(m.pop());const t=n.get(I.type);if(!t){a.push({id:I.id,reason:"missing-exporter"});continue}const o=t.toSvg(I,p);o?j(e.computeShapeExportBounds(I))?(h.push(I.id),y(I,o),t.toSvgForeground&&m.push(I)):a.push({id:I.id,reason:"missing-bounds"}):a.push({id:I.id,reason:"empty-output"})}for(;m.length>0;)S(m.pop());if(0===h.length)return null;const b=Math.max(1,c.w),x=Math.max(1,c.h),w=[];return u.length>0&&w.push({tag:"defs",children:u}),o.background&&w.push({tag:"rect",attrs:{x:c.x,y:c.y,width:c.w,height:c.h,fill:o.background}}),w.push(...g),{svg:q({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:b,height:x,viewBox:`${G(c.x)} ${G(c.y)} ${G(b)} ${G(x)}`},children:w}),bounds:c,width:b,height:x,requestedShapeIds:i,exportedShapeIds:h,skippedShapes:a}}(this,e,this.shapeSvgExporters,t)}getExportIntegrityReport(e=this.getSelectedShapeIds()){return Q({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}repairExportIntegrity(e=this.getSelectedShapeIds()){return(({editor:e,exporters:t,shapeIds:n})=>{const o=Array.from(n),i=Q({editor:e,exporters:t,shapeIds:o});i.repairableIssueCount>0&&e.bindings.repairLoadedBindings("system");const r=Q({editor:e,exporters:t,shapeIds:o});return{before:i,after:r,repaired:i.issues.length!==r.issues.length}})({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}getShapeCapabilityManifest(){return(({definitions:e,exporters:t,shapeUtils:n})=>{const o=e.map(e=>{const o=n.has(e.type)?"supported":"missing",i=t.has(e.type)?"supported":"missing",r="supported"===o&&"supported"===i?"supported":"missing";return{...e,shapeUtil:o,svgExporter:i,exportSupport:r}});return{entries:o,supportedExportTypes:o.filter(e=>"supported"===e.exportSupport).map(e=>e.type),missingExporterTypes:o.filter(e=>"supported"!==e.svgExporter).map(e=>e.type)}})({definitions:this.shapeCapabilityDefinitions,exporters:this.shapeSvgExporters,shapeUtils:this.shapeUtils})}createPageRecord(e){const t=this.nextPageNumber;return{id:this.createPageId(t),typeName:"page",scope:"document",name:e?.name??`Page ${t}`,index:e?.index??this.createPageIndex(t),meta:e?.meta??{}}}loadDocumentSnapshot(e,t){this.snapshots.loadDocumentSnapshot(e,t)}loadSessionSnapshot(e,t){this.snapshots.loadSessionSnapshot(e,t)}syncAfterDocumentRestore(){this.snapshots.syncAfterDocumentRestore()}cancelInteractionForCommand(){this.cancelInteractionAndClearTransients("command")}cancelInteractionAndClearTransients(e,t={}){!1!==t.notifyInteractionHandlers&&this.interactions.broadcastEvent(this,{type:"cancel",reason:e}),this.tools.cancel(e),this.inputs.resetPointer(),this.clearSelectionTransients()}syncToolStateFromSession(e){const{activeToolId:t,isToolLocked:n}=this.sessionSignal.get();this.tools.hasTool(t)?this.tools.setActiveTool(t,"restore"):(this.tools.setActiveTool("select","restore"),this.updateSession({activeToolId:"select"},e)),this.tools.setToolLocked(n)}createShapeRecord(e){const t=e.parentId??this.sessionSignal.get().currentPageId;if(!this.canUseShapeParent(t))throw new Error("Invalid parent id for shape");const n=this.nextShapeNumber,o=this.createShapeId(n),i=this.shapeUtils.get(e.type).validateProps({...this.getDefaultShapeProps(e.type),...e.props});return{id:o,typeName:"shape",scope:"document",type:e.type,parentId:t,index:e.index??this.createShapeIndex(n),x:e.x,y:e.y,rotation:e.rotation??0,skewX:e.skewX??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,opacity:e.opacity??1,isHidden:e.isHidden??!1,isLocked:e.isLocked??!1,props:i,meta:e.meta??{}}}createBindingRecord(e){const t=e.id??this.createBindingId(this.nextBindingNumber),n=this.bindingUtils.get(e.type),o=n.validateProps({...n.getDefaultProps(),...e.props});return{id:t,typeName:"binding",scope:"document",type:e.type,fromId:e.fromId,toId:e.toId,props:o,meta:e.meta??{}}}createAssetRecord(e){return{id:e.id??this.createAssetId(this.nextAssetNumber),typeName:"asset",scope:"document",type:e.type,props:e.props??{},meta:e.meta??{}}}updateSession(e,t="system"){const n=this.getSessionRecord();this._internalStore.put([{...n,...e}],t)}setCurrentPage(e,t="system"){if(!this.getPage(e))return;e!==this.getCurrentPageId()&&(this.cancelInteractionAndClearTransients("page_switch"),this.completeEditing(t));const n=this.sessionSignal.get();this.updateSession({currentPageId:e,pageCameraById:{...n.pageCameraById,[e]:n.pageCameraById[e]??{...NC}},pageSelectedShapeIdsById:{...n.pageSelectedShapeIdsById,[e]:n.pageSelectedShapeIdsById[e]??[]}},t)}setSelectedShapeIds(e,t){this.selection.setSelectedShapeIds(e,t)}removeShapeIdsFromSelection(e,t="system"){this.selection.removeShapeIdsFromSelection(e,t)}removeShapeIdsFromEditingSession(e,t="system"){this.editing.removeShapeIds(e,t)}prepareShapeIdsForRemoval(e,t="system"){this.editing.prepareForShapeRemoval(e,t)}ensurePageSessionState(e,t="system"){const n=this.sessionSignal.get(),o=n.pageCameraById[e]??{...NC},i=n.pageSelectedShapeIdsById[e]??[];this.updateSession({pageCameraById:{...n.pageCameraById,[e]:o},pageSelectedShapeIdsById:{...n.pageSelectedShapeIdsById,[e]:i}},t)}removePageSessionState(e,t,n="system"){const o=this.sessionSignal.get(),i={...o.pageCameraById},r={...o.pageSelectedShapeIdsById};delete i[e],delete r[e],this.updateSession({currentPageId:t,pageCameraById:i,pageSelectedShapeIdsById:r},n)}setCamera(e,t){this.camera.setCamera(e,t)}panCamera(e,t="system"){this.camera.panCamera(e,t)}zoomCameraAtScreenPoint(e,t,n="system"){this.camera.zoomCameraAtScreenPoint(e,t,n)}zoomCameraToScreenPoint(e,t,n="system"){this.camera.zoomCameraToScreenPoint(e,t,n)}zoomAtViewportCenter(e,t="system"){this.camera.zoomAtViewportCenter(e,t)}resetZoom(e="user"){this.camera.resetZoom(e)}setViewportScreenSize(e){this.camera.setViewportScreenSize(e)}getCurrentPageBounds(e=this.getCurrentPageId()){return this.selectionLayout.getCurrentPageBounds(e)}zoomToBounds(e,t){return this.selectionLayout.zoomToBounds(e,t)}zoomToFit(e){return this.selectionLayout.zoomToFit(e)}zoomToSelection(e){return this.selectionLayout.zoomToSelection(e)}createShapeId(e){const t=`shape:${e}`;return this.nextShapeNumber+=1,t}createShapeIndex(e){return String(e).padStart(6,"0")}createBindingId(e){const t=`binding:${e}`;return this.nextBindingNumber+=1,t}createAssetId(e){const t=`asset:${e}`;return this.nextAssetNumber+=1,t}syncShapeCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!f(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextShapeNumber=e+1}syncPageCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!h(t))continue;const n=t.id.split(":")[1]??"",o=Number("default"===n?1:n);Number.isFinite(o)&&(e=Math.max(e,o))}this.nextPageNumber=e+1}syncBindingCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!y(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextBindingNumber=e+1}syncAssetCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!S(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextAssetNumber=e+1}dispose(){this.runtime.dispose()}createPageId(e){const t=`page:${e}`;return this.nextPageNumber+=1,t}createPageIndex(e){return String(e).padStart(4,"0")}handleWheelEvent(e){if(e.ctrlKey){const t=this.getCurrentCamera(),n=e.delta.y,o=(Math.abs(n)>10?10*Math.sign(n):n)/100;return void this.zoomCameraToScreenPoint(e.screenPoint,t.z-1*o*t.z)}this.panCamera(e.delta)}},OT=[{id:"top",normalizedAnchor:{x:.5,y:0},outwardNormal:{x:0,y:-1}},{id:"right",normalizedAnchor:{x:1,y:.5},outwardNormal:{x:1,y:0}},{id:"bottom",normalizedAnchor:{x:.5,y:1},outwardNormal:{x:0,y:1}},{id:"left",normalizedAnchor:{x:0,y:.5},outwardNormal:{x:-1,y:0}}],DT=class{getPositionedBounds(e){const t=this.getLocalBounds(e);return new LC(t.x+e.x,t.y+e.y,t.w,t.h)}getRenderBounds(e){return this.getLocalBounds(e)}getPointHitTestBounds(e,t){return this.getPositionedBounds(e)}getExportBounds(e){return this.getRenderBounds(e)}getChildClipLocalBounds(e){return null}getChildClipLocalPolygons(e){const t=this.getChildClipLocalBounds(e);return t?[Ei(t)]:null}getChildExportClipLocalBounds(e){return this.getChildClipLocalBounds(e)}getChildExportClipLocalPolygons(e){const t=this.getChildExportClipLocalBounds(e);return t?[Ei(t)]:null}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=this.getSelectionResizeLocalBounds(e);if(0!==n.x||0!==n.y)throw new Error(`Shape util "${this.type}" must implement resizeSelectionBounds for non-origin local bounds`);const o=t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,i=this.validateProps({...e.props,w:t.selectionLocalBounds.w,h:t.selectionLocalBounds.h}),r=Ai(i,"w",t.selectionLocalBounds.w),s=Ai(i,"h",t.selectionLocalBounds.h),a=So(Mn({requestedBounds:t.selectionLocalBounds,handleId:t.handleId,actualWidth:r,actualHeight:s,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,{rotation:t.selectionRotation,rotationCenter:t.selectionRotationCenter});return{id:e.id,x:a.x-r/2,y:a.y-s/2,rotation:o,scaleX:t.scaleX<0?-e.scaleX:e.scaleX,scaleY:t.scaleY<0?-e.scaleY:e.scaleY,props:i}}getAllowedSelectionResizeModes(e,t){return yT}getSelectionResizeHandleIds(e,t){return fT}flipSelectionBounds(e,t){const n=this.getSelectionPagePoints(e);if(n){const o=n.map(e=>{const n=0===t.selectionRotation?e.clone():$C.RotWith(e,t.selectionRotationCenter,-t.selectionRotation),o=Io({axis:t.axis,bounds:t.selectionBounds,point:n});return 0===t.selectionRotation?o:$C.RotWith(o,t.selectionRotationCenter,t.selectionRotation)}),i=this.getSelectionPageMiddlePoint(e),r=i?(()=>{const e=0===t.selectionRotation?i.clone():$C.RotWith(i,t.selectionRotationCenter,-t.selectionRotation),n=Io({axis:t.axis,bounds:t.selectionBounds,point:e});return 0===t.selectionRotation?n:$C.RotWith(n,t.selectionRotationCenter,t.selectionRotation)})():void 0;return this.updateSelectionPagePoints(e,{pagePoints:[o[0],o[1]],pageMiddlePoint:r})}const o=this.getSelectionResizeLocalBounds(e),i=0===t.selectionRotation?t.selectionLocalBounds.center:$C.RotWith(t.selectionLocalBounds.center,t.selectionRotationCenter,t.selectionRotation);return{id:e.id,x:i.x-o.center.x,y:i.y-o.center.y,rotation:2*t.selectionRotation-e.rotation,scaleX:"horizontal"===t.axis?-e.scaleX:e.scaleX,scaleY:"vertical"===t.axis?-e.scaleY:e.scaleY}}updateSelectionPagePoints(e,t){throw new Error(`Shape util "${this.type}" must implement updateSelectionPagePoints before selection can transform point-defined geometry`)}getSelectionPagePoints(e){return null}getSelectionPageMiddlePoint(e){return null}contributesToSelectionFrame(e,t){return!0}canParticipateInSelectionResize(e,t){return!0}canParticipateInSelectionFlip(e,t){return this.canParticipateInSelectionResize(e,t)}canParticipateInSelectionRotation(e,t){return!0}canUseSelectionResizeHandles(e,t){return this.canParticipateInSelectionResize(e,t)}canUseSelectionRotateHandle(e,t){return this.canParticipateInSelectionRotation(e,t)}canParticipateInSelectionTranslation(e,t){return!0}getSelectionTargetId(e,t){return e.id}getHoverTargetId(e,t){return e.id}getHoverDecorationTargetId(e,t){return e.id}getTranslateTargetId(e,t){return e.id}isSelectionTransformContainer(e){return!1}shouldRotateDescendants(e){return this.isSelectionTransformContainer(e)}shouldResizeDescendants(e){return!1}getResizeToFitDescendantsProps(e,t){return null}getMinimumChildCount(e){return 0}contributesToExportBounds(e){return!0}canUngroupChildren(e){return!1}getGroupingShapeCreateInput(e){return null}canStartTranslateFromSelectionBounds(e,t){return!0}canSnap(e,t){return!0}canSnapChildrenToSelf(e){return!1}getBoundsSnapGeometry(e){return{}}getHandleSnapGeometry(e){return{outline:Ei(this.getLocalBounds(e))}}getPositionedOutlineVertices(e){const t=this.getPositionedBounds(e);return[new $C(t.minX,t.minY),new $C(t.maxX,t.minY),new $C(t.maxX,t.maxY),new $C(t.minX,t.maxY)]}getSelectionFramePositionedOutlineVertices(e,t){return null}getSelectionHandleAnchors(e,t){return{terminalHandleAnchors:[],middleHandleAnchors:[]}}getSelectionOverlayInfo(e,t){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null,bindingSegments:[]}}getLabelPathGeometry(e,t){return null}isWrappedByBrush(e,t){return 0===t.pageOutlineVertices.length?!!t.pageBounds&&t.brushBounds.containsBox(t.pageBounds):t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return!t.isWrapping||this.isWrappedByBrush(e,t)}getLocalToPageTransform(e){const t=this.getLocalBounds(e).center;return FC.Translate(e.x+t.x,e.y+t.y).compose(FC.Rotate(e.rotation)).compose(FC.SkewX(e.skewX)).compose(FC.Scale(e.scaleX,e.scaleY)).compose(FC.Translate(-t.x,-t.y))}canEdit(e){return!1}canReceiveChildren(e){return!1}canReceiveChild(e,t){return this.canReceiveChildren(e)}isChildVisible(e,t,n){return!0}getChildPlacementMeta(e,t,n){return t.meta}canAutomaticallyReceiveChildren(e){return this.canReceiveChildren(e)}canBeDirectlyBrushSelected(e){return!0}canReceiveTerminalBinding(e,t){return!1}getTerminalBindingPorts(e,t){return this.canReceiveTerminalBinding(e,t)?OT:[]}getTerminalBindingOutlines(e,t){return this.canReceiveTerminalBinding(e,t)?[{points:this.getPositionedOutlineVertices(e),closed:!0}]:[]}canCopyToClipboard(e,t){return!0}repairLoadedShape(e){return null}onEditEnd(e,t){}hitTest(e,t,n){return this.getPositionedBounds(e).containsPoint(t)}hitTestBindingTarget(e,t,n){return this.hitTest(e,t,n)}hitTestLineSegment(e,t){return((e,t,n)=>{if(n.containsPoint(e)||n.containsPoint(t))return!0;const o=Ei(n);for(let i=0;i<o.length;i+=1){const n=o[i],r=o[(i+1)%o.length];if(n&&r&&null!==Bi(e,t,n,r))return!0}return!1})(t.positionedStart,t.positionedEnd,this.getPositionedBounds(e).expand(t.positionedMargin))}resolveBindingPoint(e,t){this.getPositionedBounds(e);const n=t.editor.computeShapePositionedToPageTransform(e),o=n.tryInvert();if(!o)return t.rawPagePoint;const i=((e,t,n)=>{if(n.length<2)return null;let o=Number.POSITIVE_INFINITY;const i=t.sub(e);for(let r=0;r<n.length;r+=1){const i=n[r],s=n[(r+1)%n.length]??n[0];if(!i||!s)continue;const a=Bi(e,t,i,s);null===a||a<=1e-6||a>=o||(o=a)}return Number.isFinite(o)?e.add(i.mul(o)):null})(o.applyToPoint(t.rawPagePoint),o.applyToPoint(t.oppositePagePoint),this.getPositionedOutlineVertices(e));return i?n.applyToPoint(i):t.rawPagePoint}},zT=class{editor;id;parent;children=new Map;currentChild=null;initial=null;constructor(e,t,n){this.editor=e,this.id=t,this.parent=n}addChild(e){this.children.set(e.id,e)}enter(e){if(this.onEnter(e),!this.initial)return;const t=this.children.get(this.initial);if(!t)throw new Error(`Missing child state "${this.initial}" on "${this.id}"`);this.currentChild=t,t.enter(e)}exit(e){this.currentChild&&(this.currentChild.exit(e),this.currentChild=null),this.onExit(e)}transition(e,t){if(!this.parent){const n=this.children.get(e);if(!n)throw new Error(`Missing root child state "${e}" on tool "${this.id}"`);if(this.currentChild===n)return;return this.currentChild?.exit(t),this.currentChild=n,void n.enter(t)}this.parent.transition(e,t)}isInInitialState(){return!this.currentChild||!!this.initial&&this.currentChild.id===this.initial&&this.currentChild.isInInitialState()}dispatch(e){if(this.currentChild)this.currentChild.dispatch(e);else switch(e.type){case"pointer":return void this.handlePointerEvent(e);case"click":return void this.handleClickEvent(e);case"keyboard":return void this.handleKeyboardEvent(e);case"wheel":return void this.onWheel(e);case"tick":return void this.onTick(e);case"cancel":return void this.onCancel(e)}}onEnter(e){}onExit(e){}onPointerDown(e){}onPointerMove(e){}onPointerUp(e){}onDoubleClick(e){}onCancel(e){}onKeyDown(e){}onKeyUp(e){}onWheel(e){}onTick(e){}handlePointerEvent(e){switch(e.name){case"pointer_down":return void this.onPointerDown(e);case"pointer_move":return void this.onPointerMove(e);case"pointer_up":return void this.onPointerUp(e);case"pointer_cancel":return void this.onCancel({type:"cancel",reason:"pointer_cancel"})}}handleClickEvent(e){"double_click"!==e.name||this.onDoubleClick(e)}handleKeyboardEvent(e){"key_down"!==e.name?this.onKeyUp(e):this.onKeyDown(e)}},UT=class extends zT{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new NT(e,this)),this.addChild(new WT(e,this))}},NT=class extends zT{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",xi(this.editor,e.screenPoint))}},WT=class extends zT{info=null;constructor(e,t){super(e,"panning",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&wi(this.editor,this.info,e.screenPoint)}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}onExit(){this.info=null}},XT=Math.PI/180*15,YT=Math.PI/2,HT=Math.PI/180*5,_T=class extends zT{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},KT=class extends _T{onPointerMove(e){this.info&&((e,t)=>e.dist2(t)>=9)(this.info.originPagePoint,e.pagePoint)&&this.onDragThresholdExceeded(e)}},qT=class extends _T{operation=null;onInfoEnter(){if(this.info){const e=this.getOperationKind(this.info);this.operation=this.editor.operations.begin({kind:e,label:e,source:"user",history:"record"})}this.onDragStart()}onDragStart(){}onPointerMove(e){this.apply(e)}onTick(e){if(!this.info)return;const t=Li(this.editor,e,this.tickMode);t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Fi(this.editor,e=>this.apply(e))}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.cancel()}},jT=class extends _T{constructor(e,t){super(e,"brushing",t)}onInfoEnter(){if(!this.info)return;const e=this.editor.inputs.state.get();this.updateBrush(this.info.originPagePoint,this.info.additiveSelection,Ui(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,zi(e),Ui(e))}onTick(e){if(!this.info)return;const t=Li(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,zi(t),Ui(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,zi(e),Ui(e)),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}updateBrush(e,t,n){if(!this.info)return;const o=((e,t)=>{const n=Math.min(e.x,t.x),o=Math.min(e.y,t.y),i=Math.max(e.x,t.x),r=Math.max(e.y,t.y);return new LC(n,o,i-n,r-o)})(this.info.originPagePoint,e),i=((e,t)=>{const n=[],o=new Set;for(const i of t){const t=e.getOutermostSelectableShapeId(i);o.has(t)||(o.add(t),n.push(t))}return n})(this.editor,this.editor.getShapeIdsInBounds(o).filter(e=>((e,t,n,o)=>{const i=e.getShape(n);return!(!i||!((e,t)=>{const n=e.getShape(t);return!!n&&e.getShapeUtil(n).canBeDirectlyBrushSelected(n)})(e,i.id))&&e.getShapeUtil(i).canSelectByBrush(i,{editor:e,brushBounds:t,isWrapping:o,pageOutlineVertices:e.getShapePageOutlineVertices(i.id),pageBounds:e.getShapePageBounds(i.id)})})(this.editor,o,e,n))),r=t?((e,t)=>{const n=new Set(e);for(const o of t)n.has(o)?n.delete(o):n.add(o);return Array.from(n)})(this.info.previousSelection,i):i;this.editor.setBrushBox(o),this.editor.commands.setSelectedShapeIds(r,{source:"system"})}updateBrushFromInputs(){Fi(this.editor,e=>this.updateBrush(e.pagePoint,zi(e),Ui(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},VT=class extends qT{tickMode="apply_after_scroll";constructor(e,t){super(e,"dragging_plugin_interaction",t)}getOperationKind(e){return e.session.historyMark}onDragStart(){this.info?.session.onDragStart?.({editor:this.editor})}onPointerUp(e){this.apply(e),this.complete()}onCancel(e){const t=this.info?.previousSelection;n(()=>{var e,n;t&&(e=t,n=this.editor.getSelectedShapeIds(),e.length!==n.length||!e.every((e,t)=>e===n[t]))&&this.editor.commands.setSelectedShapeIds(t,{source:"system"}),this.info&&(this.editor.clearSelectionTransients(),this.cancelOperation())}),this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}onInfoExit(){this.info?.session.shouldClearBindingPreviewOnExit&&this.editor.setBindingPreview(null),this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:o}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&o===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=o;const i=this.info.snapMode,r=this.info.snapSnapshot,s=!o&&"none"!==i&&null!==r,a=s&&r?this.editor.snaps.snapHandle({mode:i,pagePoint:e,snapshot:r,threshold:8/this.editor.getCurrentCamera().z}):null;s||this.editor.snaps.clearIndicators();const d=a?.snappedPagePoint??e,l=this.info.session.update({editor:this.editor,pagePoint:d,accelKey:o,source:"user"}),c="string"==typeof l?l:l.status,u="string"==typeof l?d:l.finalPagePoint;!a||!u||u.dist2(a.snappedPagePoint)<=1e-6||this.editor.snaps.clearIndicators(),"stop"===c&&this.complete()}complete(){const e=this.info;e&&(this.editor.setSnapIndicators(null),e.session.onComplete?.({editor:this.editor}),this.commitOperation(),this.transition("idle"))}},GT=class extends zT{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.editor.getSelectedShapeIds(),n=this.editor.hitTestSelectionHandle(e.pagePoint);if("rotate"===n?.kind)return void this.transition("pointing_rotate_handle",{originPagePoint:e.pagePoint.clone(),previousSelection:t});if("resize"===n?.kind)return void this.transition("pointing_resize_handle",{handleId:n.id,originPagePoint:e.pagePoint.clone(),cursorHandleOffset:e.pagePoint.sub(n.point),previousSelection:t});let o=null;if(n){const i=this.editor.getSelectedShapes()[0]??null;if(i){const r=this.editor.selectionHandleInteractions.createSession(this.editor,{handle:n,shape:i,originPagePoint:e.pagePoint.clone()});if(r){const i=r.handleSnapMode??"none";o={originPagePoint:e.pagePoint.clone(),previousSelection:t,session:r,snapSnapshot:"none"===i?null:this.editor.snaps.createHandleSnapshot({context:r.handleSnapContext??{shapeId:r.shapeId,handle:n},currentPagePoint:e.pagePoint,allowSelfSnap:r.allowSelfSnap??!1,excludedShapeIds:r.excludedSnapShapeIds})}}}}const i=this.editor.hitTestShape(e.pagePoint);let r=null;if(i){const n=this.editor.getShapeUtil(i).getSelectionTargetId(i,{editor:this.editor}),o=this.editor.getShapeUtil(i).getTranslateTargetId(i,{editor:this.editor}),s=zi(e),a=Oi(this.editor,n,t),d=s?null:((e,t,n)=>{const o=new Set(n);for(const i of Di(e,t))if(o.has(i.ancestorId))return i.ancestorId;return null})(this.editor,n,t),l=s?null:d?a:null,c=Oi(this.editor,o,t),u=null===l?c:d??c,p=this.editor.interactions.createShapePointerSession(this.editor,{shape:i,selectionTargetId:a,originPagePoint:e.pagePoint.clone(),event:e});r={shapeId:a,translateTargetId:u,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:s,wasSelected:t.includes(a),fromSelectionBounds:!1,quickClickSelectionTargetId:l,dragSession:p}}if(!o||"binding_middle"!==n?.kind&&"custom"!==n?.kind)if(r?.dragSession)this.transition("pointing_shape",r);else if(o)this.transition("pointing_selection_handle_interaction",o);else if(r)this.transition("pointing_shape",r);else{if(!zi(e)&&t.length>0){const n=this.editor.getSelectedShapes()[0];if(n&&this.editor.getShapeUtil(n).canStartTranslateFromSelectionBounds(n,{editor:this.editor})&&this.editor.isPointInSelectionBounds(e.pagePoint))return void this.transition("pointing_shape",{shapeId:n.id,translateTargetId:n.id,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:!1,wasSelected:!0,fromSelectionBounds:!0,quickClickSelectionTargetId:null,dragSession:null})}this.transition("pointing_canvas",{originPagePoint:e.pagePoint.clone(),previousSelection:t,additiveSelection:zi(e)})}else this.transition("pointing_selection_handle_interaction",o)}},ZT=class extends KT{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:zi(e)})}onPointerUp(e){zi(e)||this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.transition("idle")}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.transition("idle")}},QT=class extends KT{constructor(e,t){super(e,"pointing_resize_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");if(!this.editor.canResizeSelection())return void this.transition("idle");const t=this.editor.getSelectionResizeTargetShapes(),n=new Map(t.flatMap(e=>{const t=Zt(this.editor,e);return t?[[e.id,t]]:[]})),o=t.filter(e=>n.has(e.id));if(0===o.length)return void this.transition("idle");const i=((e,t,n,o)=>0===t.length?[]:Mo(e,t,n,To(e,t,o)))(this.editor,o,this.info.handleId,e.rotation);if(0===i.length)return void this.transition("idle");const r=(({shapes:e,selectionFrame:t,getShapeSelectionResizePageOutlineVertices:n,getShapeSelectionPagePoints:o,getShapeSelectionPageMiddlePoint:i,getShapePageRecord:r})=>{const s={rotation:t.rotation,rotationCenter:t.rotationCenter},a=[],d=[];for(const l of e){const e=r(l),t=o(e);t?d.push({shape:l,pageShape:e,startLocalPagePoint:yo(t[0],s),endLocalPagePoint:yo(t[1],s),middleLocalPagePoint:(()=>{const t=i(e);return t?yo(t,s):null})()}):a.push({shape:l,pageShape:e,localBounds:LC.FromPoints(n(l).map(e=>yo(e,s))),rotation:e.rotation})}return{startBounds:t.bounds.clone(),rotation:t.rotation,rotationCenter:t.rotationCenter.clone(),aspectRatio:0===t.bounds.h?1:t.bounds.w/t.bounds.h,shapes:a,pointShapes:d}})({shapes:o,selectionFrame:e,getShapeSelectionResizePageOutlineVertices:e=>function(e,t){const n=e.getShapeUtil(t).getSelectionResizeLocalBounds(t),o=e.computeShapeLocalToPageTransform(t);return(e=>[new $C(e.minX,e.minY),new $C(e.maxX,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)])(n).map(e=>o.applyToPoint(e))}(this.editor,e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.getShapeUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>n.get(e.id)});var s,a;this.transition("resizing",{...this.info,startBounds:r.startBounds,rotation:r.rotation,rotationCenter:r.rotationCenter,aspectRatio:r.aspectRatio,snapSnapshot:this.editor.snaps.createResizeSnapshot({resizingShapeIds:this.editor.getShapeIdsForSelectionTransform(this.editor.getSelectedShapeIds()),coordinateSpace:{rotation:r.rotation,rotationCenter:r.rotationCenter}}),shapes:r.shapes,pointShapes:r.pointShapes,updates:(s=r.shapes,a=r.pointShapes,[...s.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,skewX:e.shape.skewX,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...a.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,skewX:e.shape.skewX,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),allowedResizeModes:i,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},JT=class extends KT{constructor(e,t){super(e,"pointing_rotate_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");if(!this.editor.canRotateSelection())return void this.transition("idle");const t=new Map(this.editor.getSelectionRotationTargetShapes().flatMap(e=>{const t=Zt(this.editor,e);return t?[[e.id,t]]:[]})),n=this.editor.getSelectionRotationTargetShapes().filter(e=>t.has(e.id));if(0===n.length)return void this.transition("idle");const o=(({shapes:e,selectionFrame:t,getShapeLocalBounds:n,getShapeSelectionPagePoints:o,getShapeSelectionPageMiddlePoint:i,getShapePageRecord:r})=>{const s=[],a=[];for(const d of e){const e=r(d),t=o(e);t?a.push({shape:d,pageShape:e,startPagePoint:t[0],endPagePoint:t[1],middlePagePoint:i(e)}):s.push({shape:d,pageShape:e,localBounds:n(d),rotation:e.rotation})}return{center:t.rotationCenter.clone(),initialSelectionRotation:t.rotation,shapes:s,pointShapes:a}})({shapes:n,selectionFrame:e,getShapeLocalBounds:e=>this.editor.computeShapeLocalBounds(e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.getShapeUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>t.get(e.id)});var i,r;this.transition("rotating",{...this.info,center:o.center,startAngle:$C.Angle(o.center,this.info.originPagePoint),initialSelectionRotation:o.initialSelectionRotation,shapes:o.shapes,pointShapes:o.pointShapes,updates:(i=o.shapes,r=o.pointShapes,[...i.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,skewX:e.shape.skewX,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...r.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,skewX:e.shape.skewX,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),lastPointerX:NaN,lastPointerY:NaN,lastShiftKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},eM=class extends KT{constructor(e,t){super(e,"pointing_selection_handle_interaction",t)}onDragThresholdExceeded(){this.info&&this.transition("dragging_plugin_interaction",{...this.info,snapMode:this.info.session.handleSnapMode??"none",lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(e){if(this.info){const t={editor:this.editor,source:"user"};(e.clickCount??1)>=2&&this.info.session.onDoubleClick?this.info.session.onDoubleClick(t):this.info.session.onClick?.(t)}this.transition("idle")}onCancel(e){this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}},tM=class extends KT{constructor(e,t){super(e,"pointing_shape",t)}onInfoEnter(){this.info&&(this.info.quickClickSelectionTargetId||(this.info.additiveSelection?this.info.wasSelected||this.editor.commands.setSelectedShapeIds([...this.info.previousSelection,this.info.shapeId],{source:"system"}):this.info.wasSelected||this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"})))}onDragThresholdExceeded(e){if(!this.info)return;if(this.info.dragSession)return void this.transition("dragging_plugin_interaction",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,session:this.info.dragSession,snapMode:"none",snapSnapshot:null,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1});const t=this.editor.getSelectedShapes(),n=this.info.wasSelected?t.map(e=>e.id):[this.info.translateTargetId];this.info.wasSelected||1!==n.length||n[0]===this.info.shapeId||this.editor.commands.setSelectedShapeIds(n,{source:"system"});const o=this.editor.getSelectionFrame(),i=((e,t)=>t.filter(t=>{const n=e.getShape(t);return!!n&&e.getShapeUtil(n).canParticipateInSelectionTranslation(n,{editor:e})&&!e.isShapeOrAncestorLocked(n.id)&&!e.hasLockedDescendant(n.id)}).map(t=>e.getShape(t)).filter(e=>!!e).flatMap(t=>(t.parentId.startsWith("shape:")?e.computeShapeLocalToPageTransform(e.getShape(t.parentId)):FC.Identity()).tryInvert()?[{id:t.id,x:t.x,y:t.y,startLocalToPage:e.computeShapeLocalToPageTransform(t)}]:[]))(this.editor,n);if(0===i.length)return void this.transition("brushing",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,additiveSelection:zi(e)});const r=i.map(e=>e.id),s=o?.hasCompatibleRotation?o.rotation:0,a=o?.rotationCenter.clone()??$C.Zero(),d=o?.hasCompatibleRotation?o.bounds.clone():this.editor.getSelectionPageBounds();var l;this.transition("translating",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,movingShapeIds:r,startBounds:d,snapSnapshot:this.editor.snaps.createTranslateSnapshot({movingShapeIds:r,coordinateSpace:{rotation:s,rotationCenter:a}}),snapRotation:s,selectedShapes:i,updates:(l=i,l.map(e=>({id:e.id,x:e.x,y:e.y}))),lockedAxis:null,lastDeltaX:NaN,lastDeltaY:NaN})}onPointerUp(e){if(this.info?.quickClickSelectionTargetId){const t=((e,t)=>t.timestamp-e.originTimestamp<=250)(this.info,e);t&&this.editor.commands.setSelectedShapeIds([this.info.quickClickSelectionTargetId],{source:"system"}),t&&(e.clickCount??1)>=2||this.editor.resetPointerClickTracking()}else zi(e)&&this.info?.wasSelected?this.editor.commands.setSelectedShapeIds(this.info.previousSelection.filter(e=>e!==this.info?.shapeId),{source:"system"}):this.info&&!this.info.additiveSelection&&this.info.wasSelected&&!this.info.fromSelectionBounds&&this.info.previousSelection.length>1&&this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"});this.transition("idle")}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.transition("idle")}},nM=class extends qT{tickMode="apply_after_scroll_or_without_screen_point";constructor(e,t){super(e,"resizing",t)}getOperationKind(){return"select.resize"}onDragStart(){this.editor.setSnapIndicators(null)}onPointerUp(){this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:o}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&o===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=o;const i=Yi(this.info.rotationCenter,this.info.rotation),r=yo(e.sub(this.info.cursorHandleOffset),i),s=((e,t)=>{const n=e.includes("free"),o=e.includes("aspect_ratio_locked");return n||o?n?o&&t?"aspect_ratio_locked":"free":"aspect_ratio_locked":null})(this.info.allowedResizeModes,t);if(!s)return;const a="aspect_ratio_locked"===s,d=function({startBounds:e,handleId:t,pagePoint:n,isAspectRatioLocked:o,isResizingFromCenter:i,aspectRatio:r}){const s=i?(({startBounds:e,handleId:t,pagePoint:n})=>{const o=e.center,i=n.x-o.x,r=n.y-o.y,s=Math.max(Math.abs(i),.5),a=Math.max(Math.abs(r),.5),d=In(t)||Pn(t)?i*(In(t)?-2:2)/Math.max(1,e.w):1,l=vn(t)||kn(t)?r*(vn(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new LC(e.minX,o.y-a,e.w,2*a),scaleX:d,scaleY:l};case"left":case"right":return{bounds:new LC(o.x-s,e.minY,2*s,e.h),scaleX:d,scaleY:l};default:return{bounds:new LC(o.x-s,o.y-a,2*s,2*a),scaleX:d,scaleY:l}}})({startBounds:e,handleId:t,pagePoint:n}):(({startBounds:e,handleId:t,pagePoint:n})=>{const o=e.minX,i=e.maxX,r=e.minY,s=e.maxY;let a=In(t)?o:i,d=In(t)?i:o,l=vn(t)?r:s,c=vn(t)?s:r;In(t)||Pn(t)?a=n.x:(a=i,d=o),vn(t)||kn(t)?l=n.y:(l=s,c=r);const u=a-d,p=l-c,h=In(t)?d-a:u,g=vn(t)?c-l:p,f=In(t)||Pn(t)?h/Math.max(1,e.w):1,m=vn(t)||kn(t)?g/Math.max(1,e.h):1;return{bounds:new LC(Math.min(a,d),Math.min(l,c),Math.max(1,Math.abs(u)),Math.max(1,Math.abs(p))),scaleX:f,scaleY:m}})({startBounds:e,handleId:t,pagePoint:n});return o?En({bounds:s.bounds,startBounds:e,handleId:t,aspectRatio:r,isResizingFromCenter:i,scaleX:s.scaleX,scaleY:s.scaleY}):s}({startBounds:this.info.startBounds,handleId:this.info.handleId,pagePoint:r,isAspectRatioLocked:a,isResizingFromCenter:n,aspectRatio:this.info.aspectRatio}),l=!o&&this.info.snapSnapshot.points.length>0,c=l?this.editor.snaps.snapResize({handleId:this.info.handleId,initialSelectionBounds:this.info.startBounds,resizedSelectionBounds:d.bounds,scaleX:d.scaleX,scaleY:d.scaleY,snapshot:this.info.snapSnapshot,threshold:8/this.editor.getCurrentCamera().z,isAspectRatioLocked:a,isResizingFromCenter:n}):d;l||this.editor.snaps.clearIndicators();const u=this.info.shapes.length+this.info.pointShapes.length===1;for(let p=0;p<this.info.shapes.length;p+=1){const e=this.info.shapes[p],t=this.info.updates[p];e&&t&&Xi(this.editor,e,this.info.startBounds,c.bounds,c.scaleX,c.scaleY,this.info.handleId,u,n,this.info.rotationCenter,this.info.rotation,t)}for(let p=0;p<this.info.pointShapes.length;p+=1){const e=this.info.pointShapes[p],t=this.info.updates[this.info.shapes.length+p];e&&t&&Hi(this.editor,e,this.info.startBounds,0,c.scaleX,c.scaleY,this.info.handleId,n,this.info.rotationCenter,this.info.rotation,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.setSnapIndicators(null),this.commitOperation(),this.transition("idle")}cancel(){this.editor.setSnapIndicators(null),this.cancelOperation(),this.transition("idle")}},oM=class extends qT{tickMode="apply_after_scroll";constructor(e,t){super(e,"rotating",t)}getOperationKind(){return"select.rotate"}onPointerUp(){this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;if(e.x===this.info.lastPointerX&&e.y===this.info.lastPointerY&&t===this.info.lastShiftKey&&n===this.info.lastAccelKey)return;this.info.lastPointerX=e.x,this.info.lastPointerY=e.y,this.info.lastShiftKey=t,this.info.lastAccelKey=n;let o=Ni($C.Angle(this.info.center,e)-this.info.startAngle);if(t)o=Wi(o,XT);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+o,t=Wi(e,YT),n=Ni(t-e);Math.abs(n)<=HT&&(o=Ni(t-this.info.initialSelectionRotation))}for(let i=0;i<this.info.shapes.length;i+=1){const e=this.info.shapes[i],t=this.info.updates[i];e&&t&&Ki(this.editor,e,this.info.center,o,t)}for(let i=0;i<this.info.pointShapes.length;i+=1){const e=this.info.pointShapes[i],t=this.info.updates[this.info.shapes.length+i];e&&t&&qi(this.editor,e,this.info.center,o,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.commitOperation(),this.transition("idle")}cancel(){this.cancelOperation(),this.transition("idle")}},iM=class extends qT{tickMode="always_apply";constructor(e,t){super(e,"translating",t)}getOperationKind(){return"select.translate"}onDragStart(){this.editor.setSelectionTranslationActive(!0),this.editor.setSnapIndicators(null)}onPointerUp(e){this.complete(e.pagePoint)}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.setSelectionTranslationActive(!1),this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;const o=e.x-this.info.originPagePoint.x,i=e.y-this.info.originPagePoint.y;t?this.info.lockedAxis||0===o&&0===i||(this.info.lockedAxis=Math.abs(o)>=Math.abs(i)?"x":"y"):this.info.lockedAxis=null;let r=o,s=i;"x"===this.info.lockedAxis?s=0:"y"===this.info.lockedAxis&&(r=0);const a=this.info.startBounds;if(!n&&a&&(this.info.snapSnapshot.points.length>0||this.info.snapSnapshot.nodes.length>0)&&this.editor.inputs.state.get().screenVelocity.len()<.5&&a){const e=this.info.snapRotation,t=8/this.editor.getCurrentCamera().z,n=0===e?new $C(r,s):new $C(r,s).rot(-e),{nudge:o}=this.editor.snaps.snapTranslate({lockedAxis:this.info.lockedAxis,initialSelectionBounds:a,dragDelta:n,snapshot:this.info.snapSnapshot,threshold:t}),i=0===e?o:o.rot(e);r+="y"===this.info.lockedAxis?0:i.x,s+="x"===this.info.lockedAxis?0:i.y}else this.editor.snaps.clearIndicators();if(r!==this.info.lastDeltaX||s!==this.info.lastDeltaY){this.info.lastDeltaX=r,this.info.lastDeltaY=s;for(let e=0;e<this.info.selectedShapes.length;e+=1){const t=this.info.selectedShapes[e],n=this.info.updates[e];if(!t||!n)continue;const o=this.editor.getShape(t.id);if(!o)continue;const i=o.parentId.startsWith("shape:")?this.editor.getShape(o.parentId):null,a=(i?this.editor.computeShapeLocalToPageTransform(i):FC.Identity()).tryInvert();if(!a)continue;const d=ce(a.compose(FC.Translate(r,s).compose(t.startLocalToPage)),this.editor.computeShapeLocalBounds(o),{preferredRotation:o.rotation,preferredScaleXSign:o.scaleX,preferredScaleYSign:o.scaleY});d&&Object.assign(n,d)}this.editor.commands.updateShapes(this.info.updates)}Gi(this.editor,this.info.movingShapeIds,e),((e,t,n)=>{const o=Vi(e,t,n);if(o===ji(e,t))return void e.setDropTargetShapeId(null);const i=o?e.getShape(o):null;e.setDropTargetShapeId(i?.id??null)})(this.editor,this.info.movingShapeIds,e)}complete(e){this.info&&Gi(this.editor,this.info.movingShapeIds,e),this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.commitOperation(),this.transition("idle")}cancel(){this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.cancelOperation(),this.transition("idle")}},rM=class extends zT{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new GT(e,this)),this.addChild(new ZT(e,this)),this.addChild(new jT(e,this)),this.addChild(new tM(e,this)),this.addChild(new iM(e,this)),this.addChild(new QT(e,this)),this.addChild(new nM(e,this)),this.addChild(new JT(e,this)),this.addChild(new oM(e,this)),this.addChild(new eM(e,this)),this.addChild(new VT(e,this))}},sM=class{actions=new Map;registerAction(e){if(this.actions.has(e.id))throw new Error(`Duplicate canvas action id: ${e.id}.`);this.actions.set(e.id,e)}getAction(e){return this.actions.get(e)??null}},aM={mainMenu:or("land.chrome.main-menu"),commandPalette:or("land.chrome.command-palette"),inspector:or("land.chrome.inspector"),status:or("land.chrome.status")},dM=class{contributions;channels=new Map;contributionsByChannel=new Map;stateRevision=0;constructor(e=[]){rr(e.map(({id:e})=>e),"chrome contribution"),this.contributions=[...e];const t=new Map(e.map(({id:e},t)=>[e,t]));for(const n of e){this.channels.set(n.channel.id,n.channel);const e=this.contributionsByChannel.get(n.channel.id)??[];e.push(n),e.sort((e,n)=>(e.order??0)-(n.order??0)||(t.get(e.id)??0)-(t.get(n.id)??0)),this.contributionsByChannel.set(n.channel.id,e)}}getChannels(){return[...this.channels.values()]}getStateRevision(){return this.stateRevision}subscribeToState(e,t){const n=()=>{this.stateRevision+=1,t()},o=this.contributions.flatMap(t=>t.subscribe?[t.subscribe(e,n)]:[]);return this.stateRevision+=1,()=>{for(const e of o)e()}}getSections(e,t){return((e,t)=>{const n=[],o=new Map;for(const i of e){const e=o.get(i.id);if(void 0===e){o.set(i.id,n.length),n.push({...i,items:[...i.items]});continue}const t=n[e];n[e]={...t,title:t.title??i.title,items:[...t.items,...i.items]}}for(const i of n)rr(i.items.map(({id:e})=>e),`chrome item in merged section "${i.id}" of channel "${t}"`);return n.map((e,t)=>({index:t,section:e})).sort((e,t)=>(e.section.order??0)-(t.section.order??0)||e.index-t.index).map(({section:e})=>e)})((this.contributionsByChannel.get(e.id)??[]).filter(e=>e.when?.(t)??!0).flatMap(e=>{const n=[...e.getSections(t)].sort((e,t)=>(e.order??0)-(t.order??0));return((e,t)=>{rr(t.map(({id:e})=>e),`chrome section in contribution "${e.id}"`);const n=new Set(e.actionIds);for(const o of t){rr(o.items.map(({id:e})=>e),`chrome item in section "${o.id}"`);for(const t of o.items)if("command"===t.kind&&!n.has(t.actionId))throw new Error(`Chrome contribution "${e.id}" returned undeclared action "${t.actionId}".`)}})(e,n),n}),e.id)}},lM=class{contributions=new Map;contributionsByTarget=new Map;contributionIndexes=new Map;nextContributionIndex=0;registerContribution(e){if(this.contributions.has(e.id))throw new Error(`Duplicate context-menu contribution id: ${e.id}.`);this.contributions.set(e.id,e),this.contributionIndexes.has(e.id)||(this.contributionIndexes.set(e.id,this.nextContributionIndex),this.nextContributionIndex+=1),this.addToIndex(e)}getSections(e,t){return(e=>{const t=[],n=new Map;for(const o of e){const e=n.get(o.id);if(void 0===e){n.set(o.id,t.length),t.push({...o,items:[...o.items]});continue}const i=t[e];t[e]={...i,title:i.title??o.title,items:[...i.items,...o.items]}}return t})((({anyContributions:e,contributionIndexes:t,target:n,targetContributions:o})=>"any"===n||0===o.length?e:0===e.length?o:[...o,...e].sort((e,n)=>sr(e,n,t)))({anyContributions:this.contributionsByTarget.get("any")??[],contributionIndexes:this.contributionIndexes,target:e,targetContributions:this.contributionsByTarget.get(e)??[]}).filter(e=>e.when?.(t)??!0).flatMap(e=>[...e.getSections(t)].sort((e,t)=>(e.order??0)-(t.order??0))))}addToIndex(e){((e,t,n)=>{e.push(t),e.sort((e,t)=>sr(e,t,n))})(((e,t)=>{const n=e.get(t);if(n)return n;const o=[];return e.set(t,o),o})(this.contributionsByTarget,e.target),e,this.contributionIndexes)}},cM=class{contributionsByFormat=new Map;constructor(e=[]){const t=new Set;for(const n of e){if(t.has(n.id))throw new Error(`Duplicate canvas export contribution id: ${n.id}.`);if(t.add(n.id),this.contributionsByFormat.has(n.format))throw new Error(`Duplicate canvas export format: ${n.format}.`);this.contributionsByFormat.set(n.format,n)}}getFormats(){return[...this.contributionsByFormat.values()].map(({format:e,label:t,mimeType:n,fileExtension:o})=>({format:e,label:t,mimeType:n,fileExtension:o}))}hasFormat(e){return this.contributionsByFormat.has(e)}async export(e,t){const n=this.contributionsByFormat.get(e);if(!n)throw new Error(`Canvas export format is unavailable: ${e}.`);const o=await n.export(t);return{format:n.format,label:n.label,mimeType:n.mimeType,fileExtension:n.fileExtension,...o}}},uM=class{contributions;constructor(e=[]){(e=>{const t=new Set;for(const n of e){if(t.has(n))throw new Error(`Duplicate canvas import contribution id: ${n}.`);t.add(n)}})(e.map(({id:e})=>e)),this.contributions=e.map((e,t)=>({contribution:e,index:t})).sort((e,t)=>(e.contribution.order??0)-(t.contribution.order??0)||e.index-t.index).map(({contribution:e})=>e)}getContributions(){return this.contributions}canImport(e){return this.contributions.some(t=>t.accepts(e))}canImportPreview(e){return this.contributions.some(t=>t.acceptsPreview?.(e)??!1)}async import(e,t){for(const n of this.contributions){if(!n.accepts(e))continue;const o=await n.import(e,t);if("handled"===o)return o}return"ignored"}},pM="editor.tool.set-active-tool",hM="editor.tool.toggle-locked",gM={toolSwitcher:mr("land.toolbar.tool-switcher"),toolOptions:mr("land.toolbar.tool-options"),selectionProperties:mr("land.toolbar.selection-properties"),selectionQuickActions:mr("land.toolbar.selection-quick-actions")},fM=class{contributions=new Map;channels=new Map;contributionsByChannel=new Map;contributionIndexes=new Map;nextContributionIndex=0;stateRevision=0;registerContribution(e){if(this.contributions.has(e.id))throw new Error(`Duplicate toolbar contribution id: ${e.id}.`);const t=this.channels.get(e.channel.id);this.contributions.set(e.id,e),this.contributionIndexes.has(e.id)||(this.contributionIndexes.set(e.id,this.nextContributionIndex),this.nextContributionIndex+=1),t||this.channels.set(e.channel.id,e.channel),this.addToIndexes(e)}getStateRevision(){return this.stateRevision}subscribeToState(e,t){const n=()=>{this.stateRevision+=1,t()},o=[...this.contributions.values()].flatMap(t=>t.subscribe?[t.subscribe(e,n)]:[]);return this.stateRevision+=1,()=>{for(const e of o)e()}}getGroups(e,t){const n=(this.contributionsByChannel.get(e.id)??[]).filter(e=>e.when?.(t)??!0).flatMap(e=>{const n=[...e.getGroups(t)].sort((e,t)=>(e.order??0)-(t.order??0));return((e,t)=>{const n=new Set(e.actionIds);br(t.map(({id:e})=>e),`toolbar group in contribution "${e.id}"`);for(const o of t){br(o.items.map(({id:e})=>e),`toolbar item in group "${o.id}"`);for(const t of o.items)if("actionId"in t&&!n.has(t.actionId))throw new Error(`Toolbar contribution "${e.id}" returned undeclared action "${t.actionId}".`)}})(e,n),n});return br(n.map(({id:e})=>e),`toolbar group in channel "${e.id}"`),n}getChannels(){return[...this.channels.values()]}addToIndexes(e){((e,t,n)=>{e.push(t),e.sort((e,t)=>{const o=(e.order??0)-(t.order??0);return 0!==o?o:(n.get(e.id)??0)-(n.get(t.id)??0)})})(((e,t)=>{const n=e.get(t);if(n)return n;const o=[];return e.set(t,o),o})(this.contributionsByChannel,e.channel.id),e,this.contributionIndexes)}},mM=Fk(null),yM=class{registry=new Map;registeredPluginIds=new Set;shapeOpacityModifiers=[];shapeOpacityModifierIds=new Set;registerShapeRenderer(e){if(this.registry.has(e.type))throw new Error(`Duplicate shape renderer type: ${e.type}.`);this.registry.set(e.type,e)}getShapeRenderer(e){return this.registry.get(e)??null}hasShapeRenderer(e){return this.registry.has(e)}getRegisteredShapeTypes(){return[...this.registry.keys()]}registerCanvasRenderPlugins(e){for(const t of e){if(this.registeredPluginIds.has(t.id))throw new Error(`Duplicate canvas render plugin id: ${t.id}.`);for(const e of t.shapeRenderers??[])this.registerShapeRenderer(e);for(const e of t.shapeOpacityModifiers??[]){if(this.shapeOpacityModifierIds.has(e.id))throw new Error(`Duplicate shape opacity modifier id: ${e.id}.`);this.shapeOpacityModifiers.push(e),this.shapeOpacityModifierIds.add(e.id)}this.registeredPluginIds.add(t.id)}}getShapeOpacity(e,t){return this.shapeOpacityModifiers.reduce((n,o)=>n*o.getOpacity(e,t),1)}},SM=vr(),bM=Fk(SM),xM="var(--land-shape-hover, var(--land-selection, #2563eb))",wM=zk(()=>{const e=wr();return((e,t,n)=>{const o=[],i=[],r=new Map(t.map(e=>[e.id,e]));for(const s of e){const e=r.get(s);if(e){for(;i.length>0&&!Tr(i[i.length-1],e,r);)o.push({layer:"foreground",shapeId:i.pop()});o.push({layer:"shape",shapeId:s}),n.getShapeRenderer(e.type)?.foregroundComponent&&i.push(s)}}for(;i.length>0;)o.push({layer:"foreground",shapeId:i.pop()});return o})(Ir(e.retainedShapeIdsSignal),Ir(e.currentPageShapeHierarchySignal),kr()).map((e,t)=>"shape"===e.layer?Gk(PM,{shapeId:e.shapeId,stackingOrder:t},e.shapeId):Gk(vM,{shapeId:e.shapeId,stackingOrder:t},`${e.shapeId}:foreground`))}),IM=zk(()=>{const e=wr(),t=Ir(e.currentPageShapeIdsSignal),n=Ir(e.retainedShapeIdsSignal),o=Ir(e.renderVisibleShapeIdsSignal),i=Ir(e.shapeRenderOrderByIdSignal),r=new Set(o),s=n.map(e=>i.get(e)??-1),a=n.filter(e=>r.has(e)).map(e=>i.get(e)??-1),d=n.filter(e=>!r.has(e)),l={pageShapeCount:t.length,mountedCount:n.length,visibleCount:o.length,hiddenRetainedCount:d.length,minRenderOrder:s.length>0?Math.min(...s):null,maxRenderOrder:s.length>0?Math.max(...s):null,mountedRenderOrderSeq:s.join(","),visibleRenderOrderSeq:a.join(","),firstMountedShapeId:n[0]??null,lastMountedShapeId:n[n.length-1]??null,hiddenRetainedShapeIds:d};
|
|
60
|
+
return Gk("pre",{"data-ui":"shape-layer-debug-summary","data-mounted-count":l.mountedCount,"data-visible-count":l.visibleCount,"data-hidden-retained-count":l.hiddenRetainedCount,"data-min-render-order":l.minRenderOrder??void 0,"data-max-render-order":l.maxRenderOrder??void 0,hidden:!0,children:JSON.stringify(l)})}),PM=zk(({shapeId:e,stackingOrder:t})=>{const n=wr(),o=e,i=Ir(n.getShapeSignal(o)),r=Ir(n.getShapeLocalToPageTransformSignal(o)),s=Ir(n.getShapeHoveredSignal(o)),a=Ir(n.selectionCountSignal),d=Ir(n.brushBoxActiveSignal),l=Ir(n.getShapeRenderVisibleSignal(o)),c=Ir(n.toolStateSignal).activeToolId,u=Ir(n.getShapeSelectedSignal(o)),p="select"===c&&u,h=Ir(n.getShapeEditingSessionForShapeSignal(o)),g=Ir(n.getShapeRenderOrderSignal(o)),f=Ir(n.getShapeDropTargetSignal(o)),m=Ir(n.runtime.revisionSignal),y=Ir(n.getShapeEffectiveOpacitySignal(o)),S=Ir(n.getShapeSelectedDescendantTransformAncestorSignal(o)),b=Ir(n.getShapeClipAncestorIdsSignal(o)),x=kr();if(!i||!r)return null;const w=x.getShapeRenderer(i.type);if(!w)return null;const I=w.component,P=w.hoverComponent,v=s&&!(1===a&&p)&&!d,k=$r(n,i,r),C=y*x.getShapeOpacity(n,o);
|
|
61
|
+
return Zk("div",{"data-ui":"shape-instance","data-shape-id":i.id,"data-shape-type":i.type,"data-selected":p?"true":"false","data-hovered":v?"true":"false","data-drop-target":f?"true":"false","data-visible":l?"true":"false","data-render-order":g>=0?String(g):void 0,"data-clip-ancestor-count":b.length,style:{position:"absolute",display:l?void 0:"none",left:k.left,top:k.top,width:k.width,height:k.height,opacity:1===C?void 0:C,transform:k.transform,transformOrigin:k.transformOrigin,pointerEvents:"none",outline:f?"2px solid #2563eb":void 0,outlineOffset:f?4:void 0,boxShadow:f?"0 0 0 6px rgba(37, 99, 235, 0.16)":void 0,zIndex:t+1},children:[l?Zk(Ar,{clipAncestorIds:b,shapeElementToPage:k.elementToPage,children:[Gk(kM,{Component:I,shape:i,editor:n,isSelected:p,shapeEditingSession:h,renderRevision:m}),v&&P?Gk(Mr,{Component:P,editor:n,shape:i}):null]}):null,l&&f?Gk(Br,{}):null,l&&S?Gk(Er,{}):null]})}),vM=zk(({shapeId:e,stackingOrder:t})=>{const n=wr(),o=Ir(n.getShapeSignal(e)),i=Ir(n.getShapeLocalToPageTransformSignal(e)),r=Ir(n.getShapeRenderVisibleSignal(e)),s=Ir(n.getShapeSelectedSignal(e)),a=Ir(n.getShapeEditingSessionForShapeSignal(e)),d=Ir(n.runtime.revisionSignal),l=Ir(n.getShapeEffectiveOpacitySignal(e)),c=Ir(n.getShapeClipAncestorIdsSignal(e)),u=kr();if(!o||!i)return null;const p=u.getShapeRenderer(o.type)?.foregroundComponent;if(!p)return null;const h=$r(n,o,i),g=l*u.getShapeOpacity(n,e);
|
|
62
|
+
return Gk("div",{"data-ui":"shape-foreground","data-owner-shape-id":o.id,"data-owner-shape-type":o.type,style:{position:"absolute",display:r?void 0:"none",left:h.left,top:h.top,width:h.width,height:h.height,opacity:1===g?void 0:g,transform:h.transform,transformOrigin:h.transformOrigin,pointerEvents:"none",zIndex:t+1},children:r?Gk(Ar,{clipAncestorIds:c,shapeElementToPage:h.elementToPage,children:Gk(kM,{Component:p,shape:o,editor:n,isSelected:s,shapeEditingSession:a,renderRevision:d})}):null})}),kM=zk(e=>{const{Component:t,editor:n,isSelected:o,shape:i,shapeEditingSession:r}=e;
|
|
63
|
+
return Gk(t,{editor:n,isSelected:o,shape:i,shapeEditingSession:r})}),CM=class{selectionCustomHandleRenderers=new Map;canvasOverlays=new Map;registeredPluginIds=new Set;registerCanvasOverlay(e){if(this.canvasOverlays.has(e.id))throw new Error(`Duplicate canvas overlay id: ${e.id}.`);this.canvasOverlays.set(e.id,e)}getCanvasOverlay(e){return this.canvasOverlays.get(e)??null}hasCanvasOverlay(e){return this.canvasOverlays.has(e)}getCanvasOverlays(e){return[...this.canvasOverlays.values()].filter(t=>!e||(e=>e.layer??"above-host")(t)===e).sort(Dr)}getRegisteredCanvasOverlayIds(){return[...this.canvasOverlays.keys()]}registerSelectionCustomHandleRenderer(e){if(this.selectionCustomHandleRenderers.has(e.type))throw new Error(`Duplicate selection handle renderer type: ${e.type}.`);this.selectionCustomHandleRenderers.set(e.type,e)}getSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.get(e)??null}hasSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.has(e)}getRegisteredSelectionCustomHandleTypes(){return[...this.selectionCustomHandleRenderers.keys()]}registerCanvasRenderPlugins(e){for(const t of e){if(this.registeredPluginIds.has(t.id))throw new Error(`Duplicate canvas render plugin id: ${t.id}.`);for(const e of t.canvasOverlays??[])this.registerCanvasOverlay(e);for(const e of t.selectionCustomHandleRenderers??[])this.registerSelectionCustomHandleRenderer(e);this.registeredPluginIds.add(t.id)}}},TM=zr(),MM=Fk(TM),EM="rgba(100, 116, 139, 0.82)",BM="rgba(255, 255, 255, 0.84)",AM=zk(()=>Ir(wr().bindingPreviewActiveSignal)?Gk(RM,{}):null),RM=zk(()=>{const e=wr(),t=Ir(e.bindingPreviewSignal),n=Ir(e.terminalBindingGuidesSignal);if(!t)return null;const o=n.some(e=>e.terminal===t.terminal&&e.targetShapeId===t.targetShapeId);
|
|
64
|
+
return Zk(Vk,{children:[Gk($M,{targetShapeId:t.targetShapeId}),Gk(LM,{bindingPreview:t,showGuide:!o})]})}),$M=zk(({targetShapeId:e})=>{const t=wr(),n=Ir(t.cameraZoomSignal),o=Ir(t.getShapeSignal(e));return o?Gk(Yr,{editor:t,shape:o,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),LM=zk(({bindingPreview:e,showGuide:t})=>{const n=Ir(wr().cameraZoomSignal),o=2/n,i=6/n,r=4/n;
|
|
65
|
+
return Zk(Vk,{children:[t?e.guidePath?Gk(Xr,{path:e.guidePath,strokeWidth:o,dashSize:i,gapSize:r,kind:"binding-preview",terminal:e.terminal}):Gk(Wr,{start:e.rawPagePoint,end:e.resolvedPagePoint,startInset:8/n,endInset:6/n,strokeWidth:o,dashSize:i,gapSize:r,kind:"binding-preview",terminal:e.terminal}):null,
|
|
66
|
+
Gk("circle",{"data-binding-preview-point":"raw",cx:e.rawPagePoint.x,cy:e.rawPagePoint.y,r:6,fill:"rgba(255,255,255,0.96)",stroke:"rgba(14, 165, 233, 0.8)",strokeWidth:2}),
|
|
67
|
+
Gk("circle",{"data-binding-preview-point":"resolved",cx:e.resolvedPagePoint.x,cy:e.resolvedPagePoint.y,r:7,fill:"rgba(14, 165, 233, 0.18)",stroke:"rgba(2, 132, 199, 0.9)",strokeWidth:2})]})}),FM=zk(()=>Ir(wr().brushBoxActiveSignal)?Gk(OM,{}):null),OM=zk(()=>{const e=Ir(wr().brushBoxSignal);return e?Gk("rect",{"data-ui":"brush-box-overlay",x:e.x,y:e.y,width:e.w,height:e.h,fill:"rgba(59, 130, 246, 0.14)",stroke:"rgba(37, 99, 235, 0.92)",strokeDasharray:"4 3",strokeWidth:1}):null}),DM=zk(()=>{const e=wr(),t=Ir(e.selectionOverlayFrameGeometrySignal),n=Ir(e.selectionOverlayCompanionFrameGeometriesSignal);return t||0!==n.length?Zk(Vk,{children:[t?Gk(zM,{frameGeometry:t}):null,n.map((e,t)=>Gk(zM,{frameGeometry:e},`companion-${t}`))]}):null}),zM=zk(({frameGeometry:e})=>{const t=Ir(wr().selectionOverlayFrameStyleSignal),{bounds:n,rotation:o,rotationCenter:i}=e,{cornerRadius:r,strokeWidth:s}=t,a=s/2,d=180*o/Math.PI;
|
|
68
|
+
return Gk("g",{transform:0===o?void 0:`rotate(${d} ${i.x} ${i.y})`,children:Gk("rect",{"data-selection-overlay":"bounds",x:n.x-a,y:n.y-a,width:n.w+s,height:n.h+s,rx:r+a,ry:r+a,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeWidth:s})})}),UM=new Set(mT),NM=zk(()=>{const e=Ir(wr().selectionOverlayHandleAnchorsSignal);return e?Gk(WM,{anchors:e}):null}),WM=zk(({})=>{const e=wr(),t=Ir(e.selectionOverlayHandlesSignal),n=Ir(e.selectionOverlayFrameGeometrySignal),o=Ur(),i=Ir(e.cameraZoomSignal);if(!t)return null;const{resizeHandles:r,rotateHandles:s,strokeWidth:a,terminalHandles:d,middleHandles:l,customHandles:c}=t,u=r.filter(e=>UM.has(e.id)),p=r.filter(e=>!UM.has(e.id)),h=n?.rotation??0,g=180*h/Math.PI;
|
|
69
|
+
return Zk(Vk,{children:[n?Gk("g",{transform:n&&0!==h?`rotate(${g} ${n.rotationCenter.x} ${n.rotationCenter.y})`:void 0,children:p.map(e=>Gk(Hr,{frame:n,handleId:e.id,zoom:i},e.id))}):null,u.map(e=>Gk("rect",{"data-selection-resize-handle":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2/i,ry:2/i,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,style:{cursor:_r(e.id,h),pointerEvents:"auto"}},e.id)),s.map(e=>Zk("g",{"data-selection-rotate-handle":e.id,transform:`translate(${e.bounds.center.x-6/i} ${e.bounds.center.y-6/i}) scale(${.6/i})`,fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[Gk("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),Gk("path",{d:"M21 3v5h-5"})]},e.id)),d.map(e=>Gk("circle",{"data-selection-terminal":e.terminal,cx:e.bounds.center.x,cy:e.bounds.center.y,r:Math.min(e.bounds.w,e.bounds.h)/2,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,style:{cursor:"grab",pointerEvents:"auto"}},e.terminal)),l.map(e=>Gk("rect",{"data-selection-binding-middle":"true",x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2,ry:2,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,transform:`rotate(45 ${e.bounds.center.x} ${e.bounds.center.y})`,style:{cursor:"grab",pointerEvents:"auto"}},"middle")),c.map(e=>{const t=o.getSelectionCustomHandleRenderer(e.type);
|
|
70
|
+
return Gk(t?t.component:Kr,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),XM=["ew-resize","nwse-resize","ns-resize","nesw-resize"],YM=1e-6,HM=zk(()=>{const e=wr(),t=Ir(e.selectionOverlayPathSignal),n=Ir(e.selectionOverlayPageClipPathSignal),o=Ir(e.selectionOverlayBindingSegmentsSignal),i=Ir(e.selectedShapeOverlayItemsSignal),r=Ir(e.selectionOverlayFrameStyleSignal),s=Yk().replace(/[^a-zA-Z0-9_-]/g,"-"),a=`selection-content-clip-${s}`,d=`selection-path-halo-${s}`,l=1===i.length?i[0]?.pathStyle??null:null,c=l?((e,t)=>{const n=e.localToPage.getMaximumLinearScale(),o=n>YM?Math.abs(e.localToPage.determinant())/n:0;return e.strokeWidth+2*t/(o>YM?o:n>YM?n:1)})(l,r.strokeWidth):null,u=l&&null!==c?l.localBounds.expand(c):null;return t?Zk(Vk,{children:[
|
|
71
|
+
Gk(_M,{bindingSegments:o,strokeWidth:r.strokeWidth}),n||l&&u?Zk("defs",{children:[n?Gk("clipPath",{id:a,clipPathUnits:"userSpaceOnUse",children:Gk("path",{d:n,clipRule:"evenodd",fillRule:"evenodd"})}):null,l&&null!==c&&u?Zk("mask",{id:d,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:u.x,y:u.y,width:u.w,height:u.h,children:[Gk(qr,{dataPrefix:"path-halo-mask-outer",pathStyle:l,stroke:"white",strokeWidth:c}),Gk(qr,{dataPrefix:"path-halo-mask-center",pathStyle:l,stroke:"black",strokeWidth:l.strokeWidth})]}):null]}):null,
|
|
72
|
+
Gk("g",{"data-selection-overlay":"lines",clipPath:n?`url(#${a})`:void 0,children:l&&null!==c?Gk("g",{"data-selection-overlay":"path-halo-transform",transform:l.localToPage.toSvgString(),children:Gk("g",{mask:`url(#${d})`,children:Gk(qr,{dataPrefix:"path-halo",pathStyle:l,stroke:"rgba(37, 99, 235, 0.45)",strokeWidth:c})})}):Zk(Vk,{children:[Gk("path",{"data-selection-overlay":"path-underlay",d:t,fill:"none",stroke:"rgba(255,255,255,0.92)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2*r.strokeWidth}),Gk("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:r.strokeWidth})]})})]}):null}),_M=zk(({bindingSegments:e,kind:t="selection-binding",strokeWidth:n})=>{if(0===e.length)return null;const o=3*n,i=2*n,r=4*n,s=3*n;
|
|
73
|
+
return Gk(Vk,{children:e.map(e=>e.guidePath?Gk(Xr,{path:e.guidePath,strokeWidth:n,dashSize:o,gapSize:i,kind:t,terminal:e.terminal},e.terminal):Gk(Wr,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:r,endInset:s,strokeWidth:n,dashSize:o,gapSize:i,kind:t,terminal:e.terminal},e.terminal))})}),KM=zk(()=>Ir(wr().selectionTranslationActiveSignal)?null:Zk(Vk,{children:[
|
|
74
|
+
Gk(HM,{}),
|
|
75
|
+
Gk(DM,{}),
|
|
76
|
+
Gk(NM,{})]})),qM="rgba(37, 99, 235, 0.9)",jM=zk(()=>{const e=Ir(wr().snapIndicatorsSignal);return 0===e.length?null:Gk(VM,{indicators:e})}),VM=zk(({indicators:e})=>{const t=Ir(wr().cameraZoomSignal);
|
|
77
|
+
return Gk(Vk,{children:e.map(e=>Gk("points"===e.type?GM:ZM,{indicator:e,zoom:t},e.id))})}),GM=zk(({indicator:e,zoom:t})=>{const n=2.5/t,o=1/t,[i,r]=e.line,s=180*e.rotation/Math.PI;
|
|
78
|
+
return Zk("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${s} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[Gk("path",{"data-ui":"snap-indicator-line",d:`M ${i.x} ${i.y} L ${r.x} ${r.y}`,fill:"none",stroke:qM,strokeWidth:o,strokeLinecap:"round"}),e.points.map((t,i)=>Gk("path",{"data-ui":"snap-indicator-cross",d:`M ${t.x-n} ${t.y-n} L ${t.x+n} ${t.y+n} M ${t.x-n} ${t.y+n} L ${t.x+n} ${t.y-n}`,fill:"none",stroke:qM,strokeWidth:o,strokeLinecap:"round"},`${e.id}:${i}`))]})}),ZM=zk(({indicator:e,zoom:t})=>{if(0===e.gaps.length)return null;const n="horizontal"===e.direction;let o=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY];for(const c of e.gaps){const e=jr(o,[n?c.startEdge[0].y:c.startEdge[0].x,n?c.startEdge[1].y:c.startEdge[1].x]);e&&(o=e);const t=jr(o,[n?c.endEdge[0].y:c.endEdge[0].x,n?c.endEdge[1].y:c.endEdge[1].x]);t&&(o=t)}if(!Number.isFinite(o[0])||!Number.isFinite(o[1]))return null;const i=(o[0]+o[1])/2,r=3.5/t,s=2*r,a=[];for(const{startEdge:c,endEdge:u}of e.gaps)if(n){a.push(`M ${c[0].x} ${i-s} L ${c[1].x} ${i+s}`,`M ${u[0].x} ${i-s} L ${u[1].x} ${i+s}`,`M ${c[0].x} ${i} L ${u[0].x} ${i}`);const e=(c[0].x+u[0].x)/2;a.push(`M ${e} ${i-r} L ${e} ${i+r}`)}else{a.push(`M ${i-s} ${c[0].y} L ${i+s} ${c[1].y}`,`M ${i-s} ${u[0].y} L ${i+s} ${u[1].y}`,`M ${i} ${c[0].y} L ${i} ${u[0].y}`);const e=(c[0].y+u[0].y)/2;a.push(`M ${i-r} ${e} L ${i+r} ${e}`)}const d=180*e.rotation/Math.PI,l=0===e.rotation?void 0:`rotate(${d} ${e.rotationCenter.x} ${e.rotationCenter.y})`;
|
|
79
|
+
return Gk("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:l,fill:"none",stroke:qM,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),QM=zk(()=>{const e=wr(),t=Ir(e.terminalBindingGuidesSignal),n=Ir(e.selectionOverlayFrameStyleSignal);return 0===t.length?null:Gk(_M,{bindingSegments:t,kind:"terminal-binding-guide",strokeWidth:n.strokeWidth})}),JM=zk(()=>Zk("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
|
|
80
|
+
Gk("style",{children:'\n [data-selection-terminal],\n [data-selection-binding-middle],\n [data-selection-custom-handle-visual="default"] {\n transition: fill 120ms ease, stroke 120ms ease;\n }\n [data-selection-terminal]:hover,\n [data-selection-binding-middle]:hover,\n [data-selection-custom-handle-visual="default"]:hover {\n fill: rgba(219, 234, 254, 0.98);\n stroke: rgba(29, 78, 216, 0.98);\n }\n [data-selection-terminal]:active,\n [data-selection-binding-middle]:active,\n [data-selection-custom-handle]:active {\n cursor: grabbing;\n }\n '}),
|
|
81
|
+
Gk(eE,{layer:"below-host"}),
|
|
82
|
+
Gk(jM,{}),
|
|
83
|
+
Gk(QM,{}),
|
|
84
|
+
Gk(AM,{}),
|
|
85
|
+
Gk(FM,{}),
|
|
86
|
+
Gk(KM,{}),
|
|
87
|
+
Gk(eE,{layer:"above-host"})]})),eE=zk(({layer:e})=>{const t=Ur().getCanvasOverlays(e);return 0===t.length?null:Gk(Vk,{children:t.map(({id:e,component:t})=>Gk(t,{},e))})}),tE=class{guards=[];registeredGuardIds=new Set;register(e){if(this.registeredGuardIds.has(e.id))throw new Error(`Duplicate DOM event guard id: ${e.id}.`);this.guards.push(e),this.registeredGuardIds.add(e.id)}registerCanvasRenderPlugins(e){for(const t of e)for(const e of t.domEventGuards??[])this.register(e)}getGuards(){return this.guards}handle(e){for(const t of this.guards)if("handled"===t.handle(e))return"handled";return"continue"}getCursor(e){for(const t of this.guards){const n=t.getCursor?.(e);if(void 0!==n)return n}}},nE="canvas-surface",oE=`[data-ui="${nE}"]`,iE=[{min:-1,mid:.15,step:64},{min:.05,mid:.375,step:16},{min:.15,mid:1,step:4},{min:.7,mid:2.5,step:1}],rE=/[;{}<>\u0000-\u001f\u007f]/u,sE=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,aE=/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|em|rem|%)?$/iu,dE="path-label",lE="geo-label",cE={[dE]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"owner",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!0,canUseSelectionResizeHandles:!1,canUseSelectionRotateHandle:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[lE]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"label",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!1,canUseSelectionResizeHandles:!0,canUseSelectionRotateHandle:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}},uE="default",pE={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}},hE=new WeakMap,gE=new WeakMap,fE={bold:["bold","strong"],italic:["italic","em"],strike:["strike","s"],underline:["underline","u"]},mE=14,yE=16,SE=20,bE=28,xE=16,wE={[mE]:20,[yE]:24,[SE]:28,[bE]:36},IE=class{ownerDocument;element;constructor(e){this.ownerDocument=e,this.element=e.createElement("div"),this.element.setAttribute("aria-hidden","true"),this.element.style.position="absolute",this.element.style.left="-10000px",this.element.style.top="0",this.element.style.visibility="hidden",this.element.style.pointerEvents="none",e.body.appendChild(this.element)}measureHtml(e,t){const n=this.prepareElement(t);return n.innerHTML=e,this.measurePreparedElement(n)}measureElement(e,t,n){const o=this.prepareElement(t);return o.replaceChildren(...Array.from(e.childNodes).map(e=>e.cloneNode(!0))),Aa(o,"whiteSpace",n?.whiteSpace),Aa(o,"overflowWrap",n?.overflowWrap),Aa(o,"lineHeight",n?.lineHeight),Aa(o,"letterSpacing",n?.letterSpacing),Aa(o,"textAlign",n?.textAlign),this.measurePreparedElement(o)}prepareElement(e){const t=this.element;return t.removeAttribute("contenteditable"),t.className="",t.textContent="",e?.shape&&e.fontCatalog&&((e,t,n)=>{e.className="land-text-editor__content",e.dir="auto",e.style.color=O(t.props.color),e.style.fontFamily=wa(t.props.font,n),e.style.fontSize=`${Ia(t.props.size)}px`,e.style.lineHeight=`${Pa(t.props.size)}px`,e.style.textAlign=ka(t.props.textAlign)})(t,e.shape,e.fontCatalog),t.style.position="absolute",t.style.left="-10000px",t.style.top="0",t.style.visibility="hidden",t.style.pointerEvents="none",t.style.width="number"==typeof e?.width?`${e.width}px`:"max-content",t.style.minWidth="0",t.style.height="auto",t.style.minHeight="0",t.style.maxHeight="none",t.style.maxWidth="number"==typeof e?.width?`${e.width}px`:"number"==typeof e?.maxWidth?`${e.maxWidth}px`:"none",t}measurePreparedElement(e){return e.querySelectorAll("p").forEach(e=>{e instanceof HTMLElement&&(e.style.margin="0")}),[e,...Array.from(e.querySelectorAll("*")).filter(e=>e instanceof HTMLElement)].reduce((e,t)=>{const n=t.getBoundingClientRect();return{w:Math.max(e.w,n.width,t.scrollWidth,t.offsetWidth),h:Math.max(e.h,n.height,t.scrollHeight,t.offsetHeight)}},{w:0,h:0})}},PE=new WeakMap,vE=/[;{}<>\u0000-\u001f\u007f]/u,kE=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,CE=oC.extend({inclusive:!1,renderHTML({HTMLAttributes:e}){const{href:t,target:n,rel:o,...i}=e;return["span",eC(i,{"data-rich-text-link-href":t,style:"text-decoration-line: underline;"}),0]}}),TE=[gC.configure({bold:!1,italic:!1,link:!1,strike:!1,underline:!1}),tC.extend({keepOnSplit:!0}),nC.extend({keepOnSplit:!0}),iC.extend({keepOnSplit:!0}),pC.extend({keepOnSplit:!0}),uC,aC,sC,dC,lC,cC,rC.configure({types:["paragraph"],alignments:["left","center","right"]}),hC.configure({className:"land-rich-text-selection"}),CE.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})],ME=Fk(null),EE=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),BE={id:"land.text.dom-events",handle({event:e,name:t}){if(!EE.has(t))return"continue";const n=e.target;return n instanceof HTMLElement&&n.closest('[data-ui="text-editing-box"]')?"handled":"continue"},getCursor:({element:e})=>e?.closest('[data-ui="text-editing-box"]')?"text":void 0},AE="text.create",RE=class extends zT{constructor(e){super(e,"text"),this.initial="idle",this.addChild(new $E(e,this)),this.addChild(new LE(e,this))}},$E=class extends zT{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("pointing",{originPagePoint:e.pagePoint.clone(),shapeId:null})}},LE=class extends zT{info=null;operation=null;isHandingOffOperation=!1;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e,this.operation=this.editor.operations.begin({kind:AE,label:"shape.create",source:"user",history:"record"})}onPointerMove(e){this.updateFixedWidthShape(e.pagePoint)}onPointerUp(e){if(!this.info)return void this.transition("idle");const t=null!==this.info.shapeId?this.editor.getShape(this.info.shapeId):this.createTextShape(e.pagePoint);if(!Us(t))return this.cancelOperation(),void this.transition("idle");let n;Pe(this.editor,t.id,{source:"user"}),this.editor.isToolLocked()||(this.isHandingOffOperation=!0,this.transition("idle"),this.editor.commands.setActiveTool("select",{source:"system"}));try{n=this.editor.startEditingShape({shapeId:t.id,entryMode:"focusEnd",markId:AE,reuseActiveOperation:!0,preserveInteraction:!0},"user")}catch(o){throw this.cancelOperation(),o}finally{this.isHandingOffOperation=!1}n?this.operation=null:this.cancelOperation(),this.editor.isToolLocked()&&this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.isHandingOffOperation||this.cancelOperation(),this.info=null}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}updateFixedWidthShape(e){if(!this.info)return;const t=((e,t,n)=>{const o=Math.abs(t.x-e.x);return e.dist(t)<4||o<8?null:{x:Math.min(e.x,t.x),y:e.y-n.h/2,props:{...rd(n),w:Math.max(16,o),autoSize:!1}}})(this.info.originPagePoint,e,this.getDefaultTextProps());if(t){if(!this.info.shapeId){const e=this.createTextShapeAt(t);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:t.x,y:t.y,props:{w:t.props.w,h:t.props.h,autoSize:!1}}],{source:"user"})}}createTextShape(e){return this.createTextShapeAt(((e,t)=>({x:e.x,y:e.y-t.h/2,props:rd(t)}))(e,this.getDefaultTextProps()))}createTextShapeAt({x:e,y:t,props:n}){const o=Xs(this.editor,{x:e,y:t,props:n},"user");return this.editor.commands.setSelectedShapeIds([o.id],{source:"system"}),o}getDefaultTextProps(){return Ws(this.editor)}},FE=["start","middle","end"],OE=class extends DT{type="text";getDefaultProps(){return{richText:ms(""),w:16,h:va(xE),autoSize:!0,scale:1,font:uE,size:xE,color:E("text-slate"),backgroundColor:B("transparent"),textAlign:"start"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{richText:Ss(t.richText),w:Math.max(1,sd(t.w,n.w)),h:Math.max(1,sd(t.h,n.h)),autoSize:"boolean"==typeof t.autoSize?t.autoSize:n.autoSize,scale:Math.max(.01,sd(t.scale,n.scale)),font:ia(t.font)?t.font:n.font,size:xa(t.size,n.size),color:F(t.color,n.color),backgroundColor:F(t.backgroundColor,n.backgroundColor),textAlign:(o=t.textAlign,"string"==typeof o&&FE.includes(o)?t.textAlign:n.textAlign)};var o}getPositionedBounds(e){return(e=>new LC(e.x,e.y,dd(e),ld(e)))(e)}getLocalBounds(e){return cd(e)}getRenderBounds(e){return cd(e)}getExportBounds(e){return cd(e)}canSnap(e,t){return!t||(n=t.editor,o=e.id,js(n,o)?.behavior.canSnap??null??!0);var n,o}canReceiveTerminalBinding(e,t){return!t||(n=t.editor,o=e.id,js(n,o)?.behavior.canReceiveTerminalBinding??null??!0);var n,o}canEdit(e){return!0}contributesToSelectionFrame(e,t){return n=t.editor,o=e.id,js(n,o)?.behavior.contributesToSelectionFrame??null??!0;var n,o}canUseSelectionResizeHandles(e,t){return n=t.editor,o=e.id,js(n,o)?.behavior.canUseSelectionResizeHandles??null??!0;var n,o}canUseSelectionRotateHandle(e,t){return n=t.editor,o=e.id,js(n,o)?.behavior.canUseSelectionRotateHandle??null??!0;var n,o}getSelectionTargetId(e,t){return((e,t)=>{const n=js(e,t);return n?"owner"===n.behavior.selectionTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}getHoverTargetId(e,t){return((e,t)=>{const n=js(e,t);return n?"owner"===n.behavior.hoverTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}getHoverDecorationTargetId(e,t){return((e,t)=>{const n=js(e,t);return n?"owner"===n.behavior.hoverDecorationTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}getTranslateTargetId(e,t){return((e,t)=>{const n=js(e,t);return n?"owner"===n.behavior.translateTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}resizeSelectionBounds(e,t){const n={};t.isOnlyResizeTarget&&ud(t.handleId)?(n.w=Math.max(16,t.selectionLocalBounds.w/ad(e)),n.autoSize=!1):n.scale=Math.max(.01,e.props.scale*((e,t)=>{const n=t.selectionLocalBounds.w/Math.max(1,dd(e)),o=t.selectionLocalBounds.h/Math.max(1,ld(e));switch(t.handleId){case"left":case"right":return n;case"top":case"bottom":return o;default:return Math.max(n,o)}})(e,t));const o=n.scale??ad(e),i=(n.w??e.props.w)*o,r=e.props.h*o,s=((e,t)=>0===t.selectionRotation?e.clone():$C.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(Mn({handleId:t.handleId,requestedBounds:t.selectionLocalBounds,actualWidth:i,actualHeight:r,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,t);return{id:e.id,x:s.x-i/2,y:s.y-r/2,rotation:t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,scaleX:t.scaleX<0?-e.scaleX:e.scaleX,scaleY:t.scaleY<0?-e.scaleY:e.scaleY,props:n}}getAllowedSelectionResizeModes(e,t){return t.isOnlyResizeTarget&&ud(t.handleId)?ST:bT}onEditEnd(e){if(!(ys(e.props.richText).trim().length>0))return{deleteShapeIds:[e.id]}}},DE=class{fontCatalog;type="text";constructor(e){this.fontCatalog=e}toSvg(e,t){if(0===ys(e.props.richText).trim().length)return null;const n=Ys(Gs(t.editor,e),e.props.w);return{tag:"foreignObject",attrs:{x:0,y:0,width:e.props.w*e.props.scale,height:e.props.h*e.props.scale},children:[{tag:"div",attrs:{xmlns:"http://www.w3.org/1999/xhtml",dir:"auto",style:gd(e,t,this.fontCatalog,n)},children:pd(e.props.richText,z(e.props.backgroundColor)?void 0:t.resolveColor(e.props.backgroundColor))}]}}},zE=".label",UE=class extends eT{type=dE;getDefaultProps(){return{labelPosition:.5}}validateProps(e){const t=this.getDefaultProps();return{labelPosition:md((e&&"object"==typeof e?e:{}).labelPosition,t.labelPosition)}}canBind(e,t,n){return this.canUseShapeHierarchy(t,n,e)}canUseShapeHierarchy(e,t,n){return Us(t.fromShape)&&(!n||null!==Sd(n,t.toShape))}getExclusiveBindingKey(e){return e.toId}onBindingCreate(e,t){return this.syncLabelPosition(e,t)}onBindingUpdate(e,t,n){return this.syncLabelPosition(e,n)}onBindingLoad(e,t){return this.syncLabelPosition(e,t)}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}getTargetShapeContentCutoutLocalPolygons(e,t,n){if(!Us(n.fromShape)||!Sd(e,n.toShape))return[];const o=e.computeShapeLocalToPageTransform(n.toShape).tryInvert();if(!o)return[];const i=e.computeShapeLocalBounds(n.fromShape),r=o.compose(e.computeShapeLocalToPageTransform(n.fromShape));return[[new $C(i.minX,i.minY),new $C(i.maxX,i.minY),new $C(i.maxX,i.maxY),new $C(i.minX,i.maxY)].map(e=>r.applyToPoint(e))]}onAfterShapeChange(e,t,n){return this.syncLabelPosition(e,t)}onBeforeDeleteShape(e,t,n){return"from"===n.role?{deleteBindingIds:[t.id]}:{deleteShapeIds:[t.fromId],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){return{deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}getShapeHierarchyRootId(e,t){return t===e.fromId?e.toId:null}getSelectionCompanionFrameGeometries(e,t,n){if(t.toId!==n.selectedShape.id)return[];if(!0!==((e,t)=>js(e,t)?.behavior.showsCompanionFrameWhenOwnerSelected??null)(e,t.fromId))return[];const o=e.getShape(t.fromId),i=e.getShape(t.toId);if(!Us(o)||!i||!Sd(e,i))return[];const r=e.computeShapeGeometry(o),s=e.computeShapeLocalToPageTransform(o),a=Math.atan2(s.b,s.a);return[{bounds:LC.FromPoints(r.outlineVertices.map(e=>$C.RotWith(e,r.center,-a))),rotation:a,rotationCenter:r.center}]}syncLabelPosition(e,t){if(!fd(t))return;const n=e.getShape(t.fromId),o=e.getShape(t.toId);if(!Us(n)||!o||!Sd(e,o))return{deleteBindingIds:[t.id]};const i=((e,t,n,o)=>{const i=yd(e,t,n,o),r=n.parentId,s=`${n.index}${zE}`,a=!1,d="middle",l=_s(e,t,r,i);return l?t.x===l.x&&t.y===l.y&&t.rotation===l.rotation&&t.skewX===l.skewX&&t.scaleX===l.scaleX&&t.scaleY===l.scaleY&&t.parentId===r&&t.index===s&&t.props.w===i.props.w&&t.props.autoSize===a&&t.props.textAlign===d?null:{id:t.id,...l,parentId:r,index:s,props:{w:i.props.w,autoSize:a,textAlign:d}}:null})(e,n,o,t.props.labelPosition);return i?{shapes:[{...n,...i,props:{...n.props,...i.props}}]}:void 0}},NE=".label",WE=class extends eT{type=lE;getDefaultProps(){return{normalizedAnchor:{x:.5,y:.5},ownerBaseHeight:0}}validateProps(e){const t=this.getDefaultProps(),n=e&&"object"==typeof e?e:{},o=n.normalizedAnchor&&"object"==typeof n.normalizedAnchor?n.normalizedAnchor:t.normalizedAnchor;return{normalizedAnchor:{x:wd(o.x,t.normalizedAnchor.x),y:wd(o.y,t.normalizedAnchor.y)},ownerBaseHeight:Id(n.ownerBaseHeight,t.ownerBaseHeight)}}canBind(e,t,n){return this.canUseShapeHierarchy(t,n)}canUseShapeHierarchy(e,t){return Us(t.fromShape)&&xd(t.toShape)}getExclusiveBindingKey(e){return e.toId}onBindingCreate(e,t){return this.syncLabelPosition(e,t)}onBindingUpdate(e,t,n){return this.syncLabelPosition(e,n,t.toId===n.toId?void 0:{role:"to"})}onBindingLoad(e,t){return this.syncLabelPosition(e,t)}getGeometryDependentShapeIds(e,t,n){return"from"===n.role?[t.toId]:[t.fromId]}onAfterShapeChange(e,t,n){return this.syncLabelPosition(e,t,n)}onBeforeDeleteShape(e,t,n){if("from"===n.role){const n=e.getShape(t.toId),o=n?vd(n,t):null;return{shapes:o?[o]:void 0,deleteBindingIds:[t.id]}}return{deleteShapeIds:[t.fromId],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.toId),o=n?vd(n,t):null;return{shapes:o?[o]:void 0,deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}getShapeHierarchyRootId(e,t){return t===e.fromId?e.toId:null}syncLabelPosition(e,t,n){if(o=t,"binding"!==o?.typeName||"geo-label"!==o.type)return;var o;const i=e.getShape(t.fromId),r=e.getShape(t.toId);if(!Us(i)||!xd(r))return{deleteBindingIds:[t.id]};const s=((e,t,n)=>{const o=Pd(t,"h")??1;return"to"===n?.role?o:e.props.ownerBaseHeight>0?e.props.ownerBaseHeight:o})(t,r,n),a=t.props.ownerBaseHeight===s?null:{...t,props:{...t.props,ownerBaseHeight:s}},d=function(e,t,n){const o=Pd(e,"h");if(!o)return null;const i=Math.max(n,(e=>Math.max(1,e.props.h*e.props.scale+32))(t));return o===i?null:{...e,props:{...e.props,h:i}}}(r,i,s),l=((e,t,n)=>{const o=kd(e,t,n),i=n.parentId,r=`${n.index}${NE}`,s=!1,a="middle",d=_s(e,t,i,o);return d?t.x===d.x&&t.y===d.y&&t.rotation===d.rotation&&t.skewX===d.skewX&&t.scaleX===d.scaleX&&t.scaleY===d.scaleY&&t.parentId===i&&t.index===r&&t.props.w===o.props.w&&t.props.autoSize===s&&t.props.textAlign===a?null:{id:t.id,...d,parentId:i,index:r,props:{w:o.props.w,autoSize:s,textAlign:a}}:null})(e,i,d??r),c=[];return d&&c.push(d),l&&c.push({...i,...l,props:{...i.props,...l.props}}),c.length>0||a?{shapes:c.length>0?c:void 0,bindings:a?[a]:void 0}:void 0}},XE="text.edit",YE="path-label.edit",HE="path-label.create",_E="path-label.drag",KE="geo-label.edit",qE="geo-label.create",jE=gr("plugin-text.api"),VE={token:jE,create:({editor:e})=>e.shapeUtils.has("text")?(e=>({create(t){const n=e.getDefaultShapeProps("text"),[o]=e.commands.createShapes([{type:"text",x:t.x,y:t.y,meta:t.meta?{...t.meta}:void 0,props:{...n,w:t.w??n.w,h:t.h??n.h,font:t.font??n.font,color:t.color??n.color,size:t.size??n.size,textAlign:t.textAlign??n.textAlign,richText:ms(t.text)}}],{source:"user"});return o&&"text"===o.type?{id:o.id,type:o.type}:null}}))(e):null},GE=tr("plugin-text.font-catalog"),ZE=[{value:E("text-slate"),label:"Slate",id:"slate",hexColor:"#0f172a"},{value:E("text-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:E("text-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:E("text-red"),label:"Red",id:"red",hexColor:"#dc2626"}],QE=[{id:"none",value:B("transparent"),label:"None",hexColor:"#fef08a",opacity:0},{id:"yellow",value:B("#fef08a"),label:"Yellow",hexColor:"#fef08a",opacity:1},{id:"blue",value:B("#bfdbfe"),label:"Blue",hexColor:"#bfdbfe",opacity:1},{id:"green",value:B("#bbf7d0"),label:"Green",hexColor:"#bbf7d0",opacity:1},{id:"red",value:B("#fecaca"),label:"Red",hexColor:"#fecaca",opacity:1}],JE=[{id:"s",value:14,label:"S"},{id:"m",value:16,label:"M"},{id:"l",value:20,label:"L"},{id:"xl",value:28,label:"XL"}],eB=[{value:"start",label:"Align left",icon:"align-left"},{value:"middle",label:"Align center",icon:"align-center"},{value:"end",label:"Align right",icon:"align-right"}],tB=[{format:"bold",actionId:"text.toggle-bold",label:"Bold",icon:"bold",dataUi:"selected-text-bold-button"},{format:"italic",actionId:"text.toggle-italic",label:"Italic",icon:"italic",dataUi:"selected-text-italic-button"},{format:"underline",actionId:"text.toggle-underline",label:"Underline",icon:"underline",dataUi:"selected-text-underline-button"},{format:"strike",actionId:"text.toggle-strike",label:"Strikethrough",icon:"strikethrough",dataUi:"selected-text-strike-button"}],nB="text.clear-formatting",oB="text.set-link",iB=qd(),rB=2*Math.PI,sB=gr("plugin-arrow.api"),aB={token:sB,create:({editor:e})=>e.shapeUtils.has("arrow")?(e=>({create(t){const n=e.getDefaultShapeProps("arrow"),o=Hl(e,{startPagePoint:new $C(t.start.x,t.start.y),endPagePoint:new $C(t.end.x,t.end.y),startBinding:t.startBinding?{targetShapeId:t.startBinding.targetShapeId,normalizedAnchor:t.startBinding.normalizedAnchor}:null,endBinding:t.endBinding?{targetShapeId:t.endBinding.targetShapeId,normalizedAnchor:t.endBinding.normalizedAnchor}:null,meta:t.meta?{...t.meta}:void 0,props:{...n,bend:t.bend??n.bend,stroke:t.stroke??n.stroke,strokeWidth:t.strokeWidth??n.strokeWidth,headStart:t.headStart??n.headStart,headEnd:t.headEnd??n.headEnd}});return{id:o.id,type:o.type}}}))(e):null},dB=class extends zT{constructor(e){super(e,"arrow"),this.initial="idle",this.addChild(new lB(e,this)),this.addChild(new cB(e,this))}},lB=class extends zT{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.editor.getDefaultShapeProps("arrow"),n=((e,{terminal:t,rawPagePoint:n,ignoreTargets:o=!1})=>ec(e,{terminal:t,rawPagePoint:n,oppositePagePoint:n.add(new $C(1,0)),ignoreTargets:o}))(this.editor,{terminal:"start",rawPagePoint:e.pagePoint,ignoreTargets:e.accelKey});this.transition("creating",{startPagePoint:n.pagePoint,currentPagePoint:n.pagePoint.clone(),shapeId:null,startBinding:n.binding,props:t})}},cB=class extends zT{info=null;operation=null;constructor(e,t){super(e,"creating",t)}onEnter(e){if(this.info=e,!this.info)return;this.operation=this.editor.operations.begin({kind:"arrow.create",label:"shape.create",source:"user",history:"record"});const t=Hl(this.editor,{startPagePoint:this.info.startPagePoint,endPagePoint:this.info.startPagePoint,startBinding:this.info.startBinding,props:{stroke:this.info.props.stroke,strokeWidth:this.info.props.strokeWidth,headStart:this.info.props.headStart,headEnd:this.info.props.headEnd}},"user");this.info.shapeId=t.id,this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),this.editor.setBindingPreview(null),this.updateCreationBindingGuides(t)}onPointerMove(e){this.updateShape(e.pagePoint)}onTick(e){if(!this.info)return;const t=this.editor.inputs.state.get();if("dragging"!==t.dragPhase||!t.currentPagePoint||!t.currentScreenPoint)return;const n=$i(t.currentScreenPoint,this.editor.viewportScreenSizeSignal.get(),e.elapsed);0===n.x&&0===n.y||(this.editor.panCamera(n),this.updateShape(this.editor.screenToPage(t.currentScreenPoint)))}onPointerUp(e){if(this.info){if(this.updateShape(e.pagePoint),!this.info.shapeId||this.info.startPagePoint.dist(this.info.currentPagePoint)<4)return this.cancelOperation(),void this.transition("idle");Pe(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})}else this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.editor.setTerminalBindingGuides(null),this.info=null}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}updateShape(e){if(!this.info)return;this.info.currentPagePoint=e.clone();const t=this.info.shapeId,n=t?this.editor.getShape(t):null,o=bl(n)?tc(this.editor,{arrow:n,terminal:"end",rawPagePoint:e,ignoreTargets:this.editor.inputs.state.get().accelKey}):ec(this.editor,{terminal:"end",rawPagePoint:e,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey}),i=_l(this.editor,t,"end",this.info.startBinding&&o.binding?.targetShapeId===this.info.startBinding.targetShapeId?{pagePoint:e,binding:null,preview:null}:o,"user")??(t?this.editor.getShape(t):null);this.updateCreationBindingGuides(bl(i)?i:null)}updateCreationBindingGuides(e){if(!e)return void this.editor.setTerminalBindingGuides(null);const t=new Map(this.editor.getBindingsFromShape(e.id).filter(xl).map(e=>[e.props.terminal,e.toId])),n=Pl(this.editor,e).bindingSegments.map(n=>({...n,ownerShapeId:e.id,targetShapeId:t.get(n.terminal)??null}));this.editor.setTerminalBindingGuides(n)}},uB=[{value:E("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:E("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:E("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:E("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],pB=[{value:"both",label:"Both ends",icon:"arrows-horizontal"},{value:"start",label:"Start",icon:"arrow-narrow-left"},{value:"end",label:"End",icon:"arrow-narrow-right"},{value:"none",label:"None",icon:"minus"}],hB={id:"arrow",provides:[sB],editor:{id:"land.arrow",shapeCapabilities:[{type:"arrow",schemaProps:["w","h","start","end","bend","stroke","strokeWidth","headStart","headEnd"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Binding support lives in arrow binding records, not arrow props."]}],shapeUtils:[new class extends DT{type="arrow";getDefaultProps(){return{w:160,h:48,start:{x:8,y:24},end:{x:152,y:24},bend:0,stroke:E("stroke-slate"),strokeWidth:2,headStart:"none",headEnd:"arrow"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,Zl(t.w,n.w)),h:Math.max(1,Zl(t.h,n.h)),start:Gl(t.start,n.start),end:Gl(t.end,n.end),bend:Zl(t.bend,n.bend),stroke:F(t.stroke,n.stroke),strokeWidth:Math.max(1,Zl(t.strokeWidth,n.strokeWidth)),headStart:"arrow"===t.headStart?"arrow":"none",headEnd:"none"===t.headEnd?"none":"arrow"}}getPositionedBounds(e){const t=ol(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}getPointHitTestBounds(e,t){const n=Math.max(8,e.props.strokeWidth+4);if(!t?.editor)return ol(e).bounds.expand(n);const o=Pl(t.editor,e).info,i=t.editor.computeShapePositionedToPageTransform(e).tryInvert();if(!i||0===o.points.length)return ol(e).bounds.expand(n);const r=n*Math.sqrt(i.a*i.a+i.b*i.b+i.c*i.c+i.d*i.d);return LC.FromPoints(o.points.map(e=>i.applyToPoint(e))).expand(r)}getLocalBounds(e){return new LC(0,0,e.props.w,e.props.h)}getExportBounds(e){const t=il(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}repairLoadedShape(e){return null}updateSelectionPagePoints(e,t){const n=this.getSelectionPageMiddlePoint(e);if(t.pageMiddlePoint&&n){const o=this.getSelectionPagePoints(e),i=((e,t)=>{const n=e[1].sub(e[0]),o=e[2].sub(e[0]),i=n.x*o.y-n.y*o.x;if(Math.abs(i)<1e-9)return null;const r=new FC(o.y/i,-n.y/i,-o.x/i,n.x/i,0,0),s=t[1].sub(t[0]),a=t[2].sub(t[0]),d=new FC(s.x,s.y,a.x,a.y,0,0).compose(r);return new FC(d.a,d.b,d.c,d.d,t[0].x-d.a*e[0].x-d.c*e[0].y,t[0].y-d.b*e[0].x-d.d*e[0].y)})([o[0],o[1],n],[t.pagePoints[0],t.pagePoints[1],t.pageMiddlePoint]);if(i){const t=ce(i.compose(this.getLocalToPageTransform(e)),this.getLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY});if(t)return{id:e.id,...t}}}const o=((e,t,n)=>{const o=nl(t,n);return{...e,x:o.x,y:o.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{...e.props,w:o.w,h:o.h,start:o.start,end:o.end,bend:e.props.bend}}})(e,t.pagePoints[0],t.pagePoints[1]);return{id:e.id,x:o.x,y:o.y,rotation:o.rotation,skewX:o.skewX,scaleX:o.scaleX,scaleY:o.scaleY,props:{w:o.props.w,h:o.props.h,start:o.props.start,end:o.props.end,bend:t.pageMiddlePoint?rl(t.pagePoints[0],t.pagePoints[1],t.pageMiddlePoint):o.props.bend}}}isWrappedByBrush(e,t){return t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}getSelectionPagePoints(e){return[Zd(e,"start"),Zd(e,"end")]}getSelectionPageMiddlePoint(e){return this.getLocalToPageTransform(e).applyToPoint(il(e).middle)}contributesToSelectionFrame(e,t){return t.editor.getSelectedShapeIds().length>1}canUseSelectionResizeHandles(e,t){return t.editor.getSelectedShapeIds().length>1}canUseSelectionRotateHandle(e,t){return t.editor.getSelectedShapeIds().length>1}canStartTranslateFromSelectionBounds(e,t){return t.editor.getSelectedShapeIds().length>1}getSelectionHandleAnchors(e,t){if(!t.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=Pl(t.editor,e).info;return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.start.handle},{kind:"binding_terminal",terminal:"end",point:n.end.handle}],middleHandleAnchors:n.middle?[{kind:"binding_middle",point:n.middle}]:[]}}getSelectionOverlayInfo(e,t){const n=Pl(t.editor,e),o=n.info,i=vl(t.editor,e),r=Kl(i,e.props),s=t.editor.computeShapeLocalToPageTransform(e);return{usesSelectionPathOverlay:!0,startPagePoint:o.start.point,endPagePoint:o.end.point,middlePagePoint:o.middle,path:o.path,pathStyle:{localPath:i.path,localDecorationPaths:r.path?[r.path]:[],localBounds:LC.FromPoints([...i.points,...r.points]),localToPage:s,strokeWidth:e.props.strokeWidth},pageClipPath:Pi({outputBounds:o.bounds,cutoutLocalPolygons:t.editor.getShapeContentCutoutLocalPolygonsSignal(e.id).get(),localToOutput:s}),bindingSegments:n.bindingSegments}}getLabelPathGeometry(e,t){return function(e){const t="curved"===e.type&&e.path.includes(" A "),n=t?null:(e=>{const t=[];let n=0;for(let o=1;o<e.length;o+=1){const i=e[o-1].dist(e[o]);t.push(i),n+=i}return{length:n,segmentLengths:t}})(e.points),o=t?e.arc.length:n?.length??0,i=n?sl(e.points,n,e.middle,.5):.5;return{length:o,defaultPosition:.5,getPointAt(o){const r=dl(o);return t?fl(e.start.point,e.end.point,e.arc,r):((e,t,n)=>{const o=e[0]??$C.Zero();if(!t||t.length<=1e-6)return o.clone();const i=t.length*n;let r=0;for(let s=0;s<t.segmentLengths.length;s+=1){const n=t.segmentLengths[s];if(i<=r+n||s===t.segmentLengths.length-1){const t=e[s],o=n<=1e-6?0:(i-r)/n;return t.add(e[s+1].sub(t).mul(dl(o)))}r+=n}return(e[e.length-1]??o).clone()})(e.points,n,al(r,i))},getNearestPosition:(o,r)=>t?((e,t,n=.5)=>{const o=t.sub(e.arc.center);if(o.len2()<=1e-12)return dl(n);const i=e.arc.center.add(o.normalize().mul(e.arc.radius)),r=gl(e.start.point,e.end.point,e.arc);if(Math.abs(r)<=1e-6)return dl(n);const s=gl(e.start.point,i,e.arc);if(Math.abs(s)<=Math.abs(r)+1e-6)return dl(s/r);const a=t.dist2(e.start.point),d=t.dist2(e.end.point);return Math.abs(a-d)<=1e-8?n<=.5?0:1:a<d?0:1})(e,o,r?.hintPosition):((e,t)=>{const n=dl(e),o=dl(t);return n<=o?o<=1e-6?.5:n/o*.5:1-o<=1e-6?.5:.5+(n-o)/(1-o)*.5})(sl(e.points,n,o,al(r?.hintPosition??.5,i)),i)}}(Pl(t.editor,e).info)}hitTest(e,t,n){return((e,t)=>{let n=1/0;for(let o=0;o<e.points.length-1;o++)n=Math.min(n,yl(t,e.points[o],e.points[o+1]));return Number.isFinite(n)?n:t.dist(e.start.point)})(n?.editor?Pl(n.editor,e).info:ol(e),n?.pagePoint??t)<=Math.max(8,e.props.strokeWidth+4)}hitTestLineSegment(e,t){const n=t.editor?Pl(t.editor,e).info:ol(e),o=Math.max(8,e.props.strokeWidth+4,t.editor?t.pageMargin:t.positionedMargin),i=t.editor?t.pageStart:t.positionedStart,r=t.editor?t.pageEnd:t.positionedEnd;if(1===n.points.length)return Ql(n.points[0],i,r)<=o;for(let s=0;s<n.points.length-1;s+=1){const e=n.points[s],t=n.points[s+1];if(e&&t&&Jl(i,r,e,t)<=o)return!0}return!1}}],shapeSvgExporters:[new class{type="arrow";toSvg(e,t){const n=t.resolveColor(e.props.stroke),o=vl(t.editor,e),i=Pi({outputBounds:o.bounds,cutoutLocalPolygons:t.editor.getShapeContentCutoutLocalPolygonsSignal(e.id).get()}),r=i?t.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"path",attrs:{d:i,"clip-rule":"evenodd","fill-rule":"evenodd"}}]}):void 0,s="arrow"===e.props.headStart?`url(#${t.addDef(ic("start",n))})`:void 0,a="arrow"===e.props.headEnd?`url(#${t.addDef(ic("end",n))})`:void 0;return{tag:"path",attrs:{d:o.path,fill:"none",stroke:n,"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":s,"marker-end":a,"clip-path":r?`url(#${r})`:void 0}}}}],bindingUtils:[new class extends eT{type="arrow";getDefaultProps(){return{terminal:"start",normalizedAnchor:{x:.5,y:.5}}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps(),o=t.normalizedAnchor&&"object"==typeof t.normalizedAnchor?t.normalizedAnchor:n.normalizedAnchor;return{terminal:"end"===t.terminal?"end":n.terminal,normalizedAnchor:{x:Math.min(1,Math.max(0,Xl(o.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,Xl(o.y,n.normalizedAnchor.y)))}}}canBind(e,t,n){return bl(n.fromShape)&&Nl(e,n.toShape)}getExclusiveBindingKey(e){return`${e.fromId}:${e.props.terminal}`}onBindingCreate(e,t){return Yl(this.syncArrowTerminal(e,t))}onBindingUpdate(e,t,n){return Yl(this.syncArrowTerminal(e,n))}onBindingLoad(e,t){return Yl(this.syncArrowTerminal(e,t))}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return Yl(this.syncArrowTerminal(e,t))}onBeforeDeleteShape(e,t,n){if("from"===n.role)return{deleteBindingIds:[t.id]};const o=e.getShape(t.fromId);if(!bl(o))return{deleteBindingIds:[t.id]};const i=this.resolveTerminalPagePoint(e,t);return{shapes:[i?tl(e,o,t.props.terminal,i)??o:o],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.fromId);if(!bl(n))return{deleteBindingIds:[t.id]};const o=this.resolveTerminalPagePoint(e,t);return{shapes:[o?tl(e,n,t.props.terminal,o)??n:n],deleteBindingIds:[t.id]}}syncArrowTerminal(e,t){if(!xl(t))return null;const n=e.getShape(t.fromId);if(!bl(n))return null;const o=this.resolveTerminalPagePoint(e,t);return o?Qd(e,n,t.props.terminal).dist(o)<1e-6?null:tl(e,n,t.props.terminal,o):null}resolveTerminalPagePoint(e,t){if(!xl(t))return null;const n=e.getShape(t.fromId),o=e.getShape(t.toId);if(!bl(n)||!o||bl(o))return null;const i=Qd(e,n,Jd(t.props.terminal)),r=Gd(e,o,t.props.normalizedAnchor,i);return Ll(e,{arrow:n,terminal:t.props.terminal,target:o,anchorPagePoint:Vd(e,o,t.props.normalizedAnchor),fallbackBoundaryPagePoint:r}).boundaryPagePoint}}],interactionHandlers:[{id:"land.arrow.interactions",selectionHandle:{createSession:(e,{handle:t,shape:n})=>bl(n)?"binding_terminal"===t.kind?(({handle:e,shapeId:t,terminal:n})=>({shapeId:t,historyMark:"select.binding_terminal_drag",handleSnapMode:"point",handleSnapContext:{shapeId:t,handle:e},shouldClearBindingPreviewOnExit:!0,update({editor:e,pagePoint:o,accelKey:i,source:r}){const s=e.getShape(t);if(!bl(s))return{status:"stop",finalPagePoint:null};const a=tc(e,{arrow:s,terminal:n,rawPagePoint:o,ignoreTargets:i}),d=_l(e,s.id,n,a,r);return{status:"continue",finalPagePoint:d?Qd(e,d,n):a.pagePoint}}}))({handle:t,shapeId:n.id,terminal:t.terminal}):"binding_middle"===t.kind?(({shapeId:e})=>({shapeId:e,historyMark:"select.binding_middle_drag",update({editor:t,pagePoint:n,accelKey:o,source:i}){const r=t.getShape(e);if(!bl(r))return"stop";const s=((e,t)=>({start:Il(e,t,"start").handlePagePoint,end:Il(e,t,"end").handlePagePoint}))(t,r),a=rl(s.start,s.end,n),d=t.computeShapeLocalToPageTransform(r).tryInvert();if(!d)return"stop";const l=rl(d.applyToPoint(s.start),d.applyToPoint(s.end),d.applyToPoint(n)),c=0===(({bend:e,bypassSnap:t,zoom:n})=>t?e:Math.abs(e)*n<=6?0:e)({bend:a,bypassSnap:o,zoom:t.cameraZoomSignal.get()})?0:l;return t.commands.updateShapes([{id:r.id,props:{bend:c}}],{source:i}),"continue"}}))({shapeId:n.id}):null:null}}],setup(e){e.setTerminalBindingResolver(ec),e.tools.register("arrow",e=>new dB(e),{shortcut:"a"})}},render:{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:function({shape:e,editor:t}){
|
|
88
|
+
return Gk(hc,{shape:e,editor:t,idPrefix:"arrow",stroke:O(e.props.stroke),strokeWidth:e.props.strokeWidth})},hoverComponent:function({shape:e,editor:t,strokeWidth:n}){
|
|
89
|
+
return Gk(hc,{dataUi:"arrow-hover-outline",shape:e,editor:t,idPrefix:"arrow-hover",stroke:xM,strokeWidth:n,vectorEffect:"non-scaling-stroke"})}}]},setup:e=>{e.apis.add(aB),e.actions.add(sc("stroke"),sc("strokeWidth"),{id:"arrow.set-direction",getAvailability:e=>"arrow"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:e=>(e=>{let t;for(const n of e){if("arrow"!==n.type)continue;const e=n.props,o=lc(e.headStart,e.headEnd);if(void 0===t)t=o;else if(t!==o)return null}return t??null})(e.selection.selectedShapes),run({context:e,value:t}){const n=cc(t);if(!n)return;const o=e.selection.selectedShapes.filter(e=>"arrow"===e.type).filter(e=>!e.isLocked).map(e=>({id:e.id,props:n}));o.length>0&&e.editor.commands.updateShapes(o,{source:"user"})}},ac("stroke"),ac("strokeWidth"),{id:"arrow.default-direction",getAvailability:e=>"arrow"===e.tool.activeToolId?"enabled":"inapplicable",getValue(e){const t=e.editor.getDefaultShapeProps("arrow");return lc(t.headStart,t.headEnd)},run({context:e,value:t}){const n=cc(t);n&&e.editor.updateDefaultShapeProps("arrow",n)}}),e.toolbar.add({id:"arrow.tool-toolbar",channel:gM.toolSwitcher,order:40,actionIds:[pM],getGroups:e=>[{id:"arrow.tools",items:[{kind:"button",id:"arrow.tool.arrow",actionId:pM,value:"arrow",label:"Arrow",shortcut:e.editor.shortcuts.getToolShortcutLabel("arrow"),icon:"arrow-right",dataUi:"arrow-tool-button"}]}]},{id:"arrow.default-style.tool-toolbar",channel:gM.toolOptions,order:41,actionIds:["arrow.default-stroke","arrow.default-strokeWidth","arrow.default-direction"],when:e=>"arrow"===e.tool.activeToolId,getGroups:()=>rc({strokeActionId:"arrow.default-stroke",strokeWidthActionId:"arrow.default-strokeWidth",directionActionId:"arrow.default-direction",dataUiPrefix:"arrow-default"})},{id:"arrow.selection-toolbar",channel:gM.selectionProperties,order:20,actionIds:["arrow.set-stroke","arrow.set-strokeWidth","arrow.set-direction"],when:e=>"arrow"===e.selection.commonShapeType,getGroups:()=>rc({strokeActionId:"arrow.set-stroke",strokeWidthActionId:"arrow.set-strokeWidth",directionActionId:"arrow.set-direction",dataUiPrefix:"arrow"})})}},gB=gr("plugin-frame.api"),fB={token:gB,create:({editor:e})=>e.shapeUtils.has("frame")?(e=>({create(t){const n=e.getDefaultShapeProps("frame"),[o]=e.commands.createShapes([{type:"frame",x:t.x,y:t.y,meta:t.meta?{...t.meta}:void 0,props:{...n,w:t.w??n.w,h:t.h??n.h,name:t.name??n.name,fill:t.fill??n.fill,stroke:t.stroke??n.stroke,strokeWidth:t.strokeWidth??n.strokeWidth}}],{source:"user"});return o&&"frame"===o.type?{id:o.id,type:o.type}:null},moveShapesToFrame(t,n){const o=e.getShape(n);if(!o||"frame"!==o.type)return[];const i=t.filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked});return 0===i.length?[]:(e.commands.reparentShapes({ids:i,parentId:n},{source:"user"}),i)}}))(e):null},mB=class extends zT{constructor(e){super(e,"frame"),this.initial="idle",this.addChild(new yB(e,this)),this.addChild(new SB(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("frame")}},yB=class extends zT{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("creating",{originPagePoint:e.pagePoint.clone(),currentPagePoint:e.pagePoint.clone(),shapeId:null,shiftKey:e.shiftKey})}},SB=class extends zT{tool;info=null;operation=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.operation=this.editor.operations.begin({kind:"frame.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.commitOperation(),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.info=null}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}updateShape(e,t,n=!1){if(!this.info)return;this.info.currentPagePoint=e.clone(),this.info.shiftKey=t;const o=this.info.originPagePoint.dist(e);if(!this.info.shapeId&&o<4){if(!n)return;const t=((e,t)=>new LC(e.x-t.w/2,e.y-t.h/2,t.w,t.h))(e,this.tool.getDefaultProps()),o=this.createShape(t);return void(this.info.shapeId=o.id)}const i=((e,t,n,o)=>{let i=t.x-e.x,r=t.y-e.y;if(n){const e=o.w/o.h,t=Math.abs(i),n=Math.abs(r);0===n||t/Math.max(n,1)>=e?r=t/e*(r<0?-1:1):i=n*e*(i<0?-1:1)}const s=new $C(e.x+i,e.y+r);return new LC(Math.min(e.x,s.x),Math.min(e.y,s.y),Math.max(Math.abs(s.x-e.x),1),Math.max(Math.abs(s.y-e.y),1))})(this.info.originPagePoint,e,t,this.tool.getDefaultProps());if(!this.info.shapeId){const e=this.createShape(i);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:i.x,y:i.y,props:{w:i.w,h:i.h}}],{source:"user"})}createShape(e){const[t]=this.editor.commands.createShapes([{type:"frame",x:e.x,y:e.y,props:{...this.tool.getDefaultProps(),w:e.w,h:e.h}}],{source:"user",autoReparent:!1});if(!t||"frame"!==t.type)throw new Error("Failed to create frame shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},bB=[{id:"none",value:B("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:E("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:E("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:E("fill-amber"),label:"Amber",id:"amber",hexColor:"#fff7ed"}],xB=[{value:E("stroke-muted"),label:"Slate",id:"muted",hexColor:"#94a3b8"},{value:E("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:E("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:E("stroke-orange"),label:"Orange",id:"orange",hexColor:"#ea580c"}],wB='[data-ui="frame-canvas-heading"]',IB=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),PB={id:"land.frame.name.dom-events",handle({event:e}){const t=e.target;return t instanceof Element&&t.closest(wB)?"handled":"continue"},getCursor:({element:e})=>e?.closest(wB)?"text":void 0},vB={id:"frame",provides:[gB],editor:{id:"land.frame",shapeCapabilities:[{type:"frame",schemaProps:["w","h","name","fill","stroke","strokeWidth"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Frame renderer, SVG exporter, creation tool, selected-frame style toolbar, selected-child order badge, and minimal single-child sibling reorder controls live in the frame plugin package. ParentId-based child query, child-index ordering, containing-parent query, clipped query bounds, point-in-clip checks, host clipping, select-drag containment, export descendant traversal, and clipped child export have preflights. Richer hover/drag reorder UI remains deferred."]}],shapeUtils:[new class extends DT{type="frame";getDefaultProps(){return{w:640,h:360,name:"",fill:B("transparent"),stroke:E("stroke-muted"),strokeWidth:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,mc(t.w,n.w)),h:Math.max(1,mc(t.h,n.h)),name:"string"==typeof t.name?t.name:n.name,fill:F(t.fill,n.fill),stroke:F(t.stroke,n.stroke),strokeWidth:Math.max(0,mc(t.strokeWidth,n.strokeWidth))}}getLocalBounds(e){return new LC(0,0,e.props.w,e.props.h)}getRenderBounds(e){return fc(e)}getPointHitTestBounds(e){return this.getPositionedBounds(e).expand(3)}canEdit(e){return!0}canReceiveChildren(e){return!0}canSnapChildrenToSelf(e){return!0}canReceiveTerminalBinding(e){return!0}getSelectionResizeHandleIds(e,t){return mT}shouldRotateDescendants(e){return!0}getChildClipLocalBounds(e){return this.getLocalBounds(e)}canSelectByBrush(e,t){return super.isWrappedByBrush(e,t)}hitTest(e,t){return yc(this.getPositionedBounds(e),t,6)}hitTestBindingTarget(e,t){return this.getPositionedBounds(e).containsPoint(t)}hitTestLineSegment(e,t){return((e,t,n,o)=>{const i=o/2;if(yc(e,t,o)||yc(e,n,o))return!0;const r=[new $C(e.minX,e.minY),new $C(e.maxX,e.minY),new $C(e.maxX,e.maxY),new $C(e.minX,e.maxY)];for(let s=0;s<r.length;s+=1){const e=r[s],o=r[(s+1)%r.length];if(e&&o&&P(t,n,e,o)<=i)return!0}return!1})(this.getPositionedBounds(e),t.positionedStart,t.positionedEnd,Math.max(6,t.positionedMargin))}}],shapeSvgExporters:[new class{type="frame";toSvg(e,t){const{fill:n,stroke:o,strokeWidth:i,w:r,h:s,name:a}=e.props,d=t.resolveColor(o),l=i/2;return{tag:"g",children:[{tag:"rect",attrs:{x:l,y:l,width:Math.max(r-i,0),height:Math.max(s-i,0),fill:t.resolveColor(n),stroke:d,"stroke-width":i,"stroke-linejoin":"round","stroke-linecap":"round"}},{tag:"text",attrs:{x:0,y:-8,fill:d,"font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":400},children:[gc(a)]}]}}}],setup(e){e.tools.register("frame",e=>new mB(e),{shortcut:"f"})}},render:{id:"land.frame.react",domEventGuards:[PB],shapeRenderers:[{type:"frame",component:function({editor:e,shape:t,shapeEditingSession:n}){const o=n?.shapeId===t.id;
|
|
90
|
+
return Zk("div",{style:{height:"100%",overflow:"visible",position:"relative",width:"100%"},children:[Gk(Cc,{shape:t,hideName:!0}),Gk(Tc,{editor:e,shape:t,isEditing:o})]})},hoverComponent:function({shape:e,strokeWidth:t}){const{h:n,w:o}=e.props,i=fc(e);
|
|
91
|
+
return Gk("svg",{"data-ui":"frame-hover-outline",width:"100%",height:"100%",viewBox:`${i.x} ${i.y} ${i.w} ${i.h}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Gk("rect",{x:0,y:0,width:o,height:n,fill:"none",stroke:xM,strokeWidth:t,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"non-scaling-stroke"})})}}]},setup:e=>{e.apis.add(fB),e.actions.add(Sc("fill"),Sc("stroke"),Sc("strokeWidth"),bc("fill"),bc("stroke"),bc("strokeWidth"),{id:"frame.rename",getAvailability(e){if(1!==e.selection.count||"frame"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;return"frame"!==t?.type||t.isLocked?"disabled":"enabled"},getValue(e){const[t]=e.selection.selectedShapes;return"frame"===t?.type?t.props.name:null},run({context:e,value:t}){const[n]=e.selection.selectedShapes;"frame"===n?.type&&"string"==typeof t&&e.editor.commands.updateShapes([{id:n.id,props:{name:t}}],{source:"user"})}},wc("backward"),wc("forward")),e.toolbar.add({id:"frame.tool-toolbar",channel:gM.toolSwitcher,order:60,actionIds:[pM],getGroups:e=>[{id:"frame.tools",items:[{kind:"button",id:"frame.tool.frame",actionId:pM,value:"frame",label:"Frame",shortcut:e.editor.shortcuts.getToolShortcutLabel("frame"),icon:"frame",dataUi:"frame-tool-button"}]}]},{id:"frame.default-style.tool-toolbar",channel:gM.toolOptions,order:61,actionIds:["frame.default-fill","frame.default-stroke","frame.default-strokeWidth"],when:e=>"frame"===e.tool.activeToolId,getGroups:()=>xc({fillActionId:"frame.default-fill",strokeActionId:"frame.default-stroke",strokeWidthActionId:"frame.default-strokeWidth",dataUiPrefix:"frame-default"})},{id:"frame.selection-toolbar",channel:gM.selectionProperties,order:20,actionIds:["frame.set-fill","frame.set-stroke","frame.set-strokeWidth","frame.rename"],when:e=>"frame"===e.selection.commonShapeType,getGroups:e=>[...1===e.selection.count?[{id:"frame.name",items:[{kind:"text-input",id:"frame.name",actionId:"frame.rename",label:"Frame name",placeholder:"Frame",dataUi:"frame-name-input"}]}]:[],...xc({fillActionId:"frame.set-fill",strokeActionId:"frame.set-stroke",strokeWidthActionId:"frame.set-strokeWidth",dataUiPrefix:"frame"})]},{id:"frame.child-order.selection-toolbar",channel:gM.selectionProperties,order:30,actionIds:["frame.child-order.backward","frame.child-order.forward"],when:e=>"frame"===kc(e),getGroups(e){const t=e.editor.getSelectionSiblingOrderState();return[{id:"frame.child-order",presentation:"overflow",items:[...t?[{kind:"badge",id:"frame.child-order-status",label:`${t.index+1} / ${t.count}`,dataUi:"frame-child-order-status"}]:[],{kind:"button",id:"frame.child-order.backward",actionId:"frame.child-order.backward",label:"Send backward",icon:"stack-backward",dataUi:"frame-child-send-backward-button"},{kind:"button",id:"frame.child-order.forward",actionId:"frame.child-order.forward",label:"Bring forward",icon:"stack-forward",dataUi:"frame-child-bring-forward-button"}]}]}}),e.contextMenu.add({id:"frame.child-order.context-menu",target:"selection",order:40,actionIds:["frame.child-order.backward","frame.child-order.forward"],when:e=>"frame"===kc(e),getSections(e){const t=e.editor.getSelectionSiblingOrderState();return[{id:"frame.child-order-context-menu",title:"Frame child",items:[...t?[{kind:"badge",id:"frame.child-order-status",label:`${t.index+1} / ${t.count}`,dataUi:"context-menu-frame-child-order-status"}]:[],{kind:"command",id:"frame.child-order.forward",actionId:"frame.child-order.forward",label:"Bring forward",icon:"stack-forward",dataUi:"context-menu-frame-child-bring-forward-button"},{kind:"command",id:"frame.child-order.backward",actionId:"frame.child-order.backward",label:"Send backward",icon:"stack-backward",dataUi:"context-menu-frame-child-send-backward-button"}]}]}})}},kB=class extends zT{geo;constructor(e,t,n){super(e,t),this.geo=n,this.initial="idle",this.addChild(new CB(e,this)),this.addChild(new TB(e,this))}getDefaultProps(){return{...this.editor.getDefaultShapeProps("geo"),geo:this.geo}}onEnter(){this.editor.updateDefaultShapeProps("geo",{geo:this.geo})}},CB=class extends zT{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("creating",{originPagePoint:e.pagePoint.clone(),currentPagePoint:e.pagePoint.clone(),shapeId:null,shiftKey:e.shiftKey})}},TB=class extends zT{tool;info=null;operation=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.operation=this.editor.operations.begin({kind:"geo.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.info.shapeId&&Pe(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.info=null}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}updateShape(e,t,n=!1){if(!this.info)return;this.info.currentPagePoint=e.clone(),this.info.shiftKey=t;const o=this.info.originPagePoint.dist(e);if(!this.info.shapeId&&o<4){if(!n)return;const t=((e,t)=>new LC(e.x-t.w/2,e.y-t.h/2,t.w,t.h))(e,this.tool.getDefaultProps()),o=this.createShape(t);return void(this.info.shapeId=o.id)}const i=((e,t,n)=>{let o=t.x-e.x,i=t.y-e.y;if(n){const e=Math.max(Math.abs(o),Math.abs(i));o=(o<0?-1:1)*e,i=(i<0?-1:1)*e}const r=new $C(e.x+o,e.y+i);return new LC(Math.min(e.x,r.x),Math.min(e.y,r.y),Math.max(Math.abs(r.x-e.x),1),Math.max(Math.abs(r.y-e.y),1))})(this.info.originPagePoint,e,t);if(!this.info.shapeId){const e=this.createShape(i);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:i.x,y:i.y,props:{w:i.w,h:i.h}}],{source:"user"})}createShape(e){const[t]=this.editor.commands.createShapes([{type:"geo",x:e.x,y:e.y,props:{...this.tool.getDefaultProps(),w:e.w,h:e.h}}],{source:"user",autoReparent:!1});if(!t)throw new Error("Failed to create geo shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},MB=class extends kB{constructor(e){super(e,"rectangle","rectangle")}},EB=class extends kB{constructor(e){super(e,"ellipse","ellipse")}},BB=class extends kB{constructor(e){super(e,"rhombus","rhombus")}},AB=class extends kB{constructor(e){super(e,"triangle","triangle")}},RB=class extends kB{constructor(e){super(e,"hexagon","hexagon")}},$B=class extends kB{constructor(e){super(e,"star","star")}},LB=gr("plugin-geo.api"),FB={token:LB,create:({editor:e})=>e.shapeUtils.has("geo")?(e=>({createRectangle:t=>Mc(e,"rectangle",t),createEllipse:t=>Mc(e,"ellipse",t),createRhombus:t=>Mc(e,"rhombus",t),createTriangle:t=>Mc(e,"triangle",t),createHexagon:t=>Mc(e,"hexagon",t),createStar:t=>Mc(e,"star",t)}))(e):null},OB=["rectangle","ellipse","rhombus","triangle","hexagon","star"],DB=["solid","dashed","dotted","none"],zB=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],UB=[{value:E("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:E("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:E("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:E("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],NB=[{value:E("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:E("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:E("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:E("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],WB=[{value:"solid",label:"Solid",icon:"minus"},{value:"dashed",label:"Dashed",icon:"stroke-dashed"},{value:"dotted",label:"Dotted",icon:"stroke-dotted"},{value:"none",label:"None",icon:"x"}],XB=[{value:"rectangle",label:"Rectangle",icon:"square",dataUiPrefix:"rectangle"},{value:"ellipse",label:"Ellipse",icon:"circle",dataUiPrefix:"ellipse"},{value:"rhombus",label:"Rhombus",icon:"square-rotated",dataUiPrefix:"rhombus"},{value:"triangle",label:"Triangle",icon:"triangle",dataUiPrefix:"triangle"},{value:"hexagon",label:"Hexagon",icon:"hexagon",dataUiPrefix:"hexagon"},{value:"star",label:"Star",icon:"star",dataUiPrefix:"star"}],YB={id:"geo",provides:[LB],editor:{id:"land.geo",shapeCapabilities:[{type:"geo",schemaProps:["w","h","geo","fill","stroke","strokeStyle","strokeWidth","cornerRadiusPercent"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Toolbar covers built-in geo variants through geo props."]}],shapeUtils:[new class extends DT{type="geo";getDefaultProps(){return{w:160,h:108,geo:"rectangle",fill:E("fill-slate"),stroke:E("stroke-slate"),strokeStyle:"solid",strokeWidth:2,cornerRadiusPercent:12}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,Nc(t.w,n.w)),h:Math.max(24,Nc(t.h,n.h)),geo:zc(t.geo)?t.geo:n.geo,fill:F(t.fill,n.fill),stroke:F(t.stroke,n.stroke),strokeStyle:Uc(t.strokeStyle)?t.strokeStyle:n.strokeStyle,strokeWidth:Math.max(1,Nc(t.strokeWidth,n.strokeWidth)),cornerRadiusPercent:Bc(t.cornerRadiusPercent,n.cornerRadiusPercent)}}getLocalBounds(e){return new LC(0,0,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getPositionedOutlineVertices(e){return Ec(this.getPositionedBounds(e),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}getHandleSnapGeometry(e){return{points:qc(e),outline:Kc(e)}}hitTest(e,t){const n=this.getPositionedBounds(e);switch(e.props.geo){case"ellipse":{const e=n.w/2,o=n.h/2;if(e<=0||o<=0)return!1;const i=t.x-n.center.x,r=t.y-n.center.y;return i*i/(e*e)+r*r/(o*o)<=1}case"rhombus":case"triangle":case"hexagon":case"star":return $c(t,Rc(n,e.props.geo));default:return $c(t,Rc(n,"rectangle",{cornerRadiusPercent:e.props.cornerRadiusPercent}))}}hitTestLineSegment(e,t){const n=this.getPositionedBounds(e);switch(e.props.geo){case"ellipse":return((e,t,n,o)=>{const i=e.center,r=e.w/2+o,s=e.h/2+o;if(r<=0||s<=0)return!1;const a=n.sub(t),d=t.sub(i),l=a.x/r,c=a.y/s,u=d.x/r,p=d.y/s,h=l*l+c*c,g=2*(u*l+p*c),f=u*u+p*p-1;if(f<=0)return!0;const m=g*g-4*h*f;if(0===h||m<0)return!1;const y=Math.sqrt(m),S=(-g-y)/(2*h),b=(-g+y)/(2*h);return S>=0&&S<=1||b>=0&&b<=1})(n,t.positionedStart,t.positionedEnd,t.positionedMargin);case"rectangle":case"rhombus":case"triangle":case"hexagon":case"star":{const o=Rc(n,e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent});return this.hitTest(e,t.positionedStart)||this.hitTest(e,t.positionedEnd)||((e,t,n,o)=>{if(n.length<3)return!1;for(let i=0;i<n.length;i+=1){const r=n[i],s=n[(i+1)%n.length];if(r&&s&&Yc(e,t,r,s)<=o)return!0}return!1})(t.positionedStart,t.positionedEnd,o,t.positionedMargin)}default:return super.hitTestLineSegment(e,t)}}resolveBindingPoint(e,t){const n=t.editor.computeShapePositionedToPageTransform(e),o=n.tryInvert();if(!o)return t.rawPagePoint;const i=function(e,t,n){const o=new LC(e.x,e.y,e.props.w,e.props.h);switch(e.props.geo){case"ellipse":return((e,t,n)=>{const o=e.w/2,i=e.h/2;if(o<=0||i<=0)return null;const r=t.sub(e.center),s=n.sub(t),a=s.x/o,d=s.y/i,l=r.x/o,c=r.y/i,u=a*a+d*d,p=2*(l*a+c*d),h=p*p-4*u*(l*l+c*c-1);if(0===u||h<0)return null;const g=Math.sqrt(h),f=[(-p-g)/(2*u),(-p+g)/(2*u)].filter(e=>e>1e-6&&e<=1).sort((e,t)=>e-t)[0];return void 0===f?null:t.add(s.mul(f))})(o,t,n);case"rectangle":return _c(t,n,Rc(o,e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent}));default:return _c(t,n,Rc(o,e.props.geo))}}(e,o.applyToPoint(t.rawPagePoint),o.applyToPoint(t.oppositePagePoint));return i?n.applyToPoint(i):t.rawPagePoint}}],shapeSvgExporters:[new class{type="geo";toSvg(e,t){const{geo:n,fill:o,stroke:i,strokeStyle:r,strokeWidth:s,w:a,h:d}=e.props,l="none"===r?0:s,c=l/2,u=Math.max(a-l,0),p=Math.max(d-l,0),h={fill:t.resolveColor(o),stroke:"none"===r?"none":t.resolveColor(i),"stroke-width":l,"stroke-dasharray":jc(r,s),"stroke-linejoin":"round","stroke-linecap":"round"};if("ellipse"===n)return{tag:"ellipse",attrs:{...h,cx:a/2,cy:d/2,rx:u/2,ry:p/2}};if("rectangle"!==n){const e=Rc(new LC(c,c,u,p),n).map(e=>`${Vc(e.x)},${Vc(e.y)}`).join(" ");return{tag:"polygon",attrs:{...h,points:e}}}const g=Ac({cornerRadiusPercent:e.props.cornerRadiusPercent,w:u,h:p});return{tag:"rect",attrs:{...h,x:c,y:c,width:u,height:p,rx:g,ry:g}}}}],setup(e){e.tools.register("rectangle",e=>new MB(e),{shortcut:"r"}),e.tools.register("ellipse",e=>new EB(e),{shortcut:"o"}),e.tools.register("rhombus",e=>new BB(e),{shortcut:"d"}),e.tools.register("triangle",e=>new AB(e)),e.tools.register("hexagon",e=>new RB(e)),e.tools.register("star",e=>new $B(e))}},render:{id:"land.geo.react",shapeRenderers:[{type:"geo",component:function({shape:e}){
|
|
92
|
+
return Gk(su,{shape:e})},hoverComponent:function({shape:e,strokeWidth:t}){const{geo:n,h:o,w:i}=e.props,r=Ac({cornerRadiusPercent:e.props.cornerRadiusPercent,w:i,h:o}),s="ellipse"===n||"rectangle"===n?null:Rc(new LC(0,0,i,o),n).map(e=>`${e.x},${e.y}`).join(" "),a={fill:"none",stroke:xM,strokeWidth:t,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"non-scaling-stroke"};
|
|
93
|
+
return Gk("svg",{"data-ui":"geo-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${i} ${o}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:"ellipse"===n?Gk("ellipse",{...a,cx:i/2,cy:o/2,rx:i/2,ry:o/2}):"rectangle"!==n?Gk("polygon",{...a,points:s??""}):Gk("rect",{...a,x:0,y:0,width:i,height:o,rx:r,ry:r})})}}]},setup:e=>{e.apis.add(FB),e.actions.add({id:"geo.set-kind",getAvailability:e=>"geo"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:e=>Jc(e.selection.selectedShapes),run({context:e,value:t}){if(!zc(t))return;const n=e.selection.selectedShapes.filter(Dc).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{geo:t}}));0!==n.length&&e.editor.commands.updateShapes(n,{source:"user"})}},Gc("fill"),Gc("stroke"),Gc("strokeStyle"),Gc("strokeWidth"),{id:"geo.set-cornerRadiusPercent",getAvailability:e=>"rectangle"!==Jc(e.selection.selectedShapes)?"inapplicable":e.selection.selectedShapes.some(e=>Dc(e)&&"rectangle"===e.props.geo&&!e.isLocked)?"enabled":"disabled",getValue(e){const t=(e=>{let t;for(const n of e){if(!Dc(n)||"rectangle"!==n.props.geo)continue;const e=Bc(n.props.cornerRadiusPercent);if(void 0!==t){if(t!==e)return null}else t=e}return t??null})(e.selection.selectedShapes);return null===t?null:(e=>Number(e.toFixed(2)).toString())(t)},run({context:e,value:t}){const n=eu(t);if(null===n)return;const o=Bc(n),i=e.selection.selectedShapes.filter(Dc).filter(e=>"rectangle"===e.props.geo&&!e.isLocked).map(e=>({id:e.id,props:{cornerRadiusPercent:o}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},Zc("fill"),Zc("stroke"),Zc("strokeStyle"),Zc("strokeWidth")),e.toolbar.add({id:"geo.tool-toolbar",channel:gM.toolSwitcher,order:20,actionIds:[pM],getGroups:e=>[{id:"geo.tools",items:[{kind:"segmented",id:"geo.tool-picker",actionId:pM,options:XB.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-tool-option`}))}]}]},{id:"geo.default-style.tool-toolbar",channel:gM.toolOptions,order:21,actionIds:["geo.default-fill","geo.default-stroke","geo.default-strokeStyle","geo.default-strokeWidth"],when:e=>ru(e.tool.activeToolId),getGroups:()=>Qc({fillActionId:"geo.default-fill",strokeActionId:"geo.default-stroke",strokeStyleActionId:"geo.default-strokeStyle",strokeWidthActionId:"geo.default-strokeWidth",dataUiPrefix:"geo-default"})},{id:"geo.selection-toolbar",channel:gM.selectionProperties,order:20,actionIds:["geo.set-kind","geo.set-fill","geo.set-stroke","geo.set-strokeStyle","geo.set-strokeWidth","geo.set-cornerRadiusPercent"],when:e=>"geo"===e.selection.commonShapeType,getGroups(e){const t=Jc(e.selection.selectedShapes);return[{id:"geo.shape-kind",items:[{kind:"segmented",id:"geo.shape-kind",actionId:"geo.set-kind",options:XB.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-shape-button`}))}]},...Qc({fillActionId:"geo.set-fill",strokeActionId:"geo.set-stroke",strokeStyleActionId:"geo.set-strokeStyle",strokeWidthActionId:"geo.set-strokeWidth",dataUiPrefix:"geo"}),..."rectangle"===t?[(n="geo.set-cornerRadiusPercent",o="geo",{id:`${o}.style-corner-radius-percent`,items:[{kind:"text-input",id:`${o}.corner-radius-percent`,actionId:n,label:"Corner radius %",icon:"border-corner-pill",placeholder:"0",suffix:"%",validate:tu,dataUi:`${o}-corner-radius-percent-control`}]})]:[]];var n,o}})}},HB=2*Math.PI,_B=1e-9,KB=new WeakMap,qB=l("plugin.packaging.runtime"),jB="land.packaging.artworkSide",VB={lineWidth:.5,holeFill:B("#ffffff"),cutStroke:B("#a3a3a3"),creaseStroke:B("#a3a3a3"),bleedStroke:B("#b8b8b8"),safeZoneStroke:B("#b8b8b8"),annotationStroke:B("#d4d4d4"),canvasBoundsMarkColor:B("#d4d4d4")},GB=new Set(["mm","cm","m","in","pt","px","unitless"]),ZB=new Set(["cut","crease","perforation","score","half-cut","kiss-cut","annotation","construction","custom"]),QB=["outside","inside"],JB=1e-8,eA=new WeakSet,tA=Vu({schemaVersion:1,id:"packaging:empty",revision:"empty",name:"Packaging",unit:"unitless",coordinateSystem:"top-left-y-down",points:[],edges:[],faces:[],surfaces:{outside:{},inside:{}}}),nA=12,oA=1e-4,iA=new Set(["cut","half-cut","kiss-cut"]),rA=new Set(["crease","perforation","score"]),sA=new Set(["annotation","construction","custom"]),aA=new Set(["cut","half-cut","kiss-cut"]),dA=new Set(["crease","perforation","score"]),lA=new Set(["annotation","construction","custom"]),cA=72,uA={cut:{color:[0,1,0,0]},"half-cut":{color:[.45,1,0,0]},"kiss-cut":{color:[0,1,.75,0]},crease:{color:[1,0,0,0],dashArrayPoints:[6,2]},perforation:{color:[1,0,1,0],dashArrayPoints:[2,2]},score:{color:[1,.55,0,0],dashArrayPoints:[6,2]},annotation:{color:[0,0,0,.55],dashArrayPoints:[3,2]},construction:{color:[0,0,0,.3],dashArrayPoints:[2,2]},custom:{color:[0,0,0,.8]}},pA={color:[0,.9,.75,0],dashArrayPoints:[4,2]},hA={color:[.75,0,.8,0],dashArrayPoints:[3,2]},gA=2*Math.PI,fA=1e-6,mA=1e-6,yA=new Set(["LINE","ARC","CIRCLE","ELLIPSE","LWPOLYLINE","POLYLINE"]),SA=gr("plugin-packaging.api"),bA={token:SA,create:({editor:e})=>e.shapeUtils.has("packaging")?(e=>{const t=t=>{const n=Gu(Vu(t.document)),o=e.getDefaultShapeProps("packaging"),i=t.viewSide??o.viewSide,[r]=e.commands.createShapes([{type:"packaging",x:t.x,y:t.y,scaleX:"inside"===i?-1:1,meta:t.meta?{...t.meta}:void 0,props:{...o,document:n,viewSide:i,faceFill:t.faceFill??o.faceFill,faceFillOverrides:t.faceFillOverrides?{...t.faceFillOverrides}:o.faceFillOverrides,showBleed:t.showBleed??o.showBleed,clipToBleed:t.clipToBleed??o.clipToBleed,dielineOnTop:t.dielineOnTop??o.dielineOnTop,showSafeZones:t.showSafeZones??o.showSafeZones,showCanvasBoundsMarks:t.showCanvasBoundsMarks??o.showCanvasBoundsMarks}}],{source:"user"});return wh(r)?{id:r.id,type:r.type}:null};return{create:t,importDxf(n){const o=qp(n.source,{...n.options,fileName:n.fileName}),i=au(o,"outside").bounds,r=e.viewportPageBoundsSignal.get()?.center??e.screenToPage(new $C(360,240)),s=n.pagePoint?new $C(n.pagePoint.x,n.pagePoint.y):r,a=t({x:s.x-i.center.x,y:s.y-i.center.y,document:o,meta:{importedFrom:"dxf"}});return a&&e.commands.setSelectedShapeIds([a.id],{source:"user"}),a},updateDocument({packagingId:t,document:n,expectedRevision:o}){const i=e.getShape(t);if(!wh(i)||void 0!==o&&i.props.document.revision!==o)return null;const r=Gu(Vu(n));e.commands.updateShapes([{id:i.id,props:{document:r}}],{source:"user"});const s=e.getShape(i.id);return wh(s)?{id:s.id,type:s.type}:null},getDocument(t){const n=e.getShape(t);return wh(n)?Gu(n.props.document):null},async exportPdf({packagingId:t,options:n={}}){const o=e.getShape(t);if(!wh(o))return null;const i=n.side??o.props.viewSide;return async function(e,t={}){const n=Vu(e),o=t.side??"outside",i=t.includeBleed??!0,r=t.includeSafeZones??!1,s=t.includeAnnotations??!0,a=Wp(n.unit,t.unitlessPointsPerUnit),d=Hp(t.lineWidthPoints,.25,"Packaging PDF line width"),l=au(n,o),c=[...l.edgesById.values()].filter(({edge:e})=>!1!==e.visible&&(s||"annotation"!==e.operation&&"construction"!==e.operation)),u=(({document:e,geometry:t,visibleEdges:n,includeBleed:o,includeSafeZones:i,margin:r})=>{if(e.sheetBounds)return{...e.sheetBounds};const s=n.map(({bounds:e})=>e);if(o&&s.push(...[...t.bleedContoursById.values()].map(e=>e.bounds)),i&&s.push(...[...t.safeZonesById.values()].map(e=>e.bounds)),0===s.length)return{x:0,y:0,w:0,h:0};const a=Math.min(...s.map(e=>e.minX))-r,d=Math.min(...s.map(e=>e.minY))-r;return{x:a,y:d,w:Math.max(...s.map(e=>e.maxX))+r-a,h:Math.max(...s.map(e=>e.maxY))+r-d}})({document:n,geometry:l,visibleEdges:c,includeBleed:i,includeSafeZones:r,margin:_p(t.marginInDocumentUnits,Yp(n.unit,a),"Packaging PDF margin")});if(!(u.w>0&&u.h>0))throw new Error("Cannot export an empty Packaging document to PDF.");const p=u.w*a,h=u.h*a,g=await import("./es-DocrZgUh.mjs"),f=await g.PDFDocument.create();f.setTitle(`${n.name} dieline`),f.setSubject(`Packaging dieline (${o})`),f.setCreator("Land"),f.setProducer("Land Packaging PDF exporter"),f.setKeywords(["packaging","dieline",o,n.unit]);const m=f.addPage([p,h]),y={x:-u.x*a,y:h+u.y*a};t.mirror&&m.pushOperators(g.pushGraphicsState(),g.translate(p,0),g.scale(-1,1));for(const S of c)Xp({page:m,path:S.path,style:uA[S.edge.operation],pathOrigin:y,pointsPerUnit:a,lineWidthPoints:d,pdfLib:g});if(i)for(const S of l.bleedContoursById.values())Xp({page:m,path:S.path,style:pA,pathOrigin:y,pointsPerUnit:a,lineWidthPoints:d,pdfLib:g});if(r)for(const S of l.safeZonesById.values())Xp({page:m,path:S.path,style:hA,pathOrigin:y,pointsPerUnit:a,lineWidthPoints:d,pdfLib:g});return t.mirror&&m.pushOperators(g.popGraphicsState()),{bytes:await f.save(),filename:Kp(n.name,o),side:o,page:{width:u.w,height:u.h,unit:n.unit,widthPoints:p,heightPoints:h}}}(o.props.document,{includeBleed:o.props.showBleed,includeSafeZones:o.props.showSafeZones,...n,side:i,mirror:n.mirror??"inside"===i})},attachShapes({packagingId:t,shapeIds:n}){const o=e.getShape(t);if(!wh(o))return[];const i=Array.from(new Set(n)).filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked&&!n.isHidden&&e.canUseShapeParent(o.id,n.id)});return 0===i.length?[]:e.commands.reparentShapes({ids:i,parentId:o.id},{source:"user"})?i:[]},detachShapes({packagingId:t,shapeIds:n,destinationPageId:o}){const i=e.getShape(t),r=wh(i)?e.getShapePageId(i.id):null,s=o??r;if(!wh(i)||!s||!e.getPage(s))return[];const a=Array.from(new Set(n)).filter(t=>{const n=e.getShape(t);return!!n&&n.parentId===i.id&&!n.isLocked&&!n.isHidden});return 0===a.length?[]:e.commands.reparentShapes({ids:a,parentId:s},{source:"user"})?a:[]},hitTestFace({packagingId:t,pagePoint:n}){const o=e.getShape(t);if(!wh(o))return null;const i=e.computeShapeLocalToPageTransform(o).tryInvert();if(!i)return null;const r=i.applyToPoint(new $C(n.x,n.y)),s=pu(au(o.props.document,o.props.viewSide),r);if(!s)return null;const a=function(e,t){const n=e.artworkFrame?.uvToDocument;if(!n)return null;const o=yu(n);return o?((e,t)=>new $C(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5]))(o,t):null}(s.face,r);return{faceId:s.face.id,localPoint:{x:r.x,y:r.y},faceUv:a?{x:a.x,y:a.y}:null}},getCoveredFaces({packagingId:t,shapeId:n}){const o=e.getShape(t),i=e.getShape(n);if(!wh(o)||!i)return[];const r=e.getShapePageId(o.id),s=e.getShapePageId(i.id);if(!r||!s||r!==s)return[];const a=e.computeShapeLocalToPageTransform(o).tryInvert();if(!a)return[];let d=e.getShapePageOutlineVertices(i.id);if(0===d.length){const t=e.getShapePageBounds(i.id);d=t?[new $C(t.minX,t.minY),new $C(t.maxX,t.minY),new $C(t.maxX,t.maxY),new $C(t.minX,t.maxY)]:[]}return gu(au(o.props.document,o.props.viewSide),d.map(e=>a.applyToPoint(e)))}}})(e):null},xA="packaging.toggle-show-bleed",wA="packaging.toggle-clip-to-bleed",IA="packaging.toggle-show-safe-zones",PA="packaging.toggle-dieline-on-top",vA="packaging.toggle-inside-view",kA="packaging.set-background",CA=[{id:"white",value:B("#f8fafc"),label:"White",hexColor:"#f8fafc"},{id:"warm",value:B("#fefce8"),label:"Warm",hexColor:"#fefce8"},{id:"blue",value:B("#eff6ff"),label:"Blue",hexColor:"#eff6ff"},{id:"green",value:B("#f0fdf4"),label:"Green",hexColor:"#f0fdf4"},{id:"slate",value:B("#e2e8f0"),label:"Slate",hexColor:"#e2e8f0"}],TA={id:"packaging",provides:[SA],editor:{id:"land.packaging",shapeCapabilities:[{type:"packaging",schemaProps:["document","viewSide","faceFill","faceFillOverrides","showBleed","clipToBleed","dielineOnTop","showSafeZones","showCanvasBoundsMarks"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Packaging is a parentId container with side-specific artwork visibility, document-derived faces, holes, dielines, bleed contours, optional bleed clipping, safe zones, point snap geometry, transient face hover, and configurable background/descendant/foreground render and SVG export order."]}],shapeUtils:[new class extends DT{type="packaging";getDefaultProps(){return{document:tA,viewSide:"outside",faceFill:B("#f8fafc"),faceFillOverrides:Object.create(null),showBleed:!0,clipToBleed:!1,dielineOnTop:!0,showSafeZones:!1,showCanvasBoundsMarks:!0}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps(),o=Object.create(null);if(t.faceFillOverrides&&"object"==typeof t.faceFillOverrides&&!Array.isArray(t.faceFillOverrides))for(const[i,r]of Object.entries(t.faceFillOverrides))i.length>0&&$(r)&&(o[i]=r);return{document:Vu(t.document??n.document),viewSide:"inside"===t.viewSide||"outside"===t.viewSide?t.viewSide:n.viewSide,faceFill:F(t.faceFill,n.faceFill),faceFillOverrides:o,showBleed:"boolean"==typeof t.showBleed?t.showBleed:n.showBleed,clipToBleed:"boolean"==typeof t.clipToBleed?t.clipToBleed:n.clipToBleed,dielineOnTop:"boolean"==typeof t.dielineOnTop?t.dielineOnTop:n.dielineOnTop,showSafeZones:"boolean"==typeof t.showSafeZones?t.showSafeZones:n.showSafeZones,showCanvasBoundsMarks:"boolean"==typeof t.showCanvasBoundsMarks?t.showCanvasBoundsMarks:n.showCanvasBoundsMarks}}getLocalBounds(e){return Bp(e).bounds}getRenderBounds(e){return Ep(e).expand(VB.lineWidth/2)}getExportBounds(e){return this.getRenderBounds(e)}getChildClipLocalBounds(e){const t=this.getChildClipLocalPolygons(e);return t?LC.FromPoints(t.flatMap(e=>e)):null}getChildClipLocalPolygons(e){if(!e.props.clipToBleed)return null;const t=[...Bp(e).bleedContoursById.values()].map(e=>e.samples).filter(e=>e.length>=3);return t.length>0?t:null}getChildExportClipLocalPolygons(e){return this.getChildClipLocalPolygons(e)}getPositionedOutlineVertices(e){const t=Bp(e).bounds;return[new $C(e.x+t.minX,e.y+t.minY),new $C(e.x+t.maxX,e.y+t.minY),new $C(e.x+t.maxX,e.y+t.maxY),new $C(e.x+t.minX,e.y+t.maxY)]}getSelectionFramePositionedOutlineVertices(e){const t=Bp(e).outerBounds.expand(VB.lineWidth/2);return[new $C(e.x+t.minX,e.y+t.minY),new $C(e.x+t.maxX,e.y+t.minY),new $C(e.x+t.maxX,e.y+t.maxY),new $C(e.x+t.minX,e.y+t.maxY)]}getBoundsSnapGeometry(e){return{points:Bp(e).snapPoints}}canReceiveChildren(e){return!0}canReceiveChild(e,t){return"frame"!==t.type&&"packaging"!==t.type}isChildVisible(e,t){return(ju(t)??"outside")===e.props.viewSide}getChildPlacementMeta(e,t,n){const o=ju(t);return"create"===n.reason&&o?t.meta:((e,t)=>ju(e)===t?e.meta:{...e.meta,[jB]:t})(t,e.props.viewSide)}canSnapChildrenToSelf(e){return!0}shouldRotateDescendants(e){return!0}getAllowedSelectionResizeModes(e,t){return bT}canParticipateInSelectionRotation(e,t){return!1}resizeSelectionBounds(e,t){const n=this.getLocalBounds(e).center;return{id:e.id,x:t.pageCenter.x-n.x,y:t.pageCenter.y-n.y,rotation:t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,scaleX:e.scaleX*t.scaleX,scaleY:e.scaleY*t.scaleY}}canSelectByBrush(e,t){return t.isWrapping?this.isWrappedByBrush(e,t):this.doesBrushIntersectFace(e,t)}hitTest(e,t,n){const o=new $C(t.x-e.x,t.y-e.y);return!!pu(Bp(e),o)}hitTestLineSegment(e,t){return((e,t,n,o=0)=>{const i=Math.max(0,o)+.05,r=LC.FromPoints([t,n]).expand(i),s=i*i+_B;for(const a of e.spatialIndex.searchBounds(r)){const o=e.facesById.get(a);if(o){if(hu(t,o)||hu(n,o))return!0;for(const e of[o.outer,...o.holes])for(let o=0;o<e.length;o+=1)if(Nu(t,n,e[o],e[(o+1)%e.length])<=s)return!0}}return!1})(Bp(e),new $C(t.positionedStart.x-e.x,t.positionedStart.y-e.y),new $C(t.positionedEnd.x-e.x,t.positionedEnd.y-e.y),t.positionedMargin)}doesBrushIntersectFace(e,t){const n=t.editor.computeShapeLocalToPageTransform(e).tryInvert();if(!n)return!1;const o=[new $C(t.brushBounds.minX,t.brushBounds.minY),new $C(t.brushBounds.maxX,t.brushBounds.minY),new $C(t.brushBounds.maxX,t.brushBounds.maxY),new $C(t.brushBounds.minX,t.brushBounds.maxY)].map(e=>n.applyToPoint(e));return gu(Bp(e),o).length>0}}],shapeSvgExporters:[new class{type="packaging";toSvg(e,t){const n=au(e.props.document,e.props.viewSide),o=[...n.facesById.values()].map(n=>({tag:"path",attrs:{d:n.outerPath,fill:t.resolveColor(Ap(e,n.face.id)),stroke:"none","data-packaging-face-id":n.face.id}}));return e.props.dielineOnTop||o.push(...zp(n,t)),{tag:"g",attrs:{"data-packaging-layer":"background"},children:o}}toSvgForeground(e,t){const n=au(e.props.document,e.props.viewSide),o=[];for(const r of n.facesById.values())for(const e of r.holePaths)o.push({tag:"path",attrs:{d:e,fill:t.resolveColor(VB.holeFill),stroke:"none","data-packaging-hole-fill":!0}});const i=[...n.edgesById.values()].filter(e=>!1!==e.edge.visible);return e.props.showBleed&&n.bleedContoursById.size>0&&o.push({tag:"g",attrs:{"data-packaging-layer":"bleed-contours"},children:[...n.bleedContoursById.values()].map(e=>({tag:"path",attrs:{d:e.path,...Np(t,VB.bleedStroke,VB.lineWidth),"data-packaging-guide":"bleed","data-packaging-bleed-contour-id":e.source.id,"data-packaging-minimum-bleed":e.source.minimumBleed}}))}),e.props.showSafeZones&&n.safeZonesById.size>0&&o.push({tag:"g",attrs:{"data-packaging-layer":"safe-zones"},children:[...n.safeZonesById.values()].map(e=>({tag:"path",attrs:{d:e.path,...Np(t,VB.safeZoneStroke,VB.lineWidth),"stroke-dasharray":"1 3","stroke-linecap":"round","data-packaging-guide":"safe-zone","data-packaging-safe-zone-id":e.source.id,"data-packaging-face-id":e.source.faceId,"data-packaging-minimum-clearance":e.source.minimumClearance}}))}),e.props.dielineOnTop&&o.push(...zp(n,t,i)),{tag:"g",attrs:{"data-packaging-layer":"foreground","pointer-events":"none"},children:o}}}],interactionHandlers:[{id:"land.packaging.interactions",editorEvent:{handleEvent(e,t){const n=qu(e);return"cancel"===t.type?(n.clear(),"continue"):"pointer"!==t.type?"continue":"pointer_cancel"===t.name?(n.clear(),"continue"):("pointer_move"!==t.name&&"pointer_down"!==t.name&&"pointer_up"!==t.name||n.setHover(((e,t)=>{const n=e.getCurrentPageShapeIds();for(let o=n.length-1;o>=0;o-=1){const i=e.getShape(n[o]);if(!Dp(i)||e.isShapeHidden(i.id))continue;const r=e.computeShapeLocalToPageTransform(i).tryInvert();if(!r)continue;const s=r.applyToPoint(t.pagePoint),a=pu(au(i.props.document,i.props.viewSide),s);if(a)return{packagingShapeId:i.id,faceId:a.face.id}}return null})(e,t)),"continue")}}}],setup(e){const t=(()=>{const e=a("packaging.hover",null);return{hoverSignal:e,setHover(t){const n=e.get();n?.packagingShapeId===t?.packagingShapeId&&n?.faceId===t?.faceId||e.set(t?{...t}:null)},clear(){null!==e.get()&&e.set(null)}}})();return e.runtime.provide(qB,t,e=>e.clear()),e.listen(({diff:e})=>{const n=t.hoverSignal.get();n&&(e.removed.some(e=>e.id===n.packagingShapeId)||e.updated.some(({before:e,after:t})=>e.id===n.packagingShapeId||t.id===n.packagingShapeId))&&t.clear()})}},render:{id:"land.packaging.react",shapeRenderers:[{type:"packaging",component:function({shape:e,editor:t}){const n=au(e.props.document,e.props.viewSide),o=Ep(e,n).expand(VB.lineWidth/2),i=Ir(t.cameraZoomSignal),r=Lp(VB.lineWidth,i),s=[...n.edgesById.values()].filter(e=>!1!==e.edge.visible);
|
|
94
|
+
return Zk("svg",{"data-ui":"packaging-background",width:"100%",height:"100%",viewBox:Op(o),style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:[[...n.facesById.values()].map(t=>Gk("path",{"data-packaging-face-id":t.face.id,d:t.outerPath,fill:O(Ap(e,t.face.id)),stroke:"none"},t.face.id)),e.props.dielineOnTop?null:Rp(s,n.holeEdgeIds,r)]})},foregroundComponent:function({shape:e,editor:t}){const n=au(e.props.document,e.props.viewSide),o=Ep(e,n).expand(VB.lineWidth/2),i=Ir(t.cameraZoomSignal),r=Lp(VB.lineWidth,i),s=((e,t,n)=>{const o=e.computeShapeLocalToPageTransform(t),i=Math.max(Math.hypot(o.a,o.b),oA),r=Math.max(Math.hypot(o.c,o.d),oA),s=Math.max(n,oA);return{horizontalLength:nA/(i*s),verticalLength:nA/(r*s)}})(t,e,i),a=n.dielineBounds?n.outerBounds.expand(VB.lineWidth/2):null,d=Ir(qu(t).hoverSignal),l=Ir(t.getShapeDropTargetSignal(e.id)),c=d?.packagingShapeId===e.id?d.faceId:null,u=[...n.edgesById.values()].filter(e=>!1!==e.edge.visible);
|
|
95
|
+
return Gk("svg",{"data-ui":"packaging-foreground",width:"100%",height:"100%",viewBox:Op(o),style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Zk("g",{pointerEvents:"none",children:[[...n.facesById.values()].flatMap(e=>e.holePaths.map((t,n)=>Gk("path",{"data-packaging-hole-fill":"true",d:t,fill:O(VB.holeFill),stroke:"none"},`${e.face.id}:hole-fill:${n}`))),e.props.showBleed&&n.bleedContoursById.size>0?Gk("g",{"data-packaging-layer":"bleed-contours",children:[...n.bleedContoursById.values()].map(e=>Gk("path",{"data-packaging-guide":"bleed","data-packaging-bleed-contour-id":e.source.id,"data-packaging-minimum-bleed":e.source.minimumBleed,d:e.path,...Fp(VB.bleedStroke,r)},e.source.id))}):null,e.props.showSafeZones&&n.safeZonesById.size>0?Gk("g",{"data-packaging-layer":"safe-zones",children:[...n.safeZonesById.values()].map(e=>Gk("path",{"data-packaging-guide":"safe-zone","data-packaging-safe-zone-id":e.source.id,"data-packaging-face-id":e.source.faceId,"data-packaging-minimum-clearance":e.source.minimumClearance,d:e.path,...Fp(VB.safeZoneStroke,r),strokeDasharray:"1 3",strokeLinecap:"round"},e.source.id))}):null,e.props.dielineOnTop?Rp(u,n.holeEdgeIds,r):null,e.props.showCanvasBoundsMarks?Gk("g",{"data-packaging-layer":"canvas-bounds-marks",children:fu(a,s).map((e,t)=>Gk("path",{"data-packaging-canvas-bounds-mark":"true",d:e,...Fp(VB.canvasBoundsMarkColor,r),strokeLinecap:"butt",strokeLinejoin:"miter"},`canvas-bounds-mark:${t}`))}):null,c?(()=>{const e=n.facesById.get(c);return e?Gk("path",{"data-packaging-face-hover":c,d:e.outerPath,fill:"rgba(37, 99, 235, 0.14)",stroke:"none"}):null})():null,l?Gk("path",{"data-packaging-drop-highlight":"true",d:[...n.facesById.values()].map(e=>e.outerPath).join(" "),fill:"rgba(37, 99, 235, 0.1)",stroke:"rgba(37, 99, 235, 0.96)",strokeWidth:Lp(2,i),vectorEffect:"non-scaling-stroke"}):null]})})}}]},setup:e=>{e.apis.add(bA),e.actions.add(Ih(xA,"showBleed"),Ih(wA,"clipToBleed"),Ih(IA,"showSafeZones"),Ih(PA,"dielineOnTop"),{id:vA,getAvailability:e=>"packaging"!==e.selection.commonShapeType?"inapplicable":e.selection.selectedShapes.some(e=>Ch(e)&&!e.isLocked)?"enabled":"disabled",getValue:e=>vh(e.selection.selectedShapes),run({context:e,value:t}){const n=("boolean"==typeof t?t:!0!==vh(e.selection.selectedShapes))?"inside":"outside",o=e.selection.selectedShapes.filter(Ch).filter(e=>!e.isLocked&&e.props.viewSide!==n).map(e=>({id:e.id,scaleX:-e.scaleX,props:{viewSide:n}}));o.length>0&&e.editor.commands.updateShapes(o,{source:"user"})}},{id:kA,getAvailability:e=>"packaging"!==e.selection.commonShapeType?"inapplicable":e.selection.selectedShapes.some(e=>Ch(e)&&!e.isLocked)?"enabled":"disabled",getValue:e=>(e=>{let t;for(const n of e)if(Ch(n))if(void 0===t)t=n.props.faceFill;else if(!U(t,n.props.faceFill))return null;return t??null})(e.selection.selectedShapes),run({context:e,value:t}){const n=(e=>$(e)?F(e,B("#f8fafc")):"string"==typeof e&&/^#[0-9a-f]{6}$/i.test(e)?B(e):void 0)(t);if(!n)return;const o=e.selection.selectedShapes.filter(Ch).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{faceFill:n}}));o.length>0&&e.editor.commands.updateShapes(o,{source:"user"})}}),e.toolbar.add({id:"packaging.selection-toolbar",channel:gM.selectionProperties,order:20,actionIds:[xA,wA,IA,PA,vA,kA],when:e=>"packaging"===e.selection.commonShapeType,getGroups:()=>[{id:"packaging.display",items:[{kind:"checkbox",id:xA,actionId:xA,label:"Show bleed lines",dataUi:"packaging-show-bleed-checkbox"},{kind:"checkbox",id:wA,actionId:wA,label:"Clip to bleed area",dataUi:"packaging-clip-to-bleed-checkbox"},{kind:"checkbox",id:IA,actionId:IA,label:"Show safe zones",dataUi:"packaging-show-safe-zones-checkbox"},{kind:"checkbox",id:PA,actionId:PA,label:"Dieline on top",dataUi:"packaging-dieline-on-top-checkbox"},{kind:"checkbox",id:vA,actionId:vA,label:"Inside view",dataUi:"packaging-inside-view-checkbox"}]},{id:"packaging.background",items:[{kind:"color-input",id:kA,actionId:kA,label:"Background",fallback:"#f8fafc",presets:CA.map(e=>({...e,dataUi:`packaging-background-${e.id}-button`})),dataUi:"packaging-background-color-input"}]}]})}},MA=tr("canvas-kit.tool-actions"),EA=[{id:pM,getValue:e=>e.tool.activeToolId,run({context:e,value:t}){"string"==typeof t&&e.editor.tools.hasTool(t)&&e.editor.setActiveTool(t,"system")}},{id:hM,getValue:e=>e.tool.isToolLocked,run({context:e}){e.editor.toggleToolLocked("system")}}],BA={id:"canvas-kit.tool-actions",provides:[MA],setup(e){e.actions.add(...EA),e.capabilities.provide(MA,!0)}},AA=tr("canvas-kit.import-host"),RA={id:"canvas-kit.import-host",provides:[AA],setup(e){e.capabilities.provide(AA,!0),e.ui.addComponents({id:"canvas-kit.import-host",order:50,component:Th})}},$A=fr("canvas-kit.clipboard-service"),LA="system.clipboard.copy",FA="system.clipboard.cut",OA="system.clipboard.paste",DA="system.clipboard.paste-at-point",zA=[{actionId:LA,shortcut:{key:"c",accelKey:!0}},{actionId:FA,shortcut:{key:"x",accelKey:!0}},{actionId:OA,shortcut:{key:"v",accelKey:!0}}],UA=[{id:"system.clipboard-main-menu",channel:aM.mainMenu,order:900,actionIds:[LA,FA,OA],getSections:e=>[{id:"system.edit",title:"Edit",order:10,items:[{kind:"command",id:LA,actionId:LA,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(LA),dataUi:"copy-selection-menu-button"},{kind:"command",id:FA,actionId:FA,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(FA),dataUi:"cut-selection-menu-button"},{kind:"command",id:OA,actionId:OA,label:"Paste",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(OA),dataUi:"paste-menu-button"}]}]}],NA={id:"system.selection-clipboard-context-menu",target:"selection",order:1e3,actionIds:[LA,FA],getSections:e=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:LA,actionId:LA,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(LA),dataUi:"context-menu-copy-selection-button"},{kind:"command",id:FA,actionId:FA,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(FA),dataUi:"context-menu-cut-selection-button"}]}]},WA={id:"system.canvas-clipboard-context-menu",target:"canvas",order:1e3,actionIds:[DA],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:DA,actionId:DA,label:"Paste here",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(OA),dataUi:"context-menu-paste-here-button"}]}]},XA=[NA,WA],YA={id:"canvas-kit.clipboard",provides:[$A],setup(e){var t;e.services.add({token:$A,create(){let e=null;return{async write(t){e=t},read:async()=>e,getMemoryPayload:()=>e}}}),e.actions.add(...(t=e.services,[{id:LA,getAvailability:e=>0===e.selection.count?"inapplicable":Lh(t)?"enabled":"disabled",run({context:e}){Fh({context:e,services:t})}},{id:FA,getAvailability:e=>0===e.selection.count?"inapplicable":Lh(t)?"enabled":"disabled",run({context:e}){(async({context:e,services:t})=>{await Fh({context:e,services:t})&&e.editor.deleteSelection("user")})({context:e,services:t})}},{id:OA,getAvailability:()=>Lh(t)?.getMemoryPayload()?"enabled":"inapplicable",run({context:e}){Oh({context:e,services:t})}},{id:DA,getAvailability:e=>zh(e)&&Lh(t)?.getMemoryPayload()?"enabled":"inapplicable",run({context:e}){zh(e)&&Oh({context:e,services:t,atMenuPoint:!0})}}])),e.actions.addShortcuts(...zA),e.chrome.add(...UA),e.contextMenu.add(...XA)}},HA=Fk(null),_A=Math.min,KA=Math.max,qA=Math.round,jA=Math.floor,VA=e=>({x:e,y:e}),GA={left:"right",right:"left",bottom:"top",top:"bottom"},ZA=["left","right"],QA=["right","left"],JA=["top","bottom"],eR=["bottom","top"],tR=new Set(["left","top"]),nR=/transform|translate|scale|rotate|perspective|filter/,oR=/paint|layout|strict|content/,iR=e=>!!e&&"none"!==e,rR=VA(0),sR={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:o,strategy:i}=e;const r="fixed"===i,s=dg(o),a=!!t&&fg(t.floating);if(o===s||a&&r)return n;let d={scrollLeft:0,scrollTop:0},l=VA(1);const c=VA(0),u=ug(o);if((u||!u&&!r)&&(("body"!==sg(o)||hg(s))&&(d=xg(o)),u)){const e=Eg(o);l=Tg(o),c.x=e.x+o.clientLeft,c.y=e.y+o.clientTop}const p=!s||u||r?VA(0):Ag(s,d);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-d.scrollLeft*l.x+c.x+p.x,y:n.y*l.y-d.scrollTop*l.y+c.y+p.y}},getDocumentElement:dg,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:o,strategy:i}=e;const r=[..."clippingAncestors"===n?fg(t)?[]:Lg(t,this._c):[].concat(n),o],s=Rg(t,r[0],i);let a=s.top,d=s.right,l=s.bottom,c=s.left;for(let u=1;u<r.length;u++){const e=Rg(t,r[u],i);a=KA(e.top,a),d=_A(e.right,d),l=_A(e.bottom,l),c=KA(e.left,c)}return{width:d-c,height:l-a,x:c,y:a}},getOffsetParent:zg,getElementRects:async function(e){const t=this.getOffsetParent||zg,n=this.getDimensions,o=await n(e.floating);return{reference:Fg(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=kg(e);return{width:t,height:n}},getScale:Tg,isElement:cg,isRTL:e=>"rtl"===bg(e).direction},aR=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,o;const{x:i,y:r,placement:s,middlewareData:a}=t,d=await(async(e,t)=>{const{placement:n,platform:o,elements:i}=e,r=await(null==o.isRTL?void 0:o.isRTL(i.floating)),s=jh(n),a=Vh(n),d="y"===Qh(n),l=tR.has(s)?-1:1,c=r&&d?-1:1,u=qh(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:g}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof g&&(h="end"===a?-1*g:g),d?{x:h*c,y:p*l}:{x:p*l,y:h*c}})(t,e);return s===(null==(n=a.offset)?void 0:n.placement)&&null!=(o=a.arrow)&&o.alignmentOffset?{}:{x:i+d.x,y:r+d.y,data:{...d,placement:s}}}}),dR=e=>(void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:o,placement:i,platform:r}=t,{mainAxis:s=!0,crossAxis:a=!1,limiter:d={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=qh(e,t),c={x:n,y:o},u=await r.detectOverflow(t,l),p=Qh(jh(i)),h=Gh(p);let g=c[h],f=c[p];s&&(g=Kh(g+u["y"===h?"top":"left"],g,g-u["y"===h?"bottom":"right"])),a&&(f=Kh(f+u["y"===p?"top":"left"],f,f-u["y"===p?"bottom":"right"]));const m=d.fn({...t,[h]:g,[p]:f});return{...m,data:{x:m.x-n,y:m.y-o,enabled:{[h]:s,[p]:a}}}}}),lR=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,o;const{placement:i,middlewareData:r,rects:s,initialPlacement:a,platform:d,elements:l}=t,{mainAxis:c=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:f=!0,...m}=qh(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const y=jh(i),S=Qh(a),b=jh(a)===a,x=await(null==d.isRTL?void 0:d.isRTL(l.floating)),w=p||(b||!f?[tg(a)]:(e=>{const t=tg(e);return[eg(e),t,eg(t)]})(a)),I="none"!==g;!p&&I&&w.push(...function(e,t,n,o){const i=Vh(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?QA:ZA:t?ZA:QA;case"left":case"right":return t?JA:eR;default:return[]}})(jh(e),"start"===n,o);return i&&(r=r.map(e=>e+"-"+i),t&&(r=r.concat(r.map(eg)))),r}(a,f,g,x));const P=[a,...w],v=await d.detectOverflow(t,m),k=[];let C=(null==(o=r.flip)?void 0:o.overflows)||[];if(c&&k.push(v[y]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const o=Vh(e),i=Jh(e),r=Zh(i);let s="x"===i?o===(n?"end":"start")?"right":"left":"start"===o?"bottom":"top";return t.reference[r]>t.floating[r]&&(s=tg(s)),[s,tg(s)]})(i,s,x);k.push(v[e[0]],v[e[1]])}if(C=[...C,{placement:i,overflows:k}],!k.every(e=>e<=0)){var T,M;const e=((null==(T=r.flip)?void 0:T.index)||0)+1,t=P[e];if(t&&("alignment"!==u||S===Qh(t)||C.every(e=>Qh(e.placement)!==S||e.overflows[0]>0)))return{data:{index:e,overflows:C},reset:{placement:t}};let n=null==(M=C.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:M.placement;if(!n)switch(h){case"bestFit":{var E;const e=null==(E=C.filter(e=>{if(I){const t=Qh(e.placement);return t===S||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:E[0];e&&(n=e);break}case"initialPlacement":n=a}if(i!==n)return{reset:{placement:n}}}return{}}}),cR=["bottom-start"],uR=["bottom"],pR=["bottom"],hR=[],gR=["select","hand","rectangle","ellipse","rhombus","triangle","hexagon","star","arrow","draw","path","text","frame","eraser","laser"],fR=new Set(gR),mR=gR.map(e=>`"${e}"`).join(", "),yR={audio:["src"],embed:["src"],iframe:["src"],img:["src","srcset"],input:["src"],object:["data"],script:["src"],source:["src","srcset"],track:["src"],video:["poster","src"]},SR=["href","xlink:href"],bR=new Set(["a","area"]),xR=16384,wR=67108864,IR=gr("canvas-kit.export"),PR="snapshots",vR="imageBlobs",kR=null,CR=zk(({actionRegistry:e,editor:t,executeCommand:n})=>((({actionRegistry:e,editor:t,executeCommand:n})=>{Wk(()=>{const o=o=>{if(t.getShapeEditingSession()||Zr(o.target))return;const i=t.shortcuts.getActionIdForEvent({key:o.key,shiftKey:o.shiftKey,altKey:o.altKey,ctrlKey:o.ctrlKey,metaKey:o.metaKey,accelKey:o.metaKey||o.ctrlKey});if(!i)return;const r=Ji({editor:t,selectionState:t.selectionStateSignal.get(),toolState:t.toolStateSignal.get()}),s=e.getAction(i);s&&"enabled"===Qi(s,r)&&(o.preventDefault(),o.stopPropagation(),n({commandId:i,context:r,run(){s.run({context:r,value:s.getValue?.(r)??null})}}))};return window.addEventListener("keydown",o,!0),()=>{window.removeEventListener("keydown",o,!0)}},[e,t,n])})({actionRegistry:e,editor:t,executeCommand:n}),null)),TR={id:"canvas-kit.keyboard-shortcuts",setup(e){e.ui.addComponents({id:"canvas-kit.keyboard-shortcuts",order:0,component:CR})}},MR="system.selection.delete",ER="system.selection.duplicate",BR="system.selection.select-all",AR="system.selection.reset-rotation",RR="system.selection.flip-horizontal",$R="system.selection.flip-vertical",LR="system.selection.send-to-back",FR="system.selection.send-backward",OR="system.selection.bring-forward",DR="system.selection.bring-to-front",zR="system.selection.set-opacity",UR="system.selection.align",NR="system.selection.distribute",WR=["left","horizontal-center","right","top","vertical-center","bottom"],XR=["horizontal","vertical"],YR=[{actionId:ER,shortcut:{key:"d",accelKey:!0}},{actionId:BR,shortcut:{key:"a",accelKey:!0}}],HR=[{id:ER,getAvailability:e=>e.selection.count>0?"enabled":"inapplicable",run({context:e}){e.editor.duplicateSelection({source:"user"})}},{id:BR,getAvailability:e=>e.editor.getCurrentPageShapeIds().length>0?"enabled":"disabled",run({context:e}){e.editor.selectAllCurrentPage("user")}},{id:AR,getAvailability:e=>e.selection.canResetRotation?"enabled":"inapplicable",run({context:e}){e.editor.resetSelectionRotation("user")}},{id:RR,getAvailability:e=>0===e.selection.count?"inapplicable":e.selection.canFlip?"enabled":"disabled",run({context:e}){e.editor.flipSelection("horizontal","user")}},{id:$R,getAvailability:e=>0===e.selection.count?"inapplicable":e.selection.canFlip?"enabled":"disabled",run({context:e}){e.editor.flipSelection("vertical","user")}},{id:LR,getAvailability:e=>0===e.selection.count||_f(e)?"inapplicable":e.editor.canMoveSelectionInParentOrder("backward")?"enabled":"disabled",run({context:e}){e.editor.moveSelectionToParentOrderEdge("back","user")}},{id:FR,getAvailability:e=>0===e.selection.count||_f(e)?"inapplicable":e.editor.canMoveSelectionInParentOrder("backward")?"enabled":"disabled",run({context:e}){e.editor.moveSelectionInParentOrder("backward","user")}},{id:OR,getAvailability:e=>0===e.selection.count||_f(e)?"inapplicable":e.editor.canMoveSelectionInParentOrder("forward")?"enabled":"disabled",run({context:e}){e.editor.moveSelectionInParentOrder("forward","user")}},{id:DR,getAvailability:e=>0===e.selection.count||_f(e)?"inapplicable":e.editor.canMoveSelectionInParentOrder("forward")?"enabled":"disabled",run({context:e}){e.editor.moveSelectionToParentOrderEdge("front","user")}},{id:zR,getAvailability:e=>e.selection.count>0?"enabled":"inapplicable",getValue:e=>(e=>{const[t]=e.selection.selectedShapes;if(!t)return 1;const n=Kf(t.opacity);return e.selection.selectedShapes.every(e=>Kf(e.opacity)===n)?n:null})(e),run({context:e,value:t}){if("number"!=typeof t||!Number.isFinite(t))return;const n=Kf(t),o=e.selection.selectedShapes.filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));0!==o.length&&e.editor.commands.updateShapes(o,{source:"user"})}},{id:UR,getAvailability:e=>e.selection.count<=1?"inapplicable":e.editor.canAlignSelection()?"enabled":"disabled",run({context:e,value:t}){"string"==typeof t&&(e=>WR.includes(e))(t)&&e.editor.canAlignSelection()&&e.editor.alignSelection(t,"user")}},{id:NR,getAvailability:e=>e.selection.count<=2?"inapplicable":e.editor.canDistributeSelection()?"enabled":"disabled",run({context:e,value:t}){"string"==typeof t&&(e=>XR.includes(e))(t)&&e.editor.canDistributeSelection()&&e.editor.distributeSelection(t,"user")}},{id:MR,getAvailability:e=>e.selection.count>0?"enabled":"disabled",run({context:e}){e.editor.deleteSelection("user")}}],_R=[{id:"system.selection-main-menu",channel:aM.mainMenu,order:1e3,actionIds:[ER,BR,MR],getSections:e=>[{id:"system.edit",title:"Edit",order:10,items:[{kind:"command",id:ER,actionId:ER,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(ER),dataUi:"duplicate-selection-menu-button"},{kind:"command",id:BR,actionId:BR,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(BR),dataUi:"select-all-menu-button"},{kind:"command",id:MR,actionId:MR,label:"Delete selection",icon:"trash-2",tone:"destructive",dataUi:"delete-selection-menu-button"}]}]}],KR={id:"system.selection-context-menu",target:"selection",order:1010,actionIds:[ER,AR,RR,$R,DR,OR,FR,LR],getSections(e){const t=e.selection.count>0&&!_f(e),n=[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:ER,actionId:ER,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(ER),dataUi:"context-menu-duplicate-selection-button"}]}];return(e.selection.canResetRotation||e.selection.count>0)&&n.push({id:"system.selection-transform",title:"Transform",order:20,items:[{kind:"command",id:AR,actionId:AR,label:"Reset rotation",icon:"rotate-ccw",dataUi:"context-menu-reset-rotation-button"},{kind:"command",id:RR,actionId:RR,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"context-menu-flip-horizontal-button"},{kind:"command",id:$R,actionId:$R,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"context-menu-flip-vertical-button"}]}),t&&n.push({id:"system.selection-arrange",title:"Arrange",order:30,items:[{kind:"command",id:DR,actionId:DR,label:"Bring to front",icon:"stack-front",dataUi:"context-menu-bring-to-front-button"},{kind:"command",id:OR,actionId:OR,label:"Bring forward",icon:"stack-forward",dataUi:"context-menu-bring-forward-button"},{kind:"command",id:FR,actionId:FR,label:"Send backward",icon:"stack-backward",dataUi:"context-menu-send-backward-button"},{kind:"command",id:LR,actionId:LR,label:"Send to back",icon:"stack-back",dataUi:"context-menu-send-to-back-button"}]}),n}},qR={id:"system.selection-delete-context-menu",target:"selection",order:1030,actionIds:[MR],getSections:()=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"separator",id:"system.selection.delete-leading-separator"},{kind:"command",id:MR,actionId:MR,label:"Delete selection",icon:"trash-2",tone:"destructive",dataUi:"context-menu-delete-selection-button"}]}]},jR={id:"system.canvas-selection-context-menu",target:"canvas",order:1005,actionIds:[BR],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:BR,actionId:BR,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(BR),dataUi:"context-menu-select-all-button"}]}]},VR=[KR,qR,jR],GR={id:"system.selection-toolbar",channel:gM.selectionProperties,order:1e3,actionIds:[UR,NR,AR,RR,$R,LR,FR,OR,DR,zR],getGroups(e){const t=e.selection.count>0&&!_f(e);return[{id:"system.selection-layout",presentation:"primary",items:[{kind:"segmented",id:"system.selection-align",actionId:UR,label:"Align",icon:"layout-align-left",options:[{value:"left",label:"Align left",icon:"layout-align-left",dataUi:"align-selection-left-button"},{value:"horizontal-center",label:"Align horizontal center",icon:"layout-align-center",dataUi:"align-selection-horizontal-center-button"},{value:"right",label:"Align right",icon:"layout-align-right",dataUi:"align-selection-right-button"},{value:"top",label:"Align top",icon:"layout-align-top",dataUi:"align-selection-top-button"},{value:"vertical-center",label:"Align vertical center",icon:"layout-align-middle",dataUi:"align-selection-vertical-center-button"},{value:"bottom",label:"Align bottom",icon:"layout-align-bottom",dataUi:"align-selection-bottom-button"}]},{kind:"segmented",id:"system.selection-distribute",actionId:NR,label:"Distribute",icon:"distribute-horizontal",options:[{value:"horizontal",label:"Distribute horizontally",icon:"distribute-horizontal",dataUi:"distribute-selection-horizontal-button"},{value:"vertical",label:"Distribute vertically",icon:"distribute-vertical",dataUi:"distribute-selection-vertical-button"}]}]},{id:"system.selection-opacity",presentation:"overflow",items:[{kind:"slider",id:"system.selection-opacity",actionId:zR,label:"Opacity",min:0,max:1,step:.01,dataUi:"selection-opacity-slider"}]},{id:"system.selection-actions",presentation:"overflow",items:[...e.selection.canResetRotation?[{kind:"button",id:AR,actionId:AR,label:e.selection.isMixedFrameAndPointHandleSelection?"Reset shape rotation":"Reset rotation",icon:"rotate-ccw",dataUi:"reset-selection-rotation-button"},{kind:"separator",id:"system.selection.reset-delete-separator"}]:[],{kind:"button",id:RR,actionId:RR,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"flip-selection-horizontal-button"},{kind:"button",id:$R,actionId:$R,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"flip-selection-vertical-button"},...t?[{kind:"separator",id:"system.selection.flip-order-separator"},{kind:"button",id:LR,actionId:LR,label:"Send to back",icon:"stack-back",dataUi:"send-selection-to-back-button"},{kind:"button",id:FR,actionId:FR,label:"Send backward",icon:"stack-backward",dataUi:"send-selection-backward-button"},{kind:"button",id:OR,actionId:OR,label:"Bring forward",icon:"stack-forward",dataUi:"bring-selection-forward-button"},{kind:"button",id:DR,actionId:DR,label:"Bring to front",icon:"stack-front",dataUi:"bring-selection-to-front-button"}]:[]]}]}},ZR={id:"system.selection-delete-toolbar",channel:gM.selectionProperties,order:1020,actionIds:[MR],getGroups:()=>[{id:"system.selection-delete",presentation:"overflow",items:[{kind:"separator",id:"system.selection.delete-leading-separator"},{kind:"button",id:MR,actionId:MR,label:"Delete selection",icon:"trash-2",dataUi:"delete-selection-toolbar-button"}]}]},QR=[GR,ZR],JR={id:"canvas-kit.selection",setup(e){e.actions.add(...HR),e.actions.addShortcuts(...YR),e.chrome.add(..._R),e.toolbar.add(...QR),e.contextMenu.add(...VR)}},e$={id:"system.canvas-tool-context-menu",target:"canvas",order:1020,actionIds:[pM],getSections:e=>[{id:"system.canvas-tools",title:"Tools",order:20,items:[{kind:"command",id:"system.canvas.select-tool",actionId:pM,value:"select",label:"Select tool",icon:"mouse-pointer-2",shortcut:e.editor.shortcuts.getToolShortcutLabel("select"),dataUi:"context-menu-select-tool-button"},{kind:"command",id:"system.canvas.hand-tool",actionId:pM,value:"hand",label:"Hand tool",icon:"hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),dataUi:"context-menu-hand-tool-button"}]}]},t$=[e$],n$={id:"system.select-tool-toolbar",channel:gM.toolSwitcher,order:0,actionIds:[pM],getGroups:e=>[{id:"system.select-tool",items:[{kind:"button",id:"system.select-tool",actionId:pM,value:"select",label:"Select",shortcut:e.editor.shortcuts.getToolShortcutLabel("select"),icon:"mouse-pointer-2",dataUi:"select-tool-button"},{kind:"button",id:"system.hand-tool",actionId:pM,value:"hand",label:"Hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),icon:"hand",dataUi:"hand-tool-button"}]}]},o$={id:"system.tool-lock-toolbar",channel:gM.toolSwitcher,order:1e3,actionIds:[hM],getGroups:e=>[{id:"system.tool-lock",items:[{kind:"separator",id:"system.tool-lock-separator"},{kind:"button",id:"system.tool-lock",actionId:hM,value:!0,label:e.tool.isToolLocked?"Unlock tool":"Lock tool",icon:"lock",dataUi:"tool-lock-button"}]}]},i$=[n$,o$],r$={id:"canvas-kit.tool",requires:[MA],setup(e){e.toolbar.add(...i$),e.contextMenu.add(...t$)}},s$="system.view.zoom-in",a$="system.view.zoom-out",d$="system.view.reset-zoom",l$=[{id:s$,run({context:e}){e.editor.zoomAtViewportCenter(-120,"system")}},{id:a$,run({context:e}){e.editor.zoomAtViewportCenter(120,"system")}},{id:d$,run({context:e}){e.editor.resetZoom("user")}}],c$=[{id:"system.view-main-menu",channel:aM.mainMenu,order:2e3,actionIds:[s$,a$,d$],getSections:()=>[{id:"system.view",title:"View",order:20,items:[{kind:"command",id:s$,actionId:s$,label:"Zoom in",icon:"plus",dataUi:"zoom-in-menu-button"},{kind:"command",id:a$,actionId:a$,label:"Zoom out",icon:"minus",dataUi:"zoom-out-menu-button"},{kind:"command",id:d$,actionId:d$,label:"Reset zoom",icon:"rotate-ccw",dataUi:"reset-zoom-menu-button"}]}]}],u$=[{id:"system.canvas-view-context-menu",target:"canvas",order:1010,actionIds:[s$,a$,d$],getSections:()=>[{id:"system.canvas-view",title:"View",order:10,items:[{kind:"command",id:s$,actionId:s$,label:"Zoom in",icon:"plus",dataUi:"context-menu-zoom-in-button"},{kind:"command",id:a$,actionId:a$,label:"Zoom out",icon:"minus",dataUi:"context-menu-zoom-out-button"},{kind:"command",id:d$,actionId:d$,label:"Reset zoom",icon:"rotate-ccw",dataUi:"context-menu-reset-zoom-button"}]}]}],p$={id:"canvas-kit.view",setup(e){e.actions.add(...l$),e.chrome.add(...c$),e.contextMenu.add(...u$)}},h$={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}},g$=((e,t,n,o)=>{const i=Dk(({color:t="currentColor",size:n=24,stroke:i=2,title:r,className:s,children:a,...d},l)=>Ok("svg",{ref:l,...h$[e],width:n,height:n,className:["tabler-icon","tabler-icon-arrow-right",s].join(" "),strokeWidth:i,stroke:t,...d},[r&&Ok("title",{key:"svg-title"},r),...o.map(([e,t])=>Ok(e,t)),...Array.isArray(a)?a:[a]]));return i.displayName="ArrowRight",i})("outline",0,0,[["path",{d:"M5 12l14 0",key:"svg-0"}],["path",{d:"M13 18l6 -6",key:"svg-1"}],["path",{d:"M13 6l6 6",key:"svg-2"}]]),f$=.001,m$="border:",y$=new WeakMap,S$=.4,b$=1e-6,x$="connector.curve-waypoint",w$="connector.curve-insert",I$="connector.orthogonal-segment",P$=l("plugin.connector.runtime"),v$=zk(()=>{const e=wr(),t=Ir(e.toolStateSignal).activeToolId;Ir(e.selectedShapesSignal),Ir(e.hoveredShapeIdSignal);const n=Ir(e.shapeEditingSessionSignal),o=Ir(e.inputs.isSpacePressed),i=Ir(e.selectionTranslationActiveSignal),r=Ir(e.cameraZoomSignal),s=Py(e),a=Ir(s.previewSignal);if(n||o||i)return null;const d=Qy(e),l=new Map(d.visibleShapes.map(e=>[e.id,e])),c=d.targetShapeId?e.getShape(d.targetShapeId)??null:null,u=a?c:"connector"===t?d.visibleShapes[0]:null,p=u&&!qf(u)?u:null;if(0===l.size&&!a?.isDragging)return null;const h=Math.max(r,1e-4),g=d.targetShapeId&&d.highlightedPortId?`${d.targetShapeId}:${d.highlightedPortId}`:null,f=a?{point:a.start.pagePoint,outwardNormal:a.start.pageOutwardNormal,obstacleId:a.start.shapeId??void 0,obstacleBounds:a.start.obstacleBounds}:null,m=a?{point:a.end.pagePoint,outwardNormal:a.end.pageOutwardNormal,obstacleId:a.end.shapeId??void 0,obstacleBounds:a.end.obstacleBounds}:null,y=a?.isDragging?Ym({start:f,end:m,routing:a.geometry.routing,cornerRadius:a.geometry.cornerRadius,headStart:a.geometry.headStart,headEnd:a.geometry.headEnd,strokeWidth:a.geometry.strokeWidth,curveWaypoints:a.geometry.curveWaypoints,orthogonalBends:a.geometry.orthogonalBends,terminalOffsetMapper:zm(a.geometry.localToPageTransform)}):null,S=a&&y?((e,t)=>{const n=e.geometry.localToPageTransform,o=n.tryInvert();if(!o)return{info:t,localToPageTransform:FC.Identity()};const i=ly(t,o);if("rebind"===e.kind)return{info:i,localToPageTransform:n};const r=LC.FromPoints([i.startPagePoint,...i.points,i.endPagePoint]);return{info:ly(i,FC.Translate(-r.x,-r.y)),localToPageTransform:n.compose(FC.Translate(r.x,r.y))}})(a,y):null,b=a?.isDragging?a.start.pagePoint:null,x=a?.isDragging?a.end.pagePoint:null,w=a?O(a.geometry.stroke):"var(--land-selection, #2563eb)",I=a?.geometry.strokeWidth??2,P=a?.geometry.strokeStyle??"solid",v=p?hS(e,p):null,k=a?a[a.movingTerminal]:null;
|
|
96
|
+
return Zk("g",{"data-ui":"connector-ports-overlay",children:[
|
|
97
|
+
Gk("style",{children:"\n [data-connector-port-idle],\n [data-connector-port-hover-preview] {\n transition: opacity 100ms ease;\n }\n [data-connector-port-hover-preview] {\n opacity: 0;\n }\n [data-connector-port]:hover [data-connector-port-idle] {\n opacity: 0;\n }\n [data-connector-port]:hover [data-connector-port-hover-preview] {\n opacity: 1;\n }\n "}),v?Gk("path",{"data-ui":"connector-target-border-highlight",d:v,fill:"none",stroke:xM,strokeWidth:2/h,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"}):null,S?Gk("g",{"data-ui":"connector-creation-preview",pointerEvents:"none",opacity:.78,children:Zk("g",{"data-ui":"connector-creation-preview-geometry",transform:S.localToPageTransform.toSvgString(),children:[Gk("path",{"data-ui":"connector-creation-preview-path",d:S.info.path,fill:"none",stroke:w,strokeWidth:I,strokeDasharray:"dashed"===P?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round"}),S.info.markerSegments.length>0?Gk("path",{"data-ui":"connector-creation-preview-markers",d:S.info.markerSegments.map(e=>`M ${e.start.x} ${e.start.y} L ${e.end.x} ${e.end.y}`).join(" "),fill:"none",stroke:w,strokeWidth:I,strokeLinecap:"round",strokeLinejoin:"round"}):null]})}):null,[...l.values()].flatMap(t=>Ci(e,t).map(n=>Gk(lS,{editor:e,shape:t,port:n,zoom:h,highlighted:g===`${t.id}:${n.id}`,targetMode:p?.id===t.id,quickCreateNodeFactory:s.quickCreateNodeFactory},`${t.id}:${n.id}`))),k?.shapeId?Gk(aS,{point:k.pagePoint,zoom:h}):!a&&"connector"===t&&p?Gk(sS,{shape:p,zoom:h}):null,b&&x?Gk(dS,{start:b,end:x,zoom:h}):null]})}),k$=class extends eT{type="connector";getDefaultProps(){return{terminal:"start",portId:"top"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=t.normalizedAnchor&&"object"==typeof t.normalizedAnchor?t.normalizedAnchor:null;return{terminal:"end"===t.terminal?"end":"start",portId:"string"==typeof t.portId&&t.portId.length>0?t.portId:"top",...n?{normalizedAnchor:{x:gS(n.x),y:gS(n.y)}}:{}}}canBind(e,t,n){return qf(n.fromShape)&&!qf(n.toShape)&&e.getShapePageId(n.fromShape.id)===e.getShapePageId(n.toShape.id)&&null!==Im(e,n.toShape,t.props)}getExclusiveBindingKey(e){return`${e.fromId}:${e.props.terminal}`}onBindingCreate(e,t){return this.getSyncEffect(e,t.fromId)}onBindingUpdate(e,t,n){return this.getSyncEffect(e,n.fromId)}onBindingLoad(e,t){return this.getSyncEffect(e,t.fromId)}onAfterShapeChange(e,t,n){if("from"!==n.role||"start"===t.props.terminal)return this.getSyncEffect(e,t.fromId)}onBeforeDeleteShape(e,t,n){return"from"===n.role?{deleteBindingIds:Gf(e,t.fromId).map(e=>e.id)}:e.getShape(t.fromId)?{deleteShapeIds:[t.fromId]}:{}}onBeforeDeleteBinding(e,t){return this.getDetachEffect(e,t)}getExportShapeIds(e,t){return[t.fromId]}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}getSyncEffect(e,t){const n=e.getShape(t);if(!qf(n))return;const o=My(e,n);var i,r;return!o||(i=n).parentId===(r=o).parentId&&i.x===r.x&&i.y===r.y&&i.rotation===r.rotation&&i.skewX===r.skewX&&i.scaleX===r.scaleX&&i.scaleY===r.scaleY&&JSON.stringify(i.props)===JSON.stringify(r.props)?void 0:{shapes:[o],suppressBindingIds:Gf(e,t).map(e=>e.id)}}getDetachEffect(e,t){const n=e.getShape(t.fromId);if(!qf(n))return{deleteBindingIds:[t.id]};const o=Um(e,n),i=Ey(e,n,t.props.terminal,"start"===t.props.terminal?o.startPagePoint:o.endPagePoint);return{shapes:i?[i]:void 0,deleteBindingIds:[t.id],suppressBindingIds:Gf(e,t.fromId).map(e=>e.id)}}},C$="connector.rebind",T$=class{editor;origin;quickCreateNodeFactory;pointerId;originScreenPoint;preview;initialSelectedShapeIds;props;didClearSelection=!1;operation;constructor(e,t,n,o,i){this.editor=e,this.origin=t,this.quickCreateNodeFactory=i,this.pointerId=o,this.originScreenPoint=n.clone(),this.initialSelectedShapeIds=e.getSelectedShapeIds(),this.props=e.getDefaultShapeProps("connector");const r=ky(e,t.start);if(!r)throw new Error("Connector creation requires a resolvable start endpoint");const s=ky(e,{kind:"free",pagePoint:r.pagePoint.clone()});this.preview={kind:"create",origin:t.kind,start:yS(r,s,"start"),end:yS(s,r,"end"),invalidReason:null,isDragging:!1,movingTerminal:"end",geometry:PS(this.props,bS(e,r,s))},this.operation=e.operations.begin({kind:"connector.create",label:"shape.create",source:"user",history:"record"}),Py(e).setPreview(this.preview)}update(e,t,n){const o=this.originScreenPoint.dist(e)>4;o&&!this.didClearSelection&&(this.initialSelectedShapeIds.length>0&&this.editor.commands.setSelectedShapeIds([],{source:"user"}),this.didClearSelection=!0);const i=o&&!n?_y(this.editor,t,{allowInteriorShapeId:"bound"===this.origin.start.kind?this.origin.start.shapeId:void 0,mode:"target",pageId:this.editor.getCurrentPageId()}):null,r=ky(this.editor,this.origin.start);if(!r)return void this.cancel("command");const s=SS(this.editor,r,t,this.props.routing,n),a=i?vy(i.shape.id,i.port):{kind:"free",pagePoint:s},d=ky(this.editor,a);if(!d)return void this.cancel("command");const l=Cy(this.editor,this.origin.start,a);Object.assign(this.preview,{start:yS(r,d,"start"),end:yS(d,r,"end"),invalidReason:l,isDragging:o,geometry:{...this.preview.geometry,localToPageTransform:bS(this.editor,r,d)}}),Py(this.editor).setPreview({...this.preview})}complete(e,t,n){if(this.update(e,t,n),Py(this.editor).pointerSession!==this)return;let o=!1;if(this.preview.isDragging)this.preview.invalidReason||(o=!!Ty(this.editor,{start:this.preview.start.draft,end:this.preview.end.draft,props:this.props,selectionAfter:"connector"}));else if("quick-connect"===this.origin.clickBehavior){const e=ky(this.editor,this.origin.start);o=!!(e?.shape&&e.port&&function(e,t,n,o){const i=Ky(e,t,n);return!!i&&("connect"===i.kind?!!Ty(e,{start:vy(t.shape.id,t.port),end:vy(i.target.shape.id,i.target.port),props:o,selectionAfter:[i.target.shape.id]}):((e,t,n,o)=>{const i=e.commands.createShapes([n.nodeInput],{source:"user",autoReparent:!1})[0];if(!i)return!1;const r=qy(e,i,t.port);return r&&!!Ty(e,{start:vy(t.shape.id,t.port),end:vy(i.id,r),props:o,selectionAfter:[i.id]})||(e.commands.deleteShapes([i.id],{source:"user"}),!1)})(e,t,i,o))}(this.editor,{shape:e.shape,port:e.port},this.quickCreateNodeFactory,this.props))}this.clear(),o?(this.operation.commit(),"canvas"!==this.origin.kind||this.editor.isToolLocked()||this.editor.commands.setActiveTool("select",{source:"system"})):(this.operation.cancel(),this.restoreInitialSelection())}cancel(e){this.clear(),this.operation.isActive&&this.operation.cancel(),this.restoreInitialSelection()}clear(){const e=Py(this.editor);e.setPreview(null),e.setPointerSession(null),this.editor.setHoveredShapeId(null)}restoreInitialSelection(){this.didClearSelection&&this.editor.commands.setSelectedShapeIds(this.initialSelectedShapeIds,{source:"system"})}},M$=new Set(["straight","orthogonal","curved"]),E$=new Set(["solid","dashed"]),B$=new Set(["none","arrow"]),A$=class extends DT{type="connector";getDefaultProps(){return{w:1,h:1,start:{x:0,y:.5},end:{x:1,y:.5},routing:"orthogonal",stroke:E("stroke-slate"),strokeWidth:2,strokeStyle:"solid",headStart:"none",headEnd:"arrow",cornerRadius:8,curveWaypoints:[],orthogonalBends:[]}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:vS(t.w,n.w,1),h:vS(t.h,n.h,1),start:kS(t.start,n.start),end:kS(t.end,n.end),routing:M$.has(t.routing)?t.routing:n.routing,stroke:$(t.stroke)?F(t.stroke,n.stroke):n.stroke,strokeWidth:vS(t.strokeWidth,n.strokeWidth,.5),strokeStyle:E$.has(t.strokeStyle)?t.strokeStyle:n.strokeStyle,headStart:B$.has(t.headStart)?t.headStart:n.headStart,headEnd:B$.has(t.headEnd)?t.headEnd:n.headEnd,cornerRadius:vS(t.cornerRadius,n.cornerRadius,0),curveWaypoints:CS(t.curveWaypoints),orthogonalBends:CS(t.orthogonalBends)}}getLocalBounds(e){const t="arrow"===e.props.headStart||"arrow"===e.props.headEnd?Bm(e.props.strokeWidth)+e.props.strokeWidth/2:e.props.strokeWidth/2;return new LC(0,0,e.props.w,e.props.h).expand(t)}getPointHitTestBounds(e,t){const n=Math.max(8,e.props.strokeWidth+4);if(!t?.editor)return LC.FromPoints([new $C(e.x+e.props.start.x,e.y+e.props.start.y),new $C(e.x+e.props.end.x,e.y+e.props.end.y)]).expand(n);const o=Um(t.editor,e),i=[...o.points,...o.markerSegments.flatMap(e=>[e.start,e.end])],r=t.editor.computeShapePositionedToPageTransform(e).tryInvert();if(!r||0===i.length)return super.getPointHitTestBounds(e,t).expand(n);const s=MS(t.editor,e)*r.getMaximumLinearScale();return LC.FromPoints(i.map(e=>r.applyToPoint(e))).expand(s)}canSnap(){return!1}canParticipateInSelectionResize(e,t){return!1===t.isOnlyAffectedShape}resizeSelectionBounds(e,t){const n=this.getLocalToPageTransform(e),o=n.applyToPoint(this.getSelectionResizeLocalBounds(e).center),i=FC.Translate(t.pageCenter.x,t.pageCenter.y).compose(FC.Rotate(t.selectionRotation)).compose(FC.Scale(t.scaleX,t.scaleY)).compose(FC.Rotate(-t.selectionRotation)).compose(FC.Translate(-o.x,-o.y)).compose(n),r=i.applyToPoint(new $C(e.props.start.x,e.props.start.y)),s=i.applyToPoint(new $C(e.props.end.x,e.props.end.y)),a=e.props.curveWaypoints.map(e=>i.applyToPoint(new $C(e.x,e.y))),d=e.props.orthogonalBends.map(e=>i.applyToPoint(new $C(e.x,e.y))),l=Ym({start:TS(r,s,"start"),end:TS(s,r,"end"),routing:e.props.routing,cornerRadius:e.props.cornerRadius,headStart:e.props.headStart,headEnd:e.props.headEnd,strokeWidth:e.props.strokeWidth,curveWaypoints:a,orthogonalBends:d}),c=LC.FromPoints([r,...l.points,s]),u=e=>({x:e.x-c.x,y:e.y-c.y});return{id:e.id,x:c.x,y:c.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{w:Math.max(1,c.w),h:Math.max(1,c.h),start:u(r),end:u(s),curveWaypoints:a.map(u),orthogonalBends:d.map(u)}}}canParticipateInSelectionFlip(){return!0}canParticipateInSelectionRotation(){return!1}canParticipateInSelectionTranslation(){return!1}contributesToSelectionFrame(e,t){return!0}canUseSelectionResizeHandles(e,t){return t.editor.getSelectedShapeIds().length>1}canUseSelectionRotateHandle(e,t){return t.editor.getSelectedShapeIds().length>1}canStartTranslateFromSelectionBounds(e,t){return t.editor.getSelectedShapeIds().length>1}getSelectionHandleAnchors(e,t){if(!t.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};if(Py(t.editor).selectionHandlesHiddenSignal.get())return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};const n=Um(t.editor,e),o=[];if("curved"===e.props.routing){for(let t=1;t<n.routePoints.length-1;t+=1)o.push({kind:"custom",type:x$,id:by(t-1),point:n.routePoints[t],cursor:"move"});let e=0;n.segments.forEach(t=>{var n;"cubic"===t.type&&(o.push({kind:"custom",type:w$,id:(n=e,`segment:${n}`),point:$m(t,.5),cursor:"move"}),e+=1)})}else if("orthogonal"===e.props.routing){const e=Math.max(t.editor.cameraZoomSignal.get(),1e-4);for(let t=0;t<n.routePoints.length-1;t+=1){const i=n.routePoints[t],r=n.routePoints[t+1];if(i.dist(r)*e<36)continue;const s=i.y===r.y?"horizontal":"vertical";o.push({kind:"custom",type:I$,id:xy(t,s),point:$C.Med(i,r),cursor:"horizontal"===s?"ns-resize":"ew-resize"})}}return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.startPagePoint},{kind:"binding_terminal",terminal:"end",point:n.endPagePoint}],middleHandleAnchors:[],customHandleAnchors:o}}getSelectionOverlayInfo(e,t){const n=Um(t.editor,e),o=Xm(t.editor,e),i=hy(o.markerSegments),r=t.editor.computeShapeLocalToPageTransform(e);return{usesSelectionPathOverlay:!0,startPagePoint:n.startPagePoint,endPagePoint:n.endPagePoint,middlePagePoint:null,path:n.path,pathStyle:{localPath:o.path,localDecorationPaths:i?[i]:[],localBounds:o.pageBounds,localToPage:r,strokeWidth:e.props.strokeWidth,strokeDasharray:"dashed"===e.props.strokeStyle?"8 6":void 0},pageClipPath:Pi({outputBounds:n.pageBounds,cutoutLocalPolygons:t.editor.getShapeContentCutoutLocalPolygonsSignal(e.id).get(),localToOutput:r}),bindingSegments:[]}}getLabelPathGeometry(e,t){return function(e){const t=(e=>{const t=[];let n=null,o=0;return e.forEach((e,i)=>{const r="cubic"===e.type?32:"quadratic"===e.type?16:1;for(let s=0;s<=r;s+=1){const a=s/r,d=$m(e,a);n&&(o+=n.dist(d)),t.push({point:d,distance:o,segmentIndex:i,segmentPosition:a}),n=d}}),t})(e.segments),n=t[t.length-1]?.distance??0;return{length:n,defaultPosition:.5,getPointAt:o=>((e,t,n,o)=>{const i=t[0];if(!i)return e.startPagePoint.clone();if(n<=b$)return i.point.clone();const r=n*o;for(let s=1;s<t.length;s+=1){const n=t[s-1],o=t[s];if(o.distance<r)continue;const i=o.distance-n.distance;if(i<=b$)continue;const a=Math.max(0,Math.min(1,(r-n.distance)/i));if(n.segmentIndex!==o.segmentIndex)return n.point.add(o.point.sub(n.point).mul(a));const d=e.segments[n.segmentIndex];return d?$m(d,n.segmentPosition+(o.segmentPosition-n.segmentPosition)*a):n.point.add(o.point.sub(n.point).mul(a))}return t[t.length-1].point.clone()})(e,t,n,Dm(o)),getNearestPosition:(o,i)=>((e,t,n,o,i)=>{const r=Dm(i);if(n<=b$)return r;let s=r,a=1/0;for(let d=1;d<t.length;d+=1){const i=t[d-1],l=t[d],c=l.point.sub(i.point),u=c.len2();if(u<=b$*b$)continue;const p=Math.max(0,Math.min(1,ay(o.sub(i.point),c)/u)),h=i.segmentIndex===l.segmentIndex?e.segments[i.segmentIndex]:null,g=h?Lm(h,o,i.segmentPosition,l.segmentPosition,p):0,f=h?(g-i.segmentPosition)/Math.max(b$,l.segmentPosition-i.segmentPosition):p,m=h?$m(h,g):i.point.add(c.mul(p)),y=(i.distance+(l.distance-i.distance)*f)/n,S=m.dist2(o),b=S<a-1e-8,x=Math.abs(S-a)<=1e-8&&Math.abs(y-r)<Math.abs(s-r);(b||x)&&(a=S,s=y)}return Dm(s)})(e,t,n,o,i?.hintPosition??.5)}}(Um(t.editor,e))}canCopyToClipboard(e,t){const n=Vf(t.editor,e.id);return(!n.start||t.copiedShapeIds.has(n.start.toId))&&(!n.end||t.copiedShapeIds.has(n.end.toId))}isWrappedByBrush(e,t){return Um(t.editor,e).points.every(e=>t.brushBounds.containsPoint(e))}hitTest(e,t,n){const o=n?.editor?Um(n.editor,e):null,i=o?o.points:[new $C(e.x+e.props.start.x,e.y+e.props.start.y),new $C(e.x+e.props.end.x,e.y+e.props.end.y)],r=n?.pagePoint??t,s=n?.editor?MS(n.editor,e):Math.max(8,e.props.strokeWidth+4);return ES(i,r)<=s||(o?.markerSegments.some(e=>ES([e.start,e.end],r)<=s)??!1)}hitTestLineSegment(e,t){const n=t.editor?Um(t.editor,e):null,o=n?n.points:[new $C(e.x+e.props.start.x,e.y+e.props.start.y),new $C(e.x+e.props.end.x,e.y+e.props.end.y)],i=t.editor?t.pageStart:t.positionedStart,r=t.editor?t.pageEnd:t.positionedEnd,s=t.editor?Math.max(MS(t.editor,e),t.pageMargin):Math.max(e.props.strokeWidth+4,t.positionedMargin);for(let a=1;a<o.length;a+=1)if(AS(o[a-1],o[a],i,r)<=s)return!0;for(const a of n?.markerSegments??[])if(AS(a.start,a.end,i,r)<=s)return!0;return!1}},R$=class extends zT{constructor(e){super(e,"connector")}},$$=class{type="connector";toSvg(e,t){const n=t.resolveColor(e.props.stroke),o=Xm(t.editor,e),i=Pi({outputBounds:o.pageBounds,cutoutLocalPolygons:t.editor.getShapeContentCutoutLocalPolygonsSignal(e.id).get()}),r=i?t.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"path",attrs:{d:i,"clip-rule":"evenodd","fill-rule":"evenodd"}}]}):void 0,s="arrow"===e.props.headStart&&o.startArrowScale>0?`url(#${t.addDef(RS("start",n,e.props.strokeWidth,o.startArrowScale))})`:void 0,a="arrow"===e.props.headEnd&&o.endArrowScale>0?`url(#${t.addDef(RS("end",n,e.props.strokeWidth,o.endArrowScale))})`:void 0;return{tag:"path",attrs:{d:o.path,fill:"none",stroke:n,"stroke-width":e.props.strokeWidth,"stroke-dasharray":"dashed"===e.props.strokeStyle?"8 6":void 0,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":s,"marker-end":a,"clip-path":r?`url(#${r})`:void 0}}}},L$=[{value:E("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:E("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:E("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:E("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],F$=[{value:"straight",label:"Straight",icon:"connector-straight"},{value:"orthogonal",label:"Orthogonal",icon:"connector-orthogonal"},{value:"curved",label:"Curved",icon:"connector-curved"}],O$=[{value:"solid",label:"Solid",icon:"minus"},{value:"dashed",label:"Dashed",icon:"stroke-dashed"}],D$=[{value:"both",label:"Both ends",icon:"arrows-horizontal"},{value:"start",label:"Start",icon:"arrow-narrow-left"},{value:"end",label:"End",icon:"arrow-narrow-right"},{value:"none",label:"None",icon:"minus"}],z$=["connector.set-routing","connector.set-stroke","connector.set-strokeWidth","connector.set-strokeStyle","connector.set-direction"],U$=["connector.default-routing","connector.default-stroke","connector.default-strokeWidth","connector.default-strokeStyle","connector.default-direction"],N$=((e={})=>{return{id:"connector",requires:[YB],editor:(t=e.quickCreateNodeFactory??{createNode({editor:e,sourceShape:t,pageCenter:n,parentId:o}){const i=Gy(e,t),r=o.startsWith("shape:")?e.getShape(o):null,s=(r?e.computeShapeLocalToPageTransform(r):FC.Identity()).tryInvert()?.applyToPoint(n)??n;return{type:"geo",parentId:o,x:s.x-i.w/2,y:s.y-i.h/2,rotation:0,props:{...i}}}},{id:"land.connector",shapeCapabilities:[{type:"connector",schemaProps:["w","h","start","end","routing","stroke","strokeWidth","strokeStyle","headStart","headEnd","cornerRadius","curveWaypoints","orthogonalBends"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Endpoints can remain free or snap to ports through connector binding records."]}],shapeUtils:[new A$],shapeSvgExporters:[new $$],bindingUtils:[new k$],interactionHandlers:[fS(t)],setup(e){e.runtime.provide(P$,((e,t)=>{const n=a("connector.preview",null),o=a("connector.selectionHandlesHidden",!1);let i=null;return{previewSignal:n,quickCreateNodeFactory:t,selectionHandlesHiddenSignal:o,get pointerSession(){return i},setPointerSession(t){i=t,e.runtime.notify()},setPreview(t){n.set(t),e.runtime.notify()},setSelectionHandlesHidden(t){o.get()!==t&&(o.set(t),e.runtime.notify())},dispose(){i?.cancel("dispose"),i=null,n.set(null),o.set(!1)}}})(e,t),e=>e.dispose()),e.tools.register("connector",e=>new R$(e))}}),render:{id:"land.connector.react",shapeRenderers:[{type:"connector",component:oS,hoverComponent:iS}],selectionCustomHandleRenderers:[{type:x$,component:eS},{type:w$,component:tS},{type:I$,component:nS}],canvasOverlays:[{id:"land.connector.ports-overlay",layer:"above-host",order:100,component:v$}]},setup:$S};var t})(),W$=.08,X$=new WeakMap,Y$=new WeakMap,H$=new WeakMap,_$=class extends zT{constructor(e){super(e,"draw"),this.initial="idle",this.addChild(new K$(e,this)),this.addChild(new q$(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("draw")}},K$=class extends zT{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.parent.getDefaultProps(),n=((e,t)=>{const n=e.getCurrentPageId();let o=null,i=1/0,r=-1;const s=e.getCurrentPageShapeIds();for(let a=0;a<s.length;a+=1){const n=e.getShape(s[a]);if(!n||e.isShapeHidden(n.id))continue;const d=e.getShapeUtil(n);if(!d.canAutomaticallyReceiveChildren(n))continue;if(!e.canUseShapeParent(n.id))continue;if(!e.isPagePointInShapeClip(n.id,t))continue;const l=d.getChildClipLocalBounds(n)??d.getLocalBounds(n),c=e.computeShapeLocalToPageTransform(n).invert().applyToPoint(t);if(!l.containsPoint(c))continue;const u=e.computeShapePageBounds(n),p=u.w*u.h;(!o||p<i||p===i&&a>r)&&(o=n,i=p,r=a)}return o?.id??n})(this.editor,e.pagePoint),o=n.startsWith("shape:")?this.editor.getShape(n):null,i=o?this.editor.computeShapeLocalToPageTransform(o).invert():FC.Identity(),r=i.applyToPoint(e.pagePoint),s=Fb(r,r,e.pressure,"pen"===e.pointerType);var a,d;this.transition("drawing",{originPagePoint:e.pagePoint.clone(),originParentPoint:r,pageToParent:i,parentId:n,shapeId:null,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,isClosed:t.isClosed,isPen:"pen"===e.pointerType,pointGuard:(a=t.strokeWidth,d="pen"===e.pointerType,d?{minPointDistance:Math.max(.12,.08*a),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.3,.14*a),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),pointGuardState:{anchorPoint:Ob(s),hasProvisionalPoint:!1},straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[s]}]})}},q$=class extends zT{tool;info=null;pendingUpdateFrame=null;operation=null;constructor(e,t){super(e,"drawing",t),this.tool=t}onEnter(e){this.info=e,this.editor.clearSelectionTransients(),this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.operation=this.editor.operations.begin({kind:"draw.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(e){this.appendPoint(e,!1)}onPointerUp(e){this.appendPoint(e,!0),this.flushShapeUpdate();const t=this.info?.shapeId??null;if(!t)return this.cancelOperation(),void this.transition("idle");this.info?.parentId.startsWith("shape:")||Pe(this.editor,t,{source:"user"}),this.commitOperation(),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.cancelOperation(),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.cancelOperation(),this.info=null}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}appendPoint(e,t){if(!this.info)return;const n=Fb(this.info.pageToParent.applyToPoint(e.pagePoint),this.info.originParentPoint,e.pressure,this.info.isPen);if(e.shiftKey?this.appendStraightSegmentPoint(n):(this.exitStraightSegmentMode(),this.info.preserveStraightEndpointOnNextFreePoint?this.appendDistinctCurrentPoint(n)&&(this.info.preserveStraightEndpointOnNextFreePoint=!1):this.appendGuardedCurrentPoint(n,{force:t})),this.splitCurrentSegmentAtLimit(),!this.info.shapeId){const n=this.info.originPagePoint.dist(e.pagePoint);if(!t&&n<2)return;const o=this.createShape();return void(this.info.shapeId=o.id)}this.scheduleShapeUpdate()}scheduleShapeUpdate(){var e;null===this.pendingUpdateFrame&&(this.pendingUpdateFrame=(e=()=>{this.pendingUpdateFrame=null,this.flushShapeUpdate()},"function"==typeof requestAnimationFrame?{type:"animation",id:requestAnimationFrame(e)}:{type:"timeout",id:setTimeout(e,16)}))}cancelScheduledShapeUpdate(){var e;null!==this.pendingUpdateFrame&&("animation"!==(e=this.pendingUpdateFrame).type?clearTimeout(e.id):cancelAnimationFrame(e.id),this.pendingUpdateFrame=null)}flushShapeUpdate(){this.cancelScheduledShapeUpdate(),this.info?.shapeId&&this.editor.commands.updateShapes([{id:this.info.shapeId,props:Ub(this.info.segments)}],{source:"user"})}createShape(){const e=this.tool.getDefaultProps(),t=((e,t)=>t&&e.canUseShapeParent(t)?t:e.getCurrentPageId())(this.editor,this.info?.parentId);this.info&&(this.info.parentId=t);const[n]=this.editor.commands.createShapes([{type:"draw",x:this.info?.originParentPoint.x??0,y:this.info?.originParentPoint.y??0,...t.startsWith("shape:")?{parentId:t}:{},props:{...e,stroke:this.info?.stroke??e.stroke,strokeWidth:this.info?.strokeWidth??e.strokeWidth,fill:this.info?.fill??e.fill,isClosed:this.info?.isClosed??e.isClosed,...Ub(this.info?.segments??[]),isPen:this.info?.isPen??!1}}],{source:"user"});if(!n||"draw"!==n.type)throw new Error("Failed to create draw shape");return n}appendStraightSegmentPoint(e){if(!this.info)return;this.info.preserveStraightEndpointOnNextFreePoint=!1;const t=Db(this.info),n=t[t.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return this.replaceCurrentSegmentPoints([{...e,segment:"straight"}]),void this.resetPointGuard(e);this.info.straightSegmentAnchorPoint=Ob(n)}const o={...e,segment:"straight"};if("straight"===n?.segment)return this.replaceCurrentSegmentPoints([...t.slice(0,-1),o]),void this.resetPointGuard(o);this.replaceCurrentSegmentPoints([...t,o]),this.resetPointGuard(o)}exitStraightSegmentMode(){this.info?.straightSegmentAnchorPoint&&(this.info.straightSegmentAnchorPoint=null,this.info.preserveStraightEndpointOnNextFreePoint=!0)}appendDistinctCurrentPoint(e){if(!this.info)return!1;const t=Db(this.info),n=t[t.length-1];return!(n&&(o=n).x===(i=e).x&&o.y===i.y&&o.pressure===i.pressure&&o.segment===i.segment||(this.replaceCurrentSegmentPoints([...t,Ob(e)]),this.resetPointGuard(e),0));var o,i}appendGuardedCurrentPoint(e,t={}){if(!this.info)return;const n=Db(this.info).map(Ob);this.info.pointGuardState=function(e,t,n,o,i={}){const r=qS(t),s=e[e.length-1];if(!s)return e.push(r),{anchorPoint:qS(r),hasProvisionalPoint:!1};if(_S(s,r))return i.force&&o.hasProvisionalPoint?{anchorPoint:qS(r),hasProvisionalPoint:!1}:o;if(_S(o.anchorPoint,r))return o.hasProvisionalPoint&&e.pop(),{anchorPoint:qS(o.anchorPoint),hasProvisionalPoint:!1};const a=((e,t)=>{if(e<=t.softMaxPointCount)return t.minPointDistance;const n=YS((e-t.softMaxPointCount)/Math.max(t.hardMaxPointCount-t.softMaxPointCount,1),0,1);return t.minPointDistance*(1+n*t.maxDistanceMultiplier)})(e.length,n),d=r.x-o.anchorPoint.x,l=r.y-o.anchorPoint.y,c=Math.abs((r.pressure??0)-(o.anchorPoint.pressure??0)),u=!0===i.force||d*d+l*l>=a*a||c>=n.pressureDeltaThreshold;return o.hasProvisionalPoint?e[e.length-1]=r:e.push(r),u?{anchorPoint:qS(r),hasProvisionalPoint:!1}:{anchorPoint:qS(o.anchorPoint),hasProvisionalPoint:!0}}(n,e,this.info.pointGuard,this.info.pointGuardState,t),this.replaceCurrentSegmentPoints(n)}resetPointGuard(e){this.info&&(this.info.pointGuardState={anchorPoint:Ob(e),hasProvisionalPoint:!1})}replaceCurrentSegmentPoints(e){if(!this.info)return;const t=zb(this.info.segments);this.info.segments=[...t.slice(0,-1),{points:e.map(Ob)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const e=HS(this.info.isPen);let t=zb(this.info.segments),n=t[t.length-1];for(;n.points.length>e;){const o=n.points.slice(0,e).map(Ob),i=o[o.length-1],r=n.points.slice(e).map(Ob);if(!i||0===r.length)break;const s={points:[Ob(i),...r]};t=[...t.slice(0,-1),{points:o},s],n=s}this.info.segments=t}},j$=[{id:"slate",value:E("stroke-slate"),label:"Slate",hexColor:"#334155"},{id:"blue",value:E("stroke-blue"),label:"Blue",hexColor:"#1d4ed8"},{id:"green",value:E("stroke-green"),label:"Green",hexColor:"#15803d"},{id:"red",value:E("stroke-red"),label:"Red",hexColor:"#dc2626"},{id:"orange",value:E("stroke-orange"),label:"Orange",hexColor:"#ea580c"},{id:"muted",value:E("stroke-muted"),label:"Muted",hexColor:"#94a3b8"}],V$=[{id:"none",value:B("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:E("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:E("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:E("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:E("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],G$=[{value:"open",label:"Open"},{value:"closed",label:"Closed"}],Z$={id:"draw",editor:{id:"land.draw",shapeCapabilities:[{type:"draw",schemaProps:["segments","stroke","strokeWidth","fill","isClosed","isPen"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Draw stores raw segments as document truth and derives a shared freehand stroke geometry for render, hit test, brush wrap, and SVG export."]}],shapeUtils:[new class extends DT{type="draw";getDefaultProps(){return{segments:(e=[{x:0,y:0},{x:24,y:12}],[{points:e.map(qS)}]),stroke:E("stroke-slate"),strokeWidth:4,fill:B("transparent"),isClosed:!1,isPen:!1};var e}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{segments:jb(t.segments,n.segments),stroke:F(t.stroke,n.stroke),strokeWidth:Math.max(4,_b(t.strokeWidth,n.strokeWidth)),fill:F(t.fill,n.fill),isClosed:"boolean"==typeof t.isClosed?t.isClosed:n.isClosed,isPen:"boolean"==typeof t.isPen?t.isPen:n.isPen}}getPositionedBounds(e){const t=Bb(e);return new LC(e.x+t.localBounds.x,e.y+t.localBounds.y,t.localBounds.w,t.localBounds.h)}getLocalBounds(e){return Bb(e).localBounds}getRenderBounds(e){return Bb(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}canReceiveTerminalBinding(e){return!0}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=function(e,t){let n=(({segments:e,strokeWidth:t,isPen:n,isClosed:o,targetSelectionStrokeBounds:i})=>{let r=ob(e);for(let s=0;s<2;s+=1){const e=Tb(r,t,n,o),s=Eb(e.pointBounds,e.localBounds,i);r=lb(r,e.pointBounds,s)}return r})({segments:ub($b(e),t),strokeWidth:e.props.strokeWidth,isPen:e.props.isPen??!1,isClosed:e.props.isClosed,targetSelectionStrokeBounds:t.targetSelectionStrokeBounds});return t.scaleX<0&&(n=hb(n,{axis:"horizontal",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),t.scaleY<0&&(n=hb(n,{axis:"vertical",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),Ab(pb(n,t),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed)}(e,{targetSelectionStrokeBounds:t.selectionLocalBounds,scaleX:t.scaleX,scaleY:t.scaleY,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter});return{id:e.id,x:n.x,y:n.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{segments:Lb(n.segments)}}}flipSelectionBounds(e,t){const n=((e,t)=>Ab(pb(hb(ub($b(e),t),t),t),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed))(e,{axis:t.axis,selectionMirrorBounds:t.selectionBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter});return{id:e.id,x:n.x,y:n.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{segments:Lb(n.segments)}}}getSelectionOverlayInfo(e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null}}isWrappedByBrush(e,t){return t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){if(this.isWrappedByBrush(e,t))return!0;if(t.isWrapping)return!1;const n=t.pageOutlineVertices;return!!n.some(e=>t.brushBounds.containsPoint(e))||(e=>{const t=new $C(e.minX,e.minY),n=new $C(e.maxX,e.minY),o=new $C(e.maxX,e.maxY),i=new $C(e.minX,e.maxY);return[[t,n],[n,o],[o,i],[i,t]]})(t.brushBounds).some(([e,t])=>{for(let o=0;o<n.length;o+=1){const i=n[o],r=n[(o+1)%n.length];if(i&&r&&I(e,t,i,r))return!0}return!1})}getPositionedOutlineVertices(e){return Rb(e).outlineVertices}hitTest(e,t){return function(e,t,n,o={}){if(o.isClosed&&void 0!==o.fill&&!z(o.fill)&&e.normalizedPoints.length>=3&&Xb(n,e.normalizedPoints.map(KS)))return!0;if(o.isClosed&&((e,t)=>{if(0===t.length)return Number.POSITIVE_INFINITY;if(1===t.length)return e.dist(KS(t[0]));let n=Number.POSITIVE_INFINITY;for(let o=1;o<t.length;o+=1){const i=t[o-1],r=t[o];i&&r&&(n=Math.min(n,Nb(e,KS(i),KS(r))))}return t.length>=3&&(n=Math.min(n,Nb(e,KS(t[t.length-1]),KS(t[0])))),n})(n,e.normalizedPoints)<=Math.max(4,.5*t))return!0;if(0===e.outlineVertices.length)return!1;for(const i of e.outlinePolygons){if(Xb(n,i))return!0;if(Yb(n,i)<=Math.max(4,.5*t))return!0}return!1}(Rb(e),e.props.strokeWidth,t,{fill:e.props.fill,isClosed:e.props.isClosed})}hitTestLineSegment(e,t){return((e,t,n,o,i={})=>{const r=Math.max(4,.5*t,i.margin??0);return!!(i.isClosed&&void 0!==i.fill&&!z(i.fill)&&e.normalizedPoints.length>=3&&Hb(n,o,e.normalizedPoints.map(KS),r))||0!==e.outlineVertices.length&&e.outlinePolygons.some(e=>Hb(n,o,e,r))})(Rb(e),e.props.strokeWidth,t.positionedStart,t.positionedEnd,{fill:e.props.fill,isClosed:e.props.isClosed,margin:t.positionedMargin})}repairLoadedShape(e){return null}}],shapeSvgExporters:[new class{type="draw";toSvg(e,t){const n=Bb(e);if(!n.path&&!n.selectionPath)return null;const o=[];return n.fillPath&&!z(e.props.fill)&&o.push({tag:"path",attrs:{d:n.fillPath,fill:t.resolveColor(e.props.fill),stroke:"none"}}),e.props.isClosed&&n.selectionPath?o.push({tag:"path",attrs:{d:n.selectionPath,fill:"none",stroke:t.resolveColor(e.props.stroke),"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}):n.path&&o.push({tag:"path",attrs:{d:n.path,fill:t.resolveColor(e.props.stroke),stroke:"none"}}),{tag:"g",children:o}}}],setup(e){e.tools.register("draw",e=>new _$(e),{shortcut:"p"})}},render:{id:"land.draw.react",shapeRenderers:[{type:"draw",component:function({shape:e}){
|
|
98
|
+
return Gk(ox,{shape:e})},hoverComponent:function({shape:e,strokeWidth:t}){
|
|
99
|
+
return Gk(ix,{shape:e,strokeWidth:t})}}]},setup:e=>{e.actions.add({id:"draw.set-closed",getAvailability:e=>"draw"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:e=>Qb(e.selection.selectedShapes),run({context:e,value:t}){const n=Jb(t);if(null===n)return;const o=e.selection.selectedShapes.filter(Vb).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{isClosed:n}}));0!==o.length&&e.editor.commands.updateShapes(o,{source:"user"})}},Gb("fill"),Gb("stroke"),Gb("strokeWidth"),{id:"draw.default-closed",getAvailability:e=>"draw"===e.tool.activeToolId?"enabled":"inapplicable",getValue:e=>e.editor.getDefaultShapeProps("draw").isClosed?"closed":"open",run({context:e,value:t}){const n=Jb(t);null!==n&&e.editor.updateDefaultShapeProps("draw",{isClosed:n})}},Zb("fill"),Zb("stroke"),Zb("strokeWidth")),e.toolbar.add({id:"draw.tool-toolbar",channel:gM.toolSwitcher,order:45,actionIds:[pM],getGroups:e=>[{id:"draw.tools",items:[{kind:"button",id:"draw.tool.draw",actionId:pM,value:"draw",label:"Draw",shortcut:e.editor.shortcuts.getToolShortcutLabel("draw"),icon:"pencil",dataUi:"draw-tool-button"}]}]},{id:"draw.default-style.tool-toolbar",channel:gM.toolOptions,order:46,actionIds:["draw.default-stroke","draw.default-strokeWidth"],when:e=>"draw"===e.tool.activeToolId,getGroups:()=>(({strokeActionId:e,strokeWidthActionId:t,dataUiPrefix:n})=>[{id:`${n}.initial-style`,items:[{kind:"color-input",id:`${n}.stroke`,actionId:e,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:j$.map(e=>({...e,dataUi:`${n}-stroke-${e.id}-button`})),dataUi:`${n}.stroke`},{kind:"separator",id:`${n}.initial-style-separator`},{kind:"text-input",id:`${n}.stroke-width`,actionId:t,label:"Stroke width",placeholder:"4",suffix:"Px",validate:nx,dataUi:`${n}-stroke-width-control`}]}])({strokeActionId:"draw.default-stroke",strokeWidthActionId:"draw.default-strokeWidth",dataUiPrefix:"draw-default"})},{id:"draw.selection-toolbar",channel:gM.selectionProperties,order:20,actionIds:["draw.set-closed","draw.set-fill","draw.set-stroke","draw.set-strokeWidth"],when:e=>"draw"===e.selection.commonShapeType,getGroups:()=>(({closedActionId:e,fillActionId:t,strokeActionId:n,strokeWidthActionId:o,dataUiPrefix:i})=>[{id:`${i}.style-closed`,items:[{kind:"segmented",id:`${i}.closed`,actionId:e,options:G$.map(e=>({...e,dataUi:`${i}-${e.value}-button`}))}]},{id:`${i}.style-fill`,items:[{kind:"color-input",id:`${i}.fill`,actionId:t,label:"Fill",fallback:"#f8fafc",presets:V$.map(e=>({...e,dataUi:`${i}-fill-${e.id}-button`})),dataUi:`${i}.fill`}]},{id:`${i}.style-stroke`,items:[{kind:"color-input",id:`${i}.stroke`,actionId:n,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:j$.map(e=>({...e,dataUi:`${i}-stroke-${e.id}-button`})),dataUi:`${i}.stroke`}]},{id:`${i}.style-stroke-width`,items:[{kind:"text-input",id:`${i}.stroke-width`,actionId:o,label:"Stroke width",placeholder:"4",suffix:"Px",validate:nx,dataUi:`${i}-stroke-width-control`}]}])({closedActionId:"draw.set-closed",fillActionId:"draw.set-fill",strokeActionId:"draw.set-stroke",strokeWidthActionId:"draw.set-strokeWidth",dataUiPrefix:"draw"})}),e.contextMenu.add({id:"draw.shape-context-menu",target:"selection",order:35,actionIds:["draw.set-closed"],when:e=>"draw"===e.selection.commonShapeType,getSections(e){const t="closed"===Qb(e.selection.selectedShapes)?"open":"closed";return[{id:"draw.context-menu",title:"Draw",items:[{kind:"command",id:"draw.toggle-closed",actionId:"draw.set-closed",value:t,label:"closed"===t?"Close freehand":"Open freehand",icon:"pencil",dataUi:"context-menu-toggle-draw-closed-button"}]}]}})}},Q$=l("plugin.eraser.runtime"),J$=class extends zT{constructor(e){super(e,"eraser"),this.initial="idle",this.addChild(new eL(e,this)),this.addChild(new tL(e,this)),this.addChild(new nL(e,this))}onExit(){fx(this.editor)}},eL=class extends zT{constructor(e,t){super(e,"idle",t)}onEnter(){fx(this.editor)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={originPagePoint:t.pagePoint.clone(),previousPagePoint:t.pagePoint.clone(),protectedContainerIds:dx(e,t.pagePoint),erasingShapeIds:new Set,trail:[t.pagePoint.clone()]};return ux(e,n,t),gx(e,n),n})(this.editor,e))}},tL=class extends zT{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&((e,t)=>e.dist2(t)>=9)(this.info.originPagePoint,e.pagePoint)&&(px(this.editor,this.info,e),hx(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),gx(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(e){this.info&&(ux(this.editor,this.info,e),gx(this.editor,this.info),mx(this.editor,this.info)),this.transition("idle")}onCancel(){fx(this.editor),this.transition("idle")}onExit(){this.info=null}},nL=class extends zT{info=null;constructor(e,t){super(e,"erasing",t)}onEnter(e){this.info=e}onPointerMove(e){this.update(e)}onPointerUp(e){this.update(e),this.info&&mx(this.editor,this.info),this.transition("idle")}onCancel(){fx(this.editor),this.transition("idle")}onExit(){this.info=null}update(e){this.info&&(px(this.editor,this.info,e),hx(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),gx(this.editor,this.info))}},oL=zk(()=>Ir(rx(wr()).trailActiveSignal)?Gk(iL,{}):null),iL=zk(()=>{const e=wr(),t=Ir(rx(e).trailSignal),n=Ir(e.cameraZoomSignal),o=Math.max(n,1e-4),i=(()=>{const[e,t]=qk(()=>yx());return Wk(()=>{if("undefined"==typeof window)return;let e=0;const n=o=>{t(o),e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(e)}},[]),e})(),r=Kk({samples:[],sourceLength:0}),s=Math.max(i,yx());((e,t,n,o)=>{if(bx(e,o),t.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),t.length===e.sourceLength)return;const i=e.sourceLength,r=t.length-i,s=e.samples[e.samples.length-1]?.time??o-pL*r;for(let a=i;a<t.length;a++){const d=t[a];Sx(e,{x:d.x,y:d.y},n,Bx(s,o,(a-i+1)/r))}e.sourceLength=t.length,bx(e,o)})(r.current,t,o,s);const a=function(e,t){const n=xx(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),o=[e[0]];for(let i=1;i<e.length;i++)o.push(Ex(o[o.length-1],e[i],n));return o})(n.length>sL?n.slice(-48):n,lL)}(r.current.samples,s);if(0===a.length)return null;const d=(c=dL/o,0===(l=a).length||c<=0?null:1===l.length?$x(Ix(l[0],c/2,uL))??"":$x((e=>{if(0===e.length)return[];if(1===e.length)return Ix(e[0].point,Math.max(e[0].radius,.01),uL);const t=[],n=[];for(const a of e){const e=kx(a.direction);Rx(t,Tx(a.point,Mx(e,a.radius))),Rx(n,Cx(a.point,Mx(e,a.radius)))}const o=[];for(const a of t)Rx(o,a);const i=e[e.length-1],r=kx(i.direction),s=(({center:e,direction:t,normal:n,radius:o})=>{if(o<=0)return[];const i=[];for(let r=1;r<cL;r++){const s=r/cL;i.push(Cx(e,Cx(Mx(t,Math.sin(Math.PI*s)*o),Mx(n,-Math.cos(Math.PI*s)*o))))}return i})({center:i.point,direction:i.direction,normal:r,radius:i.radius});for(const a of s)Rx(o,a);for(let a=n.length-1;a>=0;a--)Rx(o,n[a]);return o})(((e,t)=>{const n=(e=>{const t=[0];for(let n=1;n<e.length;n++)t.push(t[n-1]+Px(e[n-1],e[n]));return t})(e),o=Math.max(t,n[n.length-1]??0);return e.map((i,r)=>{const s=n[r]??0,a=Ax(s/o,0,1);return{point:i,direction:wx(e,r),radius:t/2*a,runningLength:s}})})(l,c))));var l,c;return d?Gk("g",{"data-ui":"eraser-trail-overlay",children:Gk("path",{"data-ui":"eraser-trail-scribble",d:d,fill:rL})}):null}),rL="rgba(142, 142, 142, 0.16)",sL=48,aL=1,dL=12,lL=.32,cL=8,uL=13,pL=16,hL=8,gL=180,fL=180,mL=680,yL={id:"eraser",editor:{id:"land.eraser",setup(e){e.runtime.provide(Q$,(e=>{const t=a("eraser.shapeIds",[]),n=a("eraser.trail",[]);return{erasingShapeIdsSignal:t,trailSignal:n,trailActiveSignal:d("eraser.trailActive",()=>n.get().length>1),setPreview(o,i){t.set(Array.from(new Set(o))),n.set(i.map(e=>e.clone())),e.runtime.notify()},clear(){t.set([]),n.set([]),e.runtime.notify()}}})(e)),e.tools.register("eraser",e=>new J$(e),{shortcut:"e"})}},render:{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",layer:"below-host",component:oL}],shapeOpacityModifiers:[{id:"land.eraser.preview-opacity",getOpacity(e,t){const n=new Set(rx(e).erasingShapeIdsSignal.get());return e.hierarchy.isShapeOrAncestorInSet(t,n)?.32:1}}]},setup:e=>{e.toolbar.add({id:"eraser.tool-toolbar",channel:gM.toolSwitcher,order:50,actionIds:[pM],getGroups:e=>[{id:"eraser.tools",items:[{kind:"button",id:"eraser.tool.eraser",actionId:pM,value:"eraser",label:"Eraser",shortcut:e.editor.shortcuts.getToolShortcutLabel("eraser"),icon:"eraser",dataUi:"eraser-tool-button"}]}]})}},SL="group.selection.group",bL="group.selection.ungroup",xL={id:SL,getAvailability:e=>e.editor.canGroupSelection()?"enabled":"inapplicable",run({context:e}){e.editor.groupSelection("user")}},wL={id:bL,getAvailability:e=>e.editor.canUngroupSelection()?"enabled":"inapplicable",run({context:e}){e.editor.ungroupSelection("user")}},IL={id:"group.selection-toolbar",channel:gM.selectionProperties,order:1010,actionIds:[SL,bL],getGroups:()=>[{id:"group.selection-actions",presentation:"primary",items:[{kind:"button",id:SL,actionId:SL,label:"Group",icon:"group",dataUi:"group-selection-button"},{kind:"button",id:bL,actionId:bL,label:"Ungroup",icon:"ungroup",dataUi:"ungroup-selection-button"}]}]},PL={id:"group.selection-context-menu",target:"selection",order:1020,actionIds:[SL,bL],getSections:()=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"separator",id:"group.selection-separator"},{kind:"command",id:SL,actionId:SL,label:"Group",icon:"group",dataUi:"context-menu-group-selection-button"},{kind:"command",id:bL,actionId:bL,label:"Ungroup",icon:"ungroup",dataUi:"context-menu-ungroup-selection-button"}]}]},vL={id:"group",editor:{id:"land.group",shapeCapabilities:[{type:"group",schemaProps:["w","h"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Group is a transparent structural parent. The plugin supplies concrete record construction, bounds/hit policy, actions, and UI through ShapeUtil hooks; editor core owns generic hierarchy transactions and descendant-aware transforms."]}],shapeUtils:[new class extends DT{type="group";getGroupingShapeCreateInput({parentId:e,parentLocalBounds:t}){return{type:this.type,x:t.x,y:t.y,parentId:e,props:{w:t.w,h:t.h}}}getDefaultProps(){return{w:1,h:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Dx(t.w,n.w),h:Dx(t.h,n.h)}}getLocalBounds(e){return new LC(0,0,e.props.w,e.props.h)}hitTest(e,t){return!1}hitTestLineSegment(e,t){return!1}isSelectionTransformContainer(e){return!0}canUngroupChildren(e){return!0}shouldResizeDescendants(e){return!0}getResizeToFitDescendantsProps(e,t){return this.validateProps({...e.props,w:t.w,h:t.h})}getMinimumChildCount(e){return 2}contributesToExportBounds(e){return!1}canReceiveChildren(e){return!0}canAutomaticallyReceiveChildren(e){return!1}canBeDirectlyBrushSelected(e){return!1}}],shapeSvgExporters:[new class{type="group";toSvg(e){return{tag:"g"}}}]},render:{id:"land.group.react",shapeRenderers:[{type:"group",component:function({shape:e,isSelected:t}){
|
|
100
|
+
return Gk(zx,{shape:e,isSelected:t})},hoverComponent:function({shape:e,strokeWidth:t}){const{h:n,w:o}=e.props;
|
|
101
|
+
return Gk("svg",{"data-ui":"group-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${o} ${n}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Gk("rect",{x:0,y:0,width:o,height:n,fill:"none",stroke:xM,strokeWidth:t,vectorEffect:"non-scaling-stroke"})})}}]},setup:e=>{e.actions.add(xL,wL),e.actions.addShortcuts({actionId:SL,shortcut:{key:"g",accelKey:!0}},{actionId:bL,shortcut:{key:"g",accelKey:!0,shiftKey:!0}}),e.toolbar.add(IL),e.contextMenu.add(PL)}},kL="image.replace",CL="image.download-original",TL="image.insert",ML="image.crop",EL="image.crop.done",BL="image.crop.zoom",AL="image.crop.aspect-ratio",RL="image.crop.reset",$L="image.corner-radius",LL=1e-4,FL=1e-4,OL="image.crop",DL="image.crop:edit:",zL=[{label:"1:1",value:"1:1",ratio:1},{label:"4:3",value:"4:3",ratio:4/3},{label:"16:9",value:"16:9",ratio:16/9}],UL={top_left:"nwse-resize",top:"ns-resize",top_right:"nesw-resize",right:"ew-resize",bottom_right:"nwse-resize",bottom:"ns-resize",bottom_left:"nesw-resize",left:"ew-resize"},NL=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],WL=new WeakMap,XL="image.smudge",YL="image.smudge.cancel",HL="image.smudge.confirm",_L="image.smudge.brush-size",KL="image.smudge.brush-color",qL="image.smudge:",jL=`${qL}edit:`,VL="#ffff00",GL=24,ZL=VL,QL=.45,JL=class{editor;confirmHandler=null;deactivateHistoryScope=null;session=null;snapshot=null;subscribers=new Set;constructor(e){this.editor=e,Zi("image.smudgeSession.lifecycle",e.shapeEditingSessionSignal,()=>{this.clearIfEditingSessionInvalid()},{fireImmediately:!1})}start(e,t){if(e.isLocked)return!1;const n=rw(e.id),o=this.editor.getShapeEditingSession();if(o&&(o.shapeId!==e.id||o.markId!==n))return!1;if(this.session&&o?.shapeId===e.id&&sw(e,o.markId))return this.updateSession({...this.session,brush:aw({...this.session.brush,...t})}),!0;this.clear();const i=this.editor.startEditingShape({shapeId:e.id,markId:n,entryMode:"focusEnd"},"user");return!(!i||i.shapeId!==e.id||i.markId!==n||(this.setSession({shapeId:e.id,brush:aw(t),strokes:[],activeStroke:null,redoStrokes:[],nextStrokeIndex:1}),this.activateHistoryScope(e.id),0))}cancel(){const e=this.session?.shapeId??null;this.clear();const t=this.editor.getShapeEditingSession();e&&t?.shapeId===e&&t.markId===rw(e)&&this.editor.cancelEditing("user")}complete(){const e=this.session?.shapeId??null;this.clear();const t=this.editor.getShapeEditingSession();e&&t?.shapeId===e&&t.markId===rw(e)&&this.editor.completeEditing("user")}cancelIfActive(){return!!this.getActiveSession()&&(this.cancel(),!0)}clearForShape(e){this.session?.shapeId===e&&this.clear()}updateBrush(e){if(!this.getActiveSession()||!this.session)return!1;const t=aw({...this.session.brush,...e});return t.size===this.session.brush.size&&t.color===this.session.brush.color&&t.opacity===this.session.brush.opacity||this.updateSession({...this.session,brush:t}),!0}getSnapshot(e){const t=this.getActiveSession();return t&&t.shapeId===e?this.snapshot:null}getActiveSession(){if(!this.session)return null;const e=this.editor.getShape(this.session.shapeId),t=this.editor.getShapeEditingSession();return e&&t&&t.shapeId===this.session.shapeId&&t.markId===rw(this.session.shapeId)?this.snapshot:(this.clear(),null)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}beginStroke(e){if(!this.session)return;const t=ow(this.session),n={id:`${t.shapeId}:smudge:${t.nextStrokeIndex}`,points:[gw(e)],brush:{...t.brush}};this.updateSession({...t,activeStroke:n,nextStrokeIndex:t.nextStrokeIndex+1})}appendPoint(e){if(!this.session?.activeStroke)return;const t=this.session.activeStroke.points[this.session.activeStroke.points.length-1];t&&Math.hypot(t.x-e.x,t.y-e.y)<.5||this.updateSession({...this.session,activeStroke:{...this.session.activeStroke,points:[...this.session.activeStroke.points,gw(e)]}})}endStroke(){this.session?.activeStroke&&this.updateSession(ow(this.session))}cancelStroke(){this.session?.activeStroke&&this.updateSession({...this.session,activeStroke:null})}undo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke&&this.updateSession(ow(this.session)),!this.session||0===this.session.strokes.length)return!1;const e=this.session.strokes[this.session.strokes.length-1];return!!e&&(this.updateSession({...this.session,strokes:this.session.strokes.slice(0,-1),redoStrokes:[...this.session.redoStrokes,e]}),!0)}redo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke||0===this.session.redoStrokes.length)return!1;const e=this.session.redoStrokes[this.session.redoStrokes.length-1];return!!e&&(this.updateSession({...this.session,strokes:[...this.session.strokes,e],redoStrokes:this.session.redoStrokes.slice(0,-1)}),!0)}registerConfirmHandler(e){return this.confirmHandler=e,()=>{this.confirmHandler===e&&(this.confirmHandler=null)}}requestConfirm(e){return this.confirmHandler?this.confirmHandler(e):Promise.resolve(null)}clear(){this.session&&(this.session=null,this.snapshot=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}clearIfEditingSessionInvalid(){if(!this.session)return;const e=this.editor.getShapeEditingSession();e?.shapeId===this.session.shapeId&&e.markId===rw(this.session.shapeId)||this.clear()}activateHistoryScope(e){this.deactivateHistoryScope=this.editor.history.activateScope({id:`${qL}history:${e}`,getState:()=>this.getHistoryScopeState(),subscribe:e=>this.subscribe(e),undo:()=>this.undo(),redo:()=>this.redo()})}getHistoryScopeState(){const e=this.session?.activeStroke?1:0,t=this.session?.activeStroke?0:this.session?.redoStrokes.length??0;return{canUndo:(this.session?.strokes.length??0)+e>0,canRedo:t>0,undoDepth:(this.session?.strokes.length??0)+e,redoDepth:t}}setSession(e){this.session=e,this.snapshot=(e=>({shapeId:e.shapeId,brush:e.brush,strokes:e.activeStroke?[...e.strokes,e.activeStroke]:e.strokes,canUndo:e.strokes.length>0||!!e.activeStroke,canRedo:!e.activeStroke&&e.redoStrokes.length>0}))(e),this.notify()}updateSession(e){this.setSession(e)}notify(){for(const e of this.subscribers)e()}},eF=new WeakMap,tF=[{id:"smudge-yellow",label:"Yellow",hexColor:VL},{id:"smudge-orange",label:"Orange",hexColor:"#ff9900"},{id:"smudge-pink",label:"Pink",hexColor:"#ff4fd8"},{id:"smudge-green",label:"Green",hexColor:"#39ff14"},{id:"smudge-blue",label:"Blue",hexColor:"#00c8ff"},{id:"smudge-purple",label:"Purple",hexColor:"#b967ff"}],nF={id:"land.image.crop.dom-events",handle:()=>"continue",getCursor({clientPoint:e,editor:t,element:n,container:o}){const i=(e=>{const[t]=e.getSelectedShapes();if(!mw(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Zx(t,n.markId)?t:null})(t);if(!i)return;if(n?.closest('[data-selection-custom-handle-type="image.crop"]'))return;if(!e)return;const r=o.getBoundingClientRect(),s=new $C(e.x-r.left,e.y-r.top);return Nw(t,i,t.screenToPage(s))?0!==t.inputs.state.get().buttons?"grabbing":"grab":void 0}},oF={id:"land.image.smudge.dom-events",handle:()=>"continue",getCursor({clientPoint:e,container:t,editor:n}){const o=(e=>{const[t]=e.getSelectedShapes();if(!mw(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&sw(t,n.markId)?t:null})(n);if(!o||!e)return;const i=t.getBoundingClientRect(),r=new $C(e.x-i.left,e.y-i.top);return Nw(n,o,n.screenToPage(r))?"crosshair":0!==n.inputs.state.get().buttons?"grabbing":"grab"}},iF={id:"image",editor:{id:"land.image",shapeCapabilities:[{type:"image",schemaProps:["w","h","assetId","crop","cornerRadius","altText"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Image shape util, SVG exporter, and React renderer live in @land/plugin-image. Asset records store serializable metadata plus a local or remote source; File/Blob/object URL/download behavior stays in the web host."]}],shapeUtils:[new class extends DT{type="image";getDefaultProps(){return{w:240,h:180,assetId:null,crop:null,cornerRadius:0,altText:""}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,Mw(t.w,n.w)),h:Math.max(24,Mw(t.h,n.h)),assetId:(o=t.assetId,"string"==typeof o&&o.startsWith("asset:")?t.assetId:null),crop:Yx(t.crop),cornerRadius:ww(t.cornerRadius,n.cornerRadius),altText:"string"==typeof t.altText?t.altText:n.altText};var o}getLocalBounds(e){return new LC(0,0,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getAllowedSelectionResizeModes(e,t){return bT}canEdit(e){return!0}onEditEnd(e,t){var n;n=e.id,iw(t.editor).clearForShape(n)}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const o=t.editor.getShapeEditingSession();return o&&o.shapeId===e.id&&Zx(e,o.markId)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:Jx({crop:e.props.crop,localToPage:t.editor.computeShapeLocalToPageTransform(e),shape:e})}:n}}],shapeSvgExporters:[new class{type="image";toSvg(e,t){const{assetId:n,altText:o,crop:i,h:r,w:s}=e.props;if(!n)return null;const a=t.resolveAssetUrl(n);if(!a)return null;const d=Hx(i),l=d?{tag:"svg",attrs:{x:0,y:0,width:s,height:r,viewBox:(c=d,[tw(c.left),tw(c.top),tw(c.width),tw(c.height)].join(" ")),preserveAspectRatio:"none",overflow:"hidden"},children:[{tag:"image",attrs:{href:a,x:0,y:0,width:1,height:1,preserveAspectRatio:"none","aria-label":o||void 0}}]}:{tag:"image",attrs:{href:a,width:s,height:r,preserveAspectRatio:"none","aria-label":o||void 0}};var c;const u=Iw({cornerRadius:e.props.cornerRadius,h:r,w:s});return u<=0?l:{tag:"g",attrs:{"clip-path":`url(#${t.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:0,y:0,width:s,height:r,rx:u,ry:u}}]})})`},children:[l]}}}],interactionHandlers:[function(){let e=null;const t=()=>{e?.operation?.isActive&&e.operation.cancel(),e=null};return{id:"land.image.crop.interactions",editorEvent:{handleEvent(n,o){if("cancel"===o.type)return t(),"continue";if("keyboard"===o.type)return((e,t)=>{if("key_down"!==t.name)return"continue";const n=Cw(e);if(!n)return"continue";if("Escape"===t.key&&!t.altKey&&!t.accelKey)return e.cancelEditing("user")&&nw(e,n.id),"handled";if("Enter"===t.key&&!t.altKey&&!t.accelKey)return e.completeEditing("user")&&nw(e,n.id),"handled";const o=(e=>{if(e.altKey||e.accelKey)return null;const t=e.shiftKey?10:1;switch(e.key){case"ArrowLeft":return new $C(t,0);case"ArrowRight":return new $C(-t,0);case"ArrowUp":return new $C(0,t);case"ArrowDown":return new $C(0,-t);default:return null}})(t);if(o){const t=(({pageDelta:e,shape:t,startCrop:n})=>{const o=Yx(n);return!o||e.equals($C.Zero())?null:ew({change:e.rot(-t.rotation),crop:o,shape:t})})({pageDelta:o,shape:n,startCrop:n.props.crop});return t&&e.commands.updateShapes([t],{source:"user"}),"handled"}return"continue"})(n,o);if("pointer"!==o.type)return"continue";if("pointer_cancel"===o.name)return t(),"continue";if("pointer_down"===o.name){if(t(),0!==o.button||"select"!==n.getActiveToolId()||!n.isActiveToolInInitialState())return"continue";if(n.hitTestSelectionHandle(o.pagePoint))return"continue";const i=Cw(n);return i?((e,t,n)=>{const o=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n.pagePoint);return o.x>=0&&o.y>=0&&o.x<=t.props.w&&o.y<=t.props.h})(n,i,o)?(e={pointerId:o.pointerId,shapeId:i.id,startCrop:i.props.crop,startPagePoint:o.pagePoint.clone(),startPageToLocal:n.computeShapeLocalToPageTransform(i).invert(),startShape:i,hasDragged:!1,operation:null},"handled"):n.completeEditing("user")?(nw(n,i.id),n.dispatch(o),"handled"):"continue":"continue"}return e&&o.pointerId===e.pointerId?"pointer_move"===o.name?(Tw(n,o,e),"handled"):"pointer_up"===o.name?(Tw(n,o,e),e.operation?.isActive&&e.operation.commit(),t(),"handled"):"continue":"continue"}},selectionHandle:kw()}}(),function(){let e=null;const t=t=>{e=null,(e=>{iw(e).endStroke()})(t)},n=t=>{e=null,(e=>{iw(e).cancelStroke()})(t)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(o,i){if("keyboard"===i.type)return(Bw(i)||Ew(i))&&Aw(o)&&t(o),((e,t)=>"key_down"!==t.name?"continue":Aw(e)?"Escape"!==t.key||t.altKey||t.accelKey?Ew(t)?(hw(e,{replace:!0}),"handled"):Bw(t)?(t.shiftKey?e.redo():e.undo(),"handled"):"handled":(lw(e),"handled"):"continue")(o,i);if("cancel"===i.type)return Aw(o)?(n(o),lw(o),"handled"):"continue";if("pointer"!==i.type)return"continue";const r=Aw(o);if(!r)return n(o),"continue";if("pointer_down"===i.name){if(t(o),0!==i.button)return 1===i.button?"continue":"handled";const n=$w(o,r,i.pagePoint),s=Lw(n,r);return e={mode:s?"draw":"pan",originCamera:s?null:o.getCurrentCamera(),originScreenPoint:s?null:i.screenPoint.clone(),pointerId:i.pointerId,acceptsDrawPoints:s},s&&((e,t)=>{iw(e).beginStroke(t)})(o,{x:n.x,y:n.y,pressure:i.pressure}),"handled"}return e&&e.pointerId===i.pointerId?"pointer_move"===i.name?("draw"===e.mode&&1&i.buttons?e.acceptsDrawPoints&&(e.acceptsDrawPoints=Rw(o,r,i)):"pan"===e.mode&&e.originCamera&&e.originScreenPoint&&1&i.buttons?Fw(o,i,e):t(o),"handled"):"pointer_up"===i.name?("draw"===e.mode&&e.acceptsDrawPoints?Rw(o,r,i):"pan"===e.mode&&Fw(o,i,e),t(o),"handled"):"pointer_cancel"===i.name?(n(o),"handled"):"handled":"handled"}}}}()],setup:e=>(e=>{let t=null;return Zi("image.cropSession.lifecycle",e.shapeEditingSessionSignal,()=>{const n=e.getShapeEditingSession(),o=n?.shapeId,i=o&&n?.markId===Qx(o)?o:null;t&&t!==i&&nw(e,t),t=i})})(e)},render:{id:"land.image.react",domEventGuards:[nF,oF],selectionCustomHandleRenderers:[{type:OL,component:function({handle:e,strokeWidth:t}){const{x:n,y:o,w:i,h:r,center:s}=e.bounds,a=1.35*Math.max(i,r),d=Math.max(2.5*t,2),l={fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeLinecap:"butt",strokeLinejoin:"miter",strokeWidth:d,pointerEvents:"none"},c=(({id:e,extension:t,outwardOffset:n,centerX:o,centerY:i})=>{switch(e){case"top_left":return{kind:"corner",points:[zw(o-n,i+t),zw(o-n,i-n),zw(o+t,i-n)].join(" ")};case"top":return{kind:"edge",x1:o-t,y1:i-n,x2:o+t,y2:i-n};case"top_right":return{kind:"corner",points:[zw(o-t,i-n),zw(o+n,i-n),zw(o+n,i+t)].join(" ")};case"right":return{kind:"edge",x1:o+n,y1:i-t,x2:o+n,y2:i+t};case"bottom_right":return{kind:"corner",points:[zw(o+n,i-t),zw(o+n,i+n),zw(o-t,i+n)].join(" ")};case"bottom":return{kind:"edge",x1:o-t,y1:i+n,x2:o+t,y2:i+n};case"bottom_left":return{kind:"corner",points:[zw(o+t,i+n),zw(o-n,i+n),zw(o-n,i-t)].join(" ")};case"left":return{kind:"edge",x1:o-n,y1:i-t,x2:o-n,y2:i+t};default:return{kind:"edge",x1:o,y1:i,x2:o,y2:i}}})({id:e.id,extension:a,outwardOffset:d/2,centerX:s.x,centerY:s.y});
|
|
102
|
+
return Zk("g",{children:[Gk("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:n-.8*i,y:o-.8*r,width:2.6*i,height:2.6*r,fill:"transparent",style:{cursor:e.cursor??"grab",pointerEvents:"auto"}}),"corner"===c.kind?Gk("polyline",{points:c.points,...l}):Gk("line",{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,...l})]})}}],shapeRenderers:[{type:"image",component:function({editor:e,shape:t,shapeEditingSession:n}){const{altText:o,assetId:i,crop:r,h:s,w:a}=t.props,d=i?e.resolveAssetUrl(i):null,l=Iw({cornerRadius:t.props.cornerRadius,h:s,w:a}),c=((e,t)=>jk(t=>((e,t)=>iw(e).subscribe(t))(e,t),()=>((e,t)=>iw(e).getSnapshot(t))(e,t),()=>null))(e,t.id);if(!d)return Gk("div",{"data-ui":"image-shape-missing-asset",style:{alignItems:"center",background:"#f1f5f9",border:"1px solid #cbd5e1",borderRadius:l,boxSizing:"border-box",color:"#64748b",display:"flex",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:12,height:s,justifyContent:"center",overflow:"hidden",width:a},children:"Missing image"});const u=(({crop:e,shapeHeight:t,shapeWidth:n})=>{const o=Hx(e);if(!o)return null;const i=n/o.width,r=t/o.height;return{imageX:-o.left*i,imageY:-o.top*r,imageWidth:i,imageHeight:r,rect:o}})({crop:r,shapeHeight:s,shapeWidth:a});if(u){const e=n?.shapeId===t.id&&Zx(t,n.markId),i={display:"block",height:u.imageHeight,left:u.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:u.imageY,userSelect:"none",width:u.imageWidth};
|
|
103
|
+
return Zk("div",{"data-ui":"image-shape",style:{display:"block",height:s,overflow:e?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[e?Gk("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:d,style:{...i,opacity:.1}}):null,Zk("div",{"data-ui":"image-crop-window",style:{height:s,overflow:"hidden",position:"absolute",borderRadius:l,inset:0,width:a},children:[Gk("img",{alt:o,draggable:!1,src:d,style:i}),Gk(Ow,{shape:t,session:c})]})]})}
|
|
104
|
+
return Zk("div",{"data-ui":"image-shape",style:{borderRadius:l,display:"block",height:s,overflow:"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[Gk("img",{alt:o,draggable:!1,src:d,style:{display:"block",height:s,objectFit:"fill",width:a}}),Gk(Ow,{shape:t,session:c})]})},hoverComponent:function({shape:e,strokeWidth:t}){
|
|
105
|
+
return Gk("div",{"data-ui":"image-hover-outline",style:{borderRadius:Iw({cornerRadius:e.props.cornerRadius,h:e.props.h,w:e.props.w}),boxShadow:`inset 0 0 0 ${t}px ${xM}`,inset:0,position:"absolute"}})}}]},setup:e=>{e.actions.add(...xw(),{id:XL,getAvailability(e){const t=yw(e);return!t||Sw(e)||bw(e)?"inapplicable":!t.isLocked&&t.props.assetId?"enabled":"disabled"},getValue:e=>bw(e),run({context:e}){const t=yw(e);t&&!t.isLocked&&t.props.assetId&&dw({editor:e.editor,shape:t})}},{id:_L,getAvailability:e=>bw(e)?"enabled":"inapplicable",getValue:e=>pw(e.editor)?.brush.size??24,run({context:e,value:t}){uw(e.editor,{size:t})}},{id:KL,getAvailability:e=>bw(e)?"enabled":"inapplicable",getValue(e){const t=pw(e.editor)?.brush;return{color:t?.color??"#ffff00",opacity:t?.opacity??.45}},run({context:e,value:t}){uw(e.editor,{color:t.color,opacity:t.opacity})}},{id:YL,getAvailability:e=>bw(e)?"enabled":"inapplicable",run({context:e}){lw(e.editor)}},{id:HL,getAvailability:e=>bw(e)?"enabled":"inapplicable",run({context:e}){hw(e.editor,{replace:!0})}},{id:$L,getAvailability:e=>"image"!==e.selection.commonShapeType?"inapplicable":e.selection.selectedShapes.some(e=>mw(e)&&!e.isLocked)?"enabled":"disabled",getValue:e=>(e=>{let t;for(const n of e){if(!mw(n))continue;const e=ww(n.props.cornerRadius);if(void 0!==t){if(t!==e)return null}else t=e}return void 0===t?null:(e=>Number(e.toFixed(2)).toString())(t)})(e.selection.selectedShapes),run({context:e,value:t}){const n=(e=>{if("string"!=typeof e)return null;const t=e.trim();if(0===t.length)return null;const n=Number(t);return Number.isFinite(n)?ww(n):null})(t);if(null===n)return;const o=e.selection.selectedShapes.filter(mw).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{cornerRadius:n}}));0!==o.length&&e.editor.commands.updateShapes(o,{source:"user"})}}),e.toolbar.add({id:"image.tool-toolbar",channel:gM.toolSwitcher,order:55,actionIds:[TL],getGroups:()=>[{id:"image.tools",items:[{kind:"button",id:TL,actionId:TL,label:"Image",icon:"image-plus",dataUi:"insert-image-tool-button"}]}]},{id:"image.selection-toolbar",channel:gM.selectionProperties,order:30,actionIds:[ML,EL,BL,AL,RL,XL,KL,_L,YL,HL,$L,kL,CL],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups(e){const t=[];return bw(e)?[{id:"image.smudge-color",order:5,items:[{kind:"color-input",id:KL,actionId:KL,label:"Brush color",fallback:VL,opacityMode:"separate",opacityFallback:.45,presets:tF,dataUi:"image-smudge-brush-color-input"}]},{id:"image.smudge-brush",order:10,items:[{kind:"slider",id:_L,actionId:_L,label:"Brush size",min:1,max:128,step:1,dataUi:"image-smudge-brush-size-slider"}]},{id:"image.smudge-actions",order:20,items:[{kind:"button",id:YL,actionId:YL,label:"Cancel smudge",icon:"x",dataUi:"cancel-image-smudge-button"},{kind:"button",id:HL,actionId:HL,label:"Confirm smudge",icon:"check",dataUi:"confirm-image-smudge-button"}]}]:(Sw(e)&&t.push({id:"image.crop-zoom",order:10,items:[{kind:"stepper",id:"image.crop.zoom-stepper",actionId:BL,label:"Zoom",options:[{value:-1,label:"-",dataUi:"image-crop-zoom-out-button"},{value:1,label:"+",dataUi:"image-crop-zoom-in-button"}]}]},{id:"image.crop-aspect",order:20,items:[{kind:"segmented",id:"image.crop.aspect-ratio-segmented",actionId:AL,options:zL.map(e=>({value:e.value,label:e.label,dataUi:`image-crop-aspect-${e.value.replace(":","-")}-button`}))}]},{id:"image.crop-actions",order:30,items:[{kind:"button",id:RL,actionId:RL,label:"Reset crop",icon:"rotate-ccw",dataUi:"reset-image-crop-button"}]}),t.push((({dataUiPrefix:e,id:t,order:n})=>({id:t,order:n,items:[Pw({dataUiPrefix:e})]}))({dataUiPrefix:"image",id:"image.style-corner-radius",order:35})),t.push({id:"image.asset",order:40,items:[{kind:"button",id:ML,actionId:ML,label:"Crop image",icon:"crop",dataUi:"crop-image-button"},{kind:"button",id:XL,actionId:XL,label:"Smudge image",icon:"pencil",dataUi:"smudge-image-button"},{kind:"button",id:EL,actionId:EL,label:"Done cropping",icon:"check",dataUi:"done-cropping-button"},{kind:"button",id:kL,actionId:kL,label:"Replace image",icon:"image-plus",dataUi:"replace-image-button"},{kind:"button",id:CL,actionId:CL,label:"Download original",icon:"download",dataUi:"download-image-original-button"}]}),t)}},{id:"image.floating-selection-toolbar",channel:gM.selectionQuickActions,order:30,actionIds:[ML,EL,BL,AL,RL,XL,KL,_L,YL,HL,$L,kL,CL],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups:e=>bw(e)?[{id:"image.floating-smudge-color",order:5,items:[{kind:"color-input",id:"image.floating-smudge.brush-color",actionId:KL,label:"Brush color",fallback:VL,opacityMode:"separate",opacityFallback:.45,presets:tF,dataUi:"floating-image-smudge-brush-color-input"}]},{id:"image.floating-smudge-brush",order:10,items:[{kind:"slider",id:"image.floating-smudge.brush-size",actionId:_L,label:"Brush size",min:1,max:128,step:1,dataUi:"floating-image-smudge-brush-size-slider"}]},{id:"image.floating-smudge-actions",order:20,items:[{kind:"button",id:"image.floating-smudge.cancel",actionId:YL,label:"Cancel smudge",icon:"x",dataUi:"floating-cancel-image-smudge-button"},{kind:"button",id:"image.floating-smudge.confirm",actionId:HL,label:"Confirm smudge",icon:"check",dataUi:"floating-confirm-image-smudge-button"}]}]:Sw(e)?[{id:"image.floating-crop-zoom",order:10,items:[{kind:"stepper",id:"image.floating-crop.zoom-stepper",actionId:BL,label:"Zoom",options:[{value:-1,label:"-",dataUi:"floating-image-crop-zoom-out-button"},{value:1,label:"+",dataUi:"floating-image-crop-zoom-in-button"}]}]},{id:"image.floating-crop-aspect",order:20,items:[{kind:"segmented",id:"image.floating-crop.aspect-ratio-segmented",actionId:AL,options:zL.map(e=>({value:e.value,label:e.label,dataUi:`floating-image-crop-aspect-${e.value.replace(":","-")}-button`}))}]},{id:"image.floating-crop-corner-radius",order:35,items:[Pw({dataUiPrefix:"floating-image-crop"})]},{id:"image.floating-crop-actions",order:30,items:[{kind:"button",id:"image.floating-crop.done",actionId:EL,label:"Done cropping",icon:"check",dataUi:"floating-done-cropping-button"},{kind:"button",id:"image.floating-crop.reset",actionId:RL,label:"Reset crop",icon:"rotate-ccw",dataUi:"floating-reset-image-crop-button"}]}]:[{id:"image.floating-corner-radius",order:10,items:[Pw({dataUiPrefix:"floating-image"})]},{id:"image.floating-primary-actions",order:20,items:[{kind:"button",id:"image.floating.crop",actionId:ML,label:"Crop image",icon:"crop",dataUi:"floating-crop-image-button"},{kind:"button",id:"image.floating.replace",actionId:kL,label:"Replace image",icon:"image-plus",dataUi:"floating-replace-image-button"}]},{id:"image.floating-more-actions",order:30,presentation:"overflow",items:[{kind:"button",id:"image.floating.smudge",actionId:XL,label:"Smudge image",icon:"pencil",dataUi:"floating-smudge-image-button"},{kind:"button",id:"image.floating.download",actionId:CL,label:"Download original",icon:"download",dataUi:"floating-download-image-original-button"}]}]}),e.contextMenu.add({id:"image.shape-context-menu",target:"selection",order:30,actionIds:[ML,XL,kL,CL],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getSections:()=>[{id:"image.asset-context-menu",title:"Image",items:[{kind:"command",id:ML,actionId:ML,label:"Crop image",icon:"crop",dataUi:"context-menu-crop-image-button"},{kind:"command",id:XL,actionId:XL,label:"Smudge image",icon:"pencil",dataUi:"context-menu-smudge-image-button"},{kind:"command",id:kL,actionId:kL,label:"Replace image",icon:"image-plus",dataUi:"context-menu-replace-image-button"},{kind:"command",id:CL,actionId:CL,label:"Download original",icon:"download",dataUi:"context-menu-download-image-original-button"}]}]})}},rF=l("plugin.laser.runtime"),sF=class extends zT{constructor(e){super(e,"laser"),this.initial="idle",this.addChild(new aF(e,this)),this.addChild(new dF(e,this)),this.addChild(new lF(e,this))}},aF=class extends zT{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={sessionId:Ww(e).start(),originPagePoint:t.pagePoint.clone(),trail:[t.pagePoint.clone()]};return Yw(e,n),n})(this.editor,e))}},dF=class extends zT{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&((e,t)=>e.dist2(t)>=9)(this.info.originPagePoint,e.pagePoint)&&(Xw(this.info,e.pagePoint),Yw(this.editor,this.info),this.transition("drawing",this.info))}onPointerUp(){this.info&&Ww(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&Ww(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&Ww(this.editor).finish(this.info.sessionId),this.info=null}},lF=class extends zT{info=null;constructor(e,t){super(e,"drawing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&(Xw(this.info,e.pagePoint),Yw(this.editor,this.info))}onPointerUp(){this.info&&Ww(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&Ww(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&Ww(this.editor).finish(this.info.sessionId),this.info=null}},cF=zk(()=>Ir(Ww(wr()).activeSignal)?Gk(uF,{}):null),uF=zk(()=>{const e=wr(),t=Ww(e),n=Ir(t.trailSignal),o=Ir(e.cameraZoomSignal),i=Math.max(o,1e-4),r=(()=>{const[e,t]=qk(()=>Hw());return Wk(()=>{if("undefined"==typeof window)return;let e=0;const n=o=>{t(o),e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(e)}},[]),e})(),s=Kk({sessionId:0,samples:[],sourceLength:0}),a=Math.max(r,Hw());let d,l=[];n&&(((e,t,n,o)=>{t.sessionId!==e.sessionId&&(e.sessionId=t.sessionId,e.samples=[],e.sourceLength=0);const i=t.points;if(Kw(e,o),i.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),i.length===e.sourceLength)return;const r=e.sourceLength,s=i.length-r,a=e.samples[e.samples.length-1]?.time??o-wF*s;for(let d=r;d<i.length;d++){const t=i[d];_w(e,{x:t.x,y:t.y},n,oI(a,o,(d-r+1)/s))}e.sourceLength=i.length,Kw(e,o)})(s.current,n,i,a),l=function(e,t){const n=qw(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),o=[e[0]];for(let i=1;i<e.length;i++)o.push(nI(o[o.length-1],e[i],n));return o})(n.length>fF?n.slice(-64):n,SF)}(s.current.samples,a),d=s.current.samples[s.current.samples.length-1]?.time);const c="ending"===n?.phase,u=0===l.length,p=c&&u?n.sessionId:null;if(Wk(()=>{null!==p&&t.clear(p)},[p,t]),!n||u)return null;const h=c&&void 0!==d?iI(1-(a-d)/CF,0,1):1,g=(m=yF/i,0===(f=l).length||m<=0?null:1===f.length?sI(Vw(f[0],m/2,xF))??"":sI((e=>{if(0===e.length)return[];if(1===e.length)return Vw(e[0].point,Math.max(e[0].radius,.01),xF);const t=[],n=[];for(const a of e){const e=Qw(a.direction);rI(t,eI(a.point,tI(e,a.radius))),rI(n,Jw(a.point,tI(e,a.radius)))}const o=[];for(const a of t)rI(o,a);const i=e[e.length-1],r=Qw(i.direction),s=(({center:e,direction:t,normal:n,radius:o})=>{if(o<=0)return[];const i=[];for(let r=1;r<bF;r++){const s=r/bF;i.push(Jw(e,Jw(tI(t,Math.sin(Math.PI*s)*o),tI(n,-Math.cos(Math.PI*s)*o))))}return i})({center:i.point,direction:i.direction,normal:r,radius:i.radius});for(const a of s)rI(o,a);for(let a=n.length-1;a>=0;a--)rI(o,n[a]);return o})(((e,t)=>{const n=(e=>{const t=[0];for(let n=1;n<e.length;n++)t.push(t[n-1]+Gw(e[n-1],e[n]));return t})(e),o=Math.max(t,n[n.length-1]??0);return e.map((i,r)=>{const s=n[r]??0,a=iI(s/o,0,1);return{point:i,direction:jw(e,r),radius:t/2*a,runningLength:s}})})(f,m))));var f,m;return g?Zk("g",{"data-ui":"laser-trail-overlay",style:{opacity:h},children:[Gk("path",{"data-ui":"laser-trail-glow",d:g,fill:hF,style:{filter:`blur(${gF/i}px)`}}),Gk("path",{"data-ui":"laser-trail-beam",d:g,fill:pF})]}):null}),pF="rgb(255, 38, 38)",hF="rgba(255, 48, 48, 0.55)",gF=4,fF=64,mF=1,yF=12,SF=.32,bF=8,xF=13,wF=16,IF=8,PF=600,vF=300,kF=1400,CF=400,TF={id:"laser",editor:{id:"land.laser",setup(e){e.runtime.provide(rF,(()=>{const e=a("laser.trail",null);let t=1;return{trailSignal:e,activeSignal:d("laser.active",()=>null!==e.get()),start(){const n=t++;return e.set({sessionId:n,phase:"active",points:[]}),n},set(t,n){const o=e.get();o&&o.sessionId===t&&e.set({sessionId:t,phase:"active",points:n.map(e=>e.clone())})},finish(t){const n=e.get();n&&n.sessionId===t&&e.set({...n,phase:"ending"})},clear(t){e.get()?.sessionId===t&&e.set(null)}}})()),e.tools.register("laser",e=>new sF(e),{shortcut:"l"})}},render:{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",layer:"below-host",component:cF}]},setup:e=>{e.toolbar.add({id:"laser.tool-toolbar",channel:gM.toolSwitcher,order:55,actionIds:[pM],getGroups:e=>[{id:"laser.tools",items:[{kind:"button",id:"laser.tool.laser",actionId:pM,value:"laser",label:"Laser",shortcut:e.editor.shortcuts.getToolShortcutLabel("laser"),icon:"wand",dataUi:"laser-tool-button"}]}]})}},MF="path.node",EF="path.control",BF=new WeakMap,AF=["nonzero","evenodd"],RF=["corner","smooth","symmetric"],$F=1e-6,LF=1/3,FF=Math.PI/8,OF=new WeakMap,DF=new WeakMap,zF="land.path.draftSubpathId",UF="land.path.previewNodeId",NF="var(--land-selection, #2563eb)",WF="rgba(255, 255, 255, 0.98)",XF=class{editor;deactivateHistoryScope=null;session=null;subscribers=new Set;constructor(e){this.editor=e}start(e,t,n){const o=this.editor.getShape(t);if(!gI(o))return!1;if(this.session?.mode===e&&this.session.shapeId===t)return!0;this.clear();const i=[BP(this.editor,o,e)];return this.session={mode:e,shapeId:t,snapshots:i,index:i.length-1,initialShapeSignature:AP(o),onApply:n?.onApply,onBoundaryUndo:n?.onBoundaryUndo},this.deactivateHistoryScope=this.editor.history.activateScope({id:`path.${e}.temporary:${t}`,getState:()=>this.getState(),subscribe:e=>this.subscribe(e),undo:()=>this.undo(),redo:()=>this.redo()}),this.notify(),!0}record(e){const t=this.session,n=this.editor.getShape(e);if(!t||t.shapeId!==e||!gI(n))return!1;const o=BP(this.editor,n,t.mode);return t.snapshots[t.index]?.signature===o.signature?(t.snapshots[t.index]=o,!1):(t.snapshots=[...t.snapshots.slice(0,t.index+1),o],t.index=t.snapshots.length-1,this.notify(),!0)}replaceCurrent(e){const t=this.session,n=this.editor.getShape(e);if(!t||t.shapeId!==e||!gI(n))return!1;const o=BP(this.editor,n,t.mode),i=t.snapshots[t.index];return t.snapshots[t.index]=o,i?.signature!==o.signature&&(this.notify(),!0)}end(e,t){return this.session?.mode===e&&this.session.shapeId===t&&(this.clear(),!0)}hasNetChanges(e,t){const n=this.session,o=this.editor.getShape(t);return!(!n||n.mode!==e||n.shapeId!==t||gI(o)&&n.initialShapeSignature===AP(o))}undo(){const e=this.session;return!!e&&(e.index<=0?e.onBoundaryUndo?.()??!1:this.applySnapshot(e.index-1))}redo(){const e=this.session;return!(!e||e.index>=e.snapshots.length-1)&&this.applySnapshot(e.index+1)}applySnapshot(e){const t=this.session,n=t?.snapshots[e];if(!t||!n)return!1;const o=this.editor.getShape(t.shapeId);if(!gI(o))return this.clear(),!1;t.index=e;const i=cP(this.editor);this.editor.commands.updateShapes([{id:t.shapeId,..."create"===t.mode&&n.draftMeta?{meta:xP(o.meta,n.draftMeta)}:{},props:{subpaths:vI(n.subpaths)}}],{source:"user"});const r=this.editor.getShape(t.shapeId);gI(r)&&t.onApply?.(r);const s=n.selection??i;return s&&gI(r)&&this.editor.getShapeEditingSession()?.shapeId===t.shapeId?gP(this.editor,r,s.nodes,s.primary):pP(this.editor),this.notify(),!0}getState(){const e=this.session?.index??0,t=(this.session?.snapshots.length??1)-1,n=this.session?.onBoundaryUndo?1:0;return{canUndo:e+n>0,canRedo:e<t,undoDepth:e+n,redoDepth:Math.max(0,t-e)}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}clear(){(this.session||this.deactivateHistoryScope)&&(this.session=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}notify(){for(const e of this.subscribers)e()}},YF=new WeakMap,HF=new WeakMap,_F="path.edit",KF=Math.PI/4,qF=1,jF=new WeakMap,VF=new WeakMap,GF=Math.PI/4,ZF=1,QF=1,JF=class extends zT{draft=null;operation=null;constructor(e){super(e,"path"),this.initial="idle",this.addChild(new eO(e,this)),this.addChild(new tO(e,this))}onEnter(){this.editor.clearSelectionTransients()}onExit(){this.draft&&(this.canFinishDraft()?this.finishDraft({switchToSelect:!1}):this.cancelDraft())}isInInitialState(){return!this.hasDraft()&&super.isInInitialState()}startOrExtend(e,t){if(!this.draft){this.operation=this.editor.operations.begin({kind:"path.create",label:"shape.create",source:"user",history:"record"});const t=this.editor.getDefaultShapeProps("path"),n=`subpath:${QF+=1}`,o=lv(),i={id:o,x:0,y:0,kind:"corner"},[r]=this.editor.commands.createShapes([{type:"path",x:e.x,y:e.y,meta:xP({},{subpathId:n,previewNodeId:null}),props:{...t,subpaths:[{id:n,closed:!1,nodes:[i]}]}}],{source:"user",autoReparent:!1});if(!gI(r))throw this.cancelOperation(),new Error("Failed to create path shape");return this.editor.commands.setSelectedShapeIds([r.id],{source:"system"}),this.draft={shapeId:r.id,subpathId:n,lastNodeId:o,createdShape:!0,previewNodeId:null},$P(this.editor,"create",r.id,{onBoundaryUndo:()=>this.draft?.shapeId===r.id&&(this.cancelDraft(),this.editor.commands.setActiveTool("select",{source:"system"}),!0),onApply:e=>{const t=this.draft;if(!t||t.shapeId!==e.id)return;const n=HI(e.props.subpaths,t.subpathId);this.draft={...t,lastNodeId:n?.nodes.at(-1)?.id??t.lastNodeId,previewNodeId:null}}}),{shapeId:r.id,subpathId:n,nodeId:o,originPagePoint:e.clone(),startNode:II(i),finishOnPointerUp:!1}}const n=this.editor.getShape(this.draft.shapeId);if(!gI(n))return this.cancelDraft(),null;const o=t.shiftKey?uv(this.editor,n,this.draft.subpathId,this.draft.previewNodeId)??e:e,i=t.shiftKey?pv(o,e):e;if(function(e,t,n,o,i){const r=((e,t,n)=>{const o=HI(t.props.subpaths,n)?.nodes[0];return o?e.computeShapeLocalToPageTransform(t).applyToPoint(new $C(o.x,o.y)):null})(e,t,n),s=HI(t.props.subpaths,n),a=s?.nodes.filter(e=>e.id!==o).length??0;return!(!r||!s||a<3)&&r.dist(i)<=10/e.getCurrentCamera().z}(this.editor,n,this.draft.subpathId,this.draft.previewNodeId,e)){const t=this.draft,o=HI(n.props.subpaths,t.subpathId)?.nodes.find(e=>e.id!==t.previewNodeId);return o?(this.editor.commands.updateShapes([{id:n.id,meta:xP(n.meta,{subpathId:t.subpathId,previewNodeId:null}),props:{subpaths:hv(n.props.subpaths,t).map(e=>e.id===t.subpathId?{...e,closed:!0}:e)}}],{source:"user"}),this.draft={...t,previewNodeId:null},{shapeId:n.id,subpathId:t.subpathId,nodeId:o.id,originPagePoint:e.clone(),startNode:II(o),finishOnPointerUp:!0}):null}const r=cv(this.editor,n,i),s=this.draft.previewNodeId??lv(),a=n.props.subpaths.map(e=>e.id===this.draft?.subpathId?this.draft.previewNodeId?{...e,nodes:e.nodes.map(e=>e.id===this.draft?.previewNodeId?{id:s,x:r.x,y:r.y,kind:"corner"}:e)}:{...e,nodes:[...e.nodes,{id:s,x:r.x,y:r.y,kind:"corner"}]}:e);return this.editor.commands.updateShapes([{id:n.id,meta:xP(n.meta,{subpathId:this.draft.subpathId,previewNodeId:null}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,lastNodeId:s,previewNodeId:null},{shapeId:n.id,subpathId:this.draft.subpathId,nodeId:s,originPagePoint:e.clone(),startNode:{id:s,x:r.x,y:r.y,kind:"corner"},finishOnPointerUp:!1}}updateNodeDrag(e,t,n){const o=this.editor.getShape(e.shapeId);if(!gI(o))return;const i=n.shiftKey?pv(e.originPagePoint,t):t,r=cv(this.editor,o,e.originPagePoint),s=cv(this.editor,o,i),a=e.originPagePoint.dist(i)*this.editor.getCurrentCamera().z>=3,d=KI(o.props.subpaths,e.subpathId,e.nodeId,()=>a?((e,t,n)=>({...e,kind:n.altKey?"smooth":"symmetric",in:{dx:-t.x,dy:-t.y},out:{dx:t.x,dy:t.y}}))(e.startNode,s.sub(r),n):II(e.startNode));this.editor.commands.updateShapes([{id:o.id,meta:xP(o.meta,{subpathId:e.subpathId,previewNodeId:this.draft?.previewNodeId??null}),props:{subpaths:d}}],{source:"user"})}updatePreview(e,t){if(!this.draft)return;const n=this.editor.getShape(this.draft.shapeId);if(!gI(n)||gv(n,this.draft)<1)return;const o=t.shiftKey?uv(this.editor,n,this.draft.subpathId,this.draft.previewNodeId):null,i=o?pv(o,e):e,r=cv(this.editor,n,i),s=this.draft.previewNodeId??lv(),a=n.props.subpaths.map(e=>e.id!==this.draft?.subpathId?e:this.draft.previewNodeId?{...e,nodes:e.nodes.map(e=>e.id===this.draft?.previewNodeId?{id:s,x:r.x,y:r.y,kind:"corner"}:e)}:{...e,nodes:[...e.nodes,{id:s,x:r.x,y:r.y,kind:"corner"}]});this.editor.commands.updateShapes([{id:n.id,meta:xP(n.meta,{subpathId:this.draft.subpathId,previewNodeId:s}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,previewNodeId:s}}canFinishDraft(){if(!this.draft)return!1;const e=this.editor.getShape(this.draft.shapeId);return!!gI(e)&&gv(e,this.draft)>=2}finishDraft(e={}){if(!this.draft)return;const t=e.switchToSelect??!0,n=this.editor.getShape(this.draft.shapeId);if(gI(n)){const e=hv(n.props.subpaths,this.draft),t=zI(UI({...n,props:{...n.props,subpaths:e}},this.editor.computeShapeLocalToPageTransform(n)),n.props);this.editor.commands.updateShapes([{id:n.id,x:t.x,y:t.y,rotation:0,skewX:0,scaleX:1,scaleY:1,meta:wP(n.meta),props:{subpaths:t.subpaths}}],{source:"user"}),this.draft.createdShape&&Pe(this.editor,n.id,{source:"user"})}FP(this.editor,"create",this.draft.shapeId),this.commitOperation(),this.draft=null,t&&!this.editor.isToolLocked()&&this.editor.commands.setActiveTool("select",{source:"system"})}finishDraftAndEdit(){const e=this.draft?.shapeId;if(e){if(!this.canFinishDraft())return this.cancelDraft(),void(this.editor.isToolLocked()||this.editor.commands.setActiveTool("select",{source:"system"}));this.finishDraft({switchToSelect:!1}),gI(this.editor.getShape(e))&&(this.editor.commands.setActiveTool("select",{source:"system"}),this.editor.startEditingShape({shapeId:e,markId:"path.edit",entryMode:"focusEnd"},"user"))}}cancelDraft(){this.draft&&(FP(this.editor,"create",this.draft.shapeId),this.cancelOperation(),this.draft=null)}hasDraft(){return null!==this.draft}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}},eO=class extends zT{tool;constructor(e,t){super(e,"idle",t),this.tool=t}onPointerDown(e){if(0!==e.button)return;const t=this.tool.startOrExtend(e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey});t&&this.transition("dragging_node",t)}onPointerMove(e){this.tool.updatePreview(e.pagePoint,{shiftKey:e.shiftKey})}onKeyDown(e){("Enter"===e.key&&this.tool.hasDraft()||"Escape"===e.key&&this.tool.hasDraft())&&this.tool.finishDraftAndEdit()}onCancel(e){"escape"===e.reason&&this.tool.hasDraft()&&this.tool.finishDraftAndEdit()}},tO=class extends zT{tool;info=null;constructor(e,t){super(e,"dragging_node",t),this.tool=t}onEnter(e){this.info=e}onPointerMove(e){this.info&&this.tool.updateNodeDrag(this.info,e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey})}onPointerUp(e){const t=this.info;t&&(this.tool.updateNodeDrag(t,e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey}),LP(this.editor,t.shapeId)),this.transition("idle"),t?.finishOnPointerUp&&this.tool.finishDraft()}onCancel(){this.tool.cancelDraft(),this.transition("idle")}onExit(){this.info=null}},nO=PC((e,t)=>{var n,o;n=e,o=function(){function e(e,t){return e>t?1:e<t?-1:0}function t(e,t,n){for(var o=new c(null,null),i=o,r=o;;){var s=n(e,t.key);if(s<0){if(null===t.left)break;if(n(e,t.left.key)<0&&(t.left=(a=t.left).right,a.right=t,null===(t=a).left))break;r.left=t,r=t,t=t.left}else{if(!(s>0))break;if(null===t.right)break;var a;if(n(e,t.right.key)>0&&(t.right=(a=t.right).left,a.left=t,null===(t=a).right))break;i.right=t,i=t,t=t.right}}return i.right=t.left,r.left=t.right,t.left=o.right,t.right=o.left,t}function n(e,n,o,i){var r=new c(e,n);if(null===o)return r.left=r.right=null,r;var s=i(e,(o=t(e,o,i)).key);return s<0?(r.left=o.left,r.right=o,o.left=null):s>=0&&(r.right=o.right,r.left=o,o.right=null),r}function o(e,n,o){var i=null,r=null;if(n){var s=o((n=t(e,n,o)).key,e);0===s?(i=n.left,r=n.right):s<0?(r=n.right,n.right=null,i=n):(i=n.left,n.left=null,r=n)}return{left:i,right:r}}function i(e,t,n,o,r){if(e){o(t+(n?"└── ":"├── ")+r(e)+"\n");var s=t+(n?" ":"│ ");e.left&&i(e.left,s,!1,o,r),e.right&&i(e.right,s,!0,o,r)}}function r(e,t,n,o){var i=o-n;if(i>0){var s=n+Math.floor(i/2),a=new c(e[s],t[s]);return a.left=r(e,t,n,s),a.right=r(e,t,s+1,o),a}return null}function s(e,t,n){var o=n-t;if(o>0){var i=t+Math.floor(o/2),r=s(e,t,i),a=e.head;return a.left=r,e.head=e.head.next,a.right=s(e,i+1,n),a}return null}function a(e,t,n,o,i){if(!(n>=o)){for(var r=e[n+o>>1],s=n-1,d=o+1;;){do{s++}while(i(e[s],r)<0);do{d--}while(i(e[d],r)>0);if(s>=d)break;var l=e[s];e[s]=e[d],e[d]=l,l=t[s],t[s]=t[d],t[d]=l}a(e,t,n,d,i),a(e,t,d+1,o,i)}}function d(e,t,n,o,i){let r,s,a,d,l=t[0],c=o[0],u=0,p=0;c>l==c>-l?(r=l,l=t[++u]):(r=c,c=o[++p]);let h=0;if(u<e&&p<n)for(c>l==c>-l?(s=l+r,a=r-(s-l),l=t[++u]):(s=c+r,a=r-(s-c),c=o[++p]),r=s,0!==a&&(i[h++]=a);u<e&&p<n;)c>l==c>-l?(s=r+l,d=s-r,a=r-(s-d)+(l-d),l=t[++u]):(s=r+c,d=s-r,a=r-(s-d)+(c-d),c=o[++p]),r=s,0!==a&&(i[h++]=a);for(;u<e;)s=r+l,d=s-r,a=r-(s-d)+(l-d),l=t[++u],r=s,0!==a&&(i[h++]=a);for(;p<n;)s=r+c,d=s-r,a=r-(s-d)+(c-d),c=o[++p],r=s,0!==a&&(i[h++]=a);return 0===r&&0!==h||(i[h++]=r),h}function l(e){return new Float64Array(e)}var c=function(e,t){this.next=null,this.key=e,this.data=t,this.left=null,this.right=null},u=function(){function d(t){void 0===t&&(t=e),this._root=null,this._size=0,this._comparator=t}return d.prototype.insert=function(e,t){return this._size++,this._root=n(e,t,this._root,this._comparator)},d.prototype.add=function(e,n){var o=new c(e,n);null===this._root&&(o.left=o.right=null,this._size++,this._root=o);var i=this._comparator,r=t(e,this._root,i),s=i(e,r.key);return 0===s?this._root=r:(s<0?(o.left=r.left,o.right=r,r.left=null):s>0&&(o.right=r.right,o.left=r,r.right=null),this._size++,this._root=o),this._root},d.prototype.remove=function(e){this._root=this._remove(e,this._root,this._comparator)},d.prototype._remove=function(e,n,o){var i;return null===n?null:0===o(e,(n=t(e,n,o)).key)?(null===n.left?i=n.right:(i=t(e,n.left,o)).right=n.right,this._size--,i):n},d.prototype.pop=function(){var e=this._root;if(e){for(;e.left;)e=e.left;return this._root=t(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null},d.prototype.findStatic=function(e){for(var t=this._root,n=this._comparator;t;){var o=n(e,t.key);if(0===o)return t;t=o<0?t.left:t.right}return null},d.prototype.find=function(e){return this._root&&(this._root=t(e,this._root,this._comparator),0!==this._comparator(e,this._root.key))?null:this._root},d.prototype.contains=function(e){for(var t=this._root,n=this._comparator;t;){var o=n(e,t.key);if(0===o)return!0;t=o<0?t.left:t.right}return!1},d.prototype.forEach=function(e,t){for(var n=this._root,o=[],i=!1;!i;)null!==n?(o.push(n),n=n.left):0!==o.length?(n=o.pop(),e.call(t,n),n=n.right):i=!0;return this},d.prototype.range=function(e,t,n,o){for(var i=[],r=this._comparator,s=this._root;0!==i.length||s;)if(s)i.push(s),s=s.left;else{if(r((s=i.pop()).key,t)>0)break;if(r(s.key,e)>=0&&n.call(o,s))return this;s=s.right}return this},d.prototype.keys=function(){var e=[];return this.forEach(t=>e.push(t.key)),e},d.prototype.values=function(){var e=[];return this.forEach(t=>e.push(t.data)),e},d.prototype.min=function(){return this._root?this.minNode(this._root).key:null},d.prototype.max=function(){return this._root?this.maxNode(this._root).key:null},d.prototype.minNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.left;)e=e.left;return e},d.prototype.maxNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.right;)e=e.right;return e},d.prototype.at=function(e){for(var t=this._root,n=!1,o=0,i=[];!n;)if(t)i.push(t),t=t.left;else if(i.length>0){if(t=i.pop(),o===e)return t;o++,t=t.right}else n=!0;return null},d.prototype.next=function(e){var t=this._root,n=null;if(e.right){for(n=e.right;n.left;)n=n.left;return n}for(var o=this._comparator;t;){var i=o(e.key,t.key);if(0===i)break;i<0?(n=t,t=t.left):t=t.right}return n},d.prototype.prev=function(e){var t=this._root,n=null;if(null!==e.left){for(n=e.left;n.right;)n=n.right;return n}for(var o=this._comparator;t;){var i=o(e.key,t.key);if(0===i)break;i<0?t=t.left:(n=t,t=t.right)}return n},d.prototype.clear=function(){return this._root=null,this._size=0,this},d.prototype.toList=function(){return(()=>{for(var e=this._root,t=[],n=!1,o=new c(null,null),i=o;!n;)e?(t.push(e),e=e.left):t.length>0?e=(e=i=i.next=t.pop()).right:n=!0;return i.next=null,o.next})()},d.prototype.load=function(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=!1);var o=e.length,i=this._comparator;if(n&&a(e,t,0,o-1,i),null===this._root)this._root=r(e,t,0,o),this._size=o;else{var d=((e,t,n)=>{for(var o=new c(null,null),i=o,r=e,s=t;null!==r&&null!==s;)n(r.key,s.key)<0?(i.next=r,r=r.next):(i.next=s,s=s.next),i=i.next;return null!==r?i.next=r:null!==s&&(i.next=s),o.next})(this.toList(),((e,t)=>{for(var n=new c(null,null),o=n,i=0;i<e.length;i++)o=o.next=new c(e[i],t[i]);return o.next=null,n.next})(e,t),i);this._root=s({head:d},0,o=this._size+o)}return this},d.prototype.isEmpty=function(){return null===this._root},Object.defineProperty(d.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(d.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),d.prototype.toString=function(e){void 0===e&&(e=e=>String(e.key));var t=[];return i(this._root,"",!0,e=>t.push(e),e),t.join("")},d.prototype.update=function(e,i,r){var s=this._comparator,a=o(e,this._root,s),d=a.left,l=a.right;s(e,i)<0?l=n(i,r,l,s):d=n(i,r,d,s),this._root=((e,n,o)=>null===n?e:(null===e||((n=t(e.key,n,o)).left=e),n))(d,l,s)},d.prototype.split=function(e){return o(e,this._root,this._comparator)},d.prototype[Symbol.iterator]=function(){var e,t,n;return function(e,t){function n(n){return s=>(n=>{if(o)throw new TypeError("Generator is already executing.");for(;a;)try{if(o=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,i=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==n[0]&&2!==n[0])){a=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){a.label=n[1];break}if(6===n[0]&&a.label<r[1]){a.label=r[1],r=n;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(n);break}r[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}catch(s){n=[6,s],i=0}finally{o=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}})([n,s])}var o,i,r,s,a={label:0,sent:()=>{if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s}(this,function(o){switch(o.label){case 0:e=this._root,t=[],n=!1,o.label=1;case 1:return n?[3,6]:null===e?[3,2]:(t.push(e),e=e.left,[3,5]);case 2:return 0===t.length?[3,4]:[4,e=t.pop()];case 3:return o.sent(),e=e.right,[3,5];case 4:n=!0,o.label=5;case 5:return[3,1];case 6:return[2]}})},d}();const p=(e,t)=>e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y,h=(e,t)=>t.ur.x<e.ll.x||e.ur.x<t.ll.x||t.ur.y<e.ll.y||e.ur.y<t.ll.y?null:{ll:{x:e.ll.x<t.ll.x?t.ll.x:e.ll.x,y:e.ll.y<t.ll.y?t.ll.y:e.ll.y},ur:{x:e.ur.x<t.ur.x?e.ur.x:t.ur.x,y:e.ur.y<t.ur.y?e.ur.y:t.ur.y}};let g=Number.EPSILON;void 0===g&&(g=Math.pow(2,-52));const f=g*g,m=(e,t)=>{if(-g<e&&e<g&&-g<t&&t<g)return 0;const n=e-t;return n*n<f*e*t?0:e<t?-1:1};class y{constructor(){this.tree=new u,this.round(0)}round(e){const t=this.tree.add(e),n=this.tree.prev(t);if(null!==n&&0===m(t.key,n.key))return this.tree.remove(e),n.key;const o=this.tree.next(t);return null!==o&&0===m(t.key,o.key)?(this.tree.remove(e),o.key):e}}const S=new class{constructor(){this.reset()}reset(){this.xRounder=new y,this.yRounder=new y}round(e,t){return{x:this.xRounder.round(e),y:this.yRounder.round(t)}}},b=134217729,x=l(4),w=l(8),I=l(12),P=l(16),v=l(4),k=(e,t)=>e.x*t.y-e.y*t.x,C=(e,t)=>e.x*t.x+e.y*t.y,T=(e,t,n)=>{const o=function(e,t,n,o,i,r){const s=(t-r)*(n-i),a=(e-i)*(o-r),l=s-a,c=Math.abs(s+a);return Math.abs(l)>=33306690738754716e-32*c?l:-((e,t,n,o,i,r,s)=>{let a,l,c,u,p,h,g,f,m,y,S,k,C,T,M,E,B,A;const R=e-i,$=n-i,L=t-r,F=o-r;T=R*F,h=b*R,g=h-(h-R),f=R-g,h=b*F,m=h-(h-F),y=F-m,M=f*y-(T-g*m-f*m-g*y),E=L*$,h=b*L,g=h-(h-L),f=L-g,h=b*$,m=h-(h-$),y=$-m,B=f*y-(E-g*m-f*m-g*y),S=M-B,p=M-S,x[0]=M-(S+p)+(p-B),k=T+S,p=k-T,C=T-(k-p)+(S-p),S=C-E,p=C-S,x[1]=C-(S+p)+(p-E),A=k+S,p=A-k,x[2]=k-(A-p)+(S-p),x[3]=A;let O=((e,t)=>{let n=t[0];for(let o=1;o<4;o++)n+=t[o];return n})(0,x),D=22204460492503146e-32*s;if(O>=D||-O>=D)return O;if(p=e-R,a=e-(R+p)+(p-i),p=n-$,c=n-($+p)+(p-i),p=t-L,l=t-(L+p)+(p-r),p=o-F,u=o-(F+p)+(p-r),0===a&&0===l&&0===c&&0===u)return O;if(D=11093356479670487e-47*s+33306690738754706e-32*Math.abs(O),O+=R*u+F*a-(L*c+$*l),O>=D||-O>=D)return O;T=a*F,h=b*a,g=h-(h-a),f=a-g,h=b*F,m=h-(h-F),y=F-m,M=f*y-(T-g*m-f*m-g*y),E=l*$,h=b*l,g=h-(h-l),f=l-g,h=b*$,m=h-(h-$),y=$-m,B=f*y-(E-g*m-f*m-g*y),S=M-B,p=M-S,v[0]=M-(S+p)+(p-B),k=T+S,p=k-T,C=T-(k-p)+(S-p),S=C-E,p=C-S,v[1]=C-(S+p)+(p-E),A=k+S,p=A-k,v[2]=k-(A-p)+(S-p),v[3]=A;const z=d(4,x,4,v,w);T=R*u,h=b*R,g=h-(h-R),f=R-g,h=b*u,m=h-(h-u),y=u-m,M=f*y-(T-g*m-f*m-g*y),E=L*c,h=b*L,g=h-(h-L),f=L-g,h=b*c,m=h-(h-c),y=c-m,B=f*y-(E-g*m-f*m-g*y),S=M-B,p=M-S,v[0]=M-(S+p)+(p-B),k=T+S,p=k-T,C=T-(k-p)+(S-p),S=C-E,p=C-S,v[1]=C-(S+p)+(p-E),A=k+S,p=A-k,v[2]=k-(A-p)+(S-p),v[3]=A;const U=d(z,w,4,v,I);return T=a*u,h=b*a,g=h-(h-a),f=a-g,h=b*u,m=h-(h-u),y=u-m,M=f*y-(T-g*m-f*m-g*y),E=l*c,h=b*l,g=h-(h-l),f=l-g,h=b*c,m=h-(h-c),y=c-m,B=f*y-(E-g*m-f*m-g*y),S=M-B,p=M-S,v[0]=M-(S+p)+(p-B),k=T+S,p=k-T,C=T-(k-p)+(S-p),S=C-E,p=C-S,v[1]=C-(S+p)+(p-E),A=k+S,p=A-k,v[2]=k-(A-p)+(S-p),v[3]=A,P[d(U,I,4,v,P)-1]})(e,t,n,o,i,r,c)}(e.x,e.y,t.x,t.y,n.x,n.y);return o>0?-1:o<0?1:0},M=e=>Math.sqrt(C(e,e)),E=(e,t,n)=>{const o={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return k(i,o)/M(i)/M(o)},B=(e,t,n)=>{const o={x:t.x-e.x,y:t.y-e.y},i={x:n.x-e.x,y:n.y-e.y};return C(i,o)/M(i)/M(o)},A=(e,t,n)=>0===t.y?null:{x:e.x+t.x/t.y*(n-e.y),y:n},R=(e,t,n)=>0===t.x?null:{x:n,y:e.y+t.y/t.x*(n-e.x)};class ${static compare(e,t){const n=$.comparePoints(e.point,t.point);return 0!==n?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:F.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x<t.x?-1:e.x>t.x?1:e.y<t.y?-1:e.y>t.y?1:0}constructor(e,t){void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,o=t.length;n<o;n++){const e=t[n];this.point.events.push(e),e.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let t=0;t<e;t++){const n=this.point.events[t];if(void 0===n.segment.consumedBy)for(let o=t+1;o<e;o++){const e=this.point.events[o];void 0===e.consumedBy&&n.otherSE.point.events===e.otherSE.point.events&&n.segment.consume(e.segment)}}}getAvailableLinkedEvents(){const e=[];for(let t=0,n=this.point.events.length;t<n;t++){const n=this.point.events[t];n!==this&&!n.segment.ringOut&&n.segment.isInResult()&&e.push(n)}return e}getLeftmostComparator(e){const t=new Map,n=n=>{const o=n.otherSE;t.set(n,{sine:E(this.point,e.point,o.point),cosine:B(this.point,e.point,o.point)})};return(e,o)=>{t.has(e)||n(e),t.has(o)||n(o);const{sine:i,cosine:r}=t.get(e),{sine:s,cosine:a}=t.get(o);return i>=0&&s>=0?r<a?1:r>a?-1:0:i<0&&s<0?r<a?-1:r>a?1:0:s<i?-1:s>i?1:0}}}let L=0;class F{static compare(e,t){const n=e.leftSE.point.x,o=t.leftSE.point.x,i=e.rightSE.point.x,r=t.rightSE.point.x;if(r<n)return 1;if(i<o)return-1;const s=e.leftSE.point.y,a=t.leftSE.point.y,d=e.rightSE.point.y,l=t.rightSE.point.y;if(n<o){if(a<s&&a<d)return 1;if(a>s&&a>d)return-1;const n=e.comparePoint(t.leftSE.point);if(n<0)return 1;if(n>0)return-1;const o=t.comparePoint(e.rightSE.point);return 0!==o?o:-1}if(n>o){if(s<a&&s<l)return-1;if(s>a&&s>l)return 1;const n=t.comparePoint(e.leftSE.point);if(0!==n)return n;const o=e.comparePoint(t.rightSE.point);return o<0?1:o>0?-1:1}if(s<a)return-1;if(s>a)return 1;if(i<r){const n=t.comparePoint(e.rightSE.point);if(0!==n)return n}if(i>r){const n=e.comparePoint(t.rightSE.point);if(n<0)return 1;if(n>0)return-1}if(i!==r){const e=d-s,t=i-n,c=l-a,u=r-o;if(e>t&&c<u)return 1;if(e<t&&c>u)return-1}return i>r?1:i<r||d<l?-1:d>l?1:e.id<t.id?-1:e.id>t.id?1:0}constructor(e,t,n,o){this.id=++L,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=n,this.windings=o}static fromRing(e,t,n){let o,i,r;const s=$.comparePoints(e,t);if(s<0)o=e,i=t,r=1;else{if(!(s>0))throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);o=t,i=e,r=-1}return new F(new $(o,!0),new $(i,!1),[n],[r])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<t?e:t},ur:{x:this.rightSE.point.x,y:e>t?e:t}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const t=this.leftSE.point,n=this.rightSE.point,o=this.vector();if(t.x===n.x)return e.x===t.x?0:e.x<t.x?1:-1;if(e.x===t.x+(e.y-t.y)/o.y*o.x)return 0;const i=t.y+(e.x-t.x)/o.x*o.y;return e.y===i?0:e.y<i?-1:1}getIntersection(e){const t=this.bbox(),n=e.bbox(),o=h(t,n);if(null===o)return null;const i=this.leftSE.point,r=this.rightSE.point,s=e.leftSE.point,a=e.rightSE.point,d=p(t,s)&&0===this.comparePoint(s),l=p(n,i)&&0===e.comparePoint(i),c=p(t,a)&&0===this.comparePoint(a),u=p(n,r)&&0===e.comparePoint(r);if(l&&d)return u&&!c?r:!u&&c?a:null;if(l)return c&&i.x===a.x&&i.y===a.y?null:i;if(d)return u&&r.x===s.x&&r.y===s.y?null:s;if(u&&c)return null;if(u)return r;if(c)return a;const g=((e,t,n,o)=>{if(0===t.x)return R(n,o,e.x);if(0===o.x)return R(e,t,n.x);if(0===t.y)return A(n,o,e.y);if(0===o.y)return A(e,t,n.y);const i=k(t,o);if(0==i)return null;const r={x:n.x-e.x,y:n.y-e.y},s=k(r,t)/i,a=k(r,o)/i;return{x:(e.x+a*t.x+(n.x+s*o.x))/2,y:(e.y+a*t.y+(n.y+s*o.y))/2}})(i,this.vector(),s,e.vector());return null===g?null:p(o,g)?S.round(g.x,g.y):null}split(e){const t=[],n=void 0!==e.events,o=new $(e,!0),i=new $(e,!1),r=this.rightSE;this.replaceRightSE(i),t.push(i),t.push(o);const s=new F(o,r,this.rings.slice(),this.windings.slice());return $.comparePoints(s.leftSE.point,s.rightSE.point)>0&&s.swapEvents(),$.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(o.checkForConsuming(),i.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t<n;t++)this.windings[t]*=-1}consume(e){let t=this,n=e;for(;t.consumedBy;)t=t.consumedBy;for(;n.consumedBy;)n=n.consumedBy;const o=F.compare(t,n);if(0!==o){if(o>0){const e=t;t=n,n=e}if(t.prev===n){const e=t;t=n,n=e}for(let e=0,o=n.rings.length;e<o;e++){const o=n.rings[e],i=n.windings[e],r=t.rings.indexOf(o);-1===r?(t.rings.push(o),t.windings.push(i)):t.windings[r]+=i}n.rings=null,n.windings=null,n.consumedBy=t,n.leftSE.consumedBy=t.leftSE,n.rightSE.consumedBy=t.rightSE}}prevInResult(){return void 0!==this._prevInResult||(this._prevInResult=this.prev?this.prev.isInResult()?this.prev:this.prev.prevInResult():null),this._prevInResult}beforeState(){return void 0!==this._beforeState||(this._beforeState=this.prev?(this.prev.consumedBy||this.prev).afterState():{rings:[],windings:[],multiPolys:[]}),this._beforeState}afterState(){if(void 0!==this._afterState)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const t=this._afterState.rings,n=this._afterState.windings,o=this._afterState.multiPolys;for(let s=0,a=this.rings.length;s<a;s++){const e=this.rings[s],o=this.windings[s],i=t.indexOf(e);-1===i?(t.push(e),n.push(o)):n[i]+=o}const i=[],r=[];for(let s=0,a=t.length;s<a;s++){if(0===n[s])continue;const e=t[s],o=e.poly;if(-1===r.indexOf(o))if(e.isExterior)i.push(o);else{-1===r.indexOf(o)&&r.push(o);const t=i.indexOf(e.poly);-1!==t&&i.splice(t,1)}}for(let s=0,a=i.length;s<a;s++){const e=i[s].multiPoly;-1===o.indexOf(e)&&o.push(e)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(void 0!==this._isInResult)return this._isInResult;const e=this.beforeState().multiPolys,t=this.afterState().multiPolys;switch(_.type){case"union":this._isInResult=0===e.length!=(0===t.length);break;case"intersection":{let n,o;e.length<t.length?(n=e.length,o=t.length):(n=t.length,o=e.length),this._isInResult=o===_.numMultiPolys&&n<o;break}case"xor":{const n=Math.abs(e.length-t.length);this._isInResult=n%2==1;break}case"difference":{const n=e=>1===e.length&&e[0].isSubject;this._isInResult=n(e)!==n(t);break}default:throw new Error(`Unrecognized operation type found ${_.type}`)}return this._isInResult}}class O{constructor(e,t,n){if(!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=n,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const o=S.round(e[0][0],e[0][1]);this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};let i=o;for(let r=1,s=e.length;r<s;r++){if("number"!=typeof e[r][0]||"number"!=typeof e[r][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let t=S.round(e[r][0],e[r][1]);t.x===i.x&&t.y===i.y||(this.segments.push(F.fromRing(i,t,this)),t.x<this.bbox.ll.x&&(this.bbox.ll.x=t.x),t.y<this.bbox.ll.y&&(this.bbox.ll.y=t.y),t.x>this.bbox.ur.x&&(this.bbox.ur.x=t.x),t.y>this.bbox.ur.y&&(this.bbox.ur.y=t.y),i=t)}o.x===i.x&&o.y===i.y||this.segments.push(F.fromRing(i,o,this))}getSweepEvents(){const e=[];for(let t=0,n=this.segments.length;t<n;t++){const n=this.segments[t];e.push(n.leftSE),e.push(n.rightSE)}return e}}class D{constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new O(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let n=1,o=e.length;n<o;n++){const t=new O(e[n],this,!1);t.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=t.bbox.ur.y),this.interiorRings.push(t)}this.multiPoly=t}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let t=0,n=this.interiorRings.length;t<n;t++){const n=this.interiorRings[t].getSweepEvents();for(let t=0,o=n.length;t<o;t++)e.push(n[t])}return e}}class z{constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{"number"==typeof e[0][0][0]&&(e=[e])}catch(n){}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let o=0,i=e.length;o<i;o++){const t=new D(e[o],this);t.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=t.bbox.ur.y),this.polys.push(t)}this.isSubject=t}getSweepEvents(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const n=this.polys[t].getSweepEvents();for(let t=0,o=n.length;t<o;t++)e.push(n[t])}return e}}class U{static factory(e){const t=[];for(let n=0,o=e.length;n<o;n++){const o=e[n];if(!o.isInResult()||o.ringOut)continue;let i=null,r=o.leftSE,s=o.rightSE;const a=[r],d=r.point,l=[];for(;i=r,r=s,a.push(r),r.point!==d;)for(;;){const e=r.getAvailableLinkedEvents();if(0===e.length){const e=a[0].point,t=a[a.length-1].point;throw new Error(`Unable to complete output ring starting at [${e.x}, ${e.y}]. Last matching segment found ends at [${t.x}, ${t.y}].`)}if(1===e.length){s=e[0].otherSE;break}let n=null;for(let t=0,i=l.length;t<i;t++)if(l[t].point===r.point){n=t;break}if(null!==n){const e=l.splice(n)[0],o=a.splice(e.index);o.unshift(o[0].otherSE),t.push(new U(o.reverse()));continue}l.push({index:a.length,point:r.point});const o=r.getLeftmostComparator(i);s=e.sort(o)[0].otherSE;break}t.push(new U(a))}return t}constructor(e){this.events=e;for(let t=0,n=e.length;t<n;t++)e[t].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const t=[e];for(let s=1,a=this.events.length-1;s<a;s++){const n=this.events[s].point;0!==T(n,e,this.events[s+1].point)&&(t.push(n),e=n)}if(1===t.length)return null;0===T(t[0],e,t[1])&&t.shift(),t.push(t[0]);const n=this.isExteriorRing()?1:-1,o=this.isExteriorRing()?0:t.length-1,i=this.isExteriorRing()?t.length:-1,r=[];for(let s=o;s!=i;s+=n)r.push([t[s].x,t[s].y]);return r}isExteriorRing(){if(void 0===this._isExteriorRing){const e=this.enclosingRing();this._isExteriorRing=!e||!e.isExteriorRing()}return this._isExteriorRing}enclosingRing(){return void 0===this._enclosingRing&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let o=1,i=this.events.length;o<i;o++){const t=this.events[o];$.compare(e,t)>0&&(e=t)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return n.ringOut.enclosingRing()!==t.ringOut?t.ringOut:t.ringOut.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}}class N{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(null===e[0])return null;for(let t=0,n=this.interiorRings.length;t<n;t++){const n=this.interiorRings[t].getGeom();null!==n&&e.push(n)}return e}}class W{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const n=this.polys[t].getGeom();null!==n&&e.push(n)}return e}_composePolys(e){const t=[];for(let n=0,o=e.length;n<o;n++){const o=e[n];if(!o.poly)if(o.isExteriorRing())t.push(new N(o));else{const e=o.enclosingRing();e.poly||t.push(new N(e)),e.poly.addInterior(o)}}return t}}class X{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:F.compare;this.queue=e,this.tree=new u(t),this.segments=[]}process(e){const t=e.segment,n=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(t),n;const o=e.isLeft?this.tree.add(t):this.tree.find(t);if(!o)throw new Error(`Unable to find segment #${t.id} [${t.leftSE.point.x}, ${t.leftSE.point.y}] -> [${t.rightSE.point.x}, ${t.rightSE.point.y}] in SweepLine tree.`);let i,r,s=o,a=o;for(;void 0===i;)s=this.tree.prev(s),null===s?i=null:void 0===s.key.consumedBy&&(i=s.key);for(;void 0===r;)a=this.tree.next(a),null===a?r=null:void 0===a.key.consumedBy&&(r=a.key);if(e.isLeft){let o=null;if(i){const e=i.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(o=e),!i.isAnEndpoint(e))){const t=this._splitSafely(i,e);for(let e=0,o=t.length;e<o;e++)n.push(t[e])}}let s=null;if(r){const e=r.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(s=e),!r.isAnEndpoint(e))){const t=this._splitSafely(r,e);for(let e=0,o=t.length;e<o;e++)n.push(t[e])}}if(null!==o||null!==s){let e=null;e=null===o?s:null===s||$.comparePoints(o,s)<=0?o:s,this.queue.remove(t.rightSE),n.push(t.rightSE);const i=t.split(e);for(let t=0,o=i.length;t<o;t++)n.push(i[t])}n.length>0?(this.tree.remove(t),n.push(e)):(this.segments.push(t),t.prev=i)}else{if(i&&r){const e=i.getIntersection(r);if(null!==e){if(!i.isAnEndpoint(e)){const t=this._splitSafely(i,e);for(let e=0,o=t.length;e<o;e++)n.push(t[e])}if(!r.isAnEndpoint(e)){const t=this._splitSafely(r,e);for(let e=0,o=t.length;e<o;e++)n.push(t[e])}}}this.tree.remove(t)}return n}_splitSafely(e,t){this.tree.remove(e);const n=e.rightSE;this.queue.remove(n);const o=e.split(t);return o.push(n),void 0===e.consumedBy&&this.tree.add(e),o}}const Y="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,H="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6,_=new class{run(e,t,n){_.type=e,S.reset();const o=[new z(t,!0)];for(let d=0,l=n.length;d<l;d++)o.push(new z(n[d],!1));if(_.numMultiPolys=o.length,"difference"===_.type){const e=o[0];let t=1;for(;t<o.length;)null!==h(o[t].bbox,e.bbox)?t++:o.splice(t,1)}if("intersection"===_.type)for(let d=0,l=o.length;d<l;d++){const e=o[d];for(let t=d+1,n=o.length;t<n;t++)if(null===h(e.bbox,o[t].bbox))return[]}const i=new u($.compare);for(let d=0,l=o.length;d<l;d++){const e=o[d].getSweepEvents();for(let t=0,n=e.length;t<n;t++)if(i.insert(e[t]),i.size>Y)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const r=new X(i);let s=i.size,a=i.pop();for(;a;){const e=a.key;if(i.size===s){const t=e.segment;throw new Error(`Unable to pop() ${e.isLeft?"left":"right"} SweepEvent [${e.point.x}, ${e.point.y}] from segment #${t.id} [${t.leftSE.point.x}, ${t.leftSE.point.y}] -> [${t.rightSE.point.x}, ${t.rightSE.point.y}] from queue.`)}if(i.size>Y)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(r.segments.length>H)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const t=r.process(e);for(let n=0,o=t.length;n<o;n++){const e=t[n];void 0===e.consumedBy&&i.insert(e)}s=i.size,a=i.pop()}return S.reset(),new W(U.factory(r.segments)).getGeom()}};return{union:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return _.run("union",e,n)},intersection:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return _.run("intersection",e,n)},xor:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return _.run("xor",e,n)},difference:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return _.run("difference",e,n)}}},"object"==typeof e&&void 0!==t?t.exports=o():"function"==typeof define&&define.amd?define(o):(n="undefined"!=typeof globalThis?globalThis:n||self).polygonClipping=o()}),oO=nO(),iO=1,rO=1,sO="path.edit",aO="path.edit.done",dO="path.edit.snap-nodes",lO="path.boolean.union",cO="path.boolean.subtract",uO="path.boolean.intersect",pO="path.boolean.xor",hO="path.node.delete",gO="path.node.make-curve",fO="path.node.remove-handles",mO="path.node.merge",yO="path.node.join",SO="path.node.separate",bO=[{id:"none",value:B("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:E("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:E("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:E("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:E("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],xO=[{value:E("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:E("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:E("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:E("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],wO={id:"path",editor:{id:"land.path",shapeCapabilities:[{type:"path",schemaProps:["subpaths","fill","stroke","strokeWidth","fillRule"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Path owns editable Bezier node geometry, multi-subpath fill rules, SVG export, and destructive polygon-clipping boolean materialization."]}],shapeUtils:[new class extends DT{type="path";getDefaultProps(){return{subpaths:[{id:"subpath:default",closed:!1,nodes:[{id:"node:0",x:0,y:0,kind:"corner"},{id:"node:1",x:96,y:0,kind:"corner"}]}],fill:B("transparent"),stroke:E("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{subpaths:(i=iv(t.subpaths,n.subpaths),i.map(e=>({...e,nodes:e.nodes.filter(e=>xI(e.x)&&xI(e.y))})).filter(e=>e.nodes.length>0).map(PI)),fill:F(t.fill,n.fill),stroke:F(t.stroke,n.stroke),strokeWidth:Math.max(1,nv(t.strokeWidth,n.strokeWidth)),fillRule:(o=t.fillRule,"string"==typeof o&&AF.includes(o)?t.fillRule:n.fillRule)};var o,i}getPositionedBounds(e){const t=FI(e).localBounds;return new LC(e.x+t.x,e.y+t.y,t.w,t.h)}getLocalBounds(e){return FI(e).localBounds}getRenderBounds(e){return FI(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}getSelectionResizeLocalBounds(e){return FI(e).pointBounds}resizeSelectionBounds(e,t){const n=UI(e,this.getLocalToPageTransform(e)).map(e=>({...e,nodes:e.nodes.map(e=>dv(e,e=>((e,t)=>0===t.selectionRotation?e:$C.RotWith(e,t.selectionRotationCenter,-t.selectionRotation))(e,t)))})),o=zI(((e,t)=>{const n=FI(e).pointBounds,o=0===n.w?1:t.w/Math.max(n.w,1e-6),i=0===n.h?1:t.h/Math.max(n.h,1e-6);return DI(e.props.subpaths,e=>new $C(0===n.w?t.center.x:t.x+(e.x-n.x)*o,0===n.h?t.center.y:t.y+(e.y-n.y)*i))})({...e,x:0,y:0,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{...e.props,subpaths:n}},t.selectionLocalBounds).map(e=>({...e,nodes:e.nodes.map(e=>dv(e,e=>((e,t)=>0===t.selectionRotation?e:$C.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(e,t)))})),e.props);return{id:e.id,x:o.x,y:o.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{subpaths:o.subpaths}}}getPositionedOutlineVertices(e){return FI(e).outlineVertices.map(t=>new $C(e.x+t.x,e.y+t.y))}getTerminalBindingOutlines(e){return FI(e).flattenedSubpaths.filter(e=>e.points.length>0).map(t=>({points:t.points.map(t=>new $C(e.x+t.x,e.y+t.y)),closed:t.closed}))}resolveBindingPoint(e,t){const n=t.editor.computeShapePositionedToPageTransform(e),o=n.tryInvert();if(!o)return t.rawPagePoint;const i=o.applyToPoint(t.rawPagePoint),r=o.applyToPoint(t.oppositePagePoint),s=r.sub(i);let a=Number.POSITIVE_INFINITY;for(const d of this.getTerminalBindingOutlines(e)){const e=d.closed?d.points.length:Math.max(0,d.points.length-1);for(let t=0;t<e;t+=1){const e=d.points[t],n=d.points[(t+1)%d.points.length];if(!e||!n)continue;const o=av(i,r,e,n);null!==o&&o>1e-6&&o<a&&(a=o)}}return Number.isFinite(a)?n.applyToPoint(i.add(s.mul(a))):t.rawPagePoint}getHandleSnapGeometry(e){return{points:e.props.subpaths.flatMap(e=>e.nodes.flatMap(e=>[{point:kI(e),kind:"custom"},...e.in?[{point:CI(e),kind:"custom"}]:[],...e.out?[{point:TI(e),kind:"custom"}]:[]])),outline:FI(e).outlineVertices}}canReceiveTerminalBinding(e){return!0}canEdit(e){return!0}canUseSelectionResizeHandles(e,t){return t.editor.getShapeEditingSession()?.shapeId!==e.id}canUseSelectionRotateHandle(e,t){return t.editor.getShapeEditingSession()?.shapeId!==e.id}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const o=t.editor.getShapeEditingSession();if(!o||o.shapeId!==e.id)return n;const i=t.editor.computeShapeLocalToPageTransform(e);return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=[{kind:"custom",type:MF,id:(o=e.id,r=t.id,["node",o,r].map(encodeURIComponent).join("|")),point:i.applyToPoint(kI(t)),cursor:"grab"}];var o,r;return t.in&&n.push({kind:"custom",type:EF,id:cI(e.id,t.id,"in"),point:i.applyToPoint(CI(t)),cursor:"grab"}),t.out&&n.push({kind:"custom",type:EF,id:cI(e.id,t.id,"out"),point:i.applyToPoint(TI(t)),cursor:"grab"}),n}))}}getSelectionOverlayInfo(e,t){const n=t.editor.getShapeEditingSession();return n&&n.shapeId===e.id?{usesSelectionPathOverlay:!0,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:NI(e,t.editor.computeShapeLocalToPageTransform(e)),pathStyle:null,bindingSegments:[]}:{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null,bindingSegments:[]}}hitTest(e,t,n){const o=new $C(t.x-e.x,t.y-e.y),i=FI(e);return!z(e.props.fill)&&((e,t,n)=>{let o=0,i=0;for(const r of e)if(r.closed&&!(r.points.length<3))for(let e=0;e<r.points.length;e+=1){const n=r.points[e],s=r.points[(e+1)%r.points.length];n&&s&&(n.y<=t.y&&s.y>t.y||n.y>t.y&&s.y<=t.y)&&n.x+(t.y-n.y)/(s.y-n.y)*(s.x-n.x)>t.x&&(i+=1,o+=s.y>n.y?1:-1)}return"evenodd"===n?i%2==1:0!==o})(i.flattenedSubpaths,o,e.props.fillRule)||((e,t,n)=>{const o=n*n;for(const i of e)for(let e=1;e<i.points.length;e+=1){const n=i.points[e-1],r=i.points[e];if(n&&r&&XI(t,n,r)<=o)return!0}return!1})(i.flattenedSubpaths,o,e.props.strokeWidth/2+6)}hitTestLineSegment(e,t){const n=new $C(t.positionedStart.x-e.x,t.positionedStart.y-e.y),o=new $C(t.positionedEnd.x-e.x,t.positionedEnd.y-e.y),i=t.positionedMargin+e.props.strokeWidth/2;return FI(e).flattenedSubpaths.some(e=>((e,t,n,o)=>{const i=o*o;for(let r=1;r<n.length;r+=1){const o=n[r-1],s=n[r];if(o&&s&&(sv(o,e,t)<=i||sv(s,e,t)<=i||sv(e,o,s)<=i||sv(t,o,s)<=i))return!0}return!1})(n,o,e.points,i))}isWrappedByBrush(e,t){const n=t.pageOutlineVertices;return 0===n.length?!!t.pageBounds&&t.brushBounds.containsBox(t.pageBounds):n.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return t.isWrapping?this.isWrappedByBrush(e,t):t.pageBounds?.intersects(t.brushBounds)??!1}onEditEnd(e){if(e.props.subpaths.every(e=>e.nodes.length<2))return{deleteShapeIds:[e.id]}}}],shapeSvgExporters:[new class{type="path";toSvg(e,t){const n=FI(e);return n.path?{tag:"path",attrs:{d:n.path,fill:z(e.props.fill)?"none":t.resolveColor(e.props.fill),"fill-rule":e.props.fillRule,"clip-rule":e.props.fillRule,stroke:t.resolveColor(e.props.stroke),"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}:null}}],interactionHandlers:[{id:"land.path.interactions",editorEvent:{handleEvent(e,t){if("pointer"===t.type&&"pointer_move"===t.name&&jF.get(e)?.pointerId===t.pointerId)return WP(e),_P(e,t),"handled";if("pointer"===t.type&&"pointer_up"===t.name&&(VF.delete(e),WP(e),jF.get(e)?.pointerId===t.pointerId))return((e,t)=>{const n=jF.get(e);n&&(n.isActive?_P(e,t):YP(t)||pP(e),jF.delete(e),e.setBrushBox(null))})(e,t),"handled";if("pointer"===t.type&&"pointer_cancel"===t.name&&(VF.delete(e),WP(e),jF.get(e)?.pointerId===t.pointerId))return KP(e),"handled";if("click"===t.type&&"double_click"===t.name&&"up"===t.phase&&!t.shiftKey&&!t.altKey&&!t.accelKey){XP(e);const n=e.hitTestShape(t.pagePoint);if(gI(n))return zP(e),e.startEditingShape({shapeId:n.id,markId:_F,entryMode:"focusEnd"},"user"),"handled"}if("cancel"===t.type)return VF.delete(e),jF.has(e)?(KP(e),"handled"):"escape"===t.reason&&e.isActiveToolInInitialState()&&UP(e)&&e.completeEditing("user")?"handled":(XP(e),"continue");if("keyboard"===t.type&&"key_down"===t.name)return QP(e,t)?"handled":"continue";if("pointer"===t.type&&"pointer_move"===t.name)return"mouse"!==t.pointerType||0!==t.buttons||t.altKey?WP(e):((e,t)=>{const n=UP(e);if(!n||"select"!==e.getActiveToolId()||!e.isActiveToolInInitialState())return void WP(e);if("custom"===e.hitTestSelectionHandle(t.pagePoint)?.kind)return void WP(e);const o=NP(e,n,t.pagePoint),i=YI(n.props.subpaths,o,7/e.getCurrentCamera().z);if(!i)return void WP(e);const r=e.computeShapeLocalToPageTransform(n);pI(e,{shapeId:n.id,subpathId:i.subpathId,startNodeId:i.startNodeId,endNodeId:i.endNodeId,t:i.t,pagePoint:r.applyToPoint(i.point)})})(e,t),"continue";if("pointer"===t.type&&"pointer_down"===t.name&&0===t.button&&t.altKey){WP(e);const n=UP(e);if(!n)return"continue";const o=e.hitTestSelectionHandle(t.pagePoint);if("custom"===o?.kind&&"path.node"===o.type){const t=uI(o.type,o.id);if("path.node"===t?.type){const o=uP(e);return GP(e,n,o?.selection.shapeId===n.id&&fP(o.selection,t.subpathId,t.nodeId)?o.selection.nodes:[{subpathId:t.subpathId,nodeId:t.nodeId}]),"handled"}}}if("pointer"===t.type&&"pointer_down"===t.name&&0===t.button&&!t.altKey){WP(e);const n=UP(e);if(!n)return"continue";const o=e.hitTestSelectionHandle(t.pagePoint);if("custom"===o?.kind)return uI(o.type,o.id)||pP(e),"continue";const i=NP(e,n,t.pagePoint),r=YI(n.props.subpaths,i,7/e.getCurrentCamera().z);if(!r)return((e,t,n)=>{const o=uP(e);jF.set(e,{shapeId:t.id,pointerId:n.pointerId,originPagePoint:n.pagePoint.clone(),originScreenPoint:n.screenPoint.clone(),previousEntries:o?.selection.shapeId===t.id?o.selection.nodes.map(e=>({...e})):[],previousPrimary:o?.selection.shapeId===t.id?{...o.selection.primary}:null,isActive:!1})})(e,n,t),"handled";const s=`insert-node:${qF+=1}`;return e.operations.run({kind:"path.insert-node",label:"shape.edit",source:"user",history:"record"},()=>{const t=((e,t,n)=>e.map(e=>{if(e.id!==t.subpathId)return PI(e);const o=e.nodes.findIndex(e=>e.id===t.startNodeId);if(o<0)return PI(e);const i=(o+1)%e.nodes.length,r=e.nodes[o],s=e.nodes[i];if(!r||!s||s.id!==t.endNodeId)return PI(e);const a=((e,t,n,o)=>{if(!AI(e,t)){const i=EI(kI(e),kI(t),n);return{start:II(e),node:{id:o,x:i.x,y:i.y,kind:"corner"},end:II(t)}}const[i,r,s,a]=BI(e,t),d=EI(i,r,n),l=EI(r,s,n),c=EI(s,a,n),u=EI(d,l,n),p=EI(l,c,n),h=EI(u,p,n);return{start:{...II(e),out:lP(d.sub(i))},node:{id:o,x:h.x,y:h.y,kind:"smooth",in:lP(u.sub(h)),out:lP(p.sub(h))},end:{...II(t),in:lP(c.sub(a))}}})(r,s,t.t,n),d=e.nodes.map(II);return d[o]=a.start,d[i]=a.end,d.splice(o+1,0,a.node),{...e,nodes:d}}))(n.props.subpaths,r,s);e.commands.updateShapes([{id:n.id,props:{subpaths:t}}],{source:"user"});const o=e.getShape(n.id);gI(o)&&hP(e,o,r.subpathId,s)}),LP(e,n.id),VF.set(e,{shapeId:n.id,nodeId:s}),"continue"}return"continue"}},selectionHandle:{createSession(e,{handle:t,shape:n,originPagePoint:o}){if(!gI(n)||"custom"!==t.kind)return null;const i=uI(t.type,t.id);if(!i)return null;if(e.getShapeEditingSession()?.shapeId!==n.id)return null;const r=VF.get(e),s="path.node"===i.type&&r?.shapeId===n.id&&r.nodeId===i.nodeId;s&&VF.delete(e);const a=n,d=_I(a.props.subpaths,i.subpathId,i.nodeId),l=NP(e,a,o),c=uP(e),u=c?.selection.shapeId===n.id?c.selection.nodes.map(e=>({...e})):[],p=c?.selection.shapeId===n.id?{...c.selection.primary}:null,h={subpathId:i.subpathId,nodeId:i.nodeId},g=!!c&&c.selection.shapeId===n.id&&fP(c.selection,i.subpathId,i.nodeId),f="path.node"===i.type&&g,m="path.node"===i.type&&e.inputs.state.get().shiftKey,y=m&&!f?[...c?.selection.shapeId===n.id?c.selection.nodes:[],h]:null;y?gP(e,n,y,h):e.inputs.state.get().shiftKey||g||hP(e,n,i.subpathId,i.nodeId);const S="path.node"===i.type&&(y||f)?y??c.selection.nodes:[h],b=e.computeShapeLocalToPageTransform(a),x=d?b.applyToPoint(kI(d)):o,w=t.point.sub(o),I="path.node"===i.type?S.flatMap(e=>{const t=_I(a.props.subpaths,e.subpathId,e.nodeId);return t?[b.applyToPoint(kI(t))]:[]}):[t.point],P=(I.length>0?I:[t.point]).map(e=>e.sub(o)),v=((e,t,n)=>{const o=new Set(n.map(HP)),i=e.computeShapeLocalToPageTransform(t);return{points:t.props.subpaths.flatMap(e=>e.nodes.flatMap(n=>o.has(HP({subpathId:e.id,nodeId:n.id}))?[]:[{id:`${t.id}:${e.id}:${n.id}`,nodeId:t.id,point:i.applyToPoint(kI(n)),kind:"custom"}])),outlines:[]}})(e,a,"path.node"===i.type?S:[]);return{shapeId:n.id,historyMark:"path.handle",onClick:m&&f?({editor:e})=>{const t=e.getShape(n.id);gI(t)&&((e,t,n,o)=>{const i=cP(e);if(!i||i.shapeId!==t.id)return void hP(e,t,n,o);const r={subpathId:n,nodeId:o},s=fP(i,n,o),a=s?i.nodes.filter(e=>!SP(e,r)):[...i.nodes,r];gP(e,t,a,s?a.at(-1)??null:r)})(e,t,i.subpathId,i.nodeId)}:void 0,onCancel({editor:e,reason:t}){if("pointer_cancel"!==t&&"escape"!==t)return;const o=e.getShape(n.id);gI(o)&&e.getShapeEditingSession()?.shapeId===n.id&&(0!==u.length?gP(e,o,u,p):pP(e))},onComplete({editor:e}){s?((e,t)=>{RP(e).replaceCurrent(t)})(e,n.id):LP(e,n.id)},update({editor:e,pagePoint:t,accelKey:r,source:s}){if(!gI(e.getShape(n.id)))return"stop";const c=e.inputs.state.get(),u=c.shiftKey?"path.node"===i.type?ev(o,t):ev(x,t.add(w)).sub(w):t,p=OP(e)&&!r&&!c.shiftKey&&v.points.length>0,h=p?e.snaps.snapHandle({mode:"align",pagePoint:u,sourcePointOffsets:P,snapshot:v,threshold:10/e.getCurrentCamera().z}):null;p||e.snaps.clearIndicators();const g=h?.snappedPagePoint??u,f=NP(e,a,"path.node"===i.type?g:g.add(w)),m="path.node"===i.type?d?qI(a.props.subpaths,S,e=>tv(e,f.sub(l))):vI(a.props.subpaths):KI(a.props.subpaths,i.subpathId,i.nodeId,e=>((e,t,n,o)=>{const i=kI(e),r=o.altKey?{...e,kind:"corner"}:{...e},s=n.sub(i);return"in"===t?(r.in={dx:s.x,dy:s.y},o.altKey||"corner"===e.kind||(r.out=JP(s,e.out?TI(e).sub(i):null,"symmetric"===e.kind))):(r.out={dx:s.x,dy:s.y},o.altKey||"corner"===e.kind||(r.in=JP(s,e.in?CI(e).sub(i):null,"symmetric"===e.kind))),r})(e,i.handle,f,{altKey:c.altKey}));if(e.commands.updateShapes([{id:n.id,props:{subpaths:m}}],{source:s}),"path.node"===i.type){const t=e.getShape(n.id);gI(t)&&gP(e,t,S,{subpathId:i.subpathId,nodeId:i.nodeId})}return"continue"}}}}}],setup(e){const t=function(e){let t=null;const n=Zi("path.editSnap.lifecycle",e.shapeEditingSessionSignal,()=>{const n=e.getShapeEditingSession(),o=n?e.getShape(n.shapeId):null,i=gI(o)?o.id:null;if(i!==t){if(t){const n=((e,t,n)=>RP(e).hasNetChanges("edit",n))(e,0,t);FP(e,"edit",t),n||e.editing.cancelOperation()}t=i,pP(e),zP(e),i&&$P(e,"edit",i,{onBoundaryUndo:()=>{if(e.getShapeEditingSession()?.shapeId!==i)return!1;const t=e.completeEditing("user");return t&&"select"!==e.getActiveToolId()&&e.commands.setActiveTool("select",{source:"system"}),t}})}});return()=>{n(),t&&FP(e,"edit",t),pP(e),zP(e)}}(e);return e.tools.register("path",e=>new JF(e),{shortcut:"b"}),t}},render:{id:"land.path.react",canvasOverlays:[{id:"land.path.draft-overlay",component:function(){const e=wr(),t=Ir(e.toolStateSignal),n=Ir(e.inputs.state),o=Ir(e.selectedShapesSignal),i=Ir(e.currentCameraSignal);if("path"!==t.activeToolId)return null;const r=1===o.length?o[0]:null,s=gI(r)?r:null,a=8/i.z,d=1.5/i.z,l=6/i.z,c=1/i.z,u=n.currentPagePoint;if(!s)return u?Gk(vP,{point:u,size:a,strokeWidth:d,variant:"candidate"}):null;const p=((e,t)=>{const n=bP(t);if(!n.subpathId)return null;const o=HI(UI(t,e.computeShapeLocalToPageTransform(t)),n.subpathId);if(!o)return null;const i=n.previewNodeId?o.nodes.findIndex(e=>e.id===n.previewNodeId):-1,r=i>=0?o.nodes[i]??null:null,s=i>0?o.nodes[i-1]??null:null,a=s&&r?SI({id:`${o.id}:preview`,closed:!1,nodes:[s,r]}):null;return{closed:o.closed,committedNodes:o.nodes.filter(e=>e.id!==n.previewNodeId),previewNode:r,previewPath:a}})(e,s);if(!p)return u?Gk(vP,{point:u,size:a,strokeWidth:d,variant:"candidate"}):null;const h=p.previewNode?kI(p.previewNode):n.isPointing?null:u,g=h&&!p.committedNodes.some(e=>kI(e).dist2(h)<=.25/(i.z*i.z));
|
|
106
|
+
return Zk("g",{"data-ui":"path-draft-overlay",pointerEvents:"none",children:[p.previewPath?Gk("path",{"data-ui":"path-draft-preview-segment",d:p.previewPath,fill:"none",stroke:NF,strokeWidth:Math.max(d,1/i.z),strokeDasharray:`${6/i.z} ${4/i.z}`,strokeLinecap:"round",strokeLinejoin:"round"}):null,g?Gk(vP,{point:h,size:a,strokeWidth:d,variant:"candidate"}):null,p.committedNodes.map((e,t)=>Gk(IP,{node:e,showIn:p.closed||t>0,size:l,strokeWidth:c},e.id)),p.committedNodes.map(e=>Gk(vP,{point:kI(e),size:a,strokeWidth:d,variant:"committed"},e.id))]})},layer:"above-host",order:20},{id:"land.path.edit-insert-preview-overlay",component:function(){const e=wr(),t=Ir(e.toolStateSignal),n=Ir(e.shapeEditingSessionSignal),o=Ir(e.selectedShapesSignal),i=Ir(e.currentCameraSignal);if(Ir(e.inputs.state),"select"!==t.activeToolId||!n)return null;const r=1===o.length?o[0]:null;if(!gI(r)||r.id!==n.shapeId)return null;const s=(e=>{const t=BF.get(e);return t?hI(t):null})(e);if(!s||s.shapeId!==r.id)return null;const a=8/i.z,d=a/2;
|
|
107
|
+
return Gk("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:Gk("rect",{"data-ui":"path-edit-insert-preview-control-point",x:s.pagePoint.x-d,y:s.pagePoint.y-d,width:a,height:a,rx:2,ry:2,fill:"rgba(219, 234, 254, 0.72)",stroke:"var(--land-selection, #2563eb)",strokeDasharray:`${3/i.z} ${2/i.z}`,strokeWidth:1.5/i.z})})},layer:"above-host",order:21}],shapeRenderers:[{type:"path",component:function({shape:e,shapeEditingSession:t}){
|
|
108
|
+
return Gk(kP,{shape:e,shapeEditingSession:t})},hoverComponent:function({shape:e,strokeWidth:t}){
|
|
109
|
+
return Gk(CP,{shape:e,strokeWidth:t})}}],selectionCustomHandleRenderers:[{type:MF,component:function({handle:e,strokeWidth:t}){const n=EP(e.type,e.id);
|
|
110
|
+
return Gk("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2,ry:2,fill:n?"rgba(219, 234, 254, 0.98)":"rgba(255,255,255,0.98)",stroke:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.94)",strokeWidth:n?1.5*t:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}},{type:EF,component:function({handle:e,strokeWidth:t}){const n=EP(e.type,e.id);
|
|
111
|
+
return Gk("circle",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,cx:e.point.x,cy:e.point.y,r:Math.max(e.bounds.w,e.bounds.h)/2,fill:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.92)",stroke:"rgba(255,255,255,0.96)",strokeWidth:n?1.5*t:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}}]},setup:e=>{e.actions.add(wv("fill"),wv("stroke"),wv("strokeWidth"),Iv("fill"),Iv("stroke"),Iv("strokeWidth"),{id:sO,getAvailability(e){if(1!==e.selection.count||"path"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;return gI(t)&&!t.isLocked?"enabled":"disabled"},run({context:e}){const[t]=e.selection.selectedShapes;gI(t)&&(pP(e.editor),zP(e.editor),e.editor.startEditingShape({shapeId:t.id,markId:"path.edit",entryMode:"focusEnd"},"user"))}},{id:aO,getAvailability:e=>(e=>{const t=e.editor.getShapeEditingSession();return!!t&&gI(e.editor.getShape(t.shapeId))})(e)?"enabled":"inapplicable",run({context:e}){e.editor.completeEditing("user")}},{id:dO,getAvailability(e){const t=e.editor.getShapeEditingSession(),n=t?e.editor.getShape(t.shapeId):null;return gI(n)?n.isLocked?"disabled":"enabled":"inapplicable"},getValue:e=>OP(e.editor),run({context:e}){DP(e.editor)}},{id:hO,getAvailability(e){const t=uP(e.editor);return t?t.shape.isLocked?"disabled":"enabled":"inapplicable"},run({context:e}){const t=uP(e.editor);t&&!t.shape.isLocked&&GP(e.editor,t.shape,t.selection.nodes)}},{id:gO,getAvailability(e){const t=uP(e.editor);return t?!t.shape.isLocked&&t.entries.some(({node:e})=>!e.in&&!e.out)?"enabled":"disabled":"inapplicable"},run({context:e}){const t=uP(e.editor);if(!t||t.shape.isLocked)return;const n=t.entries.flatMap(({ref:e,node:t})=>t.in||t.out?[]:[e]).reduce((e,t)=>jI(e,t.subpathId,t.nodeId),t.shape.props.subpaths);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"});const o=e.editor.getShape(t.shape.id);gI(o)&&gP(e.editor,o,t.selection.nodes,t.selection.primary),LP(e.editor,t.shape.id)}},{id:fO,getAvailability(e){const t=uP(e.editor);return t?!t.shape.isLocked&&t.entries.some(({node:e})=>!!e.in||!!e.out)?"enabled":"disabled":"inapplicable"},run({context:e}){const t=uP(e.editor);if(!t||t.shape.isLocked)return;const n=t.selection.nodes.reduce((e,t)=>VI(e,t.subpathId,t.nodeId),t.shape.props.subpaths);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"});const o=e.editor.getShape(t.shape.id);gI(o)&&gP(e.editor,o,t.selection.nodes,t.selection.primary),LP(e.editor,t.shape.id)}},Pv(mO,"merge"),Pv(yO,"join"),Pv(SO,"separate"),vv("union"),vv("subtract"),vv("intersect"),vv("xor")),e.toolbar.add({id:"path.tool-toolbar",channel:gM.toolSwitcher,order:47,actionIds:[pM],getGroups:e=>[{id:"path.tools",items:[{kind:"button",id:"path.tool.path",actionId:pM,value:"path",label:"Path",shortcut:e.editor.shortcuts.getToolShortcutLabel("path"),icon:"pen-tool",dataUi:"path-tool-button"}]}]},{id:"path.default-style.tool-toolbar",channel:gM.toolOptions,order:48,actionIds:["path.default-fill","path.default-stroke","path.default-strokeWidth"],when:e=>"path"===e.tool.activeToolId,getGroups:()=>xv({fillActionId:"path.default-fill",strokeActionId:"path.default-stroke",strokeWidthActionId:"path.default-strokeWidth",dataUiPrefix:"path-default"})},{id:"path.selection-toolbar",channel:gM.selectionProperties,order:22,actionIds:[sO,"path.set-fill","path.set-stroke","path.set-strokeWidth",lO,cO,uO,pO],when:e=>"path"===e.selection.commonShapeType,getGroups(e){const t=[{id:"path.edit",items:[{kind:"button",id:"path.edit",actionId:sO,label:"Edit",icon:"square-pen",dataUi:"path-edit-button"}]},...xv({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",dataUiPrefix:"path"})];return kv(e).length>=2&&t.push({id:"path.boolean",items:[{kind:"button",id:"path.boolean.union",actionId:lO,label:"Union",icon:"group",dataUi:"path-boolean-union-button"},{kind:"button",id:"path.boolean.subtract",actionId:cO,label:"Subtract",icon:"minus",dataUi:"path-boolean-subtract-button"},{kind:"button",id:"path.boolean.intersect",actionId:uO,label:"Intersect",icon:"crop",dataUi:"path-boolean-intersect-button"},{kind:"button",id:"path.boolean.xor",actionId:pO,label:"Exclude",icon:"ungroup",dataUi:"path-boolean-xor-button"}]}),t}},{id:"path.floating-selection-toolbar",channel:gM.selectionQuickActions,order:22,actionIds:[sO,aO,dO,hO,gO,fO,mO,yO,SO,"path.set-fill","path.set-stroke","path.set-strokeWidth",lO,cO,uO,pO],when(e){const t=e.editor.getShapeEditingSession(),n=t?e.editor.getShape(t.shapeId):null;return"path"===e.selection.commonShapeType&&(!t||gI(n))},getGroups(e){const t=e.editor.getShapeEditingSession(),n=gI(t?e.editor.getShape(t.shapeId):null);if(uP(e.editor))return[{id:"path.floating-node-edit",presentation:"overflow",items:[{kind:"button",id:"path.floating-node.delete",actionId:hO,label:"Delete node",shortcut:"⌫",icon:"remove-node",dataUi:"floating-path-node-delete-button"}]},{id:"path.floating-node-topology",items:[{kind:"button",id:"path.floating-node.merge",actionId:mO,label:"Merge nodes",shortcut:"Mod+J",icon:"merge-nodes",dataUi:"floating-path-node-merge-button"},{kind:"button",id:"path.floating-node.join",actionId:yO,label:"Join nodes",shortcut:"J",icon:"join-nodes",dataUi:"floating-path-node-join-button"},{kind:"button",id:"path.floating-node.separate",actionId:SO,label:"Separate segment",shortcut:"K",icon:"separate-nodes",dataUi:"floating-path-node-separate-button"}]},{id:"path.floating-node-convert",items:[{kind:"button",id:"path.floating-node.remove-handles",actionId:fO,label:"Corner point",shortcut:"X",icon:"to-corner",dataUi:"floating-path-node-remove-handles-button"},{kind:"button",id:"path.floating-node.make-curve",actionId:gO,label:"Curve point",shortcut:"C",icon:"to-curve",dataUi:"floating-path-node-make-curve-button"}]},Sv(),bv()];if(n)return[Sv(),bv()];const o=[{id:"path.floating-edit",items:[{kind:"button",id:"path.floating-edit",actionId:sO,label:"Edit",icon:"square-pen",dataUi:"floating-path-edit-button"}]},...xv({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",dataUiPrefix:"floating-path"})];return kv(e).length>=2&&o.push({id:"path.floating-boolean",presentation:"overflow",items:[{kind:"button",id:"path.floating-boolean.union",actionId:lO,label:"Union",icon:"group",dataUi:"floating-path-boolean-union-button"},{kind:"button",id:"path.floating-boolean.subtract",actionId:cO,label:"Subtract",icon:"minus",dataUi:"floating-path-boolean-subtract-button"},{kind:"button",id:"path.floating-boolean.intersect",actionId:uO,label:"Intersect",icon:"crop",dataUi:"floating-path-boolean-intersect-button"},{kind:"button",id:"path.floating-boolean.xor",actionId:pO,label:"Exclude",icon:"ungroup",dataUi:"floating-path-boolean-xor-button"}]}),o}}),e.contextMenu.add({id:"path.context-menu",target:"selection",order:38,actionIds:[sO,lO,cO,uO,pO],when:e=>"path"===e.selection.commonShapeType,getSections(e){const t=[{kind:"command",id:"path.edit",actionId:sO,label:"Edit path",icon:"square-pen",dataUi:"path-context-edit"}];return kv(e).length>=2&&t.push({kind:"command",id:"path.boolean.union",actionId:lO,label:"Union paths",icon:"group",dataUi:"path-context-boolean-union"},{kind:"command",id:"path.boolean.subtract",actionId:cO,label:"Subtract paths",icon:"minus",dataUi:"path-context-boolean-subtract"},{kind:"command",id:"path.boolean.intersect",actionId:uO,label:"Intersect paths",icon:"crop",dataUi:"path-context-boolean-intersect"},{kind:"command",id:"path.boolean.xor",actionId:pO,label:"Exclude paths",icon:"ungroup",dataUi:"path-context-boolean-xor"}),[{id:"path.context",title:"Path",items:t}]}})}},IO="image-blob:",PO=1,vO=zk(({editor:e,hostBridge:t,imageAssetService:n,imports:o,flushSnapshot:i})=>{const r=Kk(null),s=Kk(null),a=Uk(t=>qv({editor:e,file:t,imageObjectUrls:n.objectUrls,flushSnapshot:i}),[e,i,n]);return Wk(()=>{if(t)return t.register({openInsertFilePicker(){r.current?.click()},openReplaceFilePicker(){s.current?.click()}})},[t]),Zk(Vk,{children:[Gk("input",{ref:r,type:"file",accept:"image/*",hidden:!0,"data-ui":"insert-image-file-input",onChange:t=>{const n=t.currentTarget.files?.[0]??null;t.currentTarget.value="",n&&o.import({source:"file-picker",files:[n]},{editor:e}).catch(tk)}}),Gk("input",{ref:s,type:"file",accept:"image/*",hidden:!0,"data-ui":"replace-image-file-input",onChange:e=>{const t=e.currentTarget.files?.[0]??null;e.currentTarget.value="",t&&a(t).catch(tk)}})]})}),kO=fr("plugin-image.asset-service"),CO=new WeakSet,TO=gr("plugin-image.product-controller"),MO=class{handlers=null;register(e){return this.handlers=e,()=>{this.handlers===e&&(this.handlers=null)}}openInsertFilePicker(){this.handlers?.openInsertFilePicker()}openReplaceFilePicker(){this.handlers?.openReplaceFilePicker()}},EO=fr("plugin-image.toolbar-host-bridge"),BO={id:"canvas-kit.image",provides:[kO,EO,TO],requires:[iF],setup(e){const t=e.persistence?async()=>e.persistence.flush():void 0,n=e.services.add(nk({flushSnapshot:t})),o=e.services.add({token:EO,create:()=>new MO});e.actions.add(...(({hostBridge:e,imageObjectUrls:t})=>[{id:TL,run(){e.openInsertFilePicker()}},{id:kL,getAvailability(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;return mw(t)&&!t.isLocked?"enabled":"disabled"},run(){e.openReplaceFilePicker()}},{id:CL,getAvailability(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;if(!mw(t)||!t.props.assetId)return"disabled";const n=e.editor.getAsset(t.props.assetId);return fw(n)&&("remote"===n.props.source.kind||Av(e.editor,t.props.assetId))?"enabled":"disabled"},run({context:e}){jv({editor:e.editor,imageObjectUrls:t})}}])({hostBridge:o,imageObjectUrls:n.objectUrls})),e.imports.add({id:"canvas-kit.image-import",order:100,acceptsPreview:e=>e.fileTypes.some(e=>e.startsWith("image/"))||e.dataTypes.some(e=>{const t=e.toLowerCase();return"files"===t||"text/uri-list"===t}),accepts:e=>null!==zv(e.files)||(e.urls?.some(fk)??!1),async import(e,{editor:o}){const i=zv(e.files),r=e.urls?.find(fk);return await Yv({editor:o,imageObjectUrls:n.objectUrls,source:i?{type:"file",file:i}:{type:"url",url:r},pagePoint:e.pagePoint,flushSnapshot:t})?"handled":"ignored"}}),e.lifecycle.beforeCommand(({commandId:e,context:t,editor:n})=>{var o;"history.undo"===e||"history.redo"===e||t&&("image.smudge"===(o=e)||"image.smudge.cancel"===o||"image.smudge.confirm"===o||"image.smudge.brush-size"===o||"image.smudge.brush-color"===o)||(e=>{iw(e).cancelIfActive()})(t?.editor??n)}),e.assets.addResolver(kO),e.apis.add({token:TO,create:({editor:e,services:n})=>lk({editor:e,flushSnapshot:t,services:n})}),e.ui.allowPropertiesDuringEditing(e=>Sw(e)||bw(e)),e.assets.addSvgInliners((e=>({async prepare({editor:t,requestedShapeIds:n}){const o=ck(t,t.getShapeExportTraversalIds(n).flatMap(e=>{const n=t.getShape(e);return n?[n]:[]})),i=new Set;for(const r of o.values()){if("local"!==r.props.source.kind)continue;const{storageKey:t}=r.props.source;if(!i.has(t)&&(i.add(t),0===t.length||!(await e.objectUrls.preload(t))))throw new Error(`Could not load image asset "${r.id}".`)}},async inline({editor:t,exportedShapes:n,svg:o}){let i=o;const r=ck(t,n),s=new Set;for(const a of r.values()){const t=pk(a,e);if(!t)throw new Error(`Could not resolve image asset "${a.id}".`);if(s.has(t))continue;const n=await uk(a,t);if(n.href===n.dataUrl){s.add(t);continue}const o=`href="${hk(n.href)}"`;if(!i.includes(o))throw new Error(`Could not find image asset "${a.id}" in the generated SVG.`);i=i.split(o).join(`href="${n.dataUrl}"`),s.add(t)}return i}}))(n)),e.ui.addComponents({id:"canvas-kit.image-import",order:100,component:e=>Gk(gk,{...e,flushSnapshot:t})})}},AO=[["geo",YB],["connector",N$],["draw",Z$],["arrow",hB],["eraser",yL],["laser",TF],["path",wO],["image",iF],["text",iB],["frame",vB],["group",vL]],RO=[500,1e3,2e3,5e3],$O=class{editor;adapter;unsubscribeDocument=null;unsubscribeSession=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();isRunning=!1;constructor(e,t){this.editor=e,this.adapter=t}start(){this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.getSessionSnapshot(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.flushWhenHidden),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.flushWhenPageIsLeaving),window.addEventListener("beforeunload",this.flushWhenPageIsLeaving)))}stop(){this.isRunning&&(this.isRunning=!1,this.flush().catch(e=>{console.warn("Could not persist canvas snapshot.",e)}),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.flushWhenHidden),"undefined"!=typeof window&&(window.removeEventListener("pagehide",this.flushWhenPageIsLeaving),window.removeEventListener("beforeunload",this.flushWhenPageIsLeaving)))}flush(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return Promise.all([e,t]).then(()=>{})}savePendingDocument(){const e=this.pendingDocument;return e&&this.adapter.saveDocument?(this.pendingDocument=null,this.queueWrite(()=>this.adapter.saveDocument(e.snapshot)).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t})):this.writeChain}savePendingSession(){const e=this.pendingSession;return e&&this.adapter.saveSession?(this.pendingSession=null,this.queueWrite(()=>this.adapter.saveSession(e.snapshot)).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t})):this.writeChain}queueWrite(e){const t=this.writeChain.then(e);return this.writeChain=t.catch(()=>{}),t}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{console.warn("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{console.warn("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=RO[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=RO[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushWhenHidden=()=>{"hidden"===document.visibilityState&&this.flush().catch(e=>{console.warn("Could not persist canvas snapshot.",e)})};flushWhenPageIsLeaving=()=>{this.flush().catch(e=>{console.warn("Could not persist canvas snapshot.",e)})}},LO=new WeakMap,FO={status:"starting"};export{gR as CANVAS_KIT_TOOL_IDS,Yh as CanvasKitFloatingToolbarLayer,Ak as CanvasKitRoot,uE as DEFAULT_TEXT_FONT,Xg as FloatingSelectionToolbarPageSpace,pE as HOST_TEXT_FONT,TA as Packaging,sB as arrowApiToken,$A as canvasClipboardServiceToken,IR as canvasExportApiToken,AA as canvasImportHostCapability,MA as canvasToolActionsCapability,aM as chromeChannels,Sf as createCanvasKitController,bf as createCanvasKitControllerWithTools,Ck as createCanvasKitRuntime,tr as createCanvasPluginValueToken,or as createChromeChannel,B as createCustomShapeColor,na as createDefaultTextFontCatalog,ta as createDefaultTextPluginOptions,gr as createProductApiToken,fr as createProductServiceToken,Ik as createStandardCanvasKitPlugins,jg as createTextHostPlugin,Vg as createTextLinkHoverPopoverPresenter,E as createThemeShapeColor,mr as createToolbarChannel,qg as defineCanvasPlugin,gB as frameApiToken,LB as geoApiToken,ys as getPlainTextFromRichText,L as getThemeColorTokenName,TO as imageProductControllerToken,R as isCustomShapeColorRef,A as isThemeShapeColorRef,yr as mergeToolbarGroups,vC as n,SA as packagingApiToken,Vu as parsePackagingDocument,qp as parsePackagingDxf,D as resolveShapeColor,O as shapeColorToCssColor,PC as t,jE as textApiToken,gM as toolbarChannels,Qg as useCanvasKitLayerTree,Lk as useCanvasKitRuntime,_h as useCanvasKitWheelCapture};
|