@yuzhouu/canvas-kit 0.1.3 → 0.1.5

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 (314) hide show
  1. package/README.md +80 -78
  2. package/_vendor/canvas-core/bindings/{BindingUtil.d.ts → bindingUtil.d.ts} +1 -1
  3. package/_vendor/canvas-core/bindings/{BindingUtilRegistry.d.ts → bindingUtilRegistry.d.ts} +1 -1
  4. package/_vendor/canvas-core/bindings/terminalBinding.d.ts +28 -0
  5. package/_vendor/canvas-core/editor/clipboard.d.ts +2 -2
  6. package/_vendor/canvas-core/editor/commands.d.ts +6 -1
  7. package/_vendor/canvas-core/editor/createEditorWithPlugins.d.ts +6 -0
  8. package/_vendor/canvas-core/editor/edgeScroll.d.ts +1 -1
  9. package/_vendor/canvas-core/editor/{Editor.d.ts → editor.d.ts} +46 -51
  10. package/_vendor/canvas-core/editor/editorComputedHelpers.d.ts +5 -5
  11. package/_vendor/canvas-core/editor/editorSelectionTransforms.d.ts +2 -2
  12. package/_vendor/canvas-core/editor/events.d.ts +1 -1
  13. package/_vendor/canvas-core/editor/{HistoryManager.d.ts → historyManager.d.ts} +1 -1
  14. package/_vendor/canvas-core/editor/index.d.ts +10 -7
  15. package/_vendor/canvas-core/editor/interactions.d.ts +2 -2
  16. package/_vendor/canvas-core/editor/internal.d.ts +1 -1
  17. package/_vendor/canvas-core/editor/managers/{BindingManager.d.ts → bindingManager.d.ts} +1 -1
  18. package/_vendor/canvas-core/editor/managers/{CameraManager.d.ts → cameraManager.d.ts} +2 -2
  19. package/_vendor/canvas-core/editor/managers/{ClipboardManager.d.ts → clipboardManager.d.ts} +1 -1
  20. package/_vendor/canvas-core/editor/managers/{DocumentSnapshotManager.d.ts → documentSnapshotManager.d.ts} +1 -1
  21. package/_vendor/canvas-core/editor/managers/{InputsManager.d.ts → inputsManager.d.ts} +1 -1
  22. package/_vendor/canvas-core/editor/managers/{InteractionTransientManager.d.ts → interactionTransientManager.d.ts} +13 -10
  23. package/_vendor/canvas-core/editor/managers/{QueryManager.d.ts → queryManager.d.ts} +7 -6
  24. package/_vendor/canvas-core/editor/managers/{RenderWindowManager.d.ts → renderWindowManager.d.ts} +1 -1
  25. package/_vendor/canvas-core/editor/managers/selectionGeometry.d.ts +5 -5
  26. package/_vendor/canvas-core/editor/managers/{SelectionLayoutManager.d.ts → selectionLayoutManager.d.ts} +2 -2
  27. package/_vendor/canvas-core/editor/managers/{SelectionManager.d.ts → selectionManager.d.ts} +1 -1
  28. package/_vendor/canvas-core/editor/managers/{SelectionOverlayManager.d.ts → selectionOverlayManager.d.ts} +4 -3
  29. package/_vendor/canvas-core/editor/managers/{ShapeEditingManager.d.ts → shapeEditingManager.d.ts} +1 -1
  30. package/_vendor/canvas-core/editor/managers/{ShapeGeometryManager.d.ts → shapeGeometryManager.d.ts} +5 -5
  31. package/_vendor/canvas-core/editor/managers/{ShapeHierarchyManager.d.ts → shapeHierarchyManager.d.ts} +3 -6
  32. package/_vendor/canvas-core/editor/managers/shapeOrder.d.ts +1 -1
  33. package/_vendor/canvas-core/editor/managers/shapeReparenting.d.ts +1 -1
  34. package/_vendor/canvas-core/editor/managers/shortcutManager.d.ts +56 -0
  35. package/_vendor/canvas-core/editor/managers/snapCalculations.d.ts +2 -2
  36. package/_vendor/canvas-core/editor/managers/snapGeometry.d.ts +2 -2
  37. package/_vendor/canvas-core/editor/managers/snapIndicators.d.ts +2 -2
  38. package/_vendor/canvas-core/editor/managers/{SnapManager.d.ts → snapManager.d.ts} +1 -1
  39. package/_vendor/canvas-core/editor/managers/{SnapSnapshotBuilder.d.ts → snapSnapshotBuilder.d.ts} +1 -1
  40. package/_vendor/canvas-core/editor/managers/snapTypes.d.ts +2 -2
  41. package/_vendor/canvas-core/editor/managers/{SpatialIndexManager.d.ts → spatialIndexManager.d.ts} +4 -4
  42. package/_vendor/canvas-core/editor/managers/{ToolManager.d.ts → toolManager.d.ts} +4 -5
  43. package/_vendor/canvas-core/editor/queries/shapeTransforms.d.ts +4 -4
  44. package/_vendor/canvas-core/editor/renderWindow.d.ts +1 -1
  45. package/_vendor/canvas-core/editor/resizeGeometry.d.ts +2 -2
  46. package/_vendor/canvas-core/editor/selection.d.ts +26 -19
  47. package/_vendor/canvas-core/editor/selectionHandleInteractions.d.ts +1 -1
  48. package/_vendor/canvas-core/editor/selectionOverlay.d.ts +7 -5
  49. package/_vendor/canvas-core/editor/{StateNode.d.ts → stateNode.d.ts} +1 -1
  50. package/_vendor/canvas-core/exports/integrity.d.ts +1 -1
  51. package/_vendor/canvas-core/exports/svg.d.ts +6 -2
  52. package/_vendor/canvas-core/geometry/{Box.d.ts → box.d.ts} +1 -1
  53. package/_vendor/canvas-core/geometry/{Ellipse2d.d.ts → ellipse2d.d.ts} +3 -3
  54. package/_vendor/canvas-core/geometry/{Geometry2d.d.ts → geometry2d.d.ts} +2 -2
  55. package/_vendor/canvas-core/geometry/index.d.ts +7 -7
  56. package/_vendor/canvas-core/geometry/{Mat.d.ts → mat.d.ts} +1 -1
  57. package/_vendor/canvas-core/geometry/{Polyline2d.d.ts → polyline2d.d.ts} +3 -3
  58. package/_vendor/canvas-core/geometry/{Rectangle2d.d.ts → rectangle2d.d.ts} +3 -3
  59. package/_vendor/canvas-core/geometry/segments.d.ts +1 -1
  60. package/_vendor/canvas-core/index.d.ts +33 -31
  61. package/_vendor/canvas-core/plugins/{types.d.ts → editorPlugin.d.ts} +10 -9
  62. package/_vendor/canvas-core/plugins/index.d.ts +1 -1
  63. package/_vendor/canvas-core/schema/snapshotSupport.d.ts +43 -0
  64. package/_vendor/canvas-core/schema/snapshots.d.ts +6 -2
  65. package/_vendor/canvas-core/shapes/capabilities.d.ts +1 -1
  66. package/_vendor/canvas-core/shapes/colors.d.ts +26 -0
  67. package/_vendor/canvas-core/shapes/{ShapeUtil.d.ts → shapeUtil.d.ts} +22 -9
  68. package/_vendor/canvas-core/shapes/{ShapeUtilRegistry.d.ts → shapeUtilRegistry.d.ts} +1 -1
  69. package/_vendor/canvas-core/surfaces/actions.d.ts +35 -0
  70. package/_vendor/canvas-core/{contextMenu.d.ts → surfaces/contextMenu.d.ts} +11 -9
  71. package/_vendor/canvas-core/{toolbar.d.ts → surfaces/toolbar.d.ts} +17 -38
  72. package/_vendor/canvas-core/tools/hand/handTool.d.ts +5 -0
  73. package/_vendor/canvas-core/tools/index.d.ts +2 -2
  74. package/_vendor/canvas-core/tools/select/selectContainment.d.ts +5 -4
  75. package/_vendor/canvas-core/tools/select/selectTool.d.ts +5 -0
  76. package/_vendor/canvas-core/tools/select/selectToolHelpers.d.ts +3 -3
  77. package/_vendor/canvas-core/tools/select/states/{BrushingState.d.ts → brushingState.d.ts} +3 -3
  78. package/_vendor/canvas-core/tools/select/states/{DraggingSelectionHandleInteractionState.d.ts → draggingSelectionHandleInteractionState.d.ts} +3 -3
  79. package/_vendor/canvas-core/tools/select/states/{IdleState.d.ts → idleState.d.ts} +2 -2
  80. package/_vendor/canvas-core/tools/select/states/index.d.ts +11 -11
  81. package/_vendor/canvas-core/tools/select/states/{PointingCanvasState.d.ts → pointingCanvasState.d.ts} +3 -3
  82. package/_vendor/canvas-core/tools/select/states/{PointingResizeHandleState.d.ts → pointingResizeHandleState.d.ts} +3 -3
  83. package/_vendor/canvas-core/tools/select/states/{PointingRotateHandleState.d.ts → pointingRotateHandleState.d.ts} +3 -3
  84. package/_vendor/canvas-core/tools/select/states/{PointingSelectionHandleInteractionState.d.ts → pointingSelectionHandleInteractionState.d.ts} +3 -3
  85. package/_vendor/canvas-core/tools/select/states/{PointingShapeState.d.ts → pointingShapeState.d.ts} +3 -3
  86. package/_vendor/canvas-core/tools/select/states/{ResizingState.d.ts → resizingState.d.ts} +3 -3
  87. package/_vendor/canvas-core/tools/select/states/{RotatingState.d.ts → rotatingState.d.ts} +3 -3
  88. package/_vendor/canvas-core/tools/select/states/{SelectStateNode.d.ts → selectStateNode.d.ts} +2 -2
  89. package/_vendor/canvas-core/tools/select/states/{TranslatingState.d.ts → translatingState.d.ts} +5 -4
  90. package/_vendor/canvas-react/components/CanvasView.d.ts +7 -4
  91. package/_vendor/canvas-react/components/PageSpace.d.ts +1 -1
  92. package/_vendor/canvas-react/components/ShapeLayer.d.ts +4 -1
  93. package/_vendor/canvas-react/components/index.d.ts +0 -2
  94. package/_vendor/canvas-react/components/overlays/BindingGuide.d.ts +24 -0
  95. package/_vendor/canvas-react/components/overlays/BindingPreviewOverlay.d.ts +1 -0
  96. package/_vendor/canvas-react/components/overlays/BrushBoxOverlay.d.ts +1 -0
  97. package/_vendor/canvas-react/components/overlays/OverlaySvgRoot.d.ts +1 -0
  98. package/_vendor/canvas-react/components/overlays/SelectionFrameOverlay.d.ts +1 -0
  99. package/_vendor/canvas-react/components/overlays/SelectionHandlesOverlay.d.ts +1 -0
  100. package/_vendor/canvas-react/components/overlays/SelectionOverlaySvg.d.ts +1 -0
  101. package/_vendor/canvas-react/components/overlays/SelectionPathOverlay.d.ts +1 -0
  102. package/_vendor/canvas-react/components/overlays/ShapeOutlineOverlay.d.ts +8 -0
  103. package/_vendor/canvas-react/components/overlays/SnapIndicatorsOverlay.d.ts +1 -0
  104. package/_vendor/canvas-react/components/useCanvasDomEvents.d.ts +21 -0
  105. package/_vendor/canvas-react/dom.d.ts +10 -0
  106. package/_vendor/canvas-react/host/canvasOverlayRegistryContext.d.ts +3 -0
  107. package/_vendor/{canvas-plugin-api/index.d.ts → canvas-react/host/canvasPlugin.d.ts} +24 -8
  108. package/_vendor/canvas-react/host/contextMenuRegistry.d.ts +3 -3
  109. package/_vendor/canvas-react/host/domEventGuards.d.ts +1 -1
  110. package/_vendor/{canvas-plugin-api/feature.d.ts → canvas-react/host/extension.d.ts} +3 -3
  111. package/_vendor/canvas-react/host/index.d.ts +8 -3
  112. package/_vendor/canvas-react/host/overlayRegistry.d.ts +18 -0
  113. package/_vendor/canvas-react/host/pluginHost.d.ts +2 -93
  114. package/_vendor/canvas-react/host/pluginHostManifest.d.ts +2 -0
  115. package/_vendor/canvas-react/host/pluginHostRuntime.d.ts +3 -0
  116. package/_vendor/canvas-react/host/pluginHostTypes.d.ts +102 -0
  117. package/_vendor/canvas-react/host/pluginHostValidation.d.ts +11 -0
  118. package/_vendor/canvas-react/host/rendererRegistry.d.ts +1 -1
  119. package/_vendor/canvas-react/host/toolbarRegistry.d.ts +7 -7
  120. package/_vendor/canvas-react/index.d.ts +2 -1
  121. package/_vendor/plugin-arrow/arrowBindingAnchors.d.ts +5 -0
  122. package/_vendor/plugin-arrow/arrowBindingGeometry.d.ts +28 -0
  123. package/_vendor/plugin-arrow/arrowGeometry.d.ts +24 -0
  124. package/_vendor/plugin-arrow/{ArrowShapeUtil.d.ts → arrowShapeUtil.d.ts} +5 -4
  125. package/_vendor/plugin-arrow/arrowTerminalBindingResolver.d.ts +5 -6
  126. package/_vendor/plugin-arrow/arrowTerminalCommands.d.ts +4 -4
  127. package/_vendor/plugin-arrow/canvas.d.ts +1 -1
  128. package/_vendor/plugin-arrow/{core.d.ts → editor.d.ts} +2 -2
  129. package/_vendor/plugin-arrow/feature.d.ts +2 -2
  130. package/_vendor/plugin-arrow/index.d.ts +6 -5
  131. package/_vendor/plugin-arrow/types.d.ts +2 -2
  132. package/_vendor/plugin-draw/DrawShapeRenderer.d.ts +4 -2
  133. package/_vendor/plugin-draw/canvas.d.ts +1 -1
  134. package/_vendor/plugin-draw/drawHitTest.d.ts +2 -2
  135. package/_vendor/plugin-draw/editor.d.ts +7 -0
  136. package/_vendor/plugin-draw/feature.d.ts +2 -2
  137. package/_vendor/plugin-draw/index.d.ts +3 -3
  138. package/_vendor/plugin-draw/types.d.ts +3 -3
  139. package/_vendor/plugin-eraser/canvas.d.ts +1 -1
  140. package/_vendor/plugin-eraser/editor.d.ts +2 -0
  141. package/_vendor/plugin-eraser/feature.d.ts +2 -2
  142. package/_vendor/plugin-eraser/index.d.ts +2 -2
  143. package/_vendor/plugin-frame/canvas.d.ts +4 -3
  144. package/_vendor/plugin-frame/editor.d.ts +7 -0
  145. package/_vendor/plugin-frame/feature.d.ts +2 -2
  146. package/_vendor/plugin-frame/{FrameShapeUtil.d.ts → frameShapeUtil.d.ts} +4 -3
  147. package/_vendor/plugin-frame/{FrameTool.d.ts → frameTool.d.ts} +1 -1
  148. package/_vendor/plugin-frame/index.d.ts +4 -4
  149. package/_vendor/plugin-geo/canvas.d.ts +6 -4
  150. package/_vendor/plugin-geo/editor.d.ts +7 -0
  151. package/_vendor/plugin-geo/feature.d.ts +2 -2
  152. package/_vendor/plugin-geo/geoGeometry.d.ts +8 -0
  153. package/_vendor/plugin-geo/{GeoTools.d.ts → geoTools.d.ts} +10 -0
  154. package/_vendor/plugin-geo/index.d.ts +4 -4
  155. package/_vendor/plugin-geo/types.d.ts +6 -4
  156. package/_vendor/plugin-group/canvas.d.ts +5 -5
  157. package/_vendor/plugin-group/editor.d.ts +7 -0
  158. package/_vendor/plugin-group/feature.d.ts +2 -2
  159. package/_vendor/plugin-group/index.d.ts +3 -3
  160. package/_vendor/plugin-image/canvas.d.ts +1 -1
  161. package/_vendor/plugin-image/{core.d.ts → editor.d.ts} +3 -3
  162. package/_vendor/plugin-image/feature.d.ts +2 -2
  163. package/_vendor/plugin-image/{ImageShapeUtil.d.ts → imageShapeUtil.d.ts} +2 -1
  164. package/_vendor/plugin-image/index.d.ts +2 -2
  165. package/_vendor/plugin-laser/canvas.d.ts +1 -1
  166. package/_vendor/plugin-laser/editor.d.ts +2 -0
  167. package/_vendor/plugin-laser/feature.d.ts +2 -2
  168. package/_vendor/plugin-laser/index.d.ts +2 -2
  169. package/_vendor/plugin-text/canvas.d.ts +5 -2
  170. package/_vendor/plugin-text/editor.d.ts +5 -0
  171. package/_vendor/plugin-text/feature.d.ts +4 -3
  172. package/_vendor/plugin-text/host/RichTextEditingBox.d.ts +3 -1
  173. package/_vendor/plugin-text/host/RichTextToolbar.d.ts +3 -1
  174. package/_vendor/plugin-text/host/TiptapTextEditor.d.ts +3 -1
  175. package/_vendor/plugin-text/host/richTextBubbleMenuPositionSync.d.ts +7 -0
  176. package/_vendor/plugin-text/host/textEditingBoxStyle.d.ts +2 -1
  177. package/_vendor/plugin-text/host/textFontLoader.d.ts +2 -1
  178. package/_vendor/plugin-text/host/textMeasurement.d.ts +4 -3
  179. package/_vendor/plugin-text/host/textMeasurementSync.d.ts +2 -1
  180. package/_vendor/plugin-text/host/textShapeRendererRuntime.d.ts +2 -1
  181. package/_vendor/plugin-text/host/textShapeSync.d.ts +3 -1
  182. package/_vendor/plugin-text/host/tiptapTextEditorController.d.ts +3 -1
  183. package/_vendor/plugin-text/index.d.ts +2 -0
  184. package/_vendor/plugin-text/textFonts.d.ts +46 -0
  185. package/_vendor/plugin-text/textShapeSvgExporter.d.ts +9 -0
  186. package/_vendor/plugin-text/textStyle.d.ts +11 -2
  187. package/_vendor/plugin-text/textTypes.d.ts +4 -4
  188. package/_vendor/store/index.d.ts +1 -1
  189. package/_vendor/store/{Store.d.ts → store.d.ts} +7 -1
  190. package/browser/localSnapshotRestore.d.ts +13 -0
  191. package/{_vendor/canvas-product-react/persistence/localSnapshotPersistence.d.ts → browser/persistence.d.ts} +16 -10
  192. package/builtins/controller/createBuiltInCanvasController.d.ts +16 -0
  193. package/builtins/controller/layerController.d.ts +9 -0
  194. package/builtins/controller/shapeCreationController.d.ts +76 -0
  195. package/builtins/extensions.d.ts +17 -0
  196. package/builtins/index.d.ts +5 -0
  197. package/chrome/CanvasKitFloatingToolbarLayer.d.ts +6 -0
  198. package/chrome/FloatingSelectionToolbarPageSpace.d.ts +9 -0
  199. package/chrome/bindings/useCanvasKitChromeControls.d.ts +27 -0
  200. package/chrome/bindings/useContextMenuSurface.d.ts +12 -0
  201. package/chrome/bindings/useSvgExport.d.ts +15 -0
  202. package/chrome/bindings/useToolbarSurfaces.d.ts +26 -0
  203. package/chrome/types.d.ts +66 -0
  204. package/chrome/useCanvasKitChromeContext.d.ts +19 -0
  205. package/controller/canvasKitController.d.ts +36 -0
  206. package/{_vendor/canvas-product-react/api/canvasProductApi.d.ts → core/controller/canvasProductController.d.ts} +11 -21
  207. package/core/controller/featureControllerRegistry.d.ts +12 -0
  208. package/core/controller/index.d.ts +4 -0
  209. package/core/controller/productLayerTree.d.ts +10 -0
  210. package/core/features/actions/canvasActionContext.d.ts +15 -0
  211. package/core/features/actions/canvasActions.d.ts +26 -0
  212. package/core/features/clipboard/clipboardContextMenuContributions.d.ts +2 -0
  213. package/core/features/clipboard/clipboardContribution.d.ts +19 -0
  214. package/{_vendor/canvas-product-react/capabilities → core/features}/clipboard/clipboardService.d.ts +3 -2
  215. package/core/features/context-menu/contextMenuActions.d.ts +12 -0
  216. package/core/features/context-menu/contextMenuContext.d.ts +6 -0
  217. package/core/features/context-menu/contextMenuContribution.d.ts +4 -0
  218. package/core/features/context-menu/viewContextMenuContributions.d.ts +2 -0
  219. package/{_vendor/canvas-product-react/capabilities/export/useSvgExport.d.ts → core/features/export/svgExport.d.ts} +11 -7
  220. package/core/features/hostActionIds.d.ts +1 -0
  221. package/core/features/toolbar/selectionContextMenuContributions.d.ts +2 -0
  222. package/core/features/toolbar/toolContextMenuContributions.d.ts +2 -0
  223. package/core/features/toolbar/toolbarContribution.d.ts +4 -0
  224. package/core/features/toolbar/toolbarLabels.d.ts +8 -0
  225. package/core/index.d.ts +23 -0
  226. package/core/runtime/productAssets.d.ts +18 -0
  227. package/core/runtime/productContributions.d.ts +9 -0
  228. package/core/runtime/productDefinition.d.ts +32 -0
  229. package/core/runtime/productEditor.d.ts +3 -0
  230. package/core/runtime/productHost.d.ts +17 -0
  231. package/{_vendor/canvas-product-react → core}/runtime/productServices.d.ts +1 -2
  232. package/{_vendor/plugin-image-product-react → features/image}/ImageImportController.d.ts +2 -2
  233. package/{_vendor/plugin-image-product-react → features/image}/imageAssetService.d.ts +2 -2
  234. package/{_vendor/plugin-image-product-react → features/image}/imageBlobStore.d.ts +1 -1
  235. package/features/image/imageFileHelpers.d.ts +35 -0
  236. package/{_vendor/plugin-image-product-react → features/image}/imageHostActions.d.ts +13 -12
  237. package/features/image/imageHostExtension.d.ts +5 -0
  238. package/features/image/imageProductController.d.ts +22 -0
  239. package/features/image/imageProductToolbarActions.d.ts +2 -0
  240. package/{_vendor/plugin-image-product-react → features/image}/imageToolbarHostBridge.d.ts +2 -2
  241. package/{_vendor/plugin-image-product-react → features/image}/index.d.ts +4 -5
  242. package/{_vendor/plugin-image-product-react → features/image}/svgImageAssetInliner.d.ts +1 -1
  243. package/{_vendor/plugin-image-product-react → features/image}/useImageImport.d.ts +5 -4
  244. package/index.css +1 -2
  245. package/index.d.ts +14 -14
  246. package/index.mjs +66 -1
  247. package/package.json +1 -11
  248. package/product/canvasKitProduct.d.ts +50 -0
  249. package/react/CanvasKitPersistenceNotice.d.ts +4 -0
  250. package/react/CanvasKitRoot.d.ts +5 -0
  251. package/react/useCanvasKitController.d.ts +5 -0
  252. package/{product/useCanvasClipboardShortcuts.d.ts → react/useCanvasKitKeyboardShortcuts.d.ts} +1 -1
  253. package/react/useCanvasKitRuntime.d.ts +4 -0
  254. package/react/useCanvasKitStartup.d.ts +9 -0
  255. package/runtime/canvasKitHostExtensions.d.ts +19 -0
  256. package/runtime/canvasKitRuntime.d.ts +19 -0
  257. package/runtime/canvasKitRuntimeInitializer.d.ts +11 -0
  258. package/_vendor/canvas-core/bindings/arrow/arrowBindingHelpers.d.ts +0 -28
  259. package/_vendor/canvas-core/tools/hand/HandTool.d.ts +0 -5
  260. package/_vendor/canvas-core/tools/select/SelectTool.d.ts +0 -5
  261. package/_vendor/canvas-product-react/api/apiRegistry.d.ts +0 -12
  262. package/_vendor/canvas-product-react/api/index.d.ts +0 -4
  263. package/_vendor/canvas-product-react/capabilities/clipboard/systemClipboard.d.ts +0 -16
  264. package/_vendor/canvas-product-react/capabilities/context-menu/systemContextMenu.d.ts +0 -17
  265. package/_vendor/canvas-product-react/capabilities/context-menu/useContextMenuSurface.d.ts +0 -12
  266. package/_vendor/canvas-product-react/capabilities/history/useHistoryControls.d.ts +0 -8
  267. package/_vendor/canvas-product-react/capabilities/pages/usePageControls.d.ts +0 -12
  268. package/_vendor/canvas-product-react/capabilities/toolbar/systemToolbar.d.ts +0 -32
  269. package/_vendor/canvas-product-react/capabilities/toolbar/useToolbarSurfaces.d.ts +0 -19
  270. package/_vendor/canvas-product-react/capabilities/zoom/useZoomControls.d.ts +0 -9
  271. package/_vendor/canvas-product-react/index.d.ts +0 -24
  272. package/_vendor/canvas-product-react/persistence/index.d.ts +0 -2
  273. package/_vendor/canvas-product-react/runtime/CanvasProductRoot.d.ts +0 -4
  274. package/_vendor/canvas-product-react/runtime/productDefinition.d.ts +0 -45
  275. package/_vendor/plugin-draw/core.d.ts +0 -7
  276. package/_vendor/plugin-eraser/core.d.ts +0 -2
  277. package/_vendor/plugin-frame/core.d.ts +0 -7
  278. package/_vendor/plugin-geo/core.d.ts +0 -7
  279. package/_vendor/plugin-group/core.d.ts +0 -7
  280. package/_vendor/plugin-image-product-react/imageProductApi.d.ts +0 -21
  281. package/_vendor/plugin-image-product-react/imageToolbarRuntime.d.ts +0 -2
  282. package/_vendor/plugin-image-product-react/snapshotGuards.d.ts +0 -1
  283. package/_vendor/plugin-laser/core.d.ts +0 -2
  284. package/_vendor/plugin-text/TextShapeSvgExporter.d.ts +0 -6
  285. package/_vendor/plugin-text/core.d.ts +0 -2
  286. package/api/canvasKitApi.d.ts +0 -29
  287. package/product/Shell.d.ts +0 -19
  288. package/product/chromeContext.d.ts +0 -70
  289. package/product/createCanvasKitEditor.d.ts +0 -6
  290. package/product/index.d.ts +0 -7
  291. package/product/persistence.d.ts +0 -3
  292. package/product/product.d.ts +0 -22
  293. package/product-CxN5NN6u.mjs +0 -4
  294. package/product.mjs +0 -1
  295. package/standard/extensions.d.ts +0 -1
  296. package/standard/index.d.ts +0 -3
  297. package/standard/standardApi.d.ts +0 -91
  298. package/standard-R17_x8HU.mjs +0 -44
  299. package/standard.mjs +0 -1
  300. /package/_vendor/canvas-core/editor/managers/{SideEffectManager.d.ts → sideEffectManager.d.ts} +0 -0
  301. /package/_vendor/canvas-core/geometry/{Vec.d.ts → vec.d.ts} +0 -0
  302. /package/_vendor/canvas-react/host/{CanvasRendererRegistryContext.d.ts → canvasRendererRegistryContext.d.ts} +0 -0
  303. /package/_vendor/plugin-arrow/{ArrowBindingUtil.d.ts → arrowBindingUtil.d.ts} +0 -0
  304. /package/_vendor/plugin-arrow/{ArrowTool.d.ts → arrowTool.d.ts} +0 -0
  305. /package/_vendor/plugin-draw/{DrawShapeUtil.d.ts → drawShapeUtil.d.ts} +0 -0
  306. /package/_vendor/plugin-draw/{DrawTool.d.ts → drawTool.d.ts} +0 -0
  307. /package/_vendor/plugin-eraser/{EraserTool.d.ts → eraserTool.d.ts} +0 -0
  308. /package/_vendor/plugin-geo/{GeoShapeUtil.d.ts → geoShapeUtil.d.ts} +0 -0
  309. /package/_vendor/plugin-group/{GroupShapeUtil.d.ts → groupShapeUtil.d.ts} +0 -0
  310. /package/_vendor/plugin-laser/{LaserTool.d.ts → laserTool.d.ts} +0 -0
  311. /package/_vendor/plugin-text/{ArrowLabelBindingUtil.d.ts → arrowLabelBindingUtil.d.ts} +0 -0
  312. /package/_vendor/plugin-text/{GeoLabelBindingUtil.d.ts → geoLabelBindingUtil.d.ts} +0 -0
  313. /package/_vendor/plugin-text/{TextShapeUtil.d.ts → textShapeUtil.d.ts} +0 -0
  314. /package/_vendor/plugin-text/{TextTool.d.ts → textTool.d.ts} +0 -0
package/index.mjs CHANGED
@@ -1 +1,66 @@
1
- import{c as o,d as e,l as s,n as t,t as a,u as i}from"./product-CxN5NN6u.mjs";import{forwardRef as n,useEffect as r,useImperativeHandle as p,useMemo as d,useState as c}from"react";import{jsx as l}from"react/jsx-runtime";var m=n(({className:o,exposeApiOnWindow:s=!1,onReady:a,style:i,...n},m)=>{const[u,h]=c(null),f=d(()=>t({exposeApiOnWindow:s,onApiDispose(){h(null)},onApiReady(o){h(o)}}),[s]);return p(m,()=>u,[u]),r(()=>{u&&a?.(u)},[u,a]),l("div",{"data-ui":"canvas-kit-component-root",className:o,style:{width:"100%",height:"100%",overflow:"hidden",...i??{}},...n,children:l(e,{product:f})})});export{o as CANVAS_KIT_TOOL_IDS,m as CanvasKit,a as canvasKitProduct,s as createCanvasKitApi,i as createCanvasKitApiWithTools,t as createCanvasKitProduct};
1
+ function e(){return Eh}function t(){return++Eh}function n(e){Rh={child:e,parentSet:new Set,below:Rh}}function i(){if(!Rh)throw new Error("Cannot stop dependency capture because no capture is active");const e=Rh;return Rh=e.below,e.parentSet}function r(e){Rh&&(Rh.parentSet.add(e),e.children.add(Rh.child))}function o(e){function t(e){for(const r of e)if(!i.has(r))if(i.add(r),"effect"===r.type)n.add(r);else if("computed"===r.type){const e=r.source;e&&t(e.children)}}const n=new Set,i=new Set;for(const r of e)t(r.children);for(const r of n)r.notify()}function s(e,t,n){return new Fh(e,t,n?.isEqual)}function a(e,t,n){return new $h(e,t,n?.isEqual)}function d(){return{id:Oh,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function l(e=Oh){return{id:Kh,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...Xh}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function c(e){return!!e&&"page"===e.typeName}function u(e){return!!e&&"shape"===e.typeName}function h(e){return!!e&&"session"===e.typeName}function p(e){return!!e&&"binding"===e.typeName}function g(e){return!!e&&"asset"===e.typeName}function m(e){return"document"===e.scope}function f(e){return{kind:"theme",slot:e}}function S(e){return{kind:"custom",value:e}}function y(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&Nh.includes(e.slot)}function x(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function b(e){return"string"==typeof e||y(e)||x(e)}function P(e){return _h[e]}function I(e,t){if(y(e))return e;if(x(e))return e;if("string"!=typeof e)return t;const n=e.trim().toLowerCase();if("transparent"===n)return"transparent";const i=qh[n];return i?f(i):e}function w(e){return"string"==typeof e?e:"custom"===e.kind?e.value:`var(${P(e.slot)}, ${Vh[e.slot]})`}function v(e,t){if("string"==typeof e)return e;if("custom"===e.kind)return e.value;const n=P(e.slot),i=Vh[e.slot];return t?.(n,i)??i}function C(e){return"string"==typeof e?"transparent"===e.trim().toLowerCase():"custom"===e.kind&&"transparent"===e.value.trim().toLowerCase()}function k(e,t){return e===t||!(!e||!t)&&("string"==typeof e||"string"==typeof t?e===t:e.kind===t.kind&&("theme"===e.kind?e.slot===t.slot:e.value===t.value))}function T(e,t,n){let i=e.computeShapeExportPageBounds(t);if(!L(i))return i;for(const r of((e,t,n)=>{const i=[];for(const r of M(e,t,n)){const t=A(e,r);t&&L(t)&&i.push(t)}return i})(e,t,n)){const e=R(i,r);if(!e)return null;i=e}return i}function B(e,t,n,i,r){const o=[];for(const s of M(e,t,n)){const t=E(e,s,i,r);t&&o.push(t)}return o}function M(e,t,n){const i=[],r=new Set;let o=t.parentId;for(;o.startsWith("shape:");){const t=o;if(r.has(t))break;r.add(t);const s=e.getShape(t);if(!s)break;n.has(s.id)&&i.push(s),o=s.parentId}return i.reverse()}function E(e,t,n,i){if(n.has(t.id))return n.get(t.id)??null;const r=e.getShapeUtil(t).getChildExportClipLocalBounds(t);if(!r||!L(r))return n.set(t.id,null),null;const o=i.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:r.x,y:r.y,width:r.w,height:r.h,transform:e.computeShapeExportToPageTransform(t).toSvgString()}}]});return n.set(t.id,o),o}function A(e,t){const n=e.getShapeUtil(t).getChildExportClipLocalBounds(t);if(!n||!L(n))return null;const i=e.computeShapeExportToPageTransform(t);return Hh.FromPoints([new zh(n.minX,n.minY),new zh(n.maxX,n.minY),new zh(n.maxX,n.maxY),new zh(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))}function R(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),r=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY);return r<n||o<i?null:new Hh(n,i,r-n,o-i)}function F(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}="${$("number"==typeof i?D(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(F).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function L(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function $(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function D(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function U(e){return e[Gh]}function z({editor:e,exporters:t,shapeIds:n}){const i=Array.from(n),r=e.getShapeExportTraversalIds(i),o=[];for(const c of r){const n=e.getShape(c);n?(H(e.computeShapeExportPageBounds(n))||o.push({kind:"missing-bounds",id:n.id,canRepair:!1}),t.get(n.type)||o.push({kind:"missing-exporter",id:n.id,canRepair:!1})):o.push({kind:"missing-shape",id:c,canRepair:!1})}const s=new Set(r),a=new Set;for(const c of U(e).getAll().filter(p)){if(!s.has(c.fromId)&&!s.has(c.toId))continue;const t=e.getShape(c.fromId),n=e.getShape(c.toId);t&&n?e.bindings.canBind(c)?(e.bindings.getConflictingBindings(c).some(e=>a.has(e.id))&&o.push({kind:"duplicate-exclusive-binding",id:c.id,canRepair:!0}),a.add(c.id)):o.push({kind:"invalid-binding",id:c.id,canRepair:!0}):o.push({kind:"missing-binding-endpoint",id:c.id,canRepair:!0})}const d=o.filter(e=>e.canRepair).length,l=o.length-d;return{requestedShapeIds:i,issues:o,repairableIssueCount:d,fatalIssueCount:l,canExport:0===l}}function H(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function Y(e){return e.added.length>0||e.updated.length>0||e.removed.length>0}function O(e){return e instanceof Map?new Map(e):new Map(Array.from(e,e=>[e.id,e]))}function K(e,t){const n=O(e),i=O(t),r={added:[],updated:[],removed:[]};for(const[o,s]of n){const e=i.get(o);e?e!==s&&r.updated.push({before:s,after:e}):r.removed.push(s)}for(const[o,s]of i)n.has(o)||r.added.push(s);return r}function X(e){return{added:[...e.removed],updated:e.updated.map(e=>({before:e.after,after:e.before})),removed:[...e.added]}}function W(e,t){const n=new Map,i=new Map,r=new Map;for(const s of e.added)n.set(s.id,s);for(const s of e.updated)i.set(s.after.id,s);for(const s of e.removed)r.set(s.id,s);for(const s of t.added){const e=r.get(s.id);if(e){r.delete(s.id),i.set(s.id,{before:e,after:s});continue}const t=i.get(s.id);t?i.set(s.id,{before:t.before,after:s}):n.set(s.id,s)}for(const s of t.updated){if(n.get(s.after.id)){n.set(s.after.id,s.after);continue}const e=r.get(s.after.id);if(e){r.delete(s.after.id),i.set(s.after.id,{before:e,after:s.after});continue}const t=i.get(s.after.id);i.set(s.after.id,t?{before:t.before,after:s.after}:{before:s.before,after:s.after})}for(const s of t.removed){if(n.get(s.id)){n.delete(s.id);continue}const e=i.get(s.id);e?(i.delete(s.id),r.set(s.id,e.before)):r.set(s.id,s)}const o={added:[],updated:[],removed:[]};for(const s of n.values())o.added.push(s);for(const s of i.values())s.before!==s.after&&o.updated.push(s);for(const s of r.values())o.removed.push(s);return o}function N(e,t){return{id:e.id,forward:W(e.forward,t),parentIds:e.parentIds}}function _(e,t){return{forward:t,inverse:X(t),label:e}}function V(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function q(e,t,n){const i=e.getShape(t);if(!i)return;const r=e.getContainingParentIdForShapeRecord(i);r&&r!==i.parentId&&e.commands.reparentShapes({ids:[t],parentId:r},n)}function j(e,t,n){const i=n?.source??"user";U(e).atomic(()=>{const n=[],r=[];for(const i of t){const t=e.getShape(i.id);if(!t)continue;const o=i.x??t.x,s=i.y??t.y,a=i.rotation??t.rotation,d=i.scaleX??t.scaleX,l=i.scaleY??t.scaleY,c=void 0===i.opacity?t.opacity:G(i.opacity,t.opacity),u=i.isHidden??t.isHidden,h=i.isLocked??t.isLocked,p=i.parentId??t.parentId,g=i.index??t.index;if(!e.canUseShapeParent(p,t.id))throw new Error(`Invalid parent id for shape ${t.id}`);if(!i.props&&o===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),f={...t,x:o,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};n.push(f),r.push({before:t,after:f})}0!==n.length&&(U(e).put(n,i),e.bindings.handleShapeChanges(r,i),((e,t,n)=>{const i=new Set(t.map(e=>e.after.id)),r=new Set;for(const a of t)Z(e,a.before,r),Z(e,a.after,r);const o=[],s=[];for(const a of r){if(i.has(a))continue;const t=e.getShape(a);if(!t||0!==t.rotation||1!==t.scaleX||1!==t.scaleY)continue;const n=e.getDescendantPageBounds(t.id);if(!n)continue;const r=t.props;if("number"!=typeof r.w||"number"!=typeof r.h)continue;if(t.x===n.x&&t.y===n.y&&r.w===n.w&&r.h===n.h)continue;const d=e.shapeUtils.get(t.type),l={...t,x:n.x,y:n.y,props:d.validateProps({...r,w:n.w,h:n.h})};o.push(l),s.push({before:t,after:l})}0!==o.length&&(U(e).put(o,n),e.bindings.handleShapeChanges(s,n))})(e,r,i))},i)}function G(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Z(e,t,n){const i=new Set([t.id]);let r=t.parentId;for(;r.startsWith("shape:");){const t=e.getShape(r);if(!t||i.has(t.id))return;i.add(t.id),e.getShapeUtil(t).shouldTransformDescendants(t)&&n.add(t.id),r=t.parentId}}function Q(e,t,n){const i=n?.source??"user",r=e.getShapeIdsIncludingDescendants(t),o=e.getUnreferencedAssetIdsAfterShapeDelete(r);U(e).atomic(()=>{e.sideEffects.runBeforeDelete("shape",r,i),U(e).remove(r,i),o.length>0&&U(e).remove(o,i),e.sideEffects.runAfterDelete("shape",r,i)},i)}function J(e,t){return e.bindings.canBind(t)}function ee(e){return Math.min(8,Math.max(.1,e))}function te(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 ne(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function ie(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],r=t[n];if(!i||!r||i.x!==r.x||i.y!==r.y)return!1}return!0}function re(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 oe(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 se(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 ae(e,t){return e.selectionFrameActive===t.selectionFrameActive&&e.selectionHandlesActive===t.selectionHandlesActive&&e.bindingPreviewActive===t.bindingPreviewActive&&e.brushBoxActive===t.brushBoxActive&&e.selectionFrameChangeCount===t.selectionFrameChangeCount&&e.selectionHandlesChangeCount===t.selectionHandlesChangeCount&&e.resizeHandleCount===t.resizeHandleCount&&e.rotateHandleCount===t.rotateHandleCount&&e.terminalHandleCount===t.terminalHandleCount&&e.middleHandleCount===t.middleHandleCount&&e.customHandleCount===t.customHandleCount&&e.boundsSummary===t.boundsSummary&&e.rotation===t.rotation&&e.strokeWidth===t.strokeWidth}function de(e,t,n){const i=new Set([e.id]);let r=e.parentId;for(;r.startsWith("shape:");){const e=r;if(i.has(e))return null;i.add(e);const n=t.get(e);if(!n)return null;r=n.parentId}return n.has(r)?r:null}function le(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],r=t[n];if(!i||!r)return!1;if(i.id!==r.id||i.shape!==r.shape||i.isSelected!==r.isSelected||!re(i.bounds,r.bounds))return!1}return!0}function ce(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 ue(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function he(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)=>he(e,t[n]));const n=e,i=t,r=Object.keys(n),o=Object.keys(i);return r.length===o.length&&r.every(e=>Object.prototype.hasOwnProperty.call(i,e)&&he(n[e],i[e]))}function pe(e){const t=(e=>{const t=new Set(e.getSelectedShapeIds());return 0===t.size?[]:e.getCurrentPageShapeIds().filter(e=>t.has(e)).filter(n=>!((e,t,n)=>{const i=new Set([t]);let r=e.getShape(t);for(;r?.parentId.startsWith("shape:");){const t=r.parentId;if(n.has(t))return!0;if(i.has(t))return!1;i.add(t),r=e.getShape(t)}return!1})(e,n,t))})(e);if(0===t.length)return null;const n=((e,t)=>{const n=e.getShapeExportTraversalIds(t),i=new Set(n);return e.getCurrentPageShapeIds().filter(e=>i.has(e))})(e,t),i=new Set(n),r=n.map(t=>e.getShape(t)).filter(e=>!!e).map(we);return 0===r.length?null:{type:"land/clipboard",version:1,source:{app:"land"},rootShapeIds:t,records:{shapes:r,bindings:me(e,r,i),assets:fe(e,r)},bounds:Se(e,n)}}function ge(e,t){const{payload:n}=t;if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"land/clipboard"===t.type&&1===t.version&&!!t.records&&Array.isArray(t.rootShapeIds)&&Array.isArray(t.records.shapes)&&Array.isArray(t.records.bindings)&&Array.isArray(t.records.assets)})(n)||0===n.records.shapes.length)return[];const i=t.source??"user",r=e.getCurrentPageId(),o=(e=>{const t=e.payload.bounds;return e.pagePoint?e.pagePoint.sub(new zh(t.x+t.w/2,t.y+t.h/2)):e.offset??np})(t),s=new Map,a=new Map,d=[];U(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=e.createAssetRecord({type:t.type,props:Ie(t.props),meta:Ie(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+o.x,y:t.y+o.y,props:n,parentId:r,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,meta:Ie(t.meta)});return a.set(t.id,i.id),{original:t,draft:i}}).map(({original:e,draft:t})=>({...t,parentId:ye(e.parentId,a,r)}));d.length>0&&e.commands.createShapesFromRecords(d,{source:i});for(const r of n.records.bindings){const t=a.get(r.fromId),n=a.get(r.toId);t&&n&&e.commands.createBinding({type:r.type,fromId:t,toId:n,props:Ie(r.props),meta:Ie(r.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 me(e,t,n){const i=[],r=new Set;for(const o of t)for(const t of e.getBindingsForShape(o.id))r.has(t.id)||n.has(t.fromId)&&n.has(t.toId)&&(r.add(t.id),i.push(we(t)));return i}function fe(e,t){const n=[],i=new Set;for(const r of t)for(const t of xe(r)){if(i.has(t))continue;const r=e.getAsset(t);r&&(i.add(t),n.push(we(r)))}return n}function Se(e,t){const n=(e=>{if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.minX),n=Math.min(n,o.minY),i=Math.max(i,o.maxX),r=Math.max(r,o.maxY);return new Hh(t,n,i-t,r-n)})(t.map(t=>e.getShapePageBounds(t)).filter(e=>!!e))??new Hh(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function ye(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function xe(e){const t=[],n=new Set,i=ue(e);return i&&(n.add(i),t.push(i)),be(e.props,n,t),t}function be(e,t,n){if(ve(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)be(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))be(i,t,n)}function Pe(e,t){if(ve(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,r]of Object.entries(e))n[i]=Pe(r,t);return n}function Ie(e){return we(e)}function we(e){if(Array.isArray(e))return e.map(we);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=we(i);return t}function ve(e){return"string"==typeof e&&e.startsWith("asset:")}function Ce(e,t,n,i,r="document"){if(t>n)throw new rp(`Unsupported ${r} snapshot schema version: ${t} is newer than ${n}`);let o=e;for(let s=t;s<n;s+=1){const e=i.find(e=>e.fromVersion===s);if(!e)throw new rp(`No ${r} snapshot migration from schema version ${s}`);o=e.up(o)}return o}function ke(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Te(e,t){return"string"==typeof e?e:t}function Be(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Me(e,t){return"boolean"==typeof e?e:t}function Ee(e){return ke(e)?e:{}}function Ae(e){return ke(e)?{x:Be(e.x,Xh.x),y:Be(e.y,Xh.y),z:Math.min(8,Math.max(.1,Be(e.z,Xh.z)))}:null}function Re(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function Fe(e,t){if(!ke(e))throw new rp(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=Be(n,NaN);if(!Number.isFinite(i)||i<1)throw new rp(`Unsupported ${t} snapshot schema version: ${String(n)}`);if(!Array.isArray(e.records))throw new rp(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:1,records:Ce(e.records,i,1,"document"===t?op:sp,t)}}function Le(e,t){const n=e.filter(e=>"page"===e.typeName),i=e.filter(e=>"shape"===e.typeName),r=e.filter(p),o=e.filter(g),s=(n.length>0?[...n].sort((e,t)=>e.index.localeCompare(t.index)):[d()]).map((e,t)=>({...e,index:String(t+1).padStart(4,"0")})),a=s[0]?.id??"page:default",l=new Set(s.map(e=>e.id)),c=[...i].sort((e,t)=>e.index.localeCompare(t.index)),u=new Map(c.map(e=>[e.id,e])),h=c.map((e,n)=>{const i=(({pageIds:e,parentId:t,shapeById:n,shapeId:i,shapeUtils:r})=>{if(t.startsWith("page:"))return e.has(t);if(t===i)return!1;const o=n.get(t);if(!o)return!1;if(!r.get(o.type).canReceiveChildren(o))return!1;const s=new Set([i]);let a=o.parentId;for(;a.startsWith("shape:");){const e=a;if(s.has(e))return!1;s.add(e);const t=n.get(e);if(!t)return!1;if(!r.get(t.type).canReceiveChildren(t))return!1;a=t.parentId}return e.has(a)})({pageIds:l,parentId:e.parentId,shapeById:u,shapeId:e.id,shapeUtils:t})?e.parentId:a,r={...e,parentId:i,index:e.index||String(n+1).padStart(6,"0")};return t.get(r.type).repairLoadedShape(r)??r}),m=new Set(h.map(e=>e.id)),f=r.filter(e=>m.has(e.fromId)&&m.has(e.toId));return[...s,...o,...h,...f]}function $e(e,t,n){const i=Fe(e,"document"),r=new Set,o=[];return i.records.forEach((e,i)=>{if(!ke(e))throw new rp("Invalid document record: expected object");if("string"!=typeof e.id)throw new rp("Invalid document record id");if(r.has(e.id))throw new rp(`Duplicate document record id: ${e.id}`);if(r.add(e.id),"page"!==e.typeName)if("shape"!==e.typeName)if("binding"!==e.typeName){if("asset"!==e.typeName)throw new rp(`Unsupported document record type: ${String(e.typeName)}`);o.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new rp("Invalid asset record id");if("string"!=typeof e.type)throw new rp("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:ke(e.props)?e.props:{},meta:Ee(e.meta)}})(e))}else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new rp("Invalid binding record id");if("string"!=typeof e.type)throw new rp("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new rp(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new rp(`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:Ee(e.meta)}})(e,n));else o.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new rp("Invalid shape record id");if("string"!=typeof e.type)throw new rp("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new rp(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:Te(e.index,String(n+1).padStart(6,"0")),x:Be(e.x,0),y:Be(e.y,0),rotation:Be(e.rotation,0),scaleX:Be(e.scaleX,1),scaleY:Be(e.scaleY,1),opacity:Math.min(1,Math.max(0,Be(e.opacity,1))),isHidden:Me(e.isHidden,!1),isLocked:Me(e.isLocked,!1),meta:Ee(e.meta),type:e.type,props:t.get(e.type).validateProps(e.props)}})(e,t,i));else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("page:"))throw new rp("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:Te(e.name,`Page ${t+1}`),index:Te(e.index,String(t+1).padStart(4,"0")),meta:Ee(e.meta)}})(e,i))}),{schemaVersion:1,records:Le(o,t)}}function De(e){const t=Fe(e,"session").records[0];if(!ke(t))return{schemaVersion:1,records:[l()]};const n=l(),i="string"==typeof t.currentPageId&&t.currentPageId.startsWith("page:")?t.currentPageId:n.currentPageId,r=(e=>{if(!ke(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Ae(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),o=(e=>{if(!ke(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Re(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:Te(t.activeToolId,n.activeToolId),isToolLocked:"boolean"==typeof t.isToolLocked?t.isToolLocked:n.isToolLocked,editingShapeId:null,shapeEditingSession:null,pageCameraById:Object.keys(r).length>0?r:n.pageCameraById,pageSelectedShapeIdsById:Object.keys(o).length>0?o:n.pageSelectedShapeIdsById,meta:Ee(t.meta)}]}}function Ue(){return zh.Zero()}function ze(e,t,n){if(n<=0)return Ue();const i=t.x-e.x,r=t.y-e.y;return 0===i&&0===r?Ue():new zh(i/n,r/n)}function He(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function Ye(e,t){return t.getExportBounds(e)}function Oe(e,t){return t.getLocalToPageTransform(e)}function Ke(e,t){const n=We(e,t);return Yh.Translate(n.x,n.y).compose(Yh.Rotate(e.rotation)).compose(Yh.Scale(e.scaleX,e.scaleY)).compose(Yh.Translate(-n.x,-n.y))}function Xe(e,t){return Oe(e,t)}function We(e,t){return t.getBounds(e).center}function Ne(e,t,n){return Ke(e,n).applyToPoint(t)}function _e(e,t,n){if(0===e.scaleX||0===e.scaleY){const i=We(e,n),r=t.sub(i).rot(-e.rotation);return i.add(new zh(0===e.scaleX?0:r.x/e.scaleX,0===e.scaleY?0:r.y/e.scaleY))}return Ke(e,n).invert().applyToPoint(t)}function Ve(e,t){return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(n=>Ne(e,n,t))}function qe(e,t){const n=Ve(e,t),i=((e,t)=>{const n=t.getBounds(e);return[new zh(n.minX,n.minY),new zh(n.maxX,n.minY),new zh(n.maxX,n.maxY),new zh(n.minX,n.maxY)].map(n=>Ne(e,n,t))})(e,t);return{bounds:Hh.FromPoints(n),center:We(e,t),corners:i,outlineVertices:n}}function je(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Ge(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Ze(e,t,n){const i=e.get(t);if(!i)return!1;const r=i.indexOf(n);if(r<0)return!1;if(1===i.length)return e.delete(t),!0;const o=i.slice();return o.splice(r,1),e.set(t,o),!0}function Qe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Je(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function et(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):Je(t,n)}function tt(e,t,n,i,r){const o=e.get(t);if(!o)return e.set(t,[n.id]),!0;if(o.includes(n.id))return!1;const s=o.slice();return s.splice(((e,t,n,i)=>{for(let r=0;r<e.length;r+=1){const o=i(e[r]);if(o&&et(n,t,o)<0)return r}return e.length})(o,n,i,r),0,n.id),e.set(t,s),!0}function nt(e,t,n,i){const r=e.get(t);if(!r)return void e.set(t,[n.id]);if(r.includes(n.id))return;let o=r.length;for(let a=0;a<r.length;a+=1){const e=i(r[a]);if(void 0!==e&&e.localeCompare(n.index)>0){o=a;break}}const s=r.slice();s.splice(o,0,n.id),e.set(t,s)}function it(e,t,n){Ze(e,t,n)}function rt(e){return u(e.before)&&u(e.after)}function ot(e){return p(e.before)&&p(e.after)}function st(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],r=t[n];if(!i||!r||!ne(i,r))return!1}return!0}function at(e,t){return st(e.outlineVertices,t.outlineVertices)&&re(e.pageBounds,t.pageBounds)&&re(e.frameBounds,t.frameBounds)&&e.rotation===t.rotation&&ne(e.rotationCenter,t.rotationCenter)&&ne(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function dt(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)<cp?0:t}function lt(e,t){const n=e.selectedShapeIdsSignal.get();if(0===n.length)return{outlineVertices:[],pageBounds:null,frameBounds:null,rotation:0,rotationCenter:null,selectionAnchorPagePoint:null,hasRotation:!1,hasCompatibleRotation:!0};const i=[],r=[],o=[];let s=1/0,a=1/0,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&&r.push(...u),!c.contributesToSelectionFrame(n,{editor:e}))continue;o.push(n);const h=t(S);h&&(i.push(...h.outlineVertices),s=Math.min(s,h.bounds.minX),a=Math.min(a,h.bounds.minY),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 Hh(s,a,d-s,l-a):null,u=!(o.length>0)||function(e){if(0===e.length)return!0;const t=dt(e[0]?.rotation??0);return e.every(e=>{return n=t,Math.abs(dt(e.rotation)-dt(n))<cp;var n})}(o),h=((e,t)=>0!==e.length&&t?dt(e[0]?.rotation??0):0)(o,u),p=o.some(e=>Math.abs(dt(e.rotation))>cp),g=c?.center??null,m=0===i.length?null:Math.abs(h)<cp||!g?Hh.FromPoints(i):Hh.FromPoints(i.map(e=>zh.RotWith(e,g,-h))),f=r.length>0?Hh.FromPoints(r):null;return{outlineVertices:i,pageBounds:c,frameBounds:m,rotation:h,rotationCenter:g,selectionAnchorPagePoint:m&&g?Math.abs(h)<cp?new zh(m.center.x,m.minY):zh.RotWith(new zh(m.center.x,m.minY),g,h):f?new zh(f.center.x,f.minY):null,hasRotation:p,hasCompatibleRotation:u}}function ct(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 ut(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function ht(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],r=t[n];if(!i||!r||!ut(i,r))return!1}return!0}function pt(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 gt(e,t){return e===t||(e&&t?ct(e.bounds,t.bounds)&&ut(e.center,t.center)&&ht(e.corners,t.corners)&&ht(e.outlineVertices,t.outlineVertices):e===t)}function mt(e){return e?e.clone():e}function ft(e){return e?e.clone():e}function St(e){return e?.map(e=>e.clone())}function yt(e){if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.minX),n=Math.min(n,o.minY),i=Math.max(i,o.maxX),r=Math.max(r,o.maxY);return new Hh(t,n,i-t,r-n)}function xt(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 bt(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),r=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY);return r<n||o<i?null:new Hh(n,i,r-n,o-i)}function Pt(e,t){return t.canReceiveChildren(e)&&!t.shouldTransformDescendants(e)}function It(e,t,n,i){const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=(a.x*o.y-a.y*o.x)/s,l=(a.x*r.y-a.y*r.x)/s;return d>=0&&d<=1&&l>=0&&l<=1?d:null}function wt(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new zh(n.minX,n.minY),new zh(n.maxX,n.minY),new zh(n.maxX,n.maxY),new zh(n.minX,n.maxY)];for(let r=0;r<i.length;r+=1){const n=i[r],o=i[(r+1)%i.length];if(n&&o&&null!==It(e,t,n,o))return!0}return!1}function vt(e,t){return Hh.FromPoints([new zh(e.minX,e.minY),new zh(e.maxX,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function Ct(e){return"top_left"===e||"left"===e||"bottom_left"===e}function kt(e){return"top_right"===e||"right"===e||"bottom_right"===e}function Tt(e){return"top_left"===e||"top"===e||"top_right"===e}function Bt(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function Mt(e){return Ct(e)!==kt(e)&&Tt(e)!==Bt(e)}function Et({handleId:e,scaleX:t,scaleY:n}){const i=Ct(e)?t<0?"right":"left":kt(e)?t<0?"left":"right":null,r=Tt(e)?n<0?"bottom":"top":Bt(e)?n<0?"top":"bottom":null;return"top"===r&&"left"===i?"top_left":"top"===r&&"right"===i?"top_right":"bottom"===r&&"right"===i?"bottom_right":"bottom"===r&&"left"===i?"bottom_left":r||i||e}function At({axis:e,startBounds:t,bounds:n,handleId:i,scale:r,isResizingFromCenter:o}){const s=Math.sign(r??1)||1;return o?s:"x"===e?Ct(i)?n.minX>=t.maxX?-1:1:kt(i)?n.maxX<=t.minX?-1:1:s:Tt(i)?n.minY>=t.maxY?-1:1:Bt(i)?n.maxY<=t.minY?-1:1:s}function Rt({requestedBounds:e,handleId:t,actualWidth:n,actualHeight:i,scaleX:r,scaleY:o,isResizingFromCenter:s}){return new Hh(s?e.center.x-n/2:Ct(t)?r<0?e.minX:e.maxX-n:kt(t)?r<0?e.maxX-n:e.minX:e.center.x-n/2,s?e.center.y-i/2:Tt(t)?o<0?e.minY:e.maxY-i:Bt(t)?o<0?e.maxY-i:e.minY:e.center.y-i/2,n,i)}function Ft({bounds:e,startBounds:t,handleId:n,aspectRatio:i,isResizingFromCenter:r,scaleX:o,scaleY:s}){if(i<=0)return{bounds:e,scaleX:o??e.w/Math.max(1,t.w),scaleY:s??e.h/Math.max(1,t.h)};let a=e.w,d=e.h;const l=Math.sign(o??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(r){const e=t.center;return{bounds:new Hh(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 Hh(l<0?e.minX:e.maxX-a,c<0?e.minY:e.maxY-d,a,d);break;case"top_right":u=new Hh(l<0?e.maxX-a:e.minX,c<0?e.minY:e.maxY-d,a,d);break;case"bottom_right":u=new Hh(l<0?e.maxX-a:e.minX,c<0?e.maxY-d:e.minY,a,d);break;case"bottom_left":u=new Hh(l<0?e.minX:e.maxX-a,c<0?e.maxY-d:e.minY,a,d);break;case"top":u=new Hh(t.center.x-a/2,c<0?t.maxY:t.maxY-d,a,d);break;case"right":u=new Hh(l<0?t.minX-a:t.minX,t.center.y-d/2,a,d);break;case"bottom":u=new Hh(t.center.x-a/2,c<0?t.minY-d:t.minY,a,d);break;case"left":u=new Hh(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 Lt(e,t){return e.x===t.x&&e.y===t.y}function $t(e){return[new zh(e.minX,e.minY),new zh(e.center.x,e.minY),new zh(e.maxX,e.minY),new zh(e.minX,e.center.y),e.center,new zh(e.maxX,e.center.y),new zh(e.minX,e.maxY),new zh(e.center.x,e.maxY),new zh(e.maxX,e.maxY)]}function Dt(e,t){return"x"===t?e.x:e.y}function Ut(e,t){return"x"===t?e.minX:e.minY}function zt(e,t){return"x"===t?e.maxX:e.maxY}function Ht(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function Yt(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Ot(e,t){return null!==Yt(e,t)}function Kt(e,t){return new Hh(e.x+t.x,e.y+t.y,e.w,e.h)}function Xt(e,t,n){return Kt(e,((e,t)=>"x"===e?new zh(t,0):new zh(0,t))(t,n))}function Wt(e){return[new zh(e.minX,e.minY),new zh(e.maxX,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)]}function Nt(e,t,n){const i=n.sub(t),r=i.len2();if(r<=1e-8)return e.dist2(t);const o=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/r));return e.dist2(new zh(t.x+i.x*o,t.y+i.y*o))}function _t(e,t,n){const i=n.sub(t),r=i.len2();if(r<=1e-8)return t.clone();const o=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/r));return new zh(t.x+i.x*o,t.y+i.y*o)}function Vt(e,t){if(0===t.length)return null;if(1===t.length){const n=t[0].clone();return{point:n,distanceSquared:e.dist2(n)}}let n=null,i=Number.POSITIVE_INFINITY;const r=2===t.length?1:t.length;for(let o=0;o<r;o+=1){const r=t[o],s=t[(o+1)%t.length];if(!r||!s)continue;const a=Nt(e,r,s);a>=i||(i=a,n=_t(e,r,s))}return n?{point:n,distanceSquared:i}:null}function qt(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 jt(e,t,n,i){let r=i+1,o=0;const s=[];for(const a of t)for(const t of n){const n=Dt(t.point,e)-Dt(a,e),d=Math.abs(n);if(!(d>i||d>r+1e-8)){if(d<r-1e-8)r=d,o=n,s.length=0;else if(Math.abs(n-o)>1e-8)continue;s.push({selectionPoint:a,candidatePoint:t.point,candidateNodeId:t.nodeId})}}return s.length>0?{type:"points",nudge:o,pairs:s}:null}function Gt(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new zh(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new zh(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new zh(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new zh(t.minX,t.maxY))}return n}function Zt(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>Ut(e.bounds,t)-Ut(n.bounds,t)),r=[];for(let o=0;o<i.length;o+=1){const e=i[o];if(e)for(let s=o+1;s<i.length;s+=1){const o=i[s];if(!o)continue;const a=zt(e.bounds,t),d=Ut(o.bounds,t);if(a>=d)continue;const l=Yt(Ht(e.bounds,t),Ht(o.bounds,t));l&&r.push({direction:n,startNode:e,endNode:o,length:d-a,breadthIntersection:l})}}return r}function Qt(e,t,n,i){const r=Yt(Ht(t.bounds,i),Ht(n.bounds,i));return r?{direction:e,startNode:t,endNode:n,length:Ut(n.bounds,i)-zt(t.bounds,i),breadthIntersection:r}:null}function Jt(e,t,n,i){const r=Ht(t,e),o=((e,t)=>"x"===t?e.w:e.h)(t,e);let s=i+1,a=null;const d=(e,t)=>{const n=Math.abs(e);0===t.length||n>i||n>=s-1e-8||(s=n,a={type:"gaps",nudge:e,gaps:t})},l=n=>({id:"selection",bounds:Xt(t,e,n)});for(const c of n){if(o<=c.length&&Ot(r,c.breadthIntersection)){const n=zt(c.startNode.bounds,e)+(c.length-o)/2-Ut(t,e),i=l(n);d(n,[Qt(c.direction,c.startNode,i,e),Qt(c.direction,i,c.endNode,e)].filter(e=>null!==e))}const n=zt(c.endNode.bounds,e)+c.length-Ut(t,e),i=l(n);if(Ot(Ht(i.bounds,e),c.breadthIntersection)){const t=Qt(c.direction,c.endNode,i,e);d(n,t?[c,t]:[])}const s=Ut(c.startNode.bounds,e)-c.length-zt(t,e),a=l(s);if(Ot(Ht(a.bounds,e),c.breadthIntersection)){const t=Qt(c.direction,a,c.startNode,e);d(s,t?[t,c]:[])}}return a}function en(e,t){return e?t?Math.abs(e.nudge)<=Math.abs(t.nudge)?e:t:e:t}function tn(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&&Lt(e.rotationCenter,t.rotationCenter)&&Lt(e.line[0],t.line[0])&&Lt(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&Lt(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&&Lt(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>Lt(e.startEdge[0],t.startEdge[0])&&Lt(e.startEdge[1],t.startEdge[1])&&Lt(e.endEdge[0],t.endEdge[0])&&Lt(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function nn(e){return"horizontal"===e.direction?{startEdge:[new zh(e.startNode.bounds.maxX,e.startNode.bounds.minY),new zh(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new zh(e.endNode.bounds.minX,e.endNode.bounds.minY),new zh(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new zh(e.startNode.bounds.minX,e.startNode.bounds.maxY),new zh(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new zh(e.endNode.bounds.minX,e.endNode.bounds.minY),new zh(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function rn(e,t,n,i){const r=qt([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),o=dn(e,r);return{id:ln(e,o,r),type:"points",axis:e,line:o,points:r,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function on(e,t,n,i){return sn(e,t,n).map(t=>rn(e,t,n,i))}function sn(e,t,n){const i=new Map;for(const r of t.pairs){const t=Dt(r.selectionPoint.add(n),e).toFixed(8),o=i.get(t);o?o.push(r):i.set(t,[r])}return Array.from(i.values()).map(e=>({type:"points",nudge:t.nudge,pairs:e}))}function an(e,t,n){return"x"===e?[new zh(t,n.minY),new zh(t,n.maxY)]:[new zh(n.minX,t),new zh(n.maxX,t)]}function dn(e,t){if(0===t.length)return[zh.Zero(),zh.Zero()];let n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(const s of t)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return"x"===e?[new zh(n,r),new zh(n,o)]:[new zh(n,r),new zh(i,r)]}function ln(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 cn(e,t,n,i,r,o){return sn(e,t,n).map(t=>((e,t,n,i,r,o)=>{const s=rn(e,t,n,i),a=t.pairs[0],d=Dt(a?.selectionPoint.add(n)??r.center,e),l=new Map(o.map(e=>[e.id,e.bounds])),c=[],u=new Set;for(const g of t.pairs){if(u.has(g.candidateNodeId))continue;u.add(g.candidateNodeId);const t=l.get(g.candidateNodeId);t&&c.push(...an(e,d,t))}const h=qt([...s.points,...an(e,d,r),...c]),p=dn(e,qt([...an(e,d,r),...c]));return{...s,id:ln(e,p,h),line:p,points:h}})(e,t,n,i,r,o))}function un(e){return{id:ln("x",[e,e],[e]),type:"points",axis:"x",line:[e.clone(),e.clone()],points:[e.clone()],rotation:0,rotationCenter:e.clone()}}function hn(e,t,n){const i="x"===e?new zh(n.x,t.y):new zh(t.x,n.y),r=qt([n.clone(),i]),o=dn(e,r);return{id:ln(e,o,r),type:"points",axis:e,line:o,points:r,rotation:0,rotationCenter:zh.Zero()}}function pn(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new zh(0,n.y):new zh(n.x,0),r=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:Kt(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:Kt(e.endNode.bounds,i)}:e.endNode}));return{id:`gaps:${r.map(e=>`${e.startNode.id}:${e.endNode.id}:${e.length.toFixed(4)}`).join("|")}`,type:"gaps",direction:r[0]?.direction??"horizontal",gaps:r.map(nn),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function gn(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():zh.RotWith(e,t.rotationCenter,-t.rotation)}function fn(e,t){return 0===t.rotation?e.clone():zh.RotWith(e,t.rotationCenter,t.rotation)}function Sn(e,t){return fn(e,t)}function yn(e,t,n,i,r){return 0===n?i:i+(e-t)/n*r}function xn({point:e,fromBounds:t,toBounds:n}){return new zh(yn(e.x,t.minX,t.w,n.minX,n.w),yn(e.y,t.minY,t.h,n.minY,n.h))}function bn({axis:e,bounds:t,point:n}){return"horizontal"===e?new zh(t.minX+t.maxX-n.x,n.y):new zh(n.x,t.minY+t.maxY-n.y)}function Pn({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new Hh(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new Hh(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function In(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function wn(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 vn(e,t){return e.terminal===t.terminal&&In(e.anchorPagePoint,t.anchorPagePoint)&&In(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function Cn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],r=t[n];if(!i||!r||!vn(i,r))return!1}return!0}function kn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],r=t[n];if(!i||!r)return!1;if(!(i.id===r.id&&i.usesSelectionPathOverlay===r.usesSelectionPathOverlay&&In(i.startPagePoint,r.startPagePoint)&&In(i.endPagePoint,r.endPagePoint)&&In(i.middlePagePoint,r.middlePagePoint)&&Cn(i.bindingSegments,r.bindingSegments)&&i.path===r.path))return!1}return!0}function Tn(e,t){return e===t||(e&&t?wn(e.bounds,t.bounds)&&e.rotation===t.rotation&&In(e.rotationCenter,t.rotationCenter)&&e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius:e===t)}function Bn(e,t){return e===t||(e&&t?wn(e.bounds,t.bounds)&&e.rotation===t.rotation&&In(e.rotationCenter,t.rotationCenter):e===t)}function Mn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Bn(e[n]??null,t[n]??null))return!1;return!0}function En(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function An(e,t){return e.id===t.id&&In(e.point,t.point)&&wn(e.bounds,t.bounds)}function Rn(e,t){return e.id===t.id&&In(e.point,t.point)&&wn(e.bounds,t.bounds)}function Fn(e,t){return e.terminal===t.terminal&&In(e.point,t.point)&&wn(e.bounds,t.bounds)}function Ln(e,t){return In(e.point,t.point)&&wn(e.bounds,t.bounds)}function $n(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&In(e.point,t.point)&&wn(e.bounds,t.bounds)}function Dn(e,t){return e.id===t.id&&In(e.point,t.point)}function Un(e,t){return e.id===t.id&&In(e.point,t.point)}function zn(e,t){return e.terminal===t.terminal&&In(e.point,t.point)}function Hn(e,t){return In(e.point,t.point)}function Yn(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&In(e.point,t.point)}function On(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1){const r=e[i],o=t[i];if(!r||!o||!n(r,o))return!1}return!0}function Kn({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 zh(e.maxX+t,e.minY-t):new zh(e.minX-t,e.maxY+t)}function Xn(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&On(e.resizeHandles,t.resizeHandles,An)&&On(e.rotateHandles,t.rotateHandles,Rn)&&On(e.terminalHandles,t.terminalHandles,Fn)&&On(e.middleHandles,t.middleHandles,Ln)&&On(e.customHandles,t.customHandles,$n):e===t)}function Wn(e,t){return e===t||(e&&t?On(e.resizeHandleAnchors,t.resizeHandleAnchors,Dn)&&On(e.rotateHandleAnchors,t.rotateHandleAnchors,Un)&&On(e.terminalHandleAnchors,t.terminalHandleAnchors,zn)&&On(e.middleHandleAnchors,t.middleHandleAnchors,Hn)&&On(e.customHandleAnchors,t.customHandleAnchors,Yn):e===t)}function Nn(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 _n(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function Vn(e,t,n,i,r){const o=e.map(e=>i(e)),s=e.every(e=>r(e)),a=o.flatMap(e=>e.terminalHandleAnchors),d=o.flatMap(e=>e.middleHandleAnchors),l=o.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,m=e[0]?.rotation??h,f=8/n,S=14/n,y=u.w<2*f,x=u.h<2*f,b=e=>0===h?e:zh.RotWith(e,p,h),P=new zh(u.minX,u.minY),I=new zh(u.center.x,u.minY),w=new zh(u.maxX,u.minY),v=new zh(u.maxX,u.center.y),C=new zh(u.maxX,u.maxY),k=new zh(u.center.x,u.maxY),T=new zh(u.minX,u.maxY),B=new zh(u.minX,u.center.y);return{resizeHandleAnchors:s&&!c&&g?[{kind:"resize",id:"top_left",point:b(P)},...y?[]:[{kind:"resize",id:"top",point:b(I)}],...y&&x?[]:[{kind:"resize",id:"top_right",point:b(w)}],...x?[]:[{kind:"resize",id:"right",point:b(v)}],...y||x?[]:[{kind:"resize",id:"bottom_right",point:b(C)}],...y?[]:[{kind:"resize",id:"bottom",point:b(k)}],...y||x?[]:[{kind:"resize",id:"bottom_left",point:b(T)}],...x?[]:[{kind:"resize",id:"left",point:b(B)}]]:[],rotateHandleAnchors:!s||c||!g||y||x?[]:[{kind:"rotate",id:"bottom_left_rotate",point:b(Kn({bounds:u,rotateOffset:S,referenceRotation:m,frameRotation:h}))}],terminalHandleAnchors:a,middleHandleAnchors:d,customHandleAnchors:l}}function qn(e,t){const n=8/t,i=n/2,r=e=>new Hh(e.x-i,e.y-i,n,n);return{resizeHandles:e.resizeHandleAnchors.map(e=>({...e,bounds:r(e.point)})),rotateHandles:e.rotateHandleAnchors.map(e=>({...e,bounds:r(e.point)})),terminalHandles:e.terminalHandleAnchors.map(e=>({...e,bounds:r(e.point)})),middleHandles:e.middleHandleAnchors.map(e=>({...e,bounds:r(e.point)})),customHandles:e.customHandleAnchors.map(e=>({...e,bounds:r(e.point)}))}}function jn(e){const t=e.getSelectedShapes();if(0===t.length)return null;if(t.some(e=>e.isLocked))return null;const n=t[0]?.parentId;if(!n)return null;if(t.some(e=>e.parentId!==n))return null;const i=e.getChildShapes(n),r=new Set(t.map(e=>e.id)),o=i.map((e,t)=>r.has(e.id)?t:-1).filter(e=>e>=0);return o.length!==t.length?null:{parentId:n,selectedCount:t.length,count:i.length,canMoveBackward:o.some(e=>e>0&&!r.has(i[e-1].id)),canMoveForward:o.some(e=>e<i.length-1&&!r.has(i[e+1].id))}}function Gn(e){const t=e.getSelectedShapes();if(1!==t.length)return null;const[n]=t;if(!n||n.isLocked)return null;const i=e.getChildShapes(n.parentId),r=i.findIndex(e=>e.id===n.id);return r<0?null:{parentId:n.parentId,index:r,count:i.length,canMoveBackward:r>0,canMoveForward:r<i.length-1}}function Zn(e,t){const n=t.map(t=>e.getShape(t)).filter(e=>!!e);if(0===n.length)return null;if(n.some(t=>t.isLocked||e.isShapeHidden(t.id)))return null;const i=n[0]?.parentId;if(!i)return null;if(n.some(e=>e.parentId!==i))return null;const r=e.getChildShapes(i),o=new Set(n.map(e=>e.id)),s=r.map((e,t)=>o.has(e.id)?t:-1).filter(e=>e>=0);return s.length!==n.length?null:{parentId:i,selectedCount:n.length,count:r.length,canMoveBackward:s.some(e=>e>0&&!o.has(r[e-1].id)),canMoveForward:s.some(e=>e<r.length-1&&!o.has(r[e+1].id))}}function Qn(e,t,n,i="user"){const r=Zn(e,t);if(!r)return!1;const o=e.getChildShapes(r.parentId),s=new Set(t),a=[...o];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 Jn(e,t,n,i="user"){const r=Zn(e,t);if(!r)return!1;const o=e.getChildShapes(r.parentId),s=new Set(t),a=[],d=[];for(const c of o)s.has(c.id)?a.push(c):d.push(c);if(a.length!==s.size)return!1;if(!("back"===n?r.canMoveBackward:r.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 ei(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 ti(e,t,n,i,r){const o=((e,t,n,i)=>{const r=new Set(n),o=e.getChildShapes(t.parentId).filter(e=>!r.has(e.id));let s=o.length;if(t.beforeId){const e=o.findIndex(e=>e.id===t.beforeId);if(-1===e)return null;s=e}return o.splice(s,0,...i),o.map((n,i)=>({id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+1)}))})(e,t,n,i);return!!o&&(e.cancelInteractionForCommand(),e.commands.updateShapes(o,{source:r}),!0)}function ni(e){const t="string"==typeof e?{key:e}:e;return{key:oi(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}}function ii(e){const t=ni(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 ri(e,t){return!(oi(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 oi(e){return e.toLowerCase()}function si(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 ai(e,t,n){return Math.min(n,Math.max(t,e))}function di(e){return 0===e.length?"none":e.map(e=>`${e.start}-${e.end-1}`).join(", ")}function li(e,t=0){if(0===e.length)return[];const n=[...e].sort((e,t)=>e.start-t.start),i=[];for(const r of n){const e=i[i.length-1];!e||r.start>e.end+t?i.push({...r}):e.end=Math.max(e.end,r.end)}return i}function ci(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function ui(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function hi(e,t,n=0){return li(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n)}function pi(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function gi(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:pi(e,t)}}function mi(e,t,n){return e.dist(((e,t,n)=>{const i=t.sub(e),r=n.sub(e),o=i.x*i.x+i.y*i.y;if(0===o)return e;const s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o));return new zh(e.x+i.x*s,e.y+i.y*s)})(t,n,e))}function fi(e,t,n,i){return((e,t,n,i)=>{const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*o.y-a.y*o.x)/s,l=(a.x*r.y-a.y*r.x)/s;return d>=0&&d<=1&&l>=0&&l<=1})(e,t,n,i)?0:Math.min(mi(e,n,i),mi(t,n,i),mi(n,e,t),mi(i,e,t))}function Si(e){const t=Fe(e,"document"),n=new Set,i=new Set,r=new Set;for(const o of t.records)yi(o)&&"string"==typeof o.type&&("shape"===o.typeName?n.add(o.type):"binding"===o.typeName?i.add(o.type):"asset"===o.typeName&&r.add(o.type));return{shapeTypes:bi(n),bindingTypes:bi(i),assetTypes:bi(r)}}function yi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function xi(e,t){return e.filter(e=>!t.has(e))}function bi(e){return[...e].sort((e,t)=>e.localeCompare(t))}function Pi(e){return[new zh(e.minX,e.minY),new zh(e.maxX,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)]}function Ii(e,t,n,i){const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=(a.x*o.y-a.y*o.x)/s,l=(a.x*r.y-a.y*r.x)/s;return d>=0&&d<=1&&l>=0&&l<=1?d:null}function wi(e,t,n){const i=e[t];return"number"==typeof i&&Number.isFinite(i)?i:n}function vi(e){return Math.min(1,Math.max(0,(96-e)/96))}function Ci(e,t,n){if(t.w<=0||t.h<=0||n<=0)return zh.Zero();const i=Math.min(n,32),r=vi(e.x),o=vi(t.w-e.x),s=vi(e.y),a=1.25*(o-r)*i,d=1.25*(vi(t.h-e.y)-s)*i;return 0===a&&0===d?zh.Zero():new zh(a,d)}function ki(e,t,n){const i=e.inputs.state.get();if("dragging"!==i.dragPhase||!i.currentPagePoint)return null;let r=i.currentPagePoint;if(!i.currentScreenPoint)return"apply_after_scroll"===n?null:{pagePoint:r,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey};const o=Ci(i.currentScreenPoint,e.viewportScreenSizeSignal.get(),t.elapsed),s=0!==o.x||0!==o.y;return s||"always_apply"===n?(s&&(e.panCamera(o),r=e.screenToPage(i.currentScreenPoint)),{pagePoint:r,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey}):null}function Ti(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 Bi(e,t,n){const i=new Set(n);if(i.has(t))return t;const r=Mi(e,t);for(const s of r)if(i.has(s.ancestorId))return s.childId;const o=r[0]?.ancestorId;return o&&n.some(t=>((e,t)=>Mi(e,t)[0]?.ancestorId??null)(e,t)===o)?t:r[r.length-1]?.ancestorId??t}function Mi(e,t){const n=[];let i=e.getShape(t),r=t;const o=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(o.has(t))return n;o.add(t);const s=e.getShape(t);if(!s)return n;e.getShapeUtil(s).shouldTransformDescendants(s)&&n.push({ancestorId:s.id,childId:r}),r=s.id,i=s}return n}function Ei({shiftKey:e,accelKey:t}){return e||t}function Ai({ctrlKey:e}){return e}function Ri(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function Fi(e,t){return Math.round(e/t)*t}function Li(e,t,n,i,r,o,s,a,d,l,c){const u=$i(d,l),h=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=xn({point:new zh(e.minX,e.minY),fromBounds:t,toBounds:n}),r=xn({point:new zh(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new Hh(Math.min(i.x,r.x),Math.min(i.y,r.y),Math.abs(r.x-i.x),Math.abs(r.y-i.y))})({bounds:t.localBounds,fromBounds:n,toBounds:i}),p=fn(h.center,u),g=e.getShapeUtil(t.shape).resizeSelectionBounds(t.shape,{handleId:s,pageCenter:p,selectionLocalBounds:h,scaleX:r,scaleY:o,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 $i(e,t){return{rotation:t,rotationCenter:e}}function Di(e,t,n,i,r,o,s,a,d,l,c){const u=$i(d,l),h=fn(Ui({point:t.startLocalPagePoint,startBounds:n,scaleX:r,scaleY:o,handleId:s,isResizingFromCenter:a}),u),p=fn(Ui({point:t.endLocalPagePoint,startBounds:n,scaleX:r,scaleY:o,handleId:s,isResizingFromCenter:a}),u),g=e.getShapeUtil(t.shape).updateSelectionPagePoints(t.shape,{pagePoints:[h,p]});c.id=t.shape.id,c.x=g.x,c.y=g.y,c.rotation=g.rotation,c.scaleX=g.scaleX,c.scaleY=g.scaleY,c.props=g.props}function Ui({point:e,startBounds:t,scaleX:n,scaleY:i,handleId:r,isResizingFromCenter:o}){const s=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:Ct(t)?e.maxX:kt(t)?e.minX:e.center.x)({startBounds:t,handleId:r,isResizingFromCenter:o}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:Tt(t)?e.maxY:Bt(t)?e.minY:e.center.y)({startBounds:t,handleId:r,isResizingFromCenter:o});return new zh(s+(e.x-s)*n,a+(e.y-a)*i)}function zi(e,t,n){const i=1===t.length;let r=null;for(const o of t){const t=e.getShapeUtil(o).getSelectionResizeAspectRatioLock(o,{editor:e,handleId:n,isOnlySelected:i});if(null!==t){if(null!==r&&r!==t)return null;r=t}}return r}function Hi(e,t,n,i){const r=e.localBounds.center,o=Sn(new zh(e.x+r.x,e.y+r.y),{rotation:n,rotationCenter:t});i.id=e.id,i.x=o.x-r.x,i.y=o.y-r.y,i.rotation=e.rotation+n}function Yi(e,t,n,i,r){const o=e.getShapeUtil(t.shape).updateSelectionPagePoints(t.shape,{pagePoints:[Sn(t.startPagePoint,{rotation:i,rotationCenter:n}),Sn(t.endPagePoint,{rotation:i,rotationCenter:n})]});r.id=t.shape.id,r.x=o.x,r.y=o.y,r.rotation=o.rotation,r.scaleX=o.scaleX,r.scaleY=o.scaleY,r.props=o.props}function Oi(e,t){let n=null;for(const i of t){const t=e.getShape(i);if(!t)return null;if(n){if(t.parentId!==n)return null}else n=t.parentId}return n}function Ki(e,t,n){const i=n?e.getContainingShapeParentIdAtPoint(t,n):e.getContainingShapeParentId(t);if(!i)return null;const r=Oi(e,t);if(n||!r||!r.startsWith("shape:")||i===r)return i;const o=e.getShape(r);return o&&e.getShapeUtil(o).canReceiveChildren(o)&&t.every(t=>{const n=e.getShapeContainment(o.id,t);return"inside"===n||"intersecting"===n})?r:i}function Xi(e,t,n){const i=Ki(e,t,n);i&&t.some(t=>e.getShape(t)?.parentId!==i)&&e.commands.reparentShapes({ids:[...t],parentId:i})}function Wi(e,t,n){return(e=>{const i=new Dh(e,()=>{t.get(),n()},void 0);return i.attach(),()=>i.detach()})(e)}function Ni(e=[]){const t=new rg;return t.registerCanvasPlugins(e),t}function _i(e,t){return(e.order??0)-(t.order??0)}function Vi(e=[]){const t=new ag;return t.registerCanvasPlugins(e),t}function qi(){return hh(lg)}function ji(e=[]){const t=new cg;return t.registerCanvasPlugins(e),t}function Gi(e=[]){const t=new ug;return t.registerEditorPlugins(e),t}function Zi(e=[]){const t=new hg;return t.registerEditorPlugins(e),t}function Qi(e,t){return t?pg:w(e)}function Ji(e){if(!e.createFeature&&!e.addExtensions)throw new Error(`Land extension "${e.name}" must define createFeature() or addExtensions().`);return new gg(e,e.addOptions?.()??{})}function er(e,t){return tr(e,t)}function tr(e,t){const n={...e};for(const[i,r]of Object.entries(t)){const t=e[i];n[i]=nr(t)&&nr(r)?tr(t,r):r}return n}function nr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ir(e){const{extensionName:t,feature:n,source:i}=e;return{id:n.id,extensionName:t,source:i,editorPluginIds:n.editorPlugins.map(e=>e.id),canvasPluginIds:n.canvasPlugins.map(e=>e.id),interactionHandlerIds:n.editorPlugins.flatMap(e=>(e.interactionHandlers??[]).map(e=>e.id)),canvasActionIds:n.editorPlugins.flatMap(e=>(e.canvasActions??[]).map(e=>e.id)),toolbarContributionIds:n.editorPlugins.flatMap(e=>(e.toolbarContributions??[]).map(e=>e.id)),toolbarContributions:n.editorPlugins.flatMap(e=>(e.toolbarContributions??[]).map(e=>({id:e.id,surface:e.surface,placement:e.placement??"context",actionIds:[...e.actionIds]}))),contextMenuContributionIds:n.editorPlugins.flatMap(e=>(e.contextMenuContributions??[]).map(e=>e.id)),contextMenuContributions:n.editorPlugins.flatMap(e=>(e.contextMenuContributions??[]).map(e=>({id:e.id,target:e.target,actionIds:[...e.actionIds]}))),domEventGuardIds:n.canvasPlugins.flatMap(e=>(e.domEventGuards??[]).map(e=>e.id)),canvasOverlayIds:n.canvasPlugins.flatMap(e=>(e.canvasOverlays??[]).map(e=>e.id)),selectionCustomHandleRendererTypes:n.canvasPlugins.flatMap(e=>(e.selectionCustomHandleRenderers??[]).map(e=>e.type)),canvasProviderIds:n.canvasPlugins.flatMap(e=>(e.canvasProviders??[]).map(e=>e.id)),canvasComponentIds:n.canvasPlugins.flatMap(e=>(e.canvasComponents??[]).map(e=>e.id)),shapeTypes:[...n.shapeTypes]}}function rr({editorPlugins:e,canvasPlugins:t,knownHostActionIds:n,rendererRegistry:i,resolvedFeatures:r}){const o=[],s=r.map(({feature:e})=>e.id),a=e.map(e=>e.id),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)),m=t.flatMap(e=>(e.canvasOverlays??[]).map(e=>e.id)),f=t.flatMap(e=>(e.selectionCustomHandleRenderers??[]).map(e=>e.type)),S=t.flatMap(e=>(e.canvasProviders??[]).map(e=>e.id)),y=t.flatMap(e=>(e.canvasComponents??[]).map(e=>e.id)),x=new Set(e.flatMap(e=>(e.shapeUtils??[]).map(e=>e.type))),b=new Set(e.flatMap(e=>(e.shapeSvgExporters??[]).map(e=>e.type))),P=new Map(e.flatMap(e=>(e.shapeCapabilities??[]).map(e=>[e.type,e]))),I=new Set(i.getRegisteredShapeTypes());or({code:"duplicate-feature-id",ids:s,issues:o,messagePrefix:"Duplicate feature id"}),or({code:"duplicate-editor-plugin-id",ids:a,issues:o,messagePrefix:"Duplicate editor plugin id"}),or({code:"duplicate-canvas-plugin-id",ids:d,issues:o,messagePrefix:"Duplicate canvas plugin id"}),or({code:"duplicate-interaction-handler-id",ids:l,issues:o,messagePrefix:"Duplicate interaction handler id"}),or({code:"duplicate-canvas-action-id",ids:c,issues:o,messagePrefix:"Duplicate canvas action id"}),or({code:"duplicate-toolbar-contribution-id",ids:u,issues:o,messagePrefix:"Duplicate toolbar contribution id"}),or({code:"duplicate-context-menu-contribution-id",ids:h,issues:o,messagePrefix:"Duplicate context menu contribution id"}),(({resolvedFeatures:e,issues:t,knownCanvasActionIds:n})=>{for(const{feature:i}of e)for(const e of i.editorPlugins)for(const r of e.toolbarContributions??[])for(const o of r.actionIds)n.has(o)||t.push({severity:"error",code:"missing-canvas-action",featureId:i.id,pluginId:e.id,shapeType:null,message:`Toolbar contribution ${r.id} references missing action ${o}.`})})({resolvedFeatures:r,issues:o,knownCanvasActionIds:p}),(({resolvedFeatures:e,issues:t,knownCanvasActionIds:n})=>{for(const{feature:i}of e)for(const e of i.editorPlugins)for(const r of e.contextMenuContributions??[])for(const o of r.actionIds)n.has(o)||t.push({severity:"error",code:"missing-context-menu-action",featureId:i.id,pluginId:e.id,shapeType:null,message:`Context menu contribution ${r.id} references missing action ${o}.`})})({resolvedFeatures:r,issues:o,knownCanvasActionIds:p}),or({code:"duplicate-dom-event-guard-id",ids:g,issues:o,messagePrefix:"Duplicate DOM event guard id"}),or({code:"duplicate-canvas-overlay-id",ids:m,issues:o,messagePrefix:"Duplicate canvas overlay id"}),or({code:"duplicate-selection-custom-handle-renderer",ids:f,issues:o,messagePrefix:"Duplicate selection custom handle renderer"}),or({code:"duplicate-canvas-provider-id",ids:S,issues:o,messagePrefix:"Duplicate canvas plugin provider id"}),or({code:"duplicate-canvas-component-id",ids:y,issues:o,messagePrefix:"Duplicate canvas plugin component id"});const w=r.flatMap(({feature:e})=>{const t=0===e.shapeTypes.length&&e.editorPlugins.some(e=>(e.toolbarContributions??[]).some(e=>"tool"===e.surface)||void 0!==e.setup);return 0===e.editorPlugins.length&&o.push({severity:"error",code:"missing-editor-plugin",featureId:e.id,pluginId:null,shapeType:null,message:`Feature ${e.id} does not include an editor plugin.`}),0!==e.canvasPlugins.length||t||o.push({severity:"error",code:"missing-canvas-plugin",featureId:e.id,pluginId:null,shapeType:null,message:`Feature ${e.id} does not include a canvas plugin.`}),0!==e.shapeTypes.length||t||o.push({severity:"error",code:"missing-shape-type",featureId:e.id,pluginId:null,shapeType:null,message:`Feature ${e.id} does not declare shape types.`}),e.shapeTypes.map(t=>{const n=P.get(t)??null,i=x.has(t),r=b.has(t),s=I.has(t),a=i&&r?"supported":"missing";return n||o.push({severity:"error",code:"missing-shape-capability",featureId:e.id,pluginId:null,shapeType:t,message:`Shape type ${t} does not have a core capability entry.`}),i||o.push({severity:"error",code:"missing-shape-util",featureId:e.id,pluginId:null,shapeType:t,message:`Shape type ${t} does not have a core shape util.`}),"supported"!==n?.reactRenderer||s||o.push({severity:"error",code:"missing-canvas-renderer",featureId:e.id,pluginId:null,shapeType:t,message:`Shape type ${t} declares React renderer support but no canvas renderer registered.`}),r||o.push({severity:"warning",code:"missing-svg-exporter",featureId:e.id,pluginId:null,shapeType:t,message:`Shape type ${t} does not have an SVG exporter.`}),{featureId:e.id,shapeType:t,hasCapability:null!==n,hasShapeUtil:i,hasSvgExporter:r,hasCanvasRenderer:s,exportSupport:a}})}),v=o.filter(e=>"error"===e.severity).length;return{verdict:0===v?"pass":"fail",issueCount:o.length,errorCount:v,warningCount:o.length-v,issues:o,featureIds:s,editorPluginIds:a,canvasPluginIds:d,interactionHandlerIds:l,canvasActionIds:c,toolbarContributionIds:u,contextMenuContributionIds:h,domEventGuardIds:g,canvasOverlayIds:m,selectionCustomHandleRendererTypes:f,canvasProviderIds:S,canvasComponentIds:y,registeredRendererTypes:Array.from(I),shapeSummaries:w}}function or({code:e,ids:t,issues:n,messagePrefix:i}){const r=new Map;for(const o of t)r.set(o,(r.get(o)??0)+1);for(const[o,s]of r)s>1&&n.push({severity:"error",code:e,featureId:null,pluginId:o,shapeType:null,message:`${i}: ${o}.`})}function sr(e){return{type:"doc",content:e.split("\n").map(e=>({type:"paragraph",content:e.length>0?[{type:"text",text:e}]:[]}))}}function ar(e){return e.content.map(e=>hr(e)).join("\n")}function dr(e){if(!e||"object"!=typeof e)return sr("");const t=e,n=Array.isArray(t.content)?t.content.map(e=>mr(e,0)).filter(e=>null!==e):[];return{type:"doc",attrs:Sr(t.attrs),content:n}}function lr(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>gr(e)).join("")??"";return`<p style="margin:0">${t.length>0?t:"<br>"}</p>`})(e)).join("")}function cr(e){return"text"===e.type&&"string"==typeof e.text}function ur(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 hr(e){return cr(e)?e.text:e.content?.map(e=>hr(e)).join("")??""}function pr(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 gr(e){if(cr(e)){const t=ur(e.marks),n=e.text.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");return t?`<span style="${pr(t)}">${n}</span>`:n}return e.content?.map(e=>gr(e)).join("")??""}function mr(e,t){if(!e||"object"!=typeof e)return null;const n=e,i="string"==typeof n.type?n.type:"paragraph",r=Array.isArray(n.content)?n.content.map(e=>function(e,t){if(!e||"object"!=typeof e||t>8)return null;const n=e;if("text"===n.type){const e=(e=>({type:"text",text:"string"==typeof e.text?e.text:"",marks:Array.isArray(e.marks)?e.marks.map(fr).filter(e=>null!==e):void 0}))(n);return e.text.length>0?e:null}return mr(n,t)}(e,t+1)).filter(e=>null!==e):[];return{type:i,attrs:Sr(n.attrs),content:r}}function fr(e){return e&&"object"==typeof e?"string"!=typeof e.type?null:{type:e.type,attrs:Sr(e.attrs)}:null}function Sr(e){if(!e||"object"!=typeof e)return;const t=Object.entries(e).map(([e,t])=>[e,yr(t)]).filter(e=>void 0!==e[1]);return t.length>0?Object.fromEntries(t):void 0}function yr(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=>yr(e,t+1)).filter(e=>void 0!==e);if(e&&"object"==typeof e){const n=Object.entries(e).map(([e,n])=>[e,yr(n,t+1)]).filter(e=>void 0!==e[1]);return Object.fromEntries(n)}}}function xr(e){return e.content.map((e,t)=>((e,t)=>{const n=br(e,t);
2
+ return Ph("p",{style:{margin:0},children:n.length>0?n:Ph("br",{})},t)})(e,`block:${t}`))}function br(e,t){return e.content?.map((e,n)=>((e,t)=>cr(e)?Ph("span",{style:ur(e.marks),children:e.text},t):br(e,t))(e,`${t}:${n}`))??[]}function Pr(){return{defaultFont:fg,defaultFontLabel:"Default",fonts:[]}}function Ir(){return wr(Pr())}function wr(e){const t=new Map;for(const n of e.fonts)vr(n.id)&&"default"!==n.id&&t.set(n.id,n);return{defaultFont:e.defaultFont,defaultFontLabel:e.defaultFontLabel,fontOptions:[{id:mg,label:e.defaultFontLabel,cssFamily:e.defaultFont.cssFamily,source:e.defaultFont.source},...t.values()],fontsById:t}}function vr(e){return"string"==typeof e&&e.trim().length>0}function Cr(e,t){return"default"===t?e.defaultFont:e.fontsById.get(t)??e.defaultFont}function kr(e,t,n){const i=Cr(t,e),r=n??("undefined"==typeof document?void 0:document);if(!r||!Tr(i.source))return Promise.resolve();const o=(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=Sg.get(e);if(t)return t;const n=new Map;return Sg.set(e,n),n})(r),a=s.get(o);if(a)return a;const d=(async(e,t)=>{const{source:n}=t;if(Tr(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 r=e.createElement("link");r.rel="stylesheet",r.href=n.cssUrl,r.dataset.landTextFont=t.id;const o=()=>i();r.addEventListener("load",o,{once:!0}),r.addEventListener("error",o,{once:!0}),(e.head??e.documentElement).appendChild(r)}))(e,t,n),void(await Br(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 r=await new i(t.family,t.src,t.descriptors).load();n.add(r)})(e,n),void(await Br(e,n)))})(r,i).catch(()=>{s.delete(o)});return s.set(o,d),d}function Tr(e){return!!e&&"system"!==e.kind}async function Br(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),r=t.sampleText??"Aa";await Promise.all(i.map(e=>n.load(`${e} 16px "${t.family}"`,r)))}function Mr(){const e=hh(yg);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function Er(e){const[,t]=Sh(e=>e+1,0);return ph(()=>Wi("useValue",e,()=>{t()}),[e]),e.get()}function Ar({children:e,className:t,dataUi:n}){const i=Mr(),r=yh(null);return mh(()=>Wi("PageSpace.transform",i.pageTransformSignal,()=>{const e=r.current;e&&(e.style.transform=i.pageTransformSignal.get().toCssString())}),[i]),Ph("div",{ref:r,"data-ui":n,className:t,style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transformOrigin:"0 0"},children:e})}function Rr({hoveredShapeId:e}){const t="undefined"!=typeof window&&"1"===new URLSearchParams(window.location.search).get("renderHostDebug");
3
+ return Ih("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:[Ph(Ar,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:Ph(xg,{hoveredShapeId:e??null})}),t?Ph(bg,{}):null]})}function Fr(){
4
+ return Ph("div",{"data-ui":"transform-descendant-ancestor-boundary",style:{position:"absolute",inset:0,border:"1px dashed #64748b",pointerEvents:"none"}})}function Lr({shapeType:e}){
5
+ return Ph("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:"frame"===e?"Drop into frame":"Drop into group"})}function $r({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?Ph(bh,{children:e}):t.reduceRight((e,t)=>Ph(Dr,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function Dr({ancestorId:e,children:t,shapeElementToPage:n}){const i=Mr(),r=Er(i.getShapeSignal(e));if(!r)return Ph(bh,{children:t});const o=((e,t,n)=>{const i=e.getShapeUtil(t).getChildClipLocalBounds(t);if(!(i&&(r=i,Number.isFinite(r.x)&&Number.isFinite(r.y)&&Number.isFinite(r.w)&&Number.isFinite(r.h)&&r.w>=0&&r.h>=0)))return null;var r;const o=e.computeShapeRenderToPageTransform(t),s=n.invert();return`polygon(${(e=>[new zh(e.minX,e.minY),new zh(e.maxX,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)])(i).map(e=>s.applyToPoint(o.applyToPoint(e))).map(Ur).join(", ")})`})(i,r,n);return o?Ph("div",{"data-ui":"shape-clip-boundary","data-clip-ancestor-id":e,style:{position:"absolute",inset:0,width:"100%",height:"100%",clipPath:o,WebkitClipPath:o,overflow:"visible"},children:t}):Ph(bh,{children:t})}function Ur(e){return`${zr(e.x)}px ${zr(e.y)}px`}function zr(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}}:{underlay:{"data-selection-binding-segment-underlay":t},segment:{"data-selection-binding-segment":t}}}function Yr({start:e,end:t,startInset:n,endInset:i,strokeWidth:r,dashSize:o,gapSize:s,kind:a,terminal:d}){const l=(({start:e,end:t,startInset:n,endInset:i})=>{const r=t.x-e.x,o=t.y-e.y,s=Math.hypot(r,o);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=r/s,u=o/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);
6
+ return Ih("g",{style:{pointerEvents:"none"},children:[Ph("line",{...c.underlay,x1:l.start.x,y1:l.start.y,x2:l.end.x,y2:l.end.y,fill:"none",stroke:wg,strokeLinecap:"round",strokeWidth:2.2*r}),Ph("line",{...c.segment,x1:l.start.x,y1:l.start.y,x2:l.end.x,y2:l.end.y,fill:"none",stroke:Ig,strokeDasharray:`${o} ${s}`,strokeLinecap:"round",strokeWidth:r})]})}function Or({path:e,strokeWidth:t,dashSize:n,gapSize:i,kind:r,terminal:o}){const s=Hr(r,o);
7
+ return Ih("g",{style:{pointerEvents:"none"},children:[Ph("path",{...s.underlay,d:e,fill:"none",stroke:wg,strokeLinecap:"round",strokeWidth:2.2*t}),Ph("path",{...s.segment,d:e,fill:"none",stroke:Ig,strokeDasharray:`${n} ${i}`,strokeLinecap:"round",strokeWidth:t})]})}function Kr({editor:e,shape:t,stroke:n,fill:i,strokeWidth:r}){const o=e.getShapePageOutlineVertices(t.id);return 0===o.length?null:Ph("polygon",{points:o.map(e=>`${e.x},${e.y}`).join(" "),fill:i,stroke:n,strokeWidth:r,strokeLinejoin:"round",strokeLinecap:"round"})}function Xr(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 Lg[Math.round(n)%Lg.length]??"default"}function Wr({handle:e,strokeWidth:t}){
8
+ return Ph("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 Nr(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function _r(){
9
+ return Ph("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:Ph(Ar,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:Ph(Xg,{})})})}function Vr(e){const t=(e=>e instanceof HTMLElement?e:null)(e);return!!t&&(!!t.isContentEditable||!!t.closest('[contenteditable="true"]')||t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)}function qr(e){return(e??("undefined"==typeof document?null:document))?.querySelector(_g)??null}function jr(e,t){const n=(e=>{const t=e?.getRootNode();return t instanceof Document||t instanceof ShadowRoot?qr(t):qr()})(t);return!!n&&(n.dispatchEvent(new WheelEvent("wheel",{altKey:e.altKey,bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,composed:!0,ctrlKey:e.ctrlKey,deltaMode:e.deltaMode,deltaX:e.deltaX,deltaY:e.deltaY,deltaZ:e.deltaZ,metaKey:e.metaKey,screenX:e.screenX,screenY:e.screenY,shiftKey:e.shiftKey,view:window})),!0)}function Gr(e,t,n,i){return{type:"pointer",name:e,timestamp:t.timeStamp,pointerId:t.pointerId,button:t.button,buttons:t.buttons,pointerType:(r=t.pointerType,"touch"===r||"pen"===r?r:"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 r}function Zr(e,t){return{type:"keyboard",name:e,...Qr(t),code:t.code}}function Qr(e){return{key:e.key,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}}function Jr(e,t){return new zh(e.clientX-t.left,e.clientY-t.top)}function eo(e,t){return(e%t+t)%t}function to(){const e=Er(Mr().currentCameraSignal);
10
+ return Ih("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:[Ph("defs",{children:Vg.map(({min:t,mid:n,step:i})=>{const r=15*i*e.z,o=((e,t)=>({x:eo(.5-e.x*e.z,t),y:eo(.5-e.y*e.z,t)}))(e,r),s=e.z<n?(a=((e,[t,n],[i,r])=>i+(e-t)/(n-t)*(r-i))(e.z,[t,n],[0,1]),Math.max(0,Math.min(1,a))):1;var a;
11
+ return Ph("pattern",{id:`land-canvas-grid-${i}`,width:r,height:r,patternUnits:"userSpaceOnUse",children:Ph("circle",{cx:o.x,cy:o.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:s})},i)})}),Vg.map(({step:e})=>Ph("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function no(e,t){return"hand"===e?t?"grabbing":"grab":"select"===e?void 0:"crosshair"}function io({canvasComponents:e,canvasProviders:t,domEventGuardRegistry:n,onContextMenuRequest:i,overlayRegistry:r,rendererRegistry:o,showGrid:s=!1}={}){const a=Mr(),d=fh(()=>o??Ni(),[o]),l=fh(()=>r??Vi(),[r]),c=fh(()=>n??ji(),[n]),u=Er(a.toolStateSignal).activeToolId,h=Er(a.shapeEditingStateSignal).session,{containerRef:p,handlers:g,hoveredShapeId:m,isPointerActive:f,surfaceCursor:S}=function({activeDomEventGuards:e,activeToolId:t,editor:n,onContextMenuRequest:i,shapeEditingSession:r}){const o=yh(null),s=yh(null),a=yh(null),d=yh(null),l=yh(null),c=yh(null),u=yh(null),[h,p]=xh(!1),[g,m]=xh(null),[f,S]=xh(void 0);ph(()=>{("select"!==t||r)&&m(null)},[t,r]);const y=uh(()=>{null!==l.current&&(cancelAnimationFrame(l.current),l.current=null),c.current=null},[]),x=uh(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(x)},[n,y]),b=uh(()=>{null===l.current&&(c.current=null,l.current=requestAnimationFrame(x))},[x]);return ph(()=>{const i=o.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 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||r)return void m(null);const s=c(),d=new zh(e.x-s.left,e.y-s.top);m(n.hitTestShape(n.screenToPage(d))?.id??null)},g=(t,r)=>"handled"===e.handle({name:t,event:r,editor:n,container:i}),f=()=>{if(!r)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)},x=(e,t)=>{if(!o.current)return;const i=Jr(t,c());n.dispatch(Gr(e,t,i,n.screenToPage(i)))},b=()=>{n.setViewportScreenSize({w:i.clientWidth,h:i.clientHeight})};l(),b();const P=e=>{if(g("key_down",e))return;if(n.getShapeEditingSession())return!Vr(e.target)&&n.handleInteractionEvent(Zr("key_down",e))?(e.preventDefault(),void e.stopPropagation()):void(Vr(e.target)||"Escape"!==e.key||e.altKey||e.ctrlKey||e.metaKey?Vr(e.target)||"Enter"!==e.key||!e.metaKey&&!e.ctrlKey||n.completeEditing("user"):n.cancelEditing("user"));if(Vr(e.target))return;const t=n.shortcuts.getTargetForEvent(Qr(e));t&&"action"!==t.type&&e.preventDefault(),n.dispatch(Zr("key_down",e))},I=e=>{g("key_up",e)||n.getShapeEditingSession()||Vr(e.target)||n.dispatch(Zr("key_up",e))},w=()=>{a.current=null,d.current=null,p(!1),m(null),y(),n.dispatch({type:"cancel",reason:"blur"})},v=e=>{if(g("wheel",e))return;e.preventDefault();const t=Jr(e,c()),i=n.screenToPage(t);n.dispatch(((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new zh(e.deltaX,e.deltaY),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}))(e,t,i))},C=e=>{if(u.current={x:e.clientX,y:e.clientY},h(u.current),f(),e.pointerId!==a.current){const t=Jr(e,c());return 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}),void g("pointer_move",e)}const t={clientX:e.clientX,clientY:e.clientY,buttons:e.buttons,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey};var i,r;r=t,(i=d.current)&&i.clientX===r.clientX&&i.clientY===r.clientY&&i.buttons===r.buttons&&i.shiftKey===r.shiftKey&&i.altKey===r.altKey&&i.ctrlKey===r.ctrlKey&&i.metaKey===r.metaKey||(d.current=t,x("pointer_move",e))},k=(e,t)=>{t.pointerId===a.current&&(a.current=null,d.current=null,p(!1),y(),i.hasPointerCapture(t.pointerId)&&i.releasePointerCapture(t.pointerId),x(e,t),"pointer_up"===e?h(u.current):m(null))},T=()=>{u.current=null,m(null),f()},B=e=>{u.current={x:e.clientX,y:e.clientY},window.setTimeout(f,0),e.pointerId===a.current?k("pointer_up",e):g("pointer_up",e)},M=e=>{u.current={x:e.clientX,y:e.clientY},f(),e.pointerId===a.current?k("pointer_cancel",e):g("pointer_cancel",e)},E=new ResizeObserver(()=>{l(),b()});window.addEventListener("keydown",P),window.addEventListener("keyup",I),window.addEventListener("blur",w),window.addEventListener("scroll",l,{passive:!0,capture:!0}),window.addEventListener("pointermove",C,{passive:!0}),window.addEventListener("pointerup",B),window.addEventListener("pointercancel",M),i.addEventListener("pointerleave",T),i.addEventListener("wheel",v,{passive:!1}),E.observe(i);const A=window.requestAnimationFrame(f);return()=>{y(),p(!1),window.cancelAnimationFrame(A),window.removeEventListener("keydown",P),window.removeEventListener("keyup",I),window.removeEventListener("blur",w),window.removeEventListener("scroll",l,!0),window.removeEventListener("pointermove",C),window.removeEventListener("pointerup",B),window.removeEventListener("pointercancel",M),i.removeEventListener("pointerleave",T),i.removeEventListener("wheel",v),E.disconnect()}},[e,t,n,r,y]),{containerRef:o,handlers:{onPointerDown:uh(t=>{const i=o.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(Vr(t.target))return;t.preventDefault(),i.focus(),i.setPointerCapture(t.pointerId);const r=i.getBoundingClientRect();s.current={left:r.left,top:r.top},a.current=t.pointerId,p(!0),d.current=null,b();const l=Jr(t,s.current);m(null),n.dispatch(Gr("pointer_down",t,l,n.screenToPage(l)))},[e,n,b]),onContextMenu:uh(e=>{const t=o.current;if(!t||!i||Vr(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,y(),n.dispatch({type:"cancel",reason:"pointer_cancel"}));const r=t.getBoundingClientRect();s.current={left:r.left,top:r.top};const l=Jr(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])},hoveredShapeId:g,isPointerActive:h,surfaceCursor:f}}({activeDomEventGuards:c,activeToolId:u,editor:a,onContextMenuRequest:i,shapeEditingSession:h});
12
+ return Ih("div",{ref:p,"data-ui":Ng,className:"land-canvas__surface",tabIndex:0,style:{cursor:S??no(u,f)},...g,children:[s?Ph(to,{}):null,Ph(sg.Provider,{value:d,children:Ph(lg.Provider,{value:l,children:Ih(ro,{providers:t,children:[
13
+ Ph(Rr,{hoveredShapeId:m}),e?.map(({id:e,component:t})=>Ph(t,{},e)),
14
+ Ph(_r,{})]})})})]})}function ro({children:e,providers:t}){
15
+ return Ph(bh,{children:t?.reduceRight((e,{id:t,component:n})=>Ph(n,{children:e},t),e)??e})}function oo(e){return u(e)&&"text"===e.type}function so(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 ao(e){return so(e.getDefaultShapeProps("text"))}function lo(e,t,n="user"){const i={...ao(e),...t.props,richText:t.props?.richText??sr("")},[r]=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(!oo(r))throw new Error("Failed to create text shape");return r}function co(e){try{return e.view.dom.isConnected}catch{return!1}}function uo(e){!e.isDestroyed&&co(e)&&(e.view.dom.focus(),e.view.focus())}function ho(e){if(!co(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,r=e instanceof HTMLElement?e:e.parentElement,o=!!n&&!!i&&null!==r&&r.contains(n)&&r.contains(i);return{type:o?t.type:null,text:o?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 po(e,t=Qg){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function go(e,t){return Cr(t,e).cssFamily}function mo(e){return po(e)}function fo(e){const t=po(e);return Jg[t]??Math.ceil(1.4*t)}function So(e,t=1){return Math.max(1,Math.ceil(fo(e)*t))}function yo(e){switch(e){case"middle":return"center";case"end":return"right";default:return"left"}}function xo(e,t,n){return 0===ar(e).trim().length?bo(t):Po(t,(i=lr(e),r={width:t.props.autoSize?void 0:t.props.w,shape:t,fontCatalog:n},Io(document).measureHtml(i,r)));var i,r}function bo(e){const t=e.props.autoSize?16:e.props.w,n=So(e.props.size);if(e.props.w!==t||e.props.h!==n)return{w:t,h:n}}function Po(e,t){const n=e.props.autoSize?Math.max(16,Math.ceil(t.w)):e.props.w,i=Math.max(So(e.props.size),Math.ceil(t.h));if(n!==e.props.w||i!==e.props.h)return{w:n,h:i}}function Io(e){const t=tm.get(e);if(t)return t;const n=new em(e);return tm.set(e,n),n}function wo(e,t,n){n&&"normal"!==n&&"auto"!==n&&(e.style[t]=n)}function vo({shapeId:e,editor:t,fontCatalog:n}){return{shapeId:e,isDestroyed:()=>t.isDestroyed,isConnected:()=>!t.isDestroyed&&co(t),isFocused:()=>!t.isDestroyed&&co(t)&&t.view.dom.contains(document.activeElement),getValue:()=>dr(t.getJSON()),setValue(e){t.commands.setContent(e)},focus(){uo(t)},focusEnd(){!t.isDestroyed&&co(t)&&t.commands.focus("end")},focusSelectAll(){!t.isDestroyed&&co(t)&&(uo(t),t.chain().focus().selectAll().run())},focusAtPagePoint(e,n){((e,t,n)=>{uo(t);const i=e.pageToScreen(new zh(n.x,n.y)),r=t.view.posAtCoords({left:i.x,top:i.y})?.pos;r?t.chain().focus().setTextSelection(r).run():t.chain().focus().selectAll().run()})(e,t,n)},getSelectionSnapshot:()=>t.isDestroyed||!co(t)?{type:null,text:null}:ho(t),collapseSelectionAtClientPoint(e,n){!t.isDestroyed&&co(t)&&"Range"===ho(t).type&&((e,t,n)=>{if(e.isDestroyed||!co(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&&co(t))return function(e,t,n){if(0===e.getText().trim().length)return bo(t);const i=((e,t)=>{const n=e.ownerDocument.defaultView?.getComputedStyle(e);return Io(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)),Po(t,i)}(t,e,n)},onCompositionStateChange(e){if(t.isDestroyed)return()=>{};const n=t.view.dom,i=()=>e(!0),r=()=>e(!1);return n.addEventListener("compositionstart",i),n.addEventListener("compositionend",r),()=>{n.removeEventListener("compositionstart",i),n.removeEventListener("compositionend",r),e(!1)}}}}function Co(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 ko(e){return e instanceof Element&&null!==e.closest('[data-ui="rich-text-formatting-toolbar"]')}function To({editor:e,landEditor:t}){const n=fh(()=>({strategy:"fixed",placement:"top",offset:Co("--toolbar-floating-offset",8),flip:!0,shift:{padding:Co("--toolbar-floating-shift-padding",8)}}),[]);return function({landEditor:e,textEditor:t}){const n=yh(null);ph(()=>{if("undefined"==typeof window)return;const i=Wi("RichTextBubbleMenu.positionSync",e.pageTransformSignal,()=>{null===n.current&&(n.current=window.requestAnimationFrame(()=>{n.current=null,(e=>{e.isDestroyed||e.view.dispatch(e.state.tr.setMeta(nm,im))})(t)}))});return()=>{i(),null!==n.current&&(window.cancelAnimationFrame(n.current),n.current=null)}},[e,t])}({landEditor:t,textEditor:e}),e.isDestroyed?null:Ih(Mh,{editor:e,pluginKey:nm,updateDelay:0,resizeDelay:0,appendTo:Mo,shouldShow:Eo,options:n,"data-ui":"rich-text-formatting-toolbar",onWheelCapture:Bo,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:[
16
+ Ph("div",{"data-ui":"rich-text-formatting-toolbar-title",style:{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"},children:"Text"}),
17
+ Ph("div",{"aria-hidden":"true",style:{width:"var(--toolbar-separator-width)",height:"var(--toolbar-separator-height)",background:"var(--border)",margin:"0 var(--toolbar-separator-margin-inline)"}}),rm.map(t=>Ph(Ao,{editor:e,format:t.id,label:t.label,shortcut:t.shortcut,dataUi:t.dataUi,children:t.content},t.id))]})}function Bo(e){jr(e.nativeEvent,e.currentTarget)&&(e.preventDefault(),e.stopPropagation())}function Mo(){return document.body}function Eo({editor:e,element:t,view:n}){return e.isEditable&&!e.isDestroyed&&!e.state.selection.empty&&(n.hasFocus()||t.contains(document.activeElement))}function Ao({editor:e,format:t,label:n,shortcut:i,dataUi:r,children:o}){const s=yh(!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()}};
18
+ return Ph("button",{type:"button","aria-label":n,"aria-pressed":a,title:`${n} (${i})`,disabled:d,"data-ui":r,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:{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)",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:o})}function Ro({landEditor:e,shape:t,fontCatalog:n,initialRichText:i,className:r,editorStyle:o,onReady:s,onDispose:a,onRichTextChange:d}){const[l,c]=xh(0),u=yh(null),h=uh(e=>{const i=u.current;if(i?.editor===e)return i.controller;const r=vo({shapeId:t.id,editor:e,fontCatalog:n});return u.current={editor:e,controller:r},r},[n,t.id]),p=vh({extensions:om,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 ph(()=>{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]),ph(()=>{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]),Ih(bh,{children:[p?Ph(To,{editor:p,landEditor:e,version:l}):null,Ph(wh,{editor:p,className:r,style:o})]})}function Fo({editor:e,controller:t,shapeId:n,request:i,onApplied:r,attempt:o=0}){if(!t.isDestroyed())if(t.isConnected())(({editor:e,controller:t,shapeId:n,request:i,onApplied:r})=>{if(!t.isDestroyed())t.focus(),i&&i.shapeId===n?"selectAll"===i.entryMode?(window.requestAnimationFrame(()=>{!t.isDestroyed()&&t.isConnected()&&t.focusSelectAll()}),e.consumeShapeEditingEntryRequest(i.id),r?.(i)):"placeCaret"===i.entryMode&&i.caretPagePoint?(t.focusAtPagePoint(e,i.caretPagePoint),e.consumeShapeEditingEntryRequest(i.id),r?.(i)):(t.focusEnd(),e.consumeShapeEditingEntryRequest(i.id),r?.(i)):(t.focusEnd(),r?.(i))})({editor:e,controller:t,shapeId:n,request:i,onApplied:r});else{if(o>=4)return;window.requestAnimationFrame(()=>{Fo({editor:e,controller:t,shapeId:n,request:i,onApplied:r,attempt:o+1})})}}function Lo(e,t,n){if(t.isDestroyed()||!t.isConnected())return;const i=t.measure(n);i&&Do(e,n,i,"user")}function $o(e,t,n,i="system"){const r=xo(t.props.richText,t,n);r&&Do(e,t,r,i)}function Do(e,t,n,i){const r=e.getShape(t.id);oo(r)&&r.props.w===n.w&&r.props.h===n.h||e.commands.updateShapes([{id:t.id,props:n}],{source:i})}function Uo({shapeId:e,markId:t,fontCatalog:n}){const i=Mr(),r=Er(i.getShapeSignal(e)),o=Er(i.shapeEditingStateSignal).session;return oo(r)&&o?.shapeId===r.id?Ph(zo,{shape:r,session:o,fontCatalog:n},`${r.id}:${t}`):null}function zo({shape:e,session:t,fontCatalog:n}){const i=Mr(),r=yh(e.props.richText),o=(e=>{const t=yh(e);return ph(()=>{t.current=e},[e]),t})(e),s=Er(i.shapeEditingEntryRequestSignal),a=yh(null),[d,l]=xh(null),[c,u]=xh(null),h=uh(({editor:e,controller:t})=>{l(e.isDestroyed?null:e),u(t)},[]),p=uh(({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:r,fontCatalog:o}){const s=yh(t.props.richText),a=yh(!1),d=yh(null),l=uh(({controller:n,richText:i})=>{if(a.current||!n.isConnected())return;const l=dr(i);s.current=l,((e,t,n,i,r="user")=>{const o=e.getShape(t);oo(o)&&e.commands.updateShapes([{id:o.id,props:{richText:n,..."number"==typeof i?.w?{w:i.w}:null,..."number"==typeof i?.h?{h:i.h}:null}}],{source:r})})(e,t.id,l,n.measure(r.current)??xo(l,r.current,o),"user"),((e,t,n,i)=>{null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,Lo(e,t,n.current)},0)})(e,n,r,d)},[e,o,r,t.id]);return ph(()=>()=>{null!==d.current&&(window.clearTimeout(d.current),d.current=null)},[]),mh(()=>{n&&i&&!n.isDestroyed&&i.isConnected()&&Lo(e,i,t)},[e,i,t,n]),ph(()=>{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]),ph(()=>{if(i)return i.onCompositionStateChange(t=>{e.setShapeEditingComposition(t,"system")})},[e,i]),ph(()=>{if(!i||!i.isConnected())return;let n=!1;return kr(t.props.font,o).then(()=>{!n&&i.isConnected()&&Lo(e,i,r.current)}),()=>{n=!0}},[e,o,r,i,t.props.font]),l}({editor:i,shape:e,tiptapEditor:d,richTextController:c,latestShapeRef:o,fontCatalog:n});(({editor:e,shapeId:t,session:n,tiptapEditor:i,richTextController:r,entryRequest:o,consumedEntryRequestIdRef:s})=>{const a=yh(null),d=yh(null);ph(()=>{if(!r||r.isDestroyed()||!r.isConnected())return;let e=!1,t=null,n=0;const i=()=>{e||r.isDestroyed()||null===s.current&&(r.isFocused()||(r.focus(),n+=1,r.isFocused()||n>=4||(t=window.setTimeout(i,16))))},o=window.requestAnimationFrame(()=>{i()});return()=>{e=!0,window.cancelAnimationFrame(o),null!==t&&window.clearTimeout(t)}},[s,r,t]),ph(()=>{i&&!i.isDestroyed&&r&&null===s.current&&d.current!==n.markId&&(d.current=n.markId,window.setTimeout(()=>{Fo({editor:e,controller:r,shapeId:t,request:{id:-1,shapeId:n.shapeId,entryMode:n.entryMode,caretPagePoint:n.caretPagePoint}})},0))},[s,e,r,n.caretPagePoint,n.entryMode,n.markId,n.shapeId,t,i]),ph(()=>{i&&!i.isDestroyed&&r&&o&&o.shapeId===t&&s.current!==o.id&&Fo({editor:e,controller:r,shapeId:t,request:o,onApplied(e){e&&(s.current=e.id)}})},[s,e,o,r,t,i]),ph(()=>{if(!i||!r||i.isDestroyed||!r.isConnected())return;const t=r;"selectAll"===n.entryMode&&window.requestAnimationFrame(()=>{"Range"!==t.getSelectionSnapshot().type&&t.focusSelectAll()});const o=a.current,s=n.caretPagePoint;if("placeCaret"===n.entryMode&&s&&(o?.markId!==n.markId||o.entryMode!==n.entryMode)){a.current={markId:n.markId,entryMode:n.entryMode};const i={x:s.x,y:s.y};window.requestAnimationFrame(()=>{Fo({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,r,i])})({editor:i,shapeId:e.id,session:t,tiptapEditor:d,richTextController:c,entryRequest:s,consumedEntryRequestIdRef:a});const m=(({editor:e,shapeId:t,richTextController:n})=>{const i=yh(null);return{onPointerDownCapture:uh(r=>{if(r.stopPropagation(),ko(r.target))return void(i.current=null);if(0!==r.button||1!==r.detail||!n||n.isDestroyed())return void(i.current=null);const o=e.getShapeEditingSession();i.current=o&&o.shapeId===t&&!o.isComposing&&"Range"===n.getSelectionSnapshot().type?{pointerId:r.pointerId,clientX:r.clientX,clientY:r.clientY,moved:!1}:null},[e,n,t]),onPointerMoveCapture:uh(e=>{const t=i.current;if(!t||t.pointerId!==e.pointerId)return;const n=e.clientX-t.clientX,r=e.clientY-t.clientY;n*n+r*r>=16&&(t.moved=!0)},[]),onPointerUpCapture:uh(r=>{const o=i.current;if(i.current=null,ko(r.target))return;if(!o||o.pointerId!==r.pointerId||o.moved||!n||n.isDestroyed())return;const s=e.getShapeEditingSession();if(!s||s.shapeId!==t||s.isComposing)return;const a=r.clientX,d=r.clientY;window.setTimeout(()=>{n.isDestroyed()||"Range"!==n.getSelectionSnapshot().type||n.collapseSelectionAtClientPoint(a,d)},0)},[e,n,t]),onPointerCancel:uh(()=>{i.current=null},[])}})({editor:i,shapeId:e.id,richTextController:c}),f=((e,t)=>fh(()=>({color:w(e.props.color),fontFamily:go(e.props.font,t),fontSize:mo(e.props.size),lineHeight:`${fo(e.props.size)}px`,textAlign:yo(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);
19
+ return Ph("div",{"data-ui":"text-editing-box","data-shape-id":e.id,"data-mount-target-kind":"shape",onPointerDown:e=>{e.stopPropagation()},onPointerDownCapture:m.onPointerDownCapture,onPointerMoveCapture:m.onPointerMoveCapture,onPointerUpCapture:m.onPointerUpCapture,onPointerCancel:m.onPointerCancel,onContextMenu:e=>{e.stopPropagation()},onDragStart:e=>{e.preventDefault()},style:f,children:Ph(Ro,{landEditor:i,shape:e,fontCatalog:n,initialRichText:r.current,className:"land-text-editor__content",editorStyle:{height:"100%",minHeight:"100%"},onReady:h,onDispose:p,onRichTextChange:g})})}function Ho({fontCatalog:e=Ir()}={}){return{id:"land.text.react",domEventGuards:[am],canvasComponents:[{id:"land.text.default-font-preload",component:()=>Ph(Yo,{fontCatalog:e})}],shapeRenderers:[{type:"text",component:t=>Ph(Oo,{...t,fontCatalog:e})}]}}function Yo({fontCatalog:e}){return ph(()=>{kr(mg,e)},[e]),null}function Oo({shape:e,editor:t,isHovered:n,fontCatalog:i}){const{isEditingThisShape:r,editingHost:o}=function(e,t,n){const i=Er(e.shapeEditingStateSignal).session,r=i?.shapeId===t.id,o=i&&r?Ph(Uo,{shapeId:i.shapeId,markId:i.markId,fontCatalog:n},i.shapeId+":"+i.markId):null;return(({editor:e,shape:t,isEditingThisShape:n,fontCatalog:i})=>{mh(()=>{if(n)return;$o(e,t,i);let r=!1;return kr(t.props.font,i).then(()=>{if(r)return;const n=e.getShape(t.id);oo(n)&&n.props.font===t.props.font&&$o(e,n,i)}),()=>{r=!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:r,fontCatalog:n}),{isEditingThisShape:r,editingHost:o}}(t,e,i);
20
+ return Ih("div",{"data-editing-hidden":r?"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:w(e.props.color),fontFamily:go(e.props.font,i),fontSize:mo(e.props.size),lineHeight:`${fo(e.props.size)}px`,textAlign:yo(e.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none"},children:[
21
+ Ph("div",{style:{opacity:r?0:void 0},children:xr(e.props.richText)}),
22
+ Ph("div",{"data-ui":"text-editor-host-slot","data-shape-id":e.id,"data-active":r?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:o}),n?Ph("div",{"aria-hidden":"true","data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 2px ${pg}`,inset:0,pointerEvents:"none",position:"absolute"}}):null]})}function Ko(e){return so(e)}function Xo(e,t,n){const i=e.getBindingsToShape(t).find(e=>e.type===n);if(!i)return null;const r=e.getShape(i.fromId);return oo(r)?r:null}function Wo(e,t){const n=ao(e);e.history.mark(t.historyMarkId);const i=lo(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 No(e,t){const n=e.getShape(t);if(!oo(n))return null;const i=e.getBindingsFromShape(t).find(e=>e.type in gm);if(!i)return null;const r=i.type;return{label:n,ownerId:i.toId,bindingType:r,behavior:gm[r]}}function _o(e,t,n){e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:n.isExisting?n.editMarkId:n.createMarkId,reuseExistingMark:!n.isExisting},"user")}function Vo(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function qo(e){return Math.max(.01,e.props.scale)}function jo(e){return e.props.w*qo(e)}function Go(e){return e.props.h*qo(e)}function Zo(e){return new Hh(0,0,jo(e),Go(e))}function Qo(e){return"left"===e||"right"===e}function Jo(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>es(e))??[];return{tag:"p",attrs:{style:"margin:0"},children:t.length>0?t:[{tag:"br"}]}})(e))}function es(e){if(cr(e)){const t=(e=>{const t=ur(e.marks);return t?pr(t):void 0})(e);return t?{tag:"span",attrs:{style:t},children:[e.text]}:e.text}return{tag:"span",children:e.content?.map(e=>es(e))??[]}}function ts(e,t,n){return[`color:${t.resolveColor(e.props.color)}`,`font-family:${go(e.props.font,n)}`,`font-size:${mo(e.props.size)}px`,`line-height:${fo(e.props.size)}px`,`text-align:${yo(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 ns(e){return"shape"===e?.typeName&&"arrow"===e.type}function is(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function rs(e,t,n){const i=e.computeShapePageCenter(n),r=((e,t)=>e.getShapeUtil(t).getSelectionOverlayInfo(t,{editor:e}).middlePagePoint?.clone()??null)(e,n)??(e=>{const t=e.props,n=os(t.start),i=os(t.end),r=ss(t.bend)??0;if(!n||!i)return null;const o=zh.Med(n,i).add(i.sub(n).len()?i.sub(n).per().normalize().mul(-r):new zh(0,r)),s=new zh(e.x+(e=>ss(e.props.w)??1)(e)/2,e.y+(e=>ss(e.props.h)??1)(e)/2),a=new zh(e.x+o.x,e.y+o.y);if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return a;const d=a.sub(s);return s.add(new zh(d.x*e.scaleX,d.y*e.scaleY).rot(e.rotation))})(n)??i,o=Math.max(24,120);return{x:r.x-o*t.props.scale/2,y:r.y-t.props.h*t.props.scale/2,rotation:n.rotation,props:{w:o}}}function os(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 zh(t.x,t.y):null}function ss(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function as(e){return"shape"===e?.typeName&&"geo"===e.type}function ds(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function ls(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function cs(e,t){const n=e.props[t];return"number"==typeof n&&Number.isFinite(n)?n:null}function us(e,t){const n=cs(e,"h");return!n||t.props.ownerBaseHeight<=0||n===t.props.ownerBaseHeight?null:{...e,props:{...e.props,h:t.props.ownerBaseHeight}}}function hs(e,t,n){const i=e.computeShapeLocalBounds(n),r=e.computeShapePageCenter(n),o=Math.max(16,i.w-32);return{x:r.x-o*t.props.scale/2,y:r.y-t.props.h*t.props.scale/2,rotation:n.rotation,props:{w:o}}}function ps(){let e=null;const t=()=>{e=null};return{id:"land.text.interactions",editorEvent:{handleEvent(n,i){if("select"!==n.getActiveToolId())return"continue";if("pointer"===i.type&&"pointer_up"===i.name)return((e,t,n,i)=>{if(!n||n.pointerId!==t.pointerId)return i(),"continue";if(i(),(t.clickCount??1)>=2)return"continue";const r=t.pagePoint.x-n.originPagePoint.x,o=t.pagePoint.y-n.originPagePoint.y;if(r*r+o*o>9)return"continue";const s=e.getShape(n.shapeId);return s&&oo(s)&&e.canEditShape(s)?(e.startEditingShape({shapeId:s.id,entryMode:"placeCaret",caretPagePoint:t.pagePoint,markId:Im,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&&oo(t)&&n.canEditShape(t)?(n.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:Im},"user"),"handled"):"continue"}return"click"===i.type&&"double_click"===i.name?(t(),((e,t)=>{const n=e.hitTestShape(t.pagePoint);return n?oo(n)?e.canEditShape(n)?(e.startEditingShape({shapeId:n.id,entryMode:"selectAll",markId:Im},"user"),"handled"):"continue":"geo"===n.type?((e,t)=>{if(t.isLocked)return"continue";const n=Xo(e,t.id,pm);return _o(e,n??((e,t)=>{const n=hs(e,gs(t,{...ao(e),autoSize:!1,textAlign:"middle"}),t);return Wo(e,{bindingType:pm,owner:t,historyMarkId:km,index:`${t.index}${bm}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})})(e,t),{editMarkId:Cm,createMarkId:km,isExisting:!!n}),"handled"})(e,n):(e=>"arrow"===e.type)(n)?((e,t)=>{if(t.isLocked)return"continue";const n=Xo(e,t.id,hm);return _o(e,n??((e,t)=>{const n=rs(e,gs(t,{...ao(e),autoSize:!1,textAlign:"middle"}),t);return Wo(e,{bindingType:hm,owner:t,historyMarkId:vm,index:`${t.index}${ym}`,layout:n,bindingProps:{labelPosition:.5}})})(e,t),{editMarkId:wm,createMarkId:vm,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||!oo(i)||!t.canEditShape(i))return"continue";const r=t.getShapeEditingSession();return r&&r.shapeId!==i.id?t.completeEditing("user")?(t.startEditingShape({shapeId:i.id,entryMode:"placeCaret",caretPagePoint:n.pagePoint,markId:Im,preserveInteraction:!0},"user"),"handled"):"handled":(!r&&(n.clickCount??1)<2&&((e,t)=>{const n=e.getSelectedShapeIds();if(1!==n.length)return!1;if(n[0]===t)return!0;const i=No(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 gs(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 ms({fontCatalog:e=Ir()}={}){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 fm],shapeSvgExporters:[new Sm(e)],bindingUtils:[new Pm,new xm],interactionHandlers:[ps()],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")}},xs("color",e),xs("font",e),xs("size",e),xs("textAlign",e),bs("color",e),bs("font",e),bs("size",e),bs("textAlign",e)],toolbarContributions:[{id:"text.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[ng],getGroups:e=>[{id:"text.tools",items:[{kind:"button",id:"text.tool.text",actionId:ng,value:"text",label:"Text",shortcut:e.editor.shortcuts.getToolShortcutLabel("text"),icon:"type",dataUi:"text-tool-button"}]}]},Ss(e),fs(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 lm(e),{shortcut:"t"})}}}function fs(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:()=>ys({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"})}}function Ss(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:()=>ys({colorActionId:"text.default-color",fontActionId:"text.default-font",fontCatalog:e,sizeActionId:"text.default-size",textAlignActionId:"text.default-textAlign",dataUiPrefix:"text-default"})}}function ys({colorActionId:e,fontActionId:t,fontCatalog:n,sizeActionId:i,textAlignActionId:r,dataUiPrefix:o}){return[{id:`${o}.style-color`,items:[{kind:"swatches",id:`${o}.color`,actionId:e,label:"Color",options:Tm.map(e=>({...e,dataUi:`${o}-color-${e.label.toLowerCase()}-button`}))}]},{id:`${o}.style-font`,items:[{kind:"segmented",id:`${o}.font`,actionId:t,options:n.fontOptions.map(e=>({value:e.id,label:e.label,dataUi:`${o}-font-${e.id}-button`}))}]},{id:`${o}.style-size`,items:[{kind:"stepper",id:`${o}.size`,actionId:i,label:"Size",options:Bm.map(e=>({value:e.value,label:e.label,dataUi:`${o}-size-${e.id}-button`}))}]},{id:`${o}.style-align`,items:[{kind:"segmented",id:`${o}.align`,actionId:r,options:Mm.map(e=>({...e,dataUi:`${o}-align-${e.value}-button`}))}]}]}function xs(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?!k(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:n,value:i}){const r=Ps(e,i,t);if(void 0===r)return;const o=n.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:r}}));0!==o.length&&n.editor.commands.updateShapes(o,{source:"user"})}}}function bs(e,t){return{id:`text.default-${e}`,isVisible:e=>"text"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("text")[e],run({context:n,value:i}){const r=Ps(e,i,t);void 0!==r&&n.editor.updateDefaultShapeProps("text",{[e]:r})}}}function Ps(e,t,n){if("color"===e)return b(t)?I(t,f("text-slate")):void 0;if("font"===e){if("string"!=typeof t)return;return((e,t)=>"default"===t||vr(t)&&e.fontsById.has(t))(n,t)?t:void 0}if("size"===e){if("number"!=typeof t||!Number.isFinite(t))return;return Bm.some(e=>e.value===t)?t:void 0}return"string"==typeof t&&Mm.some(e=>e.value===t)?t:void 0}function Is({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){
23
+ return Ph("div",{"data-ui":n,className:ws("land-canvas__floating-toolbar-layer",t),children:e})}function ws(...e){return e.filter(Boolean).join(" ")}function vs({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",offset:i=8,surfaces:r}){const o=r.floatingSelectionToolbarPageAnchor;return r.showFloatingSelectionToolbar&&o?Ph(Cs,{anchor:o,className:t,dataUi:n,editor:r.context.editor,offset:i,onWheelCapture:ks,children:e}):null}function Cs({anchor:e,children:t,className:n,dataUi:i,editor:r,offset:o,onWheelCapture:s}){const a=yh(null);return mh(()=>Wi("PageAnchoredChromeSurface.scale",r.cameraZoomSignal,()=>{const e=a.current;if(!e)return;const t=r.cameraZoomSignal.get();e.style.transform=`scale(${1/t}) translateY(calc(-100% - ${o}px))`}),[r,o]),Ph(Ar,{dataUi:`${i}-page-space`,className:Ts("land-canvas__floating-selection-page-space",n),children:Ph("div",{ref:a,"data-ui":i,className:"land-canvas__floating-selection-anchor",onWheelCapture:s,style:{left:e.x,top:e.y,transformOrigin:"0 0",willChange:"transform"},children:t})})}function ks(e){jr(e.nativeEvent,e.currentTarget)&&(e.preventDefault(),e.stopPropagation())}function Ts(...e){return e.filter(Boolean).join(" ")}function Bs(e){return Math.max(0,Math.min(1,e))}function Ms(e,t,n){const i=e.getShapeUtil(t);return Ne(t,((e,t,n)=>{const i=e.computeShapeBounds(t);return new zh(i.minX+i.w*n.x,i.minY+i.h*n.y)})(e,t,n),i)}function Es(e,t,n,i){return((e,t,n,i)=>e.getShapeUtil(t).resolveBindingPoint(t,{rawPagePoint:n,oppositePagePoint:i}))(e,t,Ms(e,t,n),i)}function As(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 zh(e.x+e.props.w/2,e.y+e.props.h/2),i=t.sub(n);return n.add(new zh(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))})(e,new zh(e.x+n.x,e.y+n.y))}function Rs(e){return"start"===e?"end":"start"}function Fs(e,t,n){const i=((e,t)=>{const n=Us(e.x,t.x),i=Us(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 Ls(e,t,n){return Fs(e,"start"===t?n:As(e,"start"),"end"===t?n:As(e,"end"))}function $s(e){return Hs(new zh(e.props.start.x,e.props.start.y).add(new zh(e.x,e.y)),new zh(e.props.end.x,e.props.end.y).add(new zh(e.x,e.y)),e.props.bend)}function Ds(e,t,n){const i=zh.Med(e,t),r=t.sub(e);if(r.len()<1e-6)return 0;const o=r.per().normalize();return-js(n.sub(i),o)}function Us(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 zs(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Hs(e,t,n){const i=function(e,t=0){return((e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t)(e,t)}(n,0),r=((e,t,n)=>{const i=zh.Med(e,t),r=t.sub(e),o=r.len()?r.per().normalize():new zh(0,-1);return i.add(o.mul(-n))})(e,t,i),o=((e,t,n)=>{const i=((e,t,n)=>{const i=-2*(e.x*(t.y-n.y)-e.y*(t.x-n.x)+t.x*n.y-n.x*t.y);if(Math.abs(i)<1e-6)return null;const r=((e.x*e.x+e.y*e.y)*(n.y-t.y)+(t.x*t.x+t.y*t.y)*(e.y-n.y)+(n.x*n.x+n.y*n.y)*(t.y-e.y))/i,o=((e.x*e.x+e.y*e.y)*(t.x-n.x)+(t.x*t.x+t.y*t.y)*(n.x-e.x)+(n.x*n.x+n.y*n.y)*(e.x-t.x))/i;return Number.isFinite(r)&&Number.isFinite(o)?new zh(r,o):null})(e,t,n);if(!i)return null;const r=i.dist(e);if(r<1e-6)return null;const o=((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),r=n.dist(t),o=t.dist(e);return r<1e-6||o<1e-6?0:2*Math.acos(Math.max(-1,Math.min(1,(r*r+o*o-i*i)/(2*r*o))))})(e,t,n);var a,d,l;if(!Number.isFinite(s))return null;const c=Math.PI>s?1:0,u=(Am-s)*(o?1:-1);return{center:i,radius:r,largeArcFlag:c,sweepFlag:o,size:u,length:Math.abs(u*r)}})(e,r,t),s=Math.abs(i)<1e-6||null===o||0===o.length||!Number.isFinite(o.length)||!Number.isFinite(o.radius),a=s?[e,t]:Os(e,t,o,24),d=s||null===o?`M ${zs(e.x)} ${zs(e.y)} L ${zs(t.x)} ${zs(t.y)}`:`M ${zs(e.x)} ${zs(e.y)} A ${zs(o.radius)} ${zs(o.radius)} 0 ${o.largeArcFlag} ${o.sweepFlag} ${zs(t.x)} ${zs(t.y)}`,l={start:{terminal:"start",point:e,handle:e},end:{terminal:"end",point:t,handle:t},middle:r,bend:i,points:a,bounds:Hh.FromPoints(a),path:d};return s?{type:"straight",...l,arc:null}:{type:"curved",...l,arc:o}}function Ys({start:e,end:t,middle:n,bend:i,arc:r,startHandle:o=e,endHandle:s=t}){const a=Ks(e,t,r);if(Math.abs(a)<1e-6||!Number.isFinite(a)||!Number.isFinite(r.radius)||r.radius<1e-6){const r=Hs(e,t,0);return{...r,start:{...r.start,handle:o},end:{...r.end,handle:s},middle:n,bend:i}}const d={center:r.center,radius:r.radius,largeArcFlag:Math.abs(a)>Math.PI?1:0,sweepFlag:r.sweepFlag,size:a,length:Math.abs(a*r.radius)},l=Os(e,t,d,24),c=`M ${zs(e.x)} ${zs(e.y)} A ${zs(d.radius)} ${zs(d.radius)} 0 ${d.largeArcFlag} ${d.sweepFlag} ${zs(t.x)} ${zs(t.y)}`;return{type:"curved",start:{terminal:"start",point:e,handle:o},end:{terminal:"end",point:t,handle:s},middle:n,arc:d,bend:i,points:l,bounds:Hh.FromPoints(l),path:c}}function Os(e,t,n,i){const r=[],o=zh.Angle(n.center,e),s=Ks(e,t,n);for(let a=0;a<=i;a++)r.push(_s(n.center,n.radius,o+s*(a/i)));return r}function Ks(e,t,n){return i=zh.Angle(n.center,e),r=zh.Angle(n.center,t),n.sweepFlag?((r-i)%Am+Am)%Am:-((i-r)%Am+Am)%Am;var i,r}function Xs(e,t,n,i){const r=zh.Angle(n.center,e),o=Ks(e,t,n);return _s(n.center,n.radius,r+o*i)}function Ws({terminal:e,handlePagePoint:t,boundaryPagePoint:n,fullInfo:i}){if(t.dist(n)<1e-6)return null;const r="start"===e?i.arc.sweepFlag:(e=>e?0:1)(i.arc.sweepFlag),o={center:i.arc.center,radius:i.arc.radius,sweepFlag:r};return Ys({start:t,end:n,middle:Xs(t,n,o,.5),bend:i.bend,arc:o}).path}function Ns(e,t,n){const i=((e,t,n)=>{if(e.length<2||n<1e-6)return[];const i=[],r=2===e.length?1:e.length;for(let o=0;o<r;o+=1){const r=e[o],s=e[(o+1)%e.length];if(r&&s)for(const e of Vs(t,n,r,s))i.some(t=>t.dist(e)<1e-6)||i.push(e)}return i})(e,t.arc.center,t.arc.radius);if(0===i.length)return null;const r=Math.abs(Ks(t.start.handle,t.end.handle,t.arc));if(r<1e-6)return null;const o=i.map(e=>({point:e,measure:Math.abs(Ks(t.start.handle,e,t.arc))})).filter(({measure:e})=>e>=-1e-6&&e<=r+1e-6);return 0===o.length?null:(o.sort((e,t)=>e.measure-t.measure),"start"===n?o[0]?.point??null:o[o.length-1]?.point??null)}function _s(e,t,n){return e.add(new zh(Math.cos(n)*t,Math.sin(n)*t))}function Vs(e,t,n,i){const r=i.sub(n),o=n.sub(e),s=r.len2();if(s<1e-6)return[];const a=2*js(o,r),d=a*a-4*s*(o.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(r.mul(Math.max(0,Math.min(1,e)))))}function qs(e,t,n){const i=n.sub(t),r=i.x*i.x+i.y*i.y;if(0===r)return e.dist(t);const o=e.sub(t),s=Math.max(0,Math.min(1,js(o,i)/r)),a=t.add(i.mul(s));return e.dist(a)}function js(e,t){return e.x*t.x+e.y*t.y}function Gs(e){return!!e&&"shape"===e.typeName&&"arrow"===e.type}function Zs(e){return!!e&&"binding"===e.typeName&&"arrow"===e.type}function Qs(e,t,n){const i=As(t,n),r=((e,t,n)=>e.getBindingsFromShape(t.id).find(e=>Zs(e)&&e.props.terminal===n)??null)(e,t,n);if(!r)return{terminal:n,binding:null,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0};const o=e.getShape(r.toId);return!o||Gs(o)?{terminal:n,binding:r,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0}:{terminal:n,binding:r,target:o,handlePagePoint:Ms(e,o,r.props.normalizedAnchor),boundaryPagePoint:i,isArcBoundaryPoint:!1}}function Js(e,t){const n=Qs(e,t,"start"),i=Qs(e,t,"end"),r=Hs(n.handlePagePoint,i.handlePagePoint,t.props.bend);return"curved"===r.type&&(na(e,n,r,"start"),na(e,i,r,"end")),{info:"curved"!==r.type||!n.isArcBoundaryPoint&&n.binding||!i.isArcBoundaryPoint&&i.binding?ta(Hs(n.boundaryPagePoint,i.boundaryPagePoint,t.props.bend),n.handlePagePoint,i.handlePagePoint):Ys({start:n.boundaryPagePoint,end:i.boundaryPagePoint,middle:Xs(n.boundaryPagePoint,i.boundaryPagePoint,r.arc,.5),bend:t.props.bend,arc:r.arc,startHandle:n.handlePagePoint,endHandle:i.handlePagePoint}),fullInfo:r,bindingSegments:[ia(n,r),ia(i,r)].filter(e=>null!==e)}}function ea(e,t){return((e,t)=>{const n=e.start.point.add(t),i=e.end.point.add(t),r=e.middle.add(t),o=e.start.handle.add(t),s=e.end.handle.add(t);return"curved"===e.type?Ys({start:n,end:i,middle:r,bend:e.bend,arc:{center:e.arc.center.add(t),radius:e.arc.radius,sweepFlag:e.arc.sweepFlag},startHandle:o,endHandle:s}):ta(Hs(n,i,e.bend),o,s)})(Js(e,t).info,new zh(-t.x,-t.y))}function ta(e,t,n){return{...e,start:{...e.start,handle:t},end:{...e.end,handle:n}}}function na(e,t,n,i){if(!t.target)return void(t.isArcBoundaryPoint=!0);const r=Ns(e.getShapePageOutlineVertices(t.target.id),n,i);r?(t.boundaryPagePoint=r,t.isArcBoundaryPoint=!0):t.isArcBoundaryPoint=!1}function ia(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?Ws({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 ra(e,{arrow:t,terminal:n,target:i,anchorPagePoint:r,fallbackBoundaryPagePoint:o}){const s=((e,t,n)=>Qs(e,t,n).handlePagePoint)(e,t,Rs(n)),a=Hs("start"===n?r:s,"end"===n?r:s,t.props.bend);if("curved"!==a.type)return{terminal:n,anchorPagePoint:r,boundaryPagePoint:o,guidePath:null};const d=Ns(e.getShapePageOutlineVertices(i.id),a,n);return d?{terminal:n,anchorPagePoint:r,boundaryPagePoint:d,guidePath:Ws({terminal:n,handlePagePoint:r,boundaryPagePoint:d,fullInfo:a})}:{terminal:n,anchorPagePoint:r,boundaryPagePoint:o,guidePath:null}}function oa(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function sa(e){if(e)return{shapes:[e]}}function aa(e,t){const n=e&&"object"==typeof e?e:void 0;return{x:da(n?.x,t.x),y:da(n?.y,t.y)}}function da(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function la(e,t,n){const i=n.sub(t),r=i.len2();if(0===r)return e.dist(t);const o=e.sub(t),s=Math.max(0,Math.min(1,(o.x*i.x+o.y*i.y)/r));return e.dist(t.add(i.mul(s)))}function ca(e,t,n,i){return((e,t,n,i)=>{const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*o.y-a.y*o.x)/s,l=(a.x*r.y-a.y*r.x)/s;return d>=0&&d<=1&&l>=0&&l<=1})(e,t,n,i)?0:Math.min(la(e,n,i),la(t,n,i),la(n,e,t),la(i,e,t))}function ua(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}],{source:n});if(!Gs(i))throw new Error("Failed to create arrow shape");const r=Fs(i,t.startPagePoint,t.endPagePoint);e.commands.updateShapes([{id:i.id,x:r.x,y:r.y,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:{...r.props}}],{source:n}),t.startBinding&&e.commands.createBinding({type:"arrow",fromId:r.id,toId:t.startBinding.targetShapeId,props:{terminal:"start",normalizedAnchor:t.startBinding.normalizedAnchor}},{source:n}),t.endBinding&&e.commands.createBinding({type:"arrow",fromId:r.id,toId:t.endBinding.targetShapeId,props:{terminal:"end",normalizedAnchor:t.endBinding.normalizedAnchor}},{source:n});const o=e.getShape(r.id);if(!Gs(o))throw new Error("Failed to create arrow shape");return o}function ha(e,t,n,i,r="user"){if(!t)return e.setBindingPreview(i.preview),null;let o=null;return o=((e,t,n)=>{const i=e.getShape(t.shapeId);if(!Gs(i))return null;const r=Ls(i,t.terminal,t.pagePoint);e.commands.updateShapes([{id:i.id,x:r.x,y:r.y,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:{...r.props}}],{source:n});const o=e.bindings.getBindingsFromShape(i.id).find(e=>Zs(e)&&e.props.terminal===t.terminal)??null;t.binding?Zs(o)?e.commands.updateBinding({id:o.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n}):(o&&e.commands.deleteBinding(o.id,{source:n}),e.commands.createBinding({type:"arrow",fromId:i.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n})):o&&(e.commands.deleteBinding(o.id,{source:n}),e.commands.updateShapes([{id:i.id,x:r.x,y:r.y,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:{...r.props}}],{source:n}));const s=e.getShape(i.id);return Gs(s)?s:r})(e,{shapeId:t,terminal:n,pagePoint:i.pagePoint,binding:i.binding},r),e.setBindingPreview(i.preview),o}function pa(e,{terminal:t,rawPagePoint:n,oppositePagePoint:i,excludeShapeId:r,ignoreTargets:o=!1}){if(o)return{pagePoint:n.clone(),binding:null,preview:null};const s=function(e,t,n,i){const r=e.spatialIndex.getShapeAtPoint(t,{filter:e=>{return e.id!==i?.excludeShapeId&&!!(t=e)&&!Gs(t);var t}});if(!r)return null;const o=((e,t,n)=>{const i=_e(t,n,e.getShapeUtil(t)),r=e.computeShapeBounds(t),o=r.h<=1e-6?.5:(i.y-r.minY)/r.h;return{x:Bs(r.w<=1e-6?.5:(i.x-r.minX)/r.w),y:Bs(o)}})(e,r,t);return{targetShape:r,normalizedAnchor:o,resolvedPagePoint:Es(e,r,o,n),rawPagePoint:t.clone()}}(e,n,i,{excludeShapeId:r});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:ma(s),preview:fa(t,s)}}function ga(e,{arrow:t,terminal:n,rawPagePoint:i,ignoreTargets:r=!1}){const o=pa(e,{terminal:n,rawPagePoint:i,oppositePagePoint:As(t,Rs(n)),excludeShapeId:t.id,ignoreTargets:r});if(!o.preview)return o;const s=((e,{arrow:t,terminal:n,rawPagePoint:i,preview:r})=>{const o=e.getShape(r.targetShapeId);if(!o||Gs(o))return r;const s=ra(e,{arrow:t,terminal:n,target:o,anchorPagePoint:i,fallbackBoundaryPagePoint:r.resolvedPagePoint});return{...r,resolvedPagePoint:s.boundaryPagePoint,guidePath:s.guidePath}})(e,{arrow:t,terminal:n,rawPagePoint:i,preview:o.preview});return{...o,pagePoint:s.resolvedPagePoint,preview:s}}function ma(e){return e?{targetShapeId:e.targetShape.id,normalizedAnchor:e.normalizedAnchor}:null}function fa(e,t){return t?{terminal:e,targetShapeId:t.targetShape.id,rawPagePoint:t.rawPagePoint,resolvedPagePoint:t.resolvedPagePoint}:null}function Sa(){return{createSession:(e,{handle:t,shape:n})=>Gs(n)?"binding_terminal"===t.kind?(({handle:e,shapeId:t,terminal:n})=>({shapeId:t,historyMark:"select.binding_terminal_drag",handleSnapMode:"point",handleSnapContext:{shapeId:t,handle:e},shouldClearBindingPreviewOnExit:!0,update({editor:e,pagePoint:i,accelKey:r,source:o}){const s=e.getShape(t);if(!Gs(s))return{status:"stop",finalPagePoint:null};const a=ga(e,{arrow:s,terminal:n,rawPagePoint:i,ignoreTargets:r}),d=ha(e,s.id,n,a,o);return{status:"continue",finalPagePoint:d?As(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:r}){const o=t.getShape(e);if(!Gs(o))return"stop";const s=((e,t)=>({start:Qs(e,t,"start").handlePagePoint,end:Qs(e,t,"end").handlePagePoint}))(t,o),a=(({bend:e,bypassSnap:t,zoom:n})=>t?e:Math.abs(e)*n<=6?0:e)({bend:Ds(s.start,s.end,n),bypassSnap:i,zoom:t.cameraZoomSignal.get()});return t.commands.updateShapes([{id:o.id,props:{bend:a}}],{source:r}),"continue"}}}({shapeId:n.id}):null:null}}function ya({strokeActionId:e,strokeWidthActionId:t,headStartActionId:n,headEndActionId:i,dataUiPrefix:r}){return[{id:`${r}.style-stroke`,items:[{kind:"swatches",id:`${r}.stroke`,actionId:e,label:"Stroke",options:Hm.map(e=>({...e,dataUi:`${r}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-stroke-width`,items:[{kind:"stepper",id:`${r}.stroke-width`,actionId:t,label:"Stroke width",dataUi:`${r}-stroke-width-control`,options:Ym.map(e=>({...e,dataUi:`${r}-stroke-width-${e.value}-button`}))}]},{id:`${r}.head-start`,items:[{kind:"segmented",id:`${r}.head-start`,actionId:n,options:Om.map(e=>({...e,label:`Start head: ${e.label}`,dataUi:`${r}-start-head-${e.value}-button`}))}]},{id:`${r}.head-end`,items:[{kind:"segmented",id:`${r}.head-end`,actionId:i,options:Om.map(e=>({...e,label:`End head: ${e.label}`,dataUi:`${r}-end-head-${e.value}-button`}))}]}]}function xa(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?!k(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=Pa(e,n);if(void 0===i)return;const r=t.selection.selectedShapes.filter(e=>"arrow"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==r.length&&t.editor.commands.updateShapes(r,{source:"user"})}}}function ba(e){return{id:`arrow.default-${e}`,isVisible:e=>"arrow"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("arrow")[e],run({context:t,value:n}){const i=Pa(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("arrow",{[e]:i})}}}function Pa(e,t){return"strokeWidth"===e?"number"==typeof t&&Ym.some(e=>e.value===t)?t:void 0:"stroke"===e?b(t)?I(t,f("stroke-slate")):void 0:Om.some(e=>e.value===t)?t:void 0}function Ia(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 wa({shape:e,editor:t,isHovered:n,isSelected:i}){const r=e.id.replace(/[^a-zA-Z0-9_-]/g,"-"),o=`arrow-head-start-${r}`,s=`arrow-head-end-${r}`,a=ea(t,e),d=Qi(e.props.stroke,n);
24
+ return Ih("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,overflow:"visible",children:[Ih("defs",{children:[Ph("marker",{id:o,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"2",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:Ph("path",{d:"M8.9,8 L2,12 L8.9,16",fill:"none",stroke:d,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),Ph("marker",{id:s,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"22",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:Ph("path",{d:"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:d,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),Ph("path",{d:a.path,fill:"none",stroke:d,strokeWidth:e.props.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round",markerStart:"arrow"===e.props.headStart?`url(#${o})`:void 0,markerEnd:"arrow"===e.props.headEnd?`url(#${s})`:void 0,opacity:i?.92:1})]})}function va(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function Ca(e,t,n){return Math.max(t,Math.min(n,e))}function ka(e){return e?640:480}function Ta(e,t){return e.x===t.x&&e.y===t.y&&e.pressure===t.pressure&&e.segment===t.segment}function Ba(e){return new zh(e.x,e.y)}function Ma(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 Ea(e){const t=[];for(const n of e)t.push(...n.points.map(Ma));return t}function Aa(e){if(void 0!==e&&Number.isFinite(e))return Ca(e,.05,1)}function Ra(e,t){const n=[];for(let i=1;i<e.length-1;i+=1){if(t&&Fa(e,i))continue;const r=e[i],o=e[i-1],s=e[i+1];r&&o&&s&&n.push({index:i,score:La(r,o,s)})}return n.sort((e,t)=>e.score-t.score||e.index-t.index),n}function Fa(e,t){return"straight"===e[t]?.segment||"straight"===e[t+1]?.segment}function La(e,t,n){const i=((e,t,n)=>{const i=n.x-t.x,r=n.y-t.y,o=i*i+r*r;if(0===o){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}const s=Ca(((e.x-t.x)*i+(e.y-t.y)*r)/o,0,1),a=e.x-(t.x+i*s),d=e.y-(t.y+r*s);return a*a+d*d})(e,t,n),r=((e,t,n)=>{if(void 0===e.pressure)return 0;return 8*Math.abs(e.pressure-((t.pressure??e.pressure)+(n.pressure??e.pressure))/2)})(e,t,n);return i+r*r}function $a(e){if(0===e.length)return null;if(1===e.length){const t=e[0];return`M ${va(t.x)} ${va(t.y)}`}if(2===e.length){const t=e[0],n=e[1];return[`M ${va(t.x)} ${va(t.y)}`,`L ${va(n.x)} ${va(n.y)}`].join(" ")}const t=[],n=e[0];t.push(`M ${va(n.x)} ${va(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 ${va(n.x)} ${va(n.y)}`);continue}const r=e[i+1];if(!r||"straight"===r.segment){if(Da(e,i)){const r=e[i-1];t.push(`Q ${va(r.x)} ${va(r.y)} ${va(n.x)} ${va(n.y)}`)}else t.push(`L ${va(n.x)} ${va(n.y)}`);continue}const o=zh.Med(Ba(n),Ba(r));t.push(`Q ${va(n.x)} ${va(n.y)} ${va(o.x)} ${va(o.y)}`)}return t.join(" ")}function Da(e,t){return t>=2&&"straight"!==e[t-1]?.segment&&"straight"!==e[t-2]?.segment}function Ua(e){if(e.length<3)return(e=>{if(0===e.length)return null;const[t,...n]=e;return t?[`M ${va(t.x)} ${va(t.y)}`,...n.map(e=>`L ${va(e.x)} ${va(e.y)}`),"Z"].join(" "):null})(e);const t=e[0],n=e[e.length-1];if(!t||!n)return null;const i=zh.Med(n,t),r=[`M ${va(i.x)} ${va(i.y)}`];for(let o=0;o<e.length;o+=1){const t=e[o],n=e[(o+1)%e.length];if(!t||!n)continue;const i=zh.Med(t,n);r.push(`Q ${va(t.x)} ${va(t.y)} ${va(i.x)} ${va(i.y)}`)}return r.push("Z"),r.join(" ")}function za(e){return e.map(Ma)}function Ha(e){return e.map(Ya)}function Ya(e){return(e=>({points:e.points.map(Ma)}))(e)}function Oa(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 Ka(e,t,n){return e.map(e=>({points:Oa(e.points,t,n)}))}function Xa(e,t){return e.map((e,n)=>({points:e.points.map((e,i)=>{const r=t(Ba(e),n,i);return{x:r.x,y:r.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}})}))}function Wa(e,t,n){const i=0===t.w?1:t.w,r=0===t.h?1:t.h,o=0===n.w?1:n.w,s=0===n.h?1:n.h;return e.map(e=>({x:n.minX+(e.x-t.minX)/i*o,y:n.minY+(e.y-t.minY)/r*s,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}))}function Na(e,t,n){return e.map(e=>({points:Wa(e.points,t,n)}))}function _a(e){return{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}}function Va(e,t){const n=_a(t);return Xa(e,e=>mn(e,n))}function qa(e,t){const n=_a(t);return Xa(e,e=>fn(e,n))}function ja(e,t){return Xa(e,e=>bn({axis:t.axis,bounds:t.selectionMirrorBounds,point:e}))}function Ga(e,t,n){return Math.max(t,Math.min(n,e))}function Za(e,t,n){return e+(t-e)*n}function Qa(e,t,n){if(e.length<=1)return new zh(1,0);if(n&&e.length>=3){const n=e[t],i=e[(t+1)%e.length],r=n.sub(e[(t-1+e.length)%e.length]).uni(),o=i.sub(n).uni(),s=r.add(o);return s.len2()>1e-6?s.uni():o.len2()>0?o:r.len2()>0?r:new zh(1,0)}const i=e[t],r=e[t+1]??i,o=i.sub(e[t-1]??i).uni(),s=r.sub(i).uni();if(0===t)return s.len2()>0?s:new zh(1,0);if(t===e.length-1)return o.len2()>0?o:new zh(1,0);const a=o.add(s);return a.len2()>1e-6?a.uni():s.len2()>0?s:o.len2()>0?o:new zh(1,0)}function Ja(e,t){return e.x*t.x+e.y*t.y}function ed(e,t,n,i,r={}){if(0===e.length)return[];const o=((e,t)=>{const n=Math.max(e+1,1.6);return{baseRadius:n,minRadius:Math.max(.6,.32*n),minRadiusScale:t?.5:.48,maxRadiusScale:t?1.22:1.24,startTaper:Math.max(1.8*e,2.5),endTaper:Math.max(2.3*e,3.5),simulatePressure:!t}})(t,n),s=e.map(Ba),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,r,o,s,a){if(n.simulatePressure)return(({distanceFromPrevious:e,previousPressure:t,runningLength:n,totalLength:i,strokeWidth:r,isClosed:o})=>{const s=Ga(e/Math.max(1.5*r,1),0,1),a=Ga(1-s,Xm,1),d=null===t?Za(.5,a,.275):Za(t,a,.275*Math.max(s,.36));if(o)return Ga(d,Xm,1);const l=Ga(n/Math.max(1.8*r,1),0,1),c=Ga((i-n)/Math.max(2.6*r,1),0,1);return Ga(d*Za(.72,1,Math.min(l,c)),Xm,1)})({distanceFromPrevious:r,previousPressure:t,runningLength:o,totalLength:s,strokeWidth:i,isClosed:a});const d="number"==typeof e.pressure&&Number.isFinite(e.pressure)?Ga(e.pressure,.05,1):t??.55;return null===t?d:Za(t,d,.68)}(e,l,o,t,u,c,d,i);l=h;const p=r.taperEnd??!0,g=i||s.length<=1?1:Math.min(r.taperStart??1?Ga(c/o.startTaper,0,1):1,p?Ga((d-c)/o.endTaper,0,1):1),m=Za(o.minRadiusScale,o.maxRadiusScale,h),f=Math.max(o.minRadius,o.baseRadius*m*Za(.7,1,g));return{point:s[n],direction:Qa(s,n,i),pressure:h,radius:f,runningLength:c}});return d<.5*o.baseRadius?c.map(e=>({...e,radius:Math.max(e.radius,.92*o.baseRadius)})):c}function td(e,t){const n=e[e.length-1];n&&n.dist2(t)<.04?e[e.length-1]=t:e.push(t)}function nd(e,t,n){const i=e.dist(t);if(0===i)return[];const r=zh.Angle(e,t),o=[];for(let s=1;s<n;s+=1){const t=r-Math.PI*(s/n);o.push(new zh(e.x+Math.cos(t)*i,e.y+Math.sin(t)*i))}return o}function id(e,t,n){const i=e[e.length-1];!i||i.dist2(t)>n?td(e,t):e[e.length-1]=t}function rd(e){return{...e}}function od(e,t,n){return e.map(e=>new zh(e.x+t,e.y+n))}function sd(e,t,n){return e.map(e=>od(e,t,n))}function ad({segments:e,outlineVertices:t,outlinePolygons:n,strokeWidth:i,sampling:r,isClosed:o}){const s=Ea(e),a=s.map(Ba),d=a.length>0?Hh.FromPoints(a):new Hh(0,0,1,1),l=t.length>0?Hh.FromPoints([...t]):d.expand(Math.max(i/2,1)),c=o&&s.length>=3?(e=>{if(e.length<3)return null;const t=$a(e);return t?`${t} Z`:null})(s):null,u=void 0!==n?(e=>{const t=e.map(e=>Ua(e)).filter(e=>null!==e);return t.length>0?t.join(" "):null})(n):Ua(t);return{normalizedSegments:Ha(e),normalizedPoints:za(s),pointBounds:d,path:u,selectionPath:c??$a(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:rd(r)}}function dd(e,t,n,i){const r=(({strokeWidth:e,isPen:t})=>[e,t?"pen":"pointer"].join(":"))({strokeWidth:n,isPen:i}),o=Wm.get(e),s=o?.get(r);if(s)return{normalizedSegment:Ya(s.normalizedSegment),sampling:rd(s.sampling)};const a=((e,t)=>{if(e.length<=1)return{points:e.map(Ma),rawPointCount:e.length,sampledPointCount:e.length,maxPointCount:t.maxPointCount,reduced:!1,capped:!1};const n=[Ma(e[0])],i=t.minPointDistance*t.minPointDistance;let r=Ba(e[0]),o=Aa(e[0].pressure);for(let d=1;d<e.length;d+=1){const s=e[d];if(!s)continue;const a=Ba(s),l=Aa(s.pressure),c=d===e.length-1,u="straight"===s.segment,h=c||u?a:zh.Lrp(r,a,t.positionBlend),p=u?l:void 0===l?void 0:void 0===o?l:o+(l-o)*t.pressureBlend;r=h,o=p;const g=void 0===p?{x:h.x,y:h.y,...void 0===s.segment?null:{segment:s.segment}}:{x:h.x,y:h.y,pressure:p,...void 0===s.segment?null:{segment:s.segment}},m=n[n.length-1];if(!m){n.push(g);continue}const f=g.x-m.x,S=g.y-m.y,y=Math.abs((g.pressure??0)-(m.pressure??0));if(f*f+S*S<i){if(u){if(Ta(m,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(Ma);const i=((e,t)=>{let n=Ra(e,!0);return n.length<t&&(n=Ra(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(Ma)}(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:za(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},l=o??new Map;return l.set(r,{normalizedSegment:Ya(d.normalizedSegment),sampling:rd(d.sampling)}),o||Wm.set(e,l),d}function ld(e,t,n=!1,i=!1){const r=((e,t)=>({minPointDistance:t?Math.max(.35,.18*e):Math.max(.55,.28*e),positionBlend:t?.68:.66,pressureBlend:t?.68:.45,maxPointCount:ka(t)}))(t,n),o=[],s=[],a=e.filter(e=>e.points.length>0);for(let h=0;h<a.length;h+=1){const e=dd(a[h],r,t,n);o.push(Ya(e.normalizedSegment)),s.push(rd(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 r=2*Math.PI*i/16;n.push(new zh(e.x+Math.cos(r)*t,e.y+Math.sin(r)*t))}return n})(e[0].point,e[0].radius);const i=[],r=[];let o=.12;for(const l of e)o=Math.max(o,.38*l.radius);const s=o**2;let a=null;for(let l=0;l<e.length;l+=1){const t=e[l],n=t.direction,o=(e[l+1]??t).direction,d=Ja(n,o);let c=0===l||l===e.length-1?n.per().uni():zh.Lrp(o,n,d).per().uni();c.len2()<1e-6&&(c=a??new zh(0,1)),a=c,id(i,t.point.add(c.mul(t.radius)),s),id(r,t.point.sub(c.mul(t.radius)),s)}if(t&&e.length>=3){const e=[];for(const t of i)td(e,t);for(let t=r.length-1;t>=0;t-=1)td(e,r[t]);return e}const d=[];for(const l of i)td(d,l);if(n.capEnd??1){const t=e[e.length-1];for(const e of nd(t.point,i[i.length-1],8))td(d,e)}for(let l=r.length-1;l>=0;l-=1)td(d,r[l]);if(n.capStart??1){const t=e[0];for(const e of nd(t.point,r[0],8))td(d,e)}return d}(ed(Ea(o),t,n,i),i),l=(u=r.maxPointCount,{rawPointCount:(c=s).reduce((e,t)=>e+t.rawPointCount,0),sampledPointCount:c.reduce((e,t)=>e+t.sampledPointCount,0),sampledPointLimit:u,reduced:c.some(e=>e.reduced),capped:c.some(e=>e.capped)});var c,u;return ad({segments:o,outlineVertices:d,outlinePolygons:d.length>0?[d]:[],strokeWidth:t,sampling:l,isClosed:i})}function cd(e){return e.segments}function ud(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 Hh(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 hd(e,t){return new zh(e.x+t.localBounds.center.x,e.y+t.localBounds.center.y)}function pd(e,t,n){if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return t;const i=t.sub(n);return n.add(new zh(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))}function gd(e){const t=e,n=Nm.get(t);if(n)return n;const i=ld(cd(e.props),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed);return Nm.set(t,i),i}function md(e,t,n=!1,i=!1){return((e,t,n=!1,i=!1)=>{const r=ld(e,t,n,i),o=r.pointBounds,s=ld(Xa(r.normalizedSegments,e=>new zh(e.x-o.x,e.y-o.y)),t,n,i);return{x:o.x,y:o.y,segments:s.normalizedSegments,pointBounds:s.pointBounds,localBounds:s.localBounds,renderBounds:s.renderBounds,path:s.path,selectionPath:s.selectionPath,fillPath:s.fillPath,outlineVertices:s.outlineVertices,outlinePolygons:s.outlinePolygons,sampling:s.sampling}})(e,t,n,i)}function fd(e){const t=e,n=_m.get(t);if(n)return n;const i=((e,t,n,i,r)=>ad({segments:Ka(e.normalizedSegments,n,i),outlineVertices:od(e.outlineVertices,n,i),outlinePolygons:sd(e.outlinePolygons,n,i),strokeWidth:t,sampling:e.sampling,isClosed:r}))(gd(e),e.props.strokeWidth,e.x,e.y,e.props.isClosed);return _m.set(t,i),i}function Sd(e){const t=hd(e,gd(e));return Xa((e=>Ka(cd(e.props),e.x,e.y))(e),n=>pd(e,n,t))}function yd(e){const t=e,n=Vm.get(t);if(n)return n;if(0===e.rotation&&1===e.scaleX&&1===e.scaleY){const n=fd(e);return Vm.set(t,n),n}const i=gd(e),r=hd(e,i),o=ad({segments:Xa(i.normalizedSegments,t=>pd(e,new zh(t.x+e.x,t.y+e.y),r)),outlineVertices:i.outlineVertices.map(t=>pd(e,new zh(t.x+e.x,t.y+e.y),r)),outlinePolygons:i.outlinePolygons.map(t=>t.map(t=>pd(e,new zh(t.x+e.x,t.y+e.y),r))),strokeWidth:e.props.strokeWidth,sampling:i.sampling,isClosed:e.props.isClosed});return Vm.set(t,o),o}function xd(e){return Ha(e)}function bd(e,t,n,i){return{x:e.x-t.x,y:e.y-t.y,...i&&n>0?{pressure:n}:null}}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 Id(e){const t=wd(e.segments),n=t[t.length-1];return n?n.points.map(Pd):[]}function wd(e){return e.length>0?[...e]:[{points:[]}]}function vd(e){return{segments:xd(wd(e))}}function Cd(e,t,n){const i=n.sub(t),r=i.len2();if(0===r)return e.dist(t);const o=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/r)),s=new zh(t.x+i.x*o,t.y+i.y*o);return e.dist(s)}function kd(e,t,n,i){return((e,t,n,i)=>{const r=t.sub(e),o=i.sub(n),s=r.x*o.y-r.y*o.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),d=(a.x*o.y-a.y*o.x)/s,l=(a.x*r.y-a.y*r.x)/s;return d>=0&&d<=1&&l>=0&&l<=1})(e,t,n,i)?0:Math.min(Cd(e,n,i),Cd(t,n,i),Cd(n,e,t),Cd(i,e,t))}function Td(e,t){let n=!1;for(let i=0,r=t.length-1;i<t.length;r=i,i+=1){const o=t[i],s=t[r];o&&s&&o.y>e.y!=s.y>e.y&&e.x<(s.x-o.x)*(e.y-o.y)/(s.y-o.y)+o.x&&(n=!n)}return n}function Bd(e,t){if(0===t.length)return Number.POSITIVE_INFINITY;let n=Number.POSITIVE_INFINITY;for(let i=0;i<t.length;i+=1){const r=t[i],o=t[(i+1)%t.length];r&&o&&(n=Math.min(n,Cd(e,r,o)))}return n}function Md(e,t,n,i){if(0===n.length)return!1;if(Td(e,n)||Td(t,n))return!0;for(let r=0;r<n.length;r+=1){const o=n[r],s=n[(r+1)%n.length];if(o&&s&&kd(e,t,o,s)<=i)return!0}return!1}function Ed(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ad(e){if(!e||"object"!=typeof e)return null;const t=e,n=Ed(t.x,NaN),i=Ed(t.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(i))return null;const r=Ed(t.pressure,NaN);return t.x!==n||t.y!==i||void 0!==t.pressure&&t.pressure!==r||void 0!==t.segment&&"straight"!==t.segment?{x:n,y:i,...Number.isFinite(r)?{pressure:r}:null,..."straight"===t.segment?{segment:"straight"}:null}:e}function Rd(e){if(!e||"object"!=typeof e)return null;const t=e,n=((e,t)=>{if(!Array.isArray(e))return t;let n=!1;const i=[];for(const r of e){const e=Ad(r);e?(n=n||e!==r,i.push(e)):n=!0}return 0===i.length?t:n?i:e})(t.points,[]);return 0===n.length?null:n===t.points?e:{points:n}}function Fd(e,t){if(!Array.isArray(e))return t;let n=!1;const i=[];for(const r of e){const e=Rd(r);e?(n=n||e!==r,i.push(e)):n=!0}return 0===i.length?t:n?i:e}function Ld(e){return u(e)&&"draw"===e.type}function $d({closedActionId:e,fillActionId:t,strokeActionId:n,strokeWidthActionId:i,dataUiPrefix:r}){return[{id:`${r}.style-closed`,items:[{kind:"segmented",id:`${r}.closed`,actionId:e,options:rf.map(e=>({...e,dataUi:`${r}-${e.value}-button`}))}]},{id:`${r}.style-fill`,items:[{kind:"swatches",id:`${r}.fill`,actionId:t,label:"Fill",options:tf.map(e=>({...e,dataUi:`${r}-fill-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-stroke`,items:[{kind:"swatches",id:`${r}.stroke`,actionId:n,label:"Stroke",options:ef.map(e=>({...e,dataUi:`${r}-stroke-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-stroke-width`,items:[{kind:"stepper",id:`${r}.stroke-width`,actionId:i,label:"Stroke width",dataUi:`${r}-stroke-width-control`,options:nf.map(e=>({...e,dataUi:`${r}-stroke-width-${e.value}-button`}))}]}]}function Dd(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:!k(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=Yd(e,n);if(void 0===i)return;const r=t.selection.selectedShapes.filter(Ld).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==r.length&&t.editor.commands.updateShapes(r,{source:"user"})}}}function Ud(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=Yd(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("draw",{[e]:i})}}}function zd(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 Hd(e){return"closed"===e||"open"!==e&&null}function Yd(e,t){return"strokeWidth"===e?"number"==typeof t&&nf.some(e=>e.value===t)?t:void 0:b(t)?I(t,"fill"===e?"transparent":f("stroke-slate")):void 0}function Od({shape:e,isHovered:t=!1,stroke:n=e.props.stroke,strokeWidth:i=e.props.strokeWidth}){const{fillPath:r,renderBounds:o,path:s,selectionPath:a}=gd({props:{...e.props,strokeWidth:i}});if(!s&&!a)return null;const d=Qi(n,t);
25
+ return Ih("svg",{width:"100%",height:"100%",viewBox:`${o.x} ${o.y} ${Math.max(o.w,1)} ${Math.max(o.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[r&&!C(e.props.fill)?Ph("path",{d:r,fill:w(e.props.fill),stroke:"none"}):null,e.props.isClosed&&a?Ph("path",{d:a,fill:"none",stroke:d,strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round"}):s?Ph("path",{d:s,fill:d,stroke:"none"}):null]})}function Kd({shape:e,isHovered:t}){
26
+ return Ph(Od,{shape:e,isHovered:t})}function Xd(e){return 4/e.getCurrentCamera().z}function Wd(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 Nd(e,t){const n=new Set,i=Xd(e);for(const r of e.hitTestShapesAtPoint(t)){const o=e.getShapeUtil(r);if(!o.canReceiveChildren(r))continue;const s=o.getChildClipLocalBounds(r);s&&Wd(o.getLocalToPageTransform(r).invert().applyToPoint(t),s,i)&&n.add(r.id)}return n}function _d(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 Vd(e,t,n,i){const r=i.topMostOnly?n.slice(0,1):n;for(const o of r){const n=_d(e,o,t);n&&t.erasingShapeIds.add(n)}}function qd(e,t,n){Vd(e,t,e.hitTestShapesAtPoint(n.pagePoint),{topMostOnly:n.accelKey})}function jd(e,t,n){Vd(e,t,e.hitTestShapesByLineSegment(t.previousPagePoint,n.pagePoint,{margin:Xd(e)}),{topMostOnly:n.accelKey})}function Gd(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function Zd(e,t){e.setErasingShapeIds(Array.from(t.erasingShapeIds)),e.setEraserTrail(t.trail)}function Qd(e){e.clearErasingShapeIds(),e.clearEraserTrail()}function Jd(e,t){const n=Array.from(t.erasingShapeIds);Qd(e),0!==n.length&&e.commands.deleteShapes(n,{source:"user"})}function el(){return"undefined"==typeof performance?Date.now():performance.now()}function tl(e,t,n,i){const r=e.samples[e.samples.length-1];if(!r)return void e.samples.push({...t,time:i,velocity:0});const o=gf/n,s=sl(r,t);if(s<o)return void(e.samples[e.samples.length-1]={...r,...t,time:i});const a=s*n/Math.max(bf,i-r.time);e.samples.push({...t,time:i,velocity:pl(r.velocity,a,.68)})}function nl(e,t){e.samples=il(e.samples,t)}function il(e,t){const n=e[e.length-1];if(!n)return[];const i=t-gl(Pf+n.velocity*If,Pf,wf);if(n.time<i)return[];const r=e.findIndex(e=>e.time>=i);if(-1===r)return[];const o=e.slice(r),s=e[r-1],a=o[0];return s&&a.time>i?[(d=s,l=a,c=gl((i-s.time)/(a.time-s.time),0,1),{...hl(d,l,c),time:pl(d.time,l.time,c),velocity:pl(d.velocity,l.velocity,c)}),...o]:o;var d,l,c}function rl(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?cl(i,e[t]):cl(t===e.length-1?e[t]:i,n))}function ol(e,t,n){const i=[];for(let r=0;r<n;r++){const o=2*Math.PI*r/n;i.push({x:e.x+Math.cos(o)*t,y:e.y+Math.sin(o)*t})}return i}function sl(e,t){return Math.sqrt(al(e,t))}function al(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function dl(e){return{x:-e.y,y:e.x}}function ll(e,t){return{x:e.x+t.x,y:e.y+t.y}}function cl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ul(e,t){return{x:e.x*t,y:e.y*t}}function hl(e,t,n){return{x:pl(e.x,t.x,n),y:pl(e.y,t.y,n)}}function pl(e,t,n){return e+(t-e)*n}function gl(e,t,n){return Math.max(t,Math.min(n,e))}function ml(e,t){const n=e[e.length-1];!n||al(n,t)>.04?e.push(t):e[e.length-1]=t}function fl(e){if(e.length<2)return null;if(2===e.length)return`M ${yl(e[0])} L ${yl(e[1])} Z`;const t=[`M ${yl(Sl(e[0],e[1]))}`];for(let n=1;n<e.length;n++){const i=e[n],r=e[(n+1)%e.length];t.push(`Q ${yl(i)} ${yl(Sl(i,r))}`)}return t.push("Z"),t.join(" ")}function Sl(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function yl(e){return`${xl(e.x)},${xl(e.y)}`}function xl(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function bl(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Pl(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 Il(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:!k(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 r=t.selection.selectedShapes.filter(e=>"frame"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==r.length&&t.editor.commands.updateShapes(r,{source:"user"})}}}function wl(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=kl(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("frame",{[e]:i})}}}function vl({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"swatches",id:`${i}.fill`,actionId:e,label:"Fill",options:Af.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:Rf.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:Ff.map(e=>({...e,dataUi:`${i}-stroke-width-${e.value}-button`}))}]}]}function Cl(e){return{id:`frame.child-order.${e}`,isVisible:e=>"frame"===Tl(e),isEnabled:t=>t.editor.canMoveSelectionWithinParent(e),run({context:t}){t.editor.moveSelectionWithinParent(e,"user")}}}function kl(e,t){return"strokeWidth"===e?"number"==typeof t&&Ff.some(e=>e.value===t)?t:void 0:b(t)?I(t,"fill"===e?"transparent":f("stroke-muted")):void 0}function Tl(e){const[t]=e.selection.selectedShapes;return 1===e.selection.count&&t?.parentId.startsWith("shape:")?e.editor.getShape(t.parentId)?.type??null:null}function Bl({shape:e,isHovered:t}){
27
+ return Ph(Ml,{shape:e,isHovered:t})}function Ml({shape:e,isHovered:t=!1}){const{fill:n,h:i,name:r,stroke:o,strokeWidth:s,w:a}=e.props,d=s/2,l=Math.max(a-s,0),c=Math.max(i-s,0),u=Qi(o,t);
28
+ return Ih("svg",{width:"100%",height:"100%",viewBox:`0 0 ${a} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[Ph("rect",{x:d,y:d,width:l,height:c,fill:w(n),stroke:u,strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"}),Ph("text",{x:12,y:18,fill:w(o),fontFamily:["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),fontSize:12,fontWeight:600,style:{userSelect:"none"},children:r})]})}function El(e,t){return"ellipse"===t?((e,t=32)=>{const n=[];for(let i=0;i<t;i+=1){const r=i/t*Math.PI*2;n.push(new zh(e.center.x+e.w/2*Math.cos(r),e.center.y+e.h/2*Math.sin(r)))}return n})(e):Al(e,t)}function Al(e,t){switch(t){case"diamond":return[new zh(e.center.x,e.minY),new zh(e.maxX,e.center.y),new zh(e.center.x,e.maxY),new zh(e.minX,e.center.y)];case"triangle":return[new zh(e.center.x,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)];case"hexagon":return[new zh(e.minX+.25*e.w,e.minY),new zh(e.maxX-.25*e.w,e.minY),new zh(e.maxX,e.center.y),new zh(e.maxX-.25*e.w,e.maxY),new zh(e.minX+.25*e.w,e.maxY),new zh(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 zh(Math.cos(e)*i,Math.sin(e)*i))}return((e,t)=>{const n=Hh.FromPoints([...e]);return 0===n.w||0===n.h?[t.center]:e.map(e=>new zh(t.minX+(e.x-n.minX)/n.w*t.w,t.minY+(e.y-n.minY)/n.h*t.h))})(t,e)})(e);default:return[new zh(e.minX,e.minY),new zh(e.maxX,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)]}}function Rl(e,t){if(t.length<3)return!1;let n=!1;for(let i=0,r=t.length-1;i<t.length;r=i,i+=1){const o=t[i],s=t[r];if(o&&s){if(Fl(e,o,s)<=1e-6)return!0;o.y>e.y!=s.y>e.y&&e.x<(s.x-o.x)*(e.y-o.y)/(s.y-o.y)+o.x&&(n=!n)}}return n}function Fl(e,t,n){const i=n.sub(t),r=i.len2();if(0===r)return e.dist(t);const o=e.sub(t),s=Math.max(0,Math.min(1,(o.x*i.x+o.y*i.y)/r));return e.dist(t.add(i.mul(s)))}function Ll(e){return u(e)&&"geo"===e.type}function $l(e){return"string"==typeof e&&Nf.includes(e)}function Dl(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ul(e,t){return e.x*t.y-e.y*t.x}function zl(e,t,n){const i=n.sub(t),r=i.len2();if(0===r)return e.dist(t);const o=e.sub(t),s=Math.max(0,Math.min(1,(o.x*i.x+o.y*i.y)/r));return e.dist(t.add(i.mul(s)))}function Hl(e,t,n,i){return Yl(e,t,n,i)?0:Math.min(zl(e,n,i),zl(t,n,i),zl(n,e,t),zl(i,e,t))}function Yl(e,t,n,i){const r=t.sub(e),o=i.sub(n),s=Ul(r,o);if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=Ul(a,o)/s,l=Ul(a,r)/s;return d<0||d>1||l<0||l>1?null:{point:e.add(r.mul(d)),t:d}}function Ol(e){return El(new Hh(0,0,e.props.w,e.props.h),e.props.geo)}function Kl(e){const t=new Hh(0,0,e.props.w,e.props.h);return[new zh(t.minX,t.minY),new zh(t.center.x,t.minY),new zh(t.maxX,t.minY),new zh(t.minX,t.center.y),t.center,new zh(t.maxX,t.center.y),new zh(t.minX,t.maxY),new zh(t.center.x,t.maxY),new zh(t.maxX,t.maxY)]}function Xl(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:!k(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=_l(e,n);if(void 0===i)return;const r=t.selection.selectedShapes.filter(Ll).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==r.length&&t.editor.commands.updateShapes(r,{source:"user"})}}}function Wl(e){return{id:`geo.default-${e}`,isVisible:e=>Vl(e.tool.activeToolId),getValue:t=>t.editor.getDefaultShapeProps("geo")[e],run({context:t,value:n}){const i=_l(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("geo",{[e]:i})}}}function Nl({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"swatches",id:`${i}.fill`,actionId:e,label:"Fill",options:qf.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:jf.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:Gf.map(e=>({...e,dataUi:`${i}-stroke-width-${e.value}-button`}))}]}]}function _l(e,t){return"strokeWidth"===e?"number"==typeof t&&Gf.some(e=>e.value===t)?t:void 0:b(t)?I(t,f("fill"===e?"fill-slate":"stroke-slate")):void 0}function Vl(e){return Zf.some(t=>t.value===e)}function ql(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function jl({shape:e,isHovered:t}){
29
+ return Ph(Gl,{shape:e,isHovered:t})}function Gl({shape:e,fill:t=e.props.fill,isHovered:n=!1,stroke:i=e.props.stroke,strokeWidth:r=e.props.strokeWidth}){const{geo:o}=e.props,s=r/2,a=Math.max(e.props.w-r,0),d=Math.max(e.props.h-r,0),l=Math.min(10,.12*a,.12*d),c="ellipse"===o||"rectangle"===o?null:Al(new Hh(s,s,a,d),o).map(e=>`${e.x},${e.y}`).join(" "),u={fill:w(t),stroke:Qi(i,n),strokeWidth:r,strokeLinejoin:"round",strokeLinecap:"round"};
30
+ return Ph("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:"ellipse"===o?Ph("ellipse",{...u,cx:e.props.w/2,cy:e.props.h/2,rx:a/2,ry:d/2}):"rectangle"!==o?Ph("polygon",{...u,points:c??""}):Ph("rect",{...u,x:s,y:s,width:a,height:d,rx:l,ry:l})})}function Zl(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function Ql({shape:e,isHovered:t,isSelected:n}){
31
+ return Ph(Jl,{shape:e,isHovered:t,isSelected:n})}function Jl({shape:e,isHovered:t=!1,isSelected:n=!1}){const{h:i,w:r}=e.props,o=t||n,s=Qi("#64748b",t);
32
+ return Ph("svg",{width:"100%",height:"100%",viewBox:`0 0 ${r} ${i}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:o?Ph("rect",{x:.5,y:.5,width:Math.max(r-1,0),height:Math.max(i-1,0),fill:"none",stroke:s,strokeDasharray:"4 4",strokeWidth:1,vectorEffect:"non-scaling-stroke"}):null})}function ec(e){return Math.min(1,Math.max(0,e))}function tc(e,t,n){return Math.min(n,Math.max(t,e))}function nc(e){return!!e&&"object"==typeof e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function ic(e,t){const n=ec(e),i=ec(t);let r=Math.min(n,i),o=Math.max(n,i);return o-r<nS&&(r=Math.max(0,Math.min(.9999,(r+o)/2-5e-5)),o=r+nS),{min:r,max:o}}function rc(e){if(!e||"object"!=typeof e)return null;const t=e;if(!nc(t.topLeft)||!nc(t.bottomRight))return null;const n=ic(t.topLeft.x,t.bottomRight.x),i=ic(t.topLeft.y,t.bottomRight.y);return{topLeft:{x:n.min,y:i.min},bottomRight:{x:n.max,y:i.max}}}function oc(e){const t=rc(e);if(!t)return null;const n=t.topLeft.x,i=t.topLeft.y,r=t.bottomRight.x,o=t.bottomRight.y;return{left:n,top:i,right:r,bottom:o,width:r-n,height:o-i}}function sc(e){return oc(e)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function ac(e,t){return Math.abs(e.left-t.left)<=iS&&Math.abs(e.top-t.top)<=iS&&Math.abs(e.right-t.right)<=iS&&Math.abs(e.bottom-t.bottom)<=iS}function dc(e){return(e=>Math.abs(e.left)<=iS&&Math.abs(e.top)<=iS&&Math.abs(1-e.right)<=iS&&Math.abs(1-e.bottom)<=iS)(e)?null:rc({topLeft:{x:e.left,y:e.top},bottomRight:{x:e.right,y:e.bottom}})}function lc({centerX:e,centerY:t,height:n,width:i}){const r=tc(i,nS,1),o=tc(n,nS,1),s=tc(e-r/2,0,1-r),a=tc(t-o/2,0,1-o);return{left:s,top:a,right:s+r,bottom:a+o,width:r,height:o}}function cc(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function uc({crop:e,shape:t}){const n=sc(e);return{w:t.props.w/n.width,h:t.props.h/n.height}}function hc(e,t){return t===pc(e.id)}function pc(e){return`${sS}${e}`}function gc({localToPage:e,shape:t}){const n=t.props.w,i=t.props.h,r=(0+n)/2,o=(0+i)/2,s={top_left:new zh(0,0),top:new zh(r,0),top_right:new zh(n,0),right:new zh(n,o),bottom_right:new zh(n,i),bottom:new zh(r,i),bottom_left:new zh(0,i),left:new zh(0,o)};return lS.map(t=>{return{kind:"custom",type:rS,id:t,point:e.applyToPoint(s[t]),cursor:(n=t,dS[n])};var n})}function mc({change:e,crop:t,shape:n}){const i=uc({crop:t,shape:n}),r=t.bottomRight.x-t.topLeft.x,o=t.bottomRight.y-t.topLeft.y,s=tc(t.topLeft.x-e.x/i.w,0,1-r),a=tc(t.topLeft.y-e.y/i.h,0,1-o),d=rc({topLeft:{x:s,y:a},bottomRight:{x:s+r,y:a+o}});return d?{id:n.id,props:{crop:d}}:null}function fc(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Sc(e){cS.delete(e)}function yc(e){return u(e)&&"image"===e.type}function xc(){return{createSession(e,{handle:t,shape:n,originPagePoint:i}){return yc(n)&&"custom"===t.kind&&"image.crop"===t.type&&(r=t.id,lS.some(e=>e===r))?function({handleId:e,shapeId:t,startPagePoint:n,startPageToLocal:i,startShape:r,startCrop:o}){return{shapeId:t,historyMark:"image.crop.handle",update({editor:s,pagePoint:a,source:d}){if(!yc(s.getShape(t)))return"stop";const l=(({handleId:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:r,currentPagePoint:o})=>{const s=rc(i)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=uc({crop:s,shape:n});if(a.w<8||a.h<8)return null;const d=t.applyToPoint(r),l=t.applyToPoint(o).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,m=c.w,f=c.h;(e=>"top_left"===e||"left"===e||"bottom_left"===e)(e)?(p=tc(p+l.x,0,u-8),m=u-p):(e=>"top_right"===e||"right"===e||"bottom_right"===e)(e)&&(m=tc(u+l.x,c.x+8,a.w)-p),(e=>"top_left"===e||"top"===e||"top_right"===e)(e)?(g=tc(g+l.y,0,h-8),f=h-g):(e=>"bottom_left"===e||"bottom"===e||"bottom_right"===e)(e)&&(f=tc(h+l.y,c.y+8,a.h)-g);const S=rc({topLeft:{x:p/a.w,y:g/a.h},bottomRight:{x:(p+m)/a.w,y:(g+f)/a.h}});if(!S)return null;const y=new zh(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:m,h:f,crop:S}}})({handleId:e,currentPagePoint:a,pageToLocal:i,shape:r,startCrop:o,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 r}}}function bc(){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=Pc(e);if(!n)return"continue";if("Escape"===t.key&&!t.altKey&&!t.accelKey)return e.cancelEditing("user")&&Sc(n.id),"handled";if("Enter"===t.key&&!t.altKey&&!t.accelKey)return e.completeEditing("user")&&Sc(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 zh(t,0);case"ArrowRight":return new zh(-t,0);case"ArrowUp":return new zh(0,t);case"ArrowDown":return new zh(0,-t);default:return null}})(t);if(i){const t=(({pageDelta:e,shape:t,startCrop:n})=>{const i=rc(n);return!i||e.equals(zh.Zero())?null:mc({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(oS),t(),"continue";if("pointer_down"===i.name){if(t(),0!==i.button||"select"!==n.getActiveToolId()||!n.isActiveToolInInitialState())return"continue";if(n.hitTestSelectionHandle(i.pagePoint))return"continue";const r=Pc(n);return r?((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n.pagePoint);return i.x>=0&&i.y>=0&&i.x<=t.props.w&&i.y<=t.props.h})(n,r,i)?(e={pointerId:i.pointerId,shapeId:r.id,startCrop:r.props.crop,startPagePoint:i.pagePoint.clone(),startPageToLocal:n.computeShapeLocalToPageTransform(r).invert(),startShape:r,hasDragged:!1},"handled"):n.completeEditing("user")?(Sc(r.id),n.dispatch(i),"handled"):"continue":"continue"}return e&&i.pointerId===e.pointerId?"pointer_move"===i.name?(Ic(n,i,e),"handled"):"pointer_up"===i.name?(Ic(n,i,e),e.hasDragged&&n.history.squashToMark(oS,"shape.edit"),t(),"handled"):"continue":"continue"}},selectionHandle:xc()}}function Pc(e){const[t]=e.getSelectedShapes();if(!yc(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&hc(t,n.markId)?t:null}function Ic(e,t,n){if(!n.hasDragged){if(n.startPagePoint.dist2(t.pagePoint)<9)return;e.history.mark(oS),n.hasDragged=!0}if(!yc(e.getShape(n.shapeId)))return;const i=(({currentPagePoint:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:r,shiftKey:o})=>{const s=rc(i);if(!s)return null;const a=t.applyToPoint(r);let d=t.applyToPoint(e).sub(a);return o&&(d=Math.abs(d.x)<Math.abs(d.y)?new zh(0,d.y):new zh(d.x,0)),0===d.x&&0===d.y?null:mc({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 wc(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function vc(){return{id:"land.image",shapeCapabilities:[{type:"image",schemaProps:["w","h","assetId","crop","altText"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Image shape util, SVG exporter, and React renderer live in @land/plugin-image. Asset records store serializable metadata plus a host storageKey; File/Blob/object URL/download behavior stays in the web host."]}],shapeUtils:[new uS],shapeSvgExporters:[new bS],interactionHandlers:[bc()],canvasActions:[Tc(gS),Tc(hS),Tc(pS),{id:mS,isVisible:e=>!!Cc(e)&&!kc(e),isEnabled(e){const t=Cc(e);return!!t&&!t.isLocked},getValue:e=>kc(e),run({context:e}){const t=Cc(e);if(!t||t.isLocked)return;const n=e.editor.getShapeEditingSession();n?.shapeId===t.id&&hc(t,n.markId)?e.editor.completeEditing("user"):e.editor.startEditingShape({shapeId:t.id,markId:pc(t.id),entryMode:"focusEnd"},"user")&&(e=>{cS.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:fS,isVisible:e=>kc(e),isEnabled:e=>kc(e),run({context:e}){const t=Cc(e);t&&e.editor.completeEditing("user")&&Sc(t.id)}},{id:SS,isVisible:e=>kc(e),isEnabled(e){const t=Cc(e);return!!t&&!t.isLocked},run({context:e,value:t}){const n=Cc(e);if(!n||n.isLocked||-1!==t&&1!==t)return;const i=(({direction:e,shape:t})=>{const n=sc(t.props.crop),i=cc(n),r=tc("in"===e?.8:1.25,Math.max(nS/n.width,nS/n.height),Math.min(1/n.width,1/n.height)),o=lc({centerX:i.x,centerY:i.y,width:n.width*r,height:n.height*r});return ac(n,o)?null:{id:t.id,props:{crop:dc(o)}}})({direction:1===t?"in":"out",shape:n});i&&e.editor.commands.updateShapes([i],{source:"user"})}},{id:yS,isVisible:e=>kc(e),isEnabled(e){const t=Cc(e);return!!t&&!t.isLocked},getValue(e){const t=Cc(e);return t?(e=>{const t=e.props.w/e.props.h;for(const n of aS)if(Math.abs(t-n.ratio)<=.01)return n.value;return null})(t):null},run({context:e,value:t}){const n=Cc(e);if(!n||n.isLocked||"string"!=typeof t)return;const i=aS.find(e=>e.value===t);if(!i)return;const r=function({preset:e,shape:t}){const n=cc(sc(t.props.crop)),i=uc({crop:t.props.crop,shape:t}),r=aS.find(t=>t.value===e)?.ratio??null;if(!r)return null;const o=r*(i.h/i.w);let s=1,a=s/o;return a>1&&(a=1,s=a*o),(({nextRect:e,shape:t})=>{const n=sc(t.props.crop);if(ac(n,e))return null;const i=uc({crop:t.props.crop,shape:t}),r=new zh((e.left-n.left)*i.w,(e.top-n.top)*i.h).rot(t.rotation);return{id:t.id,x:t.x+r.x,y:t.y+r.y,props:{w:e.width*i.w,h:e.height*i.h,crop:dc(e)}}})({nextRect:lc({centerX:n.x,centerY:n.y,width:s,height:a}),shape:t})}({preset:i.value,shape:n});r&&e.editor.commands.updateShapes([r],{source:"user"})}},{id:xS,isVisible:e=>kc(e),isEnabled(e){const t=Cc(e);return!!t&&!t.isLocked&&!!t.props.crop},run({context:e}){const t=Cc(e);if(!t||t.isLocked)return;const n=(({baselineShape:e,shape:t})=>{const n=e.x,i=e.y,r=e.props.w,o=e.props.h,s=rc(e.props.crop);return Math.abs(t.x-n)<=iS&&Math.abs(t.y-i)<=iS&&Math.abs(t.props.w-r)<=iS&&Math.abs(t.props.h-o)<=iS&&(null===t.props.crop&&null===s||null!==t.props.crop&&null!==s&&Math.abs(t.props.crop.topLeft.x-s.topLeft.x)<=iS&&Math.abs(t.props.crop.topLeft.y-s.topLeft.y)<=iS&&Math.abs(t.props.crop.bottomRight.x-s.bottomRight.x)<=iS&&Math.abs(t.props.crop.bottomRight.y-s.bottomRight.y)<=iS)?null:{id:t.id,x:n,y:i,props:{w:r,h:o,crop:s}}})({baselineShape:(i=t.id,cS.get(i)??null??t),shape:t});var i;n&&e.editor.commands.updateShapes([n],{source:"user"})}}],toolbarContributions:[{id:"image.tool-toolbar",surface:"tool",placement:"chrome",order:55,actionIds:[gS],getGroups:()=>[{id:"image.tools",items:[{kind:"button",id:gS,actionId:gS,label:"Image",icon:"image-plus",dataUi:"insert-image-tool-button"}]}]},{id:"image.selection-toolbar",surface:"selection",order:30,actionIds:[mS,fS,SS,yS,xS,hS,pS],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups(e){const t=[];return kc(e)&&t.push({id:"image.crop-zoom",order:10,items:[{kind:"stepper",id:"image.crop.zoom-stepper",actionId:SS,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:yS,options:aS.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:xS,actionId:xS,label:"Reset crop",icon:"rotate-ccw",dataUi:"reset-image-crop-button"}]}),t.push({id:"image.asset",order:40,items:[{kind:"button",id:mS,actionId:mS,label:"Crop image",icon:"crop",dataUi:"crop-image-button"},{kind:"button",id:fS,actionId:fS,label:"Done cropping",icon:"check",dataUi:"done-cropping-button"},{kind:"button",id:hS,actionId:hS,label:"Replace image",icon:"image-plus",dataUi:"replace-image-button"},{kind:"button",id:pS,actionId:pS,label:"Download original",icon:"download",dataUi:"download-image-original-button"}]}),t}},{id:"image.floating-selection-toolbar",surface:"selection",placement:"floating",order:30,actionIds:[mS,fS,SS,yS,xS,hS,pS],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups:e=>kc(e)?[{id:"image.floating-crop-zoom",order:10,items:[{kind:"stepper",id:"image.floating-crop.zoom-stepper",actionId:SS,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:yS,options:aS.map(e=>({value:e.value,label:e.label,dataUi:`floating-image-crop-aspect-${e.value.replace(":","-")}-button`}))}]},{id:"image.floating-crop-actions",order:30,items:[{kind:"button",id:"image.floating-crop.done",actionId:fS,label:"Done cropping",icon:"check",dataUi:"floating-done-cropping-button"},{kind:"button",id:"image.floating-crop.reset",actionId:xS,label:"Reset crop",icon:"rotate-ccw",dataUi:"floating-reset-image-crop-button"}]}]:[{id:"image.floating-asset",order:10,items:[{kind:"button",id:"image.floating.crop",actionId:mS,label:"Crop image",icon:"crop",dataUi:"floating-crop-image-button"},{kind:"button",id:"image.floating.replace",actionId:hS,label:"Replace image",icon:"image-plus",dataUi:"floating-replace-image-button"},{kind:"button",id:"image.floating.download",actionId:pS,label:"Download original",icon:"download",dataUi:"floating-download-image-original-button"}]}]}],contextMenuContributions:[{id:"image.shape-context-menu",target:"selection",order:30,actionIds:[mS,hS,pS],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getSections:()=>[{id:"image.asset-context-menu",title:"Image",items:[{kind:"command",id:mS,actionId:mS,label:"Crop image",icon:"crop",dataUi:"context-menu-crop-image-button"},{kind:"command",id:hS,actionId:hS,label:"Replace image",icon:"image-plus",dataUi:"context-menu-replace-image-button"},{kind:"command",id:pS,actionId:pS,label:"Download original",icon:"download",dataUi:"context-menu-download-image-original-button"}]}]}]}}function Cc(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return null;const[t]=e.selection.selectedShapes;return yc(t)?t:null}function kc(e){const t=Cc(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!hc(t,n.markId))}function Tc(e){return{id:e,isVisible:()=>!1,isEnabled:()=>!1,run(){throw new Error(`Image toolbar action ${e} requires a host implementation.`)}}}function Bc({editor:e,isHovered:t,shape:n,shapeEditingSession:i}){const{altText:r,assetId:o,crop:s,h:a,w:d}=n.props,l=o?e.resolveAssetUrl(o):null;if(!l)return Ph("div",{"data-ui":"image-shape-missing-asset",style:{alignItems:"center",background:"#f1f5f9",border:`1px solid ${t?pg:"#cbd5e1"}`,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 c=(({crop:e,shapeHeight:t,shapeWidth:n})=>{const i=oc(e);if(!i)return null;const r=n/i.width,o=t/i.height;return{imageX:-i.left*r,imageY:-i.top*o,imageWidth:r,imageHeight:o,rect:i}})({crop:s,shapeHeight:a,shapeWidth:d});if(c){const e=i?.shapeId===n.id&&hc(n,i.markId),o={display:"block",height:c.imageHeight,left:c.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:c.imageY,userSelect:"none",width:c.imageWidth};
33
+ return Ih("div",{"data-ui":"image-shape",style:{display:"block",height:a,overflow:e?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:d},children:[e?Ph("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:l,style:{...o,opacity:.1}}):null,
34
+ Ph("div",{"data-ui":"image-crop-window",style:{height:a,overflow:"hidden",position:"absolute",inset:0,width:d},children:Ph("img",{alt:r,draggable:!1,src:l,style:o})}),
35
+ Ph(Mc,{isVisible:t})]})}
36
+ return Ih("div",{"data-ui":"image-shape",style:{display:"block",height:a,pointerEvents:"none",position:"relative",userSelect:"none",width:d},children:[Ph("img",{alt:r,draggable:!1,src:l,style:{display:"block",height:a,objectFit:"fill",width:d}}),Ph(Mc,{isVisible:t})]})}function Mc({isVisible:e}){return e?Ph("div",{"aria-hidden":"true","data-ui":"image-hover-outline",style:{boxShadow:`inset 0 0 0 2px ${pg}`,inset:0,pointerEvents:"none",position:"absolute"}}):null}function Ec({handle:e,strokeWidth:t}){const{x:n,y:i,w:r,h:o,center:s}=e.bounds,a=1.35*Math.max(r,o),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:r})=>{switch(e){case"top_left":return{kind:"corner",points:[Ac(i-n,r+t),Ac(i-n,r-n),Ac(i+t,r-n)].join(" ")};case"top":return{kind:"edge",x1:i-t,y1:r-n,x2:i+t,y2:r-n};case"top_right":return{kind:"corner",points:[Ac(i-t,r-n),Ac(i+n,r-n),Ac(i+n,r+t)].join(" ")};case"right":return{kind:"edge",x1:i+n,y1:r-t,x2:i+n,y2:r+t};case"bottom_right":return{kind:"corner",points:[Ac(i+n,r-t),Ac(i+n,r+n),Ac(i-t,r+n)].join(" ")};case"bottom":return{kind:"edge",x1:i-t,y1:r+n,x2:i+t,y2:r+n};case"bottom_left":return{kind:"corner",points:[Ac(i+t,r+n),Ac(i-n,r+n),Ac(i-n,r-t)].join(" ")};case"left":return{kind:"edge",x1:i-n,y1:r-t,x2:i-n,y2:r+t};default:return{kind:"edge",x1:i,y1:r,x2:i,y2:r}}})({id:e.id,extension:a,outwardOffset:d/2,centerX:s.x,centerY:s.y});
37
+ return Ih("g",{children:[Ph("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:n-.8*r,y:i-.8*o,width:2.6*r,height:2.6*o,fill:"transparent",style:{cursor:e.cursor??"grab",pointerEvents:"auto"}}),"corner"===c.kind?Ph("polyline",{points:c.points,...l}):Ph("line",{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,...l})]})}function Ac(e,t){return`${e},${t}`}function Rc(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function Fc(e,t){e.setLaserTrail(t.sessionId,t.trail)}function Lc(){return"undefined"==typeof performance?Date.now():performance.now()}function $c(e,t,n,i){const r=e.samples[e.samples.length-1];if(!r)return void e.samples.push({...t,time:i,velocity:0});const o=FS/n,s=Yc(r,t);if(s<o)return void(e.samples[e.samples.length-1]={...r,...t,time:i});const a=s*n/Math.max(HS,i-r.time);e.samples.push({...t,time:i,velocity:Vc(r.velocity,a,.68)})}function Dc(e,t){e.samples=Uc(e.samples,t)}function Uc(e,t){const n=e[e.length-1];if(!n)return[];const i=t-qc(YS+n.velocity*OS,YS,KS);if(n.time<i)return[];const r=e.findIndex(e=>e.time>=i);if(-1===r)return[];const o=e.slice(r),s=e[r-1],a=o[0];return s&&a.time>i?[(d=s,l=a,c=qc((i-s.time)/(a.time-s.time),0,1),{..._c(d,l,c),time:Vc(d.time,l.time,c),velocity:Vc(d.velocity,l.velocity,c)}),...o]:o;var d,l,c}function zc(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?Wc(i,e[t]):Wc(t===e.length-1?e[t]:i,n))}function Hc(e,t,n){const i=[];for(let r=0;r<n;r++){const o=2*Math.PI*r/n;i.push({x:e.x+Math.cos(o)*t,y:e.y+Math.sin(o)*t})}return i}function Yc(e,t){return Math.sqrt(Oc(e,t))}function Oc(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function Kc(e){return{x:-e.y,y:e.x}}function Xc(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Wc(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Nc(e,t){return{x:e.x*t,y:e.y*t}}function _c(e,t,n){return{x:Vc(e.x,t.x,n),y:Vc(e.y,t.y,n)}}function Vc(e,t,n){return e+(t-e)*n}function qc(e,t,n){return Math.max(t,Math.min(n,e))}function jc(e,t){const n=e[e.length-1];!n||Oc(n,t)>.04?e.push(t):e[e.length-1]=t}function Gc(e){if(e.length<2)return null;if(2===e.length)return`M ${Qc(e[0])} L ${Qc(e[1])} Z`;const t=[`M ${Qc(Zc(e[0],e[1]))}`];for(let n=1;n<e.length;n++){const i=e[n],r=e[(n+1)%e.length];t.push(`Q ${Qc(i)} ${Qc(Zc(i,r))}`)}return t.push("Z"),t.join(" ")}function Zc(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function Qc(e){return`${Jc(e.x)},${Jc(e.y)}`}function Jc(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function eu({childIds:e,depth:t,editor:n,index:i,pageId:r,shape:o}){return{id:o.id,parentId:o.parentId,pageId:r,type:o.type,childIds:e,siblingIndex:i,depth:t,displayName:o.type,canReceiveChildren:n.canUseShapeParent(o.id),isHidden:o.isHidden,isLocked:o.isLocked,isEffectivelyHidden:n.isShapeHidden(o.id),isEffectivelyLocked:n.isShapeOrAncestorLocked(o.id)}}function tu(e,t){let n=0,i=e.getShape(t);const r=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(r.has(t))break;r.add(t),i=e.getShape(t),n+=1}return n}function nu(e){return{id:e.id,name:e.name,index:e.index}}function iu(e,t){const n=e.sessionSignal.get(),i=n.activeToolId;t.assertToolId(i);const r=i,o=e.getPages().map(t=>({pageId:t.id,selectedShapeIds:e.getSelectedShapeIds(t.id),camera:{...e.getCamera(t.id)}}));return{currentPageId:n.currentPageId,activeToolId:r,isToolLocked:n.isToolLocked,pages:o}}function ru(e,t,n){const i=e.getDefaultShapeProps("geo"),[r]=e.commands.createShapes([{type:"geo",x:n.x,y:n.y,props:{...i,geo:t,w:n.w??i.w,h:n.h??i.h,fill:n.fill??i.fill,stroke:n.stroke??i.stroke,strokeWidth:n.strokeWidth??i.strokeWidth}}],{source:"user"});return r&&"geo"===r.type?{id:r.id,type:r.type}:null}function ou(e){return{create(t){const n=e.getDefaultShapeProps("arrow"),i=ua(e,{startPagePoint:new zh(t.start.x,t.start.y),endPagePoint:new zh(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,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 su(e){return{createRectangle:t=>ru(e,"rectangle",t),createEllipse:t=>ru(e,"ellipse",t),createDiamond:t=>ru(e,"diamond",t),createTriangle:t=>ru(e,"triangle",t),createHexagon:t=>ru(e,"hexagon",t),createStar:t=>ru(e,"star",t)}}function au(e){return{create(t){const n=e.getDefaultShapeProps("text"),[i]=e.commands.createShapes([{type:"text",x:t.x,y:t.y,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:sr(t.text)}}],{source:"user"});return i&&"text"===i.type?{id:i.id,type:i.type}:null}}}function du(e){return{create(t){const n=e.getDefaultShapeProps("frame"),[i]=e.commands.createShapes([{type:"frame",x:t.x,y:t.y,props:{...n,w:t.w??n.w,h:t.h??n.h,name:t.name??n.name,fill:t.fill??n.fill,stroke:t.stroke??n.stroke,strokeWidth:t.strokeWidth??n.strokeWidth}}],{source:"user"});return i&&"frame"===i.type?{id:i.id,type:i.type}:null},moveShapesToFrame(t,n){const i=e.getShape(n);if(!i||"frame"!==i.type)return[];const r=t.filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked});return 0===r.length?[]:(e.commands.reparentShapes({ids:r,parentId:n},{source:"user"}),r)}}}function lu(e,t){const n=e.getShape(t.id);if("geo"===t.type){const e=(n?.props)?.geo;return{...t,displayName:cu(e),geoKind:e}}if("image"===t.type){const i=n?.props,r=i?.assetId??null,o=((r?e.getAsset(r):void 0)?.props)?.name,s=i?.altText?.trim();return{...t,displayName:o||s||"Image",imageAssetId:r,imageThumbnailSrc:r?e.resolveAssetUrl(r):null}}if("text"===t.type){const e=n?.props,i=e?.richText?ar(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 cu(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 uu(e){const t=function(e){const{featureControllers:t,editor:n,productId:i}=e;return{features:t,snapshot(){const t=n.getActiveToolId();e.assertToolId(t);const r=t;return{productId:i,pageId:n.getCurrentPageId(),activeToolId:r,selectedShapeIds:n.getSelectedShapeIds(),shapeCount:n.getCurrentPageShapeIds().length,session:iu(n,e)}},clearHistory(){n.history.clear()},canUndo:()=>n.historyStateSignal.get().canUndo,canRedo:()=>n.historyStateSignal.get().canRedo,undo:()=>n.undo(),redo:()=>n.redo(),select(e){n.commands.setSelectedShapeIds(e,{source:"user"})},selectAll(){n.selectAllCurrentPage("user")},deleteSelection(){n.deleteSelection("user")},deleteShapes(e){n.deleteShapesById(e,"user")},duplicateSelection:()=>n.duplicateSelection(),centerOnShape(e){const t=n.getShapePageId(e);if(!t)return!1;t!==n.getCurrentPageId()&&n.commands.setCurrentPageId(t,{source:"user"});const i=n.getShapeSubtreePageBounds(e);if(!i)return!1;const r=n.viewportScreenSizeSignal.get();if(r.w<=0||r.h<=0)return!1;const o=n.getCurrentCamera();return n.commands.setCamera({pageId:t,camera:{x:i.center.x-r.w/(2*o.z),y:i.center.y-r.h/(2*o.z),z:o.z}},{source:"user"}),!0},getLayerTree:e=>(({editor:e,pageId:t=e.getCurrentPageId()})=>{const n=[],i=(r,o)=>{e.getChildShapes(r).forEach((r,s)=>{const a=e.getChildShapeIds(r.id);n.push(eu({childIds:a,depth:o,editor:e,index:s,pageId:t,shape:r})),i(r.id,o+1)})};return i(t,0),n})({editor:n,pageId:e??n.getCurrentPageId()}),getLayerNode:e=>(({editor:e,id:t})=>{const n=e.getShape(t),i=n?e.getShapePageId(n.id):null;if(!n||!i)return null;const r=e.getChildShapeIds(n.parentId);return eu({childIds:e.getChildShapeIds(n.id),depth:tu(e,n.id),editor:e,index:r.indexOf(n.id),pageId:i,shape:n})})({editor:n,id:e}),setShapesHidden:(e,t)=>n.setShapesHidden(e,t,"user"),setShapesLocked:(e,t)=>n.setShapesLocked(e,t,"user"),groupShapes:e=>n.groupShapes(e,"user")?.id??null,ungroupShapes:e=>n.ungroupShapes(e,"user"),moveShapesInParentOrder:(e,t)=>n.moveShapesInParentOrder(e,t,"user"),moveShapesToParentOrderEdge:(e,t)=>n.moveShapesToParentOrderEdge(e,t,"user"),moveShapesToLayerPlacement:(e,t)=>n.moveShapesToParentPlacementResult({ids:e,parentId:t.parentId,beforeId:t.beforeId},"user"),getLayerActionState:e=>({canGroup:n.canGroupShapes(e),canUngroup:n.canUngroupShapes(e),canMoveBackward:n.canMoveShapesInParentOrder(e,"backward"),canMoveForward:n.canMoveShapesInParentOrder(e,"forward")}),setTool(e){if(!n.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);n.setActiveTool(e,"user")},setCamera(e,t){n.commands.setCamera({pageId:t,camera:e},{source:"user"})},resetView(){n.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},getPages:()=>n.getPages().map(nu),createPage:e=>nu(n.createPageAndSelect(e?{name:e}:void 0,"user")),renamePage(e,t){n.renamePage(e,t,"user")},deletePage:e=>n.deletePage(e,"user"),selectPage(e){n.selectPage(e,"user")},exportSelectionSvg:()=>n.getSvgString(n.getSelectedShapeIds(),{padding:16})?.svg??null,exportPageSvg:()=>n.getSvgString(n.getCurrentPageShapeIds(),{padding:16})?.svg??null}}(e),n={arrow:ou(i=e.editor),geo:su(i),text:au(i),frame:du(i)};var i;return{...t,...n,getLayerTree:n=>t.getLayerTree(n).map(t=>lu(e.editor,t)),getLayerNode(n){const i=t.getLayerNode(n);return i?lu(e.editor,i):null}}}function hu(e,t){const n=e.getDocumentSnapshot();if(0===t.length)return n;const i=new Set(n.records.map(e=>e.id)),r=t.filter(pu).filter(e=>!i.has(e.id));return{...n,records:[...n.records,...r]}}function pu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&"string"==typeof e.id}function gu(e={}){let t=[];return{async restore(n){const{documentSnapshot:i,sessionSnapshot:r}=await(async(e={})=>{const[t,n]=await Promise.all([yu(fu(e)),yu(Su(e))]);return{documentSnapshot:t,sessionSnapshot:n}})(e),o=function(e,{documentSnapshot:t,sessionSnapshot:n}){let i=null,r=[];if(t){const n=((e,t)=>{const n=(({bindingUtils:e,renderableShapeTypes:t,shapeUtils:n})=>({modelShapeTypes:new Set([...n.values()].map(e=>e.type)),modelBindingTypes:new Set([...e.values()].map(e=>e.type)),renderableShapeTypes:t?new Set(t):void 0}))({bindingUtils:e.bindingUtils,shapeUtils:e.shapeUtils}),i=(({requirements:e,support:t})=>({modelShapeTypes:xi(e.shapeTypes,t.modelShapeTypes),modelBindingTypes:xi(e.bindingTypes,t.modelBindingTypes),renderableShapeTypes:t.renderableShapeTypes?xi(e.shapeTypes,t.renderableShapeTypes):[]}))({requirements:Si(t),support:n});if(0===i.modelShapeTypes.length&&0===i.modelBindingTypes.length)return{kind:"full",snapshot:t};const r=(({snapshot:e,support:t})=>{const n=Fe(e,"document"),i=new Set,r=new Set,o=new Set,s=new Set,a=[];for(const l of n.records)yi(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),r.add(l.type));const d=n.records.filter(e=>{if(!yi(e))return!0;if("shape"===e.typeName&&"string"==typeof e.type)return!!t.modelShapeTypes.has(e.type)||(a.push(e),!1);if("binding"===e.typeName&&"string"==typeof e.type){const n=t.modelBindingTypes.has(e.type),r=!i.has(e.fromId)&&!i.has(e.toId);return!(!n||!r)||("string"==typeof e.id&&e.id.startsWith("binding:")&&o.add(e.id),s.add(e.type),a.push(e),!1)}return!0});return{snapshot:{schemaVersion:n.schemaVersion,records:d},removedShapeIds:bi(i),removedShapeTypes:bi(r),removedBindingIds:bi(o),removedBindingTypes:bi(s),removedRecords:a}})({snapshot:t,support:n});return{kind:"partial",snapshot:r.snapshot,removedBindingIds:r.removedBindingIds,removedBindingTypes:r.removedBindingTypes,removedShapeIds:r.removedShapeIds,removedShapeTypes:r.removedShapeTypes,preservedRecords:r.removedRecords,unsupportedBindingTypes:i.modelBindingTypes,unsupportedShapeTypes:i.modelShapeTypes}})(e,t);"partial"===n.kind&&(o=n,console.warn("[land] Restored a persisted canvas snapshot with unsupported document records preserved for round-trip persistence.",{removedBindingIds:o.removedBindingIds,removedBindingTypes:o.removedBindingTypes,removedShapeIds:o.removedShapeIds,removedShapeTypes:o.removedShapeTypes,unsupportedBindingTypes:o.unsupportedBindingTypes,unsupportedShapeTypes:o.unsupportedShapeTypes}),r=n.preservedRecords,i={kind:"preserving-unsupported-records",preservedRecordCount:n.preservedRecords.length,unsupportedBindingTypes:n.unsupportedBindingTypes,unsupportedShapeTypes:n.unsupportedShapeTypes}),e.loadDocumentSnapshot(n.snapshot,{source:"system"})}var o;return n&&e.loadSessionSnapshot(n,{source:"system"}),e.history.clear(),{autoPersistence:"enabled",preservedUnsupportedRecords:r,status:i}}(n,{documentSnapshot:i,sessionSnapshot:r});return t=o.preservedUnsupportedRecords??[],o},start(n){const i=new qS(n,{getDocumentSnapshot:()=>hu(n,t),options:e});return i.start(),()=>i.stop()},flushSnapshot:n=>mu(n,e,{documentSnapshot:hu(n,t)}),discardUnsupportedRecords:async n=>(await mu(n,e),t=[],{autoPersistence:"enabled",status:null})}}async function mu(e,t={},{documentSnapshot:n=e.getDocumentSnapshot()}={}){const i=JSON.stringify(n),r=JSON.stringify(e.getSessionSnapshot());await Promise.all([bu(fu(t),i),bu(Su(t),r)])}function fu(e){return e.storageNamespace?`${e.storageNamespace}.document`:"land.canvas.document"}function Su(e){return e.storageNamespace?`${e.storageNamespace}.session`:"land.canvas.session"}async function yu(e){const t=await(async e=>{const t=await xu();return t?new Promise((n,i)=>{const r=t.transaction(_S,"readonly");r.addEventListener("complete",()=>t.close()),r.addEventListener("abort",()=>{t.close(),i(r.error)}),r.addEventListener("error",()=>{t.close(),i(r.error)});const o=r.objectStore(_S).get(e);o.addEventListener("success",()=>{n("string"==typeof o.result?o.result:null)}),o.addEventListener("error",()=>i(o.error))}):null})(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}function xu(){return"undefined"==typeof indexedDB?Promise.resolve(null):new Promise((e,t)=>{const n=indexedDB.open(NS,2);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains("snapshots")||n.result.createObjectStore(_S),n.result.objectStoreNames.contains("imageBlobs")||n.result.createObjectStore(VS)}),n.addEventListener("success",()=>e(n.result)),n.addEventListener("error",()=>t(n.error))})}async function bu(e,t){const n=await xu();n&&await new Promise((i,r)=>{const o=n.transaction(_S,"readwrite");o.addEventListener("complete",()=>{n.close(),i()}),o.addEventListener("abort",()=>{n.close(),r(o.error)}),o.addEventListener("error",()=>{n.close(),r(o.error)}),o.objectStore(_S).put(t,e)})}async function Pu(e){const t=await ku();return t?new Promise((n,i)=>{const r=t.transaction(VS,"readonly");r.addEventListener("complete",()=>t.close()),r.addEventListener("abort",()=>{t.close(),i(r.error)}),r.addEventListener("error",()=>{t.close(),i(r.error)});const o=r.objectStore(VS).get(e);o.addEventListener("success",()=>{n(o.result instanceof Blob?o.result:null)}),o.addEventListener("error",()=>i(o.error))}):null}async function Iu(e){const t=await Pu(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 wu(e){const t=await ku();t&&await new Promise((n,i)=>{const r=t.transaction(VS,"readwrite");r.addEventListener("complete",()=>{t.close(),n()}),r.addEventListener("abort",()=>{t.close(),i(r.error)}),r.addEventListener("error",()=>{t.close(),i(r.error)}),r.objectStore(VS).delete(e)})}function vu(e,t){const n=e.getAsset(t),i=n?n.props.storageKey:null;return"string"==typeof i&&i.length>0?i:null}function Cu(e){const t=new Set;for(const n of e.getAssets()){const e=n.props.storageKey;"string"==typeof e&&e.length>0&&t.add(e)}return t}function ku(){return"undefined"==typeof indexedDB?Promise.resolve(null):new Promise((e,t)=>{const n=indexedDB.open(NS,2);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains("snapshots")||n.result.createObjectStore(_S),n.result.objectStoreNames.contains("imageBlobs")||n.result.createObjectStore(VS)}),n.addEventListener("success",()=>e(n.result)),n.addEventListener("error",()=>t(n.error))})}async function Tu(e){const t=URL.createObjectURL(e),n=await(i=t,new Promise((e,t)=>{const n=new Image;n.addEventListener("load",()=>{e({width:n.naturalWidth||n.width,height:n.naturalHeight||n.height})}),n.addEventListener("error",()=>{t(new Error("Could not decode image file."))}),n.src=i})).finally(()=>{URL.revokeObjectURL(t)});var i;const{storageKey:r}=await async function(e){const t="undefined"!=typeof crypto&&"randomUUID"in crypto?`${jS}${crypto.randomUUID()}`:`${jS}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=await ku();if(!n)throw new Error("IndexedDB is not available for image storage.");return await new Promise((i,r)=>{const o=n.transaction(VS,"readwrite");o.addEventListener("complete",()=>{n.close(),i()}),o.addEventListener("abort",()=>{n.close(),r(o.error)}),o.addEventListener("error",()=>{n.close(),r(o.error)}),o.objectStore(VS).put(e,t)}),{storageKey:t}}(e);return{name:e.name||"Image",storageKey:r,mimeType:e.type||"image/png",fileSize:e.size,width:n.width,height:n.height}}function Bu(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 Mu(e,t){return function(e,t,n){return e.screenToPage(((e,t=qr())=>{if(!t)return new zh(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new zh(e.clientX-n.left,e.clientY-n.top)})(t,n))}(e,t)}function Eu({filename:e,url:t}){const n=document.createElement("a");n.href=t,n.download=e,n.click()}function Au(e,t){return e.commands.createAsset({type:"image",props:{w:t.width,h:t.height,name:t.name,storageKey:t.storageKey,mimeType:t.mimeType,fileSize:t.fileSize,isAnimated:"image/gif"===t.mimeType}},{source:"user"})}async function Ru({editor:e,file:t,imageObjectUrls:n,pagePoint:i,size:r,flushSnapshot:o}){if(!t.type.startsWith("image/"))return null;const s=await Tu(t);await n.preload(s.storageKey);let a=null;try{const t=Au(e,s);a=t.id;const n=r??(({height:e,width:t})=>{const n=Math.min(1,360/Math.max(t,e));return{w:Math.max(24,Math.round(t*n)),h:Math.max(24,Math.round(e*n))}})({width:t.props.w,height:t.props.h}),d=e.viewportPageBoundsSignal.get(),l=i??d?.center??e.screenToPage(new zh(360,240)),[c]=e.commands.createShapes([{type:"image",x:Math.round(l.x-n.w/2),y:Math.round(l.y-n.h/2),props:{...n,assetId:t.id,crop:null,altText:s.name}}],{source:"user"});return c?(e.commands.setSelectedShapeIds([c.id],{source:"user"}),await(o?.(e)),c.id):null}catch(d){throw a&&e.commands.deleteAsset(a,{source:"system"}),n.release(s.storageKey),await wu(s.storageKey),d}}async function Fu({editor:e,file:t,imageObjectUrls:n,flushSnapshot:i}){if(!t.type.startsWith("image/"))return;const[r]=e.getSelectedShapes();if(!yc(r)||r.isLocked)return;const o=r.props.assetId,s=await Tu(t);await n.preload(s.storageKey);let a=null;try{const t=Au(e,s);a=t.id,e.commands.updateShapes([{id:r.id,props:{assetId:t.id,crop:null,altText:s.name}}],{source:"user"}),o&&!((e,t)=>e.getDocumentSnapshot().records.some(e=>"shape"===e.typeName&&e.props.assetId===t))(e,o)&&e.commands.deleteAsset(o,{source:"user"}),e.commands.setSelectedShapeIds([r.id],{source:"user"}),await(i?.(e))}catch(d){throw a&&e.commands.deleteAsset(a,{source:"system"}),n.release(s.storageKey),await wu(s.storageKey),d}}async function Lu({editor:e,imageObjectUrls:t}){const[n]=e.getSelectedShapes();if(!yc(n)||!n.props.assetId)return;const i=e.getAsset(n.props.assetId);if(!g(r=i)||"image"!==r.type)return;var r;const o=i.props.storageKey,s="string"==typeof i.props.name&&i.props.name.length>0?i.props.name:"land-image";if(!o)return;const a=await Pu(o);if(a)return void(await(async({blob:e,filename:t})=>{const n=URL.createObjectURL(e);try{Eu({filename:t,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}})({blob:a,filename:s}));const d=t.resolve(o);d&&Eu({filename:s,url:d})}function $u({assetResolverTokens:e,services:t}){return e.map(e=>t.get(e)).filter(e=>!!e)}function Du(e){return{id:e}}function Uu(e){return e.get(ZS)}async function zu({context:e,services:t}){const n=Uu(t);if(!n)return null;const i=e.editor.createClipboardPayloadFromSelection();return i?(await n.write(i),i):null}async function Hu({atMenuPoint:e=!1,context:t,services:n}){const i=Uu(n);if(!i)return;const r=await i.read();r&&t.editor.pasteClipboardPayload({payload:r,pagePoint:Yu({atMenuPoint:e,context:t}),source:"user"})}function Yu({atMenuPoint:e,context:t}){return e&&Ou(t)?t.menu.anchor.pagePoint:t.editor.inputs.state.get().currentPagePoint??t.editor.viewportPageBoundsSignal.get()?.center??void 0}function Ou(e){return"menu"in e}function Ku(e){const[t]=e.selection.selectedShapes;return!(1!==e.selection.count||!t?.parentId.startsWith("shape:"))&&"frame"===e.editor.getShape(t.parentId)?.type}function Xu(e){return Math.min(1,Math.max(0,e))}function Wu({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 Nu(){return{token:Cy,create(){const e=(()=>{const e=new Map,t=new Map,n=async n=>{const i=e.get(n);if(i)return i;const r=t.get(n);if(r)return r;const o=Pu(n).then(t=>{if(!t)return null;const i=URL.createObjectURL(t);return e.set(n,i),i}).finally(()=>{t.delete(n)});return t.set(n,o),o};return{async preloadForEditor(e){await Promise.all(Array.from(Cu(e)).map(e=>n(e)))},preload:n,resolve:t=>e.get(t)??null,resolveAssetUrl(t,n){const i=vu(t,n);return i?e.get(i)??null:null},release(n){const i=e.get(n);i&&(URL.revokeObjectURL(i),e.delete(n)),t.delete(n)},releaseAll(){for(const t of e.values())URL.revokeObjectURL(t);e.clear(),t.clear()}}})();return{objectUrls:e,cleanupAfterRestore:t=>async function({editor:e,objectUrls:t}){const n=Cu(e),i=await(async()=>{const e=await ku();return e?new Promise((t,n)=>{const i=e.transaction(VS,"readonly");i.addEventListener("complete",()=>e.close()),i.addEventListener("abort",()=>{e.close(),n(i.error)}),i.addEventListener("error",()=>{e.close(),n(i.error)});const r=i.objectStore(VS).getAllKeys();r.addEventListener("success",()=>{t(r.result.map(String))}),r.addEventListener("error",()=>n(r.error))}):[]})(),r=[];for(const o of i)n.has(o)||(t?.release(o),await wu(o),r.push(o));return r}({editor:t,objectUrls:e}).then(()=>{}).catch(e=>{console.warn("Could not clean up unreferenced image blobs.",e)}),preloadForEditor:t=>e.preloadForEditor(t),resolveAssetUrl:(t,n)=>e.resolveAssetUrl(t,n)}},dispose(e){e.objectUrls.releaseAll()}}}function _u(e){return{async inline({editor:t,exportedShapeIds:n,svg:i}){let r=i;const o=new Set;for(const s of n){const n=t.getShape(s);if(!yc(n)||!n.props.assetId)continue;const i=n.props.assetId;if(o.has(i))continue;o.add(i);const a=t.getAsset(i),d=a&&"object"==typeof a.props?a.props.storageKey:null;if("string"!=typeof d||0===d.length)continue;const l=e.objectUrls.resolve(d)??await e.objectUrls.preload(d);if(!l)continue;const c=await Iu(d);c&&(r=r.split(l).join(c))}return r}}}function Vu(e){if(!(e=>Ey.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: ${Ay}.`);throw new Error(`Unknown canvas kit tool "${e}". Available tool ids: ${Ay}.`)}}function qu(e){return ju({...e,assertToolId:e.assertToolId??Vu})}function ju(e){return Object.assign({},uu(e),{image:e.featureControllers.get(ky)})}function Gu({assetInliners:e=[],editor:t,themeRootRef:n}){const[i,r]=xh(null);return{status:i,exportSvg:uh(async i=>{const o=await async function({assetInliners:e=[],editor:t,padding:n=16,resolveThemeColor:i,shapeIds:r}){const o=t.repairExportIntegrity(r),s=t.getSvgString(r,{padding:n,resolveThemeColor:i}),a=t.getExportIntegrityReport(r),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((o.before.issues.length>0||a.issues.length>0)&&console.warn("SVG export integrity report",{before:o.before,after:o.after,final:a}),!s)return{status: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 r(o.status),o},[e,t,n])}}function Zu({flushSnapshot:e}){return{id:"canvas-kit.image",services:[Nu(),{token:By,create:()=>new Ty}],assetResolverTokens:[Cy],initializeRuntime(t){(({flushSnapshot:e}={})=>({featureControllers:t,editor:n,services:i})=>{if(t.get(ky))return;const r=i.get(Cy);r&&t.register(ky,{insertImage:({file:t,pagePoint:i,size:o,source:s="file-picker"})=>Ru({editor:n,file:t,imageObjectUrls:r.objectUrls,pagePoint:i,size:o,flushSnapshot:e,source:s}),async replaceSelectedImage({file:t}){if(!t.type.startsWith("image/"))return!1;const[i]=n.getSelectedShapes();return!(!yc(i)||i.isLocked||(await Fu({editor:n,file:t,imageObjectUrls:r.objectUrls,flushSnapshot:e}),0))},downloadSelectedImageOriginal:()=>Lu({editor:n,imageObjectUrls:r.objectUrls})})})({flushSnapshot:e})(t),function({pluginHostRuntime:e,services:t}){const n=t.get(Cy),i=t.get(By);n&&i&&(({hostBridge:e,imageObjectUrls:t,pluginHostRuntime:n})=>{n.toolbarRegistry.registerHostAction({id:gS,run(){e.openInsertFilePicker()}}),n.toolbarRegistry.registerHostAction({id:hS,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return yc(t)&&!t.isLocked},run(){e.openReplaceFilePicker()}}),n.toolbarRegistry.registerHostAction({id:pS,isVisible:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,isEnabled(e){const[t]=e.selection.selectedShapes;return yc(t)&&!!t.props.assetId&&!!vu(e.editor,t.props.assetId)},run({context:e}){Lu({editor:e.editor,imageObjectUrls:t})}})})({hostBridge:i,imageObjectUrls:n.objectUrls,pluginHostRuntime:e})}(t)},canShowToolbarDuringEditing:e=>kc(e),createSvgAssetInliners(e){const t=e.get(Cy);return t?[_u(t)]:[]},renderController({editor:t,services:n}){const i=n.get(Cy);return i?Ph(GS,{editor:t,hostBridge:n.get(By)??void 0,imageAssetService:i,flushSnapshot:e}):null}}}function Qu(e,t){return e.flatMap(e=>e.createSvgAssetInliners?.(t)??[])}function Ju({ids:e,kind:t,message:n,productId:i}){if(0===e.length)return;const r=`${i}:${t}:${e.join(",")}`;Ry.has(r)||(Ry.add(r),console.warn(n,e))}function eh({controller:e,activeContextMenu:t,editor:n,grid:i,hostExtensions:r,onActiveContextMenuChange:o,persistence:s,pluginHostRuntime:a,services:d,themeRootRef:l}){const c=Er(n.currentPageIdSignal),u=Er(n.currentPageShapeIdsSignal),h=Er(n.store.recordsSignal),p=Er(n.selectedShapeIdsSignal),g=Er(n.selectionStateSignal),m=(e=>{const t=Er(e.historyStateSignal);return{canUndo:t.canUndo,canRedo:t.canRedo,undo(){e.undo()},redo(){e.redo()}}})(n),f=(e=>{const t=Er(e.pageStateSignal);return{pages:t.pages,currentPage:t.currentPage,currentPageId:t.currentPageId,canDeleteCurrentPage:t.canDeleteCurrentPage,createPage(){e.createPageAndSelect(void 0,"user")},deleteCurrentPage(){t.currentPage&&e.deletePage(t.currentPage.id,"user")},renameCurrentPage(n){t.currentPage&&e.renamePage(t.currentPage.id,n,"user")},selectPage(t){e.selectPage(t,"user")}}})(n),S=(e=>{const t=Er(e.cameraZoomSignal);return{zoom:t,label:`${Math.round(100*t)}%`,zoomIn(){e.zoomAtViewportCenter(-120,"system")},zoomOut(){e.zoomAtViewportCenter(120,"system")},resetZoom(){e.resetZoom("user")}}})(n),y=function({editor:e,activeContextMenu:t,pluginHostRuntime:n}){return Er(e.selectionStateSignal),Er(e.toolStateSignal),fh(()=>{if(!t)return{context:null,activeContextMenu:null,sections:[]};const i=(({editor:e,menu:t})=>{const n=e.toolStateSignal.get();return{...Wu({editor:e,selectionState:e.selectionStateSignal.get(),toolState:n}),menu:t}})({editor:e,menu:t}),r=((e,t)=>"canvas"===e.type?"canvas":t.getSelectedShapeIds().length>0?"selection":"shape")(t.target,e);return{context:i,activeContextMenu:t,sections:n.contextMenuRegistry.getSections(r,i)}},[e,t,n])}({editor:n,activeContextMenu:t,pluginHostRuntime:a}),x=(({canShowContextToolbarDuringEditing:e,editor:t,pluginHostRuntime:n})=>{const i=Er(t.toolStateSignal),r=Er(t.selectionStateSignal),o=Er(t.shapeEditingStateSignal),s=Er(t.queries.selectionPageBoundsSignal),a=Er(t.selectionTranslationActiveSignal),d="select"===i.activeToolId,l=d?r.count:0,c=Wu({editor:t,selectionState:r,toolState:i}),u=!o.session||(e?.(c)??!1),h=n.toolbarRegistry.getGroups("selection",c,{placement:"context"}),p=n.toolbarRegistry.getGroups("selection",c,{placement:"floating"}),g=d&&s&&p.length>0?{x:s.minX,y:s.minY}:null,m=u&&!a&&r.count>0&&p.length>0&&!!g,f=n.toolbarRegistry.getGroups("tool",c,{placement:"context"}),S=n.toolbarRegistry.getGroups("tool",c,{placement:"chrome"}),y=d&&r.count>0?h:f,x=u&&y.length>0,b=((e,t)=>{for(const n of e)for(const e of n.items)if("button"===e.kind&&"editor.tool.set-active-tool"===e.actionId&&e.value===t)return e.label;return t})(f,i.activeToolId),P=d&&r.count>0?(({commonShapeType:e,count:t,isMixedFrameAndPointHandleSelection:n,singleShapeType:i})=>{const r=i??e;if(!r)return n?"Mixed selection":`${t} selected`;const o=t>1?` (${t})`:"";return"geo"===r?`Shape${o}`:"text"===r?`Text${o}`:`${r.charAt(0).toUpperCase()}${r.slice(1)}${o}`})({commonShapeType:r.commonShapeType,count:l,isMixedFrameAndPointHandleSelection:r.isMixedFrameAndPointHandleSelection,singleShapeType:r.singleShapeType}):b;return{context:c,activeToolId:i.activeToolId,activeToolLabel:b,isToolLocked:i.isToolLocked,selectionCount:l,hasMixedSelectionRotation:r.hasMixedSelectionRotation,toolChromeToolbarGroups:S,contextToolbarGroups:y,floatingSelectionToolbarGroups:p,floatingSelectionToolbarPageAnchor:g,contextToolbarTitle:P,showContextToolbar:x,showFloatingSelectionToolbar:m}})({canShowContextToolbarDuringEditing:e=>((e,t)=>e.some(e=>e.canShowToolbarDuringEditing?.(t)))(r,e),editor:n,pluginHostRuntime:a}),b=Gu({assetInliners:Qu(r,d),editor:n,themeRootRef:l}),P=fh(()=>e.getLayerTree(c),[e,c,h]),I=fh(()=>({getActionState({actionId:e,context:t}){const n=a.toolbarRegistry.getAction(e);return n?{value:n.getValue?.(t),isEnabled:n.isEnabled?.(t)??!0,isVisible:n.isVisible?.(t)??!0}:null},runAction({actionId:e,context:t,value:n}){const i=a.toolbarRegistry.getAction(e);i&&!1!==i.isVisible?.(t)&&!1!==i.isEnabled?.(t)&&i.run({context:t,value:void 0!==n?n:i.getValue?.(t)??null})}}),[a]);return{controller:e,contextMenu:{activeContextMenu:t,onActiveContextMenuChange:o,runAction({actionId:e,context:t,value:n}){(({actionId:e,context:t,pluginHostRuntime:n,value:i})=>{const r=n.toolbarRegistry.getAction(e);r&&!1!==r.isVisible?.(t)&&!1!==r.isEnabled?.(t)&&r.run({context:t,value:void 0!==i?i:r.getValue?.(t)??null})})({actionId:e,context:t,pluginHostRuntime:a,value:n})},surface:y},currentPageId:c,currentPageShapeIds:u,history:m,layers:P,pages:f,persistence:s,selection:g,selectedShapeIds:p,svgExport:b,toolbarRuntime:I,toolbarSurfaces:x,grid:i,zoom:S}}function th({persistence:e}){const{discardUnsupportedRecords:t,isDiscardingUnsupportedRecords:n,status:i}=e;if(!i)return null;const r=[...i.unsupportedShapeTypes,...i.unsupportedBindingTypes].join(", ");
38
+ return Ih("div",{role:"alert","data-ui":"canvas-kit-persistence-notice",className:"land-canvas-kit__persistence-notice",children:[Ih("div",{className:"land-canvas-kit__persistence-notice-copy",children:[Ph("strong",{children:"Unsupported records preserved"}),Ih("span",{children:[i.preservedRecordCount," record",1===i.preservedRecordCount?"":"s"," will round-trip while saving. ",r?`Types: ${r}.`:""]})]}),Ph("button",{type:"button",className:"land-canvas-kit__persistence-notice-action",disabled:!t||n,onClick:()=>{t?.()},children:n?"Saving":"Discard unsupported records"})]})}function nh({featureControllers:e,config:t,editor:n,pluginHostRuntime:i,productId:r,services:o}){const s=fh(()=>({featureControllers:e,editor:n,pluginHostRuntime:i,productId:r,services:o}),[e,n,i,r,o]),a=fh(()=>qu(s),[s]);return(({controller:e,exposeOnWindow:t=!1,windowKey:n,onDispose:i,onReady:r})=>{const o=gh(e=>{r?.(e)}),s=gh(()=>{i?.()});ph(()=>{const i=window;return t&&n&&(i[n]=e),o(e),()=>{t&&n&&i[n]===e&&delete i[n],s()}},[e,t,n])})({controller:a,exposeOnWindow:t.exposeControllerOnWindow,onDispose:t.onControllerDispose,onReady:t.onControllerReady,windowKey:t.windowKey}),a}function ih(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:gu({storageNamespace:e.storageNamespace??"land.canvasKit"}))(e),i=((e={})=>WS.filter(([t])=>!1!==e[t]).map(([t,n])=>{if("text"===t){const t=e.text;return"object"==typeof t?Em.configure(t):n}return n}))(e.builtInExtensions??{}),r=(({flushSnapshot:e,image:t})=>{const n=[{id:"canvas-kit.clipboard",services:[{token:ZS,create(){let e=null;return{async write(t){e=t},read:async()=>e,getMemoryPayload:()=>e}}}],initializeRuntime({editor:e,pluginHostRuntime:t,services:n}){(({editor:e,pluginHostRuntime:t,services:n})=>{for(const i of(e=>[{id:QS,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!Uu(e),run({context:t}){zu({context:t,services:e})}},{id:JS,isVisible:e=>e.selection.count>0,isEnabled:t=>t.selection.count>0&&!!Uu(e),run({context:t}){(async({context:e,services:t})=>{await zu({context:e,services:t})&&e.editor.deleteSelection("user")})({context:t,services:e})}},{id:ey,isVisible:()=>!!Uu(e)?.getMemoryPayload(),isEnabled:()=>!!Uu(e)?.getMemoryPayload(),run({context:t}){Hu({context:t,services:e})}},{id:ty,isVisible:t=>Ou(t)&&!!Uu(e)?.getMemoryPayload(),isEnabled:t=>Ou(t)&&!!Uu(e)?.getMemoryPayload(),run({context:t}){Ou(t)&&Hu({context:t,services:e,atMenuPoint:!0})}}])(n))t.toolbarRegistry.registerHostAction(i);if(e)for(const{actionId:i,shortcut:r}of ny)e.shortcuts.registerActionShortcut(i,r)})({editor:e,pluginHostRuntime:t,services:n})}},{id:"canvas-kit.toolbar",initializeRuntime({editor:e,pluginHostRuntime:t}){for(const n of Py)t.toolbarRegistry.registerAction(n);for(const{actionId:n,shortcut:i}of by)e.shortcuts.registerActionShortcut(n,i);for(const n of wy)t.toolbarRegistry.registerContribution(n)}},{id:"canvas-kit.context-menu",initializeRuntime({pluginHostRuntime:e}){for(const t of sy)e.toolbarRegistry.registerHostAction(t);for(const t of vy)e.contextMenuRegistry.registerContribution(t)}}];return t&&n.push(Zu({flushSnapshot:e})),n})({flushSnapshot:rh(n),image:(o=i,o.some(e=>"image"===e.name))});var o;const s=(e=>e.flatMap(e=>e.assetResolverTokens??[]))(r),a=(e=>e.flatMap(e=>e.services??[]))(r),d=function({hostExtensions:e,seedDocument:t,warnOnPluginRegistrationConflicts:n}){return i=>{((e,t)=>{for(const n of e)n.initializeRuntime?.(t)})(e,i),n&&(({duplicateContextMenuContributionIds:e,duplicateCanvasActionIds:t,duplicateToolbarContributionIds:n,productId:i})=>{Ju({ids:t,kind:"toolbar-action",message:`[land] Duplicate canvas action ids for product ${i}. The later registrations were ignored.`,productId:i}),Ju({ids:n,kind:"toolbar-contribution",message:`[land] Duplicate toolbar contribution ids for product ${i}. The later registrations were ignored.`,productId:i}),Ju({ids:e,kind:"context-menu-contribution",message:`[land] Duplicate context menu contribution ids for product ${i}. The later registrations were ignored.`,productId:i})})({duplicateContextMenuContributionIds:i.pluginHostRuntime.contextMenuRegistry.getDuplicateContributionIds(),duplicateCanvasActionIds:i.pluginHostRuntime.toolbarRegistry.getDuplicateActionIds(),duplicateToolbarContributionIds:i.pluginHostRuntime.toolbarRegistry.getDuplicateContributionIds(),productId:i.productId}),t&&t(qu(i))}}({hostExtensions:r,seedDocument:e.seedDocument,warnOnPluginRegistrationConflicts:e.warnOnPluginRegistrationConflicts??!1});return{[Ly]:void 0,assetResolverTokens:s,canvasExtensions:i,id:e.id??"canvas-kit",config:t,hostExtensions:r,initializeRuntime:d,persistence:n,serviceFactories:a,shouldSkipStoredSnapshots:e.shouldSkipStoredSnapshots}}function rh(e){const t=e?.flushSnapshot;return t?e=>t(e):void 0}function oh(e){const{config:t,assetResolverTokens:n,canvasExtensions:i,hostExtensions:r,id:o,initializeRuntime:s,persistence:a,serviceFactories:d,shouldSkipStoredSnapshots:l}=e,c=(({factories:e,productId:t})=>{const n=new Map,i=[],r=(e,t)=>{const r=n.get(e.token.id);if(r)return r;const o=e.create(t);return n.set(e.token.id,o),e.dispose&&i.push(()=>e.dispose?.(o)),o};for(const o of e)r(o,{productId:t});return{get:e=>n.get(e.id)??null,dispose(){for(const e of[...i].reverse())e();n.clear()}}})({factories:d,productId:o}),u=(()=>{const e=new Map;return{register(t,n){if(e.has(t.id))throw new Error(`Product feature controller already registered: ${t.id}`);e.set(t.id,n)},get:t=>e.get(t.id)??null}})(),h=((e,t={})=>{const n=t.knownHostActionIds??[],i=t.source??"built-in",r=function(e){const t=[],n=new Set;let i=0;const r=e=>{if(n.has(e))throw new Error(`Circular Land extension bundle detected at "${e.name}".`);n.add(e),t.push({extension:e,index:i}),i+=1;for(const t of e.getExtensions())r(t);n.delete(e)};for(const s of e)r(s);const o=(e=>{const t=new Set,n=new Set;for(const i of e)t.has(i)?n.add(i):t.add(i);return[...n]})(t.map(({extension:e})=>e.name));if(o.length>0)throw new Error(`Duplicate Land extension names: ${o.join(", ")}.`);return t.sort((e,t)=>t.extension.priority-e.extension.priority||e.index-t.index).map(({extension:e})=>({extension:e,feature:e.createFeature()}))}(e).flatMap(({extension:e,feature:t})=>t?[{extensionName:e.name,feature:t,source:i}]:[]),o=(e=>e.flatMap(({feature:e})=>e.editorPlugins))(r),s=(e=>e.flatMap(({feature:e})=>e.canvasPlugins))(r),a=(e=>e.flatMap(e=>[...e.canvasProviders??[]]))(s),d=(e=>e.flatMap(e=>[...e.canvasComponents??[]]))(s),l=r.map(ir),c=(e=>e.filter(({source:e})=>"built-in"!==e).flatMap(({feature:e})=>[...e.editorPlugins.map(e=>e.id),...e.canvasPlugins.map(e=>e.id)]))(r),u=Ni(s);return{editorPlugins:o,canvasPlugins:s,canvasProviders:a,canvasComponents:d,rendererRegistry:u,overlayRegistry:Vi(s),domEventGuardRegistry:ji(s),toolbarRegistry:Gi(o),contextMenuRegistry:Zi(o),manifest:l,validation:rr({editorPlugins:o,canvasPlugins:s,knownHostActionIds:n,rendererRegistry:u,resolvedFeatures:r}),externalPluginIds:c}})(i,{knownHostActionIds:Iy});let p=null;const g=function(e){const t=((e={})=>{const{editorPlugins:t=[],...n}=e,i={shapeUtils:(r=t).flatMap(e=>e.shapeUtils??[]),shapeSvgExporters:r.flatMap(e=>e.shapeSvgExporters??[]),bindingUtils:r.flatMap(e=>e.bindingUtils??[]),shapeCapabilities:r.flatMap(e=>e.shapeCapabilities??[])};var r;const o=new Bp({...n,shapeUtils:i.shapeUtils,shapeSvgExporters:i.shapeSvgExporters,bindingUtils:i.bindingUtils,shapeCapabilities:i.shapeCapabilities});return((e,t)=>{for(const n of t){for(const t of n.interactionHandlers??[])e.interactions.register(t);n.setup?.(e)}})(o,t),o})({editorPlugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new tg(e),{shortcut:"v"}),t.tools.register("hand",e=>new Rp(e),{shortcut:"h"}),t.tools.setToolLocked(t.isToolLocked()),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t}({editorPlugins:h.editorPlugins,resolveAssetUrl:e=>p?(({assetResolverTokens:e,assetId:t,editor:n,services:i})=>{for(const r of $u({assetResolverTokens:e,services:i})){const e=r.resolveAssetUrl(n,t);if(e)return e}return null})({assetResolverTokens:n,assetId:e,editor:p,services:c}):null});return p=g,s({productId:o,featureControllers:u,editor:g,pluginHostRuntime:h,services:c}),{assetResolverTokens:n,config:t,featureControllers:u,editor:g,hostExtensions:r,persistence:a,pluginHostRuntime:h,productId:o,services:c,shouldSkipStoredSnapshots:l}}function sh({product:e}){const t=(e=>{const t=e,[n,i]=xh(null),r=n?.product===t?n.runtime:null;return ph(()=>{const e=oh(t);return i({product:t,runtime:e}),()=>{e.services.dispose()}},[t]),r})(e),[n,i]=xh(null),[r,o]=xh(!1),{isReady:s,persistence:a}=function(e){const[{readyRuntime:t,status:n},i]=xh(Fy),[r,o]=xh(!1),s=!!e?.persistence?.restore&&!e.shouldSkipStoredSnapshots?.();ph(()=>{if(!e)return void i(Fy);const{assetResolverTokens:t,editor:n,persistence:r,services:o}=e;let a=!1,d=null;const l=()=>{a=!0,d?.()},c=(t,o)=>{a||(i({readyRuntime:e,status:t}),o&&(d=r?.start?.(n)??null))};return s?(i(Fy),(async()=>{let e=null,i=!0;try{const s=await(r?.restore?.(n));i="disabled"!==s?.autoPersistence,e=s?.status??null,await(async({assetResolverTokens:e,editor:t,services:n})=>{await Promise.all($u({assetResolverTokens:e,services:n}).map(e=>e.preloadForEditor?.(t)))})({assetResolverTokens:t,editor:n,services:o}),await(async({assetResolverTokens:e,editor:t,services:n})=>{await Promise.all($u({assetResolverTokens:e,services:n}).map(e=>e.cleanupAfterRestore?.(t)))})({assetResolverTokens:t,editor:n,services:o})}catch(s){if(a)return;console.warn("Could not restore persisted canvas snapshot.",s)}c(e,i)})(),l):(c(null,!0),l)},[e,s]);const a=uh(async()=>{if(e?.persistence?.discardUnsupportedRecords){o(!0);try{const t=await e.persistence.discardUnsupportedRecords(e.editor);i(e=>({...e,status:t?.status??null}))}catch(t){console.warn("Could not discard unsupported persisted records.",t)}finally{o(!1)}}},[e]);return{isReady:t===e,persistence:{discardUnsupportedRecords:n&&e?.persistence?.discardUnsupportedRecords?a:null,isDiscardingUnsupportedRecords:r,status:n}}}(t),d=fh(()=>({isVisible:r,setIsVisible:o}),[r]);if(ph(()=>{i(null)},[e]),!t)return null;const{editor:l,pluginHostRuntime:c}=t;
39
+ return Ph(yg.Provider,{value:l,children:Ph(ah,{runtime:t,canvas:s?Ph(io,{canvasComponents:c.canvasComponents,canvasProviders:c.canvasProviders,domEventGuardRegistry:c.domEventGuardRegistry,onContextMenuRequest:i,overlayRegistry:c.overlayRegistry,rendererRegistry:c.rendererRegistry,showGrid:r}):null,activeContextMenu:n,onActiveContextMenuChange:i,isReady:s,persistence:a,grid:d})})}function ah({canvas:e,activeContextMenu:t,grid:n,isReady:i,onActiveContextMenuChange:r,persistence:o,runtime:s}){const{config:a,featureControllers:d,editor:l,hostExtensions:c,pluginHostRuntime:u,productId:h,services:p}=s,g=a.renderChrome,m=yh(null);(({editor:e,pluginHostRuntime:t})=>{ph(()=>{const n=n=>{if(e.getShapeEditingSession()||Vr(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 r=Wu({editor:e,selectionState:e.selectionStateSignal.get(),toolState:e.toolStateSignal.get()}),o=t.toolbarRegistry.getAction(i);o&&!1!==o.isVisible?.(r)&&!1!==o.isEnabled?.(r)&&(n.preventDefault(),n.stopPropagation(),(({context:e,pluginHostRuntime:t,actionId:n})=>{const i=t.toolbarRegistry.getAction(n);i&&!1!==i.isVisible?.(e)&&!1!==i.isEnabled?.(e)&&i.run({context:e,value:i.getValue?.(e)??null})})({actionId:i,context:r,pluginHostRuntime:t}))};return window.addEventListener("keydown",n,!0),()=>{window.removeEventListener("keydown",n,!0)}},[e,t])})({editor:l,pluginHostRuntime:u});const f=eh({controller:nh({featureControllers:d,config:a,editor:l,pluginHostRuntime:u,productId:h,services:p}),activeContextMenu:t,editor:l,grid:n,hostExtensions:c,onActiveContextMenuChange:r,persistence:o,pluginHostRuntime:u,services:p,themeRootRef:m});
40
+ return Ph("div",{ref:m,"data-ui":"app-shell","data-canvas-kit":h,className:"land-canvas-kit__shell",children:Ph("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:i?Ih(bh,{children:[e,c.map(e=>Ph(dh,{children:e.renderController?.({editor:l,services:p})??null},e.id)),g?.(f),
41
+ Ph(th,{persistence:o})]}):null})})}import{Fragment as dh,createContext as lh,memo as ch,useCallback as uh,useContext as hh,useEffect as ph,useEffectEvent as gh,useLayoutEffect as mh,useMemo as fh,useReducer as Sh,useRef as yh,useState as xh}from"react";import{Fragment as bh,jsx as Ph,jsxs as Ih}from"react/jsx-runtime";import{EditorContent as wh,useEditor as vh}from"@tiptap/react";import{Bold as Ch}from"@tiptap/extension-bold";import{Italic as kh}from"@tiptap/extension-italic";import{Strike as Th}from"@tiptap/extension-strike";import Bh from"@tiptap/starter-kit";import{BubbleMenu as Mh}from"@tiptap/react/menus";var Eh=0,Ah=null,Rh=null,Fh=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)=>{Ah&&!Ah.initialAtomValues.has(e)&&Ah.initialAtomValues.set(e,t)})(this,i),t(),this.lastChangedEpoch=e(),this.current=n,(e=>{Ah||o([e])})(this),n)}update(e){return this.set(e(this.current))}},Lh=Symbol("UNINITIALIZED"),$h=class{name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch;children=new Set;state=Lh;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!==Lh&&!this.haveParentsChanged())return this.lastCheckedEpoch=e(),this.state;let r,o;n(this.selfAsChild);try{r=this.derive(this.state===Lh?Lh:this.state)}finally{o=i()}for(const e of this.parents)o.has(e)||e.children.delete(this.selfAsChild);this.parents=[...o],this.parentEpochs=this.parents.map(e=>e.lastChangedEpoch);for(const e of this.parents)e.children.add(this.selfAsChild);return this.state!==Lh&&(this.isEqual?this.isEqual(this.state,r):Object.is(this.state,r))||(this.state=r,t(),this.lastChangedEpoch=e()),this.lastCheckedEpoch=e(),this.state}get selfAsChild(){return this._selfAsChild||(this._selfAsChild={type:"computed",notify:()=>{},source:this}),this._selfAsChild}_selfAsChild=null;haveParentsChanged(){for(let e=0;e<this.parents.length;e++){const t=this.parents[e];if(t.__unsafe__getWithoutCapture(),t.lastChangedEpoch!==this.parentEpochs[e])return!0}return!1}},Dh=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}},Uh=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}},zh=class e{x;y;constructor(e,t){this.x=e,this.y=t}add(t){return new e(this.x+t.x,this.y+t.y)}sub(t){return new e(this.x-t.x,this.y-t.y)}mul(t){return new e(this.x*t,this.y*t)}div(t){return new e(this.x/t,this.y/t)}len2(){return this.x*this.x+this.y*this.y}len(){return Math.sqrt(this.len2())}dist2(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}dist(e){return Math.sqrt(this.dist2(e))}rot(t){const n=Math.cos(t),i=Math.sin(t);return new e(this.x*n-this.y*i,this.x*i+this.y*n)}per(){return new e(-this.y,this.x)}uni(){return this.normalize()}normalize(){const t=this.len();return 0===t?new e(0,0):this.div(t)}equals(e){return this.x===e.x&&this.y===e.y}clone(){return new e(this.x,this.y)}static From(t,n){return new e(t,n)}static Zero(){return new e(0,0)}static Med(t,n){return new e((t.x+n.x)/2,(t.y+n.y)/2)}static Lrp(t,n,i){return new e(t.x+(n.x-t.x)*i,t.y+(n.y-t.y)*i)}static Dist(e,t){return e.dist(t)}static Dist2(e,t){return e.dist2(t)}static Angle(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}static Nudge(e,t,n){const i=t.sub(e),r=i.len();return 0===r?e.clone():e.add(i.mul(n/r))}static RotWith(t,n,i){const r=t.x-n.x,o=t.y-n.y,s=Math.cos(i),a=Math.sin(i);return new e(n.x+r*s-o*a,n.y+r*a+o*s)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}},Hh=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 zh(this.x+this.w/2,this.y+this.h/2)}containsPoint(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}containsBox(e){return e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return this.minX<e.maxX&&this.maxX>e.minX&&this.minY<e.maxY&&this.maxY>e.minY}expand(t){return new e(this.x-t,this.y-t,this.w+2*t,this.h+2*t)}clone(){return new e(this.x,this.y,this.w,this.h)}static FromPoints(t){let n=1/0,i=1/0,r=-1/0,o=-1/0;for(const e of t)n=Math.min(n,e.x),i=Math.min(i,e.y),r=Math.max(r,e.x),o=Math.max(o,e.y);return new e(n,i,r-n,o-i)}},Yh=class e{a;b;c;d;e;f;constructor(e,t,n,i,r,o){this.a=e,this.b=t,this.c=n,this.d=i,this.e=r,this.f=o}static Identity(){return new e(1,0,0,1,0,0)}static Translate(t,n){return new e(1,0,0,1,t,n)}static Rotate(t){const n=Math.cos(t),i=Math.sin(t);return new e(n,i,-i,n,0,0)}static Scale(t,n){return new e(t,0,0,n,0,0)}compose(t){return new e(this.a*t.a+this.c*t.b,this.b*t.a+this.d*t.b,this.a*t.c+this.c*t.d,this.b*t.c+this.d*t.d,this.a*t.e+this.c*t.f+this.e,this.b*t.e+this.d*t.f+this.f)}applyToPoint(e){return new zh(this.a*e.x+this.c*e.y+this.e,this.b*e.x+this.d*e.y+this.f)}invert(){const t=this.a*this.d-this.b*this.c;if(0===t)return e.Identity();const n=1/t;return new e(this.d*n,-this.b*n,-this.c*n,this.a*n,(this.c*this.f-this.d*this.e)*n,(this.b*this.e-this.a*this.f)*n)}toCssString(){return`matrix(${this.a},${this.b},${this.c},${this.d},${this.e},${this.f})`}toSvgString(){return`matrix(${this.a} ${this.b} ${this.c} ${this.d} ${this.e} ${this.f})`}static ForShape(t,n,i,r=1,o=1){const s=e.Translate(t,n),a=0===i?e.Identity():e.Rotate(i),d=1===r&&1===o?e.Identity():e.Scale(r,o);return s.compose(a).compose(d)}},Oh="page:default",Kh="session:main",Xh={x:0,y:0,z:1},Wh=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}},Nh=["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"],_h=Object.fromEntries(Nh.map(e=>[e,`--land-shape-${e}`])),Vh={"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"},qh={"#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"},jh=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()}},Gh=Symbol("editorStore"),Zh=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(Y(e))if(this.marks.size>0)for(const[t,n]of this.marks.entries())this.marks.set(t,N(n,e));else this.undoStack.push(_("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),!Y(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,N(e,n))}return n}squashToMark(e,t=e){const n=this.marks.get(e);if(!n)return null;if(this.marks.delete(e),!Y(n.forward))return null;if(n.parentIds.some(e=>this.marks.has(e)))return null;const i=_(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})}},Qh=class{recordsSignal;recordSignals=new Map;listeners=new Set;transactionDepth=0;draftRecords=null;pendingSource="system";constructor(e){this.recordsSignal=s("store.records",new Map(e.map(e=>[e.id,e])))}get(e){return this.getReadableRecords().get(e)}getRecordSignal(e){let t=this.recordSignals.get(e);return t||(t=a(`store.record.${e}`,()=>(this.recordsSignal.get(),this.get(e))),this.recordSignals.set(e,t)),t}getAll(){return Array.from(this.getReadableRecords().values())}getByScope(e){return this.getAll().filter(t=>"scope"in t&&t.scope===e)}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}atomic(e,t="system"){const n=0===this.transactionDepth;let i;n&&(this.draftRecords=new Map(this.recordsSignal.get()),this.pendingSource=t),this.transactionDepth+=1;try{e()}catch(r){i=r}if(this.transactionDepth-=1,n){const e=this.recordsSignal.get(),t=this.draftRecords,n=this.pendingSource;this.draftRecords=null,this.pendingSource="system";const r=t?K(e,t):{added:[],updated:[],removed:[]};if(!i&&t&&Y(r)){this.recordsSignal.set(t);const e={source:n,diff:r};for(const t of this.listeners)t(e)}}if(i)throw i}put(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)t.get(n.id)!==n&&t.set(n.id,n)},t)}remove(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)if(!t.delete(n))continue},t)}replaceAll(e,t="system"){const n=new Map(e.map(e=>[e.id,e])),i=K(this.recordsSignal.get(),n);if(!Y(i))return;this.recordsSignal.set(n);const r={source:t,diff:i};for(const o of this.listeners)o(r)}applyDiff(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e.added)t.set(n.id,n);for(const n of e.updated)t.set(n.after.id,n.after);for(const n of e.removed)t.delete(n.id)},t)}getMutableRecords(){if(!this.draftRecords)throw new Error("Store mutations must run inside store.atomic");return this.draftRecords}getReadableRecords(){return this.draftRecords??this.recordsSignal.get()}},Jh=class{editor;buffer=new Zh;state=this.buffer.state;constructor(e){this.editor=e,U(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&&(U(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&&(U(this.editor).applyDiff(e.inverse,"history"),this.editor.syncAfterDocumentRestore(),!0)}redo(){const e=this.buffer.redo();return!!e&&(U(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=m),updated:n.updated.filter(e=>i(e.before)&&i(e.after)),removed:n.removed.filter(i)};var n,i;Y(t)&&"user"===e.source&&this.buffer.append(t)}},ep=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){U(this.editor).atomic(()=>{const t=new Set;for(const n of this.getAllBindings()){const i=this.editor.getShape(n.fromId),r=this.editor.getShape(n.toId);if(!i||!r){U(this.editor).remove([n.id],e);continue}if(!this.canBind(n)){U(this.editor).remove([n.id],e);continue}const o=this.getExclusiveBindingKey(n);if(o){if(t.has(o)){U(this.editor).remove([n.id],e);continue}t.add(o)}const s=this.editor.getBindingUtil(n).onBindingLoad?.(this.editor,n);this.applyEffect(s,e,n.id)}},e)}handleShapeChanges(e,t,n){if(0!==e.length)for(const i of e)for(const e of this.getBindingsForShape(i.after.id)){if(n?.skipBindingIds?.has(e.id))continue;const r=e.fromId===i.after.id?"from":"to",o=this.editor.getBindingUtil(e).onAfterShapeChange?.(this.editor,e,{before:i.before,after:i.after,role:r});this.applyEffect(o,t,e.id)}}cleanupBindingsForDeletedShapes(e,t){if(0===e.length)return;const n=new Set(e),i=new Set;for(const r of e){const e=this.editor.getShape(r);if(e)for(const o of this.getBindingsForShape(r)){if(i.has(o.id))continue;i.add(o.id);const s=o.fromId===r?"from":"to";if("to"===s&&n.has(o.fromId)){U(this.editor).remove([o.id],t);continue}const a=this.editor.getBindingUtil(o).onBeforeDeleteShape?.(this.editor,o,{shape:e,role:s});this.applyEffect(a,t,o.id)}}}cleanupBindings(e,t){for(const n of e){const e=this.editor.getBinding(n);if(!e)continue;const i=this.editor.getBindingUtil(e).onBeforeDeleteBinding?.(this.editor,e);this.applyEffect(i,t,e.id)}}applyEffect(e,t,n){if(e){if(e.bindings&&e.bindings.length>0&&U(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}]:[]});U(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),U(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&&U(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}},tp=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]??Xh}pageToScreen(e,t=this.editor.getCurrentPageId()){const n=this.getCamera(t);return new e.constructor((e.x-n.x)*n.z,(e.y-n.y)*n.z)}screenToPage(e,t=this.editor.getCurrentPageId()){const n=this.getCamera(t);return new e.constructor(e.x/n.z+n.x,e.y/n.z+n.y)}setCamera(e,t){const n=t?.source??"system",i=t?.pageId??this.editor.getCurrentPageId(),r=this.getCamera(i),o={x:"number"==typeof e.x?e.x:r.x,y:"number"==typeof e.y?e.y:r.y,z:ee("number"==typeof e.z?e.z:r.z)};this.editor.updateSession({pageCameraById:{...this.editor.sessionSignal.get().pageCameraById,[i]:o}},n)}panCamera(e,t="system"){const n=this.getCurrentCamera();this.setCamera({x:n.x+e.x/n.z,y:n.y+e.y/n.z},{source:t})}zoomCameraAtScreenPoint(e,t,n="system"){const i=ee(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=ee(t),r=this.screenToPage(e);this.setCamera({x:r.x-e.x/i,y:r.y-e.y/i,z:i},{source:n})}zoomAtViewportCenter(e,t="system"){const n=this.viewportScreenSizeSignal.get(),i=new zh(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new zh(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)}},np=new zh(24,24),ip=class{editor;constructor(e){this.editor=e}createPayloadFromSelection(){return pe(this.editor)}pastePayload(e){return this.editor.cancelInteractionForCommand(),ge(this.editor,e)}duplicateSelection(e={}){return this.editor.cancelInteractionForCommand(),((e,t={})=>{const n=pe(e);return n?ge(e,{payload:n,offset:t.offset??np,source:t.source}):[]})(this.editor,e)}},rp=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},op=[],sp=[],ap=class{editor;constructor(e){this.editor=e}buildInitialRecords(e,t){const n=this.parseInitialDocumentSnapshot(e),i=this.parseInitialSessionSnapshot(t);return[...n.records.length?n.records:[d()],i.records[0]??l()]}getDocumentSnapshot(){const e=this.editor.store.getAll();return{schemaVersion:1,records:[...this.editor.getPages(),...e.filter(g).sort((e,t)=>e.id.localeCompare(t.id)),...e.filter(u).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index):e.parentId.localeCompare(t.parentId)),...e.filter(p).sort((e,t)=>e.id.localeCompare(t.id))]}}getSessionSnapshot(){return{schemaVersion:1,records:[this.editor.sessionSignal.get()]}}loadDocumentSnapshot(e,t){const n=t?.source??"system",i=$e(e,this.editor.shapeUtils,this.editor.bindingUtils);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n});const r=this.editor.sessionSignal.get();U(this.editor).replaceAll([...i.records,r],n),this.syncAfterDocumentSnapshotLoad(n)}loadSessionSnapshot(e,t){const n=t?.source??"system",i=De(e).records[0]??l(),r=U(this.editor).getAll().filter(m);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),U(this.editor).replaceAll([...r,i],n),this.ensureSessionIntegrity(),this.editor.syncToolStateFromSession(n)}syncAfterDocumentRestore(){this.ensureSessionIntegrity(),this.editor.syncShapeCounter(),this.editor.syncPageCounter(),this.editor.syncBindingCounter(),this.editor.syncAssetCounter()}ensureSessionIntegrity(){const e=U(this.editor),t=e.getAll(),n=t.filter(c).sort((e,t)=>e.index.localeCompare(t.index)),i=n[0]?.id??"page:default",r=new Set(n.map(e=>e.id)),o=t.filter(u),s=new Set(o.map(e=>e.id)),a=new Map(o.map(e=>[e.id,e])),d=new Map;for(const l of o)d.set(l.id,de(l,a,r)??i);const p=t.find(e=>e.id===Kh),g=h(p)?p:l(i),m={...g,currentPageId:r.has(g.currentPageId)?g.currentPageId:i,pageCameraById:this.repairCameraByPage(g.pageCameraById,r),pageSelectedShapeIdsById:this.repairSelectionByPage(g.pageSelectedShapeIdsById,r,s,d)};e.put([m],"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]??Xh;n[i]={x:Number.isFinite(t.x)?t.x:Xh.x,y:Number.isFinite(t.y)?t.y:Xh.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:Xh.z))}}return n}repairSelectionByPage(e,t,n,i){const r={};for(const o of t)r[o]=Array.from(new Set((e[o]??[]).filter(e=>n.has(e)&&i.get(e)===o)));return r}parseInitialDocumentSnapshot(e){if(!e)return{schemaVersion:1,records:[d()]};try{return $e(e,this.editor.shapeUtils,this.editor.bindingUtils)}catch(t){if(!(t instanceof rp))throw t;return{schemaVersion:1,records:[d()]}}}parseInitialSessionSnapshot(e){if(!e)return{schemaVersion:1,records:[l()]};try{return De(e)}catch(t){if(!(t instanceof rp))throw t;return{schemaVersion:1,records:[l()]}}}},dp=class{state=s("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:Ue(),screenVelocity:Ue(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1});setCurrentPointerPoint(e){this.state.update(t=>{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.shiftKey===e.shiftKey&&t.altKey===e.altKey&&t.ctrlKey===e.ctrlKey&&t.metaKey===e.metaKey&&t.accelKey===e.accelKey)return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,r=t.currentTimestamp??e.timestamp,o=e.timestamp-r;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:r,currentTimestamp:e.timestamp,pageVelocity:ze(n,e.pagePoint,o),screenVelocity:ze(i,e.screenPoint,o),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}})}handleEvent(e){switch(e.type){case"pointer":return void this.handlePointerEvent(e);case"keyboard":return void this.handleKeyboardEvent(e);case"wheel":return void this.handleWheelEvent(e);case"cancel":return void this.resetPointer()}}resetPointer(){this.state.update(e=>({...e,originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:Ue(),screenVelocity:Ue(),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:Ue(),screenVelocity:Ue(),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&&He(t,e))return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,r=t.isDragging||(t.originPagePoint??e.pagePoint).dist2(e.pagePoint)>=9,o=t.currentTimestamp??e.timestamp,s=e.timestamp-o;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:o,currentTimestamp:e.timestamp,pageVelocity:ze(n,e.pagePoint,s),screenVelocity:ze(i,e.screenPoint,s),buttons:e.buttons,isDragging:r,dragPhase:r?"dragging":"pointing",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}case"pointer_up":case"pointer_cancel":return{...t,previousPagePoint:t.currentPagePoint,previousScreenPoint:t.currentScreenPoint,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:t.currentTimestamp,currentTimestamp:e.timestamp,pageVelocity:Ue(),screenVelocity:Ue(),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=>He(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=>He(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},lp=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());_dropTargetShapeIdSignal=s("editor.dropTargetShapeId",null);dropTargetShapeIdSignal=this._dropTargetShapeIdSignal;_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){re(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));te(this._erasingShapeIdsSignal.get(),t)||this._erasingShapeIdsSignal.set(t)}clearErasingShapeIds(){this.setErasingShapeIds([])}getEraserTrail(){return this._eraserTrailSignal.get().map(e=>e.clone())}setEraserTrail(e){ie(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&&ie(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&&ne(t.rawPagePoint,n.rawPagePoint)&&ne(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)}setDropTargetShapeId(e){this._dropTargetShapeIdSignal.get()!==e&&this._dropTargetShapeIdSignal.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.setDropTargetShapeId(null),this.setSelectionTranslationActive(!1),this.setSnapIndicators(null)}},cp=.001,up=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=U(this.editor);this.stateAtom=s("editor.query.state",(e=>{const t=e.filter(c).sort((e,t)=>e.index.localeCompare(t.index)),n=e.filter(u).sort((e,t)=>e.parentId===t.parentId?((e,t)=>e.index.localeCompare(t.index))(e,t):e.parentId.localeCompare(t.parentId)),i=e.filter(p).sort(Je),r=new Map,o=new Map,s=new Map,a=new Map(n.map(e=>[e.id,e])),d=new Map,l=new Map,h=new Map,g=new Map;for(const c of n)je(o,c.parentId,c.id);const m=(e,t)=>{for(const n of o.get(t)??[]){const t=a.get(n);t&&(je(r,e,t.id),s.set(t.id,e),m(e,t.id))}};for(const c of t)m(c.id,c.id);for(const c of i)d.set(c.id,c),Ge(l,c.fromId,c.id),Ge(h,c.toId,c.id),Ge(g,c.fromId,c.id),Ge(g,c.toId,c.id);return{pageShapeIdsByPage:r,childShapeIdsByParent:o,pageIdByShape:s,bindingById:d,bindingIdsByFromShape:l,bindingIdsByToShape:h,relatedBindingIdsByShape:g}})(Array.from(t.recordsSignal.get().values()))),this.stateSignal=this.stateAtom,t.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=a("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(this.editor.getCurrentPageId()),{isEqual:Qe}),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",()=>lt(e,t),{isEqual:at}),i=a("editor.query.selectionPageOutlineVertices",()=>n.get().outlineVertices,{isEqual:st}),r=a("editor.query.selectionPageBounds",()=>n.get().pageBounds,{isEqual:re}),o=a("editor.query.selectionFrameBounds",()=>n.get().frameBounds,{isEqual:re}),s=a("editor.query.selectionRotation",()=>n.get().rotation);return{geometry:n,pageOutlineVertices:i,pageBounds:r,frameBounds:o,hasRotation:a("editor.query.selectionHasRotation",()=>n.get().hasRotation),rotation:s,rotationCenter:a("editor.query.selectionRotationCenter",()=>n.get().rotationCenter,{isEqual:ne}),hasCompatibleRotation:a("editor.query.selectionHasCompatibleRotation",()=>n.get().hasCompatibleRotation),selectionAnchorPagePoint:a("editor.query.selectionAnchorPagePoint",()=>n.get().selectionAnchorPagePoint,{isEqual:ne})}})(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 yt(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 yt(t)}getShapeContainment(e,t){const n=this.editor.getShape(e);if(!n)return null;const i=this.getShapeGeometrySnapshot(e),r=this.getShapeGeometrySnapshot(t);if(!i||!r)return null;const o=this.editor.getShapeUtil(n),s=o.getLocalBounds(n),a=o.getLocalToPageTransform(n).invert();return r.outlineVertices.length>0&&r.outlineVertices.every(e=>s.containsPoint(a.applyToPoint(e)))?"inside":i.bounds.intersects(r.bounds)?"intersecting":"outside"}getContainingShapeParentId(e){const t=Array.from(new Set(e));if(0===t.length)return null;const n=t.map(e=>this.editor.getShape(e)).filter(e=>!!e);if(n.length!==t.length)return null;const i=this.getPageIdForShape(n[0].id);if(!i)return null;if(n.some(e=>this.getPageIdForShape(e.id)!==i))return null;const r=new Set;for(const l of n){r.add(l.id);for(const e of this.getDescendantShapeIds(l.id))r.add(e)}let o=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(r.has(e))continue;const t=this.editor.getShape(e);if(!t)continue;if(!Pt(t,this.editor.getShapeUtil(t)))continue;if(!n.every(e=>this.editor.canUseShapeParent(t.id,e.id)))continue;if(!n.every(e=>"inside"===this.getShapeContainment(t.id,e.id)))continue;const i=this.getShapePageBounds(t.id);if(!i)continue;const c=i.w*i.h;(!o||c<s||c===s&&l>a)&&(o=t,s=c,a=l)}return o?.id??i}getContainingShapeParentIdAtPoint(e,t){const n=Array.from(new Set(e));if(0===n.length)return null;const i=n.map(e=>this.editor.getShape(e)).filter(e=>!!e);if(i.length!==n.length)return null;const r=this.getPageIdForShape(i[0].id);if(!r)return null;if(i.some(e=>this.getPageIdForShape(e.id)!==r))return null;const o=new Set;for(const c of i){o.add(c.id);for(const e of this.getDescendantShapeIds(c.id))o.add(e)}let s=null,a=1/0,d=-1;const l=this.stateSignal.get().pageShapeIdsByPage.get(r)??[];for(let c=0;c<l.length;c+=1){const e=l[c];if(o.has(e))continue;const n=this.editor.getShape(e);if(!n||this.editor.isShapeHidden(n.id))continue;const r=this.editor.getShapeUtil(n);if(!Pt(n,r))continue;if(!i.every(e=>this.editor.canUseShapeParent(n.id,e.id)))continue;if(!this.editor.isPagePointInShapeClip(n.id,t))continue;const u=r.getLocalBounds(n),h=r.getLocalToPageTransform(n).invert();if(!u.containsPoint(h.applyToPoint(t)))continue;const p=this.getShapePageBounds(n.id);if(!p)continue;const g=p.w*p.h;(!s||g<a||g===a&&c>d)&&(s=n,a=g,d=c)}return s?.id??r}getContainingParentIdForShapeRecord(e){const t=this.getPageIdForShapeParent(e.parentId);if(!t)return null;const n=qe(e,this.editor.getShapeUtil(e));let i=null,r=1/0,o=-1;const s=this.stateSignal.get().pageShapeIdsByPage.get(t)??[];for(let a=0;a<s.length;a+=1){const t=this.editor.getShape(s[a]);if(!t||t.id===e.id)continue;const d=this.editor.getShapeUtil(t);if(!Pt(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<r||h===r&&a>o)&&(i=t,r=h,o=a)}return i?.id??t}getShapeClipAncestorIds(e){return[...this.getShapeClipAncestorIdsSignal(e).get()]}getShapeClipAncestorIdsSignal(e){return this.getShapeQuerySignals(e).clipAncestorIds}isPagePointInShapeClip(e,t){const n=this.editor.getShape(e);if(!n)return!1;for(const i of this.getShapeClipAncestorsForShape(n,e=>this.editor.getShape(e))){const e=this.editor.getShapeUtil(i),n=e.getChildClipLocalBounds(i);if(!n||!xt(n))continue;const r=e.getLocalToPageTransform(i).invert().applyToPoint(t);if(!n.containsPoint(r))return!1}return!0}getShapeClippedPageBounds(e){let t=this.getShapePageBounds(e);if(!t)return null;for(const n of this.getShapeClipAncestors(e)){const e=this.getShapeChildClipPageBounds(n);if(!e)continue;const i=bt(t,e);if(!i)return null;t=i}return t}getShapeClipAncestors(e){const t=this.editor.getShape(e);return t?this.getShapeClipAncestorsForShape(t,e=>this.editor.getShape(e)):[]}getShapeClipAncestorsForShape(e,t){const n=[],i=new Set;let r=e.parentId;for(;r.startsWith("shape:");){const e=r;if(i.has(e))break;i.add(e);const o=t(e);if(!o)break;const s=this.editor.getShapeUtil(o).getChildClipLocalBounds(o);s&&xt(s)&&n.push(o),r=o.parentId}return n.reverse()}getShapeChildClipPageBounds(e){const t=this.editor.getShapeUtil(e),n=t.getChildClipLocalBounds(e);return n&&xt(n)?(i=n,r=t.getLocalToPageTransform(e),Hh.FromPoints([new zh(i.minX,i.minY),new zh(i.maxX,i.minY),new zh(i.maxX,i.maxY),new zh(i.minX,i.maxY)].map(e=>r.applyToPoint(e)))):null;var i,r}getShapeIdsForPageSnapshot(e){return this.stateSignal.get().pageShapeIdsByPage.get(e)??[]}getChildShapeIdsSnapshot(e){return this.stateSignal.get().childShapeIdsByParent.get(e)??[]}handleStoreChange(e){for(const n of(e=>e.diff.removed.filter(u).map(e=>e.id))(e))this.shapeQuerySignals.delete(n);const t=U(this.editor);this.stateAtom.update(n=>((e,t,n)=>{const i=t.diff.added.filter(u),r=t.diff.updated.filter(rt),o=t.diff.removed.filter(u),s=t.diff.added.filter(p),a=t.diff.updated.filter(ot),d=t.diff.removed.filter(p),l=i.length>0||o.length>0||r.some(({before:e,after:t})=>e.parentId!==t.parentId||e.index!==t.index),h=s.length>0||d.length>0||a.some(({before:e,after:t})=>e.fromId!==t.fromId||e.toId!==t.toId),g=s.length>0||d.length>0||a.length>0;if(!l&&!g)return e;const m={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 f=!1;if(l){const t=e=>{const t=n(e);return u(t)?t.index:void 0},s=new Set,a=e=>{let t=e;const i=new Set;for(;t&&!i.has(t);){i.add(t);const e=n(t);if(!e)return null;if(c(e))return e.id;if(!u(e))return null;t=e.parentId}return null};for(const n of o){it(m.childShapeIdsByParent,n.parentId,n.id);const t=e.pageIdByShape.get(n.id);t&&s.add(t)}for(const{before:n,after:i}of r){if(n.parentId===i.parentId&&n.index===i.index)continue;it(m.childShapeIdsByParent,n.parentId,n.id),nt(m.childShapeIdsByParent,i.parentId,i,t);const r=e.pageIdByShape.get(n.id);r&&s.add(r);const o=a(i.parentId);o&&s.add(o)}for(const e of i)nt(m.childShapeIdsByParent,e.parentId,e,t);for(const e of i){const t=a(e.parentId);t&&s.add(t)}if(s.size>0){const t=new Map(e.pageShapeIdsByPage),i=new Map(e.pageIdByShape);for(const[n,o]of e.pageIdByShape)s.has(o)&&i.delete(n);const r=(e,t)=>{const o=[];for(const s of m.childShapeIdsByParent.get(t)??[])n(s)&&(o.push(s),i.set(s,e),o.push(...r(e,s)));return o};for(const e of s){const n=r(e,e);n.length>0?t.set(e,n):t.delete(e)}m.pageShapeIdsByPage=t,m.pageIdByShape=i}f=!0}if(g){for(const e of d)f=m.bindingById.delete(e.id)||f;if(h){for(const e of d)f=Ze(m.bindingIdsByFromShape,e.fromId,e.id)||f,f=Ze(m.bindingIdsByToShape,e.toId,e.id)||f,f=Ze(m.relatedBindingIdsByShape,e.fromId,e.id)||f,f=Ze(m.relatedBindingIdsByShape,e.toId,e.id)||f;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(f=Ze(m.bindingIdsByFromShape,e.fromId,e.id)||f,f=Ze(m.bindingIdsByToShape,e.toId,e.id)||f,f=Ze(m.relatedBindingIdsByShape,e.fromId,e.id)||f,f=Ze(m.relatedBindingIdsByShape,e.toId,e.id)||f)}for(const e of s)m.bindingById.set(e.id,e),f=!0;for(const{after:e}of a)m.bindingById.set(e.id,e),f=!0;if(h){for(const e of s)f=tt(m.bindingIdsByFromShape,e.fromId,e,"from",e=>m.bindingById.get(e))||f,f=tt(m.bindingIdsByToShape,e.toId,e,"to",e=>m.bindingById.get(e))||f,f=tt(m.relatedBindingIdsByShape,e.fromId,e,"related",e=>m.bindingById.get(e))||f,f=tt(m.relatedBindingIdsByShape,e.toId,e,"related",e=>m.bindingById.get(e))||f;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(f=tt(m.bindingIdsByFromShape,t.fromId,t,"from",e=>m.bindingById.get(e))||f,f=tt(m.bindingIdsByToShape,t.toId,t,"to",e=>m.bindingById.get(e))||f,f=tt(m.relatedBindingIdsByShape,t.fromId,t,"related",e=>m.bindingById.get(e))||f,f=tt(m.relatedBindingIdsByShape,t.toId,t,"related",e=>m.bindingById.get(e))||f)}}return f?m: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:ct}),i=a(`editor.query.shapeGeometry.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return qe(t,this.editor.getShapeUtil(t))},{isEqual:gt});t={bounds:n,geometry:i,positionedToPageTransform:a(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return Ke(t,this.editor.getShapeUtil(t))},{isEqual:pt}),pageBounds:a(`editor.query.shapePageBounds.${e}`,()=>i.get()?.bounds,{isEqual:ct}),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:Qe})},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 Yh(t.a,t.b,t.c,t.d,t.e,t.f):void 0;var t}getShapePageBounds(e){return mt(this.getShapePageBoundsSignal(e).get())??void 0}getShapeBounds(e){return mt(this.getShapeQuerySignals(e).bounds.get())??void 0}getShapePageCenter(e){return ft(this.getShapeGeometrySnapshot(e)?.center)??void 0}getShapePageCorners(e){return St(this.getShapeGeometrySnapshot(e)?.corners)}getShapePageOutlineVertices(e){return St(this.getShapeGeometrySnapshot(e)?.outlineVertices)}getSelectionPageOutlineVertices(){return St(this.selectionPageOutlineVerticesSignal.get())??[]}getSelectionPageBounds(){return mt(this.selectionPageBoundsSignal.get())??null}getSelectionFrameBounds(){return mt(this.selectionFrameBoundsSignal.get())??null}getSelectionRotation(){return this.selectionRotationSignal.get()}getSelectionHasRotation(){return this.selectionHasRotationSignal.get()}getSelectionRotationCenter(){return ft(this.selectionRotationCenterSignal.get())??null}getSelectionHasCompatibleRotation(){return this.selectionHasCompatibleRotationSignal.get()}getSelectionAnchorPagePoint(){return ft(this.selectionAnchorPagePointSignal.get())??null}getBinding(e){return this.stateSignal.get().bindingById.get(e)}getBindings(){return Array.from(this.stateSignal.get().bindingById.values()).sort(Je)}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)}},hp=class{entries;cellSize;cells=new Map;order=new Map;constructor(e){this.entries=e,this.cellSize=(e=>{if(0===e.length)return 256;let t=0;for(const n of e)t+=Math.max(n.queryBounds.w,n.queryBounds.h);return Math.max(16,Math.round(t/e.length)||256)})(e);for(let t=0;t<e.length;t+=1){const n=e[t];n&&(this.order.set(n,t),this.insert(n))}}cellKey(e,t){return`${e}:${t}`}insert(e){const t=Math.floor(e.queryBounds.minX/this.cellSize),n=Math.floor(e.queryBounds.minY/this.cellSize),i=Math.floor(e.queryBounds.maxX/this.cellSize),r=Math.floor(e.queryBounds.maxY/this.cellSize);for(let o=n;o<=r;o+=1)for(let n=t;n<=i;n+=1){const t=this.cellKey(n,o),i=this.cells.get(t);i?i.push(e):this.cells.set(t,[e])}}search(e){const t=Math.floor(e.minX/this.cellSize),n=Math.floor(e.minY/this.cellSize),i=Math.floor(e.maxX/this.cellSize),r=Math.floor(e.maxY/this.cellSize);if((i-t+1)*(r-n+1)>this.entries.length)return this.entries.filter(t=>t.queryBounds.intersects(e));const o=new Set,s=[];for(let a=n;a<=r;a+=1)for(let n=t;n<=i;n+=1){const t=this.cells.get(this.cellKey(n,a));if(t)for(const n of t)o.has(n)||(o.add(n),n.queryBounds.intersects(e)&&s.push(n))}return s.length>1&&s.sort((e,t)=>(this.order.get(e)??0)-(this.order.get(t)??0)),s}},pp=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 Hh(e.x-.5,e.y-.5,1,1))(e)),i=[];for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(!o?.pointHitTestBounds.containsPoint(e))continue;const s=this.editor.getShape(o.shapeId);if(!s)continue;if(t?.filter&&!t.filter(s))continue;const a=this.editor.getShapeUtil(s),d=_e(s,e,a);a.hitTest(s,d,{editor:this.editor,pagePoint:e,positionedPoint:d})&&i.push(s)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,r=((e,t,n)=>Hh.FromPoints([e,t]).expand(Math.max(.5,n)))(e,t,i),o=this.getPageIndex(n?.pageId).search(r),s=[];for(let a=o.length-1;a>=0;a-=1){const r=o[a];if(!r)continue;const d=this.queries.getShapeClippedPageBounds(r.shapeId);if(!d||!wt(e,t,d.expand(i)))continue;const l=this.editor.getShape(r.shapeId);if(!l)continue;if(n?.filter&&!n.filter(l))continue;const c=this.editor.getShapeUtil(l),u=_e(l,e,c),h=_e(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),r=this.queries.getShapePageBoundsSignal(e).get();if(!r)continue;const o=vt(i.getPointHitTestBounds(t,{editor:this.editor}),Ke(t,i)),s=Hh.FromPoints([new zh(r.minX,r.minY),new zh(r.maxX,r.maxY),new zh(o.minX,o.minY),new zh(o.maxX,o.maxY)]);n.push({shapeId:e,shapeBounds:r,queryBounds:s,pointHitTestBounds:o})}return new hp(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.getCurrentPageId()){return this.getPageIndexSignal(e).get()}},gp=class{editor;constructor(e){this.editor=e}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createHandleSnapshot({context:e,currentPagePoint:t,allowSelfSnap:n=!1,excludedShapeIds:i=[]}){const r=this.editor.getShape(e.shapeId),o=new Set(this.editor.getShapeIdsIncludingDescendants([e.shapeId]));this.collectBindingDrivenExcludedShapeIds([e.shapeId],o);for(const c of i)o.add(c);const s=[],a=[],d=this.getSnapScopeParentId([e.shapeId]),l=this.getCandidateShapeIds({excludedShapeIds:o,scopeParentId:d});r&&n&&this.collectSelfHandleSnapGeometry({shape:r,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 r=this.editor.getShapeClippedPageBounds(e.id);if(!r)return;const o=this.editor.computeShapeLocalToPageTransform(e),s=i.getHandleSnapGeometry(e);for(const c of s.points??[]){const n=o.applyToPoint(c);this.editor.isPagePointInShapeClip(e.id,n)&&t.push({id:`${e.id}:point:${t.length}`,nodeId:e.id,point:n})}const a=s.outline;if(null===a)return;const d=this.editor.getShapeClipAncestorIds(e.id).length>0?Wt(r):(a??(l=i.getLocalBounds(e),[new zh(l.minX,l.minY),new zh(l.maxX,l.minY),new zh(l.maxX,l.maxY),new zh(l.minX,l.maxY)])).map(e=>o.applyToPoint(e));var l;d.length>0&&n.push({id:e.id,points:d})}collectSelfHandleSnapGeometry({shape:e,context:t,currentPagePoint:n,points:i,outlines:r}){const o=this.editor.getShapeUtil(e);if(!o.canSnap(e))return;const s=this.editor.getShapeClippedPageBounds(e.id);if(!s)return;const a=o.getHandleSnapGeometry(e),d=this.editor.computeShapeLocalToPageTransform(e),l={...t,currentPagePoint:n.clone()};for(const h of a.getSelfSnapPoints?.(l)??[]){const t=d.applyToPoint(h);this.editor.isPagePointInShapeClip(e.id,t)&&i.push({id:`${e.id}:self-point:${i.length}`,nodeId:e.id,point:t})}const c=a.getSelfSnapOutline?.(l)??null;if(!c)return;const u=this.editor.getShapeClipAncestorIds(e.id).length>0?Wt(s):c.map(e=>d.applyToPoint(e));u.length>0&&r.push({id:e.id,points:u})}createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=Array.from(e),i=new Set(this.editor.getShapeIdsIncludingDescendants(n));this.collectBindingDrivenExcludedShapeIds(n,i);const r=[],o=[],s={rotation:t.rotation,rotationCenter:t.rotationCenter},a=this.getSnapScopeParentId(n),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?Wt(i):this.editor.getShapePageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():mn(e,s));if(0===a.length)continue;const d=Hh.FromPoints(a);o.push({id:e.id,bounds:d});const c=n.getBoundsSnapGeometry(e).points;(void 0===c?$t(d):c.map(t=>{const n=this.editor.computeShapeLocalToPageTransform(e).applyToPoint(t);return this.editor.isPagePointInShapeClip(e.id,n)?n:null}).filter(e=>null!==e).map(e=>0===t.rotation?e:mn(e,s))).forEach((t,n)=>{r.push({id:`${e.id}:${n}`,nodeId:e.id,point:t})})}return{points:r,nodes:o,coordinateSpace:{rotation:t.rotation,rotationCenter:t.rotationCenter.clone()},scopeParentId:a,candidateShapeIds: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 r=this.editor.getShape(e);if(r)for(const n of this.editor.getBindingsForShape(e)){const o=n.fromId===e?"from":n.toId===e?"to":null;if(!o)continue;const s=this.editor.getBindingUtil(n).getGeometryDependentShapeIds?.(this.editor,n,{shape:r,role:o})??[];for(const e of s)for(const n of this.editor.getShapeIdsIncludingDescendants([e]))t.has(n)||(t.add(n),i.push(n))}}}getSnapScopeParentId(e){let t=null;for(const n of e){const e=this.editor.getShape(n);if(e)if(t){if(e.parentId!==t)return this.editor.getCurrentPageId()}else t=e.parentId}return t??this.editor.getCurrentPageId()}getCandidateShapeIds({excludedShapeIds:e,scopeParentId:t}){const n=this.editor.getCurrentPageId(),i=this.editor.renderViewportPageBoundsSignal.get(),r=new Set;t?.startsWith("shape:")&&r.add(t);const o=t??n;for(const s of this.editor.getChildShapeIds(o))r.add(s);return(null===i?Array.from(r):this.editor.getShapeIdsInBounds(i,{pageId:n}).filter(e=>r.has(e))).filter(n=>{if(e.has(n))return!1;const r=this.editor.getShape(n);if(!r||r.parentId!==o)return n===t;const s=this.editor.getShapeClippedPageBounds(n);return!!s&&(!i||s.intersects(i))})}},mp=class{gapCache=new WeakMap;_indicatorsSignal=s("editor.snapIndicators",[]);indicatorsSignal=this._indicatorsSignal;activeSignal=a("editor.snapIndicatorsActive",()=>this._indicatorsSignal.get().length>0);snapshots;constructor(e){this.snapshots=new gp(e)}setIndicators(e){const t=e.map(gn);tn(this._indicatorsSignal.get(),t)||this._indicatorsSignal.set(t)}clearIndicators(){this._indicatorsSignal.get().length>0&&this._indicatorsSignal.set([])}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=this.snapshots.createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t});return this.gapCache.set(n,{x:Zt(n.nodes,"x"),y:Zt(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=Kt(e.initialSelectionBounds,e.dragDelta),n=(i=$t(e.initialSelectionBounds),r=e.dragDelta,i.map(e=>e.add(r)));var i,r;const o=this.gapCache.get(e.snapshot)??{x:Zt(e.snapshot.nodes,"x"),y:Zt(e.snapshot.nodes,"y")},s="y"===e.lockedAxis?null:en(jt("x",n,e.snapshot.points,e.threshold),Jt("x",t,o.x,e.threshold)),a="x"===e.lockedAxis?null:en(jt("y",n,e.snapshot.points,e.threshold),Jt("y",t,o.y,e.threshold)),d=new zh(s?.nudge??0,a?.nudge??0),l=[];return"points"===s?.type?l.push(...on("x",s,d,e.snapshot.coordinateSpace)):"gaps"===s?.type&&l.push(pn(s,e.snapshot.coordinateSpace,d)),"points"===a?.type?l.push(...on("y",a,d,e.snapshot.coordinateSpace)):"gaps"===a?.type&&l.push(pn(a,e.snapshot.coordinateSpace,d)),this.setIndicators(l),{nudge:d,indicators:l}}snapResize(e){const t=Et({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),n=Gt(t,e.resizedSelectionBounds),i="left"===t||"right"===t,r="top"===t||"bottom"===t?null:jt("x",n,e.snapshot.points,e.threshold),o=i?null:jt("y",n,e.snapshot.points,e.threshold),s={x:null!==r,y:null!==o},a=new zh(r?.nudge??0,o?.nudge??0);if(e.isAspectRatioLocked&&Mt(t)&&(0!==a.x||0!==a.y)){const n=r&&o?Math.abs(a.x)<Math.abs(a.y)?"x":"y":r?"x":"y",i=0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h;"x"===n?(s.y=!1,a.y=a.x/i,"bottom_left"!==t&&"top_right"!==t||(a.y=-a.y)):(s.x=!1,a.x=a.y*i,"bottom_left"!==t&&"top_right"!==t||(a.x=-a.x))}const d=function(e,t){const n=Et({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY});let i=e.resizedSelectionBounds.minX,r=e.resizedSelectionBounds.maxX,o=e.resizedSelectionBounds.minY,s=e.resizedSelectionBounds.maxY;e.isResizingFromCenter?(Ct(n)?(i+=t.x,r-=t.x):kt(n)&&(i-=t.x,r+=t.x),Tt(n)?(o+=t.y,s-=t.y):Bt(n)&&(o-=t.y,s+=t.y)):(Ct(n)?i+=t.x:kt(n)&&(r+=t.x),Tt(n)?o+=t.y:Bt(n)&&(s+=t.y));const a=(({minX:e,minY:t,maxX:n,maxY:i})=>{const r=Math.min(e,n),o=Math.min(t,i),s=Math.max(e,n),a=Math.max(t,i);return new Hh(r,o,Math.max(1,s-r),Math.max(1,a-o))})({minX:i,minY:o,maxX:r,maxY:s});if(!e.isAspectRatioLocked){const t=(({startBounds:e,bounds:t,handleId:n,scaleX:i,scaleY:r,isResizingFromCenter:o=!1})=>{const s=At({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:o}),a=At({axis:"y",startBounds:e,bounds:t,handleId:n,scale:r,isResizingFromCenter:o});return{scaleX:Ct(n)||kt(n)?s*(t.w/Math.max(1,e.w)):i??1,scaleY:Tt(n)||Bt(n)?a*(t.h/Math.max(1,e.h)):r??1}})({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter});return{bounds:a,scaleX:t.scaleX,scaleY:t.scaleY}}return Ft({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,aspectRatio:0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h,isResizingFromCenter:e.isResizingFromCenter,scaleX:e.scaleX,scaleY:e.scaleY})}(e,a),{bounds:l}=d,c=Gt("any",l),u=[];if(s.x){const t=jt("x",c,e.snapshot.points,1e-8);t&&u.push(...cn("x",t,zh.Zero(),e.snapshot.coordinateSpace,l,e.snapshot.nodes))}if(s.y){const t=jt("y",c,e.snapshot.points,1e-8);t&&u.push(...cn("y",t,zh.Zero(),e.snapshot.coordinateSpace,l,e.snapshot.nodes))}return this.setIndicators(u),{nudge:a,bounds:l,scaleX:d.scaleX,scaleY:d.scaleY,indicators:u}}snapHandle(e){if("none"===e.mode)return this.clearIndicators(),null;const t="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return t?(this.setIndicators(t.indicators),t):(this.clearIndicators(),null)}snapHandlePoint(e){let t=null,n=e.threshold*e.threshold;for(const r of e.snapshot.points){const i=e.pagePoint.dist2(r.point);i>n||(n=i,t=r.point)}if(!t)for(const r of e.snapshot.outlines){const i=Vt(e.pagePoint,r.points);!i||i.distanceSquared>n||(n=i.distanceSquared,t=i.point)}if(!t)return null;const i=t.clone();return{snappedPagePoint:i,nudge:i.sub(e.pagePoint),indicators:[un(i)]}}snapHandleAlign(e){let t=null,n=null,i=e.threshold,r=e.threshold;for(const d of e.snapshot.points){const o=Math.abs(d.point.x-e.pagePoint.x);o<=i&&(i=o,t=d.point);const s=Math.abs(d.point.y-e.pagePoint.y);s<=r&&(r=s,n=d.point)}if(!t&&!n)return null;const o=new zh(t?t.x-e.pagePoint.x:0,n?n.y-e.pagePoint.y:0),s=e.pagePoint.add(o),a=[];return t&&a.push(hn("x",s,t)),n&&a.push(hn("y",s,n)),{snappedPagePoint:s,nudge:o,indicators:a}}},fp=class{beforeDelete=new Map;afterDelete=new Map;registerBeforeDeleteHandler(e,t){return this.register(this.beforeDelete,e,t)}registerAfterDeleteHandler(e,t){return this.register(this.afterDelete,e,t)}runBeforeDelete(e,t,n){if(0!==t.length)for(const i of this.beforeDelete.get(e)??[])i(t,n)}runAfterDelete(e,t,n){if(0!==t.length)for(const i of this.afterDelete.get(e)??[])i(t,n)}register(e,t,n){const i=e.get(t);return i?i.push(n):e.set(t,[n]),()=>{const i=e.get(t);if(!i)return;const r=i.indexOf(n);r>=0&&i.splice(r,1)}}},Sp=class{editor;constructor(e){this.editor=e}align(e,t="user"){const n=this.getAlignableEntries();if(n.length<2)return!1;const i=Hh.FromPoints(n.flatMap(e=>[new zh(e.bounds.minX,e.bounds.minY),new zh(e.bounds.maxX,e.bounds.maxY)])),r=n.map(({shape:t,bounds:n})=>{let r=0,o=0;switch(e){case"left":r=i.minX-n.minX;break;case"right":r=i.maxX-n.maxX;break;case"horizontal-center":r=i.center.x-n.center.x;break;case"top":o=i.minY-n.minY;break;case"bottom":o=i.maxY-n.maxY;break;case"vertical-center":o=i.center.y-n.center.y}return{id:t.id,x:t.x+r,y:t.y+o}});return this.editor.commands.updateShapes(r,{source:t}),!0}distribute(e,t="user"){const n=this.getAlignableEntries();if(n.length<3)return!1;const i="horizontal"===e,r=e=>i?e.w:e.h,o=e=>i?e.minX:e.minY,s=i?"x":"y",a=[...n].sort((e,t)=>e.bounds.center[s]-t.bounds.center[s]),d=a[0].bounds,l=a[a.length-1].bounds,c=((i?l.maxX:l.maxY)-o(d)-a.reduce((e,t)=>e+r(t.bounds),0))/(a.length-1);let u=o(d);const h=a.map(({shape:e,bounds:t},n)=>{const s=0===n||n===a.length-1?o(t):u,d=s-o(t);return u=s+r(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||!oe(e))return!1;if(e.w<=0&&e.h<=0)return!1;const i=t?.padding??64,r=Math.max(1,n.w-2*i),o=Math.max(1,n.h-2*i),s=ee(Math.min(e.w>0?r/e.w:1/0,e.h>0?o/e.h:1/0,t?.maxZoom??1)),a=e.center;return this.editor.setCamera({x:a.x-n.w/2/s,y:a.y-n.h/2/s,z:s},{source:t?.source??"user"}),!0}zoomToFit(e){const t=this.getCurrentPageBounds();return!!t&&this.zoomToBounds(t,e)}zoomToSelection(e){const t=this.boundsOfShapeIds(this.editor.getSelectedShapeIds());return!!t&&this.zoomToBounds(t,e)}boundsOfShapeIds(e){const t=[];for(const i of e){const e=this.editor.getShapePageBounds(i);e&&oe(e)&&t.push(new zh(e.minX,e.minY),new zh(e.maxX,e.maxY))}if(0===t.length)return null;const n=Hh.FromPoints(t);return oe(n)?n:null}getAlignableEntries(){const e=this.editor.getCurrentPageId(),t=[];for(const n of this.editor.getSelectedShapeIds()){const i=this.editor.getShape(n);if(!i||i.isLocked||i.parentId!==e)continue;const r=this.editor.getShapePageBounds(n);r&&oe(r)&&t.push({shape:i,bounds:r})}return t}},yp=class{editor;constructor(e){this.editor=e}setSelectedShapeIds(e,t){const n=this.editor,i=t?.pageId??n.getCurrentPageId(),r=t?.source??"user",o=((e,t)=>{const n=new Set(t);return t.filter(t=>{const i=e.getShape(t);if(!i)return!1;let r=i.parentId;const o=new Set([t]);for(;r.startsWith("shape:");){const t=r;if(o.has(t))return!0;if(n.has(t))return!1;o.add(t);const i=e.getShape(t);if(!i)return!0;r=i.parentId}return!0})})(n,Array.from(new Set(e.filter(e=>n.getShapePageId(e)===i&&!n.isShapeHidden(e))))),s=n.sessionSignal.get(),a=s.pageSelectedShapeIdsById[i]??[];n.getShapeEditingSession()&&!n.completeEditing(r)||te(a,o)||(n.setBindingPreview(null),n.setSnapIndicators(null),n.updateSession({pageSelectedShapeIdsById:{...s.pageSelectedShapeIdsById,[i]:o}},r))}removeShapeIdsFromSelection(e,t="system"){if(0===e.length)return;const n=this.editor,i=new Set(e),r=n.sessionSignal.get(),o={};for(const s of n.getPages())o[s.id]=(r.pageSelectedShapeIdsById[s.id]??[]).filter(e=>!i.has(e));n.updateSession({pageSelectedShapeIdsById:o},t)}selectAllCurrentPage(e="user"){const t=this.editor,n=t.getCurrentPageId(),i=t.getCurrentPageShapeIds().map(e=>t.getShape(e)).filter(e=>!!e&&e.parentId===n&&!t.isShapeHidden(e.id)).map(e=>e.id);t.commands.setSelectedShapeIds(i,{source:e})}},xp=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(_n(t))return null;const n=e.getSelectionFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:Bn}),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:Mn}),this.pathSignal=a("editor.selectionOverlayPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return _n(t)?t[0]?.path??null:null}),this.bindingSegmentsSignal=a("editor.selectionOverlayBindingSegments",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return _n(t)?[...t[0]?.bindingSegments??[]]:[]},{isEqual:Cn}),this.frameStyleSignal=a("editor.selectionOverlayFrameStyle",()=>{const t=e.cameraZoomSignal.get();return{strokeWidth:2/t,cornerRadius:3/t}},{isEqual:En}),this.frameSignal=a("editor.selectionOverlayFrame",()=>{const e=this.frameGeometrySignal.get();if(!e)return null;const t=this.frameStyleSignal.get();return{...e,...t}},{isEqual:Tn}),this.handleAnchorsSignal=a("editor.selectionOverlayHandleAnchors",()=>{if("select"!==e.toolStateSignal.get().activeToolId)return null;const t=e.selectedShapesSignal.get();if(0===t.length)return null;const n=e.getSelectionFrame(),i=e.cameraZoomSignal.get(),r=1===t.length;return Vn(t,n,i,t=>e.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:r,editor:e}),t=>e.getShapeUtil(t).canUseSelectionFrameHandles(t,{editor:e}))},{isEqual:Wn}),this.handlesSignal=a("editor.selectionOverlayHandles",()=>{const t=this.handleAnchorsSignal.get();if(!t)return null;const n=e.cameraZoomSignal.get(),{resizeHandles:i,rotateHandles:r,terminalHandles:o,middleHandles:s,customHandles:a}=qn(t,n);return{resizeHandles:i,rotateHandles:r,terminalHandles:o,middleHandles:s,customHandles:a,strokeWidth:2/n}},{isEqual:Xn}),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:Nn}),this.overlaySignal=a("editor.selectionOverlay",()=>{const e=this.frameSignal.get(),t=this.handlesSignal.get();return e&&t?{...e,...t}:null}),this.debugStateSnapshotSignal=a("editor.overlayDebugState.snapshot",t=>{const n=this.frameSignal.get(),i=this.handleCountsSignal.get(),r=t!==Lh?t:null,o=!r||!Tn(r.frame,n),s=!r||!Nn(r.handleCounts,i);return{metrics:{selectionFrameActive:null!==n,selectionHandlesActive:null!==i,bindingPreviewActive:e.bindingPreviewActiveSignal.get(),brushBoxActive:e.brushBoxActiveSignal.get(),selectionFrameChangeCount:(r?.metrics.selectionFrameChangeCount??0)+(o?1:0),selectionHandlesChangeCount:(r?.metrics.selectionHandlesChangeCount??0)+(s?1:0),resizeHandleCount:i?.resizeHandleCount??0,rotateHandleCount:i?.rotateHandleCount??0,terminalHandleCount:i?.terminalHandleCount??0,middleHandleCount:i?.middleHandleCount??0,customHandleCount:i?.customHandleCount??0,boundsSummary:(a=n?.bounds??null,a?`${Math.round(a.x)},${Math.round(a.y)},${Math.round(a.w)},${Math.round(a.h)}`:"none"),rotation:n?.rotation??null,strokeWidth:n?.strokeWidth??null},frame:n,handleCounts:i};var a},{isEqual:(e,t)=>ae(e.metrics,t.metrics)}),this.debugStateSignal=a("editor.overlayDebugState.public",()=>this.debugStateSnapshotSignal.get().metrics,{isEqual:ae})}},bp=class{editor;entryRequestAtom=s("editor.shapeEditingEntryRequest",null);entryRequestSignal=this.entryRequestAtom;nextEntryRequestId=1;constructor(e){this.editor=e}canEditShape(e){const t="string"==typeof e?this.editor.getShape(e):e;return!!t&&!t.isLocked&&this.editor.getShapeUtil(t).canEdit(t)}start(e,t="user"){const n=this.editor.getShape(e.shapeId);if(!n||!this.canEditShape(n))return null;const i=this.editor.getShapeEditingSession();if(i?.shapeId===n.id){const r={...i,entryMode:e.entryMode??i.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:i.caretPagePoint};return this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:r},t),this.publishEntryRequest({shapeId:n.id,entryMode:r.entryMode,caretPagePoint:r.caretPagePoint}),r}e.preserveInteraction||this.editor.cancelInteractionForCommand(),this.end({runEditEnd:!0,source:t});const r=e.markId??`editing:${n.id}`;e.reuseExistingMark||this.editor.history.mark(r);const o={shapeId:n.id,markId:r,entryMode:e.entryMode??"focusEnd",caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0,isComposing:!1};return this.editor.commands.setSelectedShapeIds([n.id],{source:t}),this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:o},t),this.publishEntryRequest({shapeId:n.id,entryMode:o.entryMode,caretPagePoint:o.caretPagePoint}),o}complete(e="user"){const t=this.editor.getShapeEditingSession();return!!t&&!t.isComposing&&(this.end({runEditEnd:!0,source:e}),this.editor.history.squashToMark(t.markId,"shape.edit"),!0)}cancel(e="user"){const t=this.editor.getShapeEditingSession();return!!t&&!t.isComposing&&(this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},e),this.editor.history.bailToMark(t.markId),!0)}setComposition(e,t="system"){const n=this.editor.getShapeEditingSession();n&&n.isComposing!==e&&this.editor.updateSession({shapeEditingSession:{...n,isComposing:e}},t)}consumeEntryRequest(e){const t=this.entryRequestAtom.get();t&&t.id===e&&this.entryRequestAtom.set(null)}removeShapeIds(e,t="system"){const n=this.editor.getShapeEditingSession();n&&e.includes(n.shapeId)&&this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},t)}end(e){const t=this.editor.getShapeEditingSession();if(!t)return;this.entryRequestAtom.set(null);const n=this.editor.getShape(t.shapeId);if(this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},e.source),!e.runEditEnd||!n)return;const i=this.editor.getShapeUtil(n).onEditEnd(n);i?.deleteShapeIds&&i.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(i.deleteShapeIds,{source:e.source})}publishEntryRequest(e){this.entryRequestAtom.set({id:this.nextEntryRequestId++,shapeId:e.shapeId,entryMode:e.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0})}},Pp=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 Ye(e,this.editor.getShapeUtil(e))}computeShapeLocalToPageTransform(e){return Oe(e,this.editor.getShapeUtil(e))}computeShapeRenderToPageTransform(e){return((e,t)=>Oe(e,t))(e,this.editor.getShapeUtil(e))}computeShapeExportToPageTransform(e){return Xe(e,this.editor.getShapeUtil(e))}computeShapePageBounds(e){return((e,t)=>Hh.FromPoints(Ve(e,t)))(e,this.editor.getShapeUtil(e))}computeShapeExportPageBounds(e){return((e,t)=>{const n=Ye(e,t),i=Xe(e,t);return Hh.FromPoints([new zh(n.minX,n.minY),new zh(n.maxX,n.minY),new zh(n.maxX,n.maxY),new zh(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))})(e,this.editor.getShapeUtil(e))}computeShapeGeometry(e){return qe(e,this.editor.getShapeUtil(e))}computeShapePositionedToPageTransform(e){return Ke(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()}},Ip=class{editor;constructor(e){this.editor=e}get store(){return U(this.editor)}getSelectionParentOrderState(){return jn(this.editor)}getSelectionGroupState(){const e=this.editor,t=e.getSelectedShapes();if(t.length<2)return null;if(t.some(t=>t.isLocked||e.hasLockedDescendant(t.id)))return null;const n=t[0]?.parentId;if(!n)return null;if(t.some(e=>e.parentId!==n))return null;const i=e.getChildShapes(n),r=new Set(t.map(e=>e.id)),o=i.filter(e=>r.has(e.id)).map(e=>e.id);if(o.length!==t.length)return null;const s=e.getSelectionPageBounds();return s&&oe(s)?{parentId:n,shapeIds:o,bounds:s}:null}canGroupSelection(){return null!==this.getSelectionGroupState()}getGroupStateForShapeIds(e){const t=this.editor,n=Array.from(new Set(e)),i=n.map(e=>t.getShape(e)).filter(e=>!!e);if(i.length<2||i.length!==n.length)return null;if(i.some(e=>e.isLocked||t.hasLockedDescendant(e.id)||t.isShapeHidden(e.id)))return null;const r=i[0]?.parentId;if(!r)return null;if(i.some(e=>e.parentId!==r))return null;const o=t.getChildShapes(r),s=new Set(n),a=o.filter(e=>s.has(e.id)).map(e=>e.id);if(a.length!==n.length)return null;const d=a.map(e=>t.getShapePageBounds(e)).filter(e=>!!e).flatMap(e=>[new zh(e.minX,e.minY),new zh(e.maxX,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)]),l=d.length>0?Hh.FromPoints(d):null;return l&&oe(l)?{parentId:r,shapeIds:a,bounds:l}:null}groupShapesFromState(e,t){const n=this.editor,i=n.getChildShapes(e.parentId),r=new Set(e.shapeIds),o=i.findIndex(e=>r.has(e.id));if(o<0)return null;n.cancelInteractionForCommand();const s=[];return this.store.atomic(()=>{const[a]=n.commands.createShapes([{type:"group",x:e.bounds.x,y:e.bounds.y,parentId:e.parentId,index:n.createShapeIndex(o+1),props:{w:e.bounds.w,h:e.bounds.h}}],{source:t});if(!a)return;s.push(a);const d=[];let l=!1;for(const e of i)r.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).shouldTransformDescendants(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=e.map(e=>n.getShape(e)).filter(e=>!!e),r=new Set(this.getUngroupableShapeIds(e));if(0===r.size)return[];n.cancelInteractionForCommand();const o=[],s=new Set;return this.store.atomic(()=>{const e=[],a=[];for(const t of i){if(!r.has(t.id)){s.has(t.id)||(s.add(t.id),o.push(t.id));continue}const i=n.getShape(t.id);if(!i)continue;const d=n.getChildShapes(i.id),l=n.getChildShapes(i.parentId),c=new Set(d.map(e=>e.id)),u=[];let h=!1;for(const e of l)e.id!==i.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)?i.parentId:e.parentId,index:n.createShapeIndex(t+1)})));for(const e of d)s.has(e.id)||(s.add(e.id),o.push(e.id));a.push(i.id)}e.length>0&&n.commands.updateShapes(e,{source:t}),a.length>0&&(n.bindings.cleanupBindingsForDeletedShapes(a,t),this.store.remove(a,t),n.removeShapeIdsFromSelection(a,t),n.removeShapeIdsFromEditingSession(a,t))},t),o.length>0&&n.commands.setSelectedShapeIds(o,{source:t}),o}ungroupSelection(e="user"){return this.ungroupShapes(this.editor.getSelectedShapeIds(),e)}getSelectionSiblingOrderState(){return Gn(this.editor)}canMoveSelectionWithinParent(e){return((e,t)=>{const n=Gn(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveSelectionInParentOrder(e){return((e,t)=>{const n=jn(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveShapesInParentOrder(e,t){return((e,t,n)=>{const i=Zn(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this.editor,e,t)}moveShapesInParentOrder(e,t,n="user"){return Qn(this.editor,e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return Jn(this.editor,e,t,n)}moveSelectionWithinParent(e,t="user"){return((e,t,n="user")=>{const i=e.getSelectedShapes();if(1!==i.length)return!1;const[r]=i;if(!r||r.isLocked)return!1;const o=Gn(e);if(!o)return!1;const s=e.getChildShapes(o.parentId),a=o.index;if(s[a]?.id!==r.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 r=i.map(t=>e.getShape(t)).filter(e=>!!e);return r.length===i.length&&!r.some(t=>t.isLocked||e.isShapeHidden(t.id))&&!i.some(n=>!ei(e,t.parentId,n))&&ti(e,t,i,r,n)})(this.editor,e,t)}moveShapesToParentPlacementResult(e,t="user"){return((e,t,n="user")=>{const i=Array.from(new Set(t.ids));if(0===i.length)return{ok:!1,reason:"notFound"};const r=i.map(t=>e.getShape(t)).filter(e=>!!e);if(r.length!==i.length)return{ok:!1,reason:"notFound"};for(const o of r){if(o.isLocked)return{ok:!1,reason:"locked"};if(e.isShapeHidden(o.id))return{ok:!1,reason:"hidden"}}for(const o of i){const n=t.parentId;if(n.startsWith("page:")){if(!e.getPage(n))return{ok:!1,reason:"invalidParent"}}else{const t=e.getShape(n);if(!t)return{ok:!1,reason:"invalidParent"};if(t.id===o||e.getDescendantShapeIds(o).includes(t.id))return{ok:!1,reason:"cycle"};if(!e.getShapeUtil(t).canReceiveChildren(t))return{ok:!1,reason:"invalidParent"}}}return ti(e,t,i,r,n)?{ok:!0,movedIds:i}:{ok:!1,reason:"invalidBeforeId"}})(this.editor,e,t)}moveSelectionInParentOrder(e,t="user"){return((e,t,n="user")=>Qn(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}moveSelectionToParentOrderEdge(e,t="user"){return((e,t,n="user")=>Jn(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}isShapeOrAncestorLocked(e){const t=this.editor,n=new Set;let i=t.getShape(e);for(;i;){if(i.isLocked)return!0;if(!i.parentId.startsWith("shape:"))return!1;const e=i.parentId;if(n.has(e))return!1;n.add(e),i=t.getShape(e)}return!1}hasLockedDescendant(e){const t=this.editor;return t.getDescendantShapeIds(e).some(e=>t.getShape(e)?.isLocked??!1)}getOutermostSelectableShapeId(e){const t=this.editor;let n=e,i=t.getShape(e);const r=new Set([e]);for(;i?.parentId.startsWith("shape:");){const e=i.parentId;if(r.has(e))break;r.add(e);const o=t.getShape(e);if(!o)break;t.getShapeUtil(o).shouldTransformDescendants(o)&&(n=o.id),i=o}return n}getShapeIdsIncludingDescendants(e){const t=[],n=new Set;for(const i of e)if(!n.has(i)){n.add(i),t.push(i);for(const e of this.editor.getDescendantShapeIds(i))n.has(e)||(n.add(e),t.push(e))}return t}getShapeIdsForSelectionTransform(e){return this.getShapeIdsForSelectionDescendantTransform(e,e=>this.editor.getShapeUtil(e).shouldTransformDescendants(e))}getShapeIdsForSelectionRotation(e){return this.getShapeIdsForSelectionDescendantTransform(e,e=>this.editor.getShapeUtil(e).shouldRotateDescendants(e))}getSelectionTransformTargetShapes(){return this.getShapeIdsForSelectionTransform(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getSelectionRotationTargetShapes(){return this.getShapeIdsForSelectionRotation(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getShapeExportTraversalIds(e){const t=this.editor,n=this.getShapeIdsIncludingDescendants(e).filter(e=>!t.isShapeHidden(e)),i=new Set(n);for(const r of n)for(const e of t.getBindingsForShape(r)){const r=t.getBindingUtil(e).getExportShapeIds?.(t,e);for(const e of r??[])for(const t of this.getShapeIdsIncludingDescendants([e]))i.has(t)||(i.add(t),n.push(t))}return n}getShapeIdsInContainerBounds(e,t={}){const n=this.editor,i=n.getShapePageId(e),r=n.getShapePageBounds(e);return i&&r?n.getShapeIdsInBounds(r,{pageId:i}).filter(i=>{if(i===e)return!1;const r=n.getShapeContainment(e,i);return"inside"===r||t.includeIntersecting&&"intersecting"===r}):[]}canUseShapeParent(e,t){return ei(this.editor,e,t)}isShapeOrAncestorInSet(e,t){let n=this.editor.getShape(e);const i=new Set;for(;n;){if(t.has(n.id))return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(i.has(e))return!1;i.add(e),n=this.editor.getShape(e)}return!1}isShapeDescendantOf(e,t){let n=this.editor.getShape(e);const i=new Set;for(;n?.parentId.startsWith("shape:");){const e=n.parentId;if(e===t)return!0;if(i.has(e))return!1;i.add(e),n=this.editor.getShape(e)}return!1}getShapeIdsForSelectionDescendantTransform(e,t){const n=this.editor,i=[],r=new Set;for(const o of e){const e=n.getShape(o);if(!e||r.has(e.id)||e.isLocked)continue;const s=t(e);if((!s||!this.hasLockedDescendant(e.id))&&(r.add(e.id),i.push(e.id),s))for(const t of n.getDescendantShapeIds(e.id)){if(r.has(t))continue;const e=n.getShape(t);e&&!e.isLocked&&(r.add(e.id),i.push(e.id))}}return i}},wp=class{bindings=new Map;bindingIds=[];register(e){const t=this.bindingIds.indexOf(e.id);t>=0&&this.bindingIds.splice(t,1);const n=ni(e.shortcut);this.bindingIds.push(e.id),this.bindings.set(e.id,{id:e.id,shortcut:n,target:e.target,label:e.label??ii(n)})}registerActionShortcut(e,t){this.register({id:`action:${e}`,shortcut:t,target:{type:"action",actionId:e}})}registerEditorShortcut(e,t){const n=ni(t);this.register({id:`editor:${e}:${si(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&&ri(n.shortcut,e))return n}return null}getBindingLabel(e){return this.bindings.get(e)?.label}},vp=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:te}),this.retainedBaseShapeWindowSnapshotSignal=a("editor.retainedBaseShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),r=hi(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(t!==Lh&&t&&t.viewportReady&&r.length>0){const e=((e,t)=>{if(e.length!==t.length||0===t.length)return null;const n=t.map((n,i)=>{const r=e[i];if(!r)return null;if(r.end+2<n.start||r.start>n.end+2)return null;const o=i>0?t[i-1]:null,s=i<t.length-1?t[i+1]:null,a=s?s.start-3:1/0,d={start:Math.min(n.start,Math.max(o?o.end+3:-1/0,r.start)),end:Math.max(n.end,Math.min(a,r.end))};return d.end-d.start>n.end-n.start+4?null:d});if(n.some(e=>null===e))return null;const i=n;if(li(i).length!==t.length)return null;const r=ui(t);return ui(i)>r+12?null:i})(li(t.ranges.map(e=>({...e}))),r);if(e)return gi(n,e,{viewportReady:i})}return gi(n,r,{viewportReady:i})},{isEqual:(e,t)=>te(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=a("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:ce}),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:te}),this.selectedShapeIdsOutsideCulledSetSignal=a("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:ce}),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:te}),this.retainedShapeWindowSnapshotSignal=a("editor.retainedShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),r=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,o=(s=r.length)<=0?0:ai(Math.ceil(.5*s),12,96);var s;const a=((e,t,n,i)=>{if(0===e.length)return[];const r=new Map;for(const[a,d]of e.entries())r.set(d,a);const o=li(t.map(e=>r.get(e)).filter(e=>void 0!==e).sort((e,t)=>e-t).map(e=>({start:e,end:e+1})),2),s=[];if(o.length>0){const t=ai(Math.ceil(i/(2*o.length)),8,32);for(const[n,i]of o.entries()){const r=n>0?o[n-1]:null,a=n<o.length-1?o[n+1]:null,d=a?a.start-i.end:1/0,l=ci(r?i.start-r.end:1/0,t),c=ci(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=r.get(a);void 0!==e&&s.push({start:e,end:e+1})}return 0===s.length?[]:li(s,2)})(n,r,this.selectedShapeIdsOutsideCulledSetSignal.get(),o);if(i&&t!==Lh&&t&&t.viewportReady&&t.ranges.length>0&&a.length>0){const e=li(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 gi(n,e,{viewportReady:i});const r=((e,t,n)=>{const i=t.map((n,i)=>{const r={...n};for(const t of e)t.end+6<n.start||t.start>n.end+6||(r.start=Math.min(r.start,t.start),r.end=Math.max(r.end,t.end));const o=i>0?t[i-1]:null,s=i<t.length-1?t[i+1]:null,a=s?s.start-3:1/0;return{start:Math.min(n.start,Math.max(o?o.end+3:-1/0,r.start)),end:Math.max(n.end,Math.min(a,r.end))}});if(li(i).length!==t.length)return null;const r=ui(t);return ui(i)>r+n?null:i})(e,a,o);if(r)return gi(n,r,{viewportReady:i})}return gi(n,a,{viewportReady:i})},{isEqual:(e,t)=>te(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=a("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:te}),this.renderVisibleShapeIdSetSignal=a("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:ce}),this.renderItemsSignal=a("editor.renderItems",()=>{const t=e.selectedShapeIdSetSignal.get(),n=[];for(const i of this.renderVisibleShapeIdsSignal.get()){const r=e.getShapeSignal(i).get(),o=e.queries.getShapePageBoundsSignal(i).get();r&&!r.isHidden&&o&&n.push({id:r.id,shape:r,bounds:o,isSelected:t.has(r.id)})}return n},{isEqual:le}),this.renderHostDebugStateSnapshotSignal=a("editor.renderHostDebugState.snapshot",t=>{const n=this.culledShapeIdsSignal.get(),i=this.renderVisibleShapeIdsSignal.get(),r=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,o=this.retainedShapeIdsSignal.get(),s=this.selectedShapeIdsOutsideCulledSignal.get(),a=this.getPageIndexById(e.currentPageShapeIdsSignal.get()),d=hi(n,a),l=hi(o,a),c=hi(r,a),u=((e,t)=>{if(0===e.length)return{changed:t.length,added:t.length,removed:0};if(0===t.length)return{changed:e.length,added:0,removed:e.length};const n=new Set(e),i=new Set(t);let r=0,o=0;for(const s of i)n.has(s)||(r+=1);for(const s of n)i.has(s)||(o+=1);return{changed:r+o,added:r,removed:o}})(t===Lh?[]:t.retainedShapeIds,o);return{metrics:{culledCount:n.length,visibleCount:i.length,retainedCount:o.length,retainedBaseCount:r.length,culledRangeCount:d.length,culledRangeSpan:ui(d),culledRangesSummary:di(d),retainedBaseRangeCount:c.length,retainedBaseRangeSpan:ui(c),retainedBaseRangesSummary:di(c),retainedRangeCount:l.length,retainedRangeSpan:ui(l),retainedRangesSummary:di(l),retainedChangeCount:u.changed,retainedAddedCount:u.added,retainedRemovedCount:u.removed,selectedOutsideCulledCount:s.length},retainedShapeIds:o.slice()}},{isEqual:(e,t)=>se(e.metrics,t.metrics)}),this.renderHostDebugStateSignal=a("editor.renderHostDebugState.public",()=>this.renderHostDebugStateSnapshotSignal.get().metrics,{isEqual:se})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},Cp=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}},kp=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}},Tp=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}},Bp=class{store;[Gh];inputs=new dp;snapshots=new ap(this);clipboard=new ip(this);shortcuts=new wp;tools=new Cp(this);camera=new tp(this);selection=new yp(this);selectionLayout=new Sp(this);editing=new bp(this);geometry=new Pp(this);hierarchy=new Ip(this);shapeUtils=new Wh;shapeSvgExporters=new jh;bindingUtils=new Uh;interactions=new kp;selectionHandleInteractions=new Tp(this.interactions);queries;bindings;spatialIndex;snaps;renderWindow;selectionOverlay;transients=new lp(this);history;sideEffects=new fp;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;dropTargetShapeIdSignal=this.transients.dropTargetShapeIdSignal;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 U(this)}sessionSignal=a("editor.session",()=>{const e=this._internalStore.getRecordSignal(Kh).get();if(!h(e))throw new Error("Missing session record");return e});currentPageIdSignal=a("editor.currentPageId",()=>this.sessionSignal.get().currentPageId);currentPageShapeIdsSignal;currentPageShapesSignal;culledShapeIdsSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionAnchorPagePointSignal;pagesSignal=a("editor.pages",()=>Array.from(this._internalStore.recordsSignal.get().values()).filter(c).sort((e,t)=>e.index.localeCompare(t.index)));currentPageSignal=a("editor.currentPage",()=>{const e=this.currentPageIdSignal.get();return this.pagesSignal.get().find(t=>t.id===e)??null});pageStateSignal=a("editor.pageState",()=>{const e=this.pagesSignal.get(),t=this.currentPageIdSignal.get(),n=e.find(e=>e.id===t)??null;return{pages:e,currentPageId:t,currentPage:n,canDeleteCurrentPage:e.length>1&&null!==n}});toolStateSignal=a("editor.toolState",()=>{const e=this.sessionSignal.get();return{activeToolId:e.activeToolId,isToolLocked:e.isToolLocked}});editingShapeIdSignal=a("editor.editingShapeId",()=>this.sessionSignal.get().editingShapeId);shapeEditingSessionSignal=a("editor.shapeEditingSession",()=>this.sessionSignal.get().shapeEditingSession);shapeEditingStateSignal=a("editor.shapeEditingState",()=>({editingShapeId:this.editingShapeIdSignal.get(),session:this.shapeEditingSessionSignal.get()}));currentCameraSignal=a("editor.currentCamera",()=>this.sessionSignal.get().pageCameraById[this.currentPageIdSignal.get()]??Xh);selectedShapeIdsSignal=a("editor.selectedShapeIds",()=>{const e=this.sessionSignal.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:te});selectedShapeIdSetSignal=a("editor.selectedShapeIdSet",()=>new Set(this.selectedShapeIdsSignal.get()),{isEqual:ce});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:kn});selectionStateSignal=a("editor.selectionState",()=>{const e=this.selectedShapeIdsSignal.get(),t=1===e.length?this.getShapeSignal(e[0]).get()??null:null,n=this.selectedShapesSignal.get(),i=(e=>{let t=null;for(const n of e)if(null!==t){if(t!==n.type)return null}else t=n.type;return t})(n),r=1===n.length,o=n.map(e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:r,editor:this})).some(e=>e.terminalHandleAnchors.length>0||e.middleHandleAnchors.length>0||(e.customHandleAnchors?.length??0)>0),s=n.some(e=>this.getShapeUtil(e).contributesToSelectionFrame(e,{editor:this})),a=o&&s,d=t?this.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:r,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:o,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 Yh.Scale(e.z,e.z).compose(Yh.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 Hh(n.x,n.y,e/n.z,t/n.z)});renderViewportPageBoundsSignal=a("editor.renderViewportPageBounds",e=>{const t=this.viewportPageBoundsSignal.get();return t?e!==Lh&&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:re});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;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 Qh(this.snapshots.buildInitialRecords(e.documentSnapshot??null,e.sessionSnapshot??null));var n;((e,t)=>{e[Gh]=t})(this,t),this.store=t,this.snapshots.ensureSessionIntegrity(),this.queries=new up(this),this.bindings=new ep(this),this.spatialIndex=new pp(this,this.queries),this.snaps=new mp(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 xp(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 vp(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 Jh(this),this.historyStateSignal=this.history.state,this.commands=(n=this,{createPage:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.createPageRecord(t);let o=r;return U(e).atomic(()=>{const t=V([...e.getPages(),r]);o=t.find(e=>e.id===r.id)??r,U(e).put(t,i),e.ensurePageSessionState(o.id,i)},i),o})(n,e,t),deletePage:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.getPages();if(r.length<=1)return!1;const o=r.findIndex(e=>e.id===t);if(o<0)return!1;const s=e.getShapesForPage(t).map(e=>e.id),a=V(r.filter(e=>e.id!==t)),d=r[o+1]?.id??r[o-1]?.id??r[0]?.id,l=e.getCurrentPageId()===t&&d?d:e.getCurrentPageId();return U(e).atomic(()=>{s.length>0&&Q(e,s,n),U(e).remove([t],i),e.removePageSessionState(t,l,i),U(e).put(a,i)},i),!0})(n,e,t),renamePage(e,t){((e,t,n)=>{const i=n?.source??"user",r=e.getPage(t.id);if(!r)return;const o=t.name.trim();o&&o!==r.name&&U(e).atomic(()=>{U(e).put([{...r,name:o}],i)},i)})(n,e,t)},movePage(e,t){((e,t,n)=>{const i=n?.source??"user",r=e.getPages(),o=r.findIndex(e=>e.id===t.id);if(o<0)return;const s=Math.max(0,Math.min(t.toIndex,r.length-1));if(o===s)return;const a=[...r],[d]=a.splice(o,1);d&&(a.splice(s,0,d),U(e).atomic(()=>{U(e).put(V(a),i)},i))})(n,e,t)},createShapes:(e,t)=>((e,t,n)=>{const i=[],r=n?.source??"user";return U(e).atomic(()=>{const n=t.map(t=>{const n=e.createShapeRecord(t);if("user"!==r||t.parentId)return n;const i=e.getContainingParentIdForShapeRecord(n);return i&&i!==n.parentId?{...n,parentId:i}:n});i.push(...n),U(e).put(n,r)},r),i})(n,e,t),createShapesFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(U(e).atomic(()=>{U(e).put(t,i)},i),t)})(n,e,t),updateShapes(e,t){j(n,e,t)},reparentShapes(e,t){((e,t,n)=>{const i=((e,t)=>{const n=Array.from(new Set(t.ids)).map(t=>e.getShape(t)).filter(e=>!!e&&e.parentId!==t.parentId);if(0===n.length)return[];const i=e.getChildShapes(t.parentId).reduce((e,t)=>{const n=Number.parseInt(t.index,10);return Number.isFinite(n)?Math.max(e,n):e},0);return n.map((n,r)=>({id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+r+1)}))})(e,t);0!==i.length&&j(e,i,n)})(n,e,t)},deleteShapes(e,t){Q(n,e,t)},createAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.createAssetRecord(t);return U(e).atomic(()=>{U(e).put([r],i)},i),r})(n,e,t),createAssetsFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(U(e).atomic(()=>{U(e).put(t,i)},i),t)})(n,e,t),updateAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.getAsset(t.id);if(!r)return null;const o={...r,props:t.props?{...r.props,...t.props}:r.props,meta:t.meta??r.meta};return U(e).atomic(()=>{U(e).put([o],i)},i),o})(n,e,t),deleteAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return!!e.getAsset(t)&&(U(e).atomic(()=>{U(e).remove([t],i)},i),!0)})(n,e,t),createBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.createBindingRecord(t);if(!J(e,r))throw new Error(`Invalid binding endpoints for ${r.type} binding`);return U(e).atomic(()=>{const t=e.bindings.getConflictingBindings(r).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),U(e).put([r],i),e.bindings.syncCreatedBinding(r,i)},i),r})(n,e,t),updateBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.getBinding(t.id);if(!r)return null;const o=e.getBindingUtil(r),s={...r,fromId:t.fromId??r.fromId,toId:t.toId??r.toId,props:t.props?o.validateProps({...r.props,...t.props}):r.props,meta:t.meta??r.meta};if(!J(e,s))throw new Error(`Invalid binding endpoints for ${s.type} binding`);return U(e).atomic(()=>{const t=e.bindings.getConflictingBindings(s).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),U(e).put([s],i),e.bindings.syncUpdatedBinding(r,s,i)},i),s})(n,e,t),deleteBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.getBinding(t);return!!r&&(U(e).atomic(()=>{e.bindings.cleanupBindings([r.id],i),U(e).remove([r.id],i)},i),!0)})(n,e,t),setCurrentPageId(e,t){((e,t,n)=>{e.setCurrentPage(t,n?.source??"system")})(n,e,t)},setCamera(e,t){((e,t,n)=>{e.setCamera(t.camera,{pageId:t.pageId,source:n?.source??"system"})})(n,e,t)},setSelectedShapeIds(e,t){((e,t,n)=>{e.setSelectedShapeIds(t,{source:n?.source??"user"})})(n,e,t)},setActiveTool(e,t){((e,t,n)=>{const i=n?.source??"system";e.completeEditing(i),e.tools.setActiveTool(t),e.updateSession({activeToolId:t},i)})(n,e,t)},setToolLocked(e,t){((e,t,n)=>{const i=n?.source??"system";e.tools.setToolLocked(t),e.updateSession({isToolLocked:t},i)})(n,e,t)}}),this.registerBuiltInShortcuts(),this.registerBuiltInSideEffects()}registerBuiltInShortcuts(){this.shortcuts.registerEditorShortcut("move-selection-backward",{key:"ArrowDown",altKey:!0}),this.shortcuts.registerEditorShortcut("move-selection-forward",{key:"ArrowUp",altKey:!0}),this.shortcuts.registerEditorShortcut("undo",{key:"z",accelKey:!0}),this.shortcuts.registerEditorShortcut("redo",{key:"z",accelKey:!0,shiftKey:!0}),this.shortcuts.registerEditorShortcut("delete-selection","Backspace"),this.shortcuts.registerEditorShortcut("delete-selection","Delete"),this.shortcuts.registerEditorShortcut("reset-interaction","Escape")}registerBuiltInSideEffects(){this.sideEffects.registerBeforeDeleteHandler("shape",(e,t)=>{this.bindings.cleanupBindingsForDeletedShapes(e,t)}),this.sideEffects.registerAfterDeleteHandler("shape",(e,t)=>{this.removeShapeIdsFromSelection(e,t),this.removeShapeIdsFromEditingSession(e,t)})}dispatch(e){const t=this.normalizeEvent(e);if(this.inputs.handleEvent(t),"keyboard"===t.type&&"key_down"===t.name){const e=this.shortcuts.getTargetForEvent(t);if(e&&this.runKeyboardShortcutTarget(e))return}if("wheel"!==t.type)if("cancel"!==t.type)if("pointer"!==t.type||"pointer_cancel"!==t.name){if("handled"!==this.interactions.handleEvent(this,t)&&(this.tools.dispatch(t),"pointer"===t.type&&"pointer_up"===t.name)){const e=this.getDoubleClickEvent(t);e&&"handled"!==this.interactions.handleEvent(this,e)&&this.tools.dispatch(e)}}else this.cancelInteractionAndClearTransients("pointer_cancel");else this.cancelInteractionAndClearTransients(t.reason);else this.handleWheelEvent(t)}handleInteractionEvent(e){const t=this.normalizeEvent(e);return this.inputs.handleEvent(t),"handled"===this.interactions.handleEvent(this,t)}runKeyboardShortcutTarget(e){switch(e.type){case"action":return!1;case"editor":return this.runEditorKeyboardShortcut(e.command);case"tool":return this.commands.setActiveTool(e.toolId,{source:"system"}),!0}}runEditorKeyboardShortcut(e){switch(e){case"delete-selection":return this.deleteSelection("user"),!0;case"move-selection-backward":return this.moveSelectionWithinParent("backward","user");case"move-selection-forward":return this.moveSelectionWithinParent("forward","user");case"redo":return this.redo(),!0;case"reset-interaction":return this.tools.isActiveToolInInitialState()&&"select"!==this.getActiveToolId()?this.commands.setActiveTool("select",{source:"system"}):this.cancelInteractionAndClearTransients("escape"),!0;case"undo":return this.undo(),!0}}normalizeEvent(e){if("pointer"!==e.type)return e;if("pointer_up"===e.name){const t=e.clickCount===this.currentPointerClickCount?e:{...e,clickCount:this.currentPointerClickCount};return this.lastPointerUpForClickCount={timestamp:t.timestamp,screenPoint:t.screenPoint.clone()},t}if("pointer_down"!==e.name)return e;const t=this.lastPointerDownForClickCount,n=this.lastPointerUpForClickCount,i=t&&n&&n.timestamp>=t.timestamp&&e.timestamp-n.timestamp<=250&&n.screenPoint.dist2(e.screenPoint)<=1600?2:1;return this.lastPointerDownForClickCount={timestamp:e.timestamp,screenPoint:e.screenPoint.clone()},this.currentPointerClickCount=i,e.clickCount===i?e:{...e,clickCount:i}}getDoubleClickEvent(e){return(e.clickCount??1)<2||this.currentPointerClickCount<2?null:{type:"click",name:"double_click",phase:"up",timestamp:e.timestamp,pointerId:e.pointerId,button:e.button,buttons:e.buttons,pointerType:e.pointerType,screenPoint:e.screenPoint.clone(),pagePoint:e.pagePoint.clone(),pressure:e.pressure,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}listen(e){return this.store.listen(t=>e(t))}getRenderItems(){return this.renderItemsSignal.get()}getPages(){return this.pagesSignal.get()}getCurrentPageId(){return this.currentPageIdSignal.get()}getActiveToolId(){return this.sessionSignal.get().activeToolId}isToolLocked(){return this.sessionSignal.get().isToolLocked}isActiveToolInInitialState(){return this.tools.isActiveToolInInitialState()}getEditingShapeId(){return this.editingShapeIdSignal.get()}getShapeEditingSession(){return this.shapeEditingSessionSignal.get()}getShapeEditingEntryRequest(){return this.shapeEditingEntryRequestSignal.get()}resetPointerClickTracking(){this.lastPointerDownForClickCount=null,this.lastPointerUpForClickCount=null,this.currentPointerClickCount=1}getCurrentPageShapeIds(){return this.currentPageShapeIdsSignal.get()}getPage(e){const t=this._internalStore.get(e);return c(t)?t:void 0}getCurrentCamera(){return this.camera.getCurrentCamera()}undo(){return this.cancelInteractionForCommand(),this.history.undo()}redo(){return this.cancelInteractionForCommand(),this.history.redo()}createPageAndSelect(e,t="user"){const n=this.commands.createPage(e,{source:t});return this.commands.setCurrentPageId(n.id,{source:t}),n}selectPage(e,t="user"){this.commands.setCurrentPageId(e,{source:t})}renamePage(e,t,n="user"){this.commands.renamePage({id:e,name:t},{source:n})}deletePage(e,t="user"){return this.cancelInteractionForCommand(),this.commands.deletePage(e,{source:t})}setActiveTool(e,t="system"){this.commands.setActiveTool(e,{source:t})}setToolLocked(e,t="system"){this.commands.setToolLocked(e,{source:t})}toggleToolLocked(e="system"){this.setToolLocked(!this.isToolLocked(),e)}getCamera(e=this.getCurrentPageId()){return this.camera.getCamera(e)}pageToScreen(e,t=this.getCurrentPageId()){return this.camera.pageToScreen(e,t)}screenToPage(e,t=this.getCurrentPageId()){return this.camera.screenToPage(e,t)}getSelectedShapeIds(e=this.getCurrentPageId()){return e===this.getCurrentPageId()?this.selectedShapeIdsSignal.get():this.sessionSignal.get().pageSelectedShapeIdsById[e]??[]}isShapeHidden(e){const t=new Set;let n=this.getShape(e);for(;n;){if(n.isHidden)return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(t.has(e))return!1;t.add(e),n=this.getShape(e)}return!1}getSelectedShapes(){return this.selectedShapesSignal.get()}getDefaultShapeProps(e){const t=this.shapeUtils.get(e),n=this._shapeDefaultPropsByTypeSignal.get().get(e)??{};return t.validateProps({...t.getDefaultProps(),...n})}updateDefaultShapeProps(e,t){const n=this.shapeUtils.get(e),i=this._shapeDefaultPropsByTypeSignal.get().get(e)??{},r=n.validateProps({...n.getDefaultProps(),...i,...t}),o=n.validateProps(n.getDefaultProps()),s={};for(const[d,l]of Object.entries(r))o[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[r,o]of n)if(!he(o,t[r]))return!1;return!0})(i,s))return;const a=new Map(this._shapeDefaultPropsByTypeSignal.get());0===Object.keys(s).length?a.delete(e):a.set(e,s),this._shapeDefaultPropsByTypeSignal.set(a)}getSelectionParentOrderState(){return this.hierarchy.getSelectionParentOrderState()}getSelectionGroupState(){return this.hierarchy.getSelectionGroupState()}canGroupSelection(){return this.hierarchy.canGroupSelection()}canGroupShapes(e){return this.hierarchy.canGroupShapes(e)}groupShapes(e,t="user"){return this.hierarchy.groupShapes(e,t)}groupSelection(e="user"){return this.hierarchy.groupSelection(e)}getUngroupableSelectedShapeIds(){return this.hierarchy.getUngroupableSelectedShapeIds()}getUngroupableShapeIds(e){return this.hierarchy.getUngroupableShapeIds(e)}canUngroupSelection(){return this.hierarchy.canUngroupSelection()}canUngroupShapes(e){return this.hierarchy.canUngroupShapes(e)}ungroupShapes(e,t="user"){return this.hierarchy.ungroupShapes(e,t)}ungroupSelection(e="user"){return this.hierarchy.ungroupSelection(e)}getSelectionSiblingOrderState(){return this.hierarchy.getSelectionSiblingOrderState()}canMoveSelectionWithinParent(e){return this.hierarchy.canMoveSelectionWithinParent(e)}canMoveSelectionInParentOrder(e){return this.hierarchy.canMoveSelectionInParentOrder(e)}canMoveShapesInParentOrder(e,t){return this.hierarchy.canMoveShapesInParentOrder(e,t)}moveShapesInParentOrder(e,t,n="user"){return this.hierarchy.moveShapesInParentOrder(e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return this.hierarchy.moveShapesToParentOrderEdge(e,t,n)}moveSelectionWithinParent(e,t="user"){return this.hierarchy.moveSelectionWithinParent(e,t)}alignSelection(e,t="user"){return this.cancelInteractionForCommand(),this.selectionLayout.align(e,t)}distributeSelection(e,t="user"){return this.cancelInteractionForCommand(),this.selectionLayout.distribute(e,t)}moveShapesToParentPlacement(e,t="user"){return this.hierarchy.moveShapesToParentPlacement(e,t)}moveShapesToParentPlacementResult(e,t="user"){return this.hierarchy.moveShapesToParentPlacementResult(e,t)}moveSelectionInParentOrder(e,t="user"){return this.hierarchy.moveSelectionInParentOrder(e,t)}moveSelectionToParentOrderEdge(e,t="user"){return this.hierarchy.moveSelectionToParentOrderEdge(e,t)}canEditShape(e){return this.editing.canEditShape(e)}startEditingShape(e,t="user"){return this.editing.start(e,t)}completeEditing(e="user"){return this.editing.complete(e)}cancelEditing(e="user"){return this.editing.cancel(e)}setShapeEditingComposition(e,t="system"){this.editing.setComposition(e,t)}consumeShapeEditingEntryRequest(e){this.editing.consumeEntryRequest(e)}deleteSelection(e="user"){this.deleteShapesById(this.getSelectedShapeIds(),e)}deleteShapesById(e,t="user"){const n=Array.from(new Set(e));0!==n.length&&(this.cancelInteractionForCommand(),this.commands.deleteShapes(n,{source:t}))}setShapesHidden(e,t,n="user"){const i=Array.from(new Set(e.filter(e=>{const n=this.getShape(e);return!!n&&n.isHidden!==t})));return 0===i.length?[]:(this.cancelInteractionForCommand(),this.commands.updateShapes(i.map(e=>({id:e,isHidden:t})),{source:n}),t&&(this.removeShapeIdsFromSelection(this.getShapeIdsIncludingDescendants(i),n),this.removeShapeIdsFromEditingSession(this.getShapeIdsIncludingDescendants(i),n)),i)}setShapesLocked(e,t,n="user"){const i=Array.from(new Set(e.filter(e=>{const n=this.getShape(e);return!!n&&n.isLocked!==t})));return 0===i.length?[]:(this.cancelInteractionForCommand(),this.commands.updateShapes(i.map(e=>({id:e,isLocked:t})),{source:n}),t&&(this.removeShapeIdsFromSelection(this.getShapeIdsIncludingDescendants(i),n),this.removeShapeIdsFromEditingSession(this.getShapeIdsIncludingDescendants(i),n)),i)}createClipboardPayloadFromSelection(){return this.clipboard.createPayloadFromSelection()}pasteClipboardPayload(e){return this.clipboard.pastePayload(e)}duplicateSelection(e={}){return this.clipboard.duplicateSelection(e)}selectAllCurrentPage(e="user"){this.cancelInteractionForCommand(),this.selection.selectAllCurrentPage(e)}resetSelectionRotation(e="user"){((e,t="user")=>{const n=e.getSelectedShapes().filter(t=>e.getShapeUtil(t).contributesToSelectionFrame(t,{editor:e}));0!==n.length&&e.commands.updateShapes(n.map(e=>({id:e.id,rotation:0})),{source:t})})(this,e)}flipSelection(e,t="user"){const n=function(e,t){const n=e.getSelectionTransformTargetShapes(),i=e.getSelectionFrame()??((e,t)=>{const n=t.flatMap(t=>e.getShapeUtil(t).getSelectionPagePoints(t)??[]);if(0===n.length)return null;const i=Hh.FromPoints(n);return{bounds:i,rotation:0,rotationCenter:i.center,hasCompatibleRotation:!0}})(e,n);return i&&0!==n.length?n.map(n=>((e,t,n,i)=>{const r=e.getShapeUtil(t),o=r.getSelectionPagePoints(t);if(!o&&!r.contributesToSelectionFrame(t,{editor:e}))return null;const s=(({points:e,transform:t})=>0===e.length?null:Hh.FromPoints(e.map(e=>mn(e,t))))({points:o?[...o]:r.getPositionedOutlineVertices(t).map(n=>e.computeShapePositionedToPageTransform(t).applyToPoint(n)),transform:n});return s?r.flipSelectionBounds(t,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:Pn({axis:i,bounds:s,selectionBounds:n.bounds}),selectionRotation:n.rotation,selectionRotationCenter:n.rotationCenter}):null})(e,n,i,t)).filter(e=>null!==e):[]}(this,e);0!==n.length&&(this.cancelInteractionForCommand(),this.commands.updateShapes(n,{source:t}))}getShape(e){const t=this._internalStore.get(e);return u(t)?t:void 0}getAsset(e){const t=this._internalStore.get(e);return g(t)?t:void 0}getAssets(){return this._internalStore.getAll().filter(g).sort((e,t)=>e.id.localeCompare(t.id))}resolveAssetUrl(e){return this.assetUrlResolver(e)}getUnreferencedAssetIdsAfterShapeDelete(e){if(0===e.length)return[];const t=new Set(e),n=new Set,i=new Set;for(const r of this._internalStore.getAll().filter(u)){const e=ue(r);e&&(t.has(r.id)?n.add(e):i.add(e))}return this.getAssets().map(e=>e.id).filter(e=>n.has(e)&&!i.has(e))}getShapeSignal(e){let t=this.shapeSignals.get(e);return t||(t=a(`editor.shape.${e}`,()=>{const t=this._internalStore.getRecordSignal(e).get();return u(t)?t:void 0}),this.shapeSignals.set(e,t)),t}getShapeSelectedSignal(e){let t=this.shapeSelectedSignals.get(e);return t||(t=a(`editor.shapeSelected.${e}`,()=>this.selectedShapeIdSetSignal.get().has(e)),this.shapeSelectedSignals.set(e,t)),t}getShapeRenderOrderSignal(e){let t=this.shapeRenderOrderSignals.get(e);return t||(t=a(`editor.shapeRenderOrder.${e}`,()=>this.shapeRenderOrderByIdSignal.get().get(e)??-1),this.shapeRenderOrderSignals.set(e,t)),t}getShapeRenderVisibleSignal(e){let t=this.shapeRenderVisibleSignals.get(e);return t||(t=a(`editor.shapeRenderVisible.${e}`,()=>{const t=this.getShapeClipAncestorIdsSignal(e).get().length>0;return this.renderVisibleShapeIdSetSignal.get().has(e)&&!this.isShapeHidden(e)&&(!t||null!==this.getShapeClippedPageBounds(e))}),this.shapeRenderVisibleSignals.set(e,t)),t}getShapeDocumentVisibleSignal(e){let t=this.shapeDocumentVisibleSignals.get(e);return t||(t=a(`editor.shapeDocumentVisible.${e}`,()=>{const t=this.getShapeSignal(e).get();return!!t&&!this.isShapeHidden(t.id)}),this.shapeDocumentVisibleSignals.set(e,t)),t}getShapeEditingSessionForShapeSignal(e){let t=this.shapeEditingSessionSignals.get(e);return t||(t=a(`editor.shapeEditingSessionForShape.${e}`,()=>{const t=this.shapeEditingSessionSignal.get();return t?.shapeId===e?t:null}),this.shapeEditingSessionSignals.set(e,t)),t}getShapeDropTargetSignal(e){let t=this.shapeDropTargetSignals.get(e);return t||(t=a(`editor.shapeDropTarget.${e}`,()=>this.dropTargetShapeIdSignal.get()===e),this.shapeDropTargetSignals.set(e,t)),t}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).shouldTransformDescendants(t))&&this.selectedShapeIdsSignal.get().some(t=>this.hierarchy.isShapeDescendantOf(t,e))}),this.shapeSelectedDescendantTransformAncestorSignals.set(e,t)),t}getBinding(e){const t=this._internalStore.get(e);return p(t)?t:void 0}getShapesForPage(e){return this.queries.getShapesForPage(e)}getBindingsFromShape(e){return this.queries.getBindingsFromShape(e)}getBindingsToShape(e){return this.queries.getBindingsToShape(e)}getBindingsForShape(e){return this.queries.getBindingsForShape(e)}getChildShapeIds(e){return this.queries.getChildShapeIds(e)}getChildShapes(e){return this.queries.getChildShapes(e)}getDescendantShapeIds(e){return this.queries.getDescendantShapeIds(e)}getDescendantPageBounds(e){return this.queries.getDescendantPageBounds(e)}getShapeSubtreePageBounds(e){return this.queries.getShapeSubtreePageBounds(e)}getShapePageId(e){return this.queries.getPageIdForShape(e)}isShapeOrAncestorLocked(e){return this.hierarchy.isShapeOrAncestorLocked(e)}hasLockedDescendant(e){return this.hierarchy.hasLockedDescendant(e)}getOutermostSelectableShapeId(e){return this.hierarchy.getOutermostSelectableShapeId(e)}getShapeIdsIncludingDescendants(e){return this.hierarchy.getShapeIdsIncludingDescendants(e)}getShapeIdsForSelectionTransform(e){return this.hierarchy.getShapeIdsForSelectionTransform(e)}getShapeIdsForSelectionRotation(e){return this.hierarchy.getShapeIdsForSelectionRotation(e)}getSelectionTransformTargetShapes(){return this.hierarchy.getSelectionTransformTargetShapes()}getSelectionRotationTargetShapes(){return this.hierarchy.getSelectionRotationTargetShapes()}getShapeExportTraversalIds(e){return this.hierarchy.getShapeExportTraversalIds(e)}getShapeContainment(e,t){return this.queries.getShapeContainment(e,t)}getContainingShapeParentId(e){return this.queries.getContainingShapeParentId(e)}getContainingShapeParentIdAtPoint(e,t){return this.queries.getContainingShapeParentIdAtPoint(e,t)}getContainingParentIdForShapeRecord(e){return this.queries.getContainingParentIdForShapeRecord(e)}getShapeClipAncestorIds(e){return this.queries.getShapeClipAncestorIds(e)}getShapeClipAncestorIdsSignal(e){return this.queries.getShapeClipAncestorIdsSignal(e)}isPagePointInShapeClip(e,t){return this.queries.isPagePointInShapeClip(e,t)}getShapeClippedPageBounds(e){return this.queries.getShapeClippedPageBounds(e)}getShapeIdsInContainerBounds(e,t={}){return this.hierarchy.getShapeIdsInContainerBounds(e,t)}canUseShapeParent(e,t){return this.hierarchy.canUseShapeParent(e,t)}getShapeUtil(e){return this.shapeUtils.get(e.type)}getBindingUtil(e){return this.bindingUtils.get(e.type)}computeShapeBounds(e){return this.geometry.computeShapeBounds(e)}computeShapeLocalBounds(e){return this.geometry.computeShapeLocalBounds(e)}computeShapeRenderBounds(e){return this.geometry.computeShapeRenderBounds(e)}computeShapeExportBounds(e){return this.geometry.computeShapeExportBounds(e)}computeShapeLocalToPageTransform(e){return this.geometry.computeShapeLocalToPageTransform(e)}computeShapeRenderToPageTransform(e){return this.geometry.computeShapeRenderToPageTransform(e)}computeShapeExportToPageTransform(e){return this.geometry.computeShapeExportToPageTransform(e)}computeShapePageBounds(e){return this.geometry.computeShapePageBounds(e)}computeShapeExportPageBounds(e){return this.geometry.computeShapeExportPageBounds(e)}computeShapeGeometry(e){return this.geometry.computeShapeGeometry(e)}computeShapePositionedToPageTransform(e){return this.geometry.computeShapePositionedToPageTransform(e)}computeShapePageCenter(e){return this.geometry.computeShapePageCenter(e)}computeShapePageCorners(e){return this.geometry.computeShapePageCorners(e)}computeShapePageOutlineVertices(e){return this.geometry.computeShapePageOutlineVertices(e)}getShapeBounds(e){return this.geometry.getShapeBounds(e)}getShapePageBounds(e){return this.geometry.getShapePageBounds(e)}getShapeGeometry(e){return this.geometry.getShapeGeometry(e)}getShapePositionedToPageTransform(e){return this.geometry.getShapePositionedToPageTransform(e)}getShapePageCenter(e){return this.geometry.getShapePageCenter(e)}getShapePageCorners(e){return this.geometry.getShapePageCorners(e)}getShapePageOutlineVertices(e){return this.geometry.getShapePageOutlineVertices(e)}getSelectionPageBounds(){return this.geometry.getSelectionPageBounds()}getSelectionFrame(){return this.geometry.getSelectionFrame()}isPointInSelectionBounds(e){return this.geometry.isPointInSelectionBounds(e)}getSelectionFrameLocalBoundsPoint(e){return this.geometry.getSelectionFrameLocalBoundsPoint(e)}getSelectionPageOutlineVertices(){return this.geometry.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.geometry.getSelectionAnchorPagePoint()}hitTestSelectionHandle(e){const t=this.selectedShapesSignal.get(),n=this.getSelectionFrame();if(0===t.length)return null;const i=1===t.length,{terminalHandles:r,middleHandles:o,customHandles:s,rotateHandles:a,resizeHandles:d}=((e,t,n,i,r)=>qn(Vn(e,t,n,i,r),n))(t,n,this.getCurrentCamera().z,e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:i,editor:this}),e=>this.getShapeUtil(e).canUseSelectionFrameHandles(e,{editor:this}));for(const l of o)if(l.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return l;for(const l of r)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)}setDropTargetShapeId(e){this.transients.setDropTargetShapeId(e)}setSelectionTranslationActive(e){this.transients.setSelectionTranslationActive(e)}setSnapIndicators(e){this.transients.setSnapIndicators(e)}setTerminalBindingResolver(e){this.transients.setTerminalBindingResolver(e)}resolveTerminalBinding(e){return this.transients.resolveTerminalBinding(e)}clearSelectionTransients(){this.transients.clearSelectionTransients()}hitTestShape(e){return this.hitTestShapesAtPoint(e)[0]??null}hitTestShapesAtPoint(e,t){return this.spatialIndex.getShapesAtPoint(e,{...t,filter:n=>!this.isShapeHidden(n.id)&&this.isPagePointInShapeClip(n.id,e)&&(t?.filter?.(n)??!0)})}hitTestShapesByLineSegment(e,t,n){return this.spatialIndex.getShapesHitByLineSegment(e,t,{...n,filter:e=>!this.isShapeHidden(e.id)&&(n?.filter?.(e)??!0)})}getShapeIdsInBounds(e,t){return this.spatialIndex.getShapeIdsInBounds(e,t).filter(e=>!this.isShapeHidden(e))}getShapesInBounds(e,t){return this.spatialIndex.getShapesInBounds(e,t).filter(e=>!this.isShapeHidden(e.id))}getShapesInViewport(e,t){return this.spatialIndex.getShapesInViewport(e,t).filter(e=>!this.isShapeHidden(e.id))}getDocumentSnapshot(){return this.snapshots.getDocumentSnapshot()}getSessionSnapshot(){return this.snapshots.getSessionSnapshot()}getSvgString(e=this.getSelectedShapeIds(),t){return function(e,t,n,i={}){const r=Array.from(t),o=e.getShapeExportTraversalIds(r),s=new Set(o),a=[],d=[];for(const x of o){const t=e.getShape(x);t?d.push(t):a.push({id:x,reason:"missing-shape"})}if(0===d.length)return null;const l=[];for(const x of d){const t=T(e,x,s);t&&(L(t)?l.push(t):a.push({id:x.id,reason:"missing-bounds"}))}if(0===l.length)return null;const c=(e=>{let t=1/0,n=1/0,i=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.minX),n=Math.min(n,o.minY),i=Math.max(i,o.maxX),r=Math.max(r,o.maxY);return new Hh(t,n,i-t,r-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=>v(e,i.resolveThemeColor)},p=[],g=[],m=new Map;for(const x of d){const t=n.get(x.type);if(!t){a.push({id:x.id,reason:"missing-exporter"});continue}const i=t.toSvg(x,h);if(!i){a.push({id:x.id,reason:"empty-output"});continue}if(!L(e.computeShapeExportBounds(x))){a.push({id:x.id,reason:"missing-bounds"});continue}const r=e.computeShapeExportToPageTransform(x);p.push(x.id);const o=B(e,x,s,m,h);let d={tag:"g",attrs:{transform:r.toSvgString(),opacity:1===x.opacity?void 0:x.opacity},children:[i]};for(let e=o.length-1;e>=0;e-=1)d={tag:"g",attrs:{"clip-path":`url(#${o[e]})`},children:[d]};g.push(d)}if(0===p.length)return null;const f=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:F({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:f,height:S,viewBox:`${D(c.x)} ${D(c.y)} ${D(f)} ${D(S)}`},children:y}),bounds:c,width:f,height:S,requestedShapeIds:r,exportedShapeIds:p,skippedShapes:a}}(this,e,this.shapeSvgExporters,t)}getExportIntegrityReport(e=this.getSelectedShapeIds()){return z({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}repairExportIntegrity(e=this.getSelectedShapeIds()){return(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),r=z({editor:e,exporters:t,shapeIds:i});r.repairableIssueCount>0&&e.bindings.repairLoadedBindings("system");const o=z({editor:e,exporters:t,shapeIds:i});return{before:r,after:o,repaired:r.issues.length!==o.issues.length}})({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}getShapeCapabilityManifest(){return(({definitions:e,exporters:t,shapeUtils:n})=>{const i=e.map(e=>{const i=n.has(e.type)?"supported":"missing",r=t.has(e.type)?"supported":"missing",o="supported"===i&&"supported"===r?"supported":"missing";return{...e,shapeUtil:i,svgExporter:r,exportSupport:o}});return{entries:i,supportedExportTypes:i.filter(e=>"supported"===e.exportSupport).map(e=>e.type),missingExporterTypes:i.filter(e=>"supported"!==e.svgExporter).map(e=>e.type)}})({definitions:this.shapeCapabilityDefinitions,exporters:this.shapeSvgExporters,shapeUtils:this.shapeUtils})}createPageRecord(e){const t=this.nextPageNumber;return{id:this.createPageId(t),typeName:"page",scope:"document",name:e?.name??`Page ${t}`,index:e?.index??this.createPageIndex(t),meta:e?.meta??{}}}loadDocumentSnapshot(e,t){this.snapshots.loadDocumentSnapshot(e,t)}loadSessionSnapshot(e,t){this.snapshots.loadSessionSnapshot(e,t)}syncAfterDocumentRestore(){this.snapshots.syncAfterDocumentRestore()}cancelInteractionForCommand(){this.cancelInteractionAndClearTransients("command")}cancelInteractionAndClearTransients(e){this.tools.cancel(e),this.inputs.resetPointer(),this.clearSelectionTransients()}syncToolStateFromSession(e){const{activeToolId:t,isToolLocked:n}=this.sessionSignal.get();this.tools.hasTool(t)?this.tools.setActiveTool(t,"restore"):(this.tools.setActiveTool("select","restore"),this.updateSession({activeToolId:"select"},e)),this.tools.setToolLocked(n)}createShapeRecord(e){const t=e.parentId??this.sessionSignal.get().currentPageId;if(!this.canUseShapeParent(t))throw new Error("Invalid parent id for shape");const n=this.nextShapeNumber,i=this.createShapeId(n),r=this.shapeUtils.get(e.type).validateProps({...this.getDefaultShapeProps(e.type),...e.props});return{id:i,typeName:"shape",scope:"document",type:e.type,parentId:t,index:e.index??this.createShapeIndex(n),x:e.x,y:e.y,rotation:e.rotation??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,opacity:e.opacity??1,isHidden:e.isHidden??!1,isLocked:e.isLocked??!1,props:r,meta:e.meta??{}}}createBindingRecord(e){const t=e.id??this.createBindingId(this.nextBindingNumber),n=this.bindingUtils.get(e.type),i=n.validateProps({...n.getDefaultProps(),...e.props});return{id:t,typeName:"binding",scope:"document",type:e.type,fromId:e.fromId,toId:e.toId,props:i,meta:e.meta??{}}}createAssetRecord(e){return{id:e.id??this.createAssetId(this.nextAssetNumber),typeName:"asset",scope:"document",type:e.type,props:e.props??{},meta:e.meta??{}}}updateSession(e,t="system"){const n=this.sessionSignal.get();this._internalStore.put([{...n,...e}],t)}setCurrentPage(e,t="system"){if(!this.getPage(e))return;e!==this.getCurrentPageId()&&(this.cancelInteractionAndClearTransients("page_switch"),this.completeEditing(t));const n=this.sessionSignal.get();this.updateSession({currentPageId:e,pageCameraById:{...n.pageCameraById,[e]:n.pageCameraById[e]??{...Xh}},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]??{...Xh},r=n.pageSelectedShapeIdsById[e]??[];this.updateSession({pageCameraById:{...n.pageCameraById,[e]:i},pageSelectedShapeIdsById:{...n.pageSelectedShapeIdsById,[e]:r}},t)}removePageSessionState(e,t,n="system"){const i=this.sessionSignal.get(),r={...i.pageCameraById},o={...i.pageSelectedShapeIdsById};delete r[e],delete o[e],this.updateSession({currentPageId:t,pageCameraById:r,pageSelectedShapeIdsById:o},n)}setCamera(e,t){this.camera.setCamera(e,t)}panCamera(e,t="system"){this.camera.panCamera(e,t)}zoomCameraAtScreenPoint(e,t,n="system"){this.camera.zoomCameraAtScreenPoint(e,t,n)}zoomCameraToScreenPoint(e,t,n="system"){this.camera.zoomCameraToScreenPoint(e,t,n)}zoomAtViewportCenter(e,t="system"){this.camera.zoomAtViewportCenter(e,t)}resetZoom(e="user"){this.camera.resetZoom(e)}setViewportScreenSize(e){this.camera.setViewportScreenSize(e)}getCurrentPageBounds(e=this.getCurrentPageId()){return this.selectionLayout.getCurrentPageBounds(e)}zoomToBounds(e,t){return this.selectionLayout.zoomToBounds(e,t)}zoomToFit(e){return this.selectionLayout.zoomToFit(e)}zoomToSelection(e){return this.selectionLayout.zoomToSelection(e)}createShapeId(e){const t=`shape:${e}`;return this.nextShapeNumber+=1,t}createShapeIndex(e){return String(e).padStart(6,"0")}createBindingId(e){const t=`binding:${e}`;return this.nextBindingNumber+=1,t}createAssetId(e){const t=`asset:${e}`;return this.nextAssetNumber+=1,t}syncShapeCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!u(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextShapeNumber=e+1}syncPageCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!c(t))continue;const n=t.id.split(":")[1]??"",i=Number("default"===n?1:n);Number.isFinite(i)&&(e=Math.max(e,i))}this.nextPageNumber=e+1}syncBindingCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!p(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextBindingNumber=e+1}syncAssetCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!g(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextAssetNumber=e+1}createPageId(e){const t=`page:${e}`;return this.nextPageNumber+=1,t}createPageIndex(e){return String(e).padStart(4,"0")}handleWheelEvent(e){if(e.ctrlKey){const t=this.getCurrentCamera(),n=e.delta.y,i=(Math.abs(n)>10?10*Math.sign(n):n)/100;return void this.zoomCameraToScreenPoint(e.screenPoint,t.z-1*i*t.z)}this.panCamera(e.delta)}},Mp=class{getLocalBounds(e){const t=this.getBounds(e);return new Hh(t.x-e.x,t.y-e.y,t.w,t.h)}getRenderBounds(e){return this.getLocalBounds(e)}getPointHitTestBounds(e,t){return this.getBounds(e)}getExportBounds(e){return this.getRenderBounds(e)}getChildClipLocalBounds(e){return null}getChildExportClipLocalBounds(e){return this.getChildClipLocalBounds(e)}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=this.getSelectionResizeLocalBounds(e);if(0!==n.x||0!==n.y)throw new Error(`Shape util "${this.type}" must implement resizeSelectionBounds for non-origin local bounds`);const i=t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,r=this.validateProps({...e.props,w:t.selectionLocalBounds.w,h:t.selectionLocalBounds.h}),o=wi(r,"w",t.selectionLocalBounds.w),s=wi(r,"h",t.selectionLocalBounds.h),a=fn(Rt({requestedBounds:t.selectionLocalBounds,handleId:t.handleId,actualWidth:o,actualHeight:s,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,{rotation:t.selectionRotation,rotationCenter:t.selectionRotationCenter});return{id:e.id,x:a.x-o/2,y:a.y-s/2,rotation:i,scaleX:t.scaleX<0?-e.scaleX:e.scaleX,scaleY:t.scaleY<0?-e.scaleY:e.scaleY,props:r}}getSelectionResizeAspectRatioLock(e,t){return null}flipSelectionBounds(e,t){const n=this.getSelectionPagePoints(e);if(n){const i=n.map(e=>{const n=0===t.selectionRotation?e.clone():zh.RotWith(e,t.selectionRotationCenter,-t.selectionRotation),i=bn({axis:t.axis,bounds:t.selectionBounds,point:n});return 0===t.selectionRotation?i:zh.RotWith(i,t.selectionRotationCenter,t.selectionRotation)});return this.updateSelectionPagePoints(e,{pagePoints:[i[0],i[1]]})}const i=this.getSelectionResizeLocalBounds(e),r=0===t.selectionRotation?t.selectionLocalBounds.center:zh.RotWith(t.selectionLocalBounds.center,t.selectionRotationCenter,t.selectionRotation);return{id:e.id,x:r.x-i.center.x,y:r.y-i.center.y,rotation:2*t.selectionRotation-e.rotation,scaleX:"horizontal"===t.axis?-e.scaleX:e.scaleX,scaleY:"vertical"===t.axis?-e.scaleY:e.scaleY}}updateSelectionPagePoints(e,t){throw new Error(`Shape util "${this.type}" must implement updateSelectionPagePoints before selection can transform point-defined geometry`)}getSelectionPagePoints(e){return null}contributesToSelectionFrame(e,t){return!0}canUseSelectionFrameHandles(e,t){return!0}getSelectionTargetId(e,t){return e.id}getTranslateTargetId(e,t){return e.id}shouldTransformDescendants(e){return!1}shouldRotateDescendants(e){return this.shouldTransformDescendants(e)}canStartTranslateFromSelectionBounds(e){return!0}canSnap(e){return!0}getBoundsSnapGeometry(e){return{}}getHandleSnapGeometry(e){return{outline:Pi(this.getLocalBounds(e))}}getPositionedOutlineVertices(e){const t=this.getBounds(e);return[new zh(t.minX,t.minY),new zh(t.maxX,t.minY),new zh(t.maxX,t.maxY),new zh(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 Yh.Translate(e.x+t.x,e.y+t.y).compose(Yh.Rotate(e.rotation)).compose(Yh.Scale(e.scaleX,e.scaleY)).compose(Yh.Translate(-t.x,-t.y))}canEdit(e){return!1}canReceiveChildren(e){return!1}repairLoadedShape(e){return null}onEditEnd(e){}hitTest(e,t,n){return this.getBounds(e).containsPoint(t)}hitTestLineSegment(e,t){return((e,t,n)=>{if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=Pi(n);for(let r=0;r<i.length;r+=1){const n=i[r],o=i[(r+1)%i.length];if(n&&o&&null!==Ii(e,t,n,o))return!0}return!1})(t.positionedStart,t.positionedEnd,this.getBounds(e).expand(t.margin))}resolveBindingPoint(e,t){return t.rawPagePoint}},Ep=class{},Ap=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)}},Rp=class extends Ap{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new Fp(e,this)),this.addChild(new Lp(e,this))}},Fp=class extends Ap{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",{originScreenPoint:e.screenPoint.clone(),originCamera:this.editor.getCurrentCamera()})}},Lp=class extends Ap{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}},$p=Math.PI/180*15,Dp=Math.PI/2,Up=Math.PI/180*5,zp="select.translate",Hp="select.resize",Yp="select.rotate",Op=class extends Ap{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},Kp=class extends Op{onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&this.onDragThresholdExceeded(e)}},Xp=class extends Op{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=ki(this.editor,e,this.tickMode);t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Ti(this.editor,e=>this.apply(e))}},Wp=class extends Op{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,Ai(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,Ei(e),Ai(e))}onTick(e){if(!this.info)return;const t=ki(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,Ei(t),Ai(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,Ei(e),Ai(e)),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}updateBrush(e,t,n){if(!this.info)return;const i=((e,t)=>{const n=Math.min(e.x,t.x),i=Math.min(e.y,t.y),r=Math.max(e.x,t.x),o=Math.max(e.y,t.y);return new Hh(n,i,r-n,o-i)})(this.info.originPagePoint,e),r=((e,t)=>{const n=[],i=new Set;for(const r of t){const t=e.getOutermostSelectableShapeId(r);i.has(t)||(i.add(t),n.push(t))}return n})(this.editor,this.editor.getShapeIdsInBounds(i).filter(e=>((e,t,n,i)=>{const r=e.getShape(n);return!(!r||!((e,t)=>{const n=e.getShape(t);return!!n&&!e.getShapeUtil(n).shouldTransformDescendants(n)})(e,r.id))&&e.getShapeUtil(r).canSelectByBrush(r,{brushBounds:t,isWrapping:i,pageOutlineVertices:e.getShapePageOutlineVertices(r.id),pageBounds:e.getShapePageBounds(r.id)})})(this.editor,i,e,n))),o=t?((e,t)=>{const n=new Set(e);for(const i of t)n.has(i)?n.delete(i):n.add(i);return Array.from(n)})(this.info.previousSelection,r):r;this.editor.setBrushBox(i),this.editor.commands.setSelectedShapeIds(o,{source:"system"})}updateBrushFromInputs(){Ti(this.editor,e=>this.updateBrush(e.pagePoint,Ei(e),Ai(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},Np=class extends Xp{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(Ah)return void e();const t={initialAtomValues:new Map};Ah=t;try{e(),o(t.initialAtomValues.keys())}catch(n){for(const[e,i]of t.initialAtomValues)e.__unsafe__setWithoutNotify(i);throw n}finally{Ah=null}})(()=>{e&&this.editor.commands.setSelectedShapeIds(e,{source:"system"}),this.info&&(this.editor.clearSelectionTransients(),this.editor.history.bailToMark(this.info.session.historyMark))}),this.transition("idle")}onInfoExit(){this.info?.session.shouldClearBindingPreviewOnExit&&this.editor.setBindingPreview(null),this.editor.setSnapIndicators(null)}apply({pagePoint:e,accelKey:t}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastAccelKey=t;const n=this.info.session.handleSnapMode??"none",i=this.info.snapSnapshot,r=!t&&"none"!==n&&null!==i,o=r&&i?this.editor.snaps.snapHandle({mode:n,pagePoint:e,snapshot:i,threshold:8/this.editor.getCurrentCamera().z}):null;r||this.editor.snaps.clearIndicators();const s=o?.snappedPagePoint??e,a=this.info.session.update({editor:this.editor,pagePoint:s,accelKey:t,source:"user"}),d="string"==typeof a?a:a.status,l="string"==typeof a?s:a.finalPagePoint;!o||!l||l.dist2(o.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")}},_p=class extends Ap{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.editor.getSelectedShapeIds(),n=this.editor.hitTestSelectionHandle(e.pagePoint);if("rotate"===n?.kind)return void this.transition("pointing_rotate_handle",{originPagePoint:e.pagePoint.clone(),previousSelection:t});if("resize"===n?.kind)return void this.transition("pointing_resize_handle",{handleId:n.id,originPagePoint:e.pagePoint.clone(),cursorHandleOffset:e.pagePoint.sub(n.point),previousSelection:t});if(n){const i=this.editor.getSelectedShapes()[0]??null;if(i){const r=this.editor.selectionHandleInteractions.createSession(this.editor,{handle:n,shape:i,originPagePoint:e.pagePoint.clone()});if(r){const i=r.handleSnapMode??"none";return void this.transition("pointing_selection_handle_interaction",{originPagePoint:e.pagePoint.clone(),previousSelection:t,session:r,snapSnapshot:"none"===i?null:this.editor.snaps.createHandleSnapshot({context:r.handleSnapContext??{shapeId:r.shapeId,handle:n},currentPagePoint:e.pagePoint,allowSelfSnap:r.allowSelfSnap??!1,excludedShapeIds:r.excludedSnapShapeIds})})}}}const i=this.editor.hitTestShape(e.pagePoint);if(i){const n=this.editor.getShapeUtil(i).getSelectionTargetId(i,{editor:this.editor}),r=this.editor.getShapeUtil(i).getTranslateTargetId(i,{editor:this.editor}),o=Ei(e),s=Bi(this.editor,n,t),a=o?null:((e,t,n)=>{const i=new Set(n);for(const r of Mi(e,t))if(i.has(r.ancestorId))return r.ancestorId;return null})(this.editor,n,t),d=o?null:a?s:null,l=Bi(this.editor,r,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:o,wasSelected:t.includes(s),fromSelectionBounds:!1,quickClickSelectionTargetId:d})}if(!Ei(e)&&t.length>0){const n=this.editor.getSelectedShapes()[0];if(n&&this.editor.getShapeUtil(n).canStartTranslateFromSelectionBounds(n)&&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:Ei(e)})}},Vp=class extends Kp{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:Ei(e)})}onPointerUp(e){Ei(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")}},qp=class extends Kp{constructor(e,t){super(e,"pointing_resize_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");const t=this.editor.getSelectionTransformTargetShapes(),n=(({shapes:e,selectionFrame:t,getShapeSelectionResizePageOutlineVertices:n,getShapeSelectionPagePoints:i})=>{const r={rotation:t.rotation,rotationCenter:t.rotationCenter},o=[],s=[];for(const a of e){const e=i(a);e?s.push({shape:a,startLocalPagePoint:mn(e[0],r),endLocalPagePoint:mn(e[1],r)}):o.push({shape:a,localBounds:Hh.FromPoints(n(a).map(e=>mn(e,r))),rotation:a.rotation})}return{startBounds:t.bounds.clone(),rotation:t.rotation,rotationCenter:t.rotationCenter.clone(),aspectRatio:0===t.bounds.h?1:t.bounds.w/t.bounds.h,shapes:o,pointShapes:s}})({shapes:t,selectionFrame:e,getShapeSelectionResizePageOutlineVertices:e=>function(e,t){const n=e.getShapeUtil(t).getSelectionResizeLocalBounds(t),i=e.computeShapeLocalToPageTransform(t);return(e=>[new zh(e.minX,e.minY),new zh(e.maxX,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)])(n).map(e=>i.applyToPoint(e))}(this.editor,e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e)});var i,r;this.transition("resizing",{...this.info,startBounds:n.startBounds,rotation:n.rotation,rotationCenter:n.rotationCenter,aspectRatio:n.aspectRatio,snapSnapshot:this.editor.snaps.createResizeSnapshot({resizingShapeIds:t.map(e=>e.id),coordinateSpace:{rotation:n.rotation,rotationCenter:n.rotationCenter}}),shapes:n.shapes,pointShapes:n.pointShapes,updates:(i=n.shapes,r=n.pointShapes,[...i.map(e=>({id:e.shape.id,rotation:e.rotation})),...r.map(e=>({id:e.shape.id}))]),aspectRatioLockOverride:zi(this.editor,t,this.info.handleId),lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},jp=class extends Kp{constructor(e,t){super(e,"pointing_rotate_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");const t=(({shapes:e,selectionFrame:t,getShapeLocalBounds:n,getShapeSelectionPagePoints:i})=>{const r=[],o=[];for(const s of e){const e=i(s);e?o.push({shape:s,startPagePoint:e[0],endPagePoint:e[1]}):r.push({id:s.id,x:s.x,y:s.y,localBounds:n(s),rotation:s.rotation})}return{center:t.rotationCenter.clone(),initialSelectionRotation:t.rotation,shapes:r,pointShapes:o}})({shapes:this.editor.getSelectionRotationTargetShapes(),selectionFrame:e,getShapeLocalBounds:e=>this.editor.computeShapeLocalBounds(e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e)});var n,i;this.transition("rotating",{...this.info,center:t.center,startAngle:zh.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")}},Gp=class extends Kp{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")}},Zp=class extends Kp{constructor(e,t){super(e,"pointing_shape",t)}onInfoEnter(){this.info&&(this.info.quickClickSelectionTargetId||(this.info.additiveSelection?this.info.wasSelected||this.editor.commands.setSelectedShapeIds([...this.info.previousSelection,this.info.shapeId],{source:"system"}):this.info.wasSelected||this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"})))}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectedShapes(),t=this.info.wasSelected?e.map(e=>e.id):[this.info.translateTargetId];this.info.wasSelected||1!==t.length||t[0]===this.info.shapeId||this.editor.commands.setSelectedShapeIds(t,{source:"system"});const n=this.editor.getSelectionFrame(),i=((e,t)=>{const n=t.filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked&&!e.hasLockedDescendant(n.id)});return e.getShapeIdsIncludingDescendants(n).map(t=>e.getShape(t)).filter(e=>!!e&&!e.isLocked).map(e=>({id:e.id,x:e.x,y:e.y}))})(this.editor,t),r=i.map(e=>e.id),o=n?.hasCompatibleRotation?n.rotation:0,s=n?.rotationCenter.clone()??zh.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:r,coordinateSpace:{rotation:o,rotationCenter:s}}),snapRotation:o,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 Ei(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")}},Qp=class extends Xp{tickMode="apply_after_scroll_or_without_screen_point";constructor(e,t){super(e,"resizing",t)}getHistoryMark(){return Hp}onDragStart(){this.editor.setSnapIndicators(null)}onPointerUp(){this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:i}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&i===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=i;const r=$i(this.info.rotationCenter,this.info.rotation),o=mn(e.sub(this.info.cursorHandleOffset),r),s=this.info.aspectRatioLockOverride??t,a=function({startBounds:e,handleId:t,pagePoint:n,isAspectRatioLocked:i,isResizingFromCenter:r,aspectRatio:o}){const s=r?(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.center,r=n.x-i.x,o=n.y-i.y,s=Math.max(Math.abs(r),.5),a=Math.max(Math.abs(o),.5),d=Ct(t)||kt(t)?r*(Ct(t)?-2:2)/Math.max(1,e.w):1,l=Tt(t)||Bt(t)?o*(Tt(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new Hh(e.minX,i.y-a,e.w,2*a),scaleX:d,scaleY:l};case"left":case"right":return{bounds:new Hh(i.x-s,e.minY,2*s,e.h),scaleX:d,scaleY:l};default:return{bounds:new Hh(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,r=e.maxX,o=e.minY,s=e.maxY;let a=Ct(t)?i:r,d=Ct(t)?r:i,l=Tt(t)?o:s,c=Tt(t)?s:o;Ct(t)||kt(t)?a=n.x:(a=r,d=i),Tt(t)||Bt(t)?l=n.y:(l=s,c=o);const u=a-d,h=l-c,p=Ct(t)?d-a:u,g=Tt(t)?c-l:h,m=Ct(t)||kt(t)?p/Math.max(1,e.w):1,f=Tt(t)||Bt(t)?g/Math.max(1,e.h):1;return{bounds:new Hh(Math.min(a,d),Math.min(l,c),Math.max(1,Math.abs(u)),Math.max(1,Math.abs(h))),scaleX:m,scaleY:f}})({startBounds:e,handleId:t,pagePoint:n});return i?Ft({bounds:s.bounds,startBounds:e,handleId:t,aspectRatio:o,isResizingFromCenter:r,scaleX:s.scaleX,scaleY:s.scaleY}):s}({startBounds:this.info.startBounds,handleId:this.info.handleId,pagePoint:o,isAspectRatioLocked:s,isResizingFromCenter:n,aspectRatio:this.info.aspectRatio}),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&&Li(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&&Di(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(Hp),this.transition("idle")}cancel(){this.editor.setSnapIndicators(null),this.editor.history.bailToMark(Hp),this.transition("idle")}},Jp=class extends Xp{tickMode="apply_after_scroll";constructor(e,t){super(e,"rotating",t)}getHistoryMark(){return Yp}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=Ri(zh.Angle(this.info.center,e)-this.info.startAngle);if(t)i=Fi(i,$p);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=Fi(e,Dp),n=Ri(t-e);Math.abs(n)<=Up&&(i=Ri(t-this.info.initialSelectionRotation))}for(let r=0;r<this.info.shapes.length;r+=1){const e=this.info.shapes[r],t=this.info.updates[r];e&&t&&Hi(e,this.info.center,i,t)}for(let r=0;r<this.info.pointShapes.length;r+=1){const e=this.info.pointShapes[r],t=this.info.updates[this.info.shapes.length+r];e&&t&&Yi(this.editor,e,this.info.center,i,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.history.squashToMark(Yp),this.transition("idle")}cancel(){this.editor.history.bailToMark(Yp),this.transition("idle")}},eg=class extends Xp{tickMode="always_apply";constructor(e,t){super(e,"translating",t)}getHistoryMark(){return zp}onDragStart(){this.editor.setSelectionTranslationActive(!0),this.editor.setSnapIndicators(null)}onPointerUp(e){this.complete(e.pagePoint)}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.setSelectionTranslationActive(!1),this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;const i=e.x-this.info.originPagePoint.x,r=e.y-this.info.originPagePoint.y;t?this.info.lockedAxis||0===i&&0===r||(this.info.lockedAxis=Math.abs(i)>=Math.abs(r)?"x":"y"):this.info.lockedAxis=null;let o=i,s=r;"x"===this.info.lockedAxis?s=0:"y"===this.info.lockedAxis&&(o=0);const a=this.info.startBounds;if(!n&&a&&(this.info.snapSnapshot.points.length>0||this.info.snapSnapshot.nodes.length>0)&&this.editor.inputs.state.get().screenVelocity.len()<.5&&a){const e=this.info.snapRotation,t=8/this.editor.getCurrentCamera().z,n=0===e?new zh(o,s):new zh(o,s).rot(-e),{nudge:i}=this.editor.snaps.snapTranslate({lockedAxis:this.info.lockedAxis,initialSelectionBounds:a,dragDelta:n,snapshot:this.info.snapSnapshot,threshold:t}),r=0===e?i:i.rot(e);o+="y"===this.info.lockedAxis?0:r.x,s+="x"===this.info.lockedAxis?0:r.y}else this.editor.snaps.clearIndicators();if(o!==this.info.lastDeltaX||s!==this.info.lastDeltaY){this.info.lastDeltaX=o,this.info.lastDeltaY=s;for(let e=0;e<this.info.selectedShapes.length;e+=1){const t=this.info.selectedShapes[e],n=this.info.updates[e];t&&n&&(n.x=t.x+o,n.y=t.y+s)}this.editor.commands.updateShapes(this.info.updates)}Xi(this.editor,this.info.selectedShapeIds,e),((e,t,n)=>{const i=Ki(e,t,n);if(i===Oi(e,t))return void e.setDropTargetShapeId(null);const r=i?e.getShape(i):null;e.setDropTargetShapeId(r?.id??null)})(this.editor,this.info.selectedShapeIds,e)}complete(e){this.info&&Xi(this.editor,this.info.selectedShapeIds,e),this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.squashToMark(zp),this.transition("idle")}cancel(){this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.bailToMark(zp),this.transition("idle")}},tg=class extends Ap{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new _p(e,this)),this.addChild(new Vp(e,this)),this.addChild(new Wp(e,this)),this.addChild(new Zp(e,this)),this.addChild(new eg(e,this)),this.addChild(new qp(e,this)),this.addChild(new Qp(e,this)),this.addChild(new jp(e,this)),this.addChild(new Jp(e,this)),this.addChild(new Gp(e,this)),this.addChild(new Np(e,this))}},ng="editor.tool.set-active-tool",ig="editor.tool.toggle-locked",rg=class{registry=new Map;registeredPluginIds=new Set;registerShapeRenderer(e){this.registry.set(e.type,e)}getShapeRenderer(e){return this.registry.get(e)??null}hasShapeRenderer(e){return this.registry.has(e)}getRegisteredShapeTypes(){return[...this.registry.keys()]}registerCanvasPlugins(e){const t=e.filter(e=>!this.registeredPluginIds.has(e.id));for(const n of t){for(const e of n.shapeRenderers??[])this.registerShapeRenderer(e);this.registeredPluginIds.add(n.id)}}},og=Ni(),sg=lh(og),ag=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(_i)}getRegisteredCanvasOverlayIds(){return[...this.canvasOverlays.keys()]}registerSelectionCustomHandleRenderer(e){this.selectionCustomHandleRenderers.set(e.type,e)}getSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.get(e)??null}hasSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.has(e)}getRegisteredSelectionCustomHandleTypes(){return[...this.selectionCustomHandleRenderers.keys()]}registerCanvasPlugins(e){const t=e.filter(e=>!this.registeredPluginIds.has(e.id));for(const n of t){for(const e of n.canvasOverlays??[])this.registerCanvasOverlay(e);for(const e of n.selectionCustomHandleRenderers??[])this.registerSelectionCustomHandleRenderer(e);this.registeredPluginIds.add(n.id)}}},dg=Vi(),lg=lh(dg),cg=class{guards=[];registeredGuardIds=new Set;register(e){this.registeredGuardIds.has(e.id)||(this.guards.push(e),this.registeredGuardIds.add(e.id))}registerCanvasPlugins(e){for(const t of e)for(const e of t.domEventGuards??[])this.register(e)}getGuards(){return this.guards}handle(e){for(const t of this.guards)if("handled"===t.handle(e))return"handled";return"continue"}getCursor(e){for(const t of this.guards){const n=t.getCursor?.(e);if(void 0!==n)return n}}},ug=class{actions=new Map;contributions=new Map;hostActionIds=new Set;duplicateActionIds=new Set;duplicateContributionIds=new Set;registerAction(e,t={}){!this.actions.has(e.id)||t.replace?this.actions.set(e.id,e):this.duplicateActionIds.add(e.id)}registerHostAction(e){this.hostActionIds.add(e.id),this.registerAction(e,{replace:!0})}registerContribution(e,t={}){!this.contributions.has(e.id)||t.replace?this.contributions.set(e.id,e):this.duplicateContributionIds.add(e.id)}registerEditorPlugins(e){for(const t of e){for(const e of t.canvasActions??[])this.registerAction(e);for(const e of t.toolbarContributions??[])this.registerContribution(e)}}getAction(e){return this.actions.get(e)??null}getHostActionIds(){return[...this.hostActionIds]}getDuplicateActionIds(){return[...this.duplicateActionIds]}getDuplicateContributionIds(){return[...this.duplicateContributionIds]}getGroups(e,t,n={}){return[...this.contributions.values()].filter(t=>t.surface===e).filter(e=>!n.placement||(e.placement??"context")===n.placement).filter(e=>e.when?.(t)??!0).sort((e,t)=>(e.order??0)-(t.order??0)).flatMap(e=>[...e.getGroups(t)].sort((e,t)=>(e.order??0)-(t.order??0)))}},hg=class{contributions=new Map;duplicateContributionIds=new Set;registerContribution(e,t={}){!this.contributions.has(e.id)||t.replace?this.contributions.set(e.id,e):this.duplicateContributionIds.add(e.id)}registerEditorPlugins(e){for(const t of e)for(const e of t.contextMenuContributions??[])this.registerContribution(e)}getDuplicateContributionIds(){return[...this.duplicateContributionIds]}getSections(e,t){return(e=>{const t=[],n=new Map;for(const i of e){const e=n.get(i.id);if(void 0===e){n.set(i.id,t.length),t.push({...i,items:[...i.items]});continue}const r=t[e];t[e]={...r,title:r.title??i.title,items:[...r.items,...i.items]}}return t})([...this.contributions.values()].filter(t=>"any"===t.target||t.target===e).filter(e=>e.when?.(t)??!0).sort((e,t)=>(e.order??0)-(t.order??0)).flatMap(e=>[...e.getSections(t)].sort((e,t)=>(e.order??0)-(t.order??0))))}},pg="var(--land-selection, #2563eb)",gg=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,er(this.options,t??{}))}createFeature(){return this.config.createFeature?.(this.options)??null}getExtensions(){return this.config.addExtensions?.(this.options)??[]}},mg="default",fg={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}},Sg=new WeakMap,yg=lh(null),xg=ch(({hoveredShapeId:e})=>Er(Mr().retainedShapeIdsSignal).map(t=>Ph(Pg,{shapeId:t,isHovered:t===e},t))),bg=ch(()=>{const e=Mr(),t=Er(e.currentPageShapeIdsSignal),n=Er(e.retainedShapeIdsSignal),i=Er(e.renderVisibleShapeIdsSignal),r=Er(e.shapeRenderOrderByIdSignal),o=new Set(i),s=n.map(e=>r.get(e)??-1),a=n.filter(e=>o.has(e)).map(e=>r.get(e)??-1),d=n.filter(e=>!o.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};
42
+ return Ph("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)})}),Pg=ch(({shapeId:e,isHovered:t})=>{const n=Mr(),i=e,r=Er(n.getShapeSignal(i)),o=Er(n.getShapeRenderVisibleSignal(i)),s=Er(n.toolStateSignal).activeToolId,a=Er(n.getShapeSelectedSignal(i)),d="select"===s&&a,l=Er(n.getShapeEditingSessionForShapeSignal(i)),c=Er(n.getShapeRenderOrderSignal(i)),u=Er(n.getShapeDropTargetSignal(i)),h=Er(n.getShapeErasingSignal(i)),p=Er(n.getShapeSelectedDescendantTransformAncestorSignal(i)),g=Er(n.getShapeClipAncestorIdsSignal(i)),m=hh(sg);if(!r)return null;const f=m.getShapeRenderer(r.type);if(!f)return null;const S=f.component,y=((e,t)=>{const n=e.computeShapeRenderBounds(t),i=e.computeShapeRenderToPageTransform(t).compose(Yh.Translate(n.x,n.y));return{left:0,top:0,width:n.w,height:n.h,transform:i.toCssString(),transformOrigin:"0 0",elementToPage:i}})(n,r),x=h?.32*r.opacity:r.opacity;
43
+ return Ih("div",{"data-ui":"shape-instance","data-shape-id":r.id,"data-shape-type":r.type,"data-selected":d?"true":"false","data-hovered":t?"true":"false","data-drop-target":u?"true":"false","data-visible":o?"true":"false","data-render-order":c>=0?String(c):void 0,"data-clip-ancestor-count":g.length,style:{position:"absolute",display:o?void 0:"none",left:y.left,top:y.top,width:y.width,height:y.height,opacity:1===x?void 0:x,transform:y.transform,transformOrigin:y.transformOrigin,pointerEvents:"none",outline:u?"2px solid #2563eb":void 0,outlineOffset:u?4:void 0,boxShadow:u?"0 0 0 6px rgba(37, 99, 235, 0.16)":void 0,zIndex:c>=0?c+1:void 0},children:[o?Ph($r,{clipAncestorIds:g,shapeElementToPage:y.elementToPage,children:Ph(S,{shape:r,editor:n,isSelected:d,isHovered:t,shapeEditingSession:l})}):null,o&&u?Ph(Lr,{shapeType:r.type}):null,o&&p?Ph(Fr,{}):null]})}),Ig="rgba(100, 116, 139, 0.82)",wg="rgba(255, 255, 255, 0.84)",vg=ch(()=>Er(Mr().bindingPreviewActiveSignal)?Ph(Cg,{}):null),Cg=ch(()=>{const e=Er(Mr().bindingPreviewSignal);return e?Ih(bh,{children:[Ph(kg,{targetShapeId:e.targetShapeId}),Ph(Tg,{bindingPreview:e})]}):null}),kg=ch(({targetShapeId:e})=>{const t=Mr(),n=Er(t.cameraZoomSignal),i=Er(t.getShapeSignal(e));return i?Ph(Kr,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),Tg=ch(({bindingPreview:e})=>{const t=Er(Mr().cameraZoomSignal),n=2/t,i=6/t,r=4/t;
44
+ return Ih(bh,{children:[e.guidePath?Ph(Or,{path:e.guidePath,strokeWidth:n,dashSize:i,gapSize:r,kind:"binding-preview",terminal:e.terminal}):Ph(Yr,{start:e.rawPagePoint,end:e.resolvedPagePoint,startInset:8/t,endInset:6/t,strokeWidth:n,dashSize:i,gapSize:r,kind:"binding-preview",terminal:e.terminal}),
45
+ Ph("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}),
46
+ Ph("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})]})}),Bg=ch(()=>Er(Mr().brushBoxActiveSignal)?Ph(Mg,{}):null),Mg=ch(()=>{const e=Er(Mr().brushBoxSignal);return e?Ph("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}),Eg=ch(()=>{const e=Mr(),t=Er(e.selectionOverlayFrameGeometrySignal),n=Er(e.selectionOverlayCompanionFrameGeometriesSignal);return t||0!==n.length?Ih(bh,{children:[t?Ph(Ag,{frameGeometry:t}):null,n.map((e,t)=>Ph(Ag,{frameGeometry:e},`companion-${t}`))]}):null}),Ag=ch(({frameGeometry:e})=>{const t=Er(Mr().selectionOverlayFrameStyleSignal),{bounds:n,rotation:i,rotationCenter:r}=e,{cornerRadius:o,strokeWidth:s}=t,a=180*i/Math.PI;
47
+ return Ih("g",{transform:0===i?void 0:`rotate(${a} ${r.x} ${r.y})`,children:[Ph("rect",{"data-selection-overlay":"bounds-underlay",x:n.x,y:n.y,width:n.w,height:n.h,rx:o,ry:o,fill:"none",stroke:"rgba(255,255,255,0.92)",strokeWidth:2*s}),Ph("rect",{"data-selection-overlay":"bounds",x:n.x,y:n.y,width:n.w,height:n.h,rx:o,ry:o,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeWidth:s})]})}),Rg=ch(()=>{const e=Er(Mr().selectionOverlayHandleAnchorsSignal);return e?Ph(Fg,{anchors:e}):null}),Fg=ch(({})=>{const e=Mr(),t=Er(e.selectionOverlayHandlesSignal),n=Er(e.selectionOverlayFrameGeometrySignal),i=qi(),r=Er(e.cameraZoomSignal);if(!t)return null;const{resizeHandles:o,rotateHandles:s,strokeWidth:a,terminalHandles:d,middleHandles:l,customHandles:c}=t;
48
+ return Ih(bh,{children:[o.map(e=>Ph("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:Xr(e.id,n?.rotation??0),pointerEvents:"auto"}},e.id)),s.map(e=>Ih("g",{"data-selection-rotate-handle":e.id,transform:`translate(${e.bounds.center.x-6/r} ${e.bounds.center.y-6/r}) scale(${.6/r})`,fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[Ph("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),Ph("path",{d:"M21 3v5h-5"})]},e.id)),d.map(e=>Ph("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=>Ph("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);
49
+ return Ph(t?t.component:Wr,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),Lg=["ew-resize","nwse-resize","ns-resize","nesw-resize"],$g=ch(()=>{const e=Mr(),t=Er(e.selectionOverlayPathSignal),n=Er(e.selectionOverlayBindingSegmentsSignal),i=Er(e.selectionOverlayFrameStyleSignal);return t?Ih(bh,{children:[
50
+ Ph(Dg,{bindingSegments:n,strokeWidth:i.strokeWidth}),
51
+ Ph("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}),
52
+ Ph("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:i.strokeWidth})]}):null}),Dg=ch(({bindingSegments:e,strokeWidth:t})=>{if(0===e.length)return null;const n=3*t,i=2*t,r=4*t,o=3*t;
53
+ return Ph(bh,{children:e.map(e=>e.guidePath?Ph(Or,{path:e.guidePath,strokeWidth:t,dashSize:n,gapSize:i,kind:"selection-binding",terminal:e.terminal},e.terminal):Ph(Yr,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:r,endInset:o,strokeWidth:t,dashSize:n,gapSize:i,kind:"selection-binding",terminal:e.terminal},e.terminal))})}),Ug=ch(()=>Er(Mr().selectionTranslationActiveSignal)?null:Ih(bh,{children:[
54
+ Ph($g,{}),
55
+ Ph(Eg,{}),
56
+ Ph(Rg,{})]})),zg="rgba(37, 99, 235, 0.9)",Hg=ch(()=>{const e=Er(Mr().snapIndicatorsSignal);return 0===e.length?null:Ph(Yg,{indicators:e})}),Yg=ch(({indicators:e})=>{const t=Er(Mr().cameraZoomSignal);
57
+ return Ph(bh,{children:e.map(e=>Ph("points"===e.type?Og:Kg,{indicator:e,zoom:t},e.id))})}),Og=ch(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[r,o]=e.line,s=180*e.rotation/Math.PI;
58
+ return Ih("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${s} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[Ph("path",{"data-ui":"snap-indicator-line",d:`M ${r.x} ${r.y} L ${o.x} ${o.y}`,fill:"none",stroke:zg,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,r)=>Ph("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:zg,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${r}`))]})}),Kg=ch(({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=Nr(i,[n?c.startEdge[0].y:c.startEdge[0].x,n?c.startEdge[1].y:c.startEdge[1].x]);e&&(i=e);const t=Nr(i,[n?c.endEdge[0].y:c.endEdge[0].x,n?c.endEdge[1].y:c.endEdge[1].x]);t&&(i=t)}if(!Number.isFinite(i[0])||!Number.isFinite(i[1]))return null;const r=(i[0]+i[1])/2,o=3.5/t,s=2*o,a=[];for(const{startEdge:c,endEdge:u}of e.gaps)if(n){a.push(`M ${c[0].x} ${r-s} L ${c[1].x} ${r+s}`,`M ${u[0].x} ${r-s} L ${u[1].x} ${r+s}`,`M ${c[0].x} ${r} L ${u[0].x} ${r}`);const e=(c[0].x+u[0].x)/2;a.push(`M ${e} ${r-o} L ${e} ${r+o}`)}else{a.push(`M ${r-s} ${c[0].y} L ${r+s} ${c[1].y}`,`M ${r-s} ${u[0].y} L ${r+s} ${u[1].y}`,`M ${r} ${c[0].y} L ${r} ${u[0].y}`);const e=(c[0].y+u[0].y)/2;a.push(`M ${r-o} ${e} L ${r+o} ${e}`)}const d=180*e.rotation/Math.PI,l=0===e.rotation?void 0:`rotate(${d} ${e.rotationCenter.x} ${e.rotationCenter.y})`;
59
+ return Ph("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:l,fill:"none",stroke:zg,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),Xg=ch(()=>Ih("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
60
+ Ph("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 '}),
61
+ Ph(Wg,{layer:"below-host"}),
62
+ Ph(Hg,{}),
63
+ Ph(vg,{}),
64
+ Ph(Bg,{}),
65
+ Ph(Ug,{}),
66
+ Ph(Wg,{layer:"above-host"})]})),Wg=ch(({layer:e})=>{const t=qi().getCanvasOverlays(e);return 0===t.length?null:Ph(bh,{children:t.map(({id:e,component:t})=>Ph(t,{},e))})}),Ng="canvas-surface",_g=`[data-ui="${Ng}"]`,Vg=[{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}],qg=14,jg=16,Gg=20,Zg=28,Qg=16,Jg={[qg]:20,[jg]:24,[Gg]:28,[Zg]:36},em=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))),wo(i,"whiteSpace",n?.whiteSpace),wo(i,"overflowWrap",n?.overflowWrap),wo(i,"lineHeight",n?.lineHeight),wo(i,"letterSpacing",n?.letterSpacing),wo(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=w(t.props.color),e.style.fontFamily=go(t.props.font,n),e.style.fontSize=`${mo(t.props.size)}px`,e.style.lineHeight=`${fo(t.props.size)}px`,e.style.textAlign=yo(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})}},tm=new WeakMap,nm="land.rich-text-bubble-menu",im="updatePosition",rm=[{id:"bold",label:"Bold",shortcut:"B",dataUi:"text-bold-button",content:"B"},{id:"italic",label:"Italic",shortcut:"I",dataUi:"text-italic-button",content:"I"},{id:"strike",label:"Strikethrough",shortcut:"S",dataUi:"text-strike-button",content:"S"}],om=[Bh.configure({bold:!1,italic:!1,strike:!1}),Ch.extend({keepOnSplit:!0}),kh.extend({keepOnSplit:!0}),Th.extend({keepOnSplit:!0})],sm=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),am={id:"land.text.dom-events",handle({event:e,name:t}){if(!sm.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},dm="text.create",lm=class extends Ap{constructor(e){super(e,"text"),this.initial="idle",this.addChild(new cm(e,this)),this.addChild(new um(e,this))}},cm=class extends Ap{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("pointing",{originPagePoint:e.pagePoint.clone(),shapeId:null,didCreateShape:!1})}},um=class extends Ap{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e,this.editor.history.mark(dm)}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(!oo(t))return this.editor.history.bailToMark(dm),void this.transition("idle");this.info.didCreateShape=!0,q(this.editor,t.id,{source:"user"}),this.editor.isToolLocked()||(this.transition("idle"),this.editor.commands.setActiveTool("select",{source:"system"})),this.editor.startEditingShape({shapeId:t.id,entryMode:"focusEnd",markId:dm,reuseExistingMark:!0,preserveInteraction:!0},"user"),this.editor.isToolLocked()&&this.transition("idle")}onCancel(){this.info?.didCreateShape||this.editor.history.bailToMark(dm),this.transition("idle")}onExit(){this.info=null}updateFixedWidthShape(e){if(!this.info)return;const t=((e,t,n)=>{const i=Math.abs(t.x-e.x);return e.dist(t)<4||i<8?null:{x:Math.min(e.x,t.x),y:e.y-n.h/2,props:{...Ko(n),w:Math.max(16,i),autoSize:!1}}})(this.info.originPagePoint,e,this.getDefaultTextProps());if(t){if(!this.info.shapeId){const e=this.createTextShapeAt(t);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:t.x,y:t.y,props:{w:t.props.w,h:t.props.h,autoSize:!1}}],{source:"user"})}}createTextShape(e){return this.createTextShapeAt(((e,t)=>({x:e.x,y:e.y-t.h/2,props:Ko(t)}))(e,this.getDefaultTextProps()))}createTextShapeAt({x:e,y:t,props:n}){const i=lo(this.editor,{x:e,y:t,props:n},"user");return this.editor.commands.setSelectedShapeIds([i.id],{source:"system"}),i}getDefaultTextProps(){return ao(this.editor)}},hm="arrow-label",pm="geo-label",gm={[hm]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!0,canUseSelectionFrameHandles:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[pm]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!1,canUseSelectionFrameHandles:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}},mm=["start","middle","end"],fm=class extends Mp{type="text";getDefaultProps(){return{richText:sr(""),w:16,h:So(Qg),autoSize:!0,scale:1,font:mg,size:Qg,color:f("text-slate"),textAlign:"start"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{richText:dr(t.richText),w:Math.max(1,Vo(t.w,n.w)),h:Math.max(1,Vo(t.h,n.h)),autoSize:"boolean"==typeof t.autoSize?t.autoSize:n.autoSize,scale:Math.max(.01,Vo(t.scale,n.scale)),font:vr(t.font)?t.font:n.font,size:po(t.size,n.size),color:I(t.color,n.color),textAlign:(i=t.textAlign,"string"==typeof i&&mm.includes(i)?t.textAlign:n.textAlign)};var i}getBounds(e){return(e=>new Hh(e.x,e.y,jo(e),Go(e)))(e)}getLocalBounds(e){return Zo(e)}getRenderBounds(e){return Zo(e)}getExportBounds(e){return Zo(e)}canEdit(e){return!0}contributesToSelectionFrame(e,t){return n=t.editor,i=e.id,No(n,i)?.behavior.contributesToSelectionFrame??null??!0;var n,i}canUseSelectionFrameHandles(e,t){return n=t.editor,i=e.id,No(n,i)?.behavior.canUseSelectionFrameHandles??null??!0;var n,i}getSelectionTargetId(e,t){return((e,t)=>{const n=No(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=No(e,t);return n?"owner"===n.behavior.translateTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}resizeSelectionBounds(e,t){const n={};Qo(t.handleId)?(n.w=Math.max(16,t.selectionLocalBounds.w/qo(e)),n.autoSize=!1):n.scale=Math.max(.01,e.props.scale*((e,t)=>{const n=t.selectionLocalBounds.w/Math.max(1,jo(e)),i=t.selectionLocalBounds.h/Math.max(1,Go(e));switch(t.handleId){case"left":case"right":return n;case"top":case"bottom":return i;default:return Math.max(n,i)}})(e,t));const i=n.scale??qo(e),r=(n.w??e.props.w)*i,o=e.props.h*i,s=((e,t)=>0===t.selectionRotation?e.clone():zh.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(Rt({handleId:t.handleId,requestedBounds:t.selectionLocalBounds,actualWidth:r,actualHeight:o,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,t);return{id:e.id,x:s.x-r/2,y:s.y-o/2,rotation:t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,scaleX:t.scaleX<0?-e.scaleX:e.scaleX,scaleY:t.scaleY<0?-e.scaleY:e.scaleY,props:n}}getSelectionResizeAspectRatioLock(e,t){return t.isOnlySelected?!Qo(t.handleId):null}onEditEnd(e){if(!(ar(e.props.richText).trim().length>0))return{deleteShapeIds:[e.id]}}},Sm=class{fontCatalog;type="text";constructor(e){this.fontCatalog=e}toSvg(e,t){return 0===ar(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:ts(e,t,this.fontCatalog)},children:Jo(e.props.richText)}]}}},ym=".label",xm=class extends Ep{type=hm;getDefaultProps(){return{labelPosition:.5}}validateProps(e){const t=this.getDefaultProps();return{labelPosition:is((e&&"object"==typeof e?e:{}).labelPosition,t.labelPosition)}}canBind(e,t,n){return oo(n.fromShape)&&ns(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)=>No(e,t)?.behavior.showsCompanionFrameWhenOwnerSelected??null)(e,t.fromId))return[];const i=e.getShape(t.fromId),r=e.getShape(t.toId);if(!oo(i)||!ns(r))return[];const o=e.computeShapeGeometry(i);return[{bounds:o.bounds,rotation:i.rotation,rotationCenter:o.center}]}syncLabelPosition(e,t){if(n=t,"binding"!==n?.typeName||"arrow-label"!==n.type)return;var n;const i=e.getShape(t.fromId),r=e.getShape(t.toId);if(!oo(i)||!ns(r))return{deleteBindingIds:[t.id]};const o=((e,t,n)=>{const i=rs(e,t,n),r=n.parentId,o=`${n.index}${ym}`,s=!1,a="middle";return t.x===i.x&&t.y===i.y&&t.rotation===i.rotation&&t.parentId===r&&t.index===o&&t.props.w===i.props.w&&t.props.autoSize===s&&t.props.textAlign===a?null:{id:t.id,x:i.x,y:i.y,rotation:i.rotation,parentId:r,index:o,props:{w:i.props.w,autoSize:s,textAlign:a}}})(e,i,r);return o?{shapes:[{...i,...o,props:{...i.props,...o.props}}]}:void 0}},bm=".label",Pm=class extends Ep{type=pm;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:ds(i.x,t.normalizedAnchor.x),y:ds(i.y,t.normalizedAnchor.y)},ownerBaseHeight:ls(n.ownerBaseHeight,t.ownerBaseHeight)}}canBind(e,t,n){return oo(n.fromShape)&&as(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?us(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?us(n,t):null;return{shapes:i?[i]:void 0,deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}syncLabelPosition(e,t,n){if(i=t,"binding"!==i?.typeName||"geo-label"!==i.type)return;var i;const r=e.getShape(t.fromId),o=e.getShape(t.toId);if(!oo(r)||!as(o))return{deleteBindingIds:[t.id]};const s=((e,t,n)=>{const i=cs(t,"h")??1;return"to"===n?.role?i:e.props.ownerBaseHeight>0?e.props.ownerBaseHeight:i})(t,o,n),a=t.props.ownerBaseHeight===s?null:{...t,props:{...t.props,ownerBaseHeight:s}},d=function(e,t,n){const i=cs(e,"h");if(!i)return null;const r=Math.max(n,(e=>Math.max(1,e.props.h*e.props.scale+32))(t));return i===r?null:{...e,props:{...e.props,h:r}}}(o,r,s),l=((e,t,n)=>{const i=hs(e,t,n),r=n.parentId,o=`${n.index}${bm}`,s=!1,a="middle";return t.x===i.x&&t.y===i.y&&t.rotation===i.rotation&&t.parentId===r&&t.index===o&&t.props.w===i.props.w&&t.props.autoSize===s&&t.props.textAlign===a?null:{id:t.id,x:i.x,y:i.y,rotation:i.rotation,parentId:r,index:o,props:{w:i.props.w,autoSize:s,textAlign:a}}})(e,r,d??o),c=[];return d&&c.push(d),l&&c.push({...r,...l,props:{...r.props,...l.props}}),c.length>0||a?{shapes:c.length>0?c:void 0,bindings:a?[a]:void 0}:void 0}},Im="text.edit",wm="arrow-label.edit",vm="arrow-label.create",Cm="geo-label.edit",km="geo-label.create",Tm=[{value:f("text-slate"),label:"Slate",color:"var(--land-shape-text-slate)"},{value:f("text-blue"),label:"Blue",color:"var(--land-shape-text-blue)"},{value:f("text-green"),label:"Green",color:"var(--land-shape-text-green)"},{value:f("text-red"),label:"Red",color:"var(--land-shape-text-red)"}],Bm=[{id:"s",value:14,label:"S"},{id:"m",value:16,label:"M"},{id:"l",value:20,label:"L"},{id:"xl",value:28,label:"XL"}],Mm=[{value:"start",label:"Align left",icon:"align-left"},{value:"middle",label:"Align center",icon:"align-center"},{value:"end",label:"Align right",icon:"align-right"}],Em=Ji({name:"text",addOptions:Pr,createFeature:(e=Pr())=>{const t=wr(e);return{id:"land.text.bundle",editorPlugins:[ms({fontCatalog:t})],canvasPlugins:[Ho({fontCatalog:t})],shapeTypes:["text"]}}}),Am=2*Math.PI,Rm=class extends Ep{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,oa(i.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,oa(i.y,n.normalizedAnchor.y)))}}}canBind(e,t,n){return Gs(n.fromShape)&&!Gs(n.toShape)}getExclusiveBindingKey(e){return`${e.fromId}:${e.props.terminal}`}onBindingCreate(e,t){return sa(this.syncArrowTerminal(e,t))}onBindingUpdate(e,t,n){return sa(this.syncArrowTerminal(e,n))}onBindingLoad(e,t){return sa(this.syncArrowTerminal(e,t))}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return sa(this.syncArrowTerminal(e,t))}onBeforeDeleteShape(e,t,n){if("from"===n.role)return{deleteBindingIds:[t.id]};const i=e.getShape(t.fromId);if(!Gs(i))return{deleteBindingIds:[t.id]};const r=this.resolveTerminalPagePoint(e,t);return{shapes:[r?Ls(i,t.props.terminal,r):i],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.fromId);if(!Gs(n))return{deleteBindingIds:[t.id]};const i=this.resolveTerminalPagePoint(e,t);return{shapes:[i?Ls(n,t.props.terminal,i):n],deleteBindingIds:[t.id]}}syncArrowTerminal(e,t){if(!Zs(t))return null;const n=e.getShape(t.fromId);if(!Gs(n))return null;const i=this.resolveTerminalPagePoint(e,t);return i?As(n,t.props.terminal).dist(i)<1e-6?null:Ls(n,t.props.terminal,i):null}resolveTerminalPagePoint(e,t){if(!Zs(t))return null;const n=e.getShape(t.fromId),i=e.getShape(t.toId);if(!Gs(n)||!i||Gs(i))return null;const r=As(n,Rs(t.props.terminal)),o=Es(e,i,t.props.normalizedAnchor,r);return ra(e,{arrow:n,terminal:t.props.terminal,target:i,anchorPagePoint:Ms(e,i,t.props.normalizedAnchor),fallbackBoundaryPagePoint:o}).boundaryPagePoint}},Fm=class extends Mp{type="arrow";getDefaultProps(){return{w:160,h:48,start:{x:8,y:24},end:{x:152,y:24},bend:0,stroke:f("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,da(t.w,n.w)),h:Math.max(1,da(t.h,n.h)),start:aa(t.start,n.start),end:aa(t.end,n.end),bend:da(t.bend,n.bend),stroke:I(t.stroke,n.stroke),strokeWidth:Math.max(1,da(t.strokeWidth,n.strokeWidth)),headStart:"arrow"===t.headStart?"arrow":"none",headEnd:"none"===t.headEnd?"none":"arrow"}}getBounds(e){const t=$s(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}getPointHitTestBounds(e,t){const n=t?.editor?Js(t.editor,e).info:$s(e),i=Math.max(8,e.props.strokeWidth+4);return n.bounds.expand(i)}getLocalBounds(e){return new Hh(0,0,e.props.w,e.props.h)}getExportBounds(e){const t=(e=>Hs(new zh(e.props.start.x,e.props.start.y),new zh(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:Fs(e,As(e,"start"),As(e,"end"))}updateSelectionPagePoints(e,t){const n=Fs(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(As(e,"start"))&&t.brushBounds.containsPoint(As(e,"end"))}getSelectionPagePoints(e){return[As(e,"start"),As(e,"end")]}contributesToSelectionFrame(e){return!1}canStartTranslateFromSelectionBounds(e){return!1}getSelectionHandleAnchors(e,t){if(!t.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=Js(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=Js(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,qs(t,e.points[i],e.points[i+1]));return Number.isFinite(n)?n:t.dist(e.start.point)})(n?.editor?Js(n.editor,e).info:$s(e),n?.pagePoint??t)<=Math.max(8,e.props.strokeWidth+4)}hitTestLineSegment(e,t){const n=t.editor?Js(t.editor,e).info:$s(e),i=Math.max(8,e.props.strokeWidth+4,t.margin),r=t.editor?t.pageStart:t.positionedStart,o=t.editor?t.pageEnd:t.positionedEnd;if(1===n.points.length)return la(n.points[0],r,o)<=i;for(let s=0;s<n.points.length-1;s+=1){const e=n.points[s],t=n.points[s+1];if(e&&t&&ca(r,o,e,t)<=i)return!0}return!1}},Lm="arrow.create",$m=class extends Ap{constructor(e){super(e,"arrow"),this.initial="idle",this.addChild(new Dm(e,this)),this.addChild(new Um(e,this))}},Dm=class extends Ap{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})=>pa(e,{terminal:t,rawPagePoint:n,oppositePagePoint:n.add(new zh(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})}},Um=class extends Ap{info=null;constructor(e,t){super(e,"creating",t)}onEnter(e){if(this.info=e,!this.info)return;this.editor.history.mark(Lm);const t=ua(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)}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=Ci(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(Lm),void this.transition("idle");q(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(Lm),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})}else this.transition("idle")}onCancel(){this.editor.history.bailToMark(Lm),this.transition("idle")}onExit(){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=Gs(n)?ga(this.editor,{arrow:n,terminal:"end",rawPagePoint:e,ignoreTargets:this.editor.inputs.state.get().accelKey}):pa(this.editor,{terminal:"end",rawPagePoint:e,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey});ha(this.editor,t,"end",i,"user")}},zm=class{type="arrow";toSvg(e,t){const n=t.resolveColor(e.props.stroke),i="arrow"===e.props.headStart?`url(#${t.addDef(Ia("start",n))})`:void 0,r="arrow"===e.props.headEnd?`url(#${t.addDef(Ia("end",n))})`:void 0;return{tag:"path",attrs:{d:ea(t.editor,e).path,fill:"none",stroke:n,"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":i,"marker-end":r}}}},Hm=[{value:f("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:f("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:f("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:f("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],Ym=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Om=[{value:"none",label:"None",icon:"minus"},{value:"arrow",label:"Arrow",icon:"arrow-right"}],Km=Ji({name:"arrow",createFeature:()=>({id:"land.arrow.bundle",editorPlugins:[{id:"land.arrow",shapeCapabilities:[{type:"arrow",schemaProps:["w","h","start","end","bend","stroke","strokeWidth","headStart","headEnd"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Binding support lives in arrow binding records, not arrow props."]}],shapeUtils:[new Fm],shapeSvgExporters:[new zm],bindingUtils:[new Rm],interactionHandlers:[{id:"land.arrow.interactions",selectionHandle:Sa()}],canvasActions:[xa("stroke"),xa("strokeWidth"),xa("headStart"),xa("headEnd"),ba("stroke"),ba("strokeWidth"),ba("headStart"),ba("headEnd")],toolbarContributions:[{id:"arrow.tool-toolbar",surface:"tool",placement:"chrome",order:40,actionIds:[ng],getGroups:e=>[{id:"arrow.tools",items:[{kind:"button",id:"arrow.tool.arrow",actionId:ng,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:()=>ya({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:()=>ya({strokeActionId:"arrow.set-stroke",strokeWidthActionId:"arrow.set-strokeWidth",headStartActionId:"arrow.set-headStart",headEndActionId:"arrow.set-headEnd",dataUiPrefix:"arrow"})}],setup(e){e.setTerminalBindingResolver(pa),e.tools.register("arrow",e=>new $m(e),{shortcut:"a"})}}],canvasPlugins:[{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:wa}]}],shapeTypes:["arrow"]})}),Xm=.08,Wm=new WeakMap,Nm=new WeakMap,_m=new WeakMap,Vm=new WeakMap,qm="draw.create",jm=class extends Ap{constructor(e){super(e,"draw"),this.initial="idle",this.addChild(new Gm(e,this)),this.addChild(new Zm(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("draw")}},Gm=class extends Ap{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.parent.getDefaultProps();var n,i;this.transition("drawing",{originPagePoint:e.pagePoint.clone(),shapeId:null,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,isClosed:t.isClosed,isPen:"pen"===e.pointerType,pointGuard:(n=t.strokeWidth,i="pen"===e.pointerType,i?{minPointDistance:Math.max(.12,.08*n),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.3,.14*n),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[bd(e.pagePoint,e.pagePoint,e.pressure,"pen"===e.pointerType)]}]})}},Zm=class extends Ap{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(qm)}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(qm),void this.transition("idle");q(this.editor,t,{source:"user"}),this.editor.history.squashToMark(qm),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.editor.history.bailToMark(qm),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.info=null}appendPoint(e,t){if(!this.info)return;const n=bd(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:vd(this.info.segments)}],{source:"user"})}createShape(){const e=this.tool.getDefaultProps(),[t]=this.editor.commands.createShapes([{type:"draw",x:this.info?.originPagePoint.x??0,y:this.info?.originPagePoint.y??0,props:{...e,stroke:this.info?.stroke??e.stroke,strokeWidth:this.info?.strokeWidth??e.strokeWidth,fill:this.info?.fill??e.fill,isClosed:this.info?.isClosed??e.isClosed,...vd(this.info?.segments??[]),isPen:this.info?.isPen??!1}}],{source:"user"});if(!t||"draw"!==t.type)throw new Error("Failed to create draw shape");return t}appendStraightSegmentPoint(e){if(!this.info)return;this.info.preserveStraightEndpointOnNextFreePoint=!1;const t=Id(this.info),n=t[t.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return void this.replaceCurrentSegmentPoints([{...e,segment:"straight"}]);this.info.straightSegmentAnchorPoint=Pd(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=Id(this.info),n=t[t.length-1];return!(n&&(i=n).x===(r=e).x&&i.y===r.y&&i.pressure===r.pressure&&i.segment===r.segment||(this.replaceCurrentSegmentPoints([...t,Pd(e)]),0));var i,r}appendGuardedCurrentPoint(e){if(!this.info)return;const t=Id(this.info).map(Pd);(function(e,t,n){const i=Ma(t),r=e[e.length-1];if(!r)return void e.push(i);if(Ta(r,i))return;const o=((e,t)=>{if(e<=t.softMaxPointCount)return t.minPointDistance;const n=Ca((e-t.softMaxPointCount)/Math.max(t.hardMaxPointCount-t.softMaxPointCount,1),0,1);return t.minPointDistance*(1+n*t.maxDistanceMultiplier)})(e.length,n),s=i.x-r.x,a=i.y-r.y,d=Math.abs((i.pressure??0)-(r.pressure??0));s*s+a*a<o*o&&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=wd(this.info.segments);this.info.segments=[...t.slice(0,-1),{points:e.map(Pd)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const e=ka(this.info.isPen);let t=wd(this.info.segments),n=t[t.length-1];for(;n.points.length>e;){const i=n.points.slice(0,e).map(Pd),r=i[i.length-1],o=n.points.slice(e).map(Pd);if(!r||0===o.length)break;const s={points:[Pd(r),...o]};t=[...t.slice(0,-1),{points:i},s],n=s}this.info.segments=t}},Qm=class extends Mp{type="draw";getDefaultProps(){return{segments:(e=[{x:0,y:0},{x:24,y:12}],[{points:e.map(Ma)}]),stroke:f("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:Fd(t.segments,n.segments),stroke:I(t.stroke,n.stroke),strokeWidth:Math.max(4,Ed(t.strokeWidth,n.strokeWidth)),fill:I(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=gd(e);return new Hh(e.x+t.localBounds.x,e.y+t.localBounds.y,t.localBounds.w,t.localBounds.h)}getLocalBounds(e){return gd(e).localBounds}getRenderBounds(e){return gd(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=function(e,t){let n=(({segments:e,strokeWidth:t,isPen:n,isClosed:i,targetSelectionStrokeBounds:r})=>{let o=Ha(e);for(let s=0;s<2;s+=1){const e=ld(o,t,n,i),s=ud(e.pointBounds,e.localBounds,r);o=Na(o,e.pointBounds,s)}return o})({segments:Va(Sd(e),t),strokeWidth:e.props.strokeWidth,isPen:e.props.isPen??!1,isClosed:e.props.isClosed,targetSelectionStrokeBounds:t.targetSelectionStrokeBounds});return t.scaleX<0&&(n=ja(n,{axis:"horizontal",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),t.scaleY<0&&(n=ja(n,{axis:"vertical",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),md(qa(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:xd(n.segments)}}}flipSelectionBounds(e,t){const n=((e,t)=>md(qa(ja(Va(Sd(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:xd(n.segments)}}}getSelectionOverlayInfo(e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null}}isWrappedByBrush(e,t){return yd(e).outlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return!!this.isWrappedByBrush(e,t)||!t.isWrapping&&(e=>{const t=new zh(e.minX,e.minY),n=new zh(e.maxX,e.minY),i=new zh(e.maxX,e.maxY),r=new zh(e.minX,e.maxY);return[[t,n],[n,i],[i,r],[r,t]]})(t.brushBounds).some(([t,n])=>this.hitTestLineSegment(e,{pageStart:t,pageEnd:n,positionedStart:t,positionedEnd:n,margin:0}))}getPositionedOutlineVertices(e){return fd(e).outlineVertices}hitTest(e,t){return function(e,t,n,i={}){if(i.isClosed&&void 0!==i.fill&&!C(i.fill)&&e.normalizedPoints.length>=3&&Td(n,e.normalizedPoints.map(Ba)))return!0;if(i.isClosed&&((e,t)=>{if(0===t.length)return Number.POSITIVE_INFINITY;if(1===t.length)return e.dist(Ba(t[0]));let n=Number.POSITIVE_INFINITY;for(let i=1;i<t.length;i+=1){const r=t[i-1],o=t[i];r&&o&&(n=Math.min(n,Cd(e,Ba(r),Ba(o))))}return t.length>=3&&(n=Math.min(n,Cd(e,Ba(t[t.length-1]),Ba(t[0])))),n})(n,e.normalizedPoints)<=Math.max(4,.5*t))return!0;if(0===e.outlineVertices.length)return!1;for(const r of e.outlinePolygons){if(Td(n,r))return!0;if(Bd(n,r)<=Math.max(4,.5*t))return!0}return!1}(fd(e),e.props.strokeWidth,t,{fill:e.props.fill,isClosed:e.props.isClosed})}hitTestLineSegment(e,t){return((e,t,n,i,r={})=>{const o=Math.max(4,.5*t,r.margin??0);return!!(r.isClosed&&void 0!==r.fill&&!C(r.fill)&&e.normalizedPoints.length>=3&&Md(n,i,e.normalizedPoints.map(Ba),o))||0!==e.outlineVertices.length&&e.outlinePolygons.some(e=>Md(n,i,e,o))})(yd(e),e.props.strokeWidth,t.pageStart,t.pageEnd,{fill:e.props.fill,isClosed:e.props.isClosed,margin:t.margin})}repairLoadedShape(e){const t=gd(e);if(0===t.pointBounds.x&&0===t.pointBounds.y&&0===e.rotation&&1===e.scaleX&&1===e.scaleY)return null;const n=(e=>md(Sd(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:xd(n.segments)}}}},Jm=class{type="draw";toSvg(e,t){const n=gd(e);if(!n.path&&!n.selectionPath)return null;const i=[];return n.fillPath&&!C(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}}},ef=[{value:f("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:f("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:f("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:f("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],tf=[{value:"transparent",label:"None",color:"transparent"},{value:f("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:f("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:f("fill-red"),label:"Red",color:"var(--land-shape-fill-red)"},{value:f("fill-white"),label:"White",color:"var(--land-shape-fill-white)"}],nf=[{value:4,label:"4"},{value:6,label:"6"},{value:8,label:"8"},{value:10,label:"10"}],rf=[{value:"open",label:"Open"},{value:"closed",label:"Closed"}],of=Ji({name:"draw",createFeature:()=>({id:"land.draw.bundle",editorPlugins:[{id:"land.draw",shapeCapabilities:[{type:"draw",schemaProps:["segments","stroke","strokeWidth","fill","isClosed","isPen"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Draw stores raw segments as document truth and derives a shared freehand stroke geometry for render, hit test, brush wrap, and SVG export."]}],shapeUtils:[new Qm],shapeSvgExporters:[new Jm],canvasActions:[{id:"draw.set-closed",isVisible:e=>"draw"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>zd(e.selection.selectedShapes),run({context:e,value:t}){const n=Hd(t);if(null===n)return;const i=e.selection.selectedShapes.filter(Ld).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{isClosed:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},Dd("fill"),Dd("stroke"),Dd("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=Hd(t);null!==n&&e.editor.updateDefaultShapeProps("draw",{isClosed:n})}},Ud("fill"),Ud("stroke"),Ud("strokeWidth")],toolbarContributions:[{id:"draw.tool-toolbar",surface:"tool",placement:"chrome",order:45,actionIds:[ng],getGroups:e=>[{id:"draw.tools",items:[{kind:"button",id:"draw.tool.draw",actionId:ng,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:()=>$d({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:()=>$d({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"===zd(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 jm(e),{shortcut:"p"})}}],canvasPlugins:[{id:"land.draw.react",shapeRenderers:[{type:"draw",component:Kd}]}],shapeTypes:["draw"]})}),sf=class extends Ap{constructor(e){super(e,"eraser"),this.initial="idle",this.addChild(new af(e,this)),this.addChild(new df(e,this)),this.addChild(new lf(e,this))}onExit(){Qd(this.editor)}},af=class extends Ap{constructor(e,t){super(e,"idle",t)}onEnter(){Qd(this.editor)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={originPagePoint:t.pagePoint.clone(),previousPagePoint:t.pagePoint.clone(),protectedContainerIds:Nd(e,t.pagePoint),erasingShapeIds:new Set,trail:[t.pagePoint.clone()]};return qd(e,n,t),Zd(e,n),n})(this.editor,e))}},df=class extends Ap{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&&(jd(this.editor,this.info,e),Gd(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),Zd(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(e){this.info&&(qd(this.editor,this.info,e),Zd(this.editor,this.info),Jd(this.editor,this.info)),this.transition("idle")}onCancel(){Qd(this.editor),this.transition("idle")}onExit(){this.info=null}},lf=class extends Ap{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&&Jd(this.editor,this.info),this.transition("idle")}onCancel(){Qd(this.editor),this.transition("idle")}onExit(){this.info=null}update(e){this.info&&(jd(this.editor,this.info,e),Gd(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),Zd(this.editor,this.info))}},cf=ch(()=>Er(Mr().eraserTrailActiveSignal)?Ph(uf,{}):null),uf=ch(()=>{const e=Mr(),t=Er(e.eraserTrailSignal),n=Er(e.cameraZoomSignal),i=Math.max(n,1e-4),r=(()=>{const[e,t]=xh(()=>el());return ph(()=>{if("undefined"==typeof window)return;let e=0;const n=i=>{t(i),e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(e)}},[]),e})(),o=yh({samples:[],sourceLength:0}),s=Math.max(r,el());((e,t,n,i)=>{if(nl(e,i),t.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),t.length===e.sourceLength)return;const r=e.sourceLength,o=t.length-r,s=e.samples[e.samples.length-1]?.time??i-xf*o;for(let a=r;a<t.length;a++){const d=t[a];tl(e,{x:d.x,y:d.y},n,pl(s,i,(a-r+1)/o))}e.sourceLength=t.length,nl(e,i)})(o.current,t,i,s);const a=function(e,t){const n=il(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),i=[e[0]];for(let r=1;r<e.length;r++)i.push(hl(i[i.length-1],e[r],n));return i})(n.length>pf?n.slice(-48):n,ff)}(o.current.samples,s);if(0===a.length)return null;const d=(c=mf/i,0===(l=a).length||c<=0?null:1===l.length?fl(ol(l[0],c/2,yf))??"":fl((e=>{if(0===e.length)return[];if(1===e.length)return ol(e[0].point,Math.max(e[0].radius,.01),yf);const t=[],n=[];for(const a of e){const e=dl(a.direction);ml(t,cl(a.point,ul(e,a.radius))),ml(n,ll(a.point,ul(e,a.radius)))}const i=[];for(const a of t)ml(i,a);const r=e[e.length-1],o=dl(r.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const r=[];for(let o=1;o<Sf;o++){const s=o/Sf;r.push(ll(e,ll(ul(t,Math.sin(Math.PI*s)*i),ul(n,-Math.cos(Math.PI*s)*i))))}return r})({center:r.point,direction:r.direction,normal:o,radius:r.radius});for(const a of s)ml(i,a);for(let a=n.length-1;a>=0;a--)ml(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]+sl(e[n-1],e[n]));return t})(e),i=Math.max(t,n[n.length-1]??0);return e.map((r,o)=>{const s=n[o]??0,a=gl(s/i,0,1);return{point:r,direction:rl(e,o),radius:t/2*a,runningLength:s}})})(l,c))));var l,c;return d?Ph("g",{"data-ui":"eraser-trail-overlay",children:Ph("path",{"data-ui":"eraser-trail-scribble",d:d,fill:hf})}):null}),hf="rgba(142, 142, 142, 0.16)",pf=48,gf=1,mf=12,ff=.32,Sf=8,yf=13,xf=16,bf=8,Pf=180,If=180,wf=680,vf=Ji({name:"eraser",createFeature:()=>({id:"land.eraser.bundle",editorPlugins:[{id:"land.eraser",toolbarContributions:[{id:"eraser.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[ng],getGroups:e=>[{id:"eraser.tools",items:[{kind:"button",id:"eraser.tool.eraser",actionId:ng,value:"eraser",label:"Eraser",shortcut:e.editor.shortcuts.getToolShortcutLabel("eraser"),icon:"eraser",dataUi:"eraser-tool-button"}]}]}],setup(e){e.tools.register("eraser",e=>new sf(e),{shortcut:"e"})}}],canvasPlugins:[{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",layer:"below-host",component:cf}]}],shapeTypes:[]})}),Cf=class extends Mp{type="frame";getDefaultProps(){return{w:640,h:360,name:"Frame",fill:"transparent",stroke:f("stroke-muted"),strokeWidth:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,bl(t.w,n.w)),h:Math.max(1,bl(t.h,n.h)),name:"string"==typeof t.name&&t.name.length>0?t.name:n.name,fill:I(t.fill,n.fill),stroke:I(t.stroke,n.stroke),strokeWidth:Math.max(0,bl(t.strokeWidth,n.strokeWidth))}}getBounds(e){return new Hh(e.x,e.y,e.props.w,e.props.h)}getPointHitTestBounds(e){return this.getBounds(e).expand(3)}canReceiveChildren(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 Pl(this.getBounds(e),t,6)}hitTestLineSegment(e,t){return((e,t,n,i)=>{const r=i/2;if(Pl(e,t,i)||Pl(e,n,i))return!0;const o=[new zh(e.minX,e.minY),new zh(e.maxX,e.minY),new zh(e.maxX,e.maxY),new zh(e.minX,e.maxY)];for(let s=0;s<o.length;s+=1){const e=o[s],i=o[(s+1)%o.length];if(e&&i&&fi(t,n,e,i)<=r)return!0}return!1})(this.getBounds(e),t.positionedStart,t.positionedEnd,Math.max(6,t.margin))}},kf="frame.create",Tf=class extends Ap{constructor(e){super(e,"frame"),this.initial="idle",this.addChild(new Bf(e,this)),this.addChild(new Mf(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("frame")}},Bf=class extends Ap{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})}},Mf=class extends Ap{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(kf)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.editor.history.squashToMark(kf),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(kf),this.transition("idle")}onExit(){this.info=null}updateShape(e,t,n=!1){if(!this.info)return;this.info.currentPagePoint=e.clone(),this.info.shiftKey=t;const i=this.info.originPagePoint.dist(e);if(!this.info.shapeId&&i<4){if(!n)return;const t=(r=e,o=this.tool.getDefaultProps(),new Hh(r.x-o.w/2,r.y-o.h/2,o.w,o.h)),i=this.createShape(t);return void(this.info.shapeId=i.id)}var r,o;const s=((e,t,n,i)=>{let r=t.x-e.x,o=t.y-e.y;if(n){const e=i.w/i.h,t=Math.abs(r),n=Math.abs(o);0===n||t/Math.max(n,1)>=e?o=t/e*(o<0?-1:1):r=n*e*(r<0?-1:1)}const s=new zh(e.x+r,e.y+o);return new Hh(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}},Ef=class{type="frame";toSvg(e,t){const{fill:n,stroke:i,strokeWidth:r,w:o,h:s,name:a}=e.props,d=t.resolveColor(i),l=r/2;return{tag:"g",children:[{tag:"rect",attrs:{x:l,y:l,width:Math.max(o-r,0),height:Math.max(s-r,0),fill:t.resolveColor(n),stroke:d,"stroke-width":r,"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]}]}}},Af=[{value:"transparent",label:"None",color:"transparent"},{value:f("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:f("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:f("fill-amber"),label:"Amber",color:"var(--land-shape-fill-amber)"}],Rf=[{value:f("stroke-muted"),label:"Slate",color:"var(--land-shape-stroke-muted)"},{value:f("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:f("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:f("stroke-orange"),label:"Orange",color:"var(--land-shape-stroke-orange)"}],Ff=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Lf=Ji({name:"frame",createFeature:()=>({id:"land.frame.bundle",editorPlugins:[{id:"land.frame",shapeCapabilities:[{type:"frame",schemaProps:["w","h","name","fill","stroke","strokeWidth"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Frame renderer, SVG exporter, creation tool, selected-frame style toolbar, selected-child order badge, and minimal single-child sibling reorder controls live in the frame plugin package. ParentId-based child query, child-index ordering, containing-parent query, clipped query bounds, point-in-clip checks, host clipping, select-drag containment, export descendant traversal, and clipped child export have preflights. Richer hover/drag reorder UI remains deferred."]}],shapeUtils:[new Cf],shapeSvgExporters:[new Ef],canvasActions:[Il("fill"),Il("stroke"),Il("strokeWidth"),wl("fill"),wl("stroke"),wl("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"})}},Cl("backward"),Cl("forward")],toolbarContributions:[{id:"frame.tool-toolbar",surface:"tool",placement:"chrome",order:60,actionIds:[ng],getGroups:e=>[{id:"frame.tools",items:[{kind:"button",id:"frame.tool.frame",actionId:ng,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:()=>vl({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"}]}]:[],...vl({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"===Tl(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"===Tl(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 Tf(e),{shortcut:"f"})}}],canvasPlugins:[{id:"land.frame.react",shapeRenderers:[{type:"frame",component:Bl}]}],shapeTypes:["frame"]})}),$f="geo.create",Df=class extends Ap{geo;constructor(e,t,n){super(e,t),this.geo=n,this.initial="idle",this.addChild(new Uf(e,this)),this.addChild(new zf(e,this))}getDefaultProps(){return{...this.editor.getDefaultShapeProps("geo"),geo:this.geo}}onEnter(){this.editor.updateDefaultShapeProps("geo",{geo:this.geo})}},Uf=class extends Ap{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})}},zf=class extends Ap{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark($f)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.info.shapeId&&q(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark($f),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark($f),this.transition("idle")}onExit(){this.info=null}updateShape(e,t,n=!1){if(!this.info)return;this.info.currentPagePoint=e.clone(),this.info.shiftKey=t;const i=this.info.originPagePoint.dist(e);if(!this.info.shapeId&&i<4){if(!n)return;const t=(r=e,o=this.tool.getDefaultProps(),new Hh(r.x-o.w/2,r.y-o.h/2,o.w,o.h)),i=this.createShape(t);return void(this.info.shapeId=i.id)}var r,o;const s=((e,t,n)=>{let i=t.x-e.x,r=t.y-e.y;if(n){const e=Math.max(Math.abs(i),Math.abs(r));i=(i<0?-1:1)*e,r=(r<0?-1:1)*e}const o=new zh(e.x+i,e.y+r);return new Hh(Math.min(e.x,o.x),Math.min(e.y,o.y),Math.max(Math.abs(o.x-e.x),1),Math.max(Math.abs(o.y-e.y),1))})(this.info.originPagePoint,e,t);if(!this.info.shapeId){const e=this.createShape(s);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:s.x,y:s.y,props:{w:s.w,h:s.h}}],{source:"user"})}createShape(e){const[t]=this.editor.commands.createShapes([{type:"geo",x:e.x,y:e.y,props:{...this.tool.getDefaultProps(),w:e.w,h:e.h}}],{source:"user"});if(!t)throw new Error("Failed to create geo shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},Hf=class extends Df{constructor(e){super(e,"rectangle","rectangle")}},Yf=class extends Df{constructor(e){super(e,"ellipse","ellipse")}},Of=class extends Df{constructor(e){super(e,"diamond","diamond")}},Kf=class extends Df{constructor(e){super(e,"triangle","triangle")}},Xf=class extends Df{constructor(e){super(e,"hexagon","hexagon")}},Wf=class extends Df{constructor(e){super(e,"star","star")}},Nf=["rectangle","ellipse","diamond","triangle","hexagon","star"],_f=class extends Mp{type="geo";getDefaultProps(){return{w:160,h:108,geo:"rectangle",fill:f("fill-slate"),stroke:f("stroke-slate"),strokeWidth:2}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,Dl(t.w,n.w)),h:Math.max(24,Dl(t.h,n.h)),geo:$l(t.geo)?t.geo:n.geo,fill:I(t.fill,n.fill),stroke:I(t.stroke,n.stroke),strokeWidth:Math.max(1,Dl(t.strokeWidth,n.strokeWidth))}}getBounds(e){return new Hh(e.x,e.y,e.props.w,e.props.h)}getPositionedOutlineVertices(e){return El(this.getBounds(e),e.props.geo)}getHandleSnapGeometry(e){return{points:Kl(e),outline:Ol(e)}}hitTest(e,t){const n=this.getBounds(e);switch(e.props.geo){case"ellipse":{const e=n.w/2,i=n.h/2;if(e<=0||i<=0)return!1;const r=t.x-n.center.x,o=t.y-n.center.y;return r*r/(e*e)+o*o/(i*i)<=1}case"diamond":case"triangle":case"hexagon":case"star":return Rl(t,Al(n,e.props.geo));default:return Rl(t,Al(n,"rectangle"))}}hitTestLineSegment(e,t){const n=this.getBounds(e);switch(e.props.geo){case"ellipse":return((e,t,n,i)=>{const r=e.center,o=e.w/2+i,s=e.h/2+i;if(o<=0||s<=0)return!1;const a=n.sub(t),d=t.sub(r),l=a.x/o,c=a.y/s,u=d.x/o,h=d.y/s,p=l*l+c*c,g=2*(u*l+h*c),m=u*u+h*h-1;if(m<=0)return!0;const f=g*g-4*p*m;if(0===p||f<0)return!1;const S=Math.sqrt(f),y=(-g-S)/(2*p),x=(-g+S)/(2*p);return y>=0&&y<=1||x>=0&&x<=1})(n,t.positionedStart,t.positionedEnd,t.margin);case"rectangle":case"diamond":case"triangle":case"hexagon":case"star":{const i=Al(n,e.props.geo);return this.hitTest(e,t.positionedStart)||this.hitTest(e,t.positionedEnd)||((e,t,n,i)=>{if(n.length<3)return!1;for(let r=0;r<n.length;r+=1){const o=n[r],s=n[(r+1)%n.length];if(o&&s&&Hl(e,t,o,s)<=i)return!0}return!1})(t.positionedStart,t.positionedEnd,i,t.margin)}default:return super.hitTestLineSegment(e,t)}}resolveBindingPoint(e,t){const n=function(e,t,n){const i=new Hh(e.x,e.y,e.props.w,e.props.h);return"ellipse"===e.props.geo?((e,t,n)=>{const i=e.w/2,r=e.h/2;if(i<=0||r<=0)return null;const o=t.sub(e.center),s=n.sub(t),a=s.x/i,d=s.y/r,l=o.x/i,c=o.y/r,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),m=[(-h-g)/(2*u),(-h+g)/(2*u)].filter(e=>e>1e-6&&e<=1).sort((e,t)=>e-t)[0];return void 0===m?null:t.add(s.mul(m))})(i,t,n):((e,t,n)=>{let i=null;for(let r=0;r<n.length;r+=1){const o=n[r],s=n[(r+1)%n.length]??n[0];if(!o||!s)continue;const a=Yl(e,t,o,s);!a||a.t<=1e-6||(!i||a.t<i.t)&&(i=a)}return i?.point??null})(t,n,Al(i,e.props.geo))}(e,_e(e,t.rawPagePoint,this),_e(e,t.oppositePagePoint,this));return n?Ne(e,n,this):t.rawPagePoint}},Vf=class{type="geo";toSvg(e,t){const{geo:n,fill:i,stroke:r,strokeWidth:o,w:s,h:a}=e.props,d=o/2,l=Math.max(s-o,0),c=Math.max(a-o,0),u={fill:t.resolveColor(i),stroke:t.resolveColor(r),"stroke-width":o,"stroke-linejoin":"round","stroke-linecap":"round"};if("ellipse"===n)return{tag:"ellipse",attrs:{...u,cx:s/2,cy:a/2,rx:l/2,ry:c/2}};if("rectangle"!==n){const e=Al(new Hh(d,d,l,c),n).map(e=>`${ql(e.x)},${ql(e.y)}`).join(" ");return{tag:"polygon",attrs:{...u,points:e}}}const h=Math.min(10,.12*l,.12*c);return{tag:"rect",attrs:{...u,x:d,y:d,width:l,height:c,rx:h,ry:h}}}},qf=[{value:f("fill-blue"),label:"Blue",color:"var(--land-shape-fill-blue)"},{value:f("fill-green"),label:"Green",color:"var(--land-shape-fill-green)"},{value:f("fill-red"),label:"Red",color:"var(--land-shape-fill-red)"},{value:f("fill-white"),label:"White",color:"var(--land-shape-fill-white)"}],jf=[{value:f("stroke-blue"),label:"Blue",color:"var(--land-shape-stroke-blue)"},{value:f("stroke-green"),label:"Green",color:"var(--land-shape-stroke-green)"},{value:f("stroke-red"),label:"Red",color:"var(--land-shape-stroke-red)"},{value:f("stroke-slate"),label:"Slate",color:"var(--land-shape-stroke-slate)"}],Gf=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Zf=[{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"}],Qf=Ji({name:"geo",createFeature:()=>({id:"land.geo.bundle",editorPlugins:[{id:"land.geo",shapeCapabilities:[{type:"geo",schemaProps:["w","h","geo","fill","stroke","strokeWidth"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Toolbar covers built-in geo variants through geo props."]}],shapeUtils:[new _f],shapeSvgExporters:[new Vf],canvasActions:[{id:"geo.set-kind",isVisible:e=>"geo"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>(e=>{let t=null;for(const n of e)if(Ll(n))if(null!==t){if(t!==n.props.geo)return null}else t=n.props.geo;return t})(e.selection.selectedShapes),run({context:e,value:t}){if(!$l(t))return;const n=e.selection.selectedShapes.filter(Ll).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{geo:t}}));0!==n.length&&e.editor.commands.updateShapes(n,{source:"user"})}},Xl("fill"),Xl("stroke"),Xl("strokeWidth"),Wl("fill"),Wl("stroke"),Wl("strokeWidth")],toolbarContributions:[{id:"geo.tool-toolbar",surface:"tool",placement:"chrome",order:20,actionIds:[ng],getGroups:e=>[{id:"geo.tools",items:[{kind:"segmented",id:"geo.tool-picker",actionId:ng,options:Zf.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=>Vl(e.tool.activeToolId),getGroups:()=>Nl({fillActionId:"geo.default-fill",strokeActionId:"geo.default-stroke",strokeWidthActionId:"geo.default-strokeWidth",dataUiPrefix:"geo-default"})},{id:"geo.selection-toolbar",surface:"selection",order:20,actionIds:["geo.set-kind","geo.set-fill","geo.set-stroke","geo.set-strokeWidth"],when:e=>"geo"===e.selection.commonShapeType,getGroups:()=>[{id:"geo.shape-kind",items:[{kind:"segmented",id:"geo.shape-kind",actionId:"geo.set-kind",options:Zf.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-shape-button`}))}]},...Nl({fillActionId:"geo.set-fill",strokeActionId:"geo.set-stroke",strokeWidthActionId:"geo.set-strokeWidth",dataUiPrefix:"geo"})]}],setup(e){e.tools.register("rectangle",e=>new Hf(e),{shortcut:"r"}),e.tools.register("ellipse",e=>new Yf(e),{shortcut:"o"}),e.tools.register("diamond",e=>new Of(e),{shortcut:"d"}),e.tools.register("triangle",e=>new Kf(e)),e.tools.register("hexagon",e=>new Xf(e)),e.tools.register("star",e=>new Wf(e))}}],canvasPlugins:[{id:"land.geo.react",shapeRenderers:[{type:"geo",component:jl}]}],shapeTypes:["geo"]})}),Jf=class extends Mp{type="group";getDefaultProps(){return{w:1,h:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Zl(t.w,n.w),h:Zl(t.h,n.h)}}getBounds(e){return new Hh(e.x,e.y,e.props.w,e.props.h)}hitTest(e,t){return!1}shouldTransformDescendants(e){return!0}canReceiveChildren(e){return!0}},eS=class{type="group";toSvg(e){return{tag:"g"}}},tS=Ji({name:"group",createFeature:()=>({id:"land.group.bundle",editorPlugins:[{id:"land.group",shapeCapabilities:[{type:"group",schemaProps:["w","h"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Group is a transparent parent shape. The editor core handles group/ungroup commands, descendant-aware selection transforms, group hit selection bubbling, selected-group child hit selection, descendant export traversal, and child movement through existing parentId queries."]}],shapeUtils:[new Jf],shapeSvgExporters:[new eS]}],canvasPlugins:[{id:"land.group.react",shapeRenderers:[{type:"group",component:Ql}]}],shapeTypes:["group"]})}),nS=1e-4,iS=1e-4,rS="image.crop",oS="image.crop.translate",sS="image.crop:edit:",aS=[{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}],dS={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"},lS=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],cS=new Map,uS=class extends Mp{type="image";getDefaultProps(){return{w:240,h:180,assetId:null,crop:null,altText:""}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,wc(t.w,n.w)),h:Math.max(24,wc(t.h,n.h)),assetId:(i=t.assetId,"string"==typeof i&&i.startsWith("asset:")?t.assetId:null),crop:rc(t.crop),altText:"string"==typeof t.altText?t.altText:n.altText};var i}getBounds(e){return new Hh(e.x,e.y,e.props.w,e.props.h)}getSelectionResizeAspectRatioLock(e,t){return!(!t.isOnlySelected||!Mt(t.handleId))||null}canEdit(e){return!0}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const i=t.editor.getShapeEditingSession();return i&&i.shapeId===e.id&&hc(e,i.markId)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:gc({crop:e.props.crop,localToPage:t.editor.computeShapeLocalToPageTransform(e),shape:e})}:n}},hS="image.replace",pS="image.download-original",gS="image.insert",mS="image.crop",fS="image.crop.done",SS="image.crop.zoom",yS="image.crop.aspect-ratio",xS="image.crop.reset",bS=class{type="image";toSvg(e,t){const{assetId:n,altText:i,crop:r,h:o,w:s}=e.props;if(!n)return null;const a=t.resolveAssetUrl(n);if(!a)return null;const d=oc(r);return d?{tag:"svg",attrs:{x:0,y:0,width:s,height:o,viewBox:(l=d,[fc(l.left),fc(l.top),fc(l.width),fc(l.height)].join(" ")),preserveAspectRatio:"none",overflow:"hidden"},children:[{tag:"image",attrs:{href:a,x:0,y:0,width:1,height:1,preserveAspectRatio:"none","aria-label":i||void 0}}]}:{tag:"image",attrs:{href:a,width:s,height:o,preserveAspectRatio:"none","aria-label":i||void 0}};var l}},PS={id:"land.image.crop.dom-events",handle:()=>"continue",getCursor({clientPoint:e,editor:t,element:n,container:i}){const r=(e=>{const[t]=e.getSelectedShapes();if(!yc(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&hc(t,n.markId)?t:null})(t);if(!r)return;if(n?.closest('[data-selection-custom-handle-type="image.crop"]'))return;if(!e)return;const o=i.getBoundingClientRect(),s=new zh(e.x-o.left,e.y-o.top);return((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n);return i.x>=0&&i.y>=0&&i.x<=t.props.w&&i.y<=t.props.h})(t,r,t.screenToPage(s))?0!==t.inputs.state.get().buttons?"grabbing":"grab":void 0}},IS=Ji({name:"image",createFeature:()=>({id:"land.image.bundle",editorPlugins:[vc()],canvasPlugins:[{id:"land.image.react",domEventGuards:[PS],selectionCustomHandleRenderers:[{type:rS,component:Ec}],shapeRenderers:[{type:"image",component:Bc}]}],shapeTypes:["image"]})}),wS=class extends Ap{constructor(e){super(e,"laser"),this.initial="idle",this.addChild(new vS(e,this)),this.addChild(new CS(e,this)),this.addChild(new kS(e,this))}},vS=class extends Ap{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 Fc(e,n),n})(this.editor,e))}},CS=class extends Ap{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&&(Rc(this.info,e.pagePoint),Fc(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}},kS=class extends Ap{info=null;constructor(e,t){super(e,"drawing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&(Rc(this.info,e.pagePoint),Fc(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}},TS=ch(()=>Er(Mr().laserTrailActiveSignal)?Ph(BS,{}):null),BS=ch(()=>{const e=Mr(),t=Er(e.laserTrailSignal),n=Er(e.cameraZoomSignal),i=Math.max(n,1e-4),r=(()=>{const[e,t]=xh(()=>Lc());return ph(()=>{if("undefined"==typeof window)return;let e=0;const n=i=>{t(i),e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(e)}},[]),e})(),o=yh({sessionId:0,samples:[],sourceLength:0}),s=Math.max(r,Lc());let a,d=[];t&&(((e,t,n,i)=>{t.sessionId!==e.sessionId&&(e.sessionId=t.sessionId,e.samples=[],e.sourceLength=0);const r=t.points;if(Dc(e,i),r.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),r.length===e.sourceLength)return;const o=e.sourceLength,s=r.length-o,a=e.samples[e.samples.length-1]?.time??i-zS*s;for(let d=o;d<r.length;d++){const t=r[d];$c(e,{x:t.x,y:t.y},n,Vc(a,i,(d-o+1)/s))}e.sourceLength=r.length,Dc(e,i)})(o.current,t,i,s),d=function(e,t){const n=Uc(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),i=[e[0]];for(let r=1;r<e.length;r++)i.push(_c(i[i.length-1],e[r],n));return i})(n.length>RS?n.slice(-64):n,$S)}(o.current.samples,s),a=o.current.samples[o.current.samples.length-1]?.time);const l="ending"===t?.phase,c=0===d.length,u=l&&c?t.sessionId:null;if(ph(()=>{null!==u&&e.clearLaserTrail(u)},[e,u]),!t||c)return null;const h=l&&void 0!==a?qc(1-(s-a)/XS,0,1):1,p=(m=LS/i,0===(g=d).length||m<=0?null:1===g.length?Gc(Hc(g[0],m/2,US))??"":Gc((e=>{if(0===e.length)return[];if(1===e.length)return Hc(e[0].point,Math.max(e[0].radius,.01),US);const t=[],n=[];for(const a of e){const e=Kc(a.direction);jc(t,Wc(a.point,Nc(e,a.radius))),jc(n,Xc(a.point,Nc(e,a.radius)))}const i=[];for(const a of t)jc(i,a);const r=e[e.length-1],o=Kc(r.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const r=[];for(let o=1;o<DS;o++){const s=o/DS;r.push(Xc(e,Xc(Nc(t,Math.sin(Math.PI*s)*i),Nc(n,-Math.cos(Math.PI*s)*i))))}return r})({center:r.point,direction:r.direction,normal:o,radius:r.radius});for(const a of s)jc(i,a);for(let a=n.length-1;a>=0;a--)jc(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]+Yc(e[n-1],e[n]));return t})(e),i=Math.max(t,n[n.length-1]??0);return e.map((r,o)=>{const s=n[o]??0,a=qc(s/i,0,1);return{point:r,direction:zc(e,o),radius:t/2*a,runningLength:s}})})(g,m))));var g,m;return p?Ih("g",{"data-ui":"laser-trail-overlay",style:{opacity:h},children:[Ph("path",{"data-ui":"laser-trail-glow",d:p,fill:ES,style:{filter:`blur(${AS/i}px)`}}),Ph("path",{"data-ui":"laser-trail-beam",d:p,fill:MS})]}):null}),MS="rgb(255, 38, 38)",ES="rgba(255, 48, 48, 0.55)",AS=4,RS=64,FS=1,LS=12,$S=.32,DS=8,US=13,zS=16,HS=8,YS=600,OS=300,KS=1400,XS=400,WS=[["geo",Qf],["draw",of],["arrow",Km],["eraser",vf],["laser",Ji({name:"laser",createFeature:()=>({id:"land.laser.bundle",editorPlugins:[{id:"land.laser",toolbarContributions:[{id:"laser.tool-toolbar",surface:"tool",placement:"chrome",order:55,actionIds:[ng],getGroups:e=>[{id:"laser.tools",items:[{kind:"button",id:"laser.tool.laser",actionId:ng,value:"laser",label:"Laser",shortcut:e.editor.shortcuts.getToolShortcutLabel("laser"),icon:"wand",dataUi:"laser-tool-button"}]}]}],setup(e){e.tools.register("laser",e=>new wS(e),{shortcut:"l"})}}],canvasPlugins:[{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",layer:"below-host",component:TS}]}],shapeTypes:[]})})],["image",IS],["text",Em],["frame",Lf],["group",tS]],NS="land.canvas.persistence",_S="snapshots",VS="imageBlobs",qS=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,mu(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()}},jS="image-blob:",GS=ch(({editor:e,hostBridge:t,imageAssetService:n,flushSnapshot:i})=>{const r=yh(null),o=yh(null),{insertImageFromFile:s,replaceSelectedImage:a}=(({editor:e,imageAssetService:t,flushSnapshot:n})=>({insertImageFromFile:uh(async({file:i,pagePoint:r,size:o,source:s})=>Ru({editor:e,file:i,imageObjectUrls:t.objectUrls,pagePoint:r,size:o,flushSnapshot:n,source:s}),[e,t,n]),replaceSelectedImage:uh(i=>Fu({editor:e,file:i,imageObjectUrls:t.objectUrls,flushSnapshot:n}),[e,t,n])}))({editor:e,imageAssetService:n,flushSnapshot:i});return ph(()=>{if(t)return t.register({openInsertFilePicker(){r.current?.click()},openReplaceFilePicker(){o.current?.click()}})},[t]),ph(()=>{const t=t=>{if(e.shapeEditingStateSignal.get().session)return;if(Vr(t.target))return;const n=Bu(t.clipboardData);n&&(t.preventDefault(),s({file:n,source:"paste"}))},n=t=>{var n;e.shapeEditingStateSignal.get().session||Vr(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(Vr(t.target))return;const n=Bu(t.dataTransfer);n&&(t.preventDefault(),s({file:n,pagePoint:Mu(e,t),source:"drop"}))};return window.addEventListener("paste",t),window.addEventListener("dragover",n),window.addEventListener("drop",i),()=>{window.removeEventListener("paste",t),window.removeEventListener("dragover",n),window.removeEventListener("drop",i)}},[e,s]),Ih(bh,{children:[Ph("input",{ref:r,type:"file",accept:"image/*",hidden:!0,"data-ui":"insert-image-file-input",onChange:e=>{const t=e.currentTarget.files?.[0]??null;e.currentTarget.value="",t&&s({file:t,source:"file-picker"})}}),Ph("input",{ref:o,type:"file",accept:"image/*",hidden:!0,"data-ui":"replace-image-file-input",onChange:e=>{const t=e.currentTarget.files?.[0]??null;e.currentTarget.value="",t&&a(t)}})]})}),ZS=Du("canvas-kit.clipboard-service"),QS="system.clipboard.copy",JS="system.clipboard.cut",ey="system.clipboard.paste",ty="system.clipboard.paste-at-point",ny=[{actionId:QS,shortcut:{key:"c",accelKey:!0}},{actionId:JS,shortcut:{key:"x",accelKey:!0}},{actionId:ey,shortcut:{key:"v",accelKey:!0}}],iy="system.view.zoom-in",ry="system.view.zoom-out",oy="system.view.reset-zoom",sy=[{id:iy,run({context:e}){e.editor.zoomAtViewportCenter(-120,"system")}},{id:ry,run({context:e}){e.editor.zoomAtViewportCenter(120,"system")}},{id:oy,run({context:e}){e.editor.resetZoom("user")}}],ay="system.selection.delete",dy="system.selection.duplicate",ly="system.selection.group",cy="system.selection.select-all",uy="system.selection.ungroup",hy="system.selection.reset-rotation",py="system.selection.flip-horizontal",gy="system.selection.flip-vertical",my="system.selection.send-to-back",fy="system.selection.send-backward",Sy="system.selection.bring-forward",yy="system.selection.bring-to-front",xy="system.selection.set-opacity",by=[{actionId:dy,shortcut:{key:"d",accelKey:!0}},{actionId:cy,shortcut:{key:"a",accelKey:!0}}],Py=[{id:ng,getValue:e=>e.tool.activeToolId,run({context:e,value:t}){"string"==typeof t&&e.editor.tools.hasTool(t)&&e.editor.setActiveTool(t,"system")}},{id:ig,getValue:e=>e.tool.isToolLocked,run({context:e}){e.editor.toggleToolLocked("system")}},{id:dy,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.duplicateSelection({source:"user"})}},{id:cy,isEnabled:e=>e.editor.getCurrentPageShapeIds().length>0,run({context:e}){e.editor.selectAllCurrentPage("user")}},{id:ly,isVisible:e=>e.selection.count>1,isEnabled:e=>e.editor.canGroupSelection(),run({context:e}){e.editor.groupSelection("user")}},{id:uy,isVisible:e=>e.editor.canUngroupSelection(),isEnabled:e=>e.editor.canUngroupSelection(),run({context:e}){e.editor.ungroupSelection("user")}},{id:hy,isVisible:e=>e.selection.canResetRotation,run({context:e}){e.editor.resetSelectionRotation("user")}},{id:py,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("horizontal","user")}},{id:gy,isVisible:e=>e.selection.count>0,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.flipSelection("vertical","user")}},{id:my,isVisible:e=>e.selection.count>0&&!Ku(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("back","user")}},{id:fy,isVisible:e=>e.selection.count>0&&!Ku(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("backward"),run({context:e}){e.editor.moveSelectionInParentOrder("backward","user")}},{id:Sy,isVisible:e=>e.selection.count>0&&!Ku(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionInParentOrder("forward","user")}},{id:yy,isVisible:e=>e.selection.count>0&&!Ku(e),isEnabled:e=>e.editor.canMoveSelectionInParentOrder("forward"),run({context:e}){e.editor.moveSelectionToParentOrderEdge("front","user")}},{id:xy,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=Xu(t.opacity);return e.selection.selectedShapes.every(e=>Xu(e.opacity)===n)?n:null})(e),run({context:e,value:t}){if("number"!=typeof t||!Number.isFinite(t))return;const n=Xu(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:ay,isEnabled:e=>e.selection.count>0,run({context:e}){e.editor.deleteSelection("user")}}],Iy=[ng,ig,QS,JS,ey,ty,dy,cy,ay,ly,uy,hy,py,gy,my,fy,Sy,yy,oy,iy,ry],wy=[{id:"system.select-tool-toolbar",surface:"tool",placement:"chrome",order:0,actionIds:[ng],getGroups:e=>[{id:"system.select-tool",items:[{kind:"button",id:"system.select-tool",actionId:ng,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:ng,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:[ig],getGroups:e=>[{id:"system.tool-lock",items:[{kind:"separator",id:"system.tool-lock-separator"},{kind:"button",id:"system.tool-lock",actionId:ig,value:!0,label:e.tool.isToolLocked?"Unlock tool":"Lock tool",icon:"lock",dataUi:"tool-lock-button"}]}]},{id:"system.selection-toolbar",surface:"selection",order:1e3,actionIds:[hy,py,gy,my,fy,Sy,yy,xy,ly,uy,ay],getGroups(e){const t=e.selection.count>0&&!Ku(e);return[{id:"system.selection-opacity",items:[{kind:"slider",id:"system.selection-opacity",actionId:xy,label:"Opacity",min:0,max:1,step:.01,dataUi:"selection-opacity-slider"}]},{id:"system.selection-actions",items:[...e.selection.canResetRotation?[{kind:"button",id:hy,actionId:hy,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:py,actionId:py,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"flip-selection-horizontal-button"},{kind:"button",id:gy,actionId:gy,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"flip-selection-vertical-button"},{kind:"separator",id:"system.selection.flip-order-separator"},...t?[{kind:"button",id:my,actionId:my,label:"Send to back",icon:"chevrons-down",dataUi:"send-selection-to-back-button"},{kind:"button",id:fy,actionId:fy,label:"Send backward",icon:"move-down",dataUi:"send-selection-backward-button"},{kind:"button",id:Sy,actionId:Sy,label:"Bring forward",icon:"move-up",dataUi:"bring-selection-forward-button"},{kind:"button",id:yy,actionId:yy,label:"Bring to front",icon:"chevrons-up",dataUi:"bring-selection-to-front-button"},{kind:"separator",id:"system.selection.order-delete-separator"}]:[],{kind:"button",id:ly,actionId:ly,label:"Group",icon:"group",dataUi:"group-selection-button"},{kind:"button",id:uy,actionId:uy,label:"Ungroup",icon:"ungroup",dataUi:"ungroup-selection-button"},{kind:"separator",id:"system.selection.group-delete-separator"},{kind:"button",id:ay,actionId:ay,label:"Delete selection",icon:"trash-2",dataUi:"delete-selection-toolbar-button"}]}]}}],vy=[{id:"system.selection-clipboard-context-menu",target:"selection",order:1e3,actionIds:[QS,JS],getSections:e=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:QS,actionId:QS,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(QS),dataUi:"context-menu-copy-selection-button"},{kind:"command",id:JS,actionId:JS,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(JS),dataUi:"context-menu-cut-selection-button"}]}]},{id:"system.canvas-clipboard-context-menu",target:"canvas",order:1e3,actionIds:[ty],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:ty,actionId:ty,label:"Paste here",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(ey),dataUi:"context-menu-paste-here-button"}]}]},{id:"system.selection-context-menu",target:"selection",order:1010,actionIds:[dy,ly,uy,hy,py,gy,yy,Sy,fy,my,ay],getSections(e){const t=e.selection.count>0&&!Ku(e),n=[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:dy,actionId:dy,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(dy),dataUi:"context-menu-duplicate-selection-button"},{kind:"separator",id:"system.selection-clipboard-separator"},{kind:"command",id:ly,actionId:ly,label:"Group",icon:"group",dataUi:"context-menu-group-selection-button"},{kind:"command",id:uy,actionId:uy,label:"Ungroup",icon:"ungroup",dataUi:"context-menu-ungroup-selection-button"},{kind:"command",id:ay,actionId:ay,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:hy,actionId:hy,label:"Reset rotation",icon:"rotate-ccw",dataUi:"context-menu-reset-rotation-button"},{kind:"command",id:py,actionId:py,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"context-menu-flip-horizontal-button"},{kind:"command",id:gy,actionId:gy,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:yy,actionId:yy,label:"Bring to front",icon:"chevrons-up",dataUi:"context-menu-bring-to-front-button"},{kind:"command",id:Sy,actionId:Sy,label:"Bring forward",icon:"move-up",dataUi:"context-menu-bring-forward-button"},{kind:"command",id:fy,actionId:fy,label:"Send backward",icon:"move-down",dataUi:"context-menu-send-backward-button"},{kind:"command",id:my,actionId:my,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:[cy],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:cy,actionId:cy,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(cy),dataUi:"context-menu-select-all-button"}]}]},{id:"system.canvas-view-context-menu",target:"canvas",order:1010,actionIds:[iy,ry,oy],getSections:()=>[{id:"system.canvas-view",title:"View",order:10,items:[{kind:"command",id:iy,actionId:iy,label:"Zoom in",icon:"plus",dataUi:"context-menu-zoom-in-button"},{kind:"command",id:ry,actionId:ry,label:"Zoom out",icon:"minus",dataUi:"context-menu-zoom-out-button"},{kind:"command",id:oy,actionId:oy,label:"Reset zoom",icon:"rotate-ccw",dataUi:"context-menu-reset-zoom-button"}]}]},{id:"system.canvas-tool-context-menu",target:"canvas",order:1020,actionIds:[ng],getSections:e=>[{id:"system.canvas-tools",title:"Tools",order:20,items:[{kind:"command",id:"system.canvas.select-tool",actionId:ng,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:ng,value:"hand",label:"Hand tool",icon:"hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),dataUi:"context-menu-hand-tool-button"}]}]}],Cy=Du("plugin-image.asset-service"),ky={id:"plugin-image.product-controller"},Ty=class{handlers=null;register(e){return this.handlers=e,()=>{this.handlers===e&&(this.handlers=null)}}openInsertFilePicker(){this.handlers?.openInsertFilePicker()}openReplaceFilePicker(){this.handlers?.openReplaceFilePicker()}},By=Du("plugin-image.toolbar-host-bridge"),My=["select","hand","rectangle","ellipse","diamond","triangle","hexagon","star","arrow","draw","text","frame","eraser","laser"],Ey=new Set(My),Ay=My.map(e=>`"${e}"`).join(", "),Ry=new Set,Fy={readyRuntime:null,status:null},Ly=Symbol("CanvasKitProduct");export{My as CANVAS_KIT_TOOL_IDS,Is as CanvasKitFloatingToolbarLayer,sh as CanvasKitRoot,mg as DEFAULT_TEXT_FONT,vs as FloatingSelectionToolbarPageSpace,fg as HOST_TEXT_FONT,qu as createCanvasKitController,ju as createCanvasKitControllerWithTools,S as createCustomShapeColor,Pr as createDefaultTextExtensionOptions,Ir as createDefaultTextFontCatalog,f as createThemeShapeColor,ih as defineCanvasKit,P as getThemeColorTokenName,x as isCustomShapeColorRef,y as isThemeShapeColorRef,v as resolveShapeColor,w as shapeColorToCssColor};