@yuzhouu/canvas-kit 0.1.3 → 0.1.4

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 (302) 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} +9 -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 +1 -1
  170. package/_vendor/plugin-text/editor.d.ts +2 -0
  171. package/_vendor/plugin-text/feature.d.ts +2 -2
  172. package/_vendor/plugin-text/host/RichTextToolbar.d.ts +3 -1
  173. package/_vendor/plugin-text/host/richTextBubbleMenuPositionSync.d.ts +7 -0
  174. package/_vendor/plugin-text/textShapeSvgExporter.d.ts +6 -0
  175. package/_vendor/plugin-text/textTypes.d.ts +2 -2
  176. package/_vendor/store/index.d.ts +1 -1
  177. package/_vendor/store/{Store.d.ts → store.d.ts} +7 -1
  178. package/browser/localSnapshotRestore.d.ts +13 -0
  179. package/{_vendor/canvas-product-react/persistence/localSnapshotPersistence.d.ts → browser/persistence.d.ts} +16 -10
  180. package/builtins/controller/createBuiltInCanvasController.d.ts +16 -0
  181. package/builtins/controller/layerController.d.ts +9 -0
  182. package/builtins/controller/shapeCreationController.d.ts +74 -0
  183. package/builtins/extensions.d.ts +15 -0
  184. package/builtins/index.d.ts +5 -0
  185. package/chrome/CanvasKitFloatingToolbarLayer.d.ts +6 -0
  186. package/chrome/FloatingSelectionToolbarPageSpace.d.ts +9 -0
  187. package/chrome/bindings/useCanvasKitChromeControls.d.ts +27 -0
  188. package/chrome/bindings/useContextMenuSurface.d.ts +12 -0
  189. package/chrome/bindings/useSvgExport.d.ts +15 -0
  190. package/chrome/bindings/useToolbarSurfaces.d.ts +26 -0
  191. package/chrome/types.d.ts +66 -0
  192. package/chrome/useCanvasKitChromeContext.d.ts +19 -0
  193. package/controller/canvasKitController.d.ts +36 -0
  194. package/{_vendor/canvas-product-react/api/canvasProductApi.d.ts → core/controller/canvasProductController.d.ts} +11 -21
  195. package/core/controller/featureControllerRegistry.d.ts +12 -0
  196. package/core/controller/index.d.ts +4 -0
  197. package/core/controller/productLayerTree.d.ts +10 -0
  198. package/core/features/actions/canvasActionContext.d.ts +15 -0
  199. package/core/features/actions/canvasActions.d.ts +26 -0
  200. package/core/features/clipboard/clipboardContextMenuContributions.d.ts +2 -0
  201. package/core/features/clipboard/clipboardContribution.d.ts +19 -0
  202. package/{_vendor/canvas-product-react/capabilities → core/features}/clipboard/clipboardService.d.ts +3 -2
  203. package/core/features/context-menu/contextMenuActions.d.ts +12 -0
  204. package/core/features/context-menu/contextMenuContext.d.ts +6 -0
  205. package/core/features/context-menu/contextMenuContribution.d.ts +4 -0
  206. package/core/features/context-menu/viewContextMenuContributions.d.ts +2 -0
  207. package/{_vendor/canvas-product-react/capabilities/export/useSvgExport.d.ts → core/features/export/svgExport.d.ts} +11 -7
  208. package/core/features/hostActionIds.d.ts +1 -0
  209. package/core/features/toolbar/selectionContextMenuContributions.d.ts +2 -0
  210. package/core/features/toolbar/toolContextMenuContributions.d.ts +2 -0
  211. package/core/features/toolbar/toolbarContribution.d.ts +4 -0
  212. package/core/features/toolbar/toolbarLabels.d.ts +8 -0
  213. package/core/index.d.ts +23 -0
  214. package/core/runtime/productAssets.d.ts +18 -0
  215. package/core/runtime/productContributions.d.ts +9 -0
  216. package/core/runtime/productDefinition.d.ts +32 -0
  217. package/core/runtime/productEditor.d.ts +3 -0
  218. package/core/runtime/productHost.d.ts +17 -0
  219. package/{_vendor/canvas-product-react → core}/runtime/productServices.d.ts +1 -2
  220. package/{_vendor/plugin-image-product-react → features/image}/ImageImportController.d.ts +2 -2
  221. package/{_vendor/plugin-image-product-react → features/image}/imageAssetService.d.ts +2 -2
  222. package/{_vendor/plugin-image-product-react → features/image}/imageBlobStore.d.ts +1 -1
  223. package/features/image/imageFileHelpers.d.ts +35 -0
  224. package/{_vendor/plugin-image-product-react → features/image}/imageHostActions.d.ts +13 -12
  225. package/features/image/imageHostExtension.d.ts +5 -0
  226. package/features/image/imageProductController.d.ts +22 -0
  227. package/features/image/imageProductToolbarActions.d.ts +2 -0
  228. package/{_vendor/plugin-image-product-react → features/image}/imageToolbarHostBridge.d.ts +2 -2
  229. package/{_vendor/plugin-image-product-react → features/image}/index.d.ts +4 -5
  230. package/{_vendor/plugin-image-product-react → features/image}/svgImageAssetInliner.d.ts +1 -1
  231. package/{_vendor/plugin-image-product-react → features/image}/useImageImport.d.ts +5 -4
  232. package/index.css +1 -2
  233. package/index.d.ts +12 -14
  234. package/index.mjs +66 -1
  235. package/package.json +1 -11
  236. package/product/canvasKitProduct.d.ts +59 -0
  237. package/react/CanvasKitPersistenceNotice.d.ts +4 -0
  238. package/react/CanvasKitRoot.d.ts +5 -0
  239. package/react/useCanvasKitController.d.ts +5 -0
  240. package/{product/useCanvasClipboardShortcuts.d.ts → react/useCanvasKitKeyboardShortcuts.d.ts} +1 -1
  241. package/react/useCanvasKitRuntime.d.ts +4 -0
  242. package/react/useCanvasKitStartup.d.ts +9 -0
  243. package/runtime/canvasKitHostExtensions.d.ts +19 -0
  244. package/runtime/canvasKitRuntime.d.ts +19 -0
  245. package/runtime/canvasKitRuntimeInitializer.d.ts +11 -0
  246. package/_vendor/canvas-core/bindings/arrow/arrowBindingHelpers.d.ts +0 -28
  247. package/_vendor/canvas-core/tools/hand/HandTool.d.ts +0 -5
  248. package/_vendor/canvas-core/tools/select/SelectTool.d.ts +0 -5
  249. package/_vendor/canvas-product-react/api/apiRegistry.d.ts +0 -12
  250. package/_vendor/canvas-product-react/api/index.d.ts +0 -4
  251. package/_vendor/canvas-product-react/capabilities/clipboard/systemClipboard.d.ts +0 -16
  252. package/_vendor/canvas-product-react/capabilities/context-menu/systemContextMenu.d.ts +0 -17
  253. package/_vendor/canvas-product-react/capabilities/context-menu/useContextMenuSurface.d.ts +0 -12
  254. package/_vendor/canvas-product-react/capabilities/history/useHistoryControls.d.ts +0 -8
  255. package/_vendor/canvas-product-react/capabilities/pages/usePageControls.d.ts +0 -12
  256. package/_vendor/canvas-product-react/capabilities/toolbar/systemToolbar.d.ts +0 -32
  257. package/_vendor/canvas-product-react/capabilities/toolbar/useToolbarSurfaces.d.ts +0 -19
  258. package/_vendor/canvas-product-react/capabilities/zoom/useZoomControls.d.ts +0 -9
  259. package/_vendor/canvas-product-react/index.d.ts +0 -24
  260. package/_vendor/canvas-product-react/persistence/index.d.ts +0 -2
  261. package/_vendor/canvas-product-react/runtime/CanvasProductRoot.d.ts +0 -4
  262. package/_vendor/canvas-product-react/runtime/productDefinition.d.ts +0 -45
  263. package/_vendor/plugin-draw/core.d.ts +0 -7
  264. package/_vendor/plugin-eraser/core.d.ts +0 -2
  265. package/_vendor/plugin-frame/core.d.ts +0 -7
  266. package/_vendor/plugin-geo/core.d.ts +0 -7
  267. package/_vendor/plugin-group/core.d.ts +0 -7
  268. package/_vendor/plugin-image-product-react/imageProductApi.d.ts +0 -21
  269. package/_vendor/plugin-image-product-react/imageToolbarRuntime.d.ts +0 -2
  270. package/_vendor/plugin-image-product-react/snapshotGuards.d.ts +0 -1
  271. package/_vendor/plugin-laser/core.d.ts +0 -2
  272. package/_vendor/plugin-text/TextShapeSvgExporter.d.ts +0 -6
  273. package/_vendor/plugin-text/core.d.ts +0 -2
  274. package/api/canvasKitApi.d.ts +0 -29
  275. package/product/Shell.d.ts +0 -19
  276. package/product/chromeContext.d.ts +0 -70
  277. package/product/createCanvasKitEditor.d.ts +0 -6
  278. package/product/index.d.ts +0 -7
  279. package/product/persistence.d.ts +0 -3
  280. package/product/product.d.ts +0 -22
  281. package/product-CxN5NN6u.mjs +0 -4
  282. package/product.mjs +0 -1
  283. package/standard/extensions.d.ts +0 -1
  284. package/standard/index.d.ts +0 -3
  285. package/standard/standardApi.d.ts +0 -91
  286. package/standard-R17_x8HU.mjs +0 -44
  287. package/standard.mjs +0 -1
  288. /package/_vendor/canvas-core/editor/managers/{SideEffectManager.d.ts → sideEffectManager.d.ts} +0 -0
  289. /package/_vendor/canvas-core/geometry/{Vec.d.ts → vec.d.ts} +0 -0
  290. /package/_vendor/canvas-react/host/{CanvasRendererRegistryContext.d.ts → canvasRendererRegistryContext.d.ts} +0 -0
  291. /package/_vendor/plugin-arrow/{ArrowBindingUtil.d.ts → arrowBindingUtil.d.ts} +0 -0
  292. /package/_vendor/plugin-arrow/{ArrowTool.d.ts → arrowTool.d.ts} +0 -0
  293. /package/_vendor/plugin-draw/{DrawShapeUtil.d.ts → drawShapeUtil.d.ts} +0 -0
  294. /package/_vendor/plugin-draw/{DrawTool.d.ts → drawTool.d.ts} +0 -0
  295. /package/_vendor/plugin-eraser/{EraserTool.d.ts → eraserTool.d.ts} +0 -0
  296. /package/_vendor/plugin-geo/{GeoShapeUtil.d.ts → geoShapeUtil.d.ts} +0 -0
  297. /package/_vendor/plugin-group/{GroupShapeUtil.d.ts → groupShapeUtil.d.ts} +0 -0
  298. /package/_vendor/plugin-laser/{LaserTool.d.ts → laserTool.d.ts} +0 -0
  299. /package/_vendor/plugin-text/{ArrowLabelBindingUtil.d.ts → arrowLabelBindingUtil.d.ts} +0 -0
  300. /package/_vendor/plugin-text/{GeoLabelBindingUtil.d.ts → geoLabelBindingUtil.d.ts} +0 -0
  301. /package/_vendor/plugin-text/{TextShapeUtil.d.ts → textShapeUtil.d.ts} +0 -0
  302. /package/_vendor/plugin-text/{TextTool.d.ts → textTool.d.ts} +0 -0
@@ -1,44 +0,0 @@
1
- function e(){return Sc}function t(){return++Sc}function n(e){xc={child:e,parentSet:new Set,below:xc}}function i(){if(!xc)throw new Error("Cannot stop dependency capture because no capture is active");const e=xc;return xc=e.below,e.parentSet}function r(e){xc&&(xc.parentSet.add(e),e.children.add(xc.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 Ic(e,t,n?.isEqual)}function a(e,t,n){return new wc(e,t,n?.isEqual)}function d(){return{id:Tc,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function l(e=Tc){return{id:Mc,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...Ec}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function c(e){return!!e&&"page"===e.typeName}function h(e){return!!e&&"shape"===e.typeName}function u(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,t,n){let i=e.computeShapeExportPageBounds(t);if(!b(i))return i;for(const r of((e,t,n)=>{const i=[];for(const r of y(e,t,n)){const t=I(e,r);t&&b(t)&&i.push(t)}return i})(e,t,n)){const e=P(i,r);if(!e)return null;i=e}return i}function S(e,t,n,i,r){const o=[];for(const s of y(e,t,n)){const t=x(e,s,i,r);t&&o.push(t)}return o}function y(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 x(e,t,n,i){if(n.has(t.id))return n.get(t.id)??null;const r=e.getShapeUtil(t).getChildExportClipLocalBounds(t);if(!r||!b(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 I(e,t){const n=e.getShapeUtil(t).getChildExportClipLocalBounds(t);if(!n||!b(n))return null;const i=e.computeShapeExportToPageTransform(t);return kc.FromPoints([new Cc(n.minX,n.minY),new Cc(n.maxX,n.minY),new Cc(n.maxX,n.maxY),new Cc(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))}function P(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 kc(n,i,r-n,o-i)}function w(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}="${v("number"==typeof i?C(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(w).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function b(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function v(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function C(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function k(e){return e[Fc]}function B({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?(T(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 k(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 T(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 M(e){return e.added.length>0||e.updated.length>0||e.removed.length>0}function E(e){return e instanceof Map?new Map(e):new Map(Array.from(e,e=>[e.id,e]))}function A(e,t){const n=E(e),i=E(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 R(e){return{added:[...e.removed],updated:e.updated.map(e=>({before:e.after,after:e.before})),removed:[...e.added]}}function F(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 L(e,t){return{id:e.id,forward:F(e.forward,t),parentIds:e.parentIds}}function $(e,t){return{forward:t,inverse:R(t),label:e}}function D(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function z(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 Y(e,t,n){const i=n?.source??"user";k(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=i.isHidden??t.isHidden,h=i.isLocked??t.isLocked,u=i.parentId??t.parentId,p=i.index??t.index;if(!e.canUseShapeParent(u,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.isHidden&&h===t.isLocked&&u===t.parentId&&p===t.index)continue;const g=e.shapeUtils.get(t.type),m={...t,x:o,y:s,rotation:a,scaleX:d,scaleY:l,isHidden:c,isLocked:h,parentId:u,index:p,props:i.props?g.validateProps({...t.props,...i.props}):t.props};n.push(m),r.push({before:t,after:m})}0!==n.length&&(k(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)X(e,a.before,r),X(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&&(k(e).put(o,n),e.bindings.handleShapeChanges(s,n))})(e,r,i))},i)}function X(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 U(e,t,n){const i=n?.source??"user",r=e.getShapeIdsIncludingDescendants(t),o=e.getUnreferencedAssetIdsAfterShapeDelete(r);k(e).atomic(()=>{e.sideEffects.runBeforeDelete("shape",r,i),k(e).remove(r,i),o.length>0&&k(e).remove(o,i),e.sideEffects.runAfterDelete("shape",r,i)},i)}function H(e,t){return e.bindings.canBind(t)}function W(e){return Math.min(8,Math.max(.1,e))}function N(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 O(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function K(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 _(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 q(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function V(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 G(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 j(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 Z(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||!_(i.bounds,r.bounds))return!1}return!0}function Q(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 J(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function ee(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)=>ee(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)&&ee(n[e],i[e]))}function te(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(he);return 0===r.length?null:{type:"land/clipboard",version:1,source:{app:"land"},rootShapeIds:t,records:{shapes:r,bindings:ie(e,r,i),assets:re(e,r)},bounds:oe(e,n)}}function ne(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 Cc(t.x+t.w/2,t.y+t.h/2)):e.offset??Xc})(t),s=new Map,a=new Map,d=[];k(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=e.createAssetRecord({type:t.type,props:ce(t.props),meta:ce(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)=>le(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:ce(t.meta)});return a.set(t.id,i.id),{original:t,draft:i}}).map(({original:e,draft:t})=>({...t,parentId:se(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:ce(r.props),meta:ce(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 ie(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(he(t)));return i}function re(e,t){const n=[],i=new Set;for(const r of t)for(const t of ae(r)){if(i.has(t))continue;const r=e.getAsset(t);r&&(i.add(t),n.push(he(r)))}return n}function oe(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 kc(t,n,i-t,r-n)})(t.map(t=>e.getShapePageBounds(t)).filter(e=>!!e))??new kc(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function se(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function ae(e){const t=[],n=new Set,i=J(e);return i&&(n.add(i),t.push(i)),de(e.props,n,t),t}function de(e,t,n){if(ue(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)de(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))de(i,t,n)}function le(e,t){if(ue(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>le(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[i,r]of Object.entries(e))n[i]=le(r,t);return n}function ce(e){return he(e)}function he(e){if(Array.isArray(e))return e.map(he);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=he(i);return t}function ue(e){return"string"==typeof e&&e.startsWith("asset:")}function pe(e,t,n,i,r="document"){if(t>n)throw new Hc(`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 Hc(`No ${r} snapshot migration from schema version ${s}`);o=e.up(o)}return o}function ge(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function me(e,t){return"string"==typeof e?e:t}function fe(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Se(e,t){return"boolean"==typeof e?e:t}function ye(e){return ge(e)?e:{}}function xe(e){return ge(e)?{x:fe(e.x,Ec.x),y:fe(e.y,Ec.y),z:Math.min(8,Math.max(.1,fe(e.z,Ec.z)))}:null}function Ie(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function Pe(e,t){if(!ge(e))throw new Hc(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=fe(n,NaN);if(!Number.isFinite(i)||i<1)throw new Hc(`Unsupported ${t} snapshot schema version: ${String(n)}`);if(!Array.isArray(e.records))throw new Hc(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:1,records:pe(e.records,i,1,"document"===t?Wc:Nc,t)}}function we(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)),h=new Map(c.map(e=>[e.id,e])),u=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:h,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(u.map(e=>e.id)),f=r.filter(e=>m.has(e.fromId)&&m.has(e.toId));return[...s,...o,...u,...f]}function be(e,t,n){const i=Pe(e,"document"),r=new Set,o=[];return i.records.forEach((e,i)=>{if(!ge(e))throw new Hc("Invalid document record: expected object");if("string"!=typeof e.id)throw new Hc("Invalid document record id");if(r.has(e.id))throw new Hc(`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 Hc(`Unsupported document record type: ${String(e.typeName)}`);o.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new Hc("Invalid asset record id");if("string"!=typeof e.type)throw new Hc("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:ge(e.props)?e.props:{},meta:ye(e.meta)}})(e))}else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new Hc("Invalid binding record id");if("string"!=typeof e.type)throw new Hc("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new Hc(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new Hc(`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:ye(e.meta)}})(e,n));else o.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new Hc("Invalid shape record id");if("string"!=typeof e.type)throw new Hc("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new Hc(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:me(e.index,String(n+1).padStart(6,"0")),x:fe(e.x,0),y:fe(e.y,0),rotation:fe(e.rotation,0),scaleX:fe(e.scaleX,1),scaleY:fe(e.scaleY,1),opacity:Math.min(1,Math.max(0,fe(e.opacity,1))),isHidden:Se(e.isHidden,!1),isLocked:Se(e.isLocked,!1),meta:ye(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 Hc("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:me(e.name,`Page ${t+1}`),index:me(e.index,String(t+1).padStart(4,"0")),meta:ye(e.meta)}})(e,i))}),{schemaVersion:1,records:we(o,t)}}function ve(e){const t=Pe(e,"session").records[0];if(!ge(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(!ge(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,xe(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),o=(e=>{if(!ge(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Ie(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:me(t.activeToolId,n.activeToolId),isToolLocked:"boolean"==typeof t.isToolLocked?t.isToolLocked:n.isToolLocked,editingShapeId:null,shapeEditingSession:null,pageCameraById:Object.keys(r).length>0?r:n.pageCameraById,pageSelectedShapeIdsById:Object.keys(o).length>0?o:n.pageSelectedShapeIdsById,meta:ye(t.meta)}]}}function Ce(){return Cc.Zero()}function ke(e,t,n){if(n<=0)return Ce();const i=t.x-e.x,r=t.y-e.y;return 0===i&&0===r?Ce():new Cc(i/n,r/n)}function Be(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function Te(e,t){return t.getExportBounds(e)}function Me(e,t){return t.getLocalToPageTransform(e)}function Ee(e,t){const n=Re(e,t);return Bc.Translate(n.x,n.y).compose(Bc.Rotate(e.rotation)).compose(Bc.Scale(e.scaleX,e.scaleY)).compose(Bc.Translate(-n.x,-n.y))}function Ae(e,t){return Me(e,t)}function Re(e,t){return t.getBounds(e).center}function Fe(e,t,n){return Ee(e,n).applyToPoint(t)}function Le(e,t,n){if(0===e.scaleX||0===e.scaleY){const i=Re(e,n),r=t.sub(i).rot(-e.rotation);return i.add(new Cc(0===e.scaleX?0:r.x/e.scaleX,0===e.scaleY?0:r.y/e.scaleY))}return Ee(e,n).invert().applyToPoint(t)}function $e(e,t){return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(n=>Fe(e,n,t))}function De(e,t){const n=$e(e,t),i=((e,t)=>{const n=t.getBounds(e);return[new Cc(n.minX,n.minY),new Cc(n.maxX,n.minY),new Cc(n.maxX,n.maxY),new Cc(n.minX,n.maxY)].map(n=>Fe(e,n,t))})(e,t);return{bounds:kc.FromPoints(n),center:Re(e,t),corners:i,outlineVertices:n}}function ze(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Ye(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Xe(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 Ue(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 He(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function We(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):He(t,n)}function Ne(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&&We(n,t,o)<0)return r}return e.length})(o,n,i,r),0,n.id),e.set(t,s),!0}function Oe(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 Ke(e,t,n){Xe(e,t,n)}function _e(e){return h(e.before)&&h(e.after)}function qe(e){return p(e.before)&&p(e.after)}function Ve(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||!O(i,r))return!1}return!0}function Ge(e,t){return Ve(e.outlineVertices,t.outlineVertices)&&_(e.pageBounds,t.pageBounds)&&_(e.frameBounds,t.frameBounds)&&e.rotation===t.rotation&&O(e.rotationCenter,t.rotationCenter)&&O(e.toolbarAnchorPagePoint,t.toolbarAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function je(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)<qc?0:t}function Ze(e,t){const n=e.selectedShapeIdsSignal.get();if(0===n.length)return{outlineVertices:[],pageBounds:null,frameBounds:null,rotation:0,rotationCenter:null,toolbarAnchorPagePoint: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),h=c.getSelectionPagePoints(n);if(h&&r.push(...h),!c.contributesToSelectionFrame(n,{editor:e}))continue;o.push(n);const u=t(S);u&&(i.push(...u.outlineVertices),s=Math.min(s,u.bounds.minX),a=Math.min(a,u.bounds.minY),d=Math.max(d,u.bounds.maxX),l=Math.max(l,u.bounds.maxY))}const c=Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(d)&&Number.isFinite(l)?new kc(s,a,d-s,l-a):null,h=!(o.length>0)||function(e){if(0===e.length)return!0;const t=je(e[0]?.rotation??0);return e.every(e=>{return n=t,Math.abs(je(e.rotation)-je(n))<qc;var n})}(o),u=((e,t)=>0!==e.length&&t?je(e[0]?.rotation??0):0)(o,h),p=o.some(e=>Math.abs(je(e.rotation))>qc),g=c?.center??null,m=0===i.length?null:Math.abs(u)<qc||!g?kc.FromPoints(i):kc.FromPoints(i.map(e=>Cc.RotWith(e,g,-u))),f=r.length>0?kc.FromPoints(r):null;return{outlineVertices:i,pageBounds:c,frameBounds:m,rotation:u,rotationCenter:g,toolbarAnchorPagePoint:m&&g?Math.abs(u)<qc?new Cc(m.center.x,m.minY):Cc.RotWith(new Cc(m.center.x,m.minY),g,u):f?new Cc(f.center.x,f.minY):null,hasRotation:p,hasCompatibleRotation:h}}function Qe(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 Je(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function et(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||!Je(i,r))return!1}return!0}function tt(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 nt(e,t){return e===t||(e&&t?Qe(e.bounds,t.bounds)&&Je(e.center,t.center)&&et(e.corners,t.corners)&&et(e.outlineVertices,t.outlineVertices):e===t)}function it(e){return e?e.clone():e}function rt(e){return e?e.clone():e}function ot(e){return e?.map(e=>e.clone())}function st(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 kc(t,n,i-t,r-n)}function at(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 dt(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 kc(n,i,r-n,o-i)}function lt(e,t){return t.canReceiveChildren(e)&&!t.shouldTransformDescendants(e)}function ct(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 ht(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new Cc(n.minX,n.minY),new Cc(n.maxX,n.minY),new Cc(n.maxX,n.maxY),new Cc(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!==ct(e,t,n,o))return!0}return!1}function ut(e){return"top_left"===e||"left"===e||"bottom_left"===e}function pt(e){return"top_right"===e||"right"===e||"bottom_right"===e}function gt(e){return"top_left"===e||"top"===e||"top_right"===e}function mt(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function ft({handleId:e,scaleX:t,scaleY:n}){const i=ut(e)?t<0?"right":"left":pt(e)?t<0?"left":"right":null,r=gt(e)?n<0?"bottom":"top":mt(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 St({axis:e,startBounds:t,bounds:n,handleId:i,scale:r,isResizingFromCenter:o}){const s=Math.sign(r??1)||1;return o?s:"x"===e?ut(i)?n.minX>=t.maxX?-1:1:pt(i)?n.maxX<=t.minX?-1:1:s:gt(i)?n.minY>=t.maxY?-1:1:mt(i)?n.maxY<=t.minY?-1:1:s}function yt({requestedBounds:e,handleId:t,actualWidth:n,actualHeight:i,scaleX:r,scaleY:o,isResizingFromCenter:s}){return new kc(s?e.center.x-n/2:ut(t)?r<0?e.minX:e.maxX-n:pt(t)?r<0?e.maxX-n:e.minX:e.center.x-n/2,s?e.center.y-i/2:gt(t)?o<0?e.minY:e.maxY-i:mt(t)?o<0?e.maxY-i:e.minY:e.center.y-i/2,n,i)}function xt({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 kc(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 h;switch(n){case"top_left":h=new kc(l<0?e.minX:e.maxX-a,c<0?e.minY:e.maxY-d,a,d);break;case"top_right":h=new kc(l<0?e.maxX-a:e.minX,c<0?e.minY:e.maxY-d,a,d);break;case"bottom_right":h=new kc(l<0?e.maxX-a:e.minX,c<0?e.maxY-d:e.minY,a,d);break;case"bottom_left":h=new kc(l<0?e.minX:e.maxX-a,c<0?e.maxY-d:e.minY,a,d);break;case"top":h=new kc(t.center.x-a/2,c<0?t.maxY:t.maxY-d,a,d);break;case"right":h=new kc(l<0?t.minX-a:t.minX,t.center.y-d/2,a,d);break;case"bottom":h=new kc(t.center.x-a/2,c<0?t.minY-d:t.minY,a,d);break;case"left":h=new kc(l<0?t.maxX:t.maxX-a,t.center.y-d/2,a,d)}return{bounds:h,scaleX:l*(a/Math.max(1,t.w)),scaleY:c*(d/Math.max(1,t.h))}}function It(e,t){return e.x===t.x&&e.y===t.y}function Pt(e){return[new Cc(e.minX,e.minY),new Cc(e.center.x,e.minY),new Cc(e.maxX,e.minY),new Cc(e.minX,e.center.y),e.center,new Cc(e.maxX,e.center.y),new Cc(e.minX,e.maxY),new Cc(e.center.x,e.maxY),new Cc(e.maxX,e.maxY)]}function wt(e,t){return"x"===t?e.x:e.y}function bt(e,t){return"x"===t?e.minX:e.minY}function vt(e,t){return"x"===t?e.maxX:e.maxY}function Ct(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function kt(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Bt(e,t){return null!==kt(e,t)}function Tt(e,t){return new kc(e.x+t.x,e.y+t.y,e.w,e.h)}function Mt(e,t,n){return Tt(e,((e,t)=>"x"===e?new Cc(t,0):new Cc(0,t))(t,n))}function Et(e){return[new Cc(e.minX,e.minY),new Cc(e.maxX,e.minY),new Cc(e.maxX,e.maxY),new Cc(e.minX,e.maxY)]}function At(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 Cc(t.x+i.x*o,t.y+i.y*o))}function Rt(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 Cc(t.x+i.x*o,t.y+i.y*o)}function Ft(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=At(e,r,s);a>=i||(i=a,n=Rt(e,r,s))}return n?{point:n,distanceSquared:i}:null}function Lt(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 $t(e,t,n,i){let r=i+1,o=0;const s=[];for(const a of t)for(const t of n){const n=wt(t.point,e)-wt(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 Dt(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new Cc(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new Cc(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new Cc(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new Cc(t.minX,t.maxY))}return n}function zt(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>bt(e.bounds,t)-bt(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=vt(e.bounds,t),d=bt(o.bounds,t);if(a>=d)continue;const l=kt(Ct(e.bounds,t),Ct(o.bounds,t));l&&r.push({direction:n,startNode:e,endNode:o,length:d-a,breadthIntersection:l})}}return r}function Yt(e,t,n,i){const r=kt(Ct(t.bounds,i),Ct(n.bounds,i));return r?{direction:e,startNode:t,endNode:n,length:bt(n.bounds,i)-vt(t.bounds,i),breadthIntersection:r}:null}function Xt(e,t,n,i){const r=Ct(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:Mt(t,e,n)});for(const c of n){if(o<=c.length&&Bt(r,c.breadthIntersection)){const n=vt(c.startNode.bounds,e)+(c.length-o)/2-bt(t,e),i=l(n);d(n,[Yt(c.direction,c.startNode,i,e),Yt(c.direction,i,c.endNode,e)].filter(e=>null!==e))}const n=vt(c.endNode.bounds,e)+c.length-bt(t,e),i=l(n);if(Bt(Ct(i.bounds,e),c.breadthIntersection)){const t=Yt(c.direction,c.endNode,i,e);d(n,t?[c,t]:[])}const s=bt(c.startNode.bounds,e)-c.length-vt(t,e),a=l(s);if(Bt(Ct(a.bounds,e),c.breadthIntersection)){const t=Yt(c.direction,a,c.startNode,e);d(s,t?[t,c]:[])}}return a}function Ut(e,t){return e?t?Math.abs(e.nudge)<=Math.abs(t.nudge)?e:t:e:t}function Ht(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&&It(e.rotationCenter,t.rotationCenter)&&It(e.line[0],t.line[0])&&It(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&It(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&&It(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>It(e.startEdge[0],t.startEdge[0])&&It(e.startEdge[1],t.startEdge[1])&&It(e.endEdge[0],t.endEdge[0])&&It(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function Wt(e){return"horizontal"===e.direction?{startEdge:[new Cc(e.startNode.bounds.maxX,e.startNode.bounds.minY),new Cc(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new Cc(e.endNode.bounds.minX,e.endNode.bounds.minY),new Cc(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new Cc(e.startNode.bounds.minX,e.startNode.bounds.maxY),new Cc(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new Cc(e.endNode.bounds.minX,e.endNode.bounds.minY),new Cc(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function Nt(e,t,n,i){const r=Lt([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),o=qt(e,r);return{id:Vt(e,o,r),type:"points",axis:e,line:o,points:r,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function Ot(e,t,n,i){return Kt(e,t,n).map(t=>Nt(e,t,n,i))}function Kt(e,t,n){const i=new Map;for(const r of t.pairs){const t=wt(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 _t(e,t,n){return"x"===e?[new Cc(t,n.minY),new Cc(t,n.maxY)]:[new Cc(n.minX,t),new Cc(n.maxX,t)]}function qt(e,t){if(0===t.length)return[Cc.Zero(),Cc.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 Cc(n,r),new Cc(n,o)]:[new Cc(n,r),new Cc(i,r)]}function Vt(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 Gt(e,t,n,i,r,o){return Kt(e,t,n).map(t=>((e,t,n,i,r,o)=>{const s=Nt(e,t,n,i),a=t.pairs[0],d=wt(a?.selectionPoint.add(n)??r.center,e),l=new Map(o.map(e=>[e.id,e.bounds])),c=[],h=new Set;for(const g of t.pairs){if(h.has(g.candidateNodeId))continue;h.add(g.candidateNodeId);const t=l.get(g.candidateNodeId);t&&c.push(..._t(e,d,t))}const u=Lt([...s.points,..._t(e,d,r),...c]),p=qt(e,Lt([..._t(e,d,r),...c]));return{...s,id:Vt(e,p,u),line:p,points:u}})(e,t,n,i,r,o))}function jt(e){return{id:Vt("x",[e,e],[e]),type:"points",axis:"x",line:[e.clone(),e.clone()],points:[e.clone()],rotation:0,rotationCenter:e.clone()}}function Zt(e,t,n){const i="x"===e?new Cc(n.x,t.y):new Cc(t.x,n.y),r=Lt([n.clone(),i]),o=qt(e,r);return{id:Vt(e,o,r),type:"points",axis:e,line:o,points:r,rotation:0,rotationCenter:Cc.Zero()}}function Qt(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new Cc(0,n.y):new Cc(n.x,0),r=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:Tt(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:Tt(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(Wt),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function Jt(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 en(e,t){return 0===t.rotation?e.clone():Cc.RotWith(e,t.rotationCenter,-t.rotation)}function tn(e,t){return 0===t.rotation?e.clone():Cc.RotWith(e,t.rotationCenter,t.rotation)}function nn(e,t){return tn(e,t)}function rn(e,t,n,i,r){return 0===n?i:i+(e-t)/n*r}function on({point:e,fromBounds:t,toBounds:n}){return new Cc(rn(e.x,t.minX,t.w,n.minX,n.w),rn(e.y,t.minY,t.h,n.minY,n.h))}function sn({axis:e,bounds:t,point:n}){return"horizontal"===e?new Cc(t.minX+t.maxX-n.x,n.y):new Cc(n.x,t.minY+t.maxY-n.y)}function an({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new kc(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new kc(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function dn(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function ln(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 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)return!1;if(i.id!==r.id||i.usesSelectionPathOverlay!==r.usesSelectionPathOverlay||!dn(i.startPagePoint,r.startPagePoint)||!dn(i.endPagePoint,r.endPagePoint)||!dn(i.middlePagePoint,r.middlePagePoint)||i.path!==r.path)return!1}return!0}function hn(e,t){return e===t||(e&&t?ln(e.bounds,t.bounds)&&e.rotation===t.rotation&&dn(e.rotationCenter,t.rotationCenter)&&e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius:e===t)}function un(e,t){return e===t||(e&&t?ln(e.bounds,t.bounds)&&e.rotation===t.rotation&&dn(e.rotationCenter,t.rotationCenter):e===t)}function pn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!un(e[n]??null,t[n]??null))return!1;return!0}function gn(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function mn(e,t){return e.id===t.id&&dn(e.point,t.point)&&ln(e.bounds,t.bounds)}function fn(e,t){return e.id===t.id&&dn(e.point,t.point)&&ln(e.bounds,t.bounds)}function Sn(e,t){return e.terminal===t.terminal&&dn(e.point,t.point)&&ln(e.bounds,t.bounds)}function yn(e,t){return dn(e.point,t.point)&&ln(e.bounds,t.bounds)}function xn(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&dn(e.point,t.point)&&ln(e.bounds,t.bounds)}function In(e,t){return e.id===t.id&&dn(e.point,t.point)}function Pn(e,t){return e.id===t.id&&dn(e.point,t.point)}function wn(e,t){return e.terminal===t.terminal&&dn(e.point,t.point)}function bn(e,t){return dn(e.point,t.point)}function vn(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&dn(e.point,t.point)}function Cn(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 Cc(e.maxX+t,e.minY-t):new Cc(e.minX-t,e.maxY+t)}function Bn(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&Cn(e.resizeHandles,t.resizeHandles,mn)&&Cn(e.rotateHandles,t.rotateHandles,fn)&&Cn(e.terminalHandles,t.terminalHandles,Sn)&&Cn(e.middleHandles,t.middleHandles,yn)&&Cn(e.customHandles,t.customHandles,xn):e===t)}function Tn(e,t){return e===t||(e&&t?Cn(e.resizeHandleAnchors,t.resizeHandleAnchors,In)&&Cn(e.rotateHandleAnchors,t.rotateHandleAnchors,Pn)&&Cn(e.terminalHandleAnchors,t.terminalHandleAnchors,wn)&&Cn(e.middleHandleAnchors,t.middleHandleAnchors,bn)&&Cn(e.customHandleAnchors,t.customHandleAnchors,vn):e===t)}function Mn(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 En(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function An(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:h,rotation:u,rotationCenter:p,hasCompatibleRotation:g}=t,m=e[0]?.rotation??u,f=8/n,S=14/n,y=h.w<2*f,x=h.h<2*f,I=e=>0===u?e:Cc.RotWith(e,p,u),P=new Cc(h.minX,h.minY),w=new Cc(h.center.x,h.minY),b=new Cc(h.maxX,h.minY),v=new Cc(h.maxX,h.center.y),C=new Cc(h.maxX,h.maxY),k=new Cc(h.center.x,h.maxY),B=new Cc(h.minX,h.maxY),T=new Cc(h.minX,h.center.y);return{resizeHandleAnchors:s&&!c&&g?[{kind:"resize",id:"top_left",point:I(P)},...y?[]:[{kind:"resize",id:"top",point:I(w)}],...y&&x?[]:[{kind:"resize",id:"top_right",point:I(b)}],...x?[]:[{kind:"resize",id:"right",point:I(v)}],...y||x?[]:[{kind:"resize",id:"bottom_right",point:I(C)}],...y?[]:[{kind:"resize",id:"bottom",point:I(k)}],...y||x?[]:[{kind:"resize",id:"bottom_left",point:I(B)}],...x?[]:[{kind:"resize",id:"left",point:I(T)}]]:[],rotateHandleAnchors:!s||c||!g||y||x?[]:[{kind:"rotate",id:"bottom_left_rotate",point:I(kn({bounds:h,rotateOffset:S,referenceRotation:m,frameRotation:u}))}],terminalHandleAnchors:a,middleHandleAnchors:d,customHandleAnchors:l}}function Rn(e,t){const n=8/t,i=n/2,r=e=>new kc(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 Fn(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 Ln(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 $n(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 Dn(e,t,n,i="user"){const r=$n(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 zn(e,t,n,i="user"){const r=$n(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 Yn(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 Xn(e,t,n,i,r){const o=new Set(n),s=e.getChildShapes(t.parentId).filter(e=>!o.has(e.id));let a=s.length;if(t.beforeId){const e=s.findIndex(e=>e.id===t.beforeId);if(-1===e)return!1;a=e}const d=[...i].sort((e,t)=>e.index.localeCompare(t.index));s.splice(a,0,...d),e.cancelInteractionForCommand();const l=s.map((n,i)=>({id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+1)}));return e.commands.updateShapes(l,{source:r}),!0}function Un(e,t,n){return Math.min(n,Math.max(t,e))}function Hn(e){return 0===e.length?"none":e.map(e=>`${e.start}-${e.end-1}`).join(", ")}function Wn(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 Nn(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function On(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function Kn(e,t,n=0){return Wn(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n)}function _n(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function qn(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:_n(e,t)}}function Vn(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 Cc(e.x+i.x*s,e.y+i.y*s)})(t,n,e))}function Gn(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(Vn(e,n,i),Vn(t,n,i),Vn(n,e,t),Vn(i,e,t))}function jn(e){return[new Cc(e.minX,e.minY),new Cc(e.maxX,e.minY),new Cc(e.maxX,e.maxY),new Cc(e.minX,e.maxY)]}function Zn(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 Qn(e,t,n){const i=e[t];return"number"==typeof i&&Number.isFinite(i)?i:n}function Jn(e){return Math.min(1,Math.max(0,(96-e)/96))}function ei(e,t,n){if(t.w<=0||t.h<=0||n<=0)return Cc.Zero();const i=Math.min(n,32),r=Jn(e.x),o=Jn(t.w-e.x),s=Jn(e.y),a=1.25*(o-r)*i,d=1.25*(Jn(t.h-e.y)-s)*i;return 0===a&&0===d?Cc.Zero():new Cc(a,d)}function ti(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=ei(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 ni(e,t){const n=(e=>{const t=e.inputs.state.get();return"dragging"===t.dragPhase&&t.currentPagePoint?{pagePoint:t.currentPagePoint,shiftKey:t.shiftKey,altKey:t.altKey,accelKey:t.accelKey,ctrlKey:t.ctrlKey}:null})(e);n&&t(n)}function ii(e,t,n){const i=new Set(n);if(i.has(t))return t;const r=ri(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)=>ri(e,t)[0]?.ancestorId??null)(e,t)===o)?t:r[r.length-1]?.ancestorId??t}function ri(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 oi({shiftKey:e,accelKey:t}){return e||t}function si({ctrlKey:e}){return e}function ai(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function di(e,t){return Math.round(e/t)*t}function li(e,t,n,i,r,o,s,a,d,l,c){const h=ci(d,l),u=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=on({point:new Cc(e.minX,e.minY),fromBounds:t,toBounds:n}),r=on({point:new Cc(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new kc(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=tn(u.center,h),g=e.getShapeUtil(t.shape).resizeSelectionBounds(t.shape,{handleId:s,pageCenter:p,selectionLocalBounds:u,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 ci(e,t){return{rotation:t,rotationCenter:e}}function hi(e,t,n,i,r,o,s,a,d,l,c){const h=ci(d,l),u=tn(ui({point:t.startLocalPagePoint,startBounds:n,scaleX:r,scaleY:o,handleId:s,isResizingFromCenter:a}),h),p=tn(ui({point:t.endLocalPagePoint,startBounds:n,scaleX:r,scaleY:o,handleId:s,isResizingFromCenter:a}),h),g=e.getShapeUtil(t.shape).updateSelectionPagePoints(t.shape,{pagePoints:[u,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:ut(t)?e.maxX:pt(t)?e.minX:e.center.x)({startBounds:t,handleId:r,isResizingFromCenter:o}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:gt(t)?e.maxY:mt(t)?e.minY:e.center.y)({startBounds:t,handleId:r,isResizingFromCenter:o});return new Cc(s+(e.x-s)*n,a+(e.y-a)*i)}function pi(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 gi(e,t,n,i){const r=e.localBounds.center,o=nn(new Cc(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 mi(e,t,n,i,r){const o=e.getShapeUtil(t.shape).updateSelectionPagePoints(t.shape,{pagePoints:[nn(t.startPagePoint,{rotation:i,rotationCenter:n}),nn(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 fi(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 Si(e,t){const n=e.getContainingShapeParentId(t);if(!n)return null;const i=fi(e,t);if(!i||!i.startsWith("shape:")||n===i)return n;const r=e.getShape(i);return r&&e.getShapeUtil(r).canReceiveChildren(r)&&t.every(t=>{const n=e.getShapeContainment(r.id,t);return"inside"===n||"intersecting"===n})?i:n}function yi(e,t,n){return(e=>{const i=new bc(e,()=>{t.get(),n()},void 0);return i.attach(),()=>i.detach()})(e)}function xi(){const e=Jl(Uh);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function Ii(e){const[,t]=rc(e=>e+1,0);return ec(()=>yi("useValue",e,()=>{t()}),[e]),e.get()}function Pi({children:e,className:t,dataUi:n}){
2
- return dc("div",{"data-ui":n,className:t,style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transform:Ii(xi().pageTransformSignal).toCssString(),transformOrigin:"0 0"},children:e})}function wi(e){if(!e.createFeature&&!e.addExtensions)throw new Error(`Land extension "${e.name}" must define createFeature() or addExtensions().`);return new Hh(e,e.addOptions?.()??{})}function bi(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()}))}function vi(e,t){return Ci(e,t)}function Ci(e,t){const n={...e};for(const[i,r]of Object.entries(t)){const t=e[i];n[i]=ki(t)&&ki(r)?Ci(t,r):r}return n}function ki(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Bi(e=[]){const t=new Wh;return t.registerCanvasPlugins(e),t}function Ti(){const e="undefined"!=typeof window&&"1"===new URLSearchParams(window.location.search).get("renderHostDebug");
3
- return lc("div",{"data-ui":"shape-layer",className:"absolute inset-0",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:[dc(Pi,{dataUi:"shape-page-space",className:"absolute inset-0",children:dc(Oh,{})}),e?dc(Kh,{}):null]})}function Mi(){
4
- return dc("div",{"data-ui":"transform-descendant-ancestor-boundary",style:{position:"absolute",inset:0,border:"1px dashed #64748b",pointerEvents:"none"}})}function Ei({state:e}){
5
- return lc("div",{"data-ui":"shape-order-badge",style:{position:"absolute",right:8,top:8,display:"flex",alignItems:"center",height:22,padding:"0 8px",borderRadius:999,border:"1px solid rgba(15, 23, 42, 0.12)",background:"rgba(255, 255, 255, 0.94)",color:"#334155",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:11,fontWeight:700,lineHeight:"22px",boxShadow:"0 8px 18px rgba(15, 23, 42, 0.12)",whiteSpace:"nowrap",pointerEvents:"none"},children:[e.index+1," / ",e.count]})}function Ai({shapeType:e}){
6
- return dc("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 Ri({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?dc(ac,{children:e}):t.reduceRight((e,t)=>dc(Fi,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function Fi({ancestorId:e,children:t,shapeElementToPage:n}){const i=xi(),r=Ii(i.getShapeSignal(e));if(!r)return dc(ac,{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 Cc(e.minX,e.minY),new Cc(e.maxX,e.minY),new Cc(e.maxX,e.maxY),new Cc(e.minX,e.maxY)])(i).map(e=>s.applyToPoint(o.applyToPoint(e))).map(Li).join(", ")})`})(i,r,n);return o?dc("div",{"data-ui":"shape-clip-boundary","data-clip-ancestor-id":e,style:{width:"100%",height:"100%",clipPath:o,WebkitClipPath:o},children:t}):dc(ac,{children:t})}function Li(e){return`${$i(e.x)}px ${$i(e.y)}px`}function $i(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Di({editor:e,shape:t,stroke:n,fill:i,strokeWidth:r}){const o=e.getShapePageOutlineVertices(t.id);return 0===o.length?null:dc("polygon",{points:o.map(e=>`${e.x},${e.y}`).join(" "),fill:i,stroke:n,strokeWidth:r,strokeLinejoin:"round",strokeLinecap:"round"})}function zi(){
7
- return dc("div",{"data-ui":"overlay-layer",className:"overlay-layer pointer-events-none absolute inset-0",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:dc(Pi,{dataUi:"overlay-page-space",className:"overlay-layer__page-space absolute inset-0",children:dc(qh,{})})})}function Yi(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Xi(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 hu[Math.round(n)%hu.length]??"default"}function Ui({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:[Hi(i-n,r+t),Hi(i-n,r-n),Hi(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:[Hi(i-t,r-n),Hi(i+n,r-n),Hi(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:[Hi(i+n,r-t),Hi(i+n,r+n),Hi(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:[Hi(i+t,r+n),Hi(i-n,r+n),Hi(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});
8
- return lc("g",{children:[dc("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?dc("polyline",{points:c.points,...l}):dc("line",{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,...l})]})}function Hi(e,t){return`${e},${t}`}function Wi(e=[]){const t=new uu;return t.registerCanvasPlugins(e),t}function Ni(e){return e instanceof HTMLElement&&(!!e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)}function Oi(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 Ki(e,t){return{type:"keyboard",name:e,key:t.key,code:t.code,shiftKey:t.shiftKey,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,accelKey:t.metaKey||t.ctrlKey}}function _i(e,t){return new Cc(e.clientX-t.left,e.clientY-t.top)}function qi(e,t){return(e%t+t)%t}function Vi(){const e=Ii(xi().currentCameraSignal);
9
- return lc("svg",{"data-ui":"canvas-background","aria-hidden":"true",className:"pointer-events-none absolute inset-0",xmlns:"http://www.w3.org/2000/svg",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},children:[dc("defs",{children:pu.map(({min:t,mid:n,step:i})=>{const r=15*i*e.z,o=((e,t)=>({x:qi(.5-e.x*e.z,t),y:qi(.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;
10
- return dc("pattern",{id:`land-canvas-grid-${i}`,width:r,height:r,patternUnits:"userSpaceOnUse",children:dc("circle",{cx:o.x,cy:o.y,r:1,fill:"var(--canvas-dot)",opacity:s})},i)})}),pu.map(({step:e})=>dc("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function Gi(e,t){return"hand"===e?t?"grabbing":"grab":"select"===e?void 0:"crosshair"}function ji({canvasComponents:e,canvasProviders:t,domEventGuardRegistry:n,onContextMenuRequest:i,rendererRegistry:r}={}){const o=xi(),s=ic(()=>r??Bi(),[r]),a=ic(()=>n??Wi(),[n]),d=Ii(o.toolStateSignal).activeToolId,l=Ii(o.shapeEditingStateSignal).session,c=oc(null),h=oc(null),u=oc(null),p=oc(null),g=oc(null),m=oc(null),f=oc(null),[S,y]=sc(!1),[x,I]=sc(void 0),P=()=>{null!==g.current&&(cancelAnimationFrame(g.current),g.current=null),m.current=null},w=e=>{if(null===u.current)return void P();const t=m.current??e;m.current=e,o.dispatch({type:"tick",timestamp:e,elapsed:e-t}),g.current=requestAnimationFrame(w)};return ec(()=>{const e=c.current;if(!e)return;const t=()=>{const t=e.getBoundingClientRect(),n={left:t.left,top:t.top};return h.current=n,n},n=()=>h.current??t(),i=(t,n)=>"handled"===a.handle({name:t,event:n,editor:o,container:e}),r=()=>{if(!l)return void I(void 0);const t=f.current;I(t?a.getCursor({clientPoint:t,element:document.elementFromPoint(t.x,t.y),editor:o,container:e}):void 0)},s=(e,t)=>{if(!c.current)return;const i=_i(t,n());o.dispatch(Oi(e,t,i,o.screenToPage(i)))},d=()=>{o.setViewportScreenSize({w:e.clientWidth,h:e.clientHeight})};t(),d();const g=e=>{if(!i("key_down",e))return o.getShapeEditingSession()?!Ni(e.target)&&o.handleInteractionEvent(Ki("key_down",e))?(e.preventDefault(),void e.stopPropagation()):void(Ni(e.target)||"Escape"!==e.key||e.altKey||e.ctrlKey||e.metaKey?Ni(e.target)||"Enter"!==e.key||!e.metaKey&&!e.ctrlKey||o.completeEditing("user"):o.cancelEditing("user")):void(Ni(e.target)||((e.metaKey||e.ctrlKey)&&"z"===e.key.toLowerCase()&&e.preventDefault(),!e.altKey||e.metaKey||e.ctrlKey||e.shiftKey||"ArrowDown"!==e.key&&"ArrowUp"!==e.key||e.preventDefault(),o.dispatch(Ki("key_down",e))))},m=e=>{i("key_up",e)||o.getShapeEditingSession()||Ni(e.target)||o.dispatch(Ki("key_up",e))},S=()=>{u.current=null,p.current=null,y(!1),P(),o.dispatch({type:"cancel",reason:"blur"})},x=e=>{if(i("wheel",e))return;e.preventDefault();const t=_i(e,n()),r=o.screenToPage(t);o.dispatch(((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new Cc(e.deltaX,e.deltaY),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}))(e,t,r))},w=e=>{if(f.current={x:e.clientX,y:e.clientY},r(),e.pointerId!==u.current){const t=_i(e,n());return o.inputs.setCurrentPointerPoint({timestamp:e.timeStamp,screenPoint:t,pagePoint:o.screenToPage(t),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}),void i("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 a,d;d=t,(a=p.current)&&a.clientX===d.clientX&&a.clientY===d.clientY&&a.buttons===d.buttons&&a.shiftKey===d.shiftKey&&a.altKey===d.altKey&&a.ctrlKey===d.ctrlKey&&a.metaKey===d.metaKey||(p.current=t,s("pointer_move",e))},b=(t,n)=>{n.pointerId===u.current&&(u.current=null,p.current=null,y(!1),P(),e.hasPointerCapture(n.pointerId)&&e.releasePointerCapture(n.pointerId),s(t,n))},v=e=>{f.current={x:e.clientX,y:e.clientY},window.setTimeout(r,0),e.pointerId===u.current?b("pointer_up",e):i("pointer_up",e)},C=e=>{f.current={x:e.clientX,y:e.clientY},r(),e.pointerId===u.current?b("pointer_cancel",e):i("pointer_cancel",e)},k=new ResizeObserver(()=>{t(),d()});window.addEventListener("keydown",g),window.addEventListener("keyup",m),window.addEventListener("blur",S),window.addEventListener("scroll",t,{passive:!0,capture:!0}),window.addEventListener("pointermove",w,{passive:!0}),window.addEventListener("pointerup",v),window.addEventListener("pointercancel",C),e.addEventListener("wheel",x,{passive:!1}),k.observe(e);const B=window.requestAnimationFrame(r);return()=>{P(),y(!1),window.cancelAnimationFrame(B),window.removeEventListener("keydown",g),window.removeEventListener("keyup",m),window.removeEventListener("blur",S),window.removeEventListener("scroll",t,!0),window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",C),e.removeEventListener("wheel",x),k.disconnect()}},[a,o,l]),lc("div",{ref:c,"data-ui":"canvas-surface",className:"ic-canvas relative h-full w-full overflow-hidden touch-none select-none",tabIndex:0,style:{cursor:x??Gi(d,S)},onPointerDown:e=>{const t=c.current;if(!t)return;if(f.current={x:e.clientX,y:e.clientY},2===e.button)return void t.focus();if("handled"===a.handle({name:"pointer_down",event:e.nativeEvent,editor:o,container:t}))return;if(Ni(e.target))return;e.preventDefault(),t.focus(),t.setPointerCapture(e.pointerId);const n=t.getBoundingClientRect();h.current={left:n.left,top:n.top},u.current=e.pointerId,y(!0),p.current=null,null===g.current&&(m.current=null,g.current=requestAnimationFrame(w));const i=_i(e,h.current);o.dispatch(Oi("pointer_down",e,i,o.screenToPage(i)))},onContextMenu:e=>{const t=c.current;if(!t||!i||Ni(e.target))return;if(e.preventDefault(),e.stopPropagation(),o.getShapeEditingSession())return;t.focus(),null!==u.current&&(t.hasPointerCapture(u.current)&&t.releasePointerCapture(u.current),u.current=null,p.current=null,P(),o.dispatch({type:"cancel",reason:"pointer_cancel"}));const n=t.getBoundingClientRect();h.current={left:n.left,top:n.top};const r=_i(e,h.current),s=o.screenToPage(r),a=o.hitTestShape(s);let d;if(a){const e=o.getSelectedShapeIds(),t=e.includes(a.id);t||o.commands.setSelectedShapeIds([a.id],{source:"user"}),d={screenPoint:r,pagePoint:s,target:{type:"selection",selectedShapeIds:t?e:[a.id]}}}else d={screenPoint:r,pagePoint:s,target:{type:"canvas"}};i?.(d)},children:[dc(Vi,{}),dc(Nh.Provider,{value:s,children:lc(Zi,{providers:t,children:[
11
- dc(Ti,{}),e?.map(({id:e,component:t})=>dc(t,{},e)),
12
- dc(zi,{})]})})]})}function Zi({children:e,providers:t}){
13
- return dc(ac,{children:t?.reduceRight((e,{id:t,component:n})=>dc(n,{children:e},t),e)??e})}function Qi(e){return{id:e}}function Ji(){const e=new Map;return{register(t,n){if(e.has(t.id))throw new Error(`Product API already registered: ${t.id}`);e.set(t.id,n)},get:t=>e.get(t.id)??null}}function er(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 Cc(e.x+e.props.w/2,e.y+e.props.h/2),i=t.sub(n);return n.add(new Cc(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))})(e,new Cc(e.x+n.x,e.y+n.y))}function tr(e){return"start"===e?"end":"start"}function nr(e,t,n){const i=((e,t)=>{const n=ar(e.x,t.x),i=ar(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 ir(e,t,n){return nr(e,"start"===t?n:er(e,"start"),"end"===t?n:er(e,"end"))}function rr(e){return lr(new Cc(e.props.start.x,e.props.start.y).add(new Cc(e.x,e.y)),new Cc(e.props.end.x,e.props.end.y).add(new Cc(e.x,e.y)),e.props.bend)}function or(e){return lr(new Cc(e.props.start.x,e.props.start.y),new Cc(e.props.end.x,e.props.end.y),e.props.bend)}function sr(e,t,n){const i=Cc.Med(e,t),r=t.sub(e);if(r.len()<1e-6)return 0;const o=r.per().normalize();return-ur(n.sub(i),o)}function ar(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 dr(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function lr(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=Cc.Med(e,t),r=t.sub(e),o=r.len()?r.per().normalize():new Cc(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)<gu)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 Cc(r,o):null})(e,t,n);if(!i)return null;const r=i.dist(e);if(r<gu)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<gu||o<gu?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,h=(mu-s)*(o?1:-1);return{center:i,radius:r,largeArcFlag:c,sweepFlag:o,size:h,length:Math.abs(h*r)}})(e,r,t),s=Math.abs(i)<gu||null===o||0===o.length||!Number.isFinite(o.length)||!Number.isFinite(o.radius),a=s?[e,t]:((e,t,n)=>{const i=[],r=Cc.Angle(n.center,e),o=((e,t,n,i)=>{const r=(t-e)%mu,o=2*r%mu-r;return i?(mu-Math.abs(o))*(n?1:-1):o})(r,Cc.Angle(n.center,t),n.sweepFlag,n.largeArcFlag);for(let s=0;s<=24;s++)i.push(cr(n.center,n.radius,r+o*(s/24)));return i})(e,t,o),d=s||null===o?`M ${dr(e.x)} ${dr(e.y)} L ${dr(t.x)} ${dr(t.y)}`:`M ${dr(e.x)} ${dr(e.y)} A ${dr(o.radius)} ${dr(o.radius)} 0 ${o.largeArcFlag} ${o.sweepFlag} ${dr(t.x)} ${dr(t.y)}`,l={start:{terminal:"start",point:e,handle:e},end:{terminal:"end",point:t,handle:t},middle:r,bend:i,points:a,bounds:kc.FromPoints(a),path:d};return s?{type:"straight",...l,arc:null}:{type:"curved",...l,arc:o}}function cr(e,t,n){return e.add(new Cc(Math.cos(n)*t,Math.sin(n)*t))}function hr(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,ur(o,i)/r)),a=t.add(i.mul(s));return e.dist(a)}function ur(e,t){return e.x*t.x+e.y*t.y}function pr(e){return!!e&&"shape"===e.typeName&&"arrow"===e.type}function gr(e){return!!e&&"binding"===e.typeName&&"arrow"===e.type}function mr(e){return Math.max(0,Math.min(1,e))}function fr(e,t,n,i){const r=e.getShapeUtil(t);return((e,t,n,i)=>e.getShapeUtil(t).resolveBindingPoint(t,{rawPagePoint:n,oppositePagePoint:i}))(e,t,Fe(t,((e,t,n)=>{const i=e.computeShapeBounds(t);return new Cc(i.minX+i.w*n.x,i.minY+i.h*n.y)})(e,t,n),r),i)}function Sr(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)&&!pr(t);var t}});if(!r)return null;const o=((e,t,n)=>{const i=Le(t,n,e.getShapeUtil(t)),r=e.computeShapeBounds(t),o=r.h<=1e-6?.5:(i.y-r.minY)/r.h;return{x:mr(r.w<=1e-6?.5:(i.x-r.minX)/r.w),y:mr(o)}})(e,r,t);return{targetShape:r,normalizedAnchor:o,resolvedPagePoint:fr(e,r,o,n),rawPagePoint:t.clone()}}(e,n,i,{excludeShapeId:r});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:xr(s),preview:Ir(t,s)}}function yr(e,{arrow:t,terminal:n,rawPagePoint:i,ignoreTargets:r=!1}){return Sr(e,{terminal:n,rawPagePoint:i,oppositePagePoint:er(t,tr(n)),excludeShapeId:t.id,ignoreTargets:r})}function xr(e){return e?{targetShapeId:e.targetShape.id,normalizedAnchor:e.normalizedAnchor}:null}function Ir(e,t){return t?{terminal:e,targetShapeId:t.targetShape.id,rawPagePoint:t.rawPagePoint,resolvedPagePoint:t.resolvedPagePoint}:null}function Pr(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function wr(e){if(e)return{shapes:[e]}}function br(e,t){const n=e&&"object"==typeof e?e:void 0;return{x:vr(n?.x,t.x),y:vr(n?.y,t.y)}}function vr(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Cr(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 kr(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(Cr(e,n,i),Cr(t,n,i),Cr(n,e,t),Cr(i,e,t))}function Br(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(!pr(i))throw new Error("Failed to create arrow shape");const r=nr(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(!pr(o))throw new Error("Failed to create arrow shape");return o}function Tr(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(!pr(i))return null;const r=ir(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=>gr(e)&&e.props.terminal===t.terminal)??null;t.binding?gr(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 pr(s)?s:r})(e,{shapeId:t,terminal:n,pagePoint:i.pagePoint,binding:i.binding},r),e.setBindingPreview(i.preview),o}function Mr(){return{createSession:(e,{handle:t,shape:n})=>pr(n)?"arrow_terminal"===t.kind?(({handle:e,shapeId:t,terminal:n})=>({shapeId:t,historyMark:"select.arrow_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(!pr(s))return{status:"stop",finalPagePoint:null};const a=yr(e,{arrow:s,terminal:n,rawPagePoint:i,ignoreTargets:r}),d=Tr(e,s.id,n,a,o);return{status:"continue",finalPagePoint:d?er(d,n):a.pagePoint}}}))({handle:t,shapeId:n.id,terminal:t.terminal}):"arrow_middle"===t.kind?function({shapeId:e}){return{shapeId:e,historyMark:"select.arrow_middle_drag",update({editor:t,pagePoint:n,accelKey:i,source:r}){const o=t.getShape(e);if(!pr(o))return"stop";const s=(({bend:e,bypassSnap:t,zoom:n})=>t?e:Math.abs(e)*n<=6?0:e)({bend:sr(er(o,"start"),er(o,"end"),n),bypassSnap:i,zoom:t.cameraZoomSignal.get()});return t.commands.updateShapes([{id:o.id,props:{bend:s}}],{source:r}),"continue"}}}({shapeId:n.id}):null:null}}function Er({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:bu.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:vu.map(e=>({...e,dataUi:`${r}-stroke-width-${e.value}-button`}))}]},{id:`${r}.head-start`,items:[{kind:"segmented",id:`${r}.head-start`,actionId:n,options:Cu.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:Cu.map(e=>({...e,label:`End head: ${e.label}`,dataUi:`${r}-end-head-${e.value}-button`}))}]}]}function Ar(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(n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){if(!Fr(e,n))return;const i=t.selection.selectedShapes.filter(e=>"arrow"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:n}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function Rr(e){return{id:`arrow.default-${e}`,isVisible:e=>"arrow"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("arrow")[e],run({context:t,value:n}){Fr(e,n)&&t.editor.updateDefaultShapeProps("arrow",{[e]:n})}}}function Fr(e,t){return"strokeWidth"===e?vu.some(e=>e.value===t):"stroke"===e?bu.some(e=>e.value===t):Cu.some(e=>e.value===t)}function Lr(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 $r({shape:e,isSelected:t}){const n=e.id.replace(/[^a-zA-Z0-9_-]/g,"-"),i=`arrow-head-start-${n}`,r=`arrow-head-end-${n}`,o=or(e);
14
- return lc("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,overflow:"visible",children:[lc("defs",{children:[dc("marker",{id:i,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"2",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:dc("path",{d:"M8.9,8 L2,12 L8.9,16",fill:"none",stroke:e.props.stroke,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),dc("marker",{id:r,markerWidth:"12",markerHeight:"12",viewBox:"0 0 24 24",refX:"22",refY:"12",orient:"auto",markerUnits:"strokeWidth",children:dc("path",{d:"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:e.props.stroke,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),dc("path",{d:o.path,fill:"none",stroke:e.props.stroke,strokeWidth:e.props.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round",markerStart:"arrow"===e.props.headStart?`url(#${i})`:void 0,markerEnd:"arrow"===e.props.headEnd?`url(#${r})`:void 0,opacity:t?.92:1})]})}function Dr(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function zr(e,t,n){return Math.max(t,Math.min(n,e))}function Yr(e){return e?640:480}function Xr(e,t){return e.x===t.x&&e.y===t.y&&e.pressure===t.pressure&&e.segment===t.segment}function Ur(e){return new Cc(e.x,e.y)}function Hr(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 Wr(e){const t=[];for(const n of e)t.push(...n.points.map(Hr));return t}function Nr(e){if(void 0!==e&&Number.isFinite(e))return zr(e,.05,1)}function Or(e,t){const n=[];for(let i=1;i<e.length-1;i+=1){if(t&&Kr(e,i))continue;const r=e[i],o=e[i-1],s=e[i+1];r&&o&&s&&n.push({index:i,score:_r(r,o,s)})}return n.sort((e,t)=>e.score-t.score||e.index-t.index),n}function Kr(e,t){return"straight"===e[t]?.segment||"straight"===e[t+1]?.segment}function _r(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=zr(((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 qr(e){if(0===e.length)return null;if(1===e.length){const t=e[0];return`M ${Dr(t.x)} ${Dr(t.y)}`}if(2===e.length){const t=e[0],n=e[1];return[`M ${Dr(t.x)} ${Dr(t.y)}`,`L ${Dr(n.x)} ${Dr(n.y)}`].join(" ")}const t=[],n=e[0];t.push(`M ${Dr(n.x)} ${Dr(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 ${Dr(n.x)} ${Dr(n.y)}`);continue}const r=e[i+1];if(!r||"straight"===r.segment){if(Vr(e,i)){const r=e[i-1];t.push(`Q ${Dr(r.x)} ${Dr(r.y)} ${Dr(n.x)} ${Dr(n.y)}`)}else t.push(`L ${Dr(n.x)} ${Dr(n.y)}`);continue}const o=Cc.Med(Ur(n),Ur(r));t.push(`Q ${Dr(n.x)} ${Dr(n.y)} ${Dr(o.x)} ${Dr(o.y)}`)}return t.join(" ")}function Vr(e,t){return t>=2&&"straight"!==e[t-1]?.segment&&"straight"!==e[t-2]?.segment}function Gr(e){if(e.length<3)return(e=>{if(0===e.length)return null;const[t,...n]=e;return t?[`M ${Dr(t.x)} ${Dr(t.y)}`,...n.map(e=>`L ${Dr(e.x)} ${Dr(e.y)}`),"Z"].join(" "):null})(e);const t=e[0],n=e[e.length-1];if(!t||!n)return null;const i=Cc.Med(n,t),r=[`M ${Dr(i.x)} ${Dr(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=Cc.Med(t,n);r.push(`Q ${Dr(t.x)} ${Dr(t.y)} ${Dr(i.x)} ${Dr(i.y)}`)}return r.push("Z"),r.join(" ")}function jr(e){return e.map(Hr)}function Zr(e){return e.map(Qr)}function Qr(e){return(e=>({points:e.points.map(Hr)}))(e)}function Jr(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 eo(e,t,n){return e.map(e=>({points:Jr(e.points,t,n)}))}function to(e,t){return e.map((e,n)=>({points:e.points.map((e,i)=>{const r=t(Ur(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 no(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 io(e,t,n){return e.map(e=>({points:no(e.points,t,n)}))}function ro(e){return{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}}function oo(e,t){const n=ro(t);return to(e,e=>en(e,n))}function so(e,t){const n=ro(t);return to(e,e=>tn(e,n))}function ao(e,t){return to(e,e=>sn({axis:t.axis,bounds:t.selectionMirrorBounds,point:e}))}function lo(e,t,n){return Math.max(t,Math.min(n,e))}function co(e,t,n){return e+(t-e)*n}function ho(e,t,n){if(e.length<=1)return new Cc(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 Cc(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 Cc(1,0);if(t===e.length-1)return o.len2()>0?o:new Cc(1,0);const a=o.add(s);return a.len2()>1e-6?a.uni():s.len2()>0?s:o.len2()>0?o:new Cc(1,0)}function uo(e,t){return e.x*t.x+e.y*t.y}function po(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(Ur),a=[0];let d=0;for(let h=1;h<s.length;h+=1)d+=s[h].dist(s[h-1]),a.push(d);let l=null;const c=e.map((e,n)=>{const c=a[n]??0,h=0===n?0:s[n].dist(s[n-1]),u=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=lo(e/Math.max(1.5*r,1),0,1),a=lo(1-s,Bu,1),d=null===t?co(.5,a,.275):co(t,a,.275*Math.max(s,.36));if(o)return lo(d,Bu,1);const l=lo(n/Math.max(1.8*r,1),0,1),c=lo((i-n)/Math.max(2.6*r,1),0,1);return lo(d*co(.72,1,Math.min(l,c)),Bu,1)})({distanceFromPrevious:r,previousPressure:t,runningLength:o,totalLength:s,strokeWidth:i,isClosed:a});const d="number"==typeof e.pressure&&Number.isFinite(e.pressure)?lo(e.pressure,.05,1):t??.55;return null===t?d:co(t,d,.68)}(e,l,o,t,h,c,d,i);l=u;const p=r.taperEnd??!0,g=i||s.length<=1?1:Math.min(r.taperStart??1?lo(c/o.startTaper,0,1):1,p?lo((d-c)/o.endTaper,0,1):1),m=co(o.minRadiusScale,o.maxRadiusScale,u),f=Math.max(o.minRadius,o.baseRadius*m*co(.7,1,g));return{point:s[n],direction:ho(s,n,i),pressure:u,radius:f,runningLength:c}});return d<.5*o.baseRadius?c.map(e=>({...e,radius:Math.max(e.radius,.92*o.baseRadius)})):c}function go(e,t){const n=e[e.length-1];n&&n.dist2(t)<.04?e[e.length-1]=t:e.push(t)}function mo(e,t,n){const i=e.dist(t);if(0===i)return[];const r=Cc.Angle(e,t),o=[];for(let s=1;s<n;s+=1){const t=r-Math.PI*(s/n);o.push(new Cc(e.x+Math.cos(t)*i,e.y+Math.sin(t)*i))}return o}function fo(e,t,n){const i=e[e.length-1];!i||i.dist2(t)>n?go(e,t):e[e.length-1]=t}function So(e){return{...e}}function yo(e,t,n){return e.map(e=>new Cc(e.x+t,e.y+n))}function xo(e,t,n){return e.map(e=>yo(e,t,n))}function Io({segments:e,outlineVertices:t,outlinePolygons:n,strokeWidth:i,sampling:r,isClosed:o}){const s=Wr(e),a=s.map(Ur),d=a.length>0?kc.FromPoints(a):new kc(0,0,1,1),l=t.length>0?kc.FromPoints([...t]):d.expand(Math.max(i/2,1)),c=o&&s.length>=3?(e=>{if(e.length<3)return null;const t=qr(e);return t?`${t} Z`:null})(s):null,h=void 0!==n?(e=>{const t=e.map(e=>Gr(e)).filter(e=>null!==e);return t.length>0?t.join(" "):null})(n):Gr(t);return{normalizedSegments:Zr(e),normalizedPoints:jr(s),pointBounds:d,path:h,selectionPath:c??qr(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:So(r)}}function Po(e,t,n,i){const r=(({strokeWidth:e,isPen:t})=>[e,t?"pen":"pointer"].join(":"))({strokeWidth:n,isPen:i}),o=Tu.get(e),s=o?.get(r);if(s)return{normalizedSegment:Qr(s.normalizedSegment),sampling:So(s.sampling)};const a=((e,t)=>{if(e.length<=1)return{points:e.map(Hr),rawPointCount:e.length,sampledPointCount:e.length,maxPointCount:t.maxPointCount,reduced:!1,capped:!1};const n=[Hr(e[0])],i=t.minPointDistance*t.minPointDistance;let r=Ur(e[0]),o=Nr(e[0].pressure);for(let d=1;d<e.length;d+=1){const s=e[d];if(!s)continue;const a=Ur(s),l=Nr(s.pressure),c=d===e.length-1,h="straight"===s.segment,u=c||h?a:Cc.Lrp(r,a,t.positionBlend),p=h?l:void 0===l?void 0:void 0===o?l:o+(l-o)*t.pressureBlend;r=u,o=p;const g=void 0===p?{x:u.x,y:u.y,...void 0===s.segment?null:{segment:s.segment}}:{x:u.x,y:u.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(h){if(Xr(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(Hr);const i=((e,t)=>{let n=Or(e,!0);return n.length<t&&(n=Or(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(Hr)}(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:jr(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:Qr(d.normalizedSegment),sampling:So(d.sampling)}),o||Tu.set(e,l),d}function wo(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:Yr(t)}))(t,n),o=[],s=[],a=e.filter(e=>e.points.length>0);for(let u=0;u<a.length;u+=1){const e=Po(a[u],r,t,n);o.push(Qr(e.normalizedSegment)),s.push(So(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 Cc(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=uo(n,o);let c=0===l||l===e.length-1?n.per().uni():Cc.Lrp(o,n,d).per().uni();c.len2()<1e-6&&(c=a??new Cc(0,1)),a=c,fo(i,t.point.add(c.mul(t.radius)),s),fo(r,t.point.sub(c.mul(t.radius)),s)}if(t&&e.length>=3){const e=[];for(const t of i)go(e,t);for(let t=r.length-1;t>=0;t-=1)go(e,r[t]);return e}const d=[];for(const l of i)go(d,l);if(n.capEnd??1){const t=e[e.length-1];for(const e of mo(t.point,i[i.length-1],8))go(d,e)}for(let l=r.length-1;l>=0;l-=1)go(d,r[l]);if(n.capStart??1){const t=e[0];for(const e of mo(t.point,r[0],8))go(d,e)}return d}(po(Wr(o),t,n,i),i),l=(h=r.maxPointCount,{rawPointCount:(c=s).reduce((e,t)=>e+t.rawPointCount,0),sampledPointCount:c.reduce((e,t)=>e+t.sampledPointCount,0),sampledPointLimit:h,reduced:c.some(e=>e.reduced),capped:c.some(e=>e.capped)});var c,h;return Io({segments:o,outlineVertices:d,outlinePolygons:d.length>0?[d]:[],strokeWidth:t,sampling:l,isClosed:i})}function bo(e){return e.segments}function vo(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 kc(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 Co(e,t){return new Cc(e.x+t.localBounds.center.x,e.y+t.localBounds.center.y)}function ko(e,t,n){if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return t;const i=t.sub(n);return n.add(new Cc(i.x*e.scaleX,i.y*e.scaleY).rot(e.rotation))}function Bo(e){const t=e,n=Mu.get(t);if(n)return n;const i=wo(bo(e.props),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed);return Mu.set(t,i),i}function To(e,t,n=!1,i=!1){return((e,t,n=!1,i=!1)=>{const r=wo(e,t,n,i),o=r.pointBounds,s=wo(to(r.normalizedSegments,e=>new Cc(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 Mo(e){const t=e,n=Eu.get(t);if(n)return n;const i=((e,t,n,i,r)=>Io({segments:eo(e.normalizedSegments,n,i),outlineVertices:yo(e.outlineVertices,n,i),outlinePolygons:xo(e.outlinePolygons,n,i),strokeWidth:t,sampling:e.sampling,isClosed:r}))(Bo(e),e.props.strokeWidth,e.x,e.y,e.props.isClosed);return Eu.set(t,i),i}function Eo(e){const t=Co(e,Bo(e));return to((e=>eo(bo(e.props),e.x,e.y))(e),n=>ko(e,n,t))}function Ao(e){const t=e,n=Au.get(t);if(n)return n;if(0===e.rotation&&1===e.scaleX&&1===e.scaleY){const n=Mo(e);return Au.set(t,n),n}const i=Bo(e),r=Co(e,i),o=Io({segments:to(i.normalizedSegments,t=>ko(e,new Cc(t.x+e.x,t.y+e.y),r)),outlineVertices:i.outlineVertices.map(t=>ko(e,new Cc(t.x+e.x,t.y+e.y),r)),outlinePolygons:i.outlinePolygons.map(t=>t.map(t=>ko(e,new Cc(t.x+e.x,t.y+e.y),r))),strokeWidth:e.props.strokeWidth,sampling:i.sampling,isClosed:e.props.isClosed});return Au.set(t,o),o}function Ro(e){return Zr(e)}function Fo(e,t,n,i){return{x:e.x-t.x,y:e.y-t.y,...i&&n>0?{pressure:n}:null}}function Lo(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 $o(e){const t=Do(e.segments),n=t[t.length-1];return n?n.points.map(Lo):[]}function Do(e){return e.length>0?[...e]:[{points:[]}]}function zo(e){return{segments:Ro(Do(e))}}function Yo(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 Cc(t.x+i.x*o,t.y+i.y*o);return e.dist(s)}function Xo(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(Yo(e,n,i),Yo(t,n,i),Yo(n,e,t),Yo(i,e,t))}function Uo(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 Ho(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,Yo(e,r,o)))}return n}function Wo(e,t,n,i){if(0===n.length)return!1;if(Uo(e,n)||Uo(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&&Xo(e,t,o,s)<=i)return!0}return!1}function No(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Oo(e){if(!e||"object"!=typeof e)return null;const t=e,n=No(t.x,NaN),i=No(t.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(i))return null;const r=No(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 Ko(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=Oo(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 _o(e,t){if(!Array.isArray(e))return t;let n=!1;const i=[];for(const r of e){const e=Ko(r);e?(n=n||e!==r,i.push(e)):n=!0}return 0===i.length?t:n?i:e}function qo(e){return h(e)&&"draw"===e.type}function Vo({closedActionId:e,fillActionId:t,strokeActionId:n,strokeWidthActionId:i,dataUiPrefix:r}){return[{id:`${r}.style-closed`,items:[{kind:"segmented",id:`${r}.closed`,actionId:e,options:Hu.map(e=>({...e,dataUi:`${r}-${e.value}-button`}))}]},{id:`${r}.style-fill`,items:[{kind:"swatches",id:`${r}.fill`,actionId:t,label:"Fill",options:Xu.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:Yu.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:Uu.map(e=>({...e,dataUi:`${r}-stroke-width-${e.value}-button`}))}]}]}function Go(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(n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){if(!Jo(e,n))return;const i=t.selection.selectedShapes.filter(qo).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:n}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function jo(e){return{id:`draw.default-${e}`,isVisible:e=>"draw"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("draw")[e],run({context:t,value:n}){Jo(e,n)&&t.editor.updateDefaultShapeProps("draw",{[e]:n})}}}function Zo(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 Qo(e){return"closed"===e||"open"!==e&&null}function Jo(e,t){return"strokeWidth"===e?Uu.some(e=>e.value===t):"fill"===e?Xu.some(e=>e.value===t):Yu.some(e=>e.value===t)}function es({shape:e,stroke:t=e.props.stroke,strokeWidth:n=e.props.strokeWidth}){const{fillPath:i,renderBounds:r,path:o,selectionPath:s}=Bo({props:{...e.props,strokeWidth:n}});return o||s?lc("svg",{width:"100%",height:"100%",viewBox:`${r.x} ${r.y} ${Math.max(r.w,1)} ${Math.max(r.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[i&&"transparent"!==e.props.fill?dc("path",{d:i,fill:e.props.fill,stroke:"none"}):null,e.props.isClosed&&s?dc("path",{d:s,fill:"none",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}):o?dc("path",{d:o,fill:t,stroke:"none"}):null]}):null}function ts({shape:e}){
15
- return dc(es,{shape:e})}function ns(e){return 4/e.getCurrentCamera().z}function is(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 rs(e,t){const n=new Set,i=ns(e);for(const r of e.hitTestShapesAtPoint(t)){const o=e.getShapeUtil(r);if(!o.canReceiveChildren(r))continue;const s=o.getChildClipLocalBounds(r);s&&is(o.getLocalToPageTransform(r).invert().applyToPoint(t),s,i)&&n.add(r.id)}return n}function os(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 ss(e,t,n,i){const r=i.topMostOnly?n.slice(0,1):n;for(const o of r){const n=os(e,o,t);n&&t.erasingShapeIds.add(n)}}function as(e,t,n){ss(e,t,e.hitTestShapesAtPoint(n.pagePoint),{topMostOnly:n.accelKey})}function ds(e,t,n){ss(e,t,e.hitTestShapesByLineSegment(t.previousPagePoint,n.pagePoint,{margin:ns(e)}),{topMostOnly:n.accelKey})}function ls(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function cs(e,t){e.setErasingShapeIds(Array.from(t.erasingShapeIds)),e.setEraserTrail(t.trail)}function hs(e){e.clearErasingShapeIds(),e.clearEraserTrail()}function us(e,t){const n=Array.from(t.erasingShapeIds);hs(e),0!==n.length&&e.commands.deleteShapes(n,{source:"user"})}function ps(){return"undefined"==typeof performance?Date.now():performance.now()}function gs(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=Zu/n,s=xs(r,t);if(s<o)return void(e.samples[e.samples.length-1]={...r,...t,time:i});const a=s*n/Math.max(ip,i-r.time);e.samples.push({...t,time:i,velocity:ks(r.velocity,a,.68)})}function ms(e,t){e.samples=fs(e.samples,t)}function fs(e,t){const n=e[e.length-1];if(!n)return[];const i=t-Bs(rp+n.velocity*op,rp,sp);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=Bs((i-s.time)/(a.time-s.time),0,1),{...Cs(d,l,c),time:ks(d.time,l.time,c),velocity:ks(d.velocity,l.velocity,c)}),...o]:o;var d,l,c}function Ss(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?bs(i,e[t]):bs(t===e.length-1?e[t]:i,n))}function ys(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 xs(e,t){return Math.sqrt(Is(e,t))}function Is(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function Ps(e){return{x:-e.y,y:e.x}}function ws(e,t){return{x:e.x+t.x,y:e.y+t.y}}function bs(e,t){return{x:e.x-t.x,y:e.y-t.y}}function vs(e,t){return{x:e.x*t,y:e.y*t}}function Cs(e,t,n){return{x:ks(e.x,t.x,n),y:ks(e.y,t.y,n)}}function ks(e,t,n){return e+(t-e)*n}function Bs(e,t,n){return Math.max(t,Math.min(n,e))}function Ts(e,t){const n=e[e.length-1];!n||Is(n,t)>.04?e.push(t):e[e.length-1]=t}function Ms(e){if(e.length<2)return null;if(2===e.length)return`M ${As(e[0])} L ${As(e[1])} Z`;const t=[`M ${As(Es(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 ${As(i)} ${As(Es(i,r))}`)}return t.push("Z"),t.join(" ")}function Es(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function As(e){return`${Rs(e.x)},${Rs(e.y)}`}function Rs(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function Fs(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ls(e){return Math.max(6,e.props.strokeWidth+4)}function $s(e,t,n){if(!e.expand(n/2).containsPoint(t))return!1;const i=n/2,r=e.w-2*i,o=e.h-2*i;return r<=0||o<=0||!new kc(e.x+i,e.y+i,r,o).containsPoint(t)}function Ds(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(n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){if(!Us(e,n))return;const i=t.selection.selectedShapes.filter(e=>"frame"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:n}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function zs(e){return{id:`frame.default-${e}`,isVisible:e=>"frame"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("frame")[e],run({context:t,value:n}){Us(e,n)&&t.editor.updateDefaultShapeProps("frame",{[e]:n})}}}function Ys({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"swatches",id:`${i}.fill`,actionId:e,label:"Fill",options:gp.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:mp.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:fp.map(e=>({...e,dataUi:`${i}-stroke-width-${e.value}-button`}))}]}]}function Xs(e){return{id:`frame.child-order.${e}`,isVisible:e=>"frame"===Hs(e),isEnabled:t=>t.editor.canMoveSelectionWithinParent(e),run({context:t}){t.editor.moveSelectionWithinParent(e,"user")}}}function Us(e,t){return"strokeWidth"===e?fp.some(e=>e.value===t):("fill"===e?gp:mp).some(e=>e.value===t)}function Hs(e){const[t]=e.selection.selectedShapes;return 1===e.selection.count&&t?.parentId.startsWith("shape:")?e.editor.getShape(t.parentId)?.type??null:null}function Ws({shape:e}){
16
- return dc(Ns,{shape:e})}function Ns({shape:e}){const{fill:t,h:n,name:i,stroke:r,strokeWidth:o,w:s}=e.props,a=o/2,d=Math.max(s-o,0),l=Math.max(n-o,0);
17
- return lc("svg",{width:"100%",height:"100%",viewBox:`0 0 ${s} ${n}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[dc("rect",{x:a,y:a,width:d,height:l,fill:t,stroke:r,strokeWidth:o,strokeLinejoin:"round",strokeLinecap:"round"}),dc("text",{x:12,y:18,fill:r,fontFamily:["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),fontSize:12,fontWeight:600,style:{userSelect:"none"},children:i})]})}function Os(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ks(e,t){return e.x*t.y-e.y*t.x}function _s(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 qs(e,t,n,i){return Vs(e,t,n,i)?0:Math.min(_s(e,n,i),_s(t,n,i),_s(n,e,t),_s(i,e,t))}function Vs(e,t,n,i){const r=t.sub(e),o=i.sub(n),s=Ks(r,o);if(Math.abs(s)<1e-8)return null;const a=n.sub(e),d=Ks(a,o)/s,l=Ks(a,r)/s;return d<0||d>1||l<0||l>1?null:{point:e.add(r.mul(d)),t:d}}function Gs(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=Vs(e,t,o,s);!a||a.t<=1e-6||(!i||a.t<i.t)&&(i=a)}return i?.point??null}function js(e){const t=new kc(0,0,e.props.w,e.props.h);switch(e.props.geo){case"ellipse":{const e=[];for(let n=0;n<32;n+=1){const i=n/32*Math.PI*2;e.push(new Cc(t.center.x+t.w/2*Math.cos(i),t.center.y+t.h/2*Math.sin(i)))}return e}case"diamond":return[new Cc(t.center.x,t.minY),new Cc(t.maxX,t.center.y),new Cc(t.center.x,t.maxY),new Cc(t.minX,t.center.y)];default:return[new Cc(t.minX,t.minY),new Cc(t.maxX,t.minY),new Cc(t.maxX,t.maxY),new Cc(t.minX,t.maxY)]}}function Zs(e){const t=new kc(0,0,e.props.w,e.props.h);return[new Cc(t.minX,t.minY),new Cc(t.center.x,t.minY),new Cc(t.maxX,t.minY),new Cc(t.minX,t.center.y),t.center,new Cc(t.maxX,t.center.y),new Cc(t.minX,t.maxY),new Cc(t.center.x,t.maxY),new Cc(t.maxX,t.maxY)]}function Qs(e){return h(e)&&"geo"===e.type}function Js(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(n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){if(!na(e,n))return;const i=t.selection.selectedShapes.filter(Qs).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:n}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function ea(e){return{id:`geo.default-${e}`,isVisible:e=>ia(e.tool.activeToolId),getValue:t=>t.editor.getDefaultShapeProps("geo")[e],run({context:t,value:n}){na(e,n)&&t.editor.updateDefaultShapeProps("geo",{[e]:n})}}}function ta({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"swatches",id:`${i}.fill`,actionId:e,label:"Fill",options:Tp.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:Mp.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:Ep.map(e=>({...e,dataUi:`${i}-stroke-width-${e.value}-button`}))}]}]}function na(e,t){return"strokeWidth"===e?Ep.some(e=>e.value===t):("fill"===e?Tp:Mp).some(e=>e.value===t)}function ia(e){return"rectangle"===e||"ellipse"===e||"diamond"===e}function ra(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function oa({shape:e}){
18
- return dc(sa,{shape:e})}function sa({shape:e,fill:t=e.props.fill,stroke:n=e.props.stroke,strokeWidth:i=e.props.strokeWidth}){const{geo:r}=e.props,o=i/2,s=Math.max(e.props.w-i,0),a=Math.max(e.props.h-i,0),d=Math.min(10,.12*s,.12*a),l={fill:t,stroke:n,strokeWidth:i,strokeLinejoin:"round",strokeLinecap:"round"};
19
- return dc("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:"ellipse"===r?dc("ellipse",{...l,cx:e.props.w/2,cy:e.props.h/2,rx:s/2,ry:a/2}):"diamond"===r?dc("polygon",{...l,points:[`${e.props.w/2},${o}`,`${e.props.w-o},${e.props.h/2}`,`${e.props.w/2},${e.props.h-o}`,`${o},${e.props.h/2}`].join(" ")}):dc("rect",{...l,x:o,y:o,width:s,height:a,rx:d,ry:d})})}function aa(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function da({shape:e,isSelected:t}){
20
- return dc(la,{shape:e,isSelected:t})}function la({shape:e,isSelected:t=!1}){const{h:n,w:i}=e.props;
21
- return dc("svg",{width:"100%",height:"100%",viewBox:`0 0 ${i} ${n}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:t?dc("rect",{x:.5,y:.5,width:Math.max(i-1,0),height:Math.max(n-1,0),fill:"none",stroke:"#64748b",strokeDasharray:"4 4",strokeWidth:1,vectorEffect:"non-scaling-stroke"}):null})}function ca(e){return Math.min(1,Math.max(0,e))}function ha(e,t,n){return Math.min(n,Math.max(t,e))}function ua(e){return!!e&&"object"==typeof e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function pa(e,t){const n=ca(e),i=ca(t);let r=Math.min(n,i),o=Math.max(n,i);return o-r<$p&&(r=Math.max(0,Math.min(.9999,(r+o)/2-5e-5)),o=r+$p),{min:r,max:o}}function ga(e){if(!e||"object"!=typeof e)return null;const t=e;if(!ua(t.topLeft)||!ua(t.bottomRight))return null;const n=pa(t.topLeft.x,t.bottomRight.x),i=pa(t.topLeft.y,t.bottomRight.y);return{topLeft:{x:n.min,y:i.min},bottomRight:{x:n.max,y:i.max}}}function ma(e){const t=ga(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 fa(e){return ma(e)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function Sa(e,t){return Math.abs(e.left-t.left)<=Dp&&Math.abs(e.top-t.top)<=Dp&&Math.abs(e.right-t.right)<=Dp&&Math.abs(e.bottom-t.bottom)<=Dp}function ya(e){return(e=>Math.abs(e.left)<=Dp&&Math.abs(e.top)<=Dp&&Math.abs(1-e.right)<=Dp&&Math.abs(1-e.bottom)<=Dp)(e)?null:ga({topLeft:{x:e.left,y:e.top},bottomRight:{x:e.right,y:e.bottom}})}function xa({centerX:e,centerY:t,height:n,width:i}){const r=ha(i,$p,1),o=ha(n,$p,1),s=ha(e-r/2,0,1-r),a=ha(t-o/2,0,1-o);return{left:s,top:a,right:s+r,bottom:a+o,width:r,height:o}}function Ia(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function Pa({crop:e,shape:t}){const n=fa(e);return{w:t.props.w/n.width,h:t.props.h/n.height}}function wa(e,t){return t===ba(e.id)}function ba(e){return`${Yp}${e}`}function va({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 Cc(0,0),top:new Cc(r,0),top_right:new Cc(n,0),right:new Cc(n,o),bottom_right:new Cc(n,i),bottom:new Cc(r,i),bottom_left:new Cc(0,i),left:new Cc(0,o)};return Hp.map(t=>{return{kind:"custom",type:"image.crop",id:t,point:e.applyToPoint(s[t]),cursor:(n=t,Up[n])};var n})}function Ca({change:e,crop:t,shape:n}){const i=Pa({crop:t,shape:n}),r=t.bottomRight.x-t.topLeft.x,o=t.bottomRight.y-t.topLeft.y,s=ha(t.topLeft.x-e.x/i.w,0,1-r),a=ha(t.topLeft.y-e.y/i.h,0,1-o),d=ga({topLeft:{x:s,y:a},bottomRight:{x:s+r,y:a+o}});return d?{id:n.id,props:{crop:d}}:null}function ka(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Ba(e){Wp.delete(e)}function Ta(e){return g(e)&&"image"===e.type}function Ma(e){return h(e)&&"image"===e.type}function Ea(){return{createSession(e,{handle:t,shape:n,originPagePoint:i}){return Ma(n)&&"custom"===t.kind&&"image.crop"===t.type&&(r=t.id,Hp.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(!Ma(s.getShape(t)))return"stop";const l=(({handleId:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:r,currentPagePoint:o})=>{const s=ga(i)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=Pa({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},h=c.x+c.w,u=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=ha(p+l.x,0,h-8),m=h-p):(e=>"top_right"===e||"right"===e||"bottom_right"===e)(e)&&(m=ha(h+l.x,c.x+8,a.w)-p),(e=>"top_left"===e||"top"===e||"top_right"===e)(e)?(g=ha(g+l.y,0,u-8),f=u-g):(e=>"bottom_left"===e||"bottom"===e||"bottom_right"===e)(e)&&(f=ha(u+l.y,c.y+8,a.h)-g);const S=ga({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 Cc(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 Aa(){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=Ra(e);if(!n)return"continue";if("Escape"===t.key&&!t.altKey&&!t.accelKey)return e.cancelEditing("user")&&Ba(n.id),"handled";if("Enter"===t.key&&!t.altKey&&!t.accelKey)return e.completeEditing("user")&&Ba(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 Cc(t,0);case"ArrowRight":return new Cc(-t,0);case"ArrowUp":return new Cc(0,t);case"ArrowDown":return new Cc(0,-t);default:return null}})(t);if(i){const t=(({pageDelta:e,shape:t,startCrop:n})=>{const i=ga(n);return!i||e.equals(Cc.Zero())?null:Ca({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(zp),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=Ra(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")?(Ba(r.id),n.dispatch(i),"handled"):"continue":"continue"}return e&&i.pointerId===e.pointerId?"pointer_move"===i.name?(Fa(n,i,e),"handled"):"pointer_up"===i.name?(Fa(n,i,e),e.hasDragged&&n.history.squashToMark(zp,"shape.edit"),t(),"handled"):"continue":"continue"}},selectionHandle:Ea()}}function Ra(e){const[t]=e.getSelectedShapes();if(!Ma(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&wa(t,n.markId)?t:null}function Fa(e,t,n){if(!n.hasDragged){if(n.startPagePoint.dist2(t.pagePoint)<9)return;e.history.mark(zp),n.hasDragged=!0}if(!Ma(e.getShape(n.shapeId)))return;const i=(({currentPagePoint:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:r,shiftKey:o})=>{const s=ga(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 Cc(0,d.y):new Cc(d.x,0)),0===d.x&&0===d.y?null:Ca({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 La(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function $a(){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 Np],shapeSvgExporters:[new Qp],interactionHandlers:[Aa()],toolbarActions:[Ya(_p),Ya(Op),Ya(Kp),{id:qp,isVisible:e=>!!Da(e)&&!za(e),isEnabled(e){const t=Da(e);return!!t&&!t.isLocked},getValue:e=>za(e),run({context:e}){const t=Da(e);if(!t||t.isLocked)return;const n=e.editor.getShapeEditingSession();n?.shapeId===t.id&&wa(t,n.markId)?e.editor.completeEditing("user"):e.editor.startEditingShape({shapeId:t.id,markId:ba(t.id),entryMode:"focusEnd"},"user")&&(e=>{Wp.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:Vp,isVisible:e=>za(e),isEnabled:e=>za(e),run({context:e}){const t=Da(e);t&&e.editor.completeEditing("user")&&Ba(t.id)}},{id:Gp,isVisible:e=>za(e),isEnabled(e){const t=Da(e);return!!t&&!t.isLocked},run({context:e,value:t}){const n=Da(e);if(!n||n.isLocked||-1!==t&&1!==t)return;const i=(({direction:e,shape:t})=>{const n=fa(t.props.crop),i=Ia(n),r=ha("in"===e?.8:1.25,Math.max($p/n.width,$p/n.height),Math.min(1/n.width,1/n.height)),o=xa({centerX:i.x,centerY:i.y,width:n.width*r,height:n.height*r});return Sa(n,o)?null:{id:t.id,props:{crop:ya(o)}}})({direction:1===t?"in":"out",shape:n});i&&e.editor.commands.updateShapes([i],{source:"user"})}},{id:jp,isVisible:e=>za(e),isEnabled(e){const t=Da(e);return!!t&&!t.isLocked},getValue(e){const t=Da(e);return t?(e=>{const t=e.props.w/e.props.h;for(const n of Xp)if(Math.abs(t-n.ratio)<=.01)return n.value;return null})(t):null},run({context:e,value:t}){const n=Da(e);if(!n||n.isLocked||"string"!=typeof t)return;const i=Xp.find(e=>e.value===t);if(!i)return;const r=function({preset:e,shape:t}){const n=fa(t.props.crop),i=Ia(n),r=Pa({crop:t.props.crop,shape:t}),o=Xp.find(t=>t.value===e)?.ratio??null;if(!o)return null;const s=o*(r.h/r.w);let a=n.width,d=a/s;return d>n.height&&(d=n.height,a=d*s),(({nextRect:e,shape:t})=>{const n=fa(t.props.crop);if(Sa(n,e))return null;const i=Pa({crop:t.props.crop,shape:t}),r=new Cc((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:ya(e)}}})({nextRect:xa({centerX:i.x,centerY:i.y,width:a,height:d}),shape:t})}({preset:i.value,shape:n});r&&e.editor.commands.updateShapes([r],{source:"user"})}},{id:Zp,isVisible:e=>za(e),isEnabled(e){const t=Da(e);return!!t&&!t.isLocked&&!!t.props.crop},run({context:e}){const t=Da(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=ga(e.props.crop);return Math.abs(t.x-n)<=Dp&&Math.abs(t.y-i)<=Dp&&Math.abs(t.props.w-r)<=Dp&&Math.abs(t.props.h-o)<=Dp&&(null===t.props.crop&&null===s||null!==t.props.crop&&null!==s&&Math.abs(t.props.crop.topLeft.x-s.topLeft.x)<=Dp&&Math.abs(t.props.crop.topLeft.y-s.topLeft.y)<=Dp&&Math.abs(t.props.crop.bottomRight.x-s.bottomRight.x)<=Dp&&Math.abs(t.props.crop.bottomRight.y-s.bottomRight.y)<=Dp)?null:{id:t.id,x:n,y:i,props:{w:r,h:o,crop:s}}})({baselineShape:(i=t.id,Wp.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:[_p],getGroups:()=>[{id:"image.tools",items:[{kind:"button",id:_p,actionId:_p,label:"Image",icon:"image-plus",dataUi:"insert-image-tool-button"}]}]},{id:"image.selection-toolbar",surface:"selection",order:30,actionIds:[qp,Vp,Gp,jp,Zp,Op,Kp],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups(e){const t=[];return za(e)&&t.push({id:"image.crop-zoom",order:10,items:[{kind:"stepper",id:"image.crop.zoom-stepper",actionId:Gp,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:jp,options:Xp.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:Zp,actionId:Zp,label:"Reset crop",icon:"rotate-ccw",dataUi:"reset-image-crop-button"}]}),t.push({id:"image.asset",order:40,items:[{kind:"button",id:qp,actionId:qp,label:"Crop image",icon:"crop",dataUi:"crop-image-button"},{kind:"button",id:Vp,actionId:Vp,label:"Done cropping",icon:"check",dataUi:"done-cropping-button"},{kind:"button",id:Op,actionId:Op,label:"Replace image",icon:"image-plus",dataUi:"replace-image-button"},{kind:"button",id:Kp,actionId:Kp,label:"Download original",icon:"download",dataUi:"download-image-original-button"}]}),t}}],contextMenuContributions:[{id:"image.shape-context-menu",target:"selection",order:30,actionIds:[qp,Op,Kp],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getSections:()=>[{id:"image.asset-context-menu",title:"Image",items:[{kind:"command",id:qp,actionId:qp,label:"Crop image",icon:"crop",dataUi:"context-menu-crop-image-button"},{kind:"command",id:Op,actionId:Op,label:"Replace image",icon:"image-plus",dataUi:"context-menu-replace-image-button"},{kind:"command",id:Kp,actionId:Kp,label:"Download original",icon:"download",dataUi:"context-menu-download-image-original-button"}]}]}]}}function Da(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return null;const[t]=e.selection.selectedShapes;return Ma(t)?t:null}function za(e){const t=Da(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!wa(t,n.markId))}function Ya(e){return{id:e,isVisible:()=>!1,isEnabled:()=>!1,run(){throw new Error(`Image toolbar action ${e} requires a host implementation.`)}}}function Xa({editor:e,shape:t,shapeEditingSession:n}){const{altText:i,assetId:r,crop:o,h:s,w:a}=t.props,d=r?e.resolveAssetUrl(r):null;if(!d)return dc("div",{"data-ui":"image-shape-missing-asset",style:{alignItems:"center",background:"#f1f5f9",border:"1px solid #cbd5e1",color:"#64748b",display:"flex",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:12,height:s,justifyContent:"center",overflow:"hidden",width:a},children:"Missing image"});const l=(({crop:e,shapeHeight:t,shapeWidth:n})=>{const i=ma(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:o,shapeHeight:s,shapeWidth:a});if(l){const e=n?.shapeId===t.id&&wa(t,n.markId),r={display:"block",height:l.imageHeight,left:l.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:l.imageY,userSelect:"none",width:l.imageWidth};
22
- return lc("div",{"data-ui":"image-shape",style:{display:"block",height:s,overflow:e?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[e?dc("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:d,style:{...r,opacity:.1}}):null,dc("div",{"data-ui":"image-crop-window",style:{height:s,overflow:"hidden",position:"absolute",inset:0,width:a},children:dc("img",{alt:i,draggable:!1,src:d,style:r})})]})}
23
- return dc("img",{alt:i,"data-ui":"image-shape",draggable:!1,src:d,style:{display:"block",height:s,objectFit:"fill",pointerEvents:"none",userSelect:"none",width:a}})}function Ua(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function Ha(e,t){e.setLaserTrail(t.sessionId,t.trail)}function Wa(){return"undefined"==typeof performance?Date.now():performance.now()}function Na(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=hg/n,s=Va(r,t);if(s<o)return void(e.samples[e.samples.length-1]={...r,...t,time:i});const a=s*n/Math.max(Sg,i-r.time);e.samples.push({...t,time:i,velocity:td(r.velocity,a,.68)})}function Oa(e,t){e.samples=Ka(e.samples,t)}function Ka(e,t){const n=e[e.length-1];if(!n)return[];const i=t-nd(yg+n.velocity*xg,yg,Ig);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=nd((i-s.time)/(a.time-s.time),0,1),{...ed(d,l,c),time:td(d.time,l.time,c),velocity:td(d.velocity,l.velocity,c)}),...o]:o;var d,l,c}function _a(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?Qa(i,e[t]):Qa(t===e.length-1?e[t]:i,n))}function qa(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 Va(e,t){return Math.sqrt(Ga(e,t))}function Ga(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function ja(e){return{x:-e.y,y:e.x}}function Za(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Qa(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Ja(e,t){return{x:e.x*t,y:e.y*t}}function ed(e,t,n){return{x:td(e.x,t.x,n),y:td(e.y,t.y,n)}}function td(e,t,n){return e+(t-e)*n}function nd(e,t,n){return Math.max(t,Math.min(n,e))}function id(e,t){const n=e[e.length-1];!n||Ga(n,t)>.04?e.push(t):e[e.length-1]=t}function rd(e){if(e.length<2)return null;if(2===e.length)return`M ${sd(e[0])} L ${sd(e[1])} Z`;const t=[`M ${sd(od(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 ${sd(i)} ${sd(od(i,r))}`)}return t.push("Z"),t.join(" ")}function od(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function sd(e){return`${ad(e.x)},${ad(e.y)}`}function ad(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function dd(e){return{type:"doc",content:e.split("\n").map(e=>({type:"paragraph",content:e.length>0?[{type:"text",text:e}]:[]}))}}function ld(e){return e.content.map(e=>gd(e)).join("\n")}function cd(e){if(!e||"object"!=typeof e)return dd("");const t=e,n=Array.isArray(t.content)?t.content.map(e=>Sd(e,0)).filter(e=>null!==e):[];return{type:"doc",attrs:xd(t.attrs),content:n}}function hd(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>fd(e)).join("")??"";return`<p style="margin:0">${t.length>0?t:"<br>"}</p>`})(e)).join("")}function ud(e){return"text"===e.type&&"string"==typeof e.text}function pd(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 gd(e){return ud(e)?e.text:e.content?.map(e=>gd(e)).join("")??""}function md(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 fd(e){if(ud(e)){const t=pd(e.marks),n=e.text.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");return t?`<span style="${md(t)}">${n}</span>`:n}return e.content?.map(e=>fd(e)).join("")??""}function Sd(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(yd).filter(e=>null!==e):void 0}))(n);return e.text.length>0?e:null}return Sd(n,t)}(e,t+1)).filter(e=>null!==e):[];return{type:i,attrs:xd(n.attrs),content:r}}function yd(e){return e&&"object"==typeof e?"string"!=typeof e.type?null:{type:e.type,attrs:xd(e.attrs)}:null}function xd(e){if(!e||"object"!=typeof e)return;const t=Object.entries(e).map(([e,t])=>[e,Id(t)]).filter(e=>void 0!==e[1]);return t.length>0?Object.fromEntries(t):void 0}function Id(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=>Id(e,t+1)).filter(e=>void 0!==e);if(e&&"object"==typeof e){const n=Object.entries(e).map(([e,n])=>[e,Id(n,t+1)]).filter(e=>void 0!==e[1]);return Object.fromEntries(n)}}}function Pd(e){return e.content.map((e,t)=>((e,t)=>{const n=wd(e,t);
24
- return dc("p",{style:{margin:0},children:n.length>0?n:dc("br",{})},t)})(e,`block:${t}`))}function wd(e,t){return e.content?.map((e,n)=>((e,t)=>ud(e)?dc("span",{style:pd(e.marks),children:e.text},t):wd(e,t))(e,`${t}:${n}`))??[]}function bd(e,t){const n=(e=>{if((e=>Object.prototype.hasOwnProperty.call(bg,e))(e))return bg[e]})(e),i=t??("undefined"==typeof document?void 0:document);if(!n||!i)return Promise.resolve();const r=(e=>{const t=vg.get(e);if(t)return t;const n=new Map;return vg.set(e,n),n})(i),o=r.get(e);if(o)return o;const s=(async(e,t)=>{await((e,t)=>e.querySelector(`link[data-land-text-web-font="${t.font}"]`)?Promise.resolve():new Promise(n=>{const i=e.createElement("link");i.rel="stylesheet",i.href=t.cssUrl,i.dataset.landTextWebFont=t.font;const r=()=>n();i.addEventListener("load",r,{once:!0}),i.addEventListener("error",r,{once:!0}),(e.head??e.documentElement).appendChild(i)}))(e,t),await(async(e,t)=>{const{fonts:n}=e;n&&await Promise.all(t.weights.map(e=>n.load(`${e} 16px "${t.family}"`,"字体Aa")))})(e,t)})(i,n).catch(()=>{r.delete(e)});return r.set(e,s),s}function vd(e){return h(e)&&"text"===e.type}function Cd(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 kd(e){return Cd(e.getDefaultShapeProps("text"))}function Bd(e,t,n="user"){const i={...kd(e),...t.props,richText:t.props?.richText??dd("")},[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(!vd(r))throw new Error("Failed to create text shape");return r}function Td(e){try{return e.view.dom.isConnected}catch{return!1}}function Md(e){!e.isDestroyed&&Td(e)&&(e.view.dom.focus(),e.view.focus())}function Ed(e){if(!Td(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 Ad(e){switch(e){case"noto-sans-sc":return"'Noto Sans SC', Inter, ui-sans-serif, system-ui, sans-serif";case"noto-serif-sc":return"'Noto Serif SC', Georgia, Cambria, serif";case"noto-sans-mono":return"'Noto Sans Mono', 'SFMono-Regular', Consolas, monospace";case"ma-shan-zheng":return"'Ma Shan Zheng', 'Comic Sans MS', 'Marker Felt', cursive";default:return"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"}}function Rd(e){return kg[e].fontSize}function Fd(e){return kg[e].lineHeight}function Ld(e,t=1){return Math.max(1,Math.ceil(Fd(e)*t))}function $d(e){switch(e){case"middle":return"center";case"end":return"right";default:return"left"}}function Dd(e,t){return 0===ld(e).trim().length?zd(t):Yd(t,(n=hd(e),i={width:t.props.autoSize?void 0:t.props.w,shape:t},Xd(document).measureHtml(n,i)));var n,i}function zd(e){const t=e.props.autoSize?16:e.props.w,n=Ld(e.props.size);if(e.props.w!==t||e.props.h!==n)return{w:t,h:n}}function Yd(e,t){const n=e.props.autoSize?Math.max(16,Math.ceil(t.w)):e.props.w,i=Math.max(Ld(e.props.size),Math.ceil(t.h));if(n!==e.props.w||i!==e.props.h)return{w:n,h:i}}function Xd(e){const t=Tg.get(e);if(t)return t;const n=new Bg(e);return Tg.set(e,n),n}function Ud(e,t,n){n&&"normal"!==n&&"auto"!==n&&(e.style[t]=n)}function Hd({shapeId:e,editor:t}){return{shapeId:e,isDestroyed:()=>t.isDestroyed,isConnected:()=>!t.isDestroyed&&Td(t),isFocused:()=>!t.isDestroyed&&Td(t)&&t.view.dom.contains(document.activeElement),getValue:()=>cd(t.getJSON()),setValue(e){t.commands.setContent(e)},focus(){Md(t)},focusEnd(){!t.isDestroyed&&Td(t)&&t.commands.focus("end")},focusSelectAll(){!t.isDestroyed&&Td(t)&&(Md(t),t.chain().focus().selectAll().run())},focusAtPagePoint(e,n){((e,t,n)=>{Md(t);const i=e.pageToScreen(new Cc(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||!Td(t)?{type:null,text:null}:Ed(t),collapseSelectionAtClientPoint(e,n){!t.isDestroyed&&Td(t)&&"Range"===Ed(t).type&&((e,t,n)=>{if(e.isDestroyed||!Td(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&&Td(t))return function(e,t){if(0===e.getText().trim().length)return zd(t);const n=((e,t)=>{const n=e.ownerDocument.defaultView?.getComputedStyle(e);return Xd(e.ownerDocument).measureElement(e,t,n)})(e.view.dom,{shape:t,width:t.props.autoSize?void 0:t.props.w});return e.view.dom.scrollHeight>t.props.h+1&&(n.h=Math.max(n.h,e.view.dom.scrollHeight)),Yd(t,n)}(t,e)},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 Wd(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 Nd(e){return e instanceof Element&&null!==e.closest('[data-ui="rich-text-formatting-toolbar"]')}function Od({editor:e}){const t=ic(()=>({strategy:"fixed",placement:"top",offset:Wd("--toolbar-floating-offset",8),flip:!0,shift:{padding:Wd("--toolbar-floating-shift-padding",8)}}),[]);return e.isDestroyed?null:lc(fc,{editor:e,updateDelay:0,resizeDelay:0,appendTo:Kd,shouldShow:_d,options:t,"data-ui":"rich-text-formatting-toolbar",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:[
25
- dc("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"}),
26
- dc("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)"}}),Mg.map(t=>dc(qd,{editor:e,format:t.id,label:t.label,shortcut:t.shortcut,dataUi:t.dataUi,children:t.content},t.id))]})}function Kd(){return document.body}function _d({editor:e,element:t,view:n}){return e.isEditable&&!e.isDestroyed&&!e.state.selection.empty&&(n.hasFocus()||t.contains(document.activeElement))}function qd({editor:e,format:t,label:n,shortcut:i,dataUi:r,children:o}){const s=oc(!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()}};
27
- return dc("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 Vd({landEditor:e,shape:t,initialRichText:n,className:i,editorStyle:r,onReady:o,onDispose:s,onRichTextChange:a}){const[d,l]=sc(0),c=oc(null),h=Ql(e=>{const n=c.current;if(n?.editor===e)return n.controller;const i=Hd({shapeId:t.id,editor:e});return c.current={editor:e,controller:i},i},[t.id]),u=hc({extensions:Eg,content:n,autofocus:!1,editable:!0,immediatelyRender:!0,shouldRerenderOnTransaction:!1,editorProps:{attributes:{"data-ui":"rich-text-editor",class:"land-rich-text-editor h-full min-h-full w-full outline-none whitespace-pre-wrap break-words",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);a({editor:e,controller:t,richText:t.getValue()})}},[t.id]);return ec(()=>{if(!u||u.isDestroyed)return;const e={editor:u,controller:h(u)};return o(e),()=>{c.current?.editor===u&&(c.current=null),s(e)}},[h,s,o,u]),ec(()=>{if(!u||u.isDestroyed)return;const e=()=>{l(e=>e+1)};return u.on("selectionUpdate",e),u.on("update",e),u.on("focus",e),u.on("blur",e),()=>{u.off("selectionUpdate",e),u.off("update",e),u.off("focus",e),u.off("blur",e)}},[u]),lc(ac,{children:[u?dc(Od,{editor:u,version:d}):null,dc(cc,{editor:u,className:i,style:r})]})}function Gd({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(()=>{Gd({editor:e,controller:t,shapeId:n,request:i,onApplied:r,attempt:o+1})})}}function jd(e,t,n){if(t.isDestroyed()||!t.isConnected())return;const i=t.measure(n);i&&Qd(e,n,i,"user")}function Zd(e,t,n="system"){const i=Dd(t.props.richText,t);i&&Qd(e,t,i,n)}function Qd(e,t,n,i){const r=e.getShape(t.id);vd(r)&&r.props.w===n.w&&r.props.h===n.h||e.commands.updateShapes([{id:t.id,props:n}],{source:i})}function Jd({shapeId:e,markId:t}){const n=xi(),i=Ii(n.getShapeSignal(e)),r=Ii(n.shapeEditingStateSignal).session;return vd(i)&&r?.shapeId===i.id?dc(el,{shape:i,session:r},`${i.id}:${t}`):null}function el({shape:e,session:t}){const n=xi(),i=oc(e.props.richText),r=(e=>{const t=oc(e);return ec(()=>{t.current=e},[e]),t})(e),o=Ii(n.shapeEditingEntryRequestSignal),s=oc(null),[a,d]=sc(null),[l,c]=sc(null),h=Ql(({editor:e,controller:t})=>{d(e.isDestroyed?null:e),c(t)},[]),u=Ql(({editor:e,controller:t})=>{d(t=>t===e?null:t),c(e=>e===t?null:e)},[]),p=function({editor:e,shape:t,tiptapEditor:n,richTextController:i,latestShapeRef:r}){const o=oc(t.props.richText),s=oc(!1),a=oc(null),d=Ql(({controller:n,richText:i})=>{if(s.current||!n.isConnected())return;const d=cd(i);o.current=d,((e,t,n,i,r="user")=>{const o=e.getShape(t);vd(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,d,n.measure(r.current)??Dd(d,r.current),"user"),((e,t,n,i)=>{null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,jd(e,t,n.current)},0)})(e,n,r,a)},[e,r,t.id]);return ec(()=>()=>{null!==a.current&&(window.clearTimeout(a.current),a.current=null)},[]),nc(()=>{n&&i&&!n.isDestroyed&&i.isConnected()&&jd(e,i,t)},[e,i,t,n]),ec(()=>{if(!n||!i||!i.isConnected())return;const e=t.props.richText;e!==o.current&&(JSON.stringify(o.current)!==JSON.stringify(e)?(s.current=!0,i.setValue(e),o.current=e,s.current=!1):o.current=e)},[i,t.props.richText,n]),ec(()=>{if(i)return i.onCompositionStateChange(t=>{e.setShapeEditingComposition(t,"system")})},[e,i]),ec(()=>{if(!i||!i.isConnected())return;let n=!1;return bd(t.props.font).then(()=>{!n&&i.isConnected()&&jd(e,i,r.current)}),()=>{n=!0}},[e,r,i,t.props.font]),d}({editor:n,shape:e,tiptapEditor:a,richTextController:l,latestShapeRef:r});(({editor:e,shapeId:t,session:n,tiptapEditor:i,richTextController:r,entryRequest:o,consumedEntryRequestIdRef:s})=>{const a=oc(null),d=oc(null);ec(()=>{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]),ec(()=>{i&&!i.isDestroyed&&r&&null===s.current&&d.current!==n.markId&&(d.current=n.markId,window.setTimeout(()=>{Gd({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]),ec(()=>{i&&!i.isDestroyed&&r&&o&&o.shapeId===t&&s.current!==o.id&&Gd({editor:e,controller:r,shapeId:t,request:o,onApplied(e){e&&(s.current=e.id)}})},[s,e,o,r,t,i]),ec(()=>{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(()=>{Gd({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:n,shapeId:e.id,session:t,tiptapEditor:a,richTextController:l,entryRequest:o,consumedEntryRequestIdRef:s});const g=(({editor:e,shapeId:t,richTextController:n})=>{const i=oc(null);return{onPointerDownCapture:Ql(r=>{if(r.stopPropagation(),Nd(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:Ql(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:Ql(r=>{const o=i.current;if(i.current=null,Nd(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:Ql(()=>{i.current=null},[])}})({editor:n,shapeId:e.id,richTextController:l}),m=(e=>ic(()=>({color:e.props.color,fontFamily:Ad(e.props.font),fontSize:Rd(e.props.size),lineHeight:`${Fd(e.props.size)}px`,textAlign:$d(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]))(e);
28
- return dc("div",{"data-ui":"text-editing-box","data-shape-id":e.id,"data-mount-target-kind":"shape",onPointerDown:e=>{e.stopPropagation()},onPointerDownCapture:g.onPointerDownCapture,onPointerMoveCapture:g.onPointerMoveCapture,onPointerUpCapture:g.onPointerUpCapture,onPointerCancel:g.onPointerCancel,onContextMenu:e=>{e.stopPropagation()},onDragStart:e=>{e.preventDefault()},style:m,children:dc(Vd,{landEditor:n,shape:e,initialRichText:i.current,className:"h-full min-h-full w-full",editorStyle:{height:"100%",minHeight:"100%"},onReady:h,onDispose:u,onRichTextChange:p})})}function tl(){return ec(()=>{bd(Cg)},[]),null}function nl({shape:e,editor:t}){const{isEditingThisShape:n,editingHost:i}=function(e,t){const n=Ii(e.shapeEditingStateSignal).session,i=n?.shapeId===t.id,r=n&&i?dc(Jd,{shapeId:n.shapeId,markId:n.markId},n.shapeId+":"+n.markId):null;return(({editor:e,shape:t,isEditingThisShape:n})=>{nc(()=>{if(n)return;Zd(e,t);let i=!1;return bd(t.props.font).then(()=>{if(i)return;const n=e.getShape(t.id);vd(n)&&n.props.font===t.props.font&&Zd(e,n)}),()=>{i=!0}},[e,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:i}),{isEditingThisShape:i,editingHost:r}}(t,e);
29
- return lc("div",{"data-editing-hidden":n?"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:e.props.color,fontFamily:Ad(e.props.font),fontSize:Rd(e.props.size),lineHeight:`${Fd(e.props.size)}px`,textAlign:$d(e.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none"},children:[dc("div",{style:{opacity:n?0:void 0},children:Pd(e.props.richText)}),dc("div",{"data-ui":"text-editor-host-slot","data-shape-id":e.id,"data-active":n?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:i})]})}function il(e){return Cd(e)}function rl(e,t,n){const i=e.getBindingsToShape(t).find(e=>e.type===n);if(!i)return null;const r=e.getShape(i.fromId);return vd(r)?r:null}function ol(e,t){const n=kd(e);e.history.mark(t.historyMarkId);const i=Bd(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 sl(e,t){const n=e.getShape(t);if(!vd(n))return null;const i=e.getBindingsFromShape(t).find(e=>e.type in Yg);if(!i)return null;const r=i.type;return{label:n,ownerId:i.toId,bindingType:r,behavior:Yg[r]}}function al(e,t,n){e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:n.isExisting?n.editMarkId:n.createMarkId,reuseExistingMark:!n.isExisting},"user")}function dl(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function ll(e){return"string"==typeof e&&Ug.includes(e)}function cl(e){return"string"==typeof e&&Hg.includes(e)}function hl(e){return Math.max(.01,e.props.scale)}function ul(e){return e.props.w*hl(e)}function pl(e){return e.props.h*hl(e)}function gl(e){return new kc(0,0,ul(e),pl(e))}function ml(e){return"left"===e||"right"===e}function fl(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>Sl(e))??[];return{tag:"p",attrs:{style:"margin:0"},children:t.length>0?t:[{tag:"br"}]}})(e))}function Sl(e){if(ud(e)){const t=(e=>{const t=pd(e.marks);return t?md(t):void 0})(e);return t?{tag:"span",attrs:{style:t},children:[e.text]}:e.text}return{tag:"span",children:e.content?.map(e=>Sl(e))??[]}}function yl(e){return[`color:${e.props.color}`,`font-family:${Ad(e.props.font)}`,`font-size:${Rd(e.props.size)}px`,`line-height:${Fd(e.props.size)}px`,`text-align:${$d(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 xl(e){return"shape"===e?.typeName&&"arrow"===e.type}function Il(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Pl(e,t,n){const i=e.computeShapePageCenter(n),r=(e=>{const t=e.props,n=wl(t.start),i=wl(t.end),r=bl(t.bend)??0;if(!n||!i)return null;const o=Cc.Med(n,i).add(i.sub(n).len()?i.sub(n).per().normalize().mul(-r):new Cc(0,r)),s=new Cc(e.x+(e=>bl(e.props.w)??1)(e)/2,e.y+(e=>bl(e.props.h)??1)(e)/2),a=new Cc(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 Cc(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 wl(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 Cc(t.x,t.y):null}function bl(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function vl(e){return"shape"===e?.typeName&&"geo"===e.type}function Cl(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function kl(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Bl(e,t){const n=e.props[t];return"number"==typeof n&&Number.isFinite(n)?n:null}function Tl(e,t){const n=Bl(e,"h");return!n||t.props.ownerBaseHeight<=0||n===t.props.ownerBaseHeight?null:{...e,props:{...e.props,h:t.props.ownerBaseHeight}}}function Ml(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 El(){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&&vd(s)&&e.canEditShape(s)?(e.startEditingShape({shapeId:s.id,entryMode:"placeCaret",caretPagePoint:t.pagePoint,markId:Vg,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&&vd(t)&&n.canEditShape(t)?(n.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:Vg},"user"),"handled"):"continue"}return"click"===i.type&&"double_click"===i.name?(t(),((e,t)=>{const n=e.hitTestShape(t.pagePoint);return n?vd(n)?e.canEditShape(n)?(e.startEditingShape({shapeId:n.id,entryMode:"selectAll",markId:Vg},"user"),"handled"):"continue":"geo"===n.type?((e,t)=>{if(t.isLocked)return"continue";const n=rl(e,t.id,zg);return al(e,n??((e,t)=>{const n=Ml(e,Al(t,{...kd(e),autoSize:!1,textAlign:"middle"}),t);return ol(e,{bindingType:zg,owner:t,historyMarkId:Qg,index:`${t.index}${_g}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})})(e,t),{editMarkId:Zg,createMarkId:Qg,isExisting:!!n}),"handled"})(e,n):(e=>"arrow"===e.type)(n)?((e,t)=>{if(t.isLocked)return"continue";const n=rl(e,t.id,Dg);return al(e,n??((e,t)=>{const n=Pl(e,Al(t,{...kd(e),autoSize:!1,textAlign:"middle"}),t);return ol(e,{bindingType:Dg,owner:t,historyMarkId:jg,index:`${t.index}${Og}`,layout:n,bindingProps:{labelPosition:.5}})})(e,t),{editMarkId:Gg,createMarkId:jg,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||!vd(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:Vg,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=sl(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 Al(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 Rl({colorActionId:e,fontActionId:t,sizeActionId:n,textAlignActionId:i,dataUiPrefix:r}){return[{id:`${r}.style-color`,items:[{kind:"swatches",id:`${r}.color`,actionId:e,label:"Color",options:Jg.map(e=>({...e,dataUi:`${r}-color-${e.label.toLowerCase()}-button`}))}]},{id:`${r}.style-font`,items:[{kind:"segmented",id:`${r}.font`,actionId:t,options:em.map(e=>({...e,dataUi:`${r}-font-${e.value}-button`}))}]},{id:`${r}.style-size`,items:[{kind:"segmented",id:`${r}.size`,actionId:n,options:tm.map(e=>({...e,dataUi:`${r}-size-${e.value}-button`}))}]},{id:`${r}.style-align`,items:[{kind:"segmented",id:`${r}.align`,actionId:i,options:nm.map(e=>({...e,dataUi:`${r}-align-${e.value}-button`}))}]}]}function Fl(e){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(n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){if(!$l(e,n))return;const i=t.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:n}}));0!==i.length&&t.editor.commands.updateShapes(i,{source:"user"})}}}function Ll(e){return{id:`text.default-${e}`,isVisible:e=>"text"===e.tool.activeToolId,getValue:t=>t.editor.getDefaultShapeProps("text")[e],run({context:t,value:n}){$l(e,n)&&t.editor.updateDefaultShapeProps("text",{[e]:n})}}}function $l(e,t){return"string"==typeof t&&("color"===e?Jg.some(e=>e.value===t):"font"===e?em.some(e=>e.value===t):"size"===e?tm.some(e=>e.value===t):nm.some(e=>e.value===t))}function Dl(e){return{id:e.id,name:e.name,index:e.index}}function zl(e,t){return{id:e.id,parentId:e.parentId,pageId:e.pageId,type:e.type,childIds:e.childIds.slice(),siblingIndex:e.index,depth:e.depth,displayName:e.type,canReceiveChildren:t.canUseShapeParent(e.id),isHidden:e.isHidden,isLocked:e.isLocked,isEffectivelyHidden:e.isEffectivelyHidden,isEffectivelyLocked:e.isEffectivelyLocked}}function Yl(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 Xl({api:e,exposeOnWindow:t=!1,windowKey:n,onDispose:i,onReady:r}){const o=tc(e=>{r?.(e)}),s=tc(()=>{i?.()});ec(()=>{const i=window;return t&&n&&(i[n]=e),o(e),()=>{t&&n&&i[n]===e&&delete i[n],s()}},[e,t,n])}function Ul(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 Hl(e){return{createRectangle:t=>Ul(e,"rectangle",t),createEllipse:t=>Ul(e,"ellipse",t),createDiamond:t=>Ul(e,"diamond",t)}}function Wl(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,color:t.color??n.color,size:t.size??n.size,richText:dd(t.text)}}],{source:"user"});return i&&"text"===i.type?{id:i.id,type:i.type}:null}}}function Nl(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.updateShapes(r.map(e=>({id:e,parentId:n})),{source:"user"}),r)}}}function Ol({api:e,context:t,token:n}){return t.apiRegistry.get(n)||(t.apiRegistry.register(n,e),e)}function Kl(e,t){const n=e.apiRegistry.get(t);if(!n)throw new Error(`Missing product API: ${t.id}`);return n}function _l(e){return{arrow:Ol({api:(t=e.editor,{create(e){const n=t.getDefaultShapeProps("arrow"),i=Br(t,{startPagePoint:new Cc(e.start.x,e.start.y),endPagePoint:new Cc(e.end.x,e.end.y),startBinding:e.startBinding?{targetShapeId:e.startBinding.targetShapeId,normalizedAnchor:e.startBinding.normalizedAnchor}:null,endBinding:e.endBinding?{targetShapeId:e.endBinding.targetShapeId,normalizedAnchor:e.endBinding.normalizedAnchor}:null,props:{...n,bend:e.bend??n.bend,stroke:e.stroke??n.stroke,strokeWidth:e.strokeWidth??n.strokeWidth,headStart:e.headStart??n.headStart,headEnd:e.headEnd??n.headEnd}});return{id:i.id,type:i.type}}}),context:e,token:am}),geo:Ol({api:Hl(e.editor),context:e,token:rm}),text:Ol({api:Wl(e.editor),context:e,token:om}),frame:Ol({api:Nl(e.editor),context:e,token:sm})};var t}function ql(e,t){if("frame"!==t.type)return t;const n=(e.getShape(t.id)?.props)?.name;return{...t,displayName:n&&n.length>0?n:"Frame"}}function Vl(e){const t=(e=>{const{apiRegistry:t,editor:n,productId:i}=e;return{plugins: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:Yl(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){const t=e??n.getCurrentPageId();return n.getLayerTree(t).map(e=>zl(e,n))},getLayerNode(e){const t=n.getLayerNode(e);return t?zl(t,n):null},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){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(Dl),createPage:e=>Dl(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:Kl(e,am),geo:Kl(e,rm),text:Kl(e,om),frame:Kl(e,sm)};return{...t,...n,getLayerTree:n=>t.getLayerTree(n).map(t=>ql(e.editor,t)),getLayerNode(n){const i=t.getLayerNode(n);return i?ql(e.editor,i):null}}}function Gl(e){const{apiRegistry:t,editor:n,pluginHostRuntime:i,productId:r,services:o}=e;return ic(()=>Vl({apiRegistry:t,assertToolId:e.assertToolId,editor:n,pluginHostRuntime:i,productId:r,services:o}),[t,n,e.assertToolId,i,r,o])}import{createContext as jl,memo as Zl,useCallback as Ql,useContext as Jl,useEffect as ec,useEffectEvent as tc,useLayoutEffect as nc,useMemo as ic,useReducer as rc,useRef as oc,useState as sc}from"react";import{Fragment as ac,jsx as dc,jsxs as lc}from"react/jsx-runtime";import{EditorContent as cc,useEditor as hc}from"@tiptap/react";import{Bold as uc}from"@tiptap/extension-bold";import{Italic as pc}from"@tiptap/extension-italic";import{Strike as gc}from"@tiptap/extension-strike";import mc from"@tiptap/starter-kit";import{BubbleMenu as fc}from"@tiptap/react/menus";var Sc=0,yc=null,xc=null,Ic=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)=>{yc&&!yc.initialAtomValues.has(e)&&yc.initialAtomValues.set(e,t)})(this,i),t(),this.lastChangedEpoch=e(),this.current=n,(e=>{yc||o([e])})(this),n)}update(e){return this.set(e(this.current))}},Pc=Symbol("UNINITIALIZED"),wc=class{name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch;children=new Set;state=Pc;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!==Pc&&!this.haveParentsChanged())return this.lastCheckedEpoch=e(),this.state;let r,o;n(this.selfAsChild);try{r=this.derive(this.state===Pc?Pc: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!==Pc&&(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}},bc=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}},vc=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}},Cc=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)}},kc=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 Cc(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)}},Bc=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 Cc(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)}},Tc="page:default",Mc="session:main",Ec={x:0,y:0,z:1},Ac=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}},Rc=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()}},Fc=Symbol("editorStore"),Lc=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(M(e))if(this.marks.size>0)for(const[t,n]of this.marks.entries())this.marks.set(t,L(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),!M(t.forward))return null;const n=R(t.forward);for(const i of t.parentIds){const e=this.marks.get(i);e&&this.marks.set(i,L(e,n))}return n}squashToMark(e,t=e){const n=this.marks.get(e);if(!n)return null;if(this.marks.delete(e),!M(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})}},$c=class{recordsSignal;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)}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?A(e,t):{added:[],updated:[],removed:[]};if(!i&&t&&M(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=A(this.recordsSignal.get(),n);if(!M(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()}},Dc=class{editor;buffer=new Lc;state=this.buffer.state;constructor(e){this.editor=e,k(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&&(k(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&&(k(this.editor).applyDiff(e.inverse,"history"),this.editor.syncAfterDocumentRestore(),!0)}redo(){const e=this.buffer.redo();return!!e&&(k(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;M(t)&&"user"===e.source&&this.buffer.append(t)}},zc=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){k(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){k(this.editor).remove([n.id],e);continue}if(!this.canBind(n)){k(this.editor).remove([n.id],e);continue}const o=this.getExclusiveBindingKey(n);if(o){if(t.has(o)){k(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)){k(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&&k(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}]:[]});k(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),k(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&&k(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}},Yc=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]??Ec}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:W("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=W(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=W(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 Cc(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new Cc(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)}},Xc=new Cc(24,24),Uc=class{editor;constructor(e){this.editor=e}createPayloadFromSelection(){return te(this.editor)}pastePayload(e){return this.editor.cancelInteractionForCommand(),ne(this.editor,e)}duplicateSelection(e={}){return this.editor.cancelInteractionForCommand(),((e,t={})=>{const n=te(e);return n?ne(e,{payload:n,offset:t.offset??Xc,source:t.source}):[]})(this.editor,e)}},Hc=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},Wc=[],Nc=[],Oc=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(h).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=be(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();k(this.editor).replaceAll([...i.records,r],n),this.syncAfterDocumentSnapshotLoad(n)}loadSessionSnapshot(e,t){const n=t?.source??"system",i=ve(e).records[0]??l(),r=k(this.editor).getAll().filter(m);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),k(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=k(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(h),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,j(l,a,r)??i);const p=t.find(e=>e.id===Mc),g=u(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]??Ec;n[i]={x:Number.isFinite(t.x)?t.x:Ec.x,y:Number.isFinite(t.y)?t.y:Ec.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:Ec.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 be(e,this.editor.shapeUtils,this.editor.bindingUtils)}catch(t){if(!(t instanceof Hc))throw t;return{schemaVersion:1,records:[d()]}}}parseInitialSessionSnapshot(e){if(!e)return{schemaVersion:1,records:[l()]};try{return ve(e)}catch(t){if(!(t instanceof Hc))throw t;return{schemaVersion:1,records:[l()]}}}},Kc=class{state=s("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:Ce(),screenVelocity:Ce(),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:ke(n,e.pagePoint,o),screenVelocity:ke(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:Ce(),screenVelocity:Ce(),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:Ce(),screenVelocity:Ce(),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&&Be(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:ke(n,e.pagePoint,s),screenVelocity:ke(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:Ce(),screenVelocity:Ce(),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=>Be(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=>Be(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},_c=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;arrowTerminalBindingResolver=(e,t)=>(({rawPagePoint:e})=>({pagePoint:e.clone(),binding:null,preview:null}))(t);constructor(e){this.editor=e}setBrushBox(e){_(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));N(this._erasingShapeIdsSignal.get(),t)||this._erasingShapeIdsSignal.set(t)}clearErasingShapeIds(){this.setErasingShapeIds([])}getEraserTrail(){return this._eraserTrailSignal.get().map(e=>e.clone())}setEraserTrail(e){K(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&&K(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&&O(t.rawPagePoint,n.rawPagePoint)&&O(t.resolvedPagePoint,n.resolvedPagePoint):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)}setSnapIndicators(e){e?this.editor.snaps.setIndicators(e):this.editor.snaps.clearIndicators()}setArrowTerminalBindingResolver(e){this.arrowTerminalBindingResolver=e}resolveArrowTerminalBinding(e){return this.arrowTerminalBindingResolver(this.editor,e)}clearSelectionTransients(){this.setBrushBox(null),this.clearErasingShapeIds(),this.clearEraserTrail(),this.setBindingPreview(null),this.setDropTargetShapeId(null),this.setSnapIndicators(null)}},qc=.001,Vc=class{editor;stateSignal;currentPageShapeIdsSignal;currentPageShapesSignal;selectionGeometrySignal;selectionPageOutlineVerticesSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionHasRotationSignal;selectionRotationSignal;selectionRotationCenterSignal;selectionHasCompatibleRotationSignal;selectionToolbarAnchorPagePointSignal;stateAtom;shapeQuerySignals=new Map;constructor(e){this.editor=e;const t=k(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(h).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(He),r=new Map,o=new Map,s=new Map,a=new Map(n.map(e=>[e.id,e])),d=new Map,l=new Map,u=new Map,g=new Map;for(const c of n)ze(o,c.parentId,c.id);const m=(e,t)=>{for(const n of o.get(t)??[]){const t=a.get(n);t&&(ze(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),Ye(l,c.fromId,c.id),Ye(u,c.toId,c.id),Ye(g,c.fromId,c.id),Ye(g,c.toId,c.id);return{pageShapeIdsByPage:r,childShapeIdsByParent:o,pageIdByShape:s,bindingById:d,bindingIdsByFromShape:l,bindingIdsByToShape:u,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:Ue}),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",()=>Ze(e,t),{isEqual:Ge}),i=a("editor.query.selectionPageOutlineVertices",()=>n.get().outlineVertices,{isEqual:Ve}),r=a("editor.query.selectionPageBounds",()=>n.get().pageBounds,{isEqual:_}),o=a("editor.query.selectionFrameBounds",()=>n.get().frameBounds,{isEqual:_}),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:O}),hasCompatibleRotation:a("editor.query.selectionHasCompatibleRotation",()=>n.get().hasCompatibleRotation),toolbarAnchorPagePoint:a("editor.query.selectionToolbarAnchorPagePoint",()=>n.get().toolbarAnchorPagePoint,{isEqual:O})}})(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.selectionToolbarAnchorPagePointSignal=n.toolbarAnchorPagePoint}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 st(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 st(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(!lt(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}getContainingParentIdForShapeRecord(e){const t=this.getPageIdForShapeParent(e.parentId);if(!t)return null;const n=De(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(!lt(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),h=d.getLocalToPageTransform(t).invert();if(!(n.outlineVertices.length>0&&n.outlineVertices.every(e=>c.containsPoint(h.applyToPoint(e)))))continue;const u=l.w*l.h;(!i||u<r||u===r&&a>o)&&(i=t,r=u,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||!at(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=dt(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&&at(s)&&n.push(o),r=o.parentId}return n.reverse()}getShapeChildClipPageBounds(e){const t=this.editor.getShapeUtil(e),n=t.getChildClipLocalBounds(e);return n&&at(n)?(i=n,r=t.getLocalToPageTransform(e),kc.FromPoints([new Cc(i.minX,i.minY),new Cc(i.maxX,i.minY),new Cc(i.maxX,i.maxY),new Cc(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(h).map(e=>e.id))(e))this.shapeQuerySignals.delete(n);const t=k(this.editor);this.stateAtom.update(n=>((e,t,n)=>{const i=t.diff.added.filter(h),r=t.diff.updated.filter(_e),o=t.diff.removed.filter(h),s=t.diff.added.filter(p),a=t.diff.updated.filter(qe),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),u=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 h(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(!h(e))return null;t=e.parentId}return null};for(const n of o){Ke(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;Ke(m.childShapeIdsByParent,n.parentId,n.id),Oe(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)Oe(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(u){for(const e of d)f=Xe(m.bindingIdsByFromShape,e.fromId,e.id)||f,f=Xe(m.bindingIdsByToShape,e.toId,e.id)||f,f=Xe(m.relatedBindingIdsByShape,e.fromId,e.id)||f,f=Xe(m.relatedBindingIdsByShape,e.toId,e.id)||f;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(f=Xe(m.bindingIdsByFromShape,e.fromId,e.id)||f,f=Xe(m.bindingIdsByToShape,e.toId,e.id)||f,f=Xe(m.relatedBindingIdsByShape,e.fromId,e.id)||f,f=Xe(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(u){for(const e of s)f=Ne(m.bindingIdsByFromShape,e.fromId,e,"from",e=>m.bindingById.get(e))||f,f=Ne(m.bindingIdsByToShape,e.toId,e,"to",e=>m.bindingById.get(e))||f,f=Ne(m.relatedBindingIdsByShape,e.fromId,e,"related",e=>m.bindingById.get(e))||f,f=Ne(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=Ne(m.bindingIdsByFromShape,t.fromId,t,"from",e=>m.bindingById.get(e))||f,f=Ne(m.bindingIdsByToShape,t.toId,t,"to",e=>m.bindingById.get(e))||f,f=Ne(m.relatedBindingIdsByShape,t.fromId,t,"related",e=>m.bindingById.get(e))||f,f=Ne(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:Qe}),i=a(`editor.query.shapeGeometry.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return De(t,this.editor.getShapeUtil(t))},{isEqual:nt});t={bounds:n,geometry:i,positionedToPageTransform:a(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return Ee(t,this.editor.getShapeUtil(t))},{isEqual:tt}),pageBounds:a(`editor.query.shapePageBounds.${e}`,()=>i.get()?.bounds,{isEqual:Qe}),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:Ue})},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 Bc(t.a,t.b,t.c,t.d,t.e,t.f):void 0;var t}getShapePageBounds(e){return it(this.getShapePageBoundsSignal(e).get())??void 0}getShapeBounds(e){return it(this.getShapeQuerySignals(e).bounds.get())??void 0}getShapePageCenter(e){return rt(this.getShapeGeometrySnapshot(e)?.center)??void 0}getShapePageCorners(e){return ot(this.getShapeGeometrySnapshot(e)?.corners)}getShapePageOutlineVertices(e){return ot(this.getShapeGeometrySnapshot(e)?.outlineVertices)}getSelectionPageOutlineVertices(){return ot(this.selectionPageOutlineVerticesSignal.get())??[]}getSelectionPageBounds(){return it(this.selectionPageBoundsSignal.get())??null}getSelectionFrameBounds(){return it(this.selectionFrameBoundsSignal.get())??null}getSelectionRotation(){return this.selectionRotationSignal.get()}getSelectionHasRotation(){return this.selectionHasRotationSignal.get()}getSelectionRotationCenter(){return rt(this.selectionRotationCenterSignal.get())??null}getSelectionHasCompatibleRotation(){return this.selectionHasCompatibleRotationSignal.get()}getSelectionToolbarAnchorPagePoint(){return rt(this.selectionToolbarAnchorPagePointSignal.get())??null}getBinding(e){return this.stateSignal.get().bindingById.get(e)}getBindings(){return Array.from(this.stateSignal.get().bindingById.values()).sort(He)}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)}},Gc=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.bounds.w,n.bounds.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.bounds.minX/this.cellSize),n=Math.floor(e.bounds.minY/this.cellSize),i=Math.floor(e.bounds.maxX/this.cellSize),r=Math.floor(e.bounds.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.bounds.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.bounds.intersects(e)&&s.push(n))}return s.length>1&&s.sort((e,t)=>(this.order.get(e)??0)-(this.order.get(t)??0)),s}},jc=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).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 kc(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?.bounds.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=Le(s,e,a);a.hitTest(s,d)&&i.push(s)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,r=((e,t,n)=>kc.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||!ht(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),h=Le(l,e,c),u=Le(l,t,c);c.hitTestLineSegment(l,{pageStart:e,pageEnd:t,positionedStart:h,positionedEnd:u,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.queries.getShapePageBoundsSignal(e).get();t&&n.push({shapeId:e,bounds:t})}return new Gc(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.getCurrentPageId()){return this.getPageIndexSignal(e).get()}},Zc=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?Et(r):(a??(l=i.getLocalBounds(e),[new Cc(l.minX,l.minY),new Cc(l.maxX,l.minY),new Cc(l.maxX,l.maxY),new Cc(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 u of a.getSelfSnapPoints?.(l)??[]){const t=d.applyToPoint(u);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 h=this.editor.getShapeClipAncestorIds(e.id).length>0?Et(s):c.map(e=>d.applyToPoint(e));h.length>0&&r.push({id:e.id,points:h})}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?Et(i):this.editor.getShapePageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():en(e,s));if(0===a.length)continue;const d=kc.FromPoints(a);o.push({id:e.id,bounds:d});const c=n.getBoundsSnapGeometry(e).points;(void 0===c?Pt(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:en(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))})}},Qc=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 Zc(e)}setIndicators(e){const t=e.map(Jt);Ht(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=Tt(e.initialSelectionBounds,e.dragDelta),n=(i=Pt(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:Ut($t("x",n,e.snapshot.points,e.threshold),Xt("x",t,o.x,e.threshold)),a="x"===e.lockedAxis?null:Ut($t("y",n,e.snapshot.points,e.threshold),Xt("y",t,o.y,e.threshold)),d=new Cc(s?.nudge??0,a?.nudge??0),l=[];return"points"===s?.type?l.push(...Ot("x",s,d,e.snapshot.coordinateSpace)):"gaps"===s?.type&&l.push(Qt(s,e.snapshot.coordinateSpace,d)),"points"===a?.type?l.push(...Ot("y",a,d,e.snapshot.coordinateSpace)):"gaps"===a?.type&&l.push(Qt(a,e.snapshot.coordinateSpace,d)),this.setIndicators(l),{nudge:d,indicators:l}}snapResize(e){const t=ft({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),n=Dt(t,e.resizedSelectionBounds),i="left"===t||"right"===t,r="top"===t||"bottom"===t?null:$t("x",n,e.snapshot.points,e.threshold),o=i?null:$t("y",n,e.snapshot.points,e.threshold),s={x:null!==r,y:null!==o},a=new Cc(r?.nudge??0,o?.nudge??0);if(e.isAspectRatioLocked&&ut(d=t)!==pt(d)&&gt(d)!==mt(d)&&(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))}var d;const l=function(e,t){const n=ft({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?(ut(n)?(i+=t.x,r-=t.x):pt(n)&&(i-=t.x,r+=t.x),gt(n)?(o+=t.y,s-=t.y):mt(n)&&(o-=t.y,s+=t.y)):(ut(n)?i+=t.x:pt(n)&&(r+=t.x),gt(n)?o+=t.y:mt(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 kc(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=St({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:o}),a=St({axis:"y",startBounds:e,bounds:t,handleId:n,scale:r,isResizingFromCenter:o});return{scaleX:ut(n)||pt(n)?s*(t.w/Math.max(1,e.w)):i??1,scaleY:gt(n)||mt(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 xt({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:c}=l,h=Dt("any",c),u=[];if(s.x){const t=$t("x",h,e.snapshot.points,1e-8);t&&u.push(...Gt("x",t,Cc.Zero(),e.snapshot.coordinateSpace,c,e.snapshot.nodes))}if(s.y){const t=$t("y",h,e.snapshot.points,1e-8);t&&u.push(...Gt("y",t,Cc.Zero(),e.snapshot.coordinateSpace,c,e.snapshot.nodes))}return this.setIndicators(u),{nudge:a,bounds:c,scaleX:l.scaleX,scaleY:l.scaleY,indicators:u}}snapHandle(e){if("none"===e.mode)return this.clearIndicators(),null;const t="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return t?(this.setIndicators(t.indicators),t):(this.clearIndicators(),null)}snapHandlePoint(e){let t=null,n=e.threshold*e.threshold;for(const r of e.snapshot.points){const i=e.pagePoint.dist2(r.point);i>n||(n=i,t=r.point)}if(!t)for(const r of e.snapshot.outlines){const i=Ft(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:[jt(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 Cc(t?t.x-e.pagePoint.x:0,n?n.y-e.pagePoint.y:0),s=e.pagePoint.add(o),a=[];return t&&a.push(Zt("x",s,t)),n&&a.push(Zt("y",s,n)),{snappedPagePoint:s,nudge:o,indicators:a}}},Jc=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)}}},eh=class{editor;constructor(e){this.editor=e}align(e,t="user"){const n=this.getAlignableEntries();if(n.length<2)return!1;const i=kc.FromPoints(n.flatMap(e=>[new Cc(e.bounds.minX,e.bounds.minY),new Cc(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 h=o(d);const u=a.map(({shape:e,bounds:t},n)=>{const s=0===n||n===a.length-1?o(t):h,d=s-o(t);return h=s+r(t)+c,i?{id:e.id,x:e.x+d}:{id:e.id,y:e.y+d}});return this.editor.commands.updateShapes(u,{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||!q(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=W(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&&q(e)&&t.push(new Cc(e.minX,e.minY),new Cc(e.maxX,e.maxY))}if(0===t.length)return null;const n=kc.FromPoints(t);return q(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&&q(r)&&t.push({shape:i,bounds:r})}return t}},th=class{editor;constructor(e){this.editor=e}setSelectedShapeIds(e,t){const n=this.editor,i=t?.pageId??n.getCurrentPageId(),r=t?.source??"user",o=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)||N(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})}},nh=class{editor;frameGeometrySignal;companionFrameGeometriesSignal;arrowPathSignal;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(En(t))return null;const n=e.getSelectionFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:un}),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:pn}),this.arrowPathSignal=a("editor.selectionOverlayArrowPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return En(t)?t[0]?.path??null:null}),this.frameStyleSignal=a("editor.selectionOverlayFrameStyle",()=>{const t=e.cameraZoomSignal.get();return{strokeWidth:2/t,cornerRadius:3/t}},{isEqual:gn}),this.frameSignal=a("editor.selectionOverlayFrame",()=>{const e=this.frameGeometrySignal.get();if(!e)return null;const t=this.frameStyleSignal.get();return{...e,...t}},{isEqual:hn}),this.handleAnchorsSignal=a("editor.selectionOverlayHandleAnchors",()=>{if("select"!==e.toolStateSignal.get().activeToolId)return null;const t=e.selectedShapesSignal.get();if(0===t.length)return null;const n=e.getSelectionFrame(),i=e.cameraZoomSignal.get(),r=1===t.length;return An(t,n,i,t=>e.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:r,editor:e}),t=>e.getShapeUtil(t).canUseSelectionFrameHandles(t,{editor:e}))},{isEqual:Tn}),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}=Rn(t,n);return{resizeHandles:i,rotateHandles:r,terminalHandles:o,middleHandles:s,customHandles:a,strokeWidth:2/n}},{isEqual:Bn}),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:Mn}),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!==Pc?t:null,o=!r||!hn(r.frame,n),s=!r||!Mn(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)=>G(e.metrics,t.metrics)}),this.debugStateSignal=a("editor.overlayDebugState.public",()=>this.debugStateSnapshotSignal.get().metrics,{isEqual:G})}},ih=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})}},rh=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 Te(e,this.editor.getShapeUtil(e))}computeShapeLocalToPageTransform(e){return Me(e,this.editor.getShapeUtil(e))}computeShapeRenderToPageTransform(e){return((e,t)=>Me(e,t))(e,this.editor.getShapeUtil(e))}computeShapeExportToPageTransform(e){return Ae(e,this.editor.getShapeUtil(e))}computeShapePageBounds(e){return((e,t)=>kc.FromPoints($e(e,t)))(e,this.editor.getShapeUtil(e))}computeShapeExportPageBounds(e){return((e,t)=>{const n=Te(e,t),i=Ae(e,t);return kc.FromPoints([new Cc(n.minX,n.minY),new Cc(n.maxX,n.minY),new Cc(n.maxX,n.maxY),new Cc(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))})(e,this.editor.getShapeUtil(e))}computeShapeGeometry(e){return De(e,this.editor.getShapeUtil(e))}computeShapePositionedToPageTransform(e){return Ee(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?en(e,t):null}getSelectionPageOutlineVertices(){return this.editor.queries.getSelectionPageOutlineVertices()}getSelectionToolbarAnchorPagePoint(){return this.editor.queries.getSelectionToolbarAnchorPagePoint()}},oh=class{editor;constructor(e){this.editor=e}get store(){return k(this.editor)}getSelectionParentOrderState(){return Fn(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&&q(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 Cc(e.minX,e.minY),new Cc(e.maxX,e.minY),new Cc(e.maxX,e.maxY),new Cc(e.minX,e.maxY)]),l=d.length>0?kc.FromPoints(d):null;return l&&q(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}getLayerTree(e=this.editor.getCurrentPageId()){const t=this.editor,n=[],i=(r,o)=>{t.getChildShapes(r).forEach((r,s)=>{const a=t.getChildShapeIds(r.id);n.push({id:r.id,parentId:r.parentId,pageId:e,type:r.type,childIds:a,index:s,depth:o,isHidden:r.isHidden,isLocked:r.isLocked,isEffectivelyHidden:t.isShapeHidden(r.id),isEffectivelyLocked:t.isShapeOrAncestorLocked(r.id)}),i(r.id,o+1)})};return i(e,0),n}getLayerNode(e){const t=this.editor,n=t.getShape(e),i=n?t.getShapePageId(n.id):null;if(!n||!i)return null;const r=t.getChildShapeIds(n.parentId);return{id:n.id,parentId:n.parentId,pageId:i,type:n.type,childIds:t.getChildShapeIds(n.id),index:r.indexOf(n.id),depth:this.getLayerDepth(n.id),isHidden:n.isHidden,isLocked:n.isLocked,isEffectivelyHidden:t.isShapeHidden(n.id),isEffectivelyLocked:t.isShapeOrAncestorLocked(n.id)}}getLayerDepth(e){const t=this.editor;let n=0,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),i=t.getShape(e),n+=1}return n}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)),h=[];let u=!1;for(const e of l)e.id!==i.id?c.has(e.id)||h.push(e):(h.push(...d),u=!0);u||h.push(...d),e.push(...h.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 Ln(this.editor)}canMoveSelectionWithinParent(e){return((e,t)=>{const n=Ln(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveSelectionInParentOrder(e){return((e,t)=>{const n=Fn(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveShapesInParentOrder(e,t){return((e,t,n)=>{const i=$n(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this.editor,e,t)}moveShapesInParentOrder(e,t,n="user"){return Dn(this.editor,e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return zn(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=Ln(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=>!Yn(e,t.parentId,n))&&Xn(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 Xn(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")=>Dn(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}moveSelectionToParentOrderEdge(e,t="user"){return((e,t,n="user")=>zn(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 Yn(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}},sh=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:N}),this.retainedBaseShapeWindowSnapshotSignal=a("editor.retainedBaseShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),r=Kn(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(t!==Pc&&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(Wn(i).length!==t.length)return null;const r=On(t);return On(i)>r+12?null:i})(Wn(t.ranges.map(e=>({...e}))),r);if(e)return qn(n,e,{viewportReady:i})}return qn(n,r,{viewportReady:i})},{isEqual:(e,t)=>N(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=a("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:Q}),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:N}),this.selectedShapeIdsOutsideCulledSetSignal=a("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:Q}),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:N}),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:Un(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=Wn(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=Un(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=Nn(r?i.start-r.end:1/0,t),c=Nn(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?[]:Wn(s,2)})(n,r,this.selectedShapeIdsOutsideCulledSetSignal.get(),o);if(i&&t!==Pc&&t&&t.viewportReady&&t.ranges.length>0&&a.length>0){const e=Wn(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 qn(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(Wn(i).length!==t.length)return null;const r=On(t);return On(i)>r+n?null:i})(e,a,o);if(r)return qn(n,r,{viewportReady:i})}return qn(n,a,{viewportReady:i})},{isEqual:(e,t)=>N(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=a("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:N}),this.renderVisibleShapeIdSetSignal=a("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:Q}),this.renderItemsSignal=a("editor.renderItems",()=>{const t=e.selectedShapeIdSetSignal.get(),n=[];for(const i of this.renderVisibleShapeIdsSignal.get()){const r=e.getShape(i),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:Z}),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=Kn(n,a),l=Kn(o,a),c=Kn(r,a),h=((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===Pc?[]:t.retainedShapeIds,o);return{metrics:{culledCount:n.length,visibleCount:i.length,retainedCount:o.length,retainedBaseCount:r.length,culledRangeCount:d.length,culledRangeSpan:On(d),culledRangesSummary:Hn(d),retainedBaseRangeCount:c.length,retainedBaseRangeSpan:On(c),retainedBaseRangesSummary:Hn(c),retainedRangeCount:l.length,retainedRangeSpan:On(l),retainedRangesSummary:Hn(l),retainedChangeCount:h.changed,retainedAddedCount:h.added,retainedRemovedCount:h.removed,selectedOutsideCulledCount:s.length},retainedShapeIds:o.slice()}},{isEqual:(e,t)=>V(e.metrics,t.metrics)}),this.renderHostDebugStateSignal=a("editor.renderHostDebugState.public",()=>this.renderHostDebugStateSnapshotSignal.get().metrics,{isEqual:V})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},ah=class{editor;activeToolId=s("tools.activeToolId","select");isToolLocked=s("tools.isToolLocked",!1);registry=new Map;shortcutToolIds=new Map;activeTool=null;constructor(e){this.editor=e}register(e,t,n={}){this.registry.set(e,t),n.shortcut&&this.shortcutToolIds.set(n.shortcut.toLowerCase(),e)}hasTool(e){return this.registry.has(e)}getToolIdForShortcut(e){return this.shortcutToolIds.get(e.toLowerCase())??null}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}},dh=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}},lh=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}},ch=class{store;[Fc];inputs=new Kc;snapshots=new Oc(this);clipboard=new Uc(this);tools=new ah(this);camera=new Yc(this);selection=new th(this);selectionLayout=new eh(this);editing=new ih(this);geometry=new rh(this);hierarchy=new oh(this);shapeUtils=new Ac;shapeSvgExporters=new Rc;bindingUtils=new vc;interactions=new dh;selectionHandleInteractions=new lh(this.interactions);queries;bindings;spatialIndex;snaps;renderWindow;selectionOverlay;transients=new _c(this);history;sideEffects=new Jc;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;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 k(this)}sessionSignal=a("editor.session",()=>{const e=this._internalStore.recordsSignal.get().get(Mc);if(!u(e))throw new Error("Missing session record");return e});currentPageIdSignal=a("editor.currentPageId",()=>this.sessionSignal.get().currentPageId);currentPageShapeIdsSignal;currentPageShapesSignal;culledShapeIdsSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionToolbarAnchorPagePointSignal;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()]??Ec);selectedShapeIdsSignal=a("editor.selectedShapeIds",()=>{const e=this.sessionSignal.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:N});selectedShapeIdSetSignal=a("editor.selectedShapeIdSet",()=>new Set(this.selectedShapeIdsSignal.get()),{isEqual:Q});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);return{id:e.id,usesSelectionPathOverlay:t.usesSelectionPathOverlay,startPagePoint:t.startPagePoint,endPagePoint:t.endPagePoint,middlePagePoint:t.middlePagePoint,path:t.path}}),{isEqual:cn});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(),toolbarAnchorPagePoint:this.selectionToolbarAnchorPagePointSignal.get()}});pageTransformSignal=a("editor.pageTransform",()=>{const e=this.currentCameraSignal.get();return Bc.Scale(e.z,e.z).compose(Bc.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 kc(n.x,n.y,e/n.z,t/n.z)});renderViewportPageBoundsSignal=a("editor.renderViewportPageBounds",e=>{const t=this.viewportPageBoundsSignal.get();return t?e!==Pc&&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:_});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;selectionOverlayArrowPathSignal;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 $c(this.snapshots.buildInitialRecords(e.documentSnapshot??null,e.sessionSnapshot??null));var n;((e,t)=>{e[Fc]=t})(this,t),this.store=t,this.snapshots.ensureSessionIntegrity(),this.queries=new Vc(this),this.bindings=new zc(this),this.spatialIndex=new jc(this,this.queries),this.snaps=new Qc(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.selectionToolbarAnchorPagePointSignal=this.queries.selectionToolbarAnchorPagePointSignal,this.selectionOverlay=new nh(this),this.selectionOverlayFrameGeometrySignal=this.selectionOverlay.frameGeometrySignal,this.selectionOverlayCompanionFrameGeometriesSignal=this.selectionOverlay.companionFrameGeometriesSignal,this.selectionOverlayArrowPathSignal=this.selectionOverlay.arrowPathSignal,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 sh(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 Dc(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 k(e).atomic(()=>{const t=D([...e.getPages(),r]);o=t.find(e=>e.id===r.id)??r,k(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=D(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 k(e).atomic(()=>{s.length>0&&U(e,s,n),k(e).remove([t],i),e.removePageSessionState(t,l,i),k(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&&k(e).atomic(()=>{k(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),k(e).atomic(()=>{k(e).put(D(a),i)},i))})(n,e,t)},createShapes:(e,t)=>((e,t,n)=>{const i=[],r=n?.source??"user";return k(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),k(e).put(n,r)},r),i})(n,e,t),createShapesFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(k(e).atomic(()=>{k(e).put(t,i)},i),t)})(n,e,t),updateShapes(e,t){Y(n,e,t)},reparentShapes(e,t){((e,t,n)=>{const i=Array.from(new Set(t.ids));0!==i.length&&Y(e,i.map(e=>({id:e,parentId:t.parentId})),n)})(n,e,t)},deleteShapes(e,t){U(n,e,t)},createAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",r=e.createAssetRecord(t);return k(e).atomic(()=>{k(e).put([r],i)},i),r})(n,e,t),createAssetsFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(k(e).atomic(()=>{k(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 k(e).atomic(()=>{k(e).put([o],i)},i),o})(n,e,t),deleteAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return!!e.getAsset(t)&&(k(e).atomic(()=>{k(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(!H(e,r))throw new Error(`Invalid binding endpoints for ${r.type} binding`);return k(e).atomic(()=>{const t=e.bindings.getConflictingBindings(r).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),k(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(!H(e,s))throw new Error(`Invalid binding endpoints for ${s.type} binding`);return k(e).atomic(()=>{const t=e.bindings.getConflictingBindings(s).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),k(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&&(k(e).atomic(()=>{e.bindings.cleanupBindings([r.id],i),k(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.registerBuiltInSideEffects()}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){if(t.altKey&&!t.accelKey&&!t.shiftKey&&("ArrowDown"===t.key||"ArrowUp"===t.key)&&this.moveSelectionWithinParent("ArrowDown"===t.key?"backward":"forward","user"))return;if(t.accelKey&&"z"===t.key.toLowerCase())return void(t.shiftKey?this.redo():this.undo());if(!t.accelKey&&!t.altKey){const e=this.tools.getToolIdForShortcut(t.key);if(e)return void this.commands.setActiveTool(e,{source:"system"});if("Backspace"===t.key||"Delete"===t.key)return void this.deleteSelection("user")}}if("keyboard"!==t.type||"key_down"!==t.name||"Escape"!==t.key)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);else this.tools.isActiveToolInInitialState()&&"select"!==this.getActiveToolId()?this.commands.setActiveTool("select",{source:"system"}):this.cancelInteractionAndClearTransients("escape")}handleInteractionEvent(e){const t=this.normalizeEvent(e);return this.inputs.handleEvent(t),"handled"===this.interactions.handleEvent(this,t)}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(!ee(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()}getLayerTree(e=this.getCurrentPageId()){return this.hierarchy.getLayerTree(e)}getLayerNode(e){return this.hierarchy.getLayerNode(e)}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=kc.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:kc.FromPoints(e.map(e=>en(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:an({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 h(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(h)){const e=J(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}`,()=>this.getShape(e)),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}`,()=>this.renderVisibleShapeIdSetSignal.get().has(e)&&!this.isShapeHidden(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)}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()}getSelectionToolbarAnchorPagePoint(){return this.geometry.getSelectionToolbarAnchorPagePoint()}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)=>Rn(An(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)}setSnapIndicators(e){this.transients.setSnapIndicators(e)}setArrowTerminalBindingResolver(e){this.transients.setArrowTerminalBindingResolver(e)}resolveArrowTerminalBinding(e){return this.transients.resolveArrowTerminalBinding(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 f of o){const t=e.getShape(f);t?d.push(t):a.push({id:f,reason:"missing-shape"})}if(0===d.length)return null;const l=[];for(const S of d){const t=f(e,S,s);t&&(b(t)?l.push(t):a.push({id:S.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 kc(t,n,i-t,r-n)})(l).expand(i.padding??16),h=[],u={editor:e,bounds:c,addDef(e){const t=`land-svg-def-${h.length+1}`;return h.push({...e,attrs:{...e.attrs,id:t}}),t},resolveAssetUrl:t=>e.resolveAssetUrl(t)},p=[],g=[],m=new Map;for(const f of d){const t=n.get(f.type);if(!t){a.push({id:f.id,reason:"missing-exporter"});continue}const i=t.toSvg(f,u);if(!i){a.push({id:f.id,reason:"empty-output"});continue}if(!b(e.computeShapeExportBounds(f))){a.push({id:f.id,reason:"missing-bounds"});continue}const r=e.computeShapeExportToPageTransform(f);p.push(f.id);const o=S(e,f,s,m,u);let d={tag:"g",attrs:{transform:r.toSvgString(),opacity:1===f.opacity?void 0:f.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 y=Math.max(1,c.w),x=Math.max(1,c.h),I=[];return h.length>0&&I.push({tag:"defs",children:h}),i.background&&I.push({tag:"rect",attrs:{x:c.x,y:c.y,width:c.w,height:c.h,fill:i.background}}),I.push(...g),{svg:w({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:y,height:x,viewBox:`${C(c.x)} ${C(c.y)} ${C(y)} ${C(x)}`},children:I}),bounds:c,width:y,height:x,requestedShapeIds:r,exportedShapeIds:p,skippedShapes:a}}(this,e,this.shapeSvgExporters,t)}getExportIntegrityReport(e=this.getSelectedShapeIds()){return B({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}repairExportIntegrity(e=this.getSelectedShapeIds()){return(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),r=B({editor:e,exporters:t,shapeIds:i});r.repairableIssueCount>0&&e.bindings.repairLoadedBindings("system");const o=B({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]??{...Ec}},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]??{...Ec},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(!h(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)}},hh=class{getLocalBounds(e){const t=this.getBounds(e);return new kc(t.x-e.x,t.y-e.y,t.w,t.h)}getRenderBounds(e){return this.getLocalBounds(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=Qn(r,"w",t.selectionLocalBounds.w),s=Qn(r,"h",t.selectionLocalBounds.h),a=tn(yt({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():Cc.RotWith(e,t.selectionRotationCenter,-t.selectionRotation),i=sn({axis:t.axis,bounds:t.selectionBounds,point:n});return 0===t.selectionRotation?i:Cc.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:Cc.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:jn(this.getLocalBounds(e))}}getPositionedOutlineVertices(e){const t=this.getBounds(e);return[new Cc(t.minX,t.minY),new Cc(t.maxX,t.minY),new Cc(t.maxX,t.maxY),new Cc(t.minX,t.maxY)]}getSelectionHandleAnchors(e,t){return{terminalHandleAnchors:[],middleHandleAnchors:[]}}getSelectionOverlayInfo(e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null}}isWrappedByBrush(e,t){return 0===t.pageOutlineVertices.length?!!t.pageBounds&&t.brushBounds.containsBox(t.pageBounds):t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return!t.isWrapping||this.isWrappedByBrush(e,t)}getLocalToPageTransform(e){const t=this.getLocalBounds(e).center;return Bc.Translate(e.x+t.x,e.y+t.y).compose(Bc.Rotate(e.rotation)).compose(Bc.Scale(e.scaleX,e.scaleY)).compose(Bc.Translate(-t.x,-t.y))}canEdit(e){return!1}canReceiveChildren(e){return!1}repairLoadedShape(e){return null}onEditEnd(e){}hitTest(e,t){return this.getBounds(e).containsPoint(t)}hitTestLineSegment(e,t){return((e,t,n)=>{if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=jn(n);for(let r=0;r<i.length;r+=1){const n=i[r],o=i[(r+1)%i.length];if(n&&o&&null!==Zn(e,t,n,o))return!0}return!1})(t.positionedStart,t.positionedEnd,this.getBounds(e).expand(t.margin))}resolveBindingPoint(e,t){return t.rawPagePoint}},uh=class{},ph=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)}},gh=class extends ph{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new mh(e,this)),this.addChild(new fh(e,this))}},mh=class extends ph{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",{originScreenPoint:e.screenPoint.clone(),originCamera:this.editor.getCurrentCamera()})}},fh=class extends ph{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}},Sh=Math.PI/180*15,yh=Math.PI/2,xh=Math.PI/180*5,Ih="select.translate",Ph="select.resize",wh="select.rotate",bh=class extends ph{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},vh=class extends bh{onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&this.onDragThresholdExceeded(e)}},Ch=class extends bh{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=ti(this.editor,e,this.tickMode);t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){ni(this.editor,e=>this.apply(e))}},kh=class extends bh{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,si(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,oi(e),si(e))}onTick(e){if(!this.info)return;const t=ti(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,oi(t),si(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,oi(e),si(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 kc(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(){ni(this.editor,e=>this.updateBrush(e.pagePoint,oi(e),si(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},Bh=class extends Ch{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(yc)return void e();const t={initialAtomValues:new Map};yc=t;try{e(),o(t.initialAtomValues.keys())}catch(n){for(const[e,i]of t.initialAtomValues)e.__unsafe__setWithoutNotify(i);throw n}finally{yc=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")}},Th=class extends ph{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=oi(e),s=ii(this.editor,n,t),a=o?null:((e,t,n)=>{const i=new Set(n);for(const r of ri(e,t))if(i.has(r.ancestorId))return r.ancestorId;return null})(this.editor,n,t),d=o?null:a?s:null,l=ii(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(!oi(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:oi(e)})}},Mh=class extends vh{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:oi(e)})}onPointerUp(e){oi(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")}},Eh=class extends vh{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:en(e[0],r),endLocalPagePoint:en(e[1],r)}):o.push({shape:a,localBounds:kc.FromPoints(n(a).map(e=>en(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 Cc(e.minX,e.minY),new Cc(e.maxX,e.minY),new Cc(e.maxX,e.maxY),new Cc(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:pi(this.editor,t,this.info.handleId),lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},Ah=class extends vh{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:Cc.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")}},Rh=class extends vh{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")}},Fh=class extends vh{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()??Cc.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 oi(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")}},Lh=class extends Ch{tickMode="apply_after_scroll_or_without_screen_point";constructor(e,t){super(e,"resizing",t)}getHistoryMark(){return Ph}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=ci(this.info.rotationCenter,this.info.rotation),o=en(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=ut(t)||pt(t)?r*(ut(t)?-2:2)/Math.max(1,e.w):1,l=gt(t)||mt(t)?o*(gt(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new kc(e.minX,i.y-a,e.w,2*a),scaleX:d,scaleY:l};case"left":case"right":return{bounds:new kc(i.x-s,e.minY,2*s,e.h),scaleX:d,scaleY:l};default:return{bounds:new kc(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=ut(t)?i:r,d=ut(t)?r:i,l=gt(t)?o:s,c=gt(t)?s:o;ut(t)||pt(t)?a=n.x:(a=r,d=i),gt(t)||mt(t)?l=n.y:(l=s,c=o);const h=a-d,u=l-c,p=ut(t)?d-a:h,g=gt(t)?c-l:u,m=ut(t)||pt(t)?p/Math.max(1,e.w):1,f=gt(t)||mt(t)?g/Math.max(1,e.h):1;return{bounds:new kc(Math.min(a,d),Math.min(l,c),Math.max(1,Math.abs(h)),Math.max(1,Math.abs(u))),scaleX:m,scaleY:f}})({startBounds:e,handleId:t,pagePoint:n});return i?xt({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&&hi(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(Ph),this.transition("idle")}cancel(){this.editor.setSnapIndicators(null),this.editor.history.bailToMark(Ph),this.transition("idle")}},$h=class extends Ch{tickMode="apply_after_scroll";constructor(e,t){super(e,"rotating",t)}getHistoryMark(){return wh}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=ai(Cc.Angle(this.info.center,e)-this.info.startAngle);if(t)i=di(i,Sh);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=di(e,yh),n=ai(t-e);Math.abs(n)<=xh&&(i=ai(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&&gi(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&&mi(this.editor,e,this.info.center,i,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.history.squashToMark(wh),this.transition("idle")}cancel(){this.editor.history.bailToMark(wh),this.transition("idle")}},Dh=class extends Ch{tickMode="always_apply";constructor(e,t){super(e,"translating",t)}getHistoryMark(){return Ih}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,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 Cc(o,s):new Cc(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),((e,t)=>{const n=Si(e,t);if(n===fi(e,t))return void e.setDropTargetShapeId(null);const i=n?e.getShape(n):null;e.setDropTargetShapeId(i?.id??null)})(this.editor,this.info.selectedShapeIds)}}complete(){this.info&&((e,t)=>{const n=Si(e,t);n&&t.some(t=>e.getShape(t)?.parentId!==n)&&e.commands.reparentShapes({ids:[...t],parentId:n})})(this.editor,this.info.selectedShapeIds),this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.squashToMark(Ih),this.transition("idle")}cancel(){this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.editor.history.bailToMark(Ih),this.transition("idle")}},zh=class extends ph{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new Th(e,this)),this.addChild(new Mh(e,this)),this.addChild(new kh(e,this)),this.addChild(new Fh(e,this)),this.addChild(new Dh(e,this)),this.addChild(new Eh(e,this)),this.addChild(new Lh(e,this)),this.addChild(new Ah(e,this)),this.addChild(new $h(e,this)),this.addChild(new Rh(e,this)),this.addChild(new Bh(e,this))}},Yh="editor.tool.set-active-tool",Xh="editor.tool.toggle-locked",Uh=jl(null),Hh=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,vi(this.options,t??{}))}createFeature(){return this.config.createFeature?.(this.options)??null}getExtensions(){return this.config.addExtensions?.(this.options)??[]}},Wh=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));((e,t)=>{for(const n of e)n.setup(t)})(t,e=>this.registerShapeRenderer(e));for(const n of t)this.registeredPluginIds.add(n.id)}},Nh=jl(Bi()),Oh=Zl(()=>Ii(xi().retainedShapeIdsSignal).map(e=>dc(_h,{shapeId:e},e))),Kh=Zl(()=>{const e=xi(),t=Ii(e.currentPageShapeIdsSignal),n=Ii(e.retainedShapeIdsSignal),i=Ii(e.renderVisibleShapeIdsSignal),r=Ii(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};
30
- return dc("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)})}),_h=Zl(({shapeId:e})=>{const t=xi(),n=e,i=Ii(t.getShapeSignal(n)),r=Ii(t.getShapeRenderVisibleSignal(n)),o=Ii(t.toolStateSignal).activeToolId,s=Ii(t.getShapeSelectedSignal(n)),a="select"===o&&s,d=Ii(t.getShapeEditingSessionForShapeSignal(n)),l=Ii(t.getShapeRenderOrderSignal(n)),c=Ii(t.getShapeDropTargetSignal(n)),h=Ii(t.getShapeErasingSignal(n)),u=Ii(t.getShapeSelectedDescendantTransformAncestorSignal(n)),p=Ii(t.getShapeClipAncestorIdsSignal(n)),g=Jl(Nh);if(!i)return null;const m=g.getShapeRenderer(i.type);if(!m)return null;const f=m.component,S=((e,t)=>{const n=e.computeShapeRenderBounds(t),i=e.computeShapeRenderToPageTransform(t).compose(Bc.Translate(n.x,n.y));return{left:0,top:0,width:n.w,height:n.h,transform:i.toCssString(),transformOrigin:"0 0",elementToPage:i}})(t,i),y=h?.32*i.opacity:i.opacity,x=a?t.getSelectionSiblingOrderState():null,I="frame"===(x?.parentId.startsWith("shape:")?t.getShape(x.parentId):null)?.type;
31
- return lc("div",{"data-ui":"shape-instance","data-shape-id":i.id,"data-shape-type":i.type,"data-selected":a?"true":"false","data-drop-target":c?"true":"false","data-visible":r?"true":"false","data-render-order":l>=0?String(l):void 0,"data-clip-ancestor-count":p.length,style:{position:"absolute",display:r?void 0:"none",left:S.left,top:S.top,width:S.width,height:S.height,opacity:1===y?void 0:y,transform:S.transform,transformOrigin:S.transformOrigin,pointerEvents:"none",outline:c?"2px solid #2563eb":void 0,outlineOffset:c?4:void 0,boxShadow:c?"0 0 0 6px rgba(37, 99, 235, 0.16)":void 0,zIndex:l>=0?l+1:void 0},children:[r?dc(Ri,{clipAncestorIds:p,shapeElementToPage:S.elementToPage,children:dc(f,{shape:i,editor:t,isSelected:a,shapeEditingSession:d})}):null,r&&c?dc(Ai,{shapeType:i.type}):null,r&&u?dc(Mi,{}):null,r&&I&&x?dc(Ei,{state:x}):null]})}),qh=Zl(()=>lc("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
32
- dc("style",{children:'\n [data-selection-terminal],\n [data-selection-arrow-middle],\n [data-selection-custom-handle]:not([data-selection-custom-handle-type="image.crop"]) {\n transition: fill 120ms ease, stroke 120ms ease;\n }\n [data-selection-terminal]:hover,\n [data-selection-arrow-middle]:hover,\n [data-selection-custom-handle]:not([data-selection-custom-handle-type="image.crop"]):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-arrow-middle]:active,\n [data-selection-custom-handle]:active {\n cursor: grabbing;\n }\n '}),
33
- dc(jh,{}),
34
- dc(Vh,{}),
35
- dc(iu,{}),
36
- dc(ou,{})]})),Vh=Zl(()=>Ii(xi().bindingPreviewActiveSignal)?dc(eu,{}):null),Gh="rgba(37, 99, 235, 0.9)",jh=Zl(()=>{const e=Ii(xi().snapIndicatorsSignal);return 0===e.length?null:dc(Zh,{indicators:e})}),Zh=Zl(({indicators:e})=>{const t=Ii(xi().cameraZoomSignal);
37
- return dc(ac,{children:e.map(e=>dc("points"===e.type?Qh:Jh,{indicator:e,zoom:t},e.id))})}),Qh=Zl(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[r,o]=e.line,s=180*e.rotation/Math.PI;
38
- return lc("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${s} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[dc("path",{"data-ui":"snap-indicator-line",d:`M ${r.x} ${r.y} L ${o.x} ${o.y}`,fill:"none",stroke:Gh,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,r)=>dc("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:Gh,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${r}`))]})}),Jh=Zl(({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=Yi(i,[n?c.startEdge[0].y:c.startEdge[0].x,n?c.startEdge[1].y:c.startEdge[1].x]);e&&(i=e);const t=Yi(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:h}of e.gaps)if(n){a.push(`M ${c[0].x} ${r-s} L ${c[1].x} ${r+s}`,`M ${h[0].x} ${r-s} L ${h[1].x} ${r+s}`,`M ${c[0].x} ${r} L ${h[0].x} ${r}`);const e=(c[0].x+h[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} ${h[0].y} L ${r+s} ${h[1].y}`,`M ${r} ${c[0].y} L ${r} ${h[0].y}`);const e=(c[0].y+h[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})`;
39
- return dc("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:l,fill:"none",stroke:Gh,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),eu=Zl(()=>{const e=Ii(xi().bindingPreviewSignal);return e?lc(ac,{children:[dc(tu,{targetShapeId:e.targetShapeId}),dc(nu,{bindingPreview:e})]}):null}),tu=Zl(({targetShapeId:e})=>{const t=xi(),n=Ii(t.cameraZoomSignal),i=Ii(t.getShapeSignal(e));return i?dc(Di,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),nu=Zl(({bindingPreview:e})=>lc(ac,{children:[dc("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}),dc("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})]})),iu=Zl(()=>Ii(xi().brushBoxActiveSignal)?dc(ru,{}):null),ru=Zl(()=>{const e=Ii(xi().brushBoxSignal);return e?dc("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}),ou=Zl(()=>lc(ac,{children:[
40
- dc(su,{}),
41
- dc(au,{}),
42
- dc(lu,{})]})),su=Zl(()=>{const e=xi(),t=Ii(e.selectionOverlayArrowPathSignal),n=Ii(e.selectionOverlayFrameStyleSignal);return t?lc(ac,{children:[dc("path",{"data-selection-overlay":"arrow-path-underlay",d:t,fill:"none",stroke:"rgba(255,255,255,0.92)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2*n.strokeWidth}),dc("path",{"data-selection-overlay":"arrow-path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:n.strokeWidth})]}):null}),au=Zl(()=>{const e=xi(),t=Ii(e.selectionOverlayFrameGeometrySignal),n=Ii(e.selectionOverlayCompanionFrameGeometriesSignal);return t||0!==n.length?lc(ac,{children:[t?dc(du,{frameGeometry:t}):null,n.map((e,t)=>dc(du,{frameGeometry:e},`companion-${t}`))]}):null}),du=Zl(({frameGeometry:e})=>{const t=Ii(xi().selectionOverlayFrameStyleSignal),{bounds:n,rotation:i,rotationCenter:r}=e,{cornerRadius:o,strokeWidth:s}=t,a=180*i/Math.PI;
43
- return dc(ac,{children:lc("g",{transform:0===i?void 0:`rotate(${a} ${r.x} ${r.y})`,children:[dc("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}),dc("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})]})})}),lu=Zl(()=>{const e=Ii(xi().selectionOverlayHandleAnchorsSignal);return e?dc(cu,{anchors:e}):null}),cu=Zl(({})=>{const e=xi(),t=Ii(e.selectionOverlayHandlesSignal),n=Ii(e.selectionOverlayFrameGeometrySignal),i=Ii(e.cameraZoomSignal);if(!t)return null;const{resizeHandles:r,rotateHandles:o,strokeWidth:s,terminalHandles:a,middleHandles:d,customHandles:l}=t;
44
- return lc(ac,{children:[r.map(e=>dc("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:s,style:{cursor:Xi(e.id,n?.rotation??0),pointerEvents:"auto"}},e.id)),o.map(e=>lc("g",{"data-selection-rotate-handle":e.id,transform:`translate(${e.bounds.center.x-6/i} ${e.bounds.center.y-6/i}) scale(${.6/i})`,fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[dc("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),dc("path",{d:"M21 3v5h-5"})]},e.id)),a.map(e=>dc("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:s,style:{cursor:"grab",pointerEvents:"auto"}},e.terminal)),d.map(e=>dc("rect",{"data-selection-arrow-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:s,transform:`rotate(45 ${e.bounds.center.x} ${e.bounds.center.y})`,style:{cursor:"grab",pointerEvents:"auto"}},"middle")),l.map(e=>"image.crop"===e.type?dc(Ui,{handle:e,strokeWidth:s},`${e.type}:${e.id}`):dc("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:3,ry:3,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:s,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}},`${e.type}:${e.id}`))]})}),hu=["ew-resize","nwse-resize","ns-resize","nesw-resize"],uu=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}}},pu=[{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}],gu=1e-6,mu=2*Math.PI,fu=class extends uh{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,Pr(i.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,Pr(i.y,n.normalizedAnchor.y)))}}}canBind(e,t,n){return pr(n.fromShape)&&!pr(n.toShape)}getExclusiveBindingKey(e){return`${e.fromId}:${e.props.terminal}`}onBindingCreate(e,t){return wr(this.syncArrowTerminal(e,t))}onBindingUpdate(e,t,n){return wr(this.syncArrowTerminal(e,n))}onBindingLoad(e,t){return wr(this.syncArrowTerminal(e,t))}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return wr(this.syncArrowTerminal(e,t))}onBeforeDeleteShape(e,t,n){if("from"===n.role)return{deleteBindingIds:[t.id]};const i=e.getShape(t.fromId);if(!pr(i))return{deleteBindingIds:[t.id]};const r=this.resolveTerminalPagePoint(e,t);return{shapes:[r?ir(i,t.props.terminal,r):i],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.fromId);if(!pr(n))return{deleteBindingIds:[t.id]};const i=this.resolveTerminalPagePoint(e,t);return{shapes:[i?ir(n,t.props.terminal,i):n],deleteBindingIds:[t.id]}}syncArrowTerminal(e,t){if(!gr(t))return null;const n=e.getShape(t.fromId);if(!pr(n))return null;const i=this.resolveTerminalPagePoint(e,t);return i?er(n,t.props.terminal).dist(i)<1e-6?null:ir(n,t.props.terminal,i):null}resolveTerminalPagePoint(e,t){if(!gr(t))return null;const n=e.getShape(t.fromId),i=e.getShape(t.toId);if(!pr(n)||!i||pr(i))return null;const r=er(n,tr(t.props.terminal));return fr(e,i,t.props.normalizedAnchor,r)}},Su=class extends hh{type="arrow";getDefaultProps(){return{w:160,h:48,start:{x:8,y:24},end:{x:152,y:24},bend:0,stroke:"#334155",strokeWidth:2,headStart:"none",headEnd:"arrow"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,vr(t.w,n.w)),h:Math.max(1,vr(t.h,n.h)),start:br(t.start,n.start),end:br(t.end,n.end),bend:vr(t.bend,n.bend),stroke:"string"==typeof t.stroke?t.stroke:n.stroke,strokeWidth:Math.max(1,vr(t.strokeWidth,n.strokeWidth)),headStart:"arrow"===t.headStart?"arrow":"none",headEnd:"none"===t.headEnd?"none":"arrow"}}getBounds(e){const t=rr(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}getLocalBounds(e){return new kc(0,0,e.props.w,e.props.h)}getExportBounds(e){const t=or(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:nr(e,er(e,"start"),er(e,"end"))}updateSelectionPagePoints(e,t){const n=nr(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(er(e,"start"))&&t.brushBounds.containsPoint(er(e,"end"))}getSelectionPagePoints(e){return[er(e,"start"),er(e,"end")]}contributesToSelectionFrame(e){return!1}canStartTranslateFromSelectionBounds(e){return!1}getSelectionHandleAnchors(e,t){if(!t.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=rr(e);return{terminalHandleAnchors:[{kind:"arrow_terminal",terminal:"start",point:n.start.point},{kind:"arrow_terminal",terminal:"end",point:n.end.point}],middleHandleAnchors:n.middle?[{kind:"arrow_middle",point:n.middle}]:[]}}getSelectionOverlayInfo(e){const t=rr(e);return{usesSelectionPathOverlay:!0,startPagePoint:t.start.point,endPagePoint:t.end.point,middlePagePoint:t.middle,path:t.path}}hitTest(e,t){return((e,t)=>{let n=1/0;for(let i=0;i<e.points.length-1;i++)n=Math.min(n,hr(t,e.points[i],e.points[i+1]));return Number.isFinite(n)?n:t.dist(e.start.point)})(rr(e),t)<=Math.max(8,e.props.strokeWidth+4)}hitTestLineSegment(e,t){const n=rr(e),i=Math.max(8,e.props.strokeWidth+4,t.margin);if(1===n.points.length)return Cr(n.points[0],t.positionedStart,t.positionedEnd)<=i;for(let r=0;r<n.points.length-1;r+=1){const e=n.points[r],o=n.points[r+1];if(e&&o&&kr(t.positionedStart,t.positionedEnd,e,o)<=i)return!0}return!1}},yu="arrow.create",xu=class extends ph{constructor(e){super(e,"arrow"),this.initial="idle",this.addChild(new Iu(e,this)),this.addChild(new Pu(e,this))}},Iu=class extends ph{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})=>Sr(e,{terminal:t,rawPagePoint:n,oppositePagePoint:n.add(new Cc(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})}},Pu=class extends ph{info=null;constructor(e,t){super(e,"creating",t)}onEnter(e){if(this.info=e,!this.info)return;this.editor.history.mark(yu);const t=Br(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=ei(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(yu),void this.transition("idle");z(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(yu),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})}else this.transition("idle")}onCancel(){this.editor.history.bailToMark(yu),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=pr(n)?yr(this.editor,{arrow:n,terminal:"end",rawPagePoint:e,ignoreTargets:this.editor.inputs.state.get().accelKey}):Sr(this.editor,{terminal:"end",rawPagePoint:e,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey});Tr(this.editor,t,"end",i,"user")}},wu=class{type="arrow";toSvg(e,t){const n="arrow"===e.props.headStart?`url(#${t.addDef(Lr("start",e.props.stroke))})`:void 0,i="arrow"===e.props.headEnd?`url(#${t.addDef(Lr("end",e.props.stroke))})`:void 0;return{tag:"path",attrs:{d:or(e).path,fill:"none",stroke:e.props.stroke,"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":n,"marker-end":i}}}},bu=[{value:"#1d4ed8",label:"Blue",color:"#1d4ed8"},{value:"#15803d",label:"Green",color:"#15803d"},{value:"#dc2626",label:"Red",color:"#dc2626"},{value:"#334155",label:"Slate",color:"#334155"}],vu=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Cu=[{value:"none",label:"None",icon:"minus"},{value:"arrow",label:"Arrow",icon:"arrow-right"}],ku=wi({name:"arrow",createFeature:()=>({id:"land.arrow.bundle",corePlugins:[{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 Su],shapeSvgExporters:[new wu],bindingUtils:[new fu],interactionHandlers:[{id:"land.arrow.interactions",selectionHandle:Mr()}],toolbarActions:[Ar("stroke"),Ar("strokeWidth"),Ar("headStart"),Ar("headEnd"),Rr("stroke"),Rr("strokeWidth"),Rr("headStart"),Rr("headEnd")],toolbarContributions:[{id:"arrow.tool-toolbar",surface:"tool",placement:"chrome",order:40,actionIds:[Yh],getGroups:()=>[{id:"arrow.tools",items:[{kind:"button",id:"arrow.tool.arrow",actionId:Yh,value:"arrow",label:"Arrow",shortcut:"A",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:()=>Er({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:()=>Er({strokeActionId:"arrow.set-stroke",strokeWidthActionId:"arrow.set-strokeWidth",headStartActionId:"arrow.set-headStart",headEndActionId:"arrow.set-headEnd",dataUiPrefix:"arrow"})}],setup(e){e.setArrowTerminalBindingResolver(Sr),e.tools.register("arrow",e=>new xu(e),{shortcut:"a"})}}],canvasPlugins:[{id:"land.arrow.react",setup(e){e({type:"arrow",component:$r})}}],shapeTypes:["arrow"]})}),Bu=.08,Tu=new WeakMap,Mu=new WeakMap,Eu=new WeakMap,Au=new WeakMap,Ru="draw.create",Fu=class extends ph{constructor(e){super(e,"draw"),this.initial="idle",this.addChild(new Lu(e,this)),this.addChild(new $u(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("draw")}},Lu=class extends ph{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:[Fo(e.pagePoint,e.pagePoint,e.pressure,"pen"===e.pointerType)]}]})}},$u=class extends ph{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(Ru)}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(Ru),void this.transition("idle");z(this.editor,t,{source:"user"}),this.editor.history.squashToMark(Ru),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.editor.history.bailToMark(Ru),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.info=null}appendPoint(e,t){if(!this.info)return;const n=Fo(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:zo(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,...zo(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=$o(this.info),n=t[t.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return void this.replaceCurrentSegmentPoints([{...e,segment:"straight"}]);this.info.straightSegmentAnchorPoint=Lo(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=$o(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,Lo(e)]),0));var i,r}appendGuardedCurrentPoint(e){if(!this.info)return;const t=$o(this.info).map(Lo);(function(e,t,n){const i=Hr(t),r=e[e.length-1];if(!r)return void e.push(i);if(Xr(r,i))return;const o=((e,t)=>{if(e<=t.softMaxPointCount)return t.minPointDistance;const n=zr((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=Do(this.info.segments);this.info.segments=[...t.slice(0,-1),{points:e.map(Lo)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const e=Yr(this.info.isPen);let t=Do(this.info.segments),n=t[t.length-1];for(;n.points.length>e;){const i=n.points.slice(0,e).map(Lo),r=i[i.length-1],o=n.points.slice(e).map(Lo);if(!r||0===o.length)break;const s={points:[Lo(r),...o]};t=[...t.slice(0,-1),{points:i},s],n=s}this.info.segments=t}},Du=class extends hh{type="draw";getDefaultProps(){return{segments:(e=[{x:0,y:0},{x:24,y:12}],[{points:e.map(Hr)}]),stroke:"#334155",strokeWidth:4,fill:"transparent",isClosed:!1,isPen:!1};var e}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{segments:_o(t.segments,n.segments),stroke:"string"==typeof t.stroke?t.stroke:n.stroke,strokeWidth:Math.max(4,No(t.strokeWidth,n.strokeWidth)),fill:"string"==typeof t.fill?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=Bo(e);return new kc(e.x+t.localBounds.x,e.y+t.localBounds.y,t.localBounds.w,t.localBounds.h)}getLocalBounds(e){return Bo(e).localBounds}getRenderBounds(e){return Bo(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=Zr(e);for(let s=0;s<2;s+=1){const e=wo(o,t,n,i),s=vo(e.pointBounds,e.localBounds,r);o=io(o,e.pointBounds,s)}return o})({segments:oo(Eo(e),t),strokeWidth:e.props.strokeWidth,isPen:e.props.isPen??!1,isClosed:e.props.isClosed,targetSelectionStrokeBounds:t.targetSelectionStrokeBounds});return t.scaleX<0&&(n=ao(n,{axis:"horizontal",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),t.scaleY<0&&(n=ao(n,{axis:"vertical",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),To(so(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:Ro(n.segments)}}}flipSelectionBounds(e,t){const n=((e,t)=>To(so(ao(oo(Eo(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:Ro(n.segments)}}}getSelectionOverlayInfo(e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null}}isWrappedByBrush(e,t){return Ao(e).outlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return!!this.isWrappedByBrush(e,t)||!t.isWrapping&&(e=>{const t=new Cc(e.minX,e.minY),n=new Cc(e.maxX,e.minY),i=new Cc(e.maxX,e.maxY),r=new Cc(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 Mo(e).outlineVertices}hitTest(e,t){return function(e,t,n,i={}){if(i.isClosed&&void 0!==i.fill&&"transparent"!==i.fill&&e.normalizedPoints.length>=3&&Uo(n,e.normalizedPoints.map(Ur)))return!0;if(i.isClosed&&((e,t)=>{if(0===t.length)return Number.POSITIVE_INFINITY;if(1===t.length)return e.dist(Ur(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,Yo(e,Ur(r),Ur(o))))}return t.length>=3&&(n=Math.min(n,Yo(e,Ur(t[t.length-1]),Ur(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(Uo(n,r))return!0;if(Ho(n,r)<=Math.max(4,.5*t))return!0}return!1}(Mo(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&&"transparent"!==r.fill&&e.normalizedPoints.length>=3&&Wo(n,i,e.normalizedPoints.map(Ur),o))||0!==e.outlineVertices.length&&e.outlinePolygons.some(e=>Wo(n,i,e,o))})(Ao(e),e.props.strokeWidth,t.pageStart,t.pageEnd,{fill:e.props.fill,isClosed:e.props.isClosed,margin:t.margin})}repairLoadedShape(e){const t=Bo(e);if(0===t.pointBounds.x&&0===t.pointBounds.y&&0===e.rotation&&1===e.scaleX&&1===e.scaleY)return null;const n=(e=>To(Eo(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:Ro(n.segments)}}}},zu=class{type="draw";toSvg(e){const t=Bo(e);if(!t.path&&!t.selectionPath)return null;const n=[];return t.fillPath&&"transparent"!==e.props.fill&&n.push({tag:"path",attrs:{d:t.fillPath,fill:e.props.fill,stroke:"none"}}),e.props.isClosed&&t.selectionPath?n.push({tag:"path",attrs:{d:t.selectionPath,fill:"none",stroke:e.props.stroke,"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}):t.path&&n.push({tag:"path",attrs:{d:t.path,fill:e.props.stroke,stroke:"none"}}),{tag:"g",children:n}}},Yu=[{value:"#1d4ed8",label:"Blue",color:"#1d4ed8"},{value:"#15803d",label:"Green",color:"#15803d"},{value:"#dc2626",label:"Red",color:"#dc2626"},{value:"#334155",label:"Slate",color:"#334155"}],Xu=[{value:"transparent",label:"None",color:"transparent"},{value:"#dbeafe",label:"Blue",color:"#dbeafe"},{value:"#dcfce7",label:"Green",color:"#dcfce7"},{value:"#fee2e2",label:"Red",color:"#fee2e2"},{value:"#f8fafc",label:"White",color:"#f8fafc"}],Uu=[{value:4,label:"4"},{value:6,label:"6"},{value:8,label:"8"},{value:10,label:"10"}],Hu=[{value:"open",label:"Open"},{value:"closed",label:"Closed"}],Wu=wi({name:"draw",createFeature:()=>({id:"land.draw.bundle",corePlugins:[{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 Du],shapeSvgExporters:[new zu],toolbarActions:[{id:"draw.set-closed",isVisible:e=>"draw"===e.selection.commonShapeType,isEnabled:e=>e.selection.count>0,getValue:e=>Zo(e.selection.selectedShapes),run({context:e,value:t}){const n=Qo(t);if(null===n)return;const i=e.selection.selectedShapes.filter(qo).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{isClosed:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},Go("fill"),Go("stroke"),Go("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=Qo(t);null!==n&&e.editor.updateDefaultShapeProps("draw",{isClosed:n})}},jo("fill"),jo("stroke"),jo("strokeWidth")],toolbarContributions:[{id:"draw.tool-toolbar",surface:"tool",placement:"chrome",order:45,actionIds:[Yh],getGroups:()=>[{id:"draw.tools",items:[{kind:"button",id:"draw.tool.draw",actionId:Yh,value:"draw",label:"Draw",shortcut:"P",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:()=>Vo({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:()=>Vo({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"===Zo(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 Fu(e),{shortcut:"p"})}}],canvasPlugins:[{id:"land.draw.react",setup(e){e({type:"draw",component:ts})}}],shapeTypes:["draw"]})}),Nu=class extends ph{constructor(e){super(e,"eraser"),this.initial="idle",this.addChild(new Ou(e,this)),this.addChild(new Ku(e,this)),this.addChild(new _u(e,this))}onExit(){hs(this.editor)}},Ou=class extends ph{constructor(e,t){super(e,"idle",t)}onEnter(){hs(this.editor)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={originPagePoint:t.pagePoint.clone(),previousPagePoint:t.pagePoint.clone(),protectedContainerIds:rs(e,t.pagePoint),erasingShapeIds:new Set,trail:[t.pagePoint.clone()]};return as(e,n,t),cs(e,n),n})(this.editor,e))}},Ku=class extends ph{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&&(ds(this.editor,this.info,e),ls(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),cs(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(e){this.info&&(as(this.editor,this.info,e),cs(this.editor,this.info),us(this.editor,this.info)),this.transition("idle")}onCancel(){hs(this.editor),this.transition("idle")}onExit(){this.info=null}},_u=class extends ph{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&&us(this.editor,this.info),this.transition("idle")}onCancel(){hs(this.editor),this.transition("idle")}onExit(){this.info=null}update(e){this.info&&(ds(this.editor,this.info,e),ls(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),cs(this.editor,this.info))}},qu=Zl(()=>Ii(xi().eraserTrailActiveSignal)?dc(Pi,{dataUi:"eraser-trail-page-space",className:"pointer-events-none absolute inset-0",children:dc("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:dc(Vu,{})})}):null),Vu=Zl(()=>{const e=xi(),t=Ii(e.eraserTrailSignal),n=Ii(e.cameraZoomSignal),i=Math.max(n,1e-4),r=(()=>{const[e,t]=sc(()=>ps());return ec(()=>{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=oc({samples:[],sourceLength:0}),s=Math.max(r,ps());((e,t,n,i)=>{if(ms(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-np*o;for(let a=r;a<t.length;a++){const d=t[a];gs(e,{x:d.x,y:d.y},n,ks(s,i,(a-r+1)/o))}e.sourceLength=t.length,ms(e,i)})(o.current,t,i,s);const a=function(e,t){const n=fs(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(Cs(i[i.length-1],e[r],n));return i})(n.length>ju?n.slice(-48):n,Ju)}(o.current.samples,s);if(0===a.length)return null;const d=(c=Qu/i,0===(l=a).length||c<=0?null:1===l.length?Ms(ys(l[0],c/2,tp))??"":Ms((e=>{if(0===e.length)return[];if(1===e.length)return ys(e[0].point,Math.max(e[0].radius,.01),tp);const t=[],n=[];for(const a of e){const e=Ps(a.direction);Ts(t,bs(a.point,vs(e,a.radius))),Ts(n,ws(a.point,vs(e,a.radius)))}const i=[];for(const a of t)Ts(i,a);const r=e[e.length-1],o=Ps(r.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const r=[];for(let o=1;o<ep;o++){const s=o/ep;r.push(ws(e,ws(vs(t,Math.sin(Math.PI*s)*i),vs(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)Ts(i,a);for(let a=n.length-1;a>=0;a--)Ts(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]+xs(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=Bs(s/i,0,1);return{point:r,direction:Ss(e,o),radius:t/2*a,runningLength:s}})})(l,c))));var l,c;return d?dc("g",{"data-ui":"eraser-trail-overlay",children:dc("path",{"data-ui":"eraser-trail-scribble",d:d,fill:Gu})}):null}),Gu="rgba(142, 142, 142, 0.16)",ju=48,Zu=1,Qu=12,Ju=.32,ep=8,tp=13,np=16,ip=8,rp=180,op=180,sp=680,ap=wi({name:"eraser",createFeature:()=>({id:"land.eraser.bundle",corePlugins:[{id:"land.eraser",toolbarContributions:[{id:"eraser.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[Yh],getGroups:()=>[{id:"eraser.tools",items:[{kind:"button",id:"eraser.tool.eraser",actionId:Yh,value:"eraser",label:"Eraser",shortcut:"E",icon:"eraser",dataUi:"eraser-tool-button"}]}]}],setup(e){e.tools.register("eraser",e=>new Nu(e),{shortcut:"e"})}}],canvasPlugins:[{id:"land.eraser.react",canvasComponents:[{id:"land.eraser.trail-overlay",component:qu}],setup(){}}],shapeTypes:[]})}),dp=class extends hh{type="frame";getDefaultProps(){return{w:640,h:360,name:"Frame",fill:"transparent",stroke:"#94a3b8",strokeWidth:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,Fs(t.w,n.w)),h:Math.max(1,Fs(t.h,n.h)),name:"string"==typeof t.name&&t.name.length>0?t.name:n.name,fill:"string"==typeof t.fill?t.fill:n.fill,stroke:"string"==typeof t.stroke?t.stroke:n.stroke,strokeWidth:Math.max(0,Fs(t.strokeWidth,n.strokeWidth))}}getBounds(e){return new kc(e.x,e.y,e.props.w,e.props.h)}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 $s(this.getBounds(e),t,Ls(e))}hitTestLineSegment(e,t){return((e,t,n,i)=>{const r=i/2;if($s(e,t,i)||$s(e,n,i))return!0;const o=[new Cc(e.minX,e.minY),new Cc(e.maxX,e.minY),new Cc(e.maxX,e.maxY),new Cc(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&&Gn(t,n,e,i)<=r)return!0}return!1})(this.getBounds(e),t.positionedStart,t.positionedEnd,Math.max(Ls(e),t.margin))}},lp="frame.create",cp=class extends ph{constructor(e){super(e,"frame"),this.initial="idle",this.addChild(new hp(e,this)),this.addChild(new up(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("frame")}},hp=class extends ph{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})}},up=class extends ph{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(lp)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.editor.history.squashToMark(lp),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(lp),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 kc(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 Cc(e.x+r,e.y+o);return new kc(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}},pp=class{type="frame";toSvg(e){const{fill:t,stroke:n,strokeWidth:i,w:r,h:o,name:s}=e.props,a=i/2;return{tag:"g",children:[{tag:"rect",attrs:{x:a,y:a,width:Math.max(r-i,0),height:Math.max(o-i,0),fill:t,stroke:n,"stroke-width":i,"stroke-linejoin":"round","stroke-linecap":"round"}},{tag:"text",attrs:{x:12,y:18,fill:n,"font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":600},children:[s]}]}}},gp=[{value:"transparent",label:"None",color:"transparent"},{value:"#eff6ff",label:"Blue",color:"#eff6ff"},{value:"#f0fdf4",label:"Green",color:"#f0fdf4"},{value:"#fff7ed",label:"Amber",color:"#fff7ed"}],mp=[{value:"#94a3b8",label:"Slate",color:"#94a3b8"},{value:"#2563eb",label:"Blue",color:"#2563eb"},{value:"#16a34a",label:"Green",color:"#16a34a"},{value:"#ea580c",label:"Orange",color:"#ea580c"}],fp=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Sp=wi({name:"frame",createFeature:()=>({id:"land.frame.bundle",corePlugins:[{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 dp],shapeSvgExporters:[new pp],toolbarActions:[Ds("fill"),Ds("stroke"),Ds("strokeWidth"),zs("fill"),zs("stroke"),zs("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"})}},Xs("backward"),Xs("forward")],toolbarContributions:[{id:"frame.tool-toolbar",surface:"tool",placement:"chrome",order:60,actionIds:[Yh],getGroups:()=>[{id:"frame.tools",items:[{kind:"button",id:"frame.tool.frame",actionId:Yh,value:"frame",label:"Frame",shortcut:"F",icon:"square",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:()=>Ys({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"}]}]:[],...Ys({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"===Hs(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"===Hs(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 cp(e),{shortcut:"f"})}}],canvasPlugins:[{id:"land.frame.react",setup(e){e({type:"frame",component:Ws})}}],shapeTypes:["frame"]})}),yp="geo.create",xp=class extends ph{geo;constructor(e,t,n){super(e,t),this.geo=n,this.initial="idle",this.addChild(new Ip(e,this)),this.addChild(new Pp(e,this))}getDefaultProps(){return{...this.editor.getDefaultShapeProps("geo"),geo:this.geo}}},Ip=class extends ph{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})}},Pp=class extends ph{tool;info=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.editor.history.mark(yp)}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.info.shapeId&&z(this.editor,this.info.shapeId,{source:"user"}),this.editor.history.squashToMark(yp),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.editor.history.bailToMark(yp),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 kc(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 Cc(e.x+i,e.y+r);return new kc(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}},wp=class extends xp{constructor(e){super(e,"rectangle","rectangle")}},bp=class extends xp{constructor(e){super(e,"ellipse","ellipse")}},vp=class extends xp{constructor(e){super(e,"diamond","diamond")}},Cp=["rectangle","ellipse","diamond"],kp=class extends hh{type="geo";getDefaultProps(){return{w:160,h:108,geo:"rectangle",fill:"#e2e8f0",stroke:"#334155",strokeWidth:2}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,Os(t.w,n.w)),h:Math.max(24,Os(t.h,n.h)),geo:(i=t.geo,"string"==typeof i&&Cp.includes(i)?t.geo:n.geo),fill:"string"==typeof t.fill?t.fill:n.fill,stroke:"string"==typeof t.stroke?t.stroke:n.stroke,strokeWidth:Math.max(1,Os(t.strokeWidth,n.strokeWidth))};var i}getBounds(e){return new kc(e.x,e.y,e.props.w,e.props.h)}getPositionedOutlineVertices(e){const t=this.getBounds(e);switch(e.props.geo){case"ellipse":{const e=t.center.x,n=t.center.y,i=t.w/2,r=t.h/2,o=32,s=[];for(let t=0;t<o;t+=1){const a=t/o*Math.PI*2;s.push(new Cc(e+i*Math.cos(a),n+r*Math.sin(a)))}return s}case"diamond":return[new Cc(t.center.x,t.minY),new Cc(t.maxX,t.center.y),new Cc(t.center.x,t.maxY),new Cc(t.minX,t.center.y)];default:return super.getPositionedOutlineVertices(e)}}getHandleSnapGeometry(e){return{points:Zs(e),outline:js(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":{const e=n.w/2,i=n.h/2;return!(e<=0||i<=0)&&Math.abs(t.x-n.center.x)/e+Math.abs(t.y-n.center.y)/i<=1}default:return n.containsPoint(t)}}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,h=d.x/o,u=d.y/s,p=l*l+c*c,g=2*(h*l+u*c),m=h*h+u*u-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"diamond":{const i=[new Cc(n.center.x,n.minY),new Cc(n.maxX,n.center.y),new Cc(n.center.x,n.maxY),new Cc(n.minX,n.center.y)];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&&qs(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 kc(e.x,e.y,e.props.w,e.props.h);switch(e.props.geo){case"ellipse":return((e,t,n)=>{const i=e.w/2,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,h=a*a+d*d,u=2*(l*a+c*d),p=u*u-4*h*(l*l+c*c-1);if(0===h||p<0)return null;const g=Math.sqrt(p),m=[(-u-g)/(2*h),(-u+g)/(2*h)].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);case"diamond":return Gs(t,n,[new Cc(i.center.x,i.minY),new Cc(i.maxX,i.center.y),new Cc(i.center.x,i.maxY),new Cc(i.minX,i.center.y)]);default:return Gs(t,n,[new Cc(i.minX,i.minY),new Cc(i.maxX,i.minY),new Cc(i.maxX,i.maxY),new Cc(i.minX,i.maxY)])}}(e,Le(e,t.rawPagePoint,this),Le(e,t.oppositePagePoint,this));return n?Fe(e,n,this):t.rawPagePoint}},Bp=class{type="geo";toSvg(e){const{geo:t,fill:n,stroke:i,strokeWidth:r,w:o,h:s}=e.props,a=r/2,d=Math.max(o-r,0),l=Math.max(s-r,0),c={fill:n,stroke:i,"stroke-width":r,"stroke-linejoin":"round","stroke-linecap":"round"};if("ellipse"===t)return{tag:"ellipse",attrs:{...c,cx:o/2,cy:s/2,rx:d/2,ry:l/2}};if("diamond"===t)return{tag:"polygon",attrs:{...c,points:[`${ra(o/2)},${ra(a)}`,`${ra(o-a)},${ra(s/2)}`,`${ra(o/2)},${ra(s-a)}`,`${ra(a)},${ra(s/2)}`].join(" ")}};const h=Math.min(10,.12*d,.12*l);return{tag:"rect",attrs:{...c,x:a,y:a,width:d,height:l,rx:h,ry:h}}}},Tp=[{value:"#dbeafe",label:"Blue",color:"#dbeafe"},{value:"#dcfce7",label:"Green",color:"#dcfce7"},{value:"#fee2e2",label:"Red",color:"#fee2e2"},{value:"#f8fafc",label:"White",color:"#f8fafc"}],Mp=[{value:"#1d4ed8",label:"Blue",color:"#1d4ed8"},{value:"#15803d",label:"Green",color:"#15803d"},{value:"#dc2626",label:"Red",color:"#dc2626"},{value:"#334155",label:"Slate",color:"#334155"}],Ep=[{value:1,label:"1"},{value:2,label:"2"},{value:4,label:"4"}],Ap=wi({name:"geo",createFeature:()=>({id:"land.geo.bundle",corePlugins:[{id:"land.geo",shapeCapabilities:[{type:"geo",schemaProps:["w","h","geo","fill","stroke","strokeWidth"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Toolbar covers rectangle, ellipse, and diamond through geo props."]}],shapeUtils:[new kp],shapeSvgExporters:[new Bp],toolbarActions:[{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(Qs(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("rectangle"!==t&&"ellipse"!==t&&"diamond"!==t)return;const n=e.selection.selectedShapes.filter(Qs).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{geo:t}}));0!==n.length&&e.editor.commands.updateShapes(n,{source:"user"})}},Js("fill"),Js("stroke"),Js("strokeWidth"),ea("fill"),ea("stroke"),ea("strokeWidth")],toolbarContributions:[{id:"geo.tool-toolbar",surface:"tool",placement:"chrome",order:20,actionIds:[Yh],getGroups:()=>[{id:"geo.tools",items:[{kind:"button",id:"geo.tool.rectangle",actionId:Yh,value:"rectangle",label:"Rectangle",shortcut:"R",icon:"square",dataUi:"rectangle-tool-button"},{kind:"button",id:"geo.tool.ellipse",actionId:Yh,value:"ellipse",label:"Ellipse",shortcut:"O",icon:"circle",dataUi:"ellipse-tool-button"},{kind:"button",id:"geo.tool.diamond",actionId:Yh,value:"diamond",label:"Diamond",shortcut:"D",icon:"diamond",dataUi:"diamond-tool-button"}]}]},{id:"geo.default-style.tool-toolbar",surface:"tool",order:21,actionIds:["geo.default-fill","geo.default-stroke","geo.default-strokeWidth"],when:e=>ia(e.tool.activeToolId),getGroups:()=>ta({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:[{value:"rectangle",label:"Rectangle",icon:"square",dataUi:"rectangle-shape-button"},{value:"ellipse",label:"Ellipse",icon:"circle",dataUi:"ellipse-shape-button"},{value:"diamond",label:"Diamond",icon:"diamond",dataUi:"diamond-shape-button"}]}]},...ta({fillActionId:"geo.set-fill",strokeActionId:"geo.set-stroke",strokeWidthActionId:"geo.set-strokeWidth",dataUiPrefix:"geo"})]}],setup(e){e.tools.register("rectangle",e=>new wp(e),{shortcut:"r"}),e.tools.register("ellipse",e=>new bp(e),{shortcut:"o"}),e.tools.register("diamond",e=>new vp(e),{shortcut:"d"})}}],canvasPlugins:[{id:"land.geo.react",setup(e){e({type:"geo",component:oa})}}],shapeTypes:["geo"]})}),Rp=class extends hh{type="group";getDefaultProps(){return{w:1,h:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:aa(t.w,n.w),h:aa(t.h,n.h)}}getBounds(e){return new kc(e.x,e.y,e.props.w,e.props.h)}hitTest(e,t){return!1}shouldTransformDescendants(e){return!0}canReceiveChildren(e){return!0}},Fp=class{type="group";toSvg(e){return{tag:"g"}}},Lp=wi({name:"group",createFeature:()=>({id:"land.group.bundle",corePlugins:[{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 Rp],shapeSvgExporters:[new Fp]}],canvasPlugins:[{id:"land.group.react",setup(e){e({type:"group",component:da})}}],shapeTypes:["group"]})}),$p=1e-4,Dp=1e-4,zp="image.crop.translate",Yp="image.crop:edit:",Xp=[{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}],Up={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"},Hp=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],Wp=new Map,Np=class extends hh{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,La(t.w,n.w)),h:Math.max(24,La(t.h,n.h)),assetId:(i=t.assetId,"string"==typeof i&&i.startsWith("asset:")?t.assetId:null),crop:ga(t.crop),altText:"string"==typeof t.altText?t.altText:n.altText};var i}getBounds(e){return new kc(e.x,e.y,e.props.w,e.props.h)}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&&wa(e,i.markId)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:va({crop:e.props.crop,localToPage:t.editor.computeShapeLocalToPageTransform(e),shape:e})}:n}},Op="image.replace",Kp="image.download-original",_p="image.insert",qp="image.crop",Vp="image.crop.done",Gp="image.crop.zoom",jp="image.crop.aspect-ratio",Zp="image.crop.reset",Qp=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=ma(r);return d?{tag:"svg",attrs:{x:0,y:0,width:s,height:o,viewBox:(l=d,[ka(l.left),ka(l.top),ka(l.width),ka(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}},Jp={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(!Ma(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&wa(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 Cc(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}},eg=wi({name:"image",createFeature:()=>({id:"land.image.bundle",corePlugins:[$a()],canvasPlugins:[{id:"land.image.react",domEventGuards:[Jp],setup(e){e({type:"image",component:Xa})}}],shapeTypes:["image"]})}),tg=class extends ph{constructor(e){super(e,"laser"),this.initial="idle",this.addChild(new ng(e,this)),this.addChild(new ig(e,this)),this.addChild(new rg(e,this))}},ng=class extends ph{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 Ha(e,n),n})(this.editor,e))}},ig=class extends ph{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&&(Ua(this.info,e.pagePoint),Ha(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}},rg=class extends ph{info=null;constructor(e,t){super(e,"drawing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&(Ua(this.info,e.pagePoint),Ha(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}},og=Zl(()=>Ii(xi().laserTrailActiveSignal)?dc(Pi,{dataUi:"laser-trail-page-space",className:"pointer-events-none absolute inset-0",children:dc("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:dc(sg,{})})}):null),sg=Zl(()=>{const e=xi(),t=Ii(e.laserTrailSignal),n=Ii(e.cameraZoomSignal),i=Math.max(n,1e-4),r=(()=>{const[e,t]=sc(()=>Wa());return ec(()=>{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=oc({sessionId:0,samples:[],sourceLength:0}),s=Math.max(r,Wa());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(Oa(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-fg*s;for(let d=o;d<r.length;d++){const t=r[d];Na(e,{x:t.x,y:t.y},n,td(a,i,(d-o+1)/s))}e.sourceLength=r.length,Oa(e,i)})(o.current,t,i,s),d=function(e,t){const n=Ka(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(ed(i[i.length-1],e[r],n));return i})(n.length>cg?n.slice(-64):n,pg)}(o.current.samples,s),a=o.current.samples[o.current.samples.length-1]?.time);const l="ending"===t?.phase,c=0===d.length,h=l&&c?t.sessionId:null;if(ec(()=>{null!==h&&e.clearLaserTrail(h)},[e,h]),!t||c)return null;const u=l&&void 0!==a?nd(1-(s-a)/Pg,0,1):1,p=(m=ug/i,0===(g=d).length||m<=0?null:1===g.length?rd(qa(g[0],m/2,mg))??"":rd((e=>{if(0===e.length)return[];if(1===e.length)return qa(e[0].point,Math.max(e[0].radius,.01),mg);const t=[],n=[];for(const a of e){const e=ja(a.direction);id(t,Qa(a.point,Ja(e,a.radius))),id(n,Za(a.point,Ja(e,a.radius)))}const i=[];for(const a of t)id(i,a);const r=e[e.length-1],o=ja(r.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const r=[];for(let o=1;o<gg;o++){const s=o/gg;r.push(Za(e,Za(Ja(t,Math.sin(Math.PI*s)*i),Ja(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)id(i,a);for(let a=n.length-1;a>=0;a--)id(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]+Va(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=nd(s/i,0,1);return{point:r,direction:_a(e,o),radius:t/2*a,runningLength:s}})})(g,m))));var g,m;return p?lc("g",{"data-ui":"laser-trail-overlay",style:{opacity:u},children:[dc("path",{"data-ui":"laser-trail-glow",d:p,fill:dg,style:{filter:`blur(${lg/i}px)`}}),dc("path",{"data-ui":"laser-trail-beam",d:p,fill:ag})]}):null}),ag="rgb(255, 38, 38)",dg="rgba(255, 48, 48, 0.55)",lg=4,cg=64,hg=1,ug=12,pg=.32,gg=8,mg=13,fg=16,Sg=8,yg=600,xg=300,Ig=1400,Pg=400,wg=wi({name:"laser",createFeature:()=>({id:"land.laser.bundle",corePlugins:[{id:"land.laser",toolbarContributions:[{id:"laser.tool-toolbar",surface:"tool",placement:"chrome",order:55,actionIds:[Yh],getGroups:()=>[{id:"laser.tools",items:[{kind:"button",id:"laser.tool.laser",actionId:Yh,value:"laser",label:"Laser",shortcut:"L",icon:"wand",dataUi:"laser-tool-button"}]}]}],setup(e){e.tools.register("laser",e=>new tg(e),{shortcut:"l"})}}],canvasPlugins:[{id:"land.laser.react",canvasComponents:[{id:"land.laser.trail-overlay",component:og}],setup(){}}],shapeTypes:[]})}),bg={"noto-sans-sc":{font:"noto-sans-sc",family:"Noto Sans SC",cssUrl:"https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;700&display=swap",weights:[400,700]},"noto-serif-sc":{font:"noto-serif-sc",family:"Noto Serif SC",cssUrl:"https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;700&display=swap",weights:[400,700]},"noto-sans-mono":{font:"noto-sans-mono",family:"Noto Sans Mono",cssUrl:"https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@400;700&display=swap",weights:[400,700]},"ma-shan-zheng":{font:"ma-shan-zheng",family:"Ma Shan Zheng",cssUrl:"https://fonts.googleapis.com/css2?family=Ma+Shan+Zheng&display=swap",weights:[400]}},vg=new WeakMap,Cg="noto-sans-sc",kg={s:{fontSize:14,lineHeight:20},m:{fontSize:16,lineHeight:24},l:{fontSize:20,lineHeight:28},xl:{fontSize:28,lineHeight:36}},Bg=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))),Ud(i,"whiteSpace",n?.whiteSpace),Ud(i,"overflowWrap",n?.overflowWrap),Ud(i,"lineHeight",n?.lineHeight),Ud(i,"letterSpacing",n?.letterSpacing),Ud(i,"textAlign",n?.textAlign),this.measurePreparedElement(i)}prepareElement(e){const t=this.element;return t.removeAttribute("contenteditable"),t.className="",t.textContent="",e?.shape&&((e,t)=>{e.className="land-rich-text-editor h-full min-h-full w-full outline-none whitespace-pre-wrap break-words",e.dir="auto",e.style.color=t.props.color,e.style.fontFamily=Ad(t.props.font),e.style.fontSize=`${Rd(t.props.size)}px`,e.style.lineHeight=`${Fd(t.props.size)}px`,e.style.textAlign=$d(t.props.textAlign)})(t,e.shape),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})}},Tg=new WeakMap,Mg=[{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"}],Eg=[mc.configure({bold:!1,italic:!1,strike:!1}),uc.extend({keepOnSplit:!0}),pc.extend({keepOnSplit:!0}),gc.extend({keepOnSplit:!0})],Ag={id:"land.text.dom-events",handle({event:e}){const t=e.target;return t instanceof HTMLElement&&t.closest('[data-ui="text-editing-box"]')?"handled":"continue"},getCursor:({element:e})=>e?.closest('[data-ui="text-editing-box"]')?"text":void 0},Rg="text.create",Fg=class extends ph{constructor(e){super(e,"text"),this.initial="idle",this.addChild(new Lg(e,this)),this.addChild(new $g(e,this))}},Lg=class extends ph{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("pointing",{originPagePoint:e.pagePoint.clone(),shapeId:null,didCreateShape:!1})}},$g=class extends ph{info=null;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e,this.editor.history.mark(Rg)}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(!vd(t))return this.editor.history.bailToMark(Rg),void this.transition("idle");this.info.didCreateShape=!0,z(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:Rg,reuseExistingMark:!0,preserveInteraction:!0},"user"),this.editor.isToolLocked()&&this.transition("idle")}onCancel(){this.info?.didCreateShape||this.editor.history.bailToMark(Rg),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:{...il(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:il(t)}))(e,this.getDefaultTextProps()))}createTextShapeAt({x:e,y:t,props:n}){const i=Bd(this.editor,{x:e,y:t,props:n},"user");return this.editor.commands.setSelectedShapeIds([i.id],{source:"system"}),i}getDefaultTextProps(){return kd(this.editor)}},Dg="arrow-label",zg="geo-label",Yg={[Dg]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!0,canUseSelectionFrameHandles:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[zg]:{selectionTarget:"owner",translateTarget:"owner",contributesToSelectionFrame:!1,canUseSelectionFrameHandles:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}},Xg=["noto-sans-sc","noto-serif-sc","noto-sans-mono","ma-shan-zheng"],Ug=["s","m","l","xl"],Hg=["start","middle","end"],Wg=class extends hh{type="text";getDefaultProps(){return{richText:dd(""),w:16,h:Ld("m"),autoSize:!0,scale:1,font:Cg,size:"m",color:"#0f172a",textAlign:"start"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{richText:cd(t.richText),w:Math.max(1,dl(t.w,n.w)),h:Math.max(1,dl(t.h,n.h)),autoSize:"boolean"==typeof t.autoSize?t.autoSize:n.autoSize,scale:Math.max(.01,dl(t.scale,n.scale)),font:(i=t.font,"string"==typeof i&&Xg.includes(i)?t.font:n.font),size:ll(t.size)?t.size:n.size,color:"string"==typeof t.color?t.color:n.color,textAlign:cl(t.textAlign)?t.textAlign:n.textAlign};var i}getBounds(e){return(e=>new kc(e.x,e.y,ul(e),pl(e)))(e)}getLocalBounds(e){return gl(e)}getRenderBounds(e){return gl(e)}getExportBounds(e){return gl(e)}canEdit(e){return!0}contributesToSelectionFrame(e,t){return n=t.editor,i=e.id,sl(n,i)?.behavior.contributesToSelectionFrame??null??!0;var n,i}canUseSelectionFrameHandles(e,t){return n=t.editor,i=e.id,sl(n,i)?.behavior.canUseSelectionFrameHandles??null??!0;var n,i}getSelectionTargetId(e,t){return((e,t)=>{const n=sl(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=sl(e,t);return n?"owner"===n.behavior.translateTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}resizeSelectionBounds(e,t){const n={};ml(t.handleId)?(n.w=Math.max(16,t.selectionLocalBounds.w/hl(e)),n.autoSize=!1):n.scale=Math.max(.01,e.props.scale*((e,t)=>{const n=t.selectionLocalBounds.w/Math.max(1,ul(e)),i=t.selectionLocalBounds.h/Math.max(1,pl(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??hl(e),r=(n.w??e.props.w)*i,o=e.props.h*i,s=((e,t)=>0===t.selectionRotation?e.clone():Cc.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(yt({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?!ml(t.handleId):null}onEditEnd(e){if(!(ld(e.props.richText).trim().length>0))return{deleteShapeIds:[e.id]}}},Ng=class{type="text";toSvg(e){return 0===ld(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:yl(e)},children:fl(e.props.richText)}]}}},Og=".label",Kg=class extends uh{type=Dg;getDefaultProps(){return{labelPosition:.5}}validateProps(e){const t=this.getDefaultProps();return{labelPosition:Il((e&&"object"==typeof e?e:{}).labelPosition,t.labelPosition)}}canBind(e,t,n){return vd(n.fromShape)&&xl(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)=>sl(e,t)?.behavior.showsCompanionFrameWhenOwnerSelected??null)(e,t.fromId))return[];const i=e.getShape(t.fromId),r=e.getShape(t.toId);if(!vd(i)||!xl(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(!vd(i)||!xl(r))return{deleteBindingIds:[t.id]};const o=((e,t,n)=>{const i=Pl(e,t,n),r=n.parentId,o=`${n.index}${Og}`,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}},_g=".label",qg=class extends uh{type=zg;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:Cl(i.x,t.normalizedAnchor.x),y:Cl(i.y,t.normalizedAnchor.y)},ownerBaseHeight:kl(n.ownerBaseHeight,t.ownerBaseHeight)}}canBind(e,t,n){return vd(n.fromShape)&&vl(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?Tl(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?Tl(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(!vd(r)||!vl(o))return{deleteBindingIds:[t.id]};const s=((e,t,n)=>{const i=Bl(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=Bl(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=Ml(e,t,n),r=n.parentId,o=`${n.index}${_g}`,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}},Vg="text.edit",Gg="arrow-label.edit",jg="arrow-label.create",Zg="geo-label.edit",Qg="geo-label.create",Jg=[{value:"#0f172a",label:"Slate",color:"#0f172a"},{value:"#1d4ed8",label:"Blue",color:"#1d4ed8"},{value:"#15803d",label:"Green",color:"#15803d"},{value:"#dc2626",label:"Red",color:"#dc2626"}],em=[{value:"noto-sans-sc",label:"Noto SC"},{value:"noto-serif-sc",label:"Serif SC"},{value:"noto-sans-mono",label:"Mono"},{value:"ma-shan-zheng",label:"Ma Shan"}],tm=[{value:"s",label:"S"},{value:"m",label:"M"},{value:"l",label:"L"},{value:"xl",label:"XL"}],nm=[{value:"start",label:"Align left",icon:"align-left"},{value:"middle",label:"Align center",icon:"align-center"},{value:"end",label:"Align right",icon:"align-right"}],im=[Ap,Wu,ku,ap,wg,eg,wi({name:"text",createFeature:()=>({id:"land.text.bundle",corePlugins:[{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 Wg],shapeSvgExporters:[new Ng],bindingUtils:[new qg,new Kg],interactionHandlers:[El()],toolbarActions:[{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")}},Fl("color"),Fl("font"),Fl("size"),Fl("textAlign"),Ll("color"),Ll("font"),Ll("size"),Ll("textAlign")],toolbarContributions:[{id:"text.tool-toolbar",surface:"tool",placement:"chrome",order:50,actionIds:[Yh],getGroups:()=>[{id:"text.tools",items:[{kind:"button",id:"text.tool.text",actionId:Yh,value:"text",label:"Text",shortcut:"T",icon:"type",dataUi:"text-tool-button"}]}]},{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:()=>Rl({colorActionId:"text.default-color",fontActionId:"text.default-font",sizeActionId:"text.default-size",textAlignActionId:"text.default-textAlign",dataUiPrefix:"text-default"})},{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:()=>Rl({colorActionId:"text.set-color",fontActionId:"text.set-font",sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"})}],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 Fg(e),{shortcut:"t"})}}],canvasPlugins:[{id:"land.text.react",domEventGuards:[Ag],canvasComponents:[{id:"land.text.default-font-preload",component:tl}],setup(e){e({type:"text",component:nl})}}],shapeTypes:["text"]})}),Sp,Lp],rm=Qi("standard.geo.product-api"),om=Qi("standard.text.product-api"),sm=Qi("standard.frame.product-api"),am=Qi("standard.arrow.product-api");export{zh as C,Cc as E,Xh as S,ch as T,Bi as _,rm as a,Uh as b,Xl as c,Ta as d,Ma as f,Wi as g,ji as h,sm as i,im as l,Qi as m,_l as n,om as o,Ji as p,am as r,Gl as s,Vl as t,za as u,bi as v,gh as w,Yh as x,Ii as y};