@yuzhouu/canvas-kit 0.1.7 → 0.1.9
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 +5 -1
- package/_vendor/canvas-core/editor/commands.d.ts +10 -1
- package/_vendor/canvas-core/editor/createEditorWithRuntimePlugins.d.ts +6 -0
- package/_vendor/canvas-core/editor/editor.d.ts +6 -1
- package/_vendor/canvas-core/editor/index.d.ts +1 -1
- package/_vendor/canvas-core/editor/managers/documentSnapshotManager.d.ts +1 -1
- package/_vendor/canvas-core/editor/managers/snapCalculations.d.ts +34 -4
- package/_vendor/canvas-core/editor/managers/snapManager.d.ts +7 -0
- package/_vendor/canvas-core/editor/managers/snapTypes.d.ts +15 -0
- package/_vendor/canvas-core/editor/middleMousePanInteraction.d.ts +2 -0
- package/_vendor/canvas-core/index.d.ts +7 -7
- package/_vendor/canvas-core/plugins/{editorPlugin.d.ts → editorRuntimePlugin.d.ts} +3 -3
- package/_vendor/canvas-core/plugins/index.d.ts +1 -1
- package/_vendor/canvas-core/schema/records.d.ts +10 -1
- package/_vendor/canvas-core/shapes/shapeUtil.d.ts +13 -4
- package/_vendor/canvas-core/shapes/types.d.ts +2 -2
- package/_vendor/canvas-core/surfaces/toolbar.d.ts +11 -1
- package/_vendor/canvas-react/components/CanvasView.d.ts +3 -3
- package/_vendor/canvas-react/components/useCanvasDomEvents.d.ts +2 -0
- package/_vendor/canvas-react/host/actionRegistry.d.ts +15 -0
- package/_vendor/canvas-react/host/{canvasPlugin.d.ts → canvasRenderPlugin.d.ts} +5 -5
- package/_vendor/canvas-react/host/canvasRenderPluginHost.d.ts +2 -0
- package/_vendor/canvas-react/host/canvasRenderPluginHostManifest.d.ts +2 -0
- package/_vendor/canvas-react/host/canvasRenderPluginHostRuntime.d.ts +3 -0
- package/_vendor/canvas-react/host/canvasRenderPluginHostTypes.d.ts +104 -0
- package/_vendor/canvas-react/host/canvasRenderPluginHostValidation.d.ts +11 -0
- package/_vendor/canvas-react/host/contextMenuRegistry.d.ts +8 -3
- package/_vendor/canvas-react/host/domEventGuards.d.ts +3 -3
- package/_vendor/canvas-react/host/extension.d.ts +4 -4
- package/_vendor/canvas-react/host/index.d.ts +5 -4
- package/_vendor/canvas-react/host/overlayRegistry.d.ts +3 -3
- package/_vendor/canvas-react/host/rendererRegistry.d.ts +3 -3
- package/_vendor/canvas-react/host/toolbarRegistry.d.ts +9 -13
- package/_vendor/plugin-arrow/canvasRender.d.ts +2 -0
- package/_vendor/plugin-arrow/{editor.d.ts → editorRuntime.d.ts} +2 -2
- package/_vendor/plugin-arrow/index.d.ts +2 -2
- package/_vendor/plugin-draw/canvasRender.d.ts +2 -0
- package/_vendor/plugin-draw/{editor.d.ts → editorRuntime.d.ts} +2 -2
- package/_vendor/plugin-draw/index.d.ts +2 -2
- package/_vendor/plugin-eraser/canvasRender.d.ts +2 -0
- package/_vendor/plugin-eraser/editorRuntime.d.ts +2 -0
- package/_vendor/plugin-eraser/index.d.ts +2 -2
- package/_vendor/plugin-frame/{canvas.d.ts → canvasRender.d.ts} +2 -2
- package/_vendor/plugin-frame/{editor.d.ts → editorRuntime.d.ts} +2 -2
- package/_vendor/plugin-frame/index.d.ts +2 -2
- package/_vendor/plugin-geo/{canvas.d.ts → canvasRender.d.ts} +2 -2
- package/_vendor/plugin-geo/{editor.d.ts → editorRuntime.d.ts} +2 -2
- package/_vendor/plugin-geo/geoGeometry.d.ts +19 -3
- package/_vendor/plugin-geo/index.d.ts +2 -2
- package/_vendor/plugin-geo/types.d.ts +1 -0
- package/_vendor/plugin-group/{canvas.d.ts → canvasRender.d.ts} +2 -2
- package/_vendor/plugin-group/{editor.d.ts → editorRuntime.d.ts} +2 -2
- package/_vendor/plugin-group/index.d.ts +2 -2
- package/_vendor/plugin-image/{editor.d.ts → actionIds.d.ts} +0 -8
- package/_vendor/plugin-image/canvasRender.d.ts +2 -0
- package/_vendor/plugin-image/cropRuntime.d.ts +2 -0
- package/_vendor/plugin-image/editorRuntime.d.ts +5 -0
- package/_vendor/plugin-image/imageHostActionContract.d.ts +2 -0
- package/_vendor/plugin-image/imageShapeUtil.d.ts +2 -1
- package/_vendor/plugin-image/imageSvgExporter.d.ts +6 -0
- package/_vendor/plugin-image/index.d.ts +8 -4
- package/_vendor/plugin-image/runtimeShared.d.ts +5 -0
- package/_vendor/plugin-image/smudge.d.ts +63 -0
- package/_vendor/plugin-image/smudgeInteractions.d.ts +2 -0
- package/_vendor/plugin-image/smudgeRuntime.d.ts +2 -0
- package/_vendor/plugin-image/styleRuntime.d.ts +17 -0
- package/_vendor/plugin-image/toolbarRuntime.d.ts +3 -0
- package/_vendor/plugin-image/types.d.ts +16 -1
- package/_vendor/plugin-laser/canvasRender.d.ts +2 -0
- package/_vendor/plugin-laser/editorRuntime.d.ts +2 -0
- package/_vendor/plugin-laser/index.d.ts +2 -2
- package/_vendor/plugin-text/canvasRender.d.ts +5 -0
- package/_vendor/plugin-text/editorRuntime.d.ts +5 -0
- package/_vendor/plugin-text/host/RichTextLinkPopover.d.ts +14 -0
- package/_vendor/plugin-text/host/richTextRendering.d.ts +9 -1
- package/_vendor/plugin-text/index.d.ts +2 -0
- package/_vendor/plugin-text/richTextLinks.d.ts +3 -0
- package/_vendor/plugin-text/richTextUtils.d.ts +2 -1
- package/browser/indexedDb.d.ts +10 -0
- package/browser/persistence.d.ts +2 -4
- package/builtins/controller/createBuiltInCanvasController.d.ts +1 -1
- package/builtins/controller/layerController.d.ts +1 -1
- package/builtins/controller/shapeCreationController.d.ts +6 -2
- package/builtins/index.d.ts +1 -1
- package/chrome/toolbar/CanvasKitWheelCapture.d.ts +2 -0
- package/chrome/{FloatingSelectionToolbarPageSpace.d.ts → toolbar/FloatingSelectionToolbarPageSpace.d.ts} +1 -1
- package/{core/features → chrome}/toolbar/toolbarLabels.d.ts +1 -1
- package/chrome/{bindings → toolbar}/useToolbarSurfaces.d.ts +2 -2
- package/chrome/types.d.ts +12 -8
- package/chrome/useCanvasKitChromeContext.d.ts +6 -4
- package/chrome/{bindings/useCanvasKitLayerTree.d.ts → useCanvasKitLayerTree.d.ts} +1 -1
- package/chrome/{bindings/useContextMenuSurface.d.ts → useContextMenuSurface.d.ts} +3 -3
- package/chrome/useHistoryControls.d.ts +12 -0
- package/chrome/usePageControls.d.ts +16 -0
- package/chrome/{bindings/useSvgExport.d.ts → useSvgExport.d.ts} +2 -2
- package/chrome/useZoomControls.d.ts +9 -0
- package/controller/canvasKitController.d.ts +10 -7
- package/core/api/apiRegistry.d.ts +12 -0
- package/core/index.d.ts +4 -19
- package/core/{controller → product-controller}/canvasProductController.d.ts +17 -4
- package/core/product-controller/index.d.ts +2 -0
- package/core/runtime/productDefinition.d.ts +5 -4
- package/core/runtime/productHost.d.ts +5 -2
- package/{core/features/actions/canvasActionContext.d.ts → features/actions/actionRuntime.d.ts} +7 -1
- package/{core/features → features}/clipboard/clipboardContextMenuContributions.d.ts +1 -1
- package/features/clipboard/clipboardContribution.d.ts +11 -0
- package/features/clipboard/clipboardHostExtension.d.ts +2 -0
- package/{core/features → features}/clipboard/clipboardService.d.ts +3 -3
- package/features/context-menu/contextMenuRuntime.d.ts +13 -0
- package/{core/features → features}/export/svgExport.d.ts +1 -1
- package/features/image/asset/imageAssetService.d.ts +11 -0
- package/features/image/{imageBlobStore.d.ts → asset/imageBlobStore.d.ts} +3 -2
- package/features/image/asset/imageFileHelpers.d.ts +49 -0
- package/features/image/{svgImageAssetInliner.d.ts → asset/svgImageAssetInliner.d.ts} +1 -1
- package/features/image/controller/imageProductController.d.ts +27 -0
- package/features/image/imageHostExtension.d.ts +10 -5
- package/features/image/{ImageImportController.d.ts → import/ImageImportController.d.ts} +3 -3
- package/features/image/{useImageImport.d.ts → import/useImageImport.d.ts} +3 -4
- package/features/image/index.d.ts +17 -15
- package/features/image/smudge/imageSmudgeHostActions.d.ts +10 -0
- package/features/image/smudge/imageSmudgeTypes.d.ts +25 -0
- package/features/image/toolbar/imageHostActions.d.ts +69 -0
- package/features/image/{imageToolbarHostBridge.d.ts → toolbar/imageToolbarHostBridge.d.ts} +2 -2
- package/features/keyboard/keyboardShortcutHostExtension.d.ts +2 -0
- package/features/keyboard/useCanvasKitKeyboardShortcuts.d.ts +6 -0
- package/{react → features/persistence}/CanvasKitPersistenceNotice.d.ts +1 -1
- package/features/persistence/persistenceHostExtension.d.ts +2 -0
- package/{core/features/actions/canvasActions.d.ts → features/selection/selectionActions.d.ts} +3 -9
- package/{core/features/toolbar → features/selection}/selectionContextMenuContributions.d.ts +1 -1
- package/features/selection/selectionHostExtension.d.ts +2 -0
- package/features/selection/selectionToolbarContributions.d.ts +2 -0
- package/features/tool/toolActions.d.ts +2 -0
- package/{core/features/toolbar → features/tool}/toolContextMenuContributions.d.ts +1 -1
- package/features/tool/toolHostExtension.d.ts +2 -0
- package/features/tool/toolToolbarContributions.d.ts +2 -0
- package/features/view/viewActions.d.ts +5 -0
- package/{core/features/context-menu → features/view}/viewContextMenuContributions.d.ts +1 -1
- package/features/view/viewHostExtension.d.ts +2 -0
- package/host/defaultHostExtensions.d.ts +2 -0
- package/index.d.ts +12 -7
- package/index.mjs +96 -76
- package/package.json +1 -1
- package/product/canvasKitProduct.d.ts +8 -7
- package/react/useCanvasKitController.d.ts +1 -1
- package/react/useCanvasKitRuntime.d.ts +1 -1
- package/runtime/canvasKitHostContracts.d.ts +135 -0
- package/runtime/canvasKitHostFeatureHooks.d.ts +12 -0
- package/runtime/canvasKitRuntime.d.ts +8 -6
- package/runtime/canvasKitRuntimePlan.d.ts +50 -0
- package/_vendor/canvas-core/editor/createEditorWithPlugins.d.ts +0 -6
- package/_vendor/canvas-react/host/pluginHost.d.ts +0 -2
- package/_vendor/canvas-react/host/pluginHostManifest.d.ts +0 -2
- package/_vendor/canvas-react/host/pluginHostRuntime.d.ts +0 -3
- package/_vendor/canvas-react/host/pluginHostTypes.d.ts +0 -102
- package/_vendor/canvas-react/host/pluginHostValidation.d.ts +0 -11
- package/_vendor/plugin-arrow/canvas.d.ts +0 -2
- package/_vendor/plugin-draw/canvas.d.ts +0 -2
- package/_vendor/plugin-eraser/canvas.d.ts +0 -2
- package/_vendor/plugin-eraser/editor.d.ts +0 -2
- package/_vendor/plugin-image/canvas.d.ts +0 -2
- package/_vendor/plugin-laser/canvas.d.ts +0 -2
- package/_vendor/plugin-laser/editor.d.ts +0 -2
- package/_vendor/plugin-text/canvas.d.ts +0 -5
- package/_vendor/plugin-text/editor.d.ts +0 -5
- package/chrome/bindings/useCanvasKitChromeControls.d.ts +0 -27
- package/core/controller/featureControllerRegistry.d.ts +0 -12
- package/core/controller/index.d.ts +0 -4
- package/core/features/clipboard/clipboardContribution.d.ts +0 -19
- package/core/features/context-menu/contextMenuActions.d.ts +0 -12
- package/core/features/context-menu/contextMenuContext.d.ts +0 -6
- package/core/features/context-menu/contextMenuContribution.d.ts +0 -4
- package/core/features/hostActionIds.d.ts +0 -1
- package/core/features/toolbar/toolbarContribution.d.ts +0 -4
- package/core/runtime/productContributions.d.ts +0 -9
- package/features/image/imageAssetService.d.ts +0 -7
- package/features/image/imageFileHelpers.d.ts +0 -35
- package/features/image/imageHostActions.d.ts +0 -36
- package/features/image/imageProductController.d.ts +0 -22
- package/features/image/imageProductToolbarActions.d.ts +0 -2
- package/react/useCanvasKitKeyboardShortcuts.d.ts +0 -6
- package/runtime/canvasKitHostExtensions.d.ts +0 -19
- package/runtime/canvasKitRuntimeInitializer.d.ts +0 -11
- /package/chrome/{CanvasKitFloatingToolbarLayer.d.ts → toolbar/CanvasKitFloatingToolbarLayer.d.ts} +0 -0
- /package/core/{controller → product-controller}/productLayerTree.d.ts +0 -0
package/index.mjs
CHANGED
|
@@ -1,76 +1,96 @@
|
|
|
1
|
-
function e(){return ug}function t(){return++ug}function n(e){pg={child:e,parentSet:new Set,below:pg}}function i(){if(!pg)throw new Error("Cannot stop dependency capture because no capture is active");const e=pg;return pg=e.below,e.parentSet}function r(e){pg&&(pg.parentSet.add(e),e.children.add(pg.child))}function o(e){function t(e){for(const r of e)if(!i.has(r))if(i.add(r),"effect"===r.type)n.add(r);else if("computed"===r.type){const e=r.source;e&&t(e.children)}}const n=new Set,i=new Set;for(const r of e)t(r.children);for(const r of n)r.notify()}function s(e,t,n){return new gg(e,t,n?.isEqual)}function a(e,t,n){return new mg(e,t,n?.isEqual)}function l(){return{id:vg,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function d(e=vg){return{id:Pg,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...wg}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function c(e){return!!e&&"page"===e.typeName}function u(e){return!!e&&"shape"===e.typeName}function h(e){return!!e&&"session"===e.typeName}function p(e){return!!e&&"binding"===e.typeName}function g(e){return!!e&&"asset"===e.typeName}function f(e){return"document"===e.scope}function m(e){return{kind:"theme",slot:e}}function S(e){return{kind:"custom",value:e}}function y(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&Cg.includes(e.slot)}function x(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function b(e){return"string"==typeof e||y(e)||x(e)}function I(e){return Tg[e]}function v(e,t){if(y(e))return e;if(x(e))return e;if("string"!=typeof e)return t;const n=e.trim().toLowerCase();if("transparent"===n)return"transparent";const i=Bg[n];return i?m(i):e}function P(e){return"string"==typeof e?e:"custom"===e.kind?e.value:`var(${I(e.slot)}, ${Eg[e.slot]})`}function w(e,t){if("string"==typeof e)return e;if("custom"===e.kind)return e.value;const n=I(e.slot),i=Eg[e.slot];return t?.(n,i)??i}function k(e){return"string"==typeof e?"transparent"===e.trim().toLowerCase():"custom"===e.kind&&"transparent"===e.value.trim().toLowerCase()}function C(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 T(e,t,n){let i=e.computeShapeExportPageBounds(t);if(!F(i))return i;for(const r of((e,t,n)=>{const i=[];for(const r of B(e,t,n)){const t=A(e,r);t&&F(t)&&i.push(t)}return i})(e,t,n)){const e=R(i,r);if(!e)return null;i=e}return i}function E(e,t,n,i,r){const o=[];for(const s of B(e,t,n)){const t=M(e,s,i,r);t&&o.push(t)}return o}function B(e,t,n){const i=[],r=new Set;let o=t.parentId;for(;o.startsWith("shape:");){const t=o;if(r.has(t))break;r.add(t);const s=e.getShape(t);if(!s)break;n.has(s.id)&&i.push(s),o=s.parentId}return i.reverse()}function M(e,t,n,i){if(n.has(t.id))return n.get(t.id)??null;const r=e.getShapeUtil(t).getChildExportClipLocalBounds(t);if(!r||!F(r))return n.set(t.id,null),null;const o=i.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:r.x,y:r.y,width:r.w,height:r.h,transform:e.computeShapeExportToPageTransform(t).toSvgString()}}]});return n.set(t.id,o),o}function A(e,t){const n=e.getShapeUtil(t).getChildExportClipLocalBounds(t);if(!n||!F(n))return null;const i=e.computeShapeExportToPageTransform(t);return bg.FromPoints([new xg(n.minX,n.minY),new xg(n.maxX,n.minY),new xg(n.maxX,n.maxY),new xg(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))}function R(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),r=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY);return r<n||o<i?null:new bg(n,i,r-n,o-i)}function L(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}="${$("number"==typeof i?U(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(L).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function F(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 $(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function U(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function D(e){return e[Ag]}function z({editor:e,exporters:t,shapeIds:n}){const i=Array.from(n),r=e.getShapeExportTraversalIds(i),o=[];for(const c of r){const n=e.getShape(c);n?(H(e.computeShapeExportPageBounds(n))||o.push({kind:"missing-bounds",id:n.id,canRepair:!1}),t.get(n.type)||o.push({kind:"missing-exporter",id:n.id,canRepair:!1})):o.push({kind:"missing-shape",id:c,canRepair:!1})}const s=new Set(r),a=new Set;for(const c of D(e).getAll().filter(p)){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))&&o.push({kind:"duplicate-exclusive-binding",id:c.id,canRepair:!0}),a.add(c.id)):o.push({kind:"invalid-binding",id:c.id,canRepair:!0}):o.push({kind:"missing-binding-endpoint",id:c.id,canRepair:!0})}const l=o.filter(e=>e.canRepair).length,d=o.length-l;return{requestedShapeIds:i,issues:o,repairableIssueCount:l,fatalIssueCount:d,canExport:0===d}}function H(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 _(e){return e.added.length>0||e.updated.length>0||e.removed.length>0}function N(e){return e instanceof Map?new Map(e):new Map(Array.from(e,e=>[e.id,e]))}function O(e,t){const n=N(e),i=N(t),r={added:[],updated:[],removed:[]};for(const[o,s]of n){const e=i.get(o);e?e!==s&&r.updated.push({before:s,after:e}):r.removed.push(s)}for(const[o,s]of i)n.has(o)||r.added.push(s);return r}function W(e){return{added:[...e.removed],updated:e.updated.map(e=>({before:e.after,after:e.before})),removed:[...e.added]}}function Y(e,t){const n=new Map,i=new Map,r=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)r.set(s.id,s);for(const s of t.added){const e=r.get(s.id);if(e){r.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=r.get(s.after.id);if(e){r.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),r.set(s.id,e.before)):r.set(s.id,s)}const o={added:[],updated:[],removed:[]};for(const s of n.values())o.added.push(s);for(const s of i.values())s.before!==s.after&&o.updated.push(s);for(const s of r.values())o.removed.push(s);return o}function X(e,t){return{id:e.id,forward:Y(e.forward,t),parentIds:e.parentIds}}function K(e,t){return{forward:t,inverse:W(t),label:e}}function V(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function q(e,t,n){const i=e.getShape(t);if(!i)return;const r=e.getContainingParentIdForShapeRecord(i);r&&r!==i.parentId&&e.commands.reparentShapes({ids:[t],parentId:r},n)}function j(e,t,n){const i=n?.source??"user";D(e).atomic(()=>{const n=[],r=[];for(const i of t){const t=e.getShape(i.id);if(!t)continue;const o=i.x??t.x,s=i.y??t.y,a=i.rotation??t.rotation,l=i.scaleX??t.scaleX,d=i.scaleY??t.scaleY,c=void 0===i.opacity?t.opacity:G(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&&o===t.x&&s===t.y&&a===t.rotation&&l===t.scaleX&&d===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:o,y:s,rotation:a,scaleX:l,scaleY:d,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),r.push({before:t,after:S})}0!==n.length&&(D(e).put(n,i),e.bindings.handleShapeChanges(r,i),((e,t,n)=>{const i=new Set(t.map(e=>e.after.id)),r=new Set;for(const o of t)Q(e,o.before,r),Q(e,o.after,r);Z(e,r,n,i)})(e,r,i))},i)}function G(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Z(e,t,n,i=new Set){const r=[],o=[];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 l=e.shapeUtils.get(t.type),d={...t,x:n.x,y:n.y,props:l.validateProps({...a,w:n.w,h:n.h})};r.push(d),o.push({before:t,after:d})}0!==r.length&&(D(e).put(r,n),e.bindings.handleShapeChanges(o,n))}function Q(e,t,n){const i=new Set([t.id]);let r=t.parentId;for(;r.startsWith("shape:");){const t=e.getShape(r);if(!t||i.has(t.id))return;i.add(t.id),e.getShapeUtil(t).isTransformDescendantContainer(t)&&n.add(t.id),r=t.parentId}}function J(e,t,n){const i=n?.source??"user",r=e.getShapeIdsIncludingDescendants(t),o=((e,t)=>{const n=new Set;for(const i of t){const t=e.getShape(i);t&&Q(e,t,n)}return n})(e,r),s=new Set(r),a=e.getUnreferencedAssetIdsAfterShapeDelete(r);D(e).atomic(()=>{e.sideEffects.runBeforeDelete("shape",r,i),D(e).remove(r,i),a.length>0&&D(e).remove(a,i);const t=((e,t,n,i)=>{const r=[],o=[...t].sort((t,n)=>e.getDescendantShapeIds(n).length-e.getDescendantShapeIds(t).length);for(let s=0;s<o.length;s+=1){const t=o[s];if(!t||n.has(t))continue;const a=e.getShape(t),l=a?e.getChildShapeIds(a.id).filter(t=>!n.has(t)&&!!e.getShape(t)):[];if(!a||!e.getShapeUtil(a).isTransformDescendantContainer(a)||l.length>0)continue;const d=new Set;Q(e,a,d);for(const e of d)o.push(e);e.sideEffects.runBeforeDelete("shape",[a.id],i),D(e).remove([a.id],i),n.add(a.id),r.push(a.id)}return r})(e,o,s,i);Z(e,o,i,s),e.sideEffects.runAfterDelete("shape",[...r,...t],i)},i)}function ee(e,t){return e.bindings.canBind(t)}function te(e){return Math.min(8,Math.max(.1,e))}function ne(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 ie(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function re(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],r=t[n];if(!i||!r||i.x!==r.x||i.y!==r.y)return!1}return!0}function oe(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 se(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 ae(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 le(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 de(e,t,n){const i=new Set([e.id]);let r=e.parentId;for(;r.startsWith("shape:");){const e=r;if(i.has(e))return null;i.add(e);const n=t.get(e);if(!n)return null;r=n.parentId}return n.has(r)?r:null}function ce(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],r=t[n];if(!i||!r)return!1;if(i.id!==r.id||i.shape!==r.shape||i.isSelected!==r.isSelected||!oe(i.bounds,r.bounds))return!1}return!0}function ue(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 he(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function pe(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)=>pe(e,t[n]));const n=e,i=t,r=Object.keys(n),o=Object.keys(i);return r.length===o.length&&r.every(e=>Object.prototype.hasOwnProperty.call(i,e)&&pe(n[e],i[e]))}function ge(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 r=e.getShape(t);for(;r?.parentId.startsWith("shape:");){const t=r.parentId;if(n.has(t))return!0;if(i.has(t))return!1;i.add(t),r=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),r=n.map(t=>e.getShape(t)).filter(e=>!!e).map(we);return 0===r.length?null:{type:"land/clipboard",version:1,source:{app:"land"},rootShapeIds:t,records:{shapes:r,bindings:me(e,r,i),assets:Se(e,r)},bounds:ye(e,n)}}function fe(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",r=e.getCurrentPageId(),o=(e=>{const t=e.payload.bounds;return e.pagePoint?e.pagePoint.sub(new xg(t.x+t.w/2,t.y+t.h/2)):e.offset??Dg})(t),s=new Map,a=new Map,l=[];D(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=e.createAssetRecord({type:t.type,props:Pe(t.props),meta:Pe(t.meta)});return s.set(t.id,n.id),n});t.length>0&&e.commands.createAssetsFromRecords(t,{source:i});const l=n.records.shapes.map(t=>{const n=((e,t)=>ve(e,t))(t.props,s),i=e.createShapeRecord({type:t.type,x:t.x+o.x,y:t.y+o.y,props:n,parentId:r,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,meta:Pe(t.meta)});return a.set(t.id,i.id),{original:t,draft:i}}).map(({original:e,draft:t})=>({...t,parentId:xe(e.parentId,a,r)}));l.length>0&&e.commands.createShapesFromRecords(l,{source:i});for(const r of n.records.bindings){const t=a.get(r.fromId),n=a.get(r.toId);t&&n&&e.commands.createBinding({type:r.type,fromId:t,toId:n,props:Pe(r.props),meta:Pe(r.meta)},{source:i})}},i);for(const d of n.rootShapeIds){const e=a.get(d);e&&l.push(e)}return l.length>0&&e.commands.setSelectedShapeIds(l,{source:i}),l}function me(e,t,n){const i=[],r=new Set;for(const o of t)for(const t of e.getBindingsForShape(o.id))r.has(t.id)||n.has(t.fromId)&&n.has(t.toId)&&(r.add(t.id),i.push(we(t)));return i}function Se(e,t){const n=[],i=new Set;for(const r of t)for(const t of be(r)){if(i.has(t))continue;const r=e.getAsset(t);r&&(i.add(t),n.push(we(r)))}return n}function ye(e,t){const n=(e=>{if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.minX),n=Math.min(n,o.minY),i=Math.max(i,o.maxX),r=Math.max(r,o.maxY);return new bg(t,n,i-t,r-n)})(t.map(t=>e.getShapePageBounds(t)).filter(e=>!!e))??new bg(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function xe(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function be(e){const t=[],n=new Set,i=he(e);return i&&(n.add(i),t.push(i)),Ie(e.props,n,t),t}function Ie(e,t,n){if(ke(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)Ie(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))Ie(i,t,n)}function ve(e,t){if(ke(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>ve(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[i,r]of Object.entries(e))n[i]=ve(r,t);return n}function Pe(e){return we(e)}function we(e){if(Array.isArray(e))return e.map(we);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=we(i);return t}function ke(e){return"string"==typeof e&&e.startsWith("asset:")}function Ce(e,t,n,i,r="document"){if(t>n)throw new Hg(`Unsupported ${r} snapshot schema version: ${t} is newer than ${n}`);let o=e;for(let s=t;s<n;s+=1){const e=i.find(e=>e.fromVersion===s);if(!e)throw new Hg(`No ${r} snapshot migration from schema version ${s}`);o=e.up(o)}return o}function Te(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ee(e,t){return"string"==typeof e?e:t}function Be(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Me(e,t){return"boolean"==typeof e?e:t}function Ae(e){return Te(e)?e:{}}function Re(e){return Te(e)?{x:Be(e.x,wg.x),y:Be(e.y,wg.y),z:Math.min(8,Math.max(.1,Be(e.z,wg.z)))}:null}function Le(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function Fe(e,t){if(!Te(e))throw new Hg(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=Be(n,NaN);if(!Number.isFinite(i)||i<1)throw new Hg(`Unsupported ${t} snapshot schema version: ${String(n)}`);if(!Array.isArray(e.records))throw new Hg(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:1,records:Ce(e.records,i,1,"document"===t?_g:Ng,t)}}function $e(e,t){const n=e.filter(e=>"page"===e.typeName),i=e.filter(e=>"shape"===e.typeName),r=e.filter(p),o=e.filter(g),s=(n.length>0?[...n].sort((e,t)=>e.index.localeCompare(t.index)):[l()]).map((e,t)=>({...e,index:String(t+1).padStart(4,"0")})),a=s[0]?.id??"page:default",d=new Set(s.map(e=>e.id)),c=[...i].sort((e,t)=>e.index.localeCompare(t.index)),u=new Map(c.map(e=>[e.id,e])),h=c.map((e,n)=>{const i=(({pageIds:e,parentId:t,shapeById:n,shapeId:i,shapeUtils:r})=>{if(t.startsWith("page:"))return e.has(t);if(t===i)return!1;const o=n.get(t);if(!o)return!1;if(!r.get(o.type).canReceiveChildren(o))return!1;const s=new Set([i]);let a=o.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(!r.get(t.type).canReceiveChildren(t))return!1;a=t.parentId}return e.has(a)})({pageIds:d,parentId:e.parentId,shapeById:u,shapeId:e.id,shapeUtils:t})?e.parentId:a,r={...e,parentId:i,index:e.index||String(n+1).padStart(6,"0")};return t.get(r.type).repairLoadedShape(r)??r}),f=new Set(h.map(e=>e.id)),m=r.filter(e=>f.has(e.fromId)&&f.has(e.toId));return[...s,...o,...h,...m]}function Ue(e,t,n){const i=Fe(e,"document"),r=new Set,o=[];return i.records.forEach((e,i)=>{if(!Te(e))throw new Hg("Invalid document record: expected object");if("string"!=typeof e.id)throw new Hg("Invalid document record id");if(r.has(e.id))throw new Hg(`Duplicate document record id: ${e.id}`);if(r.add(e.id),"page"!==e.typeName)if("shape"!==e.typeName)if("binding"!==e.typeName){if("asset"!==e.typeName)throw new Hg(`Unsupported document record type: ${String(e.typeName)}`);o.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new Hg("Invalid asset record id");if("string"!=typeof e.type)throw new Hg("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:Te(e.props)?e.props:{},meta:Ae(e.meta)}})(e))}else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new Hg("Invalid binding record id");if("string"!=typeof e.type)throw new Hg("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new Hg(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new Hg(`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:Ae(e.meta)}})(e,n));else o.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new Hg("Invalid shape record id");if("string"!=typeof e.type)throw new Hg("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new Hg(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:Ee(e.index,String(n+1).padStart(6,"0")),x:Be(e.x,0),y:Be(e.y,0),rotation:Be(e.rotation,0),scaleX:Be(e.scaleX,1),scaleY:Be(e.scaleY,1),opacity:Math.min(1,Math.max(0,Be(e.opacity,1))),isHidden:Me(e.isHidden,!1),isLocked:Me(e.isLocked,!1),meta:Ae(e.meta),type:e.type,props:t.get(e.type).validateProps(e.props)}})(e,t,i));else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("page:"))throw new Hg("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:Ee(e.name,`Page ${t+1}`),index:Ee(e.index,String(t+1).padStart(4,"0")),meta:Ae(e.meta)}})(e,i))}),{schemaVersion:1,records:$e(o,t)}}function De(e){const t=Fe(e,"session").records[0];if(!Te(t))return{schemaVersion:1,records:[d()]};const n=d(),i="string"==typeof t.currentPageId&&t.currentPageId.startsWith("page:")?t.currentPageId:n.currentPageId,r=(e=>{if(!Te(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Re(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),o=(e=>{if(!Te(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Le(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:Ee(t.activeToolId,n.activeToolId),isToolLocked:"boolean"==typeof t.isToolLocked?t.isToolLocked:n.isToolLocked,editingShapeId:null,shapeEditingSession:null,pageCameraById:Object.keys(r).length>0?r:n.pageCameraById,pageSelectedShapeIdsById:Object.keys(o).length>0?o:n.pageSelectedShapeIdsById,meta:Ae(t.meta)}]}}function ze(){return xg.Zero()}function He(e,t,n){if(n<=0)return ze();const i=t.x-e.x,r=t.y-e.y;return 0===i&&0===r?ze():new xg(i/n,r/n)}function _e(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function Ne(e){return{...e,anchorPagePoint:e.anchorPagePoint.clone(),boundaryPagePoint:e.boundaryPagePoint.clone()}}function Oe(e,t){return e.terminal===t.terminal&&ie(e.anchorPagePoint,t.anchorPagePoint)&&ie(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function We(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],r=t[n];if(!i||!r||!Oe(i,r))return!1}return!0}function Ye(e,t){return Oe(e,t)&&e.ownerShapeId===t.ownerShapeId&&(e.targetShapeId??null)===(t.targetShapeId??null)}function Xe(e,t){return t.getExportBounds(e)}function Ke(e,t){return t.getLocalToPageTransform(e)}function Ve(e,t){const n=je(e,t);return Ig.Translate(n.x,n.y).compose(Ig.Rotate(e.rotation)).compose(Ig.Scale(e.scaleX,e.scaleY)).compose(Ig.Translate(-n.x,-n.y))}function qe(e,t){return Ke(e,t)}function je(e,t){return t.getBounds(e).center}function Ge(e,t,n){return Ve(e,n).applyToPoint(t)}function Ze(e,t,n){if(0===e.scaleX||0===e.scaleY){const i=je(e,n),r=t.sub(i).rot(-e.rotation);return i.add(new xg(0===e.scaleX?0:r.x/e.scaleX,0===e.scaleY?0:r.y/e.scaleY))}return Ve(e,n).invert().applyToPoint(t)}function Qe(e,t){return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(n=>Ge(e,n,t))}function Je(e,t){const n=Qe(e,t),i=((e,t)=>{const n=t.getBounds(e);return[new xg(n.minX,n.minY),new xg(n.maxX,n.minY),new xg(n.maxX,n.maxY),new xg(n.minX,n.maxY)].map(n=>Ge(e,n,t))})(e,t);return{bounds:bg.FromPoints(n),center:je(e,t),corners:i,outlineVertices:n}}function et(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function tt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function nt(e,t,n){const i=e.get(t);if(!i)return!1;const r=i.indexOf(n);if(r<0)return!1;if(1===i.length)return e.delete(t),!0;const o=i.slice();return o.splice(r,1),e.set(t,o),!0}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)if(e[n]!==t[n])return!1;return!0}function rt(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function ot(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):rt(t,n)}function st(e,t,n,i,r){const o=e.get(t);if(!o)return e.set(t,[n.id]),!0;if(o.includes(n.id))return!1;const s=o.slice();return s.splice(((e,t,n,i)=>{for(let r=0;r<e.length;r+=1){const o=i(e[r]);if(o&&ot(n,t,o)<0)return r}return e.length})(o,n,i,r),0,n.id),e.set(t,s),!0}function at(e,t,n,i){const r=e.get(t);if(!r)return void e.set(t,[n.id]);if(r.includes(n.id))return;let o=r.length;for(let a=0;a<r.length;a+=1){const e=i(r[a]);if(void 0!==e&&e.localeCompare(n.index)>0){o=a;break}}const s=r.slice();s.splice(o,0,n.id),e.set(t,s)}function lt(e,t,n){nt(e,t,n)}function dt(e){return u(e.before)&&u(e.after)}function ct(e){return p(e.before)&&p(e.after)}function ut(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],r=t[n];if(!i||!r||!ie(i,r))return!1}return!0}function ht(e,t){return ut(e.outlineVertices,t.outlineVertices)&&oe(e.pageBounds,t.pageBounds)&&oe(e.frameBounds,t.frameBounds)&&e.rotation===t.rotation&&ie(e.rotationCenter,t.rotationCenter)&&ie(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function pt(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)<Xg?0:t}function gt(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=[],r=[],o=[];let s=1/0,a=1/0,l=-1/0,d=-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&&r.push(...u),!c.contributesToSelectionFrame(n,{editor:e}))continue;o.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),l=Math.max(l,h.bounds.maxX),d=Math.max(d,h.bounds.maxY))}const c=Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(l)&&Number.isFinite(d)?new bg(s,a,l-s,d-a):null,u=!(o.length>0)||function(e){if(0===e.length)return!0;const t=pt(e[0]?.rotation??0);return e.every(e=>{return n=t,Math.abs(pt(e.rotation)-pt(n))<Xg;var n})}(o),h=((e,t)=>0!==e.length&&t?pt(e[0]?.rotation??0):0)(o,u),p=o.some(e=>Math.abs(pt(e.rotation))>Xg),g=c?.center??null,f=0===i.length?null:Math.abs(h)<Xg||!g?bg.FromPoints(i):bg.FromPoints(i.map(e=>xg.RotWith(e,g,-h))),m=r.length>0?bg.FromPoints(r):null;return{outlineVertices:i,pageBounds:c,frameBounds:f,rotation:h,rotationCenter:g,selectionAnchorPagePoint:f&&g?Math.abs(h)<Xg?new xg(f.center.x,f.minY):xg.RotWith(new xg(f.center.x,f.minY),g,h):m?new xg(m.center.x,m.minY):null,hasRotation:p,hasCompatibleRotation:u}}function ft(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 mt(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function St(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],r=t[n];if(!i||!r||!mt(i,r))return!1}return!0}function yt(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 xt(e,t){return e===t||(e&&t?ft(e.bounds,t.bounds)&&mt(e.center,t.center)&&St(e.corners,t.corners)&&St(e.outlineVertices,t.outlineVertices):e===t)}function bt(e){return e?e.clone():e}function It(e){return e?e.clone():e}function vt(e){return e?.map(e=>e.clone())}function Pt(e){if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.minX),n=Math.min(n,o.minY),i=Math.max(i,o.maxX),r=Math.max(r,o.maxY);return new bg(t,n,i-t,r-n)}function wt(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 kt(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),r=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY);return r<n||o<i?null:new bg(n,i,r-n,o-i)}function Ct(e,t){return t.canReceiveChildren(e)&&!t.isTransformDescendantContainer(e)}function Tt(e,t,n,i){const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),l=(a.x*o.y-a.y*o.x)/s,d=(a.x*r.y-a.y*r.x)/s;return l>=0&&l<=1&&d>=0&&d<=1?l:null}function Et(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new xg(n.minX,n.minY),new xg(n.maxX,n.minY),new xg(n.maxX,n.maxY),new xg(n.minX,n.maxY)];for(let r=0;r<i.length;r+=1){const n=i[r],o=i[(r+1)%i.length];if(n&&o&&null!==Tt(e,t,n,o))return!0}return!1}function Bt(e,t){return bg.FromPoints([new xg(e.minX,e.minY),new xg(e.maxX,e.minY),new xg(e.maxX,e.maxY),new xg(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function Mt(e){return"top_left"===e||"left"===e||"bottom_left"===e}function At(e){return"top_right"===e||"right"===e||"bottom_right"===e}function Rt(e){return"top_left"===e||"top"===e||"top_right"===e}function Lt(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function Ft(e){return Mt(e)!==At(e)&&Rt(e)!==Lt(e)}function $t({handleId:e,scaleX:t,scaleY:n}){const i=Mt(e)?t<0?"right":"left":At(e)?t<0?"left":"right":null,r=Rt(e)?n<0?"bottom":"top":Lt(e)?n<0?"top":"bottom":null;return"top"===r&&"left"===i?"top_left":"top"===r&&"right"===i?"top_right":"bottom"===r&&"right"===i?"bottom_right":"bottom"===r&&"left"===i?"bottom_left":r||i||e}function Ut({axis:e,startBounds:t,bounds:n,handleId:i,scale:r,isResizingFromCenter:o}){const s=Math.sign(r??1)||1;return o?s:"x"===e?Mt(i)?n.minX>=t.maxX?-1:1:At(i)?n.maxX<=t.minX?-1:1:s:Rt(i)?n.minY>=t.maxY?-1:1:Lt(i)?n.maxY<=t.minY?-1:1:s}function Dt({requestedBounds:e,handleId:t,actualWidth:n,actualHeight:i,scaleX:r,scaleY:o,isResizingFromCenter:s}){return new bg(s?e.center.x-n/2:Mt(t)?r<0?e.minX:e.maxX-n:At(t)?r<0?e.maxX-n:e.minX:e.center.x-n/2,s?e.center.y-i/2:Rt(t)?o<0?e.minY:e.maxY-i:Lt(t)?o<0?e.maxY-i:e.minY:e.center.y-i/2,n,i)}function zt({bounds:e,startBounds:t,handleId:n,aspectRatio:i,isResizingFromCenter:r,scaleX:o,scaleY:s}){if(i<=0)return{bounds:e,scaleX:o??e.w/Math.max(1,t.w),scaleY:s??e.h/Math.max(1,t.h)};let a=e.w,l=e.h;const d=Math.sign(o??1)||1,c=Math.sign(s??1)||1;switch(n){case"left":case"right":l=a/i;break;case"top":case"bottom":a=l*i;break;default:{const e=a/Math.max(1,t.w),n=l/Math.max(1,t.h);Math.abs(e)>Math.abs(n)?l=a/i:a=l*i;break}}if(r){const e=t.center;return{bounds:new bg(e.x-a/2,e.y-l/2,a,l),scaleX:d*(a/Math.max(1,t.w)),scaleY:c*(l/Math.max(1,t.h))}}let u;switch(n){case"top_left":u=new bg(d<0?e.minX:e.maxX-a,c<0?e.minY:e.maxY-l,a,l);break;case"top_right":u=new bg(d<0?e.maxX-a:e.minX,c<0?e.minY:e.maxY-l,a,l);break;case"bottom_right":u=new bg(d<0?e.maxX-a:e.minX,c<0?e.maxY-l:e.minY,a,l);break;case"bottom_left":u=new bg(d<0?e.minX:e.maxX-a,c<0?e.maxY-l:e.minY,a,l);break;case"top":u=new bg(t.center.x-a/2,c<0?t.maxY:t.maxY-l,a,l);break;case"right":u=new bg(d<0?t.minX-a:t.minX,t.center.y-l/2,a,l);break;case"bottom":u=new bg(t.center.x-a/2,c<0?t.minY-l:t.minY,a,l);break;case"left":u=new bg(d<0?t.maxX:t.maxX-a,t.center.y-l/2,a,l)}return{bounds:u,scaleX:d*(a/Math.max(1,t.w)),scaleY:c*(l/Math.max(1,t.h))}}function Ht(e,t){return e.x===t.x&&e.y===t.y}function _t(e){return[new xg(e.minX,e.minY),new xg(e.center.x,e.minY),new xg(e.maxX,e.minY),new xg(e.minX,e.center.y),e.center,new xg(e.maxX,e.center.y),new xg(e.minX,e.maxY),new xg(e.center.x,e.maxY),new xg(e.maxX,e.maxY)]}function Nt(e,t){return"x"===t?e.x:e.y}function Ot(e,t){return"x"===t?e.minX:e.minY}function Wt(e,t){return"x"===t?e.maxX:e.maxY}function Yt(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function Xt(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Kt(e,t){return null!==Xt(e,t)}function Vt(e,t){return new bg(e.x+t.x,e.y+t.y,e.w,e.h)}function qt(e,t,n){return Vt(e,((e,t)=>"x"===e?new xg(t,0):new xg(0,t))(t,n))}function jt(e){return[new xg(e.minX,e.minY),new xg(e.maxX,e.minY),new xg(e.maxX,e.maxY),new xg(e.minX,e.maxY)]}function Gt(e,t,n){const i=n.sub(t),r=i.len2();if(r<=1e-8)return e.dist2(t);const o=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/r));return e.dist2(new xg(t.x+i.x*o,t.y+i.y*o))}function Zt(e,t,n){const i=n.sub(t),r=i.len2();if(r<=1e-8)return t.clone();const o=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/r));return new xg(t.x+i.x*o,t.y+i.y*o)}function Qt(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 r=2===t.length?1:t.length;for(let o=0;o<r;o+=1){const r=t[o],s=t[(o+1)%t.length];if(!r||!s)continue;const a=Gt(e,r,s);a>=i||(i=a,n=Zt(e,r,s))}return n?{point:n,distanceSquared:i}:null}function Jt(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 en(e,t,n,i){let r=i+1,o=0;const s=[];for(const a of t)for(const t of n){const n=Nt(t.point,e)-Nt(a,e),l=Math.abs(n);if(!(l>i||l>r+1e-8)){if(l<r-1e-8)r=l,o=n,s.length=0;else if(Math.abs(n-o)>1e-8)continue;s.push({selectionPoint:a,candidatePoint:t.point,candidateNodeId:t.nodeId})}}return s.length>0?{type:"points",nudge:o,pairs:s}:null}function tn(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new xg(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new xg(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new xg(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new xg(t.minX,t.maxY))}return n}function nn(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>Ot(e.bounds,t)-Ot(n.bounds,t)),r=[];for(let o=0;o<i.length;o+=1){const e=i[o];if(e)for(let s=o+1;s<i.length;s+=1){const o=i[s];if(!o)continue;const a=Wt(e.bounds,t),l=Ot(o.bounds,t);if(a>=l)continue;const d=Xt(Yt(e.bounds,t),Yt(o.bounds,t));d&&r.push({direction:n,startNode:e,endNode:o,length:l-a,breadthIntersection:d})}}return r}function rn(e,t,n,i){const r=Xt(Yt(t.bounds,i),Yt(n.bounds,i));return r?{direction:e,startNode:t,endNode:n,length:Ot(n.bounds,i)-Wt(t.bounds,i),breadthIntersection:r}:null}function on(e,t,n,i){const r=Yt(t,e),o=((e,t)=>"x"===t?e.w:e.h)(t,e);let s=i+1,a=null;const l=(e,t)=>{const n=Math.abs(e);0===t.length||n>i||n>=s-1e-8||(s=n,a={type:"gaps",nudge:e,gaps:t})},d=n=>({id:"selection",bounds:qt(t,e,n)});for(const c of n){if(o<=c.length&&Kt(r,c.breadthIntersection)){const n=Wt(c.startNode.bounds,e)+(c.length-o)/2-Ot(t,e),i=d(n);l(n,[rn(c.direction,c.startNode,i,e),rn(c.direction,i,c.endNode,e)].filter(e=>null!==e))}const n=Wt(c.endNode.bounds,e)+c.length-Ot(t,e),i=d(n);if(Kt(Yt(i.bounds,e),c.breadthIntersection)){const t=rn(c.direction,c.endNode,i,e);l(n,t?[c,t]:[])}const s=Ot(c.startNode.bounds,e)-c.length-Wt(t,e),a=d(s);if(Kt(Yt(a.bounds,e),c.breadthIntersection)){const t=rn(c.direction,a,c.startNode,e);l(s,t?[t,c]:[])}}return a}function sn(e,t){return e?t?Math.abs(e.nudge)<=Math.abs(t.nudge)?e:t:e:t}function an(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&&Ht(e.rotationCenter,t.rotationCenter)&&Ht(e.line[0],t.line[0])&&Ht(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&Ht(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&&Ht(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>Ht(e.startEdge[0],t.startEdge[0])&&Ht(e.startEdge[1],t.startEdge[1])&&Ht(e.endEdge[0],t.endEdge[0])&&Ht(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function ln(e){return"horizontal"===e.direction?{startEdge:[new xg(e.startNode.bounds.maxX,e.startNode.bounds.minY),new xg(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new xg(e.endNode.bounds.minX,e.endNode.bounds.minY),new xg(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new xg(e.startNode.bounds.minX,e.startNode.bounds.maxY),new xg(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new xg(e.endNode.bounds.minX,e.endNode.bounds.minY),new xg(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function dn(e,t,n,i){const r=Jt([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),o=pn(e,r);return{id:gn(e,o,r),type:"points",axis:e,line:o,points:r,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function cn(e,t,n,i){return un(e,t,n).map(t=>dn(e,t,n,i))}function un(e,t,n){const i=new Map;for(const r of t.pairs){const t=Nt(r.selectionPoint.add(n),e).toFixed(8),o=i.get(t);o?o.push(r):i.set(t,[r])}return Array.from(i.values()).map(e=>({type:"points",nudge:t.nudge,pairs:e}))}function hn(e,t,n){return"x"===e?[new xg(t,n.minY),new xg(t,n.maxY)]:[new xg(n.minX,t),new xg(n.maxX,t)]}function pn(e,t){if(0===t.length)return[xg.Zero(),xg.Zero()];let n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(const s of t)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return"x"===e?[new xg(n,r),new xg(n,o)]:[new xg(n,r),new xg(i,r)]}function gn(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 fn(e,t,n,i,r,o){return un(e,t,n).map(t=>((e,t,n,i,r,o)=>{const s=dn(e,t,n,i),a=t.pairs[0],l=Nt(a?.selectionPoint.add(n)??r.center,e),d=new Map(o.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=d.get(g.candidateNodeId);t&&c.push(...hn(e,l,t))}const h=Jt([...s.points,...hn(e,l,r),...c]),p=pn(e,Jt([...hn(e,l,r),...c]));return{...s,id:gn(e,p,h),line:p,points:h}})(e,t,n,i,r,o))}function mn(e){return{id:gn("x",[e,e],[e]),type:"points",axis:"x",line:[e.clone(),e.clone()],points:[e.clone()],rotation:0,rotationCenter:e.clone()}}function Sn(e,t,n){const i="x"===e?new xg(n.x,t.y):new xg(t.x,n.y),r=Jt([n.clone(),i]),o=pn(e,r);return{id:gn(e,o,r),type:"points",axis:e,line:o,points:r,rotation:0,rotationCenter:xg.Zero()}}function yn(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new xg(0,n.y):new xg(n.x,0),r=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:Vt(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:Vt(e.endNode.bounds,i)}:e.endNode}));return{id:`gaps:${r.map(e=>`${e.startNode.id}:${e.endNode.id}:${e.length.toFixed(4)}`).join("|")}`,type:"gaps",direction:r[0]?.direction??"horizontal",gaps:r.map(ln),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function xn(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():xg.RotWith(e,t.rotationCenter,-t.rotation)}function In(e,t){return 0===t.rotation?e.clone():xg.RotWith(e,t.rotationCenter,t.rotation)}function vn(e,t){return In(e,t)}function Pn(e,t,n,i,r){return 0===n?i:i+(e-t)/n*r}function wn({point:e,fromBounds:t,toBounds:n}){return new xg(Pn(e.x,t.minX,t.w,n.minX,n.w),Pn(e.y,t.minY,t.h,n.minY,n.h))}function kn({axis:e,bounds:t,point:n}){return"horizontal"===e?new xg(t.minX+t.maxX-n.x,n.y):new xg(n.x,t.minY+t.maxY-n.y)}function Cn({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new bg(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new bg(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function Tn(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function En(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 Bn(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],r=t[n];if(!i||!r)return!1;if(!(i.id===r.id&&i.usesSelectionPathOverlay===r.usesSelectionPathOverlay&&Tn(i.startPagePoint,r.startPagePoint)&&Tn(i.endPagePoint,r.endPagePoint)&&Tn(i.middlePagePoint,r.middlePagePoint)&&We(i.bindingSegments,r.bindingSegments)&&i.path===r.path))return!1}return!0}function Mn(e,t){return e===t||(e&&t?En(e.bounds,t.bounds)&&e.rotation===t.rotation&&Tn(e.rotationCenter,t.rotationCenter)&&e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius:e===t)}function An(e,t){return e===t||(e&&t?En(e.bounds,t.bounds)&&e.rotation===t.rotation&&Tn(e.rotationCenter,t.rotationCenter):e===t)}function Rn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!An(e[n]??null,t[n]??null))return!1;return!0}function Ln(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function Fn(e,t){return e.id===t.id&&Tn(e.point,t.point)&&En(e.bounds,t.bounds)}function $n(e,t){return e.id===t.id&&Tn(e.point,t.point)&&En(e.bounds,t.bounds)}function Un(e,t){return e.terminal===t.terminal&&Tn(e.point,t.point)&&En(e.bounds,t.bounds)}function Dn(e,t){return Tn(e.point,t.point)&&En(e.bounds,t.bounds)}function zn(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Tn(e.point,t.point)&&En(e.bounds,t.bounds)}function Hn(e,t){return e.id===t.id&&Tn(e.point,t.point)}function _n(e,t){return e.id===t.id&&Tn(e.point,t.point)}function Nn(e,t){return e.terminal===t.terminal&&Tn(e.point,t.point)}function On(e,t){return Tn(e.point,t.point)}function Wn(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Tn(e.point,t.point)}function Yn(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 r=e[i],o=t[i];if(!r||!o||!n(r,o))return!1}return!0}function Xn({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 xg(e.maxX+t,e.minY-t):new xg(e.minX-t,e.maxY+t)}function Kn(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&Yn(e.resizeHandles,t.resizeHandles,Fn)&&Yn(e.rotateHandles,t.rotateHandles,$n)&&Yn(e.terminalHandles,t.terminalHandles,Un)&&Yn(e.middleHandles,t.middleHandles,Dn)&&Yn(e.customHandles,t.customHandles,zn):e===t)}function Vn(e,t){return e===t||(e&&t?Yn(e.resizeHandleAnchors,t.resizeHandleAnchors,Hn)&&Yn(e.rotateHandleAnchors,t.rotateHandleAnchors,_n)&&Yn(e.terminalHandleAnchors,t.terminalHandleAnchors,Nn)&&Yn(e.middleHandleAnchors,t.middleHandleAnchors,On)&&Yn(e.customHandleAnchors,t.customHandleAnchors,Wn):e===t)}function qn(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 jn(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function Gn(e,t,n,i,r){const o=e.map(e=>i(e)),s=e.every(e=>r(e)),a=o.flatMap(e=>e.terminalHandleAnchors),l=o.flatMap(e=>e.middleHandleAnchors),d=o.flatMap(e=>e.customHandleAnchors??[]),c=a.length>0||l.length>0||d.length>0;if(!t)return{resizeHandleAnchors:[],rotateHandleAnchors:[],terminalHandleAnchors:a,middleHandleAnchors:l,customHandleAnchors:d};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,x=u.h<2*m,b=e=>0===h?e:xg.RotWith(e,p,h),I=new xg(u.minX,u.minY),v=new xg(u.center.x,u.minY),P=new xg(u.maxX,u.minY),w=new xg(u.maxX,u.center.y),k=new xg(u.maxX,u.maxY),C=new xg(u.center.x,u.maxY),T=new xg(u.minX,u.maxY),E=new xg(u.minX,u.center.y);return{resizeHandleAnchors:s&&!c&&g?[{kind:"resize",id:"top_left",point:b(I)},...y?[]:[{kind:"resize",id:"top",point:b(v)}],...y&&x?[]:[{kind:"resize",id:"top_right",point:b(P)}],...x?[]:[{kind:"resize",id:"right",point:b(w)}],...y||x?[]:[{kind:"resize",id:"bottom_right",point:b(k)}],...y?[]:[{kind:"resize",id:"bottom",point:b(C)}],...y||x?[]:[{kind:"resize",id:"bottom_left",point:b(T)}],...x?[]:[{kind:"resize",id:"left",point:b(E)}]]:[],rotateHandleAnchors:!s||c||!g||y||x?[]:[{kind:"rotate",id:"bottom_left_rotate",point:b(Xn({bounds:u,rotateOffset:S,referenceRotation:f,frameRotation:h}))}],terminalHandleAnchors:a,middleHandleAnchors:l,customHandleAnchors:d}}function Zn(e,t){const n=8/t,i=n/2,r=e=>new bg(e.x-i,e.y-i,n,n);return{resizeHandles:e.resizeHandleAnchors.map(e=>({...e,bounds:r(e.point)})),rotateHandles:e.rotateHandleAnchors.map(e=>({...e,bounds:r(e.point)})),terminalHandles:e.terminalHandleAnchors.map(e=>({...e,bounds:r(e.point)})),middleHandles:e.middleHandleAnchors.map(e=>({...e,bounds:r(e.point)})),customHandles:e.customHandleAnchors.map(e=>({...e,bounds:r(e.point)}))}}function Qn(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),r=new Set(t.map(e=>e.id)),o=i.map((e,t)=>r.has(e.id)?t:-1).filter(e=>e>=0);return o.length!==t.length?null:{parentId:n,selectedCount:t.length,count:i.length,canMoveBackward:o.some(e=>e>0&&!r.has(i[e-1].id)),canMoveForward:o.some(e=>e<i.length-1&&!r.has(i[e+1].id))}}function Jn(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),r=i.findIndex(e=>e.id===n.id);return r<0?null:{parentId:n.parentId,index:r,count:i.length,canMoveBackward:r>0,canMoveForward:r<i.length-1}}function ei(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 r=e.getChildShapes(i),o=new Set(n.map(e=>e.id)),s=r.map((e,t)=>o.has(e.id)?t:-1).filter(e=>e>=0);return s.length!==n.length?null:{parentId:i,selectedCount:n.length,count:r.length,canMoveBackward:s.some(e=>e>0&&!o.has(r[e-1].id)),canMoveForward:s.some(e=>e<r.length-1&&!o.has(r[e+1].id))}}function ti(e,t,n,i="user"){const r=ei(e,t);if(!r)return!1;const o=e.getChildShapes(r.parentId),s=new Set(t),a=[...o];let l=!1;if("backward"===n)for(let d=1;d<a.length;d+=1){const e=a[d],t=a[d-1];e&&t&&s.has(e.id)&&!s.has(t.id)&&(a[d-1]=e,a[d]=t,l=!0)}else for(let d=a.length-2;d>=0;d-=1){const e=a[d],t=a[d+1];e&&t&&s.has(e.id)&&!s.has(t.id)&&(a[d]=t,a[d+1]=e,l=!0)}return!!l&&(e.cancelInteractionForCommand(),e.commands.updateShapes(a.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:i}),!0)}function ni(e,t,n,i="user"){const r=ei(e,t);if(!r)return!1;const o=e.getChildShapes(r.parentId),s=new Set(t),a=[],l=[];for(const c of o)s.has(c.id)?a.push(c):l.push(c);if(a.length!==s.size)return!1;if(!("back"===n?r.canMoveBackward:r.canMoveForward))return!1;const d="back"===n?[...a,...l]:[...l,...a];return e.cancelInteractionForCommand(),e.commands.updateShapes(d.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:i}),!0}function ii(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 ri(e,t,n,i,r){const o=((e,t,n,i)=>{const r=new Set(n),o=e.getChildShapes(t.parentId).filter(e=>!r.has(e.id));let s=o.length;if(t.beforeId){const e=o.findIndex(e=>e.id===t.beforeId);if(-1===e)return null;s=e}return o.splice(s,0,...i),o.map((n,i)=>({id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+1)}))})(e,t,n,i);return!!o&&(e.cancelInteractionForCommand(),e.commands.updateShapes(o,{source:r}),!0)}function oi(e){const t="string"==typeof e?{key:e}:e;return{key:li(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}}function si(e){const t=oi(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 ai(e,t){return!(li(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 li(e){return e.toLowerCase()}function di(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 ci(e,t,n){return Math.min(n,Math.max(t,e))}function ui(e){return 0===e.length?"none":e.map(e=>`${e.start}-${e.end-1}`).join(", ")}function hi(e,t=0){if(0===e.length)return[];const n=[...e].sort((e,t)=>e.start-t.start),i=[];for(const r of n){const e=i[i.length-1];!e||r.start>e.end+t?i.push({...r}):e.end=Math.max(e.end,r.end)}return i}function pi(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function gi(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function fi(e,t,n=0){return hi(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n)}function mi(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function Si(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:mi(e,t)}}function yi(e,t,n){return e.dist(((e,t,n)=>{const i=t.sub(e),r=n.sub(e),o=i.x*i.x+i.y*i.y;if(0===o)return e;const s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o));return new xg(e.x+i.x*s,e.y+i.y*s)})(t,n,e))}function xi(e,t,n,i){return((e,t,n,i)=>{const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),l=(a.x*o.y-a.y*o.x)/s,d=(a.x*r.y-a.y*r.x)/s;return l>=0&&l<=1&&d>=0&&d<=1})(e,t,n,i)?0:Math.min(yi(e,n,i),yi(t,n,i),yi(n,e,t),yi(i,e,t))}function bi(e){const t=Fe(e,"document"),n=new Set,i=new Set,r=new Set;for(const o of t.records)Ii(o)&&"string"==typeof o.type&&("shape"===o.typeName?n.add(o.type):"binding"===o.typeName?i.add(o.type):"asset"===o.typeName&&r.add(o.type));return{shapeTypes:Pi(n),bindingTypes:Pi(i),assetTypes:Pi(r)}}function Ii(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function vi(e,t){return e.filter(e=>!t.has(e))}function Pi(e){return[...e].sort((e,t)=>e.localeCompare(t))}function wi(e){return[new xg(e.minX,e.minY),new xg(e.maxX,e.minY),new xg(e.maxX,e.maxY),new xg(e.minX,e.maxY)]}function ki(e,t,n,i){const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),l=(a.x*o.y-a.y*o.x)/s,d=(a.x*r.y-a.y*r.x)/s;return l>=0&&l<=1&&d>=0&&d<=1?l:null}function Ci(e,t,n){const i=n.center,r=t.sub(i).rot(-e.rotation);return i.add(new xg(0===e.scaleX?0:r.x/e.scaleX,0===e.scaleY?0:r.y/e.scaleY))}function Ti(e,t,n){const i=e[t];return"number"==typeof i&&Number.isFinite(i)?i:n}function Ei(e){return Math.min(1,Math.max(0,(96-e)/96))}function Bi(e,t,n){if(t.w<=0||t.h<=0||n<=0)return xg.Zero();const i=Math.min(n,32),r=Ei(e.x),o=Ei(t.w-e.x),s=Ei(e.y),a=1.25*(o-r)*i,l=1.25*(Ei(t.h-e.y)-s)*i;return 0===a&&0===l?xg.Zero():new xg(a,l)}function Mi(e,t,n){const i=e.inputs.state.get();if("dragging"!==i.dragPhase||!i.currentPagePoint)return null;let r=i.currentPagePoint;if(!i.currentScreenPoint)return"apply_after_scroll"===n?null:{pagePoint:r,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey};const o=Bi(i.currentScreenPoint,e.viewportScreenSizeSignal.get(),t.elapsed),s=0!==o.x||0!==o.y;return s||"always_apply"===n?(s&&(e.panCamera(o),r=e.screenToPage(i.currentScreenPoint)),{pagePoint:r,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey}):null}function Ai(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 Ri(e,t,n){const i=new Set(n);if(i.has(t))return t;const r=Li(e,t);for(const s of r)if(i.has(s.ancestorId))return s.childId;const o=r[0]?.ancestorId;return o&&n.some(t=>((e,t)=>Li(e,t)[0]?.ancestorId??null)(e,t)===o)?t:r[r.length-1]?.ancestorId??t}function Li(e,t){const n=[];let i=e.getShape(t),r=t;const o=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(o.has(t))return n;o.add(t);const s=e.getShape(t);if(!s)return n;e.getShapeUtil(s).isTransformDescendantContainer(s)&&n.push({ancestorId:s.id,childId:r}),r=s.id,i=s}return n}function Fi({shiftKey:e,accelKey:t}){return e||t}function $i({ctrlKey:e}){return e}function Ui(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function Di(e,t){return Math.round(e/t)*t}function zi(e,t,n,i,r,o,s,a,l,d,c){const u=Hi(l,d),h=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=wn({point:new xg(e.minX,e.minY),fromBounds:t,toBounds:n}),r=wn({point:new xg(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new bg(Math.min(i.x,r.x),Math.min(i.y,r.y),Math.abs(r.x-i.x),Math.abs(r.y-i.y))})({bounds:t.localBounds,fromBounds:n,toBounds:i}),p=In(h.center,u),g=e.getShapeUtil(t.shape).resizeSelectionBounds(t.shape,{handleId:s,pageCenter:p,selectionLocalBounds:h,scaleX:r,scaleY:o,isResizingFromCenter:a,selectionRotation:d,selectionRotationCenter:l});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 Hi(e,t){return{rotation:t,rotationCenter:e}}function _i(e,t,n,i,r,o,s,a,l,d,c){const u=Hi(l,d),h=In(Ni({point:t.startLocalPagePoint,startBounds:n,scaleX:r,scaleY:o,handleId:s,isResizingFromCenter:a}),u),p=In(Ni({point:t.endLocalPagePoint,startBounds:n,scaleX:r,scaleY:o,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 Ni({point:e,startBounds:t,scaleX:n,scaleY:i,handleId:r,isResizingFromCenter:o}){const s=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:Mt(t)?e.maxX:At(t)?e.minX:e.center.x)({startBounds:t,handleId:r,isResizingFromCenter:o}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:Rt(t)?e.maxY:Lt(t)?e.minY:e.center.y)({startBounds:t,handleId:r,isResizingFromCenter:o});return new xg(s+(e.x-s)*n,a+(e.y-a)*i)}function Oi(e,t,n){const i=1===t.length;let r=null;for(const o of t){const t=e.getShapeUtil(o).getSelectionResizeAspectRatioLock(o,{editor:e,handleId:n,isOnlySelected:i});if(null!==t){if(null!==r&&r!==t)return null;r=t}}return r}function Wi(e,t,n,i){const r=e.localBounds.center,o=vn(new xg(e.x+r.x,e.y+r.y),{rotation:n,rotationCenter:t});i.id=e.id,i.x=o.x-r.x,i.y=o.y-r.y,i.rotation=e.rotation+n}function Yi(e,t,n,i,r){const o=e.getShapeUtil(t.shape).updateSelectionPagePoints(t.shape,{pagePoints:[vn(t.startPagePoint,{rotation:i,rotationCenter:n}),vn(t.endPagePoint,{rotation:i,rotationCenter:n})]});r.id=t.shape.id,r.x=o.x,r.y=o.y,r.rotation=o.rotation,r.scaleX=o.scaleX,r.scaleY=o.scaleY,r.props=o.props}function Xi(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 Ki(e,t,n){const i=n?e.getContainingShapeParentIdAtPoint(t,n):e.getContainingShapeParentId(t);if(!i)return null;const r=Xi(e,t);if(n||!r||!r.startsWith("shape:")||i===r)return i;const o=e.getShape(r);return o&&e.getShapeUtil(o).canReceiveChildren(o)&&t.every(t=>{const n=e.getShapeContainment(o.id,t);return"inside"===n||"intersecting"===n})?r:i}function Vi(e,t,n){const i=Ki(e,t,n);i&&t.some(t=>e.getShape(t)?.parentId!==i)&&e.commands.reparentShapes({ids:[...t],parentId:i})}function qi(e,t,n,i={}){let r=!0;return(e=>{const o=new Sg(e,()=>{t.get(),r&&!1===i.fireImmediately?r=!1:(r=!1,n())},void 0);return o.attach(),()=>o.detach()})(e)}function ji(e=[]){const t=new _f;return t.registerCanvasPlugins(e),t}function Gi(e,t){return(e.order??0)-(t.order??0)}function Zi(e=[]){const t=new Wf;return t.registerCanvasPlugins(e),t}function Qi(){return Kp(Xf)}function Ji(e=[]){const t=new Kf;return t.registerCanvasPlugins(e),t}function er(e=[]){const t=new Vf;return t.registerEditorPlugins(e),t}function tr(e=[]){const t=new qf;return t.registerEditorPlugins(e),t}function nr(e,t){return t?jf:P(e)}function ir(e){if(!e.createFeature&&!e.addExtensions)throw new Error(`Land extension "${e.name}" must define createFeature() or addExtensions().`);return new Gf(e,e.addOptions?.()??{})}function rr(e,t){return or(e,t)}function or(e,t){const n={...e};for(const[i,r]of Object.entries(t)){const t=e[i];n[i]=sr(t)&&sr(r)?or(t,r):r}return n}function sr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ar(e){const{extensionName:t,feature:n,source:i}=e;return{id:n.id,extensionName:t,source:i,editorPluginIds:n.editorPlugins.map(e=>e.id),canvasPluginIds:n.canvasPlugins.map(e=>e.id),interactionHandlerIds:n.editorPlugins.flatMap(e=>(e.interactionHandlers??[]).map(e=>e.id)),canvasActionIds:n.editorPlugins.flatMap(e=>(e.canvasActions??[]).map(e=>e.id)),toolbarContributionIds:n.editorPlugins.flatMap(e=>(e.toolbarContributions??[]).map(e=>e.id)),toolbarContributions:n.editorPlugins.flatMap(e=>(e.toolbarContributions??[]).map(e=>({id:e.id,surface:e.surface,placement:e.placement??"context",actionIds:[...e.actionIds]}))),contextMenuContributionIds:n.editorPlugins.flatMap(e=>(e.contextMenuContributions??[]).map(e=>e.id)),contextMenuContributions:n.editorPlugins.flatMap(e=>(e.contextMenuContributions??[]).map(e=>({id:e.id,target:e.target,actionIds:[...e.actionIds]}))),domEventGuardIds:n.canvasPlugins.flatMap(e=>(e.domEventGuards??[]).map(e=>e.id)),canvasOverlayIds:n.canvasPlugins.flatMap(e=>(e.canvasOverlays??[]).map(e=>e.id)),selectionCustomHandleRendererTypes:n.canvasPlugins.flatMap(e=>(e.selectionCustomHandleRenderers??[]).map(e=>e.type)),canvasProviderIds:n.canvasPlugins.flatMap(e=>(e.canvasProviders??[]).map(e=>e.id)),canvasComponentIds:n.canvasPlugins.flatMap(e=>(e.canvasComponents??[]).map(e=>e.id)),shapeTypes:[...n.shapeTypes]}}function lr({editorPlugins:e,canvasPlugins:t,knownHostActionIds:n,rendererRegistry:i,resolvedFeatures:r}){const o=[],s=r.map(({feature:e})=>e.id),a=e.map(e=>e.id),l=t.map(e=>e.id),d=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)),x=new Set(e.flatMap(e=>(e.shapeUtils??[]).map(e=>e.type))),b=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());dr({code:"duplicate-feature-id",ids:s,issues:o,messagePrefix:"Duplicate feature id"}),dr({code:"duplicate-editor-plugin-id",ids:a,issues:o,messagePrefix:"Duplicate editor plugin id"}),dr({code:"duplicate-canvas-plugin-id",ids:l,issues:o,messagePrefix:"Duplicate canvas plugin id"}),dr({code:"duplicate-interaction-handler-id",ids:d,issues:o,messagePrefix:"Duplicate interaction handler id"}),dr({code:"duplicate-canvas-action-id",ids:c,issues:o,messagePrefix:"Duplicate canvas action id"}),dr({code:"duplicate-toolbar-contribution-id",ids:u,issues:o,messagePrefix:"Duplicate toolbar contribution id"}),dr({code:"duplicate-context-menu-contribution-id",ids:h,issues:o,messagePrefix:"Duplicate context menu contribution id"}),(({resolvedFeatures:e,issues:t,knownCanvasActionIds:n})=>{for(const{feature:i}of e)for(const e of i.editorPlugins)for(const r of e.toolbarContributions??[])for(const o of r.actionIds)n.has(o)||t.push({severity:"error",code:"missing-canvas-action",featureId:i.id,pluginId:e.id,shapeType:null,message:`Toolbar contribution ${r.id} references missing action ${o}.`})})({resolvedFeatures:r,issues:o,knownCanvasActionIds:p}),(({resolvedFeatures:e,issues:t,knownCanvasActionIds:n})=>{for(const{feature:i}of e)for(const e of i.editorPlugins)for(const r of e.contextMenuContributions??[])for(const o of r.actionIds)n.has(o)||t.push({severity:"error",code:"missing-context-menu-action",featureId:i.id,pluginId:e.id,shapeType:null,message:`Context menu contribution ${r.id} references missing action ${o}.`})})({resolvedFeatures:r,issues:o,knownCanvasActionIds:p}),dr({code:"duplicate-dom-event-guard-id",ids:g,issues:o,messagePrefix:"Duplicate DOM event guard id"}),dr({code:"duplicate-canvas-overlay-id",ids:f,issues:o,messagePrefix:"Duplicate canvas overlay id"}),dr({code:"duplicate-selection-custom-handle-renderer",ids:m,issues:o,messagePrefix:"Duplicate selection custom handle renderer"}),dr({code:"duplicate-canvas-provider-id",ids:S,issues:o,messagePrefix:"Duplicate canvas plugin provider id"}),dr({code:"duplicate-canvas-component-id",ids:y,issues:o,messagePrefix:"Duplicate canvas plugin component id"});const P=r.flatMap(({feature:e})=>{const t=0===e.shapeTypes.length&&e.editorPlugins.some(e=>(e.toolbarContributions??[]).some(e=>"tool"===e.surface)||void 0!==e.setup);return 0===e.editorPlugins.length&&o.push({severity:"error",code:"missing-editor-plugin",featureId:e.id,pluginId:null,shapeType:null,message:`Feature ${e.id} does not include an editor plugin.`}),0!==e.canvasPlugins.length||t||o.push({severity:"error",code:"missing-canvas-plugin",featureId:e.id,pluginId:null,shapeType:null,message:`Feature ${e.id} does not include a canvas plugin.`}),0!==e.shapeTypes.length||t||o.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=x.has(t),r=b.has(t),s=v.has(t),a=i&&r?"supported":"missing";return n||o.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||o.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||o.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.`}),r||o.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:r,hasCanvasRenderer:s,exportSupport:a}})}),w=o.filter(e=>"error"===e.severity).length;return{verdict:0===w?"pass":"fail",issueCount:o.length,errorCount:w,warningCount:o.length-w,issues:o,featureIds:s,editorPluginIds:a,canvasPluginIds:l,interactionHandlerIds:d,canvasActionIds:c,toolbarContributionIds:u,contextMenuContributionIds:h,domEventGuardIds:g,canvasOverlayIds:f,selectionCustomHandleRendererTypes:m,canvasProviderIds:S,canvasComponentIds:y,registeredRendererTypes:Array.from(v),shapeSummaries:P}}function dr({code:e,ids:t,issues:n,messagePrefix:i}){const r=new Map;for(const o of t)r.set(o,(r.get(o)??0)+1);for(const[o,s]of r)s>1&&n.push({severity:"error",code:e,featureId:null,pluginId:o,shapeType:null,message:`${i}: ${o}.`})}function cr(e){return{type:"doc",content:e.split("\n").map(e=>({type:"paragraph",content:e.length>0?[{type:"text",text:e}]:[]}))}}function ur(e){return e.content.map(e=>mr(e)).join("\n")}function hr(e){if(!e||"object"!=typeof e)return cr("");const t=e,n=Array.isArray(t.content)?t.content.map(e=>xr(e,0)).filter(e=>null!==e):[];return{type:"doc",attrs:Ir(t.attrs),content:n}}function pr(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>yr(e)).join("")??"";return`<p style="margin:0">${t.length>0?t:"<br>"}</p>`})(e)).join("")}function gr(e){return"text"===e.type&&"string"==typeof e.text}function fr(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 mr(e){return gr(e)?e.text:e.content?.map(e=>mr(e)).join("")??""}function Sr(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 yr(e){if(gr(e)){const t=fr(e.marks),n=e.text.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">");return t?`<span style="${Sr(t)}">${n}</span>`:n}return e.content?.map(e=>yr(e)).join("")??""}function xr(e,t){if(!e||"object"!=typeof e)return null;const n=e,i="string"==typeof n.type?n.type:"paragraph",r=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(br).filter(e=>null!==e):void 0}))(n);return e.text.length>0?e:null}return xr(n,t)}(e,t+1)).filter(e=>null!==e):[];return{type:i,attrs:Ir(n.attrs),content:r}}function br(e){return e&&"object"==typeof e?"string"!=typeof e.type?null:{type:e.type,attrs:Ir(e.attrs)}:null}function Ir(e){if(!e||"object"!=typeof e)return;const t=Object.entries(e).map(([e,t])=>[e,vr(t)]).filter(e=>void 0!==e[1]);return t.length>0?Object.fromEntries(t):void 0}function vr(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=>vr(e,t+1)).filter(e=>void 0!==e);if(e&&"object"==typeof e){const n=Object.entries(e).map(([e,n])=>[e,vr(n,t+1)]).filter(e=>void 0!==e[1]);return Object.fromEntries(n)}}}function Pr(e){return e.content.map((e,t)=>((e,t)=>{const n=wr(e,t);
|
|
2
|
-
return
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
return
|
|
10
|
-
return
|
|
11
|
-
return
|
|
12
|
-
return
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
return
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
return
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
tg("div",{"data-ui":"text-editor-host-slot","data-shape-id":e.id,"data-active":r?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:o}),n?tg("div",{"aria-hidden":"true","data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 2px ${jf}`,inset:0,pointerEvents:"none",position:"absolute"}}):null]})}function Ko(e){return uo(e)}function Vo(e,t,n){const i=e.getBindingsToShape(t).find(e=>e.type===n);if(!i)return null;const r=e.getShape(i.fromId);return co(r)?r:null}function qo(e,t){const n=ho(e);e.history.mark(t.historyMarkId);const i=po(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 jo(e,t){const n=e.getShape(t);if(!co(n))return null;const i=e.getBindingsFromShape(t).find(e=>e.type in Zm);if(!i)return null;const r=i.type;return{label:n,ownerId:i.toId,bindingType:r,behavior:Zm[r]}}function Go(e,t,n){e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:n.isExisting?n.editMarkId:n.createMarkId,reuseExistingMark:!n.isExisting},"user")}function Zo(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Qo(e){return Math.max(.01,e.props.scale)}function Jo(e){return e.props.w*Qo(e)}function es(e){return e.props.h*Qo(e)}function ts(e){return new bg(0,0,Jo(e),es(e))}function ns(e){return"left"===e||"right"===e}function is(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>rs(e))??[];return{tag:"p",attrs:{style:"margin:0"},children:t.length>0?t:[{tag:"br"}]}})(e))}function rs(e){if(gr(e)){const t=(e=>{const t=fr(e.marks);return t?Sr(t):void 0})(e);return t?{tag:"span",attrs:{style:t},children:[e.text]}:e.text}return{tag:"span",children:e.content?.map(e=>rs(e))??[]}}function os(e,t,n){return[`color:${t.resolveColor(e.props.color)}`,`font-family:${yo(e.props.font,n)}`,`font-size:${xo(e.props.size)}px`,`line-height:${bo(e.props.size)}px`,`text-align:${vo(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 ss(e){return"shape"===e?.typeName&&"arrow"===e.type}function as(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function ls(e,t,n){const i=e.computeShapePageCenter(n),r=((e,t)=>e.getShapeUtil(t).getSelectionOverlayInfo(t,{editor:e}).middlePagePoint?.clone()??null)(e,n)??(e=>{const t=e.props,n=ds(t.start),i=ds(t.end),r=cs(t.bend)??0;if(!n||!i)return null;const o=xg.Med(n,i).add(i.sub(n).len()?i.sub(n).per().normalize().mul(-r):new xg(0,r)),s=new xg(e.x+(e=>cs(e.props.w)??1)(e)/2,e.y+(e=>cs(e.props.h)??1)(e)/2),a=new xg(e.x+o.x,e.y+o.y);if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return a;const l=a.sub(s);return s.add(new xg(l.x*e.scaleX,l.y*e.scaleY).rot(e.rotation))})(n)??i,o=Math.max(24,120);return{x:r.x-o*t.props.scale/2,y:r.y-t.props.h*t.props.scale/2,rotation:n.rotation,props:{w:o}}}function ds(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 xg(t.x,t.y):null}function cs(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function us(e){return"shape"===e?.typeName&&"geo"===e.type}function hs(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function ps(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function gs(e,t){const n=e.props[t];return"number"==typeof n&&Number.isFinite(n)?n:null}function fs(e,t){const n=gs(e,"h");return!n||t.props.ownerBaseHeight<=0||n===t.props.ownerBaseHeight?null:{...e,props:{...e.props,h:t.props.ownerBaseHeight}}}function ms(e,t,n){const i=e.computeShapeLocalBounds(n),r=e.computeShapePageCenter(n),o=Math.max(16,i.w-32);return{x:r.x-o*t.props.scale/2,y:r.y-t.props.h*t.props.scale/2,rotation:n.rotation,props:{w:o}}}function Ss(){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 r=t.pagePoint.x-n.originPagePoint.x,o=t.pagePoint.y-n.originPagePoint.y;if(r*r+o*o>9)return"continue";const s=e.getShape(n.shapeId);return s&&co(s)&&e.canEditShape(s)?(e.startEditingShape({shapeId:s.id,entryMode:"placeCaret",caretPagePoint:t.pagePoint,markId:oS,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&&co(t)&&n.canEditShape(t)?(n.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:oS},"user"),"handled"):"continue"}return"click"===i.type&&"double_click"===i.name?(t(),((e,t)=>{const n=e.hitTestShape(t.pagePoint);return n?co(n)?e.canEditShape(n)?(e.startEditingShape({shapeId:n.id,entryMode:"selectAll",markId:oS},"user"),"handled"):"continue":"geo"===n.type?((e,t)=>{if(t.isLocked)return"continue";const n=Vo(e,t.id,Gm);return Go(e,n??((e,t)=>{const n=ms(e,ys(t,{...ho(e),autoSize:!1,textAlign:"middle"}),t);return qo(e,{bindingType:Gm,owner:t,historyMarkId:dS,index:`${t.index}${iS}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})})(e,t),{editMarkId:lS,createMarkId:dS,isExisting:!!n}),"handled"})(e,n):(e=>"arrow"===e.type)(n)?((e,t)=>{if(t.isLocked)return"continue";const n=Vo(e,t.id,jm);return Go(e,n??((e,t)=>{const n=ls(e,ys(t,{...ho(e),autoSize:!1,textAlign:"middle"}),t);return qo(e,{bindingType:jm,owner:t,historyMarkId:aS,index:`${t.index}${tS}`,layout:n,bindingProps:{labelPosition:.5}})})(e,t),{editMarkId:sS,createMarkId:aS,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||!co(i)||!t.canEditShape(i))return"continue";const r=t.getShapeEditingSession();return r&&r.shapeId!==i.id?t.completeEditing("user")?(t.startEditingShape({shapeId:i.id,entryMode:"placeCaret",caretPagePoint:n.pagePoint,markId:oS,preserveInteraction:!0},"user"),"handled"):"handled":(!r&&(n.clickCount??1)<2&&((e,t)=>{const n=e.getSelectedShapeIds();if(1!==n.length)return!1;if(n[0]===t)return!0;const i=jo(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 ys(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 xs({fontCatalog:e=Cr()}={}){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 Jm],shapeSvgExporters:[new eS(e)],bindingUtils:[new rS,new nS],interactionHandlers:[Ss()],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")}},Ps("color",e),Ps("font",e),Ps("size",e),Ps("textAlign",e),ws("color",e),ws("font",e),ws("size",e),ws("textAlign",e)],toolbarContributions:[{id:"text.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[zf],getGroups:e=>[{id:"text.tools",items:[{kind:"button",id:"text.tool.text",actionId:zf,value:"text",label:"Text",shortcut:e.editor.shortcuts.getToolShortcutLabel("text"),icon:"type",dataUi:"text-tool-button"}]}]},Is(e),bs(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 Km(e),{shortcut:"t"})}}}function bs(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:()=>vs({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"})}}function Is(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:()=>vs({colorActionId:"text.default-color",fontActionId:"text.default-font",fontCatalog:e,sizeActionId:"text.default-size",textAlignActionId:"text.default-textAlign",dataUiPrefix:"text-default"})}}function vs({colorActionId:e,fontActionId:t,fontCatalog:n,sizeActionId:i,textAlignActionId:r,dataUiPrefix:o}){return[{id:`${o}.style-color`,items:[{kind:"swatches",id:`${o}.color`,actionId:e,label:"Color",options:cS.map(e=>({...e,dataUi:`${o}-color-${e.label.toLowerCase()}-button`}))}]},{id:`${o}.style-font`,items:[{kind:"segmented",id:`${o}.font`,actionId:t,options:n.fontOptions.map(e=>({value:e.id,label:e.label,dataUi:`${o}-font-${e.id}-button`}))}]},{id:`${o}.style-size`,items:[{kind:"stepper",id:`${o}.size`,actionId:i,label:"Size",options:uS.map(e=>({value:e.value,label:e.label,dataUi:`${o}-size-${e.id}-button`}))}]},{id:`${o}.style-align`,items:[{kind:"segmented",id:`${o}.align`,actionId:r,options:hS.map(e=>({...e,dataUi:`${o}-align-${e.value}-button`}))}]}]}function Ps(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?!C(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:n,value:i}){const r=ks(e,i,t);if(void 0===r)return;const o=n.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:r}}));0!==o.length&&n.editor.commands.updateShapes(o,{source:"user"})}}}function ws(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 r=ks(e,i,t);void 0!==r&&n.editor.updateDefaultShapeProps("text",{[e]:r})}}}function ks(e,t,n){if("color"===e)return b(t)?v(t,m("text-slate")):void 0;if("font"===e){if("string"!=typeof t)return;return((e,t)=>"default"===t||Er(t)&&e.fontsById.has(t))(n,t)?t:void 0}if("size"===e){if("number"!=typeof t||!Number.isFinite(t))return;return uS.some(e=>e.value===t)?t:void 0}return"string"==typeof t&&hS.some(e=>e.value===t)?t:void 0}function Cs({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){
|
|
23
|
-
return tg("div",{"data-ui":n,className:Ts("land-canvas__floating-toolbar-layer",t),children:e})}function Ts(...e){return e.filter(Boolean).join(" ")}function Es({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",offset:i=8,surfaces:r}){const o=r.floatingSelectionToolbarPageAnchor;return r.showFloatingSelectionToolbar&&o?tg(Bs,{anchor:o,className:t,dataUi:n,editor:r.context.editor,offset:i,onWheelCapture:Ms,children:e}):null}function Bs({anchor:e,children:t,className:n,dataUi:i,editor:r,offset:o,onWheelCapture:s}){const a=Zp(null);return jp(()=>qi("PageAnchoredChromeSurface.scale",r.cameraZoomSignal,()=>{const e=a.current;if(!e)return;const t=r.cameraZoomSignal.get();e.style.transform=`scale(${1/t}) translateY(calc(-100% - ${o}px))`}),[r,o]),tg($r,{dataUi:`${i}-page-space`,className:As("land-canvas__floating-selection-page-space",n),children:tg("div",{ref:a,"data-ui":i,className:"land-canvas__floating-selection-anchor",onWheelCapture:s,style:{left:e.x,top:e.y,transformOrigin:"0 0",willChange:"transform"},children:t})})}function Ms(e){Jr(e.nativeEvent,e.currentTarget)&&(e.preventDefault(),e.stopPropagation())}function As(...e){return e.filter(Boolean).join(" ")}function Rs(e,t={}){const n=t.enabled??!0,i=t.pageId,r=Xp(t=>n?e.subscribe(t):()=>{},[n,e]),o=Xp(()=>n?e.getSnapshot(i):gS,[n,i,e]);return Jp(r,o,o)}function Ls(e){return Math.max(0,Math.min(1,e))}function Fs(e,t,n){const i=e.getShapeUtil(t);return Ge(t,((e,t,n)=>{const i=e.computeShapeBounds(t);return new xg(i.minX+i.w*n.x,i.minY+i.h*n.y)})(e,t,n),i)}function $s(e,t,n,i){return((e,t,n,i)=>e.getShapeUtil(t).resolveBindingPoint(t,{rawPagePoint:n,oppositePagePoint:i}))(e,t,Fs(e,t,n),i)}function Us(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 xg(e.x+e.props.w/2,e.y+e.props.h/2),i=t.sub(n);return n.add(new xg(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))})(e,new xg(e.x+n.x,e.y+n.y))}function Ds(e){return"start"===e?"end":"start"}function zs(e,t,n){const i=((e,t)=>{const n=Os(e.x,t.x),i=Os(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 Hs(e,t,n){return zs(e,"start"===t?n:Us(e,"start"),"end"===t?n:Us(e,"end"))}function _s(e){return Ys(new xg(e.props.start.x,e.props.start.y).add(new xg(e.x,e.y)),new xg(e.props.end.x,e.props.end.y).add(new xg(e.x,e.y)),e.props.bend)}function Ns(e,t,n){const i=xg.Med(e,t),r=t.sub(e);if(r.len()<1e-6)return 0;const o=r.per().normalize();return-ea(n.sub(i),o)}function Os(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 Ws(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Ys(e,t,n){const i=function(e,t=0){return((e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t)(e,t)}(n,0),r=((e,t,n)=>{const i=xg.Med(e,t),r=t.sub(e),o=r.len()?r.per().normalize():new xg(0,-1);return i.add(o.mul(-n))})(e,t,i),o=((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 r=((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,o=((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(r)&&Number.isFinite(o)?new xg(r,o):null})(e,t,n);if(!i)return null;const r=i.dist(e);if(r<1e-6)return null;const o=((d=n).x-(a=e).x)*((l=t).y-a.y)-(l.x-a.x)*(d.y-a.y)<0?1:0,s=((e,t,n)=>{const i=e.dist(n),r=n.dist(t),o=t.dist(e);return r<1e-6||o<1e-6?0:2*Math.acos(Math.max(-1,Math.min(1,(r*r+o*o-i*i)/(2*r*o))))})(e,t,n);var a,l,d;if(!Number.isFinite(s))return null;const c=Math.PI>s?1:0,u=(fS-s)*(o?1:-1);return{center:i,radius:r,largeArcFlag:c,sweepFlag:o,size:u,length:Math.abs(u*r)}})(e,r,t),s=Math.abs(i)<1e-6||null===o||0===o.length||!Number.isFinite(o.length)||!Number.isFinite(o.radius),a=s?[e,t]:Ks(e,t,o,24),l=s||null===o?`M ${Ws(e.x)} ${Ws(e.y)} L ${Ws(t.x)} ${Ws(t.y)}`:`M ${Ws(e.x)} ${Ws(e.y)} A ${Ws(o.radius)} ${Ws(o.radius)} 0 ${o.largeArcFlag} ${o.sweepFlag} ${Ws(t.x)} ${Ws(t.y)}`,d={start:{terminal:"start",point:e,handle:e},end:{terminal:"end",point:t,handle:t},middle:r,bend:i,points:a,bounds:bg.FromPoints(a),path:l};return s?{type:"straight",...d,arc:null}:{type:"curved",...d,arc:o}}function Xs({start:e,end:t,middle:n,bend:i,arc:r,startHandle:o=e,endHandle:s=t}){const a=Vs(e,t,r);if(Math.abs(a)<1e-6||!Number.isFinite(a)||!Number.isFinite(r.radius)||r.radius<1e-6){const r=Ys(e,t,0);return{...r,start:{...r.start,handle:o},end:{...r.end,handle:s},middle:n,bend:i}}const l={center:r.center,radius:r.radius,largeArcFlag:Math.abs(a)>Math.PI?1:0,sweepFlag:r.sweepFlag,size:a,length:Math.abs(a*r.radius)},d=Ks(e,t,l,24),c=`M ${Ws(e.x)} ${Ws(e.y)} A ${Ws(l.radius)} ${Ws(l.radius)} 0 ${l.largeArcFlag} ${l.sweepFlag} ${Ws(t.x)} ${Ws(t.y)}`;return{type:"curved",start:{terminal:"start",point:e,handle:o},end:{terminal:"end",point:t,handle:s},middle:n,arc:l,bend:i,points:d,bounds:bg.FromPoints(d),path:c}}function Ks(e,t,n,i){const r=[],o=xg.Angle(n.center,e),s=Vs(e,t,n);for(let a=0;a<=i;a++)r.push(Zs(n.center,n.radius,o+s*(a/i)));return r}function Vs(e,t,n){return i=xg.Angle(n.center,e),r=xg.Angle(n.center,t),n.sweepFlag?((r-i)%fS+fS)%fS:-((i-r)%fS+fS)%fS;var i,r}function qs(e,t,n,i){const r=xg.Angle(n.center,e),o=Vs(e,t,n);return Zs(n.center,n.radius,r+o*i)}function js({terminal:e,handlePagePoint:t,boundaryPagePoint:n,fullInfo:i}){if(t.dist(n)<1e-6)return null;const r="start"===e?i.arc.sweepFlag:(e=>e?0:1)(i.arc.sweepFlag),o={center:i.arc.center,radius:i.arc.radius,sweepFlag:r};return Xs({start:t,end:n,middle:qs(t,n,o,.5),bend:i.bend,arc:o}).path}function Gs(e,t,n){const i=((e,t,n)=>{if(e.length<2||n<1e-6)return[];const i=[],r=2===e.length?1:e.length;for(let o=0;o<r;o+=1){const r=e[o],s=e[(o+1)%e.length];if(r&&s)for(const e of Qs(t,n,r,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 r=Math.abs(Vs(t.start.handle,t.end.handle,t.arc));if(r<1e-6)return null;const o=i.map(e=>({point:e,measure:Math.abs(Vs(t.start.handle,e,t.arc))})).filter(({measure:e})=>e>=-1e-6&&e<=r+1e-6);return 0===o.length?null:(o.sort((e,t)=>e.measure-t.measure),"start"===n?o[0]?.point??null:o[o.length-1]?.point??null)}function Zs(e,t,n){return e.add(new xg(Math.cos(n)*t,Math.sin(n)*t))}function Qs(e,t,n,i){const r=i.sub(n),o=n.sub(e),s=r.len2();if(s<1e-6)return[];const a=2*ea(o,r),l=a*a-4*s*(o.len2()-t*t);if(l<-1e-6)return[];const d=Math.sqrt(Math.max(0,l));return[(-a-d)/(2*s),(-a+d)/(2*s)].filter(e=>e>=-1e-6&&e<=1.000001).map(e=>n.add(r.mul(Math.max(0,Math.min(1,e)))))}function Js(e,t,n){const i=n.sub(t),r=i.x*i.x+i.y*i.y;if(0===r)return e.dist(t);const o=e.sub(t),s=Math.max(0,Math.min(1,ea(o,i)/r)),a=t.add(i.mul(s));return e.dist(a)}function ea(e,t){return e.x*t.x+e.y*t.y}function ta(e){return!!e&&"shape"===e.typeName&&"arrow"===e.type}function na(e){return!!e&&"binding"===e.typeName&&"arrow"===e.type}function ia(e,t,n){const i=Us(t,n),r=((e,t,n)=>e.getBindingsFromShape(t.id).find(e=>na(e)&&e.props.terminal===n)??null)(e,t,n);if(!r)return{terminal:n,binding:null,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0};const o=e.getShape(r.toId);return!o||ta(o)?{terminal:n,binding:r,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0}:{terminal:n,binding:r,target:o,handlePagePoint:Fs(e,o,r.props.normalizedAnchor),boundaryPagePoint:i,isArcBoundaryPoint:!1}}function ra(e,t){const n=ia(e,t,"start"),i=ia(e,t,"end"),r=Ys(n.handlePagePoint,i.handlePagePoint,t.props.bend);return"curved"===r.type&&(aa(e,n,r,"start"),aa(e,i,r,"end")),{info:"curved"!==r.type||!n.isArcBoundaryPoint&&n.binding||!i.isArcBoundaryPoint&&i.binding?sa(Ys(n.boundaryPagePoint,i.boundaryPagePoint,t.props.bend),n.handlePagePoint,i.handlePagePoint):Xs({start:n.boundaryPagePoint,end:i.boundaryPagePoint,middle:qs(n.boundaryPagePoint,i.boundaryPagePoint,r.arc,.5),bend:t.props.bend,arc:r.arc,startHandle:n.handlePagePoint,endHandle:i.handlePagePoint}),fullInfo:r,bindingSegments:[la(n,r),la(i,r)].filter(e=>null!==e)}}function oa(e,t){return((e,t)=>{const n=e.start.point.add(t),i=e.end.point.add(t),r=e.middle.add(t),o=e.start.handle.add(t),s=e.end.handle.add(t);return"curved"===e.type?Xs({start:n,end:i,middle:r,bend:e.bend,arc:{center:e.arc.center.add(t),radius:e.arc.radius,sweepFlag:e.arc.sweepFlag},startHandle:o,endHandle:s}):sa(Ys(n,i,e.bend),o,s)})(ra(e,t).info,new xg(-t.x,-t.y))}function sa(e,t,n){return{...e,start:{...e.start,handle:t},end:{...e.end,handle:n}}}function aa(e,t,n,i){if(!t.target)return void(t.isArcBoundaryPoint=!0);const r=Gs(e.getShapePageOutlineVertices(t.target.id),n,i);r?(t.boundaryPagePoint=r,t.isArcBoundaryPoint=!0):t.isArcBoundaryPoint=!1}function la(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?js({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 da(e,{arrow:t,terminal:n,target:i,anchorPagePoint:r,fallbackBoundaryPagePoint:o}){const s=((e,t,n)=>ia(e,t,n).handlePagePoint)(e,t,Ds(n)),a=Ys("start"===n?r:s,"end"===n?r:s,t.props.bend);if("curved"!==a.type)return{terminal:n,anchorPagePoint:r,boundaryPagePoint:o,guidePath:null};const l=Gs(e.getShapePageOutlineVertices(i.id),a,n);return l?{terminal:n,anchorPagePoint:r,boundaryPagePoint:l,guidePath:js({terminal:n,handlePagePoint:r,boundaryPagePoint:l,fullInfo:a})}:{terminal:n,anchorPagePoint:r,boundaryPagePoint:o,guidePath:null}}function ca(e,t){const n=e.getShapePageBounds(t.id)??e.computeShapePageBounds(t);return n.w*n.h}function ua(e,t){return e.getShapeUtil(t).canReceiveChildren(t)}function ha(e,t){return!(!t||ta(t))&&e.getShapeUtil(t).canReceiveTerminalBinding(t,{editor:e})}function pa(e,t,n){const i=ua(e,t),r=ua(e,n);if(i!==r)return i?1:-1;if(i&&r){const i=ca(e,t)-ca(e,n);if(Math.abs(i)>1e-6)return i}return 0}function ga(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function fa(e){if(e)return{shapes:[e]}}function ma(e,t){const n=e&&"object"==typeof e?e:void 0;return{x:Sa(n?.x,t.x),y:Sa(n?.y,t.y)}}function Sa(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function ya(e,t,n){const i=n.sub(t),r=i.len2();if(0===r)return e.dist(t);const o=e.sub(t),s=Math.max(0,Math.min(1,(o.x*i.x+o.y*i.y)/r));return e.dist(t.add(i.mul(s)))}function xa(e,t,n,i){return((e,t,n,i)=>{const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),l=(a.x*o.y-a.y*o.x)/s,d=(a.x*r.y-a.y*r.x)/s;return l>=0&&l<=1&&d>=0&&d<=1})(e,t,n,i)?0:Math.min(ya(e,n,i),ya(t,n,i),ya(n,e,t),ya(i,e,t))}function ba(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(!ta(i))throw new Error("Failed to create arrow shape");const r=zs(i,t.startPagePoint,t.endPagePoint);e.commands.updateShapes([{id:i.id,x:r.x,y:r.y,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:{...r.props}}],{source:n}),t.startBinding&&e.commands.createBinding({type:"arrow",fromId:r.id,toId:t.startBinding.targetShapeId,props:{terminal:"start",normalizedAnchor:t.startBinding.normalizedAnchor}},{source:n}),t.endBinding&&e.commands.createBinding({type:"arrow",fromId:r.id,toId:t.endBinding.targetShapeId,props:{terminal:"end",normalizedAnchor:t.endBinding.normalizedAnchor}},{source:n});const o=e.getShape(r.id);if(!ta(o))throw new Error("Failed to create arrow shape");return o}function Ia(e,t,n,i,r="user"){if(!t)return e.setBindingPreview(i.preview),null;let o=null;return o=((e,t,n)=>{const i=e.getShape(t.shapeId);if(!ta(i))return null;const r=Hs(i,t.terminal,t.pagePoint);e.commands.updateShapes([{id:i.id,x:r.x,y:r.y,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:{...r.props}}],{source:n});const o=e.bindings.getBindingsFromShape(i.id).find(e=>na(e)&&e.props.terminal===t.terminal)??null;t.binding?na(o)?e.commands.updateBinding({id:o.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n}):(o&&e.commands.deleteBinding(o.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})):o&&(e.commands.deleteBinding(o.id,{source:n}),e.commands.updateShapes([{id:i.id,x:r.x,y:r.y,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:{...r.props}}],{source:n}));const s=e.getShape(i.id);return ta(s)?s:r})(e,{shapeId:t,terminal:n,pagePoint:i.pagePoint,binding:i.binding},r),e.setBindingPreview(i.preview),o}function va(e,{terminal:t,rawPagePoint:n,oppositePagePoint:i,excludeShapeId:r,ignoreTargets:o=!1}){if(o)return{pagePoint:n.clone(),binding:null,preview:null};const s=function(e,t,n,i){const r=((e,t)=>{let n=null;for(const i of t)(!n||pa(e,i,n)<0)&&(n=i);return n})(e,e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget",filter:t=>t.id!==i?.excludeShapeId&&ha(e,t)}));if(!r)return null;const o=((e,t,n)=>{const i=Ze(t,n,e.getShapeUtil(t)),r=e.computeShapeBounds(t),o=r.h<=1e-6?.5:(i.y-r.minY)/r.h;return{x:Ls(r.w<=1e-6?.5:(i.x-r.minX)/r.w),y:Ls(o)}})(e,r,t);return{targetShape:r,normalizedAnchor:o,resolvedPagePoint:$s(e,r,o,n),rawPagePoint:t.clone()}}(e,n,i,{excludeShapeId:r});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:wa(s),preview:ka(t,s)}}function Pa(e,{arrow:t,terminal:n,rawPagePoint:i,ignoreTargets:r=!1}){const o=va(e,{terminal:n,rawPagePoint:i,oppositePagePoint:Us(t,Ds(n)),excludeShapeId:t.id,ignoreTargets:r});if(!o.preview)return o;const s=((e,{arrow:t,terminal:n,rawPagePoint:i,preview:r})=>{const o=e.getShape(r.targetShapeId);if(!o||ta(o))return r;const s=da(e,{arrow:t,terminal:n,target:o,anchorPagePoint:i,fallbackBoundaryPagePoint:r.resolvedPagePoint});return{...r,resolvedPagePoint:s.boundaryPagePoint,guidePath:s.guidePath}})(e,{arrow:t,terminal:n,rawPagePoint:i,preview:o.preview});return{...o,pagePoint:s.resolvedPagePoint,preview:s}}function wa(e){return e?{targetShapeId:e.targetShape.id,normalizedAnchor:e.normalizedAnchor}:null}function ka(e,t){return t?{terminal:e,targetShapeId:t.targetShape.id,rawPagePoint:t.rawPagePoint,resolvedPagePoint:t.resolvedPagePoint}:null}function Ca(){return{createSession:(e,{handle:t,shape:n})=>ta(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:r,source:o}){const s=e.getShape(t);if(!ta(s))return{status:"stop",finalPagePoint:null};const a=Pa(e,{arrow:s,terminal:n,rawPagePoint:i,ignoreTargets:r}),l=Ia(e,s.id,n,a,o);return{status:"continue",finalPagePoint:l?Us(l,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:r}){const o=t.getShape(e);if(!ta(o))return"stop";const s=((e,t)=>({start:ia(e,t,"start").handlePagePoint,end:ia(e,t,"end").handlePagePoint}))(t,o),a=(({bend:e,bypassSnap:t,zoom:n})=>t?e:Math.abs(e)*n<=6?0:e)({bend:Ns(s.start,s.end,n),bypassSnap:i,zoom:t.cameraZoomSignal.get()});return t.commands.updateShapes([{id:o.id,props:{bend:a}}],{source:r}),"continue"}}}({shapeId:n.id}):null:null}}function Ta({strokeActionId:e,strokeWidthActionId:t,headStartActionId:n,headEndActionId:i,dataUiPrefix:r}){return[{id:`${r}.style-stroke`,items:[{kind:"swatches",id:`${r}.stroke`,actionId:e,label:"Stroke",options:PS.map(e=>({...e,dataUi:`${r}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-stroke-width`,items:[{kind:"stepper",id:`${r}.stroke-width`,actionId:t,label:"Stroke width",dataUi:`${r}-stroke-width-control`,options:wS.map(e=>({...e,dataUi:`${r}-stroke-width-${e.value}-button`}))}]},{id:`${r}.head-start`,items:[{kind:"segmented",id:`${r}.head-start`,actionId:n,options:kS.map(e=>({...e,label:`Start head: ${e.label}`,dataUi:`${r}-start-head-${e.value}-button`}))}]},{id:`${r}.head-end`,items:[{kind:"segmented",id:`${r}.head-end`,actionId:i,options:kS.map(e=>({...e,label:`End head: ${e.label}`,dataUi:`${r}-end-head-${e.value}-button`}))}]}]}function Ea(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?!C(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=Ma(e,n);if(void 0===i)return;const r=t.selection.selectedShapes.filter(e=>"arrow"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==r.length&&t.editor.commands.updateShapes(r,{source:"user"})}}}function Ba(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=Ma(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("arrow",{[e]:i})}}}function Ma(e,t){return"strokeWidth"===e?"number"==typeof t&&wS.some(e=>e.value===t)?t:void 0:"stroke"===e?b(t)?v(t,m("stroke-slate")):void 0:kS.some(e=>e.value===t)?t:void 0}function Aa(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 Ra({shape:e,editor:t,isHovered:n,isSelected:i}){const r=e.id.replace(/[^a-zA-Z0-9_-]/g,"-"),o=`arrow-head-start-${r}`,s=`arrow-head-end-${r}`,a=oa(t,e),l=nr(e.props.stroke,n);
|
|
24
|
-
return ng("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,overflow:"visible",children:[ng("defs",{children:[tg("marker",{id:o,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"2",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:tg("path",{d:"M8.9,8 L2,12 L8.9,16",fill:"none",stroke:l,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),tg("marker",{id:s,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"22",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:tg("path",{d:"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:l,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),tg("path",{d:a.path,fill:"none",stroke:l,strokeWidth:e.props.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round",markerStart:"arrow"===e.props.headStart?`url(#${o})`:void 0,markerEnd:"arrow"===e.props.headEnd?`url(#${s})`:void 0,opacity:i?.92:1})]})}function La(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function Fa(e,t,n){return Math.max(t,Math.min(n,e))}function $a(e){return e?640:480}function Ua(e,t){return e.x===t.x&&e.y===t.y&&e.pressure===t.pressure&&e.segment===t.segment}function Da(e){return new xg(e.x,e.y)}function za(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 Ha(e){const t=[];for(const n of e)t.push(...n.points.map(za));return t}function _a(e){if(void 0!==e&&Number.isFinite(e))return Fa(e,.05,1)}function Na(e,t){const n=[];for(let i=1;i<e.length-1;i+=1){if(t&&Oa(e,i))continue;const r=e[i],o=e[i-1],s=e[i+1];r&&o&&s&&n.push({index:i,score:Wa(r,o,s)})}return n.sort((e,t)=>e.score-t.score||e.index-t.index),n}function Oa(e,t){return"straight"===e[t]?.segment||"straight"===e[t+1]?.segment}function Wa(e,t,n){const i=((e,t,n)=>{const i=n.x-t.x,r=n.y-t.y,o=i*i+r*r;if(0===o){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}const s=Fa(((e.x-t.x)*i+(e.y-t.y)*r)/o,0,1),a=e.x-(t.x+i*s),l=e.y-(t.y+r*s);return a*a+l*l})(e,t,n),r=((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+r*r}function Ya(e){if(0===e.length)return null;if(1===e.length){const t=e[0];return`M ${La(t.x)} ${La(t.y)}`}if(2===e.length){const t=e[0],n=e[1];return[`M ${La(t.x)} ${La(t.y)}`,`L ${La(n.x)} ${La(n.y)}`].join(" ")}const t=[],n=e[0];t.push(`M ${La(n.x)} ${La(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 ${La(n.x)} ${La(n.y)}`);continue}const r=e[i+1];if(!r||"straight"===r.segment){if(Xa(e,i)){const r=e[i-1];t.push(`Q ${La(r.x)} ${La(r.y)} ${La(n.x)} ${La(n.y)}`)}else t.push(`L ${La(n.x)} ${La(n.y)}`);continue}const o=xg.Med(Da(n),Da(r));t.push(`Q ${La(n.x)} ${La(n.y)} ${La(o.x)} ${La(o.y)}`)}return t.join(" ")}function Xa(e,t){return t>=2&&"straight"!==e[t-1]?.segment&&"straight"!==e[t-2]?.segment}function Ka(e){if(e.length<3)return(e=>{if(0===e.length)return null;const[t,...n]=e;return t?[`M ${La(t.x)} ${La(t.y)}`,...n.map(e=>`L ${La(e.x)} ${La(e.y)}`),"Z"].join(" "):null})(e);const t=e[0],n=e[e.length-1];if(!t||!n)return null;const i=xg.Med(n,t),r=[`M ${La(i.x)} ${La(i.y)}`];for(let o=0;o<e.length;o+=1){const t=e[o],n=e[(o+1)%e.length];if(!t||!n)continue;const i=xg.Med(t,n);r.push(`Q ${La(t.x)} ${La(t.y)} ${La(i.x)} ${La(i.y)}`)}return r.push("Z"),r.join(" ")}function Va(e){return e.map(za)}function qa(e){return e.map(ja)}function ja(e){return(e=>({points:e.points.map(za)}))(e)}function Ga(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 Za(e,t,n){return e.map(e=>({points:Ga(e.points,t,n)}))}function Qa(e,t){return e.map((e,n)=>({points:e.points.map((e,i)=>{const r=t(Da(e),n,i);return{x:r.x,y:r.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}})}))}function Ja(e,t,n){const i=0===t.w?1:t.w,r=0===t.h?1:t.h,o=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*o,y:n.minY+(e.y-t.minY)/r*s,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}))}function el(e,t,n){return e.map(e=>({points:Ja(e.points,t,n)}))}function tl(e){return{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}}function nl(e,t){const n=tl(t);return Qa(e,e=>bn(e,n))}function il(e,t){const n=tl(t);return Qa(e,e=>In(e,n))}function rl(e,t){return Qa(e,e=>kn({axis:t.axis,bounds:t.selectionMirrorBounds,point:e}))}function ol(e,t,n){return Math.max(t,Math.min(n,e))}function sl(e,t,n){return e+(t-e)*n}function al(e,t,n){if(e.length<=1)return new xg(1,0);if(n&&e.length>=3){const n=e[t],i=e[(t+1)%e.length],r=n.sub(e[(t-1+e.length)%e.length]).uni(),o=i.sub(n).uni(),s=r.add(o);return s.len2()>1e-6?s.uni():o.len2()>0?o:r.len2()>0?r:new xg(1,0)}const i=e[t],r=e[t+1]??i,o=i.sub(e[t-1]??i).uni(),s=r.sub(i).uni();if(0===t)return s.len2()>0?s:new xg(1,0);if(t===e.length-1)return o.len2()>0?o:new xg(1,0);const a=o.add(s);return a.len2()>1e-6?a.uni():s.len2()>0?s:o.len2()>0?o:new xg(1,0)}function ll(e,t){return e.x*t.x+e.y*t.y}function dl(e,t,n,i,r={}){if(0===e.length)return[];const o=((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(Da),a=[0];let l=0;for(let u=1;u<s.length;u+=1)l+=s[u].dist(s[u-1]),a.push(l);let d=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,r,o,s,a){if(n.simulatePressure)return(({distanceFromPrevious:e,previousPressure:t,runningLength:n,totalLength:i,strokeWidth:r,isClosed:o})=>{const s=ol(e/Math.max(1.5*r,1),0,1),a=ol(1-s,TS,1),l=null===t?sl(.5,a,.275):sl(t,a,.275*Math.max(s,.36));if(o)return ol(l,TS,1);const d=ol(n/Math.max(1.8*r,1),0,1),c=ol((i-n)/Math.max(2.6*r,1),0,1);return ol(l*sl(.72,1,Math.min(d,c)),TS,1)})({distanceFromPrevious:r,previousPressure:t,runningLength:o,totalLength:s,strokeWidth:i,isClosed:a});const l="number"==typeof e.pressure&&Number.isFinite(e.pressure)?ol(e.pressure,.05,1):t??.55;return null===t?l:sl(t,l,.68)}(e,d,o,t,u,c,l,i);d=h;const p=r.taperEnd??!0,g=i||s.length<=1?1:Math.min(r.taperStart??1?ol(c/o.startTaper,0,1):1,p?ol((l-c)/o.endTaper,0,1):1),f=sl(o.minRadiusScale,o.maxRadiusScale,h),m=Math.max(o.minRadius,o.baseRadius*f*sl(.7,1,g));return{point:s[n],direction:al(s,n,i),pressure:h,radius:m,runningLength:c}});return l<.5*o.baseRadius?c.map(e=>({...e,radius:Math.max(e.radius,.92*o.baseRadius)})):c}function cl(e,t){const n=e[e.length-1];n&&n.dist2(t)<.04?e[e.length-1]=t:e.push(t)}function ul(e,t,n){const i=e.dist(t);if(0===i)return[];const r=xg.Angle(e,t),o=[];for(let s=1;s<n;s+=1){const t=r-Math.PI*(s/n);o.push(new xg(e.x+Math.cos(t)*i,e.y+Math.sin(t)*i))}return o}function hl(e,t,n){const i=e[e.length-1];!i||i.dist2(t)>n?cl(e,t):e[e.length-1]=t}function pl(e){return{...e}}function gl(e,t,n){return e.map(e=>new xg(e.x+t,e.y+n))}function fl(e,t,n){return e.map(e=>gl(e,t,n))}function ml({segments:e,outlineVertices:t,outlinePolygons:n,strokeWidth:i,sampling:r,isClosed:o}){const s=Ha(e),a=s.map(Da),l=a.length>0?bg.FromPoints(a):new bg(0,0,1,1),d=t.length>0?bg.FromPoints([...t]):l.expand(Math.max(i/2,1)),c=o&&s.length>=3?(e=>{if(e.length<3)return null;const t=Ya(e);return t?`${t} Z`:null})(s):null,u=void 0!==n?(e=>{const t=e.map(e=>Ka(e)).filter(e=>null!==e);return t.length>0?t.join(" "):null})(n):Ka(t);return{normalizedSegments:qa(e),normalizedPoints:Va(s),pointBounds:l,path:u,selectionPath:c??Ya(s),fillPath:c,localBounds:d,renderBounds:d.clone(),outlineVertices:t.map(e=>e.clone()),outlinePolygons:n?n.map(e=>e.map(e=>e.clone())):[t.map(e=>e.clone())],sampling:pl(r)}}function Sl(e,t,n,i){const r=(({strokeWidth:e,isPen:t})=>[e,t?"pen":"pointer"].join(":"))({strokeWidth:n,isPen:i}),o=ES.get(e),s=o?.get(r);if(s)return{normalizedSegment:ja(s.normalizedSegment),sampling:pl(s.sampling)};const a=((e,t)=>{if(e.length<=1)return{points:e.map(za),rawPointCount:e.length,sampledPointCount:e.length,maxPointCount:t.maxPointCount,reduced:!1,capped:!1};const n=[za(e[0])],i=t.minPointDistance*t.minPointDistance;let r=Da(e[0]),o=_a(e[0].pressure);for(let l=1;l<e.length;l+=1){const s=e[l];if(!s)continue;const a=Da(s),d=_a(s.pressure),c=l===e.length-1,u="straight"===s.segment,h=c||u?a:xg.Lrp(r,a,t.positionBlend),p=u?d:void 0===d?void 0:void 0===o?d:o+(d-o)*t.pressureBlend;r=h,o=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(Ua(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(za);const i=((e,t)=>{let n=Na(e,!0);return n.length<t&&(n=Na(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(za)}(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),l={normalizedSegment:{points:Va(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},d=o??new Map;return d.set(r,{normalizedSegment:ja(l.normalizedSegment),sampling:pl(l.sampling)}),o||ES.set(e,d),l}function yl(e,t,n=!1,i=!1){const r=((e,t)=>({minPointDistance:t?Math.max(.35,.18*e):Math.max(.55,.28*e),positionBlend:t?.68:.66,pressureBlend:t?.68:.45,maxPointCount:$a(t)}))(t,n),o=[],s=[],a=e.filter(e=>e.points.length>0);for(let h=0;h<a.length;h+=1){const e=Sl(a[h],r,t,n);o.push(ja(e.normalizedSegment)),s.push(pl(e.sampling))}const l=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 r=2*Math.PI*i/16;n.push(new xg(e.x+Math.cos(r)*t,e.y+Math.sin(r)*t))}return n})(e[0].point,e[0].radius);const i=[],r=[];let o=.12;for(const d of e)o=Math.max(o,.38*d.radius);const s=o**2;let a=null;for(let d=0;d<e.length;d+=1){const t=e[d],n=t.direction,o=(e[d+1]??t).direction,l=ll(n,o);let c=0===d||d===e.length-1?n.per().uni():xg.Lrp(o,n,l).per().uni();c.len2()<1e-6&&(c=a??new xg(0,1)),a=c,hl(i,t.point.add(c.mul(t.radius)),s),hl(r,t.point.sub(c.mul(t.radius)),s)}if(t&&e.length>=3){const e=[];for(const t of i)cl(e,t);for(let t=r.length-1;t>=0;t-=1)cl(e,r[t]);return e}const l=[];for(const d of i)cl(l,d);if(n.capEnd??1){const t=e[e.length-1];for(const e of ul(t.point,i[i.length-1],8))cl(l,e)}for(let d=r.length-1;d>=0;d-=1)cl(l,r[d]);if(n.capStart??1){const t=e[0];for(const e of ul(t.point,r[0],8))cl(l,e)}return l}(dl(Ha(o),t,n,i),i),d=(u=r.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 ml({segments:o,outlineVertices:l,outlinePolygons:l.length>0?[l]:[],strokeWidth:t,sampling:d,isClosed:i})}function xl(e){return e.segments}function bl(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 bg(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 Il(e,t){return new xg(e.x+t.localBounds.center.x,e.y+t.localBounds.center.y)}function vl(e,t,n){if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return t;const i=t.sub(n);return n.add(new xg(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))}function Pl(e){const t=e,n=BS.get(t);if(n)return n;const i=yl(xl(e.props),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed);return BS.set(t,i),i}function wl(e,t,n=!1,i=!1){return((e,t,n=!1,i=!1)=>{const r=yl(e,t,n,i),o=r.pointBounds,s=yl(Qa(r.normalizedSegments,e=>new xg(e.x-o.x,e.y-o.y)),t,n,i);return{x:o.x,y:o.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 kl(e){const t=e,n=MS.get(t);if(n)return n;const i=((e,t,n,i,r)=>ml({segments:Za(e.normalizedSegments,n,i),outlineVertices:gl(e.outlineVertices,n,i),outlinePolygons:fl(e.outlinePolygons,n,i),strokeWidth:t,sampling:e.sampling,isClosed:r}))(Pl(e),e.props.strokeWidth,e.x,e.y,e.props.isClosed);return MS.set(t,i),i}function Cl(e){const t=Il(e,Pl(e));return Qa((e=>Za(xl(e.props),e.x,e.y))(e),n=>vl(e,n,t))}function Tl(e){const t=e,n=AS.get(t);if(n)return n;if(0===e.rotation&&1===e.scaleX&&1===e.scaleY){const n=kl(e);return AS.set(t,n),n}const i=Pl(e),r=Il(e,i),o=ml({segments:Qa(i.normalizedSegments,t=>vl(e,new xg(t.x+e.x,t.y+e.y),r)),outlineVertices:i.outlineVertices.map(t=>vl(e,new xg(t.x+e.x,t.y+e.y),r)),outlinePolygons:i.outlinePolygons.map(t=>t.map(t=>vl(e,new xg(t.x+e.x,t.y+e.y),r))),strokeWidth:e.props.strokeWidth,sampling:i.sampling,isClosed:e.props.isClosed});return AS.set(t,o),o}function El(e){return qa(e)}function Bl(e,t,n,i){return{x:e.x-t.x,y:e.y-t.y,...i&&n>0?{pressure:n}:null}}function Ml(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 Al(e){const t=Rl(e.segments),n=t[t.length-1];return n?n.points.map(Ml):[]}function Rl(e){return e.length>0?[...e]:[{points:[]}]}function Ll(e){return{segments:El(Rl(e))}}function Fl(e,t,n){const i=n.sub(t),r=i.len2();if(0===r)return e.dist(t);const o=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/r)),s=new xg(t.x+i.x*o,t.y+i.y*o);return e.dist(s)}function $l(e,t,n,i){return((e,t,n,i)=>{const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),l=(a.x*o.y-a.y*o.x)/s,d=(a.x*r.y-a.y*r.x)/s;return l>=0&&l<=1&&d>=0&&d<=1})(e,t,n,i)?0:Math.min(Fl(e,n,i),Fl(t,n,i),Fl(n,e,t),Fl(i,e,t))}function Ul(e,t){let n=!1;for(let i=0,r=t.length-1;i<t.length;r=i,i+=1){const o=t[i],s=t[r];o&&s&&o.y>e.y!=s.y>e.y&&e.x<(s.x-o.x)*(e.y-o.y)/(s.y-o.y)+o.x&&(n=!n)}return n}function Dl(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 r=t[i],o=t[(i+1)%t.length];r&&o&&(n=Math.min(n,Fl(e,r,o)))}return n}function zl(e,t,n,i){if(0===n.length)return!1;if(Ul(e,n)||Ul(t,n))return!0;for(let r=0;r<n.length;r+=1){const o=n[r],s=n[(r+1)%n.length];if(o&&s&&$l(e,t,o,s)<=i)return!0}return!1}function Hl(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function _l(e){if(!e||"object"!=typeof e)return null;const t=e,n=Hl(t.x,NaN),i=Hl(t.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(i))return null;const r=Hl(t.pressure,NaN);return t.x!==n||t.y!==i||void 0!==t.pressure&&t.pressure!==r||void 0!==t.segment&&"straight"!==t.segment?{x:n,y:i,...Number.isFinite(r)?{pressure:r}:null,..."straight"===t.segment?{segment:"straight"}:null}:e}function Nl(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 r of e){const e=_l(r);e?(n=n||e!==r,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 Ol(e,t){if(!Array.isArray(e))return t;let n=!1;const i=[];for(const r of e){const e=Nl(r);e?(n=n||e!==r,i.push(e)):n=!0}return 0===i.length?t:n?i:e}function Wl(e){return u(e)&&"draw"===e.type}function Yl({closedActionId:e,fillActionId:t,strokeActionId:n,strokeWidthActionId:i,dataUiPrefix:r}){return[{id:`${r}.style-closed`,items:[{kind:"segmented",id:`${r}.closed`,actionId:e,options:NS.map(e=>({...e,dataUi:`${r}-${e.value}-button`}))}]},{id:`${r}.style-fill`,items:[{kind:"swatches",id:`${r}.fill`,actionId:t,label:"Fill",options:HS.map(e=>({...e,dataUi:`${r}-fill-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-stroke`,items:[{kind:"swatches",id:`${r}.stroke`,actionId:n,label:"Stroke",options:zS.map(e=>({...e,dataUi:`${r}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-stroke-width`,items:[{kind:"stepper",id:`${r}.stroke-width`,actionId:i,label:"Stroke width",dataUi:`${r}-stroke-width-control`,options:_S.map(e=>({...e,dataUi:`${r}-stroke-width-${e.value}-button`}))}]}]}function Xl(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:!C(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=jl(e,n);if(void 0===i)return;const r=t.selection.selectedShapes.filter(Wl).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==r.length&&t.editor.commands.updateShapes(r,{source:"user"})}}}function Kl(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=jl(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("draw",{[e]:i})}}}function Vl(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 ql(e){return"closed"===e||"open"!==e&&null}function jl(e,t){return"strokeWidth"===e?"number"==typeof t&&_S.some(e=>e.value===t)?t:void 0:b(t)?v(t,"fill"===e?"transparent":m("stroke-slate")):void 0}function Gl({shape:e,isHovered:t=!1,stroke:n=e.props.stroke,strokeWidth:i=e.props.strokeWidth}){const{fillPath:r,renderBounds:o,path:s,selectionPath:a}=Pl({props:{...e.props,strokeWidth:i}});if(!s&&!a)return null;const l=nr(n,t);
|
|
25
|
-
|
|
26
|
-
return
|
|
27
|
-
return
|
|
28
|
-
return
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return tg("svg",{width:"100%",height:"100%",viewBox:`0 0 ${r} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:o?tg("rect",{x:.5,y:.5,width:Math.max(r-1,0),height:Math.max(i-1,0),fill:"none",stroke:s,strokeDasharray:"4 4",strokeWidth:1,vectorEffect:"non-scaling-stroke"}):null})}function dc(e,t=0){return Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t)}function cc({cornerRadius:e,h:t,w:n}){return Math.min(dc(e),Math.max(0,n)/2,Math.max(0,t)/2)}function uc(e){return Math.min(1,Math.max(0,e))}function hc(e,t,n){return Math.min(n,Math.max(t,e))}function pc(e){return!!e&&"object"==typeof e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function gc(e,t){const n=uc(e),i=uc(t);let r=Math.min(n,i),o=Math.max(n,i);return o-r<Hy&&(r=Math.max(0,Math.min(.9999,(r+o)/2-5e-5)),o=r+Hy),{min:r,max:o}}function fc(e){if(!e||"object"!=typeof e)return null;const t=e;if(!pc(t.topLeft)||!pc(t.bottomRight))return null;const n=gc(t.topLeft.x,t.bottomRight.x),i=gc(t.topLeft.y,t.bottomRight.y);return{topLeft:{x:n.min,y:i.min},bottomRight:{x:n.max,y:i.max}}}function mc(e){const t=fc(e);if(!t)return null;const n=t.topLeft.x,i=t.topLeft.y,r=t.bottomRight.x,o=t.bottomRight.y;return{left:n,top:i,right:r,bottom:o,width:r-n,height:o-i}}function Sc(e){return mc(e)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function yc(e,t){return Math.abs(e.left-t.left)<=_y&&Math.abs(e.top-t.top)<=_y&&Math.abs(e.right-t.right)<=_y&&Math.abs(e.bottom-t.bottom)<=_y}function xc(e){return(e=>Math.abs(e.left)<=_y&&Math.abs(e.top)<=_y&&Math.abs(1-e.right)<=_y&&Math.abs(1-e.bottom)<=_y)(e)?null:fc({topLeft:{x:e.left,y:e.top},bottomRight:{x:e.right,y:e.bottom}})}function bc({centerX:e,centerY:t,height:n,width:i}){const r=hc(i,Hy,1),o=hc(n,Hy,1),s=hc(e-r/2,0,1-r),a=hc(t-o/2,0,1-o);return{left:s,top:a,right:s+r,bottom:a+o,width:r,height:o}}function Ic(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function vc({crop:e,shape:t}){const n=Sc(e);return{w:t.props.w/n.width,h:t.props.h/n.height}}function Pc(e,t){return t===wc(e.id)}function wc(e){return`${Wy}${e}`}function kc({localToPage:e,shape:t}){const n=t.props.w,i=t.props.h,r=(0+n)/2,o=(0+i)/2,s={top_left:new xg(0,0),top:new xg(r,0),top_right:new xg(n,0),right:new xg(n,o),bottom_right:new xg(n,i),bottom:new xg(r,i),bottom_left:new xg(0,i),left:new xg(0,o)};return Ky.map(t=>{return{kind:"custom",type:Ny,id:t,point:e.applyToPoint(s[t]),cursor:(n=t,Xy[n])};var n})}function Cc({change:e,crop:t,shape:n}){const i=vc({crop:t,shape:n}),r=t.bottomRight.x-t.topLeft.x,o=t.bottomRight.y-t.topLeft.y,s=hc(t.topLeft.x-e.x/i.w,0,1-r),a=hc(t.topLeft.y-e.y/i.h,0,1-o),l=fc({topLeft:{x:s,y:a},bottomRight:{x:s+r,y:a+o}});return l?{id:n.id,props:{crop:l}}:null}function Tc(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Ec(e){Vy.delete(e)}function Bc(e){return u(e)&&"image"===e.type}function Mc(){return{createSession(e,{handle:t,shape:n,originPagePoint:i}){return Bc(n)&&"custom"===t.kind&&"image.crop"===t.type&&(r=t.id,Ky.some(e=>e===r))?function({handleId:e,shapeId:t,startPagePoint:n,startPageToLocal:i,startShape:r,startCrop:o}){return{shapeId:t,historyMark:"image.crop.handle",update({editor:s,pagePoint:a,source:l}){if(!Bc(s.getShape(t)))return"stop";const d=(({handleId:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:r,currentPagePoint:o})=>{const s=fc(i)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=vc({crop:s,shape:n});if(a.w<8||a.h<8)return null;const l=t.applyToPoint(r),d=t.applyToPoint(o).sub(l);if(0===d.x&&0===d.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=hc(p+d.x,0,u-8),f=u-p):(e=>"top_right"===e||"right"===e||"bottom_right"===e)(e)&&(f=hc(u+d.x,c.x+8,a.w)-p),(e=>"top_left"===e||"top"===e||"top_right"===e)(e)?(g=hc(g+d.y,0,h-8),m=h-g):(e=>"bottom_left"===e||"bottom"===e||"bottom_right"===e)(e)&&(m=hc(h+d.y,c.y+8,a.h)-g);const S=fc({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 xg(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:r,startCrop:o,startPagePoint:n});return d?(s.commands.updateShapes([d],{source:l}),"continue"):"continue"}}}({handleId:t.id,shapeId:n.id,startPagePoint:i,startPageToLocal:e.computeShapeLocalToPageTransform(n).invert(),startShape:n,startCrop:n.props.crop}):null;var r}}}function Ac(){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=Rc(e);if(!n)return"continue";if("Escape"===t.key&&!t.altKey&&!t.accelKey)return e.cancelEditing("user")&&Ec(n.id),"handled";if("Enter"===t.key&&!t.altKey&&!t.accelKey)return e.completeEditing("user")&&Ec(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 xg(t,0);case"ArrowRight":return new xg(-t,0);case"ArrowUp":return new xg(0,t);case"ArrowDown":return new xg(0,-t);default:return null}})(t);if(i){const t=(({pageDelta:e,shape:t,startCrop:n})=>{const i=fc(n);return!i||e.equals(xg.Zero())?null:Cc({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(Oy),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 r=Rc(n);return r?((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,r,i)?(e={pointerId:i.pointerId,shapeId:r.id,startCrop:r.props.crop,startPagePoint:i.pagePoint.clone(),startPageToLocal:n.computeShapeLocalToPageTransform(r).invert(),startShape:r,hasDragged:!1},"handled"):n.completeEditing("user")?(Ec(r.id),n.dispatch(i),"handled"):"continue":"continue"}return e&&i.pointerId===e.pointerId?"pointer_move"===i.name?(Lc(n,i,e),"handled"):"pointer_up"===i.name?(Lc(n,i,e),e.hasDragged&&n.history.squashToMark(Oy,"shape.edit"),t(),"handled"):"continue":"continue"}},selectionHandle:Mc()}}function Rc(e){const[t]=e.getSelectedShapes();if(!Bc(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Pc(t,n.markId)?t:null}function Lc(e,t,n){if(!n.hasDragged){if(n.startPagePoint.dist2(t.pagePoint)<9)return;e.history.mark(Oy),n.hasDragged=!0}if(!Bc(e.getShape(n.shapeId)))return;const i=(({currentPagePoint:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:r,shiftKey:o})=>{const s=fc(i);if(!s)return null;const a=t.applyToPoint(r);let l=t.applyToPoint(e).sub(a);return o&&(l=Math.abs(l.x)<Math.abs(l.y)?new xg(0,l.y):new xg(l.x,0)),0===l.x&&0===l.y?null:Cc({change:l,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 Fc(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function $c(){return{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 host storageKey; File/Blob/object URL/download behavior stays in the web host."]}],shapeUtils:[new qy],shapeSvgExporters:[new rx],interactionHandlers:[Ac()],canvasActions:[zc(Zy),zc(jy),zc(Gy),{id:Qy,isVisible:e=>!!Uc(e)&&!Dc(e),isEnabled(e){const t=Uc(e);return!!t&&!t.isLocked},getValue:e=>Dc(e),run({context:e}){const t=Uc(e);if(!t||t.isLocked)return;const n=e.editor.getShapeEditingSession();n?.shapeId===t.id&&Pc(t,n.markId)?e.editor.completeEditing("user"):e.editor.startEditingShape({shapeId:t.id,markId:wc(t.id),entryMode:"focusEnd"},"user")&&(e=>{Vy.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:Jy,isVisible:e=>Dc(e),isEnabled:e=>Dc(e),run({context:e}){const t=Uc(e);t&&e.editor.completeEditing("user")&&Ec(t.id)}},{id:ex,isVisible:e=>Dc(e),isEnabled(e){const t=Uc(e);return!!t&&!t.isLocked},run({context:e,value:t}){const n=Uc(e);if(!n||n.isLocked||-1!==t&&1!==t)return;const i=(({direction:e,shape:t})=>{const n=Sc(t.props.crop),i=Ic(n),r=hc("in"===e?.8:1.25,Math.max(Hy/n.width,Hy/n.height),Math.min(1/n.width,1/n.height)),o=bc({centerX:i.x,centerY:i.y,width:n.width*r,height:n.height*r});return yc(n,o)?null:{id:t.id,props:{crop:xc(o)}}})({direction:1===t?"in":"out",shape:n});i&&e.editor.commands.updateShapes([i],{source:"user"})}},{id:tx,isVisible:e=>Dc(e),isEnabled(e){const t=Uc(e);return!!t&&!t.isLocked},getValue(e){const t=Uc(e);return t?(e=>{const t=e.props.w/e.props.h;for(const n of Yy)if(Math.abs(t-n.ratio)<=.01)return n.value;return null})(t):null},run({context:e,value:t}){const n=Uc(e);if(!n||n.isLocked||"string"!=typeof t)return;const i=Yy.find(e=>e.value===t);if(!i)return;const r=function({preset:e,shape:t}){const n=Ic(Sc(t.props.crop)),i=vc({crop:t.props.crop,shape:t}),r=Yy.find(t=>t.value===e)?.ratio??null;if(!r)return null;const o=r*(i.h/i.w);let s=1,a=s/o;return a>1&&(a=1,s=a*o),(({nextRect:e,shape:t})=>{const n=Sc(t.props.crop);if(yc(n,e))return null;const i=vc({crop:t.props.crop,shape:t}),r=new xg((e.left-n.left)*i.w,(e.top-n.top)*i.h).rot(t.rotation);return{id:t.id,x:t.x+r.x,y:t.y+r.y,props:{w:e.width*i.w,h:e.height*i.h,crop:xc(e)}}})({nextRect:bc({centerX:n.x,centerY:n.y,width:s,height:a}),shape:t})}({preset:i.value,shape:n});r&&e.editor.commands.updateShapes([r],{source:"user"})}},{id:nx,isVisible:e=>Dc(e),isEnabled(e){const t=Uc(e);return!!t&&!t.isLocked&&!!t.props.crop},run({context:e}){const t=Uc(e);if(!t||t.isLocked)return;const n=(({baselineShape:e,shape:t})=>{const n=e.x,i=e.y,r=e.props.w,o=e.props.h,s=fc(e.props.crop);return Math.abs(t.x-n)<=_y&&Math.abs(t.y-i)<=_y&&Math.abs(t.props.w-r)<=_y&&Math.abs(t.props.h-o)<=_y&&(null===t.props.crop&&null===s||null!==t.props.crop&&null!==s&&Math.abs(t.props.crop.topLeft.x-s.topLeft.x)<=_y&&Math.abs(t.props.crop.topLeft.y-s.topLeft.y)<=_y&&Math.abs(t.props.crop.bottomRight.x-s.bottomRight.x)<=_y&&Math.abs(t.props.crop.bottomRight.y-s.bottomRight.y)<=_y)?null:{id:t.id,x:n,y:i,props:{w:r,h:o,crop:s}}})({baselineShape:(i=t.id,Vy.get(i)??null??t),shape:t});var i;n&&e.editor.commands.updateShapes([n],{source:"user"})}},{id:ix,isVisible:e=>"image"===e.selection.commonShapeType,isEnabled:e=>e.selection.selectedShapes.some(e=>Bc(e)&&!e.isLocked),getValue:e=>(e=>{let t;for(const n of e){if(!Bc(n))continue;const e=dc(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)?dc(n):null})(t);if(null===n)return;const i=e.selection.selectedShapes.filter(Bc).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:[Zy],getGroups:()=>[{id:"image.tools",items:[{kind:"button",id:Zy,actionId:Zy,label:"Image",icon:"image-plus",dataUi:"insert-image-tool-button"}]}]},{id:"image.selection-toolbar",surface:"selection",order:30,actionIds:[Qy,Jy,ex,tx,nx,ix,jy,Gy],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups(e){const t=[];return Dc(e)&&t.push({id:"image.crop-zoom",order:10,items:[{kind:"stepper",id:"image.crop.zoom-stepper",actionId:ex,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:tx,options:Yy.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:nx,actionId:nx,label:"Reset crop",icon:"rotate-ccw",dataUi:"reset-image-crop-button"}]}),t.push((({dataUiPrefix:e,id:t,order:n})=>({id:t,order:n,items:[Hc({dataUiPrefix:e})]}))({dataUiPrefix:"image",id:"image.style-corner-radius",order:35})),t.push({id:"image.asset",order:40,items:[{kind:"button",id:Qy,actionId:Qy,label:"Crop image",icon:"crop",dataUi:"crop-image-button"},{kind:"button",id:Jy,actionId:Jy,label:"Done cropping",icon:"check",dataUi:"done-cropping-button"},{kind:"button",id:jy,actionId:jy,label:"Replace image",icon:"image-plus",dataUi:"replace-image-button"},{kind:"button",id:Gy,actionId:Gy,label:"Download original",icon:"download",dataUi:"download-image-original-button"}]}),t}},{id:"image.floating-selection-toolbar",surface:"selection",placement:"floating",order:30,actionIds:[Qy,Jy,ex,tx,nx,ix,jy,Gy],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups:e=>Dc(e)?[{id:"image.floating-crop-zoom",order:10,items:[{kind:"stepper",id:"image.floating-crop.zoom-stepper",actionId:ex,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:tx,options:Yy.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:[Hc({dataUiPrefix:"floating-image-crop"})]},{id:"image.floating-crop-actions",order:30,items:[{kind:"button",id:"image.floating-crop.done",actionId:Jy,label:"Done cropping",icon:"check",dataUi:"floating-done-cropping-button"},{kind:"button",id:"image.floating-crop.reset",actionId:nx,label:"Reset crop",icon:"rotate-ccw",dataUi:"floating-reset-image-crop-button"}]}]:[{id:"image.floating-corner-radius",order:10,items:[Hc({dataUiPrefix:"floating-image"})]},{id:"image.floating-asset",order:20,items:[{kind:"button",id:"image.floating.crop",actionId:Qy,label:"Crop image",icon:"crop",dataUi:"floating-crop-image-button"},{kind:"button",id:"image.floating.replace",actionId:jy,label:"Replace image",icon:"image-plus",dataUi:"floating-replace-image-button"},{kind:"button",id:"image.floating.download",actionId:Gy,label:"Download original",icon:"download",dataUi:"floating-download-image-original-button"}]}]}],contextMenuContributions:[{id:"image.shape-context-menu",target:"selection",order:30,actionIds:[Qy,jy,Gy],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getSections:()=>[{id:"image.asset-context-menu",title:"Image",items:[{kind:"command",id:Qy,actionId:Qy,label:"Crop image",icon:"crop",dataUi:"context-menu-crop-image-button"},{kind:"command",id:jy,actionId:jy,label:"Replace image",icon:"image-plus",dataUi:"context-menu-replace-image-button"},{kind:"command",id:Gy,actionId:Gy,label:"Download original",icon:"download",dataUi:"context-menu-download-image-original-button"}]}]}]}}function Uc(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return null;const[t]=e.selection.selectedShapes;return Bc(t)?t:null}function Dc(e){const t=Uc(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!Pc(t,n.markId))}function zc(e){return{id:e,isVisible:()=>!1,isEnabled:()=>!1,run(){throw new Error(`Image toolbar action ${e} requires a host implementation.`)}}}function Hc({dataUiPrefix:e}){return{kind:"text-input",id:`${e}.corner-radius`,actionId:ix,label:"Corner radius",placeholder:"0",dataUi:`${e}-corner-radius-control`}}function _c({editor:e,isHovered:t,shape:n,shapeEditingSession:i}){const{altText:r,assetId:o,crop:s,h:a,w:l}=n.props,d=o?e.resolveAssetUrl(o):null,c=cc({cornerRadius:n.props.cornerRadius,h:a,w:l});if(!d)return tg("div",{"data-ui":"image-shape-missing-asset",style:{alignItems:"center",background:"#f1f5f9",border:`1px solid ${t?jf:"#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:l},children:"Missing image"});const u=(({crop:e,shapeHeight:t,shapeWidth:n})=>{const i=mc(e);if(!i)return null;const r=n/i.width,o=t/i.height;return{imageX:-i.left*r,imageY:-i.top*o,imageWidth:r,imageHeight:o,rect:i}})({crop:s,shapeHeight:a,shapeWidth:l});if(u){const e=i?.shapeId===n.id&&Pc(n,i.markId),o={display:"block",height:u.imageHeight,left:u.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:u.imageY,userSelect:"none",width:u.imageWidth};
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
return
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
return tg("rect",{"data-ui":"path-draft-control-point","data-path-draft-control-point":i,x:e.x-r,y:e.y-r,width:t,height:t,rx:2,ry:2,fill:"candidate"===i?"rgba(219, 234, 254, 0.98)":"rgba(255, 255, 255, 0.98)",stroke:Ux,strokeWidth:n})}function Ju({shape:e,isHovered:t=!1,shapeEditingSession:n=null,fill:i=e.props.fill,stroke:r=e.props.stroke,strokeWidth:o=e.props.strokeWidth}){const{renderBounds:s}=Fu({props:{...e.props,strokeWidth:o}}),a=(e=>Xu(e).previewNodeId)(e),l=yu(((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,a));if(!l)return null;const d=n?.shapeId===e.id;
|
|
40
|
-
return ng("svg",{width:"100%",height:"100%",viewBox:`${s.x} ${s.y} ${Math.max(s.w,1)} ${Math.max(s.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[k(i)?null:tg("path",{d:l,fill:P(i),fillRule:e.props.fillRule,clipRule:e.props.fillRule,stroke:"none"}),
|
|
41
|
-
tg("path",{d:l,fill:"none",stroke:nr(r,t),strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round"}),d?tg(eh,{shape:e}):null]})}function eh({shape:e}){
|
|
42
|
-
return
|
|
43
|
-
return
|
|
44
|
-
return
|
|
45
|
-
return tg("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(37, 99, 235, 0.92)",stroke:"rgba(255,255,255,0.96)",strokeWidth:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}function rh(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6}function oh(e){return zu(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&&rh(i,e)||t.push(e)}return t.length>1&&rh(t[0],t[t.length-1])&&t.pop(),t.length>=3?t:null})(Lu(e).points)).filter(e=>null!==e).map(e=>[e])}function sh(e){const t=e.length>1&&rh(e[0],e[e.length-1])?e.slice(0,-1):e;return t.length<3?null:{id:`boolean-subpath:${zx+=1}`,closed:!0,nodes:t.map(([e,t])=>({id:`boolean-node:${Hx+=1}`,x:e,y:t,kind:"corner"}))}}function ah(e){const t=e.getShapeEditingSession();if(!t)return null;const n=e.getShape(t.shapeId);return qu(n)?n:null}function lh(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function dh(e,t,n){const i=n?e.len():t?.len()??e.len();if(0===i)return null;const r=e.normalize().mul(-i);return{dx:r.x,dy:r.y}}function ch(){return{id:"land.path.interactions",editorEvent:{handleEvent(e,t){if("click"===t.type&&"double_click"===t.name&&"up"===t.phase){const n=e.hitTestShape(t.pagePoint);if(qu(n))return e.startEditingShape({shapeId:n.id,markId:"path.edit",entryMode:"focusEnd"},"user"),"handled"}if("pointer"===t.type&&"pointer_down"===t.name&&t.altKey){const n=ah(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind&&"path.node"===i.type){const t=pu(i.type,i.id);if("path.node"===t?.type){const i=((e,t,n)=>e.map(e=>e.id!==t?vu(e):{...e,closed:!(e.nodes.length<=3)&&e.closed,nodes:e.nodes.filter(e=>e.id!==n).map(Iu)}).filter(e=>e.nodes.length>0))(n.props.subpaths,t.subpathId,t.nodeId);return e.commands.updateShapes([{id:n.id,props:{subpaths:i}}],{source:"user"}),"handled"}}}if("pointer"===t.type&&"pointer_down"===t.name&&0===t.button&&!t.altKey){const n=ah(e);if(!n)return"continue";if("custom"===e.hitTestSelectionHandle(t.pagePoint)?.kind)return"continue";const i=lh(e,n,t.pagePoint),r=((e,t,n)=>{const i=n*n;let r=null;for(const o of e){if(o.nodes.length<2)continue;const e=o.closed?o.nodes.length:o.nodes.length-1;for(let n=0;n<e;n+=1){const e=o.nodes[n],s=o.nodes[(n+1)%o.nodes.length];if(!e||!s)continue;const a=Mu(e,s)?32:1;let l=wu(e);for(let n=1;n<=a;n+=1){const d=Au(e,s,n/a),c=_u(t,l,d),u=(n-1+c.t)/a;u>.02&&u<.98&&c.distanceSquared<=i&&(!r||c.distanceSquared<r.distanceSquared)&&(r={subpathId:o.id,startNodeId:e.id,endNodeId:s.id,t:u,distanceSquared:c.distanceSquared}),l=d}}}return r?{subpathId:r.subpathId,startNodeId:r.startNodeId,endNodeId:r.endNodeId,t:r.t,distance:Math.sqrt(r.distanceSquared)}:null})(n.props.subpaths,i,7/e.getCurrentCamera().z);if(!r)return"continue";e.history.mark(_x);const o=function(e,t,n){return e.map(e=>{if(e.id!==t.subpathId)return vu(e);const i=e.nodes.findIndex(e=>e.id===t.startNodeId);if(i<0)return vu(e);const r=(i+1)%e.nodes.length,o=e.nodes[i],s=e.nodes[r];if(!o||!s||s.id!==t.endNodeId)return vu(e);const a=((e,t,n,i)=>{if(!Mu(e,t)){const r=Eu(wu(e),wu(t),n);return{start:Iu(e),node:{id:i,x:r.x,y:r.y,kind:"corner"},end:Iu(t)}}const[r,o,s,a]=Bu(e,t),l=Eu(r,o,n),d=Eu(o,s,n),c=Eu(s,a,n),u=Eu(l,d,n),h=Eu(d,c,n),p=Eu(u,h,n);return{start:{...Iu(e),out:Yu(l.sub(r))},node:{id:i,x:p.x,y:p.y,kind:"smooth",in:Yu(u.sub(p)),out:Yu(h.sub(p))},end:{...Iu(t),in:Yu(c.sub(a))}}})(o,s,t.t,n),l=e.nodes.map(Iu);return l[i]=a.start,l[r]=a.end,l.splice(i+1,0,a.node),{...e,nodes:l}})}(n.props.subpaths,r,`insert-node:${Nx+=1}`);return e.commands.updateShapes([{id:n.id,props:{subpaths:o}}],{source:"user"}),e.history.squashToMark(_x,"shape.edit"),"handled"}return"continue"}},selectionHandle:{createSession(e,{handle:t,shape:n,originPagePoint:i}){if(!qu(n)||"custom"!==t.kind)return null;const r=pu(t.type,t.id);if(!r)return null;if(e.getShapeEditingSession()?.shapeId!==n.id)return null;const o=n,s="path.node"===r.type?(a=o.props.subpaths,l=r.subpathId,d=r.nodeId,Ou(a,l)?.nodes.find(e=>e.id===d)??null):null;var a,l,d;const c=lh(e,o,i);return{shapeId:n.id,historyMark:"path.handle",handleSnapMode:"point",allowSelfSnap:!0,update({editor:e,pagePoint:t,source:i}){if(!qu(e.getShape(n.id)))return"stop";const a=lh(e,o,t),l="path.node"===r.type?s?Wu(o.props.subpaths,r.subpathId,r.nodeId,e=>((e,t)=>({...e,x:e.x+t.x,y:e.y+t.y}))(e,a.sub(c))):Pu(o.props.subpaths):Wu(o.props.subpaths,r.subpathId,r.nodeId,e=>((e,t,n)=>{const i=wu(e),r={...e},o=n.sub(i);return"in"===t?(r.in={dx:o.x,dy:o.y},"corner"!==e.kind&&(r.out=dh(o,e.out?Cu(e).sub(i):null,"symmetric"===e.kind))):(r.out={dx:o.x,dy:o.y},"corner"!==e.kind&&(r.in=dh(o,e.in?ku(e).sub(i):null,"symmetric"===e.kind))),r})(e,r.handle,a));return e.commands.updateShapes([{id:n.id,props:{subpaths:l}}],{source:i}),"continue"}}}}}}function uh(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function hh(e){if(!e||"object"!=typeof e)return null;const t=e,n=uh(t.dx,NaN),i=uh(t.dy,NaN);return Number.isFinite(n)&&Number.isFinite(i)?t.dx===n&&t.dy===i?e:{dx:n,dy:i}:null}function ph(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=uh(n.x,NaN),r=uh(n.y,NaN);return Number.isFinite(i)&&Number.isFinite(r)?{id:"string"==typeof n.id?n.id:`node:${t}`,x:i,y:r,kind:(o=n.kind,"string"==typeof o&&$x.includes(o)?n.kind:"corner"),in:hh(n.in),out:hh(n.out)}:null;var o})(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 gh(e,t,n){const i=n.sub(t),r=i.len2();if(0===r)return e.dist2(t);const o=e.sub(t),s=Math.max(0,Math.min(1,(o.x*i.x+o.y*i.y)/r));return e.dist2(t.add(i.mul(s)))}function fh(e,t){const n=t(wu(e)),i=e.in?t(ku(e)):null,r=e.out?t(Cu(e)):null;return{...Iu(e),x:n.x,y:n.y,in:i?{dx:i.x-n.x,dy:i.y-n.y}:null,out:r?{dx:r.x-n.x,dy:r.y-n.y}:null}}function mh(){return`node:${Yx+=1}`}function Sh(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function yh(e,t){return t.previewNodeId?e.map(e=>e.id===t.subpathId?{...e,nodes:e.nodes.filter(e=>e.id!==t.previewNodeId)}:e):Pu(e)}function xh(e,t){return Ou(e.props.subpaths,t.subpathId)?.nodes.filter(e=>e.id!==t.previewNodeId).length??0}function bh({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,fillRuleActionId:i,dataUiPrefix:r}){return[{id:`${r}.style-fill`,items:[{kind:"swatches",id:`${r}.fill`,actionId:e,label:"Fill",options:eb.map(e=>({...e,dataUi:`${r}-fill-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-stroke`,items:[{kind:"swatches",id:`${r}.stroke`,actionId:t,label:"Stroke",options:tb.map(e=>({...e,dataUi:`${r}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-stroke-width`,items:[{kind:"stepper",id:`${r}.stroke-width`,actionId:n,label:"Stroke width",dataUi:`${r}-stroke-width-control`,options:nb.map(e=>({...e,dataUi:`${r}-stroke-width-${e.value}-button`}))}]},{id:`${r}.fill-rule`,items:[{kind:"segmented",id:`${r}.fill-rule`,actionId:i,options:ib.map(e=>({...e,dataUi:`${r}-fill-rule-${e.value}-button`}))}]}]}function Ih(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(!qu(i))continue;const e=i.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!C(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=kh(e,n);if(void 0===i)return;const r=t.selection.selectedShapes.filter(qu).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));r.length>0&&t.editor.commands.updateShapes(r,{source:"user"})}}}function vh(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=kh(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("path",{[e]:i})}}}function Ph(e){return{id:`path.boolean.${e}`,isVisible:e=>"path"===e.selection.commonShapeType,isEnabled:e=>wh(e).length>=2,run({context:t}){const n=wh(t),i=n[0];if(!i||n.length<2)return;const r=((e,t,n)=>{const i=function(e,t){const n=t.map(oh).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,Dx.union)(n,...i);case"subtract":return(0,Dx.difference)(n,...i);case"intersect":return(0,Dx.intersection)(n,...i);case"xor":return(0,Dx.xor)(n,...i)}})(e,n).flatMap(e=>e).map(sh).filter(e=>null!==e)}(e,t);return 0===i.length?null:Du(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(!r)return;const o=`path.boolean.${e}`;t.editor.history.mark(o);const[s]=t.editor.commands.createShapes([{type:"path",x:r.x,y:r.y,parentId:i.parentId,props:{...i.props,subpaths:r.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(o,"shape.boolean")}}}function wh(e){return e.selection.selectedShapes.filter(qu).filter(e=>!e.isLocked).filter(e=>e.props.subpaths.some(e=>e.closed&&e.nodes.length>=3))}function kh(e,t){return"strokeWidth"===e?"number"==typeof t&&nb.some(e=>e.value===t)?t:void 0:b(t)?v(t,m("fill"===e?"fill-blue":"stroke-slate")):void 0}function Ch({childIds:e,depth:t,editor:n,index:i,pageId:r,shape:o}){return{id:o.id,parentId:o.parentId,pageId:r,type:o.type,childIds:e,siblingIndex:i,depth:t,displayName:o.type,canReceiveChildren:n.canUseShapeParent(o.id),isHidden:o.isHidden,isLocked:o.isLocked,isEffectivelyHidden:n.isShapeHidden(o.id),isEffectivelyLocked:n.isShapeOrAncestorLocked(o.id)}}function Th(e,t){let n=0,i=e.getShape(t);const r=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(r.has(t))break;r.add(t),i=e.getShape(t),n+=1}return n}function Eh(e){return{id:e.id,name:e.name,index:e.index}}function Bh(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 Mh(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 Ah(e,t){const n=e.sessionSignal.get(),i=n.activeToolId;t.assertToolId(i);const r=i,o=e.getPages().map(t=>({pageId:t.id,selectedShapeIds:[...e.getSelectedShapeIds(t.id)],camera:{...e.getCamera(t.id)}}));return{currentPageId:n.currentPageId,activeToolId:r,isToolLocked:n.isToolLocked,pages:o}}function Rh(e,t){const n=e.getActiveToolId();t.assertToolId(n);const i=n;return{productId:t.productId,pageId:e.getCurrentPageId(),activeToolId:i,selectedShapeIds:[...e.getSelectedShapeIds()],shapeCount:e.getCurrentPageShapeIds().length,session:Ah(e,t)}}function Lh(e){return{...e,selectedShapeIds:[...e.selectedShapeIds],session:{...e.session,pages:e.session.pages.map(e=>({...e,selectedShapeIds:[...e.selectedShapeIds],camera:{...e.camera}}))}}}function Fh(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 $h(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}function Uh(e,t){e.includes(t)||e.push(t)}function Dh(e){const{featureControllers:t,editor:n}=e;return{features:t,snapshot:()=>Rh(n,e),subscribe(t){let i=Lh(Rh(n,e));return n.listen(r=>{const o=Rh(n,e),s=function(e,t){const n=[];return e.pageId!==t.pageId&&n.push("pageId"),e.activeToolId!==t.activeToolId&&n.push("activeToolId"),Fh(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],r=t.pages[n];if(i.pageId!==r.pageId||!Fh(i.selectedShapeIds,r.selectedShapeIds)||!$h(i.camera,r.camera))return!1}return!0})(e.session,t.session)||n.push("session"),n}(i,o);if((r.diff.added.some(e=>"document"===e.scope)||r.diff.updated.some(e=>"document"===e.before.scope||"document"===e.after.scope)||r.diff.removed.some(e=>"document"===e.scope))&&Uh(s,"document"),(r.diff.added.some(e=>"session"===e.scope)||r.diff.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||r.diff.removed.some(e=>"session"===e.scope))&&Uh(s,"session"),0===s.length)return void(i=Lh(o));const a=i;i=Lh(o);try{t({source:r.source,changes:s,snapshot:o,previousSnapshot:a})}catch(l){(e=>{const t=globalThis.reportError;"function"!=typeof t?console.error(e):t(e)})(l)}})},clearHistory(){n.history.clear()},canUndo:()=>n.historyStateSignal.get().canUndo,canRedo:()=>n.historyStateSignal.get().canRedo,undo:()=>n.undo(),redo:()=>n.redo(),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?Bh(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=>Bh(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(Mh);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 r=n.viewportScreenSizeSignal.get();if(r.w<=0||r.h<=0)return!1;const o=n.getCurrentCamera();return n.commands.setCamera({pageId:t,camera:{x:i.center.x-r.w/(2*o.z),y:i.center.y-r.h/(2*o.z),z:o.z}},{source:"user"}),!0},getLayerTree:e=>(({editor:e,pageId:t=e.getCurrentPageId()})=>{const n=[],i=(r,o)=>{e.getChildShapes(r).forEach((r,s)=>{const a=e.getChildShapeIds(r.id);n.push(Ch({childIds:a,depth:o,editor:e,index:s,pageId:t,shape:r})),i(r.id,o+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 r=e.getChildShapeIds(n.parentId);return Ch({childIds:e.getChildShapeIds(n.id),depth:Th(e,n.id),editor:e,index:r.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(Eh),createPage:e=>Eh(n.createPageAndSelect(e?{name:e}:void 0,"user")),renamePage(e,t){n.renamePage(e,t,"user")},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 zh(e,t,n){const i=e.getDefaultShapeProps("geo"),[r]=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}}],{source:"user"});return r&&"geo"===r.type?{id:r.id,type:r.type}:null}function Hh(e){return{create(t){const n=e.getDefaultShapeProps("arrow"),i=ba(e,{startPagePoint:new xg(t.start.x,t.start.y),endPagePoint:new xg(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 _h(e){return{createRectangle:t=>zh(e,"rectangle",t),createEllipse:t=>zh(e,"ellipse",t),createDiamond:t=>zh(e,"diamond",t),createTriangle:t=>zh(e,"triangle",t),createHexagon:t=>zh(e,"hexagon",t),createStar:t=>zh(e,"star",t)}}function Nh(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:cr(t.text)}}],{source:"user"});return i&&"text"===i.type?{id:i.id,type:i.type}:null}}}function Oh(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 r=t.filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked});return 0===r.length?[]:(e.commands.reparentShapes({ids:r,parentId:n},{source:"user"}),r)}}}function Wh(e,t){const n=e.getShape(t.id);if("geo"===t.type){const e=(n?.props)?.geo;return{...t,displayName:Yh(e),geoKind:e}}if("image"===t.type){const i=n?.props,r=i?.assetId??null,o=((r?e.getAsset(r):void 0)?.props)?.name,s=i?.altText?.trim();return{...t,displayName:o||s||"Image",imageAssetId:r,imageThumbnailSrc:r?e.resolveAssetUrl(r):null}}if("text"===t.type){const e=n?.props,i=e?.richText?ur(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 Yh(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 Xh(e,t){const n=e.getDocumentSnapshot();if(0===t.length)return n;const i=new Set(n.records.map(e=>e.id)),r=t.filter(Kh).filter(e=>!i.has(e.id));return{...n,records:[...n.records,...r]}}function Kh(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&"string"==typeof e.id}function Vh(e={}){let t=[];return{async restore(n){const{documentSnapshot:i,sessionSnapshot:r}=await(async(e={})=>{const[t,n]=await Promise.all([Zh(jh(e)),Zh(Gh(e))]);return{documentSnapshot:t,sessionSnapshot:n}})(e),o=function(e,{documentSnapshot:t,sessionSnapshot:n}){let i=null,r=[];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:vi(e.shapeTypes,t.modelShapeTypes),modelBindingTypes:vi(e.bindingTypes,t.modelBindingTypes),renderableShapeTypes:t.renderableShapeTypes?vi(e.shapeTypes,t.renderableShapeTypes):[]}))({requirements:bi(t),support:n});if(0===i.modelShapeTypes.length&&0===i.modelBindingTypes.length)return{kind:"full",snapshot:t};const r=(({snapshot:e,support:t})=>{const n=Fe(e,"document"),i=new Set,r=new Set,o=new Set,s=new Set,a=[];for(const d of n.records)Ii(d)&&"shape"===d.typeName&&"string"==typeof d.type&&!t.modelShapeTypes.has(d.type)&&("string"==typeof d.id&&d.id.startsWith("shape:")&&i.add(d.id),r.add(d.type));const l=n.records.filter(e=>{if(!Ii(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),r=!i.has(e.fromId)&&!i.has(e.toId);return!(!n||!r)||("string"==typeof e.id&&e.id.startsWith("binding:")&&o.add(e.id),s.add(e.type),a.push(e),!1)}return!0});return{snapshot:{schemaVersion:n.schemaVersion,records:l},removedShapeIds:Pi(i),removedShapeTypes:Pi(r),removedBindingIds:Pi(o),removedBindingTypes:Pi(s),removedRecords:a}})({snapshot:t,support:n});return{kind:"partial",snapshot:r.snapshot,removedBindingIds:r.removedBindingIds,removedBindingTypes:r.removedBindingTypes,removedShapeIds:r.removedShapeIds,removedShapeTypes:r.removedShapeTypes,preservedRecords:r.removedRecords,unsupportedBindingTypes:i.modelBindingTypes,unsupportedShapeTypes:i.modelShapeTypes}})(e,t);"partial"===n.kind&&(o=n,console.warn("[land] Restored a persisted canvas snapshot with unsupported document records preserved for round-trip persistence.",{removedBindingIds:o.removedBindingIds,removedBindingTypes:o.removedBindingTypes,removedShapeIds:o.removedShapeIds,removedShapeTypes:o.removedShapeTypes,unsupportedBindingTypes:o.unsupportedBindingTypes,unsupportedShapeTypes:o.unsupportedShapeTypes}),r=n.preservedRecords,i={kind:"preserving-unsupported-records",preservedRecordCount:n.preservedRecords.length,unsupportedBindingTypes:n.unsupportedBindingTypes,unsupportedShapeTypes:n.unsupportedShapeTypes}),e.loadDocumentSnapshot(n.snapshot,{source:"system"})}var o;return n&&e.loadSessionSnapshot(n,{source:"system"}),e.history.clear(),{autoPersistence:"enabled",preservedUnsupportedRecords:r,status:i}}(n,{documentSnapshot:i,sessionSnapshot:r});return t=o.preservedUnsupportedRecords??[],o},start(n){const i=new db(n,{getDocumentSnapshot:()=>Xh(n,t),options:e});return i.start(),()=>i.stop()},flushSnapshot:n=>qh(n,e,{documentSnapshot:Xh(n,t)}),discardUnsupportedRecords:async n=>(await qh(n,e),t=[],{autoPersistence:"enabled",status:null})}}async function qh(e,t={},{documentSnapshot:n=e.getDocumentSnapshot()}={}){const i=JSON.stringify(n),r=JSON.stringify(e.getSessionSnapshot());await Promise.all([Jh(jh(t),i),Jh(Gh(t),r)])}function jh(e){return e.storageNamespace?`${e.storageNamespace}.document`:"land.canvas.document"}function Gh(e){return e.storageNamespace?`${e.storageNamespace}.session`:"land.canvas.session"}async function Zh(e){const t=await(async e=>{const t=await Qh();return t?new Promise((n,i)=>{const r=t.transaction(ab,"readonly");r.addEventListener("complete",()=>t.close()),r.addEventListener("abort",()=>{t.close(),i(r.error)}),r.addEventListener("error",()=>{t.close(),i(r.error)});const o=r.objectStore(ab).get(e);o.addEventListener("success",()=>{n("string"==typeof o.result?o.result:null)}),o.addEventListener("error",()=>i(o.error))}):null})(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Qh(){return"undefined"==typeof indexedDB?Promise.resolve(null):new Promise((e,t)=>{const n=indexedDB.open(sb,2);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains("snapshots")||n.result.createObjectStore(ab),n.result.objectStoreNames.contains("imageBlobs")||n.result.createObjectStore(lb)}),n.addEventListener("success",()=>e(n.result)),n.addEventListener("error",()=>t(n.error))})}async function Jh(e,t){const n=await Qh();n&&await new Promise((i,r)=>{const o=n.transaction(ab,"readwrite");o.addEventListener("complete",()=>{n.close(),i()}),o.addEventListener("abort",()=>{n.close(),r(o.error)}),o.addEventListener("error",()=>{n.close(),r(o.error)}),o.objectStore(ab).put(t,e)})}async function ep(e){const t=await op();return t?new Promise((n,i)=>{const r=t.transaction(lb,"readonly");r.addEventListener("complete",()=>t.close()),r.addEventListener("abort",()=>{t.close(),i(r.error)}),r.addEventListener("error",()=>{t.close(),i(r.error)});const o=r.objectStore(lb).get(e);o.addEventListener("success",()=>{n(o.result instanceof Blob?o.result:null)}),o.addEventListener("error",()=>i(o.error))}):null}async function tp(e){const t=await ep(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 np(e){const t=await op();t&&await new Promise((n,i)=>{const r=t.transaction(lb,"readwrite");r.addEventListener("complete",()=>{t.close(),n()}),r.addEventListener("abort",()=>{t.close(),i(r.error)}),r.addEventListener("error",()=>{t.close(),i(r.error)}),r.objectStore(lb).delete(e)})}function ip(e,t){const n=e.getAsset(t),i=n?n.props.storageKey:null;return"string"==typeof i&&i.length>0?i:null}function rp(e){const t=new Set;for(const n of e.getAssets()){const e=n.props.storageKey;"string"==typeof e&&e.length>0&&t.add(e)}return t}function op(){return"undefined"==typeof indexedDB?Promise.resolve(null):new Promise((e,t)=>{const n=indexedDB.open(sb,2);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains("snapshots")||n.result.createObjectStore(ab),n.result.objectStoreNames.contains("imageBlobs")||n.result.createObjectStore(lb)}),n.addEventListener("success",()=>e(n.result)),n.addEventListener("error",()=>t(n.error))})}async function sp(e){const t=URL.createObjectURL(e),n=await(i=t,new Promise((e,t)=>{const n=new Image;n.addEventListener("load",()=>{e({width:n.naturalWidth||n.width,height:n.naturalHeight||n.height})}),n.addEventListener("error",()=>{t(new Error("Could not decode image file."))}),n.src=i})).finally(()=>{URL.revokeObjectURL(t)});var i;const{storageKey:r}=await async function(e){const t="undefined"!=typeof crypto&&"randomUUID"in crypto?`${cb}${crypto.randomUUID()}`:`${cb}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=await op();if(!n)throw new Error("IndexedDB is not available for image storage.");return await new Promise((i,r)=>{const o=n.transaction(lb,"readwrite");o.addEventListener("complete",()=>{n.close(),i()}),o.addEventListener("abort",()=>{n.close(),r(o.error)}),o.addEventListener("error",()=>{n.close(),r(o.error)}),o.objectStore(lb).put(e,t)}),{storageKey:t}}(e);return{name:e.name||"Image",storageKey:r,mimeType:e.type||"image/png",fileSize:e.size,width:n.width,height:n.height}}function ap(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 lp(e,t){return function(e,t,n){return e.screenToPage(((e,t=Qr())=>{if(!t)return new xg(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new xg(e.clientX-n.left,e.clientY-n.top)})(t,n))}(e,t)}function dp({filename:e,url:t}){const n=document.createElement("a");n.href=t,n.download=e,n.click()}function cp(e,t){return e.commands.createAsset({type:"image",props:{w:t.width,h:t.height,name:t.name,storageKey:t.storageKey,mimeType:t.mimeType,fileSize:t.fileSize,isAnimated:"image/gif"===t.mimeType}},{source:"user"})}async function up({editor:e,file:t,imageObjectUrls:n,pagePoint:i,size:r,flushSnapshot:o}){if(!t.type.startsWith("image/"))return null;const s=await sp(t);await n.preload(s.storageKey);let a=null;try{const t=cp(e,s);a=t.id;const n=r??(({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(),d=i??l?.center??e.screenToPage(new xg(360,240)),[c]=e.commands.createShapes([{type:"image",x:Math.round(d.x-n.w/2),y:Math.round(d.y-n.h/2),props:{...n,assetId:t.id,crop:null,altText:s.name}}],{source:"user"});return c?(e.commands.setSelectedShapeIds([c.id],{source:"user"}),await(o?.(e)),c.id):null}catch(l){throw a&&e.commands.deleteAsset(a,{source:"system"}),n.release(s.storageKey),await np(s.storageKey),l}}async function hp({editor:e,file:t,imageObjectUrls:n,flushSnapshot:i}){if(!t.type.startsWith("image/"))return;const[r]=e.getSelectedShapes();if(!Bc(r)||r.isLocked)return;const o=r.props.assetId,s=await sp(t);await n.preload(s.storageKey);let a=null;try{const t=cp(e,s);a=t.id,e.commands.updateShapes([{id:r.id,props:{assetId:t.id,crop:null,altText:s.name}}],{source:"user"}),o&&!((e,t)=>e.getDocumentSnapshot().records.some(e=>"shape"===e.typeName&&e.props.assetId===t))(e,o)&&e.commands.deleteAsset(o,{source:"user"}),e.commands.setSelectedShapeIds([r.id],{source:"user"}),await(i?.(e))}catch(l){throw a&&e.commands.deleteAsset(a,{source:"system"}),n.release(s.storageKey),await np(s.storageKey),l}}async function pp({editor:e,imageObjectUrls:t}){const[n]=e.getSelectedShapes();if(!Bc(n)||!n.props.assetId)return;const i=e.getAsset(n.props.assetId);if(!g(r=i)||"image"!==r.type)return;var r;const o=i.props.storageKey,s="string"==typeof i.props.name&&i.props.name.length>0?i.props.name:"land-image";if(!o)return;const a=await ep(o);if(a)return void(await(async({blob:e,filename:t})=>{const n=URL.createObjectURL(e);try{dp({filename:t,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}})({blob:a,filename:s}));const l=t.resolve(o);l&&dp({filename:s,url:l})}function gp({assetResolverTokens:e,services:t}){return e.map(e=>t.get(e)).filter(e=>!!e)}function fp(e){return{id:e}}function mp(e){return e.get(hb)}async function Sp({context:e,services:t}){const n=mp(t);if(!n)return null;const i=e.editor.createClipboardPayloadFromSelection();return i?(await n.write(i),i):null}async function yp({atMenuPoint:e=!1,context:t,services:n}){const i=mp(n);if(!i)return;const r=await i.read();r&&t.editor.pasteClipboardPayload({payload:r,pagePoint:xp({atMenuPoint:e,context:t}),source:"user"})}function xp({atMenuPoint:e,context:t}){return e&&bp(t)?t.menu.anchor.pagePoint:t.editor.inputs.state.get().currentPagePoint??t.editor.viewportPageBoundsSignal.get()?.center??void 0}function bp(e){return"menu"in e}function Ip(e){const[t]=e.selection.selectedShapes;return!(1!==e.selection.count||!t?.parentId.startsWith("shape:"))&&"frame"===e.editor.getShape(t.parentId)?.type}function vp(e){return Math.min(1,Math.max(0,e))}function Pp({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 wp(){return{token:_b,create(){const e=(()=>{const e=new Map,t=new Map,n=async n=>{const i=e.get(n);if(i)return i;const r=t.get(n);if(r)return r;const o=ep(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,o),o};return{async preloadForEditor(e){await Promise.all(Array.from(rp(e)).map(e=>n(e)))},preload:n,resolve:t=>e.get(t)??null,resolveAssetUrl(t,n){const i=ip(t,n);return i?e.get(i)??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()}}})();return{objectUrls:e,cleanupAfterRestore:t=>async function({editor:e,objectUrls:t}){const n=rp(e),i=await(async()=>{const e=await op();return e?new Promise((t,n)=>{const i=e.transaction(lb,"readonly");i.addEventListener("complete",()=>e.close()),i.addEventListener("abort",()=>{e.close(),n(i.error)}),i.addEventListener("error",()=>{e.close(),n(i.error)});const r=i.objectStore(lb).getAllKeys();r.addEventListener("success",()=>{t(r.result.map(String))}),r.addEventListener("error",()=>n(r.error))}):[]})(),r=[];for(const o of i)n.has(o)||(t?.release(o),await np(o),r.push(o));return r}({editor:t,objectUrls:e}).then(()=>{}).catch(e=>{console.warn("Could not clean up unreferenced image blobs.",e)}),preloadForEditor:t=>e.preloadForEditor(t),resolveAssetUrl:(t,n)=>e.resolveAssetUrl(t,n)}},dispose(e){e.objectUrls.releaseAll()}}}function kp(e){return{async inline({editor:t,exportedShapeIds:n,svg:i}){let r=i;const o=new Set;for(const s of n){const n=t.getShape(s);if(!Bc(n)||!n.props.assetId)continue;const i=n.props.assetId;if(o.has(i))continue;o.add(i);const a=t.getAsset(i),l=a&&"object"==typeof a.props?a.props.storageKey:null;if("string"!=typeof l||0===l.length)continue;const d=e.objectUrls.resolve(l)??await e.objectUrls.preload(l);if(!d)continue;const c=await tp(l);c&&(r=r.split(d).join(c))}return r}}}function Cp(e){if(!(e=>Xb.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: ${Kb}.`);throw new Error(`Unknown canvas kit tool "${e}". Available tool ids: ${Kb}.`)}}function Tp(e){return Ep({...e,assertToolId:e.assertToolId??Cp})}function Ep(e){return Object.assign({},function(e){const t=Dh(e),n={arrow:Hh(i=e.editor),geo:_h(i),text:Nh(i),frame:Oh(i)};var i;return{...t,...n,getLayerTree:n=>t.getLayerTree(n).map(t=>Wh(e.editor,t)),getLayerNode(n){const i=t.getLayerNode(n);return i?Wh(e.editor,i):null}}}(e),{image:e.featureControllers.get(Nb)})}function Bp(e,t){const n=Xp(n=>t?qi("useOptionalValue",e,n,{fireImmediately:!1}):()=>{},[t,e]),i=Xp(()=>t?e.get():null,[t,e]);return Jp(n,i,i)}function Mp({assetInliners:e=[],editor:t,themeRootRef:n}){const[i,r]=Qp(null);return{status:i,exportSvg:Xp(async i=>{const o=await async function({assetInliners:e=[],editor:t,padding:n=16,resolveThemeColor:i,shapeIds:r}){const o=t.repairExportIntegrity(r),s=t.getSvgString(r,{padding:n,resolveThemeColor:i}),a=t.getExportIntegrityReport(r),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:t.getShapeCapabilityManifest(),integrity:a});if((o.before.issues.length>0||a.issues.length>0)&&console.warn("SVG export integrity report",{before:o.before,after:o.after,final:a}),!s)return{status:l,svg:null,exportedShapeIds:[],skippedShapes:[]};s.skippedShapes.length>0&&console.warn("Skipped shapes during SVG export",s.skippedShapes);let d=s.svg;for(const c of e)d=await c.inline({editor:t,exportedShapeIds:s.exportedShapeIds,svg:d});return{status:l,svg:d,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 r(o.status),o},[e,t,n])}}function Ap({flushSnapshot:e}){return{id:"canvas-kit.image",services:[wp(),{token:Wb,create:()=>new Ob}],assetResolverTokens:[_b],initializeRuntime(t){(({flushSnapshot:e}={})=>({featureControllers:t,editor:n,services:i})=>{if(t.get(Nb))return;const r=i.get(_b);r&&t.register(Nb,{insertImage:({file:t,pagePoint:i,size:o,source:s="file-picker"})=>up({editor:n,file:t,imageObjectUrls:r.objectUrls,pagePoint:i,size:o,flushSnapshot:e,source:s}),async replaceSelectedImage({file:t}){if(!t.type.startsWith("image/"))return!1;const[i]=n.getSelectedShapes();return!(!Bc(i)||i.isLocked||(await hp({editor:n,file:t,imageObjectUrls:r.objectUrls,flushSnapshot:e}),0))},downloadSelectedImageOriginal:()=>pp({editor:n,imageObjectUrls:r.objectUrls})})})({flushSnapshot:e})(t),function({pluginHostRuntime:e,services:t}){const n=t.get(_b),i=t.get(Wb);n&&i&&(({hostBridge:e,imageObjectUrls:t,pluginHostRuntime:n})=>{n.toolbarRegistry.registerHostAction({id:Zy,run(){e.openInsertFilePicker()}}),n.toolbarRegistry.registerHostAction({id:jy,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return Bc(t)&&!t.isLocked},run(){e.openReplaceFilePicker()}}),n.toolbarRegistry.registerHostAction({id:Gy,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return Bc(t)&&!!t.props.assetId&&!!ip(e.editor,t.props.assetId)},run({context:e}){pp({editor:e.editor,imageObjectUrls:t})}})})({hostBridge:i,imageObjectUrls:n.objectUrls,pluginHostRuntime:e})}(t)},canShowToolbarDuringEditing:e=>Dc(e),createSvgAssetInliners(e){const t=e.get(_b);return t?[kp(t)]:[]},renderController({editor:t,services:n}){const i=n.get(_b);return i?tg(ub,{editor:t,hostBridge:n.get(Wb)??void 0,imageAssetService:i,flushSnapshot:e}):null}}}function Rp(e,t){return e.flatMap(e=>e.createSvgAssetInliners?.(t)??[])}function Lp({ids:e,kind:t,message:n,productId:i}){if(0===e.length)return;const r=`${i}:${t}:${e.join(",")}`;Vb.has(r)||(Vb.add(r),console.warn(n,e))}function Fp({controller:e,activeContextMenu:t,editor:n,grid:i,hostExtensions:r,onActiveContextMenuChange:o,persistence:s,pluginHostRuntime:a,services:l,themeRootRef:d}){const c=Fr(n.currentPageIdSignal),u=Fr(n.currentPageShapeIdsSignal),h=Fr(n.selectedShapeIdsSignal),p=Fr(n.selectionStateSignal),g=(e=>{const t=Fr(e.historyStateSignal);return{canUndo:t.canUndo,canRedo:t.canRedo,undo(){e.undo()},redo(){e.redo()}}})(n),f=(e=>{const t=Fr(e.pageStateSignal);return{pages:t.pages,currentPage:t.currentPage,currentPageId:t.currentPageId,canDeleteCurrentPage:t.canDeleteCurrentPage,createPage(){e.createPageAndSelect(void 0,"user")},deleteCurrentPage(){t.currentPage&&e.deletePage(t.currentPage.id,"user")},renameCurrentPage(n){t.currentPage&&e.renamePage(t.currentPage.id,n,"user")},selectPage(t){e.selectPage(t,"user")}}})(n),m=(e=>{const t=Fr(e.cameraZoomSignal);return{zoom:t,label:`${Math.round(100*t)}%`,zoomIn(){e.zoomAtViewportCenter(-120,"system")},zoomOut(){e.zoomAtViewportCenter(120,"system")},resetZoom(){e.resetZoom("user")}}})(n),S=function({editor:e,activeContextMenu:t,pluginHostRuntime:n}){const i=null!==t,r=Bp(e.selectionStateSignal,i),o=Bp(e.toolStateSignal,i);return Gp(()=>{if(!t||!r||!o)return{context:null,activeContextMenu:null,sections:[]};const i=(({editor:e,menu:t})=>{const n=e.toolStateSignal.get();return{...Pp({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,r,o])}({editor:n,activeContextMenu:t,pluginHostRuntime:a}),y=(({canShowContextToolbarDuringEditing:e,editor:t,pluginHostRuntime:n})=>{const i=Fr(t.toolStateSignal),r=Fr(t.selectionStateSignal),o=Fr(t.shapeEditingStateSignal),s=Fr(t.queries.selectionPageBoundsSignal),a=Fr(t.selectionTranslationActiveSignal),l="select"===i.activeToolId,d=l?r.count:0,c=Pp({editor:t,selectionState:r,toolState:i}),u=!o.session||(e?.(c)??!1),h=n.toolbarRegistry.getGroups("selection",c,{placement:"context"}),p=n.toolbarRegistry.getGroups("selection",c,{placement:"floating"}),g=l&&s&&p.length>0?{x:s.minX,y:s.minY}:null,f=u&&!a&&r.count>0&&p.length>0&&!!g,m=n.toolbarRegistry.getGroups("tool",c,{placement:"context"}),S=n.toolbarRegistry.getGroups("tool",c,{placement:"chrome"}),y=l&&r.count>0?h:m,x=u&&y.length>0,b=((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})(m,i.activeToolId),I=l&&r.count>0?(({commonShapeType:e,count:t,isMixedFrameAndPointHandleSelection:n,singleShapeType:i})=>{const r=i??e;if(!r)return n?"Mixed selection":`${t} selected`;const o=t>1?` (${t})`:"";return"geo"===r?`Shape${o}`:"text"===r?`Text${o}`:`${r.charAt(0).toUpperCase()}${r.slice(1)}${o}`})({commonShapeType:r.commonShapeType,count:d,isMixedFrameAndPointHandleSelection:r.isMixedFrameAndPointHandleSelection,singleShapeType:r.singleShapeType}):b;return{context:c,activeToolId:i.activeToolId,activeToolLabel:b,isToolLocked:i.isToolLocked,selectionCount:d,hasMixedSelectionRotation:r.hasMixedSelectionRotation,toolChromeToolbarGroups:S,contextToolbarGroups:y,floatingSelectionToolbarGroups:p,floatingSelectionToolbarPageAnchor:g,contextToolbarTitle:I,showContextToolbar:x,showFloatingSelectionToolbar:f}})({canShowContextToolbarDuringEditing:e=>((e,t)=>e.some(e=>e.canShowToolbarDuringEditing?.(t)))(r,e),editor:n,pluginHostRuntime:a}),x=Mp({assetInliners:Rp(r,l),editor:n,themeRootRef:d}),b=Gp(()=>{let t,i,r=[];return{getSnapshot(o){const s=n.store.recordsSignal.get(),a=o??n.getCurrentPageId();return i===s&&t===a||(i=s,t=a,r=e.getLayerTree(a)),r},subscribe:e=>qi("CanvasKitLayerTree.records",n.store.recordsSignal,e,{fireImmediately:!1})}},[e,n]),I=Gp(()=>({getActionState({actionId:e,context:t}){const n=a.toolbarRegistry.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=a.toolbarRegistry.getAction(e);i&&!1!==i.isVisible?.(t)&&!1!==i.isEnabled?.(t)&&i.run({context:t,value:void 0!==n?n:i.getValue?.(t)??null})}}),[a]);return{controller:e,contextMenu:{activeContextMenu:t,onActiveContextMenuChange:o,runAction({actionId:e,context:t,value:n}){(({actionId:e,context:t,pluginHostRuntime:n,value:i})=>{const r=n.toolbarRegistry.getAction(e);r&&!1!==r.isVisible?.(t)&&!1!==r.isEnabled?.(t)&&r.run({context:t,value:void 0!==i?i:r.getValue?.(t)??null})})({actionId:e,context:t,pluginHostRuntime:a,value:n})},surface:S},currentPageId:c,currentPageShapeIds:u,history:g,layerTree:b,pages:f,persistence:s,selection:p,selectedShapeIds:h,svgExport:x,toolbarRuntime:I,toolbarSurfaces:y,grid:i,zoom:m}}function $p({persistence:e}){const{discardUnsupportedRecords:t,isDiscardingUnsupportedRecords:n,status:i}=e;if(!i)return null;const r=[...i.unsupportedShapeTypes,...i.unsupportedBindingTypes].join(", ");
|
|
46
|
-
return ng("div",{role:"alert","data-ui":"canvas-kit-persistence-notice",className:"land-canvas-kit__persistence-notice",children:[ng("div",{className:"land-canvas-kit__persistence-notice-copy",children:[tg("strong",{children:"Unsupported records preserved"}),ng("span",{children:[i.preservedRecordCount," record",1===i.preservedRecordCount?"":"s"," will round-trip while saving. ",r?`Types: ${r}.`:""]})]}),tg("button",{type:"button",className:"land-canvas-kit__persistence-notice-action",disabled:!t||n,onClick:()=>{t?.()},children:n?"Saving":"Discard unsupported records"})]})}function Up({featureControllers:e,config:t,editor:n,pluginHostRuntime:i,productId:r,services:o}){const s=Gp(()=>({featureControllers:e,editor:n,pluginHostRuntime:i,productId:r,services:o}),[e,n,i,r,o]),a=Gp(()=>Tp(s),[s]);return(({controller:e,exposeOnWindow:t=!1,windowKey:n,onDispose:i,onReady:r})=>{const o=qp(e=>{r?.(e)}),s=qp(()=>{i?.()});Vp(()=>{const i=window;return t&&n&&(i[n]=e),o(e),()=>{t&&n&&i[n]===e&&delete i[n],s()}},[e,t,n])})({controller:a,exposeOnWindow:t.exposeControllerOnWindow,onDispose:t.onControllerDispose,onReady:t.onControllerReady,windowKey:t.windowKey}),a}function Dp(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:Vh({storageNamespace:e.storageNamespace??"land.canvasKit"}))(e),i=((e={})=>ob.filter(([t])=>!1!==e[t]).map(([t,n])=>{if("text"===t){const t=e.text;return"object"==typeof t?pS.configure(t):n}return n}))(e.builtInExtensions??{}),r=(({flushSnapshot:e,image:t})=>{const n=[{id:"canvas-kit.clipboard",services:[{token:hb,create(){let e=null;return{async write(t){e=t},read:async()=>e,getMemoryPayload:()=>e}}}],initializeRuntime({editor:e,pluginHostRuntime:t,services:n}){(({editor:e,pluginHostRuntime:t,services:n})=>{for(const i of(e=>[{id:pb,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!mp(e),run({context:t}){Sp({context:t,services:e})}},{id:gb,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!mp(e),run({context:t}){(async({context:e,services:t})=>{await Sp({context:e,services:t})&&e.editor.deleteSelection("user")})({context:t,services:e})}},{id:fb,isVisible:()=>!!mp(e)?.getMemoryPayload(),isEnabled:()=>!!mp(e)?.getMemoryPayload(),run({context:t}){yp({context:t,services:e})}},{id:mb,isVisible:t=>bp(t)&&!!mp(e)?.getMemoryPayload(),isEnabled:t=>bp(t)&&!!mp(e)?.getMemoryPayload(),run({context:t}){bp(t)&&yp({context:t,services:e,atMenuPoint:!0})}}])(n))t.toolbarRegistry.registerHostAction(i);if(e)for(const{actionId:i,shortcut:r}of Sb)e.shortcuts.registerActionShortcut(i,r)})({editor:e,pluginHostRuntime:t,services:n})}},{id:"canvas-kit.toolbar",initializeRuntime({editor:e,pluginHostRuntime:t}){for(const n of Ub)t.toolbarRegistry.registerAction(n);for(const{actionId:n,shortcut:i}of $b)e.shortcuts.registerActionShortcut(n,i);for(const n of zb)t.toolbarRegistry.registerContribution(n)}},{id:"canvas-kit.context-menu",initializeRuntime({pluginHostRuntime:e}){for(const t of Ib)e.toolbarRegistry.registerHostAction(t);for(const t of Hb)e.contextMenuRegistry.registerContribution(t)}}];return t&&n.push(Ap({flushSnapshot:e})),n})({flushSnapshot:zp(n),image:(o=i,o.some(e=>"image"===e.name))});var o;const s=(e=>e.flatMap(e=>e.assetResolverTokens??[]))(r),a=(e=>e.flatMap(e=>e.services??[]))(r),l=function({hostExtensions:e,seedDocument:t,warnOnPluginRegistrationConflicts:n}){return i=>{((e,t)=>{for(const n of e)n.initializeRuntime?.(t)})(e,i),n&&(({duplicateContextMenuContributionIds:e,duplicateCanvasActionIds:t,duplicateToolbarContributionIds:n,productId:i})=>{Lp({ids:t,kind:"toolbar-action",message:`[land] Duplicate canvas action ids for product ${i}. The later registrations were ignored.`,productId:i}),Lp({ids:n,kind:"toolbar-contribution",message:`[land] Duplicate toolbar contribution ids for product ${i}. The later registrations were ignored.`,productId:i}),Lp({ids:e,kind:"context-menu-contribution",message:`[land] Duplicate context menu contribution ids for product ${i}. The later registrations were ignored.`,productId:i})})({duplicateContextMenuContributionIds:i.pluginHostRuntime.contextMenuRegistry.getDuplicateContributionIds(),duplicateCanvasActionIds:i.pluginHostRuntime.toolbarRegistry.getDuplicateActionIds(),duplicateToolbarContributionIds:i.pluginHostRuntime.toolbarRegistry.getDuplicateContributionIds(),productId:i.productId}),t&&t(Tp(i))}}({hostExtensions:r,seedDocument:e.seedDocument,warnOnPluginRegistrationConflicts:e.warnOnPluginRegistrationConflicts??!1});return{[jb]:void 0,assetResolverTokens:s,canvasExtensions:i,id:e.id??"canvas-kit",config:t,hostExtensions:r,initializeRuntime:l,persistence:n,serviceFactories:a,shouldSkipStoredSnapshots:e.shouldSkipStoredSnapshots}}function zp(e){const t=e?.flushSnapshot;return t?e=>t(e):void 0}function Hp(e){const{config:t,assetResolverTokens:n,canvasExtensions:i,hostExtensions:r,id:o,initializeRuntime:s,persistence:a,serviceFactories:l,shouldSkipStoredSnapshots:d}=e,c=(({factories:e,productId:t})=>{const n=new Map,i=[],r=(e,t)=>{const r=n.get(e.token.id);if(r)return r;const o=e.create(t);return n.set(e.token.id,o),e.dispose&&i.push(()=>e.dispose?.(o)),o};for(const o of e)r(o,{productId:t});return{get:e=>n.get(e.id)??null,dispose(){for(const e of[...i].reverse())e();n.clear()}}})({factories:l,productId:o}),u=(()=>{const e=new Map;return{register(t,n){if(e.has(t.id))throw new Error(`Product feature controller already registered: ${t.id}`);e.set(t.id,n)},get:t=>e.get(t.id)??null}})(),h=((e,t={})=>{const n=t.knownHostActionIds??[],i=t.source??"built-in",r=function(e){const t=[],n=new Set;let i=0;const r=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())r(t);n.delete(e)};for(const s of e)r(s);const o=(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(o.length>0)throw new Error(`Duplicate Land extension names: ${o.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}]:[]),o=(e=>e.flatMap(({feature:e})=>e.editorPlugins))(r),s=(e=>e.flatMap(({feature:e})=>e.canvasPlugins))(r),a=(e=>e.flatMap(e=>[...e.canvasProviders??[]]))(s),l=(e=>e.flatMap(e=>[...e.canvasComponents??[]]))(s),d=r.map(ar),c=(e=>e.filter(({source:e})=>"built-in"!==e).flatMap(({feature:e})=>[...e.editorPlugins.map(e=>e.id),...e.canvasPlugins.map(e=>e.id)]))(r),u=ji(s);return{editorPlugins:o,canvasPlugins:s,canvasProviders:a,canvasComponents:l,rendererRegistry:u,overlayRegistry:Zi(s),domEventGuardRegistry:Ji(s),toolbarRegistry:er(o),contextMenuRegistry:tr(o),manifest:d,validation:lr({editorPlugins:o,canvasPlugins:s,knownHostActionIds:n,rendererRegistry:u,resolvedFeatures:r}),externalPluginIds:c}})(i,{knownHostActionIds:Db});let p=null;const g=function(e){const t=((e={})=>{const{editorPlugins:t=[],...n}=e,i={shapeUtils:(r=t).flatMap(e=>e.shapeUtils??[]),shapeSvgExporters:r.flatMap(e=>e.shapeSvgExporters??[]),bindingUtils:r.flatMap(e=>e.bindingUtils??[]),shapeCapabilities:r.flatMap(e=>e.shapeCapabilities??[])};var r;const o=new cf({...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)}})(o,t),o})({editorPlugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new Df(e),{shortcut:"v"}),t.tools.register("hand",e=>new gf(e),{shortcut:"h"}),t.tools.setToolLocked(t.isToolLocked()),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t}({editorPlugins:h.editorPlugins,resolveAssetUrl:e=>p?(({assetResolverTokens:e,assetId:t,editor:n,services:i})=>{for(const r of gp({assetResolverTokens:e,services:i})){const e=r.resolveAssetUrl(n,t);if(e)return e}return null})({assetResolverTokens:n,assetId:e,editor:p,services:c}):null});return p=g,s({productId:o,featureControllers:u,editor:g,pluginHostRuntime:h,services:c}),{assetResolverTokens:n,config:t,featureControllers:u,editor:g,hostExtensions:r,persistence:a,pluginHostRuntime:h,productId:o,services:c,shouldSkipStoredSnapshots:d}}function _p({product:e}){const t=(e=>{const t=e,[n,i]=Qp(null),r=n?.product===t?n.runtime:null;return Vp(()=>{const e=Hp(t);return i({product:t,runtime:e}),()=>{e.services.dispose()}},[t]),r})(e),[n,i]=Qp(null),[r,o]=Qp(!1),{isReady:s,persistence:a}=function(e){const[{readyRuntime:t,status:n},i]=Qp(qb),[r,o]=Qp(!1),s=!!e?.persistence?.restore&&!e.shouldSkipStoredSnapshots?.();Vp(()=>{if(!e)return void i(qb);const{assetResolverTokens:t,editor:n,persistence:r,services:o}=e;let a=!1,l=null;const d=()=>{a=!0,l?.()},c=(t,o)=>{a||(i({readyRuntime:e,status:t}),o&&(l=r?.start?.(n)??null))};return s?(i(qb),(async()=>{let e=null,i=!0;try{const s=await(r?.restore?.(n));i="disabled"!==s?.autoPersistence,e=s?.status??null,await(async({assetResolverTokens:e,editor:t,services:n})=>{await Promise.all(gp({assetResolverTokens:e,services:n}).map(e=>e.preloadForEditor?.(t)))})({assetResolverTokens:t,editor:n,services:o}),await(async({assetResolverTokens:e,editor:t,services:n})=>{await Promise.all(gp({assetResolverTokens:e,services:n}).map(e=>e.cleanupAfterRestore?.(t)))})({assetResolverTokens:t,editor:n,services:o})}catch(s){if(a)return;console.warn("Could not restore persisted canvas snapshot.",s)}c(e,i)})(),d):(c(null,!0),d)},[e,s]);const a=Xp(async()=>{if(e?.persistence?.discardUnsupportedRecords){o(!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{o(!1)}}},[e]);return{isReady:t===e,persistence:{discardUnsupportedRecords:n&&e?.persistence?.discardUnsupportedRecords?a:null,isDiscardingUnsupportedRecords:r,status:n}}}(t),l=Gp(()=>({isVisible:r,setIsVisible:o}),[r]);if(Vp(()=>{i(null)},[e]),!t)return null;const{editor:d,pluginHostRuntime:c}=t;
|
|
47
|
-
return
|
|
48
|
-
return
|
|
49
|
-
tg($p,{persistence:o})]}):null})})}import{Fragment as Op,createContext as Wp,memo as Yp,useCallback as Xp,useContext as Kp,useEffect as Vp,useEffectEvent as qp,useLayoutEffect as jp,useMemo as Gp,useRef as Zp,useState as Qp,useSyncExternalStore as Jp}from"react";import{Fragment as eg,jsx as tg,jsxs as ng}from"react/jsx-runtime";import{EditorContent as ig,useEditor as rg}from"@tiptap/react";import{Bold as og}from"@tiptap/extension-bold";import{Italic as sg}from"@tiptap/extension-italic";import{Strike as ag}from"@tiptap/extension-strike";import lg from"@tiptap/starter-kit";import{BubbleMenu as dg}from"@tiptap/react/menus";var cg=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ug=0,hg=null,pg=null,gg=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 r(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)=>{hg&&!hg.initialAtomValues.has(e)&&hg.initialAtomValues.set(e,t)})(this,i),t(),this.lastChangedEpoch=e(),this.current=n,(e=>{hg||o([e])})(this),n)}update(e){return this.set(e(this.current))}},fg=Symbol("UNINITIALIZED"),mg=class{name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch;children=new Set;state=fg;parents=[];parentEpochs=[];constructor(t,n,i){this.name=t,this.derive=n,this.isEqual=i,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!==fg&&!this.haveParentsChanged())return this.lastCheckedEpoch=e(),this.state;let r,o;n(this.selfAsChild);try{r=this.derive(this.state===fg?fg:this.state)}finally{o=i()}for(const e of this.parents)o.has(e)||e.children.delete(this.selfAsChild);this.parents=[...o],this.parentEpochs=this.parents.map(e=>e.lastChangedEpoch);for(const e of this.parents)e.children.add(this.selfAsChild);return this.state!==fg&&(this.isEqual?this.isEqual(this.state,r):Object.is(this.state,r))||(this.state=r,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}},Sg=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}},yg=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}},xg=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),r=i.len();return 0===r?e.clone():e.add(i.mul(n/r))}static RotWith(t,n,i){const r=t.x-n.x,o=t.y-n.y,s=Math.cos(i),a=Math.sin(i);return new e(n.x+r*s-o*a,n.y+r*a+o*s)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}},bg=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 xg(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,r=-1/0,o=-1/0;for(const e of t)n=Math.min(n,e.x),i=Math.min(i,e.y),r=Math.max(r,e.x),o=Math.max(o,e.y);return new e(n,i,r-n,o-i)}},Ig=class e{a;b;c;d;e;f;constructor(e,t,n,i,r,o){this.a=e,this.b=t,this.c=n,this.d=i,this.e=r,this.f=o}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 xg(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,r=1,o=1){const s=e.Translate(t,n),a=0===i?e.Identity():e.Rotate(i),l=1===r&&1===o?e.Identity():e.Scale(r,o);return s.compose(a).compose(l)}},vg="page:default",Pg="session:main",wg={x:0,y:0,z:1},kg=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}},Cg=["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"],Tg=Object.fromEntries(Cg.map(e=>[e,`--land-shape-${e}`])),Eg={"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"},Bg={"#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"},Mg=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()}},Ag=Symbol("editorStore"),Rg=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(_(e))if(this.marks.size>0)for(const[t,n]of this.marks.entries())this.marks.set(t,X(n,e));else this.undoStack.push(K("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),!_(t.forward))return null;const n=W(t.forward);for(const i of t.parentIds){const e=this.marks.get(i);e&&this.marks.set(i,X(e,n))}return n}squashToMark(e,t=e){const n=this.marks.get(e);if(!n)return null;if(this.marks.delete(e),!_(n.forward))return null;if(n.parentIds.some(e=>this.marks.has(e)))return null;const i=K(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})}},Lg=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(r){i=r}if(this.transactionDepth-=1,n){const e=this.recordsSignal.get(),t=this.draftRecords,n=this.pendingSource;this.draftRecords=null,this.pendingSource="system";const r=t?O(e,t):{added:[],updated:[],removed:[]};if(!i&&t&&_(r)){this.recordsSignal.set(t);const e={source:n,diff:r};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=O(this.recordsSignal.get(),n);if(!_(i))return;this.recordsSignal.set(n);const r={source:t,diff:i};for(const o of this.listeners)o(r)}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()}},Fg=class{editor;buffer=new Rg;state=this.buffer.state;constructor(e){this.editor=e,D(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&&(D(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&&(D(this.editor).applyDiff(e.inverse,"history"),this.editor.syncAfterDocumentRestore(),!0)}redo(){const e=this.buffer.redo();return!!e&&(D(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=f),updated:n.updated.filter(e=>i(e.before)&&i(e.after)),removed:n.removed.filter(i)};var n,i;_(t)&&"user"===e.source&&this.buffer.append(t)}},$g=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){D(this.editor).atomic(()=>{const t=new Set;for(const n of this.getAllBindings()){const i=this.editor.getShape(n.fromId),r=this.editor.getShape(n.toId);if(!i||!r){D(this.editor).remove([n.id],e);continue}if(!this.canBind(n)){D(this.editor).remove([n.id],e);continue}const o=this.getExclusiveBindingKey(n);if(o){if(t.has(o)){D(this.editor).remove([n.id],e);continue}t.add(o)}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 r=e.fromId===i.after.id?"from":"to",o=this.editor.getBindingUtil(e).onAfterShapeChange?.(this.editor,e,{before:i.before,after:i.after,role:r});this.applyEffect(o,t,e.id)}}cleanupBindingsForDeletedShapes(e,t){if(0===e.length)return;const n=new Set(e),i=new Set;for(const r of e){const e=this.editor.getShape(r);if(e)for(const o of this.getBindingsForShape(r)){if(i.has(o.id))continue;i.add(o.id);const s=o.fromId===r?"from":"to";if("to"===s&&n.has(o.fromId)){D(this.editor).remove([o.id],t);continue}const a=this.editor.getBindingUtil(o).onBeforeDeleteShape?.(this.editor,o,{shape:e,role:s});this.applyEffect(a,t,o.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&&D(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}]:[]});D(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),D(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&&D(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}},Ug=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]??wg}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(),r=this.getCamera(i),o={x:"number"==typeof e.x?e.x:r.x,y:"number"==typeof e.y?e.y:r.y,z:te("number"==typeof e.z?e.z:r.z)};this.editor.updateSession({pageCameraById:{...this.editor.sessionSignal.get().pageCameraById,[i]:o}},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=te(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=te(t),r=this.screenToPage(e);this.setCamera({x:r.x-e.x/i,y:r.y-e.y/i,z:i},{source:n})}zoomAtViewportCenter(e,t="system"){const n=this.viewportScreenSizeSignal.get(),i=new xg(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new xg(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)}},Dg=new xg(24,24),zg=class{editor;constructor(e){this.editor=e}createPayloadFromSelection(){return ge(this.editor)}pastePayload(e){return this.editor.cancelInteractionForCommand(),fe(this.editor,e)}duplicateSelection(e={}){return this.editor.cancelInteractionForCommand(),((e,t={})=>{const n=ge(e);return n?fe(e,{payload:n,offset:t.offset??Dg,source:t.source}):[]})(this.editor,e)}},Hg=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},_g=[],Ng=[],Og=class{editor;constructor(e){this.editor=e}buildInitialRecords(e,t){const n=this.parseInitialDocumentSnapshot(e),i=this.parseInitialSessionSnapshot(t);return[...n.records.length?n.records:[l()],i.records[0]??d()]}getDocumentSnapshot(){const e=this.editor.store.getAll();return{schemaVersion:1,records:[...this.editor.getPages(),...e.filter(g).sort((e,t)=>e.id.localeCompare(t.id)),...e.filter(u).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index):e.parentId.localeCompare(t.parentId)),...e.filter(p).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=Ue(e,this.editor.shapeUtils,this.editor.bindingUtils);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n});const r=this.editor.sessionSignal.get();D(this.editor).replaceAll([...i.records,r],n),this.syncAfterDocumentSnapshotLoad(n)}loadSessionSnapshot(e,t){const n=t?.source??"system",i=De(e).records[0]??d(),r=D(this.editor).getAll().filter(f);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),D(this.editor).replaceAll([...r,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=D(this.editor),t=e.getAll(),n=t.filter(c).sort((e,t)=>e.index.localeCompare(t.index)),i=n[0]?.id??"page:default",r=new Set(n.map(e=>e.id)),o=t.filter(u),s=new Set(o.map(e=>e.id)),a=new Map(o.map(e=>[e.id,e])),l=new Map;for(const d of o)l.set(d.id,de(d,a,r)??i);const p=t.find(e=>e.id===Pg),g=h(p)?p:d(i),f={...g,currentPageId:r.has(g.currentPageId)?g.currentPageId:i,pageCameraById:this.repairCameraByPage(g.pageCameraById,r),pageSelectedShapeIdsById:this.repairSelectionByPage(g.pageSelectedShapeIdsById,r,s,l)};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]??wg;n[i]={x:Number.isFinite(t.x)?t.x:wg.x,y:Number.isFinite(t.y)?t.y:wg.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:wg.z))}}return n}repairSelectionByPage(e,t,n,i){const r={};for(const o of t)r[o]=Array.from(new Set((e[o]??[]).filter(e=>n.has(e)&&i.get(e)===o)));return r}parseInitialDocumentSnapshot(e){if(!e)return{schemaVersion:1,records:[l()]};try{return Ue(e,this.editor.shapeUtils,this.editor.bindingUtils)}catch(t){if(!(t instanceof Hg))throw t;return{schemaVersion:1,records:[l()]}}}parseInitialSessionSnapshot(e){if(!e)return{schemaVersion:1,records:[d()]};try{return De(e)}catch(t){if(!(t instanceof Hg))throw t;return{schemaVersion:1,records:[d()]}}}},Wg=class{state=s("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:ze(),screenVelocity:ze(),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,r=t.currentTimestamp??e.timestamp,o=e.timestamp-r;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:r,currentTimestamp:e.timestamp,pageVelocity:He(n,e.pagePoint,o),screenVelocity:He(i,e.screenPoint,o),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:ze(),screenVelocity:ze(),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:ze(),screenVelocity:ze(),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&&_e(t,e))return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,r=t.isDragging||(t.originPagePoint??e.pagePoint).dist2(e.pagePoint)>=9,o=t.currentTimestamp??e.timestamp,s=e.timestamp-o;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:o,currentTimestamp:e.timestamp,pageVelocity:He(n,e.pagePoint,s),screenVelocity:He(i,e.screenPoint,s),buttons:e.buttons,isDragging:r,dragPhase:r?"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:ze(),screenVelocity:ze(),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=>_e(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=>_e(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},Yg=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){oe(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));ne(this._erasingShapeIdsSignal.get(),t)||this._erasingShapeIdsSignal.set(t)}clearErasingShapeIds(){this.setErasingShapeIds([])}getEraserTrail(){return this._eraserTrailSignal.get().map(e=>e.clone())}setEraserTrail(e){re(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&&re(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&&ie(t.rawPagePoint,n.rawPagePoint)&&ie(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],r=t[n];if(!i||!r||!Ye(i,r))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(Ne))}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)}},Xg=.001,Kg=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=D(this.editor);this.stateAtom=s("editor.query.state",(e=>{const t=e.filter(c).sort((e,t)=>e.index.localeCompare(t.index)),n=e.filter(u).sort((e,t)=>e.parentId===t.parentId?((e,t)=>e.index.localeCompare(t.index))(e,t):e.parentId.localeCompare(t.parentId)),i=e.filter(p).sort(rt),r=new Map,o=new Map,s=new Map,a=new Map(n.map(e=>[e.id,e])),l=new Map,d=new Map,h=new Map,g=new Map;for(const c of n)et(o,c.parentId,c.id);const f=(e,t)=>{for(const n of o.get(t)??[]){const t=a.get(n);t&&(et(r,e,t.id),s.set(t.id,e),f(e,t.id))}};for(const c of t)f(c.id,c.id);for(const c of i)l.set(c.id,c),tt(d,c.fromId,c.id),tt(h,c.toId,c.id),tt(g,c.fromId,c.id),tt(g,c.toId,c.id);return{pageShapeIdsByPage:r,childShapeIdsByParent:o,pageIdByShape:s,bindingById:l,bindingIdsByFromShape:d,bindingIdsByToShape:h,relatedBindingIdsByShape:g}})(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:it}),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",()=>gt(e,t),{isEqual:ht}),i=a("editor.query.selectionPageOutlineVertices",()=>n.get().outlineVertices,{isEqual:ut}),r=a("editor.query.selectionPageBounds",()=>n.get().pageBounds,{isEqual:oe}),o=a("editor.query.selectionFrameBounds",()=>n.get().frameBounds,{isEqual:oe}),s=a("editor.query.selectionRotation",()=>n.get().rotation);return{geometry:n,pageOutlineVertices:i,pageBounds:r,frameBounds:o,hasRotation:a("editor.query.selectionHasRotation",()=>n.get().hasRotation),rotation:s,rotationCenter:a("editor.query.selectionRotationCenter",()=>n.get().rotationCenter,{isEqual:ie}),hasCompatibleRotation:a("editor.query.selectionHasCompatibleRotation",()=>n.get().hasCompatibleRotation),selectionAnchorPagePoint:a("editor.query.selectionAnchorPagePoint",()=>n.get().selectionAnchorPagePoint,{isEqual:ie})}})(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 Pt(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 Pt(t)}getShapeContainment(e,t){const n=this.editor.getShape(e);if(!n)return null;const i=this.getShapeGeometrySnapshot(e),r=this.getShapeGeometrySnapshot(t);if(!i||!r)return null;const o=this.editor.getShapeUtil(n),s=o.getLocalBounds(n),a=o.getLocalToPageTransform(n).invert();return r.outlineVertices.length>0&&r.outlineVertices.every(e=>s.containsPoint(a.applyToPoint(e)))?"inside":i.bounds.intersects(r.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 r=new Set;for(const d of n){r.add(d.id);for(const e of this.getDescendantShapeIds(d.id))r.add(e)}let o=null,s=1/0,a=-1;const l=this.stateSignal.get().pageShapeIdsByPage.get(i)??[];for(let d=0;d<l.length;d+=1){const e=l[d];if(r.has(e))continue;const t=this.editor.getShape(e);if(!t)continue;if(!Ct(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;(!o||c<s||c===s&&d>a)&&(o=t,s=c,a=d)}return o?.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 r=this.getPageIdForShape(i[0].id);if(!r)return null;if(i.some(e=>this.getPageIdForShape(e.id)!==r))return null;const o=new Set;for(const c of i){o.add(c.id);for(const e of this.getDescendantShapeIds(c.id))o.add(e)}let s=null,a=1/0,l=-1;const d=this.stateSignal.get().pageShapeIdsByPage.get(r)??[];for(let c=0;c<d.length;c+=1){const e=d[c];if(o.has(e))continue;const n=this.editor.getShape(e);if(!n||this.editor.isShapeHidden(n.id))continue;const r=this.editor.getShapeUtil(n);if(!Ct(n,r))continue;if(!i.every(e=>this.editor.canUseShapeParent(n.id,e.id)))continue;if(!this.editor.isPagePointInShapeClip(n.id,t))continue;const u=r.getLocalBounds(n),h=r.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>l)&&(s=n,a=g,l=c)}return s?.id??r}getContainingParentIdForShapeRecord(e){const t=this.getPageIdForShapeParent(e.parentId);if(!t)return null;const n=Je(e,this.editor.getShapeUtil(e));let i=null,r=1/0,o=-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 l=this.editor.getShapeUtil(t);if(!Ct(t,l))continue;if(!this.editor.canUseShapeParent(t.id,e.id))continue;const d=this.getShapePageBounds(t.id);if(!d)continue;const c=l.getLocalBounds(t),u=l.getLocalToPageTransform(t).invert();if(!(n.outlineVertices.length>0&&n.outlineVertices.every(e=>c.containsPoint(u.applyToPoint(e)))))continue;const h=d.w*d.h;(!i||h<r||h===r&&a>o)&&(i=t,r=h,o=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||!wt(n))continue;const r=e.getLocalToPageTransform(i).invert().applyToPoint(t);if(!n.containsPoint(r))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=kt(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 r=e.parentId;for(;r.startsWith("shape:");){const e=r;if(i.has(e))break;i.add(e);const o=t(e);if(!o)break;const s=this.editor.getShapeUtil(o).getChildClipLocalBounds(o);s&&wt(s)&&n.push(o),r=o.parentId}return n.reverse()}getShapeChildClipPageBounds(e){const t=this.editor.getShapeUtil(e),n=t.getChildClipLocalBounds(e);return n&&wt(n)?(i=n,r=t.getLocalToPageTransform(e),bg.FromPoints([new xg(i.minX,i.minY),new xg(i.maxX,i.minY),new xg(i.maxX,i.maxY),new xg(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){for(const n of(e=>e.diff.removed.filter(u).map(e=>e.id))(e))this.shapeQuerySignals.delete(n);const t=D(this.editor);this.stateAtom.update(n=>((e,t,n)=>{const i=t.diff.added.filter(u),r=t.diff.updated.filter(dt),o=t.diff.removed.filter(u),s=t.diff.added.filter(p),a=t.diff.updated.filter(ct),l=t.diff.removed.filter(p),d=i.length>0||o.length>0||r.some(({before:e,after:t})=>e.parentId!==t.parentId||e.index!==t.index),h=s.length>0||l.length>0||a.some(({before:e,after:t})=>e.fromId!==t.fromId||e.toId!==t.toId),g=s.length>0||l.length>0||a.length>0;if(!d&&!g)return e;const f={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(d){const t=e=>{const t=n(e);return u(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(c(e))return e.id;if(!u(e))return null;t=e.parentId}return null};for(const n of o){lt(f.childShapeIdsByParent,n.parentId,n.id);const t=e.pageIdByShape.get(n.id);t&&s.add(t)}for(const{before:n,after:i}of r){if(n.parentId===i.parentId&&n.index===i.index)continue;lt(f.childShapeIdsByParent,n.parentId,n.id),at(f.childShapeIdsByParent,i.parentId,i,t);const r=e.pageIdByShape.get(n.id);r&&s.add(r);const o=a(i.parentId);o&&s.add(o)}for(const e of i)at(f.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,o]of e.pageIdByShape)s.has(o)&&i.delete(n);const r=(e,t)=>{const o=[];for(const s of f.childShapeIdsByParent.get(t)??[])n(s)&&(o.push(s),i.set(s,e),o.push(...r(e,s)));return o};for(const e of s){const n=r(e,e);n.length>0?t.set(e,n):t.delete(e)}f.pageShapeIdsByPage=t,f.pageIdByShape=i}m=!0}if(g){for(const e of l)m=f.bindingById.delete(e.id)||m;if(h){for(const e of l)m=nt(f.bindingIdsByFromShape,e.fromId,e.id)||m,m=nt(f.bindingIdsByToShape,e.toId,e.id)||m,m=nt(f.relatedBindingIdsByShape,e.fromId,e.id)||m,m=nt(f.relatedBindingIdsByShape,e.toId,e.id)||m;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(m=nt(f.bindingIdsByFromShape,e.fromId,e.id)||m,m=nt(f.bindingIdsByToShape,e.toId,e.id)||m,m=nt(f.relatedBindingIdsByShape,e.fromId,e.id)||m,m=nt(f.relatedBindingIdsByShape,e.toId,e.id)||m)}for(const e of s)f.bindingById.set(e.id,e),m=!0;for(const{after:e}of a)f.bindingById.set(e.id,e),m=!0;if(h){for(const e of s)m=st(f.bindingIdsByFromShape,e.fromId,e,"from",e=>f.bindingById.get(e))||m,m=st(f.bindingIdsByToShape,e.toId,e,"to",e=>f.bindingById.get(e))||m,m=st(f.relatedBindingIdsByShape,e.fromId,e,"related",e=>f.bindingById.get(e))||m,m=st(f.relatedBindingIdsByShape,e.toId,e,"related",e=>f.bindingById.get(e))||m;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(m=st(f.bindingIdsByFromShape,t.fromId,t,"from",e=>f.bindingById.get(e))||m,m=st(f.bindingIdsByToShape,t.toId,t,"to",e=>f.bindingById.get(e))||m,m=st(f.relatedBindingIdsByShape,t.fromId,t,"related",e=>f.bindingById.get(e))||m,m=st(f.relatedBindingIdsByShape,t.toId,t,"related",e=>f.bindingById.get(e))||m)}}return m?f: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:ft}),i=a(`editor.query.shapeGeometry.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return Je(t,this.editor.getShapeUtil(t))},{isEqual:xt});t={bounds:n,geometry:i,positionedToPageTransform:a(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return Ve(t,this.editor.getShapeUtil(t))},{isEqual:yt}),pageBounds:a(`editor.query.shapePageBounds.${e}`,()=>i.get()?.bounds,{isEqual:ft}),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:it})},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 Ig(t.a,t.b,t.c,t.d,t.e,t.f):void 0;var t}getShapePageBounds(e){return bt(this.getShapePageBoundsSignal(e).get())??void 0}getShapeBounds(e){return bt(this.getShapeQuerySignals(e).bounds.get())??void 0}getShapePageCenter(e){return It(this.getShapeGeometrySnapshot(e)?.center)??void 0}getShapePageCorners(e){return vt(this.getShapeGeometrySnapshot(e)?.corners)}getShapePageOutlineVertices(e){return vt(this.getShapeGeometrySnapshot(e)?.outlineVertices)}getSelectionPageOutlineVertices(){return vt(this.selectionPageOutlineVerticesSignal.get())??[]}getSelectionPageBounds(){return bt(this.selectionPageBoundsSignal.get())??null}getSelectionFrameBounds(){return bt(this.selectionFrameBoundsSignal.get())??null}getSelectionRotation(){return this.selectionRotationSignal.get()}getSelectionHasRotation(){return this.selectionHasRotationSignal.get()}getSelectionRotationCenter(){return It(this.selectionRotationCenterSignal.get())??null}getSelectionHasCompatibleRotation(){return this.selectionHasCompatibleRotationSignal.get()}getSelectionAnchorPagePoint(){return It(this.selectionAnchorPagePointSignal.get())??null}getBinding(e){return this.stateSignal.get().bindingById.get(e)}getBindings(){return Array.from(this.stateSignal.get().bindingById.values()).sort(rt)}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)}},Vg=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),r=Math.floor(e.queryBounds.maxY/this.cellSize);for(let o=n;o<=r;o+=1)for(let n=t;n<=i;n+=1){const t=this.cellKey(n,o),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),r=Math.floor(e.maxY/this.cellSize);if((i-t+1)*(r-n+1)>this.entries.length)return this.entries.filter(t=>t.queryBounds.intersects(e));const o=new Set,s=[];for(let a=n;a<=r;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)o.has(n)||(o.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}},qg=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 bg(e.x-.5,e.y-.5,1,1))(e)),i=[];for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(!o?.pointHitTestBounds.containsPoint(e))continue;const s=this.editor.getShape(o.shapeId);if(!s)continue;if(t?.filter&&!t.filter(s))continue;const a=this.editor.getShapeUtil(s),l=Ze(s,e,a),d={editor:this.editor,pagePoint:e,positionedPoint:l};("bindingTarget"===t?.hitTest?a.hitTestBindingTarget(s,l,d):a.hitTest(s,l,d))&&i.push(s)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,r=((e,t,n)=>bg.FromPoints([e,t]).expand(Math.max(.5,n)))(e,t,i),o=this.getPageIndex(n?.pageId).search(r),s=[];for(let a=o.length-1;a>=0;a-=1){const r=o[a];if(!r)continue;const l=this.queries.getShapeClippedPageBounds(r.shapeId);if(!l||!Et(e,t,l.expand(i)))continue;const d=this.editor.getShape(r.shapeId);if(!d)continue;if(n?.filter&&!n.filter(d))continue;const c=this.editor.getShapeUtil(d),u=Ze(d,e,c),h=Ze(d,t,c);c.hitTestLineSegment(d,{editor:this.editor,pageStart:e,pageEnd:t,positionedStart:u,positionedEnd:h,margin:i})&&s.push(d)}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),r=this.queries.getShapePageBoundsSignal(e).get();if(!r)continue;const o=Bt(i.getPointHitTestBounds(t,{editor:this.editor}),Ve(t,i)),s=bg.FromPoints([new xg(r.minX,r.minY),new xg(r.maxX,r.maxY),new xg(o.minX,o.minY),new xg(o.maxX,o.maxY)]);n.push({shapeId:e,shapeBounds:r,queryBounds:s,pointHitTestBounds:o})}return new Vg(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.getCurrentPageId()){return this.getPageIndexSignal(e).get()}},jg=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 r=this.editor.getShape(e.shapeId),o=new Set(this.editor.getShapeIdsIncludingDescendants([e.shapeId]));this.collectBindingDrivenExcludedShapeIds([e.shapeId],o);for(const c of i)o.add(c);const s=[],a=[],l=this.getSnapScopeParentId([e.shapeId]),d=this.getCandidateShapeIds({excludedShapeIds:o,scopeParentId:l});r&&n&&this.collectSelfHandleSnapGeometry({shape:r,context:e,currentPagePoint:t,points:s,outlines:a});for(const c of d){const e=this.editor.getShape(c);e&&this.collectHandleSnapGeometry({shape:e,points:s,outlines:a})}return{points:s,outlines:a,scopeParentId:l,candidateShapeIds:d}}collectHandleSnapGeometry({shape:e,points:t,outlines:n}){const i=this.editor.getShapeUtil(e);if(!i.canSnap(e))return;const r=this.editor.getShapeClippedPageBounds(e.id);if(!r)return;const o=this.editor.computeShapeLocalToPageTransform(e),s=i.getHandleSnapGeometry(e);for(const c of s.points??[]){const n=o.applyToPoint(c);this.editor.isPagePointInShapeClip(e.id,n)&&t.push({id:`${e.id}:point:${t.length}`,nodeId:e.id,point:n})}const a=s.outline;if(null===a)return;const l=this.editor.getShapeClipAncestorIds(e.id).length>0?jt(r):(a??(d=i.getLocalBounds(e),[new xg(d.minX,d.minY),new xg(d.maxX,d.minY),new xg(d.maxX,d.maxY),new xg(d.minX,d.maxY)])).map(e=>o.applyToPoint(e));var d;l.length>0&&n.push({id:e.id,points:l})}collectSelfHandleSnapGeometry({shape:e,context:t,currentPagePoint:n,points:i,outlines:r}){const o=this.editor.getShapeUtil(e);if(!o.canSnap(e))return;const s=this.editor.getShapeClippedPageBounds(e.id);if(!s)return;const a=o.getHandleSnapGeometry(e),l=this.editor.computeShapeLocalToPageTransform(e),d={...t,currentPagePoint:n.clone()};for(const h of a.getSelfSnapPoints?.(d)??[]){const t=l.applyToPoint(h);this.editor.isPagePointInShapeClip(e.id,t)&&i.push({id:`${e.id}:self-point:${i.length}`,nodeId:e.id,point:t})}const c=a.getSelfSnapOutline?.(d)??null;if(!c)return;const u=this.editor.getShapeClipAncestorIds(e.id).length>0?jt(s):c.map(e=>l.applyToPoint(e));u.length>0&&r.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 r=[],o=[],s={rotation:t.rotation,rotationCenter:t.rotationCenter},a=this.getSnapScopeParentId(n),l=this.getCandidateShapeIds({excludedShapeIds:i,scopeParentId:a});for(const d of l){const e=this.editor.getShape(d);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?jt(i):this.editor.getShapePageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():bn(e,s));if(0===a.length)continue;const l=bg.FromPoints(a);o.push({id:e.id,bounds:l});const c=n.getBoundsSnapGeometry(e).points;(void 0===c?_t(l):c.map(t=>{const n=this.editor.computeShapeLocalToPageTransform(e).applyToPoint(t);return this.editor.isPagePointInShapeClip(e.id,n)?n:null}).filter(e=>null!==e).map(e=>0===t.rotation?e:bn(e,s))).forEach((t,n)=>{r.push({id:`${e.id}:${n}`,nodeId:e.id,point:t})})}return{points:r,nodes:o,coordinateSpace:{rotation:t.rotation,rotationCenter:t.rotationCenter.clone()},scopeParentId:a,candidateShapeIds:l}}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 r=this.editor.getShape(e);if(r)for(const n of this.editor.getBindingsForShape(e)){const o=n.fromId===e?"from":n.toId===e?"to":null;if(!o)continue;const s=this.editor.getBindingUtil(n).getGeometryDependentShapeIds?.(this.editor,n,{shape:r,role:o})??[];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(),r=new Set;t?.startsWith("shape:")&&r.add(t);const o=t??n;for(const s of this.editor.getChildShapeIds(o))r.add(s);return(null===i?Array.from(r):this.editor.getShapeIdsInBounds(i,{pageId:n}).filter(e=>r.has(e))).filter(n=>{if(e.has(n))return!1;const r=this.editor.getShape(n);if(!r||r.parentId!==o)return n===t;const s=this.editor.getShapeClippedPageBounds(n);return!!s&&(!i||s.intersects(i))})}},Gg=class{gapCache=new WeakMap;_indicatorsSignal=s("editor.snapIndicators",[]);indicatorsSignal=this._indicatorsSignal;activeSignal=a("editor.snapIndicatorsActive",()=>this._indicatorsSignal.get().length>0);snapshots;constructor(e){this.snapshots=new jg(e)}setIndicators(e){const t=e.map(xn);an(this._indicatorsSignal.get(),t)||this._indicatorsSignal.set(t)}clearIndicators(){this._indicatorsSignal.get().length>0&&this._indicatorsSignal.set([])}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=this.snapshots.createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t});return this.gapCache.set(n,{x:nn(n.nodes,"x"),y:nn(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=Vt(e.initialSelectionBounds,e.dragDelta),n=(i=_t(e.initialSelectionBounds),r=e.dragDelta,i.map(e=>e.add(r)));var i,r;const o=this.gapCache.get(e.snapshot)??{x:nn(e.snapshot.nodes,"x"),y:nn(e.snapshot.nodes,"y")},s="y"===e.lockedAxis?null:sn(en("x",n,e.snapshot.points,e.threshold),on("x",t,o.x,e.threshold)),a="x"===e.lockedAxis?null:sn(en("y",n,e.snapshot.points,e.threshold),on("y",t,o.y,e.threshold)),l=new xg(s?.nudge??0,a?.nudge??0),d=[];return"points"===s?.type?d.push(...cn("x",s,l,e.snapshot.coordinateSpace)):"gaps"===s?.type&&d.push(yn(s,e.snapshot.coordinateSpace,l)),"points"===a?.type?d.push(...cn("y",a,l,e.snapshot.coordinateSpace)):"gaps"===a?.type&&d.push(yn(a,e.snapshot.coordinateSpace,l)),this.setIndicators(d),{nudge:l,indicators:d}}snapResize(e){const t=$t({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),n=tn(t,e.resizedSelectionBounds),i="left"===t||"right"===t,r="top"===t||"bottom"===t?null:en("x",n,e.snapshot.points,e.threshold),o=i?null:en("y",n,e.snapshot.points,e.threshold),s={x:null!==r,y:null!==o},a=new xg(r?.nudge??0,o?.nudge??0);if(e.isAspectRatioLocked&&Ft(t)&&(0!==a.x||0!==a.y)){const n=r&&o?Math.abs(a.x)<Math.abs(a.y)?"x":"y":r?"x":"y",i=0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h;"x"===n?(s.y=!1,a.y=a.x/i,"bottom_left"!==t&&"top_right"!==t||(a.y=-a.y)):(s.x=!1,a.x=a.y*i,"bottom_left"!==t&&"top_right"!==t||(a.x=-a.x))}const l=function(e,t){const n=$t({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY});let i=e.resizedSelectionBounds.minX,r=e.resizedSelectionBounds.maxX,o=e.resizedSelectionBounds.minY,s=e.resizedSelectionBounds.maxY;e.isResizingFromCenter?(Mt(n)?(i+=t.x,r-=t.x):At(n)&&(i-=t.x,r+=t.x),Rt(n)?(o+=t.y,s-=t.y):Lt(n)&&(o-=t.y,s+=t.y)):(Mt(n)?i+=t.x:At(n)&&(r+=t.x),Rt(n)?o+=t.y:Lt(n)&&(s+=t.y));const a=(({minX:e,minY:t,maxX:n,maxY:i})=>{const r=Math.min(e,n),o=Math.min(t,i),s=Math.max(e,n),a=Math.max(t,i);return new bg(r,o,Math.max(1,s-r),Math.max(1,a-o))})({minX:i,minY:o,maxX:r,maxY:s});if(!e.isAspectRatioLocked){const t=(({startBounds:e,bounds:t,handleId:n,scaleX:i,scaleY:r,isResizingFromCenter:o=!1})=>{const s=Ut({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:o}),a=Ut({axis:"y",startBounds:e,bounds:t,handleId:n,scale:r,isResizingFromCenter:o});return{scaleX:Mt(n)||At(n)?s*(t.w/Math.max(1,e.w)):i??1,scaleY:Rt(n)||Lt(n)?a*(t.h/Math.max(1,e.h)):r??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 zt({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,a),{bounds:d}=l,c=tn("any",d),u=[];if(s.x){const t=en("x",c,e.snapshot.points,1e-8);t&&u.push(...fn("x",t,xg.Zero(),e.snapshot.coordinateSpace,d,e.snapshot.nodes))}if(s.y){const t=en("y",c,e.snapshot.points,1e-8);t&&u.push(...fn("y",t,xg.Zero(),e.snapshot.coordinateSpace,d,e.snapshot.nodes))}return this.setIndicators(u),{nudge:a,bounds:d,scaleX:l.scaleX,scaleY:l.scaleY,indicators:u}}snapHandle(e){if("none"===e.mode)return this.clearIndicators(),null;const t="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return t?(this.setIndicators(t.indicators),t):(this.clearIndicators(),null)}snapHandlePoint(e){let t=null,n=e.threshold*e.threshold;for(const r of e.snapshot.points){const i=e.pagePoint.dist2(r.point);i>n||(n=i,t=r.point)}if(!t)for(const r of e.snapshot.outlines){const i=Qt(e.pagePoint,r.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:[mn(i)]}}snapHandleAlign(e){let t=null,n=null,i=e.threshold,r=e.threshold;for(const l of e.snapshot.points){const o=Math.abs(l.point.x-e.pagePoint.x);o<=i&&(i=o,t=l.point);const s=Math.abs(l.point.y-e.pagePoint.y);s<=r&&(r=s,n=l.point)}if(!t&&!n)return null;const o=new xg(t?t.x-e.pagePoint.x:0,n?n.y-e.pagePoint.y:0),s=e.pagePoint.add(o),a=[];return t&&a.push(Sn("x",s,t)),n&&a.push(Sn("y",s,n)),{snappedPagePoint:s,nudge:o,indicators:a}}},Zg=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 r=i.indexOf(n);r>=0&&i.splice(r,1)}}},Qg=class{editor;constructor(e){this.editor=e}align(e,t="user"){const n=this.getAlignableEntries();if(n.length<2)return!1;const i=bg.FromPoints(n.flatMap(e=>[new xg(e.bounds.minX,e.bounds.minY),new xg(e.bounds.maxX,e.bounds.maxY)])),r=n.map(({shape:t,bounds:n})=>{let r=0,o=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":o=i.minY-n.minY;break;case"bottom":o=i.maxY-n.maxY;break;case"vertical-center":o=i.center.y-n.center.y}return{id:t.id,x:t.x+r,y:t.y+o}});return this.editor.commands.updateShapes(r,{source:t}),!0}distribute(e,t="user"){const n=this.getAlignableEntries();if(n.length<3)return!1;const i="horizontal"===e,r=e=>i?e.w:e.h,o=e=>i?e.minX:e.minY,s=i?"x":"y",a=[...n].sort((e,t)=>e.bounds.center[s]-t.bounds.center[s]),l=a[0].bounds,d=a[a.length-1].bounds,c=((i?d.maxX:d.maxY)-o(l)-a.reduce((e,t)=>e+r(t.bounds),0))/(a.length-1);let u=o(l);const h=a.map(({shape:e,bounds:t},n)=>{const s=0===n||n===a.length-1?o(t):u,l=s-o(t);return u=s+r(t)+c,i?{id:e.id,x:e.x+l}:{id:e.id,y:e.y+l}});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||!se(e))return!1;if(e.w<=0&&e.h<=0)return!1;const i=t?.padding??64,r=Math.max(1,n.w-2*i),o=Math.max(1,n.h-2*i),s=te(Math.min(e.w>0?r/e.w:1/0,e.h>0?o/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&&se(e)&&t.push(new xg(e.minX,e.minY),new xg(e.maxX,e.maxY))}if(0===t.length)return null;const n=bg.FromPoints(t);return se(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 r=this.editor.getShapePageBounds(n);r&&se(r)&&t.push({shape:i,bounds:r})}return t}},Jg=class{editor;constructor(e){this.editor=e}setSelectedShapeIds(e,t){const n=this.editor,i=t?.pageId??n.getCurrentPageId(),r=t?.source??"user",o=((e,t)=>{const n=new Set(t);return t.filter(t=>{const i=e.getShape(t);if(!i)return!1;let r=i.parentId;const o=new Set([t]);for(;r.startsWith("shape:");){const t=r;if(o.has(t))return!0;if(n.has(t))return!1;o.add(t);const i=e.getShape(t);if(!i)return!0;r=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(r)||ne(a,o)||(n.setBindingPreview(null),n.setSnapIndicators(null),n.updateSession({pageSelectedShapeIdsById:{...s.pageSelectedShapeIdsById,[i]:o}},r))}removeShapeIdsFromSelection(e,t="system"){if(0===e.length)return;const n=this.editor,i=new Set(e),r=n.sessionSignal.get(),o={};for(const s of n.getPages())o[s.id]=(r.pageSelectedShapeIdsById[s.id]??[]).filter(e=>!i.has(e));n.updateSession({pageSelectedShapeIdsById:o},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})}},ef=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(jn(t))return null;const n=e.getSelectionFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:An}),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:Rn}),this.pathSignal=a("editor.selectionOverlayPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return jn(t)?t[0]?.path??null:null}),this.bindingSegmentsSignal=a("editor.selectionOverlayBindingSegments",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return jn(t)?[...t[0]?.bindingSegments??[]]:[]},{isEqual:We}),this.frameStyleSignal=a("editor.selectionOverlayFrameStyle",()=>{const t=e.cameraZoomSignal.get();return{strokeWidth:2/t,cornerRadius:3/t}},{isEqual:Ln}),this.frameSignal=a("editor.selectionOverlayFrame",()=>{const e=this.frameGeometrySignal.get();if(!e)return null;const t=this.frameStyleSignal.get();return{...e,...t}},{isEqual:Mn}),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(),r=1===t.length;return Gn(t,n,i,t=>e.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:r,editor:e}),t=>e.getShapeUtil(t).canUseSelectionFrameHandles(t,{editor:e}))},{isEqual:Vn}),this.handlesSignal=a("editor.selectionOverlayHandles",()=>{const t=this.handleAnchorsSignal.get();if(!t)return null;const n=e.cameraZoomSignal.get(),{resizeHandles:i,rotateHandles:r,terminalHandles:o,middleHandles:s,customHandles:a}=Zn(t,n);return{resizeHandles:i,rotateHandles:r,terminalHandles:o,middleHandles:s,customHandles:a,strokeWidth:2/n}},{isEqual:Kn}),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:qn}),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(),r=t!==fg?t:null,o=!r||!Mn(r.frame,n),s=!r||!qn(r.handleCounts,i);return{metrics:{selectionFrameActive:null!==n,selectionHandlesActive:null!==i,bindingPreviewActive:e.bindingPreviewActiveSignal.get(),brushBoxActive:e.brushBoxActiveSignal.get(),selectionFrameChangeCount:(r?.metrics.selectionFrameChangeCount??0)+(o?1:0),selectionHandlesChangeCount:(r?.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)=>le(e.metrics,t.metrics)}),this.debugStateSignal=a("editor.overlayDebugState.public",()=>this.debugStateSnapshotSignal.get().metrics,{isEqual:le})}},tf=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 r={...i,entryMode:e.entryMode??i.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:i.caretPagePoint};return this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:r},t),this.publishEntryRequest({shapeId:n.id,entryMode:r.entryMode,caretPagePoint:r.caretPagePoint}),r}e.preserveInteraction||this.editor.cancelInteractionForCommand(),this.end({runEditEnd:!0,source:t});const r=e.markId??`editing:${n.id}`;e.reuseExistingMark||this.editor.history.mark(r);const o={shapeId:n.id,markId:r,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:o},t),this.publishEntryRequest({shapeId:n.id,entryMode:o.entryMode,caretPagePoint:o.caretPagePoint}),o}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);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})}},nf=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 Xe(e,this.editor.getShapeUtil(e))}computeShapeLocalToPageTransform(e){return Ke(e,this.editor.getShapeUtil(e))}computeShapeRenderToPageTransform(e){return((e,t)=>Ke(e,t))(e,this.editor.getShapeUtil(e))}computeShapeExportToPageTransform(e){return qe(e,this.editor.getShapeUtil(e))}computeShapePageBounds(e){return((e,t)=>bg.FromPoints(Qe(e,t)))(e,this.editor.getShapeUtil(e))}computeShapeExportPageBounds(e){return((e,t)=>{const n=Xe(e,t),i=qe(e,t);return bg.FromPoints([new xg(n.minX,n.minY),new xg(n.maxX,n.minY),new xg(n.maxX,n.maxY),new xg(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))})(e,this.editor.getShapeUtil(e))}computeShapeGeometry(e){return Je(e,this.editor.getShapeUtil(e))}computeShapePositionedToPageTransform(e){return Ve(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()}},rf=class{editor;constructor(e){this.editor=e}get store(){return D(this.editor)}getSelectionParentOrderState(){return Qn(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),r=new Set(t.map(e=>e.id)),o=i.filter(e=>r.has(e.id)).map(e=>e.id);if(o.length!==t.length)return null;const s=e.getSelectionPageBounds();return s&&se(s)?{parentId:n,shapeIds:o,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 r=i[0]?.parentId;if(!r)return null;if(i.some(e=>e.parentId!==r))return null;const o=t.getChildShapes(r),s=new Set(n),a=o.filter(e=>s.has(e.id)).map(e=>e.id);if(a.length!==n.length)return null;const l=a.map(e=>t.getShapePageBounds(e)).filter(e=>!!e).flatMap(e=>[new xg(e.minX,e.minY),new xg(e.maxX,e.minY),new xg(e.maxX,e.maxY),new xg(e.minX,e.maxY)]),d=l.length>0?bg.FromPoints(l):null;return d&&se(d)?{parentId:r,shapeIds:a,bounds:d}:null}groupShapesFromState(e,t){const n=this.editor,i=n.getChildShapes(e.parentId),r=new Set(e.shapeIds),o=i.findIndex(e=>r.has(e.id));if(o<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(o+1),props:{w:e.bounds.w,h:e.bounds.h}}],{source:t});if(!a)return;s.push(a);const l=[];let d=!1;for(const e of i)r.has(e.id)?d||(l.push(a),d=!0):l.push(e);const c=e.shapeIds.map(e=>n.getShape(e)).filter(e=>!!e);n.commands.updateShapes([...l.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 r=e.map(e=>n.getShape(e)).filter(e=>!!e);n.cancelInteractionForCommand();const o=[],s=new Set;return this.store.atomic(()=>{const e=[],a=[];for(const t of r){if(!i.has(t.id)){s.has(t.id)||(s.add(t.id),o.push(t.id));continue}const r=n.getShape(t.id);if(!r)continue;const l=n.getChildShapes(r.id),d=n.getChildShapes(r.parentId),c=new Set(l.map(e=>e.id)),u=[];let h=!1;for(const e of d)e.id!==r.id?c.has(e.id)||u.push(e):(u.push(...l),h=!0);h||u.push(...l),e.push(...u.map((e,t)=>({id:e.id,parentId:c.has(e.id)?r.parentId:e.parentId,index:n.createShapeIndex(t+1)})));for(const e of l)s.has(e.id)||(s.add(e.id),o.push(e.id));a.push(r.id)}e.length>0&&n.commands.updateShapes(e,{source:t}),this.removeUngroupedContainerShapes(a,t)},t),o.length>0&&n.commands.setSelectedShapeIds(o,{source:t}),o}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 Jn(this.editor)}canMoveSelectionWithinParent(e){return((e,t)=>{const n=Jn(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveSelectionInParentOrder(e){return((e,t)=>{const n=Qn(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveShapesInParentOrder(e,t){return((e,t,n)=>{const i=ei(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this.editor,e,t)}moveShapesInParentOrder(e,t,n="user"){return ti(this.editor,e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return ni(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[r]=i;if(!r||r.isLocked)return!1;const o=Jn(e);if(!o)return!1;const s=e.getChildShapes(o.parentId),a=o.index;if(s[a]?.id!==r.id)return!1;const l="backward"===t?a-1:a+1;if(l<0||l>=s.length)return!1;const d=[...s],[c]=d.splice(a,1);return!!c&&(d.splice(l,0,c),e.cancelInteractionForCommand(),e.commands.updateShapes(d.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 r=i.map(t=>e.getShape(t)).filter(e=>!!e);return r.length===i.length&&!r.some(t=>t.isLocked||e.isShapeHidden(t.id))&&!i.some(n=>!ii(e,t.parentId,n))&&ri(e,t,i,r,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 r=i.map(t=>e.getShape(t)).filter(e=>!!e);if(r.length!==i.length)return{ok:!1,reason:"notFound"};for(const o of r){if(o.isLocked)return{ok:!1,reason:"locked"};if(e.isShapeHidden(o.id))return{ok:!1,reason:"hidden"}}for(const o 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===o||e.getDescendantShapeIds(o).includes(t.id))return{ok:!1,reason:"cycle"};if(!e.getShapeUtil(t).canReceiveChildren(t))return{ok:!1,reason:"invalidParent"}}}return ri(e,t,i,r,n)?{ok:!0,movedIds:i}:{ok:!1,reason:"invalidBeforeId"}})(this.editor,e,t)}moveSelectionInParentOrder(e,t="user"){return((e,t,n="user")=>ti(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}moveSelectionToParentOrderEdge(e,t="user"){return((e,t,n="user")=>ni(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 r=new Set([e]);for(;i?.parentId.startsWith("shape:");){const e=i.parentId;if(r.has(e))break;r.add(e);const o=t.getShape(e);if(!o)break;t.getShapeUtil(o).isTransformDescendantContainer(o)&&(n=o.id),i=o}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 r of n)for(const e of t.getBindingsForShape(r)){const r=t.getBindingUtil(e).getExportShapeIds?.(t,e);for(const e of r??[])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),r=n.getShapePageBounds(e);return i&&r?n.getShapeIdsInBounds(r,{pageId:i}).filter(i=>{if(i===e)return!1;const r=n.getShapeContainment(e,i);return"inside"===r||t.includeIntersecting&&"intersecting"===r}):[]}canUseShapeParent(e,t){return ii(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=[],r=new Set;for(const o of e){const e=n.getShape(o);if(!e||r.has(e.id)||e.isLocked)continue;const s=t(e);if((!s||!this.hasLockedDescendant(e.id))&&(r.add(e.id),i.push(e.id),s))for(const t of n.getDescendantShapeIds(e.id)){if(r.has(t))continue;const e=n.getShape(t);e&&!e.isLocked&&(r.add(e.id),i.push(e.id))}}return i}},of=class{bindings=new Map;bindingIds=[];register(e){const t=this.bindingIds.indexOf(e.id);t>=0&&this.bindingIds.splice(t,1);const n=oi(e.shortcut);this.bindingIds.push(e.id),this.bindings.set(e.id,{id:e.id,shortcut:n,target:e.target,label:e.label??si(n)})}registerActionShortcut(e,t){this.register({id:`action:${e}`,shortcut:t,target:{type:"action",actionId:e}})}registerEditorShortcut(e,t){const n=oi(t);this.register({id:`editor:${e}:${di(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&&ai(n.shortcut,e))return n}return null}getBindingLabel(e){return this.bindings.get(e)?.label}},sf=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:ne}),this.retainedBaseShapeWindowSnapshotSignal=a("editor.retainedBaseShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),r=fi(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(t!==fg&&t&&t.viewportReady&&r.length>0){const e=((e,t)=>{if(e.length!==t.length||0===t.length)return null;const n=t.map((n,i)=>{const r=e[i];if(!r)return null;if(r.end+2<n.start||r.start>n.end+2)return null;const o=i>0?t[i-1]:null,s=i<t.length-1?t[i+1]:null,a=s?s.start-3:1/0,l={start:Math.min(n.start,Math.max(o?o.end+3:-1/0,r.start)),end:Math.max(n.end,Math.min(a,r.end))};return l.end-l.start>n.end-n.start+4?null:l});if(n.some(e=>null===e))return null;const i=n;if(hi(i).length!==t.length)return null;const r=gi(t);return gi(i)>r+12?null:i})(hi(t.ranges.map(e=>({...e}))),r);if(e)return Si(n,e,{viewportReady:i})}return Si(n,r,{viewportReady:i})},{isEqual:(e,t)=>ne(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=a("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:ue}),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:ne}),this.selectedShapeIdsOutsideCulledSetSignal=a("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:ue}),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:ne}),this.retainedShapeWindowSnapshotSignal=a("editor.retainedShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),r=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,o=(s=r.length)<=0?0:ci(Math.ceil(.5*s),12,96);var s;const a=((e,t,n,i)=>{if(0===e.length)return[];const r=new Map;for(const[a,l]of e.entries())r.set(l,a);const o=hi(t.map(e=>r.get(e)).filter(e=>void 0!==e).sort((e,t)=>e-t).map(e=>({start:e,end:e+1})),2),s=[];if(o.length>0){const t=ci(Math.ceil(i/(2*o.length)),8,32);for(const[n,i]of o.entries()){const r=n>0?o[n-1]:null,a=n<o.length-1?o[n+1]:null,l=a?a.start-i.end:1/0,d=pi(r?i.start-r.end:1/0,t),c=pi(l,t+4);s.push({start:Math.max(0,i.start-d),end:Math.min(e.length,i.end+c)})}}for(const a of n){const e=r.get(a);void 0!==e&&s.push({start:e,end:e+1})}return 0===s.length?[]:hi(s,2)})(n,r,this.selectedShapeIdsOutsideCulledSetSignal.get(),o);if(i&&t!==fg&&t&&t.viewportReady&&t.ranges.length>0&&a.length>0){const e=hi(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 Si(n,e,{viewportReady:i});const r=((e,t,n)=>{const i=t.map((n,i)=>{const r={...n};for(const t of e)t.end+6<n.start||t.start>n.end+6||(r.start=Math.min(r.start,t.start),r.end=Math.max(r.end,t.end));const o=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(o?o.end+3:-1/0,r.start)),end:Math.max(n.end,Math.min(a,r.end))}});if(hi(i).length!==t.length)return null;const r=gi(t);return gi(i)>r+n?null:i})(e,a,o);if(r)return Si(n,r,{viewportReady:i})}return Si(n,a,{viewportReady:i})},{isEqual:(e,t)=>ne(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=a("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:ne}),this.renderVisibleShapeIdSetSignal=a("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:ue}),this.renderItemsSignal=a("editor.renderItems",()=>{const t=e.selectedShapeIdSetSignal.get(),n=[];for(const i of this.renderVisibleShapeIdsSignal.get()){const r=e.getShapeSignal(i).get(),o=e.queries.getShapePageBoundsSignal(i).get();r&&!r.isHidden&&o&&n.push({id:r.id,shape:r,bounds:o,isSelected:t.has(r.id)})}return n},{isEqual:ce}),this.renderHostDebugStateSnapshotSignal=a("editor.renderHostDebugState.snapshot",t=>{const n=this.culledShapeIdsSignal.get(),i=this.renderVisibleShapeIdsSignal.get(),r=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,o=this.retainedShapeIdsSignal.get(),s=this.selectedShapeIdsOutsideCulledSignal.get(),a=this.getPageIndexById(e.currentPageShapeIdsSignal.get()),l=fi(n,a),d=fi(o,a),c=fi(r,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 r=0,o=0;for(const s of i)n.has(s)||(r+=1);for(const s of n)i.has(s)||(o+=1);return{changed:r+o,added:r,removed:o}})(t===fg?[]:t.retainedShapeIds,o);return{metrics:{culledCount:n.length,visibleCount:i.length,retainedCount:o.length,retainedBaseCount:r.length,culledRangeCount:l.length,culledRangeSpan:gi(l),culledRangesSummary:ui(l),retainedBaseRangeCount:c.length,retainedBaseRangeSpan:gi(c),retainedBaseRangesSummary:ui(c),retainedRangeCount:d.length,retainedRangeSpan:gi(d),retainedRangesSummary:ui(d),retainedChangeCount:u.changed,retainedAddedCount:u.added,retainedRemovedCount:u.removed,selectedOutsideCulledCount:s.length},retainedShapeIds:o.slice()}},{isEqual:(e,t)=>ae(e.metrics,t.metrics)}),this.renderHostDebugStateSignal=a("editor.renderHostDebugState.public",()=>this.renderHostDebugStateSnapshotSignal.get().metrics,{isEqual:ae})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},af=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}},lf=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}},df=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}},cf=class{store;[Ag];inputs=new Wg;snapshots=new Og(this);clipboard=new zg(this);shortcuts=new of;tools=new af(this);camera=new Ug(this);selection=new Jg(this);selectionLayout=new Qg(this);editing=new tf(this);geometry=new nf(this);hierarchy=new rf(this);shapeUtils=new kg;shapeSvgExporters=new Mg;bindingUtils=new yg;interactions=new lf;selectionHandleInteractions=new df(this.interactions);queries;bindings;spatialIndex;snaps;renderWindow;selectionOverlay;transients=new Yg(this);history;sideEffects=new Zg;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 D(this)}sessionSignal=a("editor.session",()=>{const e=this._internalStore.getRecordSignal(Pg).get();if(!h(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(c).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()]??wg);selectedShapeIdsSignal=a("editor.selectedShapeIds",()=>{const e=this.sessionSignal.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:ne});selectionCountSignal=a("editor.selectionCount",()=>this.selectedShapeIdsSignal.get().length);selectedShapeIdSetSignal=a("editor.selectedShapeIdSet",()=>new Set(this.selectedShapeIdsSignal.get()),{isEqual:ue});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:Bn});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),r=1===n.length,o=n.map(e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:r,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=o&&s,l=t?this.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:r,editor:this}):null,d=1===e.length&&!!l&&(l.terminalHandleAnchors.length>0||(l.customHandleAnchors?.length??0)>0),c=this.queries.selectionHasRotationSignal.get();return{count:e.length,singleShapeType:t?.type??null,commonShapeType:i,hasPointHandleSelection:o,hasFrameSelection:s,isMixedFrameAndPointHandleSelection:a,canDragPointHandles:d,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 Ig.Scale(e.z,e.z).compose(Ig.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 bg(n.x,n.y,e/n.z,t/n.z)});renderViewportPageBoundsSignal=a("editor.renderViewportPageBounds",e=>{const t=this.viewportPageBoundsSignal.get();return t?e!==fg&&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:oe});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 Lg(this.snapshots.buildInitialRecords(e.documentSnapshot??null,e.sessionSnapshot??null));var n;((e,t)=>{e[Ag]=t})(this,t),this.store=t,this.snapshots.ensureSessionIntegrity(),this.queries=new Kg(this),this.bindings=new $g(this),this.spatialIndex=new qg(this,this.queries),this.snaps=new Gg(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 ef(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 sf(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 Fg(this),this.historyStateSignal=this.history.state,this.commands=(n=this,{createPage:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.createPageRecord(t);let o=r;return D(e).atomic(()=>{const t=V([...e.getPages(),r]);o=t.find(e=>e.id===r.id)??r,D(e).put(t,i),e.ensurePageSessionState(o.id,i)},i),o})(n,e,t),deletePage:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.getPages();if(r.length<=1)return!1;const o=r.findIndex(e=>e.id===t);if(o<0)return!1;const s=e.getShapesForPage(t).map(e=>e.id),a=V(r.filter(e=>e.id!==t)),l=r[o+1]?.id??r[o-1]?.id??r[0]?.id,d=e.getCurrentPageId()===t&&l?l:e.getCurrentPageId();return D(e).atomic(()=>{s.length>0&&J(e,s,n),D(e).remove([t],i),e.removePageSessionState(t,d,i),D(e).put(a,i)},i),!0})(n,e,t),renamePage(e,t){((e,t,n)=>{const i=n?.source??"user",r=e.getPage(t.id);if(!r)return;const o=t.name.trim();o&&o!==r.name&&D(e).atomic(()=>{D(e).put([{...r,name:o}],i)},i)})(n,e,t)},movePage(e,t){((e,t,n)=>{const i=n?.source??"user",r=e.getPages(),o=r.findIndex(e=>e.id===t.id);if(o<0)return;const s=Math.max(0,Math.min(t.toIndex,r.length-1));if(o===s)return;const a=[...r],[l]=a.splice(o,1);l&&(a.splice(s,0,l),D(e).atomic(()=>{D(e).put(V(a),i)},i))})(n,e,t)},createShapes:(e,t)=>((e,t,n)=>{const i=[],r=n?.source??"user";return D(e).atomic(()=>{const n=t.map(t=>{const n=e.createShapeRecord(t);if("user"!==r||t.parentId)return n;const i=e.getContainingParentIdForShapeRecord(n);return i&&i!==n.parentId?{...n,parentId:i}:n});i.push(...n),D(e).put(n,r)},r),i})(n,e,t),createShapesFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(D(e).atomic(()=>{D(e).put(t,i)},i),t)})(n,e,t),updateShapes(e,t){j(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,r)=>({id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+r+1)}))})(e,t);0!==i.length&&j(e,i,n)})(n,e,t)},deleteShapes(e,t){J(n,e,t)},createAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.createAssetRecord(t);return D(e).atomic(()=>{D(e).put([r],i)},i),r})(n,e,t),createAssetsFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(D(e).atomic(()=>{D(e).put(t,i)},i),t)})(n,e,t),updateAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.getAsset(t.id);if(!r)return null;const o={...r,props:t.props?{...r.props,...t.props}:r.props,meta:t.meta??r.meta};return D(e).atomic(()=>{D(e).put([o],i)},i),o})(n,e,t),deleteAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return!!e.getAsset(t)&&(D(e).atomic(()=>{D(e).remove([t],i)},i),!0)})(n,e,t),createBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.createBindingRecord(t);if(!ee(e,r))throw new Error(`Invalid binding endpoints for ${r.type} binding`);return D(e).atomic(()=>{const t=e.bindings.getConflictingBindings(r).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),D(e).put([r],i),e.bindings.syncCreatedBinding(r,i)},i),r})(n,e,t),updateBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.getBinding(t.id);if(!r)return null;const o=e.getBindingUtil(r),s={...r,fromId:t.fromId??r.fromId,toId:t.toId??r.toId,props:t.props?o.validateProps({...r.props,...t.props}):r.props,meta:t.meta??r.meta};if(!ee(e,s))throw new Error(`Invalid binding endpoints for ${s.type} binding`);return D(e).atomic(()=>{const t=e.bindings.getConflictingBindings(s).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),D(e).put([s],i),e.bindings.syncUpdatedBinding(r,s,i)},i),s})(n,e,t),deleteBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.getBinding(t);return!!r&&(D(e).atomic(()=>{e.bindings.cleanupBindings([r.id],i),D(e).remove([r.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.registerBuiltInShortcuts(),this.registerBuiltInSideEffects()}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){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("pointer_cancel");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.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()}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 c(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})}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)??{},r=n.validateProps({...n.getDefaultProps(),...i,...t}),o=n.validateProps(n.getDefaultProps()),s={};for(const[l,d]of Object.entries(r))o[l]!==d&&(s[l]=d);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[r,o]of n)if(!pe(o,t[r]))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=bg.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 r=e.getShapeUtil(t),o=r.getSelectionPagePoints(t);if(!o&&!r.contributesToSelectionFrame(t,{editor:e}))return null;const s=(({points:e,transform:t})=>0===e.length?null:bg.FromPoints(e.map(e=>bn(e,t))))({points:o?[...o]:r.getPositionedOutlineVertices(t).map(n=>e.computeShapePositionedToPageTransform(t).applyToPoint(n)),transform:n});return s?r.flipSelectionBounds(t,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:Cn({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 u(t)?t:void 0}getAsset(e){const t=this._internalStore.get(e);return g(t)?t:void 0}getAssets(){return this._internalStore.getAll().filter(g).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 r of this._internalStore.getAll().filter(u)){const e=he(r);e&&(t.has(r.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 u(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 p(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:r,middleHandles:o,customHandles:s,rotateHandles:a,resizeHandles:l}=((e,t,n,i,r)=>Zn(Gn(e,t,n,i,r),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 d of o)if(d.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return d;for(const d of r)if(d.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return d;for(const d of s)if(d.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return d;for(const d of l)if(d.bounds.containsPoint(e))return d;for(const d of a)if(d.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return d;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 r=Array.from(t),o=e.getShapeExportTraversalIds(r),s=new Set(o),a=[],l=[];for(const x of o){const t=e.getShape(x);t?l.push(t):a.push({id:x,reason:"missing-shape"})}if(0===l.length)return null;const d=[];for(const x of l){const t=T(e,x,s);t&&(F(t)?d.push(t):a.push({id:x.id,reason:"missing-bounds"}))}if(0===d.length)return null;const c=(e=>{let t=1/0,n=1/0,i=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.minX),n=Math.min(n,o.minY),i=Math.max(i,o.maxX),r=Math.max(r,o.maxY);return new bg(t,n,i-t,r-n)})(d).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=>w(e,i.resolveThemeColor)},p=[],g=[],f=new Map;for(const x of l){const t=n.get(x.type);if(!t){a.push({id:x.id,reason:"missing-exporter"});continue}const i=t.toSvg(x,h);if(!i){a.push({id:x.id,reason:"empty-output"});continue}if(!F(e.computeShapeExportBounds(x))){a.push({id:x.id,reason:"missing-bounds"});continue}const r=e.computeShapeExportToPageTransform(x);p.push(x.id);const o=E(e,x,s,f,h);let l={tag:"g",attrs:{transform:r.toSvgString(),opacity:1===x.opacity?void 0:x.opacity},children:[i]};for(let e=o.length-1;e>=0;e-=1)l={tag:"g",attrs:{"clip-path":`url(#${o[e]})`},children:[l]};g.push(l)}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:L({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:m,height:S,viewBox:`${U(c.x)} ${U(c.y)} ${U(m)} ${U(S)}`},children:y}),bounds:c,width:m,height:S,requestedShapeIds:r,exportedShapeIds:p,skippedShapes:a}}(this,e,this.shapeSvgExporters,t)}getExportIntegrityReport(e=this.getSelectedShapeIds()){return z({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}repairExportIntegrity(e=this.getSelectedShapeIds()){return(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),r=z({editor:e,exporters:t,shapeIds:i});r.repairableIssueCount>0&&e.bindings.repairLoadedBindings("system");const o=z({editor:e,exporters:t,shapeIds:i});return{before:r,after:o,repaired:r.issues.length!==o.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",r=t.has(e.type)?"supported":"missing",o="supported"===i&&"supported"===r?"supported":"missing";return{...e,shapeUtil:i,svgExporter:r,exportSupport:o}});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),r=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:r,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]??{...wg}},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]??{...wg},r=n.pageSelectedShapeIdsById[e]??[];this.updateSession({pageCameraById:{...n.pageCameraById,[e]:i},pageSelectedShapeIdsById:{...n.pageSelectedShapeIdsById,[e]:r}},t)}removePageSessionState(e,t,n="system"){const i=this.sessionSignal.get(),r={...i.pageCameraById},o={...i.pageSelectedShapeIdsById};delete r[e],delete o[e],this.updateSession({currentPageId:t,pageCameraById:r,pageSelectedShapeIdsById:o},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(!u(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(!c(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(!p(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(!g(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)}},uf=class{getLocalBounds(e){const t=this.getBounds(e);return new bg(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,r=this.validateProps({...e.props,w:t.selectionLocalBounds.w,h:t.selectionLocalBounds.h}),o=Ti(r,"w",t.selectionLocalBounds.w),s=Ti(r,"h",t.selectionLocalBounds.h),a=In(Dt({requestedBounds:t.selectionLocalBounds,handleId:t.handleId,actualWidth:o,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-o/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:r}}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():xg.RotWith(e,t.selectionRotationCenter,-t.selectionRotation),i=kn({axis:t.axis,bounds:t.selectionBounds,point:n});return 0===t.selectionRotation?i:xg.RotWith(i,t.selectionRotationCenter,t.selectionRotation)});return this.updateSelectionPagePoints(e,{pagePoints:[i[0],i[1]]})}const i=this.getSelectionResizeLocalBounds(e),r=0===t.selectionRotation?t.selectionLocalBounds.center:xg.RotWith(t.selectionLocalBounds.center,t.selectionRotationCenter,t.selectionRotation);return{id:e.id,x:r.x-i.center.x,y:r.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:wi(this.getLocalBounds(e))}}getPositionedOutlineVertices(e){const t=this.getBounds(e);return[new xg(t.minX,t.minY),new xg(t.maxX,t.minY),new xg(t.maxX,t.maxY),new xg(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 Ig.Translate(e.x+t.x,e.y+t.y).compose(Ig.Rotate(e.rotation)).compose(Ig.Scale(e.scaleX,e.scaleY)).compose(Ig.Translate(-t.x,-t.y))}canEdit(e){return!1}canReceiveChildren(e){return!1}canReceiveTerminalBinding(e,t){return!1}repairLoadedShape(e){return null}onEditEnd(e){}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=wi(n);for(let r=0;r<i.length;r+=1){const n=i[r],o=i[(r+1)%i.length];if(n&&o&&null!==ki(e,t,n,o))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 r=t.sub(e);for(let o=0;o<n.length;o+=1){const r=n[o],s=n[(o+1)%n.length]??n[0];if(!r||!s)continue;const a=ki(e,t,r,s);null===a||a<=1e-6||a>=i||(i=a)}return Number.isFinite(i)?e.add(r.mul(i)):null})(Ci(e,t.rawPagePoint,n),Ci(e,t.oppositePagePoint,n),this.getPositionedOutlineVertices(e));return i?((e,t,n)=>{const i=n.center,r=t.sub(i);return i.add(new xg(r.x*e.scaleX,r.y*e.scaleY).rot(e.rotation))})(e,i,n):t.rawPagePoint}},hf=class{},pf=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)}},gf=class extends pf{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new ff(e,this)),this.addChild(new mf(e,this))}},ff=class extends pf{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",{originScreenPoint:e.screenPoint.clone(),originCamera:this.editor.getCurrentCamera()})}},mf=class extends pf{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}},Sf=Math.PI/180*15,yf=Math.PI/2,xf=Math.PI/180*5,bf="select.translate",If="select.resize",vf="select.rotate",Pf=class extends pf{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},wf=class extends Pf{onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&this.onDragThresholdExceeded(e)}},kf=class extends Pf{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=Mi(this.editor,e,this.tickMode);t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Ai(this.editor,e=>this.apply(e))}},Cf=class extends Pf{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,$i(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,Fi(e),$i(e))}onTick(e){if(!this.info)return;const t=Mi(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,Fi(t),$i(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,Fi(e),$i(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),r=Math.max(e.x,t.x),o=Math.max(e.y,t.y);return new bg(n,i,r-n,o-i)})(this.info.originPagePoint,e),r=((e,t)=>{const n=[],i=new Set;for(const r of t){const t=e.getOutermostSelectableShapeId(r);i.has(t)||(i.add(t),n.push(t))}return n})(this.editor,this.editor.getShapeIdsInBounds(i).filter(e=>((e,t,n,i)=>{const r=e.getShape(n);return!(!r||!((e,t)=>{const n=e.getShape(t);return!!n&&!e.getShapeUtil(n).isTransformDescendantContainer(n)})(e,r.id))&&e.getShapeUtil(r).canSelectByBrush(r,{brushBounds:t,isWrapping:i,pageOutlineVertices:e.getShapePageOutlineVertices(r.id),pageBounds:e.getShapePageBounds(r.id)})})(this.editor,i,e,n))),o=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,r):r;this.editor.setBrushBox(i),this.editor.commands.setSelectedShapeIds(o,{source:"system"})}updateBrushFromInputs(){Ai(this.editor,e=>this.updateBrush(e.pagePoint,Fi(e),$i(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},Tf=class extends kf{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(hg)return void e();const t={initialAtomValues:new Map};hg=t;try{e(),o(t.initialAtomValues.keys())}catch(n){for(const[e,i]of t.initialAtomValues)e.__unsafe__setWithoutNotify(i);throw n}finally{hg=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,r=!t&&"none"!==n&&null!==i,o=r&&i?this.editor.snaps.snapHandle({mode:n,pagePoint:e,snapshot:i,threshold:8/this.editor.getCurrentCamera().z}):null;r||this.editor.snaps.clearIndicators();const s=o?.snappedPagePoint??e,a=this.info.session.update({editor:this.editor,pagePoint:s,accelKey:t,source:"user"}),l="string"==typeof a?a:a.status,d="string"==typeof a?s:a.finalPagePoint;!o||!d||d.dist2(o.snappedPagePoint)<=1e-6||this.editor.snaps.clearIndicators(),"stop"===l&&this.transition("idle")}complete(){this.info&&(this.editor.setSnapIndicators(null),this.editor.history.squashToMark(this.info.session.historyMark)),this.transition("idle")}},Ef=class extends pf{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 r=this.editor.selectionHandleInteractions.createSession(this.editor,{handle:n,shape:i,originPagePoint:e.pagePoint.clone()});if(r){const i=r.handleSnapMode??"none";return void this.transition("pointing_selection_handle_interaction",{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);if(i){const n=this.editor.getShapeUtil(i).getSelectionTargetId(i,{editor:this.editor}),r=this.editor.getShapeUtil(i).getTranslateTargetId(i,{editor:this.editor}),o=Fi(e),s=Ri(this.editor,n,t),a=o?null:((e,t,n)=>{const i=new Set(n);for(const r of Li(e,t))if(i.has(r.ancestorId))return r.ancestorId;return null})(this.editor,n,t),l=o?null:a?s:null,d=Ri(this.editor,r,t);return void this.transition("pointing_shape",{shapeId:s,translateTargetId:null===l?d:a??d,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:o,wasSelected:t.includes(s),fromSelectionBounds:!1,quickClickSelectionTargetId:l})}if(!Fi(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:Fi(e)})}},Bf=class extends wf{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:Fi(e)})}onPointerUp(e){Fi(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")}},Mf=class extends wf{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 r={rotation:t.rotation,rotationCenter:t.rotationCenter},o=[],s=[];for(const a of e){const e=i(a);e?s.push({shape:a,startLocalPagePoint:bn(e[0],r),endLocalPagePoint:bn(e[1],r)}):o.push({shape:a,localBounds:bg.FromPoints(n(a).map(e=>bn(e,r))),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:o,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 xg(e.minX,e.minY),new xg(e.maxX,e.minY),new xg(e.maxX,e.maxY),new xg(e.minX,e.maxY)])(n).map(e=>i.applyToPoint(e))}(this.editor,e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e)});var i,r;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,r=n.pointShapes,[...i.map(e=>({id:e.shape.id,rotation:e.rotation})),...r.map(e=>({id:e.shape.id}))]),aspectRatioLockOverride:Oi(this.editor,t,this.info.handleId),lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},Af=class extends wf{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 r=[],o=[];for(const s of e){const e=i(s);e?o.push({shape:s,startPagePoint:e[0],endPagePoint:e[1]}):r.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:r,pointShapes:o}})({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:xg.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")}},Rf=class extends wf{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")}},Lf=class extends wf{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),r=i.map(e=>e.id),o=n?.hasCompatibleRotation?n.rotation:0,s=n?.rotationCenter.clone()??xg.Zero(),a=n?.hasCompatibleRotation?n.bounds.clone():this.editor.getSelectionPageBounds();var l;this.transition("translating",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,selectedShapeIds:t,startBounds:a,snapSnapshot:this.editor.snaps.createTranslateSnapshot({movingShapeIds:r,coordinateSpace:{rotation:o,rotationCenter:s}}),snapRotation:o,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 Fi(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")}},Ff=class extends kf{tickMode="apply_after_scroll_or_without_screen_point";constructor(e,t){super(e,"resizing",t)}getHistoryMark(){return If}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 r=Hi(this.info.rotationCenter,this.info.rotation),o=bn(e.sub(this.info.cursorHandleOffset),r),s=this.info.aspectRatioLockOverride??t,a=function({startBounds:e,handleId:t,pagePoint:n,isAspectRatioLocked:i,isResizingFromCenter:r,aspectRatio:o}){const s=r?(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.center,r=n.x-i.x,o=n.y-i.y,s=Math.max(Math.abs(r),.5),a=Math.max(Math.abs(o),.5),l=Mt(t)||At(t)?r*(Mt(t)?-2:2)/Math.max(1,e.w):1,d=Rt(t)||Lt(t)?o*(Rt(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new bg(e.minX,i.y-a,e.w,2*a),scaleX:l,scaleY:d};case"left":case"right":return{bounds:new bg(i.x-s,e.minY,2*s,e.h),scaleX:l,scaleY:d};default:return{bounds:new bg(i.x-s,i.y-a,2*s,2*a),scaleX:l,scaleY:d}}})({startBounds:e,handleId:t,pagePoint:n}):(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.minX,r=e.maxX,o=e.minY,s=e.maxY;let a=Mt(t)?i:r,l=Mt(t)?r:i,d=Rt(t)?o:s,c=Rt(t)?s:o;Mt(t)||At(t)?a=n.x:(a=r,l=i),Rt(t)||Lt(t)?d=n.y:(d=s,c=o);const u=a-l,h=d-c,p=Mt(t)?l-a:u,g=Rt(t)?c-d:h,f=Mt(t)||At(t)?p/Math.max(1,e.w):1,m=Rt(t)||Lt(t)?g/Math.max(1,e.h):1;return{bounds:new bg(Math.min(a,l),Math.min(d,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?zt({bounds:s.bounds,startBounds:e,handleId:t,aspectRatio:o,isResizingFromCenter:r,scaleX:s.scaleX,scaleY:s.scaleY}):s}({startBounds:this.info.startBounds,handleId:this.info.handleId,pagePoint:o,isAspectRatioLocked:s,isResizingFromCenter:n,aspectRatio:this.info.aspectRatio}),l=!i&&this.info.snapSnapshot.points.length>0,d=l?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;l||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&&zi(this.editor,e,this.info.startBounds,d.bounds,d.scaleX,d.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&&_i(this.editor,e,this.info.startBounds,0,d.scaleX,d.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(If),this.transition("idle")}cancel(){this.editor.setSnapIndicators(null),this.editor.history.bailToMark(If),this.transition("idle")}},$f=class extends kf{tickMode="apply_after_scroll";constructor(e,t){super(e,"rotating",t)}getHistoryMark(){return vf}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=Ui(xg.Angle(this.info.center,e)-this.info.startAngle);if(t)i=Di(i,Sf);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=Di(e,yf),n=Ui(t-e);Math.abs(n)<=xf&&(i=Ui(t-this.info.initialSelectionRotation))}for(let r=0;r<this.info.shapes.length;r+=1){const e=this.info.shapes[r],t=this.info.updates[r];e&&t&&Wi(e,this.info.center,i,t)}for(let r=0;r<this.info.pointShapes.length;r+=1){const e=this.info.pointShapes[r],t=this.info.updates[this.info.shapes.length+r];e&&t&&Yi(this.editor,e,this.info.center,i,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.history.squashToMark(vf),this.transition("idle")}cancel(){this.editor.history.bailToMark(vf),this.transition("idle")}},Uf=class extends kf{tickMode="always_apply";constructor(e,t){super(e,"translating",t)}getHistoryMark(){return bf}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,r=e.y-this.info.originPagePoint.y;t?this.info.lockedAxis||0===i&&0===r||(this.info.lockedAxis=Math.abs(i)>=Math.abs(r)?"x":"y"):this.info.lockedAxis=null;let o=i,s=r;"x"===this.info.lockedAxis?s=0:"y"===this.info.lockedAxis&&(o=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 xg(o,s):new xg(o,s).rot(-e),{nudge:i}=this.editor.snaps.snapTranslate({lockedAxis:this.info.lockedAxis,initialSelectionBounds:a,dragDelta:n,snapshot:this.info.snapSnapshot,threshold:t}),r=0===e?i:i.rot(e);o+="y"===this.info.lockedAxis?0:r.x,s+="x"===this.info.lockedAxis?0:r.y}else this.editor.snaps.clearIndicators();if(o!==this.info.lastDeltaX||s!==this.info.lastDeltaY){this.info.lastDeltaX=o,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+o,n.y=t.y+s)}this.editor.commands.updateShapes(this.info.updates)}Vi(this.editor,this.info.selectedShapeIds,e),((e,t,n)=>{const i=Ki(e,t,n);if(i===Xi(e,t))return void e.setDropTargetShapeId(null);const r=i?e.getShape(i):null;e.setDropTargetShapeId(r?.id??null)})(this.editor,this.info.selectedShapeIds,e)}complete(e){this.info&&Vi(this.editor,this.info.selectedShapeIds,e),this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.squashToMark(bf),this.transition("idle")}cancel(){this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.bailToMark(bf),this.transition("idle")}},Df=class extends pf{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new Ef(e,this)),this.addChild(new Bf(e,this)),this.addChild(new Cf(e,this)),this.addChild(new Lf(e,this)),this.addChild(new Uf(e,this)),this.addChild(new Mf(e,this)),this.addChild(new Ff(e,this)),this.addChild(new Af(e,this)),this.addChild(new $f(e,this)),this.addChild(new Rf(e,this)),this.addChild(new Tf(e,this))}},zf="editor.tool.set-active-tool",Hf="editor.tool.toggle-locked",_f=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()]}registerCanvasPlugins(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)}}},Nf=ji(),Of=Wp(Nf),Wf=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(Gi)}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()]}registerCanvasPlugins(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)}}},Yf=Zi(),Xf=Wp(Yf),Kf=class{guards=[];registeredGuardIds=new Set;register(e){this.registeredGuardIds.has(e.id)||(this.guards.push(e),this.registeredGuardIds.add(e.id))}registerCanvasPlugins(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}}},Vf=class{actions=new Map;contributions=new Map;hostActionIds=new Set;duplicateActionIds=new Set;duplicateContributionIds=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})}registerContribution(e,t={}){!this.contributions.has(e.id)||t.replace?this.contributions.set(e.id,e):this.duplicateContributionIds.add(e.id)}registerEditorPlugins(e){for(const t of e){for(const e of t.canvasActions??[])this.registerAction(e);for(const e of t.toolbarContributions??[])this.registerContribution(e)}}getAction(e){return this.actions.get(e)??null}getHostActionIds(){return[...this.hostActionIds]}getDuplicateActionIds(){return[...this.duplicateActionIds]}getDuplicateContributionIds(){return[...this.duplicateContributionIds]}getGroups(e,t,n={}){return[...this.contributions.values()].filter(t=>t.surface===e).filter(e=>!n.placement||(e.placement??"context")===n.placement).filter(e=>e.when?.(t)??!0).sort((e,t)=>(e.order??0)-(t.order??0)).flatMap(e=>[...e.getGroups(t)].sort((e,t)=>(e.order??0)-(t.order??0)))}},qf=class{contributions=new Map;duplicateContributionIds=new Set;registerContribution(e,t={}){!this.contributions.has(e.id)||t.replace?this.contributions.set(e.id,e):this.duplicateContributionIds.add(e.id)}registerEditorPlugins(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 r=t[e];t[e]={...r,title:r.title??i.title,items:[...r.items,...i.items]}}return t})([...this.contributions.values()].filter(t=>"any"===t.target||t.target===e).filter(e=>e.when?.(t)??!0).sort((e,t)=>(e.order??0)-(t.order??0)).flatMap(e=>[...e.getSections(t)].sort((e,t)=>(e.order??0)-(t.order??0))))}},jf="var(--land-selection, #2563eb)",Gf=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,rr(this.options,t??{}))}createFeature(){return this.config.createFeature?.(this.options)??null}getExtensions(){return this.config.addExtensions?.(this.options)??[]}},Zf="default",Qf={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}},Jf=new WeakMap,em=Wp(null),tm=Yp(()=>Fr(Lr().retainedShapeIdsSignal).map(e=>tg(im,{shapeId:e},e))),nm=Yp(()=>{const e=Lr(),t=Fr(e.currentPageShapeIdsSignal),n=Fr(e.retainedShapeIdsSignal),i=Fr(e.renderVisibleShapeIdsSignal),r=Fr(e.shapeRenderOrderByIdSignal),o=new Set(i),s=n.map(e=>r.get(e)??-1),a=n.filter(e=>o.has(e)).map(e=>r.get(e)??-1),l=n.filter(e=>!o.has(e)),d={pageShapeCount:t.length,mountedCount:n.length,visibleCount:i.length,hiddenRetainedCount:l.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:l};
|
|
50
|
-
return
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
return
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return
|
|
57
|
-
return
|
|
58
|
-
return
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
return tg(eg,{children:e.map(e=>tg("points"===e.type?Pm:wm,{indicator:e,zoom:t},e.id))})}),Pm=Yp(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[r,o]=e.line,s=180*e.rotation/Math.PI;
|
|
67
|
-
return ng("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${s} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[tg("path",{"data-ui":"snap-indicator-line",d:`M ${r.x} ${r.y} L ${o.x} ${o.y}`,fill:"none",stroke:bm,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,r)=>tg("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:bm,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${r}`))]})}),wm=Yp(({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=jr(i,[n?c.startEdge[0].y:c.startEdge[0].x,n?c.startEdge[1].y:c.startEdge[1].x]);e&&(i=e);const t=jr(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 r=(i[0]+i[1])/2,o=3.5/t,s=2*o,a=[];for(const{startEdge:c,endEdge:u}of e.gaps)if(n){a.push(`M ${c[0].x} ${r-s} L ${c[1].x} ${r+s}`,`M ${u[0].x} ${r-s} L ${u[1].x} ${r+s}`,`M ${c[0].x} ${r} L ${u[0].x} ${r}`);const e=(c[0].x+u[0].x)/2;a.push(`M ${e} ${r-o} L ${e} ${r+o}`)}else{a.push(`M ${r-s} ${c[0].y} L ${r+s} ${c[1].y}`,`M ${r-s} ${u[0].y} L ${r+s} ${u[1].y}`,`M ${r} ${c[0].y} L ${r} ${u[0].y}`);const e=(c[0].y+u[0].y)/2;a.push(`M ${r-o} ${e} L ${r+o} ${e}`)}const l=180*e.rotation/Math.PI,d=0===e.rotation?void 0:`rotate(${l} ${e.rotationCenter.x} ${e.rotationCenter.y})`;
|
|
68
|
-
return
|
|
69
|
-
tg("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 '}),
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
tg(Tm,{layer:"above-host"})]})),Tm=Yp(({layer:e})=>{const t=Qi().getCanvasOverlays(e);return 0===t.length?null:tg(eg,{children:t.map(({id:e,component:t})=>tg(t,{},e))})}),Em="canvas-surface",Bm=`[data-ui="${Em}"]`,Mm=[{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}],Am=14,Rm=16,Lm=20,Fm=28,$m=16,Um={[Am]:20,[Rm]:24,[Lm]:28,[Fm]:36},Dm=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))),To(i,"whiteSpace",n?.whiteSpace),To(i,"overflowWrap",n?.overflowWrap),To(i,"lineHeight",n?.lineHeight),To(i,"letterSpacing",n?.letterSpacing),To(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=P(t.props.color),e.style.fontFamily=yo(t.props.font,n),e.style.fontSize=`${xo(t.props.size)}px`,e.style.lineHeight=`${bo(t.props.size)}px`,e.style.textAlign=vo(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})}},zm=new WeakMap,Hm="land.rich-text-bubble-menu",_m="updatePosition",Nm=[{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"}],Om=[lg.configure({bold:!1,italic:!1,strike:!1}),og.extend({keepOnSplit:!0}),sg.extend({keepOnSplit:!0}),ag.extend({keepOnSplit:!0})],Wm=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),Ym={id:"land.text.dom-events",handle({event:e,name:t}){if(!Wm.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},Xm="text.create",Km=class extends pf{constructor(e){super(e,"text"),this.initial="idle",this.addChild(new Vm(e,this)),this.addChild(new qm(e,this))}},Vm=class extends pf{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("pointing",{originPagePoint:e.pagePoint.clone(),shapeId:null,didCreateShape:!1})}},qm=class extends pf{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e,this.editor.history.mark(Xm)}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(!co(t))return this.editor.history.bailToMark(Xm),void this.transition("idle");this.info.didCreateShape=!0,q(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:Xm,reuseExistingMark:!0,preserveInteraction:!0},"user"),this.editor.isToolLocked()&&this.transition("idle")}onCancel(){this.info?.didCreateShape||this.editor.history.bailToMark(Xm),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:{...Ko(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:Ko(t)}))(e,this.getDefaultTextProps()))}createTextShapeAt({x:e,y:t,props:n}){const i=po(this.editor,{x:e,y:t,props:n},"user");return this.editor.commands.setSelectedShapeIds([i.id],{source:"system"}),i}getDefaultTextProps(){return ho(this.editor)}},jm="arrow-label",Gm="geo-label",Zm={[jm]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!0,canUseSelectionFrameHandles:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[Gm]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!1,canUseSelectionFrameHandles:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}},Qm=["start","middle","end"],Jm=class extends uf{type="text";getDefaultProps(){return{richText:cr(""),w:16,h:Io($m),autoSize:!0,scale:1,font:Zf,size:$m,color:m("text-slate"),textAlign:"start"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{richText:hr(t.richText),w:Math.max(1,Zo(t.w,n.w)),h:Math.max(1,Zo(t.h,n.h)),autoSize:"boolean"==typeof t.autoSize?t.autoSize:n.autoSize,scale:Math.max(.01,Zo(t.scale,n.scale)),font:Er(t.font)?t.font:n.font,size:So(t.size,n.size),color:v(t.color,n.color),textAlign:(i=t.textAlign,"string"==typeof i&&Qm.includes(i)?t.textAlign:n.textAlign)};var i}getBounds(e){return(e=>new bg(e.x,e.y,Jo(e),es(e)))(e)}getLocalBounds(e){return ts(e)}getRenderBounds(e){return ts(e)}getExportBounds(e){return ts(e)}canReceiveTerminalBinding(e){return!0}canEdit(e){return!0}contributesToSelectionFrame(e,t){return n=t.editor,i=e.id,jo(n,i)?.behavior.contributesToSelectionFrame??null??!0;var n,i}canUseSelectionFrameHandles(e,t){return n=t.editor,i=e.id,jo(n,i)?.behavior.canUseSelectionFrameHandles??null??!0;var n,i}getSelectionTargetId(e,t){return((e,t)=>{const n=jo(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=jo(e,t);return n?"owner"===n.behavior.translateTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}resizeSelectionBounds(e,t){const n={};ns(t.handleId)?(n.w=Math.max(16,t.selectionLocalBounds.w/Qo(e)),n.autoSize=!1):n.scale=Math.max(.01,e.props.scale*((e,t)=>{const n=t.selectionLocalBounds.w/Math.max(1,Jo(e)),i=t.selectionLocalBounds.h/Math.max(1,es(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??Qo(e),r=(n.w??e.props.w)*i,o=e.props.h*i,s=((e,t)=>0===t.selectionRotation?e.clone():xg.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(Dt({handleId:t.handleId,requestedBounds:t.selectionLocalBounds,actualWidth:r,actualHeight:o,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,t);return{id:e.id,x:s.x-r/2,y:s.y-o/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?!ns(t.handleId):null}onEditEnd(e){if(!(ur(e.props.richText).trim().length>0))return{deleteShapeIds:[e.id]}}},eS=class{fontCatalog;type="text";constructor(e){this.fontCatalog=e}toSvg(e,t){return 0===ur(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:os(e,t,this.fontCatalog)},children:is(e.props.richText)}]}}},tS=".label",nS=class extends hf{type=jm;getDefaultProps(){return{labelPosition:.5}}validateProps(e){const t=this.getDefaultProps();return{labelPosition:as((e&&"object"==typeof e?e:{}).labelPosition,t.labelPosition)}}canBind(e,t,n){return co(n.fromShape)&&ss(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)=>jo(e,t)?.behavior.showsCompanionFrameWhenOwnerSelected??null)(e,t.fromId))return[];const i=e.getShape(t.fromId),r=e.getShape(t.toId);if(!co(i)||!ss(r))return[];const o=e.computeShapeGeometry(i);return[{bounds:o.bounds,rotation:i.rotation,rotationCenter:o.center}]}syncLabelPosition(e,t){if(n=t,"binding"!==n?.typeName||"arrow-label"!==n.type)return;var n;const i=e.getShape(t.fromId),r=e.getShape(t.toId);if(!co(i)||!ss(r))return{deleteBindingIds:[t.id]};const o=((e,t,n)=>{const i=ls(e,t,n),r=n.parentId,o=`${n.index}${tS}`,s=!1,a="middle";return t.x===i.x&&t.y===i.y&&t.rotation===i.rotation&&t.parentId===r&&t.index===o&&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:r,index:o,props:{w:i.props.w,autoSize:s,textAlign:a}}})(e,i,r);return o?{shapes:[{...i,...o,props:{...i.props,...o.props}}]}:void 0}},iS=".label",rS=class extends hf{type=Gm;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:hs(i.x,t.normalizedAnchor.x),y:hs(i.y,t.normalizedAnchor.y)},ownerBaseHeight:ps(n.ownerBaseHeight,t.ownerBaseHeight)}}canBind(e,t,n){return co(n.fromShape)&&us(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?fs(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?fs(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 r=e.getShape(t.fromId),o=e.getShape(t.toId);if(!co(r)||!us(o))return{deleteBindingIds:[t.id]};const s=((e,t,n)=>{const i=gs(t,"h")??1;return"to"===n?.role?i:e.props.ownerBaseHeight>0?e.props.ownerBaseHeight:i})(t,o,n),a=t.props.ownerBaseHeight===s?null:{...t,props:{...t.props,ownerBaseHeight:s}},l=function(e,t,n){const i=gs(e,"h");if(!i)return null;const r=Math.max(n,(e=>Math.max(1,e.props.h*e.props.scale+32))(t));return i===r?null:{...e,props:{...e.props,h:r}}}(o,r,s),d=((e,t,n)=>{const i=ms(e,t,n),r=n.parentId,o=`${n.index}${iS}`,s=!1,a="middle";return t.x===i.x&&t.y===i.y&&t.rotation===i.rotation&&t.parentId===r&&t.index===o&&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:r,index:o,props:{w:i.props.w,autoSize:s,textAlign:a}}})(e,r,l??o),c=[];return l&&c.push(l),d&&c.push({...r,...d,props:{...r.props,...d.props}}),c.length>0||a?{shapes:c.length>0?c:void 0,bindings:a?[a]:void 0}:void 0}},oS="text.edit",sS="arrow-label.edit",aS="arrow-label.create",lS="geo-label.edit",dS="geo-label.create",cS=[{value:m("text-slate"),label:"Slate",color:"var(--land-shape-text-slate)"},{value:m("text-blue"),label:"Blue",color:"var(--land-shape-text-blue)"},{value:m("text-green"),label:"Green",color:"var(--land-shape-text-green)"},{value:m("text-red"),label:"Red",color:"var(--land-shape-text-red)"}],uS=[{id:"s",value:14,label:"S"},{id:"m",value:16,label:"M"},{id:"l",value:20,label:"L"},{id:"xl",value:28,label:"XL"}],hS=[{value:"start",label:"Align left",icon:"align-left"},{value:"middle",label:"Align center",icon:"align-center"},{value:"end",label:"Align right",icon:"align-right"}],pS=ir({name:"text",addOptions:kr,createFeature:(e=kr())=>{const t=Tr(e);return{id:"land.text.bundle",editorPlugins:[xs({fontCatalog:t})],canvasPlugins:[Wo({fontCatalog:t})],shapeTypes:["text"]}}}),gS=[],fS=2*Math.PI,mS=class extends hf{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,ga(i.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,ga(i.y,n.normalizedAnchor.y)))}}}canBind(e,t,n){return ta(n.fromShape)&&ha(e,n.toShape)}getExclusiveBindingKey(e){return`${e.fromId}:${e.props.terminal}`}onBindingCreate(e,t){return fa(this.syncArrowTerminal(e,t))}onBindingUpdate(e,t,n){return fa(this.syncArrowTerminal(e,n))}onBindingLoad(e,t){return fa(this.syncArrowTerminal(e,t))}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return fa(this.syncArrowTerminal(e,t))}onBeforeDeleteShape(e,t,n){if("from"===n.role)return{deleteBindingIds:[t.id]};const i=e.getShape(t.fromId);if(!ta(i))return{deleteBindingIds:[t.id]};const r=this.resolveTerminalPagePoint(e,t);return{shapes:[r?Hs(i,t.props.terminal,r):i],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.fromId);if(!ta(n))return{deleteBindingIds:[t.id]};const i=this.resolveTerminalPagePoint(e,t);return{shapes:[i?Hs(n,t.props.terminal,i):n],deleteBindingIds:[t.id]}}syncArrowTerminal(e,t){if(!na(t))return null;const n=e.getShape(t.fromId);if(!ta(n))return null;const i=this.resolveTerminalPagePoint(e,t);return i?Us(n,t.props.terminal).dist(i)<1e-6?null:Hs(n,t.props.terminal,i):null}resolveTerminalPagePoint(e,t){if(!na(t))return null;const n=e.getShape(t.fromId),i=e.getShape(t.toId);if(!ta(n)||!i||ta(i))return null;const r=Us(n,Ds(t.props.terminal)),o=$s(e,i,t.props.normalizedAnchor,r);return da(e,{arrow:n,terminal:t.props.terminal,target:i,anchorPagePoint:Fs(e,i,t.props.normalizedAnchor),fallbackBoundaryPagePoint:o}).boundaryPagePoint}},SS=class extends uf{type="arrow";getDefaultProps(){return{w:160,h:48,start:{x:8,y:24},end:{x:152,y:24},bend:0,stroke:m("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,Sa(t.w,n.w)),h:Math.max(1,Sa(t.h,n.h)),start:ma(t.start,n.start),end:ma(t.end,n.end),bend:Sa(t.bend,n.bend),stroke:v(t.stroke,n.stroke),strokeWidth:Math.max(1,Sa(t.strokeWidth,n.strokeWidth)),headStart:"arrow"===t.headStart?"arrow":"none",headEnd:"none"===t.headEnd?"none":"arrow"}}getBounds(e){const t=_s(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}getPointHitTestBounds(e,t){const n=t?.editor?ra(t.editor,e).info:_s(e),i=Math.max(8,e.props.strokeWidth+4);return n.bounds.expand(i)}getLocalBounds(e){return new bg(0,0,e.props.w,e.props.h)}getExportBounds(e){const t=(e=>Ys(new xg(e.props.start.x,e.props.start.y),new xg(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:zs(e,Us(e,"start"),Us(e,"end"))}updateSelectionPagePoints(e,t){const n=zs(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(Us(e,"start"))&&t.brushBounds.containsPoint(Us(e,"end"))}getSelectionPagePoints(e){return[Us(e,"start"),Us(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=ra(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=ra(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,Js(t,e.points[i],e.points[i+1]));return Number.isFinite(n)?n:t.dist(e.start.point)})(n?.editor?ra(n.editor,e).info:_s(e),n?.pagePoint??t)<=Math.max(8,e.props.strokeWidth+4)}hitTestLineSegment(e,t){const n=t.editor?ra(t.editor,e).info:_s(e),i=Math.max(8,e.props.strokeWidth+4,t.margin),r=t.editor?t.pageStart:t.positionedStart,o=t.editor?t.pageEnd:t.positionedEnd;if(1===n.points.length)return ya(n.points[0],r,o)<=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&&xa(r,o,e,t)<=i)return!0}return!1}},yS="arrow.create",xS=class extends pf{constructor(e){super(e,"arrow"),this.initial="idle",this.addChild(new bS(e,this)),this.addChild(new IS(e,this))}},bS=class extends pf{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})=>va(e,{terminal:t,rawPagePoint:n,oppositePagePoint:n.add(new xg(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})}},IS=class extends pf{info=null;constructor(e,t){super(e,"creating",t)}onEnter(e){if(this.info=e,!this.info)return;this.editor.history.mark(yS);const t=ba(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=Bi(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(yS),void this.transition("idle");q(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(yS),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})}else this.transition("idle")}onCancel(){this.editor.history.bailToMark(yS),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=ta(n)?Pa(this.editor,{arrow:n,terminal:"end",rawPagePoint:e,ignoreTargets:this.editor.inputs.state.get().accelKey}):va(this.editor,{terminal:"end",rawPagePoint:e,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey}),r=Ia(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(ta(r)?r:null)}updateCreationBindingGuides(e){if(!e)return void this.editor.setTerminalBindingGuides(null);const t=new Map(this.editor.getBindingsFromShape(e.id).filter(na).map(e=>[e.props.terminal,e.toId])),n=ra(this.editor,e).bindingSegments.map(n=>({...n,ownerShapeId:e.id,targetShapeId:t.get(n.terminal)??null}));this.editor.setTerminalBindingGuides(n)}},vS=class{type="arrow";toSvg(e,t){const n=t.resolveColor(e.props.stroke),i="arrow"===e.props.headStart?`url(#${t.addDef(Aa("start",n))})`:void 0,r="arrow"===e.props.headEnd?`url(#${t.addDef(Aa("end",n))})`:void 0;return{tag:"path",attrs:{d:oa(t.editor,e).path,fill:"none",stroke:n,"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":i,"marker-end":r}}}},PS=[{value:m("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:m("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:m("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:m("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],wS=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],kS=[{value:"none",label:"None",icon:"minus"},{value:"arrow",label:"Arrow",icon:"arrow-right"}],CS=ir({name:"arrow",createFeature:()=>({id:"land.arrow.bundle",editorPlugins:[{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 SS],shapeSvgExporters:[new vS],bindingUtils:[new mS],interactionHandlers:[{id:"land.arrow.interactions",selectionHandle:Ca()}],canvasActions:[Ea("stroke"),Ea("strokeWidth"),Ea("headStart"),Ea("headEnd"),Ba("stroke"),Ba("strokeWidth"),Ba("headStart"),Ba("headEnd")],toolbarContributions:[{id:"arrow.tool-toolbar",surface:"tool",placement:"chrome",order:40,actionIds:[zf],getGroups:e=>[{id:"arrow.tools",items:[{kind:"button",id:"arrow.tool.arrow",actionId:zf,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:()=>Ta({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:()=>Ta({strokeActionId:"arrow.set-stroke",strokeWidthActionId:"arrow.set-strokeWidth",headStartActionId:"arrow.set-headStart",headEndActionId:"arrow.set-headEnd",dataUiPrefix:"arrow"})}],setup(e){e.setTerminalBindingResolver(va),e.tools.register("arrow",e=>new xS(e),{shortcut:"a"})}}],canvasPlugins:[{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:Ra}]}],shapeTypes:["arrow"]})}),TS=.08,ES=new WeakMap,BS=new WeakMap,MS=new WeakMap,AS=new WeakMap,RS="draw.create",LS=class extends pf{constructor(e){super(e,"draw"),this.initial="idle",this.addChild(new FS(e,this)),this.addChild(new $S(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("draw")}},FS=class extends pf{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(),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:[Bl(e.pagePoint,e.pagePoint,e.pressure,"pen"===e.pointerType)]}]})}},$S=class extends pf{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(RS)}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(RS),void this.transition("idle");q(this.editor,t,{source:"user"}),this.editor.history.squashToMark(RS),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.editor.history.bailToMark(RS),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.info=null}appendPoint(e,t){if(!this.info)return;const n=Bl(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:Ll(this.info.segments)}],{source:"user"})}createShape(){const e=this.tool.getDefaultProps(),[t]=this.editor.commands.createShapes([{type:"draw",x:this.info?.originPagePoint.x??0,y:this.info?.originPagePoint.y??0,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,...Ll(this.info?.segments??[]),isPen:this.info?.isPen??!1}}],{source:"user"});if(!t||"draw"!==t.type)throw new Error("Failed to create draw shape");return t}appendStraightSegmentPoint(e){if(!this.info)return;this.info.preserveStraightEndpointOnNextFreePoint=!1;const t=Al(this.info),n=t[t.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return void this.replaceCurrentSegmentPoints([{...e,segment:"straight"}]);this.info.straightSegmentAnchorPoint=Ml(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=Al(this.info),n=t[t.length-1];return!(n&&(i=n).x===(r=e).x&&i.y===r.y&&i.pressure===r.pressure&&i.segment===r.segment||(this.replaceCurrentSegmentPoints([...t,Ml(e)]),0));var i,r}appendGuardedCurrentPoint(e){if(!this.info)return;const t=Al(this.info).map(Ml);(function(e,t,n){const i=za(t),r=e[e.length-1];if(!r)return void e.push(i);if(Ua(r,i))return;const o=((e,t)=>{if(e<=t.softMaxPointCount)return t.minPointDistance;const n=Fa((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-r.x,a=i.y-r.y,l=Math.abs((i.pressure??0)-(r.pressure??0));s*s+a*a<o*o&&l<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=Rl(this.info.segments);this.info.segments=[...t.slice(0,-1),{points:e.map(Ml)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const e=$a(this.info.isPen);let t=Rl(this.info.segments),n=t[t.length-1];for(;n.points.length>e;){const i=n.points.slice(0,e).map(Ml),r=i[i.length-1],o=n.points.slice(e).map(Ml);if(!r||0===o.length)break;const s={points:[Ml(r),...o]};t=[...t.slice(0,-1),{points:i},s],n=s}this.info.segments=t}},US=class extends uf{type="draw";getDefaultProps(){return{segments:(e=[{x:0,y:0},{x:24,y:12}],[{points:e.map(za)}]),stroke:m("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:Ol(t.segments,n.segments),stroke:v(t.stroke,n.stroke),strokeWidth:Math.max(4,Hl(t.strokeWidth,n.strokeWidth)),fill:v(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=Pl(e);return new bg(e.x+t.localBounds.x,e.y+t.localBounds.y,t.localBounds.w,t.localBounds.h)}getLocalBounds(e){return Pl(e).localBounds}getRenderBounds(e){return Pl(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:r})=>{let o=qa(e);for(let s=0;s<2;s+=1){const e=yl(o,t,n,i),s=bl(e.pointBounds,e.localBounds,r);o=el(o,e.pointBounds,s)}return o})({segments:nl(Cl(e),t),strokeWidth:e.props.strokeWidth,isPen:e.props.isPen??!1,isClosed:e.props.isClosed,targetSelectionStrokeBounds:t.targetSelectionStrokeBounds});return t.scaleX<0&&(n=rl(n,{axis:"horizontal",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),t.scaleY<0&&(n=rl(n,{axis:"vertical",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),wl(il(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:El(n.segments)}}}flipSelectionBounds(e,t){const n=((e,t)=>wl(il(rl(nl(Cl(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:El(n.segments)}}}getSelectionOverlayInfo(e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null}}isWrappedByBrush(e,t){return Tl(e).outlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return!!this.isWrappedByBrush(e,t)||!t.isWrapping&&(e=>{const t=new xg(e.minX,e.minY),n=new xg(e.maxX,e.minY),i=new xg(e.maxX,e.maxY),r=new xg(e.minX,e.maxY);return[[t,n],[n,i],[i,r],[r,t]]})(t.brushBounds).some(([t,n])=>this.hitTestLineSegment(e,{pageStart:t,pageEnd:n,positionedStart:t,positionedEnd:n,margin:0}))}getPositionedOutlineVertices(e){return kl(e).outlineVertices}hitTest(e,t){return function(e,t,n,i={}){if(i.isClosed&&void 0!==i.fill&&!k(i.fill)&&e.normalizedPoints.length>=3&&Ul(n,e.normalizedPoints.map(Da)))return!0;if(i.isClosed&&((e,t)=>{if(0===t.length)return Number.POSITIVE_INFINITY;if(1===t.length)return e.dist(Da(t[0]));let n=Number.POSITIVE_INFINITY;for(let i=1;i<t.length;i+=1){const r=t[i-1],o=t[i];r&&o&&(n=Math.min(n,Fl(e,Da(r),Da(o))))}return t.length>=3&&(n=Math.min(n,Fl(e,Da(t[t.length-1]),Da(t[0])))),n})(n,e.normalizedPoints)<=Math.max(4,.5*t))return!0;if(0===e.outlineVertices.length)return!1;for(const r of e.outlinePolygons){if(Ul(n,r))return!0;if(Dl(n,r)<=Math.max(4,.5*t))return!0}return!1}(kl(e),e.props.strokeWidth,t,{fill:e.props.fill,isClosed:e.props.isClosed})}hitTestLineSegment(e,t){return((e,t,n,i,r={})=>{const o=Math.max(4,.5*t,r.margin??0);return!!(r.isClosed&&void 0!==r.fill&&!k(r.fill)&&e.normalizedPoints.length>=3&&zl(n,i,e.normalizedPoints.map(Da),o))||0!==e.outlineVertices.length&&e.outlinePolygons.some(e=>zl(n,i,e,o))})(Tl(e),e.props.strokeWidth,t.pageStart,t.pageEnd,{fill:e.props.fill,isClosed:e.props.isClosed,margin:t.margin})}repairLoadedShape(e){const t=Pl(e);if(0===t.pointBounds.x&&0===t.pointBounds.y&&0===e.rotation&&1===e.scaleX&&1===e.scaleY)return null;const n=(e=>wl(Cl(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:El(n.segments)}}}},DS=class{type="draw";toSvg(e,t){const n=Pl(e);if(!n.path&&!n.selectionPath)return null;const i=[];return n.fillPath&&!k(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}}},zS=[{value:m("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:m("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:m("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:m("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],HS=[{value:"transparent",label:"None",color:"transparent"},{value:m("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:m("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:m("fill-red"),label:"Red",color:"var(--land-shape-fill-red)"},{value:m("fill-white"),label:"White",color:"var(--land-shape-fill-white)"}],_S=[{value:4,label:"4"},{value:6,label:"6"},{value:8,label:"8"},{value:10,label:"10"}],NS=[{value:"open",label:"Open"},{value:"closed",label:"Closed"}],OS=ir({name:"draw",createFeature:()=>({id:"land.draw.bundle",editorPlugins:[{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 US],shapeSvgExporters:[new DS],canvasActions:[{id:"draw.set-closed",isVisible:e=>"draw"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>Vl(e.selection.selectedShapes),run({context:e,value:t}){const n=ql(t);if(null===n)return;const i=e.selection.selectedShapes.filter(Wl).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{isClosed:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},Xl("fill"),Xl("stroke"),Xl("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=ql(t);null!==n&&e.editor.updateDefaultShapeProps("draw",{isClosed:n})}},Kl("fill"),Kl("stroke"),Kl("strokeWidth")],toolbarContributions:[{id:"draw.tool-toolbar",surface:"tool",placement:"chrome",order:45,actionIds:[zf],getGroups:e=>[{id:"draw.tools",items:[{kind:"button",id:"draw.tool.draw",actionId:zf,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:()=>Yl({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:()=>Yl({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"===Vl(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 LS(e),{shortcut:"p"})}}],canvasPlugins:[{id:"land.draw.react",shapeRenderers:[{type:"draw",component:Zl}]}],shapeTypes:["draw"]})}),WS=class extends pf{constructor(e){super(e,"eraser"),this.initial="idle",this.addChild(new YS(e,this)),this.addChild(new XS(e,this)),this.addChild(new KS(e,this))}onExit(){ad(this.editor)}},YS=class extends pf{constructor(e,t){super(e,"idle",t)}onEnter(){ad(this.editor)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={originPagePoint:t.pagePoint.clone(),previousPagePoint:t.pagePoint.clone(),protectedContainerIds:ed(e,t.pagePoint),erasingShapeIds:new Set,trail:[t.pagePoint.clone()]};return id(e,n,t),sd(e,n),n})(this.editor,e))}},XS=class extends pf{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&&(rd(this.editor,this.info,e),od(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),sd(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(e){this.info&&(id(this.editor,this.info,e),sd(this.editor,this.info),ld(this.editor,this.info)),this.transition("idle")}onCancel(){ad(this.editor),this.transition("idle")}onExit(){this.info=null}},KS=class extends pf{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&&ld(this.editor,this.info),this.transition("idle")}onCancel(){ad(this.editor),this.transition("idle")}onExit(){this.info=null}update(e){this.info&&(rd(this.editor,this.info,e),od(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),sd(this.editor,this.info))}},VS=Yp(()=>Fr(Lr().eraserTrailActiveSignal)?tg(qS,{}):null),qS=Yp(()=>{const e=Lr(),t=Fr(e.eraserTrailSignal),n=Fr(e.cameraZoomSignal),i=Math.max(n,1e-4),r=(()=>{const[e,t]=Qp(()=>dd());return Vp(()=>{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})(),o=Zp({samples:[],sourceLength:0}),s=Math.max(r,dd());((e,t,n,i)=>{if(ud(e,i),t.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),t.length===e.sourceLength)return;const r=e.sourceLength,o=t.length-r,s=e.samples[e.samples.length-1]?.time??i-ny*o;for(let a=r;a<t.length;a++){const l=t[a];cd(e,{x:l.x,y:l.y},n,vd(s,i,(a-r+1)/o))}e.sourceLength=t.length,ud(e,i)})(o.current,t,i,s);const a=function(e,t){const n=hd(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),i=[e[0]];for(let r=1;r<e.length;r++)i.push(Id(i[i.length-1],e[r],n));return i})(n.length>GS?n.slice(-48):n,JS)}(o.current.samples,s);if(0===a.length)return null;const l=(c=QS/i,0===(d=a).length||c<=0?null:1===d.length?kd(gd(d[0],c/2,ty))??"":kd((e=>{if(0===e.length)return[];if(1===e.length)return gd(e[0].point,Math.max(e[0].radius,.01),ty);const t=[],n=[];for(const a of e){const e=Sd(a.direction);wd(t,xd(a.point,bd(e,a.radius))),wd(n,yd(a.point,bd(e,a.radius)))}const i=[];for(const a of t)wd(i,a);const r=e[e.length-1],o=Sd(r.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const r=[];for(let o=1;o<ey;o++){const s=o/ey;r.push(yd(e,yd(bd(t,Math.sin(Math.PI*s)*i),bd(n,-Math.cos(Math.PI*s)*i))))}return r})({center:r.point,direction:r.direction,normal:o,radius:r.radius});for(const a of s)wd(i,a);for(let a=n.length-1;a>=0;a--)wd(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]+fd(e[n-1],e[n]));return t})(e),i=Math.max(t,n[n.length-1]??0);return e.map((r,o)=>{const s=n[o]??0,a=Pd(s/i,0,1);return{point:r,direction:pd(e,o),radius:t/2*a,runningLength:s}})})(d,c))));var d,c;return l?tg("g",{"data-ui":"eraser-trail-overlay",children:tg("path",{"data-ui":"eraser-trail-scribble",d:l,fill:jS})}):null}),jS="rgba(142, 142, 142, 0.16)",GS=48,ZS=1,QS=12,JS=.32,ey=8,ty=13,ny=16,iy=8,ry=180,oy=180,sy=680,ay=ir({name:"eraser",createFeature:()=>({id:"land.eraser.bundle",editorPlugins:[{id:"land.eraser",toolbarContributions:[{id:"eraser.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[zf],getGroups:e=>[{id:"eraser.tools",items:[{kind:"button",id:"eraser.tool.eraser",actionId:zf,value:"eraser",label:"Eraser",shortcut:e.editor.shortcuts.getToolShortcutLabel("eraser"),icon:"eraser",dataUi:"eraser-tool-button"}]}]}],setup(e){e.tools.register("eraser",e=>new WS(e),{shortcut:"e"})}}],canvasPlugins:[{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",layer:"below-host",component:VS}]}],shapeTypes:[]})}),ly=class extends uf{type="frame";getDefaultProps(){return{w:640,h:360,name:"Frame",fill:"transparent",stroke:m("stroke-muted"),strokeWidth:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,Bd(t.w,n.w)),h:Math.max(1,Bd(t.h,n.h)),name:"string"==typeof t.name&&t.name.length>0?t.name:n.name,fill:v(t.fill,n.fill),stroke:v(t.stroke,n.stroke),strokeWidth:Math.max(0,Bd(t.strokeWidth,n.strokeWidth))}}getBounds(e){return new bg(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 Md(this.getBounds(e),t,6)}hitTestBindingTarget(e,t){return this.getBounds(e).containsPoint(t)}hitTestLineSegment(e,t){return((e,t,n,i)=>{const r=i/2;if(Md(e,t,i)||Md(e,n,i))return!0;const o=[new xg(e.minX,e.minY),new xg(e.maxX,e.minY),new xg(e.maxX,e.maxY),new xg(e.minX,e.maxY)];for(let s=0;s<o.length;s+=1){const e=o[s],i=o[(s+1)%o.length];if(e&&i&&xi(t,n,e,i)<=r)return!0}return!1})(this.getBounds(e),t.positionedStart,t.positionedEnd,Math.max(6,t.margin))}},dy="frame.create",cy=class extends pf{constructor(e){super(e,"frame"),this.initial="idle",this.addChild(new uy(e,this)),this.addChild(new hy(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("frame")}},uy=class extends pf{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})}},hy=class extends pf{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(dy)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.editor.history.squashToMark(dy),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(dy),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=(r=e,o=this.tool.getDefaultProps(),new bg(r.x-o.w/2,r.y-o.h/2,o.w,o.h)),i=this.createShape(t);return void(this.info.shapeId=i.id)}var r,o;const s=((e,t,n,i)=>{let r=t.x-e.x,o=t.y-e.y;if(n){const e=i.w/i.h,t=Math.abs(r),n=Math.abs(o);0===n||t/Math.max(n,1)>=e?o=t/e*(o<0?-1:1):r=n*e*(r<0?-1:1)}const s=new xg(e.x+r,e.y+o);return new bg(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}},py=class{type="frame";toSvg(e,t){const{fill:n,stroke:i,strokeWidth:r,w:o,h:s,name:a}=e.props,l=t.resolveColor(i),d=r/2;return{tag:"g",children:[{tag:"rect",attrs:{x:d,y:d,width:Math.max(o-r,0),height:Math.max(s-r,0),fill:t.resolveColor(n),stroke:l,"stroke-width":r,"stroke-linejoin":"round","stroke-linecap":"round"}},{tag:"text",attrs:{x:12,y:18,fill:l,"font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":600},children:[a]}]}}},gy=[{value:"transparent",label:"None",color:"transparent"},{value:m("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:m("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:m("fill-amber"),label:"Amber",color:"var(--land-shape-fill-amber)"}],fy=[{value:m("stroke-muted"),label:"Slate",color:"var(--land-shape-stroke-muted)"},{value:m("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:m("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:m("stroke-orange"),label:"Orange",color:"var(--land-shape-stroke-orange)"}],my=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Sy=ir({name:"frame",createFeature:()=>({id:"land.frame.bundle",editorPlugins:[{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 ly],shapeSvgExporters:[new py],canvasActions:[Ad("fill"),Ad("stroke"),Ad("strokeWidth"),Rd("fill"),Rd("stroke"),Rd("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"})}},Fd("backward"),Fd("forward")],toolbarContributions:[{id:"frame.tool-toolbar",surface:"tool",placement:"chrome",order:60,actionIds:[zf],getGroups:e=>[{id:"frame.tools",items:[{kind:"button",id:"frame.tool.frame",actionId:zf,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:()=>Ld({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"}]}]:[],...Ld({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"===Ud(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"===Ud(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 cy(e),{shortcut:"f"})}}],canvasPlugins:[{id:"land.frame.react",shapeRenderers:[{type:"frame",component:Dd}]}],shapeTypes:["frame"]})}),yy="geo.create",xy=class extends pf{geo;constructor(e,t,n){super(e,t),this.geo=n,this.initial="idle",this.addChild(new by(e,this)),this.addChild(new Iy(e,this))}getDefaultProps(){return{...this.editor.getDefaultShapeProps("geo"),geo:this.geo}}onEnter(){this.editor.updateDefaultShapeProps("geo",{geo:this.geo})}},by=class extends pf{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})}},Iy=class extends pf{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(yy)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.info.shapeId&&q(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(yy),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(yy),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=(r=e,o=this.tool.getDefaultProps(),new bg(r.x-o.w/2,r.y-o.h/2,o.w,o.h)),i=this.createShape(t);return void(this.info.shapeId=i.id)}var r,o;const s=((e,t,n)=>{let i=t.x-e.x,r=t.y-e.y;if(n){const e=Math.max(Math.abs(i),Math.abs(r));i=(i<0?-1:1)*e,r=(r<0?-1:1)*e}const o=new xg(e.x+i,e.y+r);return new bg(Math.min(e.x,o.x),Math.min(e.y,o.y),Math.max(Math.abs(o.x-e.x),1),Math.max(Math.abs(o.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}},vy=class extends xy{constructor(e){super(e,"rectangle","rectangle")}},Py=class extends xy{constructor(e){super(e,"ellipse","ellipse")}},wy=class extends xy{constructor(e){super(e,"diamond","diamond")}},ky=class extends xy{constructor(e){super(e,"triangle","triangle")}},Cy=class extends xy{constructor(e){super(e,"hexagon","hexagon")}},Ty=class extends xy{constructor(e){super(e,"star","star")}},Ey=["rectangle","ellipse","diamond","triangle","hexagon","star"],By=class extends uf{type="geo";getDefaultProps(){return{w:160,h:108,geo:"rectangle",fill:m("fill-slate"),stroke:m("stroke-slate"),strokeWidth:2}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,Xd(t.w,n.w)),h:Math.max(24,Xd(t.h,n.h)),geo:Yd(t.geo)?t.geo:n.geo,fill:v(t.fill,n.fill),stroke:v(t.stroke,n.stroke),strokeWidth:Math.max(1,Xd(t.strokeWidth,n.strokeWidth))}}getBounds(e){return new bg(e.x,e.y,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getPositionedOutlineVertices(e){return Hd(this.getBounds(e),e.props.geo)}getHandleSnapGeometry(e){return{points:Zd(e),outline:Gd(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 r=t.x-n.center.x,o=t.y-n.center.y;return r*r/(e*e)+o*o/(i*i)<=1}case"diamond":case"triangle":case"hexagon":case"star":return Nd(t,_d(n,e.props.geo));default:return Nd(t,_d(n,"rectangle"))}}hitTestLineSegment(e,t){const n=this.getBounds(e);switch(e.props.geo){case"ellipse":return((e,t,n,i)=>{const r=e.center,o=e.w/2+i,s=e.h/2+i;if(o<=0||s<=0)return!1;const a=n.sub(t),l=t.sub(r),d=a.x/o,c=a.y/s,u=l.x/o,h=l.y/s,p=d*d+c*c,g=2*(u*d+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),x=(-g+S)/(2*p);return y>=0&&y<=1||x>=0&&x<=1})(n,t.positionedStart,t.positionedEnd,t.margin);case"rectangle":case"diamond":case"triangle":case"hexagon":case"star":{const i=_d(n,e.props.geo);return this.hitTest(e,t.positionedStart)||this.hitTest(e,t.positionedEnd)||((e,t,n,i)=>{if(n.length<3)return!1;for(let r=0;r<n.length;r+=1){const o=n[r],s=n[(r+1)%n.length];if(o&&s&&qd(e,t,o,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 bg(e.x,e.y,e.props.w,e.props.h);return"ellipse"===e.props.geo?((e,t,n)=>{const i=e.w/2,r=e.h/2;if(i<=0||r<=0)return null;const o=t.sub(e.center),s=n.sub(t),a=s.x/i,l=s.y/r,d=o.x/i,c=o.y/r,u=a*a+l*l,h=2*(d*a+c*l),p=h*h-4*u*(d*d+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):((e,t,n)=>{let i=null;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=jd(e,t,o,s);!a||a.t<=1e-6||(!i||a.t<i.t)&&(i=a)}return i?.point??null})(t,n,_d(i,e.props.geo))}(e,Ze(e,t.rawPagePoint,this),Ze(e,t.oppositePagePoint,this));return n?Ge(e,n,this):t.rawPagePoint}},My=class{type="geo";toSvg(e,t){const{geo:n,fill:i,stroke:r,strokeWidth:o,w:s,h:a}=e.props,l=o/2,d=Math.max(s-o,0),c=Math.max(a-o,0),u={fill:t.resolveColor(i),stroke:t.resolveColor(r),"stroke-width":o,"stroke-linejoin":"round","stroke-linecap":"round"};if("ellipse"===n)return{tag:"ellipse",attrs:{...u,cx:s/2,cy:a/2,rx:d/2,ry:c/2}};if("rectangle"!==n){const e=_d(new bg(l,l,d,c),n).map(e=>`${ic(e.x)},${ic(e.y)}`).join(" ");return{tag:"polygon",attrs:{...u,points:e}}}const h=Math.min(10,.12*d,.12*c);return{tag:"rect",attrs:{...u,x:l,y:l,width:d,height:c,rx:h,ry:h}}}},Ay=[{value:m("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:m("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:m("fill-red"),label:"Red",color:"var(--land-shape-fill-red)"},{value:m("fill-white"),label:"White",color:"var(--land-shape-fill-white)"}],Ry=[{value:m("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:m("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:m("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:m("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],Ly=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Fy=[{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"}],$y=ir({name:"geo",createFeature:()=>({id:"land.geo.bundle",editorPlugins:[{id:"land.geo",shapeCapabilities:[{type:"geo",schemaProps:["w","h","geo","fill","stroke","strokeWidth"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Toolbar covers built-in geo variants through geo props."]}],shapeUtils:[new By],shapeSvgExporters:[new My],canvasActions:[{id:"geo.set-kind",isVisible:e=>"geo"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>(e=>{let t=null;for(const n of e)if(Wd(n))if(null!==t){if(t!==n.props.geo)return null}else t=n.props.geo;return t})(e.selection.selectedShapes),run({context:e,value:t}){if(!Yd(t))return;const n=e.selection.selectedShapes.filter(Wd).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{geo:t}}));0!==n.length&&e.editor.commands.updateShapes(n,{source:"user"})}},Qd("fill"),Qd("stroke"),Qd("strokeWidth"),Jd("fill"),Jd("stroke"),Jd("strokeWidth")],toolbarContributions:[{id:"geo.tool-toolbar",surface:"tool",placement:"chrome",order:20,actionIds:[zf],getGroups:e=>[{id:"geo.tools",items:[{kind:"segmented",id:"geo.tool-picker",actionId:zf,options:Fy.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=>nc(e.tool.activeToolId),getGroups:()=>ec({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"],when:e=>"geo"===e.selection.commonShapeType,getGroups:()=>[{id:"geo.shape-kind",items:[{kind:"segmented",id:"geo.shape-kind",actionId:"geo.set-kind",options:Fy.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-shape-button`}))}]},...ec({fillActionId:"geo.set-fill",strokeActionId:"geo.set-stroke",strokeWidthActionId:"geo.set-strokeWidth",dataUiPrefix:"geo"})]}],setup(e){e.tools.register("rectangle",e=>new vy(e),{shortcut:"r"}),e.tools.register("ellipse",e=>new Py(e),{shortcut:"o"}),e.tools.register("diamond",e=>new wy(e),{shortcut:"d"}),e.tools.register("triangle",e=>new ky(e)),e.tools.register("hexagon",e=>new Cy(e)),e.tools.register("star",e=>new Ty(e))}}],canvasPlugins:[{id:"land.geo.react",shapeRenderers:[{type:"geo",component:rc}]}],shapeTypes:["geo"]})}),Uy=class extends uf{type="group";getDefaultProps(){return{w:1,h:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:sc(t.w,n.w),h:sc(t.h,n.h)}}getBounds(e){return new bg(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}},Dy=class{type="group";toSvg(e){return{tag:"g"}}},zy=ir({name:"group",createFeature:()=>({id:"land.group.bundle",editorPlugins:[{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 Uy],shapeSvgExporters:[new Dy]}],canvasPlugins:[{id:"land.group.react",shapeRenderers:[{type:"group",component:ac}]}],shapeTypes:["group"]})}),Hy=1e-4,_y=1e-4,Ny="image.crop",Oy="image.crop.translate",Wy="image.crop:edit:",Yy=[{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}],Xy={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"},Ky=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],Vy=new Map,qy=class extends uf{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,Fc(t.w,n.w)),h:Math.max(24,Fc(t.h,n.h)),assetId:(i=t.assetId,"string"==typeof i&&i.startsWith("asset:")?t.assetId:null),crop:fc(t.crop),cornerRadius:dc(t.cornerRadius,n.cornerRadius),altText:"string"==typeof t.altText?t.altText:n.altText};var i}getBounds(e){return new bg(e.x,e.y,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getSelectionResizeAspectRatioLock(e,t){return!(!t.isOnlySelected||!Ft(t.handleId))||null}canEdit(e){return!0}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const i=t.editor.getShapeEditingSession();return i&&i.shapeId===e.id&&Pc(e,i.markId)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:kc({crop:e.props.crop,localToPage:t.editor.computeShapeLocalToPageTransform(e),shape:e})}:n}},jy="image.replace",Gy="image.download-original",Zy="image.insert",Qy="image.crop",Jy="image.crop.done",ex="image.crop.zoom",tx="image.crop.aspect-ratio",nx="image.crop.reset",ix="image.corner-radius",rx=class{type="image";toSvg(e,t){const{assetId:n,altText:i,crop:r,h:o,w:s}=e.props;if(!n)return null;const a=t.resolveAssetUrl(n);if(!a)return null;const l=mc(r),d=l?{tag:"svg",attrs:{x:0,y:0,width:s,height:o,viewBox:(c=l,[Tc(c.left),Tc(c.top),Tc(c.width),Tc(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:o,preserveAspectRatio:"none","aria-label":i||void 0}};var c;const u=cc({cornerRadius:e.props.cornerRadius,h:o,w:s});return u<=0?d:{tag:"g",attrs:{"clip-path":`url(#${t.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:0,y:0,width:s,height:o,rx:u,ry:u}}]})})`},children:[d]}}},ox={id:"land.image.crop.dom-events",handle:()=>"continue",getCursor({clientPoint:e,editor:t,element:n,container:i}){const r=(e=>{const[t]=e.getSelectedShapes();if(!Bc(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Pc(t,n.markId)?t:null})(t);if(!r)return;if(n?.closest('[data-selection-custom-handle-type="image.crop"]'))return;if(!e)return;const o=i.getBoundingClientRect(),s=new xg(e.x-o.left,e.y-o.top);return((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n);return i.x>=0&&i.y>=0&&i.x<=t.props.w&&i.y<=t.props.h})(t,r,t.screenToPage(s))?0!==t.inputs.state.get().buttons?"grabbing":"grab":void 0}},sx=ir({name:"image",createFeature:()=>({id:"land.image.bundle",editorPlugins:[$c()],canvasPlugins:[{id:"land.image.react",domEventGuards:[ox],selectionCustomHandleRenderers:[{type:Ny,component:Oc}],shapeRenderers:[{type:"image",component:_c}]}],shapeTypes:["image"]})}),ax=class extends pf{constructor(e){super(e,"laser"),this.initial="idle",this.addChild(new lx(e,this)),this.addChild(new dx(e,this)),this.addChild(new cx(e,this))}},lx=class extends pf{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 Xc(e,n),n})(this.editor,e))}},dx=class extends pf{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&&(Yc(this.info,e.pagePoint),Xc(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}},cx=class extends pf{info=null;constructor(e,t){super(e,"drawing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&(Yc(this.info,e.pagePoint),Xc(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}},ux=Yp(()=>Fr(Lr().laserTrailActiveSignal)?tg(hx,{}):null),hx=Yp(()=>{const e=Lr(),t=Fr(e.laserTrailSignal),n=Fr(e.cameraZoomSignal),i=Math.max(n,1e-4),r=(()=>{const[e,t]=Qp(()=>Kc());return Vp(()=>{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})(),o=Zp({sessionId:0,samples:[],sourceLength:0}),s=Math.max(r,Kc());let a,l=[];t&&(((e,t,n,i)=>{t.sessionId!==e.sessionId&&(e.sessionId=t.sessionId,e.samples=[],e.sourceLength=0);const r=t.points;if(qc(e,i),r.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),r.length===e.sourceLength)return;const o=e.sourceLength,s=r.length-o,a=e.samples[e.samples.length-1]?.time??i-vx*s;for(let l=o;l<r.length;l++){const t=r[l];Vc(e,{x:t.x,y:t.y},n,ou(a,i,(l-o+1)/s))}e.sourceLength=r.length,qc(e,i)})(o.current,t,i,s),l=function(e,t){const n=jc(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),i=[e[0]];for(let r=1;r<e.length;r++)i.push(ru(i[i.length-1],e[r],n));return i})(n.length>mx?n.slice(-64):n,xx)}(o.current.samples,s),a=o.current.samples[o.current.samples.length-1]?.time);const d="ending"===t?.phase,c=0===l.length,u=d&&c?t.sessionId:null;if(Vp(()=>{null!==u&&e.clearLaserTrail(u)},[e,u]),!t||c)return null;const h=d&&void 0!==a?su(1-(s-a)/Tx,0,1):1,p=(f=yx/i,0===(g=l).length||f<=0?null:1===g.length?lu(Zc(g[0],f/2,Ix))??"":lu((e=>{if(0===e.length)return[];if(1===e.length)return Zc(e[0].point,Math.max(e[0].radius,.01),Ix);const t=[],n=[];for(const a of e){const e=eu(a.direction);au(t,nu(a.point,iu(e,a.radius))),au(n,tu(a.point,iu(e,a.radius)))}const i=[];for(const a of t)au(i,a);const r=e[e.length-1],o=eu(r.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const r=[];for(let o=1;o<bx;o++){const s=o/bx;r.push(tu(e,tu(iu(t,Math.sin(Math.PI*s)*i),iu(n,-Math.cos(Math.PI*s)*i))))}return r})({center:r.point,direction:r.direction,normal:o,radius:r.radius});for(const a of s)au(i,a);for(let a=n.length-1;a>=0;a--)au(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]+Qc(e[n-1],e[n]));return t})(e),i=Math.max(t,n[n.length-1]??0);return e.map((r,o)=>{const s=n[o]??0,a=su(s/i,0,1);return{point:r,direction:Gc(e,o),radius:t/2*a,runningLength:s}})})(g,f))));var g,f;return p?ng("g",{"data-ui":"laser-trail-overlay",style:{opacity:h},children:[tg("path",{"data-ui":"laser-trail-glow",d:p,fill:gx,style:{filter:`blur(${fx/i}px)`}}),tg("path",{"data-ui":"laser-trail-beam",d:p,fill:px})]}):null}),px="rgb(255, 38, 38)",gx="rgba(255, 48, 48, 0.55)",fx=4,mx=64,Sx=1,yx=12,xx=.32,bx=8,Ix=13,vx=16,Px=8,wx=600,kx=300,Cx=1400,Tx=400,Ex=ir({name:"laser",createFeature:()=>({id:"land.laser.bundle",editorPlugins:[{id:"land.laser",toolbarContributions:[{id:"laser.tool-toolbar",surface:"tool",placement:"chrome",order:55,actionIds:[zf],getGroups:e=>[{id:"laser.tools",items:[{kind:"button",id:"laser.tool.laser",actionId:zf,value:"laser",label:"Laser",shortcut:e.editor.shortcuts.getToolShortcutLabel("laser"),icon:"wand",dataUi:"laser-tool-button"}]}]}],setup(e){e.tools.register("laser",e=>new ax(e),{shortcut:"l"})}}],canvasPlugins:[{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",layer:"below-host",component:ux}]}],shapeTypes:[]})}),Bx="path.node",Mx="path.control",Ax=new WeakMap,Rx="land.path.draftSubpathId",Lx="land.path.previewNodeId",Fx=["nonzero","evenodd"],$x=["corner","smooth","symmetric"],Ux="var(--land-selection, #2563eb)",Dx=cg((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),r=i,o=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;o.left=t,o=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;r.right=t,r=t,t=t.right}}return r.right=t.left,o.left=t.right,t.left=i.right,t.right=i.left,t}function n(e,n,i,r){var o=new c(e,n);if(null===i)return o.left=o.right=null,o;var s=r(e,(i=t(e,i,r)).key);return s<0?(o.left=i.left,o.right=i,i.left=null):s>=0&&(o.right=i.right,o.left=i,i.right=null),o}function i(e,n,i){var r=null,o=null;if(n){var s=i((n=t(e,n,i)).key,e);0===s?(r=n.left,o=n.right):s<0?(o=n.right,n.right=null,r=n):(r=n.left,n.left=null,o=n)}return{left:r,right:o}}function r(e,t,n,i,o){if(e){i(t+(n?"└── ":"├── ")+o(e)+"\n");var s=t+(n?" ":"│ ");e.left&&r(e.left,s,!1,i,o),e.right&&r(e.right,s,!0,i,o)}}function o(e,t,n,i){var r=i-n;if(r>0){var s=n+Math.floor(r/2),a=new c(e[s],t[s]);return a.left=o(e,t,n,s),a.right=o(e,t,s+1,i),a}return null}function s(e,t,n){var i=n-t;if(i>0){var r=t+Math.floor(i/2),o=s(e,t,r),a=e.head;return a.left=o,e.head=e.head.next,a.right=s(e,r+1,n),a}return null}function a(e,t,n,i,r){if(!(n>=i)){for(var o=e[n+i>>1],s=n-1,l=i+1;;){do{s++}while(r(e[s],o)<0);do{l--}while(r(e[l],o)>0);if(s>=l)break;var d=e[s];e[s]=e[l],e[l]=d,d=t[s],t[s]=t[l],t[l]=d}a(e,t,n,l,r),a(e,t,l+1,i,r)}}function l(e,t,n,i,r){let o,s,a,l,d=t[0],c=i[0],u=0,h=0;c>d==c>-d?(o=d,d=t[++u]):(o=c,c=i[++h]);let p=0;if(u<e&&h<n)for(c>d==c>-d?(s=d+o,a=o-(s-d),d=t[++u]):(s=c+o,a=o-(s-c),c=i[++h]),o=s,0!==a&&(r[p++]=a);u<e&&h<n;)c>d==c>-d?(s=o+d,l=s-o,a=o-(s-l)+(d-l),d=t[++u]):(s=o+c,l=s-o,a=o-(s-l)+(c-l),c=i[++h]),o=s,0!==a&&(r[p++]=a);for(;u<e;)s=o+d,l=s-o,a=o-(s-l)+(d-l),d=t[++u],o=s,0!==a&&(r[p++]=a);for(;h<n;)s=o+c,l=s-o,a=o-(s-l)+(c-l),c=i[++h],o=s,0!==a&&(r[p++]=a);return 0===o&&0!==p||(r[p++]=o),p}function d(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 l(t){void 0===t&&(t=e),this._root=null,this._size=0,this._comparator=t}return l.prototype.insert=function(e,t){return this._size++,this._root=n(e,t,this._root,this._comparator)},l.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 r=this._comparator,o=t(e,this._root,r),s=r(e,o.key);return 0===s?this._root=o:(s<0?(i.left=o.left,i.right=o,o.left=null):s>0&&(i.right=o.right,i.left=o,o.right=null),this._size++,this._root=i),this._root},l.prototype.remove=function(e){this._root=this._remove(e,this._root,this._comparator)},l.prototype._remove=function(e,n,i){var r;return null===n?null:0===i(e,(n=t(e,n,i)).key)?(null===n.left?r=n.right:(r=t(e,n.left,i)).right=n.right,this._size--,r):n},l.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},l.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},l.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},l.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},l.prototype.forEach=function(e,t){for(var n=this._root,i=[],r=!1;!r;)null!==n?(i.push(n),n=n.left):0!==i.length?(n=i.pop(),e.call(t,n),n=n.right):r=!0;return this},l.prototype.range=function(e,t,n,i){for(var r=[],o=this._comparator,s=this._root;0!==r.length||s;)if(s)r.push(s),s=s.left;else{if(o((s=r.pop()).key,t)>0)break;if(o(s.key,e)>=0&&n.call(i,s))return this;s=s.right}return this},l.prototype.keys=function(){var e=[];return this.forEach(t=>e.push(t.key)),e},l.prototype.values=function(){var e=[];return this.forEach(t=>e.push(t.data)),e},l.prototype.min=function(){return this._root?this.minNode(this._root).key:null},l.prototype.max=function(){return this._root?this.maxNode(this._root).key:null},l.prototype.minNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.left;)e=e.left;return e},l.prototype.maxNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.right;)e=e.right;return e},l.prototype.at=function(e){for(var t=this._root,n=!1,i=0,r=[];!n;)if(t)r.push(t),t=t.left;else if(r.length>0){if(t=r.pop(),i===e)return t;i++,t=t.right}else n=!0;return null},l.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 r=i(e.key,t.key);if(0===r)break;r<0?(n=t,t=t.left):t=t.right}return n},l.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 r=i(e.key,t.key);if(0===r)break;r<0?t=t.left:(n=t,t=t.right)}return n},l.prototype.clear=function(){return this._root=null,this._size=0,this},l.prototype.toList=function(){return(()=>{for(var e=this._root,t=[],n=!1,i=new c(null,null),r=i;!n;)e?(t.push(e),e=e.left):t.length>0?e=(e=r=r.next=t.pop()).right:n=!0;return r.next=null,i.next})()},l.prototype.load=function(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=!1);var i=e.length,r=this._comparator;if(n&&a(e,t,0,i-1,r),null===this._root)this._root=o(e,t,0,i),this._size=i;else{var l=((e,t,n)=>{for(var i=new c(null,null),r=i,o=e,s=t;null!==o&&null!==s;)n(o.key,s.key)<0?(r.next=o,o=o.next):(r.next=s,s=s.next),r=r.next;return null!==o?r.next=o:null!==s&&(r.next=s),i.next})(this.toList(),((e,t)=>{for(var n=new c(null,null),i=n,r=0;r<e.length;r++)i=i.next=new c(e[r],t[r]);return i.next=null,n.next})(e,t),r);this._root=s({head:l},0,i=this._size+i)}return this},l.prototype.isEmpty=function(){return null===this._root},Object.defineProperty(l.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),l.prototype.toString=function(e){void 0===e&&(e=e=>String(e.key));var t=[];return r(this._root,"",!0,e=>t.push(e),e),t.join("")},l.prototype.update=function(e,r,o){var s=this._comparator,a=i(e,this._root,s),l=a.left,d=a.right;s(e,r)<0?d=n(r,o,d,s):l=n(r,o,l,s),this._root=((e,n,i)=>null===n?e:(null===e||((n=t(e.key,n,i)).left=e),n))(l,d,s)},l.prototype.split=function(e){return i(e,this._root,this._comparator)},l.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,r&&(o=2&n[0]?r.return:n[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,n[1])).done)return o;switch(r=0,o&&(n=[2&n[0],o.value]),n[0]){case 0:case 1:o=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,r=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==n[0]&&2!==n[0])){a=0;continue}if(3===n[0]&&(!o||n[1]>o[0]&&n[1]<o[3])){a.label=n[1];break}if(6===n[0]&&a.label<o[1]){a.label=o[1],o=n;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(n);break}o[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}catch(s){n=[6,s],r=0}finally{i=o=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}})([n,s])}var i,r,o,s,a={label:0,sent:()=>{if(1&o[0])throw o[1];return o[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]}})},l}();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)}}},x=134217729,b=d(4),I=d(8),v=d(12),P=d(16),w=d(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,r,o){const s=(t-o)*(n-r),a=(e-r)*(i-o),d=s-a,c=Math.abs(s+a);return Math.abs(d)>=33306690738754716e-32*c?d:-((e,t,n,i,r,o,s)=>{let a,d,c,u,h,p,g,f,m,S,y,k,C,T,E,B,M,A;const R=e-r,L=n-r,F=t-o,$=i-o;T=R*$,p=x*R,g=p-(p-R),f=R-g,p=x*$,m=p-(p-$),S=$-m,E=f*S-(T-g*m-f*m-g*S),B=F*L,p=x*F,g=p-(p-F),f=F-g,p=x*L,m=p-(p-L),S=L-m,M=f*S-(B-g*m-f*m-g*S),y=E-M,h=E-y,b[0]=E-(y+h)+(h-M),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-B,h=C-y,b[1]=C-(y+h)+(h-B),A=k+y,h=A-k,b[2]=k-(A-h)+(y-h),b[3]=A;let U=((e,t)=>{let n=t[0];for(let i=1;i<4;i++)n+=t[i];return n})(0,b),D=22204460492503146e-32*s;if(U>=D||-U>=D)return U;if(h=e-R,a=e-(R+h)+(h-r),h=n-L,c=n-(L+h)+(h-r),h=t-F,d=t-(F+h)+(h-o),h=i-$,u=i-($+h)+(h-o),0===a&&0===d&&0===c&&0===u)return U;if(D=11093356479670487e-47*s+33306690738754706e-32*Math.abs(U),U+=R*u+$*a-(F*c+L*d),U>=D||-U>=D)return U;T=a*$,p=x*a,g=p-(p-a),f=a-g,p=x*$,m=p-(p-$),S=$-m,E=f*S-(T-g*m-f*m-g*S),B=d*L,p=x*d,g=p-(p-d),f=d-g,p=x*L,m=p-(p-L),S=L-m,M=f*S-(B-g*m-f*m-g*S),y=E-M,h=E-y,w[0]=E-(y+h)+(h-M),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-B,h=C-y,w[1]=C-(y+h)+(h-B),A=k+y,h=A-k,w[2]=k-(A-h)+(y-h),w[3]=A;const z=l(4,b,4,w,I);T=R*u,p=x*R,g=p-(p-R),f=R-g,p=x*u,m=p-(p-u),S=u-m,E=f*S-(T-g*m-f*m-g*S),B=F*c,p=x*F,g=p-(p-F),f=F-g,p=x*c,m=p-(p-c),S=c-m,M=f*S-(B-g*m-f*m-g*S),y=E-M,h=E-y,w[0]=E-(y+h)+(h-M),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-B,h=C-y,w[1]=C-(y+h)+(h-B),A=k+y,h=A-k,w[2]=k-(A-h)+(y-h),w[3]=A;const H=l(z,I,4,w,v);return T=a*u,p=x*a,g=p-(p-a),f=a-g,p=x*u,m=p-(p-u),S=u-m,E=f*S-(T-g*m-f*m-g*S),B=d*c,p=x*d,g=p-(p-d),f=d-g,p=x*c,m=p-(p-c),S=c-m,M=f*S-(B-g*m-f*m-g*S),y=E-M,h=E-y,w[0]=E-(y+h)+(h-M),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-B,h=C-y,w[1]=C-(y+h)+(h-B),A=k+y,h=A-k,w[2]=k-(A-h)+(y-h),w[3]=A,P[l(H,v,4,w,P)-1]})(e,t,n,i,r,o,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},r={x:n.x-e.x,y:n.y-e.y};return k(r,i)/E(r)/E(i)},M=(e,t,n)=>{const i={x:t.x-e.x,y:t.y-e.y},r={x:n.x-e.x,y:n.y-e.y};return C(r,i)/E(r)/E(i)},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 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:r,cosine:o}=t.get(e),{sine:s,cosine:a}=t.get(i);return r>=0&&s>=0?o<a?1:o>a?-1:0:r<0&&s<0?o<a?-1:o>a?1:0:s<r?-1:s>r?1:0}}}let F=0;class ${static compare(e,t){const n=e.leftSE.point.x,i=t.leftSE.point.x,r=e.rightSE.point.x,o=t.rightSE.point.x;if(o<n)return 1;if(r<i)return-1;const s=e.leftSE.point.y,a=t.leftSE.point.y,l=e.rightSE.point.y,d=t.rightSE.point.y;if(n<i){if(a<s&&a<l)return 1;if(a>s&&a>l)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<d)return-1;if(s>a&&s>d)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(r<o){const n=t.comparePoint(e.rightSE.point);if(0!==n)return n}if(r>o){const n=e.comparePoint(t.rightSE.point);if(n<0)return 1;if(n>0)return-1}if(r!==o){const e=l-s,t=r-n,c=d-a,u=o-i;if(e>t&&c<u)return 1;if(e<t&&c>u)return-1}return r>o?1:r<o||l<d?-1:l>d?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,r,o;const s=L.comparePoints(e,t);if(s<0)i=e,r=t,o=1;else{if(!(s>0))throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);i=t,r=e,o=-1}return new $(new L(i,!0),new L(r,!1),[n],[o])}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 r=t.y+(e.x-t.x)/i.x*i.y;return e.y===r?0:e.y<r?-1:1}getIntersection(e){const t=this.bbox(),n=e.bbox(),i=p(t,n);if(null===i)return null;const r=this.leftSE.point,o=this.rightSE.point,s=e.leftSE.point,a=e.rightSE.point,l=h(t,s)&&0===this.comparePoint(s),d=h(n,r)&&0===e.comparePoint(r),c=h(t,a)&&0===this.comparePoint(a),u=h(n,o)&&0===e.comparePoint(o);if(d&&l)return u&&!c?o:!u&&c?a:null;if(d)return c&&r.x===a.x&&r.y===a.y?null:r;if(l)return u&&o.x===s.x&&o.y===s.y?null:s;if(u&&c)return null;if(u)return o;if(c)return a;const g=((e,t,n,i)=>{if(0===t.x)return R(n,i,e.x);if(0===i.x)return R(e,t,n.x);if(0===t.y)return A(n,i,e.y);if(0===i.y)return A(e,t,n.y);const r=k(t,i);if(0==r)return null;const o={x:n.x-e.x,y:n.y-e.y},s=k(o,t)/r,a=k(o,i)/r;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}})(r,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),r=new L(e,!1),o=this.rightSE;this.replaceRightSE(r),t.push(r),t.push(i);const s=new $(i,o,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(),r.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],r=n.windings[e],o=t.rings.indexOf(i);-1===o?(t.rings.push(i),t.windings.push(r)):t.windings[o]+=r}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],r=t.indexOf(e);-1===r?(t.push(e),n.push(i)):n[r]+=i}const r=[],o=[];for(let s=0,a=t.length;s<a;s++){if(0===n[s])continue;const e=t[s],i=e.poly;if(-1===o.indexOf(i))if(e.isExterior)r.push(i);else{-1===o.indexOf(i)&&o.push(i);const t=r.indexOf(e.poly);-1!==t&&r.splice(t,1)}}for(let s=0,a=r.length;s<a;s++){const e=r[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 r=i;for(let o=1,s=e.length;o<s;o++){if("number"!=typeof e[o][0]||"number"!=typeof e[o][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let t=y.round(e[o][0],e[o][1]);t.x===r.x&&t.y===r.y||(this.segments.push($.fromRing(r,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),r=t)}i.x===r.x&&i.y===r.y||this.segments.push($.fromRing(r,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,r=e.length;i<r;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 H{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 r=null,o=i.leftSE,s=i.rightSE;const a=[o],l=o.point,d=[];for(;r=o,o=s,a.push(o),o.point!==l;)for(;;){const e=o.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,r=d.length;t<r;t++)if(d[t].point===o.point){n=t;break}if(null!==n){const e=d.splice(n)[0],i=a.splice(e.index);i.unshift(i[0].otherSE),t.push(new H(i.reverse()));continue}d.push({index:a.length,point:o.point});const i=o.getLeftmostComparator(r);s=e.sort(i)[0].otherSE;break}t.push(new H(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,r=this.isExteriorRing()?t.length:-1,o=[];for(let s=i;s!=r;s+=n)o.push([t[s].x,t[s].y]);return o}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,r=this.events.length;i<r;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 _{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 _(i));else{const e=i.enclosingRing();e.poly||t.push(new _(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 r,o,s=i,a=i;for(;void 0===r;)s=this.tree.prev(s),null===s?r=null:void 0===s.key.consumedBy&&(r=s.key);for(;void 0===o;)a=this.tree.next(a),null===a?o=null:void 0===a.key.consumedBy&&(o=a.key);if(e.isLeft){let i=null;if(r){const e=r.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(i=e),!r.isAnEndpoint(e))){const t=this._splitSafely(r,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}}let s=null;if(o){const e=o.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(s=e),!o.isAnEndpoint(e))){const t=this._splitSafely(o,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 r=t.split(e);for(let t=0,i=r.length;t<i;t++)n.push(r[t])}n.length>0?(this.tree.remove(t),n.push(e)):(this.segments.push(t),t.prev=r)}else{if(r&&o){const e=r.getIntersection(o);if(null!==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])}if(!o.isAnEndpoint(e)){const t=this._splitSafely(o,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 l=0,d=n.length;l<d;l++)i.push(new z(n[l],!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 l=0,d=i.length;l<d;l++){const e=i[l];for(let t=l+1,n=i.length;t<n;t++)if(null===p(e.bbox,i[t].bbox))return[]}const r=new u(L.compare);for(let l=0,d=i.length;l<d;l++){const e=i[l].getSweepEvents();for(let t=0,n=e.length;t<n;t++)if(r.insert(e[t]),r.size>W)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const o=new O(r);let s=r.size,a=r.pop();for(;a;){const e=a.key;if(r.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(r.size>W)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(o.segments.length>Y)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const t=o.process(e);for(let n=0,i=t.length;n<i;n++){const e=t[n];void 0===e.consumedBy&&r.insert(e)}s=r.size,a=r.pop()}return y.reset(),new N(H.factory(o.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()})(),zx=1,Hx=1,_x="path.insert-node",Nx=1,Ox=class extends uf{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:m("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{subpaths:(i=ph(t.subpaths,n.subpaths),i.map(e=>({...e,nodes:e.nodes.filter(e=>xu(e.x)&&xu(e.y))})).filter(e=>e.nodes.length>0).map(vu)),fill:v(t.fill,n.fill),stroke:v(t.stroke,n.stroke),strokeWidth:Math.max(1,uh(t.strokeWidth,n.strokeWidth)),fillRule:ju(t.fillRule)?t.fillRule:n.fillRule};var i}getBounds(e){const t=Fu(e).localBounds;return new bg(e.x+t.x,e.y+t.y,t.w,t.h)}getLocalBounds(e){return Fu(e).localBounds}getRenderBounds(e){return Fu(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}getSelectionResizeLocalBounds(e){return Fu(e).pointBounds}resizeSelectionBounds(e,t){const n=zu(e,this.getLocalToPageTransform(e)).map(e=>({...e,nodes:e.nodes.map(e=>fh(e,e=>((e,t)=>0===t.selectionRotation?e:xg.RotWith(e,t.selectionRotationCenter,-t.selectionRotation))(e,t)))})),i=Du(((e,t)=>{const n=Fu(e).pointBounds,i=0===n.w?1:t.w/Math.max(n.w,1e-6),r=0===n.h?1:t.h/Math.max(n.h,1e-6);return Uu(e.props.subpaths,e=>new xg(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)*r))})({...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=>fh(e,e=>((e,t)=>0===t.selectionRotation?e:xg.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 Fu(e).outlineVertices.map(t=>new xg(e.x+t.x,e.y+t.y))}getHandleSnapGeometry(e){return{points:e.props.subpaths.flatMap(e=>e.nodes.flatMap(e=>[wu(e),...e.in?[ku(e)]:[],...e.out?[Cu(e)]:[]])),outline:Fu(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 r=t.editor.computeShapeLocalToPageTransform(e);return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=[{kind:"custom",type:Bx,id:(i=e.id,o=t.id,["node",i,o].map(encodeURIComponent).join("|")),point:r.applyToPoint(wu(t)),cursor:"grab"}];var i,o;return t.in&&n.push({kind:"custom",type:Mx,id:hu(e.id,t.id,"in"),point:r.applyToPoint(ku(t)),cursor:"grab"}),t.out&&n.push({kind:"custom",type:Mx,id:hu(e.id,t.id,"out"),point:r.applyToPoint(Cu(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:Hu(e,t.editor.computeShapeLocalToPageTransform(e)),bindingSegments:[]}:{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,bindingSegments:[]}}hitTest(e,t,n){const i=new xg(t.x-e.x,t.y-e.y),r=Fu(e);return!k(e.props.fill)&&((e,t,n)=>{let i=0,r=0;for(const o of e)if(o.closed&&!(o.points.length<3))for(let e=0;e<o.points.length;e+=1){const n=o.points[e],s=o.points[(e+1)%o.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&&(r+=1,i+=s.y>n.y?1:-1)}return"evenodd"===n?r%2==1:0!==i})(r.flattenedSubpaths,i,e.props.fillRule)||((e,t,n)=>{const i=n*n;for(const r of e)for(let e=1;e<r.points.length;e+=1){const n=r.points[e-1],o=r.points[e];if(n&&o&&Nu(t,n,o)<=i)return!0}return!1})(r.flattenedSubpaths,i,e.props.strokeWidth/2+6)}hitTestLineSegment(e,t){const n=new xg(t.positionedStart.x-e.x,t.positionedStart.y-e.y),i=new xg(t.positionedEnd.x-e.x,t.positionedEnd.y-e.y),r=t.margin+e.props.strokeWidth/2;return Fu(e).flattenedSubpaths.some(e=>((e,t,n,i)=>{const r=i*i;for(let o=1;o<n.length;o+=1){const i=n[o-1],s=n[o];if(i&&s&&(gh(i,e,t)<=r||gh(s,e,t)<=r||gh(e,i,s)<=r||gh(t,i,s)<=r))return!0}return!1})(n,i,e.points,r))}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]}}},Wx="path.create",Yx=1,Xx=1,Kx=class extends pf{draft=null;constructor(e){super(e,"path"),this.initial="idle",this.addChild(new Vx(e,this)),this.addChild(new qx(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(Wx);const t=this.editor.getDefaultShapeProps("path"),n=`subpath:${Xx+=1}`,i=mh(),[r]=this.editor.commands.createShapes([{type:"path",x:e.x,y:e.y,meta:Ku({},{subpathId:n,previewNodeId:null}),props:{...t,subpaths:[{id:n,closed:!1,nodes:[{id:i,x:0,y:0,kind:"corner"}]}]}}],{source:"user"});if(!r)throw new Error("Failed to create path shape");return this.editor.commands.setSelectedShapeIds([r.id],{source:"system"}),this.draft={shapeId:r.id,subpathId:n,lastNodeId:i,createdShape:!0,previewNodeId:null},{shapeId:r.id,subpathId:n,nodeId:i,originPagePoint:e.clone()}}const t=this.editor.getShape(this.draft.shapeId);if(!qu(t))return this.cancelDraft(),null;if(function(e,t,n,i,r){const o=((e,t,n)=>{const i=Ou(t.props.subpaths,n)?.nodes[0];return i?e.computeShapeLocalToPageTransform(t).applyToPoint(new xg(i.x,i.y)):null})(e,t,n),s=Ou(t.props.subpaths,n),a=s?.nodes.filter(e=>e.id!==i).length??0;return!(!o||!s||a<3)&&o.dist(r)<=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:Vu(t.meta),props:{subpaths:yh(t.props.subpaths,e).map(t=>t.id===e.subpathId?{...t,closed:!0}:t)}}],{source:"user"}),this.finishDraft(),null}const n=Sh(this.editor,t,e),i=this.draft.previewNodeId??mh(),r=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:Ku(t.meta,{subpathId:this.draft.subpathId,previewNodeId:null}),props:{subpaths:r}}],{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(!qu(n))return;const i=Sh(this.editor,n,e.originPagePoint),r=Sh(this.editor,n,t),o=Wu(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,r));this.editor.commands.updateShapes([{id:n.id,meta:Ku(n.meta,{subpathId:e.subpathId,previewNodeId:this.draft?.previewNodeId??null}),props:{subpaths:o}}],{source:"user"})}updatePreview(e){if(!this.draft)return;const t=this.editor.getShape(this.draft.shapeId);if(!qu(t)||xh(t,this.draft)<1)return;const n=Sh(this.editor,t,e),i=this.draft.previewNodeId??mh(),r=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:Ku(t.meta,{subpathId:this.draft.subpathId,previewNodeId:i}),props:{subpaths:r}}],{source:"user"}),this.draft={...this.draft,previewNodeId:i}}canFinishDraft(){if(!this.draft)return!1;const e=this.editor.getShape(this.draft.shapeId);return!!qu(e)&&xh(e,this.draft)>=2}finishDraft(e={}){if(!this.draft)return;const t=e.switchToSelect??!0,n=this.editor.getShape(this.draft.shapeId);if(qu(n)){const e=yh(n.props.subpaths,this.draft),t=Du(zu({...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:Vu(n.meta),props:{subpaths:t.subpaths}}],{source:"user"}),this.draft.createdShape&&q(this.editor,n.id,{source:"user"})}this.editor.history.squashToMark(Wx,"shape.create"),this.draft=null,t&&!this.editor.isToolLocked()&&this.editor.commands.setActiveTool("select",{source:"system"})}cancelDraft(){this.draft&&(this.editor.history.bailToMark(Wx),this.draft=null)}hasDraft(){return null!==this.draft}},Vx=class extends pf{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()}},qx=class extends pf{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}},jx="path.edit",Gx="path.boolean.union",Zx="path.boolean.subtract",Qx="path.boolean.intersect",Jx="path.boolean.xor",eb=[{value:"transparent",label:"None",color:"transparent"},{value:m("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:m("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:m("fill-red"),label:"Red",color:"var(--land-shape-fill-red)"},{value:m("fill-white"),label:"White",color:"var(--land-shape-fill-white)"}],tb=[{value:m("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:m("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:m("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:m("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],nb=[{value:1,label:"1"},{value:2,label:"2"},{value:3,label:"3"},{value:5,label:"5"},{value:8,label:"8"}],ib=[{value:"nonzero",label:"Nonzero"},{value:"evenodd",label:"Even odd"}],rb=class{type="path";toSvg(e,t){const n=Fu(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}},ob=[["geo",$y],["draw",OS],["arrow",CS],["eraser",ay],["laser",Ex],["path",ir({name:"path",createFeature:()=>({id:"land.path.bundle",editorPlugins:[{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 Ox],shapeSvgExporters:[new rb],interactionHandlers:[ch()],canvasActions:[Ih("fill"),Ih("stroke"),Ih("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(qu(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(!ju(t))return;const n=e.selection.selectedShapes.filter(qu).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{fillRule:t}}));n.length>0&&e.editor.commands.updateShapes(n,{source:"user"})}},vh("fill"),vh("stroke"),vh("strokeWidth"),{id:"path.default-fillRule",isVisible:e=>"path"===e.tool.activeToolId,getValue:e=>e.editor.getDefaultShapeProps("path").fillRule,run({context:e,value:t}){ju(t)&&e.editor.updateDefaultShapeProps("path",{fillRule:t})}},{id:jx,isVisible:e=>1===e.selection.count&&"path"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return qu(t)&&!t.isLocked},run({context:e}){const[t]=e.selection.selectedShapes;qu(t)&&e.editor.startEditingShape({shapeId:t.id,markId:"path.edit",entryMode:"focusEnd"},"user")}},Ph("union"),Ph("subtract"),Ph("intersect"),Ph("xor")],toolbarContributions:[{id:"path.tool-toolbar",surface:"tool",placement:"chrome",order:47,actionIds:[zf],getGroups:e=>[{id:"path.tools",items:[{kind:"button",id:"path.tool.path",actionId:zf,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:()=>bh({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:[jx,"path.set-fill","path.set-stroke","path.set-strokeWidth","path.set-fillRule",Gx,Zx,Qx,Jx],when:e=>"path"===e.selection.commonShapeType,getGroups(e){const t=[{id:"path.edit",items:[{kind:"button",id:"path.edit",actionId:jx,label:"Edit",icon:"square-pen",dataUi:"path-edit-button"}]},...bh({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",fillRuleActionId:"path.set-fillRule",dataUiPrefix:"path"})];return wh(e).length>=2&&t.push({id:"path.boolean",items:[{kind:"button",id:"path.boolean.union",actionId:Gx,label:"Union",icon:"group",dataUi:"path-boolean-union-button"},{kind:"button",id:"path.boolean.subtract",actionId:Zx,label:"Subtract",icon:"minus",dataUi:"path-boolean-subtract-button"},{kind:"button",id:"path.boolean.intersect",actionId:Qx,label:"Intersect",icon:"crop",dataUi:"path-boolean-intersect-button"},{kind:"button",id:"path.boolean.xor",actionId:Jx,label:"Exclude",icon:"ungroup",dataUi:"path-boolean-xor-button"}]}),t}},{id:"path.floating-selection-toolbar",surface:"selection",placement:"floating",order:22,actionIds:[jx,"path.set-fill","path.set-stroke","path.set-strokeWidth","path.set-fillRule",Gx,Zx,Qx,Jx],when:e=>"path"===e.selection.commonShapeType,getGroups(e){const t=[{id:"path.floating-edit",items:[{kind:"button",id:"path.floating-edit",actionId:jx,label:"Edit",icon:"square-pen",dataUi:"floating-path-edit-button"}]},...bh({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",fillRuleActionId:"path.set-fillRule",dataUiPrefix:"floating-path"})];return wh(e).length>=2&&t.push({id:"path.floating-boolean",items:[{kind:"button",id:"path.floating-boolean.union",actionId:Gx,label:"Union",icon:"group",dataUi:"floating-path-boolean-union-button"},{kind:"button",id:"path.floating-boolean.subtract",actionId:Zx,label:"Subtract",icon:"minus",dataUi:"floating-path-boolean-subtract-button"},{kind:"button",id:"path.floating-boolean.intersect",actionId:Qx,label:"Intersect",icon:"crop",dataUi:"floating-path-boolean-intersect-button"},{kind:"button",id:"path.floating-boolean.xor",actionId:Jx,label:"Exclude",icon:"ungroup",dataUi:"floating-path-boolean-xor-button"}]}),t}}],contextMenuContributions:[{id:"path.context-menu",target:"selection",order:38,actionIds:[jx,Gx,Zx,Qx,Jx],when:e=>"path"===e.selection.commonShapeType,getSections(e){const t=[{kind:"command",id:"path.edit",actionId:jx,label:"Edit path",icon:"square-pen",dataUi:"path-context-edit"}];return wh(e).length>=2&&t.push({kind:"command",id:"path.boolean.union",actionId:Gx,label:"Union paths",icon:"group",dataUi:"path-context-boolean-union"},{kind:"command",id:"path.boolean.subtract",actionId:Zx,label:"Subtract paths",icon:"minus",dataUi:"path-context-boolean-subtract"},{kind:"command",id:"path.boolean.intersect",actionId:Qx,label:"Intersect paths",icon:"crop",dataUi:"path-context-boolean-intersect"},{kind:"command",id:"path.boolean.xor",actionId:Jx,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 Kx(e),{shortcut:"b"})}}],canvasPlugins:[{id:"land.path.react",canvasOverlays:[{id:"land.path.draft-overlay",component:Gu,layer:"above-host",order:20}],shapeRenderers:[{type:"path",component:th}],selectionCustomHandleRenderers:[{type:Bx,component:nh},{type:Mx,component:ih}]}],shapeTypes:["path"]})})],["image",sx],["text",pS],["frame",Sy],["group",zy]],sb="land.canvas.persistence",ab="snapshots",lb="imageBlobs",db=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,qh(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()}},cb="image-blob:",ub=Yp(({editor:e,hostBridge:t,imageAssetService:n,flushSnapshot:i})=>{const r=Zp(null),o=Zp(null),{insertImageFromFile:s,replaceSelectedImage:a}=(({editor:e,imageAssetService:t,flushSnapshot:n})=>({insertImageFromFile:Xp(async({file:i,pagePoint:r,size:o,source:s})=>up({editor:e,file:i,imageObjectUrls:t.objectUrls,pagePoint:r,size:o,flushSnapshot:n,source:s}),[e,t,n]),replaceSelectedImage:Xp(i=>hp({editor:e,file:i,imageObjectUrls:t.objectUrls,flushSnapshot:n}),[e,t,n])}))({editor:e,imageAssetService:n,flushSnapshot:i});return Vp(()=>{if(t)return t.register({openInsertFilePicker(){r.current?.click()},openReplaceFilePicker(){o.current?.click()}})},[t]),Vp(()=>{const t=t=>{if(e.shapeEditingStateSignal.get().session)return;if(Zr(t.target))return;const n=ap(t.clipboardData);n&&(t.preventDefault(),s({file:n,source:"paste"}))},n=t=>{var n;e.shapeEditingStateSignal.get().session||Zr(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(Zr(t.target))return;const n=ap(t.dataTransfer);n&&(t.preventDefault(),s({file:n,pagePoint:lp(e,t),source:"drop"}))};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]),ng(eg,{children:[tg("input",{ref:r,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,source:"file-picker"})}}),tg("input",{ref:o,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)}})]})}),hb=fp("canvas-kit.clipboard-service"),pb="system.clipboard.copy",gb="system.clipboard.cut",fb="system.clipboard.paste",mb="system.clipboard.paste-at-point",Sb=[{actionId:pb,shortcut:{key:"c",accelKey:!0}},{actionId:gb,shortcut:{key:"x",accelKey:!0}},{actionId:fb,shortcut:{key:"v",accelKey:!0}}],yb="system.view.zoom-in",xb="system.view.zoom-out",bb="system.view.reset-zoom",Ib=[{id:yb,run({context:e}){e.editor.zoomAtViewportCenter(-120,"system")}},{id:xb,run({context:e}){e.editor.zoomAtViewportCenter(120,"system")}},{id:bb,run({context:e}){e.editor.resetZoom("user")}}],vb="system.selection.delete",Pb="system.selection.duplicate",wb="system.selection.group",kb="system.selection.select-all",Cb="system.selection.ungroup",Tb="system.selection.reset-rotation",Eb="system.selection.flip-horizontal",Bb="system.selection.flip-vertical",Mb="system.selection.send-to-back",Ab="system.selection.send-backward",Rb="system.selection.bring-forward",Lb="system.selection.bring-to-front",Fb="system.selection.set-opacity",$b=[{actionId:Pb,shortcut:{key:"d",accelKey:!0}},{actionId:kb,shortcut:{key:"a",accelKey:!0}},{actionId:wb,shortcut:{key:"g",accelKey:!0}},{actionId:Cb,shortcut:{key:"g",accelKey:!0,shiftKey:!0}}],Ub=[{id:zf,getValue:e=>e.tool.activeToolId,run({context:e,value:t}){"string"==typeof t&&e.editor.tools.hasTool(t)&&e.editor.setActiveTool(t,"system")}},{id:Hf,getValue:e=>e.tool.isToolLocked,run({context:e}){e.editor.toggleToolLocked("system")}},{id:Pb,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.duplicateSelection({source:"user"})}},{id:kb,isEnabled:e=>e.editor.getCurrentPageShapeIds().length>0,run({context:e}){e.editor.selectAllCurrentPage("user")}},{id:wb,isVisible:e=>e.selection.count>0,isEnabled:e=>e.editor.canGroupSelection(),run({context:e}){e.editor.groupSelection("user")}},{id:Cb,isVisible:e=>e.editor.canUngroupSelection(),isEnabled:e=>e.editor.canUngroupSelection(),run({context:e}){e.editor.ungroupSelection("user")}},{id:Tb,isVisible:e=>e.selection.canResetRotation,run({context:e}){e.editor.resetSelectionRotation("user")}},{id:Eb,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("horizontal","user")}},{id:Bb,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("vertical","user")}},{id:Mb,isVisible:e=>e.selection.count>0&&!Ip(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("back","user")}},{id:Ab,isVisible:e=>e.selection.count>0&&!Ip(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionInParentOrder("backward","user")}},{id:Rb,isVisible:e=>e.selection.count>0&&!Ip(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionInParentOrder("forward","user")}},{id:Lb,isVisible:e=>e.selection.count>0&&!Ip(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("front","user")}},{id:Fb,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=vp(t.opacity);return e.selection.selectedShapes.every(e=>vp(e.opacity)===n)?n:null})(e),run({context:e,value:t}){if("number"!=typeof t||!Number.isFinite(t))return;const n=vp(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:vb,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.deleteSelection("user")}}],Db=[zf,Hf,pb,gb,fb,mb,Pb,kb,vb,wb,Cb,Tb,Eb,Bb,Mb,Ab,Rb,Lb,bb,yb,xb],zb=[{id:"system.select-tool-toolbar",surface:"tool",placement:"chrome",order:0,actionIds:[zf],getGroups:e=>[{id:"system.select-tool",items:[{kind:"button",id:"system.select-tool",actionId:zf,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:zf,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:[Hf],getGroups:e=>[{id:"system.tool-lock",items:[{kind:"separator",id:"system.tool-lock-separator"},{kind:"button",id:"system.tool-lock",actionId:Hf,value:!0,label:e.tool.isToolLocked?"Unlock tool":"Lock tool",icon:"lock",dataUi:"tool-lock-button"}]}]},{id:"system.selection-toolbar",surface:"selection",order:1e3,actionIds:[Tb,Eb,Bb,Mb,Ab,Rb,Lb,Fb,wb,Cb,vb],getGroups(e){const t=e.selection.count>0&&!Ip(e);return[{id:"system.selection-opacity",items:[{kind:"slider",id:"system.selection-opacity",actionId:Fb,label:"Opacity",min:0,max:1,step:.01,dataUi:"selection-opacity-slider"}]},{id:"system.selection-actions",items:[...e.selection.canResetRotation?[{kind:"button",id:Tb,actionId:Tb,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:Eb,actionId:Eb,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"flip-selection-horizontal-button"},{kind:"button",id:Bb,actionId:Bb,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"flip-selection-vertical-button"},{kind:"separator",id:"system.selection.flip-order-separator"},...t?[{kind:"button",id:Mb,actionId:Mb,label:"Send to back",icon:"chevrons-down",dataUi:"send-selection-to-back-button"},{kind:"button",id:Ab,actionId:Ab,label:"Send backward",icon:"move-down",dataUi:"send-selection-backward-button"},{kind:"button",id:Rb,actionId:Rb,label:"Bring forward",icon:"move-up",dataUi:"bring-selection-forward-button"},{kind:"button",id:Lb,actionId:Lb,label:"Bring to front",icon:"chevrons-up",dataUi:"bring-selection-to-front-button"},{kind:"separator",id:"system.selection.order-delete-separator"}]:[],{kind:"button",id:wb,actionId:wb,label:"Group",icon:"group",dataUi:"group-selection-button"},{kind:"button",id:Cb,actionId:Cb,label:"Ungroup",icon:"ungroup",dataUi:"ungroup-selection-button"},{kind:"separator",id:"system.selection.group-delete-separator"},{kind:"button",id:vb,actionId:vb,label:"Delete selection",icon:"trash-2",dataUi:"delete-selection-toolbar-button"}]}]}}],Hb=[{id:"system.selection-clipboard-context-menu",target:"selection",order:1e3,actionIds:[pb,gb],getSections:e=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:pb,actionId:pb,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(pb),dataUi:"context-menu-copy-selection-button"},{kind:"command",id:gb,actionId:gb,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(gb),dataUi:"context-menu-cut-selection-button"}]}]},{id:"system.canvas-clipboard-context-menu",target:"canvas",order:1e3,actionIds:[mb],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:mb,actionId:mb,label:"Paste here",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(fb),dataUi:"context-menu-paste-here-button"}]}]},{id:"system.selection-context-menu",target:"selection",order:1010,actionIds:[Pb,wb,Cb,Tb,Eb,Bb,Lb,Rb,Ab,Mb,vb],getSections(e){const t=e.selection.count>0&&!Ip(e),n=[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:Pb,actionId:Pb,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(Pb),dataUi:"context-menu-duplicate-selection-button"},{kind:"separator",id:"system.selection-clipboard-separator"},{kind:"command",id:wb,actionId:wb,label:"Group",icon:"group",dataUi:"context-menu-group-selection-button"},{kind:"command",id:Cb,actionId:Cb,label:"Ungroup",icon:"ungroup",dataUi:"context-menu-ungroup-selection-button"},{kind:"command",id:vb,actionId:vb,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:Tb,actionId:Tb,label:"Reset rotation",icon:"rotate-ccw",dataUi:"context-menu-reset-rotation-button"},{kind:"command",id:Eb,actionId:Eb,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"context-menu-flip-horizontal-button"},{kind:"command",id:Bb,actionId:Bb,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:Lb,actionId:Lb,label:"Bring to front",icon:"chevrons-up",dataUi:"context-menu-bring-to-front-button"},{kind:"command",id:Rb,actionId:Rb,label:"Bring forward",icon:"move-up",dataUi:"context-menu-bring-forward-button"},{kind:"command",id:Ab,actionId:Ab,label:"Send backward",icon:"move-down",dataUi:"context-menu-send-backward-button"},{kind:"command",id:Mb,actionId:Mb,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:[kb],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:kb,actionId:kb,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(kb),dataUi:"context-menu-select-all-button"}]}]},{id:"system.canvas-view-context-menu",target:"canvas",order:1010,actionIds:[yb,xb,bb],getSections:()=>[{id:"system.canvas-view",title:"View",order:10,items:[{kind:"command",id:yb,actionId:yb,label:"Zoom in",icon:"plus",dataUi:"context-menu-zoom-in-button"},{kind:"command",id:xb,actionId:xb,label:"Zoom out",icon:"minus",dataUi:"context-menu-zoom-out-button"},{kind:"command",id:bb,actionId:bb,label:"Reset zoom",icon:"rotate-ccw",dataUi:"context-menu-reset-zoom-button"}]}]},{id:"system.canvas-tool-context-menu",target:"canvas",order:1020,actionIds:[zf],getSections:e=>[{id:"system.canvas-tools",title:"Tools",order:20,items:[{kind:"command",id:"system.canvas.select-tool",actionId:zf,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:zf,value:"hand",label:"Hand tool",icon:"hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),dataUi:"context-menu-hand-tool-button"}]}]}],_b=fp("plugin-image.asset-service"),Nb={id:"plugin-image.product-controller"},Ob=class{handlers=null;register(e){return this.handlers=e,()=>{this.handlers===e&&(this.handlers=null)}}openInsertFilePicker(){this.handlers?.openInsertFilePicker()}openReplaceFilePicker(){this.handlers?.openReplaceFilePicker()}},Wb=fp("plugin-image.toolbar-host-bridge"),Yb=["select","hand","rectangle","ellipse","diamond","triangle","hexagon","star","arrow","draw","path","text","frame","eraser","laser"],Xb=new Set(Yb),Kb=Yb.map(e=>`"${e}"`).join(", "),Vb=new Set,qb={readyRuntime:null,status:null},jb=Symbol("CanvasKitProduct");export{Yb as CANVAS_KIT_TOOL_IDS,Cs as CanvasKitFloatingToolbarLayer,_p as CanvasKitRoot,Zf as DEFAULT_TEXT_FONT,Es as FloatingSelectionToolbarPageSpace,Qf as HOST_TEXT_FONT,Tp as createCanvasKitController,Ep as createCanvasKitControllerWithTools,S as createCustomShapeColor,kr as createDefaultTextExtensionOptions,Cr as createDefaultTextFontCatalog,m as createThemeShapeColor,Dp as defineCanvasKit,I as getThemeColorTokenName,x as isCustomShapeColorRef,y as isThemeShapeColorRef,w as resolveShapeColor,P as shapeColorToCssColor,Rs as useCanvasKitLayerTree};
|
|
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 nm("p",{style:{margin:0},children:o.length>0?o:nm("br",{})},t)})(e,`block:${n}`,[n],t))}function Ko(e,t,n,i){return e.content?.map((e,o)=>((e,t,n,i)=>{if(Fo(e)){const o=$o(e.marks),r=Uo(e.marks);return r&&Eo(r)?nm("span",{"data-rich-text-link":"true","data-rich-text-link-href":r,onPointerEnter:e=>{i?.onPointerEnter?.({href:r,path:n,element:e.currentTarget})},onPointerLeave:()=>{i?.onPointerLeave?.()},style:{...o,color:"inherit",cursor:i?"pointer":void 0,pointerEvents:i?"auto":"none",textDecorationLine:o?.textDecorationLine?`${o.textDecorationLine} underline`:"underline"},children:e.text},t):nm("span",{style:o,children:e.text},t)}return Ko(e,t,n,i)})(e,`${t}:${o}`,[...n,o],i))??[]}function Vo({link:e,onApply:t,onKeepVisible:n,onClear:i}){const[o,r]=Jf(!1),[s,a]=Jf(!1),[d,l]=Jf(""),[c,u]=Jf(!1),h=Qf(null);return qf(()=>{a(!1),l(e?.href??""),u(!1)},[e?.href,e?.path]),qf(()=>()=>{null!==h.current&&window.clearTimeout(h.current)},[]),e&&"undefined"!=typeof document?om(nm("div",{"data-ui":"rich-text-link-popover",onPointerEnter:()=>{r(!0),n(),null!==h.current&&(window.clearTimeout(h.current),h.current=null)},onPointerLeave:()=>{r(!1),null!==h.current&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{o||i()},120)},onPointerDown:e=>{e.stopPropagation()},onClick:e=>{e.stopPropagation()},style:{position:"fixed",zIndex:3,left:e.rect.left+e.rect.width/2,top:e.rect.top,transform:"translate(-50%, calc(-100% - var(--toolbar-floating-offset, 8px)))",display:"flex",alignItems:"center",gap:"var(--chrome-spacing)",maxWidth:"min(360px, calc(100vw - 24px))",padding:"var(--chrome-spacing)",border:"var(--chrome-border-width) solid var(--chrome-border)",borderRadius:"var(--chrome-radius)",background:"var(--chrome-background)",color:"var(--chrome-foreground)",boxShadow:"var(--shadow-chrome)",pointerEvents:"auto"},children:s?im("form",{"data-ui":"rich-text-link-popover-editor",onSubmit:n=>{if(n.preventDefault(),n.stopPropagation(),0===d.trim().length)return t({path:e.path,href:null}),void i();const o=To(d);o?(t({path:e.path,href:o}),a(!1),l(o)):u(!0)},style:{display:"flex",alignItems:"center",gap:"var(--chrome-spacing)",minWidth:0},children:[
|
|
3
|
+
nm("input",{"aria-label":"Link URL",autoFocus:!0,value:d,onChange:e=>{l(e.target.value),u(!1)},onKeyDown:t=>{t.stopPropagation(),"Escape"===t.key&&(t.preventDefault(),a(!1),l(e.href),u(!1))},style:{width:220,minWidth:0,height:"var(--toolbar-control-size)",border:"var(--chrome-control-border-width) solid",borderColor:c?"var(--destructive, #dc2626)":"var(--border)",borderRadius:"var(--chrome-control-radius)",background:"var(--background)",color:"var(--foreground)",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)",outline:"none",padding:"0 var(--toolbar-title-padding-inline)"}}),
|
|
4
|
+
nm("button",{type:"submit","aria-label":"Apply link",title:"Apply link",style:my,children:nm(uy,{size:14,strokeWidth:2})}),
|
|
5
|
+
nm("button",{type:"button","aria-label":"Cancel",title:"Cancel",onClick:()=>{a(!1),l(e.href),u(!1)},style:my,children:nm(fy,{size:14,strokeWidth:2})})]}):im(tm,{children:[
|
|
6
|
+
nm("button",{type:"button","aria-label":"Open link",title:"Open link",onClick:()=>{Bo(e.href)},style:my,children:nm(hy,{size:14,strokeWidth:2})}),
|
|
7
|
+
nm("button",{type:"button",title:e.href,onClick:()=>{Bo(e.href)},style:Sy,children:e.href}),
|
|
8
|
+
nm("button",{type:"button","aria-label":"Edit link",title:"Edit link",onClick:()=>{a(!0)},style:my,children:nm(gy,{size:14,strokeWidth:2})})]})}),document.body):null}function qo(){return{defaultFont:by,defaultFontLabel:"Default",fonts:[]}}function jo(){return Go(qo())}function Go(e){const t=new Map;for(const n of e.fonts)Zo(n.id)&&"default"!==n.id&&t.set(n.id,n);return{defaultFont:e.defaultFont,defaultFontLabel:e.defaultFontLabel,fontOptions:[{id:yy,label:e.defaultFontLabel,cssFamily:e.defaultFont.cssFamily,source:e.defaultFont.source},...t.values()],fontsById:t}}function Zo(e){return"string"==typeof e&&e.trim().length>0}function Qo(e,t){return"default"===t?e.defaultFont:e.fontsById.get(t)??e.defaultFont}function Jo(e,t,n){const i=Qo(t,e),o=n??("undefined"==typeof document?void 0:document);if(!o||!er(i.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})(i),s=(e=>{const t=xy.get(e);if(t)return t;const n=new Map;return xy.set(e,n),n})(o),a=s.get(r);if(a)return a;const d=(async(e,t)=>{const{source:n}=t;if(er(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(i=>{const o=e.createElement("link");o.rel="stylesheet",o.href=n.cssUrl,o.dataset.landTextFont=t.id;const r=()=>i();o.addEventListener("load",r,{once:!0}),o.addEventListener("error",r,{once:!0}),(e.head??e.documentElement).appendChild(o)}))(e,t,n),void(await tr(e,n))):(await(async(e,t)=>{const{fonts:n}=e,i=e.defaultView?.FontFace;if(!n||!i)return;if(Array.from(n).filter(e=>e.family===t.family&&"loaded"===e.status).length>0)return;const o=await new i(t.family,t.src,t.descriptors).load();n.add(o)})(e,n),void(await tr(e,n)))})(o,i).catch(()=>{s.delete(r)});return s.set(r,d),d}function er(e){return!!e&&"system"!==e.kind}async function tr(e,t){const{fonts:n}=e;if(!n)return;const i=(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),o=t.sampleText??"Aa";await Promise.all(i.map(e=>n.load(`${e} 16px "${t.family}"`,o)))}function nr(){const e=Vf(Iy);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function ir(e){const t=Kf(t=>oo("useValue",e,t,{fireImmediately:!1}),[e]),n=Kf(()=>e.get(),[e]);return em(t,n,n)}function or({children:e,className:t,dataUi:n}){const i=nr(),o=Qf(null);return Gf(()=>oo("PageSpace.transform",i.pageTransformSignal,()=>{const e=o.current;e&&(e.style.transform=i.pageTransformSignal.get().toCssString())}),[i]),nm("div",{ref:o,"data-ui":n,className:t,style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transformOrigin:"0 0"},children:e})}function rr(){const e="undefined"!=typeof window&&"1"===new URLSearchParams(window.location.search).get("renderHostDebug");
|
|
9
|
+
return im("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:[nm(or,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:nm(vy,{})}),e?nm(wy,{}):null]})}function sr(){
|
|
10
|
+
return nm("div",{"data-ui":"transform-descendant-ancestor-boundary",style:{position:"absolute",inset:0,border:"1px dashed #64748b",pointerEvents:"none"}})}function ar(){
|
|
11
|
+
return nm("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 frame"})}function dr({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?nm(tm,{children:e}):t.reduceRight((e,t)=>nm(lr,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function lr({ancestorId:e,children:t,shapeElementToPage:n}){const i=nr(),o=ir(i.getShapeSignal(e));if(!o)return nm(tm,{children:t});const r=((e,t,n)=>{const i=e.getShapeUtil(t).getChildClipLocalBounds(t);if(!(i&&(o=i,Number.isFinite(o.x)&&Number.isFinite(o.y)&&Number.isFinite(o.w)&&Number.isFinite(o.h)&&o.w>=0&&o.h>=0)))return null;var o;const r=e.computeShapeRenderToPageTransform(t),s=n.invert();return`polygon(${(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)])(i).map(e=>s.applyToPoint(r.applyToPoint(e))).map(cr).join(", ")})`})(i,o,n);return r?nm("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}):nm(tm,{children:t})}function cr(e){return`${ur(e.x)}px ${ur(e.y)}px`}function ur(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function hr(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 pr({start:e,end:t,startInset:n,endInset:i,strokeWidth:o,dashSize:r,gapSize:s,kind:a,terminal:d}){const l=(({start:e,end:t,startInset:n,endInset:i})=>{const o=t.x-e.x,r=t.y-e.y,s=Math.hypot(o,r);if(s<1e-6)return null;const a=Math.max(0,s/2-.001),d=Math.min(n,a),l=Math.min(i,a),c=o/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:i});if(!l)return null;const c=hr(a,d);
|
|
12
|
+
return im("g",{style:{pointerEvents:"none"},children:[nm("line",{...c.underlay,x1:l.start.x,y1:l.start.y,x2:l.end.x,y2:l.end.y,fill:"none",stroke:Cy,strokeLinecap:"round",strokeWidth:2.2*o}),nm("line",{...c.segment,x1:l.start.x,y1:l.start.y,x2:l.end.x,y2:l.end.y,fill:"none",stroke:ky,strokeDasharray:`${r} ${s}`,strokeLinecap:"round",strokeWidth:o})]})}function gr({path:e,strokeWidth:t,dashSize:n,gapSize:i,kind:o,terminal:r}){const s=hr(o,r);
|
|
13
|
+
return im("g",{style:{pointerEvents:"none"},children:[nm("path",{...s.underlay,d:e,fill:"none",stroke:Cy,strokeLinecap:"round",strokeWidth:2.2*t}),nm("path",{...s.segment,d:e,fill:"none",stroke:ky,strokeDasharray:`${n} ${i}`,strokeLinecap:"round",strokeWidth:t})]})}function fr({editor:e,shape:t,stroke:n,fill:i,strokeWidth:o}){const r=e.getShapePageOutlineVertices(t.id);return 0===r.length?null:nm("polygon",{points:r.map(e=>`${e.x},${e.y}`).join(" "),fill:i,stroke:n,strokeWidth:o,strokeLinejoin:"round",strokeLinecap:"round"})}function mr(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 Dy[Math.round(n)%Dy.length]??"default"}function Sr({handle:e,strokeWidth:t}){
|
|
14
|
+
return nm("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 yr(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function br(){
|
|
15
|
+
return nm("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:nm(or,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:nm(Vy,{})})})}function xr(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 Ir(e){return(e??("undefined"==typeof document?null:document))?.querySelector(Gy)??null}function vr(e,t){const n=(e=>{const t=e?.getRootNode();return t instanceof Document||t instanceof ShadowRoot?Ir(t):Ir()})(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)}function wr(e,t,n,i){return{type:"pointer",name:e,timestamp:t.timeStamp,pointerId:t.pointerId,button:t.button,buttons:t.buttons,pointerType:(o=t.pointerType,"touch"===o||"pen"===o?o:"mouse"),clickCount:t.detail,screenPoint:n,pagePoint:i,pressure:t.pressure,shiftKey:t.shiftKey,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,accelKey:t.metaKey||t.ctrlKey};var o}function Pr(e,t){return{type:"keyboard",name:e,...kr(t),code:t.code}}function kr(e){return{key:e.key,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}}function Cr(e,t){return new wm(e.clientX-t.left,e.clientY-t.top)}function Tr(e,t){return(e%t+t)%t}function Er(){const e=ir(nr().currentCameraSignal);
|
|
16
|
+
return im("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:[nm("defs",{children:Zy.map(({min:t,mid:n,step:i})=>{const o=15*i*e.z,r=((e,t)=>({x:Tr(.5-e.x*e.z,t),y:Tr(.5-e.y*e.z,t)}))(e,o),s=e.z<n?(a=((e,[t,n],[i,o])=>i+(e-t)/(n-t)*(o-i))(e.z,[t,n],[0,1]),Math.max(0,Math.min(1,a))):1;var a;
|
|
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 im("div",{ref:p,"data-ui":jy,className:"land-canvas__surface",tabIndex:0,style:{cursor:S??Br(u,f,m)},...g,children:[s?nm(Er,{}):null,nm(jS.Provider,{value:d,children:nm(QS.Provider,{value:l,children:im(Rr,{providers:t,children:[
|
|
19
|
+
nm(rr,{}),e?.map(({id:e,component:t})=>nm(t,{},e)),
|
|
20
|
+
nm(br,{})]})})})]})}function Rr({children:e,providers:t}){
|
|
21
|
+
return nm(tm,{children:t?.reduceRight((e,{id:t,component:n})=>nm(n,{children:e},t),e)??e})}function Ar(e){return p(e)&&"text"===e.type}function Lr(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,textAlign:e.textAlign}}function Fr(e){return Lr(e.getDefaultShapeProps("text"))}function $r(e,t,n="user"){const i={...Fr(e),...t.props,richText:t.props?.richText??Mo("")},[o]=e.commands.createShapes([{type:"text",x:t.x,y:t.y,parentId:t.parentId,index:t.index,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,meta:t.meta,props:{richText:i.richText,w:i.w,h:i.h,autoSize:i.autoSize,scale:i.scale,font:i.font,size:i.size,color:i.color,textAlign:i.textAlign}}],{source:n});if(!Ar(o))throw new Error("Failed to create text shape");return o}function Ur(e,t,n,i,o="user"){const r=e.getShape(t);Ar(r)&&e.commands.updateShapes([{id:r.id,props:{richText:n,..."number"==typeof i?.w?{w:i.w}:null,..."number"==typeof i?.h?{h:i.h}:null}}],{source:o})}function Dr(e){try{return e.view.dom.isConnected}catch{return!1}}function zr(e){!e.isDestroyed&&Dr(e)&&(e.view.dom.focus(),e.view.focus())}function _r(e){if(!Dr(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,i=t.focusNode,o=e instanceof HTMLElement?e:e.parentElement,r=!!n&&!!i&&null!==o&&o.contains(n)&&o.contains(i);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 Hr(e,t=nb){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function Nr(e,t){return Qo(t,e).cssFamily}function Or(e){return Hr(e)}function Wr(e){const t=Hr(e);return ib[t]??Math.ceil(1.4*t)}function Yr(e,t=1){return Math.max(1,Math.ceil(Wr(e)*t))}function Xr(e){switch(e){case"middle":return"center";case"end":return"right";default:return"left"}}function Kr(e,t,n){return 0===Ro(e).trim().length?Vr(t):qr(t,(i=Lo(e),o={width:t.props.autoSize?void 0:t.props.w,shape:t,fontCatalog:n},jr(document).measureHtml(i,o)));var i,o}function Vr(e){const t=e.props.autoSize?16:e.props.w,n=Yr(e.props.size);if(e.props.w!==t||e.props.h!==n)return{w:t,h:n}}function qr(e,t){const n=e.props.autoSize?Math.max(16,Math.ceil(t.w)):e.props.w,i=Math.max(Yr(e.props.size),Math.ceil(t.h));if(n!==e.props.w||i!==e.props.h)return{w:n,h:i}}function jr(e){const t=rb.get(e);if(t)return t;const n=new ob(e);return rb.set(e,n),n}function Gr(e,t,n){n&&"normal"!==n&&"auto"!==n&&(e.style[t]=n)}function Zr({shapeId:e,editor:t,fontCatalog:n}){return{shapeId:e,isDestroyed:()=>t.isDestroyed,isConnected:()=>!t.isDestroyed&&Dr(t),isFocused:()=>!t.isDestroyed&&Dr(t)&&t.view.dom.contains(document.activeElement),getValue:()=>Ao(t.getJSON()),setValue(e){t.commands.setContent(e)},focus(){zr(t)},focusEnd(){!t.isDestroyed&&Dr(t)&&t.commands.focus("end")},focusSelectAll(){!t.isDestroyed&&Dr(t)&&(zr(t),t.chain().focus().selectAll().run())},focusAtPagePoint(e,n){((e,t,n)=>{zr(t);const i=e.pageToScreen(new wm(n.x,n.y)),o=t.view.posAtCoords({left:i.x,top:i.y})?.pos;o?t.chain().focus().setTextSelection(o).run():t.chain().focus().selectAll().run()})(e,t,n)},getSelectionSnapshot:()=>t.isDestroyed||!Dr(t)?{type:null,text:null}:_r(t),collapseSelectionAtClientPoint(e,n){!t.isDestroyed&&Dr(t)&&"Range"===_r(t).type&&((e,t,n)=>{if(e.isDestroyed||!Dr(e))return;const i=e.view.posAtCoords({left:t,top:n})?.pos;"number"!=typeof i?e.commands.focus("end"):e.chain().focus().setTextSelection(i).run()})(t,e,n)},measure(e){if(!t.isDestroyed&&Dr(t))return function(e,t,n){if(0===e.getText().trim().length)return Vr(t);const i=((e,t)=>{const n=e.ownerDocument.defaultView?.getComputedStyle(e);return jr(e.ownerDocument).measureElement(e,t,n)})(e.view.dom,{shape:t,fontCatalog:n,width:t.props.autoSize?void 0:t.props.w});return e.view.dom.scrollHeight>t.props.h+1&&(i.h=Math.max(i.h,e.view.dom.scrollHeight)),qr(t,i)}(t,e,n)},onCompositionStateChange(e){if(t.isDestroyed)return()=>{};const n=t.view.dom,i=()=>e(!0),o=()=>e(!1);return n.addEventListener("compositionstart",i),n.addEventListener("compositionend",o),()=>{n.removeEventListener("compositionstart",i),n.removeEventListener("compositionend",o),e(!1)}}}}function Qr(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const i=Number.parseFloat(n);return Number.isFinite(i)?n.endsWith("rem")?16*i:i:t}function Jr(e){return e instanceof Element&&null!==e.closest('[data-ui="rich-text-formatting-toolbar"], [data-ui="rich-text-link-popover"]')}function es({editor:e,landEditor:t}){const n=Zf(()=>({strategy:"fixed",placement:"top",offset:Qr("--toolbar-floating-offset",8),flip:!0,shift:{padding:Qr("--toolbar-floating-shift-padding",8)}}),[]),[i,o]=Jf(!1);return function({landEditor:e,textEditor:t}){const n=Qf(null);qf(()=>{if("undefined"==typeof window)return;const i=oo("RichTextBubbleMenu.positionSync",e.pageTransformSignal,()=>{null===n.current&&(n.current=window.requestAnimationFrame(()=>{n.current=null,(e=>{e.isDestroyed||e.view.dispatch(e.state.tr.setMeta(sb,ab))})(t)}))});return()=>{i(),null!==n.current&&(window.cancelAnimationFrame(n.current),n.current=null)}},[e,t])}({landEditor:t,textEditor:e}),e.isDestroyed?null:nm(pm,{editor:e,pluginKey:sb,updateDelay:0,resizeDelay:0,appendTo:ns,shouldShow:is,options:n,"data-ui":"rich-text-formatting-toolbar",onWheelCapture:ts,onPointerDown:e=>{e.preventDefault(),e.stopPropagation()},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation()},style:{zIndex:2,display:"flex",alignItems:"center",gap:"var(--chrome-spacing)",padding:"var(--chrome-spacing)",border:"var(--chrome-border-width) solid var(--chrome-border)",borderRadius:"var(--chrome-radius)",background:"var(--chrome-background)",color:"var(--chrome-foreground)",boxShadow:"var(--shadow-chrome)",pointerEvents:"auto",userSelect:"none",WebkitUserSelect:"none"},children:i?nm(ss,{editor:e,onDone:()=>{o(!1)}}):im(tm,{children:[
|
|
22
|
+
nm(as,{children:"Text"}),
|
|
23
|
+
nm(ds,{}),db.map(t=>nm(os,{editor:e,format:t.id,label:t.label,shortcut:t.shortcut,dataUi:t.dataUi,children:t.content},t.id)),
|
|
24
|
+
nm(ds,{}),
|
|
25
|
+
nm(rs,{editor:e,onEdit:()=>{o(!0)}})]})})}function ts(e){vr(e.nativeEvent,e.currentTarget)&&(e.preventDefault(),e.stopPropagation())}function ns(){return document.body}function is({editor:e,element:t,view:n}){return e.isEditable&&!e.isDestroyed&&!e.state.selection.empty&&(n.hasFocus()||t.contains(document.activeElement))}function os({editor:e,format:t,label:n,shortcut:i,dataUi:o,children:r}){const s=Qf(!1),a=e.isActive(t),d=e.isDestroyed||void 0===e.schema.marks[t],l=()=>{if(!d)switch(t){case"bold":return void e.chain().focus().toggleBold().run();case"italic":return void e.chain().focus().toggleItalic().run();case"strike":return void e.chain().focus().toggleStrike().run()}};
|
|
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 im("form",{"data-ui":"rich-text-link-editor",onSubmit:i=>{i?.preventDefault(),i?.stopPropagation();const o=To(n);if(!o)return 0===n.trim().length?(e.chain().focus().extendMarkRange("link").unsetLink().run(),void t()):void r(!0);e.chain().focus().extendMarkRange("link").setLink({href:o}).run(),t()},style:{display:"flex",alignItems:"center",gap:"var(--chrome-spacing)"},children:[
|
|
29
|
+
nm(as,{children:"Link"}),
|
|
30
|
+
nm(ds,{}),
|
|
31
|
+
nm("input",{"aria-label":"Link URL",autoFocus:!0,value:n,placeholder:"https://example.com",onChange:e=>{i(e.target.value),r(!1)},onKeyDown:n=>{n.stopPropagation(),"Escape"===n.key&&(n.preventDefault(),t(),e.commands.focus())},onPointerDown:e=>{e.stopPropagation()},onMouseDown:e=>{e.stopPropagation()},style:{width:220,minWidth:0,height:"var(--toolbar-control-size)",border:"var(--chrome-control-border-width) solid",borderColor:o?"var(--destructive, #dc2626)":"var(--border)",borderRadius:"var(--chrome-control-radius)",background:"var(--background)",color:"var(--foreground)",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)",outline:"none",padding:"0 var(--toolbar-title-padding-inline)"}}),
|
|
32
|
+
nm("button",{type:"submit","aria-label":"Apply link",title:"Apply link",style:hb,children:nm(uy,{size:14,strokeWidth:2})}),
|
|
33
|
+
nm("button",{type:"button","aria-label":"Cancel",title:"Cancel",onClick:n=>{n.preventDefault(),n.stopPropagation(),t(),e.commands.focus()},style:hb,children:nm(fy,{size:14,strokeWidth:2})})]})}function as({children:e}){
|
|
34
|
+
return nm("div",{"data-ui":"rich-text-formatting-toolbar-title",style:lb,children:e})}function ds(){
|
|
35
|
+
return nm("div",{"aria-hidden":"true",style:cb})}function ls({landEditor:e,shape:t,fontCatalog:n,initialRichText:i,className:o,editorStyle:r,onReady:s,onDispose:a,onRichTextChange:d}){const[l,c]=Jf(0),u=Qf(null),h=Kf(e=>{const i=u.current;if(i?.editor===e)return i.controller;const o=Zr({shapeId:t.id,editor:e,fontCatalog:n});return u.current={editor:e,controller:o},o},[n,t.id]),p=sm({extensions:gb,content:i,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=h(e);d({editor:e,controller:t,richText:t.getValue()})}},[t.id]);return qf(()=>{if(!p||p.isDestroyed)return;const e={editor:p,controller:h(p)};return s(e),()=>{u.current?.editor===p&&(u.current=null),a(e)}},[h,a,s,p]),qf(()=>{if(!p||p.isDestroyed)return;const e=()=>{c(e=>e+1)};return p.on("selectionUpdate",e),p.on("update",e),p.on("focus",e),p.on("blur",e),()=>{p.off("selectionUpdate",e),p.off("update",e),p.off("focus",e),p.off("blur",e)}},[p]),im(tm,{children:[p?nm(es,{editor:p,landEditor:e,version:l}):null,nm(rm,{editor:p,className:o,style:r})]})}function cs({editor:e,controller:t,shapeId:n,request:i,onApplied:o,attempt:r=0}){if(!t.isDestroyed())if(t.isConnected())(({editor:e,controller:t,shapeId:n,request:i,onApplied:o})=>{if(!t.isDestroyed())t.focus(),i&&i.shapeId===n?"selectAll"===i.entryMode?(window.requestAnimationFrame(()=>{!t.isDestroyed()&&t.isConnected()&&t.focusSelectAll()}),e.consumeShapeEditingEntryRequest(i.id),o?.(i)):"placeCaret"===i.entryMode&&i.caretPagePoint?(t.focusAtPagePoint(e,i.caretPagePoint),e.consumeShapeEditingEntryRequest(i.id),o?.(i)):(t.focusEnd(),e.consumeShapeEditingEntryRequest(i.id),o?.(i)):(t.focusEnd(),o?.(i))})({editor:e,controller:t,shapeId:n,request:i,onApplied:o});else{if(r>=4)return;window.requestAnimationFrame(()=>{cs({editor:e,controller:t,shapeId:n,request:i,onApplied:o,attempt:r+1})})}}function us(e,t,n){if(t.isDestroyed()||!t.isConnected())return;const i=t.measure(n);i&&ps(e,n,i,"user")}function hs(e,t,n,i="system"){const o=Kr(t.props.richText,t,n);o&&ps(e,t,o,i)}function ps(e,t,n,i){const o=e.getShape(t.id);Ar(o)&&o.props.w===n.w&&o.props.h===n.h||e.commands.updateShapes([{id:t.id,props:n}],{source:i})}function gs({shapeId:e,markId:t,fontCatalog:n}){const i=nr(),o=ir(i.getShapeSignal(e)),r=ir(i.shapeEditingStateSignal).session;return Ar(o)&&r?.shapeId===o.id?nm(fs,{shape:o,session:r,fontCatalog:n},`${o.id}:${t}`):null}function fs({shape:e,session:t,fontCatalog:n}){const i=nr(),o=Qf(e.props.richText),r=(e=>{const t=Qf(e);return qf(()=>{t.current=e},[e]),t})(e),s=ir(i.shapeEditingEntryRequestSignal),a=Qf(null),[d,l]=Jf(null),[c,u]=Jf(null),h=Kf(({editor:e,controller:t})=>{l(e.isDestroyed?null:e),u(t)},[]),p=Kf(({editor:e,controller:t})=>{l(t=>t===e?null:t),u(e=>e===t?null:e)},[]),g=function({editor:e,shape:t,tiptapEditor:n,richTextController:i,latestShapeRef:o,fontCatalog:r}){const s=Qf(t.props.richText),a=Qf(!1),d=Qf(null),l=Kf(({controller:n,richText:i})=>{if(a.current||!n.isConnected())return;const l=Ao(i);s.current=l,Ur(e,t.id,l,n.measure(o.current)??Kr(l,o.current,r),"user"),((e,t,n,i)=>{null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,us(e,t,n.current)},0)})(e,n,o,d)},[e,r,o,t.id]);return qf(()=>()=>{null!==d.current&&(window.clearTimeout(d.current),d.current=null)},[]),Gf(()=>{n&&i&&!n.isDestroyed&&i.isConnected()&&us(e,i,t)},[e,i,t,n]),qf(()=>{if(!n||!i||!i.isConnected())return;const e=t.props.richText;e!==s.current&&(JSON.stringify(s.current)!==JSON.stringify(e)?(a.current=!0,i.setValue(e),s.current=e,a.current=!1):s.current=e)},[i,t.props.richText,n]),qf(()=>{if(i)return i.onCompositionStateChange(t=>{e.setShapeEditingComposition(t,"system")})},[e,i]),qf(()=>{if(!i||!i.isConnected())return;let n=!1;return Jo(t.props.font,r).then(()=>{!n&&i.isConnected()&&us(e,i,o.current)}),()=>{n=!0}},[e,r,o,i,t.props.font]),l}({editor:i,shape:e,tiptapEditor:d,richTextController:c,latestShapeRef:r,fontCatalog:n});(({editor:e,shapeId:t,session:n,tiptapEditor:i,richTextController:o,entryRequest:r,consumedEntryRequestIdRef:s})=>{const a=Qf(null),d=Qf(null);qf(()=>{if(!o||o.isDestroyed()||!o.isConnected())return;let e=!1,t=null,n=0;const i=()=>{e||o.isDestroyed()||null===s.current&&(o.isFocused()||(o.focus(),n+=1,o.isFocused()||n>=4||(t=window.setTimeout(i,16))))},r=window.requestAnimationFrame(()=>{i()});return()=>{e=!0,window.cancelAnimationFrame(r),null!==t&&window.clearTimeout(t)}},[s,o,t]),qf(()=>{i&&!i.isDestroyed&&o&&null===s.current&&d.current!==n.markId&&(d.current=n.markId,window.setTimeout(()=>{cs({editor:e,controller:o,shapeId:t,request:{id:-1,shapeId:n.shapeId,entryMode:n.entryMode,caretPagePoint:n.caretPagePoint}})},0))},[s,e,o,n.caretPagePoint,n.entryMode,n.markId,n.shapeId,t,i]),qf(()=>{i&&!i.isDestroyed&&o&&r&&r.shapeId===t&&s.current!==r.id&&cs({editor:e,controller:o,shapeId:t,request:r,onApplied(e){e&&(s.current=e.id)}})},[s,e,r,o,t,i]),qf(()=>{if(!i||!o||i.isDestroyed||!o.isConnected())return;const t=o;"selectAll"===n.entryMode&&window.requestAnimationFrame(()=>{"Range"!==t.getSelectionSnapshot().type&&t.focusSelectAll()});const r=a.current,s=n.caretPagePoint;if("placeCaret"===n.entryMode&&s&&(r?.markId!==n.markId||r.entryMode!==n.entryMode)){a.current={markId:n.markId,entryMode:n.entryMode};const i={x:s.x,y:s.y};window.requestAnimationFrame(()=>{cs({editor:e,controller:t,shapeId:n.shapeId,request:{id:-1,shapeId:n.shapeId,entryMode:"placeCaret",caretPagePoint:i}})})}},[e,n.caretPagePoint,n.entryMode,n.markId,n.shapeId,o,i])})({editor:i,shapeId:e.id,session:t,tiptapEditor:d,richTextController:c,entryRequest:s,consumedEntryRequestIdRef:a});const f=(({editor:e,shapeId:t,richTextController:n})=>{const i=Qf(null);return{onPointerDownCapture:Kf(o=>{if(o.stopPropagation(),Jr(o.target))return void(i.current=null);if(0!==o.button||1!==o.detail||!n||n.isDestroyed())return void(i.current=null);const r=e.getShapeEditingSession();i.current=r&&r.shapeId===t&&!r.isComposing&&"Range"===n.getSelectionSnapshot().type?{pointerId:o.pointerId,clientX:o.clientX,clientY:o.clientY,moved:!1}:null},[e,n,t]),onPointerMoveCapture:Kf(e=>{const t=i.current;if(!t||t.pointerId!==e.pointerId)return;const n=e.clientX-t.clientX,o=e.clientY-t.clientY;n*n+o*o>=16&&(t.moved=!0)},[]),onPointerUpCapture:Kf(o=>{const r=i.current;if(i.current=null,Jr(o.target))return;if(!r||r.pointerId!==o.pointerId||r.moved||!n||n.isDestroyed())return;const s=e.getShapeEditingSession();if(!s||s.shapeId!==t||s.isComposing)return;const a=o.clientX,d=o.clientY;window.setTimeout(()=>{n.isDestroyed()||"Range"!==n.getSelectionSnapshot().type||n.collapseSelectionAtClientPoint(a,d)},0)},[e,n,t]),onPointerCancel:Kf(()=>{i.current=null},[])}})({editor:i,shapeId:e.id,richTextController:c}),m=((e,t)=>Zf(()=>({color:k(e.props.color),fontFamily:Nr(e.props.font,t),fontSize:Or(e.props.size),lineHeight:`${Wr(e.props.size)}px`,textAlign:Xr(e.props.textAlign),pointerEvents:"auto",userSelect:"text",cursor:"text",position:"absolute",inset:0,width:"100%",height:"100%"}),[e.props.color,e.props.font,e.props.size,e.props.textAlign,t]))(e,n),S=Kf(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&&d&&!d.isDestroyed&&(e.preventDefault(),e.stopPropagation(),Bo(t))},[d]);
|
|
36
|
+
return nm("div",{"data-ui":"text-editing-box","data-shape-id":e.id,"data-mount-target-kind":"shape",onPointerDown:e=>{e.stopPropagation()},onClickCapture:S,onPointerDownCapture:f.onPointerDownCapture,onPointerMoveCapture:f.onPointerMoveCapture,onPointerUpCapture:f.onPointerUpCapture,onPointerCancel:f.onPointerCancel,onContextMenu:e=>{e.stopPropagation()},onDragStart:e=>{e.preventDefault()},style:m,children:nm(ls,{landEditor:i,shape:e,fontCatalog:n,initialRichText:o.current,className:"land-text-editor__content",editorStyle:{height:"100%",minHeight:"100%"},onReady:h,onDispose:p,onRichTextChange:g})})}function ms({fontCatalog:e=jo()}={}){return{id:"land.text.react",domEventGuards:[mb],canvasComponents:[{id:"land.text.default-font-preload",component:()=>nm(Ss,{fontCatalog:e})}],shapeRenderers:[{type:"text",component:t=>nm(ys,{...t,fontCatalog:e})}]}}function Ss({fontCatalog:e}){return qf(()=>{Jo(yy,e)},[e]),null}function ys({shape:e,editor:t,isHovered:n,fontCatalog:i}){const[o,r]=Jf(null),s=Qf(null),{isEditingThisShape:a,editingHost:d}=function(e,t,n){const i=ir(e.shapeEditingStateSignal).session,o=i?.shapeId===t.id,r=i&&o?nm(gs,{shapeId:i.shapeId,markId:i.markId,fontCatalog:n},i.shapeId+":"+i.markId):null;return(({editor:e,shape:t,isEditingThisShape:n,fontCatalog:i})=>{Gf(()=>{if(n)return;hs(e,t,i);let o=!1;return Jo(t.props.font,i).then(()=>{if(o)return;const n=e.getShape(t.id);Ar(n)&&n.props.font===t.props.font&&hs(e,n,i)}),()=>{o=!0}},[e,i,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:o,fontCatalog:n}),{isEditingThisShape:o,editingHost:r}}(t,e,i),l=Kf(()=>{null!==s.current&&(window.clearTimeout(s.current),s.current=null)},[]),c=Kf(()=>{l(),s.current=window.setTimeout(()=>{r(null),s.current=null},160)},[l]);return qf(()=>()=>{l()},[l]),qf(()=>{a&&(l(),r(null))},[l,a]),im("div",{"data-editing-hidden":a?"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:k(e.props.color),fontFamily:Nr(e.props.font,i),fontSize:Or(e.props.size),lineHeight:`${Wr(e.props.size)}px`,textAlign:Xr(e.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none"},children:[
|
|
37
|
+
nm("div",{style:{opacity:a?0:void 0},children:Xo(e.props.richText,a?void 0:{onPointerEnter({href:e,path:t,element:n}){l(),r({href:e,path:t,rect:n.getBoundingClientRect()})},onPointerLeave(){c()}})}),
|
|
38
|
+
nm(Vo,{link:o,onApply:({path:n,href:i})=>{Ur(t,e.id,((e,t,n)=>({...e,content:bs(e.content,t,n)}))(e.props.richText,n,i),void 0,"user"),i&&r(e=>e?{...e,href:i}:e)},onKeepVisible:l,onClear:()=>{l(),r(null)}}),
|
|
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
|
+
return im("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:[o&&!T(e.props.fill)?nm("path",{d:o,fill:k(e.props.fill),stroke:"none"}):null,e.props.isClosed&&a?nm("path",{d:a,fill:"none",stroke:d,strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round"}):s?nm("path",{d:s,fill:d,stroke:"none"}):null]})}function Tl({shape:e,isHovered:t}){
|
|
43
|
+
return nm(Cl,{shape:e,isHovered:t})}function El(e){return 4/e.getCurrentCamera().z}function Bl(e,t,n){const i=Math.min(n,t.w/2,t.h/2);return e.x>t.minX+i&&e.x<t.maxX-i&&e.y>t.minY+i&&e.y<t.maxY-i}function Ml(e,t){const n=new Set,i=El(e);for(const o of e.hitTestShapesAtPoint(t)){const r=e.getShapeUtil(o);if(!r.canReceiveChildren(o))continue;const s=r.getChildClipLocalBounds(o);s&&Bl(r.getLocalToPageTransform(o).invert().applyToPoint(t),s,i)&&n.add(o.id)}return n}function Rl(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 Al(e,t,n,i){const o=i.topMostOnly?n.slice(0,1):n;for(const r of o){const n=Rl(e,r,t);n&&t.erasingShapeIds.add(n)}}function Ll(e,t,n){Al(e,t,e.hitTestShapesAtPoint(n.pagePoint),{topMostOnly:n.accelKey})}function Fl(e,t,n){Al(e,t,e.hitTestShapesByLineSegment(t.previousPagePoint,n.pagePoint,{margin:El(e)}),{topMostOnly:n.accelKey})}function $l(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function Ul(e,t){e.setErasingShapeIds(Array.from(t.erasingShapeIds)),e.setEraserTrail(t.trail)}function Dl(e){e.clearErasingShapeIds(),e.clearEraserTrail()}function zl(e,t){const n=Array.from(t.erasingShapeIds);Dl(e),0!==n.length&&e.commands.deleteShapes(n,{source:"user"})}function _l(){return"undefined"==typeof performance?Date.now():performance.now()}function Hl(e,t,n,i){const o=e.samples[e.samples.length-1];if(!o)return void e.samples.push({...t,time:i,velocity:0});const r=wx/n,s=Xl(o,t);if(s<r)return void(e.samples[e.samples.length-1]={...o,...t,time:i});const a=s*n/Math.max(Bx,i-o.time);e.samples.push({...t,time:i,velocity:Ql(o.velocity,a,.68)})}function Nl(e,t){e.samples=Ol(e.samples,t)}function Ol(e,t){const n=e[e.length-1];if(!n)return[];const i=t-Jl(Mx+n.velocity*Rx,Mx,Ax);if(n.time<i)return[];const o=e.findIndex(e=>e.time>=i);if(-1===o)return[];const r=e.slice(o),s=e[o-1],a=r[0];return s&&a.time>i?[(d=s,l=a,c=Jl((i-s.time)/(a.time-s.time),0,1),{...Zl(d,l,c),time:Ql(d.time,l.time,c),velocity:Ql(d.velocity,l.velocity,c)}),...r]:r;var d,l,c}function Wl(e,t){if(e.length<=1)return{x:1,y:0};const n=e[t-1]??e[t],i=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?jl(i,e[t]):jl(t===e.length-1?e[t]:i,n))}function Yl(e,t,n){const i=[];for(let o=0;o<n;o++){const r=2*Math.PI*o/n;i.push({x:e.x+Math.cos(r)*t,y:e.y+Math.sin(r)*t})}return i}function Xl(e,t){return Math.sqrt(Kl(e,t))}function Kl(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function Vl(e){return{x:-e.y,y:e.x}}function ql(e,t){return{x:e.x+t.x,y:e.y+t.y}}function jl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Gl(e,t){return{x:e.x*t,y:e.y*t}}function Zl(e,t,n){return{x:Ql(e.x,t.x,n),y:Ql(e.y,t.y,n)}}function Ql(e,t,n){return e+(t-e)*n}function Jl(e,t,n){return Math.max(t,Math.min(n,e))}function ec(e,t){const n=e[e.length-1];!n||Kl(n,t)>.04?e.push(t):e[e.length-1]=t}function tc(e){if(e.length<2)return null;if(2===e.length)return`M ${ic(e[0])} L ${ic(e[1])} Z`;const t=[`M ${ic(nc(e[0],e[1]))}`];for(let n=1;n<e.length;n++){const i=e[n],o=e[(n+1)%e.length];t.push(`Q ${ic(i)} ${ic(nc(i,o))}`)}return t.push("Z"),t.join(" ")}function nc(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function ic(e){return`${oc(e.x)},${oc(e.y)}`}function oc(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function rc(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function sc(e,t,n){const i=n/2;return!!e.expand(i).containsPoint(t)&&(Math.abs(t.x-e.minX)<=i||Math.abs(t.x-e.maxX)<=i||Math.abs(t.y-e.minY)<=i||Math.abs(t.y-e.maxY)<=i)}function ac(e){return{id:`frame.set-${e}`,isVisible:e=>"frame"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:t=>((e,t)=>{let n;for(const i of e){if("frame"!==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=uc(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(e=>"frame"===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 dc(e){return{id:`frame.default-${e}`,isVisible:e=>"frame"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("frame")[e],run({context:t,value:n}){const i=uc(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("frame",{[e]:i})}}}function lc({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"swatches",id:`${i}.fill`,actionId:e,label:"Fill",options:Hx.map(e=>({...e,dataUi:`${i}-fill-${e.label.toLowerCase()}-button`}))}]},{id:`${i}.style-stroke`,items:[{kind:"swatches",id:`${i}.stroke`,actionId:t,label:"Stroke",options:Nx.map(e=>({...e,dataUi:`${i}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${i}.style-stroke-width`,items:[{kind:"stepper",id:`${i}.stroke-width`,actionId:n,label:"Stroke width",dataUi:`${i}-stroke-width-control`,options:Ox.map(e=>({...e,dataUi:`${i}-stroke-width-${e.value}-button`}))}]}]}function cc(e){return{id:`frame.child-order.${e}`,isVisible:e=>"frame"===hc(e),isEnabled:t=>t.editor.canMoveSelectionWithinParent(e),run({context:t}){t.editor.moveSelectionWithinParent(e,"user")}}}function uc(e,t){return"strokeWidth"===e?"number"==typeof t&&Ox.some(e=>e.value===t)?t:void 0:v(t)?P(t,"fill"===e?"transparent":y("stroke-muted")):void 0}function hc(e){const[t]=e.selection.selectedShapes;return 1===e.selection.count&&t?.parentId.startsWith("shape:")?e.editor.getShape(t.parentId)?.type??null:null}function pc({shape:e,isHovered:t}){
|
|
44
|
+
return nm(gc,{shape:e,isHovered:t})}function gc({shape:e,isHovered:t=!1}){const{fill:n,h:i,name:o,stroke:r,strokeWidth:s,w:a}=e.props,d=s/2,l=Math.max(a-s,0),c=Math.max(i-s,0),u=yo(r,t);
|
|
45
|
+
return im("svg",{width:"100%",height:"100%",viewBox:`0 0 ${a} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[nm("rect",{x:d,y:d,width:l,height:c,fill:k(n),stroke:u,strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"}),nm("text",{x:12,y:18,fill:k(r),fontFamily:["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),fontSize:12,fontWeight:600,style:{userSelect:"none"},children:o})]})}function fc(e,t,n={}){return"ellipse"===t?((e,t=32)=>{const n=[];for(let i=0;i<t;i+=1){const o=i/t*Math.PI*2;n.push(new wm(e.center.x+e.w/2*Math.cos(o),e.center.y+e.h/2*Math.sin(o)))}return n})(e):yc(e,t,n)}function mc(e,t=12){return Math.min(50,Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t))}function Sc({cornerRadiusPercent:e=12,h:t,w:n}){return Math.min(Math.max(0,n),Math.max(0,t))*mc(e)/100}function yc(e,t,n={}){switch(t){case"diamond":return[new wm(e.center.x,e.minY),new wm(e.maxX,e.center.y),new wm(e.center.x,e.maxY),new wm(e.minX,e.center.y)];case"triangle":return[new wm(e.center.x,e.minY),new wm(e.maxX,e.maxY),new wm(e.minX,e.maxY)];case"hexagon":return[new wm(e.minX+.25*e.w,e.minY),new wm(e.maxX-.25*e.w,e.minY),new wm(e.maxX,e.center.y),new wm(e.maxX-.25*e.w,e.maxY),new wm(e.minX+.25*e.w,e.maxY),new wm(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,i=n%2==0?1:.48;t.push(new wm(Math.cos(e)*i,Math.sin(e)*i))}return((e,t)=>{const n=Pm.FromPoints([...e]);return 0===n.w||0===n.h?[t.center]:e.map(e=>new wm(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=Sc(e),n=4)=>{const i=Math.min(Math.max(0,t),Math.max(0,e.w)/2,Math.max(0,e.h)/2);if(0===i)return Ic(e);const o=[];return xc(o,{centerX:e.maxX-i,centerY:e.minY+i,radius:i,startAngle:-Math.PI/2,endAngle:0,segments:n}),xc(o,{centerX:e.maxX-i,centerY:e.maxY-i,radius:i,startAngle:0,endAngle:Math.PI/2,segments:n}),xc(o,{centerX:e.minX+i,centerY:e.maxY-i,radius:i,startAngle:Math.PI/2,endAngle:Math.PI,segments:n}),xc(o,{centerX:e.minX+i,centerY:e.minY+i,radius:i,startAngle:Math.PI,endAngle:3*Math.PI/2,segments:n}),o})(e,Sc({cornerRadiusPercent:n.cornerRadiusPercent,w:e.w,h:e.h}));default:return Ic(e)}}function bc(e,t){if(t.length<3)return!1;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];if(r&&s){if(vc(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 xc(e,{centerX:t,centerY:n,endAngle:i,radius:o,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*(i-s);e.push(new wm(t+Math.cos(r)*o,n+Math.sin(r)*o))}}function Ic(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 vc(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 wc(e){return p(e)&&"geo"===e.type}function Pc(e){return"string"==typeof e&&eI.includes(e)}function kc(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Cc(e,t){return e.x*t.y-e.y*t.x}function Tc(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 Ec(e,t,n,i){return Bc(e,t,n,i)?0:Math.min(Tc(e,n,i),Tc(t,n,i),Tc(n,e,t),Tc(i,e,t))}function Bc(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=Cc(o,r);if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=Cc(a,r)/s,l=Cc(a,o)/s;return d<0||d>1||l<0||l>1?null:{point:e.add(o.mul(d)),t:d}}function Mc(e,t,n){let i=null;for(let o=0;o<n.length;o+=1){const r=n[o],s=n[(o+1)%n.length]??n[0];if(!r||!s)continue;const a=Bc(e,t,r,s);!a||a.t<=1e-6||(!i||a.t<i.t)&&(i=a)}return i?.point??null}function Rc(e){return fc(new Pm(0,0,e.props.w,e.props.h),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}function Ac(e){const t=new Pm(0,0,e.props.w,e.props.h);return[new wm(t.minX,t.minY),new wm(t.center.x,t.minY),new wm(t.maxX,t.minY),new wm(t.minX,t.center.y),t.center,new wm(t.maxX,t.center.y),new wm(t.minX,t.maxY),new wm(t.center.x,t.maxY),new wm(t.maxX,t.maxY)].map((e,t)=>({point:e,kind:tI[t]??"custom"}))}function Lc(e){return{id:`geo.set-${e}`,isVisible:e=>"geo"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:t=>((e,t)=>{let n;for(const i of e){if("geo"!==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=Dc(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(wc).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function Fc(e){return{id:`geo.default-${e}`,isVisible:e=>zc(e.tool.activeToolId),getValue:t=>t.editor.getDefaultShapeProps("geo")[e],run({context:t,value:n}){const i=Dc(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("geo",{[e]:i})}}}function $c({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"swatches",id:`${i}.fill`,actionId:e,label:"Fill",options:oI.map(e=>({...e,dataUi:`${i}-fill-${e.label.toLowerCase()}-button`}))}]},{id:`${i}.style-stroke`,items:[{kind:"swatches",id:`${i}.stroke`,actionId:t,label:"Stroke",options:rI.map(e=>({...e,dataUi:`${i}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${i}.style-stroke-width`,items:[{kind:"stepper",id:`${i}.stroke-width`,actionId:n,label:"Stroke width",dataUi:`${i}-stroke-width-control`,options:sI.map(e=>({...e,dataUi:`${i}-stroke-width-${e.value}-button`}))}]}]}function Uc(e){let t=null;for(const n of e)if(wc(n))if(null!==t){if(t!==n.props.geo)return null}else t=n.props.geo;return t}function Dc(e,t){return"strokeWidth"===e?"number"==typeof t&&sI.some(e=>e.value===t)?t:void 0:v(t)?P(t,y("fill"===e?"fill-slate":"stroke-slate")):void 0}function zc(e){return aI.some(t=>t.value===e)}function _c(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Hc({shape:e,isHovered:t}){
|
|
46
|
+
return nm(Nc,{shape:e,isHovered:t})}function Nc({shape:e,fill:t=e.props.fill,isHovered:n=!1,stroke:i=e.props.stroke,strokeWidth:o=e.props.strokeWidth}){const{geo:r}=e.props,s=o/2,a=Math.max(e.props.w-o,0),d=Math.max(e.props.h-o,0),l=Sc({cornerRadiusPercent:e.props.cornerRadiusPercent,w:a,h:d}),c="ellipse"===r||"rectangle"===r?null:yc(new Pm(s,s,a,d),r).map(e=>`${e.x},${e.y}`).join(" "),u={fill:k(t),stroke:yo(i,n),strokeWidth:o,strokeLinejoin:"round",strokeLinecap:"round"};
|
|
47
|
+
return nm("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:"ellipse"===r?nm("ellipse",{...u,cx:e.props.w/2,cy:e.props.h/2,rx:a/2,ry:d/2}):"rectangle"!==r?nm("polygon",{...u,points:c??""}):nm("rect",{...u,x:s,y:s,width:a,height:d,rx:l,ry:l})})}function Oc(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function Wc({shape:e,isHovered:t,isSelected:n}){
|
|
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
|
+
im("div",{"data-ui":"image-crop-window",style:{height:a,overflow:"hidden",position:"absolute",borderRadius:c,inset:0,width:d},children:[nm("img",{alt:o,draggable:!1,src:l,style:r}),nm(Wu,{shape:n,session:u})]}),
|
|
52
|
+
nm(Xu,{cornerRadius:c,isVisible:t})]})}
|
|
53
|
+
return im("div",{"data-ui":"image-shape",style:{borderRadius:c,display:"block",height:a,overflow:"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:d},children:[
|
|
54
|
+
nm("img",{alt:o,draggable:!1,src:l,style:{display:"block",height:a,objectFit:"fill",width:d}}),
|
|
55
|
+
nm(Wu,{shape:n,session:u}),
|
|
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
|
+
return im("g",{children:[nm("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:n-.8*o,y:i-.8*r,width:2.6*o,height:2.6*r,fill:"transparent",style:{cursor:e.cursor??"grab",pointerEvents:"auto"}}),"corner"===c.kind?nm("polyline",{points:c.points,...l}):nm("line",{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,...l})]})}function Vu(e,t){return`${e},${t}`}function qu(e){return Number.isFinite(e)?Number(e.toFixed(2)).toString():"0"}function ju(e,t,n){const i=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n);return i.x>=0&&i.y>=0&&i.x<=t.props.w&&i.y<=t.props.h}function Gu(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function Zu(e,t){e.setLaserTrail(t.sessionId,t.trail)}function Qu(){return"undefined"==typeof performance?Date.now():performance.now()}function Ju(e,t,n,i){const o=e.samples[e.samples.length-1];if(!o)return void e.samples.push({...t,time:i,velocity:0});const r=iv/n,s=oh(o,t);if(s<r)return void(e.samples[e.samples.length-1]={...o,...t,time:i});const a=s*n/Math.max(lv,i-o.time);e.samples.push({...t,time:i,velocity:uh(o.velocity,a,.68)})}function eh(e,t){e.samples=th(e.samples,t)}function th(e,t){const n=e[e.length-1];if(!n)return[];const i=t-hh(cv+n.velocity*uv,cv,hv);if(n.time<i)return[];const o=e.findIndex(e=>e.time>=i);if(-1===o)return[];const r=e.slice(o),s=e[o-1],a=r[0];return s&&a.time>i?[(d=s,l=a,c=hh((i-s.time)/(a.time-s.time),0,1),{...ch(d,l,c),time:uh(d.time,l.time,c),velocity:uh(d.velocity,l.velocity,c)}),...r]:r;var d,l,c}function nh(e,t){if(e.length<=1)return{x:1,y:0};const n=e[t-1]??e[t],i=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?dh(i,e[t]):dh(t===e.length-1?e[t]:i,n))}function ih(e,t,n){const i=[];for(let o=0;o<n;o++){const r=2*Math.PI*o/n;i.push({x:e.x+Math.cos(r)*t,y:e.y+Math.sin(r)*t})}return i}function oh(e,t){return Math.sqrt(rh(e,t))}function rh(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function sh(e){return{x:-e.y,y:e.x}}function ah(e,t){return{x:e.x+t.x,y:e.y+t.y}}function dh(e,t){return{x:e.x-t.x,y:e.y-t.y}}function lh(e,t){return{x:e.x*t,y:e.y*t}}function ch(e,t,n){return{x:uh(e.x,t.x,n),y:uh(e.y,t.y,n)}}function uh(e,t,n){return e+(t-e)*n}function hh(e,t,n){return Math.max(t,Math.min(n,e))}function ph(e,t){const n=e[e.length-1];!n||rh(n,t)>.04?e.push(t):e[e.length-1]=t}function gh(e){if(e.length<2)return null;if(2===e.length)return`M ${mh(e[0])} L ${mh(e[1])} Z`;const t=[`M ${mh(fh(e[0],e[1]))}`];for(let n=1;n<e.length;n++){const i=e[n],o=e[(n+1)%e.length];t.push(`Q ${mh(i)} ${mh(fh(i,o))}`)}return t.push("Z"),t.join(" ")}function fh(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function mh(e){return`${Sh(e.x)},${Sh(e.y)}`}function Sh(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function yh(e,t,n){return["control",n,e,t].map(encodeURIComponent).join("|")}function bh(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:fv,subpathId:n[1],nodeId:n[2]}:"path.control"!==e||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:mv,handle:n[1],subpathId:n[2],nodeId:n[3]}}function xh(e,t){t?Sv.set(e,Ih(t)):Sv.delete(e)}function Ih(e){return{...e,pagePoint:e.pagePoint.clone()}}function vh(e){return p(e)&&"path"===e.type}function wh(e){return"string"==typeof e&&yv.includes(e)}function Ph(){const e=nr(),t=ir(e.toolStateSignal),n=ir(e.shapeEditingSessionSignal),i=ir(e.selectedShapesSignal),o=ir(e.currentCameraSignal);if(ir(e.inputs.state),"select"!==t.activeToolId||!n)return null;const r=1===i.length?i[0]:null;if(!vh(r)||r.id!==n.shapeId)return null;const s=(e=>{const t=Sv.get(e);return t?Ih(t):null})(e);if(!s||s.shapeId!==r.id)return null;const a=8/o.z,d=a/2;
|
|
58
|
+
return nm("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:nm("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/o.z} ${2/o.z}`,strokeWidth:1.5/o.z})})}function kh(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function Ch(e){return new wm(e.x,e.y)}function Th(e,t){const n=Ch(t);if(!((e,t)=>!!e.out||!!t.in)(e,t))return`L ${kh(n.x)} ${kh(n.y)}`;const i=(e=>{const t=Ch(e);return e.out?t.add(new wm(e.out.dx,e.out.dy)):t})(e),o=(e=>{const t=Ch(e);return e.in?t.add(new wm(e.in.dx,e.in.dy)):t})(t);return["C",kh(i.x),kh(i.y),kh(o.x),kh(o.y),kh(n.x),kh(n.y)].join(" ")}function Eh(e){const t=e.nodes[0];if(!t)return null;const n=[`M ${kh(t.x)} ${kh(t.y)}`];for(let i=1;i<e.nodes.length;i+=1){const t=e.nodes[i-1],o=e.nodes[i];t&&o&&n.push(Th(t,o))}if(e.closed&&e.nodes.length>1){const i=e.nodes[e.nodes.length-1];i&&n.push(Th(i,t)),n.push("Z")}return n.join(" ")}function Bh(e){const t=e.map(Eh).filter(e=>null!==e);return t.length>0?t.join(" "):null}function Mh(e){return Number.isFinite(e)}function Rh(e){return{dx:e.dx,dy:e.dy}}function Ah(e){return{id:e.id,x:e.x,y:e.y,kind:e.kind,...e.in?{in:Rh(e.in)}:null,...e.out?{out:Rh(e.out)}:null}}function Lh(e){return{id:e.id,closed:e.closed,nodes:e.nodes.map(Ah)}}function Fh(e){return e.map(Lh)}function $h(e){return new wm(e.x,e.y)}function Uh(e){const t=$h(e);return e.in?t.add(new wm(e.in.dx,e.in.dy)):t}function Dh(e){const t=$h(e);return e.out?t.add(new wm(e.out.dx,e.out.dy)):t}function zh(e,t,n,i,o){const r=1-o,s=r*r*r,a=3*r*r*o,d=3*r*o*o,l=o*o*o;return new wm(e.x*s+t.x*a+n.x*d+i.x*l,e.y*s+t.y*a+n.y*d+i.y*l)}function _h(e,t,n){return new wm(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n)}function Hh(e,t){return[$h(e),Dh(e),Uh(t),$h(t)]}function Nh(e,t){return!!e.out||!!t.in}function Oh(e,t,n){return Nh(e,t)?zh(...Hh(e,t),n):_h($h(e),$h(t),n)}function Wh(e,t,n){const i=$h(t),o=Dh(t),r=Uh(n),s=$h(n);if(t.out||n.in)for(let a=1;a<=18;a+=1)e.push(zh(i,o,r,s,a/18));else e.push(s)}function Yh(e){const t=e.nodes[0];if(!t)return{id:e.id,closed:e.closed,points:[]};const n=[$h(t)];for(let i=1;i<e.nodes.length;i+=1){const t=e.nodes[i-1],o=e.nodes[i];t&&o&&Wh(n,t,o)}if(e.closed&&e.nodes.length>1){const i=e.nodes[e.nodes.length-1];i&&Wh(n,i,t)}return{id:e.id,closed:e.closed,points:n}}function Xh(e){const t=e.props,n=wv.get(t);if(n)return n;const i=Kh(e.props);return wv.set(t,i),i}function Kh(e){const t=e.subpaths.map(Yh),n=t.flatMap(e=>e.points),i=e.subpaths.flatMap(e=>e.nodes.flatMap(e=>[$h(e),...e.in?[Uh(e)]:[],...e.out?[Dh(e)]:[]])),o=i.length>0?Pm.FromPoints(i):new Pm(0,0,1,1),r=Math.max(e.strokeWidth/2,1),s=n.length>0?Pm.FromPoints(n).expand(r):o.expand(r),a=new Pm(s.x,s.y,Math.max(s.w,1),Math.max(s.h,1));return{path:Bh(e.subpaths),pointBounds:o,localBounds:s,renderBounds:a,outlineVertices:n.map(e=>e.clone()),flattenedSubpaths:t}}function Vh(e,t){return e.map(e=>({...e,nodes:e.nodes.map(e=>((e,t)=>{const n=t($h(e)),i=e.in?t(Uh(e)):null,o=e.out?t(Dh(e)):null;return{...e,x:n.x,y:n.y,...i?{in:{dx:i.x-n.x,dy:i.y-n.y}}:{in:null},...o?{out:{dx:o.x-n.x,dy:o.y-n.y}}:{out:null}}})(e,t))}))}function qh(e,t){const n=Kh({...t,subpaths:Fh(e)}).pointBounds,i=Number.isFinite(n.x)?n.x:0,o=Number.isFinite(n.y)?n.y:0,r=((e,t,n)=>Vh(e,e=>new wm(e.x+t,e.y+n)))(e,-i,-o);return{x:i,y:o,subpaths:r,geometry:Kh({...t,subpaths:r})}}function jh(e,t){return Vh(e.props.subpaths,e=>t.applyToPoint(e))}function Gh(e,t){return Bh(jh(e,t))}function Zh(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return{distanceSquared:e.dist2(t),t:0};const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o)),a=t.add(i.mul(s));return{distanceSquared:e.dist2(a),t:s}}function Qh(e,t,n){return Zh(e,t,n).distanceSquared}function Jh(e,t,n){const i=n*n;let o=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=Nh(e,s)?32:1;let d=$h(e);for(let n=1;n<=a;n+=1){const l=Oh(e,s,n/a),c=Zh(t,d,l),u=(n-1+c.t)/a;u>.02&&u<.98&&c.distanceSquared<=i&&(!o||c.distanceSquared<o.distanceSquared)&&(o={subpathId:r.id,startNodeId:e.id,endNodeId:s.id,t:u,point:Oh(e,s,u),distanceSquared:c.distanceSquared}),d=l}}}return o?{subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,point:o.point.clone(),distance:Math.sqrt(o.distanceSquared)}:null}function ep(e,t){return e.find(e=>e.id===t)??null}function tp(e,t,n){return ep(e,t)?.nodes.find(e=>e.id===n)??null}function np(e,t,n,i){return e.map(e=>e.id!==t?Lh(e):{...e,nodes:e.nodes.map(e=>e.id===n?i(Ah(e)):Ah(e))})}function ip(e,t,n){return e.map(e=>{if(e.id!==t)return Lh(e);const i=e.nodes.findIndex(e=>e.id===n),o=e.nodes[i];if(!o)return Lh(e);const r=i>0?e.nodes[i-1]:e.closed?e.nodes[e.nodes.length-1]:null,s=i<e.nodes.length-1?e.nodes[i+1]:e.closed?e.nodes[0]:null,a=$h(o),d=((e,t,n)=>{const i=t?$h(t):null,o=n?$h(n):null;if(i&&o){const t=o.sub(i);if(t.len()<=xv)return null;const n=t.normalize();return((e,t)=>{const n=Math.abs(e.x*t.y-e.y*t.x),i=e.len()*t.len();return i<=xv||n/i<=.001})(i.sub(e),o.sub(e))?n.rot(vv):n}const r=o?o.sub(e):i?e.sub(i):null;return!r||r.len()<=xv?null:r.normalize().rot(vv)})(a,r,s),l=e.nodes.map(Ah);return l[i]={...Ah(o),kind:"smooth",in:r&&d?rp(d.mul(-a.dist($h(r))*Iv)):null,out:s&&d?rp(d.mul(a.dist($h(s))*Iv)):null},{...e,nodes:l}})}function op(e,t,n){return np(e,t,n,e=>({...e,kind:"corner",in:null,out:null}))}function rp(e){return e.len2()<=1e-12?null:{dx:e.x,dy:e.y}}function sp(e,t,n){return e.map(e=>e.id!==t?Lh(e):{...e,closed:!(e.nodes.length<=3)&&e.closed,nodes:e.nodes.filter(e=>e.id!==n).map(Ah)}).filter(e=>e.nodes.length>0)}function ap(e){const t=Pv.get(e);if(!t)return null;if(e.getShapeEditingSession()?.shapeId!==t.shapeId)return null;const n=e.getShape(t.shapeId);if(!vh(n))return null;const i=tp(n.props.subpaths,t.subpathId,t.nodeId);return i?{selection:up(t),shape:n,node:i}:null}function dp(e,t){if(!t)return Pv.delete(e),void cp(e,null);Pv.set(e,up(t)),cp(e,t.pagePoint)}function lp(e,t,n,i){const o=ep(t.props.subpaths,n)?.nodes.find(e=>e.id===i);if(!o)return void dp(e,null);const r=e.computeShapeLocalToPageTransform(t);dp(e,{shapeId:t.id,subpathId:n,nodeId:i,pagePoint:r.applyToPoint($h(o))})}function cp(e,t){const n=e.getShapeEditingSession();n&&e.updateSession({shapeEditingSession:{...n,caretPagePoint:t?{x:t.x,y:t.y}:void 0}},"system")}function up(e){return{...e,pagePoint:e.pagePoint.clone()}}function hp(e){const t=e.meta[kv],n=e.meta[Cv];return{subpathId:"string"==typeof t?t:null,previewNodeId:"string"==typeof n?n:null}}function pp(e,t){const n=gp(e);return t.subpathId&&(n[kv]=t.subpathId),t.previewNodeId&&(n[Cv]=t.previewNodeId),n}function gp(e){const t={...e};return delete t[kv],delete t[Cv],t}function fp(){const e=nr(),t=ir(e.toolStateSignal),n=ir(e.inputs.state),i=ir(e.selectedShapesSignal),o=ir(e.currentCameraSignal);if("path"!==t.activeToolId)return null;const r=1===i.length?i[0]:null,s=vh(r)?r:null,a=8/o.z,d=1.5/o.z,l=n.currentPagePoint;if(!s)return l?nm(Sp,{point:l,size:a,strokeWidth:d,variant:"candidate"}):null;const c=((e,t)=>{const n=hp(t);if(!n.subpathId)return null;const i=ep(jh(t,e.computeShapeLocalToPageTransform(t)),n.subpathId);if(!i)return null;const o=n.previewNodeId?i.nodes.findIndex(e=>e.id===n.previewNodeId):-1,r=o>=0?i.nodes[o]??null:null,s=o>0?i.nodes[o-1]??null:null,a=s&&r?Eh({id:`${i.id}:preview`,closed:!1,nodes:[s,r]}):null;return{committedNodes:i.nodes.filter(e=>e.id!==n.previewNodeId),previewNode:r,previewPath:a}})(e,s);if(!c)return l?nm(Sp,{point:l,size:a,strokeWidth:d,variant:"candidate"}):null;const u=c.previewNode?mp(c.previewNode):l,h=u&&!c.committedNodes.some(e=>mp(e).dist2(u)<=.25/(o.z*o.z));
|
|
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 nm("rect",{"data-ui":"path-draft-control-point","data-path-draft-control-point":i,x:e.x-o,y:e.y-o,width:t,height:t,rx:2,ry:2,fill:"candidate"===i?"rgba(219, 234, 254, 0.98)":"rgba(255, 255, 255, 0.98)",stroke:Tv,strokeWidth:n})}function yp({shape:e,isHovered:t=!1,shapeEditingSession:n=null,fill:i=e.props.fill,stroke:o=e.props.stroke,strokeWidth:r=e.props.strokeWidth}){const{renderBounds:s}=Xh({props:{...e.props,strokeWidth:r}}),a=(e=>hp(e).previewNodeId)(e),d=Bh(((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,a));if(!d)return null;const l=n?.shapeId===e.id;
|
|
61
|
+
return im("svg",{width:"100%",height:"100%",viewBox:`${s.x} ${s.y} ${Math.max(s.w,1)} ${Math.max(s.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[T(i)?null:nm("path",{d:d,fill:k(i),fillRule:e.props.fillRule,clipRule:e.props.fillRule,stroke:"none"}),
|
|
62
|
+
nm("path",{d:d,fill:"none",stroke:yo(o,t),strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round"}),l?nm(bp,{shape:e}):null]})}function bp({shape:e}){
|
|
63
|
+
return nm(tm,{children:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=$h(t),i=[];if(t.in){const o=Uh(t);i.push(nm("line",{x1:n.x,y1:n.y,x2:o.x,y2:o.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 o=Dh(t);i.push(nm("line",{x1:n.x,y1:n.y,x2:o.x,y2:o.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${e.id}:${t.id}:out`))}return i}))})}function xp({shape:e,isHovered:t,shapeEditingSession:n}){
|
|
64
|
+
return nm(yp,{shape:e,isHovered:t,shapeEditingSession:n})}function Ip({handle:e,strokeWidth:t}){const n=wp(e.type,e.id);
|
|
65
|
+
return nm("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"}})}function vp({handle:e,strokeWidth:t}){const n=wp(e.type,e.id);
|
|
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 im("div",{role:"alert","data-ui":"canvas-kit-persistence-notice",className:"land-canvas-kit__persistence-notice",children:[im("div",{className:"land-canvas-kit__persistence-notice-copy",children:[nm("strong",{children:"Unsupported records preserved"}),im("span",{children:[i.preservedRecordCount," record",1===i.preservedRecordCount?"":"s"," will round-trip while saving. ",o?`Types: ${o}.`:""]})]}),nm("button",{type:"button",className:"land-canvas-kit__persistence-notice-action",disabled:!t||n,onClick:()=>{t?.()},children:n?"Saving":"Discard unsupported records"})]})}function zf({persistence:e}){
|
|
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 nm("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)})}),Py=Xf(({shapeId:e})=>{const t=nr(),n=e,i=ir(t.getShapeSignal(n)),o=ir(t.getShapeHoveredSignal(n)),r=ir(t.selectionCountSignal),s=ir(t.brushBoxActiveSignal),a=ir(t.getShapeRenderVisibleSignal(n)),d=ir(t.toolStateSignal).activeToolId,l=ir(t.getShapeSelectedSignal(n)),c="select"===d&&l,u=ir(t.getShapeEditingSessionForShapeSignal(n)),h=ir(t.getShapeRenderOrderSignal(n)),p=ir(t.getShapeDropTargetSignal(n)),g=ir(t.getShapeErasingSignal(n)),f=ir(t.getShapeSelectedDescendantTransformAncestorSignal(n)),m=ir(t.getShapeClipAncestorIdsSignal(n)),S=Vf(jS);if(!i)return null;const y=S.getShapeRenderer(i.type);if(!y)return null;const b=y.component,x=((e,t)=>{const n=e.computeShapeRenderBounds(t),i=e.computeShapeRenderToPageTransform(t).compose(km.Translate(n.x,n.y));return{left:0,top:0,width:n.w,height:n.h,transform:i.toCssString(),transformOrigin:"0 0",elementToPage:i}})(t,i),I=g?.32*i.opacity:i.opacity,v=o&&!(1===r&&c)&&!s;
|
|
71
|
+
return im("div",{"data-ui":"shape-instance","data-shape-id":i.id,"data-shape-type":i.type,"data-selected":c?"true":"false","data-hovered":v?"true":"false","data-drop-target":p?"true":"false","data-visible":a?"true":"false","data-render-order":h>=0?String(h):void 0,"data-clip-ancestor-count":m.length,style:{position:"absolute",display:a?void 0:"none",left:x.left,top:x.top,width:x.width,height:x.height,opacity:1===I?void 0:I,transform:x.transform,transformOrigin:x.transformOrigin,pointerEvents:"none",outline:p?"2px solid #2563eb":void 0,outlineOffset:p?4:void 0,boxShadow:p?"0 0 0 6px rgba(37, 99, 235, 0.16)":void 0,zIndex:h>=0?h+1:void 0},children:[a?nm(dr,{clipAncestorIds:m,shapeElementToPage:x.elementToPage,children:nm(b,{shape:i,editor:t,isSelected:c,isHovered:v,shapeEditingSession:u})}):null,a&&p?nm(ar,{}):null,a&&f?nm(sr,{}):null]})}),ky="rgba(100, 116, 139, 0.82)",Cy="rgba(255, 255, 255, 0.84)",Ty=Xf(()=>ir(nr().bindingPreviewActiveSignal)?nm(Ey,{}):null),Ey=Xf(()=>{const e=nr(),t=ir(e.bindingPreviewSignal),n=ir(e.terminalBindingGuidesSignal);if(!t)return null;const i=n.some(e=>e.terminal===t.terminal&&e.targetShapeId===t.targetShapeId);
|
|
72
|
+
return im(tm,{children:[nm(By,{targetShapeId:t.targetShapeId}),nm(My,{bindingPreview:t,showGuide:!i})]})}),By=Xf(({targetShapeId:e})=>{const t=nr(),n=ir(t.cameraZoomSignal),i=ir(t.getShapeSignal(e));return i?nm(fr,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),My=Xf(({bindingPreview:e,showGuide:t})=>{const n=ir(nr().cameraZoomSignal),i=2/n,o=6/n,r=4/n;
|
|
73
|
+
return im(tm,{children:[t?e.guidePath?nm(gr,{path:e.guidePath,strokeWidth:i,dashSize:o,gapSize:r,kind:"binding-preview",terminal:e.terminal}):nm(pr,{start:e.rawPagePoint,end:e.resolvedPagePoint,startInset:8/n,endInset:6/n,strokeWidth:i,dashSize:o,gapSize:r,kind:"binding-preview",terminal:e.terminal}):null,
|
|
74
|
+
nm("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}),
|
|
75
|
+
nm("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})]})}),Ry=Xf(()=>ir(nr().brushBoxActiveSignal)?nm(Ay,{}):null),Ay=Xf(()=>{const e=ir(nr().brushBoxSignal);return e?nm("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}),Ly=Xf(()=>{const e=nr(),t=ir(e.selectionOverlayFrameGeometrySignal),n=ir(e.selectionOverlayCompanionFrameGeometriesSignal);return t||0!==n.length?im(tm,{children:[t?nm(Fy,{frameGeometry:t}):null,n.map((e,t)=>nm(Fy,{frameGeometry:e},`companion-${t}`))]}):null}),Fy=Xf(({frameGeometry:e})=>{const t=ir(nr().selectionOverlayFrameStyleSignal),{bounds:n,rotation:i,rotationCenter:o}=e,{cornerRadius:r,strokeWidth:s}=t,a=180*i/Math.PI;
|
|
76
|
+
return im("g",{transform:0===i?void 0:`rotate(${a} ${o.x} ${o.y})`,children:[nm("rect",{"data-selection-overlay":"bounds-underlay",x:n.x,y:n.y,width:n.w,height:n.h,rx:r,ry:r,fill:"none",stroke:"rgba(255,255,255,0.92)",strokeWidth:2*s}),nm("rect",{"data-selection-overlay":"bounds",x:n.x,y:n.y,width:n.w,height:n.h,rx:r,ry:r,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeWidth:s})]})}),$y=Xf(()=>{const e=ir(nr().selectionOverlayHandleAnchorsSignal);return e?nm(Uy,{anchors:e}):null}),Uy=Xf(({})=>{const e=nr(),t=ir(e.selectionOverlayHandlesSignal),n=ir(e.selectionOverlayFrameGeometrySignal),i=lo(),o=ir(e.cameraZoomSignal);if(!t)return null;const{resizeHandles:r,rotateHandles:s,strokeWidth:a,terminalHandles:d,middleHandles:l,customHandles:c}=t;
|
|
77
|
+
return im(tm,{children:[r.map(e=>nm("rect",{"data-selection-resize-handle":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:4,ry:4,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,style:{cursor:mr(e.id,n?.rotation??0),pointerEvents:"auto"}},e.id)),s.map(e=>im("g",{"data-selection-rotate-handle":e.id,transform:`translate(${e.bounds.center.x-6/o} ${e.bounds.center.y-6/o}) scale(${.6/o})`,fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[nm("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),nm("path",{d:"M21 3v5h-5"})]},e.id)),d.map(e=>nm("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=>nm("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=i.getSelectionCustomHandleRenderer(e.type);
|
|
78
|
+
return nm(t?t.component:Sr,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),Dy=["ew-resize","nwse-resize","ns-resize","nesw-resize"],zy=Xf(()=>{const e=nr(),t=ir(e.selectionOverlayPathSignal),n=ir(e.selectionOverlayBindingSegmentsSignal),i=ir(e.selectionOverlayFrameStyleSignal);return t?im(tm,{children:[
|
|
79
|
+
nm(_y,{bindingSegments:n,strokeWidth:i.strokeWidth}),
|
|
80
|
+
nm("path",{"data-selection-overlay":"path-underlay",d:t,fill:"none",stroke:"rgba(255,255,255,0.92)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2*i.strokeWidth}),
|
|
81
|
+
nm("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:i.strokeWidth})]}):null}),_y=Xf(({bindingSegments:e,kind:t="selection-binding",strokeWidth:n})=>{if(0===e.length)return null;const i=3*n,o=2*n,r=4*n,s=3*n;
|
|
82
|
+
return nm(tm,{children:e.map(e=>e.guidePath?nm(gr,{path:e.guidePath,strokeWidth:n,dashSize:i,gapSize:o,kind:t,terminal:e.terminal},e.terminal):nm(pr,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:r,endInset:s,strokeWidth:n,dashSize:i,gapSize:o,kind:t,terminal:e.terminal},e.terminal))})}),Hy=Xf(()=>ir(nr().selectionTranslationActiveSignal)?null:im(tm,{children:[
|
|
83
|
+
nm(zy,{}),
|
|
84
|
+
nm(Ly,{}),
|
|
85
|
+
nm($y,{})]})),Ny="rgba(37, 99, 235, 0.9)",Oy=Xf(()=>{const e=ir(nr().snapIndicatorsSignal);return 0===e.length?null:nm(Wy,{indicators:e})}),Wy=Xf(({indicators:e})=>{const t=ir(nr().cameraZoomSignal);
|
|
86
|
+
return nm(tm,{children:e.map(e=>nm("points"===e.type?Yy:Xy,{indicator:e,zoom:t},e.id))})}),Yy=Xf(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[o,r]=e.line,s=180*e.rotation/Math.PI;
|
|
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 nm("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:l,fill:"none",stroke:Ny,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),Ky=Xf(()=>{const e=nr(),t=ir(e.terminalBindingGuidesSignal),n=ir(e.selectionOverlayFrameStyleSignal);return 0===t.length?null:nm(_y,{bindingSegments:t,kind:"terminal-binding-guide",strokeWidth:n.strokeWidth})}),Vy=Xf(()=>im("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
|
|
89
|
+
nm("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 '}),
|
|
90
|
+
nm(qy,{layer:"below-host"}),
|
|
91
|
+
nm(Oy,{}),
|
|
92
|
+
nm(Ky,{}),
|
|
93
|
+
nm(Ty,{}),
|
|
94
|
+
nm(Ry,{}),
|
|
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};
|