@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
@@ -1,712 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PdfAnnotator-DafvjP3U.js","./index-fDB1l4d-.js","./pdf-C2_sJa3b.js","./pdf.worker.min-CGb3BKV9.js","./pageStore-CyvNZEYX.js","./react-b7FrqRQR.js","./client-fKy9CWk0.js","./pageStore-ys8L4rjF.css","./PdfAnnotator-C_kglLCA.css"])))=>i.map(i=>d[i]);
2
- import{a as En,j as u,u as Ht,r as x,X as sd,bK as Gs,b3 as fc,Y as Il,bL as ad,b6 as cd,bM as sa,bN as id,bO as Wc,t as Te,bP as ld,bQ as ud,l as Pl,bR as dd,q as pc,br as mc,bS as _r,bT as fd,bn as pd,ad as md,a6 as hd,v as Br,bU as Ol,m as gd,bV as xd,f as gs,bW as yd,bX as Fl,bs as bd,aN as ga,i as vd,e as Yc,V as wd,_ as kd,bY as Sd,H as Cd,bZ as Ed,b_ as Md,bt as zd,aK as Uc,E as _l,b$ as Xc,c0 as Js,c1 as Gc,c2 as Ad,c3 as Jc,a9 as Nd,c4 as br,ab as Zc,ac as Td,be as $d,bf as jd,a7 as Rd,c5 as Ld,c6 as Dd}from"./index-fDB1l4d-.js";import{E as Qc,f as Id,i as Pd,F as Od,j as aa,k as Fd,h as Bl,p as Cs,l as hs,t as _d,m as Bd,n as Hd,o as Kd,q as hc,r as Hl,v as Vd,w as qa,x as qd,y as Wd,z as Yd,A as Ud,B as Xd,C as Gd,D as xa,G as ya,H as Jd,I as Zs,J as Wa,K as Zd,L as Qs,M as Qd,N as Ya,O as Kl,Q as ei,S as ef,T as tf,U as nf,V as of,W as rf,X as sf,Y as af,u as Vl,Z as cf,_ as lf,$ as uf,a0 as df,a1 as ti,a2 as ff,a3 as Rs,a4 as pf,a5 as mf,a6 as hf,a7 as ql,a8 as is,a9 as gf,aa as xf,ab as yf,ac as bf,ad as vf,ae as wf,af as kf,ag as Sf,ah as ba,g as Cf,ai as Ef,aj as Mf}from"./MarkdownBlock-DSItkLhu.js";import{ev as zf,mA as Af,aG as Vr,mB as Wt,mC as ni,mD as Bo,mE as je,mF as Vo,kI as Nf,mG as Tf,mH as $f,cM as Wl,S as jf,lv as ea,mI as Rf,mJ as Lf,mK as Df,mL as Ln,mM as Ce,mN as zo,Y as oi,gC as zr,mO as Yl,c1 as Ur,mP as ri,mQ as If,fw as Pf,mR as dr,mS as Of,mT as Ff,mU as ao,mV as _f,mW as Bf,mX as Hf,mY as Kf,mZ as si,m_ as Vf,eV as qf,eU as Wf,m$ as Yf,ez as ai,fx as Uf,n0 as Xf,i1 as Gf,n1 as Ul,n2 as Jf,n3 as Zf,n4 as Ua,f9 as Xa,db as Qf,n5 as Ga,aJ as ep,n6 as tp,n7 as ir,iK as np,hx as op,iJ as rp,n8 as sp,n9 as ap,i7 as cp,aW as Ja,e7 as ip,eE as lp,lM as up,na as dp,nb as fp,nc as pp,lL as ci,nd as mp,ne as va,nf as ii,ng as wa,dn as hp,b0 as gp,bY as xp,bD as yp,ey as li,bb as bp,nh as ui,ni as Dr,nj as Sn,nk as vp,nl as wp,nm as di,nn as kp,kf as Sp,no as Cp,aO as Ep,np as Mp,hq as zp}from"./appStore-DDOkzWDA.js";import{p as tn,a8 as Ap,aA as Xl,R as zn,cJ as Np,cK as Tp,cL as $p,F as jp,T as gc,br as fi,u as mn,b4 as Es,cM as pi,a6 as Rp,ah as ca,cN as Lp,aj as Ms,aE as rn,X as lr,I as Gl,q as Jl,B as Dp,aR as Ip,cl as Pp,cO as Op,bu as mi,cP as Fp,cQ as Jr,c9 as hi,c8 as _p,cR as gi,cS as Ls,bv as Bp,P as Hp,cT as xi,cU as yi,bb as bi,cV as Kp,bm as Vp,cW as qp,cX as Wp,cY as Yp,cZ as vi,c_ as Up,c$ as Xp,d0 as wi,d1 as Gp,d2 as Jp,b3 as Zp,cj as Qp,d3 as em,bt as tm,d4 as nm,d5 as om,d6 as rm,d7 as or,ci as sm,d8 as ki,d9 as am,as as Zl,da as cm,db as im,dc as Eo,dd as lm,av as um,de as dm,df as Si,dg as Zr,dh as Ds,co as fm,cp as pm,c7 as mm,aV as ka,di as hm,dj as gm,dk as Ci,dl as Ei,cf as xm,dm as ym}from"./pageStore-CyvNZEYX.js";import{c as bm}from"./client-fKy9CWk0.js";import{$ as zt,a as Ql,b as xc}from"./index-CmsN2Zm2.js";import{F as eu,H as vm,T as wm}from"./type-Dt7RNB9g.js";import{U as Mi}from"./upload-Dy7svciS.js";import{h as Xr,l as km,f as Gr,a as zi,i as yc,b as Ys,c as Sm,d as vr,t as Is,e as Ps,g as Sa,s as Cm,j as Em,k as Mm}from"./listFold-BeNv2v6M.js";import{e as zm,a as Am,b as Nm,c as Ai,v as Ni,i as Tm}from"./linkFollow-uke1Xtit.js";import{A as Ti}from"./arrow-up-right-BptN64d-.js";import{c as tu}from"./react-b7FrqRQR.js";import{r as Qr,a as $m,C as jm}from"./Chrome-C7F6fdDp.js";import{e as Rm,h as Lm,a as $i,o as Dm,d as Im,i as Pm,g as Om,j as Fm,k as _m,f as Bm,c as Hm}from"./canvasPrefs-ArsX3NFO.js";import{t as ji,I as Km}from"./InlineAiPanel-CdIPINsA.js";import{l as Vm,b as qm,r as Ri}from"./selectionActions-DIq0xDm8.js";import{createFoldMemory as Wm,remapFoldMemory as Ym}from"./foldActions-DGIPTmE1.js";import{c as Um}from"./FloatingToc-DO7SH8Ku.js";import{U as Xm}from"./undo-2-QimgpLBn.js";import{C as Gm}from"./code-xml-DCCD9eCS.js";import{M as Jm}from"./message-square-plus-BvUfAAZm.js";const Zm=[["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"}]],Qm=tn("align-center-vertical",Zm);const eh=[["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"}]],th=tn("between-horizontal-end",eh);const nh=[["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"}]],oh=tn("between-horizontal-start",nh);const rh=[["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"}]],sh=tn("between-vertical-end",rh);const ah=[["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"}]],ch=tn("between-vertical-start",ah);const ih=[["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"}]],lh=tn("case-sensitive",ih);const uh=[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]],dh=tn("chevrons-down",uh);const fh=[["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"}]],ph=tn("file-input",fh);const mh=[["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"}]],hh=tn("heading-1",mh);const gh=[["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"}]],xh=tn("heading-2",gh);const yh=[["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"}]],bh=tn("heading-3",yh);const vh=[["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"}]],wh=tn("list-collapse",vh);const kh=[["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"}]],Sh=tn("list-ordered",kh);const Ch=[["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"}]],Eh=tn("move-horizontal",Ch);const Mh=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],zh=tn("move-right",Mh);const Ah=[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Nh=tn("move-left",Ah);const Th=[["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"}]],Li=tn("pilcrow",Th);const $h=[["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"}]],jh=tn("regex",$h);const Rh=[["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"}]],Lh=tn("replace-all",Rh);const Dh=[["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"}]],Ih=tn("replace",Dh);const Ph=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],Oh=tn("rows-2",Ph);const Fh=[["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"}]],_h=tn("scroll-text",Fh);const Bh=[["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"}]],Hh=tn("smile",Bh);const Kh=[["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"}]],Vh=tn("spline",Kh);function qh(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 Wh(e,t,n){if(!e.trim())return t;const o=[];for(const r of t){const s=qh(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)}En({"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 Za="amadeus_delete_assets";function gw(){try{const e=localStorage.getItem(Za);return e==="yes"?!0:e==="no"?!1:null}catch{return null}}function Yh(e){try{e===null?localStorage.removeItem(Za):localStorage.setItem(Za,e?"yes":"no")}catch{}}const xs=tu(e=>({req:null,open:t=>e({req:t}),clear:()=>e({req:null})}));function Uh(e,t,n){return new Promise(o=>{xs.getState().req?.resolve(null),xs.getState().open({note:e,assets:t,block:n?.block,resolve:o})})}function xw(){const e=xs(t=>t.req);return e?u.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},children:u.jsx(Xh,{req:e},e.note)}):null}function Xh({req:e}){const{t}=Ht(),[n,o]=x.useState(!1),r=c=>{xs.getState().req===e&&(n&&c!==null&&Yh(c==="with"),xs.getState().clear(),e.resolve(c))};zf(()=>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")})]})]})})}En({"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 Qa="forsion.amadeus.aiSpaceTrigger";let ls=null;function Gh(){if(ls===null)try{ls=localStorage.getItem(Qa)==="1"}catch{ls=!1}return ls}function yw(e){ls=e;try{e?localStorage.setItem(Qa,"1"):localStorage.removeItem(Qa)}catch{}}En({"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 nu=typeof CSS<"u"&&"highlights"in CSS;let qt=[],ys=[];const Mt=tu(()=>({open:!1,query:"",active:0,total:0,root:null,caseSensitive:!1,regex:!1,bad:!1,replaceOpen:!1,replacement:"",replaceable:0,providerVer:0})),bs=new Set,Di=()=>Mt.setState(e=>({providerVer:e.providerVer+1}));function Ii(e){return bs.add(e),Di(),()=>{bs.delete(e),Di()}}function bc(e){const t=e.startContainer;for(const n of bs)if(n.el.isConnected&&(n.owns?n.owns(t):n.el.contains(t)))return n;return null}function Pi(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 ou(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 Jh(e){let t=null;const n=["fontFamily","fontSize","fontWeight","fontStyle","lineHeight","letterSpacing","wordSpacing","textIndent","textTransform","textAlign","tabSize","whiteSpace","overflowWrap","wordBreak","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing","direction"],o=()=>{if(!t)return;const r=getComputedStyle(e);for(const s of n)t.style[s]=r[s];Object.assign(t.style,{position:"absolute",left:`${e.offsetLeft}px`,top:`${e.offsetTop}px`,width:`${e.offsetWidth}px`,height:`${e.offsetHeight}px`,margin:"0",borderStyle:"solid",borderColor:"transparent",overflow:"hidden",color:"transparent",background:"transparent",pointerEvents:"none",whiteSpace:"pre-wrap"}),t.firstChild?.nodeValue!==e.value&&(t.textContent=e.value),t.scrollTop=e.scrollTop};return{el:e,owns:r=>!!t&&t.contains(r),attach:()=>{t=document.createElement("div"),t.className="amx-find-mirror",t.setAttribute("aria-hidden","true"),e.parentElement?.insertBefore(t,e.nextSibling),o();const r=new ResizeObserver(o);return r.observe(e),e.addEventListener("input",o),e.addEventListener("scroll",o),()=>{r.disconnect(),e.removeEventListener("input",o),e.removeEventListener("scroll",o),t?.remove(),t=null}},replace:r=>{const s=e.value,c=r.map(({range:R,text:k})=>({from:R.startOffset,to:R.endOffset,text:k,was:R.toString()})).filter(R=>s.slice(R.from,R.to)===R.was).sort((R,k)=>R.from-k.from);if(!c.length)return 0;const i=c[0].from,a=c[c.length-1].to;let l="",m=i;for(const R of c)l+=s.slice(m,R.from)+R.text,m=R.to;l+=s.slice(m,a);const h=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}))),h?.focus(),o(),c.length},focusAt:r=>t?.contains(r.startContainer)?(e.focus({preventScroll:!0}),e.setSelectionRange(r.startOffset,r.endOffset),!0):!1}}function Zh(){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 Qh(){const e=document.activeElement;let t="";if(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement&&/^(text|search)$/.test(e.type)){if(e.closest(".amx-findbar"))return null;t=e.value.slice(e.selectionStart??0,e.selectionEnd??0)}else t=window.getSelection()?.toString()??"";return t.trim()&&!/[\r\n]/.test(t)&&t.length<=200?t:null}let vs=null;function eg(){const e=document.activeElement;if(!(e instanceof HTMLElement)||e===document.body||e.closest(".amx-findbar")){vs=null;return}const t=window.getSelection(),n=t&&t.rangeCount?t.getRangeAt(0):null;vs={el:e,range:e.isContentEditable&&n&&e.contains(n.startContainer)?n.cloneRange():null}}function tg(e){const t=e.startContainer.parentElement;if(!t?.isContentEditable)return null;let n=t;for(;n.parentElement?.isContentEditable;)n=n.parentElement;return n}function ng(e){const t=vs;vs=null;const n=document.activeElement;if(!(n&&n!==document.body&&!n.closest(".amx-findbar"))){if(e){if(bc(e)?.focusAt?.(e))return;const r=tg(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 bw(e={}){if(!nu)return;const t=Qh();if(Mt.getState().open){Mt.setState({...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}});const n=document.querySelector(".amx-findbar input");n?.focus(),n?.select();return}eg(),Mt.setState({open:!0,root:Zh(),...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}})}function Ca(e){const t=e==="keyboard"?qt[Mt.getState().active]??null:null;qt=[],ys=[],us(-1),Mt.setState({open:!1,query:"",active:0,total:0,root:null,bad:!1,replaceable:0}),e?ng(t):vs=null}const og=/^(inline|contents|ruby)/;function rg(e,t){let n=e.parentElement;for(;n;){let o=t.get(n);if(o===void 0&&(o=og.test(getComputedStyle(n).display),t.set(n,o)),!o)return n;n=n.parentElement}return null}function sg(e,t){if(ys=[],!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 h=m.tagName;return h==="SCRIPT"||h==="STYLE"||h==="NOSCRIPT"||h==="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,h=rg(m,n);s.length&&h!==c&&(r+=`
3
- `),c=h,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,h=m+l[0].length;for(;a>0&&s[a].at>m;)a--;for(;a+1<s.length&&s[a+1].at<=m;)a++;let E=a;for(;E+1<s.length&&s[E+1].at<h;)E++;const R=document.createRange();R.setStart(s[a].node,m-s[a].at),R.setEnd(s[E].node,Math.min(h-s[E].at,s[E].node.length)),i.push(R),ys.push(l)}return i}function Ea(e){const t=Mt.getState(),n=ou(t.query,t);return qt=sg(e,n==="bad"?null:n),Mt.setState({bad:n==="bad",replaceable:qt.filter(o=>bc(o)).length}),qt.length}function us(e){if(!nu)return;const t=CSS.highlights;if(!qt.length){t.delete("amx-find"),t.delete("amx-find-active");return}t.set("amx-find",new Highlight(...qt));const n=qt[e],o=n?new Highlight(n):new Highlight;o.priority=1,t.set("amx-find-active",o)}function ag(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 Ma(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=ag(n);if(!r)return;const s=r.getBoundingClientRect(),c=r.currentCSSZoom||1;(t.bottom>s.bottom||t.top<s.top)&&(Um(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 vw(){return Mt(t=>t.open)?u.jsx(cg,{}):null}function cg(){const{t:e}=Ht(),t=Mt(_=>_.query),n=Mt(_=>_.active),o=Mt(_=>_.total),r=Mt(_=>_.root),s=Mt(_=>_.caseSensitive),c=Mt(_=>_.regex),i=Mt(_=>_.bad),a=Mt(_=>_.replaceOpen),l=Mt(_=>_.replacement),m=Mt(_=>_.replaceable),h=Mt(_=>_.providerVer),[E,R]=x.useState({top:12,right:12}),k=x.useRef(null),v=!!r&&[...bs].some(_=>_.el.isConnected&&r.contains(_.el));x.useLayoutEffect(()=>{const _=()=>{const Z=r?.getBoundingClientRect();Z&&R({top:Z.top+8,right:Math.max(8,window.innerWidth-Z.right+8)})};return _(),window.addEventListener("resize",_),()=>window.removeEventListener("resize",_)},[r]),x.useLayoutEffect(()=>{if(!r)return;const _=[...bs].filter(Z=>Z.attach&&r.contains(Z.el)).map(Z=>Z.attach());return()=>_.forEach(Z=>Z())},[r,h]),x.useEffect(()=>{r&&(Ea(r),Mt.setState({total:qt.length,active:0}),us(0),qt.length&&Ma(qt[0]))},[r,t,s,c,h]),x.useEffect(()=>{if(!r)return;const _=()=>{r.isConnected||Ca()};window.addEventListener("focusin",_);const Z=window.setInterval(_,1e3);return()=>{window.removeEventListener("focusin",_),window.clearInterval(Z)}},[r]),x.useEffect(()=>{if(!r||!t.trim())return;let _=0;const Z=new MutationObserver(()=>{window.clearTimeout(_),_=window.setTimeout(()=>{Ea(r);const ze=Math.min(Mt.getState().active,Math.max(0,qt.length-1));Mt.setState({total:qt.length,active:ze}),us(ze)},150)});return Z.observe(r,{childList:!0,subtree:!0,characterData:!0}),()=>{window.clearTimeout(_),Z.disconnect()}},[r,t,s,c]);const j=_=>{if(!qt.length)return;const Z=(Mt.getState().active+_+qt.length)%qt.length;Mt.setState({active:Z}),us(Z),Ma(qt[Z])},P=_=>{if(!r||!qt.length)return;const Z=Mt.getState(),ze=_?qt.map((ce,se)=>se):[Z.active],Ke=new Map;for(const ce of ze){const se=bc(qt[ce]);if(!se)continue;const ae=Ke.get(se)??[];ae.push({range:qt[ce],text:Pi(Z.replacement,ys[ce],Z.regex)}),Ke.set(se,ae)}let p=0;for(const[ce,se]of Ke)p+=ce.replace(se);if(!p&&!_){j(1);return}const xe=Z.active,Qe=_?"":Pi(Z.replacement,ys[Z.active],Z.regex);Ea(r);let de=0;if(!_&&qt.length){const ce=ou(Z.query,Z),se=ce&&ce!=="bad"?(Qe.match(new RegExp(ce.source,ce.flags))??[]).length:0;de=(xe+se)%qt.length}Mt.setState({total:qt.length,active:de}),us(de),qt.length&&Ma(qt[de])},q=_=>_.key==="Escape"?(Ca("keyboard"),!0):(_.metaKey||_.ctrlKey)&&_.altKey&&_.code==="KeyF"?(_.preventDefault(),v&&Mt.setState({replaceOpen:!Mt.getState().replaceOpen}),!0):!1,X=_=>{Mt.setState({[_]:!Mt.getState()[_]}),k.current?.focus()};return u.jsxs("div",{className:`amx-findbar${a&&v?" amx-findbar--replace":""}`,style:{top:E.top,right:E.right},children:[v&&u.jsx("button",{className:"amx-findbar-expand",onClick:()=>Mt.setState({replaceOpen:!a}),title:e("find.toggleReplace"),"aria-label":e("find.toggleReplace"),"aria-expanded":a,children:a?u.jsx(Ap,{size:14}):u.jsx(Xl,{size:14})}),u.jsxs("div",{className:"amx-findbar-rows",children:[u.jsxs("div",{className:"amx-findbar-row",children:[u.jsx("input",{ref:k,autoFocus:!0,placeholder:e("find.placeholder"),value:t,"aria-invalid":i||void 0,title:i?e("find.badRegex"):void 0,onFocus:_=>_.currentTarget.select(),onChange:_=>Mt.setState({query:_.target.value}),onKeyDown:_=>{!q(_)&&_.key==="Enter"&&j(_.shiftKey?-1:1),_.stopPropagation()}}),u.jsx("button",{className:"amx-findbar-opt",onClick:()=>X("caseSensitive"),"aria-pressed":s,title:e("find.case"),"aria-label":e("find.case"),children:u.jsx(lh,{size:15})}),u.jsx("button",{className:"amx-findbar-opt",onClick:()=>X("regex"),"aria-pressed":c,title:e("find.regex"),"aria-label":e("find.regex"),children:u.jsx(jh,{size:14})}),u.jsx("span",{className:"amx-findbar-count",children:o?`${n+1}/${o}`:t.trim()?"0":""}),u.jsx("button",{onClick:()=>j(-1),title:e("find.prev"),"aria-label":e("find.prev"),children:"‹"}),u.jsx("button",{onClick:()=>j(1),title:e("find.next"),"aria-label":e("find.next"),children:"›"}),u.jsx("button",{onClick:()=>Ca("pointer"),title:e("find.close"),"aria-label":e("find.close"),children:"✕"})]}),a&&v&&u.jsxs("div",{className:"amx-findbar-row",children:[u.jsx("input",{className:"amx-findbar-replace",placeholder:e("find.replacePlaceholder"),value:l,onChange:_=>Mt.setState({replacement:_.target.value}),onKeyDown:_=>{!q(_)&&_.key==="Enter"&&P(_.metaKey||_.ctrlKey),_.stopPropagation()}}),u.jsx("button",{className:"amx-findbar-act",onClick:()=>P(!1),disabled:!m,title:e("find.replaceOne"),"aria-label":e("find.replaceOne"),children:u.jsx(Ih,{size:14})}),u.jsx("button",{className:"amx-findbar-act",onClick:()=>P(!0),disabled:!m,title:e("find.replaceAll"),"aria-label":e("find.replaceAll"),children:u.jsx(Lh,{size:14})})]})]})]})}function Sr(e){const t=sd(e);return t.length===e.length&&e.startsWith(Gs)?{fmText:Gs,body:e.slice(1)}:{fmText:e.slice(0,e.length-t.length),body:t}}function Cn(e,t){return e+t}function za(e,t){const n=ks(e);return n.trim()&&!ig(n)?e:Sr(ad(e,t)).fmText}function ig(e){try{const t=sa(e);return t==null||typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function lg(e,t){const n=ug(e,t);if(n!==null)return tc(e,n);const{bom:o}=ws(e),r=nc(e),s=t.replace(/\n+$/,"");if(!r.length&&!s.trim())return o;const c=o+["---",...r,...s.trim()?[s]:[],"---",""].join(`
5
- `);return ec(s)?tc(e,c):c}function ug(e,t){const n=ks(e),o=t.replace(/(?:\r?\n)+$/,"");if(!n||!o.trim())return null;if(o===n)return e;const r=e.indexOf(n),s=r+n.length;if(r<=0||e[r-1]!==`
6
- `||!/^\r?\n/.test(e.slice(s))||e.indexOf(n,r+1)>=0)return null;const c=e.slice(0,r)+o+e.slice(s);return ks(c)===o&&nc(c).join(`
7
- `)===nc(e).join(`
8
- `)?c:null}function ec(e){try{return sa(e),!0}catch{return!1}}function tc(e,t){if(t===e)return t;const n=ws(t).inner;if(n==null||ec(n))return t;const o=ws(e).inner;return o==null||!ec(o)?t:(console.warn("[amadeus] frontmatter rewrite would produce invalid YAML; keeping the original block"),e)}const dg=/^---\r?\n([\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)$/;function ws(e){const t=e.startsWith(Gs)?Gs:"",n=dg.exec(e.slice(t.length));return{bom:t,inner:n?n[1]??"":null}}function vc(e){const{inner:t}=ws(e);return t==null?null:t?id(t.replace(/\r?\n$/,"").split(/\r?\n/)):[]}function nc(e){return(vc(e)??[]).filter(t=>cd.test(t[0])).flat()}const fg=/^["']?amadeus_(schema|layout|canvas)["']?\s*:/;function ds(e,t,n){const{bom:o}=ws(e),r=vc(e)??[],s=r.filter(a=>!fg.test(a[0])).flat(),i=[...Af(t,n).flatMap(a=>{const l=mg.exec(a)?.[1],m=l?su(r,l):null;return m&&m.length>1&&au(m,l)===(l==="layout"?t:n)?m:[a]}),...s];return i.length?tc(e,o+["---",...i,"---",""].join(`
9
- `)):o}function pg(e){const t=mo(e),n=pn(e);return t==null&&n==null||/^["']?amadeus_schema["']?\s*:/m.test(e)?e:ds(e,t,n)}function mo(e){return ru(e,"layout")}function pn(e){return ru(e,"canvas")}const mg=/^amadeus_(layout|canvas):/;function ru(e,t){const n=vc(e),o=n&&su(n,t);return o?au(o,t):null}function su(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 au(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=sa(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 hg(e){return e?fc(Il(e)):{}}function ks(e){return e?Il(e):""}const gg=80;function xg(){return zt(()=>{if(!Vr())return new Wt({});const e=Math.round(gg*zn(document.body));return new Wt({props:{scrollThreshold:{top:0,left:0,right:0,bottom:e},scrollMargin:{top:5,left:5,right:5,bottom:e}}})})}function ta(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 Oi(e,t=0,n=e.content.size){return e.textBetween(t,n,`
11
- `,()=>"").replace(/!\[\[[^\]\n]*\]\]/g,"").replace(/\[\[(?:[^\]|\n]*\|)?([^\]\n]*)\]\]/g,"$1")}function yg(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=ni(Oi(t)));const{from:r,to:s,empty:c}=o.state.selection;return{all:n,sel:c?null:ni(Oi(o.state.doc,r,s))}}}function bg(){return[zt(()=>new Wt({view:()=>{let e=0;const t=()=>{e||(e=requestAnimationFrame(()=>{e=0,Wc()}))};return t(),{update:(n,o)=>{(n.state.doc!==o.doc||!n.state.selection.eq(o.selection))&&t()},destroy:()=>{e&&cancelAnimationFrame(e),Wc()}}}}))]}function vg(e){const t=(o,r,s)=>{const c=o.selection;return!(c instanceof je)||!c.empty||!s||Vo.atStart(o.doc).$from.start()!==c.$from.start()||!s.endOfTextblock("up")?!1:e()},n=o=>{const r=o.selection;if(!(r instanceof je)||!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[zt(()=>Bo({ArrowUp:t,ArrowLeft:n}))]}function Fi(e,t){const n=e.content.size;return e.textBetween(Math.max(0,t-12),Math.min(n,t+12),`
12
- `,"")}function wg(e){return[zt(()=>new Wt({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;Tp(c,i,{a:a.anchor,h:a.head,t:Fi(t.state.doc,a.head)})};queueMicrotask(()=>{if(!n||!e.restore())return;const{vaultRoot:c,path:i}=e.where(),a=Np(c,i),l=t.state.doc;let m=null;if(a&&a.a<=l.content.size&&a.h<=l.content.size&&Fi(l,a.h)===a.t){try{m=je.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(),$p())};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())}}}}))]}En({"canvasseg.aria":{zh:"编辑模式",en:"Editing mode"},"canvasseg.doc":{zh:"文档",en:"Document"},"canvasseg.canvas":{zh:"画布",en:"Canvas"}});const kg="amx-modeseg-slot";function cu(e,t){return{modes:[{value:"doc",label:Te("canvasseg.doc"),icon:jp},{value:"canvas",label:Te("canvasseg.canvas"),icon:eu,guideAnchor:"note-canvas"}],value:e?"canvas":"doc",onChange:n=>{n==="canvas"!==e&&t()},ariaLabel:Te("canvasseg.aria")}}function Sg({on:e,toggle:t,leafId:n}){return Ht(),n?u.jsx(fi,{className:"amx-modeseg",leafId:n}):u.jsx(fi,{className:"amx-modeseg",spec:cu(e,t)})}function Cg({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(`.${kg}`));i();const a=new MutationObserver(i);return a.observe(c,{childList:!0,subtree:!0}),()=>a.disconnect()},[e]),r?gc.createPortal(u.jsx(Sg,{on:t,toggle:n,leafId:o}),r):null}En({"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 Eg=["text","number","checkbox","date","list"];function Mg(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 zg=e=>/^(tags?|alias(es)?|cssclass(es)?)$/i.test(e.trim())?"list":"text",iu=e=>/\[\[[^\]\n]+\]\]/.test(e);function Aa(e){if(!e.trim())return{ok:!0,entries:[]};try{const t=sa(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 lu=e=>Array.isArray(e)&&e.every(t=>t===null||typeof t!="object");function Na(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 uu=x.createContext(null);function wc(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=v=>{l.current.draft=v,c(v)},h=v=>{l.current.base=v,a(v)},E=x.useContext(uu);x.useLayoutEffect(()=>{if(!E)return;const v=()=>{const j=l.current,P=Na(j.draft,j.base,j.current,j.norm);P!==null&&(h(P),j.commit(P))};return E.add(v),()=>{E.delete(v),v()}},[E]);const R=s!==null&&e!==i&&Na(s,i,e,o)!==null;return{shown:s??e,conflict:R,change:v=>{l.current.draft===null&&h(l.current.current),m(v)},settle:()=>{const v=l.current,j=Na(v.draft,v.base,v.current,v.norm);return m(null),j},onKeyDown:v=>{if(!(v.nativeEvent.isComposing||v.keyCode===229)){if(v.key==="Enter"&&r){v.preventDefault(),v.currentTarget.blur();return}v.key!=="Escape"||n==="never"||!R||(v.preventDefault(),v.stopPropagation(),m(null))}}}}function Ag({fmExtra:e,onCommit:t,readOnly:n=!1,notePath:o}={}){const{t:r}=Ht(),s=mn(ae=>ae.activePage),c=mn(ae=>ae.vaultRoot),i=mn(ae=>ae.manifest?.fmExtra??""),a=Es(),l=e!==void 0,m=l?e:i,h=x.useRef(m);h.current=m;const[E,R]=x.useState(()=>pi(c)??!1);x.useEffect(()=>{R(pi(c)??!1)},[c]);const k=ae=>{R(Re=>{const Me=typeof ae=="function"?ae(Re):ae;return Lp(c,Me),Me})},[v,j]=x.useState(!1),[P,q]=x.useState(null),X=x.useRef(null),_=o??s??void 0,Z=ae=>{if(Tf(ae))return;const Re=Pl(ae);Re&&a.getState().openWikiLink(Re,_)},ze=x.useMemo(()=>Aa(m),[m]),Ke=x.useMemo(()=>{const ae=!l&&s?Nf(s):void 0;return new Set(ae?.fmKeys??[])},[l,s]),p=x.useMemo(()=>ze.entries.map((ae,Re)=>({...ae,idx:Re})).filter(ae=>!Ke.has(ae.key)),[ze,Ke]);if(x.useEffect(()=>{if(!P)return;const Re=[...X.current?.querySelectorAll(".amx-prop-row[data-key]")??[]].find(Me=>Me.dataset.key===P)?.querySelector("input:not(.amx-prop-key), textarea, .amx-prop-links");Re&&(Re.focus(),Re.classList.contains("amx-prop-links")&&Re.click(),q(null))},[P,ze]),!l&&!s)return null;const xe=ae=>{t?t(ae):a.getState().setFmExtra(ae)},Qe=ae=>{ae!==null&&xe(ae)},de=(ae,Re)=>Qe(dd(h.current,{[ae]:Re})),ce=(ae,Re)=>{const Me=ae.trim();return Me?/^amadeus_/.test(Me)?(window.alert(r("amprops.reservedKey")),!1):Ke.has(Me)?(window.alert(r("amprops.pluginManaged")),!1):(Aa(h.current).entries.some(rt=>rt.key===Me)||de(Me,Mg(Re)),q(Me),!0):!1},se=ze.ok?p.length:null;return u.jsxs("div",{className:`amx-props${se===0&&!E?" is-empty":""}`,ref:X,children:[u.jsxs("div",{className:"amx-props-bar",children:[u.jsxs("button",{className:"amx-props-chip",onClick:()=>k(ae=>!ae),children:[se===null?r("amprops.chipRaw"):r("amprops.chipCount",{n:se}),E?" ▾":" ▸"]}),!n&&u.jsx("button",{className:"amx-props-add",title:r("amprops.add"),onClick:()=>{k(!0),ze.ok&&j(!0)},children:u.jsx(Rp,{size:12})})]}),E&&(ze.ok?u.jsxs("div",{className:"amx-props-rows",children:[p.length===0&&!v&&u.jsx("div",{className:"amx-props-empty",children:r("amprops.empty")}),p.map(ae=>n?u.jsxs("div",{className:"amx-prop-row amx-prop-row-ro",children:[u.jsx("span",{className:"amx-prop-key",children:ae.key}),u.jsx($g,{value:ae.value})]},`${s}:${ae.idx}:${ae.key}`):u.jsxs("div",{className:"amx-prop-row","data-key":ae.key,children:[u.jsx(Tg,{name:ae.key,onRename:Re=>{const Me=/^(amadeus_page|amadeus_schema|amadeus_layout|amadeus_canvas|amadeus_next_id)$/.test(Re)||Ke.has(Re)||Aa(h.current).entries.some(rt=>rt.key!==ae.key&&rt.key===Re);!Re||Me||Qe(ld(h.current,ae.key,Re))}}),u.jsx(Lg,{value:ae.value,onCommit:Re=>de(ae.key,Re),onOpenLink:Z}),u.jsx("button",{className:"amx-prop-del",title:r("amprops.delete"),onClick:()=>de(ae.key,void 0),children:u.jsx(ca,{size:12})})]},`${s}:${ae.key}`)),v&&!n&&u.jsx(jg,{onAdd:(ae,Re)=>{ce(ae,Re)&&j(!1)},onCancel:()=>j(!1)})]}):u.jsxs(u.Fragment,{children:[Ke.size>0&&u.jsx("div",{className:"amx-props-empty",children:r("amprops.pluginKeysWarn",{keys:[...Ke].join(", ")})}),u.jsx(Ng,{text:m,readOnly:n,onCommit:xe})]}))]})}function Ng({text:e,readOnly:t,onCommit:n}){const{t:o}=Ht(),r=c=>{t||n(c)},s=wc(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 Tg({name:e,onRename:t}){const n=wc(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 $g({value:e}){return typeof e=="boolean"?u.jsx("span",{className:"amx-prop-check","aria-hidden":!0,children:e?"☑":"☐"}):lu(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 jg({onAdd:e,onCancel:t}){const{t:n}=Ht(),[o,r]=x.useState(""),[s,c]=x.useState("text"),[i,a]=x.useState(!1),l=i?s:zg(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:Eg.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(Ms,{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(ca,{size:12})})]})}function du({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 Rg({value:e,onCommit:t,onOpenLink:n}){const{t:o}=Ht(),[r,s]=x.useState(!1);return r?u.jsx(oc,{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(du,{text:e,onOpenLink:n})})}function Lg({value:e,onCommit:t,onOpenLink:n}){const{t:o}=Ht();return typeof e=="boolean"?u.jsx("input",{type:"checkbox",className:"amx-prop-check",checked:e,onChange:r=>t(r.target.checked)}):lu(e)?u.jsx(Ig,{items:e.map(r=>String(r??"")),onCommit:t,onOpenLink:n}):typeof e=="number"?u.jsx(oc,{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(Dg,{value:e,onCommit:t}):typeof e=="string"&&!e.includes(`
13
- `)&&iu(e)?u.jsx(Rg,{value:e,onCommit:t,onOpenLink:n}):typeof e=="string"||e==null?u.jsx(oc,{current:e??"",multiline:typeof e=="string"&&e.includes(`
14
- `),onCommit:t}):u.jsx("span",{className:"amx-prop-nested",title:o("amprops.nestedHint"),children:ud(e).trimEnd()})}function oc({current:e,norm:t,multiline:n=!1,autoFocus:o,onCommit:r,onDone:s}){const{t:c}=Ht(),i=wc(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 Dg({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 Ig({items:e,onCommit:t,onOpenLink:n}){const{t:o}=Ht(),[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&&iu(a)?u.jsx(du,{text:a,onOpenLink:n}):a,u.jsx("button",{className:"amx-chip-x",onClick:()=>t(e.filter((m,h)=>h!==l)),children:u.jsx(ca,{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})]})}En({"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 Pg=/^(未命名|untitled)(-\d+)?$/i;function Og(){const e=mn(t=>t.manifest?.fmExtra??"");return x.useMemo(()=>{const t=fc(e).cover;return typeof t=="string"&&t.trim()?t.trim():null},[e])}function Fg(){const e=mn(t=>t.manifest?.fmExtra??"");return x.useMemo(()=>{const t=fc(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 Ta(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 _g({page:e,cover:t,coverY:n,onSetCover:o,onSetCoverY:r,readOnly:s=!1}={}){const{t:c}=Ht(),i=mn(ce=>ce.activePage),a=Og(),l=Fg(),m=Es(),[h,E]=x.useState(null),[R,k]=x.useState(null),[v,j]=x.useState(!1),[P,q]=x.useState(0),X=x.useRef(null),_=x.useRef(null),Z=e??i;x.useEffect(()=>{const ce=X.current;if(!ce)return;const se=()=>q(Ta(ce));se();const ae=new ResizeObserver(se);return ae.observe(ce),()=>ae.disconnect()},[Z,t,a]),x.useEffect(()=>{v&&P<1&&j(!1)},[v,P]);const ze=t!==void 0?t:a,p=R??(n??l),xe=o??(ce=>{Z&&m.getState().setPageCover(Z,ce)}),Qe=r??(ce=>{Z&&m.getState().setPageCoverY(Z,ce)});if(!Z||!ze)return null;const de=/^https?:\/\//i.test(ze)?ze:pc(ze);return u.jsxs("div",{className:`amx-cover${v?" amx-cover-repo":""}`,children:[u.jsx("img",{ref:X,src:de,alt:"",draggable:!1,style:{objectPosition:`50% ${p}%`},onLoad:ce=>q(Ta(ce.currentTarget)),onPointerDown:ce=>{if(!v||!ce.isPrimary||ce.pointerType==="mouse"&&ce.button!==0)return;const se=Ta(ce.currentTarget);if(se<1)return;ce.preventDefault(),ce.currentTarget.setPointerCapture(ce.pointerId);const ae=ce.currentTarget.currentCSSZoom||1;_.current={id:ce.pointerId,startY:ce.clientY,base:p,z:ae,slack:se,cur:p}},onPointerMove:ce=>{const se=_.current;if(!se||se.id!==ce.pointerId)return;const ae=(ce.clientY-se.startY)/se.z;se.cur=Math.max(0,Math.min(100,se.base-ae/se.slack*100)),k(se.cur)},onPointerUp:ce=>{const se=_.current;if(!se||se.id!==ce.pointerId)return;_.current=null,k(null);const ae=Math.round(se.cur*10)/10;ae!==se.base&&Qe(ae)},onPointerCancel:()=>{_.current=null,k(null)},onError:ce=>{ce.target.style.opacity="0.15"}}),u.jsx("div",{className:"amx-cover-grad"}),v&&u.jsx("div",{className:"amx-cover-hint",children:c("pgchrome.coverDragHint")}),!s&&u.jsx("div",{className:"amx-cover-tools",children:v?u.jsx("button",{onClick:()=>j(!1),children:c("pgchrome.coverDone")}):u.jsxs(u.Fragment,{children:[u.jsx("button",{onClick:ce=>{const se=ce.currentTarget.getBoundingClientRect();E({x:se.right,y:se.bottom+6})},children:c("pgchrome.coverChange")}),P>=1&&u.jsx("button",{onClick:()=>j(!0),children:c("pgchrome.coverReposition")}),u.jsx("button",{onClick:()=>xe(null),children:c("pgchrome.coverRemove")})]})}),h&&u.jsx(fu,{page:Z,x:h.x,y:h.y,onApply:o??void 0,onClose:()=>E(null)})]})}const Bg=["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 fu({page:e,x:t,y:n,onClose:o,onApply:r}){const{t:s}=Ht(),c=!!rn.searchImages,i=Es(),[a,l]=x.useState("gallery"),[m,h]=x.useState(""),[E,R]=x.useState(null),[k,v]=x.useState(!1),[j,P]=x.useState(!1),[q,X]=x.useState(""),[_,Z]=x.useState(null),ze=x.useId(),Ke=x.useRef([]),p=x.useRef(o);p.current=o,x.useEffect(()=>{const ae=document.activeElement instanceof HTMLElement?document.activeElement:null,Re=Me=>{Me.key==="Escape"&&(Me.preventDefault(),Me.stopPropagation(),p.current())};return document.addEventListener("keydown",Re,!0),()=>{document.removeEventListener("keydown",Re,!0),ae?.isConnected&&ae.focus({preventScroll:!0})}},[]);const xe=[{id:"gallery",label:"pgchrome.tabGallery",icon:$f},{id:"url",label:"pgchrome.tabUrl",icon:Wl},{id:"upload",label:"pgchrome.tabUpload",icon:Mi}],Qe=ae=>{Z(ae),r?r(ae):i.getState().setPageCover(e,ae)},de=()=>{const ae=m.trim();!ae||!rn.searchImages||(v(!0),P(!1),rn.searchImages(ae).then(Re=>{R(Re),v(!1)}).catch(()=>{R(null),P(!0),v(!1)}))},ce=()=>{const ae=document.createElement("input");ae.type="file",ae.accept="image/*",ae.onchange=()=>{const Re=ae.files?.[0];Re&&(async()=>{try{const Me=new Uint8Array(await Re.arrayBuffer()),{opts:rt}=await ea(),{pageRel:Je}=await rn.saveAttachment(e,Re.name||"cover.png",Me,rt);Qe(mc(e.split("/").slice(0,-1).join("/"),Je))}catch{}})()},ae.click()},se=ae=>u.jsx("div",{className:"amx-coverpick-grid",children:ae.map((Re,Me)=>u.jsxs("button",{className:"amx-coverpick-item","aria-label":s("pgchrome.chooseCover",{index:Me+1}),"aria-pressed":_===Re.full,onClick:()=>Qe(Re.full),children:[u.jsxs("span",{className:"amx-coverpick-thumb",children:[u.jsx(Gl,{size:20,strokeWidth:1.7,"aria-hidden":"true"}),u.jsx("img",{src:Re.thumb,alt:"",loading:"lazy",onError:rt=>{rt.currentTarget.hidden=!0}}),_===Re.full&&u.jsx("span",{className:"amx-coverpick-selected",children:u.jsx(Ms,{size:14,"aria-hidden":"true"})})]}),Re.author&&u.jsx("span",{className:"amx-coverpick-cap",children:Re.author})]},Re.full))});return gc.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:ae=>ae.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(ca,{size:14,strokeWidth:1.7,"aria-hidden":"true"})})]}),u.jsx("div",{className:"amx-coverpick-tabs",role:"tablist","aria-label":s("pgchrome.coverTitle"),children:xe.map(({id:ae,label:Re,icon:Me},rt)=>u.jsxs("button",{ref:Je=>{Ke.current[rt]=Je},id:`${ze}-${ae}`,role:"tab","aria-selected":a===ae,"aria-controls":ze,tabIndex:a===ae?0:-1,onClick:()=>l(ae),onKeyDown:Je=>{const ee=Je.key==="ArrowRight"?(rt+1)%xe.length:Je.key==="ArrowLeft"?(rt+xe.length-1)%xe.length:Je.key==="Home"?0:Je.key==="End"?xe.length-1:-1;ee<0||(Je.preventDefault(),l(xe[ee].id),Ke.current[ee]?.focus())},children:[u.jsx(Me,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),s(Re)]},ae))}),u.jsxs("div",{id:ze,role:"tabpanel","aria-labelledby":`${ze}-${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(jf,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),u.jsx("input",{"aria-label":s("pgchrome.searchPlaceholder"),placeholder:s("pgchrome.searchPlaceholder"),value:m,onChange:ae=>h(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"&&de()}}),u.jsx("button",{className:"amx-coverpick-go",disabled:k||!m.trim(),onClick:de,children:k?"…":s("pgchrome.search")})]}),u.jsx("div",{className:"amx-coverpick-section",children:s(E?.length?"pgchrome.results":"pgchrome.featured")}),se(E&&E.length>0?E:Bg),!k&&j&&u.jsx("div",{className:"amx-coverpick-hint",children:s("pgchrome.searchUnavailable")}),!k&&!j&&E?.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:`${ze}-url-input`,children:s("pgchrome.imageUrl")}),u.jsx("input",{id:`${ze}-url-input`,placeholder:s("pgchrome.urlPlaceholder"),value:q,onChange:ae=>X(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"&&/^https?:\/\//i.test(q.trim())&&Qe(q.trim())}}),u.jsx("div",{className:"amx-coverpick-hint",children:s("pgchrome.urlHint")}),u.jsx("button",{className:"amx-coverpick-go",disabled:!/^https?:\/\//i.test(q.trim()),onClick:()=>{/^https?:\/\//i.test(q.trim())&&Qe(q.trim())},children:s("pgchrome.setCover")})]}),a==="upload"&&u.jsxs("div",{className:"amx-coverpick-body amx-coverpick-upload",children:[u.jsx(Mi,{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 Hg=()=>Qc[Math.floor(Math.random()*Qc.length)];function Kg({x:e,y:t,current:n,onPick:o,onClose:r}){const{t:s}=Ht(),[c,i]=x.useState(""),a=Id(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)):Pd.map(l=>u.jsxs(x.Fragment,{children:[u.jsx("div",{className:"amx-iconpick-group",children:s(l.nameKey)}),l.items.map(([m,h])=>u.jsx("button",{className:`amx-iconpick-item${n===m?" active":""}`,title:h,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 Vg=new Set(["bullet","ordered","task"]);function qg(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 pu(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"?(hu(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(je.near(e.state.doc.resolve(i)))),aa(e,o,null)&&(c=!0);return c&&Vg.has(o.kind)&&Wg(e,t,n+(e.state.doc.content.size-s)),c}function Wg(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 h=s.child(l+1);m.type===h.type&&/_list$/.test(m.type.name)&&c.push(i)}if(!c.length)return;const a=e.state.tr;for(const l of c.reverse())Df(a.doc,l)&&a.join(l);a.docChanged&&e.dispatch(a)}function rc(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(je.near(a.doc.resolve(t+1))),e.dispatch(a.scrollIntoView()),!0}const Yg=/^\[![\w-]+\]/;function _i(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&&Lf(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(je.near(e.state.doc.resolve(t+1)))),!aa(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||Yg.test(a.textContent)?!!i:(e.dispatch(e.state.tr.insertText(a.content.size?"[!note] ":"[!note]",s+2)),!0)}const mu=/^\[![\w-]+\]([+-])?[ \u00a0]?/;function hu(e,t){const n=e.doc.nodeAt(t),o=n?.firstChild,r=n?.type.name==="blockquote"&&o?.isTextblock?mu.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 Bi(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?mu.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 E=c[0].length-(/[ \u00a0]$/.test(c[0])?1:0);return i.replaceWith(t+2,t+2+E,e.state.schema.text(Od)),e.dispatch(i.scrollIntoView()),!0}if(hu(i,t),o!=="code"&&o.kind==="quote")return i.setSelection(je.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)),h=m?Rf(m):null;return!m||h==null?!1:(i.lift(m,h),i.setSelection(je.near(i.doc.resolve(t+1))),e.dispatch(i.scrollIntoView()),o==="code"?rc(e,t,t+l):o.kind==="text"?!0:o.kind==="heading"?aa(e,o,null):pu(e,t,t+l,o))}function Ug(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 qr(e){const t=Ug(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 fs(e,t,n){let o=n,r;try{r=e.doc.resolve(t)}catch{return n}const s=r.parent;let c=t;for(let i=r.index();i<s.childCount&&c<o;i++){const a=s.child(i);if(a.type.name==="heading"){const l=Gr(e,c);l!=null&&l>o&&(o=l)}c+=a.nodeSize}return o}function Hr(e,t,n){for(const o of[Xr,km]){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 es(e,t,n){const o=t.getMeta(Xr)?.set;if(!o?.length)return;const r=zi(e.doc,Xr.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=>zi(t.doc,[l]).every(m=>{const h=t.doc.resolve(m.start),E=h.parent;let R=m.start;for(let k=h.index();k<E.childCount&&R<m.after;k++){const v=R;R+=E.child(k).nodeSize;const j=v>=n.newStart&&v<n.newStart+c?n.from+(v-n.newStart):i.map(v);if(!s(j))return!1}return!0}));a.length!==o.length&&t.setMeta(Xr,{set:a})}En({"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 Ho=e=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:e}}))},kc=e=>(e.split("/").pop()??e).replace(/\.md$/i,""),ts=e=>e.split("/").slice(0,-1).join("/");function Xg(e,t,n){if(t===n)return e;const o=[!1,!0].map(r=>[Ki(t,r),Ki(n,r)]);return xd(e,r=>r.replace(/(^|[^!])\[([^\]\n]*)\]\(([^)\s]+)((?:\s+"[^"]*")?)\)/g,(s,c,i,a,l)=>{if(/^[/<]/.test(a)||!Hi(a))return s;const m=a.indexOf("#"),h=m<0?a:a.slice(0,m);let E=!1;try{decodeURIComponent(h)}catch{E=!0}const[R,k]=o[+E],v=yd(k,Fl(mc(R,h)));if(E&&v.includes(" "))return s;const j=v.replace(/ /g,"");return`${c}[${i}](${!j.includes("/")||!Hi(j)?"./":""}${j}${m<0?"":a.slice(m)}${l})`}))}const Hi=e=>/^(?:note|file)$/.test(Bl(e)),Ki=(e,t)=>e.split("/").map(n=>{const o=t?n.replace(/%/g,""):n;return Vi(o)===o?n:` ${Vi(n)}`}).join("/"),Vi=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 Gg(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 Jg(e,t){const{text:n,eol:o}=qr(e),r=n?n.endsWith(`
27
-
28
- `)?"":n.endsWith(`
29
- `)?`
30
- `:`
31
-
32
- `:"";return oo(`${n}${r}${t}
33
- `,o)}function Zg(e,t){const n=kc(e);return gs(n,t)===e?n:e.replace(/\.md$/i,"")}function Qg(e,t,n){const o=Zg(t,n);if(e.type.name==="heading"){const s=Fd(e.textContent);return s?{kind:"heading",link:`[[${o}#${s}]]`}:null}const r=Ol(e.textContent);return r?{kind:"block",link:`[[${o}#^${r}]]`}:null}function ex(e){const t=navigator.clipboard?.writeText(e);if(!t){Ho(Te("blocklinks.copyFailed"));return}t.then(()=>Ho(Te("blocklinks.copied",{link:e})),()=>Ho(Te("blocklinks.copyFailed")))}function tx(e){let t=!0;return e.descendants(n=>(/^amadeus(CanvasCard|ColumnRow|ColumnCell)$/.test(n.type.name)&&(t=!1),t)),t}async function nx(e){const{view:t,from:n,to:o,source:r,target:s}=e,c=kc(s);if(s===r)return!1;const i=t.state.doc.slice(n,o).content,a=e.serialize(i);if(!a?.trim())return Ho(Te("blocklinks.moveFailed",{name:c})),!1;let l=Xg(_r(a,ts(s)).trim(),ts(r),ts(s));e.pages&&ts(r)!==ts(s)&&(l=fd(l,r,s,{pairs:new Map,pagesBefore:e.pages,pagesAfter:e.pages}));try{if(pd(s)){if(!md(s,l,"end"))throw new Error("insert refused");try{await hd(s,!0)}catch{return Ho(Te("blocklinks.targetUnsaved",{name:c})),!1}}else{const h=await rn.readTextFile(s);if(h==null)throw new Error("missing");if(Gg(qr(h).text))throw new Error("unsafe tail");const E=await rn.writeTextFile(s,Jg(h,l),{base:Br(h)});if(E&&!E.ok)return Ho(Te("blocklinks.moveConflict",{name:c})),!1}}catch{return Ho(Te("blocklinks.moveFailed",{name:c})),!1}if(t.isDestroyed||o>t.state.doc.content.size||!t.state.doc.slice(n,o).content.eq(i))return Ho(Te("blocklinks.keptSource",{name:c})),!0;const m=t.state.tr.delete(n,o);return Hr(t.state,m,{from:n,to:o,drop:!0}),t.dispatch(m.scrollIntoView()),Ho(Te("blocklinks.moved",{name:c})),!0}function gu({pages:e,exclude:t,onPick:n,onClose:o}){const{t:r}=Ht(),[s,c]=x.useState(""),[i,a]=x.useState(0),l=Wh(s,e.filter(m=>m!==t&&/\.md$/i.test(m)),gd).slice(0,30);return x.useEffect(()=>{a(0)},[s]),gc.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(h=>Math.min(h+1,l.length-1))):m.key==="ArrowUp"?(m.preventDefault(),a(h=>Math.max(h-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,h)=>u.jsx("button",{className:"cmd-item",role:"option","aria-selected":h===i,"data-active":h===i||void 0,onMouseEnter:()=>a(h),onClick:()=>n(m),children:u.jsxs("span",{className:"cmd-row",children:[u.jsx("span",{className:"cmd-title",children:kc(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 ox(e){return e.nodeType===1}function rx(e){return ox(e)&&e.namespaceURI==="http://www.w3.org/1999/xhtml"}function sx(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&&rx(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 ax(e,t){let n=[],o,r;const s=()=>{const m=e.dom.getBoundingClientRect(),h=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(h)||(r=m,o=h,n=sx(e)),n},c=(m,h)=>{if(!e.editable||e.isDestroyed)return;const E=(v,j)=>{const[P,q]=v,[X,_]=j;return Wi(m,q)-Wi(m,_)||P-X};let R=s();R.sort(E),R=R.slice(0,8);const k=R.find(v=>t?.({view:e,pos:v[0],event:h})!==!1);if(!(k&&ix(e,k[0])))return k};let i,a;return(m,h)=>(i&&cx(i,m)||(i=m,a=c(m,h)),a)}function cx(e,t){return e[0]===t[0]&&e[1]===t[1]}function qi(e,t){return Math.abs(e[0]-t[0])+Math.abs(e[1]-t[1])}function Wi(e,t){return Math.min(qi(e,[t[0],t[1]]),qi(e,[t[2],t[3]]))}function ix(e,t){const n=e.dragging;if(!n)return;const{move:o}=n;if(!o)return;const r=e.state.selection;if(!(r instanceof Ce))return;const{from:s,to:c}=r;return s<=t&&t<=c}function lx(e){let t;return new Wt({key:new Ln("prosemirror-drop-indicator"),view:n=>(t=ax(n,e.onDrag),dx(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:R}=n.dragging||{};R?R.replace(a):a.deleteSelection()}const l=a.mapping.map(i),m=r.openStart==0&&r.openEnd==0&&r.content.childCount==1,h=a.doc;if(m?a.replaceRangeWith(l,l,r.content.firstChild):a.replaceRange(l,l,r),a.doc.eq(h))return!0;const E=a.doc.resolve(l);if(m&&Ce.isSelectable(r.content.firstChild)&&E.nodeAfter&&E.nodeAfter.sameMarkup(r.content.firstChild))a.setSelection(new Ce(E));else{let R=a.mapping.map(i);a.mapping.maps[a.mapping.maps.length-1].forEach((k,v,j,P)=>R=P),a.setSelection(ux(n,E,a.doc.resolve(R)))}return n.focus(),n.dispatch(a.setMeta("uiEvent","drop")),!0}}})}function ux(e,t,n,o){return e.someProp("createSelectionBetween",r=>r(e,t,n))||je.between(t,n,o)}function dx(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=h=>{i=!0;const{clientX:E,clientY:R}=h;if(s===E&&c===R)return;s=E,c=R;const k=t([E,R],h);if(k){const[v,[j,P,q,X]]=k,_={p1:{x:j,y:P},p2:{x:q,y:X}};n.onShow?.({view:e,pos:v,line:_})}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)}}}En({"canvasedit.textDefault":{zh:"文本",en:"Text"}});function qo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.id;return typeof t=="string"&&t?t:null}function Yi(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t?t:null}function _o(e){return Array.isArray(e)?[...e]:[]}function xu(e,t,n){return e.map(o=>qo(o)===t?{...o,...n}:o)}function fx(e,t){const n=new Set,o=e.filter(r=>{const s=qo(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=Yi(s.from),i=Yi(s.to);return!(c&&n.has(c)||i&&n.has(i))}):o}function Ui(e,t,n,o){return e.map(r=>{const s=qo(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 ps(e,t){const n=new Set;for(const o of e){const r=qo(o);r&&n.add(r)}for(let o=1;;o++){const r=`${t}${o}`;if(!n.has(r))return r}}const we="m:",px={rect:{w:200,h:120},ellipse:{w:180,h:120},text:{w:180,h:40}},Xi={w:480,h:320};function yu(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:Te("canvasedit.textDefault")}:{}}}function mx(e,t,n,o){const r=px[t];return yu(e,t,{x:n-r.w/2,y:o-r.h/2,w:r.w,h:r.h})}function sc(e){return e==="m:"?{main:!0}:e.startsWith("c:")?{ref:e.slice(2)}:e.startsWith("e:")?{id:e.slice(2)}:null}function hx(e,t,n){if(t===n)return e;const o=sc(t),r=sc(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:ps(e,"e"),type:"connector",from:o,to:r}]}const ms={fromEnd:"none",toEnd:"arrow"};function gx(e,t,n){let o=!1;const r=e.map(s=>{const c=qo(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 h=m===ms[l];(h?!(l in i):i[l]===m)||(a??={...i},h?delete a[l]:a[l]=m)}return a?(o=!0,a):s});return o?r:e}const Ir=(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 xx(e,t,n,o){const r=sc(o);if(!r)return e;const s=e.find(a=>qo(a)===t);if(!s||s.type!=="connector")return e;const c=n==="from"?s.to:s.from;return Ir(r,s[n])||Ir(r,c)||e.some(a=>{if(qo(a)===t||!a||typeof a!="object"||a.type!=="connector")return!1;const l=a;return Ir(r,l.from)&&Ir(c,l.to)||Ir(r,l.to)&&Ir(c,l.from)})?e:xu(e,t,{[n]:r})}function yx(e,t,n,o){return e.map(r=>{if(qo(r)!==t)return r;const s={...r};return o?s[n]=o:delete s[n],s})}function Vt(e){const t=Object.create(null);if(!e||typeof e!="object"||Array.isArray(e))return t;for(const n of Object.keys(e))t[n]=e[n];return t}function Kr(e,t,n){if(!t||!n||t===n)return e;let o=n;const r=new Set([t]);for(;typeof o=="string"&&o;){if(r.has(o))return e;r.add(o),o=e[o]}const s=Vt(e);return s[t]=n,s}function bx(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 Cr=(e,t)=>Object.keys(e).filter(n=>e[n]===t).sort();function bu(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 vx(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 na(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&&bu(n,e[r].anchor,e[t].anchor,o);)r++;return r}function wx(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 kx=/^(?:[1-6]|#[0-9a-fA-F]{6})$/;function ia(e){return typeof e!="string"||!kx.test(e)?null:e.length===1?`var(--amx-cv-${e})`:e}function Sx(e,t,n){let o=!1;const r=e.map(s=>{const c=qo(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 Sc=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/;function $a(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 Ao(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=Sc.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 ns(e,t){const n=[],o=[];return t.forEach(r=>{if(r.type.name==="amadeusCanvasCard"){let s=Ao(e);for(;n.includes(s);)s=Ao(e);n.push(s),o.push(r.type.create({...r.attrs,anchor:s},r.content,r.marks))}else o.push(r)}),n.length?{content:zo.fromArray(o),minted:n}:{content:t,minted:n}}const Cx=xc("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} -->`)}}})),Ex=xc("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 Mx(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 E=l.children[0];E?.type==="html"&&typeof E.value=="string"&&(m=E.value)}if(m==null)return null;const h=Sc.exec(m.trim());return h?h[1]:null},s=[];if(o.forEach((l,m)=>{const h=r(l);h&&s.push({id:h,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(P=>P.refs);if(!m.length)continue;const h=m.map(P=>c.get(P)??-1);if(h.some(P=>P<0||i.has(P))||new Set(h).size!==h.length||!h.every((P,q)=>q===0||P===h[q-1]+1))continue;const E=h[h.length-1],R=l.tail!=null&&E+1<s.length&&s[E+1].id===l.tail&&!i.has(E+1)?E+1:null,k=R!=null?s[R].idx:E+1<s.length?s[E+1].idx:o.length,v=[];let j=!0;l.columns.forEach((P,q)=>{const X=c.get(P.refs[0]),_=s[X].idx+1,Z=q+1<l.columns.length?c.get(l.columns[q+1].refs[0]):null,ze=Z!=null?s[Z].idx:k;if(ze<_){j=!1;return}const Ke=o.slice(_,ze);v.push({type:"amadeusColumnCell",anchor:P.refs[0],width:P.width||1,children:Ke.length?Ke:[{type:"paragraph",children:[]}]})}),!(!j||v.length<2)&&(h.forEach(P=>i.add(P)),R!=null&&i.add(R),a.push({from:s[h[0]].idx,to:R!=null?s[R].idx+1:k,node:{type:"amadeusColumnRow",tail:R!=null?l.tail:"",children:v}}))}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 zx(e,t){return[Ql("amadeusColumnsFold",()=>()=>n=>{Mx(n,e(),t)})].flat()}function Ax(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=Sc.exec(String(o.attrs.value??"").trim());r&&t.push(r[1])}),t}function Nx(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusColumnRow")return;const o=[];n.forEach(r=>{o.push({refs:Ax(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 Cc=e=>e.childCount===1&&e.firstChild.type.name==="paragraph"&&e.firstChild.content.size===0;function oa(e,t){const{paragraph:n,html:o}=e.nodes;return t&&n&&o?[n.create(null,o.create({value:`<!-- a ${t} -->`}))]:[]}function Ec(e,t,n,o=!1){const r=[];for(const s of t)r.push(...oa(e,String(s.attrs.anchor))),o&&Cc(s)||s.forEach(c=>r.push(c));return r.push(...oa(e,n)),r}const Tx=zt(()=>new Wt({key:new Ln("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=>oa(n.schema,a),c=[];if(n.doc.descendants((a,l,m)=>{if(a.type.name==="amadeusColumnRow"&&m?.type.name==="amadeusColumnCell"){const h=[];return a.forEach(E=>E.forEach(R=>h.push(R))),c.push({from:l,to:l+a.nodeSize,content:h.length?h:[r.create()]}),!1}return!0}),n.doc.forEach((a,l)=>{if(a.type.name!=="amadeusColumnRow")return;const m=[];a.forEach(j=>m.push(j));const h=o?m.filter(j=>!Cc(j)):m,E=h.some(j=>!j.attrs.anchor);if(h.length===m.length&&h.length>=2&&!E)return;const R=new Set;n.doc.descendants(j=>{j.type.name==="amadeusColumnCell"&&j.attrs.anchor&&R.add(String(j.attrs.anchor)),j.type.name==="amadeusColumnRow"&&j.attrs.tail&&R.add(String(j.attrs.tail))});const k=j=>{if(j.attrs.anchor)return j;let P="c"+Math.random().toString(36).slice(2,6);for(;R.has(P);)P="c"+Math.random().toString(36).slice(2,6);return R.add(P),j.type.create({...j.attrs,anchor:P},j.content)},v=m.filter(j=>!h.includes(j)).flatMap(j=>s(String(j.attrs.anchor)));if(h.length>=2)c.push({from:l,to:l+a.nodeSize,content:[a.type.create(a.attrs,h.map(k)),...v]});else{const j=[...v,...Ec(n.schema,h,String(a.attrs.tail??""))];c.push({from:l,to:l+a.nodeSize,content:j.length?j:[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 $x(e,t,n,o=!1){const{state:r}=e,s=r.selection;if(!(s instanceof Ce))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 h=null;if(m.depth>0){let P=-1;for(let q=m.depth;q>=1;q--)if(m.node(q).type===i){P=q;break}if(P<0||P!==1)return!1;h={rowPos:m.before(P),cellIndex:m.index(P)}}const E=new Set,R=()=>{let P=Ao(r.doc);for(;E.has(P);)P=Ao(r.doc);return E.add(P),P},k=R(),v=R();let j=r.tr;if(o||(j=j.delete(s.from,s.to)),h){const P=j.mapping.map(h.rowPos),q=j.doc.nodeAt(P);if(!q||q.type!==i)return!1;const X=n==="left"?h.cellIndex:h.cellIndex+1;let _=P+1;for(let Z=0;Z<Math.min(X,q.childCount);Z++)_+=q.child(Z).nodeSize;j=j.insert(_,a.create({anchor:v,width:1},l))}else{const P=j.mapping.map(t),q=j.doc.nodeAt(P);if(!q)return!1;const X=n==="left"?[a.create({anchor:v,width:1},l),a.create({anchor:k,width:1},q)]:[a.create({anchor:k,width:1},q),a.create({anchor:v,width:1},l)];j=j.replaceWith(P,P+q.nodeSize,i.create({tail:R()},X))}return j.setMeta("amxColumns",!0),e.dispatch(j.scrollIntoView()),!0}function jx(e,t,n=!1){const{state:o}=e,r=o.selection;if(!(r instanceof Ce))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 Rx(e,t,n=!1){const{state:o}=e,r=o.selection;if(!(r instanceof Ce))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 vu(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 E=Ao(r.doc);for(;a.has(E);)E=Ao(r.doc);return a.add(E),E},m=s.create({tail:l()},[c.create({anchor:l(),width:1},o),c.create({anchor:l(),width:1},i.create())]);let h=r.tr.replaceWith(t,n,m);return h=h.setSelection(je.near(h.doc.resolve(t+m.nodeSize-3))),h.setMeta("amxColumns",!0),h.setMeta("amxColumnsKeepEmpty",!0),e.dispatch(h.scrollIntoView()),!0}function wu(e,t,n,o=!1){const r=e.doc.nodeAt(t);if(!r||r.type.name!=="amadeusColumnCell"||!(o||Cc(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((q,X,_)=>{_!==l&&m.push(q)});const h=oa(e.schema,String(r.attrs.anchor));if(m.length>=2){const q=e.tr.delete(t,t+r.nodeSize);return h.length&&q.insert(q.mapping.map(a),h),q.setSelection(Vo.near(q.doc.resolve(Math.min(t,q.doc.content.size)),n)),q.scrollIntoView()}const E=[...Ec(e.schema,m,String(c.attrs.tail??"")),...h],R=e.tr.replaceWith(i,a,E),k=m[0],v=n<0?l>0:l>=m.length,j=v?k?.lastChild:k?.firstChild;let P=i;for(const q of E){if(q===j){R.setSelection(Vo.near(R.doc.resolve(v?P+q.nodeSize-1:P+1),v?-1:1));break}P+=q.nodeSize}return R.scrollIntoView()}function Lx(e,t){const{state:n}=e,o=n.doc.nodeAt(t);if(!o||o.type.name!=="amadeusColumnRow")return!1;const r=[];o.forEach(h=>r.push(h));const s=Ec(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,(h,E,R)=>a||R?.type.name!=="amadeusColumnCell"?!a:(i.from>=E&&i.from<E+h.nodeSize&&(a={node:h,off:i.from-E,nodeSel:i instanceof Ce&&i.from===E}),!1));const l=n.tr.replaceWith(t,t+o.nodeSize,c);let m=t;for(const h of c){const E=a;if(E&&h===E.node){l.setSelection(E.nodeSel?Ce.create(l.doc,m):Vo.near(l.doc.resolve(m+E.off)));break}m+=h.nodeSize}return e.dispatch(l.scrollIntoView()),!0}const Dx=[Cx,Ex,Tx].flat();En({"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 Ix(e){return e.kind==="instructions"?u.jsx(Px,{...e},e.pagePath):u.jsx(Ox,{...e},`${e.kind}:${e.pagePath}:${Cs(e.src)?.id??"source"}`)}function Px({src:e,readOnly:t=!1,activeInstructions:n=!0,onChange:o}){const{t:r}=Ht(),[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(_h,{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 Ox({kind:e,src:t,pagePath:n,readOnly:o=!1,onChange:r,onStart:s,onOpen:c}){const{t:i}=Ht(),a=x.useMemo(()=>Cs(t),[t]),[l,m]=x.useState(a),[h,E]=x.useState(!1),[R,k]=x.useState(null),[v,j]=x.useState(null),[P,q]=x.useState("idle"),X=x.useRef(!1),_=x.useRef(!1),Z=zr(),ze=e==="task"?typeof Z?.submitDocumentTask=="function"&&Z.hostExecution?.()!==!1:typeof Z?.startChat=="function",[Ke,p]=x.useState(()=>Z?.agents?.()??[]),xe=e==="task"?a?.sessionId||(v?.id===a?.id?v?.sessionId:void 0):void 0,Qe=o||h||!!xe;x.useEffect(()=>(X.current=!0,()=>{X.current=!1}),[]),x.useEffect(()=>{m(a),k(null)},[a]),x.useEffect(()=>{const Me=()=>{p(Z?.agents?.()??[])};return Me(),Z?.subscribeAgents?Z.subscribeAgents(Me):Z?.subscribe(Me)},[Z]),x.useEffect(()=>{if(q(xe?Z?.agentStatus?.(xe).phase??"idle":"idle"),!!xe)return Z?.subscribeAgentStatus?.(Me=>{Me.sessionId===xe&&q(Me.phase)},xe)},[Z,xe]);const de=async()=>{if(!(o||!ze||_.current||!l||!l.prompt.trim()||xe)){_.current=!0,E(!0),k(null);try{r(hs(l));const Me=await s(l,e==="prompt"?"prompt":"task");if(e==="task"&&!Me.sessionId)throw new Error(i("docagent.noSession"));X.current&&e==="task"&&Me.sessionId&&j({id:l.id,sessionId:Me.sessionId})}catch(Me){X.current&&k(Me instanceof Error?Me.message:i("docagent.startFailed"))}finally{_.current=!1,X.current&&E(!1)}}};if(!a||!l)return u.jsx("pre",{className:"am-doc-agent-source",children:u.jsx("code",{children:t})});const ce=xe?P==="waiting"?"docagent.waiting":P==="done"?"docagent.done":P==="error"?"docagent.failed":P==="idle"?"docagent.linked":"docagent.running":"docagent.ready",se=h||!!xe&&["thinking","speaking","tool"].includes(P),ae=e==="prompt"?Jl:Dp,Re=l.agent&&!Ke.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":h,children:[u.jsxs("div",{className:"am-doc-agent-header",children:[u.jsx(ae,{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":P,children:[se?u.jsx(oi,{size:12,className:"am-doc-agent-spin","aria-hidden":"true"}):P==="done"?u.jsx(Ms,{size:12,"aria-hidden":"true"}):null,i(h?"docagent.starting":ce)]})]}),o||xe?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:h,onKeyDown:Me=>Me.stopPropagation(),onChange:Me=>{const rt={...l,prompt:Me.target.value};m(rt),r(hs(rt))}}),u.jsxs("div",{className:"am-doc-agent-footer",children:[Qe?u.jsx("span",{className:"am-doc-agent-assignee",children:Ke.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 rt={...l,agent:Me.target.value||void 0};m(rt),r(hs(rt))},children:[u.jsx("option",{value:"",children:i("docagent.defaultAgent")}),Re&&u.jsx("option",{value:l.agent,children:l.agent}),Ke.map(Me=>u.jsx("option",{value:Me.slug,children:Me.name},Me.slug))]}),xe?c&&u.jsxs("button",{type:"button",className:"am-doc-agent-action",onClick:()=>c(xe),children:[u.jsx(Ti,{size:14,"aria-hidden":"true"}),i("docagent.open")]}):!o&&u.jsxs("button",{type:"button",className:"am-doc-agent-action",disabled:h||!ze||!l.prompt.trim(),title:ze?void 0:i("docagent.unavailable"),onMouseDown:Me=>Me.preventDefault(),onClick:()=>{de()},children:[h?u.jsx(oi,{size:14,className:"am-doc-agent-spin","aria-hidden":"true"}):u.jsx(Ti,{size:14,"aria-hidden":"true"}),i(h?"docagent.starting":e==="prompt"?"docagent.usePrompt":"docagent.assign")]})]}),!o&&!xe&&!ze&&u.jsx("div",{className:"am-doc-agent-hint",children:i("docagent.unavailable")}),R&&u.jsx("div",{className:"am-doc-agent-error",role:"alert",children:R})]})}function ac(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 ku(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 Su="forsion-intelligent-ui-html",Fx="forsion-sketch",_x=e=>e===Su||e===Fx;function ww(e){const t=Math.max(0,...(e.match(/`+/g)??[]).map(o=>o.length)),n="`".repeat(Math.max(3,t+1));return`${n}${Su}
38
- ${e.replace(/\s+$/,"")}
39
- ${n}`}const Bx=`/* 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
- `,Hx=`/* 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
- `,Kx=`/* 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
- `,Cu=16384,Eu="forsion_sketch_state_v1",cc=48;function la(e){try{const t=JSON.stringify(e);return t&&new TextEncoder().encode(t).length<=Cu?t:void 0}catch{return}}function Vx(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 Mu(e){const t=e.getItem(Eu);if(!t||t.length>Cu*(cc+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&&la(o.state)!==void 0).slice(-cc):[]}function qx(e){try{return Mu(localStorage).find(t=>t.key===e)?.state??null}catch{return null}}function Wx(e,t){const n=la(t);if(!(!n||e.length>=2048))try{const o=Mu(localStorage).filter(r=>r.key!==e);o.push({key:e,state:JSON.parse(n)}),localStorage.setItem(Eu,JSON.stringify(o.slice(-cc)))}catch{}}const Yx="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data:",Ux="allow-scripts",Gi=40,Xx=2400,Gx=220,Jx={"--fs-bg":"transparent"},Zx=[["--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 zu(e){return String(e).replace(/[<>]/g,"").trim()}function Ji(e){const t=getComputedStyle(e),n={...Jx};for(const[o,r]of Zx){const s=zu(t.getPropertyValue(r));s&&(n[o]=s)}return n["color-scheme"]=document.documentElement.getAttribute("data-mode")==="dark"?"dark":"light",n}const Os=new Set;let Pr=null;function Qx(e){return Os.add(e),!Pr&&typeof MutationObserver<"u"&&(Pr=new MutationObserver(()=>{for(const t of Os)t()}),Pr.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","data-skin","data-bg","data-mode","data-flat","data-glass","class"]})),()=>{Os.delete(e),!Os.size&&Pr&&(Pr.disconnect(),Pr=null)}}const ey=":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 ty(e){const t=Object.entries(e).map(([n,o])=>`${n.replace(/[^a-z-]/gi,"")}:${zu(o)}`).join(";");return t?`:root{${t}}`:""}function ny(e,t={},n=null,o=""){const r=(la(n)??"null").replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),s=Hx.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="${Yx}"><meta name="viewport" content="width=device-width, initial-scale=1"><style>${ty(t)}${ey}${Bx}</style><script>${s};
680
- ${Kx}<\/script></head><body>${e}</body></html>`}const Au=`(?![^>]*\\stype\\s*=\\s*["']?application/json\\b)`,oy=new RegExp(`<script\\b${Au}[^>]*>[\\s\\S]*?<\/script\\s*>`,"gi"),ry=new RegExp(`<script\\b${Au}[^>]*>[\\s\\S]*$`,"i"),sy=/<script\b[^>]*$/i,ay=/<[a-zA-Z][^>]*(?:>|$)/g,cy=/\son[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,iy=/<(fs-[a-z]+)\b(?![\s\S]*<\/\1\s*>)[\s\S]*$/i;function Zi(e){return e.replace(oy,"").replace(ry,"").replace(sy,"").replace(iy,"").replace(ay,t=>t.replace(cy,""))}const ly=400,uy=1500,dy=2e4,fy=150;function py(){try{const e=window.Capacitor;return!!(e&&typeof e.isNativePlatform=="function"&&e.isNativePlatform())}catch{return!1}}function my(e){return!e||document.activeElement!==e?!1:navigator.userActivation?.isActive===!0}const hy=()=>crypto.randomUUID?crypto.randomUUID():Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),gy=({item:e,actions:t,stateScope:n,onAsk:o})=>{const{t:r}=Ht(),s=x.useMemo(()=>n&&!e.draft?Vx(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?Zi(e.html):e.html),m=x.useRef(s?qx(s):null),h=x.useRef(hy()),E=x.useRef(null),R=x.useRef(null),k=x.useRef(null),[v,j]=x.useState(e.draft?Gi:Gx),[P,q]=x.useState(!1),[X,_]=x.useState(!1),[Z,ze]=x.useState(null);x.useLayoutEffect(()=>{E.current&&ze(Ji(E.current))},[]),x.useEffect(()=>Qx(()=>{const Je=E.current,ee=k.current?.contentWindow;Je&&ee&&ee.postMessage({type:"sketch-theme",vars:Ji(Je)},"*")}),[]);const Ke=x.useRef(!1),p=x.useRef(!1),xe=x.useRef(null),Qe=x.useRef(void 0),de=Je=>{k.current?.contentWindow?.postMessage(Je,"*")},ce=()=>{if(Qe.current=void 0,!Ke.current)return;const Je=xe.current;xe.current=null,Je!==null&&i.current&&!p.current&&de({type:"sketch-draft",html:Je})},se=()=>{!Ke.current||p.current||(p.current=!0,clearTimeout(Qe.current),Qe.current=void 0,xe.current=null,de({type:"sketch-final",html:e.html}))},ae=x.useRef(!!e.draft);x.useEffect(()=>{e.draft?(xe.current=Zi(e.html),Qe.current||(Qe.current=setTimeout(ce,fy))):ae.current&&se()},[e.html,e.draft]),x.useEffect(()=>()=>clearTimeout(Qe.current),[]);const Re=()=>{Ke.current=!0,!i.current&&ae.current?se():xe.current!==null&&ce()};x.useEffect(()=>{let Je,ee;const ge=()=>{s&&Je!==void 0&&Wx(s,JSON.parse(Je)),Je=void 0,ee=void 0},Se=C=>{if(!k.current||C.source!==k.current.contentWindow)return;const Y=C.data;if(Y?.type==="sketch-state"&&s){const ye=la(Y.state);ye!==void 0&&(Je=ye,ee||(ee=setTimeout(ge,200)))}Y&&Y.type==="sketch-height"&&Number.isFinite(Number(Y.height))&&j(Math.min(Xx,Math.max(Gi,Math.ceil(Number(Y.height)))));const fe=Y&&Y.nonce===h.current&&!i.current&&my(k.current);if(fe&&Y.type==="sketch-ask"&&typeof Y.text=="string"&&c.current){const ye=Date.now(),Ye=Y.text.trim().slice(0,ly);Ye&&ye-a.current>=uy&&(a.current=ye,c.current(Ye))}if(fe&&Y.type==="sketch-copy"&&typeof Y.text=="string"){const ye=Y.text.slice(0,dy);ye&&navigator.clipboard?.writeText(ye).catch(()=>{})}};return window.addEventListener("message",Se),window.addEventListener("pagehide",ge),()=>{window.removeEventListener("message",Se),window.removeEventListener("pagehide",ge),clearTimeout(ee),ge()}},[s]),x.useEffect(()=>{const Je=R.current;if(!Je||P)return;const ee=()=>_(Je.scrollHeight>Je.clientHeight+1);ee();const ge=new ResizeObserver(ee);return ge.observe(Je),()=>ge.disconnect()},[v,P]);const Me=x.useMemo(()=>Z?ny(l.current,Z,m.current,h.current):"",[Z]),rt=e.draft?void 0:t;return u.jsxs("div",{className:"sketch-card",ref:E,"data-sketch-call-id":e.callId,"data-sketch-draft":e.draft?"":void 0,children:[(e.title||rt)&&u.jsxs("div",{className:"sketch-card-head",children:[e.title&&u.jsx("div",{className:"sketch-card-title",children:e.title}),rt?.(e)]}),u.jsx("div",{ref:R,className:`sketch-clip${P?" open":""}${X&&!P?" faded":""}`,children:Z&&u.jsx("iframe",{ref:k,className:"sketch-frame",sandbox:Ux,srcDoc:Me,style:{height:v},title:e.title||"Intelligent UI",onLoad:Re})}),X&&u.jsx("button",{type:"button",className:"sketch-card-toggle",onClick:()=>q(Je=>!Je),children:r(P?"sketch.collapse":"sketch.expand")})]})},xy=({item:e})=>{const{t}=Ht();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")})]})},yy=({items:e,actions:t,stateScope:n,onAsk:o})=>{const r=py(),s=r?xy:gy;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}`))})};En({"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 Nu(){const[,e]=x.useState(0);return x.useEffect(()=>_l(()=>e(t=>t+1)),[]),Te}const by=Pf(()=>kd(()=>import("./PdfAnnotator-DafvjP3U.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url).then(e=>({default:e.PdfAnnotator}))),rr=()=>{},Tu=/^!\[\[([^\]\n]+)\]\]$/,vy=/\.(png|jpe?g|gif|webp|svg|avif|bmp)$/i,wy=/\.[a-z0-9]{1,8}$/i,ky=/\.db$/i,Sy=/\.pdf$/i,Cy=/^https?:\/\/\S+$/i;function Mo(e){if(e.type.name==="code_block"){const h={"forsion-instructions":"instructions","forsion-task":"task","forsion-prompt":"prompt"}[e.attrs.language];return h&&(h==="instructions"||Cs(e.textContent))?{k:"document-agent",type:h,src:e.textContent}:_x(e.attrs.language)?e.textContent.trim()?{k:"sketch",src:e.textContent}:null:e.attrs.language!=="forsion-button"||!Yl(ju(e.textContent))?null:{k:"button",src:e.textContent}}if(e.type.name!=="paragraph")return null;const t=e.textContent.trim(),n=Tu.exec(t);if(!n)return Cy.test(t)?{k:"bookmark",url:t}:null;const o=n[1],[r,s]=o.split("|"),c=r.trim();if(vy.test(c))return null;const i=bd(o);if(i)return{k:"web",url:i,w:ga(o)};if(!c.includes("#")&&ky.test(c))return{k:"db",name:c,view:s?.trim()||null};if(!c.includes("#")&&vd(c))return{k:"draw",target:c};const a=Ur.getState().embedRenderers;if(ri(a,o.trim()))return{k:"plugin",target:o.trim()};const l=c.includes("#")?Yc(c)?.target??null:c;if(l&&ri(a,l))return{k:"plugin",target:l};if(If(c))return{k:"note",target:o};const m=Yc(c);return m?{k:"file",name:m.target,fileKind:wd.test(m.target)?"video":"audio",loc:m.loc,badAnchor:c.includes("#")&&!m.loc,w:ga(o)}:!c.includes("#")&&wy.test(c)?{k:"file",name:c,fileKind:Sy.test(c)?"pdf":"other",w:ga(o)}:{k:"note",target:o}}const Ey=new Set(["file","db","draw","plugin","note"]),$u=e=>!!e&&Ey.has(e.k);function Ss(e){return!!e&&e.type.name==="paragraph"&&$u(Mo(e))}function My({name:e,fileKind:t,pagePath:n,loc:o,badAnchor:r,insertAfter:s}){const c=Nu(),i=mn(R=>R.files),a=mn(R=>R.openWikiLink),[l,m]=x.useState(!0),h=t==="pdf"?Ip(e,i,n):null;if(t==="other")return!/\.[a-z0-9]+\.md$/i.test(e)&&!ai()?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):rn.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 E=pc(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:["@",Uc(o.at),o.to?`–${Uc(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(R=>!R),children:c(l?"uembed.collapse":"uembed.expand")}),(t==="pdf"||ai())&&u.jsx("button",{className:"embed-media-btn",title:c(t==="pdf"?"uembed.openPdfInTab":"uembed.openWithSystem"),onClick:()=>{t==="pdf"?a(e,n):rn.openAttachment(n,e)},children:c("uembed.open")})]}),l&&t==="pdf"&&(h?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(by,{pdfPath:h,embed:!0})})}):u.jsx("iframe",{className:"embed-pdf",src:E,title:e})),l&&(t==="video"||t==="audio")&&u.jsx(Uf,{kind:t,url:E,name:e,pagePath:n,loc:o??null,insertAfter:s})]})}function zy({target:e,pagePath:t,readOnly:n}){const o=Nu(),r=mn(P=>P.openWikiLink),s=mn(P=>P.loadPage),c=mn(P=>P.pages),i=mn(P=>P.linkGraphVersion),[a,l]=x.useState("loading"),{note:m,subpath:h}=Md(e),E=h?`${m}#${h}`:m;x.useEffect(()=>{let P=!0;return l("loading"),Promise.resolve(E?rn.resolveEmbed?.(E,t)??null:null).then(q=>{P&&l(q)}).catch(()=>{P&&l(null)}),()=>{P=!1}},[E,t,i]);const R=!n&&a===null&&!!m&&!gs(m,c,t),k=()=>{mn.getState().openWikiLink(m,t),mn.getState().pendingWikiCreate?.name===m&&mn.getState().confirmWikiCreate()},j=(a&&a!=="loading"?Yf(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:[zd(a.owner)," ↗"]})]}),a==="loading"?u.jsx("div",{className:"embed-loading",children:o("uembed.resolving")}):a&&j?u.jsx(j,{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:(P,q)=>r(P,a.owner,q),getPageNames:()=>c}):u.jsxs("div",{className:"embed-missing",children:[o("uembed.embedMissing"),u.jsx("code",{children:e}),R&&u.jsx("button",{type:"button",className:"embed-media-btn embed-create",title:o("uembed.createTip",{name:m}),onClick:k,children:o("uembed.create")})]})]})}function Ay({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(Ix,{kind:e.type,src:e.src,pagePath:t,readOnly:s,activeInstructions:e.activeInstructions,onChange:c,onStart:r,onOpen:i=>zr()?.openDocumentTask?.(i)});case"db":return u.jsx(Wf,{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(qf,{target:e.target,pagePath:t,readOnly:s});case"plugin":return u.jsx(Vf,{target:e.target,pagePath:t});case"file":return u.jsx(My,{name:e.name,fileKind:e.fileKind,pagePath:t,loc:e.loc,badAnchor:e.badAnchor,insertAfter:s?()=>{}:o});case"note":return u.jsx(zy,{target:e.target,pagePath:t,readOnly:s});case"bookmark":return s?u.jsx(si,{url:e.url}):u.jsx(si,{url:e.url,onChangeUrl:i=>n(i),onEmbed:()=>n(`![[${Ed(e.url)}]]`)});case"web":return u.jsx(Kf,{url:e.url,toCard:()=>c(e.url)});case"button":{const i=Yl(ju(e.src));return i?u.jsx(Bf,{spec:i,readOnly:s,onChange:a=>c(Ny(Hf(a)))}):u.jsx("span",{})}case"sketch":return u.jsx(yy,{items:[{callId:"note-sketch",html:e.src}]})}}function ju(e){return"```forsion-button\n"+e+"\n```"}function Ny(e){const t=/^```forsion-button[ \t]*\r?\n([\s\S]*?)\r?\n?```$/.exec(e.trim());return t?t[1]:e}const Qi=(e,t)=>e.k==="db"?`db:${e.name}`:e.k==="document-agent"?`document-agent:${e.type}:${e.type==="instructions"?"":Cs(e.src)?.id}`:`${e.k}:${t}`;function Ty(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 $y(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&&!(el(r,i,a)&&el(s,l,m))&&(t=!1)}),!c&&!(n instanceof Of||n instanceof Ff)&&(t=!1)}),t}function el(e,t,n){const o=e.resolve(t);return o.parent.isTextblock&&o.depth>0&&o.sameParent(e.resolve(n))&&!Mo(o.parent)}function jy(e){return[zt(()=>{const n=new Ln("UNIFIED_EMBED_LAYER"),o=new Map,r=new Set;let s=Ur.getState().embedRenderers;const c=(a,l,m,h,E=null,R=null)=>{s=Ur.getState().embedRenderers;const k=[],v=new Map,j=(P,q)=>{const X=Mo(P);if(!X)return;X.k==="document-agent"&&(X.activeInstructions=a.resolve(q).depth===0);const _=Qi(X,P.textContent),Z=v.get(_)??0;v.set(_,Z+1);const ze=$u(X);if(!ze&&h===q&&m>q&&l<q+P.nodeSize||E===q)return;const Ke=`${_}#${Z}`,p=o.get(Ke),xe=X.k==="document-agent"?`${X.activeInstructions}:${P.textContent}`:P.textContent;p&&p.text!==xe&&(p.text=xe,p.render(X));const Qe=ze&&R===q;Qe||k.push(ao.inline(q+1,q+P.nodeSize-1,{class:"wikilink-src-hidden"})),k.push(ao.node(q,q+P.nodeSize,{class:`unified-embed-host${ze?" unified-embed-soft":""}${Qe?" unified-embed-src":""}`})),k.push(ao.widget(ze?q+P.nodeSize-1:q+1,de=>{const ce=o.get(Ke);if(ce)return ce.refs++,ce.dom;const se=document.createElement("div");se.className="unified-embed",se.contentEditable="false";const ae=Se=>{let C=0,Y=null;return Se.state.doc.descendants((fe,ye)=>{if(Y)return!1;const Ye=Mo(fe);return Ye&&Qi(Ye,fe.textContent)===_?C===Z?(Y={at:ye,size:fe.nodeSize},!1):(C++,!1):!0}),Y};se.addEventListener("mousedown",Se=>{if(Se.button!==0)return;const C=Se.target;if(C!==se&&C.parentElement!==se||C.closest('.amx-src-btn, .amx-img-resize, button, a, input, textarea, select, iframe, webview, video, audio, [contenteditable="true"]'))return;const Y=i;if(!Y)return;const fe=ae(Y);fe&&(Se.preventDefault(),Se.stopPropagation(),Y.dispatch(Y.state.tr.setSelection(Ce.create(Y.state.doc,fe.at))),Y.focus())});const Re=Se=>{const C=i;if(!C)return;const Y=ae(C);Y&&C.dispatch(C.state.tr.insertText(Se,Y.at+1,Y.at+Y.size-1))},Me=X.k==="web"||X.k==="file"&&X.fileKind!=="other",rt=X.k==="web"||X.k==="file"?X.w:void 0;rt&&(se.style.width=`${rt}px`);const Je=document.createElement("div");if(Je.className="unified-embed-body",se.appendChild(Je),Me){const Se=Tu.exec(P.textContent.trim())?.[1];Se!==void 0&&_f(se,se,C=>Re(`![[${Sd(Se,C)}]]`))}const ee=bm.createRoot(Je),ge=Se=>ee.render(u.jsx(Cd,{children:u.jsx(Ay,{kind:Se,pagePath:e.path,readOnly:!!e.readOnly,insertAfter:C=>{const Y=i;if(!Y)return;const fe=ae(Y);if(!fe)return;const ye=Y.state.schema.nodes.paragraph;if(!ye)return;const Ye=C.split(/\n{2,}/).map(Fe=>ye.create(null,Fe?Y.state.schema.text(Fe):null));Y.dispatch(Y.state.tr.insert(fe.at+fe.size,Ye))},startTask:async(C,Y)=>{const fe=zr(),ye=mn.getState().vaultRoot,Ye=i,Fe=Ye&&ae(Ye);if(!Fe)throw new Error(Te("documentTask.sourceGone"));const ht={from:Fe.at,to:Fe.at+Fe.size,deleted:!1};r.add(ht);try{const ct=()=>{if(ht.deleted||e.readOnly||!i||i!==Ye||e.alive?.()===!1||mn.getState().vaultRoot!==ye)return null;const et=i.state.doc.nodeAt(ht.from);if(!et||ht.from+et.nodeSize!==ht.to)return null;const un=Mo(et);if(un?.k!=="document-agent"||un.type!==Y)return null;const dt=et?Cs(et.textContent):null;return dt?.id===C.id&&dt.prompt===C.prompt&&dt.agent===C.agent?dt:null};if(!ct()||!e.flush)throw new Error(Te("documentTask.sourceGone"));if(await e.flush(),!ct()||!i)throw new Error(Te("documentTask.sourceGone"));const Kt=ku(ac(i.state.doc),e.path),jt=`${C.prompt.trim()}
681
-
682
- Source note: ${JSON.stringify(e.path)}. Read the source note before editing it.
683
- ${Kt}`;if(Y==="prompt"){const et=await fe?.startChat?.({agent:C.agent,prompt:jt,send:!1,...fe?.hostExecution?.()&&ye?{cwd:ye}:{},alive:()=>!!ct()});if(!et?.ok)throw new Error(et?.error||Te("docagent.unavailable"));return{}}const Et=ct()?.sessionId;if(Et)return{sessionId:Et};if(!ye||!fe?.submitDocumentTask)throw new Error(Te("docagent.unavailable"));const Gt=await fe.submitDocumentTask({key:`${ye}
684
- ${e.path}
685
- ${C.id}`,agent:C.agent,prompt:jt,vaultRoot:ye,alive:()=>!!ct(),onCreated:async et=>{const un=ct();if(!un||un.sessionId&&un.sessionId!==et)throw new Error(Te("documentTask.sourceGone"));const dt=i;if(dt.dispatch(dt.state.tr.insertText(hs({...un,sessionId:et}),ht.from+1,ht.to-1)),await e.flush(),ct()?.sessionId!==et)throw new Error(Te("documentTask.sourceGone"))}});if(!Gt.ok)throw new Error(Gt.error||Te("docagent.startFailed"));return{sessionId:Gt.sessionId}}finally{r.delete(ht)}},replaceText:Re})}));return ge(X),Am(se,de,()=>{const Se=i;if(!Se)return;const C=ae(Se);if(!C)return;const Y=Se.state.tr.setSelection(je.near(Se.state.doc.resolve(C.at+1)));Y.setMeta(n,{sourcePos:C.at}),Se.dispatch(Y),Se.focus()}),se.querySelector(".amx-src-btn")?.classList.add("amx-src-btn--block"),o.set(Ke,{root:ee,dom:se,text:xe,render:ge,refs:1}),se},{key:Ke,side:ze?1:-1,ignoreSelection:!0,stopEvent:de=>/^(key|composition|beforeinput|input|paste|cut|copy)/.test(de.type),destroy:()=>{const de=o.get(Ke);de&&(de.refs--,!(de.refs>0)&&queueMicrotask(()=>{de.refs>0||o.get(Ke)!==de||(o.delete(Ke),de.root.unmount())}))}}))};return a.descendants((P,q)=>(j(P,q),!0)),dr.create(a,k)};let i=null;return new Wt({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,h)=>{for(const q of r)for(const X of a.mapping.maps){if(q.deleted)break;const _=X.mapResult(q.from,1),Z=X.mapResult(q.to,-1);(_.deleted||Z.deleted||_.pos>=Z.pos)&&(q.deleted=!0),q.from=_.pos,q.to=Z.pos}const E=a.getMeta(n);let R=l.sourcePos;if(R!=null&&a.docChanged&&(R=a.mapping.map(R)),E&&typeof E.sourcePos=="number")R=E.sourcePos;else if(R!=null&&a.selectionSet){const q=h.doc.nodeAt(R);(!q||h.selection.to<=R||h.selection.from>=R+q.nodeSize)&&(R=null)}let k=l.pendingPos;if(k!=null&&a.docChanged&&(k=a.mapping.map(k,-1)),E?.commit)k=null;else if(a.docChanged&&h.selection.empty&&!/^(paste|drop)$/.test(String(a.getMeta("uiEvent")??""))){const q=h.selection.$head,X=q.depth>0?q.before():-1;X>=0&&q.parent.type.name==="paragraph"&&Mo(q.parent)?.k==="bookmark"&&Ty(a,X+1,X+q.parent.nodeSize-1)&&(k=X)}if(k!=null){const q=h.doc.nodeAt(k),{from:X,to:_}=h.selection;(!q||q.type.name!=="paragraph"||_<k+1||X>k+q.nodeSize-1)&&(k=null)}let v=null;const j=h.selection;if(j instanceof je&&j.$from.depth>0&&j.$from.sameParent(j.$to)&&Ss(j.$from.parent)){const q=j.$from.before(),X=l.revealPos==null?null:a.docChanged?a.mapping.map(l.revealPos):l.revealPos;(zm(h)||X===q)&&(v=q)}if(!a.docChanged&&!a.selectionSet&&!E&&k===l.pendingPos&&v===l.revealPos)return{sourcePos:R,pendingPos:k,revealPos:v,decos:l.decos.map(a.mapping,a.doc)};const P=(q,X=1)=>q==null?null:a.mapping.map(q,X);return!E&&R==null&&l.sourcePos==null&&k===P(l.pendingPos,-1)&&v===P(l.revealPos)&&s===Ur.getState().embedRenderers&&$y(a)?{sourcePos:R,pendingPos:k,revealPos:v,decos:l.decos.map(a.mapping,a.doc)}:{sourcePos:R,pendingPos:k,revealPos:v,decos:c(h.doc,h.selection.from,h.selection.to,R,k,v)}}},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 Ry=[zt(()=>Bo({Enter:Hd,"Shift-Enter":Bd,"Mod-Enter":_d}))].flat();function zs(e){let t=e.depth;for(;t>=1&&!["doc","amadeusColumnCell"].includes(e.node(t-1).type.name);)t--;return t}function ua(e){if(!e)return!1;const t=e.type.name;return t==="code_block"||t==="hr"||t==="horizontal_rule"||t==="table"?!0:Mo(e)!=null}function ic(e){if(!e)return!1;const t=e.type.name;return t==="hr"||t==="horizontal_rule"?!0:Mo(e)!=null&&!Ss(e)}function Wo(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 Ys(e,t)!=null?!0:Sm(e).some(n=>t>n.start&&t<n.after)}function Ly(e){let t=0;for(let n=e.depth;n>=1;n--)e.node(n).type.name==="list_item"&&t++;return t}function Ru(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 Dy=(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(Gr(e,r)==null)return!1;const s=e.schema.nodes.paragraph;if(!s)return!1;const c=e.tr.split(n.pos,1,[{type:s}]);return c.setMeta(Xr,{toggle:r}),t?.(c.scrollIntoView()),!0},Lu=(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(je.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},Iy=(e,t)=>{const n=e.selection;if(!(n instanceof Ce)||!n.node.isTextblock||Mo(n.node)!=null)return!1;const o=e.tr.setSelection(je.near(e.doc.resolve(n.to-1),-1));return t?.(o.scrollIntoView()),!0},Py=(e,t,n)=>{const{$from:o,empty:r}=e.selection;if(!r||!n||!t)return!1;const s=Ud(o);return!s||!Xd(o.parent.type.name,s)?!1:Gd(n,s)},Oy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parent.content.size!==0||Wo(n)==null)return!1;const r=e.schema.nodes.list_item;return r?Hl(r)(e,t):!1},Fy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o)return!1;const r=Wo(n);if(r==null||r!==n.depth-1||n.node(r).childCount<2||!yc(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 h=m.mapping.map(n.after(r));return m=m.insert(h,l),m.setSelection(je.near(m.doc.resolve(h+2))),t?.(m.scrollIntoView()),!0},_y=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset===0)return!1;const r=Wo(n);if(r==null||r!==n.depth-1)return!1;const s=n.node(r);if(s.childCount<2||yc(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(),h=e.doc.slice(l,m).content,E=n.before(r)+1+s.child(0).nodeSize+1,R=i.createAndFill(null,a.create(null,h));if(!R)return!1;let k=e.tr.delete(l,m);const v=k.mapping.map(E);return k=k.insert(v,R),k.setSelection(je.near(k.doc.resolve(v+2))),t?.(k.scrollIntoView()),!0},By=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o)return!1;const r=hc(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},Hy=(e,t,n)=>{const{$from:o,empty:r}=e.selection,s=Wo(o);if(s==null||o.node(s).attrs.checked!==!0)return!1;const c=e.schema.nodes.list_item;if(!c)return!1;if(r&&s===o.depth-1&&o.index(s)===0&&o.parentOffset===0&&o.parent.content.size>0){const h=c.createAndFill({...o.node(s).attrs,checked:!1});if(!h)return!1;if(!t)return!0;t(e.tr.insert(o.before(s),h).scrollIntoView());const E=n?n.root.getSelection?.():null;if(E&&E.rangeCount){const R=E.getRangeAt(0);E.removeAllRanges(),E.addRange(R)}return!0}if(!t)return qa(c)(e);let i=null;if(!qa(c)(e,h=>{i=h}))return!1;const a=i;if(!a)return!1;const l=a.selection.$from,m=Wo(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},Ky=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},Du=(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 Ky(Nm(n.parent)).some(([i,a])=>s>=i+2&&c<=a-2)?(t?.(e.tr.replaceSelectionWith(r.create({isInline:!0}),!1).scrollIntoView()),!0):!1},Vy=sr(Dy,Lu,Iy,Du,Py,Oy,Fy,_y,Hy,By),qy=(e,t)=>{const{$from:n}=e.selection,o=Wo(n),r=Ru(n);if(o!=null&&(r==null||o>r)&&n.node(o).attrs.checked!=null){const m=Vd(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&&Wo(n)!=null)return qa(s)(e,t);const c=e.schema.nodes.paragraph,i=zs(n);if(!c||i<1)return!1;const a=n.after(i),l=e.tr.insert(a,c.create());return l.setSelection(je.near(l.doc.resolve(a+1))),t?.(l.scrollIntoView()),!0},Wy=(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},Yy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=Ru(n);if(r==null)return!1;if(Wd(n.node(r))?.type==="fold"&&Yd.getState(e)?.srcAt!==n.before(r)){if(n.depth===r+1){const E=n.before(),R=e.doc.resolve(E).nodeBefore;if(R&&(R.type.name==="blockquote"||ua(R))&&Ce.isSelectable(R))return t?.(e.tr.setSelection(Ce.create(e.doc,E-R.nodeSize)).scrollIntoView()),!0}return!1}if(n.index(r)===0){const E=n.before(r),R=e.doc.nodeAt(E);return!R||!Ce.isSelectable(R)?!1:(t?.(e.tr.setSelection(Ce.create(e.doc,E))),!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 h=m.mapping.map(a);return m=m.insert(h,l),m.setSelection(je.near(m.doc.resolve(h+1))),t?.(m.scrollIntoView()),!0},Uy=(e,t,n)=>{const{$from:o,empty:r}=e.selection;return!r||o.parentOffset!==0||!n||Wo(o)==null?!1:qd(n)},Xy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=zs(n);if(r<1||r!==n.depth)return!1;const s=n.before(r),i=e.doc.resolve(s).nodeBefore;if(!ua(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||!Ce.isSelectable(m)||fr(e,a)?!1:(l=l.setSelection(Ce.create(l.doc,a)),t?.(l.scrollIntoView()),!0)},Gy=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==0)return!1;const r=hc(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},lc=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=wu(t,o.before(-1),e);return s?(n?.(s),!0):!1},Jy=sr(lc(-1),Wy,Yy,Uy,Gy,Xy),Zy=(e,t,n)=>{const{$from:o,empty:r}=e.selection;if(!r||o.parentOffset!==0)return!1;if(hc(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||Wo(o)==null)return!1;if(!t||!n)return!0;for(let i=0;i<32&&!(Ly(n.state.selection.$from)<=1||!Hl(c)(n.state,a=>n.dispatch(a)));i++);return!0},tl=(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 Gr(e,r)==null?!1:(t?.(e.tr.setMeta(Xr,{toggle:r})),!0)},nl=(e,t)=>{const{$from:n,empty:o}=e.selection;if(!o||n.parentOffset!==n.parent.content.size)return!1;const r=zs(n);if(r<1)return!1;const s=n.after(r),c=e.doc.resolve(s).nodeAfter;return!c||!ua(c)||!Ce.isSelectable(c)||fr(e,s)?!1:(t?.(e.tr.setSelection(Ce.create(e.doc,s)).scrollIntoView()),!0)},Qy=/^\[![\w-]+\]/,ol=(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=k=>{for(let v=k.depth;v>0;v--)if(k.node(v).type.name==="table")return!0;return!1};if(r(n))return!1;const s=n.after(),c=Vo.findFrom(e.doc.resolve(s),1,!0);if(!(c instanceof je))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=k=>{for(let v=k.depth;v>0;v--)if(k.node(v).type.spec.isolating)return k.before(v);return-1};if(a(n)!==a(i))return!1;let l=!1;if(e.doc.nodesBetween(s,i.before(),(k,v)=>(v>=s&&v+k.nodeSize<=i.before()&&(k.isLeaf||k.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&&Qy.test(i.parent.textContent)){const k=e.doc.nodeAt(m);return!k||!Ce.isSelectable(k)?!1:(t?.(e.tr.setSelection(Ce.create(e.doc,m)).scrollIntoView()),!0)}const h=n.parent.textContent+i.parent.textContent,E=e.tr.delete(n.pos,i.pos),R=E.doc.resolve(E.mapping.map(n.pos));return!R.parent.isTextblock||R.parent.textContent!==h||E.doc.textContent!==e.doc.textContent?!1:(t?.(E.setSelection(je.create(E.doc,R.pos)).scrollIntoView()),!0)};function rl(e){return(t,n,o)=>{const r=t.selection;if(!r.empty||!o||!o.endOfTextblock(e))return!1;const s=r.$from,c=zs(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(!ic(a)||!a)return!1;const l=e==="down"?i:i-a.nodeSize,m=t.doc.nodeAt(l);return!m||!Ce.isSelectable(m)||fr(t,l)?!1:(n?.(t.tr.setSelection(Ce.create(t.doc,l)).scrollIntoView()),!0)}}function Fs(e){return(t,n,o)=>{const r=t.selection;if(!(r instanceof je)||!r.empty||!o)return!1;const s=r.$head;if(!s.parent.isTextblock)return!1;const c=zs(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),h=s.depth===c&&Ss(m),E=Vo.findFrom(t.doc.resolve(i?l+m.nodeSize-1:l+1),i?-1:1,!0);if(!E||E.$head.start()!==s.start())return!1;if(a){if(h&&e==="down")try{const q=o.coordsAtPos(s.pos,s.pos===s.end()?-1:1),X=o.coordsAtPos(s.end(),-1);if(Math.abs(q.top-X.top)>Math.max(2,(q.bottom-q.top)/2))return!1}catch{return!1}else if(!o.endOfTextblock(e))return!1}else if(s.pos!==E.head)return!1;const R=i?l+m.nodeSize:l,k=i?t.doc.resolve(R).nodeAfter:t.doc.resolve(R).nodeBefore,v=k?i?R:R-k.nodeSize:-1,j=s.parentOffset;if(k&&Ss(k)){if(fr(t,v))return!1;const q=k.content.size,X=e==="right"?0:e==="left"?q:Math.min(j,q);return n?.(t.tr.setSelection(je.create(t.doc,v+1+X)).scrollIntoView()),!0}if(!h||!i)return!1;if(!k){const q=s.node(c-1),X=t.schema.nodes.paragraph;if(!X||!q.canReplaceWith(s.index(c-1)+1,s.index(c-1)+1,X))return!1;const _=o.root.getSelection?.();if(_?.anchorNode&&o.dom.contains(_.anchorNode))try{if(o.posAtDOM(_.anchorNode,_.anchorOffset)!==s.pos)return!1}catch{return!1}if(!n)return!0;const Z=t.tr.insert(R,X.create());return n(Z.setSelection(je.create(Z.doc,R+1)).scrollIntoView()),!0}if(fr(t,v))return!1;if(ic(k)&&Ce.isSelectable(k))return n?.(t.tr.setSelection(Ce.create(t.doc,v)).scrollIntoView()),!0;let P=k.isTextblock&&!k.type.spec.code?je.create(t.doc,v+1+(e==="down"?Math.min(j,k.content.size):0)):Vo.findFrom(t.doc.resolve(v),1,!0);return P?(P instanceof je&&ic(P.$head.parent)&&(P=Ce.create(t.doc,P.$head.before())),n?.(t.tr.setSelection(P).scrollIntoView()),!0):!1}}function sl(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(je.create(m.doc,l+1)).scrollIntoView()),!0}}const eb=(e,t)=>e.selection.$from.parent.type.name!=="code_block"?!1:(t?.(e.tr.insertText(`
686
- `).scrollIntoView()),!0);function al(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 Ss(r)?fr(t,s)?!1:(n?.(t.tr.setSelection(je.create(o,e==="up"?s+1:s+r.nodeSize-1)).scrollIntoView()),!0):Mo(r)!=null?!Ce.isSelectable(r)||fr(t,s)?!1:(n?.(t.tr.setSelection(Ce.create(o,s)).scrollIntoView()),!0):r.type.name==="code_block"?(n?.(t.tr.setSelection(je.create(o,e==="up"?s+1:s+r.nodeSize-1)).scrollIntoView()),!0):!1}}const tb={"(":")","[":"]","{":"}","<":">",'"':'"',"'":"'","`":"`","(":")","【":"】","「":"」","《":"》","“":"”","‘":"’"},nb=zt(e=>new Wt({props:{handleTextInput:(t,n,o,r)=>{const s=tb[r];if(!s||n===o)return!1;const c=t.state.selection;if(!(c instanceof je)||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(Xf).call(Kd.key);const i=t.state.tr.insertText(s,o).insertText(r,n);return i.setSelection(je.create(i.doc,n+1,o+1)),t.dispatch(i.scrollIntoView()),!0}}}));function ja(e){const t=e.selection;if(!(t instanceof Ce)||!t.node.isBlock)return null;const n=t.node,o=e.tr;if(n.type.name==="code_block")return o.setSelection(je.create(o.doc,t.to-1));if(n.type.name==="table"){const c=Vo.near(o.doc.resolve(t.from+1),1);return!(c instanceof je)||c.from>=t.to?null:o.setSelection(je.create(o.doc,c.$from.end()))}if(!ua(n)&&!n.isLeaf){const c=Vo.near(o.doc.resolve(t.to-1),-1);if(c instanceof je&&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(je.create(o.doc,t.to+1)))}const ob=zt(()=>new Wt({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=ja(e.state);return o&&e.dispatch(o.scrollIntoView()),!1},compositionstart:e=>{if(!e.editable)return!1;const t=ja(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=ja(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}}}})),cl=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),rb=[Ry,ob,nb,zt(()=>Bo({Enter:Vy,"Shift-Enter":sr(Lu,eb,Du),"Mod-Enter":qy,Backspace:Jy,"Mod-Backspace":Zy,Delete:sr(lc(1),tl,nl,ol),...cl?{"Ctrl-d":sr(lc(1),tl,nl,ol)}:{},ArrowUp:sr(Fs("up"),rl("up")),ArrowDown:sr(sl("down"),Fs("down"),rl("down")),ArrowLeft:Fs("left"),ArrowRight:sr(sl("right"),Fs("right")),...cl?{"Meta-ArrowUp":al("up"),"Meta-ArrowDown":al("down")}:{}}))].flat();En({"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 sb(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}:{}},h=a.type.createAndFill(m,c);if(h){const E=o?i:i+a.nodeSize;return{at:E,node:h,caret:E+3}}}const l=o?n:n+t.nodeSize;return{at:l,node:c,caret:l+2}}function Or(e){const t=e.offsetWidth;if(t<=0)return zn(e);const n=zn(e),o=e.getBoundingClientRect().width/t;return Math.abs(o-n)<.01?n:o}function il(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 Fr(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"||il(r))&&(n=o)}return n?t(n):{x:0,y:0}}for(let n=e.parentElement;n;n=n.parentElement)if(il(getComputedStyle(n)))return t(n);return{x:0,y:0}}const Ra=(e,t)=>{if(!t)return!1;const n=t.type.name;return!(n==="amadeusColumnRow"||n==="amadeusColumnCell"||Zf(o=>o.type.name==="table"||o.type.name==="blockquote")(e))};function os(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),Ra(o,r)||c(!0)};if(c(!Ra(o,r)),!r||!Ra(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 h=e.state.doc.nodeAt(i);if(h)return{node:h,pos:i,el:a}}}}return{node:r,pos:o.pos,el:s}}catch{return null}}function ll(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(Ce.isSelectable(o)&&!(o.type.name==="paragraph"&&n>1))return t.before(n)}return null}function ab(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 cb(e){let t=null,n=null;const o=new Ln("amx-block-selection-mode");let r=null,s=null;const c=g=>(s&&s.isConnected||(s=document.createElement("div"),s.className="unified-drop-vline",s.style.display="none",(g.dom.parentElement??document.body).appendChild(s)),s),i=(g,A,O)=>{const I=c(g),V=Or(g.dom),G=Fr(I),le=A.getBoundingClientRect(),J=(O==="left"?le.left-6:le.right+3)-G.x;I.style.display="block",I.style.height=`${le.height/V}px`,I.style.transform=`translate(${Math.round(J/V)}px, ${Math.round((le.top-G.y)/V)}px)`},a=()=>{s&&(s.style.display="none")},l=28,m=g=>/Mac/i.test(navigator.platform)?g.altKey:g.ctrlKey,h=g=>{const A=g.state.selection;if(!(A instanceof je)||A.empty||A.$from.sameParent(A.$to))return null;const O=G=>{let le=G.depth;for(;le>=1&&!["doc","amadeusColumnCell"].includes(G.node(le-1).type.name);)le--;return le},I=O(A.$from),V=O(A.$to);return I<1||V<1||A.$from.node(I-1)!==A.$to.node(V-1)?null:{from:A.$from.before(I),to:A.$to.after(V)}},E=(g,A,O)=>{if(O.type.name!=="paragraph")return null;const I=g.state.doc.resolve(A),V=I.parent;if(!["doc","amadeusColumnCell"].includes(V.type.name))return null;const G=Number(O.attrs.indent??0),le=I.index();let J=A+O.nodeSize,ne=0;for(let W=le+1;W<V.childCount;W++){const Ae=V.child(W);if(Ae.type.name!=="paragraph"||Number(Ae.attrs.indent??0)<=G)break;J+=Ae.nodeSize,ne++}return ne?{from:A,to:J}:null};let R=null;const k=(g,A,O,I,V)=>{Hr(g,A,{from:O.from,to:O.to,newStart:I,copy:V}),es(g,A,{from:O.from,to:O.to,newStart:I}),R===O.from&&A.doc.nodeAt(I)?.type.name==="heading"&&(A.setSelection(Ce.create(A.doc,I)),R=null)},v=(g,A)=>{const{state:O}=g,I=O.doc.content.size,V=h(g);if(V){if(!A&&V.to===I)return!0;let W=O.doc.slice(V.from,V.to).content;if(A){const _e=ns(O.doc,W);W=_e.content,_e.minted.length&&e.onCardsMinted?.(_e.minted)}let Ae=O.tr;A||(Ae=Ae.delete(V.from,V.to));const Pe=Ae.mapping.map(I);return Ae=Ae.insert(Pe,W),k(O,Ae,V,Pe,A),Ae.setMeta("amxColumns",!0),g.dispatch(Ae.scrollIntoView()),!0}const G=O.selection;if(!(G instanceof Ce))return!1;if(!A&&G.to===I)return!0;const le=G.node,J=le.type.name==="list_item"?G.$from.parent.type.create(G.$from.parent.attrs,le):le;let ne=O.tr;return A||(ne=ne.delete(G.from,G.to)),ne=ne.insert(ne.mapping.map(I),J),ne.setMeta("amxColumns",!0),g.dispatch(ne.scrollIntoView()),!0},j=(g,A,O)=>{const I=h(g);if(!I)return!1;const V=fe(g,A.clientY);if(!V)return!1;const G=V.el.getBoundingClientRect(),le=A.clientY>G.top+G.height/2?V.pos+V.node.nodeSize:V.pos;if(le>=I.from&&le<=I.to)return!0;let J=g.state.doc.slice(I.from,I.to).content;if(O){const Ae=ns(g.state.doc,J);J=Ae.content,Ae.minted.length&&e.onCardsMinted?.(Ae.minted)}ht(g,le);let ne=g.state.tr;O||(ne=ne.delete(I.from,I.to));const W=ne.mapping.map(le);return ne=ne.insert(W,J),k(g.state,ne,I,W,O),ne.setMeta("amxColumns",!0),g.dispatch(ne.scrollIntoView()),!0},P=(g,A,O)=>{const{state:I}=g,V=I.selection;if(!(V instanceof Ce))return!1;const G=I.doc.nodeAt(A);if(!G||G.type.name!=="list_item"||A>=V.from&&A<V.to)return!1;const le=I.schema.nodes.list_item,J=I.schema.nodes.bullet_list;if(!le||!J)return!1;const ne=V.node;if(ne.type.name==="amadeusColumnRow"||ne.type.name==="amadeusColumnCell")return!1;const W=ne.type.name==="list_item"?ne:le.createAndFill(null,ne);if(!W)return!1;const Ae=G.child(G.childCount-1),Pe=G.childCount>1&&/_list$/.test(Ae.type.name);let _e=I.tr;O||(_e=_e.delete(V.from,V.to));const Be=_e.mapping.map(A),Ve=_e.doc.nodeAt(Be);if(!Ve||Ve.type.name!=="list_item")return!1;const Xe=Pe?Be+Ve.nodeSize-2:Be+Ve.nodeSize-1;return _e=_e.insert(Xe,Pe?W:(Ae.type.name.endsWith("_list")?Ae.type:J).create(null,W)),_e.setMeta("amxColumns",!0),g.dispatch(_e.scrollIntoView()),!0},q=g=>!!g.dom.closest(".unified-body")?.classList.contains("amx-canvas"),X=(g,A,O,I)=>{let V=O;for(let G=0;G<A.childCount;G++){const le=A.child(G),J=g.nodeDOM(V),ne=J instanceof HTMLElement?J.getBoundingClientRect():null;if(ne&&I.clientY<=ne.bottom)return I.clientY>ne.top+ne.height/2?V+le.nodeSize:V;V+=le.nodeSize}return V},_=(g,A)=>{const O=g.state.doc,I=g.state.schema.nodes.amadeusCanvasCard;let V=0;for(let G=0;G<O.childCount;G++){const le=O.child(G);if(le.type===I)return V;const J=g.nodeDOM(V),ne=J instanceof HTMLElement?J.getBoundingClientRect():null;if(ne&&A.clientY<=ne.bottom)return A.clientY>ne.top+ne.height/2?V+le.nodeSize:V;V+=le.nodeSize}return V},Z=(g,A,O)=>{const I=g.state.selection;if(!(I instanceof Ce))return!1;const V=g.state.schema.nodes.amadeusCanvasCard;if(!V)return!1;const G=A.target;if(!G||!g.dom.contains(G))return!1;if(I.node.type===V)return!0;const le=G.closest?.(".amx-ucard");let J;if(le){let W;try{W=g.posAtDOM(le,0)-1}catch{return!1}const Ae=g.state.doc.nodeAt(W);if(Ae?.type!==V)return!1;J=X(g,Ae,W+1,A)}else J=_(g,A);if(J>=I.from&&J<=I.to)return!0;let ne=g.state.tr;return O||(ne=ne.delete(I.from,I.to)),ne=ne.insert(ne.mapping.map(J),I.node),ne.setMeta("amxColumns",!0),g.dispatch(ne.scrollIntoView()),!0},ze=g=>{const A=g.state.schema.nodes.amadeusCanvasCard,O=[];return A&&g.state.doc.forEach((I,V,G)=>{I.type===A&&O.push({anchor:String(I.attrs.anchor),idx:G,pos:V,size:I.nodeSize})}),O},Ke=(g,A)=>{const O=g.state.doc,I=g.state.schema.nodes.amadeusCanvasCard;if(!I)return null;const V=e.canvasTree?.()??{},G=ze(g),le=new Map;for(let Be=0;Be<G.length;){const Ve=na(G,Be,V);le.set(Be,Ve),Be=Ve}const J=Be=>{const Ve=g.nodeDOM(Be);return Ve instanceof HTMLElement?Ve:null},ne=[];let W=0,Ae=0,Pe=-1;for(let Be=0;Be<O.childCount;Be++){const Ve=O.child(Be);if(W<Pe){Ve.type===I&&Ae++,W+=Ve.nodeSize;continue}if(Ve.type===I){const Xe=le.get(Ae);if(Xe!=null){const We=G[Xe-1];ne.push({from:W,to:We.pos+We.size,firstEl:J(W),lastEl:J(We.pos)})}Ae++}else{let Xe=W+Ve.nodeSize,We;if(Ve.type.name==="heading"&&vr(g,W)==="folded"){const Ze=Gr(g.state,W);Ze!=null&&(Xe=Ze,Pe=Ze,We=W)}ne.push({from:W,to:Xe,firstEl:J(W),lastEl:J(W),foldPos:We})}W+=Ve.nodeSize}let _e=null;for(let Be=0;Be<ne.length;Be++){const Ve=ne[Be];if(!Ve.firstEl||!Ve.lastEl)continue;const Xe=Ve.firstEl.getBoundingClientRect().top,We=Ve.lastEl.getBoundingClientRect().bottom;if(_e={at:Ve.to,lineEl:Ve.lastEl,edge:"bottom",expandFold:Ve.foldPos},A.clientY>We)continue;const Ze=Be>0?ne[Be-1]:null;return A.clientY<=(Xe+We)/2?{at:Ve.from,lineEl:Ve.firstEl,edge:"top",expandFold:Ze&&Ze.foldPos!=null&&Ze.to===Ve.from?Ze.foldPos:void 0}:_e}return _e},p=(g,A)=>{const O=g.state.selection,I=g.state.schema.nodes.amadeusCanvasCard;if(!I||!(O instanceof Ce)||O.node.type!==I)return null;const V=Ke(g,A);if(!V)return null;const G=e.canvasTree?.()??{},le=ze(g),J=le.findIndex(Ae=>Ae.pos===O.from);if(J<0)return null;const ne=le[na(le,J,G)-1],W={from:O.from,to:ne.pos+ne.size};return{drop:V,range:W,self:V.at>=W.from&&V.at<=W.to}},xe=(g,A,O)=>{const I=g.state.selection,V=g.state.schema.nodes.amadeusCanvasCard;if(!V||!(I instanceof Ce)||I.node.type!==V)return!1;const G=p(g,A);if(!G||G.self)return!0;let le=g.state.doc.slice(G.range.from,G.range.to).content;if(O){const ne=ns(g.state.doc,le);le=ne.content,ne.minted.length&&e.onCardsMinted?.(ne.minted)}G.drop.expandFold!=null&&vr(g,G.drop.expandFold)==="folded"&&Is(g,G.drop.expandFold);let J=g.state.tr;if(O||(J=J.delete(G.range.from,G.range.to)),J=J.insert(J.mapping.map(G.drop.at),le),J.setMeta("amxColumns",!0),g.dispatch(J.scrollIntoView()),!O){const ne=String(I.node.attrs.anchor),Ae=(e.canvasTree?.()??{})[ne];typeof Ae=="string"&&ze(g).some(Pe=>Pe.anchor===Ae)&&e.onCardDetach?.([ne])}return!0};let Qe=null,de=null,ce=null,se=null,ae=!1,Re=!1,Me=null;const rt=g=>(Me&&Me.isConnected||(Me=document.createElement("div"),Me.className="unified-drop-line",Me.style.display="none",Me.style.animation="none",(g.dom.parentElement??document.body).appendChild(Me)),Me),Je=(g,A,O=0,I="bottom")=>{const V=rt(g),G=Or(g.dom),le=Fr(V),J=A.getBoundingClientRect(),ne=I==="top"?J.top-6:J.bottom+6;V.style.display="block",V.style.width=`${Math.max(0,J.width-O)/G}px`,V.style.transform=`translate(${Math.round((J.left+O-le.x)/G)}px, ${Math.round((ne-le.y)/G)}px)`},ee=()=>{Me&&(Me.style.display="none")},ge=(g,A)=>{const O=g.state.doc.resolve(A);if(O.depth===0)return g.state.doc.nodeAt(A)?.type.name!=="amadeusCanvasCard";for(let I=O.depth;I>=1;I--)if(O.node(I).type.name==="amadeusColumnRow")return I===1;return!1},Se=g=>g instanceof HTMLElement&&g.getClientRects().length>0,C=(g,A)=>{if(q(g))return null;const O=g.state.selection,I=O instanceof Ce?{from:O.from,to:O.to}:h(g);if(!I)return null;const V=A.target instanceof Element?A.target.closest("blockquote"):null;if(!(V instanceof HTMLElement)||!g.dom.contains(V))return null;let G;try{G=g.posAtDOM(V,0)-1}catch{return null}const le=g.state.doc.nodeAt(G);if(le?.type.name!=="blockquote"||g.nodeDOM(G)!==V)return null;const J=g.state.doc.slice(I.from,I.to).content;let ne=!1;if(J.descendants(Be=>{["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell"].includes(Be.type.name)&&(ne=!0)}),ne)return null;const W=!!le.firstChild?.isTextblock&&/^\[![\w-]+\]/.test(le.firstChild.textContent),Ae=g.nodeDOM(G+1);if(W&&Se(Ae)){const Be=Ae.getBoundingClientRect();if(A.clientY<Be.top+Be.height/2)return null}let Pe=null;if(le.forEach((Be,Ve)=>{const Xe=G+1+Ve,We=g.nodeDOM(Xe);if(!Se(We))return;const Ze=We.getBoundingClientRect(),Zt=A.clientY<Ze.top+Ze.height/2?"top":"bottom",xt=Math.abs(A.clientY-(Zt==="top"?Ze.top:Ze.bottom));(!Pe||xt<Pe.distance)&&(Pe={at:Zt==="top"?Xe:Xe+Be.nodeSize,lineEl:We,edge:Zt,distance:xt})}),!Pe)return null;const _e=Pe;return{..._e,self:_e.at>=I.from&&_e.at<=I.to}},Y=(g,A,O)=>{const I=C(g,A);if(!I)return!1;if(I.self)return!0;const{state:V}=g,G=V.selection,le=G instanceof Ce?{from:G.from,to:G.to}:h(g);if(!le)return!1;const J=G instanceof Ce&&G.node.type.name==="list_item"?zo.from(G.$from.parent.type.create(G.$from.parent.attrs,G.node)):V.doc.slice(le.from,le.to).content,ne=O?V.tr:V.tr.delete(le.from,le.to),W=ne.mapping.map(I.at),Ae=ne.doc.resolve(W);return Ae.parent.type.name!=="blockquote"||!Ae.parent.canReplace(Ae.index(),Ae.index(),J)?!1:(ne.insert(W,J),k(V,ne,le,W,O),Zs(ne,W,W+J.size),ne.setSelection(J.childCount===1&&Ce.isSelectable(J.firstChild)?Ce.create(ne.doc,W):je.between(ne.doc.resolve(W),ne.doc.resolve(W+J.size))),ne.setMeta("amxColumns",!0).setMeta("uiEvent","drop"),g.dispatch(ne.scrollIntoView()),g.focus(),!0)},fe=(g,A)=>{const O=g.state.doc;let I=null,V=1/0;for(let G=0,le=0;G<O.childCount;le+=O.child(G).nodeSize,G++){const J=g.nodeDOM(le);if(!Se(J))continue;const ne=J.getBoundingClientRect(),W=A<ne.top?ne.top-A:A>ne.bottom?A-ne.bottom:0;if(W===0)return{pos:le,node:O.child(G),el:J};W<V&&(V=W,I={pos:le,node:O.child(G),el:J})}return I},ye=(g,A)=>{const O=g.state.selection,I=m(A),V=G=>!I&&O instanceof Ce&&G>=O.from&&G<=O.to;for(const G of g.dom.querySelectorAll(":scope > .amx-ucolrow")){const le=G.getBoundingClientRect();if(!(A.clientY<le.top||A.clientY>le.bottom||A.clientX<le.left||A.clientX>le.right)){for(const J of Array.from(G.children)){if(!Se(J)||!("amxColcell"in J.dataset))continue;const ne=J.getBoundingClientRect();if(!(A.clientX<ne.left||A.clientX>ne.right))try{const W=g.posAtDOM(J,0)-1,Ae=g.state.doc.nodeAt(W);if(Ae?.type.name!=="amadeusColumnCell")return null;let Pe=W+1,_e=null;for(let Be=0;Be<Ae.childCount;Be++){const Ve=Ae.child(Be),Xe=g.nodeDOM(Pe);if(Se(Xe)){const We=Xe.getBoundingClientRect();if(A.clientY<=We.bottom){if(A.clientY>=We.top&&(!Ve.isTextblock&&!Ve.isAtom||A.clientX<=We.left+l||A.clientX>=We.right-l))return null;const Ze=A.clientY<=We.top+We.height/2,Zt=Ze?Pe:Pe+Ve.nodeSize;return{cellEl:J,lineEl:Xe,pos:Pe,edge:Ze?"top":"bottom",tail:!1,self:V(Zt)}}_e=Xe}Pe+=Ve.nodeSize}return _e?{cellEl:J,lineEl:_e,pos:W,edge:"bottom",tail:!0,self:V(W+Ae.nodeSize-1)}:null}catch{return null}}return null}}return null},Ye=(g,A)=>{if(!A.cellEl.isConnected||!A.lineEl.isConnected)return null;try{if(A.tail){const V=g.posAtDOM(A.cellEl,0)-1,G=g.state.doc.nodeAt(V);return G?.type.name==="amadeusColumnCell"?V+G.nodeSize-1:null}const O=g.state.doc.nodeAt(A.pos);if(!O||g.nodeDOM(A.pos)!==A.lineEl)return null;const I=A.edge==="top"?A.pos:A.pos+O.nodeSize;return g.state.doc.resolve(I).parent.type.name==="amadeusColumnCell"?I:null}catch{return null}},Fe=(g,A)=>{try{const O=g.state.doc.resolve(A),I=O.parent;let V=O.start();for(let G=0;G<I.childCount&&V<A;G++){const le=I.child(G);if(le.type.name==="heading"&&vr(g,V)==="folded"){const J=Gr(g.state,V);if(J!=null&&A>V&&A<=J)return V}V+=le.nodeSize}}catch{}return null},ht=(g,A)=>{for(let O=Fe(g,A),I=-1;O!=null&&O!==I;I=O,O=Fe(g,A))Is(g,O)};let ct=null;const Kt=()=>{ct&&(ct.style.display="none")};let jt=!1,Et=!1;const Gt=()=>{Et||(Et=!0,jt=!1,queueMicrotask(()=>{Et=!1,jt||Kt()}))},et=zt(()=>new Wt({key:new Ln("UNIFIED_BLOCK_HANDLE"),view:g=>{t=g,Ai.add(g);const A=g.dom.parentElement??document.body,O=A.closest(".unified-body")??A,I=T=>{for(const F of O.querySelectorAll(".amx-ucard.amx-droptarget"))F.classList.remove("amx-droptarget");T?.classList.add("amx-droptarget")},V=document.createElement("div");V.className="unified-gutter",V.dataset.show="false";const G=()=>{V.dataset.show="false",n=null},le=T=>{if(!g.editable)return;n=T,xt(T),tt.style.display=Yn(T)?"":"none";const F=Or(g.dom),he=Fr(V),ve=Ni(T.el),$e=ve.getBoundingClientRect(),te=(T.el.tagName==="LI"&&/^(UL|OL)$/.test(T.el.parentElement?.tagName??"")?T.el.parentElement:null)?.getBoundingClientRect().left??$e.left,nt=getComputedStyle(ve),st=Number.parseFloat(nt.lineHeight)||24,mt=(Number.parseFloat(nt.paddingTop)||0)+Math.max(0,(st-24)/2),bt=$e.height/F,Rt=Math.max(24,bt-16),Nt=Rt>24?Rt/2-4-mt:0;V.dataset.show="true",V.style.setProperty("--amx-block-h",`${bt}px`),V.style.setProperty("--amx-block-grow-y",`${Nt}px`);const an=V.offsetWidth||52;V.style.top=`${($e.top-he.y)/F+mt}px`;let Pt=(te-he.x)/F-an-8;Vr()&&(Pt=Math.max(Pt,(2-he.x)/F-J.offsetLeft)),V.style.left=`${Pt}px`},J=document.createElement("button");J.type="button",J.className="drag-handle",J.textContent="⠿",J.draggable=!0,J.title=Te("blocklayer.dragHandle"),J.setAttribute("aria-label",J.title),J.addEventListener("click",T=>{T.stopPropagation();const F=J.getBoundingClientRect();if(T.detail===0&&t&&n){const he=t.state.selection;he instanceof Ce&&he.from<=n.pos&&n.pos+n.node.nodeSize<=he.to||ne(t,n)}e.onMenu({x:F.left,y:F.bottom+4,keyboard:T.detail===0}),Vr()||t?.focus()}),V.addEventListener("mousedown",()=>{t&&n&&ne(t,n)});const ne=(T,F)=>{const he=T.state.selection,ve=F.pos+1,$e=F.pos+F.node.nodeSize-1;if(he instanceof je&&!he.empty&&!he.$from.sameParent(he.$to)&&he.from<=ve&&he.to>=$e){T.focus();return}const Ne=E(T,F.pos,F.node);if(Ne){const te=T.state.doc;T.dispatch(T.state.tr.setSelection(je.between(te.resolve(Ne.from+1),te.resolve(Ne.to-1))).setMeta(o,!0)),T.focus();return}Ce.isSelectable(F.node)&&(T.dispatch(T.state.tr.setSelection(Ce.create(T.state.doc,F.pos))),T.focus())};let W=null;const Ae=()=>{const T=t,F=n;if(!T||!F)return;(!W||!W.isConnected)&&(W=document.createElement("div"),W.className="unified-press-rect",(T.dom.parentElement??document.body).appendChild(W));const he=Or(T.dom),ve=Fr(W),$e=Ni(F.el).getBoundingClientRect(),Ne=h(T);let te={left:$e.left-ve.x,top:$e.top-ve.y,right:$e.right-ve.x,bottom:$e.bottom-ve.y};if(Ne)for(const nt of Array.from(T.dom.children)){if(!nt.classList.contains("amx-block-selected"))continue;const st=nt.getBoundingClientRect();te={left:Math.min(te.left,st.left-ve.x),top:Math.min(te.top,st.top-ve.y),right:Math.max(te.right,st.right-ve.x),bottom:Math.max(te.bottom,st.bottom-ve.y)}}Object.assign(W.style,{display:"block",transform:`translate(${Math.round((te.left-4)/he)}px, ${Math.round((te.top-4)/he)}px)`,width:`${(te.right-te.left+8)/he}px`,height:`${(te.bottom-te.top+8)/he}px`})},Pe=()=>{W&&(W.style.display="none")};V.addEventListener("mousedown",Ae),window.addEventListener("mouseup",Pe);const _e=(T,F,he)=>{T.dom.dataset.dragging="true";let ve=T.state.selection;if(R=null,ve instanceof Ce&&vr(T,ve.from)==="folded"){const Ne=ve.from,te=Gr(T.state,Ne),nt=T.state.doc;if(te!=null){T.dispatch(T.state.tr.setSelection(je.between(nt.resolve(Ne+1),nt.resolve(te-1))).setMeta(o,!0));const st=h(T);st&&st.from===Ne&&st.to===te?R=Ne:T.dispatch(T.state.tr.setSelection(Ce.create(T.state.doc,Ne)))}R==null&&Is(T,Ne),ve=T.state.selection}ve instanceof Ce&&Ps(T,ve.from)==="folded"&&Sa(T,ve.from);const $e=ve instanceof je&&!ve.empty&&!ve.$from.sameParent(ve.$to);if(F.dataTransfer&&(ve instanceof Ce||$e)){const Ne=ve.content();F.dataTransfer.effectAllowed="copyMove";const{dom:te,text:nt}=T.serializeForClipboard(Ne);F.dataTransfer.clearData(),F.dataTransfer.setData("text/html",te.innerHTML),F.dataTransfer.setData("text/plain",nt),he&&F.dataTransfer.setDragImage(he,0,0),T.dragging={slice:Ne,move:!0}}};V.addEventListener("dragstart",T=>{t&&_e(t,T,n?.el??null)});const Be=T=>{const F=t;if(!F||!(T.target instanceof Node)||!F.dom.contains(T.target)||!T.target.closest?.(".wiki-inline-img-wrap"))return;const he=Tm(T.target);let ve=-1;try{he&&(ve=F.posAtDOM(he,0)-1)}catch{}const $e=he?.querySelector(":scope > .wiki-inline-img-wrap")?.getBoundingClientRect(),Ne=$e?os(F,{x:$e.left+$e.width/2,y:$e.top+$e.height/2}):null;if(!he||!T.dataTransfer||F.nodeDOM(ve)!==he||!Ne||ve<Ne.pos||ve>=Ne.pos+Ne.node.nodeSize){T.preventDefault();return}T.stopPropagation(),ne(F,Ne),_e(F,T,null),T.target.addEventListener("dragend",Ve,{once:!0})};O.addEventListener("dragstart",Be,!0);const Ve=()=>{const T=t;if(T&&R!=null){const F=h(T);F&&F.from===R&&T.state.doc.nodeAt(R)?.type.name==="heading"&&T.dispatch(T.state.tr.setSelection(Ce.create(T.state.doc,R))),R=null}Pe(),I(null),r=null,ce=null,se=null,de=null,Re=!1,ae=!1,a(),ee(),Kt(),T&&(T.dom.dataset.dragging="false",T.dragging=null)};V.addEventListener("dragend",Ve);const Xe=document.createElement("button");Xe.type="button",Xe.className="block-add block-fold",Xe.textContent="▾",Xe.style.display="none";const We=T=>{const F=t;return F?Ps(F,T.pos)?T.pos:/_list$/.test(T.node.type.name)&&Ps(F,T.pos+1)?T.pos+1:null:null},Ze=T=>{const F=t;return F?vr(F,T.pos)?T.pos:!T.node.isTextblock&&T.node.childCount>0&&vr(F,T.pos+1)?T.pos+1:null:null},Zt=T=>!t||!T?null:Ze(T)!=null?"heading":We(T)!=null?"list":null,xt=T=>{const F=t,he=Zt(T),ve=T?We(T):null,$e=T?Ze(T):null,Ne=!F||!T||!he?null:he==="heading"?$e==null?null:vr(F,$e):ve==null?null:Ps(F,ve);Xe.style.display=Ne?"":"none",Xe.textContent=Ne==="folded"?"▸":"▾",Xe.title=he==="list"?Ne==="folded"?Te("blocklayer.expandChildren"):Te("blocklayer.foldChildren"):Ne==="folded"?Te("blocklayer.expandSection"):Te("blocklayer.foldSection"),Xe.setAttribute("aria-label",Xe.title),Xe.setAttribute("aria-expanded",String(Ne!=="folded"))};Xe.addEventListener("click",T=>{T.stopPropagation();const F=t,he=n;if(!F||!he)return;const ve=Zt(he)==="list"?We(he):null;if(ve!=null)Sa(F,ve);else{const $e=Ze(he);if($e==null)return;Is(F,$e)}xt(he)});const yt=document.createElement("button");yt.type="button",yt.className="block-add",yt.textContent="+",yt.title=Te("blocklayer.addBelow"),yt.setAttribute("aria-label",yt.title),yt.addEventListener("click",T=>{T.stopPropagation();const F=t,he=n;if(!F||!he)return;const ve=sb(F.state,he.node,he.pos,T.altKey);if(!ve)return;F.focus();let $e=F.state.tr.insert(ve.at,ve.node);$e=$e.setSelection(je.create($e.doc,ve.caret)).scrollIntoView(),Jd(F,ve.caret),F.dispatch($e),G()});const tt=document.createElement("button");tt.type="button",tt.className="card-grab",tt.textContent="❏",tt.draggable=!0,tt.title=Te("blocklayer.cardGrab"),tt.setAttribute("aria-label",tt.title),tt.style.display="none";const Yn=T=>{const F=t;if(!F||!T||T.node.type.name==="amadeusCanvasCard")return null;try{const he=F.state.doc.resolve(T.pos);for(let ve=he.depth;ve>=1;ve--){if(he.node(ve).type.name!=="amadeusCanvasCard")continue;const $e=he.before(ve),Ne=F.state.doc.nodeAt($e),te=F.nodeDOM($e);return Ne&&te instanceof HTMLElement?{node:Ne,pos:$e,el:te}:null}}catch{}return null};tt.addEventListener("mousedown",T=>{const F=t,he=Yn(n);!F||!he||(T.stopPropagation(),n=he,F.dispatch(F.state.tr.setSelection(Ce.create(F.state.doc,he.pos))),F.focus(),Ae())}),tt.addEventListener("click",T=>{if(T.stopPropagation(),!n)return;const F=tt.getBoundingClientRect();e.onMenu({x:F.left,y:F.bottom+4,keyboard:T.detail===0}),Vr()||t?.focus()}),V.append(tt,J,yt,Xe);let It=null,nn=null,Un=null;const $o=()=>{const T=[];for(const F of Array.from(g.dom.children))if(F.classList.contains("amx-ucolrow"))for(const he of Array.from(F.querySelectorAll(".amx-ucolcell")))T.push(...Array.from(he.children));else T.push(F);return T},Tr=(T,F,he)=>{const ve=T.getBoundingClientRect();if(F<ve.left||F>ve.right||he<ve.top||he>ve.bottom)return!1;if(T.matches("hr, table, pre, .amx-ucard"))return!0;const $e=te=>F>=te.left-2&&F<=te.right+2&&he>=te.top-2&&he<=te.bottom+2;for(const te of T.querySelectorAll(".unified-embed, .wiki-inline-img-wrap, .wikilink, img, video, iframe, canvas"))if($e(te.getBoundingClientRect()))return!0;const Ne=document.createTreeWalker(T,NodeFilter.SHOW_TEXT);for(let te=Ne.nextNode();te;te=Ne.nextNode()){if(!te.textContent?.length)continue;const nt=document.createRange();nt.selectNodeContents(te);const st=nt.getClientRects();if(!st.length)continue;const At=te.parentElement,mt=At?parseFloat(getComputedStyle(At).lineHeight)*zn(At):NaN;for(const bt of st){const Rt=Math.max(2,(mt-bt.height)/2||0);if(F>=bt.left-2&&he>=bt.top-Rt&&he<=bt.bottom+Rt)return!0}}return!1},Bn=T=>{if(window.removeEventListener("mouseup",Jo),T.button!==0||O.classList.contains("amx-canvas"))return;const F=T.target;if(!F||F.closest(".unified-gutter")||F.closest(".amx-embed")||F.closest("button, input, textarea, a")||!g.editable)return;if(T.pointerType==="touch")return In();const he=$o();if(he.some(Ne=>Tr(Ne,T.clientX,T.clientY)))return In();const ve=F.closest('li[data-item-type="task"]');if(ve&&T.clientX-ve.getBoundingClientRect().left<=2)return;if(he.some(Ne=>{const te=Ne.getBoundingClientRect();return T.clientX>=te.left&&T.clientX<=te.right&&T.clientY>=te.top&&T.clientY<=te.bottom})){Un={x:T.clientX,y:T.clientY},window.addEventListener("pointermove",Ro),window.addEventListener("pointerup",io,{once:!0});return}T.preventDefault(),mr(T.clientX,T.clientY)},mr=(T,F)=>{nn={x:T,y:F},It=document.createElement("div"),It.className="amx-marquee",document.body.appendChild(It),document.body.classList.add("amx-marquee-active"),window.addEventListener("pointermove",Lo),window.addEventListener("pointerup",Qo,{once:!0})},jo=()=>{Un=null,window.removeEventListener("pointermove",Ro),window.removeEventListener("pointerup",io)},In=()=>window.addEventListener("mouseup",Jo,{once:!0}),io=()=>{jo(),In()},Jo=()=>{g.isDestroyed||g.domObserver?.flush?.()},Ro=T=>{const F=Un;!F||Math.abs(T.clientX-F.x)<=4&&Math.abs(T.clientY-F.y)<=4||(jo(),mr(F.x,F.y),Qn=!0,window.addEventListener("dragstart",wn,!0),window.addEventListener("selectionchange",wn,!0),Lo(T))};let Qn=!1;const wn=T=>{T.type==="dragstart"?T.preventDefault():T.stopImmediatePropagation()},Zo=()=>{if(!Qn)return;Qn=!1,window.removeEventListener("dragstart",wn,!0);let T=!1;const F=()=>{if(T)return;T=!0,window.removeEventListener("mouseup",he,!0),clearTimeout(ve);const $e=t;$e&&!$e.isDestroyed&&$e.focus(),Qn||window.removeEventListener("selectionchange",wn,!0)},he=()=>{setTimeout(F,0)},ve=setTimeout(F,300);window.addEventListener("mouseup",he,{capture:!0,once:!0})},Lo=T=>{if(!It||!nn)return;const F=Math.min(nn.x,T.clientX),he=Math.min(nn.y,T.clientY),ve=Math.abs(T.clientX-nn.x),$e=Math.abs(T.clientY-nn.y),Ne=zn(It);Object.assign(It.style,{left:`${F/Ne}px`,top:`${he/Ne}px`,width:`${ve/Ne}px`,height:`${$e/Ne}px`});const te=[],nt=[];for(const Nt of $o()){const an=Nt.getBoundingClientRect();if(!(an.bottom<he||an.top>he+$e||an.right<F||an.left>F+ve))try{te.push(g.posAtDOM(Nt,0)),nt.push(Nt)}catch{}}if(!te.length)return;const st=g.state.doc;if(nt.length===1){const Nt=nt[0];try{const an=Array.prototype.indexOf.call(Nt.parentNode?.childNodes,Nt),Pt=g.posAtDOM(Nt.parentNode,an),Hn=st.nodeAt(Pt);if(Hn&&Ce.isSelectable(Hn)){const ko=Ce.create(st,Pt);ko.eq(g.state.selection)||g.dispatch(g.state.tr.setSelection(ko));return}}catch{}}const At=Math.min(...te),mt=nt[nt.length-1];if(!mt)return;let bt=At;try{const Nt=g.posAtDOM(mt,0),an=g.state.doc.nodeAt(Nt-1);bt=an?Nt+an.content.size:Nt}catch{}const Rt=je.between(st.resolve(Math.min(At,st.content.size)),st.resolve(Math.min(bt,st.content.size)));(!Rt.eq(g.state.selection)||!o.getState(g.state))&&g.dispatch(g.state.tr.setSelection(Rt).setMeta(o,!0))},Qo=T=>{window.removeEventListener("pointermove",Lo),Zo();const F=!!(T&&nn&&(Math.abs(T.clientX-nn.x)>4||Math.abs(T.clientY-nn.y)>4)),he=nn;if(It?.remove(),It=null,nn=null,document.body.classList.remove("amx-marquee-active"),F){g.focus();return}if(!he||!T)return;const ve=g.dom.getBoundingClientRect(),$e=Math.min(Math.max(T.clientX,ve.left+8),ve.right-8);let Ne=g.posAtCoords({left:$e,top:T.clientY});if(Ne&&!g.state.doc.resolve(Ne.pos).parent.isTextblock){let st=null,At=1/0;for(const mt of $o()){const bt=mt.getBoundingClientRect(),Rt=Math.hypot(Math.max(bt.left-T.clientX,0,T.clientX-bt.right),Math.max(bt.top-T.clientY,0,T.clientY-bt.bottom));Rt<At&&(At=Rt,st=bt)}st&&(Ne=g.posAtCoords({left:Math.min(Math.max(T.clientX,st.left+1),st.right-1),top:Math.min(Math.max(T.clientY,st.top+1),st.bottom-1)}))}if(!Ne)return;const te=g.state.doc.resolve(Ne.pos);if(!te.parent.isTextblock)return;const nt=T.clientX<ve.left+ve.width/2?te.start():te.end();g.dispatch(g.state.tr.setSelection(je.near(g.state.doc.resolve(nt)))),g.focus()};O.addEventListener("pointerdown",Bn),A.appendChild(V);let lo=0,qn=null;const hr=T=>{if(V.contains(T.target)){qn&&clearTimeout(qn),qn=null;return}const F=Date.now();if(F-lo<80){const{clientX:he,clientY:ve}=T;qn&&clearTimeout(qn),qn=setTimeout(()=>{qn=null,lo=Date.now(),yo(he,ve)},80);return}lo=F,yo(T.clientX,T.clientY)},yo=(T,F)=>{const he={clientX:T,clientY:F};if(g.dom.dataset.dragging==="true")return;let ve=os(g,{x:he.clientX,y:he.clientY});if(!ve){const $e=g.dom.getBoundingClientRect();if(he.clientY>=$e.top&&he.clientY<=$e.bottom&&(he.clientX<$e.left+8||he.clientX>$e.right-8)){const Ne=Math.min(Math.max(he.clientX,$e.left+8),$e.right-8);ve=os(g,{x:Ne,y:he.clientY})}}ve&&le(ve)};O.addEventListener("mousemove",hr,{passive:!0});const Do=T=>{const F=T.relatedTarget;F&&(V.contains(F)||O.contains(F))||G()};O.addEventListener("mouseleave",Do);const $r=()=>{g.dom.dataset.dragging!=="true"&&G()};g.dom.addEventListener("keydown",$r);const Io=T=>{const F=t;if(!F||!F.editable)return;const he=F.state.selection,ve=he instanceof Ce?{from:he.from,to:he.to}:o.getState(F.state)?h(F):null;let $e=!1;if(ve){const Ne=he instanceof Ce?F.nodeDOM(he.from):null,te=F.posAtCoords({left:T.clientX,top:T.clientY});$e=Ne instanceof Node&&T.target instanceof Node&&Ne.contains(T.target)||!!te&&te.pos>=ve.from&&te.pos<=ve.to}if(!$e){const Ne=T.target instanceof Element?T.target:null,te=Ne?.closest('[contenteditable="false"]'),nt=!!Ne&&(!!te&&te!==F.dom&&F.dom.contains(te)||/^(IMG|VIDEO|AUDIO|HR|CANVAS|IFRAME)$/.test(Ne.tagName)),st=F.state.selection.empty?Ne?.closest("td, th"):null;let At=null;if(st&&F.dom.contains(st)){const Rt=F.state.doc.resolve(F.posAtDOM(st,0));for(let Nt=Rt.depth;Nt>0;Nt--)if(Rt.node(Nt).type.spec.tableRole==="table"){At=Rt.before(Nt);break}}if(!nt&&At==null)return;const mt=At??os(F,{x:T.clientX,y:T.clientY})?.pos,bt=mt==null?null:F.state.doc.nodeAt(mt);if(mt==null||!bt||!Ce.isSelectable(bt))return;F.dispatch(F.state.tr.setSelection(Ce.create(F.state.doc,mt)))}T.preventDefault(),F.focus(),e.onMenu({x:T.clientX,y:T.clientY})};g.dom.addEventListener("contextmenu",Io),V.addEventListener("contextmenu",T=>{const F=t;!F||!F.editable||!n||(T.preventDefault(),Vr()||F.focus(),e.onMenu({x:T.clientX,y:T.clientY}))});const Xn=()=>{g.dom.dataset.dragging!=="true"&&G()};window.addEventListener("scroll",Xn,{capture:!0,passive:!0});const bo=T=>{if(g.dom.dataset.dragging!=="true")return;const F=ab(g.dom);if(!F)return;const he=F.getBoundingClientRect();T.clientY<he.top+56?F.scrollTop-=14:T.clientY>he.bottom-56&&(F.scrollTop+=14)};window.addEventListener("dragover",bo);const hn=T=>{const F=t,he=T.dataTransfer?Array.from(T.dataTransfer.types):[];if(he.includes("Files")||he.includes(Gf)&&F&&!q(F)){if(!F)return;const te=fe(F,T.clientY);if(!te)return;const nt=te.el.getBoundingClientRect();Qe={pos:te.pos,el:te.el,lower:T.clientY>nt.top+nt.height/2},Je(F,te.el);return}if(!F||F.dom.dataset.dragging!=="true")return;ae&&ee(),ae=!1;{const te=F.state.selection;if(!q(F)&&te instanceof Ce&&te.node.type===F.state.schema.nodes.amadeusCanvasCard){Re=!1,r=null,de=null,ce=null,se=null,a();const nt=p(F,T);nt&&!nt.self?(Je(F,nt.drop.lineEl,0,nt.drop.edge),T.preventDefault()):ee();return}}const ve=C(F,T);if(ve){ae=!0,r=null,de=null,ce=null,se=null,Re=!1,a(),Kt(),ve.self?ee():Je(F,ve.lineEl,0,ve.edge),T.preventDefault();return}if(Re=!1,se=null,!q(F)){const nt=F.state.selection instanceof Ce||!!h(F),st=F.dom.lastElementChild;if(nt&&Se(st)){const At=st.getBoundingClientRect(),mt=F.dom.getBoundingClientRect();if(T.clientY>At.bottom+2&&T.clientX>=mt.left&&T.clientX<=mt.right){Re=!0,r=null,de=null,ce=null,a(),Je(F,st),T.preventDefault();return}}}if(!(F.state.selection instanceof Ce))return;if(q(F)){I(T.target?.closest?.(".amx-ucard")),ce=null,ee(),T.preventDefault();return}const $e=ye(F,T);if($e){se={cellEl:$e.cellEl,lineEl:$e.lineEl,pos:$e.pos,edge:$e.edge,tail:$e.tail,self:$e.self},ce=null,r=null,de=null,a(),Kt(),$e.self?ee():Je(F,$e.lineEl,0,$e.edge),T.preventDefault();return}let Ne=null;for(const te of F.dom.querySelectorAll(":scope > .amx-ucolrow")){const nt=te.getBoundingClientRect();if(T.clientX<nt.left||T.clientX>nt.right||T.clientY<=nt.bottom+2)continue;const st=te.nextElementSibling;st&&T.clientY>=st.getBoundingClientRect().top-2||(Ne=te)}if(Ne)try{const te=F.posAtDOM(Ne,0)-1;if(F.state.doc.nodeAt(te)?.type.name==="amadeusColumnRow"){ce={rowEl:Ne},Je(F,Ne),T.preventDefault();return}}catch{}ce=null,ee()};O.addEventListener("dragover",hn,!0);const eo=T=>{const F=T.relatedTarget;F&&O.contains(F)||(ce=null,se=null,Qe=null,de=null,r=null,ae=!1,a(),ee(),Kt(),I(null))};O.addEventListener("dragleave",eo,!0);const $t=T=>{const F=t,he=r,ve=ce,$e=se,Ne=de,te=Qe,nt=Re,st=ae;if(r=null,ce=null,se=null,de=null,Qe=null,Re=!1,ae=!1,a(),ee(),Kt(),I(null),!F)return;if(te){try{const bt=F.nodeDOM(te.pos)===te.el?F.state.doc.nodeAt(te.pos):null;if(bt){ht(F,te.pos+bt.nodeSize);const Rt=F.state.doc;F.dispatch(F.state.tr.setSelection(bt.isAtom?Ce.create(Rt,te.pos):je.near(Rt.resolve(te.lower?te.pos+1+bt.content.size:te.pos+1),te.lower?-1:1)))}}catch{}return}const At=m(T);let mt=q(F)?Z(F,T,At):xe(F,T,At);if(!mt)if(nt)mt=v(F,At);else if(st)mt=Y(F,T,At);else if(h(F))mt=j(F,T,At);else if(Ne)mt=P(F,Ne.targetPos,At);else if(ve)try{ve.rowEl.isConnected&&(mt=jx(F,F.posAtDOM(ve.rowEl,0)-1,At))}catch{mt=!1}else if($e){const bt=Ye(F,$e);bt!=null&&($e.self||ht(F,bt),mt=Rx(F,bt,At))}else he&&(mt=$x(F,he.targetPos,he.side,At));mt&&(T.preventDefault(),T.stopPropagation(),F.dom.dataset.dragging="false",F.dragging=null)};O.addEventListener("drop",$t,!0);let Ut=null;const vo=T=>{const F=t,he=T.target;if(!F||!he||!he.classList?.contains("amx-ucolrow"))return;const ve=he,$e=[...ve.children].filter(Pt=>Pt instanceof HTMLElement&&"amxColcell"in Pt.dataset);let Ne=-1;for(let Pt=0;Pt<$e.length-1;Pt++)if(T.clientX>=$e[Pt].getBoundingClientRect().right-2&&T.clientX<=$e[Pt+1].getBoundingClientRect().left+2){Ne=Pt;break}if(Ne<0)return;T.preventDefault();const te=$e[Ne],nt=$e[Ne+1],st=te.getBoundingClientRect().left,At=nt.getBoundingClientRect().right-st,mt=(Number(te.dataset.width)||1)+(Number(nt.dataset.width)||1),bt=Pt=>Math.min(.85,Math.max(.15,(Pt.clientX-st)/At)),Rt=Pt=>{const Hn=bt(Pt);te.style.flexGrow=String(mt*Hn),nt.style.flexGrow=String(mt*(1-Hn))},Nt=()=>{window.removeEventListener("pointermove",Rt),window.removeEventListener("pointerup",an),window.removeEventListener("pointercancel",Nt),Ut=null},an=Pt=>{Nt();const Hn=bt(Pt),ko=f=>Math.round(f*1e4)/1e4;try{const f=F.posAtDOM(ve,0)-1,N=F.state.doc.nodeAt(f);if(!N||N.type.name!=="amadeusColumnRow")return;let $=f+1,H=F.state.tr;for(let K=0;K<N.childCount;K++){const B=N.child(K);K===Ne&&(H=H.setNodeMarkup($,void 0,{...B.attrs,width:ko(mt*Hn)})),K===Ne+1&&(H=H.setNodeMarkup($,void 0,{...B.attrs,width:ko(mt*(1-Hn))})),$+=B.nodeSize}H.setMeta("amxColumns",!0),F.dispatch(H)}catch{}};window.addEventListener("pointermove",Rt),window.addEventListener("pointerup",an),window.addEventListener("pointercancel",Nt),Ut=Nt};A.addEventListener("pointerdown",vo);const wo=_l(()=>{J.title=Te("blocklayer.dragHandle"),yt.title=Te("blocklayer.addBelow"),tt.title=Te("blocklayer.cardGrab");for(const T of[J,yt,tt])T.setAttribute("aria-label",T.title)});return{update:T=>{const F=n;if(!F)return;let he=!1;try{he=F.pos<=T.state.doc.content.size&&T.state.doc.nodeAt(F.pos)===F.node}catch{}he||G()},destroy:()=>{window.removeEventListener("mouseup",Pe),W?.remove(),W=null,qn&&clearTimeout(qn),Qo(),O.removeEventListener("pointerdown",Bn),O.removeEventListener("mousemove",hr),g.dom.removeEventListener("keydown",$r),g.dom.removeEventListener("contextmenu",Io),O.removeEventListener("dragover",hn,!0),O.removeEventListener("dragleave",eo,!0),O.removeEventListener("drop",$t,!0),O.removeEventListener("dragstart",Be,!0),Ai.delete(g),O.removeEventListener("mouseleave",Do),A.removeEventListener("pointerdown",vo),wo(),Ut?.(),window.removeEventListener("scroll",Xn,{capture:!0}),window.removeEventListener("dragover",bo),V.remove(),s?.remove(),s=null,Me?.remove(),Me=null,ct?.remove(),ct=null,r=null,ce=null,se=null,ae=!1,n=null,t===g&&(t=null)}}}})),un=zt(()=>{const g=O=>{if(ct&&ct.isConnected)return ct;const I=document.createElement("div");return I.className="unified-drop-line",I.style.display="none",I.style.animation="none",(O.dom.parentElement??document.body).appendChild(I),ct=I,I};return lx({onDrag:({view:O,event:I,pos:V})=>{if(Gt(),(I.dataTransfer?Array.from(I.dataTransfer.types):[]).includes("Files"))return!1;if(q(O))return a(),!1;if(!O.dragging||!(O.state.selection instanceof Ce)||O.state.selection.node.type===O.state.schema.nodes.amadeusCanvasCard)return!1;if(ce||Re||se||ae)return r=null,de=null,a(),!1;const le=O.state.selection,J=os(O,{x:I.clientX,y:I.clientY});if(J&&J.node.type.name==="list_item"&&!(J.pos>=le.from&&J.pos<le.to)){const W=J.el.getBoundingClientRect();if(I.clientX>W.left+24&&I.clientY>W.top+W.height/2)return de={targetPos:J.pos,el:J.el},r=null,a(),Je(O,J.el,24),!1}if(de=null,J&&!(J.pos>=le.from&&J.pos<le.to)&&ge(O,J.pos)){const W=J.el.getBoundingClientRect(),Ae=I.clientX<=W.left+l?"left":I.clientX>=W.right-l?"right":null;if(Ae)return r={targetPos:J.pos,side:Ae},i(O,J.el,Ae),!1}r=null,a();const ne=O.state.doc.resolve(V);if(ne.parent.type.name==="amadeusColumnRow")return!1;for(let W=ne.depth;W>=1;W--){if(ne.node(W).type.name!=="amadeusColumnCell")continue;const Ae=O.nodeDOM(ne.before(W));if(Ae instanceof HTMLElement){const Pe=Ae.getBoundingClientRect();if(I.clientX<Pe.left||I.clientX>Pe.right)return!1}break}return!0},onShow:({view:O,line:I})=>{jt=!0;const V=g(O),G=Or(O.dom),le=Fr(V),J=(I.p1.x-le.x)/G,ne=(I.p2.x-le.x)/G,W=(I.p1.y-le.y)/G;V.style.display="block",V.style.width=`${Math.max(0,ne-J)}px`,V.style.transform=`translate(${Math.round(J)}px, ${Math.round(W-1.5)}px)`},onHide:Kt})}),dt=zt(()=>new Wt({key:new Ln("UNIFIED_DROP_GUARD"),props:{handleDrop:g=>g.dom.dataset.dragging==="true"&&!!g.dragging}})),pt=zt(()=>{let g=null,A=null;const O=()=>{g&&(g.style.display="none")};return new Wt({key:new Ln("AMX_GAP_INSERT"),view:I=>{const V=()=>(g&&g.isConnected||(g=document.createElement("div"),g.className="amx-gap-insert",g.innerHTML="<span>+</span>",g.addEventListener("mousedown",J=>{J.preventDefault(),J.stopPropagation()}),g.addEventListener("click",J=>{if(J.preventDefault(),J.stopPropagation(),!A)return;let ne=-1;I.state.doc.forEach((Pe,_e)=>{ne<0&&Pe.type.name==="amadeusCanvasCard"&&String(Pe.attrs.anchor)===A&&(ne=_e)});const W=I.state.schema.nodes.paragraph;if(ne<0||!W){O();return}let Ae=I.state.tr.insert(ne,W.create());Ae=Ae.setSelection(je.create(Ae.doc,ne+1)).scrollIntoView(),I.dispatch(Ae),I.focus(),O()}),(I.dom.parentElement??document.body).appendChild(g)),g),G=J=>{if(q(I)||I.dragging){O();return}const ne=I.state.schema.nodes.amadeusCanvasCard;if(!ne){O();return}const W=I.state.doc;let Ae=0,Pe=null,_e=null;for(let Ze=0;Ze<W.childCount&&!_e;Ze++){const Zt=W.child(Ze);if(Zt.type===ne){const xt=I.nodeDOM(Ae);if(xt instanceof HTMLElement){if(xt.classList.contains("amx-card-f0")&&!xt.classList.contains("amx-card-f0-top")){Pe=xt,Ae+=Zt.nodeSize;continue}if(Pe){const yt=Pe.getBoundingClientRect(),tt=xt.getBoundingClientRect();J.clientY>=yt.bottom-3&&J.clientY<=tt.top+3&&J.clientX>=Math.min(yt.left,tt.left)&&J.clientX<=Math.max(yt.right,tt.right)&&(_e={top:yt.bottom,bottom:tt.top,left:Math.min(yt.left,tt.left),right:Math.max(yt.right,tt.right),anchor:String(Zt.attrs.anchor)})}Pe=xt}else Pe=null}else Pe=null;Ae+=Zt.nodeSize}if(!_e){O();return}const Be=V(),Ve=Or(I.dom),Xe=Fr(Be),We=(_e.top+_e.bottom)/2;Be.style.display="flex",Be.style.width=`${(_e.right-_e.left)/Ve}px`,Be.style.transform=`translate(${Math.round((_e.left-Xe.x)/Ve)}px, ${Math.round((We-Xe.y)/Ve-9)}px)`,A=_e.anchor},le=I.dom.parentElement??I.dom;return le.addEventListener("mousemove",G),le.addEventListener("mouseleave",O),{update:(J,ne)=>{J.state.doc.eq(ne.doc)||O()},destroy:()=>{le.removeEventListener("mousemove",G),le.removeEventListener("mouseleave",O),g?.remove(),g=null}}}})}),_t={listFoldedAt:(g,A)=>yc(g,A),unfoldList:(g,A)=>Sa(g,A)},dn=zt(()=>Bo({Tab:(g,A,O)=>xa(g,A,O,_t),"Shift-Tab":(g,A)=>ya(g,A)})),Jt=zt(()=>new Wt({props:{decorations:g=>{const A=g.selection;if(!A.empty)return null;const O=A.$from,I=O.parent;if(!I.isTextblock||I.content.size>0)return null;for(let G=O.depth;G>=1;G--)if(O.node(G).type.name==="blockquote")return null;const V=I.type.name==="paragraph"?Te("blocklayer.phParagraph"):I.type.name==="heading"?Te("blocklayer.phHeading",{n:I.attrs.level??1}):null;return V?dr.create(g.doc,[ao.node(O.before(),O.after(),{class:"is-empty","data-placeholder":V})]):null}}})),An=["doc","amadeusColumnCell","bullet_list","ordered_list"],Jn=g=>{let A=g.depth;for(;A>=1&&!An.includes(g.node(A-1).type.name);)A--;return A},pr=g=>{const A=g.selection;if(A instanceof Ce){if(!A.node.isBlock)return null;if(An.includes(A.$from.parent.type.name))return{from:A.from,to:A.to};const G=Jn(A.$from);return G<1?null:{from:A.$from.before(G),to:A.$from.after(G)}}const{$from:O,$to:I}=A;if(!O.sameParent(I)){let G=O.sharedDepth(I.pos);for(;G>0&&!An.includes(O.node(G).type.name);)G--;return{from:O.before(G+1),to:I.after(G+1)}}const V=Jn(O);return V<1?null:{from:O.before(V),to:O.after(V)}},sn=g=>(A,O)=>{const I=pr(A);if(!I)return!1;const{from:V}=I,G=fs(A,I.from,I.to),le=A.doc.resolve(V),J=le.parent,ne=le.index(),W=A.doc.resolve(G).index()-1,Ae=J.child(ne),Pe=G>I.to&&Ae.type.name==="heading"?Number(Ae.attrs.level)||1:null;let _e,Be;if(g<0){if(ne===0)return!0;Be=V,_e=V-J.child(ne-1).nodeSize;let yt=null;if(Pe!=null)for(let tt=ne-1,Yn=V;tt>=0;tt--){const It=J.child(tt);if(Yn-=It.nodeSize,It.type.name==="heading"&&(Number(It.attrs.level)||1)<=Pe){yt=Yn;break}}if(yt!=null)_e=yt;else for(let tt=Ys(A,_e+1);tt!=null&&tt<_e;tt=Ys(A,_e+1))_e=tt}else{if(W+1>=J.childCount)return!0;_e=G;const yt=J.child(W+1);Be=G+yt.nodeSize,Pe!=null&&yt.type.name==="heading"&&(Be=Cm(A.doc,_e)??Be)}if(!O)return!0;const Ve=G-V,Xe=A.doc.slice(V,G).content,We=g<0?_e:Be-Ve,Ze=A.tr.delete(V,G).insert(We,Xe),Zt=We-V;Hr(A,Ze,{from:V,to:G,newStart:We}),es(A,Ze,{from:V,to:G,newStart:We});const xt=A.selection;return xt instanceof Ce?Ze.setSelection(Ce.create(Ze.doc,xt.from+Zt)):Ze.setSelection(je.create(Ze.doc,xt.anchor+Zt,xt.head+Zt)),o.getState(A)&&Ze.setMeta(o,!0),O(Ze.scrollIntoView()),!0},Wn=zt(()=>Bo({"Mod-Alt-ArrowUp":sn(-1),"Mod-Alt-ArrowDown":sn(1),"Mod-Shift-ArrowUp":sn(-1),"Mod-Shift-ArrowDown":sn(1)})),Nn=(g,A,O)=>{const I=g.selection,V=O?h(O):null;if(V){if(!A)return!0;const Pe=fs(g,V.from,V.to),{content:_e,minted:Be}=ns(g.doc,g.doc.slice(V.from,Pe).content);Be.length&&e.onCardsMinted?.(Be);const Ve=Pe-V.from,Xe=g.tr.insert(Pe,_e);return Hr(g,Xe,{from:V.from,to:Pe,newStart:Pe,copy:!0}),es(g,Xe,{from:V.from,to:Pe,newStart:Pe}),Xe.setSelection(je.create(Xe.doc,I.anchor+Ve,I.head+Ve)),o.getState(g)&&Xe.setMeta(o,!0),A(Xe.scrollIntoView()),!0}if(I instanceof Ce){if(!I.node.isBlock)return!1;if(!A)return!0;const Pe=fs(g,I.from,I.to);if(Pe>I.to){const Ve=g.tr.insert(Pe,g.doc.slice(I.from,Pe).content);return Hr(g,Ve,{from:I.from,to:Pe,newStart:Pe,copy:!0}),es(g,Ve,{from:I.from,to:Pe,newStart:Pe}),Ve.setSelection(Ce.create(Ve.doc,Pe)),A(Ve.scrollIntoView()),!0}let _e=I.node;if(_e.type.name==="amadeusCanvasCard"){const{content:Ve,minted:Xe}=ns(g.doc,zo.from(_e)),We=Ve.firstChild??_e;_e=We.type.create({...We.attrs,x:Number(We.attrs.x)+40,y:Number(We.attrs.y)+40},We.content,We.marks),Xe.length&&e.onCardsMinted?.(Xe)}const Be=g.tr.insert(I.to,_e);return Be.setSelection(Ce.create(Be.doc,I.to)),A(Be.scrollIntoView()),!0}if(!(I instanceof je)||!I.$from.sameParent(I.$to))return!1;const{$from:G}=I;let le=G.depth;for(;le>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard","bullet_list","ordered_list"].includes(G.node(le-1).type.name);)le--;if(le<1)return!1;const J=G.before(le),ne=fs(g,J,G.after(le));if(!g.doc.nodeAt(J))return!1;if(!A)return!0;const W=ne-J,Ae=g.tr.insert(ne,g.doc.slice(J,ne).content);return Hr(g,Ae,{from:J,to:ne,newStart:ne,copy:!0}),es(g,Ae,{from:J,to:ne,newStart:ne}),Ae.setSelection(je.create(Ae.doc,I.anchor+W,I.head+W)),A(Ae.scrollIntoView()),!0},Zn=zt(()=>Bo({"Mod-d":Nn})),No=(g,A,O,I=!1)=>{const V=O?h(O):null;if(!V)return!1;const G=g.doc.resolve(V.from);if(g.doc.resolve(V.to).index()-G.index()<2)return!1;const J=g.selection;if(J.from>V.from+1||J.to<V.to-1)return!1;if(!A)return!0;const ne=g.doc.slice(V.from,V.to).content;return A(g.tr.delete(V.from,V.to).scrollIntoView()),I||e.onBlocksDeleted?.(ne),!0},Uo=(g,A)=>{const O=g.selection;if(!(O instanceof Ce))return!1;if(!A)return!0;const I=zo.from(O.node);return A(g.tr.deleteSelection().scrollIntoView()),e.onBlocksDeleted?.(I),!0},Xo=(g,A,O)=>No(g,A,O)||Uo(g,A),Mn=zt(()=>Bo({Backspace:Xo,Delete:Xo})),Tn=zt(()=>new Wt({props:{handleDOMEvents:{cut:(g,A)=>{const O=A;if(!O.clipboardData||!No(g.state,void 0,g,!0))return!1;const{dom:I,text:V}=g.serializeForClipboard(g.state.selection.content());return O.preventDefault(),O.clipboardData.clearData(),O.clipboardData.setData("text/html",I.innerHTML),O.clipboardData.setData("text/plain",V),No(g.state,g.dispatch.bind(g),g,!0),!0}}}})),Dn=zt(()=>Bo({"Mod-a":(g,A)=>{const{$from:O}=g.selection,I=(le,J)=>g.selection.from<=le&&g.selection.to>=J,V=[];O.parent.isTextblock&&V.push([O.start(),O.end()]);let G=O.depth;for(;G>=1&&!["doc","amadeusColumnCell"].includes(O.node(G-1).type.name);)G--;G>=1&&V.push([O.start(G),O.end(G)]);for(const[le,J]of V)if(!I(le,J))return A?.(g.tr.setSelection(je.create(g.doc,le,J))),!0;return A?.(g.tr.setSelection(new Ul(g.doc))),!0}})),ho=g=>{const A=g.selection;if(!(A instanceof je)||A.empty)return[];const O=!!o.getState(g);if(!O&&A.$from.sameParent(A.$to))return[];const I=[],V=le=>{if(["bullet_list","ordered_list","table","blockquote","horizontal_rule","code_block","amadeusCanvasCard"].includes(le.type.name))return!0;if(le.type.name!=="paragraph")return!1;const J=le.textContent.trim();return/^!?\[\[[^\]\n]+\]\]$/.test(J)||le.childCount===1&&le.firstChild?.type.name==="image"},G=(le,J)=>{le.forEach((ne,W)=>{const Ae=J+W,Pe=Ae+ne.nodeSize;if(!(Pe<=A.from||Ae>=A.to)){if(ne.type.name==="amadeusColumnRow"){ne.forEach((_e,Be)=>G(_e,Ae+1+Be+1));return}(O||V(ne))&&I.push([Ae,Pe,O])}})};return G(g.doc,0),I},go=zt(()=>new Wt({key:o,state:{init:()=>!1,apply:(g,A,O)=>g.getMeta(o)===!0?!0:g.docChanged||g.selectionSet&&!g.selection.eq(O.selection)?!1:A},props:{decorations:g=>{const A=ho(g);return A.length?dr.create(g.doc,A.map(([O,I,V])=>ao.node(O,I,{class:V?"amx-block-selected":"amx-rendered-selected"}))):null},attributes:g=>o.getState(g)&&ho(g).length?{"data-blocksel":"true"}:{}}})),ut=zt(()=>Bo({Escape:(g,A)=>{const O=g.selection;if(O instanceof Ce){const I=je.near(g.doc.resolve(O.from+1));return A?.(g.tr.setSelection(I)),!0}if(O instanceof je){const I=ll(g);return I==null?!1:(A?.(g.tr.setSelection(Ce.create(g.doc,I))),!0)}return!1}})),Dt=["doc","amadeusColumnCell"],xo=g=>{const A=g.selection;return A instanceof Ce?A.node.isBlock:A instanceof je&&!A.empty&&!!o.getState(g)},co=(g,A)=>{const O=g.resolve(A);if(Dt.includes(O.parent.type.name)){const V=O.nodeAfter;return V?{from:A,to:A+V.nodeSize}:null}let I=O.depth;for(;I>=1&&!Dt.includes(O.node(I-1).type.name);)I--;return I>=1?{from:O.before(I),to:O.after(I)}:null},Go=g=>{const A=g.selection,O=g.doc,I=co(O,A instanceof Ce?A.from:A.anchor),V=A instanceof Ce?I:co(O,A.head);return!I||!V||O.resolve(I.from).parent!==O.resolve(V.from).parent?null:{a:I,h:V}},To=(g,A,O)=>{const I=g.doc,V=A.from===O.from?I.nodeAt(A.from):null;if(V&&Ce.isSelectable(V))return g.tr.setSelection(Ce.create(I,A.from));const G=O.from>=A.from,le=I.resolve(G?A.from+1:A.to-1),J=I.resolve(G?O.to-1:O.from+1);return g.tr.setSelection(je.between(le,J)).setMeta(o,!0)},Vn=g=>(A,O)=>{if(!xo(A))return!1;const I=Go(A);if(!I)return!1;const V=A.doc.resolve(I.h.from),G=V.parent;let le=V.index()+g,J=g>0?I.h.to:I.h.from;for(;le>=0&&le<G.childCount;){const ne=G.child(le).nodeSize,W=g>0?J:J-ne;if(Ys(A,W+1)==null)return O?.(To(A,I.a,{from:W,to:W+ne}).scrollIntoView()),!0;J=g>0?J+ne:J-ne,le+=g}return!0},Oe=g=>g.selection.$from.parent.type.name==="code_block";return{plugins:[zt(()=>new Wt({props:{handleKeyDown:Jf({"Shift-ArrowDown":Vn(1),"Shift-ArrowUp":Vn(-1),"Mod-Alt-/":(g,A,O)=>{if(!O||!O.editable||!A)return!1;if(!xo(g)){const le=ll(g);if(le==null)return!1;A(g.tr.setSelection(Ce.create(g.doc,le)))}const I=O.state,V=I.selection instanceof Ce?O.nodeDOM(I.selection.from):null,G=V instanceof HTMLElement?V.getBoundingClientRect():O.coordsAtPos(I.selection.from);return e.onMenu({x:G.left,y:G.bottom+4,keyboard:!0,focus:"turnInto"}),!0},"Mod-]":(g,A,O)=>Oe(g)?!1:xa(g,A,O,_t),"Mod-[":(g,A)=>Oe(g)?!1:ya(g,A)}),handleDOMEvents:{mousedown:(g,A)=>{if(!A.shiftKey||A.button!==0||!g.editable||!xo(g.state))return!1;const O=g.posAtCoords({left:A.clientX,top:A.clientY}),I=Go(g.state),V=O?co(g.state.doc,O.pos):null;return!I||!V||g.state.doc.resolve(V.from).parent!==g.state.doc.resolve(I.a.from).parent?!1:(A.preventDefault(),g.dispatch(To(g.state,I.a,V)),g.focus(),!0)}}}})),et,un,dt,pt,go,Jt,ut,dn,Dn,Mn,Tn,Wn,Zn,rb].flat(),getView:()=>t,topRangeOf:h,duplicate:g=>Nn(g.state,g.dispatch.bind(g),g),indent:(g,A)=>A>0?xa(g.state,g.dispatch.bind(g),g,_t):ya(g.state,g.dispatch.bind(g))}}async function ib(e,t,n){const o=Xc(t);if(!o.length)return;const r=new Set(Xc(n).map(Js)),s=o.filter(a=>!r.has(Js(a)));if(!s.length)return;const i=(await rn.exclusiveAssets?.(e).catch(()=>[])??[]).filter(a=>s.some(l=>lb(l,a)));i.length&&await Uh(e,i,{block:!0})==="with"&&await Pp(i)}function lb(e,t){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase(),o=t.replace(/\\/g,"/").toLowerCase();return n.includes("/")?o===n||o.endsWith(`/${n}`)||o===Fl(n):Js(e)===Js(t)}function ul(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(`[](${Gc(c)??c})`)}return}const r=String(o.attrs?.src??"");r&&t.push(`![](${Gc(r)??r})`),o.forEach(n)};return e.forEach(n),t.join(`
687
- `)}const Yo=1,en=400,Ko=720,ub=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/,db=/^<!--\s*\/a\s+([A-Za-z0-9_-]+)\s*-->$/,da=/^[A-Za-z0-9_-]+$/,so=(e,t)=>typeof e=="number"&&Number.isFinite(e)?Math.round(e):t;function _n(e){if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(n.v!==Yo||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"||!da.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 fb(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 pb=xc("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=ia(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 mb(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(k=>k?.position))return;const c=k=>{let v=null;if(k?.type==="html"&&typeof k.value=="string")v=k.value;else if(k?.type==="paragraph"&&Array.isArray(k.children)&&k.children.length===1){const P=k.children[0];P?.type==="html"&&typeof P.value=="string"&&(v=P.value)}if(v==null)return null;const j=ub.exec(v.trim());return j?j[1]:null},i=k=>{let v=null;if(k?.type==="html"&&typeof k.value=="string")v=k.value;else if(k?.type==="paragraph"&&Array.isArray(k.children)&&k.children.length===1){const P=k.children[0];P?.type==="html"&&typeof P.value=="string"&&(v=P.value)}if(v==null)return null;const j=db.exec(v.trim());return j?j[1]:null},a=new Map(r.map(k=>[k.ref,k])),l=Iu(t?.cardColors),m=[];if(s.forEach((k,v)=>{const j=c(k);j&&m.push({id:j,idx:v})}),!m.length)return;const h=new Map;m.forEach(k=>h.set(k.id,(h.get(k.id)??0)+1));const E=[];for(const k of m){if((h.get(k.id)??0)>1||n.has(k.id)||!a.has(k.id))continue;let v=s.length,j=-1;for(let P=k.idx+1;P<s.length;P++){if(c(s[P])){v=P;break}if(i(s[P])===k.id){v=P,j=P;break}}E.push({id:k.id,open:k.idx,end:v,closer:j})}if(!E.length)return;const R=[];for(const k of[...E].reverse()){const v=a.get(k.id),j=s.slice(k.open+1,k.end);s.splice(k.open,(k.closer>=0?k.closer+1:k.end)-k.open,{type:"amadeusCanvasCard",anchor:k.id,x:so(v.x,0),y:so(v.y,0),w:so(v.w,en)||en,h:so(v.h,0),color:l&&Object.prototype.hasOwnProperty.call(l,k.id)&&Pu(l[k.id])?l[k.id]:typeof v.color=="string"?v.color:"",children:j.length?j:[{type:"paragraph",children:[]}]}),R.unshift(k.id)}o?.(R)}function hb(e,t,n){return[Ql("amadeusCanvasFold",()=>()=>o=>{mb(o,e(),fb(t()),n)})].flat()}function gb(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const o=String(n.attrs.anchor);if(!da.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 Iu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}const Pu=e=>e!==""&&e!=null;function dl(e){const t=Object.create(null);return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const o=String(n.attrs.anchor);da.test(o)&&Pu(n.attrs.color)&&(t[o]=n.attrs.color)}),t}function xb(e,t,n,o){const r=gb(e),s=_n(t);if(!s){if(t!=null)return t;if(!r.length)return null;const m=dl(e);return JSON.stringify({v:Yo,mode:n??"canvas",main:{x:0,y:0,w:Ko},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===Ko)return null}const c={...s,v:Yo,cards:r},i=dl(e);Object.keys(i).length?c.cardColors={...i}:(c.cardColors===void 0||Iu(c.cardColors))&&delete c.cardColors,n&&(c.mode=n),c.main||(c.main={x:0,y:0,w:Ko}),c.elements?.length||delete c.elements;const a=Vt(c.tree),l=Object.keys(a);if(l.length){const m=new Set(r.map(R=>R.ref)),h=R=>typeof R=="string"&&da.test(R)&&!m.has(R),E=new Set;for(const R of l)h(R)&&E.add(R),h(a[R])&&E.add(a[R]);if(E.size){const R=bx(a,E);Object.keys(R).length?c.tree=R:delete c.tree}}return JSON.stringify(c)}function yb(e,t){const n=_n(e);if(!n)return e??(t.length?JSON.stringify({v:Yo,mode:"canvas",main:{x:0,y:0,w:Ko},cards:[],elements:t}):null);const o={...n,v:Yo,elements:t};return t.length||delete o.elements,JSON.stringify(o)}function bb(e,t){const n={x:Math.round(t.x),y:Math.round(t.y),w:Math.round(t.w),...typeof t.h=="number"&&t.h>0?{h:Math.round(t.h)}:{}},o=_n(e);return o?JSON.stringify({...o,v:Yo,main:n}):e??(!n.x&&!n.y&&n.w===Ko?null:JSON.stringify({v:Yo,mode:"canvas",main:n,cards:[]}))}function vb(e,t){const n=Object.keys(t).length,o=_n(e);if(!o)return e??(n?JSON.stringify({v:Yo,mode:"canvas",main:{x:0,y:0,w:Ko},cards:[],tree:t}):null);const r={...o,v:Yo,tree:t};return n||delete r.tree,JSON.stringify(r)}const wb=zt(()=>new Wt({key:new Ln("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((h,E)=>{if(h.type.name!=="amadeusColumnRow")return;const R=l+1+E;r.push({from:R,to:R+h.nodeSize,node:h,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:Ao(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}})),kb=zt(()=>new Wt({key:new Ln("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)))}),zo.fromArray(c)};return Ua.maxOpen(r(e.content))}}})),Sb=zt(()=>new Wt({key:new Ln("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}})),Cb=[pb,wb,kb,Sb].flat();function Eb(e){return[zt(()=>new Wt({key:new Ln("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 k=0;for(let v=0;v<o.doc.childCount;v++){const j=o.doc.child(v);if(j.type===r){s=k;break}k+=j.nodeSize}}if(s<0)return null;const c=k=>k.depth>=1&&k.node(1).type===r?k.index(0):-1,i=k=>{if(k<0)return{from:0,to:s};let v=0;for(let j=0;j<k;j++)v+=o.doc.child(j).nodeSize;return{from:v+1,to:v+o.doc.child(k).nodeSize-1}},a=k=>k.eq(o.selection)||c(o.doc.resolve(k.anchor))!==c(o.doc.resolve(k.head))?null:o.tr.setSelection(k),l=o.selection;if(l.empty||l instanceof Ce)return null;if(l instanceof Ul){if(t.some(j=>j.docChanged))return null;const k=Math.max(0,Math.min(n.selection.head,o.doc.content.size)),v=i(c(o.doc.resolve(k)));return v.from>=v.to?null:a(je.between(o.doc.resolve(v.from),o.doc.resolve(v.to),-1))}if(!(l instanceof je))return null;const m=o.doc.resolve(l.anchor),h=c(m);if(h===c(o.doc.resolve(l.head)))return null;const E=i(h),R=Math.max(E.from,Math.min(E.to,l.head));return a(je.between(m,o.doc.resolve(R),l.head>=l.anchor?-1:1))}}))].flat()}function Mb(){return[zt(()=>new Wt({key:new Ln("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 Ce){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 zb=6,Ab=2;function Nb(e){return[zt(()=>new Wt({key:new Ln("AMX_CARD_DEPTH"),props:{decorations(t){const n=t.schema.nodes.amadeusCanvasCard;if(!n)return null;const o=Vt(e()?.tree);if(!Object.keys(o).length)return null;const r=new Set,s=[];t.doc.forEach((a,l,m)=>{if(a.type!==n)return;const h=String(a.attrs.anchor);r.add(h),s.push({pos:l,size:a.nodeSize,anchor:h,idx:m})});const c=[];for(let a=0;a<s.length;a++){const l=na(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=vx(o,l.anchor,r,zb),h=c.filter(R=>R.start<=a&&a<R.end).slice(0,Ab);if(!m&&!h.length)continue;const E=[];m>0&&E.push("amx-card-child",`amx-card-d${m}`),h.forEach((R,k)=>{E.push(`amx-card-f${k}`),R.start===a&&E.push(`amx-card-f${k}-top`),R.end-1===a&&E.push(`amx-card-f${k}-end`)}),i.push(ao.node(l.pos,l.pos+l.size,{class:E.join(" ")}))}return i.length?dr.create(t.doc,i):null}}}))].flat()}const Tb=200;function $b(e){return[zt(()=>new Wt({key:new Ln("AMX_CANVAS_HISTORY_TIMELINE"),state:{init:(t,n)=>({depth:Wa(n)}),apply:(t,n,o,r)=>{const s=Wa(r);return t.docChanged&&s>n.depth&&!Zd(t)&&(e.log.push("pm"),e.log.length>Tb&&e.log.shift(),e.future.length=0),s===n.depth?n:{depth:s}}}}))].flat()}En({"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 Ft=e=>`c:${e}`,vn=e=>`e:${e}`,Ou=e=>`t:${e}`,at=e=>e.slice(2),_s=e=>typeof e=="number"&&Number.isFinite(e)?e:null,Wr=e=>typeof e=="string"&&e?e:null,La=e=>ia(e)?e:null,Mc=e=>{const t=ia(e);return t?{"data-color":e,style:{"--amx-color":t}}:{}};function ra(e){if(!e||typeof e!="object")return null;const t=e,n=Wr(t.ref);if(n)return{ref:n};const o=Wr(t.id);return o?{id:o}:t.main===!0?{main:!0}:null}const wr=e=>e.ref?Ft(e.ref):e.id?vn(e.id):e.main?we:null;function Rn(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const o of e){if(!o||typeof o!="object")continue;const r=o,s=Wr(r.id);if(!s||n.has(s))continue;if(r.type==="connector"){const m=ra(r.from),h=ra(r.to);if(!m||!h)continue;n.add(s),t.push({kind:"connector",id:s,from:m,to:h,label:Wr(r.label),color:La(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=_s(r.x),i=_s(r.y),a=_s(r.w),l=_s(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:Wr(r.title),color:La(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:Wr(r.text),color:La(r.color)})}}return t}function fl(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 zc(e,t){const n=fl(e,t),o=fl(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 jb(e,t){const{p1:n,c1:o,c2:r,p2:s}=zc(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 Bs(e,t,n,o=8){const{p1:r,c1:s,c2:c,p2:i}=zc(e,t);let a=r.x,l=r.y;for(let m=1;m<=24;m++){const h=m/24,E=1-h,R=E*E*E*r.x+3*E*E*h*s.x+3*E*h*h*c.x+h*h*h*i.x,k=E*E*E*r.y+3*E*E*h*s.y+3*E*h*h*c.y+h*h*h*i.y,v=R-a,j=k-l,P=v*v+j*j,q=P?Math.max(0,Math.min(1,((n.x-a)*v+(n.y-l)*j)/P)):0;if(Math.hypot(a+q*v-n.x,l+q*j-n.y)<=o)return!0;a=R,l=k}return!1}function Fu(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 Rb(e,t){const n=[...t].flatMap(i=>i===we?[we]:i.startsWith("c:")?[at(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 E=s.get(l);if(!E)break;r.add(l),o.add(E),l=E}const m=[i],h=new Set;for(;m.length;){const E=m.shift();if(!h.has(E)){h.add(E);for(const R of c.get(E)??[])r.add(R),o.add(R),m.push(R)}}}return{nodes:o,edgeChildren:r}}const pl=(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 yn(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 bn(e){const t=e?.querySelector(".ProseMirror");return t?{x:t.offsetLeft,y:t.offsetTop,w:t.offsetWidth,h:t.offsetHeight}:null}function ml(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 Lb(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 yn(e)){const l=e.querySelector(`.amx-ucard[data-anchor="${CSS.escape(i)}"]`),m=l?ml(l):null;l&&m&&o.push({key:Ft(i),anchor:i,...m,h:a.h,autoHeight:Number(l.dataset.h)<=0})}const r=e.querySelector(".ProseMirror"),s=bn(e),c=r?ml(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 Db(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 Ar(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(vn(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 Ib({elements:e,hostRef:t,documentKey:n,sel:o,editing:r,tree:s,ghost:c,marquee:i,attach:a,overviewScale:l,mainAutoHeight:m=!0,preview:h,guides:E}){const{t:R}=Ht(),k=x.useMemo(()=>Rn(e),[e]),v=x.useMemo(()=>Fu(s),[s]),j=x.useMemo(()=>Rb(v,o),[v,o]),P=j.edgeChildren,[q,X]=x.useState(0),_=k.length+v.length,Z=[...o].filter(C=>C.startsWith("c:")).map(at),ze=o.has(we),Ke=_+Z.length+(ze?1:0),p=l!=null&&l>0,[xe,Qe]=x.useState({documentKey:"",items:[]});x.useEffect(()=>{const C=t.current;if(!C)return;let Y=0;const fe=new ResizeObserver(()=>Fe()),ye=new Set,Ye=()=>{const ct=new Set(C.querySelectorAll(".amx-ucard")),Kt=C.querySelector(".ProseMirror");Kt&&ct.add(Kt);for(const jt of ct)ye.has(jt)||(fe.observe(jt,{box:"border-box"}),ye.add(jt));for(const jt of[...ye])ct.has(jt)||(fe.unobserve(jt),ye.delete(jt))},Fe=()=>{cancelAnimationFrame(Y),Y=requestAnimationFrame(()=>{Ye(),X(ct=>ct+1)})};Fe();const ht=new MutationObserver(Fe);return ht.observe(C,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["style","data-x","data-y","data-w","data-h"]}),fe.observe(C),()=>{cancelAnimationFrame(Y),ht.disconnect(),fe.disconnect()}},[t]);const de=x.useMemo(()=>yn(t.current),[t,n,xe.documentKey,q,Ke,c]),ce=x.useMemo(()=>Ar(k,c),[k,c]),se=bn(t.current);x.useLayoutEffect(()=>{if(!p)return;const C=t.current,Y=C?.querySelector(".ProseMirror");if(!C||!Y||Y.childElementCount===0)return;const fe=Lb(C,m);Qe(ye=>ye.documentKey===n&&Db(ye.items,fe)?ye:{documentKey:n,items:fe})},[n,t,m,p,q]);const ae=xe.documentKey===n?xe.items:[],Re=new Set([...Z,...ze?[we]:[]]),Me=p?ae.flatMap(C=>{if(Re.has(C.anchor))return[];const Y=C.anchor===we?se:de.get(C.anchor);return Y?[{...C,box:Y}]:[]}):[],rt=t.current?.dataset.amxDragscope,Je=p&&rt?ae.flatMap(C=>{const Y=`.amx-stage[data-amx-dragscope="${CSS.escape(rt)}"].amx-stage-overview`;if(Re.has(C.anchor))return[];if(C.anchor===we)return[`${Y} .ProseMirror:not(.unified-embed .ProseMirror) > :not(.amx-ucard){display:none!important;}`,...m?[`${Y} .ProseMirror:not(.unified-embed .ProseMirror){height:${C.h}px;}`]:[]];const fe=`${Y} .amx-ucard[data-anchor="${CSS.escape(C.anchor)}"]`;return[`${fe} > *{display:none!important;}`,...C.autoHeight?[`${fe}[data-h="0"]{height:${C.h}px;}`]:[]]}).join(`
688
- `):"",ee=j.nodes.size>0&&rt?(()=>{const C=`.amx-stage[data-amx-dragscope="${CSS.escape(rt)}"]:not(.amx-stage-off)`,Y=[...de.keys()].filter(ye=>!j.nodes.has(ye)).flatMap(ye=>[`${C} .amx-ucard[data-anchor="${CSS.escape(ye)}"]`,`${C} .amx-card-overview[data-card-label="${CSS.escape(ye)}"]`]),fe=Y.length?[`${Y.join(`,
689
- `)}{opacity:0.44;}`]:[];if(!j.nodes.has(we)){const ye=`${C} .ProseMirror:not(.unified-embed .ProseMirror)`;fe.push(`${ye}{background-color:color-mix(in srgb,var(--bg) 44%,transparent);border-color:color-mix(in srgb,var(--border) 44%,transparent);box-shadow:none;}`,`${ye}>:not(.amx-ucard){opacity:0.44;}`,`${C} .amx-card-overview[data-card-label="${CSS.escape(we)}"]{opacity:0.44;}`)}return fe.push(`${C} .amx-el-conn.is-tree:not(.is-related){opacity:0.18;}`),fe.join(`
690
- `)})():"",ge=C=>C.ref!=null?de.get(C.ref)??null:C.id!=null?ce.get(C.id)??null:C.main?se:null,Se=C=>C===we?se:C.startsWith("c:")?de.get(at(C))??null:ce.get(at(C))??null;return u.jsxs("div",{className:"amx-el-layer",children:[Je?u.jsx("style",{"data-amx-overview-rules":!0,children:Je}):null,ee?u.jsx("style",{"data-amx-related-focus-rules":!0,children:ee}):null,k.filter(C=>C.kind==="frame").map(C=>u.jsx(_b,{el:C,box:ce.get(C.id),sel:o.has(vn(C.id))},C.id)),k.filter(C=>C.kind!=="frame").map(C=>C.kind==="connector"?u.jsx(Hs,{el:C,a:ge(C.from),b:ge(C.to),sel:o.has(vn(C.id))},C.id):u.jsx(Bb,{el:C,box:ce.get(C.id),sel:o.has(vn(C.id))},C.id)),o.size===1&&[...o][0].startsWith("e:")&&ce.has(at([...o][0]))?u.jsxs(u.Fragment,{children:[u.jsx(Ob,{id:at([...o][0]),box:ce.get(at([...o][0]))}),u.jsx(Da,{node:[...o][0],box:ce.get(at([...o][0]))})]}):null,(()=>{const C=o.size===1?[...o][0]:null,Y=C?.startsWith("e:")?k.find(ht=>ht.kind==="connector"&&ht.id===at(C)):null,fe=Y?ge(Y.from):null,ye=Y?ge(Y.to):null;if(!Y||!fe||!ye)return null;const{p1:Ye,p2:Fe}=zc(fe,ye);return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"amx-conn-end","data-conn-end":"from","data-el":Y.id,style:{left:`${Ye.x}px`,top:`${Ye.y}px`}}),u.jsx("div",{className:"amx-conn-end","data-conn-end":"to","data-el":Y.id,style:{left:`${Fe.x}px`,top:`${Fe.y}px`}})]})})(),v.map(([C,Y])=>{const fe=Y===we?se:de.get(Y),ye=de.get(C),Ye=Y===we?{main:!0}:{ref:Y};return fe&&ye?u.jsx(Hs,{el:{kind:"connector",id:`t:${C}`,from:Ye,to:{ref:C},label:null},a:fe,b:ye,sel:o.has(Ou(C)),related:P.has(C),tree:!0},`t:${C}`):null}),Z.map(C=>{const Y=de.get(C);return Y?u.jsx("div",{className:`amx-el-selbox${r===C?" is-editing":""}`,"data-anchor":C,style:{left:`${Y.x}px`,top:`${Y.y}px`,width:`${Y.w}px`,height:`${Y.h}px`},children:o.size===1&&r!==C?u.jsxs(u.Fragment,{children:[u.jsx(hl,{anchor:C}),u.jsx(gl,{node:C}),u.jsx(Da,{node:Ft(C)})]}):null},`sel:${C}`):null}),ze&&se?u.jsx("div",{className:`amx-el-selbox${r===we?" is-editing":""}`,"data-main-sel":!0,style:{left:`${se.x}px`,top:`${se.y}px`,width:`${se.w}px`,height:`${se.h}px`},children:o.size===1&&r!==we?u.jsxs(u.Fragment,{children:[u.jsx(hl,{anchor:we}),u.jsx(gl,{node:we}),u.jsx(Da,{node:we})]}):null}):null,Me.map(C=>{const Y=C.box.h*l,fe=Y<44?"title":Y<60?"summary":"full",ye=fe==="title"?Math.max(8,Math.min(12,(Y-3)/1.2)):12;return u.jsxs("div",{className:"amx-card-overview","data-card-label":C.anchor,"data-overview-density":fe,style:{left:`${C.box.x}px`,top:`${C.box.y}px`,width:`${C.box.w}px`,height:`${C.box.h}px`,"--amx-overview-inv":String(1/l),"--amx-overview-title-screen":`${ye}px`},children:[u.jsx("span",{className:"amx-card-overview-title",children:C.title}),C.detail?u.jsx("span",{className:"amx-card-overview-detail",children:C.detail}):null]},`overview:${C.key}`)}),h?(()=>{const C=Se(h.from);if(!C)return null;const Y=h.over?Se(h.over):null,fe=Y??{x:h.x,y:h.y,w:1,h:1};return u.jsxs(u.Fragment,{children:[u.jsx(Hs,{el:{kind:"connector",id:"~preview",from:{},to:{},label:null},a:C,b:fe,sel:!1,preview:!0}),u.jsx("div",{className:"amx-conn-target",style:{left:`${C.x}px`,top:`${C.y}px`,width:`${C.w}px`,height:`${C.h}px`}}),Y?u.jsx("div",{className:"amx-conn-target",style:{left:`${Y.x}px`,top:`${Y.y}px`,width:`${Y.w}px`,height:`${Y.h}px`}}):null]})})():null,a?(()=>{const C=a.node===we?se:de.get(a.node),Y=de.get(a.source);if(!C)return null;const fe=3,ye=22,Ye=a.side==="n"||a.side==="s",Fe=a.side==="w"?C.x:a.side==="e"?C.x+C.w:C.x+C.w/2,ht=a.side==="n"?C.y:a.side==="s"?C.y+C.h:C.y+C.h/2;return u.jsxs(u.Fragment,{children:[Y?u.jsx(Hs,{el:{kind:"connector",id:"~attach",from:{ref:a.source},to:a.node===we?{main:!0}:{ref:a.node},label:null},a:Y,b:C,sel:!1,preview:!0}):null,u.jsx("div",{className:`amx-el-attach-target is-${a.rel}`,style:{left:`${C.x}px`,top:`${C.y}px`,width:`${C.w}px`,height:`${C.h}px`}}),u.jsx("div",{className:`amx-el-attach is-${a.rel}`,"data-attach":a.side,style:{left:`${a.side==="e"?C.x+C.w-fe:a.side==="w"?C.x:C.x+(C.w-ye)/2}px`,top:`${a.side==="s"?C.y+C.h-fe:a.side==="n"?C.y:C.y+(C.h-ye)/2}px`,width:`${Ye?ye:fe}px`,height:`${Ye?fe:ye}px`}}),u.jsxs("div",{className:`amx-el-attach-label is-${a.rel}`,style:{left:`${Fe}px`,top:`${ht}px`},children:[a.count&&a.count>1?`${R("canvasel.attach.count",{n:a.count})} · `:"",a.rel==="child"?R("canvasel.attach.child"):R("canvasel.attach.sibling")]})]})})():null,E?.map((C,Y)=>u.jsx("div",{className:`amx-el-guide is-${C.dir}`,style:{left:`${C.x}px`,top:`${C.y}px`,width:`${C.w}px`,height:`${C.h}px`}},`guide:${Y}`)),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 _u=["nw","ne","sw","se"],Pb=["n","e","s","w",..._u];function hl({anchor:e}){return u.jsx(u.Fragment,{children:Pb.map(t=>u.jsx("div",{className:`amx-card-size-grip is-${t}`,"data-card-grip":e,"data-card-edge":t},t))})}function Ob({id:e,box:t}){return u.jsx(u.Fragment,{children:_u.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 gl({node:e}){const{t}=Ht();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 Fb=["n","e","s","w"];function Da({node:e,box:t}){const{t:n}=Ht(),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:Fb.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 _b({el:e,box:t,sel:n}){const o=Mc(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 Bb({el:e,box:t,sel:n}){const o=e.kind==="text"?"amx-el-text":e.shape==="ellipse"?"amx-el-ellipse":"amx-el-rect",r=Mc(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 Hs({el:e,a:t,b:n,sel:o,related:r,tree:s,preview:c}){if(!t||!n)return null;const i=jb(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,h=4.5,E=(j,P)=>{const q=Math.cos(P),X=Math.sin(P);return[`${j.x},${j.y}`,`${j.x-m*q+h*X},${j.y-m*X-h*q}`,`${j.x-m*q-h*X},${j.y-m*X+h*q}`].join(" ")},R=!s&&e.toEnd!=="none",k=!s&&e.fromEnd==="arrow",v=Mc(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":v["data-color"],style:{left:`${l.x}px`,top:`${l.y}px`,width:`${l.w}px`,height:`${l.h}px`,...v.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}),R?u.jsx("polygon",{points:E(i.tip,i.ang)}):null,k?u.jsx("polygon",{points:E(i.tail,i.tailAng)}):null]}),e.label?u.jsx("div",{className:`amx-el-label${o?" is-sel":""}`,"data-color":v["data-color"],style:{left:`${i.mid.x}px`,top:`${i.mid.y}px`,...v.style},children:e.label}):null]})}const Ks=e=>typeof e=="number"&&Number.isFinite(e)?e:null,rs=e=>typeof e=="string"&&e?e:null,Ia=e=>ia(e)?e:null,xl=e=>e==="none"||e==="arrow"?e:null,ss=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 Hb(e){const t=/^!\[\[([^\]\n]+)\]\]$/.exec(e.trim());return t?t[1]:null}function yl(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 Kb(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 v of c){if(!v||typeof v!="object"||Array.isArray(v))continue;const j=v,P=rs(j.id);if(!P||i.has(P))continue;if(j.type==="connector"){i.add(P),a.push(j);continue}if(j.type!=="shape"&&j.type!=="text"&&j.type!=="frame")continue;const q=Ks(j.x),X=Ks(j.y),_=Ks(j.w),Z=Ks(j.h);if(q==null||X==null||_==null||Z==null||_<=0||Z<=0)continue;i.add(P);const ze=`el-${P}`,Ke={x:q,y:X,w:_,h:Z};r.set(ze,Ke);const p=Ia(j.color);if(j.type==="frame"){const xe=rs(j.title);t.push({id:ze,type:"group",...ss(Ke),...xe?{label:xe}:{},...p?{color:p}:{}})}else n.push({id:ze,type:"text",...ss(Ke),text:typeof j.text=="string"?j.text:"",...p?{color:p}:{}})}for(const v of e.cards){const j=`card-${v.ref}`;r.set(j,v);const P=Ia(v.color),q=Hb(v.md),X=q&&s.length?gs(Pl(q),s,e.sourcePath):null;if(q&&X){const _=q.split("|")[0],Z=_.indexOf("#"),ze=Z>=0?_.slice(Z).trim():"";o.push({id:j,type:"file",...ss(v),file:X,...ze.length>1?{subpath:ze}:{},...P?{color:P}:{}})}else o.push({id:j,type:"text",...ss(v),text:v.md,...P?{color:P}:{}})}const l=[],m=v=>{if(!v||typeof v!="object")return null;const j=v,P=rs(j.ref)?`card-${j.ref}`:rs(j.id)?`el-${j.id}`:j.main===!0?"main":null;return P&&(r.has(P)||P==="main")?P:null};e.main&&r.set("main",e.main);let h=!1;const E=v=>{const j=r.get(v.fromNode),P=r.get(v.toNode);!j||!P||((v.fromNode==="main"||v.toNode==="main")&&(h=!0),l.push({...v,fromSide:yl(j,P),toSide:yl(P,j)}))};for(const v of a){const j=m(v.from),P=m(v.to);if(!j||!P||j===P)continue;const q=xl(v.fromEnd),X=xl(v.toEnd),_=rs(v.label),Z=Ia(v.color);E({id:`edge-${v.id}`,fromNode:j,toNode:P,...q?{fromEnd:q}:{},...X?{toEnd:X}:{},..._?{label:_}:{},...Z?{color:Z}:{}})}const R=e.tree&&typeof e.tree=="object"&&!Array.isArray(e.tree)?e.tree:{};for(const v of Object.keys(R)){const j=R[v];if(typeof j!="string"||!j||j===v)continue;const P=j==="m:"?"main":`card-${j}`,q=`card-${v}`;r.has(q)&&E({id:`tree-${v}`,fromNode:P,toNode:q,toEnd:"none"})}const k=[...t,...n];return e.main&&(e.main.md.trim()||h)&&k.push({id:"main",type:"text",...ss(e.main),text:e.main.md}),k.push(...o),{nodes:k,edges:l}}const Vb=e=>`${JSON.stringify(e,null," ")}
691
- `;function qb(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 Wb(e,t,n){for(let o=1;o<=50;o++){const r=qb(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")}En({"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 Yb=[{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"}],bl=[{id:"end",from:"none",to:"arrow",nameKey:"canvasstage.ends.end",icon:u.jsx(zh,{size:13})},{id:"start",from:"arrow",to:"none",nameKey:"canvasstage.ends.start",icon:u.jsx(Nh,{size:13})},{id:"both",from:"arrow",to:"arrow",nameKey:"canvasstage.ends.both",icon:u.jsx(Eh,{size:13})},{id:"none",from:"none",to:"none",nameKey:"canvasstage.ends.none",icon:u.jsx(op,{size:13})}],Ub=2,Us=168,Bu=72,Pa=320,vl=12,as=".amx-el-shape, .amx-el-frame-bar",wl="button, a[href], input, select, textarea",Xb='li[data-item-type="task"], .wikilink';function Gb(e,t){const n=e.closest(Xb);return n?n.tagName!=="LI"||t-n.getBoundingClientRect().left<=2:!1}const Oa=e=>e.kind==="connector"?"label":e.kind==="frame"?"title":"text",Fa=e=>Te(e.kind==="connector"?"canvasstage.textTitle.connector":e.kind==="frame"?"canvasstage.textTitle.frame":"canvasstage.textTitle.element"),Vs=e=>[...Ar(Rn(e).filter(t=>t.kind!=="frame"),null).values()],kl=50,_a=new Set(["rect","ellipse","frame"]),cs={rect:"rect",ellipse:"ellipse",text:"text"};let Jb=0;const Sl=(e,t,n,o,r,s=Us)=>Gp(e,t,n,o,r,s,Bu);function Ac(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 Fn(e){return Ac(e.state.doc)}const uc=(e,t,n)=>na(e,t,n);function Hu(e,t,n){const o=Ac(e),r=o.findIndex(c=>c.anchor===n);if(r<0)return e.content.size;const s=o[uc(o,r,t)-1];return s.pos+s.node.nodeSize}function Cl(e,t,n,o){const r=Ac(e.doc),s=r.findIndex(E=>E.anchor===n);if(s<0)return e;const c=uc(r,s,t),i=r[s].pos,a=r[c-1],l=a.pos+a.node.nodeSize;let m;if(o){const E=r.findIndex(v=>v.anchor===o);if(E<0||E>=s&&E<c)return e;const R=uc(r,E,t);if(s>E&&s<R)return e;const k=r[R-1];m=k.pos+k.node.nodeSize}else if(m=e.doc.content.size,l===m)return e;const h=zo.fromArray(r.slice(s,c).map(E=>E.node));return e.delete(i,l).insert(m>l?m-(l-i):m,h)}function cr(e,t){e.dispatch(Qs(t).setMeta("amxCanvas",!0))}function kr(e,t,n=!0){const o=Fn(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 Zb(e,t,n,o){const r=Fn(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 El(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?zo.fromArray(t):void 0}function Ml(e,t=!1){return e.kind==="note"?`${t?"":"!"}[[${e.path.replace(/\.md$/i,"")}]]`:e.kind==="session"?`[[session:${e.id}|${e.title}]]`:e.kind==="app"||e.kind==="window"?Vp(e):e.path}const zl="application/x-amx-canvas";let Ba=null;function Qb(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 Ha=(e,t)=>({x:e.x-t,y:e.y-t,w:e.w+t*2,h:e.h+t*2}),Al=(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 ev({hostRef:e,vp:t,elements:n,ghost:o,onCenter:r}){const[,s]=x.useState(0);x.useEffect(()=>{const h=e.current;if(!h)return;let E=0;const R=new Set,k=new ResizeObserver(()=>j()),v=()=>{const q=new Set(h.querySelectorAll(".amx-ucard")),X=h.querySelector(".ProseMirror");X&&q.add(X);for(const _ of q)R.has(_)||(k.observe(_,{box:"border-box"}),R.add(_));for(const _ of[...R])q.has(_)||(k.unobserve(_),R.delete(_))},j=()=>{cancelAnimationFrame(E),E=requestAnimationFrame(()=>{v(),s(q=>q+1)})},P=new MutationObserver(j);return P.observe(h,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["data-x","data-y","data-w"]}),k.observe(h),j(),()=>{cancelAnimationFrame(E),P.disconnect(),k.disconnect()}},[e]);const c=e.current;if(!c)return null;const i=[];for(const[h,E]of yn(c))i.push({key:Ft(h),kind:"card",box:E});const a=bn(c);a&&i.push({key:we,kind:"main",box:a});const l=Rn(n),m=Ar(l,o);for(const h of l){if(h.kind==="connector")continue;const E=m.get(h.id);E&&i.push({key:vn(h.id),kind:h.kind==="frame"?"frame":"shape",box:E})}return u.jsx(jm,{hostRef:e,vp:t,items:i,onCenter:r})}function tv({path:e,vaultRoot:t=null,active:n,getView:o,main:r,mainStored:s,elements:c,tree:i,onElements:a,onTree:l,onMain:m,timeline:h,histStepRef:E,onCommit:R,saveFile:k,parseMd:v,serializeMd:j,onBlocksDeleted:P,revealSelection:q=0,readOnly:X=!1,notePages:_,exportRef:Z,storedMd:ze,children:Ke}){const p=x.useRef(null),{t:xe}=Ht(),Qe=Op(t,e),[de,ce]=x.useState(()=>mi(Qe)??{x:0,y:0,z:1}),se=x.useRef(de);se.current=de;const[ae,Re]=x.useState(Rm),[Me,rt]=x.useState(Lm),[Je,ee]=x.useState($i);x.useEffect(()=>Dm(()=>ee($i())),[]);const[ge,Se]=x.useState(Im),C=x.useRef(ge);C.current=ge;const[Y,fe]=x.useState(Pm),ye=x.useRef(Y);ye.current=Y;const[Ye,Fe]=x.useState(null),ht=x.useCallback(f=>{C.current=f,Se(f),Om(f)},[]),[ct,Kt]=x.useState("select"),jt=x.useRef("select"),Et=x.useRef(X);Et.current=X;const Gt=x.useCallback(f=>{jt.current=f,Kt(f)},[]),[et,un]=x.useState([]),dt=x.useRef([]),pt=x.useCallback(f=>{const N=typeof f=="function"?f(dt.current):f;dt.current=N,un(N)},[]),[_t,dn]=x.useState(null),Jt=x.useRef(null),An=x.useCallback(f=>{Jt.current=f,dn(f)},[]),[Jn,pr]=x.useState(null),sn=x.useRef(null),Wn=x.useCallback(f=>{sn.current=f,pr(f)},[]),Nn=x.useRef({held:!1,used:!1}),[Zn,No]=x.useState(!1);x.useEffect(()=>{const f=p.current;if(!Jn||!f)return;const N=f.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 Uo=x.useRef(0),[Xo,Mn]=x.useState(null),[Tn,Dn]=x.useState(null),[ho,go]=x.useState(null),[ut,Dt]=x.useState(null),[xo,co]=x.useState(null),[Go,To]=x.useState(!1),Vn=x.useRef(0),Oe=x.useCallback(()=>{cancelAnimationFrame(Vn.current),Vn.current=0,To(!1)},[]);x.useEffect(()=>()=>cancelAnimationFrame(Vn.current),[]);const Yt=x.useRef({raf:0,animations:[]}),g=x.useCallback(()=>{cancelAnimationFrame(Yt.current.raf),Yt.current.raf=0;const f=Yt.current.animations.splice(0);for(const N of f)N.cancel()},[]),A=x.useCallback(f=>{const N=p.current;g(),!(!N||!f.length||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Yt.current.raf=requestAnimationFrame(()=>{Yt.current.raf=0;let $=0;const H=K=>{Yt.current.animations.push(K);const B=()=>{Yt.current.animations=Yt.current.animations.filter(U=>U!==K)};K.addEventListener("finish",B,{once:!0}),K.addEventListener("cancel",B,{once:!0})};for(const K of f){const B=N.querySelector(`.amx-ucard[data-anchor="${CSS.escape(K.anchor)}"]`),U=Math.hypot(K.x,K.y);if(!B||U<1)continue;const oe=Math.min(126,Math.max(0,K.depth-1)*42),be=Math.round(Math.max(420,Math.min(620,360+U*.34)));$=Math.max($,oe+be);const ie=B.animate([{transform:`translate(${-K.x}px, ${-K.y}px) scale(0.988)`,opacity:.94,boxShadow:"0 8px 24px rgb(0 0 0 / 18%)",offset:0,easing:"cubic-bezier(0.16, 0.82, 0.24, 1)"},{transform:`translate(${K.x*.035}px, ${K.y*.035}px) scale(1.003)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-K.x*.008}px, ${-K.y*.008}px) scale(0.999)`,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:.9,easing:"ease-out"},{transform:"translate(0, 0) scale(1)",opacity:1,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:1}],{duration:be,delay:oe,fill:"backwards"});ie.id="amx-card-arrange",H(ie)}if($>0)for(const K of N.querySelectorAll(".amx-el-conn, .amx-el-label")){const B=K.animate([{opacity:.12,offset:0},{opacity:.12,offset:.68},{opacity:1,offset:1,easing:"ease-out"}],{duration:$,fill:"backwards"});B.id="amx-card-arrange-line",H(B)}}))},[g]),O=x.useCallback((f,N)=>{const $=p.current,H=Math.hypot(N.x,N.y);g(),!(!$||H<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Yt.current.raf=requestAnimationFrame(()=>{Yt.current.raf=0;const K=be=>{Yt.current.animations.push(be);const ie=()=>{Yt.current.animations=Yt.current.animations.filter(re=>re!==be)};be.addEventListener("finish",ie,{once:!0}),be.addEventListener("cancel",ie,{once:!0})},B=Math.round(Math.max(400,Math.min(520,350+H*.42))),U=$.querySelector(`.amx-ucard[data-anchor="${CSS.escape(f)}"]`);if(U){const be=U.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:B,fill:"none"});be.id="amx-card-attach",K(be)}const oe=$.querySelector(`.amx-el-conn[data-el="${CSS.escape(`t:${f}`)}"]`);if(oe){const be=oe.animate([{opacity:0,offset:0},{opacity:0,offset:.56},{opacity:1,offset:1,easing:"ease-out"}],{duration:B,fill:"backwards"});be.id="amx-card-attach-line",K(be)}}))},[g]);x.useEffect(()=>g,[g]);const[I,V]=x.useState(null),[G,le]=x.useState(null);x.useEffect(()=>{_t||V(null)},[_t]);const J=new Set(et),ne=x.useRef(!mi(Qe));x.useEffect(()=>{n&&Fp(Qe,de)},[Qe,de,n]),x.useLayoutEffect(()=>{const f=p.current;!n||!Jn||!f||!document.activeElement||!f.contains(document.activeElement)||sp()},[n,Jn,de]);const W=x.useRef({getView:o,onCommit:R,onElements:a,onTree:l,onMain:m,timeline:h,elements:c,tree:i,main:r,mainStored:s,saveFile:k,parseMd:v,serializeMd:j,onBlocksDeleted:P,notePages:_,path:e,storedMd:ze});W.current={getView:o,onCommit:R,onElements:a,onTree:l,onMain:m,timeline:h,elements:c,tree:i,main:r,mainStored:s,saveFile:k,parseMd:v,serializeMd:j,onBlocksDeleted:P,notePages:_,path:e,storedMd:ze};const Ae=Rn(c),Pe=f=>{if(!f)return null;const N={x:f.x,y:f.y,w:f.w,...typeof f.h=="number"&&f.h>0?{h:f.h}:{}};return N.x!==0||N.y!==0||N.w!==Ko||(N.h??0)>0?N:null},_e=()=>{const f=W.current;return{e:_o(f.elements),t:Vt(f.tree),m:Pe(f.mainStored?f.main:null)}},Be=x.useRef(null),Ve=x.useRef({past:[],future:[]}),Xe=()=>Ve.current;x.useEffect(()=>{const f=_e(),N=JSON.stringify(f);if(!(Be.current!==null&&N===Be.current)){if(Be.current!==null)try{const $=JSON.parse(Be.current),H=(B,U)=>{let oe=$.t[B];const be=new Set([B]);for(;typeof oe=="string"&&oe&&!be.has(oe);){if(oe===U)return!0;be.add(oe),oe=$.t[oe]}return!1};if(JSON.stringify(f.e)===JSON.stringify($.e)&&JSON.stringify(f.m)===JSON.stringify($.m)&&Object.keys(f.t).length<=Object.keys($.t).length&&Object.keys(f.t).every(B=>typeof $.t[B]<"u"&&(JSON.stringify(f.t[B])===JSON.stringify($.t[B])||H(B,f.t[B])))){Be.current=N;return}}catch{}Be.current=N,Ve.current={past:[],future:[]},W.current.timeline.log.length=0,W.current.timeline.future.length=0}},[e,c,i,r,s]);const We=x.useCallback((f,N)=>{const $=W.current,H=_e(),K=JSON.stringify(H),B=JSON.stringify({e:f.e??H.e,t:f.t??H.t,m:f.m?Pe(f.m):H.m});if(B!==K){if(N?.snap!==!1){const U=Xe();U.past.push(K),U.past.length>kl&&U.past.shift(),U.future.length=0,$.timeline.log.push("fm"),$.timeline.future.length=0;const oe=$.getView();oe&&oe.dispatch(Qs(oe.state.tr))}Be.current=B,f.e&&$.onElements(f.e),f.t&&$.onTree(f.t),f.m&&$.onMain(f.m)}},[e]),Ze=x.useCallback(f=>{const N=_o(W.current.elements),$=f(N);$!==N&&We({e:$})},[We]),Zt=x.useCallback(f=>{const N=Xe(),$=f==="undo"?N.past:N.future,H=f==="undo"?N.future:N.past,K=$.pop();if(K==null)return!1;const B=W.current;H.push(JSON.stringify(_e()));const U=JSON.parse(K);return Be.current=K,B.onElements(U.e),B.onTree(U.t),B.onMain(U.m??{x:0,y:0,w:Ko}),!0},[e]),xt=x.useCallback(()=>{const f=Xe();f.past.push(JSON.stringify(_e())),f.past.length>kl&&f.past.shift(),f.future.length=0;const N=W.current.timeline;N.log.push("fm"),N.future.length=0},[e]),yt=x.useCallback(f=>{const N=Vt(W.current.tree);return f.some($=>typeof N[$]<"u"||Object.keys(N).some(H=>N[H]===$))},[]),tt=x.useCallback(()=>{const f=W.current.timeline,N=f.log.length;if(N<2)return;const $=f.log[N-2],H=f.log[N-1];($==="pm"&&H==="fm"||$==="fm"&&H==="pm")&&f.log.splice(N-2,2,"pair")},[]),Yn=x.useCallback(f=>{const N=W.current.timeline,$=f==="undo"?N.log:N.future,H=f==="undo"?N.future:N.log,K=()=>{const oe=W.current.getView();return!!oe&&(f==="undo"?Wa(oe.state):Qd(oe.state))>0},B=()=>(f==="undo"?Xe().past:Xe().future).length>0,U=()=>{const oe=W.current.getView();return!!oe&&(f==="undo"?Ya:Kl)(oe.state,oe.dispatch)};for(;$.length;){const oe=$[$.length-1];if($.pop(),oe==="pair"){if(!K()||!B())continue;return Zt(f),U(),H.push(oe),!0}if(oe==="fm"){if(Zt(f))return H.push(oe),!0;continue}if(U())return H.push("pm"),!0}return U()},[Zt]);x.useEffect(()=>{if(E)return E.current=Yn,()=>{E.current===Yn&&(E.current=null)}},[E,Yn]);const It=x.useCallback((f,N)=>{const $=p.current,H=$?.getBoundingClientRect(),{x:K,y:B,z:U}=se.current;if(!$||!H)return{x:0,y:0};const oe=zn($)||1;return{x:((f-H.left)/oe-K)/U,y:((N-H.top)/oe-B)/U}},[]),nn=x.useCallback(()=>{Oe();const f=p.current,N=o();if(!f||!N)return;const $=[...f.querySelectorAll(".amx-ucard, .amx-el-shape, .amx-el-frame, .amx-el-frame-bar, .amx-el-conn, .amx-el-label"),N.dom].map(Q=>Q.getBoundingClientRect());if(!$.length)return;const{x:H,y:K,z:B}=se.current,U=f.getBoundingClientRect(),oe=zn(f)||1,be=(Q,S)=>(Q/oe-S)/B,ie=Math.min(...$.map(Q=>be(Q.left-U.left,H))),re=Math.min(...$.map(Q=>be(Q.top-U.top,K))),d=Math.max(...$.map(Q=>be(Q.right-U.left,H))),y=Math.max(...$.map(Q=>be(Q.bottom-U.top,K))),w=d-ie,M=y-re;if(w<=0||M<=0)return;const D=48,z=Math.max(Jr,Math.min(1,Math.min((U.width/oe-D*2)/w,(U.height/oe-D*2)/M)));ce({z,x:(U.width/oe-w*z)/2-ie*z,y:(U.height/oe-M*z)/2-re*z})},[o,Oe]),Un=x.useCallback(f=>{Oe();const N=p.current;if(!N)return;const{x:$,y:H,z:K}=se.current,B=Math.max(Jr,Math.min(Ls,K*f));if(B===K)return;const U=zn(N)||1,oe=N.getBoundingClientRect().width/U/2,be=N.getBoundingClientRect().height/U/2;ce({z:B,x:oe-(oe-$)*B/K,y:be-(be-H)*B/K})},[Oe]),$o=x.useCallback((f,N)=>{Oe();const $=p.current;if(!$)return;const H=zn($)||1,K=$.getBoundingClientRect(),B=se.current.z;ce({z:B,x:K.width/H/2-f*B,y:K.height/H/2-N*B})},[Oe]);x.useEffect(()=>{const f=p.current;if(!X||!f)return;const N=()=>{const $=W.current.getView(),H=document.getSelection();if(!$||!H||H.isCollapsed||!H.rangeCount)return;const K=H.getRangeAt(0),B=be=>$.dom.contains(be.nodeType===3?be.parentNode:be),U=B(K.startContainer),oe=B(K.endContainer);if(!(!U&&!oe))try{const be=$.state.doc,ie=U?$.posAtDOM(K.startContainer,K.startOffset):0,re=oe?$.posAtDOM(K.endContainer,K.endOffset):be.content.size,d=je.between(be.resolve(Math.min(ie,re)),be.resolve(Math.max(ie,re)));d.eq($.state.selection)||$.dispatch($.state.tr.setSelection(d))}catch{}};return f.addEventListener("copy",N,!0),()=>f.removeEventListener("copy",N,!0)},[X]),x.useEffect(()=>{const f=p.current;if(!n||!f)return;const N=$=>{const H=$.detail?.rect;if(!H)return;const K=It(H.left+H.width/2,H.top+H.height/2);$o(K.x,K.y),$.preventDefault()};return f.addEventListener("amx-reveal",N),()=>f.removeEventListener("amx-reveal",N)},[n,It,$o]);const Tr=x.useRef(nn);Tr.current=nn,x.useEffect(()=>{if(!n||!ne.current)return;ne.current=!1;const f=setTimeout(()=>Tr.current(),220);return()=>clearTimeout(f)},[n]),x.useEffect(()=>{n||(pt([]),Gt("select"),An(null),Dt(null),co(null),Wn(null))},[n]),x.useEffect(()=>{if(!ut)return;const f=N=>{N.target?.closest?.(".ctx-menu")||Dt(null)};return window.addEventListener("pointerdown",f,!0),window.addEventListener("contextmenu",f,!0),()=>{window.removeEventListener("pointerdown",f,!0),window.removeEventListener("contextmenu",f,!0)}},[ut]);const Bn=x.useCallback(f=>{const N=new Map;for(const[H,K]of yn(p.current))N.set(Ft(H),K);for(const[H,K]of Ar(Rn(W.current.elements),f))N.set(vn(H),K);const $=bn(p.current);return $&&N.set(we,$),N},[]),mr=x.useRef(!1);x.useEffect(()=>()=>{mr.current=!0},[]);const jo=x.useCallback(async(f,N,$)=>{const H=Rn(W.current.elements).find(U=>U.id===f);if(!H)return;const K=(H.kind==="connector"?H.label:H.kind==="frame"?H.title:H.text)??"",B=await Xa($,K);B==null||mr.current||Rn(W.current.elements).some(U=>U.id===f)&&Ze(U=>yx(U,f,N,B.trim()))},[Ze]),In=x.useCallback((f,N)=>{const $=W.current,H=$.getView(),K=new Set(f.filter(ie=>ie.startsWith("c:")).map(at));let B=!1;if(H&&K.size){const ie=N??"",re=new Map;for(const d of Fn(H))K.has(d.anchor)&&String(d.node.attrs.color??"")!==ie&&re.set(d.anchor,{color:ie});re.size&&(kr(H,re),$.onCommit(),B=!0)}const U=new Set(f.filter(ie=>ie.startsWith("e:")).map(at));if(!U.size)return;const oe=_o(W.current.elements),be=Sx(oe,U,N);be!==oe&&(We({e:be}),B&&tt())},[We,tt]),io=x.useCallback((f,N,$,H,K)=>{const B=W.current.getView(),U=B?.state.schema.nodes.amadeusCanvasCard,oe=B?.state.schema.nodes.paragraph;if(!B||!U||!oe)return null;const be=Ao(B.state.doc),ie={x:f,y:N,w:en,h:80},re=[...yn(p.current).values(),...Vs(W.current.elements)],d=bn(p.current);d&&re.push(d);const y=Qr([ie],re),w=f+y.x,M=N+y.y,D=K?.childCount?K:oe.create(null,H?B.state.schema.text(H):void 0),z=U.createAndFill({anchor:be,x:Math.round(w),y:Math.round(M),w:en,h:0},D);if(!z)return null;const Q=$?Hu(B.state.doc,Vt(W.current.tree),$):B.state.doc.content.size;return cr(B,B.state.tr.insert(Q,z)),W.current.onCommit(be),pt([Ft(be)]),!H&&!K?.childCount&&te.current.enterNodeEdit(Ft(be)),be},[Bn]),Jo=x.useCallback((f,N)=>{const $=W.current.saveFile;$&&f.forEach((H,K)=>{const B=H.name||Te("canvasstage.upload.fileN",{n:K+1}),U=Te("canvasstage.upload.uploading",{name:B}),oe=te.current.addCardAt(N.x-en/2+K*24,N.y-24+K*24,void 0,U);oe&&$(H).then(be=>{const ie=W.current.getView(),re=ie?Fn(ie).find(d=>d.anchor===oe&&d.node.textContent===U)??Fn(ie).find(d=>d.node.textContent===U):null;!ie||!re||(be?(Zb(ie,re.anchor,be,U),W.current.onCommit()):te.current.removeSel([Ft(re.anchor)]))})})},[]),Ro=x.useCallback((f,N,$=0)=>{const H=f.trim();if(!H)return null;const K=W.current.parseMd?.(H)??null;return te.current.addCardAt(N.x-en/2+$*24,N.y-24+$*24,void 0,H,El(K))},[]),Qn=x.useCallback(f=>{const N=Vt(W.current.tree),$=f(N);return $===N?!1:(We({t:$}),!0)},[We]),wn=x.useCallback(f=>f===we?bn(p.current):yn(p.current).get(f)??null,[]),Zo=x.useCallback((f,N,$,H,K=0)=>{const B=wn(f);if(!B)return null;const U=Vt(W.current.tree),oe=U[f],be=N==="child"?f:typeof oe=="string"&&oe?oe:"",ie=(be?Cr(U,be):[f]).map(wn).filter(Boolean),re=80,d=32,w=N==="child"?$==="w"?B.x-H-re:B.x+B.w+re:ie.length?Math.min(...ie.map(S=>S.x)):B.x,M=ie.length?Math.min(...ie.map(S=>S.y))-d-K:B.y,D=ie.length?Math.max(...ie.map(S=>S.y+S.h))+d:B.y,z=$==="n"?M:D,Q=N==="child"?Cr(U,f).length?z:B.y:z;return{parent:be,x:Math.round(w),y:Math.round(Q)}},[wn]),Lo=x.useCallback((f,N,$,H=80)=>{const K=wn(f);if(!K)return null;const B=Vt(W.current.tree),U=B[f],oe=N==="child"?f:typeof U=="string"&&U?U:"",be=N==="child"?K:oe?wn(oe):K;if(!be)return null;const ie=W.current.getView(),re=ie?Fn(ie).map(pe=>pe.anchor):[],y=(oe?Cr(B,oe):N==="child"?Cr(B,f):re.filter(pe=>typeof B[pe]!="string"||!B[pe])).map(pe=>wn(pe)).filter(Boolean),w=be.x+be.w/2,M=[...yn(p.current).values(),...Vs(W.current.elements)],D=bn(p.current);D&&M.push(D);const z=80,Q=32;let S=null;for(const pe of[1,-1]){const me=y.filter(fn=>(fn.x+fn.w/2-w)*pe>0),He=pe>0?be.x+be.w+z:be.x-z-$,Ge=me.length?Math.max(...me.map(fn=>fn.y+fn.h))+Q:be.y,it=Qr([{x:He,y:Ge,w:$,h:H}],M,{x:pe,y:0}),on=Math.hypot(it.x,it.y)*100+me.length*32+(pe<0?6:0);(!S||on<S.score)&&(S={x:He+it.x,y:Ge+it.y,score:on})}return S?{parent:oe,x:Math.round(S.x),y:Math.round(S.y)}:null},[Bn,wn]),Qo=x.useCallback((f,N)=>{const $=Lo(f,N,en);if(!$)return;const H=io($.x,$.y,$.parent||void 0);H&&$.parent&&Qn(K=>Kr(K,H,$.parent))&&tt()},[Lo,io,Qn,tt]),lo=x.useCallback((f,N)=>{const $=[...new Set(typeof f=="string"?[f]:f)],H=new Set($),K=yn(p.current),B=$[0],U=B?K.get(B):null;if(!U||!B)return null;const oe=Zo(N.node,N.rel,N.side,U.w,U.h);if(!oe)return null;const be=Vt(W.current.tree),ie=$.filter(pe=>!(typeof be[pe]=="string"&&H.has(be[pe])));if(!ie.length||ie.includes(oe.parent))return null;const re=$.flatMap(pe=>{const me=K.get(pe);return me?[{anchor:pe,box:me}]:[]});if(!re.length)return null;const d=oe.x-U.x,y=oe.y-U.y,w=re.map(({box:pe})=>({...pe,x:pe.x+d,y:pe.y+y})),M=[...K].filter(([pe])=>!H.has(pe)).map(([,pe])=>pe),D=bn(p.current);D&&M.push(D),M.push(...Vs(W.current.elements));const z=Qr(w,M,{x:d,y}),Q=d+z.x,S=y+z.y;return{sources:$,sourceSet:H,boxes:K,primary:B,roots:ie,moving:re,slot:oe,dx:Q,dy:S}},[Zo]),qn=x.useCallback((f,N)=>{const $=[...new Set(typeof f=="string"?[f]:f)],H=$[0];if(!H)return null;const K=new Set($),B=48,U=D=>Math.min(38,Math.max(18,D*.32)),oe=Vt(W.current.tree),be=D=>{let z=D;const Q=new Set;for(;typeof z=="string"&&z&&!Q.has(z);){if(K.has(z))return!0;Q.add(z),z=oe[z]}return!1},re=[...yn(p.current)].filter(([D])=>!K.has(D)&&!be(D)),d=bn(p.current);d&&re.push([we,d]);let y=null;for(const[D,z]of re){if(N.x<z.x-B||N.x>z.x+z.w+B||N.y<z.y-B||N.y>z.y+z.h+B)continue;const Q=U(z.w),S=U(z.h),pe=18,me=[["e",Math.abs(z.x+z.w-N.x),N.x>z.x+z.w?B:Q,N.y>=z.y-pe&&N.y<=z.y+z.h+pe],["w",Math.abs(N.x-z.x),N.x<z.x?B:Q,N.y>=z.y-pe&&N.y<=z.y+z.h+pe],["s",Math.abs(z.y+z.h-N.y),N.y>z.y+z.h?B:S,N.x>=z.x-pe&&N.x<=z.x+z.w+pe],["n",Math.abs(N.y-z.y),N.y<z.y?B:S,N.x>=z.x-pe&&N.x<=z.x+z.w+pe]];for(const[He,Ge,qe,it]of me){if(!it||Ge>qe)continue;const on=Ge/Math.max(1,qe);(!y||on<y.score)&&(y={node:D,side:He,rel:He==="e"||He==="w"?"child":"sibling",score:on})}}if(!y)return null;const w={node:y.node,side:y.side,rel:y.rel};return lo($,w)?{source:H,count:$.length,...w}:null},[lo]),hr=x.useCallback((f,N)=>{const $=W.current.getView(),H=lo(f,N);if(!$||!H)return!1;const{sources:K,sourceSet:B,boxes:U,primary:oe,roots:be,moving:ie,slot:re,dx:d,dy:y}=H,w=Vt(W.current.tree);let M=Vt(w);for(const Q of be)if(delete M[Q],re.parent){const S=Kr(M,Q,re.parent);if(S===M)return!1;M=S}let D=$.state.tr;for(const Q of Fn($)){const S=U.get(Q.anchor);B.has(Q.anchor)&&S&&(D=D.setNodeMarkup(Q.pos,void 0,{...Q.node.attrs,x:Math.round(S.x+d),y:Math.round(S.y+y)}))}const z=be.filter(Q=>(typeof w[Q]=="string"?w[Q]:"")!==re.parent);for(const Q of z)D=Cl(D,M,Q,re.parent);return cr($,D),W.current.onCommit(),z.length&&Qn(S=>{let pe=Vt(S);for(const me of be)delete pe[me],re.parent&&(pe=Kr(pe,me,re.parent));return pe})&&tt(),K.length===1?O(oe,{x:d,y}):A(ie.map(({anchor:Q})=>({anchor:Q,x:d,y,depth:be.includes(Q)?1:2}))),pt(K.map(Ft)),!0},[lo,Qn,tt,A,O]),yo=x.useCallback((f,N)=>{const $=Vt(W.current.tree);if($[f]===N)return;const H=Kr($,f,N);if(H===$)return;const K=W.current.getView();let B=!1;if(K){const U=Cl(K.state.tr,H,f,N);U.steps.length&&(cr(K,U),B=!0)}We({t:H}),B&&tt()},[We,tt]),Do=x.useCallback((f,N,$)=>{const H=U=>U===we?we:U.startsWith("c:")?at(U):null,K=H(f),B=H(N);K&&B&&B!==we&&!$?yo(B,K):Ze(U=>hx(U,f,N))},[yo,Ze]),$r=x.useCallback((f,N,$)=>{Ze(H=>gx(H,new Set(f),{fromEnd:N,toEnd:$}))},[Ze]),Io=x.useCallback(async()=>{const f=W.current.getView(),N=p.current;if(!f||!N||!n)return;const $=W.current.storedMd,H=re=>$?.(re.content)?.trim()||re.textBetween(0,re.content.size,`
692
-
693
- `),K=yn(N),B=Fn(f).map(re=>{const d=re.node.attrs,y=K.get(re.anchor)??{x:Number(d.x)||0,y:Number(d.y)||0,w:Number(d.w)||en,h:Number(d.h)||80};return{ref:re.anchor,...y,color:d.color,md:H(re.node)}}),U=[];f.state.doc.forEach(re=>{re.type.name!=="amadeusCanvasCard"&&U.push(re)});const oe=bn(N),be=U.length?$?.(zo.fromArray(U))?.trim()??"":"",ie=Kb({cards:B,main:oe?{...oe,md:be}:null,elements:W.current.elements,tree:W.current.tree,pages:W.current.notePages?.(),sourcePath:e});try{const re=await Wb(rn,e,Vb(ie));hi({text:Te("canvasstage.export.done",{path:re}),level:"success"})}catch(re){hi({text:Te("canvasstage.export.failed",{e:_p(re)}),level:"error"})}},[n,e]);x.useEffect(()=>{if(!Z||!n||X)return;const f=()=>{Io()};return Z.current=f,()=>{Z.current===f&&(Z.current=null)}},[Z,n,X,Io]);const Xn=x.useCallback((f,N,$,H)=>{let K="";Ze(B=>(K=ps(B,"s"),[...B,H?yu(K,f,H):mx(K,f,N,$)])),K&&pt([vn(K)])},[Ze]),bo=x.useCallback((f,N,$=480,H=320)=>{let K="";Ze(B=>(K=ps(B,"f"),[...B,wx(K,f,N,$,H)])),K&&pt([vn(K)])},[Ze]),hn=x.useCallback(f=>{const N=Bn(null),$=f.map(U=>N.get(U)).filter(U=>!!U);if(!$.length)return;const H=32,K=Math.min(...$.map(U=>U.x))-H,B=Math.min(...$.map(U=>U.y))-H;bo(K,B,Math.max(...$.map(U=>U.x+U.w))+H-K,Math.max(...$.map(U=>U.y+U.h))+H-B)},[Bn,bo]),eo=x.useCallback(f=>{const N=Rn(W.current.elements),$=f.filter(B=>B.startsWith("e:")).map(B=>N.find(U=>U.id===at(B))).filter(B=>B?.kind==="frame");if(!$.length)return f;const H=Bn(null),K=new Set(f);for(const B of $)for(const[U,oe]of H)K.has(U)||oe.x>=B.x&&oe.y>=B.y&&oe.x+oe.w<=B.x+B.w&&oe.y+oe.h<=B.y+B.h&&K.add(U);return[...K]},[Bn]),$t=x.useCallback((f,N)=>{const $=f.filter(ie=>ie.startsWith("e:")).map(at),H=f.filter(ie=>ie.startsWith("c:")).map(at),K=f.filter(ie=>ie.startsWith("t:")).map(at),B=H.length?W.current.getView():null,U=new Set(H),oe=B?Fn(B).filter(ie=>U.has(ie.anchor)).sort((ie,re)=>re.pos-ie.pos):[],be=oe.length>0&&($.length>0||K.length>0||yt(H));if(be&&xt(),K.length){const ie=Vt(W.current.tree),re=Vt(ie);let d=!1;for(const y of K)typeof re[y]<"u"&&(delete re[y],d=!0);d&&We({t:re},be?{snap:!1}:void 0)}if($.length){const ie=_o(W.current.elements),re=fx(ie,new Set($));re!==ie&&We({e:re},be?{snap:!1}:void 0)}if(B&&oe.length){let ie=B.state.tr;for(const re of oe)ie=ie.delete(re.pos,re.pos+re.node.nodeSize);cr(B,ie),N?.assets!==!1&&W.current.onBlocksDeleted?.(zo.from(oe.map(re=>re.node).reverse())),W.current.onCommit(),be&&tt()}pt([])},[We,xt,yt,tt]),Ut=x.useCallback(f=>{const N=W.current.getView(),$=new Set(eo(f).filter(z=>z!==we&&!z.startsWith("t:"))),H=new Set([...$].filter(z=>z.startsWith("c:")).map(at)),K=N?Fn(N).filter(z=>H.has(z.anchor)):[],B=new Set(K.map(z=>z.anchor)),U=_o(W.current.elements),oe=z=>{const Q=z&&typeof z=="object"?z.id:null;return typeof Q=="string"&&Q?Q:null},be=z=>!!z&&typeof z=="object"&&z.type==="connector",ie=U.filter(z=>!be(z)&&$.has(vn(oe(z)??""))),re=new Set(ie.map(oe)),d=z=>{const Q=ra(z);return!!Q&&(Q.ref?B.has(Q.ref):Q.id?re.has(Q.id):!1)},y=U.filter(z=>be(z)&&oe(z)&&d(z.from)&&d(z.to)),w=Vt(W.current.tree),M=[...B].flatMap(z=>typeof w[z]=="string"&&B.has(w[z])?[[z,w[z]]]:[]);if(!K.length&&!ie.length&&!y.length)return null;const D=[...ie,...y];return{cards:K,els:D,tree:M,keys:[...K.map(z=>Ft(z.anchor)),...D.map(z=>vn(oe(z)))]}},[eo]),vo=x.useCallback((f,N,$,H,K)=>{const B=W.current,U=B.getView(),oe=U?.state.schema.nodes.amadeusCanvasCard,be=U?.state.schema.nodes.paragraph;if(!U||!oe||!be)return;const ie=new Map,re=[];let d=U.state.tr;for(const me of f){const He=Ao(d.doc),Ge=Math.round(me.x+H),qe=Math.round(me.y+K);let it=null;if(me.node&&me.node.type===oe)it=oe.create({...me.node.attrs,anchor:He,x:Ge,y:qe},me.node.content);else{const on=El(me.md?.trim()?B.parseMd?.(me.md.trim())??null:null)??be.create(null,me.md?.trim()?U.state.schema.text(me.md.trim()):void 0);it=oe.createAndFill({anchor:He,x:Ge,y:qe,w:Math.round(me.w)||en,h:Math.round(me.h)||0,color:typeof me.color=="string"?me.color:""},on)}it&&(d=d.insert(d.doc.content.size,it),ie.set(me.ref,He),re.push(He))}const y=re.length>0;y&&(cr(U,d),re.forEach(me=>B.onCommit(me)));const w=_o(W.current.elements),M=new Map,D=[],z=me=>me.type==="frame"?"f":me.type==="connector"?"e":"s",Q=[];for(const me of N){const He=me;if(typeof He.id!="string"||!He.id)continue;if(He.type==="connector"){Q.push(He);continue}const Ge=ps(w,z(He));M.set(He.id,Ge),w.push({...He,id:Ge,...typeof He.x=="number"?{x:Math.round(He.x+H)}:{},...typeof He.y=="number"?{y:Math.round(He.y+K)}:{}}),D.push(Ge)}const S=me=>{const He=ra(me);if(!He)return null;const Ge=me;if(He.ref){const qe=ie.get(He.ref);return qe?{...Ge,ref:qe}:null}if(He.id){const qe=M.get(He.id);return qe?{...Ge,id:qe}:null}return null};for(const me of Q){const He=S(me.from),Ge=S(me.to);if(!He||!Ge)continue;const qe=ps(w,"e");w.push({...me,id:qe,from:He,to:Ge}),D.push(qe)}let pe=null;for(const[me,He]of $){const Ge=ie.get(me),qe=ie.get(He);if(!Ge||!qe)continue;const it=Kr(pe??Vt(W.current.tree),Ge,qe);it!==pe&&(pe=it)}(D.length||pe)&&(We({...D.length?{e:w}:{},...pe?{t:pe}:{}}),y&&tt()),pt([...re.map(Ft),...D.map(vn)])},[We,tt]),wo=x.useCallback((f,N)=>{f.clearData();const $=Ut(N);if(!$)return Ba=null,f.setData("text/plain",""),null;const H=W.current.serializeMd,K=$.cards.map(ie=>H?.(ie.node.content)?.trim()||ie.node.textBetween(0,ie.node.content.size,`
694
-
695
- `)),B=$.els.flatMap(ie=>{const re=ie,d=re.type==="connector"?re.label:re.type==="frame"?re.title:re.text;return typeof d=="string"&&d.trim()?[d.trim()]:[]});f.setData("text/plain",[...K,...B].join(`
696
-
697
- `));const U=`t${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,oe=$.cards.map(ie=>{const re=ie.node.attrs;return{ref:ie.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}:{}}}),be={token:U,mds:K,cards:oe,...$.els.length?{els:$.els}:{},...$.tree.length?{tree:$.tree}:{}};try{f.setData(zl,JSON.stringify(be))}catch{}return Ba={token:U,nodes:$.cards.map(ie=>ie.node)},Uo.current=0,$},[Ut]),T=x.useCallback((f,N)=>{const $=W.current.getView();if(!$)return!1;const H=Ba,K=!!H&&H.token===f.token&&(H.nodes.length===0||H.nodes[0].type===$.state.schema.nodes.amadeusCanvasCard);let B;if(K&&H)B=H.nodes.map(ie=>({ref:String(ie.attrs.anchor),x:Number(ie.attrs.x)||0,y:Number(ie.attrs.y)||0,w:Number(ie.attrs.w)||en,h:Number(ie.attrs.h)||0,node:ie}));else if(f.cards)B=f.cards.map((ie,re)=>({...ie,md:f.mds[re]}));else{const ie=f.mds.filter(re=>re.trim());return ie.length?(ie.forEach((re,d)=>te.current.addCardMd(re,N,d)),!0):!1}const U=f.els??[],oe=B.map(ie=>ie.x),be=B.map(ie=>ie.y);for(const ie of U){const re=ie;typeof re.x=="number"&&typeof re.y=="number"&&(oe.push(re.x),be.push(re.y))}return oe.length?(vo(B,U,f.tree??[],N.x-Math.min(...oe),N.y-Math.min(...be)),!0):!1},[vo]),F=x.useCallback(f=>{const N=Ut(f);N&&vo(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,gi,gi)},[Ut,vo]),he=x.useCallback(f=>{const N=$=>{$.clipboardData&&($.preventDefault(),$.stopImmediatePropagation(),wo($.clipboardData,f))};document.addEventListener("copy",N,{capture:!0,once:!0});try{document.execCommand("copy")}finally{document.removeEventListener("copy",N,{capture:!0})}p.current?.focus({preventScroll:!0})},[wo]),ve=x.useCallback((f,N)=>{const $=W.current.getView();if(!$||f!==we&&!f.startsWith("c:"))return;let H=null,K=null;if(f===we)$.state.doc.forEach((B,U)=>{H==null&&B.type.name!=="amadeusCanvasCard"&&(H=Math.min($.state.doc.content.size,U+B.nodeSize-1))}),K=B=>{const U=$.state.doc.resolve(B);for(let oe=U.depth;oe>0;oe--)if(U.node(oe).type.name==="amadeusCanvasCard")return!1;return!0};else{const B=Fn($).find(U=>U.anchor===at(f));B&&(H=Math.min($.state.doc.content.size,B.pos+B.node.nodeSize-1),K=U=>U>B.pos&&U<B.pos+B.node.nodeSize)}if(H!=null){if(N){const B=$.posAtCoords({left:N.x,top:N.y});B&&K?.(B.pos)&&(H=B.pos)}try{$.dispatch(Qs($.state.tr.setSelection(je.near($.state.doc.resolve(H),-1))))}catch{}Wn(f===we?we:at(f)),$.focus()}},[]),$e=x.useCallback((f,N=!1)=>{const $=p.current;if(!$)return;const H=f===we?bn($):f.startsWith("c:")?yn($).get(at(f))??null:null;if(!H)return;const K=zn($)||1,B=$.getBoundingClientRect(),U=B.width/K,oe=B.height/K,be=Math.max(Jr,Math.min(1.5,Ls,U*.62/Math.max(1,H.w),oe*.72/Math.max(1,H.h))),ie={z:be,x:U/2-(H.x+H.w/2)*be,y:oe/2-(H.y+H.h/2)*be},re={...se.current};if(Oe(),window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)se.current=ie,ce(ie);else{const d=Math.hypot(ie.x-re.x,ie.y-re.y),y=Math.round(Math.max(460,Math.min(560,420+d*.12+Math.abs(ie.z-re.z)*120))),w=performance.now();To(!0);const M=D=>{const z=Math.min(1,(D-w)/y),Q=z>=1?1:1-Math.exp(-8*z)*(Math.cos(6*z)+8/6*Math.sin(6*z)),S={x:re.x+(ie.x-re.x)*Q,y:re.y+(ie.y-re.y)*Q,z:re.z+(ie.z-re.z)*Q};se.current=S,ce(S),z<1?Vn.current=requestAnimationFrame(M):(Vn.current=0,To(!1))};Vn.current=requestAnimationFrame(M)}N||(Wn(null),pt([f]),$.focus({preventScroll:!0}))},[Oe]),Ne=x.useCallback(f=>{const N=p.current,$=W.current.getView();if(!N||!$)return!1;const H=Vt(W.current.tree),K=yn(N),B=new Set(K.keys()),U=ft=>Cr(H,ft).filter(ot=>B.has(ot)).sort((ot,Lt)=>(K.get(ot)?.y??0)-(K.get(Lt)?.y??0)),oe=[],be=new Map,ie=new Set([f]),re=(ft,ot)=>{for(const Lt of U(ft))ie.has(Lt)||(ie.add(Lt),oe.push(Lt),be.set(Lt,ot+1),re(Lt,ot+1))};if(re(f,0),!oe.length)return!1;const d=f===we?bn(N):K.get(f);if(!d)return!1;const y=96,w=32,M=new Map,D=ft=>{const ot=ft===f?d:K.get(ft);if(!ot)return 0;const Lt=U(ft).filter(Pn=>Pn!==f&&ie.has(Pn)),kn=Lt.reduce((Pn,gn)=>Pn+D(gn),0)+Math.max(0,Lt.length-1)*w,Ot=Math.max(ot.h,kn);return M.set(ft,Ot),Ot};D(f);const z=U(f).filter(ft=>ft!==f&&ie.has(ft)),Q=ft=>{const ot=new Map,Lt=(kn,Ot,Pn)=>{const gn=U(kn).filter(Qt=>Qt!==f&&ie.has(Qt));if(!gn.length)return;const gt=gn.reduce((Qt,$n)=>Qt+(M.get($n)??D($n)),0)+(gn.length-1)*w;let xn=Ot.y+Ot.h/2-gt/2;for(const Qt of gn){const $n=K.get(Qt);if(!$n)continue;const gr=M.get(Qt)??$n.h,Po={x:Pn>0?Ot.x+Ot.w+y:Ot.x-y-$n.w,y:xn+(gr-$n.h)/2,w:$n.w,h:$n.h};ot.set(Qt,Po),Lt(Qt,Po,Pn),xn+=gr+w}};for(const kn of[1,-1]){const Ot=z.filter(gt=>ft.get(gt)===kn),Pn=Ot.reduce((gt,xn)=>gt+(M.get(xn)??D(xn)),0)+Math.max(0,Ot.length-1)*w;let gn=d.y+d.h/2-Pn/2;for(const gt of Ot){const xn=K.get(gt);if(!xn)continue;const Qt=M.get(gt)??xn.h,$n={x:kn>0?d.x+d.w+y:d.x-y-xn.w,y:gn+(Qt-xn.h)/2,w:xn.w,h:xn.h};ot.set(gt,$n),Lt(gt,$n,kn),gn+=Qt+w}}return ot},S=[],pe=new Set,me=ft=>{const ot=ft.join(",");pe.has(ot)||(pe.add(ot),S.push(new Map(z.map((Lt,kn)=>[Lt,ft[kn]]))))};if(z.length<=9)for(let ft=0;ft<2**z.length;ft++)me(z.map((ot,Lt)=>ft&1<<Lt?-1:1));else me(z.map((ft,ot)=>ot%2?-1:1)),me(z.map((ft,ot)=>ot<Math.ceil(z.length/2)?1:-1)),me(z.map(()=>1)),me(z.map(()=>-1));me(z.map(ft=>(K.get(ft)?.x??d.x)<d.x?-1:1));const He=Bn(null),Ge=new Set(oe.map(Ft)),qe=[...He].filter(([ft])=>!Ge.has(ft)).map(([,ft])=>Ha(ft,24));let it=null;for(const ft of S){const ot=z.filter(gt=>ft.get(gt)===-1).length;if(z.length>1&&(ot===0||ot===z.length))continue;const Lt=Q(ft),kn=[...Lt.values()],Ot=Math.min(...kn.map(gt=>gt.y)),Pn=Math.max(...kn.map(gt=>gt.y+gt.h)),gn=new Set([0]);for(let gt=1;gt<=20;gt++)gn.add(gt*72),gn.add(-gt*72);for(const gt of qe)gn.add(Math.ceil(gt.y+gt.h+12-Ot)),gn.add(Math.floor(gt.y-12-Pn));qe.length&&(gn.add(Math.ceil(Math.max(...qe.map(gt=>gt.y+gt.h))+12-Ot)),gn.add(Math.floor(Math.min(...qe.map(gt=>gt.y))-12-Pn)));for(const gt of[...gn].sort((xn,Qt)=>Math.abs(xn)-Math.abs(Qt))){const xn=new Map([...Lt].map(([Gn,to])=>[Gn,{...to,y:to.y+gt}]));let Qt=0;for(const Gn of xn.values())for(const to of qe)Al(Ha(Gn,12),to)&&Qt++;const $n=Gn=>{const to=z.filter(uo=>ft.get(uo)===Gn).map(uo=>M.get(uo)??0);return to.reduce((uo,er)=>uo+er,0)+Math.max(0,to.length-1)*w},gr=$n(1),Po=$n(-1),As=[...xn].reduce((Gn,[to,uo])=>{const er=K.get(to);return Gn+(er?Math.hypot(uo.x-er.x,uo.y-er.y):0)},0),Xt=Qt*1e6+Math.abs(gt)+Math.max(gr,Po)*.18+Math.abs(gr-Po)*.04+As*.002+ot*2;(!it||Xt<it.score)&&(it={plan:xn,score:Xt})}}if(!it)return!1;const on=new Map([...it.plan].map(([ft,ot])=>[ft,{x:Math.round(ot.x),y:Math.round(ot.y)}])),fn=[...on].flatMap(([ft,ot])=>{const Lt=K.get(ft);return Lt?[{anchor:ft,x:ot.x-Lt.x,y:ot.y-Lt.y,depth:be.get(ft)??1}]:[]});return kr($,on),A(fn),W.current.onCommit(),N.focus({preventScroll:!0}),!0},[Bn,A]);x.useEffect(()=>{const f=p.current;!n||!f||document.activeElement&&f.contains(document.activeElement)||f.focus({preventScroll:!0})},[n]);const te=x.useRef({mutate:Ze,writeFm:We,mergePair:tt,pushFmCheckpoint:xt,treeTouches:yt,removeSel:$t,editText:jo,boxesNow:Bn,fit:nn,zoomBy:Un,addCardAt:io,addShapeAt:Xn,addFrame:bo,addRelated:Qo,attachHit:qn,applyAttach:hr,setNodeParent:yo,expandFrames:eo,enterNodeEdit:ve,focusNode:$e,arrangeChildren:Ne,stopArrangeMotion:g,stopFocusMotion:Oe,dropFilesAt:Jo,addCardMd:Ro,writeClip:wo,pastePayload:T,linkNodes:Do});te.current={mutate:Ze,writeFm:We,mergePair:tt,pushFmCheckpoint:xt,treeTouches:yt,removeSel:$t,editText:jo,boxesNow:Bn,fit:nn,zoomBy:Un,addCardAt:io,addShapeAt:Xn,addFrame:bo,addRelated:Qo,attachHit:qn,applyAttach:hr,setNodeParent:yo,expandFrames:eo,enterNodeEdit:ve,focusNode:$e,arrangeChildren:Ne,stopArrangeMotion:g,stopFocusMotion:Oe,dropFilesAt:Jo,addCardMd:Ro,writeClip:wo,pastePayload:T,linkNodes:Do},x.useEffect(()=>{const f=p.current;if(!n||!f||typeof ResizeObserver>"u")return;const N=new Set,$=new WeakMap;let H=0,K=!1;const B=()=>{if(H=0,K)return;const re=sn.current,d=W.current.getView();if(!re||!d)return;const y=yn(f),w=re===we?bn(f):y.get(re);if(!w)return;const M=[...y].filter(([S,pe])=>S!==re&&Al(Ha(w,18),pe));if(!M.length)return;const D=new Map(y),z=new Map,Q=[];for(const[S,pe]of M){const me=[...D].filter(([on])=>on!==S).map(([,on])=>on),He=bn(f);He&&re!==we&&me.push(He),me.push(...Vs(W.current.elements));const Ge={x:pe.x+pe.w/2-(w.x+w.w/2),y:pe.y+pe.h/2-(w.y+w.h/2)},qe=Qr([pe],me,Ge);if(!qe.x&&!qe.y)continue;const it={...pe,x:pe.x+qe.x,y:pe.y+qe.y};D.set(S,it),z.set(S,{x:Math.round(it.x),y:Math.round(it.y)}),Q.push({anchor:S,x:qe.x,y:qe.y,depth:1})}z.size&&(K=!0,kr(d,z,!1),A(Q),W.current.onCommit(),requestAnimationFrame(()=>{K=!1}))},U=()=>{window.clearTimeout(H),H=window.setTimeout(B,90)},oe=new ResizeObserver(re=>{for(const d of re){const y=d.target,w={w:y.offsetWidth,h:y.offsetHeight},M=$.get(y);if($.set(y,w),M&&(M.w!==w.w||M.h!==w.h)){const D=y.classList.contains("amx-ucard")?y.dataset.anchor:we;D&&D===sn.current&&U()}}}),be=()=>{const re=new Set(f.querySelectorAll(".amx-ucard")),d=f.querySelector(".ProseMirror");d&&re.add(d);for(const y of re)N.has(y)||(N.add(y),$.set(y,{w:y.offsetWidth,h:y.offsetHeight}),oe.observe(y,{box:"border-box"}));for(const y of[...N])re.has(y)||(N.delete(y),oe.unobserve(y))};be();const ie=new MutationObserver(be);return ie.observe(f,{subtree:!0,childList:!0}),()=>{window.clearTimeout(H),ie.disconnect(),oe.disconnect()}},[n,e,A]),x.useEffect(()=>{if(!n||q<=0)return;ne.current=!1;let f=0;const N=requestAnimationFrame(()=>{f=requestAnimationFrame(()=>{const $=W.current.getView();if(!$)return;const{$from:H}=$.state.selection;let K=we;for(let B=H.depth;B>0;B--){const U=H.node(B);if(U.type.name==="amadeusCanvasCard"){K=Ft(String(U.attrs.anchor));break}}pt([K]),Wn(K===we?we:at(K)),te.current.focusNode(K,!0),$.focus()})});return()=>{cancelAnimationFrame(N),cancelAnimationFrame(f)}},[n,q]),x.useEffect(()=>{const f=p.current;if(!f||!n)return;const N=()=>W.current.getView(),$=b=>W.current.onCommit(b),H=()=>f.focus({preventScroll:!0}),K=`s${++Jb}`;f.dataset.amxDragscope=K;const B=document.createElement("style");document.head.appendChild(B);let U=[],oe=0;const be=(b,L=!1)=>`left:${b.x}px!important;top:${b.y}px!important;${L&&"w"in b&&"h"in b?`width:${b.w}px!important;height:${b.h}px!important;`:""}`,ie=`.amx-stage[data-amx-dragscope="${K}"] .unified-gutter{visibility:hidden!important;pointer-events:none!important}`,re=(b,L)=>{const ue=[];for(const Ee of b){const ke=CSS.escape(Ee.anchor);ue.push(`.amx-stage[data-amx-dragscope="${K}"] .amx-ucard[data-anchor="${ke}"]{${Ee.decl}}`),ue.push(`.amx-stage[data-amx-dragscope="${K}"] .amx-el-selbox[data-anchor="${ke}"]{${be(Ee.selection)}}`)}L&&ue.push(`.amx-stage[data-amx-dragscope="${K}"] .amx-el-selbox[data-main-sel]{${be(L)}}`),ue.push(ie),B.textContent=ue.join(`
698
- `)},d=(b,L,ue)=>{const Ee=b===we?`.amx-stage[data-amx-dragscope="${K}"] .ProseMirror:not(.unified-embed .ProseMirror){${L}}`:`.amx-stage[data-amx-dragscope="${K}"] .amx-ucard[data-anchor="${CSS.escape(b)}"]{${L}}`,ke=b===we?`.amx-stage[data-amx-dragscope="${K}"] .amx-el-selbox[data-main-sel]{${be(ue,!0)}}`:`.amx-stage[data-amx-dragscope="${K}"] .amx-el-selbox[data-anchor="${CSS.escape(b)}"]{${be(ue,!0)}}`;B.textContent=`${Ee}
699
- ${ke}
700
- ${ie}`},y="cursor:grabbing;opacity:.94;box-shadow:0 12px 32px rgb(0 0 0 / 24%);z-index:1;",w=()=>{B.textContent=""},M=()=>{cancelAnimationFrame(oe),oe=0;for(const b of U)b.cancel();U=[]},D=(b,L,ue,Ee="amx-card-repel")=>{const ke=Math.hypot(ue.x,ue.y);if(ke<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;M();const Ie=Math.round(Math.max(340,Math.min(480,320+ke*.55))),De=[{transform:`translate(${-ue.x}px, ${-ue.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(${ue.x*.06}px, ${ue.y*.06}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-ue.x*.015}px, ${-ue.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}];oe=requestAnimationFrame(()=>{oe=0;const lt=b.map(vt=>f.querySelector(`.amx-ucard[data-anchor="${CSS.escape(vt)}"]`)).filter(vt=>!!vt);if(L){const vt=f.querySelector(".ProseMirror");vt&&lt.push(vt)}for(const vt of lt){const Le=vt.animate(De,{duration:Ie,fill:"none"});Le.id=Ee,U.push(Le);const Ue=()=>{U=U.filter(wt=>wt!==Le)};Le.addEventListener("finish",Ue,{once:!0}),Le.addEventListener("cancel",Ue,{once:!0})}})},z=(b,L,ue)=>{Math.max(Math.abs(L.x-ue.x),Math.abs(L.y-ue.y),Math.abs(L.w-ue.w),Math.abs(L.h-ue.h))<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(M(),oe=requestAnimationFrame(()=>{oe=0;const ke=b===we?f.querySelector(".ProseMirror"):f.querySelector(`.amx-ucard[data-anchor="${CSS.escape(b)}"]`);if(!ke)return;const Ie=b===we?{marginLeft:`${L.x}px`,marginTop:`${L.y}px`,width:`${L.w}px`,height:`${L.h}px`}:{left:`${L.x}px`,top:`${L.y}px`,width:`${L.w}px`,height:`${L.h}px`},De=b===we?{marginLeft:`${ue.x}px`,marginTop:`${ue.y}px`,width:`${ue.w}px`,height:`${ue.h}px`}:{left:`${ue.x}px`,top:`${ue.y}px`,width:`${ue.w}px`,height:`${ue.h}px`},lt=ke.animate([Ie,De],{duration:220,easing:"cubic-bezier(0.2, 0.78, 0.28, 1)",fill:"none"});lt.id="amx-card-snap",U.push(lt);const vt=()=>{U=U.filter(Le=>Le!==lt)};lt.addEventListener("finish",vt,{once:!0}),lt.addEventListener("cancel",vt,{once:!0})}))},Q=b=>{if(b.target?.closest?.(".amx-stage-minimap"))return;te.current.stopFocusMotion(),b.preventDefault();const{x:L,y:ue,z:Ee}=se.current,ke=zn(f)||1;if(b.metaKey||b.ctrlKey){const Ie=b.ctrlKey&&!b.metaKey?Ub:1,De=Math.max(Jr,Math.min(Ls,Ee*Math.exp(-b.deltaY*Ie/300))),lt=f.getBoundingClientRect(),vt=(b.clientX-lt.left)/ke,Le=(b.clientY-lt.top)/ke;ce({z:De,x:vt-(vt-L)*De/Ee,y:Le-(Le-ue)*De/Ee})}else{const Ie=b.shiftKey&&!b.deltaX?b.deltaY:b.deltaX,De=b.shiftKey?0:b.deltaY;ce({z:Ee,x:L-Ie/ke,y:ue-De/ke})}};f.addEventListener("wheel",Q,{passive:!1});let S=null,pe=-1;const me=b=>{pe=b;try{f.setPointerCapture(b)}catch{}},He=b=>{try{f.hasPointerCapture(b)&&f.releasePointerCapture(b)}catch{}},Ge=()=>Jp/(se.current.z*(zn(f)||1)),qe=(b,L,ue)=>{const Ee=[];for(const[Ie,De]of yn(f))b.has(Ie)||Ee.push(De);const ke=L?null:bn(f);ke&&Ee.push(ke);for(const[Ie,De]of Ar(Rn(W.current.elements),null))ue.has(Ie)||Ee.push(De);return Ee},it=(b,L)=>{const ue=document.elementFromPoint(b,L);if(!ue||!f.contains(ue))return null;const Ee=ue.closest(as);if(Ee?.dataset.el)return vn(Ee.dataset.el);const ke=ue.closest("[data-card-grip]");if(ke?.dataset.cardGrip)return ke.dataset.cardGrip===we?we:Ft(ke.dataset.cardGrip);const Ie=ue.closest(".amx-ucard");return Ie?.dataset.anchor?Ft(Ie.dataset.anchor):ue.closest(".ProseMirror")?we:null},on=b=>b===f||b.classList.contains("amx-stage-inner")||b.classList.contains("amx-el-layer"),fn=new Map;let ft=null,ot=null,Lt=0,kn=null,Ot=xi;const Pn=()=>{Gn();const b=S;S=null,b&&b.kind!=="pan"&&tr(b)},gn=()=>{const[b,L]=[...fn.keys()],ue=fn.get(b),Ee=fn.get(L);if(!ue||!Ee)return null;const ke=zn(f)||1,Ie=f.getBoundingClientRect();return{x:((ue.x+Ee.x)/2-Ie.left)/ke,y:((ue.y+Ee.y)/2-Ie.top)/ke,d:Math.hypot(ue.x-Ee.x,ue.y-Ee.y)/ke,ids:`${b}/${L}`}},gt=()=>{const b=gn();if(!b)return;const{x:L,y:ue,z:Ee}=se.current;ot={d0:Math.max(1,b.d),z0:Ee,sx:(b.x-L)/Ee,sy:(b.y-ue)/Ee,ids:b.ids}},xn=()=>{const b=gn();if(!b||!ot)return;if(b.ids!==ot.ids){gt();return}const L=Math.max(Jr,Math.min(Ls,ot.z0*b.d/ot.d0));ce({z:L,x:b.x-ot.sx*L,y:b.y-ot.sy*L})},Qt=()=>{Lt&&window.clearTimeout(Lt),Lt=0,kn=null},$n=b=>{const L=b.target,{clientX:ue,clientY:Ee}=b;kn={x:ue,y:Ee},Lt=window.setTimeout(()=>{Lt=0,kn=null,Dc(L,ue,Ee)==="open"&&Pn()},qp)},gr=b=>{const L=N(),ue=L?Fn(L).map(De=>De.anchor):[],Ee=new Set([...ue,we]),ke=Vt(W.current.tree);return[b===we?we:Ft(b),...ue.filter(De=>bu(ke,De,b,Ee)).map(Ft)]},Po=(b,L)=>{const ue=dt.current;if(L.shiftKey||L.metaKey||L.ctrlKey){const Ee=L.shiftKey&&(b===we||b.startsWith("c:"))?gr(b===we?we:at(b)):[b],ke=ue.includes(b)?ue.filter(Ie=>!Ee.includes(Ie)):[...ue,...Ee.filter(Ie=>!ue.includes(Ie))];return pt(ke),ke.includes(b)?ke:null}return ue.includes(b)?ue:(pt([b]),[b])},As=b=>{Dt(null);const L=b.target;if(L.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;if(M(),te.current.stopArrangeMotion(),te.current.stopFocusMotion(),b.pointerType==="touch"){if(fn.set(b.pointerId,{x:b.clientX,y:b.clientY}),Qt(),fn.size>=2){b.preventDefault(),Pn(),gt();return}$n(b)}if(ot)return;Ot=b.pointerType==="touch"?yi/(se.current.z*(zn(f)||1)):xi;const ue=b.button===1;if(b.button!==0&&!ue)return;const Ee=jt.current,ke=It(b.clientX,b.clientY);if(Et.current){if(L.closest(`${wl}, .wikilink`))return;const Ct=performance.now(),Tt=ft;if(ft=b.pointerType==="mouse"?{t:Ct,x:b.clientX,y:b.clientY}:null,Tt&&Ct-Tt.t<500&&Math.hypot(b.clientX-Tt.x,b.clientY-Tt.y)<6&&L.closest(".ProseMirror"))return;b.preventDefault(),S={kind:"pan",x0:b.clientX,y0:b.clientY,vx:se.current.x,vy:se.current.y},me(b.pointerId);return}const Ie=sn.current,De=Nn.current.held;De&&(Nn.current.used=!0);const lt=Ee==="pan"||b.altKey||ue||De,vt=Ee!=="select"&&!lt,Le=Ie===we?!!L.closest(".ProseMirror")&&!L.closest(".amx-ucard"):!!L.closest(`.amx-ucard[data-anchor="${CSS.escape(Ie??"")}"]`);if(Ie&&!lt&&(vt||!Le)&&Wn(null),lt){b.preventDefault(),S={kind:"pan",x0:b.clientX,y0:b.clientY,vx:se.current.x,vy:se.current.y},me(b.pointerId);return}if(_a.has(Ee)){b.preventDefault(),S={kind:"create",tool:Ee,x0:ke.x,y0:ke.y,x1:ke.x,y1:ke.y},me(b.pointerId);return}if(b.pointerType==="touch"&&(Ee==="card"||cs[Ee])){b.preventDefault(),S={kind:"create",tool:Ee,x0:ke.x,y0:ke.y,x1:ke.x,y1:ke.y},me(b.pointerId);return}if(cs[Ee]){b.preventDefault(),te.current.addShapeAt(cs[Ee],ke.x,ke.y),Gt("select"),H();return}if(Ee==="card"){b.preventDefault();const Ct=te.current.addCardAt(ke.x-en/2,ke.y-24);Gt("select"),Ct||H();return}const Ue=L.closest("[data-grip]"),wt=L.closest("[data-card-grip][data-card-edge]"),Bt=L.closest(as),kt=L.closest(".amx-ucard"),jn=L.closest(".ProseMirror"),fo=!kt&&!Bt&&!!jn&&L===jn,So=!kt&&!Bt&&!!jn&&L!==jn,xr=!!kt&&L===kt,On=kt?.dataset.anchor??null;if(Ee==="select"&&wt?.dataset.cardGrip&&wt.dataset.cardEdge){const Ct=wt.dataset.cardGrip,Tt=Ct===we,cn=Tt?bn(f):yn(f).get(Ct),ln=Tt?null:N(),Kn=ln?Fn(ln).find(no=>no.anchor===Ct):null;cn&&(Tt||Kn)&&(b.preventDefault(),H(),pt([Tt?we:Ft(Ct)]),S={kind:"card-size",key:Ct,edge:wt.dataset.cardEdge,b0:cn,h0:Tt?Number(W.current.main.h)||0:Number(Kn.node.attrs.h)||0,x0:ke.x,y0:ke.y,dx:0,dy:0,next:cn},me(b.pointerId));return}const yr=Ee==="select"?L.closest("[data-link-from]"):null;if(yr?.dataset.linkFrom){b.preventDefault(),H(),S={kind:"link",from:yr.dataset.linkFrom,x0:ke.x,y0:ke.y},me(b.pointerId);return}const nr=Ee==="select"?L.closest("[data-conn-end]"):null;if(nr?.dataset.connEnd&&nr.dataset.el){const Ct=Rn(W.current.elements).find(ln=>ln.id===nr.dataset.el),Tt=nr.dataset.connEnd==="from"?"from":"to",cn=Ct?.kind==="connector"?wr(Tt==="from"?Ct.to:Ct.from):null;b.preventDefault(),H(),Ct&&cn&&(S={kind:"reconnect",id:Ct.id,end:Tt,fixed:cn,x0:ke.x,y0:ke.y},me(b.pointerId));return}const Rr=L.closest(wl)?On??(jn?we:null):null;if(Ee==="select"&&Rr){Wn(Rr);return}const Lr=kt&&On?On:So?we:null;Ee==="select"&&Lr&&sn.current!==Lr&&Gb(L,b.clientX)&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("canvasstage.toast.needEdit")}}));const St=b.pointerType==="touch"&&Ee==="select"?Bt?.dataset.el?vn(Bt.dataset.el):On?Ft(On):!kt&&jn?we:null:null;if(St&&!dt.current.includes(St)&&sn.current!==(On??we)){b.preventDefault(),S={kind:"pan",x0:b.clientX,y0:b.clientY,vx:se.current.x,vy:se.current.y,tapKey:St},me(b.pointerId);return}if(kt&&On&&!xr&&Ee==="select"){if(sn.current===On)return;b.preventDefault(),H();const Ct=b.shiftKey||b.metaKey||b.ctrlKey,Tt=Ft(On),cn=Po(Tt,b);if(!cn)return;const ln=cn,Kn=[];for(const no of ln){if(!no.startsWith("c:"))continue;const po=f.querySelector(`.amx-ucard[data-anchor="${CSS.escape(at(no))}"]`);po&&Kn.push({anchor:at(no),ox:Number(po.dataset.x)||0,oy:Number(po.dataset.y)||0})}S={kind:"move",cards:Kn,ids:new Set(ln),hit:Tt,x0:ke.x,y0:ke.y,dx:0,dy:0,mainStart:null,mainEl:null,additive:Ct},me(b.pointerId);return}if(So&&Ee==="select"){if(sn.current===we)return;b.preventDefault(),H();const Ct=b.shiftKey||b.metaKey||b.ctrlKey,Tt=Po(we,b);if(!Tt)return;const cn=Tt,ln=[];for(const Kn of cn){if(!Kn.startsWith("c:"))continue;const no=f.querySelector(`.amx-ucard[data-anchor="${CSS.escape(at(Kn))}"]`);no&&ln.push({anchor:at(Kn),ox:Number(no.dataset.x)||0,oy:Number(no.dataset.y)||0})}S={kind:"move",cards:ln,ids:new Set(cn),hit:we,x0:ke.x,y0:ke.y,dx:0,dy:0,mainStart:{x:W.current.main.x,y:W.current.main.y},mainEl:jn,additive:Ct},me(b.pointerId);return}const Co=Bt?.dataset.el?vn(Bt.dataset.el):On?Ft(On):fo?we:null;if(Ee==="conn"){b.preventDefault(),H();const Ct=Co??(!kt&&!Bt&&L.closest(".ProseMirror")?we:null);if(!Ct){An(null);return}const Tt=Jt.current;Tt?(te.current.linkNodes(Tt,Ct,b.shiftKey),An(null),Gt("select")):An(Ct);return}const $s=L.closest("[data-add]");if($s?.dataset.add&&$s.dataset.node){b.preventDefault(),H(),te.current.addRelated($s.dataset.node,$s.dataset.add==="child"?"child":"sibling");return}if(Ue?.dataset.grip){b.preventDefault();const Ct=Ar(Rn(W.current.elements),null).get(Ue.dataset.grip);if(!Ct)return;S={kind:"size",id:Ue.dataset.grip,corner:Ue.dataset.corner??"se",b0:Ct,dx:0,dy:0,dw:0,dh:0},me(b.pointerId);return}if(Co){b.preventDefault(),H();const Ct=b.shiftKey||b.metaKey||b.ctrlKey,Tt=Po(Co,b);if(!Tt)return;const cn=Tt;if(xr&&cn.length===1&&kt.dataset.anchor){const po=kt.getBoundingClientRect(),Fo=vl*se.current.z*(zn(f)||1);if(b.clientX>=po.right-Fo){const ha=yn(f).get(kt.dataset.anchor),qc=Fn(N()).find(rd=>rd.anchor===kt.dataset.anchor);if(!ha||!qc)return;S={kind:"card-size",key:kt.dataset.anchor,edge:"e",b0:ha,h0:Number(qc.node.attrs.h)||0,x0:ke.x,y0:ke.y,dx:0,dy:0,next:ha},me(b.pointerId);return}}if(Co===we&&cn.length===1&&jn){const po=jn.getBoundingClientRect();if(b.clientX>po.right-vl*se.current.z*(zn(f)||1)){const Fo=bn(f);if(!Fo)return;S={kind:"card-size",key:we,edge:"e",b0:Fo,h0:Number(W.current.main.h)||0,x0:ke.x,y0:ke.y,dx:0,dy:0,next:Fo},me(b.pointerId);return}}const ln=te.current.expandFrames(cn),Kn=[];for(const po of ln){if(!po.startsWith("c:"))continue;const Fo=f.querySelector(`.amx-ucard[data-anchor="${CSS.escape(at(po))}"]`);Fo&&Kn.push({anchor:at(po),ox:Number(Fo.dataset.x)||0,oy:Number(Fo.dataset.y)||0})}const no=ln.includes(we);S={kind:"move",cards:Kn,ids:new Set(ln),hit:Co,x0:ke.x,y0:ke.y,dx:0,dy:0,mainStart:no?{x:W.current.main.x,y:W.current.main.y}:null,mainEl:no?f.querySelector(".ProseMirror"):null,additive:Ct,growSel:ln.length>Tt.length?[...ln]:void 0},me(b.pointerId);return}if(!on(L))return;const js=te.current.boxesNow(null),pa=Rn(W.current.elements).find(Ct=>{if(Ct.kind!=="connector")return!1;const Tt=wr(Ct.from),cn=wr(Ct.to),ln=Tt?js.get(Tt):null,Kn=cn?js.get(cn):null;return!!ln&&!!Kn&&Bs(ln,Kn,ke,8/se.current.z)}),Vc=pa?null:Fu(W.current.tree).find(([Ct,Tt])=>{const cn=js.get(Ft(Ct)),ln=js.get(Tt===we?we:Ft(Tt));return!!cn&&!!ln&&Bs(ln,cn,ke,8/se.current.z)});if(b.preventDefault(),H(),pa){pt([vn(pa.id)]);return}if(Vc){pt([Ou(Vc[0])]);return}const ma=b.shiftKey||b.metaKey||b.ctrlKey,od=ma?[...dt.current]:[];if(ma||pt([]),b.pointerType==="touch"){S={kind:"pan",x0:b.clientX,y0:b.clientY,vx:se.current.x,vy:se.current.y},me(b.pointerId);return}S={kind:"marquee",x0:ke.x,y0:ke.y,additive:ma,base:od},me(b.pointerId)},Xt={raf:0,t:0,x:0,y:0,id:-1,type:"mouse"},Gn=()=>{Xt.raf&&cancelAnimationFrame(Xt.raf),Xt.raf=0},to=()=>{const b=f.getBoundingClientRect();return{left:Math.max(b.left,0),top:Math.max(b.top,0),right:Math.min(b.right,window.innerWidth),bottom:Math.min(b.bottom,window.innerHeight)}},uo=b=>Et.current||ot?!1:S?S.kind!=="pan"&&S.live===!0:jt.current==="conn"&&!!Jt.current&&!b?.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"),er=b=>{Xt.raf=0;const L=document.elementFromPoint(Xt.x,Xt.y);if(!uo(L))return;const{vx:ue,vy:Ee}=wi(to(),Xt.x,Xt.y);if(!ue&&!Ee)return;const ke=Math.min(.05,Math.max(0,(b-Xt.t)/1e3));Xt.t=b;const Ie=zn(f)||1,De={...se.current,x:se.current.x-ue*ke/Ie,y:se.current.y-Ee*ke/Ie};se.current=De,ce(De),jc({clientX:Xt.x,clientY:Xt.y,pointerId:Xt.id,pointerType:Xt.type,target:L??f}),Xt.raf=requestAnimationFrame(er)},ed=b=>{if(S&&pe!==b.pointerId)return;Xt.x=b.clientX,Xt.y=b.clientY,Xt.id=b.pointerId,Xt.type=b.pointerType;const{vx:L,vy:ue}=uo(b.target)?wi(to(),b.clientX,b.clientY):{vx:0,vy:0};if(!L&&!ue){Gn();return}Xt.raf||(Xt.t=performance.now(),Xt.raf=requestAnimationFrame(er))},Tc=()=>{S||Gn()},$c=b=>{jc(b),ed(b)},jc=b=>{if(b.pointerType==="touch"&&(fn.has(b.pointerId)&&fn.set(b.pointerId,{x:b.clientX,y:b.clientY}),kn&&Math.hypot(b.clientX-kn.x,b.clientY-kn.y)>Wp&&Qt()),ot){xn();return}if(S&&pe!==b.pointerId)return;if(!S&&jt.current==="conn"&&Jt.current){const Le=b.target,Ue=Le.closest?.(as),wt=Le.closest?.(".amx-ucard");let Bt=Ue?.dataset.el?vn(Ue.dataset.el):wt?.dataset.anchor?Ft(wt.dataset.anchor):!wt&&Le.closest?.(".ProseMirror")?we:null;Bt===Jt.current&&(Bt=null);const kt=It(b.clientX,b.clientY);V({x:kt.x,y:kt.y,over:Bt});return}if(!S)return;const L=zn(f)||1;if(S.kind==="pan"){ce({...se.current,x:S.vx+(b.clientX-S.x0)/L,y:S.vy+(b.clientY-S.y0)/L});return}const ue=It(b.clientX,b.clientY);if(S.kind==="link"||S.kind==="reconnect"){(Math.abs(ue.x-S.x0)>Ot||Math.abs(ue.y-S.y0)>Ot)&&(S.live=!0);const Le=S.kind==="link"?S.from:S.fixed,Ue=it(b.clientX,b.clientY);le({from:Le,x:ue.x,y:ue.y,over:Ue===Le?null:Ue});return}if(S.kind==="card-size"){S.dx=ue.x-S.x0,S.dy=ue.y-S.y0;const Le=S.key===we;let Ue=Sl(S.b0,S.edge,S.dx,S.dy,!1,Le?Pa:Us);if((Math.abs(Ue.x-S.b0.x)>Ot||Math.abs(Ue.y-S.b0.y)>Ot||Math.abs(Ue.w-S.b0.w)>Ot||Math.abs(Ue.h-S.b0.h)>Ot)&&(S.live=!0),S.gx=!1,S.gy=!1,ye.current&&S.live){S.others||(S.others=qe(new Set(Le?[]:[S.key]),Le,new Set));const wt=Yp(Ue,S.edge,S.others,Ge(),Le?Pa:Us,Bu);Ue=wt.box,S.gx=wt.guides.v.length>0,S.gy=wt.guides.h.length>0,Fe(S.gx||S.gy?vi(Ue,S.others,wt.guides,1/se.current.z):null)}else Fe(null);S.next=Ue,d(S.key,Le?`margin-left:${Ue.x}px;margin-top:${Ue.y}px;width:${Ue.w}px;height:${Ue.h}px;${y}`:`left:${Ue.x}px;top:${Ue.y}px;width:${Ue.w}px;height:${Ue.h}px;${y}`,Ue),Mn({move:{ids:new Set([Le?we:Ft(S.key)]),dx:0,dy:0},size:null});return}if(S.kind==="size"){const Le=S.b0,Ue=S.corner.includes("e"),wt=S.corner.includes("s"),Bt=Math.max(ar,Math.round(Ue?ue.x-Le.x:Le.x+Le.w-ue.x)),kt=Math.max(ar,Math.round(wt?ue.y-Le.y:Le.y+Le.h-ue.y));S.dx=Ue?0:Le.w-Bt,S.dy=wt?0:Le.h-kt,S.dw=Bt-Le.w,S.dh=kt-Le.h,(Math.abs(S.dw)>Ot||Math.abs(S.dh)>Ot)&&(S.live=!0),Mn({move:null,size:{id:S.id,dx:S.dx,dy:S.dy,dw:S.dw,dh:S.dh}});return}if(S.kind==="create"){S.x1=ue.x,S.y1=ue.y,(Math.abs(S.x1-S.x0)>Ot||Math.abs(S.y1-S.y0)>Ot)&&(S.live=!0),_a.has(S.tool)&&Dn({x:Math.min(S.x0,ue.x),y:Math.min(S.y0,ue.y),w:Math.abs(ue.x-S.x0),h:Math.abs(ue.y-S.y0)});return}if(S.kind==="marquee"){S.live=!0;const Le={x:Math.min(S.x0,ue.x),y:Math.min(S.y0,ue.y),w:Math.abs(ue.x-S.x0),h:Math.abs(ue.y-S.y0)};Dn(Le);const Ue=[];for(const[wt,Bt]of te.current.boxesNow(null))pl(Le,Bt)&&Ue.push(wt);pt(S.additive?[...new Set([...S.base,...Ue])]:Ue);return}if(S.dx=Math.round(ue.x-S.x0),S.dy=Math.round(ue.y-S.y0),(Math.abs(S.dx)>Ot||Math.abs(S.dy)>Ot)&&(S.live=!0),!S.align){const Le=new Set(S.cards.map(fo=>fo.anchor)),Ue=new Set([...S.ids].filter(fo=>fo.startsWith("e:")).map(at)),wt=yn(f),Bt=Ar(Rn(W.current.elements),null),kt=[];for(const fo of Le){const So=wt.get(fo);So&&kt.push(So)}const jn=S.mainStart?bn(f):null;jn&&kt.push(jn);for(const fo of Ue){const So=Bt.get(fo);So&&kt.push(So)}S.align={base:Up(kt),others:qe(Le,!!S.mainStart,Ue)}}S.gx=!1,S.gy=!1;const Ee=S.align.base;if(ye.current&&S.live&&Ee){const Le=Xp({...Ee,x:Ee.x+S.dx,y:Ee.y+S.dy},S.align.others,Ge());S.dx+=Math.round(Le.dx),S.dy+=Math.round(Le.dy),S.gx=Le.guides.v.length>0,S.gy=Le.guides.h.length>0,Fe(S.gx||S.gy?vi({...Ee,x:Ee.x+S.dx,y:Ee.y+S.dy},S.align.others,Le.guides,1/se.current.z):null)}else Fe(null);S.live&&S.kind==="move"&&S.growSel&&(pt(S.growSel),S.growSel=void 0);const{dx:ke,dy:Ie}=S;re(S.cards.map(Le=>({anchor:Le.anchor,decl:`left:${Le.ox+ke}px;top:${Le.oy+Ie}px;${y}`,selection:{x:Le.ox+ke,y:Le.oy+Ie}})),S.mainStart?{x:S.mainStart.x+ke,y:S.mainStart.y+Ie}:void 0),S.mainStart&&S.mainEl&&(S.mainEl.style.marginLeft=`${S.mainStart.x+S.dx}px`,S.mainEl.style.marginTop=`${S.mainStart.y+S.dy}px`),Mn({move:{ids:S.ids,dx:S.dx,dy:S.dy},size:null});const De=at(S.hit),lt=!S.mainStart&&S.cards.length>0&&S.ids.size===S.cards.length?S.cards.map(Le=>Le.anchor).sort((Le,Ue)=>+(Ue===De)-+(Le===De)):[],vt=lt.length&&S.live?te.current.attachHit(lt,ue):null;go(vt)},tr=b=>{w(),b.kind==="move"&&b.mainEl&&(b.mainEl.style.marginLeft="",b.mainEl.style.marginTop=""),Mn(null),Dn(null),go(null),Fe(null),le(null)},Rc=b=>{if(b.pointerType==="touch"&&(fn.delete(b.pointerId),Qt(),ot)){fn.size===0&&(ot=null),He(b.pointerId),S=null;return}if(S&&pe!==b.pointerId){He(b.pointerId);return}Gn();const L=S;if(S=null,He(b.pointerId),!L)return;if(L.kind==="pan"){L.tapKey&&Math.hypot(b.clientX-L.x0,b.clientY-L.y0)<yi&&pt([L.tapKey]);return}if(L.kind==="link"||L.kind==="reconnect"){if(tr(L),!L.live)return;const Ie=L.kind==="link"?L.from:L.fixed,De=it(b.clientX,b.clientY);if(!De||De===Ie)return;L.kind==="reconnect"?te.current.mutate(lt=>xx(lt,L.id,L.end,De)):te.current.linkNodes(Ie,De,b.shiftKey);return}if(L.kind==="create"){const Ie=Math.abs(L.x1-L.x0),De=Math.abs(L.y1-L.y0),lt=_a.has(L.tool)&&Ie>=ar&&De>=ar?{x:Math.min(L.x0,L.x1),y:Math.min(L.y0,L.y1),w:Ie,h:De}:null;let vt=null;L.tool==="frame"?lt?te.current.addFrame(lt.x,lt.y,lt.w,lt.h):te.current.addFrame(L.x0-Xi.w/2,L.y0-Xi.h/2):L.tool==="card"?vt=te.current.addCardAt(L.x0-en/2,L.y0-24):cs[L.tool]&&te.current.addShapeAt(cs[L.tool],L.x0,L.y0,lt??void 0),Gt("select"),vt||H(),tr(L);return}if(!L.live){L.kind==="move"&&L.ids.size>1&&!L.additive&&pt([L.hit]),tr(L);return}const ue=N();if(L.kind==="marquee"){const Ie=It(b.clientX,b.clientY),De={x:Math.min(L.x0,Ie.x),y:Math.min(L.y0,Ie.y),w:Math.abs(Ie.x-L.x0),h:Math.abs(Ie.y-L.y0)},lt=[];for(const[vt,Le]of te.current.boxesNow(null))pl(De,Le)&&lt.push(vt);pt(L.additive?[...new Set([...L.base,...lt])]:lt),tr(L);return}if(!ue){tr(L);return}let Ee=null,ke=null;if(L.kind==="card-size"){const Ie=L.key===we;let De=C.current?Sl(L.b0,L.edge,L.dx,L.dy,!0,Ie?Pa:Us):L.next;L.gx&&(De={...De,x:L.next.x,w:L.next.w}),L.gy&&(De={...De,y:L.next.y,h:L.next.h});const lt=L.edge.includes("n")||L.edge.includes("s");Ie?te.current.writeFm({m:{...W.current.main,x:Math.round(De.x),y:Math.round(De.y),w:Math.round(De.w),...lt?{h:Math.round(De.h)}:{}}}):kr(ue,new Map([[L.key,{x:Math.round(De.x),y:Math.round(De.y),w:Math.round(De.w),h:lt?Math.round(De.h):L.h0}]])),C.current&&(ke={key:L.key,from:L.next,to:De})}else if(L.kind==="size"){const Ie=Rn(W.current.elements).find(De=>De.id===L.id);Ie&&Ie.kind!=="connector"&&te.current.mutate(De=>xu(De,L.id,{x:Math.round(Ie.x+L.dx),y:Math.round(Ie.y+L.dy),w:Math.max(ar,Math.round(Ie.w+L.dw)),h:Math.max(ar,Math.round(Ie.h+L.dh))}))}else{const Ie=!L.mainStart&&L.cards.length>0&&L.ids.size===L.cards.length?L.cards.map(St=>St.anchor).sort((St,Co)=>+(Co===at(L.hit))-+(St===at(L.hit))):[],De=Ie.length?te.current.attachHit(Ie,It(b.clientX,b.clientY)):null;if(Ie.length&&De&&te.current.applyAttach(Ie,De)){tr(L);return}const lt=yn(f),vt=[];for(const St of L.cards){const Co=lt.get(St.anchor);Co&&vt.push(Co)}if(L.mainStart){const St=bn(f);St&&vt.push(St)}const Le=new Set(L.cards.map(St=>St.anchor)),Ue=[...lt].filter(([St])=>!Le.has(St)).map(([,St])=>St);if(!L.mainStart){const St=bn(f);St&&Ue.push(St)}const wt=(L.hit.startsWith("c:")?L.cards.find(St=>St.anchor===at(L.hit)):null)??L.cards[0]??(L.mainStart?{ox:L.mainStart.x,oy:L.mainStart.y}:null),Bt=L.gx?L.dx:C.current&&wt?bi(wt.ox+L.dx)-wt.ox:L.dx,kt=L.gy?L.dy:C.current&&wt?bi(wt.oy+L.dy)-wt.oy:L.dy,jn=Bt-L.dx,fo=kt-L.dy,So=vt.map(St=>({...St,x:St.x+jn,y:St.y+fo})),xr=Qr(So,Ue,{x:Bt,y:kt}),On=Bt+xr.x,yr=kt+xr.y,nr={x:On-L.dx,y:yr-L.dy};(nr.x||nr.y)&&(Ee={anchors:L.cards.map(St=>St.anchor),main:!!L.mainStart,push:nr,repel:!!(xr.x||xr.y)}),L.cards.length&&kr(ue,new Map(L.cards.map(St=>[St.anchor,{x:Math.round(St.ox+On),y:Math.round(St.oy+yr)}])));const Rr=new Set([...L.ids].filter(St=>St.startsWith("e:")).map(at)),Lr=L.mainStart?{...W.current.main,x:Math.round(L.mainStart.x+On),y:Math.round(L.mainStart.y+yr)}:void 0;(Rr.size||Lr)&&(te.current.writeFm({...Rr.size?{e:Ui(_o(W.current.elements),Rr,On,yr)}:{},...Lr?{m:Lr}:{}}),L.cards.length&&te.current.mergePair())}tr(L),ke&&z(ke.key,ke.from,ke.to),Ee&&D(Ee.anchors,Ee.main,Ee.push,Ee.repel?"amx-card-repel":"amx-card-snap"),$()},Lc=b=>{if(Et.current)return;const L=document.elementFromPoint(b.clientX,b.clientY)??b.target;if(L.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;const ue=L.closest(".amx-ucard"),Ee=!ue&&!!L.closest(".ProseMirror"),ke=ue?.dataset.anchor?Ft(ue.dataset.anchor):Ee?we:null;if(ke){if(sn.current===(ke===we?we:at(ke)))return;b.preventDefault(),b.stopPropagation(),te.current.enterNodeEdit(ke,{x:b.clientX,y:b.clientY}),Hm()&&te.current.focusNode(ke,!0);return}const Ie=L.closest(as);if(Ie?.dataset.el){b.preventDefault(),b.stopPropagation();const Le=Rn(W.current.elements).find(Ue=>Ue.id===Ie.dataset.el);Le&&te.current.editText(Le.id,Oa(Le),Fa(Le));return}if(!on(L))return;const De=It(b.clientX,b.clientY),lt=te.current.boxesNow(null),vt=Rn(W.current.elements).find(Le=>{if(Le.kind!=="connector")return!1;const Ue=wr(Le.from),wt=wr(Le.to),Bt=Ue?lt.get(Ue):null,kt=wt?lt.get(wt):null;return!!Bt&&!!kt&&Bs(Bt,kt,De,8/se.current.z)});b.preventDefault(),vt?te.current.editText(vt.id,"label",Te("canvasstage.textTitle.connector")):te.current.addCardAt(De.x-en/2,De.y-24)},Dc=(b,L,ue)=>{if(Et.current||b.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"))return"skip";const Ee=b.closest(as),ke=b.closest(".amx-ucard"),Ie=!ke&&!Ee&&!!b.closest(".ProseMirror");if(ke?.dataset.anchor&&sn.current===ke.dataset.anchor||Ie&&sn.current===we)return"native";let De=Ee?.dataset.el?vn(Ee.dataset.el):ke?.dataset.anchor?Ft(ke.dataset.anchor):Ie?we:null;if(!De&&!on(b))return"skip";if(!De){const lt=It(L,ue),vt=te.current.boxesNow(null),Le=Rn(W.current.elements).find(Ue=>{if(Ue.kind!=="connector")return!1;const wt=wr(Ue.from),Bt=wr(Ue.to),kt=wt?vt.get(wt):null,jn=Bt?vt.get(Bt):null;return!!kt&&!!jn&&Bs(kt,jn,lt,8/se.current.z)});Le&&(De=vn(Le.id))}return De&&!dt.current.includes(De)&&pt([De]),Dt({x:L,y:ue,key:De,at:It(L,ue)}),"open"},Ic=b=>{const L=Dc(b.target,b.clientX,b.clientY);L!=="skip"&&(b.stopPropagation(),L==="open"&&b.preventDefault())},td=b=>{const L=b.target,ue=sn.current;return!ue||!L?!1:ue===we?!!L.closest(".ProseMirror")&&!L.closest(".amx-ucard"):!!L.closest(`.amx-ucard[data-anchor="${CSS.escape(ue)}"]`)};let fa=!1;const Pc=b=>{b.target?.closest?.(".ProseMirror")&&(fa=!0)},jr=()=>{fa=!1},Oc=b=>{const L=b.dataTransfer,ue=L?Array.from(L.types):[];return fa||N()?.dragging?null:W.current.saveFile&&ue.includes("Files")?"files":rp(L)?"refs":td(b)?null:ue.includes("text/uri-list")||ue.includes("text/plain")?"text":null},Fc=b=>{if(Et.current)return;const L=N();if(Oc(b)){b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="copy"),f.classList.add("amx-dropzone");return}!L?.dragging||b.target?.closest?.(".ProseMirror")||(b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="move"),f.classList.add("amx-dropzone"))},Oo=()=>f.classList.remove("amx-dropzone"),_c=b=>{f.contains(b.relatedTarget)||Oo()},Bc=b=>{if(Oo(),Et.current){b.preventDefault();return}const L=N(),ue=Oc(b);if(ue){b.preventDefault(),b.stopPropagation();const Ie=It(b.clientX,b.clientY),De=Array.from(b.dataTransfer?.files??[]);if(ue==="files"&&De.length){te.current.dropFilesAt(De,Ie);return}if(ue==="refs"){const vt=W.current.path;np(b.dataTransfer).forEach((Le,Ue)=>te.current.addCardMd(Ml(Le,b.altKey||Le.kind==="note"&&Le.path===vt),Ie,Ue));return}const lt=b.dataTransfer?.getData("text/uri-list")||b.dataTransfer?.getData("text/plain")||"";te.current.addCardMd(lt,Ie);return}if(!L?.dragging||b.target?.closest?.(".ProseMirror"))return;b.preventDefault(),b.stopPropagation();const Ee=It(b.clientX,b.clientY),ke=L.state.selection;if(ke instanceof Ce&&ke.node.type.name==="amadeusCanvasCard")kr(L,new Map([[String(ke.node.attrs.anchor),{x:Math.round(Ee.x),y:Math.round(Ee.y)}]])),$();else{const Ie=Ku(L,Math.round(Ee.x),Math.round(Ee.y));Ie&&$(Ie)}L.dragging=null,L.dom.dataset.dragging="false"},nd=()=>{const b=f.getBoundingClientRect();return It(b.left+b.width/2,b.top+b.height/2)},Ns=b=>{if(sn.current||!b.clipboardData||!N())return;const L=dt.current;if(!L.length)return;b.preventDefault();const ue=te.current.writeClip(b.clipboardData,L);b.type==="cut"&&ue&&te.current.removeSel(ue.keys,{assets:!1})},Hc=b=>{if(Et.current||sn.current||!b.clipboardData)return;const L=Array.from(b.clipboardData.files??[]),ue=b.clipboardData.getData("text/plain")??"",Ee=Qb(b.clipboardData.getData(zl));if(!L.length&&!ue.trim()&&!Ee)return;b.preventDefault();const ke=Uo.current++,Ie=nd(),De={x:Ie.x+ke*24,y:Ie.y+ke*24};if(L.length){te.current.dropFilesAt(L,De);return}Ee&&te.current.pastePayload(Ee,De)||ue.trim()&&te.current.addCardMd(ue,De)},Ts=b=>{b.pointerType==="touch"&&(fn.delete(b.pointerId),Qt(),ot&&fn.size===0&&(ot=null))};window.addEventListener("pointerup",Ts,!0),window.addEventListener("pointercancel",Ts,!0);const Kc=b=>{b.pointerType==="touch"&&(fn.delete(b.pointerId),Qt(),ot&&fn.size===0&&(ot=null)),He(b.pointerId),!(S&&pe!==b.pointerId)&&Pn()};return f.addEventListener("pointerdown",As),f.addEventListener("pointermove",$c),f.addEventListener("pointerleave",Tc),f.addEventListener("pointerup",Rc),f.addEventListener("pointercancel",Kc),f.addEventListener("dblclick",Lc),f.addEventListener("contextmenu",Ic,!0),f.addEventListener("dragover",Fc),f.addEventListener("dragleave",_c),f.addEventListener("drop",Bc),f.addEventListener("dragstart",Pc),window.addEventListener("dragend",Oo),window.addEventListener("drop",Oo),window.addEventListener("blur",Oo),window.addEventListener("dragend",jr),window.addEventListener("drop",jr),window.addEventListener("blur",jr),f.addEventListener("copy",Ns,!0),f.addEventListener("cut",Ns,!0),f.addEventListener("paste",Hc,!0),()=>{window.removeEventListener("pointerup",Ts,!0),window.removeEventListener("pointercancel",Ts,!0),Qt(),B.remove(),M(),delete f.dataset.amxDragscope,f.removeEventListener("wheel",Q),f.removeEventListener("pointerdown",As),f.removeEventListener("pointermove",$c),f.removeEventListener("pointerleave",Tc),Gn(),f.removeEventListener("pointerup",Rc),f.removeEventListener("pointercancel",Kc),f.removeEventListener("dblclick",Lc),f.removeEventListener("contextmenu",Ic,!0),f.removeEventListener("dragover",Fc),f.removeEventListener("dragleave",_c),f.removeEventListener("drop",Bc),f.removeEventListener("dragstart",Pc),window.removeEventListener("dragend",Oo),window.removeEventListener("drop",Oo),window.removeEventListener("blur",Oo),window.removeEventListener("dragend",jr),window.removeEventListener("drop",jr),window.removeEventListener("blur",jr),Oo(),f.removeEventListener("copy",Ns,!0),f.removeEventListener("cut",Ns,!0),f.removeEventListener("paste",Hc,!0)}},[n,It]),x.useEffect(()=>{if(!n)return;const f=()=>{Nn.current={held:!1,used:!1},No(!1)},N=$=>{if($.code!=="Space"||!Nn.current.held)return;const{used:H}=Nn.current;f(),$.preventDefault();const K=p.current,B=$.target;if(H||Et.current||!K||!B||!K.contains(B)||B.closest(".ProseMirror"))return;const U=dt.current;U.length===1&&(U[0].startsWith("c:")||U[0]===we)&&te.current.enterNodeEdit(U[0])};return window.addEventListener("keyup",N,!0),window.addEventListener("blur",f),()=>{window.removeEventListener("keyup",N,!0),window.removeEventListener("blur",f),f()}},[n]);const nt=f=>{if(!n||X||f.nativeEvent.isComposing)return;const N=f.target;if((f.metaKey||f.ctrlKey)&&(f.key==="z"||f.key==="Z")){if(N.tagName==="INPUT"||N.tagName==="TEXTAREA")return;f.preventDefault(),f.stopPropagation(),Yn(f.shiftKey?"redo":"undo");return}if((f.metaKey||f.ctrlKey)&&!f.shiftKey&&!f.altKey&&(f.key==="y"||f.key==="Y")){if(N.tagName==="INPUT"||N.tagName==="TEXTAREA")return;f.preventDefault(),f.stopPropagation(),Yn("redo");return}if(f.key!=="Escape")return;const $=sn.current;!$||!N.closest(".ProseMirror")||(f.preventDefault(),f.stopPropagation(),Wn(null),pt([$===we?we:Ft($)]),p.current?.focus({preventScroll:!0}))},st=f=>{if(!n)return;const N=f.target;if(N.closest(".ProseMirror")||N.tagName==="INPUT"||N.tagName==="TEXTAREA")return;const $=f.metaKey||f.ctrlKey;if(!f.altKey&&($?f.key==="="||f.key==="+"||f.key==="-"||f.key==="0":f.shiftKey&&f.code==="Digit1")){f.preventDefault(),$?f.key==="0"?Un(1/se.current.z):Un(f.key==="-"?1/1.2:1.2):nn();return}if(!X){if($&&(f.key==="a"||f.key==="A")){f.preventDefault(),pt([...yn(p.current).keys()].map(Ft).concat(Ae.filter(H=>H.kind!=="connector").map(H=>vn(H.id)),[we]));return}if($&&!f.shiftKey&&!f.altKey&&(f.key==="d"||f.key==="D")){f.preventDefault(),et.length&&F(et);return}if(f.key==="Escape"){f.preventDefault(),ut?Dt(null):_t?An(null):ct!=="select"?Gt("select"):pt([]);return}if(f.code==="Space"&&!$&&!f.target?.closest?.("button")){f.preventDefault(),!f.repeat&&!Nn.current.held&&(Nn.current={held:!0,used:!1},No(!0));return}if(et.length){if(f.key==="Delete"||f.key==="Backspace"){f.preventDefault(),$t(et);return}if((f.key==="Enter"||f.key==="F2")&&et.length===1&&et[0].startsWith("e:")){f.preventDefault();const H=Ae.find(K=>K.id===at(et[0]));H&&jo(H.id,Oa(H),Fa(H));return}if((f.key==="Tab"||f.key==="Enter")&&et.length===1&&(et[0].startsWith("c:")||et[0]===we)){f.preventDefault(),Qo(et[0]===we?we:at(et[0]),f.key==="Tab"?"child":"sibling");return}if(f.key.startsWith("Arrow")){f.preventDefault();const H=Kp(C.current,f.shiftKey),K=f.key==="ArrowLeft"?-H:f.key==="ArrowRight"?H:0,B=f.key==="ArrowUp"?-H:f.key==="ArrowDown"?H:0;if(!K&&!B)return;const U=o(),oe=eo(et),be=oe.filter(d=>d.startsWith("c:")).map(at);if(U&&be.length){const d=yn(p.current);kr(U,new Map(be.map(y=>{const w=d.get(y);return[y,{x:Math.round((w?.x??0)+K),y:Math.round((w?.y??0)+B)}]}))),R()}const ie=new Set(oe.filter(d=>d.startsWith("e:")).map(at)),re=oe.includes(we)?{...r,x:Math.round(r.x+K),y:Math.round(r.y+B)}:void 0;(ie.size||re)&&(We({...ie.size?{e:Ui(_o(c),ie,K,B)}:{},...re?{m:re}:{}}),be.length&&tt())}}}},At=[{id:"select",icon:u.jsx(Qf,{size:14}),title:xe("canvasstage.tool.select")},{id:"pan",icon:u.jsx(vm,{size:14}),title:xe("canvasstage.tool.pan")},{id:"card",icon:u.jsx(Ga,{size:14}),title:xe("canvasstage.tool.card")},{id:"rect",icon:u.jsx(ep,{size:14}),title:xe("canvasstage.shape.rect")},{id:"ellipse",icon:u.jsx(tp,{size:14}),title:xe("canvasstage.shape.ellipse")},{id:"text",icon:u.jsx(wm,{size:14}),title:xe("canvasstage.shape.text")},{id:"frame",icon:u.jsx(eu,{size:14}),title:xe("canvasstage.tool.frame")},{id:"conn",icon:u.jsx(Vh,{size:14}),title:xe("canvasstage.tool.conn")}],mt=Bp(de),Rt=(ut?.key?.startsWith("e:")?Ae.find(f=>f.id===at(ut.key))??null:null)?.kind==="connector",Nt=ut?.key?(et.length?et:[ut.key]).filter(f=>f.startsWith("c:")||f.startsWith("e:")):[],an=(()=>{if(!Nt.length)return null;const f=ut?o():null,N=_o(c),$=K=>{if(K.startsWith("c:"))return String((f?Fn(f).find(U=>U.anchor===at(K))?.node.attrs.color:"")??"");const B=N.find(U=>!!U&&typeof U=="object"&&U.id===at(K));return typeof B?.color=="string"?B.color:""},H=$(Nt[0]);return Nt.every(K=>$(K)===H)?H:null})(),Pt=an&&an.startsWith("#")?an:null,Hn=Rt?(et.length?et:[ut.key]).filter(f=>f.startsWith("e:")).map(at).filter(f=>Ae.some(N=>N.kind==="connector"&&N.id===f)):[],ko=(()=>{const f=Hn.map(N=>{const $=Ae.find(B=>B.kind==="connector"&&B.id===N),H=$?.kind==="connector"?$.fromEnd??ms.fromEnd:ms.fromEnd,K=$?.kind==="connector"?$.toEnd??ms.toEnd:ms.toEnd;return bl.find(B=>B.from===H&&B.to===K)?.id??null});return f.length&&f.every(N=>N===f[0])?f[0]:null})();return u.jsxs("div",{className:`amx-stage${n?"":" amx-stage-off"}${n?` amx-tool-${X?"pan":ct}`:""}${X?" amx-stage-ro":""}${n&&Zn?" amx-space-pan":""}${Go?" amx-vp-focus":""}${n&&Me&&de.z<=Je?" amx-stage-overview":""}`,ref:p,tabIndex:-1,onKeyDownCapture:nt,onKeyDown:st,children:[n?u.jsx("div",{className:"amx-stage-grid","aria-hidden":"true",style:mt}):null,u.jsxs("div",{className:"amx-stage-inner",style:n?{transform:`translate(${de.x}px, ${de.y}px) scale(${de.z})`,"--amx-main-x":`${r.x}px`,"--amx-main-y":`${r.y}px`,"--amx-main-w":`${r.w}px`,"--amx-main-h":typeof r.h=="number"&&r.h>0?`${r.h}px`:"auto"}:void 0,children:[n?u.jsx(Ib,{elements:c,hostRef:p,documentKey:e,sel:J,editing:Jn,tree:i,ghost:Xo,marquee:Tn,attach:ho,overviewScale:Me&&de.z<=Je?de.z:null,mainAutoHeight:!(typeof r.h=="number"&&r.h>0),preview:G??(_t&&I?{from:_t,x:I.x,y:I.y,over:I.over}:null),guides:Ye}):null,Ke]}),n&&ae?u.jsx(ev,{hostRef:p,vp:de,elements:c,ghost:Xo,onCenter:$o}):null,n&&!X?u.jsx("div",{className:"amx-stage-tools",role:"toolbar","aria-label":xe("canvasstage.toolbar.label"),children:At.map(f=>u.jsx("button",{type:"button",title:f.title,className:ct===f.id?"on":"","aria-pressed":ct===f.id,onClick:()=>{Gt(f.id),An(null),p.current?.focus({preventScroll:!0})},children:f.icon},f.id))}):null,n&&_t?u.jsx("div",{className:"amx-stage-hint",children:xe("canvasstage.conn.hint")}):null,n?u.jsx($m,{zoom:de.z,onZoomBy:Un,onFit:nn,snap:ge,onSnap:f=>{ht(f),p.current?.focus({preventScroll:!0})},mini:ae,onMini:f=>{Re(f),Bm(f),p.current?.focus({preventScroll:!0})},extra:u.jsxs(u.Fragment,{children:[u.jsx("button",{type:"button",className:Y?"is-on":"","aria-pressed":Y,"aria-label":xe("canvasstage.guides.label"),title:xe(Y?"canvasstage.guides.off":"canvasstage.guides.on"),onClick:()=>{const f=!Y;ye.current=f,fe(f),Fm(f),p.current?.focus({preventScroll:!0})},children:u.jsx(Qm,{size:12})}),u.jsx("button",{type:"button",className:Me?"is-on":"","aria-pressed":Me,"aria-label":xe("canvasstage.overview.label"),title:xe(Me?"canvasstage.overview.off":"canvasstage.overview.on"),onClick:()=>{const f=!Me;rt(f),_m(f),p.current?.focus({preventScroll:!0})},children:u.jsx(wh,{size:12})})]})}):null,n&&ut?u.jsx(ir,{children:u.jsx(lr,{className:"ctx-menu amx-canvas-menu",x:ut.x,y:ut.y,onClick:f=>f.stopPropagation(),children:ut.key?u.jsxs(u.Fragment,{children:[Nt.length>0&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"amx-color-row",role:"group","aria-label":xe("canvasstage.color.label"),children:[Yb.map(f=>u.jsx("button",{type:"button",className:"amx-color-swatch","data-swatch":f.v||"none",title:xe(f.nameKey),"aria-label":xe(f.nameKey),"aria-pressed":an===f.v,style:f.v?{"--amx-swatch":`var(--amx-cv-${f.v})`}:void 0,onClick:()=>{const N=Nt;Dt(null),In(N,f.v||null)}},f.v||"none")),u.jsxs("label",{className:"amx-color-swatch is-custom",title:xe("canvasstage.color.custom"),"data-active":Pt?"":void 0,style:Pt?{"--amx-swatch":Pt}:void 0,children:[Pt?null:u.jsx(Hp,{size:11}),u.jsx("input",{type:"color","aria-label":xe("canvasstage.color.custom"),defaultValue:Pt??"#7b5ce5",ref:f=>{if(!f)return;const N=Nt;f.onchange=()=>{Dt(null),In(N,f.value)}}})]})]}),u.jsx("div",{className:"ctx-separator"})]}),Rt&&Hn.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"amx-color-row amx-end-row",role:"group","aria-label":xe("canvasstage.ends.label"),children:bl.map(f=>u.jsx("button",{type:"button",className:"amx-end-btn","data-ends":f.id,title:xe(f.nameKey),"aria-label":xe(f.nameKey),"aria-pressed":ko===f.id,onClick:()=>{const N=Hn;Dt(null),$r(N,f.from,f.to),p.current?.focus({preventScroll:!0})},children:f.icon},f.id))}),u.jsx("div",{className:"ctx-separator"})]}),ut.key.startsWith("e:")&&u.jsx("button",{onClick:()=>{const f=Ae.find(N=>N.id===at(ut.key));Dt(null),f&&jo(f.id,Oa(f),Fa(f))},children:xe("canvasstage.menu.editText")}),ut.key!==we&&!Rt&&u.jsxs(u.Fragment,{children:[u.jsx("button",{onClick:()=>{const f=et.length?et:[ut.key];Dt(null),he(f)},children:xe("canvasstage.menu.copy")}),u.jsx("button",{onClick:()=>{const f=et.length?et:[ut.key];Dt(null),F(f),p.current?.focus({preventScroll:!0})},children:xe("canvasstage.menu.duplicate")})]}),!Rt&&u.jsx("button",{onClick:()=>{An(ut.key),Gt("conn"),Dt(null)},children:xe("canvasstage.menu.connectTo")}),(ut.key===we||ut.key.startsWith("c:"))&&Cr(Vt(i),ut.key===we?we:at(ut.key)).length>0&&u.jsx("button",{onClick:()=>{const f=ut.key===we?we:at(ut.key);Dt(null),Ne(f)},children:xe("canvasstage.menu.arrange")}),!Rt&&u.jsx("button",{onClick:()=>{const f=et.length?et:[ut.key];Dt(null),hn(f)},children:xe("canvasstage.menu.groupFrame")}),ut.key.startsWith("c:")&&u.jsx("button",{onClick:()=>{const f=at(ut.key);Dt(null);const N=o();if(!N)return;const $=yt([f]);$&&xt(),Vu(N,f),pt([]),R(),$&&tt()},children:xe("canvasstage.menu.unwrap")}),ut.key!==we&&u.jsx("button",{className:"danger",onClick:()=>{const f=et.length?et:[ut.key];Dt(null),$t(f)},children:xe("canvasstage.menu.delete")})]}):u.jsxs(u.Fragment,{children:[u.jsx("button",{onClick:()=>{const f=ut.at;Dt(null),io(f.x-en/2,f.y-24)},children:xe("canvasstage.menu.newCard")}),_&&u.jsx("button",{onClick:()=>{const f=ut.at;Dt(null),co(f)},children:xe("canvasstage.menu.addNote")}),u.jsx("button",{onClick:()=>{const f=ut.at;Dt(null),Xn("rect",f.x,f.y)},children:xe("canvasstage.shape.rect")}),u.jsx("button",{onClick:()=>{const f=ut.at;Dt(null),Xn("ellipse",f.x,f.y)},children:xe("canvasstage.shape.ellipse")}),u.jsx("button",{onClick:()=>{const f=ut.at;Dt(null),Xn("text",f.x,f.y)},children:xe("canvasstage.shape.text")}),u.jsx("button",{onClick:()=>{const f=ut.at;Dt(null),bo(f.x,f.y)},children:"Frame"}),u.jsx("button",{onClick:()=>{Dt(null),nn()},children:xe("canvasstage.menu.fit")}),u.jsx("div",{className:"ctx-separator"}),u.jsx("button",{onClick:()=>{Dt(null),Io()},children:xe("canvasstage.menu.exportCanvas")})]})})}):null,n&&!X&&xo&&_?u.jsx(gu,{pages:_(),exclude:e,onClose:()=>{co(null),p.current?.focus({preventScroll:!0})},onPick:f=>{const N=xo;co(null),p.current?.focus({preventScroll:!0}),Ro(Ml({kind:"note",path:f}),N)}}):null]})}function Ku(e,t,n,o){const r=e.state.selection,s=e.state.schema.nodes.amadeusCanvasCard;if(!s||!(r instanceof Ce))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 R=i.depth;R>=1;R--)if(i.node(R).type.name==="amadeusColumnCell")return null;const a=Ao(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,h=e.state.schema.nodes.paragraph;let E=m?.type.name==="amadeusCanvasCard"&&m.childCount===1&&h?e.state.tr.replaceWith(r.from,r.to,h.create()):e.state.tr.delete(r.from,r.to);return E=E.insert(o?Hu(E.doc,o.tree,o.parent):E.doc.content.size,l),cr(e,E.scrollIntoView()),a}function Vu(e,t){const o=Fn(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 nv={heading:["id"]};function Nc(e,t){if(e.type!==t.type)return!1;const n=nv[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 Yr(e,t){if(e===t)return!0;if(!Nc(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(!Yr(e.child(n),t.child(n)))return!1;return!0}function qu(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(!Nc(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=qu(r.content,s.content,n+1);if(c!=null)return c}n+=r.nodeSize}}function Wu(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(!Nc(c,i))return{a:n,b:o};if(c.isText&&c.text!==i.text){const l=c.text??"",m=i.text??"";let h=0;const E=Math.min(l.length,m.length);for(;h<E&&l[l.length-h-1]===m[m.length-h-1];)h++,n--,o--;return{a:n,b:o}}if(c.content.size||i.content.size){const l=Wu(c.content,i.content,n-1,o-1);if(l)return l}n-=a,o-=a}}const ov=25e4;function rv(e,t){const n=e.childCount,o=t.childCount;let r=0;for(;r<n&&r<o&&Yr(e.child(r),t.child(r));)r++;let s=0;for(;s<n-r&&s<o-r&&Yr(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,h=l-a;if(m===0&&h===0)return[];if(m===0||h===0||m*h>ov)return[[c,i,a,l]];const E=h+1,R=new Uint32Array((m+1)*E);for(let X=m-1;X>=0;X--)for(let _=h-1;_>=0;_--)R[X*E+_]=Yr(e.child(c+X),t.child(a+_))?R[(X+1)*E+_+1]+1:Math.max(R[(X+1)*E+_],R[X*E+_+1]);const k=[];let v=0,j=0,P=0,q=0;for(;v<m&&j<h;)Yr(e.child(c+v),t.child(a+j))&&R[v*E+j]===R[(v+1)*E+j+1]+1?((P<v||q<j)&&k.push([c+P,c+v,a+q,a+j]),v++,j++,P=v,q=j):R[(v+1)*E+j]>=R[v*E+j+1]?v++:j++;return(P<m||q<h)&&k.push([c+P,i,a+q,l]),k}const qs=(e,t)=>{let n=0;for(let o=0;o<t;o++)n+=e.child(o).nodeSize;return n};function sv(e,t){const n=[];for(const[o,r,s,c]of rv(e,t)){const i=qs(e,o),a=qs(t,s),l=e.content.cut(i,qs(e,r)),m=t.content.cut(a,qs(t,c)),h=qu(l,m,i);if(h==null)continue;const E=Wu(l,m,i+l.size,a+m.size);let R=E?E.a:i+l.size,k=E?E.b:a+m.size;const v=a-i;R<h&&(k+=h-R,R=h),k-v<h&&(R+=h-(k-v),k=h+v),n.push({from:h,to:R,slice:t.slice(h+v,k)})}return n}function av(e,t,n){const o=sv(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 je){const c=l=>{for(const m of o)if(l>m.from&&l<m.to){const h=s.mapping.map(m.from,-1);return Math.min(h+(l-m.from),h+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(je.between(s.doc.resolve(m),s.doc.resolve(l)))}catch{}}}return s.setMeta("addToHistory",!1)}const ro=new Ln("amAgentChanges");let Nl=0;function Yu(e,t){if(e.childCount!==t.childCount)return!1;for(let n=0;n<e.childCount;n++)if(!Yr(e.child(n),t.child(n)))return!1;return!0}function cv(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(X=>X.e).map(X=>X.e),l=i.filter(X=>X.c).map(X=>X.c);if(!l.length){for(const X of a){const _=o.mapping.map(X.from,1);c.push({...X,from:_,to:Math.max(_,o.mapping.map(X.to,-1))})}continue}if(!a.length&&l.length===1){const X=l[0];c.push({id:++Nl,from:X.from,to:X.to,old:X.old,after:o.doc.slice(X.from,X.to).content});continue}const m=Math.min(...i.map(X=>X.a)),h=Math.max(...i.map(X=>X.b)),E=a.filter(X=>Yu(n.slice(X.from,X.to).content,X.after)),R=a.reduce((X,_)=>X+(_.locked??0)+(E.includes(_)?0:1),0),k=new ap(n);for(const X of[...E].sort((_,Z)=>Z.from-_.from))k.replace(X.from,X.to,X.old);const v=k.mapping.map(m,-1),j=k.mapping.map(h,1),P=o.mapping.map(m,-1),q=o.mapping.map(h,1);c.push({id:++Nl,from:P,to:q,old:k.doc.slice(v,j),after:o.doc.slice(P,q).content,...R?{locked:R}:{}})}return c.sort((i,a)=>i.from-a.from)}function iv(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 lv(e){return[zt(()=>uv(e))].flat()}function uv(e){return new Wt({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=cv(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?iv(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 dv(e,t,n){return n.length?e.setMeta(ro,{add:n,before:t}):e}function fv(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(!Yu(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 pv(e){e.dispatch(e.state.tr.setMeta(ro,{clear:!0}))}function mv(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}En({"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 hv(){const{t:e}=Ht();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 gv({count:e,index:t,onReview:n,onRevert:o,onKeep:r}){const{t:s}=Ht();return u.jsxs("div",{className:"am-agent-capsule",role:"status","aria-label":s("agentchg.label"),"data-testid":"agent-change-capsule",children:[u.jsx(Jl,{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")})]})}En({"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 Nr=new Ln("UNIFIED_PENDING_INSERT");function xv(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=Te("pendins.busy",{label:e.label});const r=document.createElement("button");return r.type="button",r.className="btn sm",r.textContent=Te("pendins.cancel"),r.addEventListener("mousedown",s=>s.preventDefault()),r.addEventListener("click",s=>{s.preventDefault(),e.onCancel()}),t.append(n,o,r),t}function yv(){return[zt(()=>new Wt({key:Nr,state:{init:()=>dr.empty,apply(e,t){let n=t.map(e.mapping,e.doc);const o=e.getMeta(Nr);return o&&"add"in o?n=n.add(e.doc,[ao.widget(o.add.pos,()=>xv(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=>Nr.getState(e)}}))]}function Uu(e,t){const o=Nr.getState(e)?.find(void 0,void 0,r=>r.id===t)[0];return o?o.from:null}let bv=0;function vv(e,t,n=!0){const o=`p${Date.now().toString(36)}${(bv++).toString(36)}`;let r=!1;const s=()=>{r=!0,Xu(e,o)};return e.dispatch(e.state.tr.setMeta(Nr,{add:{id:o,pos:e.state.selection.head,label:t,visible:n,onCancel:s}})),{id:o,label:t,cancelled:()=>r}}function Xu(e,t){e.isDestroyed||Uu(e.state,t)==null||e.dispatch(e.state.tr.setMeta(Nr,{remove:t}))}function wv(e,t,n){const o=Uu(e.state,t);if(o==null)return!1;let r=e.state.tr.setMeta(Nr,{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 h=s.before(c),E=s.after(c),R=s.node(c).textContent.trim()==="";m=e.hasFocus()&&i.from>=h&&i.to<=E,a=R?h:E,r=R?r.replaceWith(h,E,n):r.insert(E,n),l=a+n.size}return Zs(r,a,l),m&&(r=r.setSelection(je.near(r.doc.resolve(Math.min(l,r.doc.content.size)),-1)).scrollIntoView()),e.dispatch(r),!0}function Tl(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{level:"warning",text:Te("pendins.sourceMode",{label:e})}}))}function kv(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("pendins.lost",{label:e})}}))}function Gu(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 Ln("amInlineAi");function Sv(e){const t=e.state.selection;if(!(t instanceof je)||!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 Cv(e){return new Wt({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()||!Sv(t)?!1:(e.onSpace(t),!0)}}})}function Ev(e){return[zt(()=>Cv({spaceTrigger:e.spaceTrigger,onSpace:t=>e.onSpace.current(t)}))].flat()}function Mv(e,t,n){const o={from:t,to:n,text:e.state.doc.textBetween(t,n,`
701
- `,""),sig:Gu(e.state.doc,t,n)},r=e.state.tr.setMeta(ur,{set:o});return n>t&&r.setSelection(je.create(r.doc,n)),e.dispatch(r),o}function $l(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(je.create(n.doc,t.from,t.to))}catch{}e.dispatch(n)}function jl(e){return ur.getState(e.state)??null}function zv(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 Av(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 Nv(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"&&Gu(r,c,i)!==t.sig&&(a="below");let l=e.state.tr,m;if(a==="replace"){const h=n.childCount===1&&!!n.firstChild?.isTextblock&&r.resolve(c).sameParent(r.resolve(i));l=l.replaceRange(c,i,h?new Ua(n,1,1):new Ua(n,0,0)),m=l.mapping.map(i,1)}else{const h=Av(r,a==="below"?i:c);if(!h)return null;a==="insert"&&h.blank?(l=l.replaceWith(h.from,h.to,n),m=h.from+n.size):(l=l.insert(h.to,n),m=h.to+n.size)}return l=l.setSelection(je.near(l.doc.resolve(Math.min(m,l.doc.content.size)),-1)),e.dispatch(l.setMeta(ur,{clear:!0}).scrollIntoView()),a}En({"unipage.menu.askTangu":{zh:"问 Tangu",en:"Ask Tangu"}});const Tv=2e4;function $v(e,t){let n=null;for(const o of ta(e)){if(o.pos>t)break;n=o.text}return n}function jv(e,t,n,o){const r=e.textBetween(t,n,`
704
- `,"").trim().slice(0,Tv);if(!r)return"";const s=$v(e,t),c=s&&!/[[\]|#^\n]/.test(s)?`#${s}`:"";return o?`${r}
705
- — [[${o}${c}]]`:r}function Ju(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 Rv(e,t,n){if(e.resolve(t).depth!==0)return Ju(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 Lv(e,t){if(!t)return null;const n=ta(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?Rv(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,h)=>m.isTextblock?(h>=s&&a.push({pos:h,text:m.textContent}),!1):!0);const l=a.findIndex(m=>m.text.includes(i[0]));if(l>=0){const m=i[i.length-1],h=a.findIndex((R,k)=>k>=l&&R.text.includes(m)),E=Ju(e,a[h>=0?h:l].pos+1);if(E!=null)return E}}return r?c:null}En({"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 Rl=500,Ka=250,Ll='a[href], sup[data-type="footnote_reference"]';function Zu(e,t,n){const o=e.resolve(Math.max(0,Math.min(t,e.content.size)));if(!o.parent.isTextblock)return null;const r=o.start(),s=[];o.parent.forEach((h,E)=>s.push({node:h,from:r+E,to:r+E+h.nodeSize}));const c=h=>!!n.isInSet(h.node.marks);let i=s.findIndex(h=>c(h)&&t>=h.from&&t<h.to);if(i<0&&(i=s.findIndex(h=>c(h)&&t>=h.from&&t<=h.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 Dv(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=Zu(e.state.doc,o,n);return r&&r.from<r.to?{from:r.from,to:r.to}:null}function Iv({getView:e,onOpenNote:t}){const{t:n}=Ht(),[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 k=()=>{l.current&&clearTimeout(l.current),m.current&&clearTimeout(m.current),l.current=null,m.current=null},v=q=>{const X=e()?.dom.closest(".unified-body");return!!X&&q.closest(".unified-body")===X},j=q=>{const _=q.target?.closest?.(Ll);if(!_||!v(_))return;if(m.current&&(clearTimeout(m.current),m.current=null),l.current&&clearTimeout(l.current),_.tagName==="SUP"){l.current=setTimeout(()=>{const ze=e(),Ke=_.getBoundingClientRect();r(null),c({num:_.textContent??"",text:ze?ef(ze.state.doc,_.getAttribute("data-label")??""):null,x:Ke.left,y:Ke.bottom+6})},Rl);return}const Z=_;l.current=setTimeout(()=>{const ze=e();c(null);const Ke=Z.getBoundingClientRect(),p=ze?Dv(ze,Z):null;r({href:Z.getAttribute("href")??"",text:p&&ze?ze.state.doc.textBetween(p.from,p.to):Z.textContent??"",from:p?.from??-1,to:p?.to??-1,x:Ke.left,y:Ke.bottom+6})},Rl)},P=q=>{!q.target?.closest?.(Ll)||q.relatedTarget?.closest?.(".amx-linkcard")||(l.current&&clearTimeout(l.current),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{r(null),c(null)},Ka))};return document.addEventListener("mouseover",j,!0),document.addEventListener("mouseout",P,!0),()=>{document.removeEventListener("mouseover",j,!0),document.removeEventListener("mouseout",P,!0),k()}},[e]),x.useEffect(()=>{if(!o&&!s||i)return;const k=()=>{r(null),c(null)};return document.addEventListener("scroll",k,!0),()=>document.removeEventListener("scroll",k,!0)},[o,s,i]);const h=(k,v,j,P,q)=>{const X=e(),_=X?.state.schema.marks.link;if(!X||!_)return;const{doc:Z}=X.state;if(v>Z.content.size||k>=v)return;const ze=Zu(Z,k,_);if(!ze||ze.from!==k||ze.to!==v||ze.mark.attrs.href!==j)return;const Ke=Z.textBetween(k,v),p=Qe=>_.create({...ze.mark.attrs,href:Qe,..."ref"in ze.mark.attrs?{ref:null}:{}});let xe=X.state.tr;if(P==="")xe=xe.delete(k,v);else if(P!==null&&P!==Ke){let Qe=null;Z.nodesBetween(k,v,ce=>ce.isInline?(Qe=Qe===null?ce.marks:Qe.filter(se=>se.isInSet(ce.marks)),!1):!0);const de=(Qe??[]).filter(ce=>ce.type!==_);xe=xe.replaceWith(k,v,X.state.schema.text(P,q?p(q).addToSet(de):de)),xe.setSelection(je.near(xe.doc.resolve(k+P.length)))}else if(q){if(q===ze.mark.attrs.href){X.focus();return}xe=xe.removeMark(k,v,ze.mark).addMark(k,v,p(q))}else xe=xe.removeMark(k,v,ze.mark);X.dispatch(xe.scrollIntoView()),X.focus()};if(i){const k=!!ei(i.href)&&!!i.text.trim(),v=()=>{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:j=>{j.preventDefault();const P=ei(i.href);!P||!i.text.trim()||(h(i.from,i.to,i.wasHref,i.text,P),a(null),r(null))},onKeyDown:j=>{j.key==="Escape"&&(j.preventDefault(),j.stopPropagation(),v())},children:[u.jsxs("label",{children:[n("linkcard.text"),u.jsx("input",{autoFocus:!0,value:i.text,onChange:j=>a({...i,text:j.target.value}),onFocus:j=>j.currentTarget.select()})]}),u.jsxs("label",{children:[n("linkcard.link"),u.jsx("input",{value:i.href,onChange:j=>a({...i,href:j.target.value})})]}),u.jsxs("div",{className:"amx-linkedit-row",children:[u.jsx("button",{type:"button",onClick:v,children:n("common.cancel")}),u.jsx("button",{type:"submit",className:"primary",disabled:!k,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),Ka)},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 E=o.href;try{E=new URL(o.href).host||o.href}catch{}const R=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),Ka)},children:[u.jsx("button",{className:"amx-linkcard-host",title:o.href,onClick:k=>{t&&Bl(o.href)==="note"?(r(null),t(o.href,cp(k))):window.open(o.href,"_blank","noopener")},children:E}),u.jsx("span",{className:"amx-linkcard-sep"}),u.jsx("button",{onClick:()=>{navigator.clipboard.writeText(o.href)},children:n("linkcard.copy")}),R&&u.jsx("button",{onClick:()=>a({from:o.from,to:o.to,text:o.text,href:o.href,wasHref:o.href}),children:n("common.edit")}),R&&u.jsx("button",{onClick:()=>{h(o.from,o.to,o.href,null,null),r(null)},children:n("linkcard.unlink")}),R&&u.jsx("button",{className:"danger",onClick:()=>{h(o.from,o.to,o.href,"",null),r(null)},children:n("common.delete")})]})})}En({"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 dc(e){const t=e?.state.selection;return t instanceof Ce&&t.node.type.spec.tableRole==="table"}function Pv(e,t,n){if(!e||!dc(e))return null;const o=document.elementFromPoint(t,n)?.closest?.("td,th");if(!o||!e.dom.contains(o))return null;try{return af(e.state.doc,e.posAtDOM(o,0))}catch{return null}}const Ov=[{op:"rowAbove",key:"unipage.table.rowAbove",Icon:oh},{op:"rowBelow",key:"unipage.table.rowBelow",Icon:th},{op:"colLeft",key:"unipage.table.colLeft",Icon:ch},{op:"colRight",key:"unipage.table.colRight",Icon:sh},{op:"deleteRow",key:"unipage.table.deleteRow",Icon:Ja},{op:"deleteCol",key:"unipage.table.deleteCol",Icon:Ja}],Fv=[{align:"left",key:"unipage.table.alignLeft",Icon:ip},{align:"center",key:"unipage.table.alignCenter",Icon:nf},{align:"right",key:"unipage.table.alignRight",Icon:of}];function _v({view:e,cell:t,onDone:n}){const{t:o}=Ht(),r=e.state.selection;if(!(r instanceof Ce)||r.node.type.spec.tableRole!=="table")return null;const s=tf(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")}),Ov.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(()=>rf(e.state,s.cellPos,i)),children:[u.jsx(l,{size:13})," ",o(a)]},i)),s.align&&Fv.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(()=>sf(e.state,s.cellPos,i)),children:[u.jsx(l,{size:13})," ",o(a),s.align===i&&u.jsx(Ms,{size:13,className:"ubm-check"})]},i))]})}function Bv(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}}}En({"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 Hv=800;let Ws=null,Va=null;const Kv={insertAfter:()=>{},deleteEmpty:()=>{},mergePrev:()=>{},arrow:()=>{},moveDir:()=>{},selfFocus:()=>{}};async function Qu(e,t){try{const n=new Uint8Array(await t.arrayBuffer()),{opts:o}=await ea(),{base:r}=await rn.saveAttachment(e,t.name||"file",n,o);return`![[${r}]]`}catch{return null}}let Er=null;function Mr(){Er&&(clearTimeout(Er.timer),clearTimeout(Er.arm),Er.off(),Er.el.remove(),Er=null)}function Xs(e){if(Mr(),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",Mr,!0),window.removeEventListener("wheel",Mr,!0)},r=window.setTimeout(()=>{window.addEventListener("scroll",Mr,!0),window.addEventListener("wheel",Mr,!0)},300);Er={el:t,timer:window.setTimeout(Mr,1400),arm:r,off:o}}function Vv(e,t,n=!1,o=!1){const r=[],s=av(e.state,t,n?r:void 0);s&&(o&&s.setMeta("addToHistory",!0),e.dispatch(n?dv(s,e.state.doc,r):s))}function qv({path:e,pageDir:t,body:n,onChange:o,onFinalFlush:r,skipFinalFlush:s,hidden:c,apiRef:i,probe:a,extraPlugins:l,focusPlace:m,onFocused:h,onCard:E,readOnly:R=!1,onAskTangu:k,aiMenu:v,onAiPrompt:j}){const[,P]=ff(),q=Es(),X=x.useRef(null),[_,Z]=x.useState(!1),ze=x.useRef({onFinalFlush:r,skipFinalFlush:s});ze.current={onFinalFlush:r,skipFinalFlush:s};const Ke=x.useRef(E);Ke.current=E;const p=x.useRef(j);p.current=j,x.useEffect(()=>(i.current={applySlashItem:ee=>rt.current(ee),applyBody:(ee,ge,Se)=>{let C=!1;return P()?.action(Y=>{const fe=Y.get(Sn),ye=Y.get(Dr)(br(ee,t));ye&&(Vv(fe,ye,ge,Se),mf(fe.state.doc,ye),C=!0,a&&(a.reconciled=(a.reconciled??0)+1))}),C},serializeNow:()=>{let ee=null;return P()?.action(ge=>{const Se=ge.get(Sn);ee=_r(Rs(ge,Se.state.doc),t)}),ee},canonical:ee=>{let ge=null;return P()?.action(Se=>{const C=Se.get(Dr)(br(ee,t));C&&(ge=_r(Rs(Se,C),t))}),ge},insertFiles:ee=>{Qe(ee)},insertMarkdown:(ee,ge,Se)=>de(ee,ge,Se),parseMd:ee=>{let ge=null;return P()?.action(Se=>{const C=Se.get(Dr)(br(ee,t));ge=C?.childCount?C.content:null}),ge},serializeMd:ee=>{let ge=null;try{P()?.action(Se=>{const Y=Se.get(Sn).state.schema.topNodeType.createAndFill(void 0,ee);Y&&(ge=pf(Se.get(vp)(Y)))})}catch{return null}return ge},serializeStored:ee=>{let ge=null;try{P()?.action(Se=>{const C=Se.get(Sn).state.schema.topNodeType.createAndFill(void 0,ee);C&&(ge=_r(Rs(Se,C),t))})}catch{return null}return ge},focusStart:()=>{P()?.action(ee=>{const ge=ee.get(Sn);ge.dispatch(ge.state.tr.setSelection(je.atStart(ge.state.doc))),ge.focus()})},focusEnd:()=>{P()?.action(ee=>{const ge=ee.get(Sn);ge.dispatch(ge.state.tr.setSelection(je.atEnd(ge.state.doc))),ge.focus()})},focusTail:()=>{P()?.action(ee=>{const ge=ee.get(Sn),{doc:Se,schema:C}=ge.state,Y=C.nodes.paragraph,fe=Fe=>!!Fe&&Fe.type===Y&&Fe.content.size===0,ye=Se.lastChild;let Ye=ge.state.tr;fe(ye)||(Ye=Ye.insert(Se.content.size,Y.create())),ge.dispatch(Ye.setSelection(je.atEnd(Ye.doc)).scrollIntoView()),ge.focus()})},hasFocus:()=>{let ee=!1;return P()?.action(ge=>{ee=ge.get(Sn).hasFocus()}),ee},revealSelection:()=>{P()?.action(ee=>{const ge=ee.get(Sn);ge.dispatch(ge.state.tr.scrollIntoView()),ge.focus()})},serializePrefix:ee=>{let ge=null;try{P()?.action(Se=>{const C=Se.get(Sn);ge=_r(Rs(Se,C.state.doc.cut(0,Math.min(ee,C.state.doc.content.size))),t)})}catch{return null}return ge},posAfterPrefix:ee=>{let ge=null;try{P()?.action(Se=>{const C=Se.get(Dr)(br(ee,t));C&&(ge=je.atEnd(C).head)})}catch{return null}return ge}},()=>{if(!ze.current.skipFinalFlush()){const ee=i.current?.serializeNow()??null;ee!=null&&ze.current.onFinalFlush(ee)}i.current=null}),[P,t]);const xe=async ee=>{try{const ge=new Uint8Array(await ee.arrayBuffer()),{opts:Se}=await ea(),{pageRel:C}=await rn.saveAttachment(e,ee.name||"pasted.png",ge,Se);return pc(mc(t,C),!0)}catch{return null}},Qe=async ee=>{if(!ee.length)return;const ge=ee.map((C,Y)=>`​${Te("unipage.upload.uploading",{name:C.name||Te("unipage.upload.fileN",{n:Y+1})})}​`);P()?.action(C=>{const Y=C.get(Sn),fe=Y.state.schema.nodes.paragraph;if(!fe)return;const{$to:ye}=Y.state.selection;let Ye=ye.depth>=1?ye.after(1):ye.pos,Fe=Y.state.tr;for(const ht of ge){const ct=fe.create(null,Y.state.schema.text(ht));Fe=Fe.insert(Ye,ct),Ye+=ct.nodeSize}Y.dispatch(Fe.scrollIntoView())});const Se=(C,Y)=>{P()?.action(fe=>{const ye=fe.get(Sn);let Ye=-1,Fe=-1;if(ye.state.doc.descendants((jt,Et)=>Ye>=0||!jt.isTextblock||jt.textContent!==C?!0:(Ye=Et,Fe=Et+jt.nodeSize,!1)),Ye<0)return;const ht={from:Ye,to:Fe},ct=ye.state.schema.nodes.paragraph,Kt=Y&&ct?ye.state.tr.replaceWith(ht.from,ht.to,ct.create(null,ye.state.schema.text(Y))):ye.state.tr.delete(ht.from,ht.to);ye.dispatch(Kt)})};for(let C=0;C<ee.length;C++)Se(ge[C],await Qu(e,ee[C]))},de=(ee,ge="cursor",Se)=>{let C=!1;return P()?.action(Y=>{const fe=Y.get(Sn),ye=Y.get(Dr)(br(ee,t));if(!ye?.childCount)return;const Ye=ye.content,Fe=!!Se?.quiet,ht=Fe?Lv(fe.state.doc,Se?.after):null;if(Fe&&ht==null&&Se?.caretless&&(ge="end"),ge!=="cursor"||ht!=null){const dt=ht??(ge==="start"?0:fe.state.doc.content.size),pt=fe.state.tr.insert(dt,Ye);Fe?ce(fe,pt,dt):fe.dispatch(pt),C=!0;return}const{$from:ct}=fe.state.selection;let Kt=ct.depth;for(;Kt>=1&&!["doc","amadeusColumnCell","blockquote"].includes(ct.node(Kt-1).type.name);)Kt--;if(Kt<1)return;const jt=(dt,pt)=>{const _t=je.near(dt.doc.resolve(Math.min(pt,dt.doc.content.size)),-1),dn=Se?.caretBack??0;dt.setSelection(dn&&_t.$from.parentOffset>=dn?je.create(dt.doc,_t.from-dn):_t)};if(ct.depth>Kt&&ct.parent.isTextblock&&ct.parent.content.size===0){const dt=fe.state.tr,pt=dn=>{const Jt=dt.doc.resolve(dn),An=Jt.index(-1);return Jt.parent.isTextblock&&Jt.parent.content.size===0&&Jt.node(-1).canReplace(An,An+1,Ye)};let _t=ct.pos;if(!pt(_t)){for(let dn=dt.doc.resolve(_t).depth;dn>0;dn--)if(dt.doc.resolve(_t).node(dn).type.name==="list_item"){_t=hf(dt,_t,["list_item"]);break}}if(pt(_t)){const dn=dt.doc.resolve(_t),Jt=dn.before();dt.replaceWith(Jt,dn.after(),Ye),Zs(dt,Jt,Jt+Ye.size),jt(dt,Jt+Ye.size),Fe?ce(fe,dt,Jt):(fe.dispatch(dt.scrollIntoView()),fe.focus()),C=!0;return}}const Et=ct.before(Kt),Gt=ct.after(Kt),et=ct.node(Kt).textContent.trim()==="",un=et?fe.state.tr.replaceWith(Et,Gt,Ye):fe.state.tr.insert(Gt,Ye);Zs(un,et?Et:Gt,(et?Et:Gt)+Ye.size),jt(un,(et?Et:Gt)+Ye.size),Fe?ce(fe,un,et?Et:Gt):(fe.dispatch(un.scrollIntoView()),fe.focus()),C=!0}),C},ce=(ee,ge,Se)=>{ee.dispatch(Qs(ge)),ql(ee,Math.min(Se+1,ee.state.doc.content.size));const C=ee.nodeDOM(Se);if(!(C instanceof HTMLElement))return;const Y=C.getBoundingClientRect();(Y.top<0||Y.top>window.innerHeight-40)&&is(C),Xs(C.getBoundingClientRect())},se=(ee,ge=!0)=>{let Se=null;return P()?.action(C=>{Se=vv(C.get(Sn),ee,ge)}),Se},ae=ee=>{ee&&P()?.action(ge=>Xu(ge.get(Sn),ee.id))},Re=(ee,ge,Se=!0)=>{if(ge?.cancelled())return;if(c?.()){ae(ge),Tl(ge?.label??"");return}const C=()=>{Se||!ge?window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.insertPointLost")}})):kv(ge.label)};if(!i.current||!ge){C();return}let Y=!1;P()?.action(fe=>{const ye=fe.get(Dr)(br(ee,t));Y=wv(fe.get(Sn),ge.id,ye?.childCount?ye.content:null)}),Y||C()},Me=async(ee,ge,Se,C=!1)=>{try{const{base:Y}=await rn.saveAttachment(e,ee,ge,{mode:"vault",folder:ka(e)});return Re(`![[${C?Y.replace(/\.md$/i,""):Y}]]`,Se),q.getState().syncFdChildren(e),!0}catch{return ae(Se),!1}},rt=x.useRef(()=>{}),Je=ee=>{const ge=X.current;if(!ge)return;const Se=ee.run?void 0:yf[ee.scaffold];if(Se){ge.transform(Se)||bf(ee.label);return}ge.consume();const C=vf;if(ee.scaffold===C.template){window.dispatchEvent(new CustomEvent("amadeus:template-picker",{detail:{v4Path:e}}));return}if(ee.scaffold===C.card){P()?.action(Y=>Ke.current(Y.get(Sn)));return}if(ee.scaffold===C.instructions||ee.scaffold===C.agentTask||ee.scaffold===C.prompt){const Y=ee.scaffold===C.instructions?"instructions":ee.scaffold===C.agentTask?"task":"prompt";de(wf(Y,Y==="instructions"?"":hs(kf())));return}if(ee.scaffold===C.ai){P()?.action(Y=>p.current?.(Y.get(Sn)));return}if(ee.run){const Y=se(ee.label);(async()=>{try{const fe=await ee.run({pagePath:e,folder:ka(e)});if(fe===""||fe==null){ae(Y);return}if(typeof fe!="string")throw new Error(Te("unipage.plugin.notString",{type:typeof fe}));if(fe.length>8192)throw new Error(Te("unipage.plugin.tooLong"));if(Array.from(fe).some(ye=>ye.charCodeAt(0)<32&&ye!==" "&&ye!==`
708
- `))throw new Error(Te("unipage.plugin.controlChars"));Re(fe,Y,!1),q.getState().syncFdChildren(e)}catch(fe){if(ae(Y),Y?.cancelled())return;console.error("[plugin] slash item failed",fe),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.plugin.failed",{label:ee.label,err:fe instanceof Error?fe.message:String(fe)}),error:!0}}))}})();return}if(ee.scaffold===C.image){const Y=document.createElement("input");Y.type="file",Y.accept="image/*",Y.onchange=()=>{const fe=Y.files?.[0];if(!fe)return;const ye=se(ee.label);(async()=>{try{const Ye=new Uint8Array(await fe.arrayBuffer()),{opts:Fe}=await ea(),{base:ht}=await rn.saveAttachment(e,fe.name||"image.png",Ye,Fe);Re(`![[${ht}]]`,ye)}catch{ae(ye)}})()},Y.click();return}if(ee.scaffold===C.column){P()?.action(Y=>{const fe=Y.get(Sn),{$from:ye}=fe.state.selection;if(ye.depth!==1){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.columnTopLevelOnly")}}));return}vu(fe,ye.before(1),ye.after(1),ye.node(1)),fe.focus()});return}if(ee.scaffold===C.page){const Y=se(ee.label);(async()=>{try{const fe=q.getState(),ye=await fe.createChildNote(e,Te("amadeus.default.note"));Re(`[[${ye.split("/").pop().replace(/\.md$/i,"")}]]`,Y),fe.loadPage(ye)}catch{ae(Y)}})();return}if(ee.scaffold===C.database){const Y=Te("amadeus.default.database");Me(`${Y}.db`,new TextEncoder().encode(Zc(Td(Y))),se(ee.label)).then(fe=>{fe&&Zl("base.create")});return}if(ee.scaffold===C.drawing){Me(`${Sf(Te("unipage.file.drawing"))}.excalidraw.md`,new TextEncoder().encode($d(jd)),se(ee.label),!0);return}if(ee.scaffold===C.noteview){const Y=se(ee.label);(async()=>{const fe=ka(e);let ye=null;for(let Fe=1;Fe<=20&&ye===null;Fe++)try{ye=await rn.createFolder(fe,Fe===1?Te("unipage.file.noteView"):Te("unipage.file.noteViewN",{n:Fe}))}catch{}if(ye===null){ae(Y);return}const Ye=Te("unipage.file.untitledView");await Me(`${Ye}.db`,new TextEncoder().encode(Zc(Ld(Ye,ye))),Y)})();return}if(ee.scaffold===C.linkdb){Z(!0);return}if(ee.scaffold===C.bookmark){const Y=se(ee.label,!1);Xa(Te("unipage.bookmark.title"),"",{label:Te("unipage.bookmark.label")}).then(fe=>{const ye=fe?.trim();ye&&/^https?:\/\/\S+$/i.test(ye)?Re(ye,Y,!1):ae(Y)});return}if(ee.scaffold===C.embed){const Y=se(ee.label,!1);(async()=>{let fe="";try{const Fe=/!?\[\[([^\]\n]+)\]\]/.exec(await navigator.clipboard.readText());Fe&&(fe=Fe[1].trim())}catch{}const Ye=(await Xa(Te("unipage.embed.title"),fe,{label:Te("unipage.embed.label"),confirmLabel:Te("unipage.embed.confirm")}))?.trim().replace(/^!?\[\[/,"").replace(/\]\]$/,"").trim();Ye?Re(`![[${Ye}]]`,Y,!1):ae(Y)})();return}de(ee.scaffold,"cursor",ee.key==="math"?{caretBack:3}:void 0)};return rt.current=Je,u.jsxs(u.Fragment,{children:[u.jsx(gf,{initial:br(n,t),onChange:ee=>o(_r(ee,t)),keys:Kv,saveImage:xe,saveFiles:Qe,onOpenWiki:(ee,ge)=>{q.getState().openWikiLink(ee,e,ge??{split:!0})},getPageNames:()=>q.getState().pages,slashOpsRef:X,onSlashPick:Je,getFiles:()=>wp()?q.getState().files:[],isWikiResolved:ee=>!!gs(ee,q.getState().pages,e)||!!mm(ee,q.getState().files,e),wikiIcon:ee=>{const ge=gs(ee,q.getState().pages,e);return ge?q.getState().icons[ge]:void 0},focusPlace:m,onFocused:h,unified:!0,attachmentPagePath:e,extraPlugins:l,readOnly:R,onAskTangu:k,aiMenu:v}),_&&u.jsx(ir,{children:u.jsx(xf,{onClose:()=>Z(!1),onPick:ee=>{Z(!1),c?.()?Tl(Te("mdblock.slash.linkdb")):de(`![[${ee}]]`)}})})]})}function Dl(e){e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)}function Wv(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 Yv({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:h}=Ht(),E=Vl(),R=(e.split("/").pop()??e).replace(/\.md$/i,""),k=Pg.test(R)?"":R,[v,j]=x.useState(k),[P,q]=x.useState(null),[X,_]=x.useState(null),Z=x.useRef(null),ze=x.useRef(null),Ke=x.useRef(c);Ke.current=c,x.useEffect(()=>{j(k),ze.current=null},[e]),x.useLayoutEffect(()=>()=>{const de=ze.current;ze.current=null,de!=null&&Ke.current(de)},[]),x.useLayoutEffect(()=>{Dl(Z.current)},[v]),x.useEffect(()=>{const de=Z.current;if(!de)return;let ce=de.clientWidth;const se=new ResizeObserver(()=>{de.clientWidth!==ce&&(ce=de.clientWidth,Dl(de))});return se.observe(de),()=>se.disconnect()},[]),x.useEffect(()=>{if(!a)return;const de=Z.current;if(de){de.focus();const ce=de.value.length;de.setSelectionRange(ce,ce)}},[a]);const p=x.useRef(null),xe=x.useRef(!1),Qe=()=>{const de=p.current;if(p.current=null,ze.current=null,xe.current){xe.current=!1,j(k);return}const ce=v.trim();ce&&ce!==R?s(ce,de).then(se=>{se||j(k)}):j(k)};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:k||R})})]}):u.jsxs("div",{className:"amx-title-wrap",children:[!l&&t&&u.jsx("button",{className:"amx-title-bigicon",title:h("unipage.title.iconAction"),onClick:de=>{const ce=de.currentTarget.getBoundingClientRect();q({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(Hg()),children:[u.jsx(Hh,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),h("unipage.title.addIcon")]}),!n&&u.jsxs("button",{onClick:de=>{const ce=de.currentTarget.getBoundingClientRect();_({x:ce.right,y:ce.bottom+6})},children:[u.jsx(Gl,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),h("unipage.title.addCover")]})]}),u.jsx("div",{className:"amx-title-row",children:u.jsx("textarea",{ref:Z,className:"amx-title-input",rows:1,spellCheck:E,value:v,placeholder:"New Page",onChange:de=>{const ce=de.target.value.replace(/[\r\n]+/g," ");ze.current=ce,j(ce)},onBlur:Qe,onKeyDown:de=>{if(de.nativeEvent.isComposing||de.keyCode===229)return;const ce=de.currentTarget;if(de.key==="Tab"){de.preventDefault();return}const se=ce.selectionStart===ce.selectionEnd,ae=se&&ce.selectionEnd===ce.value.length,Re=!de.shiftKey&&!de.altKey&&!de.metaKey&&!de.ctrlKey,Me=de.key==="ArrowDown"&&Re&&se&&Wv(ce);(de.key==="Enter"||de.key==="ArrowRight"&&Re&&ae||Me)&&(de.preventDefault(),p.current=de.key==="Enter"?"enter":"move",ce.blur(),i(de.key==="Enter"?"enter":"move")),de.key==="Escape"&&(ze.current=null,xe.current=!0,j(k),ce.blur())}})}),P&&u.jsx(Kg,{x:P.x,y:P.y,current:t,onPick:de=>{o(de),q(null)},onClose:()=>q(null)}),X&&u.jsx(fu,{page:e,x:X.x,y:X.y,onApply:de=>r(de),onClose:()=>_(null)})]})}function Uv({path:e,initial:t,diskRaw:n,probe:o,onRenamed:r,onCanvasMode:s,historyRef:c,filesRef:i,mdRef:a,onUnlock:l,compact:m=!1,readOnly:h=!1,hardBreaks:E=!1}){const R=e.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),k=Es(),v=k.getState().vaultRoot,j=x.useContext(Zp),P=Qp(),q=j??P,X=lp(d=>up(d,q)),_=h?"wysiwyg":X,{t:Z}=Ht(),ze=Vl(),Ke=x.useRef(null);if(!Ke.current){const d=qr(n??t),{fmText:y,body:w}=Sr(n==null?d.text:qr(t).text);Ke.current={fm:y,body:w,lastSaved:d.text,eol:d.eol,pending:!1,timer:null,reconcileBusy:0,unpreserved:null,preserved:new Set,failed:!1,retryTimer:null,retryN:0,stashed:null,writing:0,dead:!1,retired:!1,sawRows:!1,ownedCards:new Set,chain:Promise.resolve(),readOnly:h,slot:j,peerPatch:null}}const p=Ke.current,xe=x.useRef(0),Qe=x.useRef(null),de=x.useRef(()=>{Qe.current?.()}).current,ce=()=>{xe.current=performance.now(),di(de)},se=x.useRef(!1);x.useEffect(()=>{j!=null&&j===P&&ce()},[j,P]);const[ae]=x.useState(()=>new Set),Re=()=>{for(const d of[...ae])d()},[Me,rt]=x.useState(0),[Je,ee]=x.useState(0),ge=x.useRef(null),Se=x.useRef(_==="source"),C=x.useMemo(()=>({get current(){return Se.current?null:ge.current}}),[]);if(Se.current!==(_==="source")){if(_==="source"){const d=ge.current?.serializeNow();d!=null&&(p.body=d)}Se.current=_==="source"}const Y=x.useRef(null),fe=x.useRef(null),[ye,Ye]=x.useState(null),[Fe,ht]=x.useState(()=>{if(Vr())return!1;const d=em(v,e);return d?d==="canvas":_n(pn(p.fm))?.mode==="canvas"}),[ct,Kt]=x.useState(0),jt=x.useRef(!1),Et=x.useRef(Fe);Et.current=Fe;const Gt=x.useRef(!1),et=pn(p.fm),un=x.useMemo(()=>_n(et),[et]),dt=un?.main??{x:0,y:0,w:Ko},pt=()=>{const d=!Fe;if((C.current?.hasFocus()??!1)&&(d?Kt(w=>w+1):jt.current=!0),d){const w=fe.current?.closest(".amx-pane");w&&ki(v,e,w.scrollTop)}Et.current=d,Gt.current=!0,am(v,e,d?"canvas":"doc"),ht(d),d&&Zl("note.canvas"),pn(p.fm)!=null&&($t(),Ut())},_t=x.useRef(pt);_t.current=pt,Qe.current=_==="source"?null:()=>_t.current(),tm(j,_==="source"?null:cu(Fe,()=>_t.current())),x.useEffect(()=>(di(de),()=>dp(de)),[de]);const dn=x.useRef(d=>C.current?.applySlashItem(d)).current;x.useEffect(()=>(ba(dn),()=>{Cf()===dn&&ba(null)}),[dn]),x.useEffect(()=>(s?.({on:Fe,toggle:()=>_t.current(),...Fe&&_!=="source"&&!h?{exportCanvas:()=>An.current?.()}:{}}),()=>s?.(null)),[Fe,s,_,h]);const Jt=x.useRef(null),An=x.useRef(null);x.useEffect(()=>{if(!c)return;const d=M=>{if(p.readOnly)return!1;if(Et.current&&Jt.current)return Jt.current(M);const D=Yt();return!!D&&(M==="undo"?Ya:Kl)(D.state,D.dispatch)},w={undo:()=>d("undo"),redo:()=>d("redo"),indent:M=>{const D=Yt();return!p.readOnly&&!!D&&Oe.indent(D,M)}};return c.current=w,()=>{c.current===w&&(c.current=null)}},[c]);const Jn=d=>{const y=pn(p.fm);if(y!=null&&_n(y)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.canvasElementsFailed"),error:!0}}));return}p.fm=ds(p.fm,mo(p.fm),yb(y,d)),rt(w=>w+1),T(),Ut()},pr=d=>{const y=pn(p.fm);if(y!=null&&_n(y)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.canvasTreeFailed"),error:!0}}));return}p.fm=ds(p.fm,mo(p.fm),vb(y,d)),rt(w=>w+1),T(),Ut()},sn=d=>{const y=pn(p.fm);if(y!=null&&_n(y)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.canvasMainFailed"),error:!0}}));return}p.fm=ds(p.fm,mo(p.fm),bb(y,d)),rt(w=>w+1),T(),Ut()},Wn=x.useMemo(()=>({log:[],future:[]}),[e]),Nn=Fe&&_!=="source";x.useEffect(()=>{Ye(fe.current)},[]),x.useEffect(()=>{const d=Y.current?.closest(".amx-pane");if(d)return d.classList.toggle("amx-canvas-pane",Nn),()=>d.classList.remove("amx-canvas-pane")},[Nn]),x.useEffect(()=>{if(Fe)return;const d=fe.current?.closest(".amx-pane");if(!d)return;const y=nm(v,e);let w=!1,M=0;const D=performance.now()+1500,z=()=>{if(d.scrollTop=y,d.scrollTop!==y&&performance.now()<D){M=requestAnimationFrame(z);return}w=!0};M=requestAnimationFrame(z);const Q=()=>{cancelAnimationFrame(M),w=!0},S=()=>{w&&ki(v,e,d.scrollTop)};return d.addEventListener("scroll",S,{passive:!0}),d.addEventListener("wheel",Q,{passive:!0}),d.addEventListener("pointerdown",Q),d.addEventListener("keydown",Q),()=>{cancelAnimationFrame(M),d.removeEventListener("scroll",S),d.removeEventListener("wheel",Q),d.removeEventListener("pointerdown",Q),d.removeEventListener("keydown",Q)}},[Fe,e,v]),x.useEffect(()=>{if(Fe||!jt.current)return;jt.current=!1;let d=0;const y=requestAnimationFrame(()=>{d=requestAnimationFrame(()=>C.current?.revealSelection())});return()=>{cancelAnimationFrame(y),cancelAnimationFrame(d)}},[Fe]);const[Zn,No]=x.useState(()=>{const d=Ws;return d?.path===e&&d.scope===j?(Ws=null,Date.now()-d.at<1e4?d.req:null):null}),Uo=x.useRef(Zn);Uo.current=Zn;const Xo=x.useRef(null),[Mn,Tn]=x.useState(null),[Dn,ho]=x.useState(null),go=x.useRef(0);x.useEffect(()=>{Mn||(ho(null),clearTimeout(go.current))},[Mn]);const ut=(d,y)=>{if(clearTimeout(go.current),Dn&&!y)return;const w=d.closest(".unified-block-menu");if(!w)return;const M=w.getBoundingClientRect(),D=d.getBoundingClientRect(),z=M.right+4+M.width>window.innerWidth-8;ho({x:z?M.left-4-M.width:M.right+4,y:D.top-5,anchorTop:D.bottom+5,focus:y})},Dt=()=>{clearTimeout(go.current),go.current=window.setTimeout(()=>{document.querySelector(".unified-block-submenu")?.contains(document.activeElement)&&document.querySelector('.unified-block-menu [data-sub="turnInto"]')?.focus(),ho(null)},180)};x.useLayoutEffect(()=>{if(!Dn?.focus)return;let d=0,y=0;const w=()=>{const M=document.querySelector(".unified-block-submenu button");M?.focus(),document.activeElement!==M&&++d<10&&(y=requestAnimationFrame(w))};return w(),()=>cancelAnimationFrame(y)},[Dn]);const xo=x.useRef(null),[co,Go]=x.useState(null),To=x.useRef(()=>{}),Vn=x.useRef({tree:()=>({}),detach:()=>{},minted:()=>{}}),Oe=x.useMemo(()=>cb({onMenu:d=>{const y=Oe.getView();xo.current=y?{doc:y.state.doc,sel:y.state.selection}:null,Tn({...d,cell:Pv(y,d.x,d.y)})},onBlocksDeleted:d=>To.current(d),canvasTree:()=>Vn.current.tree(),onCardDetach:d=>Vn.current.detach(d),onCardsMinted:d=>Vn.current.minted(d)}),[]),Yt=()=>Se.current?null:Oe.getView(),[g]=x.useState(()=>yg(Yt)),A=d=>{const y=Oe.getView();y&&ib(e,ul(d),ul(y.state.doc.content))};To.current=A,Vn.current={tree:()=>Vt(_n(pn(p.fm))?.tree),detach:d=>{const y=Vt(_n(pn(p.fm))?.tree);let w=!1;for(const M of d)M in y&&(delete y[M],w=!0);w&&pr(y)},minted:d=>{for(const y of d)p.ownedCards.add(y)}};const O=x.useRef({vaultRoot:v,path:e});O.current={vaultRoot:v,path:e};const I=x.useRef(!1),V=x.useRef(()=>{}),[G,le]=x.useState({count:0,index:0}),J=x.useRef(()=>{}),ne=v?`${v.replace(/[\\/]+$/,"")}/${e}`:e,W=x.useSyncExternalStore(fp,()=>!h&&pp(ne));J.current=d=>{const y=d.current==null?0:d.changes.findIndex(w=>w.id===d.current)+1;le(w=>w.count===d.changes.length&&w.index===y?w:{count:d.changes.length,index:y})};const Ae=x.useMemo(()=>[...Oe.plugins,...Dx,...zx(()=>$a(mo(p.fm)),()=>{p.sawRows=!0}),...Cb,...hb(()=>_n(pn(p.fm)),()=>$a(mo(p.fm)),d=>{for(const y of d)p.ownedCards.add(y)}),...jy({path:e,readOnly:h,alive:()=>!p.dead&&!p.retired&&!p.readOnly&&!Se.current,flush:async()=>{if(p.dead||p.retired||p.readOnly||Se.current)throw new Error(Te("documentTask.sourceGone"));if($t(),Re(),p.timer&&(clearTimeout(p.timer),p.timer=null),await hn(!0),p.dead||p.retired||p.failed)throw new Error(Te("documentTask.sourceGone"))}}),xg(),...yv(),...Eb(()=>Et.current),...$b(Wn),...Mb(),...Nb(()=>_n(pn(p.fm))),...lv(J),...Ev({spaceTrigger:()=>Gh()&&I.current,onSpace:V}),...Em,...Mm,...Wm(()=>O.current),...bg(),...vg(()=>an.current()),...wg({where:()=>O.current,restore:()=>bt.current(),focus:()=>Rt.current()}),...E?cf:[]],[Oe,e,h,E]);x.useEffect(()=>{if(!Mn)return;const d=M=>{M.target?.closest?.(".ctx-menu")||Tn(null)},y=M=>{const D=document.querySelector(".unified-block-menu"),z=document.querySelector(".unified-block-submenu"),Q=!!z&&z.contains(document.activeElement),S=!!D&&D.contains(document.activeElement)||Q,pe=D?.querySelector('[data-sub="turnInto"]');if(M.key==="Escape"){if(M.stopPropagation(),Q){ho(null),pe?.focus();return}Tn(null),Oe.getView()?.focus();return}if(!D||M.isComposing)return;const me=!M.metaKey&&!M.ctrlKey&&!M.altKey&&!M.shiftKey;if(me&&Q&&M.key==="ArrowLeft"){M.preventDefault(),M.stopPropagation(),ho(null),pe?.focus();return}if(me&&!Q&&M.key==="ArrowRight"&&pe&&document.activeElement===pe){M.preventDefault(),M.stopPropagation(),ut(pe,!0);return}if(me&&["ArrowDown","ArrowUp","Home","End"].includes(M.key)){M.preventDefault(),M.stopPropagation();const He=[...(Q?z:D).querySelectorAll('button:not([aria-disabled="true"])')],Ge=He.indexOf(document.activeElement),qe=He.length,it=M.key==="Home"?0:M.key==="End"?qe-1:Ge<0?M.key==="ArrowUp"?qe-1:0:(Ge+(M.key==="ArrowDown"?1:-1)+qe)%qe;He[it]?.focus();return}S&&(M.key==="Enter"||M.key===" ")||["Shift","Meta","Control","Alt","CapsLock"].includes(M.key)||(Tn(null),S&&(M.preventDefault(),Oe.getView()?.focus()))};let w=0;if(Mn.keyboard){let M=0;const D=()=>{const z=document.querySelector(".unified-block-menu");if(!z){++M<10&&(w=requestAnimationFrame(D));return}const Q=Mn.focus==="turnInto"?z.querySelector('[data-sub="turnInto"]'):null;if(Q){ut(Q,!0);return}z.querySelector("button")?.focus()};w=requestAnimationFrame(D)}return window.addEventListener("pointerdown",d,!0),window.addEventListener("contextmenu",d,!0),window.addEventListener("keydown",y,!0),()=>{cancelAnimationFrame(w),window.removeEventListener("pointerdown",d,!0),window.removeEventListener("contextmenu",d,!0),window.removeEventListener("keydown",y,!0)}},[Mn]);const Pe=d=>{const y=xo.current;return xo.current=null,y?d.state.doc!==y.doc?(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.menu.stale")}})),!1):(d.state.selection.eq(y.sel)||d.dispatch(d.state.tr.setSelection(y.sel)),!0):!0},_e=d=>{Tn(null);const y=Oe.getView();if(!y||!Pe(y))return;const w=y.state.selection;w instanceof Ce&&(d(y,w),y.focus())},Be=(d,y)=>{Tn(null);const w=Oe.getView();if(!w||!Pe(w))return;const M=Oe.topRangeOf(w);M?d(w,M):w.state.selection instanceof Ce&&y(w,w.state.selection),w.focus()},Ve=d=>{const y=d.state.selection,w=Oe.topRangeOf(d)??(y instanceof Ce?{from:y.from,to:y.to}:null);return w&&{from:w.from,to:fs(d.state,w.from,w.to)}},Xe=!h&&!!zr()?.askInChat,We=(d,y,w)=>{const M=jv(d.state.doc,y,w,e);M&&zr()?.askInChat?.([ku(ac(d.state.doc),e),M].filter(Boolean).join(`
709
-
710
- `).slice(0,2e4))},Ze=!h&&!!zr()?.complete;I.current=Ze;const Zt=Ur(d=>d.selectionActions),[xt,yt]=x.useState(null),Yn=["improve","fix","shorter","longer","summarize","continue","custom"].map(d=>({id:d,label:Z(`inlineai.action.${d}`)})),It=(d,y)=>{const w=Oe.getView()?.state.doc,M=w?w.textBetween(Math.min(d,w.content.size),Math.min(y,w.content.size),`
711
- `,"").length:y-d;return Vm(Zt,{view:"note",editable:!0,length:M}).map(D=>{const z=zp(D.item.icon);return{id:qm(D),label:D.item.title,icon:z?u.jsx("span",{className:"selbar-ico",children:z}):void 0}})},nn=e.split("/").pop().replace(/\.md$/i,""),Un=(d,y)=>{if(!Ze)return;const w=d.state.selection,M=y==="prompt",D=M?w.head:w.from,z=M?w.head:w.to;if(!M&&z<=D)return;const Q=y.startsWith("plugin:")?y.slice(7):void 0,S=Q?Zt.find(it=>`${it.pluginId}:${it.item.id}`===Q):void 0,pe=d.state.doc.textBetween(D,z,`
712
- `,"");if(S?.item.output==="none"){const it=C.current?.serializeMd(d.state.doc.slice(D,z).content)??pe;Ri(S,{text:pe,markdown:it,pagePath:e,view:"note",editable:!0,source:{path:e,title:nn}}).catch(on=>window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("selbar.failed",{title:S.item.title,e:String(on?.message||on)})}})));return}Mv(d,D,z);const me=d.coordsAtPos(D),He=d.coordsAtPos(z),Ge=Q||M?M?"prompt":"custom":y,qe=Q?S?.item.title??Z("inlineai.label"):Z(M?"inlineai.label":`inlineai.action.${y}`);yt({key:Date.now(),x:me.left,y:He.bottom+6,top:me.top-6,title:qe,hasSelection:!M,askFirst:M||y==="custom",action:Ge,plugin:Q,...y==="translate"?{language:ji(pe)}:{}})};V.current=d=>Un(d,"prompt");const $o=d=>async(y,w,M)=>{const D=Oe.getView(),z=D?jl(D):null;if(!D||!z)throw new Error(Te("unipage.toast.insertPointLost"));const Q=z.to>z.from?C.current?.serializeMd(D.state.doc.slice(z.from,z.to).content)??z.text:"";if(d.plugin){const Ge=Ur.getState().selectionActions.find(qe=>`${qe.pluginId}:${qe.item.id}`===d.plugin);if(!Ge)throw new Error(Te("selbar.err.gone"));return{text:await Ri(Ge,{text:z.text,markdown:Q,pagePath:e,view:"note",editable:!0,source:{path:e,title:nn},signal:M,onDelta:qe=>{typeof qe=="string"&&w(qe)}})}}const S=zr();if(!S?.complete)throw new Error(Te("inlineai.unavailable"));const{before:pe,after:me}=zv(D.state.doc,z.from,z.to),He=d.action==="prompt"?y?"custom":"continue":d.action;return S.complete({action:He,...y?{instruction:y}:{},...Q?{selection:Q}:{},...pe?{before:pe}:{},...me?{after:me}:{},title:nn,pagePath:e,pageInstructions:ac(D.state.doc),...He==="translate"?{language:d.language??ji(z.text)}:{}},{signal:M,onDelta:w})},Tr=()=>{yt(null);const d=Oe.getView();d&&($l(d),d.focus())},Bn=(d,y)=>{const w=Oe.getView(),M=w?jl(w):null,D=C.current?.parseMd(y);if(yt(null),!w||!M||!D){w&&$l(w),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.insertPointLost")}}));return}const z=Nv(w,M,D,d);w.focus(),$t(),Ut(),d==="replace"&&z==="below"&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("inlineai.targetChanged")}}))},mr=()=>{const d=Oe.getView();if(!d)return;const y=mv(d),w=y?Y.current?.querySelector(`[data-agent-change="${y.id}"]`):null;w instanceof HTMLElement&&is(w,48)},jo=()=>{const d=Oe.getView();if(!d)return;const{skipped:y}=fv(d);$t(),Ut(),y&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("agentchg.skipped",{n:String(y)})}}))},In=(d,y)=>{let w=!0;Be((M,D)=>{w=pu(M,D.from,D.to,d)},(M,D)=>{const z=Bi(M,D.from,D.to,d);if(z!=null){w=z;return}D.node.type.spec.code&&Mf(M,D.from,d)||(M.dispatch(M.state.tr.setSelection(je.near(M.state.doc.resolve(D.from+1)))),w=aa(M,d,null))}),w||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("mdblock.turn.failed",{kind:y})}}))},io=(d,y)=>{let w=!0;Be((M,D)=>{w=d==="code"?rc(M,D.from,D.to):_i(M,D.from,D.to,!0)},(M,D)=>{w=d==="code"?Bi(M,D.from,D.to,"code")??rc(M,D.from,D.to):_i(M,D.from,D.to,!1)}),w||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("mdblock.turn.failed",{kind:y})}}))},Jo=()=>{const d=Oe.getView();if(!d)return[];const y=[];if(!dc(d)){const M=(D,z,Q,S)=>{const pe=Z(Q);y.push({k:D,icon:z,label:pe,run:()=>S(pe)})};M("text",Li,"unipage.menu.text",D=>In({kind:"text"},D)),M("h1",hh,"unipage.menu.h1",D=>In({kind:"heading",level:1},D)),M("h2",xh,"unipage.menu.h2",D=>In({kind:"heading",level:2},D)),M("h3",bh,"unipage.menu.h3",D=>In({kind:"heading",level:3},D)),M("bullet",kp,"unipage.menu.bullet",D=>In({kind:"bullet"},D)),M("ordered",Sh,"unipage.menu.ordered",D=>In({kind:"ordered"},D)),M("task",Sp,"unipage.menu.task",D=>In({kind:"task"},D)),M("quote",Cp,"unipage.menu.quote",D=>In({kind:"quote"},D)),M("callout",Ep,"unipage.menu.callout",D=>io("callout",D)),M("fold",dh,"unipage.menu.fold",D=>In({kind:"fold"},D)),M("code",Gm,"unipage.menu.code",D=>io("code",D))}const w=d.state.selection;if(w instanceof Ce&&!["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(w.node.type.name)){const M=d.state.doc.resolve(w.from);let D=!1;for(let z=M.depth;z>=1;z--)M.node(z).type.name==="amadeusColumnCell"&&(D=!0);D||y.push({k:"card",icon:Ga,label:Z("unipage.menu.card"),run:()=>_e(z=>{Qn(z)})})}return y},Ro=()=>{const d=Oe.getView();if(!d||Oe.topRangeOf(d))return null;const y=d.state.selection;return y instanceof Ce?y.node.type.name==="list_item"?y.node.attrs.checked!=null?"task":y.$from.parent.type.name==="ordered_list"?"ordered":"bullet":qg(y.node):null},Qn=d=>{const y=()=>(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.cardUnavailable")}})),!1);if(!(d.state.selection instanceof Ce)){const{$from:Ge}=d.state.selection;for(let it=Ge.depth;it>=1;it--)if(Ge.node(it).type.name==="list_item")return y();let qe=Ge.depth;for(;qe>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard"].includes(Ge.node(qe-1).type.name);)qe--;if(qe<1)return!1;d.dispatch(d.state.tr.setSelection(Ce.create(d.state.doc,Ge.before(qe))))}const w=d.state.selection,M=d.state.doc.resolve(w.from),D=M.depth>=1?M.node(M.depth):null,z=D?.type.name==="amadeusCanvasCard"?String(D.attrs.anchor):"",Q=Vt(_n(pn(p.fm))?.tree);let S=0;d.state.doc.forEach(Ge=>{Ge.type.name==="amadeusCanvasCard"&&S++});const pe=z?(Number(D.attrs.x)||0)+(Number(D.attrs.w)||en)+80:dt.x+dt.w+80,me=z?(Number(D.attrs.y)||0)+Cr(Q,z).length*72:dt.y+S*72,He=Ku(d,Math.round(pe),Math.round(me),z?{parent:z,tree:Q}:void 0);return He?(p.ownedCards.add(He),$t(),Ut(),z&&pr(Kr(Vt(_n(pn(p.fm))?.tree),He,z)),!Et.current&&!z&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.cardMade")}})),!0):y()},wn=()=>{const d=Sr(p.lastSaved);if(d.fmText!==p.fm&&(p.peerPatch==null||za(d.fmText,p.peerPatch)!==p.fm))return!1;if(d.body===p.body)return!0;if(mo(p.fm)!=null||pn(p.fm)!=null)return!1;const y=C.current?.canonical(d.body);return y!=null&&y===p.body},Zo=x.useRef(null),Lo=()=>{Zo.current?.()},[Qo,lo]=x.useState(!1),qn=async d=>{const y=Br(d);if(p.preserved.has(y))return;const w=await Zr(e,oo(d,p.eol));p.preserved.add(y),Ci(e,w,!p.readOnly&&ui(ne,d)),k.getState().refreshPages()},hr=async d=>{const y=await Zr(e,oo(d,p.eol));gm(e,y),k.getState().refreshPages()},yo=()=>{if(p.gone==null||p.readOnly)return;$t();const d=Cn(p.fm,p.body);d!==p.gone&&(p.gone=d,Do(d))},Do=async d=>{try{await hr(d)}catch{Eo(v,e,d,p.lastSaved,p.slot),hm(e,d)}},$r=(d,y=!1)=>{if(p.held=Math.max(0,(p.held??0)-1),p.readOnly||p.retired)return Promise.resolve();if(!d)return!p.held&&p.pending&&hn(),Promise.resolve();p.retired=!0,$t();const w=Cn(p.fm,p.body),M=()=>{p.stashed!=null&&or(v,e,p.stashed,p.slot),p.stashed=null};if(w===p.lastSaved)return M(),Promise.resolve();Eo(v,d,w,p.lastSaved,p.slot);const D=y?d:e,z=()=>(k.getState().vaultRoot??null)===(v??null),Q=async()=>{try{if(!z())return;p.unpreserved!=null&&p.unpreserved!==w&&Ci(d,await Zr(D,oo(p.unpreserved,p.eol))),p.unpreserved=null;const pe=oo(w,p.eol),me=oo(p.lastSaved,p.eol);for(let He=0;He<3;He++){const Ge=await rn.readTextFile(d),qe=Ge==null?null:ym(me,pe,Ge);if(qe==null)break;if(!z())return;const it=await rn.writeTextFile(d,qe,{base:Br(Ge)});if(!it||it.ok!==!1){or(v,d,w,p.slot),M();return}if(it.current==null)break}if(!z())return;Si(d,await Zr(D,pe),!0),or(v,d,w,p.slot),M(),k.getState().refreshPages()}catch(pe){Ds(d,pe)}},S=p.chain.then(Q,Q);return p.chain=S.catch(()=>{}),S},Io=d=>{if(p.retired||(p.stashed=Cn(p.fm,p.body),Eo(v,e,p.stashed,p.lastSaved,p.slot)),p.failed||(p.failed=!0,lo(!0),Ds(e,d)),p.retryTimer||p.dead||p.retired)return;const y=Ei[Math.min(p.retryN,Ei.length-1)];p.retryN++,p.retryTimer=setTimeout(()=>{p.retryTimer=null,!(p.dead||p.retired||!p.pending)&&(p.reconcileBusy||hn())},y)},Xn=d=>{p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),p.retryN=0,p.failed&&(p.failed=!1,lo(!1)),p.stashed!=null&&(d==null||p.stashed===d||Cn(p.fm,p.body)===d)&&(or(v,e,p.stashed,p.slot),p.stashed=null)},bo=d=>{p.peerPatch=null,Xn(d),Rd(e,p)},hn=(d=!1)=>{if(p.readOnly)return Promise.resolve();const y=async()=>{let D=0;for(;!p.retired;){if(p.held){if(d&&Cn(p.fm,p.body)!==p.lastSaved)throw new Error("The note is being moved");return}const z=Cn(p.fm,p.body);if(z===p.lastSaved){p.pending=!1,Xn();return}let Q;try{p.unpreserved!=null&&p.unpreserved!==z&&await qn(p.unpreserved),p.unpreserved=null,Q=await rn.writeTextFile(e,oo(z,p.eol),{base:Br(oo(p.lastSaved,p.eol))})}catch(S){if(p.pending=!0,Io(S),d)throw S;return}if(Q&&Q.ok===!1&&Q.current==null){p.retired||(p.retired=!0,p.pending=!1,$t(),p.gone=Cn(p.fm,p.body),await Do(p.gone));return}if(Q&&Q.ok===!1&&Q.current!=null){const S=qr(Q.current);p.eol=S.eol;const pe=S.text;if(pe===z){p.lastSaved=z;continue}if(++D>3){const me=new Error("The note kept changing on disk while saving");if(p.pending=!0,Io(me),d)throw me;return}if(wn()){p.pending=!1,Lo();return}p.unpreserved=pe,p.lastSaved=pe;continue}if(p.lastSaved=z,k.getState().bumpLinkGraph(),Cn(p.fm,p.body)===z&&(p.pending=!1),bo(z),!d)return}},w=async()=>{p.writing++;try{await y()}finally{p.writing--}},M=p.chain.then(w,w);return p.chain=M.catch(()=>{}),M},eo=()=>{const d=Yt();if(!d)return;const y=mo(p.fm),w=Nx(d.state.doc);let M=y;w!=null?(M=w,p.sawRows=!0):p.sawRows&&y!=null&&$a(y)!=null&&(M=null);const D=xb(d.state.doc,pn(p.fm),Gt.current?Et.current?"canvas":"doc":null,p.ownedCards),z=pn(p.fm);p.fm=ds(p.fm,M,D),pn(p.fm)!==z&&rt(Q=>Q+1)},$t=()=>{const d=C.current?.serializeNow();d!=null&&(p.body=d,eo())},Ut=()=>{p.dead||p.retired||h||!p.writing&&Cn(p.fm,p.body)===p.lastSaved||(p.pending=!0,p.timer&&clearTimeout(p.timer),p.timer=setTimeout(()=>{p.timer=null,!p.reconcileBusy&&hn()},Hv))},[vo,wo]=x.useState(null),T=()=>{wo(d=>d==null?d:Cn(p.fm,p.body))},F=(d,y=!0)=>{h||(p.fm=za(p.fm,d),rt(w=>w+1),T(),y?(p.pending=!0,hn().then(()=>{const w=mn.getState();w.refreshPages(),w.refreshIcons()})):Ut())};x.useEffect(()=>{om(document)},[]);const[he,ve]=x.useState(null);x.useEffect(()=>{const d=y=>{const w=document.elementFromPoint(y.clientX,y.clientY)??y.target,M=w?.tagName==="IMG"?w:null;if(!M||!M.closest(".unified-body")||M.closest(".app-ref"))return;const D=M.currentSrc||M.src;D&&(y.preventDefault(),y.stopPropagation(),ve(D))};return document.addEventListener("dblclick",d,!0),()=>document.removeEventListener("dblclick",d,!0)},[]),ci(!!he,()=>ve(null)),ci(!!Mn&&!h,()=>Tn(null)),x.useEffect(()=>{if(!he)return;const d=y=>{y.key==="Escape"&&ve(null)};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[he]),x.useEffect(()=>{const d=async()=>{p.reconcileBusy++;try{await cm(),await p.chain;const w=await rn.readTextFile(e);if(w==null||p.dead||p.retired)return;const M=qr(w);p.eol=M.eol;const D=M.text;if(D===p.lastSaved&&!p.pending)return;if(p.pending&&$t(),p.pending&&!wn()){D!==p.lastSaved&&D!==Cn(p.fm,p.body)&&(p.unpreserved=D),p.lastSaved=D;return}const{fmText:z,body:Q}=Sr(D),S=mo(z)!==mo(p.fm)||pn(z)!==pn(p.fm);if(p.fm=z,p.peerPatch=null,rt(pe=>pe+1),Q!==p.body){p.ownedCards.clear();const pe=!p.readOnly&&ui(ne,w);(C.current??(Se.current?ge.current:null))?.applyBody(Q,pe)?p.body=Q:(p.body=Q,ee(me=>me+1))}else S&&(p.ownedCards.clear(),ee(pe=>pe+1));p.lastSaved=D,p.pending=!1,Xn(),T()}finally{p.reconcileBusy--,p.reconcileBusy===0&&p.pending&&hn()}};Zo.current=()=>{d()};const y=rn.onExternalChange?.(w=>{w===e&&d()});return d(),()=>{Zo.current=null,y?.()}},[e]),x.useEffect(()=>{const d=()=>{if($t(),Re(),p.timer&&clearTimeout(p.timer),p.timer=null,p.readOnly)return;if(p.retired){p.gone!=null&&yo(),p.stashed!=null&&or(v,e,p.stashed,p.slot),p.stashed=null;return}const w=Cn(p.fm,p.body);if(!p.writing&&w===p.lastSaved){Xn();return}if(!p.writing&&wn()){p.pending=!1;return}p.stashed=w,Eo(v,e,w,p.lastSaved,p.slot),hn()},y=w=>{d(),p.failed&&p.pending&&!im()&&(w.preventDefault(),w.returnValue="")};return window.addEventListener("beforeunload",y),()=>{p.dead=!0,window.removeEventListener("beforeunload",y),d();const w=Xo.current,M=Oe.getView();w&&M&&(w.doc=M.state.doc.toJSON(),w.anchor=M.state.selection.anchor,w.head=M.state.selection.head)}},[e]),x.useEffect(()=>{const d=()=>{!p.failed||!p.pending||p.dead||p.retired||typeof document<"u"&&document.visibilityState==="hidden"||(p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),!p.reconcileBusy&&hn())};return window.addEventListener("online",d),window.addEventListener("focus",d),document.addEventListener("visibilitychange",d),()=>{window.removeEventListener("online",d),window.removeEventListener("focus",d),document.removeEventListener("visibilitychange",d),p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null)}},[e]),x.useEffect(()=>{const d=S=>{if(p.readOnly||p.retired||p.dead)return!1;$t(),S&&Re();const pe=Cn(p.fm,p.body);return!p.writing&&(pe===p.lastSaved||wn())?!1:(p.pending=!0,p.stashed=pe,Eo(v,e,pe,p.lastSaved,p.slot),!0)},y=S=>{d(S)&&(p.timer&&(clearTimeout(p.timer),p.timer=null),!p.reconcileBusy&&hn())},w=()=>{document.visibilityState==="hidden"&&y(!0)},M=()=>y(!0);let D=0,z=null;const Q=()=>{const S=D+1e3-Date.now();if(S>0){d(!1),z||(z=setTimeout(()=>{z=null,D=Date.now(),y(!1)},S));return}D=Date.now(),y(!1)};return document.addEventListener("visibilitychange",w),window.addEventListener("pagehide",M),document.addEventListener("freeze",M),document.addEventListener("pause",M),window.addEventListener("blur",Q),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("pagehide",M),document.removeEventListener("freeze",M),document.removeEventListener("pause",M),window.removeEventListener("blur",Q),z&&clearTimeout(z)}},[e]);const $e=d=>p.readOnly||p.retired||p.dead||!C.current?!1:(C.current.insertFiles(d),!0);x.useEffect(()=>{if(!i)return;const d=y=>$e(y);return i.current=d,()=>{i.current===d&&(i.current=null)}},[i]),x.useEffect(()=>{if(!a)return;const d=y=>p.readOnly||p.retired||p.dead?!1:C.current?.insertMarkdown(y,"cursor")??!1;return a.current=d,()=>{a.current===d&&(a.current=null)}},[a]),x.useLayoutEffect(()=>Ad({path:e,owner:p,peerWrote:()=>Lo(),scope:j,lastActive:()=>xe.current,dirty:()=>p.readOnly||p.retired||p.dead?!1:($t(),Cn(p.fm,p.body)!==p.lastSaved&&!wn()),flush:(d=!1)=>p.readOnly?Promise.resolve():($t(),Re(),p.timer&&(clearTimeout(p.timer),p.timer=null),hn(d)),insertFiles:d=>$e(d),hold:()=>(p.held=(p.held??0)+1,p.chain),release:(d,y)=>$r(d,y),patchFm:(d,y=!1)=>p.readOnly||p.retired||p.dead?null:y?(p.fm=za(p.fm,d),p.peerPatch={...p.peerPatch??{},...d},rt(w=>w+1),T(),Promise.resolve()):(F(d),p.chain),fmNow:()=>ks(p.fm),insertMarkdown:(d,y)=>p.retired||p.readOnly?!1:C.current?.insertMarkdown(d,y)??!1,insertReply:h?void 0:(d,y)=>{if(p.retired||p.dead||p.readOnly||!C.current?.insertMarkdown(d,"cursor",{quiet:!0,after:y,caretless:!se.current}))return null;const w=Yt()?.state.doc,M=Wn,D={n:M.log.length,top:M.log[M.log.length-1],future:M.future.length};return{undo:()=>{const z=Yt();return!z||!w||z.state.doc!==w||p.retired||p.dead||D.top!=="pm"||M.log.length!==D.n||M.log[M.log.length-1]!=="pm"||M.future.length!==D.future?!1:Et.current&&Jt.current?Jt.current("undo"):Ya(z.state,z.dispatch)}}},bodyNow:()=>p.body,statsNow:()=>g(),headings:()=>{const d=Yt();return d?ta(d.state.doc):[]},revealHeading:(d,y,w)=>{const M=Yt();if(!M)return;const D=ta(M.state.doc),z=D[d]?.text===y?D[d]:D.find(S=>S.text===y);if(!z)return;M.focus(),M.dispatch(M.state.tr.setSelection(je.near(M.state.tr.doc.resolve(z.pos+1))));const Q=M.nodeDOM(z.pos);Q instanceof HTMLElement&&(is(Q),w&&Xs(Q.getBoundingClientRect()))},revealBlock:(d,y)=>{const w=Yt();if(!w)return!1;const M=[];w.state.doc.descendants((S,pe,me)=>S.isTextblock?(M.push({pos:pe,text:S.textContent,parent:me}),!1):!0);let D=M.findIndex(S=>Ol(S.text)===d);if(D<0)return!1;Dd(M[D].text)&&D>0&&M[D-1].parent===M[D].parent&&(D-=1);const z=M[D].pos;w.focus(),w.dispatch(w.state.tr.setSelection(je.near(w.state.tr.doc.resolve(z+1))));const Q=w.nodeDOM(z);return Q instanceof HTMLElement&&(is(Q),y&&Xs(Q.getBoundingClientRect())),!0},focusBody:()=>{if(p.readOnly||p.retired||p.dead)return!0;const d=Oe.getView();return d?(d.hasFocus()||d.focus(),!0):!1},revealText:(d,y)=>{const w=Yt();if(!w)return!1;const M=Ef(w.state.doc,d,!!y?.tag);if(!M)return!1;ql(w,M.from),w.focus(),w.dispatch(w.state.tr.setSelection(je.create(w.state.doc,M.from,M.to)));let D=w.nodeDOM(M.block);for(;D instanceof HTMLElement&&D!==w.dom;){const z=D.getBoundingClientRect();if(z.width||z.height)break;D=D.parentElement}return!(D instanceof HTMLElement)||D===w.dom||(is(D),y?.flash&&Xs(D.getBoundingClientRect())),!0},retire:d=>{if(Mr(),!p.retired&&!p.readOnly&&!p.dead){$t();const y=Cn(p.fm,p.body);y!==p.lastSaved&&!wn()&&(d?Eo(v,d,y,p.lastSaved,p.slot):(k.getState().vaultRoot??null)!==(v??null)?Eo(v,e,y,p.lastSaved,p.slot):Do(y))}else p.retired&&p.gone!=null&&yo();p.retired=!0,p.timer&&(clearTimeout(p.timer),p.timer=null),p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null)}}),[e]);const[Ne,te]=x.useState(()=>{if(h)return null;const d=w=>w==null?Jc(e,null):lm(w)||Jc(e,w),y=rm(v,e,p.slot,d);return y?y.text===p.lastSaved||y.text===(n??t)?(or(v,e,void 0,y.slot),null):y:null}),nt=()=>{Ne&&or(v,e,void 0,Ne.slot),te(null)},st=()=>{const d=Ne;if(te(null),!d||h||p.retired)return;(d.slot??null)!==p.slot&&(or(v,e,d.text,d.slot),Eo(v,e,d.text,p.lastSaved,p.slot)),$t();const y=p.lastSaved,w=Cn(p.fm,p.body),M=w!==y?w:Br(y)!==d.base?y:null;M!=null&&M!==d.text&&(p.unpreserved=M);const{fmText:D,body:z}=Sr(d.text);p.fm=D,rt(Q=>Q+1),z!==p.body&&(p.ownedCards.clear(),p.body=z,(C.current??(Se.current?ge.current:null))?.applyBody(z)||ee(Q=>Q+1)),T(),p.pending=!0,p.stashed=d.text,hn()};x.useEffect(()=>{o&&(o.scheduleState=()=>({pending:p.pending,lastSaved:p.lastSaved}),o.flush=()=>($t(),p.timer&&clearTimeout(p.timer),p.timer=null,hn()),o.fmState=()=>({fm:p.fm,body:p.body}),o.setFm=d=>F(d,!1),o.view=()=>Oe.getView(),o.serializeNow=()=>C.current?.serializeNow()??null)},[o]);const[At,mt]=x.useState(0);x.useEffect(()=>{sm(e)&&mt(d=>d+1)},[e]);const bt=x.useRef(()=>!1);bt.current=()=>!h&&!m&&!Et.current&&Uo.current==null&&At===0;const Rt=x.useRef(()=>!1);Rt.current=()=>{const d=Va;if(!d||d.scope!==j||Date.now()-d.at>5e3)return!1;Va=null;const y=document.activeElement;return(!y||y===document.body)&&(j==null||j===xm())};const Nt=x.useRef(null);x.useLayoutEffect(()=>()=>{const d=document.activeElement;d&&d!==document.body&&(Y.current?.contains(d)||Nt.current?.contains(d))&&(Va={scope:j,at:Date.now()})},[]);const an=x.useRef(()=>!1);an.current=()=>Nn||h?!1:(mt(d=>d+1),!0);const Pt=d=>{const y=Oe.getView();if(!y)return;let w=y.state.tr;if(p.body===d.body)try{const z=y.state.schema.nodeFromJSON(d.doc);z.eq(w.doc)||(w=w.replaceWith(0,w.doc.content.size,z.content))}catch{}const M=w.doc.content.size,D=z=>w.doc.resolve(Math.max(0,Math.min(z,M)));try{w=w.setSelection(je.between(D(d.anchor),D(d.head)))}catch{}y.dispatch(w.setMeta("addToHistory",!1).scrollIntoView())},Hn=async(d,y=null,w=!1)=>{if(h||w&&p.retired)return!1;const M=v;try{if($t(),await hn(),await um(),w&&(await p.chain,p.retired||mn.getState().vaultRoot!==M))return!1;const D=await rn.renamePageFile(e,d);if(D!==e){dm(v,e,D),Ym(v,e,D),p.retired=!0,$t();const z=Cn(p.fm,p.body),Q=p.body;if(z!==p.lastSaved)try{const me=await rn.writeTextFile(D,oo(z,p.eol),{base:Br(oo(p.lastSaved,p.eol))});if(me&&me.ok===!1&&me.current!==oo(z,p.eol))try{Si(D,await Zr(D,oo(z,p.eol))),mn.getState().refreshPages()}catch(He){Eo(v,D,z,p.lastSaved,p.slot),Ds(D,He)}}catch(me){Eo(v,D,z,p.lastSaved,p.slot),Ds(D,me)}const S=Uo.current,pe=Oe.getView();if(!w&&y&&S!=null&&typeof S!="object")Ws={path:D,scope:j,req:S,at:Date.now()};else if(!w&&pe?.hasFocus()){const me={place:"restore",body:Q,doc:pe.state.doc.toJSON(),anchor:pe.state.selection.anchor,head:pe.state.selection.head};Xo.current=me,Ws={path:D,scope:j,req:me,at:Date.now()}}Nd(e,"file",D),fm(e,D,"file"),await pm(e,D),mn.getState().refreshPages(),w||r?.(D)}return!0}catch{return w&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.toast.renameDetachedFailed",{name:d})}})),!1}},ko=x.useRef("");x.useEffect(()=>{const d=JSON.stringify(_n(pn(p.fm))?.tree??null);if(d===ko.current)return;ko.current=d;const y=Oe.getView();y&&y.updateState(y.state)},[Me,Oe]);const f=hg(p.fm),N=typeof f.icon=="string"&&f.icon.trim()?f.icon.trim():null,$=typeof f.cover=="string"&&f.cover.trim()?f.cover.trim():null,H=f.cover_y,K=typeof H=="number"?H:typeof H=="string"?parseFloat(H):NaN,B=Number.isFinite(K)?Math.max(0,Math.min(100,K)):50,U=x.useMemo(()=>_==="source"?Cn(p.fm,p.body):"",[_,Me]),oe=x.useRef(null),be=()=>`${mo(p.fm)??""}\0${pn(p.fm)??""}`;x.useEffect(()=>{if(!h)return mp(q,d=>{const y=va(fe.current),w=wa(y);if(d==="source"){$t();const Q=Oe.getView(),S=Cn(p.fm,p.body);let pe=p.fm.length,me=0,He=!1;if(Q){const{head:Ge,$head:qe}=Q.state.selection;He=Q.hasFocus();try{me=Q.coordsAtPos(Ge).top-w}catch{}const it=qe.parent.isTextblock?qe.parent.textBetween(Math.max(0,qe.parentOffset-16),qe.parentOffset,void 0,""):"",on=ge.current?.serializePrefix(Ge);pe=Mp(S,p.fm.length+(on?.trimEnd().length??0),it)}oe.current={to:d,offset:pe,y:me,focused:He,bodyAtEnter:p.body,struct:be()};return}const M=re.current;if(!M)return;const D=M.selectionStart??0;let z=0;try{z=ii(M,D)-w}catch{}oe.current={...oe.current??{},to:d,offset:D,bodyOff:D-Sr(M.value).fmText.length,y:z,focused:document.activeElement===M}})},[q,h]);const ie=x.useRef(_);x.useLayoutEffect(()=>{const d=ie.current;if(ie.current=_,d===_)return;const y=oe.current,w=va(fe.current);if(_==="source"){Ut();const me=re.current;if(!me||y?.to!=="source")return;const He=w.scrollTop;me.style.height="auto",me.style.height=`${me.scrollHeight}px`,w.scrollTop=He;const Ge=Math.min(y.offset,me.value.length);me.setSelectionRange(Ge,Ge),y.focused&&me.focus({preventScroll:!0}),w.scrollTop+=ii(me,Ge)-wa(w)-y.y;return}oe.current=null,wo(null);const M=ge.current,D=Oe.getView();if(!M||!D||!y||y.struct!==be()){p.ownedCards.clear(),ee(me=>me+1);return}if(p.body!==y.bodyAtEnter&&M.applyBody(p.body,!1,!0),y.to!=="wysiwyg"||y.bodyOff==null)return;const z=Oe.getView();if(!z)return;const Q=z.state.doc.content.size,S=y.bodyOff<=0?0:M.posAfterPrefix(p.body.slice(0,y.bodyOff))??0,pe=je.near(z.state.doc.resolve(Math.max(0,Math.min(S,Q))),-1);z.dispatch(z.state.tr.setSelection(pe).setMeta("addToHistory",!1)),y.focused&&z.focus();try{w.scrollTop+=z.coordsAtPos(pe.head).top-wa(w)-y.y}catch{}},[_]);const re=x.useRef(null);return x.useEffect(()=>{const d=re.current;if(_==="source"&&d){const y=va(d),w=y.scrollTop;d.style.height="auto",d.style.height=`${d.scrollHeight}px`,y.scrollTop=w}},[_,vo,U]),x.useEffect(()=>{if(h)return;if(_==="source"){const y=re.current;return y?Ii(Jh(y)):void 0}const d=Y.current;return d?Ii(Bv(d,()=>Oe.getView())):void 0},[h,_,Oe]),u.jsxs(u.Fragment,{children:[u.jsx("span",{ref:fe,className:"amx-seg-anchor","aria-hidden":!0}),_==="source"?null:u.jsx(Cg,{anchor:ye,on:Fe,toggle:()=>_t.current(),leafId:j}),Nn||m?null:u.jsx(_g,{page:e,cover:$,coverY:B,readOnly:h,onSetCover:d=>F({cover:d??void 0,...d?{}:{cover_y:void 0}}),onSetCoverY:d=>F({cover_y:d})}),Nn?null:u.jsxs("div",{ref:Nt,className:"amx-doc unified-page","data-unified-path":e,onFocusCapture:ce,onPointerDownCapture:ce,children:[u.jsx(Yv,{compact:m,path:e,icon:N,cover:$,readOnly:h,onSetIcon:d=>F({icon:d??void 0}),onSetCover:d=>F({cover:d}),onRename:Hn,onDetachedRename:d=>{const y=d.trim();y&&y!==(e.split("/").pop()??e).replace(/\.md$/i,"")&&Hn(y,null,!0)},onEnterBody:d=>No(d==="enter"?"body-enter":"start"),focusSignal:At}),!m&&u.jsx(uu.Provider,{value:ae,children:u.jsx(Ag,{fmExtra:ks(p.fm),readOnly:h,notePath:e,onCommit:d=>{p.fm=lg(p.fm,d),rt(y=>y+1),T(),p.pending=!0,hn()}})}),h&&l&&u.jsxs("div",{className:"mk-notice unified-savebar","data-lock":"on",role:"status",children:[u.jsx(hp,{size:15}),u.jsx("div",{className:"mk-notice-body",children:u.jsx("span",{children:Z("unipage.lock.bar")})}),u.jsx("button",{type:"button",className:"btn sm",onClick:l,children:Z("unipage.lock.unlock")})]}),!h&&Qo&&u.jsxs("div",{className:"mk-notice is-error unified-savebar","data-save":"failed",role:"alert",children:[u.jsx(gp,{size:15}),u.jsx("div",{className:"mk-notice-body",children:u.jsx("span",{children:Z("unisave.failed.bar")})}),u.jsx("button",{type:"button",className:"btn sm",onClick:()=>{p.retryTimer&&(clearTimeout(p.retryTimer),p.retryTimer=null),hn()},children:Z("unisave.failed.retry")})]}),!h&&Ne&&u.jsxs("div",{className:"mk-notice unified-savebar","data-save":"draft",role:"status",children:[u.jsx(xp,{size:15}),u.jsxs("div",{className:"mk-notice-body",children:[u.jsx("span",{children:Z("unisave.draft.bar",{time:yp(Ne.at)})}),u.jsx("small",{children:Z("unisave.draft.hint")})]}),u.jsx("button",{type:"button",className:"btn sm primary",onClick:st,children:Z("unisave.draft.restore")}),u.jsx("button",{type:"button",className:"btn sm",onClick:nt,children:Z("unisave.draft.discard")})]})]}),_==="source"?u.jsx("textarea",{ref:re,className:"amx-source",value:vo??U,spellCheck:ze,onFocus:ce,onChange:d=>{const y=d.target.value;wo(y);const{fmText:w,body:M}=Sr(y);p.fm=pg(w),p.body=M,Ut()}}):null,u.jsxs("div",{ref:Y,className:`page-view unified-body${Fe?" amx-canvas":""}${Nn?" amx-canvas-full":""}`,"data-guide-anchor":Fe||h?void 0:"note-body",style:_==="source"?{display:"none"}:void 0,"aria-hidden":_==="source"||void 0,"data-bare":!0,onFocusCapture:()=>{ce(),se.current=!0,ba(dn)},onPointerDownCapture:ce,children:[u.jsx(tv,{path:e,vaultRoot:v,active:Fe&&_!=="source",readOnly:h,revealSelection:ct,getView:()=>Oe.getView(),main:dt,mainStored:un?.main!=null,elements:un?.elements,tree:un?.tree,onElements:Jn,onTree:pr,onMain:sn,timeline:Wn,histStepRef:Jt,exportRef:An,saveFile:d=>Qu(e,d),parseMd:d=>C.current?.parseMd(d)??null,serializeMd:d=>C.current?.serializeMd(d)??null,storedMd:d=>C.current?.serializeStored(d)??null,onBlocksDeleted:A,notePages:()=>k.getState().pages,onCommit:d=>{d&&p.ownedCards.add(d),$t(),Ut()},children:u.jsx(lf,{children:u.jsx(qv,{path:e,pageDir:R,body:p.body,onChange:d=>{Se.current||(p.body=d,eo(),Ut())},onFinalFlush:d=>{p.body=d,eo(),Ut(),rt(y=>y+1)},skipFinalFlush:()=>p.reconcileBusy>0||Se.current,hidden:()=>Se.current,apiRef:ge,probe:o,extraPlugins:Ae,focusPlace:Zn!=null&&typeof Zn=="object"?"start":Zn,onFocused:()=>{Zn!=null&&typeof Zn=="object"&&Pt(Zn),No(null)},onCard:Qn,readOnly:h,onAskTangu:Xe?d=>We(d,d.state.selection.from,d.state.selection.to):void 0,aiMenu:Ze?{items:Yn,translate:!0,more:It,onPick:(d,y)=>Un(y,d)}:void 0,onAiPrompt:Ze?d=>Un(d,"prompt"):void 0})},`${e}:${Je}${h?":ro":""}`)}),!Fe&&!h&&u.jsx("div",{className:"page-tail",onClick:()=>C.current?.focusTail()}),W&&u.jsx(hv,{}),!h&&G.count>0&&u.jsx(gv,{count:G.count,index:G.index,onReview:mr,onRevert:jo,onKeep:()=>{const d=Oe.getView();d&&pv(d)}})]}),u.jsx(Iv,{getView:()=>Oe.getView(),onOpenNote:(d,y)=>{k.getState().openWikiLink(uf(d,e,k.getState().pages),e,y)}}),he&&u.jsx(ir,{children:u.jsx("div",{className:"amx-lightbox",onClick:()=>ve(null),role:"presentation",children:u.jsx("img",{src:he,alt:""})})}),xt&&Ze&&u.jsx(ir,{children:u.jsx(Km,{x:xt.x,y:xt.y,anchorTop:xt.top,title:xt.title,hasSelection:xt.hasSelection,askFirst:xt.askFirst,run:$o(xt),onApply:Bn,onClose:Tr,editorEl:Y.current,language:xt.language?{value:xt.language,onChange:d=>yt({...xt,key:Date.now(),language:d})}:void 0},xt.key)}),co&&!h&&u.jsx(gu,{pages:k.getState().pages,exclude:e,onClose:()=>{Go(null),Oe.getView()?.focus()},onPick:d=>{const y=co;Go(null);const w=Oe.getView();if(w){if(w.state.doc!==y.doc){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.menu.stale")}}));return}nx({view:w,from:y.from,to:y.to,source:e,target:d,pages:[...k.getState().pages].sort(),serialize:M=>C.current?.serializeMd(M)??null}).then(M=>{M&&($t(),Ut())}),w.focus()}}}),Mn&&!h&&u.jsxs(ir,{children:[u.jsxs(lr,{className:"ctx-menu unified-block-menu",role:"menu","aria-label":Z("unipage.menu.aria"),x:Mn.x,y:Mn.y,onClick:d=>d.stopPropagation(),onMouseOver:d=>{Dn&&!d.target.closest("[data-sub]")&&Dt()},children:[Xe&&u.jsxs(u.Fragment,{children:[u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"ask",onClick:()=>{Tn(null);const d=Oe.getView();if(!d||!Pe(d))return;const y=Oe.topRangeOf(d),w=d.state.selection;y?We(d,y.from,y.to):w instanceof Ce&&We(d,w.from,w.to)},children:[u.jsx(Jm,{size:13})," ",Z("unipage.menu.askTangu")]}),u.jsx("div",{className:"ubm-sep",role:"separator"})]}),(()=>{const d=Jo();if(!d.length)return null;const y=Ro(),w=d.find(D=>D.k===y)??(y==="card"?{icon:Ga,label:Z("unipage.menu.card")}:void 0),M=w?.icon??Li;return u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-sub":"turnInto","aria-haspopup":"menu","aria-expanded":!!Dn,className:Dn?"is-open":void 0,onMouseEnter:D=>ut(D.currentTarget,!1),onClick:D=>ut(D.currentTarget,!0),children:[u.jsx(M,{size:13})," ",Z("unipage.menu.turnInto"),u.jsxs("span",{className:"ubm-sub-tail",children:[w?.label,u.jsx(Xl,{size:13})]})]})})(),dc(Oe.getView())&&u.jsx(_v,{view:Oe.getView(),cell:Mn.cell??null,onDone:()=>Tn(null)}),u.jsx("div",{className:"ubm-sep",role:"separator"}),Oe.getView()&&Oe.topRangeOf(Oe.getView())?u.jsxs("button",{role:"menuitem",tabIndex:-1,"aria-disabled":"true",title:Z("unipage.menu.toNewColumnMulti"),"data-act":"toNewColumn",onClick:()=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Te("unipage.menu.toNewColumnMulti")}}))},children:[u.jsx(li,{size:13})," ",Z("unipage.menu.toNewColumn")]}):Oe.getView()&&df(Oe.getView().state.selection)&&u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"toNewColumn",onClick:()=>_e((d,y)=>{vu(d,y.from,y.to,y.node)}),children:[u.jsx(li,{size:13})," ",Z("unipage.menu.toNewColumn")]}),Oe.getView()&&ti(Oe.getView().state.selection)!=null&&u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"unsplit",onClick:()=>{Tn(null);const d=Oe.getView();if(!d||!Pe(d))return;const y=ti(d.state.selection);y!=null&&Lx(d,y),d.focus()},children:[u.jsx(Oh,{size:13})," ",Z("unipage.menu.unsplit")]}),Oe.getView()?.state.selection instanceof Ce&&Oe.getView().state.selection.node.type.name==="amadeusCanvasCard"&&u.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>_e((d,y)=>{y.node.type.name==="amadeusCanvasCard"&&(Vu(d,String(y.node.attrs.anchor)),$t(),Ut())}),children:[u.jsx(Xm,{size:13})," ",Z("unipage.menu.backToDoc")]}),u.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>{Tn(null);const d=Oe.getView();!d||!Pe(d)||(Oe.duplicate(d)&&($t(),Ut()),d.focus())},children:[u.jsx(bp,{size:13})," ",Z("unipage.menu.duplicate")]}),(()=>{const d=Oe.getView();if(!d)return null;const y=d.state.selection,w=Ve(d),M=y instanceof Ce?Qg(y.node,e,k.getState().pages):null,D=!!w&&tx(d.state.doc.slice(w.from,w.to).content);return u.jsxs(u.Fragment,{children:[M&&u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"copyLink",onClick:()=>{Tn(null),ex(M.link),Oe.getView()?.focus()},children:[u.jsx(Wl,{size:13})," ",Z(M.kind==="heading"?"blocklinks.copyHeading":"blocklinks.copyBlock")]}),D&&u.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"moveTo",onClick:()=>{Tn(null);const z=Oe.getView();if(!z||!Pe(z))return;const Q=Ve(z);Q&&Go({doc:z.state.doc,...Q})},children:[u.jsx(ph,{size:13})," ",Z("blocklinks.moveTo")]})]})})(),u.jsxs("button",{role:"menuitem",tabIndex:-1,className:"danger",onClick:()=>Be((d,y)=>{const w=d.state.doc.slice(y.from,y.to).content;d.dispatch(d.state.tr.delete(y.from,y.to).scrollIntoView()),A(w)},(d,y)=>{const w=zo.from(y.node),M=y.$from.parent,D=M.type.name==="amadeusColumnCell"&&M.childCount===1?wu(d.state,y.$from.before(),-1,!0):null;d.dispatch(D??d.state.tr.deleteSelection().scrollIntoView()),A(w)}),children:[u.jsx(Ja,{size:13})," ",Z("unipage.menu.delete")]})]}),Dn&&(()=>{const d=Ro();return u.jsx(lr,{className:"ctx-menu unified-block-submenu",role:"menu","aria-label":Z("unipage.menu.turnInto"),x:Dn.x,y:Dn.y,anchorTop:Dn.anchorTop,onClick:y=>y.stopPropagation(),onMouseEnter:()=>clearTimeout(go.current),children:Jo().map(({k:y,icon:w,label:M,run:D})=>u.jsxs("button",{role:"menuitemradio","aria-checked":y===d,tabIndex:-1,"data-kind":y,onClick:D,children:[u.jsx(w,{size:13})," ",M,y===d&&u.jsx(Ms,{size:13,className:"ubm-check"})]},y))})})()]})]})}const kw=Object.freeze(Object.defineProperty({__proto__:null,UnifiedPage:Uv},Symbol.toStringTag,{value:"Module"}));export{Ag as A,dh as C,xw as D,vw as F,Kg as I,zh as M,_g as N,Hh as S,Uv as U,Gh as a,Yh as b,_h as c,gw as d,ww as e,Wh as f,yy as g,ph as h,nu as i,Sr as j,Eh as k,fu as l,kg as m,Uh as n,bw as o,Pg as p,kw as q,Hg as r,yw as s,Og as u};