@forsion/unit 2.13.5 → 2.13.6

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 (179) hide show
  1. package/README.md +2 -2
  2. package/main.mjs +20 -4
  3. package/package.json +1 -1
  4. package/release.json +6 -5
  5. package/web/assets/{ArtificialView-BD1yHz1N.js → ArtificialView-DHqb9CTL.js} +1 -1
  6. package/web/assets/{AutomationBuilder-B09c-5Bi.js → AutomationBuilder-CzBKmOiw.js} +1 -1
  7. package/web/assets/{CalendarConfigView-Bd-ZDGPO.js → CalendarConfigView-Blw47NCs.js} +1 -1
  8. package/web/assets/CalendarSide-CFSzme3H.js +1 -0
  9. package/web/assets/CalendarView-B8sQfgZt.js +3 -0
  10. package/web/assets/{CapabilityMenu-DyHTEYLr.js → CapabilityMenu-Dzn6RbB1.js} +1 -1
  11. package/web/assets/{Chrome-C7F6fdDp.js → Chrome-owLewFu4.js} +1 -1
  12. package/web/assets/{CodeView-BGOnrGhB.js → CodeView-E18NDilX.js} +3 -3
  13. package/web/assets/{CtxMenuButtons-BYjrbUKS.js → CtxMenuButtons-CAiwQkOK.js} +1 -1
  14. package/web/assets/DashboardGridView-CBbYKcCo.js +25 -0
  15. package/web/assets/EventCard-D9uQe7g4.js +1 -0
  16. package/web/assets/{ExcalidrawCanvas-lwJCN6uB.js → ExcalidrawCanvas-BSOERegJ.js} +1 -1
  17. package/web/assets/{FloatingToc-DO7SH8Ku.js → FloatingToc-iK08Qpjc.js} +1 -1
  18. package/web/assets/GitCloneDialog-DfY0kqhP.js +1 -0
  19. package/web/assets/{HomepageView-CHJEhf9c.js → HomepageView-BCqFe1Ym.js} +3 -3
  20. package/web/assets/{ImageStudioPanels-CgVf0wiq.js → ImageStudioPanels-DdwihAkT.js} +2 -2
  21. package/web/assets/ImageStudioView-gJSYrmu1.js +1 -0
  22. package/web/assets/{InlineAiPanel-CdIPINsA.js → InlineAiPanel-CjYOW0_0.js} +1 -1
  23. package/web/assets/InlineFiles-3g2jMUeA.js +1 -0
  24. package/web/assets/{MarkdownBlock-DSItkLhu.js → MarkdownBlock-DjsGkPZ_.js} +24 -24
  25. package/web/assets/{ModelPill--CU3XTIQ.js → ModelPill-DgyXBsL9.js} +2 -2
  26. package/web/assets/MuseLibraryView-D_HBijmU.js +2 -0
  27. package/web/assets/{MuseView-CvsO62Fo.js → MuseView-BVDlmM6i.js} +3 -3
  28. package/web/assets/{PageHistoryPanel-CDh7nm78.js → PageHistoryPanel-B1EAPZeX.js} +2 -2
  29. package/web/assets/{PdfAnnotator-DafvjP3U.js → PdfAnnotator-bdB9evsY.js} +1 -1
  30. package/web/assets/{PenRow-CEy-s6SF.js → PenRow-DCOIGlfY.js} +1 -1
  31. package/web/assets/PluginToolCard-BXE5vA1h.js +2 -0
  32. package/web/assets/{ProductView-AUqnTwmQ.js → ProductView-l5Q7uBy6.js} +1 -1
  33. package/web/assets/{SettingsPage-B9mmkWaM.js → SettingsPage-fjxfS_Mt.js} +2 -2
  34. package/web/assets/{StudioGuestSurface-OOhRA8nt.js → StudioGuestSurface-360CWUwf.js} +1 -1
  35. package/web/assets/TodoListView-BsPt2GUU.js +1 -0
  36. package/web/assets/{Tooltip-DOYi44eY.js → Tooltip-CuXpWtdJ.js} +1 -1
  37. package/web/assets/UnifiedPage-6xbFLtXT.js +712 -0
  38. package/web/assets/{ViewSelectionBar-WmSWMFsR.js → ViewSelectionBar-C5FDh7fO.js} +2 -2
  39. package/web/assets/{appStore-DDOkzWDA.js → appStore-BskcSDl6.js} +114 -115
  40. package/web/assets/{arrow-up-right-BptN64d-.js → arrow-up-right-DEykpgsH.js} +1 -1
  41. package/web/assets/{astryxBridge-BL56QfEv.js → astryxBridge-B2IZdPvo.js} +1 -1
  42. package/web/assets/automationListSource-Cm09JKkK.js +1 -0
  43. package/web/assets/{boardSurface-CP4HNmcm.js → boardSurface-Dv-aVaUJ.js} +1 -1
  44. package/web/assets/{calendarNavStore-DCi7VBmM.js → calendarNavStore-FKStA7Hh.js} +1 -1
  45. package/web/assets/{canvasPrefs-ArsX3NFO.js → canvasPrefs-CMulOS0k.js} +1 -1
  46. package/web/assets/{chatBoxSurface-DRsDr-MT.js → chatBoxSurface-BR_G6cxG.js} +1 -1
  47. package/web/assets/{chevron-up-ChXNh14u.js → chevron-up-C_EDOZzI.js} +1 -1
  48. package/web/assets/{client-fKy9CWk0.js → client-DD5czSuF.js} +1 -1
  49. package/web/assets/{code-xml-DCCD9eCS.js → code-xml-vTB4LtTf.js} +1 -1
  50. package/web/assets/{codeStudioStore-BgLfCDK2.js → codeStudioStore-OswE1_s0.js} +1 -1
  51. package/web/assets/{contextMenuSurface-BF593l2M.js → contextMenuSurface-DqdYEGuH.js} +1 -1
  52. package/web/assets/{copy-plus-ClKrSgM7.js → copy-plus-CVHqDNny.js} +1 -1
  53. package/web/assets/create-DZWy4zBR.js +14 -0
  54. package/web/assets/{dashboardSurface-C6cbR3oG.js → dashboardSurface-Co4byEQm.js} +1 -1
  55. package/web/assets/dbStore-Bc2lC8ZI.js +2 -0
  56. package/web/assets/deskCapture-BfTzH2aO.js +1 -0
  57. package/web/assets/{diff2html-Di8qIz6O.js → diff2html-0MkNy2ws.js} +1 -1
  58. package/web/assets/{docx-preview-B-URZXdP.js → docx-preview-CwNWZegI.js} +1 -1
  59. package/web/assets/{draft-CBSW5tHx.js → draft-DTzuTatQ.js} +2 -2
  60. package/web/assets/{drawingStore-CGvTqqYW.js → drawingStore-BD5m2eqn.js} +1 -1
  61. package/web/assets/{file-down-Z913cCyQ.js → file-down-Cjo_T6By.js} +1 -1
  62. package/web/assets/{floatingTocSurface-DGwTiqvU.js → floatingTocSurface-D3IIVNnq.js} +1 -1
  63. package/web/assets/{foldActions-DGIPTmE1.js → foldActions-utwZpRrA.js} +1 -1
  64. package/web/assets/{folder-1OJQeDI1.js → folder-DiaFWdCg.js} +1 -1
  65. package/web/assets/{folder-minus-D_j1SwHu.js → folder-minus-DUEOcs12.js} +1 -1
  66. package/web/assets/{folder-plus-DP9sFr26.js → folder-plus-Cmhq0GcR.js} +1 -1
  67. package/web/assets/{gestures-ZhFAENNZ.js → gestures-Bx9M0le5.js} +1 -1
  68. package/web/assets/{git-branch-BMajF2cu.js → git-branch-DzGWffyD.js} +1 -1
  69. package/web/assets/{homeCardStatus-5R7XkxFL.js → homeCardStatus-NAk4A77P.js} +1 -1
  70. package/web/assets/{i18n.generated-DW_l6CkR.js → i18n.generated-D4-Wu9Wh.js} +1 -1
  71. package/web/assets/imageStudio-D67oElIb.js +4 -0
  72. package/web/assets/{index-COzdD7mZ.js → index-3VWZ1rsL.js} +1 -1
  73. package/web/assets/{index-bF04pF8q.js → index-58wBjkHy.js} +1 -1
  74. package/web/assets/{index-Cg1FWM_p.js → index-B9_zH7f5.js} +1 -1
  75. package/web/assets/index-BQrMYjou.js +1 -0
  76. package/web/assets/{index-D-ClOPbg.js → index-BWrWMYua.js} +1 -1
  77. package/web/assets/{index-C--E96Ul.js → index-BdLJBf4-.js} +1 -1
  78. package/web/assets/{index-CI2esW1X.js → index-Bf3W92Hb.js} +1 -1
  79. package/web/assets/{index-B8A3nKeL.js → index-BjmPaLFA.js} +1 -1
  80. package/web/assets/{index-BeW45J9J.js → index-Bv-vJTzF.js} +1 -1
  81. package/web/assets/{index-BnJguNqI.js → index-C7yb62gg.js} +1 -1
  82. package/web/assets/{index-CtRdzpNh.js → index-C9gBBMYv.js} +1 -1
  83. package/web/assets/index-CiQ59Kib.js +1 -0
  84. package/web/assets/{index-DfhEDV2T.js → index-CzTUjEMt.js} +1 -1
  85. package/web/assets/{index-BYKR7EVg.js → index-D4Qx6o3E.js} +1 -1
  86. package/web/assets/{index-jzlU5luC.js → index-DDBcn3UD.js} +1 -1
  87. package/web/assets/{index-CtCYv9bF.js → index-DEADY94l.js} +1 -1
  88. package/web/assets/{index-CWXpOSI2.js → index-DGTKsPAQ.js} +1 -1
  89. package/web/assets/{index-SpegRFQV.js → index-DRwDqvjf.js} +1 -1
  90. package/web/assets/{index-BDZIQnEx.js → index-DexVkoxH.js} +1 -1
  91. package/web/assets/{index-uhvJ8AiJ.js → index-IMOhRWY8.js} +1 -1
  92. package/web/assets/{index-Dr6YmrrT.js → index-XjvpYHIo.js} +1 -1
  93. package/web/assets/{index-fDB1l4d-.js → index-YuejkHoJ.js} +51 -37
  94. package/web/assets/{index-CVLDDD5Z.js → index-pH0266gX.js} +1 -1
  95. package/web/assets/{index-BniT-A2n.js → index-sQl_bGM_.js} +1 -1
  96. package/web/assets/{index-CPfmhZ3Z.js → index-vbNFy5lS.js} +1 -1
  97. package/web/assets/{invitePage-iOT1zBvp.js → invitePage-BT_rFfab.js} +1 -1
  98. package/web/assets/{ipc-SAPDwyQ4.js → ipc-8cxXGSZK.js} +1 -1
  99. package/web/assets/{jszip.min-B3n1FGCb.js → jszip.min-By4OI3XR.js} +1 -1
  100. package/web/assets/launchpad-BX4jQyF4.js +2 -0
  101. package/web/assets/{layout-grid-oIyIGbc5.js → layout-grid-CzxXbCDa.js} +1 -1
  102. package/web/assets/{linkFollow-uke1Xtit.js → linkFollow-J2c0wSgB.js} +4 -4
  103. package/web/assets/{listFold-BeNv2v6M.js → listFold-B_2Xqxn_.js} +1 -1
  104. package/web/assets/{lock-open-D2nMg0ga.js → lock-open-DVWCLSZm.js} +1 -1
  105. package/web/assets/{log-out-D70NCXC4.js → log-out-CdKTS7HC.js} +1 -1
  106. package/web/assets/{magnet-Cqmm97W8.js → magnet-BmVcZ9U4.js} +1 -1
  107. package/web/assets/main-CForzSFD.js +15 -0
  108. package/web/assets/{markdownEditorSurface-zUzFity2.js → markdownEditorSurface-Bs8FJNHu.js} +1 -1
  109. package/web/assets/{mediaPlayer-DB4KUvua.js → mediaPlayer-O9pVRl_k.js} +1 -1
  110. package/web/assets/{message-square-plus-BvUfAAZm.js → message-square-plus-CspBv9iG.js} +1 -1
  111. package/web/assets/{messages-GQUjmbwW.js → messages-CG7ywZ-K.js} +1 -1
  112. package/web/assets/{minimize-2-CMhzL6ZW.js → minimize-2-Bq4vUin-.js} +1 -1
  113. package/web/assets/mobileEntry-CptXQ4Ov.js +13 -0
  114. package/web/assets/modelPickerSurface-C0SkjaPL.js +1 -0
  115. package/web/assets/{nativeDownload-DsGyUSJ5.js → nativeDownload-DlnT8U-y.js} +1 -1
  116. package/web/assets/{nativeSheetMenu--iihXNVd.js → nativeSheetMenu-CVC51DzC.js} +1 -1
  117. package/web/assets/{pageStore-ys8L4rjF.css → pageStore-BC6Z18n7.css} +1 -1
  118. package/web/assets/{pageStore-CyvNZEYX.js → pageStore-D_fKLv-o.js} +7 -7
  119. package/web/assets/{pageTree-Ci2qzrs1.js → pageTree-DtDKozTg.js} +3 -3
  120. package/web/assets/{pen-line-DC3lbEY1.js → pen-line-ho1GgAe2.js} +1 -1
  121. package/web/assets/{pen-tool-DD5_N4lZ.js → pen-tool-CV-FKFEZ.js} +1 -1
  122. package/web/assets/{pencil--sWwxHdP.js → pencil-BgF4Kiqp.js} +1 -1
  123. package/web/assets/{phoneList-DKRMxQHf.js → phoneList-BLVdQcXY.js} +1 -1
  124. package/web/assets/pluginChat-C6t6DWhY.js +2 -0
  125. package/web/assets/{react-b7FrqRQR.js → react-DOzedx9n.js} +1 -1
  126. package/web/assets/recordSurface-C9SRNjy4.js +1 -0
  127. package/web/assets/{redo-2-CqlqhWrI.js → redo-2-DWZTaEz-.js} +1 -1
  128. package/web/assets/{rotate-ccw-D8kni6Ni.js → rotate-ccw-CyZpL7MX.js} +1 -1
  129. package/web/assets/{selectionActions-DIq0xDm8.js → selectionActions-C2a8ImJm.js} +1 -1
  130. package/web/assets/selectionBarSurface-DaXlyy1s.js +1 -0
  131. package/web/assets/{sessionTitle-Ctp4iNKu.js → sessionTitle-BtZ1BteL.js} +1 -1
  132. package/web/assets/settingsPageSurface-Cg8FNZq3.js +1 -0
  133. package/web/assets/{sharePage-CY04XCAf.js → sharePage-vnghra3Q.js} +2 -2
  134. package/web/assets/{shareViewer-DweNF8Ch.js → shareViewer-CWJQHiV-.js} +1 -1
  135. package/web/assets/{star-B0sZEmbj.js → star-ZEpUQwnX.js} +1 -1
  136. package/web/assets/tableSurface-DfEdzVDn.js +1 -0
  137. package/web/assets/{tanguProbe-B8Qv2vcm.js → tanguProbe-BboOas-a.js} +6 -6
  138. package/web/assets/{terminalView-BLGdmdl7.js → terminalView-xp8ARBLi.js} +1 -1
  139. package/web/assets/{type-Dt7RNB9g.js → type-CMyP4cKt.js} +1 -1
  140. package/web/assets/{undo-2-QimgpLBn.js → undo-2-C4ZCsMsx.js} +1 -1
  141. package/web/assets/{unitAccount-DL3jfd84.js → unitAccount-DNxfGo3c.js} +1 -1
  142. package/web/assets/{unitBridge-BSsCy1zP.js → unitBridge-Bq0n1ZM6.js} +1 -1
  143. package/web/assets/{unitCloudTransport-CI_6H0TU.js → unitCloudTransport-CErylgEO.js} +1 -1
  144. package/web/assets/{unitOwnerAccess-CiQ7nD7E.js → unitOwnerAccess-7s-3dfNM.js} +1 -1
  145. package/web/assets/{unitShim-Dl2ksNp-.js → unitShim-BfheyIG8.js} +3 -3
  146. package/web/assets/{upload-Dy7svciS.js → upload-VtCrluEO.js} +1 -1
  147. package/web/assets/userSpaces-BpeYjLni.js +1 -0
  148. package/web/assets/viewportLock-cVUalJAI.js +738 -0
  149. package/web/assets/{zoom-in-DDEtY_Go.js → zoom-in-C7R8s9x-.js} +1 -1
  150. package/web/index.html +2 -2
  151. package/web/assets/CalendarSide-B0RVbOsg.js +0 -1
  152. package/web/assets/CalendarView-BHio-n_r.js +0 -3
  153. package/web/assets/DashboardGridView-CR-R_qV8.js +0 -25
  154. package/web/assets/EventCard-QyYorE1_.js +0 -1
  155. package/web/assets/GitCloneDialog-CbW-RJak.js +0 -1
  156. package/web/assets/ImageStudioView-4WcX0_V4.js +0 -1
  157. package/web/assets/InlineFiles-CAIyTk1n.js +0 -1
  158. package/web/assets/MuseLibraryView-PlS7HAlV.js +0 -2
  159. package/web/assets/PluginToolCard-DCzLhsCA.js +0 -2
  160. package/web/assets/TodoListView-BkgMe44I.js +0 -1
  161. package/web/assets/UnifiedPage-s7-tDSwG.js +0 -712
  162. package/web/assets/automationListSource-B1jz6q0t.js +0 -1
  163. package/web/assets/create-DYmVT68X.js +0 -14
  164. package/web/assets/dbStore-BIG5Mfh2.js +0 -1
  165. package/web/assets/deskCapture-q-jRDIcc.js +0 -1
  166. package/web/assets/imageStudio-DC_syDtx.js +0 -4
  167. package/web/assets/index-CIKPZc3Q.js +0 -1
  168. package/web/assets/index-CmsN2Zm2.js +0 -1
  169. package/web/assets/launchpad-CcmSwlJl.js +0 -2
  170. package/web/assets/main-B9aT0WXG.js +0 -15
  171. package/web/assets/mobileEntry-BnHzrdoC.js +0 -13
  172. package/web/assets/modelPickerSurface-Dtz40Ae2.js +0 -1
  173. package/web/assets/pluginChat-82zZt47Y.js +0 -2
  174. package/web/assets/recordSurface-vUX25Z8R.js +0 -1
  175. package/web/assets/selectionBarSurface-B94e5JW_.js +0 -1
  176. package/web/assets/settingsPageSurface-C9TA3mJg.js +0 -1
  177. package/web/assets/tableSurface-CSBYBw5P.js +0 -1
  178. package/web/assets/userSpaces-oMHIWgYe.js +0 -1
  179. package/web/assets/viewportLock-BZq5PTeN.js +0 -738
@@ -0,0 +1,712 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PdfAnnotator-bdB9evsY.js","./index-YuejkHoJ.js","./pdf-C2_sJa3b.js","./pdf.worker.min-CGb3BKV9.js","./pageStore-D_fKLv-o.js","./react-DOzedx9n.js","./client-DD5czSuF.js","./pageStore-BC6Z18n7.css","./PdfAnnotator-C_kglLCA.css"])))=>i.map(i=>d[i]);
2
+ import{a as Cn,j as u,u as Bt,r as x,X as fd,bK as Js,b1 as hc,Y as Bl,bL as pd,b4 as md,bM as aa,bN as hd,bO as Gc,t as je,bP as gd,bQ as xd,l as Hl,bR as yd,q as gc,bp as xc,bS as Hr,bT as bd,bl as vd,ad as wd,a6 as kd,v as Kr,bU as Kl,m as Sd,bV as Cd,f as ys,bW as Ed,bX as Vl,bq as Md,aL as xa,i as zd,e as Jc,V as Ad,_ as Nd,bY as Td,H as $d,bZ as jd,b_ as Rd,br as Ld,aI as Zc,E as ql,b$ as Qc,c0 as Zs,c1 as ei,c2 as Dd,c3 as ti,a9 as Id,c4 as wr,ab as ni,ac as Pd,bc as Od,bd as Fd,a7 as _d,c5 as Bd,c6 as Hd}from"./index-YuejkHoJ.js";import{E as oi,f as Kd,i as Vd,F as qd,j as ca,k as Wd,h as Wl,p as Ms,l as xs,t as Yd,m as Ud,n as Xd,o as Gd,q as yc,r as Yl,v as Jd,w as Wa,x as Zd,y as Qd,z as ef,A as tf,B as nf,C as of,D as ya,G as ba,H as rf,I as Qs,J as Ya,K as sf,L as ea,M as af,N as Ua,O as Ul,Q as ri,S as cf,T as lf,U as uf,V as df,W as ff,X as pf,Y as mf,u as Xl,Z as hf,_ as gf,$ as xf,a0 as yf,a1 as si,a2 as bf,a3 as Ls,a4 as vf,a5 as wf,a6 as kf,a7 as Gl,a8 as us,a9 as Sf,aa as Cf,ab as Ef,ac as Mf,ad as zf,ae as Af,af as Nf,ag as Tf,ah as va,g as $f,ai as jf,aj as Rf}from"./MarkdownBlock-DjsGkPZ_.js";import{el as Lf,lY as Df,aA as Wr,lZ as Yt,l_ as ai,l$ as Ko,m0 as Le,m1 as Wo,k4 as If,m2 as Pf,m3 as Of,cE as Jl,S as Ff,kT as ta,m4 as _f,m5 as Bf,m6 as Hf,m7 as $n,m8 as Se,m9 as To,N as ci,g9 as Nr,ma as Zl,bV as Xr,mb as ii,mc as Kf,fl as Vf,md as dr,me as qf,mf as Wf,mg as ao,mh as Yf,mi as Uf,mj as Xf,mk as Gf,ml as li,mm as Jf,eK as Zf,eJ as Qf,mn as ep,ep as ui,fm as tp,mo as np,ht as op,mp as Ql,mq as rp,mr as sp,ms as Xa,e_ as Ga,d3 as ap,mt as Ja,aD as cp,mu as ip,mv as ir,i5 as lp,gZ as up,i4 as dp,mw as fp,mx as pp,hz as mp,aQ as Za,dZ as hp,eu as gp,l8 as xp,my as yp,mz as bp,mA as vp,l7 as di,mB as wp,mC as wa,mD as fi,mE as ka,df as kp,aW as Sp,bQ as Cp,bv as Ep,eo as pi,b4 as Mp,mF as mi,mG as Pr,mH as Sn,mI as zp,mJ as Ap,mK as hi,mL as Np,jC as Tp,mM as $p,aI as jp,mN as Rp,gS as Lp}from"./appStore-BskcSDl6.js";import{p as tn,a8 as Dp,aA as eu,R as Mn,cM as Ip,cN as Pp,cO as Op,F as Fp,T as bc,br as gi,u as dn,b4 as Zr,cP as xi,a6 as _p,ah as ia,cQ as Bp,aj as zs,aE as on,X as lr,I as tu,q as nu,B as Hp,aR as Kp,cl as Vp,cR as qp,bu as yi,cS as Wp,cT as Qr,c9 as bi,c8 as Yp,cU as vi,cV as Ds,bv as Up,P as Xp,cW as wi,cX as ki,bb as Si,cY as Gp,bm as Jp,cZ as Zp,c_ as Qp,c$ as em,d0 as Ci,d1 as tm,d2 as nm,d3 as Ei,d4 as om,d5 as rm,d6 as Qa,b3 as ou,cj as sm,d7 as am,bt as cm,d8 as im,cf as Mi,d9 as lm,da as um,db as Bo,ci as dm,dc as zi,dd as fm,as as ru,de as pm,df as mm,dg as go,dh as hm,av as gm,di as xm,dj as Ai,dk as es,dl as Is,co as ym,cp as bm,c7 as vm,aV as Sa,dm as wm,dn as km,dp as Ni,dq as Ti}from"./pageStore-D_fKLv-o.js";import{c as Sm}from"./client-DD5czSuF.js";import{$ as Et,a as su,b as vc}from"./index-CiQ59Kib.js";import{F as au,H as Cm,T as Em}from"./type-CMyP4cKt.js";import{U as $i}from"./upload-VtCrluEO.js";import{h as Gr,l as Mm,f as Jr,a as ji,i as wc,b as Us,c as zm,d as kr,t as Ps,e as Os,g as Ca,s as Am,j as Nm,k as Tm}from"./listFold-B_2Xqxn_.js";import{e as $m,a as jm,b as Rm,c as Ri,v as Li,i as Lm}from"./linkFollow-J2c0wSgB.js";import{A as Di}from"./arrow-up-right-DEykpgsH.js";import{c as cu}from"./react-DOzedx9n.js";import{r as ts,a as Dm,C as Im}from"./Chrome-owLewFu4.js";import{e as Pm,h as Om,a as Ii,o as Fm,d as _m,i as Bm,g as Hm,j as Km,k as Vm,f as qm,c as Wm}from"./canvasPrefs-CMulOS0k.js";import{t as Pi,I as Ym}from"./InlineAiPanel-CjYOW0_0.js";import{l as Um,b as Xm,r as Oi}from"./selectionActions-C2a8ImJm.js";import{createFoldMemory as Gm,remapFoldMemory as Jm}from"./foldActions-utwZpRrA.js";import{c as Zm}from"./FloatingToc-iK08Qpjc.js";import{U as Qm}from"./undo-2-C4ZCsMsx.js";import{C as eh}from"./code-xml-vTB4LtTf.js";import{M as th}from"./message-square-plus-CspBv9iG.js";const nh=[["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"}]],oh=tn("align-center-vertical",nh);const rh=[["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"}]],sh=tn("between-horizontal-end",rh);const ah=[["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"}]],ch=tn("between-horizontal-start",ah);const ih=[["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"}]],lh=tn("between-vertical-end",ih);const uh=[["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"}]],dh=tn("between-vertical-start",uh);const fh=[["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"}]],ph=tn("case-sensitive",fh);const mh=[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]],hh=tn("chevrons-down",mh);const gh=[["path",{d:"M4 11V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-1",key:"1q9hii"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]],xh=tn("file-input",gh);const yh=[["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"}]],bh=tn("heading-1",yh);const vh=[["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"}]],wh=tn("heading-2",vh);const kh=[["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"}]],Sh=tn("heading-3",kh);const Ch=[["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"}]],Eh=tn("list-collapse",Ch);const Mh=[["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"}]],zh=tn("list-ordered",Mh);const Ah=[["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=tn("move-horizontal",Ah);const Th=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],$h=tn("move-right",Th);const jh=[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Rh=tn("move-left",jh);const Lh=[["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"}]],Fi=tn("pilcrow",Lh);const Dh=[["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"}]],Ih=tn("regex",Dh);const Ph=[["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"}]],Oh=tn("replace-all",Ph);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"}]],_h=tn("replace",Fh);const Bh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],Hh=tn("rows-2",Bh);const Kh=[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]],Vh=tn("scroll-text",Kh);const qh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]],Wh=tn("smile",qh);const Yh=[["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"}]],Uh=tn("spline",Yh);function Xh(e,t){const n=e.trim().toLowerCase(),o=t.toLowerCase();if(!n)return 1;let r=0,s=0,c=-2,i=-1;for(let a=0;a<o.length&&s<n.length;a++)if(o[a]===n[s]){i<0&&(i=a);let l=1;a===c+1&&(l+=4),(a===0||/[\s/\-_.]/.test(o[a-1]))&&(l+=3),r+=l,c=a,s++}return s<n.length?null:(r-=i*.1,r-=o.length*.02,o===n&&(r+=10),r)}function Gh(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)}Cn({"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 ec="amadeus_delete_assets";function Sw(){try{const e=localStorage.getItem(ec);return e==="yes"?!0:e==="no"?!1:null}catch{return null}}function Jh(e){try{e===null?localStorage.removeItem(ec):localStorage.setItem(ec,e?"yes":"no")}catch{}}const bs=cu(e=>({req:null,open:t=>e({req:t}),clear:()=>e({req:null})}));function Zh(e,t,n){return new Promise(o=>{bs.getState().req?.resolve(null),bs.getState().open({note:e,assets:t,block:n?.block,resolve:o})})}function Cw(){const e=bs(t=>t.req);return e?u.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},children:u.jsx(Qh,{req:e},e.note)}):null}function Qh({req:e}){const{t}=Bt(),[n,o]=x.useState(!1),r=c=>{bs.getState().req===e&&(n&&c!==null&&Jh(c==="with"),bs.getState().clear(),e.resolve(c))};Lf(()=>r(null));const s=e.assets.slice(0,6);return u.jsx("div",{className:"dialog-overlay",onMouseDown:()=>r(null),children:u.jsxs("div",{className:"dialog",onMouseDown:c=>c.stopPropagation(),children:[u.jsx("div",{className:"dialog-title",children:e.block?t("delassets.blockTitle"):t("delassets.noteTitle",{name:e.note})}),u.jsxs("div",{className:"dialog-msg",children:[e.block?t("delassets.blockMsg",{n:e.assets.length}):t("delassets.noteMsg",{n:e.assets.length}),u.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18,opacity:.8},children:[s.map(c=>u.jsx("li",{children:c},c)),e.assets.length>s.length&&u.jsx("li",{children:t("delassets.more",{n:e.assets.length-s.length})})]})]}),!e.block&&u.jsxs("label",{className:"inline-check",style:{display:"flex",gap:6,alignItems:"center",marginTop:10},children:[u.jsx("input",{type:"checkbox",checked:n,onChange:c=>o(c.target.checked)}),t("delassets.remember")]}),u.jsxs("div",{className:"dialog-actions",children:[e.block?u.jsx("button",{className:"dialog-btn",autoFocus:!0,onClick:()=>r("only"),children:t("delassets.keepFiles")}):u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"dialog-btn",onClick:()=>r(null),children:t("delassets.cancel")}),u.jsx("button",{className:"dialog-btn",onClick:()=>r("only"),children:t("delassets.noteOnly")})]}),u.jsx("button",{className:"dialog-btn","data-danger":!0,autoFocus:!e.block,onClick:()=>r("with"),children:t("delassets.deleteAll")})]})]})})}Cn({"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 tc="forsion.amadeus.aiSpaceTrigger";let ds=null;function eg(){if(ds===null)try{ds=localStorage.getItem(tc)==="1"}catch{ds=!1}return ds}function Ew(e){ds=e;try{e?localStorage.setItem(tc,"1"):localStorage.removeItem(tc)}catch{}}Cn({"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 iu=typeof CSS<"u"&&"highlights"in CSS;let Wt=[],vs=[];const Ct=cu(()=>({open:!1,query:"",active:0,total:0,root:null,caseSensitive:!1,regex:!1,bad:!1,replaceOpen:!1,replacement:"",replaceable:0,providerVer:0})),ws=new Set,_i=()=>Ct.setState(e=>({providerVer:e.providerVer+1}));function Bi(e){return ws.add(e),_i(),()=>{ws.delete(e),_i()}}function kc(e){const t=e.startContainer;for(const n of ws)if(n.el.isConnected&&(n.owns?n.owns(t):n.el.contains(t)))return n;return null}function Hi(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 i=Number(c);if(i>=1&&i<t.length)return t[i]??"";if(c.length===2&&Number(c[0])>=1&&Number(c[0])<t.length)return(t[Number(c[0])]??"")+c[1]}return o})}function lu(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 tg(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:M,text:S})=>({from:M.startOffset,to:M.endOffset,text:S,was:M.toString()})).filter(M=>s.slice(M.from,M.to)===M.was).sort((M,S)=>M.from-S.from);if(!c.length)return 0;const i=c[0].from,a=c[c.length-1].to;let l="",m=i;for(const M of c)l+=s.slice(m,M.from)+M.text,m=M.to;l+=s.slice(m,a);const g=document.activeElement;return e.focus(),e.setSelectionRange(i,a),(l?document.execCommand("insertText",!1,l):document.execCommand("delete"))||(e.setRangeText(l,i,a,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))),g?.focus(),o(),c.length},focusAt:r=>t?.contains(r.startContainer)?(e.focus({preventScroll:!0}),e.setSelectionRange(r.startOffset,r.endOffset),!0):!1}}function ng(){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 og(){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 ks=null;function rg(){const e=document.activeElement;if(!(e instanceof HTMLElement)||e===document.body||e.closest(".amx-findbar")){ks=null;return}const t=window.getSelection(),n=t&&t.rangeCount?t.getRangeAt(0):null;ks={el:e,range:e.isContentEditable&&n&&e.contains(n.startContainer)?n.cloneRange():null}}function sg(e){const t=e.startContainer.parentElement;if(!t?.isContentEditable)return null;let n=t;for(;n.parentElement?.isContentEditable;)n=n.parentElement;return n}function ag(e){const t=ks;ks=null;const n=document.activeElement;if(!(n&&n!==document.body&&!n.closest(".amx-findbar"))){if(e){if(kc(e)?.focusAt?.(e))return;const r=sg(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 Mw(e={}){if(!iu)return;const t=og();if(Ct.getState().open){Ct.setState({...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}});const n=document.querySelector(".amx-findbar input");n?.focus(),n?.select();return}rg(),Ct.setState({open:!0,root:ng(),...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}})}function Ea(e){const t=e==="keyboard"?Wt[Ct.getState().active]??null:null;Wt=[],vs=[],fs(-1),Ct.setState({open:!1,query:"",active:0,total:0,root:null,bad:!1,replaceable:0}),e?ag(t):ks=null}const cg=/^(inline|contents|ruby)/;function ig(e,t){let n=e.parentElement;for(;n;){let o=t.get(n);if(o===void 0&&(o=cg.test(getComputedStyle(n).display),t.set(n,o)),!o)return n;n=n.parentElement}return null}function lg(e,t){if(vs=[],!t)return[];const n=new WeakMap,o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(l){const m=l.parentElement;if(!m||!l.nodeValue||m.closest(".amx-findbar"))return NodeFilter.FILTER_REJECT;const g=m.tagName;return g==="SCRIPT"||g==="STYLE"||g==="NOSCRIPT"||g==="TEXTAREA"||!m.checkVisibility()?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let r="";const s=[];let c=null;for(let l=o.nextNode();l;l=o.nextNode()){const m=l,g=ig(m,n);s.length&&g!==c&&(r+=`
3
+ `),c=g,s.push({node:m,at:r.length}),r+=m.nodeValue??""}const i=[];let a=0;t.lastIndex=0;for(let l=t.exec(r);l;l=t.exec(r)){if(!l[0]){t.lastIndex++;continue}if(l[0].includes(`
4
+ `))continue;const m=l.index,g=m+l[0].length;for(;a>0&&s[a].at>m;)a--;for(;a+1<s.length&&s[a+1].at<=m;)a++;let C=a;for(;C+1<s.length&&s[C+1].at<g;)C++;const M=document.createRange();M.setStart(s[a].node,m-s[a].at),M.setEnd(s[C].node,Math.min(g-s[C].at,s[C].node.length)),i.push(M),vs.push(l)}return i}function Ma(e){const t=Ct.getState(),n=lu(t.query,t);return Wt=lg(e,n==="bad"?null:n),Ct.setState({bad:n==="bad",replaceable:Wt.filter(o=>kc(o)).length}),Wt.length}function fs(e){if(!iu)return;const t=CSS.highlights;if(!Wt.length){t.delete("amx-find"),t.delete("amx-find-active");return}t.set("amx-find",new Highlight(...Wt));const n=Wt[e],o=n?new Highlight(n):new Highlight;o.priority=1,t.set("amx-find-active",o)}function ug(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 za(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=ug(n);if(!r)return;const s=r.getBoundingClientRect(),c=r.currentCSSZoom||1;(t.bottom>s.bottom||t.top<s.top)&&(Zm(r),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 zw(){return Ct(t=>t.open)?u.jsx(dg,{}):null}function dg(){const{t:e}=Bt(),t=Ct(q=>q.query),n=Ct(q=>q.active),o=Ct(q=>q.total),r=Ct(q=>q.root),s=Ct(q=>q.caseSensitive),c=Ct(q=>q.regex),i=Ct(q=>q.bad),a=Ct(q=>q.replaceOpen),l=Ct(q=>q.replacement),m=Ct(q=>q.replaceable),g=Ct(q=>q.providerVer),[C,M]=x.useState({top:12,right:12}),S=x.useRef(null),z=!!r&&[...ws].some(q=>q.el.isConnected&&r.contains(q.el));x.useLayoutEffect(()=>{const q=()=>{const de=r?.getBoundingClientRect();de&&M({top:de.top+8,right:Math.max(8,window.innerWidth-de.right+8)})};return q(),window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[r]),x.useLayoutEffect(()=>{if(!r)return;const q=[...ws].filter(de=>de.attach&&r.contains(de.el)).map(de=>de.attach());return()=>q.forEach(de=>de())},[r,g]),x.useEffect(()=>{r&&(Ma(r),Ct.setState({total:Wt.length,active:0}),fs(0),Wt.length&&za(Wt[0]))},[r,t,s,c,g]),x.useEffect(()=>{if(!r)return;const q=()=>{r.isConnected||Ea()};window.addEventListener("focusin",q);const de=window.setInterval(q,1e3);return()=>{window.removeEventListener("focusin",q),window.clearInterval(de)}},[r]),x.useEffect(()=>{if(!r||!t.trim())return;let q=0;const de=new MutationObserver(()=>{window.clearTimeout(q),q=window.setTimeout(()=>{Ma(r);const me=Math.min(Ct.getState().active,Math.max(0,Wt.length-1));Ct.setState({total:Wt.length,active:me}),fs(me)},150)});return de.observe(r,{childList:!0,subtree:!0,characterData:!0}),()=>{window.clearTimeout(q),de.disconnect()}},[r,t,s,c]);const L=q=>{if(!Wt.length)return;const de=(Ct.getState().active+q+Wt.length)%Wt.length;Ct.setState({active:de}),fs(de),za(Wt[de])},E=q=>{if(!r||!Wt.length)return;const de=Ct.getState(),me=q?Wt.map((ce,te)=>te):[de.active],Ne=new Map;for(const ce of me){const te=kc(Wt[ce]);if(!te)continue;const ee=Ne.get(te)??[];ee.push({range:Wt[ce],text:Hi(de.replacement,vs[ce],de.regex)}),Ne.set(te,ee)}let be=0;for(const[ce,te]of Ne)be+=ce.replace(te);if(!be&&!q){L(1);return}const ge=de.active,p=q?"":Hi(de.replacement,vs[de.active],de.regex);Ma(r);let fe=0;if(!q&&Wt.length){const ce=lu(de.query,de),te=ce&&ce!=="bad"?(p.match(new RegExp(ce.source,ce.flags))??[]).length:0;fe=(ge+te)%Wt.length}Ct.setState({total:Wt.length,active:fe}),fs(fe),Wt.length&&za(Wt[fe])},F=q=>q.key==="Escape"?(Ea("keyboard"),!0):(q.metaKey||q.ctrlKey)&&q.altKey&&q.code==="KeyF"?(q.preventDefault(),z&&Ct.setState({replaceOpen:!Ct.getState().replaceOpen}),!0):!1,U=q=>{Ct.setState({[q]:!Ct.getState()[q]}),S.current?.focus()};return u.jsxs("div",{className:`amx-findbar${a&&z?" amx-findbar--replace":""}`,style:{top:C.top,right:C.right},children:[z&&u.jsx("button",{className:"amx-findbar-expand",onClick:()=>Ct.setState({replaceOpen:!a}),title:e("find.toggleReplace"),"aria-label":e("find.toggleReplace"),"aria-expanded":a,children:a?u.jsx(Dp,{size:14}):u.jsx(eu,{size:14})}),u.jsxs("div",{className:"amx-findbar-rows",children:[u.jsxs("div",{className:"amx-findbar-row",children:[u.jsx("input",{ref:S,autoFocus:!0,placeholder:e("find.placeholder"),value:t,"aria-invalid":i||void 0,title:i?e("find.badRegex"):void 0,onFocus:q=>q.currentTarget.select(),onChange:q=>Ct.setState({query:q.target.value}),onKeyDown:q=>{!F(q)&&q.key==="Enter"&&L(q.shiftKey?-1:1),q.stopPropagation()}}),u.jsx("button",{className:"amx-findbar-opt",onClick:()=>U("caseSensitive"),"aria-pressed":s,title:e("find.case"),"aria-label":e("find.case"),children:u.jsx(ph,{size:15})}),u.jsx("button",{className:"amx-findbar-opt",onClick:()=>U("regex"),"aria-pressed":c,title:e("find.regex"),"aria-label":e("find.regex"),children:u.jsx(Ih,{size:14})}),u.jsx("span",{className:"amx-findbar-count",children:o?`${n+1}/${o}`:t.trim()?"0":""}),u.jsx("button",{onClick:()=>L(-1),title:e("find.prev"),"aria-label":e("find.prev"),children:"‹"}),u.jsx("button",{onClick:()=>L(1),title:e("find.next"),"aria-label":e("find.next"),children:"›"}),u.jsx("button",{onClick:()=>Ea("pointer"),title:e("find.close"),"aria-label":e("find.close"),children:"✕"})]}),a&&z&&u.jsxs("div",{className:"amx-findbar-row",children:[u.jsx("input",{className:"amx-findbar-replace",placeholder:e("find.replacePlaceholder"),value:l,onChange:q=>Ct.setState({replacement:q.target.value}),onKeyDown:q=>{!F(q)&&q.key==="Enter"&&E(q.metaKey||q.ctrlKey),q.stopPropagation()}}),u.jsx("button",{className:"amx-findbar-act",onClick:()=>E(!1),disabled:!m,title:e("find.replaceOne"),"aria-label":e("find.replaceOne"),children:u.jsx(_h,{size:14})}),u.jsx("button",{className:"amx-findbar-act",onClick:()=>E(!0),disabled:!m,title:e("find.replaceAll"),"aria-label":e("find.replaceAll"),children:u.jsx(Oh,{size:14})})]})]})]})}function Er(e){const t=fd(e);return t.length===e.length&&e.startsWith(Js)?{fmText:Js,body:e.slice(1)}:{fmText:e.slice(0,e.length-t.length),body:t}}function mn(e,t){return e+t}function Aa(e,t){const n=Cs(e);return n.trim()&&!fg(n)?e:Er(pd(e,t)).fmText}function fg(e){try{const t=aa(e);return t==null||typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function pg(e,t){const n=mg(e,t);if(n!==null)return oc(e,n);const{bom:o}=Ss(e),r=rc(e),s=t.replace(/\n+$/,"");if(!r.length&&!s.trim())return o;const c=o+["---",...r,...s.trim()?[s]:[],"---",""].join(`
5
+ `);return nc(s)?oc(e,c):c}function mg(e,t){const n=Cs(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 Cs(c)===o&&rc(c).join(`
7
+ `)===rc(e).join(`
8
+ `)?c:null}function nc(e){try{return aa(e),!0}catch{return!1}}function oc(e,t){if(t===e)return t;const n=Ss(t).inner;if(n==null||nc(n))return t;const o=Ss(e).inner;return o==null||!nc(o)?t:(console.warn("[amadeus] frontmatter rewrite would produce invalid YAML; keeping the original block"),e)}const hg=/^---\r?\n([\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)$/;function Ss(e){const t=e.startsWith(Js)?Js:"",n=hg.exec(e.slice(t.length));return{bom:t,inner:n?n[1]??"":null}}function Sc(e){const{inner:t}=Ss(e);return t==null?null:t?hd(t.replace(/\r?\n$/,"").split(/\r?\n/)):[]}function rc(e){return(Sc(e)??[]).filter(t=>md.test(t[0])).flat()}const gg=/^["']?amadeus_(schema|layout|canvas)["']?\s*:/;function ps(e,t,n){const{bom:o}=Ss(e),r=Sc(e)??[],s=r.filter(a=>!gg.test(a[0])).flat(),i=[...Df(t,n).flatMap(a=>{const l=yg.exec(a)?.[1],m=l?du(r,l):null;return m&&m.length>1&&fu(m,l)===(l==="layout"?t:n)?m:[a]}),...s];return i.length?oc(e,o+["---",...i,"---",""].join(`
9
+ `)):o}function xg(e){const t=xo(e),n=un(e);return t==null&&n==null||/^["']?amadeus_schema["']?\s*:/m.test(e)?e:ps(e,t,n)}function xo(e){return uu(e,"layout")}function un(e){return uu(e,"canvas")}const yg=/^amadeus_(layout|canvas):/;function uu(e,t){const n=Sc(e),o=n&&du(n,t);return o?fu(o,t):null}function du(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 fu(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=aa(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 bg(e){return e?hc(Bl(e)):{}}function Cs(e){return e?Bl(e):""}const vg=80;function wg(){return Et(()=>{if(!Wr())return new Yt({});const e=Math.round(vg*Mn(document.body));return new Yt({props:{scrollThreshold:{top:0,left:0,right:0,bottom:e},scrollMargin:{top:5,left:5,right:5,bottom:e}}})})}function na(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 Ki(e,t=0,n=e.content.size){return e.textBetween(t,n,`
11
+ `,()=>"").replace(/!\[\[[^\]\n]*\]\]/g,"").replace(/\[\[(?:[^\]|\n]*\|)?([^\]\n]*)\]\]/g,"$1")}function kg(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=ai(Ki(t)));const{from:r,to:s,empty:c}=o.state.selection;return{all:n,sel:c?null:ai(Ki(o.state.doc,r,s))}}}function Sg(){return[Et(()=>new Yt({view:()=>{let e=0;const t=()=>{e||(e=requestAnimationFrame(()=>{e=0,Gc()}))};return t(),{update:(n,o)=>{(n.state.doc!==o.doc||!n.state.selection.eq(o.selection))&&t()},destroy:()=>{e&&cancelAnimationFrame(e),Gc()}}}}))]}function Cg(e){const t=(o,r,s)=>{const c=o.selection;return!(c instanceof Le)||!c.empty||!s||Wo.atStart(o.doc).$from.start()!==c.$from.start()||!s.endOfTextblock("up")?!1:e()},n=o=>{const r=o.selection;if(!(r instanceof Le)||!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(()=>Ko({ArrowUp:t,ArrowLeft:n}))]}function Vi(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 Yt({view:t=>{try{localStorage.getItem("amx_probe")&&(window.__amxView=t)}catch{}let n=!0,o=null;const r=()=>{o=null;const{vaultRoot:c,path:i}=e.where(),a=t.state.selection;Pp(c,i,{a:a.anchor,h:a.head,t:Vi(t.state.doc,a.head)})};queueMicrotask(()=>{if(!n||!e.restore())return;const{vaultRoot:c,path:i}=e.where(),a=Ip(c,i),l=t.state.doc;let m=null;if(a&&a.a<=l.content.size&&a.h<=l.content.size&&Vi(l,a.h)===a.t){try{m=Le.between(l.resolve(a.a),l.resolve(a.h))}catch{m=null}m&&(m.anchor!==a.a||m.head!==a.h)&&(m=null)}m&&t.dispatch(t.state.tr.setSelection(m).setMeta("addToHistory",!1)),e.focus()&&t.focus()});const s=()=>{o&&(clearTimeout(o),r(),Op())};return window.addEventListener("pagehide",s),{update:(c,i)=>{c.state.selection.eq(i.selection)&&c.state.doc===i.doc||(o&&clearTimeout(o),o=setTimeout(r,300))},destroy:()=>{n=!1,window.removeEventListener("pagehide",s),o&&(clearTimeout(o),r())}}}}))]}Cn({"canvasseg.aria":{zh:"编辑模式",en:"Editing mode"},"canvasseg.doc":{zh:"文档",en:"Document"},"canvasseg.canvas":{zh:"画布",en:"Canvas"}});const Mg="amx-modeseg-slot";function pu(e,t){return{modes:[{value:"doc",label:je("canvasseg.doc"),icon:Fp},{value:"canvas",label:je("canvasseg.canvas"),icon:au,guideAnchor:"note-canvas"}],value:e?"canvas":"doc",onChange:n=>{n==="canvas"!==e&&t()},ariaLabel:je("canvasseg.aria")}}function zg({on:e,toggle:t,leafId:n}){return Bt(),n?u.jsx(gi,{className:"amx-modeseg",leafId:n}):u.jsx(gi,{className:"amx-modeseg",spec:pu(e,t)})}function Ag({anchor:e,on:t,toggle:n,leafId:o}){const[r,s]=x.useState(null);return x.useEffect(()=>{const c=e?.closest(".amx-pane")??e?.ownerDocument?.body;if(!c)return;const i=()=>s(c.querySelector(`.${Mg}`));i();const a=new MutationObserver(i);return a.observe(c,{childList:!0,subtree:!0}),()=>a.disconnect()},[e]),r?bc.createPortal(u.jsx(zg,{on:t,toggle:n,leafId:o}),r):null}Cn({"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 Ng=["text","number","checkbox","date","list"];function Tg(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 $g=e=>/^(tags?|alias(es)?|cssclass(es)?)$/i.test(e.trim())?"list":"text",mu=e=>/\[\[[^\]\n]+\]\]/.test(e);function Na(e){if(!e.trim())return{ok:!0,entries:[]};try{const t=aa(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 hu=e=>Array.isArray(e)&&e.every(t=>t===null||typeof t!="object");function Ta(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 gu=x.createContext(null);function Cc(e,t,{escDiscards:n="conflict",norm:o=s=>s,enterCommits:r=!1}={}){const[s,c]=x.useState(null),[i,a]=x.useState(e),l=x.useRef({draft:s,base:i,current:e,norm:o,commit:t});l.current.current=e,l.current.norm=o,l.current.commit=t;const m=z=>{l.current.draft=z,c(z)},g=z=>{l.current.base=z,a(z)},C=x.useContext(gu);x.useLayoutEffect(()=>{if(!C)return;const z=()=>{const L=l.current,E=Ta(L.draft,L.base,L.current,L.norm);E!==null&&(g(E),L.commit(E))};return C.add(z),()=>{C.delete(z),z()}},[C]);const M=s!==null&&e!==i&&Ta(s,i,e,o)!==null;return{shown:s??e,conflict:M,change:z=>{l.current.draft===null&&g(l.current.current),m(z)},settle:()=>{const z=l.current,L=Ta(z.draft,z.base,z.current,z.norm);return m(null),L},onKeyDown:z=>{if(!(z.nativeEvent.isComposing||z.keyCode===229)){if(z.key==="Enter"&&r){z.preventDefault(),z.currentTarget.blur();return}z.key!=="Escape"||n==="never"||!M||(z.preventDefault(),z.stopPropagation(),m(null))}}}}function jg({fmExtra:e,onCommit:t,readOnly:n=!1,notePath:o}={}){const{t:r}=Bt(),s=dn(ee=>ee.activePage),c=dn(ee=>ee.vaultRoot),i=dn(ee=>ee.manifest?.fmExtra??""),a=Zr(),l=e!==void 0,m=l?e:i,g=x.useRef(m);g.current=m;const[C,M]=x.useState(()=>xi(c)??!1);x.useEffect(()=>{M(xi(c)??!1)},[c]);const S=ee=>{M(Ie=>{const Me=typeof ee=="function"?ee(Ie):ee;return Bp(c,Me),Me})},[z,L]=x.useState(!1),[E,F]=x.useState(null),U=x.useRef(null),q=o??s??void 0,de=ee=>{if(Pf(ee))return;const Ie=Hl(ee);Ie&&a.getState().openWikiLink(Ie,q)},me=x.useMemo(()=>Na(m),[m]),Ne=x.useMemo(()=>{const ee=!l&&s?If(s):void 0;return new Set(ee?.fmKeys??[])},[l,s]),be=x.useMemo(()=>me.entries.map((ee,Ie)=>({...ee,idx:Ie})).filter(ee=>!Ne.has(ee.key)),[me,Ne]);if(x.useEffect(()=>{if(!E)return;const Ie=[...U.current?.querySelectorAll(".amx-prop-row[data-key]")??[]].find(Me=>Me.dataset.key===E)?.querySelector("input:not(.amx-prop-key), textarea, .amx-prop-links");Ie&&(Ie.focus(),Ie.classList.contains("amx-prop-links")&&Ie.click(),F(null))},[E,me]),!l&&!s)return null;const ge=ee=>{t?t(ee):a.getState().setFmExtra(ee)},p=ee=>{ee!==null&&ge(ee)},fe=(ee,Ie)=>p(yd(g.current,{[ee]:Ie})),ce=(ee,Ie)=>{const Me=ee.trim();return Me?/^amadeus_/.test(Me)?(window.alert(r("amprops.reservedKey")),!1):Ne.has(Me)?(window.alert(r("amprops.pluginManaged")),!1):(Na(g.current).entries.some(dt=>dt.key===Me)||fe(Me,Tg(Ie)),F(Me),!0):!1},te=me.ok?be.length:null;return u.jsxs("div",{className:`amx-props${te===0&&!C?" is-empty":""}`,ref:U,children:[u.jsxs("div",{className:"amx-props-bar",children:[u.jsxs("button",{className:"amx-props-chip",onClick:()=>S(ee=>!ee),children:[te===null?r("amprops.chipRaw"):r("amprops.chipCount",{n:te}),C?" ▾":" ▸"]}),!n&&u.jsx("button",{className:"amx-props-add",title:r("amprops.add"),onClick:()=>{S(!0),me.ok&&L(!0)},children:u.jsx(_p,{size:12})})]}),C&&(me.ok?u.jsxs("div",{className:"amx-props-rows",children:[be.length===0&&!z&&u.jsx("div",{className:"amx-props-empty",children:r("amprops.empty")}),be.map(ee=>n?u.jsxs("div",{className:"amx-prop-row amx-prop-row-ro",children:[u.jsx("span",{className:"amx-prop-key",children:ee.key}),u.jsx(Dg,{value:ee.value})]},`${s}:${ee.idx}:${ee.key}`):u.jsxs("div",{className:"amx-prop-row","data-key":ee.key,children:[u.jsx(Lg,{name:ee.key,onRename:Ie=>{const Me=/^(amadeus_page|amadeus_schema|amadeus_layout|amadeus_canvas|amadeus_next_id)$/.test(Ie)||Ne.has(Ie)||Na(g.current).entries.some(dt=>dt.key!==ee.key&&dt.key===Ie);!Ie||Me||p(gd(g.current,ee.key,Ie))}}),u.jsx(Og,{value:ee.value,onCommit:Ie=>fe(ee.key,Ie),onOpenLink:de}),u.jsx("button",{className:"amx-prop-del",title:r("amprops.delete"),onClick:()=>fe(ee.key,void 0),children:u.jsx(ia,{size:12})})]},`${s}:${ee.key}`)),z&&!n&&u.jsx(Ig,{onAdd:(ee,Ie)=>{ce(ee,Ie)&&L(!1)},onCancel:()=>L(!1)})]}):u.jsxs(u.Fragment,{children:[Ne.size>0&&u.jsx("div",{className:"amx-props-empty",children:r("amprops.pluginKeysWarn",{keys:[...Ne].join(", ")})}),u.jsx(Rg,{text:m,readOnly:n,onCommit:ge})]}))]})}function Rg({text:e,readOnly:t,onCommit:n}){const{t:o}=Bt(),r=c=>{t||n(c)},s=Cc(e,r,{escDiscards:"never"});return u.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=Cc(e,t,{norm:o=>o.trim(),enterCommits:!0});return u.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 Dg({value:e}){return typeof e=="boolean"?u.jsx("span",{className:"amx-prop-check","aria-hidden":!0,children:e?"☑":"☐"}):hu(e)?u.jsx("span",{className:"amx-prop-chips",children:e.map((t,n)=>u.jsx("span",{className:"amx-chip",children:String(t??"")},n))}):e==null?u.jsx("span",{className:"amx-prop-input"}):typeof e=="object"?u.jsx("span",{className:"amx-prop-input",children:JSON.stringify(e)}):u.jsx("span",{className:"amx-prop-input",children:String(e)})}function Ig({onAdd:e,onCancel:t}){const{t:n}=Bt(),[o,r]=x.useState(""),[s,c]=x.useState("text"),[i,a]=x.useState(!1),l=i?s:$g(o);return u.jsxs("div",{className:"amx-prop-row amx-prop-new",children:[u.jsx("input",{className:"amx-prop-key",autoFocus:!0,value:o,placeholder:n("amprops.keyPlaceholder"),"aria-label":n("amprops.addLabel"),onChange:m=>r(m.target.value),onKeyDown:m=>{m.nativeEvent.isComposing||m.keyCode===229||(m.key==="Enter"?(m.preventDefault(),e(o,l)):m.key==="Escape"&&(m.preventDefault(),t()))}}),u.jsx("select",{className:"amx-prop-type","aria-label":n("amprops.type"),value:l,onChange:m=>{c(m.target.value),a(!0)},onKeyDown:m=>{m.key==="Escape"&&(m.preventDefault(),t())},children:Ng.map(m=>u.jsx("option",{value:m,children:n(`amprops.type.${m}`)},m))}),u.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addConfirm"),"aria-label":n("amprops.addConfirm"),onClick:()=>e(o,l),children:u.jsx(zs,{size:12})}),u.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addCancel"),"aria-label":n("amprops.addCancel"),onClick:t,children:u.jsx(ia,{size:12})})]})}function xu({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],i=c.indexOf("|");n.push(u.jsx("span",{className:"amx-prop-link",onMouseDown:a=>{a.preventDefault(),a.stopPropagation(),t(c)},onClick:a=>a.stopPropagation(),children:i>=0?c.slice(i+1):c},s.index)),r=s.index+s[0].length}return r<e.length&&n.push(e.slice(r)),u.jsx(u.Fragment,{children:n})}function Pg({value:e,onCommit:t,onOpenLink:n}){const{t:o}=Bt(),[r,s]=x.useState(!1);return r?u.jsx(sc,{current:e,autoFocus:!0,onCommit:t,onDone:()=>s(!1)}):u.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:u.jsx(xu,{text:e,onOpenLink:n})})}function Og({value:e,onCommit:t,onOpenLink:n}){const{t:o}=Bt();return typeof e=="boolean"?u.jsx("input",{type:"checkbox",className:"amx-prop-check",checked:e,onChange:r=>t(r.target.checked)}):hu(e)?u.jsx(_g,{items:e.map(r=>String(r??"")),onCommit:t,onOpenLink:n}):typeof e=="number"?u.jsx(sc,{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)?u.jsx(Fg,{value:e,onCommit:t}):typeof e=="string"&&!e.includes(`
13
+ `)&&mu(e)?u.jsx(Pg,{value:e,onCommit:t,onOpenLink:n}):typeof e=="string"||e==null?u.jsx(sc,{current:e??"",multiline:typeof e=="string"&&e.includes(`
14
+ `),onCommit:t}):u.jsx("span",{className:"amx-prop-nested",title:o("amprops.nestedHint"),children:xd(e).trimEnd()})}function sc({current:e,norm:t,multiline:n=!1,autoFocus:o,onCommit:r,onDone:s}){const{t:c}=Bt(),i=Cc(e,r,{norm:t,enterCommits:!n}),a={className:`amx-prop-input${n?" amx-prop-multiline":""}${i.conflict?" amx-prop-conflict":""}`,value:i.shown,title:i.conflict?c("amprops.conflict",{v:e}):void 0,autoFocus:o,onKeyDown:i.onKeyDown,onBlur:()=>{const l=i.settle();l!==null&&r(l),s?.()}};return n?u.jsx("textarea",{...a,rows:Math.min(8,i.shown.replace(/\n$/,"").split(`
15
+ `).length),spellCheck:!1,onChange:l=>i.change(l.target.value)}):u.jsx("input",{...a,onChange:l=>i.change(l.target.value)})}function Fg({value:e,onCommit:t}){const[n,o]=x.useState(!1);return u.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 _g({items:e,onCommit:t,onOpenLink:n}){const{t:o}=Bt(),[r,s]=x.useState(""),c=()=>{const a=r.trim();s(""),a&&!e.includes(a)&&t([...e,a])},i=a=>{a.nativeEvent.isComposing||a.keyCode===229||(a.key==="Enter"||a.key===","?(a.preventDefault(),c()):a.key==="Backspace"&&!r&&e.length&&t(e.slice(0,-1)))};return u.jsxs("div",{className:"amx-prop-chips",children:[e.map((a,l)=>u.jsxs("span",{className:"amx-chip",children:[n&&mu(a)?u.jsx(xu,{text:a,onOpenLink:n}):a,u.jsx("button",{className:"amx-chip-x",onClick:()=>t(e.filter((m,g)=>g!==l)),children:u.jsx(ia,{size:10})})]},`${l}:${a}`)),u.jsx("input",{value:r,placeholder:e.length?"":o("amprops.chipsPlaceholder"),onChange:a=>s(a.target.value),onKeyDown:i,onBlur:c})]})}Cn({"pgchrome.coverDragHint":{zh:"上下拖动图片调整位置",en:"Drag the image up or down to reposition"},"pgchrome.coverDone":{zh:"完成",en:"Done"},"pgchrome.coverChange":{zh:"更换封面",en:"Change cover"},"pgchrome.coverReposition":{zh:"调整位置",en:"Reposition"},"pgchrome.coverRemove":{zh:"移除",en:"Remove"},"pgchrome.coverTitle":{zh:"封面",en:"Cover"},"pgchrome.close":{zh:"关闭封面选择器",en:"Close cover picker"},"pgchrome.featured":{zh:"精选图片",en:"Featured images"},"pgchrome.results":{zh:"搜索结果",en:"Search results"},"pgchrome.chooseCover":{zh:"选择封面 {index}",en:"Choose cover {index}"},"pgchrome.imageUrl":{zh:"图片链接",en:"Image URL"},"pgchrome.urlHint":{zh:"使用公开可访问的图片链接。",en:"Use a publicly accessible image URL."},"pgchrome.uploadTitle":{zh:"上传封面图片",en:"Upload a cover image"},"pgchrome.tabGallery":{zh:"图库",en:"Gallery"},"pgchrome.tabUrl":{zh:"链接",en:"Link"},"pgchrome.tabUpload":{zh:"上传",en:"Upload"},"pgchrome.searchPlaceholder":{zh:"搜索图片…",en:"Search images…"},"pgchrome.search":{zh:"搜索",en:"Search"},"pgchrome.searchUnavailable":{zh:"图库接口暂不可达,可从上方精选挑,或用「链接/上传」。",en:"The image library is unreachable right now — pick a featured cover above, or use Link or Upload."},"pgchrome.searchEmpty":{zh:"没搜到结果,上方为精选封面。",en:"No results — the covers above are our featured picks."},"pgchrome.urlPlaceholder":{zh:"粘贴图片地址(https://…)",en:"Paste an image URL (https://…)"},"pgchrome.setCover":{zh:"设为封面",en:"Set as cover"},"pgchrome.chooseLocal":{zh:"选择本地图片…",en:"Choose a local image…"},"pgchrome.uploadHint":{zh:"图片会保存到当前智库的附件位置。",en:"Images are saved with attachments in this vault."},"pgchrome.emojiPlaceholder":{zh:"搜索 emoji(中/英),或粘贴任意字符后回车…",en:"Search emoji (Chinese or English), or paste any character and press Enter…"},"pgchrome.emojiEmpty":{zh:"没有匹配的 emoji —— 回车可直接用你输入的字符",en:"No matching emoji — press Enter to use what you typed"},"pgchrome.removeIcon":{zh:"移除图标",en:"Remove icon"}});const Bg=/^(未命名|untitled)(-\d+)?$/i;function Hg(){const e=dn(t=>t.manifest?.fmExtra??"");return x.useMemo(()=>{const t=hc(e).cover;return typeof t=="string"&&t.trim()?t.trim():null},[e])}function Kg(){const e=dn(t=>t.manifest?.fmExtra??"");return x.useMemo(()=>{const t=hc(e).cover_y,n=typeof t=="number"?t:typeof t=="string"?parseFloat(t):NaN;return Number.isFinite(n)?Math.max(0,Math.min(100,n)):50},[e])}function $a(e){const t=e.naturalWidth,n=e.naturalHeight,o=e.clientWidth,r=e.clientHeight;return!t||!n||!o||!r?0:n*Math.max(o/t,r/n)-r}function Vg({page:e,cover:t,coverY:n,onSetCover:o,onSetCoverY:r,readOnly:s=!1}={}){const{t:c}=Bt(),i=dn(ce=>ce.activePage),a=Hg(),l=Kg(),m=Zr(),[g,C]=x.useState(null),[M,S]=x.useState(null),[z,L]=x.useState(!1),[E,F]=x.useState(0),U=x.useRef(null),q=x.useRef(null),de=e??i;x.useEffect(()=>{const ce=U.current;if(!ce)return;const te=()=>F($a(ce));te();const ee=new ResizeObserver(te);return ee.observe(ce),()=>ee.disconnect()},[de,t,a]),x.useEffect(()=>{z&&E<1&&L(!1)},[z,E]);const me=t!==void 0?t:a,be=M??(n??l),ge=o??(ce=>{de&&m.getState().setPageCover(de,ce)}),p=r??(ce=>{de&&m.getState().setPageCoverY(de,ce)});if(!de||!me)return null;const fe=/^https?:\/\//i.test(me)?me:gc(me);return u.jsxs("div",{className:`amx-cover${z?" amx-cover-repo":""}`,children:[u.jsx("img",{ref:U,src:fe,alt:"",draggable:!1,style:{objectPosition:`50% ${be}%`},onLoad:ce=>F($a(ce.currentTarget)),onPointerDown:ce=>{if(!z||!ce.isPrimary||ce.pointerType==="mouse"&&ce.button!==0)return;const te=$a(ce.currentTarget);if(te<1)return;ce.preventDefault(),ce.currentTarget.setPointerCapture(ce.pointerId);const ee=ce.currentTarget.currentCSSZoom||1;q.current={id:ce.pointerId,startY:ce.clientY,base:be,z:ee,slack:te,cur:be}},onPointerMove:ce=>{const te=q.current;if(!te||te.id!==ce.pointerId)return;const ee=(ce.clientY-te.startY)/te.z;te.cur=Math.max(0,Math.min(100,te.base-ee/te.slack*100)),S(te.cur)},onPointerUp:ce=>{const te=q.current;if(!te||te.id!==ce.pointerId)return;q.current=null,S(null);const ee=Math.round(te.cur*10)/10;ee!==te.base&&p(ee)},onPointerCancel:()=>{q.current=null,S(null)},onError:ce=>{ce.target.style.opacity="0.15"}}),u.jsx("div",{className:"amx-cover-grad"}),z&&u.jsx("div",{className:"amx-cover-hint",children:c("pgchrome.coverDragHint")}),!s&&u.jsx("div",{className:"amx-cover-tools",children:z?u.jsx("button",{onClick:()=>L(!1),children:c("pgchrome.coverDone")}):u.jsxs(u.Fragment,{children:[u.jsx("button",{onClick:ce=>{const te=ce.currentTarget.getBoundingClientRect();C({x:te.right,y:te.bottom+6})},children:c("pgchrome.coverChange")}),E>=1&&u.jsx("button",{onClick:()=>L(!0),children:c("pgchrome.coverReposition")}),u.jsx("button",{onClick:()=>ge(null),children:c("pgchrome.coverRemove")})]})}),g&&u.jsx(yu,{page:de,x:g.x,y:g.y,onApply:o??void 0,onClose:()=>C(null)})]})}const qg=["aurora","forest","ocean","alpine","metro","night","coast","mist","valley","dune","lake","bloom"].map(e=>({thumb:`https://picsum.photos/seed/${e}/320/180`,full:`https://picsum.photos/seed/${e}/1600/900`,source:"Picsum"}));function yu({page:e,x:t,y:n,onClose:o,onApply:r}){const{t:s}=Bt(),c=!!on.searchImages,i=Zr(),[a,l]=x.useState("gallery"),[m,g]=x.useState(""),[C,M]=x.useState(null),[S,z]=x.useState(!1),[L,E]=x.useState(!1),[F,U]=x.useState(""),[q,de]=x.useState(null),me=x.useId(),Ne=x.useRef([]),be=x.useRef(o);be.current=o,x.useEffect(()=>{const ee=document.activeElement instanceof HTMLElement?document.activeElement:null,Ie=Me=>{Me.key==="Escape"&&(Me.preventDefault(),Me.stopPropagation(),be.current())};return document.addEventListener("keydown",Ie,!0),()=>{document.removeEventListener("keydown",Ie,!0),ee?.isConnected&&ee.focus({preventScroll:!0})}},[]);const ge=[{id:"gallery",label:"pgchrome.tabGallery",icon:Of},{id:"url",label:"pgchrome.tabUrl",icon:Jl},{id:"upload",label:"pgchrome.tabUpload",icon:$i}],p=ee=>{de(ee),r?r(ee):i.getState().setPageCover(e,ee)},fe=()=>{const ee=m.trim();!ee||!on.searchImages||(z(!0),E(!1),on.searchImages(ee).then(Ie=>{M(Ie),z(!1)}).catch(()=>{M(null),E(!0),z(!1)}))},ce=()=>{const ee=document.createElement("input");ee.type="file",ee.accept="image/*",ee.onchange=()=>{const Ie=ee.files?.[0];Ie&&(async()=>{try{const Me=new Uint8Array(await Ie.arrayBuffer()),{opts:dt}=await ta(),{pageRel:tt}=await on.saveAttachment(e,Ie.name||"cover.png",Me,dt);p(xc(e.split("/").slice(0,-1).join("/"),tt))}catch{}})()},ee.click()},te=ee=>u.jsx("div",{className:"amx-coverpick-grid",children:ee.map((Ie,Me)=>u.jsxs("button",{className:"amx-coverpick-item","aria-label":s("pgchrome.chooseCover",{index:Me+1}),"aria-pressed":q===Ie.full,onClick:()=>p(Ie.full),children:[u.jsxs("span",{className:"amx-coverpick-thumb",children:[u.jsx(tu,{size:20,strokeWidth:1.7,"aria-hidden":"true"}),u.jsx("img",{src:Ie.thumb,alt:"",loading:"lazy",onError:dt=>{dt.currentTarget.hidden=!0}}),q===Ie.full&&u.jsx("span",{className:"amx-coverpick-selected",children:u.jsx(zs,{size:14,"aria-hidden":"true"})})]}),Ie.author&&u.jsx("span",{className:"amx-coverpick-cap",children:Ie.author})]},Ie.full))});return bc.createPortal(u.jsx("div",{className:"ui-popover-backdrop am-app",onMouseDown:o,children:u.jsxs(lr,{className:"ui-popover amx-coverpick",role:"dialog","aria-label":s("pgchrome.coverTitle"),x:t-336,y:n,onMouseDown:ee=>ee.stopPropagation(),children:[u.jsxs("div",{className:"amx-coverpick-header",children:[u.jsx("span",{children:s("pgchrome.coverTitle")}),u.jsx("button",{className:"amx-coverpick-close",onClick:o,"aria-label":s("pgchrome.close"),children:u.jsx(ia,{size:14,strokeWidth:1.7,"aria-hidden":"true"})})]}),u.jsx("div",{className:"amx-coverpick-tabs",role:"tablist","aria-label":s("pgchrome.coverTitle"),children:ge.map(({id:ee,label:Ie,icon:Me},dt)=>u.jsxs("button",{ref:tt=>{Ne.current[dt]=tt},id:`${me}-${ee}`,role:"tab","aria-selected":a===ee,"aria-controls":me,tabIndex:a===ee?0:-1,onClick:()=>l(ee),onKeyDown:tt=>{const J=tt.key==="ArrowRight"?(dt+1)%ge.length:tt.key==="ArrowLeft"?(dt+ge.length-1)%ge.length:tt.key==="Home"?0:tt.key==="End"?ge.length-1:-1;J<0||(tt.preventDefault(),l(ge[J].id),Ne.current[J]?.focus())},children:[u.jsx(Me,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),s(Ie)]},ee))}),u.jsxs("div",{id:me,role:"tabpanel","aria-labelledby":`${me}-${a}`,className:"amx-coverpick-panel",children:[a==="gallery"&&u.jsxs("div",{className:"amx-coverpick-body",children:[c&&u.jsxs("div",{className:"amx-coverpick-search",children:[u.jsx(Ff,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),u.jsx("input",{"aria-label":s("pgchrome.searchPlaceholder"),placeholder:s("pgchrome.searchPlaceholder"),value:m,onChange:ee=>g(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"&&fe()}}),u.jsx("button",{className:"amx-coverpick-go",disabled:S||!m.trim(),onClick:fe,children:S?"…":s("pgchrome.search")})]}),u.jsx("div",{className:"amx-coverpick-section",children:s(C?.length?"pgchrome.results":"pgchrome.featured")}),te(C&&C.length>0?C:qg),!S&&L&&u.jsx("div",{className:"amx-coverpick-hint",children:s("pgchrome.searchUnavailable")}),!S&&!L&&C?.length===0&&u.jsx("div",{className:"amx-coverpick-hint",children:s("pgchrome.searchEmpty")})]}),a==="url"&&u.jsxs("div",{className:"amx-coverpick-body amx-coverpick-url",children:[u.jsx("label",{htmlFor:`${me}-url-input`,children:s("pgchrome.imageUrl")}),u.jsx("input",{id:`${me}-url-input`,placeholder:s("pgchrome.urlPlaceholder"),value:F,onChange:ee=>U(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"&&/^https?:\/\//i.test(F.trim())&&p(F.trim())}}),u.jsx("div",{className:"amx-coverpick-hint",children:s("pgchrome.urlHint")}),u.jsx("button",{className:"amx-coverpick-go",disabled:!/^https?:\/\//i.test(F.trim()),onClick:()=>{/^https?:\/\//i.test(F.trim())&&p(F.trim())},children:s("pgchrome.setCover")})]}),a==="upload"&&u.jsxs("div",{className:"amx-coverpick-body amx-coverpick-upload",children:[u.jsx($i,{size:24,strokeWidth:1.5,"aria-hidden":"true"}),u.jsx("div",{className:"amx-coverpick-upload-title",children:s("pgchrome.uploadTitle")}),u.jsx("div",{className:"amx-coverpick-hint",children:s("pgchrome.uploadHint")}),u.jsx("button",{className:"amx-coverpick-go",onClick:ce,children:s("pgchrome.chooseLocal")})]})]})]})}),document.body)}const Wg=()=>oi[Math.floor(Math.random()*oi.length)];function Yg({x:e,y:t,current:n,onPick:o,onClose:r}){const{t:s}=Bt(),[c,i]=x.useState(""),a=Kd(c);return u.jsx("div",{className:"amx-db-popwrap",onMouseDown:r,children:u.jsxs(lr,{className:"amx-db-pop amx-iconpick",x:e,y:t,onMouseDown:l=>l.stopPropagation(),children:[u.jsx("input",{className:"amx-db-pop-input",autoFocus:!0,placeholder:s("pgchrome.emojiPlaceholder"),value:c,onChange:l=>i(l.target.value),onKeyDown:l=>{if(l.key==="Escape"){r();return}l.key!=="Enter"||!c.trim()||o(a&&a.length?a[0]:c.trim())}}),u.jsxs("div",{className:"amx-iconpick-grid",children:[a?a.map(l=>u.jsx("button",{className:`amx-iconpick-item${n===l?" active":""}`,onClick:()=>o(l),children:l},l)):Vd.map(l=>u.jsxs(x.Fragment,{children:[u.jsx("div",{className:"amx-iconpick-group",children:s(l.nameKey)}),l.items.map(([m,g])=>u.jsx("button",{className:`amx-iconpick-item${n===m?" active":""}`,title:g,onClick:()=>o(m),children:m},`${l.nameKey}-${m}`))]},l.nameKey)),a&&a.length===0&&u.jsx("div",{className:"amx-iconpick-empty",children:s("pgchrome.emojiEmpty")})]}),n&&u.jsx("button",{className:"amx-db-opt amx-db-opt-clear",onClick:()=>o(null),children:s("pgchrome.removeIcon")})]})})}const Ug=new Set(["bullet","ordered","task"]);function Xg(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 bu(e,t,n,o){if(o.kind!=="quote"&&o.kind!=="fold"){const i=e.state.tr,a=i.doc.content.size;e.state.doc.nodesBetween(t,n,(l,m)=>l.type.name==="blockquote"?(wu(i,i.mapping.map(m)),!1):!l.isTextblock),i.docChanged&&(e.dispatch(i),n+=i.doc.content.size-a)}const r=[];e.state.doc.nodesBetween(t,n,(i,a)=>i.isTextblock?(r.push(a+1),!1):!0);const s=e.state.doc.content.size;let c=!1;for(const i of r.reverse())e.dispatch(e.state.tr.setSelection(Le.near(e.state.doc.resolve(i)))),ca(e,o,null)&&(c=!0);return c&&Ug.has(o.kind)&&Gg(e,t,n+(e.state.doc.content.size-s)),c}function Gg(e,t,n){const{doc:o}=e.state,r=o.resolve(t),s=r.parent,c=[];let i=r.start();for(let l=0;l<r.index();l++)i+=s.child(l).nodeSize;for(let l=r.index();l<s.childCount-1;l++){const m=s.child(l);if(i+=m.nodeSize,i>=n)break;const g=s.child(l+1);m.type===g.type&&/_list$/.test(m.type.name)&&c.push(i)}if(!c.length)return;const a=e.state.tr;for(const l of c.reverse())Hf(a.doc,l)&&a.join(l);a.docChanged&&e.dispatch(a)}function ac(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 i=o.doc.textBetween(t,n,`
16
+ `,`
17
+ `).replace(/^\n+|\n+$/g,""),a=o.tr.replaceWith(t,n,r.create(null,i?o.schema.text(i):void 0));return a.setSelection(Le.near(a.doc.resolve(t+1))),e.dispatch(a.scrollIntoView()),!0}const Jg=/^\[![\w-]+\]/;function qi(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 l=e.state.doc.resolve(t).blockRange(e.state.doc.resolve(n)),m=l&&Bf(l,r);if(!l||!m)return!1;e.dispatch(e.state.tr.wrap(l,m)),s=t}else{if(e.dispatch(e.state.tr.setSelection(Le.near(e.state.doc.resolve(t+1)))),!ca(e,{kind:"quote"},null))return!1;const l=e.state.selection.$from;let m=l.depth;for(;m>0&&l.node(m).type!==r;)m--;if(m<1)return!1;s=l.before(m)}const i=e.state.doc.nodeAt(s),a=i?.firstChild;return!i||i.type!==r||!a?.isTextblock||Jg.test(a.textContent)?!!i:(e.dispatch(e.state.tr.insertText(a.content.size?"[!note] ":"[!note]",s+2)),!0)}const vu=/^\[![\w-]+\]([+-])?[ \u00a0]?/;function wu(e,t){const n=e.doc.nodeAt(t),o=n?.firstChild,r=n?.type.name==="blockquote"&&o?.isTextblock?vu.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 Wi(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?vu.exec(s.textContent):null;if(!r||!s||!c)return null;const i=e.state.tr;if(o!=="code"&&o.kind==="fold"){if(/^\[!fold\]/i.test(s.textContent))return!0;const C=c[0].length-(/[ \u00a0]$/.test(c[0])?1:0);return i.replaceWith(t+2,t+2+C,e.state.schema.text(qd)),e.dispatch(i.scrollIntoView()),!0}if(wu(i,t),o!=="code"&&o.kind==="quote")return i.setSelection(Le.near(i.doc.resolve(t+1))),e.dispatch(i.scrollIntoView()),!0;const a=i.doc.nodeAt(t),l=a.content.size,m=i.doc.resolve(t+1).blockRange(i.doc.resolve(t+a.nodeSize-1)),g=m?_f(m):null;return!m||g==null?!1:(i.lift(m,g),i.setSelection(Le.near(i.doc.resolve(t+1))),e.dispatch(i.scrollIntoView()),o==="code"?ac(e,t,t+l):o.kind==="text"?!0:o.kind==="heading"?ca(e,o,null):bu(e,t,t+l,o))}function Zg(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 yo(e){const t=Zg(e);return{text:t===`\r
22
+ `?e.replace(/\r\n/g,`
23
+ `):e,eol:t}}function oo(e,t){return t===`\r
24
+ `?e.replace(/\r?\n/g,`\r
25
+ `):e}function ms(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 i=r.index();i<s.childCount&&c<o;i++){const a=s.child(i);if(a.type.name==="heading"){const l=Jr(e,c);l!=null&&l>o&&(o=l)}c+=a.nodeSize}return o}function Vr(e,t,n){for(const o of[Gr,Mm]){const r=o.getState(e)?.folded;if(!r?.length)continue;const s=[];for(const c of r){const i=c>=n.from&&c<n.to;(!i||n.copy)&&s.push(t.mapping.map(c)),i&&!n.drop&&n.newStart!=null&&s.push(n.newStart+(c-n.from))}t.setMeta(o,{set:s})}}function ns(e,t,n){const o=t.getMeta(Gr)?.set;if(!o?.length)return;const r=ji(e.doc,Gr.getState(e)?.folded??[]),s=l=>r.some(m=>l>=m.start&&l<m.after),c=n.to-n.from,i=t.mapping.invert(),a=o.filter(l=>ji(t.doc,[l]).every(m=>{const g=t.doc.resolve(m.start),C=g.parent;let M=m.start;for(let S=g.index();S<C.childCount&&M<m.after;S++){const z=M;M+=C.child(S).nodeSize;const L=z>=n.newStart&&z<n.newStart+c?n.from+(z-n.newStart):i.map(z);if(!s(L))return!1}return!0}));a.length!==o.length&&t.setMeta(Gr,{set:a})}Cn({"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 Vo=e=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:e}}))},Ec=e=>(e.split("/").pop()??e).replace(/\.md$/i,""),os=e=>e.split("/").slice(0,-1).join("/");function Qg(e,t,n){if(t===n)return e;const o=[!1,!0].map(r=>[Ui(t,r),Ui(n,r)]);return Cd(e,r=>r.replace(/(^|[^!])\[([^\]\n]*)\]\(([^)\s]+)((?:\s+"[^"]*")?)\)/g,(s,c,i,a,l)=>{if(/^[/<]/.test(a)||!Yi(a))return s;const m=a.indexOf("#"),g=m<0?a:a.slice(0,m);let C=!1;try{decodeURIComponent(g)}catch{C=!0}const[M,S]=o[+C],z=Ed(S,Vl(xc(M,g)));if(C&&z.includes(" "))return s;const L=z.replace(/ /g,"");return`${c}[${i}](${!L.includes("/")||!Yi(L)?"./":""}${L}${m<0?"":a.slice(m)}${l})`}))}const Yi=e=>/^(?:note|file)$/.test(Wl(e)),Ui=(e,t)=>e.split("/").map(n=>{const o=t?n.replace(/%/g,""):n;return Xi(o)===o?n:` ${Xi(n)}`}).join("/"),Xi=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 ex(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 tx(e,t){const{text:n,eol:o}=yo(e),r=n?n.endsWith(`
27
+
28
+ `)?"":n.endsWith(`
29
+ `)?`
30
+ `:`
31
+
32
+ `:"";return oo(`${n}${r}${t}
33
+ `,o)}function nx(e,t){const n=Ec(e);return ys(n,t)===e?n:e.replace(/\.md$/i,"")}function ox(e,t,n){const o=nx(t,n);if(e.type.name==="heading"){const s=Wd(e.textContent);return s?{kind:"heading",link:`[[${o}#${s}]]`}:null}const r=Kl(e.textContent);return r?{kind:"block",link:`[[${o}#^${r}]]`}:null}function rx(e){const t=navigator.clipboard?.writeText(e);if(!t){Vo(je("blocklinks.copyFailed"));return}t.then(()=>Vo(je("blocklinks.copied",{link:e})),()=>Vo(je("blocklinks.copyFailed")))}function sx(e){let t=!0;return e.descendants(n=>(/^amadeus(CanvasCard|ColumnRow|ColumnCell)$/.test(n.type.name)&&(t=!1),t)),t}async function ax(e){const{view:t,from:n,to:o,source:r,target:s}=e,c=Ec(s);if(s===r)return!1;const i=t.state.doc.slice(n,o).content,a=e.serialize(i);if(!a?.trim())return Vo(je("blocklinks.moveFailed",{name:c})),!1;let l=Qg(Hr(a,os(s)).trim(),os(r),os(s));e.pages&&os(r)!==os(s)&&(l=bd(l,r,s,{pairs:new Map,pagesBefore:e.pages,pagesAfter:e.pages}));try{if(vd(s)){if(!wd(s,l,"end"))throw new Error("insert refused");try{await kd(s,!0)}catch{return Vo(je("blocklinks.targetUnsaved",{name:c})),!1}}else{const g=await on.readTextFile(s);if(g==null)throw new Error("missing");if(ex(yo(g).text))throw new Error("unsafe tail");const C=await on.writeTextFile(s,tx(g,l),{base:Kr(g)});if(C&&!C.ok)return Vo(je("blocklinks.moveConflict",{name:c})),!1}}catch{return Vo(je("blocklinks.moveFailed",{name:c})),!1}if(t.isDestroyed||o>t.state.doc.content.size||!t.state.doc.slice(n,o).content.eq(i))return Vo(je("blocklinks.keptSource",{name:c})),!0;const m=t.state.tr.delete(n,o);return Vr(t.state,m,{from:n,to:o,drop:!0}),t.dispatch(m.scrollIntoView()),Vo(je("blocklinks.moved",{name:c})),!0}function ku({pages:e,exclude:t,onPick:n,onClose:o}){const{t:r}=Bt(),[s,c]=x.useState(""),[i,a]=x.useState(0),l=Gh(s,e.filter(m=>m!==t&&/\.md$/i.test(m)),Sd).slice(0,30);return x.useEffect(()=>{a(0)},[s]),bc.createPortal(u.jsx("div",{className:"cmd-overlay",onMouseDown:o,children:u.jsxs("div",{className:"cmd-panel",role:"dialog","aria-label":r("blocklinks.pickTitle"),"data-testid":"note-picker",onMouseDown:m=>m.stopPropagation(),children:[u.jsx("input",{className:"cmd-input",autoFocus:!0,placeholder:r("blocklinks.pickPlaceholder"),"aria-label":r("blocklinks.pickTitle"),value:s,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="ArrowDown"?(m.preventDefault(),a(g=>Math.min(g+1,l.length-1))):m.key==="ArrowUp"?(m.preventDefault(),a(g=>Math.max(g-1,0))):m.key==="Enter"?(m.preventDefault(),l[i]&&n(l[i])):m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),o())}}),u.jsxs("div",{className:"cmd-list",role:"listbox",children:[l.map((m,g)=>u.jsx("button",{className:"cmd-item",role:"option","aria-selected":g===i,"data-active":g===i||void 0,onMouseEnter:()=>a(g),onClick:()=>n(m),children:u.jsxs("span",{className:"cmd-row",children:[u.jsx("span",{className:"cmd-title",children:Ec(m)}),u.jsx("span",{className:"cmd-path",children:m})]})},m)),!l.length&&u.jsx("div",{className:"cmd-empty",children:r("blocklinks.noMatch")})]})]})}),document.body)}function cx(e){return e.nodeType===1}function ix(e){return cx(e)&&e.namespaceURI==="http://www.w3.org/1999/xhtml"}function lx(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&&ix(s)){const{top:c,bottom:i,left:a,right:l}=s.getBoundingClientRect();n.push([o,[a,c,l,c]],[o+r.nodeSize,[a,i,l,i]])}}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 ux(e,t){let n=[],o,r;const s=()=>{const m=e.dom.getBoundingClientRect(),g=e.state.doc;return n&&o&&r&&m.width===r.width&&m.height===r.height&&m.x===r.x&&m.y===r.y&&o.eq(g)||(r=m,o=g,n=lx(e)),n},c=(m,g)=>{if(!e.editable||e.isDestroyed)return;const C=(z,L)=>{const[E,F]=z,[U,q]=L;return Ji(m,F)-Ji(m,q)||E-U};let M=s();M.sort(C),M=M.slice(0,8);const S=M.find(z=>t?.({view:e,pos:z[0],event:g})!==!1);if(!(S&&fx(e,S[0])))return S};let i,a;return(m,g)=>(i&&dx(i,m)||(i=m,a=c(m,g)),a)}function dx(e,t){return e[0]===t[0]&&e[1]===t[1]}function Gi(e,t){return Math.abs(e[0]-t[0])+Math.abs(e[1]-t[1])}function Ji(e,t){return Math.min(Gi(e,[t[0],t[1]]),Gi(e,[t[2],t[3]]))}function fx(e,t){const n=e.dragging;if(!n)return;const{move:o}=n;if(!o)return;const r=e.state.selection;if(!(r instanceof Se))return;const{from:s,to:c}=r;return s<=t&&t<=c}function px(e){let t;return new Yt({key:new $n("prosemirror-drop-indicator"),view:n=>(t=ux(n,e.onDrag),hx(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 i=c[0],a=n.state.tr;if(s){const{node:M}=n.dragging||{};M?M.replace(a):a.deleteSelection()}const l=a.mapping.map(i),m=r.openStart==0&&r.openEnd==0&&r.content.childCount==1,g=a.doc;if(m?a.replaceRangeWith(l,l,r.content.firstChild):a.replaceRange(l,l,r),a.doc.eq(g))return!0;const C=a.doc.resolve(l);if(m&&Se.isSelectable(r.content.firstChild)&&C.nodeAfter&&C.nodeAfter.sameMarkup(r.content.firstChild))a.setSelection(new Se(C));else{let M=a.mapping.map(i);a.mapping.maps[a.mapping.maps.length-1].forEach((S,z,L,E)=>M=E),a.setSelection(mx(n,C,a.doc.resolve(M)))}return n.focus(),n.dispatch(a.setMeta("uiEvent","drop")),!0}}})}function mx(e,t,n,o){return e.someProp("createSelectionBetween",r=>r(e,t,n))||Le.between(t,n,o)}function hx(e,t,n){const o=e.dom;let r,s,c,i=!1;const a=()=>{r&&clearTimeout(r),i=!1,r=setTimeout(()=>{i||n.onHide?.()},30)},l=g=>{i=!0;const{clientX:C,clientY:M}=g;if(s===C&&c===M)return;s=C,c=M;const S=t([C,M],g);if(S){const[z,[L,E,F,U]]=S,q={p1:{x:L,y:E},p2:{x:F,y:U}};n.onShow?.({view:e,pos:z,line:q})}else{a();return}};return o.addEventListener("dragover",l),o.addEventListener("dragend",a),o.addEventListener("drop",a),o.addEventListener("dragleave",a),{destroy:()=>{o.removeEventListener("dragover",l),o.removeEventListener("dragend",a),o.removeEventListener("drop",a),o.removeEventListener("dragleave",a)}}}Cn({"canvasedit.textDefault":{zh:"文本",en:"Text"}});function Yo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.id;return typeof t=="string"&&t?t:null}function Zi(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t?t:null}function Ho(e){return Array.isArray(e)?[...e]:[]}function Su(e,t,n){return e.map(o=>Yo(o)===t?{...o,...n}:o)}function gx(e,t){const n=new Set,o=e.filter(r=>{const s=Yo(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=Zi(s.from),i=Zi(s.to);return!(c&&n.has(c)||i&&n.has(i))}):o}function Qi(e,t,n,o){return e.map(r=>{const s=Yo(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 hs(e,t){const n=new Set;for(const o of e){const r=Yo(o);r&&n.add(r)}for(let o=1;;o++){const r=`${t}${o}`;if(!n.has(r))return r}}const we="m:",xx={rect:{w:200,h:120},ellipse:{w:180,h:120},text:{w:180,h:40}},el={w:480,h:320};function Cu(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:je("canvasedit.textDefault")}:{}}}function yx(e,t,n,o){const r=xx[t];return Cu(e,t,{x:n-r.w/2,y:o-r.h/2,w:r.w,h:r.h})}function cc(e){return e==="m:"?{main:!0}:e.startsWith("c:")?{ref:e.slice(2)}:e.startsWith("e:")?{id:e.slice(2)}:null}function bx(e,t,n){if(t===n)return e;const o=cc(t),r=cc(n);if(!o||!r)return e;const s=(i,a)=>{const l=a;return!!l&&l.ref===i.ref&&l.id===i.id};return e.some(i=>{if(!i||typeof i!="object"||i.type!=="connector")return!1;const a=i;return s(o,a.from)&&s(r,a.to)||s(o,a.to)&&s(r,a.from)})?e:[...e,{id:hs(e,"e"),type:"connector",from:o,to:r}]}const gs={fromEnd:"none",toEnd:"arrow"};function vx(e,t,n){let o=!1;const r=e.map(s=>{const c=Yo(s);if(!c||!t.has(c)||s.type!=="connector")return s;const i=s;let a=null;for(const l of["fromEnd","toEnd"]){const m=n[l];if(m==null)continue;const g=m===gs[l];(g?!(l in i):i[l]===m)||(a??={...i},g?delete a[l]:a[l]=m)}return a?(o=!0,a):s});return o?r:e}const Or=(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 wx(e,t,n,o){const r=cc(o);if(!r)return e;const s=e.find(a=>Yo(a)===t);if(!s||s.type!=="connector")return e;const c=n==="from"?s.to:s.from;return Or(r,s[n])||Or(r,c)||e.some(a=>{if(Yo(a)===t||!a||typeof a!="object"||a.type!=="connector")return!1;const l=a;return Or(r,l.from)&&Or(c,l.to)||Or(r,l.to)&&Or(c,l.from)})?e:Su(e,t,{[n]:r})}function kx(e,t,n,o){return e.map(r=>{if(Yo(r)!==t)return r;const s={...r};return o?s[n]=o:delete s[n],s})}function qt(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 qr(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=qt(e);return s[t]=n,s}function Sx(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 Mr=(e,t)=>Object.keys(e).filter(n=>e[n]===t).sort();function Eu(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 Cx(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 oa(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&&Eu(n,e[r].anchor,e[t].anchor,o);)r++;return r}function Ex(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 Mx=/^(?:[1-6]|#[0-9a-fA-F]{6})$/;function la(e){return typeof e!="string"||!Mx.test(e)?null:e.length===1?`var(--amx-cv-${e})`:e}function zx(e,t,n){let o=!1;const r=e.map(s=>{const c=Yo(s);if(!c||!t.has(c))return s;const i=s;if(n?i.color===n:!("color"in i))return s;o=!0;const a={...i};return n?a.color=n:delete a.color,a});return o?r:e}const Mc=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/;function ja(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 $o(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=Mc.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 rs(e,t){const n=[],o=[];return t.forEach(r=>{if(r.type.name==="amadeusCanvasCard"){let s=$o(e);for(;n.includes(s);)s=$o(e);n.push(s),o.push(r.type.create({...r.attrs,anchor:s},r.content,r.marks))}else o.push(r)}),n.length?{content:To.fromArray(o),minted:n}:{content:t,minted:n}}const Ax=vc("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} -->`)}}})),Nx=vc("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 Tx(e,t,n){if(!t?.rows?.length)return;const o=Array.isArray(e?.children)?e.children:[];if(o.length&&!o.some(l=>l?.position))return;const r=l=>{let m=null;if(l?.type==="html"&&typeof l.value=="string")m=l.value;else if(l?.type==="paragraph"&&Array.isArray(l.children)&&l.children.length===1){const C=l.children[0];C?.type==="html"&&typeof C.value=="string"&&(m=C.value)}if(m==null)return null;const g=Mc.exec(m.trim());return g?g[1]:null},s=[];if(o.forEach((l,m)=>{const g=r(l);g&&s.push({id:g,idx:m})}),!s.length)return;const c=new Map;s.forEach((l,m)=>{c.has(l.id)?c.set(l.id,-1):c.set(l.id,m)});const i=new Set,a=[];for(const l of t.rows){if(l.columns.length<2)continue;const m=l.columns.flatMap(E=>E.refs);if(!m.length)continue;const g=m.map(E=>c.get(E)??-1);if(g.some(E=>E<0||i.has(E))||new Set(g).size!==g.length||!g.every((E,F)=>F===0||E===g[F-1]+1))continue;const C=g[g.length-1],M=l.tail!=null&&C+1<s.length&&s[C+1].id===l.tail&&!i.has(C+1)?C+1:null,S=M!=null?s[M].idx:C+1<s.length?s[C+1].idx:o.length,z=[];let L=!0;l.columns.forEach((E,F)=>{const U=c.get(E.refs[0]),q=s[U].idx+1,de=F+1<l.columns.length?c.get(l.columns[F+1].refs[0]):null,me=de!=null?s[de].idx:S;if(me<q){L=!1;return}const Ne=o.slice(q,me);z.push({type:"amadeusColumnCell",anchor:E.refs[0],width:E.width||1,children:Ne.length?Ne:[{type:"paragraph",children:[]}]})}),!(!L||z.length<2)&&(g.forEach(E=>i.add(E)),M!=null&&i.add(M),a.push({from:s[g[0]].idx,to:M!=null?s[M].idx+1:S,node:{type:"amadeusColumnRow",tail:M!=null?l.tail:"",children:z}}))}a.sort((l,m)=>m.from-l.from);for(const l of a)o.splice(l.from,l.to-l.from,l.node);a.length&&n?.()}function $x(e,t){return[su("amadeusColumnsFold",()=>()=>n=>{Tx(n,e(),t)})].flat()}function jx(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=Mc.exec(String(o.attrs.value??"").trim());r&&t.push(r[1])}),t}function Rx(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusColumnRow")return;const o=[];n.forEach(r=>{o.push({refs:jx(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 zc=e=>e.childCount===1&&e.firstChild.type.name==="paragraph"&&e.firstChild.content.size===0;function ra(e,t){const{paragraph:n,html:o}=e.nodes;return t&&n&&o?[n.create(null,o.create({value:`<!-- a ${t} -->`}))]:[]}function Ac(e,t,n,o=!1){const r=[];for(const s of t)r.push(...ra(e,String(s.attrs.anchor))),o&&zc(s)||s.forEach(c=>r.push(c));return r.push(...ra(e,n)),r}const Lx=Et(()=>new Yt({key:new $n("AMX_COLUMNS_NORMALIZE"),appendTransaction:(e,t,n)=>{if(!e.some(a=>a.docChanged))return null;const o=e.some(a=>(a.getMeta("uiEvent")==="drop"||a.getMeta("amxColumns"))&&!a.getMeta("amxColumnsKeepEmpty")),{paragraph:r}=n.schema.nodes,s=a=>ra(n.schema,a),c=[];if(n.doc.descendants((a,l,m)=>{if(a.type.name==="amadeusColumnRow"&&m?.type.name==="amadeusColumnCell"){const g=[];return a.forEach(C=>C.forEach(M=>g.push(M))),c.push({from:l,to:l+a.nodeSize,content:g.length?g:[r.create()]}),!1}return!0}),n.doc.forEach((a,l)=>{if(a.type.name!=="amadeusColumnRow")return;const m=[];a.forEach(L=>m.push(L));const g=o?m.filter(L=>!zc(L)):m,C=g.some(L=>!L.attrs.anchor);if(g.length===m.length&&g.length>=2&&!C)return;const M=new Set;n.doc.descendants(L=>{L.type.name==="amadeusColumnCell"&&L.attrs.anchor&&M.add(String(L.attrs.anchor)),L.type.name==="amadeusColumnRow"&&L.attrs.tail&&M.add(String(L.attrs.tail))});const S=L=>{if(L.attrs.anchor)return L;let E="c"+Math.random().toString(36).slice(2,6);for(;M.has(E);)E="c"+Math.random().toString(36).slice(2,6);return M.add(E),L.type.create({...L.attrs,anchor:E},L.content)},z=m.filter(L=>!g.includes(L)).flatMap(L=>s(String(L.attrs.anchor)));if(g.length>=2)c.push({from:l,to:l+a.nodeSize,content:[a.type.create(a.attrs,g.map(S)),...z]});else{const L=[...z,...Ac(n.schema,g,String(a.attrs.tail??""))];c.push({from:l,to:l+a.nodeSize,content:L.length?L:[r.create()]})}}),!c.length)return null;let i=n.tr;for(const a of c.sort((l,m)=>m.from-l.from))i=i.replaceWith(a.from,a.to,a.content);return i}}));function Dx(e,t,n,o=!1){const{state:r}=e,s=r.selection;if(!(s instanceof Se))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 i=r.schema.nodes.amadeusColumnRow,a=r.schema.nodes.amadeusColumnCell;if(!i||!a)return!1;const l=c.type.name==="list_item"?s.$from.parent.type.create(s.$from.parent.attrs,c):c,m=r.doc.resolve(t);let g=null;if(m.depth>0){let E=-1;for(let F=m.depth;F>=1;F--)if(m.node(F).type===i){E=F;break}if(E<0||E!==1)return!1;g={rowPos:m.before(E),cellIndex:m.index(E)}}const C=new Set,M=()=>{let E=$o(r.doc);for(;C.has(E);)E=$o(r.doc);return C.add(E),E},S=M(),z=M();let L=r.tr;if(o||(L=L.delete(s.from,s.to)),g){const E=L.mapping.map(g.rowPos),F=L.doc.nodeAt(E);if(!F||F.type!==i)return!1;const U=n==="left"?g.cellIndex:g.cellIndex+1;let q=E+1;for(let de=0;de<Math.min(U,F.childCount);de++)q+=F.child(de).nodeSize;L=L.insert(q,a.create({anchor:z,width:1},l))}else{const E=L.mapping.map(t),F=L.doc.nodeAt(E);if(!F)return!1;const U=n==="left"?[a.create({anchor:z,width:1},l),a.create({anchor:S,width:1},F)]:[a.create({anchor:S,width:1},F),a.create({anchor:z,width:1},l)];L=L.replaceWith(E,E+F.nodeSize,i.create({tail:M()},U))}return L.setMeta("amxColumns",!0),e.dispatch(L.scrollIntoView()),!0}function Ix(e,t,n=!1){const{state:o}=e,r=o.selection;if(!(r instanceof Se))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 i=s.type.name==="list_item"?r.$from.parent.type.create(r.$from.parent.attrs,s):s;let a=o.tr;return n||(a=a.delete(r.from,r.to)),a=a.insert(a.mapping.map(t+c.nodeSize),i),a.setMeta("amxColumns",!0),e.dispatch(a.scrollIntoView()),!0}function Px(e,t,n=!1){const{state:o}=e,r=o.selection;if(!(r instanceof Se))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),i=c.parent;if(i.type.name!=="amadeusColumnCell")return!1;if(!n&&t>=r.from&&t<=r.to)return!0;const a=s.type.name==="list_item"?r.$from.parent.type.create(r.$from.parent.attrs,s):s,l=i.childCount===1&&i.firstChild.type.name==="paragraph"&&i.firstChild.content.size===0;let m=o.tr;return n||(m=m.delete(r.from,r.to)),l?m=m.replaceWith(m.mapping.map(c.start()),m.mapping.map(c.end()),a):m=m.insert(m.mapping.map(t),a),m.setMeta("amxColumns",!0),e.dispatch(m.scrollIntoView()),!0}function Mu(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,i=r.schema.nodes.paragraph;if(!s||!c||!i)return!1;const a=new Set,l=()=>{let C=$o(r.doc);for(;a.has(C);)C=$o(r.doc);return a.add(C),C},m=s.create({tail:l()},[c.create({anchor:l(),width:1},o),c.create({anchor:l(),width:1},i.create())]);let g=r.tr.replaceWith(t,n,m);return g=g.setSelection(Le.near(g.doc.resolve(t+m.nodeSize-3))),g.setMeta("amxColumns",!0),g.setMeta("amxColumnsKeepEmpty",!0),e.dispatch(g.scrollIntoView()),!0}function zu(e,t,n,o=!1){const r=e.doc.nodeAt(t);if(!r||r.type.name!=="amadeusColumnCell"||!(o||zc(r)))return null;const s=e.doc.resolve(t),c=s.parent;if(c.type.name!=="amadeusColumnRow")return null;const i=s.before(),a=s.after(),l=s.index(),m=[];c.forEach((F,U,q)=>{q!==l&&m.push(F)});const g=ra(e.schema,String(r.attrs.anchor));if(m.length>=2){const F=e.tr.delete(t,t+r.nodeSize);return g.length&&F.insert(F.mapping.map(a),g),F.setSelection(Wo.near(F.doc.resolve(Math.min(t,F.doc.content.size)),n)),F.scrollIntoView()}const C=[...Ac(e.schema,m,String(c.attrs.tail??"")),...g],M=e.tr.replaceWith(i,a,C),S=m[0],z=n<0?l>0:l>=m.length,L=z?S?.lastChild:S?.firstChild;let E=i;for(const F of C){if(F===L){M.setSelection(Wo.near(M.doc.resolve(z?E+F.nodeSize-1:E+1),z?-1:1));break}E+=F.nodeSize}return M.scrollIntoView()}function Ox(e,t){const{state:n}=e,o=n.doc.nodeAt(t);if(!o||o.type.name!=="amadeusColumnRow")return!1;const r=[];o.forEach(g=>r.push(g));const s=Ac(n.schema,r,String(o.attrs.tail??""),!0),c=s.length?s:[n.schema.nodes.paragraph.create()],i=n.selection;let a=null;n.doc.nodesBetween(t,t+o.nodeSize,(g,C,M)=>a||M?.type.name!=="amadeusColumnCell"?!a:(i.from>=C&&i.from<C+g.nodeSize&&(a={node:g,off:i.from-C,nodeSel:i instanceof Se&&i.from===C}),!1));const l=n.tr.replaceWith(t,t+o.nodeSize,c);let m=t;for(const g of c){const C=a;if(C&&g===C.node){l.setSelection(C.nodeSel?Se.create(l.doc,m):Wo.near(l.doc.resolve(m+C.off)));break}m+=g.nodeSize}return e.dispatch(l.scrollIntoView()),!0}const Fx=[Ax,Nx,Lx].flat();Cn({"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 _x(e){return e.kind==="instructions"?u.jsx(Bx,{...e},e.pagePath):u.jsx(Hx,{...e},`${e.kind}:${e.pagePath}:${Ms(e.src)?.id??"source"}`)}function Bx({src:e,readOnly:t=!1,activeInstructions:n=!0,onChange:o}){const{t:r}=Bt(),[s,c]=x.useState(e);return x.useEffect(()=>{c(e)},[e]),u.jsxs("section",{className:"am-doc-agent am-doc-agent-instructions","data-document-agent":"instructions","data-active":n,children:[u.jsxs("div",{className:"am-doc-agent-header",children:[u.jsx(Vh,{size:16,"aria-hidden":"true"}),u.jsx("span",{className:"am-doc-agent-title",children:r("docagent.instructions")}),u.jsx("span",{className:"am-doc-agent-hint",children:r(n?"docagent.instructionsScope":"docagent.instructionsNested")})]}),t?u.jsx("div",{className:"am-doc-agent-content",children:e||r("docagent.empty")}):u.jsx("textarea",{className:"am-doc-agent-input","aria-label":r("docagent.instructions"),rows:3,placeholder:r("docagent.instructionsPlaceholder"),value:s,onKeyDown:i=>i.stopPropagation(),onChange:i=>{c(i.target.value),o(i.target.value)}})]})}function Hx({kind:e,src:t,pagePath:n,readOnly:o=!1,onChange:r,onStart:s,onOpen:c}){const{t:i}=Bt(),a=x.useMemo(()=>Ms(t),[t]),[l,m]=x.useState(a),[g,C]=x.useState(!1),[M,S]=x.useState(null),[z,L]=x.useState(null),[E,F]=x.useState("idle"),U=x.useRef(!1),q=x.useRef(!1),de=Nr(),me=e==="task"?typeof de?.submitDocumentTask=="function"&&de.hostExecution?.()!==!1:typeof de?.startChat=="function",[Ne,be]=x.useState(()=>de?.agents?.()??[]),ge=e==="task"?a?.sessionId||(z?.id===a?.id?z?.sessionId:void 0):void 0,p=o||g||!!ge;x.useEffect(()=>(U.current=!0,()=>{U.current=!1}),[]),x.useEffect(()=>{m(a),S(null)},[a]),x.useEffect(()=>{const Me=()=>{be(de?.agents?.()??[])};return Me(),de?.subscribeAgents?de.subscribeAgents(Me):de?.subscribe(Me)},[de]),x.useEffect(()=>{if(F(ge?de?.agentStatus?.(ge).phase??"idle":"idle"),!!ge)return de?.subscribeAgentStatus?.(Me=>{Me.sessionId===ge&&F(Me.phase)},ge)},[de,ge]);const fe=async()=>{if(!(o||!me||q.current||!l||!l.prompt.trim()||ge)){q.current=!0,C(!0),S(null);try{r(xs(l));const Me=await s(l,e==="prompt"?"prompt":"task");if(e==="task"&&!Me.sessionId)throw new Error(i("docagent.noSession"));U.current&&e==="task"&&Me.sessionId&&L({id:l.id,sessionId:Me.sessionId})}catch(Me){U.current&&S(Me instanceof Error?Me.message:i("docagent.startFailed"))}finally{q.current=!1,U.current&&C(!1)}}};if(!a||!l)return u.jsx("pre",{className:"am-doc-agent-source",children:u.jsx("code",{children:t})});const ce=ge?E==="waiting"?"docagent.waiting":E==="done"?"docagent.done":E==="error"?"docagent.failed":E==="idle"?"docagent.linked":"docagent.running":"docagent.ready",te=g||!!ge&&["thinking","speaking","tool"].includes(E),ee=e==="prompt"?nu:Hp,Ie=l.agent&&!Ne.some(Me=>Me.slug===l.agent);return u.jsxs("section",{className:"am-doc-agent","data-document-agent":e,"data-document-agent-id":l.id,"data-page-path":n,"aria-busy":g,children:[u.jsxs("div",{className:"am-doc-agent-header",children:[u.jsx(ee,{size:16,"aria-hidden":"true"}),u.jsx("span",{className:"am-doc-agent-title",children:i(e==="prompt"?"docagent.prompt":"docagent.task")}),e==="task"&&u.jsxs("span",{className:"am-doc-agent-status",role:"status","aria-live":"polite","data-phase":E,children:[te?u.jsx(ci,{size:12,className:"am-doc-agent-spin","aria-hidden":"true"}):E==="done"?u.jsx(zs,{size:12,"aria-hidden":"true"}):null,i(g?"docagent.starting":ce)]})]}),o||ge?u.jsx("div",{className:"am-doc-agent-content",children:l.prompt||i("docagent.empty")}):u.jsx("textarea",{className:"am-doc-agent-input","aria-label":i("docagent.promptLabel"),rows:3,placeholder:i("docagent.promptPlaceholder"),value:l.prompt,disabled:g,onKeyDown:Me=>Me.stopPropagation(),onChange:Me=>{const dt={...l,prompt:Me.target.value};m(dt),r(xs(dt))}}),u.jsxs("div",{className:"am-doc-agent-footer",children:[p?u.jsx("span",{className:"am-doc-agent-assignee",children:Ne.find(Me=>Me.slug===l.agent)?.name||l.agent||i("docagent.defaultAgent")}):u.jsxs("select",{className:"am-doc-agent-select","aria-label":i("docagent.agent"),value:l.agent??"",onKeyDown:Me=>Me.stopPropagation(),onChange:Me=>{const dt={...l,agent:Me.target.value||void 0};m(dt),r(xs(dt))},children:[u.jsx("option",{value:"",children:i("docagent.defaultAgent")}),Ie&&u.jsx("option",{value:l.agent,children:l.agent}),Ne.map(Me=>u.jsx("option",{value:Me.slug,children:Me.name},Me.slug))]}),ge?c&&u.jsxs("button",{type:"button",className:"am-doc-agent-action",onClick:()=>c(ge),children:[u.jsx(Di,{size:14,"aria-hidden":"true"}),i("docagent.open")]}):!o&&u.jsxs("button",{type:"button",className:"am-doc-agent-action",disabled:g||!me||!l.prompt.trim(),title:me?void 0:i("docagent.unavailable"),onMouseDown:Me=>Me.preventDefault(),onClick:()=>{fe()},children:[g?u.jsx(ci,{size:14,className:"am-doc-agent-spin","aria-hidden":"true"}):u.jsx(Di,{size:14,"aria-hidden":"true"}),i(g?"docagent.starting":e==="prompt"?"docagent.usePrompt":"docagent.assign")]})]}),!o&&!ge&&!me&&u.jsx("div",{className:"am-doc-agent-hint",children:i("docagent.unavailable")}),M&&u.jsx("div",{className:"am-doc-agent-error",role:"alert",children:M})]})}function ic(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 Au(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.`:""}const Nu="forsion-intelligent-ui-html",Kx="forsion-sketch",Vx=e=>e===Nu||e===Kx;function Aw(e){const t=Math.max(0,...(e.match(/`+/g)??[]).map(o=>o.length)),n="`".repeat(Math.max(3,t+1));return`${n}${Nu}
38
+ ${e.replace(/\s+$/,"")}
39
+ ${n}`}const qx=`/* The sketch document is isolated. All colors inherit Forsion's current theme. */
40
+ html, body { margin: 0; padding: 0; }
41
+ *, *::before, *::after { box-sizing: border-box; }
42
+ body {
43
+ font-family: var(--fs-font); background: var(--fs-bg); color: var(--fs-text);
44
+ font-size: 14px; line-height: 1.5; padding: 16px 20px;
45
+ overflow-wrap: anywhere; -webkit-font-smoothing: antialiased;
46
+ }
47
+ [hidden] { display: none !important; }
48
+ header, figure, figcaption, footer { margin: 0; }
49
+ h1, h2, h3, h4 { margin: 0 0 .5em; font-weight: 500; line-height: 1.3; text-wrap: balance; }
50
+ h1 { font-size: 20px; } h2 { font-size: 18px; } h3 { font-size: 15px; } h4 { font-size: 14px; }
51
+ p { margin: 0 0 .7em; } p:last-child { margin-bottom: 0; }
52
+ small { font-size: 12px; color: var(--fs-muted); }
53
+ a { color: var(--fs-accent); }
54
+ hr { border: 0; border-top: 1px solid var(--fs-rule); margin: 16px 0; }
55
+ code, pre, kbd { font-family: var(--fs-mono); font-size: 12px; }
56
+ pre { overflow-x: auto; background: var(--fs-surface); border-radius: var(--fs-radius); padding: 10px; }
57
+ table { border-collapse: collapse; width: 100%; font-size: 13px; font-variant-numeric: tabular-nums; }
58
+ th, td { text-align: left; padding: 8px 12px 8px 0; border-bottom: 1px solid var(--fs-rule); vertical-align: top; }
59
+ th { font-weight: 500; color: var(--fs-muted); }
60
+ th:last-child, td:last-child { padding-right: 0; }
61
+ tr:last-child td { border-bottom: 0; }
62
+ svg { display: block; width: 100%; max-width: 100%; height: auto; }
63
+ svg text { font-family: var(--fs-font); fill: var(--fs-text); }
64
+ img, canvas { display: block; max-width: 100%; }
65
+ img { height: auto; }
66
+ button, input, select, textarea { font: inherit; color: inherit; max-width: 100%; }
67
+ button {
68
+ border: 1px solid var(--fs-border); border-radius: var(--fs-radius);
69
+ background: transparent; padding: 6px 10px; cursor: pointer;
70
+ }
71
+ button:hover { background: var(--fs-surface); }
72
+ button:disabled { opacity: .5; cursor: default; }
73
+ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {
74
+ outline: 2px solid var(--fs-accent); outline-offset: 2px;
75
+ }
76
+ input, select, textarea { accent-color: var(--fs-accent); }
77
+ .fs-header { display: grid; gap: 4px; margin: 0 0 16px; }
78
+ .fs-title { margin: 0; font-size: 20px; font-weight: 500; line-height: 1.3; text-wrap: balance; }
79
+ .fs-eyebrow, .fs-subtitle, .fs-caption, .fs-source, .fs-label { font-size: 12px; color: var(--fs-muted); }
80
+ .fs-eyebrow { font-weight: 500; }
81
+ .fs-subtitle { max-width: 62ch; }
82
+ .fs-plot { position: relative; min-width: 0; margin: 0; }
83
+ .fs-caption, .fs-source { margin-top: 10px; }
84
+ .fs-stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(130px, 100%), 1fr)); gap: 12px; margin: 4px 0 16px; }
85
+ .fs-stat { display: grid; align-content: start; gap: 3px; min-width: 0; }
86
+ .fs-value { font-size: 26px; font-weight: 500; line-height: 1.2; font-variant-numeric: tabular-nums; }
87
+ .fs-panel { padding: 12px 14px; border-radius: var(--fs-radius); background: var(--fs-surface); }
88
+ .fs-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; min-width: 0; }
89
+ .fs-chip { display: inline-flex; align-items: center; padding: 3px 8px; border-radius: 999px; background: var(--fs-surface); font-size: 12px; color: var(--fs-muted); }
90
+ .fs-bar-track { height: 9px; overflow: hidden; border-radius: 999px; background: var(--fs-surface); }
91
+ .fs-bar-fill { height: 100%; border-radius: inherit; background: var(--fs-accent); transform-origin: left center; }
92
+ .fs-controls { display: flex; flex-wrap: wrap; align-items: end; gap: 12px 16px; margin-bottom: 16px; }
93
+ .fs-field { display: grid; gap: 6px; flex: 1 1 200px; min-width: 0; }
94
+ .fs-field > span { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 6px; }
95
+ .fs-field output { font-variant-numeric: tabular-nums; }
96
+ .fs-input, .fs-select { width: 100%; min-width: 0; border: 1px solid var(--fs-border); border-radius: var(--fs-radius); padding: 6px 9px; background: var(--fs-surface); }
97
+ .fs-range { width: 100%; min-width: 0; margin: 4px 0; }
98
+ .fs-check { display: inline-flex; align-items: center; gap: 8px; }
99
+ .fs-check input { margin: 0; }
100
+ .fs-button[aria-pressed="true"], .fs-tabs [aria-selected="true"] { background: var(--fs-accent-soft); color: var(--fs-accent); border-color: transparent; }
101
+ .fs-tabs { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 12px; }
102
+ .fs-tabs button { border-color: transparent; }
103
+ .fs-number { font-variant-numeric: tabular-nums; }
104
+ .fs-muted { color: var(--fs-muted); }
105
+ .fs-sr-only { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
106
+ /* Figure primitives: direct labels, quiet structure and one focus accent. */
107
+ fs-chart, fs-flow { display: block; min-width: 0; }
108
+ fs-chart + fs-flow, fs-flow + fs-chart, fs-chart + fs-chart { margin-top: 28px; }
109
+ .fs-figure-title { margin: 0 0 18px; font-size: 16px; font-weight: 500; }
110
+ .fs-chart-bars { display: grid; gap: 14px; }
111
+ .fs-chart-bar-row { display: grid; grid-template-columns: minmax(72px, 1fr) minmax(0, 3fr) minmax(56px, 1fr); gap: 16px; align-items: center; }
112
+ .fs-chart-bar-label { font-size: 13px; }
113
+ .fs-chart-bar-value { text-align: end; font-size: 13px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
114
+ .fs-chart-track { position: relative; height: 12px; background: var(--fs-surface); border-radius: 3px; }
115
+ .fs-chart-track::after { content: ''; position: absolute; left: var(--fs-zero); top: -4px; bottom: -4px; width: 1px; background: var(--fs-rule); }
116
+ .fs-chart-bar { position: absolute; top: 0; height: 100%; background: var(--fs-s1); border-radius: 3px; }
117
+ .fs-chart-bar--context { background: var(--fs-s2); }
118
+ .fs-chart-bars--narrow .fs-chart-bar-row { grid-template-columns: minmax(0, 1fr) fit-content(50%); gap: 7px 12px; }
119
+ .fs-chart-bars--narrow .fs-chart-track { grid-column: 1 / -1; grid-row: 2; }
120
+ .fs-chart-bars--narrow .fs-chart-bar-value { grid-column: 2; grid-row: 1; }
121
+ .fs-chart-field { position: relative; }
122
+ .fs-chart-grid { fill: none; stroke: var(--fs-rule); stroke-width: 1; }
123
+ .fs-chart-tick, .fs-chart-unit { font-size: 12px; fill: var(--fs-muted); }
124
+ .fs-chart-line { fill: none; stroke: var(--fs-s1); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
125
+ .fs-chart-point { fill: var(--fs-s1); }
126
+ .fs-chart-guide { fill: none; stroke: var(--fs-muted); stroke-width: 1; stroke-dasharray: 3 4; }
127
+ .fs-chart-hit { position: absolute; border: 0; border-radius: 0; padding: 0; background: transparent; cursor: crosshair; touch-action: pan-y; }
128
+ .fs-chart-hit:hover { background: transparent; }
129
+ .fs-chart-detail { display: block; min-height: 22px; font-size: 12px; color: var(--fs-muted); font-variant-numeric: tabular-nums; }
130
+ .fs-flow-steps { display: grid; grid-template-columns: repeat(var(--fs-step-count), minmax(0, 1fr)); gap: 20px; margin: 0; padding: 0; list-style: none; }
131
+ .fs-flow-step { position: relative; min-width: 0; }
132
+ .fs-flow-marker { display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; border-radius: 50%; background: var(--fs-surface); color: var(--fs-muted); font-size: 11px; font-variant-numeric: tabular-nums; }
133
+ .fs-flow-step[data-status="done"] .fs-flow-marker { color: var(--fs-accent); }
134
+ .fs-flow-step[data-status="active"] .fs-flow-marker { background: var(--fs-accent-soft); color: var(--fs-accent); outline: 1px solid var(--fs-accent); outline-offset: 2px; }
135
+ .fs-flow-step:not(:last-child)::after { content: ''; position: absolute; height: 1px; top: 15px; left: 40px; width: calc(100% - 28px); background: var(--fs-rule); }
136
+ .fs-flow-step:not(:last-child)::before { content: ''; position: absolute; top: 12px; left: calc(100% + 7px); width: 6px; height: 6px; border-top: 1px solid var(--fs-muted); border-right: 1px solid var(--fs-muted); transform: rotate(45deg); }
137
+ .fs-flow-content { display: grid; gap: 6px; margin-top: 12px; }
138
+ .fs-flow-label { display: block; font-size: 13px; font-weight: 500; }
139
+ .fs-flow-description { display: block; font-size: 12px; color: var(--fs-muted); }
140
+ .fs-flow-branches { display: grid; gap: 12px; list-style: none; padding: 0 0 0 12px; margin: 8px 0 0; border-left: 1px solid var(--fs-rule); }
141
+ .fs-flow-branch { position: relative; display: grid; gap: 3px; }
142
+ .fs-flow-branch::before { content: ''; position: absolute; left: -12px; top: 9px; width: 7px; height: 1px; background: var(--fs-rule); }
143
+ .fs-flow-steps--vertical { grid-template-columns: minmax(0, 1fr); gap: 22px; }
144
+ .fs-flow-steps--vertical .fs-flow-step { display: grid; grid-template-columns: 30px minmax(0, 1fr); gap: 14px; }
145
+ .fs-flow-steps--vertical .fs-flow-content { margin-top: 3px; }
146
+ .fs-flow-steps--vertical .fs-flow-step:not(:last-child)::after { left: 15px; top: 39px; width: 1px; height: calc(100% - 23px); }
147
+ .fs-flow-steps--vertical .fs-flow-step:not(:last-child)::before { top: calc(100% + 11px); left: 12px; transform: rotate(135deg); }
148
+ /* 直播补丁(10-09):新来的部件淡入;文字原地续写不动画。 */
149
+ [data-fs-new] { animation: fs-in .28s ease-out both; }
150
+ @keyframes fs-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
151
+ /* 统一拼装部件(10-09,对标 Intelligent UI 的固定组件库):网格 / 选项 / 按钮行 / 提示块 / 对比 / 追问选择 / 勾选清单。 */
152
+ .fs-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(128px, 100%), 1fr)); gap: 12px; margin: 4px 0 12px; } /* 128:1200 宽的窗口里聊天栏卡内只有 ≈430px,要并排得下三个选项 */
153
+ .fs-option { display: grid; align-content: start; gap: 6px; min-width: 0; padding: 12px 14px; border-radius: var(--fs-radius); background: var(--fs-surface); }
154
+ .fs-option > h4 { margin: 0; font-size: 14px; }
155
+ .fs-points { margin: 0; padding-left: 18px; font-size: 13px; display: grid; gap: 3px; }
156
+ .fs-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
157
+ .fs-callout { padding: 10px 14px; border-left: 2px solid var(--fs-accent); background: var(--fs-surface); border-radius: 0 var(--fs-radius) var(--fs-radius) 0; font-size: 13px; }
158
+ fs-compare, fs-choice, fs-checklist { display: block; min-width: 0; }
159
+ fs-compare + fs-choice, fs-choice + fs-compare, fs-checklist + fs-choice, fs-chart + fs-compare, fs-compare + fs-chart, fs-flow + fs-checklist, fs-checklist + fs-flow { margin-top: 24px; }
160
+ .fs-choice-question { margin: 0 0 10px; font-size: 14px; font-weight: 500; }
161
+ .fs-choice-options { display: flex; flex-wrap: wrap; gap: 8px; }
162
+ .fs-checklist-items { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
163
+ .fs-checklist-items .fs-check { align-items: start; }
164
+ .fs-checklist-items .fs-check input { margin-top: 4px; }
165
+ .fs-checklist-items .fs-check input:checked + span { color: var(--fs-muted); text-decoration: line-through; }
166
+ ::selection { background: var(--fs-accent-soft); }
167
+ @media(max-width:480px) {
168
+ body { padding: 14px 12px; }
169
+ .fs-controls { gap: 12px; }
170
+ }
171
+ @media(pointer:coarse) {
172
+ button, .fs-check { min-height: 44px; }
173
+ .fs-input, .fs-select { font-size: 16px; min-height: 44px; }
174
+ .fs-range { min-height: 36px; }
175
+ }
176
+ @media(prefers-reduced-motion:reduce) {
177
+ *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; scroll-behavior: auto !important; }
178
+ }
179
+ `,Wx=`/* Runs only inside the opaque-origin sandbox. No host capabilities or network. */
180
+ (() => {
181
+ let state = __SKETCH_INITIAL_STATE__
182
+ // 授权令牌(Codex 10-09 二轮 P1):宿主只认带这个 nonce 的 ask / copy。它只活在这个闭包里 —— 运行时跑完就把自己的 script 节点删掉
183
+ // (模型脚本读 outerHTML 也拿不到),模型 HTML 绕过运行时直接 postMessage 就没有它。真正的手势判定因此可以放在卡内:
184
+ // navigator.userActivation 是每个 window 各自的,父文档里敲键不会传进子帧,子帧里的真点击才会让它为真。getter 在模型脚本
185
+ // 跑之前就抓好,模型脚本改不了。
186
+ const NONCE = '__SKETCH_NONCE__'
187
+ const uaGet = typeof Navigator !== 'undefined' ? Object.getOwnPropertyDescriptor(Navigator.prototype, 'userActivation')?.get : undefined
188
+ const activeGet = typeof UserActivation !== 'undefined' ? Object.getOwnPropertyDescriptor(UserActivation.prototype, 'isActive')?.get : undefined
189
+ const gestureActive = () => { try { const ua = uaGet && uaGet.call(navigator); return !!(ua && activeGet && activeGet.call(ua)) } catch { return false } }
190
+ const send = (msg) => parent.postMessage({ ...msg, nonce: NONCE }, '*')
191
+ const api = Object.freeze({
192
+ get state() { return state },
193
+ setState(value) {
194
+ const json = JSON.stringify(value)
195
+ if (!json || new TextEncoder().encode(json).length > 16384) throw new Error('Sketch state exceeds 16 KiB')
196
+ state = JSON.parse(json)
197
+ parent.postMessage({ type: 'sketch-state', state }, '*')
198
+ },
199
+ // 卡内按钮回头改答案:把这句话当用户的下一条消息发出去(宿主侧再核 nonce + 焦点、限频、限长,只在对话里接)。
200
+ // 手势检查在这里是**真闸**(见上):模型写的卡不能一加载 / 定时就替用户发话。
201
+ ask(text) {
202
+ if (!gestureActive()) throw new Error('forsionIntelligentUi.ask() must be called from a user gesture')
203
+ const t = String(text ?? '').trim().slice(0, 400)
204
+ if (!t) throw new Error('forsionIntelligentUi.ask() needs a non-empty text')
205
+ send({ type: 'sketch-ask', text: t })
206
+ },
207
+ // 复制到剪贴板(沙箱帧自己没有剪贴板权限,由宿主代写;同样要用户手势)。
208
+ copy(text) {
209
+ if (!gestureActive()) throw new Error('forsionIntelligentUi.copy() must be called from a user gesture')
210
+ const t = String(text ?? '')
211
+ if (!t) return
212
+ send({ type: 'sketch-copy', text: t.slice(0, 20000) })
213
+ },
214
+ })
215
+ // 10-20 改名:新卡用 forsionIntelligentUi;forsionSketch 是同一个对象,给改名前的卡(历史、笔记里的块)。
216
+ window.forsionIntelligentUi = api
217
+ window.forsionSketch = api
218
+ document.currentScript?.remove()
219
+
220
+ // An href must never turn a sandbox frame into an external navigation surface.
221
+ document.addEventListener('click', (event) => {
222
+ if (event.target.closest?.('a[href]')) event.preventDefault()
223
+ }, true)
224
+ document.addEventListener('submit', (event) => event.preventDefault(), true)
225
+
226
+ // 直播补丁(10-09,对标 ChatGPT Intelligent UI 的流式组件):宿主把最新 html 发进来,这里**原地**打补丁 —— 不换 srcdoc、不重载。
227
+ // 同位置同标签的元素保留(只同步属性、递归子节点),文字节点原地续写,新节点标 data-fs-new 淡入;自定义元素(fs-*)内容一变整个换掉
228
+ // (它们从 JSON 子节点取数据,只在接入时解析)。终稿(sketch-final)再把惰性的 script 节点换成会执行的,并补发 DOMContentLoaded / load,
229
+ // 让「等 DOM 就绪再初始化」的两种写法都能跑。
230
+ function syncAttrs(live, next) {
231
+ for (const a of [...live.attributes]) if (a.name !== 'data-fs-new' && !next.hasAttribute(a.name)) live.removeAttribute(a.name)
232
+ for (const a of [...next.attributes]) if (live.getAttribute(a.name) !== a.value) live.setAttribute(a.name, a.value)
233
+ }
234
+ const markNew = (n) => {
235
+ if (n.nodeType !== 1) return
236
+ n.setAttribute('data-fs-new', '')
237
+ n.addEventListener('animationend', () => n.removeAttribute('data-fs-new'), { once: true })
238
+ }
239
+ function morph(live, next) {
240
+ if (live.nodeType === 1 && next.nodeType === 1) syncAttrs(live, next)
241
+ const a = [...live.childNodes], b = [...next.childNodes]
242
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
243
+ const x = a[i], y = b[i]
244
+ if (!y) { x.remove(); continue }
245
+ if (!x) { const n = document.importNode(y, true); markNew(n); live.appendChild(n); continue }
246
+ if (x.nodeType === 3 && y.nodeType === 3) { if (x.nodeValue !== y.nodeValue) x.nodeValue = y.nodeValue; continue }
247
+ const sameTag = x.nodeType === 1 && y.nodeType === 1 && x.tagName === y.tagName
248
+ // 自定义元素渲染后 innerHTML 已是画好的 DOM,比的是它接入时记下的原始源码(_fsSrc),不然每一拍都会被换掉重画。
249
+ if (sameTag && x.tagName.includes('-')) {
250
+ if ((x._fsSrc ?? x.innerHTML) !== y.innerHTML) { const n = document.importNode(y, true); markNew(n); x.replaceWith(n) }
251
+ else syncAttrs(x, y)
252
+ continue
253
+ }
254
+ if (sameTag) { morph(x, y); continue }
255
+ const n = document.importNode(y, true); markNew(n); x.replaceWith(n)
256
+ }
257
+ }
258
+ // 会执行的 script type(HTML 标准的 JavaScript MIME 类型表 + module);其余(application/json、importmap …)是数据,原样留着
259
+ const JS_TYPES = /^(?:module|(?:text|application)\\/(?:x-)?(?:ecma|java)script|text\\/(?:javascript1\\.[0-5]|jscript|livescript))$/
260
+ function applyHtml(html, final) {
261
+ const t = document.createElement('template')
262
+ t.innerHTML = html
263
+ morph(document.body, t.content)
264
+ if (final) {
265
+ const pending = [] // module 脚本是异步执行的,等它们跑完再发就绪事件(Codex 10-09 P2)
266
+ for (const s of [...document.body.querySelectorAll('script')]) {
267
+ const type = (s.getAttribute('type') || '').trim().toLowerCase()
268
+ if (type && !JS_TYPES.test(type)) continue
269
+ const n = document.createElement('script')
270
+ for (const attr of [...s.attributes]) n.setAttribute(attr.name, attr.value)
271
+ n.textContent = s.textContent
272
+ if (type === 'module') pending.push(new Promise((r) => { n.addEventListener('load', r, { once: true }); n.addEventListener('error', r, { once: true }) }))
273
+ s.replaceWith(n)
274
+ }
275
+ const ready = () => { document.dispatchEvent(new Event('DOMContentLoaded')); window.dispatchEvent(new Event('load')); measure() }
276
+ if (pending.length) Promise.all(pending).then(ready)
277
+ else ready()
278
+ }
279
+ measure()
280
+ }
281
+
282
+ window.addEventListener('message', (event) => {
283
+ if (event.source !== parent) return
284
+ const data = event.data
285
+ if (!data) return
286
+ if (data.type === 'sketch-draft' || data.type === 'sketch-final') { applyHtml(String(data.html ?? ''), data.type === 'sketch-final'); return }
287
+ if (data.type !== 'sketch-theme' || !data.vars) return
288
+ for (const [key, value] of Object.entries(data.vars)) {
289
+ if (key.startsWith('--fs-')) document.documentElement.style.setProperty(key, String(value))
290
+ else if (key === 'color-scheme') document.documentElement.style.colorScheme = String(value)
291
+ }
292
+ window.dispatchEvent(new Event('forsion:themechange'))
293
+ })
294
+
295
+ let lastHeight = 0
296
+ function measure() {
297
+ const height = Math.ceil(document.body?.getBoundingClientRect().height || 0)
298
+ if (height && height !== lastHeight) {
299
+ lastHeight = height
300
+ parent.postMessage({ type: 'sketch-height', height }, '*')
301
+ }
302
+ }
303
+
304
+ function selectTab(tab) {
305
+ const list = tab.closest('.fs-tabs[role="tablist"]')
306
+ if (!list || tab.disabled || tab.getAttribute('aria-disabled') === 'true') return
307
+ for (const peer of list.querySelectorAll('[role="tab"]')) {
308
+ const selected = peer === tab
309
+ peer.setAttribute('aria-selected', String(selected))
310
+ const panel = document.getElementById(peer.getAttribute('aria-controls'))
311
+ if (panel?.getAttribute('role') === 'tabpanel') panel.hidden = !selected
312
+ }
313
+ }
314
+ document.addEventListener('click', (event) => {
315
+ const tab = event.target.closest?.('.fs-tabs [role="tab"]')
316
+ if (tab) selectTab(tab)
317
+ })
318
+ document.addEventListener('keydown', (event) => {
319
+ const tab = event.target.closest?.('.fs-tabs [role="tab"]')
320
+ if (!tab || !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
321
+ const tabs = [...tab.closest('.fs-tabs').querySelectorAll('[role="tab"]')]
322
+ .filter((node) => !node.disabled && node.getAttribute('aria-disabled') !== 'true')
323
+ const index = tabs.indexOf(tab)
324
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1
325
+ : (index + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length
326
+ event.preventDefault()
327
+ tabs[next]?.focus()
328
+ if (tabs[next]) selectTab(tabs[next])
329
+ })
330
+
331
+ function ready() {
332
+ window.__fsLoadedAt = Date.now() // 台架用:整张卡只加载一次(草稿 → 终稿不重载)
333
+ if (window.ResizeObserver) new ResizeObserver(measure).observe(document.body)
334
+ measure()
335
+ }
336
+ // once:终稿(sketch-final)会补发一次合成的 DOMContentLoaded 给模型脚本,运行时自己的就绪只跑一次
337
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready, { once: true })
338
+ else ready()
339
+ window.addEventListener('load', measure)
340
+ })()
341
+ `,Yx=`/* Small, offline figure primitives. Text and data are never interpreted as HTML. */
342
+ (() => {
343
+ const svgNS = 'http://www.w3.org/2000/svg'
344
+ const number = (value) => new Intl.NumberFormat(undefined, {
345
+ maximumSignificantDigits: 6, notation: Math.abs(value) >= 1e15 || (value !== 0 && Math.abs(value) < 1e-4) ? 'scientific' : Math.abs(value) >= 1e6 ? 'compact' : 'standard',
346
+ }).format(value)
347
+ const node = (tag, cls, text) => {
348
+ const el = document.createElement(tag)
349
+ if (cls) el.className = cls
350
+ if (text !== undefined) el.textContent = String(text)
351
+ return el
352
+ }
353
+ const mark = (tag, attrs, text) => {
354
+ const el = document.createElementNS(svgNS, tag)
355
+ for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, String(value))
356
+ if (text !== undefined) el.textContent = String(text)
357
+ return el
358
+ }
359
+ function heading(root, data) {
360
+ if (data.title) root.append(node('h3', 'fs-figure-title', data.title))
361
+ }
362
+ function caption(root, data) {
363
+ if (data.caption) root.append(node('p', 'fs-caption', data.caption))
364
+ }
365
+ class Figure extends HTMLElement {
366
+ connectedCallback() {
367
+ queueMicrotask(() => {
368
+ if (!this.isConnected) return
369
+ if (!this.figureData) {
370
+ this._fsSrc = this.innerHTML // 直播补丁(sketchRuntime morph)拿它和新来的源码比,渲染后 innerHTML 就不是源码了
371
+ try { this.figureData = JSON.parse(this.querySelector('script[type="application/json"]')?.textContent || '{}') }
372
+ catch { this.figureData = {} }
373
+ }
374
+ this.render()
375
+ this.observer?.disconnect()
376
+ if (!window.ResizeObserver) return
377
+ this.observer = new ResizeObserver(() => {
378
+ const width = Math.round(this.clientWidth)
379
+ if (width && width !== this.lastWidth) { this.lastWidth = width; this.render() }
380
+ })
381
+ this.observer.observe(this)
382
+ })
383
+ }
384
+ disconnectedCallback() { this.observer?.disconnect() }
385
+ setData(data) { this.figureData = data; if (this.isConnected) this.render() }
386
+ error() {
387
+ // No guessed labels or fabricated zeroes when the input is invalid.
388
+ const error = node('p', 'fs-caption', this.figureData?.emptyLabel || '—')
389
+ error.setAttribute('role', 'alert')
390
+ this.replaceChildren(error)
391
+ }
392
+ }
393
+
394
+ class Chart extends Figure {
395
+ render() {
396
+ const data = this.figureData
397
+ if (!['bar', 'line'].includes(this.getAttribute('type') || 'bar') ||
398
+ !data || !Array.isArray(data.data) || !data.data.length || data.data.length > 100 ||
399
+ data.data.some((item) => typeof item?.label !== 'string' || typeof item.value !== 'number' || !Number.isFinite(item.value))) {
400
+ this.error(); return
401
+ }
402
+ this.replaceChildren()
403
+ const root = node('figure', 'fs-chart-figure')
404
+ heading(root, data)
405
+ this.append(root)
406
+ if (this.getAttribute('type') === 'line') this.line(root, data)
407
+ else this.bars(root, data)
408
+ caption(root, data)
409
+ }
410
+ bars(root, data) {
411
+ // A zero baseline also handles negative-only and mixed-sign comparisons honestly.
412
+ const magnitude = Math.max(1, ...data.data.map((item) => Math.abs(item.value)))
413
+ const low = Math.min(0, ...data.data.map((item) => item.value / magnitude))
414
+ const high = Math.max(0, ...data.data.map((item) => item.value / magnitude))
415
+ const span = high - low || 1
416
+ const zero = -low / span * 100
417
+ const list = node('div', 'fs-chart-bars')
418
+ list.setAttribute('role', 'list')
419
+ list.setAttribute('aria-label', String(data.title || data.unit || data.data.map((item) => item.label).join(', ')))
420
+ const narrow = this.clientWidth < 440
421
+ list.classList.toggle('fs-chart-bars--narrow', narrow)
422
+ for (const [index, item] of data.data.entries()) {
423
+ const row = node('div', 'fs-chart-bar-row')
424
+ row.setAttribute('role', 'listitem')
425
+ const label = node('span', 'fs-chart-bar-label', item.label)
426
+ const value = node('span', 'fs-chart-bar-value', number(item.value) + (data.unit ? ' ' + data.unit : ''))
427
+ const track = node('span', 'fs-chart-track')
428
+ track.setAttribute('aria-hidden', 'true')
429
+ const bar = node('span', 'fs-chart-bar')
430
+ bar.style.left = Math.min(zero, (item.value / magnitude - low) / span * 100) + '%'
431
+ bar.style.width = Math.abs(item.value / magnitude) / span * 100 + '%'
432
+ if (Number.isInteger(data.highlight) && data.highlight !== index) bar.classList.add('fs-chart-bar--context')
433
+ track.style.setProperty('--fs-zero', zero + '%')
434
+ track.append(bar)
435
+ row.append(label, track, value)
436
+ list.append(row)
437
+ }
438
+ root.append(list)
439
+ }
440
+ line(root, data) {
441
+ const width = Math.max(1, this.clientWidth)
442
+ const height = 238
443
+ const values = data.data.map((item) => item.value)
444
+ const maxAbs = Math.max(...values.map(Math.abs))
445
+ const magnitude = maxAbs ? Math.pow(10, Math.floor(Math.log10(maxAbs))) || Number.MIN_VALUE : 1
446
+ const min = Math.min(...values.map((v) => v / magnitude)), max = Math.max(...values.map((v) => v / magnitude))
447
+ const pad = (max - min || Math.abs(max) || 1) * .12
448
+ const limit = Number.MAX_VALUE / magnitude
449
+ const paddedLow = min >= 0 ? Math.max(0, min - pad) : min - pad
450
+ const paddedHigh = max <= 0 ? Math.min(0, max + pad) : max + pad
451
+ const roughStep = (paddedHigh - paddedLow) / 4 || .25
452
+ const power = Math.pow(10, Math.floor(Math.log10(roughStep)))
453
+ const step = ([1, 2, 5, 10].find((factor) => factor >= roughStep / power) || 10) * power
454
+ const low = Math.max(-limit, Math.floor(paddedLow / step) * step)
455
+ const high = Math.min(limit, Math.ceil(paddedHigh / step) * step) || step
456
+ const ticks = []
457
+ for (let tick = Math.ceil(low / step) * step; tick <= high + step * 1e-8; tick += step) {
458
+ ticks.push(Number((tick * magnitude).toPrecision(12)))
459
+ if (ticks.length > 8) break
460
+ }
461
+ const canvas = document.createElement('canvas')
462
+ const context = canvas.getContext('2d')
463
+ if (context) context.font = '12px ' + getComputedStyle(this).fontFamily
464
+ const left = Math.min(width * .35, Math.max(48, ...ticks.map((v) => (context?.measureText(number(v)).width || 36) + 14)))
465
+ const right = Math.max(left + 1, width - 8), top = 28, bottom = height - 32
466
+ const x = (i) => left + (right - left) * (values.length === 1 ? .5 : i / (values.length - 1))
467
+ const y = (value) => bottom - (value / magnitude - low) / (high - low) * (bottom - top)
468
+ const field = node('div', 'fs-chart-field')
469
+ const svg = mark('svg', { viewBox: \`0 0 \${width} \${height}\`, role: 'img', 'aria-label': String(data.title || data.data.map((item) => item.label).join(', ')) })
470
+ svg.append(mark('title', {}, data.data.map((v) => \`\${v.label}: \${number(v.value)} \${data.unit || ''}\`).join('; ')))
471
+ if (data.unit) svg.append(mark('text', { x: left, y: 14, class: 'fs-chart-unit' }, data.unit))
472
+ for (const tick of ticks) {
473
+ svg.append(mark('path', { d: \`M\${left} \${y(tick)}H\${right}\`, class: 'fs-chart-grid' }))
474
+ svg.append(mark('text', { x: left - 10, y: y(tick) + 4, 'text-anchor': 'end', class: 'fs-chart-tick' }, number(tick)))
475
+ }
476
+ const count = Math.min(values.length, width < 440 ? 3 : 5)
477
+ let previousRight = -Infinity
478
+ for (let i = 0; i < count; i++) {
479
+ const index = count === 1 ? 0 : Math.round(i * (values.length - 1) / (count - 1))
480
+ const label = data.data[index].label
481
+ const size = context?.measureText(label).width || label.length * 8
482
+ const px = x(index)
483
+ const labelLeft = i === 0 ? px : i === count - 1 ? px - size : px - size / 2
484
+ if (labelLeft < previousRight + 8 || size > right - left) continue
485
+ previousRight = labelLeft + size
486
+ svg.append(mark('text', { x: px, y: height - 9, 'text-anchor': i === 0 ? 'start' : i === count - 1 ? 'end' : 'middle', class: 'fs-chart-tick' }, label))
487
+ }
488
+ const path = values.map((value, i) => \`\${i ? 'L' : 'M'}\${x(i)} \${y(value)}\`).join(' ')
489
+ svg.append(mark('path', { d: path, class: 'fs-chart-line' }))
490
+ for (const [i, value] of values.entries()) svg.append(mark('circle', { cx: x(i), cy: y(value), r: 2.5, class: 'fs-chart-point' }))
491
+ const guide = mark('path', { class: 'fs-chart-guide', visibility: 'hidden' })
492
+ const dot = mark('circle', { r: 4, class: 'fs-chart-point', visibility: 'hidden' })
493
+ svg.append(guide, dot)
494
+ const detail = node('output', 'fs-chart-detail')
495
+ const hit = node('button', 'fs-chart-hit')
496
+ hit.type = 'button'
497
+ hit.setAttribute('aria-label', String(data.inspectLabel || data.title || data.data.map((item) => item.label).join(', ')))
498
+ hit.style.left = left + 'px'; hit.style.top = top + 'px'
499
+ hit.style.width = (right - left) + 'px'; hit.style.height = (bottom - top) + 'px'
500
+ let current = 0
501
+ const show = (position) => {
502
+ current = Math.max(0, Math.min(values.length - 1, position))
503
+ const a = Math.floor(current), b = Math.ceil(current), t = current - a
504
+ const value = (values[a] / magnitude * (1 - t) + values[b] / magnitude * t) * magnitude
505
+ const px = x(current)
506
+ guide.setAttribute('d', \`M\${px} \${top}V\${bottom}\`)
507
+ dot.setAttribute('cx', px); dot.setAttribute('cy', y(value))
508
+ guide.setAttribute('visibility', 'visible'); dot.setAttribute('visibility', 'visible')
509
+ const label = a === b ? data.data[a].label : \`\${data.data[a].label} – \${data.data[b].label}\`
510
+ detail.textContent = \`\${label} · \${number(value)} \${data.unit || ''}\`
511
+ }
512
+ hit.addEventListener('pointermove', (event) => {
513
+ detail.removeAttribute('aria-live')
514
+ const bounds = hit.getBoundingClientRect()
515
+ show((event.clientX - bounds.left) / bounds.width * (values.length - 1))
516
+ })
517
+ hit.addEventListener('focus', () => show(Math.round(current)))
518
+ hit.addEventListener('click', (event) => {
519
+ if (!event.detail) { show(Math.round(current)); return }
520
+ const bounds = hit.getBoundingClientRect()
521
+ show((event.clientX - bounds.left) / bounds.width * (values.length - 1))
522
+ })
523
+ hit.addEventListener('keydown', (event) => {
524
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
525
+ event.preventDefault()
526
+ detail.setAttribute('aria-live', 'polite')
527
+ show(event.key === 'Home' ? 0 : event.key === 'End' ? values.length - 1 : Math.round(current) + (event.key === 'ArrowRight' ? 1 : -1))
528
+ })
529
+ field.append(svg, hit)
530
+ root.append(field, detail)
531
+ }
532
+ }
533
+
534
+ class Flow extends Figure {
535
+ render() {
536
+ const data = this.figureData
537
+ if (!data || !Array.isArray(data.steps) || !data.steps.length || data.steps.length > 12 ||
538
+ data.steps.some((step) => !step || typeof step.label !== 'string' ||
539
+ (step.branches !== undefined && (!Array.isArray(step.branches) || step.branches.length > 8 ||
540
+ step.branches.some((branch) => !branch || typeof branch.label !== 'string'))))) { this.error(); return }
541
+ this.replaceChildren()
542
+ const root = node('figure', 'fs-flow-figure')
543
+ heading(root, data)
544
+ const list = node('ol', 'fs-flow-steps')
545
+ list.classList.toggle('fs-flow-steps--vertical', this.clientWidth < data.steps.length * 145)
546
+ list.style.setProperty('--fs-step-count', data.steps.length)
547
+ for (const [index, step] of data.steps.entries()) {
548
+ const item = node('li', 'fs-flow-step')
549
+ const status = ['done', 'active'].includes(step.status) ? step.status : 'pending'
550
+ item.dataset.status = status
551
+ if (status === 'active') item.setAttribute('aria-current', 'step')
552
+ const marker = node('span', 'fs-flow-marker', String(index + 1).padStart(2, '0'))
553
+ marker.setAttribute('aria-hidden', 'true')
554
+ const content = node('div', 'fs-flow-content')
555
+ content.append(node('span', 'fs-flow-label', step.label))
556
+ if (step.detail) content.append(node('span', 'fs-flow-description', step.detail))
557
+ if (Array.isArray(step.branches) && step.branches.length) {
558
+ const branches = node('ul', 'fs-flow-branches')
559
+ for (const branch of step.branches) {
560
+ const branchNode = node('li', 'fs-flow-branch')
561
+ branchNode.append(node('span', 'fs-flow-label', branch.label || ''))
562
+ if (branch.detail) branchNode.append(node('span', 'fs-flow-description', branch.detail))
563
+ branches.append(branchNode)
564
+ }
565
+ content.append(branches)
566
+ }
567
+ item.append(marker, content); list.append(item)
568
+ }
569
+ root.append(list); caption(root, data); this.append(root)
570
+ }
571
+ }
572
+
573
+ // 10-09(对标 ChatGPT Intelligent UI「只能拼固定组件库」):统一的拼装部件,模型只给 JSON,外观由宿主定。
574
+ const askOf = (text) => { try { window.forsionIntelligentUi.ask(String(text)) } catch (e) { console.warn(e) } }
575
+ const button = (label, onClick) => { const b = node('button', 'fs-button', label); b.type = 'button'; b.addEventListener('click', onClick); return b }
576
+
577
+ /** <fs-compare>:并排选项 {title?, caption?, options:[{label, summary?, points?:string[], ask?:{label?, text}}]}(2–6 项)。 */
578
+ class Compare extends Figure {
579
+ render() {
580
+ const d = this.figureData
581
+ const ok = d && Array.isArray(d.options) && d.options.length >= 2 && d.options.length <= 6 &&
582
+ d.options.every((o) => o && typeof o.label === 'string' &&
583
+ (o.points === undefined || (Array.isArray(o.points) && o.points.length <= 8 && o.points.every((p) => typeof p === 'string'))) &&
584
+ (o.ask === undefined || (o.ask && typeof o.ask.text === 'string')))
585
+ if (!ok) { this.error(); return }
586
+ this.replaceChildren()
587
+ const root = node('div', 'fs-compare')
588
+ heading(root, d)
589
+ const grid = node('div', 'fs-grid')
590
+ for (const o of d.options) {
591
+ const card = node('section', 'fs-option')
592
+ card.append(node('h4', '', o.label))
593
+ if (typeof o.summary === 'string' && o.summary) card.append(node('p', 'fs-muted', o.summary))
594
+ if (Array.isArray(o.points) && o.points.length) { const ul = node('ul', 'fs-points'); for (const p of o.points) ul.append(node('li', '', p)); card.append(ul) }
595
+ if (o.ask) { const act = node('div', 'fs-actions'); act.append(button(o.ask.label || o.label, () => askOf(o.ask.text))); card.append(act) }
596
+ grid.append(card)
597
+ }
598
+ root.append(grid); caption(root, d); this.append(root)
599
+ }
600
+ }
601
+
602
+ /** <fs-choice>:追问选择题 {question, options:[{label, ask?}], multiple?, ask?("{choices}" 占位), submitLabel?, caption?}。
603
+ * 单选点了就把 ask(缺省 label)当用户消息发出;多选勾完按提交,把 ask 模板里的 {choices} 换成所选。 */
604
+ class Choice extends Figure {
605
+ render() {
606
+ const d = this.figureData
607
+ const ok = d && typeof d.question === 'string' && Array.isArray(d.options) && d.options.length >= 2 && d.options.length <= 8 &&
608
+ d.options.every((o) => o && typeof o.label === 'string' && (o.ask === undefined || typeof o.ask === 'string'))
609
+ if (!ok) { this.error(); return }
610
+ this.picked ||= new Set() // 宽度变化重绘时保住已勾的
611
+ for (const i of [...this.picked]) if (i >= d.options.length) this.picked.delete(i) // setData 换了更短的选项表:越界的勾作废(Codex 10-09)
612
+ this.replaceChildren()
613
+ const root = node('div', 'fs-choice')
614
+ root.setAttribute('role', 'group')
615
+ root.append(node('p', 'fs-choice-question', d.question))
616
+ const opts = node('div', 'fs-choice-options')
617
+ if (d.multiple) {
618
+ for (const [i, o] of d.options.entries()) {
619
+ const l = node('label', 'fs-check'); const c = node('input'); c.type = 'checkbox'; c.checked = this.picked.has(i)
620
+ c.addEventListener('change', () => { if (c.checked) this.picked.add(i); else this.picked.delete(i) })
621
+ l.append(c, node('span', '', o.label)); opts.append(l)
622
+ }
623
+ const act = node('div', 'fs-actions')
624
+ act.append(button(d.submitLabel || 'OK', () => {
625
+ const chosen = [...this.picked].sort((x, y) => x - y).map((i) => d.options[i]?.label).filter(Boolean)
626
+ if (chosen.length) askOf(String(d.ask || '{choices}').replace('{choices}', chosen.join(', ')))
627
+ }))
628
+ root.append(opts, act)
629
+ } else {
630
+ for (const o of d.options) opts.append(button(o.label, () => askOf(typeof o.ask === 'string' ? o.ask : o.label)))
631
+ root.append(opts)
632
+ }
633
+ caption(root, d); this.append(root)
634
+ }
635
+ }
636
+
637
+ /** <fs-checklist>:勾选清单 {title?, caption?, items:[{label, detail?}]}(1–40 项);勾选状态经 forsionIntelligentUi.setState 存在本机
638
+ * (键 checklists[<元素 id 或 'checklist'>]),重开这张卡还在。 */
639
+ class Checklist extends Figure {
640
+ render() {
641
+ const d = this.figureData
642
+ const ok = d && Array.isArray(d.items) && d.items.length >= 1 && d.items.length <= 40 &&
643
+ d.items.every((it) => it && typeof it.label === 'string' && (it.detail === undefined || typeof it.detail === 'string'))
644
+ if (!ok) { this.error(); return }
645
+ const key = this.id || 'checklist'
646
+ const st = window.forsionIntelligentUi?.state
647
+ const saved = st && typeof st === 'object' && st.checklists ? st.checklists[key] : undefined
648
+ const done = new Set(Array.isArray(saved) ? saved.filter((i) => Number.isInteger(i)) : [])
649
+ this.replaceChildren()
650
+ const root = node('div', 'fs-checklist')
651
+ heading(root, d)
652
+ const ul = node('ul', 'fs-checklist-items')
653
+ for (const [i, it] of d.items.entries()) {
654
+ const li = node('li'); const l = node('label', 'fs-check'); const c = node('input'); c.type = 'checkbox'; c.checked = done.has(i)
655
+ c.addEventListener('change', () => {
656
+ if (c.checked) done.add(i); else done.delete(i)
657
+ const cur = window.forsionIntelligentUi.state
658
+ const base = cur && typeof cur === 'object' && !Array.isArray(cur) ? cur : {}
659
+ try { window.forsionIntelligentUi.setState({ ...base, checklists: { ...(base.checklists || {}), [key]: [...done].sort((x, y) => x - y) } }) } catch (e) { console.warn(e) }
660
+ })
661
+ const text = node('span', '', it.label)
662
+ if (it.detail) text.append(node('small', 'fs-muted', ' ' + it.detail))
663
+ l.append(c, text); li.append(l); ul.append(li)
664
+ }
665
+ root.append(ul); caption(root, d); this.append(root)
666
+ }
667
+ }
668
+
669
+ function register() {
670
+ if (!customElements.get('fs-chart')) customElements.define('fs-chart', Chart)
671
+ if (!customElements.get('fs-flow')) customElements.define('fs-flow', Flow)
672
+ if (!customElements.get('fs-compare')) customElements.define('fs-compare', Compare)
673
+ if (!customElements.get('fs-choice')) customElements.define('fs-choice', Choice)
674
+ if (!customElements.get('fs-checklist')) customElements.define('fs-checklist', Checklist)
675
+ }
676
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', register)
677
+ else register()
678
+ })()
679
+ `,Tu=16384,$u="forsion_sketch_state_v1",lc=48;function ua(e){try{const t=JSON.stringify(e);return t&&new TextEncoder().encode(t).length<=Tu?t:void 0}catch{return}}function Ux(e,t,n){let o=2166136261;for(let r=0;r<n.length;r++)o=Math.imul(o^n.charCodeAt(r),16777619);return JSON.stringify([e,t,n.length,o>>>0])}function ju(e){const t=e.getItem($u);if(!t||t.length>Tu*(lc+4))return[];let n;try{n=JSON.parse(t)}catch{return[]}return Array.isArray(n)?n.filter(o=>!!o&&typeof o.key=="string"&&o.key.length<2048&&ua(o.state)!==void 0).slice(-lc):[]}function Xx(e){try{return ju(localStorage).find(t=>t.key===e)?.state??null}catch{return null}}function Gx(e,t){const n=ua(t);if(!(!n||e.length>=2048))try{const o=ju(localStorage).filter(r=>r.key!==e);o.push({key:e,state:JSON.parse(n)}),localStorage.setItem($u,JSON.stringify(o.slice(-lc)))}catch{}}const Jx="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data:",Zx="allow-scripts",tl=40,Qx=2400,ey=220,ty={"--fs-bg":"transparent"},ny=[["--fs-surface","--overlay-subtle"],["--fs-text","--text"],["--fs-muted","--text-muted"],["--fs-faint","--text-faint"],["--fs-border","--border"],["--fs-rule","--overlay-medium"],["--fs-accent","--accent-ink"],["--fs-accent-soft","--accent-light"],["--fs-green","--green"],["--fs-danger","--danger"],["--fs-radius","--radius-sm"],["--fs-font","--font-ui"],["--fs-mono","--font-mono"]];function Ru(e){return String(e).replace(/[<>]/g,"").trim()}function nl(e){const t=getComputedStyle(e),n={...ty};for(const[o,r]of ny){const s=Ru(t.getPropertyValue(r));s&&(n[o]=s)}return n["color-scheme"]=document.documentElement.getAttribute("data-mode")==="dark"?"dark":"light",n}const Fs=new Set;let Fr=null;function oy(e){return Fs.add(e),!Fr&&typeof MutationObserver<"u"&&(Fr=new MutationObserver(()=>{for(const t of Fs)t()}),Fr.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","data-skin","data-bg","data-mode","data-flat","data-glass","class"]})),()=>{Fs.delete(e),!Fs.size&&Fr&&(Fr.disconnect(),Fr=null)}}const ry=":root{--fs-s1:var(--fs-accent);--fs-s2:color-mix(in srgb,var(--fs-text) 62%,transparent);--fs-s3:color-mix(in srgb,var(--fs-text) 42%,transparent);--fs-s4:color-mix(in srgb,var(--fs-text) 26%,transparent);--fs-s5:color-mix(in srgb,var(--fs-text) 14%,transparent)}";function sy(e){const t=Object.entries(e).map(([n,o])=>`${n.replace(/[^a-z-]/gi,"")}:${Ru(o)}`).join(";");return t?`:root{${t}}`:""}function ay(e,t={},n=null,o=""){const r=(ua(n)??"null").replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),s=Wx.replace("__SKETCH_INITIAL_STATE__",()=>r).replace("__SKETCH_NONCE__",()=>o.replace(/[^A-Za-z0-9-]/g,""));return`<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${Jx}"><meta name="viewport" content="width=device-width, initial-scale=1"><style>${sy(t)}${ry}${qx}</style><script>${s};
680
+ ${Yx}<\/script></head><body>${e}</body></html>`}const Lu=`(?![^>]*\\stype\\s*=\\s*["']?application/json\\b)`,cy=new RegExp(`<script\\b${Lu}[^>]*>[\\s\\S]*?<\/script\\s*>`,"gi"),iy=new RegExp(`<script\\b${Lu}[^>]*>[\\s\\S]*$`,"i"),ly=/<script\b[^>]*$/i,uy=/<[a-zA-Z][^>]*(?:>|$)/g,dy=/\son[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,fy=/<(fs-[a-z]+)\b(?![\s\S]*<\/\1\s*>)[\s\S]*$/i;function ol(e){return e.replace(cy,"").replace(iy,"").replace(ly,"").replace(fy,"").replace(uy,t=>t.replace(dy,""))}const py=400,my=1500,hy=2e4,gy=150;function xy(){try{const e=window.Capacitor;return!!(e&&typeof e.isNativePlatform=="function"&&e.isNativePlatform())}catch{return!1}}function yy(e){return!e||document.activeElement!==e?!1:navigator.userActivation?.isActive===!0}const by=()=>crypto.randomUUID?crypto.randomUUID():Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),vy=({item:e,actions:t,stateScope:n,onAsk:o})=>{const{t:r}=Bt(),s=x.useMemo(()=>n&&!e.draft?Ux(n,e.callId,e.html):null,[n,e.callId,e.html,e.draft]),c=x.useRef(o);c.current=o;const i=x.useRef(!!e.draft);i.current=!!e.draft;const a=x.useRef(0),l=x.useRef(e.draft?ol(e.html):e.html),m=x.useRef(s?Xx(s):null),g=x.useRef(by()),C=x.useRef(null),M=x.useRef(null),S=x.useRef(null),[z,L]=x.useState(e.draft?tl:ey),[E,F]=x.useState(!1),[U,q]=x.useState(!1),[de,me]=x.useState(null);x.useLayoutEffect(()=>{C.current&&me(nl(C.current))},[]),x.useEffect(()=>oy(()=>{const tt=C.current,J=S.current?.contentWindow;tt&&J&&J.postMessage({type:"sketch-theme",vars:nl(tt)},"*")}),[]);const Ne=x.useRef(!1),be=x.useRef(!1),ge=x.useRef(null),p=x.useRef(void 0),fe=tt=>{S.current?.contentWindow?.postMessage(tt,"*")},ce=()=>{if(p.current=void 0,!Ne.current)return;const tt=ge.current;ge.current=null,tt!==null&&i.current&&!be.current&&fe({type:"sketch-draft",html:tt})},te=()=>{!Ne.current||be.current||(be.current=!0,clearTimeout(p.current),p.current=void 0,ge.current=null,fe({type:"sketch-final",html:e.html}))},ee=x.useRef(!!e.draft);x.useEffect(()=>{e.draft?(ge.current=ol(e.html),p.current||(p.current=setTimeout(ce,gy))):ee.current&&te()},[e.html,e.draft]),x.useEffect(()=>()=>clearTimeout(p.current),[]);const Ie=()=>{Ne.current=!0,!i.current&&ee.current?te():ge.current!==null&&ce()};x.useEffect(()=>{let tt,J;const ye=()=>{s&&tt!==void 0&&Gx(s,JSON.parse(tt)),tt=void 0,J=void 0},Ae=j=>{if(!S.current||j.source!==S.current.contentWindow)return;const W=j.data;if(W?.type==="sketch-state"&&s){const he=ua(W.state);he!==void 0&&(tt=he,J||(J=setTimeout(ye,200)))}W&&W.type==="sketch-height"&&Number.isFinite(Number(W.height))&&L(Math.min(Qx,Math.max(tl,Math.ceil(Number(W.height)))));const ne=W&&W.nonce===g.current&&!i.current&&yy(S.current);if(ne&&W.type==="sketch-ask"&&typeof W.text=="string"&&c.current){const he=Date.now(),qe=W.text.trim().slice(0,py);qe&&he-a.current>=my&&(a.current=he,c.current(qe))}if(ne&&W.type==="sketch-copy"&&typeof W.text=="string"){const he=W.text.slice(0,hy);he&&navigator.clipboard?.writeText(he).catch(()=>{})}};return window.addEventListener("message",Ae),window.addEventListener("pagehide",ye),()=>{window.removeEventListener("message",Ae),window.removeEventListener("pagehide",ye),clearTimeout(J),ye()}},[s]),x.useEffect(()=>{const tt=M.current;if(!tt||E)return;const J=()=>q(tt.scrollHeight>tt.clientHeight+1);J();const ye=new ResizeObserver(J);return ye.observe(tt),()=>ye.disconnect()},[z,E]);const Me=x.useMemo(()=>de?ay(l.current,de,m.current,g.current):"",[de]),dt=e.draft?void 0:t;return u.jsxs("div",{className:"sketch-card",ref:C,"data-sketch-call-id":e.callId,"data-sketch-draft":e.draft?"":void 0,children:[(e.title||dt)&&u.jsxs("div",{className:"sketch-card-head",children:[e.title&&u.jsx("div",{className:"sketch-card-title",children:e.title}),dt?.(e)]}),u.jsx("div",{ref:M,className:`sketch-clip${E?" open":""}${U&&!E?" faded":""}`,children:de&&u.jsx("iframe",{ref:S,className:"sketch-frame",sandbox:Zx,srcDoc:Me,style:{height:z},title:e.title||"Intelligent UI",onLoad:Ie})}),U&&u.jsx("button",{type:"button",className:"sketch-card-toggle",onClick:()=>F(tt=>!tt),children:r(E?"sketch.collapse":"sketch.expand")})]})},wy=({item:e})=>{const{t}=Bt();return u.jsxs("div",{className:"sketch-card","data-sketch-call-id":e.callId,children:[e.title&&u.jsx("div",{className:"sketch-card-title",children:e.title}),u.jsx("div",{className:"sketch-card-note",children:t("sketch.mobileUnavailable")})]})},ky=({items:e,actions:t,stateScope:n,onAsk:o})=>{const r=xy(),s=r?wy:vy;return u.jsx(u.Fragment,{children:e.map(c=>u.jsx(s,{item:c,actions:r?void 0:t,stateScope:n,onAsk:r?void 0:o},`${n||""}:${c.callId}`))})};Cn({"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 Du(){const[,e]=x.useState(0);return x.useEffect(()=>ql(()=>e(t=>t+1)),[]),je}const Sy=Vf(()=>Nd(()=>import("./PdfAnnotator-bdB9evsY.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url).then(e=>({default:e.PdfAnnotator}))),rr=()=>{},Iu=/^!\[\[([^\]\n]+)\]\]$/,Cy=/\.(png|jpe?g|gif|webp|svg|avif|bmp)$/i,Ey=/\.[a-z0-9]{1,8}$/i,My=/\.db$/i,zy=/\.pdf$/i,Ay=/^https?:\/\/\S+$/i;function No(e){if(e.type.name==="code_block"){const g={"forsion-instructions":"instructions","forsion-task":"task","forsion-prompt":"prompt"}[e.attrs.language];return g&&(g==="instructions"||Ms(e.textContent))?{k:"document-agent",type:g,src:e.textContent}:Vx(e.attrs.language)?e.textContent.trim()?{k:"sketch",src:e.textContent}:null:e.attrs.language!=="forsion-button"||!Zl(Ou(e.textContent))?null:{k:"button",src:e.textContent}}if(e.type.name!=="paragraph")return null;const t=e.textContent.trim(),n=Iu.exec(t);if(!n)return Ay.test(t)?{k:"bookmark",url:t}:null;const o=n[1],[r,s]=o.split("|"),c=r.trim();if(Cy.test(c))return null;const i=Md(o);if(i)return{k:"web",url:i,w:xa(o)};if(!c.includes("#")&&My.test(c))return{k:"db",name:c,view:s?.trim()||null};if(!c.includes("#")&&zd(c))return{k:"draw",target:c};const a=Xr.getState().embedRenderers;if(ii(a,o.trim()))return{k:"plugin",target:o.trim()};const l=c.includes("#")?Jc(c)?.target??null:c;if(l&&ii(a,l))return{k:"plugin",target:l};if(Kf(c))return{k:"note",target:o};const m=Jc(c);return m?{k:"file",name:m.target,fileKind:Ad.test(m.target)?"video":"audio",loc:m.loc,badAnchor:c.includes("#")&&!m.loc,w:xa(o)}:!c.includes("#")&&Ey.test(c)?{k:"file",name:c,fileKind:zy.test(c)?"pdf":"other",w:xa(o)}:{k:"note",target:o}}const Ny=new Set(["file","db","draw","plugin","note"]),Pu=e=>!!e&&Ny.has(e.k);function Es(e){return!!e&&e.type.name==="paragraph"&&Pu(No(e))}function Ty({name:e,fileKind:t,pagePath:n,loc:o,badAnchor:r,insertAfter:s}){const c=Du(),i=dn(M=>M.files),a=dn(M=>M.openWikiLink),[l,m]=x.useState(!0),g=t==="pdf"?Kp(e,i,n):null;if(t==="other")return!/\.[a-z0-9]+\.md$/i.test(e)&&!ui()?u.jsxs("div",{className:"embed-file",children:[u.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),u.jsx("span",{className:"embed-file-name",children:e})]}):u.jsxs("button",{className:"embed-file",onClick:()=>{/\.[a-z0-9]+\.md$/i.test(e)?a(e,n):on.openAttachment(n,e)},title:/\.[a-z0-9]+\.md$/i.test(e)?c("uembed.openInTab"):c("uembed.openWithSystem"),children:[u.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),u.jsx("span",{className:"embed-file-name",children:e}),u.jsx("span",{className:"embed-file-open",children:c("uembed.open")})]});const C=gc(e);return u.jsxs("div",{className:"embed-media",children:[u.jsxs("div",{className:"embed-media-head",children:[u.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:t==="pdf"?"📕":t==="video"?"🎬":"🎵"}),u.jsx("span",{className:"embed-file-name",children:e}),o&&u.jsxs("span",{className:"embed-media-at",title:c("uembed.startAt"),children:["@",Zc(o.at),o.to?`–${Zc(o.to)}`:""]}),r&&u.jsx("span",{className:"embed-media-warn",title:c("uembed.badAnchorTip"),children:c("uembed.badAnchor")}),u.jsx("button",{className:"embed-media-btn",onClick:()=>m(M=>!M),children:c(l?"uembed.collapse":"uembed.expand")}),(t==="pdf"||ui())&&u.jsx("button",{className:"embed-media-btn",title:c(t==="pdf"?"uembed.openPdfInTab":"uembed.openWithSystem"),onClick:()=>{t==="pdf"?a(e,n):on.openAttachment(n,e)},children:c("uembed.open")})]}),l&&t==="pdf"&&(g?u.jsx("div",{className:"embed-pdf embed-pdf-live",children:u.jsx(x.Suspense,{fallback:u.jsx("div",{className:"embed-pdf-loading",children:c("uembed.loadingPdf")}),children:u.jsx(Sy,{pdfPath:g,embed:!0})})}):u.jsx("iframe",{className:"embed-pdf",src:C,title:e})),l&&(t==="video"||t==="audio")&&u.jsx(tp,{kind:t,url:C,name:e,pagePath:n,loc:o??null,insertAfter:s})]})}function $y({target:e,pagePath:t,readOnly:n}){const o=Du(),r=dn(E=>E.openWikiLink),s=dn(E=>E.loadPage),c=dn(E=>E.pages),i=dn(E=>E.linkGraphVersion),[a,l]=x.useState("loading"),{note:m,subpath:g}=Rd(e),C=g?`${m}#${g}`:m;x.useEffect(()=>{let E=!0;return l("loading"),Promise.resolve(C?on.resolveEmbed?.(C,t)??null:null).then(F=>{E&&l(F)}).catch(()=>{E&&l(null)}),()=>{E=!1}},[C,t,i]);const M=!n&&a===null&&!!m&&!ys(m,c,t),S=()=>{dn.getState().openWikiLink(m,t),dn.getState().pendingWikiCreate?.name===m&&dn.getState().confirmWikiCreate()},L=(a&&a!=="loading"?ep(a.type):void 0)?.Editor;return u.jsxs("div",{className:"embed-body",children:[u.jsxs("div",{className:"embed-head",children:[u.jsx("span",{className:"embed-badge",title:o("uembed.crossNote"),children:o("uembed.badge")}),a&&a!=="loading"&&u.jsxs("button",{className:"embed-src",onClick:()=>{s(a.owner)},title:o("uembed.editAtSource"),children:[Ld(a.owner)," ↗"]})]}),a==="loading"?u.jsx("div",{className:"embed-loading",children:o("uembed.resolving")}):a&&L?u.jsx(L,{blockId:"uembed",content:a.content,pagePath:a.owner,readOnly:!0,onChange:rr,onInsertAfter:rr,onDeleteEmpty:rr,onMergePrev:rr,onArrowOut:rr,onMoveDir:rr,focusPlace:null,onFocused:rr,requestSelfFocus:rr,onOpenWiki:(E,F)=>r(E,a.owner,F),getPageNames:()=>c}):u.jsxs("div",{className:"embed-missing",children:[o("uembed.embedMissing"),u.jsx("code",{children:e}),M&&u.jsx("button",{type:"button",className:"embed-media-btn embed-create",title:o("uembed.createTip",{name:m}),onClick:S,children:o("uembed.create")})]})]})}function jy({kind:e,pagePath:t,replaceText:n,insertAfter:o,startTask:r,readOnly:s=!1}){const c=s?()=>{}:n;switch(e.k){case"document-agent":return u.jsx(_x,{kind:e.type,src:e.src,pagePath:t,readOnly:s,activeInstructions:e.activeInstructions,onChange:c,onStart:r,onOpen:i=>Nr()?.openDocumentTask?.(i)});case"db":return u.jsx(Qf,{target:e.name,pagePath:t,initialView:e.view??void 0,readOnly:s,onViewChange:i=>c(i?`![[${e.name}|${i}]]`:`![[${e.name}]]`)});case"draw":return u.jsx(Zf,{target:e.target,pagePath:t,readOnly:s});case"plugin":return u.jsx(Jf,{target:e.target,pagePath:t});case"file":return u.jsx(Ty,{name:e.name,fileKind:e.fileKind,pagePath:t,loc:e.loc,badAnchor:e.badAnchor,insertAfter:s?()=>{}:o});case"note":return u.jsx($y,{target:e.target,pagePath:t,readOnly:s});case"bookmark":return s?u.jsx(li,{url:e.url}):u.jsx(li,{url:e.url,onChangeUrl:i=>n(i),onEmbed:()=>n(`![[${jd(e.url)}]]`)});case"web":return u.jsx(Gf,{url:e.url,toCard:()=>c(e.url)});case"button":{const i=Zl(Ou(e.src));return i?u.jsx(Uf,{spec:i,readOnly:s,onChange:a=>c(Ry(Xf(a)))}):u.jsx("span",{})}case"sketch":return u.jsx(ky,{items:[{callId:"note-sketch",html:e.src}]})}}function Ou(e){return"```forsion-button\n"+e+"\n```"}function Ry(e){const t=/^```forsion-button[ \t]*\r?\n([\s\S]*?)\r?\n?```$/.exec(e.trim());return t?t[1]:e}const rl=(e,t)=>e.k==="db"?`db:${e.name}`:e.k==="document-agent"?`document-agent:${e.type}:${e.type==="instructions"?"":Ms(e.src)?.id}`:`${e.k}:${t}`;function Ly(e,t,n){let o=!0;return e.mapping.maps.forEach((r,s)=>{const c=e.mapping.slice(s+1);r.forEach((i,a,l,m)=>{(c.map(l,-1)<t||c.map(m,1)>n)&&(o=!1)})}),o}function Dy(e){let t=!0;return e.steps.forEach((n,o)=>{if(!t)return;const r=e.docs[o],s=e.docs[o+1]??e.doc;let c=0;n.getMap().forEach((i,a,l,m)=>{c++,t&&!(sl(r,i,a)&&sl(s,l,m))&&(t=!1)}),!c&&!(n instanceof qf||n instanceof Wf)&&(t=!1)}),t}function sl(e,t,n){const o=e.resolve(t);return o.parent.isTextblock&&o.depth>0&&o.sameParent(e.resolve(n))&&!No(o.parent)}function Iy(e){return[Et(()=>{const n=new $n("UNIFIED_EMBED_LAYER"),o=new Map,r=new Set;let s=Xr.getState().embedRenderers;const c=(a,l,m,g,C=null,M=null)=>{s=Xr.getState().embedRenderers;const S=[],z=new Map,L=(E,F)=>{const U=No(E);if(!U)return;U.k==="document-agent"&&(U.activeInstructions=a.resolve(F).depth===0);const q=rl(U,E.textContent),de=z.get(q)??0;z.set(q,de+1);const me=Pu(U);if(!me&&g===F&&m>F&&l<F+E.nodeSize||C===F)return;const Ne=`${q}#${de}`,be=o.get(Ne),ge=U.k==="document-agent"?`${U.activeInstructions}:${E.textContent}`:E.textContent;be&&be.text!==ge&&(be.text=ge,be.render(U));const p=me&&M===F;p||S.push(ao.inline(F+1,F+E.nodeSize-1,{class:"wikilink-src-hidden"})),S.push(ao.node(F,F+E.nodeSize,{class:`unified-embed-host${me?" unified-embed-soft":""}${p?" unified-embed-src":""}`})),S.push(ao.widget(me?F+E.nodeSize-1:F+1,fe=>{const ce=o.get(Ne);if(ce)return ce.refs++,ce.dom;const te=document.createElement("div");te.className="unified-embed",te.contentEditable="false";const ee=Ae=>{let j=0,W=null;return Ae.state.doc.descendants((ne,he)=>{if(W)return!1;const qe=No(ne);return qe&&rl(qe,ne.textContent)===q?j===de?(W={at:he,size:ne.nodeSize},!1):(j++,!1):!0}),W};te.addEventListener("mousedown",Ae=>{if(Ae.button!==0)return;const j=Ae.target;if(j!==te&&j.parentElement!==te||j.closest('.amx-src-btn, .amx-img-resize, button, a, input, textarea, select, iframe, webview, video, audio, [contenteditable="true"]'))return;const W=i;if(!W)return;const ne=ee(W);ne&&(Ae.preventDefault(),Ae.stopPropagation(),W.dispatch(W.state.tr.setSelection(Se.create(W.state.doc,ne.at))),W.focus())});const Ie=Ae=>{const j=i;if(!j)return;const W=ee(j);W&&j.dispatch(j.state.tr.insertText(Ae,W.at+1,W.at+W.size-1))},Me=U.k==="web"||U.k==="file"&&U.fileKind!=="other",dt=U.k==="web"||U.k==="file"?U.w:void 0;dt&&(te.style.width=`${dt}px`);const tt=document.createElement("div");if(tt.className="unified-embed-body",te.appendChild(tt),Me){const Ae=Iu.exec(E.textContent.trim())?.[1];Ae!==void 0&&Yf(te,te,j=>Ie(`![[${Td(Ae,j)}]]`))}const J=Sm.createRoot(tt),ye=Ae=>J.render(u.jsx($d,{children:u.jsx(jy,{kind:Ae,pagePath:e.path,readOnly:!!e.readOnly,insertAfter:j=>{const W=i;if(!W)return;const ne=ee(W);if(!ne)return;const he=W.state.schema.nodes.paragraph;if(!he)return;const qe=j.split(/\n{2,}/).map(et=>he.create(null,et?W.state.schema.text(et):null));W.dispatch(W.state.tr.insert(ne.at+ne.size,qe))},startTask:async(j,W)=>{const ne=Nr(),he=dn.getState().vaultRoot,qe=i,et=qe&&ee(qe);if(!et)throw new Error(je("documentTask.sourceGone"));const ht={from:et.at,to:et.at+et.size,deleted:!1};r.add(ht);try{const Ye=()=>{if(ht.deleted||e.readOnly||!i||i!==qe||e.alive?.()===!1||dn.getState().vaultRoot!==he)return null;const Ze=i.state.doc.nodeAt(ht.from);if(!Ze||ht.from+Ze.nodeSize!==ht.to)return null;const yn=No(Ze);if(yn?.k!=="document-agent"||yn.type!==W)return null;const ft=Ze?Ms(Ze.textContent):null;return ft?.id===j.id&&ft.prompt===j.prompt&&ft.agent===j.agent?ft:null};if(!Ye()||!e.flush)throw new Error(je("documentTask.sourceGone"));if(await e.flush(),!Ye()||!i)throw new Error(je("documentTask.sourceGone"));const Ht=Au(ic(i.state.doc),e.path),Ot=`${j.prompt.trim()}
681
+
682
+ Source note: ${JSON.stringify(e.path)}. Read the source note before editing it.
683
+ ${Ht}`;if(W==="prompt"){const Ze=await ne?.startChat?.({agent:j.agent,prompt:Ot,send:!1,...ne?.hostExecution?.()&&he?{cwd:he}:{},alive:()=>!!Ye()});if(!Ze?.ok)throw new Error(Ze?.error||je("docagent.unavailable"));return{}}const Kt=Ye()?.sessionId;if(Kt)return{sessionId:Kt};if(!he||!ne?.submitDocumentTask)throw new Error(je("docagent.unavailable"));const Ut=await ne.submitDocumentTask({key:`${he}
684
+ ${e.path}
685
+ ${j.id}`,agent:j.agent,prompt:Ot,vaultRoot:he,alive:()=>!!Ye(),onCreated:async Ze=>{const yn=Ye();if(!yn||yn.sessionId&&yn.sessionId!==Ze)throw new Error(je("documentTask.sourceGone"));const ft=i;if(ft.dispatch(ft.state.tr.insertText(xs({...yn,sessionId:Ze}),ht.from+1,ht.to-1)),await e.flush(),Ye()?.sessionId!==Ze)throw new Error(je("documentTask.sourceGone"))}});if(!Ut.ok)throw new Error(Ut.error||je("docagent.startFailed"));return{sessionId:Ut.sessionId}}finally{r.delete(ht)}},replaceText:Ie})}));return ye(U),jm(te,fe,()=>{const Ae=i;if(!Ae)return;const j=ee(Ae);if(!j)return;const W=Ae.state.tr.setSelection(Le.near(Ae.state.doc.resolve(j.at+1)));W.setMeta(n,{sourcePos:j.at}),Ae.dispatch(W),Ae.focus()}),te.querySelector(".amx-src-btn")?.classList.add("amx-src-btn--block"),o.set(Ne,{root:J,dom:te,text:ge,render:ye,refs:1}),te},{key:Ne,side:me?1:-1,ignoreSelection:!0,stopEvent:fe=>/^(key|composition|beforeinput|input|paste|cut|copy)/.test(fe.type),destroy:()=>{const fe=o.get(Ne);fe&&(fe.refs--,!(fe.refs>0)&&queueMicrotask(()=>{fe.refs>0||o.get(Ne)!==fe||(o.delete(Ne),fe.root.unmount())}))}}))};return a.descendants((E,F)=>(L(E,F),!0)),dr.create(a,S)};let i=null;return new Yt({key:n,view:a=>(i=a,{destroy:()=>{for(const l of r)l.deleted=!0;i=null,queueMicrotask(()=>{if(!i){for(const[,l]of o)l.root.unmount();o.clear()}})}}),state:{init:(a,l)=>({decos:c(l.doc,l.selection.from,l.selection.to,null),sourcePos:null,pendingPos:null,revealPos:null}),apply:(a,l,m,g)=>{for(const F of r)for(const U of a.mapping.maps){if(F.deleted)break;const q=U.mapResult(F.from,1),de=U.mapResult(F.to,-1);(q.deleted||de.deleted||q.pos>=de.pos)&&(F.deleted=!0),F.from=q.pos,F.to=de.pos}const C=a.getMeta(n);let M=l.sourcePos;if(M!=null&&a.docChanged&&(M=a.mapping.map(M)),C&&typeof C.sourcePos=="number")M=C.sourcePos;else if(M!=null&&a.selectionSet){const F=g.doc.nodeAt(M);(!F||g.selection.to<=M||g.selection.from>=M+F.nodeSize)&&(M=null)}let S=l.pendingPos;if(S!=null&&a.docChanged&&(S=a.mapping.map(S,-1)),C?.commit)S=null;else if(a.docChanged&&g.selection.empty&&!/^(paste|drop)$/.test(String(a.getMeta("uiEvent")??""))){const F=g.selection.$head,U=F.depth>0?F.before():-1;U>=0&&F.parent.type.name==="paragraph"&&No(F.parent)?.k==="bookmark"&&Ly(a,U+1,U+F.parent.nodeSize-1)&&(S=U)}if(S!=null){const F=g.doc.nodeAt(S),{from:U,to:q}=g.selection;(!F||F.type.name!=="paragraph"||q<S+1||U>S+F.nodeSize-1)&&(S=null)}let z=null;const L=g.selection;if(L instanceof Le&&L.$from.depth>0&&L.$from.sameParent(L.$to)&&Es(L.$from.parent)){const F=L.$from.before(),U=l.revealPos==null?null:a.docChanged?a.mapping.map(l.revealPos):l.revealPos;($m(g)||U===F)&&(z=F)}if(!a.docChanged&&!a.selectionSet&&!C&&S===l.pendingPos&&z===l.revealPos)return{sourcePos:M,pendingPos:S,revealPos:z,decos:l.decos.map(a.mapping,a.doc)};const E=(F,U=1)=>F==null?null:a.mapping.map(F,U);return!C&&M==null&&l.sourcePos==null&&S===E(l.pendingPos,-1)&&z===E(l.revealPos)&&s===Xr.getState().embedRenderers&&Dy(a)?{sourcePos:M,pendingPos:S,revealPos:z,decos:l.decos.map(a.mapping,a.doc)}:{sourcePos:M,pendingPos:S,revealPos:z,decos:c(g.doc,g.selection.from,g.selection.to,M,S,z)}}},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 Py=[Et(()=>Ko({Enter:Xd,"Shift-Enter":Ud,"Mod-Enter":Yd}))].flat();function As(e){let t=e.depth;for(;t>=1&&!["doc","amadeusColumnCell"].includes(e.node(t-1).type.name);)t--;return t}function da(e){if(!e)return!1;const t=e.type.name;return t==="code_block"||t==="hr"||t==="horizontal_rule"||t==="table"?!0:No(e)!=null}function uc(e){if(!e)return!1;const t=e.type.name;return t==="hr"||t==="horizontal_rule"?!0:No(e)!=null&&!Es(e)}function Uo(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 Us(e,t)!=null?!0:zm(e).some(n=>t>n.start&&t<n.after)}function Oy(e){let t=0;for(let n=e.depth;n>=1;n--)e.node(n).type.name==="list_item"&&t++;return t}function Fu(e){for(let t=e.depth;t>=1;t--)if(e.node(t).type.name==="blockquote")return t;return null}function sr(...e){return(t,n,o)=>e.some(r=>r(t,n,o))}const Fy=(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(Jr(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(Gr,{toggle:r}),t?.(c.scrollIntoView()),!0},_u=(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),i=e.tr.insert(c,r.create());return i.setSelection(Le.near(i.doc.resolve(c+1))),t?.(i.scrollIntoView()),!0}const s=e.tr.split(n.pos,1,[{type:r}]);return t?.(s.scrollIntoView()),!0},_y=(e,t)=>{const n=e.selection;if(!(n instanceof Se)||!n.node.isTextblock||No(n.node)!=null)return!1;const o=e.tr.setSelection(Le.near(e.doc.resolve(n.to-1),-1));return t?.(o.scrollIntoView()),!0},By=(e,t,n)=>{const{$from:o,empty:r}=e.selection;if(!r||!n||!t)return!1;const s=tf(o);return!s||!nf(o.parent.type.name,s)?!1:of(n,s)},Hy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parent.content.size!==0||Uo(n)==null)return!1;const r=e.schema.nodes.list_item;return r?Yl(r)(e,t):!1},Ky=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o)return!1;const r=Uo(n);if(r==null||r!==n.depth-1||n.node(r).childCount<2||!wc(e,n.before(r)))return!1;const c=e.schema.nodes.list_item,i=e.schema.nodes.paragraph;if(!c||!i)return!1;const a=e.doc.slice(n.pos,n.end()).content,l=c.createAndFill(null,i.create(null,a));if(!l)return!1;let m=e.tr.delete(n.pos,n.end());const g=m.mapping.map(n.after(r));return m=m.insert(g,l),m.setSelection(Le.near(m.doc.resolve(g+2))),t?.(m.scrollIntoView()),!0},Vy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset===0)return!1;const r=Uo(n);if(r==null||r!==n.depth-1)return!1;const s=n.node(r);if(s.childCount<2||wc(e,n.before(r)))return!1;const c=s.child(1);if(!/_list$/.test(c.type.name))return!1;const i=e.schema.nodes.list_item,a=e.schema.nodes.paragraph;if(!i||!a)return!1;const l=n.pos,m=n.end(),g=e.doc.slice(l,m).content,C=n.before(r)+1+s.child(0).nodeSize+1,M=i.createAndFill(null,a.create(null,g));if(!M)return!1;let S=e.tr.delete(l,m);const z=S.mapping.map(C);return S=S.insert(z,M),S.setSelection(Le.near(S.doc.resolve(z+2))),t?.(S.scrollIntoView()),!0},qy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o)return!1;const r=yc(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},Wy=(e,t,n)=>{const{$from:o,empty:r}=e.selection,s=Uo(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 g=c.createAndFill({...o.node(s).attrs,checked:!1});if(!g)return!1;if(!t)return!0;t(e.tr.insert(o.before(s),g).scrollIntoView());const C=n?n.root.getSelection?.():null;if(C&&C.rangeCount){const M=C.getRangeAt(0);C.removeAllRanges(),C.addRange(M)}return!0}if(!t)return Wa(c)(e);let i=null;if(!Wa(c)(e,g=>{i=g}))return!1;const a=i;if(!a)return!1;const l=a.selection.$from,m=Uo(l);return m!=null&&l.node(m).attrs.checked===!0&&a.setNodeMarkup(l.before(m),void 0,{...l.node(m).attrs,checked:!1}),t(a),!0},Yy=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},Bu=(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 Yy(Rm(n.parent)).some(([i,a])=>s>=i+2&&c<=a-2)?(t?.(e.tr.replaceSelectionWith(r.create({isInline:!0}),!1).scrollIntoView()),!0):!1},Uy=sr(Fy,_u,_y,Bu,By,Hy,Ky,Vy,Wy,qy),Xy=(e,t)=>{const{$from:n}=e.selection,o=Uo(n),r=Fu(n);if(o!=null&&(r==null||o>r)&&n.node(o).attrs.checked!=null){const m=Jd(e,n.pos);return m?(t?.(m.scrollIntoView()),!0):!1}if(r!=null){const m=e.schema.nodes.hardbreak;return m?(t?.(e.tr.replaceSelectionWith(m.create(),!1).scrollIntoView()),!0):!1}const s=e.schema.nodes.list_item;if(s&&Uo(n)!=null)return Wa(s)(e,t);const c=e.schema.nodes.paragraph,i=As(n);if(!c||i<1)return!1;const a=n.after(i),l=e.tr.insert(a,c.create());return l.setSelection(Le.near(l.doc.resolve(a+1))),t?.(l.scrollIntoView()),!0},Gy=(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},Jy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=Fu(n);if(r==null)return!1;if(Qd(n.node(r))?.type==="fold"&&ef.getState(e)?.srcAt!==n.before(r)){if(n.depth===r+1){const C=n.before(),M=e.doc.resolve(C).nodeBefore;if(M&&(M.type.name==="blockquote"||da(M))&&Se.isSelectable(M))return t?.(e.tr.setSelection(Se.create(e.doc,C-M.nodeSize)).scrollIntoView()),!0}return!1}if(n.index(r)===0){const C=n.before(r),M=e.doc.nodeAt(C);return!M||!Se.isSelectable(M)?!1:(t?.(e.tr.setSelection(Se.create(e.doc,C))),!0)}const c=n.before(r+1),i=n.after(r+1),a=n.after(r),l=e.doc.nodeAt(c);if(!l)return!1;let m=e.tr.delete(c,i);const g=m.mapping.map(a);return m=m.insert(g,l),m.setSelection(Le.near(m.doc.resolve(g+1))),t?.(m.scrollIntoView()),!0},Zy=(e,t,n)=>{const{$from:o,empty:r}=e.selection;return!r||o.parentOffset!==0||!n||Uo(o)==null?!1:Zd(n)},Qy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=As(n);if(r<1||r!==n.depth)return!1;const s=n.before(r),i=e.doc.resolve(s).nodeBefore;if(!da(i)||!i)return!1;const a=s-i.nodeSize;let l=e.tr;n.parent.content.size===0&&(l=l.delete(s,n.after(r)));const m=l.doc.nodeAt(a);return!m||!Se.isSelectable(m)||fr(e,a)?!1:(l=l.setSelection(Se.create(l.doc,a)),t?.(l.scrollIntoView()),!0)},eb=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=yc(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},dc=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=zu(t,o.before(-1),e);return s?(n?.(s),!0):!1},tb=sr(dc(-1),Gy,Jy,Zy,eb,Qy),nb=(e,t,n)=>{const{$from:o,empty:r}=e.selection;if(!r||o.parentOffset!==0)return!1;if(yc(o)){const i=o.before(o.depth);return t?.(e.tr.setNodeMarkup(i,void 0,{...o.parent.attrs,indent:0}).scrollIntoView()),!0}const c=e.schema.nodes.list_item;if(!c||Uo(o)==null)return!1;if(!t||!n)return!0;for(let i=0;i<32&&!(Oy(n.state.selection.$from)<=1||!Yl(c)(n.state,a=>n.dispatch(a)));i++);return!0},al=(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 Jr(e,r)==null?!1:(t?.(e.tr.setMeta(Gr,{toggle:r})),!0)},cl=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==n.parent.content.size)return!1;const r=As(n);if(r<1)return!1;const s=n.after(r),c=e.doc.resolve(s).nodeAfter;return!c||!da(c)||!Se.isSelectable(c)||fr(e,s)?!1:(t?.(e.tr.setSelection(Se.create(e.doc,s)).scrollIntoView()),!0)},ob=/^\[![\w-]+\]/,il=(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=S=>{for(let z=S.depth;z>0;z--)if(S.node(z).type.name==="table")return!0;return!1};if(r(n))return!1;const s=n.after(),c=Wo.findFrom(e.doc.resolve(s),1,!0);if(!(c instanceof Le))return!1;const i=c.$from;if(i.parentOffset!==0||!i.parent.isTextblock||i.parent.type.name==="code_block"||r(i)||i.depth===n.depth&&i.before()===s||fr(e,i.pos))return!1;const a=S=>{for(let z=S.depth;z>0;z--)if(S.node(z).type.spec.isolating)return S.before(z);return-1};if(a(n)!==a(i))return!1;let l=!1;if(e.doc.nodesBetween(s,i.before(),(S,z)=>(z>=s&&z+S.nodeSize<=i.before()&&(S.isLeaf||S.isTextblock)&&(l=!0),!l)),l)return!1;const m=i.depth>=2&&i.node(-1).type.name==="blockquote"&&i.index(-1)===0?i.before(-1):null;if(m!=null&&ob.test(i.parent.textContent)){const S=e.doc.nodeAt(m);return!S||!Se.isSelectable(S)?!1:(t?.(e.tr.setSelection(Se.create(e.doc,m)).scrollIntoView()),!0)}const g=n.parent.textContent+i.parent.textContent,C=e.tr.delete(n.pos,i.pos),M=C.doc.resolve(C.mapping.map(n.pos));return!M.parent.isTextblock||M.parent.textContent!==g||C.doc.textContent!==e.doc.textContent?!1:(t?.(C.setSelection(Le.create(C.doc,M.pos)).scrollIntoView()),!0)};function ll(e){return(t,n,o)=>{const r=t.selection;if(!r.empty||!o||!o.endOfTextblock(e))return!1;const s=r.$from,c=As(s);if(c<1)return!1;const i=e==="down"?s.after(c):s.before(c),a=e==="down"?t.doc.resolve(i).nodeAfter:t.doc.resolve(i).nodeBefore;if(!uc(a)||!a)return!1;const l=e==="down"?i:i-a.nodeSize,m=t.doc.nodeAt(l);return!m||!Se.isSelectable(m)||fr(t,l)?!1:(n?.(t.tr.setSelection(Se.create(t.doc,l)).scrollIntoView()),!0)}}function _s(e){return(t,n,o)=>{const r=t.selection;if(!(r instanceof Le)||!r.empty||!o)return!1;const s=r.$head;if(!s.parent.isTextblock)return!1;const c=As(s);if(c<1)return!1;const i=e==="down"||e==="right",a=e==="up"||e==="down",l=s.before(c),m=s.node(c),g=s.depth===c&&Es(m),C=Wo.findFrom(t.doc.resolve(i?l+m.nodeSize-1:l+1),i?-1:1,!0);if(!C||C.$head.start()!==s.start())return!1;if(a){if(g&&e==="down")try{const F=o.coordsAtPos(s.pos,s.pos===s.end()?-1:1),U=o.coordsAtPos(s.end(),-1);if(Math.abs(F.top-U.top)>Math.max(2,(F.bottom-F.top)/2))return!1}catch{return!1}else if(!o.endOfTextblock(e))return!1}else if(s.pos!==C.head)return!1;const M=i?l+m.nodeSize:l,S=i?t.doc.resolve(M).nodeAfter:t.doc.resolve(M).nodeBefore,z=S?i?M:M-S.nodeSize:-1,L=s.parentOffset;if(S&&Es(S)){if(fr(t,z))return!1;const F=S.content.size,U=e==="right"?0:e==="left"?F:Math.min(L,F);return n?.(t.tr.setSelection(Le.create(t.doc,z+1+U)).scrollIntoView()),!0}if(!g||!i)return!1;if(!S){const F=s.node(c-1),U=t.schema.nodes.paragraph;if(!U||!F.canReplaceWith(s.index(c-1)+1,s.index(c-1)+1,U))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 de=t.tr.insert(M,U.create());return n(de.setSelection(Le.create(de.doc,M+1)).scrollIntoView()),!0}if(fr(t,z))return!1;if(uc(S)&&Se.isSelectable(S))return n?.(t.tr.setSelection(Se.create(t.doc,z)).scrollIntoView()),!0;let E=S.isTextblock&&!S.type.spec.code?Le.create(t.doc,z+1+(e==="down"?Math.min(L,S.content.size):0)):Wo.findFrom(t.doc.resolve(z),1,!0);return E?(E instanceof Le&&uc(E.$head.parent)&&(E=Se.create(t.doc,E.$head.before())),n?.(t.tr.setSelection(E).scrollIntoView()),!0):!1}}function ul(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 i=r.node(-1);if(r.index(-1)!==i.childCount-1)return!1;const a=t.schema.nodes.paragraph,l=r.after();if(!a||!i.canReplaceWith(r.index(-1)+1,r.index(-1)+1,a))return!1;if(!n)return!0;const m=t.tr.insert(l,a.create());return n(m.setSelection(Le.create(m.doc,l+1)).scrollIntoView()),!0}}const rb=(e,t)=>e.selection.$from.parent.type.name!=="code_block"?!1:(t?.(e.tr.insertText(`
686
+ `).scrollIntoView()),!0);function dl(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 Es(r)?fr(t,s)?!1:(n?.(t.tr.setSelection(Le.create(o,e==="up"?s+1:s+r.nodeSize-1)).scrollIntoView()),!0):No(r)!=null?!Se.isSelectable(r)||fr(t,s)?!1:(n?.(t.tr.setSelection(Se.create(o,s)).scrollIntoView()),!0):r.type.name==="code_block"?(n?.(t.tr.setSelection(Le.create(o,e==="up"?s+1:s+r.nodeSize-1)).scrollIntoView()),!0):!1}}const sb={"(":")","[":"]","{":"}","<":">",'"':'"',"'":"'","`":"`","(":")","【":"】","「":"」","《":"》","“":"”","‘":"’"},ab=Et(e=>new Yt({props:{handleTextInput:(t,n,o,r)=>{const s=sb[r];if(!s||n===o)return!1;const c=t.state.selection;if(!(c instanceof Le)||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(np).call(Gd.key);const i=t.state.tr.insertText(s,o).insertText(r,n);return i.setSelection(Le.create(i.doc,n+1,o+1)),t.dispatch(i.scrollIntoView()),!0}}}));function Ra(e){const t=e.selection;if(!(t instanceof Se)||!t.node.isBlock)return null;const n=t.node,o=e.tr;if(n.type.name==="code_block")return o.setSelection(Le.create(o.doc,t.to-1));if(n.type.name==="table"){const c=Wo.near(o.doc.resolve(t.from+1),1);return!(c instanceof Le)||c.from>=t.to?null:o.setSelection(Le.create(o.doc,c.$from.end()))}if(!da(n)&&!n.isLeaf){const c=Wo.near(o.doc.resolve(t.to-1),-1);if(c instanceof Le&&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(Le.create(o.doc,t.to+1)))}const cb=Et(()=>new Yt({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=Ra(e.state);return o&&e.dispatch(o.scrollIntoView()),!1},compositionstart:e=>{if(!e.editable)return!1;const t=Ra(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=Ra(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}}}})),fl=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),ib=[Py,cb,ab,Et(()=>Ko({Enter:Uy,"Shift-Enter":sr(_u,rb,Bu),"Mod-Enter":Xy,Backspace:tb,"Mod-Backspace":nb,Delete:sr(dc(1),al,cl,il),...fl?{"Ctrl-d":sr(dc(1),al,cl,il)}:{},ArrowUp:sr(_s("up"),ll("up")),ArrowDown:sr(ul("down"),_s("down"),ll("down")),ArrowLeft:_s("left"),ArrowRight:sr(ul("right"),_s("right")),...fl?{"Meta-ArrowUp":dl("up"),"Meta-ArrowDown":dl("down")}:{}}))].flat();Cn({"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 lb(e,t,n,o){const{schema:r}=e,s=r.nodes.paragraph;if(!s)return null;const c=s.create(null,r.text("/"));let i=null;t.type.name==="list_item"?i=n:/_list$/.test(t.type.name)&&t.firstChild?.type.name==="list_item"&&(i=n+1);const a=i==null?null:e.doc.nodeAt(i);if(a&&i!=null){const m={...a.attrs,...a.attrs.checked!=null?{checked:!1}:{}},g=a.type.createAndFill(m,c);if(g){const C=o?i:i+a.nodeSize;return{at:C,node:g,caret:C+3}}}const l=o?n:n+t.nodeSize;return{at:l,node:c,caret:l+2}}function _r(e){const t=e.offsetWidth;if(t<=0)return Mn(e);const n=Mn(e),o=e.getBoundingClientRect().width/t;return Math.abs(o-n)<.01?n:o}function pl(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 Br(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"||pl(r))&&(n=o)}return n?t(n):{x:0,y:0}}for(let n=e.parentElement;n;n=n.parentElement)if(pl(getComputedStyle(n)))return t(n);return{x:0,y:0}}const La=(e,t)=>{if(!t)return!1;const n=t.type.name;return!(n==="amadeusColumnRow"||n==="amadeusColumnCell"||sp(o=>o.type.name==="table"||o.type.name==="blockquote")(e))};function ss(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=i=>{const a=o.depth>=1&&o.index(o.depth)===0&&!["amadeusColumnCell","amadeusCanvasCard"].includes(o.node(o.depth).type.name);if(!(i||a)||o.depth<1)return;const l=o.before(o.depth);r=e.state.doc.nodeAt(l),s=e.nodeDOM(l),o=e.state.doc.resolve(l),La(o,r)||c(!0)};if(c(!La(o,r)),!r||!La(o,r)||!(s instanceof HTMLElement))return null;if(o.depth>=1&&o.node(o.depth).type.name==="amadeusCanvasCard"){const i=o.before(o.depth),a=e.nodeDOM(i);if(a instanceof HTMLElement){const l=a.firstElementChild?.getBoundingClientRect(),m=a.lastElementChild?.getBoundingClientRect();if(l&&t.y<l.top||m&&t.y>m.bottom){const g=e.state.doc.nodeAt(i);if(g)return{node:g,pos:i,el:a}}}}return{node:r,pos:o.pos,el:s}}catch{return null}}function ml(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(Se.isSelectable(o)&&!(o.type.name==="paragraph"&&n>1))return t.before(n)}return null}function ub(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 db(e){let t=null,n=null;const o=new $n("amx-block-selection-mode");let r=null,s=null;const c=h=>(s&&s.isConnected||(s=document.createElement("div"),s.className="unified-drop-vline",s.style.display="none",(h.dom.parentElement??document.body).appendChild(s)),s),i=(h,A,P)=>{const I=c(h),H=_r(h.dom),X=Br(I),ie=A.getBoundingClientRect(),G=(P==="left"?ie.left-6:ie.right+3)-X.x;I.style.display="block",I.style.height=`${ie.height/H}px`,I.style.transform=`translate(${Math.round(G/H)}px, ${Math.round((ie.top-X.y)/H)}px)`},a=()=>{s&&(s.style.display="none")},l=28,m=h=>/Mac/i.test(navigator.platform)?h.altKey:h.ctrlKey,g=h=>{const A=h.state.selection;if(!(A instanceof Le)||A.empty||A.$from.sameParent(A.$to))return null;const P=X=>{let ie=X.depth;for(;ie>=1&&!["doc","amadeusColumnCell"].includes(X.node(ie-1).type.name);)ie--;return ie},I=P(A.$from),H=P(A.$to);return I<1||H<1||A.$from.node(I-1)!==A.$to.node(H-1)?null:{from:A.$from.before(I),to:A.$to.after(H)}},C=(h,A,P)=>{if(P.type.name!=="paragraph")return null;const I=h.state.doc.resolve(A),H=I.parent;if(!["doc","amadeusColumnCell"].includes(H.type.name))return null;const X=Number(P.attrs.indent??0),ie=I.index();let G=A+P.nodeSize,oe=0;for(let V=ie+1;V<H.childCount;V++){const ze=H.child(V);if(ze.type.name!=="paragraph"||Number(ze.attrs.indent??0)<=X)break;G+=ze.nodeSize,oe++}return oe?{from:A,to:G}:null};let M=null;const S=(h,A,P,I,H)=>{Vr(h,A,{from:P.from,to:P.to,newStart:I,copy:H}),ns(h,A,{from:P.from,to:P.to,newStart:I}),M===P.from&&A.doc.nodeAt(I)?.type.name==="heading"&&(A.setSelection(Se.create(A.doc,I)),M=null)},z=(h,A)=>{const{state:P}=h,I=P.doc.content.size,H=g(h);if(H){if(!A&&H.to===I)return!0;let V=P.doc.slice(H.from,H.to).content;if(A){const Ve=rs(P.doc,V);V=Ve.content,Ve.minted.length&&e.onCardsMinted?.(Ve.minted)}let ze=P.tr;A||(ze=ze.delete(H.from,H.to));const Ke=ze.mapping.map(I);return ze=ze.insert(Ke,V),S(P,ze,H,Ke,A),ze.setMeta("amxColumns",!0),h.dispatch(ze.scrollIntoView()),!0}const X=P.selection;if(!(X instanceof Se))return!1;if(!A&&X.to===I)return!0;const ie=X.node,G=ie.type.name==="list_item"?X.$from.parent.type.create(X.$from.parent.attrs,ie):ie;let oe=P.tr;return A||(oe=oe.delete(X.from,X.to)),oe=oe.insert(oe.mapping.map(I),G),oe.setMeta("amxColumns",!0),h.dispatch(oe.scrollIntoView()),!0},L=(h,A,P)=>{const I=g(h);if(!I)return!1;const H=ne(h,A.clientY);if(!H)return!1;const X=H.el.getBoundingClientRect(),ie=A.clientY>X.top+X.height/2?H.pos+H.node.nodeSize:H.pos;if(ie>=I.from&&ie<=I.to)return!0;let G=h.state.doc.slice(I.from,I.to).content;if(P){const ze=rs(h.state.doc,G);G=ze.content,ze.minted.length&&e.onCardsMinted?.(ze.minted)}ht(h,ie);let oe=h.state.tr;P||(oe=oe.delete(I.from,I.to));const V=oe.mapping.map(ie);return oe=oe.insert(V,G),S(h.state,oe,I,V,P),oe.setMeta("amxColumns",!0),h.dispatch(oe.scrollIntoView()),!0},E=(h,A,P)=>{const{state:I}=h,H=I.selection;if(!(H instanceof Se))return!1;const X=I.doc.nodeAt(A);if(!X||X.type.name!=="list_item"||A>=H.from&&A<H.to)return!1;const ie=I.schema.nodes.list_item,G=I.schema.nodes.bullet_list;if(!ie||!G)return!1;const oe=H.node;if(oe.type.name==="amadeusColumnRow"||oe.type.name==="amadeusColumnCell")return!1;const V=oe.type.name==="list_item"?oe:ie.createAndFill(null,oe);if(!V)return!1;const ze=X.child(X.childCount-1),Ke=X.childCount>1&&/_list$/.test(ze.type.name);let Ve=I.tr;P||(Ve=Ve.delete(H.from,H.to));const Be=Ve.mapping.map(A),We=Ve.doc.nodeAt(Be);if(!We||We.type.name!=="list_item")return!1;const Qe=Ke?Be+We.nodeSize-2:Be+We.nodeSize-1;return Ve=Ve.insert(Qe,Ke?V:(ze.type.name.endsWith("_list")?ze.type:G).create(null,V)),Ve.setMeta("amxColumns",!0),h.dispatch(Ve.scrollIntoView()),!0},F=h=>!!h.dom.closest(".unified-body")?.classList.contains("amx-canvas"),U=(h,A,P,I)=>{let H=P;for(let X=0;X<A.childCount;X++){const ie=A.child(X),G=h.nodeDOM(H),oe=G instanceof HTMLElement?G.getBoundingClientRect():null;if(oe&&I.clientY<=oe.bottom)return I.clientY>oe.top+oe.height/2?H+ie.nodeSize:H;H+=ie.nodeSize}return H},q=(h,A)=>{const P=h.state.doc,I=h.state.schema.nodes.amadeusCanvasCard;let H=0;for(let X=0;X<P.childCount;X++){const ie=P.child(X);if(ie.type===I)return H;const G=h.nodeDOM(H),oe=G instanceof HTMLElement?G.getBoundingClientRect():null;if(oe&&A.clientY<=oe.bottom)return A.clientY>oe.top+oe.height/2?H+ie.nodeSize:H;H+=ie.nodeSize}return H},de=(h,A,P)=>{const I=h.state.selection;if(!(I instanceof Se))return!1;const H=h.state.schema.nodes.amadeusCanvasCard;if(!H)return!1;const X=A.target;if(!X||!h.dom.contains(X))return!1;if(I.node.type===H)return!0;const ie=X.closest?.(".amx-ucard");let G;if(ie){let V;try{V=h.posAtDOM(ie,0)-1}catch{return!1}const ze=h.state.doc.nodeAt(V);if(ze?.type!==H)return!1;G=U(h,ze,V+1,A)}else G=q(h,A);if(G>=I.from&&G<=I.to)return!0;let oe=h.state.tr;return P||(oe=oe.delete(I.from,I.to)),oe=oe.insert(oe.mapping.map(G),I.node),oe.setMeta("amxColumns",!0),h.dispatch(oe.scrollIntoView()),!0},me=h=>{const A=h.state.schema.nodes.amadeusCanvasCard,P=[];return A&&h.state.doc.forEach((I,H,X)=>{I.type===A&&P.push({anchor:String(I.attrs.anchor),idx:X,pos:H,size:I.nodeSize})}),P},Ne=(h,A)=>{const P=h.state.doc,I=h.state.schema.nodes.amadeusCanvasCard;if(!I)return null;const H=e.canvasTree?.()??{},X=me(h),ie=new Map;for(let Be=0;Be<X.length;){const We=oa(X,Be,H);ie.set(Be,We),Be=We}const G=Be=>{const We=h.nodeDOM(Be);return We instanceof HTMLElement?We:null},oe=[];let V=0,ze=0,Ke=-1;for(let Be=0;Be<P.childCount;Be++){const We=P.child(Be);if(V<Ke){We.type===I&&ze++,V+=We.nodeSize;continue}if(We.type===I){const Qe=ie.get(ze);if(Qe!=null){const Xe=X[Qe-1];oe.push({from:V,to:Xe.pos+Xe.size,firstEl:G(V),lastEl:G(Xe.pos)})}ze++}else{let Qe=V+We.nodeSize,Xe;if(We.type.name==="heading"&&kr(h,V)==="folded"){const st=Jr(h.state,V);st!=null&&(Qe=st,Ke=st,Xe=V)}oe.push({from:V,to:Qe,firstEl:G(V),lastEl:G(V),foldPos:Xe})}V+=We.nodeSize}let Ve=null;for(let Be=0;Be<oe.length;Be++){const We=oe[Be];if(!We.firstEl||!We.lastEl)continue;const Qe=We.firstEl.getBoundingClientRect().top,Xe=We.lastEl.getBoundingClientRect().bottom;if(Ve={at:We.to,lineEl:We.lastEl,edge:"bottom",expandFold:We.foldPos},A.clientY>Xe)continue;const st=Be>0?oe[Be-1]:null;return A.clientY<=(Qe+Xe)/2?{at:We.from,lineEl:We.firstEl,edge:"top",expandFold:st&&st.foldPos!=null&&st.to===We.from?st.foldPos:void 0}:Ve}return Ve},be=(h,A)=>{const P=h.state.selection,I=h.state.schema.nodes.amadeusCanvasCard;if(!I||!(P instanceof Se)||P.node.type!==I)return null;const H=Ne(h,A);if(!H)return null;const X=e.canvasTree?.()??{},ie=me(h),G=ie.findIndex(ze=>ze.pos===P.from);if(G<0)return null;const oe=ie[oa(ie,G,X)-1],V={from:P.from,to:oe.pos+oe.size};return{drop:H,range:V,self:H.at>=V.from&&H.at<=V.to}},ge=(h,A,P)=>{const I=h.state.selection,H=h.state.schema.nodes.amadeusCanvasCard;if(!H||!(I instanceof Se)||I.node.type!==H)return!1;const X=be(h,A);if(!X||X.self)return!0;let ie=h.state.doc.slice(X.range.from,X.range.to).content;if(P){const oe=rs(h.state.doc,ie);ie=oe.content,oe.minted.length&&e.onCardsMinted?.(oe.minted)}X.drop.expandFold!=null&&kr(h,X.drop.expandFold)==="folded"&&Ps(h,X.drop.expandFold);let G=h.state.tr;if(P||(G=G.delete(X.range.from,X.range.to)),G=G.insert(G.mapping.map(X.drop.at),ie),G.setMeta("amxColumns",!0),h.dispatch(G.scrollIntoView()),!P){const oe=String(I.node.attrs.anchor),ze=(e.canvasTree?.()??{})[oe];typeof ze=="string"&&me(h).some(Ke=>Ke.anchor===ze)&&e.onCardDetach?.([oe])}return!0};let p=null,fe=null,ce=null,te=null,ee=!1,Ie=!1,Me=null;const dt=h=>(Me&&Me.isConnected||(Me=document.createElement("div"),Me.className="unified-drop-line",Me.style.display="none",Me.style.animation="none",(h.dom.parentElement??document.body).appendChild(Me)),Me),tt=(h,A,P=0,I="bottom")=>{const H=dt(h),X=_r(h.dom),ie=Br(H),G=A.getBoundingClientRect(),oe=I==="top"?G.top-6:G.bottom+6;H.style.display="block",H.style.width=`${Math.max(0,G.width-P)/X}px`,H.style.transform=`translate(${Math.round((G.left+P-ie.x)/X)}px, ${Math.round((oe-ie.y)/X)}px)`},J=()=>{Me&&(Me.style.display="none")},ye=(h,A)=>{const P=h.state.doc.resolve(A);if(P.depth===0)return h.state.doc.nodeAt(A)?.type.name!=="amadeusCanvasCard";for(let I=P.depth;I>=1;I--)if(P.node(I).type.name==="amadeusColumnRow")return I===1;return!1},Ae=h=>h instanceof HTMLElement&&h.getClientRects().length>0,j=(h,A)=>{if(F(h))return null;const P=h.state.selection,I=P instanceof Se?{from:P.from,to:P.to}:g(h);if(!I)return null;const H=A.target instanceof Element?A.target.closest("blockquote"):null;if(!(H instanceof HTMLElement)||!h.dom.contains(H))return null;let X;try{X=h.posAtDOM(H,0)-1}catch{return null}const ie=h.state.doc.nodeAt(X);if(ie?.type.name!=="blockquote"||h.nodeDOM(X)!==H)return null;const G=h.state.doc.slice(I.from,I.to).content;let oe=!1;if(G.descendants(Be=>{["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell"].includes(Be.type.name)&&(oe=!0)}),oe)return null;const V=!!ie.firstChild?.isTextblock&&/^\[![\w-]+\]/.test(ie.firstChild.textContent),ze=h.nodeDOM(X+1);if(V&&Ae(ze)){const Be=ze.getBoundingClientRect();if(A.clientY<Be.top+Be.height/2)return null}let Ke=null;if(ie.forEach((Be,We)=>{const Qe=X+1+We,Xe=h.nodeDOM(Qe);if(!Ae(Xe))return;const st=Xe.getBoundingClientRect(),Xt=A.clientY<st.top+st.height/2?"top":"bottom",Dt=Math.abs(A.clientY-(Xt==="top"?st.top:st.bottom));(!Ke||Dt<Ke.distance)&&(Ke={at:Xt==="top"?Qe:Qe+Be.nodeSize,lineEl:Xe,edge:Xt,distance:Dt})}),!Ke)return null;const Ve=Ke;return{...Ve,self:Ve.at>=I.from&&Ve.at<=I.to}},W=(h,A,P)=>{const I=j(h,A);if(!I)return!1;if(I.self)return!0;const{state:H}=h,X=H.selection,ie=X instanceof Se?{from:X.from,to:X.to}:g(h);if(!ie)return!1;const G=X instanceof Se&&X.node.type.name==="list_item"?To.from(X.$from.parent.type.create(X.$from.parent.attrs,X.node)):H.doc.slice(ie.from,ie.to).content,oe=P?H.tr:H.tr.delete(ie.from,ie.to),V=oe.mapping.map(I.at),ze=oe.doc.resolve(V);return ze.parent.type.name!=="blockquote"||!ze.parent.canReplace(ze.index(),ze.index(),G)?!1:(oe.insert(V,G),S(H,oe,ie,V,P),Qs(oe,V,V+G.size),oe.setSelection(G.childCount===1&&Se.isSelectable(G.firstChild)?Se.create(oe.doc,V):Le.between(oe.doc.resolve(V),oe.doc.resolve(V+G.size))),oe.setMeta("amxColumns",!0).setMeta("uiEvent","drop"),h.dispatch(oe.scrollIntoView()),h.focus(),!0)},ne=(h,A)=>{const P=h.state.doc;let I=null,H=1/0;for(let X=0,ie=0;X<P.childCount;ie+=P.child(X).nodeSize,X++){const G=h.nodeDOM(ie);if(!Ae(G))continue;const oe=G.getBoundingClientRect(),V=A<oe.top?oe.top-A:A>oe.bottom?A-oe.bottom:0;if(V===0)return{pos:ie,node:P.child(X),el:G};V<H&&(H=V,I={pos:ie,node:P.child(X),el:G})}return I},he=(h,A)=>{const P=h.state.selection,I=m(A),H=X=>!I&&P instanceof Se&&X>=P.from&&X<=P.to;for(const X of h.dom.querySelectorAll(":scope > .amx-ucolrow")){const ie=X.getBoundingClientRect();if(!(A.clientY<ie.top||A.clientY>ie.bottom||A.clientX<ie.left||A.clientX>ie.right)){for(const G of Array.from(X.children)){if(!Ae(G)||!("amxColcell"in G.dataset))continue;const oe=G.getBoundingClientRect();if(!(A.clientX<oe.left||A.clientX>oe.right))try{const V=h.posAtDOM(G,0)-1,ze=h.state.doc.nodeAt(V);if(ze?.type.name!=="amadeusColumnCell")return null;let Ke=V+1,Ve=null;for(let Be=0;Be<ze.childCount;Be++){const We=ze.child(Be),Qe=h.nodeDOM(Ke);if(Ae(Qe)){const Xe=Qe.getBoundingClientRect();if(A.clientY<=Xe.bottom){if(A.clientY>=Xe.top&&(!We.isTextblock&&!We.isAtom||A.clientX<=Xe.left+l||A.clientX>=Xe.right-l))return null;const st=A.clientY<=Xe.top+Xe.height/2,Xt=st?Ke:Ke+We.nodeSize;return{cellEl:G,lineEl:Qe,pos:Ke,edge:st?"top":"bottom",tail:!1,self:H(Xt)}}Ve=Qe}Ke+=We.nodeSize}return Ve?{cellEl:G,lineEl:Ve,pos:V,edge:"bottom",tail:!0,self:H(V+ze.nodeSize-1)}:null}catch{return null}}return null}}return null},qe=(h,A)=>{if(!A.cellEl.isConnected||!A.lineEl.isConnected)return null;try{if(A.tail){const H=h.posAtDOM(A.cellEl,0)-1,X=h.state.doc.nodeAt(H);return X?.type.name==="amadeusColumnCell"?H+X.nodeSize-1:null}const P=h.state.doc.nodeAt(A.pos);if(!P||h.nodeDOM(A.pos)!==A.lineEl)return null;const I=A.edge==="top"?A.pos:A.pos+P.nodeSize;return h.state.doc.resolve(I).parent.type.name==="amadeusColumnCell"?I:null}catch{return null}},et=(h,A)=>{try{const P=h.state.doc.resolve(A),I=P.parent;let H=P.start();for(let X=0;X<I.childCount&&H<A;X++){const ie=I.child(X);if(ie.type.name==="heading"&&kr(h,H)==="folded"){const G=Jr(h.state,H);if(G!=null&&A>H&&A<=G)return H}H+=ie.nodeSize}}catch{}return null},ht=(h,A)=>{for(let P=et(h,A),I=-1;P!=null&&P!==I;I=P,P=et(h,A))Ps(h,P)};let Ye=null;const Ht=()=>{Ye&&(Ye.style.display="none")};let Ot=!1,Kt=!1;const Ut=()=>{Kt||(Kt=!0,Ot=!1,queueMicrotask(()=>{Kt=!1,Ot||Ht()}))},Ze=Et(()=>new Yt({key:new $n("UNIFIED_BLOCK_HANDLE"),view:h=>{t=h,Ri.add(h);const A=h.dom.parentElement??document.body,P=A.closest(".unified-body")??A,I=R=>{for(const O of P.querySelectorAll(".amx-ucard.amx-droptarget"))O.classList.remove("amx-droptarget");R?.classList.add("amx-droptarget")},H=document.createElement("div");H.className="unified-gutter",H.dataset.show="false";const X=()=>{H.dataset.show="false",n=null},ie=R=>{if(!h.editable)return;n=R,Dt(R),Ue.style.display=Ln(R)?"":"none";const O=_r(h.dom),pe=Br(H),ve=Li(R.el),$e=ve.getBoundingClientRect(),Q=(R.el.tagName==="LI"&&/^(UL|OL)$/.test(R.el.parentElement?.tagName??"")?R.el.parentElement:null)?.getBoundingClientRect().left??$e.left,nt=getComputedStyle(ve),at=Number.parseFloat(nt.lineHeight)||24,gt=(Number.parseFloat(nt.paddingTop)||0)+Math.max(0,(at-24)/2),yt=$e.height/O,jt=Math.max(24,yt-16),At=jt>24?jt/2-4-gt:0;H.dataset.show="true",H.style.setProperty("--amx-block-h",`${yt}px`),H.style.setProperty("--amx-block-grow-y",`${At}px`);const sn=H.offsetWidth||52;H.style.top=`${($e.top-pe.y)/O+gt}px`;let Rt=(Q-pe.x)/O-sn-8;Wr()&&(Rt=Math.max(Rt,(2-pe.x)/O-G.offsetLeft)),H.style.left=`${Rt}px`},G=document.createElement("button");G.type="button",G.className="drag-handle",G.textContent="⠿",G.draggable=!0,G.title=je("blocklayer.dragHandle"),G.setAttribute("aria-label",G.title),G.addEventListener("click",R=>{R.stopPropagation();const O=G.getBoundingClientRect();if(R.detail===0&&t&&n){const pe=t.state.selection;pe instanceof Se&&pe.from<=n.pos&&n.pos+n.node.nodeSize<=pe.to||oe(t,n)}e.onMenu({x:O.left,y:O.bottom+4,keyboard:R.detail===0}),Wr()||t?.focus()}),H.addEventListener("mousedown",()=>{t&&n&&oe(t,n)});const oe=(R,O)=>{const pe=R.state.selection,ve=O.pos+1,$e=O.pos+O.node.nodeSize-1;if(pe instanceof Le&&!pe.empty&&!pe.$from.sameParent(pe.$to)&&pe.from<=ve&&pe.to>=$e){R.focus();return}const Re=C(R,O.pos,O.node);if(Re){const Q=R.state.doc;R.dispatch(R.state.tr.setSelection(Le.between(Q.resolve(Re.from+1),Q.resolve(Re.to-1))).setMeta(o,!0)),R.focus();return}Se.isSelectable(O.node)&&(R.dispatch(R.state.tr.setSelection(Se.create(R.state.doc,O.pos))),R.focus())};let V=null;const ze=()=>{const R=t,O=n;if(!R||!O)return;(!V||!V.isConnected)&&(V=document.createElement("div"),V.className="unified-press-rect",(R.dom.parentElement??document.body).appendChild(V));const pe=_r(R.dom),ve=Br(V),$e=Li(O.el).getBoundingClientRect(),Re=g(R);let Q={left:$e.left-ve.x,top:$e.top-ve.y,right:$e.right-ve.x,bottom:$e.bottom-ve.y};if(Re)for(const nt of Array.from(R.dom.children)){if(!nt.classList.contains("amx-block-selected"))continue;const at=nt.getBoundingClientRect();Q={left:Math.min(Q.left,at.left-ve.x),top:Math.min(Q.top,at.top-ve.y),right:Math.max(Q.right,at.right-ve.x),bottom:Math.max(Q.bottom,at.bottom-ve.y)}}Object.assign(V.style,{display:"block",transform:`translate(${Math.round((Q.left-4)/pe)}px, ${Math.round((Q.top-4)/pe)}px)`,width:`${(Q.right-Q.left+8)/pe}px`,height:`${(Q.bottom-Q.top+8)/pe}px`})},Ke=()=>{V&&(V.style.display="none")};H.addEventListener("mousedown",ze),window.addEventListener("mouseup",Ke);const Ve=(R,O,pe)=>{R.dom.dataset.dragging="true";let ve=R.state.selection;if(M=null,ve instanceof Se&&kr(R,ve.from)==="folded"){const Re=ve.from,Q=Jr(R.state,Re),nt=R.state.doc;if(Q!=null){R.dispatch(R.state.tr.setSelection(Le.between(nt.resolve(Re+1),nt.resolve(Q-1))).setMeta(o,!0));const at=g(R);at&&at.from===Re&&at.to===Q?M=Re:R.dispatch(R.state.tr.setSelection(Se.create(R.state.doc,Re)))}M==null&&Ps(R,Re),ve=R.state.selection}ve instanceof Se&&Os(R,ve.from)==="folded"&&Ca(R,ve.from);const $e=ve instanceof Le&&!ve.empty&&!ve.$from.sameParent(ve.$to);if(O.dataTransfer&&(ve instanceof Se||$e)){const Re=ve.content();O.dataTransfer.effectAllowed="copyMove";const{dom:Q,text:nt}=R.serializeForClipboard(Re);O.dataTransfer.clearData(),O.dataTransfer.setData("text/html",Q.innerHTML),O.dataTransfer.setData("text/plain",nt),pe&&O.dataTransfer.setDragImage(pe,0,0),R.dragging={slice:Re,move:!0}}};H.addEventListener("dragstart",R=>{t&&Ve(t,R,n?.el??null)});const Be=R=>{const O=t;if(!O||!(R.target instanceof Node)||!O.dom.contains(R.target)||!R.target.closest?.(".wiki-inline-img-wrap"))return;const pe=Lm(R.target);let ve=-1;try{pe&&(ve=O.posAtDOM(pe,0)-1)}catch{}const $e=pe?.querySelector(":scope > .wiki-inline-img-wrap")?.getBoundingClientRect(),Re=$e?ss(O,{x:$e.left+$e.width/2,y:$e.top+$e.height/2}):null;if(!pe||!R.dataTransfer||O.nodeDOM(ve)!==pe||!Re||ve<Re.pos||ve>=Re.pos+Re.node.nodeSize){R.preventDefault();return}R.stopPropagation(),oe(O,Re),Ve(O,R,null),R.target.addEventListener("dragend",We,{once:!0})};P.addEventListener("dragstart",Be,!0);const We=()=>{const R=t;if(R&&M!=null){const O=g(R);O&&O.from===M&&R.state.doc.nodeAt(M)?.type.name==="heading"&&R.dispatch(R.state.tr.setSelection(Se.create(R.state.doc,M))),M=null}Ke(),I(null),r=null,ce=null,te=null,fe=null,Ie=!1,ee=!1,a(),J(),Ht(),R&&(R.dom.dataset.dragging="false",R.dragging=null)};H.addEventListener("dragend",We);const Qe=document.createElement("button");Qe.type="button",Qe.className="block-add block-fold",Qe.textContent="▾",Qe.style.display="none";const Xe=R=>{const O=t;return O?Os(O,R.pos)?R.pos:/_list$/.test(R.node.type.name)&&Os(O,R.pos+1)?R.pos+1:null:null},st=R=>{const O=t;return O?kr(O,R.pos)?R.pos:!R.node.isTextblock&&R.node.childCount>0&&kr(O,R.pos+1)?R.pos+1:null:null},Xt=R=>!t||!R?null:st(R)!=null?"heading":Xe(R)!=null?"list":null,Dt=R=>{const O=t,pe=Xt(R),ve=R?Xe(R):null,$e=R?st(R):null,Re=!O||!R||!pe?null:pe==="heading"?$e==null?null:kr(O,$e):ve==null?null:Os(O,ve);Qe.style.display=Re?"":"none",Qe.textContent=Re==="folded"?"▸":"▾",Qe.title=pe==="list"?Re==="folded"?je("blocklayer.expandChildren"):je("blocklayer.foldChildren"):Re==="folded"?je("blocklayer.expandSection"):je("blocklayer.foldSection"),Qe.setAttribute("aria-label",Qe.title),Qe.setAttribute("aria-expanded",String(Re!=="folded"))};Qe.addEventListener("click",R=>{R.stopPropagation();const O=t,pe=n;if(!O||!pe)return;const ve=Xt(pe)==="list"?Xe(pe):null;if(ve!=null)Ca(O,ve);else{const $e=st(pe);if($e==null)return;Ps(O,$e)}Dt(pe)});const zt=document.createElement("button");zt.type="button",zt.className="block-add",zt.textContent="+",zt.title=je("blocklayer.addBelow"),zt.setAttribute("aria-label",zt.title),zt.addEventListener("click",R=>{R.stopPropagation();const O=t,pe=n;if(!O||!pe)return;const ve=lb(O.state,pe.node,pe.pos,R.altKey);if(!ve)return;O.focus();let $e=O.state.tr.insert(ve.at,ve.node);$e=$e.setSelection(Le.create($e.doc,ve.caret)).scrollIntoView(),rf(O,ve.caret),O.dispatch($e),X()});const Ue=document.createElement("button");Ue.type="button",Ue.className="card-grab",Ue.textContent="❏",Ue.draggable=!0,Ue.title=je("blocklayer.cardGrab"),Ue.setAttribute("aria-label",Ue.title),Ue.style.display="none";const Ln=R=>{const O=t;if(!O||!R||R.node.type.name==="amadeusCanvasCard")return null;try{const pe=O.state.doc.resolve(R.pos);for(let ve=pe.depth;ve>=1;ve--){if(pe.node(ve).type.name!=="amadeusCanvasCard")continue;const $e=pe.before(ve),Re=O.state.doc.nodeAt($e),Q=O.nodeDOM($e);return Re&&Q instanceof HTMLElement?{node:Re,pos:$e,el:Q}:null}}catch{}return null};Ue.addEventListener("mousedown",R=>{const O=t,pe=Ln(n);!O||!pe||(R.stopPropagation(),n=pe,O.dispatch(O.state.tr.setSelection(Se.create(O.state.doc,pe.pos))),O.focus(),ze())}),Ue.addEventListener("click",R=>{if(R.stopPropagation(),!n)return;const O=Ue.getBoundingClientRect();e.onMenu({x:O.left,y:O.bottom+4,keyboard:R.detail===0}),Wr()||t?.focus()}),H.append(Ue,G,zt,Qe);let Ft=null,ln=null,io=null;const lo=()=>{const R=[];for(const O of Array.from(h.dom.children))if(O.classList.contains("amx-ucolrow"))for(const pe of Array.from(O.querySelectorAll(".amx-ucolcell")))R.push(...Array.from(pe.children));else R.push(O);return R},Zo=(R,O,pe)=>{const ve=R.getBoundingClientRect();if(O<ve.left||O>ve.right||pe<ve.top||pe>ve.bottom)return!1;if(R.matches("hr, table, pre, .amx-ucard"))return!0;const $e=Q=>O>=Q.left-2&&O<=Q.right+2&&pe>=Q.top-2&&pe<=Q.bottom+2;for(const Q of R.querySelectorAll(".unified-embed, .wiki-inline-img-wrap, .wikilink, img, video, iframe, canvas"))if($e(Q.getBoundingClientRect()))return!0;const Re=document.createTreeWalker(R,NodeFilter.SHOW_TEXT);for(let Q=Re.nextNode();Q;Q=Re.nextNode()){if(!Q.textContent?.length)continue;const nt=document.createRange();nt.selectNodeContents(Q);const at=nt.getClientRects();if(!at.length)continue;const Tt=Q.parentElement,gt=Tt?parseFloat(getComputedStyle(Tt).lineHeight)*Mn(Tt):NaN;for(const yt of at){const jt=Math.max(2,(gt-yt.height)/2||0);if(O>=yt.left-2&&pe>=yt.top-jt&&pe<=yt.bottom+jt)return!0}}return!1},_n=R=>{if(window.removeEventListener("mouseup",Bn),R.button!==0||P.classList.contains("amx-canvas"))return;const O=R.target;if(!O||O.closest(".unified-gutter")||O.closest(".amx-embed")||O.closest("button, input, textarea, a")||!h.editable)return;if(R.pointerType==="touch")return Qo();const pe=lo();if(pe.some(Re=>Zo(Re,R.clientX,R.clientY)))return Qo();const ve=O.closest('li[data-item-type="task"]');if(ve&&R.clientX-ve.getBoundingClientRect().left<=2)return;if(pe.some(Re=>{const Q=Re.getBoundingClientRect();return R.clientX>=Q.left&&R.clientX<=Q.right&&R.clientY>=Q.top&&R.clientY<=Q.bottom})){io={x:R.clientX,y:R.clientY},window.addEventListener("pointermove",Lo),window.addEventListener("pointerup",ko,{once:!0});return}R.preventDefault(),mr(R.clientX,R.clientY)},mr=(R,O)=>{ln={x:R,y:O},Ft=document.createElement("div"),Ft.className="amx-marquee",document.body.appendChild(Ft),document.body.classList.add("amx-marquee-active"),window.addEventListener("pointermove",Gn),window.addEventListener("pointerup",So,{once:!0})},Ro=()=>{io=null,window.removeEventListener("pointermove",Lo),window.removeEventListener("pointerup",ko)},Qo=()=>window.addEventListener("mouseup",Bn,{once:!0}),ko=()=>{Ro(),Qo()},Bn=()=>{h.isDestroyed||h.domObserver?.flush?.()},Lo=R=>{const O=io;!O||Math.abs(R.clientX-O.x)<=4&&Math.abs(R.clientY-O.y)<=4||(Ro(),mr(O.x,O.y),Qn=!0,window.addEventListener("dragstart",Hn,!0),window.addEventListener("selectionchange",Hn,!0),Gn(R))};let Qn=!1;const Hn=R=>{R.type==="dragstart"?R.preventDefault():R.stopImmediatePropagation()},hr=()=>{if(!Qn)return;Qn=!1,window.removeEventListener("dragstart",Hn,!0);let R=!1;const O=()=>{if(R)return;R=!0,window.removeEventListener("mouseup",pe,!0),clearTimeout(ve);const $e=t;$e&&!$e.isDestroyed&&$e.focus(),Qn||window.removeEventListener("selectionchange",Hn,!0)},pe=()=>{setTimeout(O,0)},ve=setTimeout(O,300);window.addEventListener("mouseup",pe,{capture:!0,once:!0})},Gn=R=>{if(!Ft||!ln)return;const O=Math.min(ln.x,R.clientX),pe=Math.min(ln.y,R.clientY),ve=Math.abs(R.clientX-ln.x),$e=Math.abs(R.clientY-ln.y),Re=Mn(Ft);Object.assign(Ft.style,{left:`${O/Re}px`,top:`${pe/Re}px`,width:`${ve/Re}px`,height:`${$e/Re}px`});const Q=[],nt=[];for(const At of lo()){const sn=At.getBoundingClientRect();if(!(sn.bottom<pe||sn.top>pe+$e||sn.right<O||sn.left>O+ve))try{Q.push(h.posAtDOM(At,0)),nt.push(At)}catch{}}if(!Q.length)return;const at=h.state.doc;if(nt.length===1){const At=nt[0];try{const sn=Array.prototype.indexOf.call(At.parentNode?.childNodes,At),Rt=h.posAtDOM(At.parentNode,sn),Kn=at.nodeAt(Rt);if(Kn&&Se.isSelectable(Kn)){const Po=Se.create(at,Rt);Po.eq(h.state.selection)||h.dispatch(h.state.tr.setSelection(Po));return}}catch{}}const Tt=Math.min(...Q),gt=nt[nt.length-1];if(!gt)return;let yt=Tt;try{const At=h.posAtDOM(gt,0),sn=h.state.doc.nodeAt(At-1);yt=sn?At+sn.content.size:At}catch{}const jt=Le.between(at.resolve(Math.min(Tt,at.content.size)),at.resolve(Math.min(yt,at.content.size)));(!jt.eq(h.state.selection)||!o.getState(h.state))&&h.dispatch(h.state.tr.setSelection(jt).setMeta(o,!0))},So=R=>{window.removeEventListener("pointermove",Gn),hr();const O=!!(R&&ln&&(Math.abs(R.clientX-ln.x)>4||Math.abs(R.clientY-ln.y)>4)),pe=ln;if(Ft?.remove(),Ft=null,ln=null,document.body.classList.remove("amx-marquee-active"),O){h.focus();return}if(!pe||!R)return;const ve=h.dom.getBoundingClientRect(),$e=Math.min(Math.max(R.clientX,ve.left+8),ve.right-8);let Re=h.posAtCoords({left:$e,top:R.clientY});if(Re&&!h.state.doc.resolve(Re.pos).parent.isTextblock){let at=null,Tt=1/0;for(const gt of lo()){const yt=gt.getBoundingClientRect(),jt=Math.hypot(Math.max(yt.left-R.clientX,0,R.clientX-yt.right),Math.max(yt.top-R.clientY,0,R.clientY-yt.bottom));jt<Tt&&(Tt=jt,at=yt)}at&&(Re=h.posAtCoords({left:Math.min(Math.max(R.clientX,at.left+1),at.right-1),top:Math.min(Math.max(R.clientY,at.top+1),at.bottom-1)}))}if(!Re)return;const Q=h.state.doc.resolve(Re.pos);if(!Q.parent.isTextblock)return;const nt=R.clientX<ve.left+ve.width/2?Q.start():Q.end();h.dispatch(h.state.tr.setSelection(Le.near(h.state.doc.resolve(nt)))),h.focus()};P.addEventListener("pointerdown",_n),A.appendChild(H);let uo=0,qn=null;const er=R=>{if(H.contains(R.target)){qn&&clearTimeout(qn),qn=null;return}const O=Date.now();if(O-uo<80){const{clientX:pe,clientY:ve}=R;qn&&clearTimeout(qn),qn=setTimeout(()=>{qn=null,uo=Date.now(),Do(pe,ve)},80);return}uo=O,Do(R.clientX,R.clientY)},Do=(R,O)=>{const pe={clientX:R,clientY:O};if(h.dom.dataset.dragging==="true")return;let ve=ss(h,{x:pe.clientX,y:pe.clientY});if(!ve){const $e=h.dom.getBoundingClientRect();if(pe.clientY>=$e.top&&pe.clientY<=$e.bottom&&(pe.clientX<$e.left+8||pe.clientX>$e.right-8)){const Re=Math.min(Math.max(pe.clientX,$e.left+8),$e.right-8);ve=ss(h,{x:Re,y:pe.clientY})}}ve&&ie(ve)};P.addEventListener("mousemove",er,{passive:!0});const gr=R=>{const O=R.relatedTarget;O&&(H.contains(O)||P.contains(O))||X()};P.addEventListener("mouseleave",gr);const xr=()=>{h.dom.dataset.dragging!=="true"&&X()};h.dom.addEventListener("keydown",xr);const Co=R=>{const O=t;if(!O||!O.editable)return;const pe=O.state.selection,ve=pe instanceof Se?{from:pe.from,to:pe.to}:o.getState(O.state)?g(O):null;let $e=!1;if(ve){const Re=pe instanceof Se?O.nodeDOM(pe.from):null,Q=O.posAtCoords({left:R.clientX,top:R.clientY});$e=Re instanceof Node&&R.target instanceof Node&&Re.contains(R.target)||!!Q&&Q.pos>=ve.from&&Q.pos<=ve.to}if(!$e){const Re=R.target instanceof Element?R.target:null,Q=Re?.closest('[contenteditable="false"]'),nt=!!Re&&(!!Q&&Q!==O.dom&&O.dom.contains(Q)||/^(IMG|VIDEO|AUDIO|HR|CANVAS|IFRAME)$/.test(Re.tagName)),at=O.state.selection.empty?Re?.closest("td, th"):null;let Tt=null;if(at&&O.dom.contains(at)){const jt=O.state.doc.resolve(O.posAtDOM(at,0));for(let At=jt.depth;At>0;At--)if(jt.node(At).type.spec.tableRole==="table"){Tt=jt.before(At);break}}if(!nt&&Tt==null)return;const gt=Tt??ss(O,{x:R.clientX,y:R.clientY})?.pos,yt=gt==null?null:O.state.doc.nodeAt(gt);if(gt==null||!yt||!Se.isSelectable(yt))return;O.dispatch(O.state.tr.setSelection(Se.create(O.state.doc,gt)))}R.preventDefault(),O.focus(),e.onMenu({x:R.clientX,y:R.clientY})};h.dom.addEventListener("contextmenu",Co),H.addEventListener("contextmenu",R=>{const O=t;!O||!O.editable||!n||(R.preventDefault(),Wr()||O.focus(),e.onMenu({x:R.clientX,y:R.clientY}))});const Eo=()=>{h.dom.dataset.dragging!=="true"&&X()};window.addEventListener("scroll",Eo,{capture:!0,passive:!0});const fo=R=>{if(h.dom.dataset.dragging!=="true")return;const O=ub(h.dom);if(!O)return;const pe=O.getBoundingClientRect();R.clientY<pe.top+56?O.scrollTop-=14:R.clientY>pe.bottom-56&&(O.scrollTop+=14)};window.addEventListener("dragover",fo);const Io=R=>{const O=t,pe=R.dataTransfer?Array.from(R.dataTransfer.types):[];if(pe.includes("Files")||pe.includes(op)&&O&&!F(O)){if(!O)return;const Q=ne(O,R.clientY);if(!Q)return;const nt=Q.el.getBoundingClientRect();p={pos:Q.pos,el:Q.el,lower:R.clientY>nt.top+nt.height/2},tt(O,Q.el);return}if(!O||O.dom.dataset.dragging!=="true")return;ee&&J(),ee=!1;{const Q=O.state.selection;if(!F(O)&&Q instanceof Se&&Q.node.type===O.state.schema.nodes.amadeusCanvasCard){Ie=!1,r=null,fe=null,ce=null,te=null,a();const nt=be(O,R);nt&&!nt.self?(tt(O,nt.drop.lineEl,0,nt.drop.edge),R.preventDefault()):J();return}}const ve=j(O,R);if(ve){ee=!0,r=null,fe=null,ce=null,te=null,Ie=!1,a(),Ht(),ve.self?J():tt(O,ve.lineEl,0,ve.edge),R.preventDefault();return}if(Ie=!1,te=null,!F(O)){const nt=O.state.selection instanceof Se||!!g(O),at=O.dom.lastElementChild;if(nt&&Ae(at)){const Tt=at.getBoundingClientRect(),gt=O.dom.getBoundingClientRect();if(R.clientY>Tt.bottom+2&&R.clientX>=gt.left&&R.clientX<=gt.right){Ie=!0,r=null,fe=null,ce=null,a(),tt(O,at),R.preventDefault();return}}}if(!(O.state.selection instanceof Se))return;if(F(O)){I(R.target?.closest?.(".amx-ucard")),ce=null,J(),R.preventDefault();return}const $e=he(O,R);if($e){te={cellEl:$e.cellEl,lineEl:$e.lineEl,pos:$e.pos,edge:$e.edge,tail:$e.tail,self:$e.self},ce=null,r=null,fe=null,a(),Ht(),$e.self?J():tt(O,$e.lineEl,0,$e.edge),R.preventDefault();return}let Re=null;for(const Q of O.dom.querySelectorAll(":scope > .amx-ucolrow")){const nt=Q.getBoundingClientRect();if(R.clientX<nt.left||R.clientX>nt.right||R.clientY<=nt.bottom+2)continue;const at=Q.nextElementSibling;at&&R.clientY>=at.getBoundingClientRect().top-2||(Re=Q)}if(Re)try{const Q=O.posAtDOM(Re,0)-1;if(O.state.doc.nodeAt(Q)?.type.name==="amadeusColumnRow"){ce={rowEl:Re},tt(O,Re),R.preventDefault();return}}catch{}ce=null,J()};P.addEventListener("dragover",Io,!0);const Mo=R=>{const O=R.relatedTarget;O&&P.contains(O)||(ce=null,te=null,p=null,fe=null,r=null,ee=!1,a(),J(),Ht(),I(null))};P.addEventListener("dragleave",Mo,!0);const Zt=R=>{const O=t,pe=r,ve=ce,$e=te,Re=fe,Q=p,nt=Ie,at=ee;if(r=null,ce=null,te=null,fe=null,p=null,Ie=!1,ee=!1,a(),J(),Ht(),I(null),!O)return;if(Q){try{const yt=O.nodeDOM(Q.pos)===Q.el?O.state.doc.nodeAt(Q.pos):null;if(yt){ht(O,Q.pos+yt.nodeSize);const jt=O.state.doc;O.dispatch(O.state.tr.setSelection(yt.isAtom?Se.create(jt,Q.pos):Le.near(jt.resolve(Q.lower?Q.pos+1+yt.content.size:Q.pos+1),Q.lower?-1:1)))}}catch{}return}const Tt=m(R);let gt=F(O)?de(O,R,Tt):ge(O,R,Tt);if(!gt)if(nt)gt=z(O,Tt);else if(at)gt=W(O,R,Tt);else if(g(O))gt=L(O,R,Tt);else if(Re)gt=E(O,Re.targetPos,Tt);else if(ve)try{ve.rowEl.isConnected&&(gt=Ix(O,O.posAtDOM(ve.rowEl,0)-1,Tt))}catch{gt=!1}else if($e){const yt=qe(O,$e);yt!=null&&($e.self||ht(O,yt),gt=Px(O,yt,Tt))}else pe&&(gt=Dx(O,pe.targetPos,pe.side,Tt));gt&&(R.preventDefault(),R.stopPropagation(),O.dom.dataset.dragging="false",O.dragging=null)};P.addEventListener("drop",Zt,!0);let eo=null;const Nt=R=>{const O=t,pe=R.target;if(!O||!pe||!pe.classList?.contains("amx-ucolrow"))return;const ve=pe,$e=[...ve.children].filter(Rt=>Rt instanceof HTMLElement&&"amxColcell"in Rt.dataset);let Re=-1;for(let Rt=0;Rt<$e.length-1;Rt++)if(R.clientX>=$e[Rt].getBoundingClientRect().right-2&&R.clientX<=$e[Rt+1].getBoundingClientRect().left+2){Re=Rt;break}if(Re<0)return;R.preventDefault();const Q=$e[Re],nt=$e[Re+1],at=Q.getBoundingClientRect().left,Tt=nt.getBoundingClientRect().right-at,gt=(Number(Q.dataset.width)||1)+(Number(nt.dataset.width)||1),yt=Rt=>Math.min(.85,Math.max(.15,(Rt.clientX-at)/Tt)),jt=Rt=>{const Kn=yt(Rt);Q.style.flexGrow=String(gt*Kn),nt.style.flexGrow=String(gt*(1-Kn))},At=()=>{window.removeEventListener("pointermove",jt),window.removeEventListener("pointerup",sn),window.removeEventListener("pointercancel",At),eo=null},sn=Rt=>{At();const Kn=yt(Rt),Po=d=>Math.round(d*1e4)/1e4;try{const d=O.posAtDOM(ve,0)-1,N=O.state.doc.nodeAt(d);if(!N||N.type.name!=="amadeusColumnRow")return;let $=d+1,K=O.state.tr;for(let B=0;B<N.childCount;B++){const _=N.child(B);B===Re&&(K=K.setNodeMarkup($,void 0,{..._.attrs,width:Po(gt*Kn)})),B===Re+1&&(K=K.setNodeMarkup($,void 0,{..._.attrs,width:Po(gt*(1-Kn))})),$+=_.nodeSize}K.setMeta("amxColumns",!0),O.dispatch(K)}catch{}};window.addEventListener("pointermove",jt),window.addEventListener("pointerup",sn),window.addEventListener("pointercancel",At),eo=At};A.addEventListener("pointerdown",Nt);const nn=ql(()=>{G.title=je("blocklayer.dragHandle"),zt.title=je("blocklayer.addBelow"),Ue.title=je("blocklayer.cardGrab");for(const R of[G,zt,Ue])R.setAttribute("aria-label",R.title)});return{update:R=>{const O=n;if(!O)return;let pe=!1;try{pe=O.pos<=R.state.doc.content.size&&R.state.doc.nodeAt(O.pos)===O.node}catch{}pe||X()},destroy:()=>{window.removeEventListener("mouseup",Ke),V?.remove(),V=null,qn&&clearTimeout(qn),So(),P.removeEventListener("pointerdown",_n),P.removeEventListener("mousemove",er),h.dom.removeEventListener("keydown",xr),h.dom.removeEventListener("contextmenu",Co),P.removeEventListener("dragover",Io,!0),P.removeEventListener("dragleave",Mo,!0),P.removeEventListener("drop",Zt,!0),P.removeEventListener("dragstart",Be,!0),Ri.delete(h),P.removeEventListener("mouseleave",gr),A.removeEventListener("pointerdown",Nt),nn(),eo?.(),window.removeEventListener("scroll",Eo,{capture:!0}),window.removeEventListener("dragover",fo),H.remove(),s?.remove(),s=null,Me?.remove(),Me=null,Ye?.remove(),Ye=null,r=null,ce=null,te=null,ee=!1,n=null,t===h&&(t=null)}}}})),yn=Et(()=>{const h=P=>{if(Ye&&Ye.isConnected)return Ye;const I=document.createElement("div");return I.className="unified-drop-line",I.style.display="none",I.style.animation="none",(P.dom.parentElement??document.body).appendChild(I),Ye=I,I};return px({onDrag:({view:P,event:I,pos:H})=>{if(Ut(),(I.dataTransfer?Array.from(I.dataTransfer.types):[]).includes("Files"))return!1;if(F(P))return a(),!1;if(!P.dragging||!(P.state.selection instanceof Se)||P.state.selection.node.type===P.state.schema.nodes.amadeusCanvasCard)return!1;if(ce||Ie||te||ee)return r=null,fe=null,a(),!1;const ie=P.state.selection,G=ss(P,{x:I.clientX,y:I.clientY});if(G&&G.node.type.name==="list_item"&&!(G.pos>=ie.from&&G.pos<ie.to)){const V=G.el.getBoundingClientRect();if(I.clientX>V.left+24&&I.clientY>V.top+V.height/2)return fe={targetPos:G.pos,el:G.el},r=null,a(),tt(P,G.el,24),!1}if(fe=null,G&&!(G.pos>=ie.from&&G.pos<ie.to)&&ye(P,G.pos)){const V=G.el.getBoundingClientRect(),ze=I.clientX<=V.left+l?"left":I.clientX>=V.right-l?"right":null;if(ze)return r={targetPos:G.pos,side:ze},i(P,G.el,ze),!1}r=null,a();const oe=P.state.doc.resolve(H);if(oe.parent.type.name==="amadeusColumnRow")return!1;for(let V=oe.depth;V>=1;V--){if(oe.node(V).type.name!=="amadeusColumnCell")continue;const ze=P.nodeDOM(oe.before(V));if(ze instanceof HTMLElement){const Ke=ze.getBoundingClientRect();if(I.clientX<Ke.left||I.clientX>Ke.right)return!1}break}return!0},onShow:({view:P,line:I})=>{Ot=!0;const H=h(P),X=_r(P.dom),ie=Br(H),G=(I.p1.x-ie.x)/X,oe=(I.p2.x-ie.x)/X,V=(I.p1.y-ie.y)/X;H.style.display="block",H.style.width=`${Math.max(0,oe-G)}px`,H.style.transform=`translate(${Math.round(G)}px, ${Math.round(V-1.5)}px)`},onHide:Ht})}),ft=Et(()=>new Yt({key:new $n("UNIFIED_DROP_GUARD"),props:{handleDrop:h=>h.dom.dataset.dragging==="true"&&!!h.dragging}})),pt=Et(()=>{let h=null,A=null;const P=()=>{h&&(h.style.display="none")};return new Yt({key:new $n("AMX_GAP_INSERT"),view:I=>{const H=()=>(h&&h.isConnected||(h=document.createElement("div"),h.className="amx-gap-insert",h.innerHTML="<span>+</span>",h.addEventListener("mousedown",G=>{G.preventDefault(),G.stopPropagation()}),h.addEventListener("click",G=>{if(G.preventDefault(),G.stopPropagation(),!A)return;let oe=-1;I.state.doc.forEach((Ke,Ve)=>{oe<0&&Ke.type.name==="amadeusCanvasCard"&&String(Ke.attrs.anchor)===A&&(oe=Ve)});const V=I.state.schema.nodes.paragraph;if(oe<0||!V){P();return}let ze=I.state.tr.insert(oe,V.create());ze=ze.setSelection(Le.create(ze.doc,oe+1)).scrollIntoView(),I.dispatch(ze),I.focus(),P()}),(I.dom.parentElement??document.body).appendChild(h)),h),X=G=>{if(F(I)||I.dragging){P();return}const oe=I.state.schema.nodes.amadeusCanvasCard;if(!oe){P();return}const V=I.state.doc;let ze=0,Ke=null,Ve=null;for(let st=0;st<V.childCount&&!Ve;st++){const Xt=V.child(st);if(Xt.type===oe){const Dt=I.nodeDOM(ze);if(Dt instanceof HTMLElement){if(Dt.classList.contains("amx-card-f0")&&!Dt.classList.contains("amx-card-f0-top")){Ke=Dt,ze+=Xt.nodeSize;continue}if(Ke){const zt=Ke.getBoundingClientRect(),Ue=Dt.getBoundingClientRect();G.clientY>=zt.bottom-3&&G.clientY<=Ue.top+3&&G.clientX>=Math.min(zt.left,Ue.left)&&G.clientX<=Math.max(zt.right,Ue.right)&&(Ve={top:zt.bottom,bottom:Ue.top,left:Math.min(zt.left,Ue.left),right:Math.max(zt.right,Ue.right),anchor:String(Xt.attrs.anchor)})}Ke=Dt}else Ke=null}else Ke=null;ze+=Xt.nodeSize}if(!Ve){P();return}const Be=H(),We=_r(I.dom),Qe=Br(Be),Xe=(Ve.top+Ve.bottom)/2;Be.style.display="flex",Be.style.width=`${(Ve.right-Ve.left)/We}px`,Be.style.transform=`translate(${Math.round((Ve.left-Qe.x)/We)}px, ${Math.round((Xe-Qe.y)/We-9)}px)`,A=Ve.anchor},ie=I.dom.parentElement??I.dom;return ie.addEventListener("mousemove",X),ie.addEventListener("mouseleave",P),{update:(G,oe)=>{G.state.doc.eq(oe.doc)||P()},destroy:()=>{ie.removeEventListener("mousemove",X),ie.removeEventListener("mouseleave",P),h?.remove(),h=null}}}})}),Vt={listFoldedAt:(h,A)=>wc(h,A),unfoldList:(h,A)=>Ca(h,A)},bn=Et(()=>Ko({Tab:(h,A,P)=>ya(h,A,P,Vt),"Shift-Tab":(h,A)=>ba(h,A)})),Jt=Et(()=>new Yt({props:{decorations:h=>{const A=h.selection;if(!A.empty)return null;const P=A.$from,I=P.parent;if(!I.isTextblock||I.content.size>0)return null;for(let X=P.depth;X>=1;X--)if(P.node(X).type.name==="blockquote")return null;const H=I.type.name==="paragraph"?je("blocklayer.phParagraph"):I.type.name==="heading"?je("blocklayer.phHeading",{n:I.attrs.level??1}):null;return H?dr.create(h.doc,[ao.node(P.before(),P.after(),{class:"is-empty","data-placeholder":H})]):null}}})),vn=["doc","amadeusColumnCell","bullet_list","ordered_list"],jn=h=>{let A=h.depth;for(;A>=1&&!vn.includes(h.node(A-1).type.name);)A--;return A},jr=h=>{const A=h.selection;if(A instanceof Se){if(!A.node.isBlock)return null;if(vn.includes(A.$from.parent.type.name))return{from:A.from,to:A.to};const X=jn(A.$from);return X<1?null:{from:A.$from.before(X),to:A.$from.after(X)}}const{$from:P,$to:I}=A;if(!P.sameParent(I)){let X=P.sharedDepth(I.pos);for(;X>0&&!vn.includes(P.node(X).type.name);)X--;return{from:P.before(X+1),to:I.after(X+1)}}const H=jn(P);return H<1?null:{from:P.before(H),to:P.after(H)}},rn=h=>(A,P)=>{const I=jr(A);if(!I)return!1;const{from:H}=I,X=ms(A,I.from,I.to),ie=A.doc.resolve(H),G=ie.parent,oe=ie.index(),V=A.doc.resolve(X).index()-1,ze=G.child(oe),Ke=X>I.to&&ze.type.name==="heading"?Number(ze.attrs.level)||1:null;let Ve,Be;if(h<0){if(oe===0)return!0;Be=H,Ve=H-G.child(oe-1).nodeSize;let zt=null;if(Ke!=null)for(let Ue=oe-1,Ln=H;Ue>=0;Ue--){const Ft=G.child(Ue);if(Ln-=Ft.nodeSize,Ft.type.name==="heading"&&(Number(Ft.attrs.level)||1)<=Ke){zt=Ln;break}}if(zt!=null)Ve=zt;else for(let Ue=Us(A,Ve+1);Ue!=null&&Ue<Ve;Ue=Us(A,Ve+1))Ve=Ue}else{if(V+1>=G.childCount)return!0;Ve=X;const zt=G.child(V+1);Be=X+zt.nodeSize,Ke!=null&&zt.type.name==="heading"&&(Be=Am(A.doc,Ve)??Be)}if(!P)return!0;const We=X-H,Qe=A.doc.slice(H,X).content,Xe=h<0?Ve:Be-We,st=A.tr.delete(H,X).insert(Xe,Qe),Xt=Xe-H;Vr(A,st,{from:H,to:X,newStart:Xe}),ns(A,st,{from:H,to:X,newStart:Xe});const Dt=A.selection;return Dt instanceof Se?st.setSelection(Se.create(st.doc,Dt.from+Xt)):st.setSelection(Le.create(st.doc,Dt.anchor+Xt,Dt.head+Xt)),o.getState(A)&&st.setMeta(o,!0),P(st.scrollIntoView()),!0},Wn=Et(()=>Ko({"Mod-Alt-ArrowUp":rn(-1),"Mod-Alt-ArrowDown":rn(1),"Mod-Shift-ArrowUp":rn(-1),"Mod-Shift-ArrowDown":rn(1)})),Zn=(h,A,P)=>{const I=h.selection,H=P?g(P):null;if(H){if(!A)return!0;const Ke=ms(h,H.from,H.to),{content:Ve,minted:Be}=rs(h.doc,h.doc.slice(H.from,Ke).content);Be.length&&e.onCardsMinted?.(Be);const We=Ke-H.from,Qe=h.tr.insert(Ke,Ve);return Vr(h,Qe,{from:H.from,to:Ke,newStart:Ke,copy:!0}),ns(h,Qe,{from:H.from,to:Ke,newStart:Ke}),Qe.setSelection(Le.create(Qe.doc,I.anchor+We,I.head+We)),o.getState(h)&&Qe.setMeta(o,!0),A(Qe.scrollIntoView()),!0}if(I instanceof Se){if(!I.node.isBlock)return!1;if(!A)return!0;const Ke=ms(h,I.from,I.to);if(Ke>I.to){const We=h.tr.insert(Ke,h.doc.slice(I.from,Ke).content);return Vr(h,We,{from:I.from,to:Ke,newStart:Ke,copy:!0}),ns(h,We,{from:I.from,to:Ke,newStart:Ke}),We.setSelection(Se.create(We.doc,Ke)),A(We.scrollIntoView()),!0}let Ve=I.node;if(Ve.type.name==="amadeusCanvasCard"){const{content:We,minted:Qe}=rs(h.doc,To.from(Ve)),Xe=We.firstChild??Ve;Ve=Xe.type.create({...Xe.attrs,x:Number(Xe.attrs.x)+40,y:Number(Xe.attrs.y)+40},Xe.content,Xe.marks),Qe.length&&e.onCardsMinted?.(Qe)}const Be=h.tr.insert(I.to,Ve);return Be.setSelection(Se.create(Be.doc,I.to)),A(Be.scrollIntoView()),!0}if(!(I instanceof Le)||!I.$from.sameParent(I.$to))return!1;const{$from:X}=I;let ie=X.depth;for(;ie>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard","bullet_list","ordered_list"].includes(X.node(ie-1).type.name);)ie--;if(ie<1)return!1;const G=X.before(ie),oe=ms(h,G,X.after(ie));if(!h.doc.nodeAt(G))return!1;if(!A)return!0;const V=oe-G,ze=h.tr.insert(oe,h.doc.slice(G,oe).content);return Vr(h,ze,{from:G,to:oe,newStart:oe,copy:!0}),ns(h,ze,{from:G,to:oe,newStart:oe}),ze.setSelection(Le.create(ze.doc,I.anchor+V,I.head+V)),A(ze.scrollIntoView()),!0},pr=Et(()=>Ko({"Mod-d":Zn})),Yn=(h,A,P,I=!1)=>{const H=P?g(P):null;if(!H)return!1;const X=h.doc.resolve(H.from);if(h.doc.resolve(H.to).index()-X.index()<2)return!1;const G=h.selection;if(G.from>H.from+1||G.to<H.to-1)return!1;if(!A)return!0;const oe=h.doc.slice(H.from,H.to).content;return A(h.tr.delete(H.from,H.to).scrollIntoView()),I||e.onBlocksDeleted?.(oe),!0},Un=(h,A)=>{const P=h.selection;if(!(P instanceof Se))return!1;if(!A)return!0;const I=To.from(P.node);return A(h.tr.deleteSelection().scrollIntoView()),e.onBlocksDeleted?.(I),!0},Go=(h,A,P)=>Yn(h,A,P)||Un(h,A),vo=Et(()=>Ko({Backspace:Go,Delete:Go})),Rr=Et(()=>new Yt({props:{handleDOMEvents:{cut:(h,A)=>{const P=A;if(!P.clipboardData||!Yn(h.state,void 0,h,!0))return!1;const{dom:I,text:H}=h.serializeForClipboard(h.state.selection.content());return P.preventDefault(),P.clipboardData.clearData(),P.clipboardData.setData("text/html",I.innerHTML),P.clipboardData.setData("text/plain",H),Yn(h.state,h.dispatch.bind(h),h,!0),!0}}}})),zn=Et(()=>Ko({"Mod-a":(h,A)=>{const{$from:P}=h.selection,I=(ie,G)=>h.selection.from<=ie&&h.selection.to>=G,H=[];P.parent.isTextblock&&H.push([P.start(),P.end()]);let X=P.depth;for(;X>=1&&!["doc","amadeusColumnCell"].includes(P.node(X-1).type.name);)X--;X>=1&&H.push([P.start(X),P.end(X)]);for(const[ie,G]of H)if(!I(ie,G))return A?.(h.tr.setSelection(Le.create(h.doc,ie,G))),!0;return A?.(h.tr.setSelection(new Ql(h.doc))),!0}})),En=h=>{const A=h.selection;if(!(A instanceof Le)||A.empty)return[];const P=!!o.getState(h);if(!P&&A.$from.sameParent(A.$to))return[];const I=[],H=ie=>{if(["bullet_list","ordered_list","table","blockquote","horizontal_rule","code_block","amadeusCanvasCard"].includes(ie.type.name))return!0;if(ie.type.name!=="paragraph")return!1;const G=ie.textContent.trim();return/^!?\[\[[^\]\n]+\]\]$/.test(G)||ie.childCount===1&&ie.firstChild?.type.name==="image"},X=(ie,G)=>{ie.forEach((oe,V)=>{const ze=G+V,Ke=ze+oe.nodeSize;if(!(Ke<=A.from||ze>=A.to)){if(oe.type.name==="amadeusColumnRow"){oe.forEach((Ve,Be)=>X(Ve,ze+1+Be+1));return}(P||H(oe))&&I.push([ze,Ke,P])}})};return X(h.doc,0),I},Fn=Et(()=>new Yt({key:o,state:{init:()=>!1,apply:(h,A,P)=>h.getMeta(o)===!0?!0:h.docChanged||h.selectionSet&&!h.selection.eq(P.selection)?!1:A},props:{decorations:h=>{const A=En(h);return A.length?dr.create(h.doc,A.map(([P,I,H])=>ao.node(P,I,{class:H?"amx-block-selected":"amx-rendered-selected"}))):null},attributes:h=>o.getState(h)&&En(h).length?{"data-blocksel":"true"}:{}}})),lt=Et(()=>Ko({Escape:(h,A)=>{const P=h.selection;if(P instanceof Se){const I=Le.near(h.doc.resolve(P.from+1));return A?.(h.tr.setSelection(I)),!0}if(P instanceof Le){const I=ml(h);return I==null?!1:(A?.(h.tr.setSelection(Se.create(h.doc,I))),!0)}return!1}})),Mt=["doc","amadeusColumnCell"],co=h=>{const A=h.selection;return A instanceof Se?A.node.isBlock:A instanceof Le&&!A.empty&&!!o.getState(h)},wo=(h,A)=>{const P=h.resolve(A);if(Mt.includes(P.parent.type.name)){const H=P.nodeAfter;return H?{from:A,to:A+H.nodeSize}:null}let I=P.depth;for(;I>=1&&!Mt.includes(P.node(I-1).type.name);)I--;return I>=1?{from:P.before(I),to:P.after(I)}:null},Jo=h=>{const A=h.selection,P=h.doc,I=wo(P,A instanceof Se?A.from:A.anchor),H=A instanceof Se?I:wo(P,A.head);return!I||!H||P.resolve(I.from).parent!==P.resolve(H.from).parent?null:{a:I,h:H}},jo=(h,A,P)=>{const I=h.doc,H=A.from===P.from?I.nodeAt(A.from):null;if(H&&Se.isSelectable(H))return h.tr.setSelection(Se.create(I,A.from));const X=P.from>=A.from,ie=I.resolve(X?A.from+1:A.to-1),G=I.resolve(X?P.to-1:P.from+1);return h.tr.setSelection(Le.between(ie,G)).setMeta(o,!0)},Xn=h=>(A,P)=>{if(!co(A))return!1;const I=Jo(A);if(!I)return!1;const H=A.doc.resolve(I.h.from),X=H.parent;let ie=H.index()+h,G=h>0?I.h.to:I.h.from;for(;ie>=0&&ie<X.childCount;){const oe=X.child(ie).nodeSize,V=h>0?G:G-oe;if(Us(A,V+1)==null)return P?.(jo(A,I.a,{from:V,to:V+oe}).scrollIntoView()),!0;G=h>0?G+oe:G-oe,ie+=h}return!0},Rn=h=>h.selection.$from.parent.type.name==="code_block";return{plugins:[Et(()=>new Yt({props:{handleKeyDown:rp({"Shift-ArrowDown":Xn(1),"Shift-ArrowUp":Xn(-1),"Mod-Alt-/":(h,A,P)=>{if(!P||!P.editable||!A)return!1;if(!co(h)){const ie=ml(h);if(ie==null)return!1;A(h.tr.setSelection(Se.create(h.doc,ie)))}const I=P.state,H=I.selection instanceof Se?P.nodeDOM(I.selection.from):null,X=H instanceof HTMLElement?H.getBoundingClientRect():P.coordsAtPos(I.selection.from);return e.onMenu({x:X.left,y:X.bottom+4,keyboard:!0,focus:"turnInto"}),!0},"Mod-]":(h,A,P)=>Rn(h)?!1:ya(h,A,P,Vt),"Mod-[":(h,A)=>Rn(h)?!1:ba(h,A)}),handleDOMEvents:{mousedown:(h,A)=>{if(!A.shiftKey||A.button!==0||!h.editable||!co(h.state))return!1;const P=h.posAtCoords({left:A.clientX,top:A.clientY}),I=Jo(h.state),H=P?wo(h.state.doc,P.pos):null;return!I||!H||h.state.doc.resolve(H.from).parent!==h.state.doc.resolve(I.a.from).parent?!1:(A.preventDefault(),h.dispatch(jo(h.state,I.a,H)),h.focus(),!0)}}}})),Ze,yn,ft,pt,Fn,Jt,lt,bn,zn,vo,Rr,Wn,pr,ib].flat(),getView:()=>t,topRangeOf:g,duplicate:h=>Zn(h.state,h.dispatch.bind(h),h),indent:(h,A)=>A>0?ya(h.state,h.dispatch.bind(h),h,Vt):ba(h.state,h.dispatch.bind(h))}}async function fb(e,t,n){const o=Qc(t);if(!o.length)return;const r=new Set(Qc(n).map(Zs)),s=o.filter(a=>!r.has(Zs(a)));if(!s.length)return;const i=(await on.exclusiveAssets?.(e).catch(()=>[])??[]).filter(a=>s.some(l=>pb(l,a)));i.length&&await Zh(e,i,{block:!0})==="with"&&await Vp(i)}function pb(e,t){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase(),o=t.replace(/\\/g,"/").toLowerCase();return n.includes("/")?o===n||o.endsWith(`/${n}`)||o===Vl(n):Zs(e)===Zs(t)}function hl(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(`[](${ei(c)??c})`)}return}const r=String(o.attrs?.src??"");r&&t.push(`![](${ei(r)??r})`),o.forEach(n)};return e.forEach(n),t.join(`
687
+ `)}const Xo=1,en=400,qo=720,mb=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/,hb=/^<!--\s*\/a\s+([A-Za-z0-9_-]+)\s*-->$/,fa=/^[A-Za-z0-9_-]+$/,so=(e,t)=>typeof e=="number"&&Number.isFinite(e)?Math.round(e):t;function On(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!==Xo||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"||!fa.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 gb(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 xb=vc("amadeusCanvasCard",()=>({content:"block+",group:"block",defining:!0,isolating:!0,selectable:!0,attrs:{anchor:{default:""},x:{default:0},y:{default:0},w:{default:en},h:{default:0},color:{default:""}},parseDOM:[{tag:"div[data-amx-card]",getAttrs:e=>{const t=e.dataset;return{anchor:t.anchor??"",x:so(Number(t.x),0),y:so(Number(t.y),0),w:so(Number(t.w),en)||en,h:so(Number(t.h),0),color:t.color??""}}}],toDOM:e=>{const t=la(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??en,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 yb(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(S=>S?.position))return;const c=S=>{let z=null;if(S?.type==="html"&&typeof S.value=="string")z=S.value;else if(S?.type==="paragraph"&&Array.isArray(S.children)&&S.children.length===1){const E=S.children[0];E?.type==="html"&&typeof E.value=="string"&&(z=E.value)}if(z==null)return null;const L=mb.exec(z.trim());return L?L[1]:null},i=S=>{let z=null;if(S?.type==="html"&&typeof S.value=="string")z=S.value;else if(S?.type==="paragraph"&&Array.isArray(S.children)&&S.children.length===1){const E=S.children[0];E?.type==="html"&&typeof E.value=="string"&&(z=E.value)}if(z==null)return null;const L=hb.exec(z.trim());return L?L[1]:null},a=new Map(r.map(S=>[S.ref,S])),l=Hu(t?.cardColors),m=[];if(s.forEach((S,z)=>{const L=c(S);L&&m.push({id:L,idx:z})}),!m.length)return;const g=new Map;m.forEach(S=>g.set(S.id,(g.get(S.id)??0)+1));const C=[];for(const S of m){if((g.get(S.id)??0)>1||n.has(S.id)||!a.has(S.id))continue;let z=s.length,L=-1;for(let E=S.idx+1;E<s.length;E++){if(c(s[E])){z=E;break}if(i(s[E])===S.id){z=E,L=E;break}}C.push({id:S.id,open:S.idx,end:z,closer:L})}if(!C.length)return;const M=[];for(const S of[...C].reverse()){const z=a.get(S.id),L=s.slice(S.open+1,S.end);s.splice(S.open,(S.closer>=0?S.closer+1:S.end)-S.open,{type:"amadeusCanvasCard",anchor:S.id,x:so(z.x,0),y:so(z.y,0),w:so(z.w,en)||en,h:so(z.h,0),color:l&&Object.prototype.hasOwnProperty.call(l,S.id)&&Ku(l[S.id])?l[S.id]:typeof z.color=="string"?z.color:"",children:L.length?L:[{type:"paragraph",children:[]}]}),M.unshift(S.id)}o?.(M)}function bb(e,t,n){return[su("amadeusCanvasFold",()=>()=>o=>{yb(o,e(),gb(t()),n)})].flat()}function vb(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const o=String(n.attrs.anchor);if(!fa.test(o))return;const r=so(n.attrs.h,0);t.push({ref:o,x:so(n.attrs.x,0),y:so(n.attrs.y,0),w:so(n.attrs.w,en)||en,...r>0?{h:r}:{}})}),t}function Hu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}const Ku=e=>e!==""&&e!=null;function gl(e){const t=Object.create(null);return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const o=String(n.attrs.anchor);fa.test(o)&&Ku(n.attrs.color)&&(t[o]=n.attrs.color)}),t}function wb(e,t,n,o){const r=vb(e),s=On(t);if(!s){if(t!=null)return t;if(!r.length)return null;const m=gl(e);return JSON.stringify({v:Xo,mode:n??"canvas",main:{x:0,y:0,w:qo},cards:r,...Object.keys(m).length?{cardColors:{...m}}:{}})}if(!(s.cards??[]).every(m=>o.has(m.ref)))return t;if(!r.length&&!s.elements?.length){const m=s.main;if(!m||m.x===0&&m.y===0&&m.w===qo)return null}const c={...s,v:Xo,cards:r},i=gl(e);Object.keys(i).length?c.cardColors={...i}:(c.cardColors===void 0||Hu(c.cardColors))&&delete c.cardColors,n&&(c.mode=n),c.main||(c.main={x:0,y:0,w:qo}),c.elements?.length||delete c.elements;const a=qt(c.tree),l=Object.keys(a);if(l.length){const m=new Set(r.map(M=>M.ref)),g=M=>typeof M=="string"&&fa.test(M)&&!m.has(M),C=new Set;for(const M of l)g(M)&&C.add(M),g(a[M])&&C.add(a[M]);if(C.size){const M=Sx(a,C);Object.keys(M).length?c.tree=M:delete c.tree}}return JSON.stringify(c)}function kb(e,t){const n=On(e);if(!n)return e??(t.length?JSON.stringify({v:Xo,mode:"canvas",main:{x:0,y:0,w:qo},cards:[],elements:t}):null);const o={...n,v:Xo,elements:t};return t.length||delete o.elements,JSON.stringify(o)}function Sb(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=On(e);return o?JSON.stringify({...o,v:Xo,main:n}):e??(!n.x&&!n.y&&n.w===qo?null:JSON.stringify({v:Xo,mode:"canvas",main:n,cards:[]}))}function Cb(e,t){const n=Object.keys(t).length,o=On(e);if(!o)return e??(n?JSON.stringify({v:Xo,mode:"canvas",main:{x:0,y:0,w:qo},cards:[],tree:t}):null);const r={...o,v:Xo,tree:t};return n||delete r.tree,JSON.stringify(r)}const Eb=Et(()=>new Yt({key:new $n("AMX_CANVAS_NORMALIZE"),appendTransaction:(e,t,n)=>{if(!e.some(a=>a.docChanged))return null;const o=n.schema.nodes.amadeusCanvasCard;if(!o)return null;const r=[],s=[],c=new Set;if(n.doc.forEach((a,l)=>{if(a.type!==o)return;const m=String(a.attrs.anchor);c.has(m)?s.push(l):c.add(m),a.forEach((g,C)=>{if(g.type.name!=="amadeusColumnRow")return;const M=l+1+C;r.push({from:M,to:M+g.nodeSize,node:g,before:l})})}),!r.length&&!s.length)return null;let i=n.tr;for(const a of s){const l=i.doc.nodeAt(a);l?.type===o&&(i=i.setNodeMarkup(a,void 0,{...l.attrs,anchor:$o(i.doc)}))}for(const a of r)i=i.delete(i.mapping.map(a.from,1),i.mapping.map(a.to,-1)),i=i.insert(i.mapping.map(a.before),a.node);return i.steps.length?i:null}})),Mb=Et(()=>new Yt({key:new $n("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(i=>{i.type===n?r(i.content).forEach(a=>c.push(a)):c.push(i.copy(r(i.content)))}),To.fromArray(c)};return Xa.maxOpen(r(e.content))}}})),zb=Et(()=>new Yt({key:new $n("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}})),Ab=[xb,Eb,Mb,zb].flat();function Nb(e){return[Et(()=>new Yt({key:new $n("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 S=0;for(let z=0;z<o.doc.childCount;z++){const L=o.doc.child(z);if(L.type===r){s=S;break}S+=L.nodeSize}}if(s<0)return null;const c=S=>S.depth>=1&&S.node(1).type===r?S.index(0):-1,i=S=>{if(S<0)return{from:0,to:s};let z=0;for(let L=0;L<S;L++)z+=o.doc.child(L).nodeSize;return{from:z+1,to:z+o.doc.child(S).nodeSize-1}},a=S=>S.eq(o.selection)||c(o.doc.resolve(S.anchor))!==c(o.doc.resolve(S.head))?null:o.tr.setSelection(S),l=o.selection;if(l.empty||l instanceof Se)return null;if(l instanceof Ql){if(t.some(L=>L.docChanged))return null;const S=Math.max(0,Math.min(n.selection.head,o.doc.content.size)),z=i(c(o.doc.resolve(S)));return z.from>=z.to?null:a(Le.between(o.doc.resolve(z.from),o.doc.resolve(z.to),-1))}if(!(l instanceof Le))return null;const m=o.doc.resolve(l.anchor),g=c(m);if(g===c(o.doc.resolve(l.head)))return null;const C=i(g),M=Math.max(C.from,Math.min(C.to,l.head));return a(Le.between(m,o.doc.resolve(M),l.head>=l.anchor?-1:1))}}))].flat()}function Tb(){return[Et(()=>new Yt({key:new $n("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 Se){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?dr.create(e.doc,[ao.node(o,o+r.nodeSize,{class:"amx-card-active"})]):null}}}))].flat()}const $b=6,jb=2;function Rb(e){return[Et(()=>new Yt({key:new $n("AMX_CARD_DEPTH"),props:{decorations(t){const n=t.schema.nodes.amadeusCanvasCard;if(!n)return null;const o=qt(e()?.tree);if(!Object.keys(o).length)return null;const r=new Set,s=[];t.doc.forEach((a,l,m)=>{if(a.type!==n)return;const g=String(a.attrs.anchor);r.add(g),s.push({pos:l,size:a.nodeSize,anchor:g,idx:m})});const c=[];for(let a=0;a<s.length;a++){const l=oa(s,a,o);l>a+1&&c.push({start:a,end:l})}const i=[];for(let a=0;a<s.length;a++){const l=s[a],m=Cx(o,l.anchor,r,$b),g=c.filter(M=>M.start<=a&&a<M.end).slice(0,jb);if(!m&&!g.length)continue;const C=[];m>0&&C.push("amx-card-child",`amx-card-d${m}`),g.forEach((M,S)=>{C.push(`amx-card-f${S}`),M.start===a&&C.push(`amx-card-f${S}-top`),M.end-1===a&&C.push(`amx-card-f${S}-end`)}),i.push(ao.node(l.pos,l.pos+l.size,{class:C.join(" ")}))}return i.length?dr.create(t.doc,i):null}}}))].flat()}const Lb=200;function Db(e){return[Et(()=>new Yt({key:new $n("AMX_CANVAS_HISTORY_TIMELINE"),state:{init:(t,n)=>({depth:Ya(n)}),apply:(t,n,o,r)=>{const s=Ya(r);return t.docChanged&&s>n.depth&&!sf(t)&&(e.log.push("pm"),e.log.length>Lb&&e.log.shift(),e.future.length=0),s===n.depth?n:{depth:s}}}}))].flat()}Cn({"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 Pt=e=>`c:${e}`,xn=e=>`e:${e}`,Vu=e=>`t:${e}`,it=e=>e.slice(2),Bs=e=>typeof e=="number"&&Number.isFinite(e)?e:null,Yr=e=>typeof e=="string"&&e?e:null,Da=e=>la(e)?e:null,Nc=e=>{const t=la(e);return t?{"data-color":e,style:{"--amx-color":t}}:{}};function sa(e){if(!e||typeof e!="object")return null;const t=e,n=Yr(t.ref);if(n)return{ref:n};const o=Yr(t.id);return o?{id:o}:t.main===!0?{main:!0}:null}const Sr=e=>e.ref?Pt(e.ref):e.id?xn(e.id):e.main?we:null;function Tn(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=Yr(r.id);if(!s||n.has(s))continue;if(r.type==="connector"){const m=sa(r.from),g=sa(r.to);if(!m||!g)continue;n.add(s),t.push({kind:"connector",id:s,from:m,to:g,label:Yr(r.label),color:Da(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=Bs(r.x),i=Bs(r.y),a=Bs(r.w),l=Bs(r.h);if(!(c==null||i==null||a==null||l==null||a<=0||l<=0)){if(n.add(s),r.type==="frame"){t.push({kind:"frame",id:s,x:c,y:i,w:a,h:l,title:Yr(r.title),color:Da(r.color)});continue}t.push({kind:r.type==="text"?"text":"shape",id:s,x:c,y:i,w:a,h:l,shape:r.shape==="ellipse"?"ellipse":"rect",text:Yr(r.text),color:Da(r.color)})}}return t}function xl(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 Tc(e,t){const n=xl(e,t),o=xl(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),i=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+i*s},c2:r?{x:o.x-c*s,y:o.y}:{x:o.x,y:o.y-i*s},p2:o}}function Ib(e,t){const{p1:n,c1:o,c2:r,p2:s}=Tc(e,t),c=[n.x,o.x,r.x,s.x],i=[n.y,o.y,r.y,s.y],a=Math.min(...c),l=Math.min(...i);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:a,y:l,w:Math.max(1,Math.max(...c)-a),h:Math.max(1,Math.max(...i)-l)}}}function Hs(e,t,n,o=8){const{p1:r,c1:s,c2:c,p2:i}=Tc(e,t);let a=r.x,l=r.y;for(let m=1;m<=24;m++){const g=m/24,C=1-g,M=C*C*C*r.x+3*C*C*g*s.x+3*C*g*g*c.x+g*g*g*i.x,S=C*C*C*r.y+3*C*C*g*s.y+3*C*g*g*c.y+g*g*g*i.y,z=M-a,L=S-l,E=z*z+L*L,F=E?Math.max(0,Math.min(1,((n.x-a)*z+(n.y-l)*L)/E)):0;if(Math.hypot(a+F*z-n.x,l+F*L-n.y)<=o)return!0;a=M,l=S}return!1}function qu(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 Pb(e,t){const n=[...t].flatMap(i=>i===we?[we]:i.startsWith("c:")?[it(i)]:[]),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[i,a]of e){s.set(i,a);const l=c.get(a);l?l.push(i):c.set(a,[i])}for(const i of n){const a=new Set;let l=i;for(;!a.has(l);){a.add(l),o.add(l);const C=s.get(l);if(!C)break;r.add(l),o.add(C),l=C}const m=[i],g=new Set;for(;m.length;){const C=m.shift();if(!g.has(C)){g.add(C);for(const M of c.get(C)??[])r.add(M),o.add(M),m.push(M)}}}return{nodes:o,edgeChildren:r}}const yl=(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 bl(e,t=!1){const n=a=>!t||!a.closest(".amx-ucard"),o=a=>(a.innerText||a.textContent||"").split(/\r?\n/).map(l=>l.trim()).find(Boolean)??null,r=[...e.querySelectorAll("h1,h2,h3,h4,h5,h6")].filter(n).map(o).filter(a=>!!a),s=[...e.querySelectorAll("p,li,blockquote,pre")].filter(n).map(o).filter(a=>!!a),c=r[0]??s[0];if(!c)return null;const i=s.find((a,l)=>a!==c&&(r.length>0||l>0))??null;return{title:c,detail:i}}function Ob(e,t){const n=e.classList.contains("amx-stage-overview");n&&e.classList.remove("amx-stage-overview");try{const o=[];for(const[i,a]of hn(e)){const l=e.querySelector(`.amx-ucard[data-anchor="${CSS.escape(i)}"]`),m=l?bl(l):null;l&&m&&o.push({key:Pt(i),anchor:i,...m,h:a.h,autoHeight:Number(l.dataset.h)<=0})}const r=e.querySelector(".ProseMirror"),s=gn(e),c=r?bl(r,!0):null;return s&&c&&o.push({key:we,anchor:we,...c,h:s.h,autoHeight:t}),o}finally{n&&e.classList.add("amx-stage-overview")}}function Fb(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 ar=24;function Tr(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(xn(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(ar,r.w+t.size.dw),h:Math.max(ar,r.h+t.size.dh)}),n.set(o.id,r)}return n}function _b({elements:e,hostRef:t,documentKey:n,sel:o,editing:r,tree:s,ghost:c,marquee:i,attach:a,overviewScale:l,mainAutoHeight:m=!0,preview:g,guides:C}){const{t:M}=Bt(),S=x.useMemo(()=>Tn(e),[e]),z=x.useMemo(()=>qu(s),[s]),L=x.useMemo(()=>Pb(z,o),[z,o]),E=L.edgeChildren,[F,U]=x.useState(0),q=S.length+z.length,de=[...o].filter(j=>j.startsWith("c:")).map(it),me=o.has(we),Ne=q+de.length+(me?1:0),be=l!=null&&l>0,[ge,p]=x.useState({documentKey:"",items:[]});x.useEffect(()=>{const j=t.current;if(!j)return;let W=0;const ne=new ResizeObserver(()=>et()),he=new Set,qe=()=>{const Ye=new Set(j.querySelectorAll(".amx-ucard")),Ht=j.querySelector(".ProseMirror");Ht&&Ye.add(Ht);for(const Ot of Ye)he.has(Ot)||(ne.observe(Ot,{box:"border-box"}),he.add(Ot));for(const Ot of[...he])Ye.has(Ot)||(ne.unobserve(Ot),he.delete(Ot))},et=()=>{cancelAnimationFrame(W),W=requestAnimationFrame(()=>{qe(),U(Ye=>Ye+1)})};et();const ht=new MutationObserver(et);return ht.observe(j,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["style","data-x","data-y","data-w","data-h"]}),ne.observe(j),()=>{cancelAnimationFrame(W),ht.disconnect(),ne.disconnect()}},[t]);const fe=x.useMemo(()=>hn(t.current),[t,n,ge.documentKey,F,Ne,c]),ce=x.useMemo(()=>Tr(S,c),[S,c]),te=gn(t.current);x.useLayoutEffect(()=>{if(!be)return;const j=t.current,W=j?.querySelector(".ProseMirror");if(!j||!W||W.childElementCount===0)return;const ne=Ob(j,m);p(he=>he.documentKey===n&&Fb(he.items,ne)?he:{documentKey:n,items:ne})},[n,t,m,be,F]);const ee=ge.documentKey===n?ge.items:[],Ie=new Set([...de,...me?[we]:[]]),Me=be?ee.flatMap(j=>{if(Ie.has(j.anchor))return[];const W=j.anchor===we?te:fe.get(j.anchor);return W?[{...j,box:W}]:[]}):[],dt=t.current?.dataset.amxDragscope,tt=be&&dt?ee.flatMap(j=>{const W=`.amx-stage[data-amx-dragscope="${CSS.escape(dt)}"].amx-stage-overview`;if(Ie.has(j.anchor))return[];if(j.anchor===we)return[`${W} .ProseMirror:not(.unified-embed .ProseMirror) > :not(.amx-ucard){display:none!important;}`,...m?[`${W} .ProseMirror:not(.unified-embed .ProseMirror){height:${j.h}px;}`]:[]];const ne=`${W} .amx-ucard[data-anchor="${CSS.escape(j.anchor)}"]`;return[`${ne} > *{display:none!important;}`,...j.autoHeight?[`${ne}[data-h="0"]{height:${j.h}px;}`]:[]]}).join(`
688
+ `):"",J=L.nodes.size>0&&dt?(()=>{const j=`.amx-stage[data-amx-dragscope="${CSS.escape(dt)}"]:not(.amx-stage-off)`,W=[...fe.keys()].filter(he=>!L.nodes.has(he)).flatMap(he=>[`${j} .amx-ucard[data-anchor="${CSS.escape(he)}"]`,`${j} .amx-card-overview[data-card-label="${CSS.escape(he)}"]`]),ne=W.length?[`${W.join(`,
689
+ `)}{opacity:0.44;}`]:[];if(!L.nodes.has(we)){const he=`${j} .ProseMirror:not(.unified-embed .ProseMirror)`;ne.push(`${he}{background-color:color-mix(in srgb,var(--bg) 44%,transparent);border-color:color-mix(in srgb,var(--border) 44%,transparent);box-shadow:none;}`,`${he}>:not(.amx-ucard){opacity:0.44;}`,`${j} .amx-card-overview[data-card-label="${CSS.escape(we)}"]{opacity:0.44;}`)}return ne.push(`${j} .amx-el-conn.is-tree:not(.is-related){opacity:0.18;}`),ne.join(`
690
+ `)})():"",ye=j=>j.ref!=null?fe.get(j.ref)??null:j.id!=null?ce.get(j.id)??null:j.main?te:null,Ae=j=>j===we?te:j.startsWith("c:")?fe.get(it(j))??null:ce.get(it(j))??null;return u.jsxs("div",{className:"amx-el-layer",children:[tt?u.jsx("style",{"data-amx-overview-rules":!0,children:tt}):null,J?u.jsx("style",{"data-amx-related-focus-rules":!0,children:J}):null,S.filter(j=>j.kind==="frame").map(j=>u.jsx(Vb,{el:j,box:ce.get(j.id),sel:o.has(xn(j.id))},j.id)),S.filter(j=>j.kind!=="frame").map(j=>j.kind==="connector"?u.jsx(Ks,{el:j,a:ye(j.from),b:ye(j.to),sel:o.has(xn(j.id))},j.id):u.jsx(qb,{el:j,box:ce.get(j.id),sel:o.has(xn(j.id))},j.id)),o.size===1&&[...o][0].startsWith("e:")&&ce.has(it([...o][0]))?u.jsxs(u.Fragment,{children:[u.jsx(Hb,{id:it([...o][0]),box:ce.get(it([...o][0]))}),u.jsx(Ia,{node:[...o][0],box:ce.get(it([...o][0]))})]}):null,(()=>{const j=o.size===1?[...o][0]:null,W=j?.startsWith("e:")?S.find(ht=>ht.kind==="connector"&&ht.id===it(j)):null,ne=W?ye(W.from):null,he=W?ye(W.to):null;if(!W||!ne||!he)return null;const{p1:qe,p2:et}=Tc(ne,he);return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"amx-conn-end","data-conn-end":"from","data-el":W.id,style:{left:`${qe.x}px`,top:`${qe.y}px`}}),u.jsx("div",{className:"amx-conn-end","data-conn-end":"to","data-el":W.id,style:{left:`${et.x}px`,top:`${et.y}px`}})]})})(),z.map(([j,W])=>{const ne=W===we?te:fe.get(W),he=fe.get(j),qe=W===we?{main:!0}:{ref:W};return ne&&he?u.jsx(Ks,{el:{kind:"connector",id:`t:${j}`,from:qe,to:{ref:j},label:null},a:ne,b:he,sel:o.has(Vu(j)),related:E.has(j),tree:!0},`t:${j}`):null}),de.map(j=>{const W=fe.get(j);return W?u.jsx("div",{className:`amx-el-selbox${r===j?" is-editing":""}`,"data-anchor":j,style:{left:`${W.x}px`,top:`${W.y}px`,width:`${W.w}px`,height:`${W.h}px`},children:o.size===1&&r!==j?u.jsxs(u.Fragment,{children:[u.jsx(vl,{anchor:j}),u.jsx(wl,{node:j}),u.jsx(Ia,{node:Pt(j)})]}):null},`sel:${j}`):null}),me&&te?u.jsx("div",{className:`amx-el-selbox${r===we?" is-editing":""}`,"data-main-sel":!0,style:{left:`${te.x}px`,top:`${te.y}px`,width:`${te.w}px`,height:`${te.h}px`},children:o.size===1&&r!==we?u.jsxs(u.Fragment,{children:[u.jsx(vl,{anchor:we}),u.jsx(wl,{node:we}),u.jsx(Ia,{node:we})]}):null}):null,Me.map(j=>{const W=j.box.h*l,ne=W<44?"title":W<60?"summary":"full",he=ne==="title"?Math.max(8,Math.min(12,(W-3)/1.2)):12;return u.jsxs("div",{className:"amx-card-overview","data-card-label":j.anchor,"data-overview-density":ne,style:{left:`${j.box.x}px`,top:`${j.box.y}px`,width:`${j.box.w}px`,height:`${j.box.h}px`,"--amx-overview-inv":String(1/l),"--amx-overview-title-screen":`${he}px`},children:[u.jsx("span",{className:"amx-card-overview-title",children:j.title}),j.detail?u.jsx("span",{className:"amx-card-overview-detail",children:j.detail}):null]},`overview:${j.key}`)}),g?(()=>{const j=Ae(g.from);if(!j)return null;const W=g.over?Ae(g.over):null,ne=W??{x:g.x,y:g.y,w:1,h:1};return u.jsxs(u.Fragment,{children:[u.jsx(Ks,{el:{kind:"connector",id:"~preview",from:{},to:{},label:null},a:j,b:ne,sel:!1,preview:!0}),u.jsx("div",{className:"amx-conn-target",style:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}}),W?u.jsx("div",{className:"amx-conn-target",style:{left:`${W.x}px`,top:`${W.y}px`,width:`${W.w}px`,height:`${W.h}px`}}):null]})})():null,a?(()=>{const j=a.node===we?te:fe.get(a.node),W=fe.get(a.source);if(!j)return null;const ne=3,he=22,qe=a.side==="n"||a.side==="s",et=a.side==="w"?j.x:a.side==="e"?j.x+j.w:j.x+j.w/2,ht=a.side==="n"?j.y:a.side==="s"?j.y+j.h:j.y+j.h/2;return u.jsxs(u.Fragment,{children:[W?u.jsx(Ks,{el:{kind:"connector",id:"~attach",from:{ref:a.source},to:a.node===we?{main:!0}:{ref:a.node},label:null},a:W,b:j,sel:!1,preview:!0}):null,u.jsx("div",{className:`amx-el-attach-target is-${a.rel}`,style:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}}),u.jsx("div",{className:`amx-el-attach is-${a.rel}`,"data-attach":a.side,style:{left:`${a.side==="e"?j.x+j.w-ne:a.side==="w"?j.x:j.x+(j.w-he)/2}px`,top:`${a.side==="s"?j.y+j.h-ne:a.side==="n"?j.y:j.y+(j.h-he)/2}px`,width:`${qe?he:ne}px`,height:`${qe?ne:he}px`}}),u.jsxs("div",{className:`amx-el-attach-label is-${a.rel}`,style:{left:`${et}px`,top:`${ht}px`},children:[a.count&&a.count>1?`${M("canvasel.attach.count",{n:a.count})} · `:"",a.rel==="child"?M("canvasel.attach.child"):M("canvasel.attach.sibling")]})]})})():null,C?.map((j,W)=>u.jsx("div",{className:`amx-el-guide is-${j.dir}`,style:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}},`guide:${W}`)),i?u.jsx("div",{className:"amx-el-marquee",style:{left:`${i.x}px`,top:`${i.y}px`,width:`${i.w}px`,height:`${i.h}px`}}):null]})}const Wu=["nw","ne","sw","se"],Bb=["n","e","s","w",...Wu];function vl({anchor:e}){return u.jsx(u.Fragment,{children:Bb.map(t=>u.jsx("div",{className:`amx-card-size-grip is-${t}`,"data-card-grip":e,"data-card-edge":t},t))})}function Hb({id:e,box:t}){return u.jsx(u.Fragment,{children:Wu.map(n=>u.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 wl({node:e}){const{t}=Bt();return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"amx-el-add is-child","data-add":"child","data-node":e,title:t("canvasel.add.child"),children:"+"}),u.jsx("div",{className:"amx-el-add is-sibling","data-add":"sibling","data-node":e,title:t("canvasel.add.sibling"),children:"+"})]})}const Kb=["n","e","s","w"];function Ia({node:e,box:t}){const{t:n}=Bt(),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 u.jsx(u.Fragment,{children:Kb.map(r=>u.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 Vb({el:e,box:t,sel:n}){const o=Nc(e.color);return u.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:u.jsx("div",{className:"amx-el-frame-bar","data-el":e.id,children:e.title??"Frame"})})}function qb({el:e,box:t,sel:n}){const o=e.kind==="text"?"amx-el-text":e.shape==="ellipse"?"amx-el-ellipse":"amx-el-rect",r=Nc(e.color);return u.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 Ks({el:e,a:t,b:n,sel:o,related:r,tree:s,preview:c}){if(!t||!n)return null;const i=Ib(t,n),a=14,l={x:i.box.x-a,y:i.box.y-a,w:i.box.w+a*2,h:i.box.h+a*2},m=9,g=4.5,C=(L,E)=>{const F=Math.cos(E),U=Math.sin(E);return[`${L.x},${L.y}`,`${L.x-m*F+g*U},${L.y-m*U-g*F}`,`${L.x-m*F-g*U},${L.y-m*U+g*F}`].join(" ")},M=!s&&e.toEnd!=="none",S=!s&&e.fromEnd==="arrow",z=Nc(e.color);return u.jsxs(u.Fragment,{children:[u.jsxs("svg",{className:`amx-el-conn${o?" is-sel":""}${r?" is-related":""}${s?" is-tree":""}${c?" is-preview":""}`,"data-el":e.id,"data-color":z["data-color"],style:{left:`${l.x}px`,top:`${l.y}px`,width:`${l.w}px`,height:`${l.h}px`,...z.style},viewBox:`${l.x} ${l.y} ${l.w} ${l.h}`,children:[r?u.jsx("path",{className:"amx-el-conn-halo",d:i.d}):null,u.jsx("path",{className:"amx-el-conn-core",d:i.d}),M?u.jsx("polygon",{points:C(i.tip,i.ang)}):null,S?u.jsx("polygon",{points:C(i.tail,i.tailAng)}):null]}),e.label?u.jsx("div",{className:`amx-el-label${o?" is-sel":""}`,"data-color":z["data-color"],style:{left:`${i.mid.x}px`,top:`${i.mid.y}px`,...z.style},children:e.label}):null]})}const Vs=e=>typeof e=="number"&&Number.isFinite(e)?e:null,as=e=>typeof e=="string"&&e?e:null,Pa=e=>la(e)?e:null,kl=e=>e==="none"||e==="arrow"?e:null,cs=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 Wb(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 Yb(e){const t=[],n=[],o=[],r=new Map,s=e.pages?[...e.pages].sort():[],c=Array.isArray(e.elements)?e.elements:[],i=new Set,a=[];for(const z of c){if(!z||typeof z!="object"||Array.isArray(z))continue;const L=z,E=as(L.id);if(!E||i.has(E))continue;if(L.type==="connector"){i.add(E),a.push(L);continue}if(L.type!=="shape"&&L.type!=="text"&&L.type!=="frame")continue;const F=Vs(L.x),U=Vs(L.y),q=Vs(L.w),de=Vs(L.h);if(F==null||U==null||q==null||de==null||q<=0||de<=0)continue;i.add(E);const me=`el-${E}`,Ne={x:F,y:U,w:q,h:de};r.set(me,Ne);const be=Pa(L.color);if(L.type==="frame"){const ge=as(L.title);t.push({id:me,type:"group",...cs(Ne),...ge?{label:ge}:{},...be?{color:be}:{}})}else n.push({id:me,type:"text",...cs(Ne),text:typeof L.text=="string"?L.text:"",...be?{color:be}:{}})}for(const z of e.cards){const L=`card-${z.ref}`;r.set(L,z);const E=Pa(z.color),F=Wb(z.md),U=F&&s.length?ys(Hl(F),s,e.sourcePath):null;if(F&&U){const q=F.split("|")[0],de=q.indexOf("#"),me=de>=0?q.slice(de).trim():"";o.push({id:L,type:"file",...cs(z),file:U,...me.length>1?{subpath:me}:{},...E?{color:E}:{}})}else o.push({id:L,type:"text",...cs(z),text:z.md,...E?{color:E}:{}})}const l=[],m=z=>{if(!z||typeof z!="object")return null;const L=z,E=as(L.ref)?`card-${L.ref}`:as(L.id)?`el-${L.id}`:L.main===!0?"main":null;return E&&(r.has(E)||E==="main")?E:null};e.main&&r.set("main",e.main);let g=!1;const C=z=>{const L=r.get(z.fromNode),E=r.get(z.toNode);!L||!E||((z.fromNode==="main"||z.toNode==="main")&&(g=!0),l.push({...z,fromSide:Sl(L,E),toSide:Sl(E,L)}))};for(const z of a){const L=m(z.from),E=m(z.to);if(!L||!E||L===E)continue;const F=kl(z.fromEnd),U=kl(z.toEnd),q=as(z.label),de=Pa(z.color);C({id:`edge-${z.id}`,fromNode:L,toNode:E,...F?{fromEnd:F}:{},...U?{toEnd:U}:{},...q?{label:q}:{},...de?{color:de}:{}})}const M=e.tree&&typeof e.tree=="object"&&!Array.isArray(e.tree)?e.tree:{};for(const z of Object.keys(M)){const L=M[z];if(typeof L!="string"||!L||L===z)continue;const E=L==="m:"?"main":`card-${L}`,F=`card-${z}`;r.has(F)&&C({id:`tree-${z}`,fromNode:E,toNode:F,toEnd:"none"})}const S=[...t,...n];return e.main&&(e.main.md.trim()||g)&&S.push({id:"main",type:"text",...cs(e.main),text:e.main.md}),S.push(...o),{nodes:S,edges:l}}const Ub=e=>`${JSON.stringify(e,null," ")}
691
+ `;function Xb(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 Gb(e,t,n){for(let o=1;o<=50;o++){const r=Xb(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")}Cn({"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 Jb=[{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"}],Cl=[{id:"end",from:"none",to:"arrow",nameKey:"canvasstage.ends.end",icon:u.jsx($h,{size:13})},{id:"start",from:"arrow",to:"none",nameKey:"canvasstage.ends.start",icon:u.jsx(Rh,{size:13})},{id:"both",from:"arrow",to:"arrow",nameKey:"canvasstage.ends.both",icon:u.jsx(Nh,{size:13})},{id:"none",from:"none",to:"none",nameKey:"canvasstage.ends.none",icon:u.jsx(up,{size:13})}],Zb=2,Xs=168,Yu=72,Oa=320,El=12,is=".amx-el-shape, .amx-el-frame-bar",Ml="button, a[href], input, select, textarea",Qb='li[data-item-type="task"], .wikilink';function ev(e,t){const n=e.closest(Qb);return n?n.tagName!=="LI"||t-n.getBoundingClientRect().left<=2:!1}const Fa=e=>e.kind==="connector"?"label":e.kind==="frame"?"title":"text",_a=e=>je(e.kind==="connector"?"canvasstage.textTitle.connector":e.kind==="frame"?"canvasstage.textTitle.frame":"canvasstage.textTitle.element"),qs=e=>[...Tr(Tn(e).filter(t=>t.kind!=="frame"),null).values()],zl=50,Ba=new Set(["rect","ellipse","frame"]),ls={rect:"rect",ellipse:"ellipse",text:"text"};let tv=0;const Al=(e,t,n,o,r,s=Xs)=>om(e,t,n,o,r,s,Yu);function $c(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 Pn(e){return $c(e.state.doc)}const fc=(e,t,n)=>oa(e,t,n);function Uu(e,t,n){const o=$c(e),r=o.findIndex(c=>c.anchor===n);if(r<0)return e.content.size;const s=o[fc(o,r,t)-1];return s.pos+s.node.nodeSize}function Nl(e,t,n,o){const r=$c(e.doc),s=r.findIndex(C=>C.anchor===n);if(s<0)return e;const c=fc(r,s,t),i=r[s].pos,a=r[c-1],l=a.pos+a.node.nodeSize;let m;if(o){const C=r.findIndex(z=>z.anchor===o);if(C<0||C>=s&&C<c)return e;const M=fc(r,C,t);if(s>C&&s<M)return e;const S=r[M-1];m=S.pos+S.node.nodeSize}else if(m=e.doc.content.size,l===m)return e;const g=To.fromArray(r.slice(s,c).map(C=>C.node));return e.delete(i,l).insert(m>l?m-(l-i):m,g)}function cr(e,t){e.dispatch(ea(t).setMeta("amxCanvas",!0))}function Cr(e,t,n=!0){const o=Pn(e);let r=e.state.tr,s=!1;for(const c of o){const i=t.get(c.anchor);i&&(r=r.setNodeMarkup(c.pos,void 0,{...c.node.attrs,...i}),s=!0)}s&&(n?cr(e,r):e.dispatch(r.setMeta("amxCanvas",!0).setMeta("addToHistory",!1)))}function nv(e,t,n,o){const r=Pn(e).find(i=>i.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 Tl(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?To.fromArray(t):void 0}function $l(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"?Jp(e):e.path}const jl="application/x-amx-canvas";let Ha=null;function ov(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 i=c;return!i||typeof i.ref!="string"||!r(i.x)||!r(i.y)||!r(i.w)||i.w<=0?[]:[{ref:i.ref,x:i.x,y:i.y,w:i.w,h:r(i.h)&&i.h>0?i.h:0,...typeof i.color=="string"?{color:i.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 Ka=(e,t)=>({x:e.x-t,y:e.y-t,w:e.w+t*2,h:e.h+t*2}),Rl=(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 rv({hostRef:e,vp:t,elements:n,ghost:o,onCenter:r}){const[,s]=x.useState(0);x.useEffect(()=>{const g=e.current;if(!g)return;let C=0;const M=new Set,S=new ResizeObserver(()=>L()),z=()=>{const F=new Set(g.querySelectorAll(".amx-ucard")),U=g.querySelector(".ProseMirror");U&&F.add(U);for(const q of F)M.has(q)||(S.observe(q,{box:"border-box"}),M.add(q));for(const q of[...M])F.has(q)||(S.unobserve(q),M.delete(q))},L=()=>{cancelAnimationFrame(C),C=requestAnimationFrame(()=>{z(),s(F=>F+1)})},E=new MutationObserver(L);return E.observe(g,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["data-x","data-y","data-w"]}),S.observe(g),L(),()=>{cancelAnimationFrame(C),E.disconnect(),S.disconnect()}},[e]);const c=e.current;if(!c)return null;const i=[];for(const[g,C]of hn(c))i.push({key:Pt(g),kind:"card",box:C});const a=gn(c);a&&i.push({key:we,kind:"main",box:a});const l=Tn(n),m=Tr(l,o);for(const g of l){if(g.kind==="connector")continue;const C=m.get(g.id);C&&i.push({key:xn(g.id),kind:g.kind==="frame"?"frame":"shape",box:C})}return u.jsx(Im,{hostRef:e,vp:t,items:i,onCenter:r})}function sv({path:e,vaultRoot:t=null,active:n,getView:o,main:r,mainStored:s,elements:c,tree:i,onElements:a,onTree:l,onMain:m,timeline:g,histStepRef:C,onCommit:M,saveFile:S,parseMd:z,serializeMd:L,onBlocksDeleted:E,revealSelection:F=0,readOnly:U=!1,notePages:q,exportRef:de,storedMd:me,children:Ne}){const be=x.useRef(null),{t:ge}=Bt(),p=qp(t,e),[fe,ce]=x.useState(()=>yi(p)??{x:0,y:0,z:1}),te=x.useRef(fe);te.current=fe;const[ee,Ie]=x.useState(Pm),[Me,dt]=x.useState(Om),[tt,J]=x.useState(Ii);x.useEffect(()=>Fm(()=>J(Ii())),[]);const[ye,Ae]=x.useState(_m),j=x.useRef(ye);j.current=ye;const[W,ne]=x.useState(Bm),he=x.useRef(W);he.current=W;const[qe,et]=x.useState(null),ht=x.useCallback(d=>{j.current=d,Ae(d),Hm(d)},[]),[Ye,Ht]=x.useState("select"),Ot=x.useRef("select"),Kt=x.useRef(U);Kt.current=U;const Ut=x.useCallback(d=>{Ot.current=d,Ht(d)},[]),[Ze,yn]=x.useState([]),ft=x.useRef([]),pt=x.useCallback(d=>{const N=typeof d=="function"?d(ft.current):d;ft.current=N,yn(N)},[]),[Vt,bn]=x.useState(null),Jt=x.useRef(null),vn=x.useCallback(d=>{Jt.current=d,bn(d)},[]),[jn,jr]=x.useState(null),rn=x.useRef(null),Wn=x.useCallback(d=>{rn.current=d,jr(d)},[]),Zn=x.useRef({held:!1,used:!1}),[pr,Yn]=x.useState(!1);x.useEffect(()=>{const d=be.current;if(!jn||!d)return;const N=d.dataset.amxDragscope;if(!N)return;const $=document.createElement("style");return $.textContent=jn===we?`.amx-stage[data-amx-dragscope="${N}"] .ProseMirror{cursor:text;}`:`.amx-stage[data-amx-dragscope="${N}"] .amx-ucard[data-anchor="${CSS.escape(jn)}"]{cursor:text;}`,document.head.appendChild($),()=>$.remove()},[jn]);const Un=x.useRef(0),[Go,vo]=x.useState(null),[Rr,zn]=x.useState(null),[En,Fn]=x.useState(null),[lt,Mt]=x.useState(null),[co,wo]=x.useState(null),[Jo,jo]=x.useState(!1),Xn=x.useRef(0),Rn=x.useCallback(()=>{cancelAnimationFrame(Xn.current),Xn.current=0,jo(!1)},[]);x.useEffect(()=>()=>cancelAnimationFrame(Xn.current),[]);const wn=x.useRef({raf:0,animations:[]}),h=x.useCallback(()=>{cancelAnimationFrame(wn.current.raf),wn.current.raf=0;const d=wn.current.animations.splice(0);for(const N of d)N.cancel()},[]),A=x.useCallback(d=>{const N=be.current;h(),!(!N||!d.length||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(wn.current.raf=requestAnimationFrame(()=>{wn.current.raf=0;let $=0;const K=B=>{wn.current.animations.push(B);const _=()=>{wn.current.animations=wn.current.animations.filter(Y=>Y!==B)};B.addEventListener("finish",_,{once:!0}),B.addEventListener("cancel",_,{once:!0})};for(const B of d){const _=N.querySelector(`.amx-ucard[data-anchor="${CSS.escape(B.anchor)}"]`),Y=Math.hypot(B.x,B.y);if(!_||Y<1)continue;const se=Math.min(126,Math.max(0,B.depth-1)*42),xe=Math.round(Math.max(420,Math.min(620,360+Y*.34)));$=Math.max($,se+xe);const ae=_.animate([{transform:`translate(${-B.x}px, ${-B.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(${B.x*.035}px, ${B.y*.035}px) scale(1.003)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-B.x*.008}px, ${-B.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:xe,delay:se,fill:"backwards"});ae.id="amx-card-arrange",K(ae)}if($>0)for(const B of N.querySelectorAll(".amx-el-conn, .amx-el-label")){const _=B.animate([{opacity:.12,offset:0},{opacity:.12,offset:.68},{opacity:1,offset:1,easing:"ease-out"}],{duration:$,fill:"backwards"});_.id="amx-card-arrange-line",K(_)}}))},[h]),P=x.useCallback((d,N)=>{const $=be.current,K=Math.hypot(N.x,N.y);h(),!(!$||K<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(wn.current.raf=requestAnimationFrame(()=>{wn.current.raf=0;const B=xe=>{wn.current.animations.push(xe);const ae=()=>{wn.current.animations=wn.current.animations.filter(re=>re!==xe)};xe.addEventListener("finish",ae,{once:!0}),xe.addEventListener("cancel",ae,{once:!0})},_=Math.round(Math.max(400,Math.min(520,350+K*.42))),Y=$.querySelector(`.amx-ucard[data-anchor="${CSS.escape(d)}"]`);if(Y){const xe=Y.animate([{transform:`translate(${-N.x}px, ${-N.y}px) scale(1.012)`,opacity:.94,boxShadow:"0 12px 32px rgb(0 0 0 / 24%)",offset:0,easing:"ease-in"},{transform:`translate(${-N.x*.54}px, ${-N.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(${N.x*.05}px, ${N.y*.05}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-N.x*.012}px, ${-N.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:_,fill:"none"});xe.id="amx-card-attach",B(xe)}const se=$.querySelector(`.amx-el-conn[data-el="${CSS.escape(`t:${d}`)}"]`);if(se){const xe=se.animate([{opacity:0,offset:0},{opacity:0,offset:.56},{opacity:1,offset:1,easing:"ease-out"}],{duration:_,fill:"backwards"});xe.id="amx-card-attach-line",B(xe)}}))},[h]);x.useEffect(()=>h,[h]);const[I,H]=x.useState(null),[X,ie]=x.useState(null);x.useEffect(()=>{Vt||H(null)},[Vt]);const G=new Set(Ze),oe=x.useRef(!yi(p));x.useEffect(()=>{n&&Wp(p,fe)},[p,fe,n]),x.useLayoutEffect(()=>{const d=be.current;!n||!jn||!d||!document.activeElement||!d.contains(document.activeElement)||fp()},[n,jn,fe]);const V=x.useRef({getView:o,onCommit:M,onElements:a,onTree:l,onMain:m,timeline:g,elements:c,tree:i,main:r,mainStored:s,saveFile:S,parseMd:z,serializeMd:L,onBlocksDeleted:E,notePages:q,path:e,storedMd:me});V.current={getView:o,onCommit:M,onElements:a,onTree:l,onMain:m,timeline:g,elements:c,tree:i,main:r,mainStored:s,saveFile:S,parseMd:z,serializeMd:L,onBlocksDeleted:E,notePages:q,path:e,storedMd:me};const ze=Tn(c),Ke=d=>{if(!d)return null;const N={x:d.x,y:d.y,w:d.w,...typeof d.h=="number"&&d.h>0?{h:d.h}:{}};return N.x!==0||N.y!==0||N.w!==qo||(N.h??0)>0?N:null},Ve=()=>{const d=V.current;return{e:Ho(d.elements),t:qt(d.tree),m:Ke(d.mainStored?d.main:null)}},Be=x.useRef(null),We=x.useRef({past:[],future:[]}),Qe=()=>We.current;x.useEffect(()=>{const d=Ve(),N=JSON.stringify(d);if(!(Be.current!==null&&N===Be.current)){if(Be.current!==null)try{const $=JSON.parse(Be.current),K=(_,Y)=>{let se=$.t[_];const xe=new Set([_]);for(;typeof se=="string"&&se&&!xe.has(se);){if(se===Y)return!0;xe.add(se),se=$.t[se]}return!1};if(JSON.stringify(d.e)===JSON.stringify($.e)&&JSON.stringify(d.m)===JSON.stringify($.m)&&Object.keys(d.t).length<=Object.keys($.t).length&&Object.keys(d.t).every(_=>typeof $.t[_]<"u"&&(JSON.stringify(d.t[_])===JSON.stringify($.t[_])||K(_,d.t[_])))){Be.current=N;return}}catch{}Be.current=N,We.current={past:[],future:[]},V.current.timeline.log.length=0,V.current.timeline.future.length=0}},[e,c,i,r,s]);const Xe=x.useCallback((d,N)=>{const $=V.current,K=Ve(),B=JSON.stringify(K),_=JSON.stringify({e:d.e??K.e,t:d.t??K.t,m:d.m?Ke(d.m):K.m});if(_!==B){if(N?.snap!==!1){const Y=Qe();Y.past.push(B),Y.past.length>zl&&Y.past.shift(),Y.future.length=0,$.timeline.log.push("fm"),$.timeline.future.length=0;const se=$.getView();se&&se.dispatch(ea(se.state.tr))}Be.current=_,d.e&&$.onElements(d.e),d.t&&$.onTree(d.t),d.m&&$.onMain(d.m)}},[e]),st=x.useCallback(d=>{const N=Ho(V.current.elements),$=d(N);$!==N&&Xe({e:$})},[Xe]),Xt=x.useCallback(d=>{const N=Qe(),$=d==="undo"?N.past:N.future,K=d==="undo"?N.future:N.past,B=$.pop();if(B==null)return!1;const _=V.current;K.push(JSON.stringify(Ve()));const Y=JSON.parse(B);return Be.current=B,_.onElements(Y.e),_.onTree(Y.t),_.onMain(Y.m??{x:0,y:0,w:qo}),!0},[e]),Dt=x.useCallback(()=>{const d=Qe();d.past.push(JSON.stringify(Ve())),d.past.length>zl&&d.past.shift(),d.future.length=0;const N=V.current.timeline;N.log.push("fm"),N.future.length=0},[e]),zt=x.useCallback(d=>{const N=qt(V.current.tree);return d.some($=>typeof N[$]<"u"||Object.keys(N).some(K=>N[K]===$))},[]),Ue=x.useCallback(()=>{const d=V.current.timeline,N=d.log.length;if(N<2)return;const $=d.log[N-2],K=d.log[N-1];($==="pm"&&K==="fm"||$==="fm"&&K==="pm")&&d.log.splice(N-2,2,"pair")},[]),Ln=x.useCallback(d=>{const N=V.current.timeline,$=d==="undo"?N.log:N.future,K=d==="undo"?N.future:N.log,B=()=>{const se=V.current.getView();return!!se&&(d==="undo"?Ya(se.state):af(se.state))>0},_=()=>(d==="undo"?Qe().past:Qe().future).length>0,Y=()=>{const se=V.current.getView();return!!se&&(d==="undo"?Ua:Ul)(se.state,se.dispatch)};for(;$.length;){const se=$[$.length-1];if($.pop(),se==="pair"){if(!B()||!_())continue;return Xt(d),Y(),K.push(se),!0}if(se==="fm"){if(Xt(d))return K.push(se),!0;continue}if(Y())return K.push("pm"),!0}return Y()},[Xt]);x.useEffect(()=>{if(C)return C.current=Ln,()=>{C.current===Ln&&(C.current=null)}},[C,Ln]);const Ft=x.useCallback((d,N)=>{const $=be.current,K=$?.getBoundingClientRect(),{x:B,y:_,z:Y}=te.current;if(!$||!K)return{x:0,y:0};const se=Mn($)||1;return{x:((d-K.left)/se-B)/Y,y:((N-K.top)/se-_)/Y}},[]),ln=x.useCallback(()=>{Rn();const d=be.current,N=o();if(!d||!N)return;const $=[...d.querySelectorAll(".amx-ucard, .amx-el-shape, .amx-el-frame, .amx-el-frame-bar, .amx-el-conn, .amx-el-label"),N.dom].map(T=>T.getBoundingClientRect());if(!$.length)return;const{x:K,y:B,z:_}=te.current,Y=d.getBoundingClientRect(),se=Mn(d)||1,xe=(T,y)=>(T/se-y)/_,ae=Math.min(...$.map(T=>xe(T.left-Y.left,K))),re=Math.min(...$.map(T=>xe(T.top-Y.top,B))),Te=Math.max(...$.map(T=>xe(T.right-Y.left,K))),Pe=Math.max(...$.map(T=>xe(T.bottom-Y.top,B))),f=Te-ae,v=Pe-re;if(f<=0||v<=0)return;const k=48,b=Math.max(Qr,Math.min(1,Math.min((Y.width/se-k*2)/f,(Y.height/se-k*2)/v)));ce({z:b,x:(Y.width/se-f*b)/2-ae*b,y:(Y.height/se-v*b)/2-re*b})},[o,Rn]),io=x.useCallback(d=>{Rn();const N=be.current;if(!N)return;const{x:$,y:K,z:B}=te.current,_=Math.max(Qr,Math.min(Ds,B*d));if(_===B)return;const Y=Mn(N)||1,se=N.getBoundingClientRect().width/Y/2,xe=N.getBoundingClientRect().height/Y/2;ce({z:_,x:se-(se-$)*_/B,y:xe-(xe-K)*_/B})},[Rn]),lo=x.useCallback((d,N)=>{Rn();const $=be.current;if(!$)return;const K=Mn($)||1,B=$.getBoundingClientRect(),_=te.current.z;ce({z:_,x:B.width/K/2-d*_,y:B.height/K/2-N*_})},[Rn]);x.useEffect(()=>{const d=be.current;if(!U||!d)return;const N=()=>{const $=V.current.getView(),K=document.getSelection();if(!$||!K||K.isCollapsed||!K.rangeCount)return;const B=K.getRangeAt(0),_=xe=>$.dom.contains(xe.nodeType===3?xe.parentNode:xe),Y=_(B.startContainer),se=_(B.endContainer);if(!(!Y&&!se))try{const xe=$.state.doc,ae=Y?$.posAtDOM(B.startContainer,B.startOffset):0,re=se?$.posAtDOM(B.endContainer,B.endOffset):xe.content.size,Te=Le.between(xe.resolve(Math.min(ae,re)),xe.resolve(Math.max(ae,re)));Te.eq($.state.selection)||$.dispatch($.state.tr.setSelection(Te))}catch{}};return d.addEventListener("copy",N,!0),()=>d.removeEventListener("copy",N,!0)},[U]),x.useEffect(()=>{const d=be.current;if(!n||!d)return;const N=$=>{const K=$.detail?.rect;if(!K)return;const B=Ft(K.left+K.width/2,K.top+K.height/2);lo(B.x,B.y),$.preventDefault()};return d.addEventListener("amx-reveal",N),()=>d.removeEventListener("amx-reveal",N)},[n,Ft,lo]);const Zo=x.useRef(ln);Zo.current=ln,x.useEffect(()=>{if(!n||!oe.current)return;oe.current=!1;const d=setTimeout(()=>Zo.current(),220);return()=>clearTimeout(d)},[n]),x.useEffect(()=>{n||(pt([]),Ut("select"),vn(null),Mt(null),wo(null),Wn(null))},[n]),x.useEffect(()=>{if(!lt)return;const d=N=>{N.target?.closest?.(".ctx-menu")||Mt(null)};return window.addEventListener("pointerdown",d,!0),window.addEventListener("contextmenu",d,!0),()=>{window.removeEventListener("pointerdown",d,!0),window.removeEventListener("contextmenu",d,!0)}},[lt]);const _n=x.useCallback(d=>{const N=new Map;for(const[K,B]of hn(be.current))N.set(Pt(K),B);for(const[K,B]of Tr(Tn(V.current.elements),d))N.set(xn(K),B);const $=gn(be.current);return $&&N.set(we,$),N},[]),mr=x.useRef(!1);x.useEffect(()=>()=>{mr.current=!0},[]);const Ro=x.useCallback(async(d,N,$)=>{const K=Tn(V.current.elements).find(Y=>Y.id===d);if(!K)return;const B=(K.kind==="connector"?K.label:K.kind==="frame"?K.title:K.text)??"",_=await Ga($,B);_==null||mr.current||Tn(V.current.elements).some(Y=>Y.id===d)&&st(Y=>kx(Y,d,N,_.trim()))},[st]),Qo=x.useCallback((d,N)=>{const $=V.current,K=$.getView(),B=new Set(d.filter(ae=>ae.startsWith("c:")).map(it));let _=!1;if(K&&B.size){const ae=N??"",re=new Map;for(const Te of Pn(K))B.has(Te.anchor)&&String(Te.node.attrs.color??"")!==ae&&re.set(Te.anchor,{color:ae});re.size&&(Cr(K,re),$.onCommit(),_=!0)}const Y=new Set(d.filter(ae=>ae.startsWith("e:")).map(it));if(!Y.size)return;const se=Ho(V.current.elements),xe=zx(se,Y,N);xe!==se&&(Xe({e:xe}),_&&Ue())},[Xe,Ue]),ko=x.useCallback((d,N,$,K,B)=>{const _=V.current.getView(),Y=_?.state.schema.nodes.amadeusCanvasCard,se=_?.state.schema.nodes.paragraph;if(!_||!Y||!se)return null;const xe=$o(_.state.doc),ae={x:d,y:N,w:en,h:80},re=[...hn(be.current).values(),...qs(V.current.elements)],Te=gn(be.current);Te&&re.push(Te);const Pe=ts([ae],re),f=d+Pe.x,v=N+Pe.y,k=B?.childCount?B:se.create(null,K?_.state.schema.text(K):void 0),b=Y.createAndFill({anchor:xe,x:Math.round(f),y:Math.round(v),w:en,h:0},k);if(!b)return null;const T=$?Uu(_.state.doc,qt(V.current.tree),$):_.state.doc.content.size;return cr(_,_.state.tr.insert(T,b)),V.current.onCommit(xe),pt([Pt(xe)]),!K&&!B?.childCount&&Q.current.enterNodeEdit(Pt(xe)),xe},[_n]),Bn=x.useCallback((d,N)=>{const $=V.current.saveFile;$&&d.forEach((K,B)=>{const _=K.name||je("canvasstage.upload.fileN",{n:B+1}),Y=je("canvasstage.upload.uploading",{name:_}),se=Q.current.addCardAt(N.x-en/2+B*24,N.y-24+B*24,void 0,Y);se&&$(K).then(xe=>{const ae=V.current.getView(),re=ae?Pn(ae).find(Te=>Te.anchor===se&&Te.node.textContent===Y)??Pn(ae).find(Te=>Te.node.textContent===Y):null;!ae||!re||(xe?(nv(ae,re.anchor,xe,Y),V.current.onCommit()):Q.current.removeSel([Pt(re.anchor)]))})})},[]),Lo=x.useCallback((d,N,$=0)=>{const K=d.trim();if(!K)return null;const B=V.current.parseMd?.(K)??null;return Q.current.addCardAt(N.x-en/2+$*24,N.y-24+$*24,void 0,K,Tl(B))},[]),Qn=x.useCallback(d=>{const N=qt(V.current.tree),$=d(N);return $===N?!1:(Xe({t:$}),!0)},[Xe]),Hn=x.useCallback(d=>d===we?gn(be.current):hn(be.current).get(d)??null,[]),hr=x.useCallback((d,N,$,K,B=0)=>{const _=Hn(d);if(!_)return null;const Y=qt(V.current.tree),se=Y[d],xe=N==="child"?d:typeof se=="string"&&se?se:"",ae=(xe?Mr(Y,xe):[d]).map(Hn).filter(Boolean),re=80,Te=32,f=N==="child"?$==="w"?_.x-K-re:_.x+_.w+re:ae.length?Math.min(...ae.map(y=>y.x)):_.x,v=ae.length?Math.min(...ae.map(y=>y.y))-Te-B:_.y,k=ae.length?Math.max(...ae.map(y=>y.y+y.h))+Te:_.y,b=$==="n"?v:k,T=N==="child"?Mr(Y,d).length?b:_.y:b;return{parent:xe,x:Math.round(f),y:Math.round(T)}},[Hn]),Gn=x.useCallback((d,N,$,K=80)=>{const B=Hn(d);if(!B)return null;const _=qt(V.current.tree),Y=_[d],se=N==="child"?d:typeof Y=="string"&&Y?Y:"",xe=N==="child"?B:se?Hn(se):B;if(!xe)return null;const ae=V.current.getView(),re=ae?Pn(ae).map(Z=>Z.anchor):[],Pe=(se?Mr(_,se):N==="child"?Mr(_,d):re.filter(Z=>typeof _[Z]!="string"||!_[Z])).map(Z=>Hn(Z)).filter(Boolean),f=xe.x+xe.w/2,v=[...hn(be.current).values(),...qs(V.current.elements)],k=gn(be.current);k&&v.push(k);const b=80,T=32;let y=null;for(const Z of[1,-1]){const ue=Pe.filter(mt=>(mt.x+mt.w/2-f)*Z>0),Ce=Z>0?xe.x+xe.w+b:xe.x-b-$,_e=ue.length?Math.max(...ue.map(mt=>mt.y+mt.h))+T:xe.y,Ge=ts([{x:Ce,y:_e,w:$,h:K}],v,{x:Z,y:0}),ct=Math.hypot(Ge.x,Ge.y)*100+ue.length*32+(Z<0?6:0);(!y||ct<y.score)&&(y={x:Ce+Ge.x,y:_e+Ge.y,score:ct})}return y?{parent:se,x:Math.round(y.x),y:Math.round(y.y)}:null},[_n,Hn]),So=x.useCallback((d,N)=>{const $=Gn(d,N,en);if(!$)return;const K=ko($.x,$.y,$.parent||void 0);K&&$.parent&&Qn(B=>qr(B,K,$.parent))&&Ue()},[Gn,ko,Qn,Ue]),uo=x.useCallback((d,N)=>{const $=[...new Set(typeof d=="string"?[d]:d)],K=new Set($),B=hn(be.current),_=$[0],Y=_?B.get(_):null;if(!Y||!_)return null;const se=hr(N.node,N.rel,N.side,Y.w,Y.h);if(!se)return null;const xe=qt(V.current.tree),ae=$.filter(Z=>!(typeof xe[Z]=="string"&&K.has(xe[Z])));if(!ae.length||ae.includes(se.parent))return null;const re=$.flatMap(Z=>{const ue=B.get(Z);return ue?[{anchor:Z,box:ue}]:[]});if(!re.length)return null;const Te=se.x-Y.x,Pe=se.y-Y.y,f=re.map(({box:Z})=>({...Z,x:Z.x+Te,y:Z.y+Pe})),v=[...B].filter(([Z])=>!K.has(Z)).map(([,Z])=>Z),k=gn(be.current);k&&v.push(k),v.push(...qs(V.current.elements));const b=ts(f,v,{x:Te,y:Pe}),T=Te+b.x,y=Pe+b.y;return{sources:$,sourceSet:K,boxes:B,primary:_,roots:ae,moving:re,slot:se,dx:T,dy:y}},[hr]),qn=x.useCallback((d,N)=>{const $=[...new Set(typeof d=="string"?[d]:d)],K=$[0];if(!K)return null;const B=new Set($),_=48,Y=k=>Math.min(38,Math.max(18,k*.32)),se=qt(V.current.tree),xe=k=>{let b=k;const T=new Set;for(;typeof b=="string"&&b&&!T.has(b);){if(B.has(b))return!0;T.add(b),b=se[b]}return!1},re=[...hn(be.current)].filter(([k])=>!B.has(k)&&!xe(k)),Te=gn(be.current);Te&&re.push([we,Te]);let Pe=null;for(const[k,b]of re){if(N.x<b.x-_||N.x>b.x+b.w+_||N.y<b.y-_||N.y>b.y+b.h+_)continue;const T=Y(b.w),y=Y(b.h),Z=18,ue=[["e",Math.abs(b.x+b.w-N.x),N.x>b.x+b.w?_:T,N.y>=b.y-Z&&N.y<=b.y+b.h+Z],["w",Math.abs(N.x-b.x),N.x<b.x?_:T,N.y>=b.y-Z&&N.y<=b.y+b.h+Z],["s",Math.abs(b.y+b.h-N.y),N.y>b.y+b.h?_:y,N.x>=b.x-Z&&N.x<=b.x+b.w+Z],["n",Math.abs(N.y-b.y),N.y<b.y?_:y,N.x>=b.x-Z&&N.x<=b.x+b.w+Z]];for(const[Ce,_e,He,Ge]of ue){if(!Ge||_e>He)continue;const ct=_e/Math.max(1,He);(!Pe||ct<Pe.score)&&(Pe={node:k,side:Ce,rel:Ce==="e"||Ce==="w"?"child":"sibling",score:ct})}}if(!Pe)return null;const f={node:Pe.node,side:Pe.side,rel:Pe.rel};return uo($,f)?{source:K,count:$.length,...f}:null},[uo]),er=x.useCallback((d,N)=>{const $=V.current.getView(),K=uo(d,N);if(!$||!K)return!1;const{sources:B,sourceSet:_,boxes:Y,primary:se,roots:xe,moving:ae,slot:re,dx:Te,dy:Pe}=K,f=qt(V.current.tree);let v=qt(f);for(const T of xe)if(delete v[T],re.parent){const y=qr(v,T,re.parent);if(y===v)return!1;v=y}let k=$.state.tr;for(const T of Pn($)){const y=Y.get(T.anchor);_.has(T.anchor)&&y&&(k=k.setNodeMarkup(T.pos,void 0,{...T.node.attrs,x:Math.round(y.x+Te),y:Math.round(y.y+Pe)}))}const b=xe.filter(T=>(typeof f[T]=="string"?f[T]:"")!==re.parent);for(const T of b)k=Nl(k,v,T,re.parent);return cr($,k),V.current.onCommit(),b.length&&Qn(y=>{let Z=qt(y);for(const ue of xe)delete Z[ue],re.parent&&(Z=qr(Z,ue,re.parent));return Z})&&Ue(),B.length===1?P(se,{x:Te,y:Pe}):A(ae.map(({anchor:T})=>({anchor:T,x:Te,y:Pe,depth:xe.includes(T)?1:2}))),pt(B.map(Pt)),!0},[uo,Qn,Ue,A,P]),Do=x.useCallback((d,N)=>{const $=qt(V.current.tree);if($[d]===N)return;const K=qr($,d,N);if(K===$)return;const B=V.current.getView();let _=!1;if(B){const Y=Nl(B.state.tr,K,d,N);Y.steps.length&&(cr(B,Y),_=!0)}Xe({t:K}),_&&Ue()},[Xe,Ue]),gr=x.useCallback((d,N,$)=>{const K=Y=>Y===we?we:Y.startsWith("c:")?it(Y):null,B=K(d),_=K(N);B&&_&&_!==we&&!$?Do(_,B):st(Y=>bx(Y,d,N))},[Do,st]),xr=x.useCallback((d,N,$)=>{st(K=>vx(K,new Set(d),{fromEnd:N,toEnd:$}))},[st]),Co=x.useCallback(async()=>{const d=V.current.getView(),N=be.current;if(!d||!N||!n)return;const $=V.current.storedMd,K=re=>$?.(re.content)?.trim()||re.textBetween(0,re.content.size,`
692
+
693
+ `),B=hn(N),_=Pn(d).map(re=>{const Te=re.node.attrs,Pe=B.get(re.anchor)??{x:Number(Te.x)||0,y:Number(Te.y)||0,w:Number(Te.w)||en,h:Number(Te.h)||80};return{ref:re.anchor,...Pe,color:Te.color,md:K(re.node)}}),Y=[];d.state.doc.forEach(re=>{re.type.name!=="amadeusCanvasCard"&&Y.push(re)});const se=gn(N),xe=Y.length?$?.(To.fromArray(Y))?.trim()??"":"",ae=Yb({cards:_,main:se?{...se,md:xe}:null,elements:V.current.elements,tree:V.current.tree,pages:V.current.notePages?.(),sourcePath:e});try{const re=await Gb(on,e,Ub(ae));bi({text:je("canvasstage.export.done",{path:re}),level:"success"})}catch(re){bi({text:je("canvasstage.export.failed",{e:Yp(re)}),level:"error"})}},[n,e]);x.useEffect(()=>{if(!de||!n||U)return;const d=()=>{Co()};return de.current=d,()=>{de.current===d&&(de.current=null)}},[de,n,U,Co]);const Eo=x.useCallback((d,N,$,K)=>{let B="";st(_=>(B=hs(_,"s"),[..._,K?Cu(B,d,K):yx(B,d,N,$)])),B&&pt([xn(B)])},[st]),fo=x.useCallback((d,N,$=480,K=320)=>{let B="";st(_=>(B=hs(_,"f"),[..._,Ex(B,d,N,$,K)])),B&&pt([xn(B)])},[st]),Io=x.useCallback(d=>{const N=_n(null),$=d.map(Y=>N.get(Y)).filter(Y=>!!Y);if(!$.length)return;const K=32,B=Math.min(...$.map(Y=>Y.x))-K,_=Math.min(...$.map(Y=>Y.y))-K;fo(B,_,Math.max(...$.map(Y=>Y.x+Y.w))+K-B,Math.max(...$.map(Y=>Y.y+Y.h))+K-_)},[_n,fo]),Mo=x.useCallback(d=>{const N=Tn(V.current.elements),$=d.filter(_=>_.startsWith("e:")).map(_=>N.find(Y=>Y.id===it(_))).filter(_=>_?.kind==="frame");if(!$.length)return d;const K=_n(null),B=new Set(d);for(const _ of $)for(const[Y,se]of K)B.has(Y)||se.x>=_.x&&se.y>=_.y&&se.x+se.w<=_.x+_.w&&se.y+se.h<=_.y+_.h&&B.add(Y);return[...B]},[_n]),Zt=x.useCallback((d,N)=>{const $=d.filter(ae=>ae.startsWith("e:")).map(it),K=d.filter(ae=>ae.startsWith("c:")).map(it),B=d.filter(ae=>ae.startsWith("t:")).map(it),_=K.length?V.current.getView():null,Y=new Set(K),se=_?Pn(_).filter(ae=>Y.has(ae.anchor)).sort((ae,re)=>re.pos-ae.pos):[],xe=se.length>0&&($.length>0||B.length>0||zt(K));if(xe&&Dt(),B.length){const ae=qt(V.current.tree),re=qt(ae);let Te=!1;for(const Pe of B)typeof re[Pe]<"u"&&(delete re[Pe],Te=!0);Te&&Xe({t:re},xe?{snap:!1}:void 0)}if($.length){const ae=Ho(V.current.elements),re=gx(ae,new Set($));re!==ae&&Xe({e:re},xe?{snap:!1}:void 0)}if(_&&se.length){let ae=_.state.tr;for(const re of se)ae=ae.delete(re.pos,re.pos+re.node.nodeSize);cr(_,ae),N?.assets!==!1&&V.current.onBlocksDeleted?.(To.from(se.map(re=>re.node).reverse())),V.current.onCommit(),xe&&Ue()}pt([])},[Xe,Dt,zt,Ue]),eo=x.useCallback(d=>{const N=V.current.getView(),$=new Set(Mo(d).filter(b=>b!==we&&!b.startsWith("t:"))),K=new Set([...$].filter(b=>b.startsWith("c:")).map(it)),B=N?Pn(N).filter(b=>K.has(b.anchor)):[],_=new Set(B.map(b=>b.anchor)),Y=Ho(V.current.elements),se=b=>{const T=b&&typeof b=="object"?b.id:null;return typeof T=="string"&&T?T:null},xe=b=>!!b&&typeof b=="object"&&b.type==="connector",ae=Y.filter(b=>!xe(b)&&$.has(xn(se(b)??""))),re=new Set(ae.map(se)),Te=b=>{const T=sa(b);return!!T&&(T.ref?_.has(T.ref):T.id?re.has(T.id):!1)},Pe=Y.filter(b=>xe(b)&&se(b)&&Te(b.from)&&Te(b.to)),f=qt(V.current.tree),v=[..._].flatMap(b=>typeof f[b]=="string"&&_.has(f[b])?[[b,f[b]]]:[]);if(!B.length&&!ae.length&&!Pe.length)return null;const k=[...ae,...Pe];return{cards:B,els:k,tree:v,keys:[...B.map(b=>Pt(b.anchor)),...k.map(b=>xn(se(b)))]}},[Mo]),Nt=x.useCallback((d,N,$,K,B)=>{const _=V.current,Y=_.getView(),se=Y?.state.schema.nodes.amadeusCanvasCard,xe=Y?.state.schema.nodes.paragraph;if(!Y||!se||!xe)return;const ae=new Map,re=[];let Te=Y.state.tr;for(const ue of d){const Ce=$o(Te.doc),_e=Math.round(ue.x+K),He=Math.round(ue.y+B);let Ge=null;if(ue.node&&ue.node.type===se)Ge=se.create({...ue.node.attrs,anchor:Ce,x:_e,y:He},ue.node.content);else{const ct=Tl(ue.md?.trim()?_.parseMd?.(ue.md.trim())??null:null)??xe.create(null,ue.md?.trim()?Y.state.schema.text(ue.md.trim()):void 0);Ge=se.createAndFill({anchor:Ce,x:_e,y:He,w:Math.round(ue.w)||en,h:Math.round(ue.h)||0,color:typeof ue.color=="string"?ue.color:""},ct)}Ge&&(Te=Te.insert(Te.doc.content.size,Ge),ae.set(ue.ref,Ce),re.push(Ce))}const Pe=re.length>0;Pe&&(cr(Y,Te),re.forEach(ue=>_.onCommit(ue)));const f=Ho(V.current.elements),v=new Map,k=[],b=ue=>ue.type==="frame"?"f":ue.type==="connector"?"e":"s",T=[];for(const ue of N){const Ce=ue;if(typeof Ce.id!="string"||!Ce.id)continue;if(Ce.type==="connector"){T.push(Ce);continue}const _e=hs(f,b(Ce));v.set(Ce.id,_e),f.push({...Ce,id:_e,...typeof Ce.x=="number"?{x:Math.round(Ce.x+K)}:{},...typeof Ce.y=="number"?{y:Math.round(Ce.y+B)}:{}}),k.push(_e)}const y=ue=>{const Ce=sa(ue);if(!Ce)return null;const _e=ue;if(Ce.ref){const He=ae.get(Ce.ref);return He?{..._e,ref:He}:null}if(Ce.id){const He=v.get(Ce.id);return He?{..._e,id:He}:null}return null};for(const ue of T){const Ce=y(ue.from),_e=y(ue.to);if(!Ce||!_e)continue;const He=hs(f,"e");f.push({...ue,id:He,from:Ce,to:_e}),k.push(He)}let Z=null;for(const[ue,Ce]of $){const _e=ae.get(ue),He=ae.get(Ce);if(!_e||!He)continue;const Ge=qr(Z??qt(V.current.tree),_e,He);Ge!==Z&&(Z=Ge)}(k.length||Z)&&(Xe({...k.length?{e:f}:{},...Z?{t:Z}:{}}),Pe&&Ue()),pt([...re.map(Pt),...k.map(xn)])},[Xe,Ue]),nn=x.useCallback((d,N)=>{d.clearData();const $=eo(N);if(!$)return Ha=null,d.setData("text/plain",""),null;const K=V.current.serializeMd,B=$.cards.map(ae=>K?.(ae.node.content)?.trim()||ae.node.textBetween(0,ae.node.content.size,`
694
+
695
+ `)),_=$.els.flatMap(ae=>{const re=ae,Te=re.type==="connector"?re.label:re.type==="frame"?re.title:re.text;return typeof Te=="string"&&Te.trim()?[Te.trim()]:[]});d.setData("text/plain",[...B,..._].join(`
696
+
697
+ `));const Y=`t${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,se=$.cards.map(ae=>{const re=ae.node.attrs;return{ref:ae.anchor,x:Number(re.x)||0,y:Number(re.y)||0,w:Number(re.w)||en,h:Number(re.h)||0,...typeof re.color=="string"&&re.color?{color:re.color}:{}}}),xe={token:Y,mds:B,cards:se,...$.els.length?{els:$.els}:{},...$.tree.length?{tree:$.tree}:{}};try{d.setData(jl,JSON.stringify(xe))}catch{}return Ha={token:Y,nodes:$.cards.map(ae=>ae.node)},Un.current=0,$},[eo]),R=x.useCallback((d,N)=>{const $=V.current.getView();if(!$)return!1;const K=Ha,B=!!K&&K.token===d.token&&(K.nodes.length===0||K.nodes[0].type===$.state.schema.nodes.amadeusCanvasCard);let _;if(B&&K)_=K.nodes.map(ae=>({ref:String(ae.attrs.anchor),x:Number(ae.attrs.x)||0,y:Number(ae.attrs.y)||0,w:Number(ae.attrs.w)||en,h:Number(ae.attrs.h)||0,node:ae}));else if(d.cards)_=d.cards.map((ae,re)=>({...ae,md:d.mds[re]}));else{const ae=d.mds.filter(re=>re.trim());return ae.length?(ae.forEach((re,Te)=>Q.current.addCardMd(re,N,Te)),!0):!1}const Y=d.els??[],se=_.map(ae=>ae.x),xe=_.map(ae=>ae.y);for(const ae of Y){const re=ae;typeof re.x=="number"&&typeof re.y=="number"&&(se.push(re.x),xe.push(re.y))}return se.length?(Nt(_,Y,d.tree??[],N.x-Math.min(...se),N.y-Math.min(...xe)),!0):!1},[Nt]),O=x.useCallback(d=>{const N=eo(d);N&&Nt(N.cards.map($=>({ref:$.anchor,x:Number($.node.attrs.x)||0,y:Number($.node.attrs.y)||0,w:Number($.node.attrs.w)||en,h:Number($.node.attrs.h)||0,node:$.node})),N.els,N.tree,vi,vi)},[eo,Nt]),pe=x.useCallback(d=>{const N=$=>{$.clipboardData&&($.preventDefault(),$.stopImmediatePropagation(),nn($.clipboardData,d))};document.addEventListener("copy",N,{capture:!0,once:!0});try{document.execCommand("copy")}finally{document.removeEventListener("copy",N,{capture:!0})}be.current?.focus({preventScroll:!0})},[nn]),ve=x.useCallback((d,N)=>{const $=V.current.getView();if(!$||d!==we&&!d.startsWith("c:"))return;let K=null,B=null;if(d===we)$.state.doc.forEach((_,Y)=>{K==null&&_.type.name!=="amadeusCanvasCard"&&(K=Math.min($.state.doc.content.size,Y+_.nodeSize-1))}),B=_=>{const Y=$.state.doc.resolve(_);for(let se=Y.depth;se>0;se--)if(Y.node(se).type.name==="amadeusCanvasCard")return!1;return!0};else{const _=Pn($).find(Y=>Y.anchor===it(d));_&&(K=Math.min($.state.doc.content.size,_.pos+_.node.nodeSize-1),B=Y=>Y>_.pos&&Y<_.pos+_.node.nodeSize)}if(K!=null){if(N){const _=$.posAtCoords({left:N.x,top:N.y});_&&B?.(_.pos)&&(K=_.pos)}try{$.dispatch(ea($.state.tr.setSelection(Le.near($.state.doc.resolve(K),-1))))}catch{}Wn(d===we?we:it(d)),$.focus()}},[]),$e=x.useCallback((d,N=!1)=>{const $=be.current;if(!$)return;const K=d===we?gn($):d.startsWith("c:")?hn($).get(it(d))??null:null;if(!K)return;const B=Mn($)||1,_=$.getBoundingClientRect(),Y=_.width/B,se=_.height/B,xe=Math.max(Qr,Math.min(1.5,Ds,Y*.62/Math.max(1,K.w),se*.72/Math.max(1,K.h))),ae={z:xe,x:Y/2-(K.x+K.w/2)*xe,y:se/2-(K.y+K.h/2)*xe},re={...te.current};if(Rn(),window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)te.current=ae,ce(ae);else{const Te=Math.hypot(ae.x-re.x,ae.y-re.y),Pe=Math.round(Math.max(460,Math.min(560,420+Te*.12+Math.abs(ae.z-re.z)*120))),f=performance.now();jo(!0);const v=k=>{const b=Math.min(1,(k-f)/Pe),T=b>=1?1:1-Math.exp(-8*b)*(Math.cos(6*b)+8/6*Math.sin(6*b)),y={x:re.x+(ae.x-re.x)*T,y:re.y+(ae.y-re.y)*T,z:re.z+(ae.z-re.z)*T};te.current=y,ce(y),b<1?Xn.current=requestAnimationFrame(v):(Xn.current=0,jo(!1))};Xn.current=requestAnimationFrame(v)}N||(Wn(null),pt([d]),$.focus({preventScroll:!0}))},[Rn]),Re=x.useCallback(d=>{const N=be.current,$=V.current.getView();if(!N||!$)return!1;const K=qt(V.current.tree),B=hn(N),_=new Set(B.keys()),Y=rt=>Mr(K,rt).filter(ot=>_.has(ot)).sort((ot,Lt)=>(B.get(ot)?.y??0)-(B.get(Lt)?.y??0)),se=[],xe=new Map,ae=new Set([d]),re=(rt,ot)=>{for(const Lt of Y(rt))ae.has(Lt)||(ae.add(Lt),se.push(Lt),xe.set(Lt,ot+1),re(Lt,ot+1))};if(re(d,0),!se.length)return!1;const Te=d===we?gn(N):B.get(d);if(!Te)return!1;const Pe=96,f=32,v=new Map,k=rt=>{const ot=rt===d?Te:B.get(rt);if(!ot)return 0;const Lt=Y(rt).filter(Dn=>Dn!==d&&ae.has(Dn)),kn=Lt.reduce((Dn,fn)=>Dn+k(fn),0)+Math.max(0,Lt.length-1)*f,It=Math.max(ot.h,kn);return v.set(rt,It),It};k(d);const b=Y(d).filter(rt=>rt!==d&&ae.has(rt)),T=rt=>{const ot=new Map,Lt=(kn,It,Dn)=>{const fn=Y(kn).filter(Qt=>Qt!==d&&ae.has(Qt));if(!fn.length)return;const xt=fn.reduce((Qt,An)=>Qt+(v.get(An)??k(An)),0)+(fn.length-1)*f;let pn=It.y+It.h/2-xt/2;for(const Qt of fn){const An=B.get(Qt);if(!An)continue;const yr=v.get(Qt)??An.h,Oo={x:Dn>0?It.x+It.w+Pe:It.x-Pe-An.w,y:pn+(yr-An.h)/2,w:An.w,h:An.h};ot.set(Qt,Oo),Lt(Qt,Oo,Dn),pn+=yr+f}};for(const kn of[1,-1]){const It=b.filter(xt=>rt.get(xt)===kn),Dn=It.reduce((xt,pn)=>xt+(v.get(pn)??k(pn)),0)+Math.max(0,It.length-1)*f;let fn=Te.y+Te.h/2-Dn/2;for(const xt of It){const pn=B.get(xt);if(!pn)continue;const Qt=v.get(xt)??pn.h,An={x:kn>0?Te.x+Te.w+Pe:Te.x-Pe-pn.w,y:fn+(Qt-pn.h)/2,w:pn.w,h:pn.h};ot.set(xt,An),Lt(xt,An,kn),fn+=Qt+f}}return ot},y=[],Z=new Set,ue=rt=>{const ot=rt.join(",");Z.has(ot)||(Z.add(ot),y.push(new Map(b.map((Lt,kn)=>[Lt,rt[kn]]))))};if(b.length<=9)for(let rt=0;rt<2**b.length;rt++)ue(b.map((ot,Lt)=>rt&1<<Lt?-1:1));else ue(b.map((rt,ot)=>ot%2?-1:1)),ue(b.map((rt,ot)=>ot<Math.ceil(b.length/2)?1:-1)),ue(b.map(()=>1)),ue(b.map(()=>-1));ue(b.map(rt=>(B.get(rt)?.x??Te.x)<Te.x?-1:1));const Ce=_n(null),_e=new Set(se.map(Pt)),He=[...Ce].filter(([rt])=>!_e.has(rt)).map(([,rt])=>Ka(rt,24));let Ge=null;for(const rt of y){const ot=b.filter(xt=>rt.get(xt)===-1).length;if(b.length>1&&(ot===0||ot===b.length))continue;const Lt=T(rt),kn=[...Lt.values()],It=Math.min(...kn.map(xt=>xt.y)),Dn=Math.max(...kn.map(xt=>xt.y+xt.h)),fn=new Set([0]);for(let xt=1;xt<=20;xt++)fn.add(xt*72),fn.add(-xt*72);for(const xt of He)fn.add(Math.ceil(xt.y+xt.h+12-It)),fn.add(Math.floor(xt.y-12-Dn));He.length&&(fn.add(Math.ceil(Math.max(...He.map(xt=>xt.y+xt.h))+12-It)),fn.add(Math.floor(Math.min(...He.map(xt=>xt.y))-12-Dn)));for(const xt of[...fn].sort((pn,Qt)=>Math.abs(pn)-Math.abs(Qt))){const pn=new Map([...Lt].map(([Jn,to])=>[Jn,{...to,y:to.y+xt}]));let Qt=0;for(const Jn of pn.values())for(const to of He)Rl(Ka(Jn,12),to)&&Qt++;const An=Jn=>{const to=b.filter(po=>rt.get(po)===Jn).map(po=>v.get(po)??0);return to.reduce((po,tr)=>po+tr,0)+Math.max(0,to.length-1)*f},yr=An(1),Oo=An(-1),Ns=[...pn].reduce((Jn,[to,po])=>{const tr=B.get(to);return Jn+(tr?Math.hypot(po.x-tr.x,po.y-tr.y):0)},0),Gt=Qt*1e6+Math.abs(xt)+Math.max(yr,Oo)*.18+Math.abs(yr-Oo)*.04+Ns*.002+ot*2;(!Ge||Gt<Ge.score)&&(Ge={plan:pn,score:Gt})}}if(!Ge)return!1;const ct=new Map([...Ge.plan].map(([rt,ot])=>[rt,{x:Math.round(ot.x),y:Math.round(ot.y)}])),mt=[...ct].flatMap(([rt,ot])=>{const Lt=B.get(rt);return Lt?[{anchor:rt,x:ot.x-Lt.x,y:ot.y-Lt.y,depth:xe.get(rt)??1}]:[]});return Cr($,ct),A(mt),V.current.onCommit(),N.focus({preventScroll:!0}),!0},[_n,A]);x.useEffect(()=>{const d=be.current;!n||!d||document.activeElement&&d.contains(document.activeElement)||d.focus({preventScroll:!0})},[n]);const Q=x.useRef({mutate:st,writeFm:Xe,mergePair:Ue,pushFmCheckpoint:Dt,treeTouches:zt,removeSel:Zt,editText:Ro,boxesNow:_n,fit:ln,zoomBy:io,addCardAt:ko,addShapeAt:Eo,addFrame:fo,addRelated:So,attachHit:qn,applyAttach:er,setNodeParent:Do,expandFrames:Mo,enterNodeEdit:ve,focusNode:$e,arrangeChildren:Re,stopArrangeMotion:h,stopFocusMotion:Rn,dropFilesAt:Bn,addCardMd:Lo,writeClip:nn,pastePayload:R,linkNodes:gr});Q.current={mutate:st,writeFm:Xe,mergePair:Ue,pushFmCheckpoint:Dt,treeTouches:zt,removeSel:Zt,editText:Ro,boxesNow:_n,fit:ln,zoomBy:io,addCardAt:ko,addShapeAt:Eo,addFrame:fo,addRelated:So,attachHit:qn,applyAttach:er,setNodeParent:Do,expandFrames:Mo,enterNodeEdit:ve,focusNode:$e,arrangeChildren:Re,stopArrangeMotion:h,stopFocusMotion:Rn,dropFilesAt:Bn,addCardMd:Lo,writeClip:nn,pastePayload:R,linkNodes:gr},x.useEffect(()=>{const d=be.current;if(!n||!d||typeof ResizeObserver>"u")return;const N=new Set,$=new WeakMap;let K=0,B=!1;const _=()=>{if(K=0,B)return;const re=rn.current,Te=V.current.getView();if(!re||!Te)return;const Pe=hn(d),f=re===we?gn(d):Pe.get(re);if(!f)return;const v=[...Pe].filter(([y,Z])=>y!==re&&Rl(Ka(f,18),Z));if(!v.length)return;const k=new Map(Pe),b=new Map,T=[];for(const[y,Z]of v){const ue=[...k].filter(([ct])=>ct!==y).map(([,ct])=>ct),Ce=gn(d);Ce&&re!==we&&ue.push(Ce),ue.push(...qs(V.current.elements));const _e={x:Z.x+Z.w/2-(f.x+f.w/2),y:Z.y+Z.h/2-(f.y+f.h/2)},He=ts([Z],ue,_e);if(!He.x&&!He.y)continue;const Ge={...Z,x:Z.x+He.x,y:Z.y+He.y};k.set(y,Ge),b.set(y,{x:Math.round(Ge.x),y:Math.round(Ge.y)}),T.push({anchor:y,x:He.x,y:He.y,depth:1})}b.size&&(B=!0,Cr(Te,b,!1),A(T),V.current.onCommit(),requestAnimationFrame(()=>{B=!1}))},Y=()=>{window.clearTimeout(K),K=window.setTimeout(_,90)},se=new ResizeObserver(re=>{for(const Te of re){const Pe=Te.target,f={w:Pe.offsetWidth,h:Pe.offsetHeight},v=$.get(Pe);if($.set(Pe,f),v&&(v.w!==f.w||v.h!==f.h)){const k=Pe.classList.contains("amx-ucard")?Pe.dataset.anchor:we;k&&k===rn.current&&Y()}}}),xe=()=>{const re=new Set(d.querySelectorAll(".amx-ucard")),Te=d.querySelector(".ProseMirror");Te&&re.add(Te);for(const Pe of re)N.has(Pe)||(N.add(Pe),$.set(Pe,{w:Pe.offsetWidth,h:Pe.offsetHeight}),se.observe(Pe,{box:"border-box"}));for(const Pe of[...N])re.has(Pe)||(N.delete(Pe),se.unobserve(Pe))};xe();const ae=new MutationObserver(xe);return ae.observe(d,{subtree:!0,childList:!0}),()=>{window.clearTimeout(K),ae.disconnect(),se.disconnect()}},[n,e,A]),x.useEffect(()=>{if(!n||F<=0)return;oe.current=!1;let d=0;const N=requestAnimationFrame(()=>{d=requestAnimationFrame(()=>{const $=V.current.getView();if(!$)return;const{$from:K}=$.state.selection;let B=we;for(let _=K.depth;_>0;_--){const Y=K.node(_);if(Y.type.name==="amadeusCanvasCard"){B=Pt(String(Y.attrs.anchor));break}}pt([B]),Wn(B===we?we:it(B)),Q.current.focusNode(B,!0),$.focus()})});return()=>{cancelAnimationFrame(N),cancelAnimationFrame(d)}},[n,F]),x.useEffect(()=>{const d=be.current;if(!d||!n)return;const N=()=>V.current.getView(),$=w=>V.current.onCommit(w),K=()=>d.focus({preventScroll:!0}),B=`s${++tv}`;d.dataset.amxDragscope=B;const _=document.createElement("style");document.head.appendChild(_);let Y=[],se=0;const xe=(w,D=!1)=>`left:${w.x}px!important;top:${w.y}px!important;${D&&"w"in w&&"h"in w?`width:${w.w}px!important;height:${w.h}px!important;`:""}`,ae=`.amx-stage[data-amx-dragscope="${B}"] .unified-gutter{visibility:hidden!important;pointer-events:none!important}`,re=(w,D)=>{const le=[];for(const Ee of w){const ke=CSS.escape(Ee.anchor);le.push(`.amx-stage[data-amx-dragscope="${B}"] .amx-ucard[data-anchor="${ke}"]{${Ee.decl}}`),le.push(`.amx-stage[data-amx-dragscope="${B}"] .amx-el-selbox[data-anchor="${ke}"]{${xe(Ee.selection)}}`)}D&&le.push(`.amx-stage[data-amx-dragscope="${B}"] .amx-el-selbox[data-main-sel]{${xe(D)}}`),le.push(ae),_.textContent=le.join(`
698
+ `)},Te=(w,D,le)=>{const Ee=w===we?`.amx-stage[data-amx-dragscope="${B}"] .ProseMirror:not(.unified-embed .ProseMirror){${D}}`:`.amx-stage[data-amx-dragscope="${B}"] .amx-ucard[data-anchor="${CSS.escape(w)}"]{${D}}`,ke=w===we?`.amx-stage[data-amx-dragscope="${B}"] .amx-el-selbox[data-main-sel]{${xe(le,!0)}}`:`.amx-stage[data-amx-dragscope="${B}"] .amx-el-selbox[data-anchor="${CSS.escape(w)}"]{${xe(le,!0)}}`;_.textContent=`${Ee}
699
+ ${ke}
700
+ ${ae}`},Pe="cursor:grabbing;opacity:.94;box-shadow:0 12px 32px rgb(0 0 0 / 24%);z-index:1;",f=()=>{_.textContent=""},v=()=>{cancelAnimationFrame(se),se=0;for(const w of Y)w.cancel();Y=[]},k=(w,D,le,Ee="amx-card-repel")=>{const ke=Math.hypot(le.x,le.y);if(ke<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;v();const Fe=Math.round(Math.max(340,Math.min(480,320+ke*.55))),Oe=[{transform:`translate(${-le.x}px, ${-le.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(${le.x*.06}px, ${le.y*.06}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-le.x*.015}px, ${-le.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}];se=requestAnimationFrame(()=>{se=0;const ut=w.map(bt=>d.querySelector(`.amx-ucard[data-anchor="${CSS.escape(bt)}"]`)).filter(bt=>!!bt);if(D){const bt=d.querySelector(".ProseMirror");bt&&ut.push(bt)}for(const bt of ut){const De=bt.animate(Oe,{duration:Fe,fill:"none"});De.id=Ee,Y.push(De);const Je=()=>{Y=Y.filter(vt=>vt!==De)};De.addEventListener("finish",Je,{once:!0}),De.addEventListener("cancel",Je,{once:!0})}})},b=(w,D,le)=>{Math.max(Math.abs(D.x-le.x),Math.abs(D.y-le.y),Math.abs(D.w-le.w),Math.abs(D.h-le.h))<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(v(),se=requestAnimationFrame(()=>{se=0;const ke=w===we?d.querySelector(".ProseMirror"):d.querySelector(`.amx-ucard[data-anchor="${CSS.escape(w)}"]`);if(!ke)return;const Fe=w===we?{marginLeft:`${D.x}px`,marginTop:`${D.y}px`,width:`${D.w}px`,height:`${D.h}px`}:{left:`${D.x}px`,top:`${D.y}px`,width:`${D.w}px`,height:`${D.h}px`},Oe=w===we?{marginLeft:`${le.x}px`,marginTop:`${le.y}px`,width:`${le.w}px`,height:`${le.h}px`}:{left:`${le.x}px`,top:`${le.y}px`,width:`${le.w}px`,height:`${le.h}px`},ut=ke.animate([Fe,Oe],{duration:220,easing:"cubic-bezier(0.2, 0.78, 0.28, 1)",fill:"none"});ut.id="amx-card-snap",Y.push(ut);const bt=()=>{Y=Y.filter(De=>De!==ut)};ut.addEventListener("finish",bt,{once:!0}),ut.addEventListener("cancel",bt,{once:!0})}))},T=w=>{if(w.target?.closest?.(".amx-stage-minimap"))return;Q.current.stopFocusMotion(),w.preventDefault();const{x:D,y:le,z:Ee}=te.current,ke=Mn(d)||1;if(w.metaKey||w.ctrlKey){const Fe=w.ctrlKey&&!w.metaKey?Zb:1,Oe=Math.max(Qr,Math.min(Ds,Ee*Math.exp(-w.deltaY*Fe/300))),ut=d.getBoundingClientRect(),bt=(w.clientX-ut.left)/ke,De=(w.clientY-ut.top)/ke;ce({z:Oe,x:bt-(bt-D)*Oe/Ee,y:De-(De-le)*Oe/Ee})}else{const Fe=w.shiftKey&&!w.deltaX?w.deltaY:w.deltaX,Oe=w.shiftKey?0:w.deltaY;ce({z:Ee,x:D-Fe/ke,y:le-Oe/ke})}};d.addEventListener("wheel",T,{passive:!1});let y=null,Z=-1;const ue=w=>{Z=w;try{d.setPointerCapture(w)}catch{}},Ce=w=>{try{d.hasPointerCapture(w)&&d.releasePointerCapture(w)}catch{}},_e=()=>rm/(te.current.z*(Mn(d)||1)),He=(w,D,le)=>{const Ee=[];for(const[Fe,Oe]of hn(d))w.has(Fe)||Ee.push(Oe);const ke=D?null:gn(d);ke&&Ee.push(ke);for(const[Fe,Oe]of Tr(Tn(V.current.elements),null))le.has(Fe)||Ee.push(Oe);return Ee},Ge=(w,D)=>{const le=document.elementFromPoint(w,D);if(!le||!d.contains(le))return null;const Ee=le.closest(is);if(Ee?.dataset.el)return xn(Ee.dataset.el);const ke=le.closest("[data-card-grip]");if(ke?.dataset.cardGrip)return ke.dataset.cardGrip===we?we:Pt(ke.dataset.cardGrip);const Fe=le.closest(".amx-ucard");return Fe?.dataset.anchor?Pt(Fe.dataset.anchor):le.closest(".ProseMirror")?we:null},ct=w=>w===d||w.classList.contains("amx-stage-inner")||w.classList.contains("amx-el-layer"),mt=new Map;let rt=null,ot=null,Lt=0,kn=null,It=wi;const Dn=()=>{Jn();const w=y;y=null,w&&w.kind!=="pan"&&nr(w)},fn=()=>{const[w,D]=[...mt.keys()],le=mt.get(w),Ee=mt.get(D);if(!le||!Ee)return null;const ke=Mn(d)||1,Fe=d.getBoundingClientRect();return{x:((le.x+Ee.x)/2-Fe.left)/ke,y:((le.y+Ee.y)/2-Fe.top)/ke,d:Math.hypot(le.x-Ee.x,le.y-Ee.y)/ke,ids:`${w}/${D}`}},xt=()=>{const w=fn();if(!w)return;const{x:D,y:le,z:Ee}=te.current;ot={d0:Math.max(1,w.d),z0:Ee,sx:(w.x-D)/Ee,sy:(w.y-le)/Ee,ids:w.ids}},pn=()=>{const w=fn();if(!w||!ot)return;if(w.ids!==ot.ids){xt();return}const D=Math.max(Qr,Math.min(Ds,ot.z0*w.d/ot.d0));ce({z:D,x:w.x-ot.sx*D,y:w.y-ot.sy*D})},Qt=()=>{Lt&&window.clearTimeout(Lt),Lt=0,kn=null},An=w=>{const D=w.target,{clientX:le,clientY:Ee}=w;kn={x:le,y:Ee},Lt=window.setTimeout(()=>{Lt=0,kn=null,Fc(D,le,Ee)==="open"&&Dn()},Zp)},yr=w=>{const D=N(),le=D?Pn(D).map(Oe=>Oe.anchor):[],Ee=new Set([...le,we]),ke=qt(V.current.tree);return[w===we?we:Pt(w),...le.filter(Oe=>Eu(ke,Oe,w,Ee)).map(Pt)]},Oo=(w,D)=>{const le=ft.current;if(D.shiftKey||D.metaKey||D.ctrlKey){const Ee=D.shiftKey&&(w===we||w.startsWith("c:"))?yr(w===we?we:it(w)):[w],ke=le.includes(w)?le.filter(Fe=>!Ee.includes(Fe)):[...le,...Ee.filter(Fe=>!le.includes(Fe))];return pt(ke),ke.includes(w)?ke:null}return le.includes(w)?le:(pt([w]),[w])},Ns=w=>{Mt(null);const D=w.target;if(D.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;if(v(),Q.current.stopArrangeMotion(),Q.current.stopFocusMotion(),w.pointerType==="touch"){if(mt.set(w.pointerId,{x:w.clientX,y:w.clientY}),Qt(),mt.size>=2){w.preventDefault(),Dn(),xt();return}An(w)}if(ot)return;It=w.pointerType==="touch"?ki/(te.current.z*(Mn(d)||1)):wi;const le=w.button===1;if(w.button!==0&&!le)return;const Ee=Ot.current,ke=Ft(w.clientX,w.clientY);if(Kt.current){if(D.closest(`${Ml}, .wikilink`))return;const St=performance.now(),$t=rt;if(rt=w.pointerType==="mouse"?{t:St,x:w.clientX,y:w.clientY}:null,$t&&St-$t.t<500&&Math.hypot(w.clientX-$t.x,w.clientY-$t.y)<6&&D.closest(".ProseMirror"))return;w.preventDefault(),y={kind:"pan",x0:w.clientX,y0:w.clientY,vx:te.current.x,vy:te.current.y},ue(w.pointerId);return}const Fe=rn.current,Oe=Zn.current.held;Oe&&(Zn.current.used=!0);const ut=Ee==="pan"||w.altKey||le||Oe,bt=Ee!=="select"&&!ut,De=Fe===we?!!D.closest(".ProseMirror")&&!D.closest(".amx-ucard"):!!D.closest(`.amx-ucard[data-anchor="${CSS.escape(Fe??"")}"]`);if(Fe&&!ut&&(bt||!De)&&Wn(null),ut){w.preventDefault(),y={kind:"pan",x0:w.clientX,y0:w.clientY,vx:te.current.x,vy:te.current.y},ue(w.pointerId);return}if(Ba.has(Ee)){w.preventDefault(),y={kind:"create",tool:Ee,x0:ke.x,y0:ke.y,x1:ke.x,y1:ke.y},ue(w.pointerId);return}if(w.pointerType==="touch"&&(Ee==="card"||ls[Ee])){w.preventDefault(),y={kind:"create",tool:Ee,x0:ke.x,y0:ke.y,x1:ke.x,y1:ke.y},ue(w.pointerId);return}if(ls[Ee]){w.preventDefault(),Q.current.addShapeAt(ls[Ee],ke.x,ke.y),Ut("select"),K();return}if(Ee==="card"){w.preventDefault();const St=Q.current.addCardAt(ke.x-en/2,ke.y-24);Ut("select"),St||K();return}const Je=D.closest("[data-grip]"),vt=D.closest("[data-card-grip][data-card-edge]"),_t=D.closest(is),wt=D.closest(".amx-ucard"),Nn=D.closest(".ProseMirror"),mo=!wt&&!_t&&!!Nn&&D===Nn,zo=!wt&&!_t&&!!Nn&&D!==Nn,br=!!wt&&D===wt,In=wt?.dataset.anchor??null;if(Ee==="select"&&vt?.dataset.cardGrip&&vt.dataset.cardEdge){const St=vt.dataset.cardGrip,$t=St===we,an=$t?gn(d):hn(d).get(St),cn=$t?null:N(),Vn=cn?Pn(cn).find(no=>no.anchor===St):null;an&&($t||Vn)&&(w.preventDefault(),K(),pt([$t?we:Pt(St)]),y={kind:"card-size",key:St,edge:vt.dataset.cardEdge,b0:an,h0:$t?Number(V.current.main.h)||0:Number(Vn.node.attrs.h)||0,x0:ke.x,y0:ke.y,dx:0,dy:0,next:an},ue(w.pointerId));return}const vr=Ee==="select"?D.closest("[data-link-from]"):null;if(vr?.dataset.linkFrom){w.preventDefault(),K(),y={kind:"link",from:vr.dataset.linkFrom,x0:ke.x,y0:ke.y},ue(w.pointerId);return}const or=Ee==="select"?D.closest("[data-conn-end]"):null;if(or?.dataset.connEnd&&or.dataset.el){const St=Tn(V.current.elements).find(cn=>cn.id===or.dataset.el),$t=or.dataset.connEnd==="from"?"from":"to",an=St?.kind==="connector"?Sr($t==="from"?St.to:St.from):null;w.preventDefault(),K(),St&&an&&(y={kind:"reconnect",id:St.id,end:$t,fixed:an,x0:ke.x,y0:ke.y},ue(w.pointerId));return}const Dr=D.closest(Ml)?In??(Nn?we:null):null;if(Ee==="select"&&Dr){Wn(Dr);return}const Ir=wt&&In?In:zo?we:null;Ee==="select"&&Ir&&rn.current!==Ir&&ev(D,w.clientX)&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("canvasstage.toast.needEdit")}}));const kt=w.pointerType==="touch"&&Ee==="select"?_t?.dataset.el?xn(_t.dataset.el):In?Pt(In):!wt&&Nn?we:null:null;if(kt&&!ft.current.includes(kt)&&rn.current!==(In??we)){w.preventDefault(),y={kind:"pan",x0:w.clientX,y0:w.clientY,vx:te.current.x,vy:te.current.y,tapKey:kt},ue(w.pointerId);return}if(wt&&In&&!br&&Ee==="select"){if(rn.current===In)return;w.preventDefault(),K();const St=w.shiftKey||w.metaKey||w.ctrlKey,$t=Pt(In),an=Oo($t,w);if(!an)return;const cn=an,Vn=[];for(const no of cn){if(!no.startsWith("c:"))continue;const ho=d.querySelector(`.amx-ucard[data-anchor="${CSS.escape(it(no))}"]`);ho&&Vn.push({anchor:it(no),ox:Number(ho.dataset.x)||0,oy:Number(ho.dataset.y)||0})}y={kind:"move",cards:Vn,ids:new Set(cn),hit:$t,x0:ke.x,y0:ke.y,dx:0,dy:0,mainStart:null,mainEl:null,additive:St},ue(w.pointerId);return}if(zo&&Ee==="select"){if(rn.current===we)return;w.preventDefault(),K();const St=w.shiftKey||w.metaKey||w.ctrlKey,$t=Oo(we,w);if(!$t)return;const an=$t,cn=[];for(const Vn of an){if(!Vn.startsWith("c:"))continue;const no=d.querySelector(`.amx-ucard[data-anchor="${CSS.escape(it(Vn))}"]`);no&&cn.push({anchor:it(Vn),ox:Number(no.dataset.x)||0,oy:Number(no.dataset.y)||0})}y={kind:"move",cards:cn,ids:new Set(an),hit:we,x0:ke.x,y0:ke.y,dx:0,dy:0,mainStart:{x:V.current.main.x,y:V.current.main.y},mainEl:Nn,additive:St},ue(w.pointerId);return}const Ao=_t?.dataset.el?xn(_t.dataset.el):In?Pt(In):mo?we:null;if(Ee==="conn"){w.preventDefault(),K();const St=Ao??(!wt&&!_t&&D.closest(".ProseMirror")?we:null);if(!St){vn(null);return}const $t=Jt.current;$t?(Q.current.linkNodes($t,St,w.shiftKey),vn(null),Ut("select")):vn(St);return}const js=D.closest("[data-add]");if(js?.dataset.add&&js.dataset.node){w.preventDefault(),K(),Q.current.addRelated(js.dataset.node,js.dataset.add==="child"?"child":"sibling");return}if(Je?.dataset.grip){w.preventDefault();const St=Tr(Tn(V.current.elements),null).get(Je.dataset.grip);if(!St)return;y={kind:"size",id:Je.dataset.grip,corner:Je.dataset.corner??"se",b0:St,dx:0,dy:0,dw:0,dh:0},ue(w.pointerId);return}if(Ao){w.preventDefault(),K();const St=w.shiftKey||w.metaKey||w.ctrlKey,$t=Oo(Ao,w);if(!$t)return;const an=$t;if(br&&an.length===1&&wt.dataset.anchor){const ho=wt.getBoundingClientRect(),_o=El*te.current.z*(Mn(d)||1);if(w.clientX>=ho.right-_o){const ga=hn(d).get(wt.dataset.anchor),Xc=Pn(N()).find(dd=>dd.anchor===wt.dataset.anchor);if(!ga||!Xc)return;y={kind:"card-size",key:wt.dataset.anchor,edge:"e",b0:ga,h0:Number(Xc.node.attrs.h)||0,x0:ke.x,y0:ke.y,dx:0,dy:0,next:ga},ue(w.pointerId);return}}if(Ao===we&&an.length===1&&Nn){const ho=Nn.getBoundingClientRect();if(w.clientX>ho.right-El*te.current.z*(Mn(d)||1)){const _o=gn(d);if(!_o)return;y={kind:"card-size",key:we,edge:"e",b0:_o,h0:Number(V.current.main.h)||0,x0:ke.x,y0:ke.y,dx:0,dy:0,next:_o},ue(w.pointerId);return}}const cn=Q.current.expandFrames(an),Vn=[];for(const ho of cn){if(!ho.startsWith("c:"))continue;const _o=d.querySelector(`.amx-ucard[data-anchor="${CSS.escape(it(ho))}"]`);_o&&Vn.push({anchor:it(ho),ox:Number(_o.dataset.x)||0,oy:Number(_o.dataset.y)||0})}const no=cn.includes(we);y={kind:"move",cards:Vn,ids:new Set(cn),hit:Ao,x0:ke.x,y0:ke.y,dx:0,dy:0,mainStart:no?{x:V.current.main.x,y:V.current.main.y}:null,mainEl:no?d.querySelector(".ProseMirror"):null,additive:St,growSel:cn.length>$t.length?[...cn]:void 0},ue(w.pointerId);return}if(!ct(D))return;const Rs=Q.current.boxesNow(null),ma=Tn(V.current.elements).find(St=>{if(St.kind!=="connector")return!1;const $t=Sr(St.from),an=Sr(St.to),cn=$t?Rs.get($t):null,Vn=an?Rs.get(an):null;return!!cn&&!!Vn&&Hs(cn,Vn,ke,8/te.current.z)}),Uc=ma?null:qu(V.current.tree).find(([St,$t])=>{const an=Rs.get(Pt(St)),cn=Rs.get($t===we?we:Pt($t));return!!an&&!!cn&&Hs(cn,an,ke,8/te.current.z)});if(w.preventDefault(),K(),ma){pt([xn(ma.id)]);return}if(Uc){pt([Vu(Uc[0])]);return}const ha=w.shiftKey||w.metaKey||w.ctrlKey,ud=ha?[...ft.current]:[];if(ha||pt([]),w.pointerType==="touch"){y={kind:"pan",x0:w.clientX,y0:w.clientY,vx:te.current.x,vy:te.current.y},ue(w.pointerId);return}y={kind:"marquee",x0:ke.x,y0:ke.y,additive:ha,base:ud},ue(w.pointerId)},Gt={raf:0,t:0,x:0,y:0,id:-1,type:"mouse"},Jn=()=>{Gt.raf&&cancelAnimationFrame(Gt.raf),Gt.raf=0},to=()=>{const w=d.getBoundingClientRect();return{left:Math.max(w.left,0),top:Math.max(w.top,0),right:Math.min(w.right,window.innerWidth),bottom:Math.min(w.bottom,window.innerHeight)}},po=w=>Kt.current||ot?!1:y?y.kind!=="pan"&&y.live===!0:Ot.current==="conn"&&!!Jt.current&&!w?.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"),tr=w=>{Gt.raf=0;const D=document.elementFromPoint(Gt.x,Gt.y);if(!po(D))return;const{vx:le,vy:Ee}=Ei(to(),Gt.x,Gt.y);if(!le&&!Ee)return;const ke=Math.min(.05,Math.max(0,(w-Gt.t)/1e3));Gt.t=w;const Fe=Mn(d)||1,Oe={...te.current,x:te.current.x-le*ke/Fe,y:te.current.y-Ee*ke/Fe};te.current=Oe,ce(Oe),Ic({clientX:Gt.x,clientY:Gt.y,pointerId:Gt.id,pointerType:Gt.type,target:D??d}),Gt.raf=requestAnimationFrame(tr)},cd=w=>{if(y&&Z!==w.pointerId)return;Gt.x=w.clientX,Gt.y=w.clientY,Gt.id=w.pointerId,Gt.type=w.pointerType;const{vx:D,vy:le}=po(w.target)?Ei(to(),w.clientX,w.clientY):{vx:0,vy:0};if(!D&&!le){Jn();return}Gt.raf||(Gt.t=performance.now(),Gt.raf=requestAnimationFrame(tr))},Lc=()=>{y||Jn()},Dc=w=>{Ic(w),cd(w)},Ic=w=>{if(w.pointerType==="touch"&&(mt.has(w.pointerId)&&mt.set(w.pointerId,{x:w.clientX,y:w.clientY}),kn&&Math.hypot(w.clientX-kn.x,w.clientY-kn.y)>Qp&&Qt()),ot){pn();return}if(y&&Z!==w.pointerId)return;if(!y&&Ot.current==="conn"&&Jt.current){const De=w.target,Je=De.closest?.(is),vt=De.closest?.(".amx-ucard");let _t=Je?.dataset.el?xn(Je.dataset.el):vt?.dataset.anchor?Pt(vt.dataset.anchor):!vt&&De.closest?.(".ProseMirror")?we:null;_t===Jt.current&&(_t=null);const wt=Ft(w.clientX,w.clientY);H({x:wt.x,y:wt.y,over:_t});return}if(!y)return;const D=Mn(d)||1;if(y.kind==="pan"){ce({...te.current,x:y.vx+(w.clientX-y.x0)/D,y:y.vy+(w.clientY-y.y0)/D});return}const le=Ft(w.clientX,w.clientY);if(y.kind==="link"||y.kind==="reconnect"){(Math.abs(le.x-y.x0)>It||Math.abs(le.y-y.y0)>It)&&(y.live=!0);const De=y.kind==="link"?y.from:y.fixed,Je=Ge(w.clientX,w.clientY);ie({from:De,x:le.x,y:le.y,over:Je===De?null:Je});return}if(y.kind==="card-size"){y.dx=le.x-y.x0,y.dy=le.y-y.y0;const De=y.key===we;let Je=Al(y.b0,y.edge,y.dx,y.dy,!1,De?Oa:Xs);if((Math.abs(Je.x-y.b0.x)>It||Math.abs(Je.y-y.b0.y)>It||Math.abs(Je.w-y.b0.w)>It||Math.abs(Je.h-y.b0.h)>It)&&(y.live=!0),y.gx=!1,y.gy=!1,he.current&&y.live){y.others||(y.others=He(new Set(De?[]:[y.key]),De,new Set));const vt=em(Je,y.edge,y.others,_e(),De?Oa:Xs,Yu);Je=vt.box,y.gx=vt.guides.v.length>0,y.gy=vt.guides.h.length>0,et(y.gx||y.gy?Ci(Je,y.others,vt.guides,1/te.current.z):null)}else et(null);y.next=Je,Te(y.key,De?`margin-left:${Je.x}px;margin-top:${Je.y}px;width:${Je.w}px;height:${Je.h}px;${Pe}`:`left:${Je.x}px;top:${Je.y}px;width:${Je.w}px;height:${Je.h}px;${Pe}`,Je),vo({move:{ids:new Set([De?we:Pt(y.key)]),dx:0,dy:0},size:null});return}if(y.kind==="size"){const De=y.b0,Je=y.corner.includes("e"),vt=y.corner.includes("s"),_t=Math.max(ar,Math.round(Je?le.x-De.x:De.x+De.w-le.x)),wt=Math.max(ar,Math.round(vt?le.y-De.y:De.y+De.h-le.y));y.dx=Je?0:De.w-_t,y.dy=vt?0:De.h-wt,y.dw=_t-De.w,y.dh=wt-De.h,(Math.abs(y.dw)>It||Math.abs(y.dh)>It)&&(y.live=!0),vo({move:null,size:{id:y.id,dx:y.dx,dy:y.dy,dw:y.dw,dh:y.dh}});return}if(y.kind==="create"){y.x1=le.x,y.y1=le.y,(Math.abs(y.x1-y.x0)>It||Math.abs(y.y1-y.y0)>It)&&(y.live=!0),Ba.has(y.tool)&&zn({x:Math.min(y.x0,le.x),y:Math.min(y.y0,le.y),w:Math.abs(le.x-y.x0),h:Math.abs(le.y-y.y0)});return}if(y.kind==="marquee"){y.live=!0;const De={x:Math.min(y.x0,le.x),y:Math.min(y.y0,le.y),w:Math.abs(le.x-y.x0),h:Math.abs(le.y-y.y0)};zn(De);const Je=[];for(const[vt,_t]of Q.current.boxesNow(null))yl(De,_t)&&Je.push(vt);pt(y.additive?[...new Set([...y.base,...Je])]:Je);return}if(y.dx=Math.round(le.x-y.x0),y.dy=Math.round(le.y-y.y0),(Math.abs(y.dx)>It||Math.abs(y.dy)>It)&&(y.live=!0),!y.align){const De=new Set(y.cards.map(mo=>mo.anchor)),Je=new Set([...y.ids].filter(mo=>mo.startsWith("e:")).map(it)),vt=hn(d),_t=Tr(Tn(V.current.elements),null),wt=[];for(const mo of De){const zo=vt.get(mo);zo&&wt.push(zo)}const Nn=y.mainStart?gn(d):null;Nn&&wt.push(Nn);for(const mo of Je){const zo=_t.get(mo);zo&&wt.push(zo)}y.align={base:tm(wt),others:He(De,!!y.mainStart,Je)}}y.gx=!1,y.gy=!1;const Ee=y.align.base;if(he.current&&y.live&&Ee){const De=nm({...Ee,x:Ee.x+y.dx,y:Ee.y+y.dy},y.align.others,_e());y.dx+=Math.round(De.dx),y.dy+=Math.round(De.dy),y.gx=De.guides.v.length>0,y.gy=De.guides.h.length>0,et(y.gx||y.gy?Ci({...Ee,x:Ee.x+y.dx,y:Ee.y+y.dy},y.align.others,De.guides,1/te.current.z):null)}else et(null);y.live&&y.kind==="move"&&y.growSel&&(pt(y.growSel),y.growSel=void 0);const{dx:ke,dy:Fe}=y;re(y.cards.map(De=>({anchor:De.anchor,decl:`left:${De.ox+ke}px;top:${De.oy+Fe}px;${Pe}`,selection:{x:De.ox+ke,y:De.oy+Fe}})),y.mainStart?{x:y.mainStart.x+ke,y:y.mainStart.y+Fe}:void 0),y.mainStart&&y.mainEl&&(y.mainEl.style.marginLeft=`${y.mainStart.x+y.dx}px`,y.mainEl.style.marginTop=`${y.mainStart.y+y.dy}px`),vo({move:{ids:y.ids,dx:y.dx,dy:y.dy},size:null});const Oe=it(y.hit),ut=!y.mainStart&&y.cards.length>0&&y.ids.size===y.cards.length?y.cards.map(De=>De.anchor).sort((De,Je)=>+(Je===Oe)-+(De===Oe)):[],bt=ut.length&&y.live?Q.current.attachHit(ut,le):null;Fn(bt)},nr=w=>{f(),w.kind==="move"&&w.mainEl&&(w.mainEl.style.marginLeft="",w.mainEl.style.marginTop=""),vo(null),zn(null),Fn(null),et(null),ie(null)},Pc=w=>{if(w.pointerType==="touch"&&(mt.delete(w.pointerId),Qt(),ot)){mt.size===0&&(ot=null),Ce(w.pointerId),y=null;return}if(y&&Z!==w.pointerId){Ce(w.pointerId);return}Jn();const D=y;if(y=null,Ce(w.pointerId),!D)return;if(D.kind==="pan"){D.tapKey&&Math.hypot(w.clientX-D.x0,w.clientY-D.y0)<ki&&pt([D.tapKey]);return}if(D.kind==="link"||D.kind==="reconnect"){if(nr(D),!D.live)return;const Fe=D.kind==="link"?D.from:D.fixed,Oe=Ge(w.clientX,w.clientY);if(!Oe||Oe===Fe)return;D.kind==="reconnect"?Q.current.mutate(ut=>wx(ut,D.id,D.end,Oe)):Q.current.linkNodes(Fe,Oe,w.shiftKey);return}if(D.kind==="create"){const Fe=Math.abs(D.x1-D.x0),Oe=Math.abs(D.y1-D.y0),ut=Ba.has(D.tool)&&Fe>=ar&&Oe>=ar?{x:Math.min(D.x0,D.x1),y:Math.min(D.y0,D.y1),w:Fe,h:Oe}:null;let bt=null;D.tool==="frame"?ut?Q.current.addFrame(ut.x,ut.y,ut.w,ut.h):Q.current.addFrame(D.x0-el.w/2,D.y0-el.h/2):D.tool==="card"?bt=Q.current.addCardAt(D.x0-en/2,D.y0-24):ls[D.tool]&&Q.current.addShapeAt(ls[D.tool],D.x0,D.y0,ut??void 0),Ut("select"),bt||K(),nr(D);return}if(!D.live){D.kind==="move"&&D.ids.size>1&&!D.additive&&pt([D.hit]),nr(D);return}const le=N();if(D.kind==="marquee"){const Fe=Ft(w.clientX,w.clientY),Oe={x:Math.min(D.x0,Fe.x),y:Math.min(D.y0,Fe.y),w:Math.abs(Fe.x-D.x0),h:Math.abs(Fe.y-D.y0)},ut=[];for(const[bt,De]of Q.current.boxesNow(null))yl(Oe,De)&&ut.push(bt);pt(D.additive?[...new Set([...D.base,...ut])]:ut),nr(D);return}if(!le){nr(D);return}let Ee=null,ke=null;if(D.kind==="card-size"){const Fe=D.key===we;let Oe=j.current?Al(D.b0,D.edge,D.dx,D.dy,!0,Fe?Oa:Xs):D.next;D.gx&&(Oe={...Oe,x:D.next.x,w:D.next.w}),D.gy&&(Oe={...Oe,y:D.next.y,h:D.next.h});const ut=D.edge.includes("n")||D.edge.includes("s");Fe?Q.current.writeFm({m:{...V.current.main,x:Math.round(Oe.x),y:Math.round(Oe.y),w:Math.round(Oe.w),...ut?{h:Math.round(Oe.h)}:{}}}):Cr(le,new Map([[D.key,{x:Math.round(Oe.x),y:Math.round(Oe.y),w:Math.round(Oe.w),h:ut?Math.round(Oe.h):D.h0}]])),j.current&&(ke={key:D.key,from:D.next,to:Oe})}else if(D.kind==="size"){const Fe=Tn(V.current.elements).find(Oe=>Oe.id===D.id);Fe&&Fe.kind!=="connector"&&Q.current.mutate(Oe=>Su(Oe,D.id,{x:Math.round(Fe.x+D.dx),y:Math.round(Fe.y+D.dy),w:Math.max(ar,Math.round(Fe.w+D.dw)),h:Math.max(ar,Math.round(Fe.h+D.dh))}))}else{const Fe=!D.mainStart&&D.cards.length>0&&D.ids.size===D.cards.length?D.cards.map(kt=>kt.anchor).sort((kt,Ao)=>+(Ao===it(D.hit))-+(kt===it(D.hit))):[],Oe=Fe.length?Q.current.attachHit(Fe,Ft(w.clientX,w.clientY)):null;if(Fe.length&&Oe&&Q.current.applyAttach(Fe,Oe)){nr(D);return}const ut=hn(d),bt=[];for(const kt of D.cards){const Ao=ut.get(kt.anchor);Ao&&bt.push(Ao)}if(D.mainStart){const kt=gn(d);kt&&bt.push(kt)}const De=new Set(D.cards.map(kt=>kt.anchor)),Je=[...ut].filter(([kt])=>!De.has(kt)).map(([,kt])=>kt);if(!D.mainStart){const kt=gn(d);kt&&Je.push(kt)}const vt=(D.hit.startsWith("c:")?D.cards.find(kt=>kt.anchor===it(D.hit)):null)??D.cards[0]??(D.mainStart?{ox:D.mainStart.x,oy:D.mainStart.y}:null),_t=D.gx?D.dx:j.current&&vt?Si(vt.ox+D.dx)-vt.ox:D.dx,wt=D.gy?D.dy:j.current&&vt?Si(vt.oy+D.dy)-vt.oy:D.dy,Nn=_t-D.dx,mo=wt-D.dy,zo=bt.map(kt=>({...kt,x:kt.x+Nn,y:kt.y+mo})),br=ts(zo,Je,{x:_t,y:wt}),In=_t+br.x,vr=wt+br.y,or={x:In-D.dx,y:vr-D.dy};(or.x||or.y)&&(Ee={anchors:D.cards.map(kt=>kt.anchor),main:!!D.mainStart,push:or,repel:!!(br.x||br.y)}),D.cards.length&&Cr(le,new Map(D.cards.map(kt=>[kt.anchor,{x:Math.round(kt.ox+In),y:Math.round(kt.oy+vr)}])));const Dr=new Set([...D.ids].filter(kt=>kt.startsWith("e:")).map(it)),Ir=D.mainStart?{...V.current.main,x:Math.round(D.mainStart.x+In),y:Math.round(D.mainStart.y+vr)}:void 0;(Dr.size||Ir)&&(Q.current.writeFm({...Dr.size?{e:Qi(Ho(V.current.elements),Dr,In,vr)}:{},...Ir?{m:Ir}:{}}),D.cards.length&&Q.current.mergePair())}nr(D),ke&&b(ke.key,ke.from,ke.to),Ee&&k(Ee.anchors,Ee.main,Ee.push,Ee.repel?"amx-card-repel":"amx-card-snap"),$()},Oc=w=>{if(Kt.current)return;const D=document.elementFromPoint(w.clientX,w.clientY)??w.target;if(D.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;const le=D.closest(".amx-ucard"),Ee=!le&&!!D.closest(".ProseMirror"),ke=le?.dataset.anchor?Pt(le.dataset.anchor):Ee?we:null;if(ke){if(rn.current===(ke===we?we:it(ke)))return;w.preventDefault(),w.stopPropagation(),Q.current.enterNodeEdit(ke,{x:w.clientX,y:w.clientY}),Wm()&&Q.current.focusNode(ke,!0);return}const Fe=D.closest(is);if(Fe?.dataset.el){w.preventDefault(),w.stopPropagation();const De=Tn(V.current.elements).find(Je=>Je.id===Fe.dataset.el);De&&Q.current.editText(De.id,Fa(De),_a(De));return}if(!ct(D))return;const Oe=Ft(w.clientX,w.clientY),ut=Q.current.boxesNow(null),bt=Tn(V.current.elements).find(De=>{if(De.kind!=="connector")return!1;const Je=Sr(De.from),vt=Sr(De.to),_t=Je?ut.get(Je):null,wt=vt?ut.get(vt):null;return!!_t&&!!wt&&Hs(_t,wt,Oe,8/te.current.z)});w.preventDefault(),bt?Q.current.editText(bt.id,"label",je("canvasstage.textTitle.connector")):Q.current.addCardAt(Oe.x-en/2,Oe.y-24)},Fc=(w,D,le)=>{if(Kt.current||w.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"))return"skip";const Ee=w.closest(is),ke=w.closest(".amx-ucard"),Fe=!ke&&!Ee&&!!w.closest(".ProseMirror");if(ke?.dataset.anchor&&rn.current===ke.dataset.anchor||Fe&&rn.current===we)return"native";let Oe=Ee?.dataset.el?xn(Ee.dataset.el):ke?.dataset.anchor?Pt(ke.dataset.anchor):Fe?we:null;if(!Oe&&!ct(w))return"skip";if(!Oe){const ut=Ft(D,le),bt=Q.current.boxesNow(null),De=Tn(V.current.elements).find(Je=>{if(Je.kind!=="connector")return!1;const vt=Sr(Je.from),_t=Sr(Je.to),wt=vt?bt.get(vt):null,Nn=_t?bt.get(_t):null;return!!wt&&!!Nn&&Hs(wt,Nn,ut,8/te.current.z)});De&&(Oe=xn(De.id))}return Oe&&!ft.current.includes(Oe)&&pt([Oe]),Mt({x:D,y:le,key:Oe,at:Ft(D,le)}),"open"},_c=w=>{const D=Fc(w.target,w.clientX,w.clientY);D!=="skip"&&(w.stopPropagation(),D==="open"&&w.preventDefault())},id=w=>{const D=w.target,le=rn.current;return!le||!D?!1:le===we?!!D.closest(".ProseMirror")&&!D.closest(".amx-ucard"):!!D.closest(`.amx-ucard[data-anchor="${CSS.escape(le)}"]`)};let pa=!1;const Bc=w=>{w.target?.closest?.(".ProseMirror")&&(pa=!0)},Lr=()=>{pa=!1},Hc=w=>{const D=w.dataTransfer,le=D?Array.from(D.types):[];return pa||N()?.dragging?null:V.current.saveFile&&le.includes("Files")?"files":dp(D)?"refs":id(w)?null:le.includes("text/uri-list")||le.includes("text/plain")?"text":null},Kc=w=>{if(Kt.current)return;const D=N();if(Hc(w)){w.preventDefault(),w.dataTransfer&&(w.dataTransfer.dropEffect="copy"),d.classList.add("amx-dropzone");return}!D?.dragging||w.target?.closest?.(".ProseMirror")||(w.preventDefault(),w.dataTransfer&&(w.dataTransfer.dropEffect="move"),d.classList.add("amx-dropzone"))},Fo=()=>d.classList.remove("amx-dropzone"),Vc=w=>{d.contains(w.relatedTarget)||Fo()},qc=w=>{if(Fo(),Kt.current){w.preventDefault();return}const D=N(),le=Hc(w);if(le){w.preventDefault(),w.stopPropagation();const Fe=Ft(w.clientX,w.clientY),Oe=Array.from(w.dataTransfer?.files??[]);if(le==="files"&&Oe.length){Q.current.dropFilesAt(Oe,Fe);return}if(le==="refs"){const bt=V.current.path;lp(w.dataTransfer).forEach((De,Je)=>Q.current.addCardMd($l(De,w.altKey||De.kind==="note"&&De.path===bt),Fe,Je));return}const ut=w.dataTransfer?.getData("text/uri-list")||w.dataTransfer?.getData("text/plain")||"";Q.current.addCardMd(ut,Fe);return}if(!D?.dragging||w.target?.closest?.(".ProseMirror"))return;w.preventDefault(),w.stopPropagation();const Ee=Ft(w.clientX,w.clientY),ke=D.state.selection;if(ke instanceof Se&&ke.node.type.name==="amadeusCanvasCard")Cr(D,new Map([[String(ke.node.attrs.anchor),{x:Math.round(Ee.x),y:Math.round(Ee.y)}]])),$();else{const Fe=Xu(D,Math.round(Ee.x),Math.round(Ee.y));Fe&&$(Fe)}D.dragging=null,D.dom.dataset.dragging="false"},ld=()=>{const w=d.getBoundingClientRect();return Ft(w.left+w.width/2,w.top+w.height/2)},Ts=w=>{if(rn.current||!w.clipboardData||!N())return;const D=ft.current;if(!D.length)return;w.preventDefault();const le=Q.current.writeClip(w.clipboardData,D);w.type==="cut"&&le&&Q.current.removeSel(le.keys,{assets:!1})},Wc=w=>{if(Kt.current||rn.current||!w.clipboardData)return;const D=Array.from(w.clipboardData.files??[]),le=w.clipboardData.getData("text/plain")??"",Ee=ov(w.clipboardData.getData(jl));if(!D.length&&!le.trim()&&!Ee)return;w.preventDefault();const ke=Un.current++,Fe=ld(),Oe={x:Fe.x+ke*24,y:Fe.y+ke*24};if(D.length){Q.current.dropFilesAt(D,Oe);return}Ee&&Q.current.pastePayload(Ee,Oe)||le.trim()&&Q.current.addCardMd(le,Oe)},$s=w=>{w.pointerType==="touch"&&(mt.delete(w.pointerId),Qt(),ot&&mt.size===0&&(ot=null))};window.addEventListener("pointerup",$s,!0),window.addEventListener("pointercancel",$s,!0);const Yc=w=>{w.pointerType==="touch"&&(mt.delete(w.pointerId),Qt(),ot&&mt.size===0&&(ot=null)),Ce(w.pointerId),!(y&&Z!==w.pointerId)&&Dn()};return d.addEventListener("pointerdown",Ns),d.addEventListener("pointermove",Dc),d.addEventListener("pointerleave",Lc),d.addEventListener("pointerup",Pc),d.addEventListener("pointercancel",Yc),d.addEventListener("dblclick",Oc),d.addEventListener("contextmenu",_c,!0),d.addEventListener("dragover",Kc),d.addEventListener("dragleave",Vc),d.addEventListener("drop",qc),d.addEventListener("dragstart",Bc),window.addEventListener("dragend",Fo),window.addEventListener("drop",Fo),window.addEventListener("blur",Fo),window.addEventListener("dragend",Lr),window.addEventListener("drop",Lr),window.addEventListener("blur",Lr),d.addEventListener("copy",Ts,!0),d.addEventListener("cut",Ts,!0),d.addEventListener("paste",Wc,!0),()=>{window.removeEventListener("pointerup",$s,!0),window.removeEventListener("pointercancel",$s,!0),Qt(),_.remove(),v(),delete d.dataset.amxDragscope,d.removeEventListener("wheel",T),d.removeEventListener("pointerdown",Ns),d.removeEventListener("pointermove",Dc),d.removeEventListener("pointerleave",Lc),Jn(),d.removeEventListener("pointerup",Pc),d.removeEventListener("pointercancel",Yc),d.removeEventListener("dblclick",Oc),d.removeEventListener("contextmenu",_c,!0),d.removeEventListener("dragover",Kc),d.removeEventListener("dragleave",Vc),d.removeEventListener("drop",qc),d.removeEventListener("dragstart",Bc),window.removeEventListener("dragend",Fo),window.removeEventListener("drop",Fo),window.removeEventListener("blur",Fo),window.removeEventListener("dragend",Lr),window.removeEventListener("drop",Lr),window.removeEventListener("blur",Lr),Fo(),d.removeEventListener("copy",Ts,!0),d.removeEventListener("cut",Ts,!0),d.removeEventListener("paste",Wc,!0)}},[n,Ft]),x.useEffect(()=>{if(!n)return;const d=()=>{Zn.current={held:!1,used:!1},Yn(!1)},N=$=>{if($.code!=="Space"||!Zn.current.held)return;const{used:K}=Zn.current;d(),$.preventDefault();const B=be.current,_=$.target;if(K||Kt.current||!B||!_||!B.contains(_)||_.closest(".ProseMirror"))return;const Y=ft.current;Y.length===1&&(Y[0].startsWith("c:")||Y[0]===we)&&Q.current.enterNodeEdit(Y[0])};return window.addEventListener("keyup",N,!0),window.addEventListener("blur",d),()=>{window.removeEventListener("keyup",N,!0),window.removeEventListener("blur",d),d()}},[n]);const nt=d=>{if(!n||U||d.nativeEvent.isComposing)return;const N=d.target;if((d.metaKey||d.ctrlKey)&&(d.key==="z"||d.key==="Z")){if(N.tagName==="INPUT"||N.tagName==="TEXTAREA")return;d.preventDefault(),d.stopPropagation(),Ln(d.shiftKey?"redo":"undo");return}if((d.metaKey||d.ctrlKey)&&!d.shiftKey&&!d.altKey&&(d.key==="y"||d.key==="Y")){if(N.tagName==="INPUT"||N.tagName==="TEXTAREA")return;d.preventDefault(),d.stopPropagation(),Ln("redo");return}if(d.key!=="Escape")return;const $=rn.current;!$||!N.closest(".ProseMirror")||(d.preventDefault(),d.stopPropagation(),Wn(null),pt([$===we?we:Pt($)]),be.current?.focus({preventScroll:!0}))},at=d=>{if(!n)return;const N=d.target;if(N.closest(".ProseMirror")||N.tagName==="INPUT"||N.tagName==="TEXTAREA")return;const $=d.metaKey||d.ctrlKey;if(!d.altKey&&($?d.key==="="||d.key==="+"||d.key==="-"||d.key==="0":d.shiftKey&&d.code==="Digit1")){d.preventDefault(),$?d.key==="0"?io(1/te.current.z):io(d.key==="-"?1/1.2:1.2):ln();return}if(!U){if($&&(d.key==="a"||d.key==="A")){d.preventDefault(),pt([...hn(be.current).keys()].map(Pt).concat(ze.filter(K=>K.kind!=="connector").map(K=>xn(K.id)),[we]));return}if($&&!d.shiftKey&&!d.altKey&&(d.key==="d"||d.key==="D")){d.preventDefault(),Ze.length&&O(Ze);return}if(d.key==="Escape"){d.preventDefault(),lt?Mt(null):Vt?vn(null):Ye!=="select"?Ut("select"):pt([]);return}if(d.code==="Space"&&!$&&!d.target?.closest?.("button")){d.preventDefault(),!d.repeat&&!Zn.current.held&&(Zn.current={held:!0,used:!1},Yn(!0));return}if(Ze.length){if(d.key==="Delete"||d.key==="Backspace"){d.preventDefault(),Zt(Ze);return}if((d.key==="Enter"||d.key==="F2")&&Ze.length===1&&Ze[0].startsWith("e:")){d.preventDefault();const K=ze.find(B=>B.id===it(Ze[0]));K&&Ro(K.id,Fa(K),_a(K));return}if((d.key==="Tab"||d.key==="Enter")&&Ze.length===1&&(Ze[0].startsWith("c:")||Ze[0]===we)){d.preventDefault(),So(Ze[0]===we?we:it(Ze[0]),d.key==="Tab"?"child":"sibling");return}if(d.key.startsWith("Arrow")){d.preventDefault();const K=Gp(j.current,d.shiftKey),B=d.key==="ArrowLeft"?-K:d.key==="ArrowRight"?K:0,_=d.key==="ArrowUp"?-K:d.key==="ArrowDown"?K:0;if(!B&&!_)return;const Y=o(),se=Mo(Ze),xe=se.filter(Te=>Te.startsWith("c:")).map(it);if(Y&&xe.length){const Te=hn(be.current);Cr(Y,new Map(xe.map(Pe=>{const f=Te.get(Pe);return[Pe,{x:Math.round((f?.x??0)+B),y:Math.round((f?.y??0)+_)}]}))),M()}const ae=new Set(se.filter(Te=>Te.startsWith("e:")).map(it)),re=se.includes(we)?{...r,x:Math.round(r.x+B),y:Math.round(r.y+_)}:void 0;(ae.size||re)&&(Xe({...ae.size?{e:Qi(Ho(c),ae,B,_)}:{},...re?{m:re}:{}}),xe.length&&Ue())}}}},Tt=[{id:"select",icon:u.jsx(ap,{size:14}),title:ge("canvasstage.tool.select")},{id:"pan",icon:u.jsx(Cm,{size:14}),title:ge("canvasstage.tool.pan")},{id:"card",icon:u.jsx(Ja,{size:14}),title:ge("canvasstage.tool.card")},{id:"rect",icon:u.jsx(cp,{size:14}),title:ge("canvasstage.shape.rect")},{id:"ellipse",icon:u.jsx(ip,{size:14}),title:ge("canvasstage.shape.ellipse")},{id:"text",icon:u.jsx(Em,{size:14}),title:ge("canvasstage.shape.text")},{id:"frame",icon:u.jsx(au,{size:14}),title:ge("canvasstage.tool.frame")},{id:"conn",icon:u.jsx(Uh,{size:14}),title:ge("canvasstage.tool.conn")}],gt=Up(fe),jt=(lt?.key?.startsWith("e:")?ze.find(d=>d.id===it(lt.key))??null:null)?.kind==="connector",At=lt?.key?(Ze.length?Ze:[lt.key]).filter(d=>d.startsWith("c:")||d.startsWith("e:")):[],sn=(()=>{if(!At.length)return null;const d=lt?o():null,N=Ho(c),$=B=>{if(B.startsWith("c:"))return String((d?Pn(d).find(Y=>Y.anchor===it(B))?.node.attrs.color:"")??"");const _=N.find(Y=>!!Y&&typeof Y=="object"&&Y.id===it(B));return typeof _?.color=="string"?_.color:""},K=$(At[0]);return At.every(B=>$(B)===K)?K:null})(),Rt=sn&&sn.startsWith("#")?sn:null,Kn=jt?(Ze.length?Ze:[lt.key]).filter(d=>d.startsWith("e:")).map(it).filter(d=>ze.some(N=>N.kind==="connector"&&N.id===d)):[],Po=(()=>{const d=Kn.map(N=>{const $=ze.find(_=>_.kind==="connector"&&_.id===N),K=$?.kind==="connector"?$.fromEnd??gs.fromEnd:gs.fromEnd,B=$?.kind==="connector"?$.toEnd??gs.toEnd:gs.toEnd;return Cl.find(_=>_.from===K&&_.to===B)?.id??null});return d.length&&d.every(N=>N===d[0])?d[0]:null})();return u.jsxs("div",{className:`amx-stage${n?"":" amx-stage-off"}${n?` amx-tool-${U?"pan":Ye}`:""}${U?" amx-stage-ro":""}${n&&pr?" amx-space-pan":""}${Jo?" amx-vp-focus":""}${n&&Me&&fe.z<=tt?" amx-stage-overview":""}`,ref:be,tabIndex:-1,onKeyDownCapture:nt,onKeyDown:at,children:[n?u.jsx("div",{className:"amx-stage-grid","aria-hidden":"true",style:gt}):null,u.jsxs("div",{className:"amx-stage-inner",style:n?{transform:`translate(${fe.x}px, ${fe.y}px) scale(${fe.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?u.jsx(_b,{elements:c,hostRef:be,documentKey:e,sel:G,editing:jn,tree:i,ghost:Go,marquee:Rr,attach:En,overviewScale:Me&&fe.z<=tt?fe.z:null,mainAutoHeight:!(typeof r.h=="number"&&r.h>0),preview:X??(Vt&&I?{from:Vt,x:I.x,y:I.y,over:I.over}:null),guides:qe}):null,Ne]}),n&&ee?u.jsx(rv,{hostRef:be,vp:fe,elements:c,ghost:Go,onCenter:lo}):null,n&&!U?u.jsx("div",{className:"amx-stage-tools",role:"toolbar","aria-label":ge("canvasstage.toolbar.label"),children:Tt.map(d=>u.jsx("button",{type:"button",title:d.title,className:Ye===d.id?"on":"","aria-pressed":Ye===d.id,onClick:()=>{Ut(d.id),vn(null),be.current?.focus({preventScroll:!0})},children:d.icon},d.id))}):null,n&&Vt?u.jsx("div",{className:"amx-stage-hint",children:ge("canvasstage.conn.hint")}):null,n?u.jsx(Dm,{zoom:fe.z,onZoomBy:io,onFit:ln,snap:ye,onSnap:d=>{ht(d),be.current?.focus({preventScroll:!0})},mini:ee,onMini:d=>{Ie(d),qm(d),be.current?.focus({preventScroll:!0})},extra:u.jsxs(u.Fragment,{children:[u.jsx("button",{type:"button",className:W?"is-on":"","aria-pressed":W,"aria-label":ge("canvasstage.guides.label"),title:ge(W?"canvasstage.guides.off":"canvasstage.guides.on"),onClick:()=>{const d=!W;he.current=d,ne(d),Km(d),be.current?.focus({preventScroll:!0})},children:u.jsx(oh,{size:12})}),u.jsx("button",{type:"button",className:Me?"is-on":"","aria-pressed":Me,"aria-label":ge("canvasstage.overview.label"),title:ge(Me?"canvasstage.overview.off":"canvasstage.overview.on"),onClick:()=>{const d=!Me;dt(d),Vm(d),be.current?.focus({preventScroll:!0})},children:u.jsx(Eh,{size:12})})]})}):null,n&&lt?u.jsx(ir,{children:u.jsx(lr,{className:"ctx-menu amx-canvas-menu",x:lt.x,y:lt.y,onClick:d=>d.stopPropagation(),children:lt.key?u.jsxs(u.Fragment,{children:[At.length>0&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"amx-color-row",role:"group","aria-label":ge("canvasstage.color.label"),children:[Jb.map(d=>u.jsx("button",{type:"button",className:"amx-color-swatch","data-swatch":d.v||"none",title:ge(d.nameKey),"aria-label":ge(d.nameKey),"aria-pressed":sn===d.v,style:d.v?{"--amx-swatch":`var(--amx-cv-${d.v})`}:void 0,onClick:()=>{const N=At;Mt(null),Qo(N,d.v||null)}},d.v||"none")),u.jsxs("label",{className:"amx-color-swatch is-custom",title:ge("canvasstage.color.custom"),"data-active":Rt?"":void 0,style:Rt?{"--amx-swatch":Rt}:void 0,children:[Rt?null:u.jsx(Xp,{size:11}),u.jsx("input",{type:"color","aria-label":ge("canvasstage.color.custom"),defaultValue:Rt??"#7b5ce5",ref:d=>{if(!d)return;const N=At;d.onchange=()=>{Mt(null),Qo(N,d.value)}}})]})]}),u.jsx("div",{className:"ctx-separator"})]}),jt&&Kn.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"amx-color-row amx-end-row",role:"group","aria-label":ge("canvasstage.ends.label"),children:Cl.map(d=>u.jsx("button",{type:"button",className:"amx-end-btn","data-ends":d.id,title:ge(d.nameKey),"aria-label":ge(d.nameKey),"aria-pressed":Po===d.id,onClick:()=>{const N=Kn;Mt(null),xr(N,d.from,d.to),be.current?.focus({preventScroll:!0})},children:d.icon},d.id))}),u.jsx("div",{className:"ctx-separator"})]}),lt.key.startsWith("e:")&&u.jsx("button",{onClick:()=>{const d=ze.find(N=>N.id===it(lt.key));Mt(null),d&&Ro(d.id,Fa(d),_a(d))},children:ge("canvasstage.menu.editText")}),lt.key!==we&&!jt&&u.jsxs(u.Fragment,{children:[u.jsx("button",{onClick:()=>{const d=Ze.length?Ze:[lt.key];Mt(null),pe(d)},children:ge("canvasstage.menu.copy")}),u.jsx("button",{onClick:()=>{const d=Ze.length?Ze:[lt.key];Mt(null),O(d),be.current?.focus({preventScroll:!0})},children:ge("canvasstage.menu.duplicate")})]}),!jt&&u.jsx("button",{onClick:()=>{vn(lt.key),Ut("conn"),Mt(null)},children:ge("canvasstage.menu.connectTo")}),(lt.key===we||lt.key.startsWith("c:"))&&Mr(qt(i),lt.key===we?we:it(lt.key)).length>0&&u.jsx("button",{onClick:()=>{const d=lt.key===we?we:it(lt.key);Mt(null),Re(d)},children:ge("canvasstage.menu.arrange")}),!jt&&u.jsx("button",{onClick:()=>{const d=Ze.length?Ze:[lt.key];Mt(null),Io(d)},children:ge("canvasstage.menu.groupFrame")}),lt.key.startsWith("c:")&&u.jsx("button",{onClick:()=>{const d=it(lt.key);Mt(null);const N=o();if(!N)return;const $=zt([d]);$&&Dt(),Gu(N,d),pt([]),M(),$&&Ue()},children:ge("canvasstage.menu.unwrap")}),lt.key!==we&&u.jsx("button",{className:"danger",onClick:()=>{const d=Ze.length?Ze:[lt.key];Mt(null),Zt(d)},children:ge("canvasstage.menu.delete")})]}):u.jsxs(u.Fragment,{children:[u.jsx("button",{onClick:()=>{const d=lt.at;Mt(null),ko(d.x-en/2,d.y-24)},children:ge("canvasstage.menu.newCard")}),q&&u.jsx("button",{onClick:()=>{const d=lt.at;Mt(null),wo(d)},children:ge("canvasstage.menu.addNote")}),u.jsx("button",{onClick:()=>{const d=lt.at;Mt(null),Eo("rect",d.x,d.y)},children:ge("canvasstage.shape.rect")}),u.jsx("button",{onClick:()=>{const d=lt.at;Mt(null),Eo("ellipse",d.x,d.y)},children:ge("canvasstage.shape.ellipse")}),u.jsx("button",{onClick:()=>{const d=lt.at;Mt(null),Eo("text",d.x,d.y)},children:ge("canvasstage.shape.text")}),u.jsx("button",{onClick:()=>{const d=lt.at;Mt(null),fo(d.x,d.y)},children:"Frame"}),u.jsx("button",{onClick:()=>{Mt(null),ln()},children:ge("canvasstage.menu.fit")}),u.jsx("div",{className:"ctx-separator"}),u.jsx("button",{onClick:()=>{Mt(null),Co()},children:ge("canvasstage.menu.exportCanvas")})]})})}):null,n&&!U&&co&&q?u.jsx(ku,{pages:q(),exclude:e,onClose:()=>{wo(null),be.current?.focus({preventScroll:!0})},onPick:d=>{const N=co;wo(null),be.current?.focus({preventScroll:!0}),Lo($l({kind:"note",path:d}),N)}}):null]})}function Xu(e,t,n,o){const r=e.state.selection,s=e.state.schema.nodes.amadeusCanvasCard;if(!s||!(r instanceof Se))return null;const c=r.node;if(!c.isBlock||["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(c.type.name))return null;const i=e.state.doc.resolve(r.from);for(let M=i.depth;M>=1;M--)if(i.node(M).type.name==="amadeusColumnCell")return null;const a=$o(e.state.doc),l=s.createAndFill({anchor:a,x:t,y:n,w:en,h:0},c);if(!l)return null;const m=i.depth>=1?i.node(i.depth):null,g=e.state.schema.nodes.paragraph;let C=m?.type.name==="amadeusCanvasCard"&&m.childCount===1&&g?e.state.tr.replaceWith(r.from,r.to,g.create()):e.state.tr.delete(r.from,r.to);return C=C.insert(o?Uu(C.doc,o.tree,o.parent):C.doc.content.size,l),cr(e,C.scrollIntoView()),a}function Gu(e,t){const o=Pn(e).find(m=>m.anchor===t);if(!o)return;const{paragraph:r,html:s}=e.state.schema.nodes,c=[];o.node.forEach(m=>c.push(m));const a=[...t&&r&&s?[r.create(null,s.create({value:`<!-- a ${t} -->`}))]:[],...c.length?c:[r.create()]],l=e.state.tr.delete(o.pos,o.pos+o.node.nodeSize);cr(e,l.insert(o.pos,a).scrollIntoView())}const av={heading:["id"]};function jc(e,t){if(e.type!==t.type)return!1;const n=av[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 Ur(e,t){if(e===t)return!0;if(!jc(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(!Ur(e.child(n),t.child(n)))return!1;return!0}function Ju(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(!jc(r,s))return n;if(r.isText&&r.text!==s.text){const c=r.text??"",i=s.text??"";for(let a=0;c[a]===i[a];a++)n++;return n}if(r.content.size||s.content.size){const c=Ju(r.content,s.content,n+1);if(c!=null)return c}n+=r.nodeSize}}function Zu(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),i=t.child(--s),a=c.nodeSize;if(c===i){n-=a,o-=a;continue}if(!jc(c,i))return{a:n,b:o};if(c.isText&&c.text!==i.text){const l=c.text??"",m=i.text??"";let g=0;const C=Math.min(l.length,m.length);for(;g<C&&l[l.length-g-1]===m[m.length-g-1];)g++,n--,o--;return{a:n,b:o}}if(c.content.size||i.content.size){const l=Zu(c.content,i.content,n-1,o-1);if(l)return l}n-=a,o-=a}}const cv=25e4;function iv(e,t){const n=e.childCount,o=t.childCount;let r=0;for(;r<n&&r<o&&Ur(e.child(r),t.child(r));)r++;let s=0;for(;s<n-r&&s<o-r&&Ur(e.child(n-1-s),t.child(o-1-s));)s++;const c=r,i=n-s,a=r,l=o-s,m=i-c,g=l-a;if(m===0&&g===0)return[];if(m===0||g===0||m*g>cv)return[[c,i,a,l]];const C=g+1,M=new Uint32Array((m+1)*C);for(let U=m-1;U>=0;U--)for(let q=g-1;q>=0;q--)M[U*C+q]=Ur(e.child(c+U),t.child(a+q))?M[(U+1)*C+q+1]+1:Math.max(M[(U+1)*C+q],M[U*C+q+1]);const S=[];let z=0,L=0,E=0,F=0;for(;z<m&&L<g;)Ur(e.child(c+z),t.child(a+L))&&M[z*C+L]===M[(z+1)*C+L+1]+1?((E<z||F<L)&&S.push([c+E,c+z,a+F,a+L]),z++,L++,E=z,F=L):M[(z+1)*C+L]>=M[z*C+L+1]?z++:L++;return(E<m||F<g)&&S.push([c+E,i,a+F,l]),S}const Ws=(e,t)=>{let n=0;for(let o=0;o<t;o++)n+=e.child(o).nodeSize;return n};function lv(e,t){const n=[];for(const[o,r,s,c]of iv(e,t)){const i=Ws(e,o),a=Ws(t,s),l=e.content.cut(i,Ws(e,r)),m=t.content.cut(a,Ws(t,c)),g=Ju(l,m,i);if(g==null)continue;const C=Zu(l,m,i+l.size,a+m.size);let M=C?C.a:i+l.size,S=C?C.b:a+m.size;const z=a-i;M<g&&(S+=g-M,M=g),S-z<g&&(M+=g-(S-z),S=g+z),n.push({from:g,to:M,slice:t.slice(g+z,S)})}return n}function uv(e,t,n){const o=lv(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 i=o[c];s.replace(i.from,i.to,i.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 Le){const c=l=>{for(const m of o)if(l>m.from&&l<m.to){const g=s.mapping.map(m.from,-1);return Math.min(g+(l-m.from),g+m.slice.size,s.doc.content.size)}return null},i=c(r.head),a=c(r.anchor);if(i!=null||a!=null){const l=i??s.mapping.map(r.head),m=a??s.mapping.map(r.anchor);try{s.setSelection(Le.between(s.doc.resolve(m),s.doc.resolve(l)))}catch{}}}return s.setMeta("addToHistory",!1)}const ro=new $n("amAgentChanges");let Ll=0;function Qu(e,t){if(e.childCount!==t.childCount)return!1;for(let n=0;n<e.childCount;n++)if(!Ur(e.child(n),t.child(n)))return!1;return!0}function dv(e,t,n,o){const r=[...e.map(i=>({a:i.from,b:i.to,e:i})),...t.map(i=>({a:i.oldFrom,b:i.oldTo,c:i}))].sort((i,a)=>i.a-a.a||i.b-a.b),s=[];for(const i of r){const a=s[s.length-1],l=a?Math.max(...a.map(m=>m.b)):-1;a&&i.a<=l&&(i.c||a.some(m=>m.c))?a.push(i):s.push([i])}const c=[];for(const i of s){const a=i.filter(U=>U.e).map(U=>U.e),l=i.filter(U=>U.c).map(U=>U.c);if(!l.length){for(const U of a){const q=o.mapping.map(U.from,1);c.push({...U,from:q,to:Math.max(q,o.mapping.map(U.to,-1))})}continue}if(!a.length&&l.length===1){const U=l[0];c.push({id:++Ll,from:U.from,to:U.to,old:U.old,after:o.doc.slice(U.from,U.to).content});continue}const m=Math.min(...i.map(U=>U.a)),g=Math.max(...i.map(U=>U.b)),C=a.filter(U=>Qu(n.slice(U.from,U.to).content,U.after)),M=a.reduce((U,q)=>U+(q.locked??0)+(C.includes(q)?0:1),0),S=new pp(n);for(const U of[...C].sort((q,de)=>de.from-q.from))S.replace(U.from,U.to,U.old);const z=S.mapping.map(m,-1),L=S.mapping.map(g,1),E=o.mapping.map(m,-1),F=o.mapping.map(g,1);c.push({id:++Ll,from:E,to:F,old:S.doc.slice(z,L),after:o.doc.slice(E,F).content,...M?{locked:M}:{}})}return c.sort((i,a)=>i.from-a.from)}function fv(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),i=Math.min(r.to,o);i>c?(n.push(ao.inline(c,i,{class:s,"data-agent-change":String(r.id)})),e.doc.nodesBetween(c,i,(a,l)=>(a.isBlock&&a.isLeaf&&l>=c&&l+a.nodeSize<=i&&n.push(ao.node(l,l+a.nodeSize,{class:`${s} am-agent-change-block`})),!a.isTextblock))):n.push(ao.widget(c,()=>{const a=document.createElement("span");return a.className=`am-agent-del${t.current===r.id?" is-current":""}`,a.setAttribute("data-agent-change",String(r.id)),a},{side:-1,key:`am-agent-del-${r.id}-${t.current===r.id?1:0}`,ignoreSelection:!0}))}return dr.create(e.doc,n)}function pv(e){return[Et(()=>mv(e))].flat()}function mv(e){return new Yt({key:ro,state:{init:()=>({changes:[],current:null}),apply(t,n){const o=t.getMeta(ro);if(o&&"clear"in o)return{changes:[],current:null};if(o&&"add"in o){const s=dv(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=ro.getState(t);return n?fv(t,n):null}},view:t=>{const n=ro.getState(t.state);return n&&e.current(n),{update(o,r){const s=ro.getState(o.state);s&&s!==ro.getState(r)&&e.current(s)}}}})}function hv(e,t,n){return n.length?e.setMeta(ro,{add:n,before:t}):e}function gv(e){const t=ro.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,i)=>i.from-c.from)){if(!Qu(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(ro,{clear:!0}).scrollIntoView()),{reverted:o,skipped:r}}function xv(e){e.dispatch(e.state.tr.setMeta(ro,{clear:!0}))}function yv(e){const t=ro.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(ro,{current:o.id})),o}Cn({"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 bv(){const{t:e}=Bt();return u.jsxs("div",{className:"am-agent-capsule is-live",role:"status","aria-live":"polite","data-testid":"agent-live-capsule",children:[u.jsx("span",{className:"amx-pending-insert-spin","aria-hidden":!0}),u.jsx("span",{className:"am-agent-capsule-text",children:e("agentchg.live")}),u.jsx("span",{className:"am-agent-capsule-hint",children:e("agentchg.liveHint")})]})}function vv({count:e,index:t,onReview:n,onRevert:o,onKeep:r}){const{t:s}=Bt();return u.jsxs("div",{className:"am-agent-capsule",role:"status","aria-label":s("agentchg.label"),"data-testid":"agent-change-capsule",children:[u.jsx(nu,{size:14,"aria-hidden":!0}),u.jsx("span",{className:"am-agent-capsule-text",children:s("agentchg.summary",{n:String(e)})}),u.jsx("span",{className:"am-agent-capsule-sep","aria-hidden":!0}),u.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")}),u.jsx("button",{type:"button",className:"btn sm","data-act":"revert",onClick:o,children:s("agentchg.revert")}),u.jsx("button",{type:"button",className:"btn sm primary","data-act":"keep",onClick:r,children:s("agentchg.keep")})]})}Cn({"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 $r=new $n("UNIFIED_PENDING_INSERT");function wv(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=je("pendins.busy",{label:e.label});const r=document.createElement("button");return r.type="button",r.className="btn sm",r.textContent=je("pendins.cancel"),r.addEventListener("mousedown",s=>s.preventDefault()),r.addEventListener("click",s=>{s.preventDefault(),e.onCancel()}),t.append(n,o,r),t}function kv(){return[Et(()=>new Yt({key:$r,state:{init:()=>dr.empty,apply(e,t){let n=t.map(e.mapping,e.doc);const o=e.getMeta($r);return o&&"add"in o?n=n.add(e.doc,[ao.widget(o.add.pos,()=>wv(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=>$r.getState(e)}}))]}function ed(e,t){const o=$r.getState(e)?.find(void 0,void 0,r=>r.id===t)[0];return o?o.from:null}let Sv=0;function Cv(e,t,n=!0){const o=`p${Date.now().toString(36)}${(Sv++).toString(36)}`;let r=!1;const s=()=>{r=!0,td(e,o)};return e.dispatch(e.state.tr.setMeta($r,{add:{id:o,pos:e.state.selection.head,label:t,visible:n,onCancel:s}})),{id:o,label:t,cancelled:()=>r}}function td(e,t){e.isDestroyed||ed(e.state,t)==null||e.dispatch(e.state.tr.setMeta($r,{remove:t}))}function Ev(e,t,n){const o=ed(e.state,t);if(o==null)return!1;let r=e.state.tr.setMeta($r,{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 i=e.state.selection;let a,l,m;if(c<1)a=o,r=r.insert(o,n),l=o+n.size,m=e.hasFocus()&&i.empty&&i.head===o;else{const g=s.before(c),C=s.after(c),M=s.node(c).textContent.trim()==="";m=e.hasFocus()&&i.from>=g&&i.to<=C,a=M?g:C,r=M?r.replaceWith(g,C,n):r.insert(C,n),l=a+n.size}return Qs(r,a,l),m&&(r=r.setSelection(Le.near(r.doc.resolve(Math.min(l,r.doc.content.size)),-1)).scrollIntoView()),e.dispatch(r),!0}function Dl(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{level:"warning",text:je("pendins.sourceMode",{label:e})}}))}function Mv(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("pendins.lost",{label:e})}}))}function nd(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 ur=new $n("amInlineAi");function zv(e){const t=e.state.selection;if(!(t instanceof Le)||!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 Av(e){return new Yt({key:ur,state:{init:()=>null,apply(t,n){const o=t.getMeta(ur);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=ur.getState(t);return!n||n.to<=n.from?null:dr.create(t.doc,[ao.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()||!zv(t)?!1:(e.onSpace(t),!0)}}})}function Nv(e){return[Et(()=>Av({spaceTrigger:e.spaceTrigger,onSpace:t=>e.onSpace.current(t)}))].flat()}function Tv(e,t,n){const o={from:t,to:n,text:e.state.doc.textBetween(t,n,`
701
+ `,""),sig:nd(e.state.doc,t,n)},r=e.state.tr.setMeta(ur,{set:o});return n>t&&r.setSelection(Le.create(r.doc,n)),e.dispatch(r),o}function Il(e){const t=ur.getState(e.state);if(!t)return;const n=e.state.tr.setMeta(ur,{clear:!0});if(t.to>t.from&&t.to<=n.doc.content.size)try{n.setSelection(Le.create(n.doc,t.from,t.to))}catch{}e.dispatch(n)}function Pl(e){return ur.getState(e.state)??null}function $v(e,t,n){const o=e.content.size,r=e.textBetween(Math.max(0,t-8e3),t,`
702
+ `,"").slice(-2e3),s=e.textBetween(n,Math.min(o,n+4e3),`
703
+ `,"").slice(0,1e3);return{before:r,after:s}}function jv(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 Rv(e,t,n,o){if(!n.childCount)return null;const{doc:r}=e.state,s=r.content.size,c=Math.min(t.from,s),i=Math.min(Math.max(t.to,c),s);let a=o;a==="replace"&&nd(r,c,i)!==t.sig&&(a="below");let l=e.state.tr,m;if(a==="replace"){const g=n.childCount===1&&!!n.firstChild?.isTextblock&&r.resolve(c).sameParent(r.resolve(i));l=l.replaceRange(c,i,g?new Xa(n,1,1):new Xa(n,0,0)),m=l.mapping.map(i,1)}else{const g=jv(r,a==="below"?i:c);if(!g)return null;a==="insert"&&g.blank?(l=l.replaceWith(g.from,g.to,n),m=g.from+n.size):(l=l.insert(g.to,n),m=g.to+n.size)}return l=l.setSelection(Le.near(l.doc.resolve(Math.min(m,l.doc.content.size)),-1)),e.dispatch(l.setMeta(ur,{clear:!0}).scrollIntoView()),a}Cn({"unipage.menu.askTangu":{zh:"问 Tangu",en:"Ask Tangu"}});const Lv=2e4;function Dv(e,t){let n=null;for(const o of na(e)){if(o.pos>t)break;n=o.text}return n}function Iv(e,t,n,o){const r=e.textBetween(t,n,`
704
+ `,"").trim().slice(0,Lv);if(!r)return"";const s=Dv(e,t),c=s&&!/[[\]|#^\n]/.test(s)?`#${s}`:"";return o?`${r}
705
+ — [[${o}${c}]]`:r}function od(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 Pv(e,t,n){if(e.resolve(t).depth!==0)return od(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 Ov(e,t){if(!t)return null;const n=na(e),o=t.heading?n.findIndex(a=>a.text===t.heading.trim()):-1,r=o>=0?n[o]:null,s=r?r.pos:0,c=r?Pv(e,r.pos,r.level):e.content.size,i=(t.text??"").split(`
706
+ `).map(a=>a.trim()).filter(Boolean);if(i.length){const a=[];e.nodesBetween(s,c,(m,g)=>m.isTextblock?(g>=s&&a.push({pos:g,text:m.textContent}),!1):!0);const l=a.findIndex(m=>m.text.includes(i[0]));if(l>=0){const m=i[i.length-1],g=a.findIndex((M,S)=>S>=l&&M.text.includes(m)),C=od(e,a[g>=0?g:l].pos+1);if(C!=null)return C}}return r?c:null}Cn({"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 Ol=500,Va=250,Fl='a[href], sup[data-type="footnote_reference"]';function rd(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((g,C)=>s.push({node:g,from:r+C,to:r+C+g.nodeSize}));const c=g=>!!n.isInSet(g.node.marks);let i=s.findIndex(g=>c(g)&&t>=g.from&&t<g.to);if(i<0&&(i=s.findIndex(g=>c(g)&&t>=g.from&&t<=g.to)),i<0)return null;const a=n.isInSet(s[i].node.marks);let l=i,m=i;for(;l>0&&a.isInSet(s[l-1].node.marks);)l--;for(;m<s.length-1&&a.isInSet(s[m+1].node.marks);)m++;return{from:s[l].from,to:s[m].to,mark:a}}function Fv(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=rd(e.state.doc,o,n);return r&&r.from<r.to?{from:r.from,to:r.to}:null}function _v({getView:e,onOpenNote:t}){const{t:n}=Bt(),[o,r]=x.useState(null),[s,c]=x.useState(null),[i,a]=x.useState(null),l=x.useRef(null),m=x.useRef(null);x.useEffect(()=>{const S=()=>{l.current&&clearTimeout(l.current),m.current&&clearTimeout(m.current),l.current=null,m.current=null},z=F=>{const U=e()?.dom.closest(".unified-body");return!!U&&F.closest(".unified-body")===U},L=F=>{const q=F.target?.closest?.(Fl);if(!q||!z(q))return;if(m.current&&(clearTimeout(m.current),m.current=null),l.current&&clearTimeout(l.current),q.tagName==="SUP"){l.current=setTimeout(()=>{const me=e(),Ne=q.getBoundingClientRect();r(null),c({num:q.textContent??"",text:me?cf(me.state.doc,q.getAttribute("data-label")??""):null,x:Ne.left,y:Ne.bottom+6})},Ol);return}const de=q;l.current=setTimeout(()=>{const me=e();c(null);const Ne=de.getBoundingClientRect(),be=me?Fv(me,de):null;r({href:de.getAttribute("href")??"",text:be&&me?me.state.doc.textBetween(be.from,be.to):de.textContent??"",from:be?.from??-1,to:be?.to??-1,x:Ne.left,y:Ne.bottom+6})},Ol)},E=F=>{!F.target?.closest?.(Fl)||F.relatedTarget?.closest?.(".amx-linkcard")||(l.current&&clearTimeout(l.current),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{r(null),c(null)},Va))};return document.addEventListener("mouseover",L,!0),document.addEventListener("mouseout",E,!0),()=>{document.removeEventListener("mouseover",L,!0),document.removeEventListener("mouseout",E,!0),S()}},[e]),x.useEffect(()=>{if(!o&&!s||i)return;const S=()=>{r(null),c(null)};return document.addEventListener("scroll",S,!0),()=>document.removeEventListener("scroll",S,!0)},[o,s,i]);const g=(S,z,L,E,F)=>{const U=e(),q=U?.state.schema.marks.link;if(!U||!q)return;const{doc:de}=U.state;if(z>de.content.size||S>=z)return;const me=rd(de,S,q);if(!me||me.from!==S||me.to!==z||me.mark.attrs.href!==L)return;const Ne=de.textBetween(S,z),be=p=>q.create({...me.mark.attrs,href:p,..."ref"in me.mark.attrs?{ref:null}:{}});let ge=U.state.tr;if(E==="")ge=ge.delete(S,z);else if(E!==null&&E!==Ne){let p=null;de.nodesBetween(S,z,ce=>ce.isInline?(p=p===null?ce.marks:p.filter(te=>te.isInSet(ce.marks)),!1):!0);const fe=(p??[]).filter(ce=>ce.type!==q);ge=ge.replaceWith(S,z,U.state.schema.text(E,F?be(F).addToSet(fe):fe)),ge.setSelection(Le.near(ge.doc.resolve(S+E.length)))}else if(F){if(F===me.mark.attrs.href){U.focus();return}ge=ge.removeMark(S,z,me.mark).addMark(S,z,be(F))}else ge=ge.removeMark(S,z,me.mark);U.dispatch(ge.scrollIntoView()),U.focus()};if(i){const S=!!ri(i.href)&&!!i.text.trim(),z=()=>{a(null),r(null),e()?.focus()};return u.jsxs(ir,{children:[u.jsx("div",{className:"amx-linkedit-backdrop",onMouseDown:()=>a(null),role:"presentation"}),u.jsx(lr,{className:"amx-linkedit",x:window.innerWidth/2,y:Math.round(window.innerHeight*.3),center:!0,children:u.jsxs("form",{className:"amx-linkedit-form",onSubmit:L=>{L.preventDefault();const E=ri(i.href);!E||!i.text.trim()||(g(i.from,i.to,i.wasHref,i.text,E),a(null),r(null))},onKeyDown:L=>{L.key==="Escape"&&(L.preventDefault(),L.stopPropagation(),z())},children:[u.jsxs("label",{children:[n("linkcard.text"),u.jsx("input",{autoFocus:!0,value:i.text,onChange:L=>a({...i,text:L.target.value}),onFocus:L=>L.currentTarget.select()})]}),u.jsxs("label",{children:[n("linkcard.link"),u.jsx("input",{value:i.href,onChange:L=>a({...i,href:L.target.value})})]}),u.jsxs("div",{className:"amx-linkedit-row",children:[u.jsx("button",{type:"button",onClick:z,children:n("common.cancel")}),u.jsx("button",{type:"submit",className:"primary",disabled:!S,children:n("common.save")})]})]})})]})}if(s)return u.jsx(ir,{children:u.jsxs(lr,{className:"amx-linkcard amx-fncard",x:s.x,y:s.y,onMouseEnter:()=>{m.current&&clearTimeout(m.current),m.current=null},onMouseLeave:()=>{m.current=setTimeout(()=>c(null),Va)},children:[u.jsx("span",{className:"amx-fncard-num",children:s.num}),u.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 C=o.href;try{C=new URL(o.href).host||o.href}catch{}const M=o.from>=0&&(e()?.editable??!0);return u.jsx(ir,{children:u.jsxs(lr,{className:"amx-linkcard",x:o.x,y:o.y,onMouseEnter:()=>{m.current&&clearTimeout(m.current),m.current=null},onMouseLeave:()=>{m.current=setTimeout(()=>r(null),Va)},children:[u.jsx("button",{className:"amx-linkcard-host",title:o.href,onClick:S=>{t&&Wl(o.href)==="note"?(r(null),t(o.href,mp(S))):window.open(o.href,"_blank","noopener")},children:C}),u.jsx("span",{className:"amx-linkcard-sep"}),u.jsx("button",{onClick:()=>{navigator.clipboard.writeText(o.href)},children:n("linkcard.copy")}),M&&u.jsx("button",{onClick:()=>a({from:o.from,to:o.to,text:o.text,href:o.href,wasHref:o.href}),children:n("common.edit")}),M&&u.jsx("button",{onClick:()=>{g(o.from,o.to,o.href,null,null),r(null)},children:n("linkcard.unlink")}),M&&u.jsx("button",{className:"danger",onClick:()=>{g(o.from,o.to,o.href,"",null),r(null)},children:n("common.delete")})]})})}Cn({"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 pc(e){const t=e?.state.selection;return t instanceof Se&&t.node.type.spec.tableRole==="table"}function Bv(e,t,n){if(!e||!pc(e))return null;const o=document.elementFromPoint(t,n)?.closest?.("td,th");if(!o||!e.dom.contains(o))return null;try{return mf(e.state.doc,e.posAtDOM(o,0))}catch{return null}}const Hv=[{op:"rowAbove",key:"unipage.table.rowAbove",Icon:ch},{op:"rowBelow",key:"unipage.table.rowBelow",Icon:sh},{op:"colLeft",key:"unipage.table.colLeft",Icon:dh},{op:"colRight",key:"unipage.table.colRight",Icon:lh},{op:"deleteRow",key:"unipage.table.deleteRow",Icon:Za},{op:"deleteCol",key:"unipage.table.deleteCol",Icon:Za}],Kv=[{align:"left",key:"unipage.table.alignLeft",Icon:hp},{align:"center",key:"unipage.table.alignCenter",Icon:uf},{align:"right",key:"unipage.table.alignRight",Icon:df}];function Vv({view:e,cell:t,onDone:n}){const{t:o}=Bt(),r=e.state.selection;if(!(r instanceof Se)||r.node.type.spec.tableRole!=="table")return null;const s=lf(e.state.doc,r.from,t);if(!s)return null;const c=i=>{n();const a=i();a&&e.dispatch(a),e.focus()};return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"ubm-sep",role:"separator"}),u.jsx("div",{className:"ubm-label",role:"presentation",children:o("unipage.table.label")}),Hv.filter(i=>s.ops.includes(i.op)).map(({op:i,key:a,Icon:l})=>u.jsxs("button",{"data-table-op":i,role:"menuitem",tabIndex:-1,onClick:()=>c(()=>ff(e.state,s.cellPos,i)),children:[u.jsx(l,{size:13})," ",o(a)]},i)),s.align&&Kv.map(({align:i,key:a,Icon:l})=>u.jsxs("button",{"data-table-align":i,"aria-checked":s.align===i,role:"menuitemcheckbox",tabIndex:-1,onClick:()=>c(()=>pf(e.state,s.cellPos,i)),children:[u.jsx(l,{size:13})," ",o(a),s.align===i&&u.jsx(zs,{size:13,className:"ubm-check"})]},i))]})}function qv(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:i}of n){let a,l;try{a=o.posAtDOM(c.startContainer,c.startOffset),l=o.posAtDOM(c.endContainer,c.endOffset)}catch{continue}l<=a||o.state.doc.textBetween(a,l,`
707
+ `,"")!==c.toString()||r.push({from:a,to:l,text:i})}if(!r.length)return 0;r.sort((c,i)=>i.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}}}const bo=new Map,Rc=(e,t,n)=>JSON.stringify([e,t,n]),mc=5*6e4;function Wv(e,t,n,o,r,s){for(const[M,S]of bo)Date.now()-S.at>mc&&(clearTimeout(S.timer),bo.delete(M));let c=null,i=!1,a;const l={capture(){if(i)return a;const M=a=r(),S=c==null?M.text:Qa(o,M.text,c);return s(S===(c??o)?null:S??M.text,c??o),M},acknowledge(M,S){i||(o=M,c=S,l.capture())},claim(M){const S=a=r();i=!0;const z=Qa(o,S.text,M);return s(z===M?null:z??S.text,M),{text:z,snapshot:S}}},m=Rc(e,t,n),g=bo.get(m);g&&clearTimeout(g.timer);const C=setTimeout(()=>{bo.get(m)?.handoff===l&&bo.delete(m)},mc);return bo.set(m,{at:Date.now(),handoff:l,timer:C}),l.capture(),l}function sd(e,t,n){const o=Rc(e,t,n),r=bo.get(o);return r&&Date.now()-r.at>mc&&(clearTimeout(r.timer),bo.delete(o)),bo.has(o)}function Yv(e,t,n,o){const r=Rc(e,t,n);if(!sd(e,t,n))return null;const s=bo.get(r);return clearTimeout(s.timer),bo.delete(r),s.handoff.claim(o)}Cn({"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 Uv=800;let Ys=null,qa=null;const Xv={insertAfter:()=>{},deleteEmpty:()=>{},mergePrev:()=>{},arrow:()=>{},moveDir:()=>{},selfFocus:()=>{}};async function ad(e,t){try{const n=new Uint8Array(await t.arrayBuffer()),{opts:o}=await ta(),{base:r}=await on.saveAttachment(e,t.name||"file",n,o);return`![[${r}]]`}catch{return null}}let zr=null;function Ar(){zr&&(clearTimeout(zr.timer),clearTimeout(zr.arm),zr.off(),zr.el.remove(),zr=null)}function Gs(e){if(Ar(),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",Ar,!0),window.removeEventListener("wheel",Ar,!0)},r=window.setTimeout(()=>{window.addEventListener("scroll",Ar,!0),window.addEventListener("wheel",Ar,!0)},300);zr={el:t,timer:window.setTimeout(Ar,1400),arm:r,off:o}}function Gv(e,t,n=!1,o=!1){const r=[],s=uv(e.state,t,n?r:void 0);s&&(o&&s.setMeta("addToHistory",!0),e.dispatch(n?hv(s,e.state.doc,r):s))}function Jv({path:e,pageDir:t,body:n,onChange:o,onFinalFlush:r,skipFinalFlush:s,hidden:c,apiRef:i,probe:a,extraPlugins:l,focusPlace:m,onFocused:g,onCard:C,readOnly:M=!1,onAskTangu:S,aiMenu:z,onAiPrompt:L}){const[,E]=bf(),F=Zr(),U=x.useRef(null),[q,de]=x.useState(!1),me=x.useRef({onFinalFlush:r,skipFinalFlush:s});me.current={onFinalFlush:r,skipFinalFlush:s};const Ne=x.useRef(C);Ne.current=C;const be=x.useRef(L);be.current=L,x.useEffect(()=>(i.current={applySlashItem:J=>dt.current(J),applyBody:(J,ye,Ae)=>{let j=!1;return E()?.action(W=>{const ne=W.get(Sn),he=W.get(Pr)(wr(J,t));he&&(Gv(ne,he,ye,Ae),wf(ne.state.doc,he),j=!0,a&&(a.reconciled=(a.reconciled??0)+1))}),j},serializeNow:()=>{let J=null;return E()?.action(ye=>{const Ae=ye.get(Sn);J=Hr(Ls(ye,Ae.state.doc),t)}),J},canonical:J=>{let ye=null;return E()?.action(Ae=>{const j=Ae.get(Pr)(wr(J,t));j&&(ye=Hr(Ls(Ae,j),t))}),ye},insertFiles:J=>{p(J)},insertMarkdown:(J,ye,Ae)=>fe(J,ye,Ae),parseMd:J=>{let ye=null;return E()?.action(Ae=>{const j=Ae.get(Pr)(wr(J,t));ye=j?.childCount?j.content:null}),ye},serializeMd:J=>{let ye=null;try{E()?.action(Ae=>{const W=Ae.get(Sn).state.schema.topNodeType.createAndFill(void 0,J);W&&(ye=vf(Ae.get(zp)(W)))})}catch{return null}return ye},serializeStored:J=>{let ye=null;try{E()?.action(Ae=>{const j=Ae.get(Sn).state.schema.topNodeType.createAndFill(void 0,J);j&&(ye=Hr(Ls(Ae,j),t))})}catch{return null}return ye},focusStart:()=>{E()?.action(J=>{const ye=J.get(Sn);ye.dispatch(ye.state.tr.setSelection(Le.atStart(ye.state.doc))),ye.focus()})},focusEnd:()=>{E()?.action(J=>{const ye=J.get(Sn);ye.dispatch(ye.state.tr.setSelection(Le.atEnd(ye.state.doc))),ye.focus()})},focusTail:()=>{E()?.action(J=>{const ye=J.get(Sn),{doc:Ae,schema:j}=ye.state,W=j.nodes.paragraph,ne=et=>!!et&&et.type===W&&et.content.size===0,he=Ae.lastChild;let qe=ye.state.tr;ne(he)||(qe=qe.insert(Ae.content.size,W.create())),ye.dispatch(qe.setSelection(Le.atEnd(qe.doc)).scrollIntoView()),ye.focus()})},hasFocus:()=>{let J=!1;return E()?.action(ye=>{J=ye.get(Sn).hasFocus()}),J},revealSelection:()=>{E()?.action(J=>{const ye=J.get(Sn);ye.dispatch(ye.state.tr.scrollIntoView()),ye.focus()})},serializePrefix:J=>{let ye=null;try{E()?.action(Ae=>{const j=Ae.get(Sn);ye=Hr(Ls(Ae,j.state.doc.cut(0,Math.min(J,j.state.doc.content.size))),t)})}catch{return null}return ye},posAfterPrefix:J=>{let ye=null;try{E()?.action(Ae=>{const j=Ae.get(Pr)(wr(J,t));j&&(ye=Le.atEnd(j).head)})}catch{return null}return ye}},()=>{if(!me.current.skipFinalFlush()){const J=i.current?.serializeNow()??null;J!=null&&me.current.onFinalFlush(J)}i.current=null}),[E,t]);const ge=async J=>{try{const ye=new Uint8Array(await J.arrayBuffer()),{opts:Ae}=await ta(),{pageRel:j}=await on.saveAttachment(e,J.name||"pasted.png",ye,Ae);return gc(xc(t,j),!0)}catch{return null}},p=async J=>{if(!J.length)return;const ye=J.map((j,W)=>`​${je("unipage.upload.uploading",{name:j.name||je("unipage.upload.fileN",{n:W+1})})}​`);E()?.action(j=>{const W=j.get(Sn),ne=W.state.schema.nodes.paragraph;if(!ne)return;const{$to:he}=W.state.selection;let qe=he.depth>=1?he.after(1):he.pos,et=W.state.tr;for(const ht of ye){const Ye=ne.create(null,W.state.schema.text(ht));et=et.insert(qe,Ye),qe+=Ye.nodeSize}W.dispatch(et.scrollIntoView())});const Ae=(j,W)=>{E()?.action(ne=>{const he=ne.get(Sn);let qe=-1,et=-1;if(he.state.doc.descendants((Ot,Kt)=>qe>=0||!Ot.isTextblock||Ot.textContent!==j?!0:(qe=Kt,et=Kt+Ot.nodeSize,!1)),qe<0)return;const ht={from:qe,to:et},Ye=he.state.schema.nodes.paragraph,Ht=W&&Ye?he.state.tr.replaceWith(ht.from,ht.to,Ye.create(null,he.state.schema.text(W))):he.state.tr.delete(ht.from,ht.to);he.dispatch(Ht)})};for(let j=0;j<J.length;j++)Ae(ye[j],await ad(e,J[j]))},fe=(J,ye="cursor",Ae)=>{let j=!1;return E()?.action(W=>{const ne=W.get(Sn),he=W.get(Pr)(wr(J,t));if(!he?.childCount)return;const qe=he.content,et=!!Ae?.quiet,ht=et?Ov(ne.state.doc,Ae?.after):null;if(et&&ht==null&&Ae?.caretless&&(ye="end"),ye!=="cursor"||ht!=null){const ft=ht??(ye==="start"?0:ne.state.doc.content.size),pt=ne.state.tr.insert(ft,qe);et?ce(ne,pt,ft):ne.dispatch(pt),j=!0;return}const{$from:Ye}=ne.state.selection;let Ht=Ye.depth;for(;Ht>=1&&!["doc","amadeusColumnCell","blockquote"].includes(Ye.node(Ht-1).type.name);)Ht--;if(Ht<1)return;const Ot=(ft,pt)=>{const Vt=Le.near(ft.doc.resolve(Math.min(pt,ft.doc.content.size)),-1),bn=Ae?.caretBack??0;ft.setSelection(bn&&Vt.$from.parentOffset>=bn?Le.create(ft.doc,Vt.from-bn):Vt)};if(Ye.depth>Ht&&Ye.parent.isTextblock&&Ye.parent.content.size===0){const ft=ne.state.tr,pt=bn=>{const Jt=ft.doc.resolve(bn),vn=Jt.index(-1);return Jt.parent.isTextblock&&Jt.parent.content.size===0&&Jt.node(-1).canReplace(vn,vn+1,qe)};let Vt=Ye.pos;if(!pt(Vt)){for(let bn=ft.doc.resolve(Vt).depth;bn>0;bn--)if(ft.doc.resolve(Vt).node(bn).type.name==="list_item"){Vt=kf(ft,Vt,["list_item"]);break}}if(pt(Vt)){const bn=ft.doc.resolve(Vt),Jt=bn.before();ft.replaceWith(Jt,bn.after(),qe),Qs(ft,Jt,Jt+qe.size),Ot(ft,Jt+qe.size),et?ce(ne,ft,Jt):(ne.dispatch(ft.scrollIntoView()),ne.focus()),j=!0;return}}const Kt=Ye.before(Ht),Ut=Ye.after(Ht),Ze=Ye.node(Ht).textContent.trim()==="",yn=Ze?ne.state.tr.replaceWith(Kt,Ut,qe):ne.state.tr.insert(Ut,qe);Qs(yn,Ze?Kt:Ut,(Ze?Kt:Ut)+qe.size),Ot(yn,(Ze?Kt:Ut)+qe.size),et?ce(ne,yn,Ze?Kt:Ut):(ne.dispatch(yn.scrollIntoView()),ne.focus()),j=!0}),j},ce=(J,ye,Ae)=>{J.dispatch(ea(ye)),Gl(J,Math.min(Ae+1,J.state.doc.content.size));const j=J.nodeDOM(Ae);if(!(j instanceof HTMLElement))return;const W=j.getBoundingClientRect();(W.top<0||W.top>window.innerHeight-40)&&us(j),Gs(j.getBoundingClientRect())},te=(J,ye=!0)=>{let Ae=null;return E()?.action(j=>{Ae=Cv(j.get(Sn),J,ye)}),Ae},ee=J=>{J&&E()?.action(ye=>td(ye.get(Sn),J.id))},Ie=(J,ye,Ae=!0)=>{if(ye?.cancelled())return;if(c?.()){ee(ye),Dl(ye?.label??"");return}const j=()=>{Ae||!ye?window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.insertPointLost")}})):Mv(ye.label)};if(!i.current||!ye){j();return}let W=!1;E()?.action(ne=>{const he=ne.get(Pr)(wr(J,t));W=Ev(ne.get(Sn),ye.id,he?.childCount?he.content:null)}),W||j()},Me=async(J,ye,Ae,j=!1)=>{try{const{base:W}=await on.saveAttachment(e,J,ye,{mode:"vault",folder:Sa(e)});return Ie(`![[${j?W.replace(/\.md$/i,""):W}]]`,Ae),F.getState().syncFdChildren(e),!0}catch{return ee(Ae),!1}},dt=x.useRef(()=>{}),tt=J=>{const ye=U.current;if(!ye)return;const Ae=J.run?void 0:Ef[J.scaffold];if(Ae){ye.transform(Ae)||Mf(J.label);return}ye.consume();const j=zf;if(J.scaffold===j.template){window.dispatchEvent(new CustomEvent("amadeus:template-picker",{detail:{v4Path:e}}));return}if(J.scaffold===j.card){E()?.action(W=>Ne.current(W.get(Sn)));return}if(J.scaffold===j.instructions||J.scaffold===j.agentTask||J.scaffold===j.prompt){const W=J.scaffold===j.instructions?"instructions":J.scaffold===j.agentTask?"task":"prompt";fe(Af(W,W==="instructions"?"":xs(Nf())));return}if(J.scaffold===j.ai){E()?.action(W=>be.current?.(W.get(Sn)));return}if(J.run){const W=te(J.label);(async()=>{try{const ne=await J.run({pagePath:e,folder:Sa(e)});if(ne===""||ne==null){ee(W);return}if(typeof ne!="string")throw new Error(je("unipage.plugin.notString",{type:typeof ne}));if(ne.length>8192)throw new Error(je("unipage.plugin.tooLong"));if(Array.from(ne).some(he=>he.charCodeAt(0)<32&&he!==" "&&he!==`
708
+ `))throw new Error(je("unipage.plugin.controlChars"));Ie(ne,W,!1),F.getState().syncFdChildren(e)}catch(ne){if(ee(W),W?.cancelled())return;console.error("[plugin] slash item failed",ne),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.plugin.failed",{label:J.label,err:ne instanceof Error?ne.message:String(ne)}),error:!0}}))}})();return}if(J.scaffold===j.image){const W=document.createElement("input");W.type="file",W.accept="image/*",W.onchange=()=>{const ne=W.files?.[0];if(!ne)return;const he=te(J.label);(async()=>{try{const qe=new Uint8Array(await ne.arrayBuffer()),{opts:et}=await ta(),{base:ht}=await on.saveAttachment(e,ne.name||"image.png",qe,et);Ie(`![[${ht}]]`,he)}catch{ee(he)}})()},W.click();return}if(J.scaffold===j.column){E()?.action(W=>{const ne=W.get(Sn),{$from:he}=ne.state.selection;if(he.depth!==1){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.columnTopLevelOnly")}}));return}Mu(ne,he.before(1),he.after(1),he.node(1)),ne.focus()});return}if(J.scaffold===j.page){const W=te(J.label);(async()=>{try{const ne=F.getState(),he=await ne.createChildNote(e,je("amadeus.default.note"));Ie(`[[${he.split("/").pop().replace(/\.md$/i,"")}]]`,W),ne.loadPage(he)}catch{ee(W)}})();return}if(J.scaffold===j.database){const W=je("amadeus.default.database");Me(`${W}.db`,new TextEncoder().encode(ni(Pd(W))),te(J.label)).then(ne=>{ne&&ru("base.create")});return}if(J.scaffold===j.drawing){Me(`${Tf(je("unipage.file.drawing"))}.excalidraw.md`,new TextEncoder().encode(Od(Fd)),te(J.label),!0);return}if(J.scaffold===j.noteview){const W=te(J.label);(async()=>{const ne=Sa(e);let he=null;for(let et=1;et<=20&&he===null;et++)try{he=await on.createFolder(ne,et===1?je("unipage.file.noteView"):je("unipage.file.noteViewN",{n:et}))}catch{}if(he===null){ee(W);return}const qe=je("unipage.file.untitledView");await Me(`${qe}.db`,new TextEncoder().encode(ni(Bd(qe,he))),W)})();return}if(J.scaffold===j.linkdb){de(!0);return}if(J.scaffold===j.bookmark){const W=te(J.label,!1);Ga(je("unipage.bookmark.title"),"",{label:je("unipage.bookmark.label")}).then(ne=>{const he=ne?.trim();he&&/^https?:\/\/\S+$/i.test(he)?Ie(he,W,!1):ee(W)});return}if(J.scaffold===j.embed){const W=te(J.label,!1);(async()=>{let ne="";try{const et=/!?\[\[([^\]\n]+)\]\]/.exec(await navigator.clipboard.readText());et&&(ne=et[1].trim())}catch{}const qe=(await Ga(je("unipage.embed.title"),ne,{label:je("unipage.embed.label"),confirmLabel:je("unipage.embed.confirm")}))?.trim().replace(/^!?\[\[/,"").replace(/\]\]$/,"").trim();qe?Ie(`![[${qe}]]`,W,!1):ee(W)})();return}fe(J.scaffold,"cursor",J.key==="math"?{caretBack:3}:void 0)};return dt.current=tt,u.jsxs(u.Fragment,{children:[u.jsx(Sf,{initial:wr(n,t),onChange:J=>o(Hr(J,t)),keys:Xv,saveImage:ge,saveFiles:p,onOpenWiki:(J,ye)=>{F.getState().openWikiLink(J,e,ye??{split:!0})},getPageNames:()=>F.getState().pages,slashOpsRef:U,onSlashPick:tt,getFiles:()=>Ap()?F.getState().files:[],isWikiResolved:J=>!!ys(J,F.getState().pages,e)||!!vm(J,F.getState().files,e),wikiIcon:J=>{const ye=ys(J,F.getState().pages,e);return ye?F.getState().icons[ye]:void 0},focusPlace:m,onFocused:g,unified:!0,attachmentPagePath:e,extraPlugins:l,readOnly:M,onAskTangu:S,aiMenu:z}),q&&u.jsx(ir,{children:u.jsx(Cf,{onClose:()=>de(!1),onPick:J=>{de(!1),c?.()?Dl(je("mdblock.slash.linkdb")):fe(`![[${J}]]`)}})})]})}function _l(e){e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)}function Zv(e){const t=e.selectionEnd;if(t>=e.value.length)return!0;const n=getComputedStyle(e),o=document.createElement("div");for(const a of["fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","wordSpacing","lineHeight","textTransform","textIndent","tabSize","paddingLeft","paddingRight","borderLeftWidth","borderRightWidth","boxSizing","wordBreak","overflowWrap"])o.style[a]=n[a];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 i=r.offsetTop>=s.offsetTop;return o.remove(),i}function Qv({path:e,icon:t,cover:n,onSetIcon:o,onSetCover:r,onRename:s,onDetachedRename:c,onEnterBody:i,focusSignal:a,compact:l=!1,readOnly:m=!1}){const{t:g}=Bt(),C=Xl(),M=(e.split("/").pop()??e).replace(/\.md$/i,""),S=Bg.test(M)?"":M,[z,L]=x.useState(S),[E,F]=x.useState(null),[U,q]=x.useState(null),de=x.useRef(null),me=x.useRef(null),Ne=x.useRef(c);Ne.current=c,x.useEffect(()=>{L(S),me.current=null},[e]),x.useLayoutEffect(()=>()=>{const fe=me.current;me.current=null,fe!=null&&Ne.current(fe)},[]),x.useLayoutEffect(()=>{_l(de.current)},[z]),x.useEffect(()=>{const fe=de.current;if(!fe)return;let ce=fe.clientWidth;const te=new ResizeObserver(()=>{fe.clientWidth!==ce&&(ce=fe.clientWidth,_l(fe))});return te.observe(fe),()=>te.disconnect()},[]),x.useEffect(()=>{if(!a)return;const fe=de.current;if(fe){fe.focus();const ce=fe.value.length;fe.setSelectionRange(ce,ce)}},[a]);const be=x.useRef(null),ge=x.useRef(!1),p=()=>{const fe=be.current;if(be.current=null,me.current=null,ge.current){ge.current=!1,L(S);return}const ce=z.trim();ce&&ce!==M?s(ce,fe).then(te=>{te||L(S)}):L(S)};return m?u.jsxs("div",{className:"amx-title-wrap amx-title-ro",children:[t&&u.jsx("span",{className:"amx-title-bigicon","aria-hidden":!0,children:t}),u.jsx("div",{className:"amx-title-row",children:u.jsx("h1",{className:"amx-title-input amx-title-static",children:S||M})})]}):u.jsxs("div",{className:"amx-title-wrap",children:[!l&&t&&u.jsx("button",{className:"amx-title-bigicon",title:g("unipage.title.iconAction"),onClick:fe=>{const ce=fe.currentTarget.getBoundingClientRect();F({x:ce.left,y:ce.bottom+6})},children:t}),!l&&(!t||!n)&&u.jsxs("div",{className:"amx-title-actions",children:[!t&&u.jsxs("button",{onClick:()=>o(Wg()),children:[u.jsx(Wh,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),g("unipage.title.addIcon")]}),!n&&u.jsxs("button",{onClick:fe=>{const ce=fe.currentTarget.getBoundingClientRect();q({x:ce.right,y:ce.bottom+6})},children:[u.jsx(tu,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),g("unipage.title.addCover")]})]}),u.jsx("div",{className:"amx-title-row",children:u.jsx("textarea",{ref:de,className:"amx-title-input",rows:1,spellCheck:C,value:z,placeholder:"New Page",onChange:fe=>{const ce=fe.target.value.replace(/[\r\n]+/g," ");me.current=ce,L(ce)},onBlur:p,onKeyDown:fe=>{if(fe.nativeEvent.isComposing||fe.keyCode===229)return;const ce=fe.currentTarget;if(fe.key==="Tab"){fe.preventDefault();return}const te=ce.selectionStart===ce.selectionEnd,ee=te&&ce.selectionEnd===ce.value.length,Ie=!fe.shiftKey&&!fe.altKey&&!fe.metaKey&&!fe.ctrlKey,Me=fe.key==="ArrowDown"&&Ie&&te&&Zv(ce);(fe.key==="Enter"||fe.key==="ArrowRight"&&Ie&&ee||Me)&&(fe.preventDefault(),be.current=fe.key==="Enter"?"enter":"move",ce.blur(),i(fe.key==="Enter"?"enter":"move")),fe.key==="Escape"&&(me.current=null,ge.current=!0,L(S),ce.blur())}})}),E&&u.jsx(Yg,{x:E.x,y:E.y,current:t,onPick:fe=>{o(fe),F(null)},onClose:()=>F(null)}),U&&u.jsx(yu,{page:e,x:U.x,y:U.y,onApply:fe=>r(fe),onClose:()=>q(null)})]})}function ew(e){const t=Zr().getState().vaultRoot,n=x.useContext(ou),[o]=x.useState(()=>!e.readOnly&&sd(t,n,e.path)),[r,s]=x.useState(null),c=x.useRef(null);return x.useLayoutEffect(()=>{if(!o||r)return;if(c.current){s(c.current);return}const i=e.diskRaw??e.initial,a=Yv(t,n,e.path,yo(i).text),l={initial:a?.text??e.initial,diskRaw:i,inheritedMove:a?.text!=null&&a.text!==yo(i).text,moveCaret:a?.snapshot.caret};c.current=l,s(l)},[o,r,e,t,n]),o&&!r?null:u.jsx(tw,{...e,...r})}function tw({path:e,initial:t,diskRaw:n,probe:o,onRenamed:r,onCanvasMode:s,historyRef:c,filesRef:i,mdRef:a,onUnlock:l,compact:m=!1,readOnly:g=!1,hardBreaks:C=!1,inheritedMove:M=!1,moveCaret:S}){const z=e.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),L=Zr(),E=L.getState().vaultRoot,F=x.useContext(ou),U=sm(),q=F??U,de=gp(f=>xp(f,q)),me=g?"wysiwyg":de,{t:Ne}=Bt(),be=Xl(),ge=x.useRef(null);if(!ge.current){const f=yo(n??t),{fmText:v,body:k}=Er(n==null?f.text:yo(t).text);ge.current={fm:v,body:k,lastSaved:f.text,eol:f.eol,pending:M,timer:null,reconcileBusy:0,unpreserved:null,preserved:new Set,failed:!1,retryTimer:null,retryN:0,stashed:M?yo(t).text:null,writing:0,dead:!1,retired:!1,sawRows:!1,ownedCards:new Set,chain:Promise.resolve(),readOnly:g,slot:F,peerPatch:null}}const p=ge.current,fe=x.useRef(0),ce=x.useRef(null),te=x.useRef(()=>{ce.current?.()}).current,ee=()=>{fe.current=performance.now(),hi(te)},Ie=x.useRef(!1);x.useEffect(()=>{F!=null&&F===U&&ee()},[F,U]);const[Me]=x.useState(()=>new Set),dt=()=>{for(const f of[...Me])f()},[tt,J]=x.useState(0),[ye,Ae]=x.useState(0),j=x.useRef(null),W=x.useRef(me==="source"),ne=x.useMemo(()=>({get current(){return W.current?null:j.current}}),[]);if(W.current!==(me==="source")){if(me==="source"){const f=j.current?.serializeNow();f!=null&&(p.body=f)}W.current=me==="source"}const he=x.useRef(null),qe=x.useRef(null),[et,ht]=x.useState(null),[Ye,Ht]=x.useState(()=>{if(Wr())return!1;const f=am(E,e);return f?f==="canvas":On(un(p.fm))?.mode==="canvas"}),[Ot,Kt]=x.useState(0),Ut=x.useRef(!1),Ze=x.useRef(Ye);Ze.current=Ye;const yn=x.useRef(!1),ft=un(p.fm),pt=x.useMemo(()=>On(ft),[ft]),Vt=pt?.main??{x:0,y:0,w:qo},bn=()=>{const f=!Ye;if((ne.current?.hasFocus()??!1)&&(f?Kt(k=>k+1):Ut.current=!0),f){const k=qe.current?.closest(".amx-pane");k&&zi(E,e,k.scrollTop)}Ze.current=f,yn.current=!0,fm(E,e,f?"canvas":"doc"),Ht(f),f&&ru("note.canvas"),un(p.fm)!=null&&(Nt(),nn())},Jt=x.useRef(bn);Jt.current=bn,ce.current=me==="source"?null:()=>Jt.current(),cm(F,me==="source"?null:pu(Ye,()=>Jt.current())),x.useEffect(()=>(hi(te),()=>yp(te)),[te]);const vn=x.useRef(f=>ne.current?.applySlashItem(f)).current;x.useEffect(()=>(va(vn),()=>{$f()===vn&&va(null)}),[vn]),x.useEffect(()=>(s?.({on:Ye,toggle:()=>Jt.current(),...Ye&&me!=="source"&&!g?{exportCanvas:()=>jr.current?.()}:{}}),()=>s?.(null)),[Ye,s,me,g]);const jn=x.useRef(null),jr=x.useRef(null);x.useEffect(()=>{if(!c)return;const f=b=>{if(p.readOnly)return!1;if(Ze.current&&jn.current)return jn.current(b);const T=A();return!!T&&(b==="undo"?Ua:Ul)(T.state,T.dispatch)},k={undo:()=>f("undo"),redo:()=>f("redo"),indent:b=>{const T=A();return!p.readOnly&&!!T&&h.indent(T,b)}};return c.current=k,()=>{c.current===k&&(c.current=null)}},[c]);const rn=f=>{const v=un(p.fm);if(v!=null&&On(v)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.canvasElementsFailed"),error:!0}}));return}p.fm=ps(p.fm,xo(p.fm),kb(v,f)),J(k=>k+1),pe(),nn()},Wn=f=>{const v=un(p.fm);if(v!=null&&On(v)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.canvasTreeFailed"),error:!0}}));return}p.fm=ps(p.fm,xo(p.fm),Cb(v,f)),J(k=>k+1),pe(),nn()},Zn=f=>{const v=un(p.fm);if(v!=null&&On(v)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.canvasMainFailed"),error:!0}}));return}p.fm=ps(p.fm,xo(p.fm),Sb(v,f)),J(k=>k+1),pe(),nn()},pr=x.useMemo(()=>({log:[],future:[]}),[e]),Yn=Ye&&me!=="source";x.useEffect(()=>{ht(qe.current)},[]),x.useEffect(()=>{const f=he.current?.closest(".amx-pane");if(f)return f.classList.toggle("amx-canvas-pane",Yn),()=>f.classList.remove("amx-canvas-pane")},[Yn]),x.useEffect(()=>{if(Ye)return;const f=qe.current?.closest(".amx-pane");if(!f)return;const v=im(E,e);let k=!1,b=0;const T=performance.now()+1500,y=()=>{if(f.scrollTop=v,f.scrollTop!==v&&performance.now()<T){b=requestAnimationFrame(y);return}k=!0};b=requestAnimationFrame(y);const Z=()=>{cancelAnimationFrame(b),k=!0},ue=()=>{k&&zi(E,e,f.scrollTop)};return f.addEventListener("scroll",ue,{passive:!0}),f.addEventListener("wheel",Z,{passive:!0}),f.addEventListener("pointerdown",Z),f.addEventListener("keydown",Z),()=>{cancelAnimationFrame(b),f.removeEventListener("scroll",ue),f.removeEventListener("wheel",Z),f.removeEventListener("pointerdown",Z),f.removeEventListener("keydown",Z)}},[Ye,e,E]),x.useEffect(()=>{if(Ye||!Ut.current)return;Ut.current=!1;let f=0;const v=requestAnimationFrame(()=>{f=requestAnimationFrame(()=>ne.current?.revealSelection())});return()=>{cancelAnimationFrame(v),cancelAnimationFrame(f)}},[Ye]);const[Un,Go]=x.useState(()=>{const f=document.activeElement;if(S?.focused&&(!f||f===document.body)&&(F==null||F===Mi()))return{place:"restore",body:"",doc:null,anchor:S.anchor,head:S.head};const v=Ys;return v?.path===e&&v.scope===F?(Ys=null,Date.now()-v.at<1e4?v.req:null):null}),vo=x.useRef(Un);vo.current=Un;const Rr=x.useRef(null),[zn,En]=x.useState(null),[Fn,lt]=x.useState(null),Mt=x.useRef(0);x.useEffect(()=>{zn||(lt(null),clearTimeout(Mt.current))},[zn]);const co=(f,v)=>{if(clearTimeout(Mt.current),Fn&&!v)return;const k=f.closest(".unified-block-menu");if(!k)return;const b=k.getBoundingClientRect(),T=f.getBoundingClientRect(),y=b.right+4+b.width>window.innerWidth-8;lt({x:y?b.left-4-b.width:b.right+4,y:T.top-5,anchorTop:T.bottom+5,focus:v})},wo=()=>{clearTimeout(Mt.current),Mt.current=window.setTimeout(()=>{document.querySelector(".unified-block-submenu")?.contains(document.activeElement)&&document.querySelector('.unified-block-menu [data-sub="turnInto"]')?.focus(),lt(null)},180)};x.useLayoutEffect(()=>{if(!Fn?.focus)return;let f=0,v=0;const k=()=>{const b=document.querySelector(".unified-block-submenu button");b?.focus(),document.activeElement!==b&&++f<10&&(v=requestAnimationFrame(k))};return k(),()=>cancelAnimationFrame(v)},[Fn]);const Jo=x.useRef(null),[jo,Xn]=x.useState(null),Rn=x.useRef(()=>{}),wn=x.useRef({tree:()=>({}),detach:()=>{},minted:()=>{}}),h=x.useMemo(()=>db({onMenu:f=>{const v=h.getView();Jo.current=v?{doc:v.state.doc,sel:v.state.selection}:null,En({...f,cell:Bv(v,f.x,f.y)})},onBlocksDeleted:f=>Rn.current(f),canvasTree:()=>wn.current.tree(),onCardDetach:f=>wn.current.detach(f),onCardsMinted:f=>wn.current.minted(f)}),[]),A=()=>W.current?null:h.getView(),[P]=x.useState(()=>kg(A)),I=f=>{const v=h.getView();v&&fb(e,hl(f),hl(v.state.doc.content))};Rn.current=I,wn.current={tree:()=>qt(On(un(p.fm))?.tree),detach:f=>{const v=qt(On(un(p.fm))?.tree);let k=!1;for(const b of f)b in v&&(delete v[b],k=!0);k&&Wn(v)},minted:f=>{for(const v of f)p.ownedCards.add(v)}};const H=x.useRef({vaultRoot:E,path:e});H.current={vaultRoot:E,path:e};const X=x.useRef(!1),ie=x.useRef(()=>{}),[G,oe]=x.useState({count:0,index:0}),V=x.useRef(()=>{}),ze=E?`${E.replace(/[\\/]+$/,"")}/${e}`:e,Ke=x.useSyncExternalStore(bp,()=>!g&&vp(ze));V.current=f=>{const v=f.current==null?0:f.changes.findIndex(k=>k.id===f.current)+1;oe(k=>k.count===f.changes.length&&k.index===v?k:{count:f.changes.length,index:v})};const Ve=x.useMemo(()=>[...h.plugins,...Fx,...$x(()=>ja(xo(p.fm)),()=>{p.sawRows=!0}),...Ab,...bb(()=>On(un(p.fm)),()=>ja(xo(p.fm)),f=>{for(const v of f)p.ownedCards.add(v)}),...Iy({path:e,readOnly:g,alive:()=>!p.dead&&!p.retired&&!p.readOnly&&!W.current,flush:async()=>{if(p.dead||p.retired||p.readOnly||W.current)throw new Error(je("documentTask.sourceGone"));if(Nt(),dt(),p.timer&&(clearTimeout(p.timer),p.timer=null),await Zt(!0),p.dead||p.retired||p.failed)throw new Error(je("documentTask.sourceGone"))}}),wg(),...kv(),...Nb(()=>Ze.current),...Db(pr),...Tb(),...Rb(()=>On(un(p.fm))),...pv(V),...Nv({spaceTrigger:()=>eg()&&X.current,onSpace:ie}),...Nm,...Tm,...Gm(()=>H.current),...Sg(),...Cg(()=>Kn.current()),...Eg({where:()=>H.current,restore:()=>At.current(),focus:()=>sn.current()}),...C?hf:[]],[h,e,g,C]);x.useEffect(()=>{if(!zn)return;const f=b=>{b.target?.closest?.(".ctx-menu")||En(null)},v=b=>{const T=document.querySelector(".unified-block-menu"),y=document.querySelector(".unified-block-submenu"),Z=!!y&&y.contains(document.activeElement),ue=!!T&&T.contains(document.activeElement)||Z,Ce=T?.querySelector('[data-sub="turnInto"]');if(b.key==="Escape"){if(b.stopPropagation(),Z){lt(null),Ce?.focus();return}En(null),h.getView()?.focus();return}if(!T||b.isComposing)return;const _e=!b.metaKey&&!b.ctrlKey&&!b.altKey&&!b.shiftKey;if(_e&&Z&&b.key==="ArrowLeft"){b.preventDefault(),b.stopPropagation(),lt(null),Ce?.focus();return}if(_e&&!Z&&b.key==="ArrowRight"&&Ce&&document.activeElement===Ce){b.preventDefault(),b.stopPropagation(),co(Ce,!0);return}if(_e&&["ArrowDown","ArrowUp","Home","End"].includes(b.key)){b.preventDefault(),b.stopPropagation();const He=[...(Z?y:T).querySelectorAll('button:not([aria-disabled="true"])')],Ge=He.indexOf(document.activeElement),ct=He.length,mt=b.key==="Home"?0:b.key==="End"?ct-1:Ge<0?b.key==="ArrowUp"?ct-1:0:(Ge+(b.key==="ArrowDown"?1:-1)+ct)%ct;He[mt]?.focus();return}ue&&(b.key==="Enter"||b.key===" ")||["Shift","Meta","Control","Alt","CapsLock"].includes(b.key)||(En(null),ue&&(b.preventDefault(),h.getView()?.focus()))};let k=0;if(zn.keyboard){let b=0;const T=()=>{const y=document.querySelector(".unified-block-menu");if(!y){++b<10&&(k=requestAnimationFrame(T));return}const Z=zn.focus==="turnInto"?y.querySelector('[data-sub="turnInto"]'):null;if(Z){co(Z,!0);return}y.querySelector("button")?.focus()};k=requestAnimationFrame(T)}return window.addEventListener("pointerdown",f,!0),window.addEventListener("contextmenu",f,!0),window.addEventListener("keydown",v,!0),()=>{cancelAnimationFrame(k),window.removeEventListener("pointerdown",f,!0),window.removeEventListener("contextmenu",f,!0),window.removeEventListener("keydown",v,!0)}},[zn]);const Be=f=>{const v=Jo.current;return Jo.current=null,v?f.state.doc!==v.doc?(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.menu.stale")}})),!1):(f.state.selection.eq(v.sel)||f.dispatch(f.state.tr.setSelection(v.sel)),!0):!0},We=f=>{En(null);const v=h.getView();if(!v||!Be(v))return;const k=v.state.selection;k instanceof Se&&(f(v,k),v.focus())},Qe=(f,v)=>{En(null);const k=h.getView();if(!k||!Be(k))return;const b=h.topRangeOf(k);b?f(k,b):k.state.selection instanceof Se&&v(k,k.state.selection),k.focus()},Xe=f=>{const v=f.state.selection,k=h.topRangeOf(f)??(v instanceof Se?{from:v.from,to:v.to}:null);return k&&{from:k.from,to:ms(f.state,k.from,k.to)}},st=!g&&!!Nr()?.askInChat,Xt=(f,v,k)=>{const b=Iv(f.state.doc,v,k,e);b&&Nr()?.askInChat?.([Au(ic(f.state.doc),e),b].filter(Boolean).join(`
709
+
710
+ `).slice(0,2e4))},Dt=!g&&!!Nr()?.complete;X.current=Dt;const zt=Xr(f=>f.selectionActions),[Ue,Ln]=x.useState(null),ln=["improve","fix","shorter","longer","summarize","continue","custom"].map(f=>({id:f,label:Ne(`inlineai.action.${f}`)})),io=(f,v)=>{const k=h.getView()?.state.doc,b=k?k.textBetween(Math.min(f,k.content.size),Math.min(v,k.content.size),`
711
+ `,"").length:v-f;return Um(zt,{view:"note",editable:!0,length:b}).map(T=>{const y=Lp(T.item.icon);return{id:Xm(T),label:T.item.title,icon:y?u.jsx("span",{className:"selbar-ico",children:y}):void 0}})},lo=e.split("/").pop().replace(/\.md$/i,""),Zo=(f,v)=>{if(!Dt)return;const k=f.state.selection,b=v==="prompt",T=b?k.head:k.from,y=b?k.head:k.to;if(!b&&y<=T)return;const Z=v.startsWith("plugin:")?v.slice(7):void 0,ue=Z?zt.find(mt=>`${mt.pluginId}:${mt.item.id}`===Z):void 0,Ce=f.state.doc.textBetween(T,y,`
712
+ `,"");if(ue?.item.output==="none"){const mt=ne.current?.serializeMd(f.state.doc.slice(T,y).content)??Ce;Oi(ue,{text:Ce,markdown:mt,pagePath:e,view:"note",editable:!0,source:{path:e,title:lo}}).catch(rt=>window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("selbar.failed",{title:ue.item.title,e:String(rt?.message||rt)})}})));return}Tv(f,T,y);const _e=f.coordsAtPos(T),He=f.coordsAtPos(y),Ge=Z||b?b?"prompt":"custom":v,ct=Z?ue?.item.title??Ne("inlineai.label"):Ne(b?"inlineai.label":`inlineai.action.${v}`);Ln({key:Date.now(),x:_e.left,y:He.bottom+6,top:_e.top-6,title:ct,hasSelection:!b,askFirst:b||v==="custom",action:Ge,plugin:Z,...v==="translate"?{language:Pi(Ce)}:{}})};ie.current=f=>Zo(f,"prompt");const _n=f=>async(v,k,b)=>{const T=h.getView(),y=T?Pl(T):null;if(!T||!y)throw new Error(je("unipage.toast.insertPointLost"));const Z=y.to>y.from?ne.current?.serializeMd(T.state.doc.slice(y.from,y.to).content)??y.text:"";if(f.plugin){const Ge=Xr.getState().selectionActions.find(ct=>`${ct.pluginId}:${ct.item.id}`===f.plugin);if(!Ge)throw new Error(je("selbar.err.gone"));return{text:await Oi(Ge,{text:y.text,markdown:Z,pagePath:e,view:"note",editable:!0,source:{path:e,title:lo},signal:b,onDelta:ct=>{typeof ct=="string"&&k(ct)}})}}const ue=Nr();if(!ue?.complete)throw new Error(je("inlineai.unavailable"));const{before:Ce,after:_e}=$v(T.state.doc,y.from,y.to),He=f.action==="prompt"?v?"custom":"continue":f.action;return ue.complete({action:He,...v?{instruction:v}:{},...Z?{selection:Z}:{},...Ce?{before:Ce}:{},..._e?{after:_e}:{},title:lo,pagePath:e,pageInstructions:ic(T.state.doc),...He==="translate"?{language:f.language??Pi(y.text)}:{}},{signal:b,onDelta:k})},mr=()=>{Ln(null);const f=h.getView();f&&(Il(f),f.focus())},Ro=(f,v)=>{const k=h.getView(),b=k?Pl(k):null,T=ne.current?.parseMd(v);if(Ln(null),!k||!b||!T){k&&Il(k),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.insertPointLost")}}));return}const y=Rv(k,b,T,f);k.focus(),Nt(),nn(),f==="replace"&&y==="below"&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("inlineai.targetChanged")}}))},Qo=()=>{const f=h.getView();if(!f)return;const v=yv(f),k=v?he.current?.querySelector(`[data-agent-change="${v.id}"]`):null;k instanceof HTMLElement&&us(k,48)},ko=()=>{const f=h.getView();if(!f)return;const{skipped:v}=gv(f);Nt(),nn(),v&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("agentchg.skipped",{n:String(v)})}}))},Bn=(f,v)=>{let k=!0;Qe((b,T)=>{k=bu(b,T.from,T.to,f)},(b,T)=>{const y=Wi(b,T.from,T.to,f);if(y!=null){k=y;return}T.node.type.spec.code&&Rf(b,T.from,f)||(b.dispatch(b.state.tr.setSelection(Le.near(b.state.doc.resolve(T.from+1)))),k=ca(b,f,null))}),k||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("mdblock.turn.failed",{kind:v})}}))},Lo=(f,v)=>{let k=!0;Qe((b,T)=>{k=f==="code"?ac(b,T.from,T.to):qi(b,T.from,T.to,!0)},(b,T)=>{k=f==="code"?Wi(b,T.from,T.to,"code")??ac(b,T.from,T.to):qi(b,T.from,T.to,!1)}),k||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("mdblock.turn.failed",{kind:v})}}))},Qn=()=>{const f=h.getView();if(!f)return[];const v=[];if(!pc(f)){const b=(T,y,Z,ue)=>{const Ce=Ne(Z);v.push({k:T,icon:y,label:Ce,run:()=>ue(Ce)})};b("text",Fi,"unipage.menu.text",T=>Bn({kind:"text"},T)),b("h1",bh,"unipage.menu.h1",T=>Bn({kind:"heading",level:1},T)),b("h2",wh,"unipage.menu.h2",T=>Bn({kind:"heading",level:2},T)),b("h3",Sh,"unipage.menu.h3",T=>Bn({kind:"heading",level:3},T)),b("bullet",Np,"unipage.menu.bullet",T=>Bn({kind:"bullet"},T)),b("ordered",zh,"unipage.menu.ordered",T=>Bn({kind:"ordered"},T)),b("task",Tp,"unipage.menu.task",T=>Bn({kind:"task"},T)),b("quote",$p,"unipage.menu.quote",T=>Bn({kind:"quote"},T)),b("callout",jp,"unipage.menu.callout",T=>Lo("callout",T)),b("fold",hh,"unipage.menu.fold",T=>Bn({kind:"fold"},T)),b("code",eh,"unipage.menu.code",T=>Lo("code",T))}const k=f.state.selection;if(k instanceof Se&&!["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(k.node.type.name)){const b=f.state.doc.resolve(k.from);let T=!1;for(let y=b.depth;y>=1;y--)b.node(y).type.name==="amadeusColumnCell"&&(T=!0);T||v.push({k:"card",icon:Ja,label:Ne("unipage.menu.card"),run:()=>We(y=>{hr(y)})})}return v},Hn=()=>{const f=h.getView();if(!f||h.topRangeOf(f))return null;const v=f.state.selection;return v instanceof Se?v.node.type.name==="list_item"?v.node.attrs.checked!=null?"task":v.$from.parent.type.name==="ordered_list"?"ordered":"bullet":Xg(v.node):null},hr=f=>{const v=()=>(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.cardUnavailable")}})),!1);if(!(f.state.selection instanceof Se)){const{$from:Ge}=f.state.selection;for(let mt=Ge.depth;mt>=1;mt--)if(Ge.node(mt).type.name==="list_item")return v();let ct=Ge.depth;for(;ct>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard"].includes(Ge.node(ct-1).type.name);)ct--;if(ct<1)return!1;f.dispatch(f.state.tr.setSelection(Se.create(f.state.doc,Ge.before(ct))))}const k=f.state.selection,b=f.state.doc.resolve(k.from),T=b.depth>=1?b.node(b.depth):null,y=T?.type.name==="amadeusCanvasCard"?String(T.attrs.anchor):"",Z=qt(On(un(p.fm))?.tree);let ue=0;f.state.doc.forEach(Ge=>{Ge.type.name==="amadeusCanvasCard"&&ue++});const Ce=y?(Number(T.attrs.x)||0)+(Number(T.attrs.w)||en)+80:Vt.x+Vt.w+80,_e=y?(Number(T.attrs.y)||0)+Mr(Z,y).length*72:Vt.y+ue*72,He=Xu(f,Math.round(Ce),Math.round(_e),y?{parent:y,tree:Z}:void 0);return He?(p.ownedCards.add(He),Nt(),nn(),y&&Wn(qr(qt(On(un(p.fm))?.tree),He,y)),!Ze.current&&!y&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.cardMade")}})),!0):v()},Gn=()=>{const f=Er(p.lastSaved);if(f.fmText!==p.fm&&(p.peerPatch==null||Aa(f.fmText,p.peerPatch)!==p.fm))return!1;if(f.body===p.body)return!0;if(xo(p.fm)!=null||un(p.fm)!=null)return!1;const v=ne.current?.canonical(f.body);return v!=null&&v===p.body},So=x.useRef(null),uo=()=>{So.current?.()},[qn,er]=x.useState(!1),Do=async f=>{const v=Kr(f);if(p.preserved.has(v))return;const k=await es(e,oo(f,p.eol));p.preserved.add(v),Ni(e,k,!p.readOnly&&mi(ze,f)),L.getState().refreshPages()},gr=async f=>{const v=await es(e,oo(f,p.eol));km(e,v),L.getState().refreshPages()},xr=()=>{if(p.gone==null||p.readOnly)return;Nt();const f=mn(p.fm,p.body);f!==p.gone&&(p.gone=f,Co(f))},Co=async f=>{try{await gr(f)}catch{go(E,e,f,p.lastSaved,p.slot),wm(e,f)}},Eo=(f,v=!1)=>{if(p.held=Math.max(0,(p.held??0)-1),p.readOnly||p.retired)return Promise.resolve();if(!f)return!p.held&&p.pending&&Zt(),Promise.resolve();p.retired=!0,Nt();const k=mn(p.fm,p.body);let b=null,T;p.moveHandoff=Wv(E,F,f,p.lastSaved,()=>{Nt();const He=h.getView();if(He&&!He.isDestroyed){const Ge=document.activeElement,ct=He.hasFocus()||!!T?.focused&&(!Ge||Ge===document.body);T={anchor:He.state.selection.anchor,head:He.state.selection.head,focused:ct}}return{text:mn(p.fm,p.body),caret:T}},(He,Ge)=>{He==null&&b!=null&&Bo(E,f,b,p.slot),b=He,He!=null&&go(E,f,He,Ge,p.slot)});const y=()=>{p.stashed!=null&&Bo(E,e,p.stashed,p.slot),p.stashed=null};if(k===p.lastSaved)return y(),Promise.resolve();go(E,f,k,p.lastSaved,p.slot);const Z=v?f:e,ue=()=>(L.getState().vaultRoot??null)===(E??null),Ce=async()=>{try{if(!ue())return;p.unpreserved!=null&&p.unpreserved!==k&&Ni(f,await es(Z,oo(p.unpreserved,p.eol))),p.unpreserved=null;const He=oo(k,p.eol),Ge=oo(p.lastSaved,p.eol);for(let ct=0;ct<3;ct++){const mt=await on.readTextFile(f),rt=mt==null?null:Qa(Ge,He,mt);if(rt==null)break;if(!ue())return;const ot=await on.writeTextFile(f,rt,{base:Kr(mt)});if(!ot||ot.ok!==!1){p.moveHandoff?.acknowledge(k,yo(rt).text),Bo(E,f,k,p.slot),y();return}if(ot.current==null)break}if(!ue())return;Ai(f,await es(Z,He),!0),Bo(E,f,k,p.slot),y(),L.getState().refreshPages()}catch(He){Is(f,He)}},_e=p.chain.then(Ce,Ce);return p.chain=_e.catch(()=>{}),_e},fo=f=>{if(p.retired||(p.stashed=mn(p.fm,p.body),go(E,e,p.stashed,p.lastSaved,p.slot)),p.failed||(p.failed=!0,er(!0),Is(e,f)),p.retryTimer||p.dead||p.retired)return;const v=Ti[Math.min(p.retryN,Ti.length-1)];p.retryN++,p.retryTimer=setTimeout(()=>{p.retryTimer=null,!(p.dead||p.retired||!p.pending)&&(p.reconcileBusy||Zt())},v)},Io=f=>{p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),p.retryN=0,p.failed&&(p.failed=!1,er(!1)),p.stashed!=null&&(f==null||p.stashed===f||mn(p.fm,p.body)===f)&&(Bo(E,e,p.stashed,p.slot),p.stashed=null)},Mo=f=>{p.peerPatch=null,Io(f),_d(e,p)},Zt=(f=!1)=>{if(p.readOnly)return Promise.resolve();const v=async()=>{let T=0;for(;!p.retired;){if(p.held){if(f&&mn(p.fm,p.body)!==p.lastSaved)throw new Error("The note is being moved");return}const y=mn(p.fm,p.body);if(y===p.lastSaved){p.pending=!1,Io();return}let Z;try{p.unpreserved!=null&&p.unpreserved!==y&&await Do(p.unpreserved),p.unpreserved=null,Z=await on.writeTextFile(e,oo(y,p.eol),{base:Kr(oo(p.lastSaved,p.eol))})}catch(ue){if(p.pending=!0,fo(ue),f)throw ue;return}if(Z&&Z.ok===!1&&Z.current==null){p.retired||(p.retired=!0,p.pending=!1,Nt(),p.gone=mn(p.fm,p.body),await Co(p.gone));return}if(Z&&Z.ok===!1&&Z.current!=null){const ue=yo(Z.current);p.eol=ue.eol;const Ce=ue.text;if(Ce===y){p.lastSaved=y;continue}if(++T>3){const _e=new Error("The note kept changing on disk while saving");if(p.pending=!0,fo(_e),f)throw _e;return}if(Gn()){p.pending=!1,uo();return}p.unpreserved=Ce,p.lastSaved=Ce;continue}if(p.lastSaved=y,L.getState().bumpLinkGraph(),mn(p.fm,p.body)===y&&(p.pending=!1),Mo(y),!f)return}},k=async()=>{p.writing++;try{await v()}finally{p.writing--}},b=p.chain.then(k,k);return p.chain=b.catch(()=>{}),b},eo=()=>{const f=A();if(!f)return;const v=xo(p.fm),k=Rx(f.state.doc);let b=v;k!=null?(b=k,p.sawRows=!0):p.sawRows&&v!=null&&ja(v)!=null&&(b=null);const T=wb(f.state.doc,un(p.fm),yn.current?Ze.current?"canvas":"doc":null,p.ownedCards),y=un(p.fm);p.fm=ps(p.fm,b,T),un(p.fm)!==y&&J(Z=>Z+1)},Nt=()=>{const f=ne.current?.serializeNow();f!=null&&(p.body=f,eo())},nn=()=>{if(p.moveHandoff){p.moveHandoff.capture();return}p.dead||p.retired||g||!p.writing&&mn(p.fm,p.body)===p.lastSaved||(p.pending=!0,p.timer&&clearTimeout(p.timer),p.timer=setTimeout(()=>{p.timer=null,!p.reconcileBusy&&Zt()},Uv))},[R,O]=x.useState(null),pe=()=>{O(f=>f==null?f:mn(p.fm,p.body))},ve=(f,v=!0)=>{g||(p.fm=Aa(p.fm,f),J(k=>k+1),pe(),v?(p.pending=!0,Zt().then(()=>{const k=dn.getState();k.refreshPages(),k.refreshIcons()})):nn())};x.useEffect(()=>{lm(document)},[]);const[$e,Re]=x.useState(null);x.useEffect(()=>{const f=v=>{const k=document.elementFromPoint(v.clientX,v.clientY)??v.target,b=k?.tagName==="IMG"?k:null;if(!b||!b.closest(".unified-body")||b.closest(".app-ref"))return;const T=b.currentSrc||b.src;T&&(v.preventDefault(),v.stopPropagation(),Re(T))};return document.addEventListener("dblclick",f,!0),()=>document.removeEventListener("dblclick",f,!0)},[]),di(!!$e,()=>Re(null)),di(!!zn&&!g,()=>En(null)),x.useEffect(()=>{if(!$e)return;const f=v=>{v.key==="Escape"&&Re(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[$e]),x.useEffect(()=>{const f=async()=>{p.reconcileBusy++;try{await pm(),await p.chain;const k=await on.readTextFile(e);if(k==null||p.dead||p.retired)return;const b=yo(k);p.eol=b.eol;const T=b.text;if(T===p.lastSaved&&!p.pending)return;if(p.pending&&Nt(),p.pending&&!Gn()){T!==p.lastSaved&&T!==mn(p.fm,p.body)&&(p.unpreserved=T),p.lastSaved=T;return}const{fmText:y,body:Z}=Er(T),ue=xo(y)!==xo(p.fm)||un(y)!==un(p.fm);if(p.fm=y,p.peerPatch=null,J(Ce=>Ce+1),Z!==p.body){p.ownedCards.clear();const Ce=!p.readOnly&&mi(ze,k);(ne.current??(W.current?j.current:null))?.applyBody(Z,Ce)?p.body=Z:(p.body=Z,Ae(_e=>_e+1))}else ue&&(p.ownedCards.clear(),Ae(Ce=>Ce+1));p.lastSaved=T,p.pending=!1,Io(),pe()}finally{p.reconcileBusy--,p.reconcileBusy===0&&p.pending&&Zt()}};So.current=()=>{f()};const v=on.onExternalChange?.(k=>{k===e&&f()});return f(),()=>{So.current=null,v?.()}},[e]),x.useEffect(()=>{const f=()=>{if(Nt(),dt(),p.timer&&clearTimeout(p.timer),p.timer=null,p.readOnly)return;if(p.retired){p.moveHandoff&&p.moveHandoff.capture(),p.gone!=null&&xr(),p.stashed!=null&&Bo(E,e,p.stashed,p.slot),p.stashed=null;return}const k=mn(p.fm,p.body);if(!p.writing&&k===p.lastSaved){Io();return}if(!p.writing&&Gn()){p.pending=!1;return}p.stashed=k,go(E,e,k,p.lastSaved,p.slot),Zt()},v=k=>{f(),p.failed&&p.pending&&!mm()&&(k.preventDefault(),k.returnValue="")};return window.addEventListener("beforeunload",v),()=>{p.dead=!0,window.removeEventListener("beforeunload",v),f();const k=Rr.current,b=h.getView();k&&b&&(k.doc=b.state.doc.toJSON(),k.anchor=b.state.selection.anchor,k.head=b.state.selection.head)}},[e]),x.useEffect(()=>{M&&!p.readOnly&&Zt()},[]),x.useEffect(()=>{const f=()=>{!p.failed||!p.pending||p.dead||p.retired||typeof document<"u"&&document.visibilityState==="hidden"||(p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),!p.reconcileBusy&&Zt())};return window.addEventListener("online",f),window.addEventListener("focus",f),document.addEventListener("visibilitychange",f),()=>{window.removeEventListener("online",f),window.removeEventListener("focus",f),document.removeEventListener("visibilitychange",f),p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null)}},[e]),x.useEffect(()=>{const f=ue=>{if(p.readOnly||p.retired||p.dead)return!1;Nt(),ue&&dt();const Ce=mn(p.fm,p.body);return!p.writing&&(Ce===p.lastSaved||Gn())?!1:(p.pending=!0,p.stashed=Ce,go(E,e,Ce,p.lastSaved,p.slot),!0)},v=ue=>{f(ue)&&(p.timer&&(clearTimeout(p.timer),p.timer=null),!p.reconcileBusy&&Zt())},k=()=>{document.visibilityState==="hidden"&&v(!0)},b=()=>v(!0);let T=0,y=null;const Z=()=>{const ue=T+1e3-Date.now();if(ue>0){f(!1),y||(y=setTimeout(()=>{y=null,T=Date.now(),v(!1)},ue));return}T=Date.now(),v(!1)};return document.addEventListener("visibilitychange",k),window.addEventListener("pagehide",b),document.addEventListener("freeze",b),document.addEventListener("pause",b),window.addEventListener("blur",Z),()=>{document.removeEventListener("visibilitychange",k),window.removeEventListener("pagehide",b),document.removeEventListener("freeze",b),document.removeEventListener("pause",b),window.removeEventListener("blur",Z),y&&clearTimeout(y)}},[e]);const Q=f=>p.readOnly||p.retired||p.dead||!ne.current?!1:(ne.current.insertFiles(f),!0);x.useEffect(()=>{if(!i)return;const f=v=>Q(v);return i.current=f,()=>{i.current===f&&(i.current=null)}},[i]),x.useEffect(()=>{if(!a)return;const f=v=>p.readOnly||p.retired||p.dead?!1:ne.current?.insertMarkdown(v,"cursor")??!1;return a.current=f,()=>{a.current===f&&(a.current=null)}},[a]),x.useLayoutEffect(()=>Dd({path:e,owner:p,peerWrote:()=>uo(),scope:F,lastActive:()=>fe.current,dirty:()=>p.readOnly||p.retired||p.dead?!1:(Nt(),mn(p.fm,p.body)!==p.lastSaved&&!Gn()),flush:(f=!1)=>p.readOnly?Promise.resolve():(Nt(),dt(),p.timer&&(clearTimeout(p.timer),p.timer=null),Zt(f)),insertFiles:f=>Q(f),hold:()=>(p.held=(p.held??0)+1,p.chain),release:(f,v)=>Eo(f,v),patchFm:(f,v=!1)=>p.readOnly||p.retired||p.dead?null:v?(p.fm=Aa(p.fm,f),p.peerPatch={...p.peerPatch??{},...f},J(k=>k+1),pe(),Promise.resolve()):(ve(f),p.chain),fmNow:()=>Cs(p.fm),insertMarkdown:(f,v)=>p.retired||p.readOnly?!1:ne.current?.insertMarkdown(f,v)??!1,insertReply:g?void 0:(f,v)=>{if(p.retired||p.dead||p.readOnly||!ne.current?.insertMarkdown(f,"cursor",{quiet:!0,after:v,caretless:!Ie.current}))return null;const k=A()?.state.doc,b=pr,T={n:b.log.length,top:b.log[b.log.length-1],future:b.future.length};return{undo:()=>{const y=A();return!y||!k||y.state.doc!==k||p.retired||p.dead||T.top!=="pm"||b.log.length!==T.n||b.log[b.log.length-1]!=="pm"||b.future.length!==T.future?!1:Ze.current&&jn.current?jn.current("undo"):Ua(y.state,y.dispatch)}}},bodyNow:()=>p.body,statsNow:()=>P(),headings:()=>{const f=A();return f?na(f.state.doc):[]},revealHeading:(f,v,k)=>{const b=A();if(!b)return;const T=na(b.state.doc),y=T[f]?.text===v?T[f]:T.find(ue=>ue.text===v);if(!y)return;b.focus(),b.dispatch(b.state.tr.setSelection(Le.near(b.state.tr.doc.resolve(y.pos+1))));const Z=b.nodeDOM(y.pos);Z instanceof HTMLElement&&(us(Z),k&&Gs(Z.getBoundingClientRect()))},revealBlock:(f,v)=>{const k=A();if(!k)return!1;const b=[];k.state.doc.descendants((ue,Ce,_e)=>ue.isTextblock?(b.push({pos:Ce,text:ue.textContent,parent:_e}),!1):!0);let T=b.findIndex(ue=>Kl(ue.text)===f);if(T<0)return!1;Hd(b[T].text)&&T>0&&b[T-1].parent===b[T].parent&&(T-=1);const y=b[T].pos;k.focus(),k.dispatch(k.state.tr.setSelection(Le.near(k.state.tr.doc.resolve(y+1))));const Z=k.nodeDOM(y);return Z instanceof HTMLElement&&(us(Z),v&&Gs(Z.getBoundingClientRect())),!0},focusBody:()=>{if(p.readOnly||p.retired||p.dead)return!0;const f=h.getView();return f?(f.hasFocus()||f.focus(),!0):!1},revealText:(f,v)=>{const k=A();if(!k)return!1;const b=jf(k.state.doc,f,!!v?.tag);if(!b)return!1;Gl(k,b.from),k.focus(),k.dispatch(k.state.tr.setSelection(Le.create(k.state.doc,b.from,b.to)));let T=k.nodeDOM(b.block);for(;T instanceof HTMLElement&&T!==k.dom;){const y=T.getBoundingClientRect();if(y.width||y.height)break;T=T.parentElement}return!(T instanceof HTMLElement)||T===k.dom||(us(T),v?.flash&&Gs(T.getBoundingClientRect())),!0},retire:f=>{if(Ar(),!p.retired&&!p.readOnly&&!p.dead){Nt();const v=mn(p.fm,p.body);v!==p.lastSaved&&!Gn()&&(f?go(E,f,v,p.lastSaved,p.slot):(L.getState().vaultRoot??null)!==(E??null)?go(E,e,v,p.lastSaved,p.slot):Co(v))}else p.retired&&p.gone!=null&&xr();p.retired=!0,p.timer&&(clearTimeout(p.timer),p.timer=null),p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null)}}),[e]);const[nt,at]=x.useState(()=>{if(g)return null;const f=k=>k==null?ti(e,null):hm(k)||ti(e,k),v=um(E,e,p.slot,f);return!v||M&&v.text===yo(t).text?null:v.text===p.lastSaved||v.text===(n??t)?(Bo(E,e,void 0,v.slot),null):v}),Tt=()=>{nt&&Bo(E,e,void 0,nt.slot),at(null)},gt=()=>{const f=nt;if(at(null),!f||g||p.retired)return;(f.slot??null)!==p.slot&&(Bo(E,e,f.text,f.slot),go(E,e,f.text,p.lastSaved,p.slot)),Nt();const v=p.lastSaved,k=mn(p.fm,p.body),b=k!==v?k:Kr(v)!==f.base?v:null;b!=null&&b!==f.text&&(p.unpreserved=b);const{fmText:T,body:y}=Er(f.text);p.fm=T,J(Z=>Z+1),y!==p.body&&(p.ownedCards.clear(),p.body=y,(ne.current??(W.current?j.current:null))?.applyBody(y)||Ae(Z=>Z+1)),pe(),p.pending=!0,p.stashed=f.text,Zt()};x.useEffect(()=>{o&&(o.scheduleState=()=>({pending:p.pending,lastSaved:p.lastSaved}),o.flush=()=>(Nt(),p.timer&&clearTimeout(p.timer),p.timer=null,Zt()),o.fmState=()=>({fm:p.fm,body:p.body}),o.setFm=f=>ve(f,!1),o.view=()=>h.getView(),o.serializeNow=()=>ne.current?.serializeNow()??null)},[o]);const[yt,jt]=x.useState(0);x.useEffect(()=>{dm(e)&&jt(f=>f+1)},[e]);const At=x.useRef(()=>!1);At.current=()=>!g&&!m&&!Ze.current&&vo.current==null&&yt===0;const sn=x.useRef(()=>!1);sn.current=()=>{const f=qa;if(!f||f.scope!==F||Date.now()-f.at>5e3)return!1;qa=null;const v=document.activeElement;return(!v||v===document.body)&&(F==null||F===Mi())};const Rt=x.useRef(null);x.useLayoutEffect(()=>()=>{const f=document.activeElement;f&&f!==document.body&&(he.current?.contains(f)||Rt.current?.contains(f))&&(qa={scope:F,at:Date.now()})},[]);const Kn=x.useRef(()=>!1);Kn.current=()=>Yn||g?!1:(jt(f=>f+1),!0);const Po=f=>{const v=h.getView();if(!v)return;let k=v.state.tr;if(p.body===f.body)try{const y=v.state.schema.nodeFromJSON(f.doc);y.eq(k.doc)||(k=k.replaceWith(0,k.doc.content.size,y.content))}catch{}const b=k.doc.content.size,T=y=>k.doc.resolve(Math.max(0,Math.min(y,b)));try{k=k.setSelection(Le.between(T(f.anchor),T(f.head)))}catch{}v.dispatch(k.setMeta("addToHistory",!1).scrollIntoView())},d=async(f,v=null,k=!1)=>{if(g||k&&p.retired)return!1;const b=E;try{if(Nt(),await Zt(),await gm(),k&&(await p.chain,p.retired||dn.getState().vaultRoot!==b))return!1;const T=await on.renamePageFile(e,f);if(T!==e){xm(E,e,T),Jm(E,e,T),p.retired=!0,Nt();const y=mn(p.fm,p.body),Z=p.body;if(y!==p.lastSaved)try{const _e=await on.writeTextFile(T,oo(y,p.eol),{base:Kr(oo(p.lastSaved,p.eol))});if(_e&&_e.ok===!1&&_e.current!==oo(y,p.eol))try{Ai(T,await es(T,oo(y,p.eol))),dn.getState().refreshPages()}catch(He){go(E,T,y,p.lastSaved,p.slot),Is(T,He)}}catch(_e){go(E,T,y,p.lastSaved,p.slot),Is(T,_e)}const ue=vo.current,Ce=h.getView();if(!k&&v&&ue!=null&&typeof ue!="object")Ys={path:T,scope:F,req:ue,at:Date.now()};else if(!k&&Ce?.hasFocus()){const _e={place:"restore",body:Z,doc:Ce.state.doc.toJSON(),anchor:Ce.state.selection.anchor,head:Ce.state.selection.head};Rr.current=_e,Ys={path:T,scope:F,req:_e,at:Date.now()}}Id(e,"file",T),ym(e,T,"file"),await bm(e,T),dn.getState().refreshPages(),k||r?.(T)}return!0}catch{return k&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.toast.renameDetachedFailed",{name:f})}})),!1}},N=x.useRef("");x.useEffect(()=>{const f=JSON.stringify(On(un(p.fm))?.tree??null);if(f===N.current)return;N.current=f;const v=h.getView();v&&v.updateState(v.state)},[tt,h]);const $=bg(p.fm),K=typeof $.icon=="string"&&$.icon.trim()?$.icon.trim():null,B=typeof $.cover=="string"&&$.cover.trim()?$.cover.trim():null,_=$.cover_y,Y=typeof _=="number"?_:typeof _=="string"?parseFloat(_):NaN,se=Number.isFinite(Y)?Math.max(0,Math.min(100,Y)):50,xe=x.useMemo(()=>me==="source"?mn(p.fm,p.body):"",[me,tt]),ae=x.useRef(null),re=()=>`${xo(p.fm)??""}\0${un(p.fm)??""}`;x.useEffect(()=>{if(!g)return wp(q,f=>{const v=wa(qe.current),k=ka(v);if(f==="source"){Nt();const Z=h.getView(),ue=mn(p.fm,p.body);let Ce=p.fm.length,_e=0,He=!1;if(Z){const{head:Ge,$head:ct}=Z.state.selection;He=Z.hasFocus();try{_e=Z.coordsAtPos(Ge).top-k}catch{}const mt=ct.parent.isTextblock?ct.parent.textBetween(Math.max(0,ct.parentOffset-16),ct.parentOffset,void 0,""):"",rt=j.current?.serializePrefix(Ge);Ce=Rp(ue,p.fm.length+(rt?.trimEnd().length??0),mt)}ae.current={to:f,offset:Ce,y:_e,focused:He,bodyAtEnter:p.body,struct:re()};return}const b=Pe.current;if(!b)return;const T=b.selectionStart??0;let y=0;try{y=fi(b,T)-k}catch{}ae.current={...ae.current??{},to:f,offset:T,bodyOff:T-Er(b.value).fmText.length,y,focused:document.activeElement===b}})},[q,g]);const Te=x.useRef(me);x.useLayoutEffect(()=>{const f=Te.current;if(Te.current=me,f===me)return;const v=ae.current,k=wa(qe.current);if(me==="source"){nn();const _e=Pe.current;if(!_e||v?.to!=="source")return;const He=k.scrollTop;_e.style.height="auto",_e.style.height=`${_e.scrollHeight}px`,k.scrollTop=He;const Ge=Math.min(v.offset,_e.value.length);_e.setSelectionRange(Ge,Ge),v.focused&&_e.focus({preventScroll:!0}),k.scrollTop+=fi(_e,Ge)-ka(k)-v.y;return}ae.current=null,O(null);const b=j.current,T=h.getView();if(!b||!T||!v||v.struct!==re()){p.ownedCards.clear(),Ae(_e=>_e+1);return}if(p.body!==v.bodyAtEnter&&b.applyBody(p.body,!1,!0),v.to!=="wysiwyg"||v.bodyOff==null)return;const y=h.getView();if(!y)return;const Z=y.state.doc.content.size,ue=v.bodyOff<=0?0:b.posAfterPrefix(p.body.slice(0,v.bodyOff))??0,Ce=Le.near(y.state.doc.resolve(Math.max(0,Math.min(ue,Z))),-1);y.dispatch(y.state.tr.setSelection(Ce).setMeta("addToHistory",!1)),v.focused&&y.focus();try{k.scrollTop+=y.coordsAtPos(Ce.head).top-ka(k)-v.y}catch{}},[me]);const Pe=x.useRef(null);return x.useEffect(()=>{const f=Pe.current;if(me==="source"&&f){const v=wa(f),k=v.scrollTop;f.style.height="auto",f.style.height=`${f.scrollHeight}px`,v.scrollTop=k}},[me,R,xe]),x.useEffect(()=>{if(g)return;if(me==="source"){const v=Pe.current;return v?Bi(tg(v)):void 0}const f=he.current;return f?Bi(qv(f,()=>h.getView())):void 0},[g,me,h]),u.jsxs(u.Fragment,{children:[u.jsx("span",{ref:qe,className:"amx-seg-anchor","aria-hidden":!0}),me==="source"?null:u.jsx(Ag,{anchor:et,on:Ye,toggle:()=>Jt.current(),leafId:F}),Yn||m?null:u.jsx(Vg,{page:e,cover:B,coverY:se,readOnly:g,onSetCover:f=>ve({cover:f??void 0,...f?{}:{cover_y:void 0}}),onSetCoverY:f=>ve({cover_y:f})}),Yn?null:u.jsxs("div",{ref:Rt,className:"amx-doc unified-page","data-unified-path":e,onFocusCapture:ee,onPointerDownCapture:ee,children:[u.jsx(Qv,{compact:m,path:e,icon:K,cover:B,readOnly:g,onSetIcon:f=>ve({icon:f??void 0}),onSetCover:f=>ve({cover:f}),onRename:d,onDetachedRename:f=>{const v=f.trim();v&&v!==(e.split("/").pop()??e).replace(/\.md$/i,"")&&d(v,null,!0)},onEnterBody:f=>Go(f==="enter"?"body-enter":"start"),focusSignal:yt}),!m&&u.jsx(gu.Provider,{value:Me,children:u.jsx(jg,{fmExtra:Cs(p.fm),readOnly:g,notePath:e,onCommit:f=>{p.fm=pg(p.fm,f),J(v=>v+1),pe(),p.pending=!0,Zt()}})}),g&&l&&u.jsxs("div",{className:"mk-notice unified-savebar","data-lock":"on",role:"status",children:[u.jsx(kp,{size:15}),u.jsx("div",{className:"mk-notice-body",children:u.jsx("span",{children:Ne("unipage.lock.bar")})}),u.jsx("button",{type:"button",className:"btn sm",onClick:l,children:Ne("unipage.lock.unlock")})]}),!g&&qn&&u.jsxs("div",{className:"mk-notice is-error unified-savebar","data-save":"failed",role:"alert",children:[u.jsx(Sp,{size:15}),u.jsx("div",{className:"mk-notice-body",children:u.jsx("span",{children:Ne("unisave.failed.bar")})}),u.jsx("button",{type:"button",className:"btn sm",onClick:()=>{p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),Zt()},children:Ne("unisave.failed.retry")})]}),!g&&nt&&u.jsxs("div",{className:"mk-notice unified-savebar","data-save":"draft",role:"status",children:[u.jsx(Cp,{size:15}),u.jsxs("div",{className:"mk-notice-body",children:[u.jsx("span",{children:Ne("unisave.draft.bar",{time:Ep(nt.at)})}),u.jsx("small",{children:Ne("unisave.draft.hint")})]}),u.jsx("button",{type:"button",className:"btn sm primary",onClick:gt,children:Ne("unisave.draft.restore")}),u.jsx("button",{type:"button",className:"btn sm",onClick:Tt,children:Ne("unisave.draft.discard")})]})]}),me==="source"?u.jsx("textarea",{ref:Pe,className:"amx-source",value:R??xe,spellCheck:be,onFocus:ee,onChange:f=>{const v=f.target.value;O(v);const{fmText:k,body:b}=Er(v);p.fm=xg(k),p.body=b,nn()}}):null,u.jsxs("div",{ref:he,className:`page-view unified-body${Ye?" amx-canvas":""}${Yn?" amx-canvas-full":""}`,"data-guide-anchor":Ye||g?void 0:"note-body",style:me==="source"?{display:"none"}:void 0,"aria-hidden":me==="source"||void 0,"data-bare":!0,onFocusCapture:()=>{ee(),Ie.current=!0,va(vn)},onPointerDownCapture:ee,children:[u.jsx(sv,{path:e,vaultRoot:E,active:Ye&&me!=="source",readOnly:g,revealSelection:Ot,getView:()=>h.getView(),main:Vt,mainStored:pt?.main!=null,elements:pt?.elements,tree:pt?.tree,onElements:rn,onTree:Wn,onMain:Zn,timeline:pr,histStepRef:jn,exportRef:jr,saveFile:f=>ad(e,f),parseMd:f=>ne.current?.parseMd(f)??null,serializeMd:f=>ne.current?.serializeMd(f)??null,storedMd:f=>ne.current?.serializeStored(f)??null,onBlocksDeleted:I,notePages:()=>L.getState().pages,onCommit:f=>{f&&p.ownedCards.add(f),Nt(),nn()},children:u.jsx(gf,{children:u.jsx(Jv,{path:e,pageDir:z,body:p.body,onChange:f=>{W.current||(p.body=f,eo(),nn())},onFinalFlush:f=>{p.body=f,eo(),nn(),J(v=>v+1)},skipFinalFlush:()=>p.reconcileBusy>0||W.current,hidden:()=>W.current,apiRef:j,probe:o,extraPlugins:Ve,focusPlace:Un!=null&&typeof Un=="object"?"start":Un,onFocused:()=>{Un!=null&&typeof Un=="object"&&Po(Un),Go(null)},onCard:hr,readOnly:g,onAskTangu:st?f=>Xt(f,f.state.selection.from,f.state.selection.to):void 0,aiMenu:Dt?{items:ln,translate:!0,more:io,onPick:(f,v)=>Zo(v,f)}:void 0,onAiPrompt:Dt?f=>Zo(f,"prompt"):void 0})},`${e}:${ye}${g?":ro":""}`)}),!Ye&&!g&&u.jsx("div",{className:"page-tail",onClick:()=>ne.current?.focusTail()}),Ke&&u.jsx(bv,{}),!g&&G.count>0&&u.jsx(vv,{count:G.count,index:G.index,onReview:Qo,onRevert:ko,onKeep:()=>{const f=h.getView();f&&xv(f)}})]}),u.jsx(_v,{getView:()=>h.getView(),onOpenNote:(f,v)=>{L.getState().openWikiLink(xf(f,e,L.getState().pages),e,v)}}),$e&&u.jsx(ir,{children:u.jsx("div",{className:"amx-lightbox",onClick:()=>Re(null),role:"presentation",children:u.jsx("img",{src:$e,alt:""})})}),Ue&&Dt&&u.jsx(ir,{children:u.jsx(Ym,{x:Ue.x,y:Ue.y,anchorTop:Ue.top,title:Ue.title,hasSelection:Ue.hasSelection,askFirst:Ue.askFirst,run:_n(Ue),onApply:Ro,onClose:mr,editorEl:he.current,language:Ue.language?{value:Ue.language,onChange:f=>Ln({...Ue,key:Date.now(),language:f})}:void 0},Ue.key)}),jo&&!g&&u.jsx(ku,{pages:L.getState().pages,exclude:e,onClose:()=>{Xn(null),h.getView()?.focus()},onPick:f=>{const v=jo;Xn(null);const k=h.getView();if(k){if(k.state.doc!==v.doc){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.menu.stale")}}));return}ax({view:k,from:v.from,to:v.to,source:e,target:f,pages:[...L.getState().pages].sort(),serialize:b=>ne.current?.serializeMd(b)??null}).then(b=>{b&&(Nt(),nn())}),k.focus()}}}),zn&&!g&&u.jsxs(ir,{children:[u.jsxs(lr,{className:"ctx-menu unified-block-menu",role:"menu","aria-label":Ne("unipage.menu.aria"),x:zn.x,y:zn.y,onClick:f=>f.stopPropagation(),onMouseOver:f=>{Fn&&!f.target.closest("[data-sub]")&&wo()},children:[st&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"ask",onClick:()=>{En(null);const f=h.getView();if(!f||!Be(f))return;const v=h.topRangeOf(f),k=f.state.selection;v?Xt(f,v.from,v.to):k instanceof Se&&Xt(f,k.from,k.to)},children:[u.jsx(th,{size:13})," ",Ne("unipage.menu.askTangu")]}),u.jsx("div",{className:"ubm-sep",role:"separator"})]}),(()=>{const f=Qn();if(!f.length)return null;const v=Hn(),k=f.find(T=>T.k===v)??(v==="card"?{icon:Ja,label:Ne("unipage.menu.card")}:void 0),b=k?.icon??Fi;return u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-sub":"turnInto","aria-haspopup":"menu","aria-expanded":!!Fn,className:Fn?"is-open":void 0,onMouseEnter:T=>co(T.currentTarget,!1),onClick:T=>co(T.currentTarget,!0),children:[u.jsx(b,{size:13})," ",Ne("unipage.menu.turnInto"),u.jsxs("span",{className:"ubm-sub-tail",children:[k?.label,u.jsx(eu,{size:13})]})]})})(),pc(h.getView())&&u.jsx(Vv,{view:h.getView(),cell:zn.cell??null,onDone:()=>En(null)}),u.jsx("div",{className:"ubm-sep",role:"separator"}),h.getView()&&h.topRangeOf(h.getView())?u.jsxs("button",{role:"menuitem",tabIndex:-1,"aria-disabled":"true",title:Ne("unipage.menu.toNewColumnMulti"),"data-act":"toNewColumn",onClick:()=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:je("unipage.menu.toNewColumnMulti")}}))},children:[u.jsx(pi,{size:13})," ",Ne("unipage.menu.toNewColumn")]}):h.getView()&&yf(h.getView().state.selection)&&u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"toNewColumn",onClick:()=>We((f,v)=>{Mu(f,v.from,v.to,v.node)}),children:[u.jsx(pi,{size:13})," ",Ne("unipage.menu.toNewColumn")]}),h.getView()&&si(h.getView().state.selection)!=null&&u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"unsplit",onClick:()=>{En(null);const f=h.getView();if(!f||!Be(f))return;const v=si(f.state.selection);v!=null&&Ox(f,v),f.focus()},children:[u.jsx(Hh,{size:13})," ",Ne("unipage.menu.unsplit")]}),h.getView()?.state.selection instanceof Se&&h.getView().state.selection.node.type.name==="amadeusCanvasCard"&&u.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>We((f,v)=>{v.node.type.name==="amadeusCanvasCard"&&(Gu(f,String(v.node.attrs.anchor)),Nt(),nn())}),children:[u.jsx(Qm,{size:13})," ",Ne("unipage.menu.backToDoc")]}),u.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>{En(null);const f=h.getView();!f||!Be(f)||(h.duplicate(f)&&(Nt(),nn()),f.focus())},children:[u.jsx(Mp,{size:13})," ",Ne("unipage.menu.duplicate")]}),(()=>{const f=h.getView();if(!f)return null;const v=f.state.selection,k=Xe(f),b=v instanceof Se?ox(v.node,e,L.getState().pages):null,T=!!k&&sx(f.state.doc.slice(k.from,k.to).content);return u.jsxs(u.Fragment,{children:[b&&u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"copyLink",onClick:()=>{En(null),rx(b.link),h.getView()?.focus()},children:[u.jsx(Jl,{size:13})," ",Ne(b.kind==="heading"?"blocklinks.copyHeading":"blocklinks.copyBlock")]}),T&&u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"moveTo",onClick:()=>{En(null);const y=h.getView();if(!y||!Be(y))return;const Z=Xe(y);Z&&Xn({doc:y.state.doc,...Z})},children:[u.jsx(xh,{size:13})," ",Ne("blocklinks.moveTo")]})]})})(),u.jsxs("button",{role:"menuitem",tabIndex:-1,className:"danger",onClick:()=>Qe((f,v)=>{const k=f.state.doc.slice(v.from,v.to).content;f.dispatch(f.state.tr.delete(v.from,v.to).scrollIntoView()),I(k)},(f,v)=>{const k=To.from(v.node),b=v.$from.parent,T=b.type.name==="amadeusColumnCell"&&b.childCount===1?zu(f.state,v.$from.before(),-1,!0):null;f.dispatch(T??f.state.tr.deleteSelection().scrollIntoView()),I(k)}),children:[u.jsx(Za,{size:13})," ",Ne("unipage.menu.delete")]})]}),Fn&&(()=>{const f=Hn();return u.jsx(lr,{className:"ctx-menu unified-block-submenu",role:"menu","aria-label":Ne("unipage.menu.turnInto"),x:Fn.x,y:Fn.y,anchorTop:Fn.anchorTop,onClick:v=>v.stopPropagation(),onMouseEnter:()=>clearTimeout(Mt.current),children:Qn().map(({k:v,icon:k,label:b,run:T})=>u.jsxs("button",{role:"menuitemradio","aria-checked":v===f,tabIndex:-1,"data-kind":v,onClick:T,children:[u.jsx(k,{size:13})," ",b,v===f&&u.jsx(zs,{size:13,className:"ubm-check"})]},v))})})()]})]})}const Nw=Object.freeze(Object.defineProperty({__proto__:null,UnifiedPage:ew},Symbol.toStringTag,{value:"Module"}));export{jg as A,hh as C,Cw as D,zw as F,Yg as I,$h as M,Vg as N,Wh as S,ew as U,eg as a,Jh as b,Vh as c,Sw as d,Aw as e,Gh as f,ky as g,xh as h,iu as i,Er as j,Nh as k,yu as l,Mg as m,Zh as n,Mw as o,Bg as p,Nw as q,Wg as r,Ew as s,Hg as u};