@forsion/unit 2.13.4 → 2.13.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/main.mjs +112 -9
  2. package/package.json +1 -1
  3. package/release.json +5 -5
  4. package/web/assets/ArtificialView-BD1yHz1N.js +1 -0
  5. package/web/assets/AutomationBuilder-B09c-5Bi.js +1 -0
  6. package/web/assets/CalendarConfigView-Bd-ZDGPO.js +1 -0
  7. package/web/assets/CalendarSide-B0RVbOsg.js +1 -0
  8. package/web/assets/CalendarView-BHio-n_r.js +3 -0
  9. package/web/assets/CalendarView-t91KpUG7.css +1 -0
  10. package/web/assets/CapabilityMenu-DyHTEYLr.js +1 -0
  11. package/web/assets/Chrome-C7F6fdDp.js +1 -0
  12. package/web/assets/{CodeView-GZ0BAgoW.js → CodeView-BGOnrGhB.js} +3 -3
  13. package/web/assets/CtxMenuButtons-BYjrbUKS.js +1 -0
  14. package/web/assets/DashboardGridView-CR-R_qV8.js +25 -0
  15. package/web/assets/DashboardGridView-RoVFSkNO.css +1 -0
  16. package/web/assets/EventCard-QyYorE1_.js +1 -0
  17. package/web/assets/ExcalidrawCanvas-BgcFPMpU.css +1 -0
  18. package/web/assets/ExcalidrawCanvas-lwJCN6uB.js +1 -0
  19. package/web/assets/FloatingToc-DO7SH8Ku.js +1 -0
  20. package/web/assets/GitCloneDialog-CbW-RJak.js +1 -0
  21. package/web/assets/{GitCloneDialog-Bj9G3o-n.css → GitCloneDialog-DOxZk2K0.css} +1 -1
  22. package/web/assets/HomepageView-Bx8FbWlY.css +1 -0
  23. package/web/assets/HomepageView-CHJEhf9c.js +4 -0
  24. package/web/assets/ImageStudioPanels-CgVf0wiq.js +3 -0
  25. package/web/assets/ImageStudioView-4WcX0_V4.js +1 -0
  26. package/web/assets/InlineAiPanel-CdIPINsA.js +1 -0
  27. package/web/assets/InlineFiles-CAIyTk1n.js +1 -0
  28. package/web/assets/{MarkdownBlock-DQTuoen3.css → MarkdownBlock-Cqfk5DhC.css} +1 -1
  29. package/web/assets/MarkdownBlock-DSItkLhu.js +58 -0
  30. package/web/assets/ModelPill--CU3XTIQ.js +2 -0
  31. package/web/assets/{ModelPill-CzdNh7Mt.css → ModelPill-BiUsuhy3.css} +1 -1
  32. package/web/assets/MuseLibraryView-PlS7HAlV.js +2 -0
  33. package/web/assets/MuseView-CvsO62Fo.js +7 -0
  34. package/web/assets/{PageHistoryPanel-Bn4-XmdK.js → PageHistoryPanel-CDh7nm78.js} +2 -2
  35. package/web/assets/{PdfAnnotator-Cq8cklTz.js → PdfAnnotator-DafvjP3U.js} +3 -3
  36. package/web/assets/PenRow-CEy-s6SF.js +1 -0
  37. package/web/assets/PluginToolCard-BmTRr5JT.css +1 -0
  38. package/web/assets/PluginToolCard-DCzLhsCA.js +2 -0
  39. package/web/assets/ProductView-AUqnTwmQ.js +1 -0
  40. package/web/assets/SettingsPage-B9mmkWaM.js +3 -0
  41. package/web/assets/StudioGuestSurface-OOhRA8nt.js +1 -0
  42. package/web/assets/TodoListView-BkgMe44I.js +1 -0
  43. package/web/assets/Tooltip-DOYi44eY.js +1 -0
  44. package/web/assets/UnifiedPage-CTmQpf2T.css +1 -0
  45. package/web/assets/UnifiedPage-s7-tDSwG.js +712 -0
  46. package/web/assets/ViewSelectionBar-WmSWMFsR.js +2 -0
  47. package/web/assets/appStore-DDOkzWDA.js +456 -0
  48. package/web/assets/appStore-iy8_Tmac.css +1 -0
  49. package/web/assets/arrow-up-right-BptN64d-.js +1 -0
  50. package/web/assets/{artificial-BzLFkChP.css → artificial-BubVxExB.css} +1 -1
  51. package/web/assets/astryxBridge-BL56QfEv.js +69 -0
  52. package/web/assets/astryxBridge-djzCiy4v.css +1 -0
  53. package/web/assets/automationListSource-B1jz6q0t.js +1 -0
  54. package/web/assets/boardSurface-CP4HNmcm.js +1 -0
  55. package/web/assets/calendarNavStore-DCi7VBmM.js +1 -0
  56. package/web/assets/canvasPrefs-ArsX3NFO.js +1 -0
  57. package/web/assets/chatBoxSurface-DRsDr-MT.js +1 -0
  58. package/web/assets/chevron-up-ChXNh14u.js +1 -0
  59. package/web/assets/{client-CaivGZFR.js → client-fKy9CWk0.js} +5 -5
  60. package/web/assets/code-xml-DCCD9eCS.js +1 -0
  61. package/web/assets/{codeStudioStore-DhyMazGT.js → codeStudioStore-BgLfCDK2.js} +8 -8
  62. package/web/assets/codingNavigation-BrkLENBZ.css +1 -0
  63. package/web/assets/contextMenuSurface-BF593l2M.js +1 -0
  64. package/web/assets/copy-plus-ClKrSgM7.js +1 -0
  65. package/web/assets/create-DYmVT68X.js +14 -0
  66. package/web/assets/dashboardSurface-C6cbR3oG.js +1 -0
  67. package/web/assets/dbStore-BIG5Mfh2.js +1 -0
  68. package/web/assets/deskCapture-q-jRDIcc.js +1 -0
  69. package/web/assets/{diff2html-Daje9Kkm.js → diff2html-Di8qIz6O.js} +2 -2
  70. package/web/assets/{docx-preview-CABR7n30.js → docx-preview-B-URZXdP.js} +1 -1
  71. package/web/assets/draft-CBSW5tHx.js +2 -0
  72. package/web/assets/drawingStore-CGvTqqYW.js +7 -0
  73. package/web/assets/file-down-Z913cCyQ.js +1 -0
  74. package/web/assets/floatingTocSurface-DGwTiqvU.js +1 -0
  75. package/web/assets/foldActions-DGIPTmE1.js +1 -0
  76. package/web/assets/folder-1OJQeDI1.js +1 -0
  77. package/web/assets/folder-minus-D_j1SwHu.js +1 -0
  78. package/web/assets/folder-plus-DP9sFr26.js +1 -0
  79. package/web/assets/gestures-ZhFAENNZ.js +1 -0
  80. package/web/assets/git-branch-BMajF2cu.js +1 -0
  81. package/web/assets/homeCardStatus-5R7XkxFL.js +1 -0
  82. package/web/assets/i18n-CAf4PT1o.css +1 -0
  83. package/web/assets/i18n.generated-DW_l6CkR.js +15 -0
  84. package/web/assets/imageStudio-CwG21Bat.css +1 -0
  85. package/web/assets/imageStudio-DC_syDtx.js +4 -0
  86. package/web/assets/index-B8A3nKeL.js +1 -0
  87. package/web/assets/{index-BGfvNj7R.js → index-BDZIQnEx.js} +2 -2
  88. package/web/assets/index-BYKR7EVg.js +1 -0
  89. package/web/assets/index-BeW45J9J.js +7 -0
  90. package/web/assets/index-BnJguNqI.js +1 -0
  91. package/web/assets/index-BniT-A2n.js +1 -0
  92. package/web/assets/index-C--E96Ul.js +1 -0
  93. package/web/assets/index-CI2esW1X.js +1 -0
  94. package/web/assets/index-CIKPZc3Q.js +1 -0
  95. package/web/assets/index-COzdD7mZ.js +13 -0
  96. package/web/assets/index-CPfmhZ3Z.js +1 -0
  97. package/web/assets/index-CVLDDD5Z.js +1 -0
  98. package/web/assets/index-CWXpOSI2.js +1 -0
  99. package/web/assets/index-Cg1FWM_p.js +1 -0
  100. package/web/assets/index-CmsN2Zm2.js +1 -0
  101. package/web/assets/index-CtCYv9bF.js +1 -0
  102. package/web/assets/index-CtRdzpNh.js +1 -0
  103. package/web/assets/index-D-ClOPbg.js +1 -0
  104. package/web/assets/{index-gt5JBIFf.js → index-DfhEDV2T.js} +2 -2
  105. package/web/assets/index-Dr6YmrrT.js +1 -0
  106. package/web/assets/index-SpegRFQV.js +1 -0
  107. package/web/assets/index-bF04pF8q.js +3 -0
  108. package/web/assets/index-fDB1l4d-.js +3398 -0
  109. package/web/assets/index-jzlU5luC.js +1 -0
  110. package/web/assets/{index-O05r2Ty6.js → index-uhvJ8AiJ.js} +1 -1
  111. package/web/assets/{invitePage-Bgveo6Hj.js → invitePage-iOT1zBvp.js} +1 -1
  112. package/web/assets/{ipc-B6hkgxQL.js → ipc-SAPDwyQ4.js} +1 -1
  113. package/web/assets/{jszip.min-eU-k-vEy.js → jszip.min-B3n1FGCb.js} +1 -1
  114. package/web/assets/launchpad-C9U9hpWJ.css +1 -0
  115. package/web/assets/launchpad-CcmSwlJl.js +2 -0
  116. package/web/assets/layout-grid-oIyIGbc5.js +1 -0
  117. package/web/assets/linkFollow-uke1Xtit.js +8 -0
  118. package/web/assets/listFold-BeNv2v6M.js +1 -0
  119. package/web/assets/lock-open-D2nMg0ga.js +1 -0
  120. package/web/assets/log-out-D70NCXC4.js +1 -0
  121. package/web/assets/magnet-Cqmm97W8.js +1 -0
  122. package/web/assets/main-B9aT0WXG.js +15 -0
  123. package/web/assets/main-BlVApHpj.css +1 -0
  124. package/web/assets/markdownEditorSurface-BiDH0__r.css +1 -0
  125. package/web/assets/markdownEditorSurface-zUzFity2.js +3 -0
  126. package/web/assets/mediaPlayer-DB4KUvua.js +1 -0
  127. package/web/assets/message-square-plus-BvUfAAZm.js +1 -0
  128. package/web/assets/{messages-CKtabOqy.js → messages-GQUjmbwW.js} +1 -1
  129. package/web/assets/minimize-2-CMhzL6ZW.js +1 -0
  130. package/web/assets/mobileEntry-6u7TYC4s.css +1 -0
  131. package/web/assets/mobileEntry-BnHzrdoC.js +13 -0
  132. package/web/assets/modelPickerSurface-Dtz40Ae2.js +1 -0
  133. package/web/assets/nativeDownload-DsGyUSJ5.js +1 -0
  134. package/web/assets/nativeSheetMenu--iihXNVd.js +1 -0
  135. package/web/assets/pageStore-CyvNZEYX.js +13 -0
  136. package/web/assets/pageStore-ys8L4rjF.css +1 -0
  137. package/web/assets/{pageTree-BYYPgZm_.js → pageTree-Ci2qzrs1.js} +3 -3
  138. package/web/assets/pen-line-DC3lbEY1.js +1 -0
  139. package/web/assets/pen-tool-DD5_N4lZ.js +1 -0
  140. package/web/assets/pencil--sWwxHdP.js +1 -0
  141. package/web/assets/phoneList-BpLxxdq6.css +1 -0
  142. package/web/assets/phoneList-DKRMxQHf.js +1 -0
  143. package/web/assets/pluginChat-82zZt47Y.js +2 -0
  144. package/web/assets/react-b7FrqRQR.js +1 -0
  145. package/web/assets/recordSurface-vUX25Z8R.js +1 -0
  146. package/web/assets/redo-2-CqlqhWrI.js +1 -0
  147. package/web/assets/rotate-ccw-D8kni6Ni.js +1 -0
  148. package/web/assets/selectionActions-DIq0xDm8.js +2 -0
  149. package/web/assets/selectionBarSurface-B94e5JW_.js +1 -0
  150. package/web/assets/sessionTitle-Ctp4iNKu.js +1 -0
  151. package/web/assets/settingsPageSurface-C9TA3mJg.js +1 -0
  152. package/web/assets/sharePage-CY04XCAf.js +2 -0
  153. package/web/assets/{shareViewer-BiMqIBxP.js → shareViewer-DweNF8Ch.js} +2 -2
  154. package/web/assets/star-B0sZEmbj.js +1 -0
  155. package/web/assets/tableSurface-CSBYBw5P.js +1 -0
  156. package/web/assets/tanguProbe-B8Qv2vcm.js +6 -0
  157. package/web/assets/{terminalView-lbcBgG0c.js → terminalView-BLGdmdl7.js} +3 -3
  158. package/web/assets/type-Dt7RNB9g.js +1 -0
  159. package/web/assets/undo-2-QimgpLBn.js +1 -0
  160. package/web/assets/{unitAccount-DGwGsmC3.js → unitAccount-DL3jfd84.js} +1 -1
  161. package/web/assets/{unitBridge-CE2yAvm0.js → unitBridge-BSsCy1zP.js} +1 -1
  162. package/web/assets/{unitCloudTransport-BGFwkaDM.js → unitCloudTransport-CI_6H0TU.js} +1 -1
  163. package/web/assets/unitOwnerAccess-CiQ7nD7E.js +1 -0
  164. package/web/assets/unitShim-Dl2ksNp-.js +5 -0
  165. package/web/assets/upload-Dy7svciS.js +1 -0
  166. package/web/assets/userSpaces-oMHIWgYe.js +1 -0
  167. package/web/assets/viewportLock-B0l1GU_k.css +1 -0
  168. package/web/assets/viewportLock-BZq5PTeN.js +738 -0
  169. package/web/assets/zoom-in-DDEtY_Go.js +1 -0
  170. package/web/excalidraw/excalidraw.js +4 -2
  171. package/web/index.html +12 -13
  172. package/web/assets/ArtificialView-DLh75dAI.js +0 -1
  173. package/web/assets/AutomationBuilder-DNWWGnFr.js +0 -1
  174. package/web/assets/CalendarConfigView-G7je7k9-.js +0 -1
  175. package/web/assets/CalendarView-B2MtaOJk.js +0 -1
  176. package/web/assets/CapabilityMenu-DJaZ_Cyt.js +0 -1
  177. package/web/assets/CheckboxInput-FYXLaZke.js +0 -1
  178. package/web/assets/Chrome-CFonajM4.js +0 -1
  179. package/web/assets/DashboardGridView-D9s9pez_.css +0 -1
  180. package/web/assets/DashboardGridView-Xgw4wa0_.js +0 -17
  181. package/web/assets/EventCard-_39F_I5M.js +0 -1
  182. package/web/assets/ExcalidrawCanvas-4uYrLYin.css +0 -1
  183. package/web/assets/ExcalidrawCanvas-rXujil36.js +0 -1
  184. package/web/assets/FloatingToc-DNqAkkI0.js +0 -1
  185. package/web/assets/GitCloneDialog-CQx-O4j1.js +0 -1
  186. package/web/assets/HomepageView-DcWmTPQO.css +0 -1
  187. package/web/assets/HomepageView-MYEk3RCs.js +0 -3
  188. package/web/assets/ImageStudioPanels-4wnb2XF4.js +0 -3
  189. package/web/assets/ImageStudioView-qrmW8pfx.js +0 -1
  190. package/web/assets/InlineAiPanel-B3kd1ob2.js +0 -1
  191. package/web/assets/InlineFiles-Clnqh9jD.js +0 -1
  192. package/web/assets/MarkdownBlock-DT_wsaja.js +0 -58
  193. package/web/assets/ModelPill-JaIH3ffZ.js +0 -2
  194. package/web/assets/MuseLibraryView-DOJVVeU6.js +0 -2
  195. package/web/assets/MuseView-uxTmjVQa.js +0 -6
  196. package/web/assets/PenRow-COOYAaxx.js +0 -1
  197. package/web/assets/ProductView-DPTveulg.js +0 -1
  198. package/web/assets/RightPanel-BJUacrsf.js +0 -4
  199. package/web/assets/RightPanel-D0zk1g3I.css +0 -1
  200. package/web/assets/SketchCard-B_UU5sxV.js +0 -641
  201. package/web/assets/StudioGuestSurface-yBa4QKfX.js +0 -1
  202. package/web/assets/TargetHealthNotice-BLzDB-Xl.css +0 -1
  203. package/web/assets/TargetHealthNotice-CgkdTdhB.js +0 -47
  204. package/web/assets/TodoListView-CricdCfW.js +0 -1
  205. package/web/assets/Tooltip-o8ZqIb3L.js +0 -1
  206. package/web/assets/UnifiedPage-BWAyqj65.js +0 -69
  207. package/web/assets/UnifiedPage-CWXc_mo1.css +0 -1
  208. package/web/assets/ViewSelectionBar-35x8TiLA.js +0 -2
  209. package/web/assets/appStore-CI1_L5OS.js +0 -3357
  210. package/web/assets/appStore-DQc2marq.css +0 -1
  211. package/web/assets/approvalText-Cy2UAUAQ.js +0 -2
  212. package/web/assets/arrow-up-right-BDsMFoNQ.js +0 -1
  213. package/web/assets/astryxBridge-CF_hpqC2.css +0 -1
  214. package/web/assets/astryxBridge-CH_c5xjo.js +0 -70
  215. package/web/assets/automationListSource-CB6AWkL_.js +0 -1
  216. package/web/assets/boardSurface-CLvEUjbF.js +0 -1
  217. package/web/assets/book-open-BLzEdGfu.js +0 -1
  218. package/web/assets/calendarNavStore-BHUNxDx8.js +0 -1
  219. package/web/assets/canvasPrefs-CvE7mgyq.js +0 -1
  220. package/web/assets/chatBoxSurface-CuuHLzs5.js +0 -1
  221. package/web/assets/circle-question-mark-BM4ZRxQS.js +0 -1
  222. package/web/assets/circle-x-DTcNGZDT.js +0 -1
  223. package/web/assets/code-xml-AE3mT4T5.js +0 -1
  224. package/web/assets/codingNavigation-B0kVsy4x.js +0 -53
  225. package/web/assets/codingNavigation-DHCidM4N.css +0 -1
  226. package/web/assets/create-1JI2I47p.js +0 -14
  227. package/web/assets/dashboardSurface-CIE5HybN.js +0 -1
  228. package/web/assets/deskCapture-COW7aG5Y.js +0 -1
  229. package/web/assets/emoji-DZ9CA_3l.css +0 -1
  230. package/web/assets/emoji-DphwSxPx.js +0 -1
  231. package/web/assets/floatingTocSurface-BOm2QYBK.js +0 -1
  232. package/web/assets/foldActions-DNbJPlPl.js +0 -1
  233. package/web/assets/folder-DotgUhYD.js +0 -1
  234. package/web/assets/folder-plus-aJgL9NeP.js +0 -1
  235. package/web/assets/gestures-dqncPOwo.js +0 -1
  236. package/web/assets/git-branch-CwR2qic6.js +0 -1
  237. package/web/assets/hack2gate-dark-Dx2RtDRI.jpg +0 -0
  238. package/web/assets/hack2gate-light-DRKq9tyS.jpg +0 -0
  239. package/web/assets/hand-XNkzNiW2.js +0 -1
  240. package/web/assets/hard-drive-CfWKRoAE.js +0 -1
  241. package/web/assets/i18n-CykmULlm.css +0 -1
  242. package/web/assets/i18n.generated-BwynSSMk.js +0 -15
  243. package/web/assets/imageStudio-CWgLpC_d.js +0 -2
  244. package/web/assets/imageStudio-DZ0qGU2s.css +0 -1
  245. package/web/assets/index-B65ULikK.js +0 -1
  246. package/web/assets/index-BIIeiIap.js +0 -1
  247. package/web/assets/index-BOzsniE1.js +0 -297
  248. package/web/assets/index-BfrjVzia.js +0 -13
  249. package/web/assets/index-Bi9UtjVz.js +0 -1
  250. package/web/assets/index-C1uilc9i.js +0 -1
  251. package/web/assets/index-C3Dc3Ivz.js +0 -1
  252. package/web/assets/index-CJF_Ld1Y.js +0 -1
  253. package/web/assets/index-CMARP4oV.js +0 -1
  254. package/web/assets/index-C_RsQVNm.js +0 -7
  255. package/web/assets/index-ChyxZMm8.js +0 -1
  256. package/web/assets/index-CoKcOaZg.js +0 -1
  257. package/web/assets/index-CuviSCbk.js +0 -1
  258. package/web/assets/index-Cw43kua8.js +0 -1
  259. package/web/assets/index-D1fu6XQN.js +0 -3
  260. package/web/assets/index-DG-hXb63.js +0 -1
  261. package/web/assets/index-DjnTfJpN.js +0 -1
  262. package/web/assets/index-Dtw0abst.js +0 -1
  263. package/web/assets/index-W3ErfZiX.js +0 -1
  264. package/web/assets/index-Yc56b3XX.js +0 -1
  265. package/web/assets/index-d4jCdYJH.js +0 -1
  266. package/web/assets/index-siHtlYTM.js +0 -1
  267. package/web/assets/launchpad-C2c1MSVX.css +0 -1
  268. package/web/assets/layout-grid-CraV7nhh.js +0 -1
  269. package/web/assets/linkFollow-BpvDWzUx.js +0 -8
  270. package/web/assets/list-tree-cLJw-jYQ.js +0 -1
  271. package/web/assets/listFold-M8s5JYEC.js +0 -1
  272. package/web/assets/lock-DBkXXwaI.js +0 -1
  273. package/web/assets/lock-open-C-9-AWct.js +0 -1
  274. package/web/assets/log-out-C8bDXj9P.js +0 -1
  275. package/web/assets/main-BiS_5wrB.css +0 -1
  276. package/web/assets/main-CMk6twzA.js +0 -20
  277. package/web/assets/markdownEditorSurface-Bql20IAf.css +0 -1
  278. package/web/assets/markdownEditorSurface-DgQ0TUWH.js +0 -3
  279. package/web/assets/message-square-plus-8pfimvem.js +0 -1
  280. package/web/assets/minus-CfA9fAN3.js +0 -1
  281. package/web/assets/mobileEntry-DS1vohuL.css +0 -1
  282. package/web/assets/mobileEntry-NcMcK0LV.js +0 -13
  283. package/web/assets/nativeDownload-CNtwSCy0.js +0 -1
  284. package/web/assets/pageChrome-BR4cfIaA.js +0 -1
  285. package/web/assets/pageChrome-BbUhILy0.css +0 -1
  286. package/web/assets/pen-tool-C5ftHCnm.js +0 -1
  287. package/web/assets/pencil-ehhM9_9k.js +0 -1
  288. package/web/assets/phoneList-B6gwUJZF.js +0 -9
  289. package/web/assets/phoneList-iRdfiKA8.css +0 -1
  290. package/web/assets/pluginChat-DTTWWiUS.js +0 -2
  291. package/web/assets/redo-2-DCEAgQlN.js +0 -1
  292. package/web/assets/rotate-ccw-DdkrbRAB.js +0 -1
  293. package/web/assets/selectionActions-BQD2kox1.js +0 -2
  294. package/web/assets/selectionBarSurface-CzUZmJDJ.js +0 -1
  295. package/web/assets/server-Ddu9f1k3.js +0 -1
  296. package/web/assets/sharePage-CNrm2xTC.js +0 -2
  297. package/web/assets/star-Dxv7XANS.js +0 -1
  298. package/web/assets/tableSurface-Bly1iCXc.js +0 -1
  299. package/web/assets/terminal-CAmmC9cV.js +0 -1
  300. package/web/assets/type-Dz6rnTvG.js +0 -1
  301. package/web/assets/undo-2-B7izWNb_.js +0 -1
  302. package/web/assets/unitOwnerAccess-D4nKS6Gg.js +0 -1
  303. package/web/assets/unitShim-2_2hhGxS.js +0 -5
  304. package/web/assets/upload-DqpRRAhG.js +0 -1
  305. package/web/assets/userSpaces-VFu4s05v.js +0 -1
  306. package/web/assets/viewportLock-3AOdDmwi.js +0 -631
  307. package/web/assets/viewportLock-djvL8fUQ.css +0 -1
  308. package/web/assets/zoom-in-Bf-eKTnH.js +0 -1
@@ -1,69 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PdfAnnotator-Cq8cklTz.js","./index-BOzsniE1.js","./pdf-C2_sJa3b.js","./pdf.worker.min-CGb3BKV9.js","./appStore-CI1_L5OS.js","./nativeDownload-CNtwSCy0.js","./ipc-B6hkgxQL.js","./client-CaivGZFR.js","./appStore-DQc2marq.css","./PdfAnnotator-C_kglLCA.css"])))=>i.map(i=>d[i]);
2
- import{r as kn,j as f,u as tn,d as b,W as $r,t as we,bD as Ou,bE as _u,bF as Bu,bG as Ws,b5 as Ku,b1 as Cl,bH as Vu,b8 as Hu,bI as ta,bJ as qu,bK as Bc,bL as Wu,bM as Yu,w as Sl,bN as Xu,bO as _r,bP as Uu,aJ as Gu,aW as Ju,bQ as Zu,bR as El,x as Qu,bS as ed,n as gs,bT as td,bU as Ml,aR as zl,aV as nd,by as ua,m as od,l as Kc,V as rd,_ as sd,bV as ad,Q as cd,bW as id,bX as ld,ah as ud,z as $l,av as Vc,G as Al,bY as Hc,bZ as Ys,b_ as qc,b$ as dd,c0 as Wc,aj as fd,c1 as vr,c2 as Yc,c3 as md,az as pd,c4 as hd,aA as gd,c5 as yd,c6 as xd}from"./index-BOzsniE1.js";import{F as bd,c as na,d as vd,h as Nl,p as Ss,e as hs,t as wd,f as kd,g as Cd,i as Sd,j as ic,l as Tl,k as Ed,m as _a,n as Md,o as zd,q as $d,r as Ad,v as da,w as fa,x as Nd,y as Xs,z as Ba,A as Td,B as Us,C as jd,D as Ka,E as jl,G as Xc,H as Rd,I as Dd,T as Ld,J as Id,K as Pd,L as Fd,M as Od,u as Rl,N as _d,O as Bd,Q as Kd,R as Vd,S as Uc,U as Hd,V as Ts,W as qd,X as Wd,Y as Yd,Z as Dl,_ as cs,$ as Xd,a0 as Ud,a1 as Gd,a2 as Jd,a3 as Zd,a4 as Qd,a5 as ef,a6 as tf,a7 as ma,a8 as nf,a9 as of,aa as rf}from"./MarkdownBlock-DT_wsaja.js";import{J as fn,jL as sf,aC as af,bX as Ll,dd as wn,n_ as cf,cg as Vr,n$ as qt,am as En,o0 as Gc,o1 as Oo,o2 as Ne,o3 as Vo,o4 as lf,o5 as uf,o6 as df,an as Il,b as Mn,fV as lc,o7 as Jc,jC as ff,aA as mf,aM as uc,o8 as pf,o9 as hf,aR as oa,oa as gf,ob as yf,oc as xf,od as Dn,oe as Ee,of as So,T as Pl,K as bf,aU as Zc,mh as Ar,og as Fl,cM as Va,oh as Qc,oi as vf,gG as wf,oj as lr,ok as so,ol as kf,om as Cf,on as Sf,oo as Ef,op as ei,oq as Mf,fT as zf,fS as $f,or as Af,fn as Nf,ft as ti,gH as Tf,os as jf,ma as Rf,ot as Ol,ou as Df,ov as Lf,ow as If,ox as Ha,oy as Pf,oz as ni,oA as Ff,oB as Gr,ge as qa,oC as oi,oD as js,d$ as Of,oE as Wa,cE as _f,lp as Bf,lo as Kf,oF as cr,aq as Yr,R as Vf,oG as ri,oH as si,gr as ai,mB as Hf,oI as qf,mL as Wf,oJ as Yf,oK as Xf,oL as Uf,oM as ci,nH as Gf,oN as Jf,oO as ii,oP as Zf,mA as Qf,oQ as em,oR as tm,oS as nm,mf as om,bw as Ya,eV as rm,fU as sm,oT as am,fy as cm,oU as im,oV as lm,oW as um,oX as dm,oY as fm,oZ as mm,o_ as pm,o$ as li,p0 as hm,p1 as gm,p2 as pa,p3 as ui,p4 as ha,dy as ym,cA as xm,cf as bm,fs as di,bK as vm,dw as wm,p5 as fi,p6 as km,p7 as Cm,p8 as mi,p9 as Sm,a0 as Em,be as Mm,pa as zm,pb as $m,pc as Am,pd as Ir,pe as vn,pf as Nm,pg as Tm,ph as jm,pi as Xa,fH as ga,pj as pi,nN as Rm,iA as Dm,pk as Lm,eC as Im,pl as Pm,pm as Fm,ie as Om}from"./appStore-CI1_L5OS.js";import{c as _m}from"./client-CaivGZFR.js";import{$ as Et,a as _l,b as dc}from"./index-DjnTfJpN.js";import{N as Bm,S as Km,r as Vm,I as Hm,C as qm,U as Wm}from"./pageChrome-BR4cfIaA.js";import{h as Xr,l as Ym,f as Ur,a as hi,i as fc,b as Vs,c as Xm,d as wr,t as Rs,e as Ds,g as ya,s as Um,j as Gm,k as Jm}from"./listFold-M8s5JYEC.js";import{e as Zm,a as Qm,b as ep,c as gi,v as yi,i as tp}from"./linkFollow-BpvDWzUx.js";import{S as np,b as op,a as rp,F as sp}from"./SketchCard-B_UU5sxV.js";import{A as xi}from"./arrow-up-right-BDsMFoNQ.js";import{c as Bl}from"./nativeDownload-CNtwSCy0.js";import{r as Jr,a as ap,C as cp}from"./Chrome-CFonajM4.js";import{e as ip,h as lp,a as bi,o as up,d as dp,i as fp,g as mp,j as pp,k as hp,f as gp,c as yp}from"./canvasPrefs-CvE7mgyq.js";import{H as xp}from"./hand-XNkzNiW2.js";import{T as bp,F as vp}from"./type-Dz6rnTvG.js";import{M as wp}from"./minus-CfA9fAN3.js";import{t as vi,I as kp}from"./InlineAiPanel-B3kd1ob2.js";import{l as Cp,b as Sp,r as wi}from"./selectionActions-BQD2kox1.js";import{createFoldMemory as Ep,remapFoldMemory as Mp}from"./foldActions-DNbJPlPl.js";import{L as zp}from"./lock-DBkXXwaI.js";import{U as $p}from"./undo-2-B7izWNb_.js";import{C as Ap}from"./code-xml-AE3mT4T5.js";import{M as Np}from"./message-square-plus-8pfimvem.js";const Tp=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M8 10H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2h4",key:"14d6g8"}],["path",{d:"M16 10h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-4",key:"1e2lrw"}],["path",{d:"M8 20H7a2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2h1",key:"1fkdwx"}],["path",{d:"M16 14h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1",key:"1euafb"}]],jp=fn("align-center-vertical",Tp);const Rp=[["rect",{width:"13",height:"7",x:"3",y:"3",rx:"1",key:"11xb64"}],["path",{d:"m22 15-3-3 3-3",key:"26chmm"}],["rect",{width:"13",height:"7",x:"3",y:"14",rx:"1",key:"k6ky7n"}]],Dp=fn("between-horizontal-end",Rp);const Lp=[["rect",{width:"13",height:"7",x:"8",y:"3",rx:"1",key:"pkso9a"}],["path",{d:"m2 9 3 3-3 3",key:"1agib5"}],["rect",{width:"13",height:"7",x:"8",y:"14",rx:"1",key:"1q5fc1"}]],Ip=fn("between-horizontal-start",Lp);const Pp=[["rect",{width:"7",height:"13",x:"3",y:"3",rx:"1",key:"1fdu0f"}],["path",{d:"m9 22 3-3 3 3",key:"17z65a"}],["rect",{width:"7",height:"13",x:"14",y:"3",rx:"1",key:"1squn4"}]],Fp=fn("between-vertical-end",Pp);const Op=[["rect",{width:"7",height:"13",x:"3",y:"8",rx:"1",key:"1fjrkv"}],["path",{d:"m15 2-3 3-3-3",key:"1uh6eb"}],["rect",{width:"7",height:"13",x:"14",y:"8",rx:"1",key:"w3fjg8"}]],_p=fn("between-vertical-start",Op);const Bp=[["path",{d:"m2 16 4.039-9.69a.5.5 0 0 1 .923 0L11 16",key:"d5nyq2"}],["path",{d:"M22 9v7",key:"pvm9v3"}],["path",{d:"M3.304 13h6.392",key:"1q3zxz"}],["circle",{cx:"18.5",cy:"12.5",r:"3.5",key:"z97x68"}]],Kp=fn("case-sensitive",Bp);const Vp=[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]],Hp=fn("chevrons-down",Vp);const qp=[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"m17 12 3-2v8",key:"1hhhft"}]],Wp=fn("heading-1",qp);const Yp=[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1",key:"9jr5yi"}]],Xp=fn("heading-2",Yp);const Up=[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2",key:"68ncm8"}],["path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2",key:"1ejuhz"}]],Gp=fn("heading-3",Up);const Jp=[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]],Zp=fn("list-collapse",Jp);const Qp=[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]],eh=fn("list-ordered",Qp);const th=[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]],nh=fn("move-horizontal",th);const oh=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],rh=fn("move-right",oh);const sh=[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]],ah=fn("move-left",sh);const ch=[["path",{d:"M13 4v16",key:"8vvj80"}],["path",{d:"M17 4v16",key:"7dpous"}],["path",{d:"M19 4H9.5a4.5 4.5 0 0 0 0 9H13",key:"sh4n9v"}]],ki=fn("pilcrow",ch);const ih=[["path",{d:"M17 3v10",key:"15fgeh"}],["path",{d:"m12.67 5.5 8.66 5",key:"1gpheq"}],["path",{d:"m12.67 10.5 8.66-5",key:"1dkfa6"}],["path",{d:"M9 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2z",key:"swwfx4"}]],lh=fn("regex",ih);const uh=[["path",{d:"M14 14a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1",key:"zg1ipl"}],["path",{d:"M14 4a1 1 0 0 1 1-1",key:"dhj8ez"}],["path",{d:"M15 10a1 1 0 0 1-1-1",key:"1mnyi5"}],["path",{d:"M19 14a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1",key:"txt6k4"}],["path",{d:"M21 4a1 1 0 0 0-1-1",key:"sfs9ap"}],["path",{d:"M21 9a1 1 0 0 1-1 1",key:"mp6qeo"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a2 2 0 0 1 2-2h2",key:"15xut4"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}]],dh=fn("replace-all",uh);const fh=[["path",{d:"M14 4a1 1 0 0 1 1-1",key:"dhj8ez"}],["path",{d:"M15 10a1 1 0 0 1-1-1",key:"1mnyi5"}],["path",{d:"M21 4a1 1 0 0 0-1-1",key:"sfs9ap"}],["path",{d:"M21 9a1 1 0 0 1-1 1",key:"mp6qeo"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a2 2 0 0 1 2-2h2",key:"15xut4"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}]],mh=fn("replace",fh);const ph=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],hh=fn("rows-2",ph);const gh=[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]],yh=fn("spline",gh);function xh(e,t){const n=e.trim().toLowerCase(),o=t.toLowerCase();if(!n)return 1;let r=0,s=0,c=-2,a=-1;for(let i=0;i<o.length&&s<n.length;i++)if(o[i]===n[s]){a<0&&(a=i);let d=1;i===c+1&&(d+=4),(i===0||/[\s/\-_.]/.test(o[i-1]))&&(d+=3),r+=d,c=i,s++}return s<n.length?null:(r-=a*.1,r-=o.length*.02,o===n&&(r+=10),r)}function bh(e,t,n){if(!e.trim())return t;const o=[];for(const r of t){const s=xh(e,n(r));s!=null&&o.push({item:r,score:s})}return o.sort((r,s)=>s.score-r.score),o.map(r=>r.item)}kn({"delassets.blockTitle":{zh:"引用块已删除",en:"Reference block deleted"},"delassets.noteTitle":{zh:"删除「{name}」",en:'Delete "{name}"'},"delassets.blockMsg":{zh:"这 {n} 个文件只被这条笔记引用,要一并从磁盘删除吗?",en:"These {n} files are only referenced by this note. Delete them from disk too?"},"delassets.noteMsg":{zh:"有 {n} 个附件只被这条笔记引用,要一并删除吗?",en:"{n} attachments are only referenced by this note. Delete them too?"},"delassets.more":{zh:"…还有 {n} 个",en:"…and {n} more"},"delassets.remember":{zh:"下次不再问(设置→笔记可改回)",en:"Don't ask again (change it back in Settings → Notes)"},"delassets.keepFiles":{zh:"保留文件",en:"Keep files"},"delassets.cancel":{zh:"取消",en:"Cancel"},"delassets.noteOnly":{zh:"只删笔记",en:"Delete note only"},"delassets.deleteAll":{zh:"一并删除",en:"Delete them too"}});const Ua="amadeus_delete_assets";function lv(){try{const e=localStorage.getItem(Ua);return e==="yes"?!0:e==="no"?!1:null}catch{return null}}function vh(e){try{e===null?localStorage.removeItem(Ua):localStorage.setItem(Ua,e?"yes":"no")}catch{}}const ys=Bl(e=>({req:null,open:t=>e({req:t}),clear:()=>e({req:null})}));function wh(e,t,n){return new Promise(o=>{ys.getState().req?.resolve(null),ys.getState().open({note:e,assets:t,block:n?.block,resolve:o})})}function uv(){const e=ys(t=>t.req);return e?f.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},children:f.jsx(kh,{req:e},e.note)}):null}function kh({req:e}){const{t}=tn(),[n,o]=b.useState(!1),r=c=>{ys.getState().req===e&&(n&&c!==null&&vh(c==="with"),ys.getState().clear(),e.resolve(c))};sf(()=>r(null));const s=e.assets.slice(0,6);return f.jsx("div",{className:"dialog-overlay",onMouseDown:()=>r(null),children:f.jsxs("div",{className:"dialog",onMouseDown:c=>c.stopPropagation(),children:[f.jsx("div",{className:"dialog-title",children:e.block?t("delassets.blockTitle"):t("delassets.noteTitle",{name:e.note})}),f.jsxs("div",{className:"dialog-msg",children:[e.block?t("delassets.blockMsg",{n:e.assets.length}):t("delassets.noteMsg",{n:e.assets.length}),f.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18,opacity:.8},children:[s.map(c=>f.jsx("li",{children:c},c)),e.assets.length>s.length&&f.jsx("li",{children:t("delassets.more",{n:e.assets.length-s.length})})]})]}),!e.block&&f.jsxs("label",{className:"inline-check",style:{display:"flex",gap:6,alignItems:"center",marginTop:10},children:[f.jsx("input",{type:"checkbox",checked:n,onChange:c=>o(c.target.checked)}),t("delassets.remember")]}),f.jsxs("div",{className:"dialog-actions",children:[e.block?f.jsx("button",{className:"dialog-btn",autoFocus:!0,onClick:()=>r("only"),children:t("delassets.keepFiles")}):f.jsxs(f.Fragment,{children:[f.jsx("button",{className:"dialog-btn",onClick:()=>r(null),children:t("delassets.cancel")}),f.jsx("button",{className:"dialog-btn",onClick:()=>r("only"),children:t("delassets.noteOnly")})]}),f.jsx("button",{className:"dialog-btn","data-danger":!0,autoFocus:!e.block,onClick:()=>r("with"),children:t("delassets.deleteAll")})]})]})})}kn({"settings.notes.aiSpaceLabel":{zh:"空行按空格唤起 AI",en:"Press Space on an empty line for AI"},"settings.notes.aiSpaceHint":{zh:"在空的段落里按空格打开 AI 写作面板;输入法组字中的空格不受影响。仅本机生效",en:"Space on an empty paragraph opens the AI writing panel. Spaces typed with an input method are not affected. This device only"}});const Ga="forsion.amadeus.aiSpaceTrigger";let is=null;function Ch(){if(is===null)try{is=localStorage.getItem(Ga)==="1"}catch{is=!1}return is}function dv(e){is=e;try{e?localStorage.setItem(Ga,"1"):localStorage.removeItem(Ga)}catch{}}kn({"find.placeholder":{zh:"在本页查找…",en:"Find in page…"},"find.prev":{zh:"上一个(Shift+Enter)",en:"Previous (Shift+Enter)"},"find.next":{zh:"下一个(Enter)",en:"Next (Enter)"},"find.close":{zh:"关闭(Esc)",en:"Close (Esc)"},"find.case":{zh:"区分大小写",en:"Match case"},"find.regex":{zh:"使用正则表达式",en:"Use regular expression"},"find.toggleReplace":{zh:"切换替换(⌘⌥F / Ctrl+Alt+F)",en:"Toggle replace (⌘⌥F / Ctrl+Alt+F)"},"find.replacePlaceholder":{zh:"替换为…",en:"Replace with…"},"find.replaceOne":{zh:"替换(Enter)",en:"Replace (Enter)"},"find.replaceAll":{zh:"全部替换(⌘/Ctrl+Enter)",en:"Replace all (⌘/Ctrl+Enter)"},"find.badRegex":{zh:"正则表达式无效",en:"Invalid regular expression"}});const Kl=typeof CSS<"u"&&"highlights"in CSS;let Ht=[],xs=[];const St=Bl(()=>({open:!1,query:"",active:0,total:0,root:null,caseSensitive:!1,regex:!1,bad:!1,replaceOpen:!1,replacement:"",replaceable:0,providerVer:0})),bs=new Set,Ci=()=>St.setState(e=>({providerVer:e.providerVer+1}));function Si(e){return bs.add(e),Ci(),()=>{bs.delete(e),Ci()}}function mc(e){const t=e.startContainer;for(const n of bs)if(n.el.isConnected&&(n.owns?n.owns(t):n.el.contains(t)))return n;return null}function Ei(e,t,n){return!n||!t?e:e.replace(/\$(\$|&|<([^>]*)>|(\d{1,2}))/g,(o,r,s,c)=>{if(r==="$")return"$";if(r==="&")return t[0];if(s!==void 0)return t.groups?.[s]??"";if(c!==void 0){const a=Number(c);if(a>=1&&a<t.length)return t[a]??"";if(c.length===2&&Number(c[0])>=1&&Number(c[0])<t.length)return(t[Number(c[0])]??"")+c[1]}return o})}function Vl(e,t){const n=t.regex?e:e.trim();if(!n)return null;try{return new RegExp(t.regex?n:n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t.caseSensitive?"gm":"gim")}catch{return"bad"}}function Sh(e){let t=null;const n=["fontFamily","fontSize","fontWeight","fontStyle","lineHeight","letterSpacing","wordSpacing","textIndent","textTransform","textAlign","tabSize","whiteSpace","overflowWrap","wordBreak","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing","direction"],o=()=>{if(!t)return;const r=getComputedStyle(e);for(const s of n)t.style[s]=r[s];Object.assign(t.style,{position:"absolute",left:`${e.offsetLeft}px`,top:`${e.offsetTop}px`,width:`${e.offsetWidth}px`,height:`${e.offsetHeight}px`,margin:"0",borderStyle:"solid",borderColor:"transparent",overflow:"hidden",color:"transparent",background:"transparent",pointerEvents:"none",whiteSpace:"pre-wrap"}),t.firstChild?.nodeValue!==e.value&&(t.textContent=e.value),t.scrollTop=e.scrollTop};return{el:e,owns:r=>!!t&&t.contains(r),attach:()=>{t=document.createElement("div"),t.className="amx-find-mirror",t.setAttribute("aria-hidden","true"),e.parentElement?.insertBefore(t,e.nextSibling),o();const r=new ResizeObserver(o);return r.observe(e),e.addEventListener("input",o),e.addEventListener("scroll",o),()=>{r.disconnect(),e.removeEventListener("input",o),e.removeEventListener("scroll",o),t?.remove(),t=null}},replace:r=>{const s=e.value,c=r.map(({range:R,text:T})=>({from:R.startOffset,to:R.endOffset,text:T,was:R.toString()})).filter(R=>s.slice(R.from,R.to)===R.was).sort((R,T)=>R.from-T.from);if(!c.length)return 0;const a=c[0].from,i=c[c.length-1].to;let d="",p=a;for(const R of c)d+=s.slice(p,R.from)+R.text,p=R.to;d+=s.slice(p,i);const h=document.activeElement;return e.focus(),e.setSelectionRange(a,i),(d?document.execCommand("insertText",!1,d):document.execCommand("delete"))||(e.setRangeText(d,a,i,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))),h?.focus(),o(),c.length},focusAt:r=>t?.contains(r.startContainer)?(e.focus({preventScroll:!0}),e.setSelectionRange(r.startOffset,r.endOffset),!0):!1}}function Eh(){const e=document.activeElement;return(e instanceof Element?e.closest(".wb-view, .mb-view, .fs-overlay"):null)??document.querySelector(".dv-active-group .wb-view")??document.querySelector(".wb-view--main")??document.querySelector(".mb-view")??document.body}function Mh(){const e=document.activeElement;let t="";if(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement&&/^(text|search)$/.test(e.type)){if(e.closest(".amx-findbar"))return null;t=e.value.slice(e.selectionStart??0,e.selectionEnd??0)}else t=window.getSelection()?.toString()??"";return t.trim()&&!/[\r\n]/.test(t)&&t.length<=200?t:null}let vs=null;function zh(){const e=document.activeElement;if(!(e instanceof HTMLElement)||e===document.body||e.closest(".amx-findbar")){vs=null;return}const t=window.getSelection(),n=t&&t.rangeCount?t.getRangeAt(0):null;vs={el:e,range:e.isContentEditable&&n&&e.contains(n.startContainer)?n.cloneRange():null}}function $h(e){const t=e.startContainer.parentElement;if(!t?.isContentEditable)return null;let n=t;for(;n.parentElement?.isContentEditable;)n=n.parentElement;return n}function Ah(e){const t=vs;vs=null;const n=document.activeElement;if(!(n&&n!==document.body&&!n.closest(".amx-findbar"))){if(e){if(mc(e)?.focusAt?.(e))return;const r=$h(e);if(r){r.focus({preventScroll:!0});const s=window.getSelection();s?.removeAllRanges(),s?.addRange(e);return}}if(t?.el.isConnected&&(t.el.focus({preventScroll:!0}),t.range&&t.range.startContainer.isConnected)){const o=window.getSelection();o?.removeAllRanges(),o?.addRange(t.range)}}}function fv(e={}){if(!Kl)return;const t=Mh();if(St.getState().open){St.setState({...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}});const n=document.querySelector(".amx-findbar input");n?.focus(),n?.select();return}zh(),St.setState({open:!0,root:Eh(),...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}})}function xa(e){const t=e==="keyboard"?Ht[St.getState().active]??null:null;Ht=[],xs=[],ls(-1),St.setState({open:!1,query:"",active:0,total:0,root:null,bad:!1,replaceable:0}),e?Ah(t):vs=null}const Nh=/^(inline|contents|ruby)/;function Th(e,t){let n=e.parentElement;for(;n;){let o=t.get(n);if(o===void 0&&(o=Nh.test(getComputedStyle(n).display),t.set(n,o)),!o)return n;n=n.parentElement}return null}function jh(e,t){if(xs=[],!t)return[];const n=new WeakMap,o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(d){const p=d.parentElement;if(!p||!d.nodeValue||p.closest(".amx-findbar"))return NodeFilter.FILTER_REJECT;const h=p.tagName;return h==="SCRIPT"||h==="STYLE"||h==="NOSCRIPT"||h==="TEXTAREA"||!p.checkVisibility()?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let r="";const s=[];let c=null;for(let d=o.nextNode();d;d=o.nextNode()){const p=d,h=Th(p,n);s.length&&h!==c&&(r+=`
3
- `),c=h,s.push({node:p,at:r.length}),r+=p.nodeValue??""}const a=[];let i=0;t.lastIndex=0;for(let d=t.exec(r);d;d=t.exec(r)){if(!d[0]){t.lastIndex++;continue}if(d[0].includes(`
4
- `))continue;const p=d.index,h=p+d[0].length;for(;i>0&&s[i].at>p;)i--;for(;i+1<s.length&&s[i+1].at<=p;)i++;let M=i;for(;M+1<s.length&&s[M+1].at<h;)M++;const R=document.createRange();R.setStart(s[i].node,p-s[i].at),R.setEnd(s[M].node,Math.min(h-s[M].at,s[M].node.length)),a.push(R),xs.push(d)}return a}function ba(e){const t=St.getState(),n=Vl(t.query,t);return Ht=jh(e,n==="bad"?null:n),St.setState({bad:n==="bad",replaceable:Ht.filter(o=>mc(o)).length}),Ht.length}function ls(e){if(!Kl)return;const t=CSS.highlights;if(!Ht.length){t.delete("amx-find"),t.delete("amx-find-active");return}t.set("amx-find",new Highlight(...Ht));const n=Ht[e],o=n?new Highlight(n):new Highlight;o.priority=1,t.set("amx-find-active",o)}function Rh(e){for(let t=e;t&&t!==document.body;t=t.parentElement){if(!(t instanceof HTMLElement))continue;const n=getComputedStyle(t),o=/auto|scroll/.test(n.overflowY)&&t.scrollHeight>t.clientHeight+1,r=/auto|scroll/.test(n.overflowX)&&t.scrollWidth>t.clientWidth+1;if(o||r)return t}return null}function va(e){const t=e.getBoundingClientRect();if(!t.width&&!t.height)return;const n=e.startContainer.parentElement;if(!n||!n.dispatchEvent(new CustomEvent("amx-reveal",{bubbles:!0,cancelable:!0,detail:{rect:t}})))return;const r=Rh(n);if(!r)return;const s=r.getBoundingClientRect(),c=r.currentCSSZoom||1;(t.bottom>s.bottom||t.top<s.top)&&(r.scrollTop+=(t.top+t.height/2-(s.top+s.height/2))/c),(t.right>s.right||t.left<s.left)&&(r.scrollLeft+=(t.left+t.width/2-(s.left+s.width/2))/c)}function mv(){return St(t=>t.open)?f.jsx(Dh,{}):null}function Dh(){const{t:e}=tn(),t=St(q=>q.query),n=St(q=>q.active),o=St(q=>q.total),r=St(q=>q.root),s=St(q=>q.caseSensitive),c=St(q=>q.regex),a=St(q=>q.bad),i=St(q=>q.replaceOpen),d=St(q=>q.replacement),p=St(q=>q.replaceable),h=St(q=>q.providerVer),[M,R]=b.useState({top:12,right:12}),T=b.useRef(null),w=!!r&&[...bs].some(q=>q.el.isConnected&&r.contains(q.el));b.useLayoutEffect(()=>{const q=()=>{const oe=r?.getBoundingClientRect();oe&&R({top:oe.top+8,right:Math.max(8,window.innerWidth-oe.right+8)})};return q(),window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[r]),b.useLayoutEffect(()=>{if(!r)return;const q=[...bs].filter(oe=>oe.attach&&r.contains(oe.el)).map(oe=>oe.attach());return()=>q.forEach(oe=>oe())},[r,h]),b.useEffect(()=>{r&&(ba(r),St.setState({total:Ht.length,active:0}),ls(0),Ht.length&&va(Ht[0]))},[r,t,s,c,h]),b.useEffect(()=>{if(!r)return;const q=()=>{r.isConnected||xa()};window.addEventListener("focusin",q);const oe=window.setInterval(q,1e3);return()=>{window.removeEventListener("focusin",q),window.clearInterval(oe)}},[r]),b.useEffect(()=>{if(!r||!t.trim())return;let q=0;const oe=new MutationObserver(()=>{window.clearTimeout(q),q=window.setTimeout(()=>{ba(r);const Re=Math.min(St.getState().active,Math.max(0,Ht.length-1));St.setState({total:Ht.length,active:Re}),ls(Re)},150)});return oe.observe(r,{childList:!0,subtree:!0,characterData:!0}),()=>{window.clearTimeout(q),oe.disconnect()}},[r,t,s,c]);const S=q=>{if(!Ht.length)return;const oe=(St.getState().active+q+Ht.length)%Ht.length;St.setState({active:oe}),ls(oe),va(Ht[oe])},I=q=>{if(!r||!Ht.length)return;const oe=St.getState(),Re=q?Ht.map((me,he)=>he):[oe.active],Ge=new Map;for(const me of Re){const he=mc(Ht[me]);if(!he)continue;const ze=Ge.get(he)??[];ze.push({range:Ht[me],text:Ei(oe.replacement,xs[me],oe.regex)}),Ge.set(he,ze)}let m=0;for(const[me,he]of Ge)m+=me.replace(he);if(!m&&!q){S(1);return}const ke=oe.active,rt=q?"":Ei(oe.replacement,xs[oe.active],oe.regex);ba(r);let de=0;if(!q&&Ht.length){const me=Vl(oe.query,oe),he=me&&me!=="bad"?(rt.match(new RegExp(me.source,me.flags))??[]).length:0;de=(ke+he)%Ht.length}St.setState({total:Ht.length,active:de}),ls(de),Ht.length&&va(Ht[de])},X=q=>q.key==="Escape"?(xa("keyboard"),!0):(q.metaKey||q.ctrlKey)&&q.altKey&&q.code==="KeyF"?(q.preventDefault(),w&&St.setState({replaceOpen:!St.getState().replaceOpen}),!0):!1,ee=q=>{St.setState({[q]:!St.getState()[q]}),T.current?.focus()};return f.jsxs("div",{className:`amx-findbar${i&&w?" amx-findbar--replace":""}`,style:{top:M.top,right:M.right},children:[w&&f.jsx("button",{className:"amx-findbar-expand",onClick:()=>St.setState({replaceOpen:!i}),title:e("find.toggleReplace"),"aria-label":e("find.toggleReplace"),"aria-expanded":i,children:i?f.jsx(af,{size:14}):f.jsx(Ll,{size:14})}),f.jsxs("div",{className:"amx-findbar-rows",children:[f.jsxs("div",{className:"amx-findbar-row",children:[f.jsx("input",{ref:T,autoFocus:!0,placeholder:e("find.placeholder"),value:t,"aria-invalid":a||void 0,title:a?e("find.badRegex"):void 0,onFocus:q=>q.currentTarget.select(),onChange:q=>St.setState({query:q.target.value}),onKeyDown:q=>{!X(q)&&q.key==="Enter"&&S(q.shiftKey?-1:1),q.stopPropagation()}}),f.jsx("button",{className:"amx-findbar-opt",onClick:()=>ee("caseSensitive"),"aria-pressed":s,title:e("find.case"),"aria-label":e("find.case"),children:f.jsx(Kp,{size:15})}),f.jsx("button",{className:"amx-findbar-opt",onClick:()=>ee("regex"),"aria-pressed":c,title:e("find.regex"),"aria-label":e("find.regex"),children:f.jsx(lh,{size:14})}),f.jsx("span",{className:"amx-findbar-count",children:o?`${n+1}/${o}`:t.trim()?"0":""}),f.jsx("button",{onClick:()=>S(-1),title:e("find.prev"),"aria-label":e("find.prev"),children:"‹"}),f.jsx("button",{onClick:()=>S(1),title:e("find.next"),"aria-label":e("find.next"),children:"›"}),f.jsx("button",{onClick:()=>xa("pointer"),title:e("find.close"),"aria-label":e("find.close"),children:"✕"})]}),i&&w&&f.jsxs("div",{className:"amx-findbar-row",children:[f.jsx("input",{className:"amx-findbar-replace",placeholder:e("find.replacePlaceholder"),value:d,onChange:q=>St.setState({replacement:q.target.value}),onKeyDown:q=>{!X(q)&&q.key==="Enter"&&I(q.metaKey||q.ctrlKey),q.stopPropagation()}}),f.jsx("button",{className:"amx-findbar-act",onClick:()=>I(!1),disabled:!p,title:e("find.replaceOne"),"aria-label":e("find.replaceOne"),children:f.jsx(mh,{size:14})}),f.jsx("button",{className:"amx-findbar-act",onClick:()=>I(!0),disabled:!p,title:e("find.replaceAll"),"aria-label":e("find.replaceAll"),children:f.jsx(dh,{size:14})})]})]})]})}kn({"unisave.conflict.toast":{zh:"「{name}」在你编辑时被别处改过。已保留你的版本,被覆盖的那一版另存为「{copy}」。",en:'"{name}" was changed elsewhere while you were editing. Your version was kept, and the overwritten version was saved as "{copy}".'},"unisave.conflict.agentToast":{zh:"Tangu 在你编辑时改了「{name}」。已保留你的版本,Tangu 的改动另存为「{copy}」。",en:'Tangu changed "{name}" while you were editing. Your version was kept, and Tangu’s changes were saved as "{copy}".'},"unisave.conflict.open":{zh:"打开副本",en:"Open copy"},"unisave.failed.toast":{zh:"「{name}」没能保存({reason}),正在自动重试。保存成功之前请不要关闭它。",en:'Couldn’t save "{name}" ({reason}). Retrying automatically — keep it open until it’s saved.'},"unisave.failed.unknown":{zh:"未知原因",en:"unknown reason"},"unisave.failed.bar":{zh:"未保存:写入失败,正在自动重试",en:"Unsaved: the write failed and is being retried"},"unisave.failed.retry":{zh:"立即重试",en:"Retry now"},"unisave.draft.bar":{zh:"这篇笔记有一份上次没保存成功的草稿({time})。",en:"This note has a draft that wasn’t saved last time ({time})."},"unisave.draft.hint":{zh:"恢复后会覆盖盘上当前内容;盘上那一版若是别处改过的,会先另存为冲突副本。",en:"Restoring replaces what’s on disk now. If that version was changed elsewhere, it is saved as a conflict copy first."},"unisave.draft.restore":{zh:"恢复草稿",en:"Restore draft"},"unisave.draft.discard":{zh:"丢弃",en:"Discard"},"unisave.gone.toast":{zh:"「{name}」已在别处被删除或移走,最后的改动没来得及保存,另存副本也没写成。可以把这篇的内容复制下来。",en:'"{name}" was deleted or moved elsewhere before your last changes were saved, and a backup copy couldn’t be written. You can copy its text.'},"unisave.renameCopy.toast":{zh:"「{name}」改名时已被别处改过,没有覆盖它。你改名期间打的字另存为「{copy}」。",en:'"{name}" was changed elsewhere while it was being renamed, so it wasn’t overwritten. What you typed during the rename was saved as "{copy}".'},"unisave.rescued.toast":{zh:"「{name}」已在别处被删除或移走。你还没保存的内容另存为「{copy}」。",en:'"{name}" was deleted or moved elsewhere. Your unsaved changes were saved as "{copy}".'},"unisave.gone.copy":{zh:"复制内容",en:"Copy text"},"unisave.gone.copied":{zh:"已复制到剪贴板",en:"Copied to clipboard"}});function ur(e){typeof window>"u"||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:e}))}const dr=e=>(e.split("/").pop()??e).replace(/\.md$/i,"");let Mi=Promise.resolve();function wa(e,t,n=new Date){const o=Mi.then(()=>zi(e,t,n),()=>zi(e,t,n));return Mi=o.catch(()=>{}),o}async function zi(e,t,n){const o=Ou(e,n);for(let r=1;r<=50;r++){const s=_u(o,r),c=await wn.readTextFile(s);if(c===t)return s;if(c!=null)continue;const a=await wn.writeTextFile(s,t,{create:!0});if(a&&a.ok===!1){if(a.current===t)return s;if(a.current!=null)continue;throw new Error("The conflict copy could not be created")}return s}throw new Error("Too many conflict copies in one minute")}function Lh(e,t,n=!1){ur({level:"error",dedupeKey:`amx-conflict:${e}`,text:we(n?"unisave.conflict.agentToast":"unisave.conflict.toast",{name:dr(e),copy:dr(t)}),action:{label:we("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function Hl(e){const n=(e instanceof Error?e.message:typeof e=="string"?e:"").replace(/^Error invoking remote method '[^']*':\s*/,"").replace(/^(?:[A-Za-z]*Error:\s*)+/,"").trim();return n?n.length>80?`${n.slice(0,79)}…`:n:we("unisave.failed.unknown")}function ka(e,t){ur({level:"warning",dedupeKey:`amx-savefail:${e}`,text:we("unisave.failed.toast",{name:dr(e),reason:Hl(t)})})}function Ih(e,t){ur({level:"error",dedupeKey:`amx-rescued:${t}`,text:we("unisave.rescued.toast",{name:dr(e),copy:dr(t)}),action:{label:we("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function Ph(e,t){ur({level:"error",dedupeKey:`amx-renamecopy:${t}`,text:we("unisave.renameCopy.toast",{name:dr(e),copy:dr(t)}),action:{label:we("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function Fh(e,t){ur({level:"error",dedupeKey:`amx-gone:${e}:${$r(t)}`,text:we("unisave.gone.toast",{name:dr(e)}),action:{label:we("unisave.gone.copy"),run:()=>{navigator.clipboard?.writeText(t).then(()=>ur({text:we("unisave.gone.copied")}),()=>{})}}})}const $i=[2e3,5e3,1e4,3e4,6e4],ql=(e,t)=>`amadeus.unsavedDraft:${e??""}:${t}`,Gs=(e,t,n)=>ql(e,t)+(n?`\0${n}`:"");function Io(e,t,n,o,r){try{const s={text:n,base:$r(o),at:Date.now()};localStorage.setItem(Gs(e,t,r),JSON.stringify(s))}catch{}}function us(e,t){if(!e)return null;const n=JSON.parse(e);return typeof n.text=="string"&&typeof n.base=="string"?{text:n.text,base:n.base,at:Number(n.at)||0,slot:t}:null}function Oh(e,t,n,o=()=>!0){try{const r=Gs(e,t);if(n){const a=us(localStorage.getItem(Gs(e,t,n)),n);if(a)return a;const i=o(null)?null:us(localStorage.getItem(r),null);if(i)return i}else{const a=us(localStorage.getItem(r),null);if(a)return a}const s=ql(e,t)+"\0";let c=null;for(let a=0;a<localStorage.length;a++){const i=localStorage.key(a);if(!i||!i.startsWith(s))continue;const d=i.slice(s.length);if(d===n||o(d))continue;const p=us(localStorage.getItem(i),d);p&&(!c||p.at>c.at)&&(c=p)}return c}catch{return null}}function Zr(e,t,n,o){try{const r=Gs(e,t,o);if(n!=null){const s=us(localStorage.getItem(r),o??null);if(!s||s.text!==n)return}localStorage.removeItem(r)}catch{}}function _h(){return typeof navigator<"u"&&/\bElectron\//.test(navigator.userAgent)}function Sr(e){const t=Bu(e);return t.length===e.length&&e.startsWith(Ws)?{fmText:Ws,body:e.slice(1)}:{fmText:e.slice(0,e.length-t.length),body:t}}function jn(e,t){return e+t}function Ca(e,t){const n=ks(e);return n.trim()&&!Bh(n)?e:Sr(Vu(e,t)).fmText}function Bh(e){try{const t=ta(e);return t==null||typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function Kh(e,t){const n=Vh(e,t);if(n!==null)return Za(e,n);const{bom:o}=ws(e),r=Qa(e),s=t.replace(/\n+$/,"");if(!r.length&&!s.trim())return o;const c=o+["---",...r,...s.trim()?[s]:[],"---",""].join(`
5
- `);return Ja(s)?Za(e,c):c}function Vh(e,t){const n=ks(e),o=t.replace(/(?:\r?\n)+$/,"");if(!n||!o.trim())return null;if(o===n)return e;const r=e.indexOf(n),s=r+n.length;if(r<=0||e[r-1]!==`
6
- `||!/^\r?\n/.test(e.slice(s))||e.indexOf(n,r+1)>=0)return null;const c=e.slice(0,r)+o+e.slice(s);return ks(c)===o&&Qa(c).join(`
7
- `)===Qa(e).join(`
8
- `)?c:null}function Ja(e){try{return ta(e),!0}catch{return!1}}function Za(e,t){if(t===e)return t;const n=ws(t).inner;if(n==null||Ja(n))return t;const o=ws(e).inner;return o==null||!Ja(o)?t:(console.warn("[amadeus] frontmatter rewrite would produce invalid YAML; keeping the original block"),e)}const Hh=/^---\r?\n([\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)$/;function ws(e){const t=e.startsWith(Ws)?Ws:"",n=Hh.exec(e.slice(t.length));return{bom:t,inner:n?n[1]??"":null}}function pc(e){const{inner:t}=ws(e);return t==null?null:t?qu(t.replace(/\r?\n$/,"").split(/\r?\n/)):[]}function Qa(e){return(pc(e)??[]).filter(t=>Hu.test(t[0])).flat()}const qh=/^["']?amadeus_(schema|layout|canvas)["']?\s*:/;function ds(e,t,n){const{bom:o}=ws(e),r=pc(e)??[],s=r.filter(i=>!qh.test(i[0])).flat(),a=[...cf(t,n).flatMap(i=>{const d=Yh.exec(i)?.[1],p=d?Yl(r,d):null;return p&&p.length>1&&Xl(p,d)===(d==="layout"?t:n)?p:[i]}),...s];return a.length?Za(e,o+["---",...a,"---",""].join(`
9
- `)):o}function Wh(e){const t=go(e),n=dn(e);return t==null&&n==null||/^["']?amadeus_schema["']?\s*:/m.test(e)?e:ds(e,t,n)}function go(e){return Wl(e,"layout")}function dn(e){return Wl(e,"canvas")}const Yh=/^amadeus_(layout|canvas):/;function Wl(e,t){const n=pc(e),o=n&&Yl(n,t);return o?Xl(o,t):null}function Yl(e,t){const n=new RegExp(`^["']?amadeus_${t}["']?\\s*:`);let o=null;for(const r of e)n.test(r[0])&&(o=r);return o}function Xl(e,t){if(e.length===1){const o=new RegExp(`^["']?amadeus_${t}["']?\\s*:\\s*(.+)$`).exec(e[0]);return o?o[1].trim():null}const n=e.join(`
10
- `);try{const o=ta(n),r=o&&typeof o=="object"&&!Array.isArray(o)?Object.values(o)[0]:void 0;if(r&&typeof r=="object")return JSON.stringify(r);if(typeof r=="string")return r}catch{}return n}function Xh(e){return e?Ku(Cl(e)):{}}function ks(e){return e?Cl(e):""}const Uh=80;function Gh(){return Et(()=>{if(!Vr())return new qt({});const e=Math.round(Uh*En(document.body));return new qt({props:{scrollThreshold:{top:0,left:0,right:0,bottom:e},scrollMargin:{top:5,left:5,right:5,bottom:e}}})})}function Js(e){const t=[];return e.descendants((n,o)=>{if(n.type.name!=="heading")return!0;const r=Number(n.attrs?.level),s=Number.isFinite(r)?Math.min(6,Math.max(1,r)):1,c=n.textContent.trim();return c&&t.push({level:s,text:c,pos:o}),!1}),t}function Ai(e,t=0,n=e.content.size){return e.textBetween(t,n,`
11
- `,()=>"").replace(/!\[\[[^\]\n]*\]\]/g,"").replace(/\[\[(?:[^\]|\n]*\|)?([^\]\n]*)\]\]/g,"$1")}function Jh(e){let t=null,n={chars:0,words:0};return()=>{const o=e();if(!o)return null;o.state.doc!==t&&(t=o.state.doc,n=Gc(Ai(t)));const{from:r,to:s,empty:c}=o.state.selection;return{all:n,sel:c?null:Gc(Ai(o.state.doc,r,s))}}}function Zh(){return[Et(()=>new qt({view:()=>{let e=0;const t=()=>{e||(e=requestAnimationFrame(()=>{e=0,Bc()}))};return t(),{update:(n,o)=>{(n.state.doc!==o.doc||!n.state.selection.eq(o.selection))&&t()},destroy:()=>{e&&cancelAnimationFrame(e),Bc()}}}}))]}function Qh(e){const t=(o,r,s)=>{const c=o.selection;return!(c instanceof Ne)||!c.empty||!s||Vo.atStart(o.doc).$from.start()!==c.$from.start()||!s.endOfTextblock("up")?!1:e()},n=o=>{const r=o.selection;if(!(r instanceof Ne)||!r.empty)return!1;const s=r.$from;return s.depth!==1||s.index(0)!==0||s.parentOffset!==0||s.parent.type.name!=="paragraph"?!1:e()};return[Et(()=>Oo({ArrowUp:t,ArrowLeft:n}))]}function Ni(e,t){const n=e.content.size;return e.textBetween(Math.max(0,t-12),Math.min(n,t+12),`
12
- `,"")}function eg(e){return[Et(()=>new qt({view:t=>{try{localStorage.getItem("amx_probe")&&(window.__amxView=t)}catch{}let n=!0,o=null;const r=()=>{o=null;const{vaultRoot:c,path:a}=e.where(),i=t.state.selection;uf(c,a,{a:i.anchor,h:i.head,t:Ni(t.state.doc,i.head)})};queueMicrotask(()=>{if(!n||!e.restore())return;const{vaultRoot:c,path:a}=e.where(),i=lf(c,a),d=t.state.doc;let p=null;if(i&&i.a<=d.content.size&&i.h<=d.content.size&&Ni(d,i.h)===i.t){try{p=Ne.between(d.resolve(i.a),d.resolve(i.h))}catch{p=null}p&&(p.anchor!==i.a||p.head!==i.h)&&(p=null)}p&&t.dispatch(t.state.tr.setSelection(p).setMeta("addToHistory",!1)),e.focus()&&t.focus()});const s=()=>{o&&(clearTimeout(o),r(),df())};return window.addEventListener("pagehide",s),{update:(c,a)=>{c.state.selection.eq(a.selection)&&c.state.doc===a.doc||(o&&clearTimeout(o),o=setTimeout(r,300))},destroy:()=>{n=!1,window.removeEventListener("pagehide",s),o&&(clearTimeout(o),r())}}}}))]}kn({"canvasseg.aria":{zh:"编辑模式",en:"Editing mode"},"canvasseg.doc":{zh:"文档",en:"Document"},"canvasseg.canvas":{zh:"画布",en:"Canvas"}});const tg="amx-modeseg-slot";function ng({on:e,toggle:t}){const{t:n}=tn();return f.jsxs("div",{className:"t2s-vaultseg amx-modeseg",role:"tablist","aria-label":n("canvasseg.aria"),children:[f.jsx("div",{className:"t2s-vaultseg-thumb","data-side":e?"canvas":"doc"}),f.jsx("button",{type:"button",role:"tab","aria-selected":!e,className:e?"":"on",onMouseDown:o=>o.preventDefault(),onClick:()=>{e&&t()},children:n("canvasseg.doc")}),f.jsx("button",{type:"button",role:"tab","aria-selected":e,className:e?"on":"",onMouseDown:o=>o.preventDefault(),onClick:()=>{e||t()},children:n("canvasseg.canvas")})]})}function og({anchor:e,on:t,toggle:n}){const[o,r]=b.useState(null);return b.useEffect(()=>{const s=e?.closest(".amx-pane")??e?.ownerDocument?.body;if(!s)return;const c=()=>r(s.querySelector(`.${tg}`));c();const a=new MutationObserver(c);return a.observe(s,{childList:!0,subtree:!0}),()=>a.disconnect()},[e]),o?Il.createPortal(f.jsx(ng,{on:t,toggle:n}),o):null}kn({"amprops.add":{zh:"添加属性",en:"Add property"},"amprops.addLabel":{zh:"写入笔记 frontmatter 的键名",en:"Key name written to the note frontmatter"},"amprops.reservedKey":{zh:"amadeus_* 是保留键",en:"amadeus_* keys are reserved"},"amprops.pluginManaged":{zh:"该键由插件管理",en:"This key is managed by a plugin"},"amprops.chipRaw":{zh:"属性(原文)",en:"Properties (raw)"},"amprops.chipCount":{zh:"属性 {n}",en:"Properties {n}"},"amprops.empty":{zh:"还没有属性。",en:"No properties yet."},"amprops.delete":{zh:"删除属性",en:"Delete property"},"amprops.pluginKeysWarn":{zh:"⚠️ 本文件含插件数据键({keys}),修复 YAML 时请勿改动那几行。",en:"⚠️ This file contains plugin data keys ({keys}) — leave those lines untouched while fixing the YAML."},"amprops.nestedHint":{zh:"嵌套结构请在源码模式编辑",en:"Edit nested values in source mode"},"amprops.chipsPlaceholder":{zh:"回车添加…",en:"Press Enter to add…"},"amprops.conflict":{zh:"此处已在别处改为「{v}」。失焦后以你的输入为准,按 Esc 放弃你的输入。",en:'Changed elsewhere to "{v}". Leaving the field keeps your input; press Esc to discard it.'},"amprops.conflictRaw":{zh:"这段已在别处被改动。失焦后以你的输入为准;撤销你的改动再失焦则采用别处的版本。",en:"Changed elsewhere. Leaving the field keeps your input; undo your edits first to take the other version."},"amprops.keyPlaceholder":{zh:"属性名",en:"Property name"},"amprops.type":{zh:"属性类型",en:"Property type"},"amprops.type.text":{zh:"文本",en:"Text"},"amprops.type.number":{zh:"数字",en:"Number"},"amprops.type.checkbox":{zh:"勾选",en:"Checkbox"},"amprops.type.date":{zh:"日期",en:"Date"},"amprops.type.list":{zh:"列表",en:"List"},"amprops.addConfirm":{zh:"添加",en:"Add"},"amprops.addCancel":{zh:"取消",en:"Cancel"},"amprops.linksHint":{zh:"点链接跳转,点空白处编辑",en:"Click a link to open it; click elsewhere to edit"}});const rg=["text","number","checkbox","date","list"];function sg(e,t=new Date){switch(e){case"number":return 0;case"checkbox":return!1;case"date":return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`;case"list":return[];default:return""}}const ag=e=>/^(tags?|alias(es)?|cssclass(es)?)$/i.test(e.trim())?"list":"text",Ul=e=>/\[\[[^\]\n]+\]\]/.test(e);function Sa(e){if(!e.trim())return{ok:!0,entries:[]};try{const t=ta(e);if(t&&typeof t=="object"&&!Array.isArray(t))return{ok:!0,entries:Object.entries(t).map(([n,o])=>({key:n,value:o}))}}catch{}return{ok:!1,entries:[]}}const Gl=e=>Array.isArray(e)&&e.every(t=>t===null||typeof t!="object");function Ea(e,t,n,o=r=>r){if(e===null)return null;const r=o(e);return r===o(t)||r===o(n)?null:r}const Jl=b.createContext(null);function hc(e,t,{escDiscards:n="conflict",norm:o=s=>s,enterCommits:r=!1}={}){const[s,c]=b.useState(null),[a,i]=b.useState(e),d=b.useRef({draft:s,base:a,current:e,norm:o,commit:t});d.current.current=e,d.current.norm=o,d.current.commit=t;const p=w=>{d.current.draft=w,c(w)},h=w=>{d.current.base=w,i(w)},M=b.useContext(Jl);b.useLayoutEffect(()=>{if(!M)return;const w=()=>{const S=d.current,I=Ea(S.draft,S.base,S.current,S.norm);I!==null&&(h(I),S.commit(I))};return M.add(w),()=>{M.delete(w),w()}},[M]);const R=s!==null&&e!==a&&Ea(s,a,e,o)!==null;return{shown:s??e,conflict:R,change:w=>{d.current.draft===null&&h(d.current.current),p(w)},settle:()=>{const w=d.current,S=Ea(w.draft,w.base,w.current,w.norm);return p(null),S},onKeyDown:w=>{if(!(w.nativeEvent.isComposing||w.keyCode===229)){if(w.key==="Enter"&&r){w.preventDefault(),w.currentTarget.blur();return}w.key!=="Escape"||n==="never"||!R||(w.preventDefault(),w.stopPropagation(),p(null))}}}}function cg({fmExtra:e,onCommit:t,readOnly:n=!1,notePath:o}={}){const{t:r}=tn(),s=Mn(ze=>ze.activePage),c=Mn(ze=>ze.vaultRoot),a=Mn(ze=>ze.manifest?.fmExtra??""),i=lc(),d=e!==void 0,p=d?e:a,h=b.useRef(p);h.current=p;const[M,R]=b.useState(()=>Jc(c)??!1);b.useEffect(()=>{R(Jc(c)??!1)},[c]);const T=ze=>{R(He=>{const Te=typeof ze=="function"?ze(He):ze;return pf(c,Te),Te})},[w,S]=b.useState(!1),[I,X]=b.useState(null),ee=b.useRef(null),q=o??s??void 0,oe=ze=>{if(hf(ze))return;const He=Sl(ze);He&&i.getState().openWikiLink(He,q)},Re=b.useMemo(()=>Sa(p),[p]),Ge=b.useMemo(()=>{const ze=!d&&s?ff(s):void 0;return new Set(ze?.fmKeys??[])},[d,s]),m=b.useMemo(()=>Re.entries.map((ze,He)=>({...ze,idx:He})).filter(ze=>!Ge.has(ze.key)),[Re,Ge]);if(b.useEffect(()=>{if(!I)return;const He=[...ee.current?.querySelectorAll(".amx-prop-row[data-key]")??[]].find(Te=>Te.dataset.key===I)?.querySelector("input:not(.amx-prop-key), textarea, .amx-prop-links");He&&(He.focus(),He.classList.contains("amx-prop-links")&&He.click(),X(null))},[I,Re]),!d&&!s)return null;const ke=ze=>{t?t(ze):i.getState().setFmExtra(ze)},rt=ze=>{ze!==null&&ke(ze)},de=(ze,He)=>rt(Xu(h.current,{[ze]:He})),me=(ze,He)=>{const Te=ze.trim();return Te?/^amadeus_/.test(Te)?(window.alert(r("amprops.reservedKey")),!1):Ge.has(Te)?(window.alert(r("amprops.pluginManaged")),!1):(Sa(h.current).entries.some(dt=>dt.key===Te)||de(Te,sg(He)),X(Te),!0):!1},he=Re.ok?m.length:null;return f.jsxs("div",{className:`amx-props${he===0&&!M?" is-empty":""}`,ref:ee,children:[f.jsxs("div",{className:"amx-props-bar",children:[f.jsxs("button",{className:"amx-props-chip",onClick:()=>T(ze=>!ze),children:[he===null?r("amprops.chipRaw"):r("amprops.chipCount",{n:he}),M?" ▾":" ▸"]}),!n&&f.jsx("button",{className:"amx-props-add",title:r("amprops.add"),onClick:()=>{T(!0),Re.ok&&S(!0)},children:f.jsx(mf,{size:12})})]}),M&&(Re.ok?f.jsxs("div",{className:"amx-props-rows",children:[m.length===0&&!w&&f.jsx("div",{className:"amx-props-empty",children:r("amprops.empty")}),m.map(ze=>n?f.jsxs("div",{className:"amx-prop-row amx-prop-row-ro",children:[f.jsx("span",{className:"amx-prop-key",children:ze.key}),f.jsx(ug,{value:ze.value})]},`${s}:${ze.idx}:${ze.key}`):f.jsxs("div",{className:"amx-prop-row","data-key":ze.key,children:[f.jsx(lg,{name:ze.key,onRename:He=>{const Te=/^(amadeus_page|amadeus_schema|amadeus_layout|amadeus_canvas|amadeus_next_id)$/.test(He)||Ge.has(He)||Sa(h.current).entries.some(dt=>dt.key!==ze.key&&dt.key===He);!He||Te||rt(Wu(h.current,ze.key,He))}}),f.jsx(mg,{value:ze.value,onCommit:He=>de(ze.key,He),onOpenLink:oe}),f.jsx("button",{className:"amx-prop-del",title:r("amprops.delete"),onClick:()=>de(ze.key,void 0),children:f.jsx(uc,{size:12})})]},`${s}:${ze.key}`)),w&&!n&&f.jsx(dg,{onAdd:(ze,He)=>{me(ze,He)&&S(!1)},onCancel:()=>S(!1)})]}):f.jsxs(f.Fragment,{children:[Ge.size>0&&f.jsx("div",{className:"amx-props-empty",children:r("amprops.pluginKeysWarn",{keys:[...Ge].join(", ")})}),f.jsx(ig,{text:p,readOnly:n,onCommit:ke})]}))]})}function ig({text:e,readOnly:t,onCommit:n}){const{t:o}=tn(),r=c=>{t||n(c)},s=hc(e,r,{escDiscards:"never"});return f.jsx("textarea",{className:`amx-props-raw${s.conflict?" amx-prop-conflict":""}`,value:s.shown,spellCheck:!1,readOnly:t,title:s.conflict?o("amprops.conflictRaw"):void 0,onChange:c=>{t||s.change(c.target.value)},onBlur:()=>{const c=s.settle();c!==null&&r(c)}})}function lg({name:e,onRename:t}){const n=hc(e,t,{norm:o=>o.trim(),enterCommits:!0});return f.jsx("input",{className:"amx-prop-key",value:n.shown,onChange:o=>n.change(o.target.value),onKeyDown:n.onKeyDown,onBlur:()=>{const o=n.settle();o!==null&&t(o)}})}function ug({value:e}){return typeof e=="boolean"?f.jsx("span",{className:"amx-prop-check","aria-hidden":!0,children:e?"☑":"☐"}):Gl(e)?f.jsx("span",{className:"amx-prop-chips",children:e.map((t,n)=>f.jsx("span",{className:"amx-chip",children:String(t??"")},n))}):e==null?f.jsx("span",{className:"amx-prop-input"}):typeof e=="object"?f.jsx("span",{className:"amx-prop-input",children:JSON.stringify(e)}):f.jsx("span",{className:"amx-prop-input",children:String(e)})}function dg({onAdd:e,onCancel:t}){const{t:n}=tn(),[o,r]=b.useState(""),[s,c]=b.useState("text"),[a,i]=b.useState(!1),d=a?s:ag(o);return f.jsxs("div",{className:"amx-prop-row amx-prop-new",children:[f.jsx("input",{className:"amx-prop-key",autoFocus:!0,value:o,placeholder:n("amprops.keyPlaceholder"),"aria-label":n("amprops.addLabel"),onChange:p=>r(p.target.value),onKeyDown:p=>{p.nativeEvent.isComposing||p.keyCode===229||(p.key==="Enter"?(p.preventDefault(),e(o,d)):p.key==="Escape"&&(p.preventDefault(),t()))}}),f.jsx("select",{className:"amx-prop-type","aria-label":n("amprops.type"),value:d,onChange:p=>{c(p.target.value),i(!0)},onKeyDown:p=>{p.key==="Escape"&&(p.preventDefault(),t())},children:rg.map(p=>f.jsx("option",{value:p,children:n(`amprops.type.${p}`)},p))}),f.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addConfirm"),"aria-label":n("amprops.addConfirm"),onClick:()=>e(o,d),children:f.jsx(oa,{size:12})}),f.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addCancel"),"aria-label":n("amprops.addCancel"),onClick:t,children:f.jsx(uc,{size:12})})]})}function Zl({text:e,onOpenLink:t}){const n=[],o=/\[\[([^\]\n]+)\]\]/g;let r=0,s;for(;s=o.exec(e);){s.index>r&&n.push(e.slice(r,s.index));const c=s[1],a=c.indexOf("|");n.push(f.jsx("span",{className:"amx-prop-link",onMouseDown:i=>{i.preventDefault(),i.stopPropagation(),t(c)},onClick:i=>i.stopPropagation(),children:a>=0?c.slice(a+1):c},s.index)),r=s.index+s[0].length}return r<e.length&&n.push(e.slice(r)),f.jsx(f.Fragment,{children:n})}function fg({value:e,onCommit:t,onOpenLink:n}){const{t:o}=tn(),[r,s]=b.useState(!1);return r?f.jsx(ec,{current:e,autoFocus:!0,onCommit:t,onDone:()=>s(!1)}):f.jsx("div",{className:"amx-prop-input amx-prop-links",tabIndex:0,title:o("amprops.linksHint"),onClick:()=>s(!0),onKeyDown:c=>{c.key==="Enter"&&!c.nativeEvent.isComposing&&(c.preventDefault(),s(!0))},children:f.jsx(Zl,{text:e,onOpenLink:n})})}function mg({value:e,onCommit:t,onOpenLink:n}){const{t:o}=tn();return typeof e=="boolean"?f.jsx("input",{type:"checkbox",className:"amx-prop-check",checked:e,onChange:r=>t(r.target.checked)}):Gl(e)?f.jsx(hg,{items:e.map(r=>String(r??"")),onCommit:t,onOpenLink:n}):typeof e=="number"?f.jsx(ec,{current:String(e),norm:r=>r.trim(),onCommit:r=>{const s=Number(r);t(r!==""&&!Number.isNaN(s)?s:r)}}):typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?f.jsx(pg,{value:e,onCommit:t}):typeof e=="string"&&!e.includes(`
13
- `)&&Ul(e)?f.jsx(fg,{value:e,onCommit:t,onOpenLink:n}):typeof e=="string"||e==null?f.jsx(ec,{current:e??"",multiline:typeof e=="string"&&e.includes(`
14
- `),onCommit:t}):f.jsx("span",{className:"amx-prop-nested",title:o("amprops.nestedHint"),children:Yu(e).trimEnd()})}function ec({current:e,norm:t,multiline:n=!1,autoFocus:o,onCommit:r,onDone:s}){const{t:c}=tn(),a=hc(e,r,{norm:t,enterCommits:!n}),i={className:`amx-prop-input${n?" amx-prop-multiline":""}${a.conflict?" amx-prop-conflict":""}`,value:a.shown,title:a.conflict?c("amprops.conflict",{v:e}):void 0,autoFocus:o,onKeyDown:a.onKeyDown,onBlur:()=>{const d=a.settle();d!==null&&r(d),s?.()}};return n?f.jsx("textarea",{...i,rows:Math.min(8,a.shown.replace(/\n$/,"").split(`
15
- `).length),spellCheck:!1,onChange:d=>a.change(d.target.value)}):f.jsx("input",{...i,onChange:d=>a.change(d.target.value)})}function pg({value:e,onCommit:t}){const[n,o]=b.useState(!1);return f.jsx("input",{type:"date",className:"amx-prop-input",value:n?"":e,onChange:r=>{const s=r.target.value;o(!s),s&&s!==e&&t(s)},onBlur:()=>o(!1)})}function hg({items:e,onCommit:t,onOpenLink:n}){const{t:o}=tn(),[r,s]=b.useState(""),c=()=>{const i=r.trim();s(""),i&&!e.includes(i)&&t([...e,i])},a=i=>{i.nativeEvent.isComposing||i.keyCode===229||(i.key==="Enter"||i.key===","?(i.preventDefault(),c()):i.key==="Backspace"&&!r&&e.length&&t(e.slice(0,-1)))};return f.jsxs("div",{className:"amx-prop-chips",children:[e.map((i,d)=>f.jsxs("span",{className:"amx-chip",children:[n&&Ul(i)?f.jsx(Zl,{text:i,onOpenLink:n}):i,f.jsx("button",{className:"amx-chip-x",onClick:()=>t(e.filter((p,h)=>h!==d)),children:f.jsx(uc,{size:10})})]},`${d}:${i}`)),f.jsx("input",{value:r,placeholder:e.length?"":o("amprops.chipsPlaceholder"),onChange:i=>s(i.target.value),onKeyDown:a,onBlur:c})]})}const gg=new Set(["bullet","ordered","task"]);function yg(e){if(!e)return null;switch(e.type.name){case"paragraph":return"text";case"heading":return e.attrs.level>=1&&e.attrs.level<=3?`h${e.attrs.level}`:null;case"bullet_list":return e.firstChild?.attrs.checked!=null?"task":"bullet";case"ordered_list":return"ordered";case"code_block":return"code";case"amadeusCanvasCard":return"card";case"blockquote":{const t=e.firstChild?.isTextblock?e.firstChild.textContent:"";return/^\[!fold\]/i.test(t)?"fold":/^\[![\w-]+\]/.test(t)?"callout":"quote"}default:return null}}function Ql(e,t,n,o){if(o.kind!=="quote"&&o.kind!=="fold"){const a=e.state.tr,i=a.doc.content.size;e.state.doc.nodesBetween(t,n,(d,p)=>d.type.name==="blockquote"?(tu(a,a.mapping.map(p)),!1):!d.isTextblock),a.docChanged&&(e.dispatch(a),n+=a.doc.content.size-i)}const r=[];e.state.doc.nodesBetween(t,n,(a,i)=>a.isTextblock?(r.push(i+1),!1):!0);const s=e.state.doc.content.size;let c=!1;for(const a of r.reverse())e.dispatch(e.state.tr.setSelection(Ne.near(e.state.doc.resolve(a)))),na(e,o,null)&&(c=!0);return c&&gg.has(o.kind)&&xg(e,t,n+(e.state.doc.content.size-s)),c}function xg(e,t,n){const{doc:o}=e.state,r=o.resolve(t),s=r.parent,c=[];let a=r.start();for(let d=0;d<r.index();d++)a+=s.child(d).nodeSize;for(let d=r.index();d<s.childCount-1;d++){const p=s.child(d);if(a+=p.nodeSize,a>=n)break;const h=s.child(d+1);p.type===h.type&&/_list$/.test(p.type.name)&&c.push(a)}if(!c.length)return;const i=e.state.tr;for(const d of c.reverse())xf(i.doc,d)&&i.join(d);i.docChanged&&e.dispatch(i)}function tc(e,t,n){const{state:o}=e,r=o.schema.nodes.code_block;if(!r)return!1;const s=o.doc.resolve(t),c=o.doc.resolve(n);if(s.parent!==c.parent||!s.parent.canReplaceWith(s.index(),c.index(),r))return!1;const a=o.doc.textBetween(t,n,`
16
- `,`
17
- `).replace(/^\n+|\n+$/g,""),i=o.tr.replaceWith(t,n,r.create(null,a?o.schema.text(a):void 0));return i.setSelection(Ne.near(i.doc.resolve(t+1))),e.dispatch(i.scrollIntoView()),!0}const bg=/^\[![\w-]+\]/;function Ti(e,t,n,o){const r=e.state.schema.nodes.blockquote;if(!r)return!1;let s;const c=e.state.doc.nodeAt(t);if(c?.type===r&&t+c.nodeSize===n)s=t;else if(o){const d=e.state.doc.resolve(t).blockRange(e.state.doc.resolve(n)),p=d&&yf(d,r);if(!d||!p)return!1;e.dispatch(e.state.tr.wrap(d,p)),s=t}else{if(e.dispatch(e.state.tr.setSelection(Ne.near(e.state.doc.resolve(t+1)))),!na(e,{kind:"quote"},null))return!1;const d=e.state.selection.$from;let p=d.depth;for(;p>0&&d.node(p).type!==r;)p--;if(p<1)return!1;s=d.before(p)}const a=e.state.doc.nodeAt(s),i=a?.firstChild;return!a||a.type!==r||!i?.isTextblock||bg.test(i.textContent)?!!a:(e.dispatch(e.state.tr.insertText(i.content.size?"[!note] ":"[!note]",s+2)),!0)}const eu=/^\[![\w-]+\]([+-])?[ \u00a0]?/;function tu(e,t){const n=e.doc.nodeAt(t),o=n?.firstChild,r=n?.type.name==="blockquote"&&o?.isTextblock?eu.exec(o.textContent):null;return!n||!o||!r?!1:(o.content.size===r[0].length&&n.childCount>1?e.delete(t+1,t+1+o.nodeSize):e.delete(t+2,t+2+r[0].length),!0)}function ji(e,t,n,o){const r=e.state.doc.nodeAt(t),s=r?.firstChild,c=r?.type.name==="blockquote"&&t+r.nodeSize===n&&s?.isTextblock?eu.exec(s.textContent):null;if(!r||!s||!c)return null;const a=e.state.tr;if(o!=="code"&&o.kind==="fold"){if(/^\[!fold\]/i.test(s.textContent))return!0;const M=c[0].length-(/[ \u00a0]$/.test(c[0])?1:0);return a.replaceWith(t+2,t+2+M,e.state.schema.text(bd)),e.dispatch(a.scrollIntoView()),!0}if(tu(a,t),o!=="code"&&o.kind==="quote")return a.setSelection(Ne.near(a.doc.resolve(t+1))),e.dispatch(a.scrollIntoView()),!0;const i=a.doc.nodeAt(t),d=i.content.size,p=a.doc.resolve(t+1).blockRange(a.doc.resolve(t+i.nodeSize-1)),h=p?gf(p):null;return!p||h==null?!1:(a.lift(p,h),a.setSelection(Ne.near(a.doc.resolve(t+1))),e.dispatch(a.scrollIntoView()),o==="code"?tc(e,t,t+d):o.kind==="text"?!0:o.kind==="heading"?na(e,o,null):Ql(e,t,t+d,o))}function vg(e){const t=e.split(`\r
18
- `).length-1;return t&&t===e.split(`
19
- `).length-1&&t===e.split("\r").length-1?`\r
20
- `:`
21
- `}function Hr(e){const t=vg(e);return{text:t===`\r
22
- `?e.replace(/\r\n/g,`
23
- `):e,eol:t}}function Fo(e,t){return t===`\r
24
- `?e.replace(/\r?\n/g,`\r
25
- `):e}function fs(e,t,n){let o=n,r;try{r=e.doc.resolve(t)}catch{return n}const s=r.parent;let c=t;for(let a=r.index();a<s.childCount&&c<o;a++){const i=s.child(a);if(i.type.name==="heading"){const d=Ur(e,c);d!=null&&d>o&&(o=d)}c+=i.nodeSize}return o}function Br(e,t,n){for(const o of[Xr,Ym]){const r=o.getState(e)?.folded;if(!r?.length)continue;const s=[];for(const c of r){const a=c>=n.from&&c<n.to;(!a||n.copy)&&s.push(t.mapping.map(c)),a&&!n.drop&&n.newStart!=null&&s.push(n.newStart+(c-n.from))}t.setMeta(o,{set:s})}}function Qr(e,t,n){const o=t.getMeta(Xr)?.set;if(!o?.length)return;const r=hi(e.doc,Xr.getState(e)?.folded??[]),s=d=>r.some(p=>d>=p.start&&d<p.after),c=n.to-n.from,a=t.mapping.invert(),i=o.filter(d=>hi(t.doc,[d]).every(p=>{const h=t.doc.resolve(p.start),M=h.parent;let R=p.start;for(let T=h.index();T<M.childCount&&R<p.after;T++){const w=R;R+=M.child(T).nodeSize;const S=w>=n.newStart&&w<n.newStart+c?n.from+(w-n.newStart):a.map(w);if(!s(S))return!1}return!0}));i.length!==o.length&&t.setMeta(Xr,{set:i})}kn({"blocklinks.copyHeading":{zh:"复制标题链接",en:"Copy heading link"},"blocklinks.copyBlock":{zh:"复制块链接",en:"Copy block link"},"blocklinks.moveTo":{zh:"移动到…",en:"Move to…"},"blocklinks.copied":{zh:"已复制 {link}",en:"Copied {link}"},"blocklinks.copyFailed":{zh:"没能写入剪贴板",en:"Couldn't write to the clipboard"},"blocklinks.pickTitle":{zh:"移动到哪篇笔记",en:"Move to which note"},"blocklinks.pickPlaceholder":{zh:"输入笔记名…",en:"Type a note name…"},"blocklinks.noMatch":{zh:"没有匹配的笔记",en:"No matching notes"},"blocklinks.moved":{zh:"已移动到「{name}」末尾",en:'Moved to the end of "{name}"'},"blocklinks.moveFailed":{zh:"没能移动到「{name}」,原块没动",en:`Couldn't move to "{name}" — the blocks were left in place`},"blocklinks.moveConflict":{zh:"「{name}」刚被别处改过,没有移动,请重试",en:'"{name}" was just changed elsewhere — nothing was moved, try again'},"blocklinks.targetUnsaved":{zh:"已追加到「{name}」,但它还没存上,原块先保留在这里",en:`Added to "{name}", but it hasn't been saved yet, so the blocks were kept here too`},"blocklinks.keptSource":{zh:"已追加到「{name}」,但这几块期间被改过,没有从本篇删掉",en:'Added to "{name}", but these blocks changed meanwhile, so they were kept here too'}});const _o=e=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:e}}))},gc=e=>(e.split("/").pop()??e).replace(/\.md$/i,""),es=e=>e.split("/").slice(0,-1).join("/");function wg(e,t,n){if(t===n)return e;const o=[!1,!0].map(r=>[Di(t,r),Di(n,r)]);return ed(e,r=>r.replace(/(^|[^!])\[([^\]\n]*)\]\(([^)\s]+)((?:\s+"[^"]*")?)\)/g,(s,c,a,i,d)=>{if(/^[/<]/.test(i)||!Ri(i))return s;const p=i.indexOf("#"),h=p<0?i:i.slice(0,p);let M=!1;try{decodeURIComponent(h)}catch{M=!0}const[R,T]=o[+M],w=td(T,Ml(zl(R,h)));if(M&&w.includes(" "))return s;const S=w.replace(/ /g,"");return`${c}[${a}](${!S.includes("/")||!Ri(S)?"./":""}${S}${p<0?"":i.slice(p)}${d})`}))}const Ri=e=>/^(?:note|file)$/.test(Nl(e)),Di=(e,t)=>e.split("/").map(n=>{const o=t?n.replace(/%/g,""):n;return Li(o)===o?n:` ${Li(n)}`}).join("/"),Li=e=>e.replace(/[\s%#?&|"'`[\]*:<>()\u0000-\u001f\u007f-\u009f]/g,t=>Array.from(new TextEncoder().encode(t),n=>`%${n.toString(16).toUpperCase().padStart(2,"0")}`).join(""));function kg(e){let t=null;for(const n of e.split(`
26
- `)){const o=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(n);o&&(t?o[1][0]===t[0]&&o[1].length>=t.length&&!o[2].trim()&&(t=null):t=o[1])}return t!=null||e.lastIndexOf("<!--")>e.lastIndexOf("-->")}function Cg(e,t){const{text:n,eol:o}=Hr(e),r=n?n.endsWith(`
27
-
28
- `)?"":n.endsWith(`
29
- `)?`
30
- `:`
31
-
32
- `:"";return Fo(`${n}${r}${t}
33
- `,o)}function Sg(e,t){const n=gc(e);return gs(n,t)===e?n:e.replace(/\.md$/i,"")}function Eg(e,t,n){const o=Sg(t,n);if(e.type.name==="heading"){const s=vd(e.textContent);return s?{kind:"heading",link:`[[${o}#${s}]]`}:null}const r=El(e.textContent);return r?{kind:"block",link:`[[${o}#^${r}]]`}:null}function Mg(e){const t=navigator.clipboard?.writeText(e);if(!t){_o(we("blocklinks.copyFailed"));return}t.then(()=>_o(we("blocklinks.copied",{link:e})),()=>_o(we("blocklinks.copyFailed")))}function zg(e){let t=!0;return e.descendants(n=>(/^amadeus(CanvasCard|ColumnRow|ColumnCell)$/.test(n.type.name)&&(t=!1),t)),t}async function $g(e){const{view:t,from:n,to:o,source:r,target:s}=e,c=gc(s);if(s===r)return!1;const a=t.state.doc.slice(n,o).content,i=e.serialize(a);if(!i?.trim())return _o(we("blocklinks.moveFailed",{name:c})),!1;let d=wg(_r(i,es(s)).trim(),es(r),es(s));e.pages&&es(r)!==es(s)&&(d=Uu(d,r,s,{pairs:new Map,pagesBefore:e.pages,pagesAfter:e.pages}));try{if(Gu(s)){if(!Ju(s,d,"end"))throw new Error("insert refused");try{await Zu(s,!0)}catch{return _o(we("blocklinks.targetUnsaved",{name:c})),!1}}else{const h=await wn.readTextFile(s);if(h==null)throw new Error("missing");if(kg(Hr(h).text))throw new Error("unsafe tail");const M=await wn.writeTextFile(s,Cg(h,d),{base:$r(h)});if(M&&!M.ok)return _o(we("blocklinks.moveConflict",{name:c})),!1}}catch{return _o(we("blocklinks.moveFailed",{name:c})),!1}if(t.isDestroyed||o>t.state.doc.content.size||!t.state.doc.slice(n,o).content.eq(a))return _o(we("blocklinks.keptSource",{name:c})),!0;const p=t.state.tr.delete(n,o);return Br(t.state,p,{from:n,to:o,drop:!0}),t.dispatch(p.scrollIntoView()),_o(we("blocklinks.moved",{name:c})),!0}function nu({pages:e,exclude:t,onPick:n,onClose:o}){const{t:r}=tn(),[s,c]=b.useState(""),[a,i]=b.useState(0),d=bh(s,e.filter(p=>p!==t&&/\.md$/i.test(p)),Qu).slice(0,30);return b.useEffect(()=>{i(0)},[s]),Il.createPortal(f.jsx("div",{className:"cmd-overlay",onMouseDown:o,children:f.jsxs("div",{className:"cmd-panel",role:"dialog","aria-label":r("blocklinks.pickTitle"),"data-testid":"note-picker",onMouseDown:p=>p.stopPropagation(),children:[f.jsx("input",{className:"cmd-input",autoFocus:!0,placeholder:r("blocklinks.pickPlaceholder"),"aria-label":r("blocklinks.pickTitle"),value:s,onChange:p=>c(p.target.value),onKeyDown:p=>{p.key==="ArrowDown"?(p.preventDefault(),i(h=>Math.min(h+1,d.length-1))):p.key==="ArrowUp"?(p.preventDefault(),i(h=>Math.max(h-1,0))):p.key==="Enter"?(p.preventDefault(),d[a]&&n(d[a])):p.key==="Escape"&&(p.preventDefault(),p.stopPropagation(),o())}}),f.jsxs("div",{className:"cmd-list",role:"listbox",children:[d.map((p,h)=>f.jsx("button",{className:"cmd-item",role:"option","aria-selected":h===a,"data-active":h===a||void 0,onMouseEnter:()=>i(h),onClick:()=>n(p),children:f.jsxs("span",{className:"cmd-row",children:[f.jsx("span",{className:"cmd-title",children:gc(p)}),f.jsx("span",{className:"cmd-path",children:p})]})},p)),!d.length&&f.jsx("div",{className:"cmd-empty",children:r("blocklinks.noMatch")})]})]})}),document.body)}function Ag(e){return e.nodeType===1}function Ng(e){return Ag(e)&&e.namespaceURI==="http://www.w3.org/1999/xhtml"}function Tg(e){const t=[[-1,e.state.doc]],n=[];for(;t.length>0;){const[o,r]=t.pop();if(o>=0){const s=e.nodeDOM(o);if(s&&Ng(s)){const{top:c,bottom:a,left:i,right:d}=s.getBoundingClientRect();n.push([o,[i,c,d,c]],[o+r.nodeSize,[i,a,d,a]])}}if(r.isBlock&&!r.isTextblock){let s=o+1;for(const c of r.children)t.push([s,c]),s+=c.nodeSize}}return n}function jg(e,t){let n=[],o,r;const s=()=>{const p=e.dom.getBoundingClientRect(),h=e.state.doc;return n&&o&&r&&p.width===r.width&&p.height===r.height&&p.x===r.x&&p.y===r.y&&o.eq(h)||(r=p,o=h,n=Tg(e)),n},c=(p,h)=>{if(!e.editable||e.isDestroyed)return;const M=(w,S)=>{const[I,X]=w,[ee,q]=S;return Pi(p,X)-Pi(p,q)||I-ee};let R=s();R.sort(M),R=R.slice(0,8);const T=R.find(w=>t?.({view:e,pos:w[0],event:h})!==!1);if(!(T&&Dg(e,T[0])))return T};let a,i;return(p,h)=>(a&&Rg(a,p)||(a=p,i=c(p,h)),i)}function Rg(e,t){return e[0]===t[0]&&e[1]===t[1]}function Ii(e,t){return Math.abs(e[0]-t[0])+Math.abs(e[1]-t[1])}function Pi(e,t){return Math.min(Ii(e,[t[0],t[1]]),Ii(e,[t[2],t[3]]))}function Dg(e,t){const n=e.dragging;if(!n)return;const{move:o}=n;if(!o)return;const r=e.state.selection;if(!(r instanceof Ee))return;const{from:s,to:c}=r;return s<=t&&t<=c}function Lg(e){let t;return new qt({key:new Dn("prosemirror-drop-indicator"),view:n=>(t=jg(n,e.onDrag),Pg(n,t,e)),props:{handleDrop(n,o,r,s){if(!t)return!1;const c=t([o.clientX,o.clientY],o);if(!c)return!1;o.preventDefault();const a=c[0],i=n.state.tr;if(s){const{node:R}=n.dragging||{};R?R.replace(i):i.deleteSelection()}const d=i.mapping.map(a),p=r.openStart==0&&r.openEnd==0&&r.content.childCount==1,h=i.doc;if(p?i.replaceRangeWith(d,d,r.content.firstChild):i.replaceRange(d,d,r),i.doc.eq(h))return!0;const M=i.doc.resolve(d);if(p&&Ee.isSelectable(r.content.firstChild)&&M.nodeAfter&&M.nodeAfter.sameMarkup(r.content.firstChild))i.setSelection(new Ee(M));else{let R=i.mapping.map(a);i.mapping.maps[i.mapping.maps.length-1].forEach((T,w,S,I)=>R=I),i.setSelection(Ig(n,M,i.doc.resolve(R)))}return n.focus(),n.dispatch(i.setMeta("uiEvent","drop")),!0}}})}function Ig(e,t,n,o){return e.someProp("createSelectionBetween",r=>r(e,t,n))||Ne.between(t,n,o)}function Pg(e,t,n){const o=e.dom;let r,s,c,a=!1;const i=()=>{r&&clearTimeout(r),a=!1,r=setTimeout(()=>{a||n.onHide?.()},30)},d=h=>{a=!0;const{clientX:M,clientY:R}=h;if(s===M&&c===R)return;s=M,c=R;const T=t([M,R],h);if(T){const[w,[S,I,X,ee]]=T,q={p1:{x:S,y:I},p2:{x:X,y:ee}};n.onShow?.({view:e,pos:w,line:q})}else{i();return}};return o.addEventListener("dragover",d),o.addEventListener("dragend",i),o.addEventListener("drop",i),o.addEventListener("dragleave",i),{destroy:()=>{o.removeEventListener("dragover",d),o.removeEventListener("dragend",i),o.removeEventListener("drop",i),o.removeEventListener("dragleave",i)}}}kn({"canvasedit.textDefault":{zh:"文本",en:"Text"}});function Ho(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.id;return typeof t=="string"&&t?t:null}function Fi(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t?t:null}function Po(e){return Array.isArray(e)?[...e]:[]}function ou(e,t,n){return e.map(o=>Ho(o)===t?{...o,...n}:o)}function Fg(e,t){const n=new Set,o=e.filter(r=>{const s=Ho(r);return s&&t.has(s)?(n.add(s),!1):!0});return n.size?o.filter(r=>{if(!r||typeof r!="object"||r.type!=="connector")return!0;const s=r,c=Fi(s.from),a=Fi(s.to);return!(c&&n.has(c)||a&&n.has(a))}):o}function Oi(e,t,n,o){return e.map(r=>{const s=Ho(r);if(!s||!t.has(s))return r;const c=r;return typeof c.x!="number"||typeof c.y!="number"?r:{...c,x:Math.round(c.x+n),y:Math.round(c.y+o)}})}function ms(e,t){const n=new Set;for(const o of e){const r=Ho(o);r&&n.add(r)}for(let o=1;;o++){const r=`${t}${o}`;if(!n.has(r))return r}}const ye="m:",Og={rect:{w:200,h:120},ellipse:{w:180,h:120},text:{w:180,h:40}},_i={w:480,h:320};function ru(e,t,n){return{id:e,type:t==="text"?"text":"shape",...t==="text"?{}:{shape:t},x:Math.round(n.x),y:Math.round(n.y),w:Math.round(n.w),h:Math.round(n.h),...t==="text"?{text:we("canvasedit.textDefault")}:{}}}function _g(e,t,n,o){const r=Og[t];return ru(e,t,{x:n-r.w/2,y:o-r.h/2,w:r.w,h:r.h})}function nc(e){return e==="m:"?{main:!0}:e.startsWith("c:")?{ref:e.slice(2)}:e.startsWith("e:")?{id:e.slice(2)}:null}function Bg(e,t,n){if(t===n)return e;const o=nc(t),r=nc(n);if(!o||!r)return e;const s=(a,i)=>{const d=i;return!!d&&d.ref===a.ref&&d.id===a.id};return e.some(a=>{if(!a||typeof a!="object"||a.type!=="connector")return!1;const i=a;return s(o,i.from)&&s(r,i.to)||s(o,i.to)&&s(r,i.from)})?e:[...e,{id:ms(e,"e"),type:"connector",from:o,to:r}]}const ps={fromEnd:"none",toEnd:"arrow"};function Kg(e,t,n){let o=!1;const r=e.map(s=>{const c=Ho(s);if(!c||!t.has(c)||s.type!=="connector")return s;const a=s;let i=null;for(const d of["fromEnd","toEnd"]){const p=n[d];if(p==null)continue;const h=p===ps[d];(h?!(d in a):a[d]===p)||(i??={...a},h?delete i[d]:i[d]=p)}return i?(o=!0,i):s});return o?r:e}const Pr=(e,t)=>{if(!e||!t||typeof e!="object"||typeof t!="object")return!1;const n=e,o=t;return typeof n.ref=="string"||typeof o.ref=="string"?n.ref===o.ref:typeof n.id=="string"||typeof o.id=="string"?n.id===o.id:n.main===!0&&o.main===!0};function Vg(e,t,n,o){const r=nc(o);if(!r)return e;const s=e.find(i=>Ho(i)===t);if(!s||s.type!=="connector")return e;const c=n==="from"?s.to:s.from;return Pr(r,s[n])||Pr(r,c)||e.some(i=>{if(Ho(i)===t||!i||typeof i!="object"||i.type!=="connector")return!1;const d=i;return Pr(r,d.from)&&Pr(c,d.to)||Pr(r,d.to)&&Pr(c,d.from)})?e:ou(e,t,{[n]:r})}function Hg(e,t,n,o){return e.map(r=>{if(Ho(r)!==t)return r;const s={...r};return o?s[n]=o:delete s[n],s})}function Vt(e){const t=Object.create(null);if(!e||typeof e!="object"||Array.isArray(e))return t;for(const n of Object.keys(e))t[n]=e[n];return t}function Kr(e,t,n){if(!t||!n||t===n)return e;let o=n;const r=new Set([t]);for(;typeof o=="string"&&o;){if(r.has(o))return e;r.add(o),o=e[o]}const s=Vt(e);return s[t]=n,s}function qg(e,t){if(!t.size)return e;const n=Object.create(null);for(const o of Object.keys(e)){if(t.has(o))continue;let r=e[o];const s=new Set;for(;typeof r=="string"&&t.has(r)&&!s.has(r);)s.add(r),r=e[r];typeof r!="string"||!r||t.has(r)||r===o||(n[o]=r)}return n}const Er=(e,t)=>Object.keys(e).filter(n=>e[n]===t).sort();function su(e,t,n,o){if(!t||!n||t===n)return!1;const r=new Set([t]);let s=e[t];for(;typeof s=="string"&&s&&!r.has(s)&&(!o||o.has(s));){if(s===n)return!0;r.add(s),s=e[s]}return!1}function Wg(e,t,n,o=6){let r=0;const s=new Set([t]);let c=e[t];for(;typeof c=="string"&&c&&n.has(c)&&!s.has(c)&&r<o;)r++,s.add(c),c=e[c];return r}function Zs(e,t,n){const o=new Set(e.map(s=>s.anchor));let r=t+1;for(;r<e.length&&e[r].idx===e[r-1].idx+1&&su(n,e[r].anchor,e[t].anchor,o);)r++;return r}function Yg(e,t,n,o,r,s){return{id:e,type:"frame",x:Math.round(t),y:Math.round(n),w:Math.round(o),h:Math.round(r)}}const Xg=/^(?:[1-6]|#[0-9a-fA-F]{6})$/;function ra(e){return typeof e!="string"||!Xg.test(e)?null:e.length===1?`var(--amx-cv-${e})`:e}function Ug(e,t,n){let o=!1;const r=e.map(s=>{const c=Ho(s);if(!c||!t.has(c))return s;const a=s;if(n?a.color===n:!("color"in a))return s;o=!0;const i={...a};return n?i.color=n:delete i.color,i});return o?r:e}const yc=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/;function Ma(e){if(!e)return null;try{const n=JSON.parse(e);if(!n||n.v!==4||!Array.isArray(n.rows))return null;for(const o of n.rows){if(!o||!Array.isArray(o.columns)||o.columns.length<1||o.tail!=null&&(typeof o.tail!="string"||!/^[A-Za-z0-9_-]+$/.test(o.tail)))return null;for(const r of o.columns)if(!r||!Array.isArray(r.refs)||r.refs.length<1||!r.refs.every(s=>typeof s=="string"&&/^[A-Za-z0-9_-]+$/.test(s))||typeof r.width!="number"||!Number.isFinite(r.width)||r.width<=0)return null}return n}catch{return null}}function Eo(e){const t=new Set;for(e.descendants(n=>{if(n.type.name==="amadeusColumnCell"&&n.attrs.anchor&&t.add(String(n.attrs.anchor)),n.type.name==="amadeusColumnRow"&&n.attrs.tail&&t.add(String(n.attrs.tail)),n.type.name==="amadeusCanvasCard"&&n.attrs.anchor&&t.add(String(n.attrs.anchor)),n.type.name==="html"){const o=yc.exec(String(n.attrs.value??"").trim());o&&t.add(o[1])}});;){const n="c"+Math.random().toString(36).slice(2,6);if(!t.has(n))return n}}function ts(e,t){const n=[],o=[];return t.forEach(r=>{if(r.type.name==="amadeusCanvasCard"){let s=Eo(e);for(;n.includes(s);)s=Eo(e);n.push(s),o.push(r.type.create({...r.attrs,anchor:s},r.content,r.marks))}else o.push(r)}),n.length?{content:So.fromArray(o),minted:n}:{content:t,minted:n}}const Gg=dc("amadeusColumnRow",()=>({content:"amadeusColumnCell+",group:"block",defining:!0,isolating:!0,selectable:!1,attrs:{tail:{default:""}},parseDOM:[{tag:"div[data-amx-colrow]",getAttrs:e=>({tail:e.dataset.tail??""})}],toDOM:e=>["div",{"data-amx-colrow":"","data-tail":String(e.attrs.tail),class:"amx-ucolrow"},0],parseMarkdown:{match:({type:e})=>e==="amadeusColumnRow",runner:(e,t,n)=>{e.openNode(n,{tail:t.tail??""}),e.next(t.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="amadeusColumnRow",runner:(e,t)=>{t.forEach(n=>{e.addNode("html",void 0,`<!-- a ${n.attrs.anchor} -->`),n.childCount===1&&n.firstChild.type.name==="paragraph"&&n.firstChild.content.size===0||e.next(n.content)}),t.attrs.tail&&e.addNode("html",void 0,`<!-- a ${t.attrs.tail} -->`)}}})),Jg=dc("amadeusColumnCell",()=>({content:"block+",defining:!0,isolating:!0,selectable:!1,attrs:{anchor:{default:""},width:{default:1}},parseDOM:[{tag:"div[data-amx-colcell]",getAttrs:e=>{const t=Number(e.dataset.width);return{anchor:e.dataset.anchor??"",width:Number.isFinite(t)&&t>0?t:1}}}],toDOM:e=>["div",{"data-amx-colcell":"","data-anchor":String(e.attrs.anchor),"data-width":String(e.attrs.width),class:"amx-ucolcell",style:`flex-grow:${Number(e.attrs.width)||1}`},0],parseMarkdown:{match:({type:e})=>e==="amadeusColumnCell",runner:(e,t,n)=>{e.openNode(n,{anchor:t.anchor??"",width:t.width??1}),e.next(t.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="amadeusColumnCell",runner:(e,t)=>{e.next(t.content)}}}));function Zg(e,t,n){if(!t?.rows?.length)return;const o=Array.isArray(e?.children)?e.children:[];if(o.length&&!o.some(d=>d?.position))return;const r=d=>{let p=null;if(d?.type==="html"&&typeof d.value=="string")p=d.value;else if(d?.type==="paragraph"&&Array.isArray(d.children)&&d.children.length===1){const M=d.children[0];M?.type==="html"&&typeof M.value=="string"&&(p=M.value)}if(p==null)return null;const h=yc.exec(p.trim());return h?h[1]:null},s=[];if(o.forEach((d,p)=>{const h=r(d);h&&s.push({id:h,idx:p})}),!s.length)return;const c=new Map;s.forEach((d,p)=>{c.has(d.id)?c.set(d.id,-1):c.set(d.id,p)});const a=new Set,i=[];for(const d of t.rows){if(d.columns.length<2)continue;const p=d.columns.flatMap(I=>I.refs);if(!p.length)continue;const h=p.map(I=>c.get(I)??-1);if(h.some(I=>I<0||a.has(I))||new Set(h).size!==h.length||!h.every((I,X)=>X===0||I===h[X-1]+1))continue;const M=h[h.length-1],R=d.tail!=null&&M+1<s.length&&s[M+1].id===d.tail&&!a.has(M+1)?M+1:null,T=R!=null?s[R].idx:M+1<s.length?s[M+1].idx:o.length,w=[];let S=!0;d.columns.forEach((I,X)=>{const ee=c.get(I.refs[0]),q=s[ee].idx+1,oe=X+1<d.columns.length?c.get(d.columns[X+1].refs[0]):null,Re=oe!=null?s[oe].idx:T;if(Re<q){S=!1;return}const Ge=o.slice(q,Re);w.push({type:"amadeusColumnCell",anchor:I.refs[0],width:I.width||1,children:Ge.length?Ge:[{type:"paragraph",children:[]}]})}),!(!S||w.length<2)&&(h.forEach(I=>a.add(I)),R!=null&&a.add(R),i.push({from:s[h[0]].idx,to:R!=null?s[R].idx+1:T,node:{type:"amadeusColumnRow",tail:R!=null?d.tail:"",children:w}}))}i.sort((d,p)=>p.from-d.from);for(const d of i)o.splice(d.from,d.to-d.from,d.node);i.length&&n?.()}function Qg(e,t){return[_l("amadeusColumnsFold",()=>()=>n=>{Zg(n,e(),t)})].flat()}function ey(e){const t=[String(e.attrs.anchor)];return e.forEach(n=>{if(n.type.name!=="paragraph"||n.childCount!==1)return;const o=n.firstChild;if(o.type.name!=="html")return;const r=yc.exec(String(o.attrs.value??"").trim());r&&t.push(r[1])}),t}function ty(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusColumnRow")return;const o=[];n.forEach(r=>{o.push({refs:ey(r),width:Number(r.attrs.width)||1})}),o.length>=2&&t.push({columns:o,...n.attrs.tail?{tail:String(n.attrs.tail)}:{}})}),t.length?JSON.stringify({v:4,rows:t}):null}const xc=e=>e.childCount===1&&e.firstChild.type.name==="paragraph"&&e.firstChild.content.size===0;function Qs(e,t){const{paragraph:n,html:o}=e.nodes;return t&&n&&o?[n.create(null,o.create({value:`<!-- a ${t} -->`}))]:[]}function bc(e,t,n,o=!1){const r=[];for(const s of t)r.push(...Qs(e,String(s.attrs.anchor))),o&&xc(s)||s.forEach(c=>r.push(c));return r.push(...Qs(e,n)),r}const ny=Et(()=>new qt({key:new Dn("AMX_COLUMNS_NORMALIZE"),appendTransaction:(e,t,n)=>{if(!e.some(i=>i.docChanged))return null;const o=e.some(i=>(i.getMeta("uiEvent")==="drop"||i.getMeta("amxColumns"))&&!i.getMeta("amxColumnsKeepEmpty")),{paragraph:r}=n.schema.nodes,s=i=>Qs(n.schema,i),c=[];if(n.doc.descendants((i,d,p)=>{if(i.type.name==="amadeusColumnRow"&&p?.type.name==="amadeusColumnCell"){const h=[];return i.forEach(M=>M.forEach(R=>h.push(R))),c.push({from:d,to:d+i.nodeSize,content:h.length?h:[r.create()]}),!1}return!0}),n.doc.forEach((i,d)=>{if(i.type.name!=="amadeusColumnRow")return;const p=[];i.forEach(S=>p.push(S));const h=o?p.filter(S=>!xc(S)):p,M=h.some(S=>!S.attrs.anchor);if(h.length===p.length&&h.length>=2&&!M)return;const R=new Set;n.doc.descendants(S=>{S.type.name==="amadeusColumnCell"&&S.attrs.anchor&&R.add(String(S.attrs.anchor)),S.type.name==="amadeusColumnRow"&&S.attrs.tail&&R.add(String(S.attrs.tail))});const T=S=>{if(S.attrs.anchor)return S;let I="c"+Math.random().toString(36).slice(2,6);for(;R.has(I);)I="c"+Math.random().toString(36).slice(2,6);return R.add(I),S.type.create({...S.attrs,anchor:I},S.content)},w=p.filter(S=>!h.includes(S)).flatMap(S=>s(String(S.attrs.anchor)));if(h.length>=2)c.push({from:d,to:d+i.nodeSize,content:[i.type.create(i.attrs,h.map(T)),...w]});else{const S=[...w,...bc(n.schema,h,String(i.attrs.tail??""))];c.push({from:d,to:d+i.nodeSize,content:S.length?S:[r.create()]})}}),!c.length)return null;let a=n.tr;for(const i of c.sort((d,p)=>p.from-d.from))a=a.replaceWith(i.from,i.to,i.content);return a}}));function oy(e,t,n,o=!1){const{state:r}=e,s=r.selection;if(!(s instanceof Ee))return!1;const c=s.node;if(c.type.name==="amadeusColumnRow"||c.type.name==="amadeusColumnCell"||c.type.name==="amadeusCanvasCard"||r.doc.nodeAt(t)?.type.name==="amadeusCanvasCard"||t>=s.from&&t<s.to)return!1;const a=r.schema.nodes.amadeusColumnRow,i=r.schema.nodes.amadeusColumnCell;if(!a||!i)return!1;const d=c.type.name==="list_item"?s.$from.parent.type.create(s.$from.parent.attrs,c):c,p=r.doc.resolve(t);let h=null;if(p.depth>0){let I=-1;for(let X=p.depth;X>=1;X--)if(p.node(X).type===a){I=X;break}if(I<0||I!==1)return!1;h={rowPos:p.before(I),cellIndex:p.index(I)}}const M=new Set,R=()=>{let I=Eo(r.doc);for(;M.has(I);)I=Eo(r.doc);return M.add(I),I},T=R(),w=R();let S=r.tr;if(o||(S=S.delete(s.from,s.to)),h){const I=S.mapping.map(h.rowPos),X=S.doc.nodeAt(I);if(!X||X.type!==a)return!1;const ee=n==="left"?h.cellIndex:h.cellIndex+1;let q=I+1;for(let oe=0;oe<Math.min(ee,X.childCount);oe++)q+=X.child(oe).nodeSize;S=S.insert(q,i.create({anchor:w,width:1},d))}else{const I=S.mapping.map(t),X=S.doc.nodeAt(I);if(!X)return!1;const ee=n==="left"?[i.create({anchor:w,width:1},d),i.create({anchor:T,width:1},X)]:[i.create({anchor:T,width:1},X),i.create({anchor:w,width:1},d)];S=S.replaceWith(I,I+X.nodeSize,a.create({tail:R()},ee))}return S.setMeta("amxColumns",!0),e.dispatch(S.scrollIntoView()),!0}function ry(e,t,n=!1){const{state:o}=e,r=o.selection;if(!(r instanceof Ee))return!1;const s=r.node;if(s.type.name==="amadeusColumnRow"||s.type.name==="amadeusColumnCell")return!1;const c=o.doc.nodeAt(t);if(!c||c.type.name!=="amadeusColumnRow"||!n&&r.from===t+c.nodeSize)return!1;const a=s.type.name==="list_item"?r.$from.parent.type.create(r.$from.parent.attrs,s):s;let i=o.tr;return n||(i=i.delete(r.from,r.to)),i=i.insert(i.mapping.map(t+c.nodeSize),a),i.setMeta("amxColumns",!0),e.dispatch(i.scrollIntoView()),!0}function sy(e,t,n=!1){const{state:o}=e,r=o.selection;if(!(r instanceof Ee))return!1;const s=r.node;if(s.type.name==="amadeusColumnRow"||s.type.name==="amadeusColumnCell"||s.type.name==="amadeusCanvasCard")return!1;const c=o.doc.resolve(t),a=c.parent;if(a.type.name!=="amadeusColumnCell")return!1;if(!n&&t>=r.from&&t<=r.to)return!0;const i=s.type.name==="list_item"?r.$from.parent.type.create(r.$from.parent.attrs,s):s,d=a.childCount===1&&a.firstChild.type.name==="paragraph"&&a.firstChild.content.size===0;let p=o.tr;return n||(p=p.delete(r.from,r.to)),d?p=p.replaceWith(p.mapping.map(c.start()),p.mapping.map(c.end()),i):p=p.insert(p.mapping.map(t),i),p.setMeta("amxColumns",!0),e.dispatch(p.scrollIntoView()),!0}function au(e,t,n,o){if(o.type.name==="amadeusCanvasCard")return!1;const{state:r}=e;if(r.doc.resolve(t).depth!==0)return!1;const s=r.schema.nodes.amadeusColumnRow,c=r.schema.nodes.amadeusColumnCell,a=r.schema.nodes.paragraph;if(!s||!c||!a)return!1;const i=new Set,d=()=>{let M=Eo(r.doc);for(;i.has(M);)M=Eo(r.doc);return i.add(M),M},p=s.create({tail:d()},[c.create({anchor:d(),width:1},o),c.create({anchor:d(),width:1},a.create())]);let h=r.tr.replaceWith(t,n,p);return h=h.setSelection(Ne.near(h.doc.resolve(t+p.nodeSize-3))),h.setMeta("amxColumns",!0),h.setMeta("amxColumnsKeepEmpty",!0),e.dispatch(h.scrollIntoView()),!0}function cu(e,t,n,o=!1){const r=e.doc.nodeAt(t);if(!r||r.type.name!=="amadeusColumnCell"||!(o||xc(r)))return null;const s=e.doc.resolve(t),c=s.parent;if(c.type.name!=="amadeusColumnRow")return null;const a=s.before(),i=s.after(),d=s.index(),p=[];c.forEach((X,ee,q)=>{q!==d&&p.push(X)});const h=Qs(e.schema,String(r.attrs.anchor));if(p.length>=2){const X=e.tr.delete(t,t+r.nodeSize);return h.length&&X.insert(X.mapping.map(i),h),X.setSelection(Vo.near(X.doc.resolve(Math.min(t,X.doc.content.size)),n)),X.scrollIntoView()}const M=[...bc(e.schema,p,String(c.attrs.tail??"")),...h],R=e.tr.replaceWith(a,i,M),T=p[0],w=n<0?d>0:d>=p.length,S=w?T?.lastChild:T?.firstChild;let I=a;for(const X of M){if(X===S){R.setSelection(Vo.near(R.doc.resolve(w?I+X.nodeSize-1:I+1),w?-1:1));break}I+=X.nodeSize}return R.scrollIntoView()}function ay(e,t){const{state:n}=e,o=n.doc.nodeAt(t);if(!o||o.type.name!=="amadeusColumnRow")return!1;const r=[];o.forEach(h=>r.push(h));const s=bc(n.schema,r,String(o.attrs.tail??""),!0),c=s.length?s:[n.schema.nodes.paragraph.create()],a=n.selection;let i=null;n.doc.nodesBetween(t,t+o.nodeSize,(h,M,R)=>i||R?.type.name!=="amadeusColumnCell"?!i:(a.from>=M&&a.from<M+h.nodeSize&&(i={node:h,off:a.from-M,nodeSel:a instanceof Ee&&a.from===M}),!1));const d=n.tr.replaceWith(t,t+o.nodeSize,c);let p=t;for(const h of c){const M=i;if(M&&h===M.node){d.setSelection(M.nodeSel?Ee.create(d.doc,p):Vo.near(d.doc.resolve(p+M.off)));break}p+=h.nodeSize}return e.dispatch(d.scrollIntoView()),!0}const cy=[Gg,Jg,ny].flat();kn({"docagent.instructions":{zh:"本页指令",en:"Page instructions"},"docagent.instructionsScope":{zh:"仅用于维护本页",en:"Applies to this page only"},"docagent.instructionsNested":{zh:"移到页面顶层后生效",en:"Move to the page top level to apply"},"docagent.instructionsPlaceholder":{zh:"写下维护本页时应遵循的要求…",en:"Describe how this page should be maintained…"},"docagent.task":{zh:"交办 Agent",en:"Agent task"},"docagent.prompt":{zh:"提示模板",en:"Prompt template"},"docagent.promptPlaceholder":{zh:"描述要让 Agent 完成的工作…",en:"Describe the work for the agent…"},"docagent.promptLabel":{zh:"任务内容",en:"Task prompt"},"docagent.agent":{zh:"选择 Agent",en:"Select agent"},"docagent.defaultAgent":{zh:"默认 Agent",en:"Default agent"},"docagent.assign":{zh:"交办",en:"Assign task"},"docagent.usePrompt":{zh:"使用提示",en:"Use prompt"},"docagent.open":{zh:"查看会话",en:"Open session"},"docagent.starting":{zh:"正在交办…",en:"Starting…"},"docagent.ready":{zh:"待交办",en:"Ready to assign"},"docagent.linked":{zh:"已关联会话",en:"Session linked"},"docagent.running":{zh:"处理中",en:"Working"},"docagent.waiting":{zh:"等待你回应",en:"Waiting for you"},"docagent.done":{zh:"本轮已完成",en:"Turn completed"},"docagent.failed":{zh:"执行遇到问题",en:"Run needs attention"},"docagent.startFailed":{zh:"交办失败,请重试",en:"Could not start. Please try again."},"docagent.noSession":{zh:"会话尚未关联,请重试",en:"No session was linked. Please try again."},"docagent.unavailable":{zh:"当前环境无法创建会话",en:"Sessions cannot be started in this environment"},"docagent.empty":{zh:"尚未填写内容",en:"No content yet"}});function iy(e){return e.kind==="instructions"?f.jsx(ly,{...e},e.pagePath):f.jsx(uy,{...e},`${e.kind}:${e.pagePath}:${Ss(e.src)?.id??"source"}`)}function ly({src:e,readOnly:t=!1,activeInstructions:n=!0,onChange:o}){const{t:r}=tn(),[s,c]=b.useState(e);return b.useEffect(()=>{c(e)},[e]),f.jsxs("section",{className:"am-doc-agent am-doc-agent-instructions","data-document-agent":"instructions","data-active":n,children:[f.jsxs("div",{className:"am-doc-agent-header",children:[f.jsx(np,{size:16,"aria-hidden":"true"}),f.jsx("span",{className:"am-doc-agent-title",children:r("docagent.instructions")}),f.jsx("span",{className:"am-doc-agent-hint",children:r(n?"docagent.instructionsScope":"docagent.instructionsNested")})]}),t?f.jsx("div",{className:"am-doc-agent-content",children:e||r("docagent.empty")}):f.jsx("textarea",{className:"am-doc-agent-input","aria-label":r("docagent.instructions"),rows:3,placeholder:r("docagent.instructionsPlaceholder"),value:s,onKeyDown:a=>a.stopPropagation(),onChange:a=>{c(a.target.value),o(a.target.value)}})]})}function uy({kind:e,src:t,pagePath:n,readOnly:o=!1,onChange:r,onStart:s,onOpen:c}){const{t:a}=tn(),i=b.useMemo(()=>Ss(t),[t]),[d,p]=b.useState(i),[h,M]=b.useState(!1),[R,T]=b.useState(null),[w,S]=b.useState(null),[I,X]=b.useState("idle"),ee=b.useRef(!1),q=b.useRef(!1),oe=Ar(),Re=e==="task"?typeof oe?.submitDocumentTask=="function"&&oe.hostExecution?.()!==!1:typeof oe?.startChat=="function",[Ge,m]=b.useState(()=>oe?.agents?.()??[]),ke=e==="task"?i?.sessionId||(w?.id===i?.id?w?.sessionId:void 0):void 0,rt=o||h||!!ke;b.useEffect(()=>(ee.current=!0,()=>{ee.current=!1}),[]),b.useEffect(()=>{p(i),T(null)},[i]),b.useEffect(()=>{const Te=()=>{m(oe?.agents?.()??[])};return Te(),oe?.subscribeAgents?oe.subscribeAgents(Te):oe?.subscribe(Te)},[oe]),b.useEffect(()=>{if(X(ke?oe?.agentStatus?.(ke).phase??"idle":"idle"),!!ke)return oe?.subscribeAgentStatus?.(Te=>{Te.sessionId===ke&&X(Te.phase)},ke)},[oe,ke]);const de=async()=>{if(!(o||!Re||q.current||!d||!d.prompt.trim()||ke)){q.current=!0,M(!0),T(null);try{r(hs(d));const Te=await s(d,e==="prompt"?"prompt":"task");if(e==="task"&&!Te.sessionId)throw new Error(a("docagent.noSession"));ee.current&&e==="task"&&Te.sessionId&&S({id:d.id,sessionId:Te.sessionId})}catch(Te){ee.current&&T(Te instanceof Error?Te.message:a("docagent.startFailed"))}finally{q.current=!1,ee.current&&M(!1)}}};if(!i||!d)return f.jsx("pre",{className:"am-doc-agent-source",children:f.jsx("code",{children:t})});const me=ke?I==="waiting"?"docagent.waiting":I==="done"?"docagent.done":I==="error"?"docagent.failed":I==="idle"?"docagent.linked":"docagent.running":"docagent.ready",he=h||!!ke&&["thinking","speaking","tool"].includes(I),ze=e==="prompt"?Pl:bf,He=d.agent&&!Ge.some(Te=>Te.slug===d.agent);return f.jsxs("section",{className:"am-doc-agent","data-document-agent":e,"data-document-agent-id":d.id,"data-page-path":n,"aria-busy":h,children:[f.jsxs("div",{className:"am-doc-agent-header",children:[f.jsx(ze,{size:16,"aria-hidden":"true"}),f.jsx("span",{className:"am-doc-agent-title",children:a(e==="prompt"?"docagent.prompt":"docagent.task")}),e==="task"&&f.jsxs("span",{className:"am-doc-agent-status",role:"status","aria-live":"polite","data-phase":I,children:[he?f.jsx(Zc,{size:12,className:"am-doc-agent-spin","aria-hidden":"true"}):I==="done"?f.jsx(oa,{size:12,"aria-hidden":"true"}):null,a(h?"docagent.starting":me)]})]}),o||ke?f.jsx("div",{className:"am-doc-agent-content",children:d.prompt||a("docagent.empty")}):f.jsx("textarea",{className:"am-doc-agent-input","aria-label":a("docagent.promptLabel"),rows:3,placeholder:a("docagent.promptPlaceholder"),value:d.prompt,disabled:h,onKeyDown:Te=>Te.stopPropagation(),onChange:Te=>{const dt={...d,prompt:Te.target.value};p(dt),r(hs(dt))}}),f.jsxs("div",{className:"am-doc-agent-footer",children:[rt?f.jsx("span",{className:"am-doc-agent-assignee",children:Ge.find(Te=>Te.slug===d.agent)?.name||d.agent||a("docagent.defaultAgent")}):f.jsxs("select",{className:"am-doc-agent-select","aria-label":a("docagent.agent"),value:d.agent??"",onKeyDown:Te=>Te.stopPropagation(),onChange:Te=>{const dt={...d,agent:Te.target.value||void 0};p(dt),r(hs(dt))},children:[f.jsx("option",{value:"",children:a("docagent.defaultAgent")}),He&&f.jsx("option",{value:d.agent,children:d.agent}),Ge.map(Te=>f.jsx("option",{value:Te.slug,children:Te.name},Te.slug))]}),ke?c&&f.jsxs("button",{type:"button",className:"am-doc-agent-action",onClick:()=>c(ke),children:[f.jsx(xi,{size:14,"aria-hidden":"true"}),a("docagent.open")]}):!o&&f.jsxs("button",{type:"button",className:"am-doc-agent-action",disabled:h||!Re||!d.prompt.trim(),title:Re?void 0:a("docagent.unavailable"),onMouseDown:Te=>Te.preventDefault(),onClick:()=>{de()},children:[h?f.jsx(Zc,{size:14,className:"am-doc-agent-spin","aria-hidden":"true"}):f.jsx(xi,{size:14,"aria-hidden":"true"}),a(h?"docagent.starting":e==="prompt"?"docagent.usePrompt":"docagent.assign")]})]}),!o&&!ke&&!Re&&f.jsx("div",{className:"am-doc-agent-hint",children:a("docagent.unavailable")}),R&&f.jsx("div",{className:"am-doc-agent-error",role:"alert",children:R})]})}function oc(e){const t=[];return e.forEach(n=>{if(n.type.name==="code_block"&&n.attrs.language==="forsion-instructions"){const o=n.textContent.trim();o&&t.push(o)}}),t.join(`
34
-
35
- `).slice(0,12e3)}function iu(e,t){return e.trim()?`Page maintenance instructions for ${JSON.stringify(t)} (apply only when working on this page; the current user request takes precedence; do not grant permissions or inherit into other pages):
36
- ${e.slice(0,12e3)}
37
- End of page maintenance instructions.`:""}kn({"uembed.openInTab":{zh:"在 Forsion 标签页中打开",en:"Open in a Forsion tab"},"uembed.openWithSystem":{zh:"用系统默认程序打开",en:"Open with the system default app"},"uembed.openPdfInTab":{zh:"在 Forsion 标签页中打开",en:"Open in a Forsion tab"},"uembed.open":{zh:"打开 ↗",en:"Open ↗"},"uembed.startAt":{zh:"起播时刻",en:"Start time"},"uembed.badAnchor":{zh:"锚点无效 · 从 0 秒起播",en:"Invalid anchor · playing from 0:00"},"uembed.badAnchorTip":{zh:"只认 #t=95 / #t=01:35 / #t=1:02:30(MM 与 SS 须两位)",en:"Only #t=95 / #t=01:35 / #t=1:02:30 are recognized (MM and SS must be two digits)"},"uembed.collapse":{zh:"收起",en:"Collapse"},"uembed.expand":{zh:"展开",en:"Expand"},"uembed.loadingPdf":{zh:"加载 PDF…",en:"Loading PDF…"},"uembed.crossNote":{zh:"跨笔记嵌入(只读)",en:"Cross-note embed (read-only)"},"uembed.badge":{zh:"↪ 嵌入",en:"↪ Embed"},"uembed.editAtSource":{zh:"去源头编辑",en:"Edit at the source"},"uembed.resolving":{zh:"解析中…",en:"Resolving…"},"uembed.embedMissing":{zh:"嵌入丢失:",en:"Embed missing: "},"uembed.create":{zh:"创建",en:"Create"},"uembed.createTip":{zh:"新建笔记「{name}」",en:"Create the note “{name}”"}});function lu(){const[,e]=b.useState(0);return b.useEffect(()=>Al(()=>e(t=>t+1)),[]),we}const dy=wf(()=>sd(()=>import("./PdfAnnotator-Cq8cklTz.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]),import.meta.url).then(e=>({default:e.PdfAnnotator}))),or=()=>{},uu=/^!\[\[([^\]\n]+)\]\]$/,fy=/\.(png|jpe?g|gif|webp|svg|avif|bmp)$/i,my=/\.[a-z0-9]{1,8}$/i,py=/\.db$/i,hy=/\.pdf$/i,gy=/^https?:\/\/\S+$/i;function Bo(e){if(e.type.name==="code_block"){const h={"forsion-instructions":"instructions","forsion-task":"task","forsion-prompt":"prompt"}[e.attrs.language];return h&&(h==="instructions"||Ss(e.textContent))?{k:"document-agent",type:h,src:e.textContent}:e.attrs.language===op?e.textContent.trim()?{k:"sketch",src:e.textContent}:null:e.attrs.language!=="forsion-button"||!Fl(fu(e.textContent))?null:{k:"button",src:e.textContent}}if(e.type.name!=="paragraph")return null;const t=e.textContent.trim(),n=uu.exec(t);if(!n)return gy.test(t)?{k:"bookmark",url:t}:null;const o=n[1],[r,s]=o.split("|"),c=r.trim();if(fy.test(c))return null;const a=nd(o);if(a)return{k:"web",url:a,w:ua(o)};if(!c.includes("#")&&py.test(c))return{k:"db",name:c,view:s?.trim()||null};if(!c.includes("#")&&od(c))return{k:"draw",target:c};const i=Va.getState().embedRenderers;if(Qc(i,o.trim()))return{k:"plugin",target:o.trim()};const d=c.includes("#")?Kc(c)?.target??null:c;if(d&&Qc(i,d))return{k:"plugin",target:d};if(vf(c))return{k:"note",target:o};const p=Kc(c);return p?{k:"file",name:p.target,fileKind:rd.test(p.target)?"video":"audio",loc:p.loc,badAnchor:c.includes("#")&&!p.loc,w:ua(o)}:!c.includes("#")&&my.test(c)?{k:"file",name:c,fileKind:hy.test(c)?"pdf":"other",w:ua(o)}:{k:"note",target:o}}const yy=new Set(["file","db","draw","plugin","note"]),du=e=>!!e&&yy.has(e.k);function Cs(e){return!!e&&e.type.name==="paragraph"&&du(Bo(e))}function xy({name:e,fileKind:t,pagePath:n,loc:o,badAnchor:r,insertAfter:s}){const c=lu(),a=Mn(R=>R.files),i=Mn(R=>R.openWikiLink),[d,p]=b.useState(!0),h=t==="pdf"?Nf(e,a,n):null;if(t==="other")return!/\.[a-z0-9]+\.md$/i.test(e)&&!ti()?f.jsxs("div",{className:"embed-file",children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),f.jsx("span",{className:"embed-file-name",children:e})]}):f.jsxs("button",{className:"embed-file",onClick:()=>{/\.[a-z0-9]+\.md$/i.test(e)?i(e,n):wn.openAttachment(n,e)},title:/\.[a-z0-9]+\.md$/i.test(e)?c("uembed.openInTab"):c("uembed.openWithSystem"),children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),f.jsx("span",{className:"embed-file-name",children:e}),f.jsx("span",{className:"embed-file-open",children:c("uembed.open")})]});const M=$l(e);return f.jsxs("div",{className:"embed-media",children:[f.jsxs("div",{className:"embed-media-head",children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:t==="pdf"?"📕":t==="video"?"🎬":"🎵"}),f.jsx("span",{className:"embed-file-name",children:e}),o&&f.jsxs("span",{className:"embed-media-at",title:c("uembed.startAt"),children:["@",Vc(o.at),o.to?`–${Vc(o.to)}`:""]}),r&&f.jsx("span",{className:"embed-media-warn",title:c("uembed.badAnchorTip"),children:c("uembed.badAnchor")}),f.jsx("button",{className:"embed-media-btn",onClick:()=>p(R=>!R),children:c(d?"uembed.collapse":"uembed.expand")}),(t==="pdf"||ti())&&f.jsx("button",{className:"embed-media-btn",title:c(t==="pdf"?"uembed.openPdfInTab":"uembed.openWithSystem"),onClick:()=>{t==="pdf"?i(e,n):wn.openAttachment(n,e)},children:c("uembed.open")})]}),d&&t==="pdf"&&(h?f.jsx("div",{className:"embed-pdf embed-pdf-live",children:f.jsx(b.Suspense,{fallback:f.jsx("div",{className:"embed-pdf-loading",children:c("uembed.loadingPdf")}),children:f.jsx(dy,{pdfPath:h,embed:!0})})}):f.jsx("iframe",{className:"embed-pdf",src:M,title:e})),d&&(t==="video"||t==="audio")&&f.jsx(Tf,{kind:t,url:M,name:e,pagePath:n,loc:o??null,insertAfter:s})]})}function by({target:e,pagePath:t,readOnly:n}){const o=lu(),r=Mn(I=>I.openWikiLink),s=Mn(I=>I.loadPage),c=Mn(I=>I.pages),a=Mn(I=>I.linkGraphVersion),[i,d]=b.useState("loading"),{note:p,subpath:h}=ld(e),M=h?`${p}#${h}`:p;b.useEffect(()=>{let I=!0;return d("loading"),Promise.resolve(M?wn.resolveEmbed?.(M,t)??null:null).then(X=>{I&&d(X)}).catch(()=>{I&&d(null)}),()=>{I=!1}},[M,t,a]);const R=!n&&i===null&&!!p&&!gs(p,c,t),T=()=>{Mn.getState().openWikiLink(p,t),Mn.getState().pendingWikiCreate?.name===p&&Mn.getState().confirmWikiCreate()},S=(i&&i!=="loading"?Af(i.type):void 0)?.Editor;return f.jsxs("div",{className:"embed-body",children:[f.jsxs("div",{className:"embed-head",children:[f.jsx("span",{className:"embed-badge",title:o("uembed.crossNote"),children:o("uembed.badge")}),i&&i!=="loading"&&f.jsxs("button",{className:"embed-src",onClick:()=>{s(i.owner)},title:o("uembed.editAtSource"),children:[ud(i.owner)," ↗"]})]}),i==="loading"?f.jsx("div",{className:"embed-loading",children:o("uembed.resolving")}):i&&S?f.jsx(S,{blockId:"uembed",content:i.content,pagePath:i.owner,readOnly:!0,onChange:or,onInsertAfter:or,onDeleteEmpty:or,onMergePrev:or,onArrowOut:or,onMoveDir:or,focusPlace:null,onFocused:or,requestSelfFocus:or,onOpenWiki:(I,X)=>r(I,i.owner,X),getPageNames:()=>c}):f.jsxs("div",{className:"embed-missing",children:[o("uembed.embedMissing"),f.jsx("code",{children:e}),R&&f.jsx("button",{type:"button",className:"embed-media-btn embed-create",title:o("uembed.createTip",{name:p}),onClick:T,children:o("uembed.create")})]})]})}function vy({kind:e,pagePath:t,replaceText:n,insertAfter:o,startTask:r,readOnly:s=!1}){const c=s?()=>{}:n;switch(e.k){case"document-agent":return f.jsx(iy,{kind:e.type,src:e.src,pagePath:t,readOnly:s,activeInstructions:e.activeInstructions,onChange:c,onStart:r,onOpen:a=>Ar()?.openDocumentTask?.(a)});case"db":return f.jsx($f,{target:e.name,pagePath:t,initialView:e.view??void 0,readOnly:s,onViewChange:a=>c(a?`![[${e.name}|${a}]]`:`![[${e.name}]]`)});case"draw":return f.jsx(zf,{target:e.target,pagePath:t,readOnly:s});case"plugin":return f.jsx(Mf,{target:e.target,pagePath:t});case"file":return f.jsx(xy,{name:e.name,fileKind:e.fileKind,pagePath:t,loc:e.loc,badAnchor:e.badAnchor,insertAfter:s?()=>{}:o});case"note":return f.jsx(by,{target:e.target,pagePath:t,readOnly:s});case"bookmark":return s?f.jsx(ei,{url:e.url}):f.jsx(ei,{url:e.url,onChangeUrl:a=>n(a),onEmbed:()=>n(`![[${id(e.url)}]]`)});case"web":return f.jsx(Ef,{url:e.url,toCard:()=>c(e.url)});case"button":{const a=Fl(fu(e.src));return a?f.jsx(Cf,{spec:a,readOnly:s,onChange:i=>c(wy(Sf(i)))}):f.jsx("span",{})}case"sketch":return f.jsx(rp,{items:[{callId:"note-sketch",html:e.src}]})}}function fu(e){return"```forsion-button\n"+e+"\n```"}function wy(e){const t=/^```forsion-button[ \t]*\r?\n([\s\S]*?)\r?\n?```$/.exec(e.trim());return t?t[1]:e}const Bi=(e,t)=>e.k==="db"?`db:${e.name}`:e.k==="document-agent"?`document-agent:${e.type}:${e.type==="instructions"?"":Ss(e.src)?.id}`:`${e.k}:${t}`;function ky(e,t,n){let o=!0;return e.mapping.maps.forEach((r,s)=>{const c=e.mapping.slice(s+1);r.forEach((a,i,d,p)=>{(c.map(d,-1)<t||c.map(p,1)>n)&&(o=!1)})}),o}function Cy(e){return[Et(()=>{const n=new Dn("UNIFIED_EMBED_LAYER"),o=new Map,r=new Set,s=(a,i,d,p,h=null,M=null)=>{const R=[],T=new Map,w=(S,I)=>{const X=Bo(S);if(!X)return;X.k==="document-agent"&&(X.activeInstructions=a.resolve(I).depth===0);const ee=Bi(X,S.textContent),q=T.get(ee)??0;T.set(ee,q+1);const oe=du(X);if(!oe&&p===I&&d>I&&i<I+S.nodeSize||h===I)return;const Re=`${ee}#${q}`,Ge=o.get(Re),m=X.k==="document-agent"?`${X.activeInstructions}:${S.textContent}`:S.textContent;Ge&&Ge.text!==m&&(Ge.text=m,Ge.render(X));const ke=oe&&M===I;ke||R.push(so.inline(I+1,I+S.nodeSize-1,{class:"wikilink-src-hidden"})),R.push(so.node(I,I+S.nodeSize,{class:`unified-embed-host${oe?" unified-embed-soft":""}${ke?" unified-embed-src":""}`})),R.push(so.widget(oe?I+S.nodeSize-1:I+1,rt=>{const de=o.get(Re);if(de)return de.refs++,de.dom;const me=document.createElement("div");me.className="unified-embed",me.contentEditable="false";const he=ce=>{let ge=0,k=null;return ce.state.doc.descendants((J,le)=>{if(k)return!1;const ve=Bo(J);return ve&&Bi(ve,J.textContent)===ee?ge===q?(k={at:le,size:J.nodeSize},!1):(ge++,!1):!0}),k};me.addEventListener("mousedown",ce=>{if(ce.button!==0)return;const ge=ce.target;if(ge!==me&&ge.parentElement!==me||ge.closest('.amx-src-btn, .amx-img-resize, button, a, input, textarea, select, iframe, webview, video, audio, [contenteditable="true"]'))return;const k=c;if(!k)return;const J=he(k);J&&(ce.preventDefault(),ce.stopPropagation(),k.dispatch(k.state.tr.setSelection(Ee.create(k.state.doc,J.at))),k.focus())});const ze=ce=>{const ge=c;if(!ge)return;const k=he(ge);k&&ge.dispatch(ge.state.tr.insertText(ce,k.at+1,k.at+k.size-1))},He=X.k==="web"||X.k==="file"&&X.fileKind!=="other",Te=X.k==="web"||X.k==="file"?X.w:void 0;Te&&(me.style.width=`${Te}px`);const dt=document.createElement("div");if(dt.className="unified-embed-body",me.appendChild(dt),He){const ce=uu.exec(S.textContent.trim())?.[1];ce!==void 0&&kf(me,me,ge=>ze(`![[${ad(ce,ge)}]]`))}const sn=_m.createRoot(dt),re=ce=>sn.render(f.jsx(cd,{children:f.jsx(vy,{kind:ce,pagePath:e.path,readOnly:!!e.readOnly,insertAfter:ge=>{const k=c;if(!k)return;const J=he(k);if(!J)return;const le=k.state.schema.nodes.paragraph;if(!le)return;const ve=ge.split(/\n{2,}/).map(Ye=>le.create(null,Ye?k.state.schema.text(Ye):null));k.dispatch(k.state.tr.insert(J.at+J.size,ve))},startTask:async(ge,k)=>{const J=Ar(),le=Mn.getState().vaultRoot,ve=c,Ye=ve&&he(ve);if(!Ye)throw new Error(we("documentTask.sourceGone"));const Fe={from:Ye.at,to:Ye.at+Ye.size,deleted:!1};r.add(Fe);try{const mt=()=>{if(Fe.deleted||e.readOnly||!c||c!==ve||e.alive?.()===!1||Mn.getState().vaultRoot!==le)return null;const Mt=c.state.doc.nodeAt(Fe.from);if(!Mt||Fe.from+Mt.nodeSize!==Fe.to)return null;const ot=Bo(Mt);if(ot?.k!=="document-agent"||ot.type!==k)return null;const an=Mt?Ss(Mt.textContent):null;return an?.id===ge.id&&an.prompt===ge.prompt&&an.agent===ge.agent?an:null};if(!mt()||!e.flush)throw new Error(we("documentTask.sourceGone"));if(await e.flush(),!mt()||!c)throw new Error(we("documentTask.sourceGone"));const it=iu(oc(c.state.doc),e.path),_t=`${ge.prompt.trim()}
38
-
39
- Source note: ${JSON.stringify(e.path)}. Read the source note before editing it.
40
- ${it}`;if(k==="prompt"){const Mt=await J?.startChat?.({agent:ge.agent,prompt:_t,send:!1,...J?.hostExecution?.()&&le?{cwd:le}:{},alive:()=>!!mt()});if(!Mt?.ok)throw new Error(Mt?.error||we("docagent.unavailable"));return{}}const jt=mt()?.sessionId;if(jt)return{sessionId:jt};if(!le||!J?.submitDocumentTask)throw new Error(we("docagent.unavailable"));const ht=await J.submitDocumentTask({key:`${le}
41
- ${e.path}
42
- ${ge.id}`,agent:ge.agent,prompt:_t,vaultRoot:le,alive:()=>!!mt(),onCreated:async Mt=>{const ot=mt();if(!ot||ot.sessionId&&ot.sessionId!==Mt)throw new Error(we("documentTask.sourceGone"));const an=c;if(an.dispatch(an.state.tr.insertText(hs({...ot,sessionId:Mt}),Fe.from+1,Fe.to-1)),await e.flush(),mt()?.sessionId!==Mt)throw new Error(we("documentTask.sourceGone"))}});if(!ht.ok)throw new Error(ht.error||we("docagent.startFailed"));return{sessionId:ht.sessionId}}finally{r.delete(Fe)}},replaceText:ze})}));return re(X),Qm(me,rt,()=>{const ce=c;if(!ce)return;const ge=he(ce);if(!ge)return;const k=ce.state.tr.setSelection(Ne.near(ce.state.doc.resolve(ge.at+1)));k.setMeta(n,{sourcePos:ge.at}),ce.dispatch(k),ce.focus()}),me.querySelector(".amx-src-btn")?.classList.add("amx-src-btn--block"),o.set(Re,{root:sn,dom:me,text:m,render:re,refs:1}),me},{key:Re,side:oe?1:-1,ignoreSelection:!0,stopEvent:rt=>/^(key|composition|beforeinput|input|paste|cut|copy)/.test(rt.type),destroy:()=>{const rt=o.get(Re);rt&&(rt.refs--,!(rt.refs>0)&&queueMicrotask(()=>{rt.refs>0||o.get(Re)!==rt||(o.delete(Re),rt.root.unmount())}))}}))};return a.descendants((S,I)=>(w(S,I),!0)),lr.create(a,R)};let c=null;return new qt({key:n,view:a=>(c=a,{destroy:()=>{for(const i of r)i.deleted=!0;c=null,queueMicrotask(()=>{if(!c){for(const[,i]of o)i.root.unmount();o.clear()}})}}),state:{init:(a,i)=>({decos:s(i.doc,i.selection.from,i.selection.to,null),sourcePos:null,pendingPos:null,revealPos:null}),apply:(a,i,d,p)=>{for(const S of r)for(const I of a.mapping.maps){if(S.deleted)break;const X=I.mapResult(S.from,1),ee=I.mapResult(S.to,-1);(X.deleted||ee.deleted||X.pos>=ee.pos)&&(S.deleted=!0),S.from=X.pos,S.to=ee.pos}const h=a.getMeta(n);let M=i.sourcePos;if(M!=null&&a.docChanged&&(M=a.mapping.map(M)),h&&typeof h.sourcePos=="number")M=h.sourcePos;else if(M!=null&&a.selectionSet){const S=p.doc.nodeAt(M);(!S||p.selection.to<=M||p.selection.from>=M+S.nodeSize)&&(M=null)}let R=i.pendingPos;if(R!=null&&a.docChanged&&(R=a.mapping.map(R,-1)),h?.commit)R=null;else if(a.docChanged&&p.selection.empty&&!/^(paste|drop)$/.test(String(a.getMeta("uiEvent")??""))){const S=p.selection.$head,I=S.depth>0?S.before():-1;I>=0&&S.parent.type.name==="paragraph"&&Bo(S.parent)?.k==="bookmark"&&ky(a,I+1,I+S.parent.nodeSize-1)&&(R=I)}if(R!=null){const S=p.doc.nodeAt(R),{from:I,to:X}=p.selection;(!S||S.type.name!=="paragraph"||X<R+1||I>R+S.nodeSize-1)&&(R=null)}let T=null;const w=p.selection;if(w instanceof Ne&&w.$from.depth>0&&w.$from.sameParent(w.$to)&&Cs(w.$from.parent)){const S=w.$from.before(),I=i.revealPos==null?null:a.docChanged?a.mapping.map(i.revealPos):i.revealPos;(Zm(p)||I===S)&&(T=S)}return!a.docChanged&&!a.selectionSet&&!h&&R===i.pendingPos&&T===i.revealPos?{sourcePos:M,pendingPos:R,revealPos:T,decos:i.decos.map(a.mapping,a.doc)}:{sourcePos:M,pendingPos:R,revealPos:T,decos:s(p.doc,p.selection.from,p.selection.to,M,R,T)}}},props:{decorations(a){return n.getState(a)?.decos??null},handleDOMEvents:{blur:a=>(n.getState(a.state)?.pendingPos!=null&&a.dispatch(a.state.tr.setMeta(n,{commit:!0})),!1)}}})})].flat()}const Sy=[Et(()=>Oo({Enter:Cd,"Shift-Enter":kd,"Mod-Enter":wd}))].flat();function Es(e){let t=e.depth;for(;t>=1&&!["doc","amadeusColumnCell"].includes(e.node(t-1).type.name);)t--;return t}function vc(e){if(!e)return!1;const t=e.type.name;return t==="code_block"||t==="hr"||t==="horizontal_rule"||t==="table"?!0:Bo(e)!=null}function rc(e){if(!e)return!1;const t=e.type.name;return t==="hr"||t==="horizontal_rule"?!0:Bo(e)!=null&&!Cs(e)}function qo(e){for(let t=e.depth;t>=1;t--)if(e.node(t).type.name==="list_item")return t;return null}function fr(e,t){return Vs(e,t)!=null?!0:Xm(e).some(n=>t>n.start&&t<n.after)}function Ey(e){let t=0;for(let n=e.depth;n>=1;n--)e.node(n).type.name==="list_item"&&t++;return t}function mu(e){for(let t=e.depth;t>=1;t--)if(e.node(t).type.name==="blockquote")return t;return null}function rr(...e){return(t,n,o)=>e.some(r=>r(t,n,o))}const My=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset===0||n.parent.type.name!=="heading")return!1;const r=n.before(n.depth);if(Ur(e,r)==null)return!1;const s=e.schema.nodes.paragraph;if(!s)return!1;const c=e.tr.split(n.pos,1,[{type:s}]);return c.setMeta(Xr,{toggle:r}),t?.(c.scrollIntoView()),!0},pu=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parent.type.name!=="heading")return!1;const r=e.schema.nodes.paragraph;if(!r)return!1;if(n.parentOffset===0){const c=n.before(n.depth),a=e.tr.insert(c,r.create());return a.setSelection(Ne.near(a.doc.resolve(c+1))),t?.(a.scrollIntoView()),!0}const s=e.tr.split(n.pos,1,[{type:r}]);return t?.(s.scrollIntoView()),!0},zy=(e,t)=>{const n=e.selection;if(!(n instanceof Ee)||!n.node.isTextblock||Bo(n.node)!=null)return!1;const o=e.tr.setSelection(Ne.near(e.doc.resolve(n.to-1),-1));return t?.(o.scrollIntoView()),!0},$y=(e,t,n)=>{const{$from:o,empty:r}=e.selection;if(!r||!n||!t)return!1;const s=zd(o);return!s||!$d(o.parent.type.name,s)?!1:Ad(n,s)},Ay=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parent.content.size!==0||qo(n)==null)return!1;const r=e.schema.nodes.list_item;return r?Tl(r)(e,t):!1},Ny=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o)return!1;const r=qo(n);if(r==null||r!==n.depth-1||n.node(r).childCount<2||!fc(e,n.before(r)))return!1;const c=e.schema.nodes.list_item,a=e.schema.nodes.paragraph;if(!c||!a)return!1;const i=e.doc.slice(n.pos,n.end()).content,d=c.createAndFill(null,a.create(null,i));if(!d)return!1;let p=e.tr.delete(n.pos,n.end());const h=p.mapping.map(n.after(r));return p=p.insert(h,d),p.setSelection(Ne.near(p.doc.resolve(h+2))),t?.(p.scrollIntoView()),!0},Ty=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset===0)return!1;const r=qo(n);if(r==null||r!==n.depth-1)return!1;const s=n.node(r);if(s.childCount<2||fc(e,n.before(r)))return!1;const c=s.child(1);if(!/_list$/.test(c.type.name))return!1;const a=e.schema.nodes.list_item,i=e.schema.nodes.paragraph;if(!a||!i)return!1;const d=n.pos,p=n.end(),h=e.doc.slice(d,p).content,M=n.before(r)+1+s.child(0).nodeSize+1,R=a.createAndFill(null,i.create(null,h));if(!R)return!1;let T=e.tr.delete(d,p);const w=T.mapping.map(M);return T=T.insert(w,R),T.setSelection(Ne.near(T.doc.resolve(w+2))),t?.(T.scrollIntoView()),!0},jy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o)return!1;const r=ic(n);if(!r||n.parentOffset!==n.parent.content.size)return!1;const s=e.tr.split(n.pos,1,[{type:n.parent.type,attrs:{...n.parent.attrs,indent:r}}]);return t?.(s.scrollIntoView()),!0},Ry=(e,t,n)=>{const{$from:o,empty:r}=e.selection,s=qo(o);if(s==null||o.node(s).attrs.checked!==!0)return!1;const c=e.schema.nodes.list_item;if(!c)return!1;if(r&&s===o.depth-1&&o.index(s)===0&&o.parentOffset===0&&o.parent.content.size>0){const h=c.createAndFill({...o.node(s).attrs,checked:!1});if(!h)return!1;if(!t)return!0;t(e.tr.insert(o.before(s),h).scrollIntoView());const M=n?n.root.getSelection?.():null;if(M&&M.rangeCount){const R=M.getRangeAt(0);M.removeAllRanges(),M.addRange(R)}return!0}if(!t)return _a(c)(e);let a=null;if(!_a(c)(e,h=>{a=h}))return!1;const i=a;if(!i)return!1;const d=i.selection.$from,p=qo(d);return p!=null&&d.node(p).attrs.checked===!0&&i.setNodeMarkup(d.before(p),void 0,{...d.node(p).attrs,checked:!1}),t(i),!0},Dy=e=>{const t=[];for(let n=0;;){const o=e.indexOf("$$",n);if(o<0)break;if(e[o+2]==="$"){n=o+3;continue}const r=e.indexOf("$$",o+2);if(r<0)break;t.push([o,r+2]),n=r+2}return t},hu=(e,t)=>{const{$from:n,$to:o}=e.selection;if(!n.sameParent(o)||!n.parent.isTextblock||n.parent.type.spec.code)return!1;const r=e.schema.nodes.hardbreak;if(!r||!n.parent.textContent.includes("$$"))return!1;const s=n.parentOffset,c=o.parentOffset;return Dy(ep(n.parent)).some(([a,i])=>s>=a+2&&c<=i-2)?(t?.(e.tr.replaceSelectionWith(r.create({isInline:!0}),!1).scrollIntoView()),!0):!1},Ly=rr(My,pu,zy,hu,$y,Ay,Ny,Ty,Ry,jy),Iy=(e,t)=>{const{$from:n}=e.selection,o=qo(n),r=mu(n);if(o!=null&&(r==null||o>r)&&n.node(o).attrs.checked!=null){const p=Ed(e,n.pos);return p?(t?.(p.scrollIntoView()),!0):!1}if(r!=null){const p=e.schema.nodes.hardbreak;return p?(t?.(e.tr.replaceSelectionWith(p.create(),!1).scrollIntoView()),!0):!1}const s=e.schema.nodes.list_item;if(s&&qo(n)!=null)return _a(s)(e,t);const c=e.schema.nodes.paragraph,a=Es(n);if(!c||a<1)return!1;const i=n.after(a),d=e.tr.insert(i,c.create());return d.setSelection(Ne.near(d.doc.resolve(i+1))),t?.(d.scrollIntoView()),!0},Py=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0||n.parent.type.name!=="heading"||n.parent.content.size===0)return!1;const r=e.schema.nodes.paragraph;return r?(t?.(e.tr.setBlockType(n.start(),n.end(),r)),!0):!1},Fy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=mu(n);if(r==null)return!1;if(n.index(r)===0){const M=n.before(r),R=e.doc.nodeAt(M);return!R||!Ee.isSelectable(R)?!1:(t?.(e.tr.setSelection(Ee.create(e.doc,M))),!0)}const c=n.before(r+1),a=n.after(r+1),i=n.after(r),d=e.doc.nodeAt(c);if(!d)return!1;let p=e.tr.delete(c,a);const h=p.mapping.map(i);return p=p.insert(h,d),p.setSelection(Ne.near(p.doc.resolve(h+1))),t?.(p.scrollIntoView()),!0},Oy=(e,t,n)=>{const{$from:o,empty:r}=e.selection;return!r||o.parentOffset!==0||!n||qo(o)==null?!1:Md(n)},_y=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=Es(n);if(r<1||r!==n.depth)return!1;const s=n.before(r),a=e.doc.resolve(s).nodeBefore;if(!vc(a)||!a)return!1;const i=s-a.nodeSize;let d=e.tr;n.parent.content.size===0&&(d=d.delete(s,n.after(r)));const p=d.doc.nodeAt(i);return!p||!Ee.isSelectable(p)||fr(e,i)?!1:(d=d.setSelection(Ee.create(d.doc,i)),t?.(d.scrollIntoView()),!0)},By=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=ic(n);if(!r)return!1;const s=n.before(n.depth);return t?.(e.tr.setNodeMarkup(s,void 0,{...n.parent.attrs,indent:r-1}).scrollIntoView()),!0},sc=e=>(t,n)=>{const{$from:o,empty:r}=t.selection;if(!r||o.depth<2||o.node(-1).type.name!=="amadeusColumnCell")return!1;const s=cu(t,o.before(-1),e);return s?(n?.(s),!0):!1},Ky=rr(sc(-1),Py,Fy,Oy,By,_y),Vy=(e,t,n)=>{const{$from:o,empty:r}=e.selection;if(!r||o.parentOffset!==0)return!1;if(ic(o)){const a=o.before(o.depth);return t?.(e.tr.setNodeMarkup(a,void 0,{...o.parent.attrs,indent:0}).scrollIntoView()),!0}const c=e.schema.nodes.list_item;if(!c||qo(o)==null)return!1;if(!t||!n)return!0;for(let a=0;a<32&&!(Ey(n.state.selection.$from)<=1||!Tl(c)(n.state,i=>n.dispatch(i)));a++);return!0},Ki=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parent.type.name!=="heading"||n.parentOffset!==n.parent.content.size)return!1;const r=n.before(n.depth);return Ur(e,r)==null?!1:(t?.(e.tr.setMeta(Xr,{toggle:r})),!0)},Vi=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==n.parent.content.size)return!1;const r=Es(n);if(r<1)return!1;const s=n.after(r),c=e.doc.resolve(s).nodeAfter;return!c||!vc(c)||!Ee.isSelectable(c)||fr(e,s)?!1:(t?.(e.tr.setSelection(Ee.create(e.doc,s)).scrollIntoView()),!0)},Hy=/^\[![\w-]+\]/,Hi=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||!n.parent.isTextblock||n.parentOffset!==n.parent.content.size||n.parent.type.name==="code_block"||n.depth<1)return!1;const r=T=>{for(let w=T.depth;w>0;w--)if(T.node(w).type.name==="table")return!0;return!1};if(r(n))return!1;const s=n.after(),c=Vo.findFrom(e.doc.resolve(s),1,!0);if(!(c instanceof Ne))return!1;const a=c.$from;if(a.parentOffset!==0||!a.parent.isTextblock||a.parent.type.name==="code_block"||r(a)||a.depth===n.depth&&a.before()===s||fr(e,a.pos))return!1;const i=T=>{for(let w=T.depth;w>0;w--)if(T.node(w).type.spec.isolating)return T.before(w);return-1};if(i(n)!==i(a))return!1;let d=!1;if(e.doc.nodesBetween(s,a.before(),(T,w)=>(w>=s&&w+T.nodeSize<=a.before()&&(T.isLeaf||T.isTextblock)&&(d=!0),!d)),d)return!1;const p=a.depth>=2&&a.node(-1).type.name==="blockquote"&&a.index(-1)===0?a.before(-1):null;if(p!=null&&Hy.test(a.parent.textContent)){const T=e.doc.nodeAt(p);return!T||!Ee.isSelectable(T)?!1:(t?.(e.tr.setSelection(Ee.create(e.doc,p)).scrollIntoView()),!0)}const h=n.parent.textContent+a.parent.textContent,M=e.tr.delete(n.pos,a.pos),R=M.doc.resolve(M.mapping.map(n.pos));return!R.parent.isTextblock||R.parent.textContent!==h||M.doc.textContent!==e.doc.textContent?!1:(t?.(M.setSelection(Ne.create(M.doc,R.pos)).scrollIntoView()),!0)};function qi(e){return(t,n,o)=>{const r=t.selection;if(!r.empty||!o||!o.endOfTextblock(e))return!1;const s=r.$from,c=Es(s);if(c<1)return!1;const a=e==="down"?s.after(c):s.before(c),i=e==="down"?t.doc.resolve(a).nodeAfter:t.doc.resolve(a).nodeBefore;if(!rc(i)||!i)return!1;const d=e==="down"?a:a-i.nodeSize,p=t.doc.nodeAt(d);return!p||!Ee.isSelectable(p)||fr(t,d)?!1:(n?.(t.tr.setSelection(Ee.create(t.doc,d)).scrollIntoView()),!0)}}function Ls(e){return(t,n,o)=>{const r=t.selection;if(!(r instanceof Ne)||!r.empty||!o)return!1;const s=r.$head;if(!s.parent.isTextblock)return!1;const c=Es(s);if(c<1)return!1;const a=e==="down"||e==="right",i=e==="up"||e==="down",d=s.before(c),p=s.node(c),h=s.depth===c&&Cs(p),M=Vo.findFrom(t.doc.resolve(a?d+p.nodeSize-1:d+1),a?-1:1,!0);if(!M||M.$head.start()!==s.start())return!1;if(i){if(h&&e==="down")try{const X=o.coordsAtPos(s.pos,s.pos===s.end()?-1:1),ee=o.coordsAtPos(s.end(),-1);if(Math.abs(X.top-ee.top)>Math.max(2,(X.bottom-X.top)/2))return!1}catch{return!1}else if(!o.endOfTextblock(e))return!1}else if(s.pos!==M.head)return!1;const R=a?d+p.nodeSize:d,T=a?t.doc.resolve(R).nodeAfter:t.doc.resolve(R).nodeBefore,w=T?a?R:R-T.nodeSize:-1,S=s.parentOffset;if(T&&Cs(T)){if(fr(t,w))return!1;const X=T.content.size,ee=e==="right"?0:e==="left"?X:Math.min(S,X);return n?.(t.tr.setSelection(Ne.create(t.doc,w+1+ee)).scrollIntoView()),!0}if(!h||!a)return!1;if(!T){const X=s.node(c-1),ee=t.schema.nodes.paragraph;if(!ee||!X.canReplaceWith(s.index(c-1)+1,s.index(c-1)+1,ee))return!1;const q=o.root.getSelection?.();if(q?.anchorNode&&o.dom.contains(q.anchorNode))try{if(o.posAtDOM(q.anchorNode,q.anchorOffset)!==s.pos)return!1}catch{return!1}if(!n)return!0;const oe=t.tr.insert(R,ee.create());return n(oe.setSelection(Ne.create(oe.doc,R+1)).scrollIntoView()),!0}if(fr(t,w))return!1;if(rc(T)&&Ee.isSelectable(T))return n?.(t.tr.setSelection(Ee.create(t.doc,w)).scrollIntoView()),!0;let I=T.isTextblock&&!T.type.spec.code?Ne.create(t.doc,w+1+(e==="down"?Math.min(S,T.content.size):0)):Vo.findFrom(t.doc.resolve(w),1,!0);return I?(I instanceof Ne&&rc(I.$head.parent)&&(I=Ee.create(t.doc,I.$head.before())),n?.(t.tr.setSelection(I).scrollIntoView()),!0):!1}}function Wi(e){return(t,n,o)=>{const{$from:r,empty:s}=t.selection;if(!s||r.parent.type.name!=="code_block"||r.depth<1)return!1;const c=o?o.root.getSelection?.():null;if(o&&c?.anchorNode&&o.dom.contains(c.anchorNode))try{if(o.posAtDOM(c.anchorNode,c.anchorOffset)!==r.pos)return!1}catch{return!1}if(e==="down"?!o?.endOfTextblock("down"):r.parentOffset!==r.parent.content.size)return!1;const a=r.node(-1);if(r.index(-1)!==a.childCount-1)return!1;const i=t.schema.nodes.paragraph,d=r.after();if(!i||!a.canReplaceWith(r.index(-1)+1,r.index(-1)+1,i))return!1;if(!n)return!0;const p=t.tr.insert(d,i.create());return n(p.setSelection(Ne.create(p.doc,d+1)).scrollIntoView()),!0}}const qy=(e,t)=>e.selection.$from.parent.type.name!=="code_block"?!1:(t?.(e.tr.insertText(`
43
- `).scrollIntoView()),!0);function Yi(e){return(t,n)=>{const o=t.doc,r=e==="up"?o.firstChild:o.lastChild;if(!r)return!1;const s=e==="up"?0:o.content.size-r.nodeSize;return Cs(r)?fr(t,s)?!1:(n?.(t.tr.setSelection(Ne.create(o,e==="up"?s+1:s+r.nodeSize-1)).scrollIntoView()),!0):Bo(r)!=null?!Ee.isSelectable(r)||fr(t,s)?!1:(n?.(t.tr.setSelection(Ee.create(o,s)).scrollIntoView()),!0):r.type.name==="code_block"?(n?.(t.tr.setSelection(Ne.create(o,e==="up"?s+1:s+r.nodeSize-1)).scrollIntoView()),!0):!1}}const Wy={"(":")","[":"]","{":"}","<":">",'"':'"',"'":"'","`":"`","(":")","【":"】","「":"」","《":"》","“":"”","‘":"’"},Yy=Et(e=>new qt({props:{handleTextInput:(t,n,o,r)=>{const s=Wy[r];if(!s||n===o)return!1;const c=t.state.selection;if(!(c instanceof Ne)||c.empty||!c.$from.sameParent(c.$to)||c.$from.parent.type.name==="code_block")return!1;if(r==="`"&&t.state.schema.marks.inlineCode)return e.get(jf).call(Sd.key);const a=t.state.tr.insertText(s,o).insertText(r,n);return a.setSelection(Ne.create(a.doc,n+1,o+1)),t.dispatch(a.scrollIntoView()),!0}}}));function za(e){const t=e.selection;if(!(t instanceof Ee)||!t.node.isBlock)return null;const n=t.node,o=e.tr;if(n.type.name==="code_block")return o.setSelection(Ne.create(o.doc,t.to-1));if(n.type.name==="table"){const c=Vo.near(o.doc.resolve(t.from+1),1);return!(c instanceof Ne)||c.from>=t.to?null:o.setSelection(Ne.create(o.doc,c.$from.end()))}if(!vc(n)&&!n.isLeaf){const c=Vo.near(o.doc.resolve(t.to-1),-1);if(c instanceof Ne&&c.from>t.from&&c.to<t.to)return o.setSelection(c)}const r=e.schema.nodes.paragraph,s=t.$to;return!r||!s.parent.canReplaceWith(s.index(),s.index(),r)?null:(o.insert(t.to,r.create()),o.setSelection(Ne.create(o.doc,t.to+1)))}const Xy=Et(()=>new qt({props:{handleDOMEvents:{keydown:(e,t)=>{if(!e.editable||t.metaKey||t.ctrlKey||!(t.key.length===1||t.key==="Process"||t.keyCode===229))return!1;const o=za(e.state);return o&&e.dispatch(o.scrollIntoView()),!1},compositionstart:e=>{if(!e.editable)return!1;const t=za(e.state);return t&&e.dispatch(t),!1},beforeinput:(e,t)=>{const n=t;if(!e.editable||n.inputType!=="insertText"||!n.data)return!1;const o=za(e.state);if(!o)return!1;n.preventDefault();const{from:r,to:s}=o.selection;return e.dispatch(o.insertText(n.data,r,s).scrollIntoView()),!0}}}})),Xi=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Uy=[Sy,Xy,Yy,Et(()=>Oo({Enter:Ly,"Shift-Enter":rr(pu,qy,hu),"Mod-Enter":Iy,Backspace:Ky,"Mod-Backspace":Vy,Delete:rr(sc(1),Ki,Vi,Hi),...Xi?{"Ctrl-d":rr(sc(1),Ki,Vi,Hi)}:{},ArrowUp:rr(Ls("up"),qi("up")),ArrowDown:rr(Wi("down"),Ls("down"),qi("down")),ArrowLeft:Ls("left"),ArrowRight:rr(Wi("right"),Ls("right")),...Xi?{"Meta-ArrowUp":Yi("up"),"Meta-ArrowDown":Yi("down")}:{}}))].flat();kn({"blocklayer.dragHandle":{zh:"点击打开菜单,按住拖动",en:"Click for menu, hold to drag"},"blocklayer.addBelow":{zh:"在下方插入块(按住 Alt 点击插到上方)",en:"Add block below (Alt-click to add above)"},"blocklayer.cardGrab":{zh:"选中所在卡片,按住拖动整卡",en:"Select card, hold to drag it"},"blocklayer.expandChildren":{zh:"展开子项",en:"Expand children"},"blocklayer.foldChildren":{zh:"折叠子项",en:"Collapse children"},"blocklayer.expandSection":{zh:"展开小节",en:"Expand section"},"blocklayer.foldSection":{zh:"折叠小节",en:"Collapse section"},"blocklayer.phParagraph":{zh:"输入 '/' 唤起命令",en:"Type '/' for commands"},"blocklayer.phHeading":{zh:"标题 {n}",en:"Heading {n}"}});function Gy(e,t,n,o){const{schema:r}=e,s=r.nodes.paragraph;if(!s)return null;const c=s.create(null,r.text("/"));let a=null;t.type.name==="list_item"?a=n:/_list$/.test(t.type.name)&&t.firstChild?.type.name==="list_item"&&(a=n+1);const i=a==null?null:e.doc.nodeAt(a);if(i&&a!=null){const p={...i.attrs,...i.attrs.checked!=null?{checked:!1}:{}},h=i.type.createAndFill(p,c);if(h){const M=o?a:a+i.nodeSize;return{at:M,node:h,caret:M+3}}}const d=o?n:n+t.nodeSize;return{at:d,node:c,caret:d+2}}function Fr(e){const t=e.offsetWidth;if(t<=0)return En(e);const n=En(e),o=e.getBoundingClientRect().width/t;return Math.abs(o-n)<.01?n:o}function Ui(e){return e.transform!=="none"||e.perspective!=="none"||e.filter!=="none"||e.backdropFilter&&e.backdropFilter!=="none"||e.containerType&&e.containerType!=="normal"||/\b(layout|paint|strict|content)\b/.test(e.contain??"")||e.contentVisibility==="auto"||e.contentVisibility==="hidden"?!0:/\b(transform|perspective|filter|backdrop-filter|contain)\b/.test(e.willChange??"")}function Or(e){const t=n=>{const o=n.getBoundingClientRect(),r=getComputedStyle(n);return{x:o.left+(Number.parseFloat(r.borderLeftWidth)||0),y:o.top+(Number.parseFloat(r.borderTopWidth)||0)}};if(getComputedStyle(e).position==="absolute"){let n=e.offsetParent;for(let o=e.parentElement;!n&&o;o=o.parentElement){const r=getComputedStyle(o);(r.position!=="static"||Ui(r))&&(n=o)}return n?t(n):{x:0,y:0}}for(let n=e.parentElement;n;n=n.parentElement)if(Ui(getComputedStyle(n)))return t(n);return{x:0,y:0}}const $a=(e,t)=>{if(!t)return!1;const n=t.type.name;return!(n==="amadeusColumnRow"||n==="amadeusColumnCell"||Lf(o=>o.type.name==="table"||o.type.name==="blockquote")(e))};function ns(e,t){try{const n=e.posAtCoords({left:t.x,top:t.y})?.inside;if(n==null||n<0)return null;let o=e.state.doc.resolve(n),r=e.state.doc.nodeAt(n),s=e.nodeDOM(n);const c=a=>{const i=o.depth>=1&&o.index(o.depth)===0&&!["amadeusColumnCell","amadeusCanvasCard"].includes(o.node(o.depth).type.name);if(!(a||i)||o.depth<1)return;const d=o.before(o.depth);r=e.state.doc.nodeAt(d),s=e.nodeDOM(d),o=e.state.doc.resolve(d),$a(o,r)||c(!0)};if(c(!$a(o,r)),!r||!$a(o,r)||!(s instanceof HTMLElement))return null;if(o.depth>=1&&o.node(o.depth).type.name==="amadeusCanvasCard"){const a=o.before(o.depth),i=e.nodeDOM(a);if(i instanceof HTMLElement){const d=i.firstElementChild?.getBoundingClientRect(),p=i.lastElementChild?.getBoundingClientRect();if(d&&t.y<d.top||p&&t.y>p.bottom){const h=e.state.doc.nodeAt(a);if(h)return{node:h,pos:a,el:i}}}}return{node:r,pos:o.pos,el:s}}catch{return null}}function Gi(e){const{$from:t}=e.selection;for(let n=t.depth;n>=1;n--)if(t.node(n).type.name==="blockquote")return t.before(n);for(let n=t.depth;n>=1;n--){const o=t.node(n);if(Ee.isSelectable(o)&&!(o.type.name==="paragraph"&&n>1))return t.before(n)}return null}function Jy(e){for(let t=e.parentElement;t;t=t.parentElement)if(/(auto|scroll)/.test(getComputedStyle(t).overflowY)&&t.scrollHeight>t.clientHeight)return t;return null}function Zy(e){let t=null,n=null;const o=new Dn("amx-block-selection-mode");let r=null,s=null;const c=y=>(s&&s.isConnected||(s=document.createElement("div"),s.className="unified-drop-vline",s.style.display="none",(y.dom.parentElement??document.body).appendChild(s)),s),a=(y,$,P)=>{const D=c(y),V=Fr(y.dom),U=Or(D),se=$.getBoundingClientRect(),G=(P==="left"?se.left-6:se.right+3)-U.x;D.style.display="block",D.style.height=`${se.height/V}px`,D.style.transform=`translate(${Math.round(G/V)}px, ${Math.round((se.top-U.y)/V)}px)`},i=()=>{s&&(s.style.display="none")},d=28,p=y=>/Mac/i.test(navigator.platform)?y.altKey:y.ctrlKey,h=y=>{const $=y.state.selection;if(!($ instanceof Ne)||$.empty||$.$from.sameParent($.$to))return null;const P=U=>{let se=U.depth;for(;se>=1&&!["doc","amadeusColumnCell"].includes(U.node(se-1).type.name);)se--;return se},D=P($.$from),V=P($.$to);return D<1||V<1||$.$from.node(D-1)!==$.$to.node(V-1)?null:{from:$.$from.before(D),to:$.$to.after(V)}},M=(y,$,P)=>{if(P.type.name!=="paragraph")return null;const D=y.state.doc.resolve($),V=D.parent;if(!["doc","amadeusColumnCell"].includes(V.type.name))return null;const U=Number(P.attrs.indent??0),se=D.index();let G=$+P.nodeSize,Q=0;for(let H=se+1;H<V.childCount;H++){const Me=V.child(H);if(Me.type.name!=="paragraph"||Number(Me.attrs.indent??0)<=U)break;G+=Me.nodeSize,Q++}return Q?{from:$,to:G}:null};let R=null;const T=(y,$,P,D,V)=>{Br(y,$,{from:P.from,to:P.to,newStart:D,copy:V}),Qr(y,$,{from:P.from,to:P.to,newStart:D}),R===P.from&&$.doc.nodeAt(D)?.type.name==="heading"&&($.setSelection(Ee.create($.doc,D)),R=null)},w=(y,$)=>{const{state:P}=y,D=P.doc.content.size,V=h(y);if(V){if(!$&&V.to===D)return!0;let H=P.doc.slice(V.from,V.to).content;if($){const Oe=ts(P.doc,H);H=Oe.content,Oe.minted.length&&e.onCardsMinted?.(Oe.minted)}let Me=P.tr;$||(Me=Me.delete(V.from,V.to));const Ie=Me.mapping.map(D);return Me=Me.insert(Ie,H),T(P,Me,V,Ie,$),Me.setMeta("amxColumns",!0),y.dispatch(Me.scrollIntoView()),!0}const U=P.selection;if(!(U instanceof Ee))return!1;if(!$&&U.to===D)return!0;const se=U.node,G=se.type.name==="list_item"?U.$from.parent.type.create(U.$from.parent.attrs,se):se;let Q=P.tr;return $||(Q=Q.delete(U.from,U.to)),Q=Q.insert(Q.mapping.map(D),G),Q.setMeta("amxColumns",!0),y.dispatch(Q.scrollIntoView()),!0},S=(y,$,P)=>{const D=h(y);if(!D)return!1;const V=le(y,$.clientY);if(!V)return!1;const U=V.el.getBoundingClientRect(),se=$.clientY>U.top+U.height/2?V.pos+V.node.nodeSize:V.pos;if(se>=D.from&&se<=D.to)return!0;let G=y.state.doc.slice(D.from,D.to).content;if(P){const Me=ts(y.state.doc,G);G=Me.content,Me.minted.length&&e.onCardsMinted?.(Me.minted)}mt(y,se);let Q=y.state.tr;P||(Q=Q.delete(D.from,D.to));const H=Q.mapping.map(se);return Q=Q.insert(H,G),T(y.state,Q,D,H,P),Q.setMeta("amxColumns",!0),y.dispatch(Q.scrollIntoView()),!0},I=(y,$,P)=>{const{state:D}=y,V=D.selection;if(!(V instanceof Ee))return!1;const U=D.doc.nodeAt($);if(!U||U.type.name!=="list_item"||$>=V.from&&$<V.to)return!1;const se=D.schema.nodes.list_item,G=D.schema.nodes.bullet_list;if(!se||!G)return!1;const Q=V.node;if(Q.type.name==="amadeusColumnRow"||Q.type.name==="amadeusColumnCell")return!1;const H=Q.type.name==="list_item"?Q:se.createAndFill(null,Q);if(!H)return!1;const Me=U.child(U.childCount-1),Ie=U.childCount>1&&/_list$/.test(Me.type.name);let Oe=D.tr;P||(Oe=Oe.delete(V.from,V.to));const _e=Oe.mapping.map($),Ke=Oe.doc.nodeAt(_e);if(!Ke||Ke.type.name!=="list_item")return!1;const We=Ie?_e+Ke.nodeSize-2:_e+Ke.nodeSize-1;return Oe=Oe.insert(We,Ie?H:(Me.type.name.endsWith("_list")?Me.type:G).create(null,H)),Oe.setMeta("amxColumns",!0),y.dispatch(Oe.scrollIntoView()),!0},X=y=>!!y.dom.closest(".unified-body")?.classList.contains("amx-canvas"),ee=(y,$,P,D)=>{let V=P;for(let U=0;U<$.childCount;U++){const se=$.child(U),G=y.nodeDOM(V),Q=G instanceof HTMLElement?G.getBoundingClientRect():null;if(Q&&D.clientY<=Q.bottom)return D.clientY>Q.top+Q.height/2?V+se.nodeSize:V;V+=se.nodeSize}return V},q=(y,$)=>{const P=y.state.doc,D=y.state.schema.nodes.amadeusCanvasCard;let V=0;for(let U=0;U<P.childCount;U++){const se=P.child(U);if(se.type===D)return V;const G=y.nodeDOM(V),Q=G instanceof HTMLElement?G.getBoundingClientRect():null;if(Q&&$.clientY<=Q.bottom)return $.clientY>Q.top+Q.height/2?V+se.nodeSize:V;V+=se.nodeSize}return V},oe=(y,$,P)=>{const D=y.state.selection;if(!(D instanceof Ee))return!1;const V=y.state.schema.nodes.amadeusCanvasCard;if(!V)return!1;const U=$.target;if(!U||!y.dom.contains(U))return!1;if(D.node.type===V)return!0;const se=U.closest?.(".amx-ucard");let G;if(se){let H;try{H=y.posAtDOM(se,0)-1}catch{return!1}const Me=y.state.doc.nodeAt(H);if(Me?.type!==V)return!1;G=ee(y,Me,H+1,$)}else G=q(y,$);if(G>=D.from&&G<=D.to)return!0;let Q=y.state.tr;return P||(Q=Q.delete(D.from,D.to)),Q=Q.insert(Q.mapping.map(G),D.node),Q.setMeta("amxColumns",!0),y.dispatch(Q.scrollIntoView()),!0},Re=y=>{const $=y.state.schema.nodes.amadeusCanvasCard,P=[];return $&&y.state.doc.forEach((D,V,U)=>{D.type===$&&P.push({anchor:String(D.attrs.anchor),idx:U,pos:V,size:D.nodeSize})}),P},Ge=(y,$)=>{const P=y.state.doc,D=y.state.schema.nodes.amadeusCanvasCard;if(!D)return null;const V=e.canvasTree?.()??{},U=Re(y),se=new Map;for(let _e=0;_e<U.length;){const Ke=Zs(U,_e,V);se.set(_e,Ke),_e=Ke}const G=_e=>{const Ke=y.nodeDOM(_e);return Ke instanceof HTMLElement?Ke:null},Q=[];let H=0,Me=0,Ie=-1;for(let _e=0;_e<P.childCount;_e++){const Ke=P.child(_e);if(H<Ie){Ke.type===D&&Me++,H+=Ke.nodeSize;continue}if(Ke.type===D){const We=se.get(Me);if(We!=null){const Ve=U[We-1];Q.push({from:H,to:Ve.pos+Ve.size,firstEl:G(H),lastEl:G(Ve.pos)})}Me++}else{let We=H+Ke.nodeSize,Ve;if(Ke.type.name==="heading"&&wr(y,H)==="folded"){const Xe=Ur(y.state,H);Xe!=null&&(We=Xe,Ie=Xe,Ve=H)}Q.push({from:H,to:We,firstEl:G(H),lastEl:G(H),foldPos:Ve})}H+=Ke.nodeSize}let Oe=null;for(let _e=0;_e<Q.length;_e++){const Ke=Q[_e];if(!Ke.firstEl||!Ke.lastEl)continue;const We=Ke.firstEl.getBoundingClientRect().top,Ve=Ke.lastEl.getBoundingClientRect().bottom;if(Oe={at:Ke.to,lineEl:Ke.lastEl,edge:"bottom",expandFold:Ke.foldPos},$.clientY>Ve)continue;const Xe=_e>0?Q[_e-1]:null;return $.clientY<=(We+Ve)/2?{at:Ke.from,lineEl:Ke.firstEl,edge:"top",expandFold:Xe&&Xe.foldPos!=null&&Xe.to===Ke.from?Xe.foldPos:void 0}:Oe}return Oe},m=(y,$)=>{const P=y.state.selection,D=y.state.schema.nodes.amadeusCanvasCard;if(!D||!(P instanceof Ee)||P.node.type!==D)return null;const V=Ge(y,$);if(!V)return null;const U=e.canvasTree?.()??{},se=Re(y),G=se.findIndex(Me=>Me.pos===P.from);if(G<0)return null;const Q=se[Zs(se,G,U)-1],H={from:P.from,to:Q.pos+Q.size};return{drop:V,range:H,self:V.at>=H.from&&V.at<=H.to}},ke=(y,$,P)=>{const D=y.state.selection,V=y.state.schema.nodes.amadeusCanvasCard;if(!V||!(D instanceof Ee)||D.node.type!==V)return!1;const U=m(y,$);if(!U||U.self)return!0;let se=y.state.doc.slice(U.range.from,U.range.to).content;if(P){const Q=ts(y.state.doc,se);se=Q.content,Q.minted.length&&e.onCardsMinted?.(Q.minted)}U.drop.expandFold!=null&&wr(y,U.drop.expandFold)==="folded"&&Rs(y,U.drop.expandFold);let G=y.state.tr;if(P||(G=G.delete(U.range.from,U.range.to)),G=G.insert(G.mapping.map(U.drop.at),se),G.setMeta("amxColumns",!0),y.dispatch(G.scrollIntoView()),!P){const Q=String(D.node.attrs.anchor),Me=(e.canvasTree?.()??{})[Q];typeof Me=="string"&&Re(y).some(Ie=>Ie.anchor===Me)&&e.onCardDetach?.([Q])}return!0};let rt=null,de=null,me=null,he=null,ze=!1,He=!1,Te=null;const dt=y=>(Te&&Te.isConnected||(Te=document.createElement("div"),Te.className="unified-drop-line",Te.style.display="none",Te.style.animation="none",(y.dom.parentElement??document.body).appendChild(Te)),Te),sn=(y,$,P=0,D="bottom")=>{const V=dt(y),U=Fr(y.dom),se=Or(V),G=$.getBoundingClientRect(),Q=D==="top"?G.top-6:G.bottom+6;V.style.display="block",V.style.width=`${Math.max(0,G.width-P)/U}px`,V.style.transform=`translate(${Math.round((G.left+P-se.x)/U)}px, ${Math.round((Q-se.y)/U)}px)`},re=()=>{Te&&(Te.style.display="none")},ce=(y,$)=>{const P=y.state.doc.resolve($);if(P.depth===0)return y.state.doc.nodeAt($)?.type.name!=="amadeusCanvasCard";for(let D=P.depth;D>=1;D--)if(P.node(D).type.name==="amadeusColumnRow")return D===1;return!1},ge=y=>y instanceof HTMLElement&&y.getClientRects().length>0,k=(y,$)=>{if(X(y))return null;const P=y.state.selection,D=P instanceof Ee?{from:P.from,to:P.to}:h(y);if(!D)return null;const V=$.target instanceof Element?$.target.closest("blockquote"):null;if(!(V instanceof HTMLElement)||!y.dom.contains(V))return null;let U;try{U=y.posAtDOM(V,0)-1}catch{return null}const se=y.state.doc.nodeAt(U);if(se?.type.name!=="blockquote"||y.nodeDOM(U)!==V)return null;const G=y.state.doc.slice(D.from,D.to).content;let Q=!1;if(G.descendants(_e=>{["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell"].includes(_e.type.name)&&(Q=!0)}),Q)return null;const H=!!se.firstChild?.isTextblock&&/^\[![\w-]+\]/.test(se.firstChild.textContent),Me=y.nodeDOM(U+1);if(H&&ge(Me)){const _e=Me.getBoundingClientRect();if($.clientY<_e.top+_e.height/2)return null}let Ie=null;if(se.forEach((_e,Ke)=>{const We=U+1+Ke,Ve=y.nodeDOM(We);if(!ge(Ve))return;const Xe=Ve.getBoundingClientRect(),Ut=$.clientY<Xe.top+Xe.height/2?"top":"bottom",pt=Math.abs($.clientY-(Ut==="top"?Xe.top:Xe.bottom));(!Ie||pt<Ie.distance)&&(Ie={at:Ut==="top"?We:We+_e.nodeSize,lineEl:Ve,edge:Ut,distance:pt})}),!Ie)return null;const Oe=Ie;return{...Oe,self:Oe.at>=D.from&&Oe.at<=D.to}},J=(y,$,P)=>{const D=k(y,$);if(!D)return!1;if(D.self)return!0;const{state:V}=y,U=V.selection,se=U instanceof Ee?{from:U.from,to:U.to}:h(y);if(!se)return!1;const G=U instanceof Ee&&U.node.type.name==="list_item"?So.from(U.$from.parent.type.create(U.$from.parent.attrs,U.node)):V.doc.slice(se.from,se.to).content,Q=P?V.tr:V.tr.delete(se.from,se.to),H=Q.mapping.map(D.at),Me=Q.doc.resolve(H);return Me.parent.type.name!=="blockquote"||!Me.parent.canReplace(Me.index(),Me.index(),G)?!1:(Q.insert(H,G),T(V,Q,se,H,P),Xs(Q,H,H+G.size),Q.setSelection(G.childCount===1&&Ee.isSelectable(G.firstChild)?Ee.create(Q.doc,H):Ne.between(Q.doc.resolve(H),Q.doc.resolve(H+G.size))),Q.setMeta("amxColumns",!0).setMeta("uiEvent","drop"),y.dispatch(Q.scrollIntoView()),y.focus(),!0)},le=(y,$)=>{const P=y.state.doc;let D=null,V=1/0;for(let U=0,se=0;U<P.childCount;se+=P.child(U).nodeSize,U++){const G=y.nodeDOM(se);if(!ge(G))continue;const Q=G.getBoundingClientRect(),H=$<Q.top?Q.top-$:$>Q.bottom?$-Q.bottom:0;if(H===0)return{pos:se,node:P.child(U),el:G};H<V&&(V=H,D={pos:se,node:P.child(U),el:G})}return D},ve=(y,$)=>{const P=y.state.selection,D=p($),V=U=>!D&&P instanceof Ee&&U>=P.from&&U<=P.to;for(const U of y.dom.querySelectorAll(":scope > .amx-ucolrow")){const se=U.getBoundingClientRect();if(!($.clientY<se.top||$.clientY>se.bottom||$.clientX<se.left||$.clientX>se.right)){for(const G of Array.from(U.children)){if(!ge(G)||!("amxColcell"in G.dataset))continue;const Q=G.getBoundingClientRect();if(!($.clientX<Q.left||$.clientX>Q.right))try{const H=y.posAtDOM(G,0)-1,Me=y.state.doc.nodeAt(H);if(Me?.type.name!=="amadeusColumnCell")return null;let Ie=H+1,Oe=null;for(let _e=0;_e<Me.childCount;_e++){const Ke=Me.child(_e),We=y.nodeDOM(Ie);if(ge(We)){const Ve=We.getBoundingClientRect();if($.clientY<=Ve.bottom){if($.clientY>=Ve.top&&(!Ke.isTextblock&&!Ke.isAtom||$.clientX<=Ve.left+d||$.clientX>=Ve.right-d))return null;const Xe=$.clientY<=Ve.top+Ve.height/2,Ut=Xe?Ie:Ie+Ke.nodeSize;return{cellEl:G,lineEl:We,pos:Ie,edge:Xe?"top":"bottom",tail:!1,self:V(Ut)}}Oe=We}Ie+=Ke.nodeSize}return Oe?{cellEl:G,lineEl:Oe,pos:H,edge:"bottom",tail:!0,self:V(H+Me.nodeSize-1)}:null}catch{return null}}return null}}return null},Ye=(y,$)=>{if(!$.cellEl.isConnected||!$.lineEl.isConnected)return null;try{if($.tail){const V=y.posAtDOM($.cellEl,0)-1,U=y.state.doc.nodeAt(V);return U?.type.name==="amadeusColumnCell"?V+U.nodeSize-1:null}const P=y.state.doc.nodeAt($.pos);if(!P||y.nodeDOM($.pos)!==$.lineEl)return null;const D=$.edge==="top"?$.pos:$.pos+P.nodeSize;return y.state.doc.resolve(D).parent.type.name==="amadeusColumnCell"?D:null}catch{return null}},Fe=(y,$)=>{try{const P=y.state.doc.resolve($),D=P.parent;let V=P.start();for(let U=0;U<D.childCount&&V<$;U++){const se=D.child(U);if(se.type.name==="heading"&&wr(y,V)==="folded"){const G=Ur(y.state,V);if(G!=null&&$>V&&$<=G)return V}V+=se.nodeSize}}catch{}return null},mt=(y,$)=>{for(let P=Fe(y,$),D=-1;P!=null&&P!==D;D=P,P=Fe(y,$))Rs(y,P)};let it=null;const _t=()=>{it&&(it.style.display="none")};let jt=!1,ht=!1;const Mt=()=>{ht||(ht=!0,jt=!1,queueMicrotask(()=>{ht=!1,jt||_t()}))},ot=Et(()=>new qt({key:new Dn("UNIFIED_BLOCK_HANDLE"),view:y=>{t=y,gi.add(y);const $=y.dom.parentElement??document.body,P=$.closest(".unified-body")??$,D=A=>{for(const F of P.querySelectorAll(".amx-ucard.amx-droptarget"))F.classList.remove("amx-droptarget");A?.classList.add("amx-droptarget")},V=document.createElement("div");V.className="unified-gutter",V.dataset.show="false";const U=()=>{V.dataset.show="false",n=null},se=A=>{if(!y.editable)return;n=A,pt(A),Je.style.display=Un(A)?"":"none";const F=Fr(y.dom),ue=Or(V),xe=yi(A.el),$e=xe.getBoundingClientRect(),Z=(A.el.tagName==="LI"&&/^(UL|OL)$/.test(A.el.parentElement?.tagName??"")?A.el.parentElement:null)?.getBoundingClientRect().left??$e.left,Ze=getComputedStyle(xe),Qe=Number.parseFloat(Ze.lineHeight)||24,ut=(Number.parseFloat(Ze.paddingTop)||0)+Math.max(0,(Qe-24)/2),yt=$e.height/F,Rt=Math.max(24,yt-16),$t=Rt>24?Rt/2-4-ut:0;V.dataset.show="true",V.style.setProperty("--amx-block-h",`${yt}px`),V.style.setProperty("--amx-block-grow-y",`${$t}px`);const ln=V.offsetWidth||52;V.style.top=`${($e.top-ue.y)/F+ut}px`;let Dt=(Z-ue.x)/F-ln-8;Vr()&&(Dt=Math.max(Dt,(2-ue.x)/F-G.offsetLeft)),V.style.left=`${Dt}px`},G=document.createElement("button");G.type="button",G.className="drag-handle",G.textContent="⠿",G.draggable=!0,G.title=we("blocklayer.dragHandle"),G.setAttribute("aria-label",G.title),G.addEventListener("click",A=>{A.stopPropagation();const F=G.getBoundingClientRect();if(A.detail===0&&t&&n){const ue=t.state.selection;ue instanceof Ee&&ue.from<=n.pos&&n.pos+n.node.nodeSize<=ue.to||Q(t,n)}e.onMenu({x:F.left,y:F.bottom+4,keyboard:A.detail===0}),Vr()||t?.focus()}),V.addEventListener("mousedown",()=>{t&&n&&Q(t,n)});const Q=(A,F)=>{const ue=A.state.selection,xe=F.pos+1,$e=F.pos+F.node.nodeSize-1;if(ue instanceof Ne&&!ue.empty&&!ue.$from.sameParent(ue.$to)&&ue.from<=xe&&ue.to>=$e){A.focus();return}const Ae=M(A,F.pos,F.node);if(Ae){const Z=A.state.doc;A.dispatch(A.state.tr.setSelection(Ne.between(Z.resolve(Ae.from+1),Z.resolve(Ae.to-1))).setMeta(o,!0)),A.focus();return}Ee.isSelectable(F.node)&&(A.dispatch(A.state.tr.setSelection(Ee.create(A.state.doc,F.pos))),A.focus())};let H=null;const Me=()=>{const A=t,F=n;if(!A||!F)return;(!H||!H.isConnected)&&(H=document.createElement("div"),H.className="unified-press-rect",(A.dom.parentElement??document.body).appendChild(H));const ue=Fr(A.dom),xe=Or(H),$e=yi(F.el).getBoundingClientRect(),Ae=h(A);let Z={left:$e.left-xe.x,top:$e.top-xe.y,right:$e.right-xe.x,bottom:$e.bottom-xe.y};if(Ae)for(const Ze of Array.from(A.dom.children)){if(!Ze.classList.contains("amx-block-selected"))continue;const Qe=Ze.getBoundingClientRect();Z={left:Math.min(Z.left,Qe.left-xe.x),top:Math.min(Z.top,Qe.top-xe.y),right:Math.max(Z.right,Qe.right-xe.x),bottom:Math.max(Z.bottom,Qe.bottom-xe.y)}}Object.assign(H.style,{display:"block",transform:`translate(${Math.round((Z.left-4)/ue)}px, ${Math.round((Z.top-4)/ue)}px)`,width:`${(Z.right-Z.left+8)/ue}px`,height:`${(Z.bottom-Z.top+8)/ue}px`})},Ie=()=>{H&&(H.style.display="none")};V.addEventListener("mousedown",Me),window.addEventListener("mouseup",Ie);const Oe=(A,F,ue)=>{A.dom.dataset.dragging="true";let xe=A.state.selection;if(R=null,xe instanceof Ee&&wr(A,xe.from)==="folded"){const Ae=xe.from,Z=Ur(A.state,Ae),Ze=A.state.doc;if(Z!=null){A.dispatch(A.state.tr.setSelection(Ne.between(Ze.resolve(Ae+1),Ze.resolve(Z-1))).setMeta(o,!0));const Qe=h(A);Qe&&Qe.from===Ae&&Qe.to===Z?R=Ae:A.dispatch(A.state.tr.setSelection(Ee.create(A.state.doc,Ae)))}R==null&&Rs(A,Ae),xe=A.state.selection}xe instanceof Ee&&Ds(A,xe.from)==="folded"&&ya(A,xe.from);const $e=xe instanceof Ne&&!xe.empty&&!xe.$from.sameParent(xe.$to);if(F.dataTransfer&&(xe instanceof Ee||$e)){const Ae=xe.content();F.dataTransfer.effectAllowed="copyMove";const{dom:Z,text:Ze}=A.serializeForClipboard(Ae);F.dataTransfer.clearData(),F.dataTransfer.setData("text/html",Z.innerHTML),F.dataTransfer.setData("text/plain",Ze),ue&&F.dataTransfer.setDragImage(ue,0,0),A.dragging={slice:Ae,move:!0}}};V.addEventListener("dragstart",A=>{t&&Oe(t,A,n?.el??null)});const _e=A=>{const F=t;if(!F||!(A.target instanceof Node)||!F.dom.contains(A.target)||!A.target.closest?.(".wiki-inline-img-wrap"))return;const ue=tp(A.target);let xe=-1;try{ue&&(xe=F.posAtDOM(ue,0)-1)}catch{}const $e=ue?.querySelector(":scope > .wiki-inline-img-wrap")?.getBoundingClientRect(),Ae=$e?ns(F,{x:$e.left+$e.width/2,y:$e.top+$e.height/2}):null;if(!ue||!A.dataTransfer||F.nodeDOM(xe)!==ue||!Ae||xe<Ae.pos||xe>=Ae.pos+Ae.node.nodeSize){A.preventDefault();return}A.stopPropagation(),Q(F,Ae),Oe(F,A,null),A.target.addEventListener("dragend",Ke,{once:!0})};P.addEventListener("dragstart",_e,!0);const Ke=()=>{const A=t;if(A&&R!=null){const F=h(A);F&&F.from===R&&A.state.doc.nodeAt(R)?.type.name==="heading"&&A.dispatch(A.state.tr.setSelection(Ee.create(A.state.doc,R))),R=null}Ie(),D(null),r=null,me=null,he=null,de=null,He=!1,ze=!1,i(),re(),_t(),A&&(A.dom.dataset.dragging="false",A.dragging=null)};V.addEventListener("dragend",Ke);const We=document.createElement("button");We.type="button",We.className="block-add block-fold",We.textContent="▾",We.style.display="none";const Ve=A=>{const F=t;return F?Ds(F,A.pos)?A.pos:/_list$/.test(A.node.type.name)&&Ds(F,A.pos+1)?A.pos+1:null:null},Xe=A=>{const F=t;return F?wr(F,A.pos)?A.pos:!A.node.isTextblock&&A.node.childCount>0&&wr(F,A.pos+1)?A.pos+1:null:null},Ut=A=>!t||!A?null:Xe(A)!=null?"heading":Ve(A)!=null?"list":null,pt=A=>{const F=t,ue=Ut(A),xe=A?Ve(A):null,$e=A?Xe(A):null,Ae=!F||!A||!ue?null:ue==="heading"?$e==null?null:wr(F,$e):xe==null?null:Ds(F,xe);We.style.display=Ae?"":"none",We.textContent=Ae==="folded"?"▸":"▾",We.title=ue==="list"?Ae==="folded"?we("blocklayer.expandChildren"):we("blocklayer.foldChildren"):Ae==="folded"?we("blocklayer.expandSection"):we("blocklayer.foldSection"),We.setAttribute("aria-label",We.title),We.setAttribute("aria-expanded",String(Ae!=="folded"))};We.addEventListener("click",A=>{A.stopPropagation();const F=t,ue=n;if(!F||!ue)return;const xe=Ut(ue)==="list"?Ve(ue):null;if(xe!=null)ya(F,xe);else{const $e=Xe(ue);if($e==null)return;Rs(F,$e)}pt(ue)});const gt=document.createElement("button");gt.type="button",gt.className="block-add",gt.textContent="+",gt.title=we("blocklayer.addBelow"),gt.setAttribute("aria-label",gt.title),gt.addEventListener("click",A=>{A.stopPropagation();const F=t,ue=n;if(!F||!ue)return;const xe=Gy(F.state,ue.node,ue.pos,A.altKey);if(!xe)return;F.focus();let $e=F.state.tr.insert(xe.at,xe.node);$e=$e.setSelection(Ne.create($e.doc,xe.caret)).scrollIntoView(),Nd(F,xe.caret),F.dispatch($e),U()});const Je=document.createElement("button");Je.type="button",Je.className="card-grab",Je.textContent="❏",Je.draggable=!0,Je.title=we("blocklayer.cardGrab"),Je.setAttribute("aria-label",Je.title),Je.style.display="none";const Un=A=>{const F=t;if(!F||!A||A.node.type.name==="amadeusCanvasCard")return null;try{const ue=F.state.doc.resolve(A.pos);for(let xe=ue.depth;xe>=1;xe--){if(ue.node(xe).type.name!=="amadeusCanvasCard")continue;const $e=ue.before(xe),Ae=F.state.doc.nodeAt($e),Z=F.nodeDOM($e);return Ae&&Z instanceof HTMLElement?{node:Ae,pos:$e,el:Z}:null}}catch{}return null};Je.addEventListener("mousedown",A=>{const F=t,ue=Un(n);!F||!ue||(A.stopPropagation(),n=ue,F.dispatch(F.state.tr.setSelection(Ee.create(F.state.doc,ue.pos))),F.focus(),Me())}),Je.addEventListener("click",A=>{if(A.stopPropagation(),!n)return;const F=Je.getBoundingClientRect();e.onMenu({x:F.left,y:F.bottom+4,keyboard:A.detail===0}),Vr()||t?.focus()}),V.append(Je,G,gt,We);let Pt=null,Qt=null,Gn=null;const $o=()=>{const A=[];for(const F of Array.from(y.dom.children))if(F.classList.contains("amx-ucolrow"))for(const ue of Array.from(F.querySelectorAll(".amx-ucolcell")))A.push(...Array.from(ue.children));else A.push(F);return A},jr=(A,F,ue)=>{const xe=A.getBoundingClientRect();if(F<xe.left||F>xe.right||ue<xe.top||ue>xe.bottom)return!1;if(A.matches("hr, table, pre, .amx-ucard"))return!0;const $e=Z=>F>=Z.left-2&&F<=Z.right+2&&ue>=Z.top-2&&ue<=Z.bottom+2;for(const Z of A.querySelectorAll(".unified-embed, .wiki-inline-img-wrap, .wikilink, img, video, iframe, canvas"))if($e(Z.getBoundingClientRect()))return!0;const Ae=document.createTreeWalker(A,NodeFilter.SHOW_TEXT);for(let Z=Ae.nextNode();Z;Z=Ae.nextNode()){if(!Z.textContent?.length)continue;const Ze=document.createRange();Ze.selectNodeContents(Z);const Qe=Ze.getClientRects();if(!Qe.length)continue;const zt=Z.parentElement,ut=zt?parseFloat(getComputedStyle(zt).lineHeight)*En(zt):NaN;for(const yt of Qe){const Rt=Math.max(2,(ut-yt.height)/2||0);if(F>=yt.left-2&&ue>=yt.top-Rt&&ue<=yt.bottom+Rt)return!0}}return!1},Bn=A=>{if(window.removeEventListener("mouseup",Go),A.button!==0||P.classList.contains("amx-canvas"))return;const F=A.target;if(!F||F.closest(".unified-gutter")||F.closest(".amx-embed")||F.closest("button, input, textarea, a")||!y.editable)return;if(A.pointerType==="touch")return In();const ue=$o();if(ue.some(Ae=>jr(Ae,A.clientX,A.clientY)))return In();const xe=F.closest('li[data-item-type="task"]');if(xe&&A.clientX-xe.getBoundingClientRect().left<=2)return;if(ue.some(Ae=>{const Z=Ae.getBoundingClientRect();return A.clientX>=Z.left&&A.clientX<=Z.right&&A.clientY>=Z.top&&A.clientY<=Z.bottom})){Gn={x:A.clientX,y:A.clientY},window.addEventListener("pointermove",No),window.addEventListener("pointerup",co,{once:!0});return}A.preventDefault(),pr(A.clientX,A.clientY)},pr=(A,F)=>{Qt={x:A,y:F},Pt=document.createElement("div"),Pt.className="amx-marquee",document.body.appendChild(Pt),document.body.classList.add("amx-marquee-active"),window.addEventListener("pointermove",To),window.addEventListener("pointerup",Zo,{once:!0})},Ao=()=>{Gn=null,window.removeEventListener("pointermove",No),window.removeEventListener("pointerup",co)},In=()=>window.addEventListener("mouseup",Go,{once:!0}),co=()=>{Ao(),In()},Go=()=>{y.isDestroyed||y.domObserver?.flush?.()},No=A=>{const F=Gn;!F||Math.abs(A.clientX-F.x)<=4&&Math.abs(A.clientY-F.y)<=4||(Ao(),pr(F.x,F.y),eo=!0,window.addEventListener("dragstart",xn,!0),window.addEventListener("selectionchange",xn,!0),To(A))};let eo=!1;const xn=A=>{A.type==="dragstart"?A.preventDefault():A.stopImmediatePropagation()},Jo=()=>{if(!eo)return;eo=!1,window.removeEventListener("dragstart",xn,!0);let A=!1;const F=()=>{if(A)return;A=!0,window.removeEventListener("mouseup",ue,!0),clearTimeout(xe);const $e=t;$e&&!$e.isDestroyed&&$e.focus(),eo||window.removeEventListener("selectionchange",xn,!0)},ue=()=>{setTimeout(F,0)},xe=setTimeout(F,300);window.addEventListener("mouseup",ue,{capture:!0,once:!0})},To=A=>{if(!Pt||!Qt)return;const F=Math.min(Qt.x,A.clientX),ue=Math.min(Qt.y,A.clientY),xe=Math.abs(A.clientX-Qt.x),$e=Math.abs(A.clientY-Qt.y),Ae=En(Pt);Object.assign(Pt.style,{left:`${F/Ae}px`,top:`${ue/Ae}px`,width:`${xe/Ae}px`,height:`${$e/Ae}px`});const Z=[],Ze=[];for(const $t of $o()){const ln=$t.getBoundingClientRect();if(!(ln.bottom<ue||ln.top>ue+$e||ln.right<F||ln.left>F+xe))try{Z.push(y.posAtDOM($t,0)),Ze.push($t)}catch{}}if(!Z.length)return;const Qe=y.state.doc;if(Ze.length===1){const $t=Ze[0];try{const ln=Array.prototype.indexOf.call($t.parentNode?.childNodes,$t),Dt=y.posAtDOM($t.parentNode,ln),Vn=Qe.nodeAt(Dt);if(Vn&&Ee.isSelectable(Vn)){const Hn=Ee.create(Qe,Dt);Hn.eq(y.state.selection)||y.dispatch(y.state.tr.setSelection(Hn));return}}catch{}}const zt=Math.min(...Z),ut=Ze[Ze.length-1];if(!ut)return;let yt=zt;try{const $t=y.posAtDOM(ut,0),ln=y.state.doc.nodeAt($t-1);yt=ln?$t+ln.content.size:$t}catch{}const Rt=Ne.between(Qe.resolve(Math.min(zt,Qe.content.size)),Qe.resolve(Math.min(yt,Qe.content.size)));(!Rt.eq(y.state.selection)||!o.getState(y.state))&&y.dispatch(y.state.tr.setSelection(Rt).setMeta(o,!0))},Zo=A=>{window.removeEventListener("pointermove",To),Jo();const F=!!(A&&Qt&&(Math.abs(A.clientX-Qt.x)>4||Math.abs(A.clientY-Qt.y)>4)),ue=Qt;if(Pt?.remove(),Pt=null,Qt=null,document.body.classList.remove("amx-marquee-active"),F){y.focus();return}if(!ue||!A)return;const xe=y.dom.getBoundingClientRect(),$e=Math.min(Math.max(A.clientX,xe.left+8),xe.right-8);let Ae=y.posAtCoords({left:$e,top:A.clientY});if(Ae&&!y.state.doc.resolve(Ae.pos).parent.isTextblock){let Qe=null,zt=1/0;for(const ut of $o()){const yt=ut.getBoundingClientRect(),Rt=Math.hypot(Math.max(yt.left-A.clientX,0,A.clientX-yt.right),Math.max(yt.top-A.clientY,0,A.clientY-yt.bottom));Rt<zt&&(zt=Rt,Qe=yt)}Qe&&(Ae=y.posAtCoords({left:Math.min(Math.max(A.clientX,Qe.left+1),Qe.right-1),top:Math.min(Math.max(A.clientY,Qe.top+1),Qe.bottom-1)}))}if(!Ae)return;const Z=y.state.doc.resolve(Ae.pos);if(!Z.parent.isTextblock)return;const Ze=A.clientX<xe.left+xe.width/2?Z.start():Z.end();y.dispatch(y.state.tr.setSelection(Ne.near(y.state.doc.resolve(Ze)))),y.focus()};P.addEventListener("pointerdown",Bn),$.appendChild(V);let io=0,Yn=null;const hr=A=>{if(V.contains(A.target)){Yn&&clearTimeout(Yn),Yn=null;return}const F=Date.now();if(F-io<80){const{clientX:ue,clientY:xe}=A;Yn&&clearTimeout(Yn),Yn=setTimeout(()=>{Yn=null,io=Date.now(),vo(ue,xe)},80);return}io=F,vo(A.clientX,A.clientY)},vo=(A,F)=>{const ue={clientX:A,clientY:F};if(y.dom.dataset.dragging==="true")return;let xe=ns(y,{x:ue.clientX,y:ue.clientY});if(!xe){const $e=y.dom.getBoundingClientRect();if(ue.clientY>=$e.top&&ue.clientY<=$e.bottom&&(ue.clientX<$e.left+8||ue.clientX>$e.right-8)){const Ae=Math.min(Math.max(ue.clientX,$e.left+8),$e.right-8);xe=ns(y,{x:Ae,y:ue.clientY})}}xe&&se(xe)};P.addEventListener("mousemove",hr,{passive:!0});const jo=A=>{const F=A.relatedTarget;F&&(V.contains(F)||P.contains(F))||U()};P.addEventListener("mouseleave",jo);const gr=()=>{y.dom.dataset.dragging!=="true"&&U()};y.dom.addEventListener("keydown",gr);const lo=A=>{const F=t;if(!F||!F.editable)return;const ue=F.state.selection,xe=ue instanceof Ee?{from:ue.from,to:ue.to}:o.getState(F.state)?h(F):null;let $e=!1;if(xe){const Ae=ue instanceof Ee?F.nodeDOM(ue.from):null,Z=F.posAtCoords({left:A.clientX,top:A.clientY});$e=Ae instanceof Node&&A.target instanceof Node&&Ae.contains(A.target)||!!Z&&Z.pos>=xe.from&&Z.pos<=xe.to}if(!$e){const Ae=A.target instanceof Element?A.target:null,Z=Ae?.closest('[contenteditable="false"]'),Ze=!!Ae&&(!!Z&&Z!==F.dom&&F.dom.contains(Z)||/^(IMG|VIDEO|AUDIO|HR|CANVAS|IFRAME)$/.test(Ae.tagName)),Qe=F.state.selection.empty?Ae?.closest("td, th"):null;let zt=null;if(Qe&&F.dom.contains(Qe)){const Rt=F.state.doc.resolve(F.posAtDOM(Qe,0));for(let $t=Rt.depth;$t>0;$t--)if(Rt.node($t).type.spec.tableRole==="table"){zt=Rt.before($t);break}}if(!Ze&&zt==null)return;const ut=zt??ns(F,{x:A.clientX,y:A.clientY})?.pos,yt=ut==null?null:F.state.doc.nodeAt(ut);if(ut==null||!yt||!Ee.isSelectable(yt))return;F.dispatch(F.state.tr.setSelection(Ee.create(F.state.doc,ut)))}A.preventDefault(),F.focus(),e.onMenu({x:A.clientX,y:A.clientY})};y.dom.addEventListener("contextmenu",lo),V.addEventListener("contextmenu",A=>{const F=t;!F||!F.editable||!n||(A.preventDefault(),Vr()||F.focus(),e.onMenu({x:A.clientX,y:A.clientY}))});const wo=()=>{y.dom.dataset.dragging!=="true"&&U()};window.addEventListener("scroll",wo,{capture:!0,passive:!0});const en=A=>{if(y.dom.dataset.dragging!=="true")return;const F=Jy(y.dom);if(!F)return;const ue=F.getBoundingClientRect();A.clientY<ue.top+56?F.scrollTop-=14:A.clientY>ue.bottom-56&&(F.scrollTop+=14)};window.addEventListener("dragover",en);const Qo=A=>{const F=t,ue=A.dataTransfer?Array.from(A.dataTransfer.types):[];if(ue.includes("Files")||ue.includes(Rf)&&F&&!X(F)){if(!F)return;const Z=le(F,A.clientY);if(!Z)return;const Ze=Z.el.getBoundingClientRect();rt={pos:Z.pos,el:Z.el,lower:A.clientY>Ze.top+Ze.height/2},sn(F,Z.el);return}if(!F||F.dom.dataset.dragging!=="true")return;ze&&re(),ze=!1;{const Z=F.state.selection;if(!X(F)&&Z instanceof Ee&&Z.node.type===F.state.schema.nodes.amadeusCanvasCard){He=!1,r=null,de=null,me=null,he=null,i();const Ze=m(F,A);Ze&&!Ze.self?(sn(F,Ze.drop.lineEl,0,Ze.drop.edge),A.preventDefault()):re();return}}const xe=k(F,A);if(xe){ze=!0,r=null,de=null,me=null,he=null,He=!1,i(),_t(),xe.self?re():sn(F,xe.lineEl,0,xe.edge),A.preventDefault();return}if(He=!1,he=null,!X(F)){const Ze=F.state.selection instanceof Ee||!!h(F),Qe=F.dom.lastElementChild;if(Ze&&ge(Qe)){const zt=Qe.getBoundingClientRect(),ut=F.dom.getBoundingClientRect();if(A.clientY>zt.bottom+2&&A.clientX>=ut.left&&A.clientX<=ut.right){He=!0,r=null,de=null,me=null,i(),sn(F,Qe),A.preventDefault();return}}}if(!(F.state.selection instanceof Ee))return;if(X(F)){D(A.target?.closest?.(".amx-ucard")),me=null,re(),A.preventDefault();return}const $e=ve(F,A);if($e){he={cellEl:$e.cellEl,lineEl:$e.lineEl,pos:$e.pos,edge:$e.edge,tail:$e.tail,self:$e.self},me=null,r=null,de=null,i(),_t(),$e.self?re():sn(F,$e.lineEl,0,$e.edge),A.preventDefault();return}let Ae=null;for(const Z of F.dom.querySelectorAll(":scope > .amx-ucolrow")){const Ze=Z.getBoundingClientRect();if(A.clientX<Ze.left||A.clientX>Ze.right||A.clientY<=Ze.bottom+2)continue;const Qe=Z.nextElementSibling;Qe&&A.clientY>=Qe.getBoundingClientRect().top-2||(Ae=Z)}if(Ae)try{const Z=F.posAtDOM(Ae,0)-1;if(F.state.doc.nodeAt(Z)?.type.name==="amadeusColumnRow"){me={rowEl:Ae},sn(F,Ae),A.preventDefault();return}}catch{}me=null,re()};P.addEventListener("dragover",Qo,!0);const Tt=A=>{const F=A.relatedTarget;F&&P.contains(F)||(me=null,he=null,rt=null,de=null,r=null,ze=!1,i(),re(),_t(),D(null))};P.addEventListener("dragleave",Tt,!0);const Gt=A=>{const F=t,ue=r,xe=me,$e=he,Ae=de,Z=rt,Ze=He,Qe=ze;if(r=null,me=null,he=null,de=null,rt=null,He=!1,ze=!1,i(),re(),_t(),D(null),!F)return;if(Z){try{const yt=F.nodeDOM(Z.pos)===Z.el?F.state.doc.nodeAt(Z.pos):null;if(yt){mt(F,Z.pos+yt.nodeSize);const Rt=F.state.doc;F.dispatch(F.state.tr.setSelection(yt.isAtom?Ee.create(Rt,Z.pos):Ne.near(Rt.resolve(Z.lower?Z.pos+1+yt.content.size:Z.pos+1),Z.lower?-1:1)))}}catch{}return}const zt=p(A);let ut=X(F)?oe(F,A,zt):ke(F,A,zt);if(!ut)if(Ze)ut=w(F,zt);else if(Qe)ut=J(F,A,zt);else if(h(F))ut=S(F,A,zt);else if(Ae)ut=I(F,Ae.targetPos,zt);else if(xe)try{xe.rowEl.isConnected&&(ut=ry(F,F.posAtDOM(xe.rowEl,0)-1,zt))}catch{ut=!1}else if($e){const yt=Ye(F,$e);yt!=null&&($e.self||mt(F,yt),ut=sy(F,yt,zt))}else ue&&(ut=oy(F,ue.targetPos,ue.side,zt));ut&&(A.preventDefault(),A.stopPropagation(),F.dom.dataset.dragging="false",F.dragging=null)};P.addEventListener("drop",Gt,!0);let uo=null;const fo=A=>{const F=t,ue=A.target;if(!F||!ue||!ue.classList?.contains("amx-ucolrow"))return;const xe=ue,$e=[...xe.children].filter(Dt=>Dt instanceof HTMLElement&&"amxColcell"in Dt.dataset);let Ae=-1;for(let Dt=0;Dt<$e.length-1;Dt++)if(A.clientX>=$e[Dt].getBoundingClientRect().right-2&&A.clientX<=$e[Dt+1].getBoundingClientRect().left+2){Ae=Dt;break}if(Ae<0)return;A.preventDefault();const Z=$e[Ae],Ze=$e[Ae+1],Qe=Z.getBoundingClientRect().left,zt=Ze.getBoundingClientRect().right-Qe,ut=(Number(Z.dataset.width)||1)+(Number(Ze.dataset.width)||1),yt=Dt=>Math.min(.85,Math.max(.15,(Dt.clientX-Qe)/zt)),Rt=Dt=>{const Vn=yt(Dt);Z.style.flexGrow=String(ut*Vn),Ze.style.flexGrow=String(ut*(1-Vn))},$t=()=>{window.removeEventListener("pointermove",Rt),window.removeEventListener("pointerup",ln),window.removeEventListener("pointercancel",$t),uo=null},ln=Dt=>{$t();const Vn=yt(Dt),Hn=u=>Math.round(u*1e4)/1e4;try{const u=F.posAtDOM(xe,0)-1,z=F.state.doc.nodeAt(u);if(!z||z.type.name!=="amadeusColumnRow")return;let N=u+1,B=F.state.tr;for(let K=0;K<z.childCount;K++){const O=z.child(K);K===Ae&&(B=B.setNodeMarkup(N,void 0,{...O.attrs,width:Hn(ut*Vn)})),K===Ae+1&&(B=B.setNodeMarkup(N,void 0,{...O.attrs,width:Hn(ut*(1-Vn))})),N+=O.nodeSize}B.setMeta("amxColumns",!0),F.dispatch(B)}catch{}};window.addEventListener("pointermove",Rt),window.addEventListener("pointerup",ln),window.addEventListener("pointercancel",$t),uo=$t};$.addEventListener("pointerdown",fo);const Kn=Al(()=>{G.title=we("blocklayer.dragHandle"),gt.title=we("blocklayer.addBelow"),Je.title=we("blocklayer.cardGrab");for(const A of[G,gt,Je])A.setAttribute("aria-label",A.title)});return{update:A=>{const F=n;if(!F)return;let ue=!1;try{ue=F.pos<=A.state.doc.content.size&&A.state.doc.nodeAt(F.pos)===F.node}catch{}ue||U()},destroy:()=>{window.removeEventListener("mouseup",Ie),H?.remove(),H=null,Yn&&clearTimeout(Yn),Zo(),P.removeEventListener("pointerdown",Bn),P.removeEventListener("mousemove",hr),y.dom.removeEventListener("keydown",gr),y.dom.removeEventListener("contextmenu",lo),P.removeEventListener("dragover",Qo,!0),P.removeEventListener("dragleave",Tt,!0),P.removeEventListener("drop",Gt,!0),P.removeEventListener("dragstart",_e,!0),gi.delete(y),P.removeEventListener("mouseleave",jo),$.removeEventListener("pointerdown",fo),Kn(),uo?.(),window.removeEventListener("scroll",wo,{capture:!0}),window.removeEventListener("dragover",en),V.remove(),s?.remove(),s=null,Te?.remove(),Te=null,it?.remove(),it=null,r=null,me=null,he=null,ze=!1,n=null,t===y&&(t=null)}}}})),an=Et(()=>{const y=P=>{if(it&&it.isConnected)return it;const D=document.createElement("div");return D.className="unified-drop-line",D.style.display="none",D.style.animation="none",(P.dom.parentElement??document.body).appendChild(D),it=D,D};return Lg({onDrag:({view:P,event:D,pos:V})=>{if(Mt(),(D.dataTransfer?Array.from(D.dataTransfer.types):[]).includes("Files"))return!1;if(X(P))return i(),!1;if(!P.dragging||!(P.state.selection instanceof Ee)||P.state.selection.node.type===P.state.schema.nodes.amadeusCanvasCard)return!1;if(me||He||he||ze)return r=null,de=null,i(),!1;const se=P.state.selection,G=ns(P,{x:D.clientX,y:D.clientY});if(G&&G.node.type.name==="list_item"&&!(G.pos>=se.from&&G.pos<se.to)){const H=G.el.getBoundingClientRect();if(D.clientX>H.left+24&&D.clientY>H.top+H.height/2)return de={targetPos:G.pos,el:G.el},r=null,i(),sn(P,G.el,24),!1}if(de=null,G&&!(G.pos>=se.from&&G.pos<se.to)&&ce(P,G.pos)){const H=G.el.getBoundingClientRect(),Me=D.clientX<=H.left+d?"left":D.clientX>=H.right-d?"right":null;if(Me)return r={targetPos:G.pos,side:Me},a(P,G.el,Me),!1}r=null,i();const Q=P.state.doc.resolve(V);if(Q.parent.type.name==="amadeusColumnRow")return!1;for(let H=Q.depth;H>=1;H--){if(Q.node(H).type.name!=="amadeusColumnCell")continue;const Me=P.nodeDOM(Q.before(H));if(Me instanceof HTMLElement){const Ie=Me.getBoundingClientRect();if(D.clientX<Ie.left||D.clientX>Ie.right)return!1}break}return!0},onShow:({view:P,line:D})=>{jt=!0;const V=y(P),U=Fr(P.dom),se=Or(V),G=(D.p1.x-se.x)/U,Q=(D.p2.x-se.x)/U,H=(D.p1.y-se.y)/U;V.style.display="block",V.style.width=`${Math.max(0,Q-G)}px`,V.style.transform=`translate(${Math.round(G)}px, ${Math.round(H-1.5)}px)`},onHide:_t})}),Ct=Et(()=>new qt({key:new Dn("UNIFIED_DROP_GUARD"),props:{handleDrop:y=>y.dom.dataset.dragging==="true"&&!!y.dragging}})),lt=Et(()=>{let y=null,$=null;const P=()=>{y&&(y.style.display="none")};return new qt({key:new Dn("AMX_GAP_INSERT"),view:D=>{const V=()=>(y&&y.isConnected||(y=document.createElement("div"),y.className="amx-gap-insert",y.innerHTML="<span>+</span>",y.addEventListener("mousedown",G=>{G.preventDefault(),G.stopPropagation()}),y.addEventListener("click",G=>{if(G.preventDefault(),G.stopPropagation(),!$)return;let Q=-1;D.state.doc.forEach((Ie,Oe)=>{Q<0&&Ie.type.name==="amadeusCanvasCard"&&String(Ie.attrs.anchor)===$&&(Q=Oe)});const H=D.state.schema.nodes.paragraph;if(Q<0||!H){P();return}let Me=D.state.tr.insert(Q,H.create());Me=Me.setSelection(Ne.create(Me.doc,Q+1)).scrollIntoView(),D.dispatch(Me),D.focus(),P()}),(D.dom.parentElement??document.body).appendChild(y)),y),U=G=>{if(X(D)||D.dragging){P();return}const Q=D.state.schema.nodes.amadeusCanvasCard;if(!Q){P();return}const H=D.state.doc;let Me=0,Ie=null,Oe=null;for(let Xe=0;Xe<H.childCount&&!Oe;Xe++){const Ut=H.child(Xe);if(Ut.type===Q){const pt=D.nodeDOM(Me);if(pt instanceof HTMLElement){if(pt.classList.contains("amx-card-f0")&&!pt.classList.contains("amx-card-f0-top")){Ie=pt,Me+=Ut.nodeSize;continue}if(Ie){const gt=Ie.getBoundingClientRect(),Je=pt.getBoundingClientRect();G.clientY>=gt.bottom-3&&G.clientY<=Je.top+3&&G.clientX>=Math.min(gt.left,Je.left)&&G.clientX<=Math.max(gt.right,Je.right)&&(Oe={top:gt.bottom,bottom:Je.top,left:Math.min(gt.left,Je.left),right:Math.max(gt.right,Je.right),anchor:String(Ut.attrs.anchor)})}Ie=pt}else Ie=null}else Ie=null;Me+=Ut.nodeSize}if(!Oe){P();return}const _e=V(),Ke=Fr(D.dom),We=Or(_e),Ve=(Oe.top+Oe.bottom)/2;_e.style.display="flex",_e.style.width=`${(Oe.right-Oe.left)/Ke}px`,_e.style.transform=`translate(${Math.round((Oe.left-We.x)/Ke)}px, ${Math.round((Ve-We.y)/Ke-9)}px)`,$=Oe.anchor},se=D.dom.parentElement??D.dom;return se.addEventListener("mousemove",U),se.addEventListener("mouseleave",P),{update:(G,Q)=>{G.state.doc.eq(Q.doc)||P()},destroy:()=>{se.removeEventListener("mousemove",U),se.removeEventListener("mouseleave",P),y?.remove(),y=null}}}})}),Kt={listFoldedAt:(y,$)=>fc(y,$),unfoldList:(y,$)=>ya(y,$)},cn=Et(()=>Oo({Tab:(y,$,P)=>da(y,$,P,Kt),"Shift-Tab":(y,$)=>fa(y,$)})),Xt=Et(()=>new qt({props:{decorations:y=>{const $=y.selection;if(!$.empty)return null;const P=$.$from,D=P.parent;if(!D.isTextblock||D.content.size>0)return null;for(let U=P.depth;U>=1;U--)if(P.node(U).type.name==="blockquote")return null;const V=D.type.name==="paragraph"?we("blocklayer.phParagraph"):D.type.name==="heading"?we("blocklayer.phHeading",{n:D.attrs.level??1}):null;return V?lr.create(y.doc,[so.node(P.before(),P.after(),{class:"is-empty","data-placeholder":V})]):null}}})),zn=["doc","amadeusColumnCell","bullet_list","ordered_list"],Zn=y=>{let $=y.depth;for(;$>=1&&!zn.includes(y.node($-1).type.name);)$--;return $},mr=y=>{const $=y.selection;if($ instanceof Ee){if(!$.node.isBlock)return null;if(zn.includes($.$from.parent.type.name))return{from:$.from,to:$.to};const U=Zn($.$from);return U<1?null:{from:$.$from.before(U),to:$.$from.after(U)}}const{$from:P,$to:D}=$;if(!P.sameParent(D)){let U=P.sharedDepth(D.pos);for(;U>0&&!zn.includes(P.node(U).type.name);)U--;return{from:P.before(U+1),to:D.after(U+1)}}const V=Zn(P);return V<1?null:{from:P.before(V),to:P.after(V)}},nn=y=>($,P)=>{const D=mr($);if(!D)return!1;const{from:V}=D,U=fs($,D.from,D.to),se=$.doc.resolve(V),G=se.parent,Q=se.index(),H=$.doc.resolve(U).index()-1,Me=G.child(Q),Ie=U>D.to&&Me.type.name==="heading"?Number(Me.attrs.level)||1:null;let Oe,_e;if(y<0){if(Q===0)return!0;_e=V,Oe=V-G.child(Q-1).nodeSize;let gt=null;if(Ie!=null)for(let Je=Q-1,Un=V;Je>=0;Je--){const Pt=G.child(Je);if(Un-=Pt.nodeSize,Pt.type.name==="heading"&&(Number(Pt.attrs.level)||1)<=Ie){gt=Un;break}}if(gt!=null)Oe=gt;else for(let Je=Vs($,Oe+1);Je!=null&&Je<Oe;Je=Vs($,Oe+1))Oe=Je}else{if(H+1>=G.childCount)return!0;Oe=U;const gt=G.child(H+1);_e=U+gt.nodeSize,Ie!=null&&gt.type.name==="heading"&&(_e=Um($.doc,Oe)??_e)}if(!P)return!0;const Ke=U-V,We=$.doc.slice(V,U).content,Ve=y<0?Oe:_e-Ke,Xe=$.tr.delete(V,U).insert(Ve,We),Ut=Ve-V;Br($,Xe,{from:V,to:U,newStart:Ve}),Qr($,Xe,{from:V,to:U,newStart:Ve});const pt=$.selection;return pt instanceof Ee?Xe.setSelection(Ee.create(Xe.doc,pt.from+Ut)):Xe.setSelection(Ne.create(Xe.doc,pt.anchor+Ut,pt.head+Ut)),o.getState($)&&Xe.setMeta(o,!0),P(Xe.scrollIntoView()),!0},Xn=Et(()=>Oo({"Mod-Alt-ArrowUp":nn(-1),"Mod-Alt-ArrowDown":nn(1),"Mod-Shift-ArrowUp":nn(-1),"Mod-Shift-ArrowDown":nn(1)})),$n=(y,$,P)=>{const D=y.selection,V=P?h(P):null;if(V){if(!$)return!0;const Ie=fs(y,V.from,V.to),{content:Oe,minted:_e}=ts(y.doc,y.doc.slice(V.from,Ie).content);_e.length&&e.onCardsMinted?.(_e);const Ke=Ie-V.from,We=y.tr.insert(Ie,Oe);return Br(y,We,{from:V.from,to:Ie,newStart:Ie,copy:!0}),Qr(y,We,{from:V.from,to:Ie,newStart:Ie}),We.setSelection(Ne.create(We.doc,D.anchor+Ke,D.head+Ke)),o.getState(y)&&We.setMeta(o,!0),$(We.scrollIntoView()),!0}if(D instanceof Ee){if(!D.node.isBlock)return!1;if(!$)return!0;const Ie=fs(y,D.from,D.to);if(Ie>D.to){const Ke=y.tr.insert(Ie,y.doc.slice(D.from,Ie).content);return Br(y,Ke,{from:D.from,to:Ie,newStart:Ie,copy:!0}),Qr(y,Ke,{from:D.from,to:Ie,newStart:Ie}),Ke.setSelection(Ee.create(Ke.doc,Ie)),$(Ke.scrollIntoView()),!0}let Oe=D.node;if(Oe.type.name==="amadeusCanvasCard"){const{content:Ke,minted:We}=ts(y.doc,So.from(Oe)),Ve=Ke.firstChild??Oe;Oe=Ve.type.create({...Ve.attrs,x:Number(Ve.attrs.x)+40,y:Number(Ve.attrs.y)+40},Ve.content,Ve.marks),We.length&&e.onCardsMinted?.(We)}const _e=y.tr.insert(D.to,Oe);return _e.setSelection(Ee.create(_e.doc,D.to)),$(_e.scrollIntoView()),!0}if(!(D instanceof Ne)||!D.$from.sameParent(D.$to))return!1;const{$from:U}=D;let se=U.depth;for(;se>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard","bullet_list","ordered_list"].includes(U.node(se-1).type.name);)se--;if(se<1)return!1;const G=U.before(se),Q=fs(y,G,U.after(se));if(!y.doc.nodeAt(G))return!1;if(!$)return!0;const H=Q-G,Me=y.tr.insert(Q,y.doc.slice(G,Q).content);return Br(y,Me,{from:G,to:Q,newStart:Q,copy:!0}),Qr(y,Me,{from:G,to:Q,newStart:Q}),Me.setSelection(Ne.create(Me.doc,D.anchor+H,D.head+H)),$(Me.scrollIntoView()),!0},Qn=Et(()=>Oo({"Mod-d":$n})),Mo=(y,$,P,D=!1)=>{const V=P?h(P):null;if(!V)return!1;const U=y.doc.resolve(V.from);if(y.doc.resolve(V.to).index()-U.index()<2)return!1;const G=y.selection;if(G.from>V.from+1||G.to<V.to-1)return!1;if(!$)return!0;const Q=y.doc.slice(V.from,V.to).content;return $(y.tr.delete(V.from,V.to).scrollIntoView()),D||e.onBlocksDeleted?.(Q),!0},Yo=(y,$)=>{const P=y.selection;if(!(P instanceof Ee))return!1;if(!$)return!0;const D=So.from(P.node);return $(y.tr.deleteSelection().scrollIntoView()),e.onBlocksDeleted?.(D),!0},Xo=(y,$,P)=>Mo(y,$,P)||Yo(y,$),Cn=Et(()=>Oo({Backspace:Xo,Delete:Xo})),An=Et(()=>new qt({props:{handleDOMEvents:{cut:(y,$)=>{const P=$;if(!P.clipboardData||!Mo(y.state,void 0,y,!0))return!1;const{dom:D,text:V}=y.serializeForClipboard(y.state.selection.content());return P.preventDefault(),P.clipboardData.clearData(),P.clipboardData.setData("text/html",D.innerHTML),P.clipboardData.setData("text/plain",V),Mo(y.state,y.dispatch.bind(y),y,!0),!0}}}})),Ln=Et(()=>Oo({"Mod-a":(y,$)=>{const{$from:P}=y.selection,D=(se,G)=>y.selection.from<=se&&y.selection.to>=G,V=[];P.parent.isTextblock&&V.push([P.start(),P.end()]);let U=P.depth;for(;U>=1&&!["doc","amadeusColumnCell"].includes(P.node(U-1).type.name);)U--;U>=1&&V.push([P.start(U),P.end(U)]);for(const[se,G]of V)if(!D(se,G))return $?.(y.tr.setSelection(Ne.create(y.doc,se,G))),!0;return $?.(y.tr.setSelection(new Ol(y.doc))),!0}})),yo=y=>{const $=y.selection;if(!($ instanceof Ne)||$.empty)return[];const P=!!o.getState(y);if(!P&&$.$from.sameParent($.$to))return[];const D=[],V=se=>{if(["bullet_list","ordered_list","table","blockquote","horizontal_rule","code_block","amadeusCanvasCard"].includes(se.type.name))return!0;if(se.type.name!=="paragraph")return!1;const G=se.textContent.trim();return/^!?\[\[[^\]\n]+\]\]$/.test(G)||se.childCount===1&&se.firstChild?.type.name==="image"},U=(se,G)=>{se.forEach((Q,H)=>{const Me=G+H,Ie=Me+Q.nodeSize;if(!(Ie<=$.from||Me>=$.to)){if(Q.type.name==="amadeusColumnRow"){Q.forEach((Oe,_e)=>U(Oe,Me+1+_e+1));return}(P||V(Q))&&D.push([Me,Ie,P])}})};return U(y.doc,0),D},xo=Et(()=>new qt({key:o,state:{init:()=>!1,apply:(y,$,P)=>y.getMeta(o)===!0?!0:y.docChanged||y.selectionSet&&!y.selection.eq(P.selection)?!1:$},props:{decorations:y=>{const $=yo(y);return $.length?lr.create(y.doc,$.map(([P,D,V])=>so.node(P,D,{class:V?"amx-block-selected":"amx-rendered-selected"}))):null},attributes:y=>o.getState(y)&&yo(y).length?{"data-blocksel":"true"}:{}}})),at=Et(()=>Oo({Escape:(y,$)=>{const P=y.selection;if(P instanceof Ee){const D=Ne.near(y.doc.resolve(P.from+1));return $?.(y.tr.setSelection(D)),!0}if(P instanceof Ne){const D=Gi(y);return D==null?!1:($?.(y.tr.setSelection(Ee.create(y.doc,D))),!0)}return!1}})),It=["doc","amadeusColumnCell"],bo=y=>{const $=y.selection;return $ instanceof Ee?$.node.isBlock:$ instanceof Ne&&!$.empty&&!!o.getState(y)},ao=(y,$)=>{const P=y.resolve($);if(It.includes(P.parent.type.name)){const V=P.nodeAfter;return V?{from:$,to:$+V.nodeSize}:null}let D=P.depth;for(;D>=1&&!It.includes(P.node(D-1).type.name);)D--;return D>=1?{from:P.before(D),to:P.after(D)}:null},Uo=y=>{const $=y.selection,P=y.doc,D=ao(P,$ instanceof Ee?$.from:$.anchor),V=$ instanceof Ee?D:ao(P,$.head);return!D||!V||P.resolve(D.from).parent!==P.resolve(V.from).parent?null:{a:D,h:V}},zo=(y,$,P)=>{const D=y.doc,V=$.from===P.from?D.nodeAt($.from):null;if(V&&Ee.isSelectable(V))return y.tr.setSelection(Ee.create(D,$.from));const U=P.from>=$.from,se=D.resolve(U?$.from+1:$.to-1),G=D.resolve(U?P.to-1:P.from+1);return y.tr.setSelection(Ne.between(se,G)).setMeta(o,!0)},Wn=y=>($,P)=>{if(!bo($))return!1;const D=Uo($);if(!D)return!1;const V=$.doc.resolve(D.h.from),U=V.parent;let se=V.index()+y,G=y>0?D.h.to:D.h.from;for(;se>=0&&se<U.childCount;){const Q=U.child(se).nodeSize,H=y>0?G:G-Q;if(Vs($,H+1)==null)return P?.(zo($,D.a,{from:H,to:H+Q}).scrollIntoView()),!0;G=y>0?G+Q:G-Q,se+=y}return!0},Pe=y=>y.selection.$from.parent.type.name==="code_block";return{plugins:[Et(()=>new qt({props:{handleKeyDown:Df({"Shift-ArrowDown":Wn(1),"Shift-ArrowUp":Wn(-1),"Mod-Alt-/":(y,$,P)=>{if(!P||!P.editable||!$)return!1;if(!bo(y)){const se=Gi(y);if(se==null)return!1;$(y.tr.setSelection(Ee.create(y.doc,se)))}const D=P.state,V=D.selection instanceof Ee?P.nodeDOM(D.selection.from):null,U=V instanceof HTMLElement?V.getBoundingClientRect():P.coordsAtPos(D.selection.from);return e.onMenu({x:U.left,y:U.bottom+4,keyboard:!0,focus:"turnInto"}),!0},"Mod-]":(y,$,P)=>Pe(y)?!1:da(y,$,P,Kt),"Mod-[":(y,$)=>Pe(y)?!1:fa(y,$)}),handleDOMEvents:{mousedown:(y,$)=>{if(!$.shiftKey||$.button!==0||!y.editable||!bo(y.state))return!1;const P=y.posAtCoords({left:$.clientX,top:$.clientY}),D=Uo(y.state),V=P?ao(y.state.doc,P.pos):null;return!D||!V||y.state.doc.resolve(V.from).parent!==y.state.doc.resolve(D.a.from).parent?!1:($.preventDefault(),y.dispatch(zo(y.state,D.a,V)),y.focus(),!0)}}}})),ot,an,Ct,lt,xo,Xt,at,cn,Ln,Cn,An,Xn,Qn,Uy].flat(),getView:()=>t,topRangeOf:h,duplicate:y=>$n(y.state,y.dispatch.bind(y),y),indent:(y,$)=>$>0?da(y.state,y.dispatch.bind(y),y,Kt):fa(y.state,y.dispatch.bind(y))}}async function Qy(e,t,n){const o=Hc(t);if(!o.length)return;const r=new Set(Hc(n).map(Ys)),s=o.filter(i=>!r.has(Ys(i)));if(!s.length)return;const a=(await wn.exclusiveAssets?.(e).catch(()=>[])??[]).filter(i=>s.some(d=>ex(d,i)));a.length&&await wh(e,a,{block:!0})==="with"&&await If(a)}function ex(e,t){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase(),o=t.replace(/\\/g,"/").toLowerCase();return n.includes("/")?o===n||o.endsWith(`/${n}`)||o===Ml(n):Ys(e)===Ys(t)}function Ji(e){const t=[],n=o=>{if(o.isText){t.push(o.text??"");for(const s of o.marks){const c=String(s.attrs?.href??"");s.type.name==="link"&&c&&t.push(`[](${qc(c)??c})`)}return}const r=String(o.attrs?.src??"");r&&t.push(`![](${qc(r)??r})`),o.forEach(n)};return e.forEach(n),t.join(`
44
- `)}const Wo=1,Zt=400,Ko=720,tx=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/,nx=/^<!--\s*\/a\s+([A-Za-z0-9_-]+)\s*-->$/,sa=/^[A-Za-z0-9_-]+$/,ro=(e,t)=>typeof e=="number"&&Number.isFinite(e)?Math.round(e):t;function _n(e){if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(n.v!==Wo||n.mode!=null&&n.mode!=="doc"&&n.mode!=="canvas")return null;const o=r=>typeof r=="number"&&Number.isFinite(r);if(n.main!=null&&(typeof n.main!="object"||!o(n.main.w)||n.main.w<=0||!o(n.main.x)||!o(n.main.y)||n.main.h!=null&&(!o(n.main.h)||n.main.h<0)))return null;if(n.cards!=null){if(!Array.isArray(n.cards))return null;for(const s of n.cards)if(!s||typeof s!="object"||typeof s.ref!="string"||!sa.test(s.ref)||!o(s.w)||s.w<=0||!o(s.x)||!o(s.y)||s.h!=null&&(!o(s.h)||s.h<0))return null;const r=n.cards.map(s=>s.ref);if(new Set(r).size!==r.length)return null}return n.elements!=null&&!Array.isArray(n.elements)?null:n}catch{return null}}function ox(e){const t=new Set;for(const n of e?.rows??[]){for(const o of n.columns)for(const r of o.refs)t.add(r);n.tail&&t.add(n.tail)}return t}const rx=dc("amadeusCanvasCard",()=>({content:"block+",group:"block",defining:!0,isolating:!0,selectable:!0,attrs:{anchor:{default:""},x:{default:0},y:{default:0},w:{default:Zt},h:{default:0},color:{default:""}},parseDOM:[{tag:"div[data-amx-card]",getAttrs:e=>{const t=e.dataset;return{anchor:t.anchor??"",x:ro(Number(t.x),0),y:ro(Number(t.y),0),w:ro(Number(t.w),Zt)||Zt,h:ro(Number(t.h),0),color:t.color??""}}}],toDOM:e=>{const t=ra(e.attrs.color);return["div",{"data-amx-card":"","data-anchor":String(e.attrs.anchor),"data-x":String(e.attrs.x),"data-y":String(e.attrs.y),"data-w":String(e.attrs.w),"data-h":String(e.attrs.h),"data-color":typeof e.attrs.color=="string"&&e.attrs.color?e.attrs.color:null,class:"amx-ucard",style:`--amx-x:${e.attrs.x}px;--amx-y:${e.attrs.y}px;--amx-w:${e.attrs.w}px;--amx-h:${Number(e.attrs.h)>0?`${e.attrs.h}px`:"auto"}${t?`;--amx-color:${t}`:""}`},0]},parseMarkdown:{match:({type:e})=>e==="amadeusCanvasCard",runner:(e,t,n)=>{const o=t;e.openNode(n,{anchor:o.anchor??"",x:o.x??0,y:o.y??0,w:o.w??Zt,h:o.h??0,color:o.color??""}),e.next(t.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="amadeusCanvasCard",runner:(e,t)=>{e.addNode("html",void 0,`<!-- a ${t.attrs.anchor} -->`),t.childCount===1&&t.firstChild.type.name==="paragraph"&&t.firstChild.content.size===0||e.next(t.content),e.addNode("html",void 0,`<!-- /a ${t.attrs.anchor} -->`)}}}));function sx(e,t,n,o){const r=t?.cards;if(!r?.length)return;const s=Array.isArray(e?.children)?e.children:[];if(s.length&&!s.some(T=>T?.position))return;const c=T=>{let w=null;if(T?.type==="html"&&typeof T.value=="string")w=T.value;else if(T?.type==="paragraph"&&Array.isArray(T.children)&&T.children.length===1){const I=T.children[0];I?.type==="html"&&typeof I.value=="string"&&(w=I.value)}if(w==null)return null;const S=tx.exec(w.trim());return S?S[1]:null},a=T=>{let w=null;if(T?.type==="html"&&typeof T.value=="string")w=T.value;else if(T?.type==="paragraph"&&Array.isArray(T.children)&&T.children.length===1){const I=T.children[0];I?.type==="html"&&typeof I.value=="string"&&(w=I.value)}if(w==null)return null;const S=nx.exec(w.trim());return S?S[1]:null},i=new Map(r.map(T=>[T.ref,T])),d=gu(t?.cardColors),p=[];if(s.forEach((T,w)=>{const S=c(T);S&&p.push({id:S,idx:w})}),!p.length)return;const h=new Map;p.forEach(T=>h.set(T.id,(h.get(T.id)??0)+1));const M=[];for(const T of p){if((h.get(T.id)??0)>1||n.has(T.id)||!i.has(T.id))continue;let w=s.length,S=-1;for(let I=T.idx+1;I<s.length;I++){if(c(s[I])){w=I;break}if(a(s[I])===T.id){w=I,S=I;break}}M.push({id:T.id,open:T.idx,end:w,closer:S})}if(!M.length)return;const R=[];for(const T of[...M].reverse()){const w=i.get(T.id),S=s.slice(T.open+1,T.end);s.splice(T.open,(T.closer>=0?T.closer+1:T.end)-T.open,{type:"amadeusCanvasCard",anchor:T.id,x:ro(w.x,0),y:ro(w.y,0),w:ro(w.w,Zt)||Zt,h:ro(w.h,0),color:d&&Object.prototype.hasOwnProperty.call(d,T.id)&&yu(d[T.id])?d[T.id]:typeof w.color=="string"?w.color:"",children:S.length?S:[{type:"paragraph",children:[]}]}),R.unshift(T.id)}o?.(R)}function ax(e,t,n){return[_l("amadeusCanvasFold",()=>()=>o=>{sx(o,e(),ox(t()),n)})].flat()}function cx(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const o=String(n.attrs.anchor);if(!sa.test(o))return;const r=ro(n.attrs.h,0);t.push({ref:o,x:ro(n.attrs.x,0),y:ro(n.attrs.y,0),w:ro(n.attrs.w,Zt)||Zt,...r>0?{h:r}:{}})}),t}function gu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}const yu=e=>e!==""&&e!=null;function Zi(e){const t=Object.create(null);return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const o=String(n.attrs.anchor);sa.test(o)&&yu(n.attrs.color)&&(t[o]=n.attrs.color)}),t}function ix(e,t,n,o){const r=cx(e),s=_n(t);if(!s){if(t!=null)return t;if(!r.length)return null;const p=Zi(e);return JSON.stringify({v:Wo,mode:n??"canvas",main:{x:0,y:0,w:Ko},cards:r,...Object.keys(p).length?{cardColors:{...p}}:{}})}if(!(s.cards??[]).every(p=>o.has(p.ref)))return t;if(!r.length&&!s.elements?.length){const p=s.main;if(!p||p.x===0&&p.y===0&&p.w===Ko)return null}const c={...s,v:Wo,cards:r},a=Zi(e);Object.keys(a).length?c.cardColors={...a}:(c.cardColors===void 0||gu(c.cardColors))&&delete c.cardColors,n&&(c.mode=n),c.main||(c.main={x:0,y:0,w:Ko}),c.elements?.length||delete c.elements;const i=Vt(c.tree),d=Object.keys(i);if(d.length){const p=new Set(r.map(R=>R.ref)),h=R=>typeof R=="string"&&sa.test(R)&&!p.has(R),M=new Set;for(const R of d)h(R)&&M.add(R),h(i[R])&&M.add(i[R]);if(M.size){const R=qg(i,M);Object.keys(R).length?c.tree=R:delete c.tree}}return JSON.stringify(c)}function lx(e,t){const n=_n(e);if(!n)return e??(t.length?JSON.stringify({v:Wo,mode:"canvas",main:{x:0,y:0,w:Ko},cards:[],elements:t}):null);const o={...n,v:Wo,elements:t};return t.length||delete o.elements,JSON.stringify(o)}function ux(e,t){const n={x:Math.round(t.x),y:Math.round(t.y),w:Math.round(t.w),...typeof t.h=="number"&&t.h>0?{h:Math.round(t.h)}:{}},o=_n(e);return o?JSON.stringify({...o,v:Wo,main:n}):e??(!n.x&&!n.y&&n.w===Ko?null:JSON.stringify({v:Wo,mode:"canvas",main:n,cards:[]}))}function dx(e,t){const n=Object.keys(t).length,o=_n(e);if(!o)return e??(n?JSON.stringify({v:Wo,mode:"canvas",main:{x:0,y:0,w:Ko},cards:[],tree:t}):null);const r={...o,v:Wo,tree:t};return n||delete r.tree,JSON.stringify(r)}const fx=Et(()=>new qt({key:new Dn("AMX_CANVAS_NORMALIZE"),appendTransaction:(e,t,n)=>{if(!e.some(i=>i.docChanged))return null;const o=n.schema.nodes.amadeusCanvasCard;if(!o)return null;const r=[],s=[],c=new Set;if(n.doc.forEach((i,d)=>{if(i.type!==o)return;const p=String(i.attrs.anchor);c.has(p)?s.push(d):c.add(p),i.forEach((h,M)=>{if(h.type.name!=="amadeusColumnRow")return;const R=d+1+M;r.push({from:R,to:R+h.nodeSize,node:h,before:d})})}),!r.length&&!s.length)return null;let a=n.tr;for(const i of s){const d=a.doc.nodeAt(i);d?.type===o&&(a=a.setNodeMarkup(i,void 0,{...d.attrs,anchor:Eo(a.doc)}))}for(const i of r)a=a.delete(a.mapping.map(i.from,1),a.mapping.map(i.to,-1)),a=a.insert(a.mapping.map(i.before),i.node);return a.steps.length?a:null}})),mx=Et(()=>new qt({key:new Dn("AMX_CANVAS_PASTE_GUARD"),props:{transformPasted:(e,t)=>{if(t.dragging?.move)return e;const n=t.state.schema.nodes.amadeusCanvasCard;if(!n)return e;let o=!1;if(e.content.descendants(s=>s.type===n?(o=!0,!1):!0),!o)return e;const r=s=>{const c=[];return s.forEach(a=>{a.type===n?r(a.content).forEach(i=>c.push(i)):c.push(a.copy(r(a.content)))}),So.fromArray(c)};return Ha.maxOpen(r(e.content))}}})),px=Et(()=>new qt({key:new Dn("AMX_CANVAS_INTEGRITY"),filterTransaction:(e,t)=>{if(!e.docChanged)return!0;const n=t.schema.nodes.amadeusCanvasCard;if(!n)return!0;let o=!0;return e.doc.descendants((r,s,c)=>!o||r.type!==n?o:c?.type.name!=="doc"?(o=!1,!1):!0),o}})),hx=[rx,fx,mx,px].flat();function gx(e){return[Et(()=>new qt({key:new Dn("AMX_CANVAS_SEL_CLAMP"),appendTransaction:(t,n,o)=>{if(!e())return null;const r=o.schema.nodes.amadeusCanvasCard;if(!r)return null;let s=-1;{let T=0;for(let w=0;w<o.doc.childCount;w++){const S=o.doc.child(w);if(S.type===r){s=T;break}T+=S.nodeSize}}if(s<0)return null;const c=T=>T.depth>=1&&T.node(1).type===r?T.index(0):-1,a=T=>{if(T<0)return{from:0,to:s};let w=0;for(let S=0;S<T;S++)w+=o.doc.child(S).nodeSize;return{from:w+1,to:w+o.doc.child(T).nodeSize-1}},i=T=>T.eq(o.selection)||c(o.doc.resolve(T.anchor))!==c(o.doc.resolve(T.head))?null:o.tr.setSelection(T),d=o.selection;if(d.empty||d instanceof Ee)return null;if(d instanceof Ol){if(t.some(S=>S.docChanged))return null;const T=Math.max(0,Math.min(n.selection.head,o.doc.content.size)),w=a(c(o.doc.resolve(T)));return w.from>=w.to?null:i(Ne.between(o.doc.resolve(w.from),o.doc.resolve(w.to),-1))}if(!(d instanceof Ne))return null;const p=o.doc.resolve(d.anchor),h=c(p);if(h===c(o.doc.resolve(d.head)))return null;const M=a(h),R=Math.max(M.from,Math.min(M.to,d.head));return i(Ne.between(p,o.doc.resolve(R),d.head>=d.anchor?-1:1))}}))].flat()}function yx(){return[Et(()=>new qt({key:new Dn("AMX_CARD_ACTIVE"),props:{decorations(e){const t=e.schema.nodes.amadeusCanvasCard;if(!t)return null;const n=e.selection;let o=-1,r=null;if(n instanceof Ee){if(n.node.type===t)o=n.from,r=n.node;else if(n.$from.depth>=1){const s=n.$from.node(1);s.type===t&&(o=n.$from.before(1),r=s)}}else if(n.$head.depth>=1){const s=n.$head.node(1);s.type===t&&(o=n.$head.before(1),r=s)}return r?lr.create(e.doc,[so.node(o,o+r.nodeSize,{class:"amx-card-active"})]):null}}}))].flat()}const xx=6,bx=2;function vx(e){return[Et(()=>new qt({key:new Dn("AMX_CARD_DEPTH"),props:{decorations(t){const n=t.schema.nodes.amadeusCanvasCard;if(!n)return null;const o=Vt(e()?.tree);if(!Object.keys(o).length)return null;const r=new Set,s=[];t.doc.forEach((i,d,p)=>{if(i.type!==n)return;const h=String(i.attrs.anchor);r.add(h),s.push({pos:d,size:i.nodeSize,anchor:h,idx:p})});const c=[];for(let i=0;i<s.length;i++){const d=Zs(s,i,o);d>i+1&&c.push({start:i,end:d})}const a=[];for(let i=0;i<s.length;i++){const d=s[i],p=Wg(o,d.anchor,r,xx),h=c.filter(R=>R.start<=i&&i<R.end).slice(0,bx);if(!p&&!h.length)continue;const M=[];p>0&&M.push("amx-card-child",`amx-card-d${p}`),h.forEach((R,T)=>{M.push(`amx-card-f${T}`),R.start===i&&M.push(`amx-card-f${T}-top`),R.end-1===i&&M.push(`amx-card-f${T}-end`)}),a.push(so.node(d.pos,d.pos+d.size,{class:M.join(" ")}))}return a.length?lr.create(t.doc,a):null}}}))].flat()}const wx=200;function kx(e){return[Et(()=>new qt({key:new Dn("AMX_CANVAS_HISTORY_TIMELINE"),state:{init:(t,n)=>({depth:Ba(n)}),apply:(t,n,o,r)=>{const s=Ba(r);return t.docChanged&&s>n.depth&&!Td(t)&&(e.log.push("pm"),e.log.length>wx&&e.log.shift(),e.future.length=0),s===n.depth?n:{depth:s}}}}))].flat()}kn({"canvasel.attach.count":{zh:"{n} 张",en:"{n} cards"},"canvasel.attach.child":{zh:"设为子节点",en:"Attach as child"},"canvasel.attach.sibling":{zh:"设为同级节点",en:"Attach as sibling"},"canvasel.add.child":{zh:"新建子卡片(Tab)",en:"New child card (Tab)"},"canvasel.add.sibling":{zh:"新建兄弟卡片(回车)",en:"New sibling card (Enter)"},"canvasel.link.drag":{zh:"拖出连线(落在卡片上 = 设为子节点,按住 Shift = 自由连线)",en:"Drag to connect (onto a card = make it a child; hold Shift for a free connector)"}});const Ot=e=>`c:${e}`,yn=e=>`e:${e}`,xu=e=>`t:${e}`,nt=e=>e.slice(2),Is=e=>typeof e=="number"&&Number.isFinite(e)?e:null,qr=e=>typeof e=="string"&&e?e:null,Aa=e=>ra(e)?e:null,wc=e=>{const t=ra(e);return t?{"data-color":e,style:{"--amx-color":t}}:{}};function ea(e){if(!e||typeof e!="object")return null;const t=e,n=qr(t.ref);if(n)return{ref:n};const o=qr(t.id);return o?{id:o}:t.main===!0?{main:!0}:null}const kr=e=>e.ref?Ot(e.ref):e.id?yn(e.id):e.main?ye:null;function Rn(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const r=o,s=qr(r.id);if(!s||n.has(s))continue;if(r.type==="connector"){const p=ea(r.from),h=ea(r.to);if(!p||!h)continue;n.add(s),t.push({kind:"connector",id:s,from:p,to:h,label:qr(r.label),color:Aa(r.color),fromEnd:r.fromEnd==="arrow"?"arrow":"none",toEnd:r.toEnd==="none"?"none":"arrow"});continue}if(r.type!=="shape"&&r.type!=="text"&&r.type!=="frame")continue;const c=Is(r.x),a=Is(r.y),i=Is(r.w),d=Is(r.h);if(!(c==null||a==null||i==null||d==null||i<=0||d<=0)){if(n.add(s),r.type==="frame"){t.push({kind:"frame",id:s,x:c,y:a,w:i,h:d,title:qr(r.title),color:Aa(r.color)});continue}t.push({kind:r.type==="text"?"text":"shape",id:s,x:c,y:a,w:i,h:d,shape:r.shape==="ellipse"?"ellipse":"rect",text:qr(r.text),color:Aa(r.color)})}}return t}function Qi(e,t){const n=e.x+e.w/2,o=e.y+e.h/2,r=t.x+t.w/2-n,s=t.y+t.h/2-o;return Math.abs(r)*e.h>=Math.abs(s)*e.w?{x:r>=0?e.x+e.w:e.x,y:o}:{x:n,y:s>=0?e.y+e.h:e.y}}function kc(e,t){const n=Qi(e,t),o=Qi(t,e),r=Math.abs(o.x-n.x)>=Math.abs(o.y-n.y),s=Math.max(24,Math.abs(r?o.x-n.x:o.y-n.y)/2),c=Math.sign(o.x-n.x||1),a=Math.sign(o.y-n.y||1);return{p1:n,c1:r?{x:n.x+c*s,y:n.y}:{x:n.x,y:n.y+a*s},c2:r?{x:o.x-c*s,y:o.y}:{x:o.x,y:o.y-a*s},p2:o}}function Cx(e,t){const{p1:n,c1:o,c2:r,p2:s}=kc(e,t),c=[n.x,o.x,r.x,s.x],a=[n.y,o.y,r.y,s.y],i=Math.min(...c),d=Math.min(...a);return{d:`M${n.x},${n.y} C${o.x},${o.y} ${r.x},${r.y} ${s.x},${s.y}`,mid:{x:(n.x+s.x)/2+(o.x+r.x-n.x-s.x)/8,y:(n.y+s.y)/2+(o.y+r.y-n.y-s.y)/8},tip:s,ang:Math.atan2(s.y-r.y,s.x-r.x),tail:n,tailAng:Math.atan2(n.y-o.y,n.x-o.x),box:{x:i,y:d,w:Math.max(1,Math.max(...c)-i),h:Math.max(1,Math.max(...a)-d)}}}function Ps(e,t,n,o=8){const{p1:r,c1:s,c2:c,p2:a}=kc(e,t);let i=r.x,d=r.y;for(let p=1;p<=24;p++){const h=p/24,M=1-h,R=M*M*M*r.x+3*M*M*h*s.x+3*M*h*h*c.x+h*h*h*a.x,T=M*M*M*r.y+3*M*M*h*s.y+3*M*h*h*c.y+h*h*h*a.y,w=R-i,S=T-d,I=w*w+S*S,X=I?Math.max(0,Math.min(1,((n.x-i)*w+(n.y-d)*S)/I)):0;if(Math.hypot(i+X*w-n.x,d+X*S-n.y)<=o)return!0;i=R,d=T}return!1}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[];for(const[n,o]of Object.entries(e))!n||typeof o!="string"||!o||o===n||t.push([n,o]);return t}function Sx(e,t){const n=[...t].flatMap(a=>a===ye?[ye]:a.startsWith("c:")?[nt(a)]:[]),o=new Set(n),r=new Set;if(!n.length||!e.length)return{nodes:o,edgeChildren:r};const s=new Map,c=new Map;for(const[a,i]of e){s.set(a,i);const d=c.get(i);d?d.push(a):c.set(i,[a])}for(const a of n){const i=new Set;let d=a;for(;!i.has(d);){i.add(d),o.add(d);const M=s.get(d);if(!M)break;r.add(d),o.add(M),d=M}const p=[a],h=new Set;for(;p.length;){const M=p.shift();if(!h.has(M)){h.add(M);for(const R of c.get(M)??[])r.add(R),o.add(R),p.push(R)}}}return{nodes:o,edgeChildren:r}}const el=(e,t)=>e.x<t.x+t.w&&e.x+e.w>t.x&&e.y<t.y+t.h&&e.y+e.h>t.y;function hn(e){const t=new Map;if(!e)return t;for(const n of e.querySelectorAll(".amx-ucard[data-anchor]")){const o=n.dataset.anchor;o&&t.set(o,{x:n.offsetLeft,y:n.offsetTop,w:n.offsetWidth,h:n.offsetHeight})}return t}function gn(e){const t=e?.querySelector(".ProseMirror");return t?{x:t.offsetLeft,y:t.offsetTop,w:t.offsetWidth,h:t.offsetHeight}:null}function tl(e,t=!1){const n=i=>!t||!i.closest(".amx-ucard"),o=i=>(i.innerText||i.textContent||"").split(/\r?\n/).map(d=>d.trim()).find(Boolean)??null,r=[...e.querySelectorAll("h1,h2,h3,h4,h5,h6")].filter(n).map(o).filter(i=>!!i),s=[...e.querySelectorAll("p,li,blockquote,pre")].filter(n).map(o).filter(i=>!!i),c=r[0]??s[0];if(!c)return null;const a=s.find((i,d)=>i!==c&&(r.length>0||d>0))??null;return{title:c,detail:a}}function Ex(e,t){const n=e.classList.contains("amx-stage-overview");n&&e.classList.remove("amx-stage-overview");try{const o=[];for(const[a,i]of hn(e)){const d=e.querySelector(`.amx-ucard[data-anchor="${CSS.escape(a)}"]`),p=d?tl(d):null;d&&p&&o.push({key:Ot(a),anchor:a,...p,h:i.h,autoHeight:Number(d.dataset.h)<=0})}const r=e.querySelector(".ProseMirror"),s=gn(e),c=r?tl(r,!0):null;return s&&c&&o.push({key:ye,anchor:ye,...c,h:s.h,autoHeight:t}),o}finally{n&&e.classList.add("amx-stage-overview")}}function Mx(e,t){return e.length===t.length&&e.every((n,o)=>{const r=t[o];return n.key===r?.key&&n.anchor===r.anchor&&n.title===r.title&&n.detail===r.detail&&n.h===r.h&&n.autoHeight===r.autoHeight})}const sr=24;function Nr(e,t){const n=new Map;for(const o of e){if(o.kind==="connector")continue;let r={x:o.x,y:o.y,w:o.w,h:o.h};t?.move&&t.move.ids.has(yn(o.id))&&(r={...r,x:r.x+t.move.dx,y:r.y+t.move.dy}),t?.size&&t.size.id===o.id&&(r={x:r.x+t.size.dx,y:r.y+t.size.dy,w:Math.max(sr,r.w+t.size.dw),h:Math.max(sr,r.h+t.size.dh)}),n.set(o.id,r)}return n}function zx({elements:e,hostRef:t,documentKey:n,sel:o,editing:r,tree:s,ghost:c,marquee:a,attach:i,overviewScale:d,mainAutoHeight:p=!0,preview:h,guides:M}){const{t:R}=tn(),T=b.useMemo(()=>Rn(e),[e]),w=b.useMemo(()=>bu(s),[s]),S=b.useMemo(()=>Sx(w,o),[w,o]),I=S.edgeChildren,[X,ee]=b.useState(0),q=T.length+w.length,oe=[...o].filter(k=>k.startsWith("c:")).map(nt),Re=o.has(ye),Ge=q+oe.length+(Re?1:0),m=d!=null&&d>0,[ke,rt]=b.useState({documentKey:"",items:[]});b.useEffect(()=>{const k=t.current;if(!k)return;let J=0;const le=new ResizeObserver(()=>Fe()),ve=new Set,Ye=()=>{const it=new Set(k.querySelectorAll(".amx-ucard")),_t=k.querySelector(".ProseMirror");_t&&it.add(_t);for(const jt of it)ve.has(jt)||(le.observe(jt,{box:"border-box"}),ve.add(jt));for(const jt of[...ve])it.has(jt)||(le.unobserve(jt),ve.delete(jt))},Fe=()=>{cancelAnimationFrame(J),J=requestAnimationFrame(()=>{Ye(),ee(it=>it+1)})};Fe();const mt=new MutationObserver(Fe);return mt.observe(k,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["style","data-x","data-y","data-w","data-h"]}),le.observe(k),()=>{cancelAnimationFrame(J),mt.disconnect(),le.disconnect()}},[t]);const de=b.useMemo(()=>hn(t.current),[t,n,ke.documentKey,X,Ge,c]),me=b.useMemo(()=>Nr(T,c),[T,c]),he=gn(t.current);b.useLayoutEffect(()=>{if(!m)return;const k=t.current,J=k?.querySelector(".ProseMirror");if(!k||!J||J.childElementCount===0)return;const le=Ex(k,p);rt(ve=>ve.documentKey===n&&Mx(ve.items,le)?ve:{documentKey:n,items:le})},[n,t,p,m,X]);const ze=ke.documentKey===n?ke.items:[],He=new Set([...oe,...Re?[ye]:[]]),Te=m?ze.flatMap(k=>{if(He.has(k.anchor))return[];const J=k.anchor===ye?he:de.get(k.anchor);return J?[{...k,box:J}]:[]}):[],dt=t.current?.dataset.amxDragscope,sn=m&&dt?ze.flatMap(k=>{const J=`.amx-stage[data-amx-dragscope="${CSS.escape(dt)}"].amx-stage-overview`;if(He.has(k.anchor))return[];if(k.anchor===ye)return[`${J} .ProseMirror:not(.unified-embed .ProseMirror) > :not(.amx-ucard){display:none!important;}`,...p?[`${J} .ProseMirror:not(.unified-embed .ProseMirror){height:${k.h}px;}`]:[]];const le=`${J} .amx-ucard[data-anchor="${CSS.escape(k.anchor)}"]`;return[`${le} > *{display:none!important;}`,...k.autoHeight?[`${le}[data-h="0"]{height:${k.h}px;}`]:[]]}).join(`
45
- `):"",re=S.nodes.size>0&&dt?(()=>{const k=`.amx-stage[data-amx-dragscope="${CSS.escape(dt)}"]:not(.amx-stage-off)`,J=[...de.keys()].filter(ve=>!S.nodes.has(ve)).flatMap(ve=>[`${k} .amx-ucard[data-anchor="${CSS.escape(ve)}"]`,`${k} .amx-card-overview[data-card-label="${CSS.escape(ve)}"]`]),le=J.length?[`${J.join(`,
46
- `)}{opacity:0.44;}`]:[];if(!S.nodes.has(ye)){const ve=`${k} .ProseMirror:not(.unified-embed .ProseMirror)`;le.push(`${ve}{background-color:color-mix(in srgb,var(--bg) 44%,transparent);border-color:color-mix(in srgb,var(--border) 44%,transparent);box-shadow:none;}`,`${ve}>:not(.amx-ucard){opacity:0.44;}`,`${k} .amx-card-overview[data-card-label="${CSS.escape(ye)}"]{opacity:0.44;}`)}return le.push(`${k} .amx-el-conn.is-tree:not(.is-related){opacity:0.18;}`),le.join(`
47
- `)})():"",ce=k=>k.ref!=null?de.get(k.ref)??null:k.id!=null?me.get(k.id)??null:k.main?he:null,ge=k=>k===ye?he:k.startsWith("c:")?de.get(nt(k))??null:me.get(nt(k))??null;return f.jsxs("div",{className:"amx-el-layer",children:[sn?f.jsx("style",{"data-amx-overview-rules":!0,children:sn}):null,re?f.jsx("style",{"data-amx-related-focus-rules":!0,children:re}):null,T.filter(k=>k.kind==="frame").map(k=>f.jsx(Tx,{el:k,box:me.get(k.id),sel:o.has(yn(k.id))},k.id)),T.filter(k=>k.kind!=="frame").map(k=>k.kind==="connector"?f.jsx(Fs,{el:k,a:ce(k.from),b:ce(k.to),sel:o.has(yn(k.id))},k.id):f.jsx(jx,{el:k,box:me.get(k.id),sel:o.has(yn(k.id))},k.id)),o.size===1&&[...o][0].startsWith("e:")&&me.has(nt([...o][0]))?f.jsxs(f.Fragment,{children:[f.jsx(Ax,{id:nt([...o][0]),box:me.get(nt([...o][0]))}),f.jsx(Na,{node:[...o][0],box:me.get(nt([...o][0]))})]}):null,(()=>{const k=o.size===1?[...o][0]:null,J=k?.startsWith("e:")?T.find(mt=>mt.kind==="connector"&&mt.id===nt(k)):null,le=J?ce(J.from):null,ve=J?ce(J.to):null;if(!J||!le||!ve)return null;const{p1:Ye,p2:Fe}=kc(le,ve);return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-conn-end","data-conn-end":"from","data-el":J.id,style:{left:`${Ye.x}px`,top:`${Ye.y}px`}}),f.jsx("div",{className:"amx-conn-end","data-conn-end":"to","data-el":J.id,style:{left:`${Fe.x}px`,top:`${Fe.y}px`}})]})})(),w.map(([k,J])=>{const le=J===ye?he:de.get(J),ve=de.get(k),Ye=J===ye?{main:!0}:{ref:J};return le&&ve?f.jsx(Fs,{el:{kind:"connector",id:`t:${k}`,from:Ye,to:{ref:k},label:null},a:le,b:ve,sel:o.has(xu(k)),related:I.has(k),tree:!0},`t:${k}`):null}),oe.map(k=>{const J=de.get(k);return J?f.jsx("div",{className:`amx-el-selbox${r===k?" is-editing":""}`,"data-anchor":k,style:{left:`${J.x}px`,top:`${J.y}px`,width:`${J.w}px`,height:`${J.h}px`},children:o.size===1&&r!==k?f.jsxs(f.Fragment,{children:[f.jsx(nl,{anchor:k}),f.jsx(ol,{node:k}),f.jsx(Na,{node:Ot(k)})]}):null},`sel:${k}`):null}),Re&&he?f.jsx("div",{className:`amx-el-selbox${r===ye?" is-editing":""}`,"data-main-sel":!0,style:{left:`${he.x}px`,top:`${he.y}px`,width:`${he.w}px`,height:`${he.h}px`},children:o.size===1&&r!==ye?f.jsxs(f.Fragment,{children:[f.jsx(nl,{anchor:ye}),f.jsx(ol,{node:ye}),f.jsx(Na,{node:ye})]}):null}):null,Te.map(k=>{const J=k.box.h*d,le=J<44?"title":J<60?"summary":"full",ve=le==="title"?Math.max(8,Math.min(12,(J-3)/1.2)):12;return f.jsxs("div",{className:"amx-card-overview","data-card-label":k.anchor,"data-overview-density":le,style:{left:`${k.box.x}px`,top:`${k.box.y}px`,width:`${k.box.w}px`,height:`${k.box.h}px`,"--amx-overview-inv":String(1/d),"--amx-overview-title-screen":`${ve}px`},children:[f.jsx("span",{className:"amx-card-overview-title",children:k.title}),k.detail?f.jsx("span",{className:"amx-card-overview-detail",children:k.detail}):null]},`overview:${k.key}`)}),h?(()=>{const k=ge(h.from);if(!k)return null;const J=h.over?ge(h.over):null,le=J??{x:h.x,y:h.y,w:1,h:1};return f.jsxs(f.Fragment,{children:[f.jsx(Fs,{el:{kind:"connector",id:"~preview",from:{},to:{},label:null},a:k,b:le,sel:!1,preview:!0}),f.jsx("div",{className:"amx-conn-target",style:{left:`${k.x}px`,top:`${k.y}px`,width:`${k.w}px`,height:`${k.h}px`}}),J?f.jsx("div",{className:"amx-conn-target",style:{left:`${J.x}px`,top:`${J.y}px`,width:`${J.w}px`,height:`${J.h}px`}}):null]})})():null,i?(()=>{const k=i.node===ye?he:de.get(i.node),J=de.get(i.source);if(!k)return null;const le=3,ve=22,Ye=i.side==="n"||i.side==="s",Fe=i.side==="w"?k.x:i.side==="e"?k.x+k.w:k.x+k.w/2,mt=i.side==="n"?k.y:i.side==="s"?k.y+k.h:k.y+k.h/2;return f.jsxs(f.Fragment,{children:[J?f.jsx(Fs,{el:{kind:"connector",id:"~attach",from:{ref:i.source},to:i.node===ye?{main:!0}:{ref:i.node},label:null},a:J,b:k,sel:!1,preview:!0}):null,f.jsx("div",{className:`amx-el-attach-target is-${i.rel}`,style:{left:`${k.x}px`,top:`${k.y}px`,width:`${k.w}px`,height:`${k.h}px`}}),f.jsx("div",{className:`amx-el-attach is-${i.rel}`,"data-attach":i.side,style:{left:`${i.side==="e"?k.x+k.w-le:i.side==="w"?k.x:k.x+(k.w-ve)/2}px`,top:`${i.side==="s"?k.y+k.h-le:i.side==="n"?k.y:k.y+(k.h-ve)/2}px`,width:`${Ye?ve:le}px`,height:`${Ye?le:ve}px`}}),f.jsxs("div",{className:`amx-el-attach-label is-${i.rel}`,style:{left:`${Fe}px`,top:`${mt}px`},children:[i.count&&i.count>1?`${R("canvasel.attach.count",{n:i.count})} · `:"",i.rel==="child"?R("canvasel.attach.child"):R("canvasel.attach.sibling")]})]})})():null,M?.map((k,J)=>f.jsx("div",{className:`amx-el-guide is-${k.dir}`,style:{left:`${k.x}px`,top:`${k.y}px`,width:`${k.w}px`,height:`${k.h}px`}},`guide:${J}`)),a?f.jsx("div",{className:"amx-el-marquee",style:{left:`${a.x}px`,top:`${a.y}px`,width:`${a.w}px`,height:`${a.h}px`}}):null]})}const vu=["nw","ne","sw","se"],$x=["n","e","s","w",...vu];function nl({anchor:e}){return f.jsx(f.Fragment,{children:$x.map(t=>f.jsx("div",{className:`amx-card-size-grip is-${t}`,"data-card-grip":e,"data-card-edge":t},t))})}function Ax({id:e,box:t}){return f.jsx(f.Fragment,{children:vu.map(n=>f.jsx("div",{className:`amx-el-grip is-free is-${n}`,"data-grip":e,"data-corner":n,style:{left:`${(n[1]==="e"?t.x+t.w:t.x)-5}px`,top:`${(n[0]==="s"?t.y+t.h:t.y)-5}px`}},n))})}function ol({node:e}){const{t}=tn();return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-el-add is-child","data-add":"child","data-node":e,title:t("canvasel.add.child"),children:"+"}),f.jsx("div",{className:"amx-el-add is-sibling","data-add":"sibling","data-node":e,title:t("canvasel.add.sibling"),children:"+"})]})}const Nx=["n","e","s","w"];function Na({node:e,box:t}){const{t:n}=tn(),o=r=>t?{left:`${r==="w"?t.x:r==="e"?t.x+t.w:t.x+t.w/2}px`,top:`${r==="n"?t.y:r==="s"?t.y+t.h:t.y+t.h/2}px`}:void 0;return f.jsx(f.Fragment,{children:Nx.map(r=>f.jsx("div",{className:`amx-link-dot is-${r}${t?" is-free":""}`,"data-link-from":e,title:n("canvasel.link.drag"),style:o(r)},r))})}function Tx({el:e,box:t,sel:n}){const o=wc(e.color);return f.jsx("div",{className:`amx-el-frame${n?" is-sel":""}`,"data-color":o["data-color"],style:{left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,...o.style},children:f.jsx("div",{className:"amx-el-frame-bar","data-el":e.id,children:e.title??"Frame"})})}function jx({el:e,box:t,sel:n}){const o=e.kind==="text"?"amx-el-text":e.shape==="ellipse"?"amx-el-ellipse":"amx-el-rect",r=wc(e.color);return f.jsx("div",{className:`amx-el-shape ${o}${n?" is-sel":""}`,"data-el":e.id,"data-color":r["data-color"],style:{left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,...r.style},children:e.text})}function Fs({el:e,a:t,b:n,sel:o,related:r,tree:s,preview:c}){if(!t||!n)return null;const a=Cx(t,n),i=14,d={x:a.box.x-i,y:a.box.y-i,w:a.box.w+i*2,h:a.box.h+i*2},p=9,h=4.5,M=(S,I)=>{const X=Math.cos(I),ee=Math.sin(I);return[`${S.x},${S.y}`,`${S.x-p*X+h*ee},${S.y-p*ee-h*X}`,`${S.x-p*X-h*ee},${S.y-p*ee+h*X}`].join(" ")},R=!s&&e.toEnd!=="none",T=!s&&e.fromEnd==="arrow",w=wc(e.color);return f.jsxs(f.Fragment,{children:[f.jsxs("svg",{className:`amx-el-conn${o?" is-sel":""}${r?" is-related":""}${s?" is-tree":""}${c?" is-preview":""}`,"data-el":e.id,"data-color":w["data-color"],style:{left:`${d.x}px`,top:`${d.y}px`,width:`${d.w}px`,height:`${d.h}px`,...w.style},viewBox:`${d.x} ${d.y} ${d.w} ${d.h}`,children:[r?f.jsx("path",{className:"amx-el-conn-halo",d:a.d}):null,f.jsx("path",{className:"amx-el-conn-core",d:a.d}),R?f.jsx("polygon",{points:M(a.tip,a.ang)}):null,T?f.jsx("polygon",{points:M(a.tail,a.tailAng)}):null]}),e.label?f.jsx("div",{className:`amx-el-label${o?" is-sel":""}`,"data-color":w["data-color"],style:{left:`${a.mid.x}px`,top:`${a.mid.y}px`,...w.style},children:e.label}):null]})}const Os=e=>typeof e=="number"&&Number.isFinite(e)?e:null,os=e=>typeof e=="string"&&e?e:null,Ta=e=>ra(e)?e:null,rl=e=>e==="none"||e==="arrow"?e:null,rs=e=>({x:Math.round(e.x),y:Math.round(e.y),width:Math.max(1,Math.round(e.w)),height:Math.max(1,Math.round(e.h))});function Rx(e){const t=/^!\[\[([^\]\n]+)\]\]$/.exec(e.trim());return t?t[1]:null}function sl(e,t){const n=t.x+t.w/2-(e.x+e.w/2),o=t.y+t.h/2-(e.y+e.h/2);return Math.abs(n)*e.h>=Math.abs(o)*e.w?n>=0?"right":"left":o>=0?"bottom":"top"}function Dx(e){const t=[],n=[],o=[],r=new Map,s=e.pages?[...e.pages].sort():[],c=Array.isArray(e.elements)?e.elements:[],a=new Set,i=[];for(const w of c){if(!w||typeof w!="object"||Array.isArray(w))continue;const S=w,I=os(S.id);if(!I||a.has(I))continue;if(S.type==="connector"){a.add(I),i.push(S);continue}if(S.type!=="shape"&&S.type!=="text"&&S.type!=="frame")continue;const X=Os(S.x),ee=Os(S.y),q=Os(S.w),oe=Os(S.h);if(X==null||ee==null||q==null||oe==null||q<=0||oe<=0)continue;a.add(I);const Re=`el-${I}`,Ge={x:X,y:ee,w:q,h:oe};r.set(Re,Ge);const m=Ta(S.color);if(S.type==="frame"){const ke=os(S.title);t.push({id:Re,type:"group",...rs(Ge),...ke?{label:ke}:{},...m?{color:m}:{}})}else n.push({id:Re,type:"text",...rs(Ge),text:typeof S.text=="string"?S.text:"",...m?{color:m}:{}})}for(const w of e.cards){const S=`card-${w.ref}`;r.set(S,w);const I=Ta(w.color),X=Rx(w.md),ee=X&&s.length?gs(Sl(X),s,e.sourcePath):null;if(X&&ee){const q=X.split("|")[0],oe=q.indexOf("#"),Re=oe>=0?q.slice(oe).trim():"";o.push({id:S,type:"file",...rs(w),file:ee,...Re.length>1?{subpath:Re}:{},...I?{color:I}:{}})}else o.push({id:S,type:"text",...rs(w),text:w.md,...I?{color:I}:{}})}const d=[],p=w=>{if(!w||typeof w!="object")return null;const S=w,I=os(S.ref)?`card-${S.ref}`:os(S.id)?`el-${S.id}`:S.main===!0?"main":null;return I&&(r.has(I)||I==="main")?I:null};e.main&&r.set("main",e.main);let h=!1;const M=w=>{const S=r.get(w.fromNode),I=r.get(w.toNode);!S||!I||((w.fromNode==="main"||w.toNode==="main")&&(h=!0),d.push({...w,fromSide:sl(S,I),toSide:sl(I,S)}))};for(const w of i){const S=p(w.from),I=p(w.to);if(!S||!I||S===I)continue;const X=rl(w.fromEnd),ee=rl(w.toEnd),q=os(w.label),oe=Ta(w.color);M({id:`edge-${w.id}`,fromNode:S,toNode:I,...X?{fromEnd:X}:{},...ee?{toEnd:ee}:{},...q?{label:q}:{},...oe?{color:oe}:{}})}const R=e.tree&&typeof e.tree=="object"&&!Array.isArray(e.tree)?e.tree:{};for(const w of Object.keys(R)){const S=R[w];if(typeof S!="string"||!S||S===w)continue;const I=S==="m:"?"main":`card-${S}`,X=`card-${w}`;r.has(X)&&M({id:`tree-${w}`,fromNode:I,toNode:X,toEnd:"none"})}const T=[...t,...n];return e.main&&(e.main.md.trim()||h)&&T.push({id:"main",type:"text",...rs(e.main),text:e.main.md}),T.push(...o),{nodes:T,edges:d}}const Lx=e=>`${JSON.stringify(e,null," ")}
48
- `;function Ix(e,t=1){const n=e.lastIndexOf("/"),o=n>=0?e.slice(0,n+1):"",r=e.slice(n+1).replace(/\.md$/i,"");return`${o}${r}${t>1?` ${t}`:""}.canvas`}async function Px(e,t,n){for(let o=1;o<=50;o++){const r=Ix(t,o);if(await e.readTextFile(r).catch(()=>null)!=null)continue;const s=await e.writeTextFile(r,n,{create:!0});if(s&&s.ok===!1){if(s.current!=null)continue;throw new Error(`Could not create ${r}`)}return r}throw new Error("Too many exported canvases with the same name")}kn({"canvasstage.textTitle.connector":{zh:"连线标签",en:"Connector label"},"canvasstage.textTitle.frame":{zh:"Frame 标题",en:"Frame title"},"canvasstage.textTitle.element":{zh:"元素文字",en:"Element text"},"canvasstage.upload.fileN":{zh:"文件{n}",en:"File {n}"},"canvasstage.upload.uploading":{zh:"上传中 {name}",en:"Uploading {name}"},"canvasstage.toast.needEdit":{zh:"双击卡片(或选中后按空格)进入编辑模式,才能勾选待办、点开双链",en:"Double-click a card (or select it and press Space) to edit — then you can tick to-dos and open backlinks"},"canvasstage.toolbar.label":{zh:"画布工具",en:"Canvas tools"},"canvasstage.tool.select":{zh:"选择 (Esc)",en:"Select (Esc)"},"canvasstage.tool.pan":{zh:"抓手(或按住空格 / Alt 拖)",en:"Pan (or hold Space or Alt and drag)"},"canvasstage.tool.card":{zh:"新建卡片(双击空白同)",en:"New card (or double-click empty space)"},"canvasstage.tool.frame":{zh:"Frame:拖出范围(或点一下取默认大小)",en:"Frame: drag to size (or click for the default size)"},"canvasstage.tool.conn":{zh:"箭头:依次点父节点、子节点(Shift 或形状=自由连线)",en:"Arrow: click the parent, then the child (Shift or a shape = free connector)"},"canvasstage.shape.rect":{zh:"矩形",en:"Rectangle"},"canvasstage.shape.ellipse":{zh:"椭圆",en:"Ellipse"},"canvasstage.shape.text":{zh:"文本",en:"Text"},"canvasstage.conn.hint":{zh:"再点一个对象:卡片/正文 = 收它作子节点(按住 Shift = 改画自由连线),形状 = 自由连线;Esc 取消",en:"Now click another object: a card or the body text becomes a child node (hold Shift to draw a free connector instead), a shape gets a free connector. Esc cancels."},"canvasstage.overview.label":{zh:"低倍率简略显示",en:"Low-zoom overview"},"canvasstage.overview.off":{zh:"关闭低倍率简略显示",en:"Turn off low-zoom overview"},"canvasstage.overview.on":{zh:"开启低倍率简略显示",en:"Turn on low-zoom overview"},"canvasstage.guides.label":{zh:"对齐参考线",en:"Alignment guides"},"canvasstage.guides.off":{zh:"关闭对齐参考线",en:"Turn off alignment guides"},"canvasstage.guides.on":{zh:"开启对齐参考线",en:"Turn on alignment guides"},"canvasstage.menu.editText":{zh:"编辑文字",en:"Edit text"},"canvasstage.menu.connectTo":{zh:"连线到…",en:"Connect to…"},"canvasstage.menu.copy":{zh:"复制",en:"Copy"},"canvasstage.menu.duplicate":{zh:"重复",en:"Duplicate"},"canvasstage.menu.arrange":{zh:"一键整理",en:"Auto-arrange"},"canvasstage.menu.groupFrame":{zh:"成组为 Frame",en:"Group into a frame"},"canvasstage.menu.unwrap":{zh:"收回文档",en:"Unwrap into document"},"canvasstage.menu.delete":{zh:"删除",en:"Delete"},"canvasstage.menu.newCard":{zh:"新建卡片",en:"New card"},"canvasstage.menu.addNote":{zh:"添加笔记…",en:"Add note…"},"canvasstage.menu.fit":{zh:"适应内容",en:"Fit to content"},"canvasstage.menu.exportCanvas":{zh:"导出为 JSON Canvas",en:"Export as JSON Canvas"},"canvasstage.export.done":{zh:"已导出 JSON Canvas:{path}",en:"Exported JSON Canvas: {path}"},"canvasstage.export.failed":{zh:"导出 JSON Canvas 失败:{e}",en:"JSON Canvas export failed: {e}"},"canvasstage.color.label":{zh:"颜色",en:"Color"},"canvasstage.color.none":{zh:"无颜色",en:"No color"},"canvasstage.color.red":{zh:"红色",en:"Red"},"canvasstage.color.orange":{zh:"橙色",en:"Orange"},"canvasstage.color.yellow":{zh:"黄色",en:"Yellow"},"canvasstage.color.green":{zh:"绿色",en:"Green"},"canvasstage.color.cyan":{zh:"青色",en:"Cyan"},"canvasstage.color.purple":{zh:"紫色",en:"Purple"},"canvasstage.color.custom":{zh:"自定义颜色…",en:"Custom color…"},"canvasstage.ends.label":{zh:"箭头",en:"Arrows"},"canvasstage.ends.end":{zh:"箭头指向终点",en:"Arrow at end"},"canvasstage.ends.start":{zh:"箭头指向起点",en:"Arrow at start"},"canvasstage.ends.both":{zh:"双向箭头",en:"Arrows at both ends"},"canvasstage.ends.none":{zh:"无箭头",en:"No arrows"}});const Fx=[{v:"",nameKey:"canvasstage.color.none"},{v:"1",nameKey:"canvasstage.color.red"},{v:"2",nameKey:"canvasstage.color.orange"},{v:"3",nameKey:"canvasstage.color.yellow"},{v:"4",nameKey:"canvasstage.color.green"},{v:"5",nameKey:"canvasstage.color.cyan"},{v:"6",nameKey:"canvasstage.color.purple"}],al=[{id:"end",from:"none",to:"arrow",nameKey:"canvasstage.ends.end",icon:f.jsx(rh,{size:13})},{id:"start",from:"arrow",to:"none",nameKey:"canvasstage.ends.start",icon:f.jsx(ah,{size:13})},{id:"both",from:"arrow",to:"arrow",nameKey:"canvasstage.ends.both",icon:f.jsx(nh,{size:13})},{id:"none",from:"none",to:"none",nameKey:"canvasstage.ends.none",icon:f.jsx(wp,{size:13})}],Ox=2,Hs=168,wu=72,ja=320,cl=12,ss=".amx-el-shape, .amx-el-frame-bar",il="button, a[href], input, select, textarea",_x='li[data-item-type="task"], .wikilink';function Bx(e,t){const n=e.closest(_x);return n?n.tagName!=="LI"||t-n.getBoundingClientRect().left<=2:!1}const Ra=e=>e.kind==="connector"?"label":e.kind==="frame"?"title":"text",Da=e=>we(e.kind==="connector"?"canvasstage.textTitle.connector":e.kind==="frame"?"canvasstage.textTitle.frame":"canvasstage.textTitle.element"),_s=e=>[...Nr(Rn(e).filter(t=>t.kind!=="frame"),null).values()],ll=50,La=new Set(["rect","ellipse","frame"]),as={rect:"rect",ellipse:"ellipse",text:"text"};let Kx=0;const ul=(e,t,n,o,r,s=Hs)=>Zf(e,t,n,o,r,s,wu);function Cc(e){const t=[];return e.forEach((n,o,r)=>{n.type.name==="amadeusCanvasCard"&&t.push({anchor:String(n.attrs.anchor),pos:o,idx:r,node:n})}),t}function On(e){return Cc(e.state.doc)}const ac=(e,t,n)=>Zs(e,t,n);function ku(e,t,n){const o=Cc(e),r=o.findIndex(c=>c.anchor===n);if(r<0)return e.content.size;const s=o[ac(o,r,t)-1];return s.pos+s.node.nodeSize}function dl(e,t,n,o){const r=Cc(e.doc),s=r.findIndex(M=>M.anchor===n);if(s<0)return e;const c=ac(r,s,t),a=r[s].pos,i=r[c-1],d=i.pos+i.node.nodeSize;let p;if(o){const M=r.findIndex(w=>w.anchor===o);if(M<0||M>=s&&M<c)return e;const R=ac(r,M,t);if(s>M&&s<R)return e;const T=r[R-1];p=T.pos+T.node.nodeSize}else if(p=e.doc.content.size,d===p)return e;const h=So.fromArray(r.slice(s,c).map(M=>M.node));return e.delete(a,d).insert(p>d?p-(d-a):p,h)}function ar(e,t){e.dispatch(Us(t).setMeta("amxCanvas",!0))}function Cr(e,t,n=!0){const o=On(e);let r=e.state.tr,s=!1;for(const c of o){const a=t.get(c.anchor);a&&(r=r.setNodeMarkup(c.pos,void 0,{...c.node.attrs,...a}),s=!0)}s&&(n?ar(e,r):e.dispatch(r.setMeta("amxCanvas",!0).setMeta("addToHistory",!1)))}function Vx(e,t,n,o){const r=On(e).find(a=>a.anchor===t),s=e.state.schema.nodes.paragraph;if(!r||!s||o!=null&&r.node.textContent!==o)return!1;const c=s.create(null,n?e.state.schema.text(n):void 0);return e.dispatch(e.state.tr.replaceWith(r.pos+1,r.pos+r.node.nodeSize-1,c).setMeta("amxCanvas",!0)),!0}function fl(e){if(!e?.childCount)return;const t=[];return e.forEach(n=>{n.type.name==="amadeusCanvasCard"?n.content.forEach(o=>t.push(o)):t.push(n)}),t.length?So.fromArray(t):void 0}function ml(e,t=!1){return e.kind==="note"?`${t?"":"!"}[[${e.path.replace(/\.md$/i,"")}]]`:e.kind==="session"?`[[session:${e.id}|${e.title}]]`:e.kind==="app"||e.kind==="window"?Wf(e):e.path}const pl="application/x-amx-canvas";let Ia=null;function Hx(e){if(!e)return null;try{const t=JSON.parse(e);if(typeof t?.token!="string"||!Array.isArray(t.mds))return null;const n=t.mds.filter(s=>typeof s=="string"),o={token:t.token,mds:n},r=s=>typeof s=="number"&&Number.isFinite(s);if(Array.isArray(t.cards)&&t.cards.length===n.length&&n.length===t.mds.length){const s=t.cards.flatMap(c=>{const a=c;return!a||typeof a.ref!="string"||!r(a.x)||!r(a.y)||!r(a.w)||a.w<=0?[]:[{ref:a.ref,x:a.x,y:a.y,w:a.w,h:r(a.h)&&a.h>0?a.h:0,...typeof a.color=="string"?{color:a.color}:{}}]});s.length===n.length&&(o.cards=s)}return Array.isArray(t.els)&&(o.els=t.els.filter(s=>!!s&&typeof s=="object"&&!Array.isArray(s))),Array.isArray(t.tree)&&(o.tree=t.tree.filter(s=>Array.isArray(s)&&typeof s[0]=="string"&&typeof s[1]=="string")),o}catch{return null}}const Pa=(e,t)=>({x:e.x-t,y:e.y-t,w:e.w+t*2,h:e.h+t*2}),hl=(e,t)=>e.x<t.x+t.w&&e.x+e.w>t.x&&e.y<t.y+t.h&&e.y+e.h>t.y;function qx({hostRef:e,vp:t,elements:n,ghost:o,onCenter:r}){const[,s]=b.useState(0);b.useEffect(()=>{const h=e.current;if(!h)return;let M=0;const R=new Set,T=new ResizeObserver(()=>S()),w=()=>{const X=new Set(h.querySelectorAll(".amx-ucard")),ee=h.querySelector(".ProseMirror");ee&&X.add(ee);for(const q of X)R.has(q)||(T.observe(q,{box:"border-box"}),R.add(q));for(const q of[...R])X.has(q)||(T.unobserve(q),R.delete(q))},S=()=>{cancelAnimationFrame(M),M=requestAnimationFrame(()=>{w(),s(X=>X+1)})},I=new MutationObserver(S);return I.observe(h,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["data-x","data-y","data-w"]}),T.observe(h),S(),()=>{cancelAnimationFrame(M),I.disconnect(),T.disconnect()}},[e]);const c=e.current;if(!c)return null;const a=[];for(const[h,M]of hn(c))a.push({key:Ot(h),kind:"card",box:M});const i=gn(c);i&&a.push({key:ye,kind:"main",box:i});const d=Rn(n),p=Nr(d,o);for(const h of d){if(h.kind==="connector")continue;const M=p.get(h.id);M&&a.push({key:yn(h.id),kind:h.kind==="frame"?"frame":"shape",box:M})}return f.jsx(cp,{hostRef:e,vp:t,items:a,onCenter:r})}function Wx({path:e,vaultRoot:t=null,active:n,getView:o,main:r,mainStored:s,elements:c,tree:a,onElements:i,onTree:d,onMain:p,timeline:h,histStepRef:M,onCommit:R,saveFile:T,parseMd:w,serializeMd:S,onBlocksDeleted:I,revealSelection:X=0,readOnly:ee=!1,notePages:q,exportRef:oe,storedMd:Re,children:Ge}){const m=b.useRef(null),{t:ke}=tn(),rt=Pf(t,e),[de,me]=b.useState(()=>ni(rt)??{x:0,y:0,z:1}),he=b.useRef(de);he.current=de;const[ze,He]=b.useState(ip),[Te,dt]=b.useState(lp),[sn,re]=b.useState(bi);b.useEffect(()=>up(()=>re(bi())),[]);const[ce,ge]=b.useState(dp),k=b.useRef(ce);k.current=ce;const[J,le]=b.useState(fp),ve=b.useRef(J);ve.current=J;const[Ye,Fe]=b.useState(null),mt=b.useCallback(u=>{k.current=u,ge(u),mp(u)},[]),[it,_t]=b.useState("select"),jt=b.useRef("select"),ht=b.useRef(ee);ht.current=ee;const Mt=b.useCallback(u=>{jt.current=u,_t(u)},[]),[ot,an]=b.useState([]),Ct=b.useRef([]),lt=b.useCallback(u=>{const z=typeof u=="function"?u(Ct.current):u;Ct.current=z,an(z)},[]),[Kt,cn]=b.useState(null),Xt=b.useRef(null),zn=b.useCallback(u=>{Xt.current=u,cn(u)},[]),[Zn,mr]=b.useState(null),nn=b.useRef(null),Xn=b.useCallback(u=>{nn.current=u,mr(u)},[]),$n=b.useRef({held:!1,used:!1}),[Qn,Mo]=b.useState(!1);b.useEffect(()=>{const u=m.current;if(!Zn||!u)return;const z=u.dataset.amxDragscope;if(!z)return;const N=document.createElement("style");return N.textContent=Zn===ye?`.amx-stage[data-amx-dragscope="${z}"] .ProseMirror{cursor:text;}`:`.amx-stage[data-amx-dragscope="${z}"] .amx-ucard[data-anchor="${CSS.escape(Zn)}"]{cursor:text;}`,document.head.appendChild(N),()=>N.remove()},[Zn]);const Yo=b.useRef(0),[Xo,Cn]=b.useState(null),[An,Ln]=b.useState(null),[yo,xo]=b.useState(null),[at,It]=b.useState(null),[bo,ao]=b.useState(null),[Uo,zo]=b.useState(!1),Wn=b.useRef(0),Pe=b.useCallback(()=>{cancelAnimationFrame(Wn.current),Wn.current=0,zo(!1)},[]);b.useEffect(()=>()=>cancelAnimationFrame(Wn.current),[]);const Wt=b.useRef({raf:0,animations:[]}),y=b.useCallback(()=>{cancelAnimationFrame(Wt.current.raf),Wt.current.raf=0;const u=Wt.current.animations.splice(0);for(const z of u)z.cancel()},[]),$=b.useCallback(u=>{const z=m.current;y(),!(!z||!u.length||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Wt.current.raf=requestAnimationFrame(()=>{Wt.current.raf=0;let N=0;const B=K=>{Wt.current.animations.push(K);const O=()=>{Wt.current.animations=Wt.current.animations.filter(W=>W!==K)};K.addEventListener("finish",O,{once:!0}),K.addEventListener("cancel",O,{once:!0})};for(const K of u){const O=z.querySelector(`.amx-ucard[data-anchor="${CSS.escape(K.anchor)}"]`),W=Math.hypot(K.x,K.y);if(!O||W<1)continue;const te=Math.min(126,Math.max(0,K.depth-1)*42),pe=Math.round(Math.max(420,Math.min(620,360+W*.34)));N=Math.max(N,te+pe);const ne=O.animate([{transform:`translate(${-K.x}px, ${-K.y}px) scale(0.988)`,opacity:.94,boxShadow:"0 8px 24px rgb(0 0 0 / 18%)",offset:0,easing:"cubic-bezier(0.16, 0.82, 0.24, 1)"},{transform:`translate(${K.x*.035}px, ${K.y*.035}px) scale(1.003)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-K.x*.008}px, ${-K.y*.008}px) scale(0.999)`,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:.9,easing:"ease-out"},{transform:"translate(0, 0) scale(1)",opacity:1,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:1}],{duration:pe,delay:te,fill:"backwards"});ne.id="amx-card-arrange",B(ne)}if(N>0)for(const K of z.querySelectorAll(".amx-el-conn, .amx-el-label")){const O=K.animate([{opacity:.12,offset:0},{opacity:.12,offset:.68},{opacity:1,offset:1,easing:"ease-out"}],{duration:N,fill:"backwards"});O.id="amx-card-arrange-line",B(O)}}))},[y]),P=b.useCallback((u,z)=>{const N=m.current,B=Math.hypot(z.x,z.y);y(),!(!N||B<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Wt.current.raf=requestAnimationFrame(()=>{Wt.current.raf=0;const K=pe=>{Wt.current.animations.push(pe);const ne=()=>{Wt.current.animations=Wt.current.animations.filter(l=>l!==pe)};pe.addEventListener("finish",ne,{once:!0}),pe.addEventListener("cancel",ne,{once:!0})},O=Math.round(Math.max(400,Math.min(520,350+B*.42))),W=N.querySelector(`.amx-ucard[data-anchor="${CSS.escape(u)}"]`);if(W){const pe=W.animate([{transform:`translate(${-z.x}px, ${-z.y}px) scale(1.012)`,opacity:.94,boxShadow:"0 12px 32px rgb(0 0 0 / 24%)",offset:0,easing:"ease-in"},{transform:`translate(${-z.x*.54}px, ${-z.y*.54}px) scale(1.007)`,opacity:.97,boxShadow:"0 8px 24px rgb(0 0 0 / 19%)",offset:.22,easing:"cubic-bezier(0.16, 0.82, 0.24, 1)"},{transform:`translate(${z.x*.05}px, ${z.y*.05}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-z.x*.012}px, ${-z.y*.012}px) scale(1.001)`,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:.9,easing:"ease-out"},{transform:"translate(0, 0) scale(1)",opacity:1,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:1}],{duration:O,fill:"none"});pe.id="amx-card-attach",K(pe)}const te=N.querySelector(`.amx-el-conn[data-el="${CSS.escape(`t:${u}`)}"]`);if(te){const pe=te.animate([{opacity:0,offset:0},{opacity:0,offset:.56},{opacity:1,offset:1,easing:"ease-out"}],{duration:O,fill:"backwards"});pe.id="amx-card-attach-line",K(pe)}}))},[y]);b.useEffect(()=>y,[y]);const[D,V]=b.useState(null),[U,se]=b.useState(null);b.useEffect(()=>{Kt||V(null)},[Kt]);const G=new Set(ot),Q=b.useRef(!ni(rt));b.useEffect(()=>{n&&Ff(rt,de)},[rt,de,n]),b.useLayoutEffect(()=>{const u=m.current;!n||!Zn||!u||!document.activeElement||!u.contains(document.activeElement)||tm()},[n,Zn,de]);const H=b.useRef({getView:o,onCommit:R,onElements:i,onTree:d,onMain:p,timeline:h,elements:c,tree:a,main:r,mainStored:s,saveFile:T,parseMd:w,serializeMd:S,onBlocksDeleted:I,notePages:q,path:e,storedMd:Re});H.current={getView:o,onCommit:R,onElements:i,onTree:d,onMain:p,timeline:h,elements:c,tree:a,main:r,mainStored:s,saveFile:T,parseMd:w,serializeMd:S,onBlocksDeleted:I,notePages:q,path:e,storedMd:Re};const Me=Rn(c),Ie=u=>{if(!u)return null;const z={x:u.x,y:u.y,w:u.w,...typeof u.h=="number"&&u.h>0?{h:u.h}:{}};return z.x!==0||z.y!==0||z.w!==Ko||(z.h??0)>0?z:null},Oe=()=>{const u=H.current;return{e:Po(u.elements),t:Vt(u.tree),m:Ie(u.mainStored?u.main:null)}},_e=b.useRef(null),Ke=b.useRef({past:[],future:[]}),We=()=>Ke.current;b.useEffect(()=>{const u=Oe(),z=JSON.stringify(u);if(!(_e.current!==null&&z===_e.current)){if(_e.current!==null)try{const N=JSON.parse(_e.current),B=(O,W)=>{let te=N.t[O];const pe=new Set([O]);for(;typeof te=="string"&&te&&!pe.has(te);){if(te===W)return!0;pe.add(te),te=N.t[te]}return!1};if(JSON.stringify(u.e)===JSON.stringify(N.e)&&JSON.stringify(u.m)===JSON.stringify(N.m)&&Object.keys(u.t).length<=Object.keys(N.t).length&&Object.keys(u.t).every(O=>typeof N.t[O]<"u"&&(JSON.stringify(u.t[O])===JSON.stringify(N.t[O])||B(O,u.t[O])))){_e.current=z;return}}catch{}_e.current=z,Ke.current={past:[],future:[]},H.current.timeline.log.length=0,H.current.timeline.future.length=0}},[e,c,a,r,s]);const Ve=b.useCallback((u,z)=>{const N=H.current,B=Oe(),K=JSON.stringify(B),O=JSON.stringify({e:u.e??B.e,t:u.t??B.t,m:u.m?Ie(u.m):B.m});if(O!==K){if(z?.snap!==!1){const W=We();W.past.push(K),W.past.length>ll&&W.past.shift(),W.future.length=0,N.timeline.log.push("fm"),N.timeline.future.length=0;const te=N.getView();te&&te.dispatch(Us(te.state.tr))}_e.current=O,u.e&&N.onElements(u.e),u.t&&N.onTree(u.t),u.m&&N.onMain(u.m)}},[e]),Xe=b.useCallback(u=>{const z=Po(H.current.elements),N=u(z);N!==z&&Ve({e:N})},[Ve]),Ut=b.useCallback(u=>{const z=We(),N=u==="undo"?z.past:z.future,B=u==="undo"?z.future:z.past,K=N.pop();if(K==null)return!1;const O=H.current;B.push(JSON.stringify(Oe()));const W=JSON.parse(K);return _e.current=K,O.onElements(W.e),O.onTree(W.t),O.onMain(W.m??{x:0,y:0,w:Ko}),!0},[e]),pt=b.useCallback(()=>{const u=We();u.past.push(JSON.stringify(Oe())),u.past.length>ll&&u.past.shift(),u.future.length=0;const z=H.current.timeline;z.log.push("fm"),z.future.length=0},[e]),gt=b.useCallback(u=>{const z=Vt(H.current.tree);return u.some(N=>typeof z[N]<"u"||Object.keys(z).some(B=>z[B]===N))},[]),Je=b.useCallback(()=>{const u=H.current.timeline,z=u.log.length;if(z<2)return;const N=u.log[z-2],B=u.log[z-1];(N==="pm"&&B==="fm"||N==="fm"&&B==="pm")&&u.log.splice(z-2,2,"pair")},[]),Un=b.useCallback(u=>{const z=H.current.timeline,N=u==="undo"?z.log:z.future,B=u==="undo"?z.future:z.log,K=()=>{const te=H.current.getView();return!!te&&(u==="undo"?Ba(te.state):jd(te.state))>0},O=()=>(u==="undo"?We().past:We().future).length>0,W=()=>{const te=H.current.getView();return!!te&&(u==="undo"?Ka:jl)(te.state,te.dispatch)};for(;N.length;){const te=N[N.length-1];if(N.pop(),te==="pair"){if(!K()||!O())continue;return Ut(u),W(),B.push(te),!0}if(te==="fm"){if(Ut(u))return B.push(te),!0;continue}if(W())return B.push("pm"),!0}return W()},[Ut]);b.useEffect(()=>{if(M)return M.current=Un,()=>{M.current===Un&&(M.current=null)}},[M,Un]);const Pt=b.useCallback((u,z)=>{const N=m.current,B=N?.getBoundingClientRect(),{x:K,y:O,z:W}=he.current;if(!N||!B)return{x:0,y:0};const te=En(N)||1;return{x:((u-B.left)/te-K)/W,y:((z-B.top)/te-O)/W}},[]),Qt=b.useCallback(()=>{Pe();const u=m.current,z=o();if(!u||!z)return;const N=[...u.querySelectorAll(".amx-ucard, .amx-el-shape, .amx-el-frame, .amx-el-frame-bar, .amx-el-conn, .amx-el-label"),z.dom].map(ie=>ie.getBoundingClientRect());if(!N.length)return;const{x:B,y:K,z:O}=he.current,W=u.getBoundingClientRect(),te=En(u)||1,pe=(ie,C)=>(ie/te-C)/O,ne=Math.min(...N.map(ie=>pe(ie.left-W.left,B))),l=Math.min(...N.map(ie=>pe(ie.top-W.top,K))),g=Math.max(...N.map(ie=>pe(ie.right-W.left,B))),v=Math.max(...N.map(ie=>pe(ie.bottom-W.top,K))),E=g-ne,L=v-l;if(E<=0||L<=0)return;const Y=48,_=Math.max(Gr,Math.min(1,Math.min((W.width/te-Y*2)/E,(W.height/te-Y*2)/L)));me({z:_,x:(W.width/te-E*_)/2-ne*_,y:(W.height/te-L*_)/2-l*_})},[o,Pe]),Gn=b.useCallback(u=>{Pe();const z=m.current;if(!z)return;const{x:N,y:B,z:K}=he.current,O=Math.max(Gr,Math.min(js,K*u));if(O===K)return;const W=En(z)||1,te=z.getBoundingClientRect().width/W/2,pe=z.getBoundingClientRect().height/W/2;me({z:O,x:te-(te-N)*O/K,y:pe-(pe-B)*O/K})},[Pe]),$o=b.useCallback((u,z)=>{Pe();const N=m.current;if(!N)return;const B=En(N)||1,K=N.getBoundingClientRect(),O=he.current.z;me({z:O,x:K.width/B/2-u*O,y:K.height/B/2-z*O})},[Pe]);b.useEffect(()=>{const u=m.current;if(!ee||!u)return;const z=()=>{const N=H.current.getView(),B=document.getSelection();if(!N||!B||B.isCollapsed||!B.rangeCount)return;const K=B.getRangeAt(0),O=pe=>N.dom.contains(pe.nodeType===3?pe.parentNode:pe),W=O(K.startContainer),te=O(K.endContainer);if(!(!W&&!te))try{const pe=N.state.doc,ne=W?N.posAtDOM(K.startContainer,K.startOffset):0,l=te?N.posAtDOM(K.endContainer,K.endOffset):pe.content.size,g=Ne.between(pe.resolve(Math.min(ne,l)),pe.resolve(Math.max(ne,l)));g.eq(N.state.selection)||N.dispatch(N.state.tr.setSelection(g))}catch{}};return u.addEventListener("copy",z,!0),()=>u.removeEventListener("copy",z,!0)},[ee]),b.useEffect(()=>{const u=m.current;if(!n||!u)return;const z=N=>{const B=N.detail?.rect;if(!B)return;const K=Pt(B.left+B.width/2,B.top+B.height/2);$o(K.x,K.y),N.preventDefault()};return u.addEventListener("amx-reveal",z),()=>u.removeEventListener("amx-reveal",z)},[n,Pt,$o]);const jr=b.useRef(Qt);jr.current=Qt,b.useEffect(()=>{if(!n||!Q.current)return;Q.current=!1;const u=setTimeout(()=>jr.current(),220);return()=>clearTimeout(u)},[n]),b.useEffect(()=>{n||(lt([]),Mt("select"),zn(null),It(null),ao(null),Xn(null))},[n]),b.useEffect(()=>{if(!at)return;const u=z=>{z.target?.closest?.(".ctx-menu")||It(null)};return window.addEventListener("pointerdown",u,!0),window.addEventListener("contextmenu",u,!0),()=>{window.removeEventListener("pointerdown",u,!0),window.removeEventListener("contextmenu",u,!0)}},[at]);const Bn=b.useCallback(u=>{const z=new Map;for(const[B,K]of hn(m.current))z.set(Ot(B),K);for(const[B,K]of Nr(Rn(H.current.elements),u))z.set(yn(B),K);const N=gn(m.current);return N&&z.set(ye,N),z},[]),pr=b.useRef(!1);b.useEffect(()=>()=>{pr.current=!0},[]);const Ao=b.useCallback(async(u,z,N)=>{const B=Rn(H.current.elements).find(W=>W.id===u);if(!B)return;const K=(B.kind==="connector"?B.label:B.kind==="frame"?B.title:B.text)??"",O=await qa(N,K);O==null||pr.current||Rn(H.current.elements).some(W=>W.id===u)&&Xe(W=>Hg(W,u,z,O.trim()))},[Xe]),In=b.useCallback((u,z)=>{const N=H.current,B=N.getView(),K=new Set(u.filter(ne=>ne.startsWith("c:")).map(nt));let O=!1;if(B&&K.size){const ne=z??"",l=new Map;for(const g of On(B))K.has(g.anchor)&&String(g.node.attrs.color??"")!==ne&&l.set(g.anchor,{color:ne});l.size&&(Cr(B,l),N.onCommit(),O=!0)}const W=new Set(u.filter(ne=>ne.startsWith("e:")).map(nt));if(!W.size)return;const te=Po(H.current.elements),pe=Ug(te,W,z);pe!==te&&(Ve({e:pe}),O&&Je())},[Ve,Je]),co=b.useCallback((u,z,N,B,K)=>{const O=H.current.getView(),W=O?.state.schema.nodes.amadeusCanvasCard,te=O?.state.schema.nodes.paragraph;if(!O||!W||!te)return null;const pe=Eo(O.state.doc),ne={x:u,y:z,w:Zt,h:80},l=[...hn(m.current).values(),..._s(H.current.elements)],g=gn(m.current);g&&l.push(g);const v=Jr([ne],l),E=u+v.x,L=z+v.y,Y=K?.childCount?K:te.create(null,B?O.state.schema.text(B):void 0),_=W.createAndFill({anchor:pe,x:Math.round(E),y:Math.round(L),w:Zt,h:0},Y);if(!_)return null;const ie=N?ku(O.state.doc,Vt(H.current.tree),N):O.state.doc.content.size;return ar(O,O.state.tr.insert(ie,_)),H.current.onCommit(pe),lt([Ot(pe)]),!B&&!K?.childCount&&Z.current.enterNodeEdit(Ot(pe)),pe},[Bn]),Go=b.useCallback((u,z)=>{const N=H.current.saveFile;N&&u.forEach((B,K)=>{const O=B.name||we("canvasstage.upload.fileN",{n:K+1}),W=we("canvasstage.upload.uploading",{name:O}),te=Z.current.addCardAt(z.x-Zt/2+K*24,z.y-24+K*24,void 0,W);te&&N(B).then(pe=>{const ne=H.current.getView(),l=ne?On(ne).find(g=>g.anchor===te&&g.node.textContent===W)??On(ne).find(g=>g.node.textContent===W):null;!ne||!l||(pe?(Vx(ne,l.anchor,pe,W),H.current.onCommit()):Z.current.removeSel([Ot(l.anchor)]))})})},[]),No=b.useCallback((u,z,N=0)=>{const B=u.trim();if(!B)return null;const K=H.current.parseMd?.(B)??null;return Z.current.addCardAt(z.x-Zt/2+N*24,z.y-24+N*24,void 0,B,fl(K))},[]),eo=b.useCallback(u=>{const z=Vt(H.current.tree),N=u(z);return N===z?!1:(Ve({t:N}),!0)},[Ve]),xn=b.useCallback(u=>u===ye?gn(m.current):hn(m.current).get(u)??null,[]),Jo=b.useCallback((u,z,N,B,K=0)=>{const O=xn(u);if(!O)return null;const W=Vt(H.current.tree),te=W[u],pe=z==="child"?u:typeof te=="string"&&te?te:"",ne=(pe?Er(W,pe):[u]).map(xn).filter(Boolean),l=80,g=32,E=z==="child"?N==="w"?O.x-B-l:O.x+O.w+l:ne.length?Math.min(...ne.map(C=>C.x)):O.x,L=ne.length?Math.min(...ne.map(C=>C.y))-g-K:O.y,Y=ne.length?Math.max(...ne.map(C=>C.y+C.h))+g:O.y,_=N==="n"?L:Y,ie=z==="child"?Er(W,u).length?_:O.y:_;return{parent:pe,x:Math.round(E),y:Math.round(ie)}},[xn]),To=b.useCallback((u,z,N,B=80)=>{const K=xn(u);if(!K)return null;const O=Vt(H.current.tree),W=O[u],te=z==="child"?u:typeof W=="string"&&W?W:"",pe=z==="child"?K:te?xn(te):K;if(!pe)return null;const ne=H.current.getView(),l=ne?On(ne).map(fe=>fe.anchor):[],v=(te?Er(O,te):z==="child"?Er(O,u):l.filter(fe=>typeof O[fe]!="string"||!O[fe])).map(fe=>xn(fe)).filter(Boolean),E=pe.x+pe.w/2,L=[...hn(m.current).values(),..._s(H.current.elements)],Y=gn(m.current);Y&&L.push(Y);const _=80,ie=32;let C=null;for(const fe of[1,-1]){const Se=v.filter(un=>(un.x+un.w/2-E)*fe>0),Be=fe>0?pe.x+pe.w+_:pe.x-_-N,Ue=Se.length?Math.max(...Se.map(un=>un.y+un.h))+ie:pe.y,At=Jr([{x:Be,y:Ue,w:N,h:B}],L,{x:fe,y:0}),Sn=Math.hypot(At.x,At.y)*100+Se.length*32+(fe<0?6:0);(!C||Sn<C.score)&&(C={x:Be+At.x,y:Ue+At.y,score:Sn})}return C?{parent:te,x:Math.round(C.x),y:Math.round(C.y)}:null},[Bn,xn]),Zo=b.useCallback((u,z)=>{const N=To(u,z,Zt);if(!N)return;const B=co(N.x,N.y,N.parent||void 0);B&&N.parent&&eo(K=>Kr(K,B,N.parent))&&Je()},[To,co,eo,Je]),io=b.useCallback((u,z)=>{const N=[...new Set(typeof u=="string"?[u]:u)],B=new Set(N),K=hn(m.current),O=N[0],W=O?K.get(O):null;if(!W||!O)return null;const te=Jo(z.node,z.rel,z.side,W.w,W.h);if(!te)return null;const pe=Vt(H.current.tree),ne=N.filter(fe=>!(typeof pe[fe]=="string"&&B.has(pe[fe])));if(!ne.length||ne.includes(te.parent))return null;const l=N.flatMap(fe=>{const Se=K.get(fe);return Se?[{anchor:fe,box:Se}]:[]});if(!l.length)return null;const g=te.x-W.x,v=te.y-W.y,E=l.map(({box:fe})=>({...fe,x:fe.x+g,y:fe.y+v})),L=[...K].filter(([fe])=>!B.has(fe)).map(([,fe])=>fe),Y=gn(m.current);Y&&L.push(Y),L.push(..._s(H.current.elements));const _=Jr(E,L,{x:g,y:v}),ie=g+_.x,C=v+_.y;return{sources:N,sourceSet:B,boxes:K,primary:O,roots:ne,moving:l,slot:te,dx:ie,dy:C}},[Jo]),Yn=b.useCallback((u,z)=>{const N=[...new Set(typeof u=="string"?[u]:u)],B=N[0];if(!B)return null;const K=new Set(N),O=48,W=Y=>Math.min(38,Math.max(18,Y*.32)),te=Vt(H.current.tree),pe=Y=>{let _=Y;const ie=new Set;for(;typeof _=="string"&&_&&!ie.has(_);){if(K.has(_))return!0;ie.add(_),_=te[_]}return!1},l=[...hn(m.current)].filter(([Y])=>!K.has(Y)&&!pe(Y)),g=gn(m.current);g&&l.push([ye,g]);let v=null;for(const[Y,_]of l){if(z.x<_.x-O||z.x>_.x+_.w+O||z.y<_.y-O||z.y>_.y+_.h+O)continue;const ie=W(_.w),C=W(_.h),fe=18,Se=[["e",Math.abs(_.x+_.w-z.x),z.x>_.x+_.w?O:ie,z.y>=_.y-fe&&z.y<=_.y+_.h+fe],["w",Math.abs(z.x-_.x),z.x<_.x?O:ie,z.y>=_.y-fe&&z.y<=_.y+_.h+fe],["s",Math.abs(_.y+_.h-z.y),z.y>_.y+_.h?O:C,z.x>=_.x-fe&&z.x<=_.x+_.w+fe],["n",Math.abs(z.y-_.y),z.y<_.y?O:C,z.x>=_.x-fe&&z.x<=_.x+_.w+fe]];for(const[Be,Ue,tt,At]of Se){if(!At||Ue>tt)continue;const Sn=Ue/Math.max(1,tt);(!v||Sn<v.score)&&(v={node:Y,side:Be,rel:Be==="e"||Be==="w"?"child":"sibling",score:Sn})}}if(!v)return null;const E={node:v.node,side:v.side,rel:v.rel};return io(N,E)?{source:B,count:N.length,...E}:null},[io]),hr=b.useCallback((u,z)=>{const N=H.current.getView(),B=io(u,z);if(!N||!B)return!1;const{sources:K,sourceSet:O,boxes:W,primary:te,roots:pe,moving:ne,slot:l,dx:g,dy:v}=B,E=Vt(H.current.tree);let L=Vt(E);for(const ie of pe)if(delete L[ie],l.parent){const C=Kr(L,ie,l.parent);if(C===L)return!1;L=C}let Y=N.state.tr;for(const ie of On(N)){const C=W.get(ie.anchor);O.has(ie.anchor)&&C&&(Y=Y.setNodeMarkup(ie.pos,void 0,{...ie.node.attrs,x:Math.round(C.x+g),y:Math.round(C.y+v)}))}const _=pe.filter(ie=>(typeof E[ie]=="string"?E[ie]:"")!==l.parent);for(const ie of _)Y=dl(Y,L,ie,l.parent);return ar(N,Y),H.current.onCommit(),_.length&&eo(C=>{let fe=Vt(C);for(const Se of pe)delete fe[Se],l.parent&&(fe=Kr(fe,Se,l.parent));return fe})&&Je(),K.length===1?P(te,{x:g,y:v}):$(ne.map(({anchor:ie})=>({anchor:ie,x:g,y:v,depth:pe.includes(ie)?1:2}))),lt(K.map(Ot)),!0},[io,eo,Je,$,P]),vo=b.useCallback((u,z)=>{const N=Vt(H.current.tree);if(N[u]===z)return;const B=Kr(N,u,z);if(B===N)return;const K=H.current.getView();let O=!1;if(K){const W=dl(K.state.tr,B,u,z);W.steps.length&&(ar(K,W),O=!0)}Ve({t:B}),O&&Je()},[Ve,Je]),jo=b.useCallback((u,z,N)=>{const B=W=>W===ye?ye:W.startsWith("c:")?nt(W):null,K=B(u),O=B(z);K&&O&&O!==ye&&!N?vo(O,K):Xe(W=>Bg(W,u,z))},[vo,Xe]),gr=b.useCallback((u,z,N)=>{Xe(B=>Kg(B,new Set(u),{fromEnd:z,toEnd:N}))},[Xe]),lo=b.useCallback(async()=>{const u=H.current.getView(),z=m.current;if(!u||!z||!n)return;const N=H.current.storedMd,B=l=>N?.(l.content)?.trim()||l.textBetween(0,l.content.size,`
49
-
50
- `),K=hn(z),O=On(u).map(l=>{const g=l.node.attrs,v=K.get(l.anchor)??{x:Number(g.x)||0,y:Number(g.y)||0,w:Number(g.w)||Zt,h:Number(g.h)||80};return{ref:l.anchor,...v,color:g.color,md:B(l.node)}}),W=[];u.state.doc.forEach(l=>{l.type.name!=="amadeusCanvasCard"&&W.push(l)});const te=gn(z),pe=W.length?N?.(So.fromArray(W))?.trim()??"":"",ne=Dx({cards:O,main:te?{...te,md:pe}:null,elements:H.current.elements,tree:H.current.tree,pages:H.current.notePages?.(),sourcePath:e});try{const l=await Px(wn,e,Lx(ne));ur({text:we("canvasstage.export.done",{path:l}),level:"success"})}catch(l){ur({text:we("canvasstage.export.failed",{e:Hl(l)}),level:"error"})}},[n,e]);b.useEffect(()=>{if(!oe||!n||ee)return;const u=()=>{lo()};return oe.current=u,()=>{oe.current===u&&(oe.current=null)}},[oe,n,ee,lo]);const wo=b.useCallback((u,z,N,B)=>{let K="";Xe(O=>(K=ms(O,"s"),[...O,B?ru(K,u,B):_g(K,u,z,N)])),K&&lt([yn(K)])},[Xe]),en=b.useCallback((u,z,N=480,B=320)=>{let K="";Xe(O=>(K=ms(O,"f"),[...O,Yg(K,u,z,N,B)])),K&&lt([yn(K)])},[Xe]),Qo=b.useCallback(u=>{const z=Bn(null),N=u.map(W=>z.get(W)).filter(W=>!!W);if(!N.length)return;const B=32,K=Math.min(...N.map(W=>W.x))-B,O=Math.min(...N.map(W=>W.y))-B;en(K,O,Math.max(...N.map(W=>W.x+W.w))+B-K,Math.max(...N.map(W=>W.y+W.h))+B-O)},[Bn,en]),Tt=b.useCallback(u=>{const z=Rn(H.current.elements),N=u.filter(O=>O.startsWith("e:")).map(O=>z.find(W=>W.id===nt(O))).filter(O=>O?.kind==="frame");if(!N.length)return u;const B=Bn(null),K=new Set(u);for(const O of N)for(const[W,te]of B)K.has(W)||te.x>=O.x&&te.y>=O.y&&te.x+te.w<=O.x+O.w&&te.y+te.h<=O.y+O.h&&K.add(W);return[...K]},[Bn]),Gt=b.useCallback((u,z)=>{const N=u.filter(ne=>ne.startsWith("e:")).map(nt),B=u.filter(ne=>ne.startsWith("c:")).map(nt),K=u.filter(ne=>ne.startsWith("t:")).map(nt),O=B.length?H.current.getView():null,W=new Set(B),te=O?On(O).filter(ne=>W.has(ne.anchor)).sort((ne,l)=>l.pos-ne.pos):[],pe=te.length>0&&(N.length>0||K.length>0||gt(B));if(pe&&pt(),K.length){const ne=Vt(H.current.tree),l=Vt(ne);let g=!1;for(const v of K)typeof l[v]<"u"&&(delete l[v],g=!0);g&&Ve({t:l},pe?{snap:!1}:void 0)}if(N.length){const ne=Po(H.current.elements),l=Fg(ne,new Set(N));l!==ne&&Ve({e:l},pe?{snap:!1}:void 0)}if(O&&te.length){let ne=O.state.tr;for(const l of te)ne=ne.delete(l.pos,l.pos+l.node.nodeSize);ar(O,ne),z?.assets!==!1&&H.current.onBlocksDeleted?.(So.from(te.map(l=>l.node).reverse())),H.current.onCommit(),pe&&Je()}lt([])},[Ve,pt,gt,Je]),uo=b.useCallback(u=>{const z=H.current.getView(),N=new Set(Tt(u).filter(_=>_!==ye&&!_.startsWith("t:"))),B=new Set([...N].filter(_=>_.startsWith("c:")).map(nt)),K=z?On(z).filter(_=>B.has(_.anchor)):[],O=new Set(K.map(_=>_.anchor)),W=Po(H.current.elements),te=_=>{const ie=_&&typeof _=="object"?_.id:null;return typeof ie=="string"&&ie?ie:null},pe=_=>!!_&&typeof _=="object"&&_.type==="connector",ne=W.filter(_=>!pe(_)&&N.has(yn(te(_)??""))),l=new Set(ne.map(te)),g=_=>{const ie=ea(_);return!!ie&&(ie.ref?O.has(ie.ref):ie.id?l.has(ie.id):!1)},v=W.filter(_=>pe(_)&&te(_)&&g(_.from)&&g(_.to)),E=Vt(H.current.tree),L=[...O].flatMap(_=>typeof E[_]=="string"&&O.has(E[_])?[[_,E[_]]]:[]);if(!K.length&&!ne.length&&!v.length)return null;const Y=[...ne,...v];return{cards:K,els:Y,tree:L,keys:[...K.map(_=>Ot(_.anchor)),...Y.map(_=>yn(te(_)))]}},[Tt]),fo=b.useCallback((u,z,N,B,K)=>{const O=H.current,W=O.getView(),te=W?.state.schema.nodes.amadeusCanvasCard,pe=W?.state.schema.nodes.paragraph;if(!W||!te||!pe)return;const ne=new Map,l=[];let g=W.state.tr;for(const Se of u){const Be=Eo(g.doc),Ue=Math.round(Se.x+B),tt=Math.round(Se.y+K);let At=null;if(Se.node&&Se.node.type===te)At=te.create({...Se.node.attrs,anchor:Be,x:Ue,y:tt},Se.node.content);else{const Sn=fl(Se.md?.trim()?O.parseMd?.(Se.md.trim())??null:null)??pe.create(null,Se.md?.trim()?W.state.schema.text(Se.md.trim()):void 0);At=te.createAndFill({anchor:Be,x:Ue,y:tt,w:Math.round(Se.w)||Zt,h:Math.round(Se.h)||0,color:typeof Se.color=="string"?Se.color:""},Sn)}At&&(g=g.insert(g.doc.content.size,At),ne.set(Se.ref,Be),l.push(Be))}const v=l.length>0;v&&(ar(W,g),l.forEach(Se=>O.onCommit(Se)));const E=Po(H.current.elements),L=new Map,Y=[],_=Se=>Se.type==="frame"?"f":Se.type==="connector"?"e":"s",ie=[];for(const Se of z){const Be=Se;if(typeof Be.id!="string"||!Be.id)continue;if(Be.type==="connector"){ie.push(Be);continue}const Ue=ms(E,_(Be));L.set(Be.id,Ue),E.push({...Be,id:Ue,...typeof Be.x=="number"?{x:Math.round(Be.x+B)}:{},...typeof Be.y=="number"?{y:Math.round(Be.y+K)}:{}}),Y.push(Ue)}const C=Se=>{const Be=ea(Se);if(!Be)return null;const Ue=Se;if(Be.ref){const tt=ne.get(Be.ref);return tt?{...Ue,ref:tt}:null}if(Be.id){const tt=L.get(Be.id);return tt?{...Ue,id:tt}:null}return null};for(const Se of ie){const Be=C(Se.from),Ue=C(Se.to);if(!Be||!Ue)continue;const tt=ms(E,"e");E.push({...Se,id:tt,from:Be,to:Ue}),Y.push(tt)}let fe=null;for(const[Se,Be]of N){const Ue=ne.get(Se),tt=ne.get(Be);if(!Ue||!tt)continue;const At=Kr(fe??Vt(H.current.tree),Ue,tt);At!==fe&&(fe=At)}(Y.length||fe)&&(Ve({...Y.length?{e:E}:{},...fe?{t:fe}:{}}),v&&Je()),lt([...l.map(Ot),...Y.map(yn)])},[Ve,Je]),Kn=b.useCallback((u,z)=>{u.clearData();const N=uo(z);if(!N)return Ia=null,u.setData("text/plain",""),null;const B=H.current.serializeMd,K=N.cards.map(ne=>B?.(ne.node.content)?.trim()||ne.node.textBetween(0,ne.node.content.size,`
51
-
52
- `)),O=N.els.flatMap(ne=>{const l=ne,g=l.type==="connector"?l.label:l.type==="frame"?l.title:l.text;return typeof g=="string"&&g.trim()?[g.trim()]:[]});u.setData("text/plain",[...K,...O].join(`
53
-
54
- `));const W=`t${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,te=N.cards.map(ne=>{const l=ne.node.attrs;return{ref:ne.anchor,x:Number(l.x)||0,y:Number(l.y)||0,w:Number(l.w)||Zt,h:Number(l.h)||0,...typeof l.color=="string"&&l.color?{color:l.color}:{}}}),pe={token:W,mds:K,cards:te,...N.els.length?{els:N.els}:{},...N.tree.length?{tree:N.tree}:{}};try{u.setData(pl,JSON.stringify(pe))}catch{}return Ia={token:W,nodes:N.cards.map(ne=>ne.node)},Yo.current=0,N},[uo]),A=b.useCallback((u,z)=>{const N=H.current.getView();if(!N)return!1;const B=Ia,K=!!B&&B.token===u.token&&(B.nodes.length===0||B.nodes[0].type===N.state.schema.nodes.amadeusCanvasCard);let O;if(K&&B)O=B.nodes.map(ne=>({ref:String(ne.attrs.anchor),x:Number(ne.attrs.x)||0,y:Number(ne.attrs.y)||0,w:Number(ne.attrs.w)||Zt,h:Number(ne.attrs.h)||0,node:ne}));else if(u.cards)O=u.cards.map((ne,l)=>({...ne,md:u.mds[l]}));else{const ne=u.mds.filter(l=>l.trim());return ne.length?(ne.forEach((l,g)=>Z.current.addCardMd(l,z,g)),!0):!1}const W=u.els??[],te=O.map(ne=>ne.x),pe=O.map(ne=>ne.y);for(const ne of W){const l=ne;typeof l.x=="number"&&typeof l.y=="number"&&(te.push(l.x),pe.push(l.y))}return te.length?(fo(O,W,u.tree??[],z.x-Math.min(...te),z.y-Math.min(...pe)),!0):!1},[fo]),F=b.useCallback(u=>{const z=uo(u);z&&fo(z.cards.map(N=>({ref:N.anchor,x:Number(N.node.attrs.x)||0,y:Number(N.node.attrs.y)||0,w:Number(N.node.attrs.w)||Zt,h:Number(N.node.attrs.h)||0,node:N.node})),z.els,z.tree,oi,oi)},[uo,fo]),ue=b.useCallback(u=>{const z=N=>{N.clipboardData&&(N.preventDefault(),N.stopImmediatePropagation(),Kn(N.clipboardData,u))};document.addEventListener("copy",z,{capture:!0,once:!0});try{document.execCommand("copy")}finally{document.removeEventListener("copy",z,{capture:!0})}m.current?.focus({preventScroll:!0})},[Kn]),xe=b.useCallback((u,z)=>{const N=H.current.getView();if(!N||u!==ye&&!u.startsWith("c:"))return;let B=null,K=null;if(u===ye)N.state.doc.forEach((O,W)=>{B==null&&O.type.name!=="amadeusCanvasCard"&&(B=Math.min(N.state.doc.content.size,W+O.nodeSize-1))}),K=O=>{const W=N.state.doc.resolve(O);for(let te=W.depth;te>0;te--)if(W.node(te).type.name==="amadeusCanvasCard")return!1;return!0};else{const O=On(N).find(W=>W.anchor===nt(u));O&&(B=Math.min(N.state.doc.content.size,O.pos+O.node.nodeSize-1),K=W=>W>O.pos&&W<O.pos+O.node.nodeSize)}if(B!=null){if(z){const O=N.posAtCoords({left:z.x,top:z.y});O&&K?.(O.pos)&&(B=O.pos)}try{N.dispatch(Us(N.state.tr.setSelection(Ne.near(N.state.doc.resolve(B),-1))))}catch{}Xn(u===ye?ye:nt(u)),N.focus()}},[]),$e=b.useCallback((u,z=!1)=>{const N=m.current;if(!N)return;const B=u===ye?gn(N):u.startsWith("c:")?hn(N).get(nt(u))??null:null;if(!B)return;const K=En(N)||1,O=N.getBoundingClientRect(),W=O.width/K,te=O.height/K,pe=Math.max(Gr,Math.min(1.5,js,W*.62/Math.max(1,B.w),te*.72/Math.max(1,B.h))),ne={z:pe,x:W/2-(B.x+B.w/2)*pe,y:te/2-(B.y+B.h/2)*pe},l={...he.current};if(Pe(),window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)he.current=ne,me(ne);else{const g=Math.hypot(ne.x-l.x,ne.y-l.y),v=Math.round(Math.max(460,Math.min(560,420+g*.12+Math.abs(ne.z-l.z)*120))),E=performance.now();zo(!0);const L=Y=>{const _=Math.min(1,(Y-E)/v),ie=_>=1?1:1-Math.exp(-8*_)*(Math.cos(6*_)+8/6*Math.sin(6*_)),C={x:l.x+(ne.x-l.x)*ie,y:l.y+(ne.y-l.y)*ie,z:l.z+(ne.z-l.z)*ie};he.current=C,me(C),_<1?Wn.current=requestAnimationFrame(L):(Wn.current=0,zo(!1))};Wn.current=requestAnimationFrame(L)}z||(Xn(null),lt([u]),N.focus({preventScroll:!0}))},[Pe]),Ae=b.useCallback(u=>{const z=m.current,N=H.current.getView();if(!z||!N)return!1;const B=Vt(H.current.tree),K=hn(z),O=new Set(K.keys()),W=ct=>Er(B,ct).filter(et=>O.has(et)).sort((et,Lt)=>(K.get(et)?.y??0)-(K.get(Lt)?.y??0)),te=[],pe=new Map,ne=new Set([u]),l=(ct,et)=>{for(const Lt of W(ct))ne.has(Lt)||(ne.add(Lt),te.push(Lt),pe.set(Lt,et+1),l(Lt,et+1))};if(l(u,0),!te.length)return!1;const g=u===ye?gn(z):K.get(u);if(!g)return!1;const v=96,E=32,L=new Map,Y=ct=>{const et=ct===u?g:K.get(ct);if(!et)return 0;const Lt=W(ct).filter(Pn=>Pn!==u&&ne.has(Pn)),bn=Lt.reduce((Pn,mn)=>Pn+Y(mn),0)+Math.max(0,Lt.length-1)*E,Ft=Math.max(et.h,bn);return L.set(ct,Ft),Ft};Y(u);const _=W(u).filter(ct=>ct!==u&&ne.has(ct)),ie=ct=>{const et=new Map,Lt=(bn,Ft,Pn)=>{const mn=W(bn).filter(Jt=>Jt!==u&&ne.has(Jt));if(!mn.length)return;const ft=mn.reduce((Jt,Nn)=>Jt+(L.get(Nn)??Y(Nn)),0)+(mn.length-1)*E;let pn=Ft.y+Ft.h/2-ft/2;for(const Jt of mn){const Nn=K.get(Jt);if(!Nn)continue;const yr=L.get(Jt)??Nn.h,Ro={x:Pn>0?Ft.x+Ft.w+v:Ft.x-v-Nn.w,y:pn+(yr-Nn.h)/2,w:Nn.w,h:Nn.h};et.set(Jt,Ro),Lt(Jt,Ro,Pn),pn+=yr+E}};for(const bn of[1,-1]){const Ft=_.filter(ft=>ct.get(ft)===bn),Pn=Ft.reduce((ft,pn)=>ft+(L.get(pn)??Y(pn)),0)+Math.max(0,Ft.length-1)*E;let mn=g.y+g.h/2-Pn/2;for(const ft of Ft){const pn=K.get(ft);if(!pn)continue;const Jt=L.get(ft)??pn.h,Nn={x:bn>0?g.x+g.w+v:g.x-v-pn.w,y:mn+(Jt-pn.h)/2,w:pn.w,h:pn.h};et.set(ft,Nn),Lt(ft,Nn,bn),mn+=Jt+E}}return et},C=[],fe=new Set,Se=ct=>{const et=ct.join(",");fe.has(et)||(fe.add(et),C.push(new Map(_.map((Lt,bn)=>[Lt,ct[bn]]))))};if(_.length<=9)for(let ct=0;ct<2**_.length;ct++)Se(_.map((et,Lt)=>ct&1<<Lt?-1:1));else Se(_.map((ct,et)=>et%2?-1:1)),Se(_.map((ct,et)=>et<Math.ceil(_.length/2)?1:-1)),Se(_.map(()=>1)),Se(_.map(()=>-1));Se(_.map(ct=>(K.get(ct)?.x??g.x)<g.x?-1:1));const Be=Bn(null),Ue=new Set(te.map(Ot)),tt=[...Be].filter(([ct])=>!Ue.has(ct)).map(([,ct])=>Pa(ct,24));let At=null;for(const ct of C){const et=_.filter(ft=>ct.get(ft)===-1).length;if(_.length>1&&(et===0||et===_.length))continue;const Lt=ie(ct),bn=[...Lt.values()],Ft=Math.min(...bn.map(ft=>ft.y)),Pn=Math.max(...bn.map(ft=>ft.y+ft.h)),mn=new Set([0]);for(let ft=1;ft<=20;ft++)mn.add(ft*72),mn.add(-ft*72);for(const ft of tt)mn.add(Math.ceil(ft.y+ft.h+12-Ft)),mn.add(Math.floor(ft.y-12-Pn));tt.length&&(mn.add(Math.ceil(Math.max(...tt.map(ft=>ft.y+ft.h))+12-Ft)),mn.add(Math.floor(Math.min(...tt.map(ft=>ft.y))-12-Pn)));for(const ft of[...mn].sort((pn,Jt)=>Math.abs(pn)-Math.abs(Jt))){const pn=new Map([...Lt].map(([Jn,to])=>[Jn,{...to,y:to.y+ft}]));let Jt=0;for(const Jn of pn.values())for(const to of tt)hl(Pa(Jn,12),to)&&Jt++;const Nn=Jn=>{const to=_.filter(mo=>ct.get(mo)===Jn).map(mo=>L.get(mo)??0);return to.reduce((mo,er)=>mo+er,0)+Math.max(0,to.length-1)*E},yr=Nn(1),Ro=Nn(-1),Ms=[...pn].reduce((Jn,[to,mo])=>{const er=K.get(to);return Jn+(er?Math.hypot(mo.x-er.x,mo.y-er.y):0)},0),Yt=Jt*1e6+Math.abs(ft)+Math.max(yr,Ro)*.18+Math.abs(yr-Ro)*.04+Ms*.002+et*2;(!At||Yt<At.score)&&(At={plan:pn,score:Yt})}}if(!At)return!1;const Sn=new Map([...At.plan].map(([ct,et])=>[ct,{x:Math.round(et.x),y:Math.round(et.y)}])),un=[...Sn].flatMap(([ct,et])=>{const Lt=K.get(ct);return Lt?[{anchor:ct,x:et.x-Lt.x,y:et.y-Lt.y,depth:pe.get(ct)??1}]:[]});return Cr(N,Sn),$(un),H.current.onCommit(),z.focus({preventScroll:!0}),!0},[Bn,$]);b.useEffect(()=>{const u=m.current;!n||!u||document.activeElement&&u.contains(document.activeElement)||u.focus({preventScroll:!0})},[n]);const Z=b.useRef({mutate:Xe,writeFm:Ve,mergePair:Je,pushFmCheckpoint:pt,treeTouches:gt,removeSel:Gt,editText:Ao,boxesNow:Bn,fit:Qt,zoomBy:Gn,addCardAt:co,addShapeAt:wo,addFrame:en,addRelated:Zo,attachHit:Yn,applyAttach:hr,setNodeParent:vo,expandFrames:Tt,enterNodeEdit:xe,focusNode:$e,arrangeChildren:Ae,stopArrangeMotion:y,stopFocusMotion:Pe,dropFilesAt:Go,addCardMd:No,writeClip:Kn,pastePayload:A,linkNodes:jo});Z.current={mutate:Xe,writeFm:Ve,mergePair:Je,pushFmCheckpoint:pt,treeTouches:gt,removeSel:Gt,editText:Ao,boxesNow:Bn,fit:Qt,zoomBy:Gn,addCardAt:co,addShapeAt:wo,addFrame:en,addRelated:Zo,attachHit:Yn,applyAttach:hr,setNodeParent:vo,expandFrames:Tt,enterNodeEdit:xe,focusNode:$e,arrangeChildren:Ae,stopArrangeMotion:y,stopFocusMotion:Pe,dropFilesAt:Go,addCardMd:No,writeClip:Kn,pastePayload:A,linkNodes:jo},b.useEffect(()=>{const u=m.current;if(!n||!u||typeof ResizeObserver>"u")return;const z=new Set,N=new WeakMap;let B=0,K=!1;const O=()=>{if(B=0,K)return;const l=nn.current,g=H.current.getView();if(!l||!g)return;const v=hn(u),E=l===ye?gn(u):v.get(l);if(!E)return;const L=[...v].filter(([C,fe])=>C!==l&&hl(Pa(E,18),fe));if(!L.length)return;const Y=new Map(v),_=new Map,ie=[];for(const[C,fe]of L){const Se=[...Y].filter(([Sn])=>Sn!==C).map(([,Sn])=>Sn),Be=gn(u);Be&&l!==ye&&Se.push(Be),Se.push(..._s(H.current.elements));const Ue={x:fe.x+fe.w/2-(E.x+E.w/2),y:fe.y+fe.h/2-(E.y+E.h/2)},tt=Jr([fe],Se,Ue);if(!tt.x&&!tt.y)continue;const At={...fe,x:fe.x+tt.x,y:fe.y+tt.y};Y.set(C,At),_.set(C,{x:Math.round(At.x),y:Math.round(At.y)}),ie.push({anchor:C,x:tt.x,y:tt.y,depth:1})}_.size&&(K=!0,Cr(g,_,!1),$(ie),H.current.onCommit(),requestAnimationFrame(()=>{K=!1}))},W=()=>{window.clearTimeout(B),B=window.setTimeout(O,90)},te=new ResizeObserver(l=>{for(const g of l){const v=g.target,E={w:v.offsetWidth,h:v.offsetHeight},L=N.get(v);if(N.set(v,E),L&&(L.w!==E.w||L.h!==E.h)){const Y=v.classList.contains("amx-ucard")?v.dataset.anchor:ye;Y&&Y===nn.current&&W()}}}),pe=()=>{const l=new Set(u.querySelectorAll(".amx-ucard")),g=u.querySelector(".ProseMirror");g&&l.add(g);for(const v of l)z.has(v)||(z.add(v),N.set(v,{w:v.offsetWidth,h:v.offsetHeight}),te.observe(v,{box:"border-box"}));for(const v of[...z])l.has(v)||(z.delete(v),te.unobserve(v))};pe();const ne=new MutationObserver(pe);return ne.observe(u,{subtree:!0,childList:!0}),()=>{window.clearTimeout(B),ne.disconnect(),te.disconnect()}},[n,e,$]),b.useEffect(()=>{if(!n||X<=0)return;Q.current=!1;let u=0;const z=requestAnimationFrame(()=>{u=requestAnimationFrame(()=>{const N=H.current.getView();if(!N)return;const{$from:B}=N.state.selection;let K=ye;for(let O=B.depth;O>0;O--){const W=B.node(O);if(W.type.name==="amadeusCanvasCard"){K=Ot(String(W.attrs.anchor));break}}lt([K]),Xn(K===ye?ye:nt(K)),Z.current.focusNode(K,!0),N.focus()})});return()=>{cancelAnimationFrame(z),cancelAnimationFrame(u)}},[n,X]),b.useEffect(()=>{const u=m.current;if(!u||!n)return;const z=()=>H.current.getView(),N=x=>H.current.onCommit(x),B=()=>u.focus({preventScroll:!0}),K=`s${++Kx}`;u.dataset.amxDragscope=K;const O=document.createElement("style");document.head.appendChild(O);let W=[],te=0;const pe=(x,j=!1)=>`left:${x.x}px!important;top:${x.y}px!important;${j&&"w"in x&&"h"in x?`width:${x.w}px!important;height:${x.h}px!important;`:""}`,ne=`.amx-stage[data-amx-dragscope="${K}"] .unified-gutter{visibility:hidden!important;pointer-events:none!important}`,l=(x,j)=>{const ae=[];for(const Ce of x){const be=CSS.escape(Ce.anchor);ae.push(`.amx-stage[data-amx-dragscope="${K}"] .amx-ucard[data-anchor="${be}"]{${Ce.decl}}`),ae.push(`.amx-stage[data-amx-dragscope="${K}"] .amx-el-selbox[data-anchor="${be}"]{${pe(Ce.selection)}}`)}j&&ae.push(`.amx-stage[data-amx-dragscope="${K}"] .amx-el-selbox[data-main-sel]{${pe(j)}}`),ae.push(ne),O.textContent=ae.join(`
55
- `)},g=(x,j,ae)=>{const Ce=x===ye?`.amx-stage[data-amx-dragscope="${K}"] .ProseMirror:not(.unified-embed .ProseMirror){${j}}`:`.amx-stage[data-amx-dragscope="${K}"] .amx-ucard[data-anchor="${CSS.escape(x)}"]{${j}}`,be=x===ye?`.amx-stage[data-amx-dragscope="${K}"] .amx-el-selbox[data-main-sel]{${pe(ae,!0)}}`:`.amx-stage[data-amx-dragscope="${K}"] .amx-el-selbox[data-anchor="${CSS.escape(x)}"]{${pe(ae,!0)}}`;O.textContent=`${Ce}
56
- ${be}
57
- ${ne}`},v="cursor:grabbing;opacity:.94;box-shadow:0 12px 32px rgb(0 0 0 / 24%);z-index:1;",E=()=>{O.textContent=""},L=()=>{cancelAnimationFrame(te),te=0;for(const x of W)x.cancel();W=[]},Y=(x,j,ae,Ce="amx-card-repel")=>{const be=Math.hypot(ae.x,ae.y);if(be<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;L();const Le=Math.round(Math.max(340,Math.min(480,320+be*.55))),De=[{transform:`translate(${-ae.x}px, ${-ae.y}px) scale(1.012)`,opacity:.94,boxShadow:"0 12px 32px rgb(0 0 0 / 24%)",offset:0,easing:"cubic-bezier(0.16, 0.84, 0.24, 1)"},{transform:`translate(${ae.x*.06}px, ${ae.y*.06}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-ae.x*.015}px, ${-ae.y*.015}px) scale(1.001)`,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:.9,easing:"ease-out"},{transform:"translate(0, 0) scale(1)",opacity:1,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:1}];te=requestAnimationFrame(()=>{te=0;const st=x.map(xt=>u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(xt)}"]`)).filter(xt=>!!xt);if(j){const xt=u.querySelector(".ProseMirror");xt&&st.push(xt)}for(const xt of st){const je=xt.animate(De,{duration:Le,fill:"none"});je.id=Ce,W.push(je);const qe=()=>{W=W.filter(bt=>bt!==je)};je.addEventListener("finish",qe,{once:!0}),je.addEventListener("cancel",qe,{once:!0})}})},_=(x,j,ae)=>{Math.max(Math.abs(j.x-ae.x),Math.abs(j.y-ae.y),Math.abs(j.w-ae.w),Math.abs(j.h-ae.h))<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(L(),te=requestAnimationFrame(()=>{te=0;const be=x===ye?u.querySelector(".ProseMirror"):u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(x)}"]`);if(!be)return;const Le=x===ye?{marginLeft:`${j.x}px`,marginTop:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`},De=x===ye?{marginLeft:`${ae.x}px`,marginTop:`${ae.y}px`,width:`${ae.w}px`,height:`${ae.h}px`}:{left:`${ae.x}px`,top:`${ae.y}px`,width:`${ae.w}px`,height:`${ae.h}px`},st=be.animate([Le,De],{duration:220,easing:"cubic-bezier(0.2, 0.78, 0.28, 1)",fill:"none"});st.id="amx-card-snap",W.push(st);const xt=()=>{W=W.filter(je=>je!==st)};st.addEventListener("finish",xt,{once:!0}),st.addEventListener("cancel",xt,{once:!0})}))},ie=x=>{if(x.target?.closest?.(".amx-stage-minimap"))return;Z.current.stopFocusMotion(),x.preventDefault();const{x:j,y:ae,z:Ce}=he.current,be=En(u)||1;if(x.metaKey||x.ctrlKey){const Le=x.ctrlKey&&!x.metaKey?Ox:1,De=Math.max(Gr,Math.min(js,Ce*Math.exp(-x.deltaY*Le/300))),st=u.getBoundingClientRect(),xt=(x.clientX-st.left)/be,je=(x.clientY-st.top)/be;me({z:De,x:xt-(xt-j)*De/Ce,y:je-(je-ae)*De/Ce})}else{const Le=x.shiftKey&&!x.deltaX?x.deltaY:x.deltaX,De=x.shiftKey?0:x.deltaY;me({z:Ce,x:j-Le/be,y:ae-De/be})}};u.addEventListener("wheel",ie,{passive:!1});let C=null,fe=-1;const Se=x=>{fe=x;try{u.setPointerCapture(x)}catch{}},Be=x=>{try{u.hasPointerCapture(x)&&u.releasePointerCapture(x)}catch{}},Ue=()=>em/(he.current.z*(En(u)||1)),tt=(x,j,ae)=>{const Ce=[];for(const[Le,De]of hn(u))x.has(Le)||Ce.push(De);const be=j?null:gn(u);be&&Ce.push(be);for(const[Le,De]of Nr(Rn(H.current.elements),null))ae.has(Le)||Ce.push(De);return Ce},At=(x,j)=>{const ae=document.elementFromPoint(x,j);if(!ae||!u.contains(ae))return null;const Ce=ae.closest(ss);if(Ce?.dataset.el)return yn(Ce.dataset.el);const be=ae.closest("[data-card-grip]");if(be?.dataset.cardGrip)return be.dataset.cardGrip===ye?ye:Ot(be.dataset.cardGrip);const Le=ae.closest(".amx-ucard");return Le?.dataset.anchor?Ot(Le.dataset.anchor):ae.closest(".ProseMirror")?ye:null},Sn=x=>x===u||x.classList.contains("amx-stage-inner")||x.classList.contains("amx-el-layer"),un=new Map;let ct=null,et=null,Lt=0,bn=null,Ft=ri;const Pn=()=>{Jn();const x=C;C=null,x&&x.kind!=="pan"&&tr(x)},mn=()=>{const[x,j]=[...un.keys()],ae=un.get(x),Ce=un.get(j);if(!ae||!Ce)return null;const be=En(u)||1,Le=u.getBoundingClientRect();return{x:((ae.x+Ce.x)/2-Le.left)/be,y:((ae.y+Ce.y)/2-Le.top)/be,d:Math.hypot(ae.x-Ce.x,ae.y-Ce.y)/be,ids:`${x}/${j}`}},ft=()=>{const x=mn();if(!x)return;const{x:j,y:ae,z:Ce}=he.current;et={d0:Math.max(1,x.d),z0:Ce,sx:(x.x-j)/Ce,sy:(x.y-ae)/Ce,ids:x.ids}},pn=()=>{const x=mn();if(!x||!et)return;if(x.ids!==et.ids){ft();return}const j=Math.max(Gr,Math.min(js,et.z0*x.d/et.d0));me({z:j,x:x.x-et.sx*j,y:x.y-et.sy*j})},Jt=()=>{Lt&&window.clearTimeout(Lt),Lt=0,bn=null},Nn=x=>{const j=x.target,{clientX:ae,clientY:Ce}=x;bn={x:ae,y:Ce},Lt=window.setTimeout(()=>{Lt=0,bn=null,Nc(j,ae,Ce)==="open"&&Pn()},Yf)},yr=x=>{const j=z(),ae=j?On(j).map(De=>De.anchor):[],Ce=new Set([...ae,ye]),be=Vt(H.current.tree);return[x===ye?ye:Ot(x),...ae.filter(De=>su(be,De,x,Ce)).map(Ot)]},Ro=(x,j)=>{const ae=Ct.current;if(j.shiftKey||j.metaKey||j.ctrlKey){const Ce=j.shiftKey&&(x===ye||x.startsWith("c:"))?yr(x===ye?ye:nt(x)):[x],be=ae.includes(x)?ae.filter(Le=>!Ce.includes(Le)):[...ae,...Ce.filter(Le=>!ae.includes(Le))];return lt(be),be.includes(x)?be:null}return ae.includes(x)?ae:(lt([x]),[x])},Ms=x=>{It(null);const j=x.target;if(j.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;if(L(),Z.current.stopArrangeMotion(),Z.current.stopFocusMotion(),x.pointerType==="touch"){if(un.set(x.pointerId,{x:x.clientX,y:x.clientY}),Jt(),un.size>=2){x.preventDefault(),Pn(),ft();return}Nn(x)}if(et)return;Ft=x.pointerType==="touch"?si/(he.current.z*(En(u)||1)):ri;const ae=x.button===1;if(x.button!==0&&!ae)return;const Ce=jt.current,be=Pt(x.clientX,x.clientY);if(ht.current){if(j.closest(`${il}, .wikilink`))return;const kt=performance.now(),Nt=ct;if(ct=x.pointerType==="mouse"?{t:kt,x:x.clientX,y:x.clientY}:null,Nt&&kt-Nt.t<500&&Math.hypot(x.clientX-Nt.x,x.clientY-Nt.y)<6&&j.closest(".ProseMirror"))return;x.preventDefault(),C={kind:"pan",x0:x.clientX,y0:x.clientY,vx:he.current.x,vy:he.current.y},Se(x.pointerId);return}const Le=nn.current,De=$n.current.held;De&&($n.current.used=!0);const st=Ce==="pan"||x.altKey||ae||De,xt=Ce!=="select"&&!st,je=Le===ye?!!j.closest(".ProseMirror")&&!j.closest(".amx-ucard"):!!j.closest(`.amx-ucard[data-anchor="${CSS.escape(Le??"")}"]`);if(Le&&!st&&(xt||!je)&&Xn(null),st){x.preventDefault(),C={kind:"pan",x0:x.clientX,y0:x.clientY,vx:he.current.x,vy:he.current.y},Se(x.pointerId);return}if(La.has(Ce)){x.preventDefault(),C={kind:"create",tool:Ce,x0:be.x,y0:be.y,x1:be.x,y1:be.y},Se(x.pointerId);return}if(x.pointerType==="touch"&&(Ce==="card"||as[Ce])){x.preventDefault(),C={kind:"create",tool:Ce,x0:be.x,y0:be.y,x1:be.x,y1:be.y},Se(x.pointerId);return}if(as[Ce]){x.preventDefault(),Z.current.addShapeAt(as[Ce],be.x,be.y),Mt("select"),B();return}if(Ce==="card"){x.preventDefault();const kt=Z.current.addCardAt(be.x-Zt/2,be.y-24);Mt("select"),kt||B();return}const qe=j.closest("[data-grip]"),bt=j.closest("[data-card-grip][data-card-edge]"),Bt=j.closest(ss),vt=j.closest(".amx-ucard"),Tn=j.closest(".ProseMirror"),po=!vt&&!Bt&&!!Tn&&j===Tn,ko=!vt&&!Bt&&!!Tn&&j!==Tn,xr=!!vt&&j===vt,Fn=vt?.dataset.anchor??null;if(Ce==="select"&&bt?.dataset.cardGrip&&bt.dataset.cardEdge){const kt=bt.dataset.cardGrip,Nt=kt===ye,on=Nt?gn(u):hn(u).get(kt),rn=Nt?null:z(),qn=rn?On(rn).find(no=>no.anchor===kt):null;on&&(Nt||qn)&&(x.preventDefault(),B(),lt([Nt?ye:Ot(kt)]),C={kind:"card-size",key:kt,edge:bt.dataset.cardEdge,b0:on,h0:Nt?Number(H.current.main.h)||0:Number(qn.node.attrs.h)||0,x0:be.x,y0:be.y,dx:0,dy:0,next:on},Se(x.pointerId));return}const br=Ce==="select"?j.closest("[data-link-from]"):null;if(br?.dataset.linkFrom){x.preventDefault(),B(),C={kind:"link",from:br.dataset.linkFrom,x0:be.x,y0:be.y},Se(x.pointerId);return}const nr=Ce==="select"?j.closest("[data-conn-end]"):null;if(nr?.dataset.connEnd&&nr.dataset.el){const kt=Rn(H.current.elements).find(rn=>rn.id===nr.dataset.el),Nt=nr.dataset.connEnd==="from"?"from":"to",on=kt?.kind==="connector"?kr(Nt==="from"?kt.to:kt.from):null;x.preventDefault(),B(),kt&&on&&(C={kind:"reconnect",id:kt.id,end:Nt,fixed:on,x0:be.x,y0:be.y},Se(x.pointerId));return}const Dr=j.closest(il)?Fn??(Tn?ye:null):null;if(Ce==="select"&&Dr){Xn(Dr);return}const Lr=vt&&Fn?Fn:ko?ye:null;Ce==="select"&&Lr&&nn.current!==Lr&&Bx(j,x.clientX)&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("canvasstage.toast.needEdit")}}));const wt=x.pointerType==="touch"&&Ce==="select"?Bt?.dataset.el?yn(Bt.dataset.el):Fn?Ot(Fn):!vt&&Tn?ye:null:null;if(wt&&!Ct.current.includes(wt)&&nn.current!==(Fn??ye)){x.preventDefault(),C={kind:"pan",x0:x.clientX,y0:x.clientY,vx:he.current.x,vy:he.current.y,tapKey:wt},Se(x.pointerId);return}if(vt&&Fn&&!xr&&Ce==="select"){if(nn.current===Fn)return;x.preventDefault(),B();const kt=x.shiftKey||x.metaKey||x.ctrlKey,Nt=Ot(Fn),on=Ro(Nt,x);if(!on)return;const rn=on,qn=[];for(const no of rn){if(!no.startsWith("c:"))continue;const ho=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(nt(no))}"]`);ho&&qn.push({anchor:nt(no),ox:Number(ho.dataset.x)||0,oy:Number(ho.dataset.y)||0})}C={kind:"move",cards:qn,ids:new Set(rn),hit:Nt,x0:be.x,y0:be.y,dx:0,dy:0,mainStart:null,mainEl:null,additive:kt},Se(x.pointerId);return}if(ko&&Ce==="select"){if(nn.current===ye)return;x.preventDefault(),B();const kt=x.shiftKey||x.metaKey||x.ctrlKey,Nt=Ro(ye,x);if(!Nt)return;const on=Nt,rn=[];for(const qn of on){if(!qn.startsWith("c:"))continue;const no=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(nt(qn))}"]`);no&&rn.push({anchor:nt(qn),ox:Number(no.dataset.x)||0,oy:Number(no.dataset.y)||0})}C={kind:"move",cards:rn,ids:new Set(on),hit:ye,x0:be.x,y0:be.y,dx:0,dy:0,mainStart:{x:H.current.main.x,y:H.current.main.y},mainEl:Tn,additive:kt},Se(x.pointerId);return}const Co=Bt?.dataset.el?yn(Bt.dataset.el):Fn?Ot(Fn):po?ye:null;if(Ce==="conn"){x.preventDefault(),B();const kt=Co??(!vt&&!Bt&&j.closest(".ProseMirror")?ye:null);if(!kt){zn(null);return}const Nt=Xt.current;Nt?(Z.current.linkNodes(Nt,kt,x.shiftKey),zn(null),Mt("select")):zn(kt);return}const As=j.closest("[data-add]");if(As?.dataset.add&&As.dataset.node){x.preventDefault(),B(),Z.current.addRelated(As.dataset.node,As.dataset.add==="child"?"child":"sibling");return}if(qe?.dataset.grip){x.preventDefault();const kt=Nr(Rn(H.current.elements),null).get(qe.dataset.grip);if(!kt)return;C={kind:"size",id:qe.dataset.grip,corner:qe.dataset.corner??"se",b0:kt,dx:0,dy:0,dw:0,dh:0},Se(x.pointerId);return}if(Co){x.preventDefault(),B();const kt=x.shiftKey||x.metaKey||x.ctrlKey,Nt=Ro(Co,x);if(!Nt)return;const on=Nt;if(xr&&on.length===1&&vt.dataset.anchor){const ho=vt.getBoundingClientRect(),Lo=cl*he.current.z*(En(u)||1);if(x.clientX>=ho.right-Lo){const la=hn(u).get(vt.dataset.anchor),_c=On(z()).find(Fu=>Fu.anchor===vt.dataset.anchor);if(!la||!_c)return;C={kind:"card-size",key:vt.dataset.anchor,edge:"e",b0:la,h0:Number(_c.node.attrs.h)||0,x0:be.x,y0:be.y,dx:0,dy:0,next:la},Se(x.pointerId);return}}if(Co===ye&&on.length===1&&Tn){const ho=Tn.getBoundingClientRect();if(x.clientX>ho.right-cl*he.current.z*(En(u)||1)){const Lo=gn(u);if(!Lo)return;C={kind:"card-size",key:ye,edge:"e",b0:Lo,h0:Number(H.current.main.h)||0,x0:be.x,y0:be.y,dx:0,dy:0,next:Lo},Se(x.pointerId);return}}const rn=Z.current.expandFrames(on),qn=[];for(const ho of rn){if(!ho.startsWith("c:"))continue;const Lo=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(nt(ho))}"]`);Lo&&qn.push({anchor:nt(ho),ox:Number(Lo.dataset.x)||0,oy:Number(Lo.dataset.y)||0})}const no=rn.includes(ye);C={kind:"move",cards:qn,ids:new Set(rn),hit:Co,x0:be.x,y0:be.y,dx:0,dy:0,mainStart:no?{x:H.current.main.x,y:H.current.main.y}:null,mainEl:no?u.querySelector(".ProseMirror"):null,additive:kt,growSel:rn.length>Nt.length?[...rn]:void 0},Se(x.pointerId);return}if(!Sn(j))return;const Ns=Z.current.boxesNow(null),ca=Rn(H.current.elements).find(kt=>{if(kt.kind!=="connector")return!1;const Nt=kr(kt.from),on=kr(kt.to),rn=Nt?Ns.get(Nt):null,qn=on?Ns.get(on):null;return!!rn&&!!qn&&Ps(rn,qn,be,8/he.current.z)}),Oc=ca?null:bu(H.current.tree).find(([kt,Nt])=>{const on=Ns.get(Ot(kt)),rn=Ns.get(Nt===ye?ye:Ot(Nt));return!!on&&!!rn&&Ps(rn,on,be,8/he.current.z)});if(x.preventDefault(),B(),ca){lt([yn(ca.id)]);return}if(Oc){lt([xu(Oc[0])]);return}const ia=x.shiftKey||x.metaKey||x.ctrlKey,Pu=ia?[...Ct.current]:[];if(ia||lt([]),x.pointerType==="touch"){C={kind:"pan",x0:x.clientX,y0:x.clientY,vx:he.current.x,vy:he.current.y},Se(x.pointerId);return}C={kind:"marquee",x0:be.x,y0:be.y,additive:ia,base:Pu},Se(x.pointerId)},Yt={raf:0,t:0,x:0,y:0,id:-1,type:"mouse"},Jn=()=>{Yt.raf&&cancelAnimationFrame(Yt.raf),Yt.raf=0},to=()=>{const x=u.getBoundingClientRect();return{left:Math.max(x.left,0),top:Math.max(x.top,0),right:Math.min(x.right,window.innerWidth),bottom:Math.min(x.bottom,window.innerHeight)}},mo=x=>ht.current||et?!1:C?C.kind!=="pan"&&C.live===!0:jt.current==="conn"&&!!Xt.current&&!x?.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"),er=x=>{Yt.raf=0;const j=document.elementFromPoint(Yt.x,Yt.y);if(!mo(j))return;const{vx:ae,vy:Ce}=ii(to(),Yt.x,Yt.y);if(!ae&&!Ce)return;const be=Math.min(.05,Math.max(0,(x-Yt.t)/1e3));Yt.t=x;const Le=En(u)||1,De={...he.current,x:he.current.x-ae*be/Le,y:he.current.y-Ce*be/Le};he.current=De,me(De),zc({clientX:Yt.x,clientY:Yt.y,pointerId:Yt.id,pointerType:Yt.type,target:j??u}),Yt.raf=requestAnimationFrame(er)},Du=x=>{if(C&&fe!==x.pointerId)return;Yt.x=x.clientX,Yt.y=x.clientY,Yt.id=x.pointerId,Yt.type=x.pointerType;const{vx:j,vy:ae}=mo(x.target)?ii(to(),x.clientX,x.clientY):{vx:0,vy:0};if(!j&&!ae){Jn();return}Yt.raf||(Yt.t=performance.now(),Yt.raf=requestAnimationFrame(er))},Ec=()=>{C||Jn()},Mc=x=>{zc(x),Du(x)},zc=x=>{if(x.pointerType==="touch"&&(un.has(x.pointerId)&&un.set(x.pointerId,{x:x.clientX,y:x.clientY}),bn&&Math.hypot(x.clientX-bn.x,x.clientY-bn.y)>Xf&&Jt()),et){pn();return}if(C&&fe!==x.pointerId)return;if(!C&&jt.current==="conn"&&Xt.current){const je=x.target,qe=je.closest?.(ss),bt=je.closest?.(".amx-ucard");let Bt=qe?.dataset.el?yn(qe.dataset.el):bt?.dataset.anchor?Ot(bt.dataset.anchor):!bt&&je.closest?.(".ProseMirror")?ye:null;Bt===Xt.current&&(Bt=null);const vt=Pt(x.clientX,x.clientY);V({x:vt.x,y:vt.y,over:Bt});return}if(!C)return;const j=En(u)||1;if(C.kind==="pan"){me({...he.current,x:C.vx+(x.clientX-C.x0)/j,y:C.vy+(x.clientY-C.y0)/j});return}const ae=Pt(x.clientX,x.clientY);if(C.kind==="link"||C.kind==="reconnect"){(Math.abs(ae.x-C.x0)>Ft||Math.abs(ae.y-C.y0)>Ft)&&(C.live=!0);const je=C.kind==="link"?C.from:C.fixed,qe=At(x.clientX,x.clientY);se({from:je,x:ae.x,y:ae.y,over:qe===je?null:qe});return}if(C.kind==="card-size"){C.dx=ae.x-C.x0,C.dy=ae.y-C.y0;const je=C.key===ye;let qe=ul(C.b0,C.edge,C.dx,C.dy,!1,je?ja:Hs);if((Math.abs(qe.x-C.b0.x)>Ft||Math.abs(qe.y-C.b0.y)>Ft||Math.abs(qe.w-C.b0.w)>Ft||Math.abs(qe.h-C.b0.h)>Ft)&&(C.live=!0),C.gx=!1,C.gy=!1,ve.current&&C.live){C.others||(C.others=tt(new Set(je?[]:[C.key]),je,new Set));const bt=Uf(qe,C.edge,C.others,Ue(),je?ja:Hs,wu);qe=bt.box,C.gx=bt.guides.v.length>0,C.gy=bt.guides.h.length>0,Fe(C.gx||C.gy?ci(qe,C.others,bt.guides,1/he.current.z):null)}else Fe(null);C.next=qe,g(C.key,je?`margin-left:${qe.x}px;margin-top:${qe.y}px;width:${qe.w}px;height:${qe.h}px;${v}`:`left:${qe.x}px;top:${qe.y}px;width:${qe.w}px;height:${qe.h}px;${v}`,qe),Cn({move:{ids:new Set([je?ye:Ot(C.key)]),dx:0,dy:0},size:null});return}if(C.kind==="size"){const je=C.b0,qe=C.corner.includes("e"),bt=C.corner.includes("s"),Bt=Math.max(sr,Math.round(qe?ae.x-je.x:je.x+je.w-ae.x)),vt=Math.max(sr,Math.round(bt?ae.y-je.y:je.y+je.h-ae.y));C.dx=qe?0:je.w-Bt,C.dy=bt?0:je.h-vt,C.dw=Bt-je.w,C.dh=vt-je.h,(Math.abs(C.dw)>Ft||Math.abs(C.dh)>Ft)&&(C.live=!0),Cn({move:null,size:{id:C.id,dx:C.dx,dy:C.dy,dw:C.dw,dh:C.dh}});return}if(C.kind==="create"){C.x1=ae.x,C.y1=ae.y,(Math.abs(C.x1-C.x0)>Ft||Math.abs(C.y1-C.y0)>Ft)&&(C.live=!0),La.has(C.tool)&&Ln({x:Math.min(C.x0,ae.x),y:Math.min(C.y0,ae.y),w:Math.abs(ae.x-C.x0),h:Math.abs(ae.y-C.y0)});return}if(C.kind==="marquee"){C.live=!0;const je={x:Math.min(C.x0,ae.x),y:Math.min(C.y0,ae.y),w:Math.abs(ae.x-C.x0),h:Math.abs(ae.y-C.y0)};Ln(je);const qe=[];for(const[bt,Bt]of Z.current.boxesNow(null))el(je,Bt)&&qe.push(bt);lt(C.additive?[...new Set([...C.base,...qe])]:qe);return}if(C.dx=Math.round(ae.x-C.x0),C.dy=Math.round(ae.y-C.y0),(Math.abs(C.dx)>Ft||Math.abs(C.dy)>Ft)&&(C.live=!0),!C.align){const je=new Set(C.cards.map(po=>po.anchor)),qe=new Set([...C.ids].filter(po=>po.startsWith("e:")).map(nt)),bt=hn(u),Bt=Nr(Rn(H.current.elements),null),vt=[];for(const po of je){const ko=bt.get(po);ko&&vt.push(ko)}const Tn=C.mainStart?gn(u):null;Tn&&vt.push(Tn);for(const po of qe){const ko=Bt.get(po);ko&&vt.push(ko)}C.align={base:Gf(vt),others:tt(je,!!C.mainStart,qe)}}C.gx=!1,C.gy=!1;const Ce=C.align.base;if(ve.current&&C.live&&Ce){const je=Jf({...Ce,x:Ce.x+C.dx,y:Ce.y+C.dy},C.align.others,Ue());C.dx+=Math.round(je.dx),C.dy+=Math.round(je.dy),C.gx=je.guides.v.length>0,C.gy=je.guides.h.length>0,Fe(C.gx||C.gy?ci({...Ce,x:Ce.x+C.dx,y:Ce.y+C.dy},C.align.others,je.guides,1/he.current.z):null)}else Fe(null);C.live&&C.kind==="move"&&C.growSel&&(lt(C.growSel),C.growSel=void 0);const{dx:be,dy:Le}=C;l(C.cards.map(je=>({anchor:je.anchor,decl:`left:${je.ox+be}px;top:${je.oy+Le}px;${v}`,selection:{x:je.ox+be,y:je.oy+Le}})),C.mainStart?{x:C.mainStart.x+be,y:C.mainStart.y+Le}:void 0),C.mainStart&&C.mainEl&&(C.mainEl.style.marginLeft=`${C.mainStart.x+C.dx}px`,C.mainEl.style.marginTop=`${C.mainStart.y+C.dy}px`),Cn({move:{ids:C.ids,dx:C.dx,dy:C.dy},size:null});const De=nt(C.hit),st=!C.mainStart&&C.cards.length>0&&C.ids.size===C.cards.length?C.cards.map(je=>je.anchor).sort((je,qe)=>+(qe===De)-+(je===De)):[],xt=st.length&&C.live?Z.current.attachHit(st,ae):null;xo(xt)},tr=x=>{E(),x.kind==="move"&&x.mainEl&&(x.mainEl.style.marginLeft="",x.mainEl.style.marginTop=""),Cn(null),Ln(null),xo(null),Fe(null),se(null)},$c=x=>{if(x.pointerType==="touch"&&(un.delete(x.pointerId),Jt(),et)){un.size===0&&(et=null),Be(x.pointerId),C=null;return}if(C&&fe!==x.pointerId){Be(x.pointerId);return}Jn();const j=C;if(C=null,Be(x.pointerId),!j)return;if(j.kind==="pan"){j.tapKey&&Math.hypot(x.clientX-j.x0,x.clientY-j.y0)<si&&lt([j.tapKey]);return}if(j.kind==="link"||j.kind==="reconnect"){if(tr(j),!j.live)return;const Le=j.kind==="link"?j.from:j.fixed,De=At(x.clientX,x.clientY);if(!De||De===Le)return;j.kind==="reconnect"?Z.current.mutate(st=>Vg(st,j.id,j.end,De)):Z.current.linkNodes(Le,De,x.shiftKey);return}if(j.kind==="create"){const Le=Math.abs(j.x1-j.x0),De=Math.abs(j.y1-j.y0),st=La.has(j.tool)&&Le>=sr&&De>=sr?{x:Math.min(j.x0,j.x1),y:Math.min(j.y0,j.y1),w:Le,h:De}:null;let xt=null;j.tool==="frame"?st?Z.current.addFrame(st.x,st.y,st.w,st.h):Z.current.addFrame(j.x0-_i.w/2,j.y0-_i.h/2):j.tool==="card"?xt=Z.current.addCardAt(j.x0-Zt/2,j.y0-24):as[j.tool]&&Z.current.addShapeAt(as[j.tool],j.x0,j.y0,st??void 0),Mt("select"),xt||B(),tr(j);return}if(!j.live){j.kind==="move"&&j.ids.size>1&&!j.additive&&lt([j.hit]),tr(j);return}const ae=z();if(j.kind==="marquee"){const Le=Pt(x.clientX,x.clientY),De={x:Math.min(j.x0,Le.x),y:Math.min(j.y0,Le.y),w:Math.abs(Le.x-j.x0),h:Math.abs(Le.y-j.y0)},st=[];for(const[xt,je]of Z.current.boxesNow(null))el(De,je)&&st.push(xt);lt(j.additive?[...new Set([...j.base,...st])]:st),tr(j);return}if(!ae){tr(j);return}let Ce=null,be=null;if(j.kind==="card-size"){const Le=j.key===ye;let De=k.current?ul(j.b0,j.edge,j.dx,j.dy,!0,Le?ja:Hs):j.next;j.gx&&(De={...De,x:j.next.x,w:j.next.w}),j.gy&&(De={...De,y:j.next.y,h:j.next.h});const st=j.edge.includes("n")||j.edge.includes("s");Le?Z.current.writeFm({m:{...H.current.main,x:Math.round(De.x),y:Math.round(De.y),w:Math.round(De.w),...st?{h:Math.round(De.h)}:{}}}):Cr(ae,new Map([[j.key,{x:Math.round(De.x),y:Math.round(De.y),w:Math.round(De.w),h:st?Math.round(De.h):j.h0}]])),k.current&&(be={key:j.key,from:j.next,to:De})}else if(j.kind==="size"){const Le=Rn(H.current.elements).find(De=>De.id===j.id);Le&&Le.kind!=="connector"&&Z.current.mutate(De=>ou(De,j.id,{x:Math.round(Le.x+j.dx),y:Math.round(Le.y+j.dy),w:Math.max(sr,Math.round(Le.w+j.dw)),h:Math.max(sr,Math.round(Le.h+j.dh))}))}else{const Le=!j.mainStart&&j.cards.length>0&&j.ids.size===j.cards.length?j.cards.map(wt=>wt.anchor).sort((wt,Co)=>+(Co===nt(j.hit))-+(wt===nt(j.hit))):[],De=Le.length?Z.current.attachHit(Le,Pt(x.clientX,x.clientY)):null;if(Le.length&&De&&Z.current.applyAttach(Le,De)){tr(j);return}const st=hn(u),xt=[];for(const wt of j.cards){const Co=st.get(wt.anchor);Co&&xt.push(Co)}if(j.mainStart){const wt=gn(u);wt&&xt.push(wt)}const je=new Set(j.cards.map(wt=>wt.anchor)),qe=[...st].filter(([wt])=>!je.has(wt)).map(([,wt])=>wt);if(!j.mainStart){const wt=gn(u);wt&&qe.push(wt)}const bt=(j.hit.startsWith("c:")?j.cards.find(wt=>wt.anchor===nt(j.hit)):null)??j.cards[0]??(j.mainStart?{ox:j.mainStart.x,oy:j.mainStart.y}:null),Bt=j.gx?j.dx:k.current&&bt?ai(bt.ox+j.dx)-bt.ox:j.dx,vt=j.gy?j.dy:k.current&&bt?ai(bt.oy+j.dy)-bt.oy:j.dy,Tn=Bt-j.dx,po=vt-j.dy,ko=xt.map(wt=>({...wt,x:wt.x+Tn,y:wt.y+po})),xr=Jr(ko,qe,{x:Bt,y:vt}),Fn=Bt+xr.x,br=vt+xr.y,nr={x:Fn-j.dx,y:br-j.dy};(nr.x||nr.y)&&(Ce={anchors:j.cards.map(wt=>wt.anchor),main:!!j.mainStart,push:nr,repel:!!(xr.x||xr.y)}),j.cards.length&&Cr(ae,new Map(j.cards.map(wt=>[wt.anchor,{x:Math.round(wt.ox+Fn),y:Math.round(wt.oy+br)}])));const Dr=new Set([...j.ids].filter(wt=>wt.startsWith("e:")).map(nt)),Lr=j.mainStart?{...H.current.main,x:Math.round(j.mainStart.x+Fn),y:Math.round(j.mainStart.y+br)}:void 0;(Dr.size||Lr)&&(Z.current.writeFm({...Dr.size?{e:Oi(Po(H.current.elements),Dr,Fn,br)}:{},...Lr?{m:Lr}:{}}),j.cards.length&&Z.current.mergePair())}tr(j),be&&_(be.key,be.from,be.to),Ce&&Y(Ce.anchors,Ce.main,Ce.push,Ce.repel?"amx-card-repel":"amx-card-snap"),N()},Ac=x=>{if(ht.current)return;const j=document.elementFromPoint(x.clientX,x.clientY)??x.target;if(j.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;const ae=j.closest(".amx-ucard"),Ce=!ae&&!!j.closest(".ProseMirror"),be=ae?.dataset.anchor?Ot(ae.dataset.anchor):Ce?ye:null;if(be){if(nn.current===(be===ye?ye:nt(be)))return;x.preventDefault(),x.stopPropagation(),Z.current.enterNodeEdit(be,{x:x.clientX,y:x.clientY}),yp()&&Z.current.focusNode(be,!0);return}const Le=j.closest(ss);if(Le?.dataset.el){x.preventDefault(),x.stopPropagation();const je=Rn(H.current.elements).find(qe=>qe.id===Le.dataset.el);je&&Z.current.editText(je.id,Ra(je),Da(je));return}if(!Sn(j))return;const De=Pt(x.clientX,x.clientY),st=Z.current.boxesNow(null),xt=Rn(H.current.elements).find(je=>{if(je.kind!=="connector")return!1;const qe=kr(je.from),bt=kr(je.to),Bt=qe?st.get(qe):null,vt=bt?st.get(bt):null;return!!Bt&&!!vt&&Ps(Bt,vt,De,8/he.current.z)});x.preventDefault(),xt?Z.current.editText(xt.id,"label",we("canvasstage.textTitle.connector")):Z.current.addCardAt(De.x-Zt/2,De.y-24)},Nc=(x,j,ae)=>{if(ht.current||x.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"))return"skip";const Ce=x.closest(ss),be=x.closest(".amx-ucard"),Le=!be&&!Ce&&!!x.closest(".ProseMirror");if(be?.dataset.anchor&&nn.current===be.dataset.anchor||Le&&nn.current===ye)return"native";let De=Ce?.dataset.el?yn(Ce.dataset.el):be?.dataset.anchor?Ot(be.dataset.anchor):Le?ye:null;if(!De&&!Sn(x))return"skip";if(!De){const st=Pt(j,ae),xt=Z.current.boxesNow(null),je=Rn(H.current.elements).find(qe=>{if(qe.kind!=="connector")return!1;const bt=kr(qe.from),Bt=kr(qe.to),vt=bt?xt.get(bt):null,Tn=Bt?xt.get(Bt):null;return!!vt&&!!Tn&&Ps(vt,Tn,st,8/he.current.z)});je&&(De=yn(je.id))}return De&&!Ct.current.includes(De)&&lt([De]),It({x:j,y:ae,key:De,at:Pt(j,ae)}),"open"},Tc=x=>{const j=Nc(x.target,x.clientX,x.clientY);j!=="skip"&&(x.stopPropagation(),j==="open"&&x.preventDefault())},Lu=x=>{const j=x.target,ae=nn.current;return!ae||!j?!1:ae===ye?!!j.closest(".ProseMirror")&&!j.closest(".amx-ucard"):!!j.closest(`.amx-ucard[data-anchor="${CSS.escape(ae)}"]`)};let aa=!1;const jc=x=>{x.target?.closest?.(".ProseMirror")&&(aa=!0)},Rr=()=>{aa=!1},Rc=x=>{const j=x.dataTransfer,ae=j?Array.from(j.types):[];return aa||z()?.dragging?null:H.current.saveFile&&ae.includes("Files")?"files":Qf(j)?"refs":Lu(x)?null:ae.includes("text/uri-list")||ae.includes("text/plain")?"text":null},Dc=x=>{if(ht.current)return;const j=z();if(Rc(x)){x.preventDefault(),x.dataTransfer&&(x.dataTransfer.dropEffect="copy"),u.classList.add("amx-dropzone");return}!j?.dragging||x.target?.closest?.(".ProseMirror")||(x.preventDefault(),x.dataTransfer&&(x.dataTransfer.dropEffect="move"),u.classList.add("amx-dropzone"))},Do=()=>u.classList.remove("amx-dropzone"),Lc=x=>{u.contains(x.relatedTarget)||Do()},Ic=x=>{if(Do(),ht.current){x.preventDefault();return}const j=z(),ae=Rc(x);if(ae){x.preventDefault(),x.stopPropagation();const Le=Pt(x.clientX,x.clientY),De=Array.from(x.dataTransfer?.files??[]);if(ae==="files"&&De.length){Z.current.dropFilesAt(De,Le);return}if(ae==="refs"){const xt=H.current.path;Hf(x.dataTransfer).forEach((je,qe)=>Z.current.addCardMd(ml(je,x.altKey||je.kind==="note"&&je.path===xt),Le,qe));return}const st=x.dataTransfer?.getData("text/uri-list")||x.dataTransfer?.getData("text/plain")||"";Z.current.addCardMd(st,Le);return}if(!j?.dragging||x.target?.closest?.(".ProseMirror"))return;x.preventDefault(),x.stopPropagation();const Ce=Pt(x.clientX,x.clientY),be=j.state.selection;if(be instanceof Ee&&be.node.type.name==="amadeusCanvasCard")Cr(j,new Map([[String(be.node.attrs.anchor),{x:Math.round(Ce.x),y:Math.round(Ce.y)}]])),N();else{const Le=Cu(j,Math.round(Ce.x),Math.round(Ce.y));Le&&N(Le)}j.dragging=null,j.dom.dataset.dragging="false"},Iu=()=>{const x=u.getBoundingClientRect();return Pt(x.left+x.width/2,x.top+x.height/2)},zs=x=>{if(nn.current||!x.clipboardData||!z())return;const j=Ct.current;if(!j.length)return;x.preventDefault();const ae=Z.current.writeClip(x.clipboardData,j);x.type==="cut"&&ae&&Z.current.removeSel(ae.keys,{assets:!1})},Pc=x=>{if(ht.current||nn.current||!x.clipboardData)return;const j=Array.from(x.clipboardData.files??[]),ae=x.clipboardData.getData("text/plain")??"",Ce=Hx(x.clipboardData.getData(pl));if(!j.length&&!ae.trim()&&!Ce)return;x.preventDefault();const be=Yo.current++,Le=Iu(),De={x:Le.x+be*24,y:Le.y+be*24};if(j.length){Z.current.dropFilesAt(j,De);return}Ce&&Z.current.pastePayload(Ce,De)||ae.trim()&&Z.current.addCardMd(ae,De)},$s=x=>{x.pointerType==="touch"&&(un.delete(x.pointerId),Jt(),et&&un.size===0&&(et=null))};window.addEventListener("pointerup",$s,!0),window.addEventListener("pointercancel",$s,!0);const Fc=x=>{x.pointerType==="touch"&&(un.delete(x.pointerId),Jt(),et&&un.size===0&&(et=null)),Be(x.pointerId),!(C&&fe!==x.pointerId)&&Pn()};return u.addEventListener("pointerdown",Ms),u.addEventListener("pointermove",Mc),u.addEventListener("pointerleave",Ec),u.addEventListener("pointerup",$c),u.addEventListener("pointercancel",Fc),u.addEventListener("dblclick",Ac),u.addEventListener("contextmenu",Tc,!0),u.addEventListener("dragover",Dc),u.addEventListener("dragleave",Lc),u.addEventListener("drop",Ic),u.addEventListener("dragstart",jc),window.addEventListener("dragend",Do),window.addEventListener("drop",Do),window.addEventListener("blur",Do),window.addEventListener("dragend",Rr),window.addEventListener("drop",Rr),window.addEventListener("blur",Rr),u.addEventListener("copy",zs,!0),u.addEventListener("cut",zs,!0),u.addEventListener("paste",Pc,!0),()=>{window.removeEventListener("pointerup",$s,!0),window.removeEventListener("pointercancel",$s,!0),Jt(),O.remove(),L(),delete u.dataset.amxDragscope,u.removeEventListener("wheel",ie),u.removeEventListener("pointerdown",Ms),u.removeEventListener("pointermove",Mc),u.removeEventListener("pointerleave",Ec),Jn(),u.removeEventListener("pointerup",$c),u.removeEventListener("pointercancel",Fc),u.removeEventListener("dblclick",Ac),u.removeEventListener("contextmenu",Tc,!0),u.removeEventListener("dragover",Dc),u.removeEventListener("dragleave",Lc),u.removeEventListener("drop",Ic),u.removeEventListener("dragstart",jc),window.removeEventListener("dragend",Do),window.removeEventListener("drop",Do),window.removeEventListener("blur",Do),window.removeEventListener("dragend",Rr),window.removeEventListener("drop",Rr),window.removeEventListener("blur",Rr),Do(),u.removeEventListener("copy",zs,!0),u.removeEventListener("cut",zs,!0),u.removeEventListener("paste",Pc,!0)}},[n,Pt]),b.useEffect(()=>{if(!n)return;const u=()=>{$n.current={held:!1,used:!1},Mo(!1)},z=N=>{if(N.code!=="Space"||!$n.current.held)return;const{used:B}=$n.current;u(),N.preventDefault();const K=m.current,O=N.target;if(B||ht.current||!K||!O||!K.contains(O)||O.closest(".ProseMirror"))return;const W=Ct.current;W.length===1&&(W[0].startsWith("c:")||W[0]===ye)&&Z.current.enterNodeEdit(W[0])};return window.addEventListener("keyup",z,!0),window.addEventListener("blur",u),()=>{window.removeEventListener("keyup",z,!0),window.removeEventListener("blur",u),u()}},[n]);const Ze=u=>{if(!n||ee||u.nativeEvent.isComposing)return;const z=u.target;if((u.metaKey||u.ctrlKey)&&(u.key==="z"||u.key==="Z")){if(z.tagName==="INPUT"||z.tagName==="TEXTAREA")return;u.preventDefault(),u.stopPropagation(),Un(u.shiftKey?"redo":"undo");return}if((u.metaKey||u.ctrlKey)&&!u.shiftKey&&!u.altKey&&(u.key==="y"||u.key==="Y")){if(z.tagName==="INPUT"||z.tagName==="TEXTAREA")return;u.preventDefault(),u.stopPropagation(),Un("redo");return}if(u.key!=="Escape")return;const N=nn.current;!N||!z.closest(".ProseMirror")||(u.preventDefault(),u.stopPropagation(),Xn(null),lt([N===ye?ye:Ot(N)]),m.current?.focus({preventScroll:!0}))},Qe=u=>{if(!n)return;const z=u.target;if(z.closest(".ProseMirror")||z.tagName==="INPUT"||z.tagName==="TEXTAREA")return;const N=u.metaKey||u.ctrlKey;if(!u.altKey&&(N?u.key==="="||u.key==="+"||u.key==="-"||u.key==="0":u.shiftKey&&u.code==="Digit1")){u.preventDefault(),N?u.key==="0"?Gn(1/he.current.z):Gn(u.key==="-"?1/1.2:1.2):Qt();return}if(!ee){if(N&&(u.key==="a"||u.key==="A")){u.preventDefault(),lt([...hn(m.current).keys()].map(Ot).concat(Me.filter(B=>B.kind!=="connector").map(B=>yn(B.id)),[ye]));return}if(N&&!u.shiftKey&&!u.altKey&&(u.key==="d"||u.key==="D")){u.preventDefault(),ot.length&&F(ot);return}if(u.key==="Escape"){u.preventDefault(),at?It(null):Kt?zn(null):it!=="select"?Mt("select"):lt([]);return}if(u.code==="Space"&&!N&&!u.target?.closest?.("button")){u.preventDefault(),!u.repeat&&!$n.current.held&&($n.current={held:!0,used:!1},Mo(!0));return}if(ot.length){if(u.key==="Delete"||u.key==="Backspace"){u.preventDefault(),Gt(ot);return}if((u.key==="Enter"||u.key==="F2")&&ot.length===1&&ot[0].startsWith("e:")){u.preventDefault();const B=Me.find(K=>K.id===nt(ot[0]));B&&Ao(B.id,Ra(B),Da(B));return}if((u.key==="Tab"||u.key==="Enter")&&ot.length===1&&(ot[0].startsWith("c:")||ot[0]===ye)){u.preventDefault(),Zo(ot[0]===ye?ye:nt(ot[0]),u.key==="Tab"?"child":"sibling");return}if(u.key.startsWith("Arrow")){u.preventDefault();const B=qf(k.current,u.shiftKey),K=u.key==="ArrowLeft"?-B:u.key==="ArrowRight"?B:0,O=u.key==="ArrowUp"?-B:u.key==="ArrowDown"?B:0;if(!K&&!O)return;const W=o(),te=Tt(ot),pe=te.filter(g=>g.startsWith("c:")).map(nt);if(W&&pe.length){const g=hn(m.current);Cr(W,new Map(pe.map(v=>{const E=g.get(v);return[v,{x:Math.round((E?.x??0)+K),y:Math.round((E?.y??0)+O)}]}))),R()}const ne=new Set(te.filter(g=>g.startsWith("e:")).map(nt)),l=te.includes(ye)?{...r,x:Math.round(r.x+K),y:Math.round(r.y+O)}:void 0;(ne.size||l)&&(Ve({...ne.size?{e:Oi(Po(c),ne,K,O)}:{},...l?{m:l}:{}}),pe.length&&Je())}}}},zt=[{id:"select",icon:f.jsx(Of,{size:14}),title:ke("canvasstage.tool.select")},{id:"pan",icon:f.jsx(xp,{size:14}),title:ke("canvasstage.tool.pan")},{id:"card",icon:f.jsx(Wa,{size:14}),title:ke("canvasstage.tool.card")},{id:"rect",icon:f.jsx(_f,{size:14}),title:ke("canvasstage.shape.rect")},{id:"ellipse",icon:f.jsx(Bf,{size:14}),title:ke("canvasstage.shape.ellipse")},{id:"text",icon:f.jsx(bp,{size:14}),title:ke("canvasstage.shape.text")},{id:"frame",icon:f.jsx(vp,{size:14}),title:ke("canvasstage.tool.frame")},{id:"conn",icon:f.jsx(yh,{size:14}),title:ke("canvasstage.tool.conn")}],ut=Kf(de),Rt=(at?.key?.startsWith("e:")?Me.find(u=>u.id===nt(at.key))??null:null)?.kind==="connector",$t=at?.key?(ot.length?ot:[at.key]).filter(u=>u.startsWith("c:")||u.startsWith("e:")):[],ln=(()=>{if(!$t.length)return null;const u=at?o():null,z=Po(c),N=K=>{if(K.startsWith("c:"))return String((u?On(u).find(W=>W.anchor===nt(K))?.node.attrs.color:"")??"");const O=z.find(W=>!!W&&typeof W=="object"&&W.id===nt(K));return typeof O?.color=="string"?O.color:""},B=N($t[0]);return $t.every(K=>N(K)===B)?B:null})(),Dt=ln&&ln.startsWith("#")?ln:null,Vn=Rt?(ot.length?ot:[at.key]).filter(u=>u.startsWith("e:")).map(nt).filter(u=>Me.some(z=>z.kind==="connector"&&z.id===u)):[],Hn=(()=>{const u=Vn.map(z=>{const N=Me.find(O=>O.kind==="connector"&&O.id===z),B=N?.kind==="connector"?N.fromEnd??ps.fromEnd:ps.fromEnd,K=N?.kind==="connector"?N.toEnd??ps.toEnd:ps.toEnd;return al.find(O=>O.from===B&&O.to===K)?.id??null});return u.length&&u.every(z=>z===u[0])?u[0]:null})();return f.jsxs("div",{className:`amx-stage${n?"":" amx-stage-off"}${n?` amx-tool-${ee?"pan":it}`:""}${ee?" amx-stage-ro":""}${n&&Qn?" amx-space-pan":""}${Uo?" amx-vp-focus":""}${n&&Te&&de.z<=sn?" amx-stage-overview":""}`,ref:m,tabIndex:-1,onKeyDownCapture:Ze,onKeyDown:Qe,children:[n?f.jsx("div",{className:"amx-stage-grid","aria-hidden":"true",style:ut}):null,f.jsxs("div",{className:"amx-stage-inner",style:n?{transform:`translate(${de.x}px, ${de.y}px) scale(${de.z})`,"--amx-main-x":`${r.x}px`,"--amx-main-y":`${r.y}px`,"--amx-main-w":`${r.w}px`,"--amx-main-h":typeof r.h=="number"&&r.h>0?`${r.h}px`:"auto"}:void 0,children:[n?f.jsx(zx,{elements:c,hostRef:m,documentKey:e,sel:G,editing:Zn,tree:a,ghost:Xo,marquee:An,attach:yo,overviewScale:Te&&de.z<=sn?de.z:null,mainAutoHeight:!(typeof r.h=="number"&&r.h>0),preview:U??(Kt&&D?{from:Kt,x:D.x,y:D.y,over:D.over}:null),guides:Ye}):null,Ge]}),n&&ze?f.jsx(qx,{hostRef:m,vp:de,elements:c,ghost:Xo,onCenter:$o}):null,n&&!ee?f.jsx("div",{className:"amx-stage-tools",role:"toolbar","aria-label":ke("canvasstage.toolbar.label"),children:zt.map(u=>f.jsx("button",{type:"button",title:u.title,className:it===u.id?"on":"","aria-pressed":it===u.id,onClick:()=>{Mt(u.id),zn(null),m.current?.focus({preventScroll:!0})},children:u.icon},u.id))}):null,n&&Kt?f.jsx("div",{className:"amx-stage-hint",children:ke("canvasstage.conn.hint")}):null,n?f.jsx(ap,{zoom:de.z,onZoomBy:Gn,onFit:Qt,snap:ce,onSnap:u=>{mt(u),m.current?.focus({preventScroll:!0})},mini:ze,onMini:u=>{He(u),gp(u),m.current?.focus({preventScroll:!0})},extra:f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:J?"is-on":"","aria-pressed":J,"aria-label":ke("canvasstage.guides.label"),title:ke(J?"canvasstage.guides.off":"canvasstage.guides.on"),onClick:()=>{const u=!J;ve.current=u,le(u),pp(u),m.current?.focus({preventScroll:!0})},children:f.jsx(jp,{size:12})}),f.jsx("button",{type:"button",className:Te?"is-on":"","aria-pressed":Te,"aria-label":ke("canvasstage.overview.label"),title:ke(Te?"canvasstage.overview.off":"canvasstage.overview.on"),onClick:()=>{const u=!Te;dt(u),hp(u),m.current?.focus({preventScroll:!0})},children:f.jsx(Zp,{size:12})})]})}):null,n&&at?f.jsx(cr,{children:f.jsx(Yr,{className:"ctx-menu amx-canvas-menu",x:at.x,y:at.y,onClick:u=>u.stopPropagation(),children:at.key?f.jsxs(f.Fragment,{children:[$t.length>0&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"amx-color-row",role:"group","aria-label":ke("canvasstage.color.label"),children:[Fx.map(u=>f.jsx("button",{type:"button",className:"amx-color-swatch","data-swatch":u.v||"none",title:ke(u.nameKey),"aria-label":ke(u.nameKey),"aria-pressed":ln===u.v,style:u.v?{"--amx-swatch":`var(--amx-cv-${u.v})`}:void 0,onClick:()=>{const z=$t;It(null),In(z,u.v||null)}},u.v||"none")),f.jsxs("label",{className:"amx-color-swatch is-custom",title:ke("canvasstage.color.custom"),"data-active":Dt?"":void 0,style:Dt?{"--amx-swatch":Dt}:void 0,children:[Dt?null:f.jsx(Vf,{size:11}),f.jsx("input",{type:"color","aria-label":ke("canvasstage.color.custom"),defaultValue:Dt??"#7b5ce5",ref:u=>{if(!u)return;const z=$t;u.onchange=()=>{It(null),In(z,u.value)}}})]})]}),f.jsx("div",{className:"ctx-separator"})]}),Rt&&Vn.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-color-row amx-end-row",role:"group","aria-label":ke("canvasstage.ends.label"),children:al.map(u=>f.jsx("button",{type:"button",className:"amx-end-btn","data-ends":u.id,title:ke(u.nameKey),"aria-label":ke(u.nameKey),"aria-pressed":Hn===u.id,onClick:()=>{const z=Vn;It(null),gr(z,u.from,u.to),m.current?.focus({preventScroll:!0})},children:u.icon},u.id))}),f.jsx("div",{className:"ctx-separator"})]}),at.key.startsWith("e:")&&f.jsx("button",{onClick:()=>{const u=Me.find(z=>z.id===nt(at.key));It(null),u&&Ao(u.id,Ra(u),Da(u))},children:ke("canvasstage.menu.editText")}),at.key!==ye&&!Rt&&f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:()=>{const u=ot.length?ot:[at.key];It(null),ue(u)},children:ke("canvasstage.menu.copy")}),f.jsx("button",{onClick:()=>{const u=ot.length?ot:[at.key];It(null),F(u),m.current?.focus({preventScroll:!0})},children:ke("canvasstage.menu.duplicate")})]}),!Rt&&f.jsx("button",{onClick:()=>{zn(at.key),Mt("conn"),It(null)},children:ke("canvasstage.menu.connectTo")}),(at.key===ye||at.key.startsWith("c:"))&&Er(Vt(a),at.key===ye?ye:nt(at.key)).length>0&&f.jsx("button",{onClick:()=>{const u=at.key===ye?ye:nt(at.key);It(null),Ae(u)},children:ke("canvasstage.menu.arrange")}),!Rt&&f.jsx("button",{onClick:()=>{const u=ot.length?ot:[at.key];It(null),Qo(u)},children:ke("canvasstage.menu.groupFrame")}),at.key.startsWith("c:")&&f.jsx("button",{onClick:()=>{const u=nt(at.key);It(null);const z=o();if(!z)return;const N=gt([u]);N&&pt(),Su(z,u),lt([]),R(),N&&Je()},children:ke("canvasstage.menu.unwrap")}),at.key!==ye&&f.jsx("button",{className:"danger",onClick:()=>{const u=ot.length?ot:[at.key];It(null),Gt(u)},children:ke("canvasstage.menu.delete")})]}):f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:()=>{const u=at.at;It(null),co(u.x-Zt/2,u.y-24)},children:ke("canvasstage.menu.newCard")}),q&&f.jsx("button",{onClick:()=>{const u=at.at;It(null),ao(u)},children:ke("canvasstage.menu.addNote")}),f.jsx("button",{onClick:()=>{const u=at.at;It(null),wo("rect",u.x,u.y)},children:ke("canvasstage.shape.rect")}),f.jsx("button",{onClick:()=>{const u=at.at;It(null),wo("ellipse",u.x,u.y)},children:ke("canvasstage.shape.ellipse")}),f.jsx("button",{onClick:()=>{const u=at.at;It(null),wo("text",u.x,u.y)},children:ke("canvasstage.shape.text")}),f.jsx("button",{onClick:()=>{const u=at.at;It(null),en(u.x,u.y)},children:"Frame"}),f.jsx("button",{onClick:()=>{It(null),Qt()},children:ke("canvasstage.menu.fit")}),f.jsx("div",{className:"ctx-separator"}),f.jsx("button",{onClick:()=>{It(null),lo()},children:ke("canvasstage.menu.exportCanvas")})]})})}):null,n&&!ee&&bo&&q?f.jsx(nu,{pages:q(),exclude:e,onClose:()=>{ao(null),m.current?.focus({preventScroll:!0})},onPick:u=>{const z=bo;ao(null),m.current?.focus({preventScroll:!0}),No(ml({kind:"note",path:u}),z)}}):null]})}function Cu(e,t,n,o){const r=e.state.selection,s=e.state.schema.nodes.amadeusCanvasCard;if(!s||!(r instanceof Ee))return null;const c=r.node;if(!c.isBlock||["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(c.type.name))return null;const a=e.state.doc.resolve(r.from);for(let R=a.depth;R>=1;R--)if(a.node(R).type.name==="amadeusColumnCell")return null;const i=Eo(e.state.doc),d=s.createAndFill({anchor:i,x:t,y:n,w:Zt,h:0},c);if(!d)return null;const p=a.depth>=1?a.node(a.depth):null,h=e.state.schema.nodes.paragraph;let M=p?.type.name==="amadeusCanvasCard"&&p.childCount===1&&h?e.state.tr.replaceWith(r.from,r.to,h.create()):e.state.tr.delete(r.from,r.to);return M=M.insert(o?ku(M.doc,o.tree,o.parent):M.doc.content.size,d),ar(e,M.scrollIntoView()),i}function Su(e,t){const o=On(e).find(p=>p.anchor===t);if(!o)return;const{paragraph:r,html:s}=e.state.schema.nodes,c=[];o.node.forEach(p=>c.push(p));const i=[...t&&r&&s?[r.create(null,s.create({value:`<!-- a ${t} -->`}))]:[],...c.length?c:[r.create()]],d=e.state.tr.delete(o.pos,o.pos+o.node.nodeSize);ar(e,d.insert(o.pos,i).scrollIntoView())}const Yx={heading:["id"]};function Sc(e,t){if(e.type!==t.type)return!1;const n=Yx[e.type.name];if(!n)return e.sameMarkup(t);const o={...t.attrs};for(const r of n)o[r]=e.attrs[r];return e.hasMarkup(t.type,o,t.marks)}function Wr(e,t){if(e===t)return!0;if(!Sc(e,t))return!1;if(e.isText)return e.text===t.text;if(e.childCount!==t.childCount)return!1;for(let n=0;n<e.childCount;n++)if(!Wr(e.child(n),t.child(n)))return!1;return!0}function Eu(e,t,n){for(let o=0;;o++){if(o===e.childCount||o===t.childCount)return e.childCount===t.childCount?null:n;const r=e.child(o),s=t.child(o);if(r===s){n+=r.nodeSize;continue}if(!Sc(r,s))return n;if(r.isText&&r.text!==s.text){const c=r.text??"",a=s.text??"";for(let i=0;c[i]===a[i];i++)n++;return n}if(r.content.size||s.content.size){const c=Eu(r.content,s.content,n+1);if(c!=null)return c}n+=r.nodeSize}}function Mu(e,t,n,o){for(let r=e.childCount,s=t.childCount;;){if(r===0||s===0)return r===s?null:{a:n,b:o};const c=e.child(--r),a=t.child(--s),i=c.nodeSize;if(c===a){n-=i,o-=i;continue}if(!Sc(c,a))return{a:n,b:o};if(c.isText&&c.text!==a.text){const d=c.text??"",p=a.text??"";let h=0;const M=Math.min(d.length,p.length);for(;h<M&&d[d.length-h-1]===p[p.length-h-1];)h++,n--,o--;return{a:n,b:o}}if(c.content.size||a.content.size){const d=Mu(c.content,a.content,n-1,o-1);if(d)return d}n-=i,o-=i}}const Xx=25e4;function Ux(e,t){const n=e.childCount,o=t.childCount;let r=0;for(;r<n&&r<o&&Wr(e.child(r),t.child(r));)r++;let s=0;for(;s<n-r&&s<o-r&&Wr(e.child(n-1-s),t.child(o-1-s));)s++;const c=r,a=n-s,i=r,d=o-s,p=a-c,h=d-i;if(p===0&&h===0)return[];if(p===0||h===0||p*h>Xx)return[[c,a,i,d]];const M=h+1,R=new Uint32Array((p+1)*M);for(let ee=p-1;ee>=0;ee--)for(let q=h-1;q>=0;q--)R[ee*M+q]=Wr(e.child(c+ee),t.child(i+q))?R[(ee+1)*M+q+1]+1:Math.max(R[(ee+1)*M+q],R[ee*M+q+1]);const T=[];let w=0,S=0,I=0,X=0;for(;w<p&&S<h;)Wr(e.child(c+w),t.child(i+S))&&R[w*M+S]===R[(w+1)*M+S+1]+1?((I<w||X<S)&&T.push([c+I,c+w,i+X,i+S]),w++,S++,I=w,X=S):R[(w+1)*M+S]>=R[w*M+S+1]?w++:S++;return(I<p||X<h)&&T.push([c+I,a,i+X,d]),T}const Bs=(e,t)=>{let n=0;for(let o=0;o<t;o++)n+=e.child(o).nodeSize;return n};function Gx(e,t){const n=[];for(const[o,r,s,c]of Ux(e,t)){const a=Bs(e,o),i=Bs(t,s),d=e.content.cut(a,Bs(e,r)),p=t.content.cut(i,Bs(t,c)),h=Eu(d,p,a);if(h==null)continue;const M=Mu(d,p,a+d.size,i+p.size);let R=M?M.a:a+d.size,T=M?M.b:i+p.size;const w=i-a;R<h&&(T+=h-R,R=h),T-w<h&&(R+=h-(T-w),T=h+w),n.push({from:h,to:R,slice:t.slice(h+w,T)})}return n}function Jx(e,t,n){const o=Gx(e.doc,t);if(!o.length)return null;const r=e.selection,s=e.tr;for(let c=o.length-1;c>=0;c--){const a=o[c];s.replace(a.from,a.to,a.slice)}if(n)for(const c of o)n.push({from:s.mapping.map(c.from,-1),to:s.mapping.map(c.to,1),old:e.doc.slice(c.from,c.to),oldFrom:c.from,oldTo:c.to});if(r instanceof Ne){const c=d=>{for(const p of o)if(d>p.from&&d<p.to){const h=s.mapping.map(p.from,-1);return Math.min(h+(d-p.from),h+p.slice.size,s.doc.content.size)}return null},a=c(r.head),i=c(r.anchor);if(a!=null||i!=null){const d=a??s.mapping.map(r.head),p=i??s.mapping.map(r.anchor);try{s.setSelection(Ne.between(s.doc.resolve(p),s.doc.resolve(d)))}catch{}}}return s.setMeta("addToHistory",!1)}const oo=new Dn("amAgentChanges");let gl=0;function zu(e,t){if(e.childCount!==t.childCount)return!1;for(let n=0;n<e.childCount;n++)if(!Wr(e.child(n),t.child(n)))return!1;return!0}function Zx(e,t,n,o){const r=[...e.map(a=>({a:a.from,b:a.to,e:a})),...t.map(a=>({a:a.oldFrom,b:a.oldTo,c:a}))].sort((a,i)=>a.a-i.a||a.b-i.b),s=[];for(const a of r){const i=s[s.length-1],d=i?Math.max(...i.map(p=>p.b)):-1;i&&a.a<=d&&(a.c||i.some(p=>p.c))?i.push(a):s.push([a])}const c=[];for(const a of s){const i=a.filter(ee=>ee.e).map(ee=>ee.e),d=a.filter(ee=>ee.c).map(ee=>ee.c);if(!d.length){for(const ee of i){const q=o.mapping.map(ee.from,1);c.push({...ee,from:q,to:Math.max(q,o.mapping.map(ee.to,-1))})}continue}if(!i.length&&d.length===1){const ee=d[0];c.push({id:++gl,from:ee.from,to:ee.to,old:ee.old,after:o.doc.slice(ee.from,ee.to).content});continue}const p=Math.min(...a.map(ee=>ee.a)),h=Math.max(...a.map(ee=>ee.b)),M=i.filter(ee=>zu(n.slice(ee.from,ee.to).content,ee.after)),R=i.reduce((ee,q)=>ee+(q.locked??0)+(M.includes(q)?0:1),0),T=new nm(n);for(const ee of[...M].sort((q,oe)=>oe.from-q.from))T.replace(ee.from,ee.to,ee.old);const w=T.mapping.map(p,-1),S=T.mapping.map(h,1),I=o.mapping.map(p,-1),X=o.mapping.map(h,1);c.push({id:++gl,from:I,to:X,old:T.doc.slice(w,S),after:o.doc.slice(I,X).content,...R?{locked:R}:{}})}return c.sort((a,i)=>a.from-i.from)}function Qx(e,t){if(!t.changes.length)return null;const n=[],o=e.doc.content.size;for(const r of t.changes){const s=`am-agent-change${t.current===r.id?" is-current":""}`,c=Math.min(r.from,o),a=Math.min(r.to,o);a>c?(n.push(so.inline(c,a,{class:s,"data-agent-change":String(r.id)})),e.doc.nodesBetween(c,a,(i,d)=>(i.isBlock&&i.isLeaf&&d>=c&&d+i.nodeSize<=a&&n.push(so.node(d,d+i.nodeSize,{class:`${s} am-agent-change-block`})),!i.isTextblock))):n.push(so.widget(c,()=>{const i=document.createElement("span");return i.className=`am-agent-del${t.current===r.id?" is-current":""}`,i.setAttribute("data-agent-change",String(r.id)),i},{side:-1,key:`am-agent-del-${r.id}-${t.current===r.id?1:0}`,ignoreSelection:!0}))}return lr.create(e.doc,n)}function eb(e){return[Et(()=>tb(e))].flat()}function tb(e){return new qt({key:oo,state:{init:()=>({changes:[],current:null}),apply(t,n){const o=t.getMeta(oo);if(o&&"clear"in o)return{changes:[],current:null};if(o&&"add"in o){const s=Zx(n.changes,o.add,o.before,t);return{changes:s,current:s.some(c=>c.id===n.current)?n.current:null}}let r=n;return t.docChanged&&n.changes.length&&(r={...n,changes:n.changes.map(s=>{const c=t.mapping.map(s.from,1);return{...s,from:c,to:Math.max(c,t.mapping.map(s.to,-1))}})}),o&&"current"in o&&(r={...r,current:o.current}),r}},props:{decorations(t){const n=oo.getState(t);return n?Qx(t,n):null}},view:t=>{const n=oo.getState(t.state);return n&&e.current(n),{update(o,r){const s=oo.getState(o.state);s&&s!==oo.getState(r)&&e.current(s)}}}})}function nb(e,t,n){return n.length?e.setMeta(oo,{add:n,before:t}):e}function ob(e){const t=oo.getState(e.state);if(!t?.changes.length)return{reverted:0,skipped:0};const n=e.state.tr;let o=0,r=0;for(const s of[...t.changes].sort((c,a)=>a.from-c.from)){if(!zu(e.state.doc.slice(s.from,s.to).content,s.after)){r+=1+(s.locked??0);continue}n.replace(s.from,s.to,s.old),o++,r+=s.locked??0}return e.dispatch(n.setMeta(oo,{clear:!0}).scrollIntoView()),{reverted:o,skipped:r}}function rb(e){e.dispatch(e.state.tr.setMeta(oo,{clear:!0}))}function sb(e){const t=oo.getState(e.state);if(!t?.changes.length)return null;const n=t.changes.findIndex(r=>r.id===t.current),o=t.changes[(n+1)%t.changes.length];return e.dispatch(e.state.tr.setMeta(oo,{current:o.id})),o}kn({"agentchg.summary":{zh:"Tangu 修改了 {n} 处",en:"Tangu changes: {n}"},"agentchg.review":{zh:"逐处查看",en:"Review"},"agentchg.next":{zh:"下一处 {i}/{n}",en:"Next {i}/{n}"},"agentchg.revert":{zh:"全部撤回",en:"Revert all"},"agentchg.keep":{zh:"保留",en:"Keep"},"agentchg.label":{zh:"Tangu 对这篇笔记的改动",en:"Tangu's changes to this note"},"agentchg.skipped":{zh:"有 {n} 处你已改过,保留了你的版本,没有撤回",en:"Skipped {n} you had already edited; your version was kept"},"agentchg.live":{zh:"Tangu 正在修改这篇笔记",en:"Tangu is editing this note"},"agentchg.liveHint":{zh:"可以接着写;改动撞上时保留你的版本,Tangu 的另存为副本",en:"Keep writing — if edits overlap, yours are kept and Tangu’s are saved as a copy"}});function ab(){const{t:e}=tn();return f.jsxs("div",{className:"am-agent-capsule is-live",role:"status","aria-live":"polite","data-testid":"agent-live-capsule",children:[f.jsx("span",{className:"amx-pending-insert-spin","aria-hidden":!0}),f.jsx("span",{className:"am-agent-capsule-text",children:e("agentchg.live")}),f.jsx("span",{className:"am-agent-capsule-hint",children:e("agentchg.liveHint")})]})}function cb({count:e,index:t,onReview:n,onRevert:o,onKeep:r}){const{t:s}=tn();return f.jsxs("div",{className:"am-agent-capsule",role:"status","aria-label":s("agentchg.label"),"data-testid":"agent-change-capsule",children:[f.jsx(Pl,{size:14,"aria-hidden":!0}),f.jsx("span",{className:"am-agent-capsule-text",children:s("agentchg.summary",{n:String(e)})}),f.jsx("span",{className:"am-agent-capsule-sep","aria-hidden":!0}),f.jsx("button",{type:"button",className:"btn sm","data-act":"review",onClick:n,children:t?s("agentchg.next",{i:String(t),n:String(e)}):s("agentchg.review")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"revert",onClick:o,children:s("agentchg.revert")}),f.jsx("button",{type:"button",className:"btn sm primary","data-act":"keep",onClick:r,children:s("agentchg.keep")})]})}kn({"pendins.busy":{zh:"「{label}」进行中…",en:'"{label}" in progress…'},"pendins.cancel":{zh:"取消",en:"Cancel"},"pendins.lost":{zh:"「{label}」的结果没有插入:原来的位置已被删除。",en:'"{label}" wasn’t inserted: its original position was deleted.'},"pendins.sourceMode":{zh:"「{label}」的结果没有插入:你正在源码模式里编辑。切回可视模式后可以重新执行。",en:'"{label}" wasn’t inserted because you’re editing in source mode. Switch back to visual mode and run it again.'}});const Tr=new Dn("UNIFIED_PENDING_INSERT");function ib(e){const t=document.createElement("span");if(t.className="amx-pending-insert",t.dataset.pendingInsert=e.id,t.contentEditable="false",!e.visible)return t.dataset.hidden="",t;t.setAttribute("role","status");const n=document.createElement("span");n.className="amx-pending-insert-spin",n.setAttribute("aria-hidden","true");const o=document.createElement("span");o.textContent=we("pendins.busy",{label:e.label});const r=document.createElement("button");return r.type="button",r.className="btn sm",r.textContent=we("pendins.cancel"),r.addEventListener("mousedown",s=>s.preventDefault()),r.addEventListener("click",s=>{s.preventDefault(),e.onCancel()}),t.append(n,o,r),t}function lb(){return[Et(()=>new qt({key:Tr,state:{init:()=>lr.empty,apply(e,t){let n=t.map(e.mapping,e.doc);const o=e.getMeta(Tr);return o&&"add"in o?n=n.add(e.doc,[so.widget(o.add.pos,()=>ib(o.add),{id:o.add.id,key:`pending:${o.add.id}`,side:-1,ignoreSelection:!0,stopEvent:()=>!0})]):o&&"remove"in o&&(n=n.remove(n.find(void 0,void 0,r=>r.id===o.remove))),n}},props:{decorations:e=>Tr.getState(e)}}))]}function $u(e,t){const o=Tr.getState(e)?.find(void 0,void 0,r=>r.id===t)[0];return o?o.from:null}let ub=0;function db(e,t,n=!0){const o=`p${Date.now().toString(36)}${(ub++).toString(36)}`;let r=!1;const s=()=>{r=!0,Au(e,o)};return e.dispatch(e.state.tr.setMeta(Tr,{add:{id:o,pos:e.state.selection.head,label:t,visible:n,onCancel:s}})),{id:o,label:t,cancelled:()=>r}}function Au(e,t){e.isDestroyed||$u(e.state,t)==null||e.dispatch(e.state.tr.setMeta(Tr,{remove:t}))}function fb(e,t,n){const o=$u(e.state,t);if(o==null)return!1;let r=e.state.tr.setMeta(Tr,{remove:t});if(!n?.size)return e.dispatch(r),!0;const s=e.state.doc.resolve(o);let c=s.depth;for(;c>=1&&!["doc","amadeusColumnCell","blockquote"].includes(s.node(c-1).type.name);)c--;const a=e.state.selection;let i,d,p;if(c<1)i=o,r=r.insert(o,n),d=o+n.size,p=e.hasFocus()&&a.empty&&a.head===o;else{const h=s.before(c),M=s.after(c),R=s.node(c).textContent.trim()==="";p=e.hasFocus()&&a.from>=h&&a.to<=M,i=R?h:M,r=R?r.replaceWith(h,M,n):r.insert(M,n),d=i+n.size}return Xs(r,i,d),p&&(r=r.setSelection(Ne.near(r.doc.resolve(Math.min(d,r.doc.content.size)),-1)).scrollIntoView()),e.dispatch(r),!0}function yl(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{level:"warning",text:we("pendins.sourceMode",{label:e})}}))}function mb(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("pendins.lost",{label:e})}}))}function Nu(e,t,n){return JSON.stringify(e.slice(t,n).content.toJSON()??[],(o,r)=>{if(r&&typeof r=="object"&&!Array.isArray(r)&&r.type==="heading"&&r.attrs){const{id:s,...c}=r.attrs;return{...r,attrs:c}}return r})}const ir=new Dn("amInlineAi");function pb(e){const t=e.state.selection;if(!(t instanceof Ne)||!t.empty)return!1;const n=t.$from;if(n.parent.type.name!=="paragraph"||n.parent.content.size!==0)return!1;const o=n.depth>=1?n.node(n.depth-1).type.name:"";return o==="doc"||o==="amadeusColumnCell"||o==="amadeusCanvasCard"}function hb(e){return new qt({key:ir,state:{init:()=>null,apply(t,n){const o=t.getMeta(ir);if(o&&"clear"in o)return null;if(o&&"set"in o)return o.set;if(!n||!t.docChanged)return n;const r=t.mapping.map(n.from,1);return{...n,from:r,to:Math.max(r,t.mapping.map(n.to,-1))}}},props:{decorations(t){const n=ir.getState(t);return!n||n.to<=n.from?null:lr.create(t.doc,[so.inline(n.from,Math.min(n.to,t.doc.content.size),{class:"am-ai-target"})])},handleKeyDown(t,n){return n.key!==" "||n.isComposing||n.keyCode===229||t.composing||n.metaKey||n.ctrlKey||n.altKey||n.shiftKey||!e.spaceTrigger()||!pb(t)?!1:(e.onSpace(t),!0)}}})}function gb(e){return[Et(()=>hb({spaceTrigger:e.spaceTrigger,onSpace:t=>e.onSpace.current(t)}))].flat()}function yb(e,t,n){const o={from:t,to:n,text:e.state.doc.textBetween(t,n,`
58
- `,""),sig:Nu(e.state.doc,t,n)},r=e.state.tr.setMeta(ir,{set:o});return n>t&&r.setSelection(Ne.create(r.doc,n)),e.dispatch(r),o}function xl(e){const t=ir.getState(e.state);if(!t)return;const n=e.state.tr.setMeta(ir,{clear:!0});if(t.to>t.from&&t.to<=n.doc.content.size)try{n.setSelection(Ne.create(n.doc,t.from,t.to))}catch{}e.dispatch(n)}function bl(e){return ir.getState(e.state)??null}function xb(e,t,n){const o=e.content.size,r=e.textBetween(Math.max(0,t-8e3),t,`
59
- `,"").slice(-2e3),s=e.textBetween(n,Math.min(o,n+4e3),`
60
- `,"").slice(0,1e3);return{before:r,after:s}}function bb(e,t){const n=e.resolve(t);let o=n.depth;for(;o>=1&&!["doc","amadeusColumnCell"].includes(n.node(o-1).type.name);)o--;return o<1?null:{from:n.before(o),to:n.after(o),blank:n.node(o).textContent.trim()===""}}function vb(e,t,n,o){if(!n.childCount)return null;const{doc:r}=e.state,s=r.content.size,c=Math.min(t.from,s),a=Math.min(Math.max(t.to,c),s);let i=o;i==="replace"&&Nu(r,c,a)!==t.sig&&(i="below");let d=e.state.tr,p;if(i==="replace"){const h=n.childCount===1&&!!n.firstChild?.isTextblock&&r.resolve(c).sameParent(r.resolve(a));d=d.replaceRange(c,a,h?new Ha(n,1,1):new Ha(n,0,0)),p=d.mapping.map(a,1)}else{const h=bb(r,i==="below"?a:c);if(!h)return null;i==="insert"&&h.blank?(d=d.replaceWith(h.from,h.to,n),p=h.from+n.size):(d=d.insert(h.to,n),p=h.to+n.size)}return d=d.setSelection(Ne.near(d.doc.resolve(Math.min(p,d.doc.content.size)),-1)),e.dispatch(d.setMeta(ir,{clear:!0}).scrollIntoView()),i}kn({"unipage.menu.askTangu":{zh:"问 Tangu",en:"Ask Tangu"}});const wb=2e4;function kb(e,t){let n=null;for(const o of Js(e)){if(o.pos>t)break;n=o.text}return n}function Cb(e,t,n,o){const r=e.textBetween(t,n,`
61
- `,"").trim().slice(0,wb);if(!r)return"";const s=kb(e,t),c=s&&!/[[\]|#^\n]/.test(s)?`#${s}`:"";return o?`${r}
62
- — [[${o}${c}]]`:r}function Tu(e,t){const n=e.resolve(t);let o=n.depth;for(;o>=1&&!["doc","amadeusColumnCell"].includes(n.node(o-1).type.name);)o--;return o>=1?n.after(o):null}function Sb(e,t,n){if(e.resolve(t).depth!==0)return Tu(e,t+1)??e.content.size;let o=e.content.size,r=!1;return e.forEach((s,c)=>{if(o!==e.content.size)return;if(c===t){r=!0;return}if(!r||s.type.name!=="heading")return;(Number(s.attrs.level)||1)<=n&&(o=c)}),o}function Eb(e,t){if(!t)return null;const n=Js(e),o=t.heading?n.findIndex(i=>i.text===t.heading.trim()):-1,r=o>=0?n[o]:null,s=r?r.pos:0,c=r?Sb(e,r.pos,r.level):e.content.size,a=(t.text??"").split(`
63
- `).map(i=>i.trim()).filter(Boolean);if(a.length){const i=[];e.nodesBetween(s,c,(p,h)=>p.isTextblock?(h>=s&&i.push({pos:h,text:p.textContent}),!1):!0);const d=i.findIndex(p=>p.text.includes(a[0]));if(d>=0){const p=a[a.length-1],h=i.findIndex((R,T)=>T>=d&&R.text.includes(p)),M=Tu(e,i[h>=0?h:d].pos+1);if(M!=null)return M}}return r?c:null}kn({"linkcard.text":{zh:"文字",en:"Text"},"linkcard.link":{zh:"链接",en:"Link"},"linkcard.copy":{zh:"复制链接",en:"Copy link"},"linkcard.unlink":{zh:"移除链接",en:"Remove link"},"linkcard.fnEmpty":{zh:"脚注还是空的",en:"This footnote is empty"},"linkcard.fnMissing":{zh:"找不到这条脚注的定义",en:"Footnote definition not found"}});const vl=500,Fa=250,wl='a[href], sup[data-type="footnote_reference"]';function ju(e,t,n){const o=e.resolve(Math.max(0,Math.min(t,e.content.size)));if(!o.parent.isTextblock)return null;const r=o.start(),s=[];o.parent.forEach((h,M)=>s.push({node:h,from:r+M,to:r+M+h.nodeSize}));const c=h=>!!n.isInSet(h.node.marks);let a=s.findIndex(h=>c(h)&&t>=h.from&&t<h.to);if(a<0&&(a=s.findIndex(h=>c(h)&&t>=h.from&&t<=h.to)),a<0)return null;const i=n.isInSet(s[a].node.marks);let d=a,p=a;for(;d>0&&i.isInSet(s[d-1].node.marks);)d--;for(;p<s.length-1&&i.isInSet(s[p+1].node.marks);)p++;return{from:s[d].from,to:s[p].to,mark:i}}function Mb(e,t){const n=e.state.schema.marks.link;if(!n)return null;let o;try{o=e.posAtDOM(t,0)}catch{return null}const r=ju(e.state.doc,o,n);return r&&r.from<r.to?{from:r.from,to:r.to}:null}function zb({getView:e,onOpenNote:t}){const{t:n}=tn(),[o,r]=b.useState(null),[s,c]=b.useState(null),[a,i]=b.useState(null),d=b.useRef(null),p=b.useRef(null);b.useEffect(()=>{const T=()=>{d.current&&clearTimeout(d.current),p.current&&clearTimeout(p.current),d.current=null,p.current=null},w=X=>{const ee=e()?.dom.closest(".unified-body");return!!ee&&X.closest(".unified-body")===ee},S=X=>{const q=X.target?.closest?.(wl);if(!q||!w(q))return;if(p.current&&(clearTimeout(p.current),p.current=null),d.current&&clearTimeout(d.current),q.tagName==="SUP"){d.current=setTimeout(()=>{const Re=e(),Ge=q.getBoundingClientRect();r(null),c({num:q.textContent??"",text:Re?Rd(Re.state.doc,q.getAttribute("data-label")??""):null,x:Ge.left,y:Ge.bottom+6})},vl);return}const oe=q;d.current=setTimeout(()=>{const Re=e();c(null);const Ge=oe.getBoundingClientRect(),m=Re?Mb(Re,oe):null;r({href:oe.getAttribute("href")??"",text:m&&Re?Re.state.doc.textBetween(m.from,m.to):oe.textContent??"",from:m?.from??-1,to:m?.to??-1,x:Ge.left,y:Ge.bottom+6})},vl)},I=X=>{!X.target?.closest?.(wl)||X.relatedTarget?.closest?.(".amx-linkcard")||(d.current&&clearTimeout(d.current),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{r(null),c(null)},Fa))};return document.addEventListener("mouseover",S,!0),document.addEventListener("mouseout",I,!0),()=>{document.removeEventListener("mouseover",S,!0),document.removeEventListener("mouseout",I,!0),T()}},[e]),b.useEffect(()=>{if(!o&&!s||a)return;const T=()=>{r(null),c(null)};return document.addEventListener("scroll",T,!0),()=>document.removeEventListener("scroll",T,!0)},[o,s,a]);const h=(T,w,S,I,X)=>{const ee=e(),q=ee?.state.schema.marks.link;if(!ee||!q)return;const{doc:oe}=ee.state;if(w>oe.content.size||T>=w)return;const Re=ju(oe,T,q);if(!Re||Re.from!==T||Re.to!==w||Re.mark.attrs.href!==S)return;const Ge=oe.textBetween(T,w),m=rt=>q.create({...Re.mark.attrs,href:rt,..."ref"in Re.mark.attrs?{ref:null}:{}});let ke=ee.state.tr;if(I==="")ke=ke.delete(T,w);else if(I!==null&&I!==Ge){let rt=null;oe.nodesBetween(T,w,me=>me.isInline?(rt=rt===null?me.marks:rt.filter(he=>he.isInSet(me.marks)),!1):!0);const de=(rt??[]).filter(me=>me.type!==q);ke=ke.replaceWith(T,w,ee.state.schema.text(I,X?m(X).addToSet(de):de)),ke.setSelection(Ne.near(ke.doc.resolve(T+I.length)))}else if(X){if(X===Re.mark.attrs.href){ee.focus();return}ke=ke.removeMark(T,w,Re.mark).addMark(T,w,m(X))}else ke=ke.removeMark(T,w,Re.mark);ee.dispatch(ke.scrollIntoView()),ee.focus()};if(a){const T=!!Xc(a.href)&&!!a.text.trim(),w=()=>{i(null),r(null),e()?.focus()};return f.jsxs(cr,{children:[f.jsx("div",{className:"amx-linkedit-backdrop",onMouseDown:()=>i(null),role:"presentation"}),f.jsx(Yr,{className:"amx-linkedit",x:window.innerWidth/2,y:Math.round(window.innerHeight*.3),center:!0,children:f.jsxs("form",{className:"amx-linkedit-form",onSubmit:S=>{S.preventDefault();const I=Xc(a.href);!I||!a.text.trim()||(h(a.from,a.to,a.wasHref,a.text,I),i(null),r(null))},onKeyDown:S=>{S.key==="Escape"&&(S.preventDefault(),S.stopPropagation(),w())},children:[f.jsxs("label",{children:[n("linkcard.text"),f.jsx("input",{autoFocus:!0,value:a.text,onChange:S=>i({...a,text:S.target.value}),onFocus:S=>S.currentTarget.select()})]}),f.jsxs("label",{children:[n("linkcard.link"),f.jsx("input",{value:a.href,onChange:S=>i({...a,href:S.target.value})})]}),f.jsxs("div",{className:"amx-linkedit-row",children:[f.jsx("button",{type:"button",onClick:w,children:n("common.cancel")}),f.jsx("button",{type:"submit",className:"primary",disabled:!T,children:n("common.save")})]})]})})]})}if(s)return f.jsx(cr,{children:f.jsxs(Yr,{className:"amx-linkcard amx-fncard",x:s.x,y:s.y,onMouseEnter:()=>{p.current&&clearTimeout(p.current),p.current=null},onMouseLeave:()=>{p.current=setTimeout(()=>c(null),Fa)},children:[f.jsx("span",{className:"amx-fncard-num",children:s.num}),f.jsx("span",{className:`amx-fncard-text${s.text?"":" muted"}`,children:s.text==null?n("linkcard.fnMissing"):s.text||n("linkcard.fnEmpty")})]})});if(!o)return null;let M=o.href;try{M=new URL(o.href).host||o.href}catch{}const R=o.from>=0&&(e()?.editable??!0);return f.jsx(cr,{children:f.jsxs(Yr,{className:"amx-linkcard",x:o.x,y:o.y,onMouseEnter:()=>{p.current&&clearTimeout(p.current),p.current=null},onMouseLeave:()=>{p.current=setTimeout(()=>r(null),Fa)},children:[f.jsx("button",{className:"amx-linkcard-host",title:o.href,onClick:T=>{t&&Nl(o.href)==="note"?(r(null),t(o.href,om(T))):window.open(o.href,"_blank","noopener")},children:M}),f.jsx("span",{className:"amx-linkcard-sep"}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(o.href)},children:n("linkcard.copy")}),R&&f.jsx("button",{onClick:()=>i({from:o.from,to:o.to,text:o.text,href:o.href,wasHref:o.href}),children:n("common.edit")}),R&&f.jsx("button",{onClick:()=>{h(o.from,o.to,o.href,null,null),r(null)},children:n("linkcard.unlink")}),R&&f.jsx("button",{className:"danger",onClick:()=>{h(o.from,o.to,o.href,"",null),r(null)},children:n("common.delete")})]})})}kn({"unipage.table.label":{zh:"表格",en:"Table"},"unipage.table.rowAbove":{zh:"在上方插入行",en:"Insert row above"},"unipage.table.rowBelow":{zh:"在下方插入行",en:"Insert row below"},"unipage.table.colLeft":{zh:"在左侧插入列",en:"Insert column left"},"unipage.table.colRight":{zh:"在右侧插入列",en:"Insert column right"},"unipage.table.deleteRow":{zh:"删除行",en:"Delete row"},"unipage.table.deleteCol":{zh:"删除列",en:"Delete column"},"unipage.table.alignLeft":{zh:"左对齐",en:"Align left"},"unipage.table.alignCenter":{zh:"居中",en:"Align center"},"unipage.table.alignRight":{zh:"右对齐",en:"Align right"}});function cc(e){const t=e?.state.selection;return t instanceof Ee&&t.node.type.spec.tableRole==="table"}function $b(e,t,n){if(!e||!cc(e))return null;const o=document.elementFromPoint(t,n)?.closest?.("td,th");if(!o||!e.dom.contains(o))return null;try{return Od(e.state.doc,e.posAtDOM(o,0))}catch{return null}}const Ab=[{op:"rowAbove",key:"unipage.table.rowAbove",Icon:Ip},{op:"rowBelow",key:"unipage.table.rowBelow",Icon:Dp},{op:"colLeft",key:"unipage.table.colLeft",Icon:_p},{op:"colRight",key:"unipage.table.colRight",Icon:Fp},{op:"deleteRow",key:"unipage.table.deleteRow",Icon:Ya},{op:"deleteCol",key:"unipage.table.deleteCol",Icon:Ya}],Nb=[{align:"left",key:"unipage.table.alignLeft",Icon:rm},{align:"center",key:"unipage.table.alignCenter",Icon:Ld},{align:"right",key:"unipage.table.alignRight",Icon:Id}];function Tb({view:e,cell:t,onDone:n}){const{t:o}=tn(),r=e.state.selection;if(!(r instanceof Ee)||r.node.type.spec.tableRole!=="table")return null;const s=Dd(e.state.doc,r.from,t);if(!s)return null;const c=a=>{n();const i=a();i&&e.dispatch(i),e.focus()};return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"ubm-sep",role:"separator"}),f.jsx("div",{className:"ubm-label",role:"presentation",children:o("unipage.table.label")}),Ab.filter(a=>s.ops.includes(a.op)).map(({op:a,key:i,Icon:d})=>f.jsxs("button",{"data-table-op":a,role:"menuitem",tabIndex:-1,onClick:()=>c(()=>Pd(e.state,s.cellPos,a)),children:[f.jsx(d,{size:13})," ",o(i)]},a)),s.align&&Nb.map(({align:a,key:i,Icon:d})=>f.jsxs("button",{"data-table-align":a,"aria-checked":s.align===a,role:"menuitemcheckbox",tabIndex:-1,onClick:()=>c(()=>Fd(e.state,s.cellPos,a)),children:[f.jsx(d,{size:13})," ",o(i),s.align===a&&f.jsx(oa,{size:13,className:"ubm-check"})]},a))]})}function jb(e,t){return{el:e,owns:n=>{const o=t();if(!o||!o.dom.contains(n))return!1;for(let r=n.nodeType===1?n:n.parentElement;r&&r!==o.dom;r=r.parentElement)if(r.contentEditable==="false"||r.classList.contains("ProseMirror"))return!1;return!0},replace:n=>{const o=t();if(!o||!o.editable)return 0;const r=[];for(const{range:c,text:a}of n){let i,d;try{i=o.posAtDOM(c.startContainer,c.startOffset),d=o.posAtDOM(c.endContainer,c.endOffset)}catch{continue}d<=i||o.state.doc.textBetween(i,d,`
64
- `,"")!==c.toString()||r.push({from:i,to:d,text:a})}if(!r.length)return 0;r.sort((c,a)=>a.from-c.from);const s=o.state.tr;for(const c of r)c.text?s.insertText(c.text,c.from,c.to):s.delete(c.from,c.to);return o.dispatch(s),r.length}}}kn({"unipage.upload.uploading":{zh:"上传中 {name}",en:"Uploading {name}"},"unipage.upload.fileN":{zh:"文件{n}",en:"File {n}"},"unipage.toast.insertPointLost":{zh:"文件已创建,但原插入位置已失效(笔记已切换)",en:"The file was created, but the original insertion point is gone (the note was switched)."},"unipage.plugin.notString":{zh:"run() 必须返回字符串,实际是 {type}",en:"run() must return a string, but returned {type}"},"unipage.plugin.tooLong":{zh:"run() 返回内容过长",en:"run() returned too much content"},"unipage.plugin.controlChars":{zh:"run() 返回内容含控制字符",en:"run() returned content containing control characters"},"unipage.plugin.failed":{zh:"「{label}」失败:{err}",en:'"{label}" failed: {err}'},"unipage.toast.columnTopLevelOnly":{zh:"分栏只能对顶层块使用,请先把这一块拖出当前列/列表",en:"Columns only work on top-level blocks — move this block out of its current column or list first."},"unipage.file.drawing":{zh:"画板",en:"Whiteboard"},"unipage.file.noteView":{zh:"笔记视图",en:"Note view"},"unipage.file.noteViewN":{zh:"笔记视图 {n}",en:"Note view {n}"},"unipage.file.untitledView":{zh:"未命名视图",en:"Untitled view"},"unipage.bookmark.title":{zh:"插入书签",en:"Insert bookmark"},"unipage.bookmark.label":{zh:"粘贴链接地址(https:// 开头);YouTube 链接会直接内嵌播放器。",en:"Paste a link starting with https:// — YouTube links turn into an embedded player."},"unipage.embed.title":{zh:"嵌入块引用",en:"Embed a block reference"},"unipage.embed.label":{zh:"形如 笔记名#标题 或 笔记名#^块ID(块菜单「复制标题链接」「复制块链接」可得);也可只填笔记名嵌整篇首块。",en:'Looks like NoteName#Heading or NoteName#^blockId — the block menu items "Copy heading link" and "Copy block link" give you one. A note name on its own embeds the first block of that note.'},"unipage.embed.confirm":{zh:"嵌入",en:"Embed"},"unipage.title.iconAction":{zh:"更换/移除页面图标",en:"Change or remove the page icon"},"unipage.title.addIcon":{zh:"添加图标",en:"Add icon"},"unipage.title.addCover":{zh:"添加封面",en:"Add cover"},"unipage.toast.canvasElementsFailed":{zh:"画布改动没能保存:这篇笔记的 amadeus_canvas 行无法解析,请在源码模式检查",en:"Canvas changes were not saved: the amadeus_canvas line in this note cannot be parsed — check it in source mode."},"unipage.toast.canvasTreeFailed":{zh:"层级改动没能保存:这篇笔记的 amadeus_canvas 行无法解析,请在源码模式检查",en:"Hierarchy changes were not saved: the amadeus_canvas line in this note cannot be parsed — check it in source mode."},"unipage.toast.canvasMainFailed":{zh:"主卡改动没能保存:这篇笔记的 amadeus_canvas 行无法解析,请在源码模式检查",en:"Main card changes were not saved: the amadeus_canvas line in this note cannot be parsed — check it in source mode."},"unipage.toast.cardUnavailable":{zh:"当前块不能转换为卡片;请先移出列表或分栏",en:"This block cannot be turned into a card — move it out of the list or columns first."},"unipage.toast.cardMade":{zh:"已转换为卡片 —— 右上角切到画布模式查看",en:"Turned into a card — switch to canvas mode at the top right to see it."},"unipage.menu.turnInto":{zh:"转换为",en:"Turn into"},"unipage.toast.renameDetachedFailed":{zh:"没能把笔记改名为「{name}」(可能已有同名笔记),保留了原名",en:"Couldn’t rename the note to “{name}” (the name may be taken). The old name was kept."},"unipage.menu.text":{zh:"正文",en:"Text"},"unipage.menu.h1":{zh:"标题 1",en:"Heading 1"},"unipage.menu.h2":{zh:"标题 2",en:"Heading 2"},"unipage.menu.h3":{zh:"标题 3",en:"Heading 3"},"unipage.menu.bullet":{zh:"无序列表",en:"Bulleted list"},"unipage.menu.ordered":{zh:"有序列表",en:"Numbered list"},"unipage.menu.task":{zh:"待办",en:"To-do list"},"unipage.menu.quote":{zh:"引用",en:"Quote"},"unipage.menu.fold":{zh:"折叠",en:"Toggle"},"unipage.menu.callout":{zh:"标注",en:"Callout"},"unipage.menu.code":{zh:"代码块",en:"Code block"},"unipage.menu.card":{zh:"卡片",en:"Card"},"unipage.menu.toNewColumn":{zh:"移到新列",en:"Move to new column"},"unipage.menu.unsplit":{zh:"取消分栏",en:"Unsplit columns"},"unipage.menu.aria":{zh:"块操作",en:"Block actions"},"unipage.menu.stale":{zh:"笔记在菜单打开期间变了,请重新打开块菜单",en:"The note changed while the menu was open — open the block menu again"},"unipage.menu.toNewColumnMulti":{zh:"选中多块时不能移到新列,请只选一块",en:"Select a single block to move it to a new column"},"unipage.menu.backToDoc":{zh:"收回文档",en:"Return to document"},"unipage.menu.duplicate":{zh:"复制块",en:"Duplicate block"},"unipage.menu.delete":{zh:"删除",en:"Delete"},"unipage.lock.bar":{zh:"页面已锁定,防止误改。",en:"This page is locked to prevent accidental edits."},"unipage.lock.unlock":{zh:"解锁",en:"Unlock"}});const Rb=800;let Ks=null,Oa=null;const Db={insertAfter:()=>{},deleteEmpty:()=>{},mergePrev:()=>{},arrow:()=>{},moveDir:()=>{},selfFocus:()=>{}};async function Ru(e,t){try{const n=new Uint8Array(await t.arrayBuffer()),{opts:o}=await Xa(),{base:r}=await wn.saveAttachment(e,t.name||"file",n,o);return`![[${r}]]`}catch{return null}}let Mr=null;function zr(){Mr&&(clearTimeout(Mr.timer),clearTimeout(Mr.arm),Mr.off(),Mr.el.remove(),Mr=null)}function qs(e){if(zr(),e.width<1||e.height<1)return;const t=document.createElement("div");t.className="am-citeflash",t.style.cssText="position:fixed;pointer-events:none;z-index:60;left:0;top:0",document.body.appendChild(t);const n=t.currentCSSZoom||1;t.style.left=`${(e.left-4)/n}px`,t.style.top=`${(e.top-2)/n}px`,t.style.width=`${(e.width+8)/n}px`,t.style.height=`${(e.height+4)/n}px`;const o=()=>{window.removeEventListener("scroll",zr,!0),window.removeEventListener("wheel",zr,!0)},r=window.setTimeout(()=>{window.addEventListener("scroll",zr,!0),window.addEventListener("wheel",zr,!0)},300);Mr={el:t,timer:window.setTimeout(zr,1400),arm:r,off:o}}function Lb(e,t,n=!1,o=!1){const r=[],s=Jx(e.state,t,n?r:void 0);s&&(o&&s.setMeta("addToHistory",!0),e.dispatch(n?nb(s,e.state.doc,r):s))}function Ib({path:e,pageDir:t,body:n,onChange:o,onFinalFlush:r,skipFinalFlush:s,hidden:c,apiRef:a,probe:i,extraPlugins:d,focusPlace:p,onFocused:h,onCard:M,readOnly:R=!1,onAskTangu:T,aiMenu:w,onAiPrompt:S}){const[,I]=Hd(),X=lc(),ee=b.useRef(null),[q,oe]=b.useState(!1),Re=b.useRef({onFinalFlush:r,skipFinalFlush:s});Re.current={onFinalFlush:r,skipFinalFlush:s};const Ge=b.useRef(M);Ge.current=M;const m=b.useRef(S);m.current=S,b.useEffect(()=>(a.current={applySlashItem:re=>dt.current(re),applyBody:(re,ce,ge)=>{let k=!1;return I()?.action(J=>{const le=J.get(vn),ve=J.get(Ir)(vr(re,t));ve&&(Lb(le,ve,ce,ge),Wd(le.state.doc,ve),k=!0,i&&(i.reconciled=(i.reconciled??0)+1))}),k},serializeNow:()=>{let re=null;return I()?.action(ce=>{const ge=ce.get(vn);re=_r(Ts(ce,ge.state.doc),t)}),re},canonical:re=>{let ce=null;return I()?.action(ge=>{const k=ge.get(Ir)(vr(re,t));k&&(ce=_r(Ts(ge,k),t))}),ce},insertFiles:re=>{rt(re)},insertMarkdown:(re,ce,ge)=>de(re,ce,ge),parseMd:re=>{let ce=null;return I()?.action(ge=>{const k=ge.get(Ir)(vr(re,t));ce=k?.childCount?k.content:null}),ce},serializeMd:re=>{let ce=null;try{I()?.action(ge=>{const J=ge.get(vn).state.schema.topNodeType.createAndFill(void 0,re);J&&(ce=qd(ge.get(Nm)(J)))})}catch{return null}return ce},serializeStored:re=>{let ce=null;try{I()?.action(ge=>{const k=ge.get(vn).state.schema.topNodeType.createAndFill(void 0,re);k&&(ce=_r(Ts(ge,k),t))})}catch{return null}return ce},focusStart:()=>{I()?.action(re=>{const ce=re.get(vn);ce.dispatch(ce.state.tr.setSelection(Ne.atStart(ce.state.doc))),ce.focus()})},focusEnd:()=>{I()?.action(re=>{const ce=re.get(vn);ce.dispatch(ce.state.tr.setSelection(Ne.atEnd(ce.state.doc))),ce.focus()})},focusTail:()=>{I()?.action(re=>{const ce=re.get(vn),{doc:ge,schema:k}=ce.state,J=k.nodes.paragraph,le=Fe=>!!Fe&&Fe.type===J&&Fe.content.size===0,ve=ge.lastChild;let Ye=ce.state.tr;le(ve)||(Ye=Ye.insert(ge.content.size,J.create())),ce.dispatch(Ye.setSelection(Ne.atEnd(Ye.doc)).scrollIntoView()),ce.focus()})},hasFocus:()=>{let re=!1;return I()?.action(ce=>{re=ce.get(vn).hasFocus()}),re},revealSelection:()=>{I()?.action(re=>{const ce=re.get(vn);ce.dispatch(ce.state.tr.scrollIntoView()),ce.focus()})},serializePrefix:re=>{let ce=null;try{I()?.action(ge=>{const k=ge.get(vn);ce=_r(Ts(ge,k.state.doc.cut(0,Math.min(re,k.state.doc.content.size))),t)})}catch{return null}return ce},posAfterPrefix:re=>{let ce=null;try{I()?.action(ge=>{const k=ge.get(Ir)(vr(re,t));k&&(ce=Ne.atEnd(k).head)})}catch{return null}return ce}},()=>{if(!Re.current.skipFinalFlush()){const re=a.current?.serializeNow()??null;re!=null&&Re.current.onFinalFlush(re)}a.current=null}),[I,t]);const ke=async re=>{try{const ce=new Uint8Array(await re.arrayBuffer()),{opts:ge}=await Xa(),{pageRel:k}=await wn.saveAttachment(e,re.name||"pasted.png",ce,ge);return $l(zl(t,k),!0)}catch{return null}},rt=async re=>{if(!re.length)return;const ce=re.map((k,J)=>`​${we("unipage.upload.uploading",{name:k.name||we("unipage.upload.fileN",{n:J+1})})}​`);I()?.action(k=>{const J=k.get(vn),le=J.state.schema.nodes.paragraph;if(!le)return;const{$to:ve}=J.state.selection;let Ye=ve.depth>=1?ve.after(1):ve.pos,Fe=J.state.tr;for(const mt of ce){const it=le.create(null,J.state.schema.text(mt));Fe=Fe.insert(Ye,it),Ye+=it.nodeSize}J.dispatch(Fe.scrollIntoView())});const ge=(k,J)=>{I()?.action(le=>{const ve=le.get(vn);let Ye=-1,Fe=-1;if(ve.state.doc.descendants((jt,ht)=>Ye>=0||!jt.isTextblock||jt.textContent!==k?!0:(Ye=ht,Fe=ht+jt.nodeSize,!1)),Ye<0)return;const mt={from:Ye,to:Fe},it=ve.state.schema.nodes.paragraph,_t=J&&it?ve.state.tr.replaceWith(mt.from,mt.to,it.create(null,ve.state.schema.text(J))):ve.state.tr.delete(mt.from,mt.to);ve.dispatch(_t)})};for(let k=0;k<re.length;k++)ge(ce[k],await Ru(e,re[k]))},de=(re,ce="cursor",ge)=>{let k=!1;return I()?.action(J=>{const le=J.get(vn),ve=J.get(Ir)(vr(re,t));if(!ve?.childCount)return;const Ye=ve.content,Fe=!!ge?.quiet,mt=Fe?Eb(le.state.doc,ge?.after):null;if(Fe&&mt==null&&ge?.caretless&&(ce="end"),ce!=="cursor"||mt!=null){const Ct=mt??(ce==="start"?0:le.state.doc.content.size),lt=le.state.tr.insert(Ct,Ye);Fe?me(le,lt,Ct):le.dispatch(lt),k=!0;return}const{$from:it}=le.state.selection;let _t=it.depth;for(;_t>=1&&!["doc","amadeusColumnCell","blockquote"].includes(it.node(_t-1).type.name);)_t--;if(_t<1)return;const jt=(Ct,lt)=>{const Kt=Ne.near(Ct.doc.resolve(Math.min(lt,Ct.doc.content.size)),-1),cn=ge?.caretBack??0;Ct.setSelection(cn&&Kt.$from.parentOffset>=cn?Ne.create(Ct.doc,Kt.from-cn):Kt)};if(it.depth>_t&&it.parent.isTextblock&&it.parent.content.size===0){const Ct=le.state.tr,lt=cn=>{const Xt=Ct.doc.resolve(cn),zn=Xt.index(-1);return Xt.parent.isTextblock&&Xt.parent.content.size===0&&Xt.node(-1).canReplace(zn,zn+1,Ye)};let Kt=it.pos;if(!lt(Kt)){for(let cn=Ct.doc.resolve(Kt).depth;cn>0;cn--)if(Ct.doc.resolve(Kt).node(cn).type.name==="list_item"){Kt=Yd(Ct,Kt,["list_item"]);break}}if(lt(Kt)){const cn=Ct.doc.resolve(Kt),Xt=cn.before();Ct.replaceWith(Xt,cn.after(),Ye),Xs(Ct,Xt,Xt+Ye.size),jt(Ct,Xt+Ye.size),Fe?me(le,Ct,Xt):(le.dispatch(Ct.scrollIntoView()),le.focus()),k=!0;return}}const ht=it.before(_t),Mt=it.after(_t),ot=it.node(_t).textContent.trim()==="",an=ot?le.state.tr.replaceWith(ht,Mt,Ye):le.state.tr.insert(Mt,Ye);Xs(an,ot?ht:Mt,(ot?ht:Mt)+Ye.size),jt(an,(ot?ht:Mt)+Ye.size),Fe?me(le,an,ot?ht:Mt):(le.dispatch(an.scrollIntoView()),le.focus()),k=!0}),k},me=(re,ce,ge)=>{re.dispatch(Us(ce)),Dl(re,Math.min(ge+1,re.state.doc.content.size));const k=re.nodeDOM(ge);if(!(k instanceof HTMLElement))return;const J=k.getBoundingClientRect();(J.top<0||J.top>window.innerHeight-40)&&cs(k),qs(k.getBoundingClientRect())},he=(re,ce=!0)=>{let ge=null;return I()?.action(k=>{ge=db(k.get(vn),re,ce)}),ge},ze=re=>{re&&I()?.action(ce=>Au(ce.get(vn),re.id))},He=(re,ce,ge=!0)=>{if(ce?.cancelled())return;if(c?.()){ze(ce),yl(ce?.label??"");return}const k=()=>{ge||!ce?window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.insertPointLost")}})):mb(ce.label)};if(!a.current||!ce){k();return}let J=!1;I()?.action(le=>{const ve=le.get(Ir)(vr(re,t));J=fb(le.get(vn),ce.id,ve?.childCount?ve.content:null)}),J||k()},Te=async(re,ce,ge,k=!1)=>{try{const{base:J}=await wn.saveAttachment(e,re,ce,{mode:"vault",folder:ga(e)});He(`![[${k?J.replace(/\.md$/i,""):J}]]`,ge),X.getState().syncFdChildren(e)}catch{ze(ge)}},dt=b.useRef(()=>{}),sn=re=>{const ce=ee.current;if(!ce)return;const ge=re.run?void 0:Gd[re.scaffold];if(ge){ce.transform(ge)||Jd(re.label);return}ce.consume();const k=Zd;if(re.scaffold===k.template){window.dispatchEvent(new CustomEvent("amadeus:template-picker",{detail:{v4Path:e}}));return}if(re.scaffold===k.card){I()?.action(J=>Ge.current(J.get(vn)));return}if(re.scaffold===k.instructions||re.scaffold===k.agentTask||re.scaffold===k.prompt){const J=re.scaffold===k.instructions?"instructions":re.scaffold===k.agentTask?"task":"prompt";de(Qd(J,J==="instructions"?"":hs(ef())));return}if(re.scaffold===k.ai){I()?.action(J=>m.current?.(J.get(vn)));return}if(re.run){const J=he(re.label);(async()=>{try{const le=await re.run({pagePath:e,folder:ga(e)});if(le===""||le==null){ze(J);return}if(typeof le!="string")throw new Error(we("unipage.plugin.notString",{type:typeof le}));if(le.length>8192)throw new Error(we("unipage.plugin.tooLong"));if(Array.from(le).some(ve=>ve.charCodeAt(0)<32&&ve!==" "&&ve!==`
65
- `))throw new Error(we("unipage.plugin.controlChars"));He(le,J,!1),X.getState().syncFdChildren(e)}catch(le){if(ze(J),J?.cancelled())return;console.error("[plugin] slash item failed",le),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.plugin.failed",{label:re.label,err:le instanceof Error?le.message:String(le)}),error:!0}}))}})();return}if(re.scaffold===k.image){const J=document.createElement("input");J.type="file",J.accept="image/*",J.onchange=()=>{const le=J.files?.[0];if(!le)return;const ve=he(re.label);(async()=>{try{const Ye=new Uint8Array(await le.arrayBuffer()),{opts:Fe}=await Xa(),{base:mt}=await wn.saveAttachment(e,le.name||"image.png",Ye,Fe);He(`![[${mt}]]`,ve)}catch{ze(ve)}})()},J.click();return}if(re.scaffold===k.column){I()?.action(J=>{const le=J.get(vn),{$from:ve}=le.state.selection;if(ve.depth!==1){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.columnTopLevelOnly")}}));return}au(le,ve.before(1),ve.after(1),ve.node(1)),le.focus()});return}if(re.scaffold===k.page){const J=he(re.label);(async()=>{try{const le=X.getState(),ve=await le.createChildNote(e,we("amadeus.default.note"));He(`[[${ve.split("/").pop().replace(/\.md$/i,"")}]]`,J),le.loadPage(ve)}catch{ze(J)}})();return}if(re.scaffold===k.database){const J=we("amadeus.default.database");Te(`${J}.db`,new TextEncoder().encode(Yc(md(J))),he(re.label));return}if(re.scaffold===k.drawing){Te(`${tf(we("unipage.file.drawing"))}.excalidraw.md`,new TextEncoder().encode(pd(gd)),he(re.label),!0);return}if(re.scaffold===k.noteview){const J=he(re.label);(async()=>{const le=ga(e);let ve=null;for(let Fe=1;Fe<=20&&ve===null;Fe++)try{ve=await wn.createFolder(le,Fe===1?we("unipage.file.noteView"):we("unipage.file.noteViewN",{n:Fe}))}catch{}if(ve===null){ze(J);return}const Ye=we("unipage.file.untitledView");await Te(`${Ye}.db`,new TextEncoder().encode(Yc(yd(Ye,ve))),J)})();return}if(re.scaffold===k.linkdb){oe(!0);return}if(re.scaffold===k.bookmark){const J=he(re.label,!1);qa(we("unipage.bookmark.title"),"",{label:we("unipage.bookmark.label")}).then(le=>{const ve=le?.trim();ve&&/^https?:\/\/\S+$/i.test(ve)?He(ve,J,!1):ze(J)});return}if(re.scaffold===k.embed){const J=he(re.label,!1);(async()=>{let le="";try{const Fe=/!?\[\[([^\]\n]+)\]\]/.exec(await navigator.clipboard.readText());Fe&&(le=Fe[1].trim())}catch{}const Ye=(await qa(we("unipage.embed.title"),le,{label:we("unipage.embed.label"),confirmLabel:we("unipage.embed.confirm")}))?.trim().replace(/^!?\[\[/,"").replace(/\]\]$/,"").trim();Ye?He(`![[${Ye}]]`,J,!1):ze(J)})();return}de(re.scaffold,"cursor",re.key==="math"?{caretBack:3}:void 0)};return dt.current=sn,f.jsxs(f.Fragment,{children:[f.jsx(Xd,{initial:vr(n,t),onChange:re=>o(_r(re,t)),keys:Db,saveImage:ke,saveFiles:rt,onOpenWiki:(re,ce)=>{X.getState().openWikiLink(re,e,ce??{split:!0})},getPageNames:()=>X.getState().pages,slashOpsRef:ee,onSlashPick:sn,getFiles:()=>jm()?X.getState().files:[],isWikiResolved:re=>!!gs(re,X.getState().pages,e)||!!Tm(re,X.getState().files,e),wikiIcon:re=>{const ce=gs(re,X.getState().pages,e);return ce?X.getState().icons[ce]:void 0},focusPlace:p,onFocused:h,unified:!0,attachmentPagePath:e,extraPlugins:d,readOnly:R,onAskTangu:T,aiMenu:w}),q&&f.jsx(cr,{children:f.jsx(Ud,{onClose:()=>oe(!1),onPick:re=>{oe(!1),c?.()?yl(we("mdblock.slash.linkdb")):de(`![[${re}]]`)}})})]})}function kl(e){e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)}function Pb(e){const t=e.selectionEnd;if(t>=e.value.length)return!0;const n=getComputedStyle(e),o=document.createElement("div");for(const i of["fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","wordSpacing","lineHeight","textTransform","textIndent","tabSize","paddingLeft","paddingRight","borderLeftWidth","borderRightWidth","boxSizing","wordBreak","overflowWrap"])o.style[i]=n[i];Object.assign(o.style,{position:"absolute",visibility:"hidden",left:"-99999px",top:"0",width:`${e.offsetWidth}px`,whiteSpace:"pre-wrap",borderStyle:"solid",borderColor:"transparent"});const r=document.createElement("span"),s=document.createElement("span"),c=String.fromCodePoint(e.value.codePointAt(t)??32);r.textContent=c,s.textContent="​",o.append(e.value.slice(0,t),r,e.value.slice(t+c.length),s),document.body.appendChild(o);const a=r.offsetTop>=s.offsetTop;return o.remove(),a}function Fb({path:e,icon:t,cover:n,onSetIcon:o,onSetCover:r,onRename:s,onDetachedRename:c,onEnterBody:a,focusSignal:i,compact:d=!1,readOnly:p=!1}){const{t:h}=tn(),M=Rl(),R=(e.split("/").pop()??e).replace(/\.md$/i,""),T=Wm.test(R)?"":R,[w,S]=b.useState(T),[I,X]=b.useState(null),[ee,q]=b.useState(null),oe=b.useRef(null),Re=b.useRef(null),Ge=b.useRef(c);Ge.current=c,b.useEffect(()=>{S(T),Re.current=null},[e]),b.useLayoutEffect(()=>()=>{const de=Re.current;Re.current=null,de!=null&&Ge.current(de)},[]),b.useLayoutEffect(()=>{kl(oe.current)},[w]),b.useEffect(()=>{const de=oe.current;if(!de)return;let me=de.clientWidth;const he=new ResizeObserver(()=>{de.clientWidth!==me&&(me=de.clientWidth,kl(de))});return he.observe(de),()=>he.disconnect()},[]),b.useEffect(()=>{if(!i)return;const de=oe.current;if(de){de.focus();const me=de.value.length;de.setSelectionRange(me,me)}},[i]);const m=b.useRef(null),ke=b.useRef(!1),rt=()=>{const de=m.current;if(m.current=null,Re.current=null,ke.current){ke.current=!1,S(T);return}const me=w.trim();me&&me!==R?s(me,de).then(he=>{he||S(T)}):S(T)};return p?f.jsxs("div",{className:"amx-title-wrap amx-title-ro",children:[t&&f.jsx("span",{className:"amx-title-bigicon","aria-hidden":!0,children:t}),f.jsx("div",{className:"amx-title-row",children:f.jsx("h1",{className:"amx-title-input amx-title-static",children:T||R})})]}):f.jsxs("div",{className:"amx-title-wrap",children:[!d&&t&&f.jsx("button",{className:"amx-title-bigicon",title:h("unipage.title.iconAction"),onClick:de=>{const me=de.currentTarget.getBoundingClientRect();X({x:me.left,y:me.bottom+6})},children:t}),!d&&(!t||!n)&&f.jsxs("div",{className:"amx-title-actions",children:[!t&&f.jsxs("button",{onClick:()=>o(Vm()),children:[f.jsx(Km,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),h("unipage.title.addIcon")]}),!n&&f.jsxs("button",{onClick:de=>{const me=de.currentTarget.getBoundingClientRect();q({x:me.right,y:me.bottom+6})},children:[f.jsx(Em,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),h("unipage.title.addCover")]})]}),f.jsx("div",{className:"amx-title-row",children:f.jsx("textarea",{ref:oe,className:"amx-title-input",rows:1,spellCheck:M,value:w,placeholder:"New Page",onChange:de=>{const me=de.target.value.replace(/[\r\n]+/g," ");Re.current=me,S(me)},onBlur:rt,onKeyDown:de=>{if(de.nativeEvent.isComposing||de.keyCode===229)return;const me=de.currentTarget;if(de.key==="Tab"){de.preventDefault();return}const he=me.selectionStart===me.selectionEnd,ze=he&&me.selectionEnd===me.value.length,He=!de.shiftKey&&!de.altKey&&!de.metaKey&&!de.ctrlKey,Te=de.key==="ArrowDown"&&He&&he&&Pb(me);(de.key==="Enter"||de.key==="ArrowRight"&&He&&ze||Te)&&(de.preventDefault(),m.current=de.key==="Enter"?"enter":"move",me.blur(),a(de.key==="Enter"?"enter":"move")),de.key==="Escape"&&(Re.current=null,ke.current=!0,S(T),me.blur())}})}),I&&f.jsx(Hm,{x:I.x,y:I.y,current:t,onPick:de=>{o(de),X(null)},onClose:()=>X(null)}),ee&&f.jsx(qm,{page:e,x:ee.x,y:ee.y,onApply:de=>r(de),onClose:()=>q(null)})]})}function Ob({path:e,initial:t,diskRaw:n,probe:o,onRenamed:r,onCanvasMode:s,historyRef:c,filesRef:a,mdRef:i,onUnlock:d,compact:p=!1,readOnly:h=!1,hardBreaks:M=!1}){const R=e.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),T=lc(),w=T.getState().vaultRoot,S=b.useContext(sm),I=am(),X=S??I,ee=cm(l=>im(l,X)),q=h?"wysiwyg":ee,{t:oe}=tn(),Re=Rl(),Ge=b.useRef(null);if(!Ge.current){const l=Hr(n??t),{fmText:g,body:v}=Sr(n==null?l.text:Hr(t).text);Ge.current={fm:g,body:v,lastSaved:l.text,eol:l.eol,pending:!1,timer:null,reconcileBusy:0,unpreserved:null,preserved:new Set,failed:!1,retryTimer:null,retryN:0,stashed:null,writing:0,dead:!1,retired:!1,sawRows:!1,ownedCards:new Set,chain:Promise.resolve(),readOnly:h,slot:S,peerPatch:null}}const m=Ge.current,ke=b.useRef(0),rt=b.useRef(null),de=b.useRef(()=>{rt.current?.()}).current,me=()=>{ke.current=performance.now(),pi(de)},he=b.useRef(!1);b.useEffect(()=>{S!=null&&S===I&&me()},[S,I]);const[ze]=b.useState(()=>new Set),He=()=>{for(const l of[...ze])l()},[Te,dt]=b.useState(0),[sn,re]=b.useState(0),ce=b.useRef(null),ge=b.useRef(q==="source"),k=b.useMemo(()=>({get current(){return ge.current?null:ce.current}}),[]);if(ge.current!==(q==="source")){if(q==="source"){const l=ce.current?.serializeNow();l!=null&&(m.body=l)}ge.current=q==="source"}const J=b.useRef(null),le=b.useRef(null),[ve,Ye]=b.useState(null),[Fe,mt]=b.useState(()=>{if(Vr())return!1;const l=lm(w,e);return l?l==="canvas":_n(dn(m.fm))?.mode==="canvas"}),[it,_t]=b.useState(0),jt=b.useRef(!1),ht=b.useRef(Fe);ht.current=Fe;const Mt=b.useRef(!1),ot=dn(m.fm),an=b.useMemo(()=>_n(ot),[ot]),Ct=an?.main??{x:0,y:0,w:Ko},lt=()=>{const l=!Fe;if((k.current?.hasFocus()??!1)&&(l?_t(v=>v+1):jt.current=!0),l){const v=le.current?.closest(".amx-pane");v&&fi(w,e,v.scrollTop)}ht.current=l,Mt.current=!0,km(w,e,l?"canvas":"doc"),mt(l),dn(m.fm)!=null&&(Tt(),Gt())},Kt=b.useRef(lt);Kt.current=lt,rt.current=q==="source"?null:()=>Kt.current(),b.useEffect(()=>(pi(de),()=>um(de)),[de]);const cn=b.useRef(l=>k.current?.applySlashItem(l)).current;b.useEffect(()=>(ma(cn),()=>{nf()===cn&&ma(null)}),[cn]),b.useEffect(()=>(s?.({on:Fe,toggle:()=>Kt.current(),...Fe&&q!=="source"&&!h?{exportCanvas:()=>zn.current?.()}:{}}),()=>s?.(null)),[Fe,s,q,h]);const Xt=b.useRef(null),zn=b.useRef(null);b.useEffect(()=>{if(!c)return;const l=E=>{if(m.readOnly)return!1;if(ht.current&&Xt.current)return Xt.current(E);const L=Wt();return!!L&&(E==="undo"?Ka:jl)(L.state,L.dispatch)},v={undo:()=>l("undo"),redo:()=>l("redo"),indent:E=>{const L=Wt();return!m.readOnly&&!!L&&Pe.indent(L,E)}};return c.current=v,()=>{c.current===v&&(c.current=null)}},[c]);const Zn=l=>{const g=dn(m.fm);if(g!=null&&_n(g)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.canvasElementsFailed"),error:!0}}));return}m.fm=ds(m.fm,go(m.fm),lx(g,l)),dt(v=>v+1),Kn(),Gt()},mr=l=>{const g=dn(m.fm);if(g!=null&&_n(g)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.canvasTreeFailed"),error:!0}}));return}m.fm=ds(m.fm,go(m.fm),dx(g,l)),dt(v=>v+1),Kn(),Gt()},nn=l=>{const g=dn(m.fm);if(g!=null&&_n(g)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.canvasMainFailed"),error:!0}}));return}m.fm=ds(m.fm,go(m.fm),ux(g,l)),dt(v=>v+1),Kn(),Gt()},Xn=b.useMemo(()=>({log:[],future:[]}),[e]),$n=Fe&&q!=="source";b.useEffect(()=>{Ye(le.current)},[]),b.useEffect(()=>{const l=J.current?.closest(".amx-pane");if(l)return l.classList.toggle("amx-canvas-pane",$n),()=>l.classList.remove("amx-canvas-pane")},[$n]),b.useEffect(()=>{if(Fe)return;const l=le.current?.closest(".amx-pane");if(!l)return;const g=dm(w,e);let v=!1,E=0;const L=performance.now()+1500,Y=()=>{if(l.scrollTop=g,l.scrollTop!==g&&performance.now()<L){E=requestAnimationFrame(Y);return}v=!0};E=requestAnimationFrame(Y);const _=()=>{cancelAnimationFrame(E),v=!0},ie=()=>{v&&fi(w,e,l.scrollTop)};return l.addEventListener("scroll",ie,{passive:!0}),l.addEventListener("wheel",_,{passive:!0}),l.addEventListener("pointerdown",_),l.addEventListener("keydown",_),()=>{cancelAnimationFrame(E),l.removeEventListener("scroll",ie),l.removeEventListener("wheel",_),l.removeEventListener("pointerdown",_),l.removeEventListener("keydown",_)}},[Fe,e,w]),b.useEffect(()=>{if(Fe||!jt.current)return;jt.current=!1;let l=0;const g=requestAnimationFrame(()=>{l=requestAnimationFrame(()=>k.current?.revealSelection())});return()=>{cancelAnimationFrame(g),cancelAnimationFrame(l)}},[Fe]);const[Qn,Mo]=b.useState(()=>{const l=Ks;return l?.path===e&&l.scope===S?(Ks=null,Date.now()-l.at<1e4?l.req:null):null}),Yo=b.useRef(Qn);Yo.current=Qn;const Xo=b.useRef(null),[Cn,An]=b.useState(null),[Ln,yo]=b.useState(null),xo=b.useRef(0);b.useEffect(()=>{Cn||(yo(null),clearTimeout(xo.current))},[Cn]);const at=(l,g)=>{if(clearTimeout(xo.current),Ln&&!g)return;const v=l.closest(".unified-block-menu");if(!v)return;const E=v.getBoundingClientRect(),L=l.getBoundingClientRect(),Y=E.right+4+E.width>window.innerWidth-8;yo({x:Y?E.left-4-E.width:E.right+4,y:L.top-5,anchorTop:L.bottom+5,focus:g})},It=()=>{clearTimeout(xo.current),xo.current=window.setTimeout(()=>{document.querySelector(".unified-block-submenu")?.contains(document.activeElement)&&document.querySelector('.unified-block-menu [data-sub="turnInto"]')?.focus(),yo(null)},180)};b.useLayoutEffect(()=>{if(!Ln?.focus)return;let l=0,g=0;const v=()=>{const E=document.querySelector(".unified-block-submenu button");E?.focus(),document.activeElement!==E&&++l<10&&(g=requestAnimationFrame(v))};return v(),()=>cancelAnimationFrame(g)},[Ln]);const bo=b.useRef(null),[ao,Uo]=b.useState(null),zo=b.useRef(()=>{}),Wn=b.useRef({tree:()=>({}),detach:()=>{},minted:()=>{}}),Pe=b.useMemo(()=>Zy({onMenu:l=>{const g=Pe.getView();bo.current=g?{doc:g.state.doc,sel:g.state.selection}:null,An({...l,cell:$b(g,l.x,l.y)})},onBlocksDeleted:l=>zo.current(l),canvasTree:()=>Wn.current.tree(),onCardDetach:l=>Wn.current.detach(l),onCardsMinted:l=>Wn.current.minted(l)}),[]),Wt=()=>ge.current?null:Pe.getView(),[y]=b.useState(()=>Jh(Wt)),$=l=>{const g=Pe.getView();g&&Qy(e,Ji(l),Ji(g.state.doc.content))};zo.current=$,Wn.current={tree:()=>Vt(_n(dn(m.fm))?.tree),detach:l=>{const g=Vt(_n(dn(m.fm))?.tree);let v=!1;for(const E of l)E in g&&(delete g[E],v=!0);v&&mr(g)},minted:l=>{for(const g of l)m.ownedCards.add(g)}};const P=b.useRef({vaultRoot:w,path:e});P.current={vaultRoot:w,path:e};const D=b.useRef(!1),V=b.useRef(()=>{}),[U,se]=b.useState({count:0,index:0}),G=b.useRef(()=>{}),Q=w?`${w.replace(/[\\/]+$/,"")}/${e}`:e,H=b.useSyncExternalStore(fm,()=>!h&&mm(Q));G.current=l=>{const g=l.current==null?0:l.changes.findIndex(v=>v.id===l.current)+1;se(v=>v.count===l.changes.length&&v.index===g?v:{count:l.changes.length,index:g})};const Me=b.useMemo(()=>[...Pe.plugins,...cy,...Qg(()=>Ma(go(m.fm)),()=>{m.sawRows=!0}),...hx,...ax(()=>_n(dn(m.fm)),()=>Ma(go(m.fm)),l=>{for(const g of l)m.ownedCards.add(g)}),...Cy({path:e,readOnly:h,alive:()=>!m.dead&&!m.retired&&!m.readOnly&&!ge.current,flush:async()=>{if(m.dead||m.retired||m.readOnly||ge.current)throw new Error(we("documentTask.sourceGone"));if(Tt(),He(),m.timer&&(clearTimeout(m.timer),m.timer=null),await en(!0),m.dead||m.retired||m.failed)throw new Error(we("documentTask.sourceGone"))}}),Gh(),...lb(),...gx(()=>ht.current),...kx(Xn),...yx(),...vx(()=>_n(dn(m.fm))),...eb(G),...gb({spaceTrigger:()=>Ch()&&D.current,onSpace:V}),...Gm,...Jm,...Ep(()=>P.current),...Zh(),...Qh(()=>$t.current()),...eg({where:()=>P.current,restore:()=>ut.current(),focus:()=>yt.current()}),...M?_d:[]],[Pe,e,h,M]);b.useEffect(()=>{if(!Cn)return;const l=E=>{E.target?.closest?.(".ctx-menu")||An(null)},g=E=>{const L=document.querySelector(".unified-block-menu"),Y=document.querySelector(".unified-block-submenu"),_=!!Y&&Y.contains(document.activeElement),ie=!!L&&L.contains(document.activeElement)||_,C=L?.querySelector('[data-sub="turnInto"]');if(E.key==="Escape"){if(E.stopPropagation(),_){yo(null),C?.focus();return}An(null),Pe.getView()?.focus();return}if(!L||E.isComposing)return;const fe=!E.metaKey&&!E.ctrlKey&&!E.altKey&&!E.shiftKey;if(fe&&_&&E.key==="ArrowLeft"){E.preventDefault(),E.stopPropagation(),yo(null),C?.focus();return}if(fe&&!_&&E.key==="ArrowRight"&&C&&document.activeElement===C){E.preventDefault(),E.stopPropagation(),at(C,!0);return}if(fe&&["ArrowDown","ArrowUp","Home","End"].includes(E.key)){E.preventDefault(),E.stopPropagation();const Se=[...(_?Y:L).querySelectorAll('button:not([aria-disabled="true"])')],Be=Se.indexOf(document.activeElement),Ue=Se.length,tt=E.key==="Home"?0:E.key==="End"?Ue-1:Be<0?E.key==="ArrowUp"?Ue-1:0:(Be+(E.key==="ArrowDown"?1:-1)+Ue)%Ue;Se[tt]?.focus();return}ie&&(E.key==="Enter"||E.key===" ")||["Shift","Meta","Control","Alt","CapsLock"].includes(E.key)||(An(null),ie&&(E.preventDefault(),Pe.getView()?.focus()))};let v=0;if(Cn.keyboard){let E=0;const L=()=>{const Y=document.querySelector(".unified-block-menu");if(!Y){++E<10&&(v=requestAnimationFrame(L));return}const _=Cn.focus==="turnInto"?Y.querySelector('[data-sub="turnInto"]'):null;if(_){at(_,!0);return}Y.querySelector("button")?.focus()};v=requestAnimationFrame(L)}return window.addEventListener("pointerdown",l,!0),window.addEventListener("contextmenu",l,!0),window.addEventListener("keydown",g,!0),()=>{cancelAnimationFrame(v),window.removeEventListener("pointerdown",l,!0),window.removeEventListener("contextmenu",l,!0),window.removeEventListener("keydown",g,!0)}},[Cn]);const Ie=l=>{const g=bo.current;return bo.current=null,g?l.state.doc!==g.doc?(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.menu.stale")}})),!1):(l.state.selection.eq(g.sel)||l.dispatch(l.state.tr.setSelection(g.sel)),!0):!0},Oe=l=>{An(null);const g=Pe.getView();if(!g||!Ie(g))return;const v=g.state.selection;v instanceof Ee&&(l(g,v),g.focus())},_e=(l,g)=>{An(null);const v=Pe.getView();if(!v||!Ie(v))return;const E=Pe.topRangeOf(v);E?l(v,E):v.state.selection instanceof Ee&&g(v,v.state.selection),v.focus()},Ke=l=>{const g=l.state.selection,v=Pe.topRangeOf(l)??(g instanceof Ee?{from:g.from,to:g.to}:null);return v&&{from:v.from,to:fs(l.state,v.from,v.to)}},We=!h&&!!Ar()?.askInChat,Ve=(l,g,v)=>{const E=Cb(l.state.doc,g,v,e);E&&Ar()?.askInChat?.([iu(oc(l.state.doc),e),E].filter(Boolean).join(`
66
-
67
- `).slice(0,2e4))},Xe=!h&&!!Ar()?.complete;D.current=Xe;const Ut=Va(l=>l.selectionActions),[pt,gt]=b.useState(null),Un=["improve","fix","shorter","longer","summarize","continue","custom"].map(l=>({id:l,label:oe(`inlineai.action.${l}`)})),Pt=(l,g)=>{const v=Pe.getView()?.state.doc,E=v?v.textBetween(Math.min(l,v.content.size),Math.min(g,v.content.size),`
68
- `,"").length:g-l;return Cp(Ut,{view:"note",editable:!0,length:E}).map(L=>{const Y=Om(L.item.icon);return{id:Sp(L),label:L.item.title,icon:Y?f.jsx("span",{className:"selbar-ico",children:Y}):void 0}})},Qt=e.split("/").pop().replace(/\.md$/i,""),Gn=(l,g)=>{if(!Xe)return;const v=l.state.selection,E=g==="prompt",L=E?v.head:v.from,Y=E?v.head:v.to;if(!E&&Y<=L)return;const _=g.startsWith("plugin:")?g.slice(7):void 0,ie=_?Ut.find(tt=>`${tt.pluginId}:${tt.item.id}`===_):void 0,C=l.state.doc.textBetween(L,Y,`
69
- `,"");if(ie?.item.output==="none"){const tt=k.current?.serializeMd(l.state.doc.slice(L,Y).content)??C;wi(ie,{text:C,markdown:tt,pagePath:e,view:"note",editable:!0,source:{path:e,title:Qt}}).catch(At=>window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("selbar.failed",{title:ie.item.title,e:String(At?.message||At)})}})));return}yb(l,L,Y);const fe=l.coordsAtPos(L),Se=l.coordsAtPos(Y),Be=_||E?E?"prompt":"custom":g,Ue=_?ie?.item.title??oe("inlineai.label"):oe(E?"inlineai.label":`inlineai.action.${g}`);gt({key:Date.now(),x:fe.left,y:Se.bottom+6,top:fe.top-6,title:Ue,hasSelection:!E,askFirst:E||g==="custom",action:Be,plugin:_,...g==="translate"?{language:vi(C)}:{}})};V.current=l=>Gn(l,"prompt");const $o=l=>async(g,v,E)=>{const L=Pe.getView(),Y=L?bl(L):null;if(!L||!Y)throw new Error(we("unipage.toast.insertPointLost"));const _=Y.to>Y.from?k.current?.serializeMd(L.state.doc.slice(Y.from,Y.to).content)??Y.text:"";if(l.plugin){const Be=Va.getState().selectionActions.find(Ue=>`${Ue.pluginId}:${Ue.item.id}`===l.plugin);if(!Be)throw new Error(we("selbar.err.gone"));return{text:await wi(Be,{text:Y.text,markdown:_,pagePath:e,view:"note",editable:!0,source:{path:e,title:Qt},signal:E,onDelta:Ue=>{typeof Ue=="string"&&v(Ue)}})}}const ie=Ar();if(!ie?.complete)throw new Error(we("inlineai.unavailable"));const{before:C,after:fe}=xb(L.state.doc,Y.from,Y.to),Se=l.action==="prompt"?g?"custom":"continue":l.action;return ie.complete({action:Se,...g?{instruction:g}:{},..._?{selection:_}:{},...C?{before:C}:{},...fe?{after:fe}:{},title:Qt,pagePath:e,pageInstructions:oc(L.state.doc),...Se==="translate"?{language:l.language??vi(Y.text)}:{}},{signal:E,onDelta:v})},jr=()=>{gt(null);const l=Pe.getView();l&&(xl(l),l.focus())},Bn=(l,g)=>{const v=Pe.getView(),E=v?bl(v):null,L=k.current?.parseMd(g);if(gt(null),!v||!E||!L){v&&xl(v),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.insertPointLost")}}));return}const Y=vb(v,E,L,l);v.focus(),Tt(),Gt(),l==="replace"&&Y==="below"&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("inlineai.targetChanged")}}))},pr=()=>{const l=Pe.getView();if(!l)return;const g=sb(l),v=g?J.current?.querySelector(`[data-agent-change="${g.id}"]`):null;v instanceof HTMLElement&&cs(v,48)},Ao=()=>{const l=Pe.getView();if(!l)return;const{skipped:g}=ob(l);Tt(),Gt(),g&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("agentchg.skipped",{n:String(g)})}}))},In=(l,g)=>{let v=!0;_e((E,L)=>{v=Ql(E,L.from,L.to,l)},(E,L)=>{const Y=ji(E,L.from,L.to,l);if(Y!=null){v=Y;return}L.node.type.spec.code&&rf(E,L.from,l)||(E.dispatch(E.state.tr.setSelection(Ne.near(E.state.doc.resolve(L.from+1)))),v=na(E,l,null))}),v||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("mdblock.turn.failed",{kind:g})}}))},co=(l,g)=>{let v=!0;_e((E,L)=>{v=l==="code"?tc(E,L.from,L.to):Ti(E,L.from,L.to,!0)},(E,L)=>{v=l==="code"?ji(E,L.from,L.to,"code")??tc(E,L.from,L.to):Ti(E,L.from,L.to,!1)}),v||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("mdblock.turn.failed",{kind:g})}}))},Go=()=>{const l=Pe.getView();if(!l)return[];const g=[];if(!cc(l)){const E=(L,Y,_,ie)=>{const C=oe(_);g.push({k:L,icon:Y,label:C,run:()=>ie(C)})};E("text",ki,"unipage.menu.text",L=>In({kind:"text"},L)),E("h1",Wp,"unipage.menu.h1",L=>In({kind:"heading",level:1},L)),E("h2",Xp,"unipage.menu.h2",L=>In({kind:"heading",level:2},L)),E("h3",Gp,"unipage.menu.h3",L=>In({kind:"heading",level:3},L)),E("bullet",Rm,"unipage.menu.bullet",L=>In({kind:"bullet"},L)),E("ordered",eh,"unipage.menu.ordered",L=>In({kind:"ordered"},L)),E("task",Dm,"unipage.menu.task",L=>In({kind:"task"},L)),E("quote",Lm,"unipage.menu.quote",L=>In({kind:"quote"},L)),E("callout",Im,"unipage.menu.callout",L=>co("callout",L)),E("fold",Hp,"unipage.menu.fold",L=>In({kind:"fold"},L)),E("code",Ap,"unipage.menu.code",L=>co("code",L))}const v=l.state.selection;if(v instanceof Ee&&!["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(v.node.type.name)){const E=l.state.doc.resolve(v.from);let L=!1;for(let Y=E.depth;Y>=1;Y--)E.node(Y).type.name==="amadeusColumnCell"&&(L=!0);L||g.push({k:"card",icon:Wa,label:oe("unipage.menu.card"),run:()=>Oe(Y=>{eo(Y)})})}return g},No=()=>{const l=Pe.getView();if(!l||Pe.topRangeOf(l))return null;const g=l.state.selection;return g instanceof Ee?g.node.type.name==="list_item"?g.node.attrs.checked!=null?"task":g.$from.parent.type.name==="ordered_list"?"ordered":"bullet":yg(g.node):null},eo=l=>{const g=()=>(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.cardUnavailable")}})),!1);if(!(l.state.selection instanceof Ee)){const{$from:Be}=l.state.selection;for(let tt=Be.depth;tt>=1;tt--)if(Be.node(tt).type.name==="list_item")return g();let Ue=Be.depth;for(;Ue>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard"].includes(Be.node(Ue-1).type.name);)Ue--;if(Ue<1)return!1;l.dispatch(l.state.tr.setSelection(Ee.create(l.state.doc,Be.before(Ue))))}const v=l.state.selection,E=l.state.doc.resolve(v.from),L=E.depth>=1?E.node(E.depth):null,Y=L?.type.name==="amadeusCanvasCard"?String(L.attrs.anchor):"",_=Vt(_n(dn(m.fm))?.tree);let ie=0;l.state.doc.forEach(Be=>{Be.type.name==="amadeusCanvasCard"&&ie++});const C=Y?(Number(L.attrs.x)||0)+(Number(L.attrs.w)||Zt)+80:Ct.x+Ct.w+80,fe=Y?(Number(L.attrs.y)||0)+Er(_,Y).length*72:Ct.y+ie*72,Se=Cu(l,Math.round(C),Math.round(fe),Y?{parent:Y,tree:_}:void 0);return Se?(m.ownedCards.add(Se),Tt(),Gt(),Y&&mr(Kr(Vt(_n(dn(m.fm))?.tree),Se,Y)),!ht.current&&!Y&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.cardMade")}})),!0):g()},xn=()=>{const l=Sr(m.lastSaved);if(l.fmText!==m.fm&&(m.peerPatch==null||Ca(l.fmText,m.peerPatch)!==m.fm))return!1;if(l.body===m.body)return!0;if(go(m.fm)!=null||dn(m.fm)!=null)return!1;const g=k.current?.canonical(l.body);return g!=null&&g===m.body},Jo=b.useRef(null),To=()=>{Jo.current?.()},[Zo,io]=b.useState(!1),Yn=async l=>{const g=$r(l);if(m.preserved.has(g))return;const v=await wa(e,Fo(l,m.eol));m.preserved.add(g),Lh(e,v,!m.readOnly&&mi(Q,l)),T.getState().refreshPages()},hr=async l=>{const g=await wa(e,Fo(l,m.eol));Ih(e,g),T.getState().refreshPages()},vo=()=>{if(m.gone==null||m.readOnly)return;Tt();const l=jn(m.fm,m.body);l!==m.gone&&(m.gone=l,jo(l))},jo=async l=>{try{await hr(l)}catch{Io(w,e,l,m.lastSaved,m.slot),Fh(e,l)}},gr=l=>{if(m.retired||(m.stashed=jn(m.fm,m.body),Io(w,e,m.stashed,m.lastSaved,m.slot)),m.failed||(m.failed=!0,io(!0),ka(e,l)),m.retryTimer||m.dead||m.retired)return;const g=$i[Math.min(m.retryN,$i.length-1)];m.retryN++,m.retryTimer=setTimeout(()=>{m.retryTimer=null,!(m.dead||m.retired||!m.pending)&&(m.reconcileBusy||en())},g)},lo=l=>{m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null),m.retryN=0,m.failed&&(m.failed=!1,io(!1)),m.stashed!=null&&(l==null||m.stashed===l||jn(m.fm,m.body)===l)&&(Zr(w,e,m.stashed,m.slot),m.stashed=null)},wo=l=>{m.peerPatch=null,lo(l),hd(e,m)},en=(l=!1)=>{if(m.readOnly)return Promise.resolve();const g=async()=>{let L=0;for(;!m.retired;){const Y=jn(m.fm,m.body);if(Y===m.lastSaved){m.pending=!1,lo();return}let _;try{m.unpreserved!=null&&m.unpreserved!==Y&&await Yn(m.unpreserved),m.unpreserved=null,_=await wn.writeTextFile(e,Fo(Y,m.eol),{base:$r(Fo(m.lastSaved,m.eol))})}catch(ie){if(m.pending=!0,gr(ie),l)throw ie;return}if(_&&_.ok===!1&&_.current==null){m.retired||(m.retired=!0,m.pending=!1,Tt(),m.gone=jn(m.fm,m.body),await jo(m.gone));return}if(_&&_.ok===!1&&_.current!=null){const ie=Hr(_.current);m.eol=ie.eol;const C=ie.text;if(C===Y){m.lastSaved=Y;continue}if(++L>3){const fe=new Error("The note kept changing on disk while saving");if(m.pending=!0,gr(fe),l)throw fe;return}if(xn()){m.pending=!1,To();return}m.unpreserved=C,m.lastSaved=C;continue}if(m.lastSaved=Y,T.getState().bumpLinkGraph(),jn(m.fm,m.body)===Y&&(m.pending=!1),wo(Y),!l)return}},v=async()=>{m.writing++;try{await g()}finally{m.writing--}},E=m.chain.then(v,v);return m.chain=E.catch(()=>{}),E},Qo=()=>{const l=Wt();if(!l)return;const g=go(m.fm),v=ty(l.state.doc);let E=g;v!=null?(E=v,m.sawRows=!0):m.sawRows&&g!=null&&Ma(g)!=null&&(E=null);const L=ix(l.state.doc,dn(m.fm),Mt.current?ht.current?"canvas":"doc":null,m.ownedCards),Y=dn(m.fm);m.fm=ds(m.fm,E,L),dn(m.fm)!==Y&&dt(_=>_+1)},Tt=()=>{const l=k.current?.serializeNow();l!=null&&(m.body=l,Qo())},Gt=()=>{m.dead||m.retired||h||!m.writing&&jn(m.fm,m.body)===m.lastSaved||(m.pending=!0,m.timer&&clearTimeout(m.timer),m.timer=setTimeout(()=>{m.timer=null,!m.reconcileBusy&&en()},Rb))},[uo,fo]=b.useState(null),Kn=()=>{fo(l=>l==null?l:jn(m.fm,m.body))},A=(l,g=!0)=>{h||(m.fm=Ca(m.fm,l),dt(v=>v+1),Kn(),g?(m.pending=!0,en().then(()=>{const v=Mn.getState();v.refreshPages(),v.refreshIcons()})):Gt())};b.useEffect(()=>{pm(document)},[]);const[F,ue]=b.useState(null);b.useEffect(()=>{const l=g=>{const v=document.elementFromPoint(g.clientX,g.clientY)??g.target,E=v?.tagName==="IMG"?v:null;if(!E||!E.closest(".unified-body")||E.closest(".app-ref"))return;const L=E.currentSrc||E.src;L&&(g.preventDefault(),g.stopPropagation(),ue(L))};return document.addEventListener("dblclick",l,!0),()=>document.removeEventListener("dblclick",l,!0)},[]),li(!!F,()=>ue(null)),li(!!Cn&&!h,()=>An(null)),b.useEffect(()=>{if(!F)return;const l=g=>{g.key==="Escape"&&ue(null)};return window.addEventListener("keydown",l,!0),()=>window.removeEventListener("keydown",l,!0)},[F]),b.useEffect(()=>{const l=async()=>{m.reconcileBusy++;try{await Cm(),await m.chain;const v=await wn.readTextFile(e);if(v==null||m.dead||m.retired)return;const E=Hr(v);m.eol=E.eol;const L=E.text;if(L===m.lastSaved&&!m.pending)return;if(m.pending&&Tt(),m.pending&&!xn()){L!==m.lastSaved&&L!==jn(m.fm,m.body)&&(m.unpreserved=L),m.lastSaved=L;return}const{fmText:Y,body:_}=Sr(L),ie=go(Y)!==go(m.fm)||dn(Y)!==dn(m.fm);if(m.fm=Y,m.peerPatch=null,dt(C=>C+1),_!==m.body){m.ownedCards.clear();const C=!m.readOnly&&mi(Q,v);(k.current??(ge.current?ce.current:null))?.applyBody(_,C)?m.body=_:(m.body=_,re(fe=>fe+1))}else ie&&(m.ownedCards.clear(),re(C=>C+1));m.lastSaved=L,m.pending=!1,lo(),Kn()}finally{m.reconcileBusy--,m.reconcileBusy===0&&m.pending&&en()}};Jo.current=()=>{l()};const g=wn.onExternalChange?.(v=>{v===e&&l()});return l(),()=>{Jo.current=null,g?.()}},[e]),b.useEffect(()=>{const l=()=>{if(Tt(),He(),m.timer&&clearTimeout(m.timer),m.timer=null,m.readOnly)return;if(m.retired){m.gone!=null&&vo(),m.stashed!=null&&Zr(w,e,m.stashed,m.slot),m.stashed=null;return}const v=jn(m.fm,m.body);if(!m.writing&&v===m.lastSaved){lo();return}if(!m.writing&&xn()){m.pending=!1;return}m.stashed=v,Io(w,e,v,m.lastSaved,m.slot),en()},g=v=>{l(),m.failed&&m.pending&&!_h()&&(v.preventDefault(),v.returnValue="")};return window.addEventListener("beforeunload",g),()=>{m.dead=!0,window.removeEventListener("beforeunload",g),l();const v=Xo.current,E=Pe.getView();v&&E&&(v.doc=E.state.doc.toJSON(),v.anchor=E.state.selection.anchor,v.head=E.state.selection.head)}},[e]),b.useEffect(()=>{const l=()=>{!m.failed||!m.pending||m.dead||m.retired||typeof document<"u"&&document.visibilityState==="hidden"||(m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null),!m.reconcileBusy&&en())};return window.addEventListener("online",l),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("online",l),window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l),m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null)}},[e]),b.useEffect(()=>{const l=ie=>{if(m.readOnly||m.retired||m.dead)return!1;Tt(),ie&&He();const C=jn(m.fm,m.body);return!m.writing&&(C===m.lastSaved||xn())?!1:(m.pending=!0,m.stashed=C,Io(w,e,C,m.lastSaved,m.slot),!0)},g=ie=>{l(ie)&&(m.timer&&(clearTimeout(m.timer),m.timer=null),!m.reconcileBusy&&en())},v=()=>{document.visibilityState==="hidden"&&g(!0)},E=()=>g(!0);let L=0,Y=null;const _=()=>{const ie=L+1e3-Date.now();if(ie>0){l(!1),Y||(Y=setTimeout(()=>{Y=null,L=Date.now(),g(!1)},ie));return}L=Date.now(),g(!1)};return document.addEventListener("visibilitychange",v),window.addEventListener("pagehide",E),document.addEventListener("freeze",E),document.addEventListener("pause",E),window.addEventListener("blur",_),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("pagehide",E),document.removeEventListener("freeze",E),document.removeEventListener("pause",E),window.removeEventListener("blur",_),Y&&clearTimeout(Y)}},[e]);const xe=l=>m.readOnly||m.retired||m.dead||!k.current?!1:(k.current.insertFiles(l),!0);b.useEffect(()=>{if(!a)return;const l=g=>xe(g);return a.current=l,()=>{a.current===l&&(a.current=null)}},[a]),b.useEffect(()=>{if(!i)return;const l=g=>m.readOnly||m.retired||m.dead?!1:k.current?.insertMarkdown(g,"cursor")??!1;return i.current=l,()=>{i.current===l&&(i.current=null)}},[i]),b.useLayoutEffect(()=>dd({path:e,owner:m,peerWrote:()=>To(),scope:S,lastActive:()=>ke.current,dirty:()=>m.readOnly||m.retired||m.dead?!1:(Tt(),jn(m.fm,m.body)!==m.lastSaved&&!xn()),flush:(l=!1)=>m.readOnly?Promise.resolve():(Tt(),He(),m.timer&&(clearTimeout(m.timer),m.timer=null),en(l)),insertFiles:l=>xe(l),patchFm:(l,g=!1)=>m.readOnly||m.retired||m.dead?null:g?(m.fm=Ca(m.fm,l),m.peerPatch={...m.peerPatch??{},...l},dt(v=>v+1),Kn(),Promise.resolve()):(A(l),m.chain),fmNow:()=>ks(m.fm),insertMarkdown:(l,g)=>m.retired||m.readOnly?!1:k.current?.insertMarkdown(l,g)??!1,insertReply:h?void 0:(l,g)=>{if(m.retired||m.dead||m.readOnly||!k.current?.insertMarkdown(l,"cursor",{quiet:!0,after:g,caretless:!he.current}))return null;const v=Wt()?.state.doc,E=Xn,L={n:E.log.length,top:E.log[E.log.length-1],future:E.future.length};return{undo:()=>{const Y=Wt();return!Y||!v||Y.state.doc!==v||m.retired||m.dead||L.top!=="pm"||E.log.length!==L.n||E.log[E.log.length-1]!=="pm"||E.future.length!==L.future?!1:ht.current&&Xt.current?Xt.current("undo"):Ka(Y.state,Y.dispatch)}}},bodyNow:()=>m.body,statsNow:()=>y(),headings:()=>{const l=Wt();return l?Js(l.state.doc):[]},revealHeading:(l,g,v)=>{const E=Wt();if(!E)return;const L=Js(E.state.doc),Y=L[l]?.text===g?L[l]:L.find(ie=>ie.text===g);if(!Y)return;E.focus(),E.dispatch(E.state.tr.setSelection(Ne.near(E.state.tr.doc.resolve(Y.pos+1))));const _=E.nodeDOM(Y.pos);_ instanceof HTMLElement&&(cs(_),v&&qs(_.getBoundingClientRect()))},revealBlock:(l,g)=>{const v=Wt();if(!v)return!1;const E=[];v.state.doc.descendants((ie,C,fe)=>ie.isTextblock?(E.push({pos:C,text:ie.textContent,parent:fe}),!1):!0);let L=E.findIndex(ie=>El(ie.text)===l);if(L<0)return!1;xd(E[L].text)&&L>0&&E[L-1].parent===E[L].parent&&(L-=1);const Y=E[L].pos;v.focus(),v.dispatch(v.state.tr.setSelection(Ne.near(v.state.tr.doc.resolve(Y+1))));const _=v.nodeDOM(Y);return _ instanceof HTMLElement&&(cs(_),g&&qs(_.getBoundingClientRect())),!0},focusBody:()=>{if(m.readOnly||m.retired||m.dead)return!0;const l=Pe.getView();return l?(l.hasFocus()||l.focus(),!0):!1},revealText:(l,g)=>{const v=Wt();if(!v)return!1;const E=of(v.state.doc,l,!!g?.tag);if(!E)return!1;Dl(v,E.from),v.focus(),v.dispatch(v.state.tr.setSelection(Ne.create(v.state.doc,E.from,E.to)));let L=v.nodeDOM(E.block);for(;L instanceof HTMLElement&&L!==v.dom;){const Y=L.getBoundingClientRect();if(Y.width||Y.height)break;L=L.parentElement}return!(L instanceof HTMLElement)||L===v.dom||(cs(L),g?.flash&&qs(L.getBoundingClientRect())),!0},retire:l=>{if(zr(),!m.retired&&!m.readOnly&&!m.dead){Tt();const g=jn(m.fm,m.body);g!==m.lastSaved&&!xn()&&(l?Io(w,l,g,m.lastSaved,m.slot):(T.getState().vaultRoot??null)!==(w??null)?Io(w,e,g,m.lastSaved,m.slot):jo(g))}else m.retired&&m.gone!=null&&vo();m.retired=!0,m.timer&&(clearTimeout(m.timer),m.timer=null),m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null)}}),[e]);const[$e,Ae]=b.useState(()=>{if(h)return null;const l=v=>v==null?Wc(e,null):Sm(v)||Wc(e,v),g=Oh(w,e,m.slot,l);return g?g.text===m.lastSaved||g.text===(n??t)?(Zr(w,e,void 0,g.slot),null):g:null}),Z=()=>{$e&&Zr(w,e,void 0,$e.slot),Ae(null)},Ze=()=>{const l=$e;if(Ae(null),!l||h||m.retired)return;(l.slot??null)!==m.slot&&(Zr(w,e,l.text,l.slot),Io(w,e,l.text,m.lastSaved,m.slot)),Tt();const g=m.lastSaved,v=jn(m.fm,m.body),E=v!==g?v:$r(g)!==l.base?g:null;E!=null&&E!==l.text&&(m.unpreserved=E);const{fmText:L,body:Y}=Sr(l.text);m.fm=L,dt(_=>_+1),Y!==m.body&&(m.ownedCards.clear(),m.body=Y,(k.current??(ge.current?ce.current:null))?.applyBody(Y)||re(_=>_+1)),Kn(),m.pending=!0,m.stashed=l.text,en()};b.useEffect(()=>{o&&(o.scheduleState=()=>({pending:m.pending,lastSaved:m.lastSaved}),o.flush=()=>(Tt(),m.timer&&clearTimeout(m.timer),m.timer=null,en()),o.fmState=()=>({fm:m.fm,body:m.body}),o.setFm=l=>A(l,!1),o.view=()=>Pe.getView(),o.serializeNow=()=>k.current?.serializeNow()??null)},[o]);const[Qe,zt]=b.useState(0);b.useEffect(()=>{hm(e)&&zt(l=>l+1)},[e]);const ut=b.useRef(()=>!1);ut.current=()=>!h&&!p&&!ht.current&&Yo.current==null&&Qe===0;const yt=b.useRef(()=>!1);yt.current=()=>{const l=Oa;if(!l||l.scope!==S||Date.now()-l.at>5e3)return!1;Oa=null;const g=document.activeElement;return(!g||g===document.body)&&(S==null||S===Pm())};const Rt=b.useRef(null);b.useLayoutEffect(()=>()=>{const l=document.activeElement;l&&l!==document.body&&(J.current?.contains(l)||Rt.current?.contains(l))&&(Oa={scope:S,at:Date.now()})},[]);const $t=b.useRef(()=>!1);$t.current=()=>$n||h?!1:(zt(l=>l+1),!0);const ln=l=>{const g=Pe.getView();if(!g)return;let v=g.state.tr;if(m.body===l.body)try{const Y=g.state.schema.nodeFromJSON(l.doc);Y.eq(v.doc)||(v=v.replaceWith(0,v.doc.content.size,Y.content))}catch{}const E=v.doc.content.size,L=Y=>v.doc.resolve(Math.max(0,Math.min(Y,E)));try{v=v.setSelection(Ne.between(L(l.anchor),L(l.head)))}catch{}g.dispatch(v.setMeta("addToHistory",!1).scrollIntoView())},Dt=async(l,g=null,v=!1)=>{if(h||v&&m.retired)return!1;const E=w;try{if(Tt(),await en(),await Mm(),v&&(await m.chain,m.retired||Mn.getState().vaultRoot!==E))return!1;const L=await wn.renamePageFile(e,l);if(L!==e){zm(w,e,L),Mp(w,e,L),m.retired=!0,Tt();const Y=jn(m.fm,m.body),_=m.body;if(Y!==m.lastSaved)try{const fe=await wn.writeTextFile(L,Fo(Y,m.eol),{base:$r(Fo(m.lastSaved,m.eol))});if(fe&&fe.ok===!1&&fe.current!==Fo(Y,m.eol))try{Ph(L,await wa(L,Fo(Y,m.eol))),Mn.getState().refreshPages()}catch(Se){Io(w,L,Y,m.lastSaved,m.slot),ka(L,Se)}}catch(fe){Io(w,L,Y,m.lastSaved,m.slot),ka(L,fe)}const ie=Yo.current,C=Pe.getView();if(!v&&g&&ie!=null&&typeof ie!="object")Ks={path:L,scope:S,req:ie,at:Date.now()};else if(!v&&C?.hasFocus()){const fe={place:"restore",body:_,doc:C.state.doc.toJSON(),anchor:C.state.selection.anchor,head:C.state.selection.head};Xo.current=fe,Ks={path:L,scope:S,req:fe,at:Date.now()}}fd(e,"file",L),$m(e,L,"file"),await Am(e,L),Mn.getState().refreshPages(),v||r?.(L)}return!0}catch{return v&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.renameDetachedFailed",{name:l})}})),!1}},Vn=b.useRef("");b.useEffect(()=>{const l=JSON.stringify(_n(dn(m.fm))?.tree??null);if(l===Vn.current)return;Vn.current=l;const g=Pe.getView();g&&g.updateState(g.state)},[Te,Pe]);const Hn=Xh(m.fm),u=typeof Hn.icon=="string"&&Hn.icon.trim()?Hn.icon.trim():null,z=typeof Hn.cover=="string"&&Hn.cover.trim()?Hn.cover.trim():null,N=Hn.cover_y,B=typeof N=="number"?N:typeof N=="string"?parseFloat(N):NaN,K=Number.isFinite(B)?Math.max(0,Math.min(100,B)):50,O=b.useMemo(()=>q==="source"?jn(m.fm,m.body):"",[q,Te]),W=b.useRef(null),te=()=>`${go(m.fm)??""}\0${dn(m.fm)??""}`;b.useEffect(()=>{if(!h)return gm(X,l=>{const g=pa(le.current),v=ha(g);if(l==="source"){Tt();const _=Pe.getView(),ie=jn(m.fm,m.body);let C=m.fm.length,fe=0,Se=!1;if(_){const{head:Be,$head:Ue}=_.state.selection;Se=_.hasFocus();try{fe=_.coordsAtPos(Be).top-v}catch{}const tt=Ue.parent.isTextblock?Ue.parent.textBetween(Math.max(0,Ue.parentOffset-16),Ue.parentOffset,void 0,""):"",At=ce.current?.serializePrefix(Be);C=Fm(ie,m.fm.length+(At?.trimEnd().length??0),tt)}W.current={to:l,offset:C,y:fe,focused:Se,bodyAtEnter:m.body,struct:te()};return}const E=ne.current;if(!E)return;const L=E.selectionStart??0;let Y=0;try{Y=ui(E,L)-v}catch{}W.current={...W.current??{},to:l,offset:L,bodyOff:L-Sr(E.value).fmText.length,y:Y,focused:document.activeElement===E}})},[X,h]);const pe=b.useRef(q);b.useLayoutEffect(()=>{const l=pe.current;if(pe.current=q,l===q)return;const g=W.current,v=pa(le.current);if(q==="source"){Gt();const fe=ne.current;if(!fe||g?.to!=="source")return;const Se=v.scrollTop;fe.style.height="auto",fe.style.height=`${fe.scrollHeight}px`,v.scrollTop=Se;const Be=Math.min(g.offset,fe.value.length);fe.setSelectionRange(Be,Be),g.focused&&fe.focus({preventScroll:!0}),v.scrollTop+=ui(fe,Be)-ha(v)-g.y;return}W.current=null,fo(null);const E=ce.current,L=Pe.getView();if(!E||!L||!g||g.struct!==te()){m.ownedCards.clear(),re(fe=>fe+1);return}if(m.body!==g.bodyAtEnter&&E.applyBody(m.body,!1,!0),g.to!=="wysiwyg"||g.bodyOff==null)return;const Y=Pe.getView();if(!Y)return;const _=Y.state.doc.content.size,ie=g.bodyOff<=0?0:E.posAfterPrefix(m.body.slice(0,g.bodyOff))??0,C=Ne.near(Y.state.doc.resolve(Math.max(0,Math.min(ie,_))),-1);Y.dispatch(Y.state.tr.setSelection(C).setMeta("addToHistory",!1)),g.focused&&Y.focus();try{v.scrollTop+=Y.coordsAtPos(C.head).top-ha(v)-g.y}catch{}},[q]);const ne=b.useRef(null);return b.useEffect(()=>{const l=ne.current;if(q==="source"&&l){const g=pa(l),v=g.scrollTop;l.style.height="auto",l.style.height=`${l.scrollHeight}px`,g.scrollTop=v}},[q,uo,O]),b.useEffect(()=>{if(h)return;if(q==="source"){const g=ne.current;return g?Si(Sh(g)):void 0}const l=J.current;return l?Si(jb(l,()=>Pe.getView())):void 0},[h,q,Pe]),f.jsxs(f.Fragment,{children:[f.jsx("span",{ref:le,className:"amx-seg-anchor","aria-hidden":!0}),q==="source"?null:f.jsx(og,{anchor:ve,on:Fe,toggle:()=>Kt.current()}),$n||p?null:f.jsx(Bm,{page:e,cover:z,coverY:K,readOnly:h,onSetCover:l=>A({cover:l??void 0,...l?{}:{cover_y:void 0}}),onSetCoverY:l=>A({cover_y:l})}),$n?null:f.jsxs("div",{ref:Rt,className:"amx-doc unified-page","data-unified-path":e,onFocusCapture:me,onPointerDownCapture:me,children:[f.jsx(Fb,{compact:p,path:e,icon:u,cover:z,readOnly:h,onSetIcon:l=>A({icon:l??void 0}),onSetCover:l=>A({cover:l}),onRename:Dt,onDetachedRename:l=>{const g=l.trim();g&&g!==(e.split("/").pop()??e).replace(/\.md$/i,"")&&Dt(g,null,!0)},onEnterBody:l=>Mo(l==="enter"?"body-enter":"start"),focusSignal:Qe}),!p&&f.jsx(Jl.Provider,{value:ze,children:f.jsx(cg,{fmExtra:ks(m.fm),readOnly:h,notePath:e,onCommit:l=>{m.fm=Kh(m.fm,l),dt(g=>g+1),Kn(),m.pending=!0,en()}})}),h&&d&&f.jsxs("div",{className:"mk-notice unified-savebar","data-lock":"on",role:"status",children:[f.jsx(zp,{size:15}),f.jsx("div",{className:"mk-notice-body",children:f.jsx("span",{children:oe("unipage.lock.bar")})}),f.jsx("button",{type:"button",className:"btn sm",onClick:d,children:oe("unipage.lock.unlock")})]}),!h&&Zo&&f.jsxs("div",{className:"mk-notice is-error unified-savebar","data-save":"failed",role:"alert",children:[f.jsx(ym,{size:15}),f.jsx("div",{className:"mk-notice-body",children:f.jsx("span",{children:oe("unisave.failed.bar")})}),f.jsx("button",{type:"button",className:"btn sm",onClick:()=>{m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null),en()},children:oe("unisave.failed.retry")})]}),!h&&$e&&f.jsxs("div",{className:"mk-notice unified-savebar","data-save":"draft",role:"status",children:[f.jsx(xm,{size:15}),f.jsxs("div",{className:"mk-notice-body",children:[f.jsx("span",{children:oe("unisave.draft.bar",{time:bm($e.at)})}),f.jsx("small",{children:oe("unisave.draft.hint")})]}),f.jsx("button",{type:"button",className:"btn sm primary",onClick:Ze,children:oe("unisave.draft.restore")}),f.jsx("button",{type:"button",className:"btn sm",onClick:Z,children:oe("unisave.draft.discard")})]})]}),q==="source"?f.jsx("textarea",{ref:ne,className:"amx-source",value:uo??O,spellCheck:Re,onFocus:me,onChange:l=>{const g=l.target.value;fo(g);const{fmText:v,body:E}=Sr(g);m.fm=Wh(v),m.body=E,Gt()}}):null,f.jsxs("div",{ref:J,className:`page-view unified-body${Fe?" amx-canvas":""}${$n?" amx-canvas-full":""}`,style:q==="source"?{display:"none"}:void 0,"aria-hidden":q==="source"||void 0,"data-bare":!0,onFocusCapture:()=>{me(),he.current=!0,ma(cn)},onPointerDownCapture:me,children:[f.jsx(Wx,{path:e,vaultRoot:w,active:Fe&&q!=="source",readOnly:h,revealSelection:it,getView:()=>Pe.getView(),main:Ct,mainStored:an?.main!=null,elements:an?.elements,tree:an?.tree,onElements:Zn,onTree:mr,onMain:nn,timeline:Xn,histStepRef:Xt,exportRef:zn,saveFile:l=>Ru(e,l),parseMd:l=>k.current?.parseMd(l)??null,serializeMd:l=>k.current?.serializeMd(l)??null,storedMd:l=>k.current?.serializeStored(l)??null,onBlocksDeleted:$,notePages:()=>T.getState().pages,onCommit:l=>{l&&m.ownedCards.add(l),Tt(),Gt()},children:f.jsx(Bd,{children:f.jsx(Ib,{path:e,pageDir:R,body:m.body,onChange:l=>{ge.current||(m.body=l,Qo(),Gt())},onFinalFlush:l=>{m.body=l,Qo(),Gt(),dt(g=>g+1)},skipFinalFlush:()=>m.reconcileBusy>0||ge.current,hidden:()=>ge.current,apiRef:ce,probe:o,extraPlugins:Me,focusPlace:Qn!=null&&typeof Qn=="object"?"start":Qn,onFocused:()=>{Qn!=null&&typeof Qn=="object"&&ln(Qn),Mo(null)},onCard:eo,readOnly:h,onAskTangu:We?l=>Ve(l,l.state.selection.from,l.state.selection.to):void 0,aiMenu:Xe?{items:Un,translate:!0,more:Pt,onPick:(l,g)=>Gn(g,l)}:void 0,onAiPrompt:Xe?l=>Gn(l,"prompt"):void 0})},`${e}:${sn}${h?":ro":""}`)}),!Fe&&!h&&f.jsx("div",{className:"page-tail",onClick:()=>k.current?.focusTail()}),H&&f.jsx(ab,{}),!h&&U.count>0&&f.jsx(cb,{count:U.count,index:U.index,onReview:pr,onRevert:Ao,onKeep:()=>{const l=Pe.getView();l&&rb(l)}})]}),f.jsx(zb,{getView:()=>Pe.getView(),onOpenNote:(l,g)=>{T.getState().openWikiLink(Kd(l,e,T.getState().pages),e,g)}}),F&&f.jsx(cr,{children:f.jsx("div",{className:"amx-lightbox",onClick:()=>ue(null),role:"presentation",children:f.jsx("img",{src:F,alt:""})})}),pt&&Xe&&f.jsx(cr,{children:f.jsx(kp,{x:pt.x,y:pt.y,anchorTop:pt.top,title:pt.title,hasSelection:pt.hasSelection,askFirst:pt.askFirst,run:$o(pt),onApply:Bn,onClose:jr,editorEl:J.current,language:pt.language?{value:pt.language,onChange:l=>gt({...pt,key:Date.now(),language:l})}:void 0},pt.key)}),ao&&!h&&f.jsx(nu,{pages:T.getState().pages,exclude:e,onClose:()=>{Uo(null),Pe.getView()?.focus()},onPick:l=>{const g=ao;Uo(null);const v=Pe.getView();if(v){if(v.state.doc!==g.doc){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.menu.stale")}}));return}$g({view:v,from:g.from,to:g.to,source:e,target:l,pages:[...T.getState().pages].sort(),serialize:E=>k.current?.serializeMd(E)??null}).then(E=>{E&&(Tt(),Gt())}),v.focus()}}}),Cn&&!h&&f.jsxs(cr,{children:[f.jsxs(Yr,{className:"ctx-menu unified-block-menu",role:"menu","aria-label":oe("unipage.menu.aria"),x:Cn.x,y:Cn.y,onClick:l=>l.stopPropagation(),onMouseOver:l=>{Ln&&!l.target.closest("[data-sub]")&&It()},children:[We&&f.jsxs(f.Fragment,{children:[f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"ask",onClick:()=>{An(null);const l=Pe.getView();if(!l||!Ie(l))return;const g=Pe.topRangeOf(l),v=l.state.selection;g?Ve(l,g.from,g.to):v instanceof Ee&&Ve(l,v.from,v.to)},children:[f.jsx(Np,{size:13})," ",oe("unipage.menu.askTangu")]}),f.jsx("div",{className:"ubm-sep",role:"separator"})]}),(()=>{const l=Go();if(!l.length)return null;const g=No(),v=l.find(L=>L.k===g)??(g==="card"?{icon:Wa,label:oe("unipage.menu.card")}:void 0),E=v?.icon??ki;return f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-sub":"turnInto","aria-haspopup":"menu","aria-expanded":!!Ln,className:Ln?"is-open":void 0,onMouseEnter:L=>at(L.currentTarget,!1),onClick:L=>at(L.currentTarget,!0),children:[f.jsx(E,{size:13})," ",oe("unipage.menu.turnInto"),f.jsxs("span",{className:"ubm-sub-tail",children:[v?.label,f.jsx(Ll,{size:13})]})]})})(),cc(Pe.getView())&&f.jsx(Tb,{view:Pe.getView(),cell:Cn.cell??null,onDone:()=>An(null)}),f.jsx("div",{className:"ubm-sep",role:"separator"}),Pe.getView()&&Pe.topRangeOf(Pe.getView())?f.jsxs("button",{role:"menuitem",tabIndex:-1,"aria-disabled":"true",title:oe("unipage.menu.toNewColumnMulti"),"data-act":"toNewColumn",onClick:()=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.menu.toNewColumnMulti")}}))},children:[f.jsx(di,{size:13})," ",oe("unipage.menu.toNewColumn")]}):Pe.getView()&&Vd(Pe.getView().state.selection)&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"toNewColumn",onClick:()=>Oe((l,g)=>{au(l,g.from,g.to,g.node)}),children:[f.jsx(di,{size:13})," ",oe("unipage.menu.toNewColumn")]}),Pe.getView()&&Uc(Pe.getView().state.selection)!=null&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"unsplit",onClick:()=>{An(null);const l=Pe.getView();if(!l||!Ie(l))return;const g=Uc(l.state.selection);g!=null&&ay(l,g),l.focus()},children:[f.jsx(hh,{size:13})," ",oe("unipage.menu.unsplit")]}),Pe.getView()?.state.selection instanceof Ee&&Pe.getView().state.selection.node.type.name==="amadeusCanvasCard"&&f.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>Oe((l,g)=>{g.node.type.name==="amadeusCanvasCard"&&(Su(l,String(g.node.attrs.anchor)),Tt(),Gt())}),children:[f.jsx($p,{size:13})," ",oe("unipage.menu.backToDoc")]}),f.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>{An(null);const l=Pe.getView();!l||!Ie(l)||(Pe.duplicate(l)&&(Tt(),Gt()),l.focus())},children:[f.jsx(vm,{size:13})," ",oe("unipage.menu.duplicate")]}),(()=>{const l=Pe.getView();if(!l)return null;const g=l.state.selection,v=Ke(l),E=g instanceof Ee?Eg(g.node,e,T.getState().pages):null,L=!!v&&zg(l.state.doc.slice(v.from,v.to).content);return f.jsxs(f.Fragment,{children:[E&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"copyLink",onClick:()=>{An(null),Mg(E.link),Pe.getView()?.focus()},children:[f.jsx(wm,{size:13})," ",oe(E.kind==="heading"?"blocklinks.copyHeading":"blocklinks.copyBlock")]}),L&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"moveTo",onClick:()=>{An(null);const Y=Pe.getView();if(!Y||!Ie(Y))return;const _=Ke(Y);_&&Uo({doc:Y.state.doc,..._})},children:[f.jsx(sp,{size:13})," ",oe("blocklinks.moveTo")]})]})})(),f.jsxs("button",{role:"menuitem",tabIndex:-1,className:"danger",onClick:()=>_e((l,g)=>{const v=l.state.doc.slice(g.from,g.to).content;l.dispatch(l.state.tr.delete(g.from,g.to).scrollIntoView()),$(v)},(l,g)=>{const v=So.from(g.node),E=g.$from.parent,L=E.type.name==="amadeusColumnCell"&&E.childCount===1?cu(l.state,g.$from.before(),-1,!0):null;l.dispatch(L??l.state.tr.deleteSelection().scrollIntoView()),$(v)}),children:[f.jsx(Ya,{size:13})," ",oe("unipage.menu.delete")]})]}),Ln&&(()=>{const l=No();return f.jsx(Yr,{className:"ctx-menu unified-block-submenu",role:"menu","aria-label":oe("unipage.menu.turnInto"),x:Ln.x,y:Ln.y,anchorTop:Ln.anchorTop,onClick:g=>g.stopPropagation(),onMouseEnter:()=>clearTimeout(xo.current),children:Go().map(({k:g,icon:v,label:E,run:L})=>f.jsxs("button",{role:"menuitemradio","aria-checked":g===l,tabIndex:-1,"data-kind":g,onClick:L,children:[f.jsx(v,{size:13})," ",E,g===l&&f.jsx(oa,{size:13,className:"ubm-check"})]},g))})})()]})]})}const pv=Object.freeze(Object.defineProperty({__proto__:null,UnifiedPage:Ob},Symbol.toStringTag,{value:"Module"}));export{cg as A,Hp as C,uv as D,mv as F,nh as M,tg as S,Ob as U,Ch as a,vh as b,Kl as c,lv as d,Hl as e,bh as f,ur as g,Sr as h,wh as i,pv as j,fv as o,dv as s};