@yuzhouu/canvas-kit 0.1.8 → 0.1.10

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.
Files changed (271) hide show
  1. package/README.md +158 -102
  2. package/_vendor/canvas-core/bindings/bindingUtil.d.ts +8 -0
  3. package/_vendor/canvas-core/editor/cameraPanSession.d.ts +9 -0
  4. package/_vendor/canvas-core/editor/canvasPanInteraction.d.ts +2 -0
  5. package/_vendor/canvas-core/editor/commands.d.ts +15 -3
  6. package/_vendor/canvas-core/editor/createEditorWithPlugins.d.ts +6 -0
  7. package/_vendor/canvas-core/editor/editor.d.ts +24 -26
  8. package/_vendor/canvas-core/editor/editorComputedHelpers.d.ts +4 -2
  9. package/_vendor/canvas-core/editor/historyManager.d.ts +22 -1
  10. package/_vendor/canvas-core/editor/index.d.ts +2 -2
  11. package/_vendor/canvas-core/editor/interactions.d.ts +10 -1
  12. package/_vendor/canvas-core/editor/managers/bindingManager.d.ts +1 -0
  13. package/_vendor/canvas-core/editor/managers/inputsManager.d.ts +3 -0
  14. package/_vendor/canvas-core/editor/managers/interactionTransientManager.d.ts +0 -26
  15. package/_vendor/canvas-core/editor/managers/queryManager.d.ts +13 -1
  16. package/_vendor/canvas-core/editor/managers/selectionLayoutManager.d.ts +2 -0
  17. package/_vendor/canvas-core/editor/managers/shapeGeometryManager.d.ts +3 -2
  18. package/_vendor/canvas-core/editor/managers/shapeHierarchyManager.d.ts +6 -2
  19. package/_vendor/canvas-core/editor/managers/shapeReparenting.d.ts +3 -2
  20. package/_vendor/canvas-core/editor/managers/snapTypes.d.ts +1 -0
  21. package/_vendor/canvas-core/editor/managers/spatialIndexManager.d.ts +1 -0
  22. package/_vendor/canvas-core/editor/queries/shapeTransforms.d.ts +32 -12
  23. package/_vendor/canvas-core/editor/selection.d.ts +19 -5
  24. package/_vendor/canvas-core/editor/selectionOverlay.d.ts +4 -3
  25. package/_vendor/canvas-core/editor/selectionResizeCapabilities.d.ts +9 -0
  26. package/_vendor/canvas-core/editor/shapeTransformSpace.d.ts +6 -0
  27. package/_vendor/canvas-core/exports/svg.d.ts +1 -0
  28. package/_vendor/canvas-core/geometry/index.d.ts +1 -0
  29. package/_vendor/canvas-core/geometry/mat.d.ts +6 -2
  30. package/_vendor/canvas-core/geometry/polygon.d.ts +7 -0
  31. package/_vendor/canvas-core/geometry/vec.d.ts +0 -2
  32. package/_vendor/canvas-core/index.d.ts +14 -20
  33. package/_vendor/canvas-core/plugins/editorRuntimePlugin.d.ts +4 -10
  34. package/_vendor/canvas-core/plugins/editorRuntimeRegistry.d.ts +19 -0
  35. package/_vendor/canvas-core/plugins/index.d.ts +2 -1
  36. package/_vendor/canvas-core/schema/records.d.ts +2 -7
  37. package/_vendor/canvas-core/schema/snapshots.d.ts +10 -19
  38. package/_vendor/canvas-core/shapes/colors.d.ts +1 -2
  39. package/_vendor/canvas-core/shapes/shapeUtil.d.ts +52 -14
  40. package/_vendor/canvas-core/tools/select/selectToolHelpers.d.ts +9 -6
  41. package/_vendor/canvas-core/tools/select/states/draggingSelectionHandleInteractionState.d.ts +3 -3
  42. package/_vendor/canvas-core/tools/select/states/pointingSelectionHandleInteractionState.d.ts +2 -1
  43. package/_vendor/canvas-plugin-sdk/actionRegistry.d.ts +7 -0
  44. package/_vendor/{canvas-core/surfaces → canvas-plugin-sdk}/actions.d.ts +2 -4
  45. package/_vendor/{canvas-core/surfaces → canvas-plugin-sdk}/contextMenu.d.ts +25 -30
  46. package/_vendor/canvas-plugin-sdk/contextMenuRegistry.d.ts +11 -0
  47. package/_vendor/canvas-plugin-sdk/index.d.ts +7 -0
  48. package/_vendor/canvas-plugin-sdk/plugin.d.ts +39 -0
  49. package/_vendor/{canvas-core/surfaces → canvas-plugin-sdk}/toolbar.d.ts +32 -1
  50. package/_vendor/canvas-plugin-sdk/toolbarRegistry.d.ts +19 -0
  51. package/_vendor/canvas-react/components/CanvasView.d.ts +2 -2
  52. package/_vendor/canvas-react/components/canvasKeyboardEvents.d.ts +13 -0
  53. package/_vendor/canvas-react/components/useCanvasDomEvents.d.ts +4 -3
  54. package/_vendor/canvas-react/contextMenuRequest.d.ts +19 -0
  55. package/_vendor/canvas-react/host/canvasRenderPlugin.d.ts +7 -1
  56. package/_vendor/canvas-react/host/canvasRenderRuntime.d.ts +13 -0
  57. package/_vendor/canvas-react/host/domEventGuards.d.ts +3 -3
  58. package/_vendor/canvas-react/host/index.d.ts +2 -8
  59. package/_vendor/canvas-react/host/overlayRegistry.d.ts +3 -3
  60. package/_vendor/canvas-react/host/rendererRegistry.d.ts +7 -4
  61. package/_vendor/canvas-react/index.d.ts +1 -0
  62. package/_vendor/plugin-arrow/arrowGeometry.d.ts +6 -4
  63. package/_vendor/plugin-arrow/arrowShapeUtil.d.ts +5 -3
  64. package/_vendor/plugin-arrow/arrowTerminalCommands.d.ts +2 -2
  65. package/_vendor/plugin-arrow/canvasRender.d.ts +2 -2
  66. package/_vendor/plugin-arrow/editorRuntime.d.ts +4 -2
  67. package/_vendor/plugin-arrow/feature.d.ts +2 -3
  68. package/_vendor/plugin-arrow/index.d.ts +2 -2
  69. package/_vendor/plugin-draw/canvasRender.d.ts +2 -2
  70. package/_vendor/plugin-draw/drawGeometry.d.ts +4 -7
  71. package/_vendor/plugin-draw/drawShapeUtil.d.ts +2 -2
  72. package/_vendor/plugin-draw/editorRuntime.d.ts +4 -2
  73. package/_vendor/plugin-draw/feature.d.ts +2 -3
  74. package/_vendor/plugin-draw/index.d.ts +3 -3
  75. package/_vendor/plugin-eraser/canvasRender.d.ts +2 -2
  76. package/_vendor/plugin-eraser/editorRuntime.d.ts +4 -2
  77. package/_vendor/plugin-eraser/eraserRuntime.d.ts +12 -0
  78. package/_vendor/plugin-eraser/feature.d.ts +2 -3
  79. package/_vendor/plugin-eraser/index.d.ts +3 -2
  80. package/_vendor/plugin-frame/canvasRender.d.ts +2 -2
  81. package/_vendor/plugin-frame/editorRuntime.d.ts +4 -2
  82. package/_vendor/plugin-frame/feature.d.ts +2 -3
  83. package/_vendor/plugin-frame/frameShapeUtil.d.ts +4 -2
  84. package/_vendor/plugin-frame/index.d.ts +2 -2
  85. package/_vendor/plugin-geo/canvasRender.d.ts +2 -2
  86. package/_vendor/plugin-geo/editorRuntime.d.ts +4 -2
  87. package/_vendor/plugin-geo/feature.d.ts +2 -3
  88. package/_vendor/plugin-geo/geoShapeUtil.d.ts +1 -1
  89. package/_vendor/plugin-geo/index.d.ts +2 -2
  90. package/_vendor/plugin-group/canvasRender.d.ts +2 -2
  91. package/_vendor/plugin-group/editorRuntime.d.ts +4 -2
  92. package/_vendor/plugin-group/feature.d.ts +2 -3
  93. package/_vendor/plugin-group/groupContributions.d.ts +7 -0
  94. package/_vendor/plugin-group/groupShapeUtil.d.ts +24 -5
  95. package/_vendor/plugin-group/index.d.ts +3 -2
  96. package/_vendor/plugin-image/canvasRender.d.ts +2 -2
  97. package/_vendor/plugin-image/cropRuntime.d.ts +1 -1
  98. package/_vendor/plugin-image/cropSession.d.ts +5 -3
  99. package/_vendor/plugin-image/editorRuntime.d.ts +4 -2
  100. package/_vendor/plugin-image/feature.d.ts +2 -3
  101. package/_vendor/plugin-image/imageHostActionContract.d.ts +1 -1
  102. package/_vendor/plugin-image/imageShapeUtil.d.ts +3 -3
  103. package/_vendor/plugin-image/index.d.ts +4 -4
  104. package/_vendor/plugin-image/runtimeShared.d.ts +1 -1
  105. package/_vendor/plugin-image/smudge.d.ts +13 -2
  106. package/_vendor/plugin-image/smudgeRuntime.d.ts +1 -1
  107. package/_vendor/plugin-image/styleRuntime.d.ts +1 -1
  108. package/_vendor/plugin-image/toolbarRuntime.d.ts +1 -1
  109. package/_vendor/plugin-laser/canvasRender.d.ts +2 -2
  110. package/_vendor/plugin-laser/editorRuntime.d.ts +4 -2
  111. package/_vendor/plugin-laser/feature.d.ts +2 -3
  112. package/_vendor/plugin-laser/index.d.ts +3 -2
  113. package/_vendor/plugin-laser/laserRuntime.d.ts +18 -0
  114. package/_vendor/plugin-packaging/canvasRender.d.ts +2 -0
  115. package/_vendor/plugin-packaging/editorRuntime.d.ts +2 -0
  116. package/_vendor/plugin-packaging/feature.d.ts +2 -0
  117. package/_vendor/plugin-packaging/index.d.ts +17 -0
  118. package/_vendor/plugin-packaging/packagingArtwork.d.ts +5 -0
  119. package/_vendor/plugin-packaging/packagingDxf.d.ts +9 -0
  120. package/_vendor/plugin-packaging/packagingGeometry.d.ts +74 -0
  121. package/_vendor/plugin-packaging/packagingInteractions.d.ts +2 -0
  122. package/_vendor/plugin-packaging/packagingPdfExporter.d.ts +25 -0
  123. package/_vendor/plugin-packaging/packagingRuntime.d.ts +11 -0
  124. package/_vendor/plugin-packaging/packagingShapeUtil.d.ts +34 -0
  125. package/_vendor/plugin-packaging/packagingStyle.d.ts +10 -0
  126. package/_vendor/plugin-packaging/packagingSvgExporter.d.ts +7 -0
  127. package/_vendor/plugin-packaging/productRuntime.d.ts +2 -0
  128. package/_vendor/plugin-packaging/types.d.ts +168 -0
  129. package/_vendor/plugin-packaging/validation.d.ts +3 -0
  130. package/_vendor/plugin-path/PathDraftOverlay.d.ts +1 -0
  131. package/_vendor/plugin-path/PathEditInsertPreviewOverlay.d.ts +1 -0
  132. package/_vendor/plugin-path/PathShapeRenderer.d.ts +12 -0
  133. package/_vendor/plugin-path/canvasRender.d.ts +2 -0
  134. package/_vendor/plugin-path/editorRuntime.d.ts +21 -0
  135. package/_vendor/plugin-path/feature.d.ts +2 -0
  136. package/_vendor/plugin-path/index.d.ts +7 -0
  137. package/_vendor/plugin-path/pathBoolean.d.ts +13 -0
  138. package/_vendor/plugin-path/pathDraft.d.ts +10 -0
  139. package/_vendor/plugin-path/pathEditPreview.d.ts +11 -0
  140. package/_vendor/plugin-path/pathEditSelection.d.ts +24 -0
  141. package/_vendor/plugin-path/pathEditSnap.d.ts +6 -0
  142. package/_vendor/plugin-path/pathGeometry.d.ts +74 -0
  143. package/_vendor/plugin-path/pathHandles.d.ts +18 -0
  144. package/_vendor/plugin-path/pathInteractions.d.ts +7 -0
  145. package/_vendor/plugin-path/pathShapeUtil.d.ts +28 -0
  146. package/_vendor/plugin-path/pathSvg.d.ts +3 -0
  147. package/_vendor/plugin-path/pathTool.d.ts +39 -0
  148. package/_vendor/plugin-path/types.d.ts +36 -0
  149. package/_vendor/plugin-text/arrowLabelBindingUtil.d.ts +6 -1
  150. package/_vendor/plugin-text/canvasRender.d.ts +6 -3
  151. package/_vendor/plugin-text/editorRuntime.d.ts +9 -3
  152. package/_vendor/plugin-text/feature.d.ts +4 -4
  153. package/_vendor/plugin-text/geoLabelBindingUtil.d.ts +6 -1
  154. package/_vendor/plugin-text/host/RichTextEditingBox.d.ts +4 -1
  155. package/_vendor/plugin-text/host/TiptapTextEditor.d.ts +5 -2
  156. package/_vendor/plugin-text/host/richTextRendering.d.ts +0 -1
  157. package/_vendor/plugin-text/host/textFormattingApi.d.ts +16 -0
  158. package/_vendor/plugin-text/host/textShapeRendererRuntime.d.ts +3 -1
  159. package/_vendor/plugin-text/host/tiptapTextEditorController.d.ts +4 -1
  160. package/_vendor/plugin-text/index.d.ts +7 -4
  161. package/_vendor/plugin-text/richTextUtils.d.ts +6 -0
  162. package/_vendor/plugin-text/shapeWideTextFormatting.d.ts +8 -0
  163. package/_vendor/plugin-text/textFonts.d.ts +6 -3
  164. package/_vendor/plugin-text/textFormatting.d.ts +45 -0
  165. package/_vendor/plugin-text/textFormattingSession.d.ts +6 -0
  166. package/_vendor/plugin-text/textLabelHelpers.d.ts +9 -4
  167. package/_vendor/plugin-text/textLinkPopoverPresentation.d.ts +18 -0
  168. package/_vendor/plugin-text/textShapeHelpers.d.ts +1 -0
  169. package/_vendor/plugin-text/textShapeUtil.d.ts +5 -4
  170. package/_vendor/signals/effect.d.ts +0 -4
  171. package/_vendor/signals/index.d.ts +1 -1
  172. package/_vendor/store/store.d.ts +4 -0
  173. package/browser/persistence.d.ts +5 -16
  174. package/builtins/controller/createBuiltInCanvasController.d.ts +2 -0
  175. package/builtins/controller/packagingController.d.ts +71 -0
  176. package/builtins/index.d.ts +4 -2
  177. package/builtins/plugins.d.ts +16 -0
  178. package/chrome/floating/CanvasKitFloatingPortal.d.ts +6 -0
  179. package/chrome/floating/useCanvasKitFloatingPosition.d.ts +11 -0
  180. package/chrome/toolbar/CanvasKitFloatingToolbarLayer.d.ts +1 -1
  181. package/chrome/toolbar/toolbarLabels.d.ts +1 -1
  182. package/chrome/toolbar/useToolbarSurfaces.d.ts +6 -10
  183. package/chrome/types.d.ts +5 -10
  184. package/chrome/useCanvasKitChromeContext.d.ts +13 -13
  185. package/chrome/useContextMenuSurface.d.ts +4 -4
  186. package/chrome/useHistoryControls.d.ts +3 -3
  187. package/chrome/usePageControls.d.ts +3 -3
  188. package/controller/canvasKitController.d.ts +5 -9
  189. package/core/index.d.ts +1 -2
  190. package/core/product-controller/canvasProductController.d.ts +2 -1
  191. package/core/runtime/productAssets.d.ts +4 -2
  192. package/core/runtime/productEditor.d.ts +1 -1
  193. package/core/runtime/productServices.d.ts +6 -2
  194. package/core/runtime/runtimeContracts.d.ts +17 -0
  195. package/es-DocrZgUh.mjs +2 -0
  196. package/features/actions/actionRuntime.d.ts +2 -7
  197. package/features/clipboard/clipboardContextMenuContributions.d.ts +1 -1
  198. package/features/clipboard/clipboardContribution.d.ts +2 -1
  199. package/features/clipboard/clipboardPlugin.d.ts +1 -0
  200. package/features/clipboard/clipboardService.d.ts +1 -1
  201. package/features/context-menu/contextMenuRuntime.d.ts +4 -4
  202. package/features/image/asset/imageAssetService.d.ts +1 -1
  203. package/features/image/asset/imageBlobStore.d.ts +6 -2
  204. package/features/image/controller/imageProductController.d.ts +1 -1
  205. package/features/image/imageProductPlugin.d.ts +1 -0
  206. package/features/image/smudge/imageSmudgeHostActions.d.ts +1 -1
  207. package/features/image/smudge/imageSmudgeTypes.d.ts +1 -0
  208. package/features/image/toolbar/imageHostActions.d.ts +13 -2
  209. package/features/image/toolbar/imageToolbarHostBridge.d.ts +1 -1
  210. package/features/keyboard/keyboardShortcutPlugin.d.ts +1 -0
  211. package/features/keyboard/useCanvasKitKeyboardShortcuts.d.ts +5 -3
  212. package/features/selection/selectionActions.d.ts +2 -3
  213. package/features/selection/selectionContextMenuContributions.d.ts +1 -1
  214. package/features/selection/selectionPlugin.d.ts +1 -0
  215. package/features/selection/selectionToolbarContributions.d.ts +1 -1
  216. package/features/text/link/TextLinkHoverPopover.d.ts +6 -0
  217. package/features/text/textProductPlugin.d.ts +5 -0
  218. package/features/tool/toolActions.d.ts +1 -1
  219. package/features/tool/toolContextMenuContributions.d.ts +1 -1
  220. package/features/tool/toolPlugin.d.ts +1 -0
  221. package/features/tool/toolToolbarContributions.d.ts +1 -1
  222. package/features/view/viewActions.d.ts +1 -1
  223. package/features/view/viewContextMenuContributions.d.ts +1 -1
  224. package/features/view/viewPlugin.d.ts +1 -0
  225. package/index.css +1 -1
  226. package/index.d.ts +23 -9
  227. package/index.mjs +84 -96
  228. package/package.json +12 -9
  229. package/product/standardCanvasKitPlugins.d.ts +4 -0
  230. package/react/CanvasKitRoot.d.ts +10 -5
  231. package/react/useCanvasKitControllerLifecycle.d.ts +8 -0
  232. package/react/useCanvasKitRuntime.d.ts +2 -4
  233. package/runtime/canvasKitCommandExecutor.d.ts +13 -0
  234. package/runtime/canvasKitPluginContracts.d.ts +79 -0
  235. package/runtime/canvasKitPlugins.d.ts +33 -0
  236. package/runtime/canvasKitRuntime.d.ts +46 -19
  237. package/runtime/canvasKitRuntimeContracts.d.ts +37 -0
  238. package/_vendor/canvas-core/editor/createEditorWithRuntimePlugins.d.ts +0 -6
  239. package/_vendor/canvas-core/editor/middleMousePanInteraction.d.ts +0 -2
  240. package/_vendor/canvas-core/schema/snapshotSupport.d.ts +0 -43
  241. package/_vendor/canvas-react/host/actionRegistry.d.ts +0 -15
  242. package/_vendor/canvas-react/host/canvasRenderPluginHost.d.ts +0 -2
  243. package/_vendor/canvas-react/host/canvasRenderPluginHostManifest.d.ts +0 -2
  244. package/_vendor/canvas-react/host/canvasRenderPluginHostRuntime.d.ts +0 -3
  245. package/_vendor/canvas-react/host/canvasRenderPluginHostTypes.d.ts +0 -104
  246. package/_vendor/canvas-react/host/canvasRenderPluginHostValidation.d.ts +0 -11
  247. package/_vendor/canvas-react/host/contextMenuRegistry.d.ts +0 -17
  248. package/_vendor/canvas-react/host/extension.d.ts +0 -37
  249. package/_vendor/canvas-react/host/toolbarRegistry.d.ts +0 -20
  250. package/_vendor/plugin-text/host/RichTextLinkPopover.d.ts +0 -14
  251. package/_vendor/plugin-text/host/RichTextToolbar.d.ts +0 -8
  252. package/_vendor/plugin-text/host/richTextBubbleMenuPositionSync.d.ts +0 -7
  253. package/browser/localSnapshotRestore.d.ts +0 -13
  254. package/builtins/extensions.d.ts +0 -18
  255. package/core/runtime/productDefinition.d.ts +0 -33
  256. package/core/runtime/productHost.d.ts +0 -20
  257. package/features/clipboard/clipboardHostExtension.d.ts +0 -2
  258. package/features/image/imageHostExtension.d.ts +0 -10
  259. package/features/keyboard/keyboardShortcutHostExtension.d.ts +0 -2
  260. package/features/persistence/CanvasKitPersistenceNotice.d.ts +0 -4
  261. package/features/persistence/persistenceHostExtension.d.ts +0 -2
  262. package/features/selection/selectionHostExtension.d.ts +0 -2
  263. package/features/tool/toolHostExtension.d.ts +0 -2
  264. package/features/view/viewHostExtension.d.ts +0 -2
  265. package/host/defaultHostExtensions.d.ts +0 -2
  266. package/product/canvasKitProduct.d.ts +0 -51
  267. package/react/useCanvasKitController.d.ts +0 -5
  268. package/react/useCanvasKitStartup.d.ts +0 -9
  269. package/runtime/canvasKitHostContracts.d.ts +0 -135
  270. package/runtime/canvasKitHostFeatureHooks.d.ts +0 -12
  271. package/runtime/canvasKitRuntimePlan.d.ts +0 -50
package/index.mjs CHANGED
@@ -1,96 +1,84 @@
1
- function e(){return gm}function t(){return++gm}function n(e){mm={child:e,parentSet:new Set,below:mm}}function i(){if(!mm)throw new Error("Cannot stop dependency capture because no capture is active");const e=mm;return mm=e.below,e.parentSet}function o(e){mm&&(mm.parentSet.add(e),e.children.add(mm.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 Sm(e,t,n?.isEqual)}function a(e,t,n){return new bm(e,t,n?.isEqual)}function d(e={}){return{id:km,typeName:"document",scope:"document",meta:{...e}}}function l(){return{id:Cm,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function c(e=Cm){return{id:Tm,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...Em}},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&&Bm.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 Rm[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=Lm[n];return i?y(i):e}function k(e){return"string"==typeof e?e:"custom"===e.kind?e.value:`var(${w(e.slot)}, ${Am[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=Am[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 M(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 B(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 wm.FromPoints([new vm(n.minX,n.minY),new vm(n.maxX,n.minY),new vm(n.maxX,n.maxY),new vm(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 wm(n,i,o-n,r-i)}function $(e){if("string"==typeof e)return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");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("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function z(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function _(e){return e[$m]}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 vm(t.x+t.w/2,t.y+t.h/2)):e.offset??Nm})(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 wm(t,n,i-t,o-n)})(t.map(t=>e.getShapePageBounds(t)).filter(e=>!!e))??new wm(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 Wm(`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 Wm(`No ${o} snapshot migration from schema version ${s}`);r=e.up(r)}return r}function Me(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Be(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 Me(e)?e:{}}function Fe(e){return Me(e)?{x:Re(e.x,Em.x),y:Re(e.y,Em.y),z:Math.min(8,Math.max(.1,Re(e.z,Em.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(!Me(e))throw new Wm(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=Re(n,NaN);if(!Number.isFinite(i)||i<1)throw new Wm(`Unsupported ${t} snapshot schema version: ${String(n)}`);if(!Array.isArray(e.records))throw new Wm(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:1,records:Ee(e.records,i,1,"document"===t?Ym:Xm,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(!Me(e))throw new Wm("Invalid document record: expected object");if("string"!=typeof e.id)throw new Wm("Invalid document record id");if(o.has(e.id))throw new Wm(`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 Wm(`Unsupported document record type: ${String(e.typeName)}`);r.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new Wm("Invalid asset record id");if("string"!=typeof e.type)throw new Wm("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:Me(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 Wm("Invalid binding record id");if("string"!=typeof e.type)throw new Wm("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new Wm(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new Wm(`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 Wm("Invalid shape record id");if("string"!=typeof e.type)throw new Wm("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new Wm(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:Be(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 Wm("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:Be(e.name,`Page ${t+1}`),index:Be(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 Wm("Invalid document metadata record id");return{id:km,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(!Me(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(!Me(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(!Me(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:Be(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 vm.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 vm(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 Pm.Translate(n.x,n.y).compose(Pm.Rotate(e.rotation)).compose(Pm.Scale(e.scaleX,e.scaleY)).compose(Pm.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 vm(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 vm(n.minX,n.minY),new vm(n.maxX,n.minY),new vm(n.maxX,n.maxY),new vm(n.minX,n.maxY)].map(n=>Qe(e,n,t))})(e,t);return{bounds:wm.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)<jm?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 wm(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))<jm;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))>jm),g=c?.center??null,f=0===i.length?null:Math.abs(h)<jm||!g?wm.FromPoints(i):wm.FromPoints(i.map(e=>vm.RotWith(e,g,-h))),m=o.length>0?wm.FromPoints(o):null;return{outlineVertices:i,pageBounds:c,frameBounds:f,rotation:h,rotationCenter:g,selectionAnchorPagePoint:f&&g?Math.abs(h)<jm?new vm(f.center.x,f.minY):vm.RotWith(new vm(f.center.x,f.minY),g,h):m?new vm(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 wm(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 wm(n,i,o-n,r-i)}function Et(e,t){return t.canReceiveChildren(e)&&!t.isTransformDescendantContainer(e)}function Mt(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 Bt(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new vm(n.minX,n.minY),new vm(n.maxX,n.minY),new vm(n.maxX,n.maxY),new vm(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!==Mt(e,t,n,r))return!0}return!1}function Rt(e,t){return wm.FromPoints([new vm(e.minX,e.minY),new vm(e.maxX,e.minY),new vm(e.maxX,e.maxY),new vm(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 wm(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 wm(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 wm(l<0?e.minX:e.maxX-a,c<0?e.minY:e.maxY-d,a,d);break;case"top_right":u=new wm(l<0?e.maxX-a:e.minX,c<0?e.minY:e.maxY-d,a,d);break;case"bottom_right":u=new wm(l<0?e.maxX-a:e.minX,c<0?e.maxY-d:e.minY,a,d);break;case"bottom_left":u=new wm(l<0?e.minX:e.maxX-a,c<0?e.maxY-d:e.minY,a,d);break;case"top":u=new wm(t.center.x-a/2,c<0?t.maxY:t.maxY-d,a,d);break;case"right":u=new wm(l<0?t.minX-a:t.minX,t.center.y-d/2,a,d);break;case"bottom":u=new wm(t.center.x-a/2,c<0?t.minY-d:t.minY,a,d);break;case"left":u=new wm(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 vm(e.minX,e.minY),new vm(e.center.x,e.minY),new vm(e.maxX,e.minY),new vm(e.minX,e.center.y),e.center,new vm(e.maxX,e.center.y),new vm(e.minX,e.maxY),new vm(e.center.x,e.maxY),new vm(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 wm(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 vm(t,0):new vm(0,t))(t,n))}function Zt(e){return[new vm(e.minX,e.minY),new vm(e.maxX,e.minY),new vm(e.maxX,e.maxY),new vm(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 vm(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 vm(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?Jm[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 vm(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new vm(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new vm(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new vm(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 vm(e.startNode.bounds.maxX,e.startNode.bounds.minY),new vm(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new vm(e.endNode.bounds.minX,e.endNode.bounds.minY),new vm(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new vm(e.startNode.bounds.minX,e.startNode.bounds.maxY),new vm(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new vm(e.endNode.bounds.minX,e.endNode.bounds.minY),new vm(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 vm(t,n.minY),new vm(t,n.maxY)]:[new vm(n.minX,t),new vm(n.maxX,t)]}function vn(e,t){if(0===t.length)return[vm.Zero(),vm.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 vm(n,o),new vm(n,r)]:[new vm(n,o),new vm(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 vm(n.x,t.y):new vm(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:vm.Zero()}}function Tn(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new vm(0,n.y):new vm(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 Mn(e,t){return 0===t.rotation?e.clone():vm.RotWith(e,t.rotationCenter,-t.rotation)}function Bn(e,t){return 0===t.rotation?e.clone():vm.RotWith(e,t.rotationCenter,t.rotation)}function Rn(e,t){return Bn(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 vm(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 vm(t.minX+t.maxX-n.x,n.y):new vm(n.x,t.minY+t.maxY-n.y)}function $n({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new wm(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new wm(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 vm(e.maxX+t,e.minY-t):new vm(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:vm.RotWith(e,p,h),I=new vm(u.minX,u.minY),v=new vm(u.center.x,u.minY),w=new vm(u.maxX,u.minY),P=new vm(u.maxX,u.center.y),k=new vm(u.maxX,u.maxY),C=new vm(u.center.x,u.maxY),T=new vm(u.minX,u.maxY),E=new vm(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 wm(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 vm(e.x+i.x*s,e.y+i.y*s)})(t,n,e))}function Mi(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 Bi(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 vm(e.minX,e.minY),new vm(e.maxX,e.minY),new vm(e.maxX,e.maxY),new vm(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 vm(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 vm.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?vm.Zero():new vm(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 vm(e.minX,e.minY),fromBounds:t,toBounds:n}),o=Ln({point:new vm(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new wm(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=Bn(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=Bn(Zi({point:t.startLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u),p=Bn(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 vm(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 vm(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 xm(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 KS;return t.registerCanvasRenderPlugins(e),t}function so(e,t){return(e.order??0)-(t.order??0)}function ao(e=[]){const t=new jS;return t.registerCanvasRenderPlugins(e),t}function lo(){return Kf(ZS)}function co(e=[]){const t=new QS;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 JS;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 ey;return t.registerEditorRuntimePlugins(e),t}function yo(e,t){return t?ty:k(e)}function bo(e){if(!e.createFeature&&!e.addExtensions)throw new Error(`Land extension "${e.name}" must define createFeature() or addExtensions().`);return new ny(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 XS;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 Mo(e){Eo(e)&&window.open(e,"_blank","noopener,noreferrer")}function Bo(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 Bo("");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('"',"&quot;")}" 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("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}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 tm("p",{style:{margin:0},children:o.length>0?o:tm("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)?tm("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):tm("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]=Qf(!1),[s,a]=Qf(!1),[d,l]=Qf(""),[c,u]=Qf(!1),h=Zf(null);return Vf(()=>{a(!1),l(e?.href??""),u(!1)},[e?.href,e?.path]),Vf(()=>()=>{null!==h.current&&window.clearTimeout(h.current)},[]),e&&"undefined"!=typeof document?im(tm("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?nm("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
- tm("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
- tm("button",{type:"submit","aria-label":"Apply link",title:"Apply link",style:fy,children:tm(cy,{size:14,strokeWidth:2})}),
5
- tm("button",{type:"button","aria-label":"Cancel",title:"Cancel",onClick:()=>{a(!1),l(e.href),u(!1)},style:fy,children:tm(gy,{size:14,strokeWidth:2})})]}):nm(em,{children:[
6
- tm("button",{type:"button","aria-label":"Open link",title:"Open link",onClick:()=>{Mo(e.href)},style:fy,children:tm(uy,{size:14,strokeWidth:2})}),
7
- tm("button",{type:"button",title:e.href,onClick:()=>{Mo(e.href)},style:my,children:e.href}),
8
- tm("button",{type:"button","aria-label":"Edit link",title:"Edit link",onClick:()=>{a(!0)},style:fy,children:tm(py,{size:14,strokeWidth:2})})]})}),document.body):null}function qo(){return{defaultFont:yy,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:Sy,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=by.get(e);if(t)return t;const n=new Map;return by.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=Kf(xy);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function ir(e){const t=Xf(t=>oo("useValue",e,t,{fireImmediately:!1}),[e]),n=Xf(()=>e.get(),[e]);return Jf(t,n,n)}function or({children:e,className:t,dataUi:n}){const i=nr(),o=Zf(null);return jf(()=>oo("PageSpace.transform",i.pageTransformSignal,()=>{const e=o.current;e&&(e.style.transform=i.pageTransformSignal.get().toCssString())}),[i]),tm("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 nm("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:[tm(or,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:tm(Iy,{})}),e?tm(vy,{}):null]})}function sr(){
10
- return tm("div",{"data-ui":"transform-descendant-ancestor-boundary",style:{position:"absolute",inset:0,border:"1px dashed #64748b",pointerEvents:"none"}})}function ar(){
11
- return tm("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?tm(em,{children:e}):t.reduceRight((e,t)=>tm(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 tm(em,{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 vm(e.minX,e.minY),new vm(e.maxX,e.minY),new vm(e.maxX,e.maxY),new vm(e.minX,e.maxY)])(i).map(e=>s.applyToPoint(r.applyToPoint(e))).map(cr).join(", ")})`})(i,o,n);return r?tm("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}):tm(em,{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 nm("g",{style:{pointerEvents:"none"},children:[tm("line",{...c.underlay,x1:l.start.x,y1:l.start.y,x2:l.end.x,y2:l.end.y,fill:"none",stroke:ky,strokeLinecap:"round",strokeWidth:2.2*o}),tm("line",{...c.segment,x1:l.start.x,y1:l.start.y,x2:l.end.x,y2:l.end.y,fill:"none",stroke:Py,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 nm("g",{style:{pointerEvents:"none"},children:[tm("path",{...s.underlay,d:e,fill:"none",stroke:ky,strokeLinecap:"round",strokeWidth:2.2*t}),tm("path",{...s.segment,d:e,fill:"none",stroke:Py,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:tm("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 Uy[Math.round(n)%Uy.length]??"default"}function Sr({handle:e,strokeWidth:t}){
14
- return tm("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 tm("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:tm(or,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:tm(Ky,{})})})}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(jy)??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 vm(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 nm("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:[tm("defs",{children:Gy.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 tm("pattern",{id:`land-canvas-grid-${i}`,width:o,height:o,patternUnits:"userSpaceOnUse",children:tm("circle",{cx:r.x,cy:r.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:s})},i)})}),Gy.map(({step:e})=>tm("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function Mr(e,t,n){return n?"grabbing":"hand"===e?t?"grabbing":"grab":"select"===e?void 0:"crosshair"}function Br({canvasComponents:e,canvasProviders:t,domEventGuardRegistry:n,onContextMenuRequest:i,overlayRegistry:o,rendererRegistry:r,showGrid:s=!1}={}){const a=nr(),d=Gf(()=>r??ro(),[r]),l=Gf(()=>o??ao(),[o]),c=Gf(()=>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=Zf(null),s=Zf(null),a=Zf(null),d=Zf(null),l=Zf(null),c=Zf(null),u=Zf(null),[h,p]=Qf(!1),[g,f]=Qf(!1),[m,S]=Qf(void 0);Vf(()=>{("select"!==t||o)&&n.setHoveredShapeId(null)},[t,n,o]);const y=Xf(()=>{null!==l.current&&(cancelAnimationFrame(l.current),l.current=null),c.current=null},[]),b=Xf(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=Xf(()=>{null===l.current&&(c.current=null,l.current=requestAnimationFrame(b))},[b]);return Vf(()=>{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 vm(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 vm(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)},M=e=>{u.current={x:e.clientX,y:e.clientY},m(),e.pointerId===a.current?C("pointer_cancel",e):g("pointer_cancel",e)},B=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",M),i.addEventListener("pointerleave",T),i.addEventListener("wheel",P,{passive:!1}),B.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",M),i.removeEventListener("pointerleave",T),i.removeEventListener("wheel",P),B.disconnect()}},[e,t,n,o,y]),{containerRef:r,handlers:{onPointerDown:Xf(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:Xf(e=>{1!==e.button||xr(e.target)||(e.preventDefault(),e.stopPropagation())},[]),onContextMenu:Xf(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 nm("div",{ref:p,"data-ui":qy,className:"land-canvas__surface",tabIndex:0,style:{cursor:S??Mr(u,f,m)},...g,children:[s?tm(Er,{}):null,tm(qS.Provider,{value:d,children:tm(ZS.Provider,{value:l,children:nm(Rr,{providers:t,children:[
19
- tm(rr,{}),e?.map(({id:e,component:t})=>tm(t,{},e)),
20
- tm(br,{})]})})})]})}function Rr({children:e,providers:t}){
21
- return tm(em,{children:t?.reduceRight((e,{id:t,component:n})=>tm(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??Bo("")},[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=tb){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 nb[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=ob.get(e);if(t)return t;const n=new ib(e);return ob.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 vm(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=Gf(()=>({strategy:"fixed",placement:"top",offset:Qr("--toolbar-floating-offset",8),flip:!0,shift:{padding:Qr("--toolbar-floating-shift-padding",8)}}),[]),[i,o]=Qf(!1);return function({landEditor:e,textEditor:t}){const n=Zf(null);Vf(()=>{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(rb,sb))})(t)}))});return()=>{i(),null!==n.current&&(window.cancelAnimationFrame(n.current),n.current=null)}},[e,t])}({landEditor:t,textEditor:e}),e.isDestroyed?null:tm(hm,{editor:e,pluginKey:rb,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?tm(ss,{editor:e,onDone:()=>{o(!1)}}):nm(em,{children:[
22
- tm(as,{children:"Text"}),
23
- tm(ds,{}),ab.map(t=>tm(os,{editor:e,format:t.id,label:t.label,shortcut:t.shortcut,dataUi:t.dataUi,children:t.content},t.id)),
24
- tm(ds,{}),
25
- tm(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=Zf(!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 tm("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:{...cb,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=Zf(!1),i=e.isActive("link"),o=e.isDestroyed||void 0===e.schema.marks.link,r=()=>{o||t()};
27
- return tm("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:{...cb,background:i?"var(--accent)":"transparent",color:i?"var(--accent-foreground)":"var(--muted-foreground)",cursor:o?"not-allowed":"pointer",opacity:o?.45:1},children:tm(hy,{size:14,strokeWidth:2})})}function ss({editor:e,onDone:t}){const[n,i]=Qf((e=>{const t=e.getAttributes("link").href;return"string"==typeof t?t:void 0})(e)??""),[o,r]=Qf(!1);
28
- return nm("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
- tm(as,{children:"Link"}),
30
- tm(ds,{}),
31
- tm("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
- tm("button",{type:"submit","aria-label":"Apply link",title:"Apply link",style:ub,children:tm(cy,{size:14,strokeWidth:2})}),
33
- tm("button",{type:"button","aria-label":"Cancel",title:"Cancel",onClick:n=>{n.preventDefault(),n.stopPropagation(),t(),e.commands.focus()},style:ub,children:tm(gy,{size:14,strokeWidth:2})})]})}function as({children:e}){
34
- return tm("div",{"data-ui":"rich-text-formatting-toolbar-title",style:db,children:e})}function ds(){
35
- return tm("div",{"aria-hidden":"true",style:lb})}function ls({landEditor:e,shape:t,fontCatalog:n,initialRichText:i,className:o,editorStyle:r,onReady:s,onDispose:a,onRichTextChange:d}){const[l,c]=Qf(0),u=Zf(null),h=Xf(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=rm({extensions:pb,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 Vf(()=>{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]),Vf(()=>{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]),nm(em,{children:[p?tm(es,{editor:p,landEditor:e,version:l}):null,tm(om,{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?tm(fs,{shape:o,session:r,fontCatalog:n},`${o.id}:${t}`):null}function fs({shape:e,session:t,fontCatalog:n}){const i=nr(),o=Zf(e.props.richText),r=(e=>{const t=Zf(e);return Vf(()=>{t.current=e},[e]),t})(e),s=ir(i.shapeEditingEntryRequestSignal),a=Zf(null),[d,l]=Qf(null),[c,u]=Qf(null),h=Xf(({editor:e,controller:t})=>{l(e.isDestroyed?null:e),u(t)},[]),p=Xf(({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=Zf(t.props.richText),a=Zf(!1),d=Zf(null),l=Xf(({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 Vf(()=>()=>{null!==d.current&&(window.clearTimeout(d.current),d.current=null)},[]),jf(()=>{n&&i&&!n.isDestroyed&&i.isConnected()&&us(e,i,t)},[e,i,t,n]),Vf(()=>{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]),Vf(()=>{if(i)return i.onCompositionStateChange(t=>{e.setShapeEditingComposition(t,"system")})},[e,i]),Vf(()=>{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=Zf(null),d=Zf(null);Vf(()=>{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]),Vf(()=>{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]),Vf(()=>{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]),Vf(()=>{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=Zf(null);return{onPointerDownCapture:Xf(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:Xf(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:Xf(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:Xf(()=>{i.current=null},[])}})({editor:i,shapeId:e.id,richTextController:c}),m=((e,t)=>Gf(()=>({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=Xf(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(),Mo(t))},[d]);
36
- return tm("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:tm(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:[fb],canvasComponents:[{id:"land.text.default-font-preload",component:()=>tm(Ss,{fontCatalog:e})}],shapeRenderers:[{type:"text",component:t=>tm(ys,{...t,fontCatalog:e})}]}}function Ss({fontCatalog:e}){return Vf(()=>{Jo(Sy,e)},[e]),null}function ys({shape:e,editor:t,isHovered:n,fontCatalog:i}){const[o,r]=Qf(null),s=Zf(null),{isEditingThisShape:a,editingHost:d}=function(e,t,n){const i=ir(e.shapeEditingStateSignal).session,o=i?.shapeId===t.id,r=i&&o?tm(gs,{shapeId:i.shapeId,markId:i.markId,fontCatalog:n},i.shapeId+":"+i.markId):null;return(({editor:e,shape:t,isEditingThisShape:n,fontCatalog:i})=>{jf(()=>{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=Xf(()=>{null!==s.current&&(window.clearTimeout(s.current),s.current=null)},[]),c=Xf(()=>{l(),s.current=window.setTimeout(()=>{r(null),s.current=null},160)},[l]);return Vf(()=>()=>{l()},[l]),Vf(()=>{a&&(l(),r(null))},[l,a]),nm("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
- tm("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
- tm(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
- tm("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?tm("div",{"aria-hidden":"true","data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 2px ${ty}`,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 vb);if(!i)return null;const o=i.type;return{label:n,ownerId:i.toId,bindingType:o,behavior:vb[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 Ms(e){return e.props.h*Ts(e)}function Bs(e){return new wm(0,0,Es(e),Ms(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=vm.Med(n,i).add(i.sub(n).len()?i.sub(n).per().normalize().mul(-o):new vm(0,o)),s=new vm(e.x+(e=>_s(e.props.w)??1)(e)/2,e.y+(e=>_s(e.props.h)??1)(e)/2),a=new vm(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 vm(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 vm(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:Bb,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:Bb},"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:Bb},"user"),"handled"):"continue":"geo"===n.type?((e,t)=>{if(t.isLocked)return"continue";const n=vs(e,t.id,Ib);return ks(e,n??((e,t)=>{const n=Xs(e,Vs(t,{...Fr(e),autoSize:!1,textAlign:"middle"}),t);return ws(e,{bindingType:Ib,owner:t,historyMarkId:Fb,index:`${t.index}${Eb}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})})(e,t),{editMarkId:Lb,createMarkId:Fb,isExisting:!!n}),"handled"})(e,n):(e=>"arrow"===e.type)(n)?((e,t)=>{if(t.isLocked)return"continue";const n=vs(e,t.id,xb);return ks(e,n??((e,t)=>{const n=Ds(e,Vs(t,{...Fr(e),autoSize:!1,textAlign:"middle"}),t);return ws(e,{bindingType:xb,owner:t,historyMarkId:Ab,index:`${t.index}${Cb}`,layout:n,bindingProps:{labelPosition:.5}})})(e,t),{editMarkId:Rb,createMarkId:Ab,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:Bb,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 Pb],shapeSvgExporters:[new kb(e)],bindingUtils:[new Mb,new Tb],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:[WS],getGroups:e=>[{id:"text.tools",items:[{kind:"button",id:"text.tool.text",actionId:WS,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 Sb(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:$b.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:Ub.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:Db.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 Ub.some(e=>e.value===t)?t:void 0}return"string"==typeof t&&Db.some(e=>e.value===t)?t:void 0}function ta({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){
40
- return tm("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){Vf(()=>{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?tm(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=Zf(null);return ia(s),jf(()=>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]),tm(or,{dataUi:`${i}-page-space`,className:sa("land-canvas__floating-selection-page-space",n),children:tm("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=Xf(t=>n?e.subscribe(t):()=>{},[n,e]),r=Xf(()=>n?e.getSnapshot(i):_b,[n,i,e]);return Jf(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 vm(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 vm(e.x+e.props.w/2,e.y+e.props.h/2),i=t.sub(n);return n.add(new vm(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))})(e,new vm(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 vm(e.props.start.x,e.props.start.y).add(new vm(e.x,e.y)),new vm(e.props.end.x,e.props.end.y).add(new vm(e.x,e.y)),e.props.bend)}function ma(e,t,n){const i=vm.Med(e,t),o=t.sub(e);if(o.len()<1e-6)return 0;const r=o.per().normalize();return-Ma(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=vm.Med(e,t),o=t.sub(e),r=o.len()?o.per().normalize():new vm(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 vm(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=(Hb-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:wm.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:wm.FromPoints(l),path:c}}function Ia(e,t,n,i){const o=[],r=vm.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=vm.Angle(n.center,e),o=vm.Angle(n.center,t),n.sweepFlag?((o-i)%Hb+Hb)%Hb:-((i-o)%Hb+Hb)%Hb;var i,o}function wa(e,t,n,i){const o=vm.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 vm(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*Ma(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,Ma(r,i)/o)),a=t.add(i.mul(s));return e.dist(a)}function Ma(e,t){return e.x*t.x+e.y*t.y}function Ba(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||Ba(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 vm(-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||Ba(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(!Ba(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(!Ba(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(!Ba(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 Ba(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||Ba(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})=>Ba(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(!Ba(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(!Ba(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:qb.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:jb.map(e=>({...e,dataUi:`${o}-stroke-width-${e.value}-button`}))}]},{id:`${o}.head-start`,items:[{kind:"segmented",id:`${o}.head-start`,actionId:n,options:Gb.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:Gb.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&&jb.some(e=>e.value===t)?t:void 0:"stroke"===e?v(t)?P(t,y("stroke-slate")):void 0:Gb.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 nm("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,overflow:"visible",children:[nm("defs",{children:[tm("marker",{id:r,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"2",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:tm("path",{d:"M8.9,8 L2,12 L8.9,16",fill:"none",stroke:d,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),tm("marker",{id:s,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"22",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:tm("path",{d:"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:d,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),tm("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 vm(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=vm.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=vm.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=vm.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 Md(e,t,n){return e.map(e=>({points:Ed(e.points,t,n)}))}function Bd(e){return{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}}function Rd(e,t){const n=Bd(t);return Td(e,e=>Mn(e,n))}function Ad(e,t){const n=Bd(t);return Td(e,e=>Bn(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 vm(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 vm(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 vm(1,0);if(t===e.length-1)return r.len2()>0?r:new vm(1,0);const a=r.add(s);return a.len2()>1e-6?a.uni():s.len2()>0?s:r.len2()>0?r:new vm(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,Qb,1),d=null===t?$d(.5,a,.275):$d(t,a,.275*Math.max(s,.36));if(r)return Fd(d,Qb,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)),Qb,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=vm.Angle(e,t),r=[];for(let s=1;s<n;s+=1){const t=o-Math.PI*(s/n);r.push(new vm(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 vm(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?wm.FromPoints(a):new wm(0,0,1,1),l=t.length>0?wm.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=Jb.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:vm.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||Jb.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 vm(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():vm.Lrp(r,n,d).per().uni();c.len2()<1e-6&&(c=a??new vm(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 wm(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 vm(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 vm(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))}function Qd(e){const t=e,n=ex.get(t);if(n)return n;const i=Vd(qd(e.props),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed);return ex.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 vm(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=tx.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 tx.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=nx.get(t);if(n)return n;if(0===e.rotation&&1===e.scaleX&&1===e.scaleY){const n=el(e);return nx.set(t,n),n}const i=Qd(e),o=Gd(e,i),r=Xd({segments:Td(i.normalizedSegments,t=>Zd(e,new vm(t.x+e.x,t.y+e.y),o)),outlineVertices:i.outlineVertices.map(t=>Zd(e,new vm(t.x+e.x,t.y+e.y),o)),outlinePolygons:i.outlinePolygons.map(t=>t.map(t=>Zd(e,new vm(t.x+e.x,t.y+e.y),o))),strokeWidth:e.props.strokeWidth,sampling:i.sampling,isClosed:e.props.isClosed});return nx.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 vm(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:hx.map(e=>({...e,dataUi:`${o}-${e.value}-button`}))}]},{id:`${o}.style-fill`,items:[{kind:"swatches",id:`${o}.fill`,actionId:t,label:"Fill",options:cx.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:lx.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:ux.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&&ux.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 nm("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)?tm("path",{d:o,fill:k(e.props.fill),stroke:"none"}):null,e.props.isClosed&&a?tm("path",{d:a,fill:"none",stroke:d,strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round"}):s?tm("path",{d:s,fill:d,stroke:"none"}):null]})}function Tl({shape:e,isHovered:t}){
43
- return tm(Cl,{shape:e,isHovered:t})}function El(e){return 4/e.getCurrentCamera().z}function Ml(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 Bl(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&&Ml(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=vx/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(Ex,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*Bx,Mx,Rx);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:_x.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:Hx.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:Nx.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&&Nx.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 tm(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 nm("svg",{width:"100%",height:"100%",viewBox:`0 0 ${a} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[tm("rect",{x:d,y:d,width:l,height:c,fill:k(n),stroke:u,strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"}),tm("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 vm(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 vm(e.center.x,e.minY),new vm(e.maxX,e.center.y),new vm(e.center.x,e.maxY),new vm(e.minX,e.center.y)];case"triangle":return[new vm(e.center.x,e.minY),new vm(e.maxX,e.maxY),new vm(e.minX,e.maxY)];case"hexagon":return[new vm(e.minX+.25*e.w,e.minY),new vm(e.maxX-.25*e.w,e.minY),new vm(e.maxX,e.center.y),new vm(e.maxX-.25*e.w,e.maxY),new vm(e.minX+.25*e.w,e.maxY),new vm(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 vm(Math.cos(e)*i,Math.sin(e)*i))}return((e,t)=>{const n=wm.FromPoints([...e]);return 0===n.w||0===n.h?[t.center]:e.map(e=>new vm(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 vm(t+Math.cos(r)*o,n+Math.sin(r)*o))}}function Ic(e){return[new vm(e.minX,e.minY),new vm(e.maxX,e.minY),new vm(e.maxX,e.maxY),new vm(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&&Jx.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 Mc(e,t,n,i)?0:Math.min(Tc(e,n,i),Tc(t,n,i),Tc(n,e,t),Tc(i,e,t))}function Mc(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 Bc(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=Mc(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 wm(0,0,e.props.w,e.props.h),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}function Ac(e){const t=new wm(0,0,e.props.w,e.props.h);return[new vm(t.minX,t.minY),new vm(t.center.x,t.minY),new vm(t.maxX,t.minY),new vm(t.minX,t.center.y),t.center,new vm(t.maxX,t.center.y),new vm(t.minX,t.maxY),new vm(t.center.x,t.maxY),new vm(t.maxX,t.maxY)].map((e,t)=>({point:e,kind:eI[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:iI.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:oI.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:rI.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&&rI.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 sI.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 tm(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 wm(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 tm("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:"ellipse"===r?tm("ellipse",{...u,cx:e.props.w/2,cy:e.props.h/2,rx:a/2,ry:d/2}):"rectangle"!==r?tm("polygon",{...u,points:c??""}):tm("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 tm(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 tm("svg",{width:"100%",height:"100%",viewBox:`0 0 ${o} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:r?tm("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<xI&&(o=Math.max(0,Math.min(.9999,(o+r)/2-5e-5)),r=o+xI),{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)<=II&&Math.abs(e.top-t.top)<=II&&Math.abs(e.right-t.right)<=II&&Math.abs(e.bottom-t.bottom)<=II}function Jc(e){return(e=>Math.abs(e.left)<=II&&Math.abs(e.top)<=II&&Math.abs(1-e.right)<=II&&Math.abs(1-e.bottom)<=II)(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,xI,1),r=Kc(n,xI,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`${PI}${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 vm(0,0),top:new vm(o,0),top_right:new vm(n,0),right:new vm(n,r),bottom_right:new vm(n,i),bottom:new vm(o,i),bottom_left:new vm(0,i),left:new vm(0,r)};return TI.map(t=>{return{kind:"custom",type:vI,id:t,point:e.applyToPoint(s[t]),cursor:(n=t,CI[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){EI.delete(e)}function lu(e){const t=DI.get(e);if(t)return t;const n=new UI(e);return DI.set(e,n),n}function cu(e){return`${AI}${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:LI,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:FI,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){return lu(e).getActiveSession()}function mu(e,t){lu(e).addPoint(t)}function Su(e){lu(e).endStroke()}async function yu(e,t){return lu(e).requestConfirm(t)}function bu(e){return{x:e.x,y:e.y,...void 0===e.pressure?{}:{pressure:e.pressure}}}function xu(e){return m(e)&&"image"===e.type}function Iu(e){return p(e)&&"image"===e.type}function vu(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return null;const[t]=e.selection.selectedShapes;return Iu(t)?t:null}function wu(e){const t=vu(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!iu(t,n.markId))}function Pu(e){const t=vu(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!uu(t,n.markId))}function ku(){return[{id:gI,isVisible:e=>!!vu(e)&&!wu(e),isEnabled(e){const t=vu(e);return!!t&&!t.isLocked},getValue:e=>wu(e),run({context:e}){const t=vu(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=>{EI.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:fI,isVisible:e=>wu(e),isEnabled:e=>wu(e),run({context:e}){const t=vu(e);t&&e.editor.completeEditing("user")&&du(t.id)}},{id:mI,isVisible:e=>wu(e),isEnabled(e){const t=vu(e);return!!t&&!t.isLocked},run({context:e,value:t}){const n=vu(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(xI/n.width,xI/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:SI,isVisible:e=>wu(e),isEnabled(e){const t=vu(e);return!!t&&!t.isLocked},getValue(e){const t=vu(e);return t?(e=>{const t=e.props.w/e.props.h;for(const n of kI)if(Math.abs(t-n.ratio)<=.01)return n.value;return null})(t):null},run({context:e,value:t}){const n=vu(e);if(!n||n.isLocked||"string"!=typeof t)return;const i=kI.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=kI.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 vm((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:yI,isVisible:e=>wu(e),isEnabled(e){const t=vu(e);return!!t&&!t.isLocked&&!!t.props.crop},run({context:e}){const t=vu(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)<=II&&Math.abs(t.y-i)<=II&&Math.abs(t.props.w-o)<=II&&Math.abs(t.props.h-r)<=II&&(null===t.props.crop&&null===s||null!==t.props.crop&&null!==s&&Math.abs(t.props.crop.topLeft.x-s.topLeft.x)<=II&&Math.abs(t.props.crop.topLeft.y-s.topLeft.y)<=II&&Math.abs(t.props.crop.bottomRight.x-s.bottomRight.x)<=II&&Math.abs(t.props.crop.bottomRight.y-s.bottomRight.y)<=II)?null:{id:t.id,x:n,y:i,props:{w:o,h:r,crop:s}}})({baselineShape:(i=t.id,EI.get(i)??null??t),shape:t});var i;n&&e.editor.commands.updateShapes([n],{source:"user"})}}]}function Cu(){return{createSession(e,{handle:t,shape:n,originPagePoint:i}){return Iu(n)&&"custom"===t.kind&&"image.crop"===t.type&&(o=t.id,TI.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(!Iu(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 vm(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 Tu(){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=Eu(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 vm(t,0);case"ArrowRight":return new vm(-t,0);case"ArrowUp":return new vm(0,t);case"ArrowDown":return new vm(0,-t);default:return null}})(t);if(i){const t=(({pageDelta:e,shape:t,startCrop:n})=>{const i=jc(n);return!i||e.equals(vm.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(wI),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=Eu(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(wI,"shape.edit"),t(),"handled"):"continue":"continue"}},selectionHandle:Cu()}}function Eu(e){const[t]=e.getSelectedShapes();if(!Iu(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(wI),n.hasDragged=!0}if(!Iu(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 vm(0,d.y):new vm(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 Bu(e){return{id:e,isVisible:()=>!1,isEnabled:()=>!1,run(){throw new Error(`Image toolbar action ${e} requires a host implementation.`)}}}function Ru(e,t=0){return Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t)}function Au({cornerRadius:e,h:t,w:n}){return Math.min(Ru(e),Math.max(0,n)/2,Math.max(0,t)/2)}function Lu(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Fu(){let e=null;const t=t=>{e=null,Su(t)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(n,i){if("keyboard"===i.type)return((e,t)=>"key_down"!==t.name?"continue":$u(e)?"Escape"!==t.key||t.altKey||t.accelKey?("Enter"!==t.key||t.altKey||t.accelKey||yu(e,{replace:!0}),"handled"):(gu(e),"handled"):"continue")(n,i);if("cancel"===i.type)return $u(n)?(t(n),gu(n),"handled"):"continue";if("pointer"!==i.type)return"continue";const o=$u(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=Du(n,o,i.pagePoint),s=zu(r,o);return e={mode:s?"draw":"pan",originCamera:s?null:n.getCurrentCamera(),originScreenPoint:s?null:i.screenPoint.clone(),pointerId:i.pointerId},s&&mu(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?Uu(n,o,i):"pan"===e.mode&&e.originCamera&&e.originScreenPoint&&1&i.buttons?_u(n,i,e):Su(n),"handled"):"pointer_up"===i.name?("draw"===e.mode?Uu(n,o,i):"pan"===e.mode&&_u(n,i,e),t(n),"handled"):"pointer_cancel"===i.name?(t(n),"handled"):"handled":"handled"}}}}function $u(e){const[t]=e.getSelectedShapes();if(!Iu(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&uu(t,n.markId)?t:null}function Uu(e,t,n){const i=Du(e,t,n.pagePoint);zu(i,t)?mu(e,{x:i.x,y:i.y,pressure:n.pressure}):Su(e)}function Du(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function zu(e,t){return e.x>=0&&e.y>=0&&e.x<=t.props.w&&e.y<=t.props.h}function _u(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 Hu({dataUiPrefix:e}){return{kind:"text-input",id:`${e}.corner-radius`,actionId:bI,label:"Corner radius",placeholder:"0",dataUi:`${e}-corner-radius-control`}}function Nu({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=Au({cornerRadius:n.props.cornerRadius,h:a,w:d}),u=((e,t)=>Jf(t=>((e,t)=>lu(e).subscribe(t))(e,t),()=>((e,t)=>lu(e).getSnapshot(t))(e,t),()=>null))(e,n.id);if(!l)return tm("div",{"data-ui":"image-shape-missing-asset",style:{alignItems:"center",background:"#f1f5f9",border:`1px solid ${t?ty:"#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 nm("div",{"data-ui":"image-shape",style:{display:"block",height:a,overflow:e?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:d},children:[e?tm("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:l,style:{...r,opacity:.1}}):null,
51
- nm("div",{"data-ui":"image-crop-window",style:{height:a,overflow:"hidden",position:"absolute",borderRadius:c,inset:0,width:d},children:[tm("img",{alt:o,draggable:!1,src:l,style:r}),tm(Ou,{shape:n,session:u})]}),
52
- tm(Yu,{cornerRadius:c,isVisible:t})]})}
53
- return nm("div",{"data-ui":"image-shape",style:{borderRadius:c,display:"block",height:a,overflow:"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:d},children:[
54
- tm("img",{alt:o,draggable:!1,src:l,style:{display:"block",height:a,objectFit:"fill",width:d}}),
55
- tm(Ou,{shape:n,session:u}),
56
- tm(Yu,{cornerRadius:c,isVisible:t})]})}function Ou({shape:e,session:t}){return t&&t.shapeId===e.id&&0!==t.strokes.length?tm("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=>tm(Wu,{stroke:e},e.id))}):null}function Wu({stroke:e}){const t=e.points[0];if(!t)return null;const n=e.brush.color??"#111827",i=e.brush.opacity??.45,o=e.brush.size;if(1===e.points.length)return tm("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 ${Vu(t.x)} ${Vu(t.y)}`,...n.map(e=>`L ${Vu(e.x)} ${Vu(e.y)}`)].join(" "):null})(e);return r?tm("path",{d:r,fill:"none",opacity:i,stroke:n,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o}):null}function Yu({cornerRadius:e,isVisible:t}){return t?tm("div",{"aria-hidden":"true","data-ui":"image-hover-outline",style:{borderRadius:e,boxShadow:`inset 0 0 0 2px ${ty}`,inset:0,pointerEvents:"none",position:"absolute"}}):null}function Xu({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:[Ku(i-n,o+t),Ku(i-n,o-n),Ku(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:[Ku(i-t,o-n),Ku(i+n,o-n),Ku(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:[Ku(i+n,o-t),Ku(i+n,o+n),Ku(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:[Ku(i+t,o+n),Ku(i-n,o+n),Ku(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 nm("g",{children:[tm("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?tm("polyline",{points:c.points,...l}):tm("line",{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,...l})]})}function Ku(e,t){return`${e},${t}`}function Vu(e){return Number.isFinite(e)?Number(e.toFixed(2)).toString():"0"}function qu(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 ju(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function Gu(e,t){e.setLaserTrail(t.sessionId,t.trail)}function Zu(){return"undefined"==typeof performance?Date.now():performance.now()}function Qu(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=JI/n,s=ih(o,t);if(s<r)return void(e.samples[e.samples.length-1]={...o,...t,time:i});const a=s*n/Math.max(rv,i-o.time);e.samples.push({...t,time:i,velocity:ch(o.velocity,a,.68)})}function Ju(e,t){e.samples=eh(e.samples,t)}function eh(e,t){const n=e[e.length-1];if(!n)return[];const i=t-uh(sv+n.velocity*av,sv,dv);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=uh((i-s.time)/(a.time-s.time),0,1),{...lh(d,l,c),time:ch(d.time,l.time,c),velocity:ch(d.velocity,l.velocity,c)}),...r]:r;var d,l,c}function th(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?ah(i,e[t]):ah(t===e.length-1?e[t]:i,n))}function nh(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 ih(e,t){return Math.sqrt(oh(e,t))}function oh(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function rh(e){return{x:-e.y,y:e.x}}function sh(e,t){return{x:e.x+t.x,y:e.y+t.y}}function ah(e,t){return{x:e.x-t.x,y:e.y-t.y}}function dh(e,t){return{x:e.x*t,y:e.y*t}}function lh(e,t,n){return{x:ch(e.x,t.x,n),y:ch(e.y,t.y,n)}}function ch(e,t,n){return e+(t-e)*n}function uh(e,t,n){return Math.max(t,Math.min(n,e))}function hh(e,t){const n=e[e.length-1];!n||oh(n,t)>.04?e.push(t):e[e.length-1]=t}function ph(e){if(e.length<2)return null;if(2===e.length)return`M ${fh(e[0])} L ${fh(e[1])} Z`;const t=[`M ${fh(gh(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 ${fh(i)} ${fh(gh(i,o))}`)}return t.push("Z"),t.join(" ")}function gh(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function fh(e){return`${mh(e.x)},${mh(e.y)}`}function mh(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function Sh(e,t,n){return["control",n,e,t].map(encodeURIComponent).join("|")}function yh(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:uv,subpathId:n[1],nodeId:n[2]}:"path.control"!==e||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:hv,handle:n[1],subpathId:n[2],nodeId:n[3]}}function bh(e,t){t?pv.set(e,xh(t)):pv.delete(e)}function xh(e){return{...e,pagePoint:e.pagePoint.clone()}}function Ih(e){return p(e)&&"path"===e.type}function vh(e){return"string"==typeof e&&gv.includes(e)}function wh(){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(!Ih(r)||r.id!==n.shapeId)return null;const s=(e=>{const t=pv.get(e);return t?xh(t):null})(e);if(!s||s.shapeId!==r.id)return null;const a=8/o.z,d=a/2;
58
- return tm("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:tm("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 Ph(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function kh(e){return new vm(e.x,e.y)}function Ch(e,t){const n=kh(t);if(!((e,t)=>!!e.out||!!t.in)(e,t))return`L ${Ph(n.x)} ${Ph(n.y)}`;const i=(e=>{const t=kh(e);return e.out?t.add(new vm(e.out.dx,e.out.dy)):t})(e),o=(e=>{const t=kh(e);return e.in?t.add(new vm(e.in.dx,e.in.dy)):t})(t);return["C",Ph(i.x),Ph(i.y),Ph(o.x),Ph(o.y),Ph(n.x),Ph(n.y)].join(" ")}function Th(e){const t=e.nodes[0];if(!t)return null;const n=[`M ${Ph(t.x)} ${Ph(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(Ch(t,o))}if(e.closed&&e.nodes.length>1){const i=e.nodes[e.nodes.length-1];i&&n.push(Ch(i,t)),n.push("Z")}return n.join(" ")}function Eh(e){const t=e.map(Th).filter(e=>null!==e);return t.length>0?t.join(" "):null}function Mh(e){return Number.isFinite(e)}function Bh(e){return{dx:e.dx,dy:e.dy}}function Rh(e){return{id:e.id,x:e.x,y:e.y,kind:e.kind,...e.in?{in:Bh(e.in)}:null,...e.out?{out:Bh(e.out)}:null}}function Ah(e){return{id:e.id,closed:e.closed,nodes:e.nodes.map(Rh)}}function Lh(e){return e.map(Ah)}function Fh(e){return new vm(e.x,e.y)}function $h(e){const t=Fh(e);return e.in?t.add(new vm(e.in.dx,e.in.dy)):t}function Uh(e){const t=Fh(e);return e.out?t.add(new vm(e.out.dx,e.out.dy)):t}function Dh(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 vm(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 zh(e,t,n){return new vm(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n)}function _h(e,t){return[Fh(e),Uh(e),$h(t),Fh(t)]}function Hh(e,t){return!!e.out||!!t.in}function Nh(e,t,n){return Hh(e,t)?Dh(..._h(e,t),n):zh(Fh(e),Fh(t),n)}function Oh(e,t,n){const i=Fh(t),o=Uh(t),r=$h(n),s=Fh(n);if(t.out||n.in)for(let a=1;a<=18;a+=1)e.push(Dh(i,o,r,s,a/18));else e.push(s)}function Wh(e){const t=e.nodes[0];if(!t)return{id:e.id,closed:e.closed,points:[]};const n=[Fh(t)];for(let i=1;i<e.nodes.length;i+=1){const t=e.nodes[i-1],o=e.nodes[i];t&&o&&Oh(n,t,o)}if(e.closed&&e.nodes.length>1){const i=e.nodes[e.nodes.length-1];i&&Oh(n,i,t)}return{id:e.id,closed:e.closed,points:n}}function Yh(e){const t=e.props,n=bv.get(t);if(n)return n;const i=Xh(e.props);return bv.set(t,i),i}function Xh(e){const t=e.subpaths.map(Wh),n=t.flatMap(e=>e.points),i=e.subpaths.flatMap(e=>e.nodes.flatMap(e=>[Fh(e),...e.in?[$h(e)]:[],...e.out?[Uh(e)]:[]])),o=i.length>0?wm.FromPoints(i):new wm(0,0,1,1),r=Math.max(e.strokeWidth/2,1),s=n.length>0?wm.FromPoints(n).expand(r):o.expand(r),a=new wm(s.x,s.y,Math.max(s.w,1),Math.max(s.h,1));return{path:Eh(e.subpaths),pointBounds:o,localBounds:s,renderBounds:a,outlineVertices:n.map(e=>e.clone()),flattenedSubpaths:t}}function Kh(e,t){return e.map(e=>({...e,nodes:e.nodes.map(e=>((e,t)=>{const n=t(Fh(e)),i=e.in?t($h(e)):null,o=e.out?t(Uh(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 Vh(e,t){const n=Xh({...t,subpaths:Lh(e)}).pointBounds,i=Number.isFinite(n.x)?n.x:0,o=Number.isFinite(n.y)?n.y:0,r=((e,t,n)=>Kh(e,e=>new vm(e.x+t,e.y+n)))(e,-i,-o);return{x:i,y:o,subpaths:r,geometry:Xh({...t,subpaths:r})}}function qh(e,t){return Kh(e.props.subpaths,e=>t.applyToPoint(e))}function jh(e,t){return Eh(qh(e,t))}function Gh(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 Zh(e,t,n){return Gh(e,t,n).distanceSquared}function Qh(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=Hh(e,s)?32:1;let d=Fh(e);for(let n=1;n<=a;n+=1){const l=Nh(e,s,n/a),c=Gh(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:Nh(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 Jh(e,t){return e.find(e=>e.id===t)??null}function ep(e,t,n){return Jh(e,t)?.nodes.find(e=>e.id===n)??null}function tp(e,t,n,i){return e.map(e=>e.id!==t?Ah(e):{...e,nodes:e.nodes.map(e=>e.id===n?i(Rh(e)):Rh(e))})}function np(e,t,n){return e.map(e=>{if(e.id!==t)return Ah(e);const i=e.nodes.findIndex(e=>e.id===n),o=e.nodes[i];if(!o)return Ah(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=Fh(o),d=((e,t,n)=>{const i=t?Fh(t):null,o=n?Fh(n):null;if(i&&o){const t=o.sub(i);if(t.len()<=mv)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<=mv||n/i<=.001})(i.sub(e),o.sub(e))?n.rot(yv):n}const r=o?o.sub(e):i?e.sub(i):null;return!r||r.len()<=mv?null:r.normalize().rot(yv)})(a,r,s),l=e.nodes.map(Rh);return l[i]={...Rh(o),kind:"smooth",in:r&&d?op(d.mul(-a.dist(Fh(r))*Sv)):null,out:s&&d?op(d.mul(a.dist(Fh(s))*Sv)):null},{...e,nodes:l}})}function ip(e,t,n){return tp(e,t,n,e=>({...e,kind:"corner",in:null,out:null}))}function op(e){return e.len2()<=1e-12?null:{dx:e.x,dy:e.y}}function rp(e,t,n){return e.map(e=>e.id!==t?Ah(e):{...e,closed:!(e.nodes.length<=3)&&e.closed,nodes:e.nodes.filter(e=>e.id!==n).map(Rh)}).filter(e=>e.nodes.length>0)}function sp(e){const t=xv.get(e);if(!t)return null;if(e.getShapeEditingSession()?.shapeId!==t.shapeId)return null;const n=e.getShape(t.shapeId);if(!Ih(n))return null;const i=ep(n.props.subpaths,t.subpathId,t.nodeId);return i?{selection:cp(t),shape:n,node:i}:null}function ap(e,t){if(!t)return xv.delete(e),void lp(e,null);xv.set(e,cp(t)),lp(e,t.pagePoint)}function dp(e,t,n,i){const o=Jh(t.props.subpaths,n)?.nodes.find(e=>e.id===i);if(!o)return void ap(e,null);const r=e.computeShapeLocalToPageTransform(t);ap(e,{shapeId:t.id,subpathId:n,nodeId:i,pagePoint:r.applyToPoint(Fh(o))})}function lp(e,t){const n=e.getShapeEditingSession();n&&e.updateSession({shapeEditingSession:{...n,caretPagePoint:t?{x:t.x,y:t.y}:void 0}},"system")}function cp(e){return{...e,pagePoint:e.pagePoint.clone()}}function up(e){const t=e.meta[Iv],n=e.meta[vv];return{subpathId:"string"==typeof t?t:null,previewNodeId:"string"==typeof n?n:null}}function hp(e,t){const n=pp(e);return t.subpathId&&(n[Iv]=t.subpathId),t.previewNodeId&&(n[vv]=t.previewNodeId),n}function pp(e){const t={...e};return delete t[Iv],delete t[vv],t}function gp(){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=Ih(r)?r:null,a=8/o.z,d=1.5/o.z,l=n.currentPagePoint;if(!s)return l?tm(mp,{point:l,size:a,strokeWidth:d,variant:"candidate"}):null;const c=((e,t)=>{const n=up(t);if(!n.subpathId)return null;const i=Jh(qh(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?Th({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?tm(mp,{point:l,size:a,strokeWidth:d,variant:"candidate"}):null;const u=c.previewNode?fp(c.previewNode):l,h=u&&!c.committedNodes.some(e=>fp(e).dist2(u)<=.25/(o.z*o.z));
59
- return nm("g",{"data-ui":"path-draft-overlay",pointerEvents:"none",children:[c.previewPath?tm("path",{"data-ui":"path-draft-preview-segment",d:c.previewPath,fill:"none",stroke:wv,strokeWidth:Math.max(d,1/o.z),strokeDasharray:`${6/o.z} ${4/o.z}`,strokeLinecap:"round",strokeLinejoin:"round"}):null,c.committedNodes.map(e=>tm(mp,{point:fp(e),size:a,strokeWidth:d,variant:"committed"},e.id)),h?tm(mp,{point:u,size:a,strokeWidth:d,variant:"candidate"}):null]})}function fp(e){return new vm(e.x,e.y)}function mp({point:e,size:t,strokeWidth:n,variant:i}){const o=t/2;
60
- return tm("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:wv,strokeWidth:n})}function Sp({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}=Yh({props:{...e.props,strokeWidth:r}}),a=(e=>up(e).previewNodeId)(e),d=Eh(((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 nm("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:tm("path",{d:d,fill:k(i),fillRule:e.props.fillRule,clipRule:e.props.fillRule,stroke:"none"}),
62
- tm("path",{d:d,fill:"none",stroke:yo(o,t),strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round"}),l?tm(yp,{shape:e}):null]})}function yp({shape:e}){
63
- return tm(em,{children:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=Fh(t),i=[];if(t.in){const o=$h(t);i.push(tm("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=Uh(t);i.push(tm("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 bp({shape:e,isHovered:t,shapeEditingSession:n}){
64
- return tm(Sp,{shape:e,isHovered:t,shapeEditingSession:n})}function xp({handle:e,strokeWidth:t}){const n=vp(e.type,e.id);
65
- return tm("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 Ip({handle:e,strokeWidth:t}){const n=vp(e.type,e.id);
66
- return tm("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 vp(e,t){const n=nr();ir(n.shapeEditingSessionSignal);const i=(e=>{const t=xv.get(e);return t?cp(t):null})(n),o=yh(e,t);return!!i&&!!o&&i.subpathId===o.subpathId&&i.nodeId===o.nodeId}function wp(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6}function Pp(e){return qh(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&&wp(i,e)||t.push(e)}return t.length>1&&wp(t[0],t[t.length-1])&&t.pop(),t.length>=3?t:null})(Wh(e).points)).filter(e=>null!==e).map(e=>[e])}function kp(e){const t=e.length>1&&wp(e[0],e[e.length-1])?e.slice(0,-1):e;return t.length<3?null:{id:`boolean-subpath:${kv+=1}`,closed:!0,nodes:t.map(([e,t])=>({id:`boolean-node:${Cv+=1}`,x:e,y:t,kind:"corner"}))}}function Cp(e){const t=e.getShapeEditingSession();if(!t)return null;const n=e.getShape(t.shapeId);return Ih(n)?n:null}function Tp(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function Ep(e){bh(e,null)}function Mp(e){Ep(e),ap(e,null)}function Bp(e,t,n,i){const o=rp(t.props.subpaths,n,i);e.commands.updateShapes([{id:t.id,props:{subpaths:o}}],{source:"user"}),ap(e,null)}function Rp(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 Ap(){return{id:"land.path.interactions",editorEvent:{handleEvent(e,t){if("pointer"===t.type&&"pointer_up"===t.name&&Ep(e),"pointer"===t.type&&"pointer_cancel"===t.name&&Ep(e),"click"===t.type&&"double_click"===t.name&&"up"===t.phase){Mp(e);const n=e.hitTestShape(t.pagePoint);if(Ih(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=sp(e);if(!n||n.shape.isLocked)return!1;const i=t.key.toLowerCase();return"backspace"===i||"delete"===i?(Bp(e,n.shape,n.selection.subpathId,n.selection.nodeId),!0):"c"===i?(((e,t,n,i)=>{const o=ep(t.props.subpaths,n,i);if(!o||o.in||o.out)return;const r=np(t.props.subpaths,n,i);e.commands.updateShapes([{id:t.id,props:{subpaths:r}}],{source:"user"});const s=e.getShape(t.id);Ih(s)&&dp(e,s,n,i)})(e,n.shape,n.selection.subpathId,n.selection.nodeId),!0):"x"===i&&(((e,t,n,i)=>{const o=ep(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);Ih(s)&&dp(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?Ep(e):((e,t)=>{const n=Cp(e);if(!n||"select"!==e.getActiveToolId()||!e.isActiveToolInInitialState())return void Ep(e);if("custom"===e.hitTestSelectionHandle(t.pagePoint)?.kind)return void Ep(e);const i=Tp(e,n,t.pagePoint),o=Qh(n.props.subpaths,i,7/e.getCurrentCamera().z);if(!o)return void Ep(e);const r=e.computeShapeLocalToPageTransform(n);bh(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=Cp(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind&&"path.node"===i.type){const t=yh(i.type,i.id);if("path.node"===t?.type)return Bp(e,n,t.subpathId,t.nodeId),"handled"}}if("pointer"===t.type&&"pointer_down"===t.name&&0===t.button&&!t.altKey){Ep(e);const n=Cp(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind){const t=yh(i.type,i.id);return t?dp(e,n,t.subpathId,t.nodeId):ap(e,null),"continue"}const o=Tp(e,n,t.pagePoint),r=Qh(n.props.subpaths,o,7/e.getCurrentCamera().z);if(!r)return ap(e,null),"continue";e.history.mark(Tv);const s=`insert-node:${Ev+=1}`,a=function(e,t,n){return e.map(e=>{if(e.id!==t.subpathId)return Ah(e);const i=e.nodes.findIndex(e=>e.id===t.startNodeId);if(i<0)return Ah(e);const o=(i+1)%e.nodes.length,r=e.nodes[i],s=e.nodes[o];if(!r||!s||s.id!==t.endNodeId)return Ah(e);const a=((e,t,n,i)=>{if(!Hh(e,t)){const o=zh(Fh(e),Fh(t),n);return{start:Rh(e),node:{id:i,x:o.x,y:o.y,kind:"corner"},end:Rh(t)}}const[o,r,s,a]=_h(e,t),d=zh(o,r,n),l=zh(r,s,n),c=zh(s,a,n),u=zh(d,l,n),h=zh(l,c,n),p=zh(u,h,n);return{start:{...Rh(e),out:op(d.sub(o))},node:{id:i,x:p.x,y:p.y,kind:"smooth",in:op(u.sub(p)),out:op(h.sub(p))},end:{...Rh(t),in:op(c.sub(a))}}})(r,s,t.t,n),d=e.nodes.map(Rh);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 Ih(d)&&dp(e,d,r.subpathId,s),e.history.squashToMark(Tv,"shape.edit"),"continue"}return"continue"}},selectionHandle:{createSession(e,{handle:t,shape:n,originPagePoint:i}){if(!Ih(n)||"custom"!==t.kind)return null;const o=yh(t.type,t.id);if(!o)return null;if(e.getShapeEditingSession()?.shapeId!==n.id)return null;const r=n,s="path.node"===o.type?ep(r.props.subpaths,o.subpathId,o.nodeId):null,a=Tp(e,r,i);return{shapeId:n.id,historyMark:"path.handle",handleSnapMode:"point",allowSelfSnap:!0,update({editor:e,pagePoint:t,source:i}){if(!Ih(e.getShape(n.id)))return"stop";const d=Tp(e,r,t),l="path.node"===o.type?s?tp(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))):Lh(r.props.subpaths):tp(r.props.subpaths,o.subpathId,o.nodeId,e=>((e,t,n)=>{const i=Fh(e),o={...e},r=n.sub(i);return"in"===t?(o.in={dx:r.x,dy:r.y},"corner"!==e.kind&&(o.out=Rp(r,e.out?Uh(e).sub(i):null,"symmetric"===e.kind))):(o.out={dx:r.x,dy:r.y},"corner"!==e.kind&&(o.in=Rp(r,e.in?$h(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);Ih(t)&&dp(e,t,o.subpathId,o.nodeId)}return"continue"}}}}}}function Lp(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Fp(e){if(!e||"object"!=typeof e)return null;const t=e,n=Lp(t.dx,NaN),i=Lp(t.dy,NaN);return Number.isFinite(n)&&Number.isFinite(i)?t.dx===n&&t.dy===i?e:{dx:n,dy:i}:null}function $p(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=Lp(n.x,NaN),o=Lp(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&&fv.includes(r)?n.kind:"corner"),in:Fp(n.in),out:Fp(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 Up(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 Dp(e,t){const n=t(Fh(e)),i=e.in?t($h(e)):null,o=e.out?t(Uh(e)):null;return{...Rh(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 zp(){return`node:${Rv+=1}`}function _p(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function Hp(e,t){return t.previewNodeId?e.map(e=>e.id===t.subpathId?{...e,nodes:e.nodes.filter(e=>e.id!==t.previewNodeId)}:e):Lh(e)}function Np(e,t){return Jh(e.props.subpaths,t.subpathId)?.nodes.filter(e=>e.id!==t.previewNodeId).length??0}function Op({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:Yv.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:Xv.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:Kv.map(e=>({...e,dataUi:`${o}-stroke-width-${e.value}-button`}))}]},{id:`${o}.fill-rule`,items:[{kind:"segmented",id:`${o}.fill-rule`,actionId:i,options:Vv.map(e=>({...e,dataUi:`${o}-fill-rule-${e.value}-button`}))}]}]}function Wp(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(!Ih(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=Vp(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(Ih).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));o.length>0&&t.editor.commands.updateShapes(o,{source:"user"})}}}function Yp(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=Vp(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("path",{[e]:i})}}}function Xp(e){return{id:`path.boolean.${e}`,isVisible:e=>"path"===e.selection.commonShapeType,isEnabled:e=>Kp(e).length>=2,run({context:t}){const n=Kp(t),i=n[0];if(!i||n.length<2)return;const o=((e,t,n)=>{const i=function(e,t){const n=t.map(Pp).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,Pv.union)(n,...i);case"subtract":return(0,Pv.difference)(n,...i);case"intersect":return(0,Pv.intersection)(n,...i);case"xor":return(0,Pv.xor)(n,...i)}})(e,n).flatMap(e=>e).map(kp).filter(e=>null!==e)}(e,t);return 0===i.length?null:Vh(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 Kp(e){return e.selection.selectedShapes.filter(Ih).filter(e=>!e.isLocked).filter(e=>e.props.subpaths.some(e=>e.closed&&e.nodes.length>=3))}function Vp(e,t){return"strokeWidth"===e?"number"==typeof t&&Kv.some(e=>e.value===t)?t:void 0:v(t)?P(t,y("fill"===e?"fill-blue":"stroke-slate")):void 0}function qp({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 jp(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 Gp(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function Zp(e){const t=e.getDocumentMetadataRecord();return{id:t?.id??"document:main",meta:{...t?.meta??{}}}}function Qp(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 Jp(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 eg(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 tg(e,t){const n=e.getActiveToolId();t.assertToolId(n);const i=n;return{productId:t.productId,document:Zp(e),pageId:e.getCurrentPageId(),activeToolId:i,selectedShapeIds:[...e.getSelectedShapeIds()],shapeCount:e.getCurrentPageShapeIds().length,session:eg(e,t)}}function ng(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 ig(e){return{...e,meta:{...e.meta}}}function og(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 rg(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}function sg(e,t){e.includes(t)||e.push(t)}function ag(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 dg(e){const{apis:t,editor:n}=e;return{apis:t,snapshot:()=>tg(n,e),subscribe(t){let i=ng(tg(n,e));return n.listen(o=>{const r=ag(o.diff,"document"),s=ag(o.diff,"session");if(!r&&!s)return;const a=s?tg(n,e):((e,t,n,{hasDocumentMetadataChange:i})=>{return{productId:n.productId,document:i?Zp(e):ig(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"),og(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||!og(i.selectedShapeIds,o.selectedShapeIds)||!rg(i.camera,o.camera))return!1}return!0})(e.session,t.session)||n.push("session"),n}(i,a);if(r&&sg(l,"document"),s&&sg(l,"session"),0===l.length)return void(i=ng(a));const c=i;i=ng(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:()=>Zp(n),updateDocumentMeta:e=>(n.updateDocumentMeta(e,"user"),Zp(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?Qp(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=>Qp(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(Jp);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(qp({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 qp({childIds:e.getChildShapeIds(n.id),depth:jp(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(Gp),createPage:e=>Gp(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 lg(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 cg(e){return{create(t){const n=e.getDefaultShapeProps("arrow"),i=ja(e,{startPagePoint:new vm(t.start.x,t.start.y),endPagePoint:new vm(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 ug(e){return{createRectangle:t=>lg(e,"rectangle",t),createEllipse:t=>lg(e,"ellipse",t),createDiamond:t=>lg(e,"diamond",t),createTriangle:t=>lg(e,"triangle",t),createHexagon:t=>lg(e,"hexagon",t),createStar:t=>lg(e,"star",t)}}function hg(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:Bo(t.text)}}],{source:"user"});return i&&"text"===i.type?{id:i.id,type:i.type}:null}}}function pg(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 gg(e,t){const n=e.getShape(t.id);if("geo"===t.type){const e=(n?.props)?.geo;return{...t,displayName:fg(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 fg(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 mg(e){const t=dg(e),n={arrow:cg(i=e.editor),geo:ug(i),text:hg(i),frame:pg(i)};var i;return{...t,...n,getLayerTree:n=>t.getLayerTree(n).map(t=>gg(e.editor,t)),getLayerNode(n){const i=t.getLayerNode(n);return i?gg(e.editor,i):null}}}function Sg(e){if(!(e=>Zv.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: ${Qv}.`);throw new Error(`Unknown canvas kit tool "${e}". Available tool ids: ${Qv}.`)}}function yg(e){return bg({...e,assertToolId:e.assertToolId??Sg})}function bg(e){const t={...mg(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 xg({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 Ig(e,t){const n=Xf(n=>t?oo("useOptionalValue",e,n,{fireImmediately:!1}):()=>{},[t,e]),i=Xf(()=>t?e.get():null,[t,e]);return Jf(n,i,i)}function vg({assetInliners:e=[],editor:t,themeRootRef:n}){const[i,o]=Qf(null);return{status:i,exportSvg:Xf(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 wg({editor:e,hostFeatures:t,services:n}){return t.flatMap(t=>t.svgAssetInliners?.({editor:e,services:n})??[])}function Pg(e,t){for(const n of e)n.onBeforeCommand?.(t)}function kg(e,t){for(const n of e)n.onAfterCommand?.(t)}function Cg({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(){Pg(t,{commandId:"history.undo",editor:e}),e.undo()},redo(){Pg(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(){Pg(t,{commandId:"page.create",editor:e}),e.createPageAndSelect(void 0,"user")},deleteCurrentPage(){n.currentPage&&(Pg(t,{commandId:"page.delete-current",editor:e}),e.deletePage(n.currentPage.id,"user"))},renameCurrentPage(i){n.currentPage&&(Pg(t,{commandId:"page.rename-current",editor:e}),e.renamePage(n.currentPage.id,i,"user"))},selectPage(n){Pg(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=Ig(e.selectionStateSignal,i),r=Ig(e.toolStateSignal,i);return Gf(()=>{if(!t||!o||!r)return{context:null,activeContextMenu:null,sections:[]};const i=(({editor:e,menu:t})=>{const n=e.toolStateSignal.get();return{...xg({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=xg({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"}):Jv,g=h?n.toolbarRegistry.getGroups("selection",c,{placement:"floating"}):Jv,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=vg({assetInliners:wg({editor:o,hostFeatures:s,services:c}),editor:o,themeRootRef:u}),v=Gf(()=>{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=Gf(()=>({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)&&(Pg(s,{commandId:e,context:t,editor:t.editor}),i.run({context:t,value:void 0!==n?n:i.getValue?.(t)??null}),kg(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}){Pg(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}),kg(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 Tg({apis:e,config:t,controllerSlots:n,editor:i,pluginHostRuntime:o,productId:r,services:s}){const a=Gf(()=>({apis:e,controllerSlots:n,editor:i,pluginHostRuntime:o,productId:r,services:s}),[e,n,i,o,r,s]),d=Gf(()=>yg(a),[a]);return(({controller:e,exposeOnWindow:t=!1,windowKey:n,onDispose:i,onReady:o})=>{const r=qf(e=>{o?.(e)}),s=qf(()=>{i?.()});Vf(()=>{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 Eg({assetResolverTokens:e,services:t}){return e.map(e=>t.get(e)).filter(e=>!!e)}function Mg(e){return{id:e}}function Bg(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}async function Rg(e,t){for(const n of e)await n(t)}function Ag(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 Lg(e){return[...e].sort((e,t)=>(e.order??0)-(t.order??0))}function Fg(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 Ag(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 Ag(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}),Ag(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=Lg(i.flatMap(e=>e.providers??[])),f=Lg(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 Ag(o.map(e=>e.token.id),"product service token"),Ag(u.map(e=>e.token.id),"product API token"),Ag(u.map(e=>e.id),"product API contribution id"),Ag(h.map(e=>e.key),"controller slot key"),Ag(p.map(e=>e.key),"chrome slot key"),Ag(l.map(e=>e.id),"host toolbar contribution id"),Ag(c.map(e=>e.id),"host context-menu contribution id"),Ag(f.map(e=>e.id),"host component id"),Ag(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){Bg(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];Ag(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 fS({...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 OS(e),{shortcut:"v"}),t.tools.register("hand",e=>new bS(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 Eg({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})=>{$g({ids:t,kind:"canvas-action",message:`[land] Duplicate canvas action ids for product ${i}. The later registrations were ignored.`,productId:i}),$g({ids:n,kind:"toolbar-contribution",message:`[land] Duplicate toolbar contribution ids for product ${i}. The later registrations were ignored.`,productId:i}),$g({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?.(yg({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 $g({ids:e,kind:t,message:n,productId:i}){if(0===e.length)return;const o=`${i}:${t}:${e.join(",")}`;tw.has(o)||(tw.add(o),console.warn(n,e))}function Ug({product:e}){const t=(e=>{const t=e,[n,i]=Qf(null),o=n?.product===t?n.runtime:null;return Vf(()=>{const e=Fg(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]=Qf(null),[o,r]=Qf(!1),{isReady:s,persistence:a}=function(e){const[{readyRuntime:t,status:n},i]=Qf(ew),[o,r]=Qf(!1),s=!!e?.persistence?.restore&&!e.shouldSkipStoredSnapshots?.();Vf(()=>{if(!e)return void i(ew);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(ew),(async()=>{let e=null,i=!0;try{await Rg(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(Eg({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(Eg({assetResolverTokens:e,services:n}).map(e=>e.cleanupAfterRestore?.(t)))})({assetResolverTokens:t,editor:n,services:d}),await Rg(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 Rg(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 Rg(r.beforeStartupHooks,{editor:n,persistence:o,productId:a,services:d}),await Rg(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=Xf(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=Gf(()=>({isVisible:o,setIsVisible:r}),[o]);if(Vf(()=>{i(null)},[e]),!t)return null;const{editor:l,pluginHostRuntime:c}=t;
67
- return tm(xy.Provider,{value:l,children:tm(Dg,{runtime:t,canvas:s?tm(Br,{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 Dg({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=Zf(null),m=Cg({apis:a,controller:Tg({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=tm("div",{ref:f,"data-ui":"app-shell","data-canvas-kit":h,className:"land-canvas-kit__shell",children:tm("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:i?nm(em,{children:[e,zg(c.componentsBySlot.controller,S),g?.(m),zg(c.componentsBySlot.chrome,b),zg(c.componentsBySlot.workspace,y)]}):null})});return c.providers.reduceRight((e,t)=>tm(t.component,{children:e},t.id),x)}function zg(e,t){return e.map(e=>tm(e.component,{...t},e.id))}function _g(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(Hg).filter(e=>!i.has(e.id));return{...n,records:[...n.records,...o]}}function Hg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&"string"==typeof e.id}function Ng(){return"undefined"==typeof indexedDB?Promise.resolve(null):(ow||(ow=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(nw),e.objectStoreNames.contains("imageBlobs")||e.createObjectStore(iw)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),ow=null}),e(t)}),n.addEventListener("error",()=>{ow=null,t(n.error)})})),ow)}async function Og(e,t){if(0===t.length)return[];const n=await Ng();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 Wg(e,t){if(0===t.length)return;const n=await Ng();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 Yg(e={}){let t=[];return{async restore(n){const{documentSnapshot:i,sessionSnapshot:o}=await(async(e={})=>{const[t,n]=await(async e=>(await Og("snapshots",e)??e.map(()=>null)).map(qg))([Kg(e),Vg(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:Bi(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 rw(n,{getDocumentSnapshot:()=>_g(n,t),options:e});return i.start(),()=>i.stop()},flushSnapshot:n=>Xg(n,e,{documentSnapshot:_g(n,t)}),discardUnsupportedRecords:async n=>(await Xg(n,e),t=[],{autoPersistence:"enabled",status:null})}}async function Xg(e,t={},{documentSnapshot:n=e.getDocumentSnapshot()}={}){const i=JSON.stringify(n),o=JSON.stringify(e.getSessionSnapshot());await Wg(nw,[[Kg(t),i],[Vg(t),o]])}function Kg(e){return e.storageNamespace?`${e.storageNamespace}.document`:"land.canvas.document"}function Vg(e){return e.storageNamespace?`${e.storageNamespace}.session`:"land.canvas.session"}function qg(e){if("string"!=typeof e)return null;try{return JSON.parse(e)}catch{return null}}function jg(e){return e.get(sw)}async function Gg({context:e,services:t}){const n=jg(t);if(!n)return null;const i=e.editor.createClipboardPayloadFromSelection();return i?(await n.write(i),i):null}async function Zg({atMenuPoint:e=!1,context:t,services:n}){const i=jg(n);if(!i)return;const o=await i.read();o&&t.editor.pasteClipboardPayload({payload:o,pagePoint:Qg({atMenuPoint:e,context:t}),source:"user"})}function Qg({atMenuPoint:e,context:t}){return e&&Jg(t)?t.menu.anchor.pagePoint:t.editor.inputs.state.get().currentPagePoint??t.editor.viewportPageBoundsSignal.get()?.center??void 0}function Jg(e){return"menu"in e}async function ef(e){const t=await(async(e,t)=>(await Og(e,[t]))?.[0]??null)(iw,e);return t instanceof Blob?t:null}async function tf(e){const t=await ef(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 nf(e){await(async(e,t)=>{const n=await Ng();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)})})(iw,e)}function of(e,t){const n=e.getAsset(t);if(!xu(n)||"local"!==n.props.source.kind)return null;const{storageKey:i}=n.props.source;return i.length>0?i:null}function rf(e){const t=new Set;for(const n of e.getAssets())xu(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&t.add(n.props.source.storageKey);return t}function sf(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 af(e){const t=lf(e)?e:e.blob,n=(lf(e),e.name),i=lf(e)?e.type:e.mimeType||e.blob.type,o=URL.createObjectURL(t),r=await sf(o).finally(()=>{URL.revokeObjectURL(o)}),{storageKey:s}=await async function(e){const t="undefined"!=typeof crypto&&"randomUUID"in crypto?`${pw}${crypto.randomUUID()}`:`${pw}${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 Wg(iw,[[t,e]]),{storageKey:t}}(t);return{name:n||"Image",source:{kind:"local",storageKey:s,...!lf(e)&&e.originalUrl?{originalUrl:e.originalUrl}:{}},mimeType:i||"image/png",fileSize:t.size,width:r.width,height:r.height}}async function df({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 af({blob:i,name:e||cf(t)||"Image",mimeType:i.type||n.headers.get("content-type")||void 0,originalUrl:t})}function lf(e){return"undefined"!=typeof File&&e instanceof File}function cf(e){try{const t=new URL(e).pathname.split("/").filter(Boolean).at(-1);return t?decodeURIComponent(t):null}catch{return null}}function uf(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 hf(e,t){return function(e,t,n){return e.screenToPage(((e,t=Ir())=>{if(!t)return new vm(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new vm(e.clientX-n.left,e.clientY-n.top)})(t,n))}(e,t)}function pf({filename:e,url:t}){const n=document.createElement("a");n.href=t,n.download=e,n.click()}async function gf({blob:e,filename:t}){const n=URL.createObjectURL(e);try{pf({filename:t,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function ff(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 mf(e,t){return e.getDocumentSnapshot().records.some(e=>"shape"===e.typeName&&e.props.assetId===t)}async function Sf({editor:e,imageObjectUrls:t,pagePoint:n,size:i,flushSnapshot:o,source:r,strategy:s="auto"}){if("file"===r.type)return kf(r.file)?bf({editor:e,imageObjectUrls:t,input:await af(r.file),pagePoint:n,size:i,flushSnapshot:o}):null;if("blob"===r.type)return kf(r.blob)?bf({editor:e,imageObjectUrls:t,input:await af(r),pagePoint:n,size:i,flushSnapshot:o}):null;if("copy"===s)return bf({editor:e,imageObjectUrls:t,input:await df(r),pagePoint:n,size:i,flushSnapshot:o});if("link"===s)return yf({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:i,flushSnapshot:o,copyInBackground:!1});try{return await yf({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:i,flushSnapshot:o,copyInBackground:!0})}catch{return bf({editor:e,imageObjectUrls:t,input:await df(r),pagePoint:n,size:i,flushSnapshot:o})}}async function yf({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 sf(t);return{name:e||cf(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 bf({editor:t,imageObjectUrls:i,input:{...a,source:d},pagePoint:o,size:r,flushSnapshot:n,altText:s.altText}),c=l?t.getShape(l):null,u=Iu(c)?c.props.assetId:null;return e&&u&&xf({assetId:u,editor:t,flushSnapshot:n,imageObjectUrls:i,source:s}),l}async function bf({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=ff(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 vm(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 nf(a)),l}}async function xf({assetId:e,editor:t,flushSnapshot:n,imageObjectUrls:i,source:o}){try{const r=await df(o),s="local"===r.source.kind?r.source.storageKey:null;if(!s)return;await i.preload(s);const a=t.getAsset(e);if(!xu(a)||"remote"!==a.props.source.kind||a.props.source.url!==o.url||!mf(t,e))return i.release(s),void(await nf(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);xu(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:Cf(n)}}}},{source:"system"}),await(i?.(t)))})({assetId:e,editor:t,error:r,flushSnapshot:n,url:o.url})}}async function If({editor:e,file:t,imageObjectUrls:n,flushSnapshot:i}){if(!kf(t))return;const[o]=e.getSelectedShapes();if(!Iu(o)||o.isLocked)return;const r=await af(t);await wf({editor:e,flushSnapshot:i,imageObjectUrls:n,input:r,nextProps:{crop:null,altText:r.name},shape:o})}async function vf({editor:e,imageObjectUrls:t}){const[n]=e.getSelectedShapes();if(!Iu(n)||!n.props.assetId)return;const i=e.getAsset(n.props.assetId);if(!xu(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 gf({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 ef(r);if(s)return void(await gf({blob:s,filename:o}));const a=t.resolve(r);a&&pf({filename:o,url:a})}async function wf({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=ff(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);Iu(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 nf(a)),l}if(s&&!mf(e,s)){e.commands.deleteAsset(s,{source:"user"});try{await(t?.(e))}catch{}}}async function Pf(e){try{const t=await fetch(e);if(!t.ok)return null;const n=await t.blob();return kf(n)?n:null}catch{return null}}function kf(e){return!e.type||e.type.startsWith("image/")}function Cf(e){return e instanceof Error?e.message:String(e)}function Tf({flushSnapshot:e}={}){return{token:fw,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=ef(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(rf(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 xu(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=of(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);xu(r)&&"remote"===r.props.source.kind&&"pending-local-copy"===r.props.source.copyState?.status&&(n.add(o),xf({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=rf(e),i=await async function(){return(await(async e=>{const t=await Ng();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 nf(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())xu(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 Ef(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=Rf(h.brush.opacity),i=Math.max(1,h.brush.size*u);e.globalAlpha=n,e.strokeStyle=o?"#ffffff":h.brush.color??"#111827",e.fillStyle=o?"#ffffff":h.brush.color??"#111827",e.lineWidth=i;const r=Bf({cropPixelRect:d,point:t,scaleX:l,scaleY:c});if(1!==h.points.length){e.beginPath(),e.moveTo(r.x,r.y);for(const t of h.points.slice(1)){const n=Bf({cropPixelRect:d,point:t,scaleX:l,scaleY:c});e.lineTo(n.x,n.y)}e.stroke()}else e.beginPath(),e.arc(r.x,r.y,i/2,0,2*Math.PI),e.fill()}e.restore()}function Bf({cropPixelRect:e,point:t,scaleX:n,scaleY:i}){return{x:e.x+t.x*n,y:e.y+t.y*i}}function Rf(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):.45}function Af(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 Lf({editor:e,flushSnapshot:t,services:n}){const i=n.get(fw);if(!i)return null;const o={start(t){const n=t?.shapeId?e.getShape(t.shapeId):e.getSelectedShapes()[0];return!(!Iu(n)||n.isLocked||!n.props.assetId)&&pu({brush:t?.brush,editor:e,shape:n})},cancel(){gu(e)},confirm:n=>async function({editor:e,imageObjectUrls:t,flushSnapshot:n,replace:i=!0}){const o=fu(e);if(!o)return null;const r=e.getShape(o.shapeId);if(!Iu(r)||r.isLocked||!r.props.assetId)return null;const s=e.getAsset(r.props.assetId);if(!xu(s))return null;const a=r.props.assetId,d=await(async({asset:e,imageObjectUrls:t})=>{if("remote"===e.props.source.kind)return Pf(e.props.source.url);const n=e.props.source.storageKey,i=await ef(n);if(i)return i;const o=t.resolve(n);return o?Pf(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(bu)})))(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=Ef(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=Ef(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(!Iu(i)||i.isLocked||i.props.assetId!==a)return null;await(async({blob:e,editor:t,flushSnapshot:n,imageObjectUrls:i,name:o,shape:r})=>{await wf({editor:t,flushSnapshot:n,imageObjectUrls:i,input:await af({blob:e,name:o}),nextProps:{},shape:r})})({blob:c,editor:e,flushSnapshot:n,imageObjectUrls:t,name:Af(s.props.name),shape:i})}return(e=>{lu(e).complete()})(e),g}({editor:e,flushSnapshot:t,imageObjectUrls:i.objectUrls,replace:n?.replace??!0}),isActive:()=>!!fu(e)};return(e=>{lu(e).registerConfirmHandler(e=>o.confirm(e))})(e),{insertImage:({source:n,pagePoint:o,size:r,strategy:s})=>Sf({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!(!Iu(o)||o.isLocked||(await If({editor:e,file:n,imageObjectUrls:i.objectUrls,flushSnapshot:t}),0))},downloadSelectedImageOriginal:()=>vf({editor:e,imageObjectUrls:i.objectUrls}),smudge:o}}function Ff(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(!Iu(n)||!n.props.assetId)continue;const i=n.props.assetId;if(r.has(i))continue;r.add(i);const a=of(t,i);if(!a)continue;const d=e.objectUrls.resolve(a)??await e.objectUrls.preload(a);if(!d)continue;const l=await tf(a);l&&(o=o.split(d).join(l))}return o}}}function $f({editor:e,flushSnapshot:t,services:n}){const i=n.get(fw);return i?tm(gw,{editor:e,hostBridge:n.get(yw)??void 0,imageAssetService:i,flushSnapshot:t}):null}function Uf({persistence:e}){const{discardUnsupportedRecords:t,isDiscardingUnsupportedRecords:n,status:i}=e;if(!i)return null;const o=[...i.unsupportedShapeTypes,...i.unsupportedBindingTypes].join(", ");
68
- return nm("div",{role:"alert","data-ui":"canvas-kit-persistence-notice",className:"land-canvas-kit__persistence-notice",children:[nm("div",{className:"land-canvas-kit__persistence-notice-copy",children:[tm("strong",{children:"Unsupported records preserved"}),nm("span",{children:[i.preservedRecordCount," record",1===i.preservedRecordCount?"":"s"," will round-trip while saving. ",o?`Types: ${o}.`:""]})]}),tm("button",{type:"button",className:"land-canvas-kit__persistence-notice-action",disabled:!t||n,onClick:()=>{t?.()},children:n?"Saving":"Discard unsupported records"})]})}function Df({persistence:e}){
69
- return tm(Uf,{persistence:e})}function zf(e){const[t]=e.selection.selectedShapes;return!(1!==e.selection.count||!t?.parentId.startsWith("shape:"))&&"frame"===e.editor.getShape(t.parentId)?.type}function _f(e){return Math.min(1,Math.max(0,e))}function Hf(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:Yg({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?zb.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:bw}]})},{id:"canvas-kit.clipboard",createFeature:()=>({id:"canvas-kit.clipboard",services:[{token:sw,create(){let e=null;return{async write(t){e=t},read:async()=>e,getMemoryPayload:()=>e}}}],createActions:({services:e})=>function(e){return[{id:aw,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!jg(e),run({context:t}){Gg({context:t,services:e})}},{id:dw,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!jg(e),run({context:t}){(async({context:e,services:t})=>{await Gg({context:e,services:t})&&e.editor.deleteSelection("user")})({context:t,services:e})}},{id:lw,isVisible:()=>!!jg(e)?.getMemoryPayload(),isEnabled:()=>!!jg(e)?.getMemoryPayload(),run({context:t}){Zg({context:t,services:e})}},{id:cw,isVisible:t=>Jg(t)&&!!jg(e)?.getMemoryPayload(),isEnabled:t=>Jg(t)&&!!jg(e)?.getMemoryPayload(),run({context:t}){Jg(t)&&Zg({context:t,services:e,atMenuPoint:!0})}}]}(e),actionShortcuts:uw,contextMenuContributions:hw})},{id:"canvas-kit.tool",createFeature:()=>({id:"canvas-kit.tool",actions:Dw,toolbarContributions:_w,contextMenuContributions:zw})},{id:"canvas-kit.selection",createFeature:()=>({id:"canvas-kit.selection",actions:Fw,actionShortcuts:Lw,toolbarContributions:Uw,contextMenuContributions:$w})},{id:"canvas-kit.view",createFeature:()=>({id:"canvas-kit.view",actions:Ww,contextMenuContributions:Yw})},{id:"canvas-kit.persistence",createFeature:()=>({id:"canvas-kit.persistence",components:[{id:"canvas-kit.persistence-notice",slot:"workspace",order:1e3,component:Df}]})},{id:"canvas-kit.image",createFeature({canvasExtensionNames:e,persistence:t}){const n=[{key:"image",token:mw}];if(!e.has("image"))return{id:"canvas-kit.image",controllerSlots:n};const i=t?.flushSnapshot;return{id:"canvas-kit.image",requiresCanvasExtensions:["image"],services:[Tf({flushSnapshot:i}),{token:yw,create:()=>new Sw}],assetResolverTokens:[fw],createActions({services:e}){const t=e.get(fw),n=e.get(yw);return t&&n?(({hostBridge:e,imageObjectUrls:t})=>[{id:pI,run(){e.openInsertFilePicker()}},{id:uI,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return Iu(t)&&!t.isLocked},run(){e.openReplaceFilePicker()}},{id:hI,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;if(!Iu(t)||!t.props.assetId)return!1;const n=e.editor.getAsset(t.props.assetId);return!(!xu(n)||"remote"!==n.props.source.kind&&!of(e.editor,t.props.assetId))},run({context:e}){vf({editor:e.editor,imageObjectUrls:t})}}])({hostBridge:n,imageObjectUrls:t.objectUrls}):[]},apis:[{id:"canvas-kit.image",token:mw,create:({editor:e,services:t})=>Lf({editor:e,flushSnapshot:i,services:t})}],controllerSlots:n,canShowToolbarDuringEditing:e=>wu(e)||Pu(e),onBeforeCommand({commandId:e,context:t,editor:n}){var i;(!t||"image.smudge"!==(i=e)&&"image.smudge.cancel"!==i&&"image.smudge.confirm"!==i)&&(e=>{lu(e).cancelIfActive()})(t?.editor??n)},svgAssetInliners({services:e}){const t=e.get(fw);return t?[Ff(t)]:[]},components:[{id:"canvas-kit.image-import",slot:"controller",order:100,component:e=>tm($f,{...e,flushSnapshot:i})}]}}},...e.hostExtensions??[]];return{[Xw]: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 Nf,createElement as Of,forwardRef as Wf,memo as Yf,useCallback as Xf,useContext as Kf,useEffect as Vf,useEffectEvent as qf,useLayoutEffect as jf,useMemo as Gf,useRef as Zf,useState as Qf,useSyncExternalStore as Jf}from"react";import{Fragment as em,jsx as tm,jsxs as nm}from"react/jsx-runtime";import{createPortal as im}from"react-dom";import{EditorContent as om,useEditor as rm}from"@tiptap/react";import{mergeAttributes as sm}from"@tiptap/core";import{Bold as am}from"@tiptap/extension-bold";import{Italic as dm}from"@tiptap/extension-italic";import{Link as lm}from"@tiptap/extension-link";import{Strike as cm}from"@tiptap/extension-strike";import um from"@tiptap/starter-kit";import{BubbleMenu as hm}from"@tiptap/react/menus";var pm=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),gm=0,fm=null,mm=null,Sm=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)=>{fm&&!fm.initialAtomValues.has(e)&&fm.initialAtomValues.set(e,t)})(this,i),t(),this.lastChangedEpoch=e(),this.current=n,(e=>{fm||r([e])})(this),n)}update(e){return this.set(e(this.current))}},ym=Symbol("UNINITIALIZED"),bm=class{name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch;children=new Set;state=ym;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!==ym&&!this.haveParentsChanged())return this.lastCheckedEpoch=e(),this.state;let o,r;n(this.selfAsChild);try{o=this.derive(this.state===ym?ym: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!==ym&&(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}},xm=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}},Im=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}},vm=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)}},wm=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 vm(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)}},Pm=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 vm(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)}},km="document:main",Cm="page:default",Tm="session:main",Em={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}},Bm=["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"],Rm=Object.fromEntries(Bm.map(e=>[e,`--land-shape-${e}`])),Am={"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"},Lm={"#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"},Fm=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()}},$m=Symbol("editorStore"),Um=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})}},Dm=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()}},zm=class{editor;buffer=new Um;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)}},_m=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}},Hm=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]??Em}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 vm(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new vm(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)}},Nm=new vm(24,24),Om=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??Nm,source:t.source}):[]})(this.editor,e)}},Wm=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},Ym=[],Xm=[],Km=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===Tm),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]??Em;n[i]={x:Number.isFinite(t.x)?t.x:Em.x,y:Number.isFinite(t.y)?t.y:Em.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:Em.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 Wm))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 Wm))throw t;return{schemaVersion:1,records:[c()]}}}},Vm=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})}},qm=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)}},jm=.001,Gm=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),wm.FromPoints([new vm(i.minX,i.minY),new vm(i.maxX,i.minY),new vm(i.maxX,i.maxY),new vm(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 Pm(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)}},Zm=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}},Qm=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 wm(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)=>wm.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||!Bt(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=wm.FromPoints([new vm(o.minX,o.minY),new vm(o.maxX,o.maxY),new vm(r.minX,r.minY),new vm(r.maxX,r.maxY)]);n.push({shapeId:e,shapeBounds:o,queryBounds:s,pointHitTestBounds:r})}return new Zm(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.getCurrentPageId()){return this.getPageIndexSignal(e).get()}},Jm={corner:0,edge_midpoint:1,center:2,custom:3},eS=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],tS=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 vm(l.minX,l.minY),new vm(l.maxX,l.minY),new vm(l.maxX,l.maxY),new vm(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():Mn(e,s));if(0===a.length)continue;const d=wm.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:eS[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:Mn(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))})}},nS=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 tS(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 vm(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 vm(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 wm(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,vm.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,vm.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 vm(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}}},iS=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)}}},oS=class{editor;constructor(e){this.editor=e}align(e,t="user"){const n=this.getAlignableEntries();if(n.length<2)return!1;const i=wm.FromPoints(n.flatMap(e=>[new vm(e.bounds.minX,e.bounds.minY),new vm(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 vm(e.minX,e.minY),new vm(e.maxX,e.maxY))}if(0===t.length)return null;const n=wm.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}},rS=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})}},sS=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!==ym?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})}},aS=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})}},dS=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)=>wm.FromPoints(et(e,t)))(e,this.editor.getShapeUtil(e))}computeShapeExportPageBounds(e){return((e,t)=>{const n=Ve(e,t),i=Ge(e,t);return wm.FromPoints([new vm(n.minX,n.minY),new vm(n.maxX,n.minY),new vm(n.maxX,n.maxY),new vm(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?Mn(e,t):null}getSelectionPageOutlineVertices(){return this.editor.queries.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.editor.queries.getSelectionAnchorPagePoint()}},lS=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 vm(e.minX,e.minY),new vm(e.maxX,e.minY),new vm(e.maxX,e.maxY),new vm(e.minX,e.maxY)]),l=d.length>0?wm.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}},cS=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}},uS=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!==ym&&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!==ym&&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===ym?[]: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}},hS=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}},pS=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}},gS=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}},fS=class{store;[$m];inputs=new Vm;snapshots=new Km(this);clipboard=new Om(this);shortcuts=new cS;tools=new hS(this);camera=new Hm(this);selection=new rS(this);selectionLayout=new oS(this);editing=new aS(this);geometry=new dS(this);hierarchy=new lS(this);shapeUtils=new Mm;shapeSvgExporters=new Fm;bindingUtils=new Im;interactions=new pS;selectionHandleInteractions=new gS(this.interactions);queries;bindings;spatialIndex;snaps;renderWindow;selectionOverlay;transients=new qm(this);history;sideEffects=new iS;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(Tm).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()]??Em);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 Pm.Scale(e.z,e.z).compose(Pm.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 wm(n.x,n.y,e/n.z,t/n.z)});renderViewportPageBoundsSignal=a("editor.renderViewportPageBounds",e=>{const t=this.viewportPageBoundsSignal.get();return t?e!==ym&&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 Dm(this.snapshots.buildInitialRecords(e.documentSnapshot??null,e.sessionSnapshot??null,e.documentMeta??{}));var n;((e,t)=>{e[$m]=t})(this,t),this.store=t,this.snapshots.ensureSessionIntegrity(),this.queries=new Gm(this),this.bindings=new _m(this),this.spatialIndex=new Qm(this,this.queries),this.snaps=new nS(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 sS(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 uS(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 zm(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(km);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=wm.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:wm.FromPoints(e.map(e=>Mn(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=M(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 wm(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=B(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]??{...Em}},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]??{...Em},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)}},mS=class{getLocalBounds(e){const t=this.getBounds(e);return new wm(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=Bn(_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():vm.RotWith(e,t.selectionRotationCenter,-t.selectionRotation),i=Fn({axis:t.axis,bounds:t.selectionBounds,point:n});return 0===t.selectionRotation?i:vm.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:vm.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 vm(t.minX,t.minY),new vm(t.maxX,t.minY),new vm(t.maxX,t.maxY),new vm(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 Pm.Translate(e.x+t.x,e.y+t.y).compose(Pm.Rotate(e.rotation)).compose(Pm.Scale(e.scaleX,e.scaleY)).compose(Pm.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 vm(o.x*e.scaleX,o.y*e.scaleY).rot(e.rotation))})(e,i,n):t.rawPagePoint}},SS=class{},yS=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)}},bS=class extends yS{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new xS(e,this)),this.addChild(new IS(e,this))}},xS=class extends yS{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",{originScreenPoint:e.screenPoint.clone(),originCamera:this.editor.getCurrentCamera()})}},IS=class extends yS{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}},vS=Math.PI/180*15,wS=Math.PI/2,PS=Math.PI/180*5,kS="select.translate",CS="select.resize",TS="select.rotate",ES=class extends yS{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},MS=class extends ES{onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&this.onDragThresholdExceeded(e)}},BS=class extends ES{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))}},RS=class extends ES{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 wm(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")}},AS=class extends BS{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(fm)return void e();const t={initialAtomValues:new Map};fm=t;try{e(),r(t.initialAtomValues.keys())}catch(n){for(const[e,i]of t.initialAtomValues)e.__unsafe__setWithoutNotify(i);throw n}finally{fm=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")}},LS=class extends yS{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)})}},FS=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")}},$S=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:Mn(e[0],o),endLocalPagePoint:Mn(e[1],o)}):r.push({shape:a,localBounds:wm.FromPoints(n(a).map(e=>Mn(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 vm(e.minX,e.minY),new vm(e.maxX,e.minY),new vm(e.maxX,e.maxY),new vm(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")}},US=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:vm.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")}},DS=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")}},zS=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()??vm.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")}},_S=class extends BS{tickMode="apply_after_scroll_or_without_screen_point";constructor(e,t){super(e,"resizing",t)}getHistoryMark(){return CS}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=Mn(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 wm(e.minX,i.y-a,e.w,2*a),scaleX:d,scaleY:l};case"left":case"right":return{bounds:new wm(i.x-s,e.minY,2*s,e.h),scaleX:d,scaleY:l};default:return{bounds:new wm(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 wm(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(CS),this.transition("idle")}cancel(){this.editor.setSnapIndicators(null),this.editor.history.bailToMark(CS),this.transition("idle")}},HS=class extends BS{tickMode="apply_after_scroll";constructor(e,t){super(e,"rotating",t)}getHistoryMark(){return TS}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(vm.Angle(this.info.center,e)-this.info.startAngle);if(t)i=Vi(i,vS);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=Vi(e,wS),n=Ki(t-e);Math.abs(n)<=PS&&(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(TS),this.transition("idle")}cancel(){this.editor.history.bailToMark(TS),this.transition("idle")}},NS=class extends BS{tickMode="always_apply";constructor(e,t){super(e,"translating",t)}getHistoryMark(){return kS}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 vm(r,s):new vm(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(kS),this.transition("idle")}cancel(){this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.bailToMark(kS),this.transition("idle")}},OS=class extends yS{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new LS(e,this)),this.addChild(new FS(e,this)),this.addChild(new RS(e,this)),this.addChild(new zS(e,this)),this.addChild(new NS(e,this)),this.addChild(new $S(e,this)),this.addChild(new _S(e,this)),this.addChild(new US(e,this)),this.addChild(new HS(e,this)),this.addChild(new DS(e,this)),this.addChild(new AS(e,this))}},WS="editor.tool.set-active-tool",YS="editor.tool.toggle-locked",XS=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]}},KS=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)}}},VS=ro(),qS=Nf(VS),jS=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)}}},GS=ao(),ZS=Nf(GS),QS=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}}},JS=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)}},ey=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)}},ty="var(--land-selection, #2563eb)",ny=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)??[]}},iy=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),oy=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)},ry={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"},sy=e=>{for(const t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0;return!1},ay=Nf({}),dy=Wf(({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=""}=Kf(ay)??{},g=i??u?24*Number(n??c)/Number(t??l):n??c;return Of("svg",{ref:d,...ry,width:t??l??ry.width,height:t??l??ry.height,stroke:e??h,strokeWidth:g,className:iy("lucide",p,o),...!r&&!sy(a)&&{"aria-hidden":"true"},...a},[...s.map(([e,t])=>Of(e,t)),...Array.isArray(r)?r:[r]])}),ly=(e,t)=>{const n=Wf(({className:n,...i},o)=>{return Of(dy,{ref:o,iconNode:t,className:iy(`lucide-${r=oy(e),r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,`lucide-${e}`,n),...i});var r});return n.displayName=oy(e),n},cy=ly("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),uy=ly("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"}]]),hy=ly("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"}]]),py=ly("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"}]]),gy=ly("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),fy={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},my={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)"},Sy="default",yy={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}},by=new WeakMap,xy=Nf(null),Iy=Yf(()=>ir(nr().retainedShapeIdsSignal).map(e=>tm(wy,{shapeId:e},e))),vy=Yf(()=>{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 tm("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)})}),wy=Yf(({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=Kf(qS);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(Pm.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 nm("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?tm(dr,{clipAncestorIds:m,shapeElementToPage:x.elementToPage,children:tm(b,{shape:i,editor:t,isSelected:c,isHovered:v,shapeEditingSession:u})}):null,a&&p?tm(ar,{}):null,a&&f?tm(sr,{}):null]})}),Py="rgba(100, 116, 139, 0.82)",ky="rgba(255, 255, 255, 0.84)",Cy=Yf(()=>ir(nr().bindingPreviewActiveSignal)?tm(Ty,{}):null),Ty=Yf(()=>{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 nm(em,{children:[tm(Ey,{targetShapeId:t.targetShapeId}),tm(My,{bindingPreview:t,showGuide:!i})]})}),Ey=Yf(({targetShapeId:e})=>{const t=nr(),n=ir(t.cameraZoomSignal),i=ir(t.getShapeSignal(e));return i?tm(fr,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),My=Yf(({bindingPreview:e,showGuide:t})=>{const n=ir(nr().cameraZoomSignal),i=2/n,o=6/n,r=4/n;
73
- return nm(em,{children:[t?e.guidePath?tm(gr,{path:e.guidePath,strokeWidth:i,dashSize:o,gapSize:r,kind:"binding-preview",terminal:e.terminal}):tm(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
- tm("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
- tm("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})]})}),By=Yf(()=>ir(nr().brushBoxActiveSignal)?tm(Ry,{}):null),Ry=Yf(()=>{const e=ir(nr().brushBoxSignal);return e?tm("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}),Ay=Yf(()=>{const e=nr(),t=ir(e.selectionOverlayFrameGeometrySignal),n=ir(e.selectionOverlayCompanionFrameGeometriesSignal);return t||0!==n.length?nm(em,{children:[t?tm(Ly,{frameGeometry:t}):null,n.map((e,t)=>tm(Ly,{frameGeometry:e},`companion-${t}`))]}):null}),Ly=Yf(({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 nm("g",{transform:0===i?void 0:`rotate(${a} ${o.x} ${o.y})`,children:[tm("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}),tm("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})]})}),Fy=Yf(()=>{const e=ir(nr().selectionOverlayHandleAnchorsSignal);return e?tm($y,{anchors:e}):null}),$y=Yf(({})=>{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 nm(em,{children:[r.map(e=>tm("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=>nm("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:[tm("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),tm("path",{d:"M21 3v5h-5"})]},e.id)),d.map(e=>tm("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=>tm("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 tm(t?t.component:Sr,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),Uy=["ew-resize","nwse-resize","ns-resize","nesw-resize"],Dy=Yf(()=>{const e=nr(),t=ir(e.selectionOverlayPathSignal),n=ir(e.selectionOverlayBindingSegmentsSignal),i=ir(e.selectionOverlayFrameStyleSignal);return t?nm(em,{children:[
79
- tm(zy,{bindingSegments:n,strokeWidth:i.strokeWidth}),
80
- tm("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
- tm("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:i.strokeWidth})]}):null}),zy=Yf(({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 tm(em,{children:e.map(e=>e.guidePath?tm(gr,{path:e.guidePath,strokeWidth:n,dashSize:i,gapSize:o,kind:t,terminal:e.terminal},e.terminal):tm(pr,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:r,endInset:s,strokeWidth:n,dashSize:i,gapSize:o,kind:t,terminal:e.terminal},e.terminal))})}),_y=Yf(()=>ir(nr().selectionTranslationActiveSignal)?null:nm(em,{children:[
83
- tm(Dy,{}),
84
- tm(Ay,{}),
85
- tm(Fy,{})]})),Hy="rgba(37, 99, 235, 0.9)",Ny=Yf(()=>{const e=ir(nr().snapIndicatorsSignal);return 0===e.length?null:tm(Oy,{indicators:e})}),Oy=Yf(({indicators:e})=>{const t=ir(nr().cameraZoomSignal);
86
- return tm(em,{children:e.map(e=>tm("points"===e.type?Wy:Yy,{indicator:e,zoom:t},e.id))})}),Wy=Yf(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[o,r]=e.line,s=180*e.rotation/Math.PI;
87
- return nm("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${s} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[tm("path",{"data-ui":"snap-indicator-line",d:`M ${o.x} ${o.y} L ${r.x} ${r.y}`,fill:"none",stroke:Hy,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,o)=>tm("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:Hy,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${o}`))]})}),Yy=Yf(({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 tm("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:l,fill:"none",stroke:Hy,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),Xy=Yf(()=>{const e=nr(),t=ir(e.terminalBindingGuidesSignal),n=ir(e.selectionOverlayFrameStyleSignal);return 0===t.length?null:tm(zy,{bindingSegments:t,kind:"terminal-binding-guide",strokeWidth:n.strokeWidth})}),Ky=Yf(()=>nm("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
89
- tm("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
- tm(Vy,{layer:"below-host"}),
91
- tm(Ny,{}),
92
- tm(Xy,{}),
93
- tm(Cy,{}),
94
- tm(By,{}),
95
- tm(_y,{}),
96
- tm(Vy,{layer:"above-host"})]})),Vy=Yf(({layer:e})=>{const t=lo().getCanvasOverlays(e);return 0===t.length?null:tm(em,{children:t.map(({id:e,component:t})=>tm(t,{},e))})}),qy="canvas-surface",jy=`[data-ui="${qy}"]`,Gy=[{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}],Zy=14,Qy=16,Jy=20,eb=28,tb=16,nb={[Zy]:20,[Qy]:24,[Jy]:28,[eb]:36},ib=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})}},ob=new WeakMap,rb="land.rich-text-bubble-menu",sb="updatePosition",ab=[{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"}],db={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"},lb={width:"var(--toolbar-separator-width)",height:"var(--toolbar-separator-height)",background:"var(--border)",margin:"0 var(--toolbar-separator-margin-inline)"},cb={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"},ub={...cb,background:"transparent",color:"var(--muted-foreground)",cursor:"pointer"},hb=lm.extend({inclusive:!1,renderHTML({HTMLAttributes:e}){const{href:t,target:n,rel:i,...o}=e;return["span",sm(o,{"data-rich-text-link-href":t,style:"text-decoration-line: underline;"}),0]}}),pb=[um.configure({bold:!1,italic:!1,strike:!1}),am.extend({keepOnSplit:!0}),dm.extend({keepOnSplit:!0}),cm.extend({keepOnSplit:!0}),hb.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})],gb=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),fb={id:"land.text.dom-events",handle({event:e,name:t}){if(!gb.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},mb="text.create",Sb=class extends yS{constructor(e){super(e,"text"),this.initial="idle",this.addChild(new yb(e,this)),this.addChild(new bb(e,this))}},yb=class extends yS{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("pointing",{originPagePoint:e.pagePoint.clone(),shapeId:null,didCreateShape:!1})}},bb=class extends yS{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e,this.editor.history.mark(mb)}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(mb),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:mb,reuseExistingMark:!0,preserveInteraction:!0},"user"),this.editor.isToolLocked()&&this.transition("idle")}onCancel(){this.info?.didCreateShape||this.editor.history.bailToMark(mb),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)}},xb="arrow-label",Ib="geo-label",vb={[xb]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!0,canUseSelectionFrameHandles:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[Ib]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!1,canUseSelectionFrameHandles:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}},wb=["start","middle","end"],Pb=class extends mS{type="text";getDefaultProps(){return{richText:Bo(""),w:16,h:Yr(tb),autoSize:!0,scale:1,font:Sy,size:tb,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&&wb.includes(i)?t.textAlign:n.textAlign)};var i}getBounds(e){return(e=>new wm(e.x,e.y,Es(e),Ms(e)))(e)}getLocalBounds(e){return Bs(e)}getRenderBounds(e){return Bs(e)}getExportBounds(e){return Bs(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,Ms(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():vm.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]}}},kb=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)}]}}},Cb=".label",Tb=class extends SS{type=xb;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}${Cb}`,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}},Eb=".label",Mb=class extends SS{type=Ib;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}${Eb}`,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}},Bb="text.edit",Rb="arrow-label.edit",Ab="arrow-label.create",Lb="geo-label.edit",Fb="geo-label.create",$b=[{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)"}],Ub=[{id:"s",value:14,label:"S"},{id:"m",value:16,label:"M"},{id:"l",value:20,label:"L"},{id:"xl",value:28,label:"XL"}],Db=[{value:"start",label:"Align left",icon:"align-left"},{value:"middle",label:"Align center",icon:"align-center"},{value:"end",label:"Align right",icon:"align-right"}],zb=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"]}}}),_b=[],Hb=2*Math.PI,Nb=class extends SS{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 Ba(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(!Ba(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(!Ba(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(!Ba(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(!Ba(n)||!i||Ba(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}},Ob=class extends mS{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 wm(0,0,e.props.w,e.props.h)}getExportBounds(e){const t=(e=>ba(new vm(e.props.start.x,e.props.start.y),new vm(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}},Wb="arrow.create",Yb=class extends yS{constructor(e){super(e,"arrow"),this.initial="idle",this.addChild(new Xb(e,this)),this.addChild(new Kb(e,this))}},Xb=class extends yS{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 vm(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})}},Kb=class extends yS{info=null;constructor(e,t){super(e,"creating",t)}onEnter(e){if(this.info=e,!this.info)return;this.editor.history.mark(Wb);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(Wb),void this.transition("idle");G(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(Wb),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})}else this.transition("idle")}onCancel(){this.editor.history.bailToMark(Wb),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=Ba(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(Ba(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)}},Vb=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}}}},qb=[{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)"}],jb=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Gb=[{value:"none",label:"None",icon:"minus"},{value:"arrow",label:"Arrow",icon:"arrow-right"}],Zb=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 Ob],shapeSvgExporters:[new Vb],bindingUtils:[new Nb],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:[WS],getGroups:e=>[{id:"arrow.tools",items:[{kind:"button",id:"arrow.tool.arrow",actionId:WS,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 Yb(e),{shortcut:"a"})}}],canvasRenderPlugins:[{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:ad}]}],shapeTypes:["arrow"]})}),Qb=.08,Jb=new WeakMap,ex=new WeakMap,tx=new WeakMap,nx=new WeakMap,ix="draw.create",ox=class extends yS{constructor(e){super(e,"draw"),this.initial="idle",this.addChild(new rx(e,this)),this.addChild(new sx(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("draw")}},rx=class extends yS{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)]}]})}},sx=class extends yS{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(ix)}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(ix),void this.transition("idle");this.info?.parentId.startsWith("shape:")||G(this.editor,t,{source:"user"}),this.editor.history.squashToMark(ix),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.editor.history.bailToMark(ix),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}},ax=class extends mS{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 wm(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=Md(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 vm(e.minX,e.minY),n=new vm(e.maxX,e.minY),i=new vm(e.maxX,e.maxY),o=new vm(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)}}}},dx=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}}},lx=[{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)"}],cx=[{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)"}],ux=[{value:4,label:"4"},{value:6,label:"6"},{value:8,label:"8"},{value:10,label:"10"}],hx=[{value:"open",label:"Open"},{value:"closed",label:"Closed"}],px=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 ax],shapeSvgExporters:[new dx],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:[WS],getGroups:e=>[{id:"draw.tools",items:[{kind:"button",id:"draw.tool.draw",actionId:WS,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 ox(e),{shortcut:"p"})}}],canvasRenderPlugins:[{id:"land.draw.react",shapeRenderers:[{type:"draw",component:Tl}]}],shapeTypes:["draw"]})}),gx=class extends yS{constructor(e){super(e,"eraser"),this.initial="idle",this.addChild(new fx(e,this)),this.addChild(new mx(e,this)),this.addChild(new Sx(e,this))}onExit(){Dl(this.editor)}},fx=class extends yS{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:Bl(e,t.pagePoint),erasingShapeIds:new Set,trail:[t.pagePoint.clone()]};return Ll(e,n,t),Ul(e,n),n})(this.editor,e))}},mx=class extends yS{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}},Sx=class extends yS{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))}},yx=Yf(()=>ir(nr().eraserTrailActiveSignal)?tm(bx,{}):null),bx=Yf(()=>{const e=nr(),t=ir(e.eraserTrailSignal),n=ir(e.cameraZoomSignal),i=Math.max(n,1e-4),o=(()=>{const[e,t]=Qf(()=>_l());return Vf(()=>{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=Zf({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-Tx*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>Ix?n.slice(-48):n,Px)}(r.current.samples,s);if(0===a.length)return null;const d=(c=wx/i,0===(l=a).length||c<=0?null:1===l.length?tc(Yl(l[0],c/2,Cx))??"":tc((e=>{if(0===e.length)return[];if(1===e.length)return Yl(e[0].point,Math.max(e[0].radius,.01),Cx);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<kx;r++){const s=r/kx;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?tm("g",{"data-ui":"eraser-trail-overlay",children:tm("path",{"data-ui":"eraser-trail-scribble",d:d,fill:xx})}):null}),xx="rgba(142, 142, 142, 0.16)",Ix=48,vx=1,wx=12,Px=.32,kx=8,Cx=13,Tx=16,Ex=8,Mx=180,Bx=180,Rx=680,Ax=bo({name:"eraser",createFeature:()=>({id:"land.eraser.bundle",editorRuntimePlugins:[{id:"land.eraser",toolbarContributions:[{id:"eraser.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[WS],getGroups:e=>[{id:"eraser.tools",items:[{kind:"button",id:"eraser.tool.eraser",actionId:WS,value:"eraser",label:"Eraser",shortcut:e.editor.shortcuts.getToolShortcutLabel("eraser"),icon:"eraser",dataUi:"eraser-tool-button"}]}]}],setup(e){e.tools.register("eraser",e=>new gx(e),{shortcut:"e"})}}],canvasRenderPlugins:[{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",layer:"below-host",component:yx}]}],shapeTypes:[]})}),Lx=class extends mS{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 wm(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 vm(e.minX,e.minY),new vm(e.maxX,e.minY),new vm(e.maxX,e.maxY),new vm(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&&Mi(t,n,e,i)<=o)return!0}return!1})(this.getBounds(e),t.positionedStart,t.positionedEnd,Math.max(6,t.margin))}},Fx="frame.create",$x=class extends yS{constructor(e){super(e,"frame"),this.initial="idle",this.addChild(new Ux(e,this)),this.addChild(new Dx(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("frame")}},Ux=class extends yS{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})}},Dx=class extends yS{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(Fx)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.editor.history.squashToMark(Fx),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(Fx),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 wm(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 vm(e.x+o,e.y+r);return new wm(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}},zx=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]}]}}},_x=[{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)"}],Hx=[{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)"}],Nx=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Ox=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 Lx],shapeSvgExporters:[new zx],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:[WS],getGroups:e=>[{id:"frame.tools",items:[{kind:"button",id:"frame.tool.frame",actionId:WS,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 $x(e),{shortcut:"f"})}}],canvasRenderPlugins:[{id:"land.frame.react",shapeRenderers:[{type:"frame",component:pc}]}],shapeTypes:["frame"]})}),Wx="geo.create",Yx=class extends yS{geo;constructor(e,t,n){super(e,t),this.geo=n,this.initial="idle",this.addChild(new Xx(e,this)),this.addChild(new Kx(e,this))}getDefaultProps(){return{...this.editor.getDefaultShapeProps("geo"),geo:this.geo}}onEnter(){this.editor.updateDefaultShapeProps("geo",{geo:this.geo})}},Xx=class extends yS{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})}},Kx=class extends yS{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(Wx)}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(Wx),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(Wx),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 wm(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 vm(e.x+i,e.y+o);return new wm(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}},Vx=class extends Yx{constructor(e){super(e,"rectangle","rectangle")}},qx=class extends Yx{constructor(e){super(e,"ellipse","ellipse")}},jx=class extends Yx{constructor(e){super(e,"diamond","diamond")}},Gx=class extends Yx{constructor(e){super(e,"triangle","triangle")}},Zx=class extends Yx{constructor(e){super(e,"hexagon","hexagon")}},Qx=class extends Yx{constructor(e){super(e,"star","star")}},Jx=["rectangle","ellipse","diamond","triangle","hexagon","star"],eI=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],tI=class extends mS{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 wm(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 wm(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 Bc(t,n,yc(i,e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent}));default:return Bc(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}},nI=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 wm(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}}}},iI=[{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)"}],oI=[{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)"}],rI=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],sI=[{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"}],aI=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 tI],shapeSvgExporters:[new nI],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:[WS],getGroups:e=>[{id:"geo.tools",items:[{kind:"segmented",id:"geo.tool-picker",actionId:WS,options:sI.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:sI.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 Vx(e),{shortcut:"r"}),e.tools.register("ellipse",e=>new qx(e),{shortcut:"o"}),e.tools.register("diamond",e=>new jx(e),{shortcut:"d"}),e.tools.register("triangle",e=>new Gx(e)),e.tools.register("hexagon",e=>new Zx(e)),e.tools.register("star",e=>new Qx(e))}}],canvasRenderPlugins:[{id:"land.geo.react",shapeRenderers:[{type:"geo",component:Hc}]}],shapeTypes:["geo"]})}),dI=class extends mS{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 wm(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}},lI=class{type="group";toSvg(e){return{tag:"g"}}},cI=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 dI],shapeSvgExporters:[new lI]}],canvasRenderPlugins:[{id:"land.group.react",shapeRenderers:[{type:"group",component:Wc}]}],shapeTypes:["group"]})}),uI="image.replace",hI="image.download-original",pI="image.insert",gI="image.crop",fI="image.crop.done",mI="image.crop.zoom",SI="image.crop.aspect-ratio",yI="image.crop.reset",bI="image.corner-radius",xI=1e-4,II=1e-4,vI="image.crop",wI="image.crop.translate",PI="image.crop:edit:",kI=[{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}],CI={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"},TI=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],EI=new Map,MI="image.smudge",BI="image.smudge.cancel",RI="image.smudge.confirm",AI="image.smudge:edit:",LI=24,FI="#111827",$I=.45,UI=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()}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:[bu(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,bu(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()}},DI=new WeakMap,zI=class extends mS{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,Lu(t.w,n.w)),h:Math.max(24,Lu(t.h,n.h)),assetId:(i=t.assetId,"string"==typeof i&&i.startsWith("asset:")?t.assetId:null),crop:jc(t.crop),cornerRadius:Ru(t.cornerRadius,n.cornerRadius),altText:"string"==typeof t.altText?t.altText:n.altText};var i}getBounds(e){return new wm(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}},_I=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=Au({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]}}},HI={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(!Iu(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 vm(e.x-r.left,e.y-r.top);return qu(t,o,t.screenToPage(s))?0!==t.inputs.state.get().buttons?"grabbing":"grab":void 0}},NI={id:"land.image.smudge.dom-events",handle:()=>"continue",getCursor({clientPoint:e,container:t,editor:n}){const i=(e=>{const[t]=e.getSelectedShapes();if(!Iu(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 vm(e.x-o.left,e.y-o.top);return qu(n,i,n.screenToPage(r))?"crosshair":0!==n.inputs.state.get().buttons?"grabbing":"grab"}},OI=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 zI],shapeSvgExporters:[new _I],interactionHandlers:[Tu(),Fu()],canvasActions:[Bu(pI),Bu(uI),Bu(hI),...ku(),{id:MI,isVisible:e=>!!vu(e)&&!wu(e)&&!Pu(e),isEnabled(e){const t=vu(e);return!!t&&!t.isLocked&&!!t.props.assetId},getValue:e=>Pu(e),run({context:e}){const t=vu(e);t&&!t.isLocked&&t.props.assetId&&pu({editor:e.editor,shape:t})}},{id:BI,isVisible:e=>Pu(e),isEnabled:e=>Pu(e),run({context:e}){gu(e.editor)}},{id:RI,isVisible:e=>Pu(e),isEnabled:e=>Pu(e),run({context:e}){yu(e.editor,{replace:!0})}},{id:bI,isVisible:e=>"image"===e.selection.commonShapeType,isEnabled:e=>e.selection.selectedShapes.some(e=>Iu(e)&&!e.isLocked),getValue:e=>(e=>{let t;for(const n of e){if(!Iu(n))continue;const e=Ru(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)?Ru(n):null})(t);if(null===n)return;const i=e.selection.selectedShapes.filter(Iu).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:[pI],getGroups:()=>[{id:"image.tools",items:[{kind:"button",id:pI,actionId:pI,label:"Image",icon:"image-plus",dataUi:"insert-image-tool-button"}]}]},{id:"image.selection-toolbar",surface:"selection",order:30,actionIds:[gI,fI,mI,SI,yI,MI,BI,RI,bI,uI,hI],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups(e){const t=[];return Pu(e)?[{id:"image.smudge-actions",order:10,items:[{kind:"button",id:BI,actionId:BI,label:"Cancel smudge",icon:"x",dataUi:"cancel-image-smudge-button"},{kind:"button",id:RI,actionId:RI,label:"Confirm smudge",icon:"check",dataUi:"confirm-image-smudge-button"}]}]:(wu(e)&&t.push({id:"image.crop-zoom",order:10,items:[{kind:"stepper",id:"image.crop.zoom-stepper",actionId:mI,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:SI,options:kI.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:yI,actionId:yI,label:"Reset crop",icon:"rotate-ccw",dataUi:"reset-image-crop-button"}]}),t.push((({dataUiPrefix:e,id:t,order:n})=>({id:t,order:n,items:[Hu({dataUiPrefix:e})]}))({dataUiPrefix:"image",id:"image.style-corner-radius",order:35})),t.push({id:"image.asset",order:40,items:[{kind:"button",id:gI,actionId:gI,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:fI,actionId:fI,label:"Done cropping",icon:"check",dataUi:"done-cropping-button"},{kind:"button",id:uI,actionId:uI,label:"Replace image",icon:"image-plus",dataUi:"replace-image-button"},{kind:"button",id:hI,actionId:hI,label:"Download original",icon:"download",dataUi:"download-image-original-button"}]}),t)}},{id:"image.floating-selection-toolbar",surface:"selection",placement:"floating",order:30,actionIds:[gI,fI,mI,SI,yI,MI,BI,RI,bI,uI,hI],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups:e=>Pu(e)?[{id:"image.floating-smudge-actions",order:10,items:[{kind:"button",id:"image.floating-smudge.cancel",actionId:BI,label:"Cancel smudge",icon:"x",dataUi:"floating-cancel-image-smudge-button"},{kind:"button",id:"image.floating-smudge.confirm",actionId:RI,label:"Confirm smudge",icon:"check",dataUi:"floating-confirm-image-smudge-button"}]}]:wu(e)?[{id:"image.floating-crop-zoom",order:10,items:[{kind:"stepper",id:"image.floating-crop.zoom-stepper",actionId:mI,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:SI,options:kI.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:[Hu({dataUiPrefix:"floating-image-crop"})]},{id:"image.floating-crop-actions",order:30,items:[{kind:"button",id:"image.floating-crop.done",actionId:fI,label:"Done cropping",icon:"check",dataUi:"floating-done-cropping-button"},{kind:"button",id:"image.floating-crop.reset",actionId:yI,label:"Reset crop",icon:"rotate-ccw",dataUi:"floating-reset-image-crop-button"}]}]:[{id:"image.floating-corner-radius",order:10,items:[Hu({dataUiPrefix:"floating-image"})]},{id:"image.floating-asset",order:20,items:[{kind:"button",id:"image.floating.crop",actionId:gI,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:uI,label:"Replace image",icon:"image-plus",dataUi:"floating-replace-image-button"},{kind:"button",id:"image.floating.download",actionId:hI,label:"Download original",icon:"download",dataUi:"floating-download-image-original-button"}]}]}],contextMenuContributions:[{id:"image.shape-context-menu",target:"selection",order:30,actionIds:[gI,MI,uI,hI],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getSections:()=>[{id:"image.asset-context-menu",title:"Image",items:[{kind:"command",id:gI,actionId:gI,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:uI,actionId:uI,label:"Replace image",icon:"image-plus",dataUi:"context-menu-replace-image-button"},{kind:"command",id:hI,actionId:hI,label:"Download original",icon:"download",dataUi:"context-menu-download-image-original-button"}]}]}]}],canvasRenderPlugins:[{id:"land.image.react",domEventGuards:[HI,NI],selectionCustomHandleRenderers:[{type:vI,component:Xu}],shapeRenderers:[{type:"image",component:Nu}]}],shapeTypes:["image"]})}),WI=class extends yS{constructor(e){super(e,"laser"),this.initial="idle",this.addChild(new YI(e,this)),this.addChild(new XI(e,this)),this.addChild(new KI(e,this))}},YI=class extends yS{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 Gu(e,n),n})(this.editor,e))}},XI=class extends yS{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&&(ju(this.info,e.pagePoint),Gu(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}},KI=class extends yS{info=null;constructor(e,t){super(e,"drawing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&(ju(this.info,e.pagePoint),Gu(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}},VI=Yf(()=>ir(nr().laserTrailActiveSignal)?tm(qI,{}):null),qI=Yf(()=>{const e=nr(),t=ir(e.laserTrailSignal),n=ir(e.cameraZoomSignal),i=Math.max(n,1e-4),o=(()=>{const[e,t]=Qf(()=>Zu());return Vf(()=>{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=Zf({sessionId:0,samples:[],sourceLength:0}),s=Math.max(o,Zu());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(Ju(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-ov*s;for(let d=r;d<o.length;d++){const t=o[d];Qu(e,{x:t.x,y:t.y},n,ch(a,i,(d-r+1)/s))}e.sourceLength=o.length,Ju(e,i)})(r.current,t,i,s),d=function(e,t){const n=eh(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(lh(i[i.length-1],e[o],n));return i})(n.length>QI?n.slice(-64):n,tv)}(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(Vf(()=>{null!==u&&e.clearLaserTrail(u)},[e,u]),!t||c)return null;const h=l&&void 0!==a?uh(1-(s-a)/lv,0,1):1,p=(f=ev/i,0===(g=d).length||f<=0?null:1===g.length?ph(nh(g[0],f/2,iv))??"":ph((e=>{if(0===e.length)return[];if(1===e.length)return nh(e[0].point,Math.max(e[0].radius,.01),iv);const t=[],n=[];for(const a of e){const e=rh(a.direction);hh(t,ah(a.point,dh(e,a.radius))),hh(n,sh(a.point,dh(e,a.radius)))}const i=[];for(const a of t)hh(i,a);const o=e[e.length-1],r=rh(o.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const o=[];for(let r=1;r<nv;r++){const s=r/nv;o.push(sh(e,sh(dh(t,Math.sin(Math.PI*s)*i),dh(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)hh(i,a);for(let a=n.length-1;a>=0;a--)hh(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]+ih(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=uh(s/i,0,1);return{point:o,direction:th(e,r),radius:t/2*a,runningLength:s}})})(g,f))));var g,f;return p?nm("g",{"data-ui":"laser-trail-overlay",style:{opacity:h},children:[tm("path",{"data-ui":"laser-trail-glow",d:p,fill:GI,style:{filter:`blur(${ZI/i}px)`}}),tm("path",{"data-ui":"laser-trail-beam",d:p,fill:jI})]}):null}),jI="rgb(255, 38, 38)",GI="rgba(255, 48, 48, 0.55)",ZI=4,QI=64,JI=1,ev=12,tv=.32,nv=8,iv=13,ov=16,rv=8,sv=600,av=300,dv=1400,lv=400,cv=bo({name:"laser",createFeature:()=>({id:"land.laser.bundle",editorRuntimePlugins:[{id:"land.laser",toolbarContributions:[{id:"laser.tool-toolbar",surface:"tool",placement:"chrome",order:55,actionIds:[WS],getGroups:e=>[{id:"laser.tools",items:[{kind:"button",id:"laser.tool.laser",actionId:WS,value:"laser",label:"Laser",shortcut:e.editor.shortcuts.getToolShortcutLabel("laser"),icon:"wand",dataUi:"laser-tool-button"}]}]}],setup(e){e.tools.register("laser",e=>new WI(e),{shortcut:"l"})}}],canvasRenderPlugins:[{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",layer:"below-host",component:VI}]}],shapeTypes:[]})}),uv="path.node",hv="path.control",pv=new WeakMap,gv=["nonzero","evenodd"],fv=["corner","smooth","symmetric"],mv=1e-6,Sv=1/3,yv=Math.PI/8,bv=new WeakMap,xv=new WeakMap,Iv="land.path.draftSubpathId",vv="land.path.previewNodeId",wv="var(--land-selection, #2563eb)",Pv=pm((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,M,B,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),M=F*L,p=b*F,g=p-(p-F),f=F-g,p=b*L,m=p-(p-L),S=L-m,B=f*S-(M-g*m-f*m-g*S),y=E-B,h=E-y,x[0]=E-(y+h)+(h-B),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-M,h=C-y,x[1]=C-(y+h)+(h-M),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),M=l*L,p=b*l,g=p-(p-l),f=l-g,p=b*L,m=p-(p-L),S=L-m,B=f*S-(M-g*m-f*m-g*S),y=E-B,h=E-y,P[0]=E-(y+h)+(h-B),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-M,h=C-y,P[1]=C-(y+h)+(h-M),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),M=F*c,p=b*F,g=p-(p-F),f=F-g,p=b*c,m=p-(p-c),S=c-m,B=f*S-(M-g*m-f*m-g*S),y=E-B,h=E-y,P[0]=E-(y+h)+(h-B),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-M,h=C-y,P[1]=C-(y+h)+(h-M),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),M=l*c,p=b*l,g=p-(p-l),f=l-g,p=b*c,m=p-(p-c),S=c-m,B=f*S-(M-g*m-f*m-g*S),y=E-B,h=E-y,P[0]=E-(y+h)+(h-B),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-M,h=C-y,P[1]=C-(y+h)+(h-M),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)),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 k(o,i)/E(o)/E(i)},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 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:M(this.point,e.point,i.point),cosine:B(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()})(),kv=1,Cv=1,Tv="path.insert-node",Ev=1,Mv=class extends mS{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=$p(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(Ah)),fill:P(t.fill,n.fill),stroke:P(t.stroke,n.stroke),strokeWidth:Math.max(1,Lp(t.strokeWidth,n.strokeWidth)),fillRule:vh(t.fillRule)?t.fillRule:n.fillRule};var i}getBounds(e){const t=Yh(e).localBounds;return new wm(e.x+t.x,e.y+t.y,t.w,t.h)}getLocalBounds(e){return Yh(e).localBounds}getRenderBounds(e){return Yh(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}getSelectionResizeLocalBounds(e){return Yh(e).pointBounds}resizeSelectionBounds(e,t){const n=qh(e,this.getLocalToPageTransform(e)).map(e=>({...e,nodes:e.nodes.map(e=>Dp(e,e=>((e,t)=>0===t.selectionRotation?e:vm.RotWith(e,t.selectionRotationCenter,-t.selectionRotation))(e,t)))})),i=Vh(((e,t)=>{const n=Yh(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 Kh(e.props.subpaths,e=>new vm(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=>Dp(e,e=>((e,t)=>0===t.selectionRotation?e:vm.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 Yh(e).outlineVertices.map(t=>new vm(e.x+t.x,e.y+t.y))}getHandleSnapGeometry(e){return{points:e.props.subpaths.flatMap(e=>e.nodes.flatMap(e=>[{point:Fh(e),kind:"custom"},...e.in?[{point:$h(e),kind:"custom"}]:[],...e.out?[{point:Uh(e),kind:"custom"}]:[]])),outline:Yh(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:uv,id:(i=e.id,r=t.id,["node",i,r].map(encodeURIComponent).join("|")),point:o.applyToPoint(Fh(t)),cursor:"grab"}];var i,r;return t.in&&n.push({kind:"custom",type:hv,id:Sh(e.id,t.id,"in"),point:o.applyToPoint($h(t)),cursor:"grab"}),t.out&&n.push({kind:"custom",type:hv,id:Sh(e.id,t.id,"out"),point:o.applyToPoint(Uh(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:jh(e,t.editor.computeShapeLocalToPageTransform(e)),bindingSegments:[]}:{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,bindingSegments:[]}}hitTest(e,t,n){const i=new vm(t.x-e.x,t.y-e.y),o=Yh(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&&Zh(t,n,r)<=i)return!0}return!1})(o.flattenedSubpaths,i,e.props.strokeWidth/2+6)}hitTestLineSegment(e,t){const n=new vm(t.positionedStart.x-e.x,t.positionedStart.y-e.y),i=new vm(t.positionedEnd.x-e.x,t.positionedEnd.y-e.y),o=t.margin+e.props.strokeWidth/2;return Yh(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&&(Up(i,e,t)<=o||Up(s,e,t)<=o||Up(e,i,s)<=o||Up(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]}}},Bv="path.create",Rv=1,Av=1,Lv=class extends yS{draft=null;constructor(e){super(e,"path"),this.initial="idle",this.addChild(new Fv(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(Bv);const t=this.editor.getDefaultShapeProps("path"),n=`subpath:${Av+=1}`,i=zp(),[o]=this.editor.commands.createShapes([{type:"path",x:e.x,y:e.y,meta:hp({},{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(!Ih(t))return this.cancelDraft(),null;if(function(e,t,n,i,o){const r=((e,t,n)=>{const i=Jh(t.props.subpaths,n)?.nodes[0];return i?e.computeShapeLocalToPageTransform(t).applyToPoint(new vm(i.x,i.y)):null})(e,t,n),s=Jh(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:pp(t.meta),props:{subpaths:Hp(t.props.subpaths,e).map(t=>t.id===e.subpathId?{...t,closed:!0}:t)}}],{source:"user"}),this.finishDraft(),null}const n=_p(this.editor,t,e),i=this.draft.previewNodeId??zp(),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:hp(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(!Ih(n))return;const i=_p(this.editor,n,e.originPagePoint),o=_p(this.editor,n,t),r=tp(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:hp(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(!Ih(t)||Np(t,this.draft)<1)return;const n=_p(this.editor,t,e),i=this.draft.previewNodeId??zp(),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:hp(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!!Ih(e)&&Np(e,this.draft)>=2}finishDraft(e={}){if(!this.draft)return;const t=e.switchToSelect??!0,n=this.editor.getShape(this.draft.shapeId);if(Ih(n)){const e=Hp(n.props.subpaths,this.draft),t=Vh(qh({...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:pp(n.meta),props:{subpaths:t.subpaths}}],{source:"user"}),this.draft.createdShape&&G(this.editor,n.id,{source:"user"})}this.editor.history.squashToMark(Bv,"shape.create"),this.draft=null,t&&!this.editor.isToolLocked()&&this.editor.commands.setActiveTool("select",{source:"system"})}cancelDraft(){this.draft&&(this.editor.history.bailToMark(Bv),this.draft=null)}hasDraft(){return null!==this.draft}},Fv=class extends yS{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 yS{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}},Uv="path.edit",Dv="path.boolean.union",zv="path.boolean.subtract",_v="path.boolean.intersect",Hv="path.boolean.xor",Nv="path.node.delete",Ov="path.node.make-curve",Wv="path.node.remove-handles",Yv=[{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)"}],Xv=[{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)"}],Kv=[{value:1,label:"1"},{value:2,label:"2"},{value:3,label:"3"},{value:5,label:"5"},{value:8,label:"8"}],Vv=[{value:"nonzero",label:"Nonzero"},{value:"evenodd",label:"Even odd"}],qv=class{type="path";toSvg(e,t){const n=Yh(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",aI],["draw",px],["arrow",Zb],["eraser",Ax],["laser",cv],["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 Mv],shapeSvgExporters:[new qv],interactionHandlers:[Ap()],canvasActions:[Wp("fill"),Wp("stroke"),Wp("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(Ih(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(!vh(t))return;const n=e.selection.selectedShapes.filter(Ih).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{fillRule:t}}));n.length>0&&e.editor.commands.updateShapes(n,{source:"user"})}},Yp("fill"),Yp("stroke"),Yp("strokeWidth"),{id:"path.default-fillRule",isVisible:e=>"path"===e.tool.activeToolId,getValue:e=>e.editor.getDefaultShapeProps("path").fillRule,run({context:e,value:t}){vh(t)&&e.editor.updateDefaultShapeProps("path",{fillRule:t})}},{id:Uv,isVisible:e=>1===e.selection.count&&"path"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return Ih(t)&&!t.isLocked},run({context:e}){const[t]=e.selection.selectedShapes;Ih(t)&&(ap(e.editor,null),e.editor.startEditingShape({shapeId:t.id,markId:"path.edit",entryMode:"focusEnd"},"user"))}},{id:Nv,isVisible:e=>!!sp(e.editor),isEnabled(e){const t=sp(e.editor);return!!t&&!t.shape.isLocked},run({context:e}){const t=sp(e.editor);if(!t||t.shape.isLocked)return;const n=rp(t.shape.props.subpaths,t.selection.subpathId,t.selection.nodeId);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"}),ap(e.editor,null)}},{id:Ov,isVisible:e=>!!sp(e.editor),isEnabled(e){const t=sp(e.editor);return!(!t||t.shape.isLocked||t.node.in||t.node.out)},run({context:e}){const t=sp(e.editor);if(!t||t.shape.isLocked)return;const n=np(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);Ih(i)&&dp(e.editor,i,t.selection.subpathId,t.selection.nodeId)}},{id:Wv,isVisible:e=>!!sp(e.editor),isEnabled(e){const t=sp(e.editor);return!(!t||t.shape.isLocked||!t.node.in&&!t.node.out)},run({context:e}){const t=sp(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);Ih(i)&&dp(e.editor,i,t.selection.subpathId,t.selection.nodeId)}},Xp("union"),Xp("subtract"),Xp("intersect"),Xp("xor")],toolbarContributions:[{id:"path.tool-toolbar",surface:"tool",placement:"chrome",order:47,actionIds:[WS],getGroups:e=>[{id:"path.tools",items:[{kind:"button",id:"path.tool.path",actionId:WS,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:()=>Op({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:[Uv,"path.set-fill","path.set-stroke","path.set-strokeWidth","path.set-fillRule",Dv,zv,_v,Hv],when:e=>"path"===e.selection.commonShapeType,getGroups(e){const t=[{id:"path.edit",items:[{kind:"button",id:"path.edit",actionId:Uv,label:"Edit",icon:"square-pen",dataUi:"path-edit-button"}]},...Op({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",fillRuleActionId:"path.set-fillRule",dataUiPrefix:"path"})];return Kp(e).length>=2&&t.push({id:"path.boolean",items:[{kind:"button",id:"path.boolean.union",actionId:Dv,label:"Union",icon:"group",dataUi:"path-boolean-union-button"},{kind:"button",id:"path.boolean.subtract",actionId:zv,label:"Subtract",icon:"minus",dataUi:"path-boolean-subtract-button"},{kind:"button",id:"path.boolean.intersect",actionId:_v,label:"Intersect",icon:"crop",dataUi:"path-boolean-intersect-button"},{kind:"button",id:"path.boolean.xor",actionId:Hv,label:"Exclude",icon:"ungroup",dataUi:"path-boolean-xor-button"}]}),t}},{id:"path.floating-selection-toolbar",surface:"selection",placement:"floating",order:22,actionIds:[Uv,Nv,Ov,Wv,"path.set-fill","path.set-stroke","path.set-strokeWidth","path.set-fillRule",Dv,zv,_v,Hv],when:e=>!("path"!==e.selection.commonShapeType||e.editor.getShapeEditingSession()&&!sp(e.editor)),getGroups(e){if(sp(e.editor))return[{id:"path.floating-node-edit",items:[{kind:"button",id:"path.floating-node.delete",actionId:Nv,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:Wv,label:"Corner point",shortcut:"X",icon:"to-corner",dataUi:"floating-path-node-remove-handles-button"},{kind:"button",id:"path.floating-node.make-curve",actionId:Ov,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:Uv,label:"Edit",icon:"square-pen",dataUi:"floating-path-edit-button"}]},...Op({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",fillRuleActionId:"path.set-fillRule",dataUiPrefix:"floating-path"})];return Kp(e).length>=2&&t.push({id:"path.floating-boolean",items:[{kind:"button",id:"path.floating-boolean.union",actionId:Dv,label:"Union",icon:"group",dataUi:"floating-path-boolean-union-button"},{kind:"button",id:"path.floating-boolean.subtract",actionId:zv,label:"Subtract",icon:"minus",dataUi:"floating-path-boolean-subtract-button"},{kind:"button",id:"path.floating-boolean.intersect",actionId:_v,label:"Intersect",icon:"crop",dataUi:"floating-path-boolean-intersect-button"},{kind:"button",id:"path.floating-boolean.xor",actionId:Hv,label:"Exclude",icon:"ungroup",dataUi:"floating-path-boolean-xor-button"}]}),t}}],contextMenuContributions:[{id:"path.context-menu",target:"selection",order:38,actionIds:[Uv,Dv,zv,_v,Hv],when:e=>"path"===e.selection.commonShapeType,getSections(e){const t=[{kind:"command",id:"path.edit",actionId:Uv,label:"Edit path",icon:"square-pen",dataUi:"path-context-edit"}];return Kp(e).length>=2&&t.push({kind:"command",id:"path.boolean.union",actionId:Dv,label:"Union paths",icon:"group",dataUi:"path-context-boolean-union"},{kind:"command",id:"path.boolean.subtract",actionId:zv,label:"Subtract paths",icon:"minus",dataUi:"path-context-boolean-subtract"},{kind:"command",id:"path.boolean.intersect",actionId:_v,label:"Intersect paths",icon:"crop",dataUi:"path-context-boolean-intersect"},{kind:"command",id:"path.boolean.xor",actionId:Hv,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 Lv(e),{shortcut:"b"})}}],canvasRenderPlugins:[{id:"land.path.react",canvasOverlays:[{id:"land.path.draft-overlay",component:gp,layer:"above-host",order:20},{id:"land.path.edit-insert-preview-overlay",component:wh,layer:"above-host",order:21}],shapeRenderers:[{type:"path",component:bp}],selectionCustomHandleRenderers:[{type:uv,component:xp},{type:hv,component:Ip}]}],shapeTypes:["path"]})})],["image",OI],["text",zb],["frame",Ox],["group",cI]],Gv=["select","hand","rectangle","ellipse","diamond","triangle","hexagon","star","arrow","draw","path","text","frame","eraser","laser"],Zv=new Set(Gv),Qv=Gv.map(e=>`"${e}"`).join(", "),Jv=[],ew={readyRuntime:null,status:null},tw=new Set,nw="snapshots",iw="imageBlobs",ow=null,rw=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,Xg(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()}},sw=Mg("canvas-kit.clipboard-service"),aw="system.clipboard.copy",dw="system.clipboard.cut",lw="system.clipboard.paste",cw="system.clipboard.paste-at-point",uw=[{actionId:aw,shortcut:{key:"c",accelKey:!0}},{actionId:dw,shortcut:{key:"x",accelKey:!0}},{actionId:lw,shortcut:{key:"v",accelKey:!0}}],hw=[{id:"system.selection-clipboard-context-menu",target:"selection",order:1e3,actionIds:[aw,dw],getSections:e=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:aw,actionId:aw,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(aw),dataUi:"context-menu-copy-selection-button"},{kind:"command",id:dw,actionId:dw,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(dw),dataUi:"context-menu-cut-selection-button"}]}]},{id:"system.canvas-clipboard-context-menu",target:"canvas",order:1e3,actionIds:[cw],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:cw,actionId:cw,label:"Paste here",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(lw),dataUi:"context-menu-paste-here-button"}]}]}],pw="image-blob:",gw=Yf(({editor:e,hostBridge:t,imageAssetService:n,flushSnapshot:i})=>{const o=Zf(null),r=Zf(null),{insertImageFromFile:s,replaceSelectedImage:a}=(({editor:e,imageAssetService:t,flushSnapshot:n})=>({insertImageFromFile:Xf(async({file:i,pagePoint:o,size:r})=>Sf({editor:e,imageObjectUrls:t.objectUrls,source:{type:"file",file:i},pagePoint:o,size:r,flushSnapshot:n}),[e,t,n]),replaceSelectedImage:Xf(i=>If({editor:e,file:i,imageObjectUrls:t.objectUrls,flushSnapshot:n}),[e,t,n])}))({editor:e,imageAssetService:n,flushSnapshot:i});return Vf(()=>{if(t)return t.register({openInsertFilePicker(){o.current?.click()},openReplaceFilePicker(){r.current?.click()}})},[t]),Vf(()=>{const t=t=>{if(e.shapeEditingStateSignal.get().session)return;if(xr(t.target))return;const n=uf(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=uf(t.dataTransfer);n&&(t.preventDefault(),s({file:n,pagePoint:hf(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]),nm(em,{children:[tm("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})}}),tm("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)}})]})}),fw=Mg("plugin-image.asset-service"),mw={id:"plugin-image.product-controller"},Sw=class{handlers=null;register(e){return this.handlers=e,()=>{this.handlers===e&&(this.handlers=null)}}openInsertFilePicker(){this.handlers?.openInsertFilePicker()}openReplaceFilePicker(){this.handlers?.openReplaceFilePicker()}},yw=Mg("plugin-image.toolbar-host-bridge"),bw=Yf(({editor:e,pluginHostRuntime:t})=>((({editor:e,pluginHostRuntime:t})=>{Vf(()=>{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=xg({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)),xw="system.selection.delete",Iw="system.selection.duplicate",vw="system.selection.group",ww="system.selection.select-all",Pw="system.selection.ungroup",kw="system.selection.reset-rotation",Cw="system.selection.flip-horizontal",Tw="system.selection.flip-vertical",Ew="system.selection.send-to-back",Mw="system.selection.send-backward",Bw="system.selection.bring-forward",Rw="system.selection.bring-to-front",Aw="system.selection.set-opacity",Lw=[{actionId:Iw,shortcut:{key:"d",accelKey:!0}},{actionId:ww,shortcut:{key:"a",accelKey:!0}},{actionId:vw,shortcut:{key:"g",accelKey:!0}},{actionId:Pw,shortcut:{key:"g",accelKey:!0,shiftKey:!0}}],Fw=[{id:Iw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.duplicateSelection({source:"user"})}},{id:ww,isEnabled:e=>e.editor.getCurrentPageShapeIds().length>0,run({context:e}){e.editor.selectAllCurrentPage("user")}},{id:vw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.editor.canGroupSelection(),run({context:e}){e.editor.groupSelection("user")}},{id:Pw,isVisible:e=>e.editor.canUngroupSelection(),isEnabled:e=>e.editor.canUngroupSelection(),run({context:e}){e.editor.ungroupSelection("user")}},{id:kw,isVisible:e=>e.selection.canResetRotation,run({context:e}){e.editor.resetSelectionRotation("user")}},{id:Cw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("horizontal","user")}},{id:Tw,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("vertical","user")}},{id:Ew,isVisible:e=>e.selection.count>0&&!zf(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("back","user")}},{id:Mw,isVisible:e=>e.selection.count>0&&!zf(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionInParentOrder("backward","user")}},{id:Bw,isVisible:e=>e.selection.count>0&&!zf(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionInParentOrder("forward","user")}},{id:Rw,isVisible:e=>e.selection.count>0&&!zf(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("front","user")}},{id:Aw,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=_f(t.opacity);return e.selection.selectedShapes.every(e=>_f(e.opacity)===n)?n:null})(e),run({context:e,value:t}){if("number"!=typeof t||!Number.isFinite(t))return;const n=_f(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:xw,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.deleteSelection("user")}}],$w=[{id:"system.selection-context-menu",target:"selection",order:1010,actionIds:[Iw,vw,Pw,kw,Cw,Tw,Rw,Bw,Mw,Ew,xw],getSections(e){const t=e.selection.count>0&&!zf(e),n=[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:Iw,actionId:Iw,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(Iw),dataUi:"context-menu-duplicate-selection-button"},{kind:"separator",id:"system.selection-clipboard-separator"},{kind:"command",id:vw,actionId:vw,label:"Group",icon:"group",dataUi:"context-menu-group-selection-button"},{kind:"command",id:Pw,actionId:Pw,label:"Ungroup",icon:"ungroup",dataUi:"context-menu-ungroup-selection-button"},{kind:"command",id:xw,actionId:xw,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:kw,actionId:kw,label:"Reset rotation",icon:"rotate-ccw",dataUi:"context-menu-reset-rotation-button"},{kind:"command",id:Cw,actionId:Cw,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"context-menu-flip-horizontal-button"},{kind:"command",id:Tw,actionId:Tw,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:Rw,actionId:Rw,label:"Bring to front",icon:"chevrons-up",dataUi:"context-menu-bring-to-front-button"},{kind:"command",id:Bw,actionId:Bw,label:"Bring forward",icon:"move-up",dataUi:"context-menu-bring-forward-button"},{kind:"command",id:Mw,actionId:Mw,label:"Send backward",icon:"move-down",dataUi:"context-menu-send-backward-button"},{kind:"command",id:Ew,actionId:Ew,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:[ww],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:ww,actionId:ww,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(ww),dataUi:"context-menu-select-all-button"}]}]}],Uw=[{id:"system.selection-toolbar",surface:"selection",order:1e3,actionIds:[kw,Cw,Tw,Ew,Mw,Bw,Rw,Aw,vw,Pw,xw],getGroups(e){const t=e.selection.count>0&&!zf(e);return[{id:"system.selection-opacity",items:[{kind:"slider",id:"system.selection-opacity",actionId:Aw,label:"Opacity",min:0,max:1,step:.01,dataUi:"selection-opacity-slider"}]},{id:"system.selection-actions",items:[...e.selection.canResetRotation?[{kind:"button",id:kw,actionId:kw,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:Cw,actionId:Cw,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"flip-selection-horizontal-button"},{kind:"button",id:Tw,actionId:Tw,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"flip-selection-vertical-button"},{kind:"separator",id:"system.selection.flip-order-separator"},...t?[{kind:"button",id:Ew,actionId:Ew,label:"Send to back",icon:"chevrons-down",dataUi:"send-selection-to-back-button"},{kind:"button",id:Mw,actionId:Mw,label:"Send backward",icon:"move-down",dataUi:"send-selection-backward-button"},{kind:"button",id:Bw,actionId:Bw,label:"Bring forward",icon:"move-up",dataUi:"bring-selection-forward-button"},{kind:"button",id:Rw,actionId:Rw,label:"Bring to front",icon:"chevrons-up",dataUi:"bring-selection-to-front-button"},{kind:"separator",id:"system.selection.order-delete-separator"}]:[],{kind:"button",id:vw,actionId:vw,label:"Group",icon:"group",dataUi:"group-selection-button"},{kind:"button",id:Pw,actionId:Pw,label:"Ungroup",icon:"ungroup",dataUi:"ungroup-selection-button"},{kind:"separator",id:"system.selection.group-delete-separator"},{kind:"button",id:xw,actionId:xw,label:"Delete selection",icon:"trash-2",dataUi:"delete-selection-toolbar-button"}]}]}}],Dw=[{id:WS,getValue:e=>e.tool.activeToolId,run({context:e,value:t}){"string"==typeof t&&e.editor.tools.hasTool(t)&&e.editor.setActiveTool(t,"system")}},{id:YS,getValue:e=>e.tool.isToolLocked,run({context:e}){e.editor.toggleToolLocked("system")}}],zw=[{id:"system.canvas-tool-context-menu",target:"canvas",order:1020,actionIds:[WS],getSections:e=>[{id:"system.canvas-tools",title:"Tools",order:20,items:[{kind:"command",id:"system.canvas.select-tool",actionId:WS,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:WS,value:"hand",label:"Hand tool",icon:"hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),dataUi:"context-menu-hand-tool-button"}]}]}],_w=[{id:"system.select-tool-toolbar",surface:"tool",placement:"chrome",order:0,actionIds:[WS],getGroups:e=>[{id:"system.select-tool",items:[{kind:"button",id:"system.select-tool",actionId:WS,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:WS,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:[YS],getGroups:e=>[{id:"system.tool-lock",items:[{kind:"separator",id:"system.tool-lock-separator"},{kind:"button",id:"system.tool-lock",actionId:YS,value:!0,label:e.tool.isToolLocked?"Unlock tool":"Lock tool",icon:"lock",dataUi:"tool-lock-button"}]}]}],Hw="system.view.zoom-in",Nw="system.view.zoom-out",Ow="system.view.reset-zoom",Ww=[{id:Hw,run({context:e}){e.editor.zoomAtViewportCenter(-120,"system")}},{id:Nw,run({context:e}){e.editor.zoomAtViewportCenter(120,"system")}},{id:Ow,run({context:e}){e.editor.resetZoom("user")}}],Yw=[{id:"system.canvas-view-context-menu",target:"canvas",order:1010,actionIds:[Hw,Nw,Ow],getSections:()=>[{id:"system.canvas-view",title:"View",order:10,items:[{kind:"command",id:Hw,actionId:Hw,label:"Zoom in",icon:"plus",dataUi:"context-menu-zoom-in-button"},{kind:"command",id:Nw,actionId:Nw,label:"Zoom out",icon:"minus",dataUi:"context-menu-zoom-out-button"},{kind:"command",id:Ow,actionId:Ow,label:"Reset zoom",icon:"rotate-ccw",dataUi:"context-menu-reset-zoom-button"}]}]}],Xw=Symbol("CanvasKitProduct");export{Gv as CANVAS_KIT_TOOL_IDS,ta as CanvasKitFloatingToolbarLayer,Ug as CanvasKitRoot,Sy as DEFAULT_TEXT_FONT,oa as FloatingSelectionToolbarPageSpace,yy as HOST_TEXT_FONT,yg as createCanvasKitController,bg as createCanvasKitControllerWithTools,b as createCustomShapeColor,qo as createDefaultTextExtensionOptions,jo as createDefaultTextFontCatalog,y as createThemeShapeColor,Hf as defineCanvasKit,w as getThemeColorTokenName,mw as imageProductControllerToken,I as isCustomShapeColorRef,x as isThemeShapeColorRef,C as resolveShapeColor,k as shapeColorToCssColor,aa as useCanvasKitLayerTree,ia as useCanvasKitWheelCapture};
1
+ function e(){return kI}function t(){return++kI}function n(e){if(CI)return void e();const t={initialAtomValues:new Map};CI=t;try{e(),s(t.initialAtomValues.keys())}catch(n){for(const[e,i]of t.initialAtomValues)e.__unsafe__setWithoutNotify(i);throw n}finally{CI=null}}function i(e){TI={child:e,parentSet:new Set,below:TI}}function o(){if(!TI)throw new Error("Cannot stop dependency capture because no capture is active");const e=TI;return TI=e.below,e.parentSet}function r(e){TI&&(TI.parentSet.add(e),e.children.add(TI.child))}function s(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 a(e,t,n){return new MI(e,t,n?.isEqual)}function l(e,t,n){return new BI(e,t,n?.isEqual)}function d(e){return{id:e}}function c(e={}){return{id:UI,typeName:"document",scope:"document",meta:{...e}}}function u(){return{id:zI,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function h(e=zI){return{id:OI,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...XI}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function p(e){return!!e&&"page"===e.typeName}function g(e){return!!e&&"document"===e.typeName}function f(e){return!!e&&"shape"===e.typeName}function m(e){return!!e&&"session"===e.typeName}function y(e){return!!e&&"binding"===e.typeName}function S(e){return!!e&&"asset"===e.typeName}function b(e){return"document"===e.scope}function x(e,t,n){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 $I(e.x+i.x*s,e.y+i.y*s)})(t,n,e))}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!1;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1}function w(e,t,n,i){return I(e,t,n,i)?0:Math.min(x(e,n,i),x(t,n,i),x(n,e,t),x(i,e,t))}function P(e){return e.length>=3&&e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y))}function v(e){const t=e.filter(P).flatMap(e=>e);return t.length>0?LI.FromPoints(t):null}function k(e,t){if(!P(t))return!1;let n=!1;for(let i=0;i<t.length;i+=1){const o=t[i],r=t[(i+t.length-1)%t.length];if(x(e,r,o)<=1e-8)return!0;o.y>e.y!=r.y>e.y&&e.x<(r.x-o.x)*(e.y-o.y)/(r.y-o.y)+o.x&&(n=!n)}return n}function C(e,t){return t.some(t=>k(e,t))}function T(e,t,n,i=0){if(!P(n))return!1;if(k(e,n)||k(t,n))return!0;for(let o=0;o<n.length;o+=1)if(w(e,t,n[o],n[(o+1)%n.length])<=Math.max(0,i))return!0;return!1}function M(e){return{kind:"theme",slot:e}}function E(e){return{kind:"custom",value:e}}function B(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&YI.includes(e.slot)}function A(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function R(e){return B(e)||A(e)}function $(e){return _I[e]}function L(e,t){return R(e)?e:t}function F(e){return"custom"===e.kind?e.value:`var(${$(e.slot)}, ${HI[e.slot]})`}function D(e,t){if("custom"===e.kind)return e.value;const n=$(e.slot),i=HI[e.slot];return t?.(n,i)??i}function U(e){return"custom"===e.kind&&"transparent"===e.value.trim().toLowerCase()}function z(e,t){return e===t||!(!e||!t)&&e.kind===t.kind&&("theme"===e.kind?e.slot===t.slot:e.value===t.value)}function O(e,t,n){const i=new Set;let o=n.parentId;for(;o.startsWith("shape:");){const n=o;if(n===t)return!0;if(i.has(n))return!1;i.add(n);const r=e.getShape(n);if(!r)return!1;o=r.parentId}return!1}function X(e,t,n){let i=e.computeShapeExportPageBounds(t);if(!V(i))return i;for(const o of((e,t,n)=>{const i=[];for(const o of N(e,t,n)){const t=_(e,o);t&&V(t)&&i.push(t)}return i})(e,t,n)){const e=W(i,o);if(!e)return null;i=e}return i}function N(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 Y(e,t,n,i){if(n.has(t.id))return n.get(t.id)??null;const o=e.getShapeUtil(t),r=o.getChildExportClipLocalPolygons(t);if(!r||!v(r))return n.set(t.id,null),null;const s=e.computeShapeExportToPageTransform(t).toSvgString(),a=o.getChildExportClipLocalBounds(t),[l]=r,d=1===r.length&&l&&a&&((e,t)=>{const n=[new $I(t.minX,t.minY),new $I(t.maxX,t.minY),new $I(t.maxX,t.maxY),new $I(t.minX,t.maxY)];return e.length===n.length&&e.every((e,t)=>e.equals(n[t]))})(l,a)?[{tag:"rect",attrs:{x:a.x,y:a.y,width:a.w,height:a.h,transform:s}}]:r.map(e=>({tag:"path",attrs:{d:H(e),transform:s}})),c=i.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:d});return n.set(t.id,c),c}function _(e,t){const n=e.getShapeUtil(t).getChildExportClipLocalPolygons(t);if(!n||!v(n))return null;const i=e.computeShapeExportToPageTransform(t);return v(n.map(e=>e.map(e=>i.applyToPoint(e))))}function H(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).concat("Z").join(" ")}function W(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 LI(n,i,o-n,r-i)}function K(e){if("string"==typeof e)return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");const t=(e=>{const t=[];for(const[n,i]of Object.entries(e))null!=i&&!1!==i&&t.push(`${n}="${q("number"==typeof i?j(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(K).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function V(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 q(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function j(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function G(e){return e[KI]}function Z({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?(Q(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 G(e).getAll().filter(y)){if(!s.has(c.fromId)&&!s.has(c.toId))continue;const t=e.getShape(c.fromId),n=e.getShape(c.toId);t&&n?e.bindings.canBind(c)?(e.bindings.getConflictingBindings(c).some(e=>a.has(e.id))&&r.push({kind:"duplicate-exclusive-binding",id:c.id,canRepair:!0}),a.add(c.id)):r.push({kind:"invalid-binding",id:c.id,canRepair:!0}):r.push({kind:"missing-binding-endpoint",id:c.id,canRepair:!0})}const l=r.filter(e=>e.canRepair).length,d=r.length-l;return{requestedShapeIds:i,issues:r,repairableIssueCount:l,fatalIssueCount:d,canExport:0===d}}function Q(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 J(e){return e.added.length>0||e.updated.length>0||e.removed.length>0}function ee(e){return e instanceof Map?new Map(e):new Map(Array.from(e,e=>[e.id,e]))}function te(e,t){const n=ee(e),i=ee(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 ne(e){return{added:[...e.removed],updated:e.updated.map(e=>({before:e.after,after:e.before})),removed:[...e.added]}}function ie(e,t){const n=new Map,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 oe(e,t){return{id:e.id,forward:ie(e.forward,t),parentIds:e.parentIds}}function re(e,t){return{forward:t,inverse:ne(t),label:e}}function se(e){return void 0!==e&&e<0?-1:1}function ae(e,t){if(void 0===t)return e;const n=2*Math.PI;return e+Math.round((t-e)/n)*n}function le(e,t){const n=2*Math.PI,i=((e-t+Math.PI)%n+n)%n-Math.PI;return Math.abs(i)}function de(e,t,n={}){if(!(e=>[e.a,e.b,e.c,e.d,e.e,e.f].every(Number.isFinite))(e)||![t.x,t.y,t.w,t.h].every(Number.isFinite))return null;const i=Number.isFinite(n.epsilon)?Math.max(0,n.epsilon??0):1e-8,o=Math.hypot(e.a,e.b),r=Math.hypot(e.c,e.d),s=e.determinant(),a=({rotation:n,skewX:i,scaleX:o,scaleY:r})=>{const s=t.center,a=e.applyToPoint(s),l={x:a.x-s.x,y:a.y-s.y,rotation:n,skewX:i,scaleX:o,scaleY:r};return Object.values(l).every(Number.isFinite)?l:null},l=i*Math.max(1,o,r),d=o<=l,c=r<=l;if(d||c){if(d&&c)return a({rotation:n.preferredRotation??0,skewX:0,scaleX:0,scaleY:0});if(d){const t=r*se(n.preferredScaleYSign);return a({rotation:ae(Math.atan2(-e.c/t,e.d/t),n.preferredRotation),skewX:0,scaleX:0,scaleY:t})}const t=o*se(n.preferredScaleXSign);return a({rotation:ae(Math.atan2(e.b/t,e.a/t),n.preferredRotation),skewX:0,scaleX:t,scaleY:0})}if(Math.abs(s)<=i*o*r)return null;const u=Math.atan2(e.b,e.a),h=Math.cos(u),p=Math.sin(u),g=h*e.a+p*e.b,f=-p*e.c+h*e.d,m=Math.atan((h*e.c+p*e.d)/f),y=[{rotation:ae(u,n.preferredRotation),scaleX:g,scaleY:f},{rotation:ae(u+Math.PI,n.preferredRotation),scaleX:-g,scaleY:-f}],S=se(n.preferredScaleXSign),b=se(n.preferredScaleYSign),x=e=>{let t=0;return void 0!==n.preferredScaleXSign&&se(e.scaleX)===S&&(t+=1),void 0!==n.preferredScaleYSign&&se(e.scaleY)===b&&(t+=1),{signMatches:t,rotationDistance:void 0===n.preferredRotation?0:le(e.rotation,n.preferredRotation)}},I=x(y[0]),w=x(y[1]),P=w.signMatches>I.signMatches||w.signMatches===I.signMatches&&w.rotationDistance<I.rotationDistance?y[1]:y[0];return((e,t,n,i,o,r)=>{const s=Math.cos(t),a=Math.sin(t),l=Math.tan(n),d=[s*i,a*i,(s*l-a)*o,(a*l+s)*o],c=[e.a,e.b,e.c,e.d],u=r*Math.max(1,...c.map(e=>Math.abs(e)));return c.every((e,t)=>Math.abs(e-(d[t]??e))<=u)})(e,P.rotation,m,P.scaleX,P.scaleY,i)?a({rotation:P.rotation,skewX:m,scaleX:P.scaleX,scaleY:P.scaleY}):null}function ce(e,t){return t.getExportBounds(e)}function ue(e,t,n=FI.Identity()){return n.compose(t.getLocalToPageTransform(e))}function he(e,t,n=FI.Identity()){const i=t.getLocalBounds(e).center,o=new $I(e.x+i.x,e.y+i.y),r=FI.Translate(o.x,o.y).compose(FI.Rotate(e.rotation)).compose(FI.SkewX(e.skewX)).compose(FI.Scale(e.scaleX,e.scaleY)).compose(FI.Translate(-o.x,-o.y));return n.compose(r)}function pe(e,t,n=FI.Identity()){return ue(e,t,n)}function ge(e,t,n=FI.Identity()){return ue(e,t,n).applyToPoint(t.getLocalBounds(e).center)}function fe(e,t,n,i=FI.Identity()){const o=he(e,n,i).tryInvert();if(o)return o.applyToPoint(t);const r=n.getLocalBounds(e).center,s=new $I(e.x+r.x,e.y+r.y),a=i.tryInvert();if(!a)return s;const l=a.applyToPoint(t).sub(s).rot(-e.rotation),d=Math.tan(e.skewX);return s.add(new $I(0===e.scaleX?0:(l.x-d*l.y)/e.scaleX,0===e.scaleY?0:l.y/e.scaleY))}function me(e,t,n=FI.Identity()){const i=he(e,t,n);return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(e=>i.applyToPoint(e))}function ye(e,t,n=FI.Identity()){const i=me(e,t,n),o=((e,t,n=FI.Identity())=>{const i=t.getLocalBounds(e),o=ue(e,t,n);return[new $I(i.minX,i.minY),new $I(i.maxX,i.minY),new $I(i.maxX,i.maxY),new $I(i.minX,i.maxY)].map(e=>o.applyToPoint(e))})(e,t,n);return{bounds:LI.FromPoints(i),center:ge(e,t,n),corners:o,outlineVertices:i}}function Se(e,t,n){const i=n.startsWith("shape:")?e.getShape(n):null,o=(i?e.computeShapeLocalToPageTransform(i):FI.Identity()).tryInvert();if(!o)return null;const r=e.computeShapeLocalToPageTransform(t);return de(o.compose(r),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})}function be(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function xe(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 Ie(e,t,n){const i=n?.source??"user";G(e).atomic(()=>{const o=[],r=[];for(const n of t){const t=e.getShape(n.id);if(!t)continue;const i=n.x??t.x,s=n.y??t.y,a=n.rotation??t.rotation,l=n.skewX??t.skewX,d=n.scaleX??t.scaleX,c=n.scaleY??t.scaleY,u=void 0===n.opacity?t.opacity:ke(n.opacity,t.opacity),h=n.isHidden??t.isHidden,p=n.isLocked??t.isLocked,g=n.parentId??t.parentId,f=n.index??t.index,m=void 0===n.meta?t.meta:{...n.meta};if(!n.props&&void 0===n.meta&&i===t.x&&s===t.y&&a===t.rotation&&l===t.skewX&&d===t.scaleX&&c===t.scaleY&&u===t.opacity&&h===t.isHidden&&p===t.isLocked&&g===t.parentId&&f===t.index)continue;const y=e.shapeUtils.get(t.type),S={...t,x:i,y:s,rotation:a,skewX:l,scaleX:d,scaleY:c,opacity:u,isHidden:h,isLocked:p,parentId:g,index:f,props:n.props?y.validateProps({...t.props,...n.props}):t.props,meta:m};o.push(S),r.push({before:t,after:S})}0!==o.length&&(we(e,o),G(e).put(o,i),r.some(({before:e,after:t})=>e.parentId!==t.parentId)&&Pe(e,i),e.bindings.handleShapeChanges(r,i,n?.skipBindingIds?{skipBindingIds:n.skipBindingIds}:void 0),((e,t,n)=>{const i=new Set,o=new Set;for(const s of t)Ee(e,s.before,i),Ee(e,s.after,i),s.before.parentId!==s.after.parentId&&s.before.parentId.startsWith("shape:")&&o.add(s.before.parentId),e.getShapeUtil(s.after).shouldResizeDescendants(s.after)&&i.add(s.after.id);const r=new Set;Ae(e,o,r,n),Ce(e,i,n,r)})(e,r,i))},i)}function we(e,t){const n=new Set;for(const o of t){if(n.has(o.id))throw new Error(`Duplicate shape id ${o.id}`);n.add(o.id)}const i=new Map(G(e).getAll().filter(f).map(e=>[e.id,e]));for(const o of t)i.set(o.id,o);for(const o of t){const t=new Set([o.id]);let n=o;for(;n.parentId.startsWith("shape:");){const r=n.parentId;if(t.has(r))throw new Error(`Shape parent cycle includes ${o.id}`);t.add(r);const s=i.get(r);if(!s)throw new Error(`Missing parent ${r} for shape ${n.id}`);if(!e.getShapeUtil(s).canReceiveChild(s,n))throw new Error(`Shape ${r} cannot receive shape ${n.id}`);n=s}if(!e.getPage(n.parentId))throw new Error(`Missing page parent ${n.parentId} for shape ${n.id}`)}}function Pe(e,t){const n=e.getSessionRecord();let i=!1;const o={};for(const[r,s]of Object.entries(n.pageSelectedShapeIdsById)){const t=r,n=s??[],a=Array.from(new Set(n)).filter(n=>ve(e,n)===t&&!e.isShapeHidden(n)),l=new Set(a),d=a.filter(t=>{let n=e.getShape(t);const i=new Set([t]);for(;n?.parentId.startsWith("shape:");){const t=n.parentId;if(i.has(t))return!0;if(l.has(t))return!1;i.add(t),n=e.getShape(t)}return!0});o[t]=d,d.length!==n.length&&(i=!0)}i&&e.updateSession({pageSelectedShapeIdsById:o},t)}function ve(e,t){let n=e.getShape(t);const i=new Set;for(;n?.parentId.startsWith("shape:");){const t=n.parentId;if(i.has(t))return null;i.add(t),n=e.getShape(t)}return n&&e.getPage(n.parentId)?n.parentId:null}function ke(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Ce(e,t,n,i=new Set){const o=[...t].sort((t,n)=>Te(e,n)-Te(e,t));for(const r of o){if(i.has(r))continue;const t=e.getShape(r);if(!t)continue;const o=e.getShapeUtil(t);if(!o.shouldResizeDescendants(t))continue;const s=Me(e,t.id);if(0===s.length)continue;const a=s.flatMap(t=>e.getShapeUtil(t).getPositionedOutlineVertices(t).map(n=>he(t,e.getShapeUtil(t)).applyToPoint(n)));if(0===a.length)continue;const l=LI.FromPoints(a),d=o.getResizeToFitDescendantsProps(t,l);if(!d)continue;const c=o.validateProps(d),u={...t,props:c},h=de(o.getLocalToPageTransform(t).compose(FI.Translate(l.x,l.y)),o.getLocalBounds(u),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(!h)continue;const p=[...s.map(e=>({before:e,after:{...e,x:e.x-l.x,y:e.y-l.y}})),{before:t,after:{...t,...h,props:c}}].filter(({before:e,after:t})=>{return!((n=e).x===(i=t).x&&n.y===i.y&&n.rotation===i.rotation&&n.skewX===i.skewX&&n.scaleX===i.scaleX&&n.scaleY===i.scaleY&&((e,t)=>{if(e===t)return!0;const n=Object.entries(e),i=Object.entries(t);return n.length===i.length&&n.every(([e,n])=>Object.is(n,t[e]))})(n.props,i.props));var n,i});0!==p.length&&(G(e).put(p.map(e=>e.after),n),e.bindings.handleShapeChanges(p,n))}}function Te(e,t){let n=0,i=e.getShape(t);const o=new Set;for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(o.has(t))break;o.add(t),n+=1,i=e.getShape(t)}return n}function Me(e,t){return G(e).getAll().filter(f).filter(e=>e.parentId===t).sort((e,t)=>e.index.localeCompare(t.index))}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).shouldResizeDescendants(t)&&n.add(t.id),o=t.parentId}}function Be(e,t){const n=new Set;for(const i of t){const t=e.getShape(i);t&&Ee(e,t,n)}return n}function Ae(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);if(!a)continue;const l=e.getShapeUtil(a).getMinimumChildCount(a);if(l<=0)continue;const d=Me(e,a.id).filter(e=>!n.has(e.id)),c=new Set(d.map(e=>e.id));if(new Set(d.map(t=>{const n=e.bindings.getShapeHierarchyRootId(t.id);return c.has(n)?n:t.id})).size>=l)continue;const u=Me(e,a.parentId).filter(e=>!n.has(e.id)).flatMap(e=>e.id===a.id?d.map(e=>e.id):[e.id]),h=new Map(u.map((t,n)=>[t,e.createShapeIndex(n+1)])),p=[];let g=!0;for(const n of d){if(!e.canUseShapeParent(a.parentId,n.id)){g=!1;break}const t=Se(e,n,a.parentId);if(!t){g=!1;break}p.push({before:n,after:{...n,...t,parentId:a.parentId,index:h.get(n.id)??a.index}})}if(!g)continue;const f=new Set;Ee(e,a,f);for(const e of f)r.push(e);const m=new Set(p.map(e=>e.after.id)),y=u.flatMap(t=>{if(m.has(t))return[];const n=e.getShape(t),i=h.get(t);return n&&i&&n.index!==i?[{before:n,after:{...n,index:i}}]:[]}),S=[...p,...y];S.length>0&&(G(e).put(S.map(e=>e.after),i),e.bindings.handleShapeChanges(S,i));const b=e.getSelectedShapeIds();if(b.includes(a.id)){const t=Array.from(new Set(p.map(t=>{const n=e.bindings.getShapeHierarchyRootId(t.after.id);return m.has(n)?n:t.after.id})));e.commands.setSelectedShapeIds(b.flatMap(e=>e===a.id?t:[e]),{source:i})}e.sideEffects.runBeforeDelete("shape",[a.id],i),G(e).remove([a.id],i),e.sideEffects.runAfterDelete("shape",[a.id],i),n.add(a.id),o.push(a.id)}return o}function Re(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=Me(e,t.parentId).reduce((e,t)=>{const n=Number.parseInt(t.index,10);return Number.isFinite(n)?Math.max(e,n):e},0),o=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,r=new Map;for(const s of n){if(!e.canUseShapeParent(t.parentId,s.id))return null;const n=Se(e,s,t.parentId);if(!n)return null;r.set(s.id,n)}return n.map((n,s)=>{const a=o?e.getShapeUtil(o).getChildPlacementMeta(o,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+s+1),...r.get(n.id),meta:a===n.meta?void 0:a}})})(e,t);return!!i&&(0===i.length||Ie(e,i,n),!0)}function $e(e,t,n){const i=n?.source??"user",o=e.getShapeIdsIncludingDescendants(t),r=Be(e,o),s=new Set(o),a=e.getUnreferencedAssetIdsAfterShapeDelete(o);G(e).atomic(()=>{e.sideEffects.runBeforeDelete("shape",o,i),G(e).remove(o,i),a.length>0&&G(e).remove(a,i),Ae(e,r,s,i),Ce(e,r,i,s),e.sideEffects.runAfterDelete("shape",o,i)},i)}function Le(e,t){return e.bindings.canBind(t)}function Fe(e,t,n){for(const i of t){const t=e.getShape(i);t?.parentId.startsWith("shape:")&&n.add(t.parentId)}}function De(e,t,n){const i=[...t].sort((e,t)=>e.id.localeCompare(t.id)),o=new Set([e]);let r=e;for(;;){let t=null;for(const e of i){if(e.fromId!==r&&e.toId!==r)continue;const i=n(e).getShapeHierarchyRootId?.(e,r);if(i&&i!==r){t=i;break}}if(!t)return r;if(o.has(t))return e;o.add(t),r=t}}function Ue({before:e,after:t}){return e.parentId!==t.parentId||e.x!==t.x||e.y!==t.y||e.rotation!==t.rotation||e.skewX!==t.skewX||e.scaleX!==t.scaleX||e.scaleY!==t.scaleY||e.props!==t.props}function ze(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+=1)if(e[n]!==t[n])return!1;return!0}function Xe(e,t){return e.count===t.count&&e.singleShapeType===t.singleShapeType&&e.commonShapeType===t.commonShapeType&&e.hasPointHandleSelection===t.hasPointHandleSelection&&e.hasFrameSelection===t.hasFrameSelection&&e.isMixedFrameAndPointHandleSelection===t.isMixedFrameAndPointHandleSelection&&e.canDragPointHandles===t.canDragPointHandles&&e.hasSelectionRotation===t.hasSelectionRotation&&e.hasMixedSelectionRotation===t.hasMixedSelectionRotation&&e.canResetSelectionRotation===t.canResetSelectionRotation}function 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 Ye(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function _e(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 He(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 We(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 Ke(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 Ve(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 qe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o)return!1;if(i.id!==o.id||i.shape!==o.shape||i.isSelected!==o.isSelected||!_e(i.bounds,o.bounds))return!1}return!0}function je(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 Ze(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)=>Ze(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)&&Ze(n[e],i[e]))}function Qe(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,t)=>{const n=e.getShapeIdsIncludingDescendants(t),i=new Set(n);for(let o=0;o<n.length;o+=1){const t=n[o];if(t)for(const o of e.getBindingsForShape(t)){const t=e.getBindingUtil(o).getExportShapeIds?.(e,o);for(const o of t??[])for(const t of e.getShapeIdsIncludingDescendants([o]))i.has(t)||(i.add(t),n.push(t))}}return n})(e,t),i=new Set(n);return e.getCurrentPageShapeIds().filter(e=>i.has(e))})(e,t),i=new Set(n),o=new Set;for(const d of n){const t=e.getShape(d);if(!(!t||t.parentId.startsWith("shape:")&&i.has(t.parentId)||et(e,t,i))){o.add(t.id);for(const n of e.getDescendantShapeIds(t.id))o.add(n)}}const r=n.filter(e=>!o.has(e)),s=new Set(r),a=r.map(t=>e.getShape(t)).filter(e=>!!e).flatMap(t=>{const n=et(e,t,s);return n?[n]:[]});if(0===a.length)return null;const l=t.filter(e=>s.has(e));return 0===l.length?null:{type:"land/clipboard",version:1,source:{app:"land"},rootShapeIds:l,records:{shapes:a,bindings:tt(e,a,s),assets:nt(e,a)},bounds:it(e,r)}}function Je(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 $I(t.x+t.w/2,t.y+t.h/2)):e.offset??JI})(t),s=new Map,a=new Map,l=[],d=new Set(n.records.shapes.map(e=>e.id)),c=new Set(n.records.shapes.filter(e=>!e.parentId.startsWith("shape:")||!d.has(e.parentId)).map(e=>e.id));G(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=e.createAssetRecord({type:t.type,props:lt(t.props),meta:lt(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)=>at(e,t))(t.props,s),i=c.has(t.id),l=e.createShapeRecord({type:t.type,x:t.x+(i?r.x:0),y:t.y+(i?r.y:0),props:n,parentId:o,rotation:t.rotation,skewX:t.skewX,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,meta:lt(t.meta)});return a.set(t.id,l.id),{original:t,draft:l}}).map(({original:e,draft:t})=>({...t,parentId:ot(e.parentId,a,o)}));l.length>0&&e.commands.createShapesFromRecords(l,{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:lt(o.props),meta:lt(o.meta)},{source:i})}},i);for(const u of n.rootShapeIds){const e=a.get(u);e&&l.push(e)}return l.length>0&&e.commands.setSelectedShapeIds(l,{source:i}),l}function et(e,t,n){const i=dt(t);if(t.parentId.startsWith("shape:")&&n.has(t.parentId))return i;const o=e.computeShapeLocalBounds(t),r=de(e.computeShapeLocalToPageTransform(t),o,{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return r?{...i,parentId:e.getShapePageId(t.id)??i.parentId,...r}:null}function tt(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(dt(t)));return i}function nt(e,t){const n=[],i=new Set;for(const o of t)for(const t of rt(o)){if(i.has(t))continue;const o=e.getAsset(t);o&&(i.add(t),n.push(dt(o)))}return n}function it(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 LI(t,n,i-t,o-n)})(t.map(t=>e.getShapePageBounds(t)).filter(e=>!!e))??new LI(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function ot(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function rt(e){const t=[],n=new Set,i=Ge(e);return i&&(n.add(i),t.push(i)),st(e.props,n,t),t}function st(e,t,n){if(ct(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)st(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))st(i,t,n)}function at(e,t){if(ct(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>at(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[i,o]of Object.entries(e))n[i]=at(o,t);return n}function lt(e){return dt(e)}function dt(e){if(Array.isArray(e))return e.map(dt);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=dt(i);return t}function ct(e){return"string"==typeof e&&e.startsWith("asset:")}function ut(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ht(e,t){return"string"==typeof e?e:t}function pt(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function gt(e,t){return"boolean"==typeof e?e:t}function ft(e){return ut(e)?e:{}}function mt(e){return ut(e)?{x:pt(e.x,XI.x),y:pt(e.y,XI.y),z:Math.min(8,Math.max(.1,pt(e.z,XI.z)))}:null}function yt(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function St(e,t){if(!ut(e))throw new tw(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=pt(n,NaN),o="document"===t?2:1;if(i!==o)throw new tw(`Unsupported ${t} snapshot schema version: expected ${o}, received ${String(n)}`);if(!Array.isArray(e.records))throw new tw(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:i,records:e.records}}function bt(e,t,n){const i=e.find(g)??c(),o=e.filter(e=>"page"===e.typeName),r=e.filter(e=>"shape"===e.typeName),s=e.filter(y),a=e.filter(S),l=(o.length>0?[...o].sort((e,t)=>e.index.localeCompare(t.index)):[u()]).map((e,t)=>({...e,index:String(t+1).padStart(4,"0")})),d=l[0]?.id??"page:default",h=new Set(l.map(e=>e.id)),p=[...r].sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),f=new Map(p.map(e=>[e.id,e])),m=new Map,b=new Set,x=((e,t,n,i)=>{const o=new Map(e.map(e=>[e.id,e])),r=t.filter(e=>{const t=o.get(e.fromId),n=o.get(e.toId);if(!t||!n)return!1;const r=i.get(e.type);return!!r.getShapeHierarchyRootId&&(r.canUseShapeHierarchy?.(e,{fromShape:t,toShape:n})??!1)});let s=!0;for(;s;){s=!1;for(const e of[...o.values()]){const t=n.get(e.type),a=t.getMinimumChildCount(e);if(a<=0)continue;const l=[...o.values()].filter(t=>t.parentId===e.id).sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),d=new Set(l.map(e=>e.id));if(new Set(l.map(e=>{const t=De(e.id,r,e=>i.get(e.type));return d.has(t)?t:e.id})).size>=a)continue;if(0===l.length){o.delete(e.id),s=!0;break}const c=[...o.values()].filter(t=>t.parentId===e.parentId).sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)).flatMap(t=>t.id===e.id?l.map(e=>e.id):[t.id]),u=new Map(c.map((e,t)=>[e,String(t+1).padStart(6,"0")])),h=t.getLocalToPageTransform(e),p=[];for(const i of l){if(e.parentId.startsWith("shape:")&&!xt(o,n,e.parentId,i)){p.length=0;break}const t=n.get(i.type),r=de(h.compose(t.getLocalToPageTransform(i)),t.getLocalBounds(i),{preferredRotation:i.rotation,preferredScaleXSign:i.scaleX,preferredScaleYSign:i.scaleY});if(!r){p.length=0;break}p.push({...i,...r,parentId:e.parentId,index:u.get(i.id)??e.index})}if(p.length===l.length){for(const e of p)o.set(e.id,e);for(const e of c){const t=o.get(e),n=u.get(e);t&&n&&t.index!==n&&o.set(t.id,{...t,index:n})}o.delete(e.id),s=!0;break}}}return e.flatMap(e=>{const t=o.get(e.id);return t?[t]:[]})})(p.map((e,n)=>{const i=(e=>{const n=m.get(e.id);if(n)return n;const i=[{stage:"enter",shape:e}];for(;i.length>0;){const e=i[i.length-1];if("waiting-for-parent"===e.stage){m.set(e.shape.id,e.parent.id),b.delete(e.shape.id),i.pop();continue}const n=e.shape;if(m.has(n.id)){i.pop();continue}if(b.add(n.id),n.parentId.startsWith("page:")){m.set(n.id,h.has(n.parentId)?n.parentId:d),b.delete(n.id),i.pop();continue}const o=f.get(n.parentId);o&&!b.has(o.id)&&t.get(o.type).canReceiveChild(o,n)?(i[i.length-1]={stage:"waiting-for-parent",shape:n,parent:o},m.has(o.id)||i.push({stage:"enter",shape:o})):(m.set(n.id,d),b.delete(n.id),i.pop())}return m.get(e.id)??d})(e),o={...e,parentId:i,index:e.index||String(n+1).padStart(6,"0")};return t.get(o.type).repairLoadedShape(o)??o}),s,t,n),I=new Set(x.map(e=>e.id)),w=s.filter(e=>I.has(e.fromId)&&I.has(e.toId));return[i,...l,...a,...x,...w]}function xt(e,t,n,i){const o=e.get(n);return!!o&&t.get(o.type).canReceiveChild(o,i)}function It(e,t,n){const i=St(e,"document"),o=new Set,r=[];return i.records.forEach((e,i)=>{if(!ut(e))throw new tw("Invalid document record: expected object");if("string"!=typeof e.id)throw new tw("Invalid document record id");if(o.has(e.id))throw new tw(`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 tw(`Unsupported document record type: ${String(e.typeName)}`);r.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new tw("Invalid asset record id");if("string"!=typeof e.type)throw new tw("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:ut(e.props)?e.props:{},meta:ft(e.meta)}})(e))}else r.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new tw("Invalid binding record id");if("string"!=typeof e.type)throw new tw("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new tw(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new tw(`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:ft(e.meta)}})(e,n));else r.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new tw("Invalid shape record id");if("string"!=typeof e.type)throw new tw("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new tw(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:ht(e.index,String(n+1).padStart(6,"0")),x:pt(e.x,0),y:pt(e.y,0),rotation:pt(e.rotation,0),skewX:pt(e.skewX,0),scaleX:pt(e.scaleX,1),scaleY:pt(e.scaleY,1),opacity:Math.min(1,Math.max(0,pt(e.opacity,1))),isHidden:gt(e.isHidden,!1),isLocked:gt(e.isLocked,!1),meta:ft(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 tw("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:ht(e.name,`Page ${t+1}`),index:ht(e.index,String(t+1).padStart(4,"0")),meta:ft(e.meta)}})(e,i));else r.push((e=>{if("document:main"!==e.id)throw new tw("Invalid document metadata record id");return{id:UI,typeName:"document",scope:"document",meta:ft(e.meta)}})(e))}),{schemaVersion:2,records:bt(r,t,n)}}function wt(e){const t=St(e,"session").records[0];if(!ut(t))return{schemaVersion:1,records:[h()]};const n=h(),i="string"==typeof t.currentPageId&&t.currentPageId.startsWith("page:")?t.currentPageId:n.currentPageId,o=(e=>{if(!ut(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,mt(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),r=(e=>{if(!ut(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,yt(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:ht(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:ft(t.meta)}]}}function Pt(){return $I.Zero()}function vt(e,t,n){if(n<=0)return Pt();const i=t.x-e.x,o=t.y-e.y;return 0===i&&0===o?Pt():new $I(i/n,o/n)}function kt(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function Ct(e){return{...e,anchorPagePoint:e.anchorPagePoint.clone(),boundaryPagePoint:e.boundaryPagePoint.clone()}}function Tt(e,t){return e.terminal===t.terminal&&Ye(e.anchorPagePoint,t.anchorPagePoint)&&Ye(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function Mt(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||!Tt(i,o))return!1}return!0}function Et(e,t){return Tt(e,t)&&e.ownerShapeId===t.ownerShapeId&&(e.targetShapeId??null)===(t.targetShapeId??null)}function Bt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function At(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Rt(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 $t(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 Lt(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function Ft(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):Lt(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&&Ft(n,t,r)<0)return o}return e.length})(r,n,i,o),0,n.id),e.set(t,s),!0}function Ut(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 zt(e,t,n){Rt(e,t,n)}function Ot(e){return f(e.before)&&f(e.after)}function Xt(e){return y(e.before)&&y(e.after)}function Nt(e,t){const n=de(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return n?{...t,...n}:null}function Yt(e,t,n,i){const o=e.getShapeUtil(t),r={...n,x:i.x??n.x,y:i.y??n.y,rotation:i.rotation??n.rotation,skewX:i.skewX??n.skewX,scaleX:i.scaleX??n.scaleX,scaleY:i.scaleY??n.scaleY,props:i.props?o.validateProps({...n.props,...i.props}):n.props},s=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,a=(s?e.computeShapeLocalToPageTransform(s):FI.Identity()).tryInvert();if(!a)return null;const l=de(a.compose(o.getLocalToPageTransform(r)),o.getLocalBounds(r),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return l?{id:t.id,...l,props:i.props}:null}function _t(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 Ht(e,t){return _t(e.outlineVertices,t.outlineVertices)&&_e(e.pageBounds,t.pageBounds)&&_e(e.frameBounds,t.frameBounds)&&e.rotation===t.rotation&&Ye(e.rotationCenter,t.rotationCenter)&&Ye(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function Wt(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)<rw?0:t}function Kt(e,t){const n=e.computeShapeLocalToPageTransform(t);return Math.atan2(n.b,n.a)}function Vt(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,l=-1/0,d=-1/0;for(const y of n){const n=e.getShapeSignal(y).get();if(!n)continue;const c=e.getShapeUtil(n),u=Nt(e,n),h=u?c.getSelectionPagePoints(u):null;if(h&&o.push(...h),!c.contributesToSelectionFrame(n,{editor:e}))continue;r.push(n);const p=t(y);if(!p)continue;const g=c.getSelectionFramePositionedOutlineVertices(n,{editor:e}),f=g?(()=>{const t=e.computeShapePositionedToPageTransform(n);return g.map(e=>t.applyToPoint(e))})():p.outlineVertices;i.push(...f);for(const e of f)s=Math.min(s,e.x),a=Math.min(a,e.y),l=Math.max(l,e.x),d=Math.max(d,e.y)}const c=Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(l)&&Number.isFinite(d)?new LI(s,a,l-s,d-a):null,u=!(r.length>0)||function(e,t){if(0===t.length)return!0;const n=t[0],i=Wt(n?Kt(e,n):0);return t.every(t=>{return n=Kt(e,t),o=i,Math.abs(Wt(n)-Wt(o))<rw;var n,o})}(e,r),h=((e,t,n)=>{if(0===t.length||!n)return 0;const i=t[0];return Wt(i?Kt(e,i):0)})(e,r,u),p=((e,t)=>t.some(t=>Math.abs(Wt(Kt(e,t)))>rw))(e,r),g=c?.center??null,f=0===i.length?null:Math.abs(h)<rw||!g?LI.FromPoints(i):LI.FromPoints(i.map(e=>$I.RotWith(e,g,-h))),m=o.length>0?LI.FromPoints(o):null;return{outlineVertices:i,pageBounds:c,frameBounds:f,rotation:h,rotationCenter:g,selectionAnchorPagePoint:f&&g?Math.abs(h)<rw?new $I(f.center.x,f.minY):$I.RotWith(new $I(f.center.x,f.minY),g,h):m?new $I(m.center.x,m.minY):null,hasRotation:p,hasCompatibleRotation:u}}function qt(e,t){return e.length===t.length&&e.every((e,n)=>{const i=t[n];return!!i&&e.id===i.id&&e.parentId===i.parentId&&e.type===i.type})}function jt(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 Gt(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function Zt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!Gt(i,o))return!1}return!0}function Qt(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 Jt(e,t){return e===t||(e&&t?jt(e.bounds,t.bounds)&&Gt(e.center,t.center)&&Zt(e.corners,t.corners)&&Zt(e.outlineVertices,t.outlineVertices):e===t)}function en(e){return e?e.clone():e}function tn(e){return e?e.clone():e}function nn(e){return e?.map(e=>e.clone())}function on(e){return e?new FI(e.a,e.b,e.c,e.d,e.e,e.f):void 0}function rn(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 LI(t,n,i-t,o-n)}function sn(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 LI(n,i,o-n,r-i)}function an(e,t){return t.canAutomaticallyReceiveChildren(e)}function ln(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),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1?l:null}function dn(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new $I(n.minX,n.minY),new $I(n.maxX,n.minY),new $I(n.maxX,n.maxY),new $I(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!==ln(e,t,n,r))return!0}return!1}function cn(e,t){return LI.FromPoints([new $I(e.minX,e.minY),new $I(e.maxX,e.minY),new $I(e.maxX,e.maxY),new $I(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function un(e){return"top_left"===e||"left"===e||"bottom_left"===e}function hn(e){return"top_right"===e||"right"===e||"bottom_right"===e}function pn(e){return"top_left"===e||"top"===e||"top_right"===e}function gn(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function fn({handleId:e,scaleX:t,scaleY:n}){const i=un(e)?t<0?"right":"left":hn(e)?t<0?"left":"right":null,o=pn(e)?n<0?"bottom":"top":gn(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 mn({axis:e,startBounds:t,bounds:n,handleId:i,scale:o,isResizingFromCenter:r}){const s=Math.sign(o??1)||1;return r?s:"x"===e?un(i)?n.minX>=t.maxX?-1:1:hn(i)?n.maxX<=t.minX?-1:1:s:pn(i)?n.minY>=t.maxY?-1:1:gn(i)?n.maxY<=t.minY?-1:1:s}function yn({requestedBounds:e,handleId:t,actualWidth:n,actualHeight:i,scaleX:o,scaleY:r,isResizingFromCenter:s}){return new LI(s?e.center.x-n/2:un(t)?o<0?e.minX:e.maxX-n:hn(t)?o<0?e.maxX-n:e.minX:e.center.x-n/2,s?e.center.y-i/2:pn(t)?r<0?e.minY:e.maxY-i:gn(t)?r<0?e.maxY-i:e.minY:e.center.y-i/2,n,i)}function Sn({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,l=e.h;const d=Math.sign(r??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(o){const e=t.center;return{bounds:new LI(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 LI(d<0?e.minX:e.maxX-a,c<0?e.minY:e.maxY-l,a,l);break;case"top_right":u=new LI(d<0?e.maxX-a:e.minX,c<0?e.minY:e.maxY-l,a,l);break;case"bottom_right":u=new LI(d<0?e.maxX-a:e.minX,c<0?e.maxY-l:e.minY,a,l);break;case"bottom_left":u=new LI(d<0?e.minX:e.maxX-a,c<0?e.maxY-l:e.minY,a,l);break;case"top":u=new LI(t.center.x-a/2,c<0?t.maxY:t.maxY-l,a,l);break;case"right":u=new LI(d<0?t.minX-a:t.minX,t.center.y-l/2,a,l);break;case"bottom":u=new LI(t.center.x-a/2,c<0?t.minY-l:t.minY,a,l);break;case"left":u=new LI(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 bn(e,t){return e.x===t.x&&e.y===t.y}function xn(e){return[new $I(e.minX,e.minY),new $I(e.center.x,e.minY),new $I(e.maxX,e.minY),new $I(e.minX,e.center.y),e.center,new $I(e.maxX,e.center.y),new $I(e.minX,e.maxY),new $I(e.center.x,e.maxY),new $I(e.maxX,e.maxY)]}function In(e,t){return"x"===t?e.x:e.y}function wn(e,t){return"x"===t?e.minX:e.minY}function Pn(e,t){return"x"===t?e.maxX:e.maxY}function vn(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function kn(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Cn(e,t){return null!==kn(e,t)}function Tn(e,t){return new LI(e.x+t.x,e.y+t.y,e.w,e.h)}function Mn(e,t,n){return Tn(e,((e,t)=>"x"===e?new $I(t,0):new $I(0,t))(t,n))}function En(e){return[new $I(e.minX,e.minY),new $I(e.maxX,e.minY),new $I(e.maxX,e.maxY),new $I(e.minX,e.maxY)]}function Bn(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 $I(t.x+i.x*r,t.y+i.y*r))}function An(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 $I(t.x+i.x*r,t.y+i.y*r)}function Rn(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=Bn(e,o,s);a>=i||(i=a,n=An(e,o,s))}return n?{point:n,distanceSquared:i}:null}function $n(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 Ln(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(Fn),n.sort(Fn),{x:t,y:n}}function Fn(e,t){return e.value-t.value||e.point.id.localeCompare(t.point.id)}function Dn(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 Un(e){return e.weight??(e.kind?dw[e.kind]:0)}function zn(e,t){return`points:${e}:${[...t].sort().join("|")}`}function On(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 Xn(e,t,n,i,o={}){const r=o.releaseThreshold??i,s=Math.max(i,r),a=o.switchDistance??0;let l=null,d=null;for(const g of t){const t=In(g,e),a=Dn(n,e,t-s,t+s);o.stats&&(o.stats.candidatePointCount+=a.length);for(const n of a){const s=In(n.point,e)-t,a=Math.abs(s),c={offset:s,distance:a,weight:Un(n),fromPrevious:!1};if(a<=i&&On(c,l,i)&&(l=c),o.previousCandidatePointIds?.has(n.id)&&a<=r){const e={...c,fromPrevious:!0};On(e,d,r)&&(d=e)}}}const c=d&&(!l||l.distance+a>=d.distance)?d:l;if(!c)return null;const u=c.fromPrevious&&c.distance>i?r:i,h=[];for(const g of t){const t=In(g,e),i=Dn(n,e,t-u,t+u);for(const n of i){const i=In(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:zn(e,p),nudge:c.offset,distance:c.distance,weight:c.weight,candidatePointIds:p,pairs:h}:null}function Nn(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new $I(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new $I(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new $I(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new $I(t.minX,t.maxY))}return n}function Yn(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>wn(e.bounds,t)-wn(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 l=Pn(e.bounds,t),d=wn(r.bounds,t);if(d>s+1e-8)break;if(l>=d)continue;const c=kn(vn(e.bounds,t),vn(r.bounds,t));c&&(s=d,o.push({direction:n,startNode:e,endNode:r,length:d-l,breadthIntersection:c}))}}return o}function _n(e,t,n,i){const o=kn(vn(t.bounds,i),vn(n.bounds,i));return o?{direction:e,startNode:t,endNode:n,length:wn(n.bounds,i)-Pn(t.bounds,i),breadthIntersection:o}:null}function Hn(e,t){return[e,t.direction,t.startNode.id,t.endNode.id,t.length.toFixed(8)].join(":")}function Wn(e,t,n,i,o={}){const r=vn(t,e),s=((e,t)=>"x"===t?e.w:e.h)(t,e),a=o.releaseThreshold??i,l=o.switchDistance??0;let d=i+1,c=null,u=null;const h=(e,t,n)=>{const r=Math.abs(e);0!==t.length&&(r<=i&&r<d-1e-8&&(d=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:Mn(t,e,n)});for(const g of n){if(s<=g.length&&Cn(r,g.breadthIntersection)){const n=Pn(g.startNode.bounds,e)+(g.length-s)/2-wn(t,e),i=p(n);h(n,[_n(g.direction,g.startNode,i,e),_n(g.direction,i,g.endNode,e)].filter(e=>null!==e),`${Hn(e,g)}:center`)}const n=Pn(g.endNode.bounds,e)+g.length-wn(t,e),i=p(n);if(Cn(vn(i.bounds,e),g.breadthIntersection)){const t=_n(g.direction,g.endNode,i,e);h(n,t?[g,t]:[],`${Hn(e,g)}:after`)}const o=wn(g.startNode.bounds,e)-g.length-Pn(t,e),a=p(o);if(Cn(vn(a.bounds,e),g.breadthIntersection)){const t=_n(g.direction,a,g.startNode,e);h(o,t?[t,g]:[],`${Hn(e,g)}:before`)}}return u&&(!c||c.distance+l>=u.distance)?u:c}function Kn(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 Vn(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&&bn(e.rotationCenter,t.rotationCenter)&&bn(e.line[0],t.line[0])&&bn(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&bn(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&&bn(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>bn(e.startEdge[0],t.startEdge[0])&&bn(e.startEdge[1],t.startEdge[1])&&bn(e.endEdge[0],t.endEdge[0])&&bn(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function qn(e){return"horizontal"===e.direction?{startEdge:[new $I(e.startNode.bounds.maxX,e.startNode.bounds.minY),new $I(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new $I(e.endNode.bounds.minX,e.endNode.bounds.minY),new $I(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new $I(e.startNode.bounds.minX,e.startNode.bounds.maxY),new $I(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new $I(e.endNode.bounds.minX,e.endNode.bounds.minY),new $I(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function jn(e,t,n,i){const o=$n([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),r=Jn(e,o);return{id:ei(e,r,o),type:"points",axis:e,line:r,points:o,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function Gn(e,t,n,i){return Zn(e,t,n).map(t=>jn(e,t,n,i))}function Zn(e,t,n){const i=new Map;for(const o of t.pairs){const t=In(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 Qn(e,t,n){return"x"===e?[new $I(t,n.minY),new $I(t,n.maxY)]:[new $I(n.minX,t),new $I(n.maxX,t)]}function Jn(e,t){if(0===t.length)return[$I.Zero(),$I.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 $I(n,o),new $I(n,r)]:[new $I(n,o),new $I(i,o)]}function ei(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 ti(e,t,n,i,o,r){return Zn(e,t,n).map(t=>((e,t,n,i,o,r)=>{const s=jn(e,t,n,i),a=t.pairs[0],l=In(a?.selectionPoint.add(n)??o.center,e),d=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=d.get(g.candidateNodeId);t&&c.push(...Qn(e,l,t))}const h=$n([...s.points,...Qn(e,l,o),...c]),p=Jn(e,$n([...Qn(e,l,o),...c]));return{...s,id:ei(e,p,h),line:p,points:h}})(e,t,n,i,o,r))}function ni(e,t,n){const i="x"===e?new $I(n.x,t.y):new $I(t.x,n.y),o=$n([n.clone(),i]),r=Jn(e,o);return{id:ei(e,r,o),type:"points",axis:e,line:r,points:o,rotation:0,rotationCenter:$I.Zero()}}function ii(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new $I(0,n.y):new $I(n.x,0),o=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:Tn(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:Tn(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(qn),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function oi(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 ri(e,t){return 0===t.rotation?e.clone():$I.RotWith(e,t.rotationCenter,-t.rotation)}function si(e,t){return 0===t.rotation?e.clone():$I.RotWith(e,t.rotationCenter,t.rotation)}function ai(e,t){return si(e,t)}function li(e,t,n,i,o){return 0===n?i:i+(e-t)/n*o}function di({point:e,fromBounds:t,toBounds:n}){return new $I(li(e.x,t.minX,t.w,n.minX,n.w),li(e.y,t.minY,t.h,n.minY,n.h))}function ci({axis:e,bounds:t,point:n}){return"horizontal"===e?new $I(t.minX+t.maxX-n.x,n.y):new $I(n.x,t.minY+t.maxY-n.y)}function ui({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new LI(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new LI(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function hi(e){return{point:e.point,kind:e.kind??"custom",weight:e.weight}}function pi(e){const t=e.sourcePointOffsets;return t&&t.length>0?t.map(t=>e.pagePoint.add(t)):[e.pagePoint]}function gi(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&Math.abs(((e,t)=>{let n=(e-t)%Math.PI;return n<=-Math.PI/2&&(n+=Math.PI),n>Math.PI/2&&(n-=Math.PI),n})(e,t))<.001}function fi(e,t,n){return t.every(t=>{const i=e.computeShapeLocalToPageTransform(t);return gi(Math.atan2(i.b,i.a),n)})}function mi(e,t,n,i){const o=1===t.length,r=(s=t.map(t=>e.getShapeUtil(t).getAllowedSelectionResizeModes(t,{editor:e,handleId:n,isOnlyResizeTarget:o})),hw.filter(e=>s.every(t=>t.includes(e))));var s;return i?r:r.filter(e=>"free"!==e)}function yi(e,t,n){if(0===t.length)return[];const i=1===t.length,o=t.map(t=>e.getShapeUtil(t).getSelectionResizeHandleIds(t,{editor:e,isOnlyResizeTarget:i})),r=fi(e,t,n);return cw.filter(n=>o.every(e=>e.includes(n))&&mi(e,t,n,r).length>0)}function Si(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function bi(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 xi(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&&Si(i.startPagePoint,o.startPagePoint)&&Si(i.endPagePoint,o.endPagePoint)&&Si(i.middlePagePoint,o.middlePagePoint)&&Mt(i.bindingSegments,o.bindingSegments)&&i.path===o.path))return!1}return!0}function Ii(e,t){return e===t||(e&&t?bi(e.bounds,t.bounds)&&e.rotation===t.rotation&&Si(e.rotationCenter,t.rotationCenter)&&e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius:e===t)}function wi(e,t){return e===t||(e&&t?bi(e.bounds,t.bounds)&&e.rotation===t.rotation&&Si(e.rotationCenter,t.rotationCenter):e===t)}function Pi(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!wi(e[n]??null,t[n]??null))return!1;return!0}function vi(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function ki(e,t){return e.id===t.id&&Si(e.point,t.point)&&bi(e.bounds,t.bounds)}function Ci(e,t){return e.id===t.id&&Si(e.point,t.point)&&bi(e.bounds,t.bounds)}function Ti(e,t){return e.terminal===t.terminal&&Si(e.point,t.point)&&bi(e.bounds,t.bounds)}function Mi(e,t){return Si(e.point,t.point)&&bi(e.bounds,t.bounds)}function Ei(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Si(e.point,t.point)&&bi(e.bounds,t.bounds)}function Bi(e,t){return e.id===t.id&&Si(e.point,t.point)}function Ai(e,t){return e.id===t.id&&Si(e.point,t.point)}function Ri(e,t){return e.terminal===t.terminal&&Si(e.point,t.point)}function $i(e,t){return Si(e.point,t.point)}function Li(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Si(e.point,t.point)}function Fi(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 Di({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 $I(e.maxX+t,e.minY-t):new $I(e.minX-t,e.maxY+t)}function Ui(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&Fi(e.resizeHandles,t.resizeHandles,ki)&&Fi(e.rotateHandles,t.rotateHandles,Ci)&&Fi(e.terminalHandles,t.terminalHandles,Ti)&&Fi(e.middleHandles,t.middleHandles,Mi)&&Fi(e.customHandles,t.customHandles,Ei):e===t)}function zi(e,t){return e===t||(e&&t?Fi(e.resizeHandleAnchors,t.resizeHandleAnchors,Bi)&&Fi(e.rotateHandleAnchors,t.rotateHandleAnchors,Ai)&&Fi(e.terminalHandleAnchors,t.terminalHandleAnchors,Ri)&&Fi(e.middleHandleAnchors,t.middleHandleAnchors,$i)&&Fi(e.customHandleAnchors,t.customHandleAnchors,Li):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 Xi(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function Ni(e,t,n,i,o,r,s){const a=e.map(e=>i(e)),l=e.every(e=>o(e)),d=e.every(e=>r(e)),c=new Set(s),u=a.flatMap(e=>e.terminalHandleAnchors),h=a.flatMap(e=>e.middleHandleAnchors),p=a.flatMap(e=>e.customHandleAnchors??[]),g=u.length>0||h.length>0||p.length>0;if(!t)return{resizeHandleAnchors:[],rotateHandleAnchors:[],terminalHandleAnchors:u,middleHandleAnchors:h,customHandleAnchors:p};const{bounds:f,rotation:m,rotationCenter:y,hasCompatibleRotation:S}=t,b=e[0]?.rotation??m,x=8/n,I=14/n,w=f.w<2*x,P=f.h<2*x,v=e=>0===m?e:$I.RotWith(e,y,m),k=new $I(f.minX,f.minY),C=new $I(f.center.x,f.minY),T=new $I(f.maxX,f.minY),M=new $I(f.maxX,f.center.y),E=new $I(f.maxX,f.maxY),B=new $I(f.center.x,f.maxY),A=new $I(f.minX,f.maxY),R=new $I(f.minX,f.center.y);return{resizeHandleAnchors:l&&!g&&S?[{kind:"resize",id:"top_left",point:v(k)},...w?[]:[{kind:"resize",id:"top",point:v(C)}],...w&&P?[]:[{kind:"resize",id:"top_right",point:v(T)}],...P?[]:[{kind:"resize",id:"right",point:v(M)}],...w||P?[]:[{kind:"resize",id:"bottom_right",point:v(E)}],...w?[]:[{kind:"resize",id:"bottom",point:v(B)}],...w||P?[]:[{kind:"resize",id:"bottom_left",point:v(A)}],...P?[]:[{kind:"resize",id:"left",point:v(R)}]].filter(e=>c.has(e.id)):[],rotateHandleAnchors:!d||g||!S||w||P?[]:[{kind:"rotate",id:"bottom_left_rotate",point:v(Di({bounds:f,rotateOffset:I,referenceRotation:b,frameRotation:m}))}],terminalHandleAnchors:u,middleHandleAnchors:h,customHandleAnchors:p}}function Yi(e,t){const n=8/t,i=n/2,o=e=>new LI(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 _i(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 Hi(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 Wi(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 Ki(e,t,n,i="user"){const o=Wi(e,t);if(!o)return!1;const r=e.getChildShapes(o.parentId),s=new Set(t),a=[...r];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 Vi(e,t,n,i="user"){const o=Wi(e,t);if(!o)return!1;const r=e.getChildShapes(o.parentId),s=new Set(t),a=[],l=[];for(const c of r)s.has(c.id)?a.push(c):l.push(c);if(a.length!==s.size)return!1;if(!("back"===n?o.canMoveBackward:o.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 qi(e){const t="string"==typeof e?{key:e}:e;return{key:Zi(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}}function ji(e){const t=qi(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 Gi(e,t){return!(Zi(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 Zi(e){return e.toLowerCase()}function Qi(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 Ji(e,t,n){return Math.min(n,Math.max(t,e))}function eo(e){return 0===e.length?"none":e.map(e=>`${e.start}-${e.end-1}`).join(", ")}function to(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 no(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function io(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function oo(e,t,n=0){return to(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n)}function ro(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function so(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:ro(e,t)}}function ao(e,t){return{originScreenPoint:t.clone(),originCamera:e.getCurrentCamera()}}function lo(e,t,n){const i=n.sub(t.originScreenPoint),o=t.originCamera.z;e.setCamera({x:t.originCamera.x-i.x/o,y:t.originCamera.y-i.y/o},{source:"user"})}function co(e){return[new $I(e.minX,e.minY),new $I(e.maxX,e.minY),new $I(e.maxX,e.maxY),new $I(e.minX,e.maxY)]}function uo(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),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1?l:null}function ho(e,t,n){const i=e[t];return"number"==typeof i&&Number.isFinite(i)?i:n}function po(e){return Math.min(1,Math.max(0,(96-e)/96))}function go(e,t,n){if(t.w<=0||t.h<=0||n<=0)return $I.Zero();const i=Math.min(n,32),o=po(e.x),r=po(t.w-e.x),s=po(e.y),a=1.25*(r-o)*i,l=1.25*(po(t.h-e.y)-s)*i;return 0===a&&0===l?$I.Zero():new $I(a,l)}function fo(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=go(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 mo(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 yo(e,t,n){const i=new Set(n);if(i.has(t))return t;const o=So(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)=>So(e,t)[0]?.ancestorId??null)(e,t)===r)?t:o[o.length-1]?.ancestorId??t}function So(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).isSelectionTransformContainer(s)&&n.push({ancestorId:s.id,childId:o}),o=s.id,i=s}return n}function bo({shiftKey:e,accelKey:t}){return e||t}function xo({ctrlKey:e}){return e}function Io(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function wo(e,t){return Math.round(e/t)*t}function Po(e,t,n,i,o,r,s,a,l,d,c,u){const h=vo(d,c),p=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=di({point:new $I(e.minX,e.minY),fromBounds:t,toBounds:n}),o=di({point:new $I(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new LI(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}),g=si(p.center,h),f=e.getShapeUtil(t.pageShape),m=gi(t.pageShape.rotation,c),y=m?p:(()=>{const e=f.getSelectionResizeLocalBounds(t.pageShape),n=e.w*Math.abs(o),i=e.h*Math.abs(r);return new LI(g.x-n/2,g.y-i/2,n,i)})(),S=f.resizeSelectionBounds(t.pageShape,{handleId:s,isOnlyResizeTarget:a,pageCenter:g,selectionLocalBounds:y,scaleX:o,scaleY:r,isResizingFromCenter:l,selectionRotation:m?c:t.pageShape.rotation,selectionRotationCenter:m?d:g}),b=Yt(e,t.shape,t.pageShape,S);b&&Object.assign(u,b)}function vo(e,t){return{rotation:t,rotationCenter:e}}function ko(e,t,n,i,o,r,s,a,l,d,c){const u=vo(l,d),h=si(Co({point:t.startLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u),p=si(Co({point:t.endLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u),g=t.middleLocalPagePoint?si(Co({point:t.middleLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u):void 0,f=e.getShapeUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[h,p],pageMiddlePoint:g}),m=Yt(e,t.shape,t.pageShape,f);m&&Object.assign(c,m)}function Co({point:e,startBounds:t,scaleX:n,scaleY:i,handleId:o,isResizingFromCenter:r}){const s=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:un(t)?e.maxX:hn(t)?e.minX:e.center.x)({startBounds:t,handleId:o,isResizingFromCenter:r}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:pn(t)?e.maxY:gn(t)?e.minY:e.center.y)({startBounds:t,handleId:o,isResizingFromCenter:r});return new $I(s+(e.x-s)*n,a+(e.y-a)*i)}function To(e,t,n,i,o){const r=t.localBounds.center,s=ai(new $I(t.pageShape.x+r.x,t.pageShape.y+r.y),{rotation:i,rotationCenter:n}),a=Yt(e,t.shape,t.pageShape,{id:t.shape.id,x:s.x-r.x,y:s.y-r.y,rotation:t.rotation+i});a&&Object.assign(o,a)}function Mo(e,t,n,i,o){const r=e.getShapeUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[ai(t.startPagePoint,{rotation:i,rotationCenter:n}),ai(t.endPagePoint,{rotation:i,rotationCenter:n})],pageMiddlePoint:t.middlePagePoint?ai(t.middlePagePoint,{rotation:i,rotationCenter:n}):void 0}),s=Yt(e,t.shape,t.pageShape,r);s&&Object.assign(o,s)}function Eo(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 Bo(e,t,n){const i=n?e.getContainingShapeParentIdAtPoint(t,n):e.getContainingShapeParentId(t);if(!i)return null;const o=Eo(e,t);if(!o||!o.startsWith("shape:")||i===o)return i;const r=e.getShape(o);return r&&e.getShapeUtil(r).canReceiveChildren(r)?e.getShapeUtil(r).canAutomaticallyReceiveChildren(r)?n?i:t.every(t=>{const n=e.getShapeContainment(r.id,t);return"inside"===n||"intersecting"===n})?o:i:o:i}function Ao(e,t,n){const i=Bo(e,t,n);i&&t.some(t=>e.getShape(t)?.parentId!==i)&&e.commands.reparentShapes({ids:[...t],parentId:i})}function Ro(e,t,n,i={}){let o=!0;return(e=>{const r=new AI(e,()=>{t.get(),o&&!1===i.fireImmediately?o=!1:(o=!1,n())},void 0);return r.attach(),()=>r.detach()})(e)}function $o(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 Lo(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t}: ${i}.`);n.add(i)}}function Fo(e,t){return`${e}:${t}`}function Do(e,t){const n=e.get(t);if(n)return n;const i=[];return e.set(t,i),i}function Uo(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 zo(){const e=Yx(dP);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function Oo(e){const t=Nx(t=>Ro("useValue",e,t,{fireImmediately:!1}),[e]),n=Nx(()=>e.get(),[e]);return jx(t,n,n)}function Xo({children:e,className:t,dataUi:n}){const i=zo(),o=Vx(null);return Wx(()=>Ro("PageSpace.transform",i.pageTransformSignal,()=>{const e=o.current;e&&(e.style.transform=i.pageTransformSignal.get().toCssString())}),[i]),Zx("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 No(e=[]){const t=new cP;return t.registerCanvasRenderPlugins(e),t}function Yo(){return Yx(hP)}function _o(){const e="undefined"!=typeof window&&"1"===new URLSearchParams(window.location.search).get("renderHostDebug");
2
+ return Qx("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:[Zx(Xo,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:Zx(pP,{})}),e?Zx(gP,{}):null]})}function Ho(e,t,n){const i=new Set;let o=t.parentId;for(;o.startsWith("shape:");){const t=o;if(t===e)return!0;if(i.has(t))return!1;i.add(t);const r=n.get(t);if(!r)return!1;o=r.parentId}return!1}function Wo(){
3
+ return Zx("div",{"data-ui":"transform-descendant-ancestor-boundary",style:{position:"absolute",inset:0,border:"1px dashed #64748b",pointerEvents:"none"}})}function Ko(){
4
+ return Zx("div",{"data-ui":"shape-drop-target-label",style:{position:"absolute",left:10,top:10,display:"flex",alignItems:"center",height:24,padding:"0 10px",borderRadius:999,background:"#2563eb",color:"white",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:12,fontWeight:700,lineHeight:"24px",boxShadow:"0 10px 24px rgba(37, 99, 235, 0.24)",whiteSpace:"nowrap",pointerEvents:"none"},children:"Drop into container"})}function Vo({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?Zx(Gx,{children:e}):t.reduceRight((e,t)=>Zx(qo,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function qo({ancestorId:e,children:t,shapeElementToPage:n}){const i=zo(),o=Oo(i.getShapeSignal(e));if(!o)return Zx(Gx,{children:t});const r=((e,t,n)=>{const i=e.getShapeUtil(t).getChildClipLocalPolygons(t);if(!i)return null;const o=e.computeShapeRenderToPageTransform(t),r=n.tryInvert();if(!r)return null;const s=i.filter(e=>e.length>=3).map(e=>e.map(e=>r.applyToPoint(o.applyToPoint(e)))).filter(e=>e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y)));return 0===s.length?null:1===s.length?`polygon(${s[0].map(Zo).join(", ")})`:`path("${s.map(Go).join(" ")}")`})(i,o,n);return r?Zx("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}):Zx(Gx,{children:t})}function jo(e,t,n){const i=e.computeShapeRenderBounds(t),o=n.compose(FI.Translate(i.x,i.y));return{left:0,top:0,width:i.w,height:i.h,transform:o.toCssString(),transformOrigin:"0 0",elementToPage:o}}function Go(e){return e.map((e,t)=>`${0===t?"M":"L"} ${Qo(e.x)} ${Qo(e.y)}`).concat("Z").join(" ")}function Zo(e){return`${Qo(e.x)}px ${Qo(e.y)}px`}function Qo(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Jo(e,t){return(e.order??0)-(t.order??0)}function er(e=[]){const t=new yP;return t.registerCanvasRenderPlugins(e),t}function tr(){return Yx(bP)}function nr(e,t){return"binding-preview"===e?{underlay:{"data-binding-preview-segment-underlay":t},segment:{"data-binding-preview-segment":t}}:"terminal-binding-guide"===e?{underlay:{"data-terminal-binding-guide-underlay":t},segment:{"data-terminal-binding-guide":t}}:{underlay:{"data-selection-binding-segment-underlay":t},segment:{"data-selection-binding-segment":t}}}function ir({start:e,end:t,startInset:n,endInset:i,strokeWidth:o,dashSize:r,gapSize:s,kind:a,terminal:l}){const d=(({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),l=Math.min(n,a),d=Math.min(i,a),c=o/s,u=r/s;return{start:{x:e.x+c*l,y:e.y+u*l},end:{x:t.x-c*d,y:t.y-u*d}}})({start:e,end:t,startInset:n,endInset:i});if(!d)return null;const c=nr(a,l);
5
+ return Qx("g",{style:{pointerEvents:"none"},children:[Zx("line",{...c.underlay,x1:d.start.x,y1:d.start.y,x2:d.end.x,y2:d.end.y,fill:"none",stroke:IP,strokeLinecap:"round",strokeWidth:2.2*o}),Zx("line",{...c.segment,x1:d.start.x,y1:d.start.y,x2:d.end.x,y2:d.end.y,fill:"none",stroke:xP,strokeDasharray:`${r} ${s}`,strokeLinecap:"round",strokeWidth:o})]})}function or({path:e,strokeWidth:t,dashSize:n,gapSize:i,kind:o,terminal:r}){const s=nr(o,r);
6
+ return Qx("g",{style:{pointerEvents:"none"},children:[Zx("path",{...s.underlay,d:e,fill:"none",stroke:IP,strokeLinecap:"round",strokeWidth:2.2*t}),Zx("path",{...s.segment,d:e,fill:"none",stroke:xP,strokeDasharray:`${n} ${i}`,strokeLinecap:"round",strokeWidth:t})]})}function rr({editor:e,shape:t,stroke:n,fill:i,strokeWidth:o}){const r=e.getShapePageOutlineVertices(t.id);return 0===r.length?null:Zx("polygon",{points:r.map(e=>`${e.x},${e.y}`).join(" "),fill:i,stroke:n,strokeWidth:o,strokeLinejoin:"round",strokeLinecap:"round"})}function sr({frame:e,handleId:t,zoom:n}){const i=((e,t)=>{const{bounds:n}=e;switch(t){case"top":return{x1:n.minX,y1:n.minY,x2:n.maxX,y2:n.minY};case"right":return{x1:n.maxX,y1:n.minY,x2:n.maxX,y2:n.maxY};case"bottom":return{x1:n.minX,y1:n.maxY,x2:n.maxX,y2:n.maxY};case"left":return{x1:n.minX,y1:n.minY,x2:n.minX,y2:n.maxY};default:return null}})(e,t);return i?Zx("line",{"data-selection-resize-border":t,x1:i.x1,y1:i.y1,x2:i.x2,y2:i.y2,fill:"none",stroke:"transparent",strokeWidth:12/n,strokeLinecap:"butt",style:{cursor:ar(t,e.rotation),pointerEvents:"stroke"}}):null}function ar(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 $P[Math.round(n)%$P.length]??"default"}function lr({handle:e,strokeWidth:t}){
7
+ return Zx("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 dr(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function cr(){
8
+ return Zx("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:Zx(Xo,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:Zx(_P,{})})})}function ur(e=[]){const t=new WP;return t.registerCanvasRenderPlugins(e),t}function hr(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 pr(e){return(e??("undefined"==typeof document?null:document))?.querySelector(VP)??null}function gr(e,t){return{type:"keyboard",name:e,...mr(t),code:t.code}}function fr(e,t,n){e.getShapeEditingSession()?n||e.handleInteractionEvent(gr("key_up",t)):n||e.dispatch(gr("key_up",t))}function mr(e){return{key:e.key,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}}function yr(e){return"Space"===e.code}function Sr(e,t){const n=t.ownerDocument;return e===n||e===n.body||e===n.documentElement||e instanceof Node&&t.contains(e)}function br(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 xr(e,t){return new $I(e.clientX-t.left,e.clientY-t.top)}function Ir(e,t){return(e%t+t)%t}function wr(){const e=Oo(zo().currentCameraSignal);
9
+ return Qx("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:[Zx("defs",{children:qP.map(({min:t,mid:n,step:i})=>{const o=15*i*e.z,r=((e,t)=>({x:Ir(.5-e.x*e.z,t),y:Ir(.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;
10
+ return Zx("pattern",{id:`land-canvas-grid-${i}`,width:o,height:o,patternUnits:"userSpaceOnUse",children:Zx("circle",{cx:r.x,cy:r.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:s})},i)})}),qP.map(({step:e})=>Zx("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function Pr(e,t,n,i){return n||"hand"===e&&t?"grabbing":i||"hand"===e?"grab":"select"===e?void 0:"crosshair"}function vr({canvasComponents:e,canvasProviders:t,domEventGuardRegistry:n,onContextMenuRequest:i,overlayRegistry:o,rendererRegistry:r,showGrid:s=!1}={}){const a=zo(),l=Kx(()=>r??No(),[r]),d=Kx(()=>o??er(),[o]),c=Kx(()=>n??ur(),[n]),u=Oo(a.toolStateSignal).activeToolId,h=Oo(a.shapeEditingStateSignal).session,p=Oo(a.inputs.isSpacePressed)&&null===h,{containerRef:g,handlers:f,isPointerActive:m,isCameraPanning:y,surfaceCursor:S}=function({activeDomEventGuards:e,activeToolId:t,editor:n,onContextMenuRequest:i,shapeEditingSession:o}){const r=Vx(null),s=Vx(null),a=Vx(null),l=Vx(null),d=Vx(null),c=Vx(null),u=Vx(null),[h,p]=qx(!1),[g,f]=qx(!1),[m,y]=qx(void 0),S=null!==o;_x(()=>{("select"!==t||S)&&n.setHoveredShapeId(null)},[t,n,S]);const b=Nx(()=>{null!==d.current&&(cancelAnimationFrame(d.current),d.current=null),c.current=null},[]),x=Nx(e=>{if(null===a.current)return void b();const t=c.current??e;c.current=e,n.dispatch({type:"tick",timestamp:e,elapsed:e-t}),d.current=requestAnimationFrame(x)},[n,b]),I=Nx(()=>{null===d.current&&(c.current=null,d.current=requestAnimationFrame(x))},[x]);return _x(()=>{const i=r.current;if(!i)return;const o=()=>{const e=i.getBoundingClientRect(),t={left:e.left,top:e.top};return s.current=t,t},d=()=>s.current??o(),c=e=>{const o=i.getBoundingClientRect();if(!e||e.x<o.left||e.x>o.right||e.y<o.top||e.y>o.bottom||null!==a.current||"select"!==t||S)return void n.setHoveredShapeId(null);const r=d(),s=new $I(e.x-r.left,e.y-r.top),l=n.hitTestShape(n.screenToPage(s));n.setHoveredShapeId(l?n.getOutermostSelectableShapeId(l.id):null)},h=(t,o)=>"handled"===e.handle({name:t,event:o,editor:n,container:i}),g=()=>{if(!S)return void y(void 0);const t=u.current;y(t?e.getCursor({clientPoint:t,element:document.elementFromPoint(t.x,t.y),editor:n,container:i}):void 0)},m=(e,t)=>{if(!r.current)return;const i=xr(t,d());n.dispatch(br(e,t,i,n.screenToPage(i)))},x=()=>{n.setViewportScreenSize({w:i.clientWidth,h:i.clientHeight})};o(),x();const I=e=>{if(h("key_down",e))return;if(n.getShapeEditingSession()){const t=hr(e.target);return t||"Escape"!==e.key||e.altKey||e.ctrlKey||e.metaKey?!t&&n.handleInteractionEvent(gr("key_down",e))?(e.preventDefault(),void e.stopPropagation()):void(t||"Enter"!==e.key||!e.metaKey&&!e.ctrlKey||n.completeEditing("user")):(e.preventDefault(),e.stopPropagation(),n.cancelInteractionAndClearTransients("escape"),void(n.getShapeEditingSession()&&n.cancelEditing("user")))}if(hr(e.target))return;if(yr(e)){if(!Sr(e.target,i))return;e.preventDefault()}const t=n.shortcuts.getTargetForEvent(mr(e));t&&"action"!==t.type&&e.preventDefault(),n.dispatch(gr("key_down",e))},w=e=>{if(yr(e)&&n.inputs.pressedKeyCodes.get().has(e.code)&&!n.getShapeEditingSession())return e.preventDefault(),void fr(n,e,!1);h("key_up",e)||yr(e)&&!Sr(e.target,i)||fr(n,e,hr(e.target))},P=()=>{a.current=null,l.current=null,p(!1),f(!1),n.setHoveredShapeId(null),b(),n.dispatch({type:"cancel",reason:"blur"})},v=e=>{if(h("wheel",e))return;e.preventDefault();const t=xr(e,d()),i=n.screenToPage(t);n.dispatch(((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new $I(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},c(u.current),g(),e.pointerId!==a.current){const t=xr(e,d());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}),h("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)||hr(e.target))return;return void m("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=l.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||(l.current=t,m("pointer_move",e))},C=(e,t)=>{t.pointerId===a.current&&(a.current=null,l.current=null,p(!1),f(!1),b(),i.hasPointerCapture(t.pointerId)&&i.releasePointerCapture(t.pointerId),m(e,t),"pointer_up"===e?c(u.current):n.setHoveredShapeId(null))},T=()=>{u.current=null,n.setHoveredShapeId(null),g()},M=e=>{u.current={x:e.clientX,y:e.clientY},window.setTimeout(g,0),e.pointerId===a.current?C("pointer_up",e):h("pointer_up",e)},E=e=>{u.current={x:e.clientX,y:e.clientY},g(),e.pointerId===a.current?C("pointer_cancel",e):h("pointer_cancel",e)},B=new ResizeObserver(()=>{o(),x()});window.addEventListener("keydown",I),window.addEventListener("keyup",w),window.addEventListener("blur",P),window.addEventListener("scroll",o,{passive:!0,capture:!0}),window.addEventListener("pointermove",k,{passive:!0}),window.addEventListener("pointerup",M),window.addEventListener("pointercancel",E),i.addEventListener("pointerleave",T),i.addEventListener("wheel",v,{passive:!1}),B.observe(i);const A=window.requestAnimationFrame(g);return()=>{b(),p(!1),f(!1),n.setHoveredShapeId(null),window.cancelAnimationFrame(A),window.removeEventListener("keydown",I),window.removeEventListener("keyup",w),window.removeEventListener("blur",P),window.removeEventListener("scroll",o,!0),window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",M),window.removeEventListener("pointercancel",E),i.removeEventListener("pointerleave",T),i.removeEventListener("wheel",v),B.disconnect()}},[e,t,n,S,b]),{containerRef:r,handlers:{onPointerDown:Nx(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(hr(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||0===t.button&&n.inputs.isSpacePressed.get()&&!n.getShapeEditingSession()),l.current=null,I();const d=xr(t,s.current);n.setHoveredShapeId(null),n.dispatch(br("pointer_down",t,d,n.screenToPage(d)))},[e,n,I]),onAuxClick:Nx(e=>{1!==e.button||hr(e.target)||(e.preventDefault(),e.stopPropagation())},[]),onContextMenu:Nx(e=>{const t=r.current;if(!t||!i||hr(e.target))return;e.preventDefault(),e.stopPropagation();const o=t.getBoundingClientRect();if(s.current={left:o.left,top:o.top},null!==a.current){const i=a.current;t.hasPointerCapture(i)&&t.releasePointerCapture(i),a.current=null,l.current=null,p(!1),f(!1),b();const o=xr(e,s.current);n.dispatch({type:"pointer",name:"pointer_cancel",timestamp:e.timeStamp,pointerId:i,button:e.button,buttons:0,pointerType:n.inputs.state.get().pointerType??"mouse",screenPoint:o,pagePoint:n.screenToPage(o),pressure:0,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey,clickCount:e.detail})}if(n.getShapeEditingSession())return;t.focus();const d=xr(e,s.current),c=n.screenToPage(d),u=n.hitTestShape(c);let h;if(u){const e=n.getSelectedShapeIds(),t=e.find(e=>e===u.id||n.getDescendantShapeIds(e).includes(u.id))??n.getOutermostSelectableShapeId(u.id),i=e.includes(t);i||n.commands.setSelectedShapeIds([t],{source:"user"}),h={anchor:{screenPoint:d,pagePoint:c},target:{type:"selection",selectedShapeIds:i?e:[t]}}}else h={anchor:{screenPoint:d,pagePoint:c},target:{type:"canvas"}};i(h)},[n,i,b])},isPointerActive:h,isCameraPanning:g,surfaceCursor:m}}({activeDomEventGuards:c,activeToolId:u,editor:a,onContextMenuRequest:i,shapeEditingSession:h});
11
+ return Qx("div",{ref:g,"data-ui":KP,className:"land-canvas__surface",tabIndex:0,style:{cursor:S??Pr(u,m,y,p)},...f,children:[s?Zx(wr,{}):null,Zx(hP.Provider,{value:l,children:Zx(bP.Provider,{value:d,children:Qx(kr,{providers:t,children:[
12
+ Zx(_o,{}),e?.map(({id:e,component:t})=>Zx(t,{},e)),
13
+ Zx(cr,{})]})})})]})}function kr({children:e,providers:t}){
14
+ return Zx(Gx,{children:t?.reduceRight((e,{id:t,component:n})=>Zx(n,{children:e},t),e)??e})}function Cr(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 Tr(n)?n:null}function Tr(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol||"mailto:"===t.protocol}catch{return!1}}function Mr(e){Tr(e)&&window.open(e,"_blank","noopener,noreferrer")}function Er(e){return{type:"doc",content:e.split("\n").map(e=>({type:"paragraph",content:e.length>0?[{type:"text",text:e}]:[]}))}}function Br(e){return e.content.map(e=>Ur(e)).join("\n")}function Ar(e){if(!e||"object"!=typeof e)return Er("");const t=e,n=Array.isArray(t.content)?t.content.map(e=>Yr(e,0)).filter(e=>null!==e):[];return{type:"doc",attrs:Gr(t.attrs),content:n}}function Rr(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>Or(e)).join("")??"",n=Lr(e);return`<p style="${n?`margin:0;text-align:${n}`:"margin:0"}">${t.length>0?t:"<br>"}</p>`})(e)).join("")}function $r(e){return"text"===e.type&&"string"==typeof e.text}function Lr(e){if("paragraph"===e.type)return jr(e.attrs?.textAlign)}function Fr(e){if(!e||0===e.length)return;const t={},n=new Set;for(const i of e)switch(i.type){case"bold":case"strong":t.fontWeight=700;break;case"italic":case"em":t.fontStyle="italic";break;case"strike":case"s":n.add("line-through");break;case"underline":case"u":n.add("underline");break;case"textStyle":{const e=Wr(i.attrs);void 0!==e?.color&&(t.color=e.color),void 0!==e?.fontFamily&&(t.fontFamily=e.fontFamily),void 0!==e?.fontSize&&(t.fontSize=e.fontSize),void 0!==e?.lineHeight&&(t.lineHeight=e.lineHeight);break}}return n.size>0&&(t.textDecorationLine=["line-through","underline"].filter(e=>n.has(e)).join(" ")),Object.keys(t).length>0?t:void 0}function Dr(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 Ur(e){return $r(e)?e.text:e.content?.map(e=>Ur(e)).join("")??""}function zr(e){const t=[];return void 0!==e.color&&t.push(`color:${e.color}`),void 0!==e.fontFamily&&t.push(`font-family:${e.fontFamily}`),void 0!==e.fontSize&&t.push(`font-size:${e.fontSize}`),void 0!==e.fontWeight&&t.push(`font-weight:${String(e.fontWeight)}`),void 0!==e.fontStyle&&t.push(`font-style:${e.fontStyle}`),void 0!==e.lineHeight&&t.push(`line-height:${e.lineHeight}`),void 0!==e.textDecorationLine&&t.push(`text-decoration-line:${e.textDecorationLine}`),t.join(";")}function Or(e){if($r(e)){const t=Fr(e.marks),n=Dr(e.marks),i=Xr(e.text),o=t?`<span style="${Nr(zr(t))}">${i}</span>`:i;return n&&Tr(n)?`<a href="${Nr(n)}" target="_blank" rel="noopener noreferrer">${o}</a>`:t?o:i}return e.content?.map(e=>Or(e)).join("")??""}function Xr(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Nr(e){return Xr(e).replaceAll('"',"&quot;")}function Yr(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(_r).filter(e=>null!==e):void 0}))(n);return e.text.length>0?e:null}return Yr(n,t)}(e,t+1)).filter(e=>null!==e):[];return{type:i,attrs:Hr(i,n.attrs),content:o}}function _r(e){if(!e||"object"!=typeof e)return null;const t=e;if("string"!=typeof t.type)return null;if("link"===t.type){const e=Gr(t.attrs),n=e?.href;return"string"==typeof n&&Tr(n)?{type:"link",attrs:{...e,href:n}}:null}if("textStyle"===t.type){const e=Wr(t.attrs);return e?{type:"textStyle",attrs:e}:null}return{type:t.type,attrs:Gr(t.attrs)}}function Hr(e,t){const n=Gr(t);if("paragraph"!==e)return n;const i={...n};delete i.textAlign;const o=t&&"object"==typeof t&&!Array.isArray(t)?jr(t.textAlign):void 0;return void 0!==o&&(i.textAlign=o),Object.keys(i).length>0?i:void 0}function Wr(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e,n={color:Kr(t.color,128),fontFamily:Kr(t.fontFamily,256),fontSize:Vr(t.fontSize),lineHeight:qr(t.lineHeight)},i=Object.entries(n).filter(e=>void 0!==e[1]);return i.length>0?Object.fromEntries(i):void 0}function Kr(e,t){if("string"!=typeof e)return;const n=e.trim();return 0===n.length||n.length>t||jP.test(n)||GP.test(n)?void 0:n}function Vr(e){const t="string"==typeof e?ZP.exec(e.trim()):null;if(!t||"px"!==t[2]?.toLowerCase())return;const n=Number(t[1]);return n>=1&&n<=512?`${String(n)}px`:void 0}function qr(e){const t="string"==typeof e?ZP.exec(e.trim()):null;if(!t)return;const n=Number(t[1]),i=t[2]?.toLowerCase()??"";return("px"===i?n>=1&&n<=1024:"%"===i?n>=50&&n<=1e3:n>=.5&&n<=10)?`${String(n)}${i}`:void 0}function jr(e){return"left"===e||"center"===e||"right"===e?e:void 0}function Gr(e){if(!e||"object"!=typeof e)return;const t=Object.entries(e).map(([e,t])=>[e,Zr(t)]).filter(e=>void 0!==e[1]);return t.length>0?Object.fromEntries(t):void 0}function Zr(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=>Zr(e,t+1)).filter(e=>void 0!==e);if(e&&"object"==typeof e){const n=Object.entries(e).map(([e,n])=>[e,Zr(n,t+1)]).filter(e=>void 0!==e[1]);return Object.fromEntries(n)}}}function Qr(e,t){return e.content.map((e,n)=>((e,t,n)=>{const i=Jr(e,t,n);
15
+ return Zx("p",{style:{margin:0,textAlign:Lr(e)},children:i.length>0?i:Zx("br",{})},t)})(e,`block:${n}`,t))}function Jr(e,t,n){return e.content?.map((e,i)=>((e,t,n)=>{if($r(e)){const i=Fr(e.marks),o=Dr(e.marks);return o&&Tr(o)?Zx("span",{"data-rich-text-link":"true","data-rich-text-link-href":o,onPointerEnter:e=>{n?.onPointerEnter?.({href:o,element:e.currentTarget})},onPointerLeave:()=>{n?.onPointerLeave?.()},style:{...i,cursor:n?"pointer":void 0,pointerEvents:n?"auto":"none",textDecorationLine:es(i?.textDecorationLine)},children:e.text},t):Zx("span",{style:i,children:e.text},t)}return Jr(e,t,n)})(e,`${t}:${i}`,n))??[]}function es(e){const t=new Set(e?.split(/\s+/u)??[]);return t.add("underline"),["line-through","underline"].filter(e=>t.has(e)).join(" ")}function ts(){return{defaultFont:JP,defaultFontLabel:"Default",fonts:[]}}function ns(){return is(ts())}function is(e){const t=new Map;for(const n of e.fonts)os(n.id)&&"default"!==n.id&&t.set(n.id,n);return{defaultFont:e.defaultFont,defaultFontLabel:e.defaultFontLabel,fontOptions:[{id:QP,label:e.defaultFontLabel,cssFamily:e.defaultFont.cssFamily,source:e.defaultFont.source},...t.values()],fontsById:t}}function os(e){return"string"==typeof e&&e.trim().length>0}function rs(e,t){return"default"===t?e.defaultFont:e.fontsById.get(t)??e.defaultFont}function ss(e,t,n){const i=rs(t,e),o=n??("undefined"==typeof document?void 0:document);if(!o||!as(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=ev.get(e);if(t)return t;const n=new Map;return ev.set(e,n),n})(o),a=s.get(r);if(a)return a;const l=(async(e,t)=>{const{source:n}=t;if(as(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 ls(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 ls(e,n)))})(o,i).catch(()=>{s.delete(r)});return s.set(r,l),l}function as(e){return!!e&&"system"!==e.kind}async function ls(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 ds(e){return f(e)&&"text"===e.type}function cs(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 us(e){return cs(e.getDefaultShapeProps("text"))}function hs(e,t,n="user"){const i={...us(e),...t.props,richText:t.props?.richText??Er("")},[o]=e.commands.createShapes([{type:"text",x:t.x,y:t.y,parentId:t.parentId,index:t.index,rotation:t.rotation,skewX:t.skewX,scaleX:t.scaleX,scaleY:t.scaleY,meta:t.meta,props:{richText: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(!ds(o))throw new Error("Failed to create text shape");return o}function ps(e){return tv.get(e)?.api??null}function gs(e){const t=tv.get(e);if(t)return t;const n={api:null,disposeApiSubscription:null,listeners:new Set};return tv.set(e,n),n}function fs(e){for(const t of e.listeners)t()}function ms(e){try{return e.view.dom.isConnected}catch{return!1}}function ys(e){!e.isDestroyed&&ms(e)&&(e.view.dom.focus(),e.view.focus())}function Ss(e){if(!ms(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 bs(e,t=sv){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function xs(e,t){return rs(t,e).cssFamily}function Is(e){return bs(e)}function ws(e){const t=bs(e);return av[t]??Math.ceil(1.4*t)}function Ps(e,t=1){return Math.max(1,Math.ceil(ws(e)*t))}function vs(e){switch(e){case"middle":return"center";case"end":return"right";default:return"left"}}function ks(e,t,n){return 0===Br(e).trim().length?Cs(t):Ts(t,(i=Rr(e),o={width:t.props.autoSize?void 0:t.props.w,shape:t,fontCatalog:n},Ms(document).measureHtml(i,o)));var i,o}function Cs(e){const t=e.props.autoSize?16:e.props.w,n=Ps(e.props.size);if(e.props.w!==t||e.props.h!==n)return{w:t,h:n}}function Ts(e,t){const n=e.props.autoSize?Math.max(16,Math.ceil(t.w)):e.props.w,i=Math.max(Ps(e.props.size),Math.ceil(t.h));if(n!==e.props.w||i!==e.props.h)return{w:n,h:i}}function Ms(e){const t=dv.get(e);if(t)return t;const n=new lv(e);return dv.set(e,n),n}function Es(e,t,n){n&&"normal"!==n&&"auto"!==n&&(e.style[t]=n)}function Bs(e,t,n){if(t.isDestroyed()||!t.isConnected())return;const i=t.measure(n);i&&Rs(e,n,i,"user")}function As(e,t,n,i="system"){const o=ks(t.props.richText,t,n);o&&Rs(e,t,o,i)}function Rs(e,t,n,i){const o=e.getShape(t.id);ds(o)&&o.props.w===n.w&&o.props.h===n.h||e.commands.updateShapes([{id:t.id,props:n}],{source:i})}function $s({editor:e,fontCatalog:t,landEditor:n,shapeId:i}){const o=()=>{const e=n.getShape(i);return ds(e)?e:null},r={shapeId:i,getSnapshot(){if(e.isDestroyed)return null;const n=o();return n?(({editor:e,fontCatalog:t,shape:n})=>{const i=e.state.selection,o=(e=>{const{selection:t,doc:n}=e.state;return t.empty?{from:0,to:n.content.size}:{from:t.from,to:t.to}})(e),r=i.empty?"shape":"selection",s=D(n.props.color),a=n.props.textAlign;return{shapeId:n.id,target:r,bold:Os(e,o,"bold"),italic:Os(e,o,"italic"),strike:Os(e,o,"strike"),underline:Os(e,o,"underline"),color:Xs(e,o,"color",s),font:Hs(Xs(e,o,"fontFamily",n.props.font),e=>((e,t)=>t.fontOptions.find(t=>t.cssFamily===e)?.id??e)(e,t)),size:Hs(Xs(e,o,"fontSize",n.props.size),e=>((e,t)=>{if("number"==typeof e)return e;const n=Number.parseFloat(e);return Number.isFinite(n)&&n>0?n:t})(e,n.props.size)),textAlign:Ns(e,o,a),linkHref:Ys(e),canSetLink:!i.empty||e.isActive("link")}})({editor:e,fontCatalog:t,shape:n}):null},subscribe(t){if(e.isDestroyed)return()=>{};const o=()=>t();e.on("transaction",o),e.on("focus",o),e.on("blur",o);const r=Ro(`TextFormattingApi(${i})`,n.getShapeSignal(i),o,{fireImmediately:!1});return()=>{r(),e.off("transaction",o),e.off("focus",o),e.off("blur",o)}},focus(){e.isDestroyed||e.commands.focus()},toggle:t=>((e,t,n)=>{if(e.isDestroyed||void 0===e.schema.marks[t])return!1;const i=e.state.selection;if(!i.empty)return e.chain().focus().toggleMark(t).run();const o=!0!==n?.[t];if(0===e.state.doc.textContent.length){const n=e.chain().focus();return(o?n.setMark(t):n.unsetMark(t)).run()}let r=e.chain().focus().selectAll();return r=o?r.setMark(t):r.unsetMark(t),r=r.setTextSelection(zs(i)),r=o?r.setMark(t):r.unsetMark(t),r.run()})(e,t,r.getSnapshot()),setColor(t){if(null!==t&&!(e=>{const t=e.trim();return t.length>0&&t.length<=128&&!cv.test(t)&&!uv.test(t)})(t))return!1;const i=o();return!!i&&(({editor:e,landEditor:t,shape:n,color:i})=>{if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;if(!e.state.selection.empty)return null===i?e.chain().focus().unsetColor().run():e.chain().focus().setColor(i).run();const o=Fs(e,"color");return null!==i&&Us(t,n,{color:E(i)}),o||null!==i})({editor:e,landEditor:n,shape:i,color:t})},setFont(i){const r=o();if(!r)return!1;if(null===i)return Ls({editor:e,font:null,fontFamily:null,landEditor:n,shape:r});const s=t.fontOptions.find(e=>e.id===i);return!!s&&(ss(i,t).then(()=>{const e=o();e&&As(n,e,t,"system")}),Ls({editor:e,fontFamily:s.cssFamily,font:i,landEditor:n,shape:r}))},setSize(t){const i=null===t?null:Math.round(1e3*t)/1e3;if(null!==t&&(!Number.isFinite(t)||t<1||t>512||null===i||Math.abs(t-i)>Number.EPSILON*Math.max(1,Math.abs(t))))return!1;const r=o();return!!r&&(({editor:e,landEditor:t,shape:n,size:i})=>{if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;const o=e.state.selection,r=null===i?null:`${i}px`,s=null===i?null:`${ws(i)}px`;if(!o.empty)return(a=e.chain().focus(),null===r||null===s?a.unsetFontSize().unsetLineHeight():a.setFontSize(r).setLineHeight(s)).run();var a;const l=(e=>{const t=e.state.selection;let n=e.chain().focus();return e.state.doc.textContent.length>0&&(n=n.selectAll()),Ds(n.unsetFontSize().unsetLineHeight().setTextSelection(zs(t)).unsetFontSize().unsetLineHeight()).run()})(e);return null!==i&&Us(t,n,{size:i}),l||null!==i})({editor:e,landEditor:n,shape:r,size:i})},setTextAlign(t){const i=o();return!!i&&(({editor:e,landEditor:t,shape:n,align:i})=>{if(e.isDestroyed)return!1;const o=(e=>{switch(e){case"middle":return"center";case"end":return"right";default:return"left"}})(i),r=e.state.selection;if(!r.empty)return e.chain().focus().setTextAlign(o).run();const s=e.chain().focus().selectAll().unsetTextAlign().setTextSelection(zs(r)).run();return Us(t,n,{textAlign:i}),s||n.props.textAlign!==i})({editor:e,landEditor:n,shape:i,align:t})},setLink(t){if(e.isDestroyed||void 0===e.schema.marks.link)return!1;const n=null===t?null:Cr(t);if(null!==t&&null===n)return!1;const{empty:i}=e.state.selection,o=e.isActive("link");if(null===n)return!!o&&e.chain().focus().extendMarkRange("link").unsetLink().run();if(i&&!o)return!1;const r=e.chain().focus();return(i?r.extendMarkRange("link"):r).setLink({href:n}).run()},clearFormatting(){if(e.isDestroyed)return!1;const t=e.state.selection;return t.empty?e.chain().focus().selectAll().unsetAllMarks().unsetTextAlign().setTextSelection(zs(t)).command(({tr:e})=>(e.setStoredMarks([]),!0)).run():e.chain().focus().unsetAllMarks().unsetTextAlign().run()},getUnsafeTiptapEditor:()=>e.isDestroyed?null:e};return r}function Ls({editor:e,font:t,fontFamily:n,landEditor:i,shape:o}){if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;if(!e.state.selection.empty)return null===n?e.chain().focus().unsetFontFamily().run():e.chain().focus().setFontFamily(n).run();const r=Fs(e,"fontFamily");return null!==t&&i&&o&&Us(i,o,{font:t}),r||null!==t}function Fs(e,t){const n=e.state.selection;let i=e.chain().focus();return e.state.doc.textContent.length>0&&(i=i.selectAll()),i="color"===t?i.unsetColor():i.unsetFontFamily(),i=i.setTextSelection(zs(n)),i="color"===t?i.unsetColor():i.unsetFontFamily(),Ds(i).run()}function Ds(e){return e.command(({state:e,tr:t})=>{const n=e.schema.marks.textStyle;if(!n)return!0;const i=(t.storedMarks??e.storedMarks)?.find(e=>e.type===n);return i&&Object.values(i.attrs).every(e=>null==e||""===e)&&t.removeStoredMark(n),!0})}function Us(e,t,n){e.commands.updateShapes([{id:t.id,props:n}],{source:"user"})}function zs(e){return e.from===e.to?e.from:{from:e.from,to:e.to}}function Os(e,t,n){if(!e.schema.marks[n])return!1;const i=[];return e.state.doc.nodesBetween(t.from,t.to,(e,t,o)=>{const r=o?.type.schema.marks[n];e.isText&&r&&o?.type.allowsMarkType(r)&&!e.marks.some(e=>"code"===e.type.name)&&i.push(e.marks.some(e=>e.type.name===n))}),0===i.length?(e.state.storedMarks??e.state.selection.$from.marks()).some(e=>e.type.name===n):_s(i)??!1}function Xs(e,t,n,i){const o=[];if(e.state.doc.nodesBetween(t.from,t.to,e=>{if(!e.isText)return;const t=e.marks.find(e=>"textStyle"===e.type.name)?.attrs[n];o.push("string"==typeof t&&t.length>0?t:i)}),0===o.length){const t=(e.state.storedMarks??e.state.selection.$from.marks()).find(e=>"textStyle"===e.type.name)?.attrs[n];return"string"==typeof t&&t.length>0?t:i}return _s(o)}function Ns(e,t,n){const i=[];return e.state.doc.nodesBetween(t.from,t.to,e=>{e.isTextblock&&i.push(((e,t)=>{switch(e){case"center":return"middle";case"right":return"end";case"left":return"start";default:return t}})(e.attrs.textAlign,n))}),_s(i)??n}function Ys(e){const t=e.getAttributes("link").href;return"string"==typeof t&&t.length>0?t:null}function _s(e){if(0===e.length)return null;const t=e[0];return e.every(e=>Object.is(e,t))?t:"mixed"}function Hs(e,t){return null===e?null:"mixed"===e?"mixed":t(e)}function Ws({shapeId:e,editor:t,fontCatalog:n,landEditor:i}){return{shapeId:e,formatting:$s({editor:t,fontCatalog:n,landEditor:i,shapeId:e}),isDestroyed:()=>t.isDestroyed,isConnected:()=>!t.isDestroyed&&ms(t),isFocused:()=>!t.isDestroyed&&ms(t)&&t.view.dom.contains(document.activeElement),getValue:()=>Ar(t.getJSON()),setValue(e){t.commands.setContent(e)},focus(){ys(t)},focusEnd(){!t.isDestroyed&&ms(t)&&t.commands.focus("end")},focusSelectAll(){!t.isDestroyed&&ms(t)&&(ys(t),t.chain().focus().selectAll().run())},focusAtPagePoint(e,n){((e,t,n)=>{ys(t);const i=e.pageToScreen(new $I(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||!ms(t)?{type:null,text:null}:Ss(t),collapseSelectionAtClientPoint(e,n){!t.isDestroyed&&ms(t)&&"Range"===Ss(t).type&&((e,t,n)=>{if(e.isDestroyed||!ms(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&&ms(t))return function(e,t,n){if(0===e.getText().trim().length)return Cs(t);const i=((e,t)=>{const n=e.ownerDocument.defaultView?.getComputedStyle(e);return Ms(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)),Ts(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 Ks({landEditor:e,shape:t,fontCatalog:n,initialRichText:i,className:o,editorStyle:r,formattingToolbar:s,onTiptapEditorChange:a,onReady:l,onDispose:d,onRichTextChange:c}){const u=Vx(null),h=Nx(i=>{const o=u.current;if(o?.editor===i)return o.controller;const r=Ws({shapeId:t.id,editor:i,fontCatalog:n,landEditor:e});return u.current={editor:i,controller:r},r},[n,e,t.id]),p=eI({extensions:pv,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);c({editor:e,controller:t,richText:t.getValue()})}},[t.id]);return _x(()=>{if(!p||p.isDestroyed)return;const n=h(p),i={shapeId:t.id,editor:p,controller:n,formatting:n.formatting},o={shapeId:t.id,formatting:n.formatting},r=!1===s?()=>{}:((e,t)=>{const n=gs(e);return n.disposeApiSubscription?.(),n.api=t,n.disposeApiSubscription=t.subscribe(()=>{fs(n)}),fs(n),()=>{n.api===t&&(n.disposeApiSubscription?.(),n.disposeApiSubscription=null,n.api=null,fs(n))}})(e,n.formatting);return l(i),a?.(o),()=>{r(),u.current?.editor===p&&(u.current=null),d(i),a?.(null)}},[h,s,e,d,l,a,t.id,p]),Zx(Jx,{editor:p,className:o,style:r})}function Vs({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(()=>{Vs({editor:e,controller:t,shapeId:n,request:i,onApplied:o,attempt:r+1})})}}function qs({shapeId:e,markId:t,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o}){const r=zo(),s=Oo(r.getShapeSignal(e)),a=Oo(r.shapeEditingStateSignal).session;return ds(s)&&a?.shapeId===s.id?Zx(js,{shape:s,session:a,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o},`${s.id}:${t}`):null}function js({shape:e,session:t,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o}){const r=zo(),s=Vx(e.props.richText),a=(e=>{const t=Vx(e);return _x(()=>{t.current=e},[e]),t})(e),l=Oo(r.shapeEditingEntryRequestSignal),d=Vx(null),[c,u]=qx(null),[h,p]=qx(null),g=Nx(({editor:e,controller:t})=>{u(e.isDestroyed?null:e),p(t)},[]),f=Nx(({editor:e,controller:t})=>{u(t=>t===e?null:t),p(e=>e===t?null:e)},[]),m=function({editor:e,shape:t,tiptapEditor:n,richTextController:i,latestShapeRef:o,fontCatalog:r}){const s=Vx(t.props.richText),a=Vx(!1),l=Vx(null),d=Nx(({controller:n,richText:i})=>{if(a.current||!n.isConnected())return;const d=Ar(i);s.current=d,((e,t,n,i,o="user")=>{const r=e.getShape(t);ds(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})})(e,t.id,d,n.measure(o.current)??ks(d,o.current,r),"user"),((e,t,n,i)=>{null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,Bs(e,t,n.current)},0)})(e,n,o,l)},[e,r,o,t.id]);return _x(()=>()=>{null!==l.current&&(window.clearTimeout(l.current),l.current=null)},[]),Wx(()=>{n&&i&&!n.isDestroyed&&i.isConnected()&&Bs(e,i,t)},[e,i,t,n]),_x(()=>{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]),_x(()=>{if(i)return i.onCompositionStateChange(t=>{e.setShapeEditingComposition(t,"system")})},[e,i]),_x(()=>{if(!i||!i.isConnected())return;let n=!1;return ss(t.props.font,r).then(()=>{!n&&i.isConnected()&&Bs(e,i,o.current)}),()=>{n=!0}},[e,r,o,i,t.props.font]),d}({editor:r,shape:e,tiptapEditor:c,richTextController:h,latestShapeRef:a,fontCatalog:n});(({editor:e,shapeId:t,session:n,tiptapEditor:i,richTextController:o,entryRequest:r,consumedEntryRequestIdRef:s})=>{const a=Vx(null),l=Vx(null);_x(()=>{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]),_x(()=>{i&&!i.isDestroyed&&o&&null===s.current&&l.current!==n.markId&&(l.current=n.markId,window.setTimeout(()=>{Vs({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]),_x(()=>{i&&!i.isDestroyed&&o&&r&&r.shapeId===t&&s.current!==r.id&&Vs({editor:e,controller:o,shapeId:t,request:r,onApplied(e){e&&(s.current=e.id)}})},[s,e,r,o,t,i]),_x(()=>{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(()=>{Vs({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:r,shapeId:e.id,session:t,tiptapEditor:c,richTextController:h,entryRequest:l,consumedEntryRequestIdRef:d});const y=(({editor:e,shapeId:t,richTextController:n})=>{const i=Vx(null);return{onPointerDownCapture:Nx(o=>{if(o.stopPropagation(),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:Nx(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:Nx(o=>{const r=i.current;if(i.current=null,!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,l=o.clientY;window.setTimeout(()=>{n.isDestroyed()||"Range"!==n.getSelectionSnapshot().type||n.collapseSelectionAtClientPoint(a,l)},0)},[e,n,t]),onPointerCancel:Nx(()=>{i.current=null},[])}})({editor:r,shapeId:e.id,richTextController:h}),S=((e,t)=>Kx(()=>({color:F(e.props.color),fontFamily:xs(e.props.font,t),fontSize:Is(e.props.size),lineHeight:`${ws(e.props.size)}px`,textAlign:vs(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),b=Nx(e=>{if(!e.ctrlKey&&!e.metaKey)return;const t=(e=>{const t=e.target;return t instanceof Element?t.closest("[data-rich-text-link-href]")?.getAttribute("data-rich-text-link-href")??null:null})(e.nativeEvent);t&&c&&!c.isDestroyed&&(e.preventDefault(),e.stopPropagation(),Mr(t))},[c]);
16
+ return Zx("div",{"data-ui":"text-editing-box","data-shape-id":e.id,"data-mount-target-kind":"shape",onPointerDown:e=>{e.stopPropagation()},onClickCapture:b,onPointerDownCapture:y.onPointerDownCapture,onPointerMoveCapture:y.onPointerMoveCapture,onPointerUpCapture:y.onPointerUpCapture,onPointerCancel:y.onPointerCancel,onContextMenu:e=>{e.stopPropagation()},onDragStart:e=>{e.preventDefault()},style:S,children:Zx(Ks,{landEditor:r,shape:e,fontCatalog:n,initialRichText:s.current,className:"land-text-editor__content",formattingToolbar:i,editorStyle:{height:"100%",minHeight:"100%"},onReady:g,onDispose:f,onTiptapEditorChange:o,onRichTextChange:m})})}function Gs({children:e,presenter:t}){
17
+ return Zx(gv.Provider,{value:t,children:e})}function Zs(e,t){return t?fv:F(e)}function Qs(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t}: ${i}.`);n.add(i)}}function Js({fontCatalog:e=ns(),formattingToolbar:t,onTiptapEditorChange:n}={}){return{id:"land.text.react",domEventGuards:[yv],canvasComponents:[{id:"land.text.default-font-preload",component:()=>Zx(ea,{fontCatalog:e})}],shapeRenderers:[{type:"text",component:i=>Zx(ta,{...i,fontCatalog:e,formattingToolbar:t,onTiptapEditorChange:n})}]}}function ea({fontCatalog:e}){return _x(()=>{ss(QP,e)},[e]),null}function ta({shape:e,editor:t,isHovered:n,fontCatalog:i,formattingToolbar:o,onTiptapEditorChange:r}){const[s,a]=qx(null),l=Vx(null),d=Oo(t.selectedShapeIdsSignal),c=Yx(gv),{hasEditingSession:u,isEditingThisShape:h,editingHost:p}=function(e,t,n,i,o){const r=Oo(e.shapeEditingStateSignal).session,s=r?.shapeId===t.id,a=r&&s?Zx(qs,{shapeId:r.shapeId,markId:r.markId,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o},r.shapeId+":"+r.markId):null;return(({editor:e,shape:t,isEditingThisShape:n,fontCatalog:i})=>{Wx(()=>{if(n)return;As(e,t,i);let o=!1;return ss(t.props.font,i).then(()=>{if(o)return;const n=e.getShape(t.id);ds(n)&&n.props.font===t.props.font&&As(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:s,fontCatalog:n}),{hasEditingSession:null!==r,isEditingThisShape:s,editingHost:a}}(t,e,i,o,r),g=null!==c&&(({isEditing:e,isOnlySelected:t})=>!e&&!t)({isEditing:u,isOnlySelected:1===d.length&&d[0]===e.id}),f=Nx(()=>{null!==l.current&&(window.clearTimeout(l.current),l.current=null)},[]),m=Nx(()=>{f(),l.current=window.setTimeout(()=>{a(null),l.current=null},160)},[f]);return _x(()=>()=>{f()},[f]),_x(()=>{g||(f(),a(null))},[g,f]),Qx("div",{"data-editing-hidden":h?"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:F(e.props.color),fontFamily:xs(e.props.font,i),fontSize:Is(e.props.size),lineHeight:`${ws(e.props.size)}px`,textAlign:vs(e.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none"},children:[
18
+ Zx("div",{style:{opacity:h?0:void 0},children:Qr(e.props.richText,g?{onPointerEnter({href:e,element:t}){f(),a({anchorElement:t,href:e})},onPointerLeave(){m()}}:void 0)}),g&&s&&c?Zx(c,{anchorElement:s.anchorElement,href:s.href,onOpen:()=>{Mr(s.href)},onPopoverPointerEnter:f,onPopoverPointerLeave:m}):null,
19
+ Zx("div",{"data-ui":"text-editor-host-slot","data-shape-id":e.id,"data-active":h?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:p}),n?Zx("div",{"aria-hidden":"true","data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 2px ${fv}`,inset:0,pointerEvents:"none",position:"absolute"}}):null]})}function na(e){return cs(e)}function ia(e,t){return de(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})?.rotation??t.rotation}function oa(e,t,n,i){const o=e.getShapeUtil(t),r=de(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(!r)return null;const s={...t,...r,x:i.x,y:i.y,rotation:i.rotation,props:o.validateProps({...t.props,...i.props})},a=n.startsWith("shape:")?e.getShape(n):null;if(n.startsWith("shape:")&&!a)return null;const l=(a?e.computeShapeLocalToPageTransform(a):FI.Identity()).tryInvert();return l?de(l.compose(o.getLocalToPageTransform(s)),o.getLocalBounds(s),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY}):null}function ra(e,t,n){const i=e.getBindingsToShape(t).find(e=>e.type===n);if(!i)return null;const o=e.getShape(i.fromId);return ds(o)?o:null}function sa(e,t){const n={...us(e),...t.layout.props,autoSize:!1,textAlign:"middle"},i=oa(e,{id:"shape:draft-label",typeName:"shape",scope:"document",type:"text",parentId:t.owner.parentId,index:t.index,x:0,y:0,rotation:0,skewX:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:n},t.owner.parentId,t.layout);if(!i)return null;e.history.mark(t.historyMarkId);const o=hs(e,{x:i.x,y:i.y,parentId:t.owner.parentId,index:t.index,rotation:i.rotation,skewX:i.skewX,scaleX:i.scaleX,scaleY:i.scaleY,props:n},"user");return e.commands.createBinding({type:t.bindingType,fromId:o.id,toId:t.owner.id,props:t.bindingProps},{source:"user"}),o}function aa(e,t){const n=e.getShape(t);if(!ds(n))return null;const i=e.getBindingsFromShape(t).find(e=>e.type in vv);if(!i)return null;const o=i.type;return{label:n,ownerId:i.toId,bindingType:o,behavior:vv[o]}}function la(e,t,n){e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:n.isExisting?n.editMarkId:n.createMarkId,reuseExistingMark:!n.isExisting},"user")}function da(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function ca(e){return Math.max(.01,e.props.scale)}function ua(e){return e.props.w*ca(e)}function ha(e){return e.props.h*ca(e)}function pa(e){return new LI(0,0,ua(e),ha(e))}function ga(e){return"left"===e||"right"===e}function fa(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>ma(e))??[],n=Lr(e);return{tag:"p",attrs:{style:n?`margin:0;text-align:${n}`:"margin:0"},children:t.length>0?t:[{tag:"br"}]}})(e))}function ma(e){if($r(e)){const t=(e=>{const t=Fr(e.marks);return t?zr(t):void 0})(e);return t?{tag:"span",attrs:{style:t},children:[e.text]}:e.text}return{tag:"span",children:e.content?.map(e=>ma(e))??[]}}function ya(e,t,n){return[`color:${t.resolveColor(e.props.color)}`,`font-family:${xs(e.props.font,n)}`,`font-size:${Is(e.props.size)}px`,`line-height:${ws(e.props.size)}px`,`text-align:${vs(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 Sa(e){return"shape"===e?.typeName&&"arrow"===e.type}function ba(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function xa(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=Ia(t.start),i=Ia(t.end),o=wa(t.bend)??0;if(!n||!i)return null;const r=$I.Med(n,i).add(i.sub(n).len()?i.sub(n).per().normalize().mul(-o):new $I(0,o)),s=new $I(e.x+(e=>wa(e.props.w)??1)(e)/2,e.y+(e=>wa(e.props.h)??1)(e)/2),a=new $I(e.x+r.x,e.y+r.y);if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return a;const l=a.sub(s);return s.add(new $I(l.x*e.scaleX,l.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:ia(e,n),props:{w:r}}}function Ia(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 $I(t.x,t.y):null}function wa(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function Pa(e){return"shape"===e?.typeName&&"geo"===e.type}function va(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function ka(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Ca(e,t){const n=e.props[t];return"number"==typeof n&&Number.isFinite(n)?n:null}function Ta(e,t){const n=Ca(e,"h");return!n||t.props.ownerBaseHeight<=0||n===t.props.ownerBaseHeight?null:{...e,props:{...e.props,h:t.props.ownerBaseHeight}}}function Ma(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:ia(e,n),props:{w:r}}}function Ea(){let e=null;const t=()=>{e=null};return{id:"land.text.interactions",editorEvent:{handleEvent(n,i){if("cancel"===i.type)return t(),"continue";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&&ds(s)&&e.canEditShape(s)?(e.startEditingShape({shapeId:s.id,entryMode:"placeCaret",caretPagePoint:t.pagePoint,markId:Rv,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&&ds(t)&&n.canEditShape(t)?(n.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:Rv},"user"),"handled"):"continue"}return"click"===i.type&&"double_click"===i.name?(t(),((e,t)=>{const n=e.hitTestShape(t.pagePoint);return n?ds(n)?e.canEditShape(n)?(e.startEditingShape({shapeId:n.id,entryMode:"selectAll",markId:Rv},"user"),"handled"):"continue":"geo"===n.type?((e,t)=>{if(t.isLocked)return"continue";const n=ra(e,t.id,Pv),i=n??((e,t)=>{const n=Ma(e,Ba(t,{...us(e),autoSize:!1,textAlign:"middle"}),t);return sa(e,{bindingType:Pv,owner:t,historyMarkId:Dv,index:`${t.index}${Bv}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})})(e,t);return i?(la(e,i,{editMarkId:Fv,createMarkId:Dv,isExisting:!!n}),"handled"):"handled"})(e,n):(e=>"arrow"===e.type)(n)?((e,t)=>{if(t.isLocked)return"continue";const n=ra(e,t.id,wv),i=n??((e,t)=>{const n=xa(e,Ba(t,{...us(e),autoSize:!1,textAlign:"middle"}),t);return sa(e,{bindingType:wv,owner:t,historyMarkId:Lv,index:`${t.index}${Mv}`,layout:n,bindingProps:{labelPosition:.5}})})(e,t);return i?(la(e,i,{editMarkId:$v,createMarkId:Lv,isExisting:!!n}),"handled"):"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||!ds(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:Rv,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=aa(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 Ba(e,t){return{id:"shape:draft",typeName:"shape",scope:"document",type:"text",parentId:e.parentId,index:`${e.index}.label`,x:0,y:0,rotation:0,skewX:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:t}}function Aa(e,t){const n=Uv[t];let i=!1,o=!1;return $a(e.content,(e,t)=>{"text"!==e.type||!e.text||t.insideCodeBlock||e.marks?.some(e=>"code"===e.type)||(e.marks?.some(e=>n.includes(e.type))?i=!0:o=!0)}),i&&o?"mixed":i}function Ra(e){if("paragraph"!==e.type||void 0===e.attrs?.textAlign)return e;const t={...e.attrs};return delete t.textAlign,{...e,attrs:Object.keys(t).length>0?t:void 0}}function $a(e,t,n=!1){for(const i of e)t(i,{insideCodeBlock:n}),i.content&&$a(i.content,t,n||"codeBlock"===i.type)}function La(e,t,n=!1){let i=!1;return{nodes:e.map(e=>{const o=t(e,{insideCodeBlock:n}),r=o.content;if(!r)return o!==e&&(i=!0),o;const s=La(r,t,n||"codeBlock"===o.type);return s.changed?(i=!0,{...o,content:s.nodes}):(o!==e&&(i=!0),o)}),changed:i}}function Fa({fontCatalog:e=ns(),selectionFormattingToolbar:t=!0}={}){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 Cv],shapeSvgExporters:[new Tv(e)],bindingUtils:[new Av,new Ev],interactionHandlers:[Ea()],setup(e){e.tools.register("text",e=>new bv(e),{shortcut:"t"})}}}function Da(e){return{id:"text.selection-toolbar",surface:"selection",placement:"floating",order:20,actionIds:["text.set-color","text.set-font","text.set-size","text.set-textAlign",...Nv.map(e=>e.actionId),Yv,_v],subscribe:(e,t)=>((e,t)=>{const n=gs(e);return n.listeners.add(t),()=>{n.listeners.delete(t)}})(e,t),when:e=>1===e.selection.count&&"text"===e.selection.commonShapeType,getGroups(){const[t,n,i,o]=Oa({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"});return[t,n,i,{id:"text.inline-format",items:Nv.map(e=>({kind:"button",id:e.actionId,actionId:e.actionId,label:e.label,icon:e.icon,dataUi:e.dataUi}))},o,{id:"text.clear-formatting",items:[{kind:"button",id:Yv,actionId:Yv,label:"Clear formatting",icon:"remove-formatting",dataUi:"selected-text-clear-formatting-button"}]},{id:"text.link",items:[{kind:"text-input",id:"text.link",actionId:_v,label:"Link",icon:"link",presentation:"popover",placeholder:"Link URL",validate:e=>0===e.trim().length||null!==Cr(e),dataUi:"text-link-button"}]}]}}}function Ua(e){return{id:"text.default-style.tool-toolbar",surface:"tool",placement:"floating",order:51,actionIds:["text.default-color","text.default-font","text.default-size","text.default-textAlign"],when:e=>"text"===e.tool.activeToolId,getGroups:()=>Oa({colorActionId:"text.default-color",fontActionId:"text.default-font",fontCatalog:e,sizeActionId:"text.default-size",textAlignActionId:"text.default-textAlign",dataUiPrefix:"text-default"})}}function za(e){return{id:"text.multi-selection-toolbar",surface:"selection",order:20,actionIds:["text.set-color","text.set-font","text.set-size","text.set-textAlign"],when:e=>e.selection.count>1&&"text"===e.selection.commonShapeType&&null===e.editor.shapeEditingStateSignal.get().session,getGroups:()=>Oa({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"})}}function Oa({colorActionId:e,fontActionId:t,fontCatalog:n,sizeActionId:i,textAlignActionId:o,dataUiPrefix:r}){return[{id:`${r}.style-color`,items:[{kind:"color-input",id:`${r}.color`,actionId:e,label:"Color",fallback:"#0f172a",presets:zv.map(e=>({...e,dataUi:`${r}-color-${e.id}-button`})),dataUi:`${r}.color`}]},{id:`${r}.style-font`,items:[{kind:"segmented",id:`${r}.font`,actionId:t,options:n.fontOptions.map(e=>({value:e.id,label:e.label,dataUi:`${r}-font-${e.id}-button`}))}]},{id:`${r}.style-size`,items:[{kind:"stepper",id:`${r}.size`,actionId:i,label:"Size",options:Ov.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:Xv.map(e=>({...e,dataUi:`${r}-align-${e.value}-button`}))}]}]}function Xa(e,t){return{id:`text.set-${e}`,isVisible:e=>"text"===e.selection.commonShapeType,isEnabled:e=>Na(e)?null!==_a(e):e.selection.selectedShapes.some(e=>"text"===e.type&&!e.isLocked),getValue(t){const n=_a(t);return n?n[e]:((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?!z(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e)},run({context:n,value:i}){const o=Ka(e,i,t);if(void 0===o)return;if(Na(n)){const t=Ya(n);if(!t)return;return void("color"===e?t.setColor(D(o)):"font"===e?t.setFont(o):"size"===e?t.setSize(o):t.setTextAlign(o))}const r=n.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).map(t=>{const n=((e,t)=>{const n=La(e.content,e=>{if("textAlign"===t)return Ra(e);if("text"!==e.type||!e.marks)return e;let n=!1;const i=e.marks.flatMap(e=>{if("textStyle"!==e.type||!e.attrs)return[e];const i={...e.attrs};let o=!1;const r="size"===t?["fontSize","lineHeight"]:"font"===t?["fontFamily"]:["color"];for(const t of r)t in i&&(delete i[t],o=!0);return o?(n=!0,Object.keys(i).length>0?[{...e,attrs:i}]:[]):[e]});return n?{...e,marks:i.length>0?i:void 0}:e});return n.changed?Ar({...e,content:n.nodes}):e})(t.props.richText,e);return{id:t.id,props:{[e]:o,...n===t.props.richText?null:{richText:n}}}});0!==r.length&&n.editor.commands.updateShapes(r,{source:"user"})}}}function Na(e){return null!==e.editor.shapeEditingStateSignal.get().session}function Ya(e){const t=e.editor.shapeEditingStateSignal.get().session,n=ps(e.editor);return t&&n?.shapeId===t.shapeId?n:null}function _a(e){const t=e.editor.shapeEditingStateSignal.get().session,n=(i=e.editor,ps(i)?.getSnapshot()??null);var i;return t&&n?.shapeId===t.shapeId?n:null}function Ha(e,t){let n;for(const i of e){if("text"!==i.type)continue;const e=Aa(i.props.richText,t);if("mixed"===e)return null;if(void 0===n)n=e;else if(n!==e)return null}return n??!1}function Wa(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=Ka(e,i,t);void 0!==o&&n.editor.updateDefaultShapeProps("text",{[e]:o})}}}function Ka(e,t,n){if("color"===e)return R(t)?L(t,M("text-slate")):void 0;if("font"===e){if("string"!=typeof t)return;return((e,t)=>"default"===t||os(t)&&e.fontsById.has(t))(n,t)?t:void 0}if("size"===e){if("number"!=typeof t||!Number.isFinite(t))return;return Ov.some(e=>e.value===t)?t:void 0}return"string"==typeof t&&Xv.some(e=>e.value===t)?t:void 0}function Va(e={}){const t={...ts(),...e},n=is(t);return{id:"text",editor:Fa({fontCatalog:n,selectionFormattingToolbar:!1!==t.formattingToolbar}),render:Js({fontCatalog:n,formattingToolbar:t.formattingToolbar,onTiptapEditorChange:t.onTiptapEditorChange}),product:()=>function({fontCatalog:e=ns(),selectionFormattingToolbar:t=!0}={}){return{actions:[{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")}},Xa("color",e),Xa("font",e),Xa("size",e),Xa("textAlign",e),...Nv.map(e=>{return{id:`text.toggle-${t=e.format}`,isVisible:e=>"text"===e.selection.commonShapeType,isEnabled:e=>Na(e)?null!==_a(e):e.selection.selectedShapes.some(e=>"text"===e.type&&!e.isLocked),getValue(e){const n=_a(e);return n?n[t]:Ha(e.selection.selectedShapes,t)},run({context:e}){if(Na(e))return void Ya(e)?.toggle(t);const n=!0!==Ha(e.selection.selectedShapes,t),i=e.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).flatMap(e=>{const i=((e,t,n)=>{const i=Uv[t],o=La(e.content,(e,o)=>{if("text"!==e.type||!e.text)return e;const r=e.marks??[],s=r.filter(e=>i.includes(e.type));if(n&&(o.insideCodeBlock||r.some(e=>"code"===e.type)))return e;if(n&&1===s.length&&s[0]?.type===t)return e;const a=r.filter(e=>!i.includes(e.type)),l=n?[...a,{type:t}]:a;return r.length===l.length&&r.every((e,t)=>e===l[t])?e:{...e,marks:l.length>0?l:void 0}});return o.changed?Ar({...e,content:o.nodes}):e})(e.props.richText,t,n);return i===e.props.richText?[]:[{id:e.id,props:{richText:i}}]});i.length>0&&e.editor.commands.updateShapes(i,{source:"user"})}};var t}),{id:Yv,isVisible:e=>"text"===e.selection.commonShapeType,isEnabled:e=>Na(e)?null!==_a(e):e.selection.selectedShapes.some(e=>"text"===e.type&&!e.isLocked),getValue:()=>!1,run({context:e}){if(Na(e))return void Ya(e)?.clearFormatting();const t=e.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).flatMap(e=>{const t=(e=>{const t=La(e.content,e=>"text"===e.type&&e.marks&&e.marks.length>0?{...e,marks:void 0}:Ra(e));return t.changed?Ar({...e,content:t.nodes}):e})(e.props.richText);return t===e.props.richText?[]:[{id:e.id,props:{richText:t}}]});t.length>0&&e.editor.commands.updateShapes(t,{source:"user"})}},{id:_v,isVisible:e=>1===e.selection.count&&"text"===e.selection.commonShapeType,isEnabled:e=>_a(e)?.canSetLink??!1,getValue(e){const t=_a(e)?.linkHref;return"string"==typeof t&&"mixed"!==t?t:""},run({context:e,value:t}){if("string"!=typeof t)return;const n=Ya(e);if(!n)return;if(0===t.trim().length)return void n.setLink(null);const i=Cr(t);i&&n.setLink(i)}},Wa("color",e),Wa("font",e),Wa("size",e),Wa("textAlign",e)],toolbarContributions:[{id:"text.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[sP],getGroups:e=>[{id:"text.tools",items:[{kind:"button",id:"text.tool.text",actionId:sP,value:"text",label:"Text",shortcut:e.editor.shortcuts.getToolShortcutLabel("text"),icon:"type",dataUi:"text-tool-button"}]}]},Ua(e),...t?[Da(e),za(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"}]}]}]}}({fontCatalog:n,selectionFormattingToolbar:!1!==t.formattingToolbar})}}function qa(e,t){if(!Object.isFrozen(e))return ja(e,t);const n=e,i=Vv.get(n),o=i?.[t];if(o)return o;const r=ja(e,t);return Vv.set(n,{...i,[t]:r}),r}function ja(e,t){const n=(e=>JSON.parse(JSON.stringify(e)))(e),i=n.surfaces[t].prepress,o=new Map(n.points.map(e=>[e.id,new $I(e.x,e.y)])),r=new Map,s=new Map;for(const b of n.edges){const e=o.get(b.fromPointId),t=o.get(b.toPointId);if(!e||!t)throw new Error(`Packaging edge "${b.id}" references a missing point.`);const n=rl(b,e,t);r.set(b.id,n),s.set(b.id,n.path)}const a=new Map,l=new Map,d=new Map,c=new Map,u=new Map,h=new Set;for(const b of n.faces){const e=Za(b.outer,r),t=sl(b.outer,r),n=(b.holes??[]).map(e=>{for(const t of e.edges)h.add(t.edgeId);return Za(e,r)}),i=(b.holes??[]).map(e=>sl(e,r)),o=Qa(b.outer,r),s=(b.holes??[]).map(e=>Qa(e,r)),p=e.length>0?LI.FromPoints(e):new LI(0,0,0,0),g=El(e,n,p);a.set(b.id,{face:b,bounds:p,center:g,outerPath:o,holePaths:s,outer:e,holes:n,outerEdges:t,holeEdges:i}),l.set(b.id,o),d.set(b.id,[[e,...n]]),c.set(b.id,[...s]),u.set(b.id,g)}const p=[...o.values(),...Array.from(r.values()).flatMap(e=>[...Bl(e.bounds),...e.extrema])],g=p.length>0?LI.FromPoints(p):new LI(0,0,0,0),f=(e=>{const t=[...e.values()].flatMap(e=>e.outerEdges.filter(e=>"cut"===e.edge.operation).flatMap(e=>Bl(e.bounds)));return t.length>0?LI.FromPoints(t):null})(a),m=new Map((i?.bleedContours??[]).map(e=>[e.id,Ga(e.contour,e)])),y=LI.FromPoints([...Bl(g),...Array.from(m.values()).flatMap(e=>e.samples.map(e=>e.clone()))]),S=new Map((i?.safeZones??[]).map(e=>[e.id,Ga(e.contour,e)]));return{bounds:g,outerBounds:y,dielineBounds:f,pointsById:o,edgesById:r,facesById:a,facePaths:l,facePolygons:d,holePaths:c,edgePaths:s,faceCenters:u,snapPoints:Il({bounds:g,pointsById:o,edgesById:r,faceCenters:u}),spatialIndex:wl(a),holeEdgeIds:h,bleedContoursById:m,safeZonesById:S}}function Ga(e,t){const n=new $I(e.start.x,e.start.y);let i=n;const o=[`M ${Al(n)}`],r=[n.clone()],s=[n.clone()];for(const a of e.segments){const e=new $I(a.to.x,a.to.y),t=cl(a),n=dl(t,i,e),l="line"===t.type?[i.clone(),e.clone()]:al(n),d=ul(t,i,e);o.push(pl(t,e)),r.push(...l.slice(1)),s.push(e.clone(),...d),i=e}return r.length>1&&r[0].dist2(r[r.length-1])<=Kv&&r.pop(),o.push("Z"),{source:t??e,path:o.join(" "),samples:r,bounds:LI.FromPoints(s)}}function Za(e,t){const n=[];for(const i of e.edges){const e=t.get(i.edgeId);if(!e)throw new Error(`Packaging loop references missing edge "${i.edgeId}".`);const o="forward"===i.direction?e.samples:[...e.samples].reverse();for(let t=0;t<o.length;t+=1)n.length>0&&0===t||n.push(o[t].clone())}return n.length>1&&n[0].dist2(n[n.length-1])<=Kv&&n.pop(),n}function Qa(e,t){const n=e.edges[0];if(!n)return"";const i=t.get(n.edgeId);if(!i)throw new Error(`Packaging loop references missing edge "${n.edgeId}".`);const o=[`M ${Al("forward"===n.direction?i.from:i.to)}`];for(const r of e.edges){const e=t.get(r.edgeId);if(!e)throw new Error(`Packaging loop references missing edge "${r.edgeId}".`);o.push(hl(e,r))}return o.push("Z"),o.join(" ")}function Ja(e,t){const n=e.spatialIndex.searchPoint(t);for(let i=n.length-1;i>=0;i-=1){const o=e.facesById.get(n[i]);if(o&&(vl(t,o)||el(t,o)))return o}return null}function el(e,t){return Pl(e,t.outer)&&!t.holes.some(t=>Pl(e,t))}function tl(e,t){if(0===t.length)return[];const n=LI.FromPoints([...t]),i=[];for(const o of e.spatialIndex.searchBounds(n)){const n=e.facesById.get(o);n&&kl(t,n)&&i.push(o)}return i}function nl(e,t){if(!e)return[];const[n,i,o,r]=(e=>[new $I(e.minX,e.minY),new $I(e.maxX,e.minY),new $I(e.maxX,e.maxY),new $I(e.minX,e.maxY)])(e),s=Math.max(0,t.horizontalLength),a=Math.max(0,t.verticalLength);return[`M ${Rl(n.x-s,n.y)} L ${Al(n)} L ${Rl(n.x,n.y-a)}`,`M ${Rl(i.x+s,i.y)} L ${Al(i)} L ${Rl(i.x,i.y-a)}`,`M ${Rl(o.x+s,o.y)} L ${Al(o)} L ${Rl(o.x,o.y+a)}`,`M ${Rl(r.x-s,r.y)} L ${Al(r)} L ${Rl(r.x,r.y+a)}`]}function il(e,t){const[n,i]=(()=>{switch(e){case"crease":case"score":case"construction":return[3,2];default:return[2,3]}})();return`${$l(t*n)} ${$l(t*i)}`}function ol(e){const[t,n,i,o,r,s]=e,a=t*o-n*i;return!Number.isFinite(a)||Math.abs(a)<=Kv?null:[o/a,-n/a,-i/a,t/a,(i*s-o*r)/a,(n*r-t*s)/a]}function rl(e,t,n){const i=dl(e.geometry,t,n),o="line"===e.geometry.type?[t.clone(),n.clone()]:al(i),r=ul(e.geometry,t,n),s=LI.FromPoints([t,n,...r]);return{edge:e,from:t.clone(),to:n.clone(),path:`M ${Al(t)} ${pl(e.geometry,n)}`,bounds:s,midpoint:i(.5),extrema:r,samples:o,pointAt:i}}function sl(e,t){return e.edges.map(e=>{const n=t.get(e.edgeId);if(!n)throw new Error(`Packaging loop references missing edge "${e.edgeId}".`);return n})}function al(e){const t=e(0),n=[t];return ll(e,0,t,1,e(1),0,n),n}function ll(e,t,n,i,o,r,s){const a=i-t,l=e(t+.25*a),d=t+.5*a,c=e(d),u=e(t+.75*a),h=.0025000000000000005;Ml(l,n,o)<=h&&Ml(c,n,o)<=h&&Ml(u,n,o)<=h||r>=12?s.push(o):(ll(e,t,n,d,c,r+1,s),ll(e,d,c,i,o,r+1,s))}function dl(e,t,n){switch(e.type){case"line":return e=>((e,t,n)=>new $I(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n))(t,n,e);case"quadratic":{const i=new $I(e.control.x,e.control.y);return e=>yl(t,i,n,e)}case"cubic":{const i=new $I(e.control1.x,e.control1.y),o=new $I(e.control2.x,e.control2.y);return e=>Sl(t,i,o,n,e)}case"arc":{const i=gl(t,n,e);return e=>((e,t)=>fl(e,e.startAngle+e.deltaAngle*t))(i,e)}}}function cl(e){switch(e.type){case"line":return{type:"line"};case"quadratic":return{type:"quadratic",control:e.control};case"cubic":return{type:"cubic",control1:e.control1,control2:e.control2};case"arc":return{type:"arc",radiusX:e.radiusX,radiusY:e.radiusY,rotation:e.rotation,largeArc:e.largeArc,sweep:e.sweep}}}function ul(e,t,n){switch(e.type){case"line":return[];case"quadratic":{const i=new $I(e.control.x,e.control.y),o=new Set;return bl(t.x,i.x,n.x,o),bl(t.y,i.y,n.y,o),[...o].map(e=>yl(t,i,n,e))}case"cubic":{const i=new $I(e.control1.x,e.control1.y),o=new $I(e.control2.x,e.control2.y),r=new Set;for(const e of xl(t.x,i.x,o.x,n.x))r.add(e);for(const e of xl(t.y,i.y,o.y,n.y))r.add(e);return[...r].map(e=>Sl(t,i,o,n,e))}case"arc":{const i=gl(t,n,e),{radiusX:o,radiusY:r,rotation:s}=i;return[Math.atan2(-r*Math.sin(s),o*Math.cos(s)),Math.atan2(-r*Math.sin(s),o*Math.cos(s))+Math.PI,Math.atan2(r*Math.cos(s),o*Math.sin(s)),Math.atan2(r*Math.cos(s),o*Math.sin(s))+Math.PI].filter(e=>((e,t,n)=>n>=0?ml(e-t)<=n+Kv:ml(t-e)<=-n+Kv)(e,i.startAngle,i.deltaAngle)).map(e=>fl(i,e))}}}function hl(e,t){if("forward"===t.direction)return pl(e.edge.geometry,e.to);const n=e.edge.geometry;switch(n.type){case"line":return`L ${Al(e.from)}`;case"quadratic":return`Q ${Rl(n.control.x,n.control.y)} ${Al(e.from)}`;case"cubic":return`C ${Rl(n.control2.x,n.control2.y)} ${Rl(n.control1.x,n.control1.y)} ${Al(e.from)}`;case"arc":return`A ${$l(n.radiusX)} ${$l(n.radiusY)} ${$l(n.rotation)} ${n.largeArc?1:0} ${n.sweep?0:1} ${Al(e.from)}`}}function pl(e,t){switch(e.type){case"line":return`L ${Al(t)}`;case"quadratic":return`Q ${Rl(e.control.x,e.control.y)} ${Al(t)}`;case"cubic":return`C ${Rl(e.control1.x,e.control1.y)} ${Rl(e.control2.x,e.control2.y)} ${Al(t)}`;case"arc":return`A ${$l(e.radiusX)} ${$l(e.radiusY)} ${$l(e.rotation)} ${e.largeArc?1:0} ${e.sweep?1:0} ${Al(t)}`}}function gl(e,t,n){const i=n.rotation*Math.PI/180,o=Math.cos(i),r=Math.sin(i),s=(e.x-t.x)/2,a=(e.y-t.y)/2,l=o*s+r*a,d=-r*s+o*a;let c=Math.abs(n.radiusX),u=Math.abs(n.radiusY);const h=l*l/(c*c)+d*d/(u*u);if(h>1){const e=Math.sqrt(h);c*=e,u*=e}const p=c*c,g=u*u,f=Math.max(0,p*g-p*d*d-g*l*l),m=p*d*d+g*l*l,y=m<=Kv?0:(n.largeArc===n.sweep?-1:1)*Math.sqrt(f/m),S=y*(c*d/u),b=y*(-u*l/c),x=new $I(o*S-r*b+(e.x+t.x)/2,r*S+o*b+(e.y+t.y)/2),I=new $I((l-S)/c,(d-b)/u),w=new $I((-l-S)/c,(-d-b)/u),P=Math.atan2(I.y,I.x);let v=((e,t)=>Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y))(I,w);return!n.sweep&&v>0?v-=Wv:n.sweep&&v<0&&(v+=Wv),{center:x,radiusX:c,radiusY:u,rotation:i,startAngle:P,deltaAngle:v}}function fl(e,t){const n=Math.cos(e.rotation),i=Math.sin(e.rotation),o=Math.cos(t),r=Math.sin(t);return new $I(e.center.x+e.radiusX*o*n-e.radiusY*r*i,e.center.y+e.radiusX*o*i+e.radiusY*r*n)}function ml(e){return(e%Wv+Wv)%Wv}function yl(e,t,n,i){const o=1-i;return new $I(o*o*e.x+2*o*i*t.x+i*i*n.x,o*o*e.y+2*o*i*t.y+i*i*n.y)}function Sl(e,t,n,i,o){const r=1-o;return new $I(r*r*r*e.x+3*r*r*o*t.x+3*r*o*o*n.x+o*o*o*i.x,r*r*r*e.y+3*r*r*o*t.y+3*r*o*o*n.y+o*o*o*i.y)}function bl(e,t,n,i){const o=e-2*t+n;if(Math.abs(o)<=Kv)return;const r=(e-t)/o;r>Kv&&r<.999999999&&i.add(r)}function xl(e,t,n,i){const o=3*t-e-3*n+i,r=2*(e-2*t+n),s=t-e;if(Math.abs(o)<=Kv){if(Math.abs(r)<=Kv)return[];const e=-s/r;return e>Kv&&e<.999999999?[e]:[]}const a=r*r-4*o*s;if(a<0)return[];const l=Math.sqrt(a);return[(-r+l)/(2*o),(-r-l)/(2*o)].filter(e=>e>Kv&&e<.999999999)}function Il({bounds:e,pointsById:t,edgesById:n,faceCenters:i}){const o=[];for(const r of Bl(e))o.push({point:r.clone(),kind:"corner",weight:100});for(const r of t.values())o.push({point:r.clone(),kind:"custom",weight:20});for(const r of n.values())if(o.push({point:r.midpoint.clone(),kind:"edge_midpoint",weight:10}),"arc"===r.edge.geometry.type)for(const e of r.extrema)o.push({point:e.clone(),kind:"custom",weight:12});for(const r of i.values())o.push({point:r.clone(),kind:"center",weight:5});return(e=>{const t=new Map;for(const n of e){const e=`${n.point.x.toFixed(8)}:${n.point.y.toFixed(8)}`,i=t.get(e);(!i||(n.weight??0)>(i.weight??0))&&t.set(e,n)}return[...t.values()]})(o)}function wl(e){const t=[...e.values()].map(e=>({id:e.face.id,bounds:e.bounds}));return{searchPoint:e=>t.filter(t=>t.bounds.containsPoint(e)).map(e=>e.id),searchBounds:e=>t.filter(t=>t.bounds.intersects(e)).map(e=>e.id)}}function Pl(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(Ml(e,s,r)<=Kv)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 vl(e,t){return[t.outerEdges,...t.holeEdges].some(t=>t.some(t=>t.samples.slice(1).some((n,i)=>Ml(e,t.samples[i],n)<=.0025000010000000004)))}function kl(e,t){if(e.some(e=>el(e,t)))return!0;if(t.outer.some(t=>Pl(t,e)))return!0;for(let n=0;n<e.length;n+=1){const i=e[n],o=e[(n+1)%e.length];for(let e=0;e<t.outer.length;e+=1)if(Cl(i,o,t.outer[e],t.outer[(e+1)%t.outer.length]))return!0}return!1}function Cl(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)<=Kv)return Ml(e,n,i)<=Kv||Ml(t,n,i)<=Kv||Ml(n,e,t)<=Kv||Ml(i,e,t)<=Kv;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=-1e-9&&l<=1.000000001&&d>=-1e-9&&d<=1.000000001}function Tl(e,t,n,i){return Cl(e,t,n,i)?0:Math.min(Ml(e,n,i),Ml(t,n,i),Ml(n,e,t),Ml(i,e,t))}function Ml(e,t,n){const i=n.sub(t),o=i.len2();if(o<=Kv)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 El(e,t,n){const i=(e=>{if(e.length<3)return null;let t=0,n=0,i=0;for(let o=0;o<e.length;o+=1){const r=e[o],s=e[(o+1)%e.length],a=r.x*s.y-s.x*r.y;t+=a,n+=(r.x+s.x)*a,i+=(r.y+s.y)*a}return Math.abs(t)<=Kv?null:new $I(n/(3*t),i/(3*t))})(e)??n.center,o=n=>Pl(n,e)&&!t.some(e=>Pl(n,e));if(o(i))return i;const r=[];for(let s=0;s<9;s+=1)for(let e=0;e<9;e+=1)r.push(new $I(n.minX+(e+.5)/9*n.w,n.minY+(s+.5)/9*n.h));return r.sort((e,t)=>e.dist2(i)-t.dist2(i)),r.find(o)?.clone()??e[0]?.clone()??n.center}function Bl(e){return[new $I(e.minX,e.minY),new $I(e.maxX,e.minY),new $I(e.maxX,e.maxY),new $I(e.minX,e.maxY)]}function Al(e){return Rl(e.x,e.y)}function Rl(e,t){return`${$l(e)} ${$l(t)}`}function $l(e){return Number(e.toFixed(6)).toString()}function Ll(e){return e.runtime.require(qv)}function Fl(e){const t=e.meta[jv];return"outside"===t||"inside"===t?t:null}function Dl(e){if(e&&"object"==typeof e&&tk.has(e))return e;const t=dd(e,"PackagingDocument");if(gd(t,["schemaVersion","id","revision","name","unit","coordinateSystem","points","edges","faces","surfaces"],["sheetBounds","source","meta"],"PackagingDocument"),1!==t.schemaVersion&&fd("PackagingDocument.schemaVersion must equal 1."),ud(t.id,"PackagingDocument.id"),ud(t.revision,"PackagingDocument.revision"),ud(t.name,"PackagingDocument.name"),Zv.has(t.unit)||fd("PackagingDocument.unit is invalid."),"top-left-y-down"!==t.coordinateSystem&&fd('PackagingDocument.coordinateSystem must equal "top-left-y-down".'),void 0!==t.sheetBounds){const e=dd(t.sheetBounds,"PackagingDocument.sheetBounds");gd(e,["x","y","w","h"],[],"PackagingDocument.sheetBounds"),hd(e.x,"PackagingDocument.sheetBounds.x"),hd(e.y,"PackagingDocument.sheetBounds.y"),pd(e.w,"PackagingDocument.sheetBounds.w"),pd(e.h,"PackagingDocument.sheetBounds.h")}const n=cd(t.points,"PackagingDocument.points"),i=new Set;for(let c=0;c<n.length;c+=1){const e=dd(n[c],`PackagingDocument.points[${c}]`);gd(e,["id","x","y"],[],`PackagingDocument.points[${c}]`);const t=ld(e.id,i,`PackagingDocument.points[${c}].id`);hd(e.x,`Packaging point "${t}".x`),hd(e.y,`Packaging point "${t}".y`)}const o=cd(t.edges,"PackagingDocument.edges"),r=new Set;for(let c=0;c<o.length;c+=1)zl(o[c],c,r,i);const s=cd(t.faces,"PackagingDocument.faces"),a=new Set;for(let c=0;c<s.length;c+=1)Ol(s[c],c,a,r);if(((e,t,n)=>{const i=dd(e,"PackagingDocument.surfaces");gd(i,[...Jv],[],"PackagingDocument.surfaces");for(const o of Jv){const e=`PackagingDocument.surfaces.${o}`,r=dd(i[o],e);gd(r,[],["prepress","meta"],e),void 0!==r.prepress&&Xl(r.prepress,t,n,`${e}.prepress`),void 0!==r.meta&&rd(r.meta,`${e}.meta`)}})(t.surfaces,r,a),void 0!==t.source){const e=dd(t.source,"PackagingDocument.source");gd(e,[],["provider","externalId","revision"],"PackagingDocument.source");for(const t of["provider","externalId","revision"])void 0!==e[t]&&ud(e[t],`PackagingDocument.source.${t}`)}void 0!==t.meta&&rd(t.meta,"PackagingDocument.meta");const l=e;(e=>{const t=new Map(e.edges.map(e=>[e.id,e])),n=ja(e,"outside");for(const i of e.faces){Gl(i.outer,i,"outer",t,n.edgesById);const e=n.facesById.get(i.id);e||fd(`Packaging face "${i.id}" could not be compiled.`);for(let o=0;o<(i.holes?.length??0);o+=1){Gl(i.holes[o],i,`holes[${o}]`,t,n.edgesById);const r=e.holes[o];r.every(t=>id(t,e.outer))||fd(`Packaging face "${i.id}" hole ${o} must be inside its outer loop.`),ed(r,e.outer)&&fd(`Packaging face "${i.id}" hole ${o} intersects its outer loop.`);for(let t=0;t<o;t+=1){const n=e.holes[t];(ed(r,n)||id(r[0],n)||id(n[0],r))&&fd(`Packaging face "${i.id}" holes ${t} and ${o} overlap.`)}}}})(l);for(const c of Jv)Hl(l,c);const d=(e=>ad(e))(Ul(l));return tk.add(d),d}function Ul(e){return JSON.parse(JSON.stringify(e))}function zl(e,t,n,i){const o=`PackagingDocument.edges[${t}]`,r=dd(e,o);gd(r,["id","fromPointId","toPointId","geometry","operation"],["visible","meta"],o);const s=ld(r.id,n,`${o}.id`);ud(r.fromPointId,`${o}.fromPointId`),ud(r.toPointId,`${o}.toPointId`),i.has(r.fromPointId)||fd(`Packaging edge "${s}" references missing point "${String(r.fromPointId)}".`),i.has(r.toPointId)||fd(`Packaging edge "${s}" references missing point "${String(r.toPointId)}".`),Qv.has(r.operation)||fd(`Packaging edge "${s}" has an invalid operation.`),void 0!==r.visible&&"boolean"!=typeof r.visible&&fd(`Packaging edge "${s}".visible must be a boolean.`),void 0!==r.meta&&rd(r.meta,`Packaging edge "${s}".meta`);const a=dd(r.geometry,`Packaging edge "${s}".geometry`);switch(a.type){case"line":gd(a,["type"],[],`Packaging edge "${s}".geometry`);break;case"quadratic":gd(a,["type","control"],[],`Packaging edge "${s}".geometry`),od(a.control,`Packaging edge "${s}".geometry.control`);break;case"cubic":gd(a,["type","control1","control2"],[],`Packaging edge "${s}".geometry`),od(a.control1,`Packaging edge "${s}".geometry.control1`),od(a.control2,`Packaging edge "${s}".geometry.control2`);break;case"arc":gd(a,["type","radiusX","radiusY","rotation","largeArc","sweep"],[],`Packaging edge "${s}".geometry`),pd(a.radiusX,`Packaging edge "${s}".geometry.radiusX`),pd(a.radiusY,`Packaging edge "${s}".geometry.radiusY`),hd(a.rotation,`Packaging edge "${s}".geometry.rotation`),"boolean"==typeof a.largeArc&&"boolean"==typeof a.sweep||fd(`Packaging edge "${s}" arc flags must be boolean values.`),r.fromPointId===r.toPointId&&fd(`Packaging arc edge "${s}" must have distinct endpoints.`);break;default:fd(`Packaging edge "${s}" has an invalid geometry type.`)}}function Ol(e,t,n,i){const o=`PackagingDocument.faces[${t}]`,r=dd(e,o);gd(r,["id","outer"],["name","role","holes","artworkFrame","meta"],o);const s=ld(r.id,n,`${o}.id`);for(const a of["name","role"])void 0!==r[a]&&"string"!=typeof r[a]&&fd(`Packaging face "${s}".${a} must be a string.`);if(_l(r.outer,`Packaging face "${s}".outer`,i),void 0!==r.holes&&cd(r.holes,`Packaging face "${s}".holes`).forEach((e,t)=>_l(e,`Packaging face "${s}".holes[${t}]`,i)),void 0!==r.artworkFrame){const e=dd(r.artworkFrame,`Packaging face "${s}".artworkFrame`);gd(e,["uvToDocument"],[],`Packaging face "${s}".artworkFrame`);const t=cd(e.uvToDocument,`Packaging face "${s}".artworkFrame.uvToDocument`);6!==t.length&&fd(`Packaging face "${s}" artworkFrame matrix must contain 6 numbers.`),t.forEach((e,t)=>hd(e,`Packaging face "${s}" artworkFrame[${t}]`)),ol(t)||fd(`Packaging face "${s}" artworkFrame matrix must be invertible.`)}void 0!==r.meta&&rd(r.meta,`Packaging face "${s}".meta`)}function Xl(e,t,n,i){const o=dd(e,i);gd(o,["bleedContours","safeZones"],[],i);const r=new Set;cd(o.bleedContours,`${i}.bleedContours`).forEach((e,n)=>{const o=`${i}.bleedContours[${n}]`,s=dd(e,o);gd(s,["id","cutEdgeIds","minimumBleed","contour"],["name","meta"],o);const a=ld(s.id,r,`${o}.id`);Nl(s.name,`${o}.name`),pd(s.minimumBleed,`${o}.minimumBleed`);const l=cd(s.cutEdgeIds,`${o}.cutEdgeIds`);0===l.length&&fd(`Packaging bleed contour "${a}" must reference at least one cut edge.`);const d=new Set;l.forEach((e,n)=>{ud(e,`${o}.cutEdgeIds[${n}]`),t.has(e)||fd(`Packaging bleed contour "${a}" references missing edge "${String(e)}".`),d.has(e)&&fd(`Packaging bleed contour "${a}" references edge "${String(e)}" more than once.`),d.add(e)}),Yl(s.contour,`${o}.contour`),void 0!==s.meta&&rd(s.meta,`${o}.meta`)}),cd(o.safeZones,`${i}.safeZones`).forEach((e,t)=>{const o=`${i}.safeZones[${t}]`,s=dd(e,o);gd(s,["id","faceId","minimumClearance","contour"],["name","meta"],o);const a=ld(s.id,r,`${o}.id`);Nl(s.name,`${o}.name`),ud(s.faceId,`${o}.faceId`),n.has(s.faceId)||fd(`Packaging safe zone "${a}" references missing face "${String(s.faceId)}".`),pd(s.minimumClearance,`${o}.minimumClearance`),Yl(s.contour,`${o}.contour`),void 0!==s.meta&&rd(s.meta,`${o}.meta`)})}function Nl(e,t){void 0!==e&&ud(e,t)}function Yl(e,t){const n=dd(e,t);gd(n,["start","segments"],[],t),od(n.start,`${t}.start`);const i=cd(n.segments,`${t}.segments`);i.length<2&&fd(`${t} must contain at least 2 segments plus its implicit closing segment.`),i.forEach((e,n)=>{const i=`${t}.segments[${n}]`,o=dd(e,i);switch(o.type){case"line":gd(o,["type","to"],[],i),od(o.to,`${i}.to`);break;case"quadratic":gd(o,["type","control","to"],[],i),od(o.control,`${i}.control`),od(o.to,`${i}.to`);break;case"cubic":gd(o,["type","control1","control2","to"],[],i),od(o.control1,`${i}.control1`),od(o.control2,`${i}.control2`),od(o.to,`${i}.to`);break;case"arc":gd(o,["type","radiusX","radiusY","rotation","largeArc","sweep","to"],[],i),pd(o.radiusX,`${i}.radiusX`),pd(o.radiusY,`${i}.radiusY`),hd(o.rotation,`${i}.rotation`),"boolean"!=typeof o.largeArc&&fd(`${i}.largeArc must be a boolean.`),"boolean"!=typeof o.sweep&&fd(`${i}.sweep must be a boolean.`),od(o.to,`${i}.to`);break;default:fd(`${i}.type is invalid.`)}})}function _l(e,t,n){const i=dd(e,t);gd(i,["edges"],[],t);const o=cd(i.edges,`${t}.edges`);o.length<3&&fd(`${t} must contain at least 3 directed edges.`);const r=new Set;o.forEach((e,i)=>{const o=dd(e,`${t}.edges[${i}]`);gd(o,["edgeId","direction"],[],`${t}.edges[${i}]`),ud(o.edgeId,`${t}.edges[${i}].edgeId`),n.has(o.edgeId)||fd(`${t} references missing edge "${String(o.edgeId)}".`),r.has(o.edgeId)&&fd(`${t} references edge "${String(o.edgeId)}" more than once.`),r.add(o.edgeId),"forward"!==o.direction&&"reverse"!==o.direction&&fd(`${t}.edges[${i}].direction is invalid.`)})}function Hl(e,t){const n=e.surfaces[t].prepress;if(!n)return;const i=new Map(e.edges.map(e=>[e.id,e])),o=ja(e,t);for(const r of n.bleedContours){const e=o.bleedContoursById.get(r.id);e||fd(`Packaging bleed contour "${r.id}" could not be compiled.`),Wl(0,e.samples,`Packaging bleed contour "${r.id}"`);for(const t of r.cutEdgeIds){"cut"!==i.get(t).operation&&fd(`Packaging bleed contour "${r.id}" edge "${t}" must use the cut operation.`);const n=o.edgesById.get(t);n.samples.every(t=>id(t,e.samples))||fd(`Packaging bleed contour "${r.id}" must enclose cut edge "${t}".`),Kl(n.samples,e.samples)+ek<r.minimumBleed*r.minimumBleed&&fd(`Packaging bleed contour "${r.id}" does not provide its minimum bleed around cut edge "${t}".`)}}for(const r of n.safeZones){const e=o.safeZonesById.get(r.id),t=o.facesById.get(r.faceId);e&&t||fd(`Packaging safe zone "${r.id}" could not be compiled.`),Wl(0,e.samples,`Packaging safe zone "${r.id}"`),e.samples.every(e=>id(e,t.outer)&&!t.holes.some(t=>id(e,t)))||fd(`Packaging safe zone "${r.id}" must stay inside face "${r.faceId}" and outside its holes.`),[t.outer,...t.holes].some(t=>Vl(e.samples,t)+ek<r.minimumClearance*r.minimumClearance)&&fd(`Packaging safe zone "${r.id}" does not provide its minimum clearance from the cut or crease boundary of face "${r.faceId}".`)}}function Wl(e,t,n){(t.length<3||Math.abs(Ql(t))<=ek)&&fd(`${n} must form a non-zero closed area.`),Jl(t)&&fd(`${n} must not self-intersect.`)}function Kl(e,t){let n=Number.POSITIVE_INFINITY;for(let i=0;i<e.length-1;i+=1)for(let o=0;o<t.length;o+=1)n=Math.min(n,ql(e[i],e[i+1],t[o],t[(o+1)%t.length]));return n}function Vl(e,t){let n=Number.POSITIVE_INFINITY;for(let i=0;i<e.length;i+=1)for(let o=0;o<t.length;o+=1)n=Math.min(n,ql(e[i],e[(i+1)%e.length],t[o],t[(o+1)%t.length]));return n}function ql(e,t,n,i){return td(e,t,n,i)?0:Math.min(jl(e,n,i),jl(t,n,i),jl(n,e,t),jl(i,e,t))}function jl(e,t,n){const i=n.sub(t),o=i.len2();if(o<=ek)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 Gl(e,t,n,i,o){for(let s=0;s<e.edges.length;s+=1){const o=Zl(e.edges[s],i),r=Zl(e.edges[(s+1)%e.edges.length],i);o.end!==r.start&&fd(`Packaging face "${t.id}" ${n} is not continuous between edges "${e.edges[s].edgeId}" and "${e.edges[(s+1)%e.edges.length].edgeId}".`)}const r=((e,t)=>{const n=[];for(const i of e.edges){const e=t.get(i.edgeId);("forward"===i.direction?e.samples:[...e.samples].reverse()).forEach((e,t)=>{(0===n.length||t>0)&&n.push(e)})}return n.length>1&&n[0].dist2(n[n.length-1])<=ek&&n.pop(),n})(e,o);Math.abs(Ql(r))<=ek&&fd(`Packaging face "${t.id}" ${n} must form a non-zero area.`),Jl(r)&&fd(`Packaging face "${t.id}" ${n} must not self-intersect.`)}function Zl(e,t){const n=t.get(e.edgeId);return"forward"===e.direction?{start:n.fromPointId,end:n.toPointId}:{start:n.toPointId,end:n.fromPointId}}function Ql(e){let t=0;for(let n=0;n<e.length;n+=1){const i=e[n],o=e[(n+1)%e.length];t+=i.x*o.y-o.x*i.y}return t/2}function Jl(e){for(let t=0;t<e.length;t+=1){const n=e[t],i=e[(t+1)%e.length];for(let o=t+1;o<e.length;o+=1)if(o!==t&&o!==t+1&&(0!==t||o!==e.length-1)&&td(n,i,e[o],e[(o+1)%e.length]))return!0}return!1}function ed(e,t){for(let n=0;n<e.length;n+=1)for(let i=0;i<t.length;i+=1)if(td(e[n],e[(n+1)%e.length],t[i],t[(i+1)%t.length]))return!0;return!1}function td(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)<=ek)return nd(e,n,i)||nd(t,n,i)||nd(n,e,t)||nd(i,e,t);const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=-1e-8&&l<=1.00000001&&d>=-1e-8&&d<=1.00000001}function nd(e,t,n){const i=n.sub(t),o=e.sub(t);if(Math.abs(i.x*o.y-i.y*o.x)>ek)return!1;const r=o.x*i.x+o.y*i.y;return r>=-1e-8&&r<=i.len2()+ek}function id(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.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 od(e,t){const n=dd(e,t);gd(n,["x","y"],[],t),hd(n.x,`${t}.x`),hd(n.y,`${t}.y`)}function rd(e,t){dd(e,t),sd(e,t,new WeakSet)}function sd(e,t,n){if(null!==e&&"string"!=typeof e&&"boolean"!=typeof e)if("number"!=typeof e){if("object"!=typeof e&&fd(`${t} must contain only JSON values.`),n.has(e)&&fd(`${t} must not contain circular references.`),n.add(e),Array.isArray(e))e.forEach((e,i)=>sd(e,`${t}[${i}]`,n));else{const i=Object.getPrototypeOf(e);i!==Object.prototype&&null!==i&&fd(`${t} must contain only plain JSON objects.`);for(const[o,r]of Object.entries(e))sd(r,`${t}.${o}`,n)}n.delete(e)}else hd(e,t)}function ad(e){if(!e||"object"!=typeof e||Object.isFrozen(e))return e;for(const t of Object.values(e))ad(t);return Object.freeze(e)}function ld(e,t,n){ud(e,n);const i=e;return t.has(i)&&fd(`Duplicate ${n.split(".").at(-1)??"id"} "${i}" at ${n}.`),t.add(i),i}function dd(e,t){e&&"object"==typeof e&&!Array.isArray(e)||fd(`${t} must be an object.`);const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n&&fd(`${t} must be a plain object.`),e}function cd(e,t){return Array.isArray(e)||fd(`${t} must be an array.`),e}function ud(e,t){"string"==typeof e&&0!==e.trim().length||fd(`${t} must be a non-empty string.`)}function hd(e,t){"number"==typeof e&&Number.isFinite(e)||fd(`${t} must be a finite number.`)}function pd(e,t){hd(e,t),e<=0&&fd(`${t} must be greater than zero.`)}function gd(e,t,n,i){const o=new Set([...t,...n]);for(const r of t)Object.prototype.hasOwnProperty.call(e,r)||fd(`${i}.${r} is required.`);for(const r of Object.keys(e))o.has(r)||fd(`${i}.${r} is not part of Packaging schema version 1.`)}function fd(e){throw new Error(e)}function md(e,t=yd(e)){const n=e.props.showBleed?t.outerBounds:t.bounds,i=[new $I(n.minX,n.minY),new $I(n.maxX,n.minY),new $I(n.maxX,n.maxY),new $I(n.minX,n.maxY)];if(e.props.showSafeZones)for(const o of t.safeZonesById.values())i.push(...o.samples.map(e=>e.clone()));return LI.FromPoints(i)}function yd(e){return qa(e.props.document,e.props.viewSide)}function Sd(e,t){return Object.prototype.hasOwnProperty.call(e.props.faceFillOverrides,t)?e.props.faceFillOverrides[t]:e.props.faceFill}function bd(e,t,n){
20
+ return Qx("g",{"data-packaging-layer":"dieline",children:[xd(e,rk,Gv.cutStroke,n,t),xd(e,sk,Gv.creaseStroke,n,t,!0),xd(e,ak,Gv.annotationStroke,n,t,!0)]})}function xd(e,t,n,i,o,r=!1){return e.filter(e=>t.has(e.edge.operation)).map(e=>Zx("path",{"data-packaging-edge-id":e.edge.id,"data-packaging-edge-operation":e.edge.operation,"data-packaging-hole-outline":o.has(e.edge.id)?"true":void 0,d:e.path,...wd(n,i),strokeDasharray:r?il(e.edge.operation,i):void 0,strokeLinecap:r?"butt":"round"},e.edge.id))}function Id(e,t){return e/Math.max(t,1)}function wd(e,t){return{fill:"none",stroke:F(e),strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"}}function Pd(e){return`${e.x} ${e.y} ${Math.max(e.w,1)} ${Math.max(e.h,1)}`}function vd(e){return"packaging"===e?.type}function kd(e,t,n=[...e.edgesById.values()].filter(e=>!1!==e.edge.visible)){return[...Cd(n,lk,Gv.cutStroke,Gv.lineWidth,t,e.holeEdgeIds),...Cd(n,dk,Gv.creaseStroke,Gv.lineWidth,t,e.holeEdgeIds,!0),...Cd(n,ck,Gv.annotationStroke,Gv.lineWidth,t,e.holeEdgeIds,!0)]}function Cd(e,t,n,i,o,r,s=!1){return e.filter(e=>t.has(e.edge.operation)).map(e=>({tag:"path",attrs:{d:e.path,...Td(o,n,i),"stroke-dasharray":s?il(e.edge.operation,i):void 0,"stroke-linecap":s?"butt":"round","data-packaging-edge-id":e.edge.id,"data-packaging-edge-operation":e.edge.operation,"data-packaging-hole-outline":!!r.has(e.edge.id)||void 0}}))}function Td(e,t,n){return{fill:"none",stroke:e.resolveColor(t),"stroke-width":n,"stroke-linecap":"round","stroke-linejoin":"round","vector-effect":"non-scaling-stroke"}}function Md(e,t){return{id:e,isVisible:e=>"packaging"===e.selection.commonShapeType,isEnabled:e=>e.selection.selectedShapes.some(e=>Rd(e)&&!e.isLocked&&Ad(e,t)),getValue:e=>Ed(e.selection.selectedShapes,t),run({context:e,value:n}){const i="boolean"==typeof n?n:!0!==Ed(e.selection.selectedShapes,t),o=e.selection.selectedShapes.filter(Rd).filter(e=>!e.isLocked&&Ad(e,t)).map(e=>({id:e.id,props:{[t]:i}}));o.length>0&&e.editor.commands.updateShapes(o,{source:"user"})}}}function Ed(e,t){let n;for(const i of e){if(!Rd(i))continue;const e=i.props[t];if(void 0===n)n=e;else if(n!==e)return null}return n??null}function Bd(e){let t;for(const n of e){if(!Rd(n))continue;const e="inside"===n.props.viewSide;if(void 0===t)t=e;else if(t!==e)return null}return t??null}function Ad(e,t){return"showSafeZones"===t?(e=>(e.props.document.surfaces[e.props.viewSide].prepress?.safeZones.length??0)>0)(e):"dielineOnTop"===t||(e=>(e.props.document.surfaces[e.props.viewSide].prepress?.bleedContours.length??0)>0)(e)}function Rd(e){return"packaging"===e.type}function $d(e,t={}){if(e.startsWith("AutoCAD Binary DXF"))throw new Error("Binary DXF files are not supported. Save the drawing as ASCII DXF and try again.");const n=(e=>{const t=e.replace(/^\uFEFF/,"").split(/\r?\n/),n=[];for(let i=0;i+1<t.length;i+=2){const e=t[i].trim();if(0===e.length&&0===t[i+1].trim().length)continue;const o=Number(e);if(!Number.isInteger(o))throw new Error(`Invalid DXF group code at line ${i+1}.`);n.push({code:o,value:t[i+1].trim()})}if(0===n.length)throw new Error("The DXF file is empty.");return n})(e),i=Ld(n,"HEADER"),o=Ld(n,"TABLES"),r=Ld(n,"ENTITIES");if(0===r.length)throw new Error("The DXF file does not contain an ENTITIES section.");const s=(e=>{const t=_d(e,"$INSUNITS");if(null===t)return null;const n=Number(t);return Number.isFinite(n)?n:null})(i)??0,a=_d(i,"$ACADVER"),l=(e=>{switch(e){case 1:return{unit:"in",scale:1};case 2:return{unit:"in",scale:12};case 3:return{unit:"in",scale:63360};case 4:return{unit:"mm",scale:1};case 5:return{unit:"cm",scale:1};case 6:return{unit:"m",scale:1};case 7:return{unit:"m",scale:1e3};case 8:return{unit:"in",scale:1e-6};case 9:return{unit:"in",scale:.001};case 10:return{unit:"in",scale:36};case 11:return{unit:"mm",scale:1e-7};case 12:return{unit:"mm",scale:1e-6};case 13:return{unit:"mm",scale:.001};case 14:return{unit:"m",scale:.1};case 15:return{unit:"m",scale:10};case 16:return{unit:"m",scale:100};case 21:return{unit:"in",scale:12.000024000048};default:return{unit:"unitless",scale:1}}})(s),d=(e=>{const t=new Map;for(const n of Fd(e)){if("LAYER"!==n.type)continue;const e=Hd(n,2)??"0";t.set(e,{name:e,lineType:Hd(n,6)??"Continuous"})}return t})(o),c=Fd(r);if(c.length>5e4)throw new Error(`The DXF file contains more than ${5e4.toLocaleString()} entities.`);const u=new Set,h=(({records:e,layers:t,unitMapping:n,options:i,ignoredEntityTypes:o})=>{const r=[];for(let s=0;s<e.length;s+=1){const a=e[s];if("POLYLINE"===a.type){const o=[];let l=s+1;for(;l<e.length&&"VERTEX"===e[l].type;){const t=Vd(e[l]);t&&o.push(t),l+=1}const d=Wd(a,70)??0;r.push(...Ud({record:a,vertices:o,isClosed:!!(1&d),layers:t,unitMapping:n,options:i})),s="SEQEND"===e[l]?.type?l:l-1;continue}const l=Dd({record:a,layers:t,unitMapping:n,options:i});l?r.push(...l):rc(a.type)&&o.add(a.type)}return r})({records:c,layers:d,unitMapping:l,options:t,ignoredEntityTypes:u});if(0===h.length){const e=[...u].sort().join(", ");throw new Error(e.length>0?`The DXF file does not contain supported dieline geometry. Ignored entity types: ${e}.`:"The DXF file does not contain supported dieline geometry.")}const p=h.length>2e3,g=p?h:(e=>{const t=e.flatMap(e=>[e.from,e.to]),n=e.map(()=>[0,1]);for(let o=0;o<e.length;o+=1){const i=e[o];if("line"===i.geometry.type)for(const e of t){const t=jd(e,i.from,i.to);null!==t&&t>xk&&t<.999999&&n[o].push(t)}}for(let o=0;o<e.length;o+=1){const t=e[o];if("line"===t.geometry.type)for(let i=o+1;i<e.length;i+=1){const r=e[i];if("line"!==r.geometry.type)continue;const s=Gd(t.from,t.to,r.from,r.to);s&&(s.left>xk&&s.left<.999999&&n[o].push(s.left),s.right>xk&&s.right<.999999&&n[i].push(s.right))}}const i=[];for(let o=0;o<e.length;o+=1){const t=e[o];if("line"!==t.geometry.type){i.push(t);continue}const r=[...new Set(n[o].map(e=>oc(e)))].sort((e,t)=>e-t);for(let e=0;e<r.length-1;e+=1){const n=Jd(t.from,t.to,r[e]),o=Jd(t.from,t.to,r[e+1]);ec(n,o)||i.push({...t,sourceId:2===r.length?t.sourceId:`${t.sourceId}:${e+1}`,from:n,to:o,samples:[n,o]})}}return i})(h);(e=>{let t=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY;for(const o of e)for(const e of o.samples)t=Math.min(t,e.x),n=Math.min(n,e.y);const i=e=>({x:oc(e.x-t),y:oc(e.y-n)});for(const o of e)o.from=i(o.from),o.to=i(o.to),o.samples=o.samples.map(i),"quadratic"===o.geometry.type?o.geometry.control=i(o.geometry.control):"cubic"===o.geometry.type&&(o.geometry.control1=i(o.geometry.control1),o.geometry.control2=i(o.geometry.control2))})(g);const{points:f,edges:m,samplesByEdgeId:y}=(e=>{const t=(()=>{const e=[],t=new Map;return{points:e,add(n){const i=Math.round(n.x/xk),o=Math.round(n.y/xk);for(let l=-1;l<=1;l+=1)for(let r=-1;r<=1;r+=1)for(const s of t.get(`${i+l}:${o+r}`)??[]){const t=e[s];if(Math.hypot(t.x-n.x,t.y-n.y)<=xk)return t.id}const r=`dxf-point:${e.length+1}`,s=e.length;e.push({id:r,x:oc(n.x),y:oc(n.y)});const a=`${i}:${o}`;return t.set(a,[...t.get(a)??[],s]),r}}})(),n=[],i=new Map;return e.forEach((e,o)=>{const r=t.add(e.from),s=t.add(e.to);if(r===s)return;const a=`dxf-edge:${o+1}`;n.push({id:a,fromPointId:r,toPointId:s,geometry:e.geometry,operation:e.operation,meta:{dxfHandle:e.sourceId,dxfEntityType:e.sourceType,layer:e.layer,lineType:e.lineType}}),i.set(a,e.samples)}),{points:t.points,edges:n,samplesByEdgeId:i}})(g),S=p?[]:(({edges:e,samplesByEdgeId:t})=>{const n=e.filter(e=>"annotation"!==e.operation&&"construction"!==e.operation&&"custom"!==e.operation),i=new Map,o=new Map;for(const a of n){const e=t.get(a.id);if(!e||e.length<2)continue;const n=[...e],r=[...e].reverse(),s={key:`${a.id}:forward`,reverseKey:`${a.id}:reverse`,edgeId:a.id,fromPointId:a.fromPointId,toPointId:a.toPointId,direction:"forward",angle:Zd(n),samples:n},l={key:`${a.id}:reverse`,reverseKey:`${a.id}:forward`,edgeId:a.id,fromPointId:a.toPointId,toPointId:a.fromPointId,direction:"reverse",angle:Zd(r),samples:r};for(const t of[s,l]){i.set(t.key,t);const e=o.get(t.fromPointId)??[];e.push(t),o.set(t.fromPointId,e)}}for(const a of o.values())a.sort((e,t)=>e.angle-t.angle||e.key.localeCompare(t.key));const r=new Set,s=[];for(const a of i.values()){if(r.has(a.key))continue;const e=[],t=new Set;let n=a;for(;n&&!t.has(n.key)&&e.length<=i.size;){e.push(n),t.add(n.key);const i=o.get(n.toPointId)??[],r=n.reverseKey,s=i.findIndex(e=>e.key===r);n=s<0?void 0:i[(s-1+i.length)%i.length]}for(const i of t)r.add(i);if(n?.key!==a.key||e.length<3)continue;if(new Set(e.map(e=>e.edgeId)).size!==e.length)continue;const l=e.flatMap((e,t)=>0===t?[...e.samples]:e.samples.slice(1));l.length>1&&ec(l[0],l[l.length-1])&&l.pop(),Qd(l)<=Ik||s.push({id:`dxf-face:${s.length+1}`,name:`Face ${s.length+1}`,outer:{edges:e.map(e=>({edgeId:e.edgeId,direction:e.direction}))},meta:{source:"dxf-inferred"}})}return s})({edges:m,samplesByEdgeId:y}),b=(e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)})(e),x=(e=>{const t=e?.trim();return t?t.replace(/\.dxf$/i,""):null})(t.fileName),I={schemaVersion:1,id:t.documentId??`packaging-document:dxf:${b}`,revision:t.revision??`dxf:${b}`,name:x??"Imported DXF",unit:l.unit,coordinateSystem:"top-left-y-down",points:f,edges:m,faces:S,surfaces:{outside:{},inside:{}},source:{provider:"dxf",...x?{externalId:x}:{},...a?{revision:a}:{}},meta:{dxf:{...a?{acadVersion:a}:{},unitsCode:s,importedEntityCount:sc(c),importedEdgeCount:m.length,inferredFaceCount:S.length,ignoredEntityTypes:[...u].sort(),layers:[...new Set(g.map(e=>e.layer))].sort(),...p?{topologyInferenceLimited:!0}:{}}}};try{return Dl(I)}catch(w){if(0===S.length)throw w;return Dl({...I,faces:[],meta:{...I.meta,dxf:{...I.meta?.dxf,inferredFaceCount:0,faceInferenceSkipped:!0}}})}}function Ld(e,t){let n=null;const i=[];for(let o=0;o<e.length;o+=1){const r=e[o];if(0===r.code&&"SECTION"===r.value){const t=e[o+1];n=2===t?.code?t.value:null,o+=2===t?.code?1:0;continue}0!==r.code||"ENDSEC"!==r.value?n===t&&i.push(r):n=null}return i}function Fd(e){const t=[];let n=null;for(const i of e)0===i.code?(n&&t.push(n),n={type:i.value.toUpperCase(),pairs:[]}):n&&n.pairs.push(i);return n&&t.push(n),t}function Dd({record:e,layers:t,unitMapping:n,options:i}){const o=Hd(e,5)??`${e.type.toLowerCase()}`,r=Hd(e,8)??"0",s=t.get(r)??{name:r,lineType:Hd(e,6)??"Continuous"},a=Hd(e,6)??s.lineType,l=Yd({layer:s.name,lineType:a,options:i}),d=e=>({x:e.x*n.scale,y:-e.y*n.scale}),c={sourceId:o,sourceType:e.type,layer:s.name,lineType:a,operation:l};switch(e.type){case"LINE":{const t=Kd(e,10,20),n=Kd(e,11,21);if(!t||!n||ec(t,n))return[];const i=d(t),o=d(n);return[{...c,from:i,to:o,geometry:{type:"line"},samples:[i,o]}]}case"ARC":{const t=Kd(e,10,20),i=Wd(e,40),o=Wd(e,50),r=Wd(e,51);if(!t||!ic(i)||null===o||null===r)return[];const s=nc(o),a=tc(nc(r)-s);return a<=xk?[]:[Od({...c,center:t,radiusX:i,radiusY:i,rotation:0,start:s,delta:a,transform:d,scale:n.scale})]}case"CIRCLE":{const t=Kd(e,10,20),i=Wd(e,40);return t&&ic(i)?[0,1,2,3].map(e=>Od({...c,sourceId:`${o}:${e+1}`,center:t,radiusX:i,radiusY:i,rotation:0,start:e*Math.PI/2,delta:Math.PI/2,transform:d,scale:n.scale})):[]}case"ELLIPSE":{const t=Kd(e,10,20),i=Kd(e,11,21),r=Wd(e,40);if(!t||!i||!ic(r))return[];const s=Math.hypot(i.x,i.y);if(!ic(s))return[];const a=Math.atan2(i.y,i.x),l=Wd(e,41)??0;let u=tc((Wd(e,42)??bk)-l);u<=xk&&(u=bk);const h=u>=bk-xk?4:1;return Array.from({length:h},(e,i)=>Od({...c,sourceId:1===h?o:`${o}:${i+1}`,center:t,radiusX:s,radiusY:s*r,rotation:a,start:l+u*i/h,delta:u/h,transform:d,scale:n.scale}))}case"LWPOLYLINE":return Ud({record:e,vertices:qd(e),isClosed:!!(1&(Wd(e,70)??0)),layers:t,unitMapping:n,options:i});default:return null}}function Ud({record:e,vertices:t,isClosed:n,layers:i,unitMapping:o,options:r}){if(t.length<2)return[];const s=Hd(e,5)??e.type.toLowerCase(),a=Hd(e,8)??"0",l=i.get(a)??{name:a,lineType:Hd(e,6)??"Continuous"},d=Hd(e,6)??l.lineType,c=Yd({layer:l.name,lineType:d,options:r}),u=e=>({x:e.x*o.scale,y:-e.y*o.scale}),h=n?t.length:t.length-1,p=[];for(let g=0;g<h;g+=1){const n=t[g],i=t[(g+1)%t.length];if(ec(n,i))continue;const r={sourceId:`${s}:${g+1}`,sourceType:e.type,layer:l.name,lineType:d,operation:c};if(Math.abs(n.bulge)<=xk){const e=u(n),t=u(i);p.push({...r,from:e,to:t,geometry:{type:"line"},samples:[e,t]});continue}p.push(zd({...r,from:n,to:i,bulge:n.bulge,transform:u,scale:o.scale}))}return p}function zd({from:e,to:t,bulge:n,transform:i,scale:o,...r}){const s=t.x-e.x,a=t.y-e.y,l=Math.hypot(s,a),d=l*(1-n*n)/(4*n),c={x:(e.x+t.x)/2-a/l*d,y:(e.y+t.y)/2+s/l*d},u=Math.atan2(e.y-c.y,e.x-c.x),h=4*Math.atan(n),p=l*(1+n*n)/(4*Math.abs(n));return{...r,from:i(e),to:i(t),geometry:{type:"arc",radiusX:p*o,radiusY:p*o,rotation:0,largeArc:Math.abs(h)>Math.PI,sweep:h<0},samples:Xd({center:c,radiusX:p,radiusY:p,rotation:0,start:u,delta:h,transform:i})}}function Od({center:e,radiusX:t,radiusY:n,rotation:i,start:o,delta:r,transform:s,scale:a,...l}){const d=Nd({center:e,radiusX:t,radiusY:n,rotation:i,angle:o}),c=Nd({center:e,radiusX:t,radiusY:n,rotation:i,angle:o+r});return{...l,from:s(d),to:s(c),geometry:{type:"arc",radiusX:t*a,radiusY:n*a,rotation:(u=-i,180*u/Math.PI),largeArc:Math.abs(r)>Math.PI,sweep:r<0},samples:Xd({center:e,radiusX:t,radiusY:n,rotation:i,start:o,delta:r,transform:s})};var u}function Xd({center:e,radiusX:t,radiusY:n,rotation:i,start:o,delta:r,transform:s}){const a=Math.max(4,Math.ceil(Math.abs(r)/(Math.PI/12)));return Array.from({length:a+1},(l,d)=>s(Nd({center:e,radiusX:t,radiusY:n,rotation:i,angle:o+r*d/a})))}function Nd({center:e,radiusX:t,radiusY:n,rotation:i,angle:o}){const r=Math.cos(i),s=Math.sin(i);return{x:e.x+t*Math.cos(o)*r-n*Math.sin(o)*s,y:e.y+t*Math.cos(o)*s+n*Math.sin(o)*r}}function Yd({layer:e,lineType:t,options:n}){const i=n.operationByLayer?.[e];if(i)return i;const o=`${e} ${t}`.toLocaleLowerCase();return/perforat|\bperf\b|点断|齿线/.test(o)?"perforation":/half[ _-]*cut|半切/.test(o)?"half-cut":/kiss[ _-]*cut|吻切/.test(o)?"kiss-cut":/\bscore\b|压线/.test(o)?"score":/crease|fold|dash|bend|折线|折痕|压痕/.test(o)?"crease":/construction|guide|辅助|参考/.test(o)?"construction":/annotation|dimension|text|mark|注释|标注/.test(o)?"annotation":/cut|knife|dieline|die[ _-]*line|solid|刀线|模切/.test(o)?"cut":/continuous|bylayer|byblock/.test(t.toLocaleLowerCase())?n.defaultOperation??"cut":"crease"}function _d(e,t){for(let n=0;n<e.length;n+=1)if(9===e[n].code&&e[n].value===t)return e[n+1]?.value??null;return null}function Hd(e,t){return e.pairs.find(e=>e.code===t)?.value??null}function Wd(e,t){const n=Hd(e,t);if(null===n)return null;const i=Number(n);return Number.isFinite(i)?i:null}function Kd(e,t,n){const i=Wd(e,t),o=Wd(e,n);return null===i||null===o?null:{x:i,y:o}}function Vd(e){const t=Kd(e,10,20);return t?{...t,bulge:Wd(e,42)??0}:null}function qd(e){const t=[];for(const n of e.pairs)if(10===n.code){const e=Number(n.value);Number.isFinite(e)&&t.push({x:e,y:0,bulge:0})}else if(20===n.code&&t.length>0){const e=Number(n.value);Number.isFinite(e)&&(t[t.length-1].y=e)}else if(42===n.code&&t.length>0){const e=Number(n.value);Number.isFinite(e)&&(t[t.length-1].bulge=e)}return t}function jd(e,t,n){const i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(r<=1e-12)return null;const s=((e.x-t.x)*i+(e.y-t.y)*o)/r;if(s<-1e-6||s>1.000001)return null;const a=Jd(t,n,s);return Math.hypot(a.x-e.x,a.y-e.y)<=xk?Math.max(0,Math.min(1,s)):null}function Gd(e,t,n,i){const o=t.x-e.x,r=t.y-e.y,s=i.x-n.x,a=i.y-n.y,l=o*a-r*s;if(Math.abs(l)<=xk)return null;const d=n.x-e.x,c=n.y-e.y,u=(d*a-c*s)/l,h=(d*r-c*o)/l;return u>=-1e-6&&u<=1.000001&&h>=-1e-6&&h<=1.000001?{left:u,right:h}:null}function Zd(e){const t=e[0],n=e.find(e=>!ec(e,t))??e[1];return tc(Math.atan2(n.y-t.y,n.x-t.x))}function Qd(e){let t=0;for(let n=0;n<e.length;n+=1){const i=e[n],o=e[(n+1)%e.length];t+=i.x*o.y-o.x*i.y}return t/2}function Jd(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function ec(e,t){return Math.hypot(e.x-t.x,e.y-t.y)<=xk}function tc(e){return(e%bk+bk)%bk}function nc(e){return e*Math.PI/180}function ic(e){return null!==e&&Number.isFinite(e)&&e>0}function oc(e){return Math.round(1e9*e)/1e9}function rc(e){return!wk.has(e)&&"VERTEX"!==e&&"SEQEND"!==e&&"ENDSEC"!==e}function sc(e){return e.filter(e=>wk.has(e.type)).length}function ac(e,t=1){switch(e){case"mm":return 2.834645669291339;case"cm":return 28.34645669291339;case"m":return 2834.645669291339;case"in":return Pk;case"pt":return 1;case"px":return.75;case"unitless":return cc(t,1,"Packaging PDF unitless points per unit")}}function lc({page:e,path:t,style:n,pathOrigin:i,pointsPerUnit:o,lineWidthPoints:r,pdfLib:s}){e.drawSvgPath(t,{x:i.x,y:i.y,scale:o,borderColor:s.cmyk(...n.color),borderWidth:r/o,borderDashArray:n.dashArrayPoints?.map(e=>e/o),borderLineCap:n.dashArrayPoints?s.LineCapStyle.Butt:s.LineCapStyle.Round})}function dc(e,t){return"unitless"===e?14.173228346456694/t:5*ac("mm")/t}function cc(e,t,n){const i=e??t;if(!Number.isFinite(i)||i<=0)throw new Error(`${n} must be a positive finite number.`);return i}function uc(e,t,n){const i=e??t;if(!Number.isFinite(i)||i<0)throw new Error(`${n} must be a non-negative finite number.`);return i}function hc(e,t){return`${e.normalize("NFKC").replace(/[<>:"/\\|?*\u0000-\u001f]/g,"-").replace(/[. ]+$/g,"").trim()||"packaging"}-${t}-dieline.pdf`}function pc({children:e}){const[t,n]=qx(null),i=Nx(e=>{n(e)},[]),o=Kx(()=>({registerTarget:i,target:t}),[i,t]);
21
+ return Zx(Tk.Provider,{value:o,children:e})}function gc(){const{registerTarget:e}=mc();
22
+ return Zx("div",{ref:e,className:"land-canvas__floating-portal-host","data-ui":"canvas-kit-floating-portal-host"})}function fc(){return mc().target}function mc(){const e=Yx(Tk);if(!e)throw new Error("CanvasKit floating content must be rendered inside CanvasKitRoot.");return e}function yc({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const i=fc();return i?fI(Zx("div",{"data-ui":n,className:Sc("land-canvas__floating-toolbar-layer",t),children:e}),i):null}function Sc(...e){return e.filter(Boolean).join(" ")}function bc(e){_x(()=>{const t=e.current;if(!t)return;const n=e=>{(e=>e.scrollHeight>e.clientHeight)(t)||function(e,t){const n=(e=>{const t=e?.getRootNode();return t instanceof Document||t instanceof ShadowRoot?pr(t):pr()})(t);return!!n&&(n.dispatchEvent(new WheelEvent("wheel",{altKey:e.altKey,bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,composed:!0,ctrlKey:e.ctrlKey,deltaMode:e.deltaMode,deltaX:e.deltaX,deltaY:e.deltaY,deltaZ:e.deltaZ,metaKey:e.metaKey,screenX:e.screenX,screenY:e.screenY,shiftKey:e.shiftKey,view:window})),!0)}(e,t)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",n,{passive:!1}),()=>{t.removeEventListener("wheel",n)}},[e])}function xc(e,t,n){return Ek(e,Mk(t,n))}function Ic(e,t){return"function"==typeof e?e(t):e}function wc(e){return e.split("-")[0]}function Pc(e){return e.split("-")[1]}function vc(e){return"x"===e?"y":"x"}function kc(e){return"y"===e?"height":"width"}function Cc(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function Tc(e){return vc(Cc(e))}function Mc(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function Ec(e){const t=wc(e);return $k[t]+e.slice(t.length)}function Bc(e){const{x:t,y:n,width:i,height:o}=e;return{width:i,height:o,top:n,left:t,right:t+i,bottom:n+o,x:t,y:n}}function Ac(e,t,n){let{reference:i,floating:o}=e;const r=Cc(t),s=Tc(t),a=kc(s),l=wc(t),d="y"===r,c=i.x+i.width/2-o.width/2,u=i.y+i.height/2-o.height/2,h=i[a]/2-o[a]/2;let p;switch(l){case"top":p={x:c,y:i.y-o.height};break;case"bottom":p={x:c,y:i.y+i.height};break;case"right":p={x:i.x+i.width,y:u};break;case"left":p={x:i.x-o.width,y:u};break;default:p={x:i.x,y:i.y}}switch(Pc(t)){case"start":p[s]-=h*(n&&d?-1:1);break;case"end":p[s]+=h*(n&&d?-1:1)}return p}async function Rc(e,t){var n;void 0===t&&(t={});const{x:i,y:o,platform:r,rects:s,elements:a,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:c="viewport",elementContext:u="floating",altBoundary:h=!1,padding:p=0}=Ic(t,e),g=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(p),f=a[h?"floating"===u?"reference":"floating":u],m=Bc(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(f)))||n?f:f.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:d,rootBoundary:c,strategy:l})),y="floating"===u?{x:i,y:o,width:s.floating.width,height:s.floating.height}:s.reference,S=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),b=await(null==r.isElement?void 0:r.isElement(S))&&await(null==r.getScale?void 0:r.getScale(S))||{x:1,y:1},x=Bc(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:S,strategy:l}):y);return{top:(m.top-x.top+g.top)/b.y,bottom:(x.bottom-m.bottom+g.bottom)/b.y,left:(m.left-x.left+g.left)/b.x,right:(x.right-m.right+g.right)/b.x}}function $c(){return"undefined"!=typeof window}function Lc(e){return Uc(e)?(e.nodeName||"").toLowerCase():"#document"}function Fc(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Dc(e){var t;return null==(t=(Uc(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Uc(e){return!!$c()&&(e instanceof Node||e instanceof Fc(e).Node)}function zc(e){return!!$c()&&(e instanceof Element||e instanceof Fc(e).Element)}function Oc(e){return!!$c()&&(e instanceof HTMLElement||e instanceof Fc(e).HTMLElement)}function Xc(e){return!(!$c()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Fc(e).ShadowRoot)}function Nc(e){const{overflow:t,overflowX:n,overflowY:i,display:o}=Vc(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+n)&&"inline"!==o&&"contents"!==o}function Yc(e){return/^(table|td|th)$/.test(Lc(e))}function _c(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Hc(e){const t=zc(e)?Vc(e):e;return Nk(t.transform)||Nk(t.translate)||Nk(t.scale)||Nk(t.rotate)||Nk(t.perspective)||!Wc()&&(Nk(t.backdropFilter)||Nk(t.filter))||Ok.test(t.willChange||"")||Xk.test(t.contain||"")}function Wc(){return null==mI&&(mI="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),mI}function Kc(e){return/^(html|body|#document)$/.test(Lc(e))}function Vc(e){return Fc(e).getComputedStyle(e)}function qc(e){return zc(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function jc(e){if("html"===Lc(e))return e;const t=e.assignedSlot||e.parentNode||Xc(e)&&e.host||Dc(e);return Xc(t)?t.host:t}function Gc(e){const t=jc(e);return Kc(t)?e.ownerDocument?e.ownerDocument.body:e.body:Oc(t)&&Nc(t)?t:Gc(t)}function Zc(e,t,n){var i;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=Gc(e),r=o===(null==(i=e.ownerDocument)?void 0:i.body),s=Fc(o);if(r){const e=Qc(s);return t.concat(s,s.visualViewport||[],Nc(o)?o:[],e&&n?Zc(e):[])}return t.concat(o,Zc(o,[],n))}function Qc(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Jc(e){const t=Vc(e);let n=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const o=Oc(e),r=o?e.offsetWidth:n,s=o?e.offsetHeight:i,a=Bk(n)!==r||Bk(i)!==s;return a&&(n=r,i=s),{width:n,height:i,$:a}}function eu(e){return zc(e)?e:e.contextElement}function tu(e){const t=eu(e);if(!Oc(t))return Rk(1);const n=t.getBoundingClientRect(),{width:i,height:o,$:r}=Jc(t);let s=(r?Bk(n.width):n.width)/i,a=(r?Bk(n.height):n.height)/o;return s&&Number.isFinite(s)||(s=1),a&&Number.isFinite(a)||(a=1),{x:s,y:a}}function nu(e){const t=Fc(e);return Wc()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:Yk}function iu(e,t,n,i){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=eu(e);let s=Rk(1);t&&(i?zc(i)&&(s=tu(i)):s=tu(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Fc(e))&&t))(r,n,i)?nu(r):Rk(0);let l=(o.left+a.x)/s.x,d=(o.top+a.y)/s.y,c=o.width/s.x,u=o.height/s.y;if(r){const e=Fc(r),t=i&&zc(i)?Fc(i):i;let n=e,o=Qc(n);for(;o&&i&&t!==n;){const e=tu(o),t=o.getBoundingClientRect(),i=Vc(o),r=t.left+(o.clientLeft+parseFloat(i.paddingLeft))*e.x,s=t.top+(o.clientTop+parseFloat(i.paddingTop))*e.y;l*=e.x,d*=e.y,c*=e.x,u*=e.y,l+=r,d+=s,n=Fc(o),o=Qc(n)}}return Bc({width:c,height:u,x:l,y:d})}function ou(e,t){const n=qc(e).scrollLeft;return t?t.left+n:iu(Dc(e)).left+n}function ru(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ou(e,n),y:n.top+t.scrollTop}}function su(e,t,n){let i;if("viewport"===t)i=((e,t)=>{const n=Fc(e),i=Dc(e),o=n.visualViewport;let r=i.clientWidth,s=i.clientHeight,a=0,l=0;if(o){r=o.width,s=o.height;const e=Wc();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,l=o.offsetTop)}const d=ou(i);if(d<=0){const e=i.ownerDocument,t=e.body,n=getComputedStyle(t),o="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,s=Math.abs(i.clientWidth-t.clientWidth-o);s<=25&&(r-=s)}else d<=25&&(r+=d);return{width:r,height:s,x:a,y:l}})(e,n);else if("document"===t)i=(e=>{const t=Dc(e),n=qc(e),i=e.ownerDocument.body,o=Ek(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),r=Ek(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let s=-n.scrollLeft+ou(e);const a=-n.scrollTop;return"rtl"===Vc(i).direction&&(s+=Ek(t.clientWidth,i.clientWidth)-o),{width:o,height:r,x:s,y:a}})(Dc(e));else if(zc(t))i=((e,t)=>{const n=iu(e,!0,"fixed"===t),i=n.top+e.clientTop,o=n.left+e.clientLeft,r=Oc(e)?tu(e):Rk(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:o*r.x,y:i*r.y}})(t,n);else{const n=nu(e);i={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Bc(i)}function au(e,t){const n=jc(e);return!(n===t||!zc(n)||Kc(n))&&("fixed"===Vc(n).position||au(n,t))}function lu(e,t){const n=t.get(e);if(n)return n;let i=Zc(e,[],!1).filter(e=>zc(e)&&"body"!==Lc(e)),o=null;const r="fixed"===Vc(e).position;let s=r?jc(e):e;for(;zc(s)&&!Kc(s);){const t=Vc(s),n=Hc(s);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||Nc(s)&&!n&&au(e,s))?i=i.filter(e=>e!==s):o=t,s=jc(s)}return t.set(e,i),i}function du(e,t,n){function i(){d.x=ou(r)}const o=Oc(t),r=Dc(t),s="fixed"===n,a=iu(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const d=Rk(0);if(o||!o&&!s)if(("body"!==Lc(t)||Nc(r))&&(l=qc(t)),o){const e=iu(t,!0,s,t);d.x=e.x+t.clientLeft,d.y=e.y+t.clientTop}else r&&i();s&&!o&&r&&i();const c=!r||o||s?Rk(0):ru(r,l);return{x:a.left+l.scrollLeft-d.x-c.x,y:a.top+l.scrollTop-d.y-c.y,width:a.width,height:a.height}}function cu(e){return"static"===Vc(e).position}function uu(e,t){if(!Oc(e)||"fixed"===Vc(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Dc(e)===n&&(n=n.ownerDocument.body),n}function hu(e,t){const n=Fc(e);if(_c(e))return n;if(!Oc(e)){let t=jc(e);for(;t&&!Kc(t);){if(zc(t)&&!cu(t))return t;t=jc(t)}return n}let i=uu(e,t);for(;i&&Yc(i)&&cu(i);)i=uu(i,t);return i&&Kc(i)&&cu(i)&&!Hc(i)?n:i||(e=>{let t=jc(e);for(;Oc(t)&&!Kc(t);){if(Hc(t))return t;if(_c(t))return null;t=jc(t)}return null})(e)||n}function pu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function gu({editor:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:i,offset:o,placement:r}){_x(()=>{const s=i(),a=n.current;if(!s||!a)return;let l=!1,d=0;a.style.visibility="hidden";const c=()=>{const e=++d,n=fu("--toolbar-floating-shift-padding",8),i={top:fu("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((e,t,n)=>{const i={platform:_k,...n},o={...i.platform,_c:new Map};return(async(e,t,n)=>{const{placement:i="bottom",strategy:o="absolute",middleware:r=[],platform:s}=n,a=s.detectOverflow?s:{...s,detectOverflow:Rc},l=await(null==s.isRTL?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:c,y:u}=Ac(d,i,l),h=i,p=0;const g={};for(let f=0;f<r.length;f++){const n=r[f];if(!n)continue;const{name:m,fn:y}=n,{x:S,y:b,data:x,reset:I}=await y({x:c,y:u,initialPlacement:i,placement:h,strategy:o,middlewareData:g,rects:d,platform:a,elements:{reference:e,floating:t}});c=null!=S?S:c,u=null!=b?b:u,g[m]={...g[m],...x},I&&p<50&&(p++,"object"==typeof I&&(I.placement&&(h=I.placement),I.rects&&(d=!0===I.rects?await s.getElementRects({reference:e,floating:t,strategy:o}):I.rects),({x:c,y:u}=Ac(d,h,l))),f=-1)}return{x:c,y:u,placement:h,strategy:o,middlewareData:g}})(e,t,{...i,platform:o})})(s,a,{strategy:"fixed",placement:r,middleware:[Hk(o),Kk({fallbackPlacements:[...t],padding:i}),Wk({padding:i})]}).then(({placement:t,x:n,y:i})=>{l||e!==d||(a.dataset.placement=t,a.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(i)}px, 0)`,a.style.visibility="visible")})},u=function(e,t,n,i){void 0===i&&(i={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:s="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:l=!1}=i,d=eu(e),c=o||r?[...d?Zc(d):[],...t?Zc(t):[]]:[];c.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=d&&a?((e,t)=>{function n(){var e;clearTimeout(i),null==(e=o)||e.disconnect(),o=null}let i,o=null;const r=Dc(e);return function s(a,l){function d(t){const n=t[0].intersectionRatio;if(n!==l){if(!m)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}1!==n||pu(c,e.getBoundingClientRect())||s(),m=!1}void 0===a&&(a=!1),void 0===l&&(l=1),n();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:g}=c;if(a||t(),!p||!g)return;const f={rootMargin:-Ak(h)+"px "+-Ak(r.clientWidth-(u+p))+"px "+-Ak(r.clientHeight-(h+g))+"px "+-Ak(u)+"px",threshold:Ek(0,Mk(1,l))||1};let m=!0;try{o=new IntersectionObserver(d,{...f,root:r.ownerDocument})}catch(y){o=new IntersectionObserver(d,f)}o.observe(e)}(!0),n})(d,n):null;let h,p=-1,g=null;s&&(g=new ResizeObserver(e=>{let[i]=e;i&&i.target===d&&g&&t&&(g.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var e;null==(e=g)||e.observe(t)})),n()}),d&&!l&&g.observe(d),t&&g.observe(t));let f=l?iu(e):null;return l&&function t(){const i=iu(e);f&&!pu(f,i)&&n(),f=i,h=requestAnimationFrame(t)}(),n(),()=>{var e;c.forEach(e=>{o&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=g)||e.disconnect(),g=null,l&&cancelAnimationFrame(h)}}(s,a,c,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),h=Ro("CanvasKitFloatingPosition.pageTransform",e.pageTransformSignal,c,{fireImmediately:!1});return c(),()=>{l=!0,a.style.visibility="hidden",u(),h()}},[e,t,n,i,o,r])}function fu(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 mu({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",offset:i=8,surfaces:o}){return o.canShowFloatingSelectionToolbar?Zx(yu,{editor:o.context.editor,className:t,dataUi:n,offset:i,children:e}):null}function yu({children:e,className:t,dataUi:n,editor:i,offset:o}){return Oo(i.selectionTranslationActiveSignal)?null:Zx(Su,{className:t,dataUi:n,editor:i,offset:o,children:e})}function Su({children:e,className:t,dataUi:n,editor:i,offset:o}){const r=Oo(i.queries.selectionPageBoundsSignal);return r?Zx(bu,{anchor:{x:r.minX,y:r.minY,width:r.w,height:r.h},className:t,dataUi:n,editor:i,offset:o,children:e}):null}function bu({anchor:e,children:t,className:n,dataUi:i,editor:o,offset:r}){const s=Vx(null),a=Vx(null);return bc(a),gu({editor:o,fallbackPlacements:Vk,floatingRef:a,getReferenceElement:Nx(()=>s.current,[e.height,e.width,e.x,e.y]),offset:r,placement:"top-start"}),Qx(Gx,{children:[Zx(Xo,{dataUi:`${i}-page-space`,className:"land-canvas__floating-selection-page-space",children:Zx("div",{ref:s,"aria-hidden":"true",style:{position:"absolute",left:e.x,top:e.y,width:e.width,height:e.height,pointerEvents:"none"}})}),Zx("div",{ref:a,"data-ui":i,className:xu("land-canvas__floating-selection-anchor",n),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:t})]})}function xu(...e){return e.filter(Boolean).join(" ")}function Iu(e){return e}function wu({presenter:e}){function t({children:t}){
23
+ return Zx(Gs,{presenter:e,children:t})}return{id:"canvas-kit.text",requires:[Hv],product:()=>({providers:[{id:"canvas-kit.text-link-popover-presenter",component:t}]})}}function Pu(e){return t=>Zx(vu,{...t,icons:e})}function vu({icons:e,...t}){const n=fc();return n?fI(Zx(ku,{...t,icons:e}),n):null}function ku({icons:e,...t}){const{anchorElement:n,href:i,onOpen:o,onPopoverPointerEnter:r,onPopoverPointerLeave:s}=t,a=zo(),l=Vx(null),d=Nx(()=>n,[n]);return bc(l),gu({editor:a,fallbackPlacements:qk,floatingRef:l,getReferenceElement:d,offset:8,placement:"top"}),Qx("div",{ref:l,"aria-label":"Link preview",className:"land-canvas-kit__text-link-popover","data-ui":"rich-text-link-popover",role:"toolbar",onPointerEnter:r,onPointerLeave:s,onPointerDown:e=>{e.stopPropagation()},onClick:e=>{e.stopPropagation()},children:[Zx("button",{"aria-label":"Open link",className:"land-canvas-kit__text-link-popover-icon-button",title:"Open link",type:"button",onClick:o,children:e.open}),Zx("button",{"aria-label":`Open ${i}`,className:"land-canvas-kit__text-link-popover-link",title:i,type:"button",onClick:o,children:i})]})}function Cu(e,t={}){const n=t.enabled??!0,i=t.pageId,o=Nx(t=>n?e.subscribe(t):()=>{},[n,e]),r=Nx(()=>n?e.getSnapshot(i):jk,[n,i,e]);return jx(o,r,r)}function Tu(e){return Math.max(0,Math.min(1,e))}function Mu(e,t,n){return e.computeShapePositionedToPageTransform(t).applyToPoint(((e,t,n)=>{const i=e.computeShapePositionedBounds(t);return new $I(i.minX+i.w*n.x,i.minY+i.h*n.y)})(e,t,n))}function Eu(e,t,n,i){return((e,t,n,i)=>e.getShapeUtil(t).resolveBindingPoint(t,{editor:e,rawPagePoint:n,oppositePagePoint:i}))(e,t,Mu(e,t,n),i)}function Bu(e,t){const n="start"===t?e.props.start:e.props.end;return((e,t)=>{if(0===e.rotation&&0===e.skewX&&1===e.scaleX&&1===e.scaleY)return t;const n=new $I(e.x+e.props.w/2,e.y+e.props.h/2),i=t.sub(n),o=new $I(i.x*e.scaleX,i.y*e.scaleY);return n.add(new $I(o.x+Math.tan(e.skewX)*o.y,o.y).rot(e.rotation))})(e,new $I(e.x+n.x,e.y+n.y))}function Au(e,t,n){const i="start"===n?t.props.start:t.props.end;return e.computeShapeLocalToPageTransform(t).applyToPoint(new $I(i.x,i.y))}function Ru(e){return"start"===e?"end":"start"}function $u(e,t,n,i){const o=e.computeShapeLocalToPageTransform(t).tryInvert();if(!o)return null;const r=Fu(o.applyToPoint(n),o.applyToPoint(i)),s=e.getShapeUtil(t),a={...t,props:{...t.props,w:r.w,h:r.h,start:r.start,end:r.end}},l=de(s.getLocalToPageTransform(t).compose(FI.Translate(r.x,r.y)),s.getLocalBounds(a),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return l?{...a,...l}:null}function Lu(e,t,n,i){return $u(e,t,"start"===n?i:Au(e,t,"start"),"end"===n?i:Au(e,t,"end"))}function Fu(e,t){const n=Ou(e.x,t.x),i=Ou(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}}}function Du(e){return Nu(new $I(e.props.start.x,e.props.start.y).add(new $I(e.x,e.y)),new $I(e.props.end.x,e.props.end.y).add(new $I(e.x,e.y)),e.props.bend)}function Uu(e){return Nu(new $I(e.props.start.x,e.props.start.y),new $I(e.props.end.x,e.props.end.y),e.props.bend)}function zu(e,t,n){const i=$I.Med(e,t),o=t.sub(e);if(o.len()<1e-6)return 0;const r=o.per().normalize();return-qu(n.sub(i),r)}function Ou(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 Xu(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Nu(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=$I.Med(e,t),o=t.sub(e),r=o.len()?o.per().normalize():new $I(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 $I(o,r):null})(e,t,n);if(!i)return null;const o=i.dist(e);if(o<1e-6)return null;const r=((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),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,l,d;if(!Number.isFinite(s))return null;const c=Math.PI>s?1:0,u=(Gk-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]:_u(e,t,r,24),l=s||null===r?`M ${Xu(e.x)} ${Xu(e.y)} L ${Xu(t.x)} ${Xu(t.y)}`:`M ${Xu(e.x)} ${Xu(e.y)} A ${Xu(r.radius)} ${Xu(r.radius)} 0 ${r.largeArcFlag} ${r.sweepFlag} ${Xu(t.x)} ${Xu(t.y)}`,d={start:{terminal:"start",point:e,handle:e},end:{terminal:"end",point:t,handle:t},middle:o,bend:i,points:a,bounds:LI.FromPoints(a),path:l};return s?{type:"straight",...d,arc:null}:{type:"curved",...d,arc:r}}function Yu({start:e,end:t,middle:n,bend:i,arc:o,startHandle:r=e,endHandle:s=t}){const a=Hu(e,t,o);if(Math.abs(a)<1e-6||!Number.isFinite(a)||!Number.isFinite(o.radius)||o.radius<1e-6){const o=Nu(e,t,0);return{...o,start:{...o.start,handle:r},end:{...o.end,handle:s},middle:n,bend:i}}const l={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)},d=_u(e,t,l,24),c=`M ${Xu(e.x)} ${Xu(e.y)} A ${Xu(l.radius)} ${Xu(l.radius)} 0 ${l.largeArcFlag} ${l.sweepFlag} ${Xu(t.x)} ${Xu(t.y)}`;return{type:"curved",start:{terminal:"start",point:e,handle:r},end:{terminal:"end",point:t,handle:s},middle:n,arc:l,bend:i,points:d,bounds:LI.FromPoints(d),path:c}}function _u(e,t,n,i){const o=[],r=$I.Angle(n.center,e),s=Hu(e,t,n);for(let a=0;a<=i;a++)o.push(Ku(n.center,n.radius,r+s*(a/i)));return o}function Hu(e,t,n){return i=$I.Angle(n.center,e),o=$I.Angle(n.center,t),n.sweepFlag?((o-i)%Gk+Gk)%Gk:-((i-o)%Gk+Gk)%Gk;var i,o}function Wu(e,t,n,i){const o=$I.Angle(n.center,e),r=Hu(e,t,n);return Ku(n.center,n.radius,o+r*i)}function Ku(e,t,n){return e.add(new $I(Math.cos(n)*t,Math.sin(n)*t))}function Vu(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,qu(r,i)/o)),a=t.add(i.mul(s));return e.dist(a)}function qu(e,t){return e.x*t.x+e.y*t.y}function ju(e){return!!e&&"shape"===e.typeName&&"arrow"===e.type}function Gu(e){return!!e&&"binding"===e.typeName&&"arrow"===e.type}function Zu(e,t,n){return e.getBindingsFromShape(t.id).find(e=>Gu(e)&&e.props.terminal===n)??null}function Qu(e,t,n){const i=Au(e,t,n),o=Zu(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||ju(r)?{terminal:n,binding:o,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0}:{terminal:n,binding:o,target:r,handlePagePoint:Mu(e,r,o.props.normalizedAnchor),boundaryPagePoint:i,isArcBoundaryPoint:!1}}function Ju(e,t){const n=Qu(e,t,"start"),i=Qu(e,t,"end"),o=ih(e,t,n.handlePagePoint,i.handlePagePoint);return"curved"===o.type&&(lh(e,n,o,"start"),lh(e,i,o,"end")),{info:oh(o,n,i),fullInfo:o,bindingSegments:[dh(n,o),dh(i,o)].filter(e=>null!==e)}}function eh(e,t){if(!Zu(e,t,"start")&&!Zu(e,t,"end"))return Uu(t);const n=e.computeShapeLocalToPageTransform(t).tryInvert();return n?((e,t,n)=>{const i=nh(t.info,n);if("curved"!==t.info.type)return i;const o=Nu(n.applyToPoint(t.fullInfo.start.point),n.applyToPoint(t.fullInfo.end.point),e.props.bend);if("curved"!==o.type)return i;const r=n.applyToPoint(t.info.start.point),s=n.applyToPoint(t.info.end.point),a=((e,t,n)=>{const i=t.sub(e);if(i.len2()<1e-12)return null;const o=$I.Med(e,t),r=i.per().normalize(),s=n.sub(o);return o.add(r.mul(s.x*r.x+s.y*r.y))})(r,s,o.arc.center);if(!a)return i;const l={center:a,radius:a.dist(r),sweepFlag:o.arc.sweepFlag},d=Wu(r,s,l,.5);return Yu({start:r,end:s,middle:d,bend:zu(r,s,d),arc:l,startHandle:n.applyToPoint(t.info.start.handle),endHandle:n.applyToPoint(t.info.end.handle)})})(t,Ju(e,t),n):Nu(new $I(t.props.start.x,t.props.start.y),new $I(t.props.end.x,t.props.end.y),t.props.bend)}function th(e,t,n){return{...e,start:{...e.start,handle:t},end:{...e.end,handle:n}}}function nh(e,t){const n=e=>t.applyToPoint(e),i=n(e.start.point),o=n(e.end.point),r=n(e.middle),s=e.points.map(n),a=s.map((e,t)=>`${0===t?"M":"L"} ${ah(e.x)} ${ah(e.y)}`).join(" "),l={start:{...e.start,point:i,handle:n(e.start.handle)},end:{...e.end,point:o,handle:n(e.end.handle)},middle:r,bend:zu(i,o,r),points:s,bounds:LI.FromPoints(s),path:a};if("straight"===e.type)return{...e,...l};const d=n(e.arc.center),c={...e.arc,center:d,radius:d.dist(i),sweepFlag:t.determinant()<0?1===e.arc.sweepFlag?0:1:e.arc.sweepFlag};return(e=>{const t=Math.hypot(e.a,e.b),n=Math.hypot(e.c,e.d),i=Math.max(1,t,n);return Math.abs(t-n)<=1e-8*i&&Math.abs(e.a*e.c+e.b*e.d)<=1e-8*i*i})(t)?Yu({start:i,end:o,middle:r,bend:l.bend,arc:c,startHandle:l.start.handle,endHandle:l.end.handle}):{...e,...l,arc:c}}function ih(e,t,n,i){const o=e.computeShapeLocalToPageTransform(t),r=o.tryInvert();return r?nh(Nu(r.applyToPoint(n),r.applyToPoint(i),t.props.bend),o):Nu(n,i,t.props.bend)}function oh(e,t,n){if(t.boundaryPagePoint.dist2(e.start.point)<1e-10&&n.boundaryPagePoint.dist2(e.end.point)<1e-10)return th(e,t.handlePagePoint,n.handlePagePoint);if("straight"===e.type)return th(Nu(t.boundaryPagePoint,n.boundaryPagePoint,0),t.handlePagePoint,n.handlePagePoint);if(e.path.includes(" A "))return Yu({start:t.boundaryPagePoint,end:n.boundaryPagePoint,middle:Wu(t.boundaryPagePoint,n.boundaryPagePoint,e.arc,.5),bend:e.bend,arc:e.arc,startHandle:t.handlePagePoint,endHandle:n.handlePagePoint});const i=rh(e.points,t.boundaryPagePoint),o=rh(e.points,n.boundaryPagePoint),r=[t.boundaryPagePoint];for(let a=Math.floor(i)+1;a<=Math.floor(o);a+=1){const t=e.points[a];t&&a<o&&r.push(t)}r.push(n.boundaryPagePoint);const s=(e=>{if(0===e.length)return $I.Zero();const t=[];let n=0;for(let o=0;o<e.length-1;o+=1){const i=e[o].dist(e[o+1]);t.push(i),n+=i}let i=n/2;for(let o=0;o<t.length;o+=1){const n=t[o];if(i<=n){const t=e[o];return t.add(e[o+1].sub(t).mul(0===n?0:i/n))}i-=n}return e[e.length-1]})(r);return{...e,start:{...e.start,point:t.boundaryPagePoint,handle:t.handlePagePoint},end:{...e.end,point:n.boundaryPagePoint,handle:n.handlePagePoint},middle:s,points:r,bounds:LI.FromPoints(r),path:sh(r),bend:zu(t.boundaryPagePoint,n.boundaryPagePoint,s)}}function rh(e,t){let n=0,i=1/0;for(let o=0;o<e.length-1;o+=1){const r=e[o],s=e[o+1].sub(r),a=s.len2(),l=0===a?0:Math.max(0,Math.min(1,((t.x-r.x)*s.x+(t.y-r.y)*s.y)/a)),d=r.add(s.mul(l)).dist2(t);d<i&&(i=d,n=o+l)}return n}function sh(e){return e.map((e,t)=>`${0===t?"M":"L"} ${ah(e.x)} ${ah(e.y)}`).join(" ")}function ah(e){return Number(e.toFixed(3)).toString()}function lh(e,t,n,i){if(!t.target)return void(t.isArcBoundaryPoint=!0);const o=hh(e.getShapePageOutlineVertices(t.target.id),n,i);o?(t.boundaryPagePoint=o,t.isArcBoundaryPoint=!0):t.isArcBoundaryPoint=!1}function dh(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?uh(e.terminal,e.handlePagePoint,e.boundaryPagePoint,t):null}))(e,t);return{terminal:n.terminal,anchorPagePoint:n.anchorPagePoint,boundaryPagePoint:n.boundaryPagePoint,guidePath:n.guidePath}}function ch(e,{arrow:t,terminal:n,target:i,anchorPagePoint:o,fallbackBoundaryPagePoint:r}){const s=((e,t,n)=>Qu(e,t,n).handlePagePoint)(e,t,Ru(n)),a=ih(e,t,"start"===n?o:s,"end"===n?o:s);if("curved"!==a.type)return{terminal:n,anchorPagePoint:o,boundaryPagePoint:r,guidePath:null};const l=hh(e.getShapePageOutlineVertices(i.id),a,n);return l?{terminal:n,anchorPagePoint:o,boundaryPagePoint:l,guidePath:uh(n,o,l,a)}:{terminal:n,anchorPagePoint:o,boundaryPagePoint:r,guidePath:null}}function uh(e,t,n,i){if(i.path.includes(" A "))return(({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 Yu({start:t,end:n,middle:Wu(t,n,r,.5),bend:i.bend,arc:r}).path})({terminal:e,handlePagePoint:t,boundaryPagePoint:n,fullInfo:i});const o=rh(i.points,n),r=[t];if("start"===e)for(let s=1;s<=Math.floor(o);s+=1){const e=i.points[s];e&&s<o&&r.push(e)}else for(let s=i.points.length-2;s>=Math.ceil(o);s-=1){const e=i.points[s];e&&s>o&&r.push(e)}return r.push(n),sh(r)}function hh(e,t,n){const i=[];for(let o=0;o<t.points.length-1;o+=1){const n=t.points[o],r=t.points[o+1];for(let t=0;t<e.length;t+=1){const s=e[t],a=e[(t+1)%e.length];if(!s||!a)continue;const l=ph(n,r,s,a);l&&i.push({point:l.point,position:o+l.t})}}return 0===i.length?null:(i.sort((e,t)=>e.position-t.position),"start"===n?i[0].point:i[i.length-1].point)}function ph(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-9)return null;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l<-1e-9||l>1.000000001||d<-1e-9||d>1.000000001?null:{point:e.add(o.mul(Math.max(0,Math.min(1,l)))),t:Math.max(0,Math.min(1,l))}}function gh(e,t){const n=e.getShapePageBounds(t.id)??e.computeShapePageBounds(t);return n.w*n.h}function fh(e,t){return e.getShapeUtil(t).canReceiveChildren(t)}function mh(e,t){return!(!t||ju(t))&&e.getShapeUtil(t).canReceiveTerminalBinding(t,{editor:e})}function yh(e,t,n){const i=fh(e,t),o=fh(e,n);if(i!==o)return i?1:-1;if(i&&o){const i=gh(e,t)-gh(e,n);if(Math.abs(i)>1e-6)return i}return 0}function Sh(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function bh(e){if(e)return{shapes:[e]}}function xh(e,t){const n=e&&"object"==typeof e?e:void 0;return{x:Ih(n?.x,t.x),y:Ih(n?.y,t.y)}}function Ih(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function wh(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 Ph(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),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1})(e,t,n,i)?0:Math.min(wh(e,n,i),wh(t,n,i),wh(n,e,t),wh(i,e,t))}function vh(e,t,n="user"){if(t.parentId?.startsWith("shape:")){const n=e.getShape(t.parentId);if(!n||!e.computeShapeLocalToPageTransform(n).tryInvert())throw new Error("Cannot create an arrow inside a singular parent transform")}const[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,autoReparent:!1});if(!ju(i))throw new Error("Failed to create arrow shape");const o=$u(e,i,t.startPagePoint,t.endPagePoint);if(!o)throw new Error("Cannot create an arrow inside a singular parent transform");e.commands.updateShapes([{id:i.id,x:o.x,y:o.y,rotation:o.rotation,skewX:o.skewX,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(!ju(r))throw new Error("Failed to create arrow shape");return r}function kh(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(!ju(i))return null;const o=Lu(e,i,t.terminal,t.pagePoint);if(!o)return null;e.commands.updateShapes([{id:i.id,x:o.x,y:o.y,rotation:o.rotation,skewX:o.skewX,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n});const r=e.bindings.getBindingsFromShape(i.id).find(e=>Gu(e)&&e.props.terminal===t.terminal)??null;t.binding?Gu(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,skewX:o.skewX,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}));const s=e.getShape(i.id);return ju(s)?s:o})(e,{shapeId:t,terminal:n,pagePoint:i.pagePoint,binding:i.binding},o),e.setBindingPreview(i.preview),r}function Ch(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||yh(e,i,n)<0)&&(n=i);return n})(e,e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget",filter:t=>t.id!==i?.excludeShapeId&&mh(e,t)}));if(!o)return null;const r=((e,t,n)=>{const i=e.computeShapePositionedToPageTransform(t).tryInvert(),o=e.computeShapePositionedBounds(t);if(!i)return{x:.5,y:.5};const r=i.applyToPoint(n),s=o.h<=1e-6?.5:(r.y-o.minY)/o.h;return{x:Tu(o.w<=1e-6?.5:(r.x-o.minX)/o.w),y:Tu(s)}})(e,o,t);return{targetShape:o,normalizedAnchor:r,resolvedPagePoint:Eu(e,o,r,n),rawPagePoint:t.clone()}}(e,n,i,{excludeShapeId:o});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:Mh(s),preview:Eh(t,s)}}function Th(e,{arrow:t,terminal:n,rawPagePoint:i,ignoreTargets:o=!1}){const r=Ch(e,{terminal:n,rawPagePoint:i,oppositePagePoint:Au(e,t,Ru(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||ju(r))return o;const s=ch(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 Mh(e){return e?{targetShapeId:e.targetShape.id,normalizedAnchor:e.normalizedAnchor}:null}function Eh(e,t){return t?{terminal:e,targetShapeId:t.targetShape.id,rawPagePoint:t.rawPagePoint,resolvedPagePoint:t.resolvedPagePoint}:null}function Bh({strokeActionId:e,strokeWidthActionId:t,headStartActionId:n,headEndActionId:i,dataUiPrefix:o}){return[{id:`${o}.style-stroke`,items:[{kind:"color-input",id:`${o}.stroke`,actionId:e,label:"Stroke",fallback:"#334155",presets:tC.map(e=>({...e,dataUi:`${o}-stroke-${e.id}-button`})),dataUi:`${o}.stroke`}]},{id:`${o}.style-stroke-width`,items:[{kind:"stepper",id:`${o}.stroke-width`,actionId:t,label:"Stroke width",dataUi:`${o}-stroke-width-control`,options:nC.map(e=>({...e,dataUi:`${o}-stroke-width-${e.value}-button`}))}]},{id:`${o}.head-start`,items:[{kind:"segmented",id:`${o}.head-start`,actionId:n,options:iC.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:iC.map(e=>({...e,label:`End head: ${e.label}`,dataUi:`${o}-end-head-${e.value}-button`}))}]}]}function Ah(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?!z(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=$h(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 Rh(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=$h(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("arrow",{[e]:i})}}}function $h(e,t){return"strokeWidth"===e?"number"==typeof t&&nC.some(e=>e.value===t)?t:void 0:"stroke"===e?R(t)?L(t,M("stroke-slate")):void 0:iC.some(e=>e.value===t)?t:void 0}function Lh(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 Fh(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function Dh(e,t,n){return Math.max(t,Math.min(n,e))}function Uh(e){return e?640:480}function zh(e,t){return e.x===t.x&&e.y===t.y&&e.pressure===t.pressure&&e.segment===t.segment}function Oh(e){return new $I(e.x,e.y)}function Xh(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 Nh(e){const t=[];for(const n of e)t.push(...n.points.map(Xh));return t}function Yh(e){if(void 0!==e&&Number.isFinite(e))return Dh(e,.05,1)}function _h(e,t){const n=[];for(let i=1;i<e.length-1;i+=1){if(t&&Hh(e,i))continue;const o=e[i],r=e[i-1],s=e[i+1];o&&r&&s&&n.push({index:i,score:Wh(o,r,s)})}return n.sort((e,t)=>e.score-t.score||e.index-t.index),n}function Hh(e,t){return"straight"===e[t]?.segment||"straight"===e[t+1]?.segment}function Wh(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=Dh(((e.x-t.x)*i+(e.y-t.y)*o)/r,0,1),a=e.x-(t.x+i*s),l=e.y-(t.y+o*s);return a*a+l*l})(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 Kh(e){if(0===e.length)return null;if(1===e.length){const t=e[0];return`M ${Fh(t.x)} ${Fh(t.y)}`}if(2===e.length){const t=e[0],n=e[1];return[`M ${Fh(t.x)} ${Fh(t.y)}`,`L ${Fh(n.x)} ${Fh(n.y)}`].join(" ")}const t=[],n=e[0];t.push(`M ${Fh(n.x)} ${Fh(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 ${Fh(n.x)} ${Fh(n.y)}`);continue}const o=e[i+1];if(!o||"straight"===o.segment){if(Vh(e,i)){const o=e[i-1];t.push(`Q ${Fh(o.x)} ${Fh(o.y)} ${Fh(n.x)} ${Fh(n.y)}`)}else t.push(`L ${Fh(n.x)} ${Fh(n.y)}`);continue}const r=$I.Med(Oh(n),Oh(o));t.push(`Q ${Fh(n.x)} ${Fh(n.y)} ${Fh(r.x)} ${Fh(r.y)}`)}return t.join(" ")}function Vh(e,t){return t>=2&&"straight"!==e[t-1]?.segment&&"straight"!==e[t-2]?.segment}function qh(e){if(e.length<3)return(e=>{if(0===e.length)return null;const[t,...n]=e;return t?[`M ${Fh(t.x)} ${Fh(t.y)}`,...n.map(e=>`L ${Fh(e.x)} ${Fh(e.y)}`),"Z"].join(" "):null})(e);const t=e[0],n=e[e.length-1];if(!t||!n)return null;const i=$I.Med(n,t),o=[`M ${Fh(i.x)} ${Fh(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=$I.Med(t,n);o.push(`Q ${Fh(t.x)} ${Fh(t.y)} ${Fh(i.x)} ${Fh(i.y)}`)}return o.push("Z"),o.join(" ")}function jh(e){return e.map(Xh)}function Gh(e){return e.map(Zh)}function Zh(e){return(e=>({points:e.points.map(Xh)}))(e)}function Qh(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 Jh(e,t,n){return e.map(e=>({points:Qh(e.points,t,n)}))}function ep(e,t){return e.map((e,n)=>({points:e.points.map((e,i)=>{const o=t(Oh(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 tp(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 np(e,t,n){return e.map(e=>({points:tp(e.points,t,n)}))}function ip(e){return{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}}function op(e,t){const n=ip(t);return ep(e,e=>ri(e,n))}function rp(e,t){const n=ip(t);return ep(e,e=>si(e,n))}function sp(e,t){return ep(e,e=>ci({axis:t.axis,bounds:t.selectionMirrorBounds,point:e}))}function ap(e,t,n){return Math.max(t,Math.min(n,e))}function lp(e,t,n){return e+(t-e)*n}function dp(e,t,n){if(e.length<=1)return new $I(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]).normalize(),r=i.sub(n).normalize(),s=o.add(r);return s.len2()>1e-6?s.normalize():r.len2()>0?r:o.len2()>0?o:new $I(1,0)}const i=e[t],o=e[t+1]??i,r=i.sub(e[t-1]??i).normalize(),s=o.sub(i).normalize();if(0===t)return s.len2()>0?s:new $I(1,0);if(t===e.length-1)return r.len2()>0?r:new $I(1,0);const a=r.add(s);return a.len2()>1e-6?a.normalize():s.len2()>0?s:r.len2()>0?r:new $I(1,0)}function cp(e,t){return e.x*t.x+e.y*t.y}function up(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(Oh),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,o,r,s,a){if(n.simulatePressure)return(({distanceFromPrevious:e,previousPressure:t,runningLength:n,totalLength:i,strokeWidth:o,isClosed:r})=>{const s=ap(e/Math.max(1.5*o,1),0,1),a=ap(1-s,rC,1),l=null===t?lp(.5,a,.275):lp(t,a,.275*Math.max(s,.36));if(r)return ap(l,rC,1);const d=ap(n/Math.max(1.8*o,1),0,1),c=ap((i-n)/Math.max(2.6*o,1),0,1);return ap(l*lp(.72,1,Math.min(d,c)),rC,1)})({distanceFromPrevious:o,previousPressure:t,runningLength:r,totalLength:s,strokeWidth:i,isClosed:a});const l="number"==typeof e.pressure&&Number.isFinite(e.pressure)?ap(e.pressure,.05,1):t??.55;return null===t?l:lp(t,l,.68)}(e,d,r,t,u,c,l,i);d=h;const p=o.taperEnd??!0,g=i||s.length<=1?1:Math.min(o.taperStart??1?ap(c/r.startTaper,0,1):1,p?ap((l-c)/r.endTaper,0,1):1),f=lp(r.minRadiusScale,r.maxRadiusScale,h),m=Math.max(r.minRadius,r.baseRadius*f*lp(.7,1,g));return{point:s[n],direction:dp(s,n,i),pressure:h,radius:m,runningLength:c}});return l<.5*r.baseRadius?c.map(e=>({...e,radius:Math.max(e.radius,.92*r.baseRadius)})):c}function hp(e,t){const n=e[e.length-1];n&&n.dist2(t)<.04?e[e.length-1]=t:e.push(t)}function pp(e,t,n){const i=e.dist(t);if(0===i)return[];const o=$I.Angle(e,t),r=[];for(let s=1;s<n;s+=1){const t=o-Math.PI*(s/n);r.push(new $I(e.x+Math.cos(t)*i,e.y+Math.sin(t)*i))}return r}function gp(e,t,n){const i=e[e.length-1];!i||i.dist2(t)>n?hp(e,t):e[e.length-1]=t}function fp(e){return{...e}}function mp(e,t,n){return e.map(e=>new $I(e.x+t,e.y+n))}function yp(e,t,n){return e.map(e=>mp(e,t,n))}function Sp({segments:e,outlineVertices:t,outlinePolygons:n,strokeWidth:i,sampling:o,isClosed:r}){const s=Nh(e),a=s.map(Oh),l=a.length>0?LI.FromPoints(a):new LI(0,0,1,1),d=t.length>0?LI.FromPoints([...t]):l.expand(Math.max(i/2,1)),c=r&&s.length>=3?(e=>{if(e.length<3)return null;const t=Kh(e);return t?`${t} Z`:null})(s):null,u=void 0!==n?(e=>{const t=e.map(e=>qh(e)).filter(e=>null!==e);return t.length>0?t.join(" "):null})(n):qh(t);return{normalizedSegments:Gh(e),normalizedPoints:jh(s),pointBounds:l,path:u,selectionPath:c??Kh(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:fp(o)}}function bp(e,t,n,i){const o=(({strokeWidth:e,isPen:t})=>[e,t?"pen":"pointer"].join(":"))({strokeWidth:n,isPen:i}),r=sC.get(e),s=r?.get(o);if(s)return{normalizedSegment:Zh(s.normalizedSegment),sampling:fp(s.sampling)};const a=((e,t)=>{if(e.length<=1)return{points:e.map(Xh),rawPointCount:e.length,sampledPointCount:e.length,maxPointCount:t.maxPointCount,reduced:!1,capped:!1};const n=[Xh(e[0])],i=t.minPointDistance*t.minPointDistance;let o=Oh(e[0]),r=Yh(e[0].pressure);for(let l=1;l<e.length;l+=1){const s=e[l];if(!s)continue;const a=Oh(s),d=Yh(s.pressure),c=l===e.length-1,u="straight"===s.segment,h=c||u?a:$I.Lrp(o,a,t.positionBlend),p=u?d:void 0===d?void 0:void 0===r?d:r+(d-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,y=g.y-f.y,S=Math.abs((g.pressure??0)-(f.pressure??0));if(m*m+y*y<i){if(u){if(zh(f,g))continue;n.push(g);continue}(S>.08||c)&&(n[n.length-1]=g)}else n.push(g)}const s=n.length>t.maxPointCount,a=function(e,t){const n=Math.max(2,Math.floor(t));if(e.length<=n)return e.map(Xh);const i=((e,t)=>{let n=_h(e,!0);return n.length<t&&(n=_h(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(Xh)}(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:jh(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},d=r??new Map;return d.set(o,{normalizedSegment:Zh(l.normalizedSegment),sampling:fp(l.sampling)}),r||sC.set(e,d),l}function xp(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:Uh(t)}))(t,n),r=[],s=[],a=e.filter(e=>e.points.length>0);for(let h=0;h<a.length;h+=1){const e=bp(a[h],o,t,n);r.push(Zh(e.normalizedSegment)),s.push(fp(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 o=2*Math.PI*i/16;n.push(new $I(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 d of e)r=Math.max(r,.38*d.radius);const s=r**2;let a=null;for(let d=0;d<e.length;d+=1){const t=e[d],n=t.direction,r=(e[d+1]??t).direction,l=cp(n,r);let c=0===d||d===e.length-1?n.per().normalize():$I.Lrp(r,n,l).per().normalize();c.len2()<1e-6&&(c=a??new $I(0,1)),a=c,gp(i,t.point.add(c.mul(t.radius)),s),gp(o,t.point.sub(c.mul(t.radius)),s)}if(t&&e.length>=3){const e=[];for(const t of i)hp(e,t);for(let t=o.length-1;t>=0;t-=1)hp(e,o[t]);return e}const l=[];for(const d of i)hp(l,d);if(n.capEnd??1){const t=e[e.length-1];for(const e of pp(t.point,i[i.length-1],8))hp(l,e)}for(let d=o.length-1;d>=0;d-=1)hp(l,o[d]);if(n.capStart??1){const t=e[0];for(const e of pp(t.point,o[0],8))hp(l,e)}return l}(up(Nh(r),t,n,i),i),d=(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 Sp({segments:r,outlineVertices:l,outlinePolygons:l.length>0?[l]:[],strokeWidth:t,sampling:d,isClosed:i})}function Ip(e){return e.segments}function wp(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 LI(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 Pp(e){const t=e,n=aC.get(t);if(n)return n;const i=xp(Ip(e.props),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed);return aC.set(t,i),i}function vp(e,t,n=!1,i=!1){return((e,t,n=!1,i=!1)=>{const o=xp(e,t,n,i),r=o.pointBounds,s=xp(ep(o.normalizedSegments,e=>new $I(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 kp(e){const t=e,n=lC.get(t);if(n)return n;const i=((e,t,n,i,o)=>Sp({segments:Jh(e.normalizedSegments,n,i),outlineVertices:mp(e.outlineVertices,n,i),outlinePolygons:yp(e.outlinePolygons,n,i),strokeWidth:t,sampling:e.sampling,isClosed:o}))(Pp(e),e.props.strokeWidth,e.x,e.y,e.props.isClosed);return lC.set(t,i),i}function Cp(e){const t=((e,t)=>new $I(e.x+t.localBounds.center.x,e.y+t.localBounds.center.y))(e,Pp(e));return ep((e=>Jh(Ip(e.props),e.x,e.y))(e),n=>((e,t,n)=>{if(0===e.rotation&&0===e.skewX&&1===e.scaleX&&1===e.scaleY)return t;const i=t.sub(n),o=new $I(i.x*e.scaleX,i.y*e.scaleY);return n.add(new $I(o.x+Math.tan(e.skewX)*o.y,o.y).rot(e.rotation))})(e,n,t))}function Tp(e){return Gh(e)}function Mp(e,t,n,i){return{x:e.x-t.x,y:e.y-t.y,...i&&n>0?{pressure:n}:null}}function Ep(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 Bp(e){const t=Ap(e.segments),n=t[t.length-1];return n?n.points.map(Ep):[]}function Ap(e){return e.length>0?[...e]:[{points:[]}]}function Rp(e){return{segments:Tp(Ap(e))}}function $p(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 $I(t.x+i.x*r,t.y+i.y*r);return e.dist(s)}function Lp(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),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1})(e,t,n,i)?0:Math.min($p(e,n,i),$p(t,n,i),$p(n,e,t),$p(i,e,t))}function Fp(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 Dp(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,$p(e,o,r)))}return n}function Up(e,t,n,i){if(0===n.length)return!1;if(Fp(e,n)||Fp(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&&Lp(e,t,r,s)<=i)return!0}return!1}function zp(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Op(e){if(!e||"object"!=typeof e)return null;const t=e,n=zp(t.x,NaN),i=zp(t.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(i))return null;const o=zp(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 Xp(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=Op(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 Np(e,t){if(!Array.isArray(e))return t;let n=!1;const i=[];for(const o of e){const e=Xp(o);e?(n=n||e!==o,i.push(e)):n=!0}return 0===i.length?t:n?i:e}function Yp(e){return f(e)&&"draw"===e.type}function _p(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:!z(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=Vp(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(Yp).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function Hp(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=Vp(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("draw",{[e]:i})}}}function Wp(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 Kp(e){return"closed"===e||"open"!==e&&null}function Vp(e,t){return"strokeWidth"===e?(e=>{const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0})(t):R(t)?L(t,"fill"===e?E("transparent"):M("stroke-slate")):void 0}function qp({shape:e,isHovered:t=!1,stroke:n=e.props.stroke,strokeWidth:i=e.props.strokeWidth}){const{fillPath:o,renderBounds:r,path:s,selectionPath:a}=Pp({props:{...e.props,strokeWidth:i}});if(!s&&!a)return null;const l=Zs(n,t);
24
+ return Qx("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&&!U(e.props.fill)?Zx("path",{d:o,fill:F(e.props.fill),stroke:"none"}):null,e.props.isClosed&&a?Zx("path",{d:a,fill:"none",stroke:l,strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round"}):s?Zx("path",{d:s,fill:l,stroke:"none"}):null]})}function jp(e){return e.runtime.require(SC)}function Gp(e){return 4/e.getCurrentCamera().z}function Zp(e,t,n,i){const o=[new $I(t.minX,t.minY),new $I(t.maxX,t.minY),new $I(t.maxX,t.maxY),new $I(t.minX,t.maxY)].map(e=>n.applyToPoint(e));let r=0,s=Number.POSITIVE_INFINITY;for(let a=0;a<o.length;a+=1){const t=o[a],n=o[(a+1)%o.length].sub(t),i=e.sub(t),l=n.x*i.y-n.y*i.x;if(Math.abs(l)<=1e-8)return!1;const d=Math.sign(l);if(0===r)r=d;else if(d!==r)return!1;const c=n.len2(),u=0===c?0:Math.max(0,Math.min(1,(i.x*n.x+i.y*n.y)/c));s=Math.min(s,e.dist(t.add(n.mul(u))))}return s>i}function Qp(e,t){const n=new Set,i=Gp(e);for(const o of e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget"})){const r=e.getShapeUtil(o);if(!r.canReceiveChildren(o))continue;const s=r.getChildClipLocalBounds(o);s&&Zp(t,s,e.computeShapeLocalToPageTransform(o),i)&&n.add(o.id)}return n}function Jp(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 eg(e,t,n,i){const o=i.topMostOnly?n.slice(0,1):n;for(const r of o){const n=Jp(e,r,t);n&&t.erasingShapeIds.add(n)}}function tg(e,t,n){eg(e,t,e.hitTestShapesAtPoint(n.pagePoint),{topMostOnly:n.accelKey})}function ng(e,t,n){eg(e,t,e.hitTestShapesByLineSegment(t.previousPagePoint,n.pagePoint,{margin:Gp(e)}),{topMostOnly:n.accelKey})}function ig(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function og(e,t){jp(e).setPreview(Array.from(t.erasingShapeIds),t.trail)}function rg(e){jp(e).clear()}function sg(e,t){const n=Array.from(t.erasingShapeIds);rg(e),0!==n.length&&e.commands.deleteShapes(n,{source:"user"})}function ag(){return"undefined"==typeof performance?Date.now():performance.now()}function lg(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=TC/n,s=pg(o,t);if(s<r)return void(e.samples[e.samples.length-1]={...o,...t,time:i});const a=s*n/Math.max($C,i-o.time);e.samples.push({...t,time:i,velocity:xg(o.velocity,a,.68)})}function dg(e,t){e.samples=cg(e.samples,t)}function cg(e,t){const n=e[e.length-1];if(!n)return[];const i=t-Ig(LC+n.velocity*FC,LC,DC);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?[(l=s,d=a,c=Ig((i-s.time)/(a.time-s.time),0,1),{...bg(l,d,c),time:xg(l.time,d.time,c),velocity:xg(l.velocity,d.velocity,c)}),...r]:r;var l,d,c}function ug(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?yg(i,e[t]):yg(t===e.length-1?e[t]:i,n))}function hg(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 pg(e,t){return Math.sqrt(gg(e,t))}function gg(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function fg(e){return{x:-e.y,y:e.x}}function mg(e,t){return{x:e.x+t.x,y:e.y+t.y}}function yg(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Sg(e,t){return{x:e.x*t,y:e.y*t}}function bg(e,t,n){return{x:xg(e.x,t.x,n),y:xg(e.y,t.y,n)}}function xg(e,t,n){return e+(t-e)*n}function Ig(e,t,n){return Math.max(t,Math.min(n,e))}function wg(e,t){const n=e[e.length-1];!n||gg(n,t)>.04?e.push(t):e[e.length-1]=t}function Pg(e){if(e.length<2)return null;if(2===e.length)return`M ${kg(e[0])} L ${kg(e[1])} Z`;const t=[`M ${kg(vg(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 ${kg(i)} ${kg(vg(i,o))}`)}return t.push("Z"),t.join(" ")}function vg(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function kg(e){return`${Cg(e.x)},${Cg(e.y)}`}function Cg(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function Tg(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Mg(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 Eg(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:!z(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=$g(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 Bg(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=$g(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("frame",{[e]:i})}}}function Ag({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"color-input",id:`${i}.fill`,actionId:e,label:"Fill",fallback:"#f8fafc",presets:YC.map(e=>({...e,dataUi:`${i}-fill-${e.id}-button`})),dataUi:`${i}.fill`}]},{id:`${i}.style-stroke`,items:[{kind:"color-input",id:`${i}.stroke`,actionId:t,label:"Stroke",fallback:"#94a3b8",presets:_C.map(e=>({...e,dataUi:`${i}-stroke-${e.id}-button`})),dataUi:`${i}.stroke`}]},{id:`${i}.style-stroke-width`,items:[{kind:"stepper",id:`${i}.stroke-width`,actionId:n,label:"Stroke width",dataUi:`${i}-stroke-width-control`,options:HC.map(e=>({...e,dataUi:`${i}-stroke-width-${e.value}-button`}))}]}]}function Rg(e){return{id:`frame.child-order.${e}`,isVisible:e=>"frame"===Lg(e),isEnabled:t=>t.editor.canMoveSelectionWithinParent(e),run({context:t}){t.editor.moveSelectionWithinParent(e,"user")}}}function $g(e,t){return"strokeWidth"===e?"number"==typeof t&&HC.some(e=>e.value===t)?t:void 0:R(t)?L(t,"fill"===e?E("transparent"):M("stroke-muted")):void 0}function Lg(e){const[t]=e.selection.selectedShapes;return 1===e.selection.count&&t?.parentId.startsWith("shape:")?e.editor.getShape(t.parentId)?.type??null:null}function Fg({shape:e,isHovered:t=!1}){const{fill:n,h:i,name:o,stroke:r,strokeWidth:s,w:a}=e.props,l=s/2,d=Math.max(a-s,0),c=Math.max(i-s,0),u=Zs(r,t);
25
+ return Qx("svg",{width:"100%",height:"100%",viewBox:`0 0 ${a} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[Zx("rect",{x:l,y:l,width:d,height:c,fill:F(n),stroke:u,strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"}),Zx("text",{x:12,y:18,fill:F(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 Dg(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 $I(e.center.x+e.w/2*Math.cos(o),e.center.y+e.h/2*Math.sin(o)))}return n})(e):Og(e,t,n)}function Ug(e,t=12){return Math.min(50,Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t))}function zg({cornerRadiusPercent:e=12,h:t,w:n}){return Math.min(Math.max(0,n),Math.max(0,t))*Ug(e)/100}function Og(e,t,n={}){switch(t){case"diamond":return[new $I(e.center.x,e.minY),new $I(e.maxX,e.center.y),new $I(e.center.x,e.maxY),new $I(e.minX,e.center.y)];case"triangle":return[new $I(e.center.x,e.minY),new $I(e.maxX,e.maxY),new $I(e.minX,e.maxY)];case"hexagon":return[new $I(e.minX+.25*e.w,e.minY),new $I(e.maxX-.25*e.w,e.minY),new $I(e.maxX,e.center.y),new $I(e.maxX-.25*e.w,e.maxY),new $I(e.minX+.25*e.w,e.maxY),new $I(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 $I(Math.cos(e)*i,Math.sin(e)*i))}return((e,t)=>{const n=LI.FromPoints([...e]);return 0===n.w||0===n.h?[t.center]:e.map(e=>new $I(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=zg(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 Yg(e);const o=[];return Ng(o,{centerX:e.maxX-i,centerY:e.minY+i,radius:i,startAngle:-Math.PI/2,endAngle:0,segments:n}),Ng(o,{centerX:e.maxX-i,centerY:e.maxY-i,radius:i,startAngle:0,endAngle:Math.PI/2,segments:n}),Ng(o,{centerX:e.minX+i,centerY:e.maxY-i,radius:i,startAngle:Math.PI/2,endAngle:Math.PI,segments:n}),Ng(o,{centerX:e.minX+i,centerY:e.minY+i,radius:i,startAngle:Math.PI,endAngle:3*Math.PI/2,segments:n}),o})(e,zg({cornerRadiusPercent:n.cornerRadiusPercent,w:e.w,h:e.h}));default:return Yg(e)}}function Xg(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(_g(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 Ng(e,{centerX:t,centerY:n,endAngle:i,radius:o,segments:r,startAngle:s}){const a=Math.max(1,Math.floor(r));for(let l=0;l<=a;l+=1){const r=s+l/a*(i-s);e.push(new $I(t+Math.cos(r)*o,n+Math.sin(r)*o))}}function Yg(e){return[new $I(e.minX,e.minY),new $I(e.maxX,e.minY),new $I(e.maxX,e.maxY),new $I(e.minX,e.maxY)]}function _g(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 Hg(e){return f(e)&&"geo"===e.type}function Wg(e){return"string"==typeof e&&nT.includes(e)}function Kg(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Vg(e,t){return e.x*t.y-e.y*t.x}function qg(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 jg(e,t,n,i){return Gg(e,t,n,i)?0:Math.min(qg(e,n,i),qg(t,n,i),qg(n,e,t),qg(i,e,t))}function Gg(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=Vg(o,r);if(Math.abs(s)<1e-8)return null;const a=n.sub(e),l=Vg(a,r)/s,d=Vg(a,o)/s;return l<0||l>1||d<0||d>1?null:{point:e.add(o.mul(l)),t:l}}function Zg(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=Gg(e,t,r,s);!a||a.t<=1e-6||(!i||a.t<i.t)&&(i=a)}return i?.point??null}function Qg(e){return Dg(new LI(0,0,e.props.w,e.props.h),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}function Jg(e){const t=new LI(0,0,e.props.w,e.props.h);return[new $I(t.minX,t.minY),new $I(t.center.x,t.minY),new $I(t.maxX,t.minY),new $I(t.minX,t.center.y),t.center,new $I(t.maxX,t.center.y),new $I(t.minX,t.maxY),new $I(t.center.x,t.maxY),new $I(t.maxX,t.maxY)].map((e,t)=>({point:e,kind:iT[t]??"custom"}))}function ef(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:!z(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=rf(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(Hg).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function tf(e){return{id:`geo.default-${e}`,isVisible:e=>sf(e.tool.activeToolId),getValue:t=>t.editor.getDefaultShapeProps("geo")[e],run({context:t,value:n}){const i=rf(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("geo",{[e]:i})}}}function nf({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"color-input",id:`${i}.fill`,actionId:e,label:"Fill",fallback:"#e2e8f0",presets:oT.map(e=>({...e,dataUi:`${i}-fill-${e.id}-button`})),dataUi:`${i}.fill`}]},{id:`${i}.style-stroke`,items:[{kind:"color-input",id:`${i}.stroke`,actionId:t,label:"Stroke",fallback:"#334155",presets:rT.map(e=>({...e,dataUi:`${i}-stroke-${e.id}-button`})),dataUi:`${i}.stroke`}]},{id:`${i}.style-stroke-width`,items:[{kind:"stepper",id:`${i}.stroke-width`,actionId:n,label:"Stroke width",dataUi:`${i}-stroke-width-control`,options:sT.map(e=>({...e,dataUi:`${i}-stroke-width-${e.value}-button`}))}]}]}function of(e){let t=null;for(const n of e)if(Hg(n))if(null!==t){if(t!==n.props.geo)return null}else t=n.props.geo;return t}function rf(e,t){return"strokeWidth"===e?"number"==typeof t&&sT.some(e=>e.value===t)?t:void 0:R(t)?L(t,M("fill"===e?"fill-slate":"stroke-slate")):void 0}function sf(e){return aT.some(t=>t.value===e)}function af(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function lf({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),l=Math.max(e.props.h-o,0),d=zg({cornerRadiusPercent:e.props.cornerRadiusPercent,w:a,h:l}),c="ellipse"===r||"rectangle"===r?null:Og(new LI(s,s,a,l),r).map(e=>`${e.x},${e.y}`).join(" "),u={fill:F(t),stroke:Zs(i,n),strokeWidth:o,strokeLinejoin:"round",strokeLinecap:"round"};
26
+ return Zx("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:"ellipse"===r?Zx("ellipse",{...u,cx:e.props.w/2,cy:e.props.h/2,rx:a/2,ry:l/2}):"rectangle"!==r?Zx("polygon",{...u,points:c??""}):Zx("rect",{...u,x:s,y:s,width:a,height:l,rx:d,ry:d})})}function df(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function cf({shape:e,isHovered:t=!1,isSelected:n=!1}){const{h:i,w:o}=e.props,r=t||n,s=Zs(E("#64748b"),t);
27
+ return Zx("svg",{width:"100%",height:"100%",viewBox:`0 0 ${o} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:r?Zx("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 uf(e){return Math.min(1,Math.max(0,e))}function hf(e,t,n){return Math.min(n,Math.max(t,e))}function pf(e){return!!e&&"object"==typeof e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function gf(e,t){const n=uf(e),i=uf(t);let o=Math.min(n,i),r=Math.max(n,i);return r-o<kT&&(o=Math.max(0,Math.min(.9999,(o+r)/2-5e-5)),r=o+kT),{min:o,max:r}}function ff(e){if(!e||"object"!=typeof e)return null;const t=e;if(!pf(t.topLeft)||!pf(t.bottomRight))return null;const n=gf(t.topLeft.x,t.bottomRight.x),i=gf(t.topLeft.y,t.bottomRight.y);return{topLeft:{x:n.min,y:i.min},bottomRight:{x:n.max,y:i.max}}}function mf(e){const t=ff(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 yf(e){return mf(e)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function Sf(e,t){return Math.abs(e.left-t.left)<=CT&&Math.abs(e.top-t.top)<=CT&&Math.abs(e.right-t.right)<=CT&&Math.abs(e.bottom-t.bottom)<=CT}function bf(e){return(e=>Math.abs(e.left)<=CT&&Math.abs(e.top)<=CT&&Math.abs(1-e.right)<=CT&&Math.abs(1-e.bottom)<=CT)(e)?null:ff({topLeft:{x:e.left,y:e.top},bottomRight:{x:e.right,y:e.bottom}})}function xf({centerX:e,centerY:t,height:n,width:i}){const o=hf(i,kT,1),r=hf(n,kT,1),s=hf(e-o/2,0,1-o),a=hf(t-r/2,0,1-r);return{left:s,top:a,right:s+o,bottom:a+r,width:o,height:r}}function If(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function wf({crop:e,shape:t}){const n=yf(e);return{w:t.props.w/n.width,h:t.props.h/n.height}}function Pf(e,t){return t===vf(e.id)}function vf(e){return`${ET}${e}`}function kf({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 $I(0,0),top:new $I(o,0),top_right:new $I(n,0),right:new $I(n,r),bottom_right:new $I(n,i),bottom:new $I(o,i),bottom_left:new $I(0,i),left:new $I(0,r)};return RT.map(t=>{return{kind:"custom",type:TT,id:t,point:e.applyToPoint(s[t]),cursor:(n=t,AT[n])};var n})}function Cf({change:e,crop:t,shape:n}){const i=wf({crop:t,shape:n}),o=t.bottomRight.x-t.topLeft.x,r=t.bottomRight.y-t.topLeft.y,s=hf(t.topLeft.x-e.x/i.w,0,1-o),a=hf(t.topLeft.y-e.y/i.h,0,1-r),l=ff({topLeft:{x:s,y:a},bottomRight:{x:s+o,y:a+r}});return l?{id:n.id,props:{crop:l}}:null}function Tf(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Mf(e,t){const n=$T.get(e);n&&(n.delete(t),0===n.size&&$T.delete(e))}function Ef(e){return e.activeStroke?{...e,strokes:[...e.strokes,e.activeStroke],activeStroke:null,redoStrokes:[]}:e}function Bf(e){const t=KT.get(e);if(t)return t;const n=new WT(e);return KT.set(e,n),n}function Af(e){return`${XT}${e}`}function Rf(e,t){return t===Af(e.id)}function $f(e){const t="number"==typeof e?.size&&Number.isFinite(e.size)?e.size:YT,n="number"==typeof e?.opacity&&Number.isFinite(e.opacity)?e.opacity:HT??.45;return{size:Math.min(128,Math.max(1,t)),color:"string"==typeof e?.color&&e.color.trim().length>0?e.color:_T,opacity:Math.min(1,Math.max(0,n))}}function Lf({brush:e,editor:t,shape:n}){return Bf(t).start(n,e)}function Ff(e){Bf(e).cancel()}function Df(e){Bf(e).complete()}function Uf(e,t){return Bf(e).updateBrush(t)}function zf(e){return Bf(e).getActiveSession()}async function Of(e,t){return Bf(e).requestConfirm(t)}function Xf(e){return{x:e.x,y:e.y,...void 0===e.pressure?{}:{pressure:e.pressure}}}function Nf(e){return S(e)&&"image"===e.type}function Yf(e){return f(e)&&"image"===e.type}function _f(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return null;const[t]=e.selection.selectedShapes;return Yf(t)?t:null}function Hf(e){const t=_f(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!Pf(t,n.markId))}function Wf(e){const t=_f(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!Rf(t,n.markId))}function Kf(){return[{id:bT,isVisible:e=>!!_f(e)&&!Hf(e),isEnabled(e){const t=_f(e);return!!t&&!t.isLocked},getValue:e=>Hf(e),run({context:e}){const t=_f(e);if(!t||t.isLocked)return;const n=e.editor.getShapeEditingSession();n?.shapeId===t.id&&Pf(t,n.markId)?e.editor.completeEditing("user"):e.editor.startEditingShape({shapeId:t.id,markId:vf(t.id),entryMode:"focusEnd"},"user")&&((e,t)=>{const n=$T.get(e)??new Map;$T.set(e,n),n.set(t.id,{...t,props:{...t.props,crop:t.props.crop?{topLeft:{...t.props.crop.topLeft},bottomRight:{...t.props.crop.bottomRight}}:null},meta:{...t.meta}})})(e.editor,t)}},{id:xT,isVisible:e=>Hf(e),isEnabled:e=>Hf(e),run({context:e}){const t=_f(e);t&&e.editor.completeEditing("user")&&Mf(e.editor,t.id)}},{id:IT,isVisible:e=>Hf(e),isEnabled(e){const t=_f(e);return!!t&&!t.isLocked},run({context:e,value:t}){const n=_f(e);if(!n||n.isLocked||-1!==t&&1!==t)return;const i=(({direction:e,shape:t})=>{const n=yf(t.props.crop),i=If(n),o=hf("in"===e?.8:1.25,Math.max(kT/n.width,kT/n.height),Math.min(1/n.width,1/n.height)),r=xf({centerX:i.x,centerY:i.y,width:n.width*o,height:n.height*o});return Sf(n,r)?null:{id:t.id,props:{crop:bf(r)}}})({direction:1===t?"in":"out",shape:n});i&&e.editor.commands.updateShapes([i],{source:"user"})}},{id:wT,isVisible:e=>Hf(e),isEnabled(e){const t=_f(e);return!!t&&!t.isLocked},getValue(e){const t=_f(e);return t?(e=>{const t=e.props.w/e.props.h;for(const n of BT)if(Math.abs(t-n.ratio)<=.01)return n.value;return null})(t):null},run({context:e,value:t}){const n=_f(e);if(!n||n.isLocked||"string"!=typeof t)return;const i=BT.find(e=>e.value===t);if(!i)return;const o=function({preset:e,shape:t}){const n=If(yf(t.props.crop)),i=wf({crop:t.props.crop,shape:t}),o=BT.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=yf(t.props.crop);if(Sf(n,e))return null;const i=wf({crop:t.props.crop,shape:t}),o=new $I((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:bf(e)}}})({nextRect:xf({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:PT,isVisible:e=>Hf(e),isEnabled(e){const t=_f(e);return!!t&&!t.isLocked&&!!t.props.crop},run({context:e}){const t=_f(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=ff(e.props.crop);return Math.abs(t.x-n)<=CT&&Math.abs(t.y-i)<=CT&&Math.abs(t.props.w-o)<=CT&&Math.abs(t.props.h-r)<=CT&&(null===t.props.crop&&null===s||null!==t.props.crop&&null!==s&&Math.abs(t.props.crop.topLeft.x-s.topLeft.x)<=CT&&Math.abs(t.props.crop.topLeft.y-s.topLeft.y)<=CT&&Math.abs(t.props.crop.bottomRight.x-s.bottomRight.x)<=CT&&Math.abs(t.props.crop.bottomRight.y-s.bottomRight.y)<=CT)?null:{id:t.id,x:n,y:i,props:{w:o,h:r,crop:s}}})({baselineShape:(i=e.editor,o=t.id,$T.get(i)?.get(o)??null??t),shape:t});var i,o;n&&e.editor.commands.updateShapes([n],{source:"user"})}}]}function Vf(){return{createSession(e,{handle:t,shape:n,originPagePoint:i}){return Yf(n)&&"custom"===t.kind&&"image.crop"===t.type&&(o=t.id,RT.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:l}){if(!Yf(s.getShape(t)))return"stop";const d=(({handleId:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:o,currentPagePoint:r})=>{const s=ff(i)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=wf({crop:s,shape:n});if(a.w<8||a.h<8)return null;const l=t.applyToPoint(o),d=t.applyToPoint(r).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=hf(p+d.x,0,u-8),f=u-p):(e=>"top_right"===e||"right"===e||"bottom_right"===e)(e)&&(f=hf(u+d.x,c.x+8,a.w)-p),(e=>"top_left"===e||"top"===e||"top_right"===e)(e)?(g=hf(g+d.y,0,h-8),m=h-g):(e=>"bottom_left"===e||"bottom"===e||"bottom_right"===e)(e)&&(m=hf(h+d.y,c.y+8,a.h)-g);const y=ff({topLeft:{x:p/a.w,y:g/a.h},bottomRight:{x:(p+f)/a.w,y:(g+m)/a.h}});if(!y)return null;const S=new $I(p-s.topLeft.x*a.w,g-s.topLeft.y*a.h).rot(n.rotation);return{id:n.id,x:n.x+S.x,y:n.y+S.y,props:{w:f,h:m,crop:y}}})({handleId:e,currentPagePoint:a,pageToLocal:i,shape:o,startCrop:r,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 o}}}function qf(e){const[t]=e.getSelectedShapes();if(!Yf(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Pf(t,n.markId)?t:null}function jf(e,t,n){if(!n.hasDragged){if(n.startPagePoint.dist2(t.pagePoint)<9)return;e.history.mark(MT),n.hasDragged=!0}if(!Yf(e.getShape(n.shapeId)))return;const i=(({currentPagePoint:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:o,shiftKey:r})=>{const s=ff(i);if(!s)return null;const a=t.applyToPoint(o);let l=t.applyToPoint(e).sub(a);return r&&(l=Math.abs(l.x)<Math.abs(l.y)?new $I(0,l.y):new $I(l.x,0)),0===l.x&&0===l.y?null:Cf({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 Gf(e,t=0){return Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t)}function Zf({cornerRadius:e,h:t,w:n}){return Math.min(Gf(e),Math.max(0,n)/2,Math.max(0,t)/2)}function Qf(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Jf(e){return"key_down"===e.name&&"Enter"===e.key&&!e.altKey&&!e.accelKey}function em(e){return"key_down"===e.name&&"z"===e.key.toLowerCase()&&e.accelKey&&!e.altKey}function tm(e){const[t]=e.getSelectedShapes();if(!Yf(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Rf(t,n.markId)?t:null}function nm(e,t,n){const i=im(e,t,n.pagePoint);return!!om(i,t)&&(((e,t)=>{Bf(e).appendPoint(t)})(e,{x:i.x,y:i.y,pressure:n.pressure}),!0)}function im(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function om(e,t){return e.x>=0&&e.y>=0&&e.x<=t.props.w&&e.y<=t.props.h}function rm(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 sm({dataUiPrefix:e}){return{kind:"text-input",id:`${e}.corner-radius`,actionId:vT,label:"Corner radius",placeholder:"0",dataUi:`${e}-corner-radius-control`}}function am({shape:e,session:t}){return t&&t.shapeId===e.id&&0!==t.strokes.length?Zx("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=>Zx(lm,{stroke:e},e.id))}):null}function lm({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 Zx("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 ${um(t.x)} ${um(t.y)}`,...n.map(e=>`L ${um(e.x)} ${um(e.y)}`)].join(" "):null})(e);return r?Zx("path",{d:r,fill:"none",opacity:i,stroke:n,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o}):null}function dm({cornerRadius:e,isVisible:t}){return t?Zx("div",{"aria-hidden":"true","data-ui":"image-hover-outline",style:{borderRadius:e,boxShadow:`inset 0 0 0 2px ${fv}`,inset:0,pointerEvents:"none",position:"absolute"}}):null}function cm(e,t){return`${e},${t}`}function um(e){return Number.isFinite(e)?Number(e.toFixed(2)).toString():"0"}function hm(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 pm(e){return e.runtime.require(ZT)}function gm(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function fm(e,t){pm(e).set(t.sessionId,t.trail)}function mm(){return"undefined"==typeof performance?Date.now():performance.now()}function ym(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=lM/n,s=wm(o,t);if(s<r)return void(e.samples[e.samples.length-1]={...o,...t,time:i});const a=s*n/Math.max(gM,i-o.time);e.samples.push({...t,time:i,velocity:Em(o.velocity,a,.68)})}function Sm(e,t){e.samples=bm(e.samples,t)}function bm(e,t){const n=e[e.length-1];if(!n)return[];const i=t-Bm(fM+n.velocity*mM,fM,yM);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?[(l=s,d=a,c=Bm((i-s.time)/(a.time-s.time),0,1),{...Mm(l,d,c),time:Em(l.time,d.time,c),velocity:Em(l.velocity,d.velocity,c)}),...r]:r;var l,d,c}function xm(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?Cm(i,e[t]):Cm(t===e.length-1?e[t]:i,n))}function Im(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 wm(e,t){return Math.sqrt(Pm(e,t))}function Pm(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function vm(e){return{x:-e.y,y:e.x}}function km(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Cm(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Tm(e,t){return{x:e.x*t,y:e.y*t}}function Mm(e,t,n){return{x:Em(e.x,t.x,n),y:Em(e.y,t.y,n)}}function Em(e,t,n){return e+(t-e)*n}function Bm(e,t,n){return Math.max(t,Math.min(n,e))}function Am(e,t){const n=e[e.length-1];!n||Pm(n,t)>.04?e.push(t):e[e.length-1]=t}function Rm(e){if(e.length<2)return null;if(2===e.length)return`M ${Lm(e[0])} L ${Lm(e[1])} Z`;const t=[`M ${Lm($m(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 ${Lm(i)} ${Lm($m(i,o))}`)}return t.push("Z"),t.join(" ")}function $m(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function Lm(e){return`${Fm(e.x)},${Fm(e.y)}`}function Fm(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function Dm(e,t,n){return["control",n,e,t].map(encodeURIComponent).join("|")}function Um(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:xM,subpathId:n[1],nodeId:n[2]}:"path.control"!==e||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:IM,handle:n[1],subpathId:n[2],nodeId:n[3]}}function zm(e,t){t?wM.set(e,Om(t)):wM.delete(e)}function Om(e){return{...e,pagePoint:e.pagePoint.clone()}}function Xm(e){return f(e)&&"path"===e.type}function Nm(e){return"string"==typeof e&&PM.includes(e)}function Ym(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function _m(e){return new $I(e.x,e.y)}function Hm(e,t){const n=_m(t);if(!((e,t)=>!!e.out||!!t.in)(e,t))return`L ${Ym(n.x)} ${Ym(n.y)}`;const i=(e=>{const t=_m(e);return e.out?t.add(new $I(e.out.dx,e.out.dy)):t})(e),o=(e=>{const t=_m(e);return e.in?t.add(new $I(e.in.dx,e.in.dy)):t})(t);return["C",Ym(i.x),Ym(i.y),Ym(o.x),Ym(o.y),Ym(n.x),Ym(n.y)].join(" ")}function Wm(e){const t=e.nodes[0];if(!t)return null;const n=[`M ${Ym(t.x)} ${Ym(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(Hm(t,o))}if(e.closed&&e.nodes.length>1){const i=e.nodes[e.nodes.length-1];i&&n.push(Hm(i,t)),n.push("Z")}return n.join(" ")}function Km(e){const t=e.map(Wm).filter(e=>null!==e);return t.length>0?t.join(" "):null}function Vm(e){return Number.isFinite(e)}function qm(e){return{dx:e.dx,dy:e.dy}}function jm(e){return{id:e.id,x:e.x,y:e.y,kind:e.kind,...e.in?{in:qm(e.in)}:null,...e.out?{out:qm(e.out)}:null}}function Gm(e){return{id:e.id,closed:e.closed,nodes:e.nodes.map(jm)}}function Zm(e){return e.map(Gm)}function Qm(e){return new $I(e.x,e.y)}function Jm(e){const t=Qm(e);return e.in?t.add(new $I(e.in.dx,e.in.dy)):t}function ey(e){const t=Qm(e);return e.out?t.add(new $I(e.out.dx,e.out.dy)):t}function ty(e,t,n,i,o){const r=1-o,s=r*r*r,a=3*r*r*o,l=3*r*o*o,d=o*o*o;return new $I(e.x*s+t.x*a+n.x*l+i.x*d,e.y*s+t.y*a+n.y*l+i.y*d)}function ny(e,t,n){return new $I(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n)}function iy(e,t){return[Qm(e),ey(e),Jm(t),Qm(t)]}function oy(e,t){return!!e.out||!!t.in}function ry(e,t,n){return oy(e,t)?ty(...iy(e,t),n):ny(Qm(e),Qm(t),n)}function sy(e,t,n){const i=Qm(t),o=ey(t),r=Jm(n),s=Qm(n);if(t.out||n.in)for(let a=1;a<=18;a+=1)e.push(ty(i,o,r,s,a/18));else e.push(s)}function ay(e){const t=e.nodes[0];if(!t)return{id:e.id,closed:e.closed,points:[]};const n=[Qm(t)];for(let i=1;i<e.nodes.length;i+=1){const t=e.nodes[i-1],o=e.nodes[i];t&&o&&sy(n,t,o)}if(e.closed&&e.nodes.length>1){const i=e.nodes[e.nodes.length-1];i&&sy(n,i,t)}return{id:e.id,closed:e.closed,points:n}}function ly(e){const t=e.props,n=MM.get(t);if(n)return n;const i=dy(e.props);return MM.set(t,i),i}function dy(e){const t=e.subpaths.map(ay),n=t.flatMap(e=>e.points),i=e.subpaths.flatMap(e=>e.nodes.flatMap(e=>[Qm(e),...e.in?[Jm(e)]:[],...e.out?[ey(e)]:[]])),o=i.length>0?LI.FromPoints(i):new LI(0,0,1,1),r=Math.max(e.strokeWidth/2,1),s=n.length>0?LI.FromPoints(n).expand(r):o.expand(r),a=new LI(s.x,s.y,Math.max(s.w,1),Math.max(s.h,1));return{path:Km(e.subpaths),pointBounds:o,localBounds:s,renderBounds:a,outlineVertices:n.map(e=>e.clone()),flattenedSubpaths:t}}function cy(e,t){return e.map(e=>({...e,nodes:e.nodes.map(e=>((e,t)=>{const n=t(Qm(e)),i=e.in?t(Jm(e)):null,o=e.out?t(ey(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 uy(e,t){const n=dy({...t,subpaths:Zm(e)}).pointBounds,i=Number.isFinite(n.x)?n.x:0,o=Number.isFinite(n.y)?n.y:0,r=((e,t,n)=>cy(e,e=>new $I(e.x+t,e.y+n)))(e,-i,-o);return{x:i,y:o,subpaths:r,geometry:dy({...t,subpaths:r})}}function hy(e,t){return cy(e.props.subpaths,e=>t.applyToPoint(e))}function py(e,t){return Km(hy(e,t))}function gy(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 fy(e,t,n){return gy(e,t,n).distanceSquared}function my(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=oy(e,s)?32:1;let l=Qm(e);for(let n=1;n<=a;n+=1){const d=ry(e,s,n/a),c=gy(t,l,d),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:ry(e,s,u),distanceSquared:c.distanceSquared}),l=d}}}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 yy(e,t){return e.find(e=>e.id===t)??null}function Sy(e,t,n){return yy(e,t)?.nodes.find(e=>e.id===n)??null}function by(e,t,n,i){return e.map(e=>e.id!==t?Gm(e):{...e,nodes:e.nodes.map(e=>e.id===n?i(jm(e)):jm(e))})}function xy(e,t,n){const i=vy(t);return 0===i.size?Zm(e):e.map(e=>{const t=i.get(e.id);return t?{...e,nodes:e.nodes.map(e=>t.has(e.id)?n(jm(e)):jm(e))}:Gm(e)})}function Iy(e,t,n){return e.map(e=>{if(e.id!==t)return Gm(e);const i=e.nodes.findIndex(e=>e.id===n),o=e.nodes[i];if(!o)return Gm(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=Qm(o),l=((e,t,n)=>{const i=t?Qm(t):null,o=n?Qm(n):null;if(i&&o){const t=o.sub(i);if(t.len()<=kM)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<=kM||n/i<=.001})(i.sub(e),o.sub(e))?n.rot(TM):n}const r=o?o.sub(e):i?e.sub(i):null;return!r||r.len()<=kM?null:r.normalize().rot(TM)})(a,r,s),d=e.nodes.map(jm);return d[i]={...jm(o),kind:"smooth",in:r&&l?Dy(l.mul(-a.dist(Qm(r))*CM)):null,out:s&&l?Dy(l.mul(a.dist(Qm(s))*CM)):null},{...e,nodes:d}})}function wy(e,t,n){return by(e,t,n,e=>({...e,kind:"corner",in:null,out:null}))}function Py(e,t,n,i=t.at(-1)??null){if(!(e=>{const t=new Set;for(const n of e){if(!n.id||t.has(n.id))return!1;t.add(n.id);const e=new Set;for(const t of n.nodes){if(!t.id||e.has(t.id))return!1;e.add(t.id)}}return!0})(e))return null;const o=(e=>{const t=new Set,n=[];for(const i of e){const e=JSON.stringify([i.subpathId,i.nodeId]);t.has(e)||(t.add(e),n.push({subpathId:i.subpathId,nodeId:i.nodeId}))}return n})(t);if(o.length<2)return null;let r;switch(n){case"merge":r=((e,t)=>{const n=ky(t);if(null!==n)return((e,t,n)=>{const i=e.findIndex(e=>e.id===t),o=e[i];if(!o)return null;const r=((e,t)=>{const n=t.map(t=>e.nodes.findIndex(e=>e.id===t.nodeId));if(n.some(e=>e<0))return null;const i=Array.from(new Set(n)).sort((e,t)=>e-t);if(i.length!==t.length)return null;if(!e.closed)return i.every((e,t)=>0===t||e===i[t-1]+1)?i:null;if(i.length===e.nodes.length)return i;const o=i.flatMap((t,n)=>(t+1)%e.nodes.length===i[(n+1)%i.length]?[]:[n]);if(1!==o.length)return null;const r=(o[0]+1)%i.length;return[...i.slice(r),...i.slice(0,r)]})(o,n);if(!r||r.length<2)return null;const s=new Set(r),a=r.map(e=>o.nodes[e]),l=r[0],d=a[0],c=a[a.length-1],u=a.reduce((e,t)=>e.add(Qm(t)),$I.Zero()).div(a.length),h={...jm(d),x:u.x,y:u.y,kind:"corner",in:Ry(d.in,Qm(d),u),out:Ry(c.out,Qm(c),u)},p=o.nodes.flatMap((e,t)=>s.has(t)?t===l?[h]:[]:[jm(e)]),g=o.closed&&p.length>=3;return o.closed&&!g&&Ay(p),{subpaths:Ly(e,i,[{...o,closed:g,nodes:p}]),selectedNodes:[{subpathId:t,nodeId:h.id}]}})(e,n,t);const i=Cy(e,t);return i?((e,t)=>{const[n,i]=t,o=My(n),r=Ey(i),s=o[o.length-1],a=r[0],l=Qm(s).add(Qm(a)).div(2),d={...jm(s),x:l.x,y:l.y,kind:"corner",in:Ry(s.in,Qm(s),l),out:Ry(a.out,Qm(a),l)},{nodes:c}=$y(r.slice(1),new Set([...o.slice(0,-1).map(e=>e.id),d.id]),"merged"),u={...n.subpath,closed:!1,nodes:[...o.slice(0,-1),d,...c]};return{subpaths:Fy(e,t,u),selectedNodes:[{subpathId:u.id,nodeId:d.id}]}})(e,i):null})(e,o);break;case"join":r=((e,t)=>{if(2!==t.length)return null;const n=ky(t);if(null!==n)return((e,t,n)=>{const i=e.findIndex(e=>e.id===t),o=e[i];if(!o||o.closed||o.nodes.length<3)return null;const r=new Set([o.nodes[0].id,o.nodes[o.nodes.length-1].id]);if(2!==n.length||n.some(e=>!r.has(e.nodeId)))return null;const s=o.nodes.map(jm);return s[0]={...s[0],kind:"corner",in:null},s[s.length-1]={...s[s.length-1],kind:"corner",out:null},{subpaths:Ly(e,i,[{...o,closed:!0,nodes:s}]),selectedNodes:n.map(e=>({...e}))}})(e,n,t);const i=Cy(e,t);return i?((e,t)=>{const[n,i]=t,o=My(n),{nodes:r,nodeIdMap:s}=$y(Ey(i),new Set(o.map(e=>e.id)),"joined"),a=r[0];o[o.length-1]={...o[o.length-1],kind:"corner",out:null},r[0]={...a,kind:"corner",in:null};const l={...n.subpath,closed:!1,nodes:[...o,...r]};return{subpaths:Fy(e,t,l),selectedNodes:[{subpathId:l.id,nodeId:n.node.id},{subpathId:l.id,nodeId:s.get(i.node.id)??i.node.id}]}})(e,i):null})(e,o);break;case"separate":r=((e,t)=>{if(2!==t.length)return null;const n=ky(t);if(null===n)return null;const i=e.findIndex(e=>e.id===n),o=e[i];if(!o||o.nodes.length<2)return null;const r=((e,t)=>{const[n,i]=t.map(t=>e.nodes.findIndex(e=>e.id===t.nodeId));return void 0===n||void 0===i||n<0||i<0?-1:i===n+1?n:n===i+1?i:e.closed?n===e.nodes.length-1&&0===i?n:i===e.nodes.length-1&&0===n?i:-1:-1})(o,t);if(r<0)return null;if(o.closed){const n=[...o.nodes.slice(r+1).map(jm),...o.nodes.slice(0,r+1).map(jm)];return Ay(n),{subpaths:Ly(e,i,[{...o,closed:!1,nodes:n}]),selectedNodes:t.map(e=>({...e}))}}const s=o.nodes.slice(0,r+1).map(jm),a=o.nodes.slice(r+1).map(jm);Ay(s),Ay(a);const l=s.length>=2?{...o,closed:!1,nodes:s}:null,d=((e,t)=>{const n=new Set(e.map(e=>e.id));if(!n.has(t))return t;let i=2;for(;n.has(`${t}:${i}`);)i+=1;return`${t}:${i}`})(e,`${o.id}:split`),c=a.length>=2?{...o,id:d,closed:!1,nodes:a}:null,u=[l,c].filter(e=>null!==e),h=new Set(s.map(e=>e.id)),p=new Set(a.map(e=>e.id)),g=t.flatMap(e=>l&&h.has(e.nodeId)?[{subpathId:l.id,nodeId:e.nodeId}]:c&&p.has(e.nodeId)?[{subpathId:c.id,nodeId:e.nodeId}]:[]);return{subpaths:Ly(e,i,u),selectedNodes:g}})(e,o)}if(!r)return null;const s=i?o.findIndex(e=>{return(t=e).subpathId===(n=i).subpathId&&t.nodeId===n.nodeId;var t,n}):-1;return{...r,primaryNode:r.selectedNodes[s]??r.selectedNodes.at(-1)??null}}function vy(e){const t=new Map;for(const n of e){const e=t.get(n.subpathId)??new Set;e.add(n.nodeId),t.set(n.subpathId,e)}return t}function ky(e){const t=e[0];return t&&e.every(e=>e.subpathId===t.subpathId)?t.subpathId:null}function Cy(e,t){if(2!==t.length)return null;const n=Ty(e,t[0]),i=Ty(e,t[1]);return n&&i&&n.subpathIndex!==i.subpathIndex?[n,i]:null}function Ty(e,t){const n=e.findIndex(e=>e.id===t.subpathId),i=e[n];if(!i||i.closed)return null;const o=i.nodes.findIndex(e=>e.id===t.nodeId),r=i.nodes[o];return!r||0!==o&&o!==i.nodes.length-1?null:{subpath:i,subpathIndex:n,endpoint:0===o?"start":"end",node:r}}function My(e){return"end"===e.endpoint?e.subpath.nodes.map(jm):By(e.subpath.nodes)}function Ey(e){return"start"===e.endpoint?e.subpath.nodes.map(jm):By(e.subpath.nodes)}function By(e){return[...e].reverse().map(e=>({...jm(e),in:e.out?qm(e.out):null,out:e.in?qm(e.in):null}))}function Ay(e){0!==e.length&&(e[0]={...e[0],kind:"corner",in:null},e[e.length-1]={...e[e.length-1],kind:"corner",out:null})}function Ry(e,t,n){return e?Dy(t.add(new $I(e.dx,e.dy)).sub(n)):null}function $y(e,t,n){const i=new Map;return{nodes:e.map(e=>{let o=e.id;if(t.has(o)){let i=1,r=`${o}:${n}`;for(;t.has(r);)i+=1,r=`${e.id}:${n}:${i}`;o=r}return t.add(o),i.set(e.id,o),{...jm(e),id:o}}),nodeIdMap:i}}function Ly(e,t,n){return e.flatMap((e,i)=>i===t?n.map(Gm):[Gm(e)])}function Fy(e,t,n){const i=Math.min(t[0].subpathIndex,t[1].subpathIndex),o=new Set([t[0].subpathIndex,t[1].subpathIndex]);return e.flatMap((e,t)=>t===i?[n]:o.has(t)?[]:[Gm(e)])}function Dy(e){return e.len2()<=1e-12?null:{dx:e.x,dy:e.y}}function Uy(e){const t=EM.get(e);return t?(e=>({shapeId:e.shapeId,nodes:e.nodes.map(e=>({...e})),primary:{...e.primary}}))(t):null}function zy(e){const t=EM.get(e);if(!t)return null;if(e.getShapeEditingSession()?.shapeId!==t.shapeId)return null;const n=e.getShape(t.shapeId);if(!Xm(n))return null;const i=t.nodes.flatMap(e=>{const t=yy(n.props.subpaths,e.subpathId)?.nodes.find(t=>t.id===e.nodeId);return t?[{ref:{...e},node:t}]:[]});if(0===i.length)return null;const o=i.some(({ref:e})=>Wy(e,t.primary))?t.primary:i[i.length-1].ref;return{selection:{shapeId:n.id,nodes:i.map(({ref:e})=>({...e})),primary:{...o}},shape:n,entries:i}}function Oy(e){const t=EM.get(e);EM.delete(e),e.getShapeEditingSession()?.shapeId===t?.shapeId&&Hy(e,null)}function Xy(e,t,n,i){const o={subpathId:n,nodeId:i};Ny(e,t,[o],o)}function Ny(e,t,n,i=n.at(-1)??null){const o=((e,t,n)=>{const i=(e=>{const t=new Set,n=[];for(const i of e){const e=JSON.stringify([i.subpathId,i.nodeId]);t.has(e)||(t.add(e),n.push({...i}))}return n})(t).filter(t=>null!==_y(e,t));if(0===i.length)return null;const o=(n&&i.find(e=>Wy(e,n)))??i[i.length-1];return{shapeId:e.id,nodes:i,primary:{...o}}})(t,n,i);if(!o)return void Oy(e);EM.set(e,o);const r=_y(t,o.primary);Hy(e,r?e.computeShapeLocalToPageTransform(t).applyToPoint(Qm(r)):null)}function Yy(e,t,n){return e.nodes.some(e=>e.subpathId===t&&e.nodeId===n)}function _y(e,t){return yy(e.props.subpaths,t.subpathId)?.nodes.find(e=>e.id===t.nodeId)??null}function Hy(e,t){const n=e.getShapeEditingSession();n&&e.updateSession({shapeEditingSession:{...n,caretPagePoint:t?{x:t.x,y:t.y}:void 0}},"system")}function Wy(e,t){return e.subpathId===t.subpathId&&e.nodeId===t.nodeId}function Ky(e){const t=e.meta[BM],n=e.meta[AM];return{subpathId:"string"==typeof t?t:null,previewNodeId:"string"==typeof n?n:null}}function Vy(e,t){const n=qy(e);return t.subpathId&&(n[BM]=t.subpathId),t.previewNodeId&&(n[AM]=t.previewNodeId),n}function qy(e){const t={...e};return delete t[BM],delete t[AM],t}function jy({node:e,showIn:t,size:n,strokeWidth:i}){const o=Qm(e);
28
+ return Qx(Gx,{children:[t&&e.in?Zx(Gy,{anchor:o,point:Jm(e),size:n,strokeWidth:i,variant:"in"}):null,e.out?Zx(Gy,{anchor:o,point:ey(e),size:n,strokeWidth:i,variant:"out"}):null]})}function Gy({anchor:e,point:t,size:n,strokeWidth:i,variant:o}){const r=n/2;
29
+ return Qx("g",{"data-ui":"path-draft-curve-handle","data-path-draft-curve-handle":o,children:[Zx("line",{"data-ui":"path-draft-control-line",x1:e.x,y1:e.y,x2:t.x,y2:t.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:i}),Zx("rect",{"data-ui":"path-draft-control-handle",x:t.x-r,y:t.y-r,width:n,height:n,fill:$M,stroke:RM,strokeWidth:i})]})}function Zy({point:e,size:t,strokeWidth:n,variant:i}){const o=t/2;
30
+ return Zx("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)":$M,stroke:RM,strokeWidth:n})}function Qy({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}=ly({props:{...e.props,strokeWidth:r}}),a=(e=>Ky(e).previewNodeId)(e),l=Km(((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;
31
+ return Qx("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:[U(i)?null:Zx("path",{d:l,fill:F(i),fillRule:e.props.fillRule,clipRule:e.props.fillRule,stroke:"none"}),
32
+ Zx("path",{d:l,fill:"none",stroke:Zs(o,t),strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round"}),d?Zx(Jy,{shape:e}):null]})}function Jy({shape:e}){
33
+ return Zx(Gx,{children:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=Qm(t),i=[];if(t.in){const o=Jm(t);i.push(Zx("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=ey(t);i.push(Zx("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 eS(e,t){const n=zo();Oo(n.shapeEditingSessionSignal);const i=Uy(n),o=Um(e,t);return!!i&&!!o&&Yy(i,o.subpathId,o.nodeId)}function tS(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6}function nS(e){return hy(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&&tS(i,e)||t.push(e)}return t.length>1&&tS(t[0],t[t.length-1])&&t.pop(),t.length>=3?t:null})(ay(e).points)).filter(e=>null!==e).map(e=>[e])}function iS(e){const t=e.length>1&&tS(e[0],e[e.length-1])?e.slice(0,-1):e;return t.length<3?null:{id:`boolean-subpath:${FM+=1}`,closed:!0,nodes:t.map(([e,t])=>({id:`boolean-node:${DM+=1}`,x:e,y:t,kind:"corner"}))}}function oS(e){return UM.get(e)??!1}function rS(e){return((e,t)=>{const n=e.getShapeEditingSession(),i=n?e.getShape(n.shapeId):null;return!(!n||!Xm(i))&&(oS(e)===t||(UM.set(e,t),t||e.snaps.clearIndicators(),e.updateSession({shapeEditingSession:{...n}},"system")),t)})(e,!oS(e))}function sS(e){UM.delete(e),e.snaps.clearIndicators()}function aS(e){const t=e.getShapeEditingSession();if(!t)return null;const n=e.getShape(t.shapeId);return Xm(n)?n:null}function lS(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function dS(e){zm(e,null)}function cS(e){dS(e),Oy(e)}function uS(e){return e.shiftKey}function hS(e){return JSON.stringify([e.subpathId,e.nodeId])}function pS(e,t){const n=WM.get(e);if(!n)return;if(t.pointerId!==n.pointerId)return;const i=e.getShape(n.shapeId);if(!Xm(i))return void gS(e);if(!(n.isActive||(o=n.originScreenPoint,r=t.screenPoint,o.dist2(r)>=9)))return;var o,r;n.isActive=!0;const s=((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 LI(n,i,o-n,r-i)})(n.originPagePoint,t.pagePoint),a=((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t);return t.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const o=i.applyToPoint(Qm(t));return n.containsPoint(o)?[{subpathId:e.id,nodeId:t.id}]:[]}))})(e,i,s),l=uS(t)?((e,t)=>{const n=new Map(e.map(e=>[hS(e),{...e}]));for(const i of t){const e=hS(i);n.has(e)?n.delete(e):n.set(e,{...i})}return Array.from(n.values())})(n.previousEntries,a):a;e.setBrushBox(s),Ny(e,i,l,l.at(-1)??null)}function gS(e){const t=WM.get(e);if(!t)return;const n=e.getShape(t.shapeId);Xm(n)&&e.getShapeEditingSession()?.shapeId===t.shapeId?Ny(e,n,t.previousEntries,t.previousPrimary):Oy(e),WM.delete(e),e.setBrushBox(null)}function fS(e,t,n,i){const o=e.getShape(t);Xm(o)&&Ny(e,o,n,i)}function mS(e){return e.filter(e=>e.nodes.length>=2)}function yS(e,t){e.completeEditing("user"),e.getShape(t.id)&&(e.history.mark(YM),e.commands.deleteShapes([t.id],{source:"user"}),e.history.squashToMark(YM,"shape.delete"))}function SS(e,t,n){const i=mS(((e,t)=>{const n=vy(t);return 0===n.size?Zm(e):e.map(e=>{const t=n.get(e.id);if(!t)return Gm(e);const i=e.nodes.filter(e=>!t.has(e.id)).map(jm),o=e.closed&&i.length>=3;return e.closed&&!o&&Ay(i),{...e,closed:o,nodes:i}}).filter(e=>e.nodes.length>0)})(t.props.subpaths,n));0!==i.length?(e.commands.updateShapes([{id:t.id,props:{subpaths:i}}],{source:"user"}),Oy(e)):yS(e,t)}function bS(e,t){const n=zy(e);if(!n||n.shape.isLocked)return!1;const{shape:i,selection:o}=n,r=Py(i.props.subpaths,o.nodes,t,o.primary);if(!r)return!1;const s=mS(r.subpaths);return 0===s.length?(yS(e,i),!0):(e.history.mark(NM),e.commands.updateShapes([{id:i.id,props:{subpaths:s}}],{source:"user"}),fS(e,i.id,r.selectedNodes,r.primaryNode),e.history.squashToMark(NM,"shape.edit"),!0)}function xS(e,t){const n=aS(e);if(n&&e.isActiveToolInInitialState()&&("Enter"===t.key||"Escape"===t.key)&&!t.altKey&&!t.ctrlKey&&!t.metaKey&&!t.accelKey)return e.completeEditing("user");if(!(n||"Enter"!==t.key||t.altKey||t.ctrlKey||t.metaKey||t.accelKey))return(e=>{if(e.getShapeEditingSession()||"select"!==e.getActiveToolId()||!e.isActiveToolInInitialState())return!1;const t=e.getSelectedShapeIds(),[n]=e.getSelectedShapes();return!(1!==t.length||!Xm(n)||!e.canEditShape(n)||(cS(e),sS(e),!e.startEditingShape({shapeId:n.id,markId:zM,entryMode:"focusEnd"},"user")))})(e);if(t.accelKey&&("'"===t.key||"Quote"===t.code)&&n&&!n.isLocked)return rS(e),e.inputs.state.get().isPointing&&e.tools.dispatch(t),!0;if(t.accelKey&&"j"===t.key.toLowerCase()&&!t.altKey&&n&&!n.isLocked)return bS(e,"merge");const i=(e=>{if(e.altKey||e.ctrlKey||e.metaKey||e.accelKey)return null;const t=e.shiftKey?10:1;switch(e.key){case"ArrowLeft":return new $I(-t,0);case"ArrowRight":return new $I(t,0);case"ArrowUp":return new $I(0,-t);case"ArrowDown":return new $I(0,t);default:return null}})(t);if(i)return function(e,t){const n=zy(e);if(!n||n.shape.isLocked)return!1;const{shape:i,selection:o}=n,r=((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t).invert(),o=i.applyToPoint(new $I(0,0));return i.applyToPoint(n).sub(o)})(e,i,t),s=xy(i.props.subpaths,o.nodes,e=>PS(e,r));return e.history.mark(XM),e.commands.updateShapes([{id:i.id,props:{subpaths:s}}],{source:"user"}),fS(e,i.id,o.nodes,o.primary),e.history.squashToMark(XM,"shape.edit"),!0}(e,i);if(t.altKey||t.ctrlKey||t.metaKey||t.accelKey)return!1;const o=zy(e);if(!o||o.shape.isLocked)return!1;const r=t.key.toLowerCase();return"backspace"===r||"delete"===r?(SS(e,o.shape,o.selection.nodes),!0):"c"===r?((e,t,n)=>{const i=n.filter(e=>{const n=Sy(t.props.subpaths,e.subpathId,e.nodeId);return!!n&&!n.in&&!n.out});if(0===i.length)return!1;const o=i.reduce((e,t)=>Iy(e,t.subpathId,t.nodeId),t.props.subpaths);return e.commands.updateShapes([{id:t.id,props:{subpaths:o}}],{source:"user"}),fS(e,t.id,n,n.at(-1)??null),!0})(e,o.shape,o.selection.nodes):"x"===r?(((e,t,n)=>{const i=n.reduce((e,t)=>wy(e,t.subpathId,t.nodeId),t.props.subpaths);e.commands.updateShapes([{id:t.id,props:{subpaths:i}}],{source:"user"}),fS(e,t.id,n,n.at(-1)??null)})(e,o.shape,o.selection.nodes),!0):"j"===r?bS(e,"join"):"k"===r&&bS(e,"separate")}function IS(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 wS(e,t){const n=t.sub(e),i=n.len();if(0===i)return t.clone();const o=Math.round(Math.atan2(n.y,n.x)/_M)*_M;return e.add(new $I(Math.cos(o)*i,Math.sin(o)*i))}function PS(e,t){return{...e,x:e.x+t.x,y:e.y+t.y}}function vS(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function kS(e){if(!e||"object"!=typeof e)return null;const t=e,n=vS(t.dx,NaN),i=vS(t.dy,NaN);return Number.isFinite(n)&&Number.isFinite(i)?t.dx===n&&t.dy===i?e:{dx:n,dy:i}:null}function CS(e,t){if(!Array.isArray(e))return t;const n=new Set,i=e.map((e,t)=>function(e,t,n){if(!e||"object"!=typeof e)return null;const i=e,o=new Set,r=Array.isArray(i.nodes)?i.nodes.map((e,t)=>((e,t,n)=>{if(!e||"object"!=typeof e)return null;const i=e,o=vS(i.x,NaN),r=vS(i.y,NaN);return Number.isFinite(o)&&Number.isFinite(r)?{id:TS("string"==typeof i.id&&i.id.length>0?i.id:`node:${t}`,n),x:o,y:r,kind:(s=i.kind,"string"==typeof s&&vM.includes(s)?i.kind:"corner"),in:kS(i.in),out:kS(i.out)}:null;var s})(e,t,o)).filter(e=>null!==e):[];return 0===r.length?null:{id:TS("string"==typeof i.id&&i.id.length>0?i.id:`subpath:${t}`,n),closed:"boolean"==typeof i.closed&&i.closed,nodes:r}}(e,t,n)).filter(e=>null!==e);return i.length>0?i:t}function TS(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}:${n}`);)n+=1;const i=`${e}:${n}`;return t.add(i),i}function MS(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 ES(e,t){const n=t(Qm(e)),i=e.in?t(Jm(e)):null,o=e.out?t(ey(e)):null;return{...jm(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 BS(){return`node:${qM+=1}`}function AS(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function RS(e,t,n,i){const o=(yy(t.props.subpaths,n)?.nodes.filter(e=>e.id!==i))?.at(-1);return o?e.computeShapeLocalToPageTransform(t).applyToPoint(new $I(o.x,o.y)):null}function $S(e,t){const n=t.sub(e),i=n.len();if(0===i)return t.clone();const o=Math.round(Math.atan2(n.y,n.x)/VM)*VM;return e.add(new $I(Math.cos(o)*i,Math.sin(o)*i))}function LS(e,t){return t.previewNodeId?e.map(e=>e.id===t.subpathId?{...e,nodes:e.nodes.filter(e=>e.id!==t.previewNodeId)}:e):Zm(e)}function FS(e,t){return yy(e.props.subpaths,t.subpathId)?.nodes.filter(e=>e.id!==t.previewNodeId).length??0}function DS(){return{id:"path.floating-node-snap",items:[{kind:"button",id:"path.floating-node.snap",actionId:eE,label:"Snap nodes",shortcut:"Mod+'",icon:"magnet",dataUi:"floating-path-node-snap-button"}]}}function US({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,fillRuleActionId:i,dataUiPrefix:o}){return[{id:`${o}.style-fill`,items:[{kind:"color-input",id:`${o}.fill`,actionId:e,label:"Fill",fallback:"#f8fafc",presets:uE.map(e=>({...e,dataUi:`${o}-fill-${e.id}-button`})),dataUi:`${o}.fill`}]},{id:`${o}.style-stroke`,items:[{kind:"color-input",id:`${o}.stroke`,actionId:t,label:"Stroke",fallback:"#334155",presets:hE.map(e=>({...e,dataUi:`${o}-stroke-${e.id}-button`})),dataUi:`${o}.stroke`}]},{id:`${o}.style-stroke-width`,items:[{kind:"stepper",id:`${o}.stroke-width`,actionId:n,label:"Stroke width",dataUi:`${o}-stroke-width-control`,options:pE.map(e=>({...e,dataUi:`${o}-stroke-width-${e.value}-button`}))}]},{id:`${o}.fill-rule`,items:[{kind:"segmented",id:`${o}.fill-rule`,actionId:i,options:gE.map(e=>({...e,dataUi:`${o}-fill-rule-${e.value}-button`}))}]}]}function zS(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(!Xm(i))continue;const e=i.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!z(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=_S(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(Xm).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));o.length>0&&t.editor.commands.updateShapes(o,{source:"user"})}}}function OS(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=_S(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("path",{[e]:i})}}}function XS(e,t){return{id:e,isVisible:e=>!!zy(e.editor),isEnabled(e){const n=zy(e.editor);return!!n&&!n.shape.isLocked&&((e,t,n)=>null!==Py(e,t,n))(n.shape.props.subpaths,n.selection.nodes,t)},run({context:e}){const n=zy(e.editor);n&&!n.shape.isLocked&&bS(e.editor,t)}}}function NS(e){return{id:`path.boolean.${e}`,isVisible:e=>"path"===e.selection.commonShapeType,isEnabled:e=>YS(e).length>=2,run({context:t}){const n=YS(t),i=n[0];if(!i||n.length<2)return;const o=((e,t,n)=>{const i=function(e,t){const n=t.map(nS).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,LM.union)(n,...i);case"subtract":return(0,LM.difference)(n,...i);case"intersect":return(0,LM.intersection)(n,...i);case"xor":return(0,LM.xor)(n,...i)}})(e,n).flatMap(e=>e).map(iS).filter(e=>null!==e)}(e,t);return 0===i.length?null:uy(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 YS(e){return e.selection.selectedShapes.filter(Xm).filter(e=>!e.isLocked).filter(e=>e.props.subpaths.some(e=>e.closed&&e.nodes.length>=3))}function _S(e,t){return"strokeWidth"===e?"number"==typeof t&&pE.some(e=>e.value===t)?t:void 0:R(t)?L(t,M("fill"===e?"fill-blue":"stroke-slate")):void 0}function HS(e={}){return fE.filter(([t])=>!1!==e[t]).map(([t,n])=>{if("text"===t){const t=e.text;return"object"==typeof t?Va(t):n}return n})}function WS({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 KS(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 VS(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function qS(e){const t=e.getDocumentMetadataRecord();return{id:t?.id??"document:main",meta:{...t?.meta??{}}}}function jS(e,t){return{id:t.id,type:t.type,parentId:t.parentId,pageId:e.getShapePageId(t.id),index:t.index,x:t.x,y:t.y,rotation:t.rotation,skewX:t.skewX,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,props:{...t.props},meta:{...t.meta}}}function GS(e){return{id:e.id,x:e.x,y:e.y,rotation:e.rotation,skewX:e.skewX,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function ZS(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 QS(e,t){const n=e.getActiveToolId();t.assertToolId(n);const i=n;return{productId:t.productId,document:qS(e),pageId:e.getCurrentPageId(),activeToolId:i,selectedShapeIds:[...e.getSelectedShapeIds()],shapeCount:e.getCurrentPageShapeIds().length,session:ZS(e,t)}}function JS(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 eb(e){return{...e,meta:{...e.meta}}}function tb(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 nb(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}function ib(e,t){e.includes(t)||e.push(t)}function ob(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 rb(e){const{apis:t,editor:n}=e;return{apis:t,snapshot:()=>QS(n,e),subscribe(t){let i=JS(QS(n,e));return n.listen(o=>{const r=ob(o.diff,"document"),s=ob(o.diff,"session");if(!r&&!s)return;const a=s?QS(n,e):((e,t,n,{hasDocumentMetadataChange:i})=>{return{productId:n.productId,document:i?qS(e):eb(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:(l=o.diff,l.added.some(e=>"document"===e.typeName)||l.updated.some(e=>"document"===e.before.typeName||"document"===e.after.typeName)||l.removed.some(e=>"document"===e.typeName))});var l;const d=function(e,t){const n=[];return e.pageId!==t.pageId&&n.push("pageId"),e.activeToolId!==t.activeToolId&&n.push("activeToolId"),tb(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||!tb(i.selectedShapeIds,o.selectedShapeIds)||!nb(i.camera,o.camera))return!1}return!0})(e.session,t.session)||n.push("session"),n}(i,a);if(r&&ib(d,"document"),s&&ib(d,"session"),0===d.length)return void(i=JS(a));const c=i;i=JS(a);try{t({source:o.source,changes:d,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:()=>qS(n),updateDocumentMeta:e=>(n.updateDocumentMeta(e,"user"),qS(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?jS(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=>jS(n,e)),updateShapes(e){const t=e.filter(e=>{const t=n.getShape(e.id);return!!t&&function(e,t){return!(!t.props&&void 0===t.meta)||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.skewX??e.skewX)!==e.skewX||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(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(GS);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(WS({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 WS({childIds:e.getChildShapeIds(n.id),depth:KS(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(VS),createPage:e=>VS(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 sb(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 ab(e){return{create(t){const n=e.getDefaultShapeProps("arrow"),i=vh(e,{startPagePoint:new $I(t.start.x,t.start.y),endPagePoint:new $I(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 lb(e){return{createRectangle:t=>sb(e,"rectangle",t),createEllipse:t=>sb(e,"ellipse",t),createDiamond:t=>sb(e,"diamond",t),createTriangle:t=>sb(e,"triangle",t),createHexagon:t=>sb(e,"hexagon",t),createStar:t=>sb(e,"star",t)}}function db(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:Er(t.text)}}],{source:"user"});return i&&"text"===i.type?{id:i.id,type:i.type}:null}}}function cb(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 ub(e,t){const n=e.getShape(t.id);if("geo"===t.type){const e=(n?.props)?.geo;return{...t,displayName:hb(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?Br(e.richText).replace(/\s+/g," ").trim():"";return{...t,displayName:i.length>0?i:"Text"}}if("packaging"===t.type){const e=(n?.props)?.document.name;return{...t,displayName:e?.trim()||"Packaging"}}if("frame"!==t.type)return t;const i=(n?.props)?.name;return{...t,displayName:i&&i.length>0?i:"Frame"}}function hb(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 pb(e){return"packaging"===e?.type}function gb(e){const t=rb(e),n={arrow:ab(i=e.editor),geo:lb(i),text:db(i),frame:cb(i)};var i;const o=e.editor.shapeUtils.has("packaging")?(e=>{const t=t=>{const n=Ul(Dl(t.document)),i=e.getDefaultShapeProps("packaging"),o=t.viewSide??i.viewSide,[r]=e.commands.createShapes([{type:"packaging",x:t.x,y:t.y,scaleX:"inside"===o?-1:1,meta:t.meta?{...t.meta}:void 0,props:{...i,document:n,viewSide:o,faceFill:t.faceFill??i.faceFill,faceFillOverrides:t.faceFillOverrides?{...t.faceFillOverrides}:i.faceFillOverrides,showBleed:t.showBleed??i.showBleed,clipToBleed:t.clipToBleed??i.clipToBleed,dielineOnTop:t.dielineOnTop??i.dielineOnTop,showSafeZones:t.showSafeZones??i.showSafeZones,showCanvasBoundsMarks:t.showCanvasBoundsMarks??i.showCanvasBoundsMarks}}],{source:"user"});return pb(r)?{id:r.id,type:r.type}:null};return{create:t,importDxf(n){const i=$d(n.source,{...n.options,fileName:n.fileName}),o=qa(i,"outside").bounds,r=e.viewportPageBoundsSignal.get()?.center??e.screenToPage(new $I(360,240)),s=n.pagePoint?new $I(n.pagePoint.x,n.pagePoint.y):r,a=t({x:s.x-o.center.x,y:s.y-o.center.y,document:i,meta:{importedFrom:"dxf"}});return a&&e.commands.setSelectedShapeIds([a.id],{source:"user"}),a},updateDocument({packagingId:t,document:n,expectedRevision:i}){const o=e.getShape(t);if(!pb(o)||void 0!==i&&o.props.document.revision!==i)return null;const r=Ul(Dl(n));e.commands.updateShapes([{id:o.id,props:{document:r}}],{source:"user"});const s=e.getShape(o.id);return pb(s)?{id:s.id,type:s.type}:null},getDocument(t){const n=e.getShape(t);return pb(n)?Ul(n.props.document):null},async exportPdf({packagingId:t,options:n={}}){const i=e.getShape(t);if(!pb(i))return null;const o=n.side??i.props.viewSide;return async function(e,t={}){const n=Dl(e),i=t.side??"outside",o=t.includeBleed??!0,r=t.includeSafeZones??!1,s=t.includeAnnotations??!0,a=ac(n.unit,t.unitlessPointsPerUnit),l=cc(t.lineWidthPoints,.25,"Packaging PDF line width"),d=qa(n,i),c=[...d.edgesById.values()].filter(({edge:e})=>!1!==e.visible&&(s||"annotation"!==e.operation&&"construction"!==e.operation)),u=(({document:e,geometry:t,visibleEdges:n,includeBleed:i,includeSafeZones:o,margin:r})=>{if(e.sheetBounds)return{...e.sheetBounds};const s=n.map(({bounds:e})=>e);if(i&&s.push(...[...t.bleedContoursById.values()].map(e=>e.bounds)),o&&s.push(...[...t.safeZonesById.values()].map(e=>e.bounds)),0===s.length)return{x:0,y:0,w:0,h:0};const a=Math.min(...s.map(e=>e.minX))-r,l=Math.min(...s.map(e=>e.minY))-r;return{x:a,y:l,w:Math.max(...s.map(e=>e.maxX))+r-a,h:Math.max(...s.map(e=>e.maxY))+r-l}})({document:n,geometry:d,visibleEdges:c,includeBleed:o,includeSafeZones:r,margin:uc(t.marginInDocumentUnits,dc(n.unit,a),"Packaging PDF margin")});if(!(u.w>0&&u.h>0))throw new Error("Cannot export an empty Packaging document to PDF.");const h=u.w*a,p=u.h*a,g=await import("./es-DocrZgUh.mjs"),f=await g.PDFDocument.create();f.setTitle(`${n.name} dieline`),f.setSubject(`Packaging dieline (${i})`),f.setCreator("Land"),f.setProducer("Land Packaging PDF exporter"),f.setKeywords(["packaging","dieline",i,n.unit]);const m=f.addPage([h,p]),y={x:-u.x*a,y:p+u.y*a};t.mirror&&m.pushOperators(g.pushGraphicsState(),g.translate(h,0),g.scale(-1,1));for(const S of c)lc({page:m,path:S.path,style:vk[S.edge.operation],pathOrigin:y,pointsPerUnit:a,lineWidthPoints:l,pdfLib:g});if(o)for(const S of d.bleedContoursById.values())lc({page:m,path:S.path,style:kk,pathOrigin:y,pointsPerUnit:a,lineWidthPoints:l,pdfLib:g});if(r)for(const S of d.safeZonesById.values())lc({page:m,path:S.path,style:Ck,pathOrigin:y,pointsPerUnit:a,lineWidthPoints:l,pdfLib:g});return t.mirror&&m.pushOperators(g.popGraphicsState()),{bytes:await f.save(),filename:hc(n.name,i),side:i,page:{width:u.w,height:u.h,unit:n.unit,widthPoints:h,heightPoints:p}}}(i.props.document,{includeBleed:i.props.showBleed,includeSafeZones:i.props.showSafeZones,...n,side:o,mirror:n.mirror??"inside"===o})},attachShapes({packagingId:t,shapeIds:n}){const i=e.getShape(t);if(!pb(i))return[];const o=Array.from(new Set(n)).filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked&&!n.isHidden&&e.canUseShapeParent(i.id,n.id)});return 0===o.length?[]:e.commands.reparentShapes({ids:o,parentId:i.id},{source:"user"})?o:[]},detachShapes({packagingId:t,shapeIds:n,destinationPageId:i}){const o=e.getShape(t),r=pb(o)?e.getShapePageId(o.id):null,s=i??r;if(!pb(o)||!s||!e.getPage(s))return[];const a=Array.from(new Set(n)).filter(t=>{const n=e.getShape(t);return!!n&&n.parentId===o.id&&!n.isLocked&&!n.isHidden});return 0===a.length?[]:e.commands.reparentShapes({ids:a,parentId:s},{source:"user"})?a:[]},hitTestFace({packagingId:t,pagePoint:n}){const i=e.getShape(t);if(!pb(i))return null;const o=e.computeShapeLocalToPageTransform(i).tryInvert();if(!o)return null;const r=o.applyToPoint(new $I(n.x,n.y)),s=Ja(qa(i.props.document,i.props.viewSide),r);if(!s)return null;const a=function(e,t){const n=e.artworkFrame?.uvToDocument;if(!n)return null;const i=ol(n);return i?((e,t)=>new $I(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5]))(i,t):null}(s.face,r);return{faceId:s.face.id,localPoint:{x:r.x,y:r.y},faceUv:a?{x:a.x,y:a.y}:null}},getCoveredFaces({packagingId:t,shapeId:n}){const i=e.getShape(t),o=e.getShape(n);if(!pb(i)||!o)return[];const r=e.getShapePageId(i.id),s=e.getShapePageId(o.id);if(!r||!s||r!==s)return[];const a=e.computeShapeLocalToPageTransform(i).tryInvert();if(!a)return[];let l=e.getShapePageOutlineVertices(o.id);if(0===l.length){const t=e.getShapePageBounds(o.id);l=t?[new $I(t.minX,t.minY),new $I(t.maxX,t.minY),new $I(t.maxX,t.maxY),new $I(t.minX,t.maxY)]:[]}return tl(qa(i.props.document,i.props.viewSide),l.map(e=>a.applyToPoint(e)))}}})(e.editor):null;return{...t,...n,packaging:o,getLayerTree:n=>t.getLayerTree(n).map(t=>ub(e.editor,t)),getLayerNode(n){const i=t.getLayerNode(n);return i?ub(e.editor,i):null}}}function fb(e){if(!(e=>yE.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: ${SE}.`);throw new Error(`Unknown canvas kit tool "${e}". Available tool ids: ${SE}.`)}}function mb(e){return yb({...e,assertToolId:e.assertToolId??fb})}function yb(e){return{...gb(e)}}function Sb({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 bb(e,t){const n=Nx(n=>t?Ro("useOptionalValue",e,n,{fireImmediately:!1}):()=>{},[t,e]),i=Nx(()=>t?e.get():null,[t,e]);return jx(n,i,i)}function xb({assetInliners:e=[],editor:t,themeRootRef:n}){const[i,o]=qx(null);return{status:i,exportSvg:Nx(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),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((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: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 o(r.status),r},[e,t,n])}}function Ib({controller:e,activeContextMenu:t,grid:n,onActiveContextMenuChange:i,actionRegistry:o,canShowToolbarDuringEditing:r,contextMenuRegistry:s,editor:a,executeCommand:l,svgAssetInliners:d,themeRootRef:c,toolbarRegistry:u}){const h=Oo(a.currentPageIdSignal),p=Oo(a.currentPageShapeIdsSignal),g=Oo(a.selectedShapeIdsSignal),f=Oo(a.selectionMetadataSignal),m=(({editor:e,executeCommand:t})=>{const n=Oo(e.historyStateSignal);return{canUndo:n.canUndo,canRedo:n.canRedo,undo(){t({commandId:"history.undo",run(){e.undo()}})},redo(){t({commandId:"history.redo",run(){e.redo()}})}}})({editor:a,executeCommand:l}),y=(({editor:e,executeCommand:t})=>{const n=Oo(e.pageStateSignal);return{pages:n.pages,currentPage:n.currentPage,currentPageId:n.currentPageId,canDeleteCurrentPage:n.canDeleteCurrentPage,createPage(){t({commandId:"page.create",run(){e.createPageAndSelect(void 0,"user")}})},deleteCurrentPage(){if(!n.currentPage)return;const i=n.currentPage.id;t({commandId:"page.delete-current",run(){e.deletePage(i,"user")}})},renameCurrentPage(i){if(!n.currentPage)return;const o=n.currentPage.id;t({commandId:"page.rename-current",run(){e.renamePage(o,i,"user")}})},selectPage(n){t({commandId:"page.select",run(){e.selectPage(n,"user")}})}}})({editor:a,executeCommand:l}),S=(e=>{const t=Oo(e.cameraZoomSignal);return{zoom:t,label:`${Math.round(100*t)}%`,zoomIn(){e.zoomAtViewportCenter(-120,"system")},zoomOut(){e.zoomAtViewportCenter(120,"system")},resetZoom(){e.resetZoom("user")}}})(a),b=function({editor:e,activeContextMenu:t,contextMenuRegistry:n}){const i=null!==t,o=bb(e.selectionStateSignal,i),r=bb(e.toolStateSignal,i);return Kx(()=>{if(!t||!o||!r)return{context:null,activeContextMenu:null,sections:[]};const i=(({editor:e,menu:t})=>{const n=e.toolStateSignal.get();return{...Sb({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.getSections(s,i)}},[e,t,n,o,r])}({editor:a,activeContextMenu:t,contextMenuRegistry:s}),x=function({canShowContextToolbarDuringEditing:e,editor:t,toolbarRegistry:n}){const i=Nx(e=>n.subscribeToState(t,e),[t,n]),o=Nx(()=>n.getStateRevision(),[n]);jx(i,o,o);const r=Oo(t.toolStateSignal),s=Oo(t.selectionMetadataSignal);(e=>{const t=Nx(t=>Ro("useToolbarSelectionShapeState",e.selectedShapesSignal,t,{fireImmediately:!1}),[e]),n=Kx(()=>{let t=[];return()=>{const n=e.getSelectedShapes().map(e=>[e.id,e.type,e.parentId,e.index,e.rotation,e.skewX,e.scaleX,e.scaleY,e.opacity,e.isHidden,e.isLocked,e.props,e.meta]);return((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o)return!1;for(let e=0;e<i.length;e+=1)if(!Object.is(i[e],o[e]))return!1}return!0})(t,n)||(t=n),t}},[e]);jx(t,n,n)})(t);const a=Oo(t.shapeEditingStateSignal),l="select"===r.activeToolId,d=l?s.count:0,c=Sb({editor:t,selectionState:s,toolState:r}),u=!a.session||(e?.(c)??!1),h=l&&s.count>0,p=h?n.getGroups("selection",c,{placement:"context"}):bE,g=h?n.getGroups("selection",c,{placement:"floating"}):bE,f=(u||null!==a.session&&g.length>0)&&s.count>0&&g.length>0,m=n.getGroups("tool",c,{placement:"context"}),y=n.getGroups("tool",c,{placement:"chrome"}),S=a.session?bE:n.getGroups("tool",c,{placement:"floating"}),b=l&&s.count>0?p:m,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})(m,r.activeToolId),w=l&&s.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:s.commonShapeType,count:d,isMixedFrameAndPointHandleSelection:s.isMixedFrameAndPointHandleSelection,singleShapeType:s.singleShapeType}):I;return{context:c,activeToolId:r.activeToolId,activeToolLabel:I,isToolLocked:r.isToolLocked,selectionCount:d,hasMixedSelectionRotation:s.hasMixedSelectionRotation,toolChromeToolbarGroups:y,toolFloatingToolbarGroups:S,contextToolbarGroups:b,floatingSelectionToolbarGroups:g,contextToolbarTitle:w,showContextToolbar:x,canShowFloatingSelectionToolbar:f}}({canShowContextToolbarDuringEditing:r,editor:a,toolbarRegistry:u}),I=xb({assetInliners:d,editor:a,themeRootRef:c}),w=Kx(()=>{let t,n=[],i=[];return{getSnapshot(o){const r=o??a.getCurrentPageId(),s=((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})(a,r);return t===r&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0})(n,s)||(t=r,n=s,i=e.getLayerTree(r)),i},subscribe:e=>Ro("CanvasKitLayerTree.records",a.store.recordsSignal,e,{fireImmediately:!1})}},[e,a]),P=Kx(()=>({getActionState({actionId:e,context:t}){const n=o.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=o.getAction(e);i&&!1!==i.isVisible?.(t)&&!1!==i.isEnabled?.(t)&&l({commandId:e,context:t,run(){i.run({context:t,value:void 0!==n?n:i.getValue?.(t)??null})}})}}),[o,l]);return{controller:e,contextMenu:{activeContextMenu:t,onActiveContextMenuChange:i,runAction({actionId:e,context:t,value:n}){l({commandId:e,context:t,run(){(({actionRegistry:e,actionId:t,context:n,value:i})=>{const o=e.getAction(t);o&&!1!==o.isVisible?.(n)&&!1!==o.isEnabled?.(n)&&o.run({context:n,value:void 0!==i?i:o.getValue?.(n)??null})})({actionRegistry:o,actionId:e,context:t,value:n})}})},surface:b},currentPageId:h,currentPageShapeIds:p,history:m,layerTree:w,pages:y,selection:f,selectedShapeIds:g,svgExport:I,toolbarRuntime:P,toolbarSurfaces:x,grid:n,zoom:S}}function wb(){return"undefined"==typeof indexedDB?Promise.resolve(null):(wE||(wE=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(xE),e.objectStoreNames.contains("imageBlobs")||e.createObjectStore(IE)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),wE=null}),e(t)}),n.addEventListener("error",()=>{wE=null,t(n.error)})})),wE)}async function Pb(e,t){if(0===t.length)return[];const n=await wb();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 vb(e,t){if(0===t.length)return;const n=await wb();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)})}async function kb(e,t={}){const n=JSON.stringify(e.getDocumentSnapshot()),i=JSON.stringify(e.getSessionSnapshot());await vb(xE,[[Cb(t),n],[Tb(t),i]])}function Cb(e){return e.storageNamespace?`${e.storageNamespace}.document`:"land.canvas.document"}function Tb(e){return e.storageNamespace?`${e.storageNamespace}.session`:"land.canvas.session"}function Mb(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function Eb({assetResolverTokens:e,services:t}){return e.map(e=>t.get(e)).filter(e=>!!e)}function Bb(e){return{id:e}}function Ab(e){return{id:e}}function Rb(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function $b(e){return e.get(vE)}async function Lb({context:e,services:t}){const n=$b(t);if(!n)return null;const i=e.editor.createClipboardPayloadFromSelection();return i?(await n.write(i),i):null}async function Fb({atMenuPoint:e=!1,context:t,services:n}){const i=$b(n);if(!i)return;const o=await i.read();o&&t.editor.pasteClipboardPayload({payload:o,pagePoint:Db({atMenuPoint:e,context:t}),source:"user"})}function Db({atMenuPoint:e,context:t}){return e&&Ub(t)?t.menu.anchor.pagePoint:t.editor.inputs.state.get().currentPagePoint??t.editor.viewportPageBoundsSignal.get()?.center??void 0}function Ub(e){return"menu"in e}async function zb(e){const t=await(async(e,t)=>(await Pb(e,[t]))?.[0]??null)(IE,e);return t instanceof Blob?t:null}async function Ob(e){const t=await zb(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 Xb(e){await(async(e,t)=>{const n=await wb();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)})})(IE,e)}function Nb(e,t){const n=e.getAsset(t);if(!Nf(n)||"local"!==n.props.source.kind)return null;const{storageKey:i}=n.props.source;return i.length>0?i:null}function Yb(e){const t=new Set;for(const n of e.getAssets())Nf(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&t.add(n.props.source.storageKey);return t}function _b(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 Hb(e){const t=Kb(e)?e:e.blob,n=(Kb(e),e.name),i=Kb(e)?e.type:e.mimeType||e.blob.type,o=URL.createObjectURL(t),r=await _b(o).finally(()=>{URL.revokeObjectURL(o)}),{storageKey:s}=await async function(e){const t="undefined"!=typeof crypto&&"randomUUID"in crypto?`${RE}${crypto.randomUUID()}`:`${RE}${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 vb(IE,[[t,e]]),{storageKey:t}}(t);return{name:n||"Image",source:{kind:"local",storageKey:s,...!Kb(e)&&e.originalUrl?{originalUrl:e.originalUrl}:{}},mimeType:i||"image/png",fileSize:t.size,width:r.width,height:r.height}}async function Wb({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 Hb({blob:i,name:e||Vb(t)||"Image",mimeType:i.type||n.headers.get("content-type")||void 0,originalUrl:t})}function Kb(e){return"undefined"!=typeof File&&e instanceof File}function Vb(e){try{const t=new URL(e).pathname.split("/").filter(Boolean).at(-1);return t?decodeURIComponent(t):null}catch{return null}}function qb(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 jb(e,t){return function(e,t,n){return e.screenToPage(((e,t=pr())=>{if(!t)return new $I(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new $I(e.clientX-n.left,e.clientY-n.top)})(t,n))}(e,t)}function Gb({filename:e,url:t}){const n=document.createElement("a");n.href=t,n.download=e,n.click()}async function Zb({blob:e,filename:t}){const n=URL.createObjectURL(e);try{Gb({filename:t,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function Qb(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 Jb(e,t){return e.getDocumentSnapshot().records.some(e=>"shape"===e.typeName&&e.props.assetId===t)}async function ex({editor:e,imageObjectUrls:t,pagePoint:n,size:i,flushSnapshot:o,source:r,strategy:s="auto"}){if("file"===r.type)return cx(r.file)?nx({editor:e,imageObjectUrls:t,input:await Hb(r.file),pagePoint:n,size:i,flushSnapshot:o}):null;if("blob"===r.type)return cx(r.blob)?nx({editor:e,imageObjectUrls:t,input:await Hb(r),pagePoint:n,size:i,flushSnapshot:o}):null;if("copy"===s)return nx({editor:e,imageObjectUrls:t,input:await Wb(r),pagePoint:n,size:i,flushSnapshot:o});if("link"===s)return tx({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:i,flushSnapshot:o,copyInBackground:!1});try{return await tx({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:i,flushSnapshot:o,copyInBackground:!0})}catch{return nx({editor:e,imageObjectUrls:t,input:await Wb(r),pagePoint:n,size:i,flushSnapshot:o})}}async function tx({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 _b(t);return{name:e||Vb(t)||"Image",source:{kind:"remote",url:t},mimeType:null,width:n.width,height:n.height}})(s),l={kind:"remote",url:s.url,...e?{copyState:{status:"pending-local-copy"}}:{}},d=await nx({editor:t,imageObjectUrls:i,input:{...a,source:l},pagePoint:o,size:r,flushSnapshot:n,altText:s.altText}),c=d?t.getShape(d):null,u=Yf(c)?c.props.assetId:null;return e&&u&&ix({assetId:u,editor:t,flushSnapshot:n,imageObjectUrls:i,source:s}),d}async function nx({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 l=null;try{const t=Qb(e,n);l=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}),d=e.viewportPageBoundsSignal.get(),c=i??d?.center??e.screenToPage(new $I(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(d){throw l&&e.commands.deleteAsset(l,{source:"system"}),a&&(t.release(a),await Xb(a)),d}}async function ix({assetId:e,editor:t,flushSnapshot:n,imageObjectUrls:i,source:o}){try{const r=await Wb(o),s="local"===r.source.kind?r.source.storageKey:null;if(!s)return;await i.preload(s);const a=t.getAsset(e);if(!Nf(a)||"remote"!==a.props.source.kind||a.props.source.url!==o.url||!Jb(t,e))return i.release(s),void(await Xb(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);Nf(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:ux(n)}}}},{source:"system"}),await(i?.(t)))})({assetId:e,editor:t,error:r,flushSnapshot:n,url:o.url})}}async function ox({editor:e,file:t,imageObjectUrls:n,flushSnapshot:i}){if(!cx(t))return;const[o]=e.getSelectedShapes();if(!Yf(o)||o.isLocked)return;const r=await Hb(t);await sx({editor:e,flushSnapshot:i,imageObjectUrls:n,input:r,nextProps:{crop:null,altText:r.name},shape:o})}async function rx({editor:e,imageObjectUrls:t}){const[n]=e.getSelectedShapes();if(!Yf(n)||!n.props.assetId)return;const i=e.getAsset(n.props.assetId);if(!Nf(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 Zb({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 zb(r);if(s)return void(await Zb({blob:s,filename:o}));const a=t.resolve(r);a&&Gb({filename:o,url:a})}async function sx({canCommit:e,editor:t,flushSnapshot:n,imageObjectUrls:i,input:o,nextProps:r,shape:s}){const a=s.props.assetId,l="local"===o.source.kind?o.source.storageKey:null;try{l&&await i.preload(l)}catch(h){throw await lx({imageObjectUrls:i,storageKey:l}),h}const d=t.getShape(s.id);if(!Yf(d)||d.isLocked||d.props.assetId!==a||e&&!e())return await lx({imageObjectUrls:i,storageKey:l}),null;const c=`image.asset.replace:${s.id}:${$E++}`;let u;t.history.mark(c);try{const e=Qb(t,o);t.commands.updateShapes([{id:s.id,props:{assetId:e.id,...r}}],{source:"user"}),a&&!Jb(t,a)&&t.commands.deleteAsset(a,{source:"user"}),t.history.squashToMark(c,"image.asset.replace"),u={assetId:e.id,storageKey:l}}catch(h){throw t.history.bailToMark(c),await lx({imageObjectUrls:i,storageKey:l}),h}return await ax({editor:t,flushSnapshot:n,operation:"image replacement"}),u}async function ax({editor:e,flushSnapshot:t,operation:n}){if(t)try{await t(e)}catch(i){console.warn(`Could not persist ${n}; the local change remains available.`,i)}}async function lx({imageObjectUrls:e,storageKey:t}){t&&(e.release(t),await Xb(t))}async function dx(e){try{const t=await fetch(e);if(!t.ok)return null;const n=await t.blob();return cx(n)?n:null}catch{return null}}function cx(e){return!e.type||e.type.startsWith("image/")}function ux(e){return e instanceof Error?e.message:String(e)}function hx({flushSnapshot:e}={}){return{token:FE,create(){const t=function(){const e=new Map,t=new Map;let n=0,i=!1;const o=async(o,r={})=>{if(r.signal?.throwIfAborted(),i)return null;const s=e.get(o);if(s)return s;const a=t.get(o);if(a)return a;const l=n,d=zb(o).then(t=>{if(r.signal?.throwIfAborted(),!t||i||l!==n)return null;const s=URL.createObjectURL(t);return e.set(o,s),s}).finally(()=>{t.delete(o)});return t.set(o,d),d};return{async preloadForEditor(e,t={}){t.signal?.throwIfAborted(),await Promise.all(Array.from(Yb(e)).map(e=>o(e,t)))},preload:o,resolve:t=>e.get(t)??null,resolveAssetUrl(t,n){const i=((e,t)=>{const n=e.getAsset(t);return Nf(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=Nb(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(){i=!0,n+=1;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);Nf(r)&&"remote"===r.props.source.kind&&"pending-local-copy"===r.props.source.copyState?.status&&(n.add(o),ix({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,{signal:n}){n.throwIfAborted(),await(async({editor:e,objectUrls:t})=>{const n=Yb(e),i=await async function(){return(await(async e=>{const t=await wb();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 Xb(r),o.push(r));return o})({editor:e,objectUrls:t}),n.throwIfAborted(),(e=>{for(const t of e.getAssets())Nf(t)&&i(e,t.id)})(e)},preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>(i(e,n),t.resolveAssetUrl(e,n))}},dispose(e){e.objectUrls.releaseAll()}}}function px(e,t,n,i){if(zf(e)!==t)return!1;const o=e.getShape(t.shapeId);return Yf(o)&&!o.isLocked&&o.props.assetId===n&&((e,t)=>{if(e.props.w!==t.props.w||e.props.h!==t.props.h)return!1;const n=e.props.crop,i=t.props.crop;return n&&i?n.topLeft.x===i.topLeft.x&&n.topLeft.y===i.topLeft.y&&n.bottomRight.x===i.bottomRight.x&&n.bottomRight.y===i.bottomRight.y:n===i})(o,i)}function gx(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 fx({context:e,crop:t,imageHeight:n,imageWidth:i,mask:o,shape:r,strokes:s}){if(0===s.length)return;const a=yf(t),l={x:a.left*i,y:a.top*n,w:a.width*i,h:a.height*n},d=l.w/r.props.w,c=l.h/r.props.h,u=(Math.abs(d)+Math.abs(c))/2;e.save(),e.beginPath(),e.rect(l.x,l.y,l.w,l.h),e.clip(),e.lineCap="round",e.lineJoin="round";for(const h of s){const t=h.points[0];if(!t)continue;const n=yx(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=mx({cropPixelRect:l,point:t,scaleX:d,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=mx({cropPixelRect:l,point:t,scaleX:d,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 mx({cropPixelRect:e,point:t,scaleX:n,scaleY:i}){return{x:e.x+t.x*n,y:e.y+t.y*i}}function yx(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):.45}function Sx(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 bx({editor:e,flushSnapshot:t,services:n}){const i=n.get(FE);if(!i)return null;const o={start(t){const n=t?.shapeId?e.getShape(t.shapeId):e.getSelectedShapes()[0];return!(!Yf(n)||n.isLocked||!n.props.assetId)&&Lf({brush:t?.brush,editor:e,shape:n})},setBrush:t=>Uf(e,t),cancel(){Ff(e)},confirm:n=>async function({editor:e,imageObjectUrls:t,flushSnapshot:n,replace:i=!0}){const o=zf(e);if(!o)return null;const r=(e=>e.map(e=>({id:e.id,brush:{...e.brush},points:e.points.map(Xf)})))(o.strokes);if(0===r.length)return Df(e),null;if(DE.has(o))return null;DE.add(o);try{return await(async({editor:e,imageObjectUrls:t,flushSnapshot:n,replace:i,session:o,strokes:r})=>{const s=e.getShape(o.shapeId);if(!Yf(s)||s.isLocked||!s.props.assetId)return null;const a=e.getAsset(s.props.assetId);if(!Nf(a))return null;const l=s.props.assetId,d=await(async({asset:e,imageObjectUrls:t})=>{if("remote"===e.props.source.kind)return dx(e.props.source.url);const n=e.props.source.storageKey,i=await zb(n);if(i)return i;const o=t.resolve(n);return o?dx(o):null})({asset:a,imageObjectUrls:t});if(!d)return null;if(!px(e,o,l,s)||e.getAsset(l)!==a)return null;const{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=gx(n,r);s.context.drawImage(o.source,0,0,n,r),fx({context:s.context,crop:e,imageHeight:r,imageWidth:n,mask:!1,shape:t,strokes:i});const a=gx(n,r);return fx({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:s.props.crop,shape:s,sourceBlob:d,strokes:r});if(!px(e,o,l,s)||e.getAsset(l)!==a)return null;const g={shapeId:s.id,sourceAssetId:l,imageBlob:c,maskBlob:u,width:p,height:h,crop:s.props.crop?{topLeft:{...s.props.crop.topLeft},bottomRight:{...s.props.crop.bottomRight}}:null,strokes:r};if(i){const i=await(async({blob:e,canCommit:t,editor:n,flushSnapshot:i,imageObjectUrls:o,name:r,shape:s})=>sx({editor:n,flushSnapshot:i,imageObjectUrls:o,input:await Hb({blob:e,name:r}),nextProps:{},shape:s,canCommit:t}))({blob:c,canCommit:()=>px(e,o,l,s)&&e.getAsset(l)===a,editor:e,imageObjectUrls:t,name:Sx(a.props.name),shape:s});if(!i)return null;if(!px(e,o,i.assetId,s)){const n=zf(e),r=e.getShape(o.shapeId);return n?.shapeId===o.shapeId&&Yf(r)&&r.props.assetId===i.assetId&&Ff(e),await(async({assetId:e,editor:t,imageObjectUrls:n,storageKey:i})=>{!i||e&&t.getAsset(e)||(n.release(i),await Xb(i))})({assetId:i.assetId,editor:e,imageObjectUrls:t,storageKey:i.storageKey}),null}return Df(e),await ax({editor:e,flushSnapshot:n,operation:"image smudge confirmation"}),g}return Df(e),g})({editor:e,flushSnapshot:n,imageObjectUrls:t,replace:i,session:o,strokes:r})}finally{DE.delete(o)}}({editor:e,flushSnapshot:t,imageObjectUrls:i.objectUrls,replace:n?.replace??!0}),isActive:()=>!!zf(e)};return(e=>{Bf(e).registerConfirmHandler(e=>o.confirm(e))})(e),{insertImage:({source:n,pagePoint:o,size:r,strategy:s})=>ex({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!(!Yf(o)||o.isLocked||(await ox({editor:e,file:n,imageObjectUrls:i.objectUrls,flushSnapshot:t}),0))},downloadSelectedImageOriginal:()=>rx({editor:e,imageObjectUrls:i.objectUrls}),smudge:o}}function xx(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(!Yf(n)||!n.props.assetId)continue;const i=n.props.assetId;if(r.has(i))continue;r.add(i);const a=Nb(t,i);if(!a)continue;const l=e.objectUrls.resolve(a)??await e.objectUrls.preload(a);if(!l)continue;const d=await Ob(a);d&&(o=o.split(l).join(d))}return o}}}function Ix({editor:e,flushSnapshot:t,services:n}){const i=n.get(FE);return i?Zx(LE,{editor:e,hostBridge:n.get(OE)??void 0,imageAssetService:i,flushSnapshot:t}):null}function wx(e){const[t]=e.selection.selectedShapes;return!(1!==e.selection.count||!t?.parentId.startsWith("shape:"))&&"frame"===e.editor.getShape(t.parentId)?.type}function Px(e){return Math.min(1,Math.max(0,e))}function vx(e={}){return[...HS(e),YE,AE,lB,oB,gB,...!1===e.image?[]:[XE]]}function kx({editor:e,hooks:t}){return n=>{for(const i of t)i({commandId:n.commandId,context:n.context,editor:e});return n.run()}}function Cx(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t}: ${i}.`);n.add(i)}}function Tx(e){return[...e].sort((e,t)=>(e.order??0)-(t.order??0))}function Mx(e={}){const t=e.id??"canvas-kit",n=(e=>void 0!==e.persistence?e.persistence:function(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await(async(e={})=>{const[t,n]=await(async e=>(await Pb("snapshots",e)??e.map(()=>null)).map(Mb))([Cb(e),Tb(e)]);return{documentSnapshot:t,sessionSnapshot:n}})(e);return t.throwIfAborted(),n},start(t){const n=new PE(t,e);return n.start(),()=>n.stop()},flushSnapshot:t=>kb(t,e)}}({storageNamespace:e.storageNamespace??"land.canvasKit"}))(e),i=(({persistence:e,plugins:t,productId:n})=>{const i=function(e){const t=e.flat(1/0);Lo(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],i=new Set,o=new Set,r=e=>{if(!o.has(e.id)){if(i.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);i.add(e.id);for(const n of e.requires??[]){const i=t.get(n.id);if(!i)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);r(i)}i.delete(e.id),o.add(e.id),n.push(e)}};for(const s of e)r(s);return n})(t),i=[],o=[],r=[];for(const s of n)s.editor&&i.push(s.editor),s.render&&o.push(s.render),s.product&&r.push(s.product);return Lo(i.map(({id:e})=>e),"editor plugin id"),Lo(o.map(({id:e})=>e),"render plugin id"),{plugins:n,pluginIds:n.map(({id:e})=>e),editorPlugins:i,renderPlugins:o,productFactories:r,shapeTypes:Array.from(new Set(i.flatMap(e=>(e.shapeCapabilities??[]).map(({type:e})=>e))))}}(t),o=i.productFactories.map(t=>t({persistence:e??null,productId:n})),r=o.flatMap(({services:e=[]})=>e),s=o.flatMap(({apis:e=[]})=>e),a=Tx(o.flatMap(({providers:e=[]})=>e)),l=Tx(o.flatMap(({components:e=[]})=>e)),d=o.flatMap(({toolbarContributions:e=[]})=>e),c=o.flatMap(({contextMenuContributions:e=[]})=>e);return Cx(r.map(({token:e})=>e.id),"product service token"),Cx(s.map(({token:e})=>e.id),"product API token"),Cx(d.map(({id:e})=>e),"toolbar contribution id"),Cx(c.map(({id:e})=>e),"context-menu contribution id"),Cx(l.map(({id:e})=>e),"component id"),Cx(a.map(({id:e})=>e),"provider id"),{editorPlugins:i.editorPlugins,renderPlugins:i.renderPlugins,services:r,actions:o.flatMap(({actions:e=[]})=>e),createActions:o.flatMap(e=>e.createActions?[e.createActions]:[]),actionShortcuts:o.flatMap(({actionShortcuts:e=[]})=>e),toolbarContributions:d,contextMenuContributions:c,apis:s,setup:o.flatMap(e=>e.setup?[e.setup]:[]),beforeReady:o.flatMap(e=>e.beforeReady?[e.beforeReady]:[]),beforeCommand:o.flatMap(e=>e.beforeCommand?[e.beforeCommand]:[]),providers:a,components:l,assetResolverTokens:o.flatMap(({assetResolverTokens:e=[]})=>e),svgAssetInliners:o.flatMap(e=>e.svgAssetInliners?[e.svgAssetInliners]:[]),canShowToolbarDuringEditing:o.flatMap(e=>e.canShowToolbarDuringEditing?[e.canShowToolbarDuringEditing]:[])}})({persistence:n,plugins:e.plugins??vx(),productId:t}),o=i.assetResolverTokens,r=(({factories:e,productId:t})=>{const n=new Map,i=[],o=()=>{const e=i.splice(0).reverse();try{for(const n of e)try{n()}catch(t){Rb(t)}}finally{n.clear()}},r=(e,t)=>{if(n.has(e.token.id))return n.get(e.token.id);const o=e.create(t);return n.set(e.token.id,o),e.dispose&&i.push(()=>e.dispose?.(o)),o};try{for(const n of e)r(n,{productId:t})}catch(s){throw o(),s}return{get:e=>n.get(e.id)??null,dispose(){o()}}})({factories:i.services,productId:t});let s=null;const a=[];try{const d=function({contributions:e,productId:t,services:n}){const i=[...e.actions,...e.createActions.flatMap(e=>e({productId:t,services:n}))];return Cx(i.map(({id:e})=>e),"canvas action id"),((e,t,n)=>{for(const i of[...t,...n]){const t=i.actionIds.filter(t=>!e.has(t));if(t.length>0)throw new Error(`Contribution "${i.id}" references missing action(s): ${t.join(", ")}.`)}})(new Set(i.map(({id:e})=>e)),e.contextMenuContributions,e.toolbarContributions),i}({contributions:i,productId:t,services:r}),c=(Qs((l=i.renderPlugins).map(({id:e})=>e),"canvas render plugin id"),Qs(l.flatMap(({shapeRenderers:e=[]})=>e.map(({type:e})=>e)),"shape renderer type"),Qs(l.flatMap(({canvasOverlays:e=[]})=>e.map(({id:e})=>e)),"canvas overlay id"),Qs(l.flatMap(({selectionCustomHandleRenderers:e=[]})=>e.map(({type:e})=>e)),"selection handle renderer type"),Qs(l.flatMap(({domEventGuards:e=[]})=>e.map(({id:e})=>e)),"DOM event guard id"),Qs(l.flatMap(({canvasProviders:e=[]})=>e.map(({id:e})=>e)),"canvas provider id"),Qs(l.flatMap(({canvasComponents:e=[]})=>e.map(({id:e})=>e)),"canvas component id"),Qs(l.flatMap(({shapeOpacityModifiers:e=[]})=>e.map(({id:e})=>e)),"shape opacity modifier id"),{plugins:l,canvasProviders:l.flatMap(({canvasProviders:e=[]})=>e),canvasComponents:l.flatMap(({canvasComponents:e=[]})=>e),rendererRegistry:No(l),overlayRegistry:er(l),domEventGuardRegistry:ur(l)}),u=((e=[])=>{const t=new oP;for(const n of e)t.registerAction(n);return t})(d),h=((e=[])=>{const t=new lP;for(const n of e)t.registerContribution(n);return t})(i.toolbarContributions),p=((e=[])=>{const t=new rP;for(const n of e)t.registerContribution(n);return t})(i.contextMenuContributions);s=function(e){const t=((e={})=>{const{plugins:t=[],...n}=e,i=(e=>({shapeUtils:e.flatMap(e=>e.shapeUtils??[]),shapeSvgExporters:e.flatMap(e=>e.shapeSvgExporters??[]),bindingUtils:e.flatMap(e=>e.bindingUtils??[]),shapeCapabilities:e.flatMap(e=>e.shapeCapabilities??[])}))(t),o=new Aw({...n,shapeUtils:i.shapeUtils,shapeSvgExporters:i.shapeSvgExporters,bindingUtils:i.bindingUtils,shapeCapabilities:i.shapeCapabilities});return o.runtime.onDispose(((e,t)=>{const n=[];for(const i of t){for(const n of i.interactionHandlers??[])e.interactions.register(n);const t=i.setup?.(e);t&&n.push(t)}return()=>{for(const e of n.splice(0).reverse())e()}})(o,t)),o})({documentMeta:e.documentMeta,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new iP(e),{shortcut:"v"}),t.tools.register("hand",e=>new Lw(e),{shortcut:"h"}),t.tools.setToolLocked(t.isToolLocked()),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t}({documentMeta:e.documentMeta?{...e.documentMeta}:void 0,editorPlugins:i.editorPlugins,resolveAssetUrl:e=>s?(({assetResolverTokens:e,assetId:t,editor:n,services:i})=>{for(const o of Eb({assetResolverTokens:e,services:i})){const e=o.resolveAssetUrl(n,t);if(e)return e}return null})({assetResolverTokens:o,assetId:e,editor:s,services:r}):null});const g=s;for(const{actionId:e,shortcut:t}of i.actionShortcuts)s.shortcuts.registerActionShortcut(e,t);const f=s.getDocumentSnapshot(),m=s.getSessionSnapshot(),y=(()=>{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}})();for(const e of i.apis){const n=e.create({apis:y,editor:s,productId:t,services:r});null!==n&&y.register(e.token,n)}for(const e of i.setup){const n=e({apis:y,editor:s,productId:t,services:r});n&&a.push(n)}const S=mb({apis:y,editor:s,productId:t,services:r}),b={canvasRuntime:c,actionRegistry:u,toolbarRegistry:h,contextMenuRegistry:p,executeCommand:kx({editor:s,hooks:i.beforeCommand}),providers:i.providers,components:i.components,chrome:e.chrome,svgAssetInliners:i.svgAssetInliners.flatMap(e=>e({editor:g,services:r})),canShowToolbarDuringEditing:e=>i.canShowToolbarDuringEditing.some(t=>t(e))},x={abortController:new AbortController,assetResolverTokens:o,beforeReadyHooks:i.beforeReady,cleanDocumentSnapshot:f,cleanSessionSnapshot:m,controller:S,editor:s,setupDisposers:a,mountedOwner:null,persistence:n,persistenceStop:null,productId:t,render:b,seedDocument:e.seedDocument,services:r,shouldSkipStoredSnapshots:e.shouldSkipStoredSnapshots,startPromise:null,state:"created"},I={controller:S,start:()=>(e=>{if("disposing"===e.state||"disposed"===e.state)return Promise.reject(new Error("Cannot start a disposing or disposed CanvasKitRuntime."));if(e.startPromise)return e.startPromise;e.state="starting";const t=(async e=>{const{assetResolverTokens:t,beforeReadyHooks:n,editor:i,persistence:o,productId:r,services:s}=e,a=e.abortController.signal,l=[],d=e=>(async(e,t,n)=>{t.throwIfAborted();try{return await new Promise((n,i)=>{const o=()=>i(t.reason);t.addEventListener("abort",o,{once:!0}),Promise.resolve().then(e).then(n,i).finally(()=>{t.removeEventListener("abort",o)})})}catch(i){t.throwIfAborted(),n.push(i)}})(e,a,l),c=e.shouldSkipStoredSnapshots?.()??!1;let u,h=!1,p={documentSnapshot:null,sessionSnapshot:null};if(!c&&o?.load){const e=await d(()=>o.load({signal:a}));e&&(p=e,h=!0)}if(a.throwIfAborted(),Rx(e),null!==p.documentSnapshot)try{i.loadDocumentSnapshot(p.documentSnapshot,{source:"system"}),u="restored"}catch(m){a.throwIfAborted(),l.push(m),Rx(e),u=Bx(e)}else u=Bx(e);a.throwIfAborted();let g=!1;if(null!==p.sessionSnapshot)try{i.loadSessionSnapshot(p.sessionSnapshot,{source:"system"}),g=!0}catch(m){a.throwIfAborted(),l.push(m),i.loadSessionSnapshot(e.cleanSessionSnapshot,{source:"system"})}i.history.clear();const f={assetResolverTokens:t,editor:i,services:s,signal:a};await d(()=>(async({assetResolverTokens:e,editor:t,signal:n,services:i})=>{await Promise.all(Eb({assetResolverTokens:e,services:i}).map(e=>e.preloadForEditor?.(t,{signal:n})))})(f)),h&&await d(()=>(async({assetResolverTokens:e,editor:t,signal:n,services:i})=>{await Promise.all(Eb({assetResolverTokens:e,services:i}).map(e=>e.cleanupAfterRestore?.(t,{signal:n})))})(f));for(const y of n)a.throwIfAborted(),await d(()=>y({editor:i,persistence:o,productId:r,services:s,signal:a,startup:{documentSource:u,sessionRestored:g,warnings:[...l]}}));if(a.throwIfAborted(),!c&&o?.start)try{const t=o.start(i);a.aborted?Lx(t):e.persistenceStop=t}catch(m){l.push(m)}return a.throwIfAborted(),{documentSource:u,sessionRestored:g,warnings:[...l]}})(e).then(t=>(e.abortController.signal.throwIfAborted(),e.state="ready",t)).catch(t=>{throw"disposing"!==e.state&&"disposed"!==e.state&&(e.state="failed"),t});return e.startPromise=t,t})(x),dispose(){(e=>{if("disposing"===e.state||"disposed"===e.state)return;e.state="disposing",e.abortController.abort();const t=e.persistenceStop;e.persistenceStop=null,Lx(t),$x({editor:e.editor,setupDisposers:e.setupDisposers,services:e.services}),e.state="disposed"})(x)}};return fB.set(I,x),I}catch(d){throw $x({editor:s,setupDisposers:a,services:r}),d}var l}function Ex(e){const t=fB.get(e);if(!t)throw new Error("CanvasKitRoot received a runtime that was not created by createCanvasKitRuntime().");return t}function Bx(e){return e.seedDocument?(e.seedDocument(e.controller),"seeded"):"empty"}function Ax(e){if("ready"!==e.state)throw new Error(`CanvasKitRoot requires a ready runtime; received runtime in "${e.state}" state. Call and await runtime.start() before rendering.`)}function Rx(e){e.editor.loadDocumentSnapshot(e.cleanDocumentSnapshot,{source:"system"}),e.editor.loadSessionSnapshot(e.cleanSessionSnapshot,{source:"system"})}function $x({editor:e,setupDisposers:t,services:n}){for(const i of t.splice(0).reverse())Lx(i);Lx(()=>e?.dispose()),n.dispose()}function Lx(e){if(e)try{e()}catch(t){const e=globalThis.reportError;try{e?e(t):console.error(t)}catch(n){console.error(n)}}}function Fx({runtime:e,onControllerReady:t,onControllerDispose:n,exposeControllerOnWindow:i=!1,windowKey:o="landCanvasKit"}){const r=Ex(e);Ax(r);const[s]=qx(()=>({})),[a,l]=qx(null);return Wx(()=>(((e,t)=>{const n=Ex(e);if(Ax(n),n.mountedOwner&&n.mountedOwner!==t)throw new Error("A CanvasKitRuntime can only be mounted by one CanvasKitRoot at a time.");n.mountedOwner=t})(e,s),l(e),()=>{((e,t)=>{const n=Ex(e);n.mountedOwner===t&&(n.mountedOwner=null)})(e,s)}),[s,e]),a!==e?null:Zx(Dx,{exposeControllerOnWindow:i,internals:r,onControllerDispose:n,onControllerReady:t,windowKey:o})}function Dx({exposeControllerOnWindow:e=!1,internals:t,onControllerDispose:n,onControllerReady:i,windowKey:o="landCanvasKit"}){const[r,s]=qx(null),[a,l]=qx(!1),d=Kx(()=>({isVisible:a,setIsVisible:l}),[a]),c=Vx(null),{render:u}=t,h={actionRegistry:u.actionRegistry,editor:t.editor,executeCommand:u.executeCommand,services:t.services};(({controller:e,exposeControllerOnWindow:t,onControllerDispose:n,onControllerReady:i,windowKey:o})=>{const r=Hx(e=>{i?.(e)}),s=Hx(()=>{n?.()});_x(()=>(r(e),()=>{s()}),[e]),_x(()=>{if(!t)return;const n=window;return n[o]=e,()=>{n[o]===e&&delete n[o]}},[e,t,o])})({controller:t.controller,exposeControllerOnWindow:e,onControllerDispose:n,onControllerReady:i,windowKey:o});const p=Zx("div",{ref:c,"data-ui":"app-shell","data-canvas-kit":t.productId,className:"land-canvas-kit__shell",children:Qx("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
34
+ Zx(vr,{canvasComponents:u.canvasRuntime.canvasComponents,canvasProviders:u.canvasRuntime.canvasProviders,domEventGuardRegistry:u.canvasRuntime.domEventGuardRegistry,onContextMenuRequest:s,overlayRegistry:u.canvasRuntime.overlayRegistry,rendererRegistry:u.canvasRuntime.rendererRegistry,showGrid:d.isVisible}),u.components.map(e=>Zx(e.component,{...h},e.id)),u.chrome?Zx(Ux,{activeContextMenu:r,grid:d,internals:t,onActiveContextMenuChange:s,themeRootRef:c}):null,
35
+ Zx(gc,{})]})});
36
+ return Zx(dP.Provider,{value:t.editor,children:Zx(pc,{children:(g=u.providers,f=p,g.reduceRight((e,t)=>Zx(t.component,{children:e},t.id),f))})});var g,f}function Ux({activeContextMenu:e,grid:t,internals:n,onActiveContextMenuChange:i,themeRootRef:o}){const{render:r}=n,s=Ib({actionRegistry:r.actionRegistry,activeContextMenu:e,canShowToolbarDuringEditing:r.canShowToolbarDuringEditing,contextMenuRegistry:r.contextMenuRegistry,controller:n.controller,editor:n.editor,executeCommand:r.executeCommand,grid:t,onActiveContextMenuChange:i,svgAssetInliners:r.svgAssetInliners,themeRootRef:o,toolbarRegistry:r.toolbarRegistry});return r.chrome?.(s)??null}function zx(e){const[t,n]=qx(null);return _x(()=>{let t=!0,i=null;n({options:e,state:mB});try{i=Mx(e)}catch(o){return t&&n({options:e,state:{status:"error",error:o}}),()=>{t=!1}}return i.start().then(o=>{t&&i&&n({options:e,state:{status:"ready",runtime:i,startup:o}})},o=>{t&&i&&(i.dispose(),n({options:e,state:{status:"error",error:o}}))}),()=>{t=!1,i?.dispose()}},[e]),t?.options===e?t.state:mB}import{createContext as Ox,memo as Xx,useCallback as Nx,useContext as Yx,useEffect as _x,useEffectEvent as Hx,useLayoutEffect as Wx,useMemo as Kx,useRef as Vx,useState as qx,useSyncExternalStore as jx}from"react";import{Fragment as Gx,jsx as Zx,jsxs as Qx}from"react/jsx-runtime";import{EditorContent as Jx,useEditor as eI}from"@tiptap/react";import{mergeAttributes as tI}from"@tiptap/core";import{Bold as nI}from"@tiptap/extension-bold";import{Italic as iI}from"@tiptap/extension-italic";import{Link as oI}from"@tiptap/extension-link";import{Strike as rI}from"@tiptap/extension-strike";import{TextAlign as sI}from"@tiptap/extension-text-align";import{Color as aI,FontFamily as lI,FontSize as dI,LineHeight as cI,TextStyle as uI}from"@tiptap/extension-text-style";import{Underline as hI}from"@tiptap/extension-underline";import{Selection as pI}from"@tiptap/extensions/selection";import gI from"@tiptap/starter-kit";import{createPortal as fI}from"react-dom";var mI,yI=Object.create,SI=Object.defineProperty,bI=Object.getOwnPropertyDescriptor,xI=Object.getOwnPropertyNames,II=Object.getPrototypeOf,wI=Object.prototype.hasOwnProperty,PI=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),vI=(e,t,n)=>(n=null!=e?yI(II(e)):{},((e,t,n,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var o,r=xI(t),s=0,a=r.length;s<a;s++)wI.call(e,o=r[s])||void 0===o||SI(e,o,{get:(e=>t[e]).bind(null,o),enumerable:!(i=bI(t,o))||i.enumerable});return e})(!t&&e&&e.__esModule?n:SI(n,"default",{value:e,enumerable:!0}),e)),kI=0,CI=null,TI=null,MI=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)=>{CI&&!CI.initialAtomValues.has(e)&&CI.initialAtomValues.set(e,t)})(this,i),t(),this.lastChangedEpoch=e(),this.current=n,(e=>{CI||s([e])})(this),n)}update(e){return this.set(e(this.current))}},EI=Symbol("UNINITIALIZED"),BI=class{name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch;children=new Set;state=EI;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!==EI&&!this.haveParentsChanged())return this.lastCheckedEpoch=e(),this.state;let n,r;i(this.selfAsChild);try{n=this.derive(this.state===EI?EI:this.state)}finally{r=o()}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!==EI&&(this.isEqual?this.isEqual(this.state,n):Object.is(this.state,n))||(this.state=n,t(),this.lastChangedEpoch=e()),this.lastCheckedEpoch=e(),this.state}get selfAsChild(){return this._selfAsChild||(this._selfAsChild={type:"computed",notify:()=>{},source:this}),this._selfAsChild}_selfAsChild=null;haveParentsChanged(){for(let e=0;e<this.parents.length;e++){const t=this.parents[e];if(t.__unsafe__getWithoutCapture(),t.lastChangedEpoch!==this.parentEpochs[e])return!0}return!1}},AI=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);i(this.selfAsChild);try{this.fn()}finally{const t=o();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}},RI=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}},$I=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)}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)}},LI=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 $I(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)}},FI=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 SkewX(t){return new e(1,0,Math.tan(t),1,0,0)}static Scale(t,n){return new e(t,0,0,n,0,0)}compose(t){return new e(this.a*t.a+this.c*t.b,this.b*t.a+this.d*t.b,this.a*t.c+this.c*t.d,this.b*t.c+this.d*t.d,this.a*t.e+this.c*t.f+this.e,this.b*t.e+this.d*t.f+this.f)}applyToPoint(e){return new $I(this.a*e.x+this.c*e.y+this.e,this.b*e.x+this.d*e.y+this.f)}determinant(){return this.a*this.d-this.b*this.c}getMaximumLinearScale(){const e=this.a*this.a+this.b*this.b+this.c*this.c+this.d*this.d,t=this.determinant(),n=Math.max(0,e*e-4*t*t);return Math.sqrt((e+Math.sqrt(n))/2)}tryInvert(t=0){const n=this.determinant(),i=Number.isFinite(t)?Math.max(0,t):0;if(!Number.isFinite(n)||Math.abs(n)<=i)return null;const o=1/n;return new e(this.d*o,-this.b*o,-this.c*o,this.a*o,(this.c*this.f-this.d*this.e)*o,(this.b*this.e-this.a*this.f)*o)}invert(){return this.tryInvert()??e.Identity()}toCssString(){return`matrix(${this.a},${this.b},${this.c},${this.d},${this.e},${this.f})`}toSvgString(){return`matrix(${this.a} ${this.b} ${this.c} ${this.d} ${this.e} ${this.f})`}static ForShape(t,n,i,o=1,r=1,s=0){const a=e.Translate(t,n),l=0===i?e.Identity():e.Rotate(i),d=0===s?e.Identity():e.SkewX(s),c=1===o&&1===r?e.Identity():e.Scale(o,r);return a.compose(l).compose(d).compose(c)}},DI=class{values=new Map;disposers=[];isDisposed=!1;revision=a("editor.runtime.revision",0);revisionSignal=this.revision;notify(){this.revision.set(this.revision.get()+1)}provide(e,t,n){if(this.isDisposed)throw new Error("Cannot provide an editor runtime after disposal.");if(this.values.has(e.id))throw new Error(`Editor runtime already provided: ${e.id}`);return this.values.set(e.id,t),n&&this.disposers.push(()=>n(t)),t}get(e){return this.values.get(e.id)??null}require(e){const t=this.get(e);if(null===t)throw new Error(`Missing editor runtime: ${e.id}`);return t}onDispose(e){this.isDisposed?e():this.disposers.push(e)}dispose(){if(!this.isDisposed){this.isDisposed=!0;for(const e of this.disposers.splice(0).reverse())e();this.values.clear()}}},UI="document:main",zI="page:default",OI="session:main",XI={x:0,y:0,z:1},NI=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}},YI=["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"],_I=Object.fromEntries(YI.map(e=>[e,`--land-shape-${e}`])),HI={"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"},WI=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()}},KI=Symbol("editorStore"),VI=class{marks=new Map;undoStack=[];redoStack=[];_state=a("store.history.state",{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0});state=this._state;clear(){this.marks.clear(),this.undoStack.length=0,this.redoStack.length=0,this.publishState()}mark(e){this.marks.set(e,((e,t=[])=>({id:e,forward:{added:[],updated:[],removed:[]},parentIds:t}))(e,[...this.marks.keys()]))}append(e){if(J(e))if(this.marks.size>0)for(const[t,n]of this.marks.entries())this.marks.set(t,oe(n,e));else this.undoStack.push(re("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),!J(t.forward))return null;const n=ne(t.forward);for(const i of t.parentIds){const e=this.marks.get(i);e&&this.marks.set(i,oe(e,n))}return n}squashToMark(e,t=e){const n=this.marks.get(e);if(!n)return null;if(this.marks.delete(e),!J(n.forward))return null;if(n.parentIds.some(e=>this.marks.has(e)))return null;const i=re(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})}},qI=class{recordsSignal;draftRevisionSignal;recordSignals=new Map;listeners=new Set;transactionDepth=0;draftRecords=null;pendingSource="system";constructor(e){this.recordsSignal=a("store.records",new Map(e.map(e=>[e.id,e]))),this.draftRevisionSignal=a("store.draftRevision",0)}get(e){return this.getReadableRecords().get(e)}getRecordSignal(e){let t=this.recordSignals.get(e);return t||(t=l(`store.record.${e}`,()=>(this.recordsSignal.get(),this.draftRevisionSignal.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"){if(0===this.transactionDepth){let i=[];if(n(()=>{i=this.runAtomic(e,t)}),i.length>0)throw i[0];return}this.runAtomic(e,t)}runAtomic(e,t){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||this.bumpDraftRevision(),n){const e=this.recordsSignal.get(),t=this.draftRecords,n=this.pendingSource;this.draftRecords=null,this.pendingSource="system",this.bumpDraftRevision();const o=t?te(e,t):{added:[],updated:[],removed:[]};if(!i&&t&&J(o))return this.recordsSignal.set(t),this.notifyListeners({source:n,diff:o})}if(i)throw i;return[]}put(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)t.get(n.id)!==n&&t.set(n.id,n)},t)}remove(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)if(!t.delete(n))continue},t)}replaceAll(e,t="system"){const n=new Map(e.map(e=>[e.id,e])),i=te(this.recordsSignal.get(),n);if(!J(i))return;this.recordsSignal.set(n);const o=this.notifyListeners({source:t,diff:i});if(o.length>0)throw o[0]}applyDiff(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e.added)t.set(n.id,n);for(const n of e.updated)t.set(n.after.id,n.after);for(const n of e.removed)t.delete(n.id)},t)}getMutableRecords(){if(!this.draftRecords)throw new Error("Store mutations must run inside store.atomic");return this.draftRecords}getReadableRecords(){return this.draftRecords??this.recordsSignal.get()}bumpDraftRevision(){this.draftRevisionSignal.set(this.draftRevisionSignal.get()+1)}notifyListeners(e){const t=[];for(const i of this.listeners)try{i(e)}catch(n){t.push(n)}return t}},jI=class{editor;buffer=new VI;scopeActivations=[];_state=a("editor.history.state",this.buffer.state.__unsafe__getWithoutCapture());state=this._state;constructor(e){this.editor=e,G(this.editor).listen(e=>{this.handleStoreChange(e)})}clear(){this.buffer.clear(),this.publishEffectiveState()}mark(e){this.buffer.mark(e)}bailToMark(e){const t=this.buffer.bailToMark(e);t&&(G(this.editor).applyDiff(t,"history"),this.editor.syncAfterDocumentRestore())}squashToMark(e,t=e){this.buffer.squashToMark(e,t),this.publishEffectiveState()}activateScope(e){const t={scope:e,unsubscribe:()=>{},isActive:!0};return t.unsubscribe=e.subscribe(()=>{t.isActive&&this.publishEffectiveState()}),this.scopeActivations.push(t),this.publishEffectiveState(),()=>{this.deactivateActivation(t)}}deactivateScope(e){for(let t=this.scopeActivations.length-1;t>=0;t--){const n=this.scopeActivations[t];if(n.scope===e)return this.deactivateActivation(n),!0}return!1}getActiveScope(){return this.scopeActivations.at(-1)?.scope??null}undo(){const e=this.getActiveScope();if(e){const t=e.undo();return this.publishEffectiveState(),t}const t=this.buffer.undo();return!!t&&(G(this.editor).applyDiff(t.inverse,"history"),this.editor.syncAfterDocumentRestore(),this.publishEffectiveState(),!0)}redo(){const e=this.getActiveScope();if(e){const t=e.redo();return this.publishEffectiveState(),t}const t=this.buffer.redo();return!!t&&(G(this.editor).applyDiff(t.forward,"history"),this.editor.syncAfterDocumentRestore(),this.publishEffectiveState(),!0)}getEntries(){return this.buffer.getEntries()}handleStoreChange(e){const t={added:(n=e.diff).added.filter(i=b),updated:n.updated.filter(e=>i(e.before)&&i(e.after)),removed:n.removed.filter(i)};var n,i;J(t)&&"user"===e.source&&(this.buffer.append(t),this.publishEffectiveState())}deactivateActivation(e){if(!e.isActive)return;e.isActive=!1;const t=this.scopeActivations.indexOf(e);t>=0&&this.scopeActivations.splice(t,1);try{e.unsubscribe()}finally{this.publishEffectiveState()}}publishEffectiveState(){const e=this.getActiveScope(),t=e?{canUndo:(n=e.getState()).canUndo,canRedo:n.canRedo,undoDepth:n.undoDepth??(n.canUndo?1:0),redoDepth:n.redoDepth??(n.canRedo?1:0)}:this.buffer.state.__unsafe__getWithoutCapture();var n,i,o;((i=this._state.__unsafe__getWithoutCapture()).canUndo!==(o=t).canUndo||i.canRedo!==o.canRedo||i.undoDepth!==o.undoDepth||i.redoDepth!==o.redoDepth)&&this._state.set({...t})}},GI=class{},ZI=class{editor;constructor(e){this.editor=e}getBindingsFromShape(e){return this.getAllBindings().filter(t=>t.fromId===e)}getBindingsToShape(e){return this.getAllBindings().filter(t=>t.toId===e)}getBindingsForShape(e){return this.getAllBindings().filter(t=>t.fromId===e||t.toId===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){G(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){G(this.editor).remove([n.id],e);continue}if(!this.canBind(n)){G(this.editor).remove([n.id],e);continue}const r=this.getExclusiveBindingKey(n);if(r){if(t.has(r)){G(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)return;const i=new Set(e.map(e=>e.after.id)),o=new Set,r=new Set,s=(e,i,s,a)=>{for(const l of this.getBindingsForShape(e.id)){if(n?.skipBindingIds?.has(l.id))continue;if("ancestry"===a&&r.has(l.id))continue;const d=`${l.id}:${e.id}:${a}`;if(o.has(d))continue;o.add(d),"self"===a&&r.add(l.id);const c=l.fromId===e.id?"from":"to",u=this.editor.getBindingUtil(l).onAfterShapeChange?.(this.editor,l,{before:i,after:s,role:c,reason:a});this.applyEffect(u,t,l.id)}};for(const a of e)s(a.after,a.before,a.after,"self");for(const a of e)if(Ue(a))for(const e of this.editor.getDescendantShapeIds(a.after.id)){if(i.has(e))continue;const t=this.editor.getShape(e);t&&s(t,t,t,"ancestry")}}getShapeHierarchyRootId(e){const t=De(e,this.getAllBindings(),e=>this.editor.getBindingUtil(e));return this.editor.getShape(t)?t:e}cleanupBindingsForDeletedShapes(e,t){if(0===e.length)return;const n=new Set(e),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)){G(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){e&&(e.deleteBindingIds&&e.deleteBindingIds.length>0&&G(this.editor).remove(Array.from(new Set(e.deleteBindingIds)),t),e.bindings&&e.bindings.length>0&&G(this.editor).put(e.bindings,t),e.shapes&&e.shapes.length>0&&this.editor.commands.updateShapes(e.shapes.map(e=>({id:e.id,x:e.x,y:e.y,rotation:e.rotation,skewX:e.skewX,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props,meta:e.meta})),{source:t,skipBindingIds:n?new Set([n]):void 0}),e.deleteShapeIds&&e.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(Array.from(new Set(e.deleteShapeIds)),{source:t}))}getAllBindings(){return G(this.editor).getAll().filter(y).sort((e,t)=>e.id.localeCompare(t.id))}getExclusiveBindingKey(e){const t=this.editor.getBindingUtil(e).getExclusiveBindingKey?.(e);return t?`${e.type}:${t}`:null}},QI=class{editor;_viewportScreenSizeSignal=a("editor.viewportScreenSize",{w:0,h:0});viewportScreenSizeSignal=this._viewportScreenSizeSignal;constructor(e){this.editor=e}getCurrentCamera(){return this.editor.currentCameraSignal.get()}getCamera(e=this.editor.getCurrentPageId()){return this.editor.sessionSignal.get().pageCameraById[e]??XI}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:ze("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=ze(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=ze(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 $I(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new $I(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)}},JI=new $I(24,24),ew=class{editor;constructor(e){this.editor=e}createPayloadFromSelection(){return Qe(this.editor)}pastePayload(e){return this.editor.cancelInteractionForCommand(),Je(this.editor,e)}duplicateSelection(e={}){return this.editor.cancelInteractionForCommand(),((e,t={})=>{const n=Qe(e);return n?Je(e,{payload:n,offset:t.offset??JI,source:t.source}):[]})(this.editor,e)}},tw=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},nw=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:[c(n),u()],o.records[0]??h()]}getDocumentSnapshot(){const e=this.editor.store.getAll();return{schemaVersion:2,records:[e.find(g)??c(),...this.editor.getPages(),...e.filter(S).sort((e,t)=>e.id.localeCompare(t.id)),...e.filter(f).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index):e.parentId.localeCompare(t.parentId)),...e.filter(y).sort((e,t)=>e.id.localeCompare(t.id))]}}getSessionSnapshot(){return{schemaVersion:1,records:[this.editor.sessionSignal.get()]}}loadDocumentSnapshot(e,t){const n=t?.source??"system",i=It(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();G(this.editor).replaceAll([...i.records,o],n),this.syncAfterDocumentSnapshotLoad(n)}loadSessionSnapshot(e,t){const n=t?.source??"system",i=wt(e).records[0]??h(),o=G(this.editor).getAll().filter(b);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),G(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=G(this.editor),t=e.getAll(),n=t.filter(p).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(f),s=new Set(r.map(e=>e.id)),a=new Map(r.map(e=>[e.id,e])),l=new Map;for(const h of r)l.set(h.id,Ve(h,a,o)??i);const d=t.find(e=>e.id===OI),c=m(d)?d:h(i),u={...c,currentPageId:o.has(c.currentPageId)?c.currentPageId:i,pageCameraById:this.repairCameraByPage(c.pageCameraById,o),pageSelectedShapeIdsById:this.repairSelectionByPage(c.pageSelectedShapeIdsById,o,s,l)};e.put([u],"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]??XI;n[i]={x:Number.isFinite(t.x)?t.x:XI.x,y:Number.isFinite(t.y)?t.y:XI.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:XI.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:2,records:[c(t),u()]};try{return It(e,this.editor.shapeUtils,this.editor.bindingUtils)}catch(n){if(!(n instanceof tw))throw n;return{schemaVersion:2,records:[c(t),u()]}}}parseInitialSessionSnapshot(e){if(!e)return{schemaVersion:1,records:[h()]};try{return wt(e)}catch(t){if(!(t instanceof tw))throw t;return{schemaVersion:1,records:[h()]}}}},iw=class{pressedKeyCodes=a("inputs.pressedKeyCodes",new Set);isSpacePressed=l("inputs.isSpacePressed",()=>this.pressedKeyCodes.get().has("Space"));state=a("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:Pt(),screenVelocity:Pt(),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:vt(n,e.pagePoint,r),screenVelocity:vt(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 this.resetPointer(),void("blur"!==e.reason&&"dispose"!==e.reason||this.resetKeyboard())}}resetPointer(){this.state.update(e=>({...e,originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:Pt(),screenVelocity:Pt(),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:Pt(),screenVelocity:Pt(),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&&kt(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:vt(n,e.pagePoint,s),screenVelocity:vt(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:Pt(),screenVelocity:Pt(),buttons:e.buttons,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}})}handleKeyboardEvent(e){this.pressedKeyCodes.update(t=>{const n="key_down"===e.name;if(t.has(e.code)===n)return t;const i=new Set(t);return n?i.add(e.code):i.delete(e.code),i}),this.state.update(t=>kt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}resetKeyboard(){this.pressedKeyCodes.get().size>0&&this.pressedKeyCodes.set(new Set),this.state.update(e=>e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||e.accelKey?{...e,shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1}:e)}handleWheelEvent(e){this.state.update(t=>kt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},ow=class{editor;_brushBoxSignal=a("editor.brushBox",null);brushBoxSignal=this._brushBoxSignal;brushBoxActiveSignal=l("editor.brushBoxActive",()=>null!==this._brushBoxSignal.get());_bindingPreviewSignal=a("editor.bindingPreview",null);bindingPreviewSignal=this._bindingPreviewSignal;bindingPreviewActiveSignal=l("editor.bindingPreviewActive",()=>null!==this._bindingPreviewSignal.get());_terminalBindingGuidesSignal=a("editor.terminalBindingGuides",[]);terminalBindingGuidesSignal=this._terminalBindingGuidesSignal;_dropTargetShapeIdSignal=a("editor.dropTargetShapeId",null);dropTargetShapeIdSignal=this._dropTargetShapeIdSignal;_hoveredShapeIdSignal=a("editor.hoveredShapeId",null);hoveredShapeIdSignal=this._hoveredShapeIdSignal;_selectionTranslationActiveSignal=a("editor.selectionTranslationActive",!1);selectionTranslationActiveSignal=this._selectionTranslationActiveSignal;terminalBindingResolver=(e,t)=>(({rawPagePoint:e})=>({pagePoint:e.clone(),binding:null,preview:null}))(t);constructor(e){this.editor=e}setBrushBox(e){_e(this._brushBoxSignal.get(),e)||this._brushBoxSignal.set(e?e.clone():null)}setBindingPreview(e){var t,n;(t=this._bindingPreviewSignal.get())===(n=e)||(t&&n?t.terminal===n.terminal&&t.targetShapeId===n.targetShapeId&&Ye(t.rawPagePoint,n.rawPagePoint)&&Ye(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||!Et(i,o))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(Ct))}setDropTargetShapeId(e){this._dropTargetShapeIdSignal.get()!==e&&this._dropTargetShapeIdSignal.set(e)}setHoveredShapeId(e){this._hoveredShapeIdSignal.get()!==e&&this._hoveredShapeIdSignal.set(e)}setSelectionTranslationActive(e){this._selectionTranslationActiveSignal.get()!==e&&this._selectionTranslationActiveSignal.set(e)}setSnapIndicators(e){e?this.editor.snaps.setIndicators(e):this.editor.snaps.clearIndicators()}setTerminalBindingResolver(e){this.terminalBindingResolver=e}resolveTerminalBinding(e){return this.terminalBindingResolver(this.editor,e)}clearSelectionTransients(){this.setBrushBox(null),this.setBindingPreview(null),this.setTerminalBindingGuides(null),this.setDropTargetShapeId(null),this.setHoveredShapeId(null),this.setSelectionTranslationActive(!1),this.setSnapIndicators(null)}},rw=.001,sw=class{editor;stateSignal;currentPageShapeIdsSignal;currentPageShapesSignal;currentPageShapeHierarchySignal;selectionGeometrySignal;selectionPageOutlineVerticesSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionHasRotationSignal;selectionRotationSignal;selectionRotationCenterSignal;selectionHasCompatibleRotationSignal;selectionAnchorPagePointSignal;stateAtom;shapeQuerySignals=new Map;constructor(e){this.editor=e;const t=G(this.editor);this.stateAtom=a("editor.query.state",(e=>{const t=e.filter(p).sort((e,t)=>e.index.localeCompare(t.index)),n=e.filter(f).sort((e,t)=>e.parentId===t.parentId?((e,t)=>e.index.localeCompare(t.index))(e,t):e.parentId.localeCompare(t.parentId)),i=e.filter(y).sort(Lt),o=new Map,r=new Map,s=new Map,a=new Map(n.map(e=>[e.id,e])),l=new Map,d=new Map,c=new Map,u=new Map;for(const p of n)Bt(r,p.parentId,p.id);const h=(e,t)=>{for(const n of r.get(t)??[]){const t=a.get(n);t&&(Bt(o,e,t.id),s.set(t.id,e),h(e,t.id))}};for(const p of t)h(p.id,p.id);for(const p of i)l.set(p.id,p),At(d,p.fromId,p.id),At(c,p.toId,p.id),At(u,p.fromId,p.id),At(u,p.toId,p.id);return{pageShapeIdsByPage:o,childShapeIdsByParent:r,pageIdByShape:s,bindingById:l,bindingIdsByFromShape:d,bindingIdsByToShape:c,relatedBindingIdsByShape:u}})(Array.from(t.recordsSignal.get().values()))),this.stateSignal=this.stateAtom,t.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=l("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(this.editor.getCurrentPageId()),{isEqual:$t}),this.currentPageShapesSignal=l("editor.query.currentPageShapes",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.getShapeSignal(e).get()).filter(e=>!!e)),this.currentPageShapeHierarchySignal=l("editor.query.currentPageShapeHierarchy",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.getShapeSignal(e).get()).filter(e=>!!e).map(e=>({id:e.id,parentId:e.parentId,type:e.type})),{isEqual:qt});const n=((e,t)=>{const n=l("editor.query.selectionGeometry",()=>Vt(e,t),{isEqual:Ht}),i=l("editor.query.selectionPageOutlineVertices",()=>n.get().outlineVertices,{isEqual:_t}),o=l("editor.query.selectionPageBounds",()=>n.get().pageBounds,{isEqual:_e}),r=l("editor.query.selectionFrameBounds",()=>n.get().frameBounds,{isEqual:_e}),s=l("editor.query.selectionRotation",()=>n.get().rotation);return{geometry:n,pageOutlineVertices:i,pageBounds:o,frameBounds:r,hasRotation:l("editor.query.selectionHasRotation",()=>n.get().hasRotation),rotation:s,rotationCenter:l("editor.query.selectionRotationCenter",()=>n.get().rotationCenter,{isEqual:Ye}),hasCompatibleRotation:l("editor.query.selectionHasCompatibleRotation",()=>n.get().hasCompatibleRotation),selectionAnchorPagePoint:l("editor.query.selectionAnchorPagePoint",()=>n.get().selectionAnchorPagePoint,{isEqual:Ye})}})(this.editor,e=>this.getShapeGeometrySnapshot(e));this.selectionGeometrySignal=n.geometry,this.selectionPageOutlineVerticesSignal=n.pageOutlineVertices,this.selectionPageBoundsSignal=n.pageBounds,this.selectionFrameBoundsSignal=n.frameBounds,this.selectionRotationSignal=n.rotation,this.selectionHasRotationSignal=n.hasRotation,this.selectionRotationCenterSignal=n.rotationCenter,this.selectionHasCompatibleRotationSignal=n.hasCompatibleRotation,this.selectionAnchorPagePointSignal=n.selectionAnchorPagePoint}getShapeIdsForPage(e){return[...this.getShapeIdsForPageSnapshot(e)]}getShapesForPage(e){return this.getShapeIdsForPageSnapshot(e).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getChildShapeIds(e){return[...this.getChildShapeIdsSnapshot(e)]}getChildShapes(e){return this.getChildShapeIdsSnapshot(e).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getDescendantShapeIds(e){const t=[],n=new Set,i=e=>{for(const o of this.getChildShapeIdsSnapshot(e))n.has(o)||(n.add(o),t.push(o),i(o))};return i(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 rn(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 rn(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).getLocalBounds(n),s=this.getShapeQuerySignals(e).localToPageTransform.get()?.tryInvert();return s&&o.outlineVertices.length>0&&o.outlineVertices.every(e=>r.containsPoint(s.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 d of n){o.add(d.id);for(const e of this.getDescendantShapeIds(d.id))o.add(e)}let r=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(o.has(e))continue;const t=this.editor.getShape(e);if(!t||this.editor.isShapeHidden(t.id)||this.editor.isShapeOrAncestorLocked(t.id))continue;if(!an(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&&d>a)&&(r=t,s=c,a=d)}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,l=-1;const d=this.stateSignal.get().pageShapeIdsByPage.get(o)??[];for(let c=0;c<d.length;c+=1){const e=d[c];if(r.has(e))continue;const n=this.editor.getShape(e);if(!n||this.editor.isShapeHidden(n.id)||this.editor.isShapeOrAncestorLocked(n.id))continue;const o=this.editor.getShapeUtil(n);if(!an(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=this.getShapeQuerySignals(n.id).localToPageTransform.get()?.tryInvert();if(!h||!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??o}getContainingParentIdForShapeRecord(e){const t=(e=>{const t=new Set;let n=e;for(;n.startsWith("shape:");){const e=n;if(t.has(e))return null;t.add(e);const i=this.editor.getShape(e);if(!i)return null;n=i.parentId}return this.editor.getPage(n)?n:null})(e.parentId);if(!t)return null;const n=this.getShapeParentToPageTransformSnapshot(e.parentId,e=>this.editor.getShape(e));if(!n)return null;const i=ye(e,this.editor.getShapeUtil(e),n);let o=null,r=1/0,s=-1;const a=new Map;for(const u of G(this.editor).getAll().filter(f)){const e=a.get(u.parentId)??[];e.push(u),a.set(u.parentId,e)}for(const u of a.values())u.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));const l=[],d=new Set,c=e=>{for(const t of a.get(e)??[])d.has(t.id)||(d.add(t.id),l.push(t),c(t.id))};c(t);for(let u=0;u<l.length;u+=1){const t=l[u];if(!t||t.id===e.id||this.editor.isShapeHidden(t.id)||this.editor.isShapeOrAncestorLocked(t.id))continue;const n=this.editor.getShapeUtil(t);if(!an(t,n))continue;if(!this.editor.canUseShapeParent(t.id,e.id))continue;const a=this.editor.computeShapePageBounds(t),d=n.getLocalBounds(t),c=this.editor.computeShapeLocalToPageTransform(t).tryInvert();if(!(c&&i.outlineVertices.length>0&&i.outlineVertices.every(e=>d.containsPoint(c.applyToPoint(e)))))continue;const h=a.w*a.h;(!o||h<r||h===r&&u>s)&&(o=t,r=h,s=u)}return o?.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).getChildClipLocalPolygons(i);if(!e||!v(e))continue;const n=this.getShapeQuerySignals(i.id).localToPageTransform.get()?.tryInvert();if(!n)return!1;if(!C(n.applyToPoint(t),e))return!1}return!0}getShapeClippedPageBounds(e){let t=this.getShapePageBounds(e);if(!t)return null;for(const n of this.getShapeClipAncestors(e)){const e=this.getShapeChildClipPageBounds(n);if(!e)continue;const i=sn(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).getChildClipLocalPolygons(r);s&&v(s)&&n.push(r),o=r.parentId}return n.reverse()}getShapeChildClipPageBounds(e){const t=this.editor.getShapeUtil(e).getChildClipLocalPolygons(e),n=t?v(t):null;if(!n)return null;const i=this.getShapeQuerySignals(e.id).localToPageTransform.get();return i?(r=i,LI.FromPoints([new $I((o=n).minX,o.minY),new $I(o.maxX,o.minY),new $I(o.maxX,o.maxY),new $I(o.minX,o.maxY)].map(e=>r.applyToPoint(e)))):null;var o,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(f).map(e=>e.id))(e))this.shapeQuerySignals.delete(n);const t=G(this.editor);this.stateAtom.update(n=>((e,t,n)=>{const i=t.diff.added.filter(f),o=t.diff.updated.filter(Ot),r=t.diff.removed.filter(f),s=t.diff.added.filter(y),a=t.diff.updated.filter(Xt),l=t.diff.removed.filter(y),d=i.length>0||r.length>0||o.some(({before:e,after:t})=>e.parentId!==t.parentId||e.index!==t.index),c=s.length>0||l.length>0||a.some(({before:e,after:t})=>e.fromId!==t.fromId||e.toId!==t.toId),u=s.length>0||l.length>0||a.length>0;if(!d&&!u)return e;const h={pageShapeIdsByPage:new Map(e.pageShapeIdsByPage),childShapeIdsByParent:new Map(e.childShapeIdsByParent),pageIdByShape:new Map(e.pageIdByShape),bindingById:new Map(e.bindingById),bindingIdsByFromShape:new Map(e.bindingIdsByFromShape),bindingIdsByToShape:new Map(e.bindingIdsByToShape),relatedBindingIdsByShape:new Map(e.relatedBindingIdsByShape)};let g=!1;if(d){const t=e=>{const t=n(e);return f(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(p(e))return e.id;if(!f(e))return null;t=e.parentId}return null};for(const n of r){zt(h.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;zt(h.childShapeIdsByParent,n.parentId,n.id),Ut(h.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)Ut(h.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 h.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)}h.pageShapeIdsByPage=t,h.pageIdByShape=i}g=!0}if(u){for(const e of l)g=h.bindingById.delete(e.id)||g;if(c){for(const e of l)g=Rt(h.bindingIdsByFromShape,e.fromId,e.id)||g,g=Rt(h.bindingIdsByToShape,e.toId,e.id)||g,g=Rt(h.relatedBindingIdsByShape,e.fromId,e.id)||g,g=Rt(h.relatedBindingIdsByShape,e.toId,e.id)||g;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(g=Rt(h.bindingIdsByFromShape,e.fromId,e.id)||g,g=Rt(h.bindingIdsByToShape,e.toId,e.id)||g,g=Rt(h.relatedBindingIdsByShape,e.fromId,e.id)||g,g=Rt(h.relatedBindingIdsByShape,e.toId,e.id)||g)}for(const e of s)h.bindingById.set(e.id,e),g=!0;for(const{after:e}of a)h.bindingById.set(e.id,e),g=!0;if(c){for(const e of s)g=Dt(h.bindingIdsByFromShape,e.fromId,e,"from",e=>h.bindingById.get(e))||g,g=Dt(h.bindingIdsByToShape,e.toId,e,"to",e=>h.bindingById.get(e))||g,g=Dt(h.relatedBindingIdsByShape,e.fromId,e,"related",e=>h.bindingById.get(e))||g,g=Dt(h.relatedBindingIdsByShape,e.toId,e,"related",e=>h.bindingById.get(e))||g;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(g=Dt(h.bindingIdsByFromShape,t.fromId,t,"from",e=>h.bindingById.get(e))||g,g=Dt(h.bindingIdsByToShape,t.toId,t,"to",e=>h.bindingById.get(e))||g,g=Dt(h.relatedBindingIdsByShape,t.fromId,t,"related",e=>h.bindingById.get(e))||g,g=Dt(h.relatedBindingIdsByShape,t.toId,t,"related",e=>h.bindingById.get(e))||g)}}return g?h:e})(n,e,e=>t.get(e)))}getShapeLocalToPageTransformSnapshot(e,t){const n=[],i=new Set;let o=e;for(;o;){if(i.has(o.id))return;if(i.add(o.id),n.push(o),o.parentId.startsWith("page:")){if(!this.editor.getPage(o.parentId))return;break}if(o=t(o.parentId),!o)return}let r=FI.Identity();for(let s=n.length-1;s>=0;s-=1){const e=n[s];e&&(r=ue(e,this.editor.getShapeUtil(e),r))}return r}getShapeParentToPageTransformSnapshot(e,t){if(e.startsWith("page:"))return this.editor.getPage(e)?FI.Identity():void 0;const n=t(e);return n?this.getShapeLocalToPageTransformSnapshot(n,t):void 0}getShapeQuerySignals(e){let t=this.shapeQuerySignals.get(e);if(!t){const n=l(`editor.query.shapePositionedBounds.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return this.editor.getShapeUtil(t).getPositionedBounds(t)},{isEqual:jt}),i=l(`editor.query.shapeLocalToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();return t?this.getShapeLocalToPageTransformSnapshot(t,e=>this.editor.getShapeSignal(e).get()):void 0},{isEqual:Qt}),o=l(`editor.query.shapeGeometry.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(!t)return;const n=this.getShapeParentToPageTransformSnapshot(t.parentId,e=>this.editor.getShapeSignal(e).get());return n?ye(t,this.editor.getShapeUtil(t),n):void 0},{isEqual:Jt});t={positionedBounds:n,geometry:o,localToPageTransform:i,positionedToPageTransform:l(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(!t)return;const n=this.getShapeParentToPageTransformSnapshot(t.parentId,e=>this.editor.getShapeSignal(e).get());return n?he(t,this.editor.getShapeUtil(t),n):void 0},{isEqual:Qt}),pageBounds:l(`editor.query.shapePageBounds.${e}`,()=>o.get()?.bounds,{isEqual:jt}),clipAncestorIds:l(`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:$t})},this.shapeQuerySignals.set(e,t)}return t}getShapeGeometrySnapshot(e){return this.getShapeQuerySignals(e).geometry.get()}getShapePageBoundsSignal(e){return this.getShapeQuerySignals(e).pageBounds}getShapeLocalToPageTransformSignal(e){return this.getShapeQuerySignals(e).localToPageTransform}getShapeGeometry(e){return(e=>{if(e)return{bounds:e.bounds.clone(),center:e.center.clone(),corners:e.corners.map(e=>e.clone()),outlineVertices:e.outlineVertices.map(e=>e.clone())}})(this.getShapeGeometrySnapshot(e))}getShapeLocalToPageTransform(e){return on(this.getShapeLocalToPageTransformSignal(e).get())}getShapeParentToPageTransform(e){return e.startsWith("page:")?this.editor.getPage(e)?FI.Identity():void 0:on(this.getShapeQuerySignals(e).localToPageTransform.get())}getShapePageToParentTransform(e){return this.getShapeParentToPageTransform(e)?.tryInvert()??void 0}getShapePositionedToPageTransform(e){return on(this.getShapeQuerySignals(e).positionedToPageTransform.get())}getShapePageBounds(e){return en(this.getShapePageBoundsSignal(e).get())??void 0}getShapePositionedBounds(e){return en(this.getShapeQuerySignals(e).positionedBounds.get())??void 0}getShapePageCenter(e){return tn(this.getShapeGeometrySnapshot(e)?.center)??void 0}getShapePageCorners(e){return nn(this.getShapeGeometrySnapshot(e)?.corners)}getShapePageOutlineVertices(e){return nn(this.getShapeGeometrySnapshot(e)?.outlineVertices)}getSelectionPageOutlineVertices(){return nn(this.selectionPageOutlineVerticesSignal.get())??[]}getSelectionPageBounds(){return en(this.selectionPageBoundsSignal.get())??null}getSelectionFrameBounds(){return en(this.selectionFrameBoundsSignal.get())??null}getSelectionRotation(){return this.selectionRotationSignal.get()}getSelectionHasRotation(){return this.selectionHasRotationSignal.get()}getSelectionRotationCenter(){return tn(this.selectionRotationCenterSignal.get())??null}getSelectionHasCompatibleRotation(){return this.selectionHasCompatibleRotationSignal.get()}getSelectionAnchorPagePoint(){return tn(this.selectionAnchorPagePointSignal.get())??null}getBinding(e){return this.stateSignal.get().bindingById.get(e)}getBindings(){return Array.from(this.stateSignal.get().bindingById.values()).sort(Lt)}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)}},aw=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}},lw=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 LI(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),l=this.queries.getShapeParentToPageTransform(s.parentId);if(!l)continue;const d=fe(s,e,a,l),c={editor:this.editor,pagePoint:e,positionedPoint:d};("bindingTarget"===t?.hitTest?a.hitTestBindingTarget(s,d,c):a.hitTest(s,d,c))&&i.push(s)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,o=((e,t,n)=>LI.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 l=this.queries.getShapeClippedPageBounds(o.shapeId);if(!l||!dn(e,t,l.expand(i)))continue;if(!this.doesLineSegmentIntersectShapeClip(o.shapeId,e,t,i))continue;const d=this.editor.getShape(o.shapeId);if(!d)continue;if(n?.filter&&!n.filter(d))continue;const c=this.editor.getShapeUtil(d),u=this.queries.getShapeParentToPageTransform(d.parentId);if(!u)continue;const h=fe(d,e,c,u),p=fe(d,t,c,u),g=this.queries.getShapePositionedToPageTransform(d.id)?.tryInvert(),f=g?i*g.getMaximumLinearScale():i;c.hitTestLineSegment(d,{editor:this.editor,pageStart:e,pageEnd:t,pageMargin:i,positionedStart:h,positionedEnd:p,positionedMargin:f})&&s.push(d)}return s}doesLineSegmentIntersectShapeClip(e,t,n,i){for(const o of this.queries.getShapeClipAncestorIds(e)){const e=this.editor.getShape(o);if(!e)return!1;const r=this.editor.getShapeUtil(e).getChildClipLocalPolygons(e);if(!r)continue;const s=this.editor.computeShapeLocalToPageTransform(e).tryInvert();if(!s)return!1;const a=i*Math.sqrt(s.a*s.a+s.b*s.b+s.c*s.c+s.d*s.d),l=s.applyToPoint(t),d=s.applyToPoint(n);if(!r.some(e=>T(l,d,e,a)))return!1}return!0}getPageIndexSignal(e){let t=this.pageIndexSignals.get(e);return t||(t=l(`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=this.queries.getShapePositionedToPageTransform(e);if(!r)continue;const s=cn(i.getPointHitTestBounds(t,{editor:this.editor}),r),a=LI.FromPoints([new $I(o.minX,o.minY),new $I(o.maxX,o.maxY),new $I(s.minX,s.minY),new $I(s.maxX,s.maxY)]);n.push({shapeId:e,shapeBounds:o,queryBounds:a,pointHitTestBounds:s})}return new aw(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.getCurrentPageId()){return this.getPageIndexSignal(e).get()}},dw={corner:0,edge_midpoint:1,center:2,custom:3},cw=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],uw=["top_left","top_right","bottom_right","bottom_left"],hw=["free","aspect_ratio_locked"],pw=["free"],gw=["aspect_ratio_locked"],fw=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],mw=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=[],l=this.getSnapScopeParentId([e.shapeId]),d=this.getCandidateShapeIds({excludedShapeIds:r,scopeParentId:l});o&&n&&this.collectSelfHandleSnapGeometry({shape:o,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 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=hi(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 l=this.editor.getShapeClipAncestorIds(e.id).length>0?En(o):(a??(d=i.getLocalBounds(e),[new $I(d.minX,d.minY),new $I(d.maxX,d.minY),new $I(d.maxX,d.maxY),new $I(d.minX,d.maxY)])).map(e=>r.applyToPoint(e));var d;l.length>0&&n.push({id:e.id,points:l})}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),l=this.editor.computeShapeLocalToPageTransform(e),d={...t,currentPagePoint:n.clone()};for(const h of a.getSelfSnapPoints?.(d)??[]){const t=hi(h),n=l.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?.(d)??null;if(!c)return;const u=this.editor.getShapeClipAncestorIds(e.id).length>0?En(s):c.map(e=>l.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),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?En(i):this.editor.getShapePageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():ri(e,s));if(0===a.length)continue;const l=LI.FromPoints(a);r.push({id:e.id,bounds:l});const c=n.getBoundsSnapGeometry(e).points,u=[];if(void 0===c)xn(l).forEach((e,t)=>{u.push({point:e,kind:fw[t]??"custom"})});else{const n=this.editor.computeShapeLocalToPageTransform(e);for(const i of c){const o=hi(i),r=n.applyToPoint(o.point);this.editor.isPagePointInShapeClip(e.id,r)&&u.push({point:0===t.rotation?r:ri(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:Ln(o),nodes:r,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 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;if(t?.startsWith("shape:")){const e=this.editor.getShape(t);e&&this.editor.getShapeUtil(e).canSnapChildrenToSelf(e)&&o.add(e.id)}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))})}},yw=class{gapCache=new WeakMap;_indicatorsSignal=a("editor.snapIndicators",[]);indicatorsSignal=this._indicatorsSignal;activeSignal=l("editor.snapIndicatorsActive",()=>this._indicatorsSignal.get().length>0);snapshots;axisSnapMemory={x:null,y:null};constructor(e){this.snapshots=new mw(e)}setIndicators(e){const t=e.map(oi);Vn(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:Yn(n.nodes,"x"),y:Yn(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=Tn(e.initialSelectionBounds,e.dragDelta),i=(o=xn(e.initialSelectionBounds),r=e.dragDelta,o.map(e=>e.add(r)));var o,r;const s=this.gapCache.get(e.snapshot)??{x:Yn(e.snapshot.nodes,"x"),y:Yn(e.snapshot.nodes,"y")},a=this.getReleaseThreshold(e.threshold),l=this.getSwitchDistance(e.threshold),d=this.axisSnapMemory.x,c=this.axisSnapMemory.y,u={candidatePointCount:0,matchedPointCount:0},h="y"===e.lockedAxis?null:Kn(Xn("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:a,switchDistance:l,stats:u}),Wn("x",n,s.x,e.threshold,{previousSnapId:"gaps"===d?.type?d.id:null,releaseThreshold:a,switchDistance:l}),{previousSnap:d,switchDistance:l}),p="x"===e.lockedAxis?null:Kn(Xn("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:a,switchDistance:l,stats:u}),Wn("y",n,s.y,e.threshold,{previousSnapId:"gaps"===c?.type?c.id:null,releaseThreshold:a,switchDistance:l}),{previousSnap:c,switchDistance:l}),g=new $I(h?.nudge??0,p?.nudge??0),f=[];return"points"===h?.type?f.push(...Gn("x",h,g,e.snapshot.coordinateSpace)):"gaps"===h?.type&&f.push(ii(h,e.snapshot.coordinateSpace,g)),"points"===p?.type?f.push(...Gn("y",p,g,e.snapshot.coordinateSpace)):"gaps"===p?.type&&f.push(ii(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=fn({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),i=Nn(n,e.resizedSelectionBounds),o="top"===n||"bottom"===n,r="left"===n||"right"===n,s=this.getReleaseThreshold(e.threshold),a=this.getSwitchDistance(e.threshold),l=this.axisSnapMemory.x,d=this.axisSnapMemory.y,c={candidatePointCount:0,matchedPointCount:0},u=o?null:Xn("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:s,switchDistance:a,stats:c}),h=r?null:Xn("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:s,switchDistance:a,stats:c}),p={x:null!==u,y:null!==h},g=new $I(u?.nudge??0,h?.nudge??0);if(e.isAspectRatioLocked&&un(f=n)!==hn(f)&&pn(f)!==gn(f)&&(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))}var f;const m=function(e,t){const n=fn({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?(un(n)?(i+=t.x,o-=t.x):hn(n)&&(i-=t.x,o+=t.x),pn(n)?(r+=t.y,s-=t.y):gn(n)&&(r-=t.y,s+=t.y)):(un(n)?i+=t.x:hn(n)&&(o+=t.x),pn(n)?r+=t.y:gn(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 LI(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=mn({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:r}),a=mn({axis:"y",startBounds:e,bounds:t,handleId:n,scale:o,isResizingFromCenter:r});return{scaleX:un(n)||hn(n)?s*(t.w/Math.max(1,e.w)):i??1,scaleY:pn(n)||gn(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 Sn({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,aspectRatio:0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h,isResizingFromCenter:e.isResizingFromCenter,scaleX:e.scaleX,scaleY:e.scaleY})}(e,g),{bounds:y}=m,S=Nn("any",y),b=[];if(p.x){const t=Xn("x",S,e.snapshot.pointIndex,1e-8,{stats:c});t&&b.push(...ti("x",t,$I.Zero(),e.snapshot.coordinateSpace,y,e.snapshot.nodes))}if(p.y){const t=Xn("y",S,e.snapshot.pointIndex,1e-8,{stats:c});t&&b.push(...ti("y",t,$I.Zero(),e.snapshot.coordinateSpace,y,e.snapshot.nodes))}return this.setIndicators(b),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:b.length}),{nudge:g,bounds:y,scaleX:m.scaleX,scaleY:m.scaleY,indicators:b}}snapHandle(e){const t=this.getNow();if("none"===e.mode)return this.clearIndicators(),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null;const n="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return n?(this.setIndicators(n.indicators),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:n.indicators.length,indicatorCount:n.indicators.length}),n):(this.clearIndicators(),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null)}snapHandlePoint(e){const t=pi(e);let n=null,i=null,o=e.threshold*e.threshold;for(const a of t)for(const t of e.snapshot.points){const e=a.dist2(t.point);e>o||(o=e,n=t.point,i=a)}if(!n)for(const a of t)for(const t of e.snapshot.outlines){const e=Rn(a,t.points);!e||e.distanceSquared>o||(o=e.distanceSquared,n=e.point,i=a)}if(!n||!i)return null;const r=n.sub(i);return{snappedPagePoint:e.pagePoint.add(r),nudge:r,indicators:[(s=n,{id:ei("x",[s,s],[s]),type:"points",axis:"x",line:[s.clone(),s.clone()],points:[s.clone()],rotation:0,rotationCenter:s.clone()})]};var s}snapHandleAlign(e){const t=pi(e);let n=null,i=null,o=null,r=null,s=e.threshold,a=e.threshold;for(const u of t)for(const t of e.snapshot.points){const e=Math.abs(t.point.x-u.x);e<=s&&(s=e,n=t.point,o=u);const l=Math.abs(t.point.y-u.y);l<=a&&(a=l,i=t.point,r=u)}if(!n&&!i)return null;const l=new $I(n&&o?n.x-o.x:0,i&&r?i.y-r.y:0),d=e.pagePoint.add(l),c=[];return n&&o&&c.push(ni("x",o.add(l),n)),i&&r&&c.push(ni("y",r.add(l),i)),{snappedPagePoint:d,nudge:l,indicators:c}}},Sw=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)}}},bw=class{editor;constructor(e){this.editor=e}align(e,t="user"){const n=this.getAlignableEntries();if(n.length<2)return!1;const i=this.getPageToParentTransform(n[0].shape.parentId);if(!i)return!1;const o=LI.FromPoints(n.flatMap(e=>[new $I(e.bounds.minX,e.bounds.minY),new $I(e.bounds.maxX,e.bounds.maxY)])),r=n.map(({shape:t,bounds:n})=>{let r=0,s=0;switch(e){case"left":r=o.minX-n.minX;break;case"right":r=o.maxX-n.maxX;break;case"horizontal-center":r=o.center.x-n.center.x;break;case"top":s=o.minY-n.minY;break;case"bottom":s=o.maxY-n.maxY;break;case"vertical-center":s=o.center.y-n.center.y}const a=this.pageDeltaToParentDelta(i,new $I(r,s));return{id:t.id,x:t.x+a.x,y:t.y+a.y}});return this.editor.commands.updateShapes(r,{source:t}),!0}distribute(e,t="user"){const n=this.getAlignableEntries();if(n.length<3)return!1;const i=this.getPageToParentTransform(n[0].shape.parentId);if(!i)return!1;const o="horizontal"===e,r=e=>o?e.w:e.h,s=e=>o?e.minX:e.minY,a=o?"x":"y",l=[...n].sort((e,t)=>e.bounds.center[a]-t.bounds.center[a]),d=l[0].bounds,c=l[l.length-1].bounds,u=((o?c.maxX:c.maxY)-s(d)-l.reduce((e,t)=>e+r(t.bounds),0))/(l.length-1);let h=s(d);const p=l.map(({shape:e,bounds:t},n)=>{const a=0===n||n===l.length-1?s(t):h,d=a-s(t);h=a+r(t)+u;const c=this.pageDeltaToParentDelta(i,o?new $I(d,0):new $I(0,d));return{id:e.id,x:e.x+c.x,y:e.y+c.y}});return this.editor.commands.updateShapes(p,{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||!He(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=ze(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&&He(e)&&t.push(new $I(e.minX,e.minY),new $I(e.maxX,e.maxY))}if(0===t.length)return null;const n=LI.FromPoints(t);return He(n)?n:null}getAlignableEntries(){const e=this.editor.getSelectedShapeIds().map(e=>this.editor.getShape(e)).filter(e=>!!e&&!this.editor.isShapeOrAncestorLocked(e.id)),t=e[0]?.parentId;if(!t||e.some(e=>e.parentId!==t))return[];const n=[];for(const i of e){const e=this.editor.getShapePageBounds(i.id);e&&He(e)&&n.push({shape:i,bounds:e})}return n}getPageToParentTransform(e){const t=e.startsWith("shape:")?this.editor.getShape(e):null;return t?this.editor.computeShapeLocalToPageTransform(t).tryInvert():FI.Identity()}pageDeltaToParentDelta(e,t){const n=e.applyToPoint($I.Zero());return e.applyToPoint(t).sub(n)}},xw=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.getSessionRecord(),a=s.pageSelectedShapeIdsById[i]??[];n.getShapeEditingSession()&&!n.completeEditing(o)||Ne(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.getSessionRecord(),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})}},Iw=class{editor;frameGeometrySignal;companionFrameGeometriesSignal;pathSignal;bindingSegmentsSignal;frameStyleSignal;frameSignal;handleAnchorsSignal;handlesSignal;handleCountsSignal;overlaySignal;debugStateSignal;debugStateSnapshotSignal;constructor(e){this.editor=e,this.frameGeometrySignal=l("editor.selectionOverlayFrameGeometry",()=>{const t=e.selectedShapeOverlayItemsSignal.get();if(0===t.length)return null;if(Xi(t))return null;const n=e.getSelectionFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:wi}),this.companionFrameGeometriesSignal=l("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:Pi}),this.pathSignal=l("editor.selectionOverlayPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return Xi(t)?t[0]?.path??null:null}),this.bindingSegmentsSignal=l("editor.selectionOverlayBindingSegments",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return Xi(t)?[...t[0]?.bindingSegments??[]]:[]},{isEqual:Mt}),this.frameStyleSignal=l("editor.selectionOverlayFrameStyle",()=>{const t=e.cameraZoomSignal.get();return{strokeWidth:2/t,cornerRadius:3/t}},{isEqual:vi}),this.frameSignal=l("editor.selectionOverlayFrame",()=>{const e=this.frameGeometrySignal.get();if(!e)return null;const t=this.frameStyleSignal.get();return{...e,...t}},{isEqual:Ii}),this.handleAnchorsSignal=l("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,r=e.canResizeSelection(),s=e.canRotateSelection();return Ni(t,n,i,t=>e.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:o,editor:e}),t=>r&&e.getShapeUtil(t).canUseSelectionResizeHandles(t,{editor:e}),t=>s&&e.getShapeUtil(t).canUseSelectionRotateHandle(t,{editor:e}),yi(e,e.getSelectionResizeTargetShapes(),n?.rotation??0))},{isEqual:zi}),this.handlesSignal=l("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}=Yi(t,n);return{resizeHandles:i,rotateHandles:o,terminalHandles:r,middleHandles:s,customHandles:a,strokeWidth:2/n}},{isEqual:Ui}),this.handleCountsSignal=l("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=l("editor.selectionOverlay",()=>{const e=this.frameSignal.get(),t=this.handlesSignal.get();return e&&t?{...e,...t}:null}),this.debugStateSnapshotSignal=l("editor.overlayDebugState.snapshot",t=>{const n=this.frameSignal.get(),i=this.handleCountsSignal.get(),o=t!==EI?t:null,r=!o||!Ii(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)=>Ke(e.metrics,t.metrics)}),this.debugStateSignal=l("editor.overlayDebugState.public",()=>this.debugStateSnapshotSignal.get().metrics,{isEqual:Ke})}},ww=class{editor;entryRequestAtom=a("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})}},Pw=class{editor;constructor(e){this.editor=e}computeParentToPageTransform(e,t=new Set([e.id])){if(!e.parentId.startsWith("shape:"))return FI.Identity();const n=this.editor.getShape(e.parentId);if(!n||t.has(n.id))return FI.Identity();const i=new Set(t);return i.add(n.id),ue(n,this.editor.getShapeUtil(n),this.computeParentToPageTransform(n,i))}computeShapePositionedBounds(e){return this.editor.getShapeUtil(e).getPositionedBounds(e)}computeShapeLocalBounds(e){return((e,t)=>t.getLocalBounds(e))(e,this.editor.getShapeUtil(e))}computeShapeRenderBounds(e){return((e,t)=>t.getRenderBounds(e))(e,this.editor.getShapeUtil(e))}computeShapeExportBounds(e){return ce(e,this.editor.getShapeUtil(e))}computeShapeLocalToPageTransform(e){return ue(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeRenderToPageTransform(e){return((e,t,n=FI.Identity())=>ue(e,t,n))(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeExportToPageTransform(e){return pe(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePageBounds(e){return((e,t,n=FI.Identity())=>LI.FromPoints(me(e,t,n)))(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeExportPageBounds(e){return((e,t,n=FI.Identity())=>{const i=ce(e,t),o=pe(e,t,n);return LI.FromPoints([new $I(i.minX,i.minY),new $I(i.maxX,i.minY),new $I(i.maxX,i.maxY),new $I(i.minX,i.maxY)].map(e=>o.applyToPoint(e)))})(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeGeometry(e){return ye(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePositionedToPageTransform(e){return he(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePageCenter(e){return this.computeShapeGeometry(e).center}computeShapePageCorners(e){return this.computeShapeGeometry(e).corners}computeShapePageOutlineVertices(e){return this.computeShapeGeometry(e).outlineVertices}getShapePositionedBounds(e){return this.editor.queries.getShapePositionedBounds(e)??null}getShapePageBounds(e){return this.editor.queries.getShapePageBounds(e)??null}getShapeGeometry(e){return this.editor.queries.getShapeGeometry(e)??null}getShapePositionedToPageTransform(e){return this.editor.queries.getShapePositionedToPageTransform(e)??null}getShapePageCenter(e){return this.editor.queries.getShapePageCenter(e)??null}getShapePageCorners(e){return this.editor.queries.getShapePageCorners(e)??null}getShapePageOutlineVertices(e){return this.editor.queries.getShapePageOutlineVertices(e)??[]}getSelectionPageBounds(){return this.editor.queries.getSelectionPageBounds()}getSelectionFrame(){const e=this.editor.queries.getSelectionFrameBounds(),t=this.editor.queries.getSelectionRotationCenter();return e&&t?{bounds:e,rotation:this.editor.queries.getSelectionRotation(),rotationCenter:t,hasCompatibleRotation:this.editor.queries.getSelectionHasCompatibleRotation()}:null}isPointInSelectionBounds(e){const t=this.getSelectionFrame();if(!t)return!1;const n=this.getSelectionFrameLocalBoundsPoint(e);return!!n&&t.bounds.containsPoint(n)}getSelectionFrameLocalBoundsPoint(e){const t=this.getSelectionFrame();return t?ri(e,t):null}getSelectionPageOutlineVertices(){return this.editor.queries.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.editor.queries.getSelectionAnchorPagePoint()}},vw=class extends Error{},kw=class{editor;constructor(e){this.editor=e}get store(){return G(this.editor)}getSelectionParentOrderState(){return _i(this.editor)}getSelectionGroupState(){return this.getGroupStateForShapeIds(this.editor.getSelectedShapeIds())}canGroupSelection(){return null!==this.getSelectionGroupState()}getGroupStateForShapeIds(e){const t=this.editor,n=Array.from(new Set(e.map(e=>t.bindings.getShapeHierarchyRootId(e)))),i=n.map(e=>t.getShape(e)).filter(e=>!!e);if(i.length!==n.length)return null;const o=new Set(n),r=i.filter(e=>!this.isShapeDescendantOfAny(e.id,o));if(r.length<2)return null;if(r.some(e=>t.isShapeOrAncestorLocked(e.id)||t.hasLockedDescendant(e.id)||t.isShapeHidden(e.id)))return null;const s=r[0]?.parentId;if(!s)return null;if(r.some(e=>e.parentId!==s))return null;const a=t.getChildShapes(s),l=new Set(r.map(e=>e.id)),d=a.filter(e=>l.has(e.id)).map(e=>e.id);if(d.length!==r.length)return null;const c=s.startsWith("shape:")?t.getShape(s):null,u=c?t.computeShapeLocalToPageTransform(c).tryInvert():null;if(c&&!u)return null;const h=d.flatMap(e=>t.getShapePageOutlineVertices(e).map(e=>u?u.applyToPoint(e):e)),p=h.length>0?LI.FromPoints(h):null;if(!p||!He(p))return null;const g={parentId:s,shapeIds:d,parentLocalBounds:p};return this.getGroupingShapeCreateInput(g)?g:null}getGroupingShapeCreateInput(e){let t=null;for(const n of this.editor.shapeUtils.values()){const i=n.getGroupingShapeCreateInput({parentId:e.parentId,parentLocalBounds:e.parentLocalBounds});if(i){if(i.type!==n.type)throw new Error(`Shape util "${n.type}" created grouping type "${i.type}" instead of its registered type`);if(i.parentId!==e.parentId)throw new Error(`Shape util "${n.type}" must preserve the requested grouping parent`);if(t)throw new Error(`Multiple shape utils define grouping creation: "${t.shapeUtilType}" and "${n.type}"`);t={shapeInput:i,shapeUtilType:n.type}}}return t?.shapeInput??null}groupShapesFromState(e,t){const n=this.editor,i=this.getGroupingShapeCreateInput(e);if(!i)return null;const o=n.getChildShapes(e.parentId),r=new Set(e.shapeIds);let s;for(const d of o)r.has(d.id)&&(s=d);if(!s)return null;n.cancelInteractionForCommand();let a=null;try{this.store.atomic(()=>{const[l]=n.commands.createShapes([i],{source:t,deferMinimumChildRepair:!0});if(!l)throw new vw;if(a=l.id,!n.commands.reparentShapes({ids:e.shapeIds,parentId:l.id},{source:t}))throw new vw;const d=[];for(const e of o)r.has(e.id)?e.id===s.id&&d.push(l.id):d.push(e.id);n.commands.updateShapes([...d.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)})),...e.shapeIds.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)}))],{source:t})},t)}catch(l){if(l instanceof vw)return null;throw l}return a?n.getShape(a)??null:null}canGroupShapes(e){return null!==this.getGroupStateForShapeIds(e)}groupShapes(e,t="user"){const n=this.getGroupStateForShapeIds(e);return n?this.groupShapesFromState(n,t):null}groupSelection(e="user"){const t=this.editor,n=this.groupShapes(t.getSelectedShapeIds(),e);return n&&t.commands.setSelectedShapeIds([n.id],{source:e}),n}getUngroupableSelectedShapeIds(){return this.getUngroupableShapeIds(this.editor.getSelectedShapeIds())}getUngroupableShapeIds(e){const t=this.editor;return e.map(e=>t.getShape(e)).filter(e=>!!e).filter(e=>t.getShapeUtil(e).canUngroupChildren(e)).filter(e=>!t.isShapeOrAncestorLocked(e.id)&&!t.hasLockedDescendant(e.id)&&!t.isShapeHidden(e.id)&&t.getChildShapeIds(e.id).length>0&&t.getChildShapes(e.id).every(n=>t.canUseShapeParent(e.parentId,n.id)&&!!Se(t,n,e.parentId))).map(e=>e.id)}canUngroupSelection(){return this.getUngroupableSelectedShapeIds().length>0}canUngroupShapes(e){return this.getUngroupableShapeIds(e).length>0}ungroupShapes(e,t="user"){const n=this.editor,i=Array.from(new Set(e)),o=new Set(this.getOutermostUngroupableShapeIds(i));if(0===o.size)return[];const r=i.map(e=>n.getShape(e)).filter(e=>!!e),s=r.filter(e=>o.has(e.id)).map(e=>({group:e,children:n.getChildShapes(e.id)}));if(s.some(e=>e.children.some(t=>!Se(n,t,e.group.parentId))))return[];const a=new Map(s.map(e=>[e.group.id,e])),l=new Set(s.map(e=>e.group.parentId)),d=new Map;for(const p of l){const e=[];for(const t of n.getChildShapes(p)){const n=a.get(t.id);n?e.push(...n.children.map(e=>e.id)):e.push(t.id)}d.set(p,e)}n.cancelInteractionForCommand();const c=[],u=new Set;try{this.store.atomic(()=>{const e=[];for(const i of r){if(!o.has(i.id)){u.has(i.id)||(u.add(i.id),c.push(i.id));continue}const e=a.get(i.id);if(!e)continue;if(!n.commands.reparentShapes({ids:e.children.map(e=>e.id),parentId:e.group.parentId},{source:t}))throw new vw;const r=new Set(e.children.map(e=>e.id));for(const t of e.children){const e=n.bindings.getShapeHierarchyRootId(t.id),i=r.has(e)?e:t.id;u.has(i)||(u.add(i),c.push(i))}}for(const t of d.values())e.push(...t.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)})));e.length>0&&n.commands.updateShapes(e,{source:t}),this.removeUngroupedContainerShapes(s.map(e=>e.group.id),t)},t)}catch(h){if(h instanceof vw)return[];throw h}return c.length>0&&n.commands.setSelectedShapeIds(c,{source:t}),c}ungroupSelection(e="user"){return this.ungroupShapes(this.editor.getSelectedShapeIds(),e)}getOutermostUngroupableShapeIds(e){const t=this.getUngroupableShapeIds(e),n=new Set(t);return t.filter(e=>!this.isShapeDescendantOfAny(e,n))}isShapeDescendantOfAny(e,t){let n=this.editor.getShape(e);const 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=Array.from(new Set(e)).filter(e=>n.getShape(e));0!==i.length&&(n.sideEffects.runBeforeDelete("shape",i,t),this.store.remove(i,t),n.sideEffects.runAfterDelete("shape",i,t))}getSelectionSiblingOrderState(){return Hi(this.editor)}canMoveSelectionWithinParent(e){return((e,t)=>{const n=Hi(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveSelectionInParentOrder(e){return((e,t)=>{const n=_i(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveShapesInParentOrder(e,t){return((e,t,n)=>{const i=Wi(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this.editor,e,t)}moveShapesInParentOrder(e,t,n="user"){return Ki(this.editor,e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return Vi(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=Hi(e);if(!r)return!1;const s=e.getChildShapes(r.parentId),a=r.index;if(s[a]?.id!==o.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)}moveShapesToParentPlacementResult(e,t="user"){return function(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 s of o){if(s.isLocked)return{ok:!1,reason:"locked"};if(e.isShapeHidden(s.id))return{ok:!1,reason:"hidden"}}for(const s 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===s||e.getDescendantShapeIds(s).includes(t.id))return{ok:!1,reason:"cycle"};if(!e.canUseShapeParent(t.id,s))return{ok:!1,reason:"invalidParent"}}}const r=((e,t,n,i,o)=>{const r=((e,t,n,i)=>{const o=new Set(n),r=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,s=G(e).getAll().filter(e=>f(e)&&e.parentId===t.parentId).filter(e=>!o.has(e.id));s.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));let a=s.length;if(t.beforeId){const e=s.findIndex(e=>e.id===t.beforeId);if(-1===e)return{ok:!1,reason:"invalidBeforeId"};a=e}s.splice(a,0,...i);const l=new Map;for(const d of i){if(d.parentId===t.parentId)continue;const n=Se(e,d,t.parentId);if(!n)return{ok:!1,reason:"unsupportedTransform"};l.set(d.id,n)}return{ok:!0,updates:s.map((n,i)=>{const o=n.parentId!==t.parentId&&r?e.getShapeUtil(r).getChildPlacementMeta(r,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+1),...l.get(n.id),meta:o===n.meta?void 0:o}})}})(e,t,n,i);return r.ok?(e.cancelInteractionForCommand(),e.commands.updateShapes(r.updates,{source:o}),r):r})(e,t,i,o,n);return r.ok?{ok:!0,movedIds:i}:{ok:!1,reason:r.reason}}(this.editor,e,t)}moveSelectionInParentOrder(e,t="user"){return((e,t,n="user")=>Ki(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}moveSelectionToParentOrderEdge(e,t="user"){return((e,t,n="user")=>Vi(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).isSelectionTransformContainer(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.getOutermostUnlockedShapeIds(e)}getShapeIdsForSelectionRotation(e){return this.getOutermostUnlockedShapeIds(e)}getSelectionTransformTargetShapes(){return this.getShapeIdsForSelectionTransform(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}canResizeSelection(){const e=this.editor,t=this.getSelectionTransformAffectedShapes();return t.length>0&&t.every(t=>e.getShapeUtil(t).canParticipateInSelectionResize(t,{editor:e}))}canRotateSelection(){const e=this.editor,t=this.getSelectionTransformAffectedShapes();return t.length>0&&t.every(t=>e.getShapeUtil(t).canParticipateInSelectionRotation(t,{editor:e}))}getSelectionResizeTargetShapes(){const e=this.editor,t=[],n=new Set,i=o=>{if(!n.has(o.id))if(n.add(o.id),e.getShapeUtil(o).shouldResizeDescendants(o))for(const t of e.getChildShapes(o.id))i(t);else t.push(o)};for(const o of this.getOutermostUnlockedShapeIds(e.getSelectedShapeIds())){const t=e.getShape(o);t&&i(t)}return t}getSelectionRotationTargetShapes(){return this.getShapeIdsForSelectionRotation(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getSelectionTransformAffectedShapes(){const e=this.editor,t=this.getOutermostUnlockedShapeIds(e.getSelectedShapeIds());return this.getShapeIdsIncludingDescendants(t).map(t=>e.getShape(t)).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 o of this.getShapeIdsIncludingDescendants([e]))i.has(o)||t.isShapeHidden(o)||(i.add(o),n.push(o))}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((e,t,n)=>{if(t.startsWith("page:"))return!!e.getPage(t);const i=e.getShape(t);if(!i)return!1;if(n){const t=e.getShape(n);return!!t&&i.id!==n&&!e.getDescendantShapeIds(n).includes(i.id)&&e.getShapeUtil(i).canReceiveChild(i,t)}return e.getShapeUtil(i).canReceiveChildren(i)})(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}getOutermostUnlockedShapeIds(e){const t=this.editor,n=Array.from(new Set(e)),i=new Set(n);return n.filter(e=>{const n=t.getShape(e);return!(!n||t.isShapeOrAncestorLocked(n.id)||t.hasLockedDescendant(n.id)||this.isShapeDescendantOfAny(n.id,i))})}},Cw=class{bindings=new Map;bindingIds=[];register(e){const t=this.bindingIds.indexOf(e.id);t>=0&&this.bindingIds.splice(t,1);const n=qi(e.shortcut);this.bindingIds.push(e.id),this.bindings.set(e.id,{id:e.id,shortcut:n,target:e.target,label:e.label??ji(n)})}registerActionShortcut(e,t){this.register({id:`action:${e}`,shortcut:t,target:{type:"action",actionId:e}})}registerEditorShortcut(e,t){const n=qi(t);this.register({id:`editor:${e}:${Qi(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&&Gi(n.shortcut,e))return n}return null}getBindingLabel(e){return this.bindings.get(e)?.label}},Tw=class{editor;shapeRenderOrderByIdSignal;culledShapeIdsSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;renderVisibleShapeIdSetSignal;renderItemsSignal;renderHostDebugStateSignal;retainedBaseShapeWindowSnapshotSignal;retainedShapeWindowSnapshotSignal;renderHostDebugStateSnapshotSignal;constructor(e){this.editor=e,this.shapeRenderOrderByIdSignal=l("editor.shapeRenderOrderById",()=>{const t=new Map;for(const[n,i]of e.currentPageShapeIdsSignal.get().entries())t.set(i,n);return t}),this.culledShapeIdsSignal=l("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=l("editor.retainedBaseShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),o=oo(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(t!==EI&&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,l={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 l.end-l.start>n.end-n.start+4?null:l});if(n.some(e=>null===e))return null;const i=n;if(to(i).length!==t.length)return null;const o=io(t);return io(i)>o+12?null:i})(to(t.ranges.map(e=>({...e}))),o);if(e)return so(n,e,{viewportReady:i})}return so(n,o,{viewportReady:i})},{isEqual:(e,t)=>Ne(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=l("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:je}),this.selectedShapeIdsOutsideCulledSignal=l("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=l("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:je}),this.renderVisibleShapeIdsSignal=l("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=l("editor.retainedShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),o=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,r=(s=o.length)<=0?0:Ji(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,l]of e.entries())o.set(l,a);const r=to(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=Ji(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,l=a?a.start-i.end:1/0,d=no(o?i.start-o.end:1/0,t),c=no(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=o.get(a);void 0!==e&&s.push({start:e,end:e+1})}return 0===s.length?[]:to(s,2)})(n,o,this.selectedShapeIdsOutsideCulledSetSignal.get(),r);if(i&&t!==EI&&t&&t.viewportReady&&t.ranges.length>0&&a.length>0){const e=to(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 so(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(to(i).length!==t.length)return null;const o=io(t);return io(i)>o+n?null:i})(e,a,r);if(o)return so(n,o,{viewportReady:i})}return so(n,a,{viewportReady:i})},{isEqual:(e,t)=>Ne(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=l("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:Ne}),this.renderVisibleShapeIdSetSignal=l("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:je}),this.renderItemsSignal=l("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:qe}),this.renderHostDebugStateSnapshotSignal=l("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()),l=oo(n,a),d=oo(r,a),c=oo(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===EI?[]:t.retainedShapeIds,r);return{metrics:{culledCount:n.length,visibleCount:i.length,retainedCount:r.length,retainedBaseCount:o.length,culledRangeCount:l.length,culledRangeSpan:io(l),culledRangesSummary:eo(l),retainedBaseRangeCount:c.length,retainedBaseRangeSpan:io(c),retainedBaseRangesSummary:eo(c),retainedRangeCount:d.length,retainedRangeSpan:io(d),retainedRangesSummary:eo(d),retainedChangeCount:u.changed,retainedAddedCount:u.added,retainedRemovedCount:u.removed,selectedOutsideCulledCount:s.length},retainedShapeIds:r.slice()}},{isEqual:(e,t)=>We(e.metrics,t.metrics)}),this.renderHostDebugStateSignal=l("editor.renderHostDebugState.public",()=>this.renderHostDebugStateSnapshotSignal.get().metrics,{isEqual:We})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},Mw=class{editor;activeToolId=a("tools.activeToolId","select");isToolLocked=a("tools.isToolLocked",!1);registry=new Map;activeTool=null;constructor(e){this.editor=e}register(e,t,n={}){this.registry.set(e,t),n.shortcut&&this.editor.shortcuts.registerToolShortcut(e,n.shortcut)}hasTool(e){return this.registry.has(e)}setActiveTool(e,t="tool_switch"){const n=this.registry.get(e);if(!n)throw new Error(`Unknown tool "${e}"`);this.activeTool&&this.activeToolId.get()===e||(this.activeTool&&(this.editor.cancelInteractionAndClearTransients(t),this.activeTool.exit({reason:t})),this.activeToolId.set(e),this.activeTool=n(this.editor),this.activeTool.enter())}dispatch(e){this.activeTool?.dispatch(e)}cancel(e){this.activeTool?.dispatch({type:"cancel",reason:e})}setToolLocked(e){this.isToolLocked.set(e)}isActiveToolInInitialState(){return this.activeTool?.isInInitialState()??!0}},Ew=class{handlers=[];registeredIds=new Set;register(e){this.registeredIds.has(e.id)||(this.handlers.push(e),this.registeredIds.add(e.id))}getHandlers(){return this.handlers}handleEvent(e,t){for(const n of this.handlers)if("handled"===n.editorEvent?.handleEvent(e,t))return"handled";return"continue"}broadcastEvent(e,t){for(const n of this.handlers)n.editorEvent?.handleEvent(e,t)}createSelectionHandleSession(e,t){for(const n of this.handlers){const i=n.selectionHandle?.createSession(e,t);if(i)return i}return null}},Bw=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}},Aw=class{store;[KI];inputs=new iw;snapshots=new nw(this);clipboard=new ew(this);shortcuts=new Cw;tools=new Mw(this);camera=new QI(this);selection=new xw(this);selectionLayout=new bw(this);editing=new ww(this);geometry=new Pw(this);hierarchy=new kw(this);shapeUtils=new NI;shapeSvgExporters=new WI;bindingUtils=new RI;interactions=new Ew;selectionHandleInteractions=new Bw(this.interactions);runtime=new DI;queries;bindings;spatialIndex;snaps;renderWindow;selectionOverlay;transients=new ow(this);history;sideEffects=new Sw;commands;shapeCapabilityDefinitions;brushBoxSignal=this.transients.brushBoxSignal;brushBoxActiveSignal=this.transients.brushBoxActiveSignal;bindingPreviewSignal=this.transients.bindingPreviewSignal;bindingPreviewActiveSignal=this.transients.bindingPreviewActiveSignal;terminalBindingGuidesSignal=this.transients.terminalBindingGuidesSignal;dropTargetShapeIdSignal=this.transients.dropTargetShapeIdSignal;hoveredShapeIdSignal=this.transients.hoveredShapeIdSignal;selectionTranslationActiveSignal=this.transients.selectionTranslationActiveSignal;snapIndicatorsSignal;snapIndicatorsActiveSignal;get viewportScreenSizeSignal(){return this.camera.viewportScreenSizeSignal}shapeEditingEntryRequestSignal=this.editing.entryRequestSignal;_shapeDefaultPropsByTypeSignal=a("editor.shapeDefaultPropsByType",new Map);shapeDefaultPropsByTypeSignal=this._shapeDefaultPropsByTypeSignal;nextShapeNumber=1;nextPageNumber=1;nextBindingNumber=1;nextAssetNumber=1;assetUrlResolver=()=>null;get _internalStore(){return G(this)}sessionSignal=l("editor.session",()=>{const e=this._internalStore.getRecordSignal(OI).get();if(!m(e))throw new Error("Missing session record");return e});getSessionRecord(){const e=this._internalStore.get(OI);if(!m(e))throw new Error("Missing session record");return e}currentPageIdSignal=l("editor.currentPageId",()=>this.sessionSignal.get().currentPageId);currentPageShapeIdsSignal;currentPageShapesSignal;currentPageShapeHierarchySignal;culledShapeIdsSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionAnchorPagePointSignal;pagesSignal=l("editor.pages",()=>Array.from(this._internalStore.recordsSignal.get().values()).filter(p).sort((e,t)=>e.index.localeCompare(t.index)),{isEqual:Oe});currentPageSignal=l("editor.currentPage",()=>{const e=this.currentPageIdSignal.get();return this.pagesSignal.get().find(t=>t.id===e)??null});pageStateSignal=l("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=l("editor.toolState",()=>{const e=this.sessionSignal.get();return{activeToolId:e.activeToolId,isToolLocked:e.isToolLocked}});editingShapeIdSignal=l("editor.editingShapeId",()=>this.sessionSignal.get().editingShapeId);shapeEditingSessionSignal=l("editor.shapeEditingSession",()=>this.sessionSignal.get().shapeEditingSession);shapeEditingStateSignal=l("editor.shapeEditingState",()=>({editingShapeId:this.editingShapeIdSignal.get(),session:this.shapeEditingSessionSignal.get()}));currentCameraSignal=l("editor.currentCamera",()=>this.sessionSignal.get().pageCameraById[this.currentPageIdSignal.get()]??XI);selectedShapeIdsSignal=l("editor.selectedShapeIds",()=>{const e=this.sessionSignal.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:Ne});selectionCountSignal=l("editor.selectionCount",()=>this.selectedShapeIdsSignal.get().length);selectedShapeIdSetSignal=l("editor.selectedShapeIdSet",()=>new Set(this.selectedShapeIdsSignal.get()),{isEqual:je});selectedShapesSignal=l("editor.selectedShapes",()=>this.selectedShapeIdsSignal.get().map(e=>this.getShapeSignal(e).get()).filter(e=>!!e));selectedShapeOverlayItemsSignal=l("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:xi});selectionStateSignal=l("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,l=t?this.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:o,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:r,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()}});selectionMetadataSignal=l("editor.selectionMetadata",()=>{const e=this.selectionStateSignal.get();return{count:e.count,singleShapeType:e.singleShapeType,commonShapeType:e.commonShapeType,hasPointHandleSelection:e.hasPointHandleSelection,hasFrameSelection:e.hasFrameSelection,isMixedFrameAndPointHandleSelection:e.isMixedFrameAndPointHandleSelection,canDragPointHandles:e.canDragPointHandles,hasSelectionRotation:e.hasSelectionRotation,hasMixedSelectionRotation:e.hasMixedSelectionRotation,canResetSelectionRotation:e.canResetSelectionRotation}},{isEqual:Xe});pageTransformSignal=l("editor.pageTransform",()=>{const e=this.currentCameraSignal.get();return FI.Scale(e.z,e.z).compose(FI.Translate(-e.x,-e.y))});cameraZoomSignal=l("editor.cameraZoom",()=>this.currentCameraSignal.get().z);viewportPageBoundsSignal=l("editor.viewportPageBounds",()=>{const{w:e,h:t}=this.viewportScreenSizeSignal.get();if(e<=0||t<=0)return null;const n=this.currentCameraSignal.get();return new LI(n.x,n.y,e/n.z,t/n.z)});renderViewportPageBoundsSignal=l("editor.renderViewportPageBounds",e=>{const t=this.viewportPageBoundsSignal.get();return t?e!==EI&&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:_e});renderItemsSignal;renderHostDebugStateSignal;historyStateSignal;shapeRenderOrderByIdSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdSetSignal;shapeSignals=new Map;shapeSelectedSignals=new Map;shapeRenderOrderSignals=new Map;shapeRenderVisibleSignals=new Map;shapeDocumentVisibleSignals=new Map;shapeEffectiveOpacitySignals=new Map;shapeEditingSessionSignals=new Map;shapeDropTargetSignals=new Map;shapeHoveredSignals=new Map;shapeSelectedDescendantTransformAncestorSignals=new Map;lastPointerDownForClickCount=null;lastPointerUpForClickCount=null;currentPointerClickCount=1;selectionOverlayFrameGeometrySignal;selectionOverlayCompanionFrameGeometriesSignal;selectionOverlayPathSignal;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 qI(this.snapshots.buildInitialRecords(e.documentSnapshot??null,e.sessionSnapshot??null,e.documentMeta??{}));var n;((e,t)=>{e[KI]=t})(this,t),this.store=t,this.snapshots.ensureSessionIntegrity(),this.queries=new sw(this),this.bindings=new ZI(this),this.spatialIndex=new lw(this,this.queries),this.snaps=new yw(this),this.snapIndicatorsSignal=this.snaps.indicatorsSignal,this.snapIndicatorsActiveSignal=this.snaps.activeSignal,this.currentPageShapeIdsSignal=this.queries.currentPageShapeIdsSignal,this.currentPageShapesSignal=this.queries.currentPageShapesSignal,this.currentPageShapeHierarchySignal=this.queries.currentPageShapeHierarchySignal,this.selectionPageBoundsSignal=this.queries.selectionPageBoundsSignal,this.selectionFrameBoundsSignal=this.queries.selectionFrameBoundsSignal,this.selectionAnchorPagePointSignal=this.queries.selectionAnchorPagePointSignal,this.selectionOverlay=new Iw(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 Tw(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 jI(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 G(e).atomic(()=>{const t=be([...e.getPages(),o]);r=t.find(e=>e.id===o.id)??o,G(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=be(o.filter(e=>e.id!==t)),l=o[r+1]?.id??o[r-1]?.id??o[0]?.id,d=e.getCurrentPageId()===t&&l?l:e.getCurrentPageId();return G(e).atomic(()=>{s.length>0&&$e(e,s,n),G(e).remove([t],i),e.removePageSessionState(t,d,i),G(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&&G(e).atomic(()=>{G(e).put([{...o,name:r}],i)},i)})(n,e,t)},updateDocumentMeta:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getDocumentMetadataRecord()??c(),r={...o,meta:{...o.meta,...t.patch}};return G(e).atomic(()=>{G(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 G(e).atomic(()=>{G(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],[l]=a.splice(r,1);l&&(a.splice(s,0,l),G(e).atomic(()=>{G(e).put(be(a),i)},i))})(n,e,t)},createShapes:(e,t)=>((e,t,n)=>{const i=[],o=n?.source??"user";return G(e).atomic(()=>{const r=t.map(t=>e.createShapeRecord(t)),s=new Map(r.map(e=>[e.id,e])),a=r.map(t=>{if(!t.parentId.startsWith("shape:"))return t;const n=s.get(t.parentId)??e.getShape(t.parentId);if(!n)return t;const i=e.getShapeUtil(n).getChildPlacementMeta(n,t,{editor:e,reason:"create"});return i===t.meta?t:{...t,meta:i}});if(we(e,a),G(e).put(a,o),"user"===o&&!1!==n?.autoReparent){const i=new Map;for(let n=0;n<a.length;n+=1){const o=a[n],r=t[n];if(!o||!r||r.parentId)continue;const s=e.getContainingParentIdForShapeRecord(o);s&&s!==o.parentId&&i.set(o.id,s)}((e,t)=>{const n=new Set;for(const i of e.keys()){const o=[],r=new Map;let s=i;for(;s;){const i=r.get(s);if(void 0!==i){for(const e of o.slice(i))n.add(e);break}r.set(s,o.length),o.push(s);const a=e.get(s);s=a?.startsWith("shape:")&&t.has(a)?a:null}}for(const i of n)e.delete(i)})(i,new Set(a.map(e=>e.id)));const o=new Map;for(const e of a){const t=i.get(e.id);if(!t)continue;const n=o.get(t)??[];n.push(e.id),o.set(t,n)}for(const[t,r]of o)Re(e,{ids:r,parentId:t},n)}const l=Be(e,a.map(e=>e.id)),d=new Set;if(!n?.deferMinimumChildRepair){const t=new Set;for(const n of a){const i=e.getShape(n.id);i&&e.getShapeUtil(i).getMinimumChildCount(i)>0&&t.add(i.id)}Ae(e,t,d,o)}Ce(e,l,o,d),i.push(...a.map(t=>e.getShape(t.id)).filter(e=>!!e))},o),i})(n,e,t),createShapesFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";if(0===t.length)return[];for(const o of t)if(e.getShape(o.id))throw new Error(`Shape ${o.id} already exists`);return we(e,t),G(e).atomic(()=>{G(e).put(t,i),Pe(e,i);const n=Be(e,t.map(e=>e.id));for(const i of t){const t=e.getShape(i.id);t&&e.getShapeUtil(t).getMinimumChildCount(t)>0&&n.add(t.id)}const o=new Set;Ae(e,n,o,i),Ce(e,n,i,o)},i),t.map(t=>e.getShape(t.id)).filter(e=>!!e)})(n,e,t),updateShapes(e,t){Ie(n,e,t)},reparentShapes:(e,t)=>Re(n,e,t),deleteShapes(e,t){$e(n,e,t)},createAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.createAssetRecord(t);return G(e).atomic(()=>{G(e).put([o],i)},i),o})(n,e,t),createAssetsFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(G(e).atomic(()=>{G(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 G(e).atomic(()=>{G(e).put([r],i)},i),r})(n,e,t),deleteAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return!!e.getAsset(t)&&(G(e).atomic(()=>{G(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(!Le(e,o))throw new Error(`Invalid binding endpoints for ${o.type} binding`);const r=new Set;return Fe(e,[o.fromId,o.toId],r),G(e).atomic(()=>{const t=e.bindings.getConflictingBindings(o).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),G(e).put([o],i),e.bindings.syncCreatedBinding(o,i),Fe(e,[o.fromId,o.toId],r),Ae(e,r,new Set,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(!Le(e,s))throw new Error(`Invalid binding endpoints for ${s.type} binding`);const a=new Set;return Fe(e,[o.fromId,o.toId,s.fromId,s.toId],a),G(e).atomic(()=>{const t=e.bindings.getConflictingBindings(s).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),G(e).put([s],i),e.bindings.syncUpdatedBinding(o,s,i),Fe(e,[o.fromId,o.toId,s.fromId,s.toId],a),Ae(e,a,new Set,i)},i),s})(n,e,t),deleteBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getBinding(t);return!!o&&(G(e).atomic(()=>{e.bindings.cleanupBindings([o.id],i),G(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.tools.setActiveTool(t),e.completeEditing(i),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(function(){let e=!1,t=null;const n=()=>{t=null};return{id:"land.camera.canvas-pan",editorEvent:{handleEvent(i,o){if("cancel"===o.type)return"blur"!==o.reason&&"dispose"!==o.reason||(e=!1),n(),"continue";if("keyboard"===o.type&&(e=>"Space"===e.code)(o)){if("key_up"===o.name){const t=e;return e=!1,t?"handled":"continue"}return i.getShapeEditingSession()?"continue":(e=!0,"handled")}if("pointer"!==o.type||"mouse"!==o.pointerType)return"continue";if("pointer_down"===o.name){n();const r=((e,{allowLeftButton:t})=>1===e.button?4:t&&0===e.button?1:null)(o,{allowLeftButton:i.inputs.isSpacePressed.get()&&!i.getShapeEditingSession()});return null===r?"continue":(i.resetPointerClickTracking(),0===o.button&&(e=!0),t={pointerId:o.pointerId,buttons:r,camera:ao(i,o.screenPoint)},"handled")}return t&&o.pointerId===t.pointerId?"pointer_move"===o.name?0===(o.buttons&t.buttons)?(n(),"handled"):(lo(i,t.camera,o.screenPoint),"handled"):"pointer_up"===o.name||"pointer_cancel"===o.name?(n(),"handled"):"continue":"continue"}}}}())}registerBuiltInShortcuts(){this.shortcuts.registerEditorShortcut("move-selection-backward",{key:"ArrowDown",altKey:!0}),this.shortcuts.registerEditorShortcut("move-selection-forward",{key:"ArrowUp",altKey:!0}),this.shortcuts.registerEditorShortcut("undo",{key:"z",accelKey:!0}),this.shortcuts.registerEditorShortcut("redo",{key:"z",accelKey:!0,shiftKey:!0}),this.shortcuts.registerEditorShortcut("delete-selection","Backspace"),this.shortcuts.registerEditorShortcut("delete-selection","Delete"),this.shortcuts.registerEditorShortcut("reset-interaction","Escape")}registerBuiltInSideEffects(){this.sideEffects.registerBeforeDeleteHandler("shape",(e,t)=>{this.bindings.cleanupBindingsForDeletedShapes(e,t)}),this.sideEffects.registerAfterDeleteHandler("shape",(e,t)=>{this.removeShapeIdsFromSelection(e,t),this.removeShapeIdsFromEditingSession(e,t)})}dispatch(e){const t=this.normalizeEvent(e);if(this.inputs.handleEvent(t),"keyboard"===t.type&&"key_down"===t.name){const e=this.shortcuts.getTargetForEvent(t);if(e&&this.runKeyboardShortcutTarget(e))return}if("wheel"!==t.type)if("cancel"!==t.type){if("pointer"===t.type&&"pointer_cancel"===t.name)return this.interactions.broadcastEvent(this,t),void this.cancelInteractionAndClearTransients("pointer_cancel",{notifyInteractionHandlers:!1});if("handled"!==this.interactions.handleEvent(this,t)&&(this.tools.dispatch(t),"pointer"===t.type&&"pointer_up"===t.name)){const e=this.getDoubleClickEvent(t);e&&"handled"!==this.interactions.handleEvent(this,e)&&this.tools.dispatch(e)}}else this.cancelInteractionAndClearTransients(t.reason);else this.handleWheelEvent(t)}handleInteractionEvent(e){const t=this.normalizeEvent(e);return this.inputs.handleEvent(t),"handled"===this.interactions.handleEvent(this,t)}runKeyboardShortcutTarget(e){switch(e.type){case"action":return!1;case"editor":return this.runEditorKeyboardShortcut(e.command);case"tool":return this.commands.setActiveTool(e.toolId,{source:"system"}),!0}}runEditorKeyboardShortcut(e){switch(e){case"delete-selection":return!this.getShapeEditingSession()&&(this.deleteSelection("user"),!0);case"move-selection-backward":return this.moveSelectionWithinParent("backward","user");case"move-selection-forward":return this.moveSelectionWithinParent("forward","user");case"redo":return this.redo(),!0;case"reset-interaction":return 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(UI);return g(e)?e:void 0}getCurrentPageId(){return this.currentPageIdSignal.get()}getActiveToolId(){return this.sessionSignal.get().activeToolId}isToolLocked(){return this.sessionSignal.get().isToolLocked}isActiveToolInInitialState(){return this.tools.isActiveToolInInitialState()}getEditingShapeId(){return this.editingShapeIdSignal.get()}getShapeEditingSession(){return this.shapeEditingSessionSignal.get()}getShapeEditingEntryRequest(){return this.shapeEditingEntryRequestSignal.get()}resetPointerClickTracking(){this.lastPointerDownForClickCount=null,this.lastPointerUpForClickCount=null,this.currentPointerClickCount=1}getCurrentPageShapeIds(){return this.currentPageShapeIdsSignal.get()}getPage(e){const t=this._internalStore.get(e);return p(t)?t:void 0}getCurrentCamera(){return this.camera.getCurrentCamera()}undo(){return this.history.getActiveScope()||this.cancelInteractionForCommand(),this.history.undo()}redo(){return this.history.getActiveScope()||this.cancelInteractionForCommand(),this.history.redo()}createPageAndSelect(e,t="user"){const n=this.commands.createPage(e,{source:t});return this.commands.setCurrentPageId(n.id,{source:t}),n}selectPage(e,t="user"){this.commands.setCurrentPageId(e,{source:t})}renamePage(e,t,n="user"){this.commands.renamePage({id:e,name:t},{source:n})}updateDocumentMeta(e,t="user"){return this.commands.updateDocumentMeta({patch:e},{source:t})}updatePageMeta(e,t,n="user"){return this.commands.updatePageMeta({id:e,patch:t},{source:n})}deletePage(e,t="user"){return this.cancelInteractionForCommand(),this.commands.deletePage(e,{source:t})}setActiveTool(e,t="system"){this.commands.setActiveTool(e,{source:t})}setToolLocked(e,t="system"){this.commands.setToolLocked(e,{source:t})}toggleToolLocked(e="system"){this.setToolLocked(!this.isToolLocked(),e)}getCamera(e=this.getCurrentPageId()){return this.camera.getCamera(e)}pageToScreen(e,t=this.getCurrentPageId()){return this.camera.pageToScreen(e,t)}screenToPage(e,t=this.getCurrentPageId()){return this.camera.screenToPage(e,t)}getSelectedShapeIds(e=this.getCurrentPageId()){return this.getSessionRecord().pageSelectedShapeIdsById[e]??[]}isShapeHidden(e){const t=new Set;let n=this.getShape(e);for(;n;){if(n.isHidden)return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(t.has(e))return!1;t.add(e);const i=this.getShape(e);if(!i)return!1;if(!this.getShapeUtil(i).isChildVisible(i,n,{editor:this}))return!0;n=i}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[l,d]of Object.entries(o))r[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[o,r]of n)if(!Ze(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)}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")=>{if(!e.canRotateSelection())return;const n=e.getSelectedShapes().filter(t=>e.getShapeUtil(t).contributesToSelectionFrame(t,{editor:e}));if(0===n.length)return;const i=n.flatMap(t=>{const n=Nt(e,t);if(!n)return[];const i=Yt(e,t,n,{id:t.id,rotation:0});return i?[i]:[]});i.length>0&&e.commands.updateShapes(i,{source:t})})(this,e)}flipSelection(e,t="user"){const n=function(e,t){if(!e.canResizeSelection())return[];const n=e.getSelectionTransformTargetShapes(),i=e.getSelectionFrame()??((e,t)=>{const n=t.flatMap(t=>{const n=Nt(e,t);return n?e.getShapeUtil(t).getSelectionPagePoints(n)??[]:[]});if(0===n.length)return null;const i=LI.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=Nt(e,t);if(!r)return null;const s=o.getSelectionPagePoints(r);if(!s&&!o.contributesToSelectionFrame(t,{editor:e}))return null;const a=(({points:e,transform:t})=>0===e.length?null:LI.FromPoints(e.map(e=>ri(e,t))))({points:s?[...s]:o.getPositionedOutlineVertices(t).map(n=>e.computeShapePositionedToPageTransform(t).applyToPoint(n)),transform:n});return a?Yt(e,t,r,o.flipSelectionBounds(r,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:ui({axis:i,bounds:a,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 f(t)?t:void 0}getAsset(e){const t=this._internalStore.get(e);return S(t)?t:void 0}getAssets(){return this._internalStore.getAll().filter(S).sort((e,t)=>e.id.localeCompare(t.id))}resolveAssetUrl(e){return this.assetUrlResolver(e)}getUnreferencedAssetIdsAfterShapeDelete(e){if(0===e.length)return[];const t=new Set(e),n=new Set,i=new Set;for(const o of this._internalStore.getAll().filter(f)){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=l(`editor.shape.${e}`,()=>{const t=this._internalStore.getRecordSignal(e).get();return f(t)?t:void 0}),this.shapeSignals.set(e,t)),t}getShapeLocalToPageTransformSignal(e){return this.queries.getShapeLocalToPageTransformSignal(e)}getShapeSelectedSignal(e){let t=this.shapeSelectedSignals.get(e);return t||(t=l(`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=l(`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=l(`editor.shapeRenderVisible.${e}`,()=>{const t=this.getShapeClipAncestorIdsSignal(e).get().length>0;return this.renderVisibleShapeIdSetSignal.get().has(e)&&this.getShapeDocumentVisibleSignal(e).get()&&(!t||null!==this.getShapeClippedPageBounds(e))}),this.shapeRenderVisibleSignals.set(e,t)),t}getShapeDocumentVisibleSignal(e){let t=this.shapeDocumentVisibleSignals.get(e);return t||(t=l(`editor.shapeDocumentVisible.${e}`,()=>{const t=new Set([e]);let n=this.getShapeSignal(e).get();if(!n)return!1;for(;n;){if(n.isHidden)return!1;if(!n.parentId.startsWith("shape:"))return!0;const e=n.parentId;if(t.has(e))return!0;t.add(e);const i=this.getShapeSignal(e).get();if(!i)return!0;if(!this.getShapeUtil(i).isChildVisible(i,n,{editor:this}))return!1;n=i}return!0}),this.shapeDocumentVisibleSignals.set(e,t)),t}getShapeEffectiveOpacitySignal(e){let t=this.shapeEffectiveOpacitySignals.get(e);return t||(t=l(`editor.shapeEffectiveOpacity.${e}`,()=>{const t=new Set([e]);let n=1,i=this.getShapeSignal(e).get();for(;i&&(n*=i.opacity,i.parentId.startsWith("shape:"));){const e=i.parentId;if(t.has(e))break;t.add(e),i=this.getShapeSignal(e).get()}return n}),this.shapeEffectiveOpacitySignals.set(e,t)),t}getShapeEditingSessionForShapeSignal(e){let t=this.shapeEditingSessionSignals.get(e);return t||(t=l(`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=l(`editor.shapeDropTarget.${e}`,()=>this.dropTargetShapeIdSignal.get()===e),this.shapeDropTargetSignals.set(e,t)),t}getShapeHoveredSignal(e){let t=this.shapeHoveredSignals.get(e);return t||(t=l(`editor.shapeHovered.${e}`,()=>this.hoveredShapeIdSignal.get()===e),this.shapeHoveredSignals.set(e,t)),t}getShapeSelectedDescendantTransformAncestorSignal(e){let t=this.shapeSelectedDescendantTransformAncestorSignals.get(e);return t||(t=l(`editor.shapeSelectedDescendantTransformAncestor.${e}`,()=>{if(this.getShapeSelectedSignal(e).get())return!1;const t=this.getShapeSignal(e).get();return!(!t||!this.getShapeUtil(t).isSelectionTransformContainer(t))&&this.selectedShapeIdsSignal.get().some(t=>this.hierarchy.isShapeDescendantOf(t,e))}),this.shapeSelectedDescendantTransformAncestorSignals.set(e,t)),t}getBinding(e){const t=this._internalStore.get(e);return y(t)?t:void 0}getShapesForPage(e){return this.queries.getShapesForPage(e)}getBindingsFromShape(e){return this.bindings.getBindingsFromShape(e)}getBindingsToShape(e){return this.bindings.getBindingsToShape(e)}getBindingsForShape(e){return this.bindings.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()}canResizeSelection(){return this.hierarchy.canResizeSelection()}canRotateSelection(){return this.hierarchy.canRotateSelection()}getSelectionResizeTargetShapes(){return this.hierarchy.getSelectionResizeTargetShapes()}getSelectionRotationTargetShapes(){return this.hierarchy.getSelectionRotationTargetShapes()}getShapeExportTraversalIds(e){return this.hierarchy.getShapeExportTraversalIds(e)}getShapeContainment(e,t){return this.queries.getShapeContainment(e,t)}getContainingShapeParentId(e){return this.queries.getContainingShapeParentId(e)}getContainingShapeParentIdAtPoint(e,t){return this.queries.getContainingShapeParentIdAtPoint(e,t)}getContainingParentIdForShapeRecord(e){return this.queries.getContainingParentIdForShapeRecord(e)}getShapeClipAncestorIds(e){return this.queries.getShapeClipAncestorIds(e)}getShapeClipAncestorIdsSignal(e){return this.queries.getShapeClipAncestorIdsSignal(e)}isPagePointInShapeClip(e,t){return this.queries.isPagePointInShapeClip(e,t)}getShapeClippedPageBounds(e){return this.queries.getShapeClippedPageBounds(e)}getShapeIdsInContainerBounds(e,t={}){return this.hierarchy.getShapeIdsInContainerBounds(e,t)}canUseShapeParent(e,t){return this.hierarchy.canUseShapeParent(e,t)}getShapeUtil(e){return this.shapeUtils.get(e.type)}getBindingUtil(e){return this.bindingUtils.get(e.type)}computeShapePositionedBounds(e){return this.geometry.computeShapePositionedBounds(e)}computeShapeLocalBounds(e){return this.geometry.computeShapeLocalBounds(e)}computeShapeRenderBounds(e){return this.geometry.computeShapeRenderBounds(e)}computeShapeExportBounds(e){return this.geometry.computeShapeExportBounds(e)}computeShapeLocalToPageTransform(e){return this.geometry.computeShapeLocalToPageTransform(e)}computeShapeRenderToPageTransform(e){return this.geometry.computeShapeRenderToPageTransform(e)}computeShapeExportToPageTransform(e){return this.geometry.computeShapeExportToPageTransform(e)}computeShapePageBounds(e){return this.geometry.computeShapePageBounds(e)}computeShapeExportPageBounds(e){return this.geometry.computeShapeExportPageBounds(e)}computeShapeGeometry(e){return this.geometry.computeShapeGeometry(e)}computeShapePositionedToPageTransform(e){return this.geometry.computeShapePositionedToPageTransform(e)}computeShapePageCenter(e){return this.geometry.computeShapePageCenter(e)}computeShapePageCorners(e){return this.geometry.computeShapePageCorners(e)}computeShapePageOutlineVertices(e){return this.geometry.computeShapePageOutlineVertices(e)}getShapePositionedBounds(e){return this.geometry.getShapePositionedBounds(e)}getShapePageBounds(e){return this.geometry.getShapePageBounds(e)}getShapeGeometry(e){return this.geometry.getShapeGeometry(e)}getShapePositionedToPageTransform(e){return this.geometry.getShapePositionedToPageTransform(e)}getShapePageCenter(e){return this.geometry.getShapePageCenter(e)}getShapePageCorners(e){return this.geometry.getShapePageCorners(e)}getShapePageOutlineVertices(e){return this.geometry.getShapePageOutlineVertices(e)}getSelectionPageBounds(){return this.geometry.getSelectionPageBounds()}getSelectionFrame(){return this.geometry.getSelectionFrame()}isPointInSelectionBounds(e){return this.geometry.isPointInSelectionBounds(e)}getSelectionFrameLocalBoundsPoint(e){return this.geometry.getSelectionFrameLocalBoundsPoint(e)}getSelectionPageOutlineVertices(){return this.geometry.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.geometry.getSelectionAnchorPagePoint()}hitTestSelectionHandle(e){const t=this.selectedShapesSignal.get(),n=this.getSelectionFrame();if(0===t.length)return null;const i=1===t.length,o=this.canResizeSelection(),r=this.canRotateSelection(),{terminalHandles:s,middleHandles:a,customHandles:l,rotateHandles:d,resizeHandles:c}=((e,t,n,i,o,r,s)=>Yi(Ni(e,t,n,i,o,r,s),n))(t,n,this.getCurrentCamera().z,e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:i,editor:this}),e=>o&&this.getShapeUtil(e).canUseSelectionResizeHandles(e,{editor:this}),e=>r&&this.getShapeUtil(e).canUseSelectionRotateHandle(e,{editor:this}),yi(this,this.getSelectionResizeTargetShapes(),n?.rotation??0));for(const u of a)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of s)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of l)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of c)if(u.bounds.containsPoint(e))return u;if(n){const t=((e,t,n,i)=>{const o=new Set(n.map(e=>e.id)),r=ri(e,t),{bounds:s}=t,a=[];r.x>=s.minX&&r.x<=s.maxX&&(o.has("top")&&a.push({id:"top",distance:Math.abs(r.y-s.minY)}),o.has("bottom")&&a.push({id:"bottom",distance:Math.abs(r.y-s.maxY)})),r.y>=s.minY&&r.y<=s.maxY&&(o.has("right")&&a.push({id:"right",distance:Math.abs(r.x-s.maxX)}),o.has("left")&&a.push({id:"left",distance:Math.abs(r.x-s.minX)}));const l=a.filter(e=>e.distance<=i).sort((e,t)=>e.distance-t.distance)[0];return l?{kind:"resize",id:l.id,point:e.clone(),bounds:new LI(e.x-i,e.y-i,2*i,2*i)}:null})(e,n,c,6/this.getCurrentCamera().z);if(t)return t}for(const u of d)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;return null}setBrushBox(e){this.transients.setBrushBox(e)}setBindingPreview(e){this.transients.setBindingPreview(e)}setTerminalBindingGuides(e){this.transients.setTerminalBindingGuides(e)}setDropTargetShapeId(e){this.transients.setDropTargetShapeId(e)}setHoveredShapeId(e){this.transients.setHoveredShapeId(e)}setSelectionTranslationActive(e){this.transients.setSelectionTranslationActive(e)}setSnapIndicators(e){this.transients.setSnapIndicators(e)}setTerminalBindingResolver(e){this.transients.setTerminalBindingResolver(e)}resolveTerminalBinding(e){return this.transients.resolveTerminalBinding(e)}clearSelectionTransients(){this.transients.clearSelectionTransients()}hitTestShape(e){return this.hitTestShapesAtPoint(e)[0]??null}hitTestShapesAtPoint(e,t){return this.spatialIndex.getShapesAtPoint(e,{...t,filter:n=>!this.isShapeHidden(n.id)&&this.isPagePointInShapeClip(n.id,e)&&(t?.filter?.(n)??!0)})}hitTestShapesByLineSegment(e,t,n){return this.spatialIndex.getShapesHitByLineSegment(e,t,{...n,filter:e=>!this.isShapeHidden(e.id)&&(n?.filter?.(e)??!0)})}getShapeIdsInBounds(e,t){return this.spatialIndex.getShapeIdsInBounds(e,t).filter(e=>!this.isShapeHidden(e))}getShapesInBounds(e,t){return this.spatialIndex.getShapesInBounds(e,t).filter(e=>!this.isShapeHidden(e.id))}getShapesInViewport(e,t){return this.spatialIndex.getShapesInViewport(e,t).filter(e=>!this.isShapeHidden(e.id))}getDocumentSnapshot(){return this.snapshots.getDocumentSnapshot()}getSessionSnapshot(){return this.snapshots.getSessionSnapshot()}getSvgString(e=this.getSelectedShapeIds(),t){return function(e,t,n,i={}){const o=Array.from(t),r=e.getShapeExportTraversalIds(o),s=new Set(r),a=[],l=[];for(const w of r){const t=e.getShape(w);t?l.push(t):a.push({id:w,reason:"missing-shape"})}if(0===l.length)return null;const d=[];for(const w of l){if(!e.getShapeUtil(w).contributesToExportBounds(w))continue;const t=X(e,w,s);t&&(V(t)?d.push(t):a.push({id:w.id,reason:"missing-bounds"}))}if(0===d.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 LI(t,n,i-t,o-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=>D(e,i.resolveThemeColor)},p=[],g=[],f=new Map,m=[],y=(t,n)=>{const i=e.computeShapeExportToPageTransform(t),o=((e,t)=>{let n=t.opacity,i=t.parentId;const o=new Set([t.id]);for(;i.startsWith("shape:");){const t=i;if(o.has(t))break;o.add(t);const r=e.getShape(t);if(!r)break;n*=r.opacity,i=r.parentId}return n})(e,t),r=((e,t,n,i,o)=>{const r=[];for(const s of N(e,t,n)){const t=Y(e,s,i,o);t&&r.push(t)}return r})(e,t,s,f,h);let a={tag:"g",attrs:{transform:i.toSvgString(),opacity:1===o?void 0:o},children:[n]};for(let e=r.length-1;e>=0;e-=1)a={tag:"g",attrs:{"clip-path":`url(#${r[e]})`},children:[a]};g.push(a)},S=e=>{const t=n.get(e.type)?.toSvgForeground?.(e,h);t&&y(e,t)};for(const w of l){for(;m.length>0&&!O(e,m[m.length-1].id,w);)S(m.pop());const t=n.get(w.type);if(!t){a.push({id:w.id,reason:"missing-exporter"});continue}const i=t.toSvg(w,h);i?V(e.computeShapeExportBounds(w))?(p.push(w.id),y(w,i),t.toSvgForeground&&m.push(w)):a.push({id:w.id,reason:"missing-bounds"}):a.push({id:w.id,reason:"empty-output"})}for(;m.length>0;)S(m.pop());if(0===p.length)return null;const b=Math.max(1,c.w),x=Math.max(1,c.h),I=[];return u.length>0&&I.push({tag:"defs",children:u}),i.background&&I.push({tag:"rect",attrs:{x:c.x,y:c.y,width:c.w,height:c.h,fill:i.background}}),I.push(...g),{svg:K({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:b,height:x,viewBox:`${j(c.x)} ${j(c.y)} ${j(b)} ${j(x)}`},children:I}),bounds:c,width:b,height:x,requestedShapeIds:o,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),o=Z({editor:e,exporters:t,shapeIds:i});o.repairableIssueCount>0&&e.bindings.repairLoadedBindings("system");const r=Z({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,t={}){!1!==t.notifyInteractionHandlers&&this.interactions.broadcastEvent(this,{type:"cancel",reason:e}),this.tools.cancel(e),this.inputs.resetPointer(),this.clearSelectionTransients()}syncToolStateFromSession(e){const{activeToolId:t,isToolLocked:n}=this.sessionSignal.get();this.tools.hasTool(t)?this.tools.setActiveTool(t,"restore"):(this.tools.setActiveTool("select","restore"),this.updateSession({activeToolId:"select"},e)),this.tools.setToolLocked(n)}createShapeRecord(e){const t=e.parentId??this.sessionSignal.get().currentPageId;if(!this.canUseShapeParent(t))throw new Error("Invalid parent id for shape");const n=this.nextShapeNumber,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,skewX:e.skewX??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,opacity:e.opacity??1,isHidden:e.isHidden??!1,isLocked:e.isLocked??!1,props: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.getSessionRecord();this._internalStore.put([{...n,...e}],t)}setCurrentPage(e,t="system"){if(!this.getPage(e))return;e!==this.getCurrentPageId()&&(this.cancelInteractionAndClearTransients("page_switch"),this.completeEditing(t));const n=this.sessionSignal.get();this.updateSession({currentPageId:e,pageCameraById:{...n.pageCameraById,[e]:n.pageCameraById[e]??{...XI}},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]??{...XI},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(!f(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextShapeNumber=e+1}syncPageCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!p(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(!y(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextBindingNumber=e+1}syncAssetCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!S(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextAssetNumber=e+1}dispose(){this.runtime.dispose()}createPageId(e){const t=`page:${e}`;return this.nextPageNumber+=1,t}createPageIndex(e){return String(e).padStart(4,"0")}handleWheelEvent(e){if(e.ctrlKey){const t=this.getCurrentCamera(),n=e.delta.y,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)}},Rw=class{getPositionedBounds(e){const t=this.getLocalBounds(e);return new LI(t.x+e.x,t.y+e.y,t.w,t.h)}getRenderBounds(e){return this.getLocalBounds(e)}getPointHitTestBounds(e,t){return this.getPositionedBounds(e)}getExportBounds(e){return this.getRenderBounds(e)}getChildClipLocalBounds(e){return null}getChildClipLocalPolygons(e){const t=this.getChildClipLocalBounds(e);return t?[co(t)]:null}getChildExportClipLocalBounds(e){return this.getChildClipLocalBounds(e)}getChildExportClipLocalPolygons(e){const t=this.getChildExportClipLocalBounds(e);return t?[co(t)]:null}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=this.getSelectionResizeLocalBounds(e);if(0!==n.x||0!==n.y)throw new Error(`Shape util "${this.type}" must implement resizeSelectionBounds for non-origin local bounds`);const 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=ho(o,"w",t.selectionLocalBounds.w),s=ho(o,"h",t.selectionLocalBounds.h),a=si(yn({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}}getAllowedSelectionResizeModes(e,t){return hw}getSelectionResizeHandleIds(e,t){return cw}flipSelectionBounds(e,t){const n=this.getSelectionPagePoints(e);if(n){const i=n.map(e=>{const n=0===t.selectionRotation?e.clone():$I.RotWith(e,t.selectionRotationCenter,-t.selectionRotation),i=ci({axis:t.axis,bounds:t.selectionBounds,point:n});return 0===t.selectionRotation?i:$I.RotWith(i,t.selectionRotationCenter,t.selectionRotation)}),o=this.getSelectionPageMiddlePoint(e),r=o?(()=>{const e=0===t.selectionRotation?o.clone():$I.RotWith(o,t.selectionRotationCenter,-t.selectionRotation),n=ci({axis:t.axis,bounds:t.selectionBounds,point:e});return 0===t.selectionRotation?n:$I.RotWith(n,t.selectionRotationCenter,t.selectionRotation)})():void 0;return this.updateSelectionPagePoints(e,{pagePoints:[i[0],i[1]],pageMiddlePoint:r})}const i=this.getSelectionResizeLocalBounds(e),o=0===t.selectionRotation?t.selectionLocalBounds.center:$I.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}getSelectionPageMiddlePoint(e){return null}contributesToSelectionFrame(e,t){return!0}canParticipateInSelectionResize(e,t){return!0}canParticipateInSelectionRotation(e,t){return!0}canUseSelectionResizeHandles(e,t){return this.canParticipateInSelectionResize(e,t)}canUseSelectionRotateHandle(e,t){return this.canParticipateInSelectionRotation(e,t)}getSelectionTargetId(e,t){return e.id}getTranslateTargetId(e,t){return e.id}isSelectionTransformContainer(e){return!1}shouldRotateDescendants(e){return this.isSelectionTransformContainer(e)}shouldResizeDescendants(e){return!1}getResizeToFitDescendantsProps(e,t){return null}getMinimumChildCount(e){return 0}contributesToExportBounds(e){return!0}canUngroupChildren(e){return!1}getGroupingShapeCreateInput(e){return null}canStartTranslateFromSelectionBounds(e,t){return!0}canSnap(e){return!0}canSnapChildrenToSelf(e){return!1}getBoundsSnapGeometry(e){return{}}getHandleSnapGeometry(e){return{outline:co(this.getLocalBounds(e))}}getPositionedOutlineVertices(e){const t=this.getPositionedBounds(e);return[new $I(t.minX,t.minY),new $I(t.maxX,t.minY),new $I(t.maxX,t.maxY),new $I(t.minX,t.maxY)]}getSelectionFramePositionedOutlineVertices(e,t){return null}getSelectionHandleAnchors(e,t){return{terminalHandleAnchors:[],middleHandleAnchors:[]}}getSelectionOverlayInfo(e,t){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,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 FI.Translate(e.x+t.x,e.y+t.y).compose(FI.Rotate(e.rotation)).compose(FI.SkewX(e.skewX)).compose(FI.Scale(e.scaleX,e.scaleY)).compose(FI.Translate(-t.x,-t.y))}canEdit(e){return!1}canReceiveChildren(e){return!1}canReceiveChild(e,t){return this.canReceiveChildren(e)}isChildVisible(e,t,n){return!0}getChildPlacementMeta(e,t,n){return t.meta}canAutomaticallyReceiveChildren(e){return this.canReceiveChildren(e)}canBeDirectlyBrushSelected(e){return!0}canReceiveTerminalBinding(e,t){return!1}repairLoadedShape(e){return null}onEditEnd(e,t){}hitTest(e,t,n){return this.getPositionedBounds(e).containsPoint(t)}hitTestBindingTarget(e,t,n){return this.hitTest(e,t,n)}hitTestLineSegment(e,t){return((e,t,n)=>{if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=co(n);for(let o=0;o<i.length;o+=1){const n=i[o],r=i[(o+1)%i.length];if(n&&r&&null!==uo(e,t,n,r))return!0}return!1})(t.positionedStart,t.positionedEnd,this.getPositionedBounds(e).expand(t.positionedMargin))}resolveBindingPoint(e,t){this.getPositionedBounds(e);const n=t.editor.computeShapePositionedToPageTransform(e),i=n.tryInvert();if(!i)return t.rawPagePoint;const o=((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=uo(e,t,o,s);null===a||a<=1e-6||a>=i||(i=a)}return Number.isFinite(i)?e.add(o.mul(i)):null})(i.applyToPoint(t.rawPagePoint),i.applyToPoint(t.oppositePagePoint),this.getPositionedOutlineVertices(e));return o?n.applyToPoint(o):t.rawPagePoint}},$w=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)}},Lw=class extends $w{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new Fw(e,this)),this.addChild(new Dw(e,this))}},Fw=class extends $w{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",ao(this.editor,e.screenPoint))}},Dw=class extends $w{info=null;constructor(e,t){super(e,"panning",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&lo(this.editor,this.info,e.screenPoint)}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}onExit(){this.info=null}},Uw=Math.PI/180*15,zw=Math.PI/2,Ow=Math.PI/180*5,Xw="select.translate",Nw="select.resize",Yw="select.rotate",_w=class extends $w{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},Hw=class extends _w{onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&this.onDragThresholdExceeded(e)}},Ww=class extends _w{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=fo(this.editor,e,this.tickMode);t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){mo(this.editor,e=>this.apply(e))}},Kw=class extends _w{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,xo(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,bo(e),xo(e))}onTick(e){if(!this.info)return;const t=fo(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,bo(t),xo(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,bo(e),xo(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 LI(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).canBeDirectlyBrushSelected(n)})(e,o.id))&&e.getShapeUtil(o).canSelectByBrush(o,{editor:e,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(){mo(this.editor,e=>this.updateBrush(e.pagePoint,bo(e),xo(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},Vw=class extends Ww{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(e){const t=this.info?.previousSelection;n(()=>{var e,n;t&&(e=t,n=this.editor.getSelectedShapeIds(),e.length!==n.length||!e.every((e,t)=>e===n[t]))&&this.editor.commands.setSelectedShapeIds(t,{source:"system"}),this.info&&(this.editor.clearSelectionTransients(),this.editor.history.bailToMark(this.info.session.historyMark))}),this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}onInfoExit(){this.info?.session.shouldClearBindingPreviewOnExit&&this.editor.setBindingPreview(null),this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey: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=this.info.session.handleSnapMode??"none",r=this.info.snapSnapshot,s=!i&&"none"!==o&&null!==r,a=s&&r?this.editor.snaps.snapHandle({mode:o,pagePoint:e,snapshot:r,threshold:8/this.editor.getCurrentCamera().z}):null;s||this.editor.snaps.clearIndicators();const l=a?.snappedPagePoint??e,d=this.info.session.update({editor:this.editor,pagePoint:l,accelKey:i,source:"user"}),c="string"==typeof d?d:d.status,u="string"==typeof d?l:d.finalPagePoint;!a||!u||u.dist2(a.snappedPagePoint)<=1e-6||this.editor.snaps.clearIndicators(),"stop"===c&&this.transition("idle")}complete(){this.info&&(this.editor.setSnapIndicators(null),this.editor.history.squashToMark(this.info.session.historyMark)),this.transition("idle")}},qw=class extends $w{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=bo(e),s=yo(this.editor,n,t),a=r?null:((e,t,n)=>{const i=new Set(n);for(const o of So(e,t))if(i.has(o.ancestorId))return o.ancestorId;return null})(this.editor,n,t),l=r?null:a?s:null,d=yo(this.editor,o,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:r,wasSelected:t.includes(s),fromSelectionBounds:!1,quickClickSelectionTargetId:l})}if(!bo(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:bo(e)})}},jw=class extends Hw{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:bo(e)})}onPointerUp(e){bo(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")}},Gw=class extends Hw{constructor(e,t){super(e,"pointing_resize_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");if(!this.editor.canResizeSelection())return void this.transition("idle");const t=this.editor.getSelectionResizeTargetShapes(),n=new Map(t.flatMap(e=>{const t=Nt(this.editor,e);return t?[[e.id,t]]:[]})),i=t.filter(e=>n.has(e.id));if(0===i.length)return void this.transition("idle");const o=((e,t,n,i)=>0===t.length?[]:mi(e,t,n,fi(e,t,i)))(this.editor,i,this.info.handleId,e.rotation);if(0===o.length)return void this.transition("idle");const r=(({shapes:e,selectionFrame:t,getShapeSelectionResizePageOutlineVertices:n,getShapeSelectionPagePoints:i,getShapeSelectionPageMiddlePoint:o,getShapePageRecord:r})=>{const s={rotation:t.rotation,rotationCenter:t.rotationCenter},a=[],l=[];for(const d of e){const e=r(d),t=i(e);t?l.push({shape:d,pageShape:e,startLocalPagePoint:ri(t[0],s),endLocalPagePoint:ri(t[1],s),middleLocalPagePoint:(()=>{const t=o(e);return t?ri(t,s):null})()}):a.push({shape:d,pageShape:e,localBounds:LI.FromPoints(n(d).map(e=>ri(e,s))),rotation:e.rotation})}return{startBounds:t.bounds.clone(),rotation:t.rotation,rotationCenter:t.rotationCenter.clone(),aspectRatio:0===t.bounds.h?1:t.bounds.w/t.bounds.h,shapes:a,pointShapes:l}})({shapes:i,selectionFrame:e,getShapeSelectionResizePageOutlineVertices:e=>function(e,t){const n=e.getShapeUtil(t).getSelectionResizeLocalBounds(t),i=e.computeShapeLocalToPageTransform(t);return(e=>[new $I(e.minX,e.minY),new $I(e.maxX,e.minY),new $I(e.maxX,e.maxY),new $I(e.minX,e.maxY)])(n).map(e=>i.applyToPoint(e))}(this.editor,e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.getShapeUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>n.get(e.id)});var s,a;this.transition("resizing",{...this.info,startBounds:r.startBounds,rotation:r.rotation,rotationCenter:r.rotationCenter,aspectRatio:r.aspectRatio,snapSnapshot:this.editor.snaps.createResizeSnapshot({resizingShapeIds:this.editor.getShapeIdsForSelectionTransform(this.editor.getSelectedShapeIds()),coordinateSpace:{rotation:r.rotation,rotationCenter:r.rotationCenter}}),shapes:r.shapes,pointShapes:r.pointShapes,updates:(s=r.shapes,a=r.pointShapes,[...s.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,skewX:e.shape.skewX,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...a.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,skewX:e.shape.skewX,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),allowedResizeModes:o,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},Zw=class extends Hw{constructor(e,t){super(e,"pointing_rotate_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");if(!this.editor.canRotateSelection())return void this.transition("idle");const t=new Map(this.editor.getSelectionRotationTargetShapes().flatMap(e=>{const t=Nt(this.editor,e);return t?[[e.id,t]]:[]})),n=this.editor.getSelectionRotationTargetShapes().filter(e=>t.has(e.id));if(0===n.length)return void this.transition("idle");const i=(({shapes:e,selectionFrame:t,getShapeLocalBounds:n,getShapeSelectionPagePoints:i,getShapeSelectionPageMiddlePoint:o,getShapePageRecord:r})=>{const s=[],a=[];for(const l of e){const e=r(l),t=i(e);t?a.push({shape:l,pageShape:e,startPagePoint:t[0],endPagePoint:t[1],middlePagePoint:o(e)}):s.push({shape:l,pageShape:e,localBounds:n(l),rotation:e.rotation})}return{center:t.rotationCenter.clone(),initialSelectionRotation:t.rotation,shapes:s,pointShapes:a}})({shapes:n,selectionFrame:e,getShapeLocalBounds:e=>this.editor.computeShapeLocalBounds(e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.getShapeUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>t.get(e.id)});var o,r;this.transition("rotating",{...this.info,center:i.center,startAngle:$I.Angle(i.center,this.info.originPagePoint),initialSelectionRotation:i.initialSelectionRotation,shapes:i.shapes,pointShapes:i.pointShapes,updates:(o=i.shapes,r=i.pointShapes,[...o.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,skewX:e.shape.skewX,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...r.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,skewX:e.shape.skewX,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),lastPointerX:NaN,lastPointerY:NaN,lastShiftKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},Qw=class extends Hw{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,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.info&&this.info.session.onClick?.({editor:this.editor,source:"user"}),this.transition("idle")}onCancel(e){this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}},Jw=class extends Hw{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)=>t.filter(t=>{const n=e.getShape(t);return!!n&&!e.isShapeOrAncestorLocked(n.id)&&!e.hasLockedDescendant(n.id)}).map(t=>e.getShape(t)).filter(e=>!!e).flatMap(t=>(t.parentId.startsWith("shape:")?e.computeShapeLocalToPageTransform(e.getShape(t.parentId)):FI.Identity()).tryInvert()?[{id:t.id,x:t.x,y:t.y,startLocalToPage:e.computeShapeLocalToPageTransform(t)}]:[]))(this.editor,t),o=i.map(e=>e.id),r=n?.hasCompatibleRotation?n.rotation:0,s=n?.rotationCenter.clone()??$I.Zero(),a=n?.hasCompatibleRotation?n.bounds.clone():this.editor.getSelectionPageBounds();var l;this.transition("translating",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,movingShapeIds:o,startBounds:a,snapSnapshot:this.editor.snaps.createTranslateSnapshot({movingShapeIds:o,coordinateSpace:{rotation:r,rotationCenter:s}}),snapRotation:r,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 bo(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")}},eP=class extends Ww{tickMode="apply_after_scroll_or_without_screen_point";constructor(e,t){super(e,"resizing",t)}getHistoryMark(){return Nw}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=vo(this.info.rotationCenter,this.info.rotation),r=ri(e.sub(this.info.cursorHandleOffset),o),s=((e,t)=>{const n=e.includes("free"),i=e.includes("aspect_ratio_locked");return n||i?n?i&&t?"aspect_ratio_locked":"free":"aspect_ratio_locked":null})(this.info.allowedResizeModes,t);if(!s)return;const a="aspect_ratio_locked"===s,l=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),l=un(t)||hn(t)?o*(un(t)?-2:2)/Math.max(1,e.w):1,d=pn(t)||gn(t)?r*(pn(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new LI(e.minX,i.y-a,e.w,2*a),scaleX:l,scaleY:d};case"left":case"right":return{bounds:new LI(i.x-s,e.minY,2*s,e.h),scaleX:l,scaleY:d};default:return{bounds:new LI(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,o=e.maxX,r=e.minY,s=e.maxY;let a=un(t)?i:o,l=un(t)?o:i,d=pn(t)?r:s,c=pn(t)?s:r;un(t)||hn(t)?a=n.x:(a=o,l=i),pn(t)||gn(t)?d=n.y:(d=s,c=r);const u=a-l,h=d-c,p=un(t)?l-a:u,g=pn(t)?c-d:h,f=un(t)||hn(t)?p/Math.max(1,e.w):1,m=pn(t)||gn(t)?g/Math.max(1,e.h):1;return{bounds:new LI(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?Sn({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:a,isResizingFromCenter:n,aspectRatio:this.info.aspectRatio}),d=!i&&this.info.snapSnapshot.points.length>0,c=d?this.editor.snaps.snapResize({handleId:this.info.handleId,initialSelectionBounds:this.info.startBounds,resizedSelectionBounds:l.bounds,scaleX:l.scaleX,scaleY:l.scaleY,snapshot:this.info.snapSnapshot,threshold:8/this.editor.getCurrentCamera().z,isAspectRatioLocked:a,isResizingFromCenter:n}):l;d||this.editor.snaps.clearIndicators();const u=this.info.shapes.length+this.info.pointShapes.length===1;for(let h=0;h<this.info.shapes.length;h+=1){const e=this.info.shapes[h],t=this.info.updates[h];e&&t&&Po(this.editor,e,this.info.startBounds,c.bounds,c.scaleX,c.scaleY,this.info.handleId,u,n,this.info.rotationCenter,this.info.rotation,t)}for(let h=0;h<this.info.pointShapes.length;h+=1){const e=this.info.pointShapes[h],t=this.info.updates[this.info.shapes.length+h];e&&t&&ko(this.editor,e,this.info.startBounds,0,c.scaleX,c.scaleY,this.info.handleId,n,this.info.rotationCenter,this.info.rotation,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.setSnapIndicators(null),this.editor.history.squashToMark(Nw),this.transition("idle")}cancel(){this.editor.setSnapIndicators(null),this.editor.history.bailToMark(Nw),this.transition("idle")}},tP=class extends Ww{tickMode="apply_after_scroll";constructor(e,t){super(e,"rotating",t)}getHistoryMark(){return Yw}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=Io($I.Angle(this.info.center,e)-this.info.startAngle);if(t)i=wo(i,Uw);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=wo(e,zw),n=Io(t-e);Math.abs(n)<=Ow&&(i=Io(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&&To(this.editor,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&&Mo(this.editor,e,this.info.center,i,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.history.squashToMark(Yw),this.transition("idle")}cancel(){this.editor.history.bailToMark(Yw),this.transition("idle")}},nP=class extends Ww{tickMode="always_apply";constructor(e,t){super(e,"translating",t)}getHistoryMark(){return Xw}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 $I(r,s):new $I(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];if(!t||!n)continue;const i=this.editor.getShape(t.id);if(!i)continue;const o=i.parentId.startsWith("shape:")?this.editor.getShape(i.parentId):null,a=(o?this.editor.computeShapeLocalToPageTransform(o):FI.Identity()).tryInvert();if(!a)continue;const l=de(a.compose(FI.Translate(r,s).compose(t.startLocalToPage)),this.editor.computeShapeLocalBounds(i),{preferredRotation:i.rotation,preferredScaleXSign:i.scaleX,preferredScaleYSign:i.scaleY});l&&Object.assign(n,l)}this.editor.commands.updateShapes(this.info.updates)}Ao(this.editor,this.info.movingShapeIds,e),((e,t,n)=>{const i=Bo(e,t,n);if(i===Eo(e,t))return void e.setDropTargetShapeId(null);const o=i?e.getShape(i):null;e.setDropTargetShapeId(o?.id??null)})(this.editor,this.info.movingShapeIds,e)}complete(e){this.info&&Ao(this.editor,this.info.movingShapeIds,e),this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.squashToMark(Xw),this.transition("idle")}cancel(){this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.bailToMark(Xw),this.transition("idle")}},iP=class extends $w{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new qw(e,this)),this.addChild(new jw(e,this)),this.addChild(new Kw(e,this)),this.addChild(new Jw(e,this)),this.addChild(new nP(e,this)),this.addChild(new Gw(e,this)),this.addChild(new eP(e,this)),this.addChild(new Zw(e,this)),this.addChild(new tP(e,this)),this.addChild(new Qw(e,this)),this.addChild(new Vw(e,this))}},oP=class{actions=new Map;registerAction(e){if(this.actions.has(e.id))throw new Error(`Duplicate canvas action id: ${e.id}.`);this.actions.set(e.id,e)}getAction(e){return this.actions.get(e)??null}},rP=class{contributions=new Map;contributionsByTarget=new Map;contributionIndexes=new Map;nextContributionIndex=0;registerContribution(e){if(this.contributions.has(e.id))throw new Error(`Duplicate context-menu contribution id: ${e.id}.`);this.contributions.set(e.id,e),this.contributionIndexes.has(e.id)||(this.contributionIndexes.set(e.id,this.nextContributionIndex),this.nextContributionIndex+=1),this.addToIndex(e)}getSections(e,t){return(e=>{const t=[],n=new Map;for(const 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)=>$o(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)=>$o(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)}},sP="editor.tool.set-active-tool",aP="editor.tool.toggle-locked",lP=class{contributions=new Map;contributionsBySurface=new Map;contributionsBySurfaceAndPlacement=new Map;contributionIndexes=new Map;nextContributionIndex=0;stateRevision=0;registerContribution(e){if(this.contributions.has(e.id))throw new Error(`Duplicate toolbar contribution id: ${e.id}.`);this.contributions.set(e.id,e),this.contributionIndexes.has(e.id)||(this.contributionIndexes.set(e.id,this.nextContributionIndex),this.nextContributionIndex+=1),this.addToIndexes(e)}getStateRevision(){return this.stateRevision}subscribeToState(e,t){const n=()=>{this.stateRevision+=1,t()},i=[...this.contributions.values()].flatMap(t=>t.subscribe?[t.subscribe(e,n)]:[]);return this.stateRevision+=1,()=>{for(const e of i)e()}}getGroups(e,t,n={}){return(n.placement?this.contributionsBySurfaceAndPlacement.get(Fo(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){Uo(Do(this.contributionsBySurface,e.surface),e,this.contributionIndexes),Uo(Do(this.contributionsBySurfaceAndPlacement,Fo(e.surface,e.placement??"context")),e,this.contributionIndexes)}},dP=Ox(null),cP=class{registry=new Map;registeredPluginIds=new Set;shapeOpacityModifiers=[];shapeOpacityModifierIds=new Set;registerShapeRenderer(e){if(this.registry.has(e.type))throw new Error(`Duplicate shape renderer type: ${e.type}.`);this.registry.set(e.type,e)}getShapeRenderer(e){return this.registry.get(e)??null}hasShapeRenderer(e){return this.registry.has(e)}getRegisteredShapeTypes(){return[...this.registry.keys()]}registerCanvasRenderPlugins(e){for(const t of e){if(this.registeredPluginIds.has(t.id))throw new Error(`Duplicate canvas render plugin id: ${t.id}.`);for(const e of t.shapeRenderers??[])this.registerShapeRenderer(e);for(const e of t.shapeOpacityModifiers??[]){if(this.shapeOpacityModifierIds.has(e.id))throw new Error(`Duplicate shape opacity modifier id: ${e.id}.`);this.shapeOpacityModifiers.push(e),this.shapeOpacityModifierIds.add(e.id)}this.registeredPluginIds.add(t.id)}}getShapeOpacity(e,t){return this.shapeOpacityModifiers.reduce((n,i)=>n*i.getOpacity(e,t),1)}},uP=No(),hP=Ox(uP),pP=Xx(()=>{const e=zo();return((e,t,n)=>{const i=[],o=[],r=new Map(t.map(e=>[e.id,e]));for(const s of e){const e=r.get(s);if(e){for(;o.length>0&&!Ho(o[o.length-1],e,r);)i.push({layer:"foreground",shapeId:o.pop()});i.push({layer:"shape",shapeId:s}),n.getShapeRenderer(e.type)?.foregroundComponent&&o.push(s)}}for(;o.length>0;)i.push({layer:"foreground",shapeId:o.pop()});return i})(Oo(e.retainedShapeIdsSignal),Oo(e.currentPageShapeHierarchySignal),Yo()).map((e,t)=>"shape"===e.layer?Zx(fP,{shapeId:e.shapeId,stackingOrder:t},e.shapeId):Zx(mP,{shapeId:e.shapeId,stackingOrder:t},`${e.shapeId}:foreground`))}),gP=Xx(()=>{const e=zo(),t=Oo(e.currentPageShapeIdsSignal),n=Oo(e.retainedShapeIdsSignal),i=Oo(e.renderVisibleShapeIdsSignal),o=Oo(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),l=n.filter(e=>!r.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};
37
+ return Zx("pre",{"data-ui":"shape-layer-debug-summary","data-mounted-count":d.mountedCount,"data-visible-count":d.visibleCount,"data-hidden-retained-count":d.hiddenRetainedCount,"data-min-render-order":d.minRenderOrder??void 0,"data-max-render-order":d.maxRenderOrder??void 0,hidden:!0,children:JSON.stringify(d)})}),fP=Xx(({shapeId:e,stackingOrder:t})=>{const n=zo(),i=e,o=Oo(n.getShapeSignal(i)),r=Oo(n.getShapeLocalToPageTransformSignal(i)),s=Oo(n.getShapeHoveredSignal(i)),a=Oo(n.selectionCountSignal),l=Oo(n.brushBoxActiveSignal),d=Oo(n.getShapeRenderVisibleSignal(i)),c=Oo(n.toolStateSignal).activeToolId,u=Oo(n.getShapeSelectedSignal(i)),h="select"===c&&u,p=Oo(n.getShapeEditingSessionForShapeSignal(i)),g=Oo(n.getShapeRenderOrderSignal(i)),f=Oo(n.getShapeDropTargetSignal(i));Oo(n.runtime.revisionSignal);const m=Oo(n.getShapeEffectiveOpacitySignal(i)),y=Oo(n.getShapeSelectedDescendantTransformAncestorSignal(i)),S=Oo(n.getShapeClipAncestorIdsSignal(i)),b=Yo();if(!o||!r)return null;const x=b.getShapeRenderer(o.type);if(!x)return null;const I=x.component,w=s&&!(1===a&&h)&&!l,P=jo(n,o,r),v=m*b.getShapeOpacity(n,i);
38
+ return Qx("div",{"data-ui":"shape-instance","data-shape-id":o.id,"data-shape-type":o.type,"data-selected":h?"true":"false","data-hovered":w?"true":"false","data-drop-target":f?"true":"false","data-visible":d?"true":"false","data-render-order":g>=0?String(g):void 0,"data-clip-ancestor-count":S.length,style:{position:"absolute",display:d?void 0:"none",left:P.left,top:P.top,width:P.width,height:P.height,opacity:1===v?void 0:v,transform:P.transform,transformOrigin:P.transformOrigin,pointerEvents:"none",outline:f?"2px solid #2563eb":void 0,outlineOffset:f?4:void 0,boxShadow:f?"0 0 0 6px rgba(37, 99, 235, 0.16)":void 0,zIndex:t+1},children:[d?Zx(Vo,{clipAncestorIds:S,shapeElementToPage:P.elementToPage,children:Zx(I,{shape:o,editor:n,isSelected:h,isHovered:w,shapeEditingSession:p})}):null,d&&f?Zx(Ko,{}):null,d&&y?Zx(Wo,{}):null]})}),mP=Xx(({shapeId:e,stackingOrder:t})=>{const n=zo(),i=Oo(n.getShapeSignal(e)),o=Oo(n.getShapeLocalToPageTransformSignal(e)),r=Oo(n.getShapeRenderVisibleSignal(e)),s=Oo(n.getShapeHoveredSignal(e)),a=Oo(n.selectionCountSignal),l=Oo(n.getShapeSelectedSignal(e)),d=Oo(n.brushBoxActiveSignal);Oo(n.getShapeDropTargetSignal(e));const c=Oo(n.getShapeEditingSessionForShapeSignal(e));Oo(n.runtime.revisionSignal);const u=Oo(n.getShapeEffectiveOpacitySignal(e)),h=Oo(n.getShapeClipAncestorIdsSignal(e)),p=Yo();if(!i||!o)return null;const g=p.getShapeRenderer(i.type)?.foregroundComponent;if(!g)return null;const f=jo(n,i,o),m=u*p.getShapeOpacity(n,e);
39
+ return Zx("div",{"data-ui":"shape-foreground","data-owner-shape-id":i.id,"data-owner-shape-type":i.type,style:{position:"absolute",display:r?void 0:"none",left:f.left,top:f.top,width:f.width,height:f.height,opacity:1===m?void 0:m,transform:f.transform,transformOrigin:f.transformOrigin,pointerEvents:"none",zIndex:t+1},children:r?Zx(Vo,{clipAncestorIds:h,shapeElementToPage:f.elementToPage,children:Zx(g,{shape:i,editor:n,isSelected:l,isHovered:s&&!(1===a&&l)&&!d,shapeEditingSession:c})}):null})}),yP=class{selectionCustomHandleRenderers=new Map;canvasOverlays=new Map;registeredPluginIds=new Set;registerCanvasOverlay(e){if(this.canvasOverlays.has(e.id))throw new Error(`Duplicate canvas overlay id: ${e.id}.`);this.canvasOverlays.set(e.id,e)}getCanvasOverlay(e){return this.canvasOverlays.get(e)??null}hasCanvasOverlay(e){return this.canvasOverlays.has(e)}getCanvasOverlays(e){return[...this.canvasOverlays.values()].filter(t=>!e||(e=>e.layer??"above-host")(t)===e).sort(Jo)}getRegisteredCanvasOverlayIds(){return[...this.canvasOverlays.keys()]}registerSelectionCustomHandleRenderer(e){if(this.selectionCustomHandleRenderers.has(e.type))throw new Error(`Duplicate selection handle renderer type: ${e.type}.`);this.selectionCustomHandleRenderers.set(e.type,e)}getSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.get(e)??null}hasSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.has(e)}getRegisteredSelectionCustomHandleTypes(){return[...this.selectionCustomHandleRenderers.keys()]}registerCanvasRenderPlugins(e){for(const t of e){if(this.registeredPluginIds.has(t.id))throw new Error(`Duplicate canvas render plugin id: ${t.id}.`);for(const e of t.canvasOverlays??[])this.registerCanvasOverlay(e);for(const e of t.selectionCustomHandleRenderers??[])this.registerSelectionCustomHandleRenderer(e);this.registeredPluginIds.add(t.id)}}},SP=er(),bP=Ox(SP),xP="rgba(100, 116, 139, 0.82)",IP="rgba(255, 255, 255, 0.84)",wP=Xx(()=>Oo(zo().bindingPreviewActiveSignal)?Zx(PP,{}):null),PP=Xx(()=>{const e=zo(),t=Oo(e.bindingPreviewSignal),n=Oo(e.terminalBindingGuidesSignal);if(!t)return null;const i=n.some(e=>e.terminal===t.terminal&&e.targetShapeId===t.targetShapeId);
40
+ return Qx(Gx,{children:[Zx(vP,{targetShapeId:t.targetShapeId}),Zx(kP,{bindingPreview:t,showGuide:!i})]})}),vP=Xx(({targetShapeId:e})=>{const t=zo(),n=Oo(t.cameraZoomSignal),i=Oo(t.getShapeSignal(e));return i?Zx(rr,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),kP=Xx(({bindingPreview:e,showGuide:t})=>{const n=Oo(zo().cameraZoomSignal),i=2/n,o=6/n,r=4/n;
41
+ return Qx(Gx,{children:[t?e.guidePath?Zx(or,{path:e.guidePath,strokeWidth:i,dashSize:o,gapSize:r,kind:"binding-preview",terminal:e.terminal}):Zx(ir,{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,
42
+ Zx("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}),
43
+ Zx("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})]})}),CP=Xx(()=>Oo(zo().brushBoxActiveSignal)?Zx(TP,{}):null),TP=Xx(()=>{const e=Oo(zo().brushBoxSignal);return e?Zx("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}),MP=Xx(()=>{const e=zo(),t=Oo(e.selectionOverlayFrameGeometrySignal),n=Oo(e.selectionOverlayCompanionFrameGeometriesSignal);return t||0!==n.length?Qx(Gx,{children:[t?Zx(EP,{frameGeometry:t}):null,n.map((e,t)=>Zx(EP,{frameGeometry:e},`companion-${t}`))]}):null}),EP=Xx(({frameGeometry:e})=>{const t=Oo(zo().selectionOverlayFrameStyleSignal),{bounds:n,rotation:i,rotationCenter:o}=e,{cornerRadius:r,strokeWidth:s}=t,a=s/2,l=180*i/Math.PI;
44
+ return Zx("g",{transform:0===i?void 0:`rotate(${l} ${o.x} ${o.y})`,children:Zx("rect",{"data-selection-overlay":"bounds",x:n.x-a,y:n.y-a,width:n.w+s,height:n.h+s,rx:r+a,ry:r+a,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeWidth:s})})}),BP=new Set(uw),AP=Xx(()=>{const e=Oo(zo().selectionOverlayHandleAnchorsSignal);return e?Zx(RP,{anchors:e}):null}),RP=Xx(({})=>{const e=zo(),t=Oo(e.selectionOverlayHandlesSignal),n=Oo(e.selectionOverlayFrameGeometrySignal),i=tr(),o=Oo(e.cameraZoomSignal);if(!t)return null;const{resizeHandles:r,rotateHandles:s,strokeWidth:a,terminalHandles:l,middleHandles:d,customHandles:c}=t,u=r.filter(e=>BP.has(e.id)),h=r.filter(e=>!BP.has(e.id)),p=n?.rotation??0,g=180*p/Math.PI;
45
+ return Qx(Gx,{children:[n?Zx("g",{transform:n&&0!==p?`rotate(${g} ${n.rotationCenter.x} ${n.rotationCenter.y})`:void 0,children:h.map(e=>Zx(sr,{frame:n,handleId:e.id,zoom:o},e.id))}):null,u.map(e=>Zx("rect",{"data-selection-resize-handle":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2/o,ry:2/o,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,style:{cursor:ar(e.id,p),pointerEvents:"auto"}},e.id)),s.map(e=>Qx("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:[Zx("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),Zx("path",{d:"M21 3v5h-5"})]},e.id)),l.map(e=>Zx("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)),d.map(e=>Zx("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);
46
+ return Zx(t?t.component:lr,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),$P=["ew-resize","nwse-resize","ns-resize","nesw-resize"],LP=Xx(()=>{const e=zo(),t=Oo(e.selectionOverlayPathSignal),n=Oo(e.selectionOverlayBindingSegmentsSignal),i=Oo(e.selectionOverlayFrameStyleSignal);return t?Qx(Gx,{children:[
47
+ Zx(FP,{bindingSegments:n,strokeWidth:i.strokeWidth}),
48
+ Zx("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}),
49
+ Zx("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:i.strokeWidth})]}):null}),FP=Xx(({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;
50
+ return Zx(Gx,{children:e.map(e=>e.guidePath?Zx(or,{path:e.guidePath,strokeWidth:n,dashSize:i,gapSize:o,kind:t,terminal:e.terminal},e.terminal):Zx(ir,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:r,endInset:s,strokeWidth:n,dashSize:i,gapSize:o,kind:t,terminal:e.terminal},e.terminal))})}),DP=Xx(()=>Oo(zo().selectionTranslationActiveSignal)?null:Qx(Gx,{children:[
51
+ Zx(LP,{}),
52
+ Zx(MP,{}),
53
+ Zx(AP,{})]})),UP="rgba(37, 99, 235, 0.9)",zP=Xx(()=>{const e=Oo(zo().snapIndicatorsSignal);return 0===e.length?null:Zx(OP,{indicators:e})}),OP=Xx(({indicators:e})=>{const t=Oo(zo().cameraZoomSignal);
54
+ return Zx(Gx,{children:e.map(e=>Zx("points"===e.type?XP:NP,{indicator:e,zoom:t},e.id))})}),XP=Xx(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[o,r]=e.line,s=180*e.rotation/Math.PI;
55
+ return Qx("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${s} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[Zx("path",{"data-ui":"snap-indicator-line",d:`M ${o.x} ${o.y} L ${r.x} ${r.y}`,fill:"none",stroke:UP,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,o)=>Zx("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:UP,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${o}`))]})}),NP=Xx(({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=dr(i,[n?c.startEdge[0].y:c.startEdge[0].x,n?c.startEdge[1].y:c.startEdge[1].x]);e&&(i=e);const t=dr(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 l=180*e.rotation/Math.PI,d=0===e.rotation?void 0:`rotate(${l} ${e.rotationCenter.x} ${e.rotationCenter.y})`;
56
+ return Zx("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:d,fill:"none",stroke:UP,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),YP=Xx(()=>{const e=zo(),t=Oo(e.terminalBindingGuidesSignal),n=Oo(e.selectionOverlayFrameStyleSignal);return 0===t.length?null:Zx(FP,{bindingSegments:t,kind:"terminal-binding-guide",strokeWidth:n.strokeWidth})}),_P=Xx(()=>Qx("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
57
+ Zx("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 '}),
58
+ Zx(HP,{layer:"below-host"}),
59
+ Zx(zP,{}),
60
+ Zx(YP,{}),
61
+ Zx(wP,{}),
62
+ Zx(CP,{}),
63
+ Zx(DP,{}),
64
+ Zx(HP,{layer:"above-host"})]})),HP=Xx(({layer:e})=>{const t=tr().getCanvasOverlays(e);return 0===t.length?null:Zx(Gx,{children:t.map(({id:e,component:t})=>Zx(t,{},e))})}),WP=class{guards=[];registeredGuardIds=new Set;register(e){if(this.registeredGuardIds.has(e.id))throw new Error(`Duplicate DOM event guard id: ${e.id}.`);this.guards.push(e),this.registeredGuardIds.add(e.id)}registerCanvasRenderPlugins(e){for(const t of e)for(const e of t.domEventGuards??[])this.register(e)}getGuards(){return this.guards}handle(e){for(const t of this.guards)if("handled"===t.handle(e))return"handled";return"continue"}getCursor(e){for(const t of this.guards){const n=t.getCursor?.(e);if(void 0!==n)return n}}},KP="canvas-surface",VP=`[data-ui="${KP}"]`,qP=[{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}],jP=/[;{}<>\u0000-\u001f\u007f]/u,GP=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,ZP=/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|em|rem|%)?$/iu,QP="default",JP={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}},ev=new WeakMap,tv=new WeakMap,nv=14,iv=16,ov=20,rv=28,sv=16,av={[nv]:20,[iv]:24,[ov]:28,[rv]:36},lv=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))),Es(i,"whiteSpace",n?.whiteSpace),Es(i,"overflowWrap",n?.overflowWrap),Es(i,"lineHeight",n?.lineHeight),Es(i,"letterSpacing",n?.letterSpacing),Es(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=F(t.props.color),e.style.fontFamily=xs(t.props.font,n),e.style.fontSize=`${Is(t.props.size)}px`,e.style.lineHeight=`${ws(t.props.size)}px`,e.style.textAlign=vs(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})}},dv=new WeakMap,cv=/[;{}<>\u0000-\u001f\u007f]/u,uv=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,hv=oI.extend({inclusive:!1,renderHTML({HTMLAttributes:e}){const{href:t,target:n,rel:i,...o}=e;return["span",tI(o,{"data-rich-text-link-href":t,style:"text-decoration-line: underline;"}),0]}}),pv=[gI.configure({bold:!1,italic:!1,link:!1,strike:!1,underline:!1}),nI.extend({keepOnSplit:!0}),iI.extend({keepOnSplit:!0}),rI.extend({keepOnSplit:!0}),hI.extend({keepOnSplit:!0}),uI,aI,lI,dI,cI,sI.configure({types:["paragraph"],alignments:["left","center","right"]}),pI.configure({className:"land-rich-text-selection"}),hv.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})],gv=Ox(null),fv="var(--land-selection, #2563eb)",mv=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),yv={id:"land.text.dom-events",handle({event:e,name:t}){if(!mv.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},Sv="text.create",bv=class extends $w{constructor(e){super(e,"text"),this.initial="idle",this.addChild(new xv(e,this)),this.addChild(new Iv(e,this))}},xv=class extends $w{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("pointing",{originPagePoint:e.pagePoint.clone(),shapeId:null,didCreateShape:!1})}},Iv=class extends $w{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e,this.editor.history.mark(Sv)}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(!ds(t))return this.editor.history.bailToMark(Sv),void this.transition("idle");this.info.didCreateShape=!0,xe(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:Sv,reuseExistingMark:!0,preserveInteraction:!0},"user"),this.editor.isToolLocked()&&this.transition("idle")}onCancel(){this.info?.didCreateShape||this.editor.history.bailToMark(Sv),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:{...na(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:na(t)}))(e,this.getDefaultTextProps()))}createTextShapeAt({x:e,y:t,props:n}){const i=hs(this.editor,{x:e,y:t,props:n},"user");return this.editor.commands.setSelectedShapeIds([i.id],{source:"system"}),i}getDefaultTextProps(){return us(this.editor)}},wv="arrow-label",Pv="geo-label",vv={[wv]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!0,canUseSelectionResizeHandles:!1,canUseSelectionRotateHandle:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[Pv]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!1,canUseSelectionResizeHandles:!0,canUseSelectionRotateHandle:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}},kv=["start","middle","end"],Cv=class extends Rw{type="text";getDefaultProps(){return{richText:Er(""),w:16,h:Ps(sv),autoSize:!0,scale:1,font:QP,size:sv,color:M("text-slate"),textAlign:"start"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{richText:Ar(t.richText),w:Math.max(1,da(t.w,n.w)),h:Math.max(1,da(t.h,n.h)),autoSize:"boolean"==typeof t.autoSize?t.autoSize:n.autoSize,scale:Math.max(.01,da(t.scale,n.scale)),font:os(t.font)?t.font:n.font,size:bs(t.size,n.size),color:L(t.color,n.color),textAlign:(i=t.textAlign,"string"==typeof i&&kv.includes(i)?t.textAlign:n.textAlign)};var i}getPositionedBounds(e){return(e=>new LI(e.x,e.y,ua(e),ha(e)))(e)}getLocalBounds(e){return pa(e)}getRenderBounds(e){return pa(e)}getExportBounds(e){return pa(e)}canReceiveTerminalBinding(e){return!0}canEdit(e){return!0}contributesToSelectionFrame(e,t){return n=t.editor,i=e.id,aa(n,i)?.behavior.contributesToSelectionFrame??null??!0;var n,i}canUseSelectionResizeHandles(e,t){return n=t.editor,i=e.id,aa(n,i)?.behavior.canUseSelectionResizeHandles??null??!0;var n,i}canUseSelectionRotateHandle(e,t){return n=t.editor,i=e.id,aa(n,i)?.behavior.canUseSelectionRotateHandle??null??!0;var n,i}getSelectionTargetId(e,t){return((e,t)=>{const n=aa(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=aa(e,t);return n?"owner"===n.behavior.translateTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}resizeSelectionBounds(e,t){const n={};t.isOnlyResizeTarget&&ga(t.handleId)?(n.w=Math.max(16,t.selectionLocalBounds.w/ca(e)),n.autoSize=!1):n.scale=Math.max(.01,e.props.scale*((e,t)=>{const n=t.selectionLocalBounds.w/Math.max(1,ua(e)),i=t.selectionLocalBounds.h/Math.max(1,ha(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??ca(e),o=(n.w??e.props.w)*i,r=e.props.h*i,s=((e,t)=>0===t.selectionRotation?e.clone():$I.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(yn({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}}getAllowedSelectionResizeModes(e,t){return t.isOnlyResizeTarget&&ga(t.handleId)?pw:gw}onEditEnd(e){if(!(Br(e.props.richText).trim().length>0))return{deleteShapeIds:[e.id]}}},Tv=class{fontCatalog;type="text";constructor(e){this.fontCatalog=e}toSvg(e,t){return 0===Br(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:ya(e,t,this.fontCatalog)},children:fa(e.props.richText)}]}}},Mv=".label",Ev=class extends GI{type=wv;getDefaultProps(){return{labelPosition:.5}}validateProps(e){const t=this.getDefaultProps();return{labelPosition:ba((e&&"object"==typeof e?e:{}).labelPosition,t.labelPosition)}}canBind(e,t,n){return this.canUseShapeHierarchy(t,n)}canUseShapeHierarchy(e,t){return ds(t.fromShape)&&Sa(t.toShape)}getExclusiveBindingKey(e){return e.toId}onBindingCreate(e,t){return this.syncLabelPosition(e,t)}onBindingUpdate(e,t,n){return this.syncLabelPosition(e,n)}onBindingLoad(e,t){return this.syncLabelPosition(e,t)}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return this.syncLabelPosition(e,t)}onBeforeDeleteShape(e,t,n){return"from"===n.role?{deleteBindingIds:[t.id]}:{deleteShapeIds:[t.fromId],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){return{deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}getShapeHierarchyRootId(e,t){return t===e.fromId?e.toId:null}getSelectionCompanionFrameGeometries(e,t,n){if(t.toId!==n.selectedShape.id)return[];if(!0!==((e,t)=>aa(e,t)?.behavior.showsCompanionFrameWhenOwnerSelected??null)(e,t.fromId))return[];const i=e.getShape(t.fromId),o=e.getShape(t.toId);if(!ds(i)||!Sa(o))return[];const r=e.computeShapeGeometry(i),s=e.computeShapeLocalToPageTransform(i),a=Math.atan2(s.b,s.a);return[{bounds:LI.FromPoints(r.outlineVertices.map(e=>$I.RotWith(e,r.center,-a))),rotation:a,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(!ds(i)||!Sa(o))return{deleteBindingIds:[t.id]};const r=((e,t,n)=>{const i=xa(e,t,n),o=n.parentId,r=`${n.index}${Mv}`,s=!1,a="middle",l=oa(e,t,o,i);return l?t.x===l.x&&t.y===l.y&&t.rotation===l.rotation&&t.skewX===l.skewX&&t.scaleX===l.scaleX&&t.scaleY===l.scaleY&&t.parentId===o&&t.index===r&&t.props.w===i.props.w&&t.props.autoSize===s&&t.props.textAlign===a?null:{id:t.id,...l,parentId:o,index:r,props:{w:i.props.w,autoSize:s,textAlign:a}}:null})(e,i,o);return r?{shapes:[{...i,...r,props:{...i.props,...r.props}}]}:void 0}},Bv=".label",Av=class extends GI{type=Pv;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:va(i.x,t.normalizedAnchor.x),y:va(i.y,t.normalizedAnchor.y)},ownerBaseHeight:ka(n.ownerBaseHeight,t.ownerBaseHeight)}}canBind(e,t,n){return this.canUseShapeHierarchy(t,n)}canUseShapeHierarchy(e,t){return ds(t.fromShape)&&Pa(t.toShape)}getExclusiveBindingKey(e){return e.toId}onBindingCreate(e,t){return this.syncLabelPosition(e,t)}onBindingUpdate(e,t,n){return this.syncLabelPosition(e,n,t.toId===n.toId?void 0:{role:"to"})}onBindingLoad(e,t){return this.syncLabelPosition(e,t)}getGeometryDependentShapeIds(e,t,n){return"from"===n.role?[t.toId]:[t.fromId]}onAfterShapeChange(e,t,n){return this.syncLabelPosition(e,t,n)}onBeforeDeleteShape(e,t,n){if("from"===n.role){const n=e.getShape(t.toId),i=n?Ta(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?Ta(n,t):null;return{shapes:i?[i]:void 0,deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}getShapeHierarchyRootId(e,t){return t===e.fromId?e.toId:null}syncLabelPosition(e,t,n){if(i=t,"binding"!==i?.typeName||"geo-label"!==i.type)return;var i;const o=e.getShape(t.fromId),r=e.getShape(t.toId);if(!ds(o)||!Pa(r))return{deleteBindingIds:[t.id]};const s=((e,t,n)=>{const i=Ca(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}},l=function(e,t,n){const i=Ca(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),d=((e,t,n)=>{const i=Ma(e,t,n),o=n.parentId,r=`${n.index}${Bv}`,s=!1,a="middle",l=oa(e,t,o,i);return l?t.x===l.x&&t.y===l.y&&t.rotation===l.rotation&&t.skewX===l.skewX&&t.scaleX===l.scaleX&&t.scaleY===l.scaleY&&t.parentId===o&&t.index===r&&t.props.w===i.props.w&&t.props.autoSize===s&&t.props.textAlign===a?null:{id:t.id,...l,parentId:o,index:r,props:{w:i.props.w,autoSize:s,textAlign:a}}:null})(e,o,l??r),c=[];return l&&c.push(l),d&&c.push({...o,...d,props:{...o.props,...d.props}}),c.length>0||a?{shapes:c.length>0?c:void 0,bindings:a?[a]:void 0}:void 0}},Rv="text.edit",$v="arrow-label.edit",Lv="arrow-label.create",Fv="geo-label.edit",Dv="geo-label.create",Uv={bold:["bold","strong"],italic:["italic","em"],strike:["strike","s"],underline:["underline","u"]},zv=[{value:M("text-slate"),label:"Slate",id:"slate",hexColor:"#0f172a"},{value:M("text-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("text-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("text-red"),label:"Red",id:"red",hexColor:"#dc2626"}],Ov=[{id:"s",value:14,label:"S"},{id:"m",value:16,label:"M"},{id:"l",value:20,label:"L"},{id:"xl",value:28,label:"XL"}],Xv=[{value:"start",label:"Align left",icon:"align-left"},{value:"middle",label:"Align center",icon:"align-center"},{value:"end",label:"Align right",icon:"align-right"}],Nv=[{format:"bold",actionId:"text.toggle-bold",label:"Bold",icon:"bold",dataUi:"selected-text-bold-button"},{format:"italic",actionId:"text.toggle-italic",label:"Italic",icon:"italic",dataUi:"selected-text-italic-button"},{format:"underline",actionId:"text.toggle-underline",label:"Underline",icon:"underline",dataUi:"selected-text-underline-button"},{format:"strike",actionId:"text.toggle-strike",label:"Strikethrough",icon:"strikethrough",dataUi:"selected-text-strike-button"}],Yv="text.clear-formatting",_v="text.set-link",Hv=Va(),Wv=2*Math.PI,Kv=1e-9,Vv=new WeakMap,qv=d("plugin.packaging.runtime"),jv="land.packaging.artworkSide",Gv={lineWidth:.5,holeFill:E("#ffffff"),cutStroke:E("#a3a3a3"),creaseStroke:E("#a3a3a3"),bleedStroke:E("#b8b8b8"),safeZoneStroke:E("#b8b8b8"),annotationStroke:E("#d4d4d4"),canvasBoundsMarkColor:E("#d4d4d4")},Zv=new Set(["mm","cm","m","in","pt","px","unitless"]),Qv=new Set(["cut","crease","perforation","score","half-cut","kiss-cut","annotation","construction","custom"]),Jv=["outside","inside"],ek=1e-8,tk=new WeakSet,nk=Dl({schemaVersion:1,id:"packaging:empty",revision:"empty",name:"Packaging",unit:"unitless",coordinateSystem:"top-left-y-down",points:[],edges:[],faces:[],surfaces:{outside:{},inside:{}}}),ik=12,ok=1e-4,rk=new Set(["cut","half-cut","kiss-cut"]),sk=new Set(["crease","perforation","score"]),ak=new Set(["annotation","construction","custom"]),lk=new Set(["cut","half-cut","kiss-cut"]),dk=new Set(["crease","perforation","score"]),ck=new Set(["annotation","construction","custom"]),uk="packaging.toggle-show-bleed",hk="packaging.toggle-clip-to-bleed",pk="packaging.toggle-show-safe-zones",gk="packaging.toggle-dieline-on-top",fk="packaging.toggle-inside-view",mk="packaging.set-background",yk=[{id:"white",value:E("#f8fafc"),label:"White",hexColor:"#f8fafc"},{id:"warm",value:E("#fefce8"),label:"Warm",hexColor:"#fefce8"},{id:"blue",value:E("#eff6ff"),label:"Blue",hexColor:"#eff6ff"},{id:"green",value:E("#f0fdf4"),label:"Green",hexColor:"#f0fdf4"},{id:"slate",value:E("#e2e8f0"),label:"Slate",hexColor:"#e2e8f0"}],Sk={id:"packaging",editor:{id:"land.packaging",shapeCapabilities:[{type:"packaging",schemaProps:["document","viewSide","faceFill","faceFillOverrides","showBleed","clipToBleed","dielineOnTop","showSafeZones","showCanvasBoundsMarks"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Packaging is a parentId container with side-specific artwork visibility, document-derived faces, holes, dielines, bleed contours, optional bleed clipping, safe zones, point snap geometry, transient face hover, and configurable background/descendant/foreground render and SVG export order."]}],shapeUtils:[new class extends Rw{type="packaging";getDefaultProps(){return{document:nk,viewSide:"outside",faceFill:E("#f8fafc"),faceFillOverrides:Object.create(null),showBleed:!0,clipToBleed:!1,dielineOnTop:!0,showSafeZones:!1,showCanvasBoundsMarks:!0}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps(),i=Object.create(null);if(t.faceFillOverrides&&"object"==typeof t.faceFillOverrides&&!Array.isArray(t.faceFillOverrides))for(const[o,r]of Object.entries(t.faceFillOverrides))o.length>0&&R(r)&&(i[o]=r);return{document:Dl(t.document??n.document),viewSide:"inside"===t.viewSide||"outside"===t.viewSide?t.viewSide:n.viewSide,faceFill:L(t.faceFill,n.faceFill),faceFillOverrides:i,showBleed:"boolean"==typeof t.showBleed?t.showBleed:n.showBleed,clipToBleed:"boolean"==typeof t.clipToBleed?t.clipToBleed:n.clipToBleed,dielineOnTop:"boolean"==typeof t.dielineOnTop?t.dielineOnTop:n.dielineOnTop,showSafeZones:"boolean"==typeof t.showSafeZones?t.showSafeZones:n.showSafeZones,showCanvasBoundsMarks:"boolean"==typeof t.showCanvasBoundsMarks?t.showCanvasBoundsMarks:n.showCanvasBoundsMarks}}getLocalBounds(e){return yd(e).bounds}getRenderBounds(e){return md(e).expand(Gv.lineWidth/2)}getExportBounds(e){return this.getRenderBounds(e)}getChildClipLocalBounds(e){const t=this.getChildClipLocalPolygons(e);return t?LI.FromPoints(t.flatMap(e=>e)):null}getChildClipLocalPolygons(e){if(!e.props.clipToBleed)return null;const t=[...yd(e).bleedContoursById.values()].map(e=>e.samples).filter(e=>e.length>=3);return t.length>0?t:null}getChildExportClipLocalPolygons(e){return this.getChildClipLocalPolygons(e)}getPositionedOutlineVertices(e){const t=yd(e).bounds;return[new $I(e.x+t.minX,e.y+t.minY),new $I(e.x+t.maxX,e.y+t.minY),new $I(e.x+t.maxX,e.y+t.maxY),new $I(e.x+t.minX,e.y+t.maxY)]}getSelectionFramePositionedOutlineVertices(e){const t=yd(e).outerBounds.expand(Gv.lineWidth/2);return[new $I(e.x+t.minX,e.y+t.minY),new $I(e.x+t.maxX,e.y+t.minY),new $I(e.x+t.maxX,e.y+t.maxY),new $I(e.x+t.minX,e.y+t.maxY)]}getBoundsSnapGeometry(e){return{points:yd(e).snapPoints}}canReceiveChildren(e){return!0}canReceiveChild(e,t){return"frame"!==t.type&&"packaging"!==t.type}isChildVisible(e,t){return(Fl(t)??"outside")===e.props.viewSide}getChildPlacementMeta(e,t,n){const i=Fl(t);return"create"===n.reason&&i?t.meta:((e,t)=>Fl(e)===t?e.meta:{...e.meta,[jv]:t})(t,e.props.viewSide)}canSnapChildrenToSelf(e){return!0}shouldRotateDescendants(e){return!0}getAllowedSelectionResizeModes(e,t){return gw}canParticipateInSelectionRotation(e,t){return!1}resizeSelectionBounds(e,t){const n=this.getLocalBounds(e).center;return{id:e.id,x:t.pageCenter.x-n.x,y:t.pageCenter.y-n.y,rotation:t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,scaleX:e.scaleX*t.scaleX,scaleY:e.scaleY*t.scaleY}}canSelectByBrush(e,t){return t.isWrapping?this.isWrappedByBrush(e,t):this.doesBrushIntersectFace(e,t)}hitTest(e,t,n){const i=new $I(t.x-e.x,t.y-e.y);return!!Ja(yd(e),i)}hitTestLineSegment(e,t){return((e,t,n,i=0)=>{const o=Math.max(0,i)+.05,r=LI.FromPoints([t,n]).expand(o),s=o*o+Kv;for(const a of e.spatialIndex.searchBounds(r)){const i=e.facesById.get(a);if(i){if(el(t,i)||el(n,i))return!0;for(const e of[i.outer,...i.holes])for(let i=0;i<e.length;i+=1)if(Tl(t,n,e[i],e[(i+1)%e.length])<=s)return!0}}return!1})(yd(e),new $I(t.positionedStart.x-e.x,t.positionedStart.y-e.y),new $I(t.positionedEnd.x-e.x,t.positionedEnd.y-e.y),t.positionedMargin)}doesBrushIntersectFace(e,t){const n=t.editor.computeShapeLocalToPageTransform(e).tryInvert();if(!n)return!1;const i=[new $I(t.brushBounds.minX,t.brushBounds.minY),new $I(t.brushBounds.maxX,t.brushBounds.minY),new $I(t.brushBounds.maxX,t.brushBounds.maxY),new $I(t.brushBounds.minX,t.brushBounds.maxY)].map(e=>n.applyToPoint(e));return tl(yd(e),i).length>0}}],shapeSvgExporters:[new class{type="packaging";toSvg(e,t){const n=qa(e.props.document,e.props.viewSide),i=[...n.facesById.values()].map(n=>({tag:"path",attrs:{d:n.outerPath,fill:t.resolveColor(Sd(e,n.face.id)),stroke:"none","data-packaging-face-id":n.face.id}}));return e.props.dielineOnTop||i.push(...kd(n,t)),{tag:"g",attrs:{"data-packaging-layer":"background"},children:i}}toSvgForeground(e,t){const n=qa(e.props.document,e.props.viewSide),i=[];for(const r of n.facesById.values())for(const e of r.holePaths)i.push({tag:"path",attrs:{d:e,fill:t.resolveColor(Gv.holeFill),stroke:"none","data-packaging-hole-fill":!0}});const o=[...n.edgesById.values()].filter(e=>!1!==e.edge.visible);return e.props.showBleed&&n.bleedContoursById.size>0&&i.push({tag:"g",attrs:{"data-packaging-layer":"bleed-contours"},children:[...n.bleedContoursById.values()].map(e=>({tag:"path",attrs:{d:e.path,...Td(t,Gv.bleedStroke,Gv.lineWidth),"data-packaging-guide":"bleed","data-packaging-bleed-contour-id":e.source.id,"data-packaging-minimum-bleed":e.source.minimumBleed}}))}),e.props.showSafeZones&&n.safeZonesById.size>0&&i.push({tag:"g",attrs:{"data-packaging-layer":"safe-zones"},children:[...n.safeZonesById.values()].map(e=>({tag:"path",attrs:{d:e.path,...Td(t,Gv.safeZoneStroke,Gv.lineWidth),"stroke-dasharray":"1 3","stroke-linecap":"round","data-packaging-guide":"safe-zone","data-packaging-safe-zone-id":e.source.id,"data-packaging-face-id":e.source.faceId,"data-packaging-minimum-clearance":e.source.minimumClearance}}))}),e.props.dielineOnTop&&i.push(...kd(n,t,o)),{tag:"g",attrs:{"data-packaging-layer":"foreground","pointer-events":"none"},children:i}}}],interactionHandlers:[{id:"land.packaging.interactions",editorEvent:{handleEvent(e,t){const n=Ll(e);return"cancel"===t.type?(n.clear(),"continue"):"pointer"!==t.type?"continue":"pointer_cancel"===t.name?(n.clear(),"continue"):("pointer_move"!==t.name&&"pointer_down"!==t.name&&"pointer_up"!==t.name||n.setHover(((e,t)=>{const n=e.getCurrentPageShapeIds();for(let i=n.length-1;i>=0;i-=1){const o=e.getShape(n[i]);if(!vd(o)||e.isShapeHidden(o.id))continue;const r=e.computeShapeLocalToPageTransform(o).tryInvert();if(!r)continue;const s=r.applyToPoint(t.pagePoint),a=Ja(qa(o.props.document,o.props.viewSide),s);if(a)return{packagingShapeId:o.id,faceId:a.face.id}}return null})(e,t)),"continue")}}}],setup(e){const t=(()=>{const e=a("packaging.hover",null);return{hoverSignal:e,setHover(t){const n=e.get();n?.packagingShapeId===t?.packagingShapeId&&n?.faceId===t?.faceId||e.set(t?{...t}:null)},clear(){null!==e.get()&&e.set(null)}}})();return e.runtime.provide(qv,t,e=>e.clear()),e.listen(({diff:e})=>{const n=t.hoverSignal.get();n&&(e.removed.some(e=>e.id===n.packagingShapeId)||e.updated.some(({before:e,after:t})=>e.id===n.packagingShapeId||t.id===n.packagingShapeId))&&t.clear()})}},render:{id:"land.packaging.react",shapeRenderers:[{type:"packaging",component:function({shape:e,editor:t}){const n=qa(e.props.document,e.props.viewSide),i=md(e,n).expand(Gv.lineWidth/2),o=Oo(t.cameraZoomSignal),r=Id(Gv.lineWidth,o),s=[...n.edgesById.values()].filter(e=>!1!==e.edge.visible);
65
+ return Qx("svg",{"data-ui":"packaging-background",width:"100%",height:"100%",viewBox:Pd(i),style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:[[...n.facesById.values()].map(t=>Zx("path",{"data-packaging-face-id":t.face.id,d:t.outerPath,fill:F(Sd(e,t.face.id)),stroke:"none"},t.face.id)),e.props.dielineOnTop?null:bd(s,n.holeEdgeIds,r)]})},foregroundComponent:function({shape:e,editor:t}){const n=qa(e.props.document,e.props.viewSide),i=md(e,n).expand(Gv.lineWidth/2),o=Oo(t.cameraZoomSignal),r=Id(Gv.lineWidth,o),s=((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t),o=Math.max(Math.hypot(i.a,i.b),ok),r=Math.max(Math.hypot(i.c,i.d),ok),s=Math.max(n,ok);return{horizontalLength:ik/(o*s),verticalLength:ik/(r*s)}})(t,e,o),a=n.dielineBounds?n.outerBounds.expand(Gv.lineWidth/2):null,l=Oo(Ll(t).hoverSignal),d=Oo(t.getShapeDropTargetSignal(e.id)),c=l?.packagingShapeId===e.id?l.faceId:null,u=[...n.edgesById.values()].filter(e=>!1!==e.edge.visible);
66
+ return Zx("svg",{"data-ui":"packaging-foreground",width:"100%",height:"100%",viewBox:Pd(i),style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Qx("g",{pointerEvents:"none",children:[[...n.facesById.values()].flatMap(e=>e.holePaths.map((t,n)=>Zx("path",{"data-packaging-hole-fill":"true",d:t,fill:F(Gv.holeFill),stroke:"none"},`${e.face.id}:hole-fill:${n}`))),e.props.showBleed&&n.bleedContoursById.size>0?Zx("g",{"data-packaging-layer":"bleed-contours",children:[...n.bleedContoursById.values()].map(e=>Zx("path",{"data-packaging-guide":"bleed","data-packaging-bleed-contour-id":e.source.id,"data-packaging-minimum-bleed":e.source.minimumBleed,d:e.path,...wd(Gv.bleedStroke,r)},e.source.id))}):null,e.props.showSafeZones&&n.safeZonesById.size>0?Zx("g",{"data-packaging-layer":"safe-zones",children:[...n.safeZonesById.values()].map(e=>Zx("path",{"data-packaging-guide":"safe-zone","data-packaging-safe-zone-id":e.source.id,"data-packaging-face-id":e.source.faceId,"data-packaging-minimum-clearance":e.source.minimumClearance,d:e.path,...wd(Gv.safeZoneStroke,r),strokeDasharray:"1 3",strokeLinecap:"round"},e.source.id))}):null,e.props.dielineOnTop?bd(u,n.holeEdgeIds,r):null,e.props.showCanvasBoundsMarks?Zx("g",{"data-packaging-layer":"canvas-bounds-marks",children:nl(a,s).map((e,t)=>Zx("path",{"data-packaging-canvas-bounds-mark":"true",d:e,...wd(Gv.canvasBoundsMarkColor,r),strokeLinecap:"butt",strokeLinejoin:"miter"},`canvas-bounds-mark:${t}`))}):null,c?(()=>{const e=n.facesById.get(c);return e?Zx("path",{"data-packaging-face-hover":c,d:e.outerPath,fill:"rgba(37, 99, 235, 0.14)",stroke:"none"}):null})():null,d?Zx("path",{"data-packaging-drop-highlight":"true",d:[...n.facesById.values()].map(e=>e.outerPath).join(" "),fill:"rgba(37, 99, 235, 0.1)",stroke:"rgba(37, 99, 235, 0.96)",strokeWidth:Id(2,o),vectorEffect:"non-scaling-stroke"}):null]})})}}]},product:()=>({actions:[Md(uk,"showBleed"),Md(hk,"clipToBleed"),Md(pk,"showSafeZones"),Md(gk,"dielineOnTop"),{id:fk,isVisible:e=>"packaging"===e.selection.commonShapeType,isEnabled:e=>e.selection.selectedShapes.some(e=>Rd(e)&&!e.isLocked),getValue:e=>Bd(e.selection.selectedShapes),run({context:e,value:t}){const n=("boolean"==typeof t?t:!0!==Bd(e.selection.selectedShapes))?"inside":"outside",i=e.selection.selectedShapes.filter(Rd).filter(e=>!e.isLocked&&e.props.viewSide!==n).map(e=>({id:e.id,scaleX:-e.scaleX,props:{viewSide:n}}));i.length>0&&e.editor.commands.updateShapes(i,{source:"user"})}},{id:mk,isVisible:e=>"packaging"===e.selection.commonShapeType,isEnabled:e=>e.selection.selectedShapes.some(e=>Rd(e)&&!e.isLocked),getValue:e=>(e=>{let t;for(const n of e)if(Rd(n))if(void 0===t)t=n.props.faceFill;else if(!z(t,n.props.faceFill))return null;return t??null})(e.selection.selectedShapes),run({context:e,value:t}){const n=(e=>R(e)?L(e,E("#f8fafc")):"string"==typeof e&&/^#[0-9a-f]{6}$/i.test(e)?E(e):void 0)(t);if(!n)return;const i=e.selection.selectedShapes.filter(Rd).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{faceFill:n}}));i.length>0&&e.editor.commands.updateShapes(i,{source:"user"})}}],toolbarContributions:[{id:"packaging.selection-toolbar",surface:"selection",order:20,actionIds:[uk,hk,pk,gk,fk,mk],when:e=>"packaging"===e.selection.commonShapeType,getGroups:()=>[{id:"packaging.display",items:[{kind:"checkbox",id:uk,actionId:uk,label:"Show bleed lines",dataUi:"packaging-show-bleed-checkbox"},{kind:"checkbox",id:hk,actionId:hk,label:"Clip to bleed area",dataUi:"packaging-clip-to-bleed-checkbox"},{kind:"checkbox",id:pk,actionId:pk,label:"Show safe zones",dataUi:"packaging-show-safe-zones-checkbox"},{kind:"checkbox",id:gk,actionId:gk,label:"Dieline on top",dataUi:"packaging-dieline-on-top-checkbox"},{kind:"checkbox",id:fk,actionId:fk,label:"Inside view",dataUi:"packaging-inside-view-checkbox"}]},{id:"packaging.background",items:[{kind:"color-input",id:mk,actionId:mk,label:"Background",fallback:"#f8fafc",presets:yk.map(e=>({...e,dataUi:`packaging-background-${e.id}-button`})),dataUi:"packaging-background-color-input"}]}]}]})},bk=2*Math.PI,xk=1e-6,Ik=1e-6,wk=new Set(["LINE","ARC","CIRCLE","ELLIPSE","LWPOLYLINE","POLYLINE"]),Pk=72,vk={cut:{color:[0,1,0,0]},"half-cut":{color:[.45,1,0,0]},"kiss-cut":{color:[0,1,.75,0]},crease:{color:[1,0,0,0],dashArrayPoints:[6,2]},perforation:{color:[1,0,1,0],dashArrayPoints:[2,2]},score:{color:[1,.55,0,0],dashArrayPoints:[6,2]},annotation:{color:[0,0,0,.55],dashArrayPoints:[3,2]},construction:{color:[0,0,0,.3],dashArrayPoints:[2,2]},custom:{color:[0,0,0,.8]}},kk={color:[0,.9,.75,0],dashArrayPoints:[4,2]},Ck={color:[.75,0,.8,0],dashArrayPoints:[3,2]},Tk=Ox(null),Mk=Math.min,Ek=Math.max,Bk=Math.round,Ak=Math.floor,Rk=e=>({x:e,y:e}),$k={left:"right",right:"left",bottom:"top",top:"bottom"},Lk=["left","right"],Fk=["right","left"],Dk=["top","bottom"],Uk=["bottom","top"],zk=new Set(["left","top"]),Ok=/transform|translate|scale|rotate|perspective|filter/,Xk=/paint|layout|strict|content/,Nk=e=>!!e&&"none"!==e,Yk=Rk(0),_k={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:i,strategy:o}=e;const r="fixed"===o,s=Dc(i),a=!!t&&_c(t.floating);if(i===s||a&&r)return n;let l={scrollLeft:0,scrollTop:0},d=Rk(1);const c=Rk(0),u=Oc(i);if((u||!u&&!r)&&(("body"!==Lc(i)||Nc(s))&&(l=qc(i)),u)){const e=iu(i);d=tu(i),c.x=e.x+i.clientLeft,c.y=e.y+i.clientTop}const h=!s||u||r?Rk(0):ru(s,l);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+c.x+h.x,y:n.y*d.y-l.scrollTop*d.y+c.y+h.y}},getDocumentElement:Dc,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:i,strategy:o}=e;const r=[..."clippingAncestors"===n?_c(t)?[]:lu(t,this._c):[].concat(n),i],s=su(t,r[0],o);let a=s.top,l=s.right,d=s.bottom,c=s.left;for(let u=1;u<r.length;u++){const e=su(t,r[u],o);a=Ek(e.top,a),l=Mk(e.right,l),d=Mk(e.bottom,d),c=Ek(e.left,c)}return{width:l-c,height:d-a,x:c,y:a}},getOffsetParent:hu,getElementRects:async function(e){const t=this.getOffsetParent||hu,n=this.getDimensions,i=await n(e.floating);return{reference:du(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=Jc(e);return{width:t,height:n}},getScale:tu,isElement:zc,isRTL:e=>"rtl"===Vc(e).direction},Hk=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,i;const{x:o,y:r,placement:s,middlewareData:a}=t,l=await(async(e,t)=>{const{placement:n,platform:i,elements:o}=e,r=await(null==i.isRTL?void 0:i.isRTL(o.floating)),s=wc(n),a=Pc(n),l="y"===Cc(n),d=zk.has(s)?-1:1,c=r&&l?-1:1,u=Ic(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:g}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof g&&(p="end"===a?-1*g:g),l?{x:p*c,y:h*d}:{x:h*d,y:p*c}})(t,e);return s===(null==(n=a.offset)?void 0:n.placement)&&null!=(i=a.arrow)&&i.alignmentOffset?{}:{x:o+l.x,y:r+l.y,data:{...l,placement:s}}}}),Wk=e=>(void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:i,placement:o,platform:r}=t,{mainAxis:s=!0,crossAxis:a=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...d}=Ic(e,t),c={x:n,y:i},u=await r.detectOverflow(t,d),h=Cc(wc(o)),p=vc(h);let g=c[p],f=c[h];s&&(g=xc(g+u["y"===p?"top":"left"],g,g-u["y"===p?"bottom":"right"])),a&&(f=xc(f+u["y"===h?"top":"left"],f,f-u["y"===h?"bottom":"right"]));const m=l.fn({...t,[p]:g,[h]:f});return{...m,data:{x:m.x-n,y:m.y-i,enabled:{[p]:s,[h]:a}}}}}),Kk=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,i;const{placement:o,middlewareData:r,rects:s,initialPlacement:a,platform:l,elements:d}=t,{mainAxis:c=!0,crossAxis:u=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:f=!0,...m}=Ic(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const y=wc(o),S=Cc(a),b=wc(a)===a,x=await(null==l.isRTL?void 0:l.isRTL(d.floating)),I=h||(b||!f?[Ec(a)]:(e=>{const t=Ec(e);return[Mc(e),t,Mc(t)]})(a)),w="none"!==g;!h&&w&&I.push(...function(e,t,n,i){const o=Pc(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?Fk:Lk:t?Lk:Fk;case"left":case"right":return t?Dk:Uk;default:return[]}})(wc(e),"start"===n,i);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(Mc)))),r}(a,f,g,x));const P=[a,...I],v=await l.detectOverflow(t,m),k=[];let C=(null==(i=r.flip)?void 0:i.overflows)||[];if(c&&k.push(v[y]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const i=Pc(e),o=Tc(e),r=kc(o);let s="x"===o?i===(n?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[r]>t.floating[r]&&(s=Ec(s)),[s,Ec(s)]})(o,s,x);k.push(v[e[0]],v[e[1]])}if(C=[...C,{placement:o,overflows:k}],!k.every(e=>e<=0)){var T,M;const e=((null==(T=r.flip)?void 0:T.index)||0)+1,t=P[e];if(t&&("alignment"!==u||S===Cc(t)||C.every(e=>Cc(e.placement)!==S||e.overflows[0]>0)))return{data:{index:e,overflows:C},reset:{placement:t}};let n=null==(M=C.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:M.placement;if(!n)switch(p){case"bestFit":{var E;const e=null==(E=C.filter(e=>{if(w){const t=Cc(e.placement);return t===S||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:E[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),Vk=["bottom-start"],qk=["bottom"],jk=[],Gk=2*Math.PI,Zk="arrow.create",Qk=class extends $w{constructor(e){super(e,"arrow"),this.initial="idle",this.addChild(new Jk(e,this)),this.addChild(new eC(e,this))}},Jk=class extends $w{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})=>Ch(e,{terminal:t,rawPagePoint:n,oppositePagePoint:n.add(new $I(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})}},eC=class extends $w{info=null;constructor(e,t){super(e,"creating",t)}onEnter(e){if(this.info=e,!this.info)return;this.editor.history.mark(Zk);const t=vh(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=go(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(Zk),void this.transition("idle");xe(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(Zk),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})}else this.transition("idle")}onCancel(){this.editor.history.bailToMark(Zk),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=ju(n)?Th(this.editor,{arrow:n,terminal:"end",rawPagePoint:e,ignoreTargets:this.editor.inputs.state.get().accelKey}):Ch(this.editor,{terminal:"end",rawPagePoint:e,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey}),o=kh(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(ju(o)?o:null)}updateCreationBindingGuides(e){if(!e)return void this.editor.setTerminalBindingGuides(null);const t=new Map(this.editor.getBindingsFromShape(e.id).filter(Gu).map(e=>[e.props.terminal,e.toId])),n=Ju(this.editor,e).bindingSegments.map(n=>({...n,ownerShapeId:e.id,targetShapeId:t.get(n.terminal)??null}));this.editor.setTerminalBindingGuides(n)}},tC=[{value:M("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:M("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],nC=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],iC=[{value:"none",label:"None",icon:"minus"},{value:"arrow",label:"Arrow",icon:"arrow-right"}],oC={id:"arrow",editor:{id:"land.arrow",shapeCapabilities:[{type:"arrow",schemaProps:["w","h","start","end","bend","stroke","strokeWidth","headStart","headEnd"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Binding support lives in arrow binding records, not arrow props."]}],shapeUtils:[new class extends Rw{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,Ih(t.w,n.w)),h:Math.max(1,Ih(t.h,n.h)),start:xh(t.start,n.start),end:xh(t.end,n.end),bend:Ih(t.bend,n.bend),stroke:L(t.stroke,n.stroke),strokeWidth:Math.max(1,Ih(t.strokeWidth,n.strokeWidth)),headStart:"arrow"===t.headStart?"arrow":"none",headEnd:"none"===t.headEnd?"none":"arrow"}}getPositionedBounds(e){const t=Du(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}getPointHitTestBounds(e,t){const n=Math.max(8,e.props.strokeWidth+4);if(!t?.editor)return Du(e).bounds.expand(n);const i=Ju(t.editor,e).info,o=t.editor.computeShapePositionedToPageTransform(e).tryInvert();if(!o||0===i.points.length)return Du(e).bounds.expand(n);const r=n*Math.sqrt(o.a*o.a+o.b*o.b+o.c*o.c+o.d*o.d);return LI.FromPoints(i.points.map(e=>o.applyToPoint(e))).expand(r)}getLocalBounds(e){return new LI(0,0,e.props.w,e.props.h)}getExportBounds(e){const t=Uu(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}repairLoadedShape(e){return null}updateSelectionPagePoints(e,t){const n=this.getSelectionPageMiddlePoint(e);if(t.pageMiddlePoint&&n){const i=this.getSelectionPagePoints(e),o=((e,t)=>{const n=e[1].sub(e[0]),i=e[2].sub(e[0]),o=n.x*i.y-n.y*i.x;if(Math.abs(o)<1e-9)return null;const r=new FI(i.y/o,-n.y/o,-i.x/o,n.x/o,0,0),s=t[1].sub(t[0]),a=t[2].sub(t[0]),l=new FI(s.x,s.y,a.x,a.y,0,0).compose(r);return new FI(l.a,l.b,l.c,l.d,t[0].x-l.a*e[0].x-l.c*e[0].y,t[0].y-l.b*e[0].x-l.d*e[0].y)})([i[0],i[1],n],[t.pagePoints[0],t.pagePoints[1],t.pageMiddlePoint]);if(o){const t=de(o.compose(this.getLocalToPageTransform(e)),this.getLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY});if(t)return{id:e.id,...t}}}const i=((e,t,n)=>{const i=Fu(t,n);return{...e,x:i.x,y:i.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{...e.props,w:i.w,h:i.h,start:i.start,end:i.end,bend:e.props.bend}}})(e,t.pagePoints[0],t.pagePoints[1]);return{id:e.id,x:i.x,y:i.y,rotation:i.rotation,skewX:i.skewX,scaleX:i.scaleX,scaleY:i.scaleY,props:{w:i.props.w,h:i.props.h,start:i.props.start,end:i.props.end,bend:t.pageMiddlePoint?zu(t.pagePoints[0],t.pagePoints[1],t.pageMiddlePoint):i.props.bend}}}isWrappedByBrush(e,t){return t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}getSelectionPagePoints(e){return[Bu(e,"start"),Bu(e,"end")]}getSelectionPageMiddlePoint(e){return this.getLocalToPageTransform(e).applyToPoint(Uu(e).middle)}contributesToSelectionFrame(e,t){return t.editor.getSelectedShapeIds().length>1}canUseSelectionResizeHandles(e,t){return t.editor.getSelectedShapeIds().length>1}canUseSelectionRotateHandle(e,t){return t.editor.getSelectedShapeIds().length>1}canStartTranslateFromSelectionBounds(e,t){return t.editor.getSelectedShapeIds().length>1}getSelectionHandleAnchors(e,t){if(!t.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=Ju(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=Ju(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,Vu(t,e.points[i],e.points[i+1]));return Number.isFinite(n)?n:t.dist(e.start.point)})(n?.editor?Ju(n.editor,e).info:Du(e),n?.pagePoint??t)<=Math.max(8,e.props.strokeWidth+4)}hitTestLineSegment(e,t){const n=t.editor?Ju(t.editor,e).info:Du(e),i=Math.max(8,e.props.strokeWidth+4,t.editor?t.pageMargin:t.positionedMargin),o=t.editor?t.pageStart:t.positionedStart,r=t.editor?t.pageEnd:t.positionedEnd;if(1===n.points.length)return wh(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&&Ph(o,r,e,t)<=i)return!0}return!1}}],shapeSvgExporters:[new class{type="arrow";toSvg(e,t){const n=t.resolveColor(e.props.stroke),i="arrow"===e.props.headStart?`url(#${t.addDef(Lh("start",n))})`:void 0,o="arrow"===e.props.headEnd?`url(#${t.addDef(Lh("end",n))})`:void 0;return{tag:"path",attrs:{d:eh(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}}}}],bindingUtils:[new class extends GI{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,Sh(i.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,Sh(i.y,n.normalizedAnchor.y)))}}}canBind(e,t,n){return ju(n.fromShape)&&mh(e,n.toShape)}getExclusiveBindingKey(e){return`${e.fromId}:${e.props.terminal}`}onBindingCreate(e,t){return bh(this.syncArrowTerminal(e,t))}onBindingUpdate(e,t,n){return bh(this.syncArrowTerminal(e,n))}onBindingLoad(e,t){return bh(this.syncArrowTerminal(e,t))}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return bh(this.syncArrowTerminal(e,t))}onBeforeDeleteShape(e,t,n){if("from"===n.role)return{deleteBindingIds:[t.id]};const i=e.getShape(t.fromId);if(!ju(i))return{deleteBindingIds:[t.id]};const o=this.resolveTerminalPagePoint(e,t);return{shapes:[o?Lu(e,i,t.props.terminal,o)??i:i],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.fromId);if(!ju(n))return{deleteBindingIds:[t.id]};const i=this.resolveTerminalPagePoint(e,t);return{shapes:[i?Lu(e,n,t.props.terminal,i)??n:n],deleteBindingIds:[t.id]}}syncArrowTerminal(e,t){if(!Gu(t))return null;const n=e.getShape(t.fromId);if(!ju(n))return null;const i=this.resolveTerminalPagePoint(e,t);return i?Au(e,n,t.props.terminal).dist(i)<1e-6?null:Lu(e,n,t.props.terminal,i):null}resolveTerminalPagePoint(e,t){if(!Gu(t))return null;const n=e.getShape(t.fromId),i=e.getShape(t.toId);if(!ju(n)||!i||ju(i))return null;const o=Au(e,n,Ru(t.props.terminal)),r=Eu(e,i,t.props.normalizedAnchor,o);return ch(e,{arrow:n,terminal:t.props.terminal,target:i,anchorPagePoint:Mu(e,i,t.props.normalizedAnchor),fallbackBoundaryPagePoint:r}).boundaryPagePoint}}],interactionHandlers:[{id:"land.arrow.interactions",selectionHandle:{createSession:(e,{handle:t,shape:n})=>ju(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(!ju(s))return{status:"stop",finalPagePoint:null};const a=Th(e,{arrow:s,terminal:n,rawPagePoint:i,ignoreTargets:o}),l=kh(e,s.id,n,a,r);return{status:"continue",finalPagePoint:l?Au(e,l,n):a.pagePoint}}}))({handle:t,shapeId:n.id,terminal:t.terminal}):"binding_middle"===t.kind?(({shapeId:e})=>({shapeId:e,historyMark:"select.binding_middle_drag",update({editor:t,pagePoint:n,accelKey:i,source:o}){const r=t.getShape(e);if(!ju(r))return"stop";const s=((e,t)=>({start:Qu(e,t,"start").handlePagePoint,end:Qu(e,t,"end").handlePagePoint}))(t,r),a=zu(s.start,s.end,n),l=t.computeShapeLocalToPageTransform(r).tryInvert();if(!l)return"stop";const d=zu(l.applyToPoint(s.start),l.applyToPoint(s.end),l.applyToPoint(n)),c=0===(({bend:e,bypassSnap:t,zoom:n})=>t?e:Math.abs(e)*n<=6?0:e)({bend:a,bypassSnap:i,zoom:t.cameraZoomSignal.get()})?0:d;return t.commands.updateShapes([{id:r.id,props:{bend:c}}],{source:o}),"continue"}}))({shapeId:n.id}):null:null}}],setup(e){e.setTerminalBindingResolver(Ch),e.tools.register("arrow",e=>new Qk(e),{shortcut:"a"})}},render:{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:function({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=eh(t,e),l=Zs(e.props.stroke,n);
67
+ return Qx("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,overflow:"visible",children:[Qx("defs",{children:[Zx("marker",{id:r,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"2",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:Zx("path",{d:"M8.9,8 L2,12 L8.9,16",fill:"none",stroke:l,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),Zx("marker",{id:s,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"22",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:Zx("path",{d:"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:l,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),Zx("path",{d:a.path,fill:"none",stroke:l,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})]})}}]},product:()=>({actions:[Ah("stroke"),Ah("strokeWidth"),Ah("headStart"),Ah("headEnd"),Rh("stroke"),Rh("strokeWidth"),Rh("headStart"),Rh("headEnd")],toolbarContributions:[{id:"arrow.tool-toolbar",surface:"tool",placement:"chrome",order:40,actionIds:[sP],getGroups:e=>[{id:"arrow.tools",items:[{kind:"button",id:"arrow.tool.arrow",actionId:sP,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",placement:"floating",order:41,actionIds:["arrow.default-stroke","arrow.default-strokeWidth","arrow.default-headStart","arrow.default-headEnd"],when:e=>"arrow"===e.tool.activeToolId,getGroups:()=>Bh({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:()=>Bh({strokeActionId:"arrow.set-stroke",strokeWidthActionId:"arrow.set-strokeWidth",headStartActionId:"arrow.set-headStart",headEndActionId:"arrow.set-headEnd",dataUiPrefix:"arrow"})}]})},rC=.08,sC=new WeakMap,aC=new WeakMap,lC=new WeakMap,dC="draw.create",cC=class extends $w{constructor(e){super(e,"draw"),this.initial="idle",this.addChild(new uC(e,this)),this.addChild(new hC(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("draw")}},uC=class extends $w{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.parent.getDefaultProps(),n=((e,t)=>{const n=e.getCurrentPageId();let 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 l=e.getShapeUtil(n);if(!l.canAutomaticallyReceiveChildren(n))continue;if(!e.canUseShapeParent(n.id))continue;if(!e.isPagePointInShapeClip(n.id,t))continue;const d=l.getChildClipLocalBounds(n)??l.getLocalBounds(n),c=e.computeShapeLocalToPageTransform(n).invert().applyToPoint(t);if(!d.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})(this.editor,e.pagePoint),i=n.startsWith("shape:")?this.editor.getShape(n):null,o=i?this.editor.computeShapeLocalToPageTransform(i).invert():FI.Identity(),r=o.applyToPoint(e.pagePoint);var s,a;this.transition("drawing",{originPagePoint:e.pagePoint.clone(),originParentPoint:r,pageToParent:o,parentId:n,shapeId:null,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,isClosed:t.isClosed,isPen:"pen"===e.pointerType,pointGuard:(s=t.strokeWidth,a="pen"===e.pointerType,a?{minPointDistance:Math.max(.12,.08*s),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.3,.14*s),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[Mp(r,r,e.pressure,"pen"===e.pointerType)]}]})}},hC=class extends $w{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(dC)}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(dC),void this.transition("idle");this.info?.parentId.startsWith("shape:")||xe(this.editor,t,{source:"user"}),this.editor.history.squashToMark(dC),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.editor.history.bailToMark(dC),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.info=null}appendPoint(e,t){if(!this.info)return;const n=Mp(this.info.pageToParent.applyToPoint(e.pagePoint),this.info.originParentPoint,e.pressure,this.info.isPen);if(e.shiftKey?this.appendStraightSegmentPoint(n):(this.exitStraightSegmentMode(),this.info.preserveStraightEndpointOnNextFreePoint?this.appendDistinctCurrentPoint(n)&&(this.info.preserveStraightEndpointOnNextFreePoint=!1):this.appendGuardedCurrentPoint(n)),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:Rp(this.info.segments)}],{source:"user"})}createShape(){const e=this.tool.getDefaultProps(),t=((e,t)=>t&&e.canUseShapeParent(t)?t:e.getCurrentPageId())(this.editor,this.info?.parentId);this.info&&(this.info.parentId=t);const[n]=this.editor.commands.createShapes([{type:"draw",x:this.info?.originParentPoint.x??0,y:this.info?.originParentPoint.y??0,...t.startsWith("shape:")?{parentId:t}:{},props:{...e,stroke:this.info?.stroke??e.stroke,strokeWidth:this.info?.strokeWidth??e.strokeWidth,fill:this.info?.fill??e.fill,isClosed:this.info?.isClosed??e.isClosed,...Rp(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=Bp(this.info),n=t[t.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return void this.replaceCurrentSegmentPoints([{...e,segment:"straight"}]);this.info.straightSegmentAnchorPoint=Ep(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=Bp(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,Ep(e)]),0));var i,o}appendGuardedCurrentPoint(e){if(!this.info)return;const t=Bp(this.info).map(Ep);(function(e,t,n){const i=Xh(t),o=e[e.length-1];if(!o)return void e.push(i);if(zh(o,i))return;const r=((e,t)=>{if(e<=t.softMaxPointCount)return t.minPointDistance;const n=Dh((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,l=Math.abs((i.pressure??0)-(o.pressure??0));s*s+a*a<r*r&&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=Ap(this.info.segments);this.info.segments=[...t.slice(0,-1),{points:e.map(Ep)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const e=Uh(this.info.isPen);let t=Ap(this.info.segments),n=t[t.length-1];for(;n.points.length>e;){const i=n.points.slice(0,e).map(Ep),o=i[i.length-1],r=n.points.slice(e).map(Ep);if(!o||0===r.length)break;const s={points:[Ep(o),...r]};t=[...t.slice(0,-1),{points:i},s],n=s}this.info.segments=t}},pC=[{id:"slate",value:M("stroke-slate"),label:"Slate",hexColor:"#334155"},{id:"blue",value:M("stroke-blue"),label:"Blue",hexColor:"#1d4ed8"},{id:"green",value:M("stroke-green"),label:"Green",hexColor:"#15803d"},{id:"red",value:M("stroke-red"),label:"Red",hexColor:"#dc2626"},{id:"orange",value:M("stroke-orange"),label:"Orange",hexColor:"#ea580c"},{id:"muted",value:M("stroke-muted"),label:"Muted",hexColor:"#94a3b8"}],gC=[{id:"none",value:E("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:M("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:M("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:M("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:M("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],fC=[{value:4,label:"4"},{value:6,label:"6"},{value:8,label:"8"},{value:10,label:"10"}],mC=[{value:"open",label:"Open"},{value:"closed",label:"Closed"}],yC={id:"draw",editor:{id:"land.draw",shapeCapabilities:[{type:"draw",schemaProps:["segments","stroke","strokeWidth","fill","isClosed","isPen"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Draw stores raw segments as document truth and derives a shared freehand stroke geometry for render, hit test, brush wrap, and SVG export."]}],shapeUtils:[new class extends Rw{type="draw";getDefaultProps(){return{segments:(e=[{x:0,y:0},{x:24,y:12}],[{points:e.map(Xh)}]),stroke:M("stroke-slate"),strokeWidth:4,fill:E("transparent"),isClosed:!1,isPen:!1};var e}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{segments:Np(t.segments,n.segments),stroke:L(t.stroke,n.stroke),strokeWidth:Math.max(4,zp(t.strokeWidth,n.strokeWidth)),fill:L(t.fill,n.fill),isClosed:"boolean"==typeof t.isClosed?t.isClosed:n.isClosed,isPen:"boolean"==typeof t.isPen?t.isPen:n.isPen}}getPositionedBounds(e){const t=Pp(e);return new LI(e.x+t.localBounds.x,e.y+t.localBounds.y,t.localBounds.w,t.localBounds.h)}getLocalBounds(e){return Pp(e).localBounds}getRenderBounds(e){return Pp(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=Gh(e);for(let s=0;s<2;s+=1){const e=xp(r,t,n,i),s=wp(e.pointBounds,e.localBounds,o);r=np(r,e.pointBounds,s)}return r})({segments:op(Cp(e),t),strokeWidth:e.props.strokeWidth,isPen:e.props.isPen??!1,isClosed:e.props.isClosed,targetSelectionStrokeBounds:t.targetSelectionStrokeBounds});return t.scaleX<0&&(n=sp(n,{axis:"horizontal",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),t.scaleY<0&&(n=sp(n,{axis:"vertical",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),vp(rp(n,t),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed)}(e,{targetSelectionStrokeBounds:t.selectionLocalBounds,scaleX:t.scaleX,scaleY:t.scaleY,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter});return{id:e.id,x:n.x,y:n.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{segments:Tp(n.segments)}}}flipSelectionBounds(e,t){const n=((e,t)=>vp(rp(sp(op(Cp(e),t),t),t),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed))(e,{axis:t.axis,selectionMirrorBounds:t.selectionBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter});return{id:e.id,x:n.x,y:n.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{segments:Tp(n.segments)}}}getSelectionOverlayInfo(e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null}}isWrappedByBrush(e,t){return t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){if(this.isWrappedByBrush(e,t))return!0;if(t.isWrapping)return!1;const n=t.pageOutlineVertices;return!!n.some(e=>t.brushBounds.containsPoint(e))||(e=>{const t=new $I(e.minX,e.minY),n=new $I(e.maxX,e.minY),i=new $I(e.maxX,e.maxY),o=new $I(e.minX,e.maxY);return[[t,n],[n,i],[i,o],[o,t]]})(t.brushBounds).some(([e,t])=>{for(let i=0;i<n.length;i+=1){const o=n[i],r=n[(i+1)%n.length];if(o&&r&&I(e,t,o,r))return!0}return!1})}getPositionedOutlineVertices(e){return kp(e).outlineVertices}hitTest(e,t){return function(e,t,n,i={}){if(i.isClosed&&void 0!==i.fill&&!U(i.fill)&&e.normalizedPoints.length>=3&&Fp(n,e.normalizedPoints.map(Oh)))return!0;if(i.isClosed&&((e,t)=>{if(0===t.length)return Number.POSITIVE_INFINITY;if(1===t.length)return e.dist(Oh(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,$p(e,Oh(o),Oh(r))))}return t.length>=3&&(n=Math.min(n,$p(e,Oh(t[t.length-1]),Oh(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(Fp(n,o))return!0;if(Dp(n,o)<=Math.max(4,.5*t))return!0}return!1}(kp(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&&!U(o.fill)&&e.normalizedPoints.length>=3&&Up(n,i,e.normalizedPoints.map(Oh),r))||0!==e.outlineVertices.length&&e.outlinePolygons.some(e=>Up(n,i,e,r))})(kp(e),e.props.strokeWidth,t.positionedStart,t.positionedEnd,{fill:e.props.fill,isClosed:e.props.isClosed,margin:t.positionedMargin})}repairLoadedShape(e){return null}}],shapeSvgExporters:[new class{type="draw";toSvg(e,t){const n=Pp(e);if(!n.path&&!n.selectionPath)return null;const i=[];return n.fillPath&&!U(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}}}],setup(e){e.tools.register("draw",e=>new cC(e),{shortcut:"p"})}},render:{id:"land.draw.react",shapeRenderers:[{type:"draw",component:function({shape:e,isHovered:t}){
68
+ return Zx(qp,{shape:e,isHovered:t})}}]},product:()=>({actions:[{id:"draw.set-closed",isVisible:e=>"draw"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>Wp(e.selection.selectedShapes),run({context:e,value:t}){const n=Kp(t);if(null===n)return;const i=e.selection.selectedShapes.filter(Yp).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{isClosed:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},_p("fill"),_p("stroke"),_p("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=Kp(t);null!==n&&e.editor.updateDefaultShapeProps("draw",{isClosed:n})}},Hp("fill"),Hp("stroke"),Hp("strokeWidth")],toolbarContributions:[{id:"draw.tool-toolbar",surface:"tool",placement:"chrome",order:45,actionIds:[sP],getGroups:e=>[{id:"draw.tools",items:[{kind:"button",id:"draw.tool.draw",actionId:sP,value:"draw",label:"Draw",shortcut:e.editor.shortcuts.getToolShortcutLabel("draw"),icon:"pencil",dataUi:"draw-tool-button"}]}]},{id:"draw.default-style.tool-toolbar",surface:"tool",placement:"floating",order:46,actionIds:["draw.default-stroke","draw.default-strokeWidth"],when:e=>"draw"===e.tool.activeToolId,getGroups:()=>(({strokeActionId:e,strokeWidthActionId:t,dataUiPrefix:n})=>[{id:`${n}.initial-style`,items:[{kind:"color-input",id:`${n}.stroke`,actionId:e,label:"Stroke",fallback:"#334155",presets:pC.map(e=>({...e,dataUi:`${n}-stroke-${e.id}-button`})),dataUi:`${n}.stroke`},{kind:"separator",id:`${n}.initial-style-separator`},{kind:"text-input",id:`${n}.stroke-width`,actionId:t,label:"Stroke width",placeholder:"4",dataUi:`${n}-stroke-width-control`}]}])({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:()=>(({closedActionId:e,fillActionId:t,strokeActionId:n,strokeWidthActionId:i,dataUiPrefix:o})=>[{id:`${o}.style-closed`,items:[{kind:"segmented",id:`${o}.closed`,actionId:e,options:mC.map(e=>({...e,dataUi:`${o}-${e.value}-button`}))}]},{id:`${o}.style-fill`,items:[{kind:"color-input",id:`${o}.fill`,actionId:t,label:"Fill",fallback:"#f8fafc",presets:gC.map(e=>({...e,dataUi:`${o}-fill-${e.id}-button`})),dataUi:`${o}.fill`}]},{id:`${o}.style-stroke`,items:[{kind:"color-input",id:`${o}.stroke`,actionId:n,label:"Stroke",fallback:"#334155",presets:pC.map(e=>({...e,dataUi:`${o}-stroke-${e.id}-button`})),dataUi:`${o}.stroke`}]},{id:`${o}.style-stroke-width`,items:[{kind:"stepper",id:`${o}.stroke-width`,actionId:i,label:"Stroke width",dataUi:`${o}-stroke-width-control`,options:fC.map(e=>({...e,dataUi:`${o}-stroke-width-${e.value}-button`}))}]}])({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"===Wp(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"}]}]}}]})},SC=d("plugin.eraser.runtime"),bC=class extends $w{constructor(e){super(e,"eraser"),this.initial="idle",this.addChild(new xC(e,this)),this.addChild(new IC(e,this)),this.addChild(new wC(e,this))}onExit(){rg(this.editor)}},xC=class extends $w{constructor(e,t){super(e,"idle",t)}onEnter(){rg(this.editor)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={originPagePoint:t.pagePoint.clone(),previousPagePoint:t.pagePoint.clone(),protectedContainerIds:Qp(e,t.pagePoint),erasingShapeIds:new Set,trail:[t.pagePoint.clone()]};return tg(e,n,t),og(e,n),n})(this.editor,e))}},IC=class extends $w{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&&(ng(this.editor,this.info,e),ig(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),og(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(e){this.info&&(tg(this.editor,this.info,e),og(this.editor,this.info),sg(this.editor,this.info)),this.transition("idle")}onCancel(){rg(this.editor),this.transition("idle")}onExit(){this.info=null}},wC=class extends $w{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&&sg(this.editor,this.info),this.transition("idle")}onCancel(){rg(this.editor),this.transition("idle")}onExit(){this.info=null}update(e){this.info&&(ng(this.editor,this.info,e),ig(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),og(this.editor,this.info))}},PC=Xx(()=>Oo(jp(zo()).trailActiveSignal)?Zx(vC,{}):null),vC=Xx(()=>{const e=zo(),t=Oo(jp(e).trailSignal),n=Oo(e.cameraZoomSignal),i=Math.max(n,1e-4),o=(()=>{const[e,t]=qx(()=>ag());return _x(()=>{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=Vx({samples:[],sourceLength:0}),s=Math.max(o,ag());((e,t,n,i)=>{if(dg(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-RC*r;for(let a=o;a<t.length;a++){const l=t[a];lg(e,{x:l.x,y:l.y},n,xg(s,i,(a-o+1)/r))}e.sourceLength=t.length,dg(e,i)})(r.current,t,i,s);const a=function(e,t){const n=cg(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(bg(i[i.length-1],e[o],n));return i})(n.length>CC?n.slice(-48):n,EC)}(r.current.samples,s);if(0===a.length)return null;const l=(c=MC/i,0===(d=a).length||c<=0?null:1===d.length?Pg(hg(d[0],c/2,AC))??"":Pg((e=>{if(0===e.length)return[];if(1===e.length)return hg(e[0].point,Math.max(e[0].radius,.01),AC);const t=[],n=[];for(const a of e){const e=fg(a.direction);wg(t,yg(a.point,Sg(e,a.radius))),wg(n,mg(a.point,Sg(e,a.radius)))}const i=[];for(const a of t)wg(i,a);const o=e[e.length-1],r=fg(o.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const o=[];for(let r=1;r<BC;r++){const s=r/BC;o.push(mg(e,mg(Sg(t,Math.sin(Math.PI*s)*i),Sg(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)wg(i,a);for(let a=n.length-1;a>=0;a--)wg(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]+pg(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=Ig(s/i,0,1);return{point:o,direction:ug(e,r),radius:t/2*a,runningLength:s}})})(d,c))));var d,c;return l?Zx("g",{"data-ui":"eraser-trail-overlay",children:Zx("path",{"data-ui":"eraser-trail-scribble",d:l,fill:kC})}):null}),kC="rgba(142, 142, 142, 0.16)",CC=48,TC=1,MC=12,EC=.32,BC=8,AC=13,RC=16,$C=8,LC=180,FC=180,DC=680,UC={id:"eraser",editor:{id:"land.eraser",setup(e){e.runtime.provide(SC,(e=>{const t=a("eraser.shapeIds",[]),n=a("eraser.trail",[]);return{erasingShapeIdsSignal:t,trailSignal:n,trailActiveSignal:l("eraser.trailActive",()=>n.get().length>1),setPreview(i,o){t.set(Array.from(new Set(i))),n.set(o.map(e=>e.clone())),e.runtime.notify()},clear(){t.set([]),n.set([]),e.runtime.notify()}}})(e)),e.tools.register("eraser",e=>new bC(e),{shortcut:"e"})}},render:{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",layer:"below-host",component:PC}],shapeOpacityModifiers:[{id:"land.eraser.preview-opacity",getOpacity(e,t){const n=new Set(jp(e).erasingShapeIdsSignal.get());return e.hierarchy.isShapeOrAncestorInSet(t,n)?.32:1}}]},product:()=>({toolbarContributions:[{id:"eraser.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[sP],getGroups:e=>[{id:"eraser.tools",items:[{kind:"button",id:"eraser.tool.eraser",actionId:sP,value:"eraser",label:"Eraser",shortcut:e.editor.shortcuts.getToolShortcutLabel("eraser"),icon:"eraser",dataUi:"eraser-tool-button"}]}]}]})},zC="frame.create",OC=class extends $w{constructor(e){super(e,"frame"),this.initial="idle",this.addChild(new XC(e,this)),this.addChild(new NC(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("frame")}},XC=class extends $w{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})}},NC=class extends $w{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(zC)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.editor.history.squashToMark(zC),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(zC),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 LI(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 $I(e.x+o,e.y+r);return new LI(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",autoReparent:!1});if(!t||"frame"!==t.type)throw new Error("Failed to create frame shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},YC=[{id:"none",value:E("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:M("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:M("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:M("fill-amber"),label:"Amber",id:"amber",hexColor:"#fff7ed"}],_C=[{value:M("stroke-muted"),label:"Slate",id:"muted",hexColor:"#94a3b8"},{value:M("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("stroke-orange"),label:"Orange",id:"orange",hexColor:"#ea580c"}],HC=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],WC={id:"frame",editor:{id:"land.frame",shapeCapabilities:[{type:"frame",schemaProps:["w","h","name","fill","stroke","strokeWidth"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Frame renderer, SVG exporter, creation tool, selected-frame style toolbar, selected-child order badge, and minimal single-child sibling reorder controls live in the frame plugin package. ParentId-based child query, child-index ordering, containing-parent query, clipped query bounds, point-in-clip checks, host clipping, select-drag containment, export descendant traversal, and clipped child export have preflights. Richer hover/drag reorder UI remains deferred."]}],shapeUtils:[new class extends Rw{type="frame";getDefaultProps(){return{w:640,h:360,name:"Frame",fill:E("transparent"),stroke:M("stroke-muted"),strokeWidth:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,Tg(t.w,n.w)),h:Math.max(1,Tg(t.h,n.h)),name:"string"==typeof t.name&&t.name.length>0?t.name:n.name,fill:L(t.fill,n.fill),stroke:L(t.stroke,n.stroke),strokeWidth:Math.max(0,Tg(t.strokeWidth,n.strokeWidth))}}getLocalBounds(e){return new LI(0,0,e.props.w,e.props.h)}getPointHitTestBounds(e){return this.getPositionedBounds(e).expand(3)}canReceiveChildren(e){return!0}canSnapChildrenToSelf(e){return!0}canReceiveTerminalBinding(e){return!0}getSelectionResizeHandleIds(e,t){return uw}shouldRotateDescendants(e){return!0}getChildClipLocalBounds(e){return this.getLocalBounds(e)}canSelectByBrush(e,t){return super.isWrappedByBrush(e,t)}hitTest(e,t){return Mg(this.getPositionedBounds(e),t,6)}hitTestBindingTarget(e,t){return this.getPositionedBounds(e).containsPoint(t)}hitTestLineSegment(e,t){return((e,t,n,i)=>{const o=i/2;if(Mg(e,t,i)||Mg(e,n,i))return!0;const r=[new $I(e.minX,e.minY),new $I(e.maxX,e.minY),new $I(e.maxX,e.maxY),new $I(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&&w(t,n,e,i)<=o)return!0}return!1})(this.getPositionedBounds(e),t.positionedStart,t.positionedEnd,Math.max(6,t.positionedMargin))}}],shapeSvgExporters:[new class{type="frame";toSvg(e,t){const{fill:n,stroke:i,strokeWidth:o,w:r,h:s,name:a}=e.props,l=t.resolveColor(i),d=o/2;return{tag:"g",children:[{tag:"rect",attrs:{x:d,y:d,width:Math.max(r-o,0),height:Math.max(s-o,0),fill:t.resolveColor(n),stroke:l,"stroke-width":o,"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]}]}}}],setup(e){e.tools.register("frame",e=>new OC(e),{shortcut:"f"})}},render:{id:"land.frame.react",shapeRenderers:[{type:"frame",component:function({shape:e,isHovered:t}){
69
+ return Zx(Fg,{shape:e,isHovered:t})}}]},product:()=>({actions:[Eg("fill"),Eg("stroke"),Eg("strokeWidth"),Bg("fill"),Bg("stroke"),Bg("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"})}},Rg("backward"),Rg("forward")],toolbarContributions:[{id:"frame.tool-toolbar",surface:"tool",placement:"chrome",order:60,actionIds:[sP],getGroups:e=>[{id:"frame.tools",items:[{kind:"button",id:"frame.tool.frame",actionId:sP,value:"frame",label:"Frame",shortcut:e.editor.shortcuts.getToolShortcutLabel("frame"),icon:"frame",dataUi:"frame-tool-button"}]}]},{id:"frame.default-style.tool-toolbar",surface:"tool",placement:"floating",order:61,actionIds:["frame.default-fill","frame.default-stroke","frame.default-strokeWidth"],when:e=>"frame"===e.tool.activeToolId,getGroups:()=>Ag({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"}]}]:[],...Ag({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"===Lg(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"===Lg(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"}]}]}}]})},KC="geo.create",VC=class extends $w{geo;constructor(e,t,n){super(e,t),this.geo=n,this.initial="idle",this.addChild(new qC(e,this)),this.addChild(new jC(e,this))}getDefaultProps(){return{...this.editor.getDefaultShapeProps("geo"),geo:this.geo}}onEnter(){this.editor.updateDefaultShapeProps("geo",{geo:this.geo})}},qC=class extends $w{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})}},jC=class extends $w{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(KC)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.info.shapeId&&xe(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(KC),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(KC),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 LI(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 $I(e.x+i,e.y+o);return new LI(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",autoReparent:!1});if(!t)throw new Error("Failed to create geo shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},GC=class extends VC{constructor(e){super(e,"rectangle","rectangle")}},ZC=class extends VC{constructor(e){super(e,"ellipse","ellipse")}},QC=class extends VC{constructor(e){super(e,"diamond","diamond")}},JC=class extends VC{constructor(e){super(e,"triangle","triangle")}},eT=class extends VC{constructor(e){super(e,"hexagon","hexagon")}},tT=class extends VC{constructor(e){super(e,"star","star")}},nT=["rectangle","ellipse","diamond","triangle","hexagon","star"],iT=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],oT=[{value:M("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:M("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:M("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:M("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],rT=[{value:M("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:M("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],sT=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],aT=[{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"}],lT={id:"geo",editor:{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 class extends Rw{type="geo";getDefaultProps(){return{w:160,h:108,geo:"rectangle",fill:M("fill-slate"),stroke:M("stroke-slate"),strokeWidth:2,cornerRadiusPercent:12}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,Kg(t.w,n.w)),h:Math.max(24,Kg(t.h,n.h)),geo:Wg(t.geo)?t.geo:n.geo,fill:L(t.fill,n.fill),stroke:L(t.stroke,n.stroke),strokeWidth:Math.max(1,Kg(t.strokeWidth,n.strokeWidth)),cornerRadiusPercent:Ug(t.cornerRadiusPercent,n.cornerRadiusPercent)}}getLocalBounds(e){return new LI(0,0,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getPositionedOutlineVertices(e){return Dg(this.getPositionedBounds(e),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}getHandleSnapGeometry(e){return{points:Jg(e),outline:Qg(e)}}hitTest(e,t){const n=this.getPositionedBounds(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 Xg(t,Og(n,e.props.geo));default:return Xg(t,Og(n,"rectangle",{cornerRadiusPercent:e.props.cornerRadiusPercent}))}}hitTestLineSegment(e,t){const n=this.getPositionedBounds(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),l=t.sub(o),d=a.x/r,c=a.y/s,u=l.x/r,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 y=Math.sqrt(m),S=(-g-y)/(2*p),b=(-g+y)/(2*p);return S>=0&&S<=1||b>=0&&b<=1})(n,t.positionedStart,t.positionedEnd,t.positionedMargin);case"rectangle":case"diamond":case"triangle":case"hexagon":case"star":{const i=Og(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&&jg(e,t,r,s)<=i)return!0}return!1})(t.positionedStart,t.positionedEnd,i,t.positionedMargin)}default:return super.hitTestLineSegment(e,t)}}resolveBindingPoint(e,t){const n=t.editor.computeShapePositionedToPageTransform(e),i=n.tryInvert();if(!i)return t.rawPagePoint;const o=function(e,t,n){const i=new LI(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,l=s.y/o,d=r.x/i,c=r.y/o,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);case"rectangle":return Zg(t,n,Og(i,e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent}));default:return Zg(t,n,Og(i,e.props.geo))}}(e,i.applyToPoint(t.rawPagePoint),i.applyToPoint(t.oppositePagePoint));return o?n.applyToPoint(o):t.rawPagePoint}}],shapeSvgExporters:[new class{type="geo";toSvg(e,t){const{geo:n,fill:i,stroke:o,strokeWidth:r,w:s,h:a}=e.props,l=r/2,d=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:d/2,ry:c/2}};if("rectangle"!==n){const e=Og(new LI(l,l,d,c),n).map(e=>`${af(e.x)},${af(e.y)}`).join(" ");return{tag:"polygon",attrs:{...u,points:e}}}const h=zg({cornerRadiusPercent:e.props.cornerRadiusPercent,w:d,h:c});return{tag:"rect",attrs:{...u,x:l,y:l,width:d,height:c,rx:h,ry:h}}}}],setup(e){e.tools.register("rectangle",e=>new GC(e),{shortcut:"r"}),e.tools.register("ellipse",e=>new ZC(e),{shortcut:"o"}),e.tools.register("diamond",e=>new QC(e),{shortcut:"d"}),e.tools.register("triangle",e=>new JC(e)),e.tools.register("hexagon",e=>new eT(e)),e.tools.register("star",e=>new tT(e))}},render:{id:"land.geo.react",shapeRenderers:[{type:"geo",component:function({shape:e,isHovered:t}){
70
+ return Zx(lf,{shape:e,isHovered:t})}}]},product:()=>({actions:[{id:"geo.set-kind",isVisible:e=>"geo"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>of(e.selection.selectedShapes),run({context:e,value:t}){if(!Wg(t))return;const n=e.selection.selectedShapes.filter(Hg).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{geo:t}}));0!==n.length&&e.editor.commands.updateShapes(n,{source:"user"})}},ef("fill"),ef("stroke"),ef("strokeWidth"),{id:"geo.set-cornerRadiusPercent",isVisible:e=>"rectangle"===of(e.selection.selectedShapes),isEnabled:e=>e.selection.selectedShapes.some(e=>Hg(e)&&"rectangle"===e.props.geo&&!e.isLocked),getValue:e=>(e=>{let t;for(const n of e){if(!Hg(n)||"rectangle"!==n.props.geo)continue;const e=Ug(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=Ug(t),i=e.selection.selectedShapes.filter(Hg).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"})}},tf("fill"),tf("stroke"),tf("strokeWidth")],toolbarContributions:[{id:"geo.tool-toolbar",surface:"tool",placement:"chrome",order:20,actionIds:[sP],getGroups:e=>[{id:"geo.tools",items:[{kind:"segmented",id:"geo.tool-picker",actionId:sP,options:aT.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-tool-option`}))}]}]},{id:"geo.default-style.tool-toolbar",surface:"tool",placement:"floating",order:21,actionIds:["geo.default-fill","geo.default-stroke","geo.default-strokeWidth"],when:e=>sf(e.tool.activeToolId),getGroups:()=>nf({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=of(e.selection.selectedShapes);return[{id:"geo.shape-kind",items:[{kind:"segmented",id:"geo.shape-kind",actionId:"geo.set-kind",options:aT.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-shape-button`}))}]},...nf({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}}]})},dT="group.selection.group",cT="group.selection.ungroup",uT={id:dT,isVisible:e=>e.selection.count>0,isEnabled:e=>e.editor.canGroupSelection(),run({context:e}){e.editor.groupSelection("user")}},hT={id:cT,isVisible:e=>e.editor.canUngroupSelection(),isEnabled:e=>e.editor.canUngroupSelection(),run({context:e}){e.editor.ungroupSelection("user")}},pT={id:"group.selection-toolbar",surface:"selection",order:1010,actionIds:[dT,cT],getGroups:()=>[{id:"group.selection-actions",items:[{kind:"separator",id:"group.selection-leading-separator"},{kind:"button",id:dT,actionId:dT,label:"Group",icon:"group",dataUi:"group-selection-button"},{kind:"button",id:cT,actionId:cT,label:"Ungroup",icon:"ungroup",dataUi:"ungroup-selection-button"}]}]},gT={id:"group.selection-context-menu",target:"selection",order:1020,actionIds:[dT,cT],getSections:()=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"separator",id:"group.selection-separator"},{kind:"command",id:dT,actionId:dT,label:"Group",icon:"group",dataUi:"context-menu-group-selection-button"},{kind:"command",id:cT,actionId:cT,label:"Ungroup",icon:"ungroup",dataUi:"context-menu-ungroup-selection-button"}]}]},fT={id:"group",editor:{id:"land.group",shapeCapabilities:[{type:"group",schemaProps:["w","h"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Group is a transparent structural parent. The plugin supplies concrete record construction, bounds/hit policy, actions, and UI through ShapeUtil hooks; editor core owns generic hierarchy transactions and descendant-aware transforms."]}],shapeUtils:[new class extends Rw{type="group";getGroupingShapeCreateInput({parentId:e,parentLocalBounds:t}){return{type:this.type,x:t.x,y:t.y,parentId:e,props:{w:t.w,h:t.h}}}getDefaultProps(){return{w:1,h:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:df(t.w,n.w),h:df(t.h,n.h)}}getLocalBounds(e){return new LI(0,0,e.props.w,e.props.h)}hitTest(e,t){return!1}hitTestLineSegment(e,t){return!1}isSelectionTransformContainer(e){return!0}canUngroupChildren(e){return!0}shouldResizeDescendants(e){return!0}getResizeToFitDescendantsProps(e,t){return this.validateProps({...e.props,w:t.w,h:t.h})}getMinimumChildCount(e){return 2}contributesToExportBounds(e){return!1}canReceiveChildren(e){return!0}canAutomaticallyReceiveChildren(e){return!1}canBeDirectlyBrushSelected(e){return!1}}],shapeSvgExporters:[new class{type="group";toSvg(e){return{tag:"g"}}}]},render:{id:"land.group.react",shapeRenderers:[{type:"group",component:function({shape:e,isHovered:t,isSelected:n}){
71
+ return Zx(cf,{shape:e,isHovered:t,isSelected:n})}}]},product:()=>({actions:[uT,hT],actionShortcuts:[{actionId:dT,shortcut:{key:"g",accelKey:!0}},{actionId:cT,shortcut:{key:"g",accelKey:!0,shiftKey:!0}}],toolbarContributions:[pT],contextMenuContributions:[gT]})},mT="image.replace",yT="image.download-original",ST="image.insert",bT="image.crop",xT="image.crop.done",IT="image.crop.zoom",wT="image.crop.aspect-ratio",PT="image.crop.reset",vT="image.corner-radius",kT=1e-4,CT=1e-4,TT="image.crop",MT="image.crop.translate",ET="image.crop:edit:",BT=[{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}],AT={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"},RT=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],$T=new WeakMap,LT="image.smudge",FT="image.smudge.cancel",DT="image.smudge.confirm",UT="image.smudge.brush-size",zT="image.smudge.brush-color",OT="image.smudge:",XT=`${OT}edit:`,NT="#ffff00",YT=24,_T=NT,HT=.45,WT=class{editor;confirmHandler=null;deactivateHistoryScope=null;session=null;snapshot=null;subscribers=new Set;constructor(e){this.editor=e,Ro("image.smudgeSession.lifecycle",e.shapeEditingSessionSignal,()=>{this.clearIfEditingSessionInvalid()},{fireImmediately:!1})}start(e,t){if(e.isLocked)return!1;const n=Af(e.id),i=this.editor.getShapeEditingSession();if(i&&(i.shapeId!==e.id||i.markId!==n))return!1;if(this.session&&i?.shapeId===e.id&&Rf(e,i.markId))return this.updateSession({...this.session,brush:$f({...this.session.brush,...t})}),!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.setSession({shapeId:e.id,brush:$f(t),strokes:[],activeStroke:null,redoStrokes:[],nextStrokeIndex:1}),this.activateHistoryScope(e.id),0))}cancel(){const e=this.session?.shapeId??null;this.clear();const t=this.editor.getShapeEditingSession();e&&t?.shapeId===e&&t.markId===Af(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===Af(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=$f({...this.session.brush,...e});return t.size===this.session.brush.size&&t.color===this.session.brush.color&&t.opacity===this.session.brush.opacity||this.updateSession({...this.session,brush:t}),!0}getSnapshot(e){const t=this.getActiveSession();return t&&t.shapeId===e?this.snapshot:null}getActiveSession(){if(!this.session)return null;const e=this.editor.getShape(this.session.shapeId),t=this.editor.getShapeEditingSession();return e&&t&&t.shapeId===this.session.shapeId&&t.markId===Af(this.session.shapeId)?this.snapshot:(this.clear(),null)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}beginStroke(e){if(!this.session)return;const t=Ef(this.session),n={id:`${t.shapeId}:smudge:${t.nextStrokeIndex}`,points:[Xf(e)],brush:{...t.brush}};this.updateSession({...t,activeStroke:n,nextStrokeIndex:t.nextStrokeIndex+1})}appendPoint(e){if(!this.session?.activeStroke)return;const t=this.session.activeStroke.points[this.session.activeStroke.points.length-1];t&&Math.hypot(t.x-e.x,t.y-e.y)<.5||this.updateSession({...this.session,activeStroke:{...this.session.activeStroke,points:[...this.session.activeStroke.points,Xf(e)]}})}endStroke(){this.session?.activeStroke&&this.updateSession(Ef(this.session))}cancelStroke(){this.session?.activeStroke&&this.updateSession({...this.session,activeStroke:null})}undo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke&&this.updateSession(Ef(this.session)),!this.session||0===this.session.strokes.length)return!1;const e=this.session.strokes[this.session.strokes.length-1];return!!e&&(this.updateSession({...this.session,strokes:this.session.strokes.slice(0,-1),redoStrokes:[...this.session.redoStrokes,e]}),!0)}redo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke||0===this.session.redoStrokes.length)return!1;const e=this.session.redoStrokes[this.session.redoStrokes.length-1];return!!e&&(this.updateSession({...this.session,strokes:[...this.session.strokes,e],redoStrokes:this.session.redoStrokes.slice(0,-1)}),!0)}registerConfirmHandler(e){return this.confirmHandler=e,()=>{this.confirmHandler===e&&(this.confirmHandler=null)}}requestConfirm(e){return this.confirmHandler?this.confirmHandler(e):Promise.resolve(null)}clear(){this.session&&(this.session=null,this.snapshot=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}clearIfEditingSessionInvalid(){if(!this.session)return;const e=this.editor.getShapeEditingSession();e?.shapeId===this.session.shapeId&&e.markId===Af(this.session.shapeId)||this.clear()}activateHistoryScope(e){this.deactivateHistoryScope=this.editor.history.activateScope({id:`${OT}history:${e}`,getState:()=>this.getHistoryScopeState(),subscribe:e=>this.subscribe(e),undo:()=>this.undo(),redo:()=>this.redo()})}getHistoryScopeState(){const e=this.session?.activeStroke?1:0,t=this.session?.activeStroke?0:this.session?.redoStrokes.length??0;return{canUndo:(this.session?.strokes.length??0)+e>0,canRedo:t>0,undoDepth:(this.session?.strokes.length??0)+e,redoDepth:t}}setSession(e){this.session=e,this.snapshot=(e=>({shapeId:e.shapeId,brush:e.brush,strokes:e.activeStroke?[...e.strokes,e.activeStroke]:e.strokes,canUndo:e.strokes.length>0||!!e.activeStroke,canRedo:!e.activeStroke&&e.redoStrokes.length>0}))(e),this.notify()}updateSession(e){this.setSession(e)}notify(){for(const e of this.subscribers)e()}},KT=new WeakMap,VT=[{id:"smudge-yellow",label:"Yellow",hexColor:NT},{id:"smudge-orange",label:"Orange",hexColor:"#ff9900"},{id:"smudge-pink",label:"Pink",hexColor:"#ff4fd8"},{id:"smudge-green",label:"Green",hexColor:"#39ff14"},{id:"smudge-blue",label:"Blue",hexColor:"#00c8ff"},{id:"smudge-purple",label:"Purple",hexColor:"#b967ff"}],qT={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(!Yf(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Pf(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 $I(e.x-r.left,e.y-r.top);return hm(t,o,t.screenToPage(s))?0!==t.inputs.state.get().buttons?"grabbing":"grab":void 0}},jT={id:"land.image.smudge.dom-events",handle:()=>"continue",getCursor({clientPoint:e,container:t,editor:n}){const i=(e=>{const[t]=e.getSelectedShapes();if(!Yf(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Rf(t,n.markId)?t:null})(n);if(!i||!e)return;const o=t.getBoundingClientRect(),r=new $I(e.x-o.left,e.y-o.top);return hm(n,i,n.screenToPage(r))?"crosshair":0!==n.inputs.state.get().buttons?"grabbing":"grab"}},GT={id:"image",editor:{id:"land.image",shapeCapabilities:[{type:"image",schemaProps:["w","h","assetId","crop","cornerRadius","altText"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Image shape util, SVG exporter, and React renderer live in @land/plugin-image. Asset records store serializable metadata plus a local or remote source; File/Blob/object URL/download behavior stays in the web host."]}],shapeUtils:[new class extends Rw{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,Qf(t.w,n.w)),h:Math.max(24,Qf(t.h,n.h)),assetId:(i=t.assetId,"string"==typeof i&&i.startsWith("asset:")?t.assetId:null),crop:ff(t.crop),cornerRadius:Gf(t.cornerRadius,n.cornerRadius),altText:"string"==typeof t.altText?t.altText:n.altText};var i}getLocalBounds(e){return new LI(0,0,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getAllowedSelectionResizeModes(e,t){return gw}canEdit(e){return!0}onEditEnd(e,t){var n;n=e.id,Bf(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&&Pf(e,i.markId)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:kf({crop:e.props.crop,localToPage:t.editor.computeShapeLocalToPageTransform(e),shape:e})}:n}}],shapeSvgExporters:[new 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 l=mf(o),d=l?{tag:"svg",attrs:{x:0,y:0,width:s,height:r,viewBox:(c=l,[Tf(c.left),Tf(c.top),Tf(c.width),Tf(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=Zf({cornerRadius:e.props.cornerRadius,h:r,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:r,rx:u,ry:u}}]})})`},children:[d]}}}],interactionHandlers:[function(){let e=null;const t=()=>{e=null};return{id:"land.image.crop.interactions",editorEvent:{handleEvent(n,i){if("cancel"===i.type)return e?.hasDragged&&n.history.bailToMark(MT),t(),"continue";if("keyboard"===i.type)return((e,t)=>{if("key_down"!==t.name)return"continue";const n=qf(e);if(!n)return"continue";if("Escape"===t.key&&!t.altKey&&!t.accelKey)return e.cancelEditing("user")&&Mf(e,n.id),"handled";if("Enter"===t.key&&!t.altKey&&!t.accelKey)return e.completeEditing("user")&&Mf(e,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 $I(t,0);case"ArrowRight":return new $I(-t,0);case"ArrowUp":return new $I(0,t);case"ArrowDown":return new $I(0,-t);default:return null}})(t);if(i){const t=(({pageDelta:e,shape:t,startCrop:n})=>{const i=ff(n);return!i||e.equals($I.Zero())?null:Cf({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(MT),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=qf(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")?(Mf(n,o.id),n.dispatch(i),"handled"):"continue":"continue"}return e&&i.pointerId===e.pointerId?"pointer_move"===i.name?(jf(n,i,e),"handled"):"pointer_up"===i.name?(jf(n,i,e),e.hasDragged&&n.history.squashToMark(MT,"shape.edit"),t(),"handled"):"continue":"continue"}},selectionHandle:Vf()}}(),function(){let e=null;const t=t=>{e=null,(e=>{Bf(e).endStroke()})(t)},n=t=>{e=null,(e=>{Bf(e).cancelStroke()})(t)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(i,o){if("keyboard"===o.type)return(em(o)||Jf(o))&&tm(i)&&t(i),((e,t)=>"key_down"!==t.name?"continue":tm(e)?"Escape"!==t.key||t.altKey||t.accelKey?Jf(t)?(Of(e,{replace:!0}),"handled"):em(t)?(t.shiftKey?e.redo():e.undo(),"handled"):"handled":(Ff(e),"handled"):"continue")(i,o);if("cancel"===o.type)return tm(i)?(n(i),Ff(i),"handled"):"continue";if("pointer"!==o.type)return"continue";const r=tm(i);if(!r)return n(i),"continue";if("pointer_down"===o.name){if(t(i),0!==o.button)return 1===o.button?"continue":"handled";const n=im(i,r,o.pagePoint),s=om(n,r);return e={mode:s?"draw":"pan",originCamera:s?null:i.getCurrentCamera(),originScreenPoint:s?null:o.screenPoint.clone(),pointerId:o.pointerId,acceptsDrawPoints:s},s&&((e,t)=>{Bf(e).beginStroke(t)})(i,{x:n.x,y:n.y,pressure:o.pressure}),"handled"}return e&&e.pointerId===o.pointerId?"pointer_move"===o.name?("draw"===e.mode&&1&o.buttons?e.acceptsDrawPoints&&(e.acceptsDrawPoints=nm(i,r,o)):"pan"===e.mode&&e.originCamera&&e.originScreenPoint&&1&o.buttons?rm(i,o,e):t(i),"handled"):"pointer_up"===o.name?("draw"===e.mode&&e.acceptsDrawPoints?nm(i,r,o):"pan"===e.mode&&rm(i,o,e),t(i),"handled"):"pointer_cancel"===o.name?(n(i),"handled"):"handled":"handled"}}}}()],setup:e=>(e=>{let t=null;return Ro("image.cropSession.lifecycle",e.shapeEditingSessionSignal,()=>{const n=e.getShapeEditingSession(),i=n?.shapeId,o=i&&n?.markId===vf(i)?i:null;t&&t!==o&&Mf(e,t),t=o})})(e)},render:{id:"land.image.react",domEventGuards:[qT,jT],selectionCustomHandleRenderers:[{type:TT,component:function({handle:e,strokeWidth:t}){const{x:n,y:i,w:o,h:r,center:s}=e.bounds,a=1.35*Math.max(o,r),l=Math.max(2.5*t,2),d={fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeLinecap:"butt",strokeLinejoin:"miter",strokeWidth:l,pointerEvents:"none"},c=(({id:e,extension:t,outwardOffset:n,centerX:i,centerY:o})=>{switch(e){case"top_left":return{kind:"corner",points:[cm(i-n,o+t),cm(i-n,o-n),cm(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:[cm(i-t,o-n),cm(i+n,o-n),cm(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:[cm(i+n,o-t),cm(i+n,o+n),cm(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:[cm(i+t,o+n),cm(i-n,o+n),cm(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:l/2,centerX:s.x,centerY:s.y});
72
+ return Qx("g",{children:[Zx("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?Zx("polyline",{points:c.points,...d}):Zx("line",{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,...d})]})}}],shapeRenderers:[{type:"image",component:function({editor:e,isHovered:t,shape:n,shapeEditingSession:i}){const{altText:o,assetId:r,crop:s,h:a,w:l}=n.props,d=r?e.resolveAssetUrl(r):null,c=Zf({cornerRadius:n.props.cornerRadius,h:a,w:l}),u=((e,t)=>jx(t=>((e,t)=>Bf(e).subscribe(t))(e,t),()=>((e,t)=>Bf(e).getSnapshot(t))(e,t),()=>null))(e,n.id);if(!d)return Zx("div",{"data-ui":"image-shape-missing-asset",style:{alignItems:"center",background:"#f1f5f9",border:`1px solid ${t?fv:"#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 h=(({crop:e,shapeHeight:t,shapeWidth:n})=>{const i=mf(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:l});if(h){const e=i?.shapeId===n.id&&Pf(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};
73
+ return Qx("div",{"data-ui":"image-shape",style:{display:"block",height:a,overflow:e?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:l},children:[e?Zx("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:d,style:{...r,opacity:.1}}):null,
74
+ Qx("div",{"data-ui":"image-crop-window",style:{height:a,overflow:"hidden",position:"absolute",borderRadius:c,inset:0,width:l},children:[Zx("img",{alt:o,draggable:!1,src:d,style:r}),Zx(am,{shape:n,session:u})]}),
75
+ Zx(dm,{cornerRadius:c,isVisible:t})]})}
76
+ return Qx("div",{"data-ui":"image-shape",style:{borderRadius:c,display:"block",height:a,overflow:"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:l},children:[
77
+ Zx("img",{alt:o,draggable:!1,src:d,style:{display:"block",height:a,objectFit:"fill",width:l}}),
78
+ Zx(am,{shape:n,session:u}),
79
+ Zx(dm,{cornerRadius:c,isVisible:t})]})}}]},product:()=>({actions:[...Kf(),{id:LT,isVisible:e=>!!_f(e)&&!Hf(e)&&!Wf(e),isEnabled(e){const t=_f(e);return!!t&&!t.isLocked&&!!t.props.assetId},getValue:e=>Wf(e),run({context:e}){const t=_f(e);t&&!t.isLocked&&t.props.assetId&&Lf({editor:e.editor,shape:t})}},{id:UT,isVisible:e=>Wf(e),isEnabled:e=>Wf(e),getValue:e=>zf(e.editor)?.brush.size??24,run({context:e,value:t}){Uf(e.editor,{size:t})}},{id:zT,isVisible:e=>Wf(e),isEnabled:e=>Wf(e),getValue(e){const t=zf(e.editor)?.brush;return{color:t?.color??"#ffff00",opacity:t?.opacity??.45}},run({context:e,value:t}){Uf(e.editor,{color:t.color,opacity:t.opacity})}},{id:FT,isVisible:e=>Wf(e),isEnabled:e=>Wf(e),run({context:e}){Ff(e.editor)}},{id:DT,isVisible:e=>Wf(e),isEnabled:e=>Wf(e),run({context:e}){Of(e.editor,{replace:!0})}},{id:vT,isVisible:e=>"image"===e.selection.commonShapeType,isEnabled:e=>e.selection.selectedShapes.some(e=>Yf(e)&&!e.isLocked),getValue:e=>(e=>{let t;for(const n of e){if(!Yf(n))continue;const e=Gf(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)?Gf(n):null})(t);if(null===n)return;const i=e.selection.selectedShapes.filter(Yf).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:[ST],getGroups:()=>[{id:"image.tools",items:[{kind:"button",id:ST,actionId:ST,label:"Image",icon:"image-plus",dataUi:"insert-image-tool-button"}]}]},{id:"image.selection-toolbar",surface:"selection",order:30,actionIds:[bT,xT,IT,wT,PT,LT,zT,UT,FT,DT,vT,mT,yT],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups(e){const t=[];return Wf(e)?[{id:"image.smudge-color",order:5,items:[{kind:"color-input",id:zT,actionId:zT,label:"Brush color",fallback:NT,includeAlpha:!0,opacityFallback:.45,presets:VT,dataUi:"image-smudge-brush-color-input"}]},{id:"image.smudge-brush",order:10,items:[{kind:"slider",id:UT,actionId:UT,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:FT,actionId:FT,label:"Cancel smudge",icon:"x",dataUi:"cancel-image-smudge-button"},{kind:"button",id:DT,actionId:DT,label:"Confirm smudge",icon:"check",dataUi:"confirm-image-smudge-button"}]}]:(Hf(e)&&t.push({id:"image.crop-zoom",order:10,items:[{kind:"stepper",id:"image.crop.zoom-stepper",actionId:IT,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:wT,options:BT.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:PT,actionId:PT,label:"Reset crop",icon:"rotate-ccw",dataUi:"reset-image-crop-button"}]}),t.push((({dataUiPrefix:e,id:t,order:n})=>({id:t,order:n,items:[sm({dataUiPrefix:e})]}))({dataUiPrefix:"image",id:"image.style-corner-radius",order:35})),t.push({id:"image.asset",order:40,items:[{kind:"button",id:bT,actionId:bT,label:"Crop image",icon:"crop",dataUi:"crop-image-button"},{kind:"button",id:LT,actionId:LT,label:"Smudge image",icon:"pencil",dataUi:"smudge-image-button"},{kind:"button",id:xT,actionId:xT,label:"Done cropping",icon:"check",dataUi:"done-cropping-button"},{kind:"button",id:mT,actionId:mT,label:"Replace image",icon:"image-plus",dataUi:"replace-image-button"},{kind:"button",id:yT,actionId:yT,label:"Download original",icon:"download",dataUi:"download-image-original-button"}]}),t)}},{id:"image.floating-selection-toolbar",surface:"selection",placement:"floating",order:30,actionIds:[bT,xT,IT,wT,PT,LT,zT,UT,FT,DT,vT,mT,yT],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups:e=>Wf(e)?[{id:"image.floating-smudge-color",order:5,items:[{kind:"color-input",id:"image.floating-smudge.brush-color",actionId:zT,label:"Brush color",fallback:NT,includeAlpha:!0,opacityFallback:.45,presets:VT,dataUi:"floating-image-smudge-brush-color-input"}]},{id:"image.floating-smudge-brush",order:10,items:[{kind:"slider",id:"image.floating-smudge.brush-size",actionId:UT,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:FT,label:"Cancel smudge",icon:"x",dataUi:"floating-cancel-image-smudge-button"},{kind:"button",id:"image.floating-smudge.confirm",actionId:DT,label:"Confirm smudge",icon:"check",dataUi:"floating-confirm-image-smudge-button"}]}]:Hf(e)?[{id:"image.floating-crop-zoom",order:10,items:[{kind:"stepper",id:"image.floating-crop.zoom-stepper",actionId:IT,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:wT,options:BT.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:[sm({dataUiPrefix:"floating-image-crop"})]},{id:"image.floating-crop-actions",order:30,items:[{kind:"button",id:"image.floating-crop.done",actionId:xT,label:"Done cropping",icon:"check",dataUi:"floating-done-cropping-button"},{kind:"button",id:"image.floating-crop.reset",actionId:PT,label:"Reset crop",icon:"rotate-ccw",dataUi:"floating-reset-image-crop-button"}]}]:[{id:"image.floating-corner-radius",order:10,items:[sm({dataUiPrefix:"floating-image"})]},{id:"image.floating-asset",order:20,items:[{kind:"button",id:"image.floating.crop",actionId:bT,label:"Crop image",icon:"crop",dataUi:"floating-crop-image-button"},{kind:"button",id:"image.floating.smudge",actionId:LT,label:"Smudge image",icon:"pencil",dataUi:"floating-smudge-image-button"},{kind:"button",id:"image.floating.replace",actionId:mT,label:"Replace image",icon:"image-plus",dataUi:"floating-replace-image-button"},{kind:"button",id:"image.floating.download",actionId:yT,label:"Download original",icon:"download",dataUi:"floating-download-image-original-button"}]}]}],contextMenuContributions:[{id:"image.shape-context-menu",target:"selection",order:30,actionIds:[bT,LT,mT,yT],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getSections:()=>[{id:"image.asset-context-menu",title:"Image",items:[{kind:"command",id:bT,actionId:bT,label:"Crop image",icon:"crop",dataUi:"context-menu-crop-image-button"},{kind:"command",id:LT,actionId:LT,label:"Smudge image",icon:"pencil",dataUi:"context-menu-smudge-image-button"},{kind:"command",id:mT,actionId:mT,label:"Replace image",icon:"image-plus",dataUi:"context-menu-replace-image-button"},{kind:"command",id:yT,actionId:yT,label:"Download original",icon:"download",dataUi:"context-menu-download-image-original-button"}]}]}]})},ZT=d("plugin.laser.runtime"),QT=class extends $w{constructor(e){super(e,"laser"),this.initial="idle",this.addChild(new JT(e,this)),this.addChild(new eM(e,this)),this.addChild(new tM(e,this))}},JT=class extends $w{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={sessionId:pm(e).start(),originPagePoint:t.pagePoint.clone(),trail:[t.pagePoint.clone()]};return fm(e,n),n})(this.editor,e))}},eM=class extends $w{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&&(gm(this.info,e.pagePoint),fm(this.editor,this.info),this.transition("drawing",this.info))}onPointerUp(){this.info&&pm(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&pm(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&pm(this.editor).finish(this.info.sessionId),this.info=null}},tM=class extends $w{info=null;constructor(e,t){super(e,"drawing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&(gm(this.info,e.pagePoint),fm(this.editor,this.info))}onPointerUp(){this.info&&pm(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&pm(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&pm(this.editor).finish(this.info.sessionId),this.info=null}},nM=Xx(()=>Oo(pm(zo()).activeSignal)?Zx(iM,{}):null),iM=Xx(()=>{const e=zo(),t=pm(e),n=Oo(t.trailSignal),i=Oo(e.cameraZoomSignal),o=Math.max(i,1e-4),r=(()=>{const[e,t]=qx(()=>mm());return _x(()=>{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})(),s=Vx({sessionId:0,samples:[],sourceLength:0}),a=Math.max(r,mm());let l,d=[];n&&(((e,t,n,i)=>{t.sessionId!==e.sessionId&&(e.sessionId=t.sessionId,e.samples=[],e.sourceLength=0);const o=t.points;if(Sm(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-pM*s;for(let l=r;l<o.length;l++){const t=o[l];ym(e,{x:t.x,y:t.y},n,Em(a,i,(l-r+1)/s))}e.sourceLength=o.length,Sm(e,i)})(s.current,n,o,a),d=function(e,t){const n=bm(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(Mm(i[i.length-1],e[o],n));return i})(n.length>aM?n.slice(-64):n,cM)}(s.current.samples,a),l=s.current.samples[s.current.samples.length-1]?.time);const c="ending"===n?.phase,u=0===d.length,h=c&&u?n.sessionId:null;if(_x(()=>{null!==h&&t.clear(h)},[h,t]),!n||u)return null;const p=c&&void 0!==l?Bm(1-(a-l)/SM,0,1):1,g=(m=dM/o,0===(f=d).length||m<=0?null:1===f.length?Rm(Im(f[0],m/2,hM))??"":Rm((e=>{if(0===e.length)return[];if(1===e.length)return Im(e[0].point,Math.max(e[0].radius,.01),hM);const t=[],n=[];for(const a of e){const e=vm(a.direction);Am(t,Cm(a.point,Tm(e,a.radius))),Am(n,km(a.point,Tm(e,a.radius)))}const i=[];for(const a of t)Am(i,a);const o=e[e.length-1],r=vm(o.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const o=[];for(let r=1;r<uM;r++){const s=r/uM;o.push(km(e,km(Tm(t,Math.sin(Math.PI*s)*i),Tm(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)Am(i,a);for(let a=n.length-1;a>=0;a--)Am(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]+wm(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=Bm(s/i,0,1);return{point:o,direction:xm(e,r),radius:t/2*a,runningLength:s}})})(f,m))));var f,m;return g?Qx("g",{"data-ui":"laser-trail-overlay",style:{opacity:p},children:[Zx("path",{"data-ui":"laser-trail-glow",d:g,fill:rM,style:{filter:`blur(${sM/o}px)`}}),Zx("path",{"data-ui":"laser-trail-beam",d:g,fill:oM})]}):null}),oM="rgb(255, 38, 38)",rM="rgba(255, 48, 48, 0.55)",sM=4,aM=64,lM=1,dM=12,cM=.32,uM=8,hM=13,pM=16,gM=8,fM=600,mM=300,yM=1400,SM=400,bM={id:"laser",editor:{id:"land.laser",setup(e){e.runtime.provide(ZT,(()=>{const e=a("laser.trail",null);let t=1;return{trailSignal:e,activeSignal:l("laser.active",()=>null!==e.get()),start(){const n=t++;return e.set({sessionId:n,phase:"active",points:[]}),n},set(t,n){const i=e.get();i&&i.sessionId===t&&e.set({sessionId:t,phase:"active",points:n.map(e=>e.clone())})},finish(t){const n=e.get();n&&n.sessionId===t&&e.set({...n,phase:"ending"})},clear(t){e.get()?.sessionId===t&&e.set(null)}}})()),e.tools.register("laser",e=>new QT(e),{shortcut:"l"})}},render:{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",layer:"below-host",component:nM}]},product:()=>({toolbarContributions:[{id:"laser.tool-toolbar",surface:"tool",placement:"chrome",order:55,actionIds:[sP],getGroups:e=>[{id:"laser.tools",items:[{kind:"button",id:"laser.tool.laser",actionId:sP,value:"laser",label:"Laser",shortcut:e.editor.shortcuts.getToolShortcutLabel("laser"),icon:"wand",dataUi:"laser-tool-button"}]}]}]})},xM="path.node",IM="path.control",wM=new WeakMap,PM=["nonzero","evenodd"],vM=["corner","smooth","symmetric"],kM=1e-6,CM=1/3,TM=Math.PI/8,MM=new WeakMap,EM=new WeakMap,BM="land.path.draftSubpathId",AM="land.path.previewNodeId",RM="var(--land-selection, #2563eb)",$M="rgba(255, 255, 255, 0.98)",LM=PI((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,l=i+1;;){do{s++}while(o(e[s],r)<0);do{l--}while(o(e[l],r)>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,o),a(e,t,l+1,i,o)}}function l(e,t,n,i,o){let r,s,a,l,d=t[0],c=i[0],u=0,h=0;c>d==c>-d?(r=d,d=t[++u]):(r=c,c=i[++h]);let p=0;if(u<e&&h<n)for(c>d==c>-d?(s=d+r,a=r-(s-d),d=t[++u]):(s=c+r,a=r-(s-c),c=i[++h]),r=s,0!==a&&(o[p++]=a);u<e&&h<n;)c>d==c>-d?(s=r+d,l=s-r,a=r-(s-l)+(d-l),d=t[++u]):(s=r+c,l=s-r,a=r-(s-l)+(c-l),c=i[++h]),r=s,0!==a&&(o[p++]=a);for(;u<e;)s=r+d,l=s-r,a=r-(s-l)+(d-l),d=t[++u],r=s,0!==a&&(o[p++]=a);for(;h<n;)s=r+c,l=s-r,a=r-(s-l)+(c-l),c=i[++h],r=s,0!==a&&(o[p++]=a);return 0===r&&0!==p||(o[p++]=r),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 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},l.prototype.remove=function(e){this._root=this._remove(e,this._root,this._comparator)},l.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},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=[],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},l.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},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,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},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 o=i(e.key,t.key);if(0===o)break;o<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 o=i(e.key,t.key);if(0===o)break;o<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),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})()},l.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 l=((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: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 o(this._root,"",!0,e=>t.push(e),e),t.join("")},l.prototype.update=function(e,o,r){var s=this._comparator,a=i(e,this._root,s),l=a.left,d=a.right;s(e,o)<0?d=n(o,r,d,s):l=n(o,r,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,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]}})},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 y{constructor(){this.tree=new u,this.round(0)}round(e){const t=this.tree.add(e),n=this.tree.prev(t);if(null!==n&&0===m(t.key,n.key))return this.tree.remove(e),n.key;const i=this.tree.next(t);return null!==i&&0===m(t.key,i.key)?(this.tree.remove(e),i.key):e}}const S=new class{constructor(){this.reset()}reset(){this.xRounder=new y,this.yRounder=new y}round(e,t){return{x:this.xRounder.round(e),y:this.yRounder.round(t)}}},b=134217729,x=d(4),I=d(8),w=d(12),P=d(16),v=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,o,r){const s=(t-r)*(n-o),a=(e-o)*(i-r),d=s-a,c=Math.abs(s+a);return Math.abs(d)>=33306690738754716e-32*c?d:-((e,t,n,i,o,r,s)=>{let a,d,c,u,h,p,g,f,m,y,S,k,C,T,M,E,B,A;const R=e-o,$=n-o,L=t-r,F=i-r;T=R*F,p=b*R,g=p-(p-R),f=R-g,p=b*F,m=p-(p-F),y=F-m,M=f*y-(T-g*m-f*m-g*y),E=L*$,p=b*L,g=p-(p-L),f=L-g,p=b*$,m=p-(p-$),y=$-m,B=f*y-(E-g*m-f*m-g*y),S=M-B,h=M-S,x[0]=M-(S+h)+(h-B),k=T+S,h=k-T,C=T-(k-h)+(S-h),S=C-E,h=C-S,x[1]=C-(S+h)+(h-E),A=k+S,h=A-k,x[2]=k-(A-h)+(S-h),x[3]=A;let D=((e,t)=>{let n=t[0];for(let i=1;i<4;i++)n+=t[i];return n})(0,x),U=22204460492503146e-32*s;if(D>=U||-D>=U)return D;if(h=e-R,a=e-(R+h)+(h-o),h=n-$,c=n-($+h)+(h-o),h=t-L,d=t-(L+h)+(h-r),h=i-F,u=i-(F+h)+(h-r),0===a&&0===d&&0===c&&0===u)return D;if(U=11093356479670487e-47*s+33306690738754706e-32*Math.abs(D),D+=R*u+F*a-(L*c+$*d),D>=U||-D>=U)return D;T=a*F,p=b*a,g=p-(p-a),f=a-g,p=b*F,m=p-(p-F),y=F-m,M=f*y-(T-g*m-f*m-g*y),E=d*$,p=b*d,g=p-(p-d),f=d-g,p=b*$,m=p-(p-$),y=$-m,B=f*y-(E-g*m-f*m-g*y),S=M-B,h=M-S,v[0]=M-(S+h)+(h-B),k=T+S,h=k-T,C=T-(k-h)+(S-h),S=C-E,h=C-S,v[1]=C-(S+h)+(h-E),A=k+S,h=A-k,v[2]=k-(A-h)+(S-h),v[3]=A;const z=l(4,x,4,v,I);T=R*u,p=b*R,g=p-(p-R),f=R-g,p=b*u,m=p-(p-u),y=u-m,M=f*y-(T-g*m-f*m-g*y),E=L*c,p=b*L,g=p-(p-L),f=L-g,p=b*c,m=p-(p-c),y=c-m,B=f*y-(E-g*m-f*m-g*y),S=M-B,h=M-S,v[0]=M-(S+h)+(h-B),k=T+S,h=k-T,C=T-(k-h)+(S-h),S=C-E,h=C-S,v[1]=C-(S+h)+(h-E),A=k+S,h=A-k,v[2]=k-(A-h)+(S-h),v[3]=A;const O=l(z,I,4,v,w);return T=a*u,p=b*a,g=p-(p-a),f=a-g,p=b*u,m=p-(p-u),y=u-m,M=f*y-(T-g*m-f*m-g*y),E=d*c,p=b*d,g=p-(p-d),f=d-g,p=b*c,m=p-(p-c),y=c-m,B=f*y-(E-g*m-f*m-g*y),S=M-B,h=M-S,v[0]=M-(S+h)+(h-B),k=T+S,h=k-T,C=T-(k-h)+(S-h),S=C-E,h=C-S,v[1]=C-(S+h)+(h-E),A=k+S,h=A-k,v[2]=k-(A-h)+(S-h),v[3]=A,P[l(O,w,4,v,P)-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},M=e=>Math.sqrt(C(e,e)),E=(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)/M(o)/M(i)},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 C(o,i)/M(o)/M(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 ${static compare(e,t){const n=$.comparePoints(e.point,t.point);return 0!==n?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:F.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x<t.x?-1:e.x>t.x?1:e.y<t.y?-1:e.y>t.y?1:0}constructor(e,t){void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,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:E(this.point,e.point,i.point),cosine:B(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 L=0;class F{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,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(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=l-s,t=o-n,c=d-a,u=r-i;if(e>t&&c<u)return 1;if(e<t&&c>u)return-1}return o>r?1:o<r||l<d?-1:l>d?1:e.id<t.id?-1:e.id>t.id?1:0}constructor(e,t,n,i){this.id=++L,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=n,this.windings=i}static fromRing(e,t,n){let i,o,r;const s=$.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 F(new $(i,!0),new $(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,l=h(t,s)&&0===this.comparePoint(s),d=h(n,o)&&0===e.comparePoint(o),c=h(t,a)&&0===this.comparePoint(a),u=h(n,r)&&0===e.comparePoint(r);if(d&&l)return u&&!c?r:!u&&c?a:null;if(d)return c&&o.x===a.x&&o.y===a.y?null:o;if(l)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 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 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)?S.round(g.x,g.y):null}split(e){const t=[],n=void 0!==e.events,i=new $(e,!0),o=new $(e,!1),r=this.rightSE;this.replaceRightSE(o),t.push(o),t.push(i);const s=new F(i,r,this.rings.slice(),this.windings.slice());return $.comparePoints(s.leftSE.point,s.rightSE.point)>0&&s.swapEvents(),$.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(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=F.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(W.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===W.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 ${W.type}`)}return this._isInResult}}class D{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=S.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=S.round(e[r][0],e[r][1]);t.x===o.x&&t.y===o.y||(this.segments.push(F.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(F.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 U{constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new D(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 D(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 U(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 O{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],l=r.point,d=[];for(;o=r,r=s,a.push(r),r.point!==l;)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=d.length;t<o;t++)if(d[t].point===r.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 O(i.reverse()));continue}d.push({index:a.length,point:r.point});const i=r.getLeftmostComparator(o);s=e.sort(i)[0].otherSE;break}t.push(new O(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];$.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 X{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 X(i));else{const e=i.enclosingRing();e.poly||t.push(new X(e)),e.poly.addInterior(i)}}return t}}class Y{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:F.compare;this.queue=e,this.tree=new u(t),this.segments=[]}process(e){const t=e.segment,n=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(t),n;const 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||$.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 _="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,H="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6,W=new class{run(e,t,n){W.type=e,S.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(W.numMultiPolys=i.length,"difference"===W.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"===W.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 o=new u($.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(o.insert(e[t]),o.size>_)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const r=new Y(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>_)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(r.segments.length>H)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const t=r.process(e);for(let n=0,i=t.length;n<i;n++){const e=t[n];void 0===e.consumedBy&&o.insert(e)}s=o.size,a=o.pop()}return S.reset(),new N(O.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 W.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 W.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 W.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 W.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()})(),FM=1,DM=1,UM=new WeakMap,zM="path.edit",OM="path.insert-node",XM="path.node-nudge",NM="path.node-operation",YM="path.shape-delete",_M=Math.PI/4,HM=1,WM=new WeakMap,KM="path.create",VM=Math.PI/4,qM=1,jM=1,GM=class extends $w{draft=null;constructor(e){super(e,"path"),this.initial="idle",this.addChild(new ZM(e,this)),this.addChild(new QM(e,this))}onEnter(){this.editor.clearSelectionTransients()}onExit(){this.draft&&(this.canFinishDraft()?this.finishDraft({switchToSelect:!1}):this.cancelDraft())}isInInitialState(){return!this.hasDraft()&&super.isInInitialState()}startOrExtend(e,t){if(!this.draft){this.editor.history.mark(KM);const t=this.editor.getDefaultShapeProps("path"),n=`subpath:${jM+=1}`,i=BS(),o={id:i,x:0,y:0,kind:"corner"},[r]=this.editor.commands.createShapes([{type:"path",x:e.x,y:e.y,meta:Vy({},{subpathId:n,previewNodeId:null}),props:{...t,subpaths:[{id:n,closed:!1,nodes:[o]}]}}],{source:"user",autoReparent:!1});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(),startNode:jm(o),finishOnPointerUp:!1}}const n=this.editor.getShape(this.draft.shapeId);if(!Xm(n))return this.cancelDraft(),null;const i=t.shiftKey?RS(this.editor,n,this.draft.subpathId,this.draft.previewNodeId)??e:e,o=t.shiftKey?$S(i,e):e;if(function(e,t,n,i,o){const r=((e,t,n)=>{const i=yy(t.props.subpaths,n)?.nodes[0];return i?e.computeShapeLocalToPageTransform(t).applyToPoint(new $I(i.x,i.y)):null})(e,t,n),s=yy(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,n,this.draft.subpathId,this.draft.previewNodeId,e)){const t=this.draft,i=yy(n.props.subpaths,t.subpathId)?.nodes.find(e=>e.id!==t.previewNodeId);return i?(this.editor.commands.updateShapes([{id:n.id,meta:Vy(n.meta,{subpathId:t.subpathId,previewNodeId:null}),props:{subpaths:LS(n.props.subpaths,t).map(e=>e.id===t.subpathId?{...e,closed:!0}:e)}}],{source:"user"}),this.draft={...t,previewNodeId:null},{shapeId:n.id,subpathId:t.subpathId,nodeId:i.id,originPagePoint:e.clone(),startNode:jm(i),finishOnPointerUp:!0}):null}const r=AS(this.editor,n,o),s=this.draft.previewNodeId??BS(),a=n.props.subpaths.map(e=>e.id===this.draft?.subpathId?this.draft.previewNodeId?{...e,nodes:e.nodes.map(e=>e.id===this.draft?.previewNodeId?{id:s,x:r.x,y:r.y,kind:"corner"}:e)}:{...e,nodes:[...e.nodes,{id:s,x:r.x,y:r.y,kind:"corner"}]}:e);return this.editor.commands.updateShapes([{id:n.id,meta:Vy(n.meta,{subpathId:this.draft.subpathId,previewNodeId:null}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,lastNodeId:s,previewNodeId:null},{shapeId:n.id,subpathId:this.draft.subpathId,nodeId:s,originPagePoint:e.clone(),startNode:{id:s,x:r.x,y:r.y,kind:"corner"},finishOnPointerUp:!1}}updateNodeDrag(e,t,n){const i=this.editor.getShape(e.shapeId);if(!Xm(i))return;const o=n.shiftKey?$S(e.originPagePoint,t):t,r=AS(this.editor,i,e.originPagePoint),s=AS(this.editor,i,o),a=e.originPagePoint.dist(o)*this.editor.getCurrentCamera().z>=3,l=by(i.props.subpaths,e.subpathId,e.nodeId,()=>a?((e,t,n)=>({...e,kind:n.altKey?"smooth":"symmetric",in:{dx:-t.x,dy:-t.y},out:{dx:t.x,dy:t.y}}))(e.startNode,s.sub(r),n):jm(e.startNode));this.editor.commands.updateShapes([{id:i.id,meta:Vy(i.meta,{subpathId:e.subpathId,previewNodeId:this.draft?.previewNodeId??null}),props:{subpaths:l}}],{source:"user"})}updatePreview(e,t){if(!this.draft)return;const n=this.editor.getShape(this.draft.shapeId);if(!Xm(n)||FS(n,this.draft)<1)return;const i=t.shiftKey?RS(this.editor,n,this.draft.subpathId,this.draft.previewNodeId):null,o=i?$S(i,e):e,r=AS(this.editor,n,o),s=this.draft.previewNodeId??BS(),a=n.props.subpaths.map(e=>e.id!==this.draft?.subpathId?e:this.draft.previewNodeId?{...e,nodes:e.nodes.map(e=>e.id===this.draft?.previewNodeId?{id:s,x:r.x,y:r.y,kind:"corner"}:e)}:{...e,nodes:[...e.nodes,{id:s,x:r.x,y:r.y,kind:"corner"}]});this.editor.commands.updateShapes([{id:n.id,meta:Vy(n.meta,{subpathId:this.draft.subpathId,previewNodeId:s}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,previewNodeId:s}}canFinishDraft(){if(!this.draft)return!1;const e=this.editor.getShape(this.draft.shapeId);return!!Xm(e)&&FS(e,this.draft)>=2}finishDraft(e={}){if(!this.draft)return;const t=e.switchToSelect??!0,n=this.editor.getShape(this.draft.shapeId);if(Xm(n)){const e=LS(n.props.subpaths,this.draft),t=uy(hy({...n,props:{...n.props,subpaths:e}},this.editor.computeShapeLocalToPageTransform(n)),n.props);this.editor.commands.updateShapes([{id:n.id,x:t.x,y:t.y,rotation:0,skewX:0,scaleX:1,scaleY:1,meta:qy(n.meta),props:{subpaths:t.subpaths}}],{source:"user"}),this.draft.createdShape&&xe(this.editor,n.id,{source:"user"})}this.editor.history.squashToMark(KM,"shape.create"),this.draft=null,t&&!this.editor.isToolLocked()&&this.editor.commands.setActiveTool("select",{source:"system"})}finishDraftAndEdit(){const e=this.draft?.shapeId;if(e){if(!this.canFinishDraft())return this.cancelDraft(),void(this.editor.isToolLocked()||this.editor.commands.setActiveTool("select",{source:"system"}));this.finishDraft({switchToSelect:!1}),Xm(this.editor.getShape(e))&&(this.editor.commands.setActiveTool("select",{source:"system"}),this.editor.startEditingShape({shapeId:e,markId:"path.edit",entryMode:"focusEnd"},"user"))}}cancelDraft(){this.draft&&(this.editor.history.bailToMark(KM),this.draft=null)}hasDraft(){return null!==this.draft}},ZM=class extends $w{tool;constructor(e,t){super(e,"idle",t),this.tool=t}onPointerDown(e){if(0!==e.button)return;const t=this.tool.startOrExtend(e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey});t&&this.transition("dragging_node",t)}onPointerMove(e){this.tool.updatePreview(e.pagePoint,{shiftKey:e.shiftKey})}onKeyDown(e){("Enter"===e.key&&this.tool.hasDraft()||"Escape"===e.key&&this.tool.hasDraft())&&this.tool.finishDraftAndEdit()}onCancel(e){"escape"===e.reason&&this.tool.hasDraft()&&this.tool.finishDraftAndEdit()}},QM=class extends $w{tool;info=null;constructor(e,t){super(e,"dragging_node",t),this.tool=t}onEnter(e){this.info=e}onPointerMove(e){this.info&&this.tool.updateNodeDrag(this.info,e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey})}onPointerUp(e){const t=this.info;t&&this.tool.updateNodeDrag(t,e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey}),this.transition("idle"),t?.finishOnPointerUp&&this.tool.finishDraft()}onCancel(){this.tool.cancelDraft(),this.transition("idle")}onExit(){this.info=null}},JM="path.edit",eE="path.edit.snap-nodes",tE="path.boolean.union",nE="path.boolean.subtract",iE="path.boolean.intersect",oE="path.boolean.xor",rE="path.node.delete",sE="path.node.make-curve",aE="path.node.remove-handles",lE="path.node.merge",dE="path.node.join",cE="path.node.separate",uE=[{id:"none",value:E("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:M("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:M("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:M("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:M("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],hE=[{value:M("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:M("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],pE=[{value:1,label:"1"},{value:2,label:"2"},{value:3,label:"3"},{value:5,label:"5"},{value:8,label:"8"}],gE=[{value:"nonzero",label:"Nonzero"},{value:"evenodd",label:"Even odd"}],fE=[["geo",lT],["draw",yC],["arrow",oC],["eraser",UC],["laser",bM],["path",{id:"path",editor:{id:"land.path",shapeCapabilities:[{type:"path",schemaProps:["subpaths","fill","stroke","strokeWidth","fillRule"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Path owns editable Bezier node geometry, multi-subpath fill rules, SVG export, and destructive polygon-clipping boolean materialization."]}],shapeUtils:[new class extends Rw{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:E("transparent"),stroke:M("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{subpaths:(i=CS(t.subpaths,n.subpaths),i.map(e=>({...e,nodes:e.nodes.filter(e=>Vm(e.x)&&Vm(e.y))})).filter(e=>e.nodes.length>0).map(Gm)),fill:L(t.fill,n.fill),stroke:L(t.stroke,n.stroke),strokeWidth:Math.max(1,vS(t.strokeWidth,n.strokeWidth)),fillRule:Nm(t.fillRule)?t.fillRule:n.fillRule};var i}getPositionedBounds(e){const t=ly(e).localBounds;return new LI(e.x+t.x,e.y+t.y,t.w,t.h)}getLocalBounds(e){return ly(e).localBounds}getRenderBounds(e){return ly(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}getSelectionResizeLocalBounds(e){return ly(e).pointBounds}resizeSelectionBounds(e,t){const n=hy(e,this.getLocalToPageTransform(e)).map(e=>({...e,nodes:e.nodes.map(e=>ES(e,e=>((e,t)=>0===t.selectionRotation?e:$I.RotWith(e,t.selectionRotationCenter,-t.selectionRotation))(e,t)))})),i=uy(((e,t)=>{const n=ly(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 cy(e.props.subpaths,e=>new $I(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,skewX:0,scaleX:1,scaleY:1,props:{...e.props,subpaths:n}},t.selectionLocalBounds).map(e=>({...e,nodes:e.nodes.map(e=>ES(e,e=>((e,t)=>0===t.selectionRotation?e:$I.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(e,t)))})),e.props);return{id:e.id,x:i.x,y:i.y,rotation:0,skewX:0,scaleX:1,scaleY:1,props:{subpaths:i.subpaths}}}getPositionedOutlineVertices(e){return ly(e).outlineVertices.map(t=>new $I(e.x+t.x,e.y+t.y))}getHandleSnapGeometry(e){return{points:e.props.subpaths.flatMap(e=>e.nodes.flatMap(e=>[{point:Qm(e),kind:"custom"},...e.in?[{point:Jm(e),kind:"custom"}]:[],...e.out?[{point:ey(e),kind:"custom"}]:[]])),outline:ly(e).outlineVertices}}canReceiveTerminalBinding(e){return!0}canEdit(e){return!0}canUseSelectionResizeHandles(e,t){return t.editor.getShapeEditingSession()?.shapeId!==e.id}canUseSelectionRotateHandle(e,t){return t.editor.getShapeEditingSession()?.shapeId!==e.id}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const 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:xM,id:(i=e.id,r=t.id,["node",i,r].map(encodeURIComponent).join("|")),point:o.applyToPoint(Qm(t)),cursor:"grab"}];var i,r;return t.in&&n.push({kind:"custom",type:IM,id:Dm(e.id,t.id,"in"),point:o.applyToPoint(Jm(t)),cursor:"grab"}),t.out&&n.push({kind:"custom",type:IM,id:Dm(e.id,t.id,"out"),point:o.applyToPoint(ey(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:py(e,t.editor.computeShapeLocalToPageTransform(e)),bindingSegments:[]}:{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,bindingSegments:[]}}hitTest(e,t,n){const i=new $I(t.x-e.x,t.y-e.y),o=ly(e);return!U(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&&fy(t,n,r)<=i)return!0}return!1})(o.flattenedSubpaths,i,e.props.strokeWidth/2+6)}hitTestLineSegment(e,t){const n=new $I(t.positionedStart.x-e.x,t.positionedStart.y-e.y),i=new $I(t.positionedEnd.x-e.x,t.positionedEnd.y-e.y),o=t.positionedMargin+e.props.strokeWidth/2;return ly(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&&(MS(i,e,t)<=o||MS(s,e,t)<=o||MS(e,i,s)<=o||MS(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]}}}],shapeSvgExporters:[new class{type="path";toSvg(e,t){const n=ly(e);return n.path?{tag:"path",attrs:{d:n.path,fill:U(e.props.fill)?"none":t.resolveColor(e.props.fill),"fill-rule":e.props.fillRule,"clip-rule":e.props.fillRule,stroke:t.resolveColor(e.props.stroke),"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}:null}}],interactionHandlers:[{id:"land.path.interactions",editorEvent:{handleEvent(e,t){if("pointer"===t.type&&"pointer_move"===t.name&&WM.get(e)?.pointerId===t.pointerId)return dS(e),pS(e,t),"handled";if("pointer"===t.type&&"pointer_up"===t.name&&(dS(e),WM.get(e)?.pointerId===t.pointerId))return((e,t)=>{const n=WM.get(e);n&&(n.isActive?pS(e,t):uS(t)||Oy(e),WM.delete(e),e.setBrushBox(null))})(e,t),"handled";if("pointer"===t.type&&"pointer_cancel"===t.name&&(dS(e),WM.get(e)?.pointerId===t.pointerId))return gS(e),"handled";if("click"===t.type&&"double_click"===t.name&&"up"===t.phase&&!t.shiftKey&&!t.altKey&&!t.accelKey){cS(e);const n=e.hitTestShape(t.pagePoint);if(Xm(n))return sS(e),e.startEditingShape({shapeId:n.id,markId:zM,entryMode:"focusEnd"},"user"),"handled"}if("cancel"===t.type)return WM.has(e)?(gS(e),"handled"):"escape"===t.reason&&e.isActiveToolInInitialState()&&aS(e)&&e.completeEditing("user")?"handled":(cS(e),"continue");if("keyboard"===t.type&&"key_down"===t.name)return xS(e,t)?"handled":"continue";if("pointer"===t.type&&"pointer_move"===t.name)return"mouse"!==t.pointerType||0!==t.buttons||t.altKey?dS(e):((e,t)=>{const n=aS(e);if(!n||"select"!==e.getActiveToolId()||!e.isActiveToolInInitialState())return void dS(e);if("custom"===e.hitTestSelectionHandle(t.pagePoint)?.kind)return void dS(e);const i=lS(e,n,t.pagePoint),o=my(n.props.subpaths,i,7/e.getCurrentCamera().z);if(!o)return void dS(e);const r=e.computeShapeLocalToPageTransform(n);zm(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&&0===t.button&&t.altKey){dS(e);const n=aS(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind&&"path.node"===i.type){const t=Um(i.type,i.id);if("path.node"===t?.type){const i=zy(e);return SS(e,n,i?.selection.shapeId===n.id&&Yy(i.selection,t.subpathId,t.nodeId)?i.selection.nodes:[{subpathId:t.subpathId,nodeId:t.nodeId}]),"handled"}}}if("pointer"===t.type&&"pointer_down"===t.name&&0===t.button&&!t.altKey){dS(e);const n=aS(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind)return Um(i.type,i.id)||Oy(e),"continue";const o=lS(e,n,t.pagePoint),r=my(n.props.subpaths,o,7/e.getCurrentCamera().z);if(!r)return((e,t,n)=>{const i=zy(e);WM.set(e,{shapeId:t.id,pointerId:n.pointerId,originPagePoint:n.pagePoint.clone(),originScreenPoint:n.screenPoint.clone(),previousEntries:i?.selection.shapeId===t.id?i.selection.nodes.map(e=>({...e})):[],previousPrimary:i?.selection.shapeId===t.id?{...i.selection.primary}:null,isActive:!1})})(e,n,t),"handled";e.history.mark(OM);const s=`insert-node:${HM+=1}`,a=((e,t,n)=>e.map(e=>{if(e.id!==t.subpathId)return Gm(e);const i=e.nodes.findIndex(e=>e.id===t.startNodeId);if(i<0)return Gm(e);const o=(i+1)%e.nodes.length,r=e.nodes[i],s=e.nodes[o];if(!r||!s||s.id!==t.endNodeId)return Gm(e);const a=((e,t,n,i)=>{if(!oy(e,t)){const o=ny(Qm(e),Qm(t),n);return{start:jm(e),node:{id:i,x:o.x,y:o.y,kind:"corner"},end:jm(t)}}const[o,r,s,a]=iy(e,t),l=ny(o,r,n),d=ny(r,s,n),c=ny(s,a,n),u=ny(l,d,n),h=ny(d,c,n),p=ny(u,h,n);return{start:{...jm(e),out:Dy(l.sub(o))},node:{id:i,x:p.x,y:p.y,kind:"smooth",in:Dy(u.sub(p)),out:Dy(h.sub(p))},end:{...jm(t),in:Dy(c.sub(a))}}})(r,s,t.t,n),l=e.nodes.map(jm);return l[i]=a.start,l[o]=a.end,l.splice(i+1,0,a.node),{...e,nodes:l}}))(n.props.subpaths,r,s);e.commands.updateShapes([{id:n.id,props:{subpaths:a}}],{source:"user"});const l=e.getShape(n.id);return Xm(l)&&Xy(e,l,r.subpathId,s),e.history.squashToMark(OM,"shape.edit"),"continue"}return"continue"}},selectionHandle:{createSession(e,{handle:t,shape:n,originPagePoint:i}){if(!Xm(n)||"custom"!==t.kind)return null;const o=Um(t.type,t.id);if(!o)return null;if(e.getShapeEditingSession()?.shapeId!==n.id)return null;const r=n,s=Sy(r.props.subpaths,o.subpathId,o.nodeId),a=lS(e,r,i),l=zy(e),d=l?.selection.shapeId===n.id?l.selection.nodes.map(e=>({...e})):[],c=l?.selection.shapeId===n.id?{...l.selection.primary}:null,u={subpathId:o.subpathId,nodeId:o.nodeId},h=!!l&&l.selection.shapeId===n.id&&Yy(l.selection,o.subpathId,o.nodeId),p="path.node"===o.type&&h,g="path.node"===o.type&&e.inputs.state.get().shiftKey,f=g&&!p?[...l?.selection.shapeId===n.id?l.selection.nodes:[],u]:null;f?Ny(e,n,f,u):e.inputs.state.get().shiftKey||h||Xy(e,n,o.subpathId,o.nodeId);const m="path.node"===o.type&&(f||p)?f??l.selection.nodes:[u],y=e.computeShapeLocalToPageTransform(r),S=s?y.applyToPoint(Qm(s)):i,b=t.point.sub(i),x="path.node"===o.type?m.flatMap(e=>{const t=Sy(r.props.subpaths,e.subpathId,e.nodeId);return t?[y.applyToPoint(Qm(t))]:[]}):[t.point],I=(x.length>0?x:[t.point]).map(e=>e.sub(i)),w=((e,t,n)=>{const i=new Set(n.map(hS)),o=e.computeShapeLocalToPageTransform(t);return{points:t.props.subpaths.flatMap(e=>e.nodes.flatMap(n=>i.has(hS({subpathId:e.id,nodeId:n.id}))?[]:[{id:`${t.id}:${e.id}:${n.id}`,nodeId:t.id,point:o.applyToPoint(Qm(n)),kind:"custom"}])),outlines:[]}})(e,r,"path.node"===o.type?m:[]);return{shapeId:n.id,historyMark:"path.handle",onClick:g&&p?({editor:e})=>{const t=e.getShape(n.id);Xm(t)&&((e,t,n,i)=>{const o=Uy(e);if(!o||o.shapeId!==t.id)return void Xy(e,t,n,i);const r={subpathId:n,nodeId:i},s=Yy(o,n,i),a=s?o.nodes.filter(e=>!Wy(e,r)):[...o.nodes,r];Ny(e,t,a,s?a.at(-1)??null:r)})(e,t,o.subpathId,o.nodeId)}:void 0,onCancel({editor:e,reason:t}){if("pointer_cancel"!==t&&"escape"!==t)return;const i=e.getShape(n.id);Xm(i)&&e.getShapeEditingSession()?.shapeId===n.id&&(0!==d.length?Ny(e,i,d,c):Oy(e))},update({editor:e,pagePoint:t,accelKey:l,source:d}){if(!Xm(e.getShape(n.id)))return"stop";const c=e.inputs.state.get(),u=c.shiftKey?"path.node"===o.type?wS(i,t):wS(S,t.add(b)).sub(b):t,h=oS(e)&&!l&&!c.shiftKey&&w.points.length>0,p=h?e.snaps.snapHandle({mode:"align",pagePoint:u,sourcePointOffsets:I,snapshot:w,threshold:10/e.getCurrentCamera().z}):null;h||e.snaps.clearIndicators();const g=p?.snappedPagePoint??u,f=lS(e,r,"path.node"===o.type?g:g.add(b)),y="path.node"===o.type?s?xy(r.props.subpaths,m,e=>PS(e,f.sub(a))):Zm(r.props.subpaths):by(r.props.subpaths,o.subpathId,o.nodeId,e=>((e,t,n,i)=>{const o=Qm(e),r=i.altKey?{...e,kind:"corner"}:{...e},s=n.sub(o);return"in"===t?(r.in={dx:s.x,dy:s.y},i.altKey||"corner"===e.kind||(r.out=IS(s,e.out?ey(e).sub(o):null,"symmetric"===e.kind))):(r.out={dx:s.x,dy:s.y},i.altKey||"corner"===e.kind||(r.in=IS(s,e.in?Jm(e).sub(o):null,"symmetric"===e.kind))),r})(e,o.handle,f,{altKey:c.altKey}));if(e.commands.updateShapes([{id:n.id,props:{subpaths:y}}],{source:d}),"path.node"===o.type){const t=e.getShape(n.id);Xm(t)&&Ny(e,t,m,{subpathId:o.subpathId,nodeId:o.nodeId})}return"continue"}}}}}],setup(e){const t=(e=>{let t=null;return Ro("path.editSnap.lifecycle",e.shapeEditingSessionSignal,()=>{const n=e.getShapeEditingSession(),i=n?e.getShape(n.shapeId):null,o=Xm(i)?i.id:null;o!==t&&(t=o,Oy(e),sS(e))})})(e);return e.tools.register("path",e=>new GM(e),{shortcut:"b"}),t}},render:{id:"land.path.react",canvasOverlays:[{id:"land.path.draft-overlay",component:function(){const e=zo(),t=Oo(e.toolStateSignal),n=Oo(e.inputs.state),i=Oo(e.selectedShapesSignal),o=Oo(e.currentCameraSignal);if("path"!==t.activeToolId)return null;const r=1===i.length?i[0]:null,s=Xm(r)?r:null,a=8/o.z,l=1.5/o.z,d=6/o.z,c=1/o.z,u=n.currentPagePoint;if(!s)return u?Zx(Zy,{point:u,size:a,strokeWidth:l,variant:"candidate"}):null;const h=((e,t)=>{const n=Ky(t);if(!n.subpathId)return null;const i=yy(hy(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?Wm({id:`${i.id}:preview`,closed:!1,nodes:[s,r]}):null;return{closed:i.closed,committedNodes:i.nodes.filter(e=>e.id!==n.previewNodeId),previewNode:r,previewPath:a}})(e,s);if(!h)return u?Zx(Zy,{point:u,size:a,strokeWidth:l,variant:"candidate"}):null;const p=h.previewNode?Qm(h.previewNode):n.isPointing?null:u,g=p&&!h.committedNodes.some(e=>Qm(e).dist2(p)<=.25/(o.z*o.z));
80
+ return Qx("g",{"data-ui":"path-draft-overlay",pointerEvents:"none",children:[h.previewPath?Zx("path",{"data-ui":"path-draft-preview-segment",d:h.previewPath,fill:"none",stroke:RM,strokeWidth:Math.max(l,1/o.z),strokeDasharray:`${6/o.z} ${4/o.z}`,strokeLinecap:"round",strokeLinejoin:"round"}):null,g?Zx(Zy,{point:p,size:a,strokeWidth:l,variant:"candidate"}):null,h.committedNodes.map((e,t)=>Zx(jy,{node:e,showIn:h.closed||t>0,size:d,strokeWidth:c},e.id)),h.committedNodes.map(e=>Zx(Zy,{point:Qm(e),size:a,strokeWidth:l,variant:"committed"},e.id))]})},layer:"above-host",order:20},{id:"land.path.edit-insert-preview-overlay",component:function(){const e=zo(),t=Oo(e.toolStateSignal),n=Oo(e.shapeEditingSessionSignal),i=Oo(e.selectedShapesSignal),o=Oo(e.currentCameraSignal);if(Oo(e.inputs.state),"select"!==t.activeToolId||!n)return null;const r=1===i.length?i[0]:null;if(!Xm(r)||r.id!==n.shapeId)return null;const s=(e=>{const t=wM.get(e);return t?Om(t):null})(e);if(!s||s.shapeId!==r.id)return null;const a=8/o.z,l=a/2;
81
+ return Zx("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:Zx("rect",{"data-ui":"path-edit-insert-preview-control-point",x:s.pagePoint.x-l,y:s.pagePoint.y-l,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})})},layer:"above-host",order:21}],shapeRenderers:[{type:"path",component:function({shape:e,isHovered:t,shapeEditingSession:n}){
82
+ return Zx(Qy,{shape:e,isHovered:t,shapeEditingSession:n})}}],selectionCustomHandleRenderers:[{type:xM,component:function({handle:e,strokeWidth:t}){const n=eS(e.type,e.id);
83
+ return Zx("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2,ry:2,fill:n?"rgba(219, 234, 254, 0.98)":"rgba(255,255,255,0.98)",stroke:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.94)",strokeWidth:n?1.5*t:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}},{type:IM,component:function({handle:e,strokeWidth:t}){const n=eS(e.type,e.id);
84
+ return Zx("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"}})}}]},product:()=>({actions:[zS("fill"),zS("stroke"),zS("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(Xm(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(!Nm(t))return;const n=e.selection.selectedShapes.filter(Xm).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{fillRule:t}}));n.length>0&&e.editor.commands.updateShapes(n,{source:"user"})}},OS("fill"),OS("stroke"),OS("strokeWidth"),{id:"path.default-fillRule",isVisible:e=>"path"===e.tool.activeToolId,getValue:e=>e.editor.getDefaultShapeProps("path").fillRule,run({context:e,value:t}){Nm(t)&&e.editor.updateDefaultShapeProps("path",{fillRule:t})}},{id:JM,isVisible:e=>1===e.selection.count&&"path"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return Xm(t)&&!t.isLocked},run({context:e}){const[t]=e.selection.selectedShapes;Xm(t)&&(Oy(e.editor),sS(e.editor),e.editor.startEditingShape({shapeId:t.id,markId:"path.edit",entryMode:"focusEnd"},"user"))}},{id:eE,isVisible(e){const t=e.editor.getShapeEditingSession();return!!t&&Xm(e.editor.getShape(t.shapeId))},isEnabled(e){const t=e.editor.getShapeEditingSession(),n=t?e.editor.getShape(t.shapeId):null;return Xm(n)&&!n.isLocked},getValue:e=>oS(e.editor),run({context:e}){rS(e.editor)}},{id:rE,isVisible:e=>!!zy(e.editor),isEnabled(e){const t=zy(e.editor);return!!t&&!t.shape.isLocked},run({context:e}){const t=zy(e.editor);t&&!t.shape.isLocked&&SS(e.editor,t.shape,t.selection.nodes)}},{id:sE,isVisible:e=>!!zy(e.editor),isEnabled(e){const t=zy(e.editor);return!!t&&!t.shape.isLocked&&t.entries.some(({node:e})=>!e.in&&!e.out)},run({context:e}){const t=zy(e.editor);if(!t||t.shape.isLocked)return;const n=t.entries.flatMap(({ref:e,node:t})=>t.in||t.out?[]:[e]).reduce((e,t)=>Iy(e,t.subpathId,t.nodeId),t.shape.props.subpaths);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"});const i=e.editor.getShape(t.shape.id);Xm(i)&&Ny(e.editor,i,t.selection.nodes,t.selection.primary)}},{id:aE,isVisible:e=>!!zy(e.editor),isEnabled(e){const t=zy(e.editor);return!!t&&!t.shape.isLocked&&t.entries.some(({node:e})=>!!e.in||!!e.out)},run({context:e}){const t=zy(e.editor);if(!t||t.shape.isLocked)return;const n=t.selection.nodes.reduce((e,t)=>wy(e,t.subpathId,t.nodeId),t.shape.props.subpaths);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"});const i=e.editor.getShape(t.shape.id);Xm(i)&&Ny(e.editor,i,t.selection.nodes,t.selection.primary)}},XS(lE,"merge"),XS(dE,"join"),XS(cE,"separate"),NS("union"),NS("subtract"),NS("intersect"),NS("xor")],toolbarContributions:[{id:"path.tool-toolbar",surface:"tool",placement:"chrome",order:47,actionIds:[sP],getGroups:e=>[{id:"path.tools",items:[{kind:"button",id:"path.tool.path",actionId:sP,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",placement:"floating",order:48,actionIds:["path.default-fill","path.default-stroke","path.default-strokeWidth","path.default-fillRule"],when:e=>"path"===e.tool.activeToolId,getGroups:()=>US({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:[JM,"path.set-fill","path.set-stroke","path.set-strokeWidth","path.set-fillRule",tE,nE,iE,oE],when:e=>"path"===e.selection.commonShapeType,getGroups(e){const t=[{id:"path.edit",items:[{kind:"button",id:"path.edit",actionId:JM,label:"Edit",icon:"square-pen",dataUi:"path-edit-button"}]},...US({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",fillRuleActionId:"path.set-fillRule",dataUiPrefix:"path"})];return YS(e).length>=2&&t.push({id:"path.boolean",items:[{kind:"button",id:"path.boolean.union",actionId:tE,label:"Union",icon:"group",dataUi:"path-boolean-union-button"},{kind:"button",id:"path.boolean.subtract",actionId:nE,label:"Subtract",icon:"minus",dataUi:"path-boolean-subtract-button"},{kind:"button",id:"path.boolean.intersect",actionId:iE,label:"Intersect",icon:"crop",dataUi:"path-boolean-intersect-button"},{kind:"button",id:"path.boolean.xor",actionId:oE,label:"Exclude",icon:"ungroup",dataUi:"path-boolean-xor-button"}]}),t}},{id:"path.floating-selection-toolbar",surface:"selection",placement:"floating",order:22,actionIds:[JM,eE,rE,sE,aE,lE,dE,cE,"path.set-fill","path.set-stroke","path.set-strokeWidth","path.set-fillRule",tE,nE,iE,oE],when(e){const t=e.editor.getShapeEditingSession(),n=t?e.editor.getShape(t.shapeId):null;return"path"===e.selection.commonShapeType&&(!t||Xm(n))},getGroups(e){const t=e.editor.getShapeEditingSession(),n=Xm(t?e.editor.getShape(t.shapeId):null);if(zy(e.editor))return[{id:"path.floating-node-edit",items:[{kind:"button",id:"path.floating-node.delete",actionId:rE,label:"Delete node",shortcut:"⌫",icon:"remove-node",dataUi:"floating-path-node-delete-button"}]},{id:"path.floating-node-topology",items:[{kind:"button",id:"path.floating-node.merge",actionId:lE,label:"Merge nodes",shortcut:"Mod+J",icon:"merge-nodes",dataUi:"floating-path-node-merge-button"},{kind:"button",id:"path.floating-node.join",actionId:dE,label:"Join nodes",shortcut:"J",icon:"join-nodes",dataUi:"floating-path-node-join-button"},{kind:"button",id:"path.floating-node.separate",actionId:cE,label:"Separate segment",shortcut:"K",icon:"separate-nodes",dataUi:"floating-path-node-separate-button"}]},{id:"path.floating-node-convert",items:[{kind:"button",id:"path.floating-node.remove-handles",actionId:aE,label:"Corner point",shortcut:"X",icon:"to-corner",dataUi:"floating-path-node-remove-handles-button"},{kind:"button",id:"path.floating-node.make-curve",actionId:sE,label:"Curve point",shortcut:"C",icon:"to-curve",dataUi:"floating-path-node-make-curve-button"}]},DS()];if(n)return[DS()];const i=[{id:"path.floating-edit",items:[{kind:"button",id:"path.floating-edit",actionId:JM,label:"Edit",icon:"square-pen",dataUi:"floating-path-edit-button"}]},...US({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",fillRuleActionId:"path.set-fillRule",dataUiPrefix:"floating-path"})];return YS(e).length>=2&&i.push({id:"path.floating-boolean",items:[{kind:"button",id:"path.floating-boolean.union",actionId:tE,label:"Union",icon:"group",dataUi:"floating-path-boolean-union-button"},{kind:"button",id:"path.floating-boolean.subtract",actionId:nE,label:"Subtract",icon:"minus",dataUi:"floating-path-boolean-subtract-button"},{kind:"button",id:"path.floating-boolean.intersect",actionId:iE,label:"Intersect",icon:"crop",dataUi:"floating-path-boolean-intersect-button"},{kind:"button",id:"path.floating-boolean.xor",actionId:oE,label:"Exclude",icon:"ungroup",dataUi:"floating-path-boolean-xor-button"}]}),i}}],contextMenuContributions:[{id:"path.context-menu",target:"selection",order:38,actionIds:[JM,tE,nE,iE,oE],when:e=>"path"===e.selection.commonShapeType,getSections(e){const t=[{kind:"command",id:"path.edit",actionId:JM,label:"Edit path",icon:"square-pen",dataUi:"path-context-edit"}];return YS(e).length>=2&&t.push({kind:"command",id:"path.boolean.union",actionId:tE,label:"Union paths",icon:"group",dataUi:"path-context-boolean-union"},{kind:"command",id:"path.boolean.subtract",actionId:nE,label:"Subtract paths",icon:"minus",dataUi:"path-context-boolean-subtract"},{kind:"command",id:"path.boolean.intersect",actionId:iE,label:"Intersect paths",icon:"crop",dataUi:"path-context-boolean-intersect"},{kind:"command",id:"path.boolean.xor",actionId:oE,label:"Exclude paths",icon:"ungroup",dataUi:"path-context-boolean-xor"}),[{id:"path.context",title:"Path",items:t}]}}]})}],["image",GT],["text",Hv],["frame",WC],["group",fT]],mE=["select","hand","rectangle","ellipse","diamond","triangle","hexagon","star","arrow","draw","path","text","frame","eraser","laser"],yE=new Set(mE),SE=mE.map(e=>`"${e}"`).join(", "),bE=[],xE="snapshots",IE="imageBlobs",wE=null,PE=class e{editor;static SAVE_DELAY_MS=200;options;unsubscribe=null;saveTimeoutId=null;hasPendingSave=!1;isSaving=!1;saveAgainAfterCurrentSave=!1;constructor(e,t={}){this.editor=e,this.options=t}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,kb(this.editor,this.options).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()}},vE=Ab("canvas-kit.clipboard-service"),kE="system.clipboard.copy",CE="system.clipboard.cut",TE="system.clipboard.paste",ME="system.clipboard.paste-at-point",EE=[{actionId:kE,shortcut:{key:"c",accelKey:!0}},{actionId:CE,shortcut:{key:"x",accelKey:!0}},{actionId:TE,shortcut:{key:"v",accelKey:!0}}],BE=[{id:"system.selection-clipboard-context-menu",target:"selection",order:1e3,actionIds:[kE,CE],getSections:e=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:kE,actionId:kE,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(kE),dataUi:"context-menu-copy-selection-button"},{kind:"command",id:CE,actionId:CE,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(CE),dataUi:"context-menu-cut-selection-button"}]}]},{id:"system.canvas-clipboard-context-menu",target:"canvas",order:1e3,actionIds:[ME],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:ME,actionId:ME,label:"Paste here",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(TE),dataUi:"context-menu-paste-here-button"}]}]}],AE={id:"canvas-kit.clipboard",product:()=>({services:[{token:vE,create(){let e=null;return{async write(t){e=t},read:async()=>e,getMemoryPayload:()=>e}}}],createActions:({services:e})=>function(e){return[{id:kE,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!$b(e),run({context:t}){Lb({context:t,services:e})}},{id:CE,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!$b(e),run({context:t}){(async({context:e,services:t})=>{await Lb({context:e,services:t})&&e.editor.deleteSelection("user")})({context:t,services:e})}},{id:TE,isVisible:()=>!!$b(e)?.getMemoryPayload(),isEnabled:()=>!!$b(e)?.getMemoryPayload(),run({context:t}){Fb({context:t,services:e})}},{id:ME,isVisible:t=>Ub(t)&&!!$b(e)?.getMemoryPayload(),isEnabled:t=>Ub(t)&&!!$b(e)?.getMemoryPayload(),run({context:t}){Ub(t)&&Fb({context:t,services:e,atMenuPoint:!0})}}]}(e),actionShortcuts:EE,contextMenuContributions:BE})},RE="image-blob:",$E=1,LE=Xx(({editor:e,hostBridge:t,imageAssetService:n,flushSnapshot:i})=>{const o=Vx(null),r=Vx(null),{insertImageFromFile:s,replaceSelectedImage:a}=(({editor:e,imageAssetService:t,flushSnapshot:n})=>({insertImageFromFile:Nx(async({file:i,pagePoint:o,size:r})=>ex({editor:e,imageObjectUrls:t.objectUrls,source:{type:"file",file:i},pagePoint:o,size:r,flushSnapshot:n}),[e,t,n]),replaceSelectedImage:Nx(i=>ox({editor:e,file:i,imageObjectUrls:t.objectUrls,flushSnapshot:n}),[e,t,n])}))({editor:e,imageAssetService:n,flushSnapshot:i});return _x(()=>{if(t)return t.register({openInsertFilePicker(){o.current?.click()},openReplaceFilePicker(){r.current?.click()}})},[t]),_x(()=>{const t=t=>{if(e.shapeEditingStateSignal.get().session)return;if(hr(t.target))return;const n=qb(t.clipboardData);n&&(t.preventDefault(),s({file:n}))},n=t=>{var n;e.shapeEditingStateSignal.get().session||hr(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(hr(t.target))return;const n=qb(t.dataTransfer);n&&(t.preventDefault(),s({file:n,pagePoint:jb(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]),Qx(Gx,{children:[Zx("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})}}),Zx("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)}})]})}),FE=Ab("plugin-image.asset-service"),DE=new WeakSet,UE=Bb("plugin-image.product-controller"),zE=class{handlers=null;register(e){return this.handlers=e,()=>{this.handlers===e&&(this.handlers=null)}}openInsertFilePicker(){this.handlers?.openInsertFilePicker()}openReplaceFilePicker(){this.handlers?.openReplaceFilePicker()}},OE=Ab("plugin-image.toolbar-host-bridge"),XE={id:"canvas-kit.image",requires:[GT],product:({persistence:e})=>{const t=e?.flushSnapshot;return{services:[hx({flushSnapshot:t}),{token:OE,create:()=>new zE}],createActions({services:e}){const t=e.get(FE),n=e.get(OE);return t&&n?(({hostBridge:e,imageObjectUrls:t})=>[{id:ST,run(){e.openInsertFilePicker()}},{id:mT,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return Yf(t)&&!t.isLocked},run(){e.openReplaceFilePicker()}},{id:yT,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;if(!Yf(t)||!t.props.assetId)return!1;const n=e.editor.getAsset(t.props.assetId);return!(!Nf(n)||"remote"!==n.props.source.kind&&!Nb(e.editor,t.props.assetId))},run({context:e}){rx({editor:e.editor,imageObjectUrls:t})}}])({hostBridge:n,imageObjectUrls:t.objectUrls}):[]},beforeCommand({commandId:e,context:t,editor:n}){var i;"history.undo"===e||"history.redo"===e||t&&("image.smudge"===(i=e)||"image.smudge.cancel"===i||"image.smudge.confirm"===i||"image.smudge.brush-size"===i||"image.smudge.brush-color"===i)||(e=>{Bf(e).cancelIfActive()})(t?.editor??n)},assetResolverTokens:[FE],apis:[{token:UE,create:({editor:e,services:n})=>bx({editor:e,flushSnapshot:t,services:n})}],canShowToolbarDuringEditing:e=>Hf(e)||Wf(e),svgAssetInliners({services:e}){const t=e.get(FE);return t?[xx(t)]:[]},components:[{id:"canvas-kit.image-import",order:100,component:e=>Zx(Ix,{...e,flushSnapshot:t})}]}}},NE=Xx(({actionRegistry:e,editor:t,executeCommand:n})=>((({actionRegistry:e,editor:t,executeCommand:n})=>{_x(()=>{const i=i=>{if(t.getShapeEditingSession()||hr(i.target))return;const o=t.shortcuts.getActionIdForEvent({key:i.key,shiftKey:i.shiftKey,altKey:i.altKey,ctrlKey:i.ctrlKey,metaKey:i.metaKey,accelKey:i.metaKey||i.ctrlKey});if(!o)return;const r=Sb({editor:t,selectionState:t.selectionStateSignal.get(),toolState:t.toolStateSignal.get()}),s=e.getAction(o);s&&!1!==s.isVisible?.(r)&&!1!==s.isEnabled?.(r)&&(i.preventDefault(),i.stopPropagation(),n({commandId:o,context:r,run(){s.run({context:r,value:s.getValue?.(r)??null})}}))};return window.addEventListener("keydown",i,!0),()=>{window.removeEventListener("keydown",i,!0)}},[e,t,n])})({actionRegistry:e,editor:t,executeCommand:n}),null)),YE={id:"canvas-kit.keyboard-shortcuts",product:()=>({components:[{id:"canvas-kit.keyboard-shortcuts",order:0,component:NE}]})},_E="system.selection.delete",HE="system.selection.duplicate",WE="system.selection.select-all",KE="system.selection.reset-rotation",VE="system.selection.flip-horizontal",qE="system.selection.flip-vertical",jE="system.selection.send-to-back",GE="system.selection.send-backward",ZE="system.selection.bring-forward",QE="system.selection.bring-to-front",JE="system.selection.set-opacity",eB=[{actionId:HE,shortcut:{key:"d",accelKey:!0}},{actionId:WE,shortcut:{key:"a",accelKey:!0}}],tB=[{id:HE,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.duplicateSelection({source:"user"})}},{id:WE,isEnabled:e=>e.editor.getCurrentPageShapeIds().length>0,run({context:e}){e.editor.selectAllCurrentPage("user")}},{id:KE,isVisible:e=>e.selection.canResetRotation,run({context:e}){e.editor.resetSelectionRotation("user")}},{id:VE,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("horizontal","user")}},{id:qE,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("vertical","user")}},{id:jE,isVisible:e=>e.selection.count>0&&!wx(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("back","user")}},{id:GE,isVisible:e=>e.selection.count>0&&!wx(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionInParentOrder("backward","user")}},{id:ZE,isVisible:e=>e.selection.count>0&&!wx(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionInParentOrder("forward","user")}},{id:QE,isVisible:e=>e.selection.count>0&&!wx(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("front","user")}},{id:JE,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=Px(t.opacity);return e.selection.selectedShapes.every(e=>Px(e.opacity)===n)?n:null})(e),run({context:e,value:t}){if("number"!=typeof t||!Number.isFinite(t))return;const n=Px(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:_E,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.deleteSelection("user")}}],nB=[{id:"system.selection-context-menu",target:"selection",order:1010,actionIds:[HE,KE,VE,qE,QE,ZE,GE,jE],getSections(e){const t=e.selection.count>0&&!wx(e),n=[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:HE,actionId:HE,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(HE),dataUi:"context-menu-duplicate-selection-button"}]}];return(e.selection.canResetRotation||e.selection.count>0)&&n.push({id:"system.selection-transform",title:"Transform",order:20,items:[{kind:"command",id:KE,actionId:KE,label:"Reset rotation",icon:"rotate-ccw",dataUi:"context-menu-reset-rotation-button"},{kind:"command",id:VE,actionId:VE,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"context-menu-flip-horizontal-button"},{kind:"command",id:qE,actionId:qE,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:QE,actionId:QE,label:"Bring to front",icon:"chevrons-up",dataUi:"context-menu-bring-to-front-button"},{kind:"command",id:ZE,actionId:ZE,label:"Bring forward",icon:"move-up",dataUi:"context-menu-bring-forward-button"},{kind:"command",id:GE,actionId:GE,label:"Send backward",icon:"move-down",dataUi:"context-menu-send-backward-button"},{kind:"command",id:jE,actionId:jE,label:"Send to back",icon:"chevrons-down",dataUi:"context-menu-send-to-back-button"}]}),n}},{id:"system.selection-delete-context-menu",target:"selection",order:1030,actionIds:[_E],getSections:()=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"separator",id:"system.selection.delete-leading-separator"},{kind:"command",id:_E,actionId:_E,label:"Delete selection",icon:"trash-2",tone:"destructive",dataUi:"context-menu-delete-selection-button"}]}]},{id:"system.canvas-selection-context-menu",target:"canvas",order:1005,actionIds:[WE],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:WE,actionId:WE,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(WE),dataUi:"context-menu-select-all-button"}]}]}],iB=[{id:"system.selection-toolbar",surface:"selection",order:1e3,actionIds:[KE,VE,qE,jE,GE,ZE,QE,JE],getGroups(e){const t=e.selection.count>0&&!wx(e);return[{id:"system.selection-opacity",items:[{kind:"slider",id:"system.selection-opacity",actionId:JE,label:"Opacity",min:0,max:1,step:.01,dataUi:"selection-opacity-slider"}]},{id:"system.selection-actions",items:[...e.selection.canResetRotation?[{kind:"button",id:KE,actionId:KE,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:VE,actionId:VE,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"flip-selection-horizontal-button"},{kind:"button",id:qE,actionId:qE,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"flip-selection-vertical-button"},...t?[{kind:"separator",id:"system.selection.flip-order-separator"},{kind:"button",id:jE,actionId:jE,label:"Send to back",icon:"chevrons-down",dataUi:"send-selection-to-back-button"},{kind:"button",id:GE,actionId:GE,label:"Send backward",icon:"move-down",dataUi:"send-selection-backward-button"},{kind:"button",id:ZE,actionId:ZE,label:"Bring forward",icon:"move-up",dataUi:"bring-selection-forward-button"},{kind:"button",id:QE,actionId:QE,label:"Bring to front",icon:"chevrons-up",dataUi:"bring-selection-to-front-button"}]:[]]}]}},{id:"system.selection-delete-toolbar",surface:"selection",order:1020,actionIds:[_E],getGroups:()=>[{id:"system.selection-delete",items:[{kind:"separator",id:"system.selection.delete-leading-separator"},{kind:"button",id:_E,actionId:_E,label:"Delete selection",icon:"trash-2",dataUi:"delete-selection-toolbar-button"}]}]}],oB={id:"canvas-kit.selection",product:()=>({actions:tB,actionShortcuts:eB,toolbarContributions:iB,contextMenuContributions:nB})},rB=[{id:sP,getValue:e=>e.tool.activeToolId,run({context:e,value:t}){"string"==typeof t&&e.editor.tools.hasTool(t)&&e.editor.setActiveTool(t,"system")}},{id:aP,getValue:e=>e.tool.isToolLocked,run({context:e}){e.editor.toggleToolLocked("system")}}],sB=[{id:"system.canvas-tool-context-menu",target:"canvas",order:1020,actionIds:[sP],getSections:e=>[{id:"system.canvas-tools",title:"Tools",order:20,items:[{kind:"command",id:"system.canvas.select-tool",actionId:sP,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:sP,value:"hand",label:"Hand tool",icon:"hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),dataUi:"context-menu-hand-tool-button"}]}]}],aB=[{id:"system.select-tool-toolbar",surface:"tool",placement:"chrome",order:0,actionIds:[sP],getGroups:e=>[{id:"system.select-tool",items:[{kind:"button",id:"system.select-tool",actionId:sP,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:sP,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:[aP],getGroups:e=>[{id:"system.tool-lock",items:[{kind:"separator",id:"system.tool-lock-separator"},{kind:"button",id:"system.tool-lock",actionId:aP,value:!0,label:e.tool.isToolLocked?"Unlock tool":"Lock tool",icon:"lock",dataUi:"tool-lock-button"}]}]}],lB={id:"canvas-kit.tool",product:()=>({actions:rB,toolbarContributions:aB,contextMenuContributions:sB})},dB="system.view.zoom-in",cB="system.view.zoom-out",uB="system.view.reset-zoom",hB=[{id:dB,run({context:e}){e.editor.zoomAtViewportCenter(-120,"system")}},{id:cB,run({context:e}){e.editor.zoomAtViewportCenter(120,"system")}},{id:uB,run({context:e}){e.editor.resetZoom("user")}}],pB=[{id:"system.canvas-view-context-menu",target:"canvas",order:1010,actionIds:[dB,cB,uB],getSections:()=>[{id:"system.canvas-view",title:"View",order:10,items:[{kind:"command",id:dB,actionId:dB,label:"Zoom in",icon:"plus",dataUi:"context-menu-zoom-in-button"},{kind:"command",id:cB,actionId:cB,label:"Zoom out",icon:"minus",dataUi:"context-menu-zoom-out-button"},{kind:"command",id:uB,actionId:uB,label:"Reset zoom",icon:"rotate-ccw",dataUi:"context-menu-reset-zoom-button"}]}]}],gB={id:"canvas-kit.view",product:()=>({actions:hB,contextMenuContributions:pB})},fB=new WeakMap,mB={status:"starting"};export{mE as CANVAS_KIT_TOOL_IDS,yc as CanvasKitFloatingToolbarLayer,Fx as CanvasKitRoot,QP as DEFAULT_TEXT_FONT,mu as FloatingSelectionToolbarPageSpace,JP as HOST_TEXT_FONT,Sk as Packaging,mb as createCanvasKitController,yb as createCanvasKitControllerWithTools,Mx as createCanvasKitRuntime,E as createCustomShapeColor,ns as createDefaultTextFontCatalog,ts as createDefaultTextPluginOptions,Bb as createProductApiToken,Ab as createProductServiceToken,vx as createStandardCanvasKitPlugins,Pu as createTextLinkHoverPopoverPresenter,wu as createTextProductPlugin,M as createThemeShapeColor,Iu as defineCanvasPlugin,$ as getThemeColorTokenName,UE as imageProductControllerToken,A as isCustomShapeColorRef,B as isThemeShapeColorRef,vI as n,Dl as parsePackagingDocument,$d as parsePackagingDxf,D as resolveShapeColor,F as shapeColorToCssColor,PI as t,Cu as useCanvasKitLayerTree,zx as useCanvasKitRuntime,bc as useCanvasKitWheelCapture};