@yuzhouu/canvas-kit 0.1.13 → 0.1.15

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 (495) hide show
  1. package/README.md +52 -264
  2. package/_vendor/canvas-core/bindings/bindingManager.d.ts +33 -0
  3. package/_vendor/canvas-core/bindings/bindingUtil.d.ts +7 -7
  4. package/_vendor/canvas-core/bindings/terminalBinding.d.ts +1 -1
  5. package/_vendor/canvas-core/editor/clipboardAssets.d.ts +6 -0
  6. package/_vendor/canvas-core/editor/commands/assetCommands.d.ts +7 -0
  7. package/_vendor/canvas-core/editor/commands/bindingCommands.d.ts +12 -0
  8. package/_vendor/canvas-core/editor/{commands.d.ts → commands/commandTypes.d.ts} +4 -6
  9. package/_vendor/canvas-core/editor/commands/commands.d.ts +5 -0
  10. package/_vendor/canvas-core/editor/commands/documentCommands.d.ts +9 -0
  11. package/_vendor/canvas-core/editor/commands/sessionCommands.d.ts +13 -0
  12. package/_vendor/canvas-core/editor/commands/shapeCommands.d.ts +9 -0
  13. package/_vendor/canvas-core/editor/commands/shapeFlags.d.ts +10 -0
  14. package/_vendor/canvas-core/editor/commands/shapeRemoval.d.ts +10 -0
  15. package/_vendor/canvas-core/editor/commands/shapeRepair.d.ts +11 -0
  16. package/_vendor/canvas-core/editor/createEditor.d.ts +6 -0
  17. package/_vendor/canvas-core/editor/editor.d.ts +310 -538
  18. package/_vendor/canvas-core/editor/events/canvasNavigationInteraction.d.ts +2 -0
  19. package/_vendor/canvas-core/editor/events/eventRouter.d.ts +16 -0
  20. package/_vendor/canvas-core/editor/{events.d.ts → events/events.d.ts} +18 -8
  21. package/_vendor/canvas-core/editor/{managers → events}/inputsManager.d.ts +6 -4
  22. package/_vendor/canvas-core/editor/{interactions.d.ts → events/interactions.d.ts} +12 -12
  23. package/_vendor/canvas-core/editor/events/keyboardShortcuts.d.ts +23 -0
  24. package/_vendor/canvas-core/editor/events/pointerClickRecognizer.d.ts +11 -0
  25. package/_vendor/canvas-core/editor/history/historyManager.d.ts +40 -0
  26. package/_vendor/canvas-core/editor/{operationManager.d.ts → history/operationManager.d.ts} +21 -18
  27. package/_vendor/canvas-core/editor/queries/bindingQueryCache.d.ts +28 -0
  28. package/_vendor/canvas-core/editor/queries/bindingQueryState.d.ts +11 -0
  29. package/_vendor/canvas-core/editor/queries/draftBindingIndex.d.ts +19 -0
  30. package/_vendor/canvas-core/editor/queries/shapeGeometryQueryCache.d.ts +34 -0
  31. package/_vendor/canvas-core/editor/queries/shapeTransforms.d.ts +13 -15
  32. package/_vendor/canvas-core/editor/queries/shapeTreeIndex.d.ts +27 -0
  33. package/_vendor/canvas-core/editor/queries/shapeTreeIndexState.d.ts +11 -0
  34. package/_vendor/canvas-core/editor/{managers → queries}/spatialIndexManager.d.ts +5 -3
  35. package/_vendor/canvas-core/editor/records/documentSnapshots.d.ts +14 -0
  36. package/_vendor/canvas-core/editor/records/editorRecordFactory.d.ts +19 -0
  37. package/_vendor/canvas-core/editor/records/recordQueries.d.ts +3 -0
  38. package/_vendor/canvas-core/editor/{resizeGeometry.d.ts → selection/resizeGeometry.d.ts} +2 -2
  39. package/_vendor/canvas-core/editor/{selection.d.ts → selection/selection.d.ts} +4 -30
  40. package/_vendor/canvas-core/editor/{managers → selection}/selectionGeometry.d.ts +2 -2
  41. package/_vendor/canvas-core/editor/selection/selectionHandleHitTest.d.ts +8 -0
  42. package/_vendor/canvas-core/editor/selection/selectionLayout.d.ts +20 -0
  43. package/_vendor/canvas-core/editor/selection/selectionOverlay.d.ts +25 -0
  44. package/_vendor/canvas-core/editor/selection/selectionOverlayEquality.d.ts +8 -0
  45. package/_vendor/canvas-core/editor/selection/selectionOverlayManager.d.ts +34 -0
  46. package/_vendor/canvas-core/editor/{selectionResizeCapabilities.d.ts → selection/selectionResizeCapabilities.d.ts} +2 -2
  47. package/_vendor/canvas-core/editor/selection/selectionSet.d.ts +9 -0
  48. package/_vendor/canvas-core/editor/selection/selectionTargets.d.ts +10 -0
  49. package/_vendor/canvas-core/editor/selection/selectionTransforms.d.ts +6 -0
  50. package/_vendor/canvas-core/editor/shapes/shapeContainment.d.ts +14 -0
  51. package/_vendor/canvas-core/editor/{managers → shapes}/shapeEditingManager.d.ts +2 -2
  52. package/_vendor/canvas-core/editor/shapes/shapeExportTraversal.d.ts +3 -0
  53. package/_vendor/canvas-core/editor/shapes/shapeGeometry.d.ts +22 -0
  54. package/_vendor/canvas-core/editor/shapes/shapeGrouping.d.ts +22 -0
  55. package/_vendor/canvas-core/editor/{managers → shapes}/shapeOrder.d.ts +20 -2
  56. package/_vendor/canvas-core/editor/shapes/shapeReparenting.d.ts +21 -0
  57. package/_vendor/canvas-core/editor/shapes/shapeSignalManager.d.ts +33 -0
  58. package/_vendor/canvas-core/editor/{shapeTransformSpace.d.ts → shapes/shapeTransformSpace.d.ts} +3 -3
  59. package/_vendor/canvas-core/editor/shapes/shapeTreeQueries.d.ts +12 -0
  60. package/_vendor/canvas-core/editor/snapping/gapSnap.d.ts +6 -0
  61. package/_vendor/canvas-core/editor/snapping/pointSnap.d.ts +5 -0
  62. package/_vendor/canvas-core/editor/snapping/resizeSnap.d.ts +11 -0
  63. package/_vendor/canvas-core/editor/snapping/snapDecision.d.ts +2 -0
  64. package/_vendor/canvas-core/editor/{managers → snapping}/snapGeometry.d.ts +0 -1
  65. package/_vendor/canvas-core/editor/{managers → snapping}/snapIndicators.d.ts +2 -2
  66. package/_vendor/canvas-core/editor/{managers → snapping}/snapManager.d.ts +23 -5
  67. package/_vendor/canvas-core/editor/{managers/snapCalculations.d.ts → snapping/snapResults.d.ts} +2 -17
  68. package/_vendor/canvas-core/editor/{managers → snapping}/snapTypes.d.ts +1 -1
  69. package/_vendor/canvas-core/editor/state/editorReadModels.d.ts +34 -0
  70. package/_vendor/canvas-core/editor/state/editorSignals.d.ts +82 -0
  71. package/_vendor/canvas-core/editor/state/editorStateUtils.d.ts +9 -0
  72. package/_vendor/canvas-core/editor/{managers → state}/interactionTransientManager.d.ts +4 -4
  73. package/_vendor/canvas-core/editor/{managers → viewport}/cameraManager.d.ts +21 -4
  74. package/_vendor/canvas-core/editor/{cameraPanSession.d.ts → viewport/cameraPanSession.d.ts} +3 -3
  75. package/_vendor/canvas-core/editor/{edgeScroll.d.ts → viewport/edgeScroll.d.ts} +1 -1
  76. package/_vendor/canvas-core/editor/{renderWindow.d.ts → viewport/renderWindow.d.ts} +8 -8
  77. package/_vendor/canvas-core/editor/{managers → viewport}/renderWindowManager.d.ts +14 -6
  78. package/_vendor/canvas-core/geometry/box.d.ts +1 -0
  79. package/_vendor/canvas-core/index.d.ts +30 -25
  80. package/_vendor/canvas-core/plugins/editorRuntimePlugin.d.ts +2 -5
  81. package/_vendor/canvas-core/plugins/editorRuntimeRegistry.d.ts +0 -4
  82. package/_vendor/canvas-core/plugins/index.d.ts +1 -1
  83. package/_vendor/canvas-core/reactivity.d.ts +2 -0
  84. package/_vendor/canvas-core/schema/records.d.ts +1 -1
  85. package/_vendor/canvas-core/shapes/shapeUtil.d.ts +6 -5
  86. package/_vendor/canvas-core/shapes/shapeUtilGeometry.d.ts +6 -0
  87. package/_vendor/canvas-core/tools/hand/handTool.d.ts +1 -1
  88. package/_vendor/canvas-core/tools/select/selectTool.d.ts +1 -1
  89. package/_vendor/canvas-core/tools/select/selectToolHelpers.d.ts +11 -12
  90. package/_vendor/canvas-core/tools/select/states/brushingState.d.ts +2 -2
  91. package/_vendor/canvas-core/tools/select/states/draggingPluginInteractionState.d.ts +2 -3
  92. package/_vendor/canvas-core/tools/select/states/idleState.d.ts +2 -2
  93. package/_vendor/canvas-core/tools/select/states/pointingCanvasState.d.ts +2 -2
  94. package/_vendor/canvas-core/tools/select/states/pointingResizeHandleState.d.ts +1 -1
  95. package/_vendor/canvas-core/tools/select/states/pointingRotateHandleState.d.ts +1 -1
  96. package/_vendor/canvas-core/tools/select/states/pointingSelectionHandleInteractionState.d.ts +3 -3
  97. package/_vendor/canvas-core/tools/select/states/pointingShapeState.d.ts +3 -3
  98. package/_vendor/canvas-core/tools/select/states/resizingState.d.ts +3 -3
  99. package/_vendor/canvas-core/tools/select/states/rotatingState.d.ts +3 -3
  100. package/_vendor/canvas-core/tools/select/states/selectStateNode.d.ts +8 -12
  101. package/_vendor/canvas-core/tools/select/states/translatingState.d.ts +2 -3
  102. package/_vendor/canvas-core/tools/stateNode.d.ts +30 -0
  103. package/_vendor/canvas-core/tools/toolManager.d.ts +24 -0
  104. package/_vendor/canvas-core/utils/equality.d.ts +9 -0
  105. package/_vendor/canvas-extension-contracts/contributions.d.ts +92 -0
  106. package/_vendor/canvas-extension-contracts/index.d.ts +6 -0
  107. package/_vendor/canvas-extension-contracts/operations.d.ts +131 -0
  108. package/_vendor/canvas-extension-contracts/persistence.d.ts +16 -0
  109. package/_vendor/canvas-extension-contracts/plugin.d.ts +37 -0
  110. package/_vendor/canvas-extension-contracts/shape.d.ts +5 -0
  111. package/_vendor/canvas-extension-contracts/tokens.d.ts +12 -0
  112. package/_vendor/canvas-react/components/CanvasView.d.ts +3 -10
  113. package/_vendor/canvas-react/components/DefaultGrid.d.ts +1 -0
  114. package/_vendor/canvas-react/components/canvasKeyboardEvents.d.ts +2 -2
  115. package/_vendor/canvas-react/components/index.d.ts +1 -0
  116. package/_vendor/canvas-react/components/shape-layer/ShapeClipStack.d.ts +11 -0
  117. package/_vendor/canvas-react/components/shape-layer/ShapeDecorations.d.ts +1 -0
  118. package/_vendor/canvas-react/components/shape-layer/ShapeForegroundItem.d.ts +5 -0
  119. package/_vendor/canvas-react/components/shape-layer/ShapeItem.d.ts +5 -0
  120. package/_vendor/canvas-react/components/shape-layer/ShapeRenderList.d.ts +1 -0
  121. package/_vendor/canvas-react/components/shape-layer/ShapeRenderer.d.ts +12 -0
  122. package/_vendor/canvas-react/components/shape-layer/shapeFrame.d.ts +11 -0
  123. package/_vendor/canvas-react/components/useCanvasDomEvents.d.ts +2 -2
  124. package/_vendor/canvas-react/dom.d.ts +1 -1
  125. package/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +33 -0
  126. package/_vendor/canvas-react/host/canvasRenderBindings.d.ts +21 -0
  127. package/_vendor/canvas-react/host/canvasRenderBindingsContext.d.ts +5 -0
  128. package/_vendor/canvas-react/host/canvasRenderPlugin.d.ts +3 -12
  129. package/_vendor/canvas-react/host/index.d.ts +6 -7
  130. package/_vendor/canvas-react/index.d.ts +1 -1
  131. package/_vendor/signals/atom.d.ts +7 -5
  132. package/_vendor/signals/computed.d.ts +10 -8
  133. package/_vendor/signals/core.d.ts +32 -15
  134. package/_vendor/signals/effect.d.ts +2 -22
  135. package/_vendor/signals/index.d.ts +6 -7
  136. package/_vendor/signals/types.d.ts +14 -7
  137. package/_vendor/store/diff.d.ts +1 -1
  138. package/_vendor/store/history.d.ts +6 -21
  139. package/_vendor/store/index.d.ts +4 -4
  140. package/_vendor/store/store.d.ts +19 -17
  141. package/browser/indexedDb.d.ts +0 -4
  142. package/browser/persistence.d.ts +3 -3
  143. package/browser/persistenceFlushEvents.d.ts +2 -0
  144. package/chrome/floating/CanvasKitFloatingContent.d.ts +10 -0
  145. package/chrome/floating/CanvasKitFloatingPortal.d.ts +1 -0
  146. package/chrome/floating/useCanvasKitFloatingPosition.d.ts +5 -3
  147. package/chrome/toolbar/FloatingSelectionToolbarPageSpace.d.ts +7 -3
  148. package/host-VhUj_Gf6.mjs +48 -0
  149. package/index.css +1 -1
  150. package/index.d.ts +16 -47
  151. package/index.mjs +6 -88
  152. package/package.json +8 -15
  153. package/plugin-runtime.d.ts +3 -0
  154. package/plugin-runtime.mjs +1 -0
  155. package/react/CanvasKitContext.d.ts +8 -0
  156. package/react/CanvasKitRoot.d.ts +2 -11
  157. package/react/canvasActions.d.ts +3 -0
  158. package/react/canvasKitRootContracts.d.ts +19 -0
  159. package/react/host/CanvasKitCanvasHost.d.ts +7 -0
  160. package/react/host/import/CanvasImportHost.d.ts +13 -0
  161. package/react/host/keyboard/useCanvasKeyboardShortcuts.d.ts +8 -0
  162. package/react/reportCanvasHostError.d.ts +1 -0
  163. package/react/useCanvasKitRootRuntime.d.ts +12 -0
  164. package/runtime/activateCanvasPlugins.d.ts +16 -0
  165. package/runtime/canvasExportController.d.ts +11 -0
  166. package/runtime/canvasKit.d.ts +3 -0
  167. package/runtime/canvasKitContracts.d.ts +208 -0
  168. package/runtime/canvasKitRootRuntime.d.ts +17 -0
  169. package/runtime/canvasPluginGraph.d.ts +5 -11
  170. package/runtime/canvasRuntimeInitialization.d.ts +12 -0
  171. package/runtime/canvasRuntimeOwner.d.ts +16 -0
  172. package/runtime/createCanvasKitEditor.d.ts +1 -0
  173. package/runtime/facade/canvasProductData.d.ts +14 -0
  174. package/runtime/facade/canvasReadable.d.ts +13 -0
  175. package/runtime/facade/createCanvasKitFacade.d.ts +17 -0
  176. package/runtime/facade/layerTree.d.ts +12 -0
  177. package/runtime/persistenceCoordinator.d.ts +22 -5
  178. package/runtime/registries/productApiRegistry.d.ts +12 -3
  179. package/_vendor/canvas-core/editor/bindingReactionScope.d.ts +0 -7
  180. package/_vendor/canvas-core/editor/canvasPanInteraction.d.ts +0 -2
  181. package/_vendor/canvas-core/editor/createEditorWithPlugins.d.ts +0 -6
  182. package/_vendor/canvas-core/editor/editorComputedHelpers.d.ts +0 -24
  183. package/_vendor/canvas-core/editor/editorSelectionTransforms.d.ts +0 -6
  184. package/_vendor/canvas-core/editor/historyManager.d.ts +0 -36
  185. package/_vendor/canvas-core/editor/index.d.ts +0 -11
  186. package/_vendor/canvas-core/editor/managers/bindingManager.d.ts +0 -27
  187. package/_vendor/canvas-core/editor/managers/clipboardManager.d.ts +0 -14
  188. package/_vendor/canvas-core/editor/managers/documentSnapshotManager.d.ts +0 -28
  189. package/_vendor/canvas-core/editor/managers/queryManager.d.ts +0 -102
  190. package/_vendor/canvas-core/editor/managers/queryState.d.ts +0 -18
  191. package/_vendor/canvas-core/editor/managers/selectionLayoutManager.d.ts +0 -34
  192. package/_vendor/canvas-core/editor/managers/selectionManager.d.ts +0 -21
  193. package/_vendor/canvas-core/editor/managers/selectionOverlayManager.d.ts +0 -25
  194. package/_vendor/canvas-core/editor/managers/shapeGeometryManager.d.ts +0 -43
  195. package/_vendor/canvas-core/editor/managers/shapeHierarchyManager.d.ts +0 -63
  196. package/_vendor/canvas-core/editor/managers/shapeReparenting.d.ts +0 -7
  197. package/_vendor/canvas-core/editor/managers/shortcutManager.d.ts +0 -56
  198. package/_vendor/canvas-core/editor/managers/sideEffectManager.d.ts +0 -23
  199. package/_vendor/canvas-core/editor/managers/toolManager.d.ts +0 -24
  200. package/_vendor/canvas-core/editor/selectionHandleInteractions.d.ts +0 -11
  201. package/_vendor/canvas-core/editor/selectionOverlay.d.ts +0 -35
  202. package/_vendor/canvas-core/editor/stateNode.d.ts +0 -31
  203. package/_vendor/canvas-core/shapes/capabilities.d.ts +0 -25
  204. package/_vendor/canvas-core/tools/index.d.ts +0 -2
  205. package/_vendor/canvas-plugin-sdk/capability.d.ts +0 -10
  206. package/_vendor/canvas-plugin-sdk/index.d.ts +0 -3
  207. package/_vendor/canvas-plugin-sdk/plugin.d.ts +0 -29
  208. package/_vendor/canvas-plugin-sdk/setupExtension.d.ts +0 -5
  209. package/_vendor/canvas-product-contracts/actionRegistry.d.ts +0 -4
  210. package/_vendor/canvas-product-contracts/actions.d.ts +0 -44
  211. package/_vendor/canvas-product-contracts/capability.d.ts +0 -8
  212. package/_vendor/canvas-product-contracts/chrome.d.ts +0 -53
  213. package/_vendor/canvas-product-contracts/chromeRegistry.d.ts +0 -9
  214. package/_vendor/canvas-product-contracts/contextMenu.d.ts +0 -63
  215. package/_vendor/canvas-product-contracts/contextMenuRegistry.d.ts +0 -4
  216. package/_vendor/canvas-product-contracts/exportRegistry.d.ts +0 -6
  217. package/_vendor/canvas-product-contracts/exports.d.ts +0 -27
  218. package/_vendor/canvas-product-contracts/importRegistry.d.ts +0 -7
  219. package/_vendor/canvas-product-contracts/imports.d.ts +0 -39
  220. package/_vendor/canvas-product-contracts/index.d.ts +0 -15
  221. package/_vendor/canvas-product-contracts/productApi.d.ts +0 -29
  222. package/_vendor/canvas-product-contracts/services.d.ts +0 -21
  223. package/_vendor/canvas-product-contracts/toolbar.d.ts +0 -146
  224. package/_vendor/canvas-product-contracts/toolbarRegistry.d.ts +0 -9
  225. package/_vendor/canvas-react/host/canvasOverlayRegistryContext.d.ts +0 -3
  226. package/_vendor/canvas-react/host/canvasRenderRuntime.d.ts +0 -13
  227. package/_vendor/canvas-react/host/canvasRendererRegistryContext.d.ts +0 -3
  228. package/_vendor/canvas-react/host/domEventGuards.d.ts +0 -11
  229. package/_vendor/canvas-react/host/overlayRegistry.d.ts +0 -18
  230. package/_vendor/canvas-react/host/rendererRegistry.d.ts +0 -15
  231. package/_vendor/plugin-arrow/api.d.ts +0 -33
  232. package/_vendor/plugin-arrow/arrowBindingAnchors.d.ts +0 -5
  233. package/_vendor/plugin-arrow/arrowBindingGeometry.d.ts +0 -28
  234. package/_vendor/plugin-arrow/arrowBindingTargets.d.ts +0 -3
  235. package/_vendor/plugin-arrow/arrowBindingUtil.d.ts +0 -27
  236. package/_vendor/plugin-arrow/arrowGeometry.d.ts +0 -77
  237. package/_vendor/plugin-arrow/arrowHeadGeometry.d.ts +0 -8
  238. package/_vendor/plugin-arrow/arrowShapeUtil.d.ts +0 -25
  239. package/_vendor/plugin-arrow/arrowTerminalBindingResolver.d.ts +0 -20
  240. package/_vendor/plugin-arrow/arrowTerminalCommands.d.ts +0 -13
  241. package/_vendor/plugin-arrow/arrowTool.d.ts +0 -4
  242. package/_vendor/plugin-arrow/canvasRender.d.ts +0 -2
  243. package/_vendor/plugin-arrow/editorRuntime.d.ts +0 -7
  244. package/_vendor/plugin-arrow/feature.d.ts +0 -2
  245. package/_vendor/plugin-arrow/index.d.ts +0 -15
  246. package/_vendor/plugin-arrow/productRuntime.d.ts +0 -2
  247. package/_vendor/plugin-arrow/selectionHandleInteractions.d.ts +0 -3
  248. package/_vendor/plugin-arrow/types.d.ts +0 -31
  249. package/_vendor/plugin-draw/DrawShapeRenderer.d.ts +0 -13
  250. package/_vendor/plugin-draw/canvasRender.d.ts +0 -2
  251. package/_vendor/plugin-draw/drawGeometry.d.ts +0 -42
  252. package/_vendor/plugin-draw/drawHitTest.d.ts +0 -11
  253. package/_vendor/plugin-draw/drawInterpolation.d.ts +0 -5
  254. package/_vendor/plugin-draw/drawPath.d.ts +0 -43
  255. package/_vendor/plugin-draw/drawSegments.d.ts +0 -11
  256. package/_vendor/plugin-draw/drawSelectionTransform.d.ts +0 -18
  257. package/_vendor/plugin-draw/drawShapeGeometry.d.ts +0 -33
  258. package/_vendor/plugin-draw/drawShapeUtil.d.ts +0 -22
  259. package/_vendor/plugin-draw/drawStrokeGeometry.d.ts +0 -17
  260. package/_vendor/plugin-draw/drawTool.d.ts +0 -6
  261. package/_vendor/plugin-draw/editorRuntime.d.ts +0 -7
  262. package/_vendor/plugin-draw/feature.d.ts +0 -2
  263. package/_vendor/plugin-draw/index.d.ts +0 -14
  264. package/_vendor/plugin-draw/productRuntime.d.ts +0 -2
  265. package/_vendor/plugin-draw/types.d.ts +0 -23
  266. package/_vendor/plugin-eraser/canvasRender.d.ts +0 -2
  267. package/_vendor/plugin-eraser/editorRuntime.d.ts +0 -2
  268. package/_vendor/plugin-eraser/eraserRuntime.d.ts +0 -12
  269. package/_vendor/plugin-eraser/eraserTool.d.ts +0 -5
  270. package/_vendor/plugin-eraser/feature.d.ts +0 -2
  271. package/_vendor/plugin-eraser/index.d.ts +0 -6
  272. package/_vendor/plugin-eraser/productRuntime.d.ts +0 -2
  273. package/_vendor/plugin-frame/api.d.ts +0 -19
  274. package/_vendor/plugin-frame/canvasRender.d.ts +0 -9
  275. package/_vendor/plugin-frame/editorRuntime.d.ts +0 -7
  276. package/_vendor/plugin-frame/feature.d.ts +0 -2
  277. package/_vendor/plugin-frame/frameShapeUtil.d.ts +0 -35
  278. package/_vendor/plugin-frame/frameTool.d.ts +0 -6
  279. package/_vendor/plugin-frame/index.d.ts +0 -9
  280. package/_vendor/plugin-frame/productRuntime.d.ts +0 -2
  281. package/_vendor/plugin-geo/api.d.ts +0 -27
  282. package/_vendor/plugin-geo/canvasRender.d.ts +0 -13
  283. package/_vendor/plugin-geo/editorRuntime.d.ts +0 -7
  284. package/_vendor/plugin-geo/feature.d.ts +0 -2
  285. package/_vendor/plugin-geo/geoGeometry.d.ts +0 -24
  286. package/_vendor/plugin-geo/geoShapeUtil.d.ts +0 -14
  287. package/_vendor/plugin-geo/geoStrokeStyle.d.ts +0 -2
  288. package/_vendor/plugin-geo/geoTools.d.ts +0 -27
  289. package/_vendor/plugin-geo/index.d.ts +0 -10
  290. package/_vendor/plugin-geo/productRuntime.d.ts +0 -2
  291. package/_vendor/plugin-geo/types.d.ts +0 -22
  292. package/_vendor/plugin-group/canvasRender.d.ts +0 -9
  293. package/_vendor/plugin-group/editorRuntime.d.ts +0 -7
  294. package/_vendor/plugin-group/feature.d.ts +0 -2
  295. package/_vendor/plugin-group/groupContributions.d.ts +0 -7
  296. package/_vendor/plugin-group/groupShapeUtil.d.ts +0 -35
  297. package/_vendor/plugin-group/index.d.ts +0 -7
  298. package/_vendor/plugin-group/productRuntime.d.ts +0 -2
  299. package/_vendor/plugin-image/actionIds.d.ts +0 -9
  300. package/_vendor/plugin-image/canvasRender.d.ts +0 -2
  301. package/_vendor/plugin-image/cornerRadius.d.ts +0 -6
  302. package/_vendor/plugin-image/crop.d.ts +0 -112
  303. package/_vendor/plugin-image/cropInteractions.d.ts +0 -3
  304. package/_vendor/plugin-image/cropRuntime.d.ts +0 -2
  305. package/_vendor/plugin-image/cropSession.d.ts +0 -6
  306. package/_vendor/plugin-image/editorRuntime.d.ts +0 -3
  307. package/_vendor/plugin-image/feature.d.ts +0 -2
  308. package/_vendor/plugin-image/imageHostActionContract.d.ts +0 -2
  309. package/_vendor/plugin-image/imageShapeUtil.d.ts +0 -13
  310. package/_vendor/plugin-image/imageSvgExporter.d.ts +0 -6
  311. package/_vendor/plugin-image/index.d.ts +0 -13
  312. package/_vendor/plugin-image/productRuntime.d.ts +0 -4
  313. package/_vendor/plugin-image/runtimeShared.d.ts +0 -5
  314. package/_vendor/plugin-image/smudge.d.ts +0 -67
  315. package/_vendor/plugin-image/smudgeInteractions.d.ts +0 -2
  316. package/_vendor/plugin-image/smudgeRuntime.d.ts +0 -2
  317. package/_vendor/plugin-image/styleRuntime.d.ts +0 -22
  318. package/_vendor/plugin-image/toolbarRuntime.d.ts +0 -3
  319. package/_vendor/plugin-image/types.d.ts +0 -53
  320. package/_vendor/plugin-laser/canvasRender.d.ts +0 -2
  321. package/_vendor/plugin-laser/editorRuntime.d.ts +0 -2
  322. package/_vendor/plugin-laser/feature.d.ts +0 -2
  323. package/_vendor/plugin-laser/index.d.ts +0 -6
  324. package/_vendor/plugin-laser/laserRuntime.d.ts +0 -18
  325. package/_vendor/plugin-laser/laserTool.d.ts +0 -4
  326. package/_vendor/plugin-laser/productRuntime.d.ts +0 -2
  327. package/_vendor/plugin-path/PathDraftOverlay.d.ts +0 -1
  328. package/_vendor/plugin-path/PathEditInsertPreviewOverlay.d.ts +0 -1
  329. package/_vendor/plugin-path/PathShapeRenderer.d.ts +0 -15
  330. package/_vendor/plugin-path/canvasRender.d.ts +0 -2
  331. package/_vendor/plugin-path/editorRuntime.d.ts +0 -7
  332. package/_vendor/plugin-path/feature.d.ts +0 -2
  333. package/_vendor/plugin-path/index.d.ts +0 -8
  334. package/_vendor/plugin-path/pathBoolean.d.ts +0 -13
  335. package/_vendor/plugin-path/pathDraft.d.ts +0 -10
  336. package/_vendor/plugin-path/pathEditPreview.d.ts +0 -11
  337. package/_vendor/plugin-path/pathEditSelection.d.ts +0 -24
  338. package/_vendor/plugin-path/pathEditSnap.d.ts +0 -6
  339. package/_vendor/plugin-path/pathGeometry.d.ts +0 -74
  340. package/_vendor/plugin-path/pathHandles.d.ts +0 -18
  341. package/_vendor/plugin-path/pathHistory.d.ts +0 -13
  342. package/_vendor/plugin-path/pathInteractions.d.ts +0 -7
  343. package/_vendor/plugin-path/pathShapeUtil.d.ts +0 -30
  344. package/_vendor/plugin-path/pathSvg.d.ts +0 -3
  345. package/_vendor/plugin-path/pathTool.d.ts +0 -42
  346. package/_vendor/plugin-path/productRuntime.d.ts +0 -15
  347. package/_vendor/plugin-path/types.d.ts +0 -36
  348. package/_vendor/plugin-runtime-clipboard/capability.d.ts +0 -1
  349. package/_vendor/plugin-runtime-clipboard/clipboardActions.d.ts +0 -6
  350. package/_vendor/plugin-runtime-clipboard/clipboardService.d.ts +0 -10
  351. package/_vendor/plugin-runtime-clipboard/index.d.ts +0 -4
  352. package/_vendor/plugin-runtime-clipboard/plugin.d.ts +0 -1
  353. package/_vendor/plugin-runtime-export/blobDataUrl.d.ts +0 -1
  354. package/_vendor/plugin-runtime-export/canvasExportApi.d.ts +0 -43
  355. package/_vendor/plugin-runtime-export/index.d.ts +0 -8
  356. package/_vendor/plugin-runtime-export/plugin.d.ts +0 -5
  357. package/_vendor/plugin-runtime-export/pngExport.d.ts +0 -15
  358. package/_vendor/plugin-runtime-export/svgExport.d.ts +0 -40
  359. package/_vendor/plugin-text/api.d.ts +0 -20
  360. package/_vendor/plugin-text/canvasRender.d.ts +0 -8
  361. package/_vendor/plugin-text/capabilities.d.ts +0 -2
  362. package/_vendor/plugin-text/editorRuntime.d.ts +0 -5
  363. package/_vendor/plugin-text/feature.d.ts +0 -4
  364. package/_vendor/plugin-text/geoLabelBindingUtil.d.ts +0 -48
  365. package/_vendor/plugin-text/host/RichTextEditingBox.d.ts +0 -10
  366. package/_vendor/plugin-text/host/TiptapTextEditor.d.ts +0 -29
  367. package/_vendor/plugin-text/host/initialTextBackground.d.ts +0 -2
  368. package/_vendor/plugin-text/host/richTextRendering.d.ts +0 -10
  369. package/_vendor/plugin-text/host/textDomSelection.d.ts +0 -7
  370. package/_vendor/plugin-text/host/textEditingBoxStyle.d.ts +0 -4
  371. package/_vendor/plugin-text/host/textEntryFocus.d.ts +0 -23
  372. package/_vendor/plugin-text/host/textFontLoader.d.ts +0 -3
  373. package/_vendor/plugin-text/host/textFormattingApi.d.ts +0 -16
  374. package/_vendor/plugin-text/host/textMeasurement.d.ts +0 -21
  375. package/_vendor/plugin-text/host/textMeasurementSync.d.ts +0 -11
  376. package/_vendor/plugin-text/host/textRangeSelection.d.ts +0 -14
  377. package/_vendor/plugin-text/host/textShapeRendererRuntime.d.ts +0 -11
  378. package/_vendor/plugin-text/host/textShapeSync.d.ts +0 -19
  379. package/_vendor/plugin-text/host/tiptapTextEditorController.d.ts +0 -38
  380. package/_vendor/plugin-text/index.d.ts +0 -15
  381. package/_vendor/plugin-text/pathLabelBindingUtil.d.ts +0 -55
  382. package/_vendor/plugin-text/productRuntime.d.ts +0 -6
  383. package/_vendor/plugin-text/richTextLinks.d.ts +0 -3
  384. package/_vendor/plugin-text/richTextUtils.d.ts +0 -26
  385. package/_vendor/plugin-text/shapeWideTextFormatting.d.ts +0 -12
  386. package/_vendor/plugin-text/textFonts.d.ts +0 -49
  387. package/_vendor/plugin-text/textFormatting.d.ts +0 -47
  388. package/_vendor/plugin-text/textFormattingSession.d.ts +0 -6
  389. package/_vendor/plugin-text/textInteractions.d.ts +0 -2
  390. package/_vendor/plugin-text/textLabelHelpers.d.ts +0 -70
  391. package/_vendor/plugin-text/textLinkPopoverPresentation.d.ts +0 -18
  392. package/_vendor/plugin-text/textShapeHelpers.d.ts +0 -21
  393. package/_vendor/plugin-text/textShapeSvgExporter.d.ts +0 -9
  394. package/_vendor/plugin-text/textShapeUtil.d.ts +0 -24
  395. package/_vendor/plugin-text/textStyle.d.ts +0 -18
  396. package/_vendor/plugin-text/textTool.d.ts +0 -4
  397. package/_vendor/plugin-text/textTypes.d.ts +0 -29
  398. package/canvasKitTools.d.ts +0 -3
  399. package/chrome/contextMenuRuntime.d.ts +0 -7
  400. package/chrome/toolbar/mergeToolbarGroups.d.ts +0 -8
  401. package/chrome/toolbar/toolbarLabels.d.ts +0 -8
  402. package/chrome/toolbar/useToolbarSurfaces.d.ts +0 -21
  403. package/chrome/types.d.ts +0 -71
  404. package/chrome/useCanvasKitChromeContext.d.ts +0 -18
  405. package/chrome/useCanvasKitLayerTree.d.ts +0 -6
  406. package/chrome/useChromeSurfaces.d.ts +0 -12
  407. package/chrome/useContextMenuSurface.d.ts +0 -12
  408. package/chrome/useHistoryControls.d.ts +0 -12
  409. package/chrome/usePageControls.d.ts +0 -16
  410. package/chrome/useZoomControls.d.ts +0 -13
  411. package/commands/command.d.ts +0 -11
  412. package/commands/commandTokens.d.ts +0 -61
  413. package/commands/documentCommands.d.ts +0 -2
  414. package/commands/historyCommands.d.ts +0 -3
  415. package/commands/index.d.ts +0 -11
  416. package/commands/layerCommands.d.ts +0 -20
  417. package/commands/pageCommands.d.ts +0 -12
  418. package/commands/selectionCommands.d.ts +0 -12
  419. package/commands/shapeCommands.d.ts +0 -8
  420. package/commands/toolCommands.d.ts +0 -2
  421. package/commands/viewCommands.d.ts +0 -10
  422. package/contracts/canvasProductControllerContracts.d.ts +0 -32
  423. package/controller/canvasProductController.d.ts +0 -174
  424. package/controller/index.d.ts +0 -3
  425. package/controller/layerTree.d.ts +0 -10
  426. package/plugins/host/image/api/imageHostApi.d.ts +0 -11
  427. package/plugins/host/image/api/imageHostApiContract.d.ts +0 -60
  428. package/plugins/host/image/asset/imageAssetService.d.ts +0 -11
  429. package/plugins/host/image/asset/imageBlobStore.d.ts +0 -31
  430. package/plugins/host/image/asset/imageFileHelpers.d.ts +0 -43
  431. package/plugins/host/image/asset/svgImageAssetInliner.d.ts +0 -3
  432. package/plugins/host/image/import/ImageImportController.d.ts +0 -11
  433. package/plugins/host/image/index.d.ts +0 -15
  434. package/plugins/host/image/plugin.d.ts +0 -1
  435. package/plugins/host/image/smudge/imageSmudgeHostActions.d.ts +0 -10
  436. package/plugins/host/image/toolbar/imageHostActions.d.ts +0 -63
  437. package/plugins/host/image/toolbar/imageToolbarHostBridge.d.ts +0 -14
  438. package/plugins/host/text/link/TextLinkHoverPopover.d.ts +0 -6
  439. package/plugins/host/text/textHostPlugin.d.ts +0 -5
  440. package/plugins/host/text/textSvgAssetInliner.d.ts +0 -3
  441. package/plugins/host/text/textSvgAssetPlugin.d.ts +0 -2
  442. package/plugins/runtime/import-host/CanvasImportHost.d.ts +0 -4
  443. package/plugins/runtime/import-host/capability.d.ts +0 -1
  444. package/plugins/runtime/import-host/index.d.ts +0 -2
  445. package/plugins/runtime/import-host/plugin.d.ts +0 -1
  446. package/plugins/runtime/keyboard-shortcuts/index.d.ts +0 -1
  447. package/plugins/runtime/keyboard-shortcuts/plugin.d.ts +0 -1
  448. package/plugins/runtime/keyboard-shortcuts/useCanvasKeyboardShortcuts.d.ts +0 -6
  449. package/plugins/runtime/tool-actions/capability.d.ts +0 -1
  450. package/plugins/runtime/tool-actions/index.d.ts +0 -2
  451. package/plugins/runtime/tool-actions/plugin.d.ts +0 -1
  452. package/plugins/runtime/tool-actions/toolActions.d.ts +0 -2
  453. package/plugins/standard/clipboard/chrome.d.ts +0 -2
  454. package/plugins/standard/clipboard/contextMenu.d.ts +0 -2
  455. package/plugins/standard/clipboard/plugin.d.ts +0 -1
  456. package/plugins/standard/clipboard/shortcuts.d.ts +0 -5
  457. package/plugins/standard/createStandardCanvasKitPlugins.d.ts +0 -15
  458. package/plugins/standard/selection/actions.d.ts +0 -21
  459. package/plugins/standard/selection/chrome.d.ts +0 -2
  460. package/plugins/standard/selection/contextMenu.d.ts +0 -2
  461. package/plugins/standard/selection/plugin.d.ts +0 -1
  462. package/plugins/standard/selection/toolbar.d.ts +0 -2
  463. package/plugins/standard/tool-ui/contextMenu.d.ts +0 -2
  464. package/plugins/standard/tool-ui/plugin.d.ts +0 -1
  465. package/plugins/standard/tool-ui/toolbar.d.ts +0 -2
  466. package/plugins/standard/view/actions.d.ts +0 -5
  467. package/plugins/standard/view/chrome.d.ts +0 -2
  468. package/plugins/standard/view/contextMenu.d.ts +0 -2
  469. package/plugins/standard/view/plugin.d.ts +0 -1
  470. package/react/useCanvasKitRuntime.d.ts +0 -2
  471. package/react/useCanvasProductControllerLifecycle.d.ts +0 -9
  472. package/runtime/canvasKitActionContext.d.ts +0 -17
  473. package/runtime/canvasKitActionExecutor.d.ts +0 -12
  474. package/runtime/canvasKitCommandExecutor.d.ts +0 -22
  475. package/runtime/canvasKitPluginContracts.d.ts +0 -28
  476. package/runtime/canvasKitPluginLifecycle.d.ts +0 -32
  477. package/runtime/canvasKitPluginSetup.d.ts +0 -35
  478. package/runtime/canvasKitPluginUi.d.ts +0 -37
  479. package/runtime/canvasKitResourceScope.d.ts +0 -5
  480. package/runtime/canvasKitRuntime.d.ts +0 -59
  481. package/runtime/canvasKitRuntimeContracts.d.ts +0 -35
  482. package/runtime/createCanvasKitCommandAction.d.ts +0 -10
  483. package/runtime/persistenceContracts.d.ts +0 -12
  484. package/runtime/productAssetResolvers.d.ts +0 -29
  485. package/runtime/productServiceRegistry.d.ts +0 -8
  486. package/runtime/registries/actionRegistry.d.ts +0 -5
  487. package/runtime/registries/chromeRegistry.d.ts +0 -2
  488. package/runtime/registries/contextMenuRegistry.d.ts +0 -5
  489. package/runtime/registries/exportRegistry.d.ts +0 -2
  490. package/runtime/registries/importRegistry.d.ts +0 -2
  491. package/runtime/registries/index.d.ts +0 -7
  492. package/runtime/registries/toolbarRegistry.d.ts +0 -5
  493. /package/_vendor/canvas-core/editor/{selectionBindingSegments.d.ts → selection/selectionBindingSegments.d.ts} +0 -0
  494. /package/_vendor/canvas-core/editor/{managers → snapping}/snapSnapshotBuilder.d.ts +0 -0
  495. /package/_vendor/canvas-core/editor/{camera.d.ts → viewport/camera.d.ts} +0 -0
package/index.mjs CHANGED
@@ -1,88 +1,6 @@
1
- function e(){return lI}function t(){return++lI}function n(e){if(dI)return void e();const t={initialAtomValues:new Map};dI=t;try{e(),s(t.initialAtomValues.keys())}catch(n){for(const[e,i]of t.initialAtomValues)e.__unsafe__setWithoutNotify(i);throw n}finally{dI=null}}function i(e){cI={child:e,parentSet:new Set,below:cI}}function o(){if(!cI)throw new Error("Cannot stop dependency capture because no capture is active");const e=cI;return cI=e.below,e.parentSet}function r(e){cI&&(cI.parentSet.add(e),e.children.add(cI.child))}function s(e){function t(e){for(const o of e)if(!i.has(o))if(i.add(o),"effect"===o.type)n.add(o);else if("computed"===o.type){const e=o.source;e&&t(e.children)}}const n=new Set,i=new Set;for(const o of e)t(o.children);for(const o of n)o.notify()}function a(e,t,n){return new uI(e,t,n?.isEqual)}function l(e,t,n){return new pI(e,t,n?.isEqual)}function d(e){return{id:e}}function c(e={}){return{id:xI,typeName:"document",scope:"document",meta:{...e}}}function u(){return{id:II,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function h(e=II){return{id:vI,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...wI}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function p(e){return!!e&&"page"===e.typeName}function g(e){return!!e&&"document"===e.typeName}function f(e){return!!e&&"shape"===e.typeName}function m(e){return!!e&&"session"===e.typeName}function S(e){return!!e&&"binding"===e.typeName}function y(e){return!!e&&"asset"===e.typeName}function b(e){return"document"===e.scope}function x(e,t,n){return e.dist(((e,t,n)=>{const i=t.sub(e),o=n.sub(e),r=i.x*i.x+i.y*i.y;if(0===r)return e;const s=Math.max(0,Math.min(1,(o.x*i.x+o.y*i.y)/r));return new mI(e.x+i.x*s,e.y+i.y*s)})(t,n,e))}function I(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1}function v(e,t,n,i){return I(e,t,n,i)?0:Math.min(x(e,n,i),x(t,n,i),x(n,e,t),x(i,e,t))}function w(e){return e.length>=3&&e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y))}function P(e){const t=e.filter(w).flatMap(e=>e);return t.length>0?SI.FromPoints(t):null}function k(e,t){if(!w(t))return!1;let n=!1;for(let i=0;i<t.length;i+=1){const o=t[i],r=t[(i+t.length-1)%t.length];if(x(e,r,o)<=1e-8)return!0;o.y>e.y!=r.y>e.y&&e.x<(r.x-o.x)*(e.y-o.y)/(r.y-o.y)+o.x&&(n=!n)}return n}function C(e,t){return t.some(t=>k(e,t))}function T(e,t,n,i=0){if(!w(n))return!1;if(k(e,n)||k(t,n))return!0;for(let o=0;o<n.length;o+=1)if(v(e,t,n[o],n[(o+1)%n.length])<=Math.max(0,i))return!0;return!1}function M(e){return{kind:"theme",slot:e}}function E(e){return{kind:"custom",value:e}}function A(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&kI.includes(e.slot)}function B(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function R(e){return A(e)||B(e)}function L(e){return CI[e]}function $(e,t){return R(e)?e:t}function F(e){return"custom"===e.kind?e.value:`var(${L(e.slot)}, ${TI[e.slot]})`}function U(e,t){if("custom"===e.kind)return e.value;const n=L(e.slot),i=TI[e.slot];return t?.(n,i)??i}function O(e){if("custom"!==e.kind)return!1;const t=e.value.trim().toLowerCase();return"transparent"===t||/^#[0-9a-f]{6}00$/.test(t)}function D(e,t){return e===t||!(!e||!t)&&e.kind===t.kind&&("theme"===e.kind?e.slot===t.slot:e.value===t.value)}function z(e,t,n){const i=new Set;let o=n.parentId;for(;o.startsWith("shape:");){const n=o;if(n===t)return!0;if(i.has(n))return!1;i.add(n);const r=e.getShape(n);if(!r)return!1;o=r.parentId}return!1}function N(e,t,n){let i=e.computeShapeExportPageBounds(t);if(!q(i))return i;for(const o of((e,t,n)=>{const i=[];for(const o of H(e,t,n)){const t=_(e,o);t&&q(t)&&i.push(t)}return i})(e,t,n)){const e=Y(i,o);if(!e)return null;i=e}return i}function H(e,t,n){const i=[],o=new Set;let r=t.parentId;for(;r.startsWith("shape:");){const t=r;if(o.has(t))break;o.add(t);const s=e.getShape(t);if(!s)break;n.has(s.id)&&i.push(s),r=s.parentId}return i.reverse()}function W(e,t,n,i){if(n.has(t.id))return n.get(t.id)??null;const o=e.getShapeUtil(t),r=o.getChildExportClipLocalPolygons(t);if(!r||!P(r))return n.set(t.id,null),null;const s=e.computeShapeExportToPageTransform(t).toSvgString(),a=o.getChildExportClipLocalBounds(t),[l]=r,d=1===r.length&&l&&a&&((e,t)=>{const n=[new mI(t.minX,t.minY),new mI(t.maxX,t.minY),new mI(t.maxX,t.maxY),new mI(t.minX,t.maxY)];return e.length===n.length&&e.every((e,t)=>e.equals(n[t]))})(l,a)?[{tag:"rect",attrs:{x:a.x,y:a.y,width:a.w,height:a.h,transform:s}}]:r.map(e=>({tag:"path",attrs:{d:K(e),transform:s}})),c=i.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:d});return n.set(t.id,c),c}function _(e,t){const n=e.getShapeUtil(t).getChildExportClipLocalPolygons(t);if(!n||!P(n))return null;const i=e.computeShapeExportToPageTransform(t);return P(n.map(e=>e.map(e=>i.applyToPoint(e))))}function K(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).concat("Z").join(" ")}function Y(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return o<n||r<i?null:new SI(n,i,o-n,r-i)}function X(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}="${j("number"==typeof i?V(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(X).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${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 j(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function V(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function G(e){return e[EI]}function Z({editor:e,exporters:t,shapeIds:n}){const i=Array.from(n),o=e.getShapeExportTraversalIds(i),r=[];for(const c of o){const n=e.getShape(c);n?(Q(e.computeShapeExportPageBounds(n))||r.push({kind:"missing-bounds",id:n.id,canRepair:!1}),t.get(n.type)||r.push({kind:"missing-exporter",id:n.id,canRepair:!1})):r.push({kind:"missing-shape",id:c,canRepair:!1})}const s=new Set(o),a=new Set;for(const c of G(e).getAll().filter(S)){if(!s.has(c.fromId)&&!s.has(c.toId))continue;const t=e.getShape(c.fromId),n=e.getShape(c.toId);t&&n?e.bindings.canBind(c)?(e.bindings.getConflictingBindings(c).some(e=>a.has(e.id))&&r.push({kind:"duplicate-exclusive-binding",id:c.id,canRepair:!0}),a.add(c.id)):r.push({kind:"invalid-binding",id:c.id,canRepair:!0}):r.push({kind:"missing-binding-endpoint",id:c.id,canRepair:!0})}const l=r.filter(e=>e.canRepair).length,d=r.length-l;return{requestedShapeIds:i,issues:r,repairableIssueCount:l,fatalIssueCount:d,canExport:0===d}}function Q(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function J(e){return e.added.length>0||e.updated.length>0||e.removed.length>0}function ee(e){return e instanceof Map?new Map(e):new Map(Array.from(e,e=>[e.id,e]))}function te(e,t){const n=ee(e),i=ee(t),o={added:[],updated:[],removed:[]};for(const[r,s]of n){const e=i.get(r);e?e!==s&&o.updated.push({before:s,after:e}):o.removed.push(s)}for(const[r,s]of i)n.has(r)||o.added.push(s);return o}function ne(e){return{added:[...e.removed],updated:e.updated.map(e=>({before:e.after,after:e.before})),removed:[...e.added]}}function ie(e,t){const n=new Map,i=new Map,o=new Map;for(const s of e.added)n.set(s.id,s);for(const s of e.updated)i.set(s.after.id,s);for(const s of e.removed)o.set(s.id,s);for(const s of t.added){const e=o.get(s.id);if(e){o.delete(s.id),i.set(s.id,{before:e,after:s});continue}const t=i.get(s.id);t?i.set(s.id,{before:t.before,after:s}):n.set(s.id,s)}for(const s of t.updated){if(n.get(s.after.id)){n.set(s.after.id,s.after);continue}const e=o.get(s.after.id);if(e){o.delete(s.after.id),i.set(s.after.id,{before:e,after:s.after});continue}const t=i.get(s.after.id);i.set(s.after.id,t?{before:t.before,after:s.after}:{before:s.before,after:s.after})}for(const s of t.removed){if(n.get(s.id)){n.delete(s.id);continue}const e=i.get(s.id);e?(i.delete(s.id),o.set(s.id,e.before)):o.set(s.id,s)}const r={added:[],updated:[],removed:[]};for(const s of n.values())r.added.push(s);for(const s of i.values())s.before!==s.after&&r.updated.push(s);for(const s of o.values())r.removed.push(s);return r}function oe(e,t){return{id:e.id,forward:ie(e.forward,t),parentIds:e.parentIds}}function re(e,t){return{forward:t,inverse:ne(t),label:e}}function se(e){return void 0!==e&&e<0?-1:1}function ae(e,t){if(void 0===t)return e;const n=2*Math.PI;return e+Math.round((t-e)/n)*n}function le(e,t){const n=2*Math.PI,i=((e-t+Math.PI)%n+n)%n-Math.PI;return Math.abs(i)}function de(e,t,n={}){if(!(e=>[e.a,e.b,e.c,e.d,e.e,e.f].every(Number.isFinite))(e)||![t.x,t.y,t.w,t.h].every(Number.isFinite))return null;const i=Number.isFinite(n.epsilon)?Math.max(0,n.epsilon??0):1e-8,o=Math.hypot(e.a,e.b),r=Math.hypot(e.c,e.d),s=e.determinant(),a=({rotation:n,scaleX:i,scaleY:o})=>{const r=t.center,s=e.applyToPoint(r),a={x:s.x-r.x,y:s.y-r.y,rotation:n,scaleX:i,scaleY:o};return Object.values(a).every(Number.isFinite)?a:null},l=i*Math.max(1,o,r),d=o<=l,c=r<=l;if(d||c){if(d&&c)return a({rotation:n.preferredRotation??0,scaleX:0,scaleY:0});if(d){const t=r*se(n.preferredScaleYSign);return a({rotation:ae(Math.atan2(-e.c/t,e.d/t),n.preferredRotation),scaleX:0,scaleY:t})}const t=o*se(n.preferredScaleXSign);return a({rotation:ae(Math.atan2(e.b/t,e.a/t),n.preferredRotation),scaleX:t,scaleY:0})}if(Math.abs(e.a*e.c+e.b*e.d)/(o*r)>i)return null;if(Math.abs(s)<=i*o*r)return null;const u=Math.atan2(e.b,e.a),h=o,p=r*(s<0?-1:1),g=[{rotation:ae(u,n.preferredRotation),scaleX:h,scaleY:p},{rotation:ae(u+Math.PI,n.preferredRotation),scaleX:-h,scaleY:-p}],f=se(n.preferredScaleXSign),m=se(n.preferredScaleYSign),S=e=>{let t=0;return void 0!==n.preferredScaleXSign&&se(e.scaleX)===f&&(t+=1),void 0!==n.preferredScaleYSign&&se(e.scaleY)===m&&(t+=1),{signMatches:t,rotationDistance:void 0===n.preferredRotation?0:le(e.rotation,n.preferredRotation)}},y=S(g[0]),b=S(g[1]),x=b.signMatches>y.signMatches||b.signMatches===y.signMatches&&b.rotationDistance<y.rotationDistance?g[1]:g[0];return a({rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY})}function ce(e,t){return t.getExportBounds(e)}function ue(e,t,n=yI.Identity()){return n.compose(t.getLocalToPageTransform(e))}function he(e,t,n=yI.Identity()){const i=t.getLocalBounds(e).center,o=new mI(e.x+i.x,e.y+i.y),r=yI.Translate(o.x,o.y).compose(yI.Rotate(e.rotation)).compose(yI.Scale(e.scaleX,e.scaleY)).compose(yI.Translate(-o.x,-o.y));return n.compose(r)}function pe(e,t,n=yI.Identity()){return ue(e,t,n)}function ge(e,t,n=yI.Identity()){return ue(e,t,n).applyToPoint(t.getLocalBounds(e).center)}function fe(e,t,n,i=yI.Identity()){const o=he(e,n,i).tryInvert();if(o)return o.applyToPoint(t);const r=n.getLocalBounds(e).center,s=new mI(e.x+r.x,e.y+r.y),a=i.tryInvert();if(!a)return s;const l=a.applyToPoint(t).sub(s).rot(-e.rotation);return s.add(new mI(0===e.scaleX?0:l.x/e.scaleX,0===e.scaleY?0:l.y/e.scaleY))}function me(e,t,n=yI.Identity()){const i=he(e,t,n);return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(e=>i.applyToPoint(e))}function Se(e,t,n=yI.Identity()){const i=me(e,t,n),o=((e,t,n=yI.Identity())=>{const i=t.getLocalBounds(e),o=ue(e,t,n);return[new mI(i.minX,i.minY),new mI(i.maxX,i.minY),new mI(i.maxX,i.maxY),new mI(i.minX,i.maxY)].map(e=>o.applyToPoint(e))})(e,t,n);return{bounds:SI.FromPoints(i),center:ge(e,t,n),corners:o,outlineVertices:i}}function ye(e,t,n){return Math.abs(e-t)<=n*Math.max(1,Math.abs(e),Math.abs(t))}function be(e,t,n=1e-8){if(!t.canReceiveChildren(e))return null;const i=t.getChildTransformPolicy(e),o=Math.abs(e.scaleX),r=Math.abs(e.scaleY);return Number.isFinite(o)&&Number.isFinite(r)&&("isometry"===i?ye(o,1,n)&&ye(r,1,n):o>n&&r>n&&ye(o,r,n))?null:{shapeId:e.id,shapeType:e.type,policy:i,scaleX:e.scaleX,scaleY:e.scaleY}}function xe(e){return`Container shape ${e.shapeId} (${e.shapeType}) violates ${e.policy} child transform policy with scale (${e.scaleX}, ${e.scaleY})`}function Ie(e,t,n){const i=n.startsWith("shape:")?e.getShape(n):null,o=(i?e.computeShapeLocalToPageTransform(i):yI.Identity()).tryInvert();if(!o)return null;const r=e.computeShapeLocalToPageTransform(t);return de(o.compose(r),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})}function ve(e,t,n,...i){const o=LI.get(e),r=new Set(o?.suppressedBindingIds??RI),s=r.size;for(const a of t)r.add(a);if(r.size===s)return we(n);LI.set(e,{suppressedBindingIds:r});try{return we(n)}finally{o?LI.set(e,o):LI.delete(e)}}function we(e){const t=e();if(("object"==typeof(n=t)&&null!==n||"function"==typeof n)&&"function"==typeof n.then)throw new Error("Binding reaction scope callbacks must be synchronous");var n;return t}function Pe(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function ke(e,t,n){const i=e.getShape(t);if(!i)return;const o=e.getContainingParentIdForShapeRecord(i);o&&o!==i.parentId&&e.commands.reparentShapes({ids:[t],parentId:o},n)}function Ce(e,t,n){const i=n?.source??"user";ve(e,n?.suppressBindingIds??[],()=>((e,t,n)=>{G(e).atomic(()=>{const i=[],o=[];for(const n of t){const t=e.getShape(n.id);if(!t)continue;const r=n.x??t.x,s=n.y??t.y,a=n.rotation??t.rotation,l=n.scaleX??t.scaleX,d=n.scaleY??t.scaleY,c=void 0===n.opacity?t.opacity:Ae(n.opacity,t.opacity),u=n.isHidden??t.isHidden,h=n.isLocked??t.isLocked,p=n.parentId??t.parentId,g=n.index??t.index,f=void 0===n.meta?t.meta:{...n.meta};if(!n.props&&void 0===n.meta&&r===t.x&&s===t.y&&a===t.rotation&&l===t.scaleX&&d===t.scaleY&&c===t.opacity&&u===t.isHidden&&h===t.isLocked&&p===t.parentId&&g===t.index)continue;const m=e.shapeUtils.get(t.type),S={...t,x:r,y:s,rotation:a,scaleX:l,scaleY:d,opacity:c,isHidden:u,isLocked:h,parentId:p,index:g,props:n.props?m.validateProps({...t.props,...n.props}):t.props,meta:f};i.push(S),o.push({before:t,after:S})}0!==i.length&&(Te(e,i),G(e).put(i,n),o.some(({before:e,after:t})=>e.parentId!==t.parentId)&&Me(e,n),e.bindings.handleShapeChanges(o,n),((e,t,n)=>{const i=new Set,o=new Set;for(const s of t)$e(e,s.before,i),$e(e,s.after,i),s.before.parentId!==s.after.parentId&&s.before.parentId.startsWith("shape:")&&o.add(s.before.parentId),e.getShapeUtil(s.after).shouldResizeDescendants(s.after)&&i.add(s.after.id);const r=new Set;Ue(e,o,r,n),Be(e,i,n,r)})(e,o,n))},n)})(e,t,i))}function Te(e,t){const n=new Set;for(const r of t){if(n.has(r.id))throw new Error(`Duplicate shape id ${r.id}`);n.add(r.id)}const i=new Map(G(e).getAll().filter(f).map(e=>[e.id,e]));for(const r of t)i.set(r.id,r);for(const r of i.values()){const t=be(r,e.getShapeUtil(r));if(t)throw new Error(xe(t))}const o=new Map(t.map(e=>[e.id,e]));for(const r of i.values())r.parentId.startsWith("shape:")&&n.has(r.parentId)&&o.set(r.id,r);for(const r of o.values()){const t=new Set([r.id]);let n=r;for(;n.parentId.startsWith("shape:");){const o=n.parentId;if(t.has(o))throw new Error(`Shape parent cycle includes ${r.id}`);t.add(o);const s=i.get(o);if(!s)throw new Error(`Missing parent ${o} for shape ${n.id}`);if(!e.getShapeUtil(s).canReceiveChild(s,n))throw new Error(`Shape ${o} cannot receive shape ${n.id}`);n=s}if(!e.getPage(n.parentId))throw new Error(`Missing page parent ${n.parentId} for shape ${n.id}`)}}function Me(e,t){const n=e.getSessionRecord();let i=!1;const o={};for(const[r,s]of Object.entries(n.pageSelectedShapeIdsById)){const t=r,n=s??[],a=Array.from(new Set(n)).filter(n=>Ee(e,n)===t&&!e.isShapeHidden(n)),l=new Set(a),d=a.filter(t=>{let n=e.getShape(t);const i=new Set([t]);for(;n?.parentId.startsWith("shape:");){const t=n.parentId;if(i.has(t))return!0;if(l.has(t))return!1;i.add(t),n=e.getShape(t)}return!0});o[t]=d,d.length!==n.length&&(i=!0)}i&&e.updateSession({pageSelectedShapeIdsById:o},t)}function Ee(e,t){let n=e.getShape(t);const i=new Set;for(;n?.parentId.startsWith("shape:");){const t=n.parentId;if(i.has(t))return null;i.add(t),n=e.getShape(t)}return n&&e.getPage(n.parentId)?n.parentId:null}function Ae(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Be(e,t,n,i=new Set){const o=[...t].sort((t,n)=>Re(e,n)-Re(e,t));for(const r of o){if(i.has(r))continue;const t=e.getShape(r);if(!t)continue;const o=e.getShapeUtil(t);if(!o.shouldResizeDescendants(t))continue;const s=Le(e,t.id);if(0===s.length)continue;const a=s.flatMap(t=>e.getShapeUtil(t).getPositionedOutlineVertices(t).map(n=>he(t,e.getShapeUtil(t)).applyToPoint(n)));if(0===a.length)continue;const l=SI.FromPoints(a),d=o.getResizeToFitDescendantsProps(t,l);if(!d)continue;const c=o.validateProps(d),u={...t,props:c},h=de(o.getLocalToPageTransform(t).compose(yI.Translate(l.x,l.y)),o.getLocalBounds(u),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(!h)continue;const p=[...s.map(e=>({before:e,after:{...e,x:e.x-l.x,y:e.y-l.y}})),{before:t,after:{...t,...h,props:c}}].filter(({before:e,after:t})=>{return!((n=e).x===(i=t).x&&n.y===i.y&&n.rotation===i.rotation&&n.scaleX===i.scaleX&&n.scaleY===i.scaleY&&((e,t)=>{if(e===t)return!0;const n=Object.entries(e),i=Object.entries(t);return n.length===i.length&&n.every(([e,n])=>Object.is(n,t[e]))})(n.props,i.props));var n,i});0!==p.length&&(G(e).put(p.map(e=>e.after),n),e.bindings.handleShapeChanges(p,n))}}function Re(e,t){let n=0,i=e.getShape(t);const o=new Set;for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(o.has(t))break;o.add(t),n+=1,i=e.getShape(t)}return n}function Le(e,t){return G(e).getAll().filter(f).filter(e=>e.parentId===t).sort((e,t)=>e.index.localeCompare(t.index))}function $e(e,t,n){const i=new Set([t.id]);let o=t.parentId;for(;o.startsWith("shape:");){const t=e.getShape(o);if(!t||i.has(t.id))return;i.add(t.id),e.getShapeUtil(t).shouldResizeDescendants(t)&&n.add(t.id),o=t.parentId}}function Fe(e,t){const n=new Set;for(const i of t){const t=e.getShape(i);t&&$e(e,t,n)}return n}function Ue(e,t,n,i){const o=[],r=[...t].sort((t,n)=>e.getDescendantShapeIds(n).length-e.getDescendantShapeIds(t).length);for(let s=0;s<r.length;s+=1){const t=r[s];if(!t||n.has(t))continue;const a=e.getShape(t);if(!a)continue;const l=e.getShapeUtil(a).getMinimumChildCount(a);if(l<=0)continue;const d=Le(e,a.id).filter(e=>!n.has(e.id)),c=new Set(d.map(e=>e.id));if(new Set(d.map(t=>{const n=e.bindings.getShapeHierarchyRootId(t.id);return c.has(n)?n:t.id})).size>=l)continue;const u=Le(e,a.parentId).filter(e=>!n.has(e.id)).flatMap(e=>e.id===a.id?d.map(e=>e.id):[e.id]),h=new Map(u.map((t,n)=>[t,e.createShapeIndex(n+1)])),p=[];let g=!0;for(const n of d){if(!e.canUseShapeParent(a.parentId,n.id)){g=!1;break}const t=Ie(e,n,a.parentId);if(!t){g=!1;break}p.push({before:n,after:{...n,...t,parentId:a.parentId,index:h.get(n.id)??a.index}})}if(!g)continue;const f=new Set;$e(e,a,f);for(const e of f)r.push(e);const m=new Set(p.map(e=>e.after.id)),S=u.flatMap(t=>{if(m.has(t))return[];const n=e.getShape(t),i=h.get(t);return n&&i&&n.index!==i?[{before:n,after:{...n,index:i}}]:[]}),y=[...p,...S];y.length>0&&(G(e).put(y.map(e=>e.after),i),e.bindings.handleShapeChanges(y,i));const b=e.getSelectedShapeIds();if(b.includes(a.id)){const t=Array.from(new Set(p.map(t=>{const n=e.bindings.getShapeHierarchyRootId(t.after.id);return m.has(n)?n:t.after.id})));e.commands.setSelectedShapeIds(b.flatMap(e=>e===a.id?t:[e]),{source:i})}e.sideEffects.runBeforeDelete("shape",[a.id],i),G(e).remove([a.id],i),e.sideEffects.runAfterDelete("shape",[a.id],i),n.add(a.id),o.push(a.id)}return o}function Oe(e,t,n){const i=((e,t)=>{const n=Array.from(new Set(t.ids)).map(t=>e.getShape(t)).filter(e=>!!e&&e.parentId!==t.parentId);if(0===n.length)return[];const i=Le(e,t.parentId).reduce((e,t)=>{const n=Number.parseInt(t.index,10);return Number.isFinite(n)?Math.max(e,n):e},0),o=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,r=new Map;for(const s of n){if(!e.canUseShapeParent(t.parentId,s.id))return null;const n=Ie(e,s,t.parentId);if(!n)return null;r.set(s.id,n)}return n.map((n,s)=>{const a=o?e.getShapeUtil(o).getChildPlacementMeta(o,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+s+1),...r.get(n.id),meta:a===n.meta?void 0:a}})})(e,t);return!!i&&(0===i.length||Ce(e,i,n),!0)}function De(e,t,n){const i=n?.source??"user",o=e.getShapeIdsIncludingDescendants(t),r=Fe(e,o),s=new Set(o),a=e.getUnreferencedAssetIdsAfterShapeDelete(o);e.prepareShapeIdsForRemoval(o,i),G(e).atomic(()=>{e.sideEffects.runBeforeDelete("shape",o,i),G(e).remove(o,i),a.length>0&&G(e).remove(a,i),Ue(e,r,s,i),Be(e,r,i,s),e.sideEffects.runAfterDelete("shape",o,i)},i)}function ze(e,t){return e.bindings.canBind(t)}function Ne(e,t,n){for(const i of t){const t=e.getShape(i);t?.parentId.startsWith("shape:")&&n.add(t.parentId)}}function He(e){return{added:[...e.added],updated:e.updated.filter(({before:e,after:t})=>!We(e,t)),removed:[...e.removed]}}function We(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>We(e,t[n]));if("object"!=typeof e||"object"!=typeof t)return!1;const n=e,i=t,o=Object.keys(n),r=Object.keys(i);return o.length===r.length&&o.every(e=>Object.prototype.hasOwnProperty.call(i,e)&&We(n[e],i[e]))}function _e(e){return JSON.parse(JSON.stringify(e))}function Ke(e){return JSON.parse(JSON.stringify(e))}function Ye(e){const t=globalThis.reportError;"function"==typeof t&&t(e)}function Xe(e,t,n){return qe([e],t,n).get(e)??e}function qe(e,t,n){const i=[...t].sort((e,t)=>e.id.localeCompare(t.id)),o=new Map;for(const s of i){const e=s.fromId===s.toId?[s.fromId]:[s.fromId,s.toId];for(const t of e){if(o.has(t))continue;const e=n(s).getShapeHierarchyRootId?.(s,t);e&&e!==t&&o.set(t,e)}}const r=new Map;for(const s of e){if(r.has(s))continue;const e=new Set([s]);let t=s;for(;;){const n=o.get(t);if(!n){r.set(s,t);break}if(e.has(n)){r.set(s,s);break}e.add(n),t=n}}return r}function je({before:e,after:t}){return e.parentId!==t.parentId||e.x!==t.x||e.y!==t.y||e.rotation!==t.rotation||e.scaleX!==t.scaleX||e.scaleY!==t.scaleY||e.props!==t.props}function Ve(e){return Math.min(8,Math.max(.1,e))}function Ge(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 Ze(e,t){return e.count===t.count&&e.singleShapeType===t.singleShapeType&&e.commonShapeType===t.commonShapeType&&e.canFlipSelection===t.canFlipSelection&&e.hasPointHandleSelection===t.hasPointHandleSelection&&e.hasFrameSelection===t.hasFrameSelection&&e.isMixedFrameAndPointHandleSelection===t.isMixedFrameAndPointHandleSelection&&e.canDragPointHandles===t.canDragPointHandles&&e.hasSelectionRotation===t.hasSelectionRotation&&e.hasMixedSelectionRotation===t.hasMixedSelectionRotation&&e.canResetSelectionRotation===t.canResetSelectionRotation}function Qe(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 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],o=t[n];if(!i||!o||i.x!==o.x||i.y!==o.y)return!1}return!0}function tt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!et(i,o))return!1}return!0}function nt(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 it(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 ot(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 rt(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 st(e,t,n){const i=new Set([e.id]);let o=e.parentId;for(;o.startsWith("shape:");){const e=o;if(i.has(e))return null;i.add(e);const n=t.get(e);if(!n)return null;o=n.parentId}return n.has(o)?o:null}function at(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o)return!1;if(i.id!==o.id||i.shape!==o.shape||i.isSelected!==o.isSelected||!nt(i.bounds,o.bounds))return!1}return!0}function lt(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 dt(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function ct(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)=>ct(e,t[n]));const n=e,i=t,o=Object.keys(n),r=Object.keys(i);return o.length===r.length&&o.every(e=>Object.prototype.hasOwnProperty.call(i,e)&&ct(n[e],i[e]))}function ut(e){const t=(e=>{const t=new Set(e.getSelectedShapeIds());return 0===t.size?[]:e.getCurrentPageShapeIds().filter(e=>t.has(e)).filter(n=>!((e,t,n)=>{const i=new Set([t]);let o=e.getShape(t);for(;o?.parentId.startsWith("shape:");){const t=o.parentId;if(n.has(t))return!0;if(i.has(t))return!1;i.add(t),o=e.getShape(t)}return!1})(e,n,t))})(e);if(0===t.length)return null;const n=((e,t)=>{const n=((e,t)=>{const n=e.getShapeIdsIncludingDescendants(t),i=new Set(n);for(let o=0;o<n.length;o+=1){const t=n[o];if(t)for(const o of e.getBindingsForShape(t)){const t=e.getBindingUtil(o).getExportShapeIds?.(e,o);for(const o of t??[])for(const t of e.getShapeIdsIncludingDescendants([o]))i.has(t)||(i.add(t),n.push(t))}}return n})(e,t),i=new Set(n);return e.getCurrentPageShapeIds().filter(e=>i.has(e))})(e,t),i=new Set(n),o=new Set;for(const d of n){const t=e.getShape(d);if(!(!t||t.parentId.startsWith("shape:")&&i.has(t.parentId)||pt(e,t,i))){o.add(t.id);for(const n of e.getDescendantShapeIds(t.id))o.add(n)}}const r=n.filter(e=>!o.has(e)),s=new Set(r),a=r.map(t=>e.getShape(t)).filter(e=>!!e).flatMap(t=>{const n=pt(e,t,s);return n?[n]:[]});if(0===a.length)return null;const l=t.filter(e=>s.has(e));return 0===l.length?null:{type:"land/clipboard",version:2,source:{app:"land"},rootShapeIds:l,records:{shapes:a,bindings:gt(e,a,s),assets:ft(e,a)},bounds:mt(e,r)}}function ht(e,t){const{payload:n}=t;if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"land/clipboard"===t.type&&2===t.version&&!!t.records&&Array.isArray(t.rootShapeIds)&&Array.isArray(t.records.shapes)&&Array.isArray(t.records.bindings)&&Array.isArray(t.records.assets)})(n)||0===n.records.shapes.length)return[];const i=t.source??"user",o=e.getCurrentPageId(),r=(e=>{const t=e.payload.bounds;return e.pagePoint?e.pagePoint.sub(new mI(t.x+t.w/2,t.y+t.h/2)):e.offset??NI})(t),s=new Map,a=new Map,l=[],d=new Set(n.records.shapes.map(e=>e.id)),c=new Set(n.records.shapes.filter(e=>!e.parentId.startsWith("shape:")||!d.has(e.parentId)).map(e=>e.id));G(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=e.createAssetRecord({type:t.type,props:It(t.props),meta:It(t.meta)});return s.set(t.id,n.id),n});t.length>0&&e.commands.createAssetsFromRecords(t,{source:i});const l=n.records.shapes.map(t=>{const n=((e,t)=>xt(e,t))(t.props,s),i=c.has(t.id),l=e.createShapeRecord({type:t.type,x:t.x+(i?r.x:0),y:t.y+(i?r.y:0),props:n,parentId:o,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,meta:It(t.meta)});return a.set(t.id,l.id),{original:t,draft:l}}).map(({original:e,draft:t})=>({...t,parentId:St(e.parentId,a,o)}));l.length>0&&e.commands.createShapesFromRecords(l,{source:i});for(const o of n.records.bindings){const t=a.get(o.fromId),n=a.get(o.toId);t&&n&&e.commands.createBinding({type:o.type,fromId:t,toId:n,props:It(o.props),meta:It(o.meta)},{source:i})}},i);for(const u of n.rootShapeIds){const e=a.get(u);e&&l.push(e)}return l.length>0&&e.commands.setSelectedShapeIds(l,{source:i}),l}function pt(e,t,n){if(!e.getShapeUtil(t).canCopyToClipboard(t,{editor:e,copiedShapeIds:n}))return null;const i=vt(t);if(t.parentId.startsWith("shape:")&&n.has(t.parentId))return i;const o=e.computeShapeLocalBounds(t),r=de(e.computeShapeLocalToPageTransform(t),o,{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return r?{...i,parentId:e.getShapePageId(t.id)??i.parentId,...r}:null}function gt(e,t,n){const i=[],o=new Set;for(const r of t)for(const t of e.getBindingsForShape(r.id))o.has(t.id)||n.has(t.fromId)&&n.has(t.toId)&&(o.add(t.id),i.push(vt(t)));return i}function ft(e,t){const n=[],i=new Set;for(const o of t)for(const t of yt(o)){if(i.has(t))continue;const o=e.getAsset(t);o&&(i.add(t),n.push(vt(o)))}return n}function mt(e,t){const n=(e=>{if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,o=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),i=Math.max(i,r.maxX),o=Math.max(o,r.maxY);return new SI(t,n,i-t,o-n)})(t.map(t=>e.getShapePageBounds(t)).filter(e=>!!e))??new SI(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function St(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function yt(e){const t=[],n=new Set,i=dt(e);return i&&(n.add(i),t.push(i)),bt(e.props,n,t),t}function bt(e,t,n){if(wt(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)bt(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))bt(i,t,n)}function xt(e,t){if(wt(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>xt(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[i,o]of Object.entries(e))n[i]=xt(o,t);return n}function It(e){return vt(e)}function vt(e){if(Array.isArray(e))return e.map(vt);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=vt(i);return t}function wt(e){return"string"==typeof e&&e.startsWith("asset:")}function Pt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function kt(e,t){return"string"==typeof e?e:t}function Ct(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Tt(e,t){return"boolean"==typeof e?e:t}function Mt(e){return Pt(e)?e:{}}function Et(e){return Pt(e)?{x:Ct(e.x,wI.x),y:Ct(e.y,wI.y),z:Math.min(8,Math.max(.1,Ct(e.z,wI.z)))}:null}function At(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function Bt(e,t){if(!Pt(e))throw new WI(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=Ct(n,NaN),o="document"===t?3:1;if(i!==o)throw new WI(`Unsupported ${t} snapshot schema version: expected ${o}, received ${String(n)}`);if(!Array.isArray(e.records))throw new WI(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:i,records:e.records}}function Rt(e,t,n){const i=e.find(g)??c(),o=e.filter(e=>"page"===e.typeName),r=e.filter(e=>"shape"===e.typeName),s=e.filter(S),a=e.filter(y),l=(o.length>0?[...o].sort((e,t)=>e.index.localeCompare(t.index)):[u()]).map((e,t)=>({...e,index:String(t+1).padStart(4,"0")})),d=l[0]?.id??"page:default",h=new Set(l.map(e=>e.id)),p=[...r].sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),f=new Map(p.map(e=>[e.id,e])),m=new Map,b=new Set,x=p.map((e,n)=>{const i=(e=>{const n=m.get(e.id);if(n)return n;const i=[{stage:"enter",shape:e}];for(;i.length>0;){const e=i[i.length-1];if("waiting-for-parent"===e.stage){m.set(e.shape.id,e.parent.id),b.delete(e.shape.id),i.pop();continue}const n=e.shape;if(m.has(n.id)){i.pop();continue}if(b.add(n.id),n.parentId.startsWith("page:")){m.set(n.id,h.has(n.parentId)?n.parentId:d),b.delete(n.id),i.pop();continue}const o=f.get(n.parentId);o&&!b.has(o.id)&&t.get(o.type).canReceiveChild(o,n)?(i[i.length-1]={stage:"waiting-for-parent",shape:n,parent:o},m.has(o.id)||i.push({stage:"enter",shape:o})):(m.set(n.id,d),b.delete(n.id),i.pop())}return m.get(e.id)??d})(e),o={...e,parentId:i,index:e.index||String(n+1).padStart(6,"0")};return t.get(o.type).repairLoadedShape(o)??o});for(const c of x){const e=be(c,t.get(c.type));if(e)throw new WI(xe(e))}const I=((e,t,n,i)=>{const o=new Map(e.map(e=>[e.id,e])),r=t.filter(e=>{const t=o.get(e.fromId),n=o.get(e.toId);if(!t||!n)return!1;const r=i.get(e.type);return!!r.getShapeHierarchyRootId&&(r.canUseShapeHierarchy?.(e,{fromShape:t,toShape:n})??!1)});let s=!0;for(;s;){s=!1;for(const e of[...o.values()]){const t=n.get(e.type),a=t.getMinimumChildCount(e);if(a<=0)continue;const l=[...o.values()].filter(t=>t.parentId===e.id).sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),d=new Set(l.map(e=>e.id));if(new Set(l.map(e=>{const t=Xe(e.id,r,e=>i.get(e.type));return d.has(t)?t:e.id})).size>=a)continue;if(0===l.length){o.delete(e.id),s=!0;break}const c=[...o.values()].filter(t=>t.parentId===e.parentId).sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)).flatMap(t=>t.id===e.id?l.map(e=>e.id):[t.id]),u=new Map(c.map((e,t)=>[e,String(t+1).padStart(6,"0")])),h=t.getLocalToPageTransform(e),p=[];for(const i of l){if(e.parentId.startsWith("shape:")&&!Lt(o,n,e.parentId,i)){p.length=0;break}const t=n.get(i.type),r=de(h.compose(t.getLocalToPageTransform(i)),t.getLocalBounds(i),{preferredRotation:i.rotation,preferredScaleXSign:i.scaleX,preferredScaleYSign:i.scaleY});if(!r){p.length=0;break}p.push({...i,...r,parentId:e.parentId,index:u.get(i.id)??e.index})}if(p.length===l.length){for(const e of p)o.set(e.id,e);for(const e of c){const t=o.get(e),n=u.get(e);t&&n&&t.index!==n&&o.set(t.id,{...t,index:n})}o.delete(e.id),s=!0;break}}}return e.flatMap(e=>{const t=o.get(e.id);return t?[t]:[]})})(x,s,t,n),v=new Set(I.map(e=>e.id)),w=s.filter(e=>v.has(e.fromId)&&v.has(e.toId));return[i,...l,...a,...I,...w]}function Lt(e,t,n,i){const o=e.get(n);return!!o&&t.get(o.type).canReceiveChild(o,i)}function $t(e,t,n){const i=Bt(e,"document"),o=new Set,r=[];return i.records.forEach((e,i)=>{if(!Pt(e))throw new WI("Invalid document record: expected object");if("string"!=typeof e.id)throw new WI("Invalid document record id");if(o.has(e.id))throw new WI(`Duplicate document record id: ${e.id}`);if(o.add(e.id),"document"!==e.typeName)if("page"!==e.typeName)if("shape"!==e.typeName)if("binding"!==e.typeName){if("asset"!==e.typeName)throw new WI(`Unsupported document record type: ${String(e.typeName)}`);r.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new WI("Invalid asset record id");if("string"!=typeof e.type)throw new WI("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:Pt(e.props)?e.props:{},meta:Mt(e.meta)}})(e))}else r.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new WI("Invalid binding record id");if("string"!=typeof e.type)throw new WI("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new WI(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new WI(`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:Mt(e.meta)}})(e,n));else r.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new WI("Invalid shape record id");if("string"!=typeof e.type)throw new WI("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new WI(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:kt(e.index,String(n+1).padStart(6,"0")),x:Ct(e.x,0),y:Ct(e.y,0),rotation:Ct(e.rotation,0),scaleX:Ct(e.scaleX,1),scaleY:Ct(e.scaleY,1),opacity:Math.min(1,Math.max(0,Ct(e.opacity,1))),isHidden:Tt(e.isHidden,!1),isLocked:Tt(e.isLocked,!1),meta:Mt(e.meta),type:e.type,props:t.get(e.type).validateProps(e.props)}})(e,t,i));else r.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("page:"))throw new WI("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:kt(e.name,`Page ${t+1}`),index:kt(e.index,String(t+1).padStart(4,"0")),meta:Mt(e.meta)}})(e,i));else r.push((e=>{if("document:main"!==e.id)throw new WI("Invalid document metadata record id");return{id:xI,typeName:"document",scope:"document",meta:Mt(e.meta)}})(e))}),{schemaVersion:3,records:Rt(r,t,n)}}function Ft(e){const t=Bt(e,"session").records[0];if(!Pt(t))return{schemaVersion:1,records:[h()]};const n=h(),i="string"==typeof t.currentPageId&&t.currentPageId.startsWith("page:")?t.currentPageId:n.currentPageId,o=(e=>{if(!Pt(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Et(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),r=(e=>{if(!Pt(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,At(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:kt(t.activeToolId,n.activeToolId),isToolLocked:"boolean"==typeof t.isToolLocked?t.isToolLocked:n.isToolLocked,editingShapeId:null,shapeEditingSession:null,pageCameraById:Object.keys(o).length>0?o:n.pageCameraById,pageSelectedShapeIdsById:Object.keys(r).length>0?r:n.pageSelectedShapeIdsById,meta:Mt(t.meta)}]}}function Ut(){return mI.Zero()}function Ot(e,t,n){if(n<=0)return Ut();const i=t.x-e.x,o=t.y-e.y;return 0===i&&0===o?Ut():new mI(i/n,o/n)}function Dt(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function zt(e){return{...e,anchorPagePoint:e.anchorPagePoint.clone(),boundaryPagePoint:e.boundaryPagePoint.clone()}}function Nt(e,t){return e.terminal===t.terminal&&Je(e.anchorPagePoint,t.anchorPagePoint)&&Je(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function Ht(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!Nt(i,o))return!1}return!0}function Wt(e,t){return Nt(e,t)&&e.ownerShapeId===t.ownerShapeId&&(e.targetShapeId??null)===(t.targetShapeId??null)}function _t(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Kt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Yt(e,t,n){const i=e.get(t);if(!i)return!1;const o=i.indexOf(n);if(o<0)return!1;if(1===i.length)return e.delete(t),!0;const r=i.slice();return r.splice(o,1),e.set(t,r),!0}function Xt(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 qt(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function jt(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):qt(t,n)}function Vt(e,t,n,i,o){const r=e.get(t);if(!r)return e.set(t,[n.id]),!0;if(r.includes(n.id))return!1;const s=r.slice();return s.splice(((e,t,n,i)=>{for(let o=0;o<e.length;o+=1){const r=i(e[o]);if(r&&jt(n,t,r)<0)return o}return e.length})(r,n,i,o),0,n.id),e.set(t,s),!0}function Gt(e,t,n,i){const o=e.get(t);if(!o)return void e.set(t,[n.id]);if(o.includes(n.id))return;let r=o.length;for(let a=0;a<o.length;a+=1){const e=i(o[a]);if(void 0!==e&&e.localeCompare(n.index)>0){r=a;break}}const s=o.slice();s.splice(r,0,n.id),e.set(t,s)}function Zt(e,t,n){Yt(e,t,n)}function Qt(e){return f(e.before)&&f(e.after)}function Jt(e){return S(e.before)&&S(e.after)}function en(e,t){const n=de(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return n?{...t,...n}:null}function tn(e,t,n,i){const o=e.getShapeUtil(t),r={...n,x:i.x??n.x,y:i.y??n.y,rotation:i.rotation??n.rotation,scaleX:i.scaleX??n.scaleX,scaleY:i.scaleY??n.scaleY,props:i.props?o.validateProps({...n.props,...i.props}):n.props},s=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,a=(s?e.computeShapeLocalToPageTransform(s):yI.Identity()).tryInvert();if(!a)return null;const l=de(a.compose(o.getLocalToPageTransform(r)),o.getLocalBounds(r),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return l?{id:t.id,...l,props:i.props}:null}function nn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!Je(i,o))return!1}return!0}function on(e,t){return nn(e.outlineVertices,t.outlineVertices)&&nt(e.pageBounds,t.pageBounds)&&nt(e.frameBounds,t.frameBounds)&&e.rotation===t.rotation&&Je(e.rotationCenter,t.rotationCenter)&&Je(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function rn(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)<XI?0:t}function sn(e,t){const n=e.computeShapeLocalToPageTransform(t);return Math.atan2(n.b,n.a)}function an(e,t){const n=e.selectedShapeIdsSignal.get();if(0===n.length)return{outlineVertices:[],pageBounds:null,frameBounds:null,rotation:0,rotationCenter:null,selectionAnchorPagePoint:null,hasRotation:!1,hasCompatibleRotation:!0};const i=[],o=[],r=[];let s=1/0,a=1/0,l=-1/0,d=-1/0;for(const S of n){const n=e.getShapeSignal(S).get();if(!n)continue;const c=e.getShapeUtil(n),u=en(e,n),h=u?c.getSelectionPagePoints(u):null;if(h&&o.push(...h),!c.contributesToSelectionFrame(n,{editor:e}))continue;r.push(n);const p=t(S);if(!p)continue;const g=c.getSelectionFramePositionedOutlineVertices(n,{editor:e}),f=g?(()=>{const t=e.computeShapePositionedToPageTransform(n);return g.map(e=>t.applyToPoint(e))})():p.outlineVertices;i.push(...f);for(const e of f)s=Math.min(s,e.x),a=Math.min(a,e.y),l=Math.max(l,e.x),d=Math.max(d,e.y)}const c=Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(l)&&Number.isFinite(d)?new SI(s,a,l-s,d-a):null,u=!(r.length>0)||function(e,t){if(0===t.length)return!0;const n=t[0],i=rn(n?sn(e,n):0);return t.every(t=>((e,t)=>{const n=rn(e)-rn(t),i=Math.PI/2;return Math.abs(n-Math.round(n/i)*i)<XI})(sn(e,t),i))}(e,r),h=((e,t,n)=>{if(0===t.length||!n)return 0;const i=t[0];return rn(i?sn(e,i):0)})(e,r,u),p=((e,t)=>t.some(t=>Math.abs(rn(sn(e,t)))>XI))(e,r),g=c?.center??null,f=0===i.length?null:Math.abs(h)<XI||!g?SI.FromPoints(i):SI.FromPoints(i.map(e=>mI.RotWith(e,g,-h))),m=o.length>0?SI.FromPoints(o):null;return{outlineVertices:i,pageBounds:c,frameBounds:f,rotation:h,rotationCenter:g,selectionAnchorPagePoint:f&&g?Math.abs(h)<XI?new mI(f.center.x,f.minY):mI.RotWith(new mI(f.center.x,f.minY),g,h):m?new mI(m.center.x,m.minY):null,hasRotation:p,hasCompatibleRotation:u}}function ln(e,t){return e.length===t.length&&e.every((e,n)=>{const i=t[n];return!!i&&e.id===i.id&&e.parentId===i.parentId&&e.type===i.type})}function dn(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){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function un(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!cn(i,o))return!1}return!0}function hn(e,t){return e===t||e.length===t.length&&e.every((e,n)=>e===t[n])}function pn(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 gn(e,t){return e===t||(e&&t?dn(e.bounds,t.bounds)&&cn(e.center,t.center)&&un(e.corners,t.corners)&&un(e.outlineVertices,t.outlineVertices):e===t)}function fn(e){return e?e.clone():e}function mn(e){return e?e.clone():e}function Sn(e){return e?.map(e=>e.clone())}function yn(e){return e?new yI(e.a,e.b,e.c,e.d,e.e,e.f):void 0}function bn(e){if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,o=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),i=Math.max(i,r.maxX),o=Math.max(o,r.maxY);return new SI(t,n,i-t,o-n)}function xn(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),o=Math.min(e.maxX,t.maxX),r=Math.min(e.maxY,t.maxY);return o<n||r<i?null:new SI(n,i,o-n,r-i)}function In(e,t){return t.canAutomaticallyReceiveChildren(e)}function vn(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1?l:null}function wn(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new mI(n.minX,n.minY),new mI(n.maxX,n.minY),new mI(n.maxX,n.maxY),new mI(n.minX,n.maxY)];for(let o=0;o<i.length;o+=1){const n=i[o],r=i[(o+1)%i.length];if(n&&r&&null!==vn(e,t,n,r))return!0}return!1}function Pn(e,t){return SI.FromPoints([new mI(e.minX,e.minY),new mI(e.maxX,e.minY),new mI(e.maxX,e.maxY),new mI(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function kn({localWidth:e,localHeight:t,scaleX:n,scaleY:i}){return{width:Math.abs(n)*e,height:Math.abs(i)*t}}function Cn({width:e,height:t,scaleX:n,scaleY:i}){const o=Math.abs(n),r=Math.abs(i);return{width:0===o?e:e/o,height:0===r?t:t/r}}function Tn(e){return"top_left"===e||"left"===e||"bottom_left"===e}function Mn(e){return"top_right"===e||"right"===e||"bottom_right"===e}function En(e){return"top_left"===e||"top"===e||"top_right"===e}function An(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function Bn({handleId:e,scaleX:t,scaleY:n}){const i=Tn(e)?t<0?"right":"left":Mn(e)?t<0?"left":"right":null,o=En(e)?n<0?"bottom":"top":An(e)?n<0?"top":"bottom":null;return"top"===o&&"left"===i?"top_left":"top"===o&&"right"===i?"top_right":"bottom"===o&&"right"===i?"bottom_right":"bottom"===o&&"left"===i?"bottom_left":o||i||e}function Rn({axis:e,startBounds:t,bounds:n,handleId:i,scale:o,isResizingFromCenter:r}){const s=Math.sign(o??1)||1;return r?s:"x"===e?Tn(i)?n.minX>=t.maxX?-1:1:Mn(i)?n.maxX<=t.minX?-1:1:s:En(i)?n.minY>=t.maxY?-1:1:An(i)?n.maxY<=t.minY?-1:1:s}function Ln({requestedBounds:e,handleId:t,actualWidth:n,actualHeight:i,scaleX:o,scaleY:r,isResizingFromCenter:s}){return new SI(s?e.center.x-n/2:Tn(t)?o<0?e.minX:e.maxX-n:Mn(t)?o<0?e.maxX-n:e.minX:e.center.x-n/2,s?e.center.y-i/2:En(t)?r<0?e.minY:e.maxY-i:An(t)?r<0?e.maxY-i:e.minY:e.center.y-i/2,n,i)}function $n({bounds:e,startBounds:t,handleId:n,aspectRatio:i,isResizingFromCenter:o,scaleX:r,scaleY:s}){if(i<=0)return{bounds:e,scaleX:r??e.w/Math.max(1,t.w),scaleY:s??e.h/Math.max(1,t.h)};let a=e.w,l=e.h;const d=Math.sign(r??1)||1,c=Math.sign(s??1)||1;switch(n){case"left":case"right":l=a/i;break;case"top":case"bottom":a=l*i;break;default:{const e=a/Math.max(1,t.w),n=l/Math.max(1,t.h);Math.abs(e)>Math.abs(n)?l=a/i:a=l*i;break}}if(o){const e=t.center;return{bounds:new SI(e.x-a/2,e.y-l/2,a,l),scaleX:d*(a/Math.max(1,t.w)),scaleY:c*(l/Math.max(1,t.h))}}let u;switch(n){case"top_left":u=new SI(d<0?e.minX:e.maxX-a,c<0?e.minY:e.maxY-l,a,l);break;case"top_right":u=new SI(d<0?e.maxX-a:e.minX,c<0?e.minY:e.maxY-l,a,l);break;case"bottom_right":u=new SI(d<0?e.maxX-a:e.minX,c<0?e.maxY-l:e.minY,a,l);break;case"bottom_left":u=new SI(d<0?e.minX:e.maxX-a,c<0?e.maxY-l:e.minY,a,l);break;case"top":u=new SI(t.center.x-a/2,c<0?t.maxY:t.maxY-l,a,l);break;case"right":u=new SI(d<0?t.minX-a:t.minX,t.center.y-l/2,a,l);break;case"bottom":u=new SI(t.center.x-a/2,c<0?t.minY-l:t.minY,a,l);break;case"left":u=new SI(d<0?t.maxX:t.maxX-a,t.center.y-l/2,a,l)}return{bounds:u,scaleX:d*(a/Math.max(1,t.w)),scaleY:c*(l/Math.max(1,t.h))}}function Fn(e,t){return e.x===t.x&&e.y===t.y}function Un(e){return[new mI(e.minX,e.minY),new mI(e.center.x,e.minY),new mI(e.maxX,e.minY),new mI(e.minX,e.center.y),e.center,new mI(e.maxX,e.center.y),new mI(e.minX,e.maxY),new mI(e.center.x,e.maxY),new mI(e.maxX,e.maxY)]}function On(e,t){return"x"===t?e.x:e.y}function Dn(e,t){return"x"===t?e.minX:e.minY}function zn(e,t){return"x"===t?e.maxX:e.maxY}function Nn(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function Hn(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Wn(e,t){return null!==Hn(e,t)}function _n(e,t){return new SI(e.x+t.x,e.y+t.y,e.w,e.h)}function Kn(e,t,n){return _n(e,((e,t)=>"x"===e?new mI(t,0):new mI(0,t))(t,n))}function Yn(e){return[new mI(e.minX,e.minY),new mI(e.maxX,e.minY),new mI(e.maxX,e.maxY),new mI(e.minX,e.maxY)]}function Xn(e,t,n){const i=n.sub(t),o=i.len2();if(o<=1e-8)return e.dist2(t);const r=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/o));return e.dist2(new mI(t.x+i.x*r,t.y+i.y*r))}function qn(e,t,n){const i=n.sub(t),o=i.len2();if(o<=1e-8)return t.clone();const r=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/o));return new mI(t.x+i.x*r,t.y+i.y*r)}function jn(e,t){if(0===t.length)return null;if(1===t.length){const n=t[0].clone();return{point:n,distanceSquared:e.dist2(n)}}let n=null,i=Number.POSITIVE_INFINITY;const o=2===t.length?1:t.length;for(let r=0;r<o;r+=1){const o=t[r],s=t[(r+1)%t.length];if(!o||!s)continue;const a=Xn(e,o,s);a>=i||(i=a,n=qn(e,o,s))}return n?{point:n,distanceSquared:i}:null}function Vn(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 Gn(e){const t=e.map(e=>({value:e.point.x,point:e})),n=e.map(e=>({value:e.point.y,point:e}));return t.sort(Zn),n.sort(Zn),{x:t,y:n}}function Zn(e,t){return e.value-t.value||e.point.id.localeCompare(t.point.id)}function Qn(e,t,n,i){const o=((e,t)=>"x"===t?e.x:e.y)(e,t),r=[];for(let s=((e,t)=>{let n=0,i=e.length;for(;n<i;){const o=Math.floor((n+i)/2),r=e[o];r&&r.value<t?n=o+1:i=o}return n})(o,n);s<o.length;s+=1){const e=o[s];if(!e||e.value>i)break;r.push(e.point)}return r}function Jn(e){return e.weight??(e.kind?ZI[e.kind]:0)}function ei(e,t){return`points:${e}:${[...t].sort().join("|")}`}function ti(e,t,n){if(!t)return!0;const i=(e=>Math.min(.2*e,1.5))(n);return e.distance<t.distance-1e-8?!(t.weight>e.weight+1e-8&&t.distance-e.distance<=i):e.distance<=t.distance+i&&e.weight>t.weight+1e-8}function ni(e,t,n,i,o={}){const r=o.releaseThreshold??i,s=Math.max(i,r),a=o.switchDistance??0;let l=null,d=null;for(const g of t){const t=On(g,e),a=Qn(n,e,t-s,t+s);o.stats&&(o.stats.candidatePointCount+=a.length);for(const n of a){const s=On(n.point,e)-t,a=Math.abs(s),c={offset:s,distance:a,weight:Jn(n),fromPrevious:!1};if(a<=i&&ti(c,l,i)&&(l=c),o.previousCandidatePointIds?.has(n.id)&&a<=r){const e={...c,fromPrevious:!0};ti(e,d,r)&&(d=e)}}}const c=d&&(!l||l.distance+a>=d.distance)?d:l;if(!c)return null;const u=c.fromPrevious&&c.distance>i?r:i,h=[];for(const[g,f]of t.entries()){const t=On(f,e),i=Qn(n,e,t-u,t+u);for(const n of i){const i=On(n.point,e)-t;Math.abs(i)>u||Math.abs(i-c.offset)>1e-8||h.push({selectionPoint:f,selectionPointKind:o.selectionPointKinds?.[g],candidatePoint:n.point,candidatePointKind:n.kind,candidatePointId:n.id,candidateNodeId:n.nodeId})}}o.stats&&(o.stats.matchedPointCount+=h.length);const p=Array.from(new Set(h.map(e=>e.candidatePointId)));return h.length>0?{type:"points",id:ei(e,p),nudge:c.offset,distance:c.distance,weight:c.weight,candidatePointIds:p,pairs:h}:null}function ii(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new mI(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new mI(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new mI(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new mI(t.minX,t.maxY))}return n}function oi(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>Dn(e.bounds,t)-Dn(n.bounds,t)),o=[];for(let r=0;r<i.length;r+=1){const e=i[r];if(!e)continue;let s=Number.POSITIVE_INFINITY;for(let a=r+1;a<i.length;a+=1){const r=i[a];if(!r)continue;const l=zn(e.bounds,t),d=Dn(r.bounds,t);if(d>s+1e-8)break;if(l>=d)continue;const c=Hn(Nn(e.bounds,t),Nn(r.bounds,t));c&&(s=d,o.push({direction:n,startNode:e,endNode:r,length:d-l,breadthIntersection:c}))}}return o}function ri(e,t,n,i){const o=Hn(Nn(t.bounds,i),Nn(n.bounds,i));return o?{direction:e,startNode:t,endNode:n,length:Dn(n.bounds,i)-zn(t.bounds,i),breadthIntersection:o}:null}function si(e,t){return[e,t.direction,t.startNode.id,t.endNode.id,t.length.toFixed(8)].join(":")}function ai(e,t,n,i,o={}){const r=Nn(t,e),s=((e,t)=>"x"===t?e.w:e.h)(t,e),a=o.releaseThreshold??i,l=o.switchDistance??0;let d=i+1,c=null,u=null;const h=(e,t,n)=>{const r=Math.abs(e);0!==t.length&&(r<=i&&r<d-1e-8&&(d=r,c={type:"gaps",id:n,nudge:e,distance:r,gaps:t}),o.previousSnapId===n&&r<=a&&(!u||r<u.distance-1e-8)&&(u={type:"gaps",id:n,nudge:e,distance:r,gaps:t}))},p=n=>({id:"selection",bounds:Kn(t,e,n)});for(const g of n){if(s<=g.length&&Wn(r,g.breadthIntersection)){const n=zn(g.startNode.bounds,e)+(g.length-s)/2-Dn(t,e),i=p(n);h(n,[ri(g.direction,g.startNode,i,e),ri(g.direction,i,g.endNode,e)].filter(e=>null!==e),`${si(e,g)}:center`)}const n=zn(g.endNode.bounds,e)+g.length-Dn(t,e),i=p(n);if(Wn(Nn(i.bounds,e),g.breadthIntersection)){const t=ri(g.direction,g.endNode,i,e);h(n,t?[g,t]:[],`${si(e,g)}:after`)}const o=Dn(g.startNode.bounds,e)-g.length-zn(t,e),a=p(o);if(Wn(Nn(a.bounds,e),g.breadthIntersection)){const t=ri(g.direction,a,g.startNode,e);h(o,t?[t,g]:[],`${si(e,g)}:before`)}}return u&&(!c||c.distance+l>=u.distance)?u:c}function li(e,t,n={}){if(!e)return t;if(!t)return e;const i=n.switchDistance??0;return"points"===n.previousSnap?.type&&n.previousSnap.id===e.id?Math.abs(t.nudge)+i<Math.abs(e.nudge)?t:e:"gaps"===n.previousSnap?.type&&n.previousSnap.id===t.id?Math.abs(e.nudge)+i<Math.abs(t.nudge)?e:t:Math.abs(e.nudge)<=Math.abs(t.nudge)?e:t}function di(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&&Fn(e.rotationCenter,t.rotationCenter)&&Fn(e.line[0],t.line[0])&&Fn(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&Fn(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&&Fn(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>Fn(e.startEdge[0],t.startEdge[0])&&Fn(e.startEdge[1],t.startEdge[1])&&Fn(e.endEdge[0],t.endEdge[0])&&Fn(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function ci(e){return"horizontal"===e.direction?{startEdge:[new mI(e.startNode.bounds.maxX,e.startNode.bounds.minY),new mI(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new mI(e.endNode.bounds.minX,e.endNode.bounds.minY),new mI(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new mI(e.startNode.bounds.minX,e.startNode.bounds.maxY),new mI(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new mI(e.endNode.bounds.minX,e.endNode.bounds.minY),new mI(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function ui(e,t,n,i){const o=t.pairs.some(({candidatePointKind:e,selectionPointKind:t})=>"center"===e&&"center"===t),r=Vn([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),s=Vn([...t.pairs.filter(({selectionPointKind:e})=>"center"===e).map(({selectionPoint:e})=>e.add(n)),...t.pairs.filter(({candidatePointKind:e})=>"center"===e).map(({candidatePoint:e})=>e.clone())]),a=o?s:r,l=o?s:Vn([...t.pairs.filter(({selectionPointKind:e})=>"center"!==e&&"edge_midpoint"!==e).map(({selectionPoint:e})=>e.add(n)),...t.pairs.filter(({candidatePointKind:e})=>"center"!==e&&"edge_midpoint"!==e).map(({candidatePoint:e})=>e.clone())]),d=fi(e,a);return{id:mi(e,d,l),type:"points",axis:e,line:d,points:l,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function hi(e,t,n,i){return pi(e,t,n).map(t=>ui(e,t,n,i))}function pi(e,t,n){const i=new Map;for(const o of t.pairs){const t=On(o.selectionPoint.add(n),e).toFixed(8),r=i.get(t);r?r.push(o):i.set(t,[o])}return Array.from(i.values()).map(e=>({type:"points",id:t.id,nudge:t.nudge,distance:t.distance,weight:t.weight,candidatePointIds:Array.from(new Set(e.map(e=>e.candidatePointId))),pairs:e}))}function gi(e,t,n){return"x"===e?[new mI(t,n.minY),new mI(t,n.maxY)]:[new mI(n.minX,t),new mI(n.maxX,t)]}function fi(e,t){if(0===t.length)return[mI.Zero(),mI.Zero()];let n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const s of t)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),r=Math.max(r,s.y);return"x"===e?[new mI(n,o),new mI(n,r)]:[new mI(n,o),new mI(i,o)]}function mi(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 Si(e,t,n,i,o,r){return pi(e,t,n).map(t=>((e,t,n,i,o,r)=>{const s=ui(e,t,n,i),a=t.pairs[0],l=On(a?.selectionPoint.add(n)??o.center,e),d=new Map(r.map(e=>[e.id,e.bounds])),c=[],u=new Set;for(const g of t.pairs){if(u.has(g.candidateNodeId))continue;u.add(g.candidateNodeId);const t=d.get(g.candidateNodeId);t&&c.push(...gi(e,l,t))}const h=Vn([...s.points,...gi(e,l,o),...c]),p=fi(e,Vn([...gi(e,l,o),...c]));return{...s,id:mi(e,p,h),line:p,points:h}})(e,t,n,i,o,r))}function yi(e,t,n){const i="x"===e?new mI(n.x,t.y):new mI(t.x,n.y),o=Vn([n.clone(),i]),r=fi(e,o);return{id:mi(e,r,o),type:"points",axis:e,line:r,points:o,rotation:0,rotationCenter:mI.Zero()}}function bi(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new mI(0,n.y):new mI(n.x,0),o=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:_n(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:_n(e.endNode.bounds,i)}:e.endNode}));return{id:`gaps:${o.map(e=>`${e.startNode.id}:${e.endNode.id}:${e.length.toFixed(4)}`).join("|")}`,type:"gaps",direction:o[0]?.direction??"horizontal",gaps:o.map(ci),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function xi(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 Ii(e,t){return 0===t.rotation?e.clone():mI.RotWith(e,t.rotationCenter,-t.rotation)}function vi(e,t){return 0===t.rotation?e.clone():mI.RotWith(e,t.rotationCenter,t.rotation)}function wi(e,t){return vi(e,t)}function Pi(e,t,n,i,o){return 0===n?i:i+(e-t)/n*o}function ki({point:e,fromBounds:t,toBounds:n}){return new mI(Pi(e.x,t.minX,t.w,n.minX,n.w),Pi(e.y,t.minY,t.h,n.minY,n.h))}function Ci({axis:e,bounds:t,point:n}){return"horizontal"===e?new mI(t.minX+t.maxX-n.x,n.y):new mI(n.x,t.minY+t.maxY-n.y)}function Ti({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new SI(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new SI(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function Mi(e){return{point:e.point,kind:e.kind??"custom",weight:e.weight}}function Ei(e){const t=e.sourcePointOffsets;return t&&t.length>0?t.map(t=>e.pagePoint.add(t)):[e.pagePoint]}function Ai(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;const n=Math.PI/2,i=Math.round((e-t)/n);return Math.abs(e-t-i*n)>=.001?null:Math.abs(i)%2==0?"parallel":"perpendicular"}function Bi(e,t,n){return t.every(t=>{const i=e.computeShapeLocalToPageTransform(t);return null!==Ai(Math.atan2(i.b,i.a),n)})}function Ri(e,t,n,i){const o=1===t.length,r=(s=t.map(t=>e.getShapeUtil(t).getAllowedSelectionResizeModes(t,{editor:e,handleId:n,isOnlyResizeTarget:o})),ev.filter(e=>s.every(t=>t.includes(e))));var s;return i?r:r.filter(e=>"free"!==e)}function Li(e,t,n){if(0===t.length)return[];const i=1===t.length,o=t.map(t=>e.getShapeUtil(t).getSelectionResizeHandleIds(t,{editor:e,isOnlyResizeTarget:i})),r=Bi(e,t,n);return QI.filter(n=>o.every(e=>e.includes(n))&&Ri(e,t,n,r).length>0)}function $i(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function Fi(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 Ui(e,t){return e===t||(e&&t?e.localPath===t.localPath&&((e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]))(e.localDecorationPaths,t.localDecorationPaths)&&Fi(e.localBounds,t.localBounds)&&((e,t)=>e.a===t.a&&e.b===t.b&&e.c===t.c&&e.d===t.d&&e.e===t.e&&e.f===t.f)(e.localToPage,t.localToPage)&&e.strokeWidth===t.strokeWidth&&e.strokeDasharray===t.strokeDasharray:e===t)}function Oi(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o)return!1;if(!(i.id===o.id&&i.usesSelectionPathOverlay===o.usesSelectionPathOverlay&&$i(i.startPagePoint,o.startPagePoint)&&$i(i.endPagePoint,o.endPagePoint)&&$i(i.middlePagePoint,o.middlePagePoint)&&Ui(i.pathStyle,o.pathStyle)&&Ht(i.bindingSegments,o.bindingSegments)&&i.path===o.path&&i.pageClipPath===o.pageClipPath))return!1}return!0}function Di(e,t){return e===t||(e&&t?Fi(e.bounds,t.bounds)&&e.rotation===t.rotation&&$i(e.rotationCenter,t.rotationCenter)&&e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius:e===t)}function zi(e,t){return e===t||(e&&t?Fi(e.bounds,t.bounds)&&e.rotation===t.rotation&&$i(e.rotationCenter,t.rotationCenter):e===t)}function Ni(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!zi(e[n]??null,t[n]??null))return!1;return!0}function Hi(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function Wi(e,t){return e.id===t.id&&$i(e.point,t.point)&&Fi(e.bounds,t.bounds)}function _i(e,t){return e.id===t.id&&$i(e.point,t.point)&&Fi(e.bounds,t.bounds)}function Ki(e,t){return e.terminal===t.terminal&&$i(e.point,t.point)&&Fi(e.bounds,t.bounds)}function Yi(e,t){return $i(e.point,t.point)&&Fi(e.bounds,t.bounds)}function Xi(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&$i(e.point,t.point)&&Fi(e.bounds,t.bounds)}function qi(e,t){return e.id===t.id&&$i(e.point,t.point)}function ji(e,t){return e.id===t.id&&$i(e.point,t.point)}function Vi(e,t){return e.terminal===t.terminal&&$i(e.point,t.point)}function Gi(e,t){return $i(e.point,t.point)}function Zi(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&$i(e.point,t.point)}function Qi(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1){const o=e[i],r=t[i];if(!o||!r||!n(o,r))return!1}return!0}function Ji({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 mI(e.maxX+t,e.minY-t):new mI(e.minX-t,e.maxY+t)}function eo(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&Qi(e.resizeHandles,t.resizeHandles,Wi)&&Qi(e.rotateHandles,t.rotateHandles,_i)&&Qi(e.terminalHandles,t.terminalHandles,Ki)&&Qi(e.middleHandles,t.middleHandles,Yi)&&Qi(e.customHandles,t.customHandles,Xi):e===t)}function to(e,t){return e===t||(e&&t?Qi(e.resizeHandleAnchors,t.resizeHandleAnchors,qi)&&Qi(e.rotateHandleAnchors,t.rotateHandleAnchors,ji)&&Qi(e.terminalHandleAnchors,t.terminalHandleAnchors,Vi)&&Qi(e.middleHandleAnchors,t.middleHandleAnchors,Gi)&&Qi(e.customHandleAnchors,t.customHandleAnchors,Zi):e===t)}function no(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 io(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function oo(e,t,n,i,o,r,s){const a=e.map(e=>i(e)),l=e.every(e=>o(e)),d=e.every(e=>r(e)),c=new Set(s),u=a.flatMap(e=>e.terminalHandleAnchors),h=a.flatMap(e=>e.middleHandleAnchors),p=a.flatMap(e=>e.customHandleAnchors??[]),g=u.length>0||h.length>0||p.length>0;if(!t)return{resizeHandleAnchors:[],rotateHandleAnchors:[],terminalHandleAnchors:u,middleHandleAnchors:h,customHandleAnchors:p};const{bounds:f,rotation:m,rotationCenter:S,hasCompatibleRotation:y}=t,b=e[0]?.rotation??m,x=8/n,I=14/n,v=f.w<2*x,w=f.h<2*x,P=e=>0===m?e:mI.RotWith(e,S,m),k=new mI(f.minX,f.minY),C=new mI(f.center.x,f.minY),T=new mI(f.maxX,f.minY),M=new mI(f.maxX,f.center.y),E=new mI(f.maxX,f.maxY),A=new mI(f.center.x,f.maxY),B=new mI(f.minX,f.maxY),R=new mI(f.minX,f.center.y);return{resizeHandleAnchors:!l||g?[]:[{kind:"resize",id:"top_left",point:P(k)},...v?[]:[{kind:"resize",id:"top",point:P(C)}],...v&&w?[]:[{kind:"resize",id:"top_right",point:P(T)}],...w?[]:[{kind:"resize",id:"right",point:P(M)}],...v||w?[]:[{kind:"resize",id:"bottom_right",point:P(E)}],...v?[]:[{kind:"resize",id:"bottom",point:P(A)}],...v||w?[]:[{kind:"resize",id:"bottom_left",point:P(B)}],...w?[]:[{kind:"resize",id:"left",point:P(R)}]].filter(e=>c.has(e.id)),rotateHandleAnchors:!d||g||!y||v||w?[]:[{kind:"rotate",id:"bottom_left_rotate",point:P(Ji({bounds:f,rotateOffset:I,referenceRotation:b,frameRotation:m}))}],terminalHandleAnchors:u,middleHandleAnchors:h,customHandleAnchors:p}}function ro(e,t){const n=8/t,i=n/2,o=e=>new SI(e.x-i,e.y-i,n,n);return{resizeHandles:e.resizeHandleAnchors.map(e=>({...e,bounds:o(e.point)})),rotateHandles:e.rotateHandleAnchors.map(e=>({...e,bounds:o(e.point)})),terminalHandles:e.terminalHandleAnchors.map(e=>({...e,bounds:o(e.point)})),middleHandles:e.middleHandleAnchors.map(e=>({...e,bounds:o(e.point)})),customHandles:e.customHandleAnchors.map(e=>({...e,bounds:o(e.point)}))}}function so(e){const t=e.getSelectedShapes();if(0===t.length)return null;if(t.some(e=>e.isLocked))return null;const n=t[0]?.parentId;if(!n)return null;if(t.some(e=>e.parentId!==n))return null;const i=e.getChildShapes(n),o=new Set(t.map(e=>e.id)),r=i.map((e,t)=>o.has(e.id)?t:-1).filter(e=>e>=0);return r.length!==t.length?null:{parentId:n,selectedCount:t.length,count:i.length,canMoveBackward:r.some(e=>e>0&&!o.has(i[e-1].id)),canMoveForward:r.some(e=>e<i.length-1&&!o.has(i[e+1].id))}}function ao(e){const t=e.getSelectedShapes();if(1!==t.length)return null;const[n]=t;if(!n||n.isLocked)return null;const i=e.getChildShapes(n.parentId),o=i.findIndex(e=>e.id===n.id);return o<0?null:{parentId:n.parentId,index:o,count:i.length,canMoveBackward:o>0,canMoveForward:o<i.length-1}}function lo(e,t){const n=t.map(t=>e.getShape(t)).filter(e=>!!e);if(0===n.length)return null;if(n.some(t=>t.isLocked||e.isShapeHidden(t.id)))return null;const i=n[0]?.parentId;if(!i)return null;if(n.some(e=>e.parentId!==i))return null;const o=e.getChildShapes(i),r=new Set(n.map(e=>e.id)),s=o.map((e,t)=>r.has(e.id)?t:-1).filter(e=>e>=0);return s.length!==n.length?null:{parentId:i,selectedCount:n.length,count:o.length,canMoveBackward:s.some(e=>e>0&&!r.has(o[e-1].id)),canMoveForward:s.some(e=>e<o.length-1&&!r.has(o[e+1].id))}}function co(e,t,n,i="user"){const o=lo(e,t);if(!o)return!1;const r=e.getChildShapes(o.parentId),s=new Set(t),a=[...r];let l=!1;if("backward"===n)for(let d=1;d<a.length;d+=1){const e=a[d],t=a[d-1];e&&t&&s.has(e.id)&&!s.has(t.id)&&(a[d-1]=e,a[d]=t,l=!0)}else for(let d=a.length-2;d>=0;d-=1){const e=a[d],t=a[d+1];e&&t&&s.has(e.id)&&!s.has(t.id)&&(a[d]=t,a[d+1]=e,l=!0)}return!!l&&(e.cancelInteractionForCommand(),e.commands.updateShapes(a.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:i}),!0)}function uo(e,t,n,i="user"){const o=lo(e,t);if(!o)return!1;const r=e.getChildShapes(o.parentId),s=new Set(t),a=[],l=[];for(const c of r)s.has(c.id)?a.push(c):l.push(c);if(a.length!==s.size)return!1;if(!("back"===n?o.canMoveBackward:o.canMoveForward))return!1;const d="back"===n?[...a,...l]:[...l,...a];return e.cancelInteractionForCommand(),e.commands.updateShapes(d.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:i}),!0}function ho(e){const t="string"==typeof e?{key:e}:e;return{key:fo(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}}function po(e){const t=ho(e),n=[];var i;return t.accelKey?n.push("⌘"):(t.ctrlKey&&n.push("Ctrl"),t.metaKey&&n.push("Meta")),t.altKey&&n.push("Alt"),t.shiftKey&&n.push("Shift"),n.push(1===(i=t.key).length?i.toUpperCase():i),n.join("")}function go(e,t){return!(fo(t.key)!==e.key||t.altKey!==e.altKey||t.shiftKey!==e.shiftKey||void 0!==e.accelKey&&t.accelKey!==e.accelKey||void 0!==e.ctrlKey&&t.ctrlKey!==e.ctrlKey||void 0!==e.metaKey&&t.metaKey!==e.metaKey||void 0===e.accelKey&&void 0===e.ctrlKey&&void 0===e.metaKey&&t.accelKey)}function fo(e){return e.toLowerCase()}function mo(e){return[e.key,e.altKey?"alt":null,e.ctrlKey?"ctrl":null,e.metaKey?"meta":null,e.shiftKey?"shift":null,e.accelKey?"accel":null].filter(Boolean).join("+")}function So(e,t,n){return Math.min(n,Math.max(t,e))}function yo(e){return 0===e.length?"none":e.map(e=>`${e.start}-${e.end-1}`).join(", ")}function bo(e,t=0){if(0===e.length)return[];const n=[...e].sort((e,t)=>e.start-t.start),i=[];for(const o of n){const e=i[i.length-1];!e||o.start>e.end+t?i.push({...o}):e.end=Math.max(e.end,o.end)}return i}function xo(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function Io(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function vo(e,t,n=0){return bo(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n)}function wo(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function Po(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:wo(e,t)}}function ko(e,t){return{originScreenPoint:t.clone(),originCamera:e.getCurrentCamera()}}function Co(e,t,n){const i=n.sub(t.originScreenPoint),o=t.originCamera.z;e.setCamera({x:t.originCamera.x-i.x/o,y:t.originCamera.y-i.y/o},{source:"user"})}function To(e){let t=null;for(const i of e.splice(0).reverse())try{i()}catch(n){t??=n}return t}function Mo({outputBounds:e,cutoutLocalPolygons:t,localToOutput:n}){const i=t.filter(e=>e.length>=3);return 0===i.length?null:[Eo((o=e.expand(100),[new mI(o.minX,o.minY),new mI(o.maxX,o.minY),new mI(o.maxX,o.maxY),new mI(o.minX,o.maxY)])),...i.map(e=>Eo(e,n))].join(" ");var o}function Eo(e,t){const n=t?e.map(e=>t.applyToPoint(e)):e,i=n[0];return i?[`M ${Ao(i.x)} ${Ao(i.y)}`,...n.slice(1).map(e=>`L ${Ao(e.x)} ${Ao(e.y)}`),"Z"].join(" "):""}function Ao(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Bo(e){return[new mI(e.minX,e.minY),new mI(e.maxX,e.minY),new mI(e.maxX,e.maxY),new mI(e.minX,e.maxY)]}function Ro(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1?l:null}function Lo(e,t,n){const i=e[t];return"number"==typeof i&&Number.isFinite(i)?i:n}function $o(e){return Math.min(1,Math.max(0,(96-e)/96))}function Fo(e,t,n){if(t.w<=0||t.h<=0||n<=0)return mI.Zero();const i=Math.min(n,32),o=$o(e.x),r=$o(t.w-e.x),s=$o(e.y),a=1.25*(r-o)*i,l=1.25*($o(t.h-e.y)-s)*i;return 0===a&&0===l?mI.Zero():new mI(a,l)}function Uo(e,t,n){const i=e.inputs.state.get();if("dragging"!==i.dragPhase||!i.currentPagePoint)return null;let o=i.currentPagePoint;if(!i.currentScreenPoint)return"apply_after_scroll"===n?null:{pagePoint:o,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey};const r=Fo(i.currentScreenPoint,e.viewportScreenSizeSignal.get(),t.elapsed),s=0!==r.x||0!==r.y;return s||"always_apply"===n?(s&&(e.panCamera(r),o=e.screenToPage(i.currentScreenPoint)),{pagePoint:o,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey}):null}function Oo(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 Do(e,t,n){const i=new Set(n);if(i.has(t))return t;const o=zo(e,t);for(const s of o)if(i.has(s.ancestorId))return s.childId;const r=o[0]?.ancestorId;return r&&n.some(t=>((e,t)=>zo(e,t)[0]?.ancestorId??null)(e,t)===r)?t:o[o.length-1]?.ancestorId??t}function zo(e,t){const n=[];let i=e.getShape(t),o=t;const r=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(r.has(t))return n;r.add(t);const s=e.getShape(t);if(!s)return n;e.getShapeUtil(s).isSelectionTransformContainer(s)&&n.push({ancestorId:s.id,childId:o}),o=s.id,i=s}return n}function No({shiftKey:e,accelKey:t}){return e||t}function Ho({ctrlKey:e}){return e}function Wo(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function _o(e,t){return Math.round(e/t)*t}function Ko(e,t,n,i,o,r,s,a,l,d,c,u){const h=Yo(d,c),p=qo({point:t.localBounds.center,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:l}),g=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=ki({point:new mI(e.minX,e.minY),fromBounds:t,toBounds:n}),o=ki({point:new mI(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new SI(Math.min(i.x,o.x),Math.min(i.y,o.y),Math.abs(o.x-i.x),Math.abs(o.y-i.y))})({bounds:t.localBounds,fromBounds:n,toBounds:i}),f=new SI(p.x-g.w/2,p.y-g.h/2,g.w,g.h),m=vi(p,h),S=e.getShapeUtil(t.pageShape),y=Ai(t.pageShape.rotation,c),b=null!==y,x="perpendicular"===y?new SI(f.center.x-f.h/2,f.center.y-f.w/2,f.h,f.w):f,I=b?x:(()=>{const e=S.getSelectionResizeLocalBounds(t.pageShape),n=kn({localWidth:e.w,localHeight:e.h,scaleX:t.pageShape.scaleX,scaleY:t.pageShape.scaleY}),i=n.width*Math.abs(o),s=n.height*Math.abs(r);return new SI(m.x-i/2,m.y-s/2,i,s)})(),v=S.resizeSelectionBounds(t.pageShape,{handleId:s,isOnlyResizeTarget:a,pageCenter:m,selectionLocalBounds:I,scaleX:o,scaleY:r,isResizingFromCenter:l,selectionRotation:b?c:t.pageShape.rotation,selectionRotationCenter:b?d:m}),w=tn(e,t.shape,t.pageShape,v);w&&Object.assign(u,w)}function Yo(e,t){return{rotation:t,rotationCenter:e}}function Xo(e,t,n,i,o,r,s,a,l,d,c){const u=Yo(l,d),h=vi(qo({point:t.startLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u),p=vi(qo({point:t.endLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u),g=t.middleLocalPagePoint?vi(qo({point:t.middleLocalPagePoint,startBounds:n,scaleX:o,scaleY:r,handleId:s,isResizingFromCenter:a}),u):void 0,f=e.getShapeUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[h,p],pageMiddlePoint:g}),m=tn(e,t.shape,t.pageShape,f);m&&Object.assign(c,m)}function qo({point:e,startBounds:t,scaleX:n,scaleY:i,handleId:o,isResizingFromCenter:r}){const s=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:Tn(t)?e.maxX:Mn(t)?e.minX:e.center.x)({startBounds:t,handleId:o,isResizingFromCenter:r}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:En(t)?e.maxY:An(t)?e.minY:e.center.y)({startBounds:t,handleId:o,isResizingFromCenter:r});return new mI(s+(e.x-s)*n,a+(e.y-a)*i)}function jo(e,t,n,i,o){const r=t.localBounds.center,s=wi(new mI(t.pageShape.x+r.x,t.pageShape.y+r.y),{rotation:i,rotationCenter:n}),a=tn(e,t.shape,t.pageShape,{id:t.shape.id,x:s.x-r.x,y:s.y-r.y,rotation:t.rotation+i});a&&Object.assign(o,a)}function Vo(e,t,n,i,o){const r=e.getShapeUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[wi(t.startPagePoint,{rotation:i,rotationCenter:n}),wi(t.endPagePoint,{rotation:i,rotationCenter:n})],pageMiddlePoint:t.middlePagePoint?wi(t.middlePagePoint,{rotation:i,rotationCenter:n}):void 0}),s=tn(e,t.shape,t.pageShape,r);s&&Object.assign(o,s)}function Go(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 Zo(e,t,n){const i=n?e.getContainingShapeParentIdAtPoint(t,n):e.getContainingShapeParentId(t);if(!i)return null;const o=Go(e,t);if(!o||!o.startsWith("shape:")||i===o)return i;const r=e.getShape(o);return r&&e.getShapeUtil(r).canReceiveChildren(r)?e.getShapeUtil(r).canAutomaticallyReceiveChildren(r)?n?i:t.every(t=>{const n=e.getShapeContainment(r.id,t);return"inside"===n||"intersecting"===n})?o:i:o:i}function Qo(e,t,n){const i=Zo(e,t,n);i&&t.some(t=>e.getShape(t)?.parentId!==i)&&e.commands.reparentShapes({ids:[...t],parentId:i})}function Jo(e,t,n,i={}){let o=!0;return(e=>{const r=new gI(e,()=>{t.get(),o&&!1===i.fireImmediately?o=!1:(o=!1,n())},void 0);return r.attach(),()=>r.detach()})(e)}function er(e){return{id:e,kind:"value"}}function tr(e){return!(!e||"object"!=typeof e)&&("string"==typeof e.id&&("api"===e.kind||"service"===e.kind||"value"===e.kind))}function nr(e){return Object.freeze({id:e})}function ir(){const e=Ax(_v);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function or(e){const t=Ex(t=>Jo("useValue",e,t,{fireImmediately:!1}),[e]),n=Ex(()=>e.get(),[e]);return Dx(t,n,n)}function rr({children:e,className:t,dataUi:n}){const i=ir(),o=Ux(null);return $x(()=>Jo("PageSpace.transform",i.pageTransformSignal,()=>{const e=o.current;e&&(e.style.transform=i.pageTransformSignal.get().toCssString())}),[i]),Nx("div",{ref:o,"data-ui":n,className:t,style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transformOrigin:"0 0"},children:e})}function sr(e=[]){const t=new Kv;return t.registerCanvasRenderPlugins(e),t}function ar(){return Ax(Xv)}function lr(){const e="undefined"!=typeof window&&"1"===new URLSearchParams(window.location.search).get("renderHostDebug");
2
- return Hx("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:[Nx(rr,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:Nx(jv,{})}),e?Nx(Vv,{}):null]})}function dr(e,t,n){const i=new Set;let o=t.parentId;for(;o.startsWith("shape:");){const t=o;if(t===e)return!0;if(i.has(t))return!1;i.add(t);const r=n.get(t);if(!r)return!1;o=r.parentId}return!1}function cr({Component:e,editor:t,shape:n}){
3
- return Nx("div",{"aria-hidden":"true","data-ui":"shape-hover-decoration",style:{position:"absolute",inset:0,pointerEvents:"none"},children:Nx(e,{shape:n,editor:t,strokeWidth:2/or(t.cameraZoomSignal)})})}function ur(){
4
- return Nx("div",{"data-ui":"transform-descendant-ancestor-boundary",style:{position:"absolute",inset:0,border:"1px dashed #64748b",pointerEvents:"none"}})}function hr(){
5
- return Nx("div",{"data-ui":"shape-drop-target-label",style:{position:"absolute",left:10,top:10,display:"flex",alignItems:"center",height:24,padding:"0 10px",borderRadius:999,background:"#2563eb",color:"white",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:12,fontWeight:700,lineHeight:"24px",boxShadow:"0 10px 24px rgba(37, 99, 235, 0.24)",whiteSpace:"nowrap",pointerEvents:"none"},children:"Drop into container"})}function pr({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?Nx(zx,{children:e}):t.reduceRight((e,t)=>Nx(gr,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function gr({ancestorId:e,children:t,shapeElementToPage:n}){const i=ir(),o=or(i.getShapeSignal(e));if(!o)return Nx(zx,{children:t});const r=((e,t,n)=>{const i=e.getShapeUtil(t).getChildClipLocalPolygons(t);if(!i)return null;const o=e.computeShapeRenderToPageTransform(t),r=n.tryInvert();if(!r)return null;const s=i.filter(e=>e.length>=3).map(e=>e.map(e=>r.applyToPoint(o.applyToPoint(e)))).filter(e=>e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y)));return 0===s.length?null:1===s.length?`polygon(${s[0].map(Sr).join(", ")})`:`path("${s.map(mr).join(" ")}")`})(i,o,n);return r?Nx("div",{"data-ui":"shape-clip-boundary","data-clip-ancestor-id":e,style:{position:"absolute",inset:0,width:"100%",height:"100%",clipPath:r,WebkitClipPath:r,overflow:"visible"},children:t}):Nx(zx,{children:t})}function fr(e,t,n){const i=e.computeShapeRenderBounds(t),o=n.compose(yI.Translate(i.x,i.y));return{left:0,top:0,width:i.w,height:i.h,transform:o.toCssString(),transformOrigin:"0 0",elementToPage:o}}function mr(e){return e.map((e,t)=>`${0===t?"M":"L"} ${yr(e.x)} ${yr(e.y)}`).concat("Z").join(" ")}function Sr(e){return`${yr(e.x)}px ${yr(e.y)}px`}function yr(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function br(e,t){return(e.order??0)-(t.order??0)}function xr(e=[]){const t=new Jv;return t.registerCanvasRenderPlugins(e),t}function Ir(){return Ax(tw)}function vr(e,t){return"binding-preview"===e?{underlay:{"data-binding-preview-segment-underlay":t},segment:{"data-binding-preview-segment":t}}:"terminal-binding-guide"===e?{underlay:{"data-terminal-binding-guide-underlay":t},segment:{"data-terminal-binding-guide":t}}:{underlay:{"data-selection-binding-segment-underlay":t},segment:{"data-selection-binding-segment":t}}}function wr({start:e,end:t,startInset:n,endInset:i,strokeWidth:o,dashSize:r,gapSize:s,kind:a,terminal:l}){const d=(({start:e,end:t,startInset:n,endInset:i})=>{const o=t.x-e.x,r=t.y-e.y,s=Math.hypot(o,r);if(s<1e-6)return null;const a=Math.max(0,s/2-.001),l=Math.min(n,a),d=Math.min(i,a),c=o/s,u=r/s;return{start:{x:e.x+c*l,y:e.y+u*l},end:{x:t.x-c*d,y:t.y-u*d}}})({start:e,end:t,startInset:n,endInset:i});if(!d)return null;const c=vr(a,l);
6
- return Hx("g",{style:{pointerEvents:"none"},children:[Nx("line",{...c.underlay,x1:d.start.x,y1:d.start.y,x2:d.end.x,y2:d.end.y,fill:"none",stroke:iw,strokeLinecap:"round",strokeWidth:2.2*o}),Nx("line",{...c.segment,x1:d.start.x,y1:d.start.y,x2:d.end.x,y2:d.end.y,fill:"none",stroke:nw,strokeDasharray:`${r} ${s}`,strokeLinecap:"round",strokeWidth:o})]})}function Pr({path:e,strokeWidth:t,dashSize:n,gapSize:i,kind:o,terminal:r}){const s=vr(o,r);
7
- return Hx("g",{style:{pointerEvents:"none"},children:[Nx("path",{...s.underlay,d:e,fill:"none",stroke:iw,strokeLinecap:"round",strokeWidth:2.2*t}),Nx("path",{...s.segment,d:e,fill:"none",stroke:nw,strokeDasharray:`${n} ${i}`,strokeLinecap:"round",strokeWidth:t})]})}function kr({editor:e,shape:t,stroke:n,fill:i,strokeWidth:o}){const r=e.getShapePageOutlineVertices(t.id);return 0===r.length?null:Nx("polygon",{points:r.map(e=>`${e.x},${e.y}`).join(" "),fill:i,stroke:n,strokeWidth:o,strokeLinejoin:"round",strokeLinecap:"round"})}function Cr({frame:e,handleId:t,zoom:n}){const i=((e,t)=>{const{bounds:n}=e;switch(t){case"top":return{x1:n.minX,y1:n.minY,x2:n.maxX,y2:n.minY};case"right":return{x1:n.maxX,y1:n.minY,x2:n.maxX,y2:n.maxY};case"bottom":return{x1:n.minX,y1:n.maxY,x2:n.maxX,y2:n.maxY};case"left":return{x1:n.minX,y1:n.minY,x2:n.minX,y2:n.maxY};default:return null}})(e,t);return i?Nx("line",{"data-selection-resize-border":t,x1:i.x1,y1:i.y1,x2:i.x2,y2:i.y2,fill:"none",stroke:"transparent",strokeWidth:12/n,strokeLinecap:"butt",style:{cursor:Tr(t,e.rotation),pointerEvents:"stroke"}}):null}function Tr(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 fw[Math.round(n)%fw.length]??"default"}function Mr({handle:e,strokeWidth:t}){
8
- return Nx("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,"data-selection-custom-handle-visual":"default",x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:3,ry:3,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}function Er({dataPrefix:e,pathStyle:t,stroke:n,strokeWidth:i}){
9
- return Hx(zx,{children:[Nx("path",{"data-selection-overlay":e,d:t.localPath,fill:"none",stroke:n,strokeWidth:i,strokeDasharray:t.strokeDasharray,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"}),t.localDecorationPaths.map((t,o)=>Nx("path",{"data-selection-overlay":`${e}-decoration`,d:t,fill:"none",stroke:n,strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"},`${o}:${t}`))]})}function Ar(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Br(){
10
- return Nx("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:Nx(rr,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:Nx(Cw,{})})})}function Rr(e=[]){const t=new Mw;return t.registerCanvasRenderPlugins(e),t}function Lr(e){const t=(e=>e instanceof HTMLElement?e:null)(e);return!!t&&(!!t.isContentEditable||!!t.closest('[contenteditable="true"]')||t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)}function $r(e){return(e??("undefined"==typeof document?null:document))?.querySelector(Aw)??null}function Fr(e,t,n){return e.screenToPage(((e,t=$r())=>{if(!t)return new mI(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new mI(e.clientX-n.left,e.clientY-n.top)})(t,n))}function Ur(e,t){return{type:"keyboard",name:e,...Dr(t),code:t.code}}function Or(e,t,n){e.getShapeEditingSession()?n||e.handleInteractionEvent(Ur("key_up",t)):n||e.dispatch(Ur("key_up",t))}function Dr(e){return{key:e.key,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}}function zr(e){return"Space"===e.code}function Nr(e,t){const n=t.ownerDocument;return e===n||e===n.body||e===n.documentElement||e instanceof Node&&t.contains(e)}function Hr(e,t,n,i){return{type:"pointer",name:e,timestamp:t.timeStamp,pointerId:t.pointerId,button:t.button,buttons:t.buttons,pointerType:(o=t.pointerType,"touch"===o||"pen"===o?o:"mouse"),clickCount:t.detail,screenPoint:n,pagePoint:i,pressure:t.pressure,shiftKey:t.shiftKey,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,accelKey:t.metaKey||t.ctrlKey};var o}function Wr(e,t){return new mI(e.clientX-t.left,e.clientY-t.top)}function _r(e,t){return e instanceof Node&&t.contains(e)}function Kr(e,t){return(e%t+t)%t}function Yr(){const e=or(ir().currentCameraSignal);
11
- return Hx("svg",{"data-ui":"canvas-background","aria-hidden":"true",className:"land-canvas__grid-background",xmlns:"http://www.w3.org/2000/svg",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},children:[Nx("defs",{children:Bw.map(({min:t,mid:n,step:i})=>{const o=15*i*e.z,r=((e,t)=>({x:Kr(.5-e.x*e.z,t),y:Kr(.5-e.y*e.z,t)}))(e,o),s=e.z<n?(a=((e,[t,n],[i,o])=>i+(e-t)/(n-t)*(o-i))(e.z,[t,n],[0,1]),Math.max(0,Math.min(1,a))):1;var a;
12
- return Nx("pattern",{id:`land-canvas-grid-${i}`,width:o,height:o,patternUnits:"userSpaceOnUse",children:Nx("circle",{cx:r.x,cy:r.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:s})},i)})}),Bw.map(({step:e})=>Nx("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function Xr(e,t,n,i){return n||"hand"===e&&t?"grabbing":i||"hand"===e?"grab":"select"===e?void 0:"crosshair"}function qr({canvasComponents:e,canvasProviders:t,domEventGuardRegistry:n,onContextMenuRequest:i,overlayRegistry:o,rendererRegistry:r,showGrid:s=!1}={}){const a=ir(),l=Fx(()=>r??sr(),[r]),d=Fx(()=>o??xr(),[o]),c=Fx(()=>n??Rr(),[n]),u=or(a.toolStateSignal).activeToolId,h=or(a.shapeEditingStateSignal).session,p=or(a.inputs.isSpacePressed)&&null===h,{containerRef:g,handlers:f,isPointerActive:m,isCameraPanning:S,surfaceCursor:y}=function({activeDomEventGuards:e,activeToolId:t,editor:n,onContextMenuRequest:i,shapeEditingSession:o}){const r=Ux(null),s=Ux(null),a=Ux(null),l=Ux(null),d=Ux(null),c=Ux(null),u=Ux(null),[h,p]=Ox(!1),[g,f]=Ox(!1),[m,S]=Ox(void 0),y=null!==o;Bx(()=>{("select"!==t||y)&&n.setHoveredShapeId(null)},[t,n,y]);const b=Ex(()=>{null!==d.current&&(cancelAnimationFrame(d.current),d.current=null),c.current=null},[]),x=Ex(e=>{if(null===a.current)return void b();const t=c.current??e;c.current=e,n.dispatch({type:"tick",timestamp:e,elapsed:e-t}),d.current=requestAnimationFrame(x)},[n,b]),I=Ex(()=>{null===d.current&&(c.current=null,d.current=requestAnimationFrame(x))},[x]);return Bx(()=>{const i=r.current;if(!i)return;let o=null;const d=()=>{const e=i.getBoundingClientRect(),t={left:e.left,top:e.top};return s.current=t,t},c=()=>s.current??d(),h=()=>{null!==o&&(window.cancelAnimationFrame(o),o=null)},g=({clientPoint:e,target:o})=>{if(h(),!e||null!==a.current||"select"!==t||y)return void n.setHoveredShapeId(null);const r=i.getBoundingClientRect();if(!_r(o,i)||e.x<r.left||e.x>r.right||e.y<r.top||e.y>r.bottom)return void n.setHoveredShapeId(null);const s=c(),l=new mI(e.x-s.left,e.y-s.top),d=n.hitTestShape(n.screenToPage(l));if(!d)return void n.setHoveredShapeId(null);const u=n.getShapeUtil(d).getHoverTargetId(d,{editor:n});n.setHoveredShapeId(n.getOutermostSelectableShapeId(u))},m=()=>{const e=u.current;g({clientPoint:e,target:e?document.elementFromPoint(e.x,e.y):null})},x=()=>{null===o&&(o=window.requestAnimationFrame(()=>{o=null,m()}))},I=(t,o)=>"handled"===e.handle({name:t,event:o,editor:n,container:i}),v=()=>{if(!y)return void S(void 0);const t=u.current;S(t?e.getCursor({clientPoint:t,element:document.elementFromPoint(t.x,t.y),editor:n,container:i}):void 0)},w=(e,t)=>{if(!r.current)return;const i=Wr(t,c());n.dispatch(Hr(e,t,i,n.screenToPage(i)))},P=()=>{n.setViewportScreenSize({w:i.clientWidth,h:i.clientHeight})};d(),P();const k=e=>{if(I("key_down",e))return;if(n.getShapeEditingSession()){const t=Lr(e.target);return t||"Escape"!==e.key||e.altKey||e.ctrlKey||e.metaKey?!t&&n.handleInteractionEvent(Ur("key_down",e))?(e.preventDefault(),void e.stopPropagation()):void(t||"Enter"!==e.key||!e.metaKey&&!e.ctrlKey||n.completeEditing("user")):(e.preventDefault(),e.stopPropagation(),n.cancelInteractionAndClearTransients("escape"),void(n.getShapeEditingSession()&&n.cancelEditing("user")))}if(Lr(e.target))return;if(zr(e)){if(!Nr(e.target,i))return;e.preventDefault()}const t=n.shortcuts.getTargetForEvent(Dr(e));t&&"action"!==t.type&&e.preventDefault(),n.dispatch(Ur("key_down",e))},C=e=>{if(zr(e)&&n.inputs.pressedKeyCodes.get().has(e.code)&&!n.getShapeEditingSession())return e.preventDefault(),void Or(n,e,!1);I("key_up",e)||zr(e)&&!Nr(e.target,i)||Or(n,e,Lr(e.target))},T=()=>{a.current=null,l.current=null,p(!1),f(!1),n.setHoveredShapeId(null),b(),n.dispatch({type:"cancel",reason:"blur"})},M=e=>{if(I("wheel",e))return;e.preventDefault();const t={x:e.clientX,y:e.clientY};u.current=t;const i=Wr(e,c()),o=n.screenToPage(i);n.dispatch(((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new mI(e.deltaX,e.deltaY),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}))(e,i,o)),g({clientPoint:t,target:document.elementFromPoint(t.x,t.y)})},E=e=>{if(u.current={x:e.clientX,y:e.clientY},g({clientPoint:u.current,target:e.target}),v(),e.pointerId!==a.current){const t=Wr(e,c());if(n.inputs.setCurrentPointerPoint({timestamp:e.timeStamp,screenPoint:t,pagePoint:n.screenToPage(t),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}),I("pointer_move",e))return;if(!((e,t)=>{const n=t.getBoundingClientRect();return e.clientX>=n.left&&e.clientX<=n.right&&e.clientY>=n.top&&e.clientY<=n.bottom})(e,i)||!_r(e.target,i)||Lr(e.target))return;return void w("pointer_move",e)}const t={clientX:e.clientX,clientY:e.clientY,buttons:e.buttons,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey};var o,r;r=t,(o=l.current)&&o.clientX===r.clientX&&o.clientY===r.clientY&&o.buttons===r.buttons&&o.shiftKey===r.shiftKey&&o.altKey===r.altKey&&o.ctrlKey===r.ctrlKey&&o.metaKey===r.metaKey||(l.current=t,w("pointer_move",e))},A=(e,t)=>{t.pointerId===a.current&&(a.current=null,l.current=null,p(!1),f(!1),b(),i.hasPointerCapture(t.pointerId)&&i.releasePointerCapture(t.pointerId),w(e,t),"pointer_up"===e?m():n.setHoveredShapeId(null))},B=()=>{u.current=null,n.setHoveredShapeId(null),v()},R=e=>{u.current={x:e.clientX,y:e.clientY},window.setTimeout(v,0),e.pointerId===a.current?A("pointer_up",e):I("pointer_up",e)},L=e=>{u.current={x:e.clientX,y:e.clientY},v(),e.pointerId===a.current?A("pointer_cancel",e):I("pointer_cancel",e)},$=new ResizeObserver(()=>{d(),P(),x()}),F=()=>{d(),x()},U=n.listen(x);window.addEventListener("keydown",k),window.addEventListener("keyup",C),window.addEventListener("blur",T),window.addEventListener("scroll",F,{passive:!0,capture:!0}),window.addEventListener("pointermove",E,{passive:!0}),window.addEventListener("pointerup",R),window.addEventListener("pointercancel",L),i.addEventListener("pointerleave",B),i.addEventListener("wheel",M,{passive:!1}),$.observe(i);const O=window.requestAnimationFrame(v);return x(),()=>{b(),h(),U(),p(!1),f(!1),n.setHoveredShapeId(null),window.cancelAnimationFrame(O),window.removeEventListener("keydown",k),window.removeEventListener("keyup",C),window.removeEventListener("blur",T),window.removeEventListener("scroll",F,!0),window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",R),window.removeEventListener("pointercancel",L),i.removeEventListener("pointerleave",B),i.removeEventListener("wheel",M),$.disconnect()}},[e,t,n,y,b]),{containerRef:r,handlers:{onPointerDown:Ex(t=>{const i=r.current;if(!i)return;if(u.current={x:t.clientX,y:t.clientY},2===t.button)return void i.focus();if("handled"===e.handle({name:"pointer_down",event:t.nativeEvent,editor:n,container:i}))return;if(Lr(t.target))return;t.preventDefault(),i.focus(),i.setPointerCapture(t.pointerId);const o=i.getBoundingClientRect();s.current={left:o.left,top:o.top},a.current=t.pointerId,p(!0),f(1===t.button||0===t.button&&n.inputs.isSpacePressed.get()&&!n.getShapeEditingSession()),l.current=null,I();const d=Wr(t,s.current);n.setHoveredShapeId(null),n.dispatch(Hr("pointer_down",t,d,n.screenToPage(d)))},[e,n,I]),onAuxClick:Ex(e=>{1!==e.button||Lr(e.target)||(e.preventDefault(),e.stopPropagation())},[]),onContextMenu:Ex(e=>{const t=r.current;if(!t||!i||Lr(e.target))return;e.preventDefault(),e.stopPropagation();const o=t.getBoundingClientRect();if(s.current={left:o.left,top:o.top},null!==a.current){const i=a.current;t.hasPointerCapture(i)&&t.releasePointerCapture(i),a.current=null,l.current=null,p(!1),f(!1),b();const o=Wr(e,s.current);n.dispatch({type:"pointer",name:"pointer_cancel",timestamp:e.timeStamp,pointerId:i,button:e.button,buttons:0,pointerType:n.inputs.state.get().pointerType??"mouse",screenPoint:o,pagePoint:n.screenToPage(o),pressure:0,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey,clickCount:e.detail})}if(n.getShapeEditingSession())return;t.focus();const d=Wr(e,s.current),c=n.screenToPage(d),u=n.hitTestShape(c);let h;if(u){const e=n.getSelectedShapeIds(),t=e.find(e=>e===u.id||n.getDescendantShapeIds(e).includes(u.id))??n.getOutermostSelectableShapeId(u.id),i=e.includes(t);i||n.commands.setSelectedShapeIds([t],{source:"user"}),h={anchor:{screenPoint:d,pagePoint:c},target:{type:"selection",selectedShapeIds:i?e:[t]}}}else h={anchor:{screenPoint:d,pagePoint:c},target:{type:"canvas"}};i(h)},[n,i,b])},isPointerActive:h,isCameraPanning:g,surfaceCursor:m}}({activeDomEventGuards:c,activeToolId:u,editor:a,onContextMenuRequest:i,shapeEditingSession:h});
13
- return Hx("div",{ref:g,"data-ui":Ew,className:"land-canvas__surface",tabIndex:0,style:{cursor:y??Xr(u,m,S,p)},...f,children:[s?Nx(Yr,{}):null,Nx(Xv.Provider,{value:l,children:Nx(tw.Provider,{value:d,children:Hx(jr,{providers:t,children:[
14
- Nx(lr,{}),e?.map(({id:e,component:t})=>Nx(t,{},e)),
15
- Nx(Br,{})]})})})]})}function jr({children:e,providers:t}){
16
- return Nx(zx,{children:t?.reduceRight((e,{id:t,component:n})=>Nx(n,{children:e},t),e)??e})}function Vr(e){const t=e.trim();if(!t)return null;const n=(e=>/^[a-z][a-z0-9+.-]*:/i.test(e))(t)?t:`https://${t}`;return Gr(n)?n:null}function Gr(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol||"mailto:"===t.protocol}catch{return!1}}function Zr(e){Gr(e)&&window.open(e,"_blank","noopener,noreferrer")}function Qr(e){return{type:"doc",content:e.split("\n").map(e=>({type:"paragraph",content:e.length>0?[{type:"text",text:e}]:[]}))}}function Jr(e){return e.content.map(e=>ss(e)).join("\n")}function es(e){if(!e||"object"!=typeof e)return Qr("");const t=e,n=Array.isArray(t.content)?t.content.map(e=>us(e,0)).filter(e=>null!==e):[];return{type:"doc",attrs:bs(t.attrs),content:n}}function ts(e){return e.content.map(e=>(e=>{const t=e.content?.map(e=>ls(e)).join("")??"",n=is(e);return`<p style="${n?`margin:0;text-align:${n}`:"margin:0"}">${t.length>0?t:"<br>"}</p>`})(e)).join("")}function ns(e){return"text"===e.type&&"string"==typeof e.text}function is(e){if("paragraph"===e.type)return ys(e.attrs?.textAlign)}function os(e,t){const n=e?.some(e=>"code"===e.type)?void 0:t;if(!(e&&0!==e.length||n))return;const i=n?{backgroundColor:n}:{},o=new Set;for(const r of e??[])switch(r.type){case"bold":case"strong":i.fontWeight=700;break;case"italic":case"em":i.fontStyle="italic";break;case"strike":case"s":o.add("line-through");break;case"underline":case"u":o.add("underline");break;case"textStyle":{const e=gs(r.attrs);void 0!==e?.color&&(i.color=e.color),void 0!==e?.backgroundColor&&(i.backgroundColor=e.backgroundColor),void 0!==e?.fontFamily&&(i.fontFamily=e.fontFamily),void 0!==e?.fontSize&&(i.fontSize=e.fontSize),void 0!==e?.lineHeight&&(i.lineHeight=e.lineHeight);break}}return o.size>0&&(i.textDecorationLine=["line-through","underline"].filter(e=>o.has(e)).join(" ")),Object.keys(i).length>0?i:void 0}function rs(e){if(e&&0!==e.length)for(const t of e){if("link"!==t.type)continue;const e=t.attrs?.href;return"string"==typeof e?e:void 0}}function ss(e){return ns(e)?e.text:e.content?.map(e=>ss(e)).join("")??""}function as(e){const t=[];return void 0!==e.color&&t.push(`color:${e.color}`),void 0!==e.backgroundColor&&t.push(`background-color:${e.backgroundColor}`),void 0!==e.fontFamily&&t.push(`font-family:${e.fontFamily}`),void 0!==e.fontSize&&t.push(`font-size:${e.fontSize}`),void 0!==e.fontWeight&&t.push(`font-weight:${String(e.fontWeight)}`),void 0!==e.fontStyle&&t.push(`font-style:${e.fontStyle}`),void 0!==e.lineHeight&&t.push(`line-height:${e.lineHeight}`),void 0!==e.textDecorationLine&&t.push(`text-decoration-line:${e.textDecorationLine}`),t.join(";")}function ls(e){if(ns(e)){const t=os(e.marks),n=rs(e.marks),i=ds(e.text),o=t?`<span style="${cs(as(t))}">${i}</span>`:i;return n&&Gr(n)?`<a href="${cs(n)}" target="_blank" rel="noopener noreferrer">${o}</a>`:t?o:i}return e.content?.map(e=>ls(e)).join("")??""}function ds(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function cs(e){return ds(e).replaceAll('"',"&quot;")}function us(e,t){if(!e||"object"!=typeof e)return null;const n=e,i="string"==typeof n.type?n.type:"paragraph",o=Array.isArray(n.content)?n.content.map(e=>function(e,t){if(!e||"object"!=typeof e||t>8)return null;const n=e;if("text"===n.type){const e=(e=>({type:"text",text:"string"==typeof e.text?e.text:"",marks:Array.isArray(e.marks)?e.marks.map(hs).filter(e=>null!==e):void 0}))(n);return e.text.length>0?e:null}return us(n,t)}(e,t+1)).filter(e=>null!==e):[];return{type:i,attrs:ps(i,n.attrs),content:o}}function hs(e){if(!e||"object"!=typeof e)return null;const t=e;if("string"!=typeof t.type)return null;if("link"===t.type){const e=bs(t.attrs),n=e?.href;return"string"==typeof n&&Gr(n)?{type:"link",attrs:{...e,href:n}}:null}if("textStyle"===t.type){const e=gs(t.attrs);return e?{type:"textStyle",attrs:e}:null}return{type:t.type,attrs:bs(t.attrs)}}function ps(e,t){const n=bs(t);if("paragraph"!==e)return n;const i={...n};delete i.textAlign;const o=t&&"object"==typeof t&&!Array.isArray(t)?ys(t.textAlign):void 0;return void 0!==o&&(i.textAlign=o),Object.keys(i).length>0?i:void 0}function gs(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e,n={color:fs(t.color,128),backgroundColor:fs(t.backgroundColor,128),fontFamily:fs(t.fontFamily,256),fontSize:ms(t.fontSize),lineHeight:Ss(t.lineHeight)},i=Object.entries(n).filter(e=>void 0!==e[1]);return i.length>0?Object.fromEntries(i):void 0}function fs(e,t){if("string"!=typeof e)return;const n=e.trim();return 0===n.length||n.length>t||Rw.test(n)||Lw.test(n)?void 0:n}function ms(e){const t="string"==typeof e?$w.exec(e.trim()):null;if(!t||"px"!==t[2]?.toLowerCase())return;const n=Number(t[1]);return n>=1&&n<=512?`${String(n)}px`:void 0}function Ss(e){const t="string"==typeof e?$w.exec(e.trim()):null;if(!t)return;const n=Number(t[1]),i=t[2]?.toLowerCase()??"";return("px"===i?n>=1&&n<=1024:"%"===i?n>=50&&n<=1e3:n>=.5&&n<=10)?`${String(n)}${i}`:void 0}function ys(e){return"left"===e||"center"===e||"right"===e?e:void 0}function bs(e){if(!e||"object"!=typeof e)return;const t=Object.entries(e).map(([e,t])=>[e,xs(t)]).filter(e=>void 0!==e[1]);return t.length>0?Object.fromEntries(t):void 0}function xs(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=>xs(e,t+1)).filter(e=>void 0!==e);if(e&&"object"==typeof e){const n=Object.entries(e).map(([e,n])=>[e,xs(n,t+1)]).filter(e=>void 0!==e[1]);return Object.fromEntries(n)}}}function Is(e){return f(e)&&"text"===e.type}function vs(e){return{richText:e.richText,w:e.w,h:e.h,autoSize:e.autoSize,scale:e.scale,font:e.font,size:e.size,color:e.color,backgroundColor:e.backgroundColor,textAlign:e.textAlign}}function ws(e){return vs(e.getDefaultShapeProps("text"))}function Ps(e,t,n="user"){const i={...ws(e),...t.props,richText:t.props?.richText??Qr("")},[o]=e.commands.createShapes([{type:"text",x:t.x,y:t.y,parentId:t.parentId,index:t.index,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,meta:t.meta,props:{richText:i.richText,w:i.w,h:i.h,autoSize:i.autoSize,scale:i.scale,font:i.font,size:i.size,color:i.color,backgroundColor:i.backgroundColor,textAlign:i.textAlign}}],{source:n});if(!Is(o))throw new Error("Failed to create text shape");return o}function ks(e,t){return e?Math.min(e.paddingInline,Math.max(0,(t-1)/2)):0}function Cs(e,t){return de(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})?.rotation??t.rotation}function Ts(e,t,n,i){const o=e.getShapeUtil(t),r=de(e.computeShapeLocalToPageTransform(t),e.computeShapeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(!r)return null;const s={...t,...r,x:i.x,y:i.y,rotation:i.rotation,props:o.validateProps({...t.props,...i.props})},a=n.startsWith("shape:")?e.getShape(n):null;if(n.startsWith("shape:")&&!a)return null;const l=(a?e.computeShapeLocalToPageTransform(a):yI.Identity()).tryInvert();return l?de(l.compose(o.getLocalToPageTransform(s)),o.getLocalBounds(s),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY}):null}function Ms(e,t,n){const i=e.getBindingsToShape(t).find(e=>e.type===n);if(!i)return null;const o=e.getShape(i.fromId);return Is(o)?o:null}function Es(e,t){const n={...ws(e),...t.layout.props,autoSize:!1,textAlign:"middle"},i=Ts(e,{id:"shape:draft-label",typeName:"shape",scope:"document",type:"text",parentId:t.owner.parentId,index:t.index,x:0,y:0,rotation:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:n},t.owner.parentId,t.layout);if(!i)return null;const o=e.operations.begin({kind:t.historyMarkId,label:"shape.create",source:"user",history:"record"});try{const o=Ps(e,{x:i.x,y:i.y,parentId:t.owner.parentId,index:t.index,rotation:i.rotation,scaleX:i.scaleX,scaleY:i.scaleY,props:n},"user");return e.commands.createBinding({type:t.bindingType,fromId:o.id,toId:t.owner.id,props:t.bindingProps},{source:"user"}),o}catch(r){throw o.cancel(),r}}function As(e,t){const n=e.getShape(t);if(!Is(n))return null;const i=e.getBindingsFromShape(t).find(e=>e.type in Ow);if(!i)return null;const o=i.type;return{label:n,ownerId:i.toId,bindingType:o,behavior:Ow[o]}}function Bs(e,t,n,i){if("path-label"===i)return{minWidth:24,maxWidth:120,paddingInline:4.25};const o=Math.max(.01,t.props.scale);return{minWidth:16,maxWidth:Math.max(16,e.computeShapeLocalBounds(n).w/o),paddingInline:16}}function Rs(e,t){const n=As(e,t.id);if(!n)return null;const i=e.getShape(n.ownerId);return i?Bs(e,t,i,n.bindingType):null}function Ls(e,t,n){e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:n.isExisting?n.editMarkId:n.createMarkId,reuseActiveOperation:!n.isExisting},"user")}function $s(e,t,n){return e.content.map((e,i)=>((e,t,n,i)=>{const o=Fs(e,t,n,"codeBlock"===e.type?void 0:i);
17
- return Nx("p",{style:{margin:0,textAlign:is(e)},children:o.length>0?o:Nx("br",{})},t)})(e,`block:${i}`,t,n))}function Fs(e,t,n,i){return e.content?.map((e,o)=>((e,t,n,i)=>{if(ns(e)){const o=os(e.marks,i),r=rs(e.marks);return r&&Gr(r)?Nx("span",{"data-rich-text-link":"true","data-rich-text-link-href":r,onPointerEnter:e=>{n?.onPointerEnter?.({href:r,element:e.currentTarget})},onPointerLeave:()=>{n?.onPointerLeave?.()},style:{...o,cursor:n?"pointer":void 0,pointerEvents:n?"auto":"none",textDecorationLine:Us(o?.textDecorationLine)},children:e.text},t):Nx("span",{style:o,children:e.text},t)}return Fs(e,t,n,"codeBlock"===e.type?void 0:i)})(e,`${t}:${o}`,n,i))??[]}function Us(e){const t=new Set(e?.split(/\s+/u)??[]);return t.add("underline"),["line-through","underline"].filter(e=>t.has(e)).join(" ")}function Os(){return{defaultFont:zw,defaultFontLabel:"Default",fonts:[]}}function Ds(){return zs(Os())}function zs(e){const t=new Map;for(const n of e.fonts)Ns(n.id)&&"default"!==n.id&&t.set(n.id,n);return{defaultFont:e.defaultFont,defaultFontLabel:e.defaultFontLabel,fontOptions:[{id:Dw,label:e.defaultFontLabel,cssFamily:e.defaultFont.cssFamily,source:e.defaultFont.source},...t.values()],fontsById:t}}function Ns(e){return"string"==typeof e&&e.trim().length>0}function Hs(e,t){return"default"===t?e.defaultFont:e.fontsById.get(t)??e.defaultFont}function Ws(e,t,n){const i=Hs(t,e),o=n??("undefined"==typeof document?void 0:document);if(!o||!_s(i.source))return Promise.resolve();const r=(e=>{const{source:t}=e;return t&&"system"!==t.kind?"stylesheet"===t.kind?`${e.id}:stylesheet:${t.cssUrl}`:`${e.id}:font-face:${t.family}:${String(t.src)}`:e.id})(i),s=(e=>{const t=Nw.get(e);if(t)return t;const n=new Map;return Nw.set(e,n),n})(o),a=s.get(r);if(a)return a;const l=(async(e,t)=>{const{source:n}=t;if(_s(n))return"stylesheet"===n.kind?(await((e,t,n)=>Array.from(e.querySelectorAll("link[data-land-text-font]")).find(e=>e.dataset.landTextFont===t.id)?Promise.resolve():new Promise(i=>{const o=e.createElement("link");o.rel="stylesheet",o.href=n.cssUrl,o.dataset.landTextFont=t.id;const r=()=>i();o.addEventListener("load",r,{once:!0}),o.addEventListener("error",r,{once:!0}),(e.head??e.documentElement).appendChild(o)}))(e,t,n),void(await Ks(e,n))):(await(async(e,t)=>{const{fonts:n}=e,i=e.defaultView?.FontFace;if(!n||!i)return;if(Array.from(n).filter(e=>e.family===t.family&&"loaded"===e.status).length>0)return;const o=await new i(t.family,t.src,t.descriptors).load();n.add(o)})(e,n),void(await Ks(e,n)))})(o,i).catch(()=>{s.delete(r)});return s.set(r,l),l}function _s(e){return!!e&&"system"!==e.kind}async function Ks(e,t){const{fonts:n}=e;if(!n)return;const i=(e=>{if(e.weights)return e.weights;if("font-face"===e.kind){const t=e.descriptors?.weight;if("string"==typeof t&&/^\d+$/.test(t))return[Number(t)]}return[400]})(t),o=t.sampleText??"Aa";await Promise.all(i.map(e=>n.load(`${e} 16px "${t.family}"`,o)))}function Ys(e){return Hw.get(e)?.api??null}function Xs(e){const t=Hw.get(e);if(t)return t;const n={api:null,disposeApiSubscription:null,listeners:new Set};return Hw.set(e,n),n}function qs(e){for(const t of e.listeners)t()}function js(e,t){const n=Ww[t];let i=!1,o=!1;return Zs(e.content,(e,t)=>{"text"!==e.type||!e.text||t.insideCodeBlock||e.marks?.some(e=>"code"===e.type)||(e.marks?.some(e=>n.includes(e.type))?i=!0:o=!0)}),i&&o?"mixed":i}function Vs(e){const t=[];if(Zs(e.content,(e,n)=>{if("text"!==e.type||!e.text||n.insideCodeBlock||e.marks?.some(e=>"code"===e.type))return;const i=(e.marks?.find(e=>"textStyle"===e.type))?.attrs?.backgroundColor;t.push("string"==typeof i&&i.length>0?i:null)}),0===t.length)return null;const n=t[0]??null;return t.every(e=>e===n)?n:"mixed"}function Gs(e){if("paragraph"!==e.type||void 0===e.attrs?.textAlign)return e;const t={...e.attrs};return delete t.textAlign,{...e,attrs:Object.keys(t).length>0?t:void 0}}function Zs(e,t,n=!1){for(const i of e)t(i,{insideCodeBlock:n}),i.content&&Zs(i.content,t,n||"codeBlock"===i.type)}function Qs(e,t,n=!1){let i=!1;return{nodes:e.map(e=>{const o=t(e,{insideCodeBlock:n}),r=o.content;if(!r)return o!==e&&(i=!0),o;const s=Qs(r,t,n||"codeBlock"===o.type);return s.changed?(i=!0,{...o,content:s.nodes}):(o!==e&&(i=!0),o)}),changed:i}}function Js(e){try{return e.view.dom.isConnected}catch{return!1}}function ea(e){!e.isDestroyed&&Js(e)&&(e.view.dom.focus(),e.view.focus())}function ta(e){if(!Js(e))return{type:null,text:null};const t=(e=>{if(!e)return{type:null,text:null};const t=window.getSelection();if(!t||0===t.rangeCount)return{type:t?.type??null,text:null};const n=t.anchorNode,i=t.focusNode,o=e instanceof HTMLElement?e:e.parentElement,r=!!n&&!!i&&null!==o&&o.contains(n)&&o.contains(i);return{type:r?t.type:null,text:r?t.toString():null}})(e.view.dom);if(null!==t.type)return t;const n=e.state.selection;return{type:n.empty?"Caret":"Range",text:n.empty?"":e.state.doc.textBetween(n.from,n.to,"\n")}}function na(e,t=qw){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function ia(e,t){return Hs(t,e).cssFamily}function oa(e){return na(e)}function ra(e){const t=na(e);return jw[t]??Math.ceil(1.4*t)}function sa(e,t=1){return Math.max(1,Math.ceil(ra(e)*t))}function aa(e){switch(e){case"middle":return"center";case"end":return"right";default:return"left"}}function la(e,t,n,i){return 0===Jr(e).trim().length?da(t,i):ca(t,(o=ts(e),r={...ua(t,i),shape:t,fontCatalog:n},ha(document).measureHtml(o,r)),i);var o,r}function da(e,t){const n=t?t.minWidth:e.props.autoSize?16:e.props.w,i=sa(e.props.size);if(e.props.w!==n||e.props.h!==i)return{w:n,h:i}}function ca(e,t,n){const i=n?Math.min(n.maxWidth,Math.max(n.minWidth,Math.ceil(t.w+2*n.paddingInline))):e.props.autoSize?Math.max(16,Math.ceil(t.w)):e.props.w,o=Math.max(sa(e.props.size),Math.ceil(t.h));if(i!==e.props.w||o!==e.props.h)return{w:i,h:o}}function ua(e,t){if(t){const e=ks(t,t.maxWidth);return{maxWidth:Math.max(1,t.maxWidth-2*e)}}return e.props.autoSize?{}:{width:e.props.w}}function ha(e){const t=Gw.get(e);if(t)return t;const n=new Vw(e);return Gw.set(e,n),n}function pa(e,t,n){n&&"normal"!==n&&"auto"!==n&&(e.style[t]=n)}function ga(e,t,n){if(t.isDestroyed()||!t.isConnected())return;const i=t.measure(n);i&&ma(e,n,i,"user")}function fa(e,t,n,i="system"){const o=la(t.props.richText,t,n,Rs(e,t));o&&ma(e,t,o,i)}function ma(e,t,n,i){const o=e.getShape(t.id);Is(o)&&o.props.w===n.w&&o.props.h===n.h||e.commands.updateShapes([{id:t.id,props:n}],{source:i})}function Sa({editor:e,fontCatalog:t,landEditor:n,shapeId:i}){const o=()=>{const e=n.getShape(i);return Is(e)?e:null},r={shapeId:i,getSnapshot(){if(e.isDestroyed)return null;const n=o();return n?(({editor:e,fontCatalog:t,shape:n})=>{const i=e.state.selection,o=(e=>{const{selection:t,doc:n}=e.state;return t.empty?{from:0,to:n.content.size}:{from:t.from,to:t.to}})(e),r=i.empty?"shape":"selection",s=U(n.props.color),a=O(n.props.backgroundColor)?null:U(n.props.backgroundColor),l=n.props.textAlign;return{shapeId:n.id,target:r,bold:wa(e,o,"bold"),italic:wa(e,o,"italic"),strike:wa(e,o,"strike"),underline:wa(e,o,"underline"),color:Pa(e,o,"color",s),backgroundColor:Pa(e,o,"backgroundColor",0===e.state.doc.textContent.length?a:null),font:Ma(Pa(e,o,"fontFamily",n.props.font),e=>((e,t)=>t.fontOptions.find(t=>t.cssFamily===e)?.id??e)(e,t)),size:Ma(Pa(e,o,"fontSize",n.props.size),e=>((e,t)=>{if("number"==typeof e)return e;const n=Number.parseFloat(e);return Number.isFinite(n)&&n>0?n:t})(e,n.props.size)),textAlign:ka(e,o,l),linkHref:Ca(e),canSetLink:!i.empty||e.isActive("link")}})({editor:e,fontCatalog:t,shape:n}):null},subscribe(t){if(e.isDestroyed)return()=>{};const o=()=>t();e.on("transaction",o),e.on("focus",o),e.on("blur",o);const r=Jo(`TextFormattingApi(${i})`,n.getShapeSignal(i),o,{fireImmediately:!1});return()=>{r(),e.off("transaction",o),e.off("focus",o),e.off("blur",o)}},focus(){e.isDestroyed||e.commands.focus()},toggle:t=>((e,t,n)=>{if(e.isDestroyed||void 0===e.schema.marks[t])return!1;const i=e.state.selection;if(!i.empty)return e.chain().focus().toggleMark(t).run();const o=!0!==n?.[t];if(0===e.state.doc.textContent.length){const n=e.chain().focus();return(o?n.setMark(t):n.unsetMark(t)).run()}let r=e.chain().focus().selectAll();return r=o?r.setMark(t):r.unsetMark(t),r=r.setTextSelection(va(i)),r=o?r.setMark(t):r.unsetMark(t),r.run()})(e,t,r.getSnapshot()),setColor(t){if(null!==t&&!Ea(t))return!1;const i=o();return!!i&&(({editor:e,landEditor:t,shape:n,color:i})=>{if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;if(!e.state.selection.empty)return null===i?e.chain().focus().unsetColor().run():e.chain().focus().setColor(i).run();const o=ba(e,"color");return null!==i&&Ia(t,n,{color:E(i)}),o||null!==i})({editor:e,landEditor:n,shape:i,color:t})},setBackgroundColor(t){if(null!==t&&!Ea(t))return!1;const i=o();return!!i&&(({editor:e,landEditor:t,shape:n,color:i})=>{if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;const o=e.state.selection,r=e=>null===i?e.unsetBackgroundColor():e.setBackgroundColor(i);if(!o.empty)return Ia(t,n,{backgroundColor:E("transparent")}),r(e.chain().focus()).run();const s=r(r(e.chain().focus().selectAll()).setTextSelection(va(o))).run();return Ia(t,n,{backgroundColor:E(i??"transparent")}),s})({editor:e,landEditor:n,shape:i,color:t})},setFont(i){const r=o();if(!r)return!1;if(null===i)return ya({editor:e,font:null,fontFamily:null,landEditor:n,shape:r});const s=t.fontOptions.find(e=>e.id===i);return!!s&&(Ws(i,t).then(()=>{const e=o();e&&fa(n,e,t,"system")}),ya({editor:e,fontFamily:s.cssFamily,font:i,landEditor:n,shape:r}))},setSize(t){const i=null===t?null:Math.round(1e3*t)/1e3;if(null!==t&&(!Number.isFinite(t)||t<1||t>512||null===i||Math.abs(t-i)>Number.EPSILON*Math.max(1,Math.abs(t))))return!1;const r=o();return!!r&&(({editor:e,landEditor:t,shape:n,size:i})=>{if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;const o=e.state.selection,r=null===i?null:`${i}px`,s=null===i?null:`${ra(i)}px`;if(!o.empty)return(a=e.chain().focus(),null===r||null===s?a.unsetFontSize().unsetLineHeight():a.setFontSize(r).setLineHeight(s)).run();var a;const l=(e=>{const t=e.state.selection;let n=e.chain().focus();return e.state.doc.textContent.length>0&&(n=n.selectAll()),xa(n.unsetFontSize().unsetLineHeight().setTextSelection(va(t)).unsetFontSize().unsetLineHeight()).run()})(e);return null!==i&&Ia(t,n,{size:i}),l||null!==i})({editor:e,landEditor:n,shape:r,size:i})},setTextAlign(t){const i=o();return!!i&&(({editor:e,landEditor:t,shape:n,align:i})=>{if(e.isDestroyed)return!1;const o=(e=>{switch(e){case"middle":return"center";case"end":return"right";default:return"left"}})(i),r=e.state.selection;if(!r.empty)return e.chain().focus().setTextAlign(o).run();const s=e.chain().focus().selectAll().unsetTextAlign().setTextSelection(va(r)).run();return Ia(t,n,{textAlign:i}),s||n.props.textAlign!==i})({editor:e,landEditor:n,shape:i,align:t})},setLink(t){if(e.isDestroyed||void 0===e.schema.marks.link)return!1;const n=null===t?null:Vr(t);if(null!==t&&null===n)return!1;const{empty:i}=e.state.selection,o=e.isActive("link");if(null===n)return!!o&&e.chain().focus().extendMarkRange("link").unsetLink().run();if(i&&!o)return!1;const r=e.chain().focus();return(i?r.extendMarkRange("link"):r).setLink({href:n}).run()},clearFormatting(){if(e.isDestroyed)return!1;const t=o();t&&Ia(n,t,{backgroundColor:E("transparent")});const i=e.state.selection;return i.empty?e.chain().focus().selectAll().unsetAllMarks().unsetTextAlign().setTextSelection(va(i)).command(({tr:e})=>(e.setStoredMarks([]),!0)).run():e.chain().focus().unsetAllMarks().unsetTextAlign().run()},getUnsafeTiptapEditor:()=>e.isDestroyed?null:e};return r}function ya({editor:e,font:t,fontFamily:n,landEditor:i,shape:o}){if(e.isDestroyed||void 0===e.schema.marks.textStyle)return!1;if(!e.state.selection.empty)return null===n?e.chain().focus().unsetFontFamily().run():e.chain().focus().setFontFamily(n).run();const r=ba(e,"fontFamily");return null!==t&&i&&o&&Ia(i,o,{font:t}),r||null!==t}function ba(e,t){const n=e.state.selection;let i=e.chain().focus();return e.state.doc.textContent.length>0&&(i=i.selectAll()),i="color"===t?i.unsetColor():i.unsetFontFamily(),i=i.setTextSelection(va(n)),i="color"===t?i.unsetColor():i.unsetFontFamily(),xa(i).run()}function xa(e){return e.command(({state:e,tr:t})=>{const n=e.schema.marks.textStyle;if(!n)return!0;const i=(t.storedMarks??e.storedMarks)?.find(e=>e.type===n);return i&&Object.values(i.attrs).every(e=>null==e||""===e)&&t.removeStoredMark(n),!0})}function Ia(e,t,n){e.commands.updateShapes([{id:t.id,props:n}],{source:"user"})}function va(e){return e.from===e.to?e.from:{from:e.from,to:e.to}}function wa(e,t,n){if(!e.schema.marks[n])return!1;const i=[];return e.state.doc.nodesBetween(t.from,t.to,(e,t,o)=>{const r=o?.type.schema.marks[n];e.isText&&r&&o?.type.allowsMarkType(r)&&!e.marks.some(e=>"code"===e.type.name)&&i.push(e.marks.some(e=>e.type.name===n))}),0===i.length?(e.state.storedMarks??e.state.selection.$from.marks()).some(e=>e.type.name===n):Ta(i)??!1}function Pa(e,t,n,i){const o=[];if(e.state.doc.nodesBetween(t.from,t.to,(e,t,r)=>{if(!e.isText)return;if("backgroundColor"===n&&(e.marks.some(e=>"code"===e.type.name)||"codeBlock"===r?.type.name))return;const s=e.marks.find(e=>"textStyle"===e.type.name)?.attrs[n];o.push("string"==typeof s&&s.length>0?s:i)}),0===o.length){const t=(e.state.storedMarks??e.state.selection.$from.marks()).find(e=>"textStyle"===e.type.name)?.attrs[n];return"string"==typeof t&&t.length>0?t:i}return Ta(o)}function ka(e,t,n){const i=[];return e.state.doc.nodesBetween(t.from,t.to,e=>{e.isTextblock&&i.push(((e,t)=>{switch(e){case"center":return"middle";case"right":return"end";case"left":return"start";default:return t}})(e.attrs.textAlign,n))}),Ta(i)??n}function Ca(e){const t=e.getAttributes("link").href;return"string"==typeof t&&t.length>0?t:null}function Ta(e){if(0===e.length)return null;const t=e[0];return e.every(e=>Object.is(e,t))?t:"mixed"}function Ma(e,t){return null===e?null:"mixed"===e?"mixed":t(e)}function Ea(e){const t=e.trim();return t.length>0&&t.length<=128&&!Zw.test(t)&&!Qw.test(t)}function Aa({shapeId:e,editor:t,fontCatalog:n,landEditor:i}){return{shapeId:e,formatting:Sa({editor:t,fontCatalog:n,landEditor:i,shapeId:e}),isDestroyed:()=>t.isDestroyed,isConnected:()=>!t.isDestroyed&&Js(t),isFocused:()=>!t.isDestroyed&&Js(t)&&t.view.dom.contains(document.activeElement),getValue:()=>es(t.getJSON()),setValue(e){t.commands.setContent(e)},focus(){ea(t)},focusEnd(){!t.isDestroyed&&Js(t)&&t.commands.focus("end")},focusSelectAll(){!t.isDestroyed&&Js(t)&&(ea(t),t.chain().focus().selectAll().run())},focusAtPagePoint(e,n){((e,t,n)=>{ea(t);const i=e.pageToScreen(new mI(n.x,n.y)),o=t.view.posAtCoords({left:i.x,top:i.y})?.pos;o?t.chain().focus().setTextSelection(o).run():t.chain().focus().selectAll().run()})(e,t,n)},getSelectionSnapshot:()=>t.isDestroyed||!Js(t)?{type:null,text:null}:ta(t),collapseSelectionAtClientPoint(e,n){!t.isDestroyed&&Js(t)&&"Range"===ta(t).type&&((e,t,n)=>{if(e.isDestroyed||!Js(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&&Js(t))return function(e,t,n,i){if(0===e.getText().trim().length)return da(t,i);const o=((e,t)=>{const n=e.ownerDocument.defaultView?.getComputedStyle(e);return ha(e.ownerDocument).measureElement(e,t,n)})(e.view.dom,{shape:t,fontCatalog:n,...ua(t,i)});return!i&&e.view.dom.scrollHeight>t.props.h+1&&(o.h=Math.max(o.h,e.view.dom.scrollHeight)),ca(t,o,i)}(t,e,n,Rs(i,e))},onCompositionStateChange(e){if(t.isDestroyed)return()=>{};const n=t.view.dom,i=()=>e(!0),o=()=>e(!1);return n.addEventListener("compositionstart",i),n.addEventListener("compositionend",o),()=>{n.removeEventListener("compositionstart",i),n.removeEventListener("compositionend",o),e(!1)}}}}function Ba({landEditor:e,shape:t,fontCatalog:n,initialRichText:i,className:o,editorStyle:r,formattingToolbar:s,onTiptapEditorChange:a,onReady:l,onDispose:d,onRichTextChange:c}){const u=Ux(null),h=O(t.props.backgroundColor)?null:U(t.props.backgroundColor),p=h&&i.content.length>0?((e,t)=>{const n=Qs(e.content,(e,n)=>{if("text"!==e.type||!e.text||n.insideCodeBlock||e.marks?.some(e=>"code"===e.type))return e;const i=e.marks??[],o=i.findIndex(e=>"textStyle"===e.type);if(o<0)return{...e,marks:[...i,{type:"textStyle",attrs:{backgroundColor:t}}]};const r=i[o]?.attrs?.backgroundColor;return"string"==typeof r&&r.length>0?e:{...e,marks:i.map((e,n)=>n===o?{...e,attrs:{...e.attrs,backgroundColor:t}}:e)}});return n.changed?es({...e,content:n.nodes}):e})(i,h):i,g=Ex(i=>{const o=u.current;if(o?.editor===i)return o.controller;const r=Aa({shapeId:t.id,editor:i,fontCatalog:n,landEditor:e});return u.current={editor:i,controller:r},r},[n,e,t.id]),f=_x({extensions:eP,content:p,autofocus:!1,editable:!0,immediatelyRender:!0,shouldRerenderOnTransaction:!1,editorProps:{attributes:{"data-ui":"rich-text-editor",class:"land-text-editor__content",dir:"auto"},handleKeyDown:(t,n)=>(n.stopPropagation(),!(n.isComposing||("Escape"===n.key?(n.preventDefault(),e.cancelEditing("user"),0):"Enter"!==n.key||!n.metaKey&&!n.ctrlKey||(n.preventDefault(),e.completeEditing("user"),0))))},onUpdate:({editor:e})=>{const t=g(e);c({editor:e,controller:t,richText:t.getValue()})}},[t.id]);return Bx(()=>{if(!f||f.isDestroyed)return;const n=g(f),i={shapeId:t.id,editor:f,controller:n,formatting:n.formatting},o={shapeId:t.id,formatting:n.formatting},r=!1===s?()=>{}:((e,t)=>{const n=Xs(e);return n.disposeApiSubscription?.(),n.api=t,n.disposeApiSubscription=t.subscribe(()=>{qs(n)}),qs(n),()=>{n.api===t&&(n.disposeApiSubscription?.(),n.disposeApiSubscription=null,n.api=null,qs(n))}})(e,n.formatting);return l(i),a?.(o),()=>{r(),u.current?.editor===f&&(u.current=null),d(i),a?.(null)}},[g,s,e,d,l,a,t.id,f]),Nx(Wx,{editor:f,className:o,style:r})}function Ra({editor:e,controller:t,shapeId:n,request:i,onApplied:o,attempt:r=0}){if(!t.isDestroyed())if(t.isConnected())(({editor:e,controller:t,shapeId:n,request:i,onApplied:o})=>{if(!t.isDestroyed())t.focus(),i&&i.shapeId===n?"selectAll"===i.entryMode?(window.requestAnimationFrame(()=>{!t.isDestroyed()&&t.isConnected()&&t.focusSelectAll()}),e.consumeShapeEditingEntryRequest(i.id),o?.(i)):"placeCaret"===i.entryMode&&i.caretPagePoint?(t.focusAtPagePoint(e,i.caretPagePoint),e.consumeShapeEditingEntryRequest(i.id),o?.(i)):(t.focusEnd(),e.consumeShapeEditingEntryRequest(i.id),o?.(i)):(t.focusEnd(),o?.(i))})({editor:e,controller:t,shapeId:n,request:i,onApplied:o});else{if(r>=4)return;window.requestAnimationFrame(()=>{Ra({editor:e,controller:t,shapeId:n,request:i,onApplied:o,attempt:r+1})})}}function La({shapeId:e,markId:t,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o}){const r=ir(),s=or(r.getShapeSignal(e)),a=or(r.shapeEditingStateSignal).session;return Is(s)&&a?.shapeId===s.id?Nx($a,{shape:s,session:a,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o},`${s.id}:${t}`):null}function $a({shape:e,session:t,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o}){const r=ir(),s=Ux(e.props.richText),a=(e=>{const t=Ux(e);return Bx(()=>{t.current=e},[e]),t})(e),l=or(r.shapeEditingEntryRequestSignal),d=Ux(null),[c,u]=Ox(null),[h,p]=Ox(null),g=Ex(({editor:e,controller:t})=>{u(e.isDestroyed?null:e),p(t)},[]),f=Ex(({editor:e,controller:t})=>{u(t=>t===e?null:t),p(e=>e===t?null:e)},[]),m=function({editor:e,shape:t,tiptapEditor:n,richTextController:i,latestShapeRef:o,fontCatalog:r}){const s=Ux(t.props.richText),a=Ux(!1),l=Ux(null),d=Ex(({controller:n,richText:i})=>{if(a.current||!n.isConnected())return;const d=es(i);s.current=d,((e,t,n,i,o="user")=>{const r=e.getShape(t);Is(r)&&e.commands.updateShapes([{id:r.id,props:{richText:n,..."number"==typeof i?.w?{w:i.w}:null,..."number"==typeof i?.h?{h:i.h}:null}}],{source:o})})(e,t.id,d,n.measure(o.current)??la(d,o.current,r,Rs(e,o.current)),"user"),((e,t,n,i)=>{null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,ga(e,t,n.current)},0)})(e,n,o,l)},[e,r,o,t.id]);return Bx(()=>()=>{null!==l.current&&(window.clearTimeout(l.current),l.current=null)},[]),$x(()=>{n&&i&&!n.isDestroyed&&i.isConnected()&&ga(e,i,t)},[e,i,t,n]),Bx(()=>{if(!n||!i||!i.isConnected())return;const e=t.props.richText;e!==s.current&&(JSON.stringify(s.current)!==JSON.stringify(e)?(a.current=!0,i.setValue(e),s.current=e,a.current=!1):s.current=e)},[i,t.props.richText,n]),Bx(()=>{if(i)return i.onCompositionStateChange(t=>{e.setShapeEditingComposition(t,"system")})},[e,i]),Bx(()=>{if(!i||!i.isConnected())return;let n=!1;return Ws(t.props.font,r).then(()=>{!n&&i.isConnected()&&ga(e,i,o.current)}),()=>{n=!0}},[e,r,o,i,t.props.font]),d}({editor:r,shape:e,tiptapEditor:c,richTextController:h,latestShapeRef:a,fontCatalog:n}),S=Ex(()=>{c&&((e,t)=>{!(!t||e.isDestroyed||e.state.doc.textContent.length>0||e.getAttributes("textStyle").backgroundColor===t)&&e.commands.setBackgroundColor(t)})(c,O(e.props.backgroundColor)?null:U(e.props.backgroundColor))},[e.props.backgroundColor,c]);(({editor:e,shapeId:t,session:n,tiptapEditor:i,richTextController:o,entryRequest:r,consumedEntryRequestIdRef:s,onEntryFocusApplied:a})=>{const l=Ux(null),d=Ux(null);Bx(()=>{if(!o||o.isDestroyed()||!o.isConnected())return;let e=!1,t=null,n=0;const i=()=>{e||o.isDestroyed()||null===s.current&&(o.isFocused()||(o.focus(),n+=1,o.isFocused()||n>=4||(t=window.setTimeout(i,16))))},r=window.requestAnimationFrame(()=>{i()});return()=>{e=!0,window.cancelAnimationFrame(r),null!==t&&window.clearTimeout(t)}},[s,o,t]),Bx(()=>{i&&!i.isDestroyed&&o&&null===s.current&&d.current!==n.markId&&(d.current=n.markId,window.setTimeout(()=>{Ra({editor:e,controller:o,shapeId:t,request:{id:-1,shapeId:n.shapeId,entryMode:n.entryMode,caretPagePoint:n.caretPagePoint},onApplied:a})},0))},[s,e,o,n.caretPagePoint,n.entryMode,n.markId,n.shapeId,t,i,a]),Bx(()=>{i&&!i.isDestroyed&&o&&r&&r.shapeId===t&&s.current!==r.id&&Ra({editor:e,controller:o,shapeId:t,request:r,onApplied(e){e&&(s.current=e.id),a?.()}})},[s,e,r,o,t,i,a]),Bx(()=>{if(!i||!o||i.isDestroyed||!o.isConnected())return;const t=o;"selectAll"===n.entryMode&&window.requestAnimationFrame(()=>{"Range"!==t.getSelectionSnapshot().type&&t.focusSelectAll()});const r=l.current,s=n.caretPagePoint;if("placeCaret"===n.entryMode&&s&&(r?.markId!==n.markId||r.entryMode!==n.entryMode)){l.current={markId:n.markId,entryMode:n.entryMode};const i={x:s.x,y:s.y};window.requestAnimationFrame(()=>{Ra({editor:e,controller:t,shapeId:n.shapeId,request:{id:-1,shapeId:n.shapeId,entryMode:"placeCaret",caretPagePoint:i},onApplied:a})})}},[e,n.caretPagePoint,n.entryMode,n.markId,n.shapeId,o,i,a])})({editor:r,shapeId:e.id,session:t,tiptapEditor:c,richTextController:h,entryRequest:l,consumedEntryRequestIdRef:d,onEntryFocusApplied:S});const y=(({editor:e,shapeId:t,richTextController:n})=>{const i=Ux(null);return{onPointerDownCapture:Ex(o=>{if(o.stopPropagation(),0!==o.button||1!==o.detail||!n||n.isDestroyed())return void(i.current=null);const r=e.getShapeEditingSession();i.current=r&&r.shapeId===t&&!r.isComposing&&"Range"===n.getSelectionSnapshot().type?{pointerId:o.pointerId,clientX:o.clientX,clientY:o.clientY,moved:!1}:null},[e,n,t]),onPointerMoveCapture:Ex(e=>{const t=i.current;if(!t||t.pointerId!==e.pointerId)return;const n=e.clientX-t.clientX,o=e.clientY-t.clientY;n*n+o*o>=16&&(t.moved=!0)},[]),onPointerUpCapture:Ex(o=>{const r=i.current;if(i.current=null,!r||r.pointerId!==o.pointerId||r.moved||!n||n.isDestroyed())return;const s=e.getShapeEditingSession();if(!s||s.shapeId!==t||s.isComposing)return;const a=o.clientX,l=o.clientY;window.setTimeout(()=>{n.isDestroyed()||"Range"!==n.getSelectionSnapshot().type||n.collapseSelectionAtClientPoint(a,l)},0)},[e,n,t]),onPointerCancel:Ex(()=>{i.current=null},[])}})({editor:r,shapeId:e.id,richTextController:h}),b=((e,t,n=0)=>Fx(()=>({color:F(e.props.color),fontFamily:ia(e.props.font,t),fontSize:oa(e.props.size),lineHeight:`${ra(e.props.size)}px`,textAlign:aa(e.props.textAlign),pointerEvents:"auto",userSelect:"text",cursor:"text",boxSizing:"border-box",position:"absolute",inset:0,width:"100%",height:"100%",paddingInline:n}),[e.props.color,e.props.font,e.props.size,e.props.textAlign,t,n]))(e,n,ks(Rs(r,e),e.props.w)),x=Ex(e=>{if(!e.ctrlKey&&!e.metaKey)return;const t=(e=>{const t=e.target;return t instanceof Element?t.closest("[data-rich-text-link-href]")?.getAttribute("data-rich-text-link-href")??null:null})(e.nativeEvent);t&&c&&!c.isDestroyed&&(e.preventDefault(),e.stopPropagation(),Zr(t))},[c]);
18
- return Nx("div",{"data-ui":"text-editing-box","data-shape-id":e.id,"data-mount-target-kind":"shape",onPointerDown:e=>{e.stopPropagation()},onClickCapture:x,onPointerDownCapture:y.onPointerDownCapture,onPointerMoveCapture:y.onPointerMoveCapture,onPointerUpCapture:y.onPointerUpCapture,onPointerCancel:y.onPointerCancel,onContextMenu:e=>{e.stopPropagation()},onDragStart:e=>{e.preventDefault()},style:b,children:Nx(Ba,{landEditor:r,shape:e,fontCatalog:n,initialRichText:s.current,className:"land-text-editor__content",formattingToolbar:i,editorStyle:{height:"100%",minHeight:"100%"},onReady:g,onDispose:f,onTiptapEditorChange:o,onRichTextChange:m})})}function Fa({children:e,presenter:t}){
19
- return Nx(tP.Provider,{value:t,children:e})}function Ua(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t}: ${i}.`);n.add(i)}}function Oa({fontCatalog:e=Ds(),formattingToolbar:t,onTiptapEditorChange:n}={}){return{id:"land.text.react",domEventGuards:[iP],canvasComponents:[{id:"land.text.default-font-preload",component:()=>Nx(Da,{fontCatalog:e})}],shapeRenderers:[{type:"text",hoverComponent:Na,component:i=>Nx(za,{...i,fontCatalog:e,formattingToolbar:t,onTiptapEditorChange:n})}]}}function Da({fontCatalog:e}){return Bx(()=>{Ws(Dw,e)},[e]),null}function za({shape:e,editor:t,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o}){const[r,s]=Ox(null),a=Ux(null),l=or(t.selectedShapeIdsSignal),d=Ax(tP),{hasEditingSession:c,isEditingThisShape:u,editingHost:h}=function(e,t,n,i,o){const r=or(e.shapeEditingStateSignal).session,s=r?.shapeId===t.id,a=r&&s?Nx(La,{shapeId:r.shapeId,markId:r.markId,fontCatalog:n,formattingToolbar:i,onTiptapEditorChange:o},r.shapeId+":"+r.markId):null;return(({editor:e,shape:t,isEditingThisShape:n,fontCatalog:i})=>{$x(()=>{if(n)return;fa(e,t,i);let o=!1;return Ws(t.props.font,i).then(()=>{if(o)return;const n=e.getShape(t.id);Is(n)&&n.props.font===t.props.font&&fa(e,n,i)}),()=>{o=!0}},[e,i,n,t,t.props.autoSize,t.props.font,t.props.richText,t.props.scale,t.props.size,t.props.textAlign,t.props.w])})({editor:e,shape:t,isEditingThisShape:s,fontCatalog:n}),{hasEditingSession:null!==r,isEditingThisShape:s,editingHost:a}}(t,e,n,i,o),p=ks(Rs(t,e),e.props.w),g=null!==d&&(({isEditing:e,isOnlySelected:t})=>!e&&!t)({isEditing:c,isOnlySelected:1===l.length&&l[0]===e.id}),f=Ex(()=>{null!==a.current&&(window.clearTimeout(a.current),a.current=null)},[]),m=Ex(()=>{f(),a.current=window.setTimeout(()=>{s(null),a.current=null},160)},[f]);return Bx(()=>()=>{f()},[f]),Bx(()=>{g||(f(),s(null))},[g,f]),Hx("div",{"data-editing-hidden":u?"true":void 0,style:{position:"relative",boxSizing:"border-box",width:e.props.w,minHeight:e.props.h,transform:`scale(${e.props.scale})`,transformOrigin:"top left",color:F(e.props.color),fontFamily:ia(e.props.font,n),fontSize:oa(e.props.size),lineHeight:`${ra(e.props.size)}px`,textAlign:aa(e.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none"},children:[
20
- Nx("div",{style:{boxSizing:"border-box",opacity:u?0:void 0,paddingInline:p,width:"100%"},children:$s(e.props.richText,g?{onPointerEnter({href:e,element:t}){f(),s({anchorElement:t,href:e})},onPointerLeave(){m()}}:void 0,O(e.props.backgroundColor)?void 0:F(e.props.backgroundColor))}),g&&r&&d?Nx(d,{anchorElement:r.anchorElement,href:r.href,onOpen:()=>{Zr(r.href)},onPopoverPointerEnter:f,onPopoverPointerLeave:m}):null,
21
- Nx("div",{"data-ui":"text-editor-host-slot","data-shape-id":e.id,"data-active":u?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:h})]})}function Na({strokeWidth:e}){
22
- return Nx("div",{"data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 ${e}px ${qv}`,inset:0,position:"absolute"}})}function Ha(e){return vs(e)}function Wa(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function _a(e){return Math.max(.01,e.props.scale)}function Ka(e){return e.props.w*_a(e)}function Ya(e){return e.props.h*_a(e)}function Xa(e){return new SI(0,0,Ka(e),Ya(e))}function qa(e){return"left"===e||"right"===e}function ja(e,t){return e.content.map(e=>((e,t)=>{const n="codeBlock"===e.type?void 0:t,i=e.content?.map(e=>Va(e,n))??[],o=is(e);return{tag:"p",attrs:{style:o?`margin:0;text-align:${o}`:"margin:0"},children:i.length>0?i:[{tag:"br"}]}})(e,t))}function Va(e,t){if(ns(e)){const n=((e,t)=>{const n=os(e.marks,t);return n?as(n):void 0})(e,t);return n?{tag:"span",attrs:{style:n},children:[e.text]}:e.text}return{tag:"span",children:e.content?.map(n=>Va(n,"codeBlock"===e.type?void 0:t))??[]}}function Ga(e,t,n,i){return[`color:${t.resolveColor(e.props.color)}`,`font-family:${ia(e.props.font,n)}`,`font-size:${oa(e.props.size)}px`,`line-height:${ra(e.props.size)}px`,`text-align:${aa(e.props.textAlign)}`,"white-space:pre-wrap","overflow-wrap:break-word","box-sizing:border-box",`padding-inline:${i}px`,`width:${e.props.w}px`,`height:${e.props.h}px`,`transform:scale(${e.props.scale})`,"transform-origin:top left"].join(";")}function Za(e){return"binding"===e?.typeName&&"path-label"===e.type}function Qa(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function Ja(e,t,n,i=.5){const o=el(e,n),r=o?tl(e,t,o):{start:0,end:1},s=Math.min(r.end,Math.max(r.start,i)),a=o?.getPointAt(s)??e.computeShapePageCenter(n),l=Bs(e,t,n,Fw),d=Math.min(l.maxWidth,Math.max(l.minWidth,t.props.w));return{x:a.x-d*t.props.scale/2,y:a.y-t.props.h*t.props.scale/2,rotation:Cs(e,n),props:{w:d}}}function el(e,t){return e.getShapeUtil(t).getLabelPathGeometry(t,{editor:e})}function tl(e,t,n){if(n.length<=1e-6)return{start:.5,end:.5};const i=e.getShapePageBounds(t.id);if(!i)return{start:0,end:1};const o=Math.hypot(i.w,i.h)/2,r=Math.min(.5,(o+8)/n.length);return{start:r,end:1-r}}function nl(e){return"shape"===e?.typeName&&"geo"===e.type}function il(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function ol(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function rl(e,t){const n=e.props[t];return"number"==typeof n&&Number.isFinite(n)?n:null}function sl(e,t){const n=rl(e,"h");return!n||t.props.ownerBaseHeight<=0||n===t.props.ownerBaseHeight?null:{...e,props:{...e.props,h:t.props.ownerBaseHeight}}}function al(e,t,n){const i=e.computeShapePageCenter(n),o=Bs(e,t,n,Uw),r=Math.min(o.maxWidth,Math.max(o.minWidth,t.props.w));return{x:i.x-r*t.props.scale/2,y:i.y-t.props.h*t.props.scale/2,rotation:Cs(e,n),props:{w:r}}}function ll(){let e=null,t=null;const n=()=>{e=null,t=null};return{id:"land.text.interactions",editorEvent:{handleEvent(i,o){if("cancel"===o.type)return n(),"continue";if("select"!==i.getActiveToolId())return"continue";if("pointer"===o.type&&"pointer_up"===o.name)return((e,t,n,i)=>{if(!n||n.pointerId!==t.pointerId)return i(),"continue";if(i(),(t.clickCount??1)>=2)return"continue";const o=t.pagePoint.x-n.originPagePoint.x,r=t.pagePoint.y-n.originPagePoint.y;if(o*o+r*r>9)return"continue";const s=e.getShape(n.shapeId);s&&Is(s)&&e.canEditShape(s)&&e.startEditingShape({shapeId:s.id,entryMode:"placeCaret",caretPagePoint:t.pagePoint,markId:fP,preserveInteraction:!0},"user")})(i,o,e,()=>{e=null}),((e,t,n,i)=>{if(!n||n.pointerId!==t.pointerId)return i(),"continue";if(i(),(t.clickCount??1)>=2)return"continue";const o=t.pagePoint.x-n.originPagePoint.x,r=t.pagePoint.y-n.originPagePoint.y;if(o*o+r*r>9)return"continue";const s=e.getShape(n.shapeId),a=e.getSelectedShapeIds();if(!s||!dl(s)||s.isLocked||e.getShapeEditingSession()||1!==a.length||a[0]!==s.id||Ms(e,s.id,"geo-label"))return"continue";const l=ul(e,s);return l&&Ls(e,l,{editMarkId:bP,createMarkId:xP,isExisting:!1}),"continue"})(i,o,t,()=>{t=null});if("pointer"===o.type&&"pointer_cancel"===o.name)return n(),"continue";if(!i.isActiveToolInInitialState())return"continue";if("keyboard"===o.type&&"key_down"===o.name){if(i.getShapeEditingSession())return"continue";if("Enter"!==o.key||o.altKey||o.accelKey)return"continue";const e=i.getSelectedShapeIds(),[t]=i.getSelectedShapes();return 1===e.length&&t&&Is(t)&&i.canEditShape(t)?(i.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:fP},"user"),"handled"):"continue"}if("click"===o.type&&"double_click"===o.name)return n(),((e,t)=>{const n=e.hitTestShape(t.pagePoint);return n?Is(n)?e.canEditShape(n)?(e.startEditingShape({shapeId:n.id,entryMode:"selectAll",markId:fP},"user"),"handled"):"continue":dl(n)?((e,t)=>{if(t.isLocked)return"continue";const n=Ms(e,t.id,Uw),i=n??ul(e,t);return i?(Ls(e,i,{editMarkId:bP,createMarkId:xP,isExisting:!!n}),"handled"):"handled"})(e,n):el(e,n)?((e,t,n)=>{if(t.isLocked)return"continue";const i=Ms(e,t.id,Fw),o=i??((e,t,n)=>{const i=el(e,t);if(!i)return null;const o=hl(t,{...ws(e),autoSize:!1,textAlign:"middle"}),r=i.getNearestPosition(n,{hintPosition:i.defaultPosition}),s=Ja(e,o,t,r),a=Es(e,{bindingType:Fw,owner:t,historyMarkId:SP,index:`${t.index}${uP}`,layout:s,bindingProps:{labelPosition:r}});if(!a)return null;const l=e.getShape(a.id),d=e.getBindingsFromShape(a.id).find(Za);if(!Is(l)||!d)return a;const c=cl({editor:e,label:l,pathGeometry:i,pagePoint:n,hintPosition:r,snapToDefault:!1});return Math.abs(c-r)>1e-6&&e.commands.updateBinding({id:d.id,props:{labelPosition:c}},{source:"user"}),a})(e,t,n);return o?(Ls(e,o,{editMarkId:mP,createMarkId:SP,isExisting:!!i}),"handled"):"handled"})(e,n,t.pagePoint):"continue":"continue"})(i,o);if("pointer"===o.type&&"pointer_down"===o.name){n();const r=((t,n)=>{const i=t.hitTestShape(n.pagePoint);if(!i||!Is(i)||!t.canEditShape(i))return"continue";const o=t.getShapeEditingSession();return o&&o.shapeId!==i.id?t.completeEditing("user")?(t.startEditingShape({shapeId:i.id,entryMode:"placeCaret",caretPagePoint:n.pagePoint,markId:fP,preserveInteraction:!0},"user"),"handled"):"handled":(!o&&(n.clickCount??1)<2&&((e,t)=>{const n=e.getSelectedShapeIds();if(1!==n.length)return!1;if(n[0]===t)return!0;const i=As(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")})(i,o);return"handled"===r||e?r:((e,n)=>{const i=e.hitTestShape(n.pagePoint),o=e.getSelectedShapeIds();return!i||!dl(i)||i.isLocked||e.getShapeEditingSession()||n.shiftKey||n.altKey||n.accelKey||(n.clickCount??1)>=2||1!==o.length||o[0]!==i.id||Ms(e,i.id,"geo-label")||(t={pointerId:n.pointerId,shapeId:i.id,originPagePoint:{x:n.pagePoint.x,y:n.pagePoint.y}}),"continue"})(i,o)}return"continue"}},shapePointer:{createSession:(e,t)=>((e,t)=>{if(t.event.shiftKey||t.event.accelKey||e.getShapeEditingSession()||!Is(t.shape))return null;const n=e.getBindingsFromShape(t.shape.id).find(Za);if(!n||n.toId!==t.selectionTargetId)return null;const i=e.getShape(n.toId),o=e.getShapePageBounds(t.shape.id);if(!i||!o||e.isShapeOrAncestorLocked(i.id)||!el(e,i))return null;const r=o.center.sub(t.originPagePoint);return{shapeId:i.id,historyMark:yP,onDragStart({editor:e}){e.commands.setSelectedShapeIds([i.id],{source:"system"})},update({editor:e,pagePoint:t,source:i}){const o=e.getBinding(n.id),s=e.getShape(n.fromId),a=e.getShape(n.toId);if(!Za(o)||!Is(s)||!a)return"stop";const l=el(e,a);if(!l)return"stop";const d=cl({editor:e,label:s,pathGeometry:l,pagePoint:t.add(r),hintPosition:o.props.labelPosition,snapToDefault:!0});return Math.abs(d-o.props.labelPosition)>1e-6&&e.commands.updateBinding({id:o.id,props:{labelPosition:d}},{source:i}),{status:"continue",finalPagePoint:l.getPointAt(d)}}}})(e,t)}}}function dl(e){return"geo"===e.type}function cl({editor:e,label:t,pathGeometry:n,pagePoint:i,hintPosition:o,snapToDefault:r}){let s=n.getNearestPosition(i,{hintPosition:o});if(r){const t=n.defaultPosition,i=n.getPointAt(t),o=n.getPointAt(s),r=Math.max(e.cameraZoomSignal.get(),1e-4);o.dist(i)*r<=10&&(s=t)}const a=tl(e,t,n);return Math.min(a.end,Math.max(a.start,s))}function ul(e,t){const n=al(e,hl(t,{...ws(e),autoSize:!1,textAlign:"middle"}),t);return Es(e,{bindingType:Uw,owner:t,historyMarkId:xP,index:`${t.index}${pP}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})}function hl(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 pl({fontCatalog:e=Ds()}={}){return{id:"land.text",shapeCapabilities:[{type:"text",schemaProps:["richText","w","h","autoSize","scale","font","size","color","backgroundColor","textAlign"],reactRenderer:"partial",toolbarEntry:"supported",notes:["Text shape util, SVG fallback, React renderer, rich editing runtime, creation tool, and selected-text style toolbar live in the text plugin package. React rendering remains partial while product-grade rich text rendering and measurement continue to mature."]}],shapeUtils:[new dP],shapeSvgExporters:[new cP(e)],bindingUtils:[new gP,new hP],interactionHandlers:[ll()],setup(e){e.tools.register("text",e=>new rP(e),{shortcut:"t"})}}}function gl(e,t){return e.getAvailability?.(t)??"enabled"}function fl(e){return Object.freeze({id:e})}function ml(e){return{id:e,kind:"api"}}function Sl(e){return{id:e,kind:"service"}}function yl(e){return Object.freeze({id:e})}function bl({fontCatalog:e=Ds(),selectionFormattingToolbar:t=!0}={}){return n=>{n.get(vP).provide(FP,e),n.get(MP).add($P),n.get(IP).add({id:"text.edit",getAvailability(e){if(1!==e.selection.count||"text"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;return"text"!==t?.type||t.isLocked?"disabled":"enabled"},run({context:e}){const[t]=e.selection.selectedShapes;"text"!==t?.type||t.isLocked||e.editor.startEditingShape({shapeId:t.id,entryMode:"focusEnd"},"user")}},Pl("color",e),{id:"text.set-background-color",getAvailability:e=>Cl(e),getValue(e){const t=Ml(e);return t?Al(t.backgroundColor):(e=>{let t,n=!1;for(const i of e){if("text"!==i.type)continue;n=!0;const e=Vs(i.props.richText);if("mixed"===e)return"mixed";const o=i.props,r=null!==e||O(o.backgroundColor)?e:U(o.backgroundColor);if(void 0===t)t=r;else if(t!==r)return"mixed"}return n?Al(t??null):null})(e.selection.selectedShapes)},run({context:e,value:t}){const n=Bl(t);if(!n)return;const i=O(n)?null:U(n);if(kl(e))return void Tl(e)?.setBackgroundColor(i);const o=e.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).flatMap(e=>{const t=((e,t)=>{const n=Qs(e.content,(e,n)=>{if("text"!==e.type||!e.text||n.insideCodeBlock||e.marks?.some(e=>"code"===e.type))return e;const i=e.marks??[],o=i.findIndex(e=>"textStyle"===e.type);if(o<0)return null===t?e:{...e,marks:[...i,{type:"textStyle",attrs:{backgroundColor:t}}]};const r=i[o];if((r?.attrs?.backgroundColor??null)===t)return e;const s={...r?.attrs};null===t?delete s.backgroundColor:s.backgroundColor=t;const a=Object.keys(s).length>0?i.map((e,t)=>t===o?{...e,attrs:s}:e):i.filter((e,t)=>t!==o);return{...e,marks:a.length>0?a:void 0}});return n.changed?es({...e,content:n.nodes}):e})(e.props.richText,i),o=!D(e.props.backgroundColor,n);return t!==e.props.richText||o?[{id:e.id,props:{backgroundColor:n,...t===e.props.richText?null:{richText:t}}}]:[]});o.length>0&&e.editor.commands.updateShapes(o,{source:"user"})}},Pl("font",e),Pl("size",e),Pl("textAlign",e),...NP.map(e=>{return{id:`text.toggle-${t=e.format}`,getAvailability:e=>Cl(e),getValue(e){const n=Ml(e);return n?n[t]:El(e.selection.selectedShapes,t)},run({context:e}){if(kl(e))return void Tl(e)?.toggle(t);const n=!0!==El(e.selection.selectedShapes,t),i=e.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).flatMap(e=>{const i=((e,t,n)=>{const i=Ww[t],o=Qs(e.content,(e,o)=>{if("text"!==e.type||!e.text)return e;const r=e.marks??[],s=r.filter(e=>i.includes(e.type));if(n&&(o.insideCodeBlock||r.some(e=>"code"===e.type)))return e;if(n&&1===s.length&&s[0]?.type===t)return e;const a=r.filter(e=>!i.includes(e.type)),l=n?[...a,{type:t}]:a;return r.length===l.length&&r.every((e,t)=>e===l[t])?e:{...e,marks:l.length>0?l:void 0}});return o.changed?es({...e,content:o.nodes}):e})(e.props.richText,t,n);return i===e.props.richText?[]:[{id:e.id,props:{richText:i}}]});i.length>0&&e.editor.commands.updateShapes(i,{source:"user"})}};var t}),{id:HP,getAvailability:e=>Cl(e),getValue:()=>!1,run({context:e}){if(kl(e))return void Tl(e)?.clearFormatting();const t=e.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).flatMap(e=>{const t=(e=>{const t=Qs(e.content,e=>"text"===e.type&&e.marks&&e.marks.length>0?{...e,marks:void 0}:Gs(e));return t.changed?es({...e,content:t.nodes}):e})(e.props.richText),n=E("transparent"),i=!D(e.props.backgroundColor,n);return t!==e.props.richText||i?[{id:e.id,props:{backgroundColor:n,...t===e.props.richText?null:{richText:t}}}]:[]});t.length>0&&e.editor.commands.updateShapes(t,{source:"user"})}},{id:WP,getAvailability:e=>1!==e.selection.count||"text"!==e.selection.commonShapeType?"inapplicable":Ml(e)?.canSetLink?"enabled":"disabled",getValue(e){const t=Ml(e)?.linkHref;return"string"==typeof t&&"mixed"!==t?t:""},run({context:e,value:t}){if("string"!=typeof t)return;const n=Tl(e);if(!n)return;if(0===t.trim().length)return void n.setLink(null);const i=Vr(t);i&&n.setLink(i)}},Rl("color",e),{id:"text.default-background-color",getAvailability:e=>"text"===e.tool.activeToolId?"enabled":"inapplicable",getValue:e=>e.editor.getDefaultShapeProps("text").backgroundColor,run({context:e,value:t}){const n=Bl(t);n&&e.editor.updateDefaultShapeProps("text",{backgroundColor:n})}},Rl("font",e),Rl("size",e),Rl("textAlign",e)),n.get(RP).add({id:"text.tool-toolbar",channel:BP.toolSwitcher,order:50,actionIds:[AP],getGroups:e=>[{id:"text.tools",items:[{kind:"button",id:"text.tool.text",actionId:AP,value:"text",label:"Text",shortcut:e.editor.shortcuts.getToolShortcutLabel("text"),icon:"type",dataUi:"text-tool-button"}]}]},(e=>({id:"text.default-style.tool-toolbar",channel:BP.toolOptions,order:51,actionIds:["text.default-color","text.default-background-color","text.default-font","text.default-size","text.default-textAlign"],when:e=>"text"===e.tool.activeToolId,getGroups(){const[t,n,i,o]=wl({colorActionId:"text.default-color",fontActionId:"text.default-font",fontCatalog:e,sizeActionId:"text.default-size",textAlignActionId:"text.default-textAlign",dataUiPrefix:"text-default"});return[t,vl("text-default","text.default-background-color"),n,i,o]}}))(e),...t?[xl(e),Il(e)]:[]),n.get(kP).add({id:"text.shape-context-menu",target:"selection",order:35,actionIds:["text.edit"],when:e=>1===e.selection.count&&"text"===e.selection.singleShapeType,getSections:()=>[{id:"text.context-menu",title:"Text",items:[{kind:"command",id:"text.edit",actionId:"text.edit",label:"Edit text",icon:"type",dataUi:"context-menu-edit-text-button"}]}]})}}function xl(e){return{id:"text.selection-toolbar",channel:BP.selectionQuickActions,order:20,actionIds:["text.set-color","text.set-background-color","text.set-font","text.set-size","text.set-textAlign",...NP.map(e=>e.actionId),HP,WP],subscribe:(e,t)=>((e,t)=>{const n=Xs(e);return n.listeners.add(t),()=>{n.listeners.delete(t)}})(e,t),when:e=>1===e.selection.count&&"text"===e.selection.commonShapeType,getGroups(){const[t,n,i,o]=wl({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"});return[t,vl("text"),n,i,{id:"text.inline-emphasis",items:NP.slice(0,2).map(e=>({kind:"button",id:e.actionId,actionId:e.actionId,label:e.label,icon:e.icon,dataUi:e.dataUi}))},{id:"text.inline-decoration",presentation:"overflow",items:NP.slice(2).map(e=>({kind:"button",id:e.actionId,actionId:e.actionId,label:e.label,icon:e.icon,dataUi:e.dataUi}))},{...o,presentation:"overflow"},{id:"text.clear-formatting",presentation:"overflow",items:[{kind:"button",id:HP,actionId:HP,label:"Clear formatting",icon:"remove-formatting",dataUi:"selected-text-clear-formatting-button"}]},{id:"text.link",presentation:"overflow",items:[{kind:"text-input",id:"text.link",actionId:WP,label:"Link",icon:"link",presentation:"popover",placeholder:"Link URL",validate:e=>0===e.trim().length||null!==Vr(e),dataUi:"text-link-button"}]}]}}}function Il(e){return{id:"text.multi-selection-toolbar",channel:BP.selectionProperties,order:20,actionIds:["text.set-color","text.set-background-color","text.set-font","text.set-size","text.set-textAlign"],when:e=>e.selection.count>1&&"text"===e.selection.commonShapeType&&null===e.editor.shapeEditingStateSignal.get().session,getGroups(){const[t,n,i,o]=wl({colorActionId:"text.set-color",fontActionId:"text.set-font",fontCatalog:e,sizeActionId:"text.set-size",textAlignActionId:"text.set-textAlign",dataUiPrefix:"text"});return[t,vl("text"),{...n,presentation:"overflow"},{...i,presentation:"overflow"},{...o,presentation:"overflow"}]}}}function vl(e,t="text.set-background-color"){return{id:`${e}.style-background-color`,items:[{kind:"color-input",id:`${e}.background-color`,actionId:t,label:"Background",fallback:"#fef08a",presets:OP.map(t=>({...t,dataUi:`${e}-background-color-${t.id}-button`})),dataUi:`${e}.background-color`}]}}function wl({colorActionId:e,fontActionId:t,fontCatalog:n,sizeActionId:i,textAlignActionId:o,dataUiPrefix:r}){return[{id:`${r}.style-color`,items:[{kind:"color-input",id:`${r}.color`,actionId:e,label:"Color",fallback:"#0f172a",presets:UP.map(e=>({...e,dataUi:`${r}-color-${e.id}-button`})),dataUi:`${r}.color`}]},{id:`${r}.style-font`,items:[{kind:"segmented",id:`${r}.font`,actionId:t,options:n.fontOptions.map(e=>({value:e.id,label:e.label,dataUi:`${r}-font-${e.id}-button`}))}]},{id:`${r}.style-size`,items:[{kind:"stepper",id:`${r}.size`,actionId:i,label:"Size",options:DP.map(e=>({value:e.value,label:e.label,dataUi:`${r}-size-${e.id}-button`}))}]},{id:`${r}.style-align`,items:[{kind:"segmented",id:`${r}.align`,actionId:o,options:zP.map(e=>({...e,dataUi:`${r}-align-${e.value}-button`}))}]}]}function Pl(e,t){return{id:`text.set-${e}`,getAvailability:e=>Cl(e),getValue(t){const n=Ml(t);return n?n[e]:((e,t)=>{let n;for(const i of e){if("text"!==i.type)continue;const e=i.props[t];if(void 0!==n){if("color"===t?!D(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e)},run({context:n,value:i}){const o=Ll(e,i,t);if(void 0===o)return;if(kl(n)){const t=Tl(n);if(!t)return;return void("color"===e?t.setColor(U(o)):"font"===e?t.setFont(o):"size"===e?t.setSize(o):t.setTextAlign(o))}const r=n.selection.selectedShapes.filter(e=>"text"===e.type).filter(e=>!e.isLocked).map(t=>{const n=((e,t)=>{const n=Qs(e.content,e=>{if("textAlign"===t)return Gs(e);if("text"!==e.type||!e.marks)return e;let n=!1;const i=e.marks.flatMap(e=>{if("textStyle"!==e.type||!e.attrs)return[e];const i={...e.attrs};let o=!1;const r="size"===t?["fontSize","lineHeight"]:"font"===t?["fontFamily"]:["color"];for(const t of r)t in i&&(delete i[t],o=!0);return o?(n=!0,Object.keys(i).length>0?[{...e,attrs:i}]:[]):[e]});return n?{...e,marks:i.length>0?i:void 0}:e});return n.changed?es({...e,content:n.nodes}):e})(t.props.richText,e);return{id:t.id,props:{[e]:o,...n===t.props.richText?null:{richText:n}}}});0!==r.length&&n.editor.commands.updateShapes(r,{source:"user"})}}}function kl(e){return null!==e.editor.shapeEditingStateSignal.get().session}function Cl(e){return"text"!==e.selection.commonShapeType?"inapplicable":(kl(e)?null!==Ml(e):e.selection.selectedShapes.some(e=>"text"===e.type&&!e.isLocked))?"enabled":"disabled"}function Tl(e){const t=e.editor.shapeEditingStateSignal.get().session,n=Ys(e.editor);return t&&n?.shapeId===t.shapeId?n:null}function Ml(e){const t=e.editor.shapeEditingStateSignal.get().session,n=(i=e.editor,Ys(i)?.getSnapshot()??null);var i;return t&&n?.shapeId===t.shapeId?n:null}function El(e,t){let n;for(const i of e){if("text"!==i.type)continue;const e=js(i.props.richText,t);if("mixed"===e)return null;if(void 0===n)n=e;else if(n!==e)return null}return n??!1}function Al(e){return"mixed"===e?e:E(e??"transparent")}function Bl(e){if(R(e))return $(e,E("transparent"))}function Rl(e,t){return{id:`text.default-${e}`,getAvailability:e=>"text"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("text")[e],run({context:n,value:i}){const o=Ll(e,i,t);void 0!==o&&n.editor.updateDefaultShapeProps("text",{[e]:o})}}}function Ll(e,t,n){if("color"===e)return R(t)?$(t,M("text-slate")):void 0;if("font"===e){if("string"!=typeof t)return;return((e,t)=>"default"===t||Ns(t)&&e.fontsById.has(t))(n,t)?t:void 0}if("size"===e){if("number"!=typeof t||!Number.isFinite(t))return;return DP.some(e=>e.value===t)?t:void 0}return"string"==typeof t&&zP.some(e=>e.value===t)?t:void 0}function $l(e={}){const t={...Os(),...e},n=zs(t);return{id:"text",provides:[LP,FP],editor:pl({fontCatalog:n}),render:Oa({fontCatalog:n,formattingToolbar:t.formattingToolbar,onTiptapEditorChange:t.onTiptapEditorChange}),setup:bl({fontCatalog:n,selectionFormattingToolbar:!1!==t.formattingToolbar})}}function Fl(e){return Math.max(0,Math.min(1,e))}function Ul(e,t,n){return e.computeShapePositionedToPageTransform(t).applyToPoint(((e,t,n)=>{const i=e.computeShapePositionedBounds(t);return new mI(i.minX+i.w*n.x,i.minY+i.h*n.y)})(e,t,n))}function Ol(e,t,n,i){return((e,t,n,i)=>e.getShapeUtil(t).resolveBindingPoint(t,{editor:e,rawPagePoint:n,oppositePagePoint:i}))(e,t,Ul(e,t,n),i)}function Dl(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 mI(e.x+e.props.w/2,e.y+e.props.h/2),i=t.sub(n),o=new mI(i.x*e.scaleX,i.y*e.scaleY);return n.add(o.rot(e.rotation))})(e,new mI(e.x+n.x,e.y+n.y))}function zl(e,t,n){const i="start"===n?t.props.start:t.props.end;return e.computeShapeLocalToPageTransform(t).applyToPoint(new mI(i.x,i.y))}function Nl(e){return"start"===e?"end":"start"}function Hl(e,t,n,i){const o=e.computeShapeLocalToPageTransform(t).tryInvert();if(!o)return null;const r=_l(o.applyToPoint(n),o.applyToPoint(i)),s=e.getShapeUtil(t),a={...t,props:{...t.props,w:r.w,h:r.h,start:r.start,end:r.end}},l=de(s.getLocalToPageTransform(t).compose(yI.Translate(r.x,r.y)),s.getLocalBounds(a),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return l?{...a,...l}:null}function Wl(e,t,n,i){return Hl(e,t,"start"===n?i:zl(e,t,"start"),"end"===n?i:zl(e,t,"end"))}function _l(e,t){const n=Gl(e.x,t.x),i=Gl(e.y,t.y);return{x:n.origin,y:i.origin,w:n.size,h:i.size,start:{x:n.startOffset,y:i.startOffset},end:{x:n.endOffset,y:i.endOffset}}}function Kl(e){return Ql(new mI(e.props.start.x,e.props.start.y).add(new mI(e.x,e.y)),new mI(e.props.end.x,e.props.end.y).add(new mI(e.x,e.y)),e.props.bend)}function Yl(e){return Ql(new mI(e.props.start.x,e.props.start.y),new mI(e.props.end.x,e.props.end.y),e.props.bend)}function Xl(e,t,n){const i=mI.Med(e,t),o=t.sub(e);if(o.len()<1e-6)return 0;const r=o.per().normalize();return-rd(n.sub(i),r)}function ql(e,t,n,i=.5){if(!t||t.length<=1e-6)return Vl(i);let o=0,r=Vl(i),s=1/0;for(let a=0;a<t.segmentLengths.length;a+=1){const l=e[a],d=t.segmentLengths[a],c=e[a+1].sub(l),u=d<=1e-6?0:Vl(rd(n.sub(l),c)/c.len2()),h=l.add(c.mul(u)),p=(o+d*u)/t.length,g=h.dist2(n),f=g<s-1e-8,m=Math.abs(g-s)<=1e-8&&Math.abs(p-i)<Math.abs(r-i);(f||m)&&(s=g,r=p),o+=d}return Vl(r)}function jl(e,t){const n=Vl(e),i=Vl(t);return n<=.5?i*n*2:i+(1-i)*(n-.5)*2}function Vl(e){return Math.max(0,Math.min(1,e))}function Gl(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 Zl(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Ql(e,t,n){const i=function(e,t=0){return((e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t)(e,t)}(n,0),o=((e,t,n)=>{const i=mI.Med(e,t),o=t.sub(e),r=o.len()?o.per().normalize():new mI(0,-1);return i.add(r.mul(-n))})(e,t,i),r=((e,t,n)=>{const i=((e,t,n)=>{const i=-2*(e.x*(t.y-n.y)-e.y*(t.x-n.x)+t.x*n.y-n.x*t.y);if(Math.abs(i)<1e-6)return null;const o=((e.x*e.x+e.y*e.y)*(n.y-t.y)+(t.x*t.x+t.y*t.y)*(e.y-n.y)+(n.x*n.x+n.y*n.y)*(t.y-e.y))/i,r=((e.x*e.x+e.y*e.y)*(t.x-n.x)+(t.x*t.x+t.y*t.y)*(n.x-e.x)+(n.x*n.x+n.y*n.y)*(e.x-t.x))/i;return Number.isFinite(o)&&Number.isFinite(r)?new mI(o,r):null})(e,t,n);if(!i)return null;const o=i.dist(e);if(o<1e-6)return null;const r=((d=n).x-(a=e).x)*((l=t).y-a.y)-(l.x-a.x)*(d.y-a.y)<0?1:0,s=((e,t,n)=>{const i=e.dist(n),o=n.dist(t),r=t.dist(e);return o<1e-6||r<1e-6?0:2*Math.acos(Math.max(-1,Math.min(1,(o*o+r*r-i*i)/(2*o*r))))})(e,t,n);var a,l,d;if(!Number.isFinite(s))return null;const c=Math.PI>s?1:0,u=(KP-s)*(r?1:-1);return{center:i,radius:o,largeArcFlag:c,sweepFlag:r,size:u,length:Math.abs(u*o)}})(e,o,t),s=Math.abs(i)<1e-6||null===r||0===r.length||!Number.isFinite(r.length)||!Number.isFinite(r.radius),a=s?[e,t]:ed(e,t,r,24),l=s||null===r?`M ${Zl(e.x)} ${Zl(e.y)} L ${Zl(t.x)} ${Zl(t.y)}`:`M ${Zl(e.x)} ${Zl(e.y)} A ${Zl(r.radius)} ${Zl(r.radius)} 0 ${r.largeArcFlag} ${r.sweepFlag} ${Zl(t.x)} ${Zl(t.y)}`,d={start:{terminal:"start",point:e,handle:e},end:{terminal:"end",point:t,handle:t},middle:o,bend:i,points:a,bounds:SI.FromPoints(a),path:l};return s?{type:"straight",...d,arc:null}:{type:"curved",...d,arc:r}}function Jl({start:e,end:t,middle:n,bend:i,arc:o,startHandle:r=e,endHandle:s=t}){const a=td(e,t,o);if(Math.abs(a)<1e-6||!Number.isFinite(a)||!Number.isFinite(o.radius)||o.radius<1e-6){const o=Ql(e,t,0);return{...o,start:{...o.start,handle:r},end:{...o.end,handle:s},middle:n,bend:i}}const l={center:o.center,radius:o.radius,largeArcFlag:Math.abs(a)>Math.PI?1:0,sweepFlag:o.sweepFlag,size:a,length:Math.abs(a*o.radius)},d=ed(e,t,l,24),c=`M ${Zl(e.x)} ${Zl(e.y)} A ${Zl(l.radius)} ${Zl(l.radius)} 0 ${l.largeArcFlag} ${l.sweepFlag} ${Zl(t.x)} ${Zl(t.y)}`;return{type:"curved",start:{terminal:"start",point:e,handle:r},end:{terminal:"end",point:t,handle:s},middle:n,arc:l,bend:i,points:d,bounds:SI.FromPoints(d),path:c}}function ed(e,t,n,i){const o=[],r=mI.Angle(n.center,e),s=td(e,t,n);for(let a=0;a<=i;a++)o.push(id(n.center,n.radius,r+s*(a/i)));return o}function td(e,t,n){return i=mI.Angle(n.center,e),o=mI.Angle(n.center,t),n.sweepFlag?((o-i)%KP+KP)%KP:-((i-o)%KP+KP)%KP;var i,o}function nd(e,t,n,i){const o=mI.Angle(n.center,e),r=td(e,t,n);return id(n.center,n.radius,o+r*i)}function id(e,t,n){return e.add(new mI(Math.cos(n)*t,Math.sin(n)*t))}function od(e,t,n){const i=n.sub(t),o=i.x*i.x+i.y*i.y;if(0===o)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,rd(r,i)/o)),a=t.add(i.mul(s));return e.dist(a)}function rd(e,t){return e.x*t.x+e.y*t.y}function sd(e){return!!e&&"shape"===e.typeName&&"arrow"===e.type}function ad(e){return!!e&&"binding"===e.typeName&&"arrow"===e.type}function ld(e,t,n){return e.getBindingsFromShape(t.id).find(e=>ad(e)&&e.props.terminal===n)??null}function dd(e,t,n){const i=zl(e,t,n),o=ld(e,t,n);if(!o)return{terminal:n,binding:null,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0};const r=e.getShape(o.toId);return!r||sd(r)?{terminal:n,binding:o,target:null,handlePagePoint:i,boundaryPagePoint:i,isArcBoundaryPoint:!0}:{terminal:n,binding:o,target:r,handlePagePoint:Ul(e,r,o.props.normalizedAnchor),boundaryPagePoint:i,isArcBoundaryPoint:!1}}function cd(e,t){const n=dd(e,t,"start"),i=dd(e,t,"end"),o=gd(e,t,n.handlePagePoint,i.handlePagePoint);return"curved"===o.type&&(bd(e,n,o,"start"),bd(e,i,o,"end")),{info:fd(o,n,i),fullInfo:o,bindingSegments:[xd(n,o),xd(i,o)].filter(e=>null!==e)}}function ud(e,t){if(!ld(e,t,"start")&&!ld(e,t,"end"))return Yl(t);const n=e.computeShapeLocalToPageTransform(t).tryInvert();return n?((e,t,n)=>{const i=pd(t.info,n);if("curved"!==t.info.type)return i;const o=Ql(n.applyToPoint(t.fullInfo.start.point),n.applyToPoint(t.fullInfo.end.point),e.props.bend);if("curved"!==o.type)return i;const r=n.applyToPoint(t.info.start.point),s=n.applyToPoint(t.info.end.point),a=((e,t,n)=>{const i=t.sub(e);if(i.len2()<1e-12)return null;const o=mI.Med(e,t),r=i.per().normalize(),s=n.sub(o);return o.add(r.mul(s.x*r.x+s.y*r.y))})(r,s,o.arc.center);if(!a)return i;const l={center:a,radius:a.dist(r),sweepFlag:o.arc.sweepFlag},d=nd(r,s,l,.5);return Jl({start:r,end:s,middle:d,bend:Xl(r,s,d),arc:l,startHandle:n.applyToPoint(t.info.start.handle),endHandle:n.applyToPoint(t.info.end.handle)})})(t,cd(e,t),n):Ql(new mI(t.props.start.x,t.props.start.y),new mI(t.props.end.x,t.props.end.y),t.props.bend)}function hd(e,t,n){return{...e,start:{...e.start,handle:t},end:{...e.end,handle:n}}}function pd(e,t){const n=e=>t.applyToPoint(e),i=n(e.start.point),o=n(e.end.point),r=n(e.middle),s=e.points.map(n),a=s.map((e,t)=>`${0===t?"M":"L"} ${yd(e.x)} ${yd(e.y)}`).join(" "),l={start:{...e.start,point:i,handle:n(e.start.handle)},end:{...e.end,point:o,handle:n(e.end.handle)},middle:r,bend:Xl(i,o,r),points:s,bounds:SI.FromPoints(s),path:a};if("straight"===e.type)return{...e,...l};const d=n(e.arc.center),c={...e.arc,center:d,radius:d.dist(i),sweepFlag:t.determinant()<0?1===e.arc.sweepFlag?0:1:e.arc.sweepFlag};return(e=>{const t=Math.hypot(e.a,e.b),n=Math.hypot(e.c,e.d),i=Math.max(1,t,n);return Math.abs(t-n)<=1e-8*i&&Math.abs(e.a*e.c+e.b*e.d)<=1e-8*i*i})(t)?Jl({start:i,end:o,middle:r,bend:l.bend,arc:c,startHandle:l.start.handle,endHandle:l.end.handle}):{...e,...l,arc:c}}function gd(e,t,n,i){const o=e.computeShapeLocalToPageTransform(t),r=o.tryInvert();return r?pd(Ql(r.applyToPoint(n),r.applyToPoint(i),t.props.bend),o):Ql(n,i,t.props.bend)}function fd(e,t,n){if(t.boundaryPagePoint.dist2(e.start.point)<1e-10&&n.boundaryPagePoint.dist2(e.end.point)<1e-10)return hd(e,t.handlePagePoint,n.handlePagePoint);if("straight"===e.type)return hd(Ql(t.boundaryPagePoint,n.boundaryPagePoint,0),t.handlePagePoint,n.handlePagePoint);if(e.path.includes(" A "))return Jl({start:t.boundaryPagePoint,end:n.boundaryPagePoint,middle:nd(t.boundaryPagePoint,n.boundaryPagePoint,e.arc,.5),bend:e.bend,arc:e.arc,startHandle:t.handlePagePoint,endHandle:n.handlePagePoint});const i=md(e.points,t.boundaryPagePoint),o=md(e.points,n.boundaryPagePoint),r=[t.boundaryPagePoint];for(let a=Math.floor(i)+1;a<=Math.floor(o);a+=1){const t=e.points[a];t&&a<o&&r.push(t)}r.push(n.boundaryPagePoint);const s=(e=>{if(0===e.length)return mI.Zero();const t=[];let n=0;for(let o=0;o<e.length-1;o+=1){const i=e[o].dist(e[o+1]);t.push(i),n+=i}let i=n/2;for(let o=0;o<t.length;o+=1){const n=t[o];if(i<=n){const t=e[o];return t.add(e[o+1].sub(t).mul(0===n?0:i/n))}i-=n}return e[e.length-1]})(r);return{...e,start:{...e.start,point:t.boundaryPagePoint,handle:t.handlePagePoint},end:{...e.end,point:n.boundaryPagePoint,handle:n.handlePagePoint},middle:s,points:r,bounds:SI.FromPoints(r),path:Sd(r),bend:Xl(t.boundaryPagePoint,n.boundaryPagePoint,s)}}function md(e,t){let n=0,i=1/0;for(let o=0;o<e.length-1;o+=1){const r=e[o],s=e[o+1].sub(r),a=s.len2(),l=0===a?0:Math.max(0,Math.min(1,((t.x-r.x)*s.x+(t.y-r.y)*s.y)/a)),d=r.add(s.mul(l)).dist2(t);d<i&&(i=d,n=o+l)}return n}function Sd(e){return e.map((e,t)=>`${0===t?"M":"L"} ${yd(e.x)} ${yd(e.y)}`).join(" ")}function yd(e){return Number(e.toFixed(3)).toString()}function bd(e,t,n,i){if(!t.target)return void(t.isArcBoundaryPoint=!0);const o=wd(e.getShapePageOutlineVertices(t.target.id),n,i);o?(t.boundaryPagePoint=o,t.isArcBoundaryPoint=!0):t.isArcBoundaryPoint=!1}function xd(e,t){if(!e.binding)return null;const n=((e,t)=>({terminal:e.terminal,anchorPagePoint:e.handlePagePoint,boundaryPagePoint:e.boundaryPagePoint,guidePath:"curved"===t.type&&e.isArcBoundaryPoint?vd(e.terminal,e.handlePagePoint,e.boundaryPagePoint,t):null}))(e,t);return{terminal:n.terminal,anchorPagePoint:n.anchorPagePoint,boundaryPagePoint:n.boundaryPagePoint,guidePath:n.guidePath}}function Id(e,{arrow:t,terminal:n,target:i,anchorPagePoint:o,fallbackBoundaryPagePoint:r}){const s=((e,t,n)=>dd(e,t,n).handlePagePoint)(e,t,Nl(n)),a=gd(e,t,"start"===n?o:s,"end"===n?o:s);if("curved"!==a.type)return{terminal:n,anchorPagePoint:o,boundaryPagePoint:r,guidePath:null};const l=wd(e.getShapePageOutlineVertices(i.id),a,n);return l?{terminal:n,anchorPagePoint:o,boundaryPagePoint:l,guidePath:vd(n,o,l,a)}:{terminal:n,anchorPagePoint:o,boundaryPagePoint:r,guidePath:null}}function vd(e,t,n,i){if(i.path.includes(" A "))return(({terminal:e,handlePagePoint:t,boundaryPagePoint:n,fullInfo:i})=>{if(t.dist(n)<1e-6)return null;const o="start"===e?i.arc.sweepFlag:(e=>e?0:1)(i.arc.sweepFlag),r={center:i.arc.center,radius:i.arc.radius,sweepFlag:o};return Jl({start:t,end:n,middle:nd(t,n,r,.5),bend:i.bend,arc:r}).path})({terminal:e,handlePagePoint:t,boundaryPagePoint:n,fullInfo:i});const o=md(i.points,n),r=[t];if("start"===e)for(let s=1;s<=Math.floor(o);s+=1){const e=i.points[s];e&&s<o&&r.push(e)}else for(let s=i.points.length-2;s>=Math.ceil(o);s-=1){const e=i.points[s];e&&s>o&&r.push(e)}return r.push(n),Sd(r)}function wd(e,t,n){const i=[];for(let o=0;o<t.points.length-1;o+=1){const n=t.points[o],r=t.points[o+1];for(let t=0;t<e.length;t+=1){const s=e[t],a=e[(t+1)%e.length];if(!s||!a)continue;const l=Pd(n,r,s,a);l&&i.push({point:l.point,position:o+l.t})}}return 0===i.length?null:(i.sort((e,t)=>e.position-t.position),"start"===n?i[0].point:i[i.length-1].point)}function Pd(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-9)return null;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l<-1e-9||l>1.000000001||d<-1e-9||d>1.000000001?null:{point:e.add(o.mul(Math.max(0,Math.min(1,l)))),t:Math.max(0,Math.min(1,l))}}function kd(e,t){const n=e.getShapePageBounds(t.id)??e.computeShapePageBounds(t);return n.w*n.h}function Cd(e,t){return e.getShapeUtil(t).canReceiveChildren(t)}function Td(e,t){return!(!t||sd(t))&&e.getShapeUtil(t).canReceiveTerminalBinding(t,{editor:e})}function Md(e,t,n){const i=Cd(e,t),o=Cd(e,n);if(i!==o)return i?1:-1;if(i&&o){const i=kd(e,t)-kd(e,n);if(Math.abs(i)>1e-6)return i}return 0}function Ed(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Ad(e){if(e)return{shapes:[e]}}function Bd(e,t,n="user"){if(t.parentId?.startsWith("shape:")){const n=e.getShape(t.parentId);if(!n||!e.computeShapeLocalToPageTransform(n).tryInvert())throw new Error("Cannot create an arrow inside a singular parent transform")}const[i]=e.commands.createShapes([{type:"arrow",x:t.startPagePoint.x,y:t.startPagePoint.y,parentId:t.parentId,props:t.props,meta:t.meta}],{source:n,autoReparent:!1});if(!sd(i))throw new Error("Failed to create arrow shape");const o=Hl(e,i,t.startPagePoint,t.endPagePoint);if(!o)throw new Error("Cannot create an arrow inside a singular parent transform");e.commands.updateShapes([{id:i.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}),t.startBinding&&e.commands.createBinding({type:"arrow",fromId:o.id,toId:t.startBinding.targetShapeId,props:{terminal:"start",normalizedAnchor:t.startBinding.normalizedAnchor}},{source:n}),t.endBinding&&e.commands.createBinding({type:"arrow",fromId:o.id,toId:t.endBinding.targetShapeId,props:{terminal:"end",normalizedAnchor:t.endBinding.normalizedAnchor}},{source:n});const r=e.getShape(o.id);if(!sd(r))throw new Error("Failed to create arrow shape");return r}function Rd(e,t,n,i,o="user"){if(!t)return e.setBindingPreview(i.preview),null;let r=null;return r=((e,t,n)=>{const i=e.getShape(t.shapeId);if(!sd(i))return null;const o=Wl(e,i,t.terminal,t.pagePoint);if(!o)return null;e.commands.updateShapes([{id:i.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n});const r=e.getBindingsFromShape(i.id).find(e=>ad(e)&&e.props.terminal===t.terminal)??null;t.binding?ad(r)?e.commands.updateBinding({id:r.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n}):(r&&e.commands.deleteBinding(r.id,{source:n}),e.commands.createBinding({type:"arrow",fromId:i.id,toId:t.binding.targetShapeId,props:{terminal:t.terminal,normalizedAnchor:t.binding.normalizedAnchor}},{source:n})):r&&(e.commands.deleteBinding(r.id,{source:n}),e.commands.updateShapes([{id:i.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}));const s=e.getShape(i.id);return sd(s)?s:o})(e,{shapeId:t,terminal:n,pagePoint:i.pagePoint,binding:i.binding},o),e.setBindingPreview(i.preview),r}function Ld(e,t){const n=[];return"arrow"===t.headStart&&n.push(Fd(e,"start",t.strokeWidth)),"arrow"===t.headEnd&&n.push(Fd(e,"end",t.strokeWidth)),{path:n.length>0?n.map($d).join(" "):null,points:n.flat()}}function $d([e,t,n]){return[`M ${Ud(e.x)} ${Ud(e.y)}`,`L ${Ud(t.x)} ${Ud(t.y)}`,`L ${Ud(n.x)} ${Ud(n.y)}`].join(" ")}function Fd(e,t,n){const i=e[t].point,o=((e,t)=>{if("curved"===e.type){const n=e[t].point.sub(e.arc.center).per().mul(1===e.arc.sweepFlag?1:-1).normalize();if(n.len2()>0)return n}const n=e.end.point.sub(e.start.point).normalize();return n.len2()>0?n:new mI(1,0)})(e,t),r=3.45*n*("start"===t?1:-1),s=o.per().mul(2*n),a=i.add(o.mul(r));return[a.sub(s),i,a.add(s)]}function Ud(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function Od(e,t){const n=e&&"object"==typeof e?e:void 0;return{x:Dd(n?.x,t.x),y:Dd(n?.y,t.y)}}function Dd(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function zd(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o));return e.dist(t.add(i.mul(s)))}function Nd(e,t,n,i){return((e,t,n,i)=>{const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1})(e,t,n,i)?0:Math.min(zd(e,n,i),zd(t,n,i),zd(n,e,t),zd(i,e,t))}function Hd(e,{terminal:t,rawPagePoint:n,oppositePagePoint:i,excludeShapeId:o,ignoreTargets:r=!1}){if(r)return{pagePoint:n.clone(),binding:null,preview:null};const s=function(e,t,n,i){const o=((e,t)=>{let n=null;for(const i of t)(!n||Md(e,i,n)<0)&&(n=i);return n})(e,e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget",filter:t=>t.id!==i?.excludeShapeId&&Td(e,t)}));if(!o)return null;const r=((e,t,n)=>{const i=e.computeShapePositionedToPageTransform(t).tryInvert(),o=e.computeShapePositionedBounds(t);if(!i)return{x:.5,y:.5};const r=i.applyToPoint(n),s=o.h<=1e-6?.5:(r.y-o.minY)/o.h;return{x:Fl(o.w<=1e-6?.5:(r.x-o.minX)/o.w),y:Fl(s)}})(e,o,t);return{targetShape:o,normalizedAnchor:r,resolvedPagePoint:Ol(e,o,r,n),rawPagePoint:t.clone()}}(e,n,i,{excludeShapeId:o});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:_d(s),preview:Kd(t,s)}}function Wd(e,{arrow:t,terminal:n,rawPagePoint:i,ignoreTargets:o=!1}){const r=Hd(e,{terminal:n,rawPagePoint:i,oppositePagePoint:zl(e,t,Nl(n)),excludeShapeId:t.id,ignoreTargets:o});if(!r.preview)return r;const s=((e,{arrow:t,terminal:n,rawPagePoint:i,preview:o})=>{const r=e.getShape(o.targetShapeId);if(!r||sd(r))return o;const s=Id(e,{arrow:t,terminal:n,target:r,anchorPagePoint:i,fallbackBoundaryPagePoint:o.resolvedPagePoint});return{...o,resolvedPagePoint:s.boundaryPagePoint,guidePath:s.guidePath}})(e,{arrow:t,terminal:n,rawPagePoint:i,preview:r.preview});return{...r,pagePoint:s.resolvedPagePoint,preview:s}}function _d(e){return e?{targetShapeId:e.targetShape.id,normalizedAnchor:e.normalizedAnchor}:null}function Kd(e,t){return t?{terminal:e,targetShapeId:t.targetShape.id,rawPagePoint:t.rawPagePoint,resolvedPagePoint:t.resolvedPagePoint}:null}function Yd(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 Xd({strokeActionId:e,strokeWidthActionId:t,directionActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-stroke`,items:[{kind:"color-input",id:`${i}.stroke`,actionId:e,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:GP.map(e=>({...e,dataUi:`${i}-stroke-${e.id}-button`})),dataUi:`${i}.stroke`}]},{id:`${i}.style-stroke-width`,items:[{kind:"text-input",id:`${i}.stroke-width`,actionId:t,label:"Stroke width",placeholder:"2",suffix:"Px",validate:Jd,dataUi:`${i}-stroke-width-control`}]},{id:`${i}.direction`,items:[{kind:"segmented",id:`${i}.direction`,actionId:n,options:ZP.map(e=>({...e,label:`Arrow direction: ${e.label}`,dataUi:`${i}-direction-${e.value}-button`}))}]}]}function qd(e){return{id:`arrow.set-${e}`,getAvailability:e=>"arrow"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const i of e){if("arrow"!==i.type)continue;const e=i.props[t];if(void 0!==n){if("stroke"===t?!D(n,e):n!==e)return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=Vd(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(e=>"arrow"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function jd(e){return{id:`arrow.default-${e}`,getAvailability:e=>"arrow"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("arrow")[e],run({context:t,value:n}){const i=Vd(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("arrow",{[e]:i})}}}function Vd(e,t){return"strokeWidth"===e?Qd(t):"stroke"===e&&R(t)?$(t,M("stroke-slate")):void 0}function Gd(e,t){return"arrow"===e&&"arrow"===t?"both":"arrow"===e?"start":"arrow"===t?"end":"none"}function Zd(e){if(!ZP.some(t=>t.value===e))return null;switch(e){case"both":return{headStart:"arrow",headEnd:"arrow"};case"start":return{headStart:"arrow",headEnd:"none"};case"end":return{headStart:"none",headEnd:"arrow"};case"none":return{headStart:"none",headEnd:"none"}}}function Qd(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function Jd(e){return void 0!==Qd(e)}function ec({dataUi:e,editor:t,idPrefix:n,shape:i,stroke:o,strokeWidth:r,vectorEffect:s}){const a=`${n}-content-clip-${i.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,l=ud(t,i),d=Ld(l,i.props),c=or(t.getShapeContentCutoutLocalPolygonsSignal(i.id)),u=Mo({outputBounds:l.bounds,cutoutLocalPolygons:c});
23
- return Hx("svg",{"data-ui":e,width:"100%",height:"100%",viewBox:`0 0 ${i.props.w} ${i.props.h}`,overflow:"visible",children:[u?Nx("defs",{children:Nx("clipPath",{id:a,clipPathUnits:"userSpaceOnUse",children:Nx("path",{d:u,clipRule:"evenodd",fillRule:"evenodd"})})}):null,Hx("g",{clipPath:u?`url(#${a})`:void 0,children:[Nx("path",{"data-arrow-path":"body",d:l.path,fill:"none",stroke:o,strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:s}),d.path?Nx("path",{"data-arrow-path":"heads",d:d.path,fill:"none",stroke:o,strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:s}):null]})]})}function tc(e){return/^\s*$/.test(e)?"Frame":e}function nc(e){return new SI(0,-34,e.props.w,e.props.h+34)}function ic(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function oc(e,t,n){const i=n/2;return!!e.expand(i).containsPoint(t)&&(Math.abs(t.x-e.minX)<=i||Math.abs(t.x-e.maxX)<=i||Math.abs(t.y-e.minY)<=i||Math.abs(t.y-e.maxY)<=i)}function rc(e){return{id:`frame.set-${e}`,getAvailability:e=>"frame"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const i of e){if("frame"!==i.type)continue;const e=i.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!D(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=dc(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(e=>"frame"===e.type).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function sc(e){return{id:`frame.default-${e}`,getAvailability:e=>"frame"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("frame")[e],run({context:t,value:n}){const i=dc(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("frame",{[e]:i})}}}function ac({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"color-input",id:`${i}.fill`,actionId:e,label:"Fill",fallback:"#f8fafc",presets:ok.map(e=>({...e,dataUi:`${i}-fill-${e.id}-button`})),dataUi:`${i}.fill`}]},{id:`${i}.style-stroke`,items:[{kind:"color-input",id:`${i}.stroke`,actionId:t,label:"Stroke",previewStyle:"outline",fallback:"#94a3b8",presets:rk.map(e=>({...e,dataUi:`${i}-stroke-${e.id}-button`})),dataUi:`${i}.stroke`}]},{id:`${i}.style-stroke-width`,items:[{kind:"text-input",id:`${i}.stroke-width`,actionId:n,label:"Stroke width",placeholder:"1",suffix:"Px",validate:uc,dataUi:`${i}-stroke-width-control`}]}]}function lc(e){return{id:`frame.child-order.${e}`,getAvailability:t=>"frame"!==hc(t)?"inapplicable":t.editor.canMoveSelectionWithinParent(e)?"enabled":"disabled",run({context:t}){t.editor.moveSelectionWithinParent(e,"user")}}}function dc(e,t){return"strokeWidth"===e?cc(t):R(t)?$(t,"fill"===e?E("transparent"):M("stroke-muted")):void 0}function cc(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function uc(e){return void 0!==cc(e)}function hc(e){const[t]=e.selection.selectedShapes;return 1===e.selection.count&&t?.parentId.startsWith("shape:")?e.editor.getShape(t.parentId)?.type??null:null}function pc({shape:e,hideName:t=!1}){const{fill:n,h:i,name:o,stroke:r,strokeWidth:s,w:a}=e.props,l=s/2,d=Math.max(a-s,0),c=Math.max(i-s,0),u=tc(o),h=nc(e);
24
- return Hx("svg",{width:"100%",height:"100%",viewBox:`${h.x} ${h.y} ${h.w} ${h.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[Nx("rect",{x:l,y:l,width:d,height:c,fill:F(n),stroke:F(r),strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"}),t?null:Nx("text",{x:0,y:-8,fill:F(r),fontFamily:ak,fontSize:12,fontWeight:400,style:{userSelect:"none"},children:u})]})}function gc({editor:e,shape:t,isEditing:n}){const i=Ux(null),o=or(e.cameraZoomSignal),r=or(e.getShapeLocalToPageTransformSignal(t.id)),s=Math.max(o,1e-4),a=Math.min(1/s,3.5),l=(e=>{const t=2*Math.PI;return Math.floor(2*((e%t+t)%t+Math.PI/4)/Math.PI%4)})(r?Math.atan2(r.b,r.a):0),d=0===l||2===l?t.props.w:t.props.h,c=((e,t)=>{switch(t){case 0:return"";case 1:return`translate(0px, ${e.props.h}px) rotate(270deg)`;case 2:return`translate(${e.props.w}px, ${e.props.h}px) rotate(180deg)`;case 3:return`translate(${e.props.w}px, 0px) rotate(90deg)`}})(t,l),u=tc(t.props.name);Bx(()=>{const e=i.current;n&&e&&(e.focus(),e.select())},[n]);const h=Ex(()=>{e.canEditShape(t)&&e.startEditingShape({shapeId:t.id,entryMode:"selectAll",markId:"frame.edit"},"user")},[e,t]),p=Ex(n=>{e.commands.updateShapes([{id:t.id,props:{name:n.currentTarget.value}}],{source:"user"})},[e,t.id]),g=Ex(t=>{e.completeEditing("user")},[e]),f=Ex(t=>{e.setShapeEditingComposition(!0,"system")},[e]),m=Ex(t=>{e.setShapeEditingComposition(!1,"system")},[e]),S=Ex(t=>{if(t.stopPropagation(),!t.nativeEvent.isComposing)return"Enter"===t.key?(t.preventDefault(),void e.completeEditing("user")):void("Escape"===t.key&&(t.preventDefault(),e.cancelEditing("user")))},[e]),y=Ex(e=>{e.stopPropagation()},[]),b=Ex(e=>{e.stopPropagation(),n||h()},[n,h]);
25
- return Nx("div",{style:{height:0,left:0,overflow:"visible",pointerEvents:"none",position:"absolute",top:34,width:0},children:Nx("div",{"data-ui":"frame-canvas-heading","data-shape-id":t.id,role:n?void 0:"button","aria-label":n?void 0:`Edit frame name: ${u}`,onClick:b,onPointerDown:y,style:{alignItems:"center",bottom:0,cursor:t.isLocked?"default":"text",display:"flex",fontFamily:ak,fontSize:12,fontWeight:400,maxWidth:d*s+16,minWidth:32,overflow:n?"visible":"hidden",paddingBottom:4,pointerEvents:t.isLocked?"none":"auto",position:"absolute",transform:`${c} scale(${a}) translateX(-7px)`,transformOrigin:"0 100%",userSelect:"none",whiteSpace:"pre"},children:Nx("div",{style:{alignItems:"center",background:"var(--land-canvas-bg, white)",borderRadius:4,boxShadow:"inset 0 0 0 1px var(--land-canvas-bg, white)",color:"var(--land-text-primary, #0f172a)",display:"flex",height:24,pointerEvents:"auto",width:"100%"},children:Hx("div",{style:{background:n?"var(--land-surface-bg, white)":void 0,borderRadius:4,boxShadow:n?"inset 0 0 0 1.5px var(--land-selection, #2563eb)":void 0,color:n?"transparent":"inherit",height:n?"100%":void 0,minWidth:n?32:void 0,overflow:n?"visible":"hidden",padding:"0 6px",pointerEvents:"auto",position:"relative",textOverflow:"ellipsis",whiteSpace:"pre",width:n?"auto":void 0},children:[Nx("input",{ref:i,"data-ui":"frame-canvas-name-input","data-shape-id":t.id,"aria-label":"Frame name",value:t.props.name,autoComplete:"off",disabled:!n,readOnly:!n,spellCheck:!1,onBlur:g,onChange:p,onCompositionStart:f,onCompositionEnd:m,onKeyDown:S,onPointerDown:y,style:{background:"none",border:0,borderRadius:4,boxSizing:"border-box",color:"var(--land-text-primary, #0f172a)",cursor:"text",display:n?void 0:"none",font:"inherit",height:"100%",inset:0,lineHeight:"24px",minWidth:0,outline:0,padding:"0 6px",position:"absolute",userSelect:"text",width:"100%"}}),u+String.fromCharCode(8203)]})})})})}function fc(e,t,n){const i=e.getDefaultShapeProps("geo"),[o]=e.commands.createShapes([{type:"geo",x:n.x,y:n.y,meta:n.meta?{...n.meta}:void 0,props:{...i,geo:t,w:n.w??i.w,h:n.h??i.h,fill:n.fill??i.fill,stroke:n.stroke??i.stroke,strokeStyle:n.strokeStyle??i.strokeStyle,strokeWidth:n.strokeWidth??i.strokeWidth,cornerRadiusPercent:n.cornerRadiusPercent??i.cornerRadiusPercent}}],{source:"user"});return o&&"geo"===o.type?{id:o.id,type:o.type}:null}function mc(e,t,n={}){return"ellipse"===t?((e,t=32)=>{const n=[];for(let i=0;i<t;i+=1){const o=i/t*Math.PI*2;n.push(new mI(e.center.x+e.w/2*Math.cos(o),e.center.y+e.h/2*Math.sin(o)))}return n})(e):bc(e,t,n)}function Sc(e,t=12){return Math.min(50,Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t))}function yc({cornerRadiusPercent:e=12,h:t,w:n}){return Math.min(Math.max(0,n),Math.max(0,t))*Sc(e)/100}function bc(e,t,n={}){switch(t){case"rhombus":return[new mI(e.center.x,e.minY),new mI(e.maxX,e.center.y),new mI(e.center.x,e.maxY),new mI(e.minX,e.center.y)];case"triangle":return[new mI(e.center.x,e.minY),new mI(e.maxX,e.maxY),new mI(e.minX,e.maxY)];case"hexagon":return[new mI(e.minX+.25*e.w,e.minY),new mI(e.maxX-.25*e.w,e.minY),new mI(e.maxX,e.center.y),new mI(e.maxX-.25*e.w,e.maxY),new mI(e.minX+.25*e.w,e.maxY),new mI(e.minX,e.center.y)];case"star":return(e=>{const t=[];for(let n=0;n<10;n+=1){const e=-Math.PI/2+n*Math.PI/5,i=n%2==0?1:.48;t.push(new mI(Math.cos(e)*i,Math.sin(e)*i))}return((e,t)=>{const n=SI.FromPoints([...e]);return 0===n.w||0===n.h?[t.center]:e.map(e=>new mI(t.minX+(e.x-n.minX)/n.w*t.w,t.minY+(e.y-n.minY)/n.h*t.h))})(t,e)})(e);case"rectangle":return((e,t=yc(e),n=4)=>{const i=Math.min(Math.max(0,t),Math.max(0,e.w)/2,Math.max(0,e.h)/2);if(0===i)return vc(e);const o=[];return Ic(o,{centerX:e.maxX-i,centerY:e.minY+i,radius:i,startAngle:-Math.PI/2,endAngle:0,segments:n}),Ic(o,{centerX:e.maxX-i,centerY:e.maxY-i,radius:i,startAngle:0,endAngle:Math.PI/2,segments:n}),Ic(o,{centerX:e.minX+i,centerY:e.maxY-i,radius:i,startAngle:Math.PI/2,endAngle:Math.PI,segments:n}),Ic(o,{centerX:e.minX+i,centerY:e.minY+i,radius:i,startAngle:Math.PI,endAngle:3*Math.PI/2,segments:n}),o})(e,yc({cornerRadiusPercent:n.cornerRadiusPercent,w:e.w,h:e.h}));default:return vc(e)}}function xc(e,t){if(t.length<3)return!1;let n=!1;for(let i=0,o=t.length-1;i<t.length;o=i,i+=1){const r=t[i],s=t[o];if(r&&s){if(wc(e,r,s)<=1e-6)return!0;r.y>e.y!=s.y>e.y&&e.x<(s.x-r.x)*(e.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}}return n}function Ic(e,{centerX:t,centerY:n,endAngle:i,radius:o,segments:r,startAngle:s}){const a=Math.max(1,Math.floor(r));for(let l=0;l<=a;l+=1){const r=s+l/a*(i-s);e.push(new mI(t+Math.cos(r)*o,n+Math.sin(r)*o))}}function vc(e){return[new mI(e.minX,e.minY),new mI(e.maxX,e.minY),new mI(e.maxX,e.maxY),new mI(e.minX,e.maxY)]}function wc(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o));return e.dist(t.add(i.mul(s)))}function Pc(e){return f(e)&&"geo"===e.type}function kc(e){return"string"==typeof e&&Ik.includes(e)}function Cc(e){return"string"==typeof e&&vk.includes(e)}function Tc(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Mc(e,t){return e.x*t.y-e.y*t.x}function Ec(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return e.dist(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o));return e.dist(t.add(i.mul(s)))}function Ac(e,t,n,i){return Bc(e,t,n,i)?0:Math.min(Ec(e,n,i),Ec(t,n,i),Ec(n,e,t),Ec(i,e,t))}function Bc(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=Mc(o,r);if(Math.abs(s)<1e-8)return null;const a=n.sub(e),l=Mc(a,r)/s,d=Mc(a,o)/s;return l<0||l>1||d<0||d>1?null:{point:e.add(o.mul(l)),t:l}}function Rc(e,t,n){let i=null;for(let o=0;o<n.length;o+=1){const r=n[o],s=n[(o+1)%n.length]??n[0];if(!r||!s)continue;const a=Bc(e,t,r,s);!a||a.t<=1e-6||(!i||a.t<i.t)&&(i=a)}return i?.point??null}function Lc(e){return mc(new SI(0,0,e.props.w,e.props.h),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}function $c(e){const t=new SI(0,0,e.props.w,e.props.h);return[new mI(t.minX,t.minY),new mI(t.center.x,t.minY),new mI(t.maxX,t.minY),new mI(t.minX,t.center.y),t.center,new mI(t.maxX,t.center.y),new mI(t.minX,t.maxY),new mI(t.center.x,t.maxY),new mI(t.maxX,t.maxY)].map((e,t)=>({point:e,kind:wk[t]??"custom"}))}function Fc(e,t){switch(e){case"dashed":return`${4*t} ${2*t}`;case"dotted":return"0 "+2*t;default:return}}function Uc(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Oc(e){return{id:`geo.set-${e}`,getAvailability:e=>"geo"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const i of e){if("geo"!==i.type)continue;const e=i.props[t];if(void 0!==n){if(!("fill"===t||"stroke"===t?D(n,e):n===e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=Kc(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(Pc).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function Dc(e){return{id:`geo.default-${e}`,getAvailability:e=>Xc(e.tool.activeToolId)?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("geo")[e],run({context:t,value:n}){const i=Kc(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("geo",{[e]:i})}}}function zc({fillActionId:e,strokeActionId:t,strokeStyleActionId:n,strokeWidthActionId:i,dataUiPrefix:o}){return[{id:`${o}.style-fill`,items:[{kind:"color-input",id:`${o}.fill`,actionId:e,label:"Fill",fallback:"#e2e8f0",presets:Pk.map(e=>({...e,dataUi:`${o}-fill-${e.id}-button`})),dataUi:`${o}.fill`}]},{id:`${o}.style-stroke`,items:[{kind:"color-input",id:`${o}.stroke`,actionId:t,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:kk.map(e=>({...e,dataUi:`${o}-stroke-${e.id}-button`})),dataUi:`${o}.stroke`}]},{id:`${o}.stroke-style`,presentation:"overflow",items:[{kind:"segmented",id:`${o}.stroke-style`,actionId:n,options:Ck.map(e=>({...e,dataUi:`${o}-stroke-style-${e.value}-button`}))}]},{id:`${o}.style-stroke-width`,items:[{kind:"text-input",id:`${o}.stroke-width`,actionId:i,label:"Stroke width",placeholder:"2",suffix:"Px",validate:_c,dataUi:`${o}-stroke-width-control`}]}]}function Nc(e){let t=null;for(const n of e)if(Pc(n))if(null!==t){if(t!==n.props.geo)return null}else t=n.props.geo;return t}function Hc(e){if("string"!=typeof e||0===e.trim().length)return null;const t=Number(e);return Number.isFinite(t)?t:null}function Wc(e){const t=Hc(e);return null!==t&&t>=0&&t<=50}function _c(e){return void 0!==Yc(e)}function Kc(e,t){return"strokeWidth"===e?Yc(t):"strokeStyle"===e?Cc(t)?t:void 0:R(t)?$(t,M("fill"===e?"fill-slate":"stroke-slate")):void 0}function Yc(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function Xc(e){return Tk.some(t=>t.value===e)}function qc({shape:e,fill:t=e.props.fill,stroke:n=e.props.stroke,strokeStyle:i=e.props.strokeStyle,strokeWidth:o=e.props.strokeWidth}){const{geo:r}=e.props,s="none"===i?0:o,a=s/2,l=Math.max(e.props.w-s,0),d=Math.max(e.props.h-s,0),c=yc({cornerRadiusPercent:e.props.cornerRadiusPercent,w:l,h:d}),u="ellipse"===r||"rectangle"===r?null:bc(new SI(a,a,l,d),r).map(e=>`${e.x},${e.y}`).join(" "),h={fill:F(t),stroke:"none"===i?"none":F(n),strokeWidth:s,strokeDasharray:Fc(i,o),strokeLinejoin:"round",strokeLinecap:"round"};
26
- return Nx("svg",{width:"100%",height:"100%",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:"ellipse"===r?Nx("ellipse",{...h,cx:e.props.w/2,cy:e.props.h/2,rx:l/2,ry:d/2}):"rectangle"!==r?Nx("polygon",{...h,points:u??""}):Nx("rect",{...h,x:a,y:a,width:l,height:d,rx:c,ry:c})})}function jc(e,t={}){const n=new Set,i=new Set,o=[];for(const r of e){for(const e of r.groups){const s=Vc(t.dedupeActionIdsAcrossSources?e.items.filter(e=>!("actionId"in e&&n.has(e.actionId))):e.items);if(0===s.length)continue;const a=r.groupIdPrefix?`${r.groupIdPrefix}.${e.id}`:e.id;if(i.has(a))throw new Error(`Duplicate merged toolbar group id: ${a}.`);i.add(a),o.push({...e,id:a,items:s})}if(t.dedupeActionIdsAcrossSources)for(const e of r.groups)for(const t of e.items)"actionId"in t&&n.add(t.actionId)}return o}function Vc(e){const t=[];for(const n of e)("separator"!==n.kind||0!==t.length&&"separator"!==t.at(-1)?.kind)&&t.push(n);return"separator"===t.at(-1)?.kind&&t.pop(),t}function Gc(e){return Object.freeze({id:e})}function Zc(e){return{...e,id:e.token.id}}function Qc(e){return{id:e.id,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function Jc(e,t={}){const n={...t,id:e.id,run({context:t}){e.run(t.editor)}};return SC.set(n,{execute:(t,n)=>(t.executeFromAction(e,n.context),!0)}),n}function eu(e,t){const{toCommandArgs:n,...i}=t,o={...i,id:e.id,run(t){const i=n(t);i&&e.run(t.context.editor,...i)}};return SC.set(o,{execute(t,i){const o=n(i);return!!o&&(t.executeFromAction(e,i.context,...o),!0)}}),o}function tu(e){return e}function nu({editor:e,getHostElement:t,imports:n}){return Bx(()=>{const i=i=>{if(!ru(t(),i)||e.shapeEditingStateSignal.get().session||Lr(i.target))return;const o=ou({source:"clipboard",dataTransfer:i.clipboardData});n.canImport(o)&&(i.preventDefault(),n.import(o,{editor:e}).catch(lu))},o=i=>{!ru(t(),i)||e.shapeEditingStateSignal.get().session||Lr(i.target)||n.canImportPreview(iu(i.dataTransfer))&&(i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="copy"))},r=i=>{const o=ru(t(),i);if(!o||e.shapeEditingStateSignal.get().session||Lr(i.target))return;const r=n.canImportPreview(iu(i.dataTransfer)),s=ou({source:"drop",dataTransfer:i.dataTransfer,pagePoint:Fr(e,i,o)});n.canImport(s)?(i.preventDefault(),n.import(s,{editor:e}).catch(lu)):r&&(i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="none"))};return window.addEventListener("paste",i),window.addEventListener("dragover",o),window.addEventListener("drop",r),()=>{window.removeEventListener("paste",i),window.removeEventListener("dragover",o),window.removeEventListener("drop",r)}},[e,t,n]),null}function iu(e){return e?{source:"drop",dataTypes:Array.from(e.types),fileTypes:Array.from(e.items).filter(e=>"file"===e.kind).map(e=>e.type).filter(Boolean)}:{source:"drop",dataTypes:[],fileTypes:[]}}function ou({dataTransfer:e,pagePoint:t,source:n}){const i=e?.getData("text/plain")||void 0,o=e?.getData("text/html")||void 0,r=[...(e?.getData("text/uri-list")||void 0)?.split(/\r?\n/).filter(e=>e&&!e.startsWith("#"))??[],...i&&au(i.trim())?[i.trim()]:[]];return{source:n,files:su(e),text:i,html:o,...r.length>0?{urls:r}:{},pagePoint:t}}function ru(e,t){if(!e)return null;const n=(t.target instanceof Element?t.target:document.activeElement)?.closest(Aw);return n instanceof HTMLElement&&e.contains(n)?n:null}function su(e){if(!e)return[];const t=Array.from(e.files);return t.length>0?t:Array.from(e.items).flatMap(e=>{if("file"!==e.kind)return[];const t=e.getAsFile();return t?[t]:[]})}function au(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return e.startsWith("data:image/")}}function lu(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function du(e){return e.get(MC)}async function cu({context:e,services:t}){const n=du(t);if(!n)return null;const i=e.editor.createClipboardPayloadFromSelection();return i?(await n.write(i),i):null}async function uu({atMenuPoint:e=!1,context:t,services:n}){const i=du(n);if(!i)return;const o=await i.read();o&&t.editor.pasteClipboardPayload({payload:o,pagePoint:hu({atMenuPoint:e,context:t}),source:"user"})}function hu({atMenuPoint:e,context:t}){return e&&pu(t)?t.menu.anchor.pagePoint:t.editor.inputs.state.get().currentPagePoint??t.editor.viewportPageBoundsSignal.get()?.center??void 0}function pu(e){return"menu"in e}function gu({children:e}){const[t,n]=Ox(null),i=Ex(e=>{n(e)},[]),o=Fx(()=>({registerTarget:i,target:t}),[i,t]);
27
- return Nx($C.Provider,{value:o,children:e})}function fu(){const{registerTarget:e}=Su();
28
- return Nx("div",{ref:e,className:"land-canvas__floating-portal-host","data-ui":"canvas-kit-floating-portal-host"})}function mu(){return Su().target}function Su(){const e=Ax($C);if(!e)throw new Error("CanvasKit floating content must be rendered inside CanvasKitRoot.");return e}function yu({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const i=mu();return i?rI(Nx("div",{"data-ui":n,className:bu("land-canvas__floating-toolbar-layer",t),children:e}),i):null}function bu(...e){return e.filter(Boolean).join(" ")}function xu(e){Bx(()=>{const t=e.current;if(!t)return;const n=e=>{(e=>e.scrollHeight>e.clientHeight)(t)||function(e,t){const n=(e=>{const t=e?.getRootNode();return t instanceof Document||t instanceof ShadowRoot?$r(t):$r()})(t);return!!n&&(n.dispatchEvent(new WheelEvent("wheel",{altKey:e.altKey,bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,composed:!0,ctrlKey:e.ctrlKey,deltaMode:e.deltaMode,deltaX:e.deltaX,deltaY:e.deltaY,deltaZ:e.deltaZ,metaKey:e.metaKey,screenX:e.screenX,screenY:e.screenY,shiftKey:e.shiftKey,view:window})),!0)}(e,t)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",n,{passive:!1}),()=>{t.removeEventListener("wheel",n)}},[e])}function Iu(e,t,n){return UC(e,FC(t,n))}function vu(e,t){return"function"==typeof e?e(t):e}function wu(e){return e.split("-")[0]}function Pu(e){return e.split("-")[1]}function ku(e){return"x"===e?"y":"x"}function Cu(e){return"y"===e?"height":"width"}function Tu(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function Mu(e){return ku(Tu(e))}function Eu(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function Au(e){const t=wu(e);return NC[t]+e.slice(t.length)}function Bu(e){const{x:t,y:n,width:i,height:o}=e;return{width:i,height:o,top:n,left:t,right:t+i,bottom:n+o,x:t,y:n}}function Ru(e,t,n){let{reference:i,floating:o}=e;const r=Tu(t),s=Mu(t),a=Cu(s),l=wu(t),d="y"===r,c=i.x+i.width/2-o.width/2,u=i.y+i.height/2-o.height/2,h=i[a]/2-o[a]/2;let p;switch(l){case"top":p={x:c,y:i.y-o.height};break;case"bottom":p={x:c,y:i.y+i.height};break;case"right":p={x:i.x+i.width,y:u};break;case"left":p={x:i.x-o.width,y:u};break;default:p={x:i.x,y:i.y}}switch(Pu(t)){case"start":p[s]-=h*(n&&d?-1:1);break;case"end":p[s]+=h*(n&&d?-1:1)}return p}async function Lu(e,t){var n;void 0===t&&(t={});const{x:i,y:o,platform:r,rects:s,elements:a,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:c="viewport",elementContext:u="floating",altBoundary:h=!1,padding:p=0}=vu(t,e),g=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(p),f=a[h?"floating"===u?"reference":"floating":u],m=Bu(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(f)))||n?f:f.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:d,rootBoundary:c,strategy:l})),S="floating"===u?{x:i,y:o,width:s.floating.width,height:s.floating.height}:s.reference,y=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),b=await(null==r.isElement?void 0:r.isElement(y))&&await(null==r.getScale?void 0:r.getScale(y))||{x:1,y:1},x=Bu(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:S,offsetParent:y,strategy:l}):S);return{top:(m.top-x.top+g.top)/b.y,bottom:(x.bottom-m.bottom+g.bottom)/b.y,left:(m.left-x.left+g.left)/b.x,right:(x.right-m.right+g.right)/b.x}}function $u(){return"undefined"!=typeof window}function Fu(e){return Du(e)?(e.nodeName||"").toLowerCase():"#document"}function Uu(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Ou(e){var t;return null==(t=(Du(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Du(e){return!!$u()&&(e instanceof Node||e instanceof Uu(e).Node)}function zu(e){return!!$u()&&(e instanceof Element||e instanceof Uu(e).Element)}function Nu(e){return!!$u()&&(e instanceof HTMLElement||e instanceof Uu(e).HTMLElement)}function Hu(e){return!(!$u()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Uu(e).ShadowRoot)}function Wu(e){const{overflow:t,overflowX:n,overflowY:i,display:o}=ju(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+n)&&"inline"!==o&&"contents"!==o}function _u(e){return/^(table|td|th)$/.test(Fu(e))}function Ku(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Yu(e){const t=zu(e)?ju(e):e;return jC(t.transform)||jC(t.translate)||jC(t.scale)||jC(t.rotate)||jC(t.perspective)||!Xu()&&(jC(t.backdropFilter)||jC(t.filter))||XC.test(t.willChange||"")||qC.test(t.contain||"")}function Xu(){return null==sI&&(sI="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),sI}function qu(e){return/^(html|body|#document)$/.test(Fu(e))}function ju(e){return Uu(e).getComputedStyle(e)}function Vu(e){return zu(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Gu(e){if("html"===Fu(e))return e;const t=e.assignedSlot||e.parentNode||Hu(e)&&e.host||Ou(e);return Hu(t)?t.host:t}function Zu(e){const t=Gu(e);return qu(t)?e.ownerDocument?e.ownerDocument.body:e.body:Nu(t)&&Wu(t)?t:Zu(t)}function Qu(e,t,n){var i;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=Zu(e),r=o===(null==(i=e.ownerDocument)?void 0:i.body),s=Uu(o);if(r){const e=Ju(s);return t.concat(s,s.visualViewport||[],Wu(o)?o:[],e&&n?Qu(e):[])}return t.concat(o,Qu(o,[],n))}function Ju(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function eh(e){const t=ju(e);let n=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const o=Nu(e),r=o?e.offsetWidth:n,s=o?e.offsetHeight:i,a=OC(n)!==r||OC(i)!==s;return a&&(n=r,i=s),{width:n,height:i,$:a}}function th(e){return zu(e)?e:e.contextElement}function nh(e){const t=th(e);if(!Nu(t))return zC(1);const n=t.getBoundingClientRect(),{width:i,height:o,$:r}=eh(t);let s=(r?OC(n.width):n.width)/i,a=(r?OC(n.height):n.height)/o;return s&&Number.isFinite(s)||(s=1),a&&Number.isFinite(a)||(a=1),{x:s,y:a}}function ih(e){const t=Uu(e);return Xu()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:VC}function oh(e,t,n,i){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=th(e);let s=zC(1);t&&(i?zu(i)&&(s=nh(i)):s=nh(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Uu(e))&&t))(r,n,i)?ih(r):zC(0);let l=(o.left+a.x)/s.x,d=(o.top+a.y)/s.y,c=o.width/s.x,u=o.height/s.y;if(r){const e=Uu(r),t=i&&zu(i)?Uu(i):i;let n=e,o=Ju(n);for(;o&&i&&t!==n;){const e=nh(o),t=o.getBoundingClientRect(),i=ju(o),r=t.left+(o.clientLeft+parseFloat(i.paddingLeft))*e.x,s=t.top+(o.clientTop+parseFloat(i.paddingTop))*e.y;l*=e.x,d*=e.y,c*=e.x,u*=e.y,l+=r,d+=s,n=Uu(o),o=Ju(n)}}return Bu({width:c,height:u,x:l,y:d})}function rh(e,t){const n=Vu(e).scrollLeft;return t?t.left+n:oh(Ou(e)).left+n}function sh(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-rh(e,n),y:n.top+t.scrollTop}}function ah(e,t,n){let i;if("viewport"===t)i=((e,t)=>{const n=Uu(e),i=Ou(e),o=n.visualViewport;let r=i.clientWidth,s=i.clientHeight,a=0,l=0;if(o){r=o.width,s=o.height;const e=Xu();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,l=o.offsetTop)}const d=rh(i);if(d<=0){const e=i.ownerDocument,t=e.body,n=getComputedStyle(t),o="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,s=Math.abs(i.clientWidth-t.clientWidth-o);s<=25&&(r-=s)}else d<=25&&(r+=d);return{width:r,height:s,x:a,y:l}})(e,n);else if("document"===t)i=(e=>{const t=Ou(e),n=Vu(e),i=e.ownerDocument.body,o=UC(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),r=UC(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let s=-n.scrollLeft+rh(e);const a=-n.scrollTop;return"rtl"===ju(i).direction&&(s+=UC(t.clientWidth,i.clientWidth)-o),{width:o,height:r,x:s,y:a}})(Ou(e));else if(zu(t))i=((e,t)=>{const n=oh(e,!0,"fixed"===t),i=n.top+e.clientTop,o=n.left+e.clientLeft,r=Nu(e)?nh(e):zC(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:o*r.x,y:i*r.y}})(t,n);else{const n=ih(e);i={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Bu(i)}function lh(e,t){const n=Gu(e);return!(n===t||!zu(n)||qu(n))&&("fixed"===ju(n).position||lh(n,t))}function dh(e,t){const n=t.get(e);if(n)return n;let i=Qu(e,[],!1).filter(e=>zu(e)&&"body"!==Fu(e)),o=null;const r="fixed"===ju(e).position;let s=r?Gu(e):e;for(;zu(s)&&!qu(s);){const t=ju(s),n=Yu(s);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||Wu(s)&&!n&&lh(e,s))?i=i.filter(e=>e!==s):o=t,s=Gu(s)}return t.set(e,i),i}function ch(e,t,n){function i(){d.x=rh(r)}const o=Nu(t),r=Ou(t),s="fixed"===n,a=oh(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const d=zC(0);if(o||!o&&!s)if(("body"!==Fu(t)||Wu(r))&&(l=Vu(t)),o){const e=oh(t,!0,s,t);d.x=e.x+t.clientLeft,d.y=e.y+t.clientTop}else r&&i();s&&!o&&r&&i();const c=!r||o||s?zC(0):sh(r,l);return{x:a.left+l.scrollLeft-d.x-c.x,y:a.top+l.scrollTop-d.y-c.y,width:a.width,height:a.height}}function uh(e){return"static"===ju(e).position}function hh(e,t){if(!Nu(e)||"fixed"===ju(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Ou(e)===n&&(n=n.ownerDocument.body),n}function ph(e,t){const n=Uu(e);if(Ku(e))return n;if(!Nu(e)){let t=Gu(e);for(;t&&!qu(t);){if(zu(t)&&!uh(t))return t;t=Gu(t)}return n}let i=hh(e,t);for(;i&&_u(i)&&uh(i);)i=hh(i,t);return i&&qu(i)&&uh(i)&&!Yu(i)?n:i||(e=>{let t=Gu(e);for(;Nu(t)&&!qu(t);){if(Yu(t))return t;if(Ku(t))return null;t=Gu(t)}return null})(e)||n}function gh(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function fh({editor:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:i,offset:o,placement:r}){Bx(()=>{const s=i(),a=n.current;if(!s||!a)return;let l=!1,d=0;a.style.visibility="hidden";const c=()=>{const e=++d,n=mh("--toolbar-floating-shift-padding",8),i=o??mh("--toolbar-floating-offset",38),c={top:mh("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((e,t,n)=>{const i={platform:GC,...n},o={...i.platform,_c:new Map};return(async(e,t,n)=>{const{placement:i="bottom",strategy:o="absolute",middleware:r=[],platform:s}=n,a=s.detectOverflow?s:{...s,detectOverflow:Lu},l=await(null==s.isRTL?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:c,y:u}=Ru(d,i,l),h=i,p=0;const g={};for(let f=0;f<r.length;f++){const n=r[f];if(!n)continue;const{name:m,fn:S}=n,{x:y,y:b,data:x,reset:I}=await S({x:c,y:u,initialPlacement:i,placement:h,strategy:o,middlewareData:g,rects:d,platform:a,elements:{reference:e,floating:t}});c=null!=y?y:c,u=null!=b?b:u,g[m]={...g[m],...x},I&&p<50&&(p++,"object"==typeof I&&(I.placement&&(h=I.placement),I.rects&&(d=!0===I.rects?await s.getElementRects({reference:e,floating:t,strategy:o}):I.rects),({x:c,y:u}=Ru(d,h,l))),f=-1)}return{x:c,y:u,placement:h,strategy:o,middlewareData:g}})(e,t,{...i,platform:o})})(s,a,{strategy:"fixed",placement:r,middleware:[ZC(i),JC({fallbackPlacements:[...t],padding:c}),QC({padding:c})]}).then(({placement:t,x:n,y:i})=>{l||e!==d||(a.dataset.placement=t,a.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(i)}px, 0)`,a.style.visibility="visible")})},u=function(e,t,n,i){void 0===i&&(i={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:s="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:l=!1}=i,d=th(e),c=o||r?[...d?Qu(d):[],...t?Qu(t):[]]:[];c.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=d&&a?((e,t)=>{function n(){var e;clearTimeout(i),null==(e=o)||e.disconnect(),o=null}let i,o=null;const r=Ou(e);return function s(a,l){function d(t){const n=t[0].intersectionRatio;if(n!==l){if(!m)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}1!==n||gh(c,e.getBoundingClientRect())||s(),m=!1}void 0===a&&(a=!1),void 0===l&&(l=1),n();const c=e.getBoundingClientRect(),{left:u,top:h,width:p,height:g}=c;if(a||t(),!p||!g)return;const f={rootMargin:-DC(h)+"px "+-DC(r.clientWidth-(u+p))+"px "+-DC(r.clientHeight-(h+g))+"px "+-DC(u)+"px",threshold:UC(0,FC(1,l))||1};let m=!0;try{o=new IntersectionObserver(d,{...f,root:r.ownerDocument})}catch(S){o=new IntersectionObserver(d,f)}o.observe(e)}(!0),n})(d,n):null;let h,p=-1,g=null;s&&(g=new ResizeObserver(e=>{let[i]=e;i&&i.target===d&&g&&t&&(g.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var e;null==(e=g)||e.observe(t)})),n()}),d&&!l&&g.observe(d),t&&g.observe(t));let f=l?oh(e):null;return l&&function t(){const i=oh(e);f&&!gh(f,i)&&n(),f=i,h=requestAnimationFrame(t)}(),n(),()=>{var e;c.forEach(e=>{o&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=g)||e.disconnect(),g=null,l&&cancelAnimationFrame(h)}}(s,a,c,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),h=Jo("CanvasKitFloatingPosition.pageTransform",e.pageTransformSignal,c,{fireImmediately:!1});return c(),()=>{l=!0,a.style.visibility="hidden",u(),h()}},[e,t,n,i,o,r])}function mh(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 Sh({children:e,className:t,context:n,dataUi:i="floating-selection-toolbar-slot",horizontalAlign:o="start",offset:r,visible:s=!0}){return s?Nx(yh,{editor:n.editor,className:t,dataUi:i,offset:r,horizontalAlign:o,children:e}):null}function yh({children:e,className:t,dataUi:n,editor:i,horizontalAlign:o,offset:r}){return or(i.selectionTranslationActiveSignal)?null:Nx(bh,{className:t,dataUi:n,editor:i,horizontalAlign:o,offset:r,children:e})}function bh({children:e,className:t,dataUi:n,editor:i,horizontalAlign:o,offset:r}){const s=or(i.queries.selectionPageBoundsSignal);return s?Nx(xh,{anchor:{x:s.minX,y:s.minY,width:s.w,height:s.h},className:t,dataUi:n,editor:i,horizontalAlign:o,offset:r,children:e}):null}function xh({anchor:e,children:t,className:n,dataUi:i,editor:o,horizontalAlign:r,offset:s}){const a=Ux(null),l=Ux(null);xu(l);const d=Ex(()=>a.current,[e.height,e.width,e.x,e.y]);return fh({editor:o,fallbackPlacements:"center"===r?tT:eT,floatingRef:l,getReferenceElement:d,offset:s,placement:"center"===r?"top":"top-start"}),Hx(zx,{children:[Nx(rr,{dataUi:`${i}-page-space`,className:"land-canvas__floating-selection-page-space",children:Nx("div",{ref:a,"aria-hidden":"true",style:{position:"absolute",left:e.x,top:e.y,width:e.width,height:e.height,pointerEvents:"none"}})}),Nx("div",{ref:l,"data-ui":i,className:Ih("land-canvas__floating-selection-anchor",n),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:t})]})}function Ih(...e){return e.filter(Boolean).join(" ")}function vh({presenter:e}){function t({children:t}){
29
- return Nx(Fa,{presenter:e,children:t})}return{id:"canvas-kit.text",requires:[LP],setup(e){e.get(wC).addProviders({id:"canvas-kit.text-link-popover-presenter",component:t})}}}function wh(e){return t=>Nx(Ph,{...t,icons:e})}function Ph({icons:e,...t}){const n=mu();return n?rI(Nx(kh,{...t,icons:e}),n):null}function kh({icons:e,...t}){const{anchorElement:n,href:i,onOpen:o,onPopoverPointerEnter:r,onPopoverPointerLeave:s}=t,a=ir(),l=Ux(null),d=Ex(()=>n,[n]);return xu(l),fh({editor:a,fallbackPlacements:nT,floatingRef:l,getReferenceElement:d,offset:8,placement:"top"}),Hx("div",{ref:l,"aria-label":"Link preview",className:"land-canvas-kit__text-link-popover","data-ui":"rich-text-link-popover",role:"toolbar",onPointerEnter:r,onPointerLeave:s,onPointerDown:e=>{e.stopPropagation()},onClick:e=>{e.stopPropagation()},children:[Nx("button",{"aria-label":"Open link",className:"land-canvas-kit__text-link-popover-icon-button",title:"Open link",type:"button",onClick:o,children:e.open}),Nx("button",{"aria-label":`Open ${i}`,className:"land-canvas-kit__text-link-popover-link",title:i,type:"button",onClick:o,children:i})]})}function Ch(e,t={}){const n=t.enabled??!0,i=t.pageId,o=Ex(t=>n?e.subscribe(t):()=>{},[n,e]),r=Ex(()=>n?e.getSnapshot(i):iT,[n,i,e]);return Dx(o,r,r)}function Th({editor:e,toolState:t,selectionState:n}){return{editor:e,selection:{selectedShapeIds:e.getSelectedShapeIds(),selectedShapes:e.getSelectedShapes(),count:n.count,singleShapeType:n.singleShapeType,commonShapeType:n.commonShapeType,canFlip:n.canFlipSelection,canResetRotation:n.canResetSelectionRotation,isMixedFrameAndPointHandleSelection:n.isMixedFrameAndPointHandleSelection},tool:{activeToolId:t.activeToolId,isToolLocked:t.isToolLocked}}}function Mh(e,t){const n=Ex(n=>t?Jo("useOptionalValue",e,n,{fireImmediately:!1}):()=>{},[t,e]),i=Ex(()=>t?e.get():null,[t,e]);return Dx(n,i,i)}function Eh(e){return new Promise((t,n)=>{const i=new FileReader;i.addEventListener("load",()=>{t("string"==typeof i.result?i.result:null)}),i.addEventListener("error",()=>{n(i.error)}),i.readAsDataURL(e)})}async function Ah({assetInliners:e=[],editor:t,padding:n=16,resolveThemeColor:i,shapeIds:o}){const r=t.repairExportIntegrity(o),s=t.getShapeCapabilityManifest();let a,l=t.getExportIntegrityReport(o);try{a=await(async({assetInliners:e,editor:t,padding:n,resolveThemeColor:i,shapeIds:o})=>{for(let s=0;s<3;s+=1){const s=t.store.recordsSignal.get();try{for(const n of e)await(n.prepare?.({editor:t,requestedShapeIds:o}))}catch(r){if(t.store.recordsSignal.get()!==s)continue;throw r}if(t.store.recordsSignal.get()!==s)continue;const a=t.getSvgString(o,{padding:n,resolveThemeColor:i}),l=a?.exportedShapeIds.flatMap(e=>{const n=t.getShape(e);return n?[n]:[]})??[];if(t.store.recordsSignal.get()===s)return{exportedShapes:l,result:a}}throw new Error("The document changed repeatedly during SVG export.")})({assetInliners:e,editor:t,padding:n,resolveThemeColor:i,shapeIds:o})}catch(p){return l=t.getExportIntegrityReport(o),Bh({capabilityManifest:s,cause:p,integrity:l})}l=t.getExportIntegrityReport(o);const d=(({capabilityManifest:e,integrity:t})=>{const n=(e=>{const t=Object.entries(e).filter(e=>"number"==typeof e[1]);return 0===t.length?"none":t.map(([e,t])=>`${e} ${t}`).join(", ")})((e=>{const t={};for(const n of e.issues)t[n.kind]=(t[n.kind]??0)+1;return t})(t));return 0===t.fatalIssueCount&&0===t.issues.length?{tone:"success",title:"SVG export ready",details:`${t.requestedShapeIds.length} shape(s) ready. Issues: ${n}.`,integrity:t,capabilityManifest:e}:t.canExport?{tone:"warning",title:"SVG export repaired",details:`${t.requestedShapeIds.length} shape(s) exportable. Issues: ${n}.`,integrity:t,capabilityManifest:e}:{tone:"error",title:"SVG export blocked",details:`Fatal export issue(s): ${n}.`,integrity:t,capabilityManifest:e}})({capabilityManifest:s,integrity:l});(r.before.issues.length>0||l.issues.length>0)&&console.warn("SVG export integrity report",{before:r.before,after:r.after,final:l});const{exportedShapes:c,result:u}=a;if(!u)return{status:{...d,tone:"error",title:"SVG export blocked",details:`${d.details} No exportable SVG content was produced.`},svg:null,width:null,height:null,exportedShapeIds:[],skippedShapes:[]};u.skippedShapes.length>0&&console.warn("Skipped shapes during SVG export",u.skippedShapes);let h=u.svg;try{for(const n of e)h=await n.inline({editor:t,exportedShapes:c,exportedShapeIds:u.exportedShapeIds,svg:h});(e=>{const t=new Set,n=/\burl\(\s*(["']?)(.*?)\1\s*\)/giu,i=Array.from(e.matchAll(/<([a-z][\w:-]*)\b([^>]*)>/giu));for(const r of i){const e=Rh(r[1]??""),n=$h(r[2]??"");for(const i of Lh(e)){const e=n.get(i)?.trim();if(!e)continue;const o="srcset"===i?Fh(e):[e];for(const n of o)Uh(n)||t.add(n)}}const o=[...i.map(e=>e[0]),...Array.from(e.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/giu),e=>e[1]??"")];for(const r of o){for(const e of r.matchAll(n)){const n=e[2]?.trim();n&&!Uh(n)&&t.add(n)}/@import\b/iu.test(r)&&t.add("CSS @import"),/\blocal\(/iu.test(r)&&t.add("CSS local() font source")}if(t.size>0)throw new Error(`${t.size} external SVG resource(s) remain after embedding.`)})(h)}catch(p){return Bh({capabilityManifest:s,cause:p,exportedShapeIds:u.exportedShapeIds,integrity:l,skippedShapes:u.skippedShapes})}return{status:d,svg:h,width:u.width,height:u.height,exportedShapeIds:u.exportedShapeIds,skippedShapes:u.skippedShapes}}function Bh({capabilityManifest:e,cause:t,exportedShapeIds:n=[],integrity:i,skippedShapes:o=[]}){const r=t instanceof Error&&t.message.trim().length>0?t.message:"An SVG resource could not be embedded.";return console.warn("SVG resource embedding failed",t),{status:{tone:"error",title:"SVG export blocked",details:`Resource embedding failed: ${r}`,integrity:i,capabilityManifest:e},svg:null,width:null,height:null,exportedShapeIds:n,skippedShapes:o}}function Rh(e){return(e.split(":").pop()??e).toLowerCase()}function Lh(e){const t=oT[e]??[];return sT.has(e)?t:[...rT,...t]}function $h(e){const t=new Map;for(const n of e.matchAll(/([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gu)){const e=n[1]?.toLowerCase(),i=n[2]??n[3]??n[4];e&&void 0!==i&&t.set(e,i)}return t}function Fh(e){const t=[];let n=0;for(;n<e.length;){for(;n<e.length&&(","===e[n]||/\s/u.test(e[n]??""));)n+=1;if(n>=e.length)break;const i="data:"===e.slice(n,n+5).toLowerCase(),o=n;for(;n<e.length&&!/\s/u.test(e[n]??"")&&(i||","!==e[n]);)n+=1;let r=e.slice(o,n);const s=i&&r.endsWith(",");if(s&&(r=r.replace(/,+$/u,"")),r&&t.push(r),!s)for(;n<e.length&&","!==e[n];)n+=1}return t}function Uh(e){return e.startsWith("#")||/^data:/iu.test(e)}function Oh(e){return new Promise((t,n)=>{e.toBlob(e=>{e?t(e):n(new Error("The browser did not produce a PNG blob."))},"image/png")})}function Dh(e,t){return{...e,title:"success"===e.tone?"PNG export ready":"warning"===e.tone?"PNG export repaired":"PNG export blocked",details:t?`${e.details} ${t}`:e.details}}function zh({editor:e,exportRegistry:t}){let n=!1;const i=i=>(async()=>{if(n)throw new Error("An export is already in progress.");n=!0;try{return await t.export(i.format,{editor:e,shapeIds:Hh(e,i),options:i.options})}finally{n=!1}})();return{getFormats:()=>t.getFormats(),export:i,exportPng:async e=>(await i({...Nh(e),format:"png",options:e})).result,exportSvg:async e=>(await i({...Nh(e),format:"svg",options:e})).result}}function Nh(e){return e.scope?{scope:e.scope}:{shapeIds:e.shapeIds}}function Hh(e,t){if("selection"===t.scope)return e.getSelectedShapeIds();if("page"===t.scope)return e.getCurrentPageShapeIds();if(!t.shapeIds)throw new Error("Canvas export requires a scope or shapeIds.");return t.shapeIds}function Wh({svgAssetInliners:e}){return{id:"canvas-kit.export",provides:[dT],setup(t){t.get(CP).add((({assetInliners:e})=>({id:"canvas-kit.export.svg",format:"svg",label:"SVG",mimeType:"image/svg+xml;charset=utf-8",fileExtension:"svg",async export({editor:t,options:n,shapeIds:i}){const o=n??{},r=await Ah({assetInliners:e,editor:t,padding:o.padding,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:i});return{data:r.svg,result:r,status:r.status}}}))({assetInliners:e}),(({assetInliners:e})=>({id:"canvas-kit.export.png",format:"png",label:"PNG",mimeType:"image/png",fileExtension:"png",async export({editor:t,options:n,shapeIds:i}){const o=n??{},r=await async function({background:e,pixelRatio:t=2,...n}){const i=await Ah(n);if(!i.svg||null===i.width||null===i.height)return{status:"error"===i.status.tone?Dh(i.status):{...i.status,tone:"error",title:"PNG export blocked",details:`${i.status.details} No exportable SVG content was produced.`},blob:null,width:null,height:null,exportedShapeIds:i.exportedShapeIds,skippedShapes:i.skippedShapes};try{const n=await(async({background:e,height:t,pixelRatio:n,svg:i,width:o})=>{const r=Math.ceil(o*n),s=Math.ceil(t*n);if((({height:e,pixelRatio:t,sourceHeight:n,sourceWidth:i,width:o})=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(i)||i<=0||!Number.isFinite(n)||n<=0)throw new Error("PNG dimensions and pixel ratio must be positive numbers.");if(o>aT||e>aT||o*e>lT)throw new Error(`PNG dimensions ${o}×${e} exceed the browser export limit.`)})({height:s,pixelRatio:n,sourceHeight:t,sourceWidth:o,width:r}),"undefined"==typeof document||"undefined"==typeof Image||"undefined"==typeof FileReader)throw new Error("PNG export requires a browser environment.");const a=await Eh(new Blob([i],{type:"image/svg+xml;charset=utf-8"}));if(!a)throw new Error("The exported SVG could not be encoded as a data URL.");const l=await(c=a,new Promise((e,t)=>{const n=new Image;n.onload=()=>e(n),n.onerror=()=>t(new Error("The exported SVG could not be decoded.")),n.src=c})),d=document.createElement("canvas");var c;d.width=r,d.height=s;const u=d.getContext("2d");if(!u)throw new Error("A 2D canvas context is unavailable.");return e&&(u.fillStyle=e,u.fillRect(0,0,r,s)),u.drawImage(l,0,0,r,s),{blob:await Oh(d),width:r,height:s}})({background:e,height:i.height,pixelRatio:t,svg:i.svg,width:i.width});return{status:Dh(i.status,`${n.width}×${n.height} px.`),blob:n.blob,width:n.width,height:n.height,exportedShapeIds:i.exportedShapeIds,skippedShapes:i.skippedShapes}}catch(o){console.warn("PNG rasterization failed",o);const e=o instanceof Error&&o.message.trim().length>0?o.message:"The SVG could not be rasterized.";return{status:{...i.status,tone:"error",title:"PNG export blocked",details:`Rasterization failed: ${e}`},blob:null,width:null,height:null,exportedShapeIds:i.exportedShapeIds,skippedShapes:i.skippedShapes}}}({assetInliners:e,background:o.background,editor:t,padding:o.padding,pixelRatio:o.pixelRatio,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:i});return{data:r.blob,result:r,status:r.status}}}))({assetInliners:e})),t.get(MP).add({token:dT,create:({editor:e,exportRegistry:t})=>zh({editor:e,exportRegistry:t})})}}}function _h({controller:e,activeContextMenu:t,grid:n,onActiveContextMenuChange:i,actionRegistry:o,canShowPropertiesDuringEditing:r,chromeRegistry:s,contextMenuRegistry:a,editor:l,executeAction:d,toolbarRegistry:c}){const u=or(l.currentPageIdSignal),h=or(l.currentPageShapeIdsSignal),p=or(l.sessionSignal).meta,g=or(l.selectedShapeIdsSignal),f=or(l.selectionMetadataSignal),m=(({controller:e,editor:t})=>{const n=or(t.historyStateSignal);return{canUndo:n.canUndo,canRedo:n.canRedo,undo(){e.undo()},redo(){e.redo()}}})({controller:e,editor:l}),S=(({controller:e,editor:t})=>{const n=or(t.pageStateSignal),i=e.getPages();return{pages:i,currentPage:i.find(e=>e.id===n.currentPageId)??null,currentPageId:n.currentPageId,canDeleteCurrentPage:n.canDeleteCurrentPage,createPage(){e.createPage()},deleteCurrentPage(){n.currentPage&&e.deletePage(n.currentPage.id)},renameCurrentPage(t){n.currentPage&&e.renamePage(n.currentPage.id,t)},selectPage(t){e.selectPage(t)}}})({controller:e,editor:l}),y=(({controller:e,editor:t})=>{const n=or(t.cameraZoomSignal);return{zoom:n,label:`${Math.round(100*n)}%`,zoomIn(){e.zoomIn()},zoomOut(){e.zoomOut()},resetZoom(){e.resetZoom()}}})({controller:e,editor:l}),b=function({editor:e,activeContextMenu:t,contextMenuRegistry:n}){const i=null!==t,o=Mh(e.selectionStateSignal,i),r=Mh(e.toolStateSignal,i);return Fx(()=>{if(!t||!o||!r)return{context:null,activeContextMenu:null,sections:[]};const i=(({editor:e,menu:t})=>{const n=e.toolStateSignal.get();return{...Th({editor:e,selectionState:e.selectionStateSignal.get(),toolState:n}),menu:t}})({editor:e,menu:t}),s=((e,t)=>"canvas"===e.type?"canvas":t.getSelectedShapeIds().length>0?"selection":"shape")(t.target,e);return{context:i,activeContextMenu:t,sections:n.getSections(s,i)}},[e,t,n,o,r])}({editor:l,activeContextMenu:t,contextMenuRegistry:a}),x=function({canShowPropertiesDuringEditing:e,editor:t,toolbarRegistry:n}){const i=Ex(e=>n.subscribeToState(t,e),[t,n]),o=Ex(()=>n.getStateRevision(),[n]);Dx(i,o,o);const r=Fx(()=>n.getChannels(),[n]),s=or(t.toolStateSignal),a=or(t.selectionMetadataSignal);(e=>{const t=Ex(t=>Jo("useToolbarSelectionShapeState",e.selectedShapesSignal,t,{fireImmediately:!1}),[e]),n=Fx(()=>{let t=[];return()=>{const n=e.getSelectedShapes().map(e=>[e.id,e.type,e.parentId,e.index,e.rotation,e.scaleX,e.scaleY,e.opacity,e.isHidden,e.isLocked,e.props,e.meta]);return((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o)return!1;for(let e=0;e<i.length;e+=1)if(!Object.is(i[e],o[e]))return!1}return!0})(t,n)||(t=n),t}},[e]);Dx(t,n,n)})(t);const l=or(t.shapeEditingStateSignal),d="select"===s.activeToolId,c=d?a.count:0,u=Th({editor:t,selectionState:a,toolState:s}),h=null!==l.session,p=!h||(e?.(u)??!1),g=new Map,f=e=>{const t=g.get(e.id);if(t)return t;const i=n.getGroups(e,u);return g.set(e.id,i),i},m=((e,t)=>{for(const n of e)for(const e of n.items)if("button"===e.kind&&e.actionId===Ak.tool.setActive.id&&e.value===t)return e.label;return t})(f(BP.toolSwitcher),s.activeToolId),S=(({commonShapeType:e,count:t,isMixedFrameAndPointHandleSelection:n,singleShapeType:i})=>{const o=i??e;if(!o)return n?"Mixed selection":`${t} selected`;const r=t>1?` (${t})`:"";return"geo"===o?`Shape${r}`:"text"===o?`Text${r}`:`${o.charAt(0).toUpperCase()}${o.slice(1)}${r}`})({commonShapeType:a.commonShapeType,count:c,isMixedFrameAndPointHandleSelection:a.isMixedFrameAndPointHandleSelection,singleShapeType:a.singleShapeType});return{context:u,channels:r,getGroups:f,isSurfaceActive:e=>"tool"===e||d&&a.count>0,activeToolId:s.activeToolId,activeToolLabel:m,isToolLocked:s.isToolLocked,isEditing:h,canShowPropertiesDuringEditing:p,selectionCount:c,hasMixedSelectionRotation:a.hasMixedSelectionRotation,selectionLabel:S}}({canShowPropertiesDuringEditing:r,editor:l,toolbarRegistry:c}),I=(({context:e,editor:t,registry:n})=>{const i=Ex(e=>n.subscribeToState(t,e),[t,n]),o=Ex(()=>n.getStateRevision(),[n]);return Fx(()=>{const t=new Map;return{context:e,channels:n.getChannels(),getSections(i){const o=t.get(i.id);if(o)return o;const r=n.getSections(i,e);return t.set(i.id,r),r}}},[e,n,Dx(i,o,o)])})({context:x.context,editor:l,registry:s}),v=e.apis.get(dT);if(!v)throw new Error("Canvas export API is unavailable.");const w=Fx(()=>{let t,n=[],i=[];return{getSnapshot(o){const r=o??l.getCurrentPageId(),s=((e,t)=>{const n=e.getShapesForPage(t),i=n.flatMap(t=>e.getBindingsForShape(t.id));return[...n,...i,...e.getAssets()]})(l,r);return t===r&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0})(n,s)||(t=r,n=s,i=e.getLayerTree(r)),i},subscribe:e=>Jo("CanvasKitLayerTree.records",l.store.recordsSignal,e,{fireImmediately:!1})}},[e,l]),P=Fx(()=>({getActionState({actionId:e,context:t}){const n=o.getAction(e);if(!n)return null;const i=gl(n,t);return{value:n.getValue?.(t),isEnabled:"enabled"===i,isVisible:"inapplicable"!==i}},runAction({actionId:e,context:t,value:n}){d({actionId:e,context:t,value:n})}}),[o,d]);return{controller:e,chromeSurfaces:I,contextMenu:{activeContextMenu:t,onActiveContextMenuChange:i,runAction({actionId:e,context:t,value:n}){d({actionId:e,context:t,value:n})},surface:b},currentPageId:u,currentPageShapeIds:h,sessionMeta:p,history:m,layerTree:w,pages:S,selection:f,selectedShapeIds:g,exportApi:v,toolbarRuntime:P,toolbarSurfaces:x,grid:n,zoom:y}}function Kh(){return"undefined"==typeof indexedDB?Promise.resolve(null):(hT||(hT=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(cT),e.objectStoreNames.contains("imageBlobs")||e.createObjectStore(uT)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),hT=null}),e(t)}),n.addEventListener("error",()=>{hT=null,t(n.error)})})),hT)}async function Yh(e,t){if(0===t.length)return[];const n=await Kh();return n?new Promise((i,o)=>{const r=n.transaction(e,"readonly"),s=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>i(a)),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),t.forEach((e,t)=>{const n=s.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>o(n.error))})}):null}async function Xh(e,t){if(0===t.length)return;const n=await Kh();n&&await new Promise((i,o)=>{const r=n.transaction(e,"readwrite"),s=r.objectStore(e);r.addEventListener("complete",()=>i()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error));for(const[e,n]of t)s.put(n,e)})}async function qh(e,t){const n=[];null!==e.documentSnapshot&&n.push([jh(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([Vh(t),e.sessionSnapshot]),0!==n.length&&await Xh(cT,n)}function jh(e){return e.storageNamespace?`${e.storageNamespace}.document`:"canvas-kit.document"}function Vh(e){return e.storageNamespace?`${e.storageNamespace}.session`:"canvas-kit.session"}function Gh(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function Zh({childIds:e,companionIds:t,depth:n,editor:i,index:o,pageId:r,shape:s}){return{id:s.id,parentId:s.parentId,pageId:r,type:s.type,companionIds:t,childIds:e,siblingIndex:o,depth:n,canReceiveChildren:i.canUseShapeParent(s.id),isHidden:s.isHidden,isLocked:s.isLocked,isEffectivelyHidden:i.isShapeHidden(s.id),isEffectivelyLocked:i.isShapeOrAncestorLocked(s.id)}}function Qh(e,t){const n=e.getShapesForPage(t),i=e.bindings.getShapeHierarchyRootIds(n.map(e=>e.id)),o=new Map;for(const r of n){const e=i.get(r.id)??r.id;if(e===r.id)continue;const t=o.get(e);t?t.push(r.id):o.set(e,[r.id])}return{companionIdsByRootId:o,rootIdByShapeId:i}}function Jh(e,t,n){return e.getChildShapes(n).filter(e=>t.rootIdByShapeId.get(e.id)===e.id)}function ep(e,t){let n=0,i=e.getShape(t);const o=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(o.has(t))break;o.add(t),i=e.getShape(t),n+=1}return n}function tp(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function np(e){const t=e.getDocumentMetadataRecord();return{id:t?.id??"document:main",meta:{...t?.meta??{}}}}function ip(e,t){return{id:t.id,type:t.type,parentId:t.parentId,pageId:e.getShapePageId(t.id),index:t.index,x:t.x,y:t.y,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,props:{...t.props},meta:{...t.meta}}}function op(e,t){const n=e.sessionSignal.get(),i=n.activeToolId;t.assertToolId(i);const o=i,r=e.getPages().map(t=>({pageId:t.id,selectedShapeIds:[...e.getSelectedShapeIds(t.id)],camera:{...e.getCamera(t.id)}}));return{currentPageId:n.currentPageId,activeToolId:o,isToolLocked:n.isToolLocked,meta:{...n.meta},pages:r}}function rp(e,t){const n=e.getActiveToolId();t.assertToolId(n);const i=n;return{productId:t.productId,document:np(e),pageId:e.getCurrentPageId(),activeToolId:i,selectedShapeIds:[...e.getSelectedShapeIds()],shapeCount:e.getCurrentPageShapeIds().length,session:op(e,t)}}function sp(e){return{...e,selectedShapeIds:[...e.selectedShapeIds],session:{...e.session,meta:{...e.session.meta},pages:e.session.pages.map(e=>({...e,selectedShapeIds:[...e.selectedShapeIds],camera:{...e.camera}}))},document:{...e.document,meta:{...e.document.meta}}}}function ap(e){return{...e,meta:{...e.meta}}}function lp(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 dp(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}function cp(e,t){e.includes(t)||e.push(t)}function up(e,t){return e.added.some(e=>e.scope===t)||e.updated.some(e=>e.before.scope===t||e.after.scope===t)||e.removed.some(e=>e.scope===t)}function hp(e){const t=globalThis.reportError;"function"!=typeof t?console.error(e):t(e)}function pp(e){return{added:e.diff.added.filter(e=>"shape"===e.typeName).map(e=>e.id),updated:e.diff.updated.filter(e=>"shape"===e.after.typeName).map(e=>e.after.id),removed:e.diff.removed.filter(e=>"shape"===e.typeName).map(e=>e.id)}}function gp(e){const{apis:t,editor:n}=e,i=e.executeCommand;return{apis:t,snapshot:()=>rp(n,e),subscribe(t,i){let o=sp(rp(n,e));if("committed"===i?.delivery)return n.operations.subscribe(n=>{const i=function(e,t){const n=e.snapshot.records,i=e.sessionSnapshot.records[0];if(!i)throw new Error("Editor commit is missing its session snapshot.");const o=i.activeToolId;t.assertToolId(o);const r=o,s=n.filter(e=>"page"===e.typeName).sort((e,t)=>e.index.localeCompare(t.index)),a=n.filter(e=>"shape"===e.typeName),l=new Map(a.map(e=>[e.id,e])),d=new Set(s.map(e=>e.id)),c=i.currentPageId,u=[...i.pageSelectedShapeIdsById[c]??[]],h=n.find(e=>"document"===e.typeName);return{productId:t.productId,document:{id:h?.id??"document:main",meta:{...h?.meta??{}}},pageId:c,activeToolId:r,selectedShapeIds:u,shapeCount:a.filter(e=>((e,t,n)=>{const i=new Set([e.id]);let o=e.parentId;for(;o.startsWith("shape:");){const e=o;if(i.has(e))return null;i.add(e);const n=t.get(e);if(!n)return null;o=n.parentId}return n.has(o)?o:null})(e,l,d)===c).length,session:{currentPageId:c,activeToolId:r,isToolLocked:i.isToolLocked,meta:{...i.meta},pages:s.map(e=>({pageId:e.id,selectedShapeIds:[...i.pageSelectedShapeIdsById[e.id]??[]],camera:{...i.pageCameraById[e.id]??wI}}))}}}(n,e),r=["document"];i.shapeCount!==o.shapeCount&&r.push("shapeCount"),o=sp(i);try{t({delivery:"committed",source:n.source,commit:{id:n.id,revision:n.revision,kind:n.kind,label:n.label},changes:r,affectedShapeIds:pp(n),snapshot:i})}catch(s){hp(s)}});const r=i?.scope??"all";return n.listen(i=>{const s=up(i.diff,"document"),a=up(i.diff,"session");if(!s&&!a||"document"===r&&!s||"session"===r&&!a)return;const l=a?rp(n,e):((e,t,n,{hasDocumentMetadataChange:i})=>{return{productId:n.productId,document:i?np(e):ap(t.document),pageId:t.pageId,activeToolId:t.activeToolId,selectedShapeIds:[...t.selectedShapeIds],shapeCount:e.getCurrentPageShapeIds().length,session:(o=t.session,{...o,meta:{...o.meta},pages:o.pages.map(e=>({...e,selectedShapeIds:[...e.selectedShapeIds],camera:{...e.camera}}))})};var o})(n,o,e,{hasDocumentMetadataChange:(d=i.diff,d.added.some(e=>"document"===e.typeName)||d.updated.some(e=>"document"===e.before.typeName||"document"===e.after.typeName)||d.removed.some(e=>"document"===e.typeName))});var d;let c=((e,t)=>{const n=[];return e.pageId!==t.pageId&&n.push("pageId"),e.activeToolId!==t.activeToolId&&n.push("activeToolId"),lp(e.selectedShapeIds,t.selectedShapeIds)||n.push("selectedShapeIds"),e.shapeCount!==t.shapeCount&&n.push("shapeCount"),function(e,t){if(e.currentPageId!==t.currentPageId||e.activeToolId!==t.activeToolId||e.isToolLocked!==t.isToolLocked||!((e,t)=>{const n=Object.keys(e),i=Object.keys(t);return n.length===i.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))})(e.meta,t.meta)||e.pages.length!==t.pages.length)return!1;for(let n=0;n<e.pages.length;n+=1){const i=e.pages[n],o=t.pages[n];if(i.pageId!==o.pageId||!lp(i.selectedShapeIds,o.selectedShapeIds)||!dp(i.camera,o.camera))return!1}return!0}(e.session,t.session)||n.push("session"),n})(o,l);if(s&&cp(c,"document"),a&&cp(c,"session"),c=((e,t)=>"all"===t?e:e.filter("document"===t?e=>"document"===e||"shapeCount"===e:e=>"document"!==e))(c,r),0===c.length)return void(o=sp(l));const u=o;o=sp(l);try{t({delivery:"realtime",source:i.source,changes:c,snapshot:l,previousSnapshot:u})}catch(h){hp(h)}})},clearHistory(){i(Lk)},canUndo:()=>n.historyStateSignal.get().canUndo,canRedo:()=>n.historyStateSignal.get().canRedo,undo:()=>i($k),redo:()=>i(Fk),getDocument:()=>np(n),updateDocumentMeta:e=>(i(Bk,e),np(n)),updateSessionMeta:t=>(i(Rk,t),op(n,e)),select(e){i(Gk,e)},selectAll(){i(Zk)},deleteSelection(){i(Qk)},deleteShapes(e){i(sC,e)},getAsset(e){const t=n.getAsset(e);return t?(e=>({id:e.id,type:e.type,props:{...e.props},meta:{...e.meta}}))(t):null},resolveAssetUrl:e=>n.resolveAssetUrl(e),getShape(e){const t=n.getShape(e);return t?ip(n,t):null},getShapes:e=>(e?e.map(e=>n.getShape(e)).filter(e=>!!e):n.getPages().flatMap(e=>n.getShapesForPage(e.id))).map(e=>ip(n,e)),updateShapes:e=>i(aC,e),updateShapeMeta:(e,t)=>i(lC,{id:e,patch:t}),duplicateSelection:()=>i(Jk),centerOnShape:e=>i(uC,e),getLayerTree:e=>(({editor:e,pageId:t=e.getCurrentPageId()})=>{const n=[],i=Qh(e,t),o=(r,s)=>{Jh(e,i,r).forEach((r,a)=>{const l=Jh(e,i,r.id).map(e=>e.id);n.push(Zh({childIds:l,companionIds:i.companionIdsByRootId.get(r.id)??[],depth:s,editor:e,index:a,pageId:t,shape:r})),o(r.id,s+1)})};return o(t,0),n})({editor:n,pageId:e??n.getCurrentPageId()}),getLayerNode:e=>(({editor:e,id:t})=>{const n=e.getShape(t),i=n?e.getShapePageId(n.id):null;if(!n||!i)return null;const o=Qh(e,i),r=o.rootIdByShapeId.get(n.id)??n.id,s=e.getShape(r);if(!s)return null;const a=Jh(e,o,s.parentId);return Zh({childIds:Jh(e,o,s.id).map(e=>e.id),companionIds:o.companionIdsByRootId.get(s.id)??[],depth:ep(e,s.id),editor:e,index:a.findIndex(e=>e.id===s.id),pageId:i,shape:s})})({editor:n,id:e}),setShapesHidden:(e,t)=>i(Uk,{ids:e,isHidden:t}),setShapesLocked:(e,t)=>i(Ok,{ids:e,isLocked:t}),groupShapes:e=>i(Dk,e),ungroupShapes:e=>i(zk,e),moveShapesInParentOrder:(e,t)=>i("backward"===t?Nk:Hk,e),moveShapesToParentOrderEdge:(e,t)=>i("back"===t?Wk:_k,e),moveShapesToLayerPlacement:(e,t)=>i(Kk,{ids:e,placement:t}),getLayerActionState:e=>({canGroup:n.canGroupShapes(e),canUngroup:n.canUngroupShapes(e),canMoveBackward:n.canMoveShapesInParentOrder(e,"backward"),canMoveForward:n.canMoveShapesInParentOrder(e,"forward")}),setTool(e){i(dC,e)},setCamera(e,t){i(hC,{camera:e,pageId:t})},zoomIn(){i(pC)},zoomOut(){i(gC)},resetZoom(){i(fC)},resetView(){i(mC)},getPages:()=>n.getPages().map(tp),createPage:e=>tp(i(Yk,e)),renamePage(e,t){i(Xk,{pageId:e,name:t})},updatePageMeta:(e,t)=>i(qk,{pageId:e,patch:t}),deletePage:e=>i(jk,e),selectPage(e){i(Vk,e)}}}function fp({assetResolverTokens:e,services:t}){return e.map(e=>t.get(e)).filter(e=>!!e)}function mp(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function Sp(e){if(!gT.has(e)){if("geo"===e)throw new Error(`Unknown canvas kit tool "${e}". "geo" is a shape type, not a tool id. Use one of the geo tool ids such as "rectangle", "ellipse", or "triangle". Available tool ids: ${fT}.`);throw new Error(`Unknown canvas kit tool "${e}". Available tool ids: ${fT}.`)}}function yp(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function bp(e,t,n){return Math.max(t,Math.min(n,e))}function xp(e){return e?640:480}function Ip(e,t){return e.x===t.x&&e.y===t.y&&e.pressure===t.pressure&&e.segment===t.segment}function vp(e){return new mI(e.x,e.y)}function wp(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 Pp(e){const t=[];for(const n of e)t.push(...n.points.map(wp));return t}function kp(e){if(void 0!==e&&Number.isFinite(e))return bp(e,.05,1)}function Cp(e,t){const n=[];for(let i=1;i<e.length-1;i+=1){if(t&&Tp(e,i))continue;const o=e[i],r=e[i-1],s=e[i+1];o&&r&&s&&n.push({index:i,score:Mp(o,r,s)})}return n.sort((e,t)=>e.score-t.score||e.index-t.index),n}function Tp(e,t){return"straight"===e[t]?.segment||"straight"===e[t+1]?.segment}function Mp(e,t,n){const i=((e,t,n)=>{const i=n.x-t.x,o=n.y-t.y,r=i*i+o*o;if(0===r){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}const s=bp(((e.x-t.x)*i+(e.y-t.y)*o)/r,0,1),a=e.x-(t.x+i*s),l=e.y-(t.y+o*s);return a*a+l*l})(e,t,n),o=((e,t,n)=>{if(void 0===e.pressure)return 0;return 8*Math.abs(e.pressure-((t.pressure??e.pressure)+(n.pressure??e.pressure))/2)})(e,t,n);return i+o*o}function Ep(e){if(0===e.length)return null;if(1===e.length){const t=e[0];return`M ${yp(t.x)} ${yp(t.y)}`}if(2===e.length){const t=e[0],n=e[1];return[`M ${yp(t.x)} ${yp(t.y)}`,`L ${yp(n.x)} ${yp(n.y)}`].join(" ")}const t=[],n=e[0];t.push(`M ${yp(n.x)} ${yp(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 ${yp(n.x)} ${yp(n.y)}`);continue}const o=e[i+1];if(!o||"straight"===o.segment){if(Ap(e,i)){const o=e[i-1];t.push(`Q ${yp(o.x)} ${yp(o.y)} ${yp(n.x)} ${yp(n.y)}`)}else t.push(`L ${yp(n.x)} ${yp(n.y)}`);continue}const r=mI.Med(vp(n),vp(o));t.push(`Q ${yp(n.x)} ${yp(n.y)} ${yp(r.x)} ${yp(r.y)}`)}return t.join(" ")}function Ap(e,t){return t>=2&&"straight"!==e[t-1]?.segment&&"straight"!==e[t-2]?.segment}function Bp(e){if(e.length<3)return(e=>{if(0===e.length)return null;const[t,...n]=e;return t?[`M ${yp(t.x)} ${yp(t.y)}`,...n.map(e=>`L ${yp(e.x)} ${yp(e.y)}`),"Z"].join(" "):null})(e);const t=e[0],n=e[e.length-1];if(!t||!n)return null;const i=mI.Med(n,t),o=[`M ${yp(i.x)} ${yp(i.y)}`];for(let r=0;r<e.length;r+=1){const t=e[r],n=e[(r+1)%e.length];if(!t||!n)continue;const i=mI.Med(t,n);o.push(`Q ${yp(t.x)} ${yp(t.y)} ${yp(i.x)} ${yp(i.y)}`)}return o.push("Z"),o.join(" ")}function Rp(e){return e.map(wp)}function Lp(e){return e.map($p)}function $p(e){return(e=>({points:e.points.map(wp)}))(e)}function Fp(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 Up(e,t,n){return e.map(e=>({points:Fp(e.points,t,n)}))}function Op(e,t){return e.map((e,n)=>({points:e.points.map((e,i)=>{const o=t(vp(e),n,i);return{x:o.x,y:o.y,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}})}))}function Dp(e,t,n){const i=0===t.w?1:t.w,o=0===t.h?1:t.h,r=0===n.w?1:n.w,s=0===n.h?1:n.h;return e.map(e=>({x:n.minX+(e.x-t.minX)/i*r,y:n.minY+(e.y-t.minY)/o*s,...void 0===e.pressure?null:{pressure:e.pressure},...void 0===e.segment?null:{segment:e.segment}}))}function zp(e,t,n){return e.map(e=>({points:Dp(e.points,t,n)}))}function Np(e){return{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}}function Hp(e,t){const n=Np(t);return Op(e,e=>Ii(e,n))}function Wp(e,t){const n=Np(t);return Op(e,e=>vi(e,n))}function _p(e,t){return Op(e,e=>Ci({axis:t.axis,bounds:t.selectionMirrorBounds,point:e}))}function Kp(e,t,n){return Math.max(t,Math.min(n,e))}function Yp(e,t,n){return e+(t-e)*n}function Xp(e,t,n){if(e.length<=1)return new mI(1,0);if(n&&e.length>=3){const n=e[t],i=e[(t+1)%e.length],o=n.sub(e[(t-1+e.length)%e.length]).normalize(),r=i.sub(n).normalize(),s=o.add(r);return s.len2()>1e-6?s.normalize():r.len2()>0?r:o.len2()>0?o:new mI(1,0)}const i=e[t],o=e[t+1]??i,r=i.sub(e[t-1]??i).normalize(),s=o.sub(i).normalize();if(0===t)return s.len2()>0?s:new mI(1,0);if(t===e.length-1)return r.len2()>0?r:new mI(1,0);const a=r.add(s);return a.len2()>1e-6?a.normalize():s.len2()>0?s:r.len2()>0?r:new mI(1,0)}function qp(e,t){return e.x*t.x+e.y*t.y}function jp(e,t,n,i,o={}){if(0===e.length)return[];const r=((e,t)=>{const n=Math.max(e+1,1.6);return{baseRadius:n,minRadius:Math.max(.6,.32*n),minRadiusScale:t?.5:.48,maxRadiusScale:t?1.22:1.24,startTaper:Math.max(1.8*e,2.5),endTaper:Math.max(2.3*e,3.5),simulatePressure:!t}})(t,n),s=e.map(vp),a=[0];let l=0;for(let u=1;u<s.length;u+=1)l+=s[u].dist(s[u-1]),a.push(l);let d=null;const c=e.map((e,n)=>{const c=a[n]??0,u=0===n?0:s[n].dist(s[n-1]),h=function(e,t,n,i,o,r,s,a){if(n.simulatePressure)return(({distanceFromPrevious:e,previousPressure:t,runningLength:n,totalLength:i,strokeWidth:o,isClosed:r})=>{const s=Kp(e/Math.max(1.5*o,1),0,1),a=Kp(1-s,mT,1),l=null===t?Yp(.5,a,.275):Yp(t,a,.275*Math.max(s,.36));if(r)return Kp(l,mT,1);const d=Kp(n/Math.max(1.8*o,1),0,1),c=Kp((i-n)/Math.max(2.6*o,1),0,1);return Kp(l*Yp(.72,1,Math.min(d,c)),mT,1)})({distanceFromPrevious:o,previousPressure:t,runningLength:r,totalLength:s,strokeWidth:i,isClosed:a});const l="number"==typeof e.pressure&&Number.isFinite(e.pressure)?Kp(e.pressure,.05,1):t??.55;return null===t?l:Yp(t,l,.68)}(e,d,r,t,u,c,l,i);d=h;const p=o.taperEnd??!0,g=i||s.length<=1?1:Math.min(o.taperStart??1?Kp(c/r.startTaper,0,1):1,p?Kp((l-c)/r.endTaper,0,1):1),f=Yp(r.minRadiusScale,r.maxRadiusScale,h),m=Math.max(r.minRadius,r.baseRadius*f*Yp(.7,1,g));return{point:s[n],direction:Xp(s,n,i),pressure:h,radius:m,runningLength:c}});return l<.5*r.baseRadius?c.map(e=>({...e,radius:Math.max(e.radius,.92*r.baseRadius)})):c}function Vp(e,t){const n=e[e.length-1];n&&n.dist2(t)<.04?e[e.length-1]=t:e.push(t)}function Gp(e,t,n){const i=e.dist(t);if(0===i)return[];const o=mI.Angle(e,t),r=[];for(let s=1;s<n;s+=1){const t=o-Math.PI*(s/n);r.push(new mI(e.x+Math.cos(t)*i,e.y+Math.sin(t)*i))}return r}function Zp(e,t,n,i={}){const o=e[e.length-1];(!o||!0===i.force||o.dist2(t)>n)&&Vp(e,t)}function Qp(e){return{...e}}function Jp(e,t,n){return e.map(e=>new mI(e.x+t,e.y+n))}function eg(e,t,n){return e.map(e=>Jp(e,t,n))}function tg({segments:e,outlineVertices:t,outlinePolygons:n,strokeWidth:i,sampling:o,isClosed:r}){const s=Pp(e),a=s.map(vp),l=a.length>0?SI.FromPoints(a):new SI(0,0,1,1),d=t.length>0?SI.FromPoints([...t]):l.expand(Math.max(i/2,1)),c=r&&s.length>=3?(e=>{if(e.length<3)return null;const t=Ep(e);return t?`${t} Z`:null})(s):null,u=void 0!==n?(e=>{const t=e.map(e=>Bp(e)).filter(e=>null!==e);return t.length>0?t.join(" "):null})(n):Bp(t);return{normalizedSegments:Lp(e),normalizedPoints:Rp(s),pointBounds:l,path:u,selectionPath:c??Ep(s),fillPath:c,localBounds:d,renderBounds:d.clone(),outlineVertices:t.map(e=>e.clone()),outlinePolygons:n?n.map(e=>e.map(e=>e.clone())):[t.map(e=>e.clone())],sampling:Qp(o)}}function ng(e,t,n,i){const o=(({strokeWidth:e,isPen:t})=>[e,t?"pen":"pointer"].join(":"))({strokeWidth:n,isPen:i}),r=ST.get(e),s=r?.get(o);if(s)return{normalizedSegment:$p(s.normalizedSegment),sampling:Qp(s.sampling)};const a=((e,t)=>{if(e.length<=1)return{points:e.map(wp),rawPointCount:e.length,sampledPointCount:e.length,maxPointCount:t.maxPointCount,reduced:!1,capped:!1};const n=[wp(e[0])],i=t.minPointDistance*t.minPointDistance;let o=vp(e[0]),r=kp(e[0].pressure);for(let l=1;l<e.length;l+=1){const s=e[l];if(!s)continue;const a=vp(s),d=kp(s.pressure),c=l===e.length-1,u="straight"===s.segment,h=c||u?a:mI.Lrp(o,a,t.positionBlend),p=u?d:void 0===d?void 0:void 0===r?d:r+(d-r)*t.pressureBlend;o=h,r=p;const g=void 0===p?{x:h.x,y:h.y,...void 0===s.segment?null:{segment:s.segment}}:{x:h.x,y:h.y,pressure:p,...void 0===s.segment?null:{segment:s.segment}},f=n[n.length-1];if(!f){n.push(g);continue}const m=g.x-f.x,S=g.y-f.y,y=Math.abs((g.pressure??0)-(f.pressure??0));if(m*m+S*S<i){if(u){if(Ip(f,g))continue;n.push(g);continue}(y>.08||c)&&(n[n.length-1]=g)}else n.push(g)}const s=n.length>t.maxPointCount,a=function(e,t){const n=Math.max(2,Math.floor(t));if(e.length<=n)return e.map(wp);const i=((e,t)=>{let n=Cp(e,!0);return n.length<t&&(n=Cp(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(wp)}(n,t.maxPointCount);return{points:a,rawPointCount:e.length,sampledPointCount:a.length,maxPointCount:t.maxPointCount,reduced:a.length<e.length,capped:s}})(e.points,t),l={normalizedSegment:{points:Rp(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},d=r??new Map;return d.set(o,{normalizedSegment:$p(l.normalizedSegment),sampling:Qp(l.sampling)}),r||ST.set(e,d),l}function ig(e,t,n=!1,i=!1){const o=((e,t)=>({minPointDistance:t?Math.max(.35,.18*e):Math.max(.55,.28*e),positionBlend:t?.68:.66,pressureBlend:t?.68:.45,maxPointCount:xp(t)}))(t,n),r=[],s=[],a=e.filter(e=>e.points.length>0);for(let h=0;h<a.length;h+=1){const e=ng(a[h],o,t,n);r.push($p(e.normalizedSegment)),s.push(Qp(e.sampling))}const l=function(e,t,n={}){if(0===e.length)return[];if(1===e.length)return((e,t)=>{const n=[];for(let i=0;i<16;i+=1){const o=2*Math.PI*i/16;n.push(new mI(e.x+Math.cos(o)*t,e.y+Math.sin(o)*t))}return n})(e[0].point,e[0].radius);const i=[],o=[];let r=.12;for(const d of e)r=Math.max(r,.38*d.radius);const s=r**2;let a=null;for(let d=0;d<e.length;d+=1){const t=e[d],n=t.direction,r=(e[d+1]??t).direction,l=qp(n,r);let c=0===d||d===e.length-1?n.per().normalize():mI.Lrp(r,n,l).per().normalize();c.len2()<1e-6&&(c=a??new mI(0,1)),a=c,Zp(i,t.point.add(c.mul(t.radius)),s,{force:d===e.length-1}),Zp(o,t.point.sub(c.mul(t.radius)),s,{force:d===e.length-1})}if(t&&e.length>=3){const e=[];for(const t of i)Vp(e,t);for(let t=o.length-1;t>=0;t-=1)Vp(e,o[t]);return e}const l=[];for(const d of i)Vp(l,d);if(n.capEnd??1){const t=e[e.length-1];for(const e of Gp(t.point,i[i.length-1],8))Vp(l,e)}for(let d=o.length-1;d>=0;d-=1)Vp(l,o[d]);if(n.capStart??1){const t=e[0];for(const e of Gp(t.point,o[0],8))Vp(l,e)}return l}(jp(Pp(r),t,n,i),i),d=(u=o.maxPointCount,{rawPointCount:(c=s).reduce((e,t)=>e+t.rawPointCount,0),sampledPointCount:c.reduce((e,t)=>e+t.sampledPointCount,0),sampledPointLimit:u,reduced:c.some(e=>e.reduced),capped:c.some(e=>e.capped)});var c,u;return tg({segments:r,outlineVertices:l,outlinePolygons:l.length>0?[l]:[],strokeWidth:t,sampling:d,isClosed:i})}function og(e){return e.segments}function rg(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 SI(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 sg(e){const t=e,n=yT.get(t);if(n)return n;const i=ig(og(e.props),e.props.strokeWidth,e.props.isPen??!1,e.props.isClosed);return yT.set(t,i),i}function ag(e,t,n=!1,i=!1){return((e,t,n=!1,i=!1)=>{const o=ig(e,t,n,i),r=o.pointBounds,s=ig(Op(o.normalizedSegments,e=>new mI(e.x-r.x,e.y-r.y)),t,n,i);return{x:r.x,y:r.y,segments:s.normalizedSegments,pointBounds:s.pointBounds,localBounds:s.localBounds,renderBounds:s.renderBounds,path:s.path,selectionPath:s.selectionPath,fillPath:s.fillPath,outlineVertices:s.outlineVertices,outlinePolygons:s.outlinePolygons,sampling:s.sampling}})(e,t,n,i)}function lg(e){const t=e,n=bT.get(t);if(n)return n;const i=((e,t,n,i,o)=>tg({segments:Up(e.normalizedSegments,n,i),outlineVertices:Jp(e.outlineVertices,n,i),outlinePolygons:eg(e.outlinePolygons,n,i),strokeWidth:t,sampling:e.sampling,isClosed:o}))(sg(e),e.props.strokeWidth,e.x,e.y,e.props.isClosed);return bT.set(t,i),i}function dg(e){const t=((e,t)=>new mI(e.x+t.localBounds.center.x,e.y+t.localBounds.center.y))(e,sg(e));return Op((e=>Up(og(e.props),e.x,e.y))(e),n=>((e,t,n)=>{if(0===e.rotation&&1===e.scaleX&&1===e.scaleY)return t;const i=t.sub(n),o=new mI(i.x*e.scaleX,i.y*e.scaleY);return n.add(o.rot(e.rotation))})(e,n,t))}function cg(e){return Lp(e)}function ug(e,t,n,i){return{x:e.x-t.x,y:e.y-t.y,...i&&n>0?{pressure:n}:null}}function hg(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 pg(e){const t=gg(e.segments),n=t[t.length-1];return n?n.points.map(hg):[]}function gg(e){return e.length>0?[...e]:[{points:[]}]}function fg(e){return{segments:cg(gg(e))}}function mg(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return e.dist(t);const r=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/o)),s=new mI(t.x+i.x*r,t.y+i.y*r);return e.dist(s)}function Sg(e,t,n,i){return((e,t,n,i)=>{const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1})(e,t,n,i)?0:Math.min(mg(e,n,i),mg(t,n,i),mg(n,e,t),mg(i,e,t))}function yg(e,t){let n=!1;for(let i=0,o=t.length-1;i<t.length;o=i,i+=1){const r=t[i],s=t[o];r&&s&&r.y>e.y!=s.y>e.y&&e.x<(s.x-r.x)*(e.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n}function bg(e,t){if(0===t.length)return Number.POSITIVE_INFINITY;let n=Number.POSITIVE_INFINITY;for(let i=0;i<t.length;i+=1){const o=t[i],r=t[(i+1)%t.length];o&&r&&(n=Math.min(n,mg(e,o,r)))}return n}function xg(e,t,n,i){if(0===n.length)return!1;if(yg(e,n)||yg(t,n))return!0;for(let o=0;o<n.length;o+=1){const r=n[o],s=n[(o+1)%n.length];if(r&&s&&Sg(e,t,r,s)<=i)return!0}return!1}function Ig(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function vg(e){if(!e||"object"!=typeof e)return null;const t=e,n=Ig(t.x,NaN),i=Ig(t.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(i))return null;const o=Ig(t.pressure,NaN);return t.x!==n||t.y!==i||void 0!==t.pressure&&t.pressure!==o||void 0!==t.segment&&"straight"!==t.segment?{x:n,y:i,...Number.isFinite(o)?{pressure:o}:null,..."straight"===t.segment?{segment:"straight"}:null}:e}function wg(e){if(!e||"object"!=typeof e)return null;const t=e,n=((e,t)=>{if(!Array.isArray(e))return t;let n=!1;const i=[];for(const o of e){const e=vg(o);e?(n=n||e!==o,i.push(e)):n=!0}return 0===i.length?t:n?i:e})(t.points,[]);return 0===n.length?null:n===t.points?e:{points:n}}function Pg(e,t){if(!Array.isArray(e))return t;let n=!1;const i=[];for(const o of e){const e=wg(o);e?(n=n||e!==o,i.push(e)):n=!0}return 0===i.length?t:n?i:e}function kg(e){return f(e)&&"draw"===e.type}function Cg(e){return{id:`draw.set-${e}`,getAvailability:e=>"draw"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const i of e){if("draw"!==i.type)continue;const e=i.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!D(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=Ag(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(kg).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));0!==o.length&&t.editor.commands.updateShapes(o,{source:"user"})}}}function Tg(e){return{id:`draw.default-${e}`,getAvailability:e=>"draw"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("draw")[e],run({context:t,value:n}){const i=Ag(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("draw",{[e]:i})}}}function Mg(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 Eg(e){return"closed"===e||"open"!==e&&null}function Ag(e,t){return"strokeWidth"===e?Bg(t):R(t)?$(t,"fill"===e?E("transparent"):M("stroke-slate")):void 0}function Bg(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function Rg(e){return void 0!==Bg(e)}function Lg({shape:e,stroke:t=e.props.stroke,strokeWidth:n=e.props.strokeWidth}){const{fillPath:i,renderBounds:o,path:r,selectionPath:s}=sg({props:{...e.props,strokeWidth:n}});if(!r&&!s)return null;const a=F(t);
30
- return Hx("svg",{width:"100%",height:"100%",viewBox:`${o.x} ${o.y} ${Math.max(o.w,1)} ${Math.max(o.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[i&&!O(e.props.fill)?Nx("path",{d:i,fill:F(e.props.fill),stroke:"none"}):null,e.props.isClosed&&s?Nx("path",{d:s,fill:"none",stroke:a,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}):r?Nx("path",{d:r,fill:a,stroke:"none"}):null]})}function $g({shape:e,strokeWidth:t}){const{path:n,renderBounds:i,selectionPath:o}=sg(e),r=o??n;return r?Nx("svg",{"data-ui":"draw-hover-outline",width:"100%",height:"100%",viewBox:`${i.x} ${i.y} ${Math.max(i.w,1)} ${Math.max(i.h,1)}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Nx("path",{d:r,fill:"none",stroke:qv,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function Fg(e){return e.runtime.require(TT)}function Ug(e){return 4/e.getCurrentCamera().z}function Og(e,t,n,i){const o=[new mI(t.minX,t.minY),new mI(t.maxX,t.minY),new mI(t.maxX,t.maxY),new mI(t.minX,t.maxY)].map(e=>n.applyToPoint(e));let r=0,s=Number.POSITIVE_INFINITY;for(let a=0;a<o.length;a+=1){const t=o[a],n=o[(a+1)%o.length].sub(t),i=e.sub(t),l=n.x*i.y-n.y*i.x;if(Math.abs(l)<=1e-8)return!1;const d=Math.sign(l);if(0===r)r=d;else if(d!==r)return!1;const c=n.len2(),u=0===c?0:Math.max(0,Math.min(1,(i.x*n.x+i.y*n.y)/c));s=Math.min(s,e.dist(t.add(n.mul(u))))}return s>i}function Dg(e,t){const n=new Set,i=Ug(e);for(const o of e.hitTestShapesAtPoint(t,{hitTest:"bindingTarget"})){const r=e.getShapeUtil(o);if(!r.canReceiveChildren(o))continue;const s=r.getChildClipLocalBounds(o);s&&Og(t,s,e.computeShapeLocalToPageTransform(o),i)&&n.add(o.id)}return n}function zg(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 Ng(e,t,n,i){const o=i.topMostOnly?n.slice(0,1):n;for(const r of o){const n=zg(e,r,t);n&&t.erasingShapeIds.add(n)}}function Hg(e,t,n){Ng(e,t,e.hitTestShapesAtPoint(n.pagePoint),{topMostOnly:n.accelKey})}function Wg(e,t,n){Ng(e,t,e.hitTestShapesByLineSegment(t.previousPagePoint,n.pagePoint,{margin:Ug(e)}),{topMostOnly:n.accelKey})}function _g(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function Kg(e,t){Fg(e).setPreview(Array.from(t.erasingShapeIds),t.trail)}function Yg(e){Fg(e).clear()}function Xg(e,t){const n=Array.from(t.erasingShapeIds);Yg(e),0!==n.length&&e.commands.deleteShapes(n,{source:"user"})}function qg(){return"undefined"==typeof performance?Date.now():performance.now()}function jg(e,t,n,i){const o=e.samples[e.samples.length-1];if(!o)return void e.samples.push({...t,time:i,velocity:0});const r=UT/n,s=Jg(o,t);if(s<r)return void(e.samples[e.samples.length-1]={...o,...t,time:i});const a=s*n/Math.max(WT,i-o.time);e.samples.push({...t,time:i,velocity:af(o.velocity,a,.68)})}function Vg(e,t){e.samples=Gg(e.samples,t)}function Gg(e,t){const n=e[e.length-1];if(!n)return[];const i=t-lf(_T+n.velocity*KT,_T,YT);if(n.time<i)return[];const o=e.findIndex(e=>e.time>=i);if(-1===o)return[];const r=e.slice(o),s=e[o-1],a=r[0];return s&&a.time>i?[(l=s,d=a,c=lf((i-s.time)/(a.time-s.time),0,1),{...sf(l,d,c),time:af(l.time,d.time,c),velocity:af(l.velocity,d.velocity,c)}),...r]:r;var l,d,c}function Zg(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?of(i,e[t]):of(t===e.length-1?e[t]:i,n))}function Qg(e,t,n){const i=[];for(let o=0;o<n;o++){const r=2*Math.PI*o/n;i.push({x:e.x+Math.cos(r)*t,y:e.y+Math.sin(r)*t})}return i}function Jg(e,t){return Math.sqrt(ef(e,t))}function ef(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function tf(e){return{x:-e.y,y:e.x}}function nf(e,t){return{x:e.x+t.x,y:e.y+t.y}}function of(e,t){return{x:e.x-t.x,y:e.y-t.y}}function rf(e,t){return{x:e.x*t,y:e.y*t}}function sf(e,t,n){return{x:af(e.x,t.x,n),y:af(e.y,t.y,n)}}function af(e,t,n){return e+(t-e)*n}function lf(e,t,n){return Math.max(t,Math.min(n,e))}function df(e,t){const n=e[e.length-1];!n||ef(n,t)>.04?e.push(t):e[e.length-1]=t}function cf(e){if(e.length<2)return null;if(2===e.length)return`M ${hf(e[0])} L ${hf(e[1])} Z`;const t=[`M ${hf(uf(e[0],e[1]))}`];for(let n=1;n<e.length;n++){const i=e[n],o=e[(n+1)%e.length];t.push(`Q ${hf(i)} ${hf(uf(i,o))}`)}return t.push("Z"),t.join(" ")}function uf(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function hf(e){return`${pf(e.x)},${pf(e.y)}`}function pf(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function gf(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.max(1,e):t}function ff({shape:e,isSelected:t=!1}){const{h:n,w:i}=e.props,o=F(E("#64748b"));
31
- return Nx("svg",{width:"100%",height:"100%",viewBox:`0 0 ${i} ${n}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:t?Nx("rect",{x:.5,y:.5,width:Math.max(i-1,0),height:Math.max(n-1,0),fill:"none",stroke:o,strokeDasharray:"4 4",strokeWidth:1,vectorEffect:"non-scaling-stroke"}):null})}function mf(e){return Math.min(1,Math.max(0,e))}function Sf(e,t,n){return Math.min(n,Math.max(t,e))}function yf(e){return!!e&&"object"==typeof e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function bf(e,t){const n=mf(e),i=mf(t);let o=Math.min(n,i),r=Math.max(n,i);return r-o<dM&&(o=Math.max(0,Math.min(.9999,(o+r)/2-5e-5)),r=o+dM),{min:o,max:r}}function xf(e){if(!e||"object"!=typeof e)return null;const t=e;if(!yf(t.topLeft)||!yf(t.bottomRight))return null;const n=bf(t.topLeft.x,t.bottomRight.x),i=bf(t.topLeft.y,t.bottomRight.y);return{topLeft:{x:n.min,y:i.min},bottomRight:{x:n.max,y:i.max}}}function If(e){const t=xf(e);if(!t)return null;const n=t.topLeft.x,i=t.topLeft.y,o=t.bottomRight.x,r=t.bottomRight.y;return{left:n,top:i,right:o,bottom:r,width:o-n,height:r-i}}function vf(e){return If(e)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function wf(e,t){return Math.abs(e.left-t.left)<=cM&&Math.abs(e.top-t.top)<=cM&&Math.abs(e.right-t.right)<=cM&&Math.abs(e.bottom-t.bottom)<=cM}function Pf(e){return(e=>Math.abs(e.left)<=cM&&Math.abs(e.top)<=cM&&Math.abs(1-e.right)<=cM&&Math.abs(1-e.bottom)<=cM)(e)?null:xf({topLeft:{x:e.left,y:e.top},bottomRight:{x:e.right,y:e.bottom}})}function kf({centerX:e,centerY:t,height:n,width:i}){const o=Sf(i,dM,1),r=Sf(n,dM,1),s=Sf(e-o/2,0,1-o),a=Sf(t-r/2,0,1-r);return{left:s,top:a,right:s+o,bottom:a+r,width:o,height:r}}function Cf(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function Tf({crop:e,shape:t}){const n=vf(e);return{w:t.props.w/n.width,h:t.props.h/n.height}}function Mf(e,t){return t===Ef(e.id)}function Ef(e){return`${hM}${e}`}function Af({localToPage:e,shape:t}){const n=t.props.w,i=t.props.h,o=(0+n)/2,r=(0+i)/2,s={top_left:new mI(0,0),top:new mI(o,0),top_right:new mI(n,0),right:new mI(n,r),bottom_right:new mI(n,i),bottom:new mI(o,i),bottom_left:new mI(0,i),left:new mI(0,r)};return fM.map(t=>{return{kind:"custom",type:uM,id:t,point:e.applyToPoint(s[t]),cursor:(n=t,gM[n])};var n})}function Bf({change:e,crop:t,shape:n}){const i=Tf({crop:t,shape:n}),o=t.bottomRight.x-t.topLeft.x,r=t.bottomRight.y-t.topLeft.y,s=Sf(t.topLeft.x-e.x/i.w,0,1-o),a=Sf(t.topLeft.y-e.y/i.h,0,1-r),l=xf({topLeft:{x:s,y:a},bottomRight:{x:s+o,y:a+r}});return l?{id:n.id,props:{crop:l}}:null}function Rf(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Lf(e,t){const n=mM.get(e);n&&(n.delete(t),0===n.size&&mM.delete(e))}function $f(e){return e.activeStroke?{...e,strokes:[...e.strokes,e.activeStroke],activeStroke:null,redoStrokes:[]}:e}function Ff(e){const t=EM.get(e);if(t)return t;const n=new MM(e);return EM.set(e,n),n}function Uf(e){return`${wM}${e}`}function Of(e,t){return t===Uf(e.id)}function Df(e){const t="number"==typeof e?.size&&Number.isFinite(e.size)?e.size:kM,n="number"==typeof e?.opacity&&Number.isFinite(e.opacity)?e.opacity:TM??.45;return{size:Math.min(128,Math.max(1,t)),color:"string"==typeof e?.color&&e.color.trim().length>0?e.color:CM,opacity:Math.min(1,Math.max(0,n))}}function zf({brush:e,editor:t,shape:n}){return Ff(t).start(n,e)}function Nf(e){Ff(e).cancel()}function Hf(e){Ff(e).complete()}function Wf(e,t){return Ff(e).updateBrush(t)}function _f(e){return Ff(e).getActiveSession()}async function Kf(e,t){return Ff(e).requestConfirm(t)}function Yf(e){return{x:e.x,y:e.y,...void 0===e.pressure?{}:{pressure:e.pressure}}}function Xf(e){return y(e)&&"image"===e.type}function qf(e){return f(e)&&"image"===e.type}function jf(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return null;const[t]=e.selection.selectedShapes;return qf(t)?t:null}function Vf(e){const t=jf(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!Mf(t,n.markId))}function Gf(e){const t=jf(e),n=e.editor.getShapeEditingSession();return!(!t||n?.shapeId!==t.id||!Of(t,n.markId))}function Zf(){return[{id:iM,getAvailability(e){const t=jf(e);return!t||Vf(e)?"inapplicable":t.isLocked?"disabled":"enabled"},getValue:e=>Vf(e),run({context:e}){const t=jf(e);if(!t||t.isLocked)return;const n=e.editor.getShapeEditingSession();n?.shapeId===t.id&&Mf(t,n.markId)?e.editor.completeEditing("user"):e.editor.startEditingShape({shapeId:t.id,markId:Ef(t.id),entryMode:"focusEnd"},"user")&&((e,t)=>{const n=mM.get(e)??new Map;mM.set(e,n),n.set(t.id,{...t,props:{...t.props,crop:t.props.crop?{topLeft:{...t.props.crop.topLeft},bottomRight:{...t.props.crop.bottomRight}}:null},meta:{...t.meta}})})(e.editor,t)}},{id:oM,getAvailability:e=>Vf(e)?"enabled":"inapplicable",run({context:e}){const t=jf(e);t&&e.editor.completeEditing("user")&&Lf(e.editor,t.id)}},{id:rM,getAvailability(e){if(!Vf(e))return"inapplicable";const t=jf(e);return t&&!t.isLocked?"enabled":"disabled"},run({context:e,value:t}){const n=jf(e);if(!n||n.isLocked||-1!==t&&1!==t)return;const i=(({direction:e,shape:t})=>{const n=vf(t.props.crop),i=Cf(n),o=Sf("in"===e?.8:1.25,Math.max(dM/n.width,dM/n.height),Math.min(1/n.width,1/n.height)),r=kf({centerX:i.x,centerY:i.y,width:n.width*o,height:n.height*o});return wf(n,r)?null:{id:t.id,props:{crop:Pf(r)}}})({direction:1===t?"in":"out",shape:n});i&&e.editor.commands.updateShapes([i],{source:"user"})}},{id:sM,getAvailability(e){if(!Vf(e))return"inapplicable";const t=jf(e);return t&&!t.isLocked?"enabled":"disabled"},getValue(e){const t=jf(e);return t?(e=>{const t=e.props.w/e.props.h;for(const n of pM)if(Math.abs(t-n.ratio)<=.01)return n.value;return null})(t):null},run({context:e,value:t}){const n=jf(e);if(!n||n.isLocked||"string"!=typeof t)return;const i=pM.find(e=>e.value===t);if(!i)return;const o=function({preset:e,shape:t}){const n=Cf(vf(t.props.crop)),i=Tf({crop:t.props.crop,shape:t}),o=pM.find(t=>t.value===e)?.ratio??null;if(!o)return null;const r=o*(i.h/i.w);let s=1,a=s/r;return a>1&&(a=1,s=a*r),(({nextRect:e,shape:t})=>{const n=vf(t.props.crop);if(wf(n,e))return null;const i=Tf({crop:t.props.crop,shape:t}),o=new mI((e.left-n.left)*i.w,(e.top-n.top)*i.h).rot(t.rotation);return{id:t.id,x:t.x+o.x,y:t.y+o.y,props:{w:e.width*i.w,h:e.height*i.h,crop:Pf(e)}}})({nextRect:kf({centerX:n.x,centerY:n.y,width:s,height:a}),shape:t})}({preset:i.value,shape:n});o&&e.editor.commands.updateShapes([o],{source:"user"})}},{id:aM,getAvailability(e){if(!Vf(e))return"inapplicable";const t=jf(e);return t&&!t.isLocked&&t.props.crop?"enabled":"disabled"},run({context:e}){const t=jf(e);if(!t||t.isLocked)return;const n=(({baselineShape:e,shape:t})=>{const n=e.x,i=e.y,o=e.props.w,r=e.props.h,s=xf(e.props.crop);return Math.abs(t.x-n)<=cM&&Math.abs(t.y-i)<=cM&&Math.abs(t.props.w-o)<=cM&&Math.abs(t.props.h-r)<=cM&&(null===t.props.crop&&null===s||null!==t.props.crop&&null!==s&&Math.abs(t.props.crop.topLeft.x-s.topLeft.x)<=cM&&Math.abs(t.props.crop.topLeft.y-s.topLeft.y)<=cM&&Math.abs(t.props.crop.bottomRight.x-s.bottomRight.x)<=cM&&Math.abs(t.props.crop.bottomRight.y-s.bottomRight.y)<=cM)?null:{id:t.id,x:n,y:i,props:{w:o,h:r,crop:s}}})({baselineShape:(i=e.editor,o=t.id,mM.get(i)?.get(o)??null??t),shape:t});var i,o;n&&e.editor.commands.updateShapes([n],{source:"user"})}}]}function Qf(e,t=0){return Math.max(0,"number"==typeof e&&Number.isFinite(e)?e:t)}function Jf({cornerRadius:e,h:t,w:n}){return Math.min(Qf(e),Math.max(0,n)/2,Math.max(0,t)/2)}function em({dataUiPrefix:e}){return{kind:"text-input",id:`${e}.corner-radius`,actionId:lM,label:"Corner radius",icon:"border-corner-pill",placeholder:"0",suffix:"Px",validate:tm,dataUi:`${e}-corner-radius-control`}}function tm(e){const t=e.trim();if(0===t.length)return!1;const n=Number(t);return Number.isFinite(n)&&n>=0}function nm(){return{createSession(e,{handle:t,shape:n,originPagePoint:i}){return qf(n)&&"custom"===t.kind&&"image.crop"===t.type&&(o=t.id,fM.some(e=>e===o))?function({handleId:e,shapeId:t,startPagePoint:n,startPageToLocal:i,startShape:o,startCrop:r}){return{shapeId:t,historyMark:"image.crop.handle",update({editor:s,pagePoint:a,source:l}){if(!qf(s.getShape(t)))return"stop";const d=(({handleId:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:o,currentPagePoint:r})=>{const s=xf(i)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=Tf({crop:s,shape:n});if(a.w<8||a.h<8)return null;const l=t.applyToPoint(o),d=t.applyToPoint(r).sub(l);if(0===d.x&&0===d.y)return null;const c={x:s.topLeft.x*a.w,y:s.topLeft.y*a.h,w:(s.bottomRight.x-s.topLeft.x)*a.w,h:(s.bottomRight.y-s.topLeft.y)*a.h},u=c.x+c.w,h=c.y+c.h;let p=c.x,g=c.y,f=c.w,m=c.h;(e=>"top_left"===e||"left"===e||"bottom_left"===e)(e)?(p=Sf(p+d.x,0,u-8),f=u-p):(e=>"top_right"===e||"right"===e||"bottom_right"===e)(e)&&(f=Sf(u+d.x,c.x+8,a.w)-p),(e=>"top_left"===e||"top"===e||"top_right"===e)(e)?(g=Sf(g+d.y,0,h-8),m=h-g):(e=>"bottom_left"===e||"bottom"===e||"bottom_right"===e)(e)&&(m=Sf(h+d.y,c.y+8,a.h)-g);const S=xf({topLeft:{x:p/a.w,y:g/a.h},bottomRight:{x:(p+f)/a.w,y:(g+m)/a.h}});if(!S)return null;const y=new mI(p-s.topLeft.x*a.w,g-s.topLeft.y*a.h).rot(n.rotation);return{id:n.id,x:n.x+y.x,y:n.y+y.y,props:{w:f,h:m,crop:S}}})({handleId:e,currentPagePoint:a,pageToLocal:i,shape:o,startCrop:r,startPagePoint:n});return d?(s.commands.updateShapes([d],{source:l}),"continue"):"continue"}}}({handleId:t.id,shapeId:n.id,startPagePoint:i,startPageToLocal:e.computeShapeLocalToPageTransform(n).invert(),startShape:n,startCrop:n.props.crop}):null;var o}}}function im(e){const[t]=e.getSelectedShapes();if(!qf(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Mf(t,n.markId)?t:null}function om(e,t,n){if(!n.hasDragged){if(n.startPagePoint.dist2(t.pagePoint)<9)return;n.operation=e.operations.begin({kind:"image.crop.translate",label:"shape.edit",source:"user",history:"record"}),n.hasDragged=!0}if(!qf(e.getShape(n.shapeId)))return;const i=(({currentPagePoint:e,pageToLocal:t,shape:n,startCrop:i,startPagePoint:o,shiftKey:r})=>{const s=xf(i);if(!s)return null;const a=t.applyToPoint(o);let l=t.applyToPoint(e).sub(a);return r&&(l=Math.abs(l.x)<Math.abs(l.y)?new mI(0,l.y):new mI(l.x,0)),0===l.x&&0===l.y?null:Bf({change:l,crop:s,shape:n})})({currentPagePoint:t.pagePoint,pageToLocal:n.startPageToLocal,shape:n.startShape,shiftKey:t.shiftKey,startCrop:n.startCrop,startPagePoint:n.startPagePoint});i&&e.commands.updateShapes([i],{source:"user"})}function rm(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function sm(e){return"key_down"===e.name&&"Enter"===e.key&&!e.altKey&&!e.accelKey}function am(e){return"key_down"===e.name&&"z"===e.key.toLowerCase()&&e.accelKey&&!e.altKey}function lm(e){const[t]=e.getSelectedShapes();if(!qf(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Of(t,n.markId)?t:null}function dm(e,t,n){const i=cm(e,t,n.pagePoint);return!!um(i,t)&&(((e,t)=>{Ff(e).appendPoint(t)})(e,{x:i.x,y:i.y,pressure:n.pressure}),!0)}function cm(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function um(e,t){return e.x>=0&&e.y>=0&&e.x<=t.props.w&&e.y<=t.props.h}function hm(e,t,n){if(!n.originCamera||!n.originScreenPoint)return;const i=t.screenPoint.sub(n.originScreenPoint),o=n.originCamera.z;e.setCamera({x:n.originCamera.x-i.x/o,y:n.originCamera.y-i.y/o},{source:"user"})}function pm({shape:e,session:t}){return t&&t.shapeId===e.id&&0!==t.strokes.length?Nx("svg",{"aria-hidden":"true","data-ui":"image-smudge-preview",viewBox:`0 0 ${e.props.w} ${e.props.h}`,style:{display:"block",height:e.props.h,inset:0,overflow:"hidden",pointerEvents:"none",position:"absolute",width:e.props.w},children:t.strokes.map(e=>Nx(gm,{stroke:e},e.id))}):null}function gm({stroke:e}){const t=e.points[0];if(!t)return null;const n=e.brush.color??"#ffff00",i=e.brush.opacity??.45,o=e.brush.size;if(1===e.points.length)return Nx("circle",{cx:t.x,cy:t.y,r:o/2,fill:n,opacity:i});const r=(e=>{const[t,...n]=e.points;return t?[`M ${mm(t.x)} ${mm(t.y)}`,...n.map(e=>`L ${mm(e.x)} ${mm(e.y)}`)].join(" "):null})(e);return r?Nx("path",{d:r,fill:"none",opacity:i,stroke:n,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o}):null}function fm(e,t){return`${e},${t}`}function mm(e){return Number.isFinite(e)?Number(e.toFixed(2)).toString():"0"}function Sm(e,t,n){const i=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n);return i.x>=0&&i.y>=0&&i.x<=t.props.w&&i.y<=t.props.h}function ym(e){return e.runtime.require($M)}function bm(e,t){const n=e.trail[e.trail.length-1];n&&n.dist2(t)<=1e-6||e.trail.push(t.clone())}function xm(e,t){ym(e).set(t.sessionId,t.trail)}function Im(){return"undefined"==typeof performance?Date.now():performance.now()}function vm(e,t,n,i){const o=e.samples[e.samples.length-1];if(!o)return void e.samples.push({...t,time:i,velocity:0});const r=YM/n,s=Tm(o,t);if(s<r)return void(e.samples[e.samples.length-1]={...o,...t,time:i});const a=s*n/Math.max(ZM,i-o.time);e.samples.push({...t,time:i,velocity:$m(o.velocity,a,.68)})}function wm(e,t){e.samples=Pm(e.samples,t)}function Pm(e,t){const n=e[e.length-1];if(!n)return[];const i=t-Fm(QM+n.velocity*JM,QM,eE);if(n.time<i)return[];const o=e.findIndex(e=>e.time>=i);if(-1===o)return[];const r=e.slice(o),s=e[o-1],a=r[0];return s&&a.time>i?[(l=s,d=a,c=Fm((i-s.time)/(a.time-s.time),0,1),{...Lm(l,d,c),time:$m(l.time,d.time,c),velocity:$m(l.velocity,d.velocity,c)}),...r]:r;var l,d,c}function km(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?Bm(i,e[t]):Bm(t===e.length-1?e[t]:i,n))}function Cm(e,t,n){const i=[];for(let o=0;o<n;o++){const r=2*Math.PI*o/n;i.push({x:e.x+Math.cos(r)*t,y:e.y+Math.sin(r)*t})}return i}function Tm(e,t){return Math.sqrt(Mm(e,t))}function Mm(e,t){const n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function Em(e){return{x:-e.y,y:e.x}}function Am(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Bm(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Rm(e,t){return{x:e.x*t,y:e.y*t}}function Lm(e,t,n){return{x:$m(e.x,t.x,n),y:$m(e.y,t.y,n)}}function $m(e,t,n){return e+(t-e)*n}function Fm(e,t,n){return Math.max(t,Math.min(n,e))}function Um(e,t){const n=e[e.length-1];!n||Mm(n,t)>.04?e.push(t):e[e.length-1]=t}function Om(e){if(e.length<2)return null;if(2===e.length)return`M ${zm(e[0])} L ${zm(e[1])} Z`;const t=[`M ${zm(Dm(e[0],e[1]))}`];for(let n=1;n<e.length;n++){const i=e[n],o=e[(n+1)%e.length];t.push(`Q ${zm(i)} ${zm(Dm(i,o))}`)}return t.push("Z"),t.join(" ")}function Dm(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function zm(e){return`${Nm(e.x)},${Nm(e.y)}`}function Nm(e){return Number.isInteger(e)?`${e}`:e.toFixed(3)}function Hm(e,t,n){return["control",n,e,t].map(encodeURIComponent).join("|")}function Wm(e,t){const n=t.split("|").map(e=>{try{return decodeURIComponent(e)}catch{return""}});return"path.node"===e&&3===n.length&&"node"===n[0]?{type:iE,subpathId:n[1],nodeId:n[2]}:"path.control"!==e||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:oE,handle:n[1],subpathId:n[2],nodeId:n[3]}}function _m(e,t){t?rE.set(e,Km(t)):rE.delete(e)}function Km(e){return{...e,pagePoint:e.pagePoint.clone()}}function Ym(e){return f(e)&&"path"===e.type}function Xm(e){return Number.isInteger(e)?`${e}`:`${Number(e.toFixed(2))}`}function qm(e){return new mI(e.x,e.y)}function jm(e,t){const n=qm(t);if(!((e,t)=>!!e.out||!!t.in)(e,t))return`L ${Xm(n.x)} ${Xm(n.y)}`;const i=(e=>{const t=qm(e);return e.out?t.add(new mI(e.out.dx,e.out.dy)):t})(e),o=(e=>{const t=qm(e);return e.in?t.add(new mI(e.in.dx,e.in.dy)):t})(t);return["C",Xm(i.x),Xm(i.y),Xm(o.x),Xm(o.y),Xm(n.x),Xm(n.y)].join(" ")}function Vm(e){const t=e.nodes[0];if(!t)return null;const n=[`M ${Xm(t.x)} ${Xm(t.y)}`];for(let i=1;i<e.nodes.length;i+=1){const t=e.nodes[i-1],o=e.nodes[i];t&&o&&n.push(jm(t,o))}if(e.closed&&e.nodes.length>1){const i=e.nodes[e.nodes.length-1];i&&n.push(jm(i,t)),n.push("Z")}return n.join(" ")}function Gm(e){const t=e.map(Vm).filter(e=>null!==e);return t.length>0?t.join(" "):null}function Zm(e){return Number.isFinite(e)}function Qm(e){return{dx:e.dx,dy:e.dy}}function Jm(e){return{id:e.id,x:e.x,y:e.y,kind:e.kind,...e.in?{in:Qm(e.in)}:null,...e.out?{out:Qm(e.out)}:null}}function eS(e){return{id:e.id,closed:e.closed,nodes:e.nodes.map(Jm)}}function tS(e){return e.map(eS)}function nS(e){return new mI(e.x,e.y)}function iS(e){const t=nS(e);return e.in?t.add(new mI(e.in.dx,e.in.dy)):t}function oS(e){const t=nS(e);return e.out?t.add(new mI(e.out.dx,e.out.dy)):t}function rS(e,t,n,i,o){const r=1-o,s=r*r*r,a=3*r*r*o,l=3*r*o*o,d=o*o*o;return new mI(e.x*s+t.x*a+n.x*l+i.x*d,e.y*s+t.y*a+n.y*l+i.y*d)}function sS(e,t,n){return new mI(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n)}function aS(e,t){return[nS(e),oS(e),iS(t),nS(t)]}function lS(e,t){return!!e.out||!!t.in}function dS(e,t,n){return lS(e,t)?rS(...aS(e,t),n):sS(nS(e),nS(t),n)}function cS(e,t,n){const i=nS(t),o=oS(t),r=iS(n),s=nS(n);if(t.out||n.in)for(let a=1;a<=18;a+=1)e.push(rS(i,o,r,s,a/18));else e.push(s)}function uS(e){const t=e.nodes[0];if(!t)return{id:e.id,closed:e.closed,points:[]};const n=[nS(t)];for(let i=1;i<e.nodes.length;i+=1){const t=e.nodes[i-1],o=e.nodes[i];t&&o&&cS(n,t,o)}if(e.closed&&e.nodes.length>1){const i=e.nodes[e.nodes.length-1];i&&cS(n,i,t)}return{id:e.id,closed:e.closed,points:n}}function hS(e){const t=e.props,n=uE.get(t);if(n)return n;const i=pS(e.props);return uE.set(t,i),i}function pS(e){const t=e.subpaths.map(uS),n=t.flatMap(e=>e.points),i=e.subpaths.flatMap(e=>e.nodes.flatMap(e=>[nS(e),...e.in?[iS(e)]:[],...e.out?[oS(e)]:[]])),o=i.length>0?SI.FromPoints(i):new SI(0,0,1,1),r=Math.max(e.strokeWidth/2,1),s=n.length>0?SI.FromPoints(n).expand(r):o.expand(r),a=new SI(s.x,s.y,Math.max(s.w,1),Math.max(s.h,1));return{path:Gm(e.subpaths),pointBounds:o,localBounds:s,renderBounds:a,outlineVertices:n.map(e=>e.clone()),flattenedSubpaths:t}}function gS(e,t){return e.map(e=>({...e,nodes:e.nodes.map(e=>((e,t)=>{const n=t(nS(e)),i=e.in?t(iS(e)):null,o=e.out?t(oS(e)):null;return{...e,x:n.x,y:n.y,...i?{in:{dx:i.x-n.x,dy:i.y-n.y}}:{in:null},...o?{out:{dx:o.x-n.x,dy:o.y-n.y}}:{out:null}}})(e,t))}))}function fS(e,t){const n=pS({...t,subpaths:tS(e)}).pointBounds,i=Number.isFinite(n.x)?n.x:0,o=Number.isFinite(n.y)?n.y:0,r=((e,t,n)=>gS(e,e=>new mI(e.x+t,e.y+n)))(e,-i,-o);return{x:i,y:o,subpaths:r,geometry:pS({...t,subpaths:r})}}function mS(e,t){return gS(e.props.subpaths,e=>t.applyToPoint(e))}function SS(e,t){return Gm(mS(e,t))}function yS(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return{distanceSquared:e.dist2(t),t:0};const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o)),a=t.add(i.mul(s));return{distanceSquared:e.dist2(a),t:s}}function bS(e,t,n){return yS(e,t,n).distanceSquared}function xS(e,t,n){const i=n*n;let o=null;for(const r of e){if(r.nodes.length<2)continue;const e=r.closed?r.nodes.length:r.nodes.length-1;for(let n=0;n<e;n+=1){const e=r.nodes[n],s=r.nodes[(n+1)%r.nodes.length];if(!e||!s)continue;const a=lS(e,s)?32:1;let l=nS(e);for(let n=1;n<=a;n+=1){const d=dS(e,s,n/a),c=yS(t,l,d),u=(n-1+c.t)/a;u>.02&&u<.98&&c.distanceSquared<=i&&(!o||c.distanceSquared<o.distanceSquared)&&(o={subpathId:r.id,startNodeId:e.id,endNodeId:s.id,t:u,point:dS(e,s,u),distanceSquared:c.distanceSquared}),l=d}}}return o?{subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,point:o.point.clone(),distance:Math.sqrt(o.distanceSquared)}:null}function IS(e,t){return e.find(e=>e.id===t)??null}function vS(e,t,n){return IS(e,t)?.nodes.find(e=>e.id===n)??null}function wS(e,t,n,i){return e.map(e=>e.id!==t?eS(e):{...e,nodes:e.nodes.map(e=>e.id===n?i(Jm(e)):Jm(e))})}function PS(e,t,n){const i=MS(t);return 0===i.size?tS(e):e.map(e=>{const t=i.get(e.id);return t?{...e,nodes:e.nodes.map(e=>t.has(e.id)?n(Jm(e)):Jm(e))}:eS(e)})}function kS(e,t,n){return e.map(e=>{if(e.id!==t)return eS(e);const i=e.nodes.findIndex(e=>e.id===n),o=e.nodes[i];if(!o)return eS(e);const r=i>0?e.nodes[i-1]:e.closed?e.nodes[e.nodes.length-1]:null,s=i<e.nodes.length-1?e.nodes[i+1]:e.closed?e.nodes[0]:null,a=nS(o),l=((e,t,n)=>{const i=t?nS(t):null,o=n?nS(n):null;if(i&&o){const t=o.sub(i);if(t.len()<=lE)return null;const n=t.normalize();return((e,t)=>{const n=Math.abs(e.x*t.y-e.y*t.x),i=e.len()*t.len();return i<=lE||n/i<=.001})(i.sub(e),o.sub(e))?n.rot(cE):n}const r=o?o.sub(e):i?e.sub(i):null;return!r||r.len()<=lE?null:r.normalize().rot(cE)})(a,r,s),d=e.nodes.map(Jm);return d[i]={...Jm(o),kind:"smooth",in:r&&l?NS(l.mul(-a.dist(nS(r))*dE)):null,out:s&&l?NS(l.mul(a.dist(nS(s))*dE)):null},{...e,nodes:d}})}function CS(e,t,n){return wS(e,t,n,e=>({...e,kind:"corner",in:null,out:null}))}function TS(e,t,n,i=t.at(-1)??null){if(!(e=>{const t=new Set;for(const n of e){if(!n.id||t.has(n.id))return!1;t.add(n.id);const e=new Set;for(const t of n.nodes){if(!t.id||e.has(t.id))return!1;e.add(t.id)}}return!0})(e))return null;const o=(e=>{const t=new Set,n=[];for(const i of e){const e=JSON.stringify([i.subpathId,i.nodeId]);t.has(e)||(t.add(e),n.push({subpathId:i.subpathId,nodeId:i.nodeId}))}return n})(t);if(o.length<2)return null;let r;switch(n){case"merge":r=((e,t)=>{const n=ES(t);if(null!==n)return((e,t,n)=>{const i=e.findIndex(e=>e.id===t),o=e[i];if(!o)return null;const r=((e,t)=>{const n=t.map(t=>e.nodes.findIndex(e=>e.id===t.nodeId));if(n.some(e=>e<0))return null;const i=Array.from(new Set(n)).sort((e,t)=>e-t);if(i.length!==t.length)return null;if(!e.closed)return i.every((e,t)=>0===t||e===i[t-1]+1)?i:null;if(i.length===e.nodes.length)return i;const o=i.flatMap((t,n)=>(t+1)%e.nodes.length===i[(n+1)%i.length]?[]:[n]);if(1!==o.length)return null;const r=(o[0]+1)%i.length;return[...i.slice(r),...i.slice(0,r)]})(o,n);if(!r||r.length<2)return null;const s=new Set(r),a=r.map(e=>o.nodes[e]),l=r[0],d=a[0],c=a[a.length-1],u=a.reduce((e,t)=>e.add(nS(t)),mI.Zero()).div(a.length),h={...Jm(d),x:u.x,y:u.y,kind:"corner",in:US(d.in,nS(d),u),out:US(c.out,nS(c),u)},p=o.nodes.flatMap((e,t)=>s.has(t)?t===l?[h]:[]:[Jm(e)]),g=o.closed&&p.length>=3;return o.closed&&!g&&FS(p),{subpaths:DS(e,i,[{...o,closed:g,nodes:p}]),selectedNodes:[{subpathId:t,nodeId:h.id}]}})(e,n,t);const i=AS(e,t);return i?((e,t)=>{const[n,i]=t,o=RS(n),r=LS(i),s=o[o.length-1],a=r[0],l=nS(s).add(nS(a)).div(2),d={...Jm(s),x:l.x,y:l.y,kind:"corner",in:US(s.in,nS(s),l),out:US(a.out,nS(a),l)},{nodes:c}=OS(r.slice(1),new Set([...o.slice(0,-1).map(e=>e.id),d.id]),"merged"),u={...n.subpath,closed:!1,nodes:[...o.slice(0,-1),d,...c]};return{subpaths:zS(e,t,u),selectedNodes:[{subpathId:u.id,nodeId:d.id}]}})(e,i):null})(e,o);break;case"join":r=((e,t)=>{if(2!==t.length)return null;const n=ES(t);if(null!==n)return((e,t,n)=>{const i=e.findIndex(e=>e.id===t),o=e[i];if(!o||o.closed||o.nodes.length<3)return null;const r=new Set([o.nodes[0].id,o.nodes[o.nodes.length-1].id]);if(2!==n.length||n.some(e=>!r.has(e.nodeId)))return null;const s=o.nodes.map(Jm);return s[0]={...s[0],kind:"corner",in:null},s[s.length-1]={...s[s.length-1],kind:"corner",out:null},{subpaths:DS(e,i,[{...o,closed:!0,nodes:s}]),selectedNodes:n.map(e=>({...e}))}})(e,n,t);const i=AS(e,t);return i?((e,t)=>{const[n,i]=t,o=RS(n),{nodes:r,nodeIdMap:s}=OS(LS(i),new Set(o.map(e=>e.id)),"joined"),a=r[0];o[o.length-1]={...o[o.length-1],kind:"corner",out:null},r[0]={...a,kind:"corner",in:null};const l={...n.subpath,closed:!1,nodes:[...o,...r]};return{subpaths:zS(e,t,l),selectedNodes:[{subpathId:l.id,nodeId:n.node.id},{subpathId:l.id,nodeId:s.get(i.node.id)??i.node.id}]}})(e,i):null})(e,o);break;case"separate":r=((e,t)=>{if(2!==t.length)return null;const n=ES(t);if(null===n)return null;const i=e.findIndex(e=>e.id===n),o=e[i];if(!o||o.nodes.length<2)return null;const r=((e,t)=>{const[n,i]=t.map(t=>e.nodes.findIndex(e=>e.id===t.nodeId));return void 0===n||void 0===i||n<0||i<0?-1:i===n+1?n:n===i+1?i:e.closed?n===e.nodes.length-1&&0===i?n:i===e.nodes.length-1&&0===n?i:-1:-1})(o,t);if(r<0)return null;if(o.closed){const n=[...o.nodes.slice(r+1).map(Jm),...o.nodes.slice(0,r+1).map(Jm)];return FS(n),{subpaths:DS(e,i,[{...o,closed:!1,nodes:n}]),selectedNodes:t.map(e=>({...e}))}}const s=o.nodes.slice(0,r+1).map(Jm),a=o.nodes.slice(r+1).map(Jm);FS(s),FS(a);const l=s.length>=2?{...o,closed:!1,nodes:s}:null,d=((e,t)=>{const n=new Set(e.map(e=>e.id));if(!n.has(t))return t;let i=2;for(;n.has(`${t}:${i}`);)i+=1;return`${t}:${i}`})(e,`${o.id}:split`),c=a.length>=2?{...o,id:d,closed:!1,nodes:a}:null,u=[l,c].filter(e=>null!==e),h=new Set(s.map(e=>e.id)),p=new Set(a.map(e=>e.id)),g=t.flatMap(e=>l&&h.has(e.nodeId)?[{subpathId:l.id,nodeId:e.nodeId}]:c&&p.has(e.nodeId)?[{subpathId:c.id,nodeId:e.nodeId}]:[]);return{subpaths:DS(e,i,u),selectedNodes:g}})(e,o)}if(!r)return null;const s=i?o.findIndex(e=>{return(t=e).subpathId===(n=i).subpathId&&t.nodeId===n.nodeId;var t,n}):-1;return{...r,primaryNode:r.selectedNodes[s]??r.selectedNodes.at(-1)??null}}function MS(e){const t=new Map;for(const n of e){const e=t.get(n.subpathId)??new Set;e.add(n.nodeId),t.set(n.subpathId,e)}return t}function ES(e){const t=e[0];return t&&e.every(e=>e.subpathId===t.subpathId)?t.subpathId:null}function AS(e,t){if(2!==t.length)return null;const n=BS(e,t[0]),i=BS(e,t[1]);return n&&i&&n.subpathIndex!==i.subpathIndex?[n,i]:null}function BS(e,t){const n=e.findIndex(e=>e.id===t.subpathId),i=e[n];if(!i||i.closed)return null;const o=i.nodes.findIndex(e=>e.id===t.nodeId),r=i.nodes[o];return!r||0!==o&&o!==i.nodes.length-1?null:{subpath:i,subpathIndex:n,endpoint:0===o?"start":"end",node:r}}function RS(e){return"end"===e.endpoint?e.subpath.nodes.map(Jm):$S(e.subpath.nodes)}function LS(e){return"start"===e.endpoint?e.subpath.nodes.map(Jm):$S(e.subpath.nodes)}function $S(e){return[...e].reverse().map(e=>({...Jm(e),in:e.out?Qm(e.out):null,out:e.in?Qm(e.in):null}))}function FS(e){0!==e.length&&(e[0]={...e[0],kind:"corner",in:null},e[e.length-1]={...e[e.length-1],kind:"corner",out:null})}function US(e,t,n){return e?NS(t.add(new mI(e.dx,e.dy)).sub(n)):null}function OS(e,t,n){const i=new Map;return{nodes:e.map(e=>{let o=e.id;if(t.has(o)){let i=1,r=`${o}:${n}`;for(;t.has(r);)i+=1,r=`${e.id}:${n}:${i}`;o=r}return t.add(o),i.set(e.id,o),{...Jm(e),id:o}}),nodeIdMap:i}}function DS(e,t,n){return e.flatMap((e,i)=>i===t?n.map(eS):[eS(e)])}function zS(e,t,n){const i=Math.min(t[0].subpathIndex,t[1].subpathIndex),o=new Set([t[0].subpathIndex,t[1].subpathIndex]);return e.flatMap((e,t)=>t===i?[n]:o.has(t)?[]:[eS(e)])}function NS(e){return e.len2()<=1e-12?null:{dx:e.x,dy:e.y}}function HS(e){const t=hE.get(e);return t?(e=>({shapeId:e.shapeId,nodes:e.nodes.map(e=>({...e})),primary:{...e.primary}}))(t):null}function WS(e){const t=hE.get(e);if(!t)return null;if(e.getShapeEditingSession()?.shapeId!==t.shapeId)return null;const n=e.getShape(t.shapeId);if(!Ym(n))return null;const i=t.nodes.flatMap(e=>{const t=IS(n.props.subpaths,e.subpathId)?.nodes.find(t=>t.id===e.nodeId);return t?[{ref:{...e},node:t}]:[]});if(0===i.length)return null;const o=i.some(({ref:e})=>VS(e,t.primary))?t.primary:i[i.length-1].ref;return{selection:{shapeId:n.id,nodes:i.map(({ref:e})=>({...e})),primary:{...o}},shape:n,entries:i}}function _S(e){const t=hE.get(e);hE.delete(e),e.getShapeEditingSession()?.shapeId===t?.shapeId&&jS(e,null)}function KS(e,t,n,i){const o={subpathId:n,nodeId:i};YS(e,t,[o],o)}function YS(e,t,n,i=n.at(-1)??null){const o=((e,t,n)=>{const i=(e=>{const t=new Set,n=[];for(const i of e){const e=JSON.stringify([i.subpathId,i.nodeId]);t.has(e)||(t.add(e),n.push({...i}))}return n})(t).filter(t=>null!==qS(e,t));if(0===i.length)return null;const o=(n&&i.find(e=>VS(e,n)))??i[i.length-1];return{shapeId:e.id,nodes:i,primary:{...o}}})(t,n,i);if(!o)return void _S(e);hE.set(e,o);const r=qS(t,o.primary);jS(e,r?e.computeShapeLocalToPageTransform(t).applyToPoint(nS(r)):null)}function XS(e,t,n){return e.nodes.some(e=>e.subpathId===t&&e.nodeId===n)}function qS(e,t){return IS(e.props.subpaths,t.subpathId)?.nodes.find(e=>e.id===t.nodeId)??null}function jS(e,t){const n=e.getShapeEditingSession();n&&e.updateSession({shapeEditingSession:{...n,caretPagePoint:t?{x:t.x,y:t.y}:void 0}},"system")}function VS(e,t){return e.subpathId===t.subpathId&&e.nodeId===t.nodeId}function GS(e){const t=e.meta[pE],n=e.meta[gE];return{subpathId:"string"==typeof t?t:null,previewNodeId:"string"==typeof n?n:null}}function ZS(e,t){const n=QS(e);return t.subpathId&&(n[pE]=t.subpathId),t.previewNodeId&&(n[gE]=t.previewNodeId),n}function QS(e){const t={...e};return delete t[pE],delete t[gE],t}function JS({node:e,showIn:t,size:n,strokeWidth:i}){const o=nS(e);
32
- return Hx(zx,{children:[t&&e.in?Nx(ey,{anchor:o,point:iS(e),size:n,strokeWidth:i,variant:"in"}):null,e.out?Nx(ey,{anchor:o,point:oS(e),size:n,strokeWidth:i,variant:"out"}):null]})}function ey({anchor:e,point:t,size:n,strokeWidth:i,variant:o}){const r=n/2;
33
- return Hx("g",{"data-ui":"path-draft-curve-handle","data-path-draft-curve-handle":o,children:[Nx("line",{"data-ui":"path-draft-control-line",x1:e.x,y1:e.y,x2:t.x,y2:t.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:i}),Nx("rect",{"data-ui":"path-draft-control-handle",x:t.x-r,y:t.y-r,width:n,height:n,fill:mE,stroke:fE,strokeWidth:i})]})}function ty({point:e,size:t,strokeWidth:n,variant:i}){const o=t/2;
34
- return Nx("rect",{"data-ui":"path-draft-control-point","data-path-draft-control-point":i,x:e.x-o,y:e.y-o,width:t,height:t,rx:2,ry:2,fill:"candidate"===i?"rgba(219, 234, 254, 0.98)":mE,stroke:fE,strokeWidth:n})}function ny({shape:e,shapeEditingSession:t=null,fill:n=e.props.fill,stroke:i=e.props.stroke,strokeWidth:o=e.props.strokeWidth}){const{renderBounds:r}=hS({props:{...e.props,strokeWidth:o}}),s=oy(e);if(!s)return null;const a=t?.shapeId===e.id;
35
- return Hx("svg",{width:"100%",height:"100%",viewBox:`${r.x} ${r.y} ${Math.max(r.w,1)} ${Math.max(r.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[O(n)?null:Nx("path",{d:s,fill:F(n),fillRule:e.props.fillRule,clipRule:e.props.fillRule,stroke:"none"}),
36
- Nx("path",{d:s,fill:"none",stroke:F(i),strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round"}),a?Nx(ry,{shape:e}):null]})}function iy({shape:e,strokeWidth:t}){const{renderBounds:n}=hS(e),i=oy(e);return i?Nx("svg",{"data-ui":"path-hover-outline",width:"100%",height:"100%",viewBox:`${n.x} ${n.y} ${Math.max(n.w,1)} ${Math.max(n.h,1)}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Nx("path",{d:i,fill:"none",stroke:qv,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function oy(e){const t=(e=>GS(e).previewNodeId)(e);return Gm(((e,t)=>t?e.map(e=>({...e,nodes:e.nodes.filter(e=>e.id!==t).map(e=>({...e}))})).filter(e=>e.nodes.length>0):e.map(e=>({...e,nodes:e.nodes.map(e=>({...e}))})))(e.props.subpaths,t))}function ry({shape:e}){
37
- return Nx(zx,{children:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=nS(t),i=[];if(t.in){const o=iS(t);i.push(Nx("line",{x1:n.x,y1:n.y,x2:o.x,y2:o.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${e.id}:${t.id}:in`))}if(t.out){const o=oS(t);i.push(Nx("line",{x1:n.x,y1:n.y,x2:o.x,y2:o.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${e.id}:${t.id}:out`))}return i}))})}function sy(e,t){const n=ir();or(n.shapeEditingSessionSignal);const i=HS(n),o=Wm(e,t);return!!i&&!!o&&XS(i,o.subpathId,o.nodeId)}function ay(e,t,n){const i=tS(t.props.subpaths),o="create"===n?GS(t):null;return{subpaths:i,draftMeta:o,selection:HS(e),signature:JSON.stringify({subpaths:i,draftMeta:o})}}function ly(e){return JSON.stringify((e=>({...e,meta:{...e.meta},props:{...e.props,fill:{...e.props.fill},stroke:{...e.props.stroke},subpaths:tS(e.props.subpaths)}}))(e))}function dy(e){const t=yE.get(e);if(t)return t;const n=new SE(e);return yE.set(e,n),n}function cy(e,t,n,i){return dy(e).start(t,n,i)}function uy(e,t){return dy(e).record(t)}function hy(e,t,n){return dy(e).end(t,n)}function py(e){return bE.get(e)??!1}function gy(e){return((e,t)=>{const n=e.getShapeEditingSession(),i=n?e.getShape(n.shapeId):null;return!(!n||!Ym(i))&&(py(e)===t||(bE.set(e,t),t||e.snaps.clearIndicators(),e.updateSession({shapeEditingSession:{...n}},"system")),t)})(e,!py(e))}function fy(e){bE.delete(e),e.snaps.clearIndicators()}function my(e){const t=e.getShapeEditingSession();if(!t)return null;const n=e.getShape(t.shapeId);return Ym(n)?n:null}function Sy(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function yy(e){_m(e,null)}function by(e){yy(e),_S(e)}function xy(e){return e.shiftKey}function Iy(e){return JSON.stringify([e.subpathId,e.nodeId])}function vy(e,t){const n=wE.get(e);if(!n)return;if(t.pointerId!==n.pointerId)return;const i=e.getShape(n.shapeId);if(!Ym(i))return void wy(e);if(!(n.isActive||(o=n.originScreenPoint,r=t.screenPoint,o.dist2(r)>=9)))return;var o,r;n.isActive=!0;const s=((e,t)=>{const n=Math.min(e.x,t.x),i=Math.min(e.y,t.y),o=Math.max(e.x,t.x),r=Math.max(e.y,t.y);return new SI(n,i,o-n,r-i)})(n.originPagePoint,t.pagePoint),a=((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t);return t.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const o=i.applyToPoint(nS(t));return n.containsPoint(o)?[{subpathId:e.id,nodeId:t.id}]:[]}))})(e,i,s),l=xy(t)?((e,t)=>{const n=new Map(e.map(e=>[Iy(e),{...e}]));for(const i of t){const e=Iy(i);n.has(e)?n.delete(e):n.set(e,{...i})}return Array.from(n.values())})(n.previousEntries,a):a;e.setBrushBox(s),YS(e,i,l,l.at(-1)??null)}function wy(e){const t=wE.get(e);if(!t)return;const n=e.getShape(t.shapeId);Ym(n)&&e.getShapeEditingSession()?.shapeId===t.shapeId?YS(e,n,t.previousEntries,t.previousPrimary):_S(e),wE.delete(e),e.setBrushBox(null)}function Py(e,t,n,i){const o=e.getShape(t);Ym(o)&&YS(e,o,n,i)}function ky(e){return e.filter(e=>e.nodes.length>=2)}function Cy(e,t){e.completeEditing("user"),e.getShape(t.id)&&e.operations.run({kind:"path.shape-delete",label:"shape.delete",source:"user",history:"record"},()=>{e.commands.deleteShapes([t.id],{source:"user"})})}function Ty(e,t,n){const i=ky(((e,t)=>{const n=MS(t);return 0===n.size?tS(e):e.map(e=>{const t=n.get(e.id);if(!t)return eS(e);const i=e.nodes.filter(e=>!t.has(e.id)).map(Jm),o=e.closed&&i.length>=3;return e.closed&&!o&&FS(i),{...e,closed:o,nodes:i}}).filter(e=>e.nodes.length>0)})(t.props.subpaths,n));0!==i.length?(e.commands.updateShapes([{id:t.id,props:{subpaths:i}}],{source:"user"}),_S(e),uy(e,t.id)):Cy(e,t)}function My(e,t){const n=WS(e);if(!n||n.shape.isLocked)return!1;const{shape:i,selection:o}=n,r=TS(i.props.subpaths,o.nodes,t,o.primary);if(!r)return!1;const s=ky(r.subpaths);return 0===s.length?(Cy(e,i),!0):(e.operations.run({kind:"path.node-operation",label:"shape.edit",source:"user",history:"record"},()=>{e.commands.updateShapes([{id:i.id,props:{subpaths:s}}],{source:"user"}),Py(e,i.id,r.selectedNodes,r.primaryNode)}),uy(e,i.id),!0)}function Ey(e,t){const n=my(e);if(n&&e.isActiveToolInInitialState()&&("Enter"===t.key||"Escape"===t.key)&&!t.altKey&&!t.ctrlKey&&!t.metaKey&&!t.accelKey)return e.completeEditing("user");if(!(n||"Enter"!==t.key||t.altKey||t.ctrlKey||t.metaKey||t.accelKey))return(e=>{if(e.getShapeEditingSession()||"select"!==e.getActiveToolId()||!e.isActiveToolInInitialState())return!1;const t=e.getSelectedShapeIds(),[n]=e.getSelectedShapes();return!(1!==t.length||!Ym(n)||!e.canEditShape(n)||(by(e),fy(e),!e.startEditingShape({shapeId:n.id,markId:xE,entryMode:"focusEnd"},"user")))})(e);if(n&&t.accelKey&&"z"===t.key.toLowerCase()&&!t.altKey)return t.shiftKey?e.redo():e.undo();if(t.accelKey&&("'"===t.key||"Quote"===t.code)&&n&&!n.isLocked)return gy(e),e.inputs.state.get().isPointing&&e.tools.dispatch(t),!0;if(t.accelKey&&"j"===t.key.toLowerCase()&&!t.altKey&&n&&!n.isLocked)return My(e,"merge");const i=(e=>{if(e.altKey||e.ctrlKey||e.metaKey||e.accelKey)return null;const t=e.shiftKey?10:1;switch(e.key){case"ArrowLeft":return new mI(-t,0);case"ArrowRight":return new mI(t,0);case"ArrowUp":return new mI(0,-t);case"ArrowDown":return new mI(0,t);default:return null}})(t);if(i)return function(e,t){const n=WS(e);if(!n||n.shape.isLocked)return!1;const{shape:i,selection:o}=n,r=((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t).invert(),o=i.applyToPoint(new mI(0,0));return i.applyToPoint(n).sub(o)})(e,i,t),s=PS(i.props.subpaths,o.nodes,e=>Ry(e,r));return e.operations.run({kind:"path.node-nudge",label:"shape.edit",source:"user",history:"record"},()=>{e.commands.updateShapes([{id:i.id,props:{subpaths:s}}],{source:"user"}),Py(e,i.id,o.nodes,o.primary)}),uy(e,i.id),!0}(e,i);if(t.altKey||t.ctrlKey||t.metaKey||t.accelKey)return!1;const o=WS(e);if(!o||o.shape.isLocked)return!1;const r=t.key.toLowerCase();return"backspace"===r||"delete"===r?(Ty(e,o.shape,o.selection.nodes),!0):"c"===r?((e,t,n)=>{const i=n.filter(e=>{const n=vS(t.props.subpaths,e.subpathId,e.nodeId);return!!n&&!n.in&&!n.out});if(0===i.length)return!1;const o=i.reduce((e,t)=>kS(e,t.subpathId,t.nodeId),t.props.subpaths);return e.commands.updateShapes([{id:t.id,props:{subpaths:o}}],{source:"user"}),Py(e,t.id,n,n.at(-1)??null),uy(e,t.id),!0})(e,o.shape,o.selection.nodes):"x"===r?(((e,t,n)=>{const i=n.reduce((e,t)=>CS(e,t.subpathId,t.nodeId),t.props.subpaths);e.commands.updateShapes([{id:t.id,props:{subpaths:i}}],{source:"user"}),Py(e,t.id,n,n.at(-1)??null),uy(e,t.id)})(e,o.shape,o.selection.nodes),!0):"j"===r?My(e,"join"):"k"===r&&My(e,"separate")}function Ay(e,t,n){const i=n?e.len():t?.len()??e.len();if(0===i)return null;const o=e.normalize().mul(-i);return{dx:o.x,dy:o.y}}function By(e,t){const n=t.sub(e),i=n.len();if(0===i)return t.clone();const o=Math.round(Math.atan2(n.y,n.x)/IE)*IE;return e.add(new mI(Math.cos(o)*i,Math.sin(o)*i))}function Ry(e,t){return{...e,x:e.x+t.x,y:e.y+t.y}}function Ly(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function $y(e){if(!e||"object"!=typeof e)return null;const t=e,n=Ly(t.dx,NaN),i=Ly(t.dy,NaN);return Number.isFinite(n)&&Number.isFinite(i)?t.dx===n&&t.dy===i?e:{dx:n,dy:i}:null}function Fy(e,t){if(!Array.isArray(e))return t;const n=new Set,i=e.map((e,t)=>function(e,t,n){if(!e||"object"!=typeof e)return null;const i=e,o=new Set,r=Array.isArray(i.nodes)?i.nodes.map((e,t)=>((e,t,n)=>{if(!e||"object"!=typeof e)return null;const i=e,o=Ly(i.x,NaN),r=Ly(i.y,NaN);return Number.isFinite(o)&&Number.isFinite(r)?{id:Uy("string"==typeof i.id&&i.id.length>0?i.id:`node:${t}`,n),x:o,y:r,kind:(s=i.kind,"string"==typeof s&&aE.includes(s)?i.kind:"corner"),in:$y(i.in),out:$y(i.out)}:null;var s})(e,t,o)).filter(e=>null!==e):[];return 0===r.length?null:{id:Uy("string"==typeof i.id&&i.id.length>0?i.id:`subpath:${t}`,n),closed:"boolean"==typeof i.closed&&i.closed,nodes:r}}(e,t,n)).filter(e=>null!==e);return i.length>0?i:t}function Uy(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}:${n}`);)n+=1;const i=`${e}:${n}`;return t.add(i),i}function Oy(e,t,n){const i=n.sub(t),o=i.len2();if(0===o)return e.dist2(t);const r=e.sub(t),s=Math.max(0,Math.min(1,(r.x*i.x+r.y*i.y)/o));return e.dist2(t.add(i.mul(s)))}function Dy(e,t,n,i){const o=t.sub(e),r=i.sub(n),s=o.x*r.y-o.y*r.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(e),l=(a.x*r.y-a.y*r.x)/s,d=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&d>=0&&d<=1?l:null}function zy(e,t){const n=t(nS(e)),i=e.in?t(iS(e)):null,o=e.out?t(oS(e)):null;return{...Jm(e),x:n.x,y:n.y,in:i?{dx:i.x-n.x,dy:i.y-n.y}:null,out:o?{dx:o.x-n.x,dy:o.y-n.y}:null}}function Ny(){return`node:${CE+=1}`}function Hy(e,t,n){return e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n)}function Wy(e,t,n,i){const o=(IS(t.props.subpaths,n)?.nodes.filter(e=>e.id!==i))?.at(-1);return o?e.computeShapeLocalToPageTransform(t).applyToPoint(new mI(o.x,o.y)):null}function _y(e,t){const n=t.sub(e),i=n.len();if(0===i)return t.clone();const o=Math.round(Math.atan2(n.y,n.x)/kE)*kE;return e.add(new mI(Math.cos(o)*i,Math.sin(o)*i))}function Ky(e,t){return t.previewNodeId?e.map(e=>e.id===t.subpathId?{...e,nodes:e.nodes.filter(e=>e.id!==t.previewNodeId)}:e):tS(e)}function Yy(e,t){return IS(e.props.subpaths,t.subpathId)?.nodes.filter(e=>e.id!==t.previewNodeId).length??0}function Xy(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6}function qy(e){return mS(e.shape,e.localToPage).filter(e=>e.closed&&e.nodes.length>=3).map(e=>(e=>{const t=[];for(const n of e){const e=[n.x,n.y],i=t[t.length-1];i&&Xy(i,e)||t.push(e)}return t.length>1&&Xy(t[0],t[t.length-1])&&t.pop(),t.length>=3?t:null})(uS(e).points)).filter(e=>null!==e).map(e=>[e])}function jy(e){const t=e.length>1&&Xy(e[0],e[e.length-1])?e.slice(0,-1):e;return t.length<3?null:{id:`boolean-subpath:${RE+=1}`,closed:!0,nodes:t.map(([e,t])=>({id:`boolean-node:${LE+=1}`,x:e,y:t,kind:"corner"}))}}function Vy(){return{id:"path.floating-node-snap",items:[{kind:"button",id:"path.floating-node.snap",actionId:UE,label:"Snap nodes",shortcut:"Mod+'",icon:"magnet",dataUi:"floating-path-node-snap-button"}]}}function Gy(){return{id:"path.floating-edit-session",items:[{kind:"button",id:"path.floating-edit.done",actionId:FE,label:"Done editing",icon:"check",dataUi:"floating-path-edit-done-button"}]}}function Zy({fillActionId:e,strokeActionId:t,strokeWidthActionId:n,dataUiPrefix:i}){return[{id:`${i}.style-fill`,items:[{kind:"color-input",id:`${i}.fill`,actionId:e,label:"Fill",fallback:"#f8fafc",presets:qE.map(e=>({...e,dataUi:`${i}-fill-${e.id}-button`})),dataUi:`${i}.fill`}]},{id:`${i}.style-stroke`,items:[{kind:"color-input",id:`${i}.stroke`,actionId:t,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:jE.map(e=>({...e,dataUi:`${i}-stroke-${e.id}-button`})),dataUi:`${i}.stroke`}]},{id:`${i}.style-stroke-width`,items:[{kind:"text-input",id:`${i}.stroke-width`,actionId:n,label:"Stroke width",placeholder:"3",suffix:"Px",validate:rb,dataUi:`${i}-stroke-width-control`}]}]}function Qy(e){return{id:`path.set-${e}`,getAvailability:e=>"path"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:t=>((e,t)=>{let n;for(const i of e){if(!Ym(i))continue;const e=i.props[t];if(void 0!==n){if("strokeWidth"===t?n!==e:!D(n,e))return null}else n=e}return n??null})(t.selection.selectedShapes,e),run({context:t,value:n}){const i=ib(e,n);if(void 0===i)return;const o=t.selection.selectedShapes.filter(Ym).filter(e=>!e.isLocked).map(t=>({id:t.id,props:{[e]:i}}));o.length>0&&t.editor.commands.updateShapes(o,{source:"user"})}}}function Jy(e){return{id:`path.default-${e}`,getAvailability:e=>"path"===e.tool.activeToolId?"enabled":"inapplicable",getValue:t=>t.editor.getDefaultShapeProps("path")[e],run({context:t,value:n}){const i=ib(e,n);void 0!==i&&t.editor.updateDefaultShapeProps("path",{[e]:i})}}}function eb(e,t){return{id:e,getAvailability(e){const n=WS(e.editor);return n?!n.shape.isLocked&&((e,t,n)=>null!==TS(e,t,n))(n.shape.props.subpaths,n.selection.nodes,t)?"enabled":"disabled":"inapplicable"},run({context:e}){const n=WS(e.editor);n&&!n.shape.isLocked&&My(e.editor,t)}}}function tb(e){return{id:`path.boolean.${e}`,getAvailability:e=>"path"!==e.selection.commonShapeType?"inapplicable":nb(e).length>=2?"enabled":"disabled",run({context:t}){const n=nb(t),i=n[0];if(!i||n.length<2)return;const o=((e,t,n)=>{const i=function(e,t){const n=t.map(qy).filter(e=>e.length>0);return 0===n.length?[]:((e,t)=>{const[n,...i]=t;if(!n)return[];if(0===i.length)return n;switch(e){case"union":return(0,BE.union)(n,...i);case"subtract":return(0,BE.difference)(n,...i);case"intersect":return(0,BE.intersection)(n,...i);case"xor":return(0,BE.xor)(n,...i)}})(e,n).flatMap(e=>e).map(jy).filter(e=>null!==e)}(e,t);return 0===i.length?null:fS(i,{...n,fillRule:"evenodd"})})(e,n.map(e=>({shape:e,localToPage:t.editor.computeShapeLocalToPageTransform(e)})),{fill:i.props.fill,stroke:i.props.stroke,strokeWidth:i.props.strokeWidth});o&&t.editor.operations.run({kind:`path.boolean.${e}`,label:"shape.boolean",source:"user",history:"record"},()=>{const[e]=t.editor.commands.createShapes([{type:"path",x:o.x,y:o.y,parentId:i.parentId,props:{...i.props,subpaths:o.subpaths,fillRule:"evenodd"}}],{source:"user"});t.editor.commands.deleteShapes(n.map(e=>e.id),{source:"user"}),e&&t.editor.commands.setSelectedShapeIds([e.id],{source:"system"})})}}}function nb(e){return e.selection.selectedShapes.filter(Ym).filter(e=>!e.isLocked).filter(e=>e.props.subpaths.some(e=>e.closed&&e.nodes.length>=3))}function ib(e,t){return"strokeWidth"===e?ob(t):R(t)?$(t,M("fill"===e?"fill-blue":"stroke-slate")):void 0}function ob(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function rb(e){return void 0!==ob(e)}async function sb(e){const t=await(async(e,t)=>(await Yh(e,[t]))?.[0]??null)(uT,e);return t instanceof Blob?t:null}async function ab(e){await(async(e,t)=>{const n=await Kh();n&&await new Promise((i,o)=>{const r=n.transaction(e,"readwrite"),s=r.objectStore(e);r.addEventListener("complete",()=>i()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),s.delete(t)})})(uT,e)}function lb(e,t){const n=e.getAsset(t);if(!Xf(n)||"local"!==n.props.source.kind)return null;const{storageKey:i}=n.props.source;return i.length>0?i:null}function db(e){const t=new Set;for(const n of e.getAssets())Xf(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&t.add(n.props.source.storageKey);return t}function cb(e){return new Promise((t,n)=>{const i=new Image;i.addEventListener("load",()=>{t({width:i.naturalWidth||i.width,height:i.naturalHeight||i.height})}),i.addEventListener("error",()=>{n(new Error("Could not decode image file."))}),i.src=e})}async function ub(e){const t=pb(e)?e:e.blob,n=(pb(e),e.name),i=pb(e)?e.type:e.mimeType||e.blob.type,o=URL.createObjectURL(t),r=await cb(o).finally(()=>{URL.revokeObjectURL(o)}),{storageKey:s}=await async function(e){const t="undefined"!=typeof crypto&&"randomUUID"in crypto?`${QE}${crypto.randomUUID()}`:`${QE}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for image storage.");return await Xh(uT,[[t,e]]),{storageKey:t}}(t);return{name:n||"Image",source:{kind:"local",storageKey:s,...!pb(e)&&e.originalUrl?{originalUrl:e.originalUrl}:{}},mimeType:i||"image/png",fileSize:t.size,width:r.width,height:r.height}}async function hb({name:e,url:t}){const n=await fetch(t);if(!n.ok)throw new Error(`Could not download image URL (${n.status}).`);const i=await n.blob();return ub({blob:i,name:e||gb(t)||"Image",mimeType:i.type||n.headers.get("content-type")||void 0,originalUrl:t})}function pb(e){return"undefined"!=typeof File&&e instanceof File}function gb(e){try{const t=new URL(e).pathname.split("/").filter(Boolean).at(-1);return t?decodeURIComponent(t):null}catch{return null}}function fb(e){for(const t of e)if(t.type.startsWith("image/"))return t;return null}function mb({filename:e,url:t}){const n=document.createElement("a");n.href=t,n.download=e,n.click()}async function Sb({blob:e,filename:t}){const n=URL.createObjectURL(e);try{mb({filename:t,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function yb(e,t){return e.commands.createAsset({type:"image",props:{w:t.width,h:t.height,name:t.name,source:t.source,mimeType:t.mimeType,fileSize:t.fileSize,isAnimated:"image/gif"===t.mimeType}},{source:"user"})}function bb(e,t){return e.getDocumentSnapshot().records.some(e=>"shape"===e.typeName&&e.props.assetId===t)}async function xb({editor:e,imageObjectUrls:t,pagePoint:n,size:i,flushSnapshot:o,source:r,strategy:s="auto"}){if("file"===r.type)return Ab(r.file)?vb({editor:e,imageObjectUrls:t,input:await ub(r.file),pagePoint:n,size:i,flushSnapshot:o}):null;if("blob"===r.type)return Ab(r.blob)?vb({editor:e,imageObjectUrls:t,input:await ub(r),pagePoint:n,size:i,flushSnapshot:o}):null;if("copy"===s)return vb({editor:e,imageObjectUrls:t,input:await hb(r),pagePoint:n,size:i,flushSnapshot:o});if("link"===s)return Ib({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:i,flushSnapshot:o,copyInBackground:!1});try{return await Ib({editor:e,imageObjectUrls:t,source:r,pagePoint:n,size:i,flushSnapshot:o,copyInBackground:!0})}catch{return vb({editor:e,imageObjectUrls:t,input:await hb(r),pagePoint:n,size:i,flushSnapshot:o})}}async function Ib({copyInBackground:e,editor:t,flushSnapshot:n,imageObjectUrls:i,pagePoint:o,size:r,source:s}){const a=await(async({name:e,url:t})=>{const n=await cb(t);return{name:e||gb(t)||"Image",source:{kind:"remote",url:t},mimeType:null,width:n.width,height:n.height}})(s),l={kind:"remote",url:s.url,...e?{copyState:{status:"pending-local-copy"}}:{}},d=await vb({editor:t,imageObjectUrls:i,input:{...a,source:l},pagePoint:o,size:r,flushSnapshot:n,altText:s.altText}),c=d?t.getShape(d):null,u=qf(c)?c.props.assetId:null;return e&&u&&wb({assetId:u,editor:t,flushSnapshot:n,imageObjectUrls:i,source:s}),d}async function vb({editor:e,imageObjectUrls:t,input:n,pagePoint:i,size:o,flushSnapshot:r,altText:s}){const a="local"===n.source.kind?n.source.storageKey:null;a&&await t.preload(a);let l=null;try{const t=yb(e,n);l=t.id;const a=o??(({height:e,width:t})=>{const n=Math.min(1,360/Math.max(t,e));return{w:Math.max(24,Math.round(t*n)),h:Math.max(24,Math.round(e*n))}})({width:t.props.w,height:t.props.h}),d=e.viewportPageBoundsSignal.get(),c=i??d?.center??e.screenToPage(new mI(360,240)),[u]=e.commands.createShapes([{type:"image",x:Math.round(c.x-a.w/2),y:Math.round(c.y-a.h/2),props:{...a,assetId:t.id,crop:null,altText:s??n.name}}],{source:"user"});return u?(e.commands.setSelectedShapeIds([u.id],{source:"user"}),await(r?.()),u.id):null}catch(d){throw l&&e.commands.deleteAsset(l,{source:"system"}),a&&(t.release(a),await ab(a)),d}}async function wb({assetId:e,editor:t,flushSnapshot:n,imageObjectUrls:i,source:o}){try{const r=await hb(o),s="local"===r.source.kind?r.source.storageKey:null;if(!s)return;await i.preload(s);const a=t.getAsset(e);if(!Xf(a)||"remote"!==a.props.source.kind||a.props.source.url!==o.url||!bb(t,e))return i.release(s),void(await ab(s));t.commands.updateAsset({id:e,props:{w:r.width,h:r.height,name:r.name,source:r.source,mimeType:r.mimeType,fileSize:r.fileSize,isAnimated:"image/gif"===r.mimeType}},{source:"system"}),await(n?.())}catch(r){await(async({assetId:e,editor:t,error:n,flushSnapshot:i,url:o})=>{const r=t.getAsset(e);Xf(r)&&"remote"===r.props.source.kind&&r.props.source.url===o&&(t.commands.updateAsset({id:e,props:{source:{kind:"remote",url:o,copyState:{status:"copy-failed",errorMessage:Bb(n)}}}},{source:"system"}),await(i?.()))})({assetId:e,editor:t,error:r,flushSnapshot:n,url:o.url})}}async function Pb({editor:e,file:t,imageObjectUrls:n,flushSnapshot:i}){if(!Ab(t))return;const[o]=e.getSelectedShapes();if(!qf(o)||o.isLocked)return;const r=await ub(t);await Cb({editor:e,flushSnapshot:i,imageObjectUrls:n,input:r,nextProps:{crop:null,altText:r.name},shape:o})}async function kb({editor:e,imageObjectUrls:t}){const[n]=e.getSelectedShapes();if(!qf(n)||!n.props.assetId)return;const i=e.getAsset(n.props.assetId);if(!Xf(i))return;const o="string"==typeof i.props.name&&i.props.name.length>0?i.props.name:"land-image";if("remote"===i.props.source.kind)return void(await(async({filename:e,url:t})=>{try{const n=await fetch(t);if(!n.ok)throw new Error(`Could not download image URL (${n.status}).`);await Sb({blob:await n.blob(),filename:e})}catch(n){console.warn("Could not download remote image; opening URL instead.",n),(e=>{const t=document.createElement("a");t.href=e,t.rel="noreferrer",t.target="_blank",t.click()})(t)}})({filename:o,url:i.props.source.url}));const r=i.props.source.storageKey;if(!r)return;const s=await sb(r);if(s)return void(await Sb({blob:s,filename:o}));const a=t.resolve(r);a&&mb({filename:o,url:a})}async function Cb({canCommit:e,editor:t,flushSnapshot:n,imageObjectUrls:i,input:o,nextProps:r,shape:s}){const a=s.props.assetId,l="local"===o.source.kind?o.source.storageKey:null;try{l&&await i.preload(l)}catch(p){throw await Mb({imageObjectUrls:i,storageKey:l}),p}const d=t.getShape(s.id);if(!qf(d)||d.isLocked||d.props.assetId!==a||e&&!e())return await Mb({imageObjectUrls:i,storageKey:l}),null;const c=`image.asset.replace:${s.id}:${JE++}`,u=t.operations.begin({kind:c,label:"image.asset.replace",source:"user",history:"record"});let h;try{const e=yb(t,o);t.commands.updateShapes([{id:s.id,props:{assetId:e.id,...r}}],{source:"user"}),a&&!bb(t,a)&&t.commands.deleteAsset(a,{source:"user"}),u.commit(),h={assetId:e.id,storageKey:l}}catch(p){throw u.isActive&&u.cancel(),await Mb({imageObjectUrls:i,storageKey:l}),p}return await Tb({flushSnapshot:n,operation:"image replacement"}),h}async function Tb({flushSnapshot:e,operation:t}){if(e)try{await e()}catch(n){console.warn(`Could not persist ${t}; the local change remains available.`,n)}}async function Mb({imageObjectUrls:e,storageKey:t}){t&&(e.release(t),await ab(t))}async function Eb(e){try{const t=await fetch(e);if(!t.ok)return null;const n=await t.blob();return Ab(n)?n:null}catch{return null}}function Ab(e){return!e.type||e.type.startsWith("image/")}function Bb(e){return e instanceof Error?e.message:String(e)}function Rb(e){const t=globalThis.reportError;"function"!=typeof t?console.error(e):t(e)}function Lb({flushSnapshot:e}={}){return{token:tA,create(){const t=function(){const e=new Map,t=new Map;let n=0,i=!1;const o=async(o,r={})=>{if(r.signal?.throwIfAborted(),i)return null;const s=e.get(o);if(s)return s;const a=t.get(o);if(a)return a;const l=n,d=sb(o).then(t=>{if(r.signal?.throwIfAborted(),!t||i||l!==n)return null;const s=URL.createObjectURL(t);return e.set(o,s),s}).finally(()=>{t.delete(o)});return t.set(o,d),d};return{async preloadForEditor(e,t={}){t.signal?.throwIfAborted(),await Promise.all(Array.from(db(e)).map(e=>o(e,t)))},preload:o,resolve:t=>e.get(t)??null,resolveAssetUrl(t,n){const i=((e,t)=>{const n=e.getAsset(t);return Xf(n)&&"remote"===n.props.source.kind&&n.props.source.url.length>0?n.props.source.url:null})(t,n);if(i)return i;const o=lb(t,n);return o?e.get(o)??null:null},release(n){const i=e.get(n);i&&(URL.revokeObjectURL(i),e.delete(n)),t.delete(n)},releaseAll(){i=!0,n+=1;for(const t of e.values())URL.revokeObjectURL(t);e.clear(),t.clear()}}}(),n=new Set,i=(i,o)=>{if(n.has(o))return;const r=i.getAsset(o);Xf(r)&&"remote"===r.props.source.kind&&"pending-local-copy"===r.props.source.copyState?.status&&(n.add(o),wb({assetId:o,editor:i,flushSnapshot:e,imageObjectUrls:t,source:{type:"url",url:r.props.source.url,name:r.props.name}}).finally(()=>{n.delete(o)}))};return{objectUrls:t,async cleanupAfterRestore(e,{signal:n}){n.throwIfAborted(),await(async({editor:e,objectUrls:t})=>{const n=db(e),i=await async function(){return(await(async e=>{const t=await Kh();return t?new Promise((n,i)=>{const o=t.transaction(e,"readonly"),r=o.objectStore(e).getAllKeys();o.addEventListener("abort",()=>i(o.error)),o.addEventListener("error",()=>i(o.error)),r.addEventListener("success",()=>{n([...r.result])}),r.addEventListener("error",()=>i(r.error))}):null})("imageBlobs"))?.map(String)??[]}(),o=[];for(const r of i)n.has(r)||(t?.release(r),await ab(r),o.push(r));return o})({editor:e,objectUrls:t}),n.throwIfAborted(),(e=>{for(const t of e.getAssets())Xf(t)&&i(e,t.id)})(e)},preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>(i(e,n),t.resolveAssetUrl(e,n))}},dispose(e){e.objectUrls.releaseAll()}}}function $b(e,t,n,i){if(_f(e)!==t)return!1;const o=e.getShape(t.shapeId);return qf(o)&&!o.isLocked&&o.props.assetId===n&&((e,t)=>{if(e.props.w!==t.props.w||e.props.h!==t.props.h)return!1;const n=e.props.crop,i=t.props.crop;return n&&i?n.topLeft.x===i.topLeft.x&&n.topLeft.y===i.topLeft.y&&n.bottomRight.x===i.bottomRight.x&&n.bottomRight.y===i.bottomRight.y:n===i})(o,i)}function Fb(e,t){if("undefined"!=typeof OffscreenCanvas){const n=new OffscreenCanvas(e,t),i=n.getContext("2d");if(!i)throw new Error("Could not create image smudge canvas context.");return{context:i,toBlob:e=>n.convertToBlob({type:e})}}const n=document.createElement("canvas");n.width=e,n.height=t;const i=n.getContext("2d");if(!i)throw new Error("Could not create image smudge canvas context.");return{context:i,toBlob:e=>new Promise((t,i)=>{n.toBlob(e=>{e?t(e):i(new Error("Could not encode image smudge canvas."))},e)})}}function Ub({context:e,crop:t,imageHeight:n,imageWidth:i,mask:o,shape:r,strokes:s}){if(0===s.length)return;const a=vf(t),l={x:a.left*i,y:a.top*n,w:a.width*i,h:a.height*n},d=l.w/r.props.w,c=l.h/r.props.h,u=(Math.abs(d)+Math.abs(c))/2;e.save(),e.beginPath(),e.rect(l.x,l.y,l.w,l.h),e.clip(),e.lineCap="round",e.lineJoin="round";for(const h of s){const t=h.points[0];if(!t)continue;const n=Db(h.brush.opacity),i=Math.max(1,h.brush.size*u),r=h.brush.color??"#ffff00";e.globalAlpha=n,e.strokeStyle=o?"#ffffff":r,e.fillStyle=o?"#ffffff":r,e.lineWidth=i;const s=Ob({cropPixelRect:l,point:t,scaleX:d,scaleY:c});if(1!==h.points.length){e.beginPath(),e.moveTo(s.x,s.y);for(const t of h.points.slice(1)){const n=Ob({cropPixelRect:l,point:t,scaleX:d,scaleY:c});e.lineTo(n.x,n.y)}e.stroke()}else e.beginPath(),e.arc(s.x,s.y,i/2,0,2*Math.PI),e.fill()}e.restore()}function Ob({cropPixelRect:e,point:t,scaleX:n,scaleY:i}){return{x:e.x+t.x*n,y:e.y+t.y*i}}function Db(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):.45}function zb(e){const t=e.trim();if(!t)return"Image smudged.png";const n=t.lastIndexOf(".");return n<=0?`${t} smudged.png`:`${t.slice(0,n)} smudged.png`}function Nb({editor:e,flushSnapshot:t,services:n}){const i=n.get(tA);if(!i)return null;const o={start(t){const n=t?.shapeId?e.getShape(t.shapeId):e.getSelectedShapes()[0];return!(!qf(n)||n.isLocked||!n.props.assetId)&&zf({brush:t?.brush,editor:e,shape:n})},setBrush:t=>Wf(e,t),cancel(){Nf(e)},confirm:n=>async function({editor:e,imageObjectUrls:t,flushSnapshot:n,replace:i=!0}){const o=_f(e);if(!o)return null;const r=(e=>e.map(e=>({id:e.id,brush:{...e.brush},points:e.points.map(Yf)})))(o.strokes);if(0===r.length)return Hf(e),null;if(nA.has(o))return null;nA.add(o);try{return await(async({editor:e,imageObjectUrls:t,flushSnapshot:n,replace:i,session:o,strokes:r})=>{const s=e.getShape(o.shapeId);if(!qf(s)||s.isLocked||!s.props.assetId)return null;const a=e.getAsset(s.props.assetId);if(!Xf(a))return null;const l=s.props.assetId,d=await(async({asset:e,imageObjectUrls:t})=>{if("remote"===e.props.source.kind)return Eb(e.props.source.url);const n=e.props.source.storageKey,i=await sb(n);if(i)return i;const o=t.resolve(n);return o?Eb(o):null})({asset:a,imageObjectUrls:t});if(!d)return null;if(!$b(e,o,l,s)||e.getAsset(l)!==a)return null;const{imageBlob:c,maskBlob:u,height:h,width:p}=await(async({crop:e,shape:t,sourceBlob:n,strokes:i})=>{const o=await(async e=>{if("function"==typeof createImageBitmap){const t=await createImageBitmap(e);return{source:t,width:t.width,height:t.height,dispose(){t.close()}}}const t=URL.createObjectURL(e),n=new Image;return n.decoding="async",n.src=t,"function"==typeof n.decode?await n.decode():await new Promise((e,t)=>{n.onload=()=>e(),n.onerror=()=>t(new Error("Could not decode image."))}),{source:n,width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,dispose(){URL.revokeObjectURL(t)}}})(n);try{const n=o.width,r=o.height,s=Fb(n,r);s.context.drawImage(o.source,0,0,n,r),Ub({context:s.context,crop:e,imageHeight:r,imageWidth:n,mask:!1,shape:t,strokes:i});const a=Fb(n,r);return Ub({context:a.context,crop:e,imageHeight:r,imageWidth:n,mask:!0,shape:t,strokes:i}),{imageBlob:await s.toBlob("image/png"),maskBlob:await a.toBlob("image/png"),width:n,height:r}}finally{o.dispose()}})({crop:s.props.crop,shape:s,sourceBlob:d,strokes:r});if(!$b(e,o,l,s)||e.getAsset(l)!==a)return null;const g={shapeId:s.id,sourceAssetId:l,imageBlob:c,maskBlob:u,width:p,height:h,crop:s.props.crop?{topLeft:{...s.props.crop.topLeft},bottomRight:{...s.props.crop.bottomRight}}:null,strokes:r};if(i){const i=await(async({blob:e,canCommit:t,editor:n,flushSnapshot:i,imageObjectUrls:o,name:r,shape:s})=>Cb({editor:n,flushSnapshot:i,imageObjectUrls:o,input:await ub({blob:e,name:r}),nextProps:{},shape:s,canCommit:t}))({blob:c,canCommit:()=>$b(e,o,l,s)&&e.getAsset(l)===a,editor:e,imageObjectUrls:t,name:zb(a.props.name),shape:s});if(!i)return null;if(!$b(e,o,i.assetId,s)){const n=_f(e),r=e.getShape(o.shapeId);return n?.shapeId===o.shapeId&&qf(r)&&r.props.assetId===i.assetId&&Nf(e),await(async({assetId:e,editor:t,imageObjectUrls:n,storageKey:i})=>{!i||e&&t.getAsset(e)||(n.release(i),await ab(i))})({assetId:i.assetId,editor:e,imageObjectUrls:t,storageKey:i.storageKey}),null}return Hf(e),await Tb({flushSnapshot:n,operation:"image smudge confirmation"}),g}return Hf(e),g})({editor:e,flushSnapshot:n,imageObjectUrls:t,replace:i,session:o,strokes:r})}finally{nA.delete(o)}}({editor:e,flushSnapshot:t,imageObjectUrls:i.objectUrls,replace:n?.replace??!0}),isActive:()=>!!_f(e)};return(e=>{Ff(e).registerConfirmHandler(e=>o.confirm(e))})(e),{insert:({source:n,pagePoint:o,size:r,strategy:s})=>xb({editor:e,imageObjectUrls:i.objectUrls,source:n,pagePoint:o,size:r,strategy:s,flushSnapshot:t}),async replaceSelection({file:n}){if(!n.type.startsWith("image/"))return!1;const[o]=e.getSelectedShapes();return!(!qf(o)||o.isLocked||(await Pb({editor:e,file:n,imageObjectUrls:i.objectUrls,flushSnapshot:t}),0))},downloadSelectionOriginal:()=>kb({editor:e,imageObjectUrls:i.objectUrls}),smudge:o}}function Hb(e,t){const n=new Map;for(const i of t){if(!qf(i)||!i.props.assetId)continue;const t=e.getAsset(i.props.assetId);if(!Xf(t))throw new Error(`Image asset "${i.props.assetId}" is unavailable.`);n.set(t.id,t)}return n}async function Wb(e,t){const{source:n}=e.props;if("local"===n.kind){const i=await(async e=>{const t=await sb(e);return t?Eh(t):null})(n.storageKey);if(!i)throw new Error(`Could not embed local image asset "${e.id}".`);return{href:t,dataUrl:i}}if(t.startsWith("data:"))return{href:t,dataUrl:t};let i;try{i=await fetch(t)}catch(r){throw new Error(`Could not download image asset "${e.id}".`,{cause:r})}if(!i.ok)throw new Error(`Could not download image asset "${e.id}" (${i.status}).`);const o=await Eh(await i.blob());if(!o)throw new Error(`Could not embed remote image asset "${e.id}".`);return{href:t,dataUrl:o}}function _b(e,t){return"local"===e.props.source.kind?t.objectUrls.resolve(e.props.source.storageKey):e.props.source.url}function Kb(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Yb({editor:e,flushSnapshot:t,imports:n,services:i}){const o=i.get(tA);return o?Nx(eA,{editor:e,hostBridge:i.get(rA)??void 0,imageAssetService:o,imports:n,flushSnapshot:t}):null}function Xb(e){return e.startsWith("data:image/")||/\.(?:avif|bmp|gif|jpe?g|png|svg|webp)(?:[?#].*)?$/i.test(e)}async function qb(e,t,n){const i=Array.from(e.matchAll(/\burl\(\s*(["']?)(.*?)\1\s*\)/giu),e=>e[2]?.trim()).filter(e=>!!e),o=new Map;for(const r of new Set(i)){if(r.startsWith("data:")||r.startsWith("#"))continue;const e=Qb(r,t).href,i=await Zb(await(await Gb(e,n)).blob(),n);o.set(r,i)}return e.replace(/\burl\(\s*(["']?)(.*?)\1\s*\)/giu,(e,t,n)=>{const i=o.get(n.trim());return i?`url(${t}${i}${t})`:e})}function jb(e){const t=String.raw`\blocal\(\s*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^)]*)\s*\)`;return e.replace(new RegExp(`${t}\\s*,\\s*`,"giu"),"").replace(new RegExp(`\\s*,\\s*${t}`,"giu"),"").replace(new RegExp(t,"giu"),"")}function Vb(e,t){if(!/\burl\(\s*["']?data:/iu.test(e))throw new Error(`Font resource "${t}" has no embeddable source.`);return e}async function Gb(e,t){let n;try{n=await fetch(e)}catch(i){throw new Error(`Could not download font resource "${t}".`,{cause:i})}if(!n.ok)throw new Error(`Could not download font resource "${t}" (${n.status}).`);return n}async function Zb(e,t){const n=await Eh(e);if(!n)throw new Error(`Could not embed font resource "${t}".`);return n}function Qb(e,t){try{return t?new URL(e,t):new URL(e,globalThis.location?.href)}catch(n){throw new Error(`Could not resolve font resource URL "${e}".`,{cause:n})}}function Jb(e,t){return tx(e).some(e=>e.provides?.some(e=>e.id===t.id))}function ex(e){const t=tx(e);return nx(t.map(({id:e})=>e),"canvas plugin id"),nx(t.flatMap(e=>(e.provides??[]).map(({id:e})=>e)),"canvas plugin capability provider"),(e=>{const t=new Map(e.map(e=>[e.id,e])),n=new Map(e.flatMap(e=>(e.provides??[]).map(t=>[t.id,e]))),i=[],o=new Set,r=new Set,s=e=>{if(!r.has(e.id)){if(o.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);o.add(e.id);for(const i of e.requires??[]){const o=tr(i)?n.get(i.id):t.get(i.id);if(!o){const t=tr(i)?`capability "${i.id}"`:`plugin "${i.id}"`;throw new Error(`Canvas plugin "${e.id}" requires missing ${t}.`)}s(o)}o.delete(e.id),r.add(e.id),i.push(e)}};for(const a of e)s(a);return i})(t)}function tx(e){return e.flat(1/0)}function nx(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t}: ${i}.`);n.add(i)}}function ix(e){const[t]=e.selection.selectedShapes;return!(1!==e.selection.count||!t?.parentId.startsWith("shape:"))&&"frame"===e.editor.getShape(t.parentId)?.type}function ox(e){return Math.min(1,Math.max(0,e))}function rx(e={}){const t=YA.filter(([t])=>!1!==e[t]).map(([t,n])=>{if("text"===t){const t=e.text;return"object"==typeof t?$l(t):n}return n});return ex(t),[...t,ZE,cA,OA,BA,KA,...!1===e.image?[]:[sA],...!1===e.text?[]:[{id:"canvas-kit.text-svg-assets",requires:[FP],setup(e){const t=e.get(vP).get(FP);if(!t)throw new Error("Text font catalog capability is unavailable.");e.get(kC).addSvgInliners(function(e){return{async inline({exportedShapes:t,svg:n}){const i=t.filter(Is),o=i.map(e=>Jr(e.props.richText)).join(""),r=new Set(i.map(e=>e.props.font)),s=[e.defaultFont,...e.fontsById.values()].filter(t=>(({definition:e,isDefault:t,svg:n,usedFontIds:i})=>{return!!e.source&&"system"!==e.source.kind&&(t&&i.has("default")||i.has(e.id)||n.includes(`font-family:${o=e.cssFamily,o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}`));var o})({definition:t,isDefault:t===e.defaultFont,svg:n,usedFontIds:r})),a=(await Promise.all(s.map(e=>(async(e,t)=>{const{source:n}=e;if(!n||"system"===n.kind)return"";if("stylesheet"===n.kind){const i=((e,t)=>{const n=Qb(e);if(t.length>0&&"fonts.googleapis.com"===n.hostname&&!n.searchParams.has("text")){const e=Array.from(new Set(t)).join("");encodeURIComponent(e).length<=1500&&n.searchParams.set("text",e)}return n.href})(n.cssUrl,t),o=await Gb(i,e.id);return Vb(jb(await qb(await o.text(),o.url||i,e.id)),e.id)}return(async(e,t)=>{const n="string"==typeof e.src?Vb(jb(await qb(e.src,void 0,t)),t):`url("${await Zb(new Blob([e.src],{type:"application/octet-stream"}),t)}")`,i=(e=>e?[["ascent-override",e.ascentOverride],["descent-override",e.descentOverride],["font-display",e.display],["font-feature-settings",e.featureSettings],["line-gap-override",e.lineGapOverride],["font-stretch",e.stretch],["font-style",e.style],["unicode-range",e.unicodeRange],["font-weight",e.weight]].flatMap(([e,t])=>t?[`;${e}:${t}`]:[]).join(""):"")(e.descriptors);return`@font-face{font-family:${o=e.family,`"${o.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`};src:${n}${i}}`;var o})(n,e.id)})(e,o)))).filter(e=>e.length>0);return a.length>0?((e,t)=>{const n=e.match(/^<svg\b[^>]*>/u);if(!n)throw new Error("Could not embed font resources in the generated SVG.");const i=`<style type="text/css">${o=t,o.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}</style>`;var o;return`${n[0]}${i}${e.slice(n[0].length)}`})(n,a.join("\n")):n}}}(t))}}]]}function sx(e=[]){const t=new XA;for(const n of e)t.registerAction(n);return t}function ax(e=[]){return new qA(e)}function lx(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t} id: ${i}.`);n.add(i)}}function dx(e=[]){const t=new jA;for(const n of e)t.registerContribution(n);return t}function cx(e,t,n){const i=(e.order??0)-(t.order??0);return 0===i&&e.id&&t.id?(n?.get(e.id)??0)-(n?.get(t.id)??0):i}function ux(e=[]){return new VA(e)}function hx(e=[]){return new GA(e)}function px(e=[]){const t=new ZA;for(const n of e)t.registerContribution(n);return t}function gx(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t} id: ${i}.`);n.add(i)}}function fx(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t}: ${i}.`);n.add(i)}}function mx(e){return[...e].sort((e,t)=>(e.order??0)-(t.order??0))}function Sx(e){try{e()}catch(t){const e=globalThis.reportError;try{e?e(t):console.error(t)}catch(n){console.error(n)}}}function yx(e={}){const t=e.id??"canvas-kit",n=(e=>void 0!==e.persistence?e.persistence:function(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await(async(e={})=>{const[t,n]=await(async e=>(await Yh("snapshots",e)??e.map(()=>null)).map(Gh))([jh(e),Vh(e)]);return{documentSnapshot:t,sessionSnapshot:n}})(e);return t.throwIfAborted(),n},saveDocument:t=>qh({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>qh({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}({storageNamespace:e.storageNamespace??"land.canvasKit"}))(e),i=[],o=e.plugins??rx(),r=!Jb(o,dT),s=(e=>{const t=ex(e),n=[],i=[];for(const o of t)o.editor&&n.push(o.editor),o.render&&i.push(o.render);return nx(n.map(({id:e})=>e),"editor plugin id"),nx(i.map(({id:e})=>e),"render plugin id"),{plugins:t,pluginIds:t.map(({id:e})=>e),editorPlugins:n,renderPlugins:i,shapeTypes:Array.from(new Set(n.flatMap(e=>(e.shapeCapabilities??[]).map(({type:e})=>e))))}})([[[...Jb(o,TC)?[]:[LC],...Jb(o,xC)?[]:[CC],...Jb(o,Ek)?[]:[bC],...r?[Wh({svgAssetInliners:i})]:[]],o]]),a=(({factories:e=[],productId:t})=>{const n=new Map,i=[],o=()=>{const e=i.splice(0).reverse();try{for(const n of e)try{n()}catch(t){mp(t)}}finally{n.clear()}},r=(e,t)=>{if(n.has(e.token.id))throw new Error(`Duplicate product service token: ${e.token.id}.`);const o=e.create(t);return n.set(e.token.id,o),e.dispose&&i.push(()=>e.dispose?.(o)),o};try{for(const n of e)r(n,{productId:t})}catch(s){throw o(),s}return{add:e=>r(e,{productId:t}),get:e=>n.get(e.id)??null,dispose(){o()}}})({productId:t}),l=(()=>{const e=[];let t=!1;return{defer(n){t?Sx(n):e.push(n)},dispose(){if(!t){t=!0;for(const t of e.splice(0).reverse())Sx(t)}}}})();l.defer(()=>a.dispose());let d=null;const c=[];try{const o=(Ua((u=s.renderPlugins).map(({id:e})=>e),"canvas render plugin id"),Ua(u.flatMap(({shapeRenderers:e=[]})=>e.map(({type:e})=>e)),"shape renderer type"),Ua(u.flatMap(({canvasOverlays:e=[]})=>e.map(({id:e})=>e)),"canvas overlay id"),Ua(u.flatMap(({selectionCustomHandleRenderers:e=[]})=>e.map(({type:e})=>e)),"selection handle renderer type"),Ua(u.flatMap(({domEventGuards:e=[]})=>e.map(({id:e})=>e)),"DOM event guard id"),Ua(u.flatMap(({canvasProviders:e=[]})=>e.map(({id:e})=>e)),"canvas provider id"),Ua(u.flatMap(({canvasComponents:e=[]})=>e.map(({id:e})=>e)),"canvas component id"),Ua(u.flatMap(({shapeOpacityModifiers:e=[]})=>e.map(({id:e})=>e)),"shape opacity modifier id"),{plugins:u,canvasProviders:u.flatMap(({canvasProviders:e=[]})=>e),canvasComponents:u.flatMap(({canvasComponents:e=[]})=>e),rendererRegistry:sr(u),overlayRegistry:xr(u),domEventGuardRegistry:Rr(u)});d=(e=>{const t=function(e={}){const{plugins:t=[],...n}=e,i=(e=>({shapeUtils:e.flatMap(e=>e.shapeUtils??[]),shapeSvgExporters:e.flatMap(e=>e.shapeSvgExporters??[]),bindingUtils:e.flatMap(e=>e.bindingUtils??[]),shapeCapabilities:e.flatMap(e=>e.shapeCapabilities??[])}))(t),o=new yv({...n,shapeUtils:i.shapeUtils,shapeSvgExporters:i.shapeSvgExporters,bindingUtils:i.bindingUtils,shapeCapabilities:i.shapeCapabilities});try{return o.runtime.onDispose(((e,t)=>{const n=[];try{for(const i of t){for(const n of i.interactionHandlers??[])e.interactions.register(n);const t=i.setup?.(e);t&&n.push(t)}}catch(i){throw To(n),i}return()=>{const e=To(n);if(null!==e)throw e}})(o,t)),o}catch(r){try{o.dispose()}catch{}throw r}}({documentMeta:e.documentMeta,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new Wv(e),{shortcut:"v"}),t.tools.register("hand",e=>new vv(e),{shortcut:"h"}),t.tools.setToolLocked(t.isToolLocked()),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({documentMeta:e.documentMeta?{...e.documentMeta}:void 0,editorPlugins:s.editorPlugins,resolveAssetUrl:e=>d?(({assetResolverTokens:e,assetId:t,editor:n,services:i})=>{for(const o of fp({assetResolverTokens:e,services:i})){const e=o.resolveAssetUrl(n,t);if(e)return e}return null})({assetResolverTokens:c,assetId:e,editor:d,services:a}):null});const r=d;l.defer(()=>r.dispose());const h=n?new JA(d,n):null,p=d.getDocumentSnapshot(),g=d.getSessionSnapshot(),f=function({assetResolverTokens:e,defer:t,editor:n,persistence:i,productId:o,services:r,svgAssetInliners:s}){const a=[],l=[],d=[],c=[],u=[],h=[],p=[],g=[],f=[],m=[],S=[],y=[],b=new Map,x=new Map,I=new Map,v=[],w=[];let P=null,k=!1;const C=()=>{if(k)throw new Error("Canvas plugin setup is already sealed.")},T=()=>{if(!P)throw new Error("Canvas plugin registration is only available during setup.");return P},M={get:e=>b.has(e.id)?b.get(e.id):null,provide(e,t){C();const n=T();if(b.has(e.id))throw new Error(`Duplicate canvas plugin capability: ${e.id}.`);b.set(e.id,t),x.set(e.id,n.id)}},E=new Map([[IP.id,{add(...e){C(),a.push(...e)},addShortcuts(...e){C(),l.push(...e)}}],[MP.id,{add(e){C(),g.push({api:e,pluginId:T().id})}}],[vP.id,M],[PP.id,{add(...e){C(),u.push(...e)}}],[kP.id,{add(...e){C(),c.push(...e)}}],[CP.id,{add(...e){C(),p.push(...e)}}],[TP.id,{add(...e){C(),h.push(...e)}}],[EP.id,{add(e){C();const t=r.add(e);return I.set(e.token.id,T().id),t},get:e=>r.get(e)}],[RP.id,{add(...e){C(),d.push(...e)}}],[kC.id,{addResolver(t){C(),e.push(t)},addSvgInliners(...e){C(),s.push(...e)}}],[IC.id,{beforeCommand(e){C(),m.push(e)},beforeReady(e){C(),f.push(e)},defer(e){C(),t(e)}}],[vC.id,i],[wC.id,{addComponents(...e){C(),y.push(...e)},addProviders(...e){C(),S.push(...e)},allowPropertiesDuringEditing(e){C(),w.push(e)}}]]),A={editor:n,productId:o,get(e){if(!E.has(e.id))throw new Error(`Canvas plugin setup extension is unavailable: ${e.id}.`);return E.get(e.id)}};return{install(e){if(C(),v.push(...(e.provides??[]).map(t=>({pluginId:e.id,token:t}))),e.setup){P=e;try{if(void 0!==e.setup(A))throw new Error(`Canvas plugin "${e.id}" setup must register cleanup through the lifecycle extension.`)}finally{P=null}}},seal(){C(),k=!0,fx(a.map(({id:e})=>e),"canvas action id"),fx(d.map(({id:e})=>e),"toolbar contribution id"),fx(u.map(({id:e})=>e),"chrome contribution id"),fx(c.map(({id:e})=>e),"context-menu contribution id"),fx(h.map(({id:e})=>e),"canvas import contribution id"),fx(p.map(({id:e})=>e),"canvas export contribution id"),fx(p.map(({format:e})=>e),"canvas export format"),fx(y.map(({id:e})=>e),"component id"),fx(S.map(({id:e})=>e),"provider id"),fx(g.map(({api:e})=>e.token.id),"product API token"),fx(l.map(({actionId:e})=>e),"action shortcut action id"),((e,t,n,i,o)=>{const r=t.map(({actionId:e})=>e).filter(t=>!e.has(t));if(r.length>0)throw new Error(`Action shortcuts reference missing action(s): ${r.join(", ")}.`);for(const s of[...n,...i,...o]){const t=s.actionIds.filter(t=>!e.has(t));if(t.length>0)throw new Error(`Contribution "${s.id}" references missing action(s): ${t.join(", ")}.`)}})(new Set(a.map(({id:e})=>e)),l,u,c,d),(({apiDefinitions:e,capabilityValueProviders:t,declaredCapabilities:n,serviceProviders:i})=>{const o=new Map(e.map(({api:e,pluginId:t})=>[e.token.id,t]));for(const{pluginId:r,token:s}of n)if(("api"===s.kind?o.get(s.id):"service"===s.kind?i.get(s.id):t.get(s.id))!==r)throw new Error(`Canvas plugin "${r}" did not register declared capability "${s.id}".`)})({apiDefinitions:g,capabilityValueProviders:x,declaredCapabilities:v,serviceProviders:I});for(const{actionId:e,shortcut:o}of l)n.shortcuts.registerActionShortcut(e,o);const t=(()=>{const e=new Map;return{register(t,n){if(e.has(t.id))throw new Error(`Duplicate product API token: ${t.id}.`);e.set(t.id,n)},get:t=>e.get(t.id)??null}})(),i={apis:t,capabilities:M,editor:n,exportRegistry:ux(p),productId:o,services:r};for(const{api:e}of g){const n=e.create(i);null!==n&&t.register(e.token,n)}return{actionRegistry:sx(a),apis:t,assetResolverTokens:[...e],beforeCommandHooks:[...m],beforeReadyHooks:[...f],components:mx(y),chromeRegistry:ax(u),contextMenuRegistry:dx(c),importRegistry:hx(h),providers:mx(S),toolbarRegistry:px(d),canShowPropertiesDuringEditing:e=>w.some(t=>t(e))}}}}({assetResolverTokens:c,defer(e){l.defer(e)},editor:d,persistence:h,productId:t,services:a,svgAssetInliners:i});for(const e of s.plugins)f.install(e);const m=f.seal(),S={active:!1};let y=null;const b=(({assertCanBootstrap:e,assertCanExecute:t,editor:n,hooks:i})=>{const o=e=>{t?.();for(const t of i)t({commandId:e.commandId,context:e.context,editor:n});return e.run()};return{execute:(e,...t)=>o({commandId:e.id,run:()=>e.run(n,...t)}),executeBootstrap:(t,...i)=>(e?.(),t.run(n,...i)),executeFromAction:(e,t,...i)=>o({commandId:e.id,context:t,run:()=>e.run(n,...i)}),executeAction:o}})({assertCanBootstrap(){if(!S.active)throw new Error("CanvasKit bootstrap commands are only available while seedDocument is running.")},assertCanExecute(){const e=y?.state??"created";if("ready"!==e)throw new Error(`CanvasKit commands require a ready runtime; received runtime in "${e}" state.`)},editor:d,hooks:m.beforeCommandHooks}),x=gp({apis:m.apis,assertToolId:Sp,editor:d,executeCommand:b.execute,productId:t}),I=gp({apis:m.apis,assertToolId:Sp,editor:d,executeCommand:b.executeBootstrap,productId:t}),v=function({actionRegistry:e,commandExecutor:t}){return({actionId:n,context:i,value:o})=>{const r=e.getAction(n);if(!r||"enabled"!==gl(r,i))return!1;const s={context:i,value:void 0!==o?o:r.getValue?.(i)??null},a=((e,t,n)=>{const i=SC.get(t);return i?i.execute(e,n):null})(t,r,s);return null!==a?a:(t.executeAction({commandId:r.id,context:i,run(){r.run(s)}}),!0)}}({actionRegistry:m.actionRegistry,commandExecutor:b}),w={canvasRuntime:o,actionRegistry:m.actionRegistry,chromeRegistry:m.chromeRegistry,toolbarRegistry:m.toolbarRegistry,contextMenuRegistry:m.contextMenuRegistry,importRegistry:m.importRegistry,executeAction:v,executeCommand:b.executeAction,providers:m.providers,components:m.components,chrome:e.chrome,canShowPropertiesDuringEditing:m.canShowPropertiesDuringEditing},P={abortController:new AbortController,assetResolverTokens:c,beforeReadyHooks:m.beforeReadyHooks,cleanDocumentSnapshot:p,cleanSessionSnapshot:g,commandBootstrap:S,controller:x,editor:d,mountedOwner:null,persistence:n,persistenceCoordinator:h,productId:t,resources:l,render:w,seedDocument:e.seedDocument,seedController:I,services:a,shouldSkipStoredSnapshots:e.shouldSkipStoredSnapshots,startPromise:null,state:"created"};y=P;const k={controller:x,start:()=>(e=>{if("disposing"===e.state||"disposed"===e.state)return Promise.reject(new Error("Cannot start a disposing or disposed CanvasKitRuntime."));if(e.startPromise)return e.startPromise;e.state="starting";const t=(async e=>{const{assetResolverTokens:t,beforeReadyHooks:n,editor:i,persistence:o,persistenceCoordinator:r,productId:s,services:a}=e,l=e.abortController.signal,d=[],c=e=>(async(e,t,n)=>{t.throwIfAborted();try{return await new Promise((n,i)=>{const o=()=>i(t.reason);t.addEventListener("abort",o,{once:!0}),Promise.resolve().then(e).then(n,i).finally(()=>{t.removeEventListener("abort",o)})})}catch(i){t.throwIfAborted(),n.push(i)}})(e,l,d),u=e.shouldSkipStoredSnapshots?.()??!1;let h,p=!1,g={documentSnapshot:null,sessionSnapshot:null};if(!u&&o?.load){const e=await c(()=>o.load({signal:l}));e&&(g=e,p=!0)}if(l.throwIfAborted(),vx(e),null!==g.documentSnapshot)try{i.loadDocumentSnapshot(g.documentSnapshot,{source:"system"}),h="restored"}catch(S){l.throwIfAborted(),d.push(S),vx(e),h=xx(e)}else h=xx(e);l.throwIfAborted();let f=!1;if(null!==g.sessionSnapshot)try{i.loadSessionSnapshot(g.sessionSnapshot,{source:"system"}),f=!0}catch(S){l.throwIfAborted(),d.push(S),i.loadSessionSnapshot(e.cleanSessionSnapshot,{source:"system"})}i.history.clear();const m={assetResolverTokens:t,editor:i,services:a,signal:l};await c(()=>(async({assetResolverTokens:e,editor:t,signal:n,services:i})=>{await Promise.all(fp({assetResolverTokens:e,services:i}).map(e=>e.preloadForEditor?.(t,{signal:n})))})(m)),p&&await c(()=>(async({assetResolverTokens:e,editor:t,signal:n,services:i})=>{await Promise.all(fp({assetResolverTokens:e,services:i}).map(e=>e.cleanupAfterRestore?.(t,{signal:n})))})(m));for(const y of n)l.throwIfAborted(),await c(()=>y({editor:i,persistence:r,productId:s,services:a,signal:l,startup:{documentSource:h,sessionRestored:f,warnings:[...d]}}));return l.throwIfAborted(),!u&&r&&(r.start(),e.resources.defer(()=>r.stop())),l.throwIfAborted(),{documentSource:h,sessionRestored:f,warnings:[...d]}})(e).then(t=>(e.abortController.signal.throwIfAborted(),e.state="ready",t)).catch(t=>{throw"disposing"!==e.state&&"disposed"!==e.state&&(e.state="failed"),t});return e.startPromise=t,t})(P),dispose(){(e=>{"disposing"!==e.state&&"disposed"!==e.state&&(e.state="disposing",e.abortController.abort(),e.resources.dispose(),e.state="disposed")})(P)}};return eB.set(k,P),k}catch(h){throw l.dispose(),h}var u}function bx(e){const t=eB.get(e);if(!t)throw new Error("CanvasKitRoot received a runtime that was not created by createCanvasKitRuntime().");return t}function xx(e){if(!e.seedDocument)return"empty";e.commandBootstrap.active=!0;try{e.seedDocument(e.seedController)}finally{e.commandBootstrap.active=!1}return"seeded"}function Ix(e){if("ready"!==e.state)throw new Error(`CanvasKitRoot requires a ready runtime; received runtime in "${e.state}" state. Call and await runtime.start() before rendering.`)}function vx(e){e.editor.loadDocumentSnapshot(e.cleanDocumentSnapshot,{source:"system"}),e.editor.loadSessionSnapshot(e.cleanSessionSnapshot,{source:"system"})}function wx({runtime:e,onControllerReady:t,onControllerDispose:n,exposeControllerOnWindow:i=!1,windowKey:o="landCanvasKit"}){const r=bx(e);Ix(r);const[s]=Ox(()=>({})),[a,l]=Ox(null);return $x(()=>(((e,t)=>{const n=bx(e);if(Ix(n),n.mountedOwner&&n.mountedOwner!==t)throw new Error("A CanvasKitRuntime can only be mounted by one CanvasKitRoot at a time.");n.mountedOwner=t})(e,s),l(e),()=>{((e,t)=>{const n=bx(e);n.mountedOwner===t&&(n.mountedOwner=null)})(e,s)}),[s,e]),a!==e?null:Nx(Px,{exposeControllerOnWindow:i,internals:r,onControllerDispose:n,onControllerReady:t,windowKey:o})}function Px({exposeControllerOnWindow:e=!1,internals:t,onControllerDispose:n,onControllerReady:i,windowKey:o="landCanvasKit"}){const[r,s]=Ox(null),[a,l]=Ox(!1),d=Ux(null),c=Ex(()=>d.current,[]),u=Fx(()=>({isVisible:a,setIsVisible:l}),[a]),{render:h}=t,p={actionRegistry:h.actionRegistry,editor:t.editor,executeAction:h.executeAction,executeCommand:h.executeCommand,getHostElement:c,imports:h.importRegistry,services:t.services};(({controller:e,exposeControllerOnWindow:t,onControllerDispose:n,onControllerReady:i,windowKey:o})=>{const r=Rx(e=>{i?.(e)}),s=Rx(()=>{n?.()});Bx(()=>(r(e),()=>{s()}),[e]),Bx(()=>{if(!t)return;const n=window;return n[o]=e,()=>{n[o]===e&&delete n[o]}},[e,t,o])})({controller:t.controller,exposeControllerOnWindow:e,onControllerDispose:n,onControllerReady:i,windowKey:o});const g=Nx("div",{ref:d,"data-ui":"app-shell","data-canvas-kit":t.productId,className:"land-canvas-kit__shell",children:Hx("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
38
- Nx(qr,{canvasComponents:h.canvasRuntime.canvasComponents,canvasProviders:h.canvasRuntime.canvasProviders,domEventGuardRegistry:h.canvasRuntime.domEventGuardRegistry,onContextMenuRequest:s,overlayRegistry:h.canvasRuntime.overlayRegistry,rendererRegistry:h.canvasRuntime.rendererRegistry,showGrid:u.isVisible}),h.components.map(e=>Nx(e.component,{...p},e.id)),h.chrome?Nx(kx,{activeContextMenu:r,grid:u,internals:t,onActiveContextMenuChange:s}):null,
39
- Nx(fu,{})]})});
40
- return Nx(_v.Provider,{value:t.editor,children:Nx(gu,{children:(f=h.providers,m=g,f.reduceRight((e,t)=>Nx(t.component,{children:e},t.id),m))})});var f,m}function kx({activeContextMenu:e,grid:t,internals:n,onActiveContextMenuChange:i}){const{render:o}=n,r=_h({actionRegistry:o.actionRegistry,activeContextMenu:e,canShowPropertiesDuringEditing:o.canShowPropertiesDuringEditing,chromeRegistry:o.chromeRegistry,contextMenuRegistry:o.contextMenuRegistry,controller:n.controller,editor:n.editor,executeAction:o.executeAction,grid:t,onActiveContextMenuChange:i,toolbarRegistry:o.toolbarRegistry});return o.chrome?.(r)??null}function Cx(e){const[t,n]=Ox(null);return Bx(()=>{let t=!0,i=null;n({options:e,state:tB});try{i=yx(e)}catch(o){return t&&n({options:e,state:{status:"error",error:o}}),()=>{t=!1}}return i.start().then(o=>{t&&i&&n({options:e,state:{status:"ready",runtime:i,startup:o}})},o=>{t&&i&&(i.dispose(),n({options:e,state:{status:"error",error:o}}))}),()=>{t=!1,i?.dispose()}},[e]),t?.options===e?t.state:tB}import{createContext as Tx,memo as Mx,useCallback as Ex,useContext as Ax,useEffect as Bx,useEffectEvent as Rx,useId as Lx,useLayoutEffect as $x,useMemo as Fx,useRef as Ux,useState as Ox,useSyncExternalStore as Dx}from"react";import{Fragment as zx,jsx as Nx,jsxs as Hx}from"react/jsx-runtime";import{EditorContent as Wx,useEditor as _x}from"@tiptap/react";import{mergeAttributes as Kx}from"@tiptap/core";import{Bold as Yx}from"@tiptap/extension-bold";import{Italic as Xx}from"@tiptap/extension-italic";import{Link as qx}from"@tiptap/extension-link";import{Strike as jx}from"@tiptap/extension-strike";import{TextAlign as Vx}from"@tiptap/extension-text-align";import{BackgroundColor as Gx,Color as Zx,FontFamily as Qx,FontSize as Jx,LineHeight as eI,TextStyle as tI}from"@tiptap/extension-text-style";import{Underline as nI}from"@tiptap/extension-underline";import{Selection as iI}from"@tiptap/extensions/selection";import oI from"@tiptap/starter-kit";import{createPortal as rI}from"react-dom";var sI,aI=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),lI=0,dI=null,cI=null,uI=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)=>{dI&&!dI.initialAtomValues.has(e)&&dI.initialAtomValues.set(e,t)})(this,i),t(),this.lastChangedEpoch=e(),this.current=n,(e=>{dI||s([e])})(this),n)}update(e){return this.set(e(this.current))}},hI=Symbol("UNINITIALIZED"),pI=class{name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch;children=new Set;state=hI;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!==hI&&!this.haveParentsChanged())return this.lastCheckedEpoch=e(),this.state;let n,r;i(this.selfAsChild);try{n=this.derive(this.state===hI?hI:this.state)}finally{r=o()}for(const e of this.parents)r.has(e)||e.children.delete(this.selfAsChild);this.parents=[...r],this.parentEpochs=this.parents.map(e=>e.lastChangedEpoch);for(const e of this.parents)e.children.add(this.selfAsChild);return this.state!==hI&&(this.isEqual?this.isEqual(this.state,n):Object.is(this.state,n))||(this.state=n,t(),this.lastChangedEpoch=e()),this.lastCheckedEpoch=e(),this.state}get selfAsChild(){return this._selfAsChild||(this._selfAsChild={type:"computed",notify:()=>{},source:this}),this._selfAsChild}_selfAsChild=null;haveParentsChanged(){for(let e=0;e<this.parents.length;e++){const t=this.parents[e];if(t.__unsafe__getWithoutCapture(),t.lastChangedEpoch!==this.parentEpochs[e])return!0}return!1}},gI=class{name;fn;type="effect";parents=[];parentEpochs=[];lastReactedEpoch=-1;isActive=!1;scheduleEffect;constructor(e,t,n){this.name=e,this.fn=t,this.scheduleEffect=n?.scheduleEffect}selfAsChild={type:"effect",notify:()=>this.maybeSchedule()};attach(){this.isActive=!0,this.execute()}detach(){this.isActive=!1;for(const e of this.parents)e.children.delete(this.selfAsChild);this.parents=[],this.parentEpochs=[]}maybeSchedule(){this.isActive&&this.lastReactedEpoch!==e()&&(this.haveParentsChanged()?this.scheduleEffect?this.scheduleEffect(()=>this.execute()):this.execute():this.lastReactedEpoch=e())}execute(){if(this.isActive){for(const e of this.parents)e.children.delete(this.selfAsChild);i(this.selfAsChild);try{this.fn()}finally{const t=o();this.parents=[...t],this.parentEpochs=this.parents.map(e=>e.lastChangedEpoch);for(const e of this.parents)e.children.add(this.selfAsChild);this.lastReactedEpoch=e()}}}haveParentsChanged(){for(let e=0;e<this.parents.length;e++){const t=this.parents[e];if(t.__unsafe__getWithoutCapture(),t.lastChangedEpoch!==this.parentEpochs[e])return!0}return!1}},fI=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}},mI=class e{x;y;constructor(e,t){this.x=e,this.y=t}add(t){return new e(this.x+t.x,this.y+t.y)}sub(t){return new e(this.x-t.x,this.y-t.y)}mul(t){return new e(this.x*t,this.y*t)}div(t){return new e(this.x/t,this.y/t)}len2(){return this.x*this.x+this.y*this.y}len(){return Math.sqrt(this.len2())}dist2(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}dist(e){return Math.sqrt(this.dist2(e))}rot(t){const n=Math.cos(t),i=Math.sin(t);return new e(this.x*n-this.y*i,this.x*i+this.y*n)}per(){return new e(-this.y,this.x)}normalize(){const t=this.len();return 0===t?new e(0,0):this.div(t)}equals(e){return this.x===e.x&&this.y===e.y}clone(){return new e(this.x,this.y)}static From(t,n){return new e(t,n)}static Zero(){return new e(0,0)}static Med(t,n){return new e((t.x+n.x)/2,(t.y+n.y)/2)}static Lrp(t,n,i){return new e(t.x+(n.x-t.x)*i,t.y+(n.y-t.y)*i)}static Dist(e,t){return e.dist(t)}static Dist2(e,t){return e.dist2(t)}static Angle(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}static Nudge(e,t,n){const i=t.sub(e),o=i.len();return 0===o?e.clone():e.add(i.mul(n/o))}static RotWith(t,n,i){const o=t.x-n.x,r=t.y-n.y,s=Math.cos(i),a=Math.sin(i);return new e(n.x+o*s-r*a,n.y+o*a+r*s)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}},SI=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 mI(this.x+this.w/2,this.y+this.h/2)}containsPoint(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}containsBox(e){return e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return this.minX<e.maxX&&this.maxX>e.minX&&this.minY<e.maxY&&this.maxY>e.minY}expand(t){return new e(this.x-t,this.y-t,this.w+2*t,this.h+2*t)}clone(){return new e(this.x,this.y,this.w,this.h)}static FromPoints(t){let n=1/0,i=1/0,o=-1/0,r=-1/0;for(const e of t)n=Math.min(n,e.x),i=Math.min(i,e.y),o=Math.max(o,e.x),r=Math.max(r,e.y);return new e(n,i,o-n,r-i)}},yI=class e{a;b;c;d;e;f;constructor(e,t,n,i,o,r){this.a=e,this.b=t,this.c=n,this.d=i,this.e=o,this.f=r}static Identity(){return new e(1,0,0,1,0,0)}static Translate(t,n){return new e(1,0,0,1,t,n)}static Rotate(t){const n=Math.cos(t),i=Math.sin(t);return new e(n,i,-i,n,0,0)}static Scale(t,n){return new e(t,0,0,n,0,0)}compose(t){return new e(this.a*t.a+this.c*t.b,this.b*t.a+this.d*t.b,this.a*t.c+this.c*t.d,this.b*t.c+this.d*t.d,this.a*t.e+this.c*t.f+this.e,this.b*t.e+this.d*t.f+this.f)}applyToPoint(e){return new mI(this.a*e.x+this.c*e.y+this.e,this.b*e.x+this.d*e.y+this.f)}determinant(){return this.a*this.d-this.b*this.c}getMaximumLinearScale(){const e=this.a*this.a+this.b*this.b+this.c*this.c+this.d*this.d,t=this.determinant(),n=Math.max(0,e*e-4*t*t);return Math.sqrt((e+Math.sqrt(n))/2)}tryInvert(t=0){const n=this.determinant(),i=Number.isFinite(t)?Math.max(0,t):0;if(!Number.isFinite(n)||Math.abs(n)<=i)return null;const o=1/n;return new e(this.d*o,-this.b*o,-this.c*o,this.a*o,(this.c*this.f-this.d*this.e)*o,(this.b*this.e-this.a*this.f)*o)}invert(){return this.tryInvert()??e.Identity()}toCssString(){return`matrix(${this.a},${this.b},${this.c},${this.d},${this.e},${this.f})`}toSvgString(){return`matrix(${this.a} ${this.b} ${this.c} ${this.d} ${this.e} ${this.f})`}static ForShape(t,n,i,o=1,r=1){const s=e.Translate(t,n),a=0===i?e.Identity():e.Rotate(i),l=1===o&&1===r?e.Identity():e.Scale(o,r);return s.compose(a).compose(l)}},bI=class{values=new Map;disposers=[];isDisposed=!1;revision=a("editor.runtime.revision",0);revisionSignal=this.revision;notify(){this.revision.set(this.revision.get()+1)}provide(e,t,n){if(this.isDisposed)throw new Error("Cannot provide an editor runtime after disposal.");if(this.values.has(e.id))throw new Error(`Editor runtime already provided: ${e.id}`);return this.values.set(e.id,t),n&&this.disposers.push(()=>n(t)),t}get(e){return this.values.get(e.id)??null}require(e){const t=this.get(e);if(null===t)throw new Error(`Missing editor runtime: ${e.id}`);return t}onDispose(e){this.isDisposed?e():this.disposers.push(e)}dispose(){if(this.isDisposed)return;this.isDisposed=!0;let e=null;try{for(const n of this.disposers.splice(0).reverse())try{n()}catch(t){e??=t}}finally{this.values.clear()}if(null!==e)throw e}},xI="document:main",II="page:default",vI="session:main",wI={x:0,y:0,z:1},PI=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}},kI=["fill-blue","fill-green","fill-red","fill-amber","fill-white","fill-slate","stroke-blue","stroke-green","stroke-red","stroke-orange","stroke-slate","stroke-muted","text-slate","text-blue","text-green","text-red"],CI=Object.fromEntries(kI.map(e=>[e,`--land-shape-${e}`])),TI={"fill-blue":"#dbeafe","fill-green":"#dcfce7","fill-red":"#fee2e2","fill-amber":"#fff7ed","fill-white":"#f8fafc","fill-slate":"#e2e8f0","stroke-blue":"#1d4ed8","stroke-green":"#15803d","stroke-red":"#dc2626","stroke-orange":"#ea580c","stroke-slate":"#334155","stroke-muted":"#94a3b8","text-slate":"#0f172a","text-blue":"#1d4ed8","text-green":"#15803d","text-red":"#dc2626"},MI=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()}},EI=Symbol("editorStore"),AI=class{marks=new Map;undoStack=[];redoStack=[];_state=a("store.history.state",{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0});state=this._state;clear(){this.marks.clear(),this.undoStack.length=0,this.redoStack.length=0,this.publishState()}mark(e){this.marks.set(e,((e,t=[])=>({id:e,forward:{added:[],updated:[],removed:[]},parentIds:t}))(e,[...this.marks.keys()]))}append(e,t="change"){if(J(e))if(this.marks.size>0)for(const[n,i]of this.marks.entries())this.marks.set(n,oe(i,e));else this.undoStack.push(re(t,e)),this.redoStack.length=0,this.publishState()}bailToMark(e){const t=this.marks.get(e);if(!t)return null;if(this.marks.delete(e),!J(t.forward))return null;const n=ne(t.forward);for(const i of t.parentIds){const e=this.marks.get(i);e&&this.marks.set(i,oe(e,n))}return n}squashToMark(e,t=e){const n=this.marks.get(e);if(!n)return null;if(this.marks.delete(e),!J(n.forward))return null;if(n.parentIds.some(e=>this.marks.has(e)))return null;const i=re(t,n.forward);return this.undoStack.push(i),this.redoStack.length=0,this.publishState(),i}undo(){const e=this.undoStack.pop()??null;return e?(this.redoStack.push(e),this.publishState(),e):null}redo(){const e=this.redoStack.pop()??null;return e?(this.undoStack.push(e),this.publishState(),e):null}getEntries(){return this.undoStack}publishState(){this._state.set({canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoDepth:this.undoStack.length,redoDepth:this.redoStack.length})}},BI=class{recordsSignal;draftRevisionSignal;recordSignals=new Map;listeners=new Set;transactionDepth=0;draftRecords=null;pendingSource="system";constructor(e){this.recordsSignal=a("store.records",new Map(e.map(e=>[e.id,e]))),this.draftRevisionSignal=a("store.draftRevision",0)}get(e){return this.getReadableRecords().get(e)}getActiveAtomicOperationRevision(){return this.transactionDepth>0?this.draftRevisionSignal.get():null}getActiveAtomicOperationSnapshot(){if(!this.draftRecords||0===this.transactionDepth)throw new Error("Store.getActiveAtomicOperationSnapshot() requires an active atomic operation.");return Array.from(this.draftRecords.values())}getRecordSignal(e){let t=this.recordSignals.get(e);return t||(t=l(`store.record.${e}`,()=>(this.recordsSignal.get(),this.draftRevisionSignal.get(),this.get(e))),this.recordSignals.set(e,t)),t}getAll(){if("computed"===cI?.child.type)throw new Error("Store.getAll() cannot run while deriving a computed signal. Read a keyed record or indexed query signal instead.");return Array.from(this.getReadableRecords().values())}getByScope(e){return this.getAll().filter(t=>"scope"in t&&t.scope===e)}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}atomic(e,t="system"){if(0===this.transactionDepth){let i=[];if(n(()=>{i=this.runAtomic(e,t)}),i.length>0)throw i[0];return}this.runAtomic(e,t)}runAtomic(e,t){const n=0===this.transactionDepth;let i;n&&(this.draftRecords=new Map(this.recordsSignal.get()),this.pendingSource=t),this.transactionDepth+=1;try{e()}catch(o){i=o}if(this.transactionDepth-=1,n||this.bumpDraftRevision(),n){const e=this.recordsSignal.get(),t=this.draftRecords,n=this.pendingSource;this.draftRecords=null,this.pendingSource="system",this.bumpDraftRevision();const o=t?te(e,t):{added:[],updated:[],removed:[]};if(!i&&t&&J(o))return this.recordsSignal.set(t),this.notifyListeners({source:n,diff:o})}if(i)throw i;return[]}put(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)t.get(n.id)!==n&&t.set(n.id,n)},t)}remove(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e)if(!t.delete(n))continue},t)}replaceAll(e,t="system"){const n=new Map(e.map(e=>[e.id,e])),i=te(this.recordsSignal.get(),n);if(!J(i))return;this.recordsSignal.set(n);const o=this.notifyListeners({source:t,diff:i});if(o.length>0)throw o[0]}applyDiff(e,t="system"){this.atomic(()=>{const t=this.getMutableRecords();for(const n of e.added)t.set(n.id,n);for(const n of e.updated)t.set(n.after.id,n.after);for(const n of e.removed)t.delete(n.id)},t)}getMutableRecords(){if(!this.draftRecords)throw new Error("Store mutations must run inside store.atomic");return this.draftRecords}getReadableRecords(){return this.draftRecords??this.recordsSignal.get()}bumpDraftRevision(){this.draftRevisionSignal.set(this.draftRevisionSignal.get()+1)}notifyListeners(e){const t=[];for(const i of this.listeners)try{i(e)}catch(n){t.push(n)}return t}},RI=new Set,LI=new WeakMap,$I=class{editor;buffer=new AI;scopeActivations=[];_state=a("editor.history.state",this.buffer.state.__unsafe__getWithoutCapture());state=this._state;constructor(e){this.editor=e,this.editor.operations.subscribe(e=>{this.handleCommit(e)})}clear(){this.buffer.clear(),this.publishEffectiveState()}activateScope(e){const t={scope:e,unsubscribe:()=>{},isActive:!0};return t.unsubscribe=e.subscribe(()=>{t.isActive&&this.publishEffectiveState()}),this.scopeActivations.push(t),this.publishEffectiveState(),()=>{this.deactivateActivation(t)}}deactivateScope(e){for(let t=this.scopeActivations.length-1;t>=0;t--){const n=this.scopeActivations[t];if(n.scope===e)return this.deactivateActivation(n),!0}return!1}getActiveScope(){return this.scopeActivations.at(-1)?.scope??null}undo(){const e=this.getActiveScope();if(e){const t=e.undo();return this.publishEffectiveState(),t}const t=this.buffer.undo();return!!t&&(this.editor.operations.run({kind:"history.undo",label:t.label,source:"history",history:"ignore"},()=>{G(this.editor).applyDiff(t.inverse,"history"),this.editor.syncAfterDocumentRestore()}),this.publishEffectiveState(),!0)}redo(){const e=this.getActiveScope();if(e){const t=e.redo();return this.publishEffectiveState(),t}const t=this.buffer.redo();return!!t&&(this.editor.operations.run({kind:"history.redo",label:t.label,source:"history",history:"ignore"},()=>{G(this.editor).applyDiff(t.forward,"history"),this.editor.syncAfterDocumentRestore()}),this.publishEffectiveState(),!0)}getEntries(){return this.buffer.getEntries()}handleCommit(e){"record"===e.history&&"user"===e.source&&(this.buffer.append(e.diff,e.label),this.publishEffectiveState())}deactivateActivation(e){if(!e.isActive)return;e.isActive=!1;const t=this.scopeActivations.indexOf(e);t>=0&&this.scopeActivations.splice(t,1);try{e.unsubscribe()}finally{this.publishEffectiveState()}}publishEffectiveState(){const e=this.getActiveScope(),t=e?{canUndo:(n=e.getState()).canUndo,canRedo:n.canRedo,undoDepth:n.undoDepth??(n.canUndo?1:0),redoDepth:n.redoDepth??(n.canRedo?1:0)}:this.buffer.state.__unsafe__getWithoutCapture();var n,i,o;((i=this._state.__unsafe__getWithoutCapture()).canUndo!==(o=t).canUndo||i.canRedo!==o.canRedo||i.undoDepth!==o.undoDepth||i.redoDepth!==o.redoDepth)&&this._state.set({...t})}},FI=class{manager;state;constructor(e,t){this.manager=e,this.state=t}get id(){return this.state.id}get kind(){return this.state.kind}get source(){return this.state.source}get isActive(){return"active"===this.state.status}commit(){return this.manager.commit(this.state)}cancel(){this.manager.cancel(this.state)}},UI=class{editor;stack=[];commitListeners=new Set;commitQueue=[];nextOperationId=1;revision=0;isPublishing=!1;constructor(e){this.editor=e,G(e).listen(e=>this.handleStoreChange(e))}begin(e){const t=e.source??"user",n=this.getActiveState(),i={id:"operation:"+this.nextOperationId++,kind:e.kind,label:e.label??e.kind,source:t,history:e.history??("user"===t?"record":"ignore"),parent:n,diff:{added:[],updated:[],removed:[]},status:"active",handle:void 0};return i.handle=new FI(this,i),this.stack.push(i),i.handle}run(e,t){const n=this.begin(e);try{const e=t();return n.commit(),e}catch(i){throw n.isActive&&n.cancel(),i}}getActive(){return this.getActiveState()?.handle??null}subscribe(e){return this.commitListeners.add(e),()=>{this.commitListeners.delete(e)}}commit(e){this.assertTopActive(e);const t=He(e.diff);if(this.stack.pop(),e.status="committed",e.parent)return e.parent.diff=ie(e.parent.diff,t),null;if(!J(t))return null;const n={id:e.id,revision:++this.revision,kind:e.kind,label:e.label,source:e.source,history:e.history,diff:t,snapshot:_e(this.editor.getDocumentSnapshot()),sessionSnapshot:Ke(this.editor.getSessionSnapshot())};return this.enqueueCommit(n),n}cancel(e){this.assertTopActive(e);const t=He(e.diff);J(t)&&(G(this.editor).applyDiff(ne(t),e.source),this.editor.syncAfterDocumentRestore()),this.stack.pop(),e.status="cancelled"}handleStoreChange(e){const t=((e,t)=>({added:e.added.filter(t),updated:e.updated.filter(e=>t(e.before)&&t(e.after)),removed:e.removed.filter(t)}))(e.diff,b);if(!J(t))return;const n=this.getActiveState();if(n)return void(n.diff=ie(n.diff,t));const i=He(t);J(i)&&this.enqueueCommit({id:"operation:"+this.nextOperationId++,revision:++this.revision,kind:"editor.change",label:"change",source:e.source,history:"user"===e.source?"record":"ignore",diff:i,snapshot:_e(this.editor.getDocumentSnapshot()),sessionSnapshot:Ke(this.editor.getSessionSnapshot())})}getActiveState(){return this.stack.at(-1)??null}assertTopActive(e){if("active"!==e.status)throw new Error(`Editor operation "${e.kind}" is no longer active.`);if(this.getActiveState()!==e)throw new Error(`Editor operation "${e.kind}" must be completed in LIFO order.`)}enqueueCommit(e){if(this.commitQueue.push(e),!this.isPublishing){this.isPublishing=!0;try{for(;this.commitQueue.length>0;){const e=this.commitQueue.shift();for(const n of this.commitListeners)try{n(e)}catch(t){Ye(t)}}}finally{this.isPublishing=!1}}}},OI=class{},DI=class{editor;constructor(e){this.editor=e}getConflictingBindings(e){const t=this.getExclusiveBindingKey(e);return t?this.getAllBindings().filter(n=>n.id!==e.id&&n.type===e.type&&this.getExclusiveBindingKey(n)===t):[]}canBind(e){const t=this.editor.getShape(e.fromId),n=this.editor.getShape(e.toId);return!(!t||!n)&&(this.editor.getBindingUtil(e).canBind?.(this.editor,e,{fromShape:t,toShape:n})??!0)}syncCreatedBinding(e,t){const n=this.editor.getBindingUtil(e).onBindingCreate?.(this.editor,e);this.applyEffect(n,t,e.id),this.syncShapeHierarchyState([e.fromId,e.toId],t,e.id)}syncUpdatedBinding(e,t,n){const i=this.editor.getBindingUtil(t).onBindingUpdate?.(this.editor,e,t);this.applyEffect(i,n,t.id),this.syncShapeHierarchyState([t.fromId,t.toId],n,t.id)}repairLoadedBindings(e){G(this.editor).atomic(()=>{const t=new Set,n=new Set;for(const i of this.getAllBindings()){const o=this.editor.getShape(i.fromId),r=this.editor.getShape(i.toId);if(!o||!r){this.applyEffect(this.editor.getBindingUtil(i).onInvalidBindingLoad?.(this.editor,i),e,i.id),G(this.editor).remove([i.id],e);continue}if(!this.canBind(i)){this.applyEffect(this.editor.getBindingUtil(i).onInvalidBindingLoad?.(this.editor,i),e,i.id),G(this.editor).remove([i.id],e);continue}const s=this.getExclusiveBindingKey(i);if(s){if(t.has(s)){G(this.editor).remove([i.id],e);continue}t.add(s)}const a=this.editor.getBindingUtil(i).onBindingLoad?.(this.editor,i);this.applyEffect(a,e,i.id),n.add(i.fromId),n.add(i.toId)}this.syncShapeHierarchyState(Array.from(n),e)},e)}handleShapeChanges(e,t){if(0===e.length)return;const n=(i=this.editor,LI.get(i)?.suppressedBindingIds??RI);var i;const o=new Set(e.map(e=>e.after.id)),r=new Set,s=new Set,a=(e,i,o,a)=>{for(const l of this.editor.queries.getBindingsForShape(e.id)){if(n.has(l.id))continue;if("ancestry"===a&&s.has(l.id))continue;const d=`${l.id}:${e.id}:${a}`;if(r.has(d))continue;r.add(d),"self"===a&&s.add(l.id);const c=l.fromId===e.id?"from":"to",u=this.editor.getBindingUtil(l).onAfterShapeChange?.(this.editor,l,{before:i,after:o,role:c,reason:a});this.applyEffect(u,t,l.id)}};for(const l of e)a(l.after,l.before,l.after,"self");for(const l of e)if(je(l))for(const e of this.editor.getDescendantShapeIds(l.after.id)){if(o.has(e))continue;const t=this.editor.getShape(e);t&&a(t,t,t,"ancestry")}this.syncShapeHierarchyState(e.filter(({before:e,after:t})=>e.isHidden!==t.isHidden||e.isLocked!==t.isLocked).map(({after:e})=>e.id),t)}getShapeHierarchyRootId(e){return this.getShapeHierarchyRootIds([e]).get(e)??e}getShapeHierarchyRootIds(e){const t=qe(e,this.getAllBindings(),e=>this.editor.getBindingUtil(e)),n=new Map;for(const i of e){const e=t.get(i)??i;n.set(i,this.editor.getShape(e)?e:i)}return n}getShapeHierarchyMemberIds(e){const t=this.getShapeHierarchyContext(),n=[],i=new Set;for(const o of e){const e=t.rootIdByShapeId.get(o)??o;if(t.shapeById.has(e))for(const o of[e,...t.memberIdsByRootId.get(e)??[]])i.has(o)||(i.add(o),n.push(o))}return n}cleanupBindingsForDeletedShapes(e,t){if(0===e.length)return;const n=new Set(e),i=new Set;for(const o of e){const e=this.editor.getShape(o);if(e)for(const r of this.editor.queries.getBindingsForShape(o)){if(i.has(r.id))continue;i.add(r.id);const s=r.fromId===o?"from":"to";if("to"===s&&n.has(r.fromId)){G(this.editor).remove([r.id],t);continue}const a=this.editor.getBindingUtil(r).onBeforeDeleteShape?.(this.editor,r,{shape:e,role:s});this.applyEffect(a,t,r.id)}}}cleanupBindings(e,t){for(const n of e){const e=this.editor.getBinding(n);if(!e)continue;const i=this.editor.getBindingUtil(e).onBeforeDeleteBinding?.(this.editor,e);this.applyEffect(i,t,e.id)}}applyEffect(e,t,n){if(!e)return;const i=new Set(e.suppressBindingIds??[]);n&&i.add(n),ve(this.editor,i,()=>{e.deleteBindingIds&&e.deleteBindingIds.length>0&&G(this.editor).remove(Array.from(new Set(e.deleteBindingIds)),t),e.bindings&&e.bindings.length>0&&G(this.editor).put(e.bindings,t),e.shapes&&e.shapes.length>0&&this.editor.commands.updateShapes(e.shapes.map(e=>({id:e.id,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props,meta:e.meta})),{source:t}),e.deleteShapeIds&&e.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(Array.from(new Set(e.deleteShapeIds)),{source:t})})}syncShapeHierarchyState(e,t,n){if(0===e.length)return;const i=this.getShapeHierarchyContext(),o=new Set,r=[];for(const s of e){const e=i.rootIdByShapeId.get(s)??s;if(o.has(e))continue;o.add(e);const t=i.shapeById.get(e);if(t)for(const n of i.memberIdsByRootId.get(e)??[]){const e=i.shapeById.get(n);!e||e.isHidden===t.isHidden&&e.isLocked===t.isLocked||r.push({...e,isHidden:t.isHidden,isLocked:t.isLocked})}}r.length>0&&this.applyEffect({shapes:r},t,n)}getShapeHierarchyContext(){const e=G(this.editor).getAll(),t=e.filter(f),n=new Map(t.map(e=>[e.id,e])),i=new Map(qe(t.map(e=>e.id),e.filter(S),e=>this.editor.getBindingUtil(e))),o=new Map;for(const r of t){const e=i.get(r.id)??r.id,t=n.has(e)?e:r.id;if(i.set(r.id,t),t===r.id)continue;const s=o.get(t);s?s.push(r.id):o.set(t,[r.id])}return{memberIdsByRootId:o,rootIdByShapeId:i,shapeById:n}}getAllBindings(){return G(this.editor).getAll().filter(S).sort((e,t)=>e.id.localeCompare(t.id))}getExclusiveBindingKey(e){const t=this.editor.getBindingUtil(e).getExclusiveBindingKey?.(e);return t?`${e.type}:${t}`:null}},zI=class{editor;_viewportScreenSizeSignal=a("editor.viewportScreenSize",{w:0,h:0});viewportScreenSizeSignal=this._viewportScreenSizeSignal;constructor(e){this.editor=e}getCurrentCamera(){return this.editor.currentCameraSignal.get()}getCamera(e=this.editor.getCurrentPageId()){return this.editor.sessionSignal.get().pageCameraById[e]??wI}pageToScreen(e,t=this.editor.getCurrentPageId()){const n=this.getCamera(t);return new e.constructor((e.x-n.x)*n.z,(e.y-n.y)*n.z)}screenToPage(e,t=this.editor.getCurrentPageId()){const n=this.getCamera(t);return new e.constructor(e.x/n.z+n.x,e.y/n.z+n.y)}setCamera(e,t){const n=t?.source??"system",i=t?.pageId??this.editor.getCurrentPageId(),o=this.getCamera(i),r={x:"number"==typeof e.x?e.x:o.x,y:"number"==typeof e.y?e.y:o.y,z:Ve("number"==typeof e.z?e.z:o.z)};this.editor.updateSession({pageCameraById:{...this.editor.sessionSignal.get().pageCameraById,[i]:r}},n)}panCamera(e,t="system"){const n=this.getCurrentCamera();this.setCamera({x:n.x+e.x/n.z,y:n.y+e.y/n.z},{source:t})}zoomCameraAtScreenPoint(e,t,n="system"){const i=Ve(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=Ve(t),o=this.screenToPage(e);this.setCamera({x:o.x-e.x/i,y:o.y-e.y/i,z:i},{source:n})}zoomAtViewportCenter(e,t="system"){const n=this.viewportScreenSizeSignal.get(),i=new mI(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new mI(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)}},NI=new mI(24,24),HI=class{editor;constructor(e){this.editor=e}createPayloadFromSelection(){return ut(this.editor)}pastePayload(e){return this.editor.cancelInteractionForCommand(),ht(this.editor,e)}duplicateSelection(e={}){return this.editor.cancelInteractionForCommand(),((e,t={})=>{const n=ut(e);return n?ht(e,{payload:n,offset:t.offset??NI,source:t.source}):[]})(this.editor,e)}},WI=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},_I=class{editor;constructor(e){this.editor=e}buildInitialRecords(e,t,n={}){const i=this.parseInitialDocumentSnapshot(e,n),o=this.parseInitialSessionSnapshot(t);return[...i.records.length?i.records:[c(n),u()],o.records[0]??h()]}getDocumentSnapshot(){const e=this.editor.store.getAll();return{schemaVersion:3,records:[e.find(g)??c(),...this.editor.getPages(),...e.filter(y).sort((e,t)=>e.id.localeCompare(t.id)),...e.filter(f).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index):e.parentId.localeCompare(t.parentId)),...e.filter(S).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=$t(e,this.editor.shapeUtils,this.editor.bindingUtils);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),this.editor.editing.cancelOperation();const o=this.editor.sessionSignal.get();G(this.editor).replaceAll([...i.records,o],n),this.syncAfterDocumentSnapshotLoad(n)}loadSessionSnapshot(e,t){const n=t?.source??"system",i=Ft(e).records[0]??h(),o=G(this.editor).getAll().filter(b);this.editor.cancelInteractionAndClearTransients("restore"),this.editor.editing.end({runEditEnd:!1,source:n}),this.editor.editing.cancelOperation(),G(this.editor).replaceAll([...o,i],n),this.ensureSessionIntegrity(),this.editor.syncToolStateFromSession(n)}syncAfterDocumentRestore(){this.ensureSessionIntegrity(),this.editor.syncShapeCounter(),this.editor.syncPageCounter(),this.editor.syncBindingCounter(),this.editor.syncAssetCounter()}ensureSessionIntegrity(){const e=G(this.editor),t=e.getAll(),n=t.filter(p).sort((e,t)=>e.index.localeCompare(t.index)),i=n[0]?.id??"page:default",o=new Set(n.map(e=>e.id)),r=t.filter(f),s=new Set(r.map(e=>e.id)),a=new Map(r.map(e=>[e.id,e])),l=new Map;for(const h of r)l.set(h.id,st(h,a,o)??i);const d=t.find(e=>e.id===vI),c=m(d)?d:h(i),u={...c,currentPageId:o.has(c.currentPageId)?c.currentPageId:i,pageCameraById:this.repairCameraByPage(c.pageCameraById,o),pageSelectedShapeIdsById:this.repairSelectionByPage(c.pageSelectedShapeIdsById,o,s,l)};e.put([u],"system")}syncAfterDocumentSnapshotLoad(e){this.syncAfterDocumentRestore(),this.editor.history.clear(),this.editor.bindings.repairLoadedBindings(e)}repairCameraByPage(e,t){const n={};for(const i of t){const t=e[i]??wI;n[i]={x:Number.isFinite(t.x)?t.x:wI.x,y:Number.isFinite(t.y)?t.y:wI.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:wI.z))}}return n}repairSelectionByPage(e,t,n,i){const o={};for(const r of t)o[r]=Array.from(new Set((e[r]??[]).filter(e=>n.has(e)&&i.get(e)===r)));return o}parseInitialDocumentSnapshot(e,t){if(!e)return{schemaVersion:3,records:[c(t),u()]};try{return $t(e,this.editor.shapeUtils,this.editor.bindingUtils)}catch(n){if(!(n instanceof WI))throw n;return{schemaVersion:3,records:[c(t),u()]}}}parseInitialSessionSnapshot(e){if(!e)return{schemaVersion:1,records:[h()]};try{return Ft(e)}catch(t){if(!(t instanceof WI))throw t;return{schemaVersion:1,records:[h()]}}}},KI=class{pressedKeyCodes=a("inputs.pressedKeyCodes",new Set);isSpacePressed=l("inputs.isSpacePressed",()=>this.pressedKeyCodes.get().has("Space"));state=a("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:Ut(),screenVelocity:Ut(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1});setCurrentPointerPoint(e){this.state.update(t=>{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.shiftKey===e.shiftKey&&t.altKey===e.altKey&&t.ctrlKey===e.ctrlKey&&t.metaKey===e.metaKey&&t.accelKey===e.accelKey)return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,o=t.currentTimestamp??e.timestamp,r=e.timestamp-o;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:o,currentTimestamp:e.timestamp,pageVelocity:Ot(n,e.pagePoint,r),screenVelocity:Ot(i,e.screenPoint,r),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}})}handleEvent(e){switch(e.type){case"pointer":return void this.handlePointerEvent(e);case"keyboard":return void this.handleKeyboardEvent(e);case"wheel":return void this.handleWheelEvent(e);case"cancel":return this.resetPointer(),void("blur"!==e.reason&&"dispose"!==e.reason||this.resetKeyboard())}}resetPointer(){this.state.update(e=>({...e,originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:Ut(),screenVelocity:Ut(),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:Ut(),screenVelocity:Ut(),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&&Dt(t,e))return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,o=t.isDragging||(t.originPagePoint??e.pagePoint).dist2(e.pagePoint)>=9,r=t.currentTimestamp??e.timestamp,s=e.timestamp-r;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:r,currentTimestamp:e.timestamp,pageVelocity:Ot(n,e.pagePoint,s),screenVelocity:Ot(i,e.screenPoint,s),buttons:e.buttons,isDragging:o,dragPhase:o?"dragging":"pointing",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}case"pointer_up":case"pointer_cancel":return{...t,previousPagePoint:t.currentPagePoint,previousScreenPoint:t.currentScreenPoint,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:t.currentTimestamp,currentTimestamp:e.timestamp,pageVelocity:Ut(),screenVelocity:Ut(),buttons:e.buttons,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}})}handleKeyboardEvent(e){this.pressedKeyCodes.update(t=>{const n="key_down"===e.name;if(t.has(e.code)===n)return t;const i=new Set(t);return n?i.add(e.code):i.delete(e.code),i}),this.state.update(t=>Dt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}resetKeyboard(){this.pressedKeyCodes.get().size>0&&this.pressedKeyCodes.set(new Set),this.state.update(e=>e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||e.accelKey?{...e,shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1}:e)}handleWheelEvent(e){this.state.update(t=>Dt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},YI=class{editor;_brushBoxSignal=a("editor.brushBox",null);brushBoxSignal=this._brushBoxSignal;brushBoxActiveSignal=l("editor.brushBoxActive",()=>null!==this._brushBoxSignal.get());_bindingPreviewSignal=a("editor.bindingPreview",null);bindingPreviewSignal=this._bindingPreviewSignal;bindingPreviewActiveSignal=l("editor.bindingPreviewActive",()=>null!==this._bindingPreviewSignal.get());_terminalBindingGuidesSignal=a("editor.terminalBindingGuides",[]);terminalBindingGuidesSignal=this._terminalBindingGuidesSignal;_dropTargetShapeIdSignal=a("editor.dropTargetShapeId",null);dropTargetShapeIdSignal=this._dropTargetShapeIdSignal;_hoveredShapeIdSignal=a("editor.hoveredShapeId",null);hoveredShapeIdSignal=this._hoveredShapeIdSignal;_selectionTranslationActiveSignal=a("editor.selectionTranslationActive",!1);selectionTranslationActiveSignal=this._selectionTranslationActiveSignal;terminalBindingResolver=(e,t)=>(({rawPagePoint:e})=>({pagePoint:e.clone(),binding:null,preview:null}))(t);constructor(e){this.editor=e}setBrushBox(e){nt(this._brushBoxSignal.get(),e)||this._brushBoxSignal.set(e?e.clone():null)}setBindingPreview(e){var t,n;(t=this._bindingPreviewSignal.get())===(n=e)||(t&&n?t.terminal===n.terminal&&t.targetShapeId===n.targetShapeId&&Je(t.rawPagePoint,n.rawPagePoint)&&Je(t.resolvedPagePoint,n.resolvedPagePoint)&&(t.guidePath??null)===(n.guidePath??null):t===n)||this._bindingPreviewSignal.set(e?{...e,rawPagePoint:e.rawPagePoint.clone(),resolvedPagePoint:e.resolvedPagePoint.clone()}:null)}setTerminalBindingGuides(e){const t=e??[];((e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],o=t[n];if(!i||!o||!Wt(i,o))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(zt))}setDropTargetShapeId(e){this._dropTargetShapeIdSignal.get()!==e&&this._dropTargetShapeIdSignal.set(e)}setHoveredShapeId(e){this._hoveredShapeIdSignal.get()!==e&&this._hoveredShapeIdSignal.set(e)}setSelectionTranslationActive(e){this._selectionTranslationActiveSignal.get()!==e&&this._selectionTranslationActiveSignal.set(e)}setSnapIndicators(e){e?this.editor.snaps.setIndicators(e):this.editor.snaps.clearIndicators()}setTerminalBindingResolver(e){this.terminalBindingResolver=e}resolveTerminalBinding(e){return this.terminalBindingResolver(this.editor,e)}clearSelectionTransients(){this.setBrushBox(null),this.setBindingPreview(null),this.setTerminalBindingGuides(null),this.setDropTargetShapeId(null),this.setHoveredShapeId(null),this.setSelectionTranslationActive(!1),this.setSnapIndicators(null)}},XI=.001,qI=class{editor;stateSignal;currentPageShapeIdsSignal;currentPageShapesSignal;currentPageShapeHierarchySignal;selectionGeometrySignal;selectionPageOutlineVerticesSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionHasRotationSignal;selectionRotationSignal;selectionRotationCenterSignal;selectionHasCompatibleRotationSignal;selectionAnchorPagePointSignal;stateAtom;shapeQuerySignals=new Map;bindingsFromShapeSignals=new Map;bindingsToShapeSignals=new Map;bindingsForShapeSignals=new Map;draftBindingIndex=null;constructor(e){this.editor=e;const t=G(this.editor);this.stateAtom=a("editor.query.state",(e=>{const t=e.filter(p).sort((e,t)=>e.index.localeCompare(t.index)),n=e.filter(f).sort((e,t)=>e.parentId===t.parentId?((e,t)=>e.index.localeCompare(t.index))(e,t):e.parentId.localeCompare(t.parentId)),i=e.filter(S).sort(qt),o=new Map,r=new Map,s=new Map,a=new Map(n.map(e=>[e.id,e])),l=new Map,d=new Map,c=new Map,u=new Map;for(const p of n)_t(r,p.parentId,p.id);const h=(e,t)=>{for(const n of r.get(t)??[]){const t=a.get(n);t&&(_t(o,e,t.id),s.set(t.id,e),h(e,t.id))}};for(const p of t)h(p.id,p.id);for(const p of i)l.set(p.id,p),Kt(d,p.fromId,p.id),Kt(c,p.toId,p.id),Kt(u,p.fromId,p.id),Kt(u,p.toId,p.id);return{pageShapeIdsByPage:o,childShapeIdsByParent:r,pageIdByShape:s,bindingById:l,bindingIdsByFromShape:d,bindingIdsByToShape:c,relatedBindingIdsByShape:u}})(Array.from(t.recordsSignal.get().values()))),this.stateSignal=this.stateAtom,t.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=l("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(this.editor.getCurrentPageId()),{isEqual:Xt}),this.currentPageShapesSignal=l("editor.query.currentPageShapes",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.getShapeSignal(e).get()).filter(e=>!!e)),this.currentPageShapeHierarchySignal=l("editor.query.currentPageShapeHierarchy",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.getShapeSignal(e).get()).filter(e=>!!e).map(e=>({id:e.id,parentId:e.parentId,type:e.type})),{isEqual:ln});const n=((e,t)=>{const n=l("editor.query.selectionGeometry",()=>an(e,t),{isEqual:on}),i=l("editor.query.selectionPageOutlineVertices",()=>n.get().outlineVertices,{isEqual:nn}),o=l("editor.query.selectionPageBounds",()=>n.get().pageBounds,{isEqual:nt}),r=l("editor.query.selectionFrameBounds",()=>n.get().frameBounds,{isEqual:nt}),s=l("editor.query.selectionRotation",()=>n.get().rotation);return{geometry:n,pageOutlineVertices:i,pageBounds:o,frameBounds:r,hasRotation:l("editor.query.selectionHasRotation",()=>n.get().hasRotation),rotation:s,rotationCenter:l("editor.query.selectionRotationCenter",()=>n.get().rotationCenter,{isEqual:Je}),hasCompatibleRotation:l("editor.query.selectionHasCompatibleRotation",()=>n.get().hasCompatibleRotation),selectionAnchorPagePoint:l("editor.query.selectionAnchorPagePoint",()=>n.get().selectionAnchorPagePoint,{isEqual:Je})}})(this.editor,e=>this.getShapeGeometrySnapshot(e));this.selectionGeometrySignal=n.geometry,this.selectionPageOutlineVerticesSignal=n.pageOutlineVertices,this.selectionPageBoundsSignal=n.pageBounds,this.selectionFrameBoundsSignal=n.frameBounds,this.selectionRotationSignal=n.rotation,this.selectionHasRotationSignal=n.hasRotation,this.selectionRotationCenterSignal=n.rotationCenter,this.selectionHasCompatibleRotationSignal=n.hasCompatibleRotation,this.selectionAnchorPagePointSignal=n.selectionAnchorPagePoint}getShapeIdsForPage(e){return[...this.getShapeIdsForPageSnapshot(e)]}getShapesForPage(e){return this.getShapeIdsForPageSnapshot(e).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getChildShapeIds(e){return[...this.getChildShapeIdsSnapshot(e)]}getChildShapes(e){return this.getChildShapeIdsSnapshot(e).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getDescendantShapeIds(e){const t=[],n=new Set,i=e=>{for(const o of this.getChildShapeIdsSnapshot(e))n.has(o)||(n.add(o),t.push(o),i(o))};return i(e),t}getPageIdForShape(e){return this.stateSignal.get().pageIdByShape.get(e)??null}getPageIdForShapeParent(e){return e.startsWith("page:")?this.editor.getPage(e)?e:null:this.getPageIdForShape(e)}getDescendantPageBounds(e){const t=[];for(const n of this.getDescendantShapeIds(e)){const e=this.getShapePageBounds(n);e&&t.push(e)}return bn(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 bn(t)}getShapeContainment(e,t){const n=this.editor.getShape(e);if(!n)return null;const i=this.getShapeGeometrySnapshot(e),o=this.getShapeGeometrySnapshot(t);if(!i||!o)return null;const r=this.editor.getShapeUtil(n).getLocalBounds(n),s=this.getShapeQuerySignals(e).localToPageTransform.get()?.tryInvert();return s&&o.outlineVertices.length>0&&o.outlineVertices.every(e=>r.containsPoint(s.applyToPoint(e)))?"inside":i.bounds.intersects(o.bounds)?"intersecting":"outside"}getContainingShapeParentId(e){const t=Array.from(new Set(e));if(0===t.length)return null;const n=t.map(e=>this.editor.getShape(e)).filter(e=>!!e);if(n.length!==t.length)return null;const i=this.getPageIdForShape(n[0].id);if(!i)return null;if(n.some(e=>this.getPageIdForShape(e.id)!==i))return null;const o=new Set;for(const d of n){o.add(d.id);for(const e of this.getDescendantShapeIds(d.id))o.add(e)}let r=null,s=1/0,a=-1;const l=this.stateSignal.get().pageShapeIdsByPage.get(i)??[];for(let d=0;d<l.length;d+=1){const e=l[d];if(o.has(e))continue;const t=this.editor.getShape(e);if(!t||this.editor.isShapeHidden(t.id)||this.editor.isShapeOrAncestorLocked(t.id))continue;if(!In(t,this.editor.getShapeUtil(t)))continue;if(!n.every(e=>this.editor.canUseShapeParent(t.id,e.id)))continue;if(!n.every(e=>"inside"===this.getShapeContainment(t.id,e.id)))continue;const i=this.getShapePageBounds(t.id);if(!i)continue;const c=i.w*i.h;(!r||c<s||c===s&&d>a)&&(r=t,s=c,a=d)}return r?.id??i}getContainingShapeParentIdAtPoint(e,t){const n=Array.from(new Set(e));if(0===n.length)return null;const i=n.map(e=>this.editor.getShape(e)).filter(e=>!!e);if(i.length!==n.length)return null;const o=this.getPageIdForShape(i[0].id);if(!o)return null;if(i.some(e=>this.getPageIdForShape(e.id)!==o))return null;const r=new Set;for(const c of i){r.add(c.id);for(const e of this.getDescendantShapeIds(c.id))r.add(e)}let s=null,a=1/0,l=-1;const d=this.stateSignal.get().pageShapeIdsByPage.get(o)??[];for(let c=0;c<d.length;c+=1){const e=d[c];if(r.has(e))continue;const n=this.editor.getShape(e);if(!n||this.editor.isShapeHidden(n.id)||this.editor.isShapeOrAncestorLocked(n.id))continue;const o=this.editor.getShapeUtil(n);if(!In(n,o))continue;if(!i.every(e=>this.editor.canUseShapeParent(n.id,e.id)))continue;if(!this.editor.isPagePointInShapeClip(n.id,t))continue;const u=o.getLocalBounds(n),h=this.getShapeQuerySignals(n.id).localToPageTransform.get()?.tryInvert();if(!h||!u.containsPoint(h.applyToPoint(t)))continue;const p=this.getShapePageBounds(n.id);if(!p)continue;const g=p.w*p.h;(!s||g<a||g===a&&c>l)&&(s=n,a=g,l=c)}return s?.id??o}getContainingParentIdForShapeRecord(e){const t=(e=>{const t=new Set;let n=e;for(;n.startsWith("shape:");){const e=n;if(t.has(e))return null;t.add(e);const i=this.editor.getShape(e);if(!i)return null;n=i.parentId}return this.editor.getPage(n)?n:null})(e.parentId);if(!t)return null;const n=this.getShapeParentToPageTransformSnapshot(e.parentId,e=>this.editor.getShape(e));if(!n)return null;const i=Se(e,this.editor.getShapeUtil(e),n);let o=null,r=1/0,s=-1;const a=new Map;for(const u of G(this.editor).getAll().filter(f)){const e=a.get(u.parentId)??[];e.push(u),a.set(u.parentId,e)}for(const u of a.values())u.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));const l=[],d=new Set,c=e=>{for(const t of a.get(e)??[])d.has(t.id)||(d.add(t.id),l.push(t),c(t.id))};c(t);for(let u=0;u<l.length;u+=1){const t=l[u];if(!t||t.id===e.id||this.editor.isShapeHidden(t.id)||this.editor.isShapeOrAncestorLocked(t.id))continue;const n=this.editor.getShapeUtil(t);if(!In(t,n))continue;if(!this.editor.canUseShapeParent(t.id,e.id))continue;const a=this.editor.computeShapePageBounds(t),d=n.getLocalBounds(t),c=this.editor.computeShapeLocalToPageTransform(t).tryInvert();if(!(c&&i.outlineVertices.length>0&&i.outlineVertices.every(e=>d.containsPoint(c.applyToPoint(e)))))continue;const h=a.w*a.h;(!o||h<r||h===r&&u>s)&&(o=t,r=h,s=u)}return o?.id??t}getShapeClipAncestorIds(e){return[...this.getShapeClipAncestorIdsSignal(e).get()]}getShapeClipAncestorIdsSignal(e){return this.getShapeQuerySignals(e).clipAncestorIds}isPagePointInShapeClip(e,t){const n=this.editor.getShape(e);if(!n)return!1;for(const i of this.getShapeClipAncestorsForShape(n,e=>this.editor.getShape(e))){const e=this.editor.getShapeUtil(i).getChildClipLocalPolygons(i);if(!e||!P(e))continue;const n=this.getShapeQuerySignals(i.id).localToPageTransform.get()?.tryInvert();if(!n)return!1;if(!C(n.applyToPoint(t),e))return!1}return!0}getShapeClippedPageBounds(e){let t=this.getShapePageBounds(e);if(!t)return null;for(const n of this.getShapeClipAncestors(e)){const e=this.getShapeChildClipPageBounds(n);if(!e)continue;const i=xn(t,e);if(!i)return null;t=i}return t}getShapeClipAncestors(e){const t=this.editor.getShape(e);return t?this.getShapeClipAncestorsForShape(t,e=>this.editor.getShape(e)):[]}getShapeClipAncestorsForShape(e,t){const n=[],i=new Set;let o=e.parentId;for(;o.startsWith("shape:");){const e=o;if(i.has(e))break;i.add(e);const r=t(e);if(!r)break;const s=this.editor.getShapeUtil(r).getChildClipLocalPolygons(r);s&&P(s)&&n.push(r),o=r.parentId}return n.reverse()}getShapeChildClipPageBounds(e){const t=this.editor.getShapeUtil(e).getChildClipLocalPolygons(e),n=t?P(t):null;if(!n)return null;const i=this.getShapeQuerySignals(e.id).localToPageTransform.get();return i?(r=i,SI.FromPoints([new mI((o=n).minX,o.minY),new mI(o.maxX,o.minY),new mI(o.maxX,o.maxY),new mI(o.minX,o.maxY)].map(e=>r.applyToPoint(e)))):null;var o,r}getShapeIdsForPageSnapshot(e){return this.stateSignal.get().pageShapeIdsByPage.get(e)??[]}getChildShapeIdsSnapshot(e){return this.stateSignal.get().childShapeIdsByParent.get(e)??[]}handleStoreChange(e){const t=G(this.editor),i=this.stateAtom.get(),o=((e,t,n)=>{const i=t.diff.added.filter(f),o=t.diff.updated.filter(Qt),r=t.diff.removed.filter(f),s=t.diff.added.filter(S),a=t.diff.updated.filter(Jt),l=t.diff.removed.filter(S),d=i.length>0||r.length>0||o.some(({before:e,after:t})=>e.parentId!==t.parentId||e.index!==t.index),c=s.length>0||l.length>0||a.some(({before:e,after:t})=>e.fromId!==t.fromId||e.toId!==t.toId),u=s.length>0||l.length>0||a.length>0;if(!d&&!u)return e;const h={pageShapeIdsByPage:new Map(e.pageShapeIdsByPage),childShapeIdsByParent:new Map(e.childShapeIdsByParent),pageIdByShape:new Map(e.pageIdByShape),bindingById:new Map(e.bindingById),bindingIdsByFromShape:new Map(e.bindingIdsByFromShape),bindingIdsByToShape:new Map(e.bindingIdsByToShape),relatedBindingIdsByShape:new Map(e.relatedBindingIdsByShape)};let g=!1;if(d){const t=e=>{const t=n(e);return f(t)?t.index:void 0},s=new Set,a=e=>{let t=e;const i=new Set;for(;t&&!i.has(t);){i.add(t);const e=n(t);if(!e)return null;if(p(e))return e.id;if(!f(e))return null;t=e.parentId}return null};for(const n of r){Zt(h.childShapeIdsByParent,n.parentId,n.id);const t=e.pageIdByShape.get(n.id);t&&s.add(t)}for(const{before:n,after:i}of o){if(n.parentId===i.parentId&&n.index===i.index)continue;Zt(h.childShapeIdsByParent,n.parentId,n.id),Gt(h.childShapeIdsByParent,i.parentId,i,t);const o=e.pageIdByShape.get(n.id);o&&s.add(o);const r=a(i.parentId);r&&s.add(r)}for(const e of i)Gt(h.childShapeIdsByParent,e.parentId,e,t);for(const e of i){const t=a(e.parentId);t&&s.add(t)}if(s.size>0){const t=new Map(e.pageShapeIdsByPage),i=new Map(e.pageIdByShape);for(const[n,r]of e.pageIdByShape)s.has(r)&&i.delete(n);const o=(e,t)=>{const r=[];for(const s of h.childShapeIdsByParent.get(t)??[])n(s)&&(r.push(s),i.set(s,e),r.push(...o(e,s)));return r};for(const e of s){const n=o(e,e);n.length>0?t.set(e,n):t.delete(e)}h.pageShapeIdsByPage=t,h.pageIdByShape=i}g=!0}if(u){for(const e of l)g=h.bindingById.delete(e.id)||g;if(c){for(const e of l)g=Yt(h.bindingIdsByFromShape,e.fromId,e.id)||g,g=Yt(h.bindingIdsByToShape,e.toId,e.id)||g,g=Yt(h.relatedBindingIdsByShape,e.fromId,e.id)||g,g=Yt(h.relatedBindingIdsByShape,e.toId,e.id)||g;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(g=Yt(h.bindingIdsByFromShape,e.fromId,e.id)||g,g=Yt(h.bindingIdsByToShape,e.toId,e.id)||g,g=Yt(h.relatedBindingIdsByShape,e.fromId,e.id)||g,g=Yt(h.relatedBindingIdsByShape,e.toId,e.id)||g)}for(const e of s)h.bindingById.set(e.id,e),g=!0;for(const{after:e}of a)h.bindingById.set(e.id,e),g=!0;if(c){for(const e of s)g=Vt(h.bindingIdsByFromShape,e.fromId,e,"from",e=>h.bindingById.get(e))||g,g=Vt(h.bindingIdsByToShape,e.toId,e,"to",e=>h.bindingById.get(e))||g,g=Vt(h.relatedBindingIdsByShape,e.fromId,e,"related",e=>h.bindingById.get(e))||g,g=Vt(h.relatedBindingIdsByShape,e.toId,e,"related",e=>h.bindingById.get(e))||g;for(const{before:e,after:t}of a)e.fromId===t.fromId&&e.toId===t.toId||(g=Vt(h.bindingIdsByFromShape,t.fromId,t,"from",e=>h.bindingById.get(e))||g,g=Vt(h.bindingIdsByToShape,t.toId,t,"to",e=>h.bindingById.get(e))||g,g=Vt(h.relatedBindingIdsByShape,t.fromId,t,"related",e=>h.bindingById.get(e))||g,g=Vt(h.relatedBindingIdsByShape,t.toId,t,"related",e=>h.bindingById.get(e))||g)}}return g?h:e})(i,e,e=>t.get(e));o!==i&&n(()=>{this.stateAtom.set(o),this.updateCachedBindingSignals(e,o)});for(const n of(e=>e.diff.removed.filter(f).map(e=>e.id))(e))this.shapeQuerySignals.delete(n)}updateCachedBindingSignals(e,t){const n=new Set,i=new Set,o=new Set,r=e=>{S(e)&&(n.add(e.fromId),i.add(e.toId),o.add(e.fromId),o.add(e.toId))};for(const s of e.diff.added)r(s);for(const s of e.diff.removed)r(s);for(const s of e.diff.updated)r(s.before),r(s.after);for(const s of n)this.bindingsFromShapeSignals.get(s)?.set(this.getBindingsFromState(t,s));for(const s of i)this.bindingsToShapeSignals.get(s)?.set(this.getBindingsToState(t,s));for(const s of o)this.bindingsForShapeSignals.get(s)?.set(this.getBindingsForState(t,s))}getShapeLocalToPageTransformSnapshot(e,t){const n=[],i=new Set;let o=e;for(;o;){if(i.has(o.id))return;if(i.add(o.id),n.push(o),o.parentId.startsWith("page:")){if(!this.editor.getPage(o.parentId))return;break}if(o=t(o.parentId),!o)return}let r=yI.Identity();for(let s=n.length-1;s>=0;s-=1){const e=n[s];e&&(r=ue(e,this.editor.getShapeUtil(e),r))}return r}getShapeParentToPageTransformSnapshot(e,t){if(e.startsWith("page:"))return this.editor.getPage(e)?yI.Identity():void 0;const n=t(e);return n?this.getShapeLocalToPageTransformSnapshot(n,t):void 0}getShapeQuerySignals(e){let t=this.shapeQuerySignals.get(e);if(!t){const n=l(`editor.query.shapePositionedBounds.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(t)return this.editor.getShapeUtil(t).getPositionedBounds(t)},{isEqual:dn}),i=l(`editor.query.shapeLocalToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();return t?this.getShapeLocalToPageTransformSnapshot(t,e=>this.editor.getShapeSignal(e).get()):void 0},{isEqual:pn}),o=l(`editor.query.shapeGeometry.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(!t)return;const n=this.getShapeParentToPageTransformSnapshot(t.parentId,e=>this.editor.getShapeSignal(e).get());return n?Se(t,this.editor.getShapeUtil(t),n):void 0},{isEqual:gn});t={positionedBounds:n,geometry:o,localToPageTransform:i,positionedToPageTransform:l(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();if(!t)return;const n=this.getShapeParentToPageTransformSnapshot(t.parentId,e=>this.editor.getShapeSignal(e).get());return n?he(t,this.editor.getShapeUtil(t),n):void 0},{isEqual:pn}),pageBounds:l(`editor.query.shapePageBounds.${e}`,()=>o.get()?.bounds,{isEqual:dn}),clipAncestorIds:l(`editor.query.shapeClipAncestorIds.${e}`,()=>{const t=this.editor.getShapeSignal(e).get();return t?this.getShapeClipAncestorsForShape(t,e=>this.editor.getShapeSignal(e).get()).map(e=>e.id):[]},{isEqual:Xt})},this.shapeQuerySignals.set(e,t)}return t}getShapeGeometrySnapshot(e){return this.getShapeQuerySignals(e).geometry.get()}getShapePageBoundsSignal(e){return this.getShapeQuerySignals(e).pageBounds}getShapeLocalToPageTransformSignal(e){return this.getShapeQuerySignals(e).localToPageTransform}getShapeGeometry(e){return(e=>{if(e)return{bounds:e.bounds.clone(),center:e.center.clone(),corners:e.corners.map(e=>e.clone()),outlineVertices:e.outlineVertices.map(e=>e.clone())}})(this.getShapeGeometrySnapshot(e))}getShapeLocalToPageTransform(e){return yn(this.getShapeLocalToPageTransformSignal(e).get())}getShapeParentToPageTransform(e){return e.startsWith("page:")?this.editor.getPage(e)?yI.Identity():void 0:yn(this.getShapeQuerySignals(e).localToPageTransform.get())}getShapePageToParentTransform(e){return this.getShapeParentToPageTransform(e)?.tryInvert()??void 0}getShapePositionedToPageTransform(e){return yn(this.getShapeQuerySignals(e).positionedToPageTransform.get())}getShapePageBounds(e){return fn(this.getShapePageBoundsSignal(e).get())??void 0}getShapePositionedBounds(e){return fn(this.getShapeQuerySignals(e).positionedBounds.get())??void 0}getShapePageCenter(e){return mn(this.getShapeGeometrySnapshot(e)?.center)??void 0}getShapePageCorners(e){return Sn(this.getShapeGeometrySnapshot(e)?.corners)}getShapePageOutlineVertices(e){return Sn(this.getShapeGeometrySnapshot(e)?.outlineVertices)}getSelectionPageOutlineVertices(){return Sn(this.selectionPageOutlineVerticesSignal.get())??[]}getSelectionPageBounds(){return fn(this.selectionPageBoundsSignal.get())??null}getSelectionFrameBounds(){return fn(this.selectionFrameBoundsSignal.get())??null}getSelectionRotation(){return this.selectionRotationSignal.get()}getSelectionHasRotation(){return this.selectionHasRotationSignal.get()}getSelectionRotationCenter(){return mn(this.selectionRotationCenterSignal.get())??null}getSelectionHasCompatibleRotation(){return this.selectionHasCompatibleRotationSignal.get()}getSelectionAnchorPagePoint(){return mn(this.selectionAnchorPagePointSignal.get())??null}getBinding(e){return this.stateSignal.get().bindingById.get(e)}getBindings(){return Array.from(this.stateSignal.get().bindingById.values()).sort(qt)}getBindingIdsFromShape(e){return this.stateSignal.get().bindingIdsByFromShape.get(e)??[]}getBindingIdsToShape(e){return this.stateSignal.get().bindingIdsByToShape.get(e)??[]}getBindingIdsForShape(e){return this.stateSignal.get().relatedBindingIdsByShape.get(e)??[]}getBindingsFromShape(e){const t=this.getDraftBindingIndex();return t?[...t.bindingsFromShape.get(e)??[]]:[...this.getBindingsFromShapeSignal(e).get()]}getBindingsFromShapeSignal(e){let t=this.bindingsFromShapeSignals.get(e);return t||(t=a(`editor.query.bindingsFromShape.${e}`,this.getBindingsFromState(this.stateAtom.__unsafe__getWithoutCapture(),e),{isEqual:hn}),this.bindingsFromShapeSignals.set(e,t)),t}getBindingsToShape(e){const t=this.getDraftBindingIndex();return t?[...t.bindingsToShape.get(e)??[]]:[...this.getBindingsToShapeSignal(e).get()]}getBindingsToShapeSignal(e){let t=this.bindingsToShapeSignals.get(e);return t||(t=a(`editor.query.bindingsToShape.${e}`,this.getBindingsToState(this.stateAtom.__unsafe__getWithoutCapture(),e),{isEqual:hn}),this.bindingsToShapeSignals.set(e,t)),t}getBindingsForShape(e){const t=this.getDraftBindingIndex();return t?[...t.bindingsForShape.get(e)??[]]:[...this.getBindingsForShapeSignal(e).get()]}getBindingsForShapeSignal(e){let t=this.bindingsForShapeSignals.get(e);return t||(t=a(`editor.query.bindingsForShape.${e}`,this.getBindingsForState(this.stateAtom.__unsafe__getWithoutCapture(),e),{isEqual:hn}),this.bindingsForShapeSignals.set(e,t)),t}getBindingsFromState(e,t){return this.getBindingsForIds(e,e.bindingIdsByFromShape.get(t))}getBindingsToState(e,t){return this.getBindingsForIds(e,e.bindingIdsByToShape.get(t))}getBindingsForState(e,t){return this.getBindingsForIds(e,e.relatedBindingIdsByShape.get(t))}getBindingsForIds(e,t){return t&&0!==t.length?t.map(t=>e.bindingById.get(t)).filter(e=>!!e):[]}getDraftBindingIndex(){const e=G(this.editor),t=e.getActiveAtomicOperationRevision();if(null===t)return null;if(this.draftBindingIndex?.revision===t)return this.draftBindingIndex;const n=e.getActiveAtomicOperationSnapshot().filter(S),i=new Map,o=new Map,r=new Map,s=(e,t,n)=>{const i=e.get(t);i?i.push(n):e.set(t,[n])};for(const a of n)s(i,a.fromId,a),s(o,a.toId,a),s(r,a.fromId,a),a.toId!==a.fromId&&s(r,a.toId,a);for(const a of[i,o,r])for(const e of a.values())e.sort(qt);return this.draftBindingIndex={revision:t,bindingsFromShape:i,bindingsToShape:o,bindingsForShape:r},this.draftBindingIndex}},jI=class{entries;cellSize;cells=new Map;order=new Map;constructor(e){this.entries=e,this.cellSize=(e=>{if(0===e.length)return 256;let t=0;for(const n of e)t+=Math.max(n.queryBounds.w,n.queryBounds.h);return Math.max(16,Math.round(t/e.length)||256)})(e);for(let t=0;t<e.length;t+=1){const n=e[t];n&&(this.order.set(n,t),this.insert(n))}}cellKey(e,t){return`${e}:${t}`}insert(e){const t=Math.floor(e.queryBounds.minX/this.cellSize),n=Math.floor(e.queryBounds.minY/this.cellSize),i=Math.floor(e.queryBounds.maxX/this.cellSize),o=Math.floor(e.queryBounds.maxY/this.cellSize);for(let r=n;r<=o;r+=1)for(let n=t;n<=i;n+=1){const t=this.cellKey(n,r),i=this.cells.get(t);i?i.push(e):this.cells.set(t,[e])}}search(e){const t=Math.floor(e.minX/this.cellSize),n=Math.floor(e.minY/this.cellSize),i=Math.floor(e.maxX/this.cellSize),o=Math.floor(e.maxY/this.cellSize);if((i-t+1)*(o-n+1)>this.entries.length)return this.entries.filter(t=>t.queryBounds.intersects(e));const r=new Set,s=[];for(let a=n;a<=o;a+=1)for(let n=t;n<=i;n+=1){const t=this.cells.get(this.cellKey(n,a));if(t)for(const n of t)r.has(n)||(r.add(n),n.queryBounds.intersects(e)&&s.push(n))}return s.length>1&&s.sort((e,t)=>(this.order.get(e)??0)-(this.order.get(t)??0)),s}},VI=class{editor;queries;pageIndexSignals=new Map;constructor(e,t){this.editor=e,this.queries=t}getShapesInBounds(e,t){return this.getShapeIdsInBounds(e,t).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getShapeIdsInBounds(e,t){return this.getPageIndex(t?.pageId).search(e).filter(t=>t.shapeBounds.intersects(e)).map(e=>e.shapeId)}getShapesInViewport(e,t){return this.getShapesInBounds(e,t)}getShapeIdsInViewport(e,t){return this.getShapeIdsInBounds(e,t)}getShapeAtPoint(e,t){return this.getShapesAtPoint(e,t)[0]??null}getShapesAtPoint(e,t){const n=this.getPageIndex(t?.pageId).search((e=>new SI(e.x-.5,e.y-.5,1,1))(e)),i=[];for(let o=n.length-1;o>=0;o-=1){const r=n[o];if(!r?.pointHitTestBounds.containsPoint(e))continue;const s=this.editor.getShape(r.shapeId);if(!s)continue;if(t?.filter&&!t.filter(s))continue;const a=this.editor.getShapeUtil(s),l=this.queries.getShapeParentToPageTransform(s.parentId);if(!l)continue;const d=fe(s,e,a,l),c={editor:this.editor,pagePoint:e,positionedPoint:d};("bindingTarget"===t?.hitTest?a.hitTestBindingTarget(s,d,c):a.hitTest(s,d,c))&&i.push(s)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,o=((e,t,n)=>SI.FromPoints([e,t]).expand(Math.max(.5,n)))(e,t,i),r=this.getPageIndex(n?.pageId).search(o),s=[];for(let a=r.length-1;a>=0;a-=1){const o=r[a];if(!o)continue;const l=this.queries.getShapeClippedPageBounds(o.shapeId);if(!l||!wn(e,t,l.expand(i)))continue;if(!this.doesLineSegmentIntersectShapeClip(o.shapeId,e,t,i))continue;const d=this.editor.getShape(o.shapeId);if(!d)continue;if(n?.filter&&!n.filter(d))continue;const c=this.editor.getShapeUtil(d),u=this.queries.getShapeParentToPageTransform(d.parentId);if(!u)continue;const h=fe(d,e,c,u),p=fe(d,t,c,u),g=this.queries.getShapePositionedToPageTransform(d.id)?.tryInvert(),f=g?i*g.getMaximumLinearScale():i;c.hitTestLineSegment(d,{editor:this.editor,pageStart:e,pageEnd:t,pageMargin:i,positionedStart:h,positionedEnd:p,positionedMargin:f})&&s.push(d)}return s}doesLineSegmentIntersectShapeClip(e,t,n,i){for(const o of this.queries.getShapeClipAncestorIds(e)){const e=this.editor.getShape(o);if(!e)return!1;const r=this.editor.getShapeUtil(e).getChildClipLocalPolygons(e);if(!r)continue;const s=this.editor.computeShapeLocalToPageTransform(e).tryInvert();if(!s)return!1;const a=i*Math.sqrt(s.a*s.a+s.b*s.b+s.c*s.c+s.d*s.d),l=s.applyToPoint(t),d=s.applyToPoint(n);if(!r.some(e=>T(l,d,e,a)))return!1}return!0}getPageIndexSignal(e){let t=this.pageIndexSignals.get(e);return t||(t=l(`editor.spatialIndex.page.${e}`,()=>{const t=this.queries.stateSignal.get().pageShapeIdsByPage.get(e)??[],n=[];for(const e of t){const t=this.editor.getShapeSignal(e).get();if(!t)continue;const i=this.editor.getShapeUtil(t),o=this.queries.getShapePageBoundsSignal(e).get();if(!o)continue;const r=this.queries.getShapePositionedToPageTransform(e);if(!r)continue;const s=Pn(i.getPointHitTestBounds(t,{editor:this.editor}),r),a=SI.FromPoints([new mI(o.minX,o.minY),new mI(o.maxX,o.maxY),new mI(s.minX,s.minY),new mI(s.maxX,s.maxY)]);n.push({shapeId:e,shapeBounds:o,queryBounds:a,pointHitTestBounds:s})}return new jI(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.getCurrentPageId()){return this.getPageIndexSignal(e).get()}},GI=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],ZI={corner:0,edge_midpoint:1,center:2,custom:3},QI=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],JI=["top_left","top_right","bottom_right","bottom_left"],ev=["free","aspect_ratio_locked"],tv=["free"],nv=["aspect_ratio_locked"],iv=class{editor;constructor(e){this.editor=e}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createHandleSnapshot({context:e,currentPagePoint:t,allowSelfSnap:n=!1,excludedShapeIds:i=[]}){const o=this.editor.getShape(e.shapeId),r=new Set(this.editor.getShapeIdsIncludingDescendants([e.shapeId]));this.collectBindingDrivenExcludedShapeIds([e.shapeId],r);for(const c of i)r.add(c);const s=[],a=[],l=this.getSnapScopeParentId([e.shapeId]),d=this.getCandidateShapeIds({excludedShapeIds:r,scopeParentId:l});o&&n&&this.collectSelfHandleSnapGeometry({shape:o,context:e,currentPagePoint:t,points:s,outlines:a});for(const c of d){const e=this.editor.getShape(c);e&&this.collectHandleSnapGeometry({shape:e,points:s,outlines:a})}return{points:s,outlines:a,scopeParentId:l,candidateShapeIds:d}}collectHandleSnapGeometry({shape:e,points:t,outlines:n}){const i=this.editor.getShapeUtil(e);if(!i.canSnap(e,{editor:this.editor}))return;const o=this.editor.getShapeClippedPageBounds(e.id);if(!o)return;const r=this.editor.computeShapeLocalToPageTransform(e),s=i.getHandleSnapGeometry(e);for(const c of s.points??[]){const n=Mi(c),i=r.applyToPoint(n.point);this.editor.isPagePointInShapeClip(e.id,i)&&t.push({id:`${e.id}:point:${t.length}`,nodeId:e.id,point:i,kind:n.kind,weight:n.weight})}const a=s.outline;if(null===a)return;const l=this.editor.getShapeClipAncestorIds(e.id).length>0?Yn(o):(a??(d=i.getLocalBounds(e),[new mI(d.minX,d.minY),new mI(d.maxX,d.minY),new mI(d.maxX,d.maxY),new mI(d.minX,d.maxY)])).map(e=>r.applyToPoint(e));var d;l.length>0&&n.push({id:e.id,points:l})}collectSelfHandleSnapGeometry({shape:e,context:t,currentPagePoint:n,points:i,outlines:o}){const r=this.editor.getShapeUtil(e);if(!r.canSnap(e,{editor:this.editor}))return;const s=this.editor.getShapeClippedPageBounds(e.id);if(!s)return;const a=r.getHandleSnapGeometry(e),l=this.editor.computeShapeLocalToPageTransform(e),d={...t,currentPagePoint:n.clone()};for(const h of a.getSelfSnapPoints?.(d)??[]){const t=Mi(h),n=l.applyToPoint(t.point);this.editor.isPagePointInShapeClip(e.id,n)&&i.push({id:`${e.id}:self-point:${i.length}`,nodeId:e.id,point:n,kind:t.kind,weight:t.weight})}const c=a.getSelfSnapOutline?.(d)??null;if(!c)return;const u=this.editor.getShapeClipAncestorIds(e.id).length>0?Yn(s):c.map(e=>l.applyToPoint(e));u.length>0&&o.push({id:e.id,points:u})}createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=Array.from(e),i=new Set(this.editor.getShapeIdsIncludingDescendants(n));this.collectBindingDrivenExcludedShapeIds(n,i);const o=[],r=[],s={rotation:t.rotation,rotationCenter:t.rotationCenter},a=this.getSnapScopeParentId(n),l=this.getCandidateShapeIds({excludedShapeIds:i,scopeParentId:a});for(const d of l){const e=this.editor.getShape(d);if(!e)continue;const n=this.editor.getShapeUtil(e);if(!n.canSnap(e,{editor:this.editor}))continue;const i=this.editor.getShapeClippedPageBounds(e.id);if(!i)continue;const a=(this.editor.getShapeClipAncestorIds(e.id).length>0?Yn(i):this.editor.getShapePageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():Ii(e,s));if(0===a.length)continue;const l=SI.FromPoints(a);r.push({id:e.id,bounds:l});const c=n.getBoundsSnapGeometry(e).points,u=[];if(void 0===c)Un(l).forEach((e,t)=>{u.push({point:e,kind:GI[t]??"custom"})});else{const n=this.editor.computeShapeLocalToPageTransform(e);for(const i of c){const o=Mi(i),r=n.applyToPoint(o.point);this.editor.isPagePointInShapeClip(e.id,r)&&u.push({point:0===t.rotation?r:Ii(r,s),kind:o.kind,weight:o.weight})}}u.forEach((t,n)=>{o.push({id:`${e.id}:${n}`,nodeId:e.id,point:t.point,kind:t.kind,weight:t.weight})})}return{points:o,pointIndex:Gn(o),nodes:r,coordinateSpace:{rotation:t.rotation,rotationCenter:t.rotationCenter.clone()},scopeParentId:a,candidateShapeIds:l}}collectBindingDrivenExcludedShapeIds(e,t){const n=new Set,i=[...e];for(;i.length>0;){const e=i.pop();if(!e||n.has(e))continue;n.add(e);const o=this.editor.getShape(e);if(o)for(const n of this.editor.getBindingsForShape(e)){const r=n.fromId===e?"from":n.toId===e?"to":null;if(!r)continue;const s=this.editor.getBindingUtil(n).getGeometryDependentShapeIds?.(this.editor,n,{shape:o,role:r})??[];for(const e of s)for(const n of this.editor.getShapeIdsIncludingDescendants([e]))t.has(n)||(t.add(n),i.push(n))}}}getSnapScopeParentId(e){let t=null;for(const n of e){const e=this.editor.getShape(n);if(e)if(t){if(e.parentId!==t)return this.editor.getCurrentPageId()}else t=e.parentId}return t??this.editor.getCurrentPageId()}getCandidateShapeIds({excludedShapeIds:e,scopeParentId:t}){const n=this.editor.getCurrentPageId(),i=this.editor.renderViewportPageBoundsSignal.get(),o=new Set;if(t?.startsWith("shape:")){const e=this.editor.getShape(t);e&&this.editor.getShapeUtil(e).canSnapChildrenToSelf(e)&&o.add(e.id)}const r=t??n;for(const s of this.editor.getChildShapeIds(r))o.add(s);return(null===i?Array.from(o):this.editor.getShapeIdsInBounds(i,{pageId:n}).filter(e=>o.has(e))).filter(n=>{if(e.has(n))return!1;const o=this.editor.getShape(n);if(!o||o.parentId!==r)return n===t;const s=this.editor.getShapeClippedPageBounds(n);return!!s&&(!i||s.intersects(i))})}},ov=class{gapCache=new WeakMap;_indicatorsSignal=a("editor.snapIndicators",[]);indicatorsSignal=this._indicatorsSignal;activeSignal=l("editor.snapIndicatorsActive",()=>this._indicatorsSignal.get().length>0);snapshots;axisSnapMemory={x:null,y:null};constructor(e){this.snapshots=new iv(e)}setIndicators(e){const t=e.map(xi);di(this._indicatorsSignal.get(),t)||this._indicatorsSignal.set(t)}clearIndicators(){this._indicatorsSignal.get().length>0&&this._indicatorsSignal.set([]),this.clearAxisSnapMemory()}clearAxisSnapMemory(){this.axisSnapMemory.x=null,this.axisSnapMemory.y=null}getSwitchDistance(e){return Math.min(.25*e,2)}getReleaseThreshold(e){return 1.5*e}updateAxisSnapMemory(e,t){this.axisSnapMemory[e]=t?{type:t.type,id:t.id,candidatePointIds:"points"===t.type?t.candidatePointIds:void 0}:null}writeDebugState(e){const t=globalThis;t.__LAND_LAST_SNAP_DEBUG__=e,t.__LAND_SNAP_DEBUG__&&t.console?.debug?.("[land:snap]",e)}getNow(){return globalThis.performance?.now?.()??Date.now()}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=this.snapshots.createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t});return this.gapCache.set(n,{x:oi(n.nodes,"x"),y:oi(n.nodes,"y")}),n}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.snapshots.createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t})}createHandleSnapshot(e){return this.snapshots.createHandleSnapshot(e)}snapTranslate(e){const t=this.getNow(),n=_n(e.initialSelectionBounds,e.dragDelta),i=(o=Un(e.initialSelectionBounds),r=e.dragDelta,o.map(e=>e.add(r)));var o,r;const s=this.gapCache.get(e.snapshot)??{x:oi(e.snapshot.nodes,"x"),y:oi(e.snapshot.nodes,"y")},a=this.getReleaseThreshold(e.threshold),l=this.getSwitchDistance(e.threshold),d=this.axisSnapMemory.x,c=this.axisSnapMemory.y,u={candidatePointCount:0,matchedPointCount:0},h="y"===e.lockedAxis?null:li(ni("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:GI,switchDistance:l,stats:u}),ai("x",n,s.x,e.threshold,{previousSnapId:"gaps"===d?.type?d.id:null,releaseThreshold:a,switchDistance:l}),{previousSnap:d,switchDistance:l}),p="x"===e.lockedAxis?null:li(ni("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:GI,switchDistance:l,stats:u}),ai("y",n,s.y,e.threshold,{previousSnapId:"gaps"===c?.type?c.id:null,releaseThreshold:a,switchDistance:l}),{previousSnap:c,switchDistance:l}),g=new mI(h?.nudge??0,p?.nudge??0),f=[];return"points"===h?.type?f.push(...hi("x",h,g,e.snapshot.coordinateSpace)):"gaps"===h?.type&&f.push(bi(h,e.snapshot.coordinateSpace,g)),"points"===p?.type?f.push(...hi("y",p,g,e.snapshot.coordinateSpace)):"gaps"===p?.type&&f.push(bi(p,e.snapshot.coordinateSpace,g)),this.setIndicators(f),this.updateAxisSnapMemory("x",h),this.updateAxisSnapMemory("y",p),this.writeDebugState({operation:"translate",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:u.candidatePointCount,candidateGapCount:("y"===e.lockedAxis?0:s.x.length)+("x"===e.lockedAxis?0:s.y.length),matchedPointCount:u.matchedPointCount,xSnapId:h?.id??null,ySnapId:p?.id??null,indicatorCount:f.length}),{nudge:g,indicators:f}}snapResize(e){const t=this.getNow(),n=Bn({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),i=ii(n,e.resizedSelectionBounds),o="top"===n||"bottom"===n,r="left"===n||"right"===n,s=this.getReleaseThreshold(e.threshold),a=this.getSwitchDistance(e.threshold),l=this.axisSnapMemory.x,d=this.axisSnapMemory.y,c={candidatePointCount:0,matchedPointCount:0},u=o?null:ni("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:s,switchDistance:a,stats:c}),h=r?null:ni("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:s,switchDistance:a,stats:c}),p={x:null!==u,y:null!==h},g=new mI(u?.nudge??0,h?.nudge??0);if(e.isAspectRatioLocked&&Tn(f=n)!==Mn(f)&&En(f)!==An(f)&&(0!==g.x||0!==g.y)){const t=u&&h?Math.abs(g.x)<Math.abs(g.y)?"x":"y":u?"x":"y",i=0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h;"x"===t?(p.y=!1,g.y=g.x/i,"bottom_left"!==n&&"top_right"!==n||(g.y=-g.y)):(p.x=!1,g.x=g.y*i,"bottom_left"!==n&&"top_right"!==n||(g.x=-g.x))}var f;const m=function(e,t){const n=Bn({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY});let i=e.resizedSelectionBounds.minX,o=e.resizedSelectionBounds.maxX,r=e.resizedSelectionBounds.minY,s=e.resizedSelectionBounds.maxY;e.isResizingFromCenter?(Tn(n)?(i+=t.x,o-=t.x):Mn(n)&&(i-=t.x,o+=t.x),En(n)?(r+=t.y,s-=t.y):An(n)&&(r-=t.y,s+=t.y)):(Tn(n)?i+=t.x:Mn(n)&&(o+=t.x),En(n)?r+=t.y:An(n)&&(s+=t.y));const a=(({minX:e,minY:t,maxX:n,maxY:i})=>{const o=Math.min(e,n),r=Math.min(t,i),s=Math.max(e,n),a=Math.max(t,i);return new SI(o,r,Math.max(1,s-o),Math.max(1,a-r))})({minX:i,minY:r,maxX:o,maxY:s});if(!e.isAspectRatioLocked){const t=(({startBounds:e,bounds:t,handleId:n,scaleX:i,scaleY:o,isResizingFromCenter:r=!1})=>{const s=Rn({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:r}),a=Rn({axis:"y",startBounds:e,bounds:t,handleId:n,scale:o,isResizingFromCenter:r});return{scaleX:Tn(n)||Mn(n)?s*(t.w/Math.max(1,e.w)):i??1,scaleY:En(n)||An(n)?a*(t.h/Math.max(1,e.h)):o??1}})({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter});return{bounds:a,scaleX:t.scaleX,scaleY:t.scaleY}}return $n({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,aspectRatio:0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h,isResizingFromCenter:e.isResizingFromCenter,scaleX:e.scaleX,scaleY:e.scaleY})}(e,g),{bounds:S}=m,y=ii("any",S),b=[];if(p.x){const t=ni("x",y,e.snapshot.pointIndex,1e-8,{stats:c});t&&b.push(...Si("x",t,mI.Zero(),e.snapshot.coordinateSpace,S,e.snapshot.nodes))}if(p.y){const t=ni("y",y,e.snapshot.pointIndex,1e-8,{stats:c});t&&b.push(...Si("y",t,mI.Zero(),e.snapshot.coordinateSpace,S,e.snapshot.nodes))}return this.setIndicators(b),this.updateAxisSnapMemory("x",p.x?u:null),this.updateAxisSnapMemory("y",p.y?h:null),this.writeDebugState({operation:"resize",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:c.candidatePointCount,candidateGapCount:0,matchedPointCount:c.matchedPointCount,xSnapId:p.x?u?.id??null:null,ySnapId:p.y?h?.id??null:null,indicatorCount:b.length}),{nudge:g,bounds:S,scaleX:m.scaleX,scaleY:m.scaleY,indicators:b}}snapHandle(e){const t=this.getNow();if("none"===e.mode)return this.clearIndicators(),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null;const n="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return n?(this.setIndicators(n.indicators),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:n.indicators.length,indicatorCount:n.indicators.length}),n):(this.clearIndicators(),this.writeDebugState({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null)}snapHandlePoint(e){const t=Ei(e);let n=null,i=null,o=e.threshold*e.threshold;for(const a of t)for(const t of e.snapshot.points){const e=a.dist2(t.point);e>o||(o=e,n=t.point,i=a)}if(!n)for(const a of t)for(const t of e.snapshot.outlines){const e=jn(a,t.points);!e||e.distanceSquared>o||(o=e.distanceSquared,n=e.point,i=a)}if(!n||!i)return null;const r=n.sub(i);return{snappedPagePoint:e.pagePoint.add(r),nudge:r,indicators:[(s=n,{id:mi("x",[s,s],[s]),type:"points",axis:"x",line:[s.clone(),s.clone()],points:[s.clone()],rotation:0,rotationCenter:s.clone()})]};var s}snapHandleAlign(e){const t=Ei(e);let n=null,i=null,o=null,r=null,s=e.threshold,a=e.threshold;for(const u of t)for(const t of e.snapshot.points){const e=Math.abs(t.point.x-u.x);e<=s&&(s=e,n=t.point,o=u);const l=Math.abs(t.point.y-u.y);l<=a&&(a=l,i=t.point,r=u)}if(!n&&!i)return null;const l=new mI(n&&o?n.x-o.x:0,i&&r?i.y-r.y:0),d=e.pagePoint.add(l),c=[];return n&&o&&c.push(yi("x",o.add(l),n)),i&&r&&c.push(yi("y",r.add(l),i)),{snappedPagePoint:d,nudge:l,indicators:c}}},rv=class{beforeDelete=new Map;afterDelete=new Map;registerBeforeDeleteHandler(e,t){return this.register(this.beforeDelete,e,t)}registerAfterDeleteHandler(e,t){return this.register(this.afterDelete,e,t)}runBeforeDelete(e,t,n){if(0!==t.length)for(const i of this.beforeDelete.get(e)??[])i(t,n)}runAfterDelete(e,t,n){if(0!==t.length)for(const i of this.afterDelete.get(e)??[])i(t,n)}register(e,t,n){const i=e.get(t);return i?i.push(n):e.set(t,[n]),()=>{const i=e.get(t);if(!i)return;const o=i.indexOf(n);o>=0&&i.splice(o,1)}}},sv=class{editor;constructor(e){this.editor=e}canAlign(){return this.canLayoutSelection(2)}align(e,t="user"){const n=this.getAlignableEntries();if(n.length<2)return!1;const i=this.getPageToParentTransform(n[0].shape.parentId);if(!i)return!1;const o=SI.FromPoints(n.flatMap(e=>[new mI(e.bounds.minX,e.bounds.minY),new mI(e.bounds.maxX,e.bounds.maxY)])),r=n.map(({shape:t,bounds:n})=>{let r=0,s=0;switch(e){case"left":r=o.minX-n.minX;break;case"right":r=o.maxX-n.maxX;break;case"horizontal-center":r=o.center.x-n.center.x;break;case"top":s=o.minY-n.minY;break;case"bottom":s=o.maxY-n.maxY;break;case"vertical-center":s=o.center.y-n.center.y}const a=this.pageDeltaToParentDelta(i,new mI(r,s));return{id:t.id,x:t.x+a.x,y:t.y+a.y}});return this.editor.commands.updateShapes(r,{source:t}),!0}canDistribute(){return this.canLayoutSelection(3)}distribute(e,t="user"){const n=this.getAlignableEntries();if(n.length<3)return!1;const i=this.getPageToParentTransform(n[0].shape.parentId);if(!i)return!1;const o="horizontal"===e,r=e=>o?e.w:e.h,s=e=>o?e.minX:e.minY,a=o?"x":"y",l=[...n].sort((e,t)=>e.bounds.center[a]-t.bounds.center[a]),d=l[0].bounds,c=l[l.length-1].bounds,u=((o?c.maxX:c.maxY)-s(d)-l.reduce((e,t)=>e+r(t.bounds),0))/(l.length-1);let h=s(d);const p=l.map(({shape:e,bounds:t},n)=>{const a=0===n||n===l.length-1?s(t):h,d=a-s(t);h=a+r(t)+u;const c=this.pageDeltaToParentDelta(i,o?new mI(d,0):new mI(0,d));return{id:e.id,x:e.x+c.x,y:e.y+c.y}});return this.editor.commands.updateShapes(p,{source:t}),!0}getCurrentPageBounds(e=this.editor.getCurrentPageId()){return this.boundsOfShapeIds(this.editor.getCurrentPageShapeIds())}zoomToBounds(e,t){const n=this.editor.viewportScreenSizeSignal.get();if(n.w<=0||n.h<=0||!it(e))return!1;if(e.w<=0&&e.h<=0)return!1;const i=t?.padding??64,o=Math.max(1,n.w-2*i),r=Math.max(1,n.h-2*i),s=Ve(Math.min(e.w>0?o/e.w:1/0,e.h>0?r/e.h:1/0,t?.maxZoom??1)),a=e.center;return this.editor.setCamera({x:a.x-n.w/2/s,y:a.y-n.h/2/s,z:s},{source:t?.source??"user"}),!0}zoomToFit(e){const t=this.getCurrentPageBounds();return!!t&&this.zoomToBounds(t,e)}zoomToSelection(e){const t=this.boundsOfShapeIds(this.editor.getSelectedShapeIds());return!!t&&this.zoomToBounds(t,e)}boundsOfShapeIds(e){const t=[];for(const i of e){const e=this.editor.getShapePageBounds(i);e&&it(e)&&t.push(new mI(e.minX,e.minY),new mI(e.maxX,e.maxY))}if(0===t.length)return null;const n=SI.FromPoints(t);return it(n)?n:null}canLayoutSelection(e){const t=this.getAlignableEntries();return t.length>=e&&null!==this.getPageToParentTransform(t[0].shape.parentId)}getAlignableEntries(){const e=this.editor.getSelectedShapeIds().map(e=>this.editor.getShape(e)).filter(e=>!!e&&!this.editor.isShapeOrAncestorLocked(e.id)),t=e[0]?.parentId;if(!t||e.some(e=>e.parentId!==t))return[];const n=[];for(const i of e){const e=this.editor.getShapePageBounds(i.id);e&&it(e)&&n.push({shape:i,bounds:e})}return n}getPageToParentTransform(e){const t=e.startsWith("shape:")?this.editor.getShape(e):null;return t?this.editor.computeShapeLocalToPageTransform(t).tryInvert():yI.Identity()}pageDeltaToParentDelta(e,t){const n=e.applyToPoint(mI.Zero());return e.applyToPoint(t).sub(n)}},av=class{editor;constructor(e){this.editor=e}setSelectedShapeIds(e,t){const n=this.editor,i=t?.pageId??n.getCurrentPageId(),o=t?.source??"user",r=((e,t)=>{const n=new Set(t);return t.filter(t=>{const i=e.getShape(t);if(!i)return!1;let o=i.parentId;const r=new Set([t]);for(;o.startsWith("shape:");){const t=o;if(r.has(t))return!0;if(n.has(t))return!1;r.add(t);const i=e.getShape(t);if(!i)return!0;o=i.parentId}return!0})})(n,Array.from(new Set(e.filter(e=>n.getShapePageId(e)===i&&!n.isShapeHidden(e))))),s=n.getSessionRecord(),a=s.pageSelectedShapeIdsById[i]??[];n.getShapeEditingSession()&&!n.completeEditing(o)||Qe(a,r)||(n.setBindingPreview(null),n.setSnapIndicators(null),n.updateSession({pageSelectedShapeIdsById:{...s.pageSelectedShapeIdsById,[i]:r}},o))}removeShapeIdsFromSelection(e,t="system"){if(0===e.length)return;const n=this.editor,i=new Set(e),o=n.getSessionRecord(),r={};for(const s of n.getPages())r[s.id]=(o.pageSelectedShapeIdsById[s.id]??[]).filter(e=>!i.has(e));n.updateSession({pageSelectedShapeIdsById:r},t)}selectAllCurrentPage(e="user"){const t=this.editor,n=t.getCurrentPageId(),i=t.getCurrentPageShapeIds().map(e=>t.getShape(e)).filter(e=>!!e&&e.parentId===n&&!t.isShapeHidden(e.id)).map(e=>e.id);t.commands.setSelectedShapeIds(i,{source:e})}},lv=class{editor;frameGeometrySignal;companionFrameGeometriesSignal;pathSignal;pageClipPathSignal;bindingSegmentsSignal;frameStyleSignal;frameSignal;handleAnchorsSignal;handlesSignal;handleCountsSignal;overlaySignal;debugStateSignal;debugStateSnapshotSignal;constructor(e){this.editor=e,this.frameGeometrySignal=l("editor.selectionOverlayFrameGeometry",()=>{const t=e.selectedShapeOverlayItemsSignal.get();if(0===t.length)return null;if(io(t))return null;const n=e.getSelectionFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:zi}),this.companionFrameGeometriesSignal=l("editor.selectionOverlayCompanionFrameGeometries",()=>{if("select"!==e.toolStateSignal.get().activeToolId)return[];const t=[];for(const n of e.selectedShapesSignal.get())for(const i of e.getBindingsForShape(n.id))t.push(...e.getBindingUtil(i).getSelectionCompanionFrameGeometries?.(e,i,{selectedShape:n})??[]);return t},{isEqual:Ni}),this.pathSignal=l("editor.selectionOverlayPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return io(t)?t[0]?.path??null:null}),this.pageClipPathSignal=l("editor.selectionOverlayPageClipPath",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return io(t)?t[0]?.pageClipPath??null:null}),this.bindingSegmentsSignal=l("editor.selectionOverlayBindingSegments",()=>{const t=e.selectedShapeOverlayItemsSignal.get();return io(t)?[...t[0]?.bindingSegments??[]]:[]},{isEqual:Ht}),this.frameStyleSignal=l("editor.selectionOverlayFrameStyle",()=>{const t=e.cameraZoomSignal.get();return{strokeWidth:2/t,cornerRadius:3/t}},{isEqual:Hi}),this.frameSignal=l("editor.selectionOverlayFrame",()=>{const e=this.frameGeometrySignal.get();if(!e)return null;const t=this.frameStyleSignal.get();return{...e,...t}},{isEqual:Di}),this.handleAnchorsSignal=l("editor.selectionOverlayHandleAnchors",()=>{if("select"!==e.toolStateSignal.get().activeToolId)return null;const t=e.selectedShapesSignal.get();if(0===t.length)return null;const n=e.getSelectionFrame(),i=e.cameraZoomSignal.get(),o=1===t.length,r=e.canResizeSelection(),s=e.canRotateSelection();return oo(t,n,i,t=>e.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:o,editor:e}),t=>r&&e.getShapeUtil(t).canUseSelectionResizeHandles(t,{editor:e}),t=>s&&e.getShapeUtil(t).canUseSelectionRotateHandle(t,{editor:e}),Li(e,e.getSelectionResizeTargetShapes(),n?.rotation??0))},{isEqual:to}),this.handlesSignal=l("editor.selectionOverlayHandles",()=>{const t=this.handleAnchorsSignal.get();if(!t)return null;const n=e.cameraZoomSignal.get(),{resizeHandles:i,rotateHandles:o,terminalHandles:r,middleHandles:s,customHandles:a}=ro(t,n);return{resizeHandles:i,rotateHandles:o,terminalHandles:r,middleHandles:s,customHandles:a,strokeWidth:2/n}},{isEqual:eo}),this.handleCountsSignal=l("editor.selectionOverlayHandleCounts",()=>{const e=this.handleAnchorsSignal.get();return e?{resizeHandleCount:e.resizeHandleAnchors.length,rotateHandleCount:e.rotateHandleAnchors.length,terminalHandleCount:e.terminalHandleAnchors.length,middleHandleCount:e.middleHandleAnchors.length,customHandleCount:e.customHandleAnchors.length}:null},{isEqual:no}),this.overlaySignal=l("editor.selectionOverlay",()=>{const e=this.frameSignal.get(),t=this.handlesSignal.get();return e&&t?{...e,...t}:null}),this.debugStateSnapshotSignal=l("editor.overlayDebugState.snapshot",t=>{const n=this.frameSignal.get(),i=this.handleCountsSignal.get(),o=t!==hI?t:null,r=!o||!Di(o.frame,n),s=!o||!no(o.handleCounts,i);return{metrics:{selectionFrameActive:null!==n,selectionHandlesActive:null!==i,bindingPreviewActive:e.bindingPreviewActiveSignal.get(),brushBoxActive:e.brushBoxActiveSignal.get(),selectionFrameChangeCount:(o?.metrics.selectionFrameChangeCount??0)+(r?1:0),selectionHandlesChangeCount:(o?.metrics.selectionHandlesChangeCount??0)+(s?1:0),resizeHandleCount:i?.resizeHandleCount??0,rotateHandleCount:i?.rotateHandleCount??0,terminalHandleCount:i?.terminalHandleCount??0,middleHandleCount:i?.middleHandleCount??0,customHandleCount:i?.customHandleCount??0,boundsSummary:(a=n?.bounds??null,a?`${Math.round(a.x)},${Math.round(a.y)},${Math.round(a.w)},${Math.round(a.h)}`:"none"),rotation:n?.rotation??null,strokeWidth:n?.strokeWidth??null},frame:n,handleCounts:i};var a},{isEqual:(e,t)=>rt(e.metrics,t.metrics)}),this.debugStateSignal=l("editor.overlayDebugState.public",()=>this.debugStateSnapshotSignal.get().metrics,{isEqual:rt})}},dv=class{editor;entryRequestAtom=a("editor.shapeEditingEntryRequest",null);entryRequestSignal=this.entryRequestAtom;nextEntryRequestId=1;operation=null;constructor(e){this.editor=e}canEditShape(e){const t="string"==typeof e?this.editor.getShape(e):e;return!!t&&!t.isLocked&&this.editor.getShapeUtil(t).canEdit(t)}start(e,t="user"){let n=this.editor.getShape(e.shapeId);if(!n||!this.canEditShape(n))return null;const i=this.editor.getShapeEditingSession();if(i?.shapeId===n.id){const o={...i,entryMode:e.entryMode??i.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:i.caretPagePoint};return this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:o},t),this.publishEntryRequest({shapeId:n.id,entryMode:o.entryMode,caretPagePoint:o.caretPagePoint}),o}if(e.preserveInteraction||this.editor.cancelInteractionForCommand(),this.editor.getShapeEditingSession()&&!this.complete(t))return null;if(n=this.editor.getShape(e.shapeId),!n||!this.canEditShape(n))return null;const o=e.markId??`editing:${n.id}`;if(e.reuseActiveOperation){const e=this.editor.operations.getActive();if(!e||e.source!==t)throw new Error("Shape editing can only reuse an active operation with the same source.");this.operation=e}else this.operation=this.editor.operations.begin({kind:o,label:"shape.edit",source:"user",history:"record"});const r={shapeId:n.id,markId:o,entryMode:e.entryMode??"focusEnd",caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0,isComposing:!1};return this.editor.commands.setSelectedShapeIds([n.id],{source:t}),this.editor.updateSession({editingShapeId:n.id,shapeEditingSession:r},t),this.publishEntryRequest({shapeId:n.id,entryMode:r.entryMode,caretPagePoint:r.caretPagePoint}),r}complete(e="user"){const t=this.editor.getShapeEditingSession();return!!t&&!t.isComposing&&(this.end({runEditEnd:!0,source:e}),this.commitOperation(),!0)}cancel(e="user"){const t=this.editor.getShapeEditingSession();return!!t&&!t.isComposing&&(this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},e),this.cancelOperation(),!0)}setComposition(e,t="system"){const n=this.editor.getShapeEditingSession();n&&n.isComposing!==e&&this.editor.updateSession({shapeEditingSession:{...n,isComposing:e}},t)}consumeEntryRequest(e){const t=this.entryRequestAtom.get();t&&t.id===e&&this.entryRequestAtom.set(null)}removeShapeIds(e,t="system"){const n=this.editor.getShapeEditingSession();n&&e.includes(n.shapeId)&&(this.end({runEditEnd:!1,source:t}),this.commitOperation())}prepareForShapeRemoval(e,t="system"){const n=this.editor.getShapeEditingSession();if(!n||!e.includes(n.shapeId))return;this.editor.isActiveToolInInitialState()||this.editor.cancelInteractionForCommand();const i=this.editor.getShapeEditingSession();i&&e.includes(i.shapeId)&&(this.end({runEditEnd:!1,source:t}),this.commitOperation())}end(e){const t=this.editor.getShapeEditingSession();if(!t)return;this.entryRequestAtom.set(null);const n=this.editor.getShape(t.shapeId);if(this.editor.updateSession({editingShapeId:null,shapeEditingSession:null},e.source),!e.runEditEnd||!n)return;const i=this.editor.getShapeUtil(n).onEditEnd(n,{editor:this.editor});i?.deleteShapeIds&&i.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(i.deleteShapeIds,{source:e.source})}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}commitOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.commit()}publishEntryRequest(e){this.entryRequestAtom.set({id:this.nextEntryRequestId++,shapeId:e.shapeId,entryMode:e.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0})}},cv=class{editor;constructor(e){this.editor=e}computeParentToPageTransform(e,t=new Set([e.id])){if(!e.parentId.startsWith("shape:"))return yI.Identity();const n=this.editor.getShape(e.parentId);if(!n||t.has(n.id))return yI.Identity();const i=new Set(t);return i.add(n.id),ue(n,this.editor.getShapeUtil(n),this.computeParentToPageTransform(n,i))}computeShapePositionedBounds(e){return this.editor.getShapeUtil(e).getPositionedBounds(e)}computeShapeLocalBounds(e){return((e,t)=>t.getLocalBounds(e))(e,this.editor.getShapeUtil(e))}computeShapeRenderBounds(e){return((e,t)=>t.getRenderBounds(e))(e,this.editor.getShapeUtil(e))}computeShapeExportBounds(e){return ce(e,this.editor.getShapeUtil(e))}computeShapeLocalToPageTransform(e){return ue(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeRenderToPageTransform(e){return((e,t,n=yI.Identity())=>ue(e,t,n))(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeExportToPageTransform(e){return pe(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePageBounds(e){return((e,t,n=yI.Identity())=>SI.FromPoints(me(e,t,n)))(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeExportPageBounds(e){return((e,t,n=yI.Identity())=>{const i=ce(e,t),o=pe(e,t,n);return SI.FromPoints([new mI(i.minX,i.minY),new mI(i.maxX,i.minY),new mI(i.maxX,i.maxY),new mI(i.minX,i.maxY)].map(e=>o.applyToPoint(e)))})(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapeGeometry(e){return Se(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePositionedToPageTransform(e){return he(e,this.editor.getShapeUtil(e),this.computeParentToPageTransform(e))}computeShapePageCenter(e){return this.computeShapeGeometry(e).center}computeShapePageCorners(e){return this.computeShapeGeometry(e).corners}computeShapePageOutlineVertices(e){return this.computeShapeGeometry(e).outlineVertices}getShapePositionedBounds(e){return this.editor.queries.getShapePositionedBounds(e)??null}getShapePageBounds(e){return this.editor.queries.getShapePageBounds(e)??null}getShapeGeometry(e){return this.editor.queries.getShapeGeometry(e)??null}getShapePositionedToPageTransform(e){return this.editor.queries.getShapePositionedToPageTransform(e)??null}getShapePageCenter(e){return this.editor.queries.getShapePageCenter(e)??null}getShapePageCorners(e){return this.editor.queries.getShapePageCorners(e)??null}getShapePageOutlineVertices(e){return this.editor.queries.getShapePageOutlineVertices(e)??[]}getSelectionPageBounds(){return this.editor.queries.getSelectionPageBounds()}getSelectionFrame(){const e=this.editor.queries.getSelectionFrameBounds(),t=this.editor.queries.getSelectionRotationCenter();return e&&t?{bounds:e,rotation:this.editor.queries.getSelectionRotation(),rotationCenter:t,hasCompatibleRotation:this.editor.queries.getSelectionHasCompatibleRotation()}:null}isPointInSelectionBounds(e){const t=this.getSelectionFrame();if(!t)return!1;const n=this.getSelectionFrameLocalBoundsPoint(e);return!!n&&t.bounds.containsPoint(n)}getSelectionFrameLocalBoundsPoint(e){const t=this.getSelectionFrame();return t?Ii(e,t):null}getSelectionPageOutlineVertices(){return this.editor.queries.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.editor.queries.getSelectionAnchorPagePoint()}},uv=class extends Error{},hv=class{editor;constructor(e){this.editor=e}get store(){return G(this.editor)}getSelectionParentOrderState(){return so(this.editor)}getSelectionGroupState(){return this.getGroupStateForShapeIds(this.editor.getSelectedShapeIds())}canGroupSelection(){return null!==this.getSelectionGroupState()}getGroupStateForShapeIds(e){const t=this.editor,n=Array.from(new Set(e.map(e=>t.bindings.getShapeHierarchyRootId(e)))),i=n.map(e=>t.getShape(e)).filter(e=>!!e);if(i.length!==n.length)return null;const o=new Set(n),r=i.filter(e=>!this.isShapeDescendantOfAny(e.id,o));if(r.length<2)return null;if(r.some(e=>t.isShapeOrAncestorLocked(e.id)||t.hasLockedDescendant(e.id)||t.isShapeHidden(e.id)))return null;const s=r[0]?.parentId;if(!s)return null;if(r.some(e=>e.parentId!==s))return null;const a=t.getChildShapes(s),l=new Set(r.map(e=>e.id)),d=a.filter(e=>l.has(e.id)).map(e=>e.id);if(d.length!==r.length)return null;const c=s.startsWith("shape:")?t.getShape(s):null,u=c?t.computeShapeLocalToPageTransform(c).tryInvert():null;if(c&&!u)return null;const h=d.flatMap(e=>t.getShapePageOutlineVertices(e).map(e=>u?u.applyToPoint(e):e)),p=h.length>0?SI.FromPoints(h):null;if(!p||!it(p))return null;const g={parentId:s,shapeIds:d,parentLocalBounds:p};return this.getGroupingShapeCreateInput(g)?g:null}getGroupingShapeCreateInput(e){let t=null;for(const n of this.editor.shapeUtils.values()){const i=n.getGroupingShapeCreateInput({parentId:e.parentId,parentLocalBounds:e.parentLocalBounds});if(i){if(i.type!==n.type)throw new Error(`Shape util "${n.type}" created grouping type "${i.type}" instead of its registered type`);if(i.parentId!==e.parentId)throw new Error(`Shape util "${n.type}" must preserve the requested grouping parent`);if(t)throw new Error(`Multiple shape utils define grouping creation: "${t.shapeUtilType}" and "${n.type}"`);t={shapeInput:i,shapeUtilType:n.type}}}return t?.shapeInput??null}groupShapesFromState(e,t){const n=this.editor,i=this.getGroupingShapeCreateInput(e);if(!i)return null;const o=n.getChildShapes(e.parentId),r=new Set(e.shapeIds);let s;for(const d of o)r.has(d.id)&&(s=d);if(!s)return null;n.cancelInteractionForCommand();let a=null;try{this.store.atomic(()=>{const[l]=n.commands.createShapes([i],{source:t,deferMinimumChildRepair:!0});if(!l)throw new uv;if(a=l.id,!n.commands.reparentShapes({ids:e.shapeIds,parentId:l.id},{source:t}))throw new uv;const d=[];for(const e of o)r.has(e.id)?e.id===s.id&&d.push(l.id):d.push(e.id);n.commands.updateShapes([...d.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)})),...e.shapeIds.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)}))],{source:t})},t)}catch(l){if(l instanceof uv)return null;throw l}return a?n.getShape(a)??null:null}canGroupShapes(e){return null!==this.getGroupStateForShapeIds(e)}groupShapes(e,t="user"){const n=this.getGroupStateForShapeIds(e);return n?this.groupShapesFromState(n,t):null}groupSelection(e="user"){const t=this.editor,n=this.groupShapes(t.getSelectedShapeIds(),e);return n&&t.commands.setSelectedShapeIds([n.id],{source:e}),n}getUngroupableSelectedShapeIds(){return this.getUngroupableShapeIds(this.editor.getSelectedShapeIds())}getUngroupableShapeIds(e){const t=this.editor;return e.map(e=>t.getShape(e)).filter(e=>!!e).filter(e=>t.getShapeUtil(e).canUngroupChildren(e)).filter(e=>!t.isShapeOrAncestorLocked(e.id)&&!t.hasLockedDescendant(e.id)&&!t.isShapeHidden(e.id)&&t.getChildShapeIds(e.id).length>0&&t.getChildShapes(e.id).every(n=>t.canUseShapeParent(e.parentId,n.id)&&!!Ie(t,n,e.parentId))).map(e=>e.id)}canUngroupSelection(){return this.getUngroupableSelectedShapeIds().length>0}canUngroupShapes(e){return this.getUngroupableShapeIds(e).length>0}ungroupShapes(e,t="user"){const n=this.editor,i=Array.from(new Set(e)),o=new Set(this.getOutermostUngroupableShapeIds(i));if(0===o.size)return[];const r=i.map(e=>n.getShape(e)).filter(e=>!!e),s=r.filter(e=>o.has(e.id)).map(e=>({group:e,children:n.getChildShapes(e.id)}));if(s.some(e=>e.children.some(t=>!Ie(n,t,e.group.parentId))))return[];const a=new Map(s.map(e=>[e.group.id,e])),l=new Set(s.map(e=>e.group.parentId)),d=new Map;for(const p of l){const e=[];for(const t of n.getChildShapes(p)){const n=a.get(t.id);n?e.push(...n.children.map(e=>e.id)):e.push(t.id)}d.set(p,e)}n.cancelInteractionForCommand();const c=[],u=new Set;try{this.store.atomic(()=>{const e=[];for(const i of r){if(!o.has(i.id)){u.has(i.id)||(u.add(i.id),c.push(i.id));continue}const e=a.get(i.id);if(!e)continue;if(!n.commands.reparentShapes({ids:e.children.map(e=>e.id),parentId:e.group.parentId},{source:t}))throw new uv;const r=new Set(e.children.map(e=>e.id));for(const t of e.children){const e=n.bindings.getShapeHierarchyRootId(t.id),i=r.has(e)?e:t.id;u.has(i)||(u.add(i),c.push(i))}}for(const t of d.values())e.push(...t.map((e,t)=>({id:e,index:n.createShapeIndex(t+1)})));e.length>0&&n.commands.updateShapes(e,{source:t}),this.removeUngroupedContainerShapes(s.map(e=>e.group.id),t)},t)}catch(h){if(h instanceof uv)return[];throw h}return c.length>0&&n.commands.setSelectedShapeIds(c,{source:t}),c}ungroupSelection(e="user"){return this.ungroupShapes(this.editor.getSelectedShapeIds(),e)}getOutermostUngroupableShapeIds(e){const t=this.getUngroupableShapeIds(e),n=new Set(t);return t.filter(e=>!this.isShapeDescendantOfAny(e,n))}isShapeDescendantOfAny(e,t){let n=this.editor.getShape(e);const i=new Set;for(;n?.parentId.startsWith("shape:");){const e=n.parentId;if(t.has(e))return!0;if(i.has(e))return!1;i.add(e),n=this.editor.getShape(e)}return!1}removeUngroupedContainerShapes(e,t){if(0===e.length)return;const n=this.editor,i=Array.from(new Set(e)).filter(e=>n.getShape(e));0!==i.length&&(n.sideEffects.runBeforeDelete("shape",i,t),this.store.remove(i,t),n.sideEffects.runAfterDelete("shape",i,t))}getSelectionSiblingOrderState(){return ao(this.editor)}canMoveSelectionWithinParent(e){return((e,t)=>{const n=ao(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveSelectionInParentOrder(e){return((e,t)=>{const n=so(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this.editor,e)}canMoveShapesInParentOrder(e,t){return((e,t,n)=>{const i=lo(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this.editor,e,t)}moveShapesInParentOrder(e,t,n="user"){return co(this.editor,e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return uo(this.editor,e,t,n)}moveSelectionWithinParent(e,t="user"){return((e,t,n="user")=>{const i=e.getSelectedShapes();if(1!==i.length)return!1;const[o]=i;if(!o||o.isLocked)return!1;const r=ao(e);if(!r)return!1;const s=e.getChildShapes(r.parentId),a=r.index;if(s[a]?.id!==o.id)return!1;const l="backward"===t?a-1:a+1;if(l<0||l>=s.length)return!1;const d=[...s],[c]=d.splice(a,1);return!!c&&(d.splice(l,0,c),e.cancelInteractionForCommand(),e.commands.updateShapes(d.map((t,n)=>({id:t.id,index:e.createShapeIndex(n+1)})),{source:n}),!0)})(this.editor,e,t)}moveShapesToParentPlacementResult(e,t="user"){return function(e,t,n="user"){const i=Array.from(new Set(t.ids));if(0===i.length)return{ok:!1,reason:"notFound"};const o=i.map(t=>e.getShape(t)).filter(e=>!!e);if(o.length!==i.length)return{ok:!1,reason:"notFound"};for(const s of o){if(s.isLocked)return{ok:!1,reason:"locked"};if(e.isShapeHidden(s.id))return{ok:!1,reason:"hidden"}}for(const s of i){const n=t.parentId;if(n.startsWith("page:")){if(!e.getPage(n))return{ok:!1,reason:"invalidParent"}}else{const t=e.getShape(n);if(!t)return{ok:!1,reason:"invalidParent"};if(t.id===s||e.getDescendantShapeIds(s).includes(t.id))return{ok:!1,reason:"cycle"};if(!e.canUseShapeParent(t.id,s))return{ok:!1,reason:"invalidParent"}}}const r=((e,t,n,i,o)=>{const r=((e,t,n,i)=>{const o=new Set(n),r=t.parentId.startsWith("shape:")?e.getShape(t.parentId):null,s=G(e).getAll().filter(e=>f(e)&&e.parentId===t.parentId).filter(e=>!o.has(e.id));s.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));let a=s.length;if(t.beforeId){const e=s.findIndex(e=>e.id===t.beforeId);if(-1===e)return{ok:!1,reason:"invalidBeforeId"};a=e}s.splice(a,0,...i);const l=new Map;for(const d of i){if(d.parentId===t.parentId)continue;const n=Ie(e,d,t.parentId);if(!n)return{ok:!1,reason:"unsupportedTransform"};l.set(d.id,n)}return{ok:!0,updates:s.map((n,i)=>{const o=n.parentId!==t.parentId&&r?e.getShapeUtil(r).getChildPlacementMeta(r,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:e.createShapeIndex(i+1),...l.get(n.id),meta:o===n.meta?void 0:o}})}})(e,t,n,i);return r.ok?(e.cancelInteractionForCommand(),e.commands.updateShapes(r.updates,{source:o}),r):r})(e,t,i,o,n);return r.ok?{ok:!0,movedIds:i}:{ok:!1,reason:r.reason}}(this.editor,e,t)}moveSelectionInParentOrder(e,t="user"){return((e,t,n="user")=>co(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}moveSelectionToParentOrderEdge(e,t="user"){return((e,t,n="user")=>uo(e,e.getSelectedShapeIds(),t,n))(this.editor,e,t)}isShapeOrAncestorLocked(e){const t=this.editor,n=new Set;let i=t.getShape(e);for(;i;){if(i.isLocked)return!0;if(!i.parentId.startsWith("shape:"))return!1;const e=i.parentId;if(n.has(e))return!1;n.add(e),i=t.getShape(e)}return!1}hasLockedDescendant(e){const t=this.editor;return t.getDescendantShapeIds(e).some(e=>t.getShape(e)?.isLocked??!1)}getOutermostSelectableShapeId(e){const t=this.editor;let n=e,i=t.getShape(e);const o=new Set([e]);for(;i?.parentId.startsWith("shape:");){const e=i.parentId;if(o.has(e))break;o.add(e);const r=t.getShape(e);if(!r)break;t.getShapeUtil(r).isSelectionTransformContainer(r)&&(n=r.id),i=r}return n}getShapeIdsIncludingDescendants(e){const t=[],n=new Set;for(const i of e)if(!n.has(i)){n.add(i),t.push(i);for(const e of this.editor.getDescendantShapeIds(i))n.has(e)||(n.add(e),t.push(e))}return t}getShapeIdsForSelectionTransform(e){return this.getOutermostUnlockedShapeIds(e)}getShapeIdsForSelectionRotation(e){return this.getOutermostUnlockedShapeIds(e)}getSelectionTransformTargetShapes(){return this.getShapeIdsForSelectionTransform(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}canResizeSelection(){const e=this.editor,t=this.getSelectionTransformAffectedShapes(),n=1===t.length;return t.length>0&&t.every(t=>e.getShapeUtil(t).canParticipateInSelectionResize(t,{editor:e,isOnlyAffectedShape:n}))}canFlipSelection(){const e=this.editor,t=this.getSelectionTransformAffectedShapes(),n=1===t.length;return t.length>0&&t.every(t=>e.getShapeUtil(t).canParticipateInSelectionFlip(t,{editor:e,isOnlyAffectedShape:n}))}canRotateSelection(){const e=this.editor,t=this.getSelectionTransformAffectedShapes(),n=1===t.length;return t.length>0&&t.every(t=>e.getShapeUtil(t).canParticipateInSelectionRotation(t,{editor:e,isOnlyAffectedShape:n}))}getSelectionResizeTargetShapes(){const e=this.editor,t=[],n=new Set,i=o=>{if(!n.has(o.id))if(n.add(o.id),e.getShapeUtil(o).shouldResizeDescendants(o))for(const t of e.getChildShapes(o.id))i(t);else t.push(o)};for(const o of this.getOutermostUnlockedShapeIds(e.getSelectedShapeIds())){const t=e.getShape(o);t&&i(t)}return t}getSelectionRotationTargetShapes(){return this.getShapeIdsForSelectionRotation(this.editor.getSelectedShapeIds()).map(e=>this.editor.getShape(e)).filter(e=>!!e)}getSelectionTransformAffectedShapes(){const e=this.editor,t=this.getOutermostUnlockedShapeIds(e.getSelectedShapeIds());return this.getShapeIdsIncludingDescendants(t).map(t=>e.getShapeSignal(t).get()).filter(e=>!!e)}getShapeExportTraversalIds(e){const t=this.editor,n=this.getShapeIdsIncludingDescendants(e).filter(e=>!t.isShapeHidden(e)),i=new Set(n);for(const o of n)for(const e of t.getBindingsForShape(o)){const o=t.getBindingUtil(e).getExportShapeIds?.(t,e);for(const e of o??[])for(const o of this.getShapeIdsIncludingDescendants([e]))i.has(o)||t.isShapeHidden(o)||(i.add(o),n.push(o))}return n}getShapeIdsInContainerBounds(e,t={}){const n=this.editor,i=n.getShapePageId(e),o=n.getShapePageBounds(e);return i&&o?n.getShapeIdsInBounds(o,{pageId:i}).filter(i=>{if(i===e)return!1;const o=n.getShapeContainment(e,i);return"inside"===o||t.includeIntersecting&&"intersecting"===o}):[]}canUseShapeParent(e,t){return((e,t,n)=>{if(t.startsWith("page:"))return!!e.getPage(t);const i=e.getShape(t);if(!i)return!1;if(be(i,e.getShapeUtil(i)))return!1;if(n){const t=e.getShape(n);return!!t&&i.id!==n&&!e.getDescendantShapeIds(n).includes(i.id)&&e.getShapeUtil(i).canReceiveChild(i,t)}return e.getShapeUtil(i).canReceiveChildren(i)})(this.editor,e,t)}isShapeOrAncestorInSet(e,t){let n=this.editor.getShape(e);const i=new Set;for(;n;){if(t.has(n.id))return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(i.has(e))return!1;i.add(e),n=this.editor.getShape(e)}return!1}isShapeDescendantOf(e,t){let n=this.editor.getShape(e);const i=new Set;for(;n?.parentId.startsWith("shape:");){const e=n.parentId;if(e===t)return!0;if(i.has(e))return!1;i.add(e),n=this.editor.getShape(e)}return!1}getOutermostUnlockedShapeIds(e){const t=this.editor,n=Array.from(new Set(e)),i=new Set(n);return n.filter(e=>{const n=t.getShape(e);return!(!n||t.isShapeOrAncestorLocked(n.id)||t.hasLockedDescendant(n.id)||this.isShapeDescendantOfAny(n.id,i))})}},pv=class{bindings=new Map;bindingIds=[];register(e){const t=this.bindingIds.indexOf(e.id);t>=0&&this.bindingIds.splice(t,1);const n=ho(e.shortcut);this.bindingIds.push(e.id),this.bindings.set(e.id,{id:e.id,shortcut:n,target:e.target,label:e.label??po(n)})}registerActionShortcut(e,t){this.register({id:`action:${e}`,shortcut:t,target:{type:"action",actionId:e}})}registerEditorShortcut(e,t){const n=ho(t);this.register({id:`editor:${e}:${mo(n)}`,shortcut:n,target:{type:"editor",command:e}})}registerToolShortcut(e,t){this.register({id:`tool:${e}`,shortcut:t,target:{type:"tool",toolId:e}})}unregister(e){const t=this.bindingIds.indexOf(e);t>=0&&this.bindingIds.splice(t,1),this.bindings.delete(e)}getBinding(e){const t=this.bindings.get(e);return t?{id:t.id,shortcut:t.shortcut,target:t.target,label:t.label}:null}getTargetForEvent(e){return this.getBindingForEvent(e)?.target??null}getActionIdForEvent(e){const t=this.getTargetForEvent(e);return"action"===t?.type?t.actionId:null}getToolIdForEvent(e){const t=this.getTargetForEvent(e);return"tool"===t?.type?t.toolId:null}getActionShortcutLabel(e){return this.getBindingLabel(`action:${e}`)}getToolShortcutLabel(e){return this.getBindingLabel(`tool:${e}`)}getBindingForEvent(e){for(let t=this.bindingIds.length-1;t>=0;t--){const n=this.bindings.get(this.bindingIds[t]);if(n&&go(n.shortcut,e))return n}return null}getBindingLabel(e){return this.bindings.get(e)?.label}},gv=class{editor;shapeRenderOrderByIdSignal;culledShapeIdsSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;renderVisibleShapeIdSetSignal;renderItemsSignal;renderHostDebugStateSignal;retainedBaseShapeWindowSnapshotSignal;retainedShapeWindowSnapshotSignal;renderHostDebugStateSnapshotSignal;constructor(e){this.editor=e,this.shapeRenderOrderByIdSignal=l("editor.shapeRenderOrderById",()=>{const t=new Map;for(const[n,i]of e.currentPageShapeIdsSignal.get().entries())t.set(i,n);return t}),this.culledShapeIdsSignal=l("editor.culledShapeIds",()=>{const t=e.getCurrentPageId(),n=e.renderViewportPageBoundsSignal.get();return n?e.spatialIndex.getShapeIdsInViewport(n,{pageId:t}):e.currentPageShapeIdsSignal.get()},{isEqual:Qe}),this.retainedBaseShapeWindowSnapshotSignal=l("editor.retainedBaseShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),o=vo(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(t!==hI&&t&&t.viewportReady&&o.length>0){const e=((e,t)=>{if(e.length!==t.length||0===t.length)return null;const n=t.map((n,i)=>{const o=e[i];if(!o)return null;if(o.end+2<n.start||o.start>n.end+2)return null;const r=i>0?t[i-1]:null,s=i<t.length-1?t[i+1]:null,a=s?s.start-3:1/0,l={start:Math.min(n.start,Math.max(r?r.end+3:-1/0,o.start)),end:Math.max(n.end,Math.min(a,o.end))};return l.end-l.start>n.end-n.start+4?null:l});if(n.some(e=>null===e))return null;const i=n;if(bo(i).length!==t.length)return null;const o=Io(t);return Io(i)>o+12?null:i})(bo(t.ranges.map(e=>({...e}))),o);if(e)return Po(n,e,{viewportReady:i})}return Po(n,o,{viewportReady:i})},{isEqual:(e,t)=>Qe(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=l("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:lt}),this.selectedShapeIdsOutsideCulledSignal=l("editor.selectedShapeIdsOutsideCulled",()=>{const t=e.selectedShapeIdsSignal.get();if(0===t.length)return[];const n=this.culledShapeIdSetSignal.get();return t.filter(e=>!n.has(e))},{isEqual:Qe}),this.selectedShapeIdsOutsideCulledSetSignal=l("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:lt}),this.renderVisibleShapeIdsSignal=l("editor.renderVisibleShapeIds",()=>{if(0===this.selectedShapeIdsOutsideCulledSignal.get().length)return this.culledShapeIdsSignal.get();const t=this.culledShapeIdSetSignal.get(),n=this.selectedShapeIdsOutsideCulledSetSignal.get();return e.currentPageShapeIdsSignal.get().filter(e=>t.has(e)||n.has(e))},{isEqual:Qe}),this.retainedShapeWindowSnapshotSignal=l("editor.retainedShapeWindowSnapshot",t=>{const n=e.currentPageShapeIdsSignal.get(),i=null!==e.viewportPageBoundsSignal.get(),o=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,r=(s=o.length)<=0?0:So(Math.ceil(.5*s),12,96);var s;const a=((e,t,n,i)=>{if(0===e.length)return[];const o=new Map;for(const[a,l]of e.entries())o.set(l,a);const r=bo(t.map(e=>o.get(e)).filter(e=>void 0!==e).sort((e,t)=>e-t).map(e=>({start:e,end:e+1})),2),s=[];if(r.length>0){const t=So(Math.ceil(i/(2*r.length)),8,32);for(const[n,i]of r.entries()){const o=n>0?r[n-1]:null,a=n<r.length-1?r[n+1]:null,l=a?a.start-i.end:1/0,d=xo(o?i.start-o.end:1/0,t),c=xo(l,t+4);s.push({start:Math.max(0,i.start-d),end:Math.min(e.length,i.end+c)})}}for(const a of n){const e=o.get(a);void 0!==e&&s.push({start:e,end:e+1})}return 0===s.length?[]:bo(s,2)})(n,o,this.selectedShapeIdsOutsideCulledSetSignal.get(),r);if(i&&t!==hI&&t&&t.viewportReady&&t.ranges.length>0&&a.length>0){const e=bo(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 Po(n,e,{viewportReady:i});const o=((e,t,n)=>{const i=t.map((n,i)=>{const o={...n};for(const t of e)t.end+6<n.start||t.start>n.end+6||(o.start=Math.min(o.start,t.start),o.end=Math.max(o.end,t.end));const r=i>0?t[i-1]:null,s=i<t.length-1?t[i+1]:null,a=s?s.start-3:1/0;return{start:Math.min(n.start,Math.max(r?r.end+3:-1/0,o.start)),end:Math.max(n.end,Math.min(a,o.end))}});if(bo(i).length!==t.length)return null;const o=Io(t);return Io(i)>o+n?null:i})(e,a,r);if(o)return Po(n,o,{viewportReady:i})}return Po(n,a,{viewportReady:i})},{isEqual:(e,t)=>Qe(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=l("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:Qe}),this.renderVisibleShapeIdSetSignal=l("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:lt}),this.renderItemsSignal=l("editor.renderItems",()=>{const t=e.selectedShapeIdSetSignal.get(),n=[];for(const i of this.renderVisibleShapeIdsSignal.get()){const o=e.getShapeSignal(i).get(),r=e.queries.getShapePageBoundsSignal(i).get();o&&!o.isHidden&&r&&n.push({id:o.id,shape:o,bounds:r,isSelected:t.has(o.id)})}return n},{isEqual:at}),this.renderHostDebugStateSnapshotSignal=l("editor.renderHostDebugState.snapshot",t=>{const n=this.culledShapeIdsSignal.get(),i=this.renderVisibleShapeIdsSignal.get(),o=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,r=this.retainedShapeIdsSignal.get(),s=this.selectedShapeIdsOutsideCulledSignal.get(),a=this.getPageIndexById(e.currentPageShapeIdsSignal.get()),l=vo(n,a),d=vo(r,a),c=vo(o,a),u=((e,t)=>{if(0===e.length)return{changed:t.length,added:t.length,removed:0};if(0===t.length)return{changed:e.length,added:0,removed:e.length};const n=new Set(e),i=new Set(t);let o=0,r=0;for(const s of i)n.has(s)||(o+=1);for(const s of n)i.has(s)||(r+=1);return{changed:o+r,added:o,removed:r}})(t===hI?[]:t.retainedShapeIds,r);return{metrics:{culledCount:n.length,visibleCount:i.length,retainedCount:r.length,retainedBaseCount:o.length,culledRangeCount:l.length,culledRangeSpan:Io(l),culledRangesSummary:yo(l),retainedBaseRangeCount:c.length,retainedBaseRangeSpan:Io(c),retainedBaseRangesSummary:yo(c),retainedRangeCount:d.length,retainedRangeSpan:Io(d),retainedRangesSummary:yo(d),retainedChangeCount:u.changed,retainedAddedCount:u.added,retainedRemovedCount:u.removed,selectedOutsideCulledCount:s.length},retainedShapeIds:r.slice()}},{isEqual:(e,t)=>ot(e.metrics,t.metrics)}),this.renderHostDebugStateSignal=l("editor.renderHostDebugState.public",()=>this.renderHostDebugStateSnapshotSignal.get().metrics,{isEqual:ot})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},fv=class{editor;activeToolId=a("tools.activeToolId","select");isToolLocked=a("tools.isToolLocked",!1);registry=new Map;activeTool=null;constructor(e){this.editor=e}register(e,t,n={}){this.registry.set(e,t),n.shortcut&&this.editor.shortcuts.registerToolShortcut(e,n.shortcut)}hasTool(e){return this.registry.has(e)}setActiveTool(e,t="tool_switch"){const n=this.registry.get(e);if(!n)throw new Error(`Unknown tool "${e}"`);this.activeTool&&this.activeToolId.get()===e||(this.activeTool&&(this.editor.cancelInteractionAndClearTransients(t),this.activeTool.exit({reason:t})),this.activeToolId.set(e),this.activeTool=n(this.editor),this.activeTool.enter())}dispatch(e){this.activeTool?.dispatch(e)}cancel(e){this.activeTool?.dispatch({type:"cancel",reason:e})}setToolLocked(e){this.isToolLocked.set(e)}isActiveToolInInitialState(){return this.activeTool?.isInInitialState()??!0}},mv=class{handlers=[];registeredIds=new Set;register(e){this.registeredIds.has(e.id)||(this.handlers.push(e),this.registeredIds.add(e.id))}getHandlers(){return this.handlers}handleEvent(e,t){for(const n of this.handlers)if("handled"===n.editorEvent?.handleEvent(e,t))return"handled";return"continue"}broadcastEvent(e,t){let n="continue";for(const i of this.handlers)"handled"===i.editorEvent?.handleEvent(e,t)&&(n="handled");return n}createSelectionHandleSession(e,t){for(const n of this.handlers){const i=n.selectionHandle?.createSession(e,t);if(i)return i}return null}createShapePointerSession(e,t){for(const n of this.handlers){const i=n.shapePointer?.createSession(e,t);if(i)return i}return null}},Sv=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}},yv=class{store;[EI];inputs=new KI;snapshots=new _I(this);clipboard=new HI(this);shortcuts=new pv;tools=new fv(this);camera=new zI(this);selection=new av(this);selectionLayout=new sv(this);editing=new dv(this);geometry=new cv(this);hierarchy=new hv(this);shapeUtils=new PI;shapeSvgExporters=new MI;bindingUtils=new fI;interactions=new mv;selectionHandleInteractions=new Sv(this.interactions);runtime=new bI;queries;bindings;spatialIndex;snaps;renderWindow;selectionOverlay;transients=new YI(this);history;operations;sideEffects=new rv;commands;shapeCapabilityDefinitions;brushBoxSignal=this.transients.brushBoxSignal;brushBoxActiveSignal=this.transients.brushBoxActiveSignal;bindingPreviewSignal=this.transients.bindingPreviewSignal;bindingPreviewActiveSignal=this.transients.bindingPreviewActiveSignal;terminalBindingGuidesSignal=this.transients.terminalBindingGuidesSignal;dropTargetShapeIdSignal=this.transients.dropTargetShapeIdSignal;hoveredShapeIdSignal=this.transients.hoveredShapeIdSignal;selectionTranslationActiveSignal=this.transients.selectionTranslationActiveSignal;snapIndicatorsSignal;snapIndicatorsActiveSignal;get viewportScreenSizeSignal(){return this.camera.viewportScreenSizeSignal}shapeEditingEntryRequestSignal=this.editing.entryRequestSignal;_shapeDefaultPropsByTypeSignal=a("editor.shapeDefaultPropsByType",new Map);shapeDefaultPropsByTypeSignal=this._shapeDefaultPropsByTypeSignal;nextShapeNumber=1;nextPageNumber=1;nextBindingNumber=1;nextAssetNumber=1;assetUrlResolver=()=>null;get _internalStore(){return G(this)}sessionSignal=l("editor.session",()=>{const e=this._internalStore.getRecordSignal(vI).get();if(!m(e))throw new Error("Missing session record");return e});getSessionRecord(){const e=this._internalStore.get(vI);if(!m(e))throw new Error("Missing session record");return e}currentPageIdSignal=l("editor.currentPageId",()=>this.sessionSignal.get().currentPageId);currentPageShapeIdsSignal;currentPageShapesSignal;currentPageShapeHierarchySignal;culledShapeIdsSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;selectionPageBoundsSignal;selectionFrameBoundsSignal;selectionAnchorPagePointSignal;pagesSignal=l("editor.pages",()=>Array.from(this._internalStore.recordsSignal.get().values()).filter(p).sort((e,t)=>e.index.localeCompare(t.index)),{isEqual:Ge});currentPageSignal=l("editor.currentPage",()=>{const e=this.currentPageIdSignal.get();return this.pagesSignal.get().find(t=>t.id===e)??null});pageStateSignal=l("editor.pageState",()=>{const e=this.pagesSignal.get(),t=this.currentPageIdSignal.get(),n=e.find(e=>e.id===t)??null;return{pages:e,currentPageId:t,currentPage:n,canDeleteCurrentPage:e.length>1&&null!==n}});toolStateSignal=l("editor.toolState",()=>{const e=this.sessionSignal.get();return{activeToolId:e.activeToolId,isToolLocked:e.isToolLocked}});editingShapeIdSignal=l("editor.editingShapeId",()=>this.sessionSignal.get().editingShapeId);shapeEditingSessionSignal=l("editor.shapeEditingSession",()=>this.sessionSignal.get().shapeEditingSession);shapeEditingStateSignal=l("editor.shapeEditingState",()=>({editingShapeId:this.editingShapeIdSignal.get(),session:this.shapeEditingSessionSignal.get()}));currentCameraSignal=l("editor.currentCamera",()=>this.sessionSignal.get().pageCameraById[this.currentPageIdSignal.get()]??wI);selectedShapeIdsSignal=l("editor.selectedShapeIds",()=>{const e=this.sessionSignal.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:Qe});selectionCountSignal=l("editor.selectionCount",()=>this.selectedShapeIdsSignal.get().length);selectedShapeIdSetSignal=l("editor.selectedShapeIdSet",()=>new Set(this.selectedShapeIdsSignal.get()),{isEqual:lt});selectedShapesSignal=l("editor.selectedShapes",()=>this.selectedShapeIdsSignal.get().map(e=>this.getShapeSignal(e).get()).filter(e=>!!e));selectionCanFlipSignal=l("editor.selectionCanFlip",()=>this.hierarchy.canFlipSelection());selectedShapeOverlayItemsSignal=l("editor.selectedShapeOverlayItems",()=>"select"!==this.toolStateSignal.get().activeToolId?[]:this.selectedShapeIdsSignal.get().map(e=>this.getShapeSignal(e).get()).filter(e=>!!e).map(e=>{const t=this.getShapeUtil(e).getSelectionOverlayInfo(e,{editor:this});return{id:e.id,usesSelectionPathOverlay:t.usesSelectionPathOverlay,startPagePoint:t.startPagePoint,endPagePoint:t.endPagePoint,middlePagePoint:t.middlePagePoint,path:t.path,pathStyle:t.pathStyle,pageClipPath:t.pageClipPath??null,bindingSegments:t.bindingSegments??[]}}),{isEqual:Oi});selectionStateSignal=l("editor.selectionState",()=>{const e=this.selectedShapeIdsSignal.get(),t=1===e.length?this.getShapeSignal(e[0]).get()??null:null,n=this.selectedShapesSignal.get(),i=(e=>{let t=null;for(const n of e)if(null!==t){if(t!==n.type)return null}else t=n.type;return t})(n),o=1===n.length,r=n.map(e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:o,editor:this})).some(e=>e.terminalHandleAnchors.length>0||e.middleHandleAnchors.length>0||(e.customHandleAnchors?.length??0)>0),s=n.some(e=>this.getShapeUtil(e).contributesToSelectionFrame(e,{editor:this})),a=r&&s,l=t?this.getShapeUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:o,editor:this}):null,d=1===e.length&&!!l&&(l.terminalHandleAnchors.length>0||(l.customHandleAnchors?.length??0)>0),c=this.queries.selectionHasRotationSignal.get();return{count:e.length,singleShapeType:t?.type??null,commonShapeType:i,canFlipSelection:this.selectionCanFlipSignal.get(),hasPointHandleSelection:r,hasFrameSelection:s,isMixedFrameAndPointHandleSelection:a,canDragPointHandles:d,hasSelectionRotation:c,hasMixedSelectionRotation:!this.queries.selectionHasCompatibleRotationSignal.get(),canResetSelectionRotation:c&&s,frameBounds:this.selectionFrameBoundsSignal.get(),frameRotation:this.queries.selectionRotationSignal.get(),frameRotationCenter:this.queries.selectionRotationCenterSignal.get(),selectionAnchorPagePoint:this.selectionAnchorPagePointSignal.get()}});selectionMetadataSignal=l("editor.selectionMetadata",()=>{const e=this.selectionStateSignal.get();return{count:e.count,singleShapeType:e.singleShapeType,commonShapeType:e.commonShapeType,canFlipSelection:e.canFlipSelection,hasPointHandleSelection:e.hasPointHandleSelection,hasFrameSelection:e.hasFrameSelection,isMixedFrameAndPointHandleSelection:e.isMixedFrameAndPointHandleSelection,canDragPointHandles:e.canDragPointHandles,hasSelectionRotation:e.hasSelectionRotation,hasMixedSelectionRotation:e.hasMixedSelectionRotation,canResetSelectionRotation:e.canResetSelectionRotation}},{isEqual:Ze});pageTransformSignal=l("editor.pageTransform",()=>{const e=this.currentCameraSignal.get();return yI.Scale(e.z,e.z).compose(yI.Translate(-e.x,-e.y))});cameraZoomSignal=l("editor.cameraZoom",()=>this.currentCameraSignal.get().z);viewportPageBoundsSignal=l("editor.viewportPageBounds",()=>{const{w:e,h:t}=this.viewportScreenSizeSignal.get();if(e<=0||t<=0)return null;const n=this.currentCameraSignal.get();return new SI(n.x,n.y,e/n.z,t/n.z)});renderViewportPageBoundsSignal=l("editor.renderViewportPageBounds",e=>{const t=this.viewportPageBoundsSignal.get();return t?e!==hI&&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:nt});renderItemsSignal;renderHostDebugStateSignal;historyStateSignal;shapeRenderOrderByIdSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdSetSignal;shapeSignals=new Map;shapeContentCutoutLocalPolygonSignals=new Map;shapeSelectedSignals=new Map;shapeRenderOrderSignals=new Map;shapeRenderVisibleSignals=new Map;shapeDocumentVisibleSignals=new Map;shapeEffectiveOpacitySignals=new Map;shapeEditingSessionSignals=new Map;shapeDropTargetSignals=new Map;shapeHoveredSignals=new Map;shapeSelectedDescendantTransformAncestorSignals=new Map;lastPointerDownForClickCount=null;lastPointerUpForClickCount=null;currentPointerClickCount=1;selectionOverlayFrameGeometrySignal;selectionOverlayCompanionFrameGeometriesSignal;selectionOverlayPathSignal;selectionOverlayPageClipPathSignal;selectionOverlayBindingSegmentsSignal;selectionOverlayFrameStyleSignal;selectionOverlayFrameSignal;selectionOverlayHandleAnchorsSignal;selectionOverlayHandlesSignal;selectionOverlayHandleCountsSignal;selectionOverlaySignal;overlayDebugStateSignal;constructor(e={}){this.shapeCapabilityDefinitions=e.shapeCapabilities??[],e.resolveAssetUrl&&(this.assetUrlResolver=e.resolveAssetUrl);for(const 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 BI(this.snapshots.buildInitialRecords(e.documentSnapshot??null,e.sessionSnapshot??null,e.documentMeta??{}));var n;((e,t)=>{e[EI]=t})(this,t),this.store=t,this.snapshots.ensureSessionIntegrity(),this.queries=new qI(this),this.bindings=new DI(this),this.spatialIndex=new VI(this,this.queries),this.snaps=new ov(this),this.snapIndicatorsSignal=this.snaps.indicatorsSignal,this.snapIndicatorsActiveSignal=this.snaps.activeSignal,this.currentPageShapeIdsSignal=this.queries.currentPageShapeIdsSignal,this.currentPageShapesSignal=this.queries.currentPageShapesSignal,this.currentPageShapeHierarchySignal=this.queries.currentPageShapeHierarchySignal,this.selectionPageBoundsSignal=this.queries.selectionPageBoundsSignal,this.selectionFrameBoundsSignal=this.queries.selectionFrameBoundsSignal,this.selectionAnchorPagePointSignal=this.queries.selectionAnchorPagePointSignal,this.selectionOverlay=new lv(this),this.selectionOverlayFrameGeometrySignal=this.selectionOverlay.frameGeometrySignal,this.selectionOverlayCompanionFrameGeometriesSignal=this.selectionOverlay.companionFrameGeometriesSignal,this.selectionOverlayPathSignal=this.selectionOverlay.pathSignal,this.selectionOverlayPageClipPathSignal=this.selectionOverlay.pageClipPathSignal,this.selectionOverlayBindingSegmentsSignal=this.selectionOverlay.bindingSegmentsSignal,this.selectionOverlayFrameStyleSignal=this.selectionOverlay.frameStyleSignal,this.selectionOverlayFrameSignal=this.selectionOverlay.frameSignal,this.selectionOverlayHandleAnchorsSignal=this.selectionOverlay.handleAnchorsSignal,this.selectionOverlayHandlesSignal=this.selectionOverlay.handlesSignal,this.selectionOverlayHandleCountsSignal=this.selectionOverlay.handleCountsSignal,this.selectionOverlaySignal=this.selectionOverlay.overlaySignal,this.overlayDebugStateSignal=this.selectionOverlay.debugStateSignal,this.renderWindow=new gv(this),this.shapeRenderOrderByIdSignal=this.renderWindow.shapeRenderOrderByIdSignal,this.culledShapeIdsSignal=this.renderWindow.culledShapeIdsSignal,this.culledShapeIdSetSignal=this.renderWindow.culledShapeIdSetSignal,this.selectedShapeIdsOutsideCulledSignal=this.renderWindow.selectedShapeIdsOutsideCulledSignal,this.selectedShapeIdsOutsideCulledSetSignal=this.renderWindow.selectedShapeIdsOutsideCulledSetSignal,this.renderVisibleShapeIdsSignal=this.renderWindow.renderVisibleShapeIdsSignal,this.retainedShapeIdsSignal=this.renderWindow.retainedShapeIdsSignal,this.renderVisibleShapeIdSetSignal=this.renderWindow.renderVisibleShapeIdSetSignal,this.renderItemsSignal=this.renderWindow.renderItemsSignal,this.renderHostDebugStateSignal=this.renderWindow.renderHostDebugStateSignal,this.syncShapeCounter(),this.syncPageCounter(),this.syncBindingCounter(),this.syncAssetCounter(),this.operations=new UI(this),this.history=new $I(this),this.historyStateSignal=this.history.state,this.commands=(n=this,{createPage:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.createPageRecord(t);let r=o;return G(e).atomic(()=>{const t=Pe([...e.getPages(),o]);r=t.find(e=>e.id===o.id)??o,G(e).put(t,i),e.ensurePageSessionState(r.id,i)},i),r})(n,e,t),deletePage:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getPages();if(o.length<=1)return!1;const r=o.findIndex(e=>e.id===t);if(r<0)return!1;const s=e.getShapesForPage(t).map(e=>e.id),a=Pe(o.filter(e=>e.id!==t)),l=o[r+1]?.id??o[r-1]?.id??o[0]?.id,d=e.getCurrentPageId()===t&&l?l:e.getCurrentPageId();return G(e).atomic(()=>{s.length>0&&De(e,s,n),G(e).remove([t],i),e.removePageSessionState(t,d,i),G(e).put(a,i)},i),!0})(n,e,t),renamePage(e,t){((e,t,n)=>{const i=n?.source??"user",o=e.getPage(t.id);if(!o)return;const r=t.name.trim();r&&r!==o.name&&G(e).atomic(()=>{G(e).put([{...o,name:r}],i)},i)})(n,e,t)},updateDocumentMeta:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getDocumentMetadataRecord()??c(),r={...o,meta:{...o.meta,...t.patch}};return G(e).atomic(()=>{G(e).put([r],i)},i),r})(n,e,t),updatePageMeta:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getPage(t.id);if(!o)return null;const r={...o,meta:{...o.meta,...t.patch}};return G(e).atomic(()=>{G(e).put([r],i)},i),r})(n,e,t),movePage(e,t){((e,t,n)=>{const i=n?.source??"user",o=e.getPages(),r=o.findIndex(e=>e.id===t.id);if(r<0)return;const s=Math.max(0,Math.min(t.toIndex,o.length-1));if(r===s)return;const a=[...o],[l]=a.splice(r,1);l&&(a.splice(s,0,l),G(e).atomic(()=>{G(e).put(Pe(a),i)},i))})(n,e,t)},createShapes:(e,t)=>((e,t,n)=>{const i=[],o=n?.source??"user";return G(e).atomic(()=>{const r=t.map(t=>e.createShapeRecord(t)),s=new Map(r.map(e=>[e.id,e])),a=r.map(t=>{if(!t.parentId.startsWith("shape:"))return t;const n=s.get(t.parentId)??e.getShape(t.parentId);if(!n)return t;const i=e.getShapeUtil(n).getChildPlacementMeta(n,t,{editor:e,reason:"create"});return i===t.meta?t:{...t,meta:i}});if(Te(e,a),G(e).put(a,o),"user"===o&&!1!==n?.autoReparent){const i=new Map;for(let n=0;n<a.length;n+=1){const o=a[n],r=t[n];if(!o||!r||r.parentId)continue;const s=e.getContainingParentIdForShapeRecord(o);s&&s!==o.parentId&&i.set(o.id,s)}((e,t)=>{const n=new Set;for(const i of e.keys()){const o=[],r=new Map;let s=i;for(;s;){const i=r.get(s);if(void 0!==i){for(const e of o.slice(i))n.add(e);break}r.set(s,o.length),o.push(s);const a=e.get(s);s=a?.startsWith("shape:")&&t.has(a)?a:null}}for(const i of n)e.delete(i)})(i,new Set(a.map(e=>e.id)));const o=new Map;for(const e of a){const t=i.get(e.id);if(!t)continue;const n=o.get(t)??[];n.push(e.id),o.set(t,n)}for(const[t,r]of o)Oe(e,{ids:r,parentId:t},n)}const l=Fe(e,a.map(e=>e.id)),d=new Set;if(!n?.deferMinimumChildRepair){const t=new Set;for(const n of a){const i=e.getShape(n.id);i&&e.getShapeUtil(i).getMinimumChildCount(i)>0&&t.add(i.id)}Ue(e,t,d,o)}Be(e,l,o,d),i.push(...a.map(t=>e.getShape(t.id)).filter(e=>!!e))},o),i})(n,e,t),createShapesFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";if(0===t.length)return[];for(const o of t)if(e.getShape(o.id))throw new Error(`Shape ${o.id} already exists`);return Te(e,t),G(e).atomic(()=>{G(e).put(t,i),Me(e,i);const n=Fe(e,t.map(e=>e.id));for(const i of t){const t=e.getShape(i.id);t&&e.getShapeUtil(t).getMinimumChildCount(t)>0&&n.add(t.id)}const o=new Set;Ue(e,n,o,i),Be(e,n,i,o)},i),t.map(t=>e.getShape(t.id)).filter(e=>!!e)})(n,e,t),updateShapes(e,t){Ce(n,e,t)},reparentShapes:(e,t)=>Oe(n,e,t),deleteShapes(e,t){De(n,e,t)},createAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.createAssetRecord(t);return G(e).atomic(()=>{G(e).put([o],i)},i),o})(n,e,t),createAssetsFromRecords:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(G(e).atomic(()=>{G(e).put(t,i)},i),t)})(n,e,t),updateAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getAsset(t.id);if(!o)return null;const r={...o,props:t.props?{...o.props,...t.props}:o.props,meta:t.meta??o.meta};return G(e).atomic(()=>{G(e).put([r],i)},i),r})(n,e,t),deleteAsset:(e,t)=>((e,t,n)=>{const i=n?.source??"user";return!!e.getAsset(t)&&(G(e).atomic(()=>{G(e).remove([t],i)},i),!0)})(n,e,t),createBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.createBindingRecord(t);if(!ze(e,o))throw new Error(`Invalid binding endpoints for ${o.type} binding`);const r=new Set;return Ne(e,[o.fromId,o.toId],r),G(e).atomic(()=>{const t=e.bindings.getConflictingBindings(o).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),G(e).put([o],i),e.bindings.syncCreatedBinding(o,i),Ne(e,[o.fromId,o.toId],r),Ue(e,r,new Set,i)},i),o})(n,e,t),updateBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getBinding(t.id);if(!o)return null;const r=e.getBindingUtil(o),s={...o,fromId:t.fromId??o.fromId,toId:t.toId??o.toId,props:t.props?r.validateProps({...o.props,...t.props}):o.props,meta:t.meta??o.meta};if(!ze(e,s))throw new Error(`Invalid binding endpoints for ${s.type} binding`);const a=new Set;return Ne(e,[o.fromId,o.toId,s.fromId,s.toId],a),G(e).atomic(()=>{const t=e.bindings.getConflictingBindings(s).map(e=>e.id);t.length>0&&e.bindings.cleanupBindings(t,i),G(e).put([s],i),e.bindings.syncUpdatedBinding(o,s,i),Ne(e,[o.fromId,o.toId,s.fromId,s.toId],a),Ue(e,a,new Set,i)},i),s})(n,e,t),deleteBinding:(e,t)=>((e,t,n)=>{const i=n?.source??"user",o=e.getBinding(t);return!!o&&(G(e).atomic(()=>{e.bindings.cleanupBindings([o.id],i),G(e).remove([o.id],i)},i),!0)})(n,e,t),setCurrentPageId(e,t){((e,t,n)=>{e.setCurrentPage(t,n?.source??"system")})(n,e,t)},setCamera(e,t){((e,t,n)=>{e.setCamera(t.camera,{pageId:t.pageId,source:n?.source??"system"})})(n,e,t)},setSelectedShapeIds(e,t){((e,t,n)=>{e.setSelectedShapeIds(t,{source:n?.source??"user"})})(n,e,t)},setActiveTool(e,t){((e,t,n)=>{const i=n?.source??"system";e.tools.setActiveTool(t),e.completeEditing(i),e.updateSession({activeToolId:t},i)})(n,e,t)},setToolLocked(e,t){((e,t,n)=>{const i=n?.source??"system";e.tools.setToolLocked(t),e.updateSession({isToolLocked:t},i)})(n,e,t)}}),this.bindings.repairLoadedBindings("system"),this.registerBuiltInInteractions(),this.registerBuiltInShortcuts(),this.registerBuiltInSideEffects()}registerBuiltInInteractions(){this.interactions.register(function(){let e=!1,t=null;const n=()=>{t=null};return{id:"land.camera.canvas-pan",editorEvent:{handleEvent(i,o){if("cancel"===o.type)return"blur"!==o.reason&&"dispose"!==o.reason||(e=!1),n(),"continue";if("keyboard"===o.type&&(e=>"Space"===e.code)(o)){if("key_up"===o.name){const t=e;return e=!1,t?"handled":"continue"}return i.getShapeEditingSession()?"continue":(e=!0,"handled")}if("pointer"!==o.type||"mouse"!==o.pointerType)return"continue";if("pointer_down"===o.name){n();const r=((e,{allowLeftButton:t})=>1===e.button?4:t&&0===e.button?1:null)(o,{allowLeftButton:i.inputs.isSpacePressed.get()&&!i.getShapeEditingSession()});return null===r?"continue":(i.resetPointerClickTracking(),0===o.button&&(e=!0),t={pointerId:o.pointerId,buttons:r,camera:ko(i,o.screenPoint)},"handled")}return t&&o.pointerId===t.pointerId?"pointer_move"===o.name?0===(o.buttons&t.buttons)?(n(),"handled"):(Co(i,t.camera,o.screenPoint),"handled"):"pointer_up"===o.name||"pointer_cancel"===o.name?(n(),"handled"):"continue":"continue"}}}}())}registerBuiltInShortcuts(){this.shortcuts.registerEditorShortcut("move-selection-backward",{key:"ArrowDown",altKey:!0}),this.shortcuts.registerEditorShortcut("move-selection-forward",{key:"ArrowUp",altKey:!0}),this.shortcuts.registerEditorShortcut("undo",{key:"z",accelKey:!0}),this.shortcuts.registerEditorShortcut("redo",{key:"z",accelKey:!0,shiftKey:!0}),this.shortcuts.registerEditorShortcut("delete-selection","Backspace"),this.shortcuts.registerEditorShortcut("delete-selection","Delete"),this.shortcuts.registerEditorShortcut("reset-interaction","Escape")}registerBuiltInSideEffects(){this.sideEffects.registerBeforeDeleteHandler("shape",(e,t)=>{this.bindings.cleanupBindingsForDeletedShapes(e,t)}),this.sideEffects.registerAfterDeleteHandler("shape",(e,t)=>{this.removeShapeIdsFromSelection(e,t),this.removeShapeIdsFromEditingSession(e,t)})}dispatch(e){const t=this.normalizeEvent(e);if(this.inputs.handleEvent(t),"keyboard"===t.type&&"key_down"===t.name){const e=this.shortcuts.getTargetForEvent(t);if(e&&this.runKeyboardShortcutTarget(e))return}if("wheel"!==t.type)if("cancel"!==t.type){if("pointer"===t.type&&"pointer_cancel"===t.name)return this.interactions.broadcastEvent(this,t),void this.cancelInteractionAndClearTransients("pointer_cancel",{notifyInteractionHandlers:!1});if("handled"!==this.interactions.handleEvent(this,t)&&(this.tools.dispatch(t),"pointer"===t.type&&"pointer_up"===t.name)){const e=this.getDoubleClickEvent(t);e&&"handled"!==this.interactions.handleEvent(this,e)&&this.tools.dispatch(e)}}else this.cancelInteractionAndClearTransients(t.reason);else this.handleWheelEvent(t)}handleInteractionEvent(e){const t=this.normalizeEvent(e);return this.inputs.handleEvent(t),"handled"===this.interactions.handleEvent(this,t)}runKeyboardShortcutTarget(e){switch(e.type){case"action":return!1;case"editor":return this.runEditorKeyboardShortcut(e.command);case"tool":return this.commands.setActiveTool(e.toolId,{source:"system"}),!0}}runEditorKeyboardShortcut(e){switch(e){case"delete-selection":return!this.getShapeEditingSession()&&(this.deleteSelection("user"),!0);case"move-selection-backward":return this.moveSelectionWithinParent("backward","user");case"move-selection-forward":return this.moveSelectionWithinParent("forward","user");case"redo":return this.redo(),!0;case"reset-interaction":return"handled"===this.interactions.broadcastEvent(this,{type:"cancel",reason:"escape"})?(this.tools.cancel("escape"),this.inputs.resetPointer(),this.clearSelectionTransients(),!0):(this.tools.isActiveToolInInitialState()&&"select"!==this.getActiveToolId()?this.commands.setActiveTool("select",{source:"system"}):this.cancelInteractionAndClearTransients("escape"),!0);case"undo":return this.undo(),!0}}normalizeEvent(e){if("pointer"!==e.type)return e;if("pointer_up"===e.name){const t=e.clickCount===this.currentPointerClickCount?e:{...e,clickCount:this.currentPointerClickCount};return this.lastPointerUpForClickCount={timestamp:t.timestamp,screenPoint:t.screenPoint.clone()},t}if("pointer_down"!==e.name)return e;const t=this.lastPointerDownForClickCount,n=this.lastPointerUpForClickCount,i=t&&n&&n.timestamp>=t.timestamp&&e.timestamp-n.timestamp<=250&&n.screenPoint.dist2(e.screenPoint)<=1600?2:1;return this.lastPointerDownForClickCount={timestamp:e.timestamp,screenPoint:e.screenPoint.clone()},this.currentPointerClickCount=i,e.clickCount===i?e:{...e,clickCount:i}}getDoubleClickEvent(e){return(e.clickCount??1)<2||this.currentPointerClickCount<2?null:{type:"click",name:"double_click",phase:"up",timestamp:e.timestamp,pointerId:e.pointerId,button:e.button,buttons:e.buttons,pointerType:e.pointerType,screenPoint:e.screenPoint.clone(),pagePoint:e.pagePoint.clone(),pressure:e.pressure,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}listen(e){return this.store.listen(t=>e(t))}getRenderItems(){return this.renderItemsSignal.get()}getPages(){return this.pagesSignal.get()}getDocumentMetadataRecord(){const e=this._internalStore.get(xI);return g(e)?e:void 0}getCurrentPageId(){return this.currentPageIdSignal.get()}getActiveToolId(){return this.sessionSignal.get().activeToolId}isToolLocked(){return this.sessionSignal.get().isToolLocked}isActiveToolInInitialState(){return this.tools.isActiveToolInInitialState()}getEditingShapeId(){return this.editingShapeIdSignal.get()}getShapeEditingSession(){return this.shapeEditingSessionSignal.get()}getShapeEditingEntryRequest(){return this.shapeEditingEntryRequestSignal.get()}resetPointerClickTracking(){this.lastPointerDownForClickCount=null,this.lastPointerUpForClickCount=null,this.currentPointerClickCount=1}getCurrentPageShapeIds(){return this.currentPageShapeIdsSignal.get()}getPage(e){const t=this._internalStore.get(e);return p(t)?t:void 0}getCurrentCamera(){return this.camera.getCurrentCamera()}undo(){return this.history.getActiveScope()||this.cancelInteractionForCommand(),this.history.undo()}redo(){return this.history.getActiveScope()||this.cancelInteractionForCommand(),this.history.redo()}createPageAndSelect(e,t="user"){const n=this.commands.createPage(e,{source:t});return this.commands.setCurrentPageId(n.id,{source:t}),n}selectPage(e,t="user"){this.commands.setCurrentPageId(e,{source:t})}renamePage(e,t,n="user"){this.commands.renamePage({id:e,name:t},{source:n})}updateDocumentMeta(e,t="user"){return this.commands.updateDocumentMeta({patch:e},{source:t})}updatePageMeta(e,t,n="user"){return this.commands.updatePageMeta({id:e,patch:t},{source:n})}deletePage(e,t="user"){return this.cancelInteractionForCommand(),this.commands.deletePage(e,{source:t})}setActiveTool(e,t="system"){this.commands.setActiveTool(e,{source:t})}setToolLocked(e,t="system"){this.commands.setToolLocked(e,{source:t})}toggleToolLocked(e="system"){this.setToolLocked(!this.isToolLocked(),e)}getCamera(e=this.getCurrentPageId()){return this.camera.getCamera(e)}pageToScreen(e,t=this.getCurrentPageId()){return this.camera.pageToScreen(e,t)}screenToPage(e,t=this.getCurrentPageId()){return this.camera.screenToPage(e,t)}getSelectedShapeIds(e=this.getCurrentPageId()){return this.getSessionRecord().pageSelectedShapeIdsById[e]??[]}isShapeHidden(e){const t=new Set;let n=this.getShape(e);for(;n;){if(n.isHidden)return!0;if(!n.parentId.startsWith("shape:"))return!1;const e=n.parentId;if(t.has(e))return!1;t.add(e);const i=this.getShape(e);if(!i)return!1;if(!this.getShapeUtil(i).isChildVisible(i,n,{editor:this}))return!0;n=i}return!1}getSelectedShapes(){return this.selectedShapesSignal.get()}getDefaultShapeProps(e){const t=this.shapeUtils.get(e),n=this._shapeDefaultPropsByTypeSignal.get().get(e)??{};return t.validateProps({...t.getDefaultProps(),...n})}updateDefaultShapeProps(e,t){const n=this.shapeUtils.get(e),i=this._shapeDefaultPropsByTypeSignal.get().get(e)??{},o=n.validateProps({...n.getDefaultProps(),...i,...t}),r=n.validateProps(n.getDefaultProps()),s={};for(const[l,d]of Object.entries(o))r[l]!==d&&(s[l]=d);if(((e,t)=>{if(e===t)return!0;const n=Object.entries(e),i=Object.entries(t);if(n.length!==i.length)return!1;for(const[o,r]of n)if(!ct(r,t[o]))return!1;return!0})(i,s))return;const a=new Map(this._shapeDefaultPropsByTypeSignal.get());0===Object.keys(s).length?a.delete(e):a.set(e,s),this._shapeDefaultPropsByTypeSignal.set(a)}getSelectionParentOrderState(){return this.hierarchy.getSelectionParentOrderState()}getSelectionGroupState(){return this.hierarchy.getSelectionGroupState()}canGroupSelection(){return this.hierarchy.canGroupSelection()}canGroupShapes(e){return this.hierarchy.canGroupShapes(e)}groupShapes(e,t="user"){return this.hierarchy.groupShapes(e,t)}groupSelection(e="user"){return this.hierarchy.groupSelection(e)}getUngroupableSelectedShapeIds(){return this.hierarchy.getUngroupableSelectedShapeIds()}getUngroupableShapeIds(e){return this.hierarchy.getUngroupableShapeIds(e)}canUngroupSelection(){return this.hierarchy.canUngroupSelection()}canUngroupShapes(e){return this.hierarchy.canUngroupShapes(e)}ungroupShapes(e,t="user"){return this.hierarchy.ungroupShapes(e,t)}ungroupSelection(e="user"){return this.hierarchy.ungroupSelection(e)}getSelectionSiblingOrderState(){return this.hierarchy.getSelectionSiblingOrderState()}canMoveSelectionWithinParent(e){return this.hierarchy.canMoveSelectionWithinParent(e)}canMoveSelectionInParentOrder(e){return this.hierarchy.canMoveSelectionInParentOrder(e)}canMoveShapesInParentOrder(e,t){return this.hierarchy.canMoveShapesInParentOrder(e,t)}moveShapesInParentOrder(e,t,n="user"){return this.hierarchy.moveShapesInParentOrder(e,t,n)}moveShapesToParentOrderEdge(e,t,n="user"){return this.hierarchy.moveShapesToParentOrderEdge(e,t,n)}moveSelectionWithinParent(e,t="user"){return this.hierarchy.moveSelectionWithinParent(e,t)}canAlignSelection(){return this.selectionLayout.canAlign()}alignSelection(e,t="user"){return this.cancelInteractionForCommand(),this.selectionLayout.align(e,t)}canDistributeSelection(){return this.selectionLayout.canDistribute()}distributeSelection(e,t="user"){return this.cancelInteractionForCommand(),this.selectionLayout.distribute(e,t)}moveShapesToParentPlacementResult(e,t="user"){return this.hierarchy.moveShapesToParentPlacementResult(e,t)}moveSelectionInParentOrder(e,t="user"){return this.hierarchy.moveSelectionInParentOrder(e,t)}moveSelectionToParentOrderEdge(e,t="user"){return this.hierarchy.moveSelectionToParentOrderEdge(e,t)}canEditShape(e){return this.editing.canEditShape(e)}startEditingShape(e,t="user"){return this.editing.start(e,t)}completeEditing(e="user"){return this.editing.complete(e)}cancelEditing(e="user"){return this.editing.cancel(e)}setShapeEditingComposition(e,t="system"){this.editing.setComposition(e,t)}consumeShapeEditingEntryRequest(e){this.editing.consumeEntryRequest(e)}deleteSelection(e="user"){this.deleteShapesById(this.getSelectedShapeIds(),e)}deleteShapesById(e,t="user"){const n=Array.from(new Set(e));0!==n.length&&(this.cancelInteractionForCommand(),this.commands.deleteShapes(n,{source:t}))}setShapesHidden(e,t,n="user"){const i=this.bindings.getShapeHierarchyMemberIds(e),o=Array.from(new Set(i.filter(e=>{const n=this.getShape(e);return!!n&&n.isHidden!==t})));return 0===o.length?[]:(this.cancelInteractionForCommand(),this.commands.updateShapes(o.map(e=>({id:e,isHidden:t})),{source:n}),t&&(this.removeShapeIdsFromSelection(this.getShapeIdsIncludingDescendants(o),n),this.removeShapeIdsFromEditingSession(this.getShapeIdsIncludingDescendants(o),n)),o)}setShapesLocked(e,t,n="user"){const i=this.bindings.getShapeHierarchyMemberIds(e),o=Array.from(new Set(i.filter(e=>{const n=this.getShape(e);return!!n&&n.isLocked!==t})));return 0===o.length?[]:(this.cancelInteractionForCommand(),this.commands.updateShapes(o.map(e=>({id:e,isLocked:t})),{source:n}),t&&(this.removeShapeIdsFromSelection(this.getShapeIdsIncludingDescendants(o),n),this.removeShapeIdsFromEditingSession(this.getShapeIdsIncludingDescendants(o),n)),o)}createClipboardPayloadFromSelection(){return this.clipboard.createPayloadFromSelection()}pasteClipboardPayload(e){return this.clipboard.pastePayload(e)}duplicateSelection(e={}){return this.clipboard.duplicateSelection(e)}selectAllCurrentPage(e="user"){this.cancelInteractionForCommand(),this.selection.selectAllCurrentPage(e)}resetSelectionRotation(e="user"){((e,t="user")=>{if(!e.canRotateSelection())return;const n=e.getSelectedShapes().filter(t=>e.getShapeUtil(t).contributesToSelectionFrame(t,{editor:e}));if(0===n.length)return;const i=n.flatMap(t=>{const n=en(e,t);if(!n)return[];const i=tn(e,t,n,{id:t.id,rotation:0});return i?[i]:[]});i.length>0&&e.commands.updateShapes(i,{source:t})})(this,e)}flipSelection(e,t="user"){const n=function(e,t){if(!e.canFlipSelection())return[];const n=e.getSelectionTransformTargetShapes(),i=e.getSelectionFrame()??((e,t)=>{const n=t.flatMap(t=>{const n=en(e,t);return n?e.getShapeUtil(t).getSelectionPagePoints(n)??[]:[]});if(0===n.length)return null;const i=SI.FromPoints(n);return{bounds:i,rotation:0,rotationCenter:i.center,hasCompatibleRotation:!0}})(e,n);return i&&0!==n.length?n.map(n=>((e,t,n,i)=>{const o=e.getShapeUtil(t),r=en(e,t);if(!r)return null;const s=o.getSelectionPagePoints(r);if(!s&&!o.contributesToSelectionFrame(t,{editor:e}))return null;const a=(({points:e,transform:t})=>0===e.length?null:SI.FromPoints(e.map(e=>Ii(e,t))))({points:s?[...s]:o.getPositionedOutlineVertices(t).map(n=>e.computeShapePositionedToPageTransform(t).applyToPoint(n)),transform:n});return a?tn(e,t,r,o.flipSelectionBounds(r,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:Ti({axis:i,bounds:a,selectionBounds:n.bounds}),selectionRotation:n.rotation,selectionRotationCenter:n.rotationCenter})):null})(e,n,i,t)).filter(e=>null!==e):[]}(this,e);0!==n.length&&(this.cancelInteractionForCommand(),this.commands.updateShapes(n,{source:t}))}getShape(e){const t=this._internalStore.get(e);return f(t)?t:void 0}getAsset(e){const t=this._internalStore.get(e);return y(t)?t:void 0}getAssets(){return this._internalStore.getAll().filter(y).sort((e,t)=>e.id.localeCompare(t.id))}resolveAssetUrl(e){return this.assetUrlResolver(e)}getUnreferencedAssetIdsAfterShapeDelete(e){if(0===e.length)return[];const t=new Set(e),n=new Set,i=new Set;for(const o of this._internalStore.getAll().filter(f)){const e=dt(o);e&&(t.has(o.id)?n.add(e):i.add(e))}return this.getAssets().map(e=>e.id).filter(e=>n.has(e)&&!i.has(e))}getShapeSignal(e){let t=this.shapeSignals.get(e);return t||(t=l(`editor.shape.${e}`,()=>{const t=this._internalStore.getRecordSignal(e).get();return f(t)?t:void 0}),this.shapeSignals.set(e,t)),t}getShapeContentCutoutLocalPolygonsSignal(e){let t=this.shapeContentCutoutLocalPolygonSignals.get(e);return t||(t=l(`editor.shapeContentCutouts.${e}`,()=>{const t=this.getShapeSignal(e).get();return t?this.queries.getBindingsToShapeSignal(e).get().flatMap(e=>{const n=this.getShapeSignal(e.fromId).get();return n?this.getBindingUtil(e).getTargetShapeContentCutoutLocalPolygons?.(this,e,{fromShape:n,toShape:t})??[]:[]}):[]},{isEqual:tt}),this.shapeContentCutoutLocalPolygonSignals.set(e,t)),t}getShapeLocalToPageTransformSignal(e){return this.queries.getShapeLocalToPageTransformSignal(e)}getShapeSelectedSignal(e){let t=this.shapeSelectedSignals.get(e);return t||(t=l(`editor.shapeSelected.${e}`,()=>this.selectedShapeIdSetSignal.get().has(e)),this.shapeSelectedSignals.set(e,t)),t}getShapeRenderOrderSignal(e){let t=this.shapeRenderOrderSignals.get(e);return t||(t=l(`editor.shapeRenderOrder.${e}`,()=>this.shapeRenderOrderByIdSignal.get().get(e)??-1),this.shapeRenderOrderSignals.set(e,t)),t}getShapeRenderVisibleSignal(e){let t=this.shapeRenderVisibleSignals.get(e);return t||(t=l(`editor.shapeRenderVisible.${e}`,()=>{const t=this.getShapeClipAncestorIdsSignal(e).get().length>0;return this.renderVisibleShapeIdSetSignal.get().has(e)&&this.getShapeDocumentVisibleSignal(e).get()&&(!t||null!==this.getShapeClippedPageBounds(e))}),this.shapeRenderVisibleSignals.set(e,t)),t}getShapeDocumentVisibleSignal(e){let t=this.shapeDocumentVisibleSignals.get(e);return t||(t=l(`editor.shapeDocumentVisible.${e}`,()=>{const t=new Set([e]);let n=this.getShapeSignal(e).get();if(!n)return!1;for(;n;){if(n.isHidden)return!1;if(!n.parentId.startsWith("shape:"))return!0;const e=n.parentId;if(t.has(e))return!0;t.add(e);const i=this.getShapeSignal(e).get();if(!i)return!0;if(!this.getShapeUtil(i).isChildVisible(i,n,{editor:this}))return!1;n=i}return!0}),this.shapeDocumentVisibleSignals.set(e,t)),t}getShapeEffectiveOpacitySignal(e){let t=this.shapeEffectiveOpacitySignals.get(e);return t||(t=l(`editor.shapeEffectiveOpacity.${e}`,()=>{const t=new Set([e]);let n=1,i=this.getShapeSignal(e).get();for(;i&&(n*=i.opacity,i.parentId.startsWith("shape:"));){const e=i.parentId;if(t.has(e))break;t.add(e),i=this.getShapeSignal(e).get()}return n}),this.shapeEffectiveOpacitySignals.set(e,t)),t}getShapeEditingSessionForShapeSignal(e){let t=this.shapeEditingSessionSignals.get(e);return t||(t=l(`editor.shapeEditingSessionForShape.${e}`,()=>{const t=this.shapeEditingSessionSignal.get();return t?.shapeId===e?t:null}),this.shapeEditingSessionSignals.set(e,t)),t}getShapeDropTargetSignal(e){let t=this.shapeDropTargetSignals.get(e);return t||(t=l(`editor.shapeDropTarget.${e}`,()=>this.dropTargetShapeIdSignal.get()===e),this.shapeDropTargetSignals.set(e,t)),t}getShapeHoveredSignal(e){let t=this.shapeHoveredSignals.get(e);return t||(t=l(`editor.shapeHovered.${e}`,()=>{const t=this.hoveredShapeIdSignal.get();if(!t)return!1;const n=this.getShapeSignal(e).get();return!!n&&this.getShapeUtil(n).getHoverDecorationTargetId(n,{editor:this})===t}),this.shapeHoveredSignals.set(e,t)),t}getShapeSelectedDescendantTransformAncestorSignal(e){let t=this.shapeSelectedDescendantTransformAncestorSignals.get(e);return t||(t=l(`editor.shapeSelectedDescendantTransformAncestor.${e}`,()=>{if(this.getShapeSelectedSignal(e).get())return!1;const t=this.getShapeSignal(e).get();return!(!t||!this.getShapeUtil(t).isSelectionTransformContainer(t))&&this.selectedShapeIdsSignal.get().some(t=>this.hierarchy.isShapeDescendantOf(t,e))}),this.shapeSelectedDescendantTransformAncestorSignals.set(e,t)),t}getBinding(e){const t=this._internalStore.get(e);return S(t)?t:void 0}getShapesForPage(e){return this.queries.getShapesForPage(e)}getBindingsFromShape(e){return this.queries.getBindingsFromShape(e)}getBindingsFromShapeSignal(e){return this.queries.getBindingsFromShapeSignal(e)}getBindingsToShape(e){return this.queries.getBindingsToShape(e)}getBindingsToShapeSignal(e){return this.queries.getBindingsToShapeSignal(e)}getBindingsForShape(e){return this.queries.getBindingsForShape(e)}getBindingsForShapeSignal(e){return this.queries.getBindingsForShapeSignal(e)}getChildShapeIds(e){return this.queries.getChildShapeIds(e)}getChildShapes(e){return this.queries.getChildShapes(e)}getDescendantShapeIds(e){return this.queries.getDescendantShapeIds(e)}getDescendantPageBounds(e){return this.queries.getDescendantPageBounds(e)}getShapeSubtreePageBounds(e){return this.queries.getShapeSubtreePageBounds(e)}getShapePageId(e){return this.queries.getPageIdForShape(e)}isShapeOrAncestorLocked(e){return this.hierarchy.isShapeOrAncestorLocked(e)}hasLockedDescendant(e){return this.hierarchy.hasLockedDescendant(e)}getOutermostSelectableShapeId(e){return this.hierarchy.getOutermostSelectableShapeId(e)}getShapeIdsIncludingDescendants(e){return this.hierarchy.getShapeIdsIncludingDescendants(e)}getShapeIdsForSelectionTransform(e){return this.hierarchy.getShapeIdsForSelectionTransform(e)}getShapeIdsForSelectionRotation(e){return this.hierarchy.getShapeIdsForSelectionRotation(e)}getSelectionTransformTargetShapes(){return this.hierarchy.getSelectionTransformTargetShapes()}canResizeSelection(){return this.hierarchy.canResizeSelection()}canFlipSelection(){return this.selectionCanFlipSignal.get()}canRotateSelection(){return this.hierarchy.canRotateSelection()}getSelectionResizeTargetShapes(){return this.hierarchy.getSelectionResizeTargetShapes()}getSelectionRotationTargetShapes(){return this.hierarchy.getSelectionRotationTargetShapes()}getShapeExportTraversalIds(e){return this.hierarchy.getShapeExportTraversalIds(e)}getShapeContainment(e,t){return this.queries.getShapeContainment(e,t)}getContainingShapeParentId(e){return this.queries.getContainingShapeParentId(e)}getContainingShapeParentIdAtPoint(e,t){return this.queries.getContainingShapeParentIdAtPoint(e,t)}getContainingParentIdForShapeRecord(e){return this.queries.getContainingParentIdForShapeRecord(e)}getShapeClipAncestorIds(e){return this.queries.getShapeClipAncestorIds(e)}getShapeClipAncestorIdsSignal(e){return this.queries.getShapeClipAncestorIdsSignal(e)}isPagePointInShapeClip(e,t){return this.queries.isPagePointInShapeClip(e,t)}getShapeClippedPageBounds(e){return this.queries.getShapeClippedPageBounds(e)}getShapeIdsInContainerBounds(e,t={}){return this.hierarchy.getShapeIdsInContainerBounds(e,t)}canUseShapeParent(e,t){return this.hierarchy.canUseShapeParent(e,t)}getShapeUtil(e){return this.shapeUtils.get(e.type)}getBindingUtil(e){return this.bindingUtils.get(e.type)}computeShapePositionedBounds(e){return this.geometry.computeShapePositionedBounds(e)}computeShapeLocalBounds(e){return this.geometry.computeShapeLocalBounds(e)}computeShapeRenderBounds(e){return this.geometry.computeShapeRenderBounds(e)}computeShapeExportBounds(e){return this.geometry.computeShapeExportBounds(e)}computeShapeLocalToPageTransform(e){return this.geometry.computeShapeLocalToPageTransform(e)}computeShapeRenderToPageTransform(e){return this.geometry.computeShapeRenderToPageTransform(e)}computeShapeExportToPageTransform(e){return this.geometry.computeShapeExportToPageTransform(e)}computeShapePageBounds(e){return this.geometry.computeShapePageBounds(e)}computeShapeExportPageBounds(e){return this.geometry.computeShapeExportPageBounds(e)}computeShapeGeometry(e){return this.geometry.computeShapeGeometry(e)}computeShapePositionedToPageTransform(e){return this.geometry.computeShapePositionedToPageTransform(e)}computeShapePageCenter(e){return this.geometry.computeShapePageCenter(e)}computeShapePageCorners(e){return this.geometry.computeShapePageCorners(e)}computeShapePageOutlineVertices(e){return this.geometry.computeShapePageOutlineVertices(e)}getShapePositionedBounds(e){return this.geometry.getShapePositionedBounds(e)}getShapePageBounds(e){return this.geometry.getShapePageBounds(e)}getShapeGeometry(e){return this.geometry.getShapeGeometry(e)}getShapePositionedToPageTransform(e){return this.geometry.getShapePositionedToPageTransform(e)}getShapePageCenter(e){return this.geometry.getShapePageCenter(e)}getShapePageCorners(e){return this.geometry.getShapePageCorners(e)}getShapePageOutlineVertices(e){return this.geometry.getShapePageOutlineVertices(e)}getSelectionPageBounds(){return this.geometry.getSelectionPageBounds()}getSelectionFrame(){return this.geometry.getSelectionFrame()}isPointInSelectionBounds(e){return this.geometry.isPointInSelectionBounds(e)}getSelectionFrameLocalBoundsPoint(e){return this.geometry.getSelectionFrameLocalBoundsPoint(e)}getSelectionPageOutlineVertices(){return this.geometry.getSelectionPageOutlineVertices()}getSelectionAnchorPagePoint(){return this.geometry.getSelectionAnchorPagePoint()}hitTestSelectionHandle(e){const t=this.selectedShapesSignal.get(),n=this.getSelectionFrame();if(0===t.length)return null;const i=1===t.length,o=this.canResizeSelection(),r=this.canRotateSelection(),{terminalHandles:s,middleHandles:a,customHandles:l,rotateHandles:d,resizeHandles:c}=((e,t,n,i,o,r,s)=>ro(oo(e,t,n,i,o,r,s),n))(t,n,this.getCurrentCamera().z,e=>this.getShapeUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:i,editor:this}),e=>o&&this.getShapeUtil(e).canUseSelectionResizeHandles(e,{editor:this}),e=>r&&this.getShapeUtil(e).canUseSelectionRotateHandle(e,{editor:this}),Li(this,this.getSelectionResizeTargetShapes(),n?.rotation??0));for(const u of a)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of s)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of l)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;for(const u of c)if(u.bounds.containsPoint(e))return u;if(n){const t=((e,t,n,i)=>{const o=new Set(n.map(e=>e.id)),r=Ii(e,t),{bounds:s}=t,a=[];r.x>=s.minX&&r.x<=s.maxX&&(o.has("top")&&a.push({id:"top",distance:Math.abs(r.y-s.minY)}),o.has("bottom")&&a.push({id:"bottom",distance:Math.abs(r.y-s.maxY)})),r.y>=s.minY&&r.y<=s.maxY&&(o.has("right")&&a.push({id:"right",distance:Math.abs(r.x-s.maxX)}),o.has("left")&&a.push({id:"left",distance:Math.abs(r.x-s.minX)}));const l=a.filter(e=>e.distance<=i).sort((e,t)=>e.distance-t.distance)[0];return l?{kind:"resize",id:l.id,point:e.clone(),bounds:new SI(e.x-i,e.y-i,2*i,2*i)}:null})(e,n,c,6/this.getCurrentCamera().z);if(t)return t}for(const u of d)if(u.bounds.expand(6/this.getCurrentCamera().z).containsPoint(e))return u;return null}setBrushBox(e){this.transients.setBrushBox(e)}setBindingPreview(e){this.transients.setBindingPreview(e)}setTerminalBindingGuides(e){this.transients.setTerminalBindingGuides(e)}setDropTargetShapeId(e){this.transients.setDropTargetShapeId(e)}setHoveredShapeId(e){this.transients.setHoveredShapeId(e)}setSelectionTranslationActive(e){this.transients.setSelectionTranslationActive(e)}setSnapIndicators(e){this.transients.setSnapIndicators(e)}setTerminalBindingResolver(e){this.transients.setTerminalBindingResolver(e)}resolveTerminalBinding(e){return this.transients.resolveTerminalBinding(e)}clearSelectionTransients(){this.transients.clearSelectionTransients()}hitTestShape(e){return this.hitTestShapesAtPoint(e)[0]??null}hitTestShapesAtPoint(e,t){return this.spatialIndex.getShapesAtPoint(e,{...t,filter:n=>!this.isShapeHidden(n.id)&&this.isPagePointInShapeClip(n.id,e)&&(t?.filter?.(n)??!0)})}hitTestShapesByLineSegment(e,t,n){return this.spatialIndex.getShapesHitByLineSegment(e,t,{...n,filter:e=>!this.isShapeHidden(e.id)&&(n?.filter?.(e)??!0)})}getShapeIdsInBounds(e,t){return this.spatialIndex.getShapeIdsInBounds(e,t).filter(e=>!this.isShapeHidden(e))}getShapesInBounds(e,t){return this.spatialIndex.getShapesInBounds(e,t).filter(e=>!this.isShapeHidden(e.id))}getShapesInViewport(e,t){return this.spatialIndex.getShapesInViewport(e,t).filter(e=>!this.isShapeHidden(e.id))}getDocumentSnapshot(){return this.snapshots.getDocumentSnapshot()}getSessionSnapshot(){return this.snapshots.getSessionSnapshot()}getSvgString(e=this.getSelectedShapeIds(),t){return function(e,t,n,i={}){const o=Array.from(t),r=e.getShapeExportTraversalIds(o),s=new Set(r),a=[],l=[];for(const v of r){const t=e.getShape(v);t?l.push(t):a.push({id:v,reason:"missing-shape"})}if(0===l.length)return null;const d=[];for(const v of l){if(!e.getShapeUtil(v).contributesToExportBounds(v))continue;const t=N(e,v,s);t&&(q(t)?d.push(t):a.push({id:v.id,reason:"missing-bounds"}))}if(0===d.length)return null;const c=(e=>{let t=1/0,n=1/0,i=-1/0,o=-1/0;for(const r of e)t=Math.min(t,r.minX),n=Math.min(n,r.minY),i=Math.max(i,r.maxX),o=Math.max(o,r.maxY);return new SI(t,n,i-t,o-n)})(d).expand(i.padding??16),u=[],h={editor:e,bounds:c,addDef(e){const t=`land-svg-def-${u.length+1}`;return u.push({...e,attrs:{...e.attrs,id:t}}),t},resolveAssetUrl:t=>e.resolveAssetUrl(t),resolveColor:e=>U(e,i.resolveThemeColor)},p=[],g=[],f=new Map,m=[],S=(t,n)=>{const i=e.computeShapeExportToPageTransform(t),o=((e,t)=>{let n=t.opacity,i=t.parentId;const o=new Set([t.id]);for(;i.startsWith("shape:");){const t=i;if(o.has(t))break;o.add(t);const r=e.getShape(t);if(!r)break;n*=r.opacity,i=r.parentId}return n})(e,t),r=((e,t,n,i,o)=>{const r=[];for(const s of H(e,t,n)){const t=W(e,s,i,o);t&&r.push(t)}return r})(e,t,s,f,h);let a={tag:"g",attrs:{transform:i.toSvgString(),opacity:1===o?void 0:o},children:[n]};for(let e=r.length-1;e>=0;e-=1)a={tag:"g",attrs:{"clip-path":`url(#${r[e]})`},children:[a]};g.push(a)},y=e=>{const t=n.get(e.type)?.toSvgForeground?.(e,h);t&&S(e,t)};for(const v of l){for(;m.length>0&&!z(e,m[m.length-1].id,v);)y(m.pop());const t=n.get(v.type);if(!t){a.push({id:v.id,reason:"missing-exporter"});continue}const i=t.toSvg(v,h);i?q(e.computeShapeExportBounds(v))?(p.push(v.id),S(v,i),t.toSvgForeground&&m.push(v)):a.push({id:v.id,reason:"missing-bounds"}):a.push({id:v.id,reason:"empty-output"})}for(;m.length>0;)y(m.pop());if(0===p.length)return null;const b=Math.max(1,c.w),x=Math.max(1,c.h),I=[];return u.length>0&&I.push({tag:"defs",children:u}),i.background&&I.push({tag:"rect",attrs:{x:c.x,y:c.y,width:c.w,height:c.h,fill:i.background}}),I.push(...g),{svg:X({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:b,height:x,viewBox:`${V(c.x)} ${V(c.y)} ${V(b)} ${V(x)}`},children:I}),bounds:c,width:b,height:x,requestedShapeIds:o,exportedShapeIds:p,skippedShapes:a}}(this,e,this.shapeSvgExporters,t)}getExportIntegrityReport(e=this.getSelectedShapeIds()){return Z({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}repairExportIntegrity(e=this.getSelectedShapeIds()){return(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),o=Z({editor:e,exporters:t,shapeIds:i});o.repairableIssueCount>0&&e.bindings.repairLoadedBindings("system");const r=Z({editor:e,exporters:t,shapeIds:i});return{before:o,after:r,repaired:o.issues.length!==r.issues.length}})({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})}getShapeCapabilityManifest(){return(({definitions:e,exporters:t,shapeUtils:n})=>{const i=e.map(e=>{const i=n.has(e.type)?"supported":"missing",o=t.has(e.type)?"supported":"missing",r="supported"===i&&"supported"===o?"supported":"missing";return{...e,shapeUtil:i,svgExporter:o,exportSupport:r}});return{entries:i,supportedExportTypes:i.filter(e=>"supported"===e.exportSupport).map(e=>e.type),missingExporterTypes:i.filter(e=>"supported"!==e.svgExporter).map(e=>e.type)}})({definitions:this.shapeCapabilityDefinitions,exporters:this.shapeSvgExporters,shapeUtils:this.shapeUtils})}createPageRecord(e){const t=this.nextPageNumber;return{id:this.createPageId(t),typeName:"page",scope:"document",name:e?.name??`Page ${t}`,index:e?.index??this.createPageIndex(t),meta:e?.meta??{}}}loadDocumentSnapshot(e,t){this.snapshots.loadDocumentSnapshot(e,t)}loadSessionSnapshot(e,t){this.snapshots.loadSessionSnapshot(e,t)}syncAfterDocumentRestore(){this.snapshots.syncAfterDocumentRestore()}cancelInteractionForCommand(){this.cancelInteractionAndClearTransients("command")}cancelInteractionAndClearTransients(e,t={}){!1!==t.notifyInteractionHandlers&&this.interactions.broadcastEvent(this,{type:"cancel",reason:e}),this.tools.cancel(e),this.inputs.resetPointer(),this.clearSelectionTransients()}syncToolStateFromSession(e){const{activeToolId:t,isToolLocked:n}=this.sessionSignal.get();this.tools.hasTool(t)?this.tools.setActiveTool(t,"restore"):(this.tools.setActiveTool("select","restore"),this.updateSession({activeToolId:"select"},e)),this.tools.setToolLocked(n)}createShapeRecord(e){const t=e.parentId??this.sessionSignal.get().currentPageId;if(!this.canUseShapeParent(t))throw new Error("Invalid parent id for shape");const n=this.nextShapeNumber,i=this.createShapeId(n),o=this.shapeUtils.get(e.type).validateProps({...this.getDefaultShapeProps(e.type),...e.props});return{id:i,typeName:"shape",scope:"document",type:e.type,parentId:t,index:e.index??this.createShapeIndex(n),x:e.x,y:e.y,rotation:e.rotation??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,opacity:e.opacity??1,isHidden:e.isHidden??!1,isLocked:e.isLocked??!1,props:o,meta:e.meta??{}}}createBindingRecord(e){const t=e.id??this.createBindingId(this.nextBindingNumber),n=this.bindingUtils.get(e.type),i=n.validateProps({...n.getDefaultProps(),...e.props});return{id:t,typeName:"binding",scope:"document",type:e.type,fromId:e.fromId,toId:e.toId,props:i,meta:e.meta??{}}}createAssetRecord(e){return{id:e.id??this.createAssetId(this.nextAssetNumber),typeName:"asset",scope:"document",type:e.type,props:e.props??{},meta:e.meta??{}}}updateSession(e,t="system"){const n=this.getSessionRecord();this._internalStore.put([{...n,...e}],t)}setCurrentPage(e,t="system"){if(!this.getPage(e))return;e!==this.getCurrentPageId()&&(this.cancelInteractionAndClearTransients("page_switch"),this.completeEditing(t));const n=this.sessionSignal.get();this.updateSession({currentPageId:e,pageCameraById:{...n.pageCameraById,[e]:n.pageCameraById[e]??{...wI}},pageSelectedShapeIdsById:{...n.pageSelectedShapeIdsById,[e]:n.pageSelectedShapeIdsById[e]??[]}},t)}setSelectedShapeIds(e,t){this.selection.setSelectedShapeIds(e,t)}removeShapeIdsFromSelection(e,t="system"){this.selection.removeShapeIdsFromSelection(e,t)}removeShapeIdsFromEditingSession(e,t="system"){this.editing.removeShapeIds(e,t)}prepareShapeIdsForRemoval(e,t="system"){this.editing.prepareForShapeRemoval(e,t)}ensurePageSessionState(e,t="system"){const n=this.sessionSignal.get(),i=n.pageCameraById[e]??{...wI},o=n.pageSelectedShapeIdsById[e]??[];this.updateSession({pageCameraById:{...n.pageCameraById,[e]:i},pageSelectedShapeIdsById:{...n.pageSelectedShapeIdsById,[e]:o}},t)}removePageSessionState(e,t,n="system"){const i=this.sessionSignal.get(),o={...i.pageCameraById},r={...i.pageSelectedShapeIdsById};delete o[e],delete r[e],this.updateSession({currentPageId:t,pageCameraById:o,pageSelectedShapeIdsById:r},n)}setCamera(e,t){this.camera.setCamera(e,t)}panCamera(e,t="system"){this.camera.panCamera(e,t)}zoomCameraAtScreenPoint(e,t,n="system"){this.camera.zoomCameraAtScreenPoint(e,t,n)}zoomCameraToScreenPoint(e,t,n="system"){this.camera.zoomCameraToScreenPoint(e,t,n)}zoomAtViewportCenter(e,t="system"){this.camera.zoomAtViewportCenter(e,t)}resetZoom(e="user"){this.camera.resetZoom(e)}setViewportScreenSize(e){this.camera.setViewportScreenSize(e)}getCurrentPageBounds(e=this.getCurrentPageId()){return this.selectionLayout.getCurrentPageBounds(e)}zoomToBounds(e,t){return this.selectionLayout.zoomToBounds(e,t)}zoomToFit(e){return this.selectionLayout.zoomToFit(e)}zoomToSelection(e){return this.selectionLayout.zoomToSelection(e)}createShapeId(e){const t=`shape:${e}`;return this.nextShapeNumber+=1,t}createShapeIndex(e){return String(e).padStart(6,"0")}createBindingId(e){const t=`binding:${e}`;return this.nextBindingNumber+=1,t}createAssetId(e){const t=`asset:${e}`;return this.nextAssetNumber+=1,t}syncShapeCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!f(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextShapeNumber=e+1}syncPageCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!p(t))continue;const n=t.id.split(":")[1]??"",i=Number("default"===n?1:n);Number.isFinite(i)&&(e=Math.max(e,i))}this.nextPageNumber=e+1}syncBindingCounter(){let e=0;for(const t of this._internalStore.getAll()){if(!S(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(!y(t))continue;const n=Number(t.id.split(":")[1]??0);Number.isFinite(n)&&(e=Math.max(e,n))}this.nextAssetNumber=e+1}dispose(){this.runtime.dispose()}createPageId(e){const t=`page:${e}`;return this.nextPageNumber+=1,t}createPageIndex(e){return String(e).padStart(4,"0")}handleWheelEvent(e){if(e.ctrlKey){const t=this.getCurrentCamera(),n=e.delta.y,i=(Math.abs(n)>10?10*Math.sign(n):n)/100;return void this.zoomCameraToScreenPoint(e.screenPoint,t.z-1*i*t.z)}this.panCamera(e.delta)}},bv=[{id:"top",normalizedAnchor:{x:.5,y:0},outwardNormal:{x:0,y:-1}},{id:"right",normalizedAnchor:{x:1,y:.5},outwardNormal:{x:1,y:0}},{id:"bottom",normalizedAnchor:{x:.5,y:1},outwardNormal:{x:0,y:1}},{id:"left",normalizedAnchor:{x:0,y:.5},outwardNormal:{x:-1,y:0}}],xv=class{getPositionedBounds(e){const t=this.getLocalBounds(e);return new SI(t.x+e.x,t.y+e.y,t.w,t.h)}getRenderBounds(e){return this.getLocalBounds(e)}getPointHitTestBounds(e,t){return this.getPositionedBounds(e)}getExportBounds(e){return this.getRenderBounds(e)}getChildClipLocalBounds(e){return null}getChildClipLocalPolygons(e){const t=this.getChildClipLocalBounds(e);return t?[Bo(t)]:null}getChildExportClipLocalBounds(e){return this.getChildClipLocalBounds(e)}getChildExportClipLocalPolygons(e){const t=this.getChildExportClipLocalBounds(e);return t?[Bo(t)]:null}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=this.getSelectionResizeLocalBounds(e);if(0!==n.x||0!==n.y)throw new Error(`Shape util "${this.type}" must implement resizeSelectionBounds for non-origin local bounds`);const i=Cn({width:t.selectionLocalBounds.w,height:t.selectionLocalBounds.h,scaleX:e.scaleX,scaleY:e.scaleY}),o=t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,r=this.validateProps({...e.props,w:i.width,h:i.height}),s=Lo(r,"w",i.width),a=Lo(r,"h",i.height),l=kn({localWidth:s,localHeight:a,scaleX:e.scaleX,scaleY:e.scaleY}),d=vi(Ln({requestedBounds:t.selectionLocalBounds,handleId:t.handleId,actualWidth:l.width,actualHeight:l.height,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,{rotation:t.selectionRotation,rotationCenter:t.selectionRotationCenter});return{id:e.id,x:d.x-s/2,y:d.y-a/2,rotation:o,scaleX:t.scaleX<0?-e.scaleX:e.scaleX,scaleY:t.scaleY<0?-e.scaleY:e.scaleY,props:r}}getAllowedSelectionResizeModes(e,t){return ev}getSelectionResizeHandleIds(e,t){return QI}flipSelectionBounds(e,t){const n=this.getSelectionPagePoints(e);if(n){const i=n.map(e=>{const n=0===t.selectionRotation?e.clone():mI.RotWith(e,t.selectionRotationCenter,-t.selectionRotation),i=Ci({axis:t.axis,bounds:t.selectionBounds,point:n});return 0===t.selectionRotation?i:mI.RotWith(i,t.selectionRotationCenter,t.selectionRotation)}),o=this.getSelectionPageMiddlePoint(e),r=o?(()=>{const e=0===t.selectionRotation?o.clone():mI.RotWith(o,t.selectionRotationCenter,-t.selectionRotation),n=Ci({axis:t.axis,bounds:t.selectionBounds,point:e});return 0===t.selectionRotation?n:mI.RotWith(n,t.selectionRotationCenter,t.selectionRotation)})():void 0;return this.updateSelectionPagePoints(e,{pagePoints:[i[0],i[1]],pageMiddlePoint:r})}const i=this.getSelectionResizeLocalBounds(e),o=0===t.selectionRotation?t.selectionLocalBounds.center:mI.RotWith(t.selectionLocalBounds.center,t.selectionRotationCenter,t.selectionRotation);return{id:e.id,x:o.x-i.center.x,y:o.y-i.center.y,rotation:2*t.selectionRotation-e.rotation,scaleX:"horizontal"===t.axis?-e.scaleX:e.scaleX,scaleY:"vertical"===t.axis?-e.scaleY:e.scaleY}}updateSelectionPagePoints(e,t){throw new Error(`Shape util "${this.type}" must implement updateSelectionPagePoints before selection can transform point-defined geometry`)}getSelectionPagePoints(e){return null}getSelectionPageMiddlePoint(e){return null}contributesToSelectionFrame(e,t){return!0}canParticipateInSelectionResize(e,t){return!0}canParticipateInSelectionFlip(e,t){return this.canParticipateInSelectionResize(e,t)}canParticipateInSelectionRotation(e,t){return!0}canUseSelectionResizeHandles(e,t){return this.canParticipateInSelectionResize(e,t)}canUseSelectionRotateHandle(e,t){return this.canParticipateInSelectionRotation(e,t)}canParticipateInSelectionTranslation(e,t){return!0}getSelectionTargetId(e,t){return e.id}getHoverTargetId(e,t){return e.id}getHoverDecorationTargetId(e,t){return e.id}getTranslateTargetId(e,t){return e.id}isSelectionTransformContainer(e){return!1}shouldRotateDescendants(e){return this.isSelectionTransformContainer(e)}shouldResizeDescendants(e){return!1}getResizeToFitDescendantsProps(e,t){return null}getMinimumChildCount(e){return 0}contributesToExportBounds(e){return!0}canUngroupChildren(e){return!1}getGroupingShapeCreateInput(e){return null}canStartTranslateFromSelectionBounds(e,t){return!0}canSnap(e,t){return!0}canSnapChildrenToSelf(e){return!1}getBoundsSnapGeometry(e){return{}}getHandleSnapGeometry(e){return{outline:Bo(this.getLocalBounds(e))}}getPositionedOutlineVertices(e){const t=this.getPositionedBounds(e);return[new mI(t.minX,t.minY),new mI(t.maxX,t.minY),new mI(t.maxX,t.maxY),new mI(t.minX,t.maxY)]}getSelectionFramePositionedOutlineVertices(e,t){return null}getSelectionHandleAnchors(e,t){return{terminalHandleAnchors:[],middleHandleAnchors:[]}}getSelectionOverlayInfo(e,t){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null,bindingSegments:[]}}getLabelPathGeometry(e,t){return null}isWrappedByBrush(e,t){return 0===t.pageOutlineVertices.length?!!t.pageBounds&&t.brushBounds.containsBox(t.pageBounds):t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return!t.isWrapping||this.isWrappedByBrush(e,t)}getLocalToPageTransform(e){const t=this.getLocalBounds(e).center;return yI.Translate(e.x+t.x,e.y+t.y).compose(yI.Rotate(e.rotation)).compose(yI.Scale(e.scaleX,e.scaleY)).compose(yI.Translate(-t.x,-t.y))}canEdit(e){return!1}canReceiveChildren(e){return!1}getChildTransformPolicy(e){return"isometry"}canReceiveChild(e,t){return this.canReceiveChildren(e)}isChildVisible(e,t,n){return!0}getChildPlacementMeta(e,t,n){return t.meta}canAutomaticallyReceiveChildren(e){return this.canReceiveChildren(e)}canBeDirectlyBrushSelected(e){return!0}canReceiveTerminalBinding(e,t){return!1}getTerminalBindingPorts(e,t){return this.canReceiveTerminalBinding(e,t)?bv:[]}getTerminalBindingOutlines(e,t){return this.canReceiveTerminalBinding(e,t)?[{points:this.getPositionedOutlineVertices(e),closed:!0}]:[]}canCopyToClipboard(e,t){return!0}repairLoadedShape(e){return null}onEditEnd(e,t){}hitTest(e,t,n){return this.getPositionedBounds(e).containsPoint(t)}hitTestBindingTarget(e,t,n){return this.hitTest(e,t,n)}hitTestLineSegment(e,t){return((e,t,n)=>{if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=Bo(n);for(let o=0;o<i.length;o+=1){const n=i[o],r=i[(o+1)%i.length];if(n&&r&&null!==Ro(e,t,n,r))return!0}return!1})(t.positionedStart,t.positionedEnd,this.getPositionedBounds(e).expand(t.positionedMargin))}resolveBindingPoint(e,t){this.getPositionedBounds(e);const n=t.editor.computeShapePositionedToPageTransform(e),i=n.tryInvert();if(!i)return t.rawPagePoint;const o=((e,t,n)=>{if(n.length<2)return null;let i=Number.POSITIVE_INFINITY;const o=t.sub(e);for(let r=0;r<n.length;r+=1){const o=n[r],s=n[(r+1)%n.length]??n[0];if(!o||!s)continue;const a=Ro(e,t,o,s);null===a||a<=1e-6||a>=i||(i=a)}return Number.isFinite(i)?e.add(o.mul(i)):null})(i.applyToPoint(t.rawPagePoint),i.applyToPoint(t.oppositePagePoint),this.getPositionedOutlineVertices(e));return o?n.applyToPoint(o):t.rawPagePoint}},Iv=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)}},vv=class extends Iv{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new wv(e,this)),this.addChild(new Pv(e,this))}},wv=class extends Iv{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",ko(this.editor,e.screenPoint))}},Pv=class extends Iv{info=null;constructor(e,t){super(e,"panning",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&Co(this.editor,this.info,e.screenPoint)}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}onExit(){this.info=null}},kv=Math.PI/180*15,Cv=Math.PI/2,Tv=Math.PI/180*5,Mv=class extends Iv{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},Ev=class extends Mv{onPointerMove(e){this.info&&this.info.originPagePoint.dist2(e.pagePoint)>=9&&this.onDragThresholdExceeded(e)}},Av=class extends Mv{operation=null;onInfoEnter(){if(this.info){const e=this.getOperationKind(this.info);this.operation=this.editor.operations.begin({kind:e,label:e,source:"user",history:"record"})}this.onDragStart()}onDragStart(){}onPointerMove(e){this.apply(e)}onTick(e){if(!this.info)return;const t=Uo(this.editor,e,this.tickMode);t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Oo(this.editor,e=>this.apply(e))}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.cancel()}},Bv=class extends Mv{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,Ho(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,No(e),Ho(e))}onTick(e){if(!this.info)return;const t=Uo(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,No(t),Ho(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,No(e),Ho(e)),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}updateBrush(e,t,n){if(!this.info)return;const i=((e,t)=>{const n=Math.min(e.x,t.x),i=Math.min(e.y,t.y),o=Math.max(e.x,t.x),r=Math.max(e.y,t.y);return new SI(n,i,o-n,r-i)})(this.info.originPagePoint,e),o=((e,t)=>{const n=[],i=new Set;for(const o of t){const t=e.getOutermostSelectableShapeId(o);i.has(t)||(i.add(t),n.push(t))}return n})(this.editor,this.editor.getShapeIdsInBounds(i).filter(e=>((e,t,n,i)=>{const o=e.getShape(n);return!(!o||!((e,t)=>{const n=e.getShape(t);return!!n&&e.getShapeUtil(n).canBeDirectlyBrushSelected(n)})(e,o.id))&&e.getShapeUtil(o).canSelectByBrush(o,{editor:e,brushBounds:t,isWrapping:i,pageOutlineVertices:e.getShapePageOutlineVertices(o.id),pageBounds:e.getShapePageBounds(o.id)})})(this.editor,i,e,n))),r=t?((e,t)=>{const n=new Set(e);for(const i of t)n.has(i)?n.delete(i):n.add(i);return Array.from(n)})(this.info.previousSelection,o):o;this.editor.setBrushBox(i),this.editor.commands.setSelectedShapeIds(r,{source:"system"})}updateBrushFromInputs(){Oo(this.editor,e=>this.updateBrush(e.pagePoint,No(e),Ho(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},Rv=class extends Av{tickMode="apply_after_scroll";constructor(e,t){super(e,"dragging_plugin_interaction",t)}getOperationKind(e){return e.session.historyMark}onDragStart(){this.info?.session.onDragStart?.({editor:this.editor})}onPointerUp(e){this.apply(e),this.complete()}onCancel(e){const t=this.info?.previousSelection;n(()=>{var e,n;t&&(e=t,n=this.editor.getSelectedShapeIds(),e.length!==n.length||!e.every((e,t)=>e===n[t]))&&this.editor.commands.setSelectedShapeIds(t,{source:"system"}),this.info&&(this.editor.clearSelectionTransients(),this.cancelOperation())}),this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}onInfoExit(){this.info?.session.shouldClearBindingPreviewOnExit&&this.editor.setBindingPreview(null),this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:i}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&i===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=i;const o=this.info.snapMode,r=this.info.snapSnapshot,s=!i&&"none"!==o&&null!==r,a=s&&r?this.editor.snaps.snapHandle({mode:o,pagePoint:e,snapshot:r,threshold:8/this.editor.getCurrentCamera().z}):null;s||this.editor.snaps.clearIndicators();const l=a?.snappedPagePoint??e,d=this.info.session.update({editor:this.editor,pagePoint:l,accelKey:i,source:"user"}),c="string"==typeof d?d:d.status,u="string"==typeof d?l:d.finalPagePoint;!a||!u||u.dist2(a.snappedPagePoint)<=1e-6||this.editor.snaps.clearIndicators(),"stop"===c&&this.complete()}complete(){const e=this.info;e&&(this.editor.setSnapIndicators(null),e.session.onComplete?.({editor:this.editor}),this.commitOperation(),this.transition("idle"))}},Lv=class extends Iv{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.editor.getSelectedShapeIds(),n=this.editor.hitTestSelectionHandle(e.pagePoint);if("rotate"===n?.kind)return void this.transition("pointing_rotate_handle",{originPagePoint:e.pagePoint.clone(),previousSelection:t});if("resize"===n?.kind)return void this.transition("pointing_resize_handle",{handleId:n.id,originPagePoint:e.pagePoint.clone(),cursorHandleOffset:e.pagePoint.sub(n.point),previousSelection:t});let i=null;if(n){const o=this.editor.getSelectedShapes()[0]??null;if(o){const r=this.editor.selectionHandleInteractions.createSession(this.editor,{handle:n,shape:o,originPagePoint:e.pagePoint.clone()});if(r){const o=r.handleSnapMode??"none";i={originPagePoint:e.pagePoint.clone(),previousSelection:t,session:r,snapSnapshot:"none"===o?null:this.editor.snaps.createHandleSnapshot({context:r.handleSnapContext??{shapeId:r.shapeId,handle:n},currentPagePoint:e.pagePoint,allowSelfSnap:r.allowSelfSnap??!1,excludedShapeIds:r.excludedSnapShapeIds})}}}}const o=this.editor.hitTestShape(e.pagePoint);let r=null;if(o){const n=this.editor.getShapeUtil(o).getSelectionTargetId(o,{editor:this.editor}),i=this.editor.getShapeUtil(o).getTranslateTargetId(o,{editor:this.editor}),s=No(e),a=Do(this.editor,n,t),l=s?null:((e,t,n)=>{const i=new Set(n);for(const o of zo(e,t))if(i.has(o.ancestorId))return o.ancestorId;return null})(this.editor,n,t),d=s?null:l?a:null,c=Do(this.editor,i,t),u=null===d?c:l??c,h=this.editor.interactions.createShapePointerSession(this.editor,{shape:o,selectionTargetId:a,originPagePoint:e.pagePoint.clone(),event:e});r={shapeId:a,translateTargetId:u,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:s,wasSelected:t.includes(a),fromSelectionBounds:!1,quickClickSelectionTargetId:d,dragSession:h}}if(!i||"binding_middle"!==n?.kind&&"custom"!==n?.kind)if(r?.dragSession)this.transition("pointing_shape",r);else if(i)this.transition("pointing_selection_handle_interaction",i);else if(r)this.transition("pointing_shape",r);else{if(!No(e)&&t.length>0){const n=this.editor.getSelectedShapes()[0];if(n&&this.editor.getShapeUtil(n).canStartTranslateFromSelectionBounds(n,{editor:this.editor})&&this.editor.isPointInSelectionBounds(e.pagePoint))return void this.transition("pointing_shape",{shapeId:n.id,translateTargetId:n.id,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:!1,wasSelected:!0,fromSelectionBounds:!0,quickClickSelectionTargetId:null,dragSession:null})}this.transition("pointing_canvas",{originPagePoint:e.pagePoint.clone(),previousSelection:t,additiveSelection:No(e)})}else this.transition("pointing_selection_handle_interaction",i)}},$v=class extends Ev{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:No(e)})}onPointerUp(e){No(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")}},Fv=class extends Ev{constructor(e,t){super(e,"pointing_resize_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");if(!this.editor.canResizeSelection())return void this.transition("idle");const t=this.editor.getSelectionResizeTargetShapes(),n=new Map(t.flatMap(e=>{const t=en(this.editor,e);return t?[[e.id,t]]:[]})),i=t.filter(e=>n.has(e.id));if(0===i.length)return void this.transition("idle");const o=((e,t,n,i)=>0===t.length?[]:Ri(e,t,n,Bi(e,t,i)))(this.editor,i,this.info.handleId,e.rotation);if(0===o.length)return void this.transition("idle");const r=(({shapes:e,selectionFrame:t,getShapeSelectionResizePageOutlineVertices:n,getShapeSelectionPagePoints:i,getShapeSelectionPageMiddlePoint:o,getShapePageRecord:r})=>{const s={rotation:t.rotation,rotationCenter:t.rotationCenter},a=[],l=[];for(const d of e){const e=r(d),t=i(e);t?l.push({shape:d,pageShape:e,startLocalPagePoint:Ii(t[0],s),endLocalPagePoint:Ii(t[1],s),middleLocalPagePoint:(()=>{const t=o(e);return t?Ii(t,s):null})()}):a.push({shape:d,pageShape:e,localBounds:SI.FromPoints(n(d).map(e=>Ii(e,s))),rotation:e.rotation})}return{startBounds:t.bounds.clone(),rotation:t.rotation,rotationCenter:t.rotationCenter.clone(),aspectRatio:0===t.bounds.h?1:t.bounds.w/t.bounds.h,shapes:a,pointShapes:l}})({shapes:i,selectionFrame:e,getShapeSelectionResizePageOutlineVertices:e=>function(e,t){const n=e.getShapeUtil(t).getSelectionResizeLocalBounds(t),i=e.computeShapeLocalToPageTransform(t);return(e=>[new mI(e.minX,e.minY),new mI(e.maxX,e.minY),new mI(e.maxX,e.maxY),new mI(e.minX,e.maxY)])(n).map(e=>i.applyToPoint(e))}(this.editor,e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.getShapeUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>n.get(e.id)});var s,a;this.transition("resizing",{...this.info,startBounds:r.startBounds,rotation:r.rotation,rotationCenter:r.rotationCenter,aspectRatio:r.aspectRatio,snapSnapshot:this.editor.snaps.createResizeSnapshot({resizingShapeIds:this.editor.getShapeIdsForSelectionTransform(this.editor.getSelectedShapeIds()),coordinateSpace:{rotation:r.rotation,rotationCenter:r.rotationCenter}}),shapes:r.shapes,pointShapes:r.pointShapes,updates:(s=r.shapes,a=r.pointShapes,[...s.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...a.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),allowedResizeModes:o,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},Uv=class extends Ev{constructor(e,t){super(e,"pointing_rotate_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.getSelectionFrame();if(!e)return void this.transition("idle");if(!this.editor.canRotateSelection())return void this.transition("idle");const t=new Map(this.editor.getSelectionRotationTargetShapes().flatMap(e=>{const t=en(this.editor,e);return t?[[e.id,t]]:[]})),n=this.editor.getSelectionRotationTargetShapes().filter(e=>t.has(e.id));if(0===n.length)return void this.transition("idle");const i=(({shapes:e,selectionFrame:t,getShapeLocalBounds:n,getShapeSelectionPagePoints:i,getShapeSelectionPageMiddlePoint:o,getShapePageRecord:r})=>{const s=[],a=[];for(const l of e){const e=r(l),t=i(e);t?a.push({shape:l,pageShape:e,startPagePoint:t[0],endPagePoint:t[1],middlePagePoint:o(e)}):s.push({shape:l,pageShape:e,localBounds:n(l),rotation:e.rotation})}return{center:t.rotationCenter.clone(),initialSelectionRotation:t.rotation,shapes:s,pointShapes:a}})({shapes:n,selectionFrame:e,getShapeLocalBounds:e=>this.editor.computeShapeLocalBounds(e),getShapeSelectionPagePoints:e=>this.editor.getShapeUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.getShapeUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>t.get(e.id)});var o,r;this.transition("rotating",{...this.info,center:i.center,startAngle:mI.Angle(i.center,this.info.originPagePoint),initialSelectionRotation:i.initialSelectionRotation,shapes:i.shapes,pointShapes:i.pointShapes,updates:(o=i.shapes,r=i.pointShapes,[...o.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...r.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),lastPointerX:NaN,lastPointerY:NaN,lastShiftKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},Ov=class extends Ev{constructor(e,t){super(e,"pointing_selection_handle_interaction",t)}onDragThresholdExceeded(){this.info&&this.transition("dragging_plugin_interaction",{...this.info,snapMode:this.info.session.handleSnapMode??"none",lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(e){if(this.info){const t={editor:this.editor,source:"user"};(e.clickCount??1)>=2&&this.info.session.onDoubleClick?this.info.session.onDoubleClick(t):this.info.session.onClick?.(t)}this.transition("idle")}onCancel(e){this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}},Dv=class extends Ev{constructor(e,t){super(e,"pointing_shape",t)}onInfoEnter(){this.info&&(this.info.quickClickSelectionTargetId||(this.info.additiveSelection?this.info.wasSelected||this.editor.commands.setSelectedShapeIds([...this.info.previousSelection,this.info.shapeId],{source:"system"}):this.info.wasSelected||this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"})))}onDragThresholdExceeded(e){if(!this.info)return;if(this.info.dragSession)return void this.transition("dragging_plugin_interaction",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,session:this.info.dragSession,snapMode:"none",snapSnapshot:null,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1});const t=this.editor.getSelectedShapes(),n=this.info.wasSelected?t.map(e=>e.id):[this.info.translateTargetId];this.info.wasSelected||1!==n.length||n[0]===this.info.shapeId||this.editor.commands.setSelectedShapeIds(n,{source:"system"});const i=this.editor.getSelectionFrame(),o=((e,t)=>t.filter(t=>{const n=e.getShape(t);return!!n&&e.getShapeUtil(n).canParticipateInSelectionTranslation(n,{editor:e})&&!e.isShapeOrAncestorLocked(n.id)&&!e.hasLockedDescendant(n.id)}).map(t=>e.getShape(t)).filter(e=>!!e).flatMap(t=>(t.parentId.startsWith("shape:")?e.computeShapeLocalToPageTransform(e.getShape(t.parentId)):yI.Identity()).tryInvert()?[{id:t.id,x:t.x,y:t.y,startLocalToPage:e.computeShapeLocalToPageTransform(t)}]:[]))(this.editor,n);if(0===o.length)return void this.transition("brushing",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,additiveSelection:No(e)});const r=o.map(e=>e.id),s=i?.hasCompatibleRotation?i.rotation:0,a=i?.rotationCenter.clone()??mI.Zero(),l=i?.hasCompatibleRotation?i.bounds.clone():this.editor.getSelectionPageBounds();var d;this.transition("translating",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,movingShapeIds:r,startBounds:l,snapSnapshot:this.editor.snaps.createTranslateSnapshot({movingShapeIds:r,coordinateSpace:{rotation:s,rotationCenter:a}}),snapRotation:s,selectedShapes:o,updates:(d=o,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 No(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")}},zv=class extends Av{tickMode="apply_after_scroll_or_without_screen_point";constructor(e,t){super(e,"resizing",t)}getOperationKind(){return"select.resize"}onDragStart(){this.editor.setSnapIndicators(null)}onPointerUp(){this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:i}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&i===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=i;const o=Yo(this.info.rotationCenter,this.info.rotation),r=Ii(e.sub(this.info.cursorHandleOffset),o),s=((e,t)=>{const n=e.includes("free"),i=e.includes("aspect_ratio_locked");return n||i?n?i&&t?"aspect_ratio_locked":"free":"aspect_ratio_locked":null})(this.info.allowedResizeModes,t);if(!s)return;const a="aspect_ratio_locked"===s,l=function({startBounds:e,handleId:t,pagePoint:n,isAspectRatioLocked:i,isResizingFromCenter:o,aspectRatio:r}){const s=o?(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.center,o=n.x-i.x,r=n.y-i.y,s=Math.max(Math.abs(o),.5),a=Math.max(Math.abs(r),.5),l=Tn(t)||Mn(t)?o*(Tn(t)?-2:2)/Math.max(1,e.w):1,d=En(t)||An(t)?r*(En(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new SI(e.minX,i.y-a,e.w,2*a),scaleX:l,scaleY:d};case"left":case"right":return{bounds:new SI(i.x-s,e.minY,2*s,e.h),scaleX:l,scaleY:d};default:return{bounds:new SI(i.x-s,i.y-a,2*s,2*a),scaleX:l,scaleY:d}}})({startBounds:e,handleId:t,pagePoint:n}):(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.minX,o=e.maxX,r=e.minY,s=e.maxY;let a=Tn(t)?i:o,l=Tn(t)?o:i,d=En(t)?r:s,c=En(t)?s:r;Tn(t)||Mn(t)?a=n.x:(a=o,l=i),En(t)||An(t)?d=n.y:(d=s,c=r);const u=a-l,h=d-c,p=Tn(t)?l-a:u,g=En(t)?c-d:h,f=Tn(t)||Mn(t)?p/Math.max(1,e.w):1,m=En(t)||An(t)?g/Math.max(1,e.h):1;return{bounds:new SI(Math.min(a,l),Math.min(d,c),Math.max(1,Math.abs(u)),Math.max(1,Math.abs(h))),scaleX:f,scaleY:m}})({startBounds:e,handleId:t,pagePoint:n});return i?$n({bounds:s.bounds,startBounds:e,handleId:t,aspectRatio:r,isResizingFromCenter:o,scaleX:s.scaleX,scaleY:s.scaleY}):s}({startBounds:this.info.startBounds,handleId:this.info.handleId,pagePoint:r,isAspectRatioLocked:a,isResizingFromCenter:n,aspectRatio:this.info.aspectRatio}),d=!i&&this.info.snapSnapshot.points.length>0,c=d?this.editor.snaps.snapResize({handleId:this.info.handleId,initialSelectionBounds:this.info.startBounds,resizedSelectionBounds:l.bounds,scaleX:l.scaleX,scaleY:l.scaleY,snapshot:this.info.snapSnapshot,threshold:8/this.editor.getCurrentCamera().z,isAspectRatioLocked:a,isResizingFromCenter:n}):l;d||this.editor.snaps.clearIndicators();const u=this.info.shapes.length+this.info.pointShapes.length===1;for(let h=0;h<this.info.shapes.length;h+=1){const e=this.info.shapes[h],t=this.info.updates[h];e&&t&&Ko(this.editor,e,this.info.startBounds,c.bounds,c.scaleX,c.scaleY,this.info.handleId,u,n,this.info.rotationCenter,this.info.rotation,t)}for(let h=0;h<this.info.pointShapes.length;h+=1){const e=this.info.pointShapes[h],t=this.info.updates[this.info.shapes.length+h];e&&t&&Xo(this.editor,e,this.info.startBounds,0,c.scaleX,c.scaleY,this.info.handleId,n,this.info.rotationCenter,this.info.rotation,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.setSnapIndicators(null),this.commitOperation(),this.transition("idle")}cancel(){this.editor.setSnapIndicators(null),this.cancelOperation(),this.transition("idle")}},Nv=class extends Av{tickMode="apply_after_scroll";constructor(e,t){super(e,"rotating",t)}getOperationKind(){return"select.rotate"}onPointerUp(){this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;if(e.x===this.info.lastPointerX&&e.y===this.info.lastPointerY&&t===this.info.lastShiftKey&&n===this.info.lastAccelKey)return;this.info.lastPointerX=e.x,this.info.lastPointerY=e.y,this.info.lastShiftKey=t,this.info.lastAccelKey=n;let i=Wo(mI.Angle(this.info.center,e)-this.info.startAngle);if(t)i=_o(i,kv);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=_o(e,Cv),n=Wo(t-e);Math.abs(n)<=Tv&&(i=Wo(t-this.info.initialSelectionRotation))}for(let o=0;o<this.info.shapes.length;o+=1){const e=this.info.shapes[o],t=this.info.updates[o];e&&t&&jo(this.editor,e,this.info.center,i,t)}for(let o=0;o<this.info.pointShapes.length;o+=1){const e=this.info.pointShapes[o],t=this.info.updates[this.info.shapes.length+o];e&&t&&Vo(this.editor,e,this.info.center,i,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.commitOperation(),this.transition("idle")}cancel(){this.cancelOperation(),this.transition("idle")}},Hv=class extends Av{tickMode="always_apply";constructor(e,t){super(e,"translating",t)}getOperationKind(){return"select.translate"}onDragStart(){this.editor.setSelectionTranslationActive(!0),this.editor.setSnapIndicators(null)}onPointerUp(e){this.complete(e.pagePoint)}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.setSelectionTranslationActive(!1),this.editor.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;const i=e.x-this.info.originPagePoint.x,o=e.y-this.info.originPagePoint.y;t?this.info.lockedAxis||0===i&&0===o||(this.info.lockedAxis=Math.abs(i)>=Math.abs(o)?"x":"y"):this.info.lockedAxis=null;let r=i,s=o;"x"===this.info.lockedAxis?s=0:"y"===this.info.lockedAxis&&(r=0);const a=this.info.startBounds;if(!n&&a&&(this.info.snapSnapshot.points.length>0||this.info.snapSnapshot.nodes.length>0)&&this.editor.inputs.state.get().screenVelocity.len()<.5&&a){const e=this.info.snapRotation,t=8/this.editor.getCurrentCamera().z,n=0===e?new mI(r,s):new mI(r,s).rot(-e),{nudge:i}=this.editor.snaps.snapTranslate({lockedAxis:this.info.lockedAxis,initialSelectionBounds:a,dragDelta:n,snapshot:this.info.snapSnapshot,threshold:t}),o=0===e?i:i.rot(e);r+="y"===this.info.lockedAxis?0:o.x,s+="x"===this.info.lockedAxis?0:o.y}else this.editor.snaps.clearIndicators();if(r!==this.info.lastDeltaX||s!==this.info.lastDeltaY){this.info.lastDeltaX=r,this.info.lastDeltaY=s;for(let e=0;e<this.info.selectedShapes.length;e+=1){const t=this.info.selectedShapes[e],n=this.info.updates[e];if(!t||!n)continue;const i=this.editor.getShape(t.id);if(!i)continue;const o=i.parentId.startsWith("shape:")?this.editor.getShape(i.parentId):null,a=(o?this.editor.computeShapeLocalToPageTransform(o):yI.Identity()).tryInvert();if(!a)continue;const l=de(a.compose(yI.Translate(r,s).compose(t.startLocalToPage)),this.editor.computeShapeLocalBounds(i),{preferredRotation:i.rotation,preferredScaleXSign:i.scaleX,preferredScaleYSign:i.scaleY});l&&Object.assign(n,l)}this.editor.commands.updateShapes(this.info.updates)}Qo(this.editor,this.info.movingShapeIds,e),((e,t,n)=>{const i=Zo(e,t,n);if(i===Go(e,t))return void e.setDropTargetShapeId(null);const o=i?e.getShape(i):null;e.setDropTargetShapeId(o?.id??null)})(this.editor,this.info.movingShapeIds,e)}complete(e){this.info&&Qo(this.editor,this.info.movingShapeIds,e),this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.commitOperation(),this.transition("idle")}cancel(){this.editor.setDropTargetShapeId(null),this.editor.setSnapIndicators(null),this.cancelOperation(),this.transition("idle")}},Wv=class extends Iv{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new Lv(e,this)),this.addChild(new $v(e,this)),this.addChild(new Bv(e,this)),this.addChild(new Dv(e,this)),this.addChild(new Hv(e,this)),this.addChild(new Fv(e,this)),this.addChild(new zv(e,this)),this.addChild(new Uv(e,this)),this.addChild(new Nv(e,this)),this.addChild(new Ov(e,this)),this.addChild(new Rv(e,this))}},_v=Tx(null),Kv=class{registry=new Map;registeredPluginIds=new Set;shapeOpacityModifiers=[];shapeOpacityModifierIds=new Set;registerShapeRenderer(e){if(this.registry.has(e.type))throw new Error(`Duplicate shape renderer type: ${e.type}.`);this.registry.set(e.type,e)}getShapeRenderer(e){return this.registry.get(e)??null}hasShapeRenderer(e){return this.registry.has(e)}getRegisteredShapeTypes(){return[...this.registry.keys()]}registerCanvasRenderPlugins(e){for(const t of e){if(this.registeredPluginIds.has(t.id))throw new Error(`Duplicate canvas render plugin id: ${t.id}.`);for(const e of t.shapeRenderers??[])this.registerShapeRenderer(e);for(const e of t.shapeOpacityModifiers??[]){if(this.shapeOpacityModifierIds.has(e.id))throw new Error(`Duplicate shape opacity modifier id: ${e.id}.`);this.shapeOpacityModifiers.push(e),this.shapeOpacityModifierIds.add(e.id)}this.registeredPluginIds.add(t.id)}}getShapeOpacity(e,t){return this.shapeOpacityModifiers.reduce((n,i)=>n*i.getOpacity(e,t),1)}},Yv=sr(),Xv=Tx(Yv),qv="var(--land-shape-hover, var(--land-selection, #2563eb))",jv=Mx(()=>{const e=ir();return((e,t,n)=>{const i=[],o=[],r=new Map(t.map(e=>[e.id,e]));for(const s of e){const e=r.get(s);if(e){for(;o.length>0&&!dr(o[o.length-1],e,r);)i.push({layer:"foreground",shapeId:o.pop()});i.push({layer:"shape",shapeId:s}),n.getShapeRenderer(e.type)?.foregroundComponent&&o.push(s)}}for(;o.length>0;)i.push({layer:"foreground",shapeId:o.pop()});return i})(or(e.retainedShapeIdsSignal),or(e.currentPageShapeHierarchySignal),ar()).map((e,t)=>"shape"===e.layer?Nx(Gv,{shapeId:e.shapeId,stackingOrder:t},e.shapeId):Nx(Zv,{shapeId:e.shapeId,stackingOrder:t},`${e.shapeId}:foreground`))}),Vv=Mx(()=>{const e=ir(),t=or(e.currentPageShapeIdsSignal),n=or(e.retainedShapeIdsSignal),i=or(e.renderVisibleShapeIdsSignal),o=or(e.shapeRenderOrderByIdSignal),r=new Set(i),s=n.map(e=>o.get(e)??-1),a=n.filter(e=>r.has(e)).map(e=>o.get(e)??-1),l=n.filter(e=>!r.has(e)),d={pageShapeCount:t.length,mountedCount:n.length,visibleCount:i.length,hiddenRetainedCount:l.length,minRenderOrder:s.length>0?Math.min(...s):null,maxRenderOrder:s.length>0?Math.max(...s):null,mountedRenderOrderSeq:s.join(","),visibleRenderOrderSeq:a.join(","),firstMountedShapeId:n[0]??null,lastMountedShapeId:n[n.length-1]??null,hiddenRetainedShapeIds:l};
41
- return Nx("pre",{"data-ui":"shape-layer-debug-summary","data-mounted-count":d.mountedCount,"data-visible-count":d.visibleCount,"data-hidden-retained-count":d.hiddenRetainedCount,"data-min-render-order":d.minRenderOrder??void 0,"data-max-render-order":d.maxRenderOrder??void 0,hidden:!0,children:JSON.stringify(d)})}),Gv=Mx(({shapeId:e,stackingOrder:t})=>{const n=ir(),i=e,o=or(n.getShapeSignal(i)),r=or(n.getShapeLocalToPageTransformSignal(i)),s=or(n.getShapeHoveredSignal(i)),a=or(n.selectionCountSignal),l=or(n.brushBoxActiveSignal),d=or(n.getShapeRenderVisibleSignal(i)),c=or(n.toolStateSignal).activeToolId,u=or(n.getShapeSelectedSignal(i)),h="select"===c&&u,p=or(n.getShapeEditingSessionForShapeSignal(i)),g=or(n.getShapeRenderOrderSignal(i)),f=or(n.getShapeDropTargetSignal(i)),m=or(n.runtime.revisionSignal),S=or(n.getShapeEffectiveOpacitySignal(i)),y=or(n.getShapeSelectedDescendantTransformAncestorSignal(i)),b=or(n.getShapeClipAncestorIdsSignal(i)),x=ar();if(!o||!r)return null;const I=x.getShapeRenderer(o.type);if(!I)return null;const v=I.component,w=I.hoverComponent,P=s&&!(1===a&&h)&&!l,k=fr(n,o,r),C=S*x.getShapeOpacity(n,i);
42
- return Hx("div",{"data-ui":"shape-instance","data-shape-id":o.id,"data-shape-type":o.type,"data-selected":h?"true":"false","data-hovered":P?"true":"false","data-drop-target":f?"true":"false","data-visible":d?"true":"false","data-render-order":g>=0?String(g):void 0,"data-clip-ancestor-count":b.length,style:{position:"absolute",display:d?void 0:"none",left:k.left,top:k.top,width:k.width,height:k.height,opacity:1===C?void 0:C,transform:k.transform,transformOrigin:k.transformOrigin,pointerEvents:"none",outline:f?"2px solid #2563eb":void 0,outlineOffset:f?4:void 0,boxShadow:f?"0 0 0 6px rgba(37, 99, 235, 0.16)":void 0,zIndex:t+1},children:[d?Hx(pr,{clipAncestorIds:b,shapeElementToPage:k.elementToPage,children:[Nx(Qv,{Component:v,shape:o,editor:n,isSelected:h,shapeEditingSession:p,renderRevision:m}),P&&w?Nx(cr,{Component:w,editor:n,shape:o}):null]}):null,d&&f?Nx(hr,{}):null,d&&y?Nx(ur,{}):null]})}),Zv=Mx(({shapeId:e,stackingOrder:t})=>{const n=ir(),i=or(n.getShapeSignal(e)),o=or(n.getShapeLocalToPageTransformSignal(e)),r=or(n.getShapeRenderVisibleSignal(e)),s=or(n.getShapeSelectedSignal(e)),a=or(n.getShapeEditingSessionForShapeSignal(e)),l=or(n.runtime.revisionSignal),d=or(n.getShapeEffectiveOpacitySignal(e)),c=or(n.getShapeClipAncestorIdsSignal(e)),u=ar();if(!i||!o)return null;const h=u.getShapeRenderer(i.type)?.foregroundComponent;if(!h)return null;const p=fr(n,i,o),g=d*u.getShapeOpacity(n,e);
43
- return Nx("div",{"data-ui":"shape-foreground","data-owner-shape-id":i.id,"data-owner-shape-type":i.type,style:{position:"absolute",display:r?void 0:"none",left:p.left,top:p.top,width:p.width,height:p.height,opacity:1===g?void 0:g,transform:p.transform,transformOrigin:p.transformOrigin,pointerEvents:"none",zIndex:t+1},children:r?Nx(pr,{clipAncestorIds:c,shapeElementToPage:p.elementToPage,children:Nx(Qv,{Component:h,shape:i,editor:n,isSelected:s,shapeEditingSession:a,renderRevision:l})}):null})}),Qv=Mx(e=>{const{Component:t,editor:n,isSelected:i,shape:o,shapeEditingSession:r}=e;
44
- return Nx(t,{editor:n,isSelected:i,shape:o,shapeEditingSession:r})}),Jv=class{selectionCustomHandleRenderers=new Map;canvasOverlays=new Map;registeredPluginIds=new Set;registerCanvasOverlay(e){if(this.canvasOverlays.has(e.id))throw new Error(`Duplicate canvas overlay id: ${e.id}.`);this.canvasOverlays.set(e.id,e)}getCanvasOverlay(e){return this.canvasOverlays.get(e)??null}hasCanvasOverlay(e){return this.canvasOverlays.has(e)}getCanvasOverlays(e){return[...this.canvasOverlays.values()].filter(t=>!e||(e=>e.layer??"above-host")(t)===e).sort(br)}getRegisteredCanvasOverlayIds(){return[...this.canvasOverlays.keys()]}registerSelectionCustomHandleRenderer(e){if(this.selectionCustomHandleRenderers.has(e.type))throw new Error(`Duplicate selection handle renderer type: ${e.type}.`);this.selectionCustomHandleRenderers.set(e.type,e)}getSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.get(e)??null}hasSelectionCustomHandleRenderer(e){return this.selectionCustomHandleRenderers.has(e)}getRegisteredSelectionCustomHandleTypes(){return[...this.selectionCustomHandleRenderers.keys()]}registerCanvasRenderPlugins(e){for(const t of e){if(this.registeredPluginIds.has(t.id))throw new Error(`Duplicate canvas render plugin id: ${t.id}.`);for(const e of t.canvasOverlays??[])this.registerCanvasOverlay(e);for(const e of t.selectionCustomHandleRenderers??[])this.registerSelectionCustomHandleRenderer(e);this.registeredPluginIds.add(t.id)}}},ew=xr(),tw=Tx(ew),nw="rgba(100, 116, 139, 0.82)",iw="rgba(255, 255, 255, 0.84)",ow=Mx(()=>or(ir().bindingPreviewActiveSignal)?Nx(rw,{}):null),rw=Mx(()=>{const e=ir(),t=or(e.bindingPreviewSignal),n=or(e.terminalBindingGuidesSignal);if(!t)return null;const i=n.some(e=>e.terminal===t.terminal&&e.targetShapeId===t.targetShapeId);
45
- return Hx(zx,{children:[Nx(sw,{targetShapeId:t.targetShapeId}),Nx(aw,{bindingPreview:t,showGuide:!i})]})}),sw=Mx(({targetShapeId:e})=>{const t=ir(),n=or(t.cameraZoomSignal),i=or(t.getShapeSignal(e));return i?Nx(kr,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),aw=Mx(({bindingPreview:e,showGuide:t})=>{const n=or(ir().cameraZoomSignal),i=2/n,o=6/n,r=4/n;
46
- return Hx(zx,{children:[t?e.guidePath?Nx(Pr,{path:e.guidePath,strokeWidth:i,dashSize:o,gapSize:r,kind:"binding-preview",terminal:e.terminal}):Nx(wr,{start:e.rawPagePoint,end:e.resolvedPagePoint,startInset:8/n,endInset:6/n,strokeWidth:i,dashSize:o,gapSize:r,kind:"binding-preview",terminal:e.terminal}):null,
47
- Nx("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}),
48
- Nx("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})]})}),lw=Mx(()=>or(ir().brushBoxActiveSignal)?Nx(dw,{}):null),dw=Mx(()=>{const e=or(ir().brushBoxSignal);return e?Nx("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}),cw=Mx(()=>{const e=ir(),t=or(e.selectionOverlayFrameGeometrySignal),n=or(e.selectionOverlayCompanionFrameGeometriesSignal);return t||0!==n.length?Hx(zx,{children:[t?Nx(uw,{frameGeometry:t}):null,n.map((e,t)=>Nx(uw,{frameGeometry:e},`companion-${t}`))]}):null}),uw=Mx(({frameGeometry:e})=>{const t=or(ir().selectionOverlayFrameStyleSignal),{bounds:n,rotation:i,rotationCenter:o}=e,{cornerRadius:r,strokeWidth:s}=t,a=s/2,l=180*i/Math.PI;
49
- return Nx("g",{transform:0===i?void 0:`rotate(${l} ${o.x} ${o.y})`,children:Nx("rect",{"data-selection-overlay":"bounds",x:n.x-a,y:n.y-a,width:n.w+s,height:n.h+s,rx:r+a,ry:r+a,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeWidth:s})})}),hw=new Set(JI),pw=Mx(()=>{const e=or(ir().selectionOverlayHandleAnchorsSignal);return e?Nx(gw,{anchors:e}):null}),gw=Mx(({})=>{const e=ir(),t=or(e.selectionOverlayHandlesSignal),n=or(e.selectionOverlayFrameGeometrySignal),i=Ir(),o=or(e.cameraZoomSignal);if(!t)return null;const{resizeHandles:r,rotateHandles:s,strokeWidth:a,terminalHandles:l,middleHandles:d,customHandles:c}=t,u=r.filter(e=>hw.has(e.id)),h=r.filter(e=>!hw.has(e.id)),p=n?.rotation??0,g=180*p/Math.PI;
50
- return Hx(zx,{children:[n?Nx("g",{transform:n&&0!==p?`rotate(${g} ${n.rotationCenter.x} ${n.rotationCenter.y})`:void 0,children:h.map(e=>Nx(Cr,{frame:n,handleId:e.id,zoom:o},e.id))}):null,u.map(e=>Nx("rect",{"data-selection-resize-handle":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2/o,ry:2/o,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,style:{cursor:Tr(e.id,p),pointerEvents:"auto"}},e.id)),s.map(e=>Hx("g",{"data-selection-rotate-handle":e.id,transform:`translate(${e.bounds.center.x-6/o} ${e.bounds.center.y-6/o}) scale(${.6/o})`,fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[Nx("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),Nx("path",{d:"M21 3v5h-5"})]},e.id)),l.map(e=>Nx("circle",{"data-selection-terminal":e.terminal,cx:e.bounds.center.x,cy:e.bounds.center.y,r:Math.min(e.bounds.w,e.bounds.h)/2,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,style:{cursor:"grab",pointerEvents:"auto"}},e.terminal)),d.map(e=>Nx("rect",{"data-selection-binding-middle":"true",x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2,ry:2,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,transform:`rotate(45 ${e.bounds.center.x} ${e.bounds.center.y})`,style:{cursor:"grab",pointerEvents:"auto"}},"middle")),c.map(e=>{const t=i.getSelectionCustomHandleRenderer(e.type);
51
- return Nx(t?t.component:Mr,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),fw=["ew-resize","nwse-resize","ns-resize","nesw-resize"],mw=1e-6,Sw=Mx(()=>{const e=ir(),t=or(e.selectionOverlayPathSignal),n=or(e.selectionOverlayPageClipPathSignal),i=or(e.selectionOverlayBindingSegmentsSignal),o=or(e.selectedShapeOverlayItemsSignal),r=or(e.selectionOverlayFrameStyleSignal),s=Lx().replace(/[^a-zA-Z0-9_-]/g,"-"),a=`selection-content-clip-${s}`,l=`selection-path-halo-${s}`,d=1===o.length?o[0]?.pathStyle??null:null,c=d?((e,t)=>{const n=e.localToPage.getMaximumLinearScale(),i=n>mw?Math.abs(e.localToPage.determinant())/n:0;return e.strokeWidth+2*t/(i>mw?i:n>mw?n:1)})(d,r.strokeWidth):null,u=d&&null!==c?d.localBounds.expand(c):null;return t?Hx(zx,{children:[
52
- Nx(yw,{bindingSegments:i,strokeWidth:r.strokeWidth}),n||d&&u?Hx("defs",{children:[n?Nx("clipPath",{id:a,clipPathUnits:"userSpaceOnUse",children:Nx("path",{d:n,clipRule:"evenodd",fillRule:"evenodd"})}):null,d&&null!==c&&u?Hx("mask",{id:l,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:u.x,y:u.y,width:u.w,height:u.h,children:[Nx(Er,{dataPrefix:"path-halo-mask-outer",pathStyle:d,stroke:"white",strokeWidth:c}),Nx(Er,{dataPrefix:"path-halo-mask-center",pathStyle:d,stroke:"black",strokeWidth:d.strokeWidth})]}):null]}):null,
53
- Nx("g",{"data-selection-overlay":"lines",clipPath:n?`url(#${a})`:void 0,children:d&&null!==c?Nx("g",{"data-selection-overlay":"path-halo-transform",transform:d.localToPage.toSvgString(),children:Nx("g",{mask:`url(#${l})`,children:Nx(Er,{dataPrefix:"path-halo",pathStyle:d,stroke:"rgba(37, 99, 235, 0.45)",strokeWidth:c})})}):Hx(zx,{children:[Nx("path",{"data-selection-overlay":"path-underlay",d:t,fill:"none",stroke:"rgba(255,255,255,0.92)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2*r.strokeWidth}),Nx("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:r.strokeWidth})]})})]}):null}),yw=Mx(({bindingSegments:e,kind:t="selection-binding",strokeWidth:n})=>{if(0===e.length)return null;const i=3*n,o=2*n,r=4*n,s=3*n;
54
- return Nx(zx,{children:e.map(e=>e.guidePath?Nx(Pr,{path:e.guidePath,strokeWidth:n,dashSize:i,gapSize:o,kind:t,terminal:e.terminal},e.terminal):Nx(wr,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:r,endInset:s,strokeWidth:n,dashSize:i,gapSize:o,kind:t,terminal:e.terminal},e.terminal))})}),bw=Mx(()=>or(ir().selectionTranslationActiveSignal)?null:Hx(zx,{children:[
55
- Nx(Sw,{}),
56
- Nx(cw,{}),
57
- Nx(pw,{})]})),xw="rgba(37, 99, 235, 0.9)",Iw=Mx(()=>{const e=or(ir().snapIndicatorsSignal);return 0===e.length?null:Nx(vw,{indicators:e})}),vw=Mx(({indicators:e})=>{const t=or(ir().cameraZoomSignal);
58
- return Nx(zx,{children:e.map(e=>Nx("points"===e.type?ww:Pw,{indicator:e,zoom:t},e.id))})}),ww=Mx(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[o,r]=e.line,s=180*e.rotation/Math.PI;
59
- return Hx("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${s} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[Nx("path",{"data-ui":"snap-indicator-line",d:`M ${o.x} ${o.y} L ${r.x} ${r.y}`,fill:"none",stroke:xw,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,o)=>Nx("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:xw,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${o}`))]})}),Pw=Mx(({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=Ar(i,[n?c.startEdge[0].y:c.startEdge[0].x,n?c.startEdge[1].y:c.startEdge[1].x]);e&&(i=e);const t=Ar(i,[n?c.endEdge[0].y:c.endEdge[0].x,n?c.endEdge[1].y:c.endEdge[1].x]);t&&(i=t)}if(!Number.isFinite(i[0])||!Number.isFinite(i[1]))return null;const o=(i[0]+i[1])/2,r=3.5/t,s=2*r,a=[];for(const{startEdge:c,endEdge:u}of e.gaps)if(n){a.push(`M ${c[0].x} ${o-s} L ${c[1].x} ${o+s}`,`M ${u[0].x} ${o-s} L ${u[1].x} ${o+s}`,`M ${c[0].x} ${o} L ${u[0].x} ${o}`);const e=(c[0].x+u[0].x)/2;a.push(`M ${e} ${o-r} L ${e} ${o+r}`)}else{a.push(`M ${o-s} ${c[0].y} L ${o+s} ${c[1].y}`,`M ${o-s} ${u[0].y} L ${o+s} ${u[1].y}`,`M ${o} ${c[0].y} L ${o} ${u[0].y}`);const e=(c[0].y+u[0].y)/2;a.push(`M ${o-r} ${e} L ${o+r} ${e}`)}const l=180*e.rotation/Math.PI,d=0===e.rotation?void 0:`rotate(${l} ${e.rotationCenter.x} ${e.rotationCenter.y})`;
60
- return Nx("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:d,fill:"none",stroke:xw,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),kw=Mx(()=>{const e=ir(),t=or(e.terminalBindingGuidesSignal),n=or(e.selectionOverlayFrameStyleSignal);return 0===t.length?null:Nx(yw,{bindingSegments:t,kind:"terminal-binding-guide",strokeWidth:n.strokeWidth})}),Cw=Mx(()=>Hx("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
61
- Nx("style",{children:'\n [data-selection-terminal],\n [data-selection-binding-middle],\n [data-selection-custom-handle-visual="default"] {\n transition: fill 120ms ease, stroke 120ms ease;\n }\n [data-selection-terminal]:hover,\n [data-selection-binding-middle]:hover,\n [data-selection-custom-handle-visual="default"]:hover {\n fill: rgba(219, 234, 254, 0.98);\n stroke: rgba(29, 78, 216, 0.98);\n }\n [data-selection-terminal]:active,\n [data-selection-binding-middle]:active,\n [data-selection-custom-handle]:active {\n cursor: grabbing;\n }\n '}),
62
- Nx(Tw,{layer:"below-host"}),
63
- Nx(Iw,{}),
64
- Nx(kw,{}),
65
- Nx(ow,{}),
66
- Nx(lw,{}),
67
- Nx(bw,{}),
68
- Nx(Tw,{layer:"above-host"})]})),Tw=Mx(({layer:e})=>{const t=Ir().getCanvasOverlays(e);return 0===t.length?null:Nx(zx,{children:t.map(({id:e,component:t})=>Nx(t,{},e))})}),Mw=class{guards=[];registeredGuardIds=new Set;register(e){if(this.registeredGuardIds.has(e.id))throw new Error(`Duplicate DOM event guard id: ${e.id}.`);this.guards.push(e),this.registeredGuardIds.add(e.id)}registerCanvasRenderPlugins(e){for(const t of e)for(const e of t.domEventGuards??[])this.register(e)}getGuards(){return this.guards}handle(e){for(const t of this.guards)if("handled"===t.handle(e))return"handled";return"continue"}getCursor(e){for(const t of this.guards){const n=t.getCursor?.(e);if(void 0!==n)return n}}},Ew="canvas-surface",Aw=`[data-ui="${Ew}"]`,Bw=[{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}],Rw=/[;{}<>\u0000-\u001f\u007f]/u,Lw=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,$w=/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|em|rem|%)?$/iu,Fw="path-label",Uw="geo-label",Ow={[Fw]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"owner",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!0,canUseSelectionResizeHandles:!1,canUseSelectionRotateHandle:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[Uw]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"label",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!1,canUseSelectionResizeHandles:!0,canUseSelectionRotateHandle:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}},Dw="default",zw={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}},Nw=new WeakMap,Hw=new WeakMap,Ww={bold:["bold","strong"],italic:["italic","em"],strike:["strike","s"],underline:["underline","u"]},_w=14,Kw=16,Yw=20,Xw=28,qw=16,jw={[_w]:20,[Kw]:24,[Yw]:28,[Xw]:36},Vw=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))),pa(i,"whiteSpace",n?.whiteSpace),pa(i,"overflowWrap",n?.overflowWrap),pa(i,"lineHeight",n?.lineHeight),pa(i,"letterSpacing",n?.letterSpacing),pa(i,"textAlign",n?.textAlign),this.measurePreparedElement(i)}prepareElement(e){const t=this.element;return t.removeAttribute("contenteditable"),t.className="",t.textContent="",e?.shape&&e.fontCatalog&&((e,t,n)=>{e.className="land-text-editor__content",e.dir="auto",e.style.color=F(t.props.color),e.style.fontFamily=ia(t.props.font,n),e.style.fontSize=`${oa(t.props.size)}px`,e.style.lineHeight=`${ra(t.props.size)}px`,e.style.textAlign=aa(t.props.textAlign)})(t,e.shape,e.fontCatalog),t.style.position="absolute",t.style.left="-10000px",t.style.top="0",t.style.visibility="hidden",t.style.pointerEvents="none",t.style.width="number"==typeof e?.width?`${e.width}px`:"max-content",t.style.minWidth="0",t.style.height="auto",t.style.minHeight="0",t.style.maxHeight="none",t.style.maxWidth="number"==typeof e?.width?`${e.width}px`:"number"==typeof e?.maxWidth?`${e.maxWidth}px`:"none",t}measurePreparedElement(e){return e.querySelectorAll("p").forEach(e=>{e instanceof HTMLElement&&(e.style.margin="0")}),[e,...Array.from(e.querySelectorAll("*")).filter(e=>e instanceof HTMLElement)].reduce((e,t)=>{const n=t.getBoundingClientRect();return{w:Math.max(e.w,n.width,t.scrollWidth,t.offsetWidth),h:Math.max(e.h,n.height,t.scrollHeight,t.offsetHeight)}},{w:0,h:0})}},Gw=new WeakMap,Zw=/[;{}<>\u0000-\u001f\u007f]/u,Qw=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,Jw=qx.extend({inclusive:!1,renderHTML({HTMLAttributes:e}){const{href:t,target:n,rel:i,...o}=e;return["span",Kx(o,{"data-rich-text-link-href":t,style:"text-decoration-line: underline;"}),0]}}),eP=[oI.configure({bold:!1,italic:!1,link:!1,strike:!1,underline:!1}),Yx.extend({keepOnSplit:!0}),Xx.extend({keepOnSplit:!0}),jx.extend({keepOnSplit:!0}),nI.extend({keepOnSplit:!0}),tI,Zx,Gx,Qx,Jx,eI,Vx.configure({types:["paragraph"],alignments:["left","center","right"]}),iI.configure({className:"land-rich-text-selection"}),Jw.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})],tP=Tx(null),nP=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),iP={id:"land.text.dom-events",handle({event:e,name:t}){if(!nP.has(t))return"continue";const n=e.target;return n instanceof HTMLElement&&n.closest('[data-ui="text-editing-box"]')?"handled":"continue"},getCursor:({element:e})=>e?.closest('[data-ui="text-editing-box"]')?"text":void 0},oP="text.create",rP=class extends Iv{constructor(e){super(e,"text"),this.initial="idle",this.addChild(new sP(e,this)),this.addChild(new aP(e,this))}},sP=class extends Iv{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){this.transition("pointing",{originPagePoint:e.pagePoint.clone(),shapeId:null})}},aP=class extends Iv{info=null;operation=null;isHandingOffOperation=!1;constructor(e,t){super(e,"pointing",t)}onEnter(e){this.info=e,this.operation=this.editor.operations.begin({kind:oP,label:"shape.create",source:"user",history:"record"})}onPointerMove(e){this.updateFixedWidthShape(e.pagePoint)}onPointerUp(e){if(!this.info)return void this.transition("idle");const t=null!==this.info.shapeId?this.editor.getShape(this.info.shapeId):this.createTextShape(e.pagePoint);if(!Is(t))return this.cancelOperation(),void this.transition("idle");let n;ke(this.editor,t.id,{source:"user"}),this.editor.isToolLocked()||(this.isHandingOffOperation=!0,this.transition("idle"),this.editor.commands.setActiveTool("select",{source:"system"}));try{n=this.editor.startEditingShape({shapeId:t.id,entryMode:"focusEnd",markId:oP,reuseActiveOperation:!0,preserveInteraction:!0},"user")}catch(i){throw this.cancelOperation(),i}finally{this.isHandingOffOperation=!1}n?this.operation=null:this.cancelOperation(),this.editor.isToolLocked()&&this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.isHandingOffOperation||this.cancelOperation(),this.info=null}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}updateFixedWidthShape(e){if(!this.info)return;const t=((e,t,n)=>{const 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:{...Ha(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:Ha(t)}))(e,this.getDefaultTextProps()))}createTextShapeAt({x:e,y:t,props:n}){const i=Ps(this.editor,{x:e,y:t,props:n},"user");return this.editor.commands.setSelectedShapeIds([i.id],{source:"system"}),i}getDefaultTextProps(){return ws(this.editor)}},lP=["start","middle","end"],dP=class extends xv{type="text";getDefaultProps(){return{richText:Qr(""),w:16,h:sa(qw),autoSize:!0,scale:1,font:Dw,size:qw,color:M("text-slate"),backgroundColor:E("transparent"),textAlign:"start"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{richText:es(t.richText),w:Math.max(1,Wa(t.w,n.w)),h:Math.max(1,Wa(t.h,n.h)),autoSize:"boolean"==typeof t.autoSize?t.autoSize:n.autoSize,scale:Math.max(.01,Wa(t.scale,n.scale)),font:Ns(t.font)?t.font:n.font,size:na(t.size,n.size),color:$(t.color,n.color),backgroundColor:$(t.backgroundColor,n.backgroundColor),textAlign:(i=t.textAlign,"string"==typeof i&&lP.includes(i)?t.textAlign:n.textAlign)};var i}getPositionedBounds(e){return(e=>new SI(e.x,e.y,Ka(e),Ya(e)))(e)}getLocalBounds(e){return Xa(e)}getRenderBounds(e){return Xa(e)}getExportBounds(e){return Xa(e)}canSnap(e,t){return!t||(n=t.editor,i=e.id,As(n,i)?.behavior.canSnap??null??!0);var n,i}canReceiveTerminalBinding(e,t){return!t||(n=t.editor,i=e.id,As(n,i)?.behavior.canReceiveTerminalBinding??null??!0);var n,i}canEdit(e){return!0}contributesToSelectionFrame(e,t){return n=t.editor,i=e.id,As(n,i)?.behavior.contributesToSelectionFrame??null??!0;var n,i}canUseSelectionResizeHandles(e,t){return n=t.editor,i=e.id,As(n,i)?.behavior.canUseSelectionResizeHandles??null??!0;var n,i}canUseSelectionRotateHandle(e,t){return n=t.editor,i=e.id,As(n,i)?.behavior.canUseSelectionRotateHandle??null??!0;var n,i}getSelectionTargetId(e,t){return((e,t)=>{const n=As(e,t);return n?"owner"===n.behavior.selectionTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}getHoverTargetId(e,t){return((e,t)=>{const n=As(e,t);return n?"owner"===n.behavior.hoverTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}getHoverDecorationTargetId(e,t){return((e,t)=>{const n=As(e,t);return n?"owner"===n.behavior.hoverDecorationTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}getTranslateTargetId(e,t){return((e,t)=>{const n=As(e,t);return n?"owner"===n.behavior.translateTarget?n.ownerId:t:null})(t.editor,e.id)??e.id}resizeSelectionBounds(e,t){const n={};if(t.isOnlyResizeTarget&&qa(t.handleId)){const i=Cn({width:t.selectionLocalBounds.w,height:t.selectionLocalBounds.h,scaleX:e.scaleX,scaleY:e.scaleY});n.w=Math.max(16,i.width/_a(e)),n.autoSize=!1}else n.scale=Math.max(.01,e.props.scale*function(e,t){const n=(e=>kn({localWidth:Ka(e),localHeight:Ya(e),scaleX:e.scaleX,scaleY:e.scaleY}))(e),i=t.selectionLocalBounds.w/Math.max(1,n.width),o=t.selectionLocalBounds.h/Math.max(1,n.height);switch(t.handleId){case"left":case"right":return i;case"top":case"bottom":return o;default:return Math.max(i,o)}}(e,t));const i=n.scale??_a(e),o=(n.w??e.props.w)*i,r=e.props.h*i,s=kn({localWidth:o,localHeight:r,scaleX:e.scaleX,scaleY:e.scaleY}),a=((e,t)=>0===t.selectionRotation?e.clone():mI.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(Ln({handleId:t.handleId,requestedBounds:t.selectionLocalBounds,actualWidth:s.width,actualHeight:s.height,scaleX:t.scaleX,scaleY:t.scaleY,isResizingFromCenter:t.isResizingFromCenter}).center,t);return{id:e.id,x:a.x-o/2,y:a.y-r/2,rotation:t.scaleX<0!=t.scaleY<0?2*t.selectionRotation-e.rotation:e.rotation,scaleX:t.scaleX<0?-e.scaleX:e.scaleX,scaleY:t.scaleY<0?-e.scaleY:e.scaleY,props:n}}getAllowedSelectionResizeModes(e,t){return t.isOnlyResizeTarget&&qa(t.handleId)?tv:nv}onEditEnd(e){if(!(Jr(e.props.richText).trim().length>0))return{deleteShapeIds:[e.id]}}},cP=class{fontCatalog;type="text";constructor(e){this.fontCatalog=e}toSvg(e,t){if(0===Jr(e.props.richText).trim().length)return null;const n=ks(Rs(t.editor,e),e.props.w);return{tag:"foreignObject",attrs:{x:0,y:0,width:e.props.w*e.props.scale,height:e.props.h*e.props.scale},children:[{tag:"div",attrs:{xmlns:"http://www.w3.org/1999/xhtml",dir:"auto",style:Ga(e,t,this.fontCatalog,n)},children:ja(e.props.richText,O(e.props.backgroundColor)?void 0:t.resolveColor(e.props.backgroundColor))}]}}},uP=".label",hP=class extends OI{type=Fw;getDefaultProps(){return{labelPosition:.5}}validateProps(e){const t=this.getDefaultProps();return{labelPosition:Qa((e&&"object"==typeof e?e:{}).labelPosition,t.labelPosition)}}canBind(e,t,n){return this.canUseShapeHierarchy(t,n,e)}canUseShapeHierarchy(e,t,n){return Is(t.fromShape)&&(!n||null!==el(n,t.toShape))}getExclusiveBindingKey(e){return e.toId}onBindingCreate(e,t){return this.syncLabelPosition(e,t)}onBindingUpdate(e,t,n){return this.syncLabelPosition(e,n)}onBindingLoad(e,t){return this.syncLabelPosition(e,t)}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}getTargetShapeContentCutoutLocalPolygons(e,t,n){if(!Is(n.fromShape)||!el(e,n.toShape))return[];const i=e.computeShapeLocalToPageTransform(n.toShape).tryInvert();if(!i)return[];const o=e.computeShapeLocalBounds(n.fromShape),r=i.compose(e.computeShapeLocalToPageTransform(n.fromShape));return[[new mI(o.minX,o.minY),new mI(o.maxX,o.minY),new mI(o.maxX,o.maxY),new mI(o.minX,o.maxY)].map(e=>r.applyToPoint(e))]}onAfterShapeChange(e,t,n){return this.syncLabelPosition(e,t)}onBeforeDeleteShape(e,t,n){return"from"===n.role?{deleteBindingIds:[t.id]}:{deleteShapeIds:[t.fromId],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){return{deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}getShapeHierarchyRootId(e,t){return t===e.fromId?e.toId:null}getSelectionCompanionFrameGeometries(e,t,n){if(t.toId!==n.selectedShape.id)return[];if(!0!==((e,t)=>As(e,t)?.behavior.showsCompanionFrameWhenOwnerSelected??null)(e,t.fromId))return[];const i=e.getShape(t.fromId),o=e.getShape(t.toId);if(!Is(i)||!o||!el(e,o))return[];const r=e.computeShapeGeometry(i),s=e.computeShapeLocalToPageTransform(i),a=Math.atan2(s.b,s.a);return[{bounds:SI.FromPoints(r.outlineVertices.map(e=>mI.RotWith(e,r.center,-a))),rotation:a,rotationCenter:r.center}]}syncLabelPosition(e,t){if(!Za(t))return;const n=e.getShape(t.fromId),i=e.getShape(t.toId);if(!Is(n)||!i||!el(e,i))return{deleteBindingIds:[t.id]};const o=((e,t,n,i)=>{const o=Ja(e,t,n,i),r=n.parentId,s=`${n.index}${uP}`,a=!1,l="middle",d=Ts(e,t,r,o);return d?t.x===d.x&&t.y===d.y&&t.rotation===d.rotation&&t.scaleX===d.scaleX&&t.scaleY===d.scaleY&&t.parentId===r&&t.index===s&&t.props.w===o.props.w&&t.props.autoSize===a&&t.props.textAlign===l?null:{id:t.id,...d,parentId:r,index:s,props:{w:o.props.w,autoSize:a,textAlign:l}}:null})(e,n,i,t.props.labelPosition);return o?{shapes:[{...n,...o,props:{...n.props,...o.props}}]}:void 0}},pP=".label",gP=class extends OI{type=Uw;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:il(i.x,t.normalizedAnchor.x),y:il(i.y,t.normalizedAnchor.y)},ownerBaseHeight:ol(n.ownerBaseHeight,t.ownerBaseHeight)}}canBind(e,t,n){return this.canUseShapeHierarchy(t,n)}canUseShapeHierarchy(e,t){return Is(t.fromShape)&&nl(t.toShape)}getExclusiveBindingKey(e){return e.toId}onBindingCreate(e,t){return this.syncLabelPosition(e,t)}onBindingUpdate(e,t,n){return this.syncLabelPosition(e,n,t.toId===n.toId?void 0:{role:"to"})}onBindingLoad(e,t){return this.syncLabelPosition(e,t)}getGeometryDependentShapeIds(e,t,n){return"from"===n.role?[t.toId]:[t.fromId]}onAfterShapeChange(e,t,n){return this.syncLabelPosition(e,t,n)}onBeforeDeleteShape(e,t,n){if("from"===n.role){const n=e.getShape(t.toId),i=n?sl(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?sl(n,t):null;return{shapes:i?[i]:void 0,deleteBindingIds:[t.id]}}getExportShapeIds(e,t){return[t.fromId]}getShapeHierarchyRootId(e,t){return t===e.fromId?e.toId:null}syncLabelPosition(e,t,n){if(i=t,"binding"!==i?.typeName||"geo-label"!==i.type)return;var i;const o=e.getShape(t.fromId),r=e.getShape(t.toId);if(!Is(o)||!nl(r))return{deleteBindingIds:[t.id]};const s=((e,t,n)=>{const i=rl(t,"h")??1;return"to"===n?.role?i:e.props.ownerBaseHeight>0?e.props.ownerBaseHeight:i})(t,r,n),a=t.props.ownerBaseHeight===s?null:{...t,props:{...t.props,ownerBaseHeight:s}},l=function(e,t,n){const i=rl(e,"h");if(!i)return null;const o=Math.max(n,(e=>Math.max(1,e.props.h*e.props.scale+32))(t));return i===o?null:{...e,props:{...e.props,h:o}}}(r,o,s),d=((e,t,n)=>{const i=al(e,t,n),o=n.parentId,r=`${n.index}${pP}`,s=!1,a="middle",l=Ts(e,t,o,i);return l?t.x===l.x&&t.y===l.y&&t.rotation===l.rotation&&t.scaleX===l.scaleX&&t.scaleY===l.scaleY&&t.parentId===o&&t.index===r&&t.props.w===i.props.w&&t.props.autoSize===s&&t.props.textAlign===a?null:{id:t.id,...l,parentId:o,index:r,props:{w:i.props.w,autoSize:s,textAlign:a}}:null})(e,o,l??r),c=[];return l&&c.push(l),d&&c.push({...o,...d,props:{...o.props,...d.props}}),c.length>0||a?{shapes:c.length>0?c:void 0,bindings:a?[a]:void 0}:void 0}},fP="text.edit",mP="path-label.edit",SP="path-label.create",yP="path-label.drag",bP="geo-label.edit",xP="geo-label.create",IP=nr("land.plugin-setup.actions"),vP=nr("land.plugin-setup.capabilities"),wP={mainMenu:fl("land.chrome.main-menu"),commandPalette:fl("land.chrome.command-palette"),inspector:fl("land.chrome.inspector"),status:fl("land.chrome.status")},PP=nr("land.plugin-setup.chrome"),kP=nr("land.plugin-setup.context-menu"),CP=nr("land.plugin-setup.exports"),TP=nr("land.plugin-setup.imports"),MP=nr("land.plugin-setup.apis"),EP=nr("land.plugin-setup.services"),AP="editor.tool.set-active-tool",BP={toolSwitcher:yl("land.toolbar.tool-switcher"),toolOptions:yl("land.toolbar.tool-options"),selectionProperties:yl("land.toolbar.selection-properties"),selectionQuickActions:yl("land.toolbar.selection-quick-actions")},RP=nr("land.plugin-setup.toolbar"),LP=ml("plugin-text.api"),$P={token:LP,create:({editor:e})=>e.shapeUtils.has("text")?(e=>({create(t){const n=e.getDefaultShapeProps("text"),[i]=e.commands.createShapes([{type:"text",x:t.x,y:t.y,meta:t.meta?{...t.meta}:void 0,props:{...n,w:t.w??n.w,h:t.h??n.h,font:t.font??n.font,color:t.color??n.color,size:t.size??n.size,textAlign:t.textAlign??n.textAlign,richText:Qr(t.text)}}],{source:"user"});return i&&"text"===i.type?{id:i.id,type:i.type}:null}}))(e):null},FP=er("plugin-text.font-catalog"),UP=[{value:M("text-slate"),label:"Slate",id:"slate",hexColor:"#0f172a"},{value:M("text-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("text-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("text-red"),label:"Red",id:"red",hexColor:"#dc2626"}],OP=[{id:"none",value:E("transparent"),label:"None",hexColor:"#fef08a",opacity:0},{id:"yellow",value:E("#fef08a"),label:"Yellow",hexColor:"#fef08a",opacity:1},{id:"blue",value:E("#bfdbfe"),label:"Blue",hexColor:"#bfdbfe",opacity:1},{id:"green",value:E("#bbf7d0"),label:"Green",hexColor:"#bbf7d0",opacity:1},{id:"red",value:E("#fecaca"),label:"Red",hexColor:"#fecaca",opacity:1}],DP=[{id:"s",value:14,label:"S"},{id:"m",value:16,label:"M"},{id:"l",value:20,label:"L"},{id:"xl",value:28,label:"XL"}],zP=[{value:"start",label:"Align left",icon:"align-left"},{value:"middle",label:"Align center",icon:"align-center"},{value:"end",label:"Align right",icon:"align-right"}],NP=[{format:"bold",actionId:"text.toggle-bold",label:"Bold",icon:"bold",dataUi:"selected-text-bold-button"},{format:"italic",actionId:"text.toggle-italic",label:"Italic",icon:"italic",dataUi:"selected-text-italic-button"},{format:"underline",actionId:"text.toggle-underline",label:"Underline",icon:"underline",dataUi:"selected-text-underline-button"},{format:"strike",actionId:"text.toggle-strike",label:"Strikethrough",icon:"strikethrough",dataUi:"selected-text-strike-button"}],HP="text.clear-formatting",WP="text.set-link",_P=$l(),KP=2*Math.PI,YP=ml("plugin-arrow.api"),XP={token:YP,create:({editor:e})=>e.shapeUtils.has("arrow")?(e=>({create(t){const n=e.getDefaultShapeProps("arrow"),i=Bd(e,{startPagePoint:new mI(t.start.x,t.start.y),endPagePoint:new mI(t.end.x,t.end.y),startBinding:t.startBinding?{targetShapeId:t.startBinding.targetShapeId,normalizedAnchor:t.startBinding.normalizedAnchor}:null,endBinding:t.endBinding?{targetShapeId:t.endBinding.targetShapeId,normalizedAnchor:t.endBinding.normalizedAnchor}:null,meta:t.meta?{...t.meta}:void 0,props:{...n,bend:t.bend??n.bend,stroke:t.stroke??n.stroke,strokeWidth:t.strokeWidth??n.strokeWidth,headStart:t.headStart??n.headStart,headEnd:t.headEnd??n.headEnd}});return{id:i.id,type:i.type}}}))(e):null},qP=class extends Iv{constructor(e){super(e,"arrow"),this.initial="idle",this.addChild(new jP(e,this)),this.addChild(new VP(e,this))}},jP=class extends Iv{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})=>Hd(e,{terminal:t,rawPagePoint:n,oppositePagePoint:n.add(new mI(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})}},VP=class extends Iv{info=null;operation=null;constructor(e,t){super(e,"creating",t)}onEnter(e){if(this.info=e,!this.info)return;this.operation=this.editor.operations.begin({kind:"arrow.create",label:"shape.create",source:"user",history:"record"});const t=Bd(this.editor,{startPagePoint:this.info.startPagePoint,endPagePoint:this.info.startPagePoint,startBinding:this.info.startBinding,props:{stroke:this.info.props.stroke,strokeWidth:this.info.props.strokeWidth,headStart:this.info.props.headStart,headEnd:this.info.props.headEnd}},"user");this.info.shapeId=t.id,this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),this.editor.setBindingPreview(null),this.updateCreationBindingGuides(t)}onPointerMove(e){this.updateShape(e.pagePoint)}onTick(e){if(!this.info)return;const t=this.editor.inputs.state.get();if("dragging"!==t.dragPhase||!t.currentPagePoint||!t.currentScreenPoint)return;const n=Fo(t.currentScreenPoint,this.editor.viewportScreenSizeSignal.get(),e.elapsed);0===n.x&&0===n.y||(this.editor.panCamera(n),this.updateShape(this.editor.screenToPage(t.currentScreenPoint)))}onPointerUp(e){if(this.info){if(this.updateShape(e.pagePoint),!this.info.shapeId||this.info.startPagePoint.dist(this.info.currentPagePoint)<4)return this.cancelOperation(),void this.transition("idle");ke(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})}else this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.editor.setTerminalBindingGuides(null),this.info=null}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}updateShape(e){if(!this.info)return;this.info.currentPagePoint=e.clone();const t=this.info.shapeId,n=t?this.editor.getShape(t):null,i=sd(n)?Wd(this.editor,{arrow:n,terminal:"end",rawPagePoint:e,ignoreTargets:this.editor.inputs.state.get().accelKey}):Hd(this.editor,{terminal:"end",rawPagePoint:e,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey}),o=Rd(this.editor,t,"end",this.info.startBinding&&i.binding?.targetShapeId===this.info.startBinding.targetShapeId?{pagePoint:e,binding:null,preview:null}:i,"user")??(t?this.editor.getShape(t):null);this.updateCreationBindingGuides(sd(o)?o:null)}updateCreationBindingGuides(e){if(!e)return void this.editor.setTerminalBindingGuides(null);const t=new Map(this.editor.getBindingsFromShape(e.id).filter(ad).map(e=>[e.props.terminal,e.toId])),n=cd(this.editor,e).bindingSegments.map(n=>({...n,ownerShapeId:e.id,targetShapeId:t.get(n.terminal)??null}));this.editor.setTerminalBindingGuides(n)}},GP=[{value:M("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:M("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],ZP=[{value:"both",label:"Both ends",icon:"arrows-horizontal"},{value:"start",label:"Start",icon:"arrow-narrow-left"},{value:"end",label:"End",icon:"arrow-narrow-right"},{value:"none",label:"None",icon:"minus"}],QP={id:"arrow",provides:[YP],editor:{id:"land.arrow",shapeCapabilities:[{type:"arrow",schemaProps:["w","h","start","end","bend","stroke","strokeWidth","headStart","headEnd"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Binding support lives in arrow binding records, not arrow props."]}],shapeUtils:[new class extends xv{type="arrow";getDefaultProps(){return{w:160,h:48,start:{x:8,y:24},end:{x:152,y:24},bend:0,stroke:M("stroke-slate"),strokeWidth:2,headStart:"none",headEnd:"arrow"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,Dd(t.w,n.w)),h:Math.max(1,Dd(t.h,n.h)),start:Od(t.start,n.start),end:Od(t.end,n.end),bend:Dd(t.bend,n.bend),stroke:$(t.stroke,n.stroke),strokeWidth:Math.max(1,Dd(t.strokeWidth,n.strokeWidth)),headStart:"arrow"===t.headStart?"arrow":"none",headEnd:"none"===t.headEnd?"none":"arrow"}}getPositionedBounds(e){const t=Kl(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}getPointHitTestBounds(e,t){const n=Math.max(8,e.props.strokeWidth+4);if(!t?.editor)return Kl(e).bounds.expand(n);const i=cd(t.editor,e).info,o=t.editor.computeShapePositionedToPageTransform(e).tryInvert();if(!o||0===i.points.length)return Kl(e).bounds.expand(n);const r=n*Math.sqrt(o.a*o.a+o.b*o.b+o.c*o.c+o.d*o.d);return SI.FromPoints(i.points.map(e=>o.applyToPoint(e))).expand(r)}getLocalBounds(e){return new SI(0,0,e.props.w,e.props.h)}getExportBounds(e){const t=Yl(e),n=Math.max(6,.5*e.props.strokeWidth+4);return t.bounds.expand(n)}repairLoadedShape(e){return null}updateSelectionPagePoints(e,t){const n=this.getSelectionPageMiddlePoint(e);if(t.pageMiddlePoint&&n){const i=this.getSelectionPagePoints(e),o=((e,t)=>{const n=e[1].sub(e[0]),i=e[2].sub(e[0]),o=n.x*i.y-n.y*i.x;if(Math.abs(o)<1e-9)return null;const r=new yI(i.y/o,-n.y/o,-i.x/o,n.x/o,0,0),s=t[1].sub(t[0]),a=t[2].sub(t[0]),l=new yI(s.x,s.y,a.x,a.y,0,0).compose(r);return new yI(l.a,l.b,l.c,l.d,t[0].x-l.a*e[0].x-l.c*e[0].y,t[0].y-l.b*e[0].x-l.d*e[0].y)})([i[0],i[1],n],[t.pagePoints[0],t.pagePoints[1],t.pageMiddlePoint]);if(o){const t=de(o.compose(this.getLocalToPageTransform(e)),this.getLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY});if(t)return{id:e.id,...t}}}const i=((e,t,n)=>{const i=_l(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}}})(e,t.pagePoints[0],t.pagePoints[1]);return{id:e.id,x:i.x,y:i.y,rotation:i.rotation,scaleX:i.scaleX,scaleY:i.scaleY,props:{w:i.props.w,h:i.props.h,start:i.props.start,end:i.props.end,bend:t.pageMiddlePoint?Xl(t.pagePoints[0],t.pagePoints[1],t.pageMiddlePoint):i.props.bend}}}isWrappedByBrush(e,t){return t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}getSelectionPagePoints(e){return[Dl(e,"start"),Dl(e,"end")]}getSelectionPageMiddlePoint(e){return this.getLocalToPageTransform(e).applyToPoint(Yl(e).middle)}contributesToSelectionFrame(e,t){return t.editor.getSelectedShapeIds().length>1}canUseSelectionResizeHandles(e,t){return t.editor.getSelectedShapeIds().length>1}canUseSelectionRotateHandle(e,t){return t.editor.getSelectedShapeIds().length>1}canStartTranslateFromSelectionBounds(e,t){return t.editor.getSelectedShapeIds().length>1}getSelectionHandleAnchors(e,t){if(!t.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=cd(t.editor,e).info;return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.start.handle},{kind:"binding_terminal",terminal:"end",point:n.end.handle}],middleHandleAnchors:n.middle?[{kind:"binding_middle",point:n.middle}]:[]}}getSelectionOverlayInfo(e,t){const n=cd(t.editor,e),i=n.info,o=ud(t.editor,e),r=Ld(o,e.props),s=t.editor.computeShapeLocalToPageTransform(e);return{usesSelectionPathOverlay:!0,startPagePoint:i.start.point,endPagePoint:i.end.point,middlePagePoint:i.middle,path:i.path,pathStyle:{localPath:o.path,localDecorationPaths:r.path?[r.path]:[],localBounds:SI.FromPoints([...o.points,...r.points]),localToPage:s,strokeWidth:e.props.strokeWidth},pageClipPath:Mo({outputBounds:i.bounds,cutoutLocalPolygons:t.editor.getShapeContentCutoutLocalPolygonsSignal(e.id).get(),localToOutput:s}),bindingSegments:n.bindingSegments}}getLabelPathGeometry(e,t){return function(e){const t="curved"===e.type&&e.path.includes(" A "),n=t?null:(e=>{const t=[];let n=0;for(let i=1;i<e.length;i+=1){const o=e[i-1].dist(e[i]);t.push(o),n+=o}return{length:n,segmentLengths:t}})(e.points),i=t?e.arc.length:n?.length??0,o=n?ql(e.points,n,e.middle,.5):.5;return{length:i,defaultPosition:.5,getPointAt(i){const r=Vl(i);return t?nd(e.start.point,e.end.point,e.arc,r):((e,t,n)=>{const i=e[0]??mI.Zero();if(!t||t.length<=1e-6)return i.clone();const o=t.length*n;let r=0;for(let s=0;s<t.segmentLengths.length;s+=1){const n=t.segmentLengths[s];if(o<=r+n||s===t.segmentLengths.length-1){const t=e[s],i=n<=1e-6?0:(o-r)/n;return t.add(e[s+1].sub(t).mul(Vl(i)))}r+=n}return(e[e.length-1]??i).clone()})(e.points,n,jl(r,o))},getNearestPosition:(i,r)=>t?((e,t,n=.5)=>{const i=t.sub(e.arc.center);if(i.len2()<=1e-12)return Vl(n);const o=e.arc.center.add(i.normalize().mul(e.arc.radius)),r=td(e.start.point,e.end.point,e.arc);if(Math.abs(r)<=1e-6)return Vl(n);const s=td(e.start.point,o,e.arc);if(Math.abs(s)<=Math.abs(r)+1e-6)return Vl(s/r);const a=t.dist2(e.start.point),l=t.dist2(e.end.point);return Math.abs(a-l)<=1e-8?n<=.5?0:1:a<l?0:1})(e,i,r?.hintPosition):((e,t)=>{const n=Vl(e),i=Vl(t);return n<=i?i<=1e-6?.5:n/i*.5:1-i<=1e-6?.5:.5+(n-i)/(1-i)*.5})(ql(e.points,n,i,jl(r?.hintPosition??.5,o)),o)}}(cd(t.editor,e).info)}hitTest(e,t,n){return((e,t)=>{let n=1/0;for(let i=0;i<e.points.length-1;i++)n=Math.min(n,od(t,e.points[i],e.points[i+1]));return Number.isFinite(n)?n:t.dist(e.start.point)})(n?.editor?cd(n.editor,e).info:Kl(e),n?.pagePoint??t)<=Math.max(8,e.props.strokeWidth+4)}hitTestLineSegment(e,t){const n=t.editor?cd(t.editor,e).info:Kl(e),i=Math.max(8,e.props.strokeWidth+4,t.editor?t.pageMargin:t.positionedMargin),o=t.editor?t.pageStart:t.positionedStart,r=t.editor?t.pageEnd:t.positionedEnd;if(1===n.points.length)return zd(n.points[0],o,r)<=i;for(let s=0;s<n.points.length-1;s+=1){const e=n.points[s],t=n.points[s+1];if(e&&t&&Nd(o,r,e,t)<=i)return!0}return!1}}],shapeSvgExporters:[new class{type="arrow";toSvg(e,t){const n=t.resolveColor(e.props.stroke),i=ud(t.editor,e),o=Mo({outputBounds:i.bounds,cutoutLocalPolygons:t.editor.getShapeContentCutoutLocalPolygonsSignal(e.id).get()}),r=o?t.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"path",attrs:{d:o,"clip-rule":"evenodd","fill-rule":"evenodd"}}]}):void 0,s="arrow"===e.props.headStart?`url(#${t.addDef(Yd("start",n))})`:void 0,a="arrow"===e.props.headEnd?`url(#${t.addDef(Yd("end",n))})`:void 0;return{tag:"path",attrs:{d:i.path,fill:"none",stroke:n,"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":s,"marker-end":a,"clip-path":r?`url(#${r})`:void 0}}}}],bindingUtils:[new class extends OI{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,Ed(i.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,Ed(i.y,n.normalizedAnchor.y)))}}}canBind(e,t,n){return sd(n.fromShape)&&Td(e,n.toShape)}getExclusiveBindingKey(e){return`${e.fromId}:${e.props.terminal}`}onBindingCreate(e,t){return Ad(this.syncArrowTerminal(e,t))}onBindingUpdate(e,t,n){return Ad(this.syncArrowTerminal(e,n))}onBindingLoad(e,t){return Ad(this.syncArrowTerminal(e,t))}getGeometryDependentShapeIds(e,t,n){return"to"===n.role?[t.fromId]:[]}onAfterShapeChange(e,t,n){return Ad(this.syncArrowTerminal(e,t))}onBeforeDeleteShape(e,t,n){if("from"===n.role)return{deleteBindingIds:[t.id]};const i=e.getShape(t.fromId);if(!sd(i))return{deleteBindingIds:[t.id]};const o=this.resolveTerminalPagePoint(e,t);return{shapes:[o?Wl(e,i,t.props.terminal,o)??i:i],deleteBindingIds:[t.id]}}onBeforeDeleteBinding(e,t){const n=e.getShape(t.fromId);if(!sd(n))return{deleteBindingIds:[t.id]};const i=this.resolveTerminalPagePoint(e,t);return{shapes:[i?Wl(e,n,t.props.terminal,i)??n:n],deleteBindingIds:[t.id]}}syncArrowTerminal(e,t){if(!ad(t))return null;const n=e.getShape(t.fromId);if(!sd(n))return null;const i=this.resolveTerminalPagePoint(e,t);return i?zl(e,n,t.props.terminal).dist(i)<1e-6?null:Wl(e,n,t.props.terminal,i):null}resolveTerminalPagePoint(e,t){if(!ad(t))return null;const n=e.getShape(t.fromId),i=e.getShape(t.toId);if(!sd(n)||!i||sd(i))return null;const o=zl(e,n,Nl(t.props.terminal)),r=Ol(e,i,t.props.normalizedAnchor,o);return Id(e,{arrow:n,terminal:t.props.terminal,target:i,anchorPagePoint:Ul(e,i,t.props.normalizedAnchor),fallbackBoundaryPagePoint:r}).boundaryPagePoint}}],interactionHandlers:[{id:"land.arrow.interactions",selectionHandle:{createSession:(e,{handle:t,shape:n})=>sd(n)?"binding_terminal"===t.kind?(({handle:e,shapeId:t,terminal:n})=>({shapeId:t,historyMark:"select.binding_terminal_drag",handleSnapMode:"point",handleSnapContext:{shapeId:t,handle:e},shouldClearBindingPreviewOnExit:!0,update({editor:e,pagePoint:i,accelKey:o,source:r}){const s=e.getShape(t);if(!sd(s))return{status:"stop",finalPagePoint:null};const a=Wd(e,{arrow:s,terminal:n,rawPagePoint:i,ignoreTargets:o}),l=Rd(e,s.id,n,a,r);return{status:"continue",finalPagePoint:l?zl(e,l,n):a.pagePoint}}}))({handle:t,shapeId:n.id,terminal:t.terminal}):"binding_middle"===t.kind?(({shapeId:e})=>({shapeId:e,historyMark:"select.binding_middle_drag",update({editor:t,pagePoint:n,accelKey:i,source:o}){const r=t.getShape(e);if(!sd(r))return"stop";const s=((e,t)=>({start:dd(e,t,"start").handlePagePoint,end:dd(e,t,"end").handlePagePoint}))(t,r),a=Xl(s.start,s.end,n),l=t.computeShapeLocalToPageTransform(r).tryInvert();if(!l)return"stop";const d=Xl(l.applyToPoint(s.start),l.applyToPoint(s.end),l.applyToPoint(n)),c=0===(({bend:e,bypassSnap:t,zoom:n})=>t?e:Math.abs(e)*n<=6?0:e)({bend:a,bypassSnap:i,zoom:t.cameraZoomSignal.get()})?0:d;return t.commands.updateShapes([{id:r.id,props:{bend:c}}],{source:o}),"continue"}}))({shapeId:n.id}):null:null}}],setup(e){e.setTerminalBindingResolver(Hd),e.tools.register("arrow",e=>new qP(e),{shortcut:"a"})}},render:{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:function({shape:e,editor:t}){
69
- return Nx(ec,{shape:e,editor:t,idPrefix:"arrow",stroke:F(e.props.stroke),strokeWidth:e.props.strokeWidth})},hoverComponent:function({shape:e,editor:t,strokeWidth:n}){
70
- return Nx(ec,{dataUi:"arrow-hover-outline",shape:e,editor:t,idPrefix:"arrow-hover",stroke:qv,strokeWidth:n,vectorEffect:"non-scaling-stroke"})}}]},setup:e=>{e.get(MP).add(XP),e.get(IP).add(qd("stroke"),qd("strokeWidth"),{id:"arrow.set-direction",getAvailability:e=>"arrow"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:e=>(e=>{let t;for(const n of e){if("arrow"!==n.type)continue;const e=n.props,i=Gd(e.headStart,e.headEnd);if(void 0===t)t=i;else if(t!==i)return null}return t??null})(e.selection.selectedShapes),run({context:e,value:t}){const n=Zd(t);if(!n)return;const i=e.selection.selectedShapes.filter(e=>"arrow"===e.type).filter(e=>!e.isLocked).map(e=>({id:e.id,props:n}));i.length>0&&e.editor.commands.updateShapes(i,{source:"user"})}},jd("stroke"),jd("strokeWidth"),{id:"arrow.default-direction",getAvailability:e=>"arrow"===e.tool.activeToolId?"enabled":"inapplicable",getValue(e){const t=e.editor.getDefaultShapeProps("arrow");return Gd(t.headStart,t.headEnd)},run({context:e,value:t}){const n=Zd(t);n&&e.editor.updateDefaultShapeProps("arrow",n)}}),e.get(RP).add({id:"arrow.tool-toolbar",channel:BP.toolSwitcher,order:40,actionIds:[AP],getGroups:e=>[{id:"arrow.tools",items:[{kind:"button",id:"arrow.tool.arrow",actionId:AP,value:"arrow",label:"Arrow",shortcut:e.editor.shortcuts.getToolShortcutLabel("arrow"),icon:"arrow-right",dataUi:"arrow-tool-button"}]}]},{id:"arrow.default-style.tool-toolbar",channel:BP.toolOptions,order:41,actionIds:["arrow.default-stroke","arrow.default-strokeWidth","arrow.default-direction"],when:e=>"arrow"===e.tool.activeToolId,getGroups:()=>Xd({strokeActionId:"arrow.default-stroke",strokeWidthActionId:"arrow.default-strokeWidth",directionActionId:"arrow.default-direction",dataUiPrefix:"arrow-default"})},{id:"arrow.selection-toolbar",channel:BP.selectionProperties,order:20,actionIds:["arrow.set-stroke","arrow.set-strokeWidth","arrow.set-direction"],when:e=>"arrow"===e.selection.commonShapeType,getGroups:()=>Xd({strokeActionId:"arrow.set-stroke",strokeWidthActionId:"arrow.set-strokeWidth",directionActionId:"arrow.set-direction",dataUiPrefix:"arrow"})})}},JP=ml("plugin-frame.api"),ek={token:JP,create:({editor:e})=>e.shapeUtils.has("frame")?(e=>({create(t){const n=e.getDefaultShapeProps("frame"),[i]=e.commands.createShapes([{type:"frame",x:t.x,y:t.y,meta:t.meta?{...t.meta}:void 0,props:{...n,w:t.w??n.w,h:t.h??n.h,name:t.name??n.name,fill:t.fill??n.fill,stroke:t.stroke??n.stroke,strokeWidth:t.strokeWidth??n.strokeWidth}}],{source:"user"});return i&&"frame"===i.type?{id:i.id,type:i.type}:null},moveShapesToFrame(t,n){const i=e.getShape(n);if(!i||"frame"!==i.type)return[];const o=t.filter(t=>{const n=e.getShape(t);return!!n&&!n.isLocked});return 0===o.length?[]:(e.commands.reparentShapes({ids:o,parentId:n},{source:"user"}),o)}}))(e):null},tk=class extends Iv{constructor(e){super(e,"frame"),this.initial="idle",this.addChild(new nk(e,this)),this.addChild(new ik(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("frame")}},nk=class extends Iv{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})}},ik=class extends Iv{tool;info=null;operation=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.operation=this.editor.operations.begin({kind:"frame.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.commitOperation(),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.info=null}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}updateShape(e,t,n=!1){if(!this.info)return;this.info.currentPagePoint=e.clone(),this.info.shiftKey=t;const i=this.info.originPagePoint.dist(e);if(!this.info.shapeId&&i<4){if(!n)return;const t=(o=e,r=this.tool.getDefaultProps(),new SI(o.x-r.w/2,o.y-r.h/2,r.w,r.h)),i=this.createShape(t);return void(this.info.shapeId=i.id)}var o,r;const s=((e,t,n,i)=>{let o=t.x-e.x,r=t.y-e.y;if(n){const e=i.w/i.h,t=Math.abs(o),n=Math.abs(r);0===n||t/Math.max(n,1)>=e?r=t/e*(r<0?-1:1):o=n*e*(o<0?-1:1)}const s=new mI(e.x+o,e.y+r);return new SI(Math.min(e.x,s.x),Math.min(e.y,s.y),Math.max(Math.abs(s.x-e.x),1),Math.max(Math.abs(s.y-e.y),1))})(this.info.originPagePoint,e,t,this.tool.getDefaultProps());if(!this.info.shapeId){const e=this.createShape(s);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:s.x,y:s.y,props:{w:s.w,h:s.h}}],{source:"user"})}createShape(e){const[t]=this.editor.commands.createShapes([{type:"frame",x:e.x,y:e.y,props:{...this.tool.getDefaultProps(),w:e.w,h:e.h}}],{source:"user",autoReparent:!1});if(!t||"frame"!==t.type)throw new Error("Failed to create frame shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},ok=[{id:"none",value:E("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:M("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:M("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:M("fill-amber"),label:"Amber",id:"amber",hexColor:"#fff7ed"}],rk=[{value:M("stroke-muted"),label:"Slate",id:"muted",hexColor:"#94a3b8"},{value:M("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("stroke-orange"),label:"Orange",id:"orange",hexColor:"#ea580c"}],sk='[data-ui="frame-canvas-heading"]',ak=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),lk={id:"land.frame.name.dom-events",handle({event:e}){const t=e.target;return t instanceof Element&&t.closest(sk)?"handled":"continue"},getCursor:({element:e})=>e?.closest(sk)?"text":void 0},dk={id:"frame",provides:[JP],editor:{id:"land.frame",shapeCapabilities:[{type:"frame",schemaProps:["w","h","name","fill","stroke","strokeWidth"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Frame renderer, SVG exporter, creation tool, selected-frame style toolbar, selected-child order badge, and minimal single-child sibling reorder controls live in the frame plugin package. ParentId-based child query, child-index ordering, containing-parent query, clipped query bounds, point-in-clip checks, host clipping, select-drag containment, export descendant traversal, and clipped child export have preflights. Richer hover/drag reorder UI remains deferred."]}],shapeUtils:[new class extends xv{type="frame";getDefaultProps(){return{w:640,h:360,name:"",fill:E("transparent"),stroke:M("stroke-muted"),strokeWidth:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(1,ic(t.w,n.w)),h:Math.max(1,ic(t.h,n.h)),name:"string"==typeof t.name?t.name:n.name,fill:$(t.fill,n.fill),stroke:$(t.stroke,n.stroke),strokeWidth:Math.max(0,ic(t.strokeWidth,n.strokeWidth))}}getLocalBounds(e){return new SI(0,0,e.props.w,e.props.h)}getRenderBounds(e){return nc(e)}getPointHitTestBounds(e){return this.getPositionedBounds(e).expand(3)}canEdit(e){return!0}canReceiveChildren(e){return!0}canSnapChildrenToSelf(e){return!0}canReceiveTerminalBinding(e){return!0}getSelectionResizeHandleIds(e,t){return JI}shouldRotateDescendants(e){return!0}getChildClipLocalBounds(e){return this.getLocalBounds(e)}canSelectByBrush(e,t){return super.isWrappedByBrush(e,t)}hitTest(e,t){return oc(this.getPositionedBounds(e),t,6)}hitTestBindingTarget(e,t){return this.getPositionedBounds(e).containsPoint(t)}hitTestLineSegment(e,t){return((e,t,n,i)=>{const o=i/2;if(oc(e,t,i)||oc(e,n,i))return!0;const r=[new mI(e.minX,e.minY),new mI(e.maxX,e.minY),new mI(e.maxX,e.maxY),new mI(e.minX,e.maxY)];for(let s=0;s<r.length;s+=1){const e=r[s],i=r[(s+1)%r.length];if(e&&i&&v(t,n,e,i)<=o)return!0}return!1})(this.getPositionedBounds(e),t.positionedStart,t.positionedEnd,Math.max(6,t.positionedMargin))}}],shapeSvgExporters:[new class{type="frame";toSvg(e,t){const{fill:n,stroke:i,strokeWidth:o,w:r,h:s,name:a}=e.props,l=t.resolveColor(i),d=o/2;return{tag:"g",children:[{tag:"rect",attrs:{x:d,y:d,width:Math.max(r-o,0),height:Math.max(s-o,0),fill:t.resolveColor(n),stroke:l,"stroke-width":o,"stroke-linejoin":"round","stroke-linecap":"round"}},{tag:"text",attrs:{x:0,y:-8,fill:l,"font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":400},children:[tc(a)]}]}}}],setup(e){e.tools.register("frame",e=>new tk(e),{shortcut:"f"})}},render:{id:"land.frame.react",domEventGuards:[lk],shapeRenderers:[{type:"frame",component:function({editor:e,shape:t,shapeEditingSession:n}){const i=n?.shapeId===t.id;
71
- return Hx("div",{style:{height:"100%",overflow:"visible",position:"relative",width:"100%"},children:[Nx(pc,{shape:t,hideName:!0}),Nx(gc,{editor:e,shape:t,isEditing:i})]})},hoverComponent:function({shape:e,strokeWidth:t}){const{h:n,w:i}=e.props,o=nc(e);
72
- return Nx("svg",{"data-ui":"frame-hover-outline",width:"100%",height:"100%",viewBox:`${o.x} ${o.y} ${o.w} ${o.h}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Nx("rect",{x:0,y:0,width:i,height:n,fill:"none",stroke:qv,strokeWidth:t,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"non-scaling-stroke"})})}}]},setup:e=>{e.get(MP).add(ek),e.get(IP).add(rc("fill"),rc("stroke"),rc("strokeWidth"),sc("fill"),sc("stroke"),sc("strokeWidth"),{id:"frame.rename",getAvailability(e){if(1!==e.selection.count||"frame"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;return"frame"!==t?.type||t.isLocked?"disabled":"enabled"},getValue(e){const[t]=e.selection.selectedShapes;return"frame"===t?.type?t.props.name:null},run({context:e,value:t}){const[n]=e.selection.selectedShapes;"frame"===n?.type&&"string"==typeof t&&e.editor.commands.updateShapes([{id:n.id,props:{name:t}}],{source:"user"})}},lc("backward"),lc("forward")),e.get(RP).add({id:"frame.tool-toolbar",channel:BP.toolSwitcher,order:60,actionIds:[AP],getGroups:e=>[{id:"frame.tools",items:[{kind:"button",id:"frame.tool.frame",actionId:AP,value:"frame",label:"Frame",shortcut:e.editor.shortcuts.getToolShortcutLabel("frame"),icon:"frame",dataUi:"frame-tool-button"}]}]},{id:"frame.default-style.tool-toolbar",channel:BP.toolOptions,order:61,actionIds:["frame.default-fill","frame.default-stroke","frame.default-strokeWidth"],when:e=>"frame"===e.tool.activeToolId,getGroups:()=>ac({fillActionId:"frame.default-fill",strokeActionId:"frame.default-stroke",strokeWidthActionId:"frame.default-strokeWidth",dataUiPrefix:"frame-default"})},{id:"frame.selection-toolbar",channel:BP.selectionProperties,order:20,actionIds:["frame.set-fill","frame.set-stroke","frame.set-strokeWidth","frame.rename"],when:e=>"frame"===e.selection.commonShapeType,getGroups:e=>[...1===e.selection.count?[{id:"frame.name",items:[{kind:"text-input",id:"frame.name",actionId:"frame.rename",label:"Frame name",placeholder:"Frame",dataUi:"frame-name-input"}]}]:[],...ac({fillActionId:"frame.set-fill",strokeActionId:"frame.set-stroke",strokeWidthActionId:"frame.set-strokeWidth",dataUiPrefix:"frame"})]},{id:"frame.child-order.selection-toolbar",channel:BP.selectionProperties,order:30,actionIds:["frame.child-order.backward","frame.child-order.forward"],when:e=>"frame"===hc(e),getGroups(e){const t=e.editor.getSelectionSiblingOrderState();return[{id:"frame.child-order",presentation:"overflow",items:[...t?[{kind:"badge",id:"frame.child-order-status",label:`${t.index+1} / ${t.count}`,dataUi:"frame-child-order-status"}]:[],{kind:"button",id:"frame.child-order.backward",actionId:"frame.child-order.backward",label:"Send backward",icon:"stack-backward",dataUi:"frame-child-send-backward-button"},{kind:"button",id:"frame.child-order.forward",actionId:"frame.child-order.forward",label:"Bring forward",icon:"stack-forward",dataUi:"frame-child-bring-forward-button"}]}]}}),e.get(kP).add({id:"frame.child-order.context-menu",target:"selection",order:40,actionIds:["frame.child-order.backward","frame.child-order.forward"],when:e=>"frame"===hc(e),getSections(e){const t=e.editor.getSelectionSiblingOrderState();return[{id:"frame.child-order-context-menu",title:"Frame child",items:[...t?[{kind:"badge",id:"frame.child-order-status",label:`${t.index+1} / ${t.count}`,dataUi:"context-menu-frame-child-order-status"}]:[],{kind:"command",id:"frame.child-order.forward",actionId:"frame.child-order.forward",label:"Bring forward",icon:"stack-forward",dataUi:"context-menu-frame-child-bring-forward-button"},{kind:"command",id:"frame.child-order.backward",actionId:"frame.child-order.backward",label:"Send backward",icon:"stack-backward",dataUi:"context-menu-frame-child-send-backward-button"}]}]}})}},ck=class extends Iv{geo;constructor(e,t,n){super(e,t),this.geo=n,this.initial="idle",this.addChild(new uk(e,this)),this.addChild(new hk(e,this))}getDefaultProps(){return{...this.editor.getDefaultShapeProps("geo"),geo:this.geo}}onEnter(){this.editor.updateDefaultShapeProps("geo",{geo:this.geo})}},uk=class extends Iv{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})}},hk=class extends Iv{tool;info=null;operation=null;constructor(e,t){super(e,"creating",t),this.tool=t}onEnter(e){this.info=e,this.operation=this.editor.operations.begin({kind:"geo.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(e){this.updateShape(e.pagePoint,e.shiftKey)}onPointerUp(e){this.info?(this.updateShape(e.pagePoint,e.shiftKey,!0),this.info.shapeId&&ke(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.isToolLocked()?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.info=null}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}updateShape(e,t,n=!1){if(!this.info)return;this.info.currentPagePoint=e.clone(),this.info.shiftKey=t;const i=this.info.originPagePoint.dist(e);if(!this.info.shapeId&&i<4){if(!n)return;const t=(o=e,r=this.tool.getDefaultProps(),new SI(o.x-r.w/2,o.y-r.h/2,r.w,r.h)),i=this.createShape(t);return void(this.info.shapeId=i.id)}var o,r;const s=((e,t,n)=>{let i=t.x-e.x,o=t.y-e.y;if(n){const e=Math.max(Math.abs(i),Math.abs(o));i=(i<0?-1:1)*e,o=(o<0?-1:1)*e}const r=new mI(e.x+i,e.y+o);return new SI(Math.min(e.x,r.x),Math.min(e.y,r.y),Math.max(Math.abs(r.x-e.x),1),Math.max(Math.abs(r.y-e.y),1))})(this.info.originPagePoint,e,t);if(!this.info.shapeId){const e=this.createShape(s);return void(this.info.shapeId=e.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:s.x,y:s.y,props:{w:s.w,h:s.h}}],{source:"user"})}createShape(e){const[t]=this.editor.commands.createShapes([{type:"geo",x:e.x,y:e.y,props:{...this.tool.getDefaultProps(),w:e.w,h:e.h}}],{source:"user",autoReparent:!1});if(!t)throw new Error("Failed to create geo shape");return this.editor.commands.setSelectedShapeIds([t.id],{source:"system"}),t}},pk=class extends ck{constructor(e){super(e,"rectangle","rectangle")}},gk=class extends ck{constructor(e){super(e,"ellipse","ellipse")}},fk=class extends ck{constructor(e){super(e,"rhombus","rhombus")}},mk=class extends ck{constructor(e){super(e,"triangle","triangle")}},Sk=class extends ck{constructor(e){super(e,"hexagon","hexagon")}},yk=class extends ck{constructor(e){super(e,"star","star")}},bk=ml("plugin-geo.api"),xk={token:bk,create:({editor:e})=>e.shapeUtils.has("geo")?(e=>({createRectangle:t=>fc(e,"rectangle",t),createEllipse:t=>fc(e,"ellipse",t),createRhombus:t=>fc(e,"rhombus",t),createTriangle:t=>fc(e,"triangle",t),createHexagon:t=>fc(e,"hexagon",t),createStar:t=>fc(e,"star",t)}))(e):null},Ik=["rectangle","ellipse","rhombus","triangle","hexagon","star"],vk=["solid","dashed","dotted","none"],wk=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],Pk=[{value:M("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:M("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:M("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:M("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],kk=[{value:M("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:M("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],Ck=[{value:"solid",label:"Solid",icon:"minus"},{value:"dashed",label:"Dashed",icon:"stroke-dashed"},{value:"dotted",label:"Dotted",icon:"stroke-dotted"},{value:"none",label:"None",icon:"x"}],Tk=[{value:"rectangle",label:"Rectangle",icon:"square",dataUiPrefix:"rectangle"},{value:"ellipse",label:"Ellipse",icon:"circle",dataUiPrefix:"ellipse"},{value:"rhombus",label:"Rhombus",icon:"square-rotated",dataUiPrefix:"rhombus"},{value:"triangle",label:"Triangle",icon:"triangle",dataUiPrefix:"triangle"},{value:"hexagon",label:"Hexagon",icon:"hexagon",dataUiPrefix:"hexagon"},{value:"star",label:"Star",icon:"star",dataUiPrefix:"star"}],Mk={id:"geo",provides:[bk],editor:{id:"land.geo",shapeCapabilities:[{type:"geo",schemaProps:["w","h","geo","fill","stroke","strokeStyle","strokeWidth","cornerRadiusPercent"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Toolbar covers built-in geo variants through geo props."]}],shapeUtils:[new class extends xv{type="geo";getDefaultProps(){return{w:160,h:108,geo:"rectangle",fill:M("fill-slate"),stroke:M("stroke-slate"),strokeStyle:"solid",strokeWidth:2,cornerRadiusPercent:12}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,Tc(t.w,n.w)),h:Math.max(24,Tc(t.h,n.h)),geo:kc(t.geo)?t.geo:n.geo,fill:$(t.fill,n.fill),stroke:$(t.stroke,n.stroke),strokeStyle:Cc(t.strokeStyle)?t.strokeStyle:n.strokeStyle,strokeWidth:Math.max(1,Tc(t.strokeWidth,n.strokeWidth)),cornerRadiusPercent:Sc(t.cornerRadiusPercent,n.cornerRadiusPercent)}}getLocalBounds(e){return new SI(0,0,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getPositionedOutlineVertices(e){return mc(this.getPositionedBounds(e),e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent})}getHandleSnapGeometry(e){return{points:$c(e),outline:Lc(e)}}hitTest(e,t){const n=this.getPositionedBounds(e);switch(e.props.geo){case"ellipse":{const e=n.w/2,i=n.h/2;if(e<=0||i<=0)return!1;const o=t.x-n.center.x,r=t.y-n.center.y;return o*o/(e*e)+r*r/(i*i)<=1}case"rhombus":case"triangle":case"hexagon":case"star":return xc(t,bc(n,e.props.geo));default:return xc(t,bc(n,"rectangle",{cornerRadiusPercent:e.props.cornerRadiusPercent}))}}hitTestLineSegment(e,t){const n=this.getPositionedBounds(e);switch(e.props.geo){case"ellipse":return((e,t,n,i)=>{const o=e.center,r=e.w/2+i,s=e.h/2+i;if(r<=0||s<=0)return!1;const a=n.sub(t),l=t.sub(o),d=a.x/r,c=a.y/s,u=l.x/r,h=l.y/s,p=d*d+c*c,g=2*(u*d+h*c),f=u*u+h*h-1;if(f<=0)return!0;const m=g*g-4*p*f;if(0===p||m<0)return!1;const S=Math.sqrt(m),y=(-g-S)/(2*p),b=(-g+S)/(2*p);return y>=0&&y<=1||b>=0&&b<=1})(n,t.positionedStart,t.positionedEnd,t.positionedMargin);case"rectangle":case"rhombus":case"triangle":case"hexagon":case"star":{const i=bc(n,e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent});return this.hitTest(e,t.positionedStart)||this.hitTest(e,t.positionedEnd)||((e,t,n,i)=>{if(n.length<3)return!1;for(let o=0;o<n.length;o+=1){const r=n[o],s=n[(o+1)%n.length];if(r&&s&&Ac(e,t,r,s)<=i)return!0}return!1})(t.positionedStart,t.positionedEnd,i,t.positionedMargin)}default:return super.hitTestLineSegment(e,t)}}resolveBindingPoint(e,t){const n=t.editor.computeShapePositionedToPageTransform(e),i=n.tryInvert();if(!i)return t.rawPagePoint;const o=function(e,t,n){const i=new SI(e.x,e.y,e.props.w,e.props.h);switch(e.props.geo){case"ellipse":return((e,t,n)=>{const i=e.w/2,o=e.h/2;if(i<=0||o<=0)return null;const r=t.sub(e.center),s=n.sub(t),a=s.x/i,l=s.y/o,d=r.x/i,c=r.y/o,u=a*a+l*l,h=2*(d*a+c*l),p=h*h-4*u*(d*d+c*c-1);if(0===u||p<0)return null;const g=Math.sqrt(p),f=[(-h-g)/(2*u),(-h+g)/(2*u)].filter(e=>e>1e-6&&e<=1).sort((e,t)=>e-t)[0];return void 0===f?null:t.add(s.mul(f))})(i,t,n);case"rectangle":return Rc(t,n,bc(i,e.props.geo,{cornerRadiusPercent:e.props.cornerRadiusPercent}));default:return Rc(t,n,bc(i,e.props.geo))}}(e,i.applyToPoint(t.rawPagePoint),i.applyToPoint(t.oppositePagePoint));return o?n.applyToPoint(o):t.rawPagePoint}}],shapeSvgExporters:[new class{type="geo";toSvg(e,t){const{geo:n,fill:i,stroke:o,strokeStyle:r,strokeWidth:s,w:a,h:l}=e.props,d="none"===r?0:s,c=d/2,u=Math.max(a-d,0),h=Math.max(l-d,0),p={fill:t.resolveColor(i),stroke:"none"===r?"none":t.resolveColor(o),"stroke-width":d,"stroke-dasharray":Fc(r,s),"stroke-linejoin":"round","stroke-linecap":"round"};if("ellipse"===n)return{tag:"ellipse",attrs:{...p,cx:a/2,cy:l/2,rx:u/2,ry:h/2}};if("rectangle"!==n){const e=bc(new SI(c,c,u,h),n).map(e=>`${Uc(e.x)},${Uc(e.y)}`).join(" ");return{tag:"polygon",attrs:{...p,points:e}}}const g=yc({cornerRadiusPercent:e.props.cornerRadiusPercent,w:u,h:h});return{tag:"rect",attrs:{...p,x:c,y:c,width:u,height:h,rx:g,ry:g}}}}],setup(e){e.tools.register("rectangle",e=>new pk(e),{shortcut:"r"}),e.tools.register("ellipse",e=>new gk(e),{shortcut:"o"}),e.tools.register("rhombus",e=>new fk(e),{shortcut:"d"}),e.tools.register("triangle",e=>new mk(e)),e.tools.register("hexagon",e=>new Sk(e)),e.tools.register("star",e=>new yk(e))}},render:{id:"land.geo.react",shapeRenderers:[{type:"geo",component:function({shape:e}){
73
- return Nx(qc,{shape:e})},hoverComponent:function({shape:e,strokeWidth:t}){const{geo:n,h:i,w:o}=e.props,r=yc({cornerRadiusPercent:e.props.cornerRadiusPercent,w:o,h:i}),s="ellipse"===n||"rectangle"===n?null:bc(new SI(0,0,o,i),n).map(e=>`${e.x},${e.y}`).join(" "),a={fill:"none",stroke:qv,strokeWidth:t,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"non-scaling-stroke"};
74
- return Nx("svg",{"data-ui":"geo-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${o} ${i}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:"ellipse"===n?Nx("ellipse",{...a,cx:o/2,cy:i/2,rx:o/2,ry:i/2}):"rectangle"!==n?Nx("polygon",{...a,points:s??""}):Nx("rect",{...a,x:0,y:0,width:o,height:i,rx:r,ry:r})})}}]},setup:e=>{e.get(MP).add(xk),e.get(IP).add({id:"geo.set-kind",getAvailability:e=>"geo"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:e=>Nc(e.selection.selectedShapes),run({context:e,value:t}){if(!kc(t))return;const n=e.selection.selectedShapes.filter(Pc).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{geo:t}}));0!==n.length&&e.editor.commands.updateShapes(n,{source:"user"})}},Oc("fill"),Oc("stroke"),Oc("strokeStyle"),Oc("strokeWidth"),{id:"geo.set-cornerRadiusPercent",getAvailability:e=>"rectangle"!==Nc(e.selection.selectedShapes)?"inapplicable":e.selection.selectedShapes.some(e=>Pc(e)&&"rectangle"===e.props.geo&&!e.isLocked)?"enabled":"disabled",getValue(e){const t=(e=>{let t;for(const n of e){if(!Pc(n)||"rectangle"!==n.props.geo)continue;const e=Sc(n.props.cornerRadiusPercent);if(void 0!==t){if(t!==e)return null}else t=e}return t??null})(e.selection.selectedShapes);return null===t?null:(e=>Number(e.toFixed(2)).toString())(t)},run({context:e,value:t}){const n=Hc(t);if(null===n)return;const i=Sc(n),o=e.selection.selectedShapes.filter(Pc).filter(e=>"rectangle"===e.props.geo&&!e.isLocked).map(e=>({id:e.id,props:{cornerRadiusPercent:i}}));0!==o.length&&e.editor.commands.updateShapes(o,{source:"user"})}},Dc("fill"),Dc("stroke"),Dc("strokeStyle"),Dc("strokeWidth")),e.get(RP).add({id:"geo.tool-toolbar",channel:BP.toolSwitcher,order:20,actionIds:[AP],getGroups:e=>[{id:"geo.tools",items:[{kind:"segmented",id:"geo.tool-picker",actionId:AP,options:Tk.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-tool-option`}))}]}]},{id:"geo.default-style.tool-toolbar",channel:BP.toolOptions,order:21,actionIds:["geo.default-fill","geo.default-stroke","geo.default-strokeStyle","geo.default-strokeWidth"],when:e=>Xc(e.tool.activeToolId),getGroups:()=>zc({fillActionId:"geo.default-fill",strokeActionId:"geo.default-stroke",strokeStyleActionId:"geo.default-strokeStyle",strokeWidthActionId:"geo.default-strokeWidth",dataUiPrefix:"geo-default"})},{id:"geo.selection-toolbar",channel:BP.selectionProperties,order:20,actionIds:["geo.set-kind","geo.set-fill","geo.set-stroke","geo.set-strokeStyle","geo.set-strokeWidth","geo.set-cornerRadiusPercent"],when:e=>"geo"===e.selection.commonShapeType,getGroups(e){const t=Nc(e.selection.selectedShapes);return[{id:"geo.shape-kind",items:[{kind:"segmented",id:"geo.shape-kind",actionId:"geo.set-kind",options:Tk.map(e=>({value:e.value,label:e.label,icon:e.icon,dataUi:`${e.dataUiPrefix}-shape-button`}))}]},...zc({fillActionId:"geo.set-fill",strokeActionId:"geo.set-stroke",strokeStyleActionId:"geo.set-strokeStyle",strokeWidthActionId:"geo.set-strokeWidth",dataUiPrefix:"geo"}),..."rectangle"===t?[(n="geo.set-cornerRadiusPercent",i="geo",{id:`${i}.style-corner-radius-percent`,items:[{kind:"text-input",id:`${i}.corner-radius-percent`,actionId:n,label:"Corner radius %",icon:"border-corner-pill",placeholder:"0",suffix:"%",validate:Wc,dataUi:`${i}-corner-radius-percent-control`}]})]:[]];var n,i}})}},Ek=er("canvas-kit.tool-actions"),Ak=Object.freeze({document:Object.freeze({updateMeta:Gc("document.update-meta")}),session:Object.freeze({updateMeta:Gc("session.update-meta")}),history:Object.freeze({clear:Gc("history.clear"),undo:Gc("history.undo"),redo:Gc("history.redo")}),selection:Object.freeze({select:Gc("selection.select"),selectAll:Gc("system.selection.select-all"),delete:Gc("system.selection.delete"),duplicate:Gc("system.selection.duplicate"),resetRotation:Gc("system.selection.reset-rotation"),flipHorizontal:Gc("system.selection.flip-horizontal"),flipVertical:Gc("system.selection.flip-vertical"),setOpacity:Gc("system.selection.set-opacity"),align:Gc("system.selection.align"),distribute:Gc("system.selection.distribute")}),shape:Object.freeze({delete:Gc("shape.delete"),update:Gc("shape.update"),updateMeta:Gc("shape.update-meta")}),layer:Object.freeze({setHidden:Gc("layer.set-hidden"),setLocked:Gc("layer.set-locked"),group:Gc("layer.group"),ungroup:Gc("layer.ungroup"),sendBackward:Gc("layer.send-backward"),bringForward:Gc("layer.bring-forward"),sendToBack:Gc("layer.send-to-back"),bringToFront:Gc("layer.bring-to-front"),moveToPlacement:Gc("layer.move-to-placement")}),tool:Object.freeze({setActive:Gc(AP),toggleLocked:Gc("editor.tool.toggle-locked")}),view:Object.freeze({centerOnShape:Gc("view.center-on-shape"),setCamera:Gc("view.set-camera"),zoomIn:Gc("system.view.zoom-in"),zoomOut:Gc("system.view.zoom-out"),resetZoom:Gc("system.view.reset-zoom"),reset:Gc("view.reset")}),page:Object.freeze({create:Gc("page.create"),rename:Gc("page.rename"),updateMeta:Gc("page.update-meta"),delete:Gc("page.delete"),select:Gc("page.select")})}),Bk=Zc({token:Ak.document.updateMeta,run(e,t){e.updateDocumentMeta(t,"user")}}),Rk=Zc({token:Ak.session.updateMeta,run(e,t){const n=e.getSessionRecord();e.updateSession({meta:{...n.meta,...t}},"user")}}),Lk=Zc({token:Ak.history.clear,run(e){e.history.clear()}}),$k=Zc({token:Ak.history.undo,run:e=>e.undo()}),Fk=Zc({token:Ak.history.redo,run:e=>e.redo()}),Uk=Zc({token:Ak.layer.setHidden,run:(e,t)=>e.setShapesHidden(t.ids,t.isHidden,"user")}),Ok=Zc({token:Ak.layer.setLocked,run:(e,t)=>e.setShapesLocked(t.ids,t.isLocked,"user")}),Dk=Zc({token:Ak.layer.group,run:(e,t)=>e.groupShapes(t,"user")?.id??null}),zk=Zc({token:Ak.layer.ungroup,run:(e,t)=>e.ungroupShapes(t,"user")}),Nk=Zc({token:Ak.layer.sendBackward,run:(e,t)=>e.moveShapesInParentOrder(t,"backward","user")}),Hk=Zc({token:Ak.layer.bringForward,run:(e,t)=>e.moveShapesInParentOrder(t,"forward","user")}),Wk=Zc({token:Ak.layer.sendToBack,run:(e,t)=>e.moveShapesToParentOrderEdge(t,"back","user")}),_k=Zc({token:Ak.layer.bringToFront,run:(e,t)=>e.moveShapesToParentOrderEdge(t,"front","user")}),Kk=Zc({token:Ak.layer.moveToPlacement,run:(e,t)=>e.moveShapesToParentPlacementResult({ids:t.ids,parentId:t.placement.parentId,beforeId:t.placement.beforeId},"user")}),Yk=Zc({token:Ak.page.create,run:(e,t)=>e.createPageAndSelect(t?{name:t.name,meta:t.meta?{...t.meta}:void 0}:void 0,"user")}),Xk=Zc({token:Ak.page.rename,run(e,t){e.renamePage(t.pageId,t.name,"user")}}),qk=Zc({token:Ak.page.updateMeta,run:(e,t)=>e.updatePageMeta(t.pageId,t.patch,"user")?.id??null}),jk=Zc({token:Ak.page.delete,run:(e,t)=>e.deletePage(t,"user")}),Vk=Zc({token:Ak.page.select,run(e,t){e.selectPage(t,"user")}}),Gk=Zc({token:Ak.selection.select,run(e,t){e.commands.setSelectedShapeIds(t,{source:"user"})}}),Zk=Zc({token:Ak.selection.selectAll,run(e){e.selectAllCurrentPage("user")}}),Qk=Zc({token:Ak.selection.delete,run(e){e.deleteSelection("user")}}),Jk=Zc({token:Ak.selection.duplicate,run:e=>e.duplicateSelection({source:"user"})}),eC=Zc({token:Ak.selection.resetRotation,run(e){e.resetSelectionRotation("user")}}),tC=Zc({token:Ak.selection.flipHorizontal,run(e){e.flipSelection("horizontal","user")}}),nC=Zc({token:Ak.selection.flipVertical,run(e){e.flipSelection("vertical","user")}}),iC=Zc({token:Ak.selection.setOpacity,run(e,t){if(!Number.isFinite(t))return;const n=Math.min(1,Math.max(0,t)),i=e.getSelectedShapes().filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));i.length>0&&e.commands.updateShapes(i,{source:"user"})}}),oC=Zc({token:Ak.selection.align,run:(e,t)=>e.alignSelection(t,"user")}),rC=Zc({token:Ak.selection.distribute,run:(e,t)=>e.distributeSelection(t,"user")}),sC=Zc({token:Ak.shape.delete,run(e,t){e.deleteShapesById(t,"user")}}),aC=Zc({token:Ak.shape.update,run(e,t){const n=t.filter(t=>{const n=e.getShape(t.id);return!!n&&function(e,t){return!(!t.props&&void 0===t.meta)||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(i=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):i))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,i}(n,t)}).map(Qc);return 0===n.length?[]:(e.commands.updateShapes(n,{source:"user"}),n.map(e=>e.id))}}),lC=Zc({token:Ak.shape.updateMeta,run(e,t){const n=e.getShape(t.id);return n?(e.commands.updateShapes([{id:t.id,meta:{...n.meta,...t.patch}}],{source:"user"}),t.id):null}}),dC=Zc({token:Ak.tool.setActive,run(e,t){if(!e.tools.hasTool(t))throw new Error(`Unknown product tool "${t}".`);e.setActiveTool(t,"user")}}),cC=Zc({token:Ak.tool.toggleLocked,run(e){e.toggleToolLocked("system")}}),uC=Zc({token:Ak.view.centerOnShape,run(e,t){const n=e.getShapePageId(t);if(!n)return!1;n!==e.getCurrentPageId()&&e.commands.setCurrentPageId(n,{source:"user"});const i=e.getShapeSubtreePageBounds(t);if(!i)return!1;const o=e.viewportScreenSizeSignal.get();if(o.w<=0||o.h<=0)return!1;const r=e.getCurrentCamera();return e.commands.setCamera({pageId:n,camera:{x:i.center.x-o.w/(2*r.z),y:i.center.y-o.h/(2*r.z),z:r.z}},{source:"user"}),!0}}),hC=Zc({token:Ak.view.setCamera,run(e,t){e.commands.setCamera({pageId:t.pageId,camera:t.camera},{source:"user"})}}),pC=Zc({token:Ak.view.zoomIn,run(e){e.zoomAtViewportCenter(-120,"system")}}),gC=Zc({token:Ak.view.zoomOut,run(e){e.zoomAtViewportCenter(120,"system")}}),fC=Zc({token:Ak.view.resetZoom,run(e){e.resetZoom("user")}}),mC=Zc({token:Ak.view.reset,run(e){e.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})}}),SC=new WeakMap,yC=[eu(dC,{getValue:e=>e.tool.activeToolId,toCommandArgs:({context:e,value:t})=>"string"==typeof t&&e.editor.tools.hasTool(t)?[t]:null}),Jc(cC,{getValue:e=>e.tool.isToolLocked})],bC={id:"canvas-kit.tool-actions",provides:[Ek],setup(e){e.get(IP).add(...yC),e.get(vP).provide(Ek,!0)}},xC=er("canvas-kit.import-host"),IC=nr("land.canvas-kit.plugin-setup.lifecycle"),vC=nr("land.canvas-kit.plugin-setup.persistence"),wC=nr("land.canvas-kit.plugin-setup.ui"),PC=MP,kC=nr("land.canvas-kit.plugin-setup.assets"),CC={id:"canvas-kit.import-host",provides:[xC],setup(e){e.get(vP).provide(xC,!0),e.get(wC).addComponents({id:"canvas-kit.import-host",order:50,component:nu})}},TC=er("canvas-kit.clipboard-runtime"),MC=Sl("canvas-kit.clipboard-service"),EC="system.clipboard.copy",AC="system.clipboard.cut",BC="system.clipboard.paste",RC="system.clipboard.paste-at-point",LC={id:"canvas-kit.clipboard-runtime",provides:[TC,MC],setup(e){const t=e.get(EP);t.add({token:MC,create(){let e=null;return{async write(t){e=t},read:async()=>e,getMemoryPayload:()=>e}}}),e.get(IP).add(...function(e){return[{id:EC,getAvailability:t=>0===t.selection.count?"inapplicable":du(e)?"enabled":"disabled",run({context:t}){cu({context:t,services:e})}},{id:AC,getAvailability:t=>0===t.selection.count?"inapplicable":du(e)?"enabled":"disabled",run({context:t}){(async({context:e,services:t})=>{await cu({context:e,services:t})&&e.editor.deleteSelection("user")})({context:t,services:e})}},{id:BC,getAvailability:()=>du(e)?.getMemoryPayload()?"enabled":"inapplicable",run({context:t}){uu({context:t,services:e})}},{id:RC,getAvailability:t=>pu(t)&&du(e)?.getMemoryPayload()?"enabled":"inapplicable",run({context:t}){pu(t)&&uu({context:t,services:e,atMenuPoint:!0})}}]}(t)),e.get(vP).provide(TC,!0)}},$C=Tx(null),FC=Math.min,UC=Math.max,OC=Math.round,DC=Math.floor,zC=e=>({x:e,y:e}),NC={left:"right",right:"left",bottom:"top",top:"bottom"},HC=["left","right"],WC=["right","left"],_C=["top","bottom"],KC=["bottom","top"],YC=new Set(["left","top"]),XC=/transform|translate|scale|rotate|perspective|filter/,qC=/paint|layout|strict|content/,jC=e=>!!e&&"none"!==e,VC=zC(0),GC={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:i,strategy:o}=e;const r="fixed"===o,s=Ou(i),a=!!t&&Ku(t.floating);if(i===s||a&&r)return n;let l={scrollLeft:0,scrollTop:0},d=zC(1);const c=zC(0),u=Nu(i);if((u||!u&&!r)&&(("body"!==Fu(i)||Wu(s))&&(l=Vu(i)),u)){const e=oh(i);d=nh(i),c.x=e.x+i.clientLeft,c.y=e.y+i.clientTop}const h=!s||u||r?zC(0):sh(s,l);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+c.x+h.x,y:n.y*d.y-l.scrollTop*d.y+c.y+h.y}},getDocumentElement:Ou,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:i,strategy:o}=e;const r=[..."clippingAncestors"===n?Ku(t)?[]:dh(t,this._c):[].concat(n),i],s=ah(t,r[0],o);let a=s.top,l=s.right,d=s.bottom,c=s.left;for(let u=1;u<r.length;u++){const e=ah(t,r[u],o);a=UC(e.top,a),l=FC(e.right,l),d=FC(e.bottom,d),c=UC(e.left,c)}return{width:l-c,height:d-a,x:c,y:a}},getOffsetParent:ph,getElementRects:async function(e){const t=this.getOffsetParent||ph,n=this.getDimensions,i=await n(e.floating);return{reference:ch(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=eh(e);return{width:t,height:n}},getScale:nh,isElement:zu,isRTL:e=>"rtl"===ju(e).direction},ZC=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,i;const{x:o,y:r,placement:s,middlewareData:a}=t,l=await(async(e,t)=>{const{placement:n,platform:i,elements:o}=e,r=await(null==i.isRTL?void 0:i.isRTL(o.floating)),s=wu(n),a=Pu(n),l="y"===Tu(n),d=YC.has(s)?-1:1,c=r&&l?-1:1,u=vu(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:g}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof g&&(p="end"===a?-1*g:g),l?{x:p*c,y:h*d}:{x:h*d,y:p*c}})(t,e);return s===(null==(n=a.offset)?void 0:n.placement)&&null!=(i=a.arrow)&&i.alignmentOffset?{}:{x:o+l.x,y:r+l.y,data:{...l,placement:s}}}}),QC=e=>(void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:i,placement:o,platform:r}=t,{mainAxis:s=!0,crossAxis:a=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...d}=vu(e,t),c={x:n,y:i},u=await r.detectOverflow(t,d),h=Tu(wu(o)),p=ku(h);let g=c[p],f=c[h];s&&(g=Iu(g+u["y"===p?"top":"left"],g,g-u["y"===p?"bottom":"right"])),a&&(f=Iu(f+u["y"===h?"top":"left"],f,f-u["y"===h?"bottom":"right"]));const m=l.fn({...t,[p]:g,[h]:f});return{...m,data:{x:m.x-n,y:m.y-i,enabled:{[p]:s,[h]:a}}}}}),JC=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,i;const{placement:o,middlewareData:r,rects:s,initialPlacement:a,platform:l,elements:d}=t,{mainAxis:c=!0,crossAxis:u=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:f=!0,...m}=vu(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const S=wu(o),y=Tu(a),b=wu(a)===a,x=await(null==l.isRTL?void 0:l.isRTL(d.floating)),I=h||(b||!f?[Au(a)]:(e=>{const t=Au(e);return[Eu(e),t,Eu(t)]})(a)),v="none"!==g;!h&&v&&I.push(...function(e,t,n,i){const o=Pu(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?WC:HC:t?HC:WC;case"left":case"right":return t?_C:KC;default:return[]}})(wu(e),"start"===n,i);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(Eu)))),r}(a,f,g,x));const w=[a,...I],P=await l.detectOverflow(t,m),k=[];let C=(null==(i=r.flip)?void 0:i.overflows)||[];if(c&&k.push(P[S]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const i=Pu(e),o=Mu(e),r=Cu(o);let s="x"===o?i===(n?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[r]>t.floating[r]&&(s=Au(s)),[s,Au(s)]})(o,s,x);k.push(P[e[0]],P[e[1]])}if(C=[...C,{placement:o,overflows:k}],!k.every(e=>e<=0)){var T,M;const e=((null==(T=r.flip)?void 0:T.index)||0)+1,t=w[e];if(t&&("alignment"!==u||y===Tu(t)||C.every(e=>Tu(e.placement)!==y||e.overflows[0]>0)))return{data:{index:e,overflows:C},reset:{placement:t}};let n=null==(M=C.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:M.placement;if(!n)switch(p){case"bestFit":{var E;const e=null==(E=C.filter(e=>{if(v){const t=Tu(e.placement);return t===y||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:E[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),eT=["bottom-start"],tT=["bottom"],nT=["bottom"],iT=[],oT={audio:["src"],embed:["src"],iframe:["src"],img:["src","srcset"],input:["src"],object:["data"],script:["src"],source:["src","srcset"],track:["src"],video:["poster","src"]},rT=["href","xlink:href"],sT=new Set(["a","area"]),aT=16384,lT=67108864,dT=ml("canvas-kit.export"),cT="snapshots",uT="imageBlobs",hT=null,pT=["select","hand","rectangle","ellipse","rhombus","triangle","hexagon","star","arrow","draw","path","text","frame","eraser","laser"],gT=new Set(pT),fT=pT.map(e=>`"${e}"`).join(", "),mT=.08,ST=new WeakMap,yT=new WeakMap,bT=new WeakMap,xT=class extends Iv{constructor(e){super(e,"draw"),this.initial="idle",this.addChild(new IT(e,this)),this.addChild(new vT(e,this))}getDefaultProps(){return this.editor.getDefaultShapeProps("draw")}},IT=class extends Iv{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.clearSelectionTransients()}onPointerDown(e){const t=this.parent.getDefaultProps(),n=((e,t)=>{const n=e.getCurrentPageId();let i=null,o=1/0,r=-1;const s=e.getCurrentPageShapeIds();for(let a=0;a<s.length;a+=1){const n=e.getShape(s[a]);if(!n||e.isShapeHidden(n.id))continue;const l=e.getShapeUtil(n);if(!l.canAutomaticallyReceiveChildren(n))continue;if(!e.canUseShapeParent(n.id))continue;if(!e.isPagePointInShapeClip(n.id,t))continue;const d=l.getChildClipLocalBounds(n)??l.getLocalBounds(n),c=e.computeShapeLocalToPageTransform(n).invert().applyToPoint(t);if(!d.containsPoint(c))continue;const u=e.computeShapePageBounds(n),h=u.w*u.h;(!i||h<o||h===o&&a>r)&&(i=n,o=h,r=a)}return i?.id??n})(this.editor,e.pagePoint),i=n.startsWith("shape:")?this.editor.getShape(n):null,o=i?this.editor.computeShapeLocalToPageTransform(i).invert():yI.Identity(),r=o.applyToPoint(e.pagePoint),s=ug(r,r,e.pressure,"pen"===e.pointerType);var a,l;this.transition("drawing",{originPagePoint:e.pagePoint.clone(),originParentPoint:r,pageToParent:o,parentId:n,shapeId:null,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,isClosed:t.isClosed,isPen:"pen"===e.pointerType,pointGuard:(a=t.strokeWidth,l="pen"===e.pointerType,l?{minPointDistance:Math.max(.12,.08*a),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.3,.14*a),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),pointGuardState:{anchorPoint:hg(s),hasProvisionalPoint:!1},straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[s]}]})}},vT=class extends Iv{tool;info=null;pendingUpdateFrame=null;operation=null;constructor(e,t){super(e,"drawing",t),this.tool=t}onEnter(e){this.info=e,this.editor.clearSelectionTransients(),this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.operation=this.editor.operations.begin({kind:"draw.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(e){this.appendPoint(e,!1)}onPointerUp(e){this.appendPoint(e,!0),this.flushShapeUpdate();const t=this.info?.shapeId??null;if(!t)return this.cancelOperation(),void this.transition("idle");this.info?.parentId.startsWith("shape:")||ke(this.editor,t,{source:"user"}),this.commitOperation(),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.cancelOperation(),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.cancelOperation(),this.info=null}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}appendPoint(e,t){if(!this.info)return;const n=ug(this.info.pageToParent.applyToPoint(e.pagePoint),this.info.originParentPoint,e.pressure,this.info.isPen);if(e.shiftKey?this.appendStraightSegmentPoint(n):(this.exitStraightSegmentMode(),this.info.preserveStraightEndpointOnNextFreePoint?this.appendDistinctCurrentPoint(n)&&(this.info.preserveStraightEndpointOnNextFreePoint=!1):this.appendGuardedCurrentPoint(n,{force:t})),this.splitCurrentSegmentAtLimit(),!this.info.shapeId){const n=this.info.originPagePoint.dist(e.pagePoint);if(!t&&n<2)return;const 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:fg(this.info.segments)}],{source:"user"})}createShape(){const e=this.tool.getDefaultProps(),t=((e,t)=>t&&e.canUseShapeParent(t)?t:e.getCurrentPageId())(this.editor,this.info?.parentId);this.info&&(this.info.parentId=t);const[n]=this.editor.commands.createShapes([{type:"draw",x:this.info?.originParentPoint.x??0,y:this.info?.originParentPoint.y??0,...t.startsWith("shape:")?{parentId:t}:{},props:{...e,stroke:this.info?.stroke??e.stroke,strokeWidth:this.info?.strokeWidth??e.strokeWidth,fill:this.info?.fill??e.fill,isClosed:this.info?.isClosed??e.isClosed,...fg(this.info?.segments??[]),isPen:this.info?.isPen??!1}}],{source:"user"});if(!n||"draw"!==n.type)throw new Error("Failed to create draw shape");return n}appendStraightSegmentPoint(e){if(!this.info)return;this.info.preserveStraightEndpointOnNextFreePoint=!1;const t=pg(this.info),n=t[t.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return this.replaceCurrentSegmentPoints([{...e,segment:"straight"}]),void this.resetPointGuard(e);this.info.straightSegmentAnchorPoint=hg(n)}const i={...e,segment:"straight"};if("straight"===n?.segment)return this.replaceCurrentSegmentPoints([...t.slice(0,-1),i]),void this.resetPointGuard(i);this.replaceCurrentSegmentPoints([...t,i]),this.resetPointGuard(i)}exitStraightSegmentMode(){this.info?.straightSegmentAnchorPoint&&(this.info.straightSegmentAnchorPoint=null,this.info.preserveStraightEndpointOnNextFreePoint=!0)}appendDistinctCurrentPoint(e){if(!this.info)return!1;const t=pg(this.info),n=t[t.length-1];return!(n&&(i=n).x===(o=e).x&&i.y===o.y&&i.pressure===o.pressure&&i.segment===o.segment||(this.replaceCurrentSegmentPoints([...t,hg(e)]),this.resetPointGuard(e),0));var i,o}appendGuardedCurrentPoint(e,t={}){if(!this.info)return;const n=pg(this.info).map(hg);this.info.pointGuardState=function(e,t,n,i,o={}){const r=wp(t),s=e[e.length-1];if(!s)return e.push(r),{anchorPoint:wp(r),hasProvisionalPoint:!1};if(Ip(s,r))return o.force&&i.hasProvisionalPoint?{anchorPoint:wp(r),hasProvisionalPoint:!1}:i;if(Ip(i.anchorPoint,r))return i.hasProvisionalPoint&&e.pop(),{anchorPoint:wp(i.anchorPoint),hasProvisionalPoint:!1};const a=((e,t)=>{if(e<=t.softMaxPointCount)return t.minPointDistance;const n=bp((e-t.softMaxPointCount)/Math.max(t.hardMaxPointCount-t.softMaxPointCount,1),0,1);return t.minPointDistance*(1+n*t.maxDistanceMultiplier)})(e.length,n),l=r.x-i.anchorPoint.x,d=r.y-i.anchorPoint.y,c=Math.abs((r.pressure??0)-(i.anchorPoint.pressure??0)),u=!0===o.force||l*l+d*d>=a*a||c>=n.pressureDeltaThreshold;return i.hasProvisionalPoint?e[e.length-1]=r:e.push(r),u?{anchorPoint:wp(r),hasProvisionalPoint:!1}:{anchorPoint:wp(i.anchorPoint),hasProvisionalPoint:!0}}(n,e,this.info.pointGuard,this.info.pointGuardState,t),this.replaceCurrentSegmentPoints(n)}resetPointGuard(e){this.info&&(this.info.pointGuardState={anchorPoint:hg(e),hasProvisionalPoint:!1})}replaceCurrentSegmentPoints(e){if(!this.info)return;const t=gg(this.info.segments);this.info.segments=[...t.slice(0,-1),{points:e.map(hg)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const e=xp(this.info.isPen);let t=gg(this.info.segments),n=t[t.length-1];for(;n.points.length>e;){const i=n.points.slice(0,e).map(hg),o=i[i.length-1],r=n.points.slice(e).map(hg);if(!o||0===r.length)break;const s={points:[hg(o),...r]};t=[...t.slice(0,-1),{points:i},s],n=s}this.info.segments=t}},wT=[{id:"slate",value:M("stroke-slate"),label:"Slate",hexColor:"#334155"},{id:"blue",value:M("stroke-blue"),label:"Blue",hexColor:"#1d4ed8"},{id:"green",value:M("stroke-green"),label:"Green",hexColor:"#15803d"},{id:"red",value:M("stroke-red"),label:"Red",hexColor:"#dc2626"},{id:"orange",value:M("stroke-orange"),label:"Orange",hexColor:"#ea580c"},{id:"muted",value:M("stroke-muted"),label:"Muted",hexColor:"#94a3b8"}],PT=[{id:"none",value:E("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:M("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:M("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:M("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:M("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],kT=[{value:"open",label:"Open"},{value:"closed",label:"Closed"}],CT={id:"draw",editor:{id:"land.draw",shapeCapabilities:[{type:"draw",schemaProps:["segments","stroke","strokeWidth","fill","isClosed","isPen"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Draw stores raw segments as document truth and derives a shared freehand stroke geometry for render, hit test, brush wrap, and SVG export."]}],shapeUtils:[new class extends xv{type="draw";getDefaultProps(){return{segments:(e=[{x:0,y:0},{x:24,y:12}],[{points:e.map(wp)}]),stroke:M("stroke-slate"),strokeWidth:4,fill:E("transparent"),isClosed:!1,isPen:!1};var e}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{segments:Pg(t.segments,n.segments),stroke:$(t.stroke,n.stroke),strokeWidth:Math.max(4,Ig(t.strokeWidth,n.strokeWidth)),fill:$(t.fill,n.fill),isClosed:"boolean"==typeof t.isClosed?t.isClosed:n.isClosed,isPen:"boolean"==typeof t.isPen?t.isPen:n.isPen}}getPositionedBounds(e){const t=sg(e);return new SI(e.x+t.localBounds.x,e.y+t.localBounds.y,t.localBounds.w,t.localBounds.h)}getLocalBounds(e){return sg(e).localBounds}getRenderBounds(e){return sg(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}canReceiveTerminalBinding(e){return!0}getSelectionResizeLocalBounds(e){return this.getLocalBounds(e)}resizeSelectionBounds(e,t){const n=function(e,t){let n=(({segments:e,strokeWidth:t,isPen:n,isClosed:i,targetSelectionStrokeBounds:o})=>{let r=Lp(e);for(let s=0;s<2;s+=1){const e=ig(r,t,n,i),s=rg(e.pointBounds,e.localBounds,o);r=zp(r,e.pointBounds,s)}return r})({segments:Hp(dg(e),t),strokeWidth:e.props.strokeWidth,isPen:e.props.isPen??!1,isClosed:e.props.isClosed,targetSelectionStrokeBounds:t.targetSelectionStrokeBounds});return t.scaleX<0&&(n=_p(n,{axis:"horizontal",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),t.scaleY<0&&(n=_p(n,{axis:"vertical",selectionMirrorBounds:t.targetSelectionStrokeBounds,selectionRotation:t.selectionRotation,selectionRotationCenter:t.selectionRotationCenter})),ag(Wp(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:cg(n.segments)}}}flipSelectionBounds(e,t){const n=((e,t)=>ag(Wp(_p(Hp(dg(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:cg(n.segments)}}}getSelectionOverlayInfo(e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null}}isWrappedByBrush(e,t){return t.pageOutlineVertices.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){if(this.isWrappedByBrush(e,t))return!0;if(t.isWrapping)return!1;const n=t.pageOutlineVertices;return!!n.some(e=>t.brushBounds.containsPoint(e))||(e=>{const t=new mI(e.minX,e.minY),n=new mI(e.maxX,e.minY),i=new mI(e.maxX,e.maxY),o=new mI(e.minX,e.maxY);return[[t,n],[n,i],[i,o],[o,t]]})(t.brushBounds).some(([e,t])=>{for(let i=0;i<n.length;i+=1){const o=n[i],r=n[(i+1)%n.length];if(o&&r&&I(e,t,o,r))return!0}return!1})}getPositionedOutlineVertices(e){return lg(e).outlineVertices}hitTest(e,t){return function(e,t,n,i={}){if(i.isClosed&&void 0!==i.fill&&!O(i.fill)&&e.normalizedPoints.length>=3&&yg(n,e.normalizedPoints.map(vp)))return!0;if(i.isClosed&&((e,t)=>{if(0===t.length)return Number.POSITIVE_INFINITY;if(1===t.length)return e.dist(vp(t[0]));let n=Number.POSITIVE_INFINITY;for(let i=1;i<t.length;i+=1){const o=t[i-1],r=t[i];o&&r&&(n=Math.min(n,mg(e,vp(o),vp(r))))}return t.length>=3&&(n=Math.min(n,mg(e,vp(t[t.length-1]),vp(t[0])))),n})(n,e.normalizedPoints)<=Math.max(4,.5*t))return!0;if(0===e.outlineVertices.length)return!1;for(const o of e.outlinePolygons){if(yg(n,o))return!0;if(bg(n,o)<=Math.max(4,.5*t))return!0}return!1}(lg(e),e.props.strokeWidth,t,{fill:e.props.fill,isClosed:e.props.isClosed})}hitTestLineSegment(e,t){return((e,t,n,i,o={})=>{const r=Math.max(4,.5*t,o.margin??0);return!!(o.isClosed&&void 0!==o.fill&&!O(o.fill)&&e.normalizedPoints.length>=3&&xg(n,i,e.normalizedPoints.map(vp),r))||0!==e.outlineVertices.length&&e.outlinePolygons.some(e=>xg(n,i,e,r))})(lg(e),e.props.strokeWidth,t.positionedStart,t.positionedEnd,{fill:e.props.fill,isClosed:e.props.isClosed,margin:t.positionedMargin})}repairLoadedShape(e){return null}}],shapeSvgExporters:[new class{type="draw";toSvg(e,t){const n=sg(e);if(!n.path&&!n.selectionPath)return null;const i=[];return n.fillPath&&!O(e.props.fill)&&i.push({tag:"path",attrs:{d:n.fillPath,fill:t.resolveColor(e.props.fill),stroke:"none"}}),e.props.isClosed&&n.selectionPath?i.push({tag:"path",attrs:{d:n.selectionPath,fill:"none",stroke:t.resolveColor(e.props.stroke),"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}):n.path&&i.push({tag:"path",attrs:{d:n.path,fill:t.resolveColor(e.props.stroke),stroke:"none"}}),{tag:"g",children:i}}}],setup(e){e.tools.register("draw",e=>new xT(e),{shortcut:"p"})}},render:{id:"land.draw.react",shapeRenderers:[{type:"draw",component:function({shape:e}){
75
- return Nx(Lg,{shape:e})},hoverComponent:function({shape:e,strokeWidth:t}){
76
- return Nx($g,{shape:e,strokeWidth:t})}}]},setup:e=>{e.get(IP).add({id:"draw.set-closed",getAvailability:e=>"draw"!==e.selection.commonShapeType?"inapplicable":e.selection.count>0?"enabled":"disabled",getValue:e=>Mg(e.selection.selectedShapes),run({context:e,value:t}){const n=Eg(t);if(null===n)return;const i=e.selection.selectedShapes.filter(kg).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{isClosed:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}},Cg("fill"),Cg("stroke"),Cg("strokeWidth"),{id:"draw.default-closed",getAvailability:e=>"draw"===e.tool.activeToolId?"enabled":"inapplicable",getValue:e=>e.editor.getDefaultShapeProps("draw").isClosed?"closed":"open",run({context:e,value:t}){const n=Eg(t);null!==n&&e.editor.updateDefaultShapeProps("draw",{isClosed:n})}},Tg("fill"),Tg("stroke"),Tg("strokeWidth")),e.get(RP).add({id:"draw.tool-toolbar",channel:BP.toolSwitcher,order:45,actionIds:[AP],getGroups:e=>[{id:"draw.tools",items:[{kind:"button",id:"draw.tool.draw",actionId:AP,value:"draw",label:"Draw",shortcut:e.editor.shortcuts.getToolShortcutLabel("draw"),icon:"pencil",dataUi:"draw-tool-button"}]}]},{id:"draw.default-style.tool-toolbar",channel:BP.toolOptions,order:46,actionIds:["draw.default-stroke","draw.default-strokeWidth"],when:e=>"draw"===e.tool.activeToolId,getGroups:()=>(({strokeActionId:e,strokeWidthActionId:t,dataUiPrefix:n})=>[{id:`${n}.initial-style`,items:[{kind:"color-input",id:`${n}.stroke`,actionId:e,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:wT.map(e=>({...e,dataUi:`${n}-stroke-${e.id}-button`})),dataUi:`${n}.stroke`},{kind:"separator",id:`${n}.initial-style-separator`},{kind:"text-input",id:`${n}.stroke-width`,actionId:t,label:"Stroke width",placeholder:"4",suffix:"Px",validate:Rg,dataUi:`${n}-stroke-width-control`}]}])({strokeActionId:"draw.default-stroke",strokeWidthActionId:"draw.default-strokeWidth",dataUiPrefix:"draw-default"})},{id:"draw.selection-toolbar",channel:BP.selectionProperties,order:20,actionIds:["draw.set-closed","draw.set-fill","draw.set-stroke","draw.set-strokeWidth"],when:e=>"draw"===e.selection.commonShapeType,getGroups:()=>(({closedActionId:e,fillActionId:t,strokeActionId:n,strokeWidthActionId:i,dataUiPrefix:o})=>[{id:`${o}.style-closed`,items:[{kind:"segmented",id:`${o}.closed`,actionId:e,options:kT.map(e=>({...e,dataUi:`${o}-${e.value}-button`}))}]},{id:`${o}.style-fill`,items:[{kind:"color-input",id:`${o}.fill`,actionId:t,label:"Fill",fallback:"#f8fafc",presets:PT.map(e=>({...e,dataUi:`${o}-fill-${e.id}-button`})),dataUi:`${o}.fill`}]},{id:`${o}.style-stroke`,items:[{kind:"color-input",id:`${o}.stroke`,actionId:n,label:"Stroke",previewStyle:"outline",fallback:"#334155",presets:wT.map(e=>({...e,dataUi:`${o}-stroke-${e.id}-button`})),dataUi:`${o}.stroke`}]},{id:`${o}.style-stroke-width`,items:[{kind:"text-input",id:`${o}.stroke-width`,actionId:i,label:"Stroke width",placeholder:"4",suffix:"Px",validate:Rg,dataUi:`${o}-stroke-width-control`}]}])({closedActionId:"draw.set-closed",fillActionId:"draw.set-fill",strokeActionId:"draw.set-stroke",strokeWidthActionId:"draw.set-strokeWidth",dataUiPrefix:"draw"})}),e.get(kP).add({id:"draw.shape-context-menu",target:"selection",order:35,actionIds:["draw.set-closed"],when:e=>"draw"===e.selection.commonShapeType,getSections(e){const t="closed"===Mg(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"}]}]}})}},TT=d("plugin.eraser.runtime"),MT=class extends Iv{constructor(e){super(e,"eraser"),this.initial="idle",this.addChild(new ET(e,this)),this.addChild(new AT(e,this)),this.addChild(new BT(e,this))}onExit(){Yg(this.editor)}},ET=class extends Iv{constructor(e,t){super(e,"idle",t)}onEnter(){Yg(this.editor)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={originPagePoint:t.pagePoint.clone(),previousPagePoint:t.pagePoint.clone(),protectedContainerIds:Dg(e,t.pagePoint),erasingShapeIds:new Set,trail:[t.pagePoint.clone()]};return Hg(e,n,t),Kg(e,n),n})(this.editor,e))}},AT=class extends Iv{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&&(Wg(this.editor,this.info,e),_g(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),Kg(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(e){this.info&&(Hg(this.editor,this.info,e),Kg(this.editor,this.info),Xg(this.editor,this.info)),this.transition("idle")}onCancel(){Yg(this.editor),this.transition("idle")}onExit(){this.info=null}},BT=class extends Iv{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&&Xg(this.editor,this.info),this.transition("idle")}onCancel(){Yg(this.editor),this.transition("idle")}onExit(){this.info=null}update(e){this.info&&(Wg(this.editor,this.info,e),_g(this.info,e.pagePoint),this.info.previousPagePoint=e.pagePoint.clone(),Kg(this.editor,this.info))}},RT=Mx(()=>or(Fg(ir()).trailActiveSignal)?Nx(LT,{}):null),LT=Mx(()=>{const e=ir(),t=or(Fg(e).trailSignal),n=or(e.cameraZoomSignal),i=Math.max(n,1e-4),o=(()=>{const[e,t]=Ox(()=>qg());return Bx(()=>{if("undefined"==typeof window)return;let e=0;const n=i=>{t(i),e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(e)}},[]),e})(),r=Ux({samples:[],sourceLength:0}),s=Math.max(o,qg());((e,t,n,i)=>{if(Vg(e,i),t.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),t.length===e.sourceLength)return;const o=e.sourceLength,r=t.length-o,s=e.samples[e.samples.length-1]?.time??i-HT*r;for(let a=o;a<t.length;a++){const l=t[a];jg(e,{x:l.x,y:l.y},n,af(s,i,(a-o+1)/r))}e.sourceLength=t.length,Vg(e,i)})(r.current,t,i,s);const a=function(e,t){const n=Gg(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),i=[e[0]];for(let o=1;o<e.length;o++)i.push(sf(i[i.length-1],e[o],n));return i})(n.length>FT?n.slice(-48):n,DT)}(r.current.samples,s);if(0===a.length)return null;const l=(c=OT/i,0===(d=a).length||c<=0?null:1===d.length?cf(Qg(d[0],c/2,NT))??"":cf((e=>{if(0===e.length)return[];if(1===e.length)return Qg(e[0].point,Math.max(e[0].radius,.01),NT);const t=[],n=[];for(const a of e){const e=tf(a.direction);df(t,of(a.point,rf(e,a.radius))),df(n,nf(a.point,rf(e,a.radius)))}const i=[];for(const a of t)df(i,a);const o=e[e.length-1],r=tf(o.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const o=[];for(let r=1;r<zT;r++){const s=r/zT;o.push(nf(e,nf(rf(t,Math.sin(Math.PI*s)*i),rf(n,-Math.cos(Math.PI*s)*i))))}return o})({center:o.point,direction:o.direction,normal:r,radius:o.radius});for(const a of s)df(i,a);for(let a=n.length-1;a>=0;a--)df(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]+Jg(e[n-1],e[n]));return t})(e),i=Math.max(t,n[n.length-1]??0);return e.map((o,r)=>{const s=n[r]??0,a=lf(s/i,0,1);return{point:o,direction:Zg(e,r),radius:t/2*a,runningLength:s}})})(d,c))));var d,c;return l?Nx("g",{"data-ui":"eraser-trail-overlay",children:Nx("path",{"data-ui":"eraser-trail-scribble",d:l,fill:$T})}):null}),$T="rgba(142, 142, 142, 0.16)",FT=48,UT=1,OT=12,DT=.32,zT=8,NT=13,HT=16,WT=8,_T=180,KT=180,YT=680,XT={id:"eraser",editor:{id:"land.eraser",setup(e){e.runtime.provide(TT,(e=>{const t=a("eraser.shapeIds",[]),n=a("eraser.trail",[]);return{erasingShapeIdsSignal:t,trailSignal:n,trailActiveSignal:l("eraser.trailActive",()=>n.get().length>1),setPreview(i,o){t.set(Array.from(new Set(i))),n.set(o.map(e=>e.clone())),e.runtime.notify()},clear(){t.set([]),n.set([]),e.runtime.notify()}}})(e)),e.tools.register("eraser",e=>new MT(e),{shortcut:"e"})}},render:{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",layer:"below-host",component:RT}],shapeOpacityModifiers:[{id:"land.eraser.preview-opacity",getOpacity(e,t){const n=new Set(Fg(e).erasingShapeIdsSignal.get());return e.hierarchy.isShapeOrAncestorInSet(t,n)?.32:1}}]},setup:e=>{e.get(RP).add({id:"eraser.tool-toolbar",channel:BP.toolSwitcher,order:50,actionIds:[AP],getGroups:e=>[{id:"eraser.tools",items:[{kind:"button",id:"eraser.tool.eraser",actionId:AP,value:"eraser",label:"Eraser",shortcut:e.editor.shortcuts.getToolShortcutLabel("eraser"),icon:"eraser",dataUi:"eraser-tool-button"}]}]})}},qT="group.selection.group",jT="group.selection.ungroup",VT={id:qT,getAvailability:e=>e.editor.canGroupSelection()?"enabled":"inapplicable",run({context:e}){e.editor.groupSelection("user")}},GT={id:jT,getAvailability:e=>e.editor.canUngroupSelection()?"enabled":"inapplicable",run({context:e}){e.editor.ungroupSelection("user")}},ZT={id:"group.selection-toolbar",channel:BP.selectionProperties,order:1010,actionIds:[qT,jT],getGroups:()=>[{id:"group.selection-actions",presentation:"primary",items:[{kind:"button",id:qT,actionId:qT,label:"Group",icon:"group",dataUi:"group-selection-button"},{kind:"button",id:jT,actionId:jT,label:"Ungroup",icon:"ungroup",dataUi:"ungroup-selection-button"}]}]},QT={id:"group.selection-context-menu",target:"selection",order:1020,actionIds:[qT,jT],getSections:()=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"separator",id:"group.selection-separator"},{kind:"command",id:qT,actionId:qT,label:"Group",icon:"group",dataUi:"context-menu-group-selection-button"},{kind:"command",id:jT,actionId:jT,label:"Ungroup",icon:"ungroup",dataUi:"context-menu-ungroup-selection-button"}]}]},JT={id:"group",editor:{id:"land.group",shapeCapabilities:[{type:"group",schemaProps:["w","h"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Group is a transparent structural parent. The plugin supplies concrete record construction, bounds/hit policy, actions, and UI through ShapeUtil hooks; editor core owns generic hierarchy transactions and descendant-aware transforms."]}],shapeUtils:[new class extends xv{type="group";getGroupingShapeCreateInput({parentId:e,parentLocalBounds:t}){return{type:this.type,x:t.x,y:t.y,parentId:e,props:{w:t.w,h:t.h}}}getDefaultProps(){return{w:1,h:1}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:gf(t.w,n.w),h:gf(t.h,n.h)}}getLocalBounds(e){return new SI(0,0,e.props.w,e.props.h)}hitTest(e,t){return!1}hitTestLineSegment(e,t){return!1}isSelectionTransformContainer(e){return!0}canUngroupChildren(e){return!0}shouldResizeDescendants(e){return!0}getResizeToFitDescendantsProps(e,t){return this.validateProps({...e.props,w:t.w,h:t.h})}getMinimumChildCount(e){return 2}contributesToExportBounds(e){return!1}canReceiveChildren(e){return!0}canAutomaticallyReceiveChildren(e){return!1}canBeDirectlyBrushSelected(e){return!1}}],shapeSvgExporters:[new class{type="group";toSvg(e){return{tag:"g"}}}]},render:{id:"land.group.react",shapeRenderers:[{type:"group",component:function({shape:e,isSelected:t}){
77
- return Nx(ff,{shape:e,isSelected:t})},hoverComponent:function({shape:e,strokeWidth:t}){const{h:n,w:i}=e.props;
78
- return Nx("svg",{"data-ui":"group-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${i} ${n}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:Nx("rect",{x:0,y:0,width:i,height:n,fill:"none",stroke:qv,strokeWidth:t,vectorEffect:"non-scaling-stroke"})})}}]},setup:e=>{e.get(IP).add(VT,GT),e.get(IP).addShortcuts({actionId:qT,shortcut:{key:"g",accelKey:!0}},{actionId:jT,shortcut:{key:"g",accelKey:!0,shiftKey:!0}}),e.get(RP).add(ZT),e.get(kP).add(QT)}},eM="image.replace",tM="image.download-original",nM="image.insert",iM="image.crop",oM="image.crop.done",rM="image.crop.zoom",sM="image.crop.aspect-ratio",aM="image.crop.reset",lM="image.corner-radius",dM=1e-4,cM=1e-4,uM="image.crop",hM="image.crop:edit:",pM=[{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}],gM={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"},fM=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],mM=new WeakMap,SM="image.smudge",yM="image.smudge.cancel",bM="image.smudge.confirm",xM="image.smudge.brush-size",IM="image.smudge.brush-color",vM="image.smudge:",wM=`${vM}edit:`,PM="#ffff00",kM=24,CM=PM,TM=.45,MM=class{editor;confirmHandler=null;deactivateHistoryScope=null;session=null;snapshot=null;subscribers=new Set;constructor(e){this.editor=e,Jo("image.smudgeSession.lifecycle",e.shapeEditingSessionSignal,()=>{this.clearIfEditingSessionInvalid()},{fireImmediately:!1})}start(e,t){if(e.isLocked)return!1;const n=Uf(e.id),i=this.editor.getShapeEditingSession();if(i&&(i.shapeId!==e.id||i.markId!==n))return!1;if(this.session&&i?.shapeId===e.id&&Of(e,i.markId))return this.updateSession({...this.session,brush:Df({...this.session.brush,...t})}),!0;this.clear();const o=this.editor.startEditingShape({shapeId:e.id,markId:n,entryMode:"focusEnd"},"user");return!(!o||o.shapeId!==e.id||o.markId!==n||(this.setSession({shapeId:e.id,brush:Df(t),strokes:[],activeStroke:null,redoStrokes:[],nextStrokeIndex:1}),this.activateHistoryScope(e.id),0))}cancel(){const e=this.session?.shapeId??null;this.clear();const t=this.editor.getShapeEditingSession();e&&t?.shapeId===e&&t.markId===Uf(e)&&this.editor.cancelEditing("user")}complete(){const e=this.session?.shapeId??null;this.clear();const t=this.editor.getShapeEditingSession();e&&t?.shapeId===e&&t.markId===Uf(e)&&this.editor.completeEditing("user")}cancelIfActive(){return!!this.getActiveSession()&&(this.cancel(),!0)}clearForShape(e){this.session?.shapeId===e&&this.clear()}updateBrush(e){if(!this.getActiveSession()||!this.session)return!1;const t=Df({...this.session.brush,...e});return t.size===this.session.brush.size&&t.color===this.session.brush.color&&t.opacity===this.session.brush.opacity||this.updateSession({...this.session,brush:t}),!0}getSnapshot(e){const t=this.getActiveSession();return t&&t.shapeId===e?this.snapshot:null}getActiveSession(){if(!this.session)return null;const e=this.editor.getShape(this.session.shapeId),t=this.editor.getShapeEditingSession();return e&&t&&t.shapeId===this.session.shapeId&&t.markId===Uf(this.session.shapeId)?this.snapshot:(this.clear(),null)}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}beginStroke(e){if(!this.session)return;const t=$f(this.session),n={id:`${t.shapeId}:smudge:${t.nextStrokeIndex}`,points:[Yf(e)],brush:{...t.brush}};this.updateSession({...t,activeStroke:n,nextStrokeIndex:t.nextStrokeIndex+1})}appendPoint(e){if(!this.session?.activeStroke)return;const t=this.session.activeStroke.points[this.session.activeStroke.points.length-1];t&&Math.hypot(t.x-e.x,t.y-e.y)<.5||this.updateSession({...this.session,activeStroke:{...this.session.activeStroke,points:[...this.session.activeStroke.points,Yf(e)]}})}endStroke(){this.session?.activeStroke&&this.updateSession($f(this.session))}cancelStroke(){this.session?.activeStroke&&this.updateSession({...this.session,activeStroke:null})}undo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke&&this.updateSession($f(this.session)),!this.session||0===this.session.strokes.length)return!1;const e=this.session.strokes[this.session.strokes.length-1];return!!e&&(this.updateSession({...this.session,strokes:this.session.strokes.slice(0,-1),redoStrokes:[...this.session.redoStrokes,e]}),!0)}redo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke||0===this.session.redoStrokes.length)return!1;const e=this.session.redoStrokes[this.session.redoStrokes.length-1];return!!e&&(this.updateSession({...this.session,strokes:[...this.session.strokes,e],redoStrokes:this.session.redoStrokes.slice(0,-1)}),!0)}registerConfirmHandler(e){return this.confirmHandler=e,()=>{this.confirmHandler===e&&(this.confirmHandler=null)}}requestConfirm(e){return this.confirmHandler?this.confirmHandler(e):Promise.resolve(null)}clear(){this.session&&(this.session=null,this.snapshot=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}clearIfEditingSessionInvalid(){if(!this.session)return;const e=this.editor.getShapeEditingSession();e?.shapeId===this.session.shapeId&&e.markId===Uf(this.session.shapeId)||this.clear()}activateHistoryScope(e){this.deactivateHistoryScope=this.editor.history.activateScope({id:`${vM}history:${e}`,getState:()=>this.getHistoryScopeState(),subscribe:e=>this.subscribe(e),undo:()=>this.undo(),redo:()=>this.redo()})}getHistoryScopeState(){const e=this.session?.activeStroke?1:0,t=this.session?.activeStroke?0:this.session?.redoStrokes.length??0;return{canUndo:(this.session?.strokes.length??0)+e>0,canRedo:t>0,undoDepth:(this.session?.strokes.length??0)+e,redoDepth:t}}setSession(e){this.session=e,this.snapshot=(e=>({shapeId:e.shapeId,brush:e.brush,strokes:e.activeStroke?[...e.strokes,e.activeStroke]:e.strokes,canUndo:e.strokes.length>0||!!e.activeStroke,canRedo:!e.activeStroke&&e.redoStrokes.length>0}))(e),this.notify()}updateSession(e){this.setSession(e)}notify(){for(const e of this.subscribers)e()}},EM=new WeakMap,AM=[{id:"smudge-yellow",label:"Yellow",hexColor:PM},{id:"smudge-orange",label:"Orange",hexColor:"#ff9900"},{id:"smudge-pink",label:"Pink",hexColor:"#ff4fd8"},{id:"smudge-green",label:"Green",hexColor:"#39ff14"},{id:"smudge-blue",label:"Blue",hexColor:"#00c8ff"},{id:"smudge-purple",label:"Purple",hexColor:"#b967ff"}],BM={id:"land.image.crop.dom-events",handle:()=>"continue",getCursor({clientPoint:e,editor:t,element:n,container:i}){const o=(e=>{const[t]=e.getSelectedShapes();if(!qf(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Mf(t,n.markId)?t:null})(t);if(!o)return;if(n?.closest('[data-selection-custom-handle-type="image.crop"]'))return;if(!e)return;const r=i.getBoundingClientRect(),s=new mI(e.x-r.left,e.y-r.top);return Sm(t,o,t.screenToPage(s))?0!==t.inputs.state.get().buttons?"grabbing":"grab":void 0}},RM={id:"land.image.smudge.dom-events",handle:()=>"continue",getCursor({clientPoint:e,container:t,editor:n}){const i=(e=>{const[t]=e.getSelectedShapes();if(!qf(t))return null;const n=e.getShapeEditingSession();return n&&n.shapeId===t.id&&Of(t,n.markId)?t:null})(n);if(!i||!e)return;const o=t.getBoundingClientRect(),r=new mI(e.x-o.left,e.y-o.top);return Sm(n,i,n.screenToPage(r))?"crosshair":0!==n.inputs.state.get().buttons?"grabbing":"grab"}},LM={id:"image",editor:{id:"land.image",shapeCapabilities:[{type:"image",schemaProps:["w","h","assetId","crop","cornerRadius","altText"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Image shape util, SVG exporter, and React renderer live in @land/plugin-image. Asset records store serializable metadata plus a local or remote source; File/Blob/object URL/download behavior stays in the web host."]}],shapeUtils:[new class extends xv{type="image";getDefaultProps(){return{w:240,h:180,assetId:null,crop:null,cornerRadius:0,altText:""}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{w:Math.max(24,rm(t.w,n.w)),h:Math.max(24,rm(t.h,n.h)),assetId:(i=t.assetId,"string"==typeof i&&i.startsWith("asset:")?t.assetId:null),crop:xf(t.crop),cornerRadius:Qf(t.cornerRadius,n.cornerRadius),altText:"string"==typeof t.altText?t.altText:n.altText};var i}getLocalBounds(e){return new SI(0,0,e.props.w,e.props.h)}canReceiveTerminalBinding(e){return!0}getAllowedSelectionResizeModes(e,t){return nv}canEdit(e){return!0}onEditEnd(e,t){var n;n=e.id,Ff(t.editor).clearForShape(n)}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const i=t.editor.getShapeEditingSession();return i&&i.shapeId===e.id&&Mf(e,i.markId)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:Af({crop:e.props.crop,localToPage:t.editor.computeShapeLocalToPageTransform(e),shape:e})}:n}}],shapeSvgExporters:[new class{type="image";toSvg(e,t){const{assetId:n,altText:i,crop:o,h:r,w:s}=e.props;if(!n)return null;const a=t.resolveAssetUrl(n);if(!a)return null;const l=If(o),d=l?{tag:"svg",attrs:{x:0,y:0,width:s,height:r,viewBox:(c=l,[Rf(c.left),Rf(c.top),Rf(c.width),Rf(c.height)].join(" ")),preserveAspectRatio:"none",overflow:"hidden"},children:[{tag:"image",attrs:{href:a,x:0,y:0,width:1,height:1,preserveAspectRatio:"none","aria-label":i||void 0}}]}:{tag:"image",attrs:{href:a,width:s,height:r,preserveAspectRatio:"none","aria-label":i||void 0}};var c;const u=Jf({cornerRadius:e.props.cornerRadius,h:r,w:s});return u<=0?d:{tag:"g",attrs:{"clip-path":`url(#${t.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:0,y:0,width:s,height:r,rx:u,ry:u}}]})})`},children:[d]}}}],interactionHandlers:[function(){let e=null;const t=()=>{e?.operation?.isActive&&e.operation.cancel(),e=null};return{id:"land.image.crop.interactions",editorEvent:{handleEvent(n,i){if("cancel"===i.type)return t(),"continue";if("keyboard"===i.type)return((e,t)=>{if("key_down"!==t.name)return"continue";const n=im(e);if(!n)return"continue";if("Escape"===t.key&&!t.altKey&&!t.accelKey)return e.cancelEditing("user")&&Lf(e,n.id),"handled";if("Enter"===t.key&&!t.altKey&&!t.accelKey)return e.completeEditing("user")&&Lf(e,n.id),"handled";const i=(e=>{if(e.altKey||e.accelKey)return null;const t=e.shiftKey?10:1;switch(e.key){case"ArrowLeft":return new mI(t,0);case"ArrowRight":return new mI(-t,0);case"ArrowUp":return new mI(0,t);case"ArrowDown":return new mI(0,-t);default:return null}})(t);if(i){const t=(({pageDelta:e,shape:t,startCrop:n})=>{const i=xf(n);return!i||e.equals(mI.Zero())?null:Bf({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 t(),"continue";if("pointer_down"===i.name){if(t(),0!==i.button||"select"!==n.getActiveToolId()||!n.isActiveToolInInitialState())return"continue";if(n.hitTestSelectionHandle(i.pagePoint))return"continue";const o=im(n);return o?((e,t,n)=>{const i=e.computeShapeLocalToPageTransform(t).invert().applyToPoint(n.pagePoint);return i.x>=0&&i.y>=0&&i.x<=t.props.w&&i.y<=t.props.h})(n,o,i)?(e={pointerId:i.pointerId,shapeId:o.id,startCrop:o.props.crop,startPagePoint:i.pagePoint.clone(),startPageToLocal:n.computeShapeLocalToPageTransform(o).invert(),startShape:o,hasDragged:!1,operation:null},"handled"):n.completeEditing("user")?(Lf(n,o.id),n.dispatch(i),"handled"):"continue":"continue"}return e&&i.pointerId===e.pointerId?"pointer_move"===i.name?(om(n,i,e),"handled"):"pointer_up"===i.name?(om(n,i,e),e.operation?.isActive&&e.operation.commit(),t(),"handled"):"continue":"continue"}},selectionHandle:nm()}}(),function(){let e=null;const t=t=>{e=null,(e=>{Ff(e).endStroke()})(t)},n=t=>{e=null,(e=>{Ff(e).cancelStroke()})(t)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(i,o){if("keyboard"===o.type)return(am(o)||sm(o))&&lm(i)&&t(i),((e,t)=>"key_down"!==t.name?"continue":lm(e)?"Escape"!==t.key||t.altKey||t.accelKey?sm(t)?(Kf(e,{replace:!0}),"handled"):am(t)?(t.shiftKey?e.redo():e.undo(),"handled"):"handled":(Nf(e),"handled"):"continue")(i,o);if("cancel"===o.type)return lm(i)?(n(i),Nf(i),"handled"):"continue";if("pointer"!==o.type)return"continue";const r=lm(i);if(!r)return n(i),"continue";if("pointer_down"===o.name){if(t(i),0!==o.button)return 1===o.button?"continue":"handled";const n=cm(i,r,o.pagePoint),s=um(n,r);return e={mode:s?"draw":"pan",originCamera:s?null:i.getCurrentCamera(),originScreenPoint:s?null:o.screenPoint.clone(),pointerId:o.pointerId,acceptsDrawPoints:s},s&&((e,t)=>{Ff(e).beginStroke(t)})(i,{x:n.x,y:n.y,pressure:o.pressure}),"handled"}return e&&e.pointerId===o.pointerId?"pointer_move"===o.name?("draw"===e.mode&&1&o.buttons?e.acceptsDrawPoints&&(e.acceptsDrawPoints=dm(i,r,o)):"pan"===e.mode&&e.originCamera&&e.originScreenPoint&&1&o.buttons?hm(i,o,e):t(i),"handled"):"pointer_up"===o.name?("draw"===e.mode&&e.acceptsDrawPoints?dm(i,r,o):"pan"===e.mode&&hm(i,o,e),t(i),"handled"):"pointer_cancel"===o.name?(n(i),"handled"):"handled":"handled"}}}}()],setup:e=>(e=>{let t=null;return Jo("image.cropSession.lifecycle",e.shapeEditingSessionSignal,()=>{const n=e.getShapeEditingSession(),i=n?.shapeId,o=i&&n?.markId===Ef(i)?i:null;t&&t!==o&&Lf(e,t),t=o})})(e)},render:{id:"land.image.react",domEventGuards:[BM,RM],selectionCustomHandleRenderers:[{type:uM,component:function({handle:e,strokeWidth:t}){const{x:n,y:i,w:o,h:r,center:s}=e.bounds,a=1.35*Math.max(o,r),l=Math.max(2.5*t,2),d={fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeLinecap:"butt",strokeLinejoin:"miter",strokeWidth:l,pointerEvents:"none"},c=(({id:e,extension:t,outwardOffset:n,centerX:i,centerY:o})=>{switch(e){case"top_left":return{kind:"corner",points:[fm(i-n,o+t),fm(i-n,o-n),fm(i+t,o-n)].join(" ")};case"top":return{kind:"edge",x1:i-t,y1:o-n,x2:i+t,y2:o-n};case"top_right":return{kind:"corner",points:[fm(i-t,o-n),fm(i+n,o-n),fm(i+n,o+t)].join(" ")};case"right":return{kind:"edge",x1:i+n,y1:o-t,x2:i+n,y2:o+t};case"bottom_right":return{kind:"corner",points:[fm(i+n,o-t),fm(i+n,o+n),fm(i-t,o+n)].join(" ")};case"bottom":return{kind:"edge",x1:i-t,y1:o+n,x2:i+t,y2:o+n};case"bottom_left":return{kind:"corner",points:[fm(i+t,o+n),fm(i-n,o+n),fm(i-n,o-t)].join(" ")};case"left":return{kind:"edge",x1:i-n,y1:o-t,x2:i-n,y2:o+t};default:return{kind:"edge",x1:i,y1:o,x2:i,y2:o}}})({id:e.id,extension:a,outwardOffset:l/2,centerX:s.x,centerY:s.y});
79
- return Hx("g",{children:[Nx("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:n-.8*o,y:i-.8*r,width:2.6*o,height:2.6*r,fill:"transparent",style:{cursor:e.cursor??"grab",pointerEvents:"auto"}}),"corner"===c.kind?Nx("polyline",{points:c.points,...d}):Nx("line",{x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,...d})]})}}],shapeRenderers:[{type:"image",component:function({editor:e,shape:t,shapeEditingSession:n}){const{altText:i,assetId:o,crop:r,h:s,w:a}=t.props,l=o?e.resolveAssetUrl(o):null,d=Jf({cornerRadius:t.props.cornerRadius,h:s,w:a}),c=((e,t)=>Dx(t=>((e,t)=>Ff(e).subscribe(t))(e,t),()=>((e,t)=>Ff(e).getSnapshot(t))(e,t),()=>null))(e,t.id);if(!l)return Nx("div",{"data-ui":"image-shape-missing-asset",style:{alignItems:"center",background:"#f1f5f9",border:"1px solid #cbd5e1",borderRadius:d,boxSizing:"border-box",color:"#64748b",display:"flex",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:12,height:s,justifyContent:"center",overflow:"hidden",width:a},children:"Missing image"});const u=(({crop:e,shapeHeight:t,shapeWidth:n})=>{const i=If(e);if(!i)return null;const o=n/i.width,r=t/i.height;return{imageX:-i.left*o,imageY:-i.top*r,imageWidth:o,imageHeight:r,rect:i}})({crop:r,shapeHeight:s,shapeWidth:a});if(u){const e=n?.shapeId===t.id&&Mf(t,n.markId),o={display:"block",height:u.imageHeight,left:u.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:u.imageY,userSelect:"none",width:u.imageWidth};
80
- return Hx("div",{"data-ui":"image-shape",style:{display:"block",height:s,overflow:e?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[e?Nx("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:l,style:{...o,opacity:.1}}):null,Hx("div",{"data-ui":"image-crop-window",style:{height:s,overflow:"hidden",position:"absolute",borderRadius:d,inset:0,width:a},children:[Nx("img",{alt:i,draggable:!1,src:l,style:o}),Nx(pm,{shape:t,session:c})]})]})}
81
- return Hx("div",{"data-ui":"image-shape",style:{borderRadius:d,display:"block",height:s,overflow:"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[Nx("img",{alt:i,draggable:!1,src:l,style:{display:"block",height:s,objectFit:"fill",width:a}}),Nx(pm,{shape:t,session:c})]})},hoverComponent:function({shape:e,strokeWidth:t}){
82
- return Nx("div",{"data-ui":"image-hover-outline",style:{borderRadius:Jf({cornerRadius:e.props.cornerRadius,h:e.props.h,w:e.props.w}),boxShadow:`inset 0 0 0 ${t}px ${qv}`,inset:0,position:"absolute"}})}}]},setup:e=>{e.get(IP).add(...Zf(),{id:SM,getAvailability(e){const t=jf(e);return!t||Vf(e)||Gf(e)?"inapplicable":!t.isLocked&&t.props.assetId?"enabled":"disabled"},getValue:e=>Gf(e),run({context:e}){const t=jf(e);t&&!t.isLocked&&t.props.assetId&&zf({editor:e.editor,shape:t})}},{id:xM,getAvailability:e=>Gf(e)?"enabled":"inapplicable",getValue:e=>_f(e.editor)?.brush.size??24,run({context:e,value:t}){Wf(e.editor,{size:t})}},{id:IM,getAvailability:e=>Gf(e)?"enabled":"inapplicable",getValue(e){const t=_f(e.editor)?.brush;return{color:t?.color??"#ffff00",opacity:t?.opacity??.45}},run({context:e,value:t}){Wf(e.editor,{color:t.color,opacity:t.opacity})}},{id:yM,getAvailability:e=>Gf(e)?"enabled":"inapplicable",run({context:e}){Nf(e.editor)}},{id:bM,getAvailability:e=>Gf(e)?"enabled":"inapplicable",run({context:e}){Kf(e.editor,{replace:!0})}},{id:lM,getAvailability:e=>"image"!==e.selection.commonShapeType?"inapplicable":e.selection.selectedShapes.some(e=>qf(e)&&!e.isLocked)?"enabled":"disabled",getValue:e=>(e=>{let t;for(const n of e){if(!qf(n))continue;const e=Qf(n.props.cornerRadius);if(void 0!==t){if(t!==e)return null}else t=e}return void 0===t?null:(e=>Number(e.toFixed(2)).toString())(t)})(e.selection.selectedShapes),run({context:e,value:t}){const n=(e=>{if("string"!=typeof e)return null;const t=e.trim();if(0===t.length)return null;const n=Number(t);return Number.isFinite(n)?Qf(n):null})(t);if(null===n)return;const i=e.selection.selectedShapes.filter(qf).filter(e=>!e.isLocked).map(e=>({id:e.id,props:{cornerRadius:n}}));0!==i.length&&e.editor.commands.updateShapes(i,{source:"user"})}}),e.get(RP).add({id:"image.tool-toolbar",channel:BP.toolSwitcher,order:55,actionIds:[nM],getGroups:()=>[{id:"image.tools",items:[{kind:"button",id:nM,actionId:nM,label:"Image",icon:"image-plus",dataUi:"insert-image-tool-button"}]}]},{id:"image.selection-toolbar",channel:BP.selectionProperties,order:30,actionIds:[iM,oM,rM,sM,aM,SM,IM,xM,yM,bM,lM,eM,tM],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups(e){const t=[];return Gf(e)?[{id:"image.smudge-color",order:5,items:[{kind:"color-input",id:IM,actionId:IM,label:"Brush color",fallback:PM,opacityMode:"separate",opacityFallback:.45,presets:AM,dataUi:"image-smudge-brush-color-input"}]},{id:"image.smudge-brush",order:10,items:[{kind:"slider",id:xM,actionId:xM,label:"Brush size",min:1,max:128,step:1,dataUi:"image-smudge-brush-size-slider"}]},{id:"image.smudge-actions",order:20,items:[{kind:"button",id:yM,actionId:yM,label:"Cancel smudge",icon:"x",dataUi:"cancel-image-smudge-button"},{kind:"button",id:bM,actionId:bM,label:"Confirm smudge",icon:"check",dataUi:"confirm-image-smudge-button"}]}]:(Vf(e)&&t.push({id:"image.crop-zoom",order:10,items:[{kind:"stepper",id:"image.crop.zoom-stepper",actionId:rM,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:sM,options:pM.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:aM,actionId:aM,label:"Reset crop",icon:"rotate-ccw",dataUi:"reset-image-crop-button"}]}),t.push((({dataUiPrefix:e,id:t,order:n})=>({id:t,order:n,items:[em({dataUiPrefix:e})]}))({dataUiPrefix:"image",id:"image.style-corner-radius",order:35})),t.push({id:"image.asset",order:40,items:[{kind:"button",id:iM,actionId:iM,label:"Crop image",icon:"crop",dataUi:"crop-image-button"},{kind:"button",id:SM,actionId:SM,label:"Smudge image",icon:"pencil",dataUi:"smudge-image-button"},{kind:"button",id:oM,actionId:oM,label:"Done cropping",icon:"check",dataUi:"done-cropping-button"},{kind:"button",id:eM,actionId:eM,label:"Replace image",icon:"image-plus",dataUi:"replace-image-button"},{kind:"button",id:tM,actionId:tM,label:"Download original",icon:"download",dataUi:"download-image-original-button"}]}),t)}},{id:"image.floating-selection-toolbar",channel:BP.selectionQuickActions,order:30,actionIds:[iM,oM,rM,sM,aM,SM,IM,xM,yM,bM,lM,eM,tM],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getGroups:e=>Gf(e)?[{id:"image.floating-smudge-color",order:5,items:[{kind:"color-input",id:"image.floating-smudge.brush-color",actionId:IM,label:"Brush color",fallback:PM,opacityMode:"separate",opacityFallback:.45,presets:AM,dataUi:"floating-image-smudge-brush-color-input"}]},{id:"image.floating-smudge-brush",order:10,items:[{kind:"slider",id:"image.floating-smudge.brush-size",actionId:xM,label:"Brush size",min:1,max:128,step:1,dataUi:"floating-image-smudge-brush-size-slider"}]},{id:"image.floating-smudge-actions",order:20,items:[{kind:"button",id:"image.floating-smudge.cancel",actionId:yM,label:"Cancel smudge",icon:"x",dataUi:"floating-cancel-image-smudge-button"},{kind:"button",id:"image.floating-smudge.confirm",actionId:bM,label:"Confirm smudge",icon:"check",dataUi:"floating-confirm-image-smudge-button"}]}]:Vf(e)?[{id:"image.floating-crop-zoom",order:10,items:[{kind:"stepper",id:"image.floating-crop.zoom-stepper",actionId:rM,label:"Zoom",options:[{value:-1,label:"-",dataUi:"floating-image-crop-zoom-out-button"},{value:1,label:"+",dataUi:"floating-image-crop-zoom-in-button"}]}]},{id:"image.floating-crop-aspect",order:20,items:[{kind:"segmented",id:"image.floating-crop.aspect-ratio-segmented",actionId:sM,options:pM.map(e=>({value:e.value,label:e.label,dataUi:`floating-image-crop-aspect-${e.value.replace(":","-")}-button`}))}]},{id:"image.floating-crop-corner-radius",order:35,items:[em({dataUiPrefix:"floating-image-crop"})]},{id:"image.floating-crop-actions",order:30,items:[{kind:"button",id:"image.floating-crop.done",actionId:oM,label:"Done cropping",icon:"check",dataUi:"floating-done-cropping-button"},{kind:"button",id:"image.floating-crop.reset",actionId:aM,label:"Reset crop",icon:"rotate-ccw",dataUi:"floating-reset-image-crop-button"}]}]:[{id:"image.floating-corner-radius",order:10,items:[em({dataUiPrefix:"floating-image"})]},{id:"image.floating-primary-actions",order:20,items:[{kind:"button",id:"image.floating.crop",actionId:iM,label:"Crop image",icon:"crop",dataUi:"floating-crop-image-button"},{kind:"button",id:"image.floating.replace",actionId:eM,label:"Replace image",icon:"image-plus",dataUi:"floating-replace-image-button"}]},{id:"image.floating-more-actions",order:30,presentation:"overflow",items:[{kind:"button",id:"image.floating.smudge",actionId:SM,label:"Smudge image",icon:"pencil",dataUi:"floating-smudge-image-button"},{kind:"button",id:"image.floating.download",actionId:tM,label:"Download original",icon:"download",dataUi:"floating-download-image-original-button"}]}]}),e.get(kP).add({id:"image.shape-context-menu",target:"selection",order:30,actionIds:[iM,SM,eM,tM],when:e=>1===e.selection.count&&"image"===e.selection.singleShapeType,getSections:()=>[{id:"image.asset-context-menu",title:"Image",items:[{kind:"command",id:iM,actionId:iM,label:"Crop image",icon:"crop",dataUi:"context-menu-crop-image-button"},{kind:"command",id:SM,actionId:SM,label:"Smudge image",icon:"pencil",dataUi:"context-menu-smudge-image-button"},{kind:"command",id:eM,actionId:eM,label:"Replace image",icon:"image-plus",dataUi:"context-menu-replace-image-button"},{kind:"command",id:tM,actionId:tM,label:"Download original",icon:"download",dataUi:"context-menu-download-image-original-button"}]}]})}},$M=d("plugin.laser.runtime"),FM=class extends Iv{constructor(e){super(e,"laser"),this.initial="idle",this.addChild(new UM(e,this)),this.addChild(new OM(e,this)),this.addChild(new DM(e,this))}},UM=class extends Iv{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("pointing",((e,t)=>{const n={sessionId:ym(e).start(),originPagePoint:t.pagePoint.clone(),trail:[t.pagePoint.clone()]};return xm(e,n),n})(this.editor,e))}},OM=class extends Iv{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&&(bm(this.info,e.pagePoint),xm(this.editor,this.info),this.transition("drawing",this.info))}onPointerUp(){this.info&&ym(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&ym(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&ym(this.editor).finish(this.info.sessionId),this.info=null}},DM=class extends Iv{info=null;constructor(e,t){super(e,"drawing",t)}onEnter(e){this.info=e}onPointerMove(e){this.info&&(bm(this.info,e.pagePoint),xm(this.editor,this.info))}onPointerUp(){this.info&&ym(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&ym(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&ym(this.editor).finish(this.info.sessionId),this.info=null}},zM=Mx(()=>or(ym(ir()).activeSignal)?Nx(NM,{}):null),NM=Mx(()=>{const e=ir(),t=ym(e),n=or(t.trailSignal),i=or(e.cameraZoomSignal),o=Math.max(i,1e-4),r=(()=>{const[e,t]=Ox(()=>Im());return Bx(()=>{if("undefined"==typeof window)return;let e=0;const n=i=>{t(i),e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(e)}},[]),e})(),s=Ux({sessionId:0,samples:[],sourceLength:0}),a=Math.max(r,Im());let l,d=[];n&&(((e,t,n,i)=>{t.sessionId!==e.sessionId&&(e.sessionId=t.sessionId,e.samples=[],e.sourceLength=0);const o=t.points;if(wm(e,i),o.length<e.sourceLength&&(e.samples=[],e.sourceLength=0),o.length===e.sourceLength)return;const r=e.sourceLength,s=o.length-r,a=e.samples[e.samples.length-1]?.time??i-GM*s;for(let l=r;l<o.length;l++){const t=o[l];vm(e,{x:t.x,y:t.y},n,$m(a,i,(l-r+1)/s))}e.sourceLength=o.length,wm(e,i)})(s.current,n,o,a),d=function(e,t){const n=Pm(e,t);return((e,t)=>{if(e.length<=1)return[...e];const n=.15+.85*(1-t),i=[e[0]];for(let o=1;o<e.length;o++)i.push(Lm(i[i.length-1],e[o],n));return i})(n.length>KM?n.slice(-64):n,qM)}(s.current.samples,a),l=s.current.samples[s.current.samples.length-1]?.time);const c="ending"===n?.phase,u=0===d.length,h=c&&u?n.sessionId:null;if(Bx(()=>{null!==h&&t.clear(h)},[h,t]),!n||u)return null;const p=c&&void 0!==l?Fm(1-(a-l)/tE,0,1):1,g=(m=XM/o,0===(f=d).length||m<=0?null:1===f.length?Om(Cm(f[0],m/2,VM))??"":Om((e=>{if(0===e.length)return[];if(1===e.length)return Cm(e[0].point,Math.max(e[0].radius,.01),VM);const t=[],n=[];for(const a of e){const e=Em(a.direction);Um(t,Bm(a.point,Rm(e,a.radius))),Um(n,Am(a.point,Rm(e,a.radius)))}const i=[];for(const a of t)Um(i,a);const o=e[e.length-1],r=Em(o.direction),s=(({center:e,direction:t,normal:n,radius:i})=>{if(i<=0)return[];const o=[];for(let r=1;r<jM;r++){const s=r/jM;o.push(Am(e,Am(Rm(t,Math.sin(Math.PI*s)*i),Rm(n,-Math.cos(Math.PI*s)*i))))}return o})({center:o.point,direction:o.direction,normal:r,radius:o.radius});for(const a of s)Um(i,a);for(let a=n.length-1;a>=0;a--)Um(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]+Tm(e[n-1],e[n]));return t})(e),i=Math.max(t,n[n.length-1]??0);return e.map((o,r)=>{const s=n[r]??0,a=Fm(s/i,0,1);return{point:o,direction:km(e,r),radius:t/2*a,runningLength:s}})})(f,m))));var f,m;return g?Hx("g",{"data-ui":"laser-trail-overlay",style:{opacity:p},children:[Nx("path",{"data-ui":"laser-trail-glow",d:g,fill:WM,style:{filter:`blur(${_M/o}px)`}}),Nx("path",{"data-ui":"laser-trail-beam",d:g,fill:HM})]}):null}),HM="rgb(255, 38, 38)",WM="rgba(255, 48, 48, 0.55)",_M=4,KM=64,YM=1,XM=12,qM=.32,jM=8,VM=13,GM=16,ZM=8,QM=600,JM=300,eE=1400,tE=400,nE={id:"laser",editor:{id:"land.laser",setup(e){e.runtime.provide($M,(()=>{const e=a("laser.trail",null);let t=1;return{trailSignal:e,activeSignal:l("laser.active",()=>null!==e.get()),start(){const n=t++;return e.set({sessionId:n,phase:"active",points:[]}),n},set(t,n){const i=e.get();i&&i.sessionId===t&&e.set({sessionId:t,phase:"active",points:n.map(e=>e.clone())})},finish(t){const n=e.get();n&&n.sessionId===t&&e.set({...n,phase:"ending"})},clear(t){e.get()?.sessionId===t&&e.set(null)}}})()),e.tools.register("laser",e=>new FM(e),{shortcut:"l"})}},render:{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",layer:"below-host",component:zM}]},setup:e=>{e.get(RP).add({id:"laser.tool-toolbar",channel:BP.toolSwitcher,order:55,actionIds:[AP],getGroups:e=>[{id:"laser.tools",items:[{kind:"button",id:"laser.tool.laser",actionId:AP,value:"laser",label:"Laser",shortcut:e.editor.shortcuts.getToolShortcutLabel("laser"),icon:"wand",dataUi:"laser-tool-button"}]}]})}},iE="path.node",oE="path.control",rE=new WeakMap,sE=["nonzero","evenodd"],aE=["corner","smooth","symmetric"],lE=1e-6,dE=1/3,cE=Math.PI/8,uE=new WeakMap,hE=new WeakMap,pE="land.path.draftSubpathId",gE="land.path.previewNodeId",fE="var(--land-selection, #2563eb)",mE="rgba(255, 255, 255, 0.98)",SE=class{editor;deactivateHistoryScope=null;session=null;subscribers=new Set;constructor(e){this.editor=e}start(e,t,n){const i=this.editor.getShape(t);if(!Ym(i))return!1;if(this.session?.mode===e&&this.session.shapeId===t)return!0;this.clear();const o=[ay(this.editor,i,e)];return this.session={mode:e,shapeId:t,snapshots:o,index:o.length-1,initialShapeSignature:ly(i),onApply:n?.onApply,onBoundaryUndo:n?.onBoundaryUndo},this.deactivateHistoryScope=this.editor.history.activateScope({id:`path.${e}.temporary:${t}`,getState:()=>this.getState(),subscribe:e=>this.subscribe(e),undo:()=>this.undo(),redo:()=>this.redo()}),this.notify(),!0}record(e){const t=this.session,n=this.editor.getShape(e);if(!t||t.shapeId!==e||!Ym(n))return!1;const i=ay(this.editor,n,t.mode);return t.snapshots[t.index]?.signature===i.signature?(t.snapshots[t.index]=i,!1):(t.snapshots=[...t.snapshots.slice(0,t.index+1),i],t.index=t.snapshots.length-1,this.notify(),!0)}replaceCurrent(e){const t=this.session,n=this.editor.getShape(e);if(!t||t.shapeId!==e||!Ym(n))return!1;const i=ay(this.editor,n,t.mode),o=t.snapshots[t.index];return t.snapshots[t.index]=i,o?.signature!==i.signature&&(this.notify(),!0)}end(e,t){return this.session?.mode===e&&this.session.shapeId===t&&(this.clear(),!0)}hasNetChanges(e,t){const n=this.session,i=this.editor.getShape(t);return!(!n||n.mode!==e||n.shapeId!==t||Ym(i)&&n.initialShapeSignature===ly(i))}undo(){const e=this.session;return!!e&&(e.index<=0?e.onBoundaryUndo?.()??!1:this.applySnapshot(e.index-1))}redo(){const e=this.session;return!(!e||e.index>=e.snapshots.length-1)&&this.applySnapshot(e.index+1)}applySnapshot(e){const t=this.session,n=t?.snapshots[e];if(!t||!n)return!1;const i=this.editor.getShape(t.shapeId);if(!Ym(i))return this.clear(),!1;t.index=e;const o=HS(this.editor);this.editor.commands.updateShapes([{id:t.shapeId,..."create"===t.mode&&n.draftMeta?{meta:ZS(i.meta,n.draftMeta)}:{},props:{subpaths:tS(n.subpaths)}}],{source:"user"});const r=this.editor.getShape(t.shapeId);Ym(r)&&t.onApply?.(r);const s=n.selection??o;return s&&Ym(r)&&this.editor.getShapeEditingSession()?.shapeId===t.shapeId?YS(this.editor,r,s.nodes,s.primary):_S(this.editor),this.notify(),!0}getState(){const e=this.session?.index??0,t=(this.session?.snapshots.length??1)-1,n=this.session?.onBoundaryUndo?1:0;return{canUndo:e+n>0,canRedo:e<t,undoDepth:e+n,redoDepth:Math.max(0,t-e)}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}clear(){(this.session||this.deactivateHistoryScope)&&(this.session=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}notify(){for(const e of this.subscribers)e()}},yE=new WeakMap,bE=new WeakMap,xE="path.edit",IE=Math.PI/4,vE=1,wE=new WeakMap,PE=new WeakMap,kE=Math.PI/4,CE=1,TE=1,ME=class extends Iv{draft=null;operation=null;constructor(e){super(e,"path"),this.initial="idle",this.addChild(new EE(e,this)),this.addChild(new AE(e,this))}onEnter(){this.editor.clearSelectionTransients()}onExit(){this.draft&&(this.canFinishDraft()?this.finishDraft({switchToSelect:!1}):this.cancelDraft())}isInInitialState(){return!this.hasDraft()&&super.isInInitialState()}startOrExtend(e,t){if(!this.draft){this.operation=this.editor.operations.begin({kind:"path.create",label:"shape.create",source:"user",history:"record"});const t=this.editor.getDefaultShapeProps("path"),n=`subpath:${TE+=1}`,i=Ny(),o={id:i,x:0,y:0,kind:"corner"},[r]=this.editor.commands.createShapes([{type:"path",x:e.x,y:e.y,meta:ZS({},{subpathId:n,previewNodeId:null}),props:{...t,subpaths:[{id:n,closed:!1,nodes:[o]}]}}],{source:"user",autoReparent:!1});if(!Ym(r))throw this.cancelOperation(),new Error("Failed to create path shape");return this.editor.commands.setSelectedShapeIds([r.id],{source:"system"}),this.draft={shapeId:r.id,subpathId:n,lastNodeId:i,createdShape:!0,previewNodeId:null},cy(this.editor,"create",r.id,{onBoundaryUndo:()=>this.draft?.shapeId===r.id&&(this.cancelDraft(),this.editor.commands.setActiveTool("select",{source:"system"}),!0),onApply:e=>{const t=this.draft;if(!t||t.shapeId!==e.id)return;const n=IS(e.props.subpaths,t.subpathId);this.draft={...t,lastNodeId:n?.nodes.at(-1)?.id??t.lastNodeId,previewNodeId:null}}}),{shapeId:r.id,subpathId:n,nodeId:i,originPagePoint:e.clone(),startNode:Jm(o),finishOnPointerUp:!1}}const n=this.editor.getShape(this.draft.shapeId);if(!Ym(n))return this.cancelDraft(),null;const i=t.shiftKey?Wy(this.editor,n,this.draft.subpathId,this.draft.previewNodeId)??e:e,o=t.shiftKey?_y(i,e):e;if(function(e,t,n,i,o){const r=((e,t,n)=>{const i=IS(t.props.subpaths,n)?.nodes[0];return i?e.computeShapeLocalToPageTransform(t).applyToPoint(new mI(i.x,i.y)):null})(e,t,n),s=IS(t.props.subpaths,n),a=s?.nodes.filter(e=>e.id!==i).length??0;return!(!r||!s||a<3)&&r.dist(o)<=10/e.getCurrentCamera().z}(this.editor,n,this.draft.subpathId,this.draft.previewNodeId,e)){const t=this.draft,i=IS(n.props.subpaths,t.subpathId)?.nodes.find(e=>e.id!==t.previewNodeId);return i?(this.editor.commands.updateShapes([{id:n.id,meta:ZS(n.meta,{subpathId:t.subpathId,previewNodeId:null}),props:{subpaths:Ky(n.props.subpaths,t).map(e=>e.id===t.subpathId?{...e,closed:!0}:e)}}],{source:"user"}),this.draft={...t,previewNodeId:null},{shapeId:n.id,subpathId:t.subpathId,nodeId:i.id,originPagePoint:e.clone(),startNode:Jm(i),finishOnPointerUp:!0}):null}const r=Hy(this.editor,n,o),s=this.draft.previewNodeId??Ny(),a=n.props.subpaths.map(e=>e.id===this.draft?.subpathId?this.draft.previewNodeId?{...e,nodes:e.nodes.map(e=>e.id===this.draft?.previewNodeId?{id:s,x:r.x,y:r.y,kind:"corner"}:e)}:{...e,nodes:[...e.nodes,{id:s,x:r.x,y:r.y,kind:"corner"}]}:e);return this.editor.commands.updateShapes([{id:n.id,meta:ZS(n.meta,{subpathId:this.draft.subpathId,previewNodeId:null}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,lastNodeId:s,previewNodeId:null},{shapeId:n.id,subpathId:this.draft.subpathId,nodeId:s,originPagePoint:e.clone(),startNode:{id:s,x:r.x,y:r.y,kind:"corner"},finishOnPointerUp:!1}}updateNodeDrag(e,t,n){const i=this.editor.getShape(e.shapeId);if(!Ym(i))return;const o=n.shiftKey?_y(e.originPagePoint,t):t,r=Hy(this.editor,i,e.originPagePoint),s=Hy(this.editor,i,o),a=e.originPagePoint.dist(o)*this.editor.getCurrentCamera().z>=3,l=wS(i.props.subpaths,e.subpathId,e.nodeId,()=>a?((e,t,n)=>({...e,kind:n.altKey?"smooth":"symmetric",in:{dx:-t.x,dy:-t.y},out:{dx:t.x,dy:t.y}}))(e.startNode,s.sub(r),n):Jm(e.startNode));this.editor.commands.updateShapes([{id:i.id,meta:ZS(i.meta,{subpathId:e.subpathId,previewNodeId:this.draft?.previewNodeId??null}),props:{subpaths:l}}],{source:"user"})}updatePreview(e,t){if(!this.draft)return;const n=this.editor.getShape(this.draft.shapeId);if(!Ym(n)||Yy(n,this.draft)<1)return;const i=t.shiftKey?Wy(this.editor,n,this.draft.subpathId,this.draft.previewNodeId):null,o=i?_y(i,e):e,r=Hy(this.editor,n,o),s=this.draft.previewNodeId??Ny(),a=n.props.subpaths.map(e=>e.id!==this.draft?.subpathId?e:this.draft.previewNodeId?{...e,nodes:e.nodes.map(e=>e.id===this.draft?.previewNodeId?{id:s,x:r.x,y:r.y,kind:"corner"}:e)}:{...e,nodes:[...e.nodes,{id:s,x:r.x,y:r.y,kind:"corner"}]});this.editor.commands.updateShapes([{id:n.id,meta:ZS(n.meta,{subpathId:this.draft.subpathId,previewNodeId:s}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,previewNodeId:s}}canFinishDraft(){if(!this.draft)return!1;const e=this.editor.getShape(this.draft.shapeId);return!!Ym(e)&&Yy(e,this.draft)>=2}finishDraft(e={}){if(!this.draft)return;const t=e.switchToSelect??!0,n=this.editor.getShape(this.draft.shapeId);if(Ym(n)){const e=Ky(n.props.subpaths,this.draft),t=fS(mS({...n,props:{...n.props,subpaths:e}},this.editor.computeShapeLocalToPageTransform(n)),n.props);this.editor.commands.updateShapes([{id:n.id,x:t.x,y:t.y,rotation:0,scaleX:1,scaleY:1,meta:QS(n.meta),props:{subpaths:t.subpaths}}],{source:"user"}),this.draft.createdShape&&ke(this.editor,n.id,{source:"user"})}hy(this.editor,"create",this.draft.shapeId),this.commitOperation(),this.draft=null,t&&!this.editor.isToolLocked()&&this.editor.commands.setActiveTool("select",{source:"system"})}finishDraftAndEdit(){const e=this.draft?.shapeId;if(e){if(!this.canFinishDraft())return this.cancelDraft(),void(this.editor.isToolLocked()||this.editor.commands.setActiveTool("select",{source:"system"}));this.finishDraft({switchToSelect:!1}),Ym(this.editor.getShape(e))&&(this.editor.commands.setActiveTool("select",{source:"system"}),this.editor.startEditingShape({shapeId:e,markId:"path.edit",entryMode:"focusEnd"},"user"))}}cancelDraft(){this.draft&&(hy(this.editor,"create",this.draft.shapeId),this.cancelOperation(),this.draft=null)}hasDraft(){return null!==this.draft}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}},EE=class extends Iv{tool;constructor(e,t){super(e,"idle",t),this.tool=t}onPointerDown(e){if(0!==e.button)return;const t=this.tool.startOrExtend(e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey});t&&this.transition("dragging_node",t)}onPointerMove(e){this.tool.updatePreview(e.pagePoint,{shiftKey:e.shiftKey})}onKeyDown(e){("Enter"===e.key&&this.tool.hasDraft()||"Escape"===e.key&&this.tool.hasDraft())&&this.tool.finishDraftAndEdit()}onCancel(e){"escape"===e.reason&&this.tool.hasDraft()&&this.tool.finishDraftAndEdit()}},AE=class extends Iv{tool;info=null;constructor(e,t){super(e,"dragging_node",t),this.tool=t}onEnter(e){this.info=e}onPointerMove(e){this.info&&this.tool.updateNodeDrag(this.info,e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey})}onPointerUp(e){const t=this.info;t&&(this.tool.updateNodeDrag(t,e.pagePoint,{altKey:e.altKey,shiftKey:e.shiftKey}),uy(this.editor,t.shapeId)),this.transition("idle"),t?.finishOnPointerUp&&this.tool.finishDraft()}onCancel(){this.tool.cancelDraft(),this.transition("idle")}onExit(){this.info=null}},BE=aI((e,t)=>{var n,i;n=e,i=function(){function e(e,t){return e>t?1:e<t?-1:0}function t(e,t,n){for(var i=new c(null,null),o=i,r=i;;){var s=n(e,t.key);if(s<0){if(null===t.left)break;if(n(e,t.left.key)<0&&(t.left=(a=t.left).right,a.right=t,null===(t=a).left))break;r.left=t,r=t,t=t.left}else{if(!(s>0))break;if(null===t.right)break;var a;if(n(e,t.right.key)>0&&(t.right=(a=t.right).left,a.left=t,null===(t=a).right))break;o.right=t,o=t,t=t.right}}return o.right=t.left,r.left=t.right,t.left=i.right,t.right=i.left,t}function n(e,n,i,o){var r=new c(e,n);if(null===i)return r.left=r.right=null,r;var s=o(e,(i=t(e,i,o)).key);return s<0?(r.left=i.left,r.right=i,i.left=null):s>=0&&(r.right=i.right,r.left=i,i.right=null),r}function i(e,n,i){var o=null,r=null;if(n){var s=i((n=t(e,n,i)).key,e);0===s?(o=n.left,r=n.right):s<0?(r=n.right,n.right=null,o=n):(o=n.left,n.left=null,r=n)}return{left:o,right:r}}function o(e,t,n,i,r){if(e){i(t+(n?"└── ":"├── ")+r(e)+"\n");var s=t+(n?" ":"│ ");e.left&&o(e.left,s,!1,i,r),e.right&&o(e.right,s,!0,i,r)}}function r(e,t,n,i){var o=i-n;if(o>0){var s=n+Math.floor(o/2),a=new c(e[s],t[s]);return a.left=r(e,t,n,s),a.right=r(e,t,s+1,i),a}return null}function s(e,t,n){var i=n-t;if(i>0){var o=t+Math.floor(i/2),r=s(e,t,o),a=e.head;return a.left=r,e.head=e.head.next,a.right=s(e,o+1,n),a}return null}function a(e,t,n,i,o){if(!(n>=i)){for(var r=e[n+i>>1],s=n-1,l=i+1;;){do{s++}while(o(e[s],r)<0);do{l--}while(o(e[l],r)>0);if(s>=l)break;var d=e[s];e[s]=e[l],e[l]=d,d=t[s],t[s]=t[l],t[l]=d}a(e,t,n,l,o),a(e,t,l+1,i,o)}}function l(e,t,n,i,o){let r,s,a,l,d=t[0],c=i[0],u=0,h=0;c>d==c>-d?(r=d,d=t[++u]):(r=c,c=i[++h]);let p=0;if(u<e&&h<n)for(c>d==c>-d?(s=d+r,a=r-(s-d),d=t[++u]):(s=c+r,a=r-(s-c),c=i[++h]),r=s,0!==a&&(o[p++]=a);u<e&&h<n;)c>d==c>-d?(s=r+d,l=s-r,a=r-(s-l)+(d-l),d=t[++u]):(s=r+c,l=s-r,a=r-(s-l)+(c-l),c=i[++h]),r=s,0!==a&&(o[p++]=a);for(;u<e;)s=r+d,l=s-r,a=r-(s-l)+(d-l),d=t[++u],r=s,0!==a&&(o[p++]=a);for(;h<n;)s=r+c,l=s-r,a=r-(s-l)+(c-l),c=i[++h],r=s,0!==a&&(o[p++]=a);return 0===r&&0!==p||(o[p++]=r),p}function d(e){return new Float64Array(e)}var c=function(e,t){this.next=null,this.key=e,this.data=t,this.left=null,this.right=null},u=function(){function l(t){void 0===t&&(t=e),this._root=null,this._size=0,this._comparator=t}return l.prototype.insert=function(e,t){return this._size++,this._root=n(e,t,this._root,this._comparator)},l.prototype.add=function(e,n){var i=new c(e,n);null===this._root&&(i.left=i.right=null,this._size++,this._root=i);var o=this._comparator,r=t(e,this._root,o),s=o(e,r.key);return 0===s?this._root=r:(s<0?(i.left=r.left,i.right=r,r.left=null):s>0&&(i.right=r.right,i.left=r,r.right=null),this._size++,this._root=i),this._root},l.prototype.remove=function(e){this._root=this._remove(e,this._root,this._comparator)},l.prototype._remove=function(e,n,i){var o;return null===n?null:0===i(e,(n=t(e,n,i)).key)?(null===n.left?o=n.right:(o=t(e,n.left,i)).right=n.right,this._size--,o):n},l.prototype.pop=function(){var e=this._root;if(e){for(;e.left;)e=e.left;return this._root=t(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null},l.prototype.findStatic=function(e){for(var t=this._root,n=this._comparator;t;){var i=n(e,t.key);if(0===i)return t;t=i<0?t.left:t.right}return null},l.prototype.find=function(e){return this._root&&(this._root=t(e,this._root,this._comparator),0!==this._comparator(e,this._root.key))?null:this._root},l.prototype.contains=function(e){for(var t=this._root,n=this._comparator;t;){var i=n(e,t.key);if(0===i)return!0;t=i<0?t.left:t.right}return!1},l.prototype.forEach=function(e,t){for(var n=this._root,i=[],o=!1;!o;)null!==n?(i.push(n),n=n.left):0!==i.length?(n=i.pop(),e.call(t,n),n=n.right):o=!0;return this},l.prototype.range=function(e,t,n,i){for(var o=[],r=this._comparator,s=this._root;0!==o.length||s;)if(s)o.push(s),s=s.left;else{if(r((s=o.pop()).key,t)>0)break;if(r(s.key,e)>=0&&n.call(i,s))return this;s=s.right}return this},l.prototype.keys=function(){var e=[];return this.forEach(t=>e.push(t.key)),e},l.prototype.values=function(){var e=[];return this.forEach(t=>e.push(t.data)),e},l.prototype.min=function(){return this._root?this.minNode(this._root).key:null},l.prototype.max=function(){return this._root?this.maxNode(this._root).key:null},l.prototype.minNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.left;)e=e.left;return e},l.prototype.maxNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.right;)e=e.right;return e},l.prototype.at=function(e){for(var t=this._root,n=!1,i=0,o=[];!n;)if(t)o.push(t),t=t.left;else if(o.length>0){if(t=o.pop(),i===e)return t;i++,t=t.right}else n=!0;return null},l.prototype.next=function(e){var t=this._root,n=null;if(e.right){for(n=e.right;n.left;)n=n.left;return n}for(var i=this._comparator;t;){var o=i(e.key,t.key);if(0===o)break;o<0?(n=t,t=t.left):t=t.right}return n},l.prototype.prev=function(e){var t=this._root,n=null;if(null!==e.left){for(n=e.left;n.right;)n=n.right;return n}for(var i=this._comparator;t;){var o=i(e.key,t.key);if(0===o)break;o<0?t=t.left:(n=t,t=t.right)}return n},l.prototype.clear=function(){return this._root=null,this._size=0,this},l.prototype.toList=function(){return(()=>{for(var e=this._root,t=[],n=!1,i=new c(null,null),o=i;!n;)e?(t.push(e),e=e.left):t.length>0?e=(e=o=o.next=t.pop()).right:n=!0;return o.next=null,i.next})()},l.prototype.load=function(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=!1);var i=e.length,o=this._comparator;if(n&&a(e,t,0,i-1,o),null===this._root)this._root=r(e,t,0,i),this._size=i;else{var l=((e,t,n)=>{for(var i=new c(null,null),o=i,r=e,s=t;null!==r&&null!==s;)n(r.key,s.key)<0?(o.next=r,r=r.next):(o.next=s,s=s.next),o=o.next;return null!==r?o.next=r:null!==s&&(o.next=s),i.next})(this.toList(),((e,t)=>{for(var n=new c(null,null),i=n,o=0;o<e.length;o++)i=i.next=new c(e[o],t[o]);return i.next=null,n.next})(e,t),o);this._root=s({head:l},0,i=this._size+i)}return this},l.prototype.isEmpty=function(){return null===this._root},Object.defineProperty(l.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),l.prototype.toString=function(e){void 0===e&&(e=e=>String(e.key));var t=[];return o(this._root,"",!0,e=>t.push(e),e),t.join("")},l.prototype.update=function(e,o,r){var s=this._comparator,a=i(e,this._root,s),l=a.left,d=a.right;s(e,o)<0?d=n(o,r,d,s):l=n(o,r,l,s),this._root=((e,n,i)=>null===n?e:(null===e||((n=t(e.key,n,i)).left=e),n))(l,d,s)},l.prototype.split=function(e){return i(e,this._root,this._comparator)},l.prototype[Symbol.iterator]=function(){var e,t,n;return function(e,t){function n(n){return s=>(n=>{if(i)throw new TypeError("Generator is already executing.");for(;a;)try{if(i=1,o&&(r=2&n[0]?o.return:n[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,n[1])).done)return r;switch(o=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,o=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==n[0]&&2!==n[0])){a=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){a.label=n[1];break}if(6===n[0]&&a.label<r[1]){a.label=r[1],r=n;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(n);break}r[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}catch(s){n=[6,s],o=0}finally{i=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}})([n,s])}var i,o,r,s,a={label:0,sent:()=>{if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s}(this,function(i){switch(i.label){case 0:e=this._root,t=[],n=!1,i.label=1;case 1:return n?[3,6]:null===e?[3,2]:(t.push(e),e=e.left,[3,5]);case 2:return 0===t.length?[3,4]:[4,e=t.pop()];case 3:return i.sent(),e=e.right,[3,5];case 4:n=!0,i.label=5;case 5:return[3,1];case 6:return[2]}})},l}();const h=(e,t)=>e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y,p=(e,t)=>t.ur.x<e.ll.x||e.ur.x<t.ll.x||t.ur.y<e.ll.y||e.ur.y<t.ll.y?null:{ll:{x:e.ll.x<t.ll.x?t.ll.x:e.ll.x,y:e.ll.y<t.ll.y?t.ll.y:e.ll.y},ur:{x:e.ur.x<t.ur.x?e.ur.x:t.ur.x,y:e.ur.y<t.ur.y?e.ur.y:t.ur.y}};let g=Number.EPSILON;void 0===g&&(g=Math.pow(2,-52));const f=g*g,m=(e,t)=>{if(-g<e&&e<g&&-g<t&&t<g)return 0;const n=e-t;return n*n<f*e*t?0:e<t?-1:1};class S{constructor(){this.tree=new u,this.round(0)}round(e){const t=this.tree.add(e),n=this.tree.prev(t);if(null!==n&&0===m(t.key,n.key))return this.tree.remove(e),n.key;const i=this.tree.next(t);return null!==i&&0===m(t.key,i.key)?(this.tree.remove(e),i.key):e}}const y=new class{constructor(){this.reset()}reset(){this.xRounder=new S,this.yRounder=new S}round(e,t){return{x:this.xRounder.round(e),y:this.yRounder.round(t)}}},b=134217729,x=d(4),I=d(8),v=d(12),w=d(16),P=d(4),k=(e,t)=>e.x*t.y-e.y*t.x,C=(e,t)=>e.x*t.x+e.y*t.y,T=(e,t,n)=>{const i=function(e,t,n,i,o,r){const s=(t-r)*(n-o),a=(e-o)*(i-r),d=s-a,c=Math.abs(s+a);return Math.abs(d)>=33306690738754716e-32*c?d:-((e,t,n,i,o,r,s)=>{let a,d,c,u,h,p,g,f,m,S,y,k,C,T,M,E,A,B;const R=e-o,L=n-o,$=t-r,F=i-r;T=R*F,p=b*R,g=p-(p-R),f=R-g,p=b*F,m=p-(p-F),S=F-m,M=f*S-(T-g*m-f*m-g*S),E=$*L,p=b*$,g=p-(p-$),f=$-g,p=b*L,m=p-(p-L),S=L-m,A=f*S-(E-g*m-f*m-g*S),y=M-A,h=M-y,x[0]=M-(y+h)+(h-A),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-E,h=C-y,x[1]=C-(y+h)+(h-E),B=k+y,h=B-k,x[2]=k-(B-h)+(y-h),x[3]=B;let U=((e,t)=>{let n=t[0];for(let i=1;i<4;i++)n+=t[i];return n})(0,x),O=22204460492503146e-32*s;if(U>=O||-U>=O)return U;if(h=e-R,a=e-(R+h)+(h-o),h=n-L,c=n-(L+h)+(h-o),h=t-$,d=t-($+h)+(h-r),h=i-F,u=i-(F+h)+(h-r),0===a&&0===d&&0===c&&0===u)return U;if(O=11093356479670487e-47*s+33306690738754706e-32*Math.abs(U),U+=R*u+F*a-($*c+L*d),U>=O||-U>=O)return U;T=a*F,p=b*a,g=p-(p-a),f=a-g,p=b*F,m=p-(p-F),S=F-m,M=f*S-(T-g*m-f*m-g*S),E=d*L,p=b*d,g=p-(p-d),f=d-g,p=b*L,m=p-(p-L),S=L-m,A=f*S-(E-g*m-f*m-g*S),y=M-A,h=M-y,P[0]=M-(y+h)+(h-A),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-E,h=C-y,P[1]=C-(y+h)+(h-E),B=k+y,h=B-k,P[2]=k-(B-h)+(y-h),P[3]=B;const D=l(4,x,4,P,I);T=R*u,p=b*R,g=p-(p-R),f=R-g,p=b*u,m=p-(p-u),S=u-m,M=f*S-(T-g*m-f*m-g*S),E=$*c,p=b*$,g=p-(p-$),f=$-g,p=b*c,m=p-(p-c),S=c-m,A=f*S-(E-g*m-f*m-g*S),y=M-A,h=M-y,P[0]=M-(y+h)+(h-A),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-E,h=C-y,P[1]=C-(y+h)+(h-E),B=k+y,h=B-k,P[2]=k-(B-h)+(y-h),P[3]=B;const z=l(D,I,4,P,v);return T=a*u,p=b*a,g=p-(p-a),f=a-g,p=b*u,m=p-(p-u),S=u-m,M=f*S-(T-g*m-f*m-g*S),E=d*c,p=b*d,g=p-(p-d),f=d-g,p=b*c,m=p-(p-c),S=c-m,A=f*S-(E-g*m-f*m-g*S),y=M-A,h=M-y,P[0]=M-(y+h)+(h-A),k=T+y,h=k-T,C=T-(k-h)+(y-h),y=C-E,h=C-y,P[1]=C-(y+h)+(h-E),B=k+y,h=B-k,P[2]=k-(B-h)+(y-h),P[3]=B,w[l(z,v,4,P,w)-1]})(e,t,n,i,o,r,c)}(e.x,e.y,t.x,t.y,n.x,n.y);return i>0?-1:i<0?1:0},M=e=>Math.sqrt(C(e,e)),E=(e,t,n)=>{const i={x:t.x-e.x,y:t.y-e.y},o={x:n.x-e.x,y:n.y-e.y};return k(o,i)/M(o)/M(i)},A=(e,t,n)=>{const i={x:t.x-e.x,y:t.y-e.y},o={x:n.x-e.x,y:n.y-e.y};return C(o,i)/M(o)/M(i)},B=(e,t,n)=>0===t.y?null:{x:e.x+t.x/t.y*(n-e.y),y:n},R=(e,t,n)=>0===t.x?null:{x:n,y:e.y+t.y/t.x*(n-e.x)};class L{static compare(e,t){const n=L.comparePoints(e.point,t.point);return 0!==n?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:F.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x<t.x?-1:e.x>t.x?1:e.y<t.y?-1:e.y>t.y?1:0}constructor(e,t){void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,i=t.length;n<i;n++){const e=t[n];this.point.events.push(e),e.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let t=0;t<e;t++){const n=this.point.events[t];if(void 0===n.segment.consumedBy)for(let i=t+1;i<e;i++){const e=this.point.events[i];void 0===e.consumedBy&&n.otherSE.point.events===e.otherSE.point.events&&n.segment.consume(e.segment)}}}getAvailableLinkedEvents(){const e=[];for(let t=0,n=this.point.events.length;t<n;t++){const n=this.point.events[t];n!==this&&!n.segment.ringOut&&n.segment.isInResult()&&e.push(n)}return e}getLeftmostComparator(e){const t=new Map,n=n=>{const i=n.otherSE;t.set(n,{sine:E(this.point,e.point,i.point),cosine:A(this.point,e.point,i.point)})};return(e,i)=>{t.has(e)||n(e),t.has(i)||n(i);const{sine:o,cosine:r}=t.get(e),{sine:s,cosine:a}=t.get(i);return o>=0&&s>=0?r<a?1:r>a?-1:0:o<0&&s<0?r<a?-1:r>a?1:0:s<o?-1:s>o?1:0}}}let $=0;class F{static compare(e,t){const n=e.leftSE.point.x,i=t.leftSE.point.x,o=e.rightSE.point.x,r=t.rightSE.point.x;if(r<n)return 1;if(o<i)return-1;const s=e.leftSE.point.y,a=t.leftSE.point.y,l=e.rightSE.point.y,d=t.rightSE.point.y;if(n<i){if(a<s&&a<l)return 1;if(a>s&&a>l)return-1;const n=e.comparePoint(t.leftSE.point);if(n<0)return 1;if(n>0)return-1;const i=t.comparePoint(e.rightSE.point);return 0!==i?i:-1}if(n>i){if(s<a&&s<d)return-1;if(s>a&&s>d)return 1;const n=t.comparePoint(e.leftSE.point);if(0!==n)return n;const i=e.comparePoint(t.rightSE.point);return i<0?1:i>0?-1:1}if(s<a)return-1;if(s>a)return 1;if(o<r){const n=t.comparePoint(e.rightSE.point);if(0!==n)return n}if(o>r){const n=e.comparePoint(t.rightSE.point);if(n<0)return 1;if(n>0)return-1}if(o!==r){const e=l-s,t=o-n,c=d-a,u=r-i;if(e>t&&c<u)return 1;if(e<t&&c>u)return-1}return o>r?1:o<r||l<d?-1:l>d?1:e.id<t.id?-1:e.id>t.id?1:0}constructor(e,t,n,i){this.id=++$,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=n,this.windings=i}static fromRing(e,t,n){let i,o,r;const s=L.comparePoints(e,t);if(s<0)i=e,o=t,r=1;else{if(!(s>0))throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);i=t,o=e,r=-1}return new F(new L(i,!0),new L(o,!1),[n],[r])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e<t?e:t},ur:{x:this.rightSE.point.x,y:e>t?e:t}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}comparePoint(e){if(this.isAnEndpoint(e))return 0;const t=this.leftSE.point,n=this.rightSE.point,i=this.vector();if(t.x===n.x)return e.x===t.x?0:e.x<t.x?1:-1;if(e.x===t.x+(e.y-t.y)/i.y*i.x)return 0;const o=t.y+(e.x-t.x)/i.x*i.y;return e.y===o?0:e.y<o?-1:1}getIntersection(e){const t=this.bbox(),n=e.bbox(),i=p(t,n);if(null===i)return null;const o=this.leftSE.point,r=this.rightSE.point,s=e.leftSE.point,a=e.rightSE.point,l=h(t,s)&&0===this.comparePoint(s),d=h(n,o)&&0===e.comparePoint(o),c=h(t,a)&&0===this.comparePoint(a),u=h(n,r)&&0===e.comparePoint(r);if(d&&l)return u&&!c?r:!u&&c?a:null;if(d)return c&&o.x===a.x&&o.y===a.y?null:o;if(l)return u&&r.x===s.x&&r.y===s.y?null:s;if(u&&c)return null;if(u)return r;if(c)return a;const g=((e,t,n,i)=>{if(0===t.x)return R(n,i,e.x);if(0===i.x)return R(e,t,n.x);if(0===t.y)return B(n,i,e.y);if(0===i.y)return B(e,t,n.y);const o=k(t,i);if(0==o)return null;const r={x:n.x-e.x,y:n.y-e.y},s=k(r,t)/o,a=k(r,i)/o;return{x:(e.x+a*t.x+(n.x+s*i.x))/2,y:(e.y+a*t.y+(n.y+s*i.y))/2}})(o,this.vector(),s,e.vector());return null===g?null:h(i,g)?y.round(g.x,g.y):null}split(e){const t=[],n=void 0!==e.events,i=new L(e,!0),o=new L(e,!1),r=this.rightSE;this.replaceRightSE(o),t.push(o),t.push(i);const s=new F(i,r,this.rings.slice(),this.windings.slice());return L.comparePoints(s.leftSE.point,s.rightSE.point)>0&&s.swapEvents(),L.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(i.checkForConsuming(),o.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t<n;t++)this.windings[t]*=-1}consume(e){let t=this,n=e;for(;t.consumedBy;)t=t.consumedBy;for(;n.consumedBy;)n=n.consumedBy;const i=F.compare(t,n);if(0!==i){if(i>0){const e=t;t=n,n=e}if(t.prev===n){const e=t;t=n,n=e}for(let e=0,i=n.rings.length;e<i;e++){const i=n.rings[e],o=n.windings[e],r=t.rings.indexOf(i);-1===r?(t.rings.push(i),t.windings.push(o)):t.windings[r]+=o}n.rings=null,n.windings=null,n.consumedBy=t,n.leftSE.consumedBy=t.leftSE,n.rightSE.consumedBy=t.rightSE}}prevInResult(){return void 0!==this._prevInResult||(this._prevInResult=this.prev?this.prev.isInResult()?this.prev:this.prev.prevInResult():null),this._prevInResult}beforeState(){return void 0!==this._beforeState||(this._beforeState=this.prev?(this.prev.consumedBy||this.prev).afterState():{rings:[],windings:[],multiPolys:[]}),this._beforeState}afterState(){if(void 0!==this._afterState)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const t=this._afterState.rings,n=this._afterState.windings,i=this._afterState.multiPolys;for(let s=0,a=this.rings.length;s<a;s++){const e=this.rings[s],i=this.windings[s],o=t.indexOf(e);-1===o?(t.push(e),n.push(i)):n[o]+=i}const o=[],r=[];for(let s=0,a=t.length;s<a;s++){if(0===n[s])continue;const e=t[s],i=e.poly;if(-1===r.indexOf(i))if(e.isExterior)o.push(i);else{-1===r.indexOf(i)&&r.push(i);const t=o.indexOf(e.poly);-1!==t&&o.splice(t,1)}}for(let s=0,a=o.length;s<a;s++){const e=o[s].multiPoly;-1===i.indexOf(e)&&i.push(e)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(void 0!==this._isInResult)return this._isInResult;const e=this.beforeState().multiPolys,t=this.afterState().multiPolys;switch(Y.type){case"union":this._isInResult=0===e.length!=(0===t.length);break;case"intersection":{let n,i;e.length<t.length?(n=e.length,i=t.length):(n=t.length,i=e.length),this._isInResult=i===Y.numMultiPolys&&n<i;break}case"xor":{const n=Math.abs(e.length-t.length);this._isInResult=n%2==1;break}case"difference":{const n=e=>1===e.length&&e[0].isSubject;this._isInResult=n(e)!==n(t);break}default:throw new Error(`Unrecognized operation type found ${Y.type}`)}return this._isInResult}}class U{constructor(e,t,n){if(!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=n,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const i=y.round(e[0][0],e[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};let o=i;for(let r=1,s=e.length;r<s;r++){if("number"!=typeof e[r][0]||"number"!=typeof e[r][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let t=y.round(e[r][0],e[r][1]);t.x===o.x&&t.y===o.y||(this.segments.push(F.fromRing(o,t,this)),t.x<this.bbox.ll.x&&(this.bbox.ll.x=t.x),t.y<this.bbox.ll.y&&(this.bbox.ll.y=t.y),t.x>this.bbox.ur.x&&(this.bbox.ur.x=t.x),t.y>this.bbox.ur.y&&(this.bbox.ur.y=t.y),o=t)}i.x===o.x&&i.y===o.y||this.segments.push(F.fromRing(o,i,this))}getSweepEvents(){const e=[];for(let t=0,n=this.segments.length;t<n;t++){const n=this.segments[t];e.push(n.leftSE),e.push(n.rightSE)}return e}}class O{constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new U(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let n=1,i=e.length;n<i;n++){const t=new U(e[n],this,!1);t.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=t.bbox.ur.y),this.interiorRings.push(t)}this.multiPoly=t}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let t=0,n=this.interiorRings.length;t<n;t++){const n=this.interiorRings[t].getSweepEvents();for(let t=0,i=n.length;t<i;t++)e.push(n[t])}return e}}class D{constructor(e,t){if(!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{"number"==typeof e[0][0][0]&&(e=[e])}catch(n){}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let i=0,o=e.length;i<o;i++){const t=new O(e[i],this);t.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=t.bbox.ur.y),this.polys.push(t)}this.isSubject=t}getSweepEvents(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const n=this.polys[t].getSweepEvents();for(let t=0,i=n.length;t<i;t++)e.push(n[t])}return e}}class z{static factory(e){const t=[];for(let n=0,i=e.length;n<i;n++){const i=e[n];if(!i.isInResult()||i.ringOut)continue;let o=null,r=i.leftSE,s=i.rightSE;const a=[r],l=r.point,d=[];for(;o=r,r=s,a.push(r),r.point!==l;)for(;;){const e=r.getAvailableLinkedEvents();if(0===e.length){const e=a[0].point,t=a[a.length-1].point;throw new Error(`Unable to complete output ring starting at [${e.x}, ${e.y}]. Last matching segment found ends at [${t.x}, ${t.y}].`)}if(1===e.length){s=e[0].otherSE;break}let n=null;for(let t=0,o=d.length;t<o;t++)if(d[t].point===r.point){n=t;break}if(null!==n){const e=d.splice(n)[0],i=a.splice(e.index);i.unshift(i[0].otherSE),t.push(new z(i.reverse()));continue}d.push({index:a.length,point:r.point});const i=r.getLeftmostComparator(o);s=e.sort(i)[0].otherSE;break}t.push(new z(a))}return t}constructor(e){this.events=e;for(let t=0,n=e.length;t<n;t++)e[t].segment.ringOut=this;this.poly=null}getGeom(){let e=this.events[0].point;const t=[e];for(let s=1,a=this.events.length-1;s<a;s++){const n=this.events[s].point;0!==T(n,e,this.events[s+1].point)&&(t.push(n),e=n)}if(1===t.length)return null;0===T(t[0],e,t[1])&&t.shift(),t.push(t[0]);const n=this.isExteriorRing()?1:-1,i=this.isExteriorRing()?0:t.length-1,o=this.isExteriorRing()?t.length:-1,r=[];for(let s=i;s!=o;s+=n)r.push([t[s].x,t[s].y]);return r}isExteriorRing(){if(void 0===this._isExteriorRing){const e=this.enclosingRing();this._isExteriorRing=!e||!e.isExteriorRing()}return this._isExteriorRing}enclosingRing(){return void 0===this._enclosingRing&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let e=this.events[0];for(let i=1,o=this.events.length;i<o;i++){const t=this.events[i];L.compare(e,t)>0&&(e=t)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return n.ringOut.enclosingRing()!==t.ringOut?t.ringOut:t.ringOut.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}}class N{constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=[this.exteriorRing.getGeom()];if(null===e[0])return null;for(let t=0,n=this.interiorRings.length;t<n;t++){const n=this.interiorRings[t].getGeom();null!==n&&e.push(n)}return e}}class H{constructor(e){this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let t=0,n=this.polys.length;t<n;t++){const n=this.polys[t].getGeom();null!==n&&e.push(n)}return e}_composePolys(e){const t=[];for(let n=0,i=e.length;n<i;n++){const i=e[n];if(!i.poly)if(i.isExteriorRing())t.push(new N(i));else{const e=i.enclosingRing();e.poly||t.push(new N(e)),e.poly.addInterior(i)}}return t}}class W{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:F.compare;this.queue=e,this.tree=new u(t),this.segments=[]}process(e){const t=e.segment,n=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(t),n;const i=e.isLeft?this.tree.add(t):this.tree.find(t);if(!i)throw new Error(`Unable to find segment #${t.id} [${t.leftSE.point.x}, ${t.leftSE.point.y}] -> [${t.rightSE.point.x}, ${t.rightSE.point.y}] in SweepLine tree.`);let o,r,s=i,a=i;for(;void 0===o;)s=this.tree.prev(s),null===s?o=null:void 0===s.key.consumedBy&&(o=s.key);for(;void 0===r;)a=this.tree.next(a),null===a?r=null:void 0===a.key.consumedBy&&(r=a.key);if(e.isLeft){let i=null;if(o){const e=o.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(i=e),!o.isAnEndpoint(e))){const t=this._splitSafely(o,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}}let s=null;if(r){const e=r.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(s=e),!r.isAnEndpoint(e))){const t=this._splitSafely(r,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}}if(null!==i||null!==s){let e=null;e=null===i?s:null===s||L.comparePoints(i,s)<=0?i:s,this.queue.remove(t.rightSE),n.push(t.rightSE);const o=t.split(e);for(let t=0,i=o.length;t<i;t++)n.push(o[t])}n.length>0?(this.tree.remove(t),n.push(e)):(this.segments.push(t),t.prev=o)}else{if(o&&r){const e=o.getIntersection(r);if(null!==e){if(!o.isAnEndpoint(e)){const t=this._splitSafely(o,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}if(!r.isAnEndpoint(e)){const t=this._splitSafely(r,e);for(let e=0,i=t.length;e<i;e++)n.push(t[e])}}}this.tree.remove(t)}return n}_splitSafely(e,t){this.tree.remove(e);const n=e.rightSE;this.queue.remove(n);const i=e.split(t);return i.push(n),void 0===e.consumedBy&&this.tree.add(e),i}}const _="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,K="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6,Y=new class{run(e,t,n){Y.type=e,y.reset();const i=[new D(t,!0)];for(let l=0,d=n.length;l<d;l++)i.push(new D(n[l],!1));if(Y.numMultiPolys=i.length,"difference"===Y.type){const e=i[0];let t=1;for(;t<i.length;)null!==p(i[t].bbox,e.bbox)?t++:i.splice(t,1)}if("intersection"===Y.type)for(let l=0,d=i.length;l<d;l++){const e=i[l];for(let t=l+1,n=i.length;t<n;t++)if(null===p(e.bbox,i[t].bbox))return[]}const o=new u(L.compare);for(let l=0,d=i.length;l<d;l++){const e=i[l].getSweepEvents();for(let t=0,n=e.length;t<n;t++)if(o.insert(e[t]),o.size>_)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const r=new W(o);let s=o.size,a=o.pop();for(;a;){const e=a.key;if(o.size===s){const t=e.segment;throw new Error(`Unable to pop() ${e.isLeft?"left":"right"} SweepEvent [${e.point.x}, ${e.point.y}] from segment #${t.id} [${t.leftSE.point.x}, ${t.leftSE.point.y}] -> [${t.rightSE.point.x}, ${t.rightSE.point.y}] from queue.`)}if(o.size>_)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(r.segments.length>K)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const t=r.process(e);for(let n=0,i=t.length;n<i;n++){const e=t[n];void 0===e.consumedBy&&o.insert(e)}s=o.size,a=o.pop()}return y.reset(),new H(z.factory(r.segments)).getGeom()}};return{union:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return Y.run("union",e,n)},intersection:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return Y.run("intersection",e,n)},xor:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return Y.run("xor",e,n)},difference:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return Y.run("difference",e,n)}}},"object"==typeof e&&void 0!==t?t.exports=i():"function"==typeof define&&define.amd?define(i):(n="undefined"!=typeof globalThis?globalThis:n||self).polygonClipping=i()})(),RE=1,LE=1,$E="path.edit",FE="path.edit.done",UE="path.edit.snap-nodes",OE="path.boolean.union",DE="path.boolean.subtract",zE="path.boolean.intersect",NE="path.boolean.xor",HE="path.node.delete",WE="path.node.make-curve",_E="path.node.remove-handles",KE="path.node.merge",YE="path.node.join",XE="path.node.separate",qE=[{id:"none",value:E("transparent"),label:"None",hexColor:"#f8fafc",opacity:0},{value:M("fill-blue"),label:"Blue",id:"blue",hexColor:"#dbeafe"},{value:M("fill-green"),label:"Green",id:"green",hexColor:"#dcfce7"},{value:M("fill-red"),label:"Red",id:"red",hexColor:"#fee2e2"},{value:M("fill-white"),label:"White",id:"white",hexColor:"#f8fafc"}],jE=[{value:M("stroke-blue"),label:"Blue",id:"blue",hexColor:"#1d4ed8"},{value:M("stroke-green"),label:"Green",id:"green",hexColor:"#15803d"},{value:M("stroke-red"),label:"Red",id:"red",hexColor:"#dc2626"},{value:M("stroke-slate"),label:"Slate",id:"slate",hexColor:"#334155"}],VE={id:"path",editor:{id:"land.path",shapeCapabilities:[{type:"path",schemaProps:["subpaths","fill","stroke","strokeWidth","fillRule"],reactRenderer:"supported",toolbarEntry:"supported",notes:["Path owns editable Bezier node geometry, multi-subpath fill rules, SVG export, and destructive polygon-clipping boolean materialization."]}],shapeUtils:[new class extends xv{type="path";getDefaultProps(){return{subpaths:[{id:"subpath:default",closed:!1,nodes:[{id:"node:0",x:0,y:0,kind:"corner"},{id:"node:1",x:96,y:0,kind:"corner"}]}],fill:E("transparent"),stroke:M("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(e){const t=e&&"object"==typeof e?e:{},n=this.getDefaultProps();return{subpaths:(o=Fy(t.subpaths,n.subpaths),o.map(e=>({...e,nodes:e.nodes.filter(e=>Zm(e.x)&&Zm(e.y))})).filter(e=>e.nodes.length>0).map(eS)),fill:$(t.fill,n.fill),stroke:$(t.stroke,n.stroke),strokeWidth:Math.max(1,Ly(t.strokeWidth,n.strokeWidth)),fillRule:(i=t.fillRule,"string"==typeof i&&sE.includes(i)?t.fillRule:n.fillRule)};var i,o}getPositionedBounds(e){const t=hS(e).localBounds;return new SI(e.x+t.x,e.y+t.y,t.w,t.h)}getLocalBounds(e){return hS(e).localBounds}getRenderBounds(e){return hS(e).renderBounds}getExportBounds(e){return this.getRenderBounds(e)}getSelectionResizeLocalBounds(e){return hS(e).pointBounds}resizeSelectionBounds(e,t){const n=mS(e,this.getLocalToPageTransform(e)).map(e=>({...e,nodes:e.nodes.map(e=>zy(e,e=>((e,t)=>0===t.selectionRotation?e:mI.RotWith(e,t.selectionRotationCenter,-t.selectionRotation))(e,t)))})),i=fS(((e,t)=>{const n=hS(e).pointBounds,i=0===n.w?1:t.w/Math.max(n.w,1e-6),o=0===n.h?1:t.h/Math.max(n.h,1e-6);return gS(e.props.subpaths,e=>new mI(0===n.w?t.center.x:t.x+(e.x-n.x)*i,0===n.h?t.center.y:t.y+(e.y-n.y)*o))})({...e,x:0,y:0,rotation:0,scaleX:1,scaleY:1,props:{...e.props,subpaths:n}},t.selectionLocalBounds).map(e=>({...e,nodes:e.nodes.map(e=>zy(e,e=>((e,t)=>0===t.selectionRotation?e:mI.RotWith(e,t.selectionRotationCenter,t.selectionRotation))(e,t)))})),e.props);return{id:e.id,x:i.x,y:i.y,rotation:0,scaleX:1,scaleY:1,props:{subpaths:i.subpaths}}}getPositionedOutlineVertices(e){return hS(e).outlineVertices.map(t=>new mI(e.x+t.x,e.y+t.y))}getTerminalBindingOutlines(e){return hS(e).flattenedSubpaths.filter(e=>e.points.length>0).map(t=>({points:t.points.map(t=>new mI(e.x+t.x,e.y+t.y)),closed:t.closed}))}resolveBindingPoint(e,t){const n=t.editor.computeShapePositionedToPageTransform(e),i=n.tryInvert();if(!i)return t.rawPagePoint;const o=i.applyToPoint(t.rawPagePoint),r=i.applyToPoint(t.oppositePagePoint),s=r.sub(o);let a=Number.POSITIVE_INFINITY;for(const l of this.getTerminalBindingOutlines(e)){const e=l.closed?l.points.length:Math.max(0,l.points.length-1);for(let t=0;t<e;t+=1){const e=l.points[t],n=l.points[(t+1)%l.points.length];if(!e||!n)continue;const i=Dy(o,r,e,n);null!==i&&i>1e-6&&i<a&&(a=i)}}return Number.isFinite(a)?n.applyToPoint(o.add(s.mul(a))):t.rawPagePoint}getHandleSnapGeometry(e){return{points:e.props.subpaths.flatMap(e=>e.nodes.flatMap(e=>[{point:nS(e),kind:"custom"},...e.in?[{point:iS(e),kind:"custom"}]:[],...e.out?[{point:oS(e),kind:"custom"}]:[]])),outline:hS(e).outlineVertices}}canReceiveTerminalBinding(e){return!0}canEdit(e){return!0}canUseSelectionResizeHandles(e,t){return t.editor.getShapeEditingSession()?.shapeId!==e.id}canUseSelectionRotateHandle(e,t){return t.editor.getShapeEditingSession()?.shapeId!==e.id}getSelectionHandleAnchors(e,t){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!t.isOnlySelected)return n;const i=t.editor.getShapeEditingSession();if(!i||i.shapeId!==e.id)return n;const o=t.editor.computeShapeLocalToPageTransform(e);return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:e.props.subpaths.flatMap(e=>e.nodes.flatMap(t=>{const n=[{kind:"custom",type:iE,id:(i=e.id,r=t.id,["node",i,r].map(encodeURIComponent).join("|")),point:o.applyToPoint(nS(t)),cursor:"grab"}];var i,r;return t.in&&n.push({kind:"custom",type:oE,id:Hm(e.id,t.id,"in"),point:o.applyToPoint(iS(t)),cursor:"grab"}),t.out&&n.push({kind:"custom",type:oE,id:Hm(e.id,t.id,"out"),point:o.applyToPoint(oS(t)),cursor:"grab"}),n}))}}getSelectionOverlayInfo(e,t){const n=t.editor.getShapeEditingSession();return n&&n.shapeId===e.id?{usesSelectionPathOverlay:!0,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:SS(e,t.editor.computeShapeLocalToPageTransform(e)),pathStyle:null,bindingSegments:[]}:{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null,bindingSegments:[]}}hitTest(e,t,n){const i=new mI(t.x-e.x,t.y-e.y),o=hS(e);return!O(e.props.fill)&&((e,t,n)=>{let i=0,o=0;for(const r of e)if(r.closed&&!(r.points.length<3))for(let e=0;e<r.points.length;e+=1){const n=r.points[e],s=r.points[(e+1)%r.points.length];n&&s&&(n.y<=t.y&&s.y>t.y||n.y>t.y&&s.y<=t.y)&&n.x+(t.y-n.y)/(s.y-n.y)*(s.x-n.x)>t.x&&(o+=1,i+=s.y>n.y?1:-1)}return"evenodd"===n?o%2==1:0!==i})(o.flattenedSubpaths,i,e.props.fillRule)||((e,t,n)=>{const i=n*n;for(const o of e)for(let e=1;e<o.points.length;e+=1){const n=o.points[e-1],r=o.points[e];if(n&&r&&bS(t,n,r)<=i)return!0}return!1})(o.flattenedSubpaths,i,e.props.strokeWidth/2+6)}hitTestLineSegment(e,t){const n=new mI(t.positionedStart.x-e.x,t.positionedStart.y-e.y),i=new mI(t.positionedEnd.x-e.x,t.positionedEnd.y-e.y),o=t.positionedMargin+e.props.strokeWidth/2;return hS(e).flattenedSubpaths.some(e=>((e,t,n,i)=>{const o=i*i;for(let r=1;r<n.length;r+=1){const i=n[r-1],s=n[r];if(i&&s&&(Oy(i,e,t)<=o||Oy(s,e,t)<=o||Oy(e,i,s)<=o||Oy(t,i,s)<=o))return!0}return!1})(n,i,e.points,o))}isWrappedByBrush(e,t){const n=t.pageOutlineVertices;return 0===n.length?!!t.pageBounds&&t.brushBounds.containsBox(t.pageBounds):n.every(e=>t.brushBounds.containsPoint(e))}canSelectByBrush(e,t){return t.isWrapping?this.isWrappedByBrush(e,t):t.pageBounds?.intersects(t.brushBounds)??!1}onEditEnd(e){if(e.props.subpaths.every(e=>e.nodes.length<2))return{deleteShapeIds:[e.id]}}}],shapeSvgExporters:[new class{type="path";toSvg(e,t){const n=hS(e);return n.path?{tag:"path",attrs:{d:n.path,fill:O(e.props.fill)?"none":t.resolveColor(e.props.fill),"fill-rule":e.props.fillRule,"clip-rule":e.props.fillRule,stroke:t.resolveColor(e.props.stroke),"stroke-width":e.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}:null}}],interactionHandlers:[{id:"land.path.interactions",editorEvent:{handleEvent(e,t){if("pointer"===t.type&&"pointer_move"===t.name&&wE.get(e)?.pointerId===t.pointerId)return yy(e),vy(e,t),"handled";if("pointer"===t.type&&"pointer_up"===t.name&&(PE.delete(e),yy(e),wE.get(e)?.pointerId===t.pointerId))return((e,t)=>{const n=wE.get(e);n&&(n.isActive?vy(e,t):xy(t)||_S(e),wE.delete(e),e.setBrushBox(null))})(e,t),"handled";if("pointer"===t.type&&"pointer_cancel"===t.name&&(PE.delete(e),yy(e),wE.get(e)?.pointerId===t.pointerId))return wy(e),"handled";if("click"===t.type&&"double_click"===t.name&&"up"===t.phase&&!t.shiftKey&&!t.altKey&&!t.accelKey){by(e);const n=e.hitTestShape(t.pagePoint);if(Ym(n))return fy(e),e.startEditingShape({shapeId:n.id,markId:xE,entryMode:"focusEnd"},"user"),"handled"}if("cancel"===t.type)return PE.delete(e),wE.has(e)?(wy(e),"handled"):"escape"===t.reason&&e.isActiveToolInInitialState()&&my(e)&&e.completeEditing("user")?"handled":(by(e),"continue");if("keyboard"===t.type&&"key_down"===t.name)return Ey(e,t)?"handled":"continue";if("pointer"===t.type&&"pointer_move"===t.name)return"mouse"!==t.pointerType||0!==t.buttons||t.altKey?yy(e):((e,t)=>{const n=my(e);if(!n||"select"!==e.getActiveToolId()||!e.isActiveToolInInitialState())return void yy(e);if("custom"===e.hitTestSelectionHandle(t.pagePoint)?.kind)return void yy(e);const i=Sy(e,n,t.pagePoint),o=xS(n.props.subpaths,i,7/e.getCurrentCamera().z);if(!o)return void yy(e);const r=e.computeShapeLocalToPageTransform(n);_m(e,{shapeId:n.id,subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,pagePoint:r.applyToPoint(o.point)})})(e,t),"continue";if("pointer"===t.type&&"pointer_down"===t.name&&0===t.button&&t.altKey){yy(e);const n=my(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind&&"path.node"===i.type){const t=Wm(i.type,i.id);if("path.node"===t?.type){const i=WS(e);return Ty(e,n,i?.selection.shapeId===n.id&&XS(i.selection,t.subpathId,t.nodeId)?i.selection.nodes:[{subpathId:t.subpathId,nodeId:t.nodeId}]),"handled"}}}if("pointer"===t.type&&"pointer_down"===t.name&&0===t.button&&!t.altKey){yy(e);const n=my(e);if(!n)return"continue";const i=e.hitTestSelectionHandle(t.pagePoint);if("custom"===i?.kind)return Wm(i.type,i.id)||_S(e),"continue";const o=Sy(e,n,t.pagePoint),r=xS(n.props.subpaths,o,7/e.getCurrentCamera().z);if(!r)return((e,t,n)=>{const i=WS(e);wE.set(e,{shapeId:t.id,pointerId:n.pointerId,originPagePoint:n.pagePoint.clone(),originScreenPoint:n.screenPoint.clone(),previousEntries:i?.selection.shapeId===t.id?i.selection.nodes.map(e=>({...e})):[],previousPrimary:i?.selection.shapeId===t.id?{...i.selection.primary}:null,isActive:!1})})(e,n,t),"handled";const s=`insert-node:${vE+=1}`;return e.operations.run({kind:"path.insert-node",label:"shape.edit",source:"user",history:"record"},()=>{const t=((e,t,n)=>e.map(e=>{if(e.id!==t.subpathId)return eS(e);const i=e.nodes.findIndex(e=>e.id===t.startNodeId);if(i<0)return eS(e);const o=(i+1)%e.nodes.length,r=e.nodes[i],s=e.nodes[o];if(!r||!s||s.id!==t.endNodeId)return eS(e);const a=((e,t,n,i)=>{if(!lS(e,t)){const o=sS(nS(e),nS(t),n);return{start:Jm(e),node:{id:i,x:o.x,y:o.y,kind:"corner"},end:Jm(t)}}const[o,r,s,a]=aS(e,t),l=sS(o,r,n),d=sS(r,s,n),c=sS(s,a,n),u=sS(l,d,n),h=sS(d,c,n),p=sS(u,h,n);return{start:{...Jm(e),out:NS(l.sub(o))},node:{id:i,x:p.x,y:p.y,kind:"smooth",in:NS(u.sub(p)),out:NS(h.sub(p))},end:{...Jm(t),in:NS(c.sub(a))}}})(r,s,t.t,n),l=e.nodes.map(Jm);return l[i]=a.start,l[o]=a.end,l.splice(i+1,0,a.node),{...e,nodes:l}}))(n.props.subpaths,r,s);e.commands.updateShapes([{id:n.id,props:{subpaths:t}}],{source:"user"});const i=e.getShape(n.id);Ym(i)&&KS(e,i,r.subpathId,s)}),uy(e,n.id),PE.set(e,{shapeId:n.id,nodeId:s}),"continue"}return"continue"}},selectionHandle:{createSession(e,{handle:t,shape:n,originPagePoint:i}){if(!Ym(n)||"custom"!==t.kind)return null;const o=Wm(t.type,t.id);if(!o)return null;if(e.getShapeEditingSession()?.shapeId!==n.id)return null;const r=PE.get(e),s="path.node"===o.type&&r?.shapeId===n.id&&r.nodeId===o.nodeId;s&&PE.delete(e);const a=n,l=vS(a.props.subpaths,o.subpathId,o.nodeId),d=Sy(e,a,i),c=WS(e),u=c?.selection.shapeId===n.id?c.selection.nodes.map(e=>({...e})):[],h=c?.selection.shapeId===n.id?{...c.selection.primary}:null,p={subpathId:o.subpathId,nodeId:o.nodeId},g=!!c&&c.selection.shapeId===n.id&&XS(c.selection,o.subpathId,o.nodeId),f="path.node"===o.type&&g,m="path.node"===o.type&&e.inputs.state.get().shiftKey,S=m&&!f?[...c?.selection.shapeId===n.id?c.selection.nodes:[],p]:null;S?YS(e,n,S,p):e.inputs.state.get().shiftKey||g||KS(e,n,o.subpathId,o.nodeId);const y="path.node"===o.type&&(S||f)?S??c.selection.nodes:[p],b=e.computeShapeLocalToPageTransform(a),x=l?b.applyToPoint(nS(l)):i,I=t.point.sub(i),v="path.node"===o.type?y.flatMap(e=>{const t=vS(a.props.subpaths,e.subpathId,e.nodeId);return t?[b.applyToPoint(nS(t))]:[]}):[t.point],w=(v.length>0?v:[t.point]).map(e=>e.sub(i)),P=((e,t,n)=>{const i=new Set(n.map(Iy)),o=e.computeShapeLocalToPageTransform(t);return{points:t.props.subpaths.flatMap(e=>e.nodes.flatMap(n=>i.has(Iy({subpathId:e.id,nodeId:n.id}))?[]:[{id:`${t.id}:${e.id}:${n.id}`,nodeId:t.id,point:o.applyToPoint(nS(n)),kind:"custom"}])),outlines:[]}})(e,a,"path.node"===o.type?y:[]);return{shapeId:n.id,historyMark:"path.handle",onClick:m&&f?({editor:e})=>{const t=e.getShape(n.id);Ym(t)&&((e,t,n,i)=>{const o=HS(e);if(!o||o.shapeId!==t.id)return void KS(e,t,n,i);const r={subpathId:n,nodeId:i},s=XS(o,n,i),a=s?o.nodes.filter(e=>!VS(e,r)):[...o.nodes,r];YS(e,t,a,s?a.at(-1)??null:r)})(e,t,o.subpathId,o.nodeId)}:void 0,onCancel({editor:e,reason:t}){if("pointer_cancel"!==t&&"escape"!==t)return;const i=e.getShape(n.id);Ym(i)&&e.getShapeEditingSession()?.shapeId===n.id&&(0!==u.length?YS(e,i,u,h):_S(e))},onComplete({editor:e}){s?((e,t)=>{dy(e).replaceCurrent(t)})(e,n.id):uy(e,n.id)},update({editor:e,pagePoint:t,accelKey:r,source:s}){if(!Ym(e.getShape(n.id)))return"stop";const c=e.inputs.state.get(),u=c.shiftKey?"path.node"===o.type?By(i,t):By(x,t.add(I)).sub(I):t,h=py(e)&&!r&&!c.shiftKey&&P.points.length>0,p=h?e.snaps.snapHandle({mode:"align",pagePoint:u,sourcePointOffsets:w,snapshot:P,threshold:10/e.getCurrentCamera().z}):null;h||e.snaps.clearIndicators();const g=p?.snappedPagePoint??u,f=Sy(e,a,"path.node"===o.type?g:g.add(I)),m="path.node"===o.type?l?PS(a.props.subpaths,y,e=>Ry(e,f.sub(d))):tS(a.props.subpaths):wS(a.props.subpaths,o.subpathId,o.nodeId,e=>((e,t,n,i)=>{const o=nS(e),r=i.altKey?{...e,kind:"corner"}:{...e},s=n.sub(o);return"in"===t?(r.in={dx:s.x,dy:s.y},i.altKey||"corner"===e.kind||(r.out=Ay(s,e.out?oS(e).sub(o):null,"symmetric"===e.kind))):(r.out={dx:s.x,dy:s.y},i.altKey||"corner"===e.kind||(r.in=Ay(s,e.in?iS(e).sub(o):null,"symmetric"===e.kind))),r})(e,o.handle,f,{altKey:c.altKey}));if(e.commands.updateShapes([{id:n.id,props:{subpaths:m}}],{source:s}),"path.node"===o.type){const t=e.getShape(n.id);Ym(t)&&YS(e,t,y,{subpathId:o.subpathId,nodeId:o.nodeId})}return"continue"}}}}}],setup(e){const t=function(e){let t=null;const n=Jo("path.editSnap.lifecycle",e.shapeEditingSessionSignal,()=>{const n=e.getShapeEditingSession(),i=n?e.getShape(n.shapeId):null,o=Ym(i)?i.id:null;if(o!==t){if(t){const n=((e,t,n)=>dy(e).hasNetChanges("edit",n))(e,0,t);hy(e,"edit",t),n||e.editing.cancelOperation()}t=o,_S(e),fy(e),o&&cy(e,"edit",o,{onBoundaryUndo:()=>{if(e.getShapeEditingSession()?.shapeId!==o)return!1;const t=e.completeEditing("user");return t&&"select"!==e.getActiveToolId()&&e.commands.setActiveTool("select",{source:"system"}),t}})}});return()=>{n(),t&&hy(e,"edit",t),_S(e),fy(e)}}(e);return e.tools.register("path",e=>new ME(e),{shortcut:"b"}),t}},render:{id:"land.path.react",canvasOverlays:[{id:"land.path.draft-overlay",component:function(){const e=ir(),t=or(e.toolStateSignal),n=or(e.inputs.state),i=or(e.selectedShapesSignal),o=or(e.currentCameraSignal);if("path"!==t.activeToolId)return null;const r=1===i.length?i[0]:null,s=Ym(r)?r:null,a=8/o.z,l=1.5/o.z,d=6/o.z,c=1/o.z,u=n.currentPagePoint;if(!s)return u?Nx(ty,{point:u,size:a,strokeWidth:l,variant:"candidate"}):null;const h=((e,t)=>{const n=GS(t);if(!n.subpathId)return null;const i=IS(mS(t,e.computeShapeLocalToPageTransform(t)),n.subpathId);if(!i)return null;const o=n.previewNodeId?i.nodes.findIndex(e=>e.id===n.previewNodeId):-1,r=o>=0?i.nodes[o]??null:null,s=o>0?i.nodes[o-1]??null:null,a=s&&r?Vm({id:`${i.id}:preview`,closed:!1,nodes:[s,r]}):null;return{closed:i.closed,committedNodes:i.nodes.filter(e=>e.id!==n.previewNodeId),previewNode:r,previewPath:a}})(e,s);if(!h)return u?Nx(ty,{point:u,size:a,strokeWidth:l,variant:"candidate"}):null;const p=h.previewNode?nS(h.previewNode):n.isPointing?null:u,g=p&&!h.committedNodes.some(e=>nS(e).dist2(p)<=.25/(o.z*o.z));
83
- return Hx("g",{"data-ui":"path-draft-overlay",pointerEvents:"none",children:[h.previewPath?Nx("path",{"data-ui":"path-draft-preview-segment",d:h.previewPath,fill:"none",stroke:fE,strokeWidth:Math.max(l,1/o.z),strokeDasharray:`${6/o.z} ${4/o.z}`,strokeLinecap:"round",strokeLinejoin:"round"}):null,g?Nx(ty,{point:p,size:a,strokeWidth:l,variant:"candidate"}):null,h.committedNodes.map((e,t)=>Nx(JS,{node:e,showIn:h.closed||t>0,size:d,strokeWidth:c},e.id)),h.committedNodes.map(e=>Nx(ty,{point:nS(e),size:a,strokeWidth:l,variant:"committed"},e.id))]})},layer:"above-host",order:20},{id:"land.path.edit-insert-preview-overlay",component:function(){const e=ir(),t=or(e.toolStateSignal),n=or(e.shapeEditingSessionSignal),i=or(e.selectedShapesSignal),o=or(e.currentCameraSignal);if(or(e.inputs.state),"select"!==t.activeToolId||!n)return null;const r=1===i.length?i[0]:null;if(!Ym(r)||r.id!==n.shapeId)return null;const s=(e=>{const t=rE.get(e);return t?Km(t):null})(e);if(!s||s.shapeId!==r.id)return null;const a=8/o.z,l=a/2;
84
- return Nx("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:Nx("rect",{"data-ui":"path-edit-insert-preview-control-point",x:s.pagePoint.x-l,y:s.pagePoint.y-l,width:a,height:a,rx:2,ry:2,fill:"rgba(219, 234, 254, 0.72)",stroke:"var(--land-selection, #2563eb)",strokeDasharray:`${3/o.z} ${2/o.z}`,strokeWidth:1.5/o.z})})},layer:"above-host",order:21}],shapeRenderers:[{type:"path",component:function({shape:e,shapeEditingSession:t}){
85
- return Nx(ny,{shape:e,shapeEditingSession:t})},hoverComponent:function({shape:e,strokeWidth:t}){
86
- return Nx(iy,{shape:e,strokeWidth:t})}}],selectionCustomHandleRenderers:[{type:iE,component:function({handle:e,strokeWidth:t}){const n=sy(e.type,e.id);
87
- return Nx("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2,ry:2,fill:n?"rgba(219, 234, 254, 0.98)":"rgba(255,255,255,0.98)",stroke:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.94)",strokeWidth:n?1.5*t:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}},{type:oE,component:function({handle:e,strokeWidth:t}){const n=sy(e.type,e.id);
88
- return Nx("circle",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,cx:e.point.x,cy:e.point.y,r:Math.max(e.bounds.w,e.bounds.h)/2,fill:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.92)",stroke:"rgba(255,255,255,0.96)",strokeWidth:n?1.5*t:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}}]},setup:e=>{e.get(IP).add(Qy("fill"),Qy("stroke"),Qy("strokeWidth"),Jy("fill"),Jy("stroke"),Jy("strokeWidth"),{id:$E,getAvailability(e){if(1!==e.selection.count||"path"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;return Ym(t)&&!t.isLocked?"enabled":"disabled"},run({context:e}){const[t]=e.selection.selectedShapes;Ym(t)&&(_S(e.editor),fy(e.editor),e.editor.startEditingShape({shapeId:t.id,markId:"path.edit",entryMode:"focusEnd"},"user"))}},{id:FE,getAvailability:e=>(e=>{const t=e.editor.getShapeEditingSession();return!!t&&Ym(e.editor.getShape(t.shapeId))})(e)?"enabled":"inapplicable",run({context:e}){e.editor.completeEditing("user")}},{id:UE,getAvailability(e){const t=e.editor.getShapeEditingSession(),n=t?e.editor.getShape(t.shapeId):null;return Ym(n)?n.isLocked?"disabled":"enabled":"inapplicable"},getValue:e=>py(e.editor),run({context:e}){gy(e.editor)}},{id:HE,getAvailability(e){const t=WS(e.editor);return t?t.shape.isLocked?"disabled":"enabled":"inapplicable"},run({context:e}){const t=WS(e.editor);t&&!t.shape.isLocked&&Ty(e.editor,t.shape,t.selection.nodes)}},{id:WE,getAvailability(e){const t=WS(e.editor);return t?!t.shape.isLocked&&t.entries.some(({node:e})=>!e.in&&!e.out)?"enabled":"disabled":"inapplicable"},run({context:e}){const t=WS(e.editor);if(!t||t.shape.isLocked)return;const n=t.entries.flatMap(({ref:e,node:t})=>t.in||t.out?[]:[e]).reduce((e,t)=>kS(e,t.subpathId,t.nodeId),t.shape.props.subpaths);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"});const i=e.editor.getShape(t.shape.id);Ym(i)&&YS(e.editor,i,t.selection.nodes,t.selection.primary),uy(e.editor,t.shape.id)}},{id:_E,getAvailability(e){const t=WS(e.editor);return t?!t.shape.isLocked&&t.entries.some(({node:e})=>!!e.in||!!e.out)?"enabled":"disabled":"inapplicable"},run({context:e}){const t=WS(e.editor);if(!t||t.shape.isLocked)return;const n=t.selection.nodes.reduce((e,t)=>CS(e,t.subpathId,t.nodeId),t.shape.props.subpaths);e.editor.commands.updateShapes([{id:t.shape.id,props:{subpaths:n}}],{source:"user"});const i=e.editor.getShape(t.shape.id);Ym(i)&&YS(e.editor,i,t.selection.nodes,t.selection.primary),uy(e.editor,t.shape.id)}},eb(KE,"merge"),eb(YE,"join"),eb(XE,"separate"),tb("union"),tb("subtract"),tb("intersect"),tb("xor")),e.get(RP).add({id:"path.tool-toolbar",channel:BP.toolSwitcher,order:47,actionIds:[AP],getGroups:e=>[{id:"path.tools",items:[{kind:"button",id:"path.tool.path",actionId:AP,value:"path",label:"Path",shortcut:e.editor.shortcuts.getToolShortcutLabel("path"),icon:"pen-tool",dataUi:"path-tool-button"}]}]},{id:"path.default-style.tool-toolbar",channel:BP.toolOptions,order:48,actionIds:["path.default-fill","path.default-stroke","path.default-strokeWidth"],when:e=>"path"===e.tool.activeToolId,getGroups:()=>Zy({fillActionId:"path.default-fill",strokeActionId:"path.default-stroke",strokeWidthActionId:"path.default-strokeWidth",dataUiPrefix:"path-default"})},{id:"path.selection-toolbar",channel:BP.selectionProperties,order:22,actionIds:[$E,"path.set-fill","path.set-stroke","path.set-strokeWidth",OE,DE,zE,NE],when:e=>"path"===e.selection.commonShapeType,getGroups(e){const t=[{id:"path.edit",items:[{kind:"button",id:"path.edit",actionId:$E,label:"Edit",icon:"square-pen",dataUi:"path-edit-button"}]},...Zy({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",dataUiPrefix:"path"})];return nb(e).length>=2&&t.push({id:"path.boolean",items:[{kind:"button",id:"path.boolean.union",actionId:OE,label:"Union",icon:"group",dataUi:"path-boolean-union-button"},{kind:"button",id:"path.boolean.subtract",actionId:DE,label:"Subtract",icon:"minus",dataUi:"path-boolean-subtract-button"},{kind:"button",id:"path.boolean.intersect",actionId:zE,label:"Intersect",icon:"crop",dataUi:"path-boolean-intersect-button"},{kind:"button",id:"path.boolean.xor",actionId:NE,label:"Exclude",icon:"ungroup",dataUi:"path-boolean-xor-button"}]}),t}},{id:"path.floating-selection-toolbar",channel:BP.selectionQuickActions,order:22,actionIds:[$E,FE,UE,HE,WE,_E,KE,YE,XE,"path.set-fill","path.set-stroke","path.set-strokeWidth",OE,DE,zE,NE],when(e){const t=e.editor.getShapeEditingSession(),n=t?e.editor.getShape(t.shapeId):null;return"path"===e.selection.commonShapeType&&(!t||Ym(n))},getGroups(e){const t=e.editor.getShapeEditingSession(),n=Ym(t?e.editor.getShape(t.shapeId):null);if(WS(e.editor))return[{id:"path.floating-node-edit",presentation:"overflow",items:[{kind:"button",id:"path.floating-node.delete",actionId:HE,label:"Delete node",shortcut:"⌫",icon:"remove-node",dataUi:"floating-path-node-delete-button"}]},{id:"path.floating-node-topology",items:[{kind:"button",id:"path.floating-node.merge",actionId:KE,label:"Merge nodes",shortcut:"Mod+J",icon:"merge-nodes",dataUi:"floating-path-node-merge-button"},{kind:"button",id:"path.floating-node.join",actionId:YE,label:"Join nodes",shortcut:"J",icon:"join-nodes",dataUi:"floating-path-node-join-button"},{kind:"button",id:"path.floating-node.separate",actionId:XE,label:"Separate segment",shortcut:"K",icon:"separate-nodes",dataUi:"floating-path-node-separate-button"}]},{id:"path.floating-node-convert",items:[{kind:"button",id:"path.floating-node.remove-handles",actionId:_E,label:"Corner point",shortcut:"X",icon:"to-corner",dataUi:"floating-path-node-remove-handles-button"},{kind:"button",id:"path.floating-node.make-curve",actionId:WE,label:"Curve point",shortcut:"C",icon:"to-curve",dataUi:"floating-path-node-make-curve-button"}]},Vy(),Gy()];if(n)return[Vy(),Gy()];const i=[{id:"path.floating-edit",items:[{kind:"button",id:"path.floating-edit",actionId:$E,label:"Edit",icon:"square-pen",dataUi:"floating-path-edit-button"}]},...Zy({fillActionId:"path.set-fill",strokeActionId:"path.set-stroke",strokeWidthActionId:"path.set-strokeWidth",dataUiPrefix:"floating-path"})];return nb(e).length>=2&&i.push({id:"path.floating-boolean",presentation:"overflow",items:[{kind:"button",id:"path.floating-boolean.union",actionId:OE,label:"Union",icon:"group",dataUi:"floating-path-boolean-union-button"},{kind:"button",id:"path.floating-boolean.subtract",actionId:DE,label:"Subtract",icon:"minus",dataUi:"floating-path-boolean-subtract-button"},{kind:"button",id:"path.floating-boolean.intersect",actionId:zE,label:"Intersect",icon:"crop",dataUi:"floating-path-boolean-intersect-button"},{kind:"button",id:"path.floating-boolean.xor",actionId:NE,label:"Exclude",icon:"ungroup",dataUi:"floating-path-boolean-xor-button"}]}),i}}),e.get(kP).add({id:"path.context-menu",target:"selection",order:38,actionIds:[$E,OE,DE,zE,NE],when:e=>"path"===e.selection.commonShapeType,getSections(e){const t=[{kind:"command",id:"path.edit",actionId:$E,label:"Edit path",icon:"square-pen",dataUi:"path-context-edit"}];return nb(e).length>=2&&t.push({kind:"command",id:"path.boolean.union",actionId:OE,label:"Union paths",icon:"group",dataUi:"path-context-boolean-union"},{kind:"command",id:"path.boolean.subtract",actionId:DE,label:"Subtract paths",icon:"minus",dataUi:"path-context-boolean-subtract"},{kind:"command",id:"path.boolean.intersect",actionId:zE,label:"Intersect paths",icon:"crop",dataUi:"path-context-boolean-intersect"},{kind:"command",id:"path.boolean.xor",actionId:NE,label:"Exclude paths",icon:"ungroup",dataUi:"path-context-boolean-xor"}),[{id:"path.context",title:"Path",items:t}]}})}},GE=Mx(({editor:e,executeAction:t})=>((({editor:e,executeAction:t})=>{Bx(()=>{const n=n=>{if(e.getShapeEditingSession()||Lr(n.target))return;const i=e.shortcuts.getActionIdForEvent({key:n.key,shiftKey:n.shiftKey,altKey:n.altKey,ctrlKey:n.ctrlKey,metaKey:n.metaKey,accelKey:n.metaKey||n.ctrlKey});i&&t({actionId:i,context:Th({editor:e,selectionState:e.selectionStateSignal.get(),toolState:e.toolStateSignal.get()})})&&(n.preventDefault(),n.stopPropagation())};return window.addEventListener("keydown",n,!0),()=>{window.removeEventListener("keydown",n,!0)}},[e,t])})({editor:e,executeAction:t}),null)),ZE={id:"canvas-kit.keyboard-shortcut-host",setup(e){e.get(wC).addComponents({id:"canvas-kit.keyboard-shortcut-host",order:0,component:GE})}},QE="image-blob:",JE=1,eA=Mx(({editor:e,hostBridge:t,imageAssetService:n,imports:i,flushSnapshot:o})=>{const r=Ux(null),s=Ux(null),a=Ex(t=>Pb({editor:e,file:t,imageObjectUrls:n.objectUrls,flushSnapshot:o}),[e,o,n]);return Bx(()=>{if(t)return t.register({openInsertFilePicker(){r.current?.click()},openReplaceFilePicker(){s.current?.click()}})},[t]),Hx(zx,{children:[Nx("input",{ref:r,type:"file",accept:"image/*",hidden:!0,"data-ui":"insert-image-file-input",onChange:t=>{const n=t.currentTarget.files?.[0]??null;t.currentTarget.value="",n&&i.import({source:"file-picker",files:[n]},{editor:e}).catch(Rb)}}),Nx("input",{ref:s,type:"file",accept:"image/*",hidden:!0,"data-ui":"replace-image-file-input",onChange:e=>{const t=e.currentTarget.files?.[0]??null;e.currentTarget.value="",t&&a(t).catch(Rb)}})]})}),tA=Sl("plugin-image.asset-service"),nA=new WeakSet,iA=ml("canvas-kit.image-host-api"),oA=class{handlers=null;register(e){return this.handlers=e,()=>{this.handlers===e&&(this.handlers=null)}}openInsertFilePicker(){this.handlers?.openInsertFilePicker()}openReplaceFilePicker(){this.handlers?.openReplaceFilePicker()}},rA=Sl("plugin-image.toolbar-host-bridge"),sA={id:"canvas-kit.image",provides:[tA,rA,iA],requires:[LM],setup(e){const t=e.get(vC),n=t?async()=>t.flush():void 0,i=e.get(EP),o=i.add(Lb({flushSnapshot:n})),r=i.add({token:rA,create:()=>new oA});e.get(IP).add(...(({hostBridge:e,imageObjectUrls:t})=>[{id:nM,run(){e.openInsertFilePicker()}},{id:eM,getAvailability(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;return qf(t)&&!t.isLocked?"enabled":"disabled"},run(){e.openReplaceFilePicker()}},{id:tM,getAvailability(e){if(1!==e.selection.count||"image"!==e.selection.singleShapeType)return"inapplicable";const[t]=e.selection.selectedShapes;if(!qf(t)||!t.props.assetId)return"disabled";const n=e.editor.getAsset(t.props.assetId);return Xf(n)&&("remote"===n.props.source.kind||lb(e.editor,t.props.assetId))?"enabled":"disabled"},run({context:e}){kb({editor:e.editor,imageObjectUrls:t})}}])({hostBridge:r,imageObjectUrls:o.objectUrls})),e.get(TP).add({id:"canvas-kit.image-import",order:100,acceptsPreview:e=>e.fileTypes.some(e=>e.startsWith("image/"))||e.dataTypes.some(e=>{const t=e.toLowerCase();return"files"===t||"text/uri-list"===t}),accepts:e=>null!==fb(e.files)||(e.urls?.some(Xb)??!1),async import(e,{editor:t}){const i=fb(e.files),r=e.urls?.find(Xb);return await xb({editor:t,imageObjectUrls:o.objectUrls,source:i?{type:"file",file:i}:{type:"url",url:r},pagePoint:e.pagePoint,flushSnapshot:n})?"handled":"ignored"}}),e.get(IC).beforeCommand(({commandId:e,context:t,editor:n})=>{var i;e===$k.id||e===Fk.id||t&&("image.smudge"===(i=e)||"image.smudge.cancel"===i||"image.smudge.confirm"===i||"image.smudge.brush-size"===i||"image.smudge.brush-color"===i)||(e=>{Ff(e).cancelIfActive()})(t?.editor??n)}),e.get(kC).addResolver(tA),e.get(PC).add({token:iA,create:({editor:e,services:t})=>Nb({editor:e,flushSnapshot:n,services:t})}),e.get(wC).allowPropertiesDuringEditing(e=>Vf(e)||Gf(e)),e.get(kC).addSvgInliners((e=>({async prepare({editor:t,requestedShapeIds:n}){const i=Hb(t,t.getShapeExportTraversalIds(n).flatMap(e=>{const n=t.getShape(e);return n?[n]:[]})),o=new Set;for(const r of i.values()){if("local"!==r.props.source.kind)continue;const{storageKey:t}=r.props.source;if(!o.has(t)&&(o.add(t),0===t.length||!(await e.objectUrls.preload(t))))throw new Error(`Could not load image asset "${r.id}".`)}},async inline({editor:t,exportedShapes:n,svg:i}){let o=i;const r=Hb(t,n),s=new Set;for(const a of r.values()){const t=_b(a,e);if(!t)throw new Error(`Could not resolve image asset "${a.id}".`);if(s.has(t))continue;const n=await Wb(a,t);if(n.href===n.dataUrl){s.add(t);continue}const i=`href="${Kb(n.href)}"`;if(!o.includes(i))throw new Error(`Could not find image asset "${a.id}" in the generated SVG.`);o=o.split(i).join(`href="${n.dataUrl}"`),s.add(t)}return o}}))(o)),e.get(wC).addComponents({id:"canvas-kit.image-import",order:100,component:e=>Nx(Yb,{...e,flushSnapshot:n})})}},aA=[{id:"system.clipboard-main-menu",channel:wP.mainMenu,order:900,actionIds:[EC,AC,BC],getSections:e=>[{id:"system.edit",title:"Edit",order:10,items:[{kind:"command",id:EC,actionId:EC,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(EC),dataUi:"copy-selection-menu-button"},{kind:"command",id:AC,actionId:AC,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(AC),dataUi:"cut-selection-menu-button"},{kind:"command",id:BC,actionId:BC,label:"Paste",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(BC),dataUi:"paste-menu-button"}]}]}],lA=[{id:"system.selection-clipboard-context-menu",target:"selection",order:1e3,actionIds:[EC,AC],getSections:e=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:EC,actionId:EC,label:"Copy",icon:"copy",shortcut:e.editor.shortcuts.getActionShortcutLabel(EC),dataUi:"context-menu-copy-selection-button"},{kind:"command",id:AC,actionId:AC,label:"Cut",icon:"scissors",shortcut:e.editor.shortcuts.getActionShortcutLabel(AC),dataUi:"context-menu-cut-selection-button"}]}]},{id:"system.canvas-clipboard-context-menu",target:"canvas",order:1e3,actionIds:[RC],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:RC,actionId:RC,label:"Paste here",icon:"clipboard-paste",shortcut:e.editor.shortcuts.getActionShortcutLabel(BC),dataUi:"context-menu-paste-here-button"}]}]}],dA=[{actionId:EC,shortcut:{key:"c",accelKey:!0}},{actionId:AC,shortcut:{key:"x",accelKey:!0}},{actionId:BC,shortcut:{key:"v",accelKey:!0}}],cA={id:"canvas-kit.standard.clipboard",requires:[TC],setup(e){e.get(IP).addShortcuts(...dA),e.get(PP).add(...aA),e.get(kP).add(...lA)}},uA=Qk.id,hA=Jk.id,pA=Zk.id,gA=eC.id,fA=tC.id,mA=nC.id,SA=Wk.id,yA=Nk.id,bA=Hk.id,xA=_k.id,IA=iC.id,vA=oC.id,wA=rC.id,PA=["left","horizontal-center","right","top","vertical-center","bottom"],kA=["horizontal","vertical"],CA=[{actionId:hA,shortcut:{key:"d",accelKey:!0}},{actionId:pA,shortcut:{key:"a",accelKey:!0}}],TA=[Jc(Jk,{getAvailability:e=>e.selection.count>0?"enabled":"inapplicable"}),Jc(Zk,{getAvailability:e=>e.editor.getCurrentPageShapeIds().length>0?"enabled":"disabled"}),Jc(eC,{getAvailability:e=>e.selection.canResetRotation?"enabled":"inapplicable"}),Jc(tC,{getAvailability:e=>0===e.selection.count?"inapplicable":e.selection.canFlip?"enabled":"disabled"}),Jc(nC,{getAvailability:e=>0===e.selection.count?"inapplicable":e.selection.canFlip?"enabled":"disabled"}),eu(Wk,{getAvailability:e=>0===e.selection.count||ix(e)?"inapplicable":e.editor.canMoveSelectionInParentOrder("backward")?"enabled":"disabled",toCommandArgs:({context:e})=>[e.selection.selectedShapeIds]}),eu(Nk,{getAvailability:e=>0===e.selection.count||ix(e)?"inapplicable":e.editor.canMoveSelectionInParentOrder("backward")?"enabled":"disabled",toCommandArgs:({context:e})=>[e.selection.selectedShapeIds]}),eu(Hk,{getAvailability:e=>0===e.selection.count||ix(e)?"inapplicable":e.editor.canMoveSelectionInParentOrder("forward")?"enabled":"disabled",toCommandArgs:({context:e})=>[e.selection.selectedShapeIds]}),eu(_k,{getAvailability:e=>0===e.selection.count||ix(e)?"inapplicable":e.editor.canMoveSelectionInParentOrder("forward")?"enabled":"disabled",toCommandArgs:({context:e})=>[e.selection.selectedShapeIds]}),eu(iC,{getAvailability:e=>e.selection.count>0?"enabled":"inapplicable",getValue:e=>(e=>{const[t]=e.selection.selectedShapes;if(!t)return 1;const n=ox(t.opacity);return e.selection.selectedShapes.every(e=>ox(e.opacity)===n)?n:null})(e),toCommandArgs:({value:e})=>"number"==typeof e&&Number.isFinite(e)?[e]:null}),eu(oC,{getAvailability:e=>e.selection.count<=1?"inapplicable":e.editor.canAlignSelection()?"enabled":"disabled",toCommandArgs:({context:e,value:t})=>"string"==typeof t&&(e=>PA.includes(e))(t)&&e.editor.canAlignSelection()?[t]:null}),eu(rC,{getAvailability:e=>e.selection.count<=2?"inapplicable":e.editor.canDistributeSelection()?"enabled":"disabled",toCommandArgs:({context:e,value:t})=>"string"==typeof t&&(e=>kA.includes(e))(t)&&e.editor.canDistributeSelection()?[t]:null}),Jc(Qk,{getAvailability:e=>e.selection.count>0?"enabled":"disabled"})],MA=[{id:"system.selection-main-menu",channel:wP.mainMenu,order:1e3,actionIds:[hA,pA,uA],getSections:e=>[{id:"system.edit",title:"Edit",order:10,items:[{kind:"command",id:hA,actionId:hA,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(hA),dataUi:"duplicate-selection-menu-button"},{kind:"command",id:pA,actionId:pA,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(pA),dataUi:"select-all-menu-button"},{kind:"command",id:uA,actionId:uA,label:"Delete selection",icon:"trash-2",tone:"destructive",dataUi:"delete-selection-menu-button"}]}]}],EA=[{id:"system.selection-context-menu",target:"selection",order:1010,actionIds:[hA,gA,fA,mA,xA,bA,yA,SA],getSections(e){const t=e.selection.count>0&&!ix(e),n=[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"command",id:hA,actionId:hA,label:"Duplicate",icon:"copy-plus",shortcut:e.editor.shortcuts.getActionShortcutLabel(hA),dataUi:"context-menu-duplicate-selection-button"}]}];return(e.selection.canResetRotation||e.selection.count>0)&&n.push({id:"system.selection-transform",title:"Transform",order:20,items:[{kind:"command",id:gA,actionId:gA,label:"Reset rotation",icon:"rotate-ccw",dataUi:"context-menu-reset-rotation-button"},{kind:"command",id:fA,actionId:fA,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"context-menu-flip-horizontal-button"},{kind:"command",id:mA,actionId:mA,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"context-menu-flip-vertical-button"}]}),t&&n.push({id:"system.selection-arrange",title:"Arrange",order:30,items:[{kind:"command",id:xA,actionId:xA,label:"Bring to front",icon:"stack-front",dataUi:"context-menu-bring-to-front-button"},{kind:"command",id:bA,actionId:bA,label:"Bring forward",icon:"stack-forward",dataUi:"context-menu-bring-forward-button"},{kind:"command",id:yA,actionId:yA,label:"Send backward",icon:"stack-backward",dataUi:"context-menu-send-backward-button"},{kind:"command",id:SA,actionId:SA,label:"Send to back",icon:"stack-back",dataUi:"context-menu-send-to-back-button"}]}),n}},{id:"system.selection-delete-context-menu",target:"selection",order:1030,actionIds:[uA],getSections:()=>[{id:"system.selection-edit",title:"Edit",order:10,items:[{kind:"separator",id:"system.selection.delete-leading-separator"},{kind:"command",id:uA,actionId:uA,label:"Delete selection",icon:"trash-2",tone:"destructive",dataUi:"context-menu-delete-selection-button"}]}]},{id:"system.canvas-selection-context-menu",target:"canvas",order:1005,actionIds:[pA],getSections:e=>[{id:"system.canvas-edit",title:"Edit",order:5,items:[{kind:"command",id:pA,actionId:pA,label:"Select all",icon:"scan",shortcut:e.editor.shortcuts.getActionShortcutLabel(pA),dataUi:"context-menu-select-all-button"}]}]}],AA=[{id:"system.selection-toolbar",channel:BP.selectionProperties,order:1e3,actionIds:[vA,wA,gA,fA,mA,SA,yA,bA,xA,IA],getGroups(e){const t=e.selection.count>0&&!ix(e);return[{id:"system.selection-layout",presentation:"primary",items:[{kind:"segmented",id:"system.selection-align",actionId:vA,label:"Align",icon:"layout-align-left",options:[{value:"left",label:"Align left",icon:"layout-align-left",dataUi:"align-selection-left-button"},{value:"horizontal-center",label:"Align horizontal center",icon:"layout-align-center",dataUi:"align-selection-horizontal-center-button"},{value:"right",label:"Align right",icon:"layout-align-right",dataUi:"align-selection-right-button"},{value:"top",label:"Align top",icon:"layout-align-top",dataUi:"align-selection-top-button"},{value:"vertical-center",label:"Align vertical center",icon:"layout-align-middle",dataUi:"align-selection-vertical-center-button"},{value:"bottom",label:"Align bottom",icon:"layout-align-bottom",dataUi:"align-selection-bottom-button"}]},{kind:"segmented",id:"system.selection-distribute",actionId:wA,label:"Distribute",icon:"distribute-horizontal",options:[{value:"horizontal",label:"Distribute horizontally",icon:"distribute-horizontal",dataUi:"distribute-selection-horizontal-button"},{value:"vertical",label:"Distribute vertically",icon:"distribute-vertical",dataUi:"distribute-selection-vertical-button"}]}]},{id:"system.selection-opacity",presentation:"overflow",items:[{kind:"slider",id:"system.selection-opacity",actionId:IA,label:"Opacity",min:0,max:1,step:.01,dataUi:"selection-opacity-slider"}]},{id:"system.selection-actions",presentation:"overflow",items:[...e.selection.canResetRotation?[{kind:"button",id:gA,actionId:gA,label:e.selection.isMixedFrameAndPointHandleSelection?"Reset shape rotation":"Reset rotation",icon:"rotate-ccw",dataUi:"reset-selection-rotation-button"},{kind:"separator",id:"system.selection.reset-delete-separator"}]:[],{kind:"button",id:fA,actionId:fA,label:"Flip horizontal",icon:"flip-horizontal-2",dataUi:"flip-selection-horizontal-button"},{kind:"button",id:mA,actionId:mA,label:"Flip vertical",icon:"flip-vertical-2",dataUi:"flip-selection-vertical-button"},...t?[{kind:"separator",id:"system.selection.flip-order-separator"},{kind:"button",id:SA,actionId:SA,label:"Send to back",icon:"stack-back",dataUi:"send-selection-to-back-button"},{kind:"button",id:yA,actionId:yA,label:"Send backward",icon:"stack-backward",dataUi:"send-selection-backward-button"},{kind:"button",id:bA,actionId:bA,label:"Bring forward",icon:"stack-forward",dataUi:"bring-selection-forward-button"},{kind:"button",id:xA,actionId:xA,label:"Bring to front",icon:"stack-front",dataUi:"bring-selection-to-front-button"}]:[]]}]}},{id:"system.selection-delete-toolbar",channel:BP.selectionProperties,order:1020,actionIds:[uA],getGroups:()=>[{id:"system.selection-delete",presentation:"overflow",items:[{kind:"separator",id:"system.selection.delete-leading-separator"},{kind:"button",id:uA,actionId:uA,label:"Delete selection",icon:"trash-2",dataUi:"delete-selection-toolbar-button"}]}]}],BA={id:"canvas-kit.standard.selection",setup(e){const t=e.get(IP);t.add(...TA),t.addShortcuts(...CA),e.get(PP).add(...MA),e.get(RP).add(...AA),e.get(kP).add(...EA)}},RA=Ak.tool.setActive.id,LA=[{id:"system.canvas-tool-context-menu",target:"canvas",order:1020,actionIds:[RA],getSections:e=>[{id:"system.canvas-tools",title:"Tools",order:20,items:[{kind:"command",id:"system.canvas.select-tool",actionId:RA,value:"select",label:"Select tool",icon:"mouse-pointer-2",shortcut:e.editor.shortcuts.getToolShortcutLabel("select"),dataUi:"context-menu-select-tool-button"},{kind:"command",id:"system.canvas.hand-tool",actionId:RA,value:"hand",label:"Hand tool",icon:"hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),dataUi:"context-menu-hand-tool-button"}]}]}],$A=Ak.tool.setActive.id,FA=Ak.tool.toggleLocked.id,UA=[{id:"system.select-tool-toolbar",channel:BP.toolSwitcher,order:0,actionIds:[$A],getGroups:e=>[{id:"system.select-tool",items:[{kind:"button",id:"system.select-tool",actionId:$A,value:"select",label:"Select",shortcut:e.editor.shortcuts.getToolShortcutLabel("select"),icon:"mouse-pointer-2",dataUi:"select-tool-button"},{kind:"button",id:"system.hand-tool",actionId:$A,value:"hand",label:"Hand",shortcut:e.editor.shortcuts.getToolShortcutLabel("hand"),icon:"hand",dataUi:"hand-tool-button"}]}]},{id:"system.tool-lock-toolbar",channel:BP.toolSwitcher,order:1e3,actionIds:[FA],getGroups:e=>[{id:"system.tool-lock",items:[{kind:"separator",id:"system.tool-lock-separator"},{kind:"button",id:"system.tool-lock",actionId:FA,value:!0,label:e.tool.isToolLocked?"Unlock tool":"Lock tool",icon:"lock",dataUi:"tool-lock-button"}]}]}],OA={id:"canvas-kit.standard.tool-ui",requires:[Ek],setup(e){e.get(RP).add(...UA),e.get(kP).add(...LA)}},DA=pC.id,zA=gC.id,NA=fC.id,HA=[Jc(pC),Jc(gC),Jc(fC)],WA=[{id:"system.view-main-menu",channel:wP.mainMenu,order:2e3,actionIds:[DA,zA,NA],getSections:()=>[{id:"system.view",title:"View",order:20,items:[{kind:"command",id:DA,actionId:DA,label:"Zoom in",icon:"plus",dataUi:"zoom-in-menu-button"},{kind:"command",id:zA,actionId:zA,label:"Zoom out",icon:"minus",dataUi:"zoom-out-menu-button"},{kind:"command",id:NA,actionId:NA,label:"Reset zoom",icon:"rotate-ccw",dataUi:"reset-zoom-menu-button"}]}]}],_A=[{id:"system.canvas-view-context-menu",target:"canvas",order:1010,actionIds:[DA,zA,NA],getSections:()=>[{id:"system.canvas-view",title:"View",order:10,items:[{kind:"command",id:DA,actionId:DA,label:"Zoom in",icon:"plus",dataUi:"context-menu-zoom-in-button"},{kind:"command",id:zA,actionId:zA,label:"Zoom out",icon:"minus",dataUi:"context-menu-zoom-out-button"},{kind:"command",id:NA,actionId:NA,label:"Reset zoom",icon:"rotate-ccw",dataUi:"context-menu-reset-zoom-button"}]}]}],KA={id:"canvas-kit.standard.view",setup(e){e.get(IP).add(...HA),e.get(PP).add(...WA),e.get(kP).add(..._A)}},YA=[["geo",Mk],["draw",CT],["arrow",QP],["eraser",XT],["laser",nE],["path",VE],["image",LM],["text",_P],["frame",dk],["group",JT]],XA=class{actions=new Map;registerAction(e){if(this.actions.has(e.id))throw new Error(`Duplicate canvas action id: ${e.id}.`);this.actions.set(e.id,e)}getAction(e){return this.actions.get(e)??null}},qA=class{contributions;channels=new Map;contributionsByChannel=new Map;stateRevision=0;constructor(e=[]){lx(e.map(({id:e})=>e),"chrome contribution"),this.contributions=[...e];const t=new Map(e.map(({id:e},t)=>[e,t]));for(const n of e){this.channels.set(n.channel.id,n.channel);const e=this.contributionsByChannel.get(n.channel.id)??[];e.push(n),e.sort((e,n)=>(e.order??0)-(n.order??0)||(t.get(e.id)??0)-(t.get(n.id)??0)),this.contributionsByChannel.set(n.channel.id,e)}}getChannels(){return[...this.channels.values()]}getStateRevision(){return this.stateRevision}subscribeToState(e,t){const n=()=>{this.stateRevision+=1,t()},i=this.contributions.flatMap(t=>t.subscribe?[t.subscribe(e,n)]:[]);return this.stateRevision+=1,()=>{for(const e of i)e()}}getSections(e,t){return((e,t)=>{const n=[],i=new Map;for(const o of e){const e=i.get(o.id);if(void 0===e){i.set(o.id,n.length),n.push({...o,items:[...o.items]});continue}const t=n[e];n[e]={...t,title:t.title??o.title,items:[...t.items,...o.items]}}for(const o of n)lx(o.items.map(({id:e})=>e),`chrome item in merged section "${o.id}" of channel "${t}"`);return n.map((e,t)=>({index:t,section:e})).sort((e,t)=>(e.section.order??0)-(t.section.order??0)||e.index-t.index).map(({section:e})=>e)})((this.contributionsByChannel.get(e.id)??[]).filter(e=>e.when?.(t)??!0).flatMap(e=>{const n=[...e.getSections(t)].sort((e,t)=>(e.order??0)-(t.order??0));return((e,t)=>{lx(t.map(({id:e})=>e),`chrome section in contribution "${e.id}"`);const n=new Set(e.actionIds);for(const i of t){lx(i.items.map(({id:e})=>e),`chrome item in section "${i.id}"`);for(const t of i.items)if("command"===t.kind&&!n.has(t.actionId))throw new Error(`Chrome contribution "${e.id}" returned undeclared action "${t.actionId}".`)}})(e,n),n}),e.id)}},jA=class{contributions=new Map;contributionsByTarget=new Map;contributionIndexes=new Map;nextContributionIndex=0;registerContribution(e){if(this.contributions.has(e.id))throw new Error(`Duplicate context-menu contribution id: ${e.id}.`);this.contributions.set(e.id,e),this.contributionIndexes.has(e.id)||(this.contributionIndexes.set(e.id,this.nextContributionIndex),this.nextContributionIndex+=1),((e,t,n)=>{e.push(t),e.sort((e,t)=>cx(e,t,n))})(((e,t)=>{const n=e.get(t);if(n)return n;const i=[];return e.set(t,i),i})(this.contributionsByTarget,e.target),e,this.contributionIndexes)}getSections(e,t){return(e=>{const t=[],n=new Map;for(const i of e){const e=n.get(i.id);if(void 0===e){n.set(i.id,t.length),t.push({...i,items:[...i.items]});continue}const o=t[e];t[e]={...o,title:o.title??i.title,items:[...o.items,...i.items]}}return t})((({anyContributions:e,contributionIndexes:t,target:n,targetContributions:i})=>"any"===n||0===i.length?e:0===e.length?i:[...i,...e].sort((e,n)=>cx(e,n,t)))({anyContributions:this.contributionsByTarget.get("any")??[],contributionIndexes:this.contributionIndexes,target:e,targetContributions:this.contributionsByTarget.get(e)??[]}).filter(e=>e.when?.(t)??!0).flatMap(e=>[...e.getSections(t)].sort((e,t)=>(e.order??0)-(t.order??0))))}},VA=class{contributionsByFormat=new Map;constructor(e=[]){const t=new Set;for(const n of e){if(t.has(n.id))throw new Error(`Duplicate canvas export contribution id: ${n.id}.`);if(t.add(n.id),this.contributionsByFormat.has(n.format))throw new Error(`Duplicate canvas export format: ${n.format}.`);this.contributionsByFormat.set(n.format,n)}}getFormats(){return[...this.contributionsByFormat.values()].map(({format:e,label:t,mimeType:n,fileExtension:i})=>({format:e,label:t,mimeType:n,fileExtension:i}))}hasFormat(e){return this.contributionsByFormat.has(e)}async export(e,t){const n=this.contributionsByFormat.get(e);if(!n)throw new Error(`Canvas export format is unavailable: ${e}.`);const i=await n.export(t);return{format:n.format,label:n.label,mimeType:n.mimeType,fileExtension:n.fileExtension,...i}}},GA=class{contributions;constructor(e=[]){(e=>{const t=new Set;for(const n of e){if(t.has(n))throw new Error(`Duplicate canvas import contribution id: ${n}.`);t.add(n)}})(e.map(({id:e})=>e)),this.contributions=e.map((e,t)=>({contribution:e,index:t})).sort((e,t)=>(e.contribution.order??0)-(t.contribution.order??0)||e.index-t.index).map(({contribution:e})=>e)}getContributions(){return this.contributions}canImport(e){return this.contributions.some(t=>t.accepts(e))}canImportPreview(e){return this.contributions.some(t=>t.acceptsPreview?.(e)??!1)}async import(e,t){for(const n of this.contributions){if(!n.accepts(e))continue;const i=await n.import(e,t);if("handled"===i)return i}return"ignored"}},ZA=class{contributions=new Map;channels=new Map;contributionsByChannel=new Map;contributionIndexes=new Map;nextContributionIndex=0;stateRevision=0;registerContribution(e){if(this.contributions.has(e.id))throw new Error(`Duplicate toolbar contribution id: ${e.id}.`);const t=this.channels.get(e.channel.id);this.contributions.set(e.id,e),this.contributionIndexes.has(e.id)||(this.contributionIndexes.set(e.id,this.nextContributionIndex),this.nextContributionIndex+=1),t||this.channels.set(e.channel.id,e.channel),((e,t,n)=>{e.push(t),e.sort((e,t)=>{const i=(e.order??0)-(t.order??0);return 0!==i?i:(n.get(e.id)??0)-(n.get(t.id)??0)})})(((e,t)=>{const n=e.get(t);if(n)return n;const i=[];return e.set(t,i),i})(this.contributionsByChannel,e.channel.id),e,this.contributionIndexes)}getStateRevision(){return this.stateRevision}subscribeToState(e,t){const n=()=>{this.stateRevision+=1,t()},i=[...this.contributions.values()].flatMap(t=>t.subscribe?[t.subscribe(e,n)]:[]);return this.stateRevision+=1,()=>{for(const e of i)e()}}getGroups(e,t){const n=(this.contributionsByChannel.get(e.id)??[]).filter(e=>e.when?.(t)??!0).flatMap(e=>{const n=[...e.getGroups(t)].sort((e,t)=>(e.order??0)-(t.order??0));return((e,t)=>{const n=new Set(e.actionIds);gx(t.map(({id:e})=>e),`toolbar group in contribution "${e.id}"`);for(const i of t){gx(i.items.map(({id:e})=>e),`toolbar item in group "${i.id}"`);for(const t of i.items)if("actionId"in t&&!n.has(t.actionId))throw new Error(`Toolbar contribution "${e.id}" returned undeclared action "${t.actionId}".`)}})(e,n),n});return gx(n.map(({id:e})=>e),`toolbar group in channel "${e.id}"`),n}getChannels(){return[...this.channels.values()]}},QA=[500,1e3,2e3,5e3],JA=class{editor;adapter;unsubscribeDocument=null;unsubscribeSession=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();isRunning=!1;constructor(e,t){this.editor=e,this.adapter=t}start(){this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.getSessionSnapshot(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.flushWhenHidden),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.flushWhenPageIsLeaving),window.addEventListener("beforeunload",this.flushWhenPageIsLeaving)))}stop(){this.isRunning&&(this.isRunning=!1,this.flush().catch(e=>{console.warn("Could not persist canvas snapshot.",e)}),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.flushWhenHidden),"undefined"!=typeof window&&(window.removeEventListener("pagehide",this.flushWhenPageIsLeaving),window.removeEventListener("beforeunload",this.flushWhenPageIsLeaving)))}flush(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return Promise.all([e,t]).then(()=>{})}savePendingDocument(){const e=this.pendingDocument;return e&&this.adapter.saveDocument?(this.pendingDocument=null,this.queueWrite(()=>this.adapter.saveDocument(e.snapshot)).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t})):this.writeChain}savePendingSession(){const e=this.pendingSession;return e&&this.adapter.saveSession?(this.pendingSession=null,this.queueWrite(()=>this.adapter.saveSession(e.snapshot)).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t})):this.writeChain}queueWrite(e){const t=this.writeChain.then(e);return this.writeChain=t.catch(()=>{}),t}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{console.warn("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{console.warn("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=QA[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=QA[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushWhenHidden=()=>{"hidden"===document.visibilityState&&this.flush().catch(e=>{console.warn("Could not persist canvas snapshot.",e)})};flushWhenPageIsLeaving=()=>{this.flush().catch(e=>{console.warn("Could not persist canvas snapshot.",e)})}},eB=new WeakMap,tB={status:"starting"};export{Ak as CANVAS_KIT_COMMAND_TOKENS,pT as CANVAS_KIT_TOOL_IDS,yu as CanvasKitFloatingToolbarLayer,wx as CanvasKitRoot,Dw as DEFAULT_TEXT_FONT,Sh as FloatingSelectionToolbarPageSpace,zw as HOST_TEXT_FONT,EC as SYSTEM_CLIPBOARD_COPY_ACTION_ID,AC as SYSTEM_CLIPBOARD_CUT_ACTION_ID,BC as SYSTEM_CLIPBOARD_PASTE_ACTION_ID,RC as SYSTEM_CLIPBOARD_PASTE_AT_POINT_ACTION_ID,YP as arrowApiToken,IP as canvasActionsExtension,MP as canvasApisExtension,vP as canvasCapabilitiesExtension,PP as canvasChromeExtension,TC as canvasClipboardRuntimeCapability,MC as canvasClipboardServiceToken,kP as canvasContextMenuExtension,dT as canvasExportApiToken,CP as canvasExportsExtension,xC as canvasImportHostCapability,TP as canvasImportsExtension,PC as canvasKitApisExtension,kC as canvasKitAssetsExtension,iA as canvasKitImageHostApiToken,IC as canvasKitLifecycleExtension,vC as canvasKitPersistenceExtension,wC as canvasKitUiExtension,EP as canvasServicesExtension,Ek as canvasToolActionsCapability,RP as canvasToolbarExtension,wP as chromeChannels,yx as createCanvasKitRuntime,er as createCanvasPluginValueToken,fl as createChromeChannel,E as createCustomShapeColor,Ds as createDefaultTextFontCatalog,Os as createDefaultTextPluginOptions,ml as createProductApiToken,Sl as createProductServiceToken,rx as createStandardCanvasKitPlugins,vh as createTextHostPlugin,wh as createTextLinkHoverPopoverPresenter,M as createThemeShapeColor,yl as createToolbarChannel,tu as defineCanvasPlugin,JP as frameApiToken,bk as geoApiToken,Jr as getPlainTextFromRichText,L as getThemeColorTokenName,B as isCustomShapeColorRef,A as isThemeShapeColorRef,jc as mergeToolbarGroups,U as resolveShapeColor,F as shapeColorToCssColor,LP as textApiToken,BP as toolbarChannels,Ch as useCanvasKitLayerTree,Cx as useCanvasKitRuntime,xu as useCanvasKitWheelCapture};
1
+ function e(e){return e}function t(e){return Object.freeze({id:e,kind:"api"})}function n(e,t){return e.require(t)}function s(e){Nt(()=>{const t=e.current;if(!t)return;const n=t.closest("[data-canvas-kit]"),s=e=>{!e.ctrlKey&&((e,t)=>{let n=e instanceof Element?e:e instanceof Node?e.parentElement:null;for(;n&&t.contains(n);){if(n instanceof HTMLElement&&o(n))return!0;if(n===t)break;n=n.parentElement}return!1})(e.target,t)||bt(e,t,n??void 0)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",s,{passive:!1}),()=>{t.removeEventListener("wheel",s)}},[e])}function o(e){const{overflowY:t}=window.getComputedStyle(e);return e.scrollHeight>e.clientHeight&&("auto"===t||"scroll"===t||"overlay"===t)}function r({children:e}){const[t,n]=Kt(null),s=Ft(e=>{n(e)},[]),o=$t(()=>({registerTarget:s,target:t}),[s,t]);
2
+ return Vt(_t.Provider,{value:o,children:e})}function i(){const{registerTarget:e}=l(),t=Ht(null);return s(t),Vt("div",{ref:Ft(n=>{t.current=n,e(n)},[e]),className:"land-canvas__floating-portal-host","data-ui":"canvas-kit-floating-portal-host"})}function a(){return l().target}function c(){return Bt(_t)?.target??void 0}function l(){const e=Bt(_t);if(!e)throw new Error("CanvasKit floating content must be rendered inside CanvasKitRoot.");return e}function d({canvas:e,children:t}){
3
+ return Vt(Yt.Provider,{value:e,children:t})}function u(){const e=Bt(Yt);if(!e)throw new Error("useCanvasKit must be used inside CanvasKitProvider.");return e}function p(e){return jt(e.subscribe,e.getSnapshot,e.getSnapshot)}function h({contributions:e,getHostElement:t,isEditing:n,onError:s,screenToPage:o}){return Nt(()=>{const r=o=>{if(!y(t(),o)||n()||Rt(o.target))return;const r=w({source:"clipboard",dataTransfer:o.clipboardData});f(e,r)&&(o.preventDefault(),m(e,r).catch(e=>{s(new Error("Canvas clipboard import failed.",{cause:e}))}))},i=s=>{!y(t(),s)||n()||Rt(s.target)||g(e,v(s.dataTransfer))&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy"))},a=r=>{const i=y(t(),r);if(!i||n()||Rt(r.target))return;const a=g(e,v(r.dataTransfer)),c=w({source:"drop",dataTransfer:r.dataTransfer,pagePoint:o(Tt(r,i))});f(e,c)?(r.preventDefault(),m(e,c).catch(e=>{s(new Error("Canvas drop import failed.",{cause:e}))})):a&&(r.preventDefault(),r.dataTransfer&&(r.dataTransfer.dropEffect="none"))};return window.addEventListener("paste",r),window.addEventListener("dragover",i),window.addEventListener("drop",a),()=>{window.removeEventListener("paste",r),window.removeEventListener("dragover",i),window.removeEventListener("drop",a)}},[e,t,n,s,o]),null}function f(e,t){return e.some(e=>e.accepts(t))}function g(e,t){return e.some(e=>e.acceptsPreview?.(t)??!1)}async function m(e,t){for(const n of e)if(n.accepts(t)&&"handled"===await n.import(t))return"handled";return"ignored"}function v(e){return e?{source:"drop",dataTypes:Array.from(e.types),fileTypes:Array.from(e.items).filter(e=>"file"===e.kind).map(e=>e.type).filter(Boolean)}:{source:"drop",dataTypes:[],fileTypes:[]}}function w({dataTransfer:e,pagePoint:t,source:n}){const s=e?.getData("text/plain")||void 0,o=e?.getData("text/html")||void 0,r=[...(e?.getData("text/uri-list")||void 0)?.split(/\r?\n/).filter(e=>e&&!e.startsWith("#"))??[],...s&&x(s.trim())?[s.trim()]:[]];return{source:n,files:b(e),text:s,html:o,...r.length>0?{urls:r}:{},pagePoint:t}}function y(e,t){if(!e)return null;const n=(t.target instanceof Element?t.target:document.activeElement)?.closest(It);return n instanceof HTMLElement&&e.contains(n)?n:null}function b(e){if(!e)return[];const t=Array.from(e.files);return t.length>0?t:Array.from(e.items).flatMap(e=>{if("file"!==e.kind)return[];const t=e.getAsFile();return t?[t]:[]})}function x(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return e.startsWith("data:image/")}}function S({bindings:e,getHostElement:t,onError:n}){const s=u(),o=p(s.viewport.grid.state),{editor:r,importContributions:i,renderBindings:a,setContextMenu:c}=e,l=Ft(()=>s.tools.state.getSnapshot().isEditing,[s]),d=Ft(e=>r.viewport.screenToPage(e),[r]);
4
+ return Wt(zt,{children:[Vt(St.Provider,{value:r,children:Vt(kt,{onContextMenuRequest:c,renderBindings:a,showGrid:o})}),Vt(h,{contributions:i,getHostElement:t,isEditing:l,onError:n,screenToPage:d})]})}function E(e){return void 0===e?[]:Array.isArray(e)?e:[e]}function I(e,t){if(!t||0===Object.keys(t).length)return e;const n=new Set(Object.keys(t)),s=e.map(e=>{if(!Object.prototype.hasOwnProperty.call(t,e.id))return e;n.delete(e.id);const s=t[e.id];return{...e,shortcut:s??void 0}});if(n.size>0)throw new Error(`Unknown CanvasAction shortcut override ids: ${[...n].join(", ")}.`);return s}function C(e,t){if(e.api&&!t?.api)throw new Error(`Canvas plugin "${e.id}" declares API "${e.api.id}" but setup returned no API value.`);if(!e.api&&t?.api)throw new Error(`Canvas plugin "${e.id}" returned an API value without declaring an API token.`)}function P(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function T(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t} id: ${s}.`);n.add(s)}}function k(e){return"provider"===e.kind}function R(e){return"svg-inliner"===e.kind}function A(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t}: ${s}.`);n.add(s)}}function L(){if("undefined"!=typeof window&&"function"==typeof window.requestAnimationFrame&&"function"==typeof window.cancelAnimationFrame)return{requestFrame:e=>window.requestAnimationFrame(e),cancelFrame:e=>window.cancelAnimationFrame(e),prefersReducedMotion:()=>"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function D(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function M(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function O(e,t){return{id:e.id,type:e.type,parentId:e.parentId,pageId:t,index:e.index,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,props:{...e.props},meta:{...e.meta}}}function F(e){const{editor:t}=e,n=t.state.session.get(),s=n.activeToolId;e.assertToolId(s);const o=t.pages.getAll().map(e=>({pageId:e.id,selectedShapeIds:[...t.selection.getIds(e.id)],camera:{...t.viewport.getCamera(e.id)}}));return{currentPageId:n.currentPageId,activeToolId:s,isToolLocked:n.isToolLocked,meta:{...n.meta},pages:o}}function B(e){return{id:e.id,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function N({childIds:e,companionIds:t,context:n,depth:s,editor:o,index:r,pageId:i,shape:a}){return{id:a.id,parentId:a.parentId,pageId:i,type:a.type,companionIds:t,childIds:e,siblingIndex:r,depth:s,canReceiveChildren:o.layers.canReceiveChildren(a.id),isHidden:a.isHidden,isLocked:a.isLocked,isEffectivelyHidden:j(o,n,a.id),isEffectivelyLocked:z(n,a.id)}}function $({bindings:e,editor:t,shapes:n}){const s=new Map(n.map(e=>[e.id,e])),o=t.bindings.getShapeCompanionRootIds(n.map(({id:e})=>e),e),r=new Map,i=new Map,a=new Map;for(const c of n){const e=o.get(c.id)??c.id,t=s.has(e)?e:c.id;if(r.set(c.id,t),t===c.id){const e=a.get(c.parentId);e?e.push(c):a.set(c.parentId,[c])}else{const e=i.get(t);e?e.push(c.id):i.set(t,[c.id])}}return{childShapesByParentId:a,companionIdsByRootId:i,rootIdByShapeId:r,shapeById:s}}function H(e,t){return e.childShapesByParentId.get(t)??[]}function K(e,t){let n=0,s=e.shapeById.get(t);const o=new Set([t]);for(;s?.parentId.startsWith("shape:");){const t=s.parentId;if(o.has(t))break;o.add(t),s=e.shapeById.get(t),n+=1}return n}function j(e,t,n){const s=new Set;let o=t.shapeById.get(n);for(;o;){if(o.isHidden)return!0;if(!o.parentId.startsWith("shape:"))return!1;const n=o.parentId;if(s.has(n))return!1;s.add(n);const r=t.shapeById.get(n);if(!r)return!1;if(!e.shapes.getUtil(r).isChildVisible(r,o,{editor:e}))return!0;o=r}return!1}function z(e,t){const n=new Set;let s=e.shapeById.get(t);for(;s;){if(s.isLocked)return!0;if(!s.parentId.startsWith("shape:"))return!1;const t=s.parentId;if(n.has(t))return!1;n.add(t),s=e.shapeById.get(t)}return!1}function V(e){let t=e;const n=new Set;return{readable:{getSnapshot:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e))},set(e){if(!Object.is(t,e)){t=e;for(const e of[...n])e()}}}}function W({getDependencies:e,getSnapshot:t,name:n,signals:s}){let o,r=[],i=!1;const a=()=>{const n=e();return i&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0})(r,n)||(r=n,o=t(n),i=!0),o};return{getSnapshot:a,subscribe(t){let o=a();return At(n,{get:e,graph:s},()=>{const e=a();Object.is(o,e)||(o=e,t())},{fireImmediately:!1})}}}function q({apis:e,editor:t,exports:n,productId:s,startup:o}){const r=e=>(e?e.map(e=>t.shapes.get(e)).filter(e=>!!e):t.pages.getAll().flatMap(e=>t.shapes.getForPage(e.id))).map(e=>O(e,t.layers.getPageId(e.id))),i=e=>{const[n,...s]=e;return(({bindings:e,editor:t,pageId:n,shapes:s})=>{const o=[],r=$({bindings:e,editor:t,shapes:s}),i=(e,s)=>{H(r,e).forEach((e,a)=>{const c=H(r,e.id).map(e=>e.id);o.push(N({childIds:c,companionIds:r.companionIdsByRootId.get(e.id)??[],context:r,depth:s,editor:t,index:a,pageId:n,shape:e})),i(e.id,s+1)})};return i(n,0),o})({bindings:s.filter(Ct),editor:t,pageId:n,shapes:s.filter(mt)})},a=e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown canvas kit tool "${e}".`)},c={assertToolId:a,editor:t,productId:s},{readable:l,set:d}=V(!1),{readable:u,set:p}=V(null),h=W({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>M(e)}),f=W({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),g=W({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),m=W({signals:t.signals,name:"CanvasKit.selection",getDependencies:()=>[t.state.selectedShapeIds.get(),t.state.selectedShapes.get(),t.state.selectionMetadata.get(),t.state.selectionPageBounds.get(),t.state.selectionAnchorPagePoint.get(),t.render.interaction.selectionTranslationActive.get(),t.state.currentPageId.get()],getSnapshot:([e,t,n,s,o,r,i])=>({...n,ids:[...e],shapes:t.map(e=>O(e,i)),pageBounds:s?{x:s.minX,y:s.minY,width:s.w,height:s.h}:null,anchorPagePoint:o?{x:o.x,y:o.y}:null,isTranslating:r})}),v=W({signals:t.signals,name:"CanvasKit.pages",getDependencies:()=>[t.state.pages.get(),t.state.currentPageId.get(),t.state.currentPageShapeIds.get()],getSnapshot:([e,t,n])=>{const s=e.map(D),o=s.find(e=>e.id===t)??null;return{pages:s,currentPage:o,currentPageId:t,currentPageShapeIds:[...n],canDeleteCurrentPage:s.length>1&&null!==o}}}),w=W({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),y=W({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.pageTransform.get()],getSnapshot:([e,t])=>({camera:{...e},zoom:e.z,pageTransform:t.toCssString()})}),b=W({signals:t.signals,name:"CanvasKit.tools",getDependencies:()=>[t.state.tool.get(),t.state.shapeEditing.get()],getSnapshot:([e,t])=>(a(e.activeToolId),{currentToolId:e.activeToolId,isLocked:e.isToolLocked,isEditing:null!==t.session})}),x=W({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>U(t,t.pages.getCurrentId()),getSnapshot:i});return{canvas:{startup:o,api:t=>e.get(t)??void 0,document:{state:h,readonlyState:f,getSnapshot:()=>(e=>{const{editor:t}=e,n=t.state.tool.get().activeToolId;return e.assertToolId(n),{productId:e.productId,document:M(t.document.getMetadata()),pageId:t.pages.getCurrentId(),activeToolId:n,selectedShapeIds:[...t.selection.getIds()],shapeCount:t.state.currentPageShapeIds.get().length,session:F(e)}})(c),updateMeta:e=>(t.document.updateMetadata({...e},"user"),M(t.document.getMetadata()))},session:{state:g,updateMeta(e){const n=t.session.get();return t.session.update({meta:{...n.meta,...e}},"user"),{meta:{...t.state.session.get().meta}}}},selection:{state:m,select:e=>t.commands.setSelectedShapeIds([...e],{source:"user"}),selectAll:()=>t.selection.selectAll("user"),clear:()=>t.commands.setSelectedShapeIds([],{source:"user"}),delete:()=>t.selection.delete("user"),duplicate:()=>t.selection.duplicate({source:"user"}),resetRotation:()=>t.selection.resetRotation("user"),flip:e=>t.selection.flip(e,"user"),setOpacity:e=>((e,t)=>{if(!Number.isFinite(t))return;const n=Math.min(1,Math.max(0,t)),s=e.state.selectedShapes.get().filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));s.length>0&&e.commands.updateShapes(s,{source:"user"})})(t,e),align:e=>t.selection.align(e,"user"),distribute:e=>t.selection.distribute(e,"user")},pages:{state:v,create:e=>D(t.pages.createAndSelect(e?{name:e.name,meta:e.meta?{...e.meta}:void 0}:void 0,"user")),rename:(e,n)=>t.pages.rename(e,n,"user"),updateMeta:(e,n)=>t.pages.updateMetadata(e,{...n},"user")?.id??null,delete:e=>t.pages.delete(e,"user"),deleteCurrent:()=>t.pages.delete(t.pages.getCurrentId(),"user"),setCurrent:e=>t.pages.select(e,"user")},history:{state:w,clear:()=>t.history.clear(),undo:()=>t.history.undo(),redo:()=>t.history.redo()},viewport:{state:y,grid:{state:l,setVisible:d,toggle:()=>d(!l.getSnapshot())},setCamera:(e,n)=>t.commands.setCamera({pageId:n,camera:e},{source:"user"}),zoomIn:()=>t.viewport.zoomAtCenter(-120,"system"),zoomOut:()=>t.viewport.zoomAtCenter(120,"system"),resetZoom:()=>t.viewport.resetZoom("user"),reset:()=>t.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},tools:{state:b,setCurrent:e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);t.tools.select(e,"user")},setLocked:e=>t.tools.setLocked(e,"user"),toggleLocked:()=>t.tools.toggleLocked("user")},shapes:{get:e=>{const n=t.shapes.get(e);return n?O(n,t.layers.getPageId(n.id)):null},getMany:e=>r(e),getAll:()=>r(),getExportBounds:(e,n)=>{const s=t.shapes.get(e);if(!s)return null;let o;switch(n.space.type){case"shape-local":{const e=t.shapes.get(n.space.shapeId);if(!e)return null;if(o=t.shapes.computeExportBoundsInShapeSpace(s,e),!o)return null;break}case"page":o=t.shapes.computeExportPageBounds(s);break;default:throw new Error(`Unsupported canvas shape export bounds space "${String(n.space)}".`)}return![o.x,o.y,o.w,o.h].every(Number.isFinite)||o.w<0||o.h<0?null:{x:o.x,y:o.y,width:o.w,height:o.h}},update:e=>function(e,t){const n=t.filter(t=>{const n=e.shapes.get(t.id);return!!n&&((e,t)=>{return!(!t.props&&void 0===t.meta)||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(s=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):s))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,s})(n,t)}).map(B);return 0===n.length?[]:(e.commands.updateShapes(n,{source:"user"}),n.map(e=>e.id))}(t,e),updateMeta:(e,n)=>{const s=t.shapes.get(e);return s?(t.commands.updateShapes([{id:e,meta:{...s.meta,...n}}],{source:"user"}),e):null},delete:e=>t.shapes.delete([...e],"user")},assets:{get:e=>{const n=t.assets.get(e);return n?(e=>({id:e.id,type:e.type,props:{...e.props},meta:{...e.meta}}))(n):null},resolveUrl:e=>t.assets.resolveUrl(e)},layers:{state:x,getTree:e=>i(U(t,e??t.pages.getCurrentId())),getNode:e=>(({editor:e,id:t})=>{const n=e.shapes.get(t),s=n?e.layers.getPageId(n.id):null;if(!n||!s)return null;const o=e.shapes.getForPage(s),r=$({bindings:o.flatMap(t=>e.bindings.getForShape(t.id)),editor:e,shapes:o}),i=r.rootIdByShapeId.get(n.id)??n.id,a=r.shapeById.get(i);if(!a)return null;const c=H(r,a.parentId);return N({childIds:H(r,a.id).map(e=>e.id),companionIds:r.companionIdsByRootId.get(a.id)??[],context:r,depth:K(r,a.id),editor:e,index:c.findIndex(e=>e.id===a.id),pageId:s,shape:a})})({editor:t,id:e}),getActionState:e=>({canGroup:t.layers.canGroup(e),canUngroup:t.layers.canUngroup(e),canMoveBackward:t.layers.canMove(e,"backward"),canMoveForward:t.layers.canMove(e,"forward")}),centerOn:(e,n)=>t.viewport.centerOnShape(e,{...n,source:"user"}),setHidden:(e,n)=>t.shapes.setHidden([...e],n,"user"),setLocked:(e,n)=>t.shapes.setLocked([...e],n,"user"),group:e=>t.layers.group([...e],"user")?.id??null,ungroup:e=>t.layers.ungroup([...e],"user"),move:(e,n)=>t.layers.move([...e],n,"user"),moveToEdge:(e,n)=>t.layers.moveToEdge([...e],n,"user"),moveToPlacement:(e,n)=>{const s=t.layers.moveToPlacement({ids:[...e],parentId:n.parentId,beforeId:n.beforeId??void 0},"user");return s.ok?{ok:!0,ids:s.movedIds}:{ok:!1,reason:"locked"===s.reason?"locked":"cycle"===s.reason?"cycle":"invalidBeforeId"===s.reason?"invalid-before":"unsupportedTransform"===s.reason?"mixed-parent":"notFound"===s.reason&&0===e.length?"empty-selection":"invalid-parent"}}},contextMenu:{state:u,dismiss:()=>p(null)},exports:{state:{getSnapshot:()=>n.getStatus(),subscribe:e=>n.subscribe(e)},getFormats:()=>n.getFormats(),getStatus:()=>n.getStatus(),export:(e,t)=>n.export(e,t)}},host:{setContextMenu:p}}}function U(e,t){const n=e.shapes.getForPage(t),s=new Map;for(const o of n)for(const t of e.bindings.getForShape(o.id))s.set(t.id,t);return[t,...n,...s.values()]}function _(){const e=new Map;let t=!1;return{register({token:n,api:s,pluginId:o}){if(t)throw new Error("Canvas API registry is disposed.");if(e.has(n.id))throw new Error(`Duplicate canvas API token: ${n.id}.`);e.set(n.id,{token:n,api:s,pluginId:o})},view:t=>(({allowedTokenIds:t,ownerLabel:n})=>{const s=s=>{if(t&&!t.has(s.id))throw new Error(`${n} attempted to read undeclared canvas API "${s.id}".`);const o=e.get(s.id);return o?o.api:null};return{get:s,require(e){const t=s(e);if(null===t)throw new Error(`${n} requires unavailable canvas API "${e.id}".`);return t}}})(t),clear(){t||(t=!0,e.clear())}}}async function Y(e,t={}){(e=>{if(!e||!Array.isArray(e.plugins))throw new Error("CanvasKit requires an explicit plugins array.");if(!("persistence"in e))throw new Error("CanvasKit requires an explicit persistence option.")})(e),t.signal?.throwIfAborted();const{canvasPlugins:n,editorPlugins:s,renderPlugins:o}=function(e){const t=(e=>e.flat(1/0))(e);A(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],s=new Set,o=new Set,r=e=>{if(!o.has(e.id)){if(s.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);s.add(e.id);for(const n of e.requires??[]){const s=t.get(n.id);if(!s)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);r(s)}s.delete(e.id),o.add(e.id),n.push(e)}};for(const i of e)r(i);return n})(t),s=n.flatMap(e=>e.editor?[e.editor]:[]),o=n.flatMap(e=>e.render?[e.render]:[]);return A(s.map(({id:e})=>e),"editor plugin id"),A(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=Et(o),i=new Jt,a=t.signal?AbortSignal.any([i.signal,t.signal]):i.signal;try{const o=e.id??"canvas-kit",c=e.persistence;c&&i.own(c,e=>e.dispose?.());let l=[];const d=i.own((e=>{const t=wt({cameraAnimationScheduler:L(),documentMeta:e.documentMeta,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new Mt(e)),t.tools.register("hand",e=>new xt(e)),t.tools.syncLockedState(t.state.tool.get().isToolLocked),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({documentMeta:e.documentMeta?{...e.documentMeta}:void 0,onUnhandledError:e.onError,editorPlugins:s,resolveAssetUrl(e){for(const t of l){const n=t.resolve(e);if(n)return n}return null}}),e=>e.dispose()),u=c?i.own(new Zt(d,c,{flushEvents:t.persistenceFlushEvents,onError:e.onError}),{shutdown:e=>e.shutdown(),rollback:e=>e.rollback()}):null,{apis:p,contributions:{assetResolvers:h,exports:f,imports:g}}=function({apis:e,canvasPlugins:t,editor:n,owner:s,productId:o}){const r=new Map(t.map(e=>[e.id,e])),i=[];for(const c of t){s.signal.throwIfAborted();const t=c.setup?.({editor:n,productId:o,apis:e.view({allowedTokenIds:P(c,r),ownerLabel:`Canvas plugin "${c.id}" setup`}),tasks:s.tasks});t&&(s.own(t,e=>e.dispose?.()),i.push({plugin:c,instance:t})),C(c,t),c.api&&t?.api&&e.register({token:c.api,api:t.api,pluginId:c.id})}const a=(e=>{const t=e.flatMap(({instance:e})=>e.imports??[]),n=e.flatMap(({instance:e})=>e.exports??[]),s=e.flatMap(({instance:e})=>e.assetResolvers??[]);return T(t.map(({id:e})=>e),"import contribution"),T(n.map(({id:e})=>e),"export contribution"),T(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),T(s.map(({id:e})=>e),"asset resolver contribution"),Object.freeze({imports:Object.freeze((o=t,o.map((e,t)=>({value:e,index:t})).sort((e,t)=>(e.value.order??0)-(t.value.order??0)||e.index-t.index).map(({value:e})=>e))),exports:Object.freeze([...n]),assetResolvers:Object.freeze([...s])});var o})(i);return{apis:e.view({ownerLabel:"CanvasKit"}),contributions:a}}({apis:i.own(_(),e=>e.clear()),canvasPlugins:n,editor:d,owner:i,productId:o});l=h;const m=await(async({assetResolvers:e,editor:t,initialDocumentSnapshot:n,persistenceAdapter:s,persistenceCoordinator:o,signal:r})=>{const i=t.snapshots.getSession(),a=[],c=s?.load?await s.load({signal:r}):{documentSnapshot:null,sessionSnapshot:null};let l;r.throwIfAborted(),null!==c.documentSnapshot?(t.snapshots.loadDocument(c.documentSnapshot,{source:"system"}),l="restored"):void 0!==n?(t.snapshots.loadDocument(n,{source:"system"}),l="initial"):l="empty",r.throwIfAborted();let d=!1;if("restored"===l&&null!==c.sessionSnapshot)try{t.snapshots.loadSession(c.sessionSnapshot,{source:"system"}),d=!0}catch(u){r.throwIfAborted(),a.push(u),t.snapshots.loadSession(i,{source:"system"})}t.history.clear();for(const p of e){r.throwIfAborted();try{await(p.preload?.({editor:t,signal:r})),"restored"===l&&await(p.cleanupAfterRestore?.({editor:t,signal:r}))}catch(u){r.throwIfAborted(),a.push(u)}}return r.throwIfAborted(),o?.start(),{documentSource:l,sessionRestored:d,warnings:[...a]}})({assetResolvers:l,editor:d,initialDocumentSnapshot:e.initialDocumentSnapshot,persistenceAdapter:c,persistenceCoordinator:u,signal:a});!0===e.readonly&&d.document.setReadonly(!0),i.signal.throwIfAborted();const v=i.own(function({editor:e,contributions:t,tasks:n}){const s=t.filter(k),o=t.filter(R),r=new Map;for(const d of s){if(r.has(d.format))throw new Error(`Duplicate canvas export format: ${d.format}.`);r.set(d.format,d)}let i=Xt,a=!1;const c=new Set,l=e=>{if(!Object.is(i,e)){i=e;for(const e of[...c])e()}};return{getFormats:()=>s.map(({format:e,label:t,mimeType:n,fileExtension:s})=>({format:e,label:t,mimeType:n,fileExtension:s})),getStatus:()=>i,subscribe:e=>(c.add(e),()=>c.delete(e)),export:async(t,s)=>n.run(async n=>{if(a)throw new Error("Canvas export controller is disposed.");if("exporting"===i.state)throw new Error("An export is already in progress.");const c=r.get(t);if(!c)throw new Error(`Canvas export format is unavailable: ${t}.`);l({state:"exporting",format:t});try{const t=((e,t)=>{if("selection"===t.scope)return e.selection.getIds();if("page"===t.scope)return e.state.currentPageShapeIds.get();if(!t.shapeIds)throw new Error("Canvas export requires a scope or shapeIds.");return t.shapeIds})(e,s);for(const s of o)n.throwIfAborted(),await(s.prepare?.({editor:e,requestedShapeIds:t,signal:n}));n.throwIfAborted();const r=await c.export({editor:e,shapeIds:t,options:s.options},{signal:n,async inlineSvg(e){let t=e.svg;for(const s of o)n.throwIfAborted(),t=await s.inline({editor:e.editor,exportedShapes:e.exportedShapes,exportedShapeIds:e.exportedShapeIds,svg:t,signal:n});return n.throwIfAborted(),t}});return n.throwIfAborted(),{format:c.format,label:c.label,mimeType:c.mimeType,fileExtension:c.fileExtension,...r}}finally{l(Xt)}}),dispose(){a||(a=!0,l(Xt),c.clear())}}}({editor:d,contributions:f,tasks:i.tasks}),e=>e.dispose());i.signal.throwIfAborted();const{canvas:w,host:y}=q({apis:p,editor:d,exports:v,productId:o,startup:m});return{canvas:w,dispose:i.publish({beforeShutdown:()=>d.closeWrites()}),productId:o,render:{editor:d,importContributions:g,onError:e.onError,renderBindings:r,setContextMenu:y.setContextMenu}}}catch(c){return i.rollback(c)}}function X(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function J({actions:e=en,chromeRenderer:t,onCanvasChange:n,options:s}){const o=(e=>{const[t,n]=Kt(null);return Nt(()=>{let t=!0,s=null;const o=new AbortController,r=e.onError??X;return n({options:e,state:Qt}),Y(e,{persistenceFlushEvents:{subscribe(e){const t=()=>{"hidden"===document.visibilityState&&e()},n=()=>e();return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",n),window.addEventListener("beforeunload",n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",n),window.removeEventListener("beforeunload",n)}}},signal:o.signal}).then(o=>{s=o,t?n({options:e,state:{status:"ready",runtime:o}}):o.dispose().catch(r)},s=>{t&&n({options:e,state:{status:"error",error:s}})}),()=>{t=!1,o.abort(new DOMException("CanvasKitRoot was cleaned up.","AbortError")),s?.dispose().catch(r)}},[e]),t?.options===e?t.state:Qt})(s);if("error"===o.status)throw o.error;return"ready"!==o.status?null:Vt(G,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function G({actions:e=en,chromeRenderer:t,onCanvasChange:n,runtime:s}){const o=Ht(n),a=Ht(null),c=Ft(()=>a.current,[]),{canvas:l,productId:u,render:p}=s,h=p.onError??X,f=Ft(()=>l.tools.state.getSnapshot().isEditing,[l]);return o.current=n,Nt(()=>(o.current?.(l),()=>o.current?.(null)),[l]),function({actions:e,canvas:t,isEditing:n,onError:s}){Nt(()=>{(e=>{const t=new Set;for(const n of e){if(t.has(n.id))throw new Error(`Duplicate CanvasAction id "${n.id}".`);t.add(n.id)}})(e);const o=o=>{if(n()||Rt(o.target))return;const r={key:o.key,shiftKey:o.shiftKey,altKey:o.altKey,ctrlKey:o.ctrlKey,metaKey:o.metaKey,accelKey:o.metaKey||o.ctrlKey},i=e.find(e=>void 0!==e.shortcut&&E(e.shortcut).some(e=>Dt(e,r)));if(!i)return;if(o.preventDefault(),o.stopPropagation(),!i.isEnabled(t))return;let a;try{a=i.run(t)}catch(c){return void s(new Error(`Canvas action "${i.id}" failed.`,{cause:c}))}a instanceof Promise&&a.catch(e=>{s(new Error(`Canvas action "${i.id}" failed.`,{cause:e}))})};return window.addEventListener("keydown",o,!0),()=>window.removeEventListener("keydown",o,!0)},[e,t,n,s])}({actions:e,canvas:l,isEditing:f,onError:h}),Vt(d,{canvas:l,children:Vt(r,{children:Vt("div",{ref:a,"data-ui":"app-shell","data-canvas-kit":u,className:"land-canvas-kit__shell",children:Wt("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
5
+ Vt(S,{bindings:p,getHostElement:c,onError:h}),t?.(l)??null,
6
+ Vt(i,{})]})})})})}function Z(){return"undefined"==typeof indexedDB?Promise.resolve(null):(nn||(nn=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(tn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),nn=null}),e(t)}),n.addEventListener("error",()=>{nn=null,t(n.error)})})),nn)}function Q(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await te(e);return t.throwIfAborted(),n},saveDocument:t=>ee({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>ee({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function ee(e,t){const n=[];null!==e.documentSnapshot&&n.push([oe(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([re(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Z();n&&await new Promise((s,o)=>{const r=n.transaction(e,"readwrite"),i=r.objectStore(e);r.addEventListener("complete",()=>s()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error));for(const[e,n]of t)i.put(n,e)})})(tn,n)}async function te(e={}){const[t,n]=await ae([oe(e),re(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function ne(){return ie(sn)}async function se(){return ie(on)}function oe(e){return e.storageNamespace?`${e.storageNamespace}.document`:sn}function re(e){return e.storageNamespace?`${e.storageNamespace}.session`:on}async function ie(e){const[t]=await ae([e]);return t??null}async function ae(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Z();return n?new Promise((s,o)=>{const r=n.transaction(e,"readonly"),i=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>s(a)),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),t.forEach((e,t)=>{const n=i.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>o(n.error))})}):null})("snapshots",e)??e.map(()=>null)).map(ce)}function ce(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function le({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?qt(Vt("div",{"data-ui":n,className:de("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function de(...e){return e.filter(Boolean).join(" ")}function ue(e,t,n){return an(e,rn(t,n))}function pe(e,t){return"function"==typeof e?e(t):e}function he(e){return e.split("-")[0]}function fe(e){return e.split("-")[1]}function ge(e){return"x"===e?"y":"x"}function me(e){return"y"===e?"height":"width"}function ve(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function we(e){return ge(ve(e))}function ye(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function be(e){const t=he(e);return un[t]+e.slice(t.length)}function xe(e){const{x:t,y:n,width:s,height:o}=e;return{width:s,height:o,top:n,left:t,right:t+s,bottom:n+o,x:t,y:n}}function Se(e,t,n){let{reference:s,floating:o}=e;const r=ve(t),i=we(t),a=me(i),c=he(t),l="y"===r,d=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[a]/2-o[a]/2;let h;switch(c){case"top":h={x:d,y:s.y-o.height};break;case"bottom":h={x:d,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(fe(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Ee(e,t){var n;void 0===t&&(t={});const{x:s,y:o,platform:r,rects:i,elements:a,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=pe(t,e),f=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(h),g=a[p?"floating"===u?"reference":"floating":u],m=xe(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(g)))||n?g:g.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),v="floating"===u?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,w=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),y=await(null==r.isElement?void 0:r.isElement(w))&&await(null==r.getScale?void 0:r.getScale(w))||{x:1,y:1},b=xe(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:w,strategy:c}):v);return{top:(m.top-b.top+f.top)/y.y,bottom:(b.bottom-m.bottom+f.bottom)/y.y,left:(m.left-b.left+f.left)/y.x,right:(b.right-m.right+f.right)/y.x}}function Ie(){return"undefined"!=typeof window}function Ce(e){return ke(e)?(e.nodeName||"").toLowerCase():"#document"}function Pe(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Te(e){var t;return null==(t=(ke(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function ke(e){return!!Ie()&&(e instanceof Node||e instanceof Pe(e).Node)}function Re(e){return!!Ie()&&(e instanceof Element||e instanceof Pe(e).Element)}function Ae(e){return!!Ie()&&(e instanceof HTMLElement||e instanceof Pe(e).HTMLElement)}function Le(e){return!(!Ie()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Pe(e).ShadowRoot)}function De(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=$e(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function Me(e){return/^(table|td|th)$/.test(Ce(e))}function Oe(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Fe(e){const t=Re(e)?$e(e):e;return yn(t.transform)||yn(t.translate)||yn(t.scale)||yn(t.rotate)||yn(t.perspective)||!Be()&&(yn(t.backdropFilter)||yn(t.filter))||vn.test(t.willChange||"")||wn.test(t.contain||"")}function Be(){return null==Ut&&(Ut="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ut}function Ne(e){return/^(html|body|#document)$/.test(Ce(e))}function $e(e){return Pe(e).getComputedStyle(e)}function He(e){return Re(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ke(e){if("html"===Ce(e))return e;const t=e.assignedSlot||e.parentNode||Le(e)&&e.host||Te(e);return Le(t)?t.host:t}function je(e){const t=Ke(e);return Ne(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ae(t)&&De(t)?t:je(t)}function ze(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=je(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Pe(o);if(r){const e=Ve(i);return t.concat(i,i.visualViewport||[],De(o)?o:[],e&&n?ze(e):[])}return t.concat(o,ze(o,[],n))}function Ve(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function We(e){const t=$e(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Ae(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=cn(n)!==r||cn(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function qe(e){return Re(e)?e:e.contextElement}function Ue(e){const t=qe(e);if(!Ae(t))return dn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=We(t);let i=(r?cn(n.width):n.width)/s,a=(r?cn(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function _e(e){const t=Pe(e);return Be()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:bn}function Ye(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=qe(e);let i=dn(1);t&&(s?Re(s)&&(i=Ue(s)):i=Ue(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Pe(e))&&t))(r,n,s)?_e(r):dn(0);let c=(o.left+a.x)/i.x,l=(o.top+a.y)/i.y,d=o.width/i.x,u=o.height/i.y;if(r){const e=Pe(r),t=s&&Re(s)?Pe(s):s;let n=e,o=Ve(n);for(;o&&s&&t!==n;){const e=Ue(o),t=o.getBoundingClientRect(),s=$e(o),r=t.left+(o.clientLeft+parseFloat(s.paddingLeft))*e.x,i=t.top+(o.clientTop+parseFloat(s.paddingTop))*e.y;c*=e.x,l*=e.y,d*=e.x,u*=e.y,c+=r,l+=i,n=Pe(o),o=Ve(n)}}return xe({width:d,height:u,x:c,y:l})}function Xe(e,t){const n=He(e).scrollLeft;return t?t.left+n:Ye(Te(e)).left+n}function Je(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Xe(e,n),y:n.top+t.scrollTop}}function Ge(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Pe(e),s=Te(e),o=n.visualViewport;let r=s.clientWidth,i=s.clientHeight,a=0,c=0;if(o){r=o.width,i=o.height;const e=Be();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Xe(s);if(l<=0){const e=s.ownerDocument,t=e.body,n=getComputedStyle(t),o="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(s.clientWidth-t.clientWidth-o);i<=25&&(r-=i)}else l<=25&&(r+=l);return{width:r,height:i,x:a,y:c}})(e,n);else if("document"===t)s=(e=>{const t=Te(e),n=He(e),s=e.ownerDocument.body,o=an(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=an(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+Xe(e);const a=-n.scrollTop;return"rtl"===$e(s).direction&&(i+=an(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Te(e));else if(Re(t))s=((e,t)=>{const n=Ye(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Ae(e)?Ue(e):dn(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:o*r.x,y:s*r.y}})(t,n);else{const n=_e(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return xe(s)}function Ze(e,t){const n=Ke(e);return!(n===t||!Re(n)||Ne(n))&&("fixed"===$e(n).position||Ze(n,t))}function Qe(e,t){const n=t.get(e);if(n)return n;let s=ze(e,[],!1).filter(e=>Re(e)&&"body"!==Ce(e)),o=null;const r="fixed"===$e(e).position;let i=r?Ke(e):e;for(;Re(i)&&!Ne(i);){const t=$e(i),n=Fe(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||De(i)&&!n&&Ze(e,i))?s=s.filter(e=>e!==i):o=t,i=Ke(i)}return t.set(e,s),s}function et(e,t,n){function s(){l.x=Xe(r)}const o=Ae(t),r=Te(t),i="fixed"===n,a=Ye(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=dn(0);if(o||!o&&!i)if(("body"!==Ce(t)||De(r))&&(c=He(t)),o){const e=Ye(t,!0,i,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&s();i&&!o&&r&&s();const d=!r||o||i?dn(0):Je(r,c);return{x:a.left+c.scrollLeft-l.x-d.x,y:a.top+c.scrollTop-l.y-d.y,width:a.width,height:a.height}}function tt(e){return"static"===$e(e).position}function nt(e,t){if(!Ae(e)||"fixed"===$e(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Te(e)===n&&(n=n.ownerDocument.body),n}function st(e,t){const n=Pe(e);if(Oe(e))return n;if(!Ae(e)){let t=Ke(e);for(;t&&!Ne(t);){if(Re(t)&&!tt(t))return t;t=Ke(t)}return n}let s=nt(e,t);for(;s&&Me(s)&&tt(s);)s=nt(s,t);return s&&Ne(s)&&tt(s)&&!Fe(s)?n:s||(e=>{let t=Ke(e);for(;Ae(t)&&!Ne(t);){if(Fe(t))return t;if(Oe(t))return null;t=Ke(t)}return null})(e)||n}function ot(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function rt({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){Nt(()=>{const c=s(),l=n.current;if(!c||!l)return;let d=!1,u=0;l.style.visibility="hidden";const p=()=>{const e=++u,n=it("--toolbar-floating-shift-padding",8),s=r??it("--toolbar-floating-offset",38),p={top:it("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((e,t,n)=>{const s={platform:xn,...n},o={...s.platform,_c:new Map};return(async(e,t,n)=>{const{placement:s="bottom",strategy:o="absolute",middleware:r=[],platform:i}=n,a=i.detectOverflow?i:{...i,detectOverflow:Ee},c=await(null==i.isRTL?void 0:i.isRTL(t));let l=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=Se(l,s,c),p=s,h=0;const f={};for(let g=0;g<r.length;g++){const n=r[g];if(!n)continue;const{name:m,fn:v}=n,{x:w,y:y,data:b,reset:x}=await v({x:d,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:f,rects:l,platform:a,elements:{reference:e,floating:t}});d=null!=w?w:d,u=null!=y?y:u,f[m]={...f[m],...b},x&&h<50&&(h++,"object"==typeof x&&(x.placement&&(p=x.placement),x.rects&&(l=!0===x.rects?await i.getElementRects({reference:e,floating:t,strategy:o}):x.rects),({x:d,y:u}=Se(l,p,c))),g=-1)}return{x:d,y:u,placement:p,strategy:o,middlewareData:f}})(e,t,{...s,platform:o})})(c,l,{strategy:"fixed",placement:i,middleware:[Sn(s),In({fallbackPlacements:[...t],padding:p}),En({padding:p})]}).then(({placement:t,x:n,y:s})=>{d||e!==u||(l.dataset.placement=t,o?.(t),l.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(s)}px, 0)`,l.style.visibility=a?"visible":"hidden")})},h=function(e,t,n,s){void 0===s&&(s={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=s,l=qe(e),d=o||r?[...l?ze(l):[],...t?ze(t):[]]:[];d.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=l&&a?((e,t)=>{function n(){var e;clearTimeout(s),null==(e=o)||e.disconnect(),o=null}let s,o=null;const r=Te(e);return function i(a,c){function l(t){const n=t[0].intersectionRatio;if(n!==c){if(!m)return i();n?i(!1,n):s=setTimeout(()=>{i(!1,1e-7)},1e3)}1!==n||ot(d,e.getBoundingClientRect())||i(),m=!1}void 0===a&&(a=!1),void 0===c&&(c=1),n();const d=e.getBoundingClientRect(),{left:u,top:p,width:h,height:f}=d;if(a||t(),!h||!f)return;const g={rootMargin:-ln(p)+"px "+-ln(r.clientWidth-(u+h))+"px "+-ln(r.clientHeight-(p+f))+"px "+-ln(u)+"px",threshold:an(0,rn(1,c))||1};let m=!0;try{o=new IntersectionObserver(l,{...g,root:r.ownerDocument})}catch(v){o=new IntersectionObserver(l,g)}o.observe(e)}(!0),n})(l,n):null;let p,h=-1,f=null;i&&(f=new ResizeObserver(e=>{let[s]=e;s&&s.target===l&&f&&t&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),l&&!c&&f.observe(l),t&&f.observe(t));let g=c?Ye(e):null;return c&&function t(){const s=Ye(e);g&&!ot(g,s)&&n(),g=s,p=requestAnimationFrame(t)}(),n(),()=>{var e;d.forEach(e=>{o&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}(c,l,p,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),f=e.subscribe(p);return p(),()=>{d=!0,l.style.visibility="hidden",h(),f()}},[e,t,n,s,o,r,i,a])}function it(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const s=Number.parseFloat(n);return Number.isFinite(s)?n.endsWith("rem")?16*s:s:t}function at(e){const t=a();return t?qt(Vt(ct,{...e}),t):null}function ct({fallbackPlacements:e=Cn,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ht(null),c=Ft(()=>o,[o]);return s(a),rt({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Vt("div",{...r,ref:a})}function lt(){return Bt(kn)}function dt({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",horizontalAlign:o="start",offset:r,visible:i=!0}){const a=u(),c=p(a.selection.state),l=p(a.viewport.state),d=Ht(null),h=Ht(null),[f,g]=Kt("center"===o?"top":"top-start"),m=c.pageBounds??(c.anchorPagePoint?{x:c.anchorPagePoint.x,y:c.anchorPagePoint.y,width:0,height:0}:null),v=i&&null!==m,w=v&&!c.isTranslating,y=Ft(()=>d.current,[m?.height,m?.width,m?.x,m?.y]),b=Ft(()=>d.current?.getBoundingClientRect()??null,[]),x=$t(()=>({placement:f,getContentBounds:b}),[m?.height,m?.width,m?.x,m?.y,b,f,l.pageTransform]);return s(h),rt({viewport:a.viewport.state,fallbackPlacements:"center"===o?Tn:Pn,floatingRef:h,getReferenceElement:y,onPlacementChange:g,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&m?Wt(zt,{children:[Vt("div",{"data-ui":`${n}-page-space`,className:"land-canvas__floating-selection-page-space",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transform:l.pageTransform,transformOrigin:"0 0"},children:Vt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:m.x,top:m.y,width:m.width,height:m.height,pointerEvents:"none"}})}),Vt("div",{ref:h,"data-ui":n,className:ut("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Vt(kn.Provider,{value:x,children:e})})]}):null}function ut(...e){return e.filter(Boolean).join(" ")}import{A as pt,C as ht,D as ft,E as gt,M as mt,O as vt,S as wt,T as yt,a as bt,b as xt,g as St,h as Et,i as It,j as Ct,k as Pt,o as Tt,r as kt,s as Rt,v as At,w as Lt,x as Dt,y as Mt}from"./host-VhUj_Gf6.mjs";import{createContext as Ot,useCallback as Ft,useContext as Bt,useEffect as Nt,useMemo as $t,useRef as Ht,useState as Kt,useSyncExternalStore as jt}from"react";import{Fragment as zt,jsx as Vt,jsxs as Wt}from"react/jsx-runtime";import{createPortal as qt}from"react-dom";var Ut,_t=Ot(null),Yt=Ot(null),Xt={state:"idle"},Jt=class{abortController=new AbortController;activeTasks=new Set;disposers=[];phase="starting";close=null;signal=this.abortController.signal;tasks={run:e=>this.runTask(e)};own(e,t){if("starting"!==this.phase)throw new Error("Cannot register a resource after the Canvas Runtime is published or disposal starts.");return this.disposers.push(n=>"function"==typeof t?t(e):"rollback"===n&&t.rollback?t.rollback(e):t.shutdown(e)),e}publish({beforeShutdown:e}={}){if("starting"!==this.phase)throw new Error(`Only a starting Canvas Runtime can be published; received runtime in "${this.phase}" phase.`);return this.phase="ready",()=>null!==this.close?"shutdown"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot shut down a Canvas Runtime during rollback.")):this.beginClose({mode:"shutdown",beforeShutdown:e})}rollback(e){return null!==this.close?"rollback"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot roll back a Canvas Runtime during shutdown.")):"starting"!==this.phase?Promise.reject(new Error(`Only a starting Canvas Runtime can roll back; received runtime in "${this.phase}" phase.`)):this.beginClose({mode:"rollback",cause:e})}beginClose(e){const t=[],n=Promise.resolve().then(async()=>{const n=[...t,...await this.disposeResources(e.mode)];if(this.phase="disposed","rollback"===e.mode){if(n.length>0)throw new AggregateError([e.cause,...n],"CanvasKit Runtime initialization failed and cleanup reported errors.",{cause:e.cause});throw e.cause}if(n.length>0)throw new AggregateError(n,"Failed to dispose one or more CanvasKit Runtime resources.")});if(this.close={mode:e.mode,result:n},"shutdown"===e.mode)try{e.beforeShutdown?.()}catch(s){t.push(s)}return this.phase="disposing",this.abortController.abort("rollback"===e.mode?e.cause:new DOMException("Canvas runtime is disposing.","AbortError")),n}runTask(e){if("ready"!==this.phase)throw new Error(`Canvas tasks require a ready runtime; received runtime in "${this.phase}" phase.`);this.signal.throwIfAborted();const t=Promise.resolve().then(()=>e(this.signal));return this.activeTasks.add(t),t.finally(()=>this.activeTasks.delete(t)).catch(()=>{}),t}async disposeResources(e){await Promise.allSettled([...this.activeTasks]);const t=[];for(;this.disposers.length>0;){const s=this.disposers.pop();try{await s(e)}catch(n){t.push(n)}}return t}},Gt=[500,1e3,2e3,5e3],Zt=class{editor;adapter;options;unsubscribeDocument=null;unsubscribeSession=null;unsubscribeFlushEvents=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();flushChain=Promise.resolve();isRunning=!1;disposeMode=null;disposePromise=null;constructor(e,t,n={}){this.editor=e,this.adapter=t,this.options=n}start(){if(null!==this.disposeMode)throw new Error("Cannot start disposed canvas persistence.");this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.snapshots.getSession(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),this.unsubscribeFlushEvents=this.options.flushEvents?.subscribe(this.flushForHostLifecycle)??null)}flush(){if(null!==this.disposeMode)return Promise.reject(new Error("Cannot flush disposed canvas persistence."));const e=this.flushChain.then(()=>this.flushNow());return this.flushChain=e.catch(()=>{}),e}shutdown(){return this.dispose("shutdown")}rollback(){return this.dispose("rollback")}dispose(e){return null!==this.disposeMode?this.disposeMode!==e?Promise.reject(new Error(`Canvas persistence disposal already started in "${this.disposeMode}" mode.`)):this.disposePromise:(this.disposeMode=e,this.disposePromise=Promise.resolve().then(()=>"shutdown"===e?this.finishShutdown():this.finishRollback()),this.disposePromise)}async finishShutdown(){this.stopIntake(),await this.flushChain,await this.flushNow()}async finishRollback(){this.stopIntake(),this.discardPendingSnapshots(),await this.flushChain,await this.writeChain,this.discardPendingSnapshots()}stopIntake(){this.isRunning=!1,this.cancelDocumentTimer(),this.cancelSessionTimer(),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeFlushEvents?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,this.unsubscribeFlushEvents=null}async flushNow(){const e=await this.flushPendingSnapshots();try{await(this.adapter.flush?.())}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to flush canvas persistence.")}async flushPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return(await Promise.allSettled([e,t])).flatMap(e=>"rejected"===e.status?[e.reason]:[])}discardPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer(),this.pendingDocument=null,this.pendingSession=null}savePendingDocument(){const e=this.pendingDocument;if(!e||!this.adapter.saveDocument)return this.writeChain;this.pendingDocument=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveDocument(e.snapshot))).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t});return this.writeChain=t.catch(()=>{}),t}savePendingSession(){const e=this.pendingSession;if(!e||!this.adapter.saveSession)return this.writeChain;this.pendingSession=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveSession(e.snapshot))).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t});return this.writeChain=t.catch(()=>{}),t}queueWrite(e){return this.writeChain.then(e)}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{this.reportError("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{this.reportError("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=Gt[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=Gt[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushForHostLifecycle=()=>{this.flush().catch(e=>{this.reportError("Could not persist canvas snapshot.",e)})};reportError(e,t){try{this.options.onError?.(new Error(e,{cause:t}))}catch{}}},Qt={status:"starting"},en=[],tn="snapshots",nn=null,sn="canvas-kit.document",on="canvas-kit.session",rn=Math.min,an=Math.max,cn=Math.round,ln=Math.floor,dn=e=>({x:e,y:e}),un={left:"right",right:"left",bottom:"top",top:"bottom"},pn=["left","right"],hn=["right","left"],fn=["top","bottom"],gn=["bottom","top"],mn=new Set(["left","top"]),vn=/transform|translate|scale|rotate|perspective|filter/,wn=/paint|layout|strict|content/,yn=e=>!!e&&"none"!==e,bn=dn(0),xn={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=Te(s),a=!!t&&Oe(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=dn(1);const d=dn(0),u=Ae(s);if((u||!u&&!r)&&(("body"!==Ce(s)||De(i))&&(c=He(s)),u)){const e=Ye(s);l=Ue(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?dn(0):Je(i,c);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+p.x,y:n.y*l.y-c.scrollTop*l.y+d.y+p.y}},getDocumentElement:Te,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?Oe(t)?[]:Qe(t,this._c):[].concat(n),s],i=Ge(t,r[0],o);let a=i.top,c=i.right,l=i.bottom,d=i.left;for(let u=1;u<r.length;u++){const e=Ge(t,r[u],o);a=an(e.top,a),c=rn(e.right,c),l=rn(e.bottom,l),d=an(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:st,getElementRects:async function(e){const t=this.getOffsetParent||st,n=this.getDimensions,s=await n(e.floating);return{reference:et(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=We(e);return{width:t,height:n}},getScale:Ue,isElement:Re,isRTL:e=>"rtl"===$e(e).direction},Sn=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,s;const{x:o,y:r,placement:i,middlewareData:a}=t,c=await(async(e,t)=>{const{placement:n,platform:s,elements:o}=e,r=await(null==s.isRTL?void 0:s.isRTL(o.floating)),i=he(n),a=fe(n),c="y"===ve(n),l=mn.has(i)?-1:1,d=r&&c?-1:1,u=pe(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*d,y:p*l}:{x:p*l,y:h*d}})(t,e);return i===(null==(n=a.offset)?void 0:n.placement)&&null!=(s=a.arrow)&&s.alignmentOffset?{}:{x:o+c.x,y:r+c.y,data:{...c,placement:i}}}}),En=e=>(void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:s,placement:o,platform:r}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=pe(e,t),d={x:n,y:s},u=await r.detectOverflow(t,l),p=ve(he(o)),h=ge(p);let f=d[h],g=d[p];i&&(f=ue(f+u["y"===h?"top":"left"],f,f-u["y"===h?"bottom":"right"])),a&&(g=ue(g+u["y"===p?"top":"left"],g,g-u["y"===p?"bottom":"right"]));const m=c.fn({...t,[h]:f,[p]:g});return{...m,data:{x:m.x-n,y:m.y-s,enabled:{[h]:i,[p]:a}}}}}),In=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,s;const{placement:o,middlewareData:r,rects:i,initialPlacement:a,platform:c,elements:l}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:g=!0,...m}=pe(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=he(o),w=ve(a),y=he(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!g?[be(a)]:(e=>{const t=be(e);return[ye(e),t,ye(t)]})(a)),S="none"!==f;!p&&S&&x.push(...function(e,t,n,s){const o=fe(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?hn:pn:t?pn:hn;case"left":case"right":return t?fn:gn;default:return[]}})(he(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(ye)))),r}(a,g,f,b));const E=[a,...x],I=await c.detectOverflow(t,m),C=[];let P=(null==(s=r.flip)?void 0:s.overflows)||[];if(d&&C.push(I[v]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const s=fe(e),o=we(e),r=me(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=be(i)),[i,be(i)]})(o,i,b);C.push(I[e[0]],I[e[1]])}if(P=[...P,{placement:o,overflows:C}],!C.every(e=>e<=0)){var T,k;const e=((null==(T=r.flip)?void 0:T.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===ve(t)||P.every(e=>ve(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:P},reset:{placement:t}};let n=null==(k=P.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:k.placement;if(!n)switch(h){case"bestFit":{var R;const e=null==(R=P.filter(e=>{if(S){const t=ve(e.placement);return t===w||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:R[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),Cn=["bottom"],Pn=["bottom-start"],Tn=["bottom"],kn=Ot(null);export{at as CanvasKitFloatingContent,le as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,J as CanvasKitRoot,dt as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,ht as createCustomShapeColor,Q as createLocalSnapshotPersistence,Lt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,yt as getThemeColorTokenName,gt as isCustomShapeColorRef,ft as isThemeShapeColorRef,ne as readPersistedDocumentSnapshot,te as readPersistedEditorSnapshots,se as readPersistedSessionSnapshot,n as requireApi,vt as resolveShapeColor,Pt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,lt as useFloatingSelectionToolbarPosition};