@forsion/unit 2.13.1 → 2.13.2

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 (181) hide show
  1. package/main.mjs +19 -1
  2. package/package.json +1 -1
  3. package/release.json +5 -5
  4. package/web/assets/{ArtificialView-XwHMLUFb.js → ArtificialView-Bs_6B211.js} +1 -1
  5. package/web/assets/{AutomationBuilder-hqs0QhMt.js → AutomationBuilder-C-IFaaBp.js} +1 -1
  6. package/web/assets/CalendarConfigView-DEsNvVkD.js +1 -0
  7. package/web/assets/CalendarView-D7ZUE_dr.js +1 -0
  8. package/web/assets/{CapabilityMenu-SwVlZ06x.js → CapabilityMenu-CrsaTtDe.js} +1 -1
  9. package/web/assets/{CheckboxInput-BC-5a_C9.js → CheckboxInput-DVO2-1J7.js} +1 -1
  10. package/web/assets/{Chrome-HdfyYV3i.js → Chrome-BvpbCvo1.js} +1 -1
  11. package/web/assets/{CodeView-CFL6yQ-6.js → CodeView-CB4kG7Y6.js} +3 -3
  12. package/web/assets/DashboardGridView-hpRmBr9B.css +1 -0
  13. package/web/assets/DashboardGridView-tgaj9-SM.js +17 -0
  14. package/web/assets/{EventCard-B_ndpqH_.js → EventCard-c6s4uGBu.js} +1 -1
  15. package/web/assets/ExcalidrawCanvas-NdV86AR3.js +1 -0
  16. package/web/assets/{FloatingToc-Ce9GamvH.js → FloatingToc-ldOYWe2C.js} +1 -1
  17. package/web/assets/HomepageView-4joJWYlg.js +1 -0
  18. package/web/assets/HomepageView-Cxf3AWBu.css +1 -0
  19. package/web/assets/ImageStudioPanels-DgMYAsHj.js +3 -0
  20. package/web/assets/{ImageStudioView-UPv52acl.js → ImageStudioView-_CYHoOoG.js} +1 -1
  21. package/web/assets/InlineFiles-BIfsx3R-.js +1 -0
  22. package/web/assets/MarkdownBlock-wYEaBBOr.js +58 -0
  23. package/web/assets/ModelPill-DveHcLqq.js +2 -0
  24. package/web/assets/MuseLibraryView-Do9RnKiq.js +2 -0
  25. package/web/assets/{MuseView-CC2A7MBs.js → MuseView-3GL4Ltoj.js} +2 -2
  26. package/web/assets/{PageHistoryPanel-KhKT1DLy.js → PageHistoryPanel-BMQC-V_l.js} +2 -2
  27. package/web/assets/{PdfAnnotator-DUyrgY-t.js → PdfAnnotator-CyAw8sgq.js} +1 -1
  28. package/web/assets/PenRow-BSB-h5Pb.js +1 -0
  29. package/web/assets/{ProductView-CgsIYZqD.js → ProductView-B96OeHOP.js} +1 -1
  30. package/web/assets/{RightPanel-BHDgqTFs.js → RightPanel-BgSeCLnw.js} +3 -3
  31. package/web/assets/RunLocationPicker-CEmFio4n.css +1 -0
  32. package/web/assets/RunLocationPicker-M1UoJyjf.js +38 -0
  33. package/web/assets/{SketchCard-BGYz-bXP.js → SketchCard-DAD0jR0i.js} +212 -8
  34. package/web/assets/{StudioGuestSurface-lt6znmkl.js → StudioGuestSurface-DlUKXBXv.js} +1 -1
  35. package/web/assets/TodoListView-_yFkPUrw.js +1 -0
  36. package/web/assets/{Tooltip-ZxrDqN4p.js → Tooltip-DXuy9-1_.js} +1 -1
  37. package/web/assets/UnifiedPage-EJNWKzxN.js +68 -0
  38. package/web/assets/{appStore-DWP8UET9.js → appStore-CidPWYa0.js} +220 -132
  39. package/web/assets/appStore-DeaC1U32.css +1 -0
  40. package/web/assets/{arrow-up-right-DrCXuWS7.js → arrow-up-right-KPFbRA41.js} +1 -1
  41. package/web/assets/{astryxBridge-D-m4_kYt.js → astryxBridge-Bupzouso.js} +3 -3
  42. package/web/assets/{automationListSource-C8BNy6RY.js → automationListSource-1aOVKBLw.js} +1 -1
  43. package/web/assets/boardSurface-BHuMoQN-.js +1 -0
  44. package/web/assets/{book-open-OLNm7OaB.js → book-open-CBeNsIpo.js} +1 -1
  45. package/web/assets/{calendarNavStore-Cylfvv3s.js → calendarNavStore-Duyhbmm_.js} +1 -1
  46. package/web/assets/{canvasPrefs-8taQ42Cz.js → canvasPrefs-CxfyDTMT.js} +1 -1
  47. package/web/assets/{chatBoxSurface-CIlzs45H.js → chatBoxSurface-OBzO1Z5E.js} +1 -1
  48. package/web/assets/{circle-question-mark-XbAFplz1.js → circle-question-mark-M8QUJJYk.js} +1 -1
  49. package/web/assets/{circle-x-fcReAZaE.js → circle-x-Szwop5L_.js} +1 -1
  50. package/web/assets/{client-0MPbodA6.js → client-CPUljePZ.js} +1 -1
  51. package/web/assets/{code-xml-Cuna8Kh4.js → code-xml-n9mgGgkv.js} +1 -1
  52. package/web/assets/{codeStudioStore-BBU62GTy.js → codeStudioStore-DXMQwRzG.js} +1 -1
  53. package/web/assets/codingNavigation-CCjs1kon.js +53 -0
  54. package/web/assets/codingNavigation-yp19w6uu.css +1 -0
  55. package/web/assets/{create-BGtEfCcg.js → create-C19zqt5N.js} +2 -2
  56. package/web/assets/dashboardSurface-BwcH16Qc.js +1 -0
  57. package/web/assets/{deskCapture-BiUCmqfc.js → deskCapture-B_LKZSPt.js} +1 -1
  58. package/web/assets/{diff2html-BNp2FTbk.js → diff2html-DrCCWvpR.js} +1 -1
  59. package/web/assets/{docx-preview-CFznGVOU.js → docx-preview-Bi7wekSM.js} +1 -1
  60. package/web/assets/{emoji-6zl4yfOS.js → emoji-DczIG8SO.js} +1 -1
  61. package/web/assets/{floatingTocSurface-DreXPCa6.js → floatingTocSurface-rc1ZC7-I.js} +1 -1
  62. package/web/assets/{foldActions-05QcQziQ.js → foldActions-BGocXE-o.js} +1 -1
  63. package/web/assets/{folder-BpsfOHD4.js → folder-CoOsfQ64.js} +1 -1
  64. package/web/assets/{folder-plus-BeQHr4AZ.js → folder-plus-d5MwIMlf.js} +1 -1
  65. package/web/assets/{gestures-DQBCcK4y.js → gestures-CXFaEydn.js} +1 -1
  66. package/web/assets/{hand-Bko7ms15.js → hand-fuehbnkI.js} +1 -1
  67. package/web/assets/{hard-drive-BpuI5ebj.js → hard-drive-Bh1DmZg0.js} +1 -1
  68. package/web/assets/i18n-DjziAw8r.css +1 -0
  69. package/web/assets/{i18n.generated-BuLjnmY8.js → i18n.generated-BiQFRL2U.js} +1 -1
  70. package/web/assets/{imageStudio-BLVNKmEG.js → imageStudio-Dgl1wZNB.js} +2 -2
  71. package/web/assets/{index-C1doZp5H.js → index-2tD0kijW.js} +1 -1
  72. package/web/assets/{index-D6AycQIz.js → index-38xsQSS9.js} +1 -1
  73. package/web/assets/{index-CLHoq1w-.js → index-7kdR1oL8.js} +1 -1
  74. package/web/assets/index-B5UW6SaE.js +297 -0
  75. package/web/assets/{index-DuBQ0j2g.js → index-B8Co6KG3.js} +1 -1
  76. package/web/assets/{index-D7gVhvNY.js → index-BCG8Wnc4.js} +1 -1
  77. package/web/assets/{index-CwcOeZdT.js → index-BPqoEOV_.js} +1 -1
  78. package/web/assets/index-BqGpbntz.js +1 -0
  79. package/web/assets/{index-Ck_O3Jdd.js → index-CPLtf9Vc.js} +1 -1
  80. package/web/assets/{index-CD3yIkOA.js → index-Ce1sNSS8.js} +1 -1
  81. package/web/assets/{index-o8cj0pRH.js → index-Ch0FIsJX.js} +1 -1
  82. package/web/assets/{index-C0Gy2NQ6.js → index-CnDAYLti.js} +1 -1
  83. package/web/assets/{index-CJeUgjPU.js → index-D4CSH-v1.js} +1 -1
  84. package/web/assets/{index-D9UZQy42.js → index-Dc8iMctf.js} +1 -1
  85. package/web/assets/{index-sCXThwqZ.js → index-DcRyQ3eU.js} +1 -1
  86. package/web/assets/{index-CUZI62qU.js → index-Df9jregv.js} +1 -1
  87. package/web/assets/{index-rggq2czF.js → index-Dff-DL1v.js} +1 -1
  88. package/web/assets/{index-rHjhbwvm.js → index-DvOrTnw2.js} +1 -1
  89. package/web/assets/{index-BF10xp_K.js → index-Dx9aIoyo.js} +1 -1
  90. package/web/assets/{index-BgnNNv3e.js → index-Dy07SBfH.js} +1 -1
  91. package/web/assets/{index-BHm6K743.js → index-QjVOA7QM.js} +1 -1
  92. package/web/assets/{index-Cff42k7q.js → index-YRWOePBS.js} +1 -1
  93. package/web/assets/{index-C4L6vjd_.js → index-e-MxdHFO.js} +1 -1
  94. package/web/assets/{index-Uo5tswys.js → index-fViJsYjM.js} +1 -1
  95. package/web/assets/{index-OD1gSX3h.js → index-lfow5R3O.js} +1 -1
  96. package/web/assets/{invitePage-b0HGvMj6.js → invitePage-Dgl3-c_m.js} +1 -1
  97. package/web/assets/{ipc-CxAyeo8q.js → ipc-CNlIRMtU.js} +1 -1
  98. package/web/assets/{jszip.min-B94KpE21.js → jszip.min-tyV0GaJg.js} +1 -1
  99. package/web/assets/{layout-grid-BBVuEdWG.js → layout-grid-DFmwM9NU.js} +1 -1
  100. package/web/assets/linkFollow-iP2zfbA3.js +8 -0
  101. package/web/assets/{list-tree-4-0QDbLu.js → list-tree-i07HsP3D.js} +1 -1
  102. package/web/assets/{listFold-DLuxXiIj.js → listFold-Aea6I0Sa.js} +1 -1
  103. package/web/assets/{lock-CnbZm4vo.js → lock-TSDKuCod.js} +1 -1
  104. package/web/assets/{log-out-BEynWaHa.js → log-out-DK84lW5n.js} +1 -1
  105. package/web/assets/main-D7CEGndC.js +20 -0
  106. package/web/assets/markdownEditorSurface-DISu_twy.js +3 -0
  107. package/web/assets/{message-square-plus-CpiKDvle.js → message-square-plus-3wFslIMY.js} +1 -1
  108. package/web/assets/{messages-_jta1lSI.js → messages-DEAGRsC3.js} +1 -1
  109. package/web/assets/minus-BBdfT_sc.js +1 -0
  110. package/web/assets/mobileEntry-5UaAITwY.js +13 -0
  111. package/web/assets/{nativeDownload-BYT082bY.js → nativeDownload-B3JGkABw.js} +1 -1
  112. package/web/assets/pageChrome-BDHHmRnt.css +1 -0
  113. package/web/assets/{pageChrome-D3Niv1JM.js → pageChrome-DFi9zs6F.js} +1 -1
  114. package/web/assets/{pageTree-CgfvpzIj.js → pageTree-DZ7Eiro-.js} +4 -4
  115. package/web/assets/{pen-tool-BXEFnU2i.js → pen-tool-ChGmX6g_.js} +1 -1
  116. package/web/assets/{pencil-cqvCkekG.js → pencil-CJsJD7M_.js} +1 -1
  117. package/web/assets/phoneList-DrxIwJxQ.js +9 -0
  118. package/web/assets/phoneList-DvpzD3zT.css +1 -0
  119. package/web/assets/pluginChat-0QI9a8Q1.js +2 -0
  120. package/web/assets/{redo-2-BO7wCDwy.js → redo-2-CI57sDFr.js} +1 -1
  121. package/web/assets/{rotate-ccw-BvipPIjC.js → rotate-ccw-xgT_0UN9.js} +1 -1
  122. package/web/assets/{sharePage-XbN50US7.js → sharePage-C2Yqx0NQ.js} +2 -2
  123. package/web/assets/{shareViewer-BaYogetW.js → shareViewer-DKPWhTJv.js} +2 -2
  124. package/web/assets/{star-BQWMXnn7.js → star-C9KTji9N.js} +1 -1
  125. package/web/assets/tableSurface-cYs6dX6B.js +1 -0
  126. package/web/assets/{terminal-l9k6RDrH.js → terminal-DPZazOQ2.js} +1 -1
  127. package/web/assets/{terminalView-Cpnt5_0P.js → terminalView-CsJmxE_m.js} +1 -1
  128. package/web/assets/{theme-C6D3tMGV.css → theme-Dgqst5S9.css} +1 -1
  129. package/web/assets/{type-CFoaj2eD.js → type-C5J875vb.js} +1 -1
  130. package/web/assets/{undo-2-DusxpdLa.js → undo-2-BOUt5qks.js} +1 -1
  131. package/web/assets/{unitAccount-DwutFPPw.js → unitAccount-BIAIxKNp.js} +1 -1
  132. package/web/assets/unitBridge-b2C6zb3a.js +1 -0
  133. package/web/assets/{unitCloudTransport-vA7cLDts.js → unitCloudTransport-NGtDDKWo.js} +1 -1
  134. package/web/assets/{unitOwnerAccess-LBlJ1YfA.js → unitOwnerAccess-CwH9ApZT.js} +1 -1
  135. package/web/assets/{unitShim-B_M9IrbC.js → unitShim-CY8EVkKD.js} +3 -3
  136. package/web/assets/{upload-ZrOj6tXA.js → upload-CrbEAW8C.js} +1 -1
  137. package/web/assets/userSpaces-B_Njvel_.js +1 -0
  138. package/web/assets/viewportLock-Bi3orrUs.css +1 -0
  139. package/web/assets/viewportLock-DZ927PNz.js +629 -0
  140. package/web/assets/{workflow-DPoG4QE2.js → workflow-DY2Cnaei.js} +1 -1
  141. package/web/assets/{zoom-in-lbTgzdQP.js → zoom-in-BcuPvIYd.js} +1 -1
  142. package/web/index.html +24 -27
  143. package/web/assets/CalendarConfigView-DKib8Oed.js +0 -1
  144. package/web/assets/CalendarView-DJ5iOzvu.js +0 -1
  145. package/web/assets/DashboardGridView-B9DCWYVb.js +0 -17
  146. package/web/assets/DashboardGridView-Ck3LKkOb.css +0 -1
  147. package/web/assets/ExcalidrawCanvas-BQ4KKLJP.js +0 -1
  148. package/web/assets/HomepageView-BNabJQfP.css +0 -1
  149. package/web/assets/HomepageView-RCOfcVbE.js +0 -1
  150. package/web/assets/ImageStudioPanels-lkS_y2uM.js +0 -3
  151. package/web/assets/InlineFiles-CQbQumkf.js +0 -1
  152. package/web/assets/MarkdownBlock-CkqiwPXa.js +0 -58
  153. package/web/assets/ModelPill-CY-rU1RU.js +0 -2
  154. package/web/assets/MuseLibraryView-CtTHlVnT.js +0 -2
  155. package/web/assets/RunLocationPicker-BE5mxnab.css +0 -1
  156. package/web/assets/RunLocationPicker-DBnXYV5B.js +0 -38
  157. package/web/assets/SidebarRow-BAJxbMcx.js +0 -9
  158. package/web/assets/SidebarRow-CsWEqPKX.css +0 -1
  159. package/web/assets/TodoListView-DPKhee6i.js +0 -1
  160. package/web/assets/UnifiedPage-BX6ZQL0h.js +0 -68
  161. package/web/assets/appStore-wtOILggO.css +0 -1
  162. package/web/assets/codingNavigation-CZB4v1ZW.css +0 -1
  163. package/web/assets/codingNavigation-DDlPpPk5.js +0 -47
  164. package/web/assets/dashboardSurface-BYM3C7WG.js +0 -1
  165. package/web/assets/i18n-ecQQxiMQ.css +0 -1
  166. package/web/assets/index-BM2o7PeV.js +0 -298
  167. package/web/assets/index-CuiYK18N.js +0 -1
  168. package/web/assets/linkFollow-B7ivDZMM.js +0 -8
  169. package/web/assets/main-sIq2N9Z5.js +0 -20
  170. package/web/assets/markdownEditorSurface-ZSJ3RHAv.js +0 -3
  171. package/web/assets/mdMarkStore-DQHDjG7s.js +0 -2
  172. package/web/assets/mdMarks-DbIcRa0O.js +0 -1
  173. package/web/assets/minus-C9ndHJ9O.js +0 -1
  174. package/web/assets/mobileEntry-CPmU_c4m.js +0 -13
  175. package/web/assets/pageChrome-CovzZPdb.css +0 -1
  176. package/web/assets/pluginChat-BbBukMuN.js +0 -2
  177. package/web/assets/tableSurface-BXqqidd1.js +0 -1
  178. package/web/assets/unitBridge-CcgQpkqV.js +0 -1
  179. package/web/assets/userSpaces-uJOnsedR.js +0 -1
  180. package/web/assets/viewportLock-D3SNkwS2.js +0 -631
  181. package/web/assets/viewportLock-IP1zaVkz.css +0 -1
@@ -1,68 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PdfAnnotator-DUyrgY-t.js","./index-BM2o7PeV.js","./pdf-C2_sJa3b.js","./pdf.worker.min-CGb3BKV9.js","./appStore-DWP8UET9.js","./nativeDownload-BYT082bY.js","./ipc-CxAyeo8q.js","./client-0MPbodA6.js","./appStore-wtOILggO.css","./PdfAnnotator-C_kglLCA.css"])))=>i.map(i=>d[i]);
2
- import{r as yn,j as f,u as Zt,d as v,O as So,t as Ce,bB as Au,bC as $u,bD as Tu,bE as qs,b2 as ju,a_ as gl,bF as Ru,b5 as Du,bG as Zs,bH as Lu,bI as Oc,bJ as Iu,bK as Pu,l as yl,bL as Fu,bM as Oo,bN as Ou,aG as _u,aT as Bu,bO as Ku,bP as xl,n as qu,bQ as Hu,m as hs,aO as bl,aS as Vu,bv as ia,I as Wu,ag as _c,V as Yu,_ as Xu,bR as Uu,K as Gu,bS as Ju,bT as Zu,ab as Qu,q as vl,as as Bc,B as wl,bU as Kc,bV as Hs,bW as qc,bX as ed,bY as Hc,ad as td,bZ as go,b_ as Vc,b$ as nd,aw as rd,c0 as od,ax as sd,c1 as ad,c2 as cd}from"./index-BM2o7PeV.js";import{F as id,c as Qs,d as ld,p as ks,e as ps,t as ud,f as dd,g as fd,h as md,i as sc,l as kl,j as pd,k as Fa,m as hd,n as gd,o as yd,q as xd,r as la,v as ua,w as bd,x as Vs,y as Oa,z as vd,A as Ws,B as wd,C as _a,D as Cl,E as Wc,G as kd,H as Cd,I as Sd,T as Ed,J as Md,K as zd,L as Nd,M as Ad,u as Sl,N as $d,O as Td,Q as jd,R as Rd,S as Yc,U as Dd,V as As,W as Ld,X as Id,Y as Pd,Z as El,_ as as,$ as Fd,a0 as Od,a1 as _d,a2 as Bd,a3 as Kd,a4 as qd,a5 as Hd,a6 as Vd,a7 as da,a8 as Wd,a9 as Yd,aa as Xd}from"./MarkdownBlock-CkqiwPXa.js";import{F as Qt,my as Ud,as as Gd,c5 as Ml,dl as vn,mz as Jd,cq as Ko,mA as Ht,ag as Fn,mB as Xc,mC as Pr,mD as Pe,mE as Ao,mF as Zd,mG as Qd,mH as ef,bp as zl,b as Cn,fr as ac,mI as Uc,iM as tf,aq as nf,aE as cc,mJ as rf,aJ as ea,mK as of,mL as sf,mM as af,mN as jn,mO as ze,mP as Sr,K as ic,G as cf,aM as Gc,l6 as Eo,mQ as Nl,cV as Ba,mR as Jc,mS as lf,gc as uf,mT as io,mU as cr,mV as df,mW as ff,mX as mf,mY as pf,mZ as Zc,m_ as hf,fp as gf,fo as yf,m$ as xf,f9 as Al,n0 as Qc,gd as bf,n1 as vf,l0 as wf,n2 as $l,n3 as kf,n4 as Cf,n5 as Sf,n6 as Ka,n7 as Ef,n8 as ei,n9 as Mf,na as Uo,fL as qa,nb as ti,nc as $s,dX as zf,cO as Nf,kq as Af,kp as $f,nd as ao,ah as zo,P as Tf,ne as ni,nf as ri,fZ as oi,ly as jf,ng as Rf,nh as Df,ni as Lf,nj as If,nk as si,me as Pf,nl as Ff,nm as ai,nn as Of,lx as _f,no as Bf,np as Kf,nq as qf,bJ as Ha,eD as Hf,fq as Vf,nr as Wf,f2 as Yf,ns as Xf,nt as Uf,nu as Gf,nv as Jf,nw as Zf,nx as Qf,ny as em,nz as ci,nA as tm,nB as nm,nC as fa,nD as ii,nE as ma,dD as rm,cK as om,cp as sm,ix as li,bU as am,dB as cm,nF as ui,nG as im,nH as lm,nI as di,nJ as um,Y as dm,b5 as fm,nK as mm,nL as pm,nM as hm,nN as Lo,nO as bn,nP as gm,nQ as ym,nR as Va,fe as pa,nS as fi,mj as xm,hK as bm,nT as vm,nU as wm}from"./appStore-DWP8UET9.js";import{c as km}from"./client-0MPbodA6.js";import{$ as St,a as Tl,b as lc}from"./index-CuiYK18N.js";import{N as Cm,S as Sm,r as Em,a as Mm,C as zm,U as Nm,I as Am}from"./pageChrome-D3Niv1JM.js";import{h as Yo,l as $m,f as Xo,a as mi,i as uc,b as _s,c as Tm,d as yo,t as Ts,e as js,g as ha,s as jm,j as Rm,k as Dm}from"./listFold-DLuxXiIj.js";import{a as Lm,b as Im,c as pi,v as hi,i as Pm}from"./linkFollow-B7ivDZMM.js";import{S as Fm,b as Om,a as _m,F as Bm}from"./SketchCard-BGYz-bXP.js";import{A as gi}from"./arrow-up-right-DrCXuWS7.js";import{c as jl}from"./nativeDownload-BYT082bY.js";import{r as Go,a as Km,C as qm}from"./Chrome-HdfyYV3i.js";import{e as Hm,h as Vm,a as yi,o as Wm,d as Ym,i as Xm,g as Um,j as Gm,k as Jm,f as Zm,c as Qm}from"./canvasPrefs-8taQ42Cz.js";import{H as ep}from"./hand-Bko7ms15.js";import{T as tp,F as np}from"./type-CFoaj2eD.js";import{M as rp}from"./minus-C9ndHJ9O.js";import{createFoldMemory as op,remapFoldMemory as sp}from"./foldActions-05QcQziQ.js";import{L as ap}from"./lock-CnbZm4vo.js";import{U as cp}from"./undo-2-DusxpdLa.js";import{C as ip}from"./code-xml-Cuna8Kh4.js";import{M as lp}from"./message-square-plus-CpiKDvle.js";const up=[["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"}]],dp=Qt("align-center-vertical",up);const fp=[["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"}]],mp=Qt("between-horizontal-end",fp);const pp=[["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"}]],hp=Qt("between-horizontal-start",pp);const gp=[["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"}]],yp=Qt("between-vertical-end",gp);const xp=[["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"}]],bp=Qt("between-vertical-start",xp);const vp=[["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"}]],wp=Qt("case-sensitive",vp);const kp=[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]],Cp=Qt("chevrons-down",kp);const Sp=[["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"}]],Ep=Qt("heading-1",Sp);const Mp=[["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"}]],zp=Qt("heading-2",Mp);const Np=[["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"}]],Ap=Qt("heading-3",Np);const $p=[["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"}]],Tp=Qt("list-collapse",$p);const jp=[["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"}]],Rp=Qt("list-ordered",jp);const Dp=[["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"}]],Lp=Qt("move-horizontal",Dp);const Ip=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Pp=Qt("move-right",Ip);const Fp=[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Op=Qt("move-left",Fp);const _p=[["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"}]],xi=Qt("pilcrow",_p);const Bp=[["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"}]],Kp=Qt("regex",Bp);const qp=[["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"}]],Hp=Qt("replace-all",qp);const Vp=[["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"}]],Wp=Qt("replace",Vp);const Yp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],Xp=Qt("rows-2",Yp);const Up=[["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"}]],Gp=Qt("spline",Up);const Jp=[["path",{d:"M21 9a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z",key:"1dfntj"}],["path",{d:"M15 3v5a1 1 0 0 0 1 1h5",key:"6s6qgf"}]],Wa=Qt("sticky-note",Jp);const Zp=[["path",{d:"M17 5H3",key:"1cn7zz"}],["path",{d:"M21 12H8",key:"scolzb"}],["path",{d:"M21 19H8",key:"13qgcb"}],["path",{d:"M3 12v7",key:"1ri8j3"}]],Qp=Qt("text-quote",Zp);function eh(e,t){const n=e.trim().toLowerCase(),r=t.toLowerCase();if(!n)return 1;let o=0,s=0,c=-2,a=-1;for(let i=0;i<r.length&&s<n.length;i++)if(r[i]===n[s]){a<0&&(a=i);let d=1;i===c+1&&(d+=4),(i===0||/[\s/\-_.]/.test(r[i-1]))&&(d+=3),o+=d,c=i,s++}return s<n.length?null:(o-=a*.1,o-=r.length*.02,r===n&&(o+=10),o)}function th(e,t,n){if(!e.trim())return t;const r=[];for(const o of t){const s=eh(e,n(o));s!=null&&r.push({item:o,score:s})}return r.sort((o,s)=>s.score-o.score),r.map(o=>o.item)}yn({"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 Ya="amadeus_delete_assets";function Yb(){try{const e=localStorage.getItem(Ya);return e==="yes"?!0:e==="no"?!1:null}catch{return null}}function nh(e){try{e===null?localStorage.removeItem(Ya):localStorage.setItem(Ya,e?"yes":"no")}catch{}}const gs=jl(e=>({req:null,open:t=>e({req:t}),clear:()=>e({req:null})}));function rh(e,t,n){return new Promise(r=>{gs.getState().req?.resolve(null),gs.getState().open({note:e,assets:t,block:n?.block,resolve:r})})}function Xb(){const e=gs(t=>t.req);return e?f.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},children:f.jsx(oh,{req:e},e.note)}):null}function oh({req:e}){const{t}=Zt(),[n,r]=v.useState(!1),o=c=>{gs.getState().req===e&&(n&&c!==null&&nh(c==="with"),gs.getState().clear(),e.resolve(c))};Ud(()=>o(null));const s=e.assets.slice(0,6);return f.jsx("div",{className:"dialog-overlay",onMouseDown:()=>o(null),children:f.jsxs("div",{className:"dialog",onMouseDown:c=>c.stopPropagation(),children:[f.jsx("div",{className:"dialog-title",children:e.block?t("delassets.blockTitle"):t("delassets.noteTitle",{name:e.note})}),f.jsxs("div",{className:"dialog-msg",children:[e.block?t("delassets.blockMsg",{n:e.assets.length}):t("delassets.noteMsg",{n:e.assets.length}),f.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18,opacity:.8},children:[s.map(c=>f.jsx("li",{children:c},c)),e.assets.length>s.length&&f.jsx("li",{children:t("delassets.more",{n:e.assets.length-s.length})})]})]}),!e.block&&f.jsxs("label",{className:"inline-check",style:{display:"flex",gap:6,alignItems:"center",marginTop:10},children:[f.jsx("input",{type:"checkbox",checked:n,onChange:c=>r(c.target.checked)}),t("delassets.remember")]}),f.jsxs("div",{className:"dialog-actions",children:[e.block?f.jsx("button",{className:"dialog-btn",autoFocus:!0,onClick:()=>o("only"),children:t("delassets.keepFiles")}):f.jsxs(f.Fragment,{children:[f.jsx("button",{className:"dialog-btn",onClick:()=>o(null),children:t("delassets.cancel")}),f.jsx("button",{className:"dialog-btn",onClick:()=>o("only"),children:t("delassets.noteOnly")})]}),f.jsx("button",{className:"dialog-btn","data-danger":!0,autoFocus:!e.block,onClick:()=>o("with"),children:t("delassets.deleteAll")})]})]})})}yn({"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 Xa="forsion.amadeus.aiSpaceTrigger";let cs=null;function sh(){if(cs===null)try{cs=localStorage.getItem(Xa)==="1"}catch{cs=!1}return cs}function Ub(e){cs=e;try{e?localStorage.setItem(Xa,"1"):localStorage.removeItem(Xa)}catch{}}yn({"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 Rl=typeof CSS<"u"&&"highlights"in CSS;let qt=[],ys=[];const Ct=jl(()=>({open:!1,query:"",active:0,total:0,root:null,caseSensitive:!1,regex:!1,bad:!1,replaceOpen:!1,replacement:"",replaceable:0,providerVer:0})),xs=new Set,bi=()=>Ct.setState(e=>({providerVer:e.providerVer+1}));function vi(e){return xs.add(e),bi(),()=>{xs.delete(e),bi()}}function dc(e){const t=e.startContainer;for(const n of xs)if(n.el.isConnected&&(n.owns?n.owns(t):n.el.contains(t)))return n;return null}function wi(e,t,n){return!n||!t?e:e.replace(/\$(\$|&|<([^>]*)>|(\d{1,2}))/g,(r,o,s,c)=>{if(o==="$")return"$";if(o==="&")return t[0];if(s!==void 0)return t.groups?.[s]??"";if(c!==void 0){const a=Number(c);if(a>=1&&a<t.length)return t[a]??"";if(c.length===2&&Number(c[0])>=1&&Number(c[0])<t.length)return(t[Number(c[0])]??"")+c[1]}return r})}function Dl(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 ah(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"],r=()=>{if(!t)return;const o=getComputedStyle(e);for(const s of n)t.style[s]=o[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:o=>!!t&&t.contains(o),attach:()=>{t=document.createElement("div"),t.className="amx-find-mirror",t.setAttribute("aria-hidden","true"),e.parentElement?.insertBefore(t,e.nextSibling),r();const o=new ResizeObserver(r);return o.observe(e),e.addEventListener("input",r),e.addEventListener("scroll",r),()=>{o.disconnect(),e.removeEventListener("input",r),e.removeEventListener("scroll",r),t?.remove(),t=null}},replace:o=>{const s=e.value,c=o.map(({range:I,text:N})=>({from:I.startOffset,to:I.endOffset,text:N,was:I.toString()})).filter(I=>s.slice(I.from,I.to)===I.was).sort((I,N)=>I.from-N.from);if(!c.length)return 0;const a=c[0].from,i=c[c.length-1].to;let d="",p=a;for(const I of c)d+=s.slice(p,I.from)+I.text,p=I.to;d+=s.slice(p,i);const g=document.activeElement;return e.focus(),e.setSelectionRange(a,i),(d?document.execCommand("insertText",!1,d):document.execCommand("delete"))||(e.setRangeText(d,a,i,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))),g?.focus(),r(),c.length},focusAt:o=>t?.contains(o.startContainer)?(e.focus({preventScroll:!0}),e.setSelectionRange(o.startOffset,o.endOffset),!0):!1}}function ch(){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 ih(){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 bs=null;function lh(){const e=document.activeElement;if(!(e instanceof HTMLElement)||e===document.body||e.closest(".amx-findbar")){bs=null;return}const t=window.getSelection(),n=t&&t.rangeCount?t.getRangeAt(0):null;bs={el:e,range:e.isContentEditable&&n&&e.contains(n.startContainer)?n.cloneRange():null}}function uh(e){const t=e.startContainer.parentElement;if(!t?.isContentEditable)return null;let n=t;for(;n.parentElement?.isContentEditable;)n=n.parentElement;return n}function dh(e){const t=bs;bs=null;const n=document.activeElement;if(!(n&&n!==document.body&&!n.closest(".amx-findbar"))){if(e){if(dc(e)?.focusAt?.(e))return;const o=uh(e);if(o){o.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 r=window.getSelection();r?.removeAllRanges(),r?.addRange(t.range)}}}function Gb(e={}){if(!Rl)return;const t=ih();if(Ct.getState().open){Ct.setState({...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}});const n=document.querySelector(".amx-findbar input");n?.focus(),n?.select();return}lh(),Ct.setState({open:!0,root:ch(),...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}})}function ga(e){const t=e==="keyboard"?qt[Ct.getState().active]??null:null;qt=[],ys=[],is(-1),Ct.setState({open:!1,query:"",active:0,total:0,root:null,bad:!1,replaceable:0}),e?dh(t):bs=null}const fh=/^(inline|contents|ruby)/;function mh(e,t){let n=e.parentElement;for(;n;){let r=t.get(n);if(r===void 0&&(r=fh.test(getComputedStyle(n).display),t.set(n,r)),!r)return n;n=n.parentElement}return null}function ph(e,t){if(ys=[],!t)return[];const n=new WeakMap,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(d){const p=d.parentElement;if(!p||!d.nodeValue||p.closest(".amx-findbar"))return NodeFilter.FILTER_REJECT;const g=p.tagName;return g==="SCRIPT"||g==="STYLE"||g==="NOSCRIPT"||g==="TEXTAREA"||!p.checkVisibility()?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let o="";const s=[];let c=null;for(let d=r.nextNode();d;d=r.nextNode()){const p=d,g=mh(p,n);s.length&&g!==c&&(o+=`
3
- `),c=g,s.push({node:p,at:o.length}),o+=p.nodeValue??""}const a=[];let i=0;t.lastIndex=0;for(let d=t.exec(o);d;d=t.exec(o)){if(!d[0]){t.lastIndex++;continue}if(d[0].includes(`
4
- `))continue;const p=d.index,g=p+d[0].length;for(;i>0&&s[i].at>p;)i--;for(;i+1<s.length&&s[i+1].at<=p;)i++;let C=i;for(;C+1<s.length&&s[C+1].at<g;)C++;const I=document.createRange();I.setStart(s[i].node,p-s[i].at),I.setEnd(s[C].node,Math.min(g-s[C].at,s[C].node.length)),a.push(I),ys.push(d)}return a}function ya(e){const t=Ct.getState(),n=Dl(t.query,t);return qt=ph(e,n==="bad"?null:n),Ct.setState({bad:n==="bad",replaceable:qt.filter(r=>dc(r)).length}),qt.length}function is(e){if(!Rl)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],r=n?new Highlight(n):new Highlight;r.priority=1,t.set("amx-find-active",r)}function hh(e){for(let t=e;t&&t!==document.body;t=t.parentElement){if(!(t instanceof HTMLElement))continue;const n=getComputedStyle(t),r=/auto|scroll/.test(n.overflowY)&&t.scrollHeight>t.clientHeight+1,o=/auto|scroll/.test(n.overflowX)&&t.scrollWidth>t.clientWidth+1;if(r||o)return t}return null}function xa(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 o=hh(n);if(!o)return;const s=o.getBoundingClientRect(),c=o.currentCSSZoom||1;(t.bottom>s.bottom||t.top<s.top)&&(o.scrollTop+=(t.top+t.height/2-(s.top+s.height/2))/c),(t.right>s.right||t.left<s.left)&&(o.scrollLeft+=(t.left+t.width/2-(s.left+s.width/2))/c)}function Jb(){return Ct(t=>t.open)?f.jsx(gh,{}):null}function gh(){const{t:e}=Zt(),t=Ct(H=>H.query),n=Ct(H=>H.active),r=Ct(H=>H.total),o=Ct(H=>H.root),s=Ct(H=>H.caseSensitive),c=Ct(H=>H.regex),a=Ct(H=>H.bad),i=Ct(H=>H.replaceOpen),d=Ct(H=>H.replacement),p=Ct(H=>H.replaceable),g=Ct(H=>H.providerVer),[C,I]=v.useState({top:12,right:12}),N=v.useRef(null),k=!!o&&[...xs].some(H=>H.el.isConnected&&o.contains(H.el));v.useLayoutEffect(()=>{const H=()=>{const te=o?.getBoundingClientRect();te&&I({top:te.top+8,right:Math.max(8,window.innerWidth-te.right+8)})};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[o]),v.useLayoutEffect(()=>{if(!o)return;const H=[...xs].filter(te=>te.attach&&o.contains(te.el)).map(te=>te.attach());return()=>H.forEach(te=>te())},[o,g]),v.useEffect(()=>{o&&(ya(o),Ct.setState({total:qt.length,active:0}),is(0),qt.length&&xa(qt[0]))},[o,t,s,c,g]),v.useEffect(()=>{if(!o)return;const H=()=>{o.isConnected||ga()};window.addEventListener("focusin",H);const te=window.setInterval(H,1e3);return()=>{window.removeEventListener("focusin",H),window.clearInterval(te)}},[o]),v.useEffect(()=>{if(!o||!t.trim())return;let H=0;const te=new MutationObserver(()=>{window.clearTimeout(H),H=window.setTimeout(()=>{ya(o);const Re=Math.min(Ct.getState().active,Math.max(0,qt.length-1));Ct.setState({total:qt.length,active:Re}),is(Re)},150)});return te.observe(o,{childList:!0,subtree:!0,characterData:!0}),()=>{window.clearTimeout(H),te.disconnect()}},[o,t,s,c]);const $=H=>{if(!qt.length)return;const te=(Ct.getState().active+H+qt.length)%qt.length;Ct.setState({active:te}),is(te),xa(qt[te])},F=H=>{if(!o||!qt.length)return;const te=Ct.getState(),Re=H?qt.map((be,fe)=>fe):[te.active],Ve=new Map;for(const be of Re){const fe=dc(qt[be]);if(!fe)continue;const Me=Ve.get(fe)??[];Me.push({range:qt[be],text:wi(te.replacement,ys[be],te.regex)}),Ve.set(fe,Me)}let m=0;for(const[be,fe]of Ve)m+=be.replace(fe);if(!m&&!H){$(1);return}const de=te.active,ot=H?"":wi(te.replacement,ys[te.active],te.regex);ya(o);let ce=0;if(!H&&qt.length){const be=Dl(te.query,te),fe=be&&be!=="bad"?(ot.match(new RegExp(be.source,be.flags))??[]).length:0;ce=(de+fe)%qt.length}Ct.setState({total:qt.length,active:ce}),is(ce),qt.length&&xa(qt[ce])},J=H=>H.key==="Escape"?(ga("keyboard"),!0):(H.metaKey||H.ctrlKey)&&H.altKey&&H.code==="KeyF"?(H.preventDefault(),k&&Ct.setState({replaceOpen:!Ct.getState().replaceOpen}),!0):!1,oe=H=>{Ct.setState({[H]:!Ct.getState()[H]}),N.current?.focus()};return f.jsxs("div",{className:`amx-findbar${i&&k?" amx-findbar--replace":""}`,style:{top:C.top,right:C.right},children:[k&&f.jsx("button",{className:"amx-findbar-expand",onClick:()=>Ct.setState({replaceOpen:!i}),title:e("find.toggleReplace"),"aria-label":e("find.toggleReplace"),"aria-expanded":i,children:i?f.jsx(Gd,{size:14}):f.jsx(Ml,{size:14})}),f.jsxs("div",{className:"amx-findbar-rows",children:[f.jsxs("div",{className:"amx-findbar-row",children:[f.jsx("input",{ref:N,autoFocus:!0,placeholder:e("find.placeholder"),value:t,"aria-invalid":a||void 0,title:a?e("find.badRegex"):void 0,onFocus:H=>H.currentTarget.select(),onChange:H=>Ct.setState({query:H.target.value}),onKeyDown:H=>{!J(H)&&H.key==="Enter"&&$(H.shiftKey?-1:1),H.stopPropagation()}}),f.jsx("button",{className:"amx-findbar-opt",onClick:()=>oe("caseSensitive"),"aria-pressed":s,title:e("find.case"),"aria-label":e("find.case"),children:f.jsx(wp,{size:15})}),f.jsx("button",{className:"amx-findbar-opt",onClick:()=>oe("regex"),"aria-pressed":c,title:e("find.regex"),"aria-label":e("find.regex"),children:f.jsx(Kp,{size:14})}),f.jsx("span",{className:"amx-findbar-count",children:r?`${n+1}/${r}`:t.trim()?"0":""}),f.jsx("button",{onClick:()=>$(-1),title:e("find.prev"),"aria-label":e("find.prev"),children:"‹"}),f.jsx("button",{onClick:()=>$(1),title:e("find.next"),"aria-label":e("find.next"),children:"›"}),f.jsx("button",{onClick:()=>ga("pointer"),title:e("find.close"),"aria-label":e("find.close"),children:"✕"})]}),i&&k&&f.jsxs("div",{className:"amx-findbar-row",children:[f.jsx("input",{className:"amx-findbar-replace",placeholder:e("find.replacePlaceholder"),value:d,onChange:H=>Ct.setState({replacement:H.target.value}),onKeyDown:H=>{!J(H)&&H.key==="Enter"&&F(H.metaKey||H.ctrlKey),H.stopPropagation()}}),f.jsx("button",{className:"amx-findbar-act",onClick:()=>F(!1),disabled:!p,title:e("find.replaceOne"),"aria-label":e("find.replaceOne"),children:f.jsx(Wp,{size:14})}),f.jsx("button",{className:"amx-findbar-act",onClick:()=>F(!0),disabled:!p,title:e("find.replaceAll"),"aria-label":e("find.replaceAll"),children:f.jsx(Hp,{size:14})})]})]})]})}yn({"unisave.conflict.toast":{zh:"「{name}」在你编辑时被别处改过。已保留你的版本,被覆盖的那一版另存为「{copy}」。",en:'"{name}" was changed elsewhere while you were editing. Your version was kept, and the overwritten version was saved as "{copy}".'},"unisave.conflict.agentToast":{zh:"Tangu 在你编辑时改了「{name}」。已保留你的版本,Tangu 的改动另存为「{copy}」。",en:'Tangu changed "{name}" while you were editing. Your version was kept, and Tangu’s changes were saved as "{copy}".'},"unisave.conflict.open":{zh:"打开副本",en:"Open copy"},"unisave.failed.toast":{zh:"「{name}」没能保存({reason}),正在自动重试。保存成功之前请不要关闭它。",en:'Couldn’t save "{name}" ({reason}). Retrying automatically — keep it open until it’s saved.'},"unisave.failed.unknown":{zh:"未知原因",en:"unknown reason"},"unisave.failed.bar":{zh:"未保存:写入失败,正在自动重试",en:"Unsaved: the write failed and is being retried"},"unisave.failed.retry":{zh:"立即重试",en:"Retry now"},"unisave.draft.bar":{zh:"这篇笔记有一份上次没保存成功的草稿({time})。",en:"This note has a draft that wasn’t saved last time ({time})."},"unisave.draft.hint":{zh:"恢复后会覆盖盘上当前内容;盘上那一版若是别处改过的,会先另存为冲突副本。",en:"Restoring replaces what’s on disk now. If that version was changed elsewhere, it is saved as a conflict copy first."},"unisave.draft.restore":{zh:"恢复草稿",en:"Restore draft"},"unisave.draft.discard":{zh:"丢弃",en:"Discard"},"unisave.gone.toast":{zh:"「{name}」已在别处被删除或移走,最后的改动没来得及保存,另存副本也没写成。可以把这篇的内容复制下来。",en:'"{name}" was deleted or moved elsewhere before your last changes were saved, and a backup copy couldn’t be written. You can copy its text.'},"unisave.renameCopy.toast":{zh:"「{name}」改名时已被别处改过,没有覆盖它。你改名期间打的字另存为「{copy}」。",en:'"{name}" was changed elsewhere while it was being renamed, so it wasn’t overwritten. What you typed during the rename was saved as "{copy}".'},"unisave.rescued.toast":{zh:"「{name}」已在别处被删除或移走。你还没保存的内容另存为「{copy}」。",en:'"{name}" was deleted or moved elsewhere. Your unsaved changes were saved as "{copy}".'},"unisave.gone.copy":{zh:"复制内容",en:"Copy text"},"unisave.gone.copied":{zh:"已复制到剪贴板",en:"Copied to clipboard"}});function lo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:e}))}const uo=e=>(e.split("/").pop()??e).replace(/\.md$/i,"");let ki=Promise.resolve();function ba(e,t,n=new Date){const r=ki.then(()=>Ci(e,t,n),()=>Ci(e,t,n));return ki=r.catch(()=>{}),r}async function Ci(e,t,n){const r=Au(e,n);for(let o=1;o<=50;o++){const s=$u(r,o),c=await vn.readTextFile(s);if(c===t)return s;if(c!=null)continue;const a=await vn.writeTextFile(s,t,{create:!0});if(a&&a.ok===!1){if(a.current===t)return s;if(a.current!=null)continue;throw new Error("The conflict copy could not be created")}return s}throw new Error("Too many conflict copies in one minute")}function yh(e,t,n=!1){lo({level:"error",dedupeKey:`amx-conflict:${e}`,text:Ce(n?"unisave.conflict.agentToast":"unisave.conflict.toast",{name:uo(e),copy:uo(t)}),action:{label:Ce("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function Ll(e){const n=(e instanceof Error?e.message:typeof e=="string"?e:"").replace(/^Error invoking remote method '[^']*':\s*/,"").replace(/^(?:[A-Za-z]*Error:\s*)+/,"").trim();return n?n.length>80?`${n.slice(0,79)}…`:n:Ce("unisave.failed.unknown")}function va(e,t){lo({level:"warning",dedupeKey:`amx-savefail:${e}`,text:Ce("unisave.failed.toast",{name:uo(e),reason:Ll(t)})})}function xh(e,t){lo({level:"error",dedupeKey:`amx-rescued:${t}`,text:Ce("unisave.rescued.toast",{name:uo(e),copy:uo(t)}),action:{label:Ce("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function bh(e,t){lo({level:"error",dedupeKey:`amx-renamecopy:${t}`,text:Ce("unisave.renameCopy.toast",{name:uo(e),copy:uo(t)}),action:{label:Ce("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function vh(e,t){lo({level:"error",dedupeKey:`amx-gone:${e}:${So(t)}`,text:Ce("unisave.gone.toast",{name:uo(e)}),action:{label:Ce("unisave.gone.copy"),run:()=>{navigator.clipboard?.writeText(t).then(()=>lo({text:Ce("unisave.gone.copied")}),()=>{})}}})}const Si=[2e3,5e3,1e4,3e4,6e4],Il=(e,t)=>`amadeus.unsavedDraft:${e??""}:${t}`,Ys=(e,t,n)=>Il(e,t)+(n?`\0${n}`:"");function Dr(e,t,n,r,o){try{const s={text:n,base:So(r),at:Date.now()};localStorage.setItem(Ys(e,t,o),JSON.stringify(s))}catch{}}function ls(e,t){if(!e)return null;const n=JSON.parse(e);return typeof n.text=="string"&&typeof n.base=="string"?{text:n.text,base:n.base,at:Number(n.at)||0,slot:t}:null}function wh(e,t,n,r=()=>!0){try{const o=Ys(e,t);if(n){const a=ls(localStorage.getItem(Ys(e,t,n)),n);if(a)return a;const i=r(null)?null:ls(localStorage.getItem(o),null);if(i)return i}else{const a=ls(localStorage.getItem(o),null);if(a)return a}const s=Il(e,t)+"\0";let c=null;for(let a=0;a<localStorage.length;a++){const i=localStorage.key(a);if(!i||!i.startsWith(s))continue;const d=i.slice(s.length);if(d===n||r(d))continue;const p=ls(localStorage.getItem(i),d);p&&(!c||p.at>c.at)&&(c=p)}return c}catch{return null}}function Jo(e,t,n,r){try{const o=Ys(e,t,r);if(n!=null){const s=ls(localStorage.getItem(o),r??null);if(!s||s.text!==n)return}localStorage.removeItem(o)}catch{}}function kh(){return typeof navigator<"u"&&/\bElectron\//.test(navigator.userAgent)}function vo(e){const t=Tu(e);return t.length===e.length&&e.startsWith(qs)?{fmText:qs,body:e.slice(1)}:{fmText:e.slice(0,e.length-t.length),body:t}}function $n(e,t){return e+t}function wa(e,t){const n=ws(e);return n.trim()&&!Ch(n)?e:vo(Ru(e,t)).fmText}function Ch(e){try{const t=Zs(e);return t==null||typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function Sh(e,t){const n=Eh(e,t);if(n!==null)return Ga(e,n);const{bom:r}=vs(e),o=Ja(e),s=t.replace(/\n+$/,"");if(!o.length&&!s.trim())return r;const c=r+["---",...o,...s.trim()?[s]:[],"---",""].join(`
5
- `);return Ua(s)?Ga(e,c):c}function Eh(e,t){const n=ws(e),r=t.replace(/(?:\r?\n)+$/,"");if(!n||!r.trim())return null;if(r===n)return e;const o=e.indexOf(n),s=o+n.length;if(o<=0||e[o-1]!==`
6
- `||!/^\r?\n/.test(e.slice(s))||e.indexOf(n,o+1)>=0)return null;const c=e.slice(0,o)+r+e.slice(s);return ws(c)===r&&Ja(c).join(`
7
- `)===Ja(e).join(`
8
- `)?c:null}function Ua(e){try{return Zs(e),!0}catch{return!1}}function Ga(e,t){if(t===e)return t;const n=vs(t).inner;if(n==null||Ua(n))return t;const r=vs(e).inner;return r==null||!Ua(r)?t:(console.warn("[amadeus] frontmatter rewrite would produce invalid YAML; keeping the original block"),e)}const Mh=/^---\r?\n([\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)$/;function vs(e){const t=e.startsWith(qs)?qs:"",n=Mh.exec(e.slice(t.length));return{bom:t,inner:n?n[1]??"":null}}function fc(e){const{inner:t}=vs(e);return t==null?null:t?Lu(t.replace(/\r?\n$/,"").split(/\r?\n/)):[]}function Ja(e){return(fc(e)??[]).filter(t=>Du.test(t[0])).flat()}const zh=/^["']?amadeus_(schema|layout|canvas)["']?\s*:/;function us(e,t,n){const{bom:r}=vs(e),o=fc(e)??[],s=o.filter(i=>!zh.test(i[0])).flat(),a=[...Jd(t,n).flatMap(i=>{const d=Ah.exec(i)?.[1],p=d?Fl(o,d):null;return p&&p.length>1&&Ol(p,d)===(d==="layout"?t:n)?p:[i]}),...s];return a.length?Ga(e,r+["---",...a,"---",""].join(`
9
- `)):r}function Nh(e){const t=pr(e),n=un(e);return t==null&&n==null||/^["']?amadeus_schema["']?\s*:/m.test(e)?e:us(e,t,n)}function pr(e){return Pl(e,"layout")}function un(e){return Pl(e,"canvas")}const Ah=/^amadeus_(layout|canvas):/;function Pl(e,t){const n=fc(e),r=n&&Fl(n,t);return r?Ol(r,t):null}function Fl(e,t){const n=new RegExp(`^["']?amadeus_${t}["']?\\s*:`);let r=null;for(const o of e)n.test(o[0])&&(r=o);return r}function Ol(e,t){if(e.length===1){const r=new RegExp(`^["']?amadeus_${t}["']?\\s*:\\s*(.+)$`).exec(e[0]);return r?r[1].trim():null}const n=e.join(`
10
- `);try{const r=Zs(n),o=r&&typeof r=="object"&&!Array.isArray(r)?Object.values(r)[0]:void 0;if(o&&typeof o=="object")return JSON.stringify(o);if(typeof o=="string")return o}catch{}return n}function $h(e){return e?ju(gl(e)):{}}function ws(e){return e?gl(e):""}const Th=80;function jh(){return St(()=>{if(!Ko())return new Ht({});const e=Math.round(Th*Fn(document.body));return new Ht({props:{scrollThreshold:{top:0,left:0,right:0,bottom:e},scrollMargin:{top:5,left:5,right:5,bottom:e}}})})}function Xs(e){const t=[];return e.descendants((n,r)=>{if(n.type.name!=="heading")return!0;const o=Number(n.attrs?.level),s=Number.isFinite(o)?Math.min(6,Math.max(1,o)):1,c=n.textContent.trim();return c&&t.push({level:s,text:c,pos:r}),!1}),t}function Ei(e,t=0,n=e.content.size){return e.textBetween(t,n,`
11
- `,()=>"").replace(/!\[\[[^\]\n]*\]\]/g,"").replace(/\[\[(?:[^\]|\n]*\|)?([^\]\n]*)\]\]/g,"$1")}function Rh(e){let t=null,n={chars:0,words:0};return()=>{const r=e();if(!r)return null;r.state.doc!==t&&(t=r.state.doc,n=Xc(Ei(t)));const{from:o,to:s,empty:c}=r.state.selection;return{all:n,sel:c?null:Xc(Ei(r.state.doc,o,s))}}}function Dh(){return[St(()=>new Ht({view:()=>{let e=0;const t=()=>{e||(e=requestAnimationFrame(()=>{e=0,Oc()}))};return t(),{update:(n,r)=>{(n.state.doc!==r.doc||!n.state.selection.eq(r.selection))&&t()},destroy:()=>{e&&cancelAnimationFrame(e),Oc()}}}}))]}function Lh(e){const t=(r,o,s)=>{const c=r.selection;return!(c instanceof Pe)||!c.empty||!s||Ao.atStart(r.doc).$from.start()!==c.$from.start()||!s.endOfTextblock("up")?!1:e()},n=r=>{const o=r.selection;if(!(o instanceof Pe)||!o.empty)return!1;const s=o.$from;return s.depth!==1||s.index(0)!==0||s.parentOffset!==0||s.parent.type.name!=="paragraph"?!1:e()};return[St(()=>Pr({ArrowUp:t,ArrowLeft:n}))]}function Mi(e,t){const n=e.content.size;return e.textBetween(Math.max(0,t-12),Math.min(n,t+12),`
12
- `,"")}function Ih(e){return[St(()=>new Ht({view:t=>{let n=!0,r=null;const o=()=>{r=null;const{vaultRoot:c,path:a}=e.where(),i=t.state.selection;Qd(c,a,{a:i.anchor,h:i.head,t:Mi(t.state.doc,i.head)})};queueMicrotask(()=>{if(!n||!e.restore())return;const{vaultRoot:c,path:a}=e.where(),i=Zd(c,a),d=t.state.doc;let p=null;if(i&&i.a<=d.content.size&&i.h<=d.content.size&&Mi(d,i.h)===i.t){try{p=Pe.between(d.resolve(i.a),d.resolve(i.h))}catch{p=null}p&&(p.anchor!==i.a||p.head!==i.h)&&(p=null)}p&&t.dispatch(t.state.tr.setSelection(p).setMeta("addToHistory",!1)),e.focus()&&t.focus()});const s=()=>{r&&(clearTimeout(r),o(),ef())};return window.addEventListener("pagehide",s),{update:(c,a)=>{c.state.selection.eq(a.selection)&&c.state.doc===a.doc||(r&&clearTimeout(r),r=setTimeout(o,300))},destroy:()=>{n=!1,window.removeEventListener("pagehide",s),r&&(clearTimeout(r),o())}}}}))]}yn({"canvasseg.aria":{zh:"编辑模式",en:"Editing mode"},"canvasseg.doc":{zh:"文档",en:"Document"},"canvasseg.canvas":{zh:"画布",en:"Canvas"}});const Ph="amx-modeseg-slot";function Fh({on:e,toggle:t}){const{t:n}=Zt();return f.jsxs("div",{className:"t2s-vaultseg amx-modeseg",role:"tablist","aria-label":n("canvasseg.aria"),children:[f.jsx("div",{className:"t2s-vaultseg-thumb","data-side":e?"canvas":"doc"}),f.jsx("button",{type:"button",role:"tab","aria-selected":!e,className:e?"":"on",onMouseDown:r=>r.preventDefault(),onClick:()=>{e&&t()},children:n("canvasseg.doc")}),f.jsx("button",{type:"button",role:"tab","aria-selected":e,className:e?"on":"",onMouseDown:r=>r.preventDefault(),onClick:()=>{e||t()},children:n("canvasseg.canvas")})]})}function Oh({anchor:e,on:t,toggle:n}){const[r,o]=v.useState(null);return v.useEffect(()=>{const s=e?.closest(".amx-pane")??e?.ownerDocument?.body;if(!s)return;const c=()=>o(s.querySelector(`.${Ph}`));c();const a=new MutationObserver(c);return a.observe(s,{childList:!0,subtree:!0}),()=>a.disconnect()},[e]),r?zl.createPortal(f.jsx(Fh,{on:t,toggle:n}),r):null}yn({"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 _h=["text","number","checkbox","date","list"];function Bh(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 Kh=e=>/^(tags?|alias(es)?|cssclass(es)?)$/i.test(e.trim())?"list":"text",_l=e=>/\[\[[^\]\n]+\]\]/.test(e);function ka(e){if(!e.trim())return{ok:!0,entries:[]};try{const t=Zs(e);if(t&&typeof t=="object"&&!Array.isArray(t))return{ok:!0,entries:Object.entries(t).map(([n,r])=>({key:n,value:r}))}}catch{}return{ok:!1,entries:[]}}const Bl=e=>Array.isArray(e)&&e.every(t=>t===null||typeof t!="object");function Ca(e,t,n,r=o=>o){if(e===null)return null;const o=r(e);return o===r(t)||o===r(n)?null:o}const Kl=v.createContext(null);function mc(e,t,{escDiscards:n="conflict",norm:r=s=>s,enterCommits:o=!1}={}){const[s,c]=v.useState(null),[a,i]=v.useState(e),d=v.useRef({draft:s,base:a,current:e,norm:r,commit:t});d.current.current=e,d.current.norm=r,d.current.commit=t;const p=k=>{d.current.draft=k,c(k)},g=k=>{d.current.base=k,i(k)},C=v.useContext(Kl);v.useLayoutEffect(()=>{if(!C)return;const k=()=>{const $=d.current,F=Ca($.draft,$.base,$.current,$.norm);F!==null&&(g(F),$.commit(F))};return C.add(k),()=>{C.delete(k),k()}},[C]);const I=s!==null&&e!==a&&Ca(s,a,e,r)!==null;return{shown:s??e,conflict:I,change:k=>{d.current.draft===null&&g(d.current.current),p(k)},settle:()=>{const k=d.current,$=Ca(k.draft,k.base,k.current,k.norm);return p(null),$},onKeyDown:k=>{if(!(k.nativeEvent.isComposing||k.keyCode===229)){if(k.key==="Enter"&&o){k.preventDefault(),k.currentTarget.blur();return}k.key!=="Escape"||n==="never"||!I||(k.preventDefault(),k.stopPropagation(),p(null))}}}}function qh({fmExtra:e,onCommit:t,readOnly:n=!1,notePath:r}={}){const{t:o}=Zt(),s=Cn(Me=>Me.activePage),c=Cn(Me=>Me.vaultRoot),a=Cn(Me=>Me.manifest?.fmExtra??""),i=ac(),d=e!==void 0,p=d?e:a,g=v.useRef(p);g.current=p;const[C,I]=v.useState(()=>Uc(c)??!1);v.useEffect(()=>{I(Uc(c)??!1)},[c]);const N=Me=>{I(Ke=>{const me=typeof Me=="function"?Me(Ke):Me;return rf(c,me),me})},[k,$]=v.useState(!1),[F,J]=v.useState(null),oe=v.useRef(null),H=r??s??void 0,te=Me=>{const Ke=yl(Me);Ke&&i.getState().openWikiLink(Ke,H)},Re=v.useMemo(()=>ka(p),[p]),Ve=v.useMemo(()=>{const Me=!d&&s?tf(s):void 0;return new Set(Me?.fmKeys??[])},[d,s]),m=v.useMemo(()=>Re.entries.map((Me,Ke)=>({...Me,idx:Ke})).filter(Me=>!Ve.has(Me.key)),[Re,Ve]);if(v.useEffect(()=>{if(!F)return;const Ke=[...oe.current?.querySelectorAll(".amx-prop-row[data-key]")??[]].find(me=>me.dataset.key===F)?.querySelector("input:not(.amx-prop-key), textarea, .amx-prop-links");Ke&&(Ke.focus(),Ke.classList.contains("amx-prop-links")&&Ke.click(),J(null))},[F,Re]),!d&&!s)return null;const de=Me=>{t?t(Me):i.getState().setFmExtra(Me)},ot=Me=>{Me!==null&&de(Me)},ce=(Me,Ke)=>ot(Fu(g.current,{[Me]:Ke})),be=(Me,Ke)=>{const me=Me.trim();return me?/^amadeus_/.test(me)?(window.alert(o("amprops.reservedKey")),!1):Ve.has(me)?(window.alert(o("amprops.pluginManaged")),!1):(ka(g.current).entries.some(Ae=>Ae.key===me)||ce(me,Bh(Ke)),J(me),!0):!1},fe=Re.ok?m.length:null;return f.jsxs("div",{className:`amx-props${fe===0&&!C?" is-empty":""}`,ref:oe,children:[f.jsxs("div",{className:"amx-props-bar",children:[f.jsxs("button",{className:"amx-props-chip",onClick:()=>N(Me=>!Me),children:[fe===null?o("amprops.chipRaw"):o("amprops.chipCount",{n:fe}),C?" ▾":" ▸"]}),!n&&f.jsx("button",{className:"amx-props-add",title:o("amprops.add"),onClick:()=>{N(!0),Re.ok&&$(!0)},children:f.jsx(nf,{size:12})})]}),C&&(Re.ok?f.jsxs("div",{className:"amx-props-rows",children:[m.length===0&&!k&&f.jsx("div",{className:"amx-props-empty",children:o("amprops.empty")}),m.map(Me=>n?f.jsxs("div",{className:"amx-prop-row amx-prop-row-ro",children:[f.jsx("span",{className:"amx-prop-key",children:Me.key}),f.jsx(Wh,{value:Me.value})]},`${s}:${Me.idx}:${Me.key}`):f.jsxs("div",{className:"amx-prop-row","data-key":Me.key,children:[f.jsx(Vh,{name:Me.key,onRename:Ke=>{const me=/^(amadeus_page|amadeus_schema|amadeus_layout|amadeus_canvas|amadeus_next_id)$/.test(Ke)||Ve.has(Ke)||ka(g.current).entries.some(Ae=>Ae.key!==Me.key&&Ae.key===Ke);!Ke||me||ot(Iu(g.current,Me.key,Ke))}}),f.jsx(Uh,{value:Me.value,onCommit:Ke=>ce(Me.key,Ke),onOpenLink:te}),f.jsx("button",{className:"amx-prop-del",title:o("amprops.delete"),onClick:()=>ce(Me.key,void 0),children:f.jsx(cc,{size:12})})]},`${s}:${Me.key}`)),k&&!n&&f.jsx(Yh,{onAdd:(Me,Ke)=>{be(Me,Ke)&&$(!1)},onCancel:()=>$(!1)})]}):f.jsxs(f.Fragment,{children:[Ve.size>0&&f.jsx("div",{className:"amx-props-empty",children:o("amprops.pluginKeysWarn",{keys:[...Ve].join(", ")})}),f.jsx(Hh,{text:p,readOnly:n,onCommit:de})]}))]})}function Hh({text:e,readOnly:t,onCommit:n}){const{t:r}=Zt(),o=c=>{t||n(c)},s=mc(e,o,{escDiscards:"never"});return f.jsx("textarea",{className:`amx-props-raw${s.conflict?" amx-prop-conflict":""}`,value:s.shown,spellCheck:!1,readOnly:t,title:s.conflict?r("amprops.conflictRaw"):void 0,onChange:c=>{t||s.change(c.target.value)},onBlur:()=>{const c=s.settle();c!==null&&o(c)}})}function Vh({name:e,onRename:t}){const n=mc(e,t,{norm:r=>r.trim(),enterCommits:!0});return f.jsx("input",{className:"amx-prop-key",value:n.shown,onChange:r=>n.change(r.target.value),onKeyDown:n.onKeyDown,onBlur:()=>{const r=n.settle();r!==null&&t(r)}})}function Wh({value:e}){return typeof e=="boolean"?f.jsx("span",{className:"amx-prop-check","aria-hidden":!0,children:e?"☑":"☐"}):Bl(e)?f.jsx("span",{className:"amx-prop-chips",children:e.map((t,n)=>f.jsx("span",{className:"amx-chip",children:String(t??"")},n))}):e==null?f.jsx("span",{className:"amx-prop-input"}):typeof e=="object"?f.jsx("span",{className:"amx-prop-input",children:JSON.stringify(e)}):f.jsx("span",{className:"amx-prop-input",children:String(e)})}function Yh({onAdd:e,onCancel:t}){const{t:n}=Zt(),[r,o]=v.useState(""),[s,c]=v.useState("text"),[a,i]=v.useState(!1),d=a?s:Kh(r);return f.jsxs("div",{className:"amx-prop-row amx-prop-new",children:[f.jsx("input",{className:"amx-prop-key",autoFocus:!0,value:r,placeholder:n("amprops.keyPlaceholder"),"aria-label":n("amprops.addLabel"),onChange:p=>o(p.target.value),onKeyDown:p=>{p.nativeEvent.isComposing||p.keyCode===229||(p.key==="Enter"?(p.preventDefault(),e(r,d)):p.key==="Escape"&&(p.preventDefault(),t()))}}),f.jsx("select",{className:"amx-prop-type","aria-label":n("amprops.type"),value:d,onChange:p=>{c(p.target.value),i(!0)},onKeyDown:p=>{p.key==="Escape"&&(p.preventDefault(),t())},children:_h.map(p=>f.jsx("option",{value:p,children:n(`amprops.type.${p}`)},p))}),f.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addConfirm"),"aria-label":n("amprops.addConfirm"),onClick:()=>e(r,d),children:f.jsx(ea,{size:12})}),f.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addCancel"),"aria-label":n("amprops.addCancel"),onClick:t,children:f.jsx(cc,{size:12})})]})}function ql({text:e,onOpenLink:t}){const n=[],r=/\[\[([^\]\n]+)\]\]/g;let o=0,s;for(;s=r.exec(e);){s.index>o&&n.push(e.slice(o,s.index));const c=s[1],a=c.indexOf("|");n.push(f.jsx("span",{className:"amx-prop-link",onMouseDown:i=>{i.preventDefault(),i.stopPropagation(),t(c)},onClick:i=>i.stopPropagation(),children:a>=0?c.slice(a+1):c},s.index)),o=s.index+s[0].length}return o<e.length&&n.push(e.slice(o)),f.jsx(f.Fragment,{children:n})}function Xh({value:e,onCommit:t,onOpenLink:n}){const{t:r}=Zt(),[o,s]=v.useState(!1);return o?f.jsx(Za,{current:e,autoFocus:!0,onCommit:t,onDone:()=>s(!1)}):f.jsx("div",{className:"amx-prop-input amx-prop-links",tabIndex:0,title:r("amprops.linksHint"),onClick:()=>s(!0),onKeyDown:c=>{c.key==="Enter"&&!c.nativeEvent.isComposing&&(c.preventDefault(),s(!0))},children:f.jsx(ql,{text:e,onOpenLink:n})})}function Uh({value:e,onCommit:t,onOpenLink:n}){const{t:r}=Zt();return typeof e=="boolean"?f.jsx("input",{type:"checkbox",className:"amx-prop-check",checked:e,onChange:o=>t(o.target.checked)}):Bl(e)?f.jsx(Jh,{items:e.map(o=>String(o??"")),onCommit:t,onOpenLink:n}):typeof e=="number"?f.jsx(Za,{current:String(e),norm:o=>o.trim(),onCommit:o=>{const s=Number(o);t(o!==""&&!Number.isNaN(s)?s:o)}}):typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?f.jsx(Gh,{value:e,onCommit:t}):typeof e=="string"&&!e.includes(`
13
- `)&&_l(e)?f.jsx(Xh,{value:e,onCommit:t,onOpenLink:n}):typeof e=="string"||e==null?f.jsx(Za,{current:e??"",multiline:typeof e=="string"&&e.includes(`
14
- `),onCommit:t}):f.jsx("span",{className:"amx-prop-nested",title:r("amprops.nestedHint"),children:Pu(e).trimEnd()})}function Za({current:e,norm:t,multiline:n=!1,autoFocus:r,onCommit:o,onDone:s}){const{t:c}=Zt(),a=mc(e,o,{norm:t,enterCommits:!n}),i={className:`amx-prop-input${n?" amx-prop-multiline":""}${a.conflict?" amx-prop-conflict":""}`,value:a.shown,title:a.conflict?c("amprops.conflict",{v:e}):void 0,autoFocus:r,onKeyDown:a.onKeyDown,onBlur:()=>{const d=a.settle();d!==null&&o(d),s?.()}};return n?f.jsx("textarea",{...i,rows:Math.min(8,a.shown.replace(/\n$/,"").split(`
15
- `).length),spellCheck:!1,onChange:d=>a.change(d.target.value)}):f.jsx("input",{...i,onChange:d=>a.change(d.target.value)})}function Gh({value:e,onCommit:t}){const[n,r]=v.useState(!1);return f.jsx("input",{type:"date",className:"amx-prop-input",value:n?"":e,onChange:o=>{const s=o.target.value;r(!s),s&&s!==e&&t(s)},onBlur:()=>r(!1)})}function Jh({items:e,onCommit:t,onOpenLink:n}){const{t:r}=Zt(),[o,s]=v.useState(""),c=()=>{const i=o.trim();s(""),i&&!e.includes(i)&&t([...e,i])},a=i=>{i.nativeEvent.isComposing||i.keyCode===229||(i.key==="Enter"||i.key===","?(i.preventDefault(),c()):i.key==="Backspace"&&!o&&e.length&&t(e.slice(0,-1)))};return f.jsxs("div",{className:"amx-prop-chips",children:[e.map((i,d)=>f.jsxs("span",{className:"amx-chip",children:[n&&_l(i)?f.jsx(ql,{text:i,onOpenLink:n}):i,f.jsx("button",{className:"amx-chip-x",onClick:()=>t(e.filter((p,g)=>g!==d)),children:f.jsx(cc,{size:10})})]},`${d}:${i}`)),f.jsx("input",{value:o,placeholder:e.length?"":r("amprops.chipsPlaceholder"),onChange:i=>s(i.target.value),onKeyDown:a,onBlur:c})]})}const Zh=new Set(["bullet","ordered","task"]);function Qh(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 Hl(e,t,n,r){if(r.kind!=="quote"&&r.kind!=="fold"){const a=e.state.tr,i=a.doc.content.size;e.state.doc.nodesBetween(t,n,(d,p)=>d.type.name==="blockquote"?(Wl(a,a.mapping.map(p)),!1):!d.isTextblock),a.docChanged&&(e.dispatch(a),n+=a.doc.content.size-i)}const o=[];e.state.doc.nodesBetween(t,n,(a,i)=>a.isTextblock?(o.push(i+1),!1):!0);const s=e.state.doc.content.size;let c=!1;for(const a of o.reverse())e.dispatch(e.state.tr.setSelection(Pe.near(e.state.doc.resolve(a)))),Qs(e,r,null)&&(c=!0);return c&&Zh.has(r.kind)&&eg(e,t,n+(e.state.doc.content.size-s)),c}function eg(e,t,n){const{doc:r}=e.state,o=r.resolve(t),s=o.parent,c=[];let a=o.start();for(let d=0;d<o.index();d++)a+=s.child(d).nodeSize;for(let d=o.index();d<s.childCount-1;d++){const p=s.child(d);if(a+=p.nodeSize,a>=n)break;const g=s.child(d+1);p.type===g.type&&/_list$/.test(p.type.name)&&c.push(a)}if(!c.length)return;const i=e.state.tr;for(const d of c.reverse())af(i.doc,d)&&i.join(d);i.docChanged&&e.dispatch(i)}function Qa(e,t,n){const{state:r}=e,o=r.schema.nodes.code_block;if(!o)return!1;const s=r.doc.resolve(t),c=r.doc.resolve(n);if(s.parent!==c.parent||!s.parent.canReplaceWith(s.index(),c.index(),o))return!1;const a=r.doc.textBetween(t,n,`
16
- `,`
17
- `).replace(/^\n+|\n+$/g,""),i=r.tr.replaceWith(t,n,o.create(null,a?r.schema.text(a):void 0));return i.setSelection(Pe.near(i.doc.resolve(t+1))),e.dispatch(i.scrollIntoView()),!0}const tg=/^\[![\w-]+\]/;function zi(e,t,n,r){const o=e.state.schema.nodes.blockquote;if(!o)return!1;let s;const c=e.state.doc.nodeAt(t);if(c?.type===o&&t+c.nodeSize===n)s=t;else if(r){const d=e.state.doc.resolve(t).blockRange(e.state.doc.resolve(n)),p=d&&sf(d,o);if(!d||!p)return!1;e.dispatch(e.state.tr.wrap(d,p)),s=t}else{if(e.dispatch(e.state.tr.setSelection(Pe.near(e.state.doc.resolve(t+1)))),!Qs(e,{kind:"quote"},null))return!1;const d=e.state.selection.$from;let p=d.depth;for(;p>0&&d.node(p).type!==o;)p--;if(p<1)return!1;s=d.before(p)}const a=e.state.doc.nodeAt(s),i=a?.firstChild;return!a||a.type!==o||!i?.isTextblock||tg.test(i.textContent)?!!a:(e.dispatch(e.state.tr.insertText(i.content.size?"[!note] ":"[!note]",s+2)),!0)}const Vl=/^\[![\w-]+\]([+-])?[ \u00a0]?/;function Wl(e,t){const n=e.doc.nodeAt(t),r=n?.firstChild,o=n?.type.name==="blockquote"&&r?.isTextblock?Vl.exec(r.textContent):null;return!n||!r||!o?!1:(r.content.size===o[0].length&&n.childCount>1?e.delete(t+1,t+1+r.nodeSize):e.delete(t+2,t+2+o[0].length),!0)}function Ni(e,t,n,r){const o=e.state.doc.nodeAt(t),s=o?.firstChild,c=o?.type.name==="blockquote"&&t+o.nodeSize===n&&s?.isTextblock?Vl.exec(s.textContent):null;if(!o||!s||!c)return null;const a=e.state.tr;if(r!=="code"&&r.kind==="fold"){if(/^\[!fold\]/i.test(s.textContent))return!0;const C=c[0].length-(/[ \u00a0]$/.test(c[0])?1:0);return a.replaceWith(t+2,t+2+C,e.state.schema.text(id)),e.dispatch(a.scrollIntoView()),!0}if(Wl(a,t),r!=="code"&&r.kind==="quote")return a.setSelection(Pe.near(a.doc.resolve(t+1))),e.dispatch(a.scrollIntoView()),!0;const i=a.doc.nodeAt(t),d=i.content.size,p=a.doc.resolve(t+1).blockRange(a.doc.resolve(t+i.nodeSize-1)),g=p?of(p):null;return!p||g==null?!1:(a.lift(p,g),a.setSelection(Pe.near(a.doc.resolve(t+1))),e.dispatch(a.scrollIntoView()),r==="code"?Qa(e,t,t+d):r.kind==="text"?!0:r.kind==="heading"?Qs(e,r,null):Hl(e,t,t+d,r))}function ng(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 qo(e){const t=ng(e);return{text:t===`\r
22
- `?e.replace(/\r\n/g,`
23
- `):e,eol:t}}function Ir(e,t){return t===`\r
24
- `?e.replace(/\r?\n/g,`\r
25
- `):e}function ds(e,t,n){let r=n,o;try{o=e.doc.resolve(t)}catch{return n}const s=o.parent;let c=t;for(let a=o.index();a<s.childCount&&c<r;a++){const i=s.child(a);if(i.type.name==="heading"){const d=Xo(e,c);d!=null&&d>r&&(r=d)}c+=i.nodeSize}return r}function _o(e,t,n){for(const r of[Yo,$m]){const o=r.getState(e)?.folded;if(!o?.length)continue;const s=[];for(const c of o){const a=c>=n.from&&c<n.to;(!a||n.copy)&&s.push(t.mapping.map(c)),a&&!n.drop&&n.newStart!=null&&s.push(n.newStart+(c-n.from))}t.setMeta(r,{set:s})}}function Zo(e,t,n){const r=t.getMeta(Yo)?.set;if(!r?.length)return;const o=mi(e.doc,Yo.getState(e)?.folded??[]),s=d=>o.some(p=>d>=p.start&&d<p.after),c=n.to-n.from,a=t.mapping.invert(),i=r.filter(d=>mi(t.doc,[d]).every(p=>{const g=t.doc.resolve(p.start),C=g.parent;let I=p.start;for(let N=g.index();N<C.childCount&&I<p.after;N++){const k=I;I+=C.child(N).nodeSize;const $=k>=n.newStart&&k<n.newStart+c?n.from+(k-n.newStart):a.map(k);if(!s($))return!1}return!0}));i.length!==r.length&&t.setMeta(Yo,{set:i})}yn({"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 Fr=e=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:e}}))},pc=e=>(e.split("/").pop()??e).replace(/\.md$/i,""),Qo=e=>e.split("/").slice(0,-1).join("/");function rg(e){const t=[];for(const n of e.split("/"))!n||n==="."||(n===".."&&t.length&&t[t.length-1]!==".."?t.pop():t.push(n));return t.join("/")}function og(e,t){const n=e?e.split("/"):[],r=t.split("/");let o=0;for(;o<n.length&&o<r.length-1&&n[o]===r[o];)o++;return[...n.slice(o).map(()=>".."),...r.slice(o)].join("/")}function sg(e,t,n){return t===n?e:Hu(e,r=>r.replace(/(^|[^!])\[([^\]\n]*)\]\(([^)\s]+)((?:\s+"[^"]*")?)\)/g,(o,s,c,a,i)=>{if(/^(?:[a-z][a-z0-9+.-]*:|\/|#|<)/i.test(a))return o;const[d,p=""]=a.split(/(?=#)/);return`${s}[${c}](${og(n,rg(bl(t,d)))}${p}${i})`}))}function ag(e){let t=null;for(const n of e.split(`
26
- `)){const r=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(n);r&&(t?r[1][0]===t[0]&&r[1].length>=t.length&&!r[2].trim()&&(t=null):t=r[1])}return t!=null||e.lastIndexOf("<!--")>e.lastIndexOf("-->")}function cg(e,t){const{text:n,eol:r}=qo(e),o=n?n.endsWith(`
27
-
28
- `)?"":n.endsWith(`
29
- `)?`
30
- `:`
31
-
32
- `:"";return Ir(`${n}${o}${t}
33
- `,r)}function ig(e,t){const n=pc(e);return hs(n,t)===e?n:e.replace(/\.md$/i,"")}function lg(e,t,n){const r=ig(t,n);if(e.type.name==="heading"){const s=ld(e.textContent);return s?{kind:"heading",link:`[[${r}#${s}]]`}:null}const o=xl(e.textContent);return o?{kind:"block",link:`[[${r}#^${o}]]`}:null}function ug(e){const t=navigator.clipboard?.writeText(e);if(!t){Fr(Ce("blocklinks.copyFailed"));return}t.then(()=>Fr(Ce("blocklinks.copied",{link:e})),()=>Fr(Ce("blocklinks.copyFailed")))}function dg(e){let t=!0;return e.descendants(n=>(/^amadeus(CanvasCard|ColumnRow|ColumnCell)$/.test(n.type.name)&&(t=!1),t)),t}async function fg(e){const{view:t,from:n,to:r,source:o,target:s}=e,c=pc(s);if(s===o)return!1;const a=t.state.doc.slice(n,r).content,i=e.serialize(a);if(!i?.trim())return Fr(Ce("blocklinks.moveFailed",{name:c})),!1;let d=sg(Oo(i,Qo(s)).trim(),Qo(o),Qo(s));e.pages&&Qo(o)!==Qo(s)&&(d=Ou(d,o,s,{pairs:new Map,pagesBefore:e.pages,pagesAfter:e.pages}));try{if(_u(s)){if(!Bu(s,d,"end"))throw new Error("insert refused");try{await Ku(s,!0)}catch{return Fr(Ce("blocklinks.targetUnsaved",{name:c})),!1}}else{const g=await vn.readTextFile(s);if(g==null)throw new Error("missing");if(ag(qo(g).text))throw new Error("unsafe tail");const C=await vn.writeTextFile(s,cg(g,d),{base:So(g)});if(C&&!C.ok)return Fr(Ce("blocklinks.moveConflict",{name:c})),!1}}catch{return Fr(Ce("blocklinks.moveFailed",{name:c})),!1}if(t.isDestroyed||r>t.state.doc.content.size||!t.state.doc.slice(n,r).content.eq(a))return Fr(Ce("blocklinks.keptSource",{name:c})),!0;const p=t.state.tr.delete(n,r);return _o(t.state,p,{from:n,to:r,drop:!0}),t.dispatch(p.scrollIntoView()),Fr(Ce("blocklinks.moved",{name:c})),!0}function Yl({pages:e,exclude:t,onPick:n,onClose:r}){const{t:o}=Zt(),[s,c]=v.useState(""),[a,i]=v.useState(0),d=th(s,e.filter(p=>p!==t&&/\.md$/i.test(p)),qu).slice(0,30);return v.useEffect(()=>{i(0)},[s]),zl.createPortal(f.jsx("div",{className:"cmd-overlay",onMouseDown:r,children:f.jsxs("div",{className:"cmd-panel",role:"dialog","aria-label":o("blocklinks.pickTitle"),"data-testid":"note-picker",onMouseDown:p=>p.stopPropagation(),children:[f.jsx("input",{className:"cmd-input",autoFocus:!0,placeholder:o("blocklinks.pickPlaceholder"),"aria-label":o("blocklinks.pickTitle"),value:s,onChange:p=>c(p.target.value),onKeyDown:p=>{p.key==="ArrowDown"?(p.preventDefault(),i(g=>Math.min(g+1,d.length-1))):p.key==="ArrowUp"?(p.preventDefault(),i(g=>Math.max(g-1,0))):p.key==="Enter"?(p.preventDefault(),d[a]&&n(d[a])):p.key==="Escape"&&(p.preventDefault(),p.stopPropagation(),r())}}),f.jsxs("div",{className:"cmd-list",role:"listbox",children:[d.map((p,g)=>f.jsx("button",{className:"cmd-item",role:"option","aria-selected":g===a,"data-active":g===a||void 0,onMouseEnter:()=>i(g),onClick:()=>n(p),children:f.jsxs("span",{className:"cmd-row",children:[f.jsx("span",{className:"cmd-title",children:pc(p)}),f.jsx("span",{className:"cmd-path",children:p})]})},p)),!d.length&&f.jsx("div",{className:"cmd-empty",children:o("blocklinks.noMatch")})]})]})}),document.body)}function mg(e){return e.nodeType===1}function pg(e){return mg(e)&&e.namespaceURI==="http://www.w3.org/1999/xhtml"}function hg(e){const t=[[-1,e.state.doc]],n=[];for(;t.length>0;){const[r,o]=t.pop();if(r>=0){const s=e.nodeDOM(r);if(s&&pg(s)){const{top:c,bottom:a,left:i,right:d}=s.getBoundingClientRect();n.push([r,[i,c,d,c]],[r+o.nodeSize,[i,a,d,a]])}}if(o.isBlock&&!o.isTextblock){let s=r+1;for(const c of o.children)t.push([s,c]),s+=c.nodeSize}}return n}function gg(e,t){let n=[],r,o;const s=()=>{const p=e.dom.getBoundingClientRect(),g=e.state.doc;return n&&r&&o&&p.width===o.width&&p.height===o.height&&p.x===o.x&&p.y===o.y&&r.eq(g)||(o=p,r=g,n=hg(e)),n},c=(p,g)=>{if(!e.editable||e.isDestroyed)return;const C=(k,$)=>{const[F,J]=k,[oe,H]=$;return $i(p,J)-$i(p,H)||F-oe};let I=s();I.sort(C),I=I.slice(0,8);const N=I.find(k=>t?.({view:e,pos:k[0],event:g})!==!1);if(!(N&&xg(e,N[0])))return N};let a,i;return(p,g)=>(a&&yg(a,p)||(a=p,i=c(p,g)),i)}function yg(e,t){return e[0]===t[0]&&e[1]===t[1]}function Ai(e,t){return Math.abs(e[0]-t[0])+Math.abs(e[1]-t[1])}function $i(e,t){return Math.min(Ai(e,[t[0],t[1]]),Ai(e,[t[2],t[3]]))}function xg(e,t){const n=e.dragging;if(!n)return;const{move:r}=n;if(!r)return;const o=e.state.selection;if(!(o instanceof ze))return;const{from:s,to:c}=o;return s<=t&&t<=c}function bg(e){let t;return new Ht({key:new jn("prosemirror-drop-indicator"),view:n=>(t=gg(n,e.onDrag),wg(n,t,e)),props:{handleDrop(n,r,o,s){if(!t)return!1;const c=t([r.clientX,r.clientY],r);if(!c)return!1;r.preventDefault();const a=c[0],i=n.state.tr;if(s){const{node:I}=n.dragging||{};I?I.replace(i):i.deleteSelection()}const d=i.mapping.map(a),p=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,g=i.doc;if(p?i.replaceRangeWith(d,d,o.content.firstChild):i.replaceRange(d,d,o),i.doc.eq(g))return!0;const C=i.doc.resolve(d);if(p&&ze.isSelectable(o.content.firstChild)&&C.nodeAfter&&C.nodeAfter.sameMarkup(o.content.firstChild))i.setSelection(new ze(C));else{let I=i.mapping.map(a);i.mapping.maps[i.mapping.maps.length-1].forEach((N,k,$,F)=>I=F),i.setSelection(vg(n,C,i.doc.resolve(I)))}return n.focus(),n.dispatch(i.setMeta("uiEvent","drop")),!0}}})}function vg(e,t,n,r){return e.someProp("createSelectionBetween",o=>o(e,t,n))||Pe.between(t,n,r)}function wg(e,t,n){const r=e.dom;let o,s,c,a=!1;const i=()=>{o&&clearTimeout(o),a=!1,o=setTimeout(()=>{a||n.onHide?.()},30)},d=g=>{a=!0;const{clientX:C,clientY:I}=g;if(s===C&&c===I)return;s=C,c=I;const N=t([C,I],g);if(N){const[k,[$,F,J,oe]]=N,H={p1:{x:$,y:F},p2:{x:J,y:oe}};n.onShow?.({view:e,pos:k,line:H})}else{i();return}};return r.addEventListener("dragover",d),r.addEventListener("dragend",i),r.addEventListener("drop",i),r.addEventListener("dragleave",i),{destroy:()=>{r.removeEventListener("dragover",d),r.removeEventListener("dragend",i),r.removeEventListener("drop",i),r.removeEventListener("dragleave",i)}}}yn({"canvasedit.textDefault":{zh:"文本",en:"Text"}});function _r(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.id;return typeof t=="string"&&t?t:null}function Ti(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t?t:null}function Lr(e){return Array.isArray(e)?[...e]:[]}function Xl(e,t,n){return e.map(r=>_r(r)===t?{...r,...n}:r)}function kg(e,t){const n=new Set,r=e.filter(o=>{const s=_r(o);return s&&t.has(s)?(n.add(s),!1):!0});return n.size?r.filter(o=>{if(!o||typeof o!="object"||o.type!=="connector")return!0;const s=o,c=Ti(s.from),a=Ti(s.to);return!(c&&n.has(c)||a&&n.has(a))}):r}function ji(e,t,n,r){return e.map(o=>{const s=_r(o);if(!s||!t.has(s))return o;const c=o;return typeof c.x!="number"||typeof c.y!="number"?o:{...c,x:Math.round(c.x+n),y:Math.round(c.y+r)}})}function fs(e,t){const n=new Set;for(const r of e){const o=_r(r);o&&n.add(o)}for(let r=1;;r++){const o=`${t}${r}`;if(!n.has(o))return o}}const he="m:",Cg={rect:{w:200,h:120},ellipse:{w:180,h:120},text:{w:180,h:40}},Ri={w:480,h:320};function Ul(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:Ce("canvasedit.textDefault")}:{}}}function Sg(e,t,n,r){const o=Cg[t];return Ul(e,t,{x:n-o.w/2,y:r-o.h/2,w:o.w,h:o.h})}function ec(e){return e==="m:"?{main:!0}:e.startsWith("c:")?{ref:e.slice(2)}:e.startsWith("e:")?{id:e.slice(2)}:null}function Eg(e,t,n){if(t===n)return e;const r=ec(t),o=ec(n);if(!r||!o)return e;const s=(a,i)=>{const d=i;return!!d&&d.ref===a.ref&&d.id===a.id};return e.some(a=>{if(!a||typeof a!="object"||a.type!=="connector")return!1;const i=a;return s(r,i.from)&&s(o,i.to)||s(r,i.to)&&s(o,i.from)})?e:[...e,{id:fs(e,"e"),type:"connector",from:r,to:o}]}const ms={fromEnd:"none",toEnd:"arrow"};function Mg(e,t,n){let r=!1;const o=e.map(s=>{const c=_r(s);if(!c||!t.has(c)||s.type!=="connector")return s;const a=s;let i=null;for(const d of["fromEnd","toEnd"]){const p=n[d];if(p==null)continue;const g=p===ms[d];(g?!(d in a):a[d]===p)||(i??={...a},g?delete i[d]:i[d]=p)}return i?(r=!0,i):s});return r?o:e}const Io=(e,t)=>{if(!e||!t||typeof e!="object"||typeof t!="object")return!1;const n=e,r=t;return typeof n.ref=="string"||typeof r.ref=="string"?n.ref===r.ref:typeof n.id=="string"||typeof r.id=="string"?n.id===r.id:n.main===!0&&r.main===!0};function zg(e,t,n,r){const o=ec(r);if(!o)return e;const s=e.find(i=>_r(i)===t);if(!s||s.type!=="connector")return e;const c=n==="from"?s.to:s.from;return Io(o,s[n])||Io(o,c)||e.some(i=>{if(_r(i)===t||!i||typeof i!="object"||i.type!=="connector")return!1;const d=i;return Io(o,d.from)&&Io(c,d.to)||Io(o,d.to)&&Io(c,d.from)})?e:Xl(e,t,{[n]:o})}function Ng(e,t,n,r){return e.map(o=>{if(_r(o)!==t)return o;const s={...o};return r?s[n]=r:delete s[n],s})}function Kt(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 Bo(e,t,n){if(!t||!n||t===n)return e;let r=n;const o=new Set([t]);for(;typeof r=="string"&&r;){if(o.has(r))return e;o.add(r),r=e[r]}const s=Kt(e);return s[t]=n,s}function Ag(e,t){if(!t.size)return e;const n=Object.create(null);for(const r of Object.keys(e)){if(t.has(r))continue;let o=e[r];const s=new Set;for(;typeof o=="string"&&t.has(o)&&!s.has(o);)s.add(o),o=e[o];typeof o!="string"||!o||t.has(o)||o===r||(n[r]=o)}return n}const wo=(e,t)=>Object.keys(e).filter(n=>e[n]===t).sort();function Gl(e,t,n,r){if(!t||!n||t===n)return!1;const o=new Set([t]);let s=e[t];for(;typeof s=="string"&&s&&!o.has(s)&&(!r||r.has(s));){if(s===n)return!0;o.add(s),s=e[s]}return!1}function $g(e,t,n,r=6){let o=0;const s=new Set([t]);let c=e[t];for(;typeof c=="string"&&c&&n.has(c)&&!s.has(c)&&o<r;)o++,s.add(c),c=e[c];return o}function Us(e,t,n){const r=new Set(e.map(s=>s.anchor));let o=t+1;for(;o<e.length&&e[o].idx===e[o-1].idx+1&&Gl(n,e[o].anchor,e[t].anchor,r);)o++;return o}function Tg(e,t,n,r,o,s){return{id:e,type:"frame",x:Math.round(t),y:Math.round(n),w:Math.round(r),h:Math.round(o)}}const jg=/^(?:[1-6]|#[0-9a-fA-F]{6})$/;function ta(e){return typeof e!="string"||!jg.test(e)?null:e.length===1?`var(--amx-cv-${e})`:e}function Rg(e,t,n){let r=!1;const o=e.map(s=>{const c=_r(s);if(!c||!t.has(c))return s;const a=s;if(n?a.color===n:!("color"in a))return s;r=!0;const i={...a};return n?i.color=n:delete i.color,i});return r?o:e}const hc=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/;function Sa(e){if(!e)return null;try{const n=JSON.parse(e);if(!n||n.v!==4||!Array.isArray(n.rows))return null;for(const r of n.rows){if(!r||!Array.isArray(r.columns)||r.columns.length<1||r.tail!=null&&(typeof r.tail!="string"||!/^[A-Za-z0-9_-]+$/.test(r.tail)))return null;for(const o of r.columns)if(!o||!Array.isArray(o.refs)||o.refs.length<1||!o.refs.every(s=>typeof s=="string"&&/^[A-Za-z0-9_-]+$/.test(s))||typeof o.width!="number"||!Number.isFinite(o.width)||o.width<=0)return null}return n}catch{return null}}function Er(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 r=hc.exec(String(n.attrs.value??"").trim());r&&t.add(r[1])}});;){const n="c"+Math.random().toString(36).slice(2,6);if(!t.has(n))return n}}function es(e,t){const n=[],r=[];return t.forEach(o=>{if(o.type.name==="amadeusCanvasCard"){let s=Er(e);for(;n.includes(s);)s=Er(e);n.push(s),r.push(o.type.create({...o.attrs,anchor:s},o.content,o.marks))}else r.push(o)}),n.length?{content:Sr.fromArray(r),minted:n}:{content:t,minted:n}}const Dg=lc("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} -->`)}}})),Lg=lc("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 Ig(e,t,n){if(!t?.rows?.length)return;const r=Array.isArray(e?.children)?e.children:[];if(r.length&&!r.some(d=>d?.position))return;const o=d=>{let p=null;if(d?.type==="html"&&typeof d.value=="string")p=d.value;else if(d?.type==="paragraph"&&Array.isArray(d.children)&&d.children.length===1){const C=d.children[0];C?.type==="html"&&typeof C.value=="string"&&(p=C.value)}if(p==null)return null;const g=hc.exec(p.trim());return g?g[1]:null},s=[];if(r.forEach((d,p)=>{const g=o(d);g&&s.push({id:g,idx:p})}),!s.length)return;const c=new Map;s.forEach((d,p)=>{c.has(d.id)?c.set(d.id,-1):c.set(d.id,p)});const a=new Set,i=[];for(const d of t.rows){if(d.columns.length<2)continue;const p=d.columns.flatMap(F=>F.refs);if(!p.length)continue;const g=p.map(F=>c.get(F)??-1);if(g.some(F=>F<0||a.has(F))||new Set(g).size!==g.length||!g.every((F,J)=>J===0||F===g[J-1]+1))continue;const C=g[g.length-1],I=d.tail!=null&&C+1<s.length&&s[C+1].id===d.tail&&!a.has(C+1)?C+1:null,N=I!=null?s[I].idx:C+1<s.length?s[C+1].idx:r.length,k=[];let $=!0;d.columns.forEach((F,J)=>{const oe=c.get(F.refs[0]),H=s[oe].idx+1,te=J+1<d.columns.length?c.get(d.columns[J+1].refs[0]):null,Re=te!=null?s[te].idx:N;if(Re<H){$=!1;return}const Ve=r.slice(H,Re);k.push({type:"amadeusColumnCell",anchor:F.refs[0],width:F.width||1,children:Ve.length?Ve:[{type:"paragraph",children:[]}]})}),!(!$||k.length<2)&&(g.forEach(F=>a.add(F)),I!=null&&a.add(I),i.push({from:s[g[0]].idx,to:I!=null?s[I].idx+1:N,node:{type:"amadeusColumnRow",tail:I!=null?d.tail:"",children:k}}))}i.sort((d,p)=>p.from-d.from);for(const d of i)r.splice(d.from,d.to-d.from,d.node);i.length&&n?.()}function Pg(e,t){return[Tl("amadeusColumnsFold",()=>()=>n=>{Ig(n,e(),t)})].flat()}function Fg(e){const t=[String(e.attrs.anchor)];return e.forEach(n=>{if(n.type.name!=="paragraph"||n.childCount!==1)return;const r=n.firstChild;if(r.type.name!=="html")return;const o=hc.exec(String(r.attrs.value??"").trim());o&&t.push(o[1])}),t}function Og(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusColumnRow")return;const r=[];n.forEach(o=>{r.push({refs:Fg(o),width:Number(o.attrs.width)||1})}),r.length>=2&&t.push({columns:r,...n.attrs.tail?{tail:String(n.attrs.tail)}:{}})}),t.length?JSON.stringify({v:4,rows:t}):null}const gc=e=>e.childCount===1&&e.firstChild.type.name==="paragraph"&&e.firstChild.content.size===0;function Gs(e,t){const{paragraph:n,html:r}=e.nodes;return t&&n&&r?[n.create(null,r.create({value:`<!-- a ${t} -->`}))]:[]}function yc(e,t,n,r=!1){const o=[];for(const s of t)o.push(...Gs(e,String(s.attrs.anchor))),r&&gc(s)||s.forEach(c=>o.push(c));return o.push(...Gs(e,n)),o}const _g=St(()=>new Ht({key:new jn("AMX_COLUMNS_NORMALIZE"),appendTransaction:(e,t,n)=>{if(!e.some(i=>i.docChanged))return null;const r=e.some(i=>(i.getMeta("uiEvent")==="drop"||i.getMeta("amxColumns"))&&!i.getMeta("amxColumnsKeepEmpty")),{paragraph:o}=n.schema.nodes,s=i=>Gs(n.schema,i),c=[];if(n.doc.descendants((i,d,p)=>{if(i.type.name==="amadeusColumnRow"&&p?.type.name==="amadeusColumnCell"){const g=[];return i.forEach(C=>C.forEach(I=>g.push(I))),c.push({from:d,to:d+i.nodeSize,content:g.length?g:[o.create()]}),!1}return!0}),n.doc.forEach((i,d)=>{if(i.type.name!=="amadeusColumnRow")return;const p=[];i.forEach($=>p.push($));const g=r?p.filter($=>!gc($)):p,C=g.some($=>!$.attrs.anchor);if(g.length===p.length&&g.length>=2&&!C)return;const I=new Set;n.doc.descendants($=>{$.type.name==="amadeusColumnCell"&&$.attrs.anchor&&I.add(String($.attrs.anchor)),$.type.name==="amadeusColumnRow"&&$.attrs.tail&&I.add(String($.attrs.tail))});const N=$=>{if($.attrs.anchor)return $;let F="c"+Math.random().toString(36).slice(2,6);for(;I.has(F);)F="c"+Math.random().toString(36).slice(2,6);return I.add(F),$.type.create({...$.attrs,anchor:F},$.content)},k=p.filter($=>!g.includes($)).flatMap($=>s(String($.attrs.anchor)));if(g.length>=2)c.push({from:d,to:d+i.nodeSize,content:[i.type.create(i.attrs,g.map(N)),...k]});else{const $=[...k,...yc(n.schema,g,String(i.attrs.tail??""))];c.push({from:d,to:d+i.nodeSize,content:$.length?$:[o.create()]})}}),!c.length)return null;let a=n.tr;for(const i of c.sort((d,p)=>p.from-d.from))a=a.replaceWith(i.from,i.to,i.content);return a}}));function Bg(e,t,n,r=!1){const{state:o}=e,s=o.selection;if(!(s instanceof ze))return!1;const c=s.node;if(c.type.name==="amadeusColumnRow"||c.type.name==="amadeusColumnCell"||c.type.name==="amadeusCanvasCard"||o.doc.nodeAt(t)?.type.name==="amadeusCanvasCard"||t>=s.from&&t<s.to)return!1;const a=o.schema.nodes.amadeusColumnRow,i=o.schema.nodes.amadeusColumnCell;if(!a||!i)return!1;const d=c.type.name==="list_item"?s.$from.parent.type.create(s.$from.parent.attrs,c):c,p=o.doc.resolve(t);let g=null;if(p.depth>0){let F=-1;for(let J=p.depth;J>=1;J--)if(p.node(J).type===a){F=J;break}if(F<0||F!==1)return!1;g={rowPos:p.before(F),cellIndex:p.index(F)}}const C=new Set,I=()=>{let F=Er(o.doc);for(;C.has(F);)F=Er(o.doc);return C.add(F),F},N=I(),k=I();let $=o.tr;if(r||($=$.delete(s.from,s.to)),g){const F=$.mapping.map(g.rowPos),J=$.doc.nodeAt(F);if(!J||J.type!==a)return!1;const oe=n==="left"?g.cellIndex:g.cellIndex+1;let H=F+1;for(let te=0;te<Math.min(oe,J.childCount);te++)H+=J.child(te).nodeSize;$=$.insert(H,i.create({anchor:k,width:1},d))}else{const F=$.mapping.map(t),J=$.doc.nodeAt(F);if(!J)return!1;const oe=n==="left"?[i.create({anchor:k,width:1},d),i.create({anchor:N,width:1},J)]:[i.create({anchor:N,width:1},J),i.create({anchor:k,width:1},d)];$=$.replaceWith(F,F+J.nodeSize,a.create({tail:I()},oe))}return $.setMeta("amxColumns",!0),e.dispatch($.scrollIntoView()),!0}function Kg(e,t,n=!1){const{state:r}=e,o=r.selection;if(!(o instanceof ze))return!1;const s=o.node;if(s.type.name==="amadeusColumnRow"||s.type.name==="amadeusColumnCell")return!1;const c=r.doc.nodeAt(t);if(!c||c.type.name!=="amadeusColumnRow"||!n&&o.from===t+c.nodeSize)return!1;const a=s.type.name==="list_item"?o.$from.parent.type.create(o.$from.parent.attrs,s):s;let i=r.tr;return n||(i=i.delete(o.from,o.to)),i=i.insert(i.mapping.map(t+c.nodeSize),a),i.setMeta("amxColumns",!0),e.dispatch(i.scrollIntoView()),!0}function qg(e,t,n=!1){const{state:r}=e,o=r.selection;if(!(o instanceof ze))return!1;const s=o.node;if(s.type.name==="amadeusColumnRow"||s.type.name==="amadeusColumnCell"||s.type.name==="amadeusCanvasCard")return!1;const c=r.doc.resolve(t),a=c.parent;if(a.type.name!=="amadeusColumnCell")return!1;if(!n&&t>=o.from&&t<=o.to)return!0;const i=s.type.name==="list_item"?o.$from.parent.type.create(o.$from.parent.attrs,s):s,d=a.childCount===1&&a.firstChild.type.name==="paragraph"&&a.firstChild.content.size===0;let p=r.tr;return n||(p=p.delete(o.from,o.to)),d?p=p.replaceWith(p.mapping.map(c.start()),p.mapping.map(c.end()),i):p=p.insert(p.mapping.map(t),i),p.setMeta("amxColumns",!0),e.dispatch(p.scrollIntoView()),!0}function Jl(e,t,n,r){if(r.type.name==="amadeusCanvasCard")return!1;const{state:o}=e;if(o.doc.resolve(t).depth!==0)return!1;const s=o.schema.nodes.amadeusColumnRow,c=o.schema.nodes.amadeusColumnCell,a=o.schema.nodes.paragraph;if(!s||!c||!a)return!1;const i=new Set,d=()=>{let C=Er(o.doc);for(;i.has(C);)C=Er(o.doc);return i.add(C),C},p=s.create({tail:d()},[c.create({anchor:d(),width:1},r),c.create({anchor:d(),width:1},a.create())]);let g=o.tr.replaceWith(t,n,p);return g=g.setSelection(Pe.near(g.doc.resolve(t+p.nodeSize-3))),g.setMeta("amxColumns",!0),g.setMeta("amxColumnsKeepEmpty",!0),e.dispatch(g.scrollIntoView()),!0}function Zl(e,t,n,r=!1){const o=e.doc.nodeAt(t);if(!o||o.type.name!=="amadeusColumnCell"||!(r||gc(o)))return null;const s=e.doc.resolve(t),c=s.parent;if(c.type.name!=="amadeusColumnRow")return null;const a=s.before(),i=s.after(),d=s.index(),p=[];c.forEach((J,oe,H)=>{H!==d&&p.push(J)});const g=Gs(e.schema,String(o.attrs.anchor));if(p.length>=2){const J=e.tr.delete(t,t+o.nodeSize);return g.length&&J.insert(J.mapping.map(i),g),J.setSelection(Ao.near(J.doc.resolve(Math.min(t,J.doc.content.size)),n)),J.scrollIntoView()}const C=[...yc(e.schema,p,String(c.attrs.tail??"")),...g],I=e.tr.replaceWith(a,i,C),N=p[0],k=n<0?d>0:d>=p.length,$=k?N?.lastChild:N?.firstChild;let F=a;for(const J of C){if(J===$){I.setSelection(Ao.near(I.doc.resolve(k?F+J.nodeSize-1:F+1),k?-1:1));break}F+=J.nodeSize}return I.scrollIntoView()}function Hg(e,t){const{state:n}=e,r=n.doc.nodeAt(t);if(!r||r.type.name!=="amadeusColumnRow")return!1;const o=[];r.forEach(g=>o.push(g));const s=yc(n.schema,o,String(r.attrs.tail??""),!0),c=s.length?s:[n.schema.nodes.paragraph.create()],a=n.selection;let i=null;n.doc.nodesBetween(t,t+r.nodeSize,(g,C,I)=>i||I?.type.name!=="amadeusColumnCell"?!i:(a.from>=C&&a.from<C+g.nodeSize&&(i={node:g,off:a.from-C,nodeSel:a instanceof ze&&a.from===C}),!1));const d=n.tr.replaceWith(t,t+r.nodeSize,c);let p=t;for(const g of c){const C=i;if(C&&g===C.node){d.setSelection(C.nodeSel?ze.create(d.doc,p):Ao.near(d.doc.resolve(p+C.off)));break}p+=g.nodeSize}return e.dispatch(d.scrollIntoView()),!0}const Vg=[Dg,Lg,_g].flat();yn({"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 Wg(e){return e.kind==="instructions"?f.jsx(Yg,{...e},e.pagePath):f.jsx(Xg,{...e},`${e.kind}:${e.pagePath}:${ks(e.src)?.id??"source"}`)}function Yg({src:e,readOnly:t=!1,activeInstructions:n=!0,onChange:r}){const{t:o}=Zt(),[s,c]=v.useState(e);return v.useEffect(()=>{c(e)},[e]),f.jsxs("section",{className:"am-doc-agent am-doc-agent-instructions","data-document-agent":"instructions","data-active":n,children:[f.jsxs("div",{className:"am-doc-agent-header",children:[f.jsx(Fm,{size:16,"aria-hidden":"true"}),f.jsx("span",{className:"am-doc-agent-title",children:o("docagent.instructions")}),f.jsx("span",{className:"am-doc-agent-hint",children:o(n?"docagent.instructionsScope":"docagent.instructionsNested")})]}),t?f.jsx("div",{className:"am-doc-agent-content",children:e||o("docagent.empty")}):f.jsx("textarea",{className:"am-doc-agent-input","aria-label":o("docagent.instructions"),rows:3,placeholder:o("docagent.instructionsPlaceholder"),value:s,onKeyDown:a=>a.stopPropagation(),onChange:a=>{c(a.target.value),r(a.target.value)}})]})}function Xg({kind:e,src:t,pagePath:n,readOnly:r=!1,onChange:o,onStart:s,onOpen:c}){const{t:a}=Zt(),i=v.useMemo(()=>ks(t),[t]),[d,p]=v.useState(i),[g,C]=v.useState(!1),[I,N]=v.useState(null),[k,$]=v.useState(null),[F,J]=v.useState("idle"),oe=v.useRef(!1),H=v.useRef(!1),te=Eo(),Re=e==="task"?typeof te?.submitDocumentTask=="function"&&te.hostExecution?.()!==!1:typeof te?.startChat=="function",[Ve,m]=v.useState(()=>te?.agents?.()??[]),de=e==="task"?i?.sessionId||(k?.id===i?.id?k?.sessionId:void 0):void 0,ot=r||g||!!de;v.useEffect(()=>(oe.current=!0,()=>{oe.current=!1}),[]),v.useEffect(()=>{p(i),N(null)},[i]),v.useEffect(()=>{const me=()=>{m(te?.agents?.()??[])};return me(),te?.subscribeAgents?te.subscribeAgents(me):te?.subscribe(me)},[te]),v.useEffect(()=>{if(J(de?te?.agentStatus?.(de).phase??"idle":"idle"),!!de)return te?.subscribeAgentStatus?.(me=>{me.sessionId===de&&J(me.phase)},de)},[te,de]);const ce=async()=>{if(!(r||!Re||H.current||!d||!d.prompt.trim()||de)){H.current=!0,C(!0),N(null);try{o(ps(d));const me=await s(d,e==="prompt"?"prompt":"task");if(e==="task"&&!me.sessionId)throw new Error(a("docagent.noSession"));oe.current&&e==="task"&&me.sessionId&&$({id:d.id,sessionId:me.sessionId})}catch(me){oe.current&&N(me instanceof Error?me.message:a("docagent.startFailed"))}finally{H.current=!1,oe.current&&C(!1)}}};if(!i||!d)return f.jsx("pre",{className:"am-doc-agent-source",children:f.jsx("code",{children:t})});const be=de?F==="waiting"?"docagent.waiting":F==="done"?"docagent.done":F==="error"?"docagent.failed":F==="idle"?"docagent.linked":"docagent.running":"docagent.ready",fe=g||!!de&&["thinking","speaking","tool"].includes(F),Me=e==="prompt"?ic:cf,Ke=d.agent&&!Ve.some(me=>me.slug===d.agent);return f.jsxs("section",{className:"am-doc-agent","data-document-agent":e,"data-document-agent-id":d.id,"data-page-path":n,"aria-busy":g,children:[f.jsxs("div",{className:"am-doc-agent-header",children:[f.jsx(Me,{size:16,"aria-hidden":"true"}),f.jsx("span",{className:"am-doc-agent-title",children:a(e==="prompt"?"docagent.prompt":"docagent.task")}),e==="task"&&f.jsxs("span",{className:"am-doc-agent-status",role:"status","aria-live":"polite","data-phase":F,children:[fe?f.jsx(Gc,{size:12,className:"am-doc-agent-spin","aria-hidden":"true"}):F==="done"?f.jsx(ea,{size:12,"aria-hidden":"true"}):null,a(g?"docagent.starting":be)]})]}),r||de?f.jsx("div",{className:"am-doc-agent-content",children:d.prompt||a("docagent.empty")}):f.jsx("textarea",{className:"am-doc-agent-input","aria-label":a("docagent.promptLabel"),rows:3,placeholder:a("docagent.promptPlaceholder"),value:d.prompt,disabled:g,onKeyDown:me=>me.stopPropagation(),onChange:me=>{const Ae={...d,prompt:me.target.value};p(Ae),o(ps(Ae))}}),f.jsxs("div",{className:"am-doc-agent-footer",children:[ot?f.jsx("span",{className:"am-doc-agent-assignee",children:Ve.find(me=>me.slug===d.agent)?.name||d.agent||a("docagent.defaultAgent")}):f.jsxs("select",{className:"am-doc-agent-select","aria-label":a("docagent.agent"),value:d.agent??"",onKeyDown:me=>me.stopPropagation(),onChange:me=>{const Ae={...d,agent:me.target.value||void 0};p(Ae),o(ps(Ae))},children:[f.jsx("option",{value:"",children:a("docagent.defaultAgent")}),Ke&&f.jsx("option",{value:d.agent,children:d.agent}),Ve.map(me=>f.jsx("option",{value:me.slug,children:me.name},me.slug))]}),de?c&&f.jsxs("button",{type:"button",className:"am-doc-agent-action",onClick:()=>c(de),children:[f.jsx(gi,{size:14,"aria-hidden":"true"}),a("docagent.open")]}):!r&&f.jsxs("button",{type:"button",className:"am-doc-agent-action",disabled:g||!Re||!d.prompt.trim(),title:Re?void 0:a("docagent.unavailable"),onMouseDown:me=>me.preventDefault(),onClick:()=>{ce()},children:[g?f.jsx(Gc,{size:14,className:"am-doc-agent-spin","aria-hidden":"true"}):f.jsx(gi,{size:14,"aria-hidden":"true"}),a(g?"docagent.starting":e==="prompt"?"docagent.usePrompt":"docagent.assign")]})]}),!r&&!de&&!Re&&f.jsx("div",{className:"am-doc-agent-hint",children:a("docagent.unavailable")}),I&&f.jsx("div",{className:"am-doc-agent-error",role:"alert",children:I})]})}function tc(e){const t=[];return e.forEach(n=>{if(n.type.name==="code_block"&&n.attrs.language==="forsion-instructions"){const r=n.textContent.trim();r&&t.push(r)}}),t.join(`
34
-
35
- `).slice(0,12e3)}function Ql(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.`:""}yn({"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 eu(){const[,e]=v.useState(0);return v.useEffect(()=>wl(()=>e(t=>t+1)),[]),Ce}const Ug=uf(()=>Xu(()=>import("./PdfAnnotator-DUyrgY-t.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]),import.meta.url).then(e=>({default:e.PdfAnnotator}))),no=()=>{},tu=/^!\[\[([^\]\n]+)\]\]$/,Gg=/\.(png|jpe?g|gif|webp|svg|avif|bmp)$/i,Jg=/\.[a-z0-9]{1,8}$/i,Zg=/\.db$/i,Qg=/\.pdf$/i,ey=/^https?:\/\/\S+$/i;function so(e){if(e.type.name==="code_block"){const g={"forsion-instructions":"instructions","forsion-task":"task","forsion-prompt":"prompt"}[e.attrs.language];return g&&(g==="instructions"||ks(e.textContent))?{k:"document-agent",type:g,src:e.textContent}:e.attrs.language===Om?e.textContent.trim()?{k:"sketch",src:e.textContent}:null:e.attrs.language!=="forsion-button"||!Nl(nu(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 ey.test(t)?{k:"bookmark",url:t}:null;const r=n[1],[o,s]=r.split("|"),c=o.trim();if(Gg.test(c))return null;const a=Vu(r);if(a)return{k:"web",url:a,w:ia(r)};if(!c.includes("#")&&Zg.test(c))return{k:"db",name:c,view:s?.trim()||null};if(!c.includes("#")&&Wu(c))return{k:"draw",target:c};const i=Ba.getState().embedRenderers;if(Jc(i,r.trim()))return{k:"plugin",target:r.trim()};const d=c.includes("#")?_c(c)?.target??null:c;if(d&&Jc(i,d))return{k:"plugin",target:d};if(lf(c))return{k:"note",target:r};const p=_c(c);return p?{k:"file",name:p.target,fileKind:Yu.test(p.target)?"video":"audio",loc:p.loc,badAnchor:c.includes("#")&&!p.loc,w:ia(r)}:!c.includes("#")&&Jg.test(c)?{k:"file",name:c,fileKind:Qg.test(c)?"pdf":"other",w:ia(r)}:{k:"note",target:r}}function ty({name:e,fileKind:t,pagePath:n,loc:r,badAnchor:o,insertAfter:s}){const c=eu(),a=Cn(I=>I.files),i=Cn(I=>I.openWikiLink),[d,p]=v.useState(!0),g=t==="pdf"?Al(e,a,n):null;if(t==="other")return!/\.[a-z0-9]+\.md$/i.test(e)&&!Qc()?f.jsxs("div",{className:"embed-file",children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),f.jsx("span",{className:"embed-file-name",children:e})]}):f.jsxs("button",{className:"embed-file",onClick:()=>{/\.[a-z0-9]+\.md$/i.test(e)?i(e,n):vn.openAttachment(n,e)},title:/\.[a-z0-9]+\.md$/i.test(e)?c("uembed.openInTab"):c("uembed.openWithSystem"),children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),f.jsx("span",{className:"embed-file-name",children:e}),f.jsx("span",{className:"embed-file-open",children:c("uembed.open")})]});const C=vl(e);return f.jsxs("div",{className:"embed-media",children:[f.jsxs("div",{className:"embed-media-head",children:[f.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:t==="pdf"?"📕":t==="video"?"🎬":"🎵"}),f.jsx("span",{className:"embed-file-name",children:e}),r&&f.jsxs("span",{className:"embed-media-at",title:c("uembed.startAt"),children:["@",Bc(r.at),r.to?`–${Bc(r.to)}`:""]}),o&&f.jsx("span",{className:"embed-media-warn",title:c("uembed.badAnchorTip"),children:c("uembed.badAnchor")}),f.jsx("button",{className:"embed-media-btn",onClick:()=>p(I=>!I),children:c(d?"uembed.collapse":"uembed.expand")}),(t==="pdf"||Qc())&&f.jsx("button",{className:"embed-media-btn",title:c(t==="pdf"?"uembed.openPdfInTab":"uembed.openWithSystem"),onClick:()=>{t==="pdf"?i(e,n):vn.openAttachment(n,e)},children:c("uembed.open")})]}),d&&t==="pdf"&&(g?f.jsx("div",{className:"embed-pdf embed-pdf-live",children:f.jsx(v.Suspense,{fallback:f.jsx("div",{className:"embed-pdf-loading",children:c("uembed.loadingPdf")}),children:f.jsx(Ug,{pdfPath:g,embed:!0})})}):f.jsx("iframe",{className:"embed-pdf",src:C,title:e})),d&&(t==="video"||t==="audio")&&f.jsx(bf,{kind:t,url:C,name:e,pagePath:n,loc:r??null,insertAfter:s})]})}function ny({target:e,pagePath:t,readOnly:n}){const r=eu(),o=Cn(F=>F.openWikiLink),s=Cn(F=>F.loadPage),c=Cn(F=>F.pages),a=Cn(F=>F.linkGraphVersion),[i,d]=v.useState("loading"),{note:p,subpath:g}=Zu(e),C=g?`${p}#${g}`:p;v.useEffect(()=>{let F=!0;return d("loading"),Promise.resolve(C?vn.resolveEmbed?.(C,t)??null:null).then(J=>{F&&d(J)}).catch(()=>{F&&d(null)}),()=>{F=!1}},[C,t,a]);const I=!n&&i===null&&!!p&&!hs(p,c,t),N=()=>{Cn.getState().openWikiLink(p,t),Cn.getState().pendingWikiCreate?.name===p&&Cn.getState().confirmWikiCreate()},$=(i&&i!=="loading"?xf(i.type):void 0)?.Editor;return f.jsxs("div",{className:"embed-body",children:[f.jsxs("div",{className:"embed-head",children:[f.jsx("span",{className:"embed-badge",title:r("uembed.crossNote"),children:r("uembed.badge")}),i&&i!=="loading"&&f.jsxs("button",{className:"embed-src",onClick:()=>{s(i.owner)},title:r("uembed.editAtSource"),children:[Qu(i.owner)," ↗"]})]}),i==="loading"?f.jsx("div",{className:"embed-loading",children:r("uembed.resolving")}):i&&$?f.jsx($,{blockId:"uembed",content:i.content,pagePath:i.owner,readOnly:!0,onChange:no,onInsertAfter:no,onDeleteEmpty:no,onMergePrev:no,onArrowOut:no,onMoveDir:no,focusPlace:null,onFocused:no,requestSelfFocus:no,onOpenWiki:(F,J)=>o(F,i.owner,J),getPageNames:()=>c}):f.jsxs("div",{className:"embed-missing",children:[r("uembed.embedMissing"),f.jsx("code",{children:e}),I&&f.jsx("button",{type:"button",className:"embed-media-btn embed-create",title:r("uembed.createTip",{name:p}),onClick:N,children:r("uembed.create")})]})]})}function ry({kind:e,pagePath:t,replaceText:n,insertAfter:r,startTask:o,readOnly:s=!1}){const c=s?()=>{}:n;switch(e.k){case"document-agent":return f.jsx(Wg,{kind:e.type,src:e.src,pagePath:t,readOnly:s,activeInstructions:e.activeInstructions,onChange:c,onStart:o,onOpen:a=>Eo()?.openDocumentTask?.(a)});case"db":return f.jsx(yf,{target:e.name,pagePath:t,initialView:e.view??void 0,readOnly:s,onViewChange:a=>c(a?`![[${e.name}|${a}]]`:`![[${e.name}]]`)});case"draw":return f.jsx(gf,{target:e.target,pagePath:t,readOnly:s});case"plugin":return f.jsx(hf,{target:e.target,pagePath:t});case"file":return f.jsx(ty,{name:e.name,fileKind:e.fileKind,pagePath:t,loc:e.loc,badAnchor:e.badAnchor,insertAfter:s?()=>{}:r});case"note":return f.jsx(ny,{target:e.target,pagePath:t,readOnly:s});case"bookmark":return s?f.jsx(Zc,{url:e.url}):f.jsx(Zc,{url:e.url,onChangeUrl:a=>n(a),onEmbed:()=>n(`![[${Ju(e.url)}]]`)});case"web":return f.jsx(pf,{url:e.url,toCard:()=>c(e.url)});case"button":{const a=Nl(nu(e.src));return a?f.jsx(ff,{spec:a,readOnly:s,onChange:i=>c(oy(mf(i)))}):f.jsx("span",{})}case"sketch":return f.jsx(_m,{items:[{callId:"note-sketch",html:e.src}]})}}function nu(e){return"```forsion-button\n"+e+"\n```"}function oy(e){const t=/^```forsion-button[ \t]*\r?\n([\s\S]*?)\r?\n?```$/.exec(e.trim());return t?t[1]:e}const Di=(e,t)=>e.k==="db"?`db:${e.name}`:e.k==="document-agent"?`document-agent:${e.type}:${e.type==="instructions"?"":ks(e.src)?.id}`:`${e.k}:${t}`;function sy(e,t,n){let r=!0;return e.mapping.maps.forEach((o,s)=>{const c=e.mapping.slice(s+1);o.forEach((a,i,d,p)=>{(c.map(d,-1)<t||c.map(p,1)>n)&&(r=!1)})}),r}function ay(e){return[St(()=>{const n=new jn("UNIFIED_EMBED_LAYER"),r=new Map,o=new Set,s=(a,i,d,p,g=null)=>{const C=[],I=new Map,N=(k,$)=>{const F=so(k);if(!F)return;F.k==="document-agent"&&(F.activeInstructions=a.resolve($).depth===0);const J=Di(F,k.textContent),oe=I.get(J)??0;if(I.set(J,oe+1),p===$&&d>$&&i<$+k.nodeSize||g===$)return;const H=`${J}#${oe}`,te=r.get(H),Re=F.k==="document-agent"?`${F.activeInstructions}:${k.textContent}`:k.textContent;te&&te.text!==Re&&(te.text=Re,te.render(F)),C.push(cr.inline($+1,$+k.nodeSize-1,{class:"wikilink-src-hidden"})),C.push(cr.node($,$+k.nodeSize,{class:"unified-embed-host"})),C.push(cr.widget($+1,Ve=>{const m=r.get(H);if(m)return m.refs++,m.dom;const de=document.createElement("div");de.className="unified-embed",de.contentEditable="false";const ot=Ae=>{let Ge=0,U=null;return Ae.state.doc.descendants((ae,$e)=>{if(U)return!1;const T=so(ae);return T&&Di(T,ae.textContent)===J?Ge===oe?(U={at:$e,size:ae.nodeSize},!1):(Ge++,!1):!0}),U};de.addEventListener("mousedown",Ae=>{if(Ae.button!==0)return;const Ge=Ae.target;if(Ge!==de&&Ge.parentElement!==de||Ge.closest('.amx-src-btn, .amx-img-resize, button, a, input, textarea, select, iframe, webview, video, audio, [contenteditable="true"]'))return;const U=c;if(!U)return;const ae=ot(U);ae&&(Ae.preventDefault(),Ae.stopPropagation(),U.dispatch(U.state.tr.setSelection(ze.create(U.state.doc,ae.at))),U.focus())});const ce=Ae=>{const Ge=c;if(!Ge)return;const U=ot(Ge);U&&Ge.dispatch(Ge.state.tr.insertText(Ae,U.at+1,U.at+U.size-1))},be=F.k==="web"||F.k==="file"&&F.fileKind!=="other",fe=F.k==="web"||F.k==="file"?F.w:void 0;fe&&(de.style.width=`${fe}px`);const Me=document.createElement("div");if(Me.className="unified-embed-body",de.appendChild(Me),be){const Ae=tu.exec(k.textContent.trim())?.[1];Ae!==void 0&&df(de,de,Ge=>ce(`![[${Uu(Ae,Ge)}]]`))}const Ke=km.createRoot(Me),me=Ae=>Ke.render(f.jsx(Gu,{children:f.jsx(ry,{kind:Ae,pagePath:e.path,readOnly:!!e.readOnly,insertAfter:Ge=>{const U=c;if(!U)return;const ae=ot(U);if(!ae)return;const $e=U.state.schema.nodes.paragraph;if(!$e)return;const T=Ge.split(/\n{2,}/).map(Z=>$e.create(null,Z?U.state.schema.text(Z):null));U.dispatch(U.state.tr.insert(ae.at+ae.size,T))},startTask:async(Ge,U)=>{const ae=Eo(),$e=Cn.getState().vaultRoot,T=c,Z=T&&ot(T);if(!Z)throw new Error(Ce("documentTask.sourceGone"));const ie={from:Z.at,to:Z.at+Z.size,deleted:!1};o.add(ie);try{const we=()=>{if(ie.deleted||e.readOnly||!c||c!==T||e.alive?.()===!1||Cn.getState().vaultRoot!==$e)return null;const it=c.state.doc.nodeAt(ie.from);if(!it||ie.from+it.nodeSize!==ie.to)return null;const mt=so(it);if(mt?.k!=="document-agent"||mt.type!==U)return null;const ct=it?ks(it.textContent):null;return ct?.id===Ge.id&&ct.prompt===Ge.prompt&&ct.agent===Ge.agent?ct:null};if(!we()||!e.flush)throw new Error(Ce("documentTask.sourceGone"));if(await e.flush(),!we()||!c)throw new Error(Ce("documentTask.sourceGone"));const Qe=Ql(tc(c.state.doc),e.path),qe=`${Ge.prompt.trim()}
38
-
39
- Source note: ${JSON.stringify(e.path)}. Read the source note before editing it.
40
- ${Qe}`;if(U==="prompt"){const it=await ae?.startChat?.({agent:Ge.agent,prompt:qe,send:!1,...ae?.hostExecution?.()&&$e?{cwd:$e}:{},alive:()=>!!we()});if(!it?.ok)throw new Error(it?.error||Ce("docagent.unavailable"));return{}}const zt=we()?.sessionId;if(zt)return{sessionId:zt};if(!$e||!ae?.submitDocumentTask)throw new Error(Ce("docagent.unavailable"));const st=await ae.submitDocumentTask({key:`${$e}
41
- ${e.path}
42
- ${Ge.id}`,agent:Ge.agent,prompt:qe,vaultRoot:$e,alive:()=>!!we(),onCreated:async it=>{const mt=we();if(!mt||mt.sessionId&&mt.sessionId!==it)throw new Error(Ce("documentTask.sourceGone"));const ct=c;if(ct.dispatch(ct.state.tr.insertText(ps({...mt,sessionId:it}),ie.from+1,ie.to-1)),await e.flush(),we()?.sessionId!==it)throw new Error(Ce("documentTask.sourceGone"))}});if(!st.ok)throw new Error(st.error||Ce("docagent.startFailed"));return{sessionId:st.sessionId}}finally{o.delete(ie)}},replaceText:ce})}));return me(F),Lm(de,Ve,()=>{const Ae=c;if(!Ae)return;const Ge=ot(Ae);if(!Ge)return;const U=Ae.state.tr.setSelection(Pe.near(Ae.state.doc.resolve(Ge.at+1)));U.setMeta(n,{sourcePos:Ge.at}),Ae.dispatch(U),Ae.focus()}),de.querySelector(".amx-src-btn")?.classList.add("amx-src-btn--block"),r.set(H,{root:Ke,dom:de,text:Re,render:me,refs:1}),de},{key:H,side:-1,ignoreSelection:!0,stopEvent:Ve=>/^(key|composition|beforeinput|input|paste|cut|copy)/.test(Ve.type),destroy:()=>{const Ve=r.get(H);Ve&&(Ve.refs--,!(Ve.refs>0)&&queueMicrotask(()=>{Ve.refs>0||r.get(H)!==Ve||(r.delete(H),Ve.root.unmount())}))}}))};return a.descendants((k,$)=>(N(k,$),!0)),io.create(a,C)};let c=null;return new Ht({key:n,view:a=>(c=a,{destroy:()=>{for(const i of o)i.deleted=!0;c=null,queueMicrotask(()=>{if(!c){for(const[,i]of r)i.root.unmount();r.clear()}})}}),state:{init:(a,i)=>({decos:s(i.doc,i.selection.from,i.selection.to,null),sourcePos:null,pendingPos:null}),apply:(a,i,d,p)=>{for(const N of o)for(const k of a.mapping.maps){if(N.deleted)break;const $=k.mapResult(N.from,1),F=k.mapResult(N.to,-1);($.deleted||F.deleted||$.pos>=F.pos)&&(N.deleted=!0),N.from=$.pos,N.to=F.pos}const g=a.getMeta(n);let C=i.sourcePos;if(C!=null&&a.docChanged&&(C=a.mapping.map(C)),g&&typeof g.sourcePos=="number")C=g.sourcePos;else if(C!=null&&a.selectionSet){const N=p.doc.nodeAt(C);(!N||p.selection.to<=C||p.selection.from>=C+N.nodeSize)&&(C=null)}let I=i.pendingPos;if(I!=null&&a.docChanged&&(I=a.mapping.map(I,-1)),g?.commit)I=null;else if(a.docChanged&&p.selection.empty&&!/^(paste|drop)$/.test(String(a.getMeta("uiEvent")??""))){const N=p.selection.$head,k=N.depth>0?N.before():-1;k>=0&&N.parent.type.name==="paragraph"&&so(N.parent)?.k==="bookmark"&&sy(a,k+1,k+N.parent.nodeSize-1)&&(I=k)}if(I!=null){const N=p.doc.nodeAt(I),{from:k,to:$}=p.selection;(!N||N.type.name!=="paragraph"||$<I+1||k>I+N.nodeSize-1)&&(I=null)}return!a.docChanged&&!a.selectionSet&&!g&&I===i.pendingPos?{sourcePos:C,pendingPos:I,decos:i.decos.map(a.mapping,a.doc)}:{sourcePos:C,pendingPos:I,decos:s(p.doc,p.selection.from,p.selection.to,C,I)}}},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 cy=[St(()=>Pr({Enter:fd,"Shift-Enter":dd,"Mod-Enter":ud}))].flat();function na(e){let t=e.depth;for(;t>=1&&!["doc","amadeusColumnCell"].includes(e.node(t-1).type.name);)t--;return t}function xc(e){if(!e)return!1;const t=e.type.name;return t==="code_block"||t==="hr"||t==="horizontal_rule"||t==="table"?!0:so(e)!=null}function iy(e){if(!e)return!1;const t=e.type.name;return t==="hr"||t==="horizontal_rule"?!0:so(e)!=null}function Br(e){for(let t=e.depth;t>=1;t--)if(e.node(t).type.name==="list_item")return t;return null}function Cs(e,t){return _s(e,t)!=null?!0:Tm(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 Ho(...e){return(t,n,r)=>e.some(o=>o(t,n,r))}const uy=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset===0||n.parent.type.name!=="heading")return!1;const o=n.before(n.depth);if(Xo(e,o)==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(Yo,{toggle:o}),t?.(c.scrollIntoView()),!0},ou=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parent.type.name!=="heading")return!1;const o=e.schema.nodes.paragraph;if(!o)return!1;if(n.parentOffset===0){const c=n.before(n.depth),a=e.tr.insert(c,o.create());return a.setSelection(Pe.near(a.doc.resolve(c+1))),t?.(a.scrollIntoView()),!0}const s=e.tr.split(n.pos,1,[{type:o}]);return t?.(s.scrollIntoView()),!0},dy=(e,t)=>{const n=e.selection;if(!(n instanceof ze)||!n.node.isTextblock||so(n.node)!=null)return!1;const r=e.tr.setSelection(Pe.near(e.doc.resolve(n.to-1),-1));return t?.(r.scrollIntoView()),!0},fy=(e,t,n)=>{const{$from:r,empty:o}=e.selection;if(!o||!n||!t)return!1;const s=gd(r);return!s||!yd(r.parent.type.name,s)?!1:xd(n,s)},my=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parent.content.size!==0||Br(n)==null)return!1;const o=e.schema.nodes.list_item;return o?kl(o)(e,t):!1},py=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r)return!1;const o=Br(n);if(o==null||o!==n.depth-1||n.node(o).childCount<2||!uc(e,n.before(o)))return!1;const c=e.schema.nodes.list_item,a=e.schema.nodes.paragraph;if(!c||!a)return!1;const i=e.doc.slice(n.pos,n.end()).content,d=c.createAndFill(null,a.create(null,i));if(!d)return!1;let p=e.tr.delete(n.pos,n.end());const g=p.mapping.map(n.after(o));return p=p.insert(g,d),p.setSelection(Pe.near(p.doc.resolve(g+2))),t?.(p.scrollIntoView()),!0},hy=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset===0)return!1;const o=Br(n);if(o==null||o!==n.depth-1)return!1;const s=n.node(o);if(s.childCount<2||uc(e,n.before(o)))return!1;const c=s.child(1);if(!/_list$/.test(c.type.name))return!1;const a=e.schema.nodes.list_item,i=e.schema.nodes.paragraph;if(!a||!i)return!1;const d=n.pos,p=n.end(),g=e.doc.slice(d,p).content,C=n.before(o)+1+s.child(0).nodeSize+1,I=a.createAndFill(null,i.create(null,g));if(!I)return!1;let N=e.tr.delete(d,p);const k=N.mapping.map(C);return N=N.insert(k,I),N.setSelection(Pe.near(N.doc.resolve(k+2))),t?.(N.scrollIntoView()),!0},gy=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r)return!1;const o=sc(n);if(!o||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:o}}]);return t?.(s.scrollIntoView()),!0},yy=(e,t,n)=>{const{$from:r,empty:o}=e.selection,s=Br(r);if(s==null||r.node(s).attrs.checked!==!0)return!1;const c=e.schema.nodes.list_item;if(!c)return!1;if(o&&s===r.depth-1&&r.index(s)===0&&r.parentOffset===0&&r.parent.content.size>0){const g=c.createAndFill({...r.node(s).attrs,checked:!1});if(!g)return!1;if(!t)return!0;t(e.tr.insert(r.before(s),g).scrollIntoView());const C=n?n.root.getSelection?.():null;if(C&&C.rangeCount){const I=C.getRangeAt(0);C.removeAllRanges(),C.addRange(I)}return!0}if(!t)return Fa(c)(e);let a=null;if(!Fa(c)(e,g=>{a=g}))return!1;const i=a;if(!i)return!1;const d=i.selection.$from,p=Br(d);return p!=null&&d.node(p).attrs.checked===!0&&i.setNodeMarkup(d.before(p),void 0,{...d.node(p).attrs,checked:!1}),t(i),!0},xy=e=>{const t=[];for(let n=0;;){const r=e.indexOf("$$",n);if(r<0)break;if(e[r+2]==="$"){n=r+3;continue}const o=e.indexOf("$$",r+2);if(o<0)break;t.push([r,o+2]),n=o+2}return t},su=(e,t)=>{const{$from:n,$to:r}=e.selection;if(!n.sameParent(r)||!n.parent.isTextblock||n.parent.type.spec.code)return!1;const o=e.schema.nodes.hardbreak;if(!o||!n.parent.textContent.includes("$$"))return!1;const s=n.parentOffset,c=r.parentOffset;return xy(Im(n.parent)).some(([a,i])=>s>=a+2&&c<=i-2)?(t?.(e.tr.replaceSelectionWith(o.create({isInline:!0}),!1).scrollIntoView()),!0):!1},by=Ho(uy,ou,dy,su,fy,my,py,hy,yy,gy),vy=(e,t)=>{const{$from:n}=e.selection,r=Br(n),o=ru(n);if(r!=null&&(o==null||r>o)&&n.node(r).attrs.checked!=null){const p=pd(e,n.pos);return p?(t?.(p.scrollIntoView()),!0):!1}if(o!=null){const p=e.schema.nodes.hardbreak;return p?(t?.(e.tr.replaceSelectionWith(p.create(),!1).scrollIntoView()),!0):!1}const s=e.schema.nodes.list_item;if(s&&Br(n)!=null)return Fa(s)(e,t);const c=e.schema.nodes.paragraph,a=na(n);if(!c||a<1)return!1;const i=n.after(a),d=e.tr.insert(i,c.create());return d.setSelection(Pe.near(d.doc.resolve(i+1))),t?.(d.scrollIntoView()),!0},wy=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==0||n.parent.type.name!=="heading"||n.parent.content.size===0)return!1;const o=e.schema.nodes.paragraph;return o?(t?.(e.tr.setBlockType(n.start(),n.end(),o)),!0):!1},ky=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==0)return!1;const o=ru(n);if(o==null)return!1;if(n.index(o)===0){const C=n.before(o),I=e.doc.nodeAt(C);return!I||!ze.isSelectable(I)?!1:(t?.(e.tr.setSelection(ze.create(e.doc,C))),!0)}const c=n.before(o+1),a=n.after(o+1),i=n.after(o),d=e.doc.nodeAt(c);if(!d)return!1;let p=e.tr.delete(c,a);const g=p.mapping.map(i);return p=p.insert(g,d),p.setSelection(Pe.near(p.doc.resolve(g+1))),t?.(p.scrollIntoView()),!0},Cy=(e,t,n)=>{const{$from:r,empty:o}=e.selection;return!o||r.parentOffset!==0||!n||Br(r)==null?!1:hd(n)},Sy=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==0)return!1;const o=na(n);if(o<1||o!==n.depth)return!1;const s=n.before(o),a=e.doc.resolve(s).nodeBefore;if(!xc(a)||!a)return!1;const i=s-a.nodeSize;let d=e.tr;n.parent.content.size===0&&(d=d.delete(s,n.after(o)));const p=d.doc.nodeAt(i);return!p||!ze.isSelectable(p)||Cs(e,i)?!1:(d=d.setSelection(ze.create(d.doc,i)),t?.(d.scrollIntoView()),!0)},Ey=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==0)return!1;const o=sc(n);if(!o)return!1;const s=n.before(n.depth);return t?.(e.tr.setNodeMarkup(s,void 0,{...n.parent.attrs,indent:o-1}).scrollIntoView()),!0},nc=e=>(t,n)=>{const{$from:r,empty:o}=t.selection;if(!o||r.depth<2||r.node(-1).type.name!=="amadeusColumnCell")return!1;const s=Zl(t,r.before(-1),e);return s?(n?.(s),!0):!1},My=Ho(nc(-1),wy,ky,Cy,Ey,Sy),zy=(e,t,n)=>{const{$from:r,empty:o}=e.selection;if(!o||r.parentOffset!==0)return!1;if(sc(r)){const a=r.before(r.depth);return t?.(e.tr.setNodeMarkup(a,void 0,{...r.parent.attrs,indent:0}).scrollIntoView()),!0}const c=e.schema.nodes.list_item;if(!c||Br(r)==null)return!1;if(!t||!n)return!0;for(let a=0;a<32&&!(ly(n.state.selection.$from)<=1||!kl(c)(n.state,i=>n.dispatch(i)));a++);return!0},Li=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parent.type.name!=="heading"||n.parentOffset!==n.parent.content.size)return!1;const o=n.before(n.depth);return Xo(e,o)==null?!1:(t?.(e.tr.setMeta(Yo,{toggle:o})),!0)},Ii=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==n.parent.content.size)return!1;const o=na(n);if(o<1)return!1;const s=n.after(o),c=e.doc.resolve(s).nodeAfter;return!c||!xc(c)||!ze.isSelectable(c)||Cs(e,s)?!1:(t?.(e.tr.setSelection(ze.create(e.doc,s)).scrollIntoView()),!0)},Ny=/^\[![\w-]+\]/,Pi=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||!n.parent.isTextblock||n.parentOffset!==n.parent.content.size||n.parent.type.name==="code_block"||n.depth<1)return!1;const o=N=>{for(let k=N.depth;k>0;k--)if(N.node(k).type.name==="table")return!0;return!1};if(o(n))return!1;const s=n.after(),c=Ao.findFrom(e.doc.resolve(s),1,!0);if(!(c instanceof Pe))return!1;const a=c.$from;if(a.parentOffset!==0||!a.parent.isTextblock||a.parent.type.name==="code_block"||o(a)||a.depth===n.depth&&a.before()===s||Cs(e,a.pos))return!1;const i=N=>{for(let k=N.depth;k>0;k--)if(N.node(k).type.spec.isolating)return N.before(k);return-1};if(i(n)!==i(a))return!1;let d=!1;if(e.doc.nodesBetween(s,a.before(),(N,k)=>(k>=s&&k+N.nodeSize<=a.before()&&(N.isLeaf||N.isTextblock)&&(d=!0),!d)),d)return!1;const p=a.depth>=2&&a.node(-1).type.name==="blockquote"&&a.index(-1)===0?a.before(-1):null;if(p!=null&&Ny.test(a.parent.textContent)){const N=e.doc.nodeAt(p);return!N||!ze.isSelectable(N)?!1:(t?.(e.tr.setSelection(ze.create(e.doc,p)).scrollIntoView()),!0)}const g=n.parent.textContent+a.parent.textContent,C=e.tr.delete(n.pos,a.pos),I=C.doc.resolve(C.mapping.map(n.pos));return!I.parent.isTextblock||I.parent.textContent!==g||C.doc.textContent!==e.doc.textContent?!1:(t?.(C.setSelection(Pe.create(C.doc,I.pos)).scrollIntoView()),!0)};function Fi(e){return(t,n,r)=>{const o=t.selection;if(!o.empty||!r||!r.endOfTextblock(e))return!1;const s=o.$from,c=na(s);if(c<1)return!1;const a=e==="down"?s.after(c):s.before(c),i=e==="down"?t.doc.resolve(a).nodeAfter:t.doc.resolve(a).nodeBefore;if(!iy(i)||!i)return!1;const d=e==="down"?a:a-i.nodeSize,p=t.doc.nodeAt(d);return!p||!ze.isSelectable(p)||Cs(t,d)?!1:(n?.(t.tr.setSelection(ze.create(t.doc,d)).scrollIntoView()),!0)}}function Oi(e){return(t,n,r)=>{const{$from:o,empty:s}=t.selection;if(!s||o.parent.type.name!=="code_block"||o.depth<1)return!1;const c=r?r.root.getSelection?.():null;if(r&&c?.anchorNode&&r.dom.contains(c.anchorNode))try{if(r.posAtDOM(c.anchorNode,c.anchorOffset)!==o.pos)return!1}catch{return!1}if(e==="down"?!r?.endOfTextblock("down"):o.parentOffset!==o.parent.content.size)return!1;const a=o.node(-1);if(o.index(-1)!==a.childCount-1)return!1;const i=t.schema.nodes.paragraph,d=o.after();if(!i||!a.canReplaceWith(o.index(-1)+1,o.index(-1)+1,i))return!1;if(!n)return!0;const p=t.tr.insert(d,i.create());return n(p.setSelection(Pe.create(p.doc,d+1)).scrollIntoView()),!0}}const Ay=(e,t)=>e.selection.$from.parent.type.name!=="code_block"?!1:(t?.(e.tr.insertText(`
43
- `).scrollIntoView()),!0);function _i(e){return(t,n)=>{const r=t.doc,o=e==="up"?r.firstChild:r.lastChild;if(!o)return!1;const s=e==="up"?0:r.content.size-o.nodeSize;return so(o)!=null?!ze.isSelectable(o)||Cs(t,s)?!1:(n?.(t.tr.setSelection(ze.create(r,s)).scrollIntoView()),!0):o.type.name==="code_block"?(n?.(t.tr.setSelection(Pe.create(r,e==="up"?s+1:s+o.nodeSize-1)).scrollIntoView()),!0):!1}}const $y={"(":")","[":"]","{":"}","<":">",'"':'"',"'":"'","`":"`","(":")","【":"】","「":"」","《":"》","“":"”","‘":"’"},Ty=St(e=>new Ht({props:{handleTextInput:(t,n,r,o)=>{const s=$y[o];if(!s||n===r)return!1;const c=t.state.selection;if(!(c instanceof Pe)||c.empty||!c.$from.sameParent(c.$to)||c.$from.parent.type.name==="code_block")return!1;if(o==="`"&&t.state.schema.marks.inlineCode)return e.get(vf).call(md.key);const a=t.state.tr.insertText(s,r).insertText(o,n);return a.setSelection(Pe.create(a.doc,n+1,r+1)),t.dispatch(a.scrollIntoView()),!0}}}));function Ea(e){const t=e.selection;if(!(t instanceof ze)||!t.node.isBlock)return null;const n=t.node,r=e.tr;if(n.type.name==="code_block")return r.setSelection(Pe.create(r.doc,t.to-1));if(n.type.name==="table"){const c=Ao.near(r.doc.resolve(t.from+1),1);return!(c instanceof Pe)||c.from>=t.to?null:r.setSelection(Pe.create(r.doc,c.$from.end()))}if(!xc(n)&&!n.isLeaf){const c=Ao.near(r.doc.resolve(t.to-1),-1);if(c instanceof Pe&&c.from>t.from&&c.to<t.to)return r.setSelection(c)}const o=e.schema.nodes.paragraph,s=t.$to;return!o||!s.parent.canReplaceWith(s.index(),s.index(),o)?null:(r.insert(t.to,o.create()),r.setSelection(Pe.create(r.doc,t.to+1)))}const jy=St(()=>new Ht({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 r=Ea(e.state);return r&&e.dispatch(r.scrollIntoView()),!1},compositionstart:e=>{if(!e.editable)return!1;const t=Ea(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 r=Ea(e.state);if(!r)return!1;n.preventDefault();const{from:o,to:s}=r.selection;return e.dispatch(r.insertText(n.data,o,s).scrollIntoView()),!0}}}})),Bi=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Ry=[cy,jy,Ty,St(()=>Pr({Enter:by,"Shift-Enter":Ho(ou,Ay,su),"Mod-Enter":vy,Backspace:My,"Mod-Backspace":zy,Delete:Ho(nc(1),Li,Ii,Pi),...Bi?{"Ctrl-d":Ho(nc(1),Li,Ii,Pi)}:{},ArrowUp:Fi("up"),ArrowDown:Ho(Oi("down"),Fi("down")),ArrowRight:Oi("right"),...Bi?{"Meta-ArrowUp":_i("up"),"Meta-ArrowDown":_i("down")}:{}}))].flat();yn({"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 Dy(e,t,n,r){const{schema:o}=e,s=o.nodes.paragraph;if(!s)return null;const c=s.create(null,o.text("/"));let a=null;t.type.name==="list_item"?a=n:/_list$/.test(t.type.name)&&t.firstChild?.type.name==="list_item"&&(a=n+1);const i=a==null?null:e.doc.nodeAt(a);if(i&&a!=null){const p={...i.attrs,...i.attrs.checked!=null?{checked:!1}:{}},g=i.type.createAndFill(p,c);if(g){const C=r?a:a+i.nodeSize;return{at:C,node:g,caret:C+3}}}const d=r?n:n+t.nodeSize;return{at:d,node:c,caret:d+2}}function Po(e){const t=e.offsetWidth;if(t<=0)return Fn(e);const n=Fn(e),r=e.getBoundingClientRect().width/t;return Math.abs(r-n)<.01?n:r}function Ki(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 Fo(e){const t=n=>{const r=n.getBoundingClientRect(),o=getComputedStyle(n);return{x:r.left+(Number.parseFloat(o.borderLeftWidth)||0),y:r.top+(Number.parseFloat(o.borderTopWidth)||0)}};if(getComputedStyle(e).position==="absolute"){let n=e.offsetParent;for(let r=e.parentElement;!n&&r;r=r.parentElement){const o=getComputedStyle(r);(o.position!=="static"||Ki(o))&&(n=r)}return n?t(n):{x:0,y:0}}for(let n=e.parentElement;n;n=n.parentElement)if(Ki(getComputedStyle(n)))return t(n);return{x:0,y:0}}const Ma=(e,t)=>{if(!t)return!1;const n=t.type.name;return!(n==="amadeusColumnRow"||n==="amadeusColumnCell"||Cf(r=>r.type.name==="table"||r.type.name==="blockquote")(e))};function ts(e,t){try{const n=e.posAtCoords({left:t.x,top:t.y})?.inside;if(n==null||n<0)return null;let r=e.state.doc.resolve(n),o=e.state.doc.nodeAt(n),s=e.nodeDOM(n);const c=a=>{const i=r.depth>=1&&r.index(r.depth)===0&&!["amadeusColumnCell","amadeusCanvasCard"].includes(r.node(r.depth).type.name);if(!(a||i)||r.depth<1)return;const d=r.before(r.depth);o=e.state.doc.nodeAt(d),s=e.nodeDOM(d),r=e.state.doc.resolve(d),Ma(r,o)||c(!0)};if(c(!Ma(r,o)),!o||!Ma(r,o)||!(s instanceof HTMLElement))return null;if(r.depth>=1&&r.node(r.depth).type.name==="amadeusCanvasCard"){const a=r.before(r.depth),i=e.nodeDOM(a);if(i instanceof HTMLElement){const d=i.firstElementChild?.getBoundingClientRect(),p=i.lastElementChild?.getBoundingClientRect();if(d&&t.y<d.top||p&&t.y>p.bottom){const g=e.state.doc.nodeAt(a);if(g)return{node:g,pos:a,el:i}}}}return{node:o,pos:r.pos,el:s}}catch{return null}}function qi(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 r=t.node(n);if(ze.isSelectable(r)&&!(r.type.name==="paragraph"&&n>1))return t.before(n)}return null}function Ly(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 Iy(e){let t=null,n=null;const r=new jn("amx-block-selection-mode");let o=null,s=null;const c=y=>(s&&s.isConnected||(s=document.createElement("div"),s.className="unified-drop-vline",s.style.display="none",(y.dom.parentElement??document.body).appendChild(s)),s),a=(y,S,L)=>{const D=c(y),K=Po(y.dom),X=Fo(D),ne=S.getBoundingClientRect(),G=(L==="left"?ne.left-6:ne.right+3)-X.x;D.style.display="block",D.style.height=`${ne.height/K}px`,D.style.transform=`translate(${Math.round(G/K)}px, ${Math.round((ne.top-X.y)/K)}px)`},i=()=>{s&&(s.style.display="none")},d=28,p=y=>/Mac/i.test(navigator.platform)?y.altKey:y.ctrlKey,g=y=>{const S=y.state.selection;if(!(S instanceof Pe)||S.empty||S.$from.sameParent(S.$to))return null;const L=X=>{let ne=X.depth;for(;ne>=1&&!["doc","amadeusColumnCell"].includes(X.node(ne-1).type.name);)ne--;return ne},D=L(S.$from),K=L(S.$to);return D<1||K<1||S.$from.node(D-1)!==S.$to.node(K-1)?null:{from:S.$from.before(D),to:S.$to.after(K)}},C=(y,S,L)=>{if(L.type.name!=="paragraph")return null;const D=y.state.doc.resolve(S),K=D.parent;if(!["doc","amadeusColumnCell"].includes(K.type.name))return null;const X=Number(L.attrs.indent??0),ne=D.index();let G=S+L.nodeSize,Q=0;for(let q=ne+1;q<K.childCount;q++){const Ne=K.child(q);if(Ne.type.name!=="paragraph"||Number(Ne.attrs.indent??0)<=X)break;G+=Ne.nodeSize,Q++}return Q?{from:S,to:G}:null};let I=null;const N=(y,S,L,D,K)=>{_o(y,S,{from:L.from,to:L.to,newStart:D,copy:K}),Zo(y,S,{from:L.from,to:L.to,newStart:D}),I===L.from&&S.doc.nodeAt(D)?.type.name==="heading"&&(S.setSelection(ze.create(S.doc,D)),I=null)},k=(y,S)=>{const{state:L}=y,D=L.doc.content.size,K=g(y);if(K){if(!S&&K.to===D)return!0;let q=L.doc.slice(K.from,K.to).content;if(S){const _e=es(L.doc,q);q=_e.content,_e.minted.length&&e.onCardsMinted?.(_e.minted)}let Ne=L.tr;S||(Ne=Ne.delete(K.from,K.to));const Fe=Ne.mapping.map(D);return Ne=Ne.insert(Fe,q),N(L,Ne,K,Fe,S),Ne.setMeta("amxColumns",!0),y.dispatch(Ne.scrollIntoView()),!0}const X=L.selection;if(!(X instanceof ze))return!1;if(!S&&X.to===D)return!0;const ne=X.node,G=ne.type.name==="list_item"?X.$from.parent.type.create(X.$from.parent.attrs,ne):ne;let Q=L.tr;return S||(Q=Q.delete(X.from,X.to)),Q=Q.insert(Q.mapping.map(D),G),Q.setMeta("amxColumns",!0),y.dispatch(Q.scrollIntoView()),!0},$=(y,S,L)=>{const D=g(y);if(!D)return!1;const K=ie(y,S.clientY);if(!K)return!1;const X=K.el.getBoundingClientRect(),ne=S.clientY>X.top+X.height/2?K.pos+K.node.nodeSize:K.pos;if(ne>=D.from&&ne<=D.to)return!0;let G=y.state.doc.slice(D.from,D.to).content;if(L){const Ne=es(y.state.doc,G);G=Ne.content,Ne.minted.length&&e.onCardsMinted?.(Ne.minted)}zt(y,ne);let Q=y.state.tr;L||(Q=Q.delete(D.from,D.to));const q=Q.mapping.map(ne);return Q=Q.insert(q,G),N(y.state,Q,D,q,L),Q.setMeta("amxColumns",!0),y.dispatch(Q.scrollIntoView()),!0},F=(y,S,L)=>{const{state:D}=y,K=D.selection;if(!(K instanceof ze))return!1;const X=D.doc.nodeAt(S);if(!X||X.type.name!=="list_item"||S>=K.from&&S<K.to)return!1;const ne=D.schema.nodes.list_item,G=D.schema.nodes.bullet_list;if(!ne||!G)return!1;const Q=K.node;if(Q.type.name==="amadeusColumnRow"||Q.type.name==="amadeusColumnCell")return!1;const q=Q.type.name==="list_item"?Q:ne.createAndFill(null,Q);if(!q)return!1;const Ne=X.child(X.childCount-1),Fe=X.childCount>1&&/_list$/.test(Ne.type.name);let _e=D.tr;L||(_e=_e.delete(K.from,K.to));const Be=_e.mapping.map(S),He=_e.doc.nodeAt(Be);if(!He||He.type.name!=="list_item")return!1;const Ue=Fe?Be+He.nodeSize-2:Be+He.nodeSize-1;return _e=_e.insert(Ue,Fe?q:(Ne.type.name.endsWith("_list")?Ne.type:G).create(null,q)),_e.setMeta("amxColumns",!0),y.dispatch(_e.scrollIntoView()),!0},J=y=>!!y.dom.closest(".unified-body")?.classList.contains("amx-canvas"),oe=(y,S,L,D)=>{let K=L;for(let X=0;X<S.childCount;X++){const ne=S.child(X),G=y.nodeDOM(K),Q=G instanceof HTMLElement?G.getBoundingClientRect():null;if(Q&&D.clientY<=Q.bottom)return D.clientY>Q.top+Q.height/2?K+ne.nodeSize:K;K+=ne.nodeSize}return K},H=(y,S)=>{const L=y.state.doc,D=y.state.schema.nodes.amadeusCanvasCard;let K=0;for(let X=0;X<L.childCount;X++){const ne=L.child(X);if(ne.type===D)return K;const G=y.nodeDOM(K),Q=G instanceof HTMLElement?G.getBoundingClientRect():null;if(Q&&S.clientY<=Q.bottom)return S.clientY>Q.top+Q.height/2?K+ne.nodeSize:K;K+=ne.nodeSize}return K},te=(y,S,L)=>{const D=y.state.selection;if(!(D instanceof ze))return!1;const K=y.state.schema.nodes.amadeusCanvasCard;if(!K)return!1;const X=S.target;if(!X||!y.dom.contains(X))return!1;if(D.node.type===K)return!0;const ne=X.closest?.(".amx-ucard");let G;if(ne){let q;try{q=y.posAtDOM(ne,0)-1}catch{return!1}const Ne=y.state.doc.nodeAt(q);if(Ne?.type!==K)return!1;G=oe(y,Ne,q+1,S)}else G=H(y,S);if(G>=D.from&&G<=D.to)return!0;let Q=y.state.tr;return L||(Q=Q.delete(D.from,D.to)),Q=Q.insert(Q.mapping.map(G),D.node),Q.setMeta("amxColumns",!0),y.dispatch(Q.scrollIntoView()),!0},Re=y=>{const S=y.state.schema.nodes.amadeusCanvasCard,L=[];return S&&y.state.doc.forEach((D,K,X)=>{D.type===S&&L.push({anchor:String(D.attrs.anchor),idx:X,pos:K,size:D.nodeSize})}),L},Ve=(y,S)=>{const L=y.state.doc,D=y.state.schema.nodes.amadeusCanvasCard;if(!D)return null;const K=e.canvasTree?.()??{},X=Re(y),ne=new Map;for(let Be=0;Be<X.length;){const He=Us(X,Be,K);ne.set(Be,He),Be=He}const G=Be=>{const He=y.nodeDOM(Be);return He instanceof HTMLElement?He:null},Q=[];let q=0,Ne=0,Fe=-1;for(let Be=0;Be<L.childCount;Be++){const He=L.child(Be);if(q<Fe){He.type===D&&Ne++,q+=He.nodeSize;continue}if(He.type===D){const Ue=ne.get(Ne);if(Ue!=null){const We=X[Ue-1];Q.push({from:q,to:We.pos+We.size,firstEl:G(q),lastEl:G(We.pos)})}Ne++}else{let Ue=q+He.nodeSize,We;if(He.type.name==="heading"&&yo(y,q)==="folded"){const Je=Xo(y.state,q);Je!=null&&(Ue=Je,Fe=Je,We=q)}Q.push({from:q,to:Ue,firstEl:G(q),lastEl:G(q),foldPos:We})}q+=He.nodeSize}let _e=null;for(let Be=0;Be<Q.length;Be++){const He=Q[Be];if(!He.firstEl||!He.lastEl)continue;const Ue=He.firstEl.getBoundingClientRect().top,We=He.lastEl.getBoundingClientRect().bottom;if(_e={at:He.to,lineEl:He.lastEl,edge:"bottom",expandFold:He.foldPos},S.clientY>We)continue;const Je=Be>0?Q[Be-1]:null;return S.clientY<=(Ue+We)/2?{at:He.from,lineEl:He.firstEl,edge:"top",expandFold:Je&&Je.foldPos!=null&&Je.to===He.from?Je.foldPos:void 0}:_e}return _e},m=(y,S)=>{const L=y.state.selection,D=y.state.schema.nodes.amadeusCanvasCard;if(!D||!(L instanceof ze)||L.node.type!==D)return null;const K=Ve(y,S);if(!K)return null;const X=e.canvasTree?.()??{},ne=Re(y),G=ne.findIndex(Ne=>Ne.pos===L.from);if(G<0)return null;const Q=ne[Us(ne,G,X)-1],q={from:L.from,to:Q.pos+Q.size};return{drop:K,range:q,self:K.at>=q.from&&K.at<=q.to}},de=(y,S,L)=>{const D=y.state.selection,K=y.state.schema.nodes.amadeusCanvasCard;if(!K||!(D instanceof ze)||D.node.type!==K)return!1;const X=m(y,S);if(!X||X.self)return!0;let ne=y.state.doc.slice(X.range.from,X.range.to).content;if(L){const Q=es(y.state.doc,ne);ne=Q.content,Q.minted.length&&e.onCardsMinted?.(Q.minted)}X.drop.expandFold!=null&&yo(y,X.drop.expandFold)==="folded"&&Ts(y,X.drop.expandFold);let G=y.state.tr;if(L||(G=G.delete(X.range.from,X.range.to)),G=G.insert(G.mapping.map(X.drop.at),ne),G.setMeta("amxColumns",!0),y.dispatch(G.scrollIntoView()),!L){const Q=String(D.node.attrs.anchor),Ne=(e.canvasTree?.()??{})[Q];typeof Ne=="string"&&Re(y).some(Fe=>Fe.anchor===Ne)&&e.onCardDetach?.([Q])}return!0};let ot=null,ce=null,be=null,fe=null,Me=!1,Ke=!1,me=null;const Ae=y=>(me&&me.isConnected||(me=document.createElement("div"),me.className="unified-drop-line",me.style.display="none",me.style.animation="none",(y.dom.parentElement??document.body).appendChild(me)),me),Ge=(y,S,L=0,D="bottom")=>{const K=Ae(y),X=Po(y.dom),ne=Fo(K),G=S.getBoundingClientRect(),Q=D==="top"?G.top-6:G.bottom+6;K.style.display="block",K.style.width=`${Math.max(0,G.width-L)/X}px`,K.style.transform=`translate(${Math.round((G.left+L-ne.x)/X)}px, ${Math.round((Q-ne.y)/X)}px)`},U=()=>{me&&(me.style.display="none")},ae=(y,S)=>{const L=y.state.doc.resolve(S);if(L.depth===0)return y.state.doc.nodeAt(S)?.type.name!=="amadeusCanvasCard";for(let D=L.depth;D>=1;D--)if(L.node(D).type.name==="amadeusColumnRow")return D===1;return!1},$e=y=>y instanceof HTMLElement&&y.getClientRects().length>0,T=(y,S)=>{if(J(y))return null;const L=y.state.selection,D=L instanceof ze?{from:L.from,to:L.to}:g(y);if(!D)return null;const K=S.target instanceof Element?S.target.closest("blockquote"):null;if(!(K instanceof HTMLElement)||!y.dom.contains(K))return null;let X;try{X=y.posAtDOM(K,0)-1}catch{return null}const ne=y.state.doc.nodeAt(X);if(ne?.type.name!=="blockquote"||y.nodeDOM(X)!==K)return null;const G=y.state.doc.slice(D.from,D.to).content;let Q=!1;if(G.descendants(Be=>{["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell"].includes(Be.type.name)&&(Q=!0)}),Q)return null;const q=!!ne.firstChild?.isTextblock&&/^\[![\w-]+\]/.test(ne.firstChild.textContent),Ne=y.nodeDOM(X+1);if(q&&$e(Ne)){const Be=Ne.getBoundingClientRect();if(S.clientY<Be.top+Be.height/2)return null}let Fe=null;if(ne.forEach((Be,He)=>{const Ue=X+1+He,We=y.nodeDOM(Ue);if(!$e(We))return;const Je=We.getBoundingClientRect(),Ut=S.clientY<Je.top+Je.height/2?"top":"bottom",Et=Math.abs(S.clientY-(Ut==="top"?Je.top:Je.bottom));(!Fe||Et<Fe.distance)&&(Fe={at:Ut==="top"?Ue:Ue+Be.nodeSize,lineEl:We,edge:Ut,distance:Et})}),!Fe)return null;const _e=Fe;return{..._e,self:_e.at>=D.from&&_e.at<=D.to}},Z=(y,S,L)=>{const D=T(y,S);if(!D)return!1;if(D.self)return!0;const{state:K}=y,X=K.selection,ne=X instanceof ze?{from:X.from,to:X.to}:g(y);if(!ne)return!1;const G=X instanceof ze&&X.node.type.name==="list_item"?Sr.from(X.$from.parent.type.create(X.$from.parent.attrs,X.node)):K.doc.slice(ne.from,ne.to).content,Q=L?K.tr:K.tr.delete(ne.from,ne.to),q=Q.mapping.map(D.at),Ne=Q.doc.resolve(q);return Ne.parent.type.name!=="blockquote"||!Ne.parent.canReplace(Ne.index(),Ne.index(),G)?!1:(Q.insert(q,G),N(K,Q,ne,q,L),Vs(Q,q,q+G.size),Q.setSelection(G.childCount===1&&ze.isSelectable(G.firstChild)?ze.create(Q.doc,q):Pe.between(Q.doc.resolve(q),Q.doc.resolve(q+G.size))),Q.setMeta("amxColumns",!0).setMeta("uiEvent","drop"),y.dispatch(Q.scrollIntoView()),y.focus(),!0)},ie=(y,S)=>{const L=y.state.doc;let D=null,K=1/0;for(let X=0,ne=0;X<L.childCount;ne+=L.child(X).nodeSize,X++){const G=y.nodeDOM(ne);if(!$e(G))continue;const Q=G.getBoundingClientRect(),q=S<Q.top?Q.top-S:S>Q.bottom?S-Q.bottom:0;if(q===0)return{pos:ne,node:L.child(X),el:G};q<K&&(K=q,D={pos:ne,node:L.child(X),el:G})}return D},we=(y,S)=>{const L=y.state.selection,D=p(S),K=X=>!D&&L instanceof ze&&X>=L.from&&X<=L.to;for(const X of y.dom.querySelectorAll(":scope > .amx-ucolrow")){const ne=X.getBoundingClientRect();if(!(S.clientY<ne.top||S.clientY>ne.bottom||S.clientX<ne.left||S.clientX>ne.right)){for(const G of Array.from(X.children)){if(!$e(G)||!("amxColcell"in G.dataset))continue;const Q=G.getBoundingClientRect();if(!(S.clientX<Q.left||S.clientX>Q.right))try{const q=y.posAtDOM(G,0)-1,Ne=y.state.doc.nodeAt(q);if(Ne?.type.name!=="amadeusColumnCell")return null;let Fe=q+1,_e=null;for(let Be=0;Be<Ne.childCount;Be++){const He=Ne.child(Be),Ue=y.nodeDOM(Fe);if($e(Ue)){const We=Ue.getBoundingClientRect();if(S.clientY<=We.bottom){if(S.clientY>=We.top&&(!He.isTextblock&&!He.isAtom||S.clientX<=We.left+d||S.clientX>=We.right-d))return null;const Je=S.clientY<=We.top+We.height/2,Ut=Je?Fe:Fe+He.nodeSize;return{cellEl:G,lineEl:Ue,pos:Fe,edge:Je?"top":"bottom",tail:!1,self:K(Ut)}}_e=Ue}Fe+=He.nodeSize}return _e?{cellEl:G,lineEl:_e,pos:q,edge:"bottom",tail:!0,self:K(q+Ne.nodeSize-1)}:null}catch{return null}}return null}}return null},Qe=(y,S)=>{if(!S.cellEl.isConnected||!S.lineEl.isConnected)return null;try{if(S.tail){const K=y.posAtDOM(S.cellEl,0)-1,X=y.state.doc.nodeAt(K);return X?.type.name==="amadeusColumnCell"?K+X.nodeSize-1:null}const L=y.state.doc.nodeAt(S.pos);if(!L||y.nodeDOM(S.pos)!==S.lineEl)return null;const D=S.edge==="top"?S.pos:S.pos+L.nodeSize;return y.state.doc.resolve(D).parent.type.name==="amadeusColumnCell"?D:null}catch{return null}},qe=(y,S)=>{try{const L=y.state.doc.resolve(S),D=L.parent;let K=L.start();for(let X=0;X<D.childCount&&K<S;X++){const ne=D.child(X);if(ne.type.name==="heading"&&yo(y,K)==="folded"){const G=Xo(y.state,K);if(G!=null&&S>K&&S<=G)return K}K+=ne.nodeSize}}catch{}return null},zt=(y,S)=>{for(let L=qe(y,S),D=-1;L!=null&&L!==D;D=L,L=qe(y,S))Ts(y,L)};let st=null;const it=()=>{st&&(st.style.display="none")};let mt=!1,ct=!1;const dn=()=>{ct||(ct=!0,mt=!1,queueMicrotask(()=>{ct=!1,mt||it()}))},ut=St(()=>new Ht({key:new jn("UNIFIED_BLOCK_HANDLE"),view:y=>{t=y,pi.add(y);const S=y.dom.parentElement??document.body,L=S.closest(".unified-body")??S,D=A=>{for(const P of L.querySelectorAll(".amx-ucard.amx-droptarget"))P.classList.remove("amx-droptarget");A?.classList.add("amx-droptarget")},K=document.createElement("div");K.className="unified-gutter",K.dataset.show="false";const X=()=>{K.dataset.show="false",n=null},ne=A=>{if(!y.editable)return;n=A,Et(A),Ze.style.display=Xn(A)?"":"none";const P=Po(y.dom),le=Fo(K),pe=hi(A.el),Te=pe.getBoundingClientRect(),ge=(A.el.tagName==="LI"&&/^(UL|OL)$/.test(A.el.parentElement?.tagName??"")?A.el.parentElement:null)?.getBoundingClientRect().left??Te.left,ve=getComputedStyle(pe),ft=Number.parseFloat(ve.lineHeight)||24,wt=(Number.parseFloat(ve.paddingTop)||0)+Math.max(0,(ft-24)/2),Wt=Te.height/P,Pt=Math.max(24,Wt-16),Rt=Pt>24?Pt/2-4-wt:0;K.dataset.show="true",K.style.setProperty("--amx-block-h",`${Wt}px`),K.style.setProperty("--amx-block-grow-y",`${Rt}px`);const zn=K.offsetWidth||52;K.style.top=`${(Te.top-le.y)/P+wt}px`;let Dt=(ge-le.x)/P-zn-8;Ko()&&(Dt=Math.max(Dt,(2-le.x)/P-G.offsetLeft)),K.style.left=`${Dt}px`},G=document.createElement("button");G.type="button",G.className="drag-handle",G.textContent="⠿",G.draggable=!0,G.title=Ce("blocklayer.dragHandle"),G.setAttribute("aria-label",G.title),G.addEventListener("click",A=>{A.stopPropagation();const P=G.getBoundingClientRect();if(A.detail===0&&t&&n){const le=t.state.selection;le instanceof ze&&le.from<=n.pos&&n.pos+n.node.nodeSize<=le.to||Q(t,n)}e.onMenu({x:P.left,y:P.bottom+4,keyboard:A.detail===0}),Ko()||t?.focus()}),K.addEventListener("mousedown",()=>{t&&n&&Q(t,n)});const Q=(A,P)=>{const le=A.state.selection,pe=P.pos+1,Te=P.pos+P.node.nodeSize-1;if(le instanceof Pe&&!le.empty&&!le.$from.sameParent(le.$to)&&le.from<=pe&&le.to>=Te){A.focus();return}const De=C(A,P.pos,P.node);if(De){const ge=A.state.doc;A.dispatch(A.state.tr.setSelection(Pe.between(ge.resolve(De.from+1),ge.resolve(De.to-1))).setMeta(r,!0)),A.focus();return}ze.isSelectable(P.node)&&(A.dispatch(A.state.tr.setSelection(ze.create(A.state.doc,P.pos))),A.focus())};let q=null;const Ne=()=>{const A=t,P=n;if(!A||!P)return;(!q||!q.isConnected)&&(q=document.createElement("div"),q.className="unified-press-rect",(A.dom.parentElement??document.body).appendChild(q));const le=Po(A.dom),pe=Fo(q),Te=hi(P.el).getBoundingClientRect(),De=g(A);let ge={left:Te.left-pe.x,top:Te.top-pe.y,right:Te.right-pe.x,bottom:Te.bottom-pe.y};if(De)for(const ve of Array.from(A.dom.children)){if(!ve.classList.contains("amx-block-selected"))continue;const ft=ve.getBoundingClientRect();ge={left:Math.min(ge.left,ft.left-pe.x),top:Math.min(ge.top,ft.top-pe.y),right:Math.max(ge.right,ft.right-pe.x),bottom:Math.max(ge.bottom,ft.bottom-pe.y)}}Object.assign(q.style,{display:"block",transform:`translate(${Math.round((ge.left-4)/le)}px, ${Math.round((ge.top-4)/le)}px)`,width:`${(ge.right-ge.left+8)/le}px`,height:`${(ge.bottom-ge.top+8)/le}px`})},Fe=()=>{q&&(q.style.display="none")};K.addEventListener("mousedown",Ne),window.addEventListener("mouseup",Fe);const _e=(A,P,le)=>{A.dom.dataset.dragging="true";let pe=A.state.selection;if(I=null,pe instanceof ze&&yo(A,pe.from)==="folded"){const De=pe.from,ge=Xo(A.state,De),ve=A.state.doc;if(ge!=null){A.dispatch(A.state.tr.setSelection(Pe.between(ve.resolve(De+1),ve.resolve(ge-1))).setMeta(r,!0));const ft=g(A);ft&&ft.from===De&&ft.to===ge?I=De:A.dispatch(A.state.tr.setSelection(ze.create(A.state.doc,De)))}I==null&&Ts(A,De),pe=A.state.selection}pe instanceof ze&&js(A,pe.from)==="folded"&&ha(A,pe.from);const Te=pe instanceof Pe&&!pe.empty&&!pe.$from.sameParent(pe.$to);if(P.dataTransfer&&(pe instanceof ze||Te)){const De=pe.content();P.dataTransfer.effectAllowed="copyMove";const{dom:ge,text:ve}=A.serializeForClipboard(De);P.dataTransfer.clearData(),P.dataTransfer.setData("text/html",ge.innerHTML),P.dataTransfer.setData("text/plain",ve),le&&P.dataTransfer.setDragImage(le,0,0),A.dragging={slice:De,move:!0}}};K.addEventListener("dragstart",A=>{t&&_e(t,A,n?.el??null)});const Be=A=>{const P=t;if(!P||!(A.target instanceof Node)||!P.dom.contains(A.target)||!A.target.closest?.(".wiki-inline-img-wrap"))return;const le=Pm(A.target);let pe=-1;try{le&&(pe=P.posAtDOM(le,0)-1)}catch{}const Te=le?.querySelector(":scope > .wiki-inline-img-wrap")?.getBoundingClientRect(),De=Te?ts(P,{x:Te.left+Te.width/2,y:Te.top+Te.height/2}):null;if(!le||!A.dataTransfer||P.nodeDOM(pe)!==le||!De||pe<De.pos||pe>=De.pos+De.node.nodeSize){A.preventDefault();return}A.stopPropagation(),Q(P,De),_e(P,A,null),A.target.addEventListener("dragend",He,{once:!0})};L.addEventListener("dragstart",Be,!0);const He=()=>{const A=t;if(A&&I!=null){const P=g(A);P&&P.from===I&&A.state.doc.nodeAt(I)?.type.name==="heading"&&A.dispatch(A.state.tr.setSelection(ze.create(A.state.doc,I))),I=null}Fe(),D(null),o=null,be=null,fe=null,ce=null,Ke=!1,Me=!1,i(),U(),it(),A&&(A.dom.dataset.dragging="false",A.dragging=null)};K.addEventListener("dragend",He);const Ue=document.createElement("button");Ue.type="button",Ue.className="block-add block-fold",Ue.textContent="▾",Ue.style.display="none";const We=A=>{const P=t;return P?js(P,A.pos)?A.pos:/_list$/.test(A.node.type.name)&&js(P,A.pos+1)?A.pos+1:null:null},Je=A=>{const P=t;return P?yo(P,A.pos)?A.pos:!A.node.isTextblock&&A.node.childCount>0&&yo(P,A.pos+1)?A.pos+1:null:null},Ut=A=>!t||!A?null:Je(A)!=null?"heading":We(A)!=null?"list":null,Et=A=>{const P=t,le=Ut(A),pe=A?We(A):null,Te=A?Je(A):null,De=!P||!A||!le?null:le==="heading"?Te==null?null:yo(P,Te):pe==null?null:js(P,pe);Ue.style.display=De?"":"none",Ue.textContent=De==="folded"?"▸":"▾",Ue.title=le==="list"?De==="folded"?Ce("blocklayer.expandChildren"):Ce("blocklayer.foldChildren"):De==="folded"?Ce("blocklayer.expandSection"):Ce("blocklayer.foldSection"),Ue.setAttribute("aria-label",Ue.title),Ue.setAttribute("aria-expanded",String(De!=="folded"))};Ue.addEventListener("click",A=>{A.stopPropagation();const P=t,le=n;if(!P||!le)return;const pe=Ut(le)==="list"?We(le):null;if(pe!=null)ha(P,pe);else{const Te=Je(le);if(Te==null)return;Ts(P,Te)}Et(le)});const vt=document.createElement("button");vt.type="button",vt.className="block-add",vt.textContent="+",vt.title=Ce("blocklayer.addBelow"),vt.setAttribute("aria-label",vt.title),vt.addEventListener("click",A=>{A.stopPropagation();const P=t,le=n;if(!P||!le)return;const pe=Dy(P.state,le.node,le.pos,A.altKey);if(!pe)return;P.focus();let Te=P.state.tr.insert(pe.at,pe.node);Te=Te.setSelection(Pe.create(Te.doc,pe.caret)).scrollIntoView(),bd(P,pe.caret),P.dispatch(Te),X()});const Ze=document.createElement("button");Ze.type="button",Ze.className="card-grab",Ze.textContent="❏",Ze.draggable=!0,Ze.title=Ce("blocklayer.cardGrab"),Ze.setAttribute("aria-label",Ze.title),Ze.style.display="none";const Xn=A=>{const P=t;if(!P||!A||A.node.type.name==="amadeusCanvasCard")return null;try{const le=P.state.doc.resolve(A.pos);for(let pe=le.depth;pe>=1;pe--){if(le.node(pe).type.name!=="amadeusCanvasCard")continue;const Te=le.before(pe),De=P.state.doc.nodeAt(Te),ge=P.nodeDOM(Te);return De&&ge instanceof HTMLElement?{node:De,pos:Te,el:ge}:null}}catch{}return null};Ze.addEventListener("mousedown",A=>{const P=t,le=Xn(n);!P||!le||(A.stopPropagation(),n=le,P.dispatch(P.state.tr.setSelection(ze.create(P.state.doc,le.pos))),P.focus(),Ne())}),Ze.addEventListener("click",A=>{if(A.stopPropagation(),!n)return;const P=Ze.getBoundingClientRect();e.onMenu({x:P.left,y:P.bottom+4,keyboard:A.detail===0}),Ko()||t?.focus()}),K.append(Ze,G,vt,Ue);let At=null,sn=null,lr=null;const Wr=()=>{const A=[];for(const P of Array.from(y.dom.children))if(P.classList.contains("amx-ucolrow"))for(const le of Array.from(P.querySelectorAll(".amx-ucolcell")))A.push(...Array.from(le.children));else A.push(P);return A},$o=(A,P,le)=>{const pe=A.getBoundingClientRect();if(P<pe.left||P>pe.right||le<pe.top||le>pe.bottom)return!1;if(A.matches("hr, table, pre, .amx-ucard"))return!0;const Te=ge=>P>=ge.left-2&&P<=ge.right+2&&le>=ge.top-2&&le<=ge.bottom+2;for(const ge of A.querySelectorAll(".unified-embed, .wiki-inline-img-wrap, .wikilink, img, video, iframe, canvas"))if(Te(ge.getBoundingClientRect()))return!0;const De=document.createTreeWalker(A,NodeFilter.SHOW_TEXT);for(let ge=De.nextNode();ge;ge=De.nextNode()){if(!ge.textContent?.length)continue;const ve=document.createRange();ve.selectNodeContents(ge);for(const ft of ve.getClientRects())if(Te(ft))return!0}return!1},Bn=A=>{if(A.button!==0||A.pointerType==="touch"||L.classList.contains("amx-canvas"))return;const P=A.target;if(!P||P.closest(".unified-gutter")||P.closest(".amx-embed")||P.closest("button, input, textarea, a")||!y.editable)return;const le=Wr();if(le.some(De=>$o(De,A.clientX,A.clientY)))return;const pe=P.closest('li[data-item-type="task"]');if(pe&&A.clientX-pe.getBoundingClientRect().left<=2)return;if(le.some(De=>{const ge=De.getBoundingClientRect();return A.clientX>=ge.left&&A.clientX<=ge.right&&A.clientY>=ge.top&&A.clientY<=ge.bottom})){lr={x:A.clientX,y:A.clientY},window.addEventListener("pointermove",Xr),window.addEventListener("pointerup",Yr,{once:!0});return}A.preventDefault(),Kn(A.clientX,A.clientY)},Kn=(A,P)=>{sn={x:A,y:P},At=document.createElement("div"),At.className="amx-marquee",document.body.appendChild(At),document.body.classList.add("amx-marquee-active"),window.addEventListener("pointermove",Ur),window.addEventListener("pointerup",Gr,{once:!0})},xr=()=>{lr=null,window.removeEventListener("pointermove",Xr),window.removeEventListener("pointerup",Yr)},Yr=()=>{xr(),window.addEventListener("mouseup",br,{once:!0})},br=()=>{y.isDestroyed||y.domObserver?.flush?.()},Xr=A=>{const P=lr;!P||Math.abs(A.clientX-P.x)<=4&&Math.abs(A.clientY-P.y)<=4||(xr(),Kn(P.x,P.y),qn=!0,window.addEventListener("dragstart",Un,!0),window.addEventListener("selectionchange",Un,!0),Ur(A))};let qn=!1;const Un=A=>{A.type==="dragstart"?A.preventDefault():A.stopImmediatePropagation()},er=()=>{if(!qn)return;qn=!1,window.removeEventListener("dragstart",Un,!0);let A=!1;const P=()=>{if(A)return;A=!0,window.removeEventListener("mouseup",le,!0),clearTimeout(pe);const Te=t;Te&&!Te.isDestroyed&&Te.focus(),qn||window.removeEventListener("selectionchange",Un,!0)},le=()=>{setTimeout(P,0)},pe=setTimeout(P,300);window.addEventListener("mouseup",le,{capture:!0,once:!0})},Ur=A=>{if(!At||!sn)return;const P=Math.min(sn.x,A.clientX),le=Math.min(sn.y,A.clientY),pe=Math.abs(A.clientX-sn.x),Te=Math.abs(A.clientY-sn.y);Object.assign(At.style,{left:`${P}px`,top:`${le}px`,width:`${pe}px`,height:`${Te}px`});const De=[],ge=[];for(const Pt of Wr()){const Rt=Pt.getBoundingClientRect();if(!(Rt.bottom<le||Rt.top>le+Te||Rt.right<P||Rt.left>P+pe))try{De.push(y.posAtDOM(Pt,0)),ge.push(Pt)}catch{}}if(!De.length)return;const ve=y.state.doc;if(ge.length===1){const Pt=ge[0];try{const Rt=Array.prototype.indexOf.call(Pt.parentNode?.childNodes,Pt),zn=y.posAtDOM(Pt.parentNode,Rt),Dt=ve.nodeAt(zn);if(Dt&&ze.isSelectable(Dt)){const tn=ze.create(ve,zn);tn.eq(y.state.selection)||y.dispatch(y.state.tr.setSelection(tn));return}}catch{}}const ft=Math.min(...De),Bt=ge[ge.length-1];if(!Bt)return;let wt=ft;try{const Pt=y.posAtDOM(Bt,0),Rt=y.state.doc.nodeAt(Pt-1);wt=Rt?Pt+Rt.content.size:Pt}catch{}const Wt=Pe.between(ve.resolve(Math.min(ft,ve.content.size)),ve.resolve(Math.min(wt,ve.content.size)));(!Wt.eq(y.state.selection)||!r.getState(y.state))&&y.dispatch(y.state.tr.setSelection(Wt).setMeta(r,!0))},Gr=A=>{window.removeEventListener("pointermove",Ur),er();const P=!!(A&&sn&&(Math.abs(A.clientX-sn.x)>4||Math.abs(A.clientY-sn.y)>4)),le=sn;if(At?.remove(),At=null,sn=null,document.body.classList.remove("amx-marquee-active"),P){y.focus();return}if(!le||!A)return;const pe=y.dom.getBoundingClientRect(),Te=Math.min(Math.max(A.clientX,pe.left+8),pe.right-8),De=y.posAtCoords({left:Te,top:A.clientY});if(!De)return;const ge=y.state.doc.resolve(De.pos);if(!ge.parent.isTextblock)return;const ve=A.clientX<pe.left+pe.width/2?ge.start():ge.end();y.dispatch(y.state.tr.setSelection(Pe.near(y.state.doc.resolve(ve)))),y.focus()};L.addEventListener("pointerdown",Bn),S.appendChild(K);let Nr=0,Dn=null;const Jr=A=>{if(K.contains(A.target)){Dn&&clearTimeout(Dn),Dn=null;return}const P=Date.now();if(P-Nr<80){const{clientX:le,clientY:pe}=A;Dn&&clearTimeout(Dn),Dn=setTimeout(()=>{Dn=null,Nr=Date.now(),Ar(le,pe)},80);return}Nr=P,Ar(A.clientX,A.clientY)},Ar=(A,P)=>{const le={clientX:A,clientY:P};if(y.dom.dataset.dragging==="true")return;let pe=ts(y,{x:le.clientX,y:le.clientY});if(!pe){const Te=y.dom.getBoundingClientRect();if(le.clientY>=Te.top&&le.clientY<=Te.bottom&&(le.clientX<Te.left+8||le.clientX>Te.right-8)){const De=Math.min(Math.max(le.clientX,Te.left+8),Te.right-8);pe=ts(y,{x:De,y:le.clientY})}}pe&&ne(pe)};L.addEventListener("mousemove",Jr,{passive:!0});const vr=A=>{const P=A.relatedTarget;P&&(K.contains(P)||L.contains(P))||X()};L.addEventListener("mouseleave",vr);const wr=()=>{y.dom.dataset.dragging!=="true"&&X()};y.dom.addEventListener("keydown",wr);const To=A=>{const P=t;if(!P||!P.editable)return;const le=P.state.selection,pe=le instanceof ze?{from:le.from,to:le.to}:r.getState(P.state)?g(P):null;let Te=!1;if(pe){const De=le instanceof ze?P.nodeDOM(le.from):null,ge=P.posAtCoords({left:A.clientX,top:A.clientY});Te=De instanceof Node&&A.target instanceof Node&&De.contains(A.target)||!!ge&&ge.pos>=pe.from&&ge.pos<=pe.to}if(!Te){const De=A.target instanceof Element?A.target:null,ge=De?.closest('[contenteditable="false"]'),ve=!!De&&(!!ge&&ge!==P.dom&&P.dom.contains(ge)||/^(IMG|VIDEO|AUDIO|HR|CANVAS|IFRAME)$/.test(De.tagName)),ft=P.state.selection.empty?De?.closest("td, th"):null;let Bt=null;if(ft&&P.dom.contains(ft)){const Pt=P.state.doc.resolve(P.posAtDOM(ft,0));for(let Rt=Pt.depth;Rt>0;Rt--)if(Pt.node(Rt).type.spec.tableRole==="table"){Bt=Pt.before(Rt);break}}if(!ve&&Bt==null)return;const wt=Bt??ts(P,{x:A.clientX,y:A.clientY})?.pos,Wt=wt==null?null:P.state.doc.nodeAt(wt);if(wt==null||!Wt||!ze.isSelectable(Wt))return;P.dispatch(P.state.tr.setSelection(ze.create(P.state.doc,wt)))}A.preventDefault(),P.focus(),e.onMenu({x:A.clientX,y:A.clientY})};y.dom.addEventListener("contextmenu",To),K.addEventListener("contextmenu",A=>{const P=t;!P||!P.editable||!n||(A.preventDefault(),Ko()||P.focus(),e.onMenu({x:A.clientX,y:A.clientY}))});const an=()=>{y.dom.dataset.dragging!=="true"&&X()};window.addEventListener("scroll",an,{capture:!0,passive:!0});const tr=A=>{if(y.dom.dataset.dragging!=="true")return;const P=Ly(y.dom);if(!P)return;const le=P.getBoundingClientRect();A.clientY<le.top+56?P.scrollTop-=14:A.clientY>le.bottom-56&&(P.scrollTop+=14)};window.addEventListener("dragover",tr);const Nt=A=>{const P=t,le=A.dataTransfer?Array.from(A.dataTransfer.types):[];if(le.includes("Files")||le.includes(wf)&&P&&!J(P)){if(!P)return;const ge=ie(P,A.clientY);if(!ge)return;const ve=ge.el.getBoundingClientRect();ot={pos:ge.pos,el:ge.el,lower:A.clientY>ve.top+ve.height/2},Ge(P,ge.el);return}if(!P||P.dom.dataset.dragging!=="true")return;Me&&U(),Me=!1;{const ge=P.state.selection;if(!J(P)&&ge instanceof ze&&ge.node.type===P.state.schema.nodes.amadeusCanvasCard){Ke=!1,o=null,ce=null,be=null,fe=null,i();const ve=m(P,A);ve&&!ve.self?(Ge(P,ve.drop.lineEl,0,ve.drop.edge),A.preventDefault()):U();return}}const pe=T(P,A);if(pe){Me=!0,o=null,ce=null,be=null,fe=null,Ke=!1,i(),it(),pe.self?U():Ge(P,pe.lineEl,0,pe.edge),A.preventDefault();return}if(Ke=!1,fe=null,!J(P)){const ve=P.state.selection instanceof ze||!!g(P),ft=P.dom.lastElementChild;if(ve&&$e(ft)){const Bt=ft.getBoundingClientRect(),wt=P.dom.getBoundingClientRect();if(A.clientY>Bt.bottom+2&&A.clientX>=wt.left&&A.clientX<=wt.right){Ke=!0,o=null,ce=null,be=null,i(),Ge(P,ft),A.preventDefault();return}}}if(!(P.state.selection instanceof ze))return;if(J(P)){D(A.target?.closest?.(".amx-ucard")),be=null,U(),A.preventDefault();return}const Te=we(P,A);if(Te){fe={cellEl:Te.cellEl,lineEl:Te.lineEl,pos:Te.pos,edge:Te.edge,tail:Te.tail,self:Te.self},be=null,o=null,ce=null,i(),it(),Te.self?U():Ge(P,Te.lineEl,0,Te.edge),A.preventDefault();return}let De=null;for(const ge of P.dom.querySelectorAll(":scope > .amx-ucolrow")){const ve=ge.getBoundingClientRect();if(A.clientX<ve.left||A.clientX>ve.right||A.clientY<=ve.bottom+2)continue;const ft=ge.nextElementSibling;ft&&A.clientY>=ft.getBoundingClientRect().top-2||(De=ge)}if(De)try{const ge=P.posAtDOM(De,0)-1;if(P.state.doc.nodeAt(ge)?.type.name==="amadeusColumnRow"){be={rowEl:De},Ge(P,De),A.preventDefault();return}}catch{}be=null,U()};L.addEventListener("dragover",Nt,!0);const cn=A=>{const P=A.relatedTarget;P&&L.contains(P)||(be=null,fe=null,ot=null,ce=null,o=null,Me=!1,i(),U(),it(),D(null))};L.addEventListener("dragleave",cn,!0);const ur=A=>{const P=t,le=o,pe=be,Te=fe,De=ce,ge=ot,ve=Ke,ft=Me;if(o=null,be=null,fe=null,ce=null,ot=null,Ke=!1,Me=!1,i(),U(),it(),D(null),!P)return;if(ge){try{const Wt=P.nodeDOM(ge.pos)===ge.el?P.state.doc.nodeAt(ge.pos):null;if(Wt){zt(P,ge.pos+Wt.nodeSize);const Pt=P.state.doc;P.dispatch(P.state.tr.setSelection(Wt.isAtom?ze.create(Pt,ge.pos):Pe.near(Pt.resolve(ge.lower?ge.pos+1+Wt.content.size:ge.pos+1),ge.lower?-1:1)))}}catch{}return}const Bt=p(A);let wt=J(P)?te(P,A,Bt):de(P,A,Bt);if(!wt)if(ve)wt=k(P,Bt);else if(ft)wt=Z(P,A,Bt);else if(g(P))wt=$(P,A,Bt);else if(De)wt=F(P,De.targetPos,Bt);else if(pe)try{pe.rowEl.isConnected&&(wt=Kg(P,P.posAtDOM(pe.rowEl,0)-1,Bt))}catch{wt=!1}else if(Te){const Wt=Qe(P,Te);Wt!=null&&(Te.self||zt(P,Wt),wt=qg(P,Wt,Bt))}else le&&(wt=Bg(P,le.targetPos,le.side,Bt));wt&&(A.preventDefault(),A.stopPropagation(),P.dom.dataset.dragging="false",P.dragging=null)};L.addEventListener("drop",ur,!0);let nr=null;const Ln=A=>{const P=t,le=A.target;if(!P||!le||!le.classList?.contains("amx-ucolrow"))return;const pe=le,Te=[...pe.children].filter(Dt=>Dt instanceof HTMLElement&&"amxColcell"in Dt.dataset);let De=-1;for(let Dt=0;Dt<Te.length-1;Dt++)if(A.clientX>=Te[Dt].getBoundingClientRect().right-2&&A.clientX<=Te[Dt+1].getBoundingClientRect().left+2){De=Dt;break}if(De<0)return;A.preventDefault();const ge=Te[De],ve=Te[De+1],ft=ge.getBoundingClientRect().left,Bt=ve.getBoundingClientRect().right-ft,wt=(Number(ge.dataset.width)||1)+(Number(ve.dataset.width)||1),Wt=Dt=>Math.min(.85,Math.max(.15,(Dt.clientX-ft)/Bt)),Pt=Dt=>{const tn=Wt(Dt);ge.style.flexGrow=String(wt*tn),ve.style.flexGrow=String(wt*(1-tn))},Rt=()=>{window.removeEventListener("pointermove",Pt),window.removeEventListener("pointerup",zn),window.removeEventListener("pointercancel",Rt),nr=null},zn=Dt=>{Rt();const tn=Wt(Dt),Zr=$r=>Math.round($r*1e4)/1e4;try{const $r=P.posAtDOM(pe,0)-1,u=P.state.doc.nodeAt($r);if(!u||u.type.name!=="amadeusColumnRow")return;let E=$r+1,M=P.state.tr;for(let B=0;B<u.childCount;B++){const O=u.child(B);B===De&&(M=M.setNodeMarkup(E,void 0,{...O.attrs,width:Zr(wt*tn)})),B===De+1&&(M=M.setNodeMarkup(E,void 0,{...O.attrs,width:Zr(wt*(1-tn))})),E+=O.nodeSize}M.setMeta("amxColumns",!0),P.dispatch(M)}catch{}};window.addEventListener("pointermove",Pt),window.addEventListener("pointerup",zn),window.addEventListener("pointercancel",Rt),nr=Rt};S.addEventListener("pointerdown",Ln);const Gn=wl(()=>{G.title=Ce("blocklayer.dragHandle"),vt.title=Ce("blocklayer.addBelow"),Ze.title=Ce("blocklayer.cardGrab");for(const A of[G,vt,Ze])A.setAttribute("aria-label",A.title)});return{update:A=>{const P=n;if(!P)return;let le=!1;try{le=P.pos<=A.state.doc.content.size&&A.state.doc.nodeAt(P.pos)===P.node}catch{}le||X()},destroy:()=>{window.removeEventListener("mouseup",Fe),q?.remove(),q=null,Dn&&clearTimeout(Dn),Gr(),L.removeEventListener("pointerdown",Bn),L.removeEventListener("mousemove",Jr),y.dom.removeEventListener("keydown",wr),y.dom.removeEventListener("contextmenu",To),L.removeEventListener("dragover",Nt,!0),L.removeEventListener("dragleave",cn,!0),L.removeEventListener("drop",ur,!0),L.removeEventListener("dragstart",Be,!0),pi.delete(y),L.removeEventListener("mouseleave",vr),S.removeEventListener("pointerdown",Ln),Gn(),nr?.(),window.removeEventListener("scroll",an,{capture:!0}),window.removeEventListener("dragover",tr),K.remove(),s?.remove(),s=null,me?.remove(),me=null,st?.remove(),st=null,o=null,be=null,fe=null,Me=!1,n=null,t===y&&(t=null)}}}})),Wn=St(()=>{const y=L=>{if(st&&st.isConnected)return st;const D=document.createElement("div");return D.className="unified-drop-line",D.style.display="none",D.style.animation="none",(L.dom.parentElement??document.body).appendChild(D),st=D,D};return bg({onDrag:({view:L,event:D,pos:K})=>{if(dn(),(D.dataTransfer?Array.from(D.dataTransfer.types):[]).includes("Files"))return!1;if(J(L))return i(),!1;if(!L.dragging||!(L.state.selection instanceof ze)||L.state.selection.node.type===L.state.schema.nodes.amadeusCanvasCard)return!1;if(be||Ke||fe||Me)return o=null,ce=null,i(),!1;const ne=L.state.selection,G=ts(L,{x:D.clientX,y:D.clientY});if(G&&G.node.type.name==="list_item"&&!(G.pos>=ne.from&&G.pos<ne.to)){const q=G.el.getBoundingClientRect();if(D.clientX>q.left+24&&D.clientY>q.top+q.height/2)return ce={targetPos:G.pos,el:G.el},o=null,i(),Ge(L,G.el,24),!1}if(ce=null,G&&!(G.pos>=ne.from&&G.pos<ne.to)&&ae(L,G.pos)){const q=G.el.getBoundingClientRect(),Ne=D.clientX<=q.left+d?"left":D.clientX>=q.right-d?"right":null;if(Ne)return o={targetPos:G.pos,side:Ne},a(L,G.el,Ne),!1}o=null,i();const Q=L.state.doc.resolve(K);if(Q.parent.type.name==="amadeusColumnRow")return!1;for(let q=Q.depth;q>=1;q--){if(Q.node(q).type.name!=="amadeusColumnCell")continue;const Ne=L.nodeDOM(Q.before(q));if(Ne instanceof HTMLElement){const Fe=Ne.getBoundingClientRect();if(D.clientX<Fe.left||D.clientX>Fe.right)return!1}break}return!0},onShow:({view:L,line:D})=>{mt=!0;const K=y(L),X=Po(L.dom),ne=Fo(K),G=(D.p1.x-ne.x)/X,Q=(D.p2.x-ne.x)/X,q=(D.p1.y-ne.y)/X;K.style.display="block",K.style.width=`${Math.max(0,Q-G)}px`,K.style.transform=`translate(${Math.round(G)}px, ${Math.round(q-1.5)}px)`},onHide:it})}),bt=St(()=>new Ht({key:new jn("UNIFIED_DROP_GUARD"),props:{handleDrop:y=>y.dom.dataset.dragging==="true"&&!!y.dragging}})),lt=St(()=>{let y=null,S=null;const L=()=>{y&&(y.style.display="none")};return new Ht({key:new jn("AMX_GAP_INSERT"),view:D=>{const K=()=>(y&&y.isConnected||(y=document.createElement("div"),y.className="amx-gap-insert",y.innerHTML="<span>+</span>",y.addEventListener("mousedown",G=>{G.preventDefault(),G.stopPropagation()}),y.addEventListener("click",G=>{if(G.preventDefault(),G.stopPropagation(),!S)return;let Q=-1;D.state.doc.forEach((Fe,_e)=>{Q<0&&Fe.type.name==="amadeusCanvasCard"&&String(Fe.attrs.anchor)===S&&(Q=_e)});const q=D.state.schema.nodes.paragraph;if(Q<0||!q){L();return}let Ne=D.state.tr.insert(Q,q.create());Ne=Ne.setSelection(Pe.create(Ne.doc,Q+1)).scrollIntoView(),D.dispatch(Ne),D.focus(),L()}),(D.dom.parentElement??document.body).appendChild(y)),y),X=G=>{if(J(D)||D.dragging){L();return}const Q=D.state.schema.nodes.amadeusCanvasCard;if(!Q){L();return}const q=D.state.doc;let Ne=0,Fe=null,_e=null;for(let Je=0;Je<q.childCount&&!_e;Je++){const Ut=q.child(Je);if(Ut.type===Q){const Et=D.nodeDOM(Ne);if(Et instanceof HTMLElement){if(Et.classList.contains("amx-card-f0")&&!Et.classList.contains("amx-card-f0-top")){Fe=Et,Ne+=Ut.nodeSize;continue}if(Fe){const vt=Fe.getBoundingClientRect(),Ze=Et.getBoundingClientRect();G.clientY>=vt.bottom-3&&G.clientY<=Ze.top+3&&G.clientX>=Math.min(vt.left,Ze.left)&&G.clientX<=Math.max(vt.right,Ze.right)&&(_e={top:vt.bottom,bottom:Ze.top,left:Math.min(vt.left,Ze.left),right:Math.max(vt.right,Ze.right),anchor:String(Ut.attrs.anchor)})}Fe=Et}else Fe=null}else Fe=null;Ne+=Ut.nodeSize}if(!_e){L();return}const Be=K(),He=Po(D.dom),Ue=Fo(Be),We=(_e.top+_e.bottom)/2;Be.style.display="flex",Be.style.width=`${(_e.right-_e.left)/He}px`,Be.style.transform=`translate(${Math.round((_e.left-Ue.x)/He)}px, ${Math.round((We-Ue.y)/He-9)}px)`,S=_e.anchor},ne=D.dom.parentElement??D.dom;return ne.addEventListener("mousemove",X),ne.addEventListener("mouseleave",L),{update:(G,Q)=>{G.state.doc.eq(Q.doc)||L()},destroy:()=>{ne.removeEventListener("mousemove",X),ne.removeEventListener("mouseleave",L),y?.remove(),y=null}}}})}),Ot={listFoldedAt:(y,S)=>uc(y,S),unfoldList:(y,S)=>ha(y,S)},on=St(()=>Pr({Tab:(y,S,L)=>la(y,S,L,Ot),"Shift-Tab":(y,S)=>ua(y,S)})),Xt=St(()=>new Ht({props:{decorations:y=>{const S=y.selection;if(!S.empty)return null;const L=S.$from,D=L.parent;if(!D.isTextblock||D.content.size>0)return null;for(let X=L.depth;X>=1;X--)if(L.node(X).type.name==="blockquote")return null;const K=D.type.name==="paragraph"?Ce("blocklayer.phParagraph"):D.type.name==="heading"?Ce("blocklayer.phHeading",{n:D.attrs.level??1}):null;return K?io.create(y.doc,[cr.node(L.before(),L.after(),{class:"is-empty","data-placeholder":K})]):null}}})),Sn=["doc","amadeusColumnCell","bullet_list","ordered_list"],Zn=y=>{let S=y.depth;for(;S>=1&&!Sn.includes(y.node(S-1).type.name);)S--;return S},fo=y=>{const S=y.selection;if(S instanceof ze){if(!S.node.isBlock)return null;if(Sn.includes(S.$from.parent.type.name))return{from:S.from,to:S.to};const X=Zn(S.$from);return X<1?null:{from:S.$from.before(X),to:S.$from.after(X)}}const{$from:L,$to:D}=S;if(!L.sameParent(D)){let X=L.sharedDepth(D.pos);for(;X>0&&!Sn.includes(L.node(X).type.name);)X--;return{from:L.before(X+1),to:D.after(X+1)}}const K=Zn(L);return K<1?null:{from:L.before(K),to:L.after(K)}},en=y=>(S,L)=>{const D=fo(S);if(!D)return!1;const{from:K}=D,X=ds(S,D.from,D.to),ne=S.doc.resolve(K),G=ne.parent,Q=ne.index(),q=S.doc.resolve(X).index()-1,Ne=G.child(Q),Fe=X>D.to&&Ne.type.name==="heading"?Number(Ne.attrs.level)||1:null;let _e,Be;if(y<0){if(Q===0)return!0;Be=K,_e=K-G.child(Q-1).nodeSize;let vt=null;if(Fe!=null)for(let Ze=Q-1,Xn=K;Ze>=0;Ze--){const At=G.child(Ze);if(Xn-=At.nodeSize,At.type.name==="heading"&&(Number(At.attrs.level)||1)<=Fe){vt=Xn;break}}if(vt!=null)_e=vt;else for(let Ze=_s(S,_e+1);Ze!=null&&Ze<_e;Ze=_s(S,_e+1))_e=Ze}else{if(q+1>=G.childCount)return!0;_e=X;const vt=G.child(q+1);Be=X+vt.nodeSize,Fe!=null&&vt.type.name==="heading"&&(Be=jm(S.doc,_e)??Be)}if(!L)return!0;const He=X-K,Ue=S.doc.slice(K,X).content,We=y<0?_e:Be-He,Je=S.tr.delete(K,X).insert(We,Ue),Ut=We-K;_o(S,Je,{from:K,to:X,newStart:We}),Zo(S,Je,{from:K,to:X,newStart:We});const Et=S.selection;return Et instanceof ze?Je.setSelection(ze.create(Je.doc,Et.from+Ut)):Je.setSelection(Pe.create(Je.doc,Et.anchor+Ut,Et.head+Ut)),r.getState(S)&&Je.setMeta(r,!0),L(Je.scrollIntoView()),!0},Yn=St(()=>Pr({"Mod-Alt-ArrowUp":en(-1),"Mod-Alt-ArrowDown":en(1),"Mod-Shift-ArrowUp":en(-1),"Mod-Shift-ArrowDown":en(1)})),En=(y,S,L)=>{const D=y.selection,K=L?g(L):null;if(K){if(!S)return!0;const Fe=ds(y,K.from,K.to),{content:_e,minted:Be}=es(y.doc,y.doc.slice(K.from,Fe).content);Be.length&&e.onCardsMinted?.(Be);const He=Fe-K.from,Ue=y.tr.insert(Fe,_e);return _o(y,Ue,{from:K.from,to:Fe,newStart:Fe,copy:!0}),Zo(y,Ue,{from:K.from,to:Fe,newStart:Fe}),Ue.setSelection(Pe.create(Ue.doc,D.anchor+He,D.head+He)),r.getState(y)&&Ue.setMeta(r,!0),S(Ue.scrollIntoView()),!0}if(D instanceof ze){if(!D.node.isBlock)return!1;if(!S)return!0;const Fe=ds(y,D.from,D.to);if(Fe>D.to){const He=y.tr.insert(Fe,y.doc.slice(D.from,Fe).content);return _o(y,He,{from:D.from,to:Fe,newStart:Fe,copy:!0}),Zo(y,He,{from:D.from,to:Fe,newStart:Fe}),He.setSelection(ze.create(He.doc,Fe)),S(He.scrollIntoView()),!0}let _e=D.node;if(_e.type.name==="amadeusCanvasCard"){const{content:He,minted:Ue}=es(y.doc,Sr.from(_e)),We=He.firstChild??_e;_e=We.type.create({...We.attrs,x:Number(We.attrs.x)+40,y:Number(We.attrs.y)+40},We.content,We.marks),Ue.length&&e.onCardsMinted?.(Ue)}const Be=y.tr.insert(D.to,_e);return Be.setSelection(ze.create(Be.doc,D.to)),S(Be.scrollIntoView()),!0}if(!(D instanceof Pe)||!D.$from.sameParent(D.$to))return!1;const{$from:X}=D;let ne=X.depth;for(;ne>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard","bullet_list","ordered_list"].includes(X.node(ne-1).type.name);)ne--;if(ne<1)return!1;const G=X.before(ne),Q=ds(y,G,X.after(ne));if(!y.doc.nodeAt(G))return!1;if(!S)return!0;const q=Q-G,Ne=y.tr.insert(Q,y.doc.slice(G,Q).content);return _o(y,Ne,{from:G,to:Q,newStart:Q,copy:!0}),Zo(y,Ne,{from:G,to:Q,newStart:Q}),Ne.setSelection(Pe.create(Ne.doc,D.anchor+q,D.head+q)),S(Ne.scrollIntoView()),!0},Qn=St(()=>Pr({"Mod-d":En})),Mr=(y,S,L,D=!1)=>{const K=L?g(L):null;if(!K)return!1;const X=y.doc.resolve(K.from);if(y.doc.resolve(K.to).index()-X.index()<2)return!1;const G=y.selection;if(G.from>K.from+1||G.to<K.to-1)return!1;if(!S)return!0;const Q=y.doc.slice(K.from,K.to).content;return S(y.tr.delete(K.from,K.to).scrollIntoView()),D||e.onBlocksDeleted?.(Q),!0},qr=(y,S)=>{const L=y.selection;if(!(L instanceof ze))return!1;if(!S)return!0;const D=Sr.from(L.node);return S(y.tr.deleteSelection().scrollIntoView()),e.onBlocksDeleted?.(D),!0},Hr=(y,S,L)=>Mr(y,S,L)||qr(y,S),wn=St(()=>Pr({Backspace:Hr,Delete:Hr})),Mn=St(()=>new Ht({props:{handleDOMEvents:{cut:(y,S)=>{const L=S;if(!L.clipboardData||!Mr(y.state,void 0,y,!0))return!1;const{dom:D,text:K}=y.serializeForClipboard(y.state.selection.content());return L.preventDefault(),L.clipboardData.clearData(),L.clipboardData.setData("text/html",D.innerHTML),L.clipboardData.setData("text/plain",K),Mr(y.state,y.dispatch.bind(y),y,!0),!0}}}})),Rn=St(()=>Pr({"Mod-a":(y,S)=>{const{$from:L}=y.selection,D=(ne,G)=>y.selection.from<=ne&&y.selection.to>=G,K=[];L.parent.isTextblock&&K.push([L.start(),L.end()]);let X=L.depth;for(;X>=1&&!["doc","amadeusColumnCell"].includes(L.node(X-1).type.name);)X--;X>=1&&K.push([L.start(X),L.end(X)]);for(const[ne,G]of K)if(!D(ne,G))return S?.(y.tr.setSelection(Pe.create(y.doc,ne,G))),!0;return S?.(y.tr.setSelection(new $l(y.doc))),!0}})),hr=y=>{const S=y.selection;if(!(S instanceof Pe)||S.empty)return[];const L=!!r.getState(y);if(!L&&S.$from.sameParent(S.$to))return[];const D=[],K=ne=>{if(["bullet_list","ordered_list","table","blockquote","horizontal_rule","code_block","amadeusCanvasCard"].includes(ne.type.name))return!0;if(ne.type.name!=="paragraph")return!1;const G=ne.textContent.trim();return/^!?\[\[[^\]\n]+\]\]$/.test(G)||ne.childCount===1&&ne.firstChild?.type.name==="image"},X=(ne,G)=>{ne.forEach((Q,q)=>{const Ne=G+q,Fe=Ne+Q.nodeSize;if(!(Fe<=S.from||Ne>=S.to)){if(Q.type.name==="amadeusColumnRow"){Q.forEach((_e,Be)=>X(_e,Ne+1+Be+1));return}(L||K(Q))&&D.push([Ne,Fe,L])}})};return X(y.doc,0),D},gr=St(()=>new Ht({key:r,state:{init:()=>!1,apply:(y,S,L)=>y.getMeta(r)===!0?!0:y.docChanged||y.selectionSet&&!y.selection.eq(L.selection)?!1:S},props:{decorations:y=>{const S=hr(y);return S.length?io.create(y.doc,S.map(([L,D,K])=>cr.node(L,D,{class:K?"amx-block-selected":"amx-rendered-selected"}))):null},attributes:y=>r.getState(y)&&hr(y).length?{"data-blocksel":"true"}:{}}})),rt=St(()=>Pr({Escape:(y,S)=>{const L=y.selection;if(L instanceof ze){const D=Pe.near(y.doc.resolve(L.from+1));return S?.(y.tr.setSelection(D)),!0}if(L instanceof Pe){const D=qi(y);return D==null?!1:(S?.(y.tr.setSelection(ze.create(y.doc,D))),!0)}return!1}})),jt=["doc","amadeusColumnCell"],yr=y=>{const S=y.selection;return S instanceof ze?S.node.isBlock:S instanceof Pe&&!S.empty&&!!r.getState(y)},ir=(y,S)=>{const L=y.resolve(S);if(jt.includes(L.parent.type.name)){const K=L.nodeAfter;return K?{from:S,to:S+K.nodeSize}:null}let D=L.depth;for(;D>=1&&!jt.includes(L.node(D-1).type.name);)D--;return D>=1?{from:L.before(D),to:L.after(D)}:null},Vr=y=>{const S=y.selection,L=y.doc,D=ir(L,S instanceof ze?S.from:S.anchor),K=S instanceof ze?D:ir(L,S.head);return!D||!K||L.resolve(D.from).parent!==L.resolve(K.from).parent?null:{a:D,h:K}},zr=(y,S,L)=>{const D=y.doc,K=S.from===L.from?D.nodeAt(S.from):null;if(K&&ze.isSelectable(K))return y.tr.setSelection(ze.create(D,S.from));const X=L.from>=S.from,ne=D.resolve(X?S.from+1:S.to-1),G=D.resolve(X?L.to-1:L.from+1);return y.tr.setSelection(Pe.between(ne,G)).setMeta(r,!0)},Vn=y=>(S,L)=>{if(!yr(S))return!1;const D=Vr(S);if(!D)return!1;const K=S.doc.resolve(D.h.from),X=K.parent;let ne=K.index()+y,G=y>0?D.h.to:D.h.from;for(;ne>=0&&ne<X.childCount;){const Q=X.child(ne).nodeSize,q=y>0?G:G-Q;if(_s(S,q+1)==null)return L?.(zr(S,D.a,{from:q,to:q+Q}).scrollIntoView()),!0;G=y>0?G+Q:G-Q,ne+=y}return!0},Oe=y=>y.selection.$from.parent.type.name==="code_block";return{plugins:[St(()=>new Ht({props:{handleKeyDown:kf({"Shift-ArrowDown":Vn(1),"Shift-ArrowUp":Vn(-1),"Mod-Alt-/":(y,S,L)=>{if(!L||!L.editable||!S)return!1;if(!yr(y)){const ne=qi(y);if(ne==null)return!1;S(y.tr.setSelection(ze.create(y.doc,ne)))}const D=L.state,K=D.selection instanceof ze?L.nodeDOM(D.selection.from):null,X=K instanceof HTMLElement?K.getBoundingClientRect():L.coordsAtPos(D.selection.from);return e.onMenu({x:X.left,y:X.bottom+4,keyboard:!0,focus:"turnInto"}),!0},"Mod-]":(y,S,L)=>Oe(y)?!1:la(y,S,L,Ot),"Mod-[":(y,S)=>Oe(y)?!1:ua(y,S)}),handleDOMEvents:{mousedown:(y,S)=>{if(!S.shiftKey||S.button!==0||!y.editable||!yr(y.state))return!1;const L=y.posAtCoords({left:S.clientX,top:S.clientY}),D=Vr(y.state),K=L?ir(y.state.doc,L.pos):null;return!D||!K||y.state.doc.resolve(K.from).parent!==y.state.doc.resolve(D.a.from).parent?!1:(S.preventDefault(),y.dispatch(zr(y.state,D.a,K)),y.focus(),!0)}}}})),ut,Wn,bt,lt,gr,Xt,rt,on,Rn,wn,Mn,Yn,Qn,Ry].flat(),getView:()=>t,topRangeOf:g,duplicate:y=>En(y.state,y.dispatch.bind(y),y),indent:(y,S)=>S>0?la(y.state,y.dispatch.bind(y),y,Ot):ua(y.state,y.dispatch.bind(y))}}async function Py(e,t,n){const r=Kc(t);if(!r.length)return;const o=new Set(Kc(n).map(Hs)),s=r.filter(i=>!o.has(Hs(i)));if(!s.length)return;const a=(await vn.exclusiveAssets?.(e).catch(()=>[])??[]).filter(i=>s.some(d=>Fy(d,i)));a.length&&await rh(e,a,{block:!0})==="with"&&await Sf(a)}function Fy(e,t){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase(),r=t.replace(/\\/g,"/").toLowerCase();return n.includes("/")?r===n||r.endsWith(`/${n}`):Hs(e)===Hs(t)}function Hi(e){const t=[],n=r=>{if(r.isText){t.push(r.text??"");for(const s of r.marks){const c=String(s.attrs?.href??"");s.type.name==="link"&&c&&t.push(`[](${qc(c)??c})`)}return}const o=String(r.attrs?.src??"");o&&t.push(`![](${qc(o)??o})`),r.forEach(n)};return e.forEach(n),t.join(`
44
- `)}const Kr=1,Jt=400,Or=720,Oy=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/,_y=/^<!--\s*\/a\s+([A-Za-z0-9_-]+)\s*-->$/,ra=/^[A-Za-z0-9_-]+$/,ar=(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!==Kr||n.mode!=null&&n.mode!=="doc"&&n.mode!=="canvas")return null;const r=o=>typeof o=="number"&&Number.isFinite(o);if(n.main!=null&&(typeof n.main!="object"||!r(n.main.w)||n.main.w<=0||!r(n.main.x)||!r(n.main.y)||n.main.h!=null&&(!r(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"||!ra.test(s.ref)||!r(s.w)||s.w<=0||!r(s.x)||!r(s.y)||s.h!=null&&(!r(s.h)||s.h<0))return null;const o=n.cards.map(s=>s.ref);if(new Set(o).size!==o.length)return null}return n.elements!=null&&!Array.isArray(n.elements)?null:n}catch{return null}}function By(e){const t=new Set;for(const n of e?.rows??[]){for(const r of n.columns)for(const o of r.refs)t.add(o);n.tail&&t.add(n.tail)}return t}const Ky=lc("amadeusCanvasCard",()=>({content:"block+",group:"block",defining:!0,isolating:!0,selectable:!0,attrs:{anchor:{default:""},x:{default:0},y:{default:0},w:{default:Jt},h:{default:0},color:{default:""}},parseDOM:[{tag:"div[data-amx-card]",getAttrs:e=>{const t=e.dataset;return{anchor:t.anchor??"",x:ar(Number(t.x),0),y:ar(Number(t.y),0),w:ar(Number(t.w),Jt)||Jt,h:ar(Number(t.h),0),color:t.color??""}}}],toDOM:e=>{const t=ta(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 r=t;e.openNode(n,{anchor:r.anchor??"",x:r.x??0,y:r.y??0,w:r.w??Jt,h:r.h??0,color:r.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 qy(e,t,n,r){const o=t?.cards;if(!o?.length)return;const s=Array.isArray(e?.children)?e.children:[];if(s.length&&!s.some(N=>N?.position))return;const c=N=>{let k=null;if(N?.type==="html"&&typeof N.value=="string")k=N.value;else if(N?.type==="paragraph"&&Array.isArray(N.children)&&N.children.length===1){const F=N.children[0];F?.type==="html"&&typeof F.value=="string"&&(k=F.value)}if(k==null)return null;const $=Oy.exec(k.trim());return $?$[1]:null},a=N=>{let k=null;if(N?.type==="html"&&typeof N.value=="string")k=N.value;else if(N?.type==="paragraph"&&Array.isArray(N.children)&&N.children.length===1){const F=N.children[0];F?.type==="html"&&typeof F.value=="string"&&(k=F.value)}if(k==null)return null;const $=_y.exec(k.trim());return $?$[1]:null},i=new Map(o.map(N=>[N.ref,N])),d=au(t?.cardColors),p=[];if(s.forEach((N,k)=>{const $=c(N);$&&p.push({id:$,idx:k})}),!p.length)return;const g=new Map;p.forEach(N=>g.set(N.id,(g.get(N.id)??0)+1));const C=[];for(const N of p){if((g.get(N.id)??0)>1||n.has(N.id)||!i.has(N.id))continue;let k=s.length,$=-1;for(let F=N.idx+1;F<s.length;F++){if(c(s[F])){k=F;break}if(a(s[F])===N.id){k=F,$=F;break}}C.push({id:N.id,open:N.idx,end:k,closer:$})}if(!C.length)return;const I=[];for(const N of[...C].reverse()){const k=i.get(N.id),$=s.slice(N.open+1,N.end);s.splice(N.open,(N.closer>=0?N.closer+1:N.end)-N.open,{type:"amadeusCanvasCard",anchor:N.id,x:ar(k.x,0),y:ar(k.y,0),w:ar(k.w,Jt)||Jt,h:ar(k.h,0),color:d&&Object.prototype.hasOwnProperty.call(d,N.id)&&cu(d[N.id])?d[N.id]:typeof k.color=="string"?k.color:"",children:$.length?$:[{type:"paragraph",children:[]}]}),I.unshift(N.id)}r?.(I)}function Hy(e,t,n){return[Tl("amadeusCanvasFold",()=>()=>r=>{qy(r,e(),By(t()),n)})].flat()}function Vy(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const r=String(n.attrs.anchor);if(!ra.test(r))return;const o=ar(n.attrs.h,0);t.push({ref:r,x:ar(n.attrs.x,0),y:ar(n.attrs.y,0),w:ar(n.attrs.w,Jt)||Jt,...o>0?{h:o}:{}})}),t}function au(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}const cu=e=>e!==""&&e!=null;function Vi(e){const t=Object.create(null);return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const r=String(n.attrs.anchor);ra.test(r)&&cu(n.attrs.color)&&(t[r]=n.attrs.color)}),t}function Wy(e,t,n,r){const o=Vy(e),s=_n(t);if(!s){if(t!=null)return t;if(!o.length)return null;const p=Vi(e);return JSON.stringify({v:Kr,mode:n??"canvas",main:{x:0,y:0,w:Or},cards:o,...Object.keys(p).length?{cardColors:{...p}}:{}})}if(!(s.cards??[]).every(p=>r.has(p.ref)))return t;if(!o.length&&!s.elements?.length){const p=s.main;if(!p||p.x===0&&p.y===0&&p.w===Or)return null}const c={...s,v:Kr,cards:o},a=Vi(e);Object.keys(a).length?c.cardColors={...a}:(c.cardColors===void 0||au(c.cardColors))&&delete c.cardColors,n&&(c.mode=n),c.main||(c.main={x:0,y:0,w:Or}),c.elements?.length||delete c.elements;const i=Kt(c.tree),d=Object.keys(i);if(d.length){const p=new Set(o.map(I=>I.ref)),g=I=>typeof I=="string"&&ra.test(I)&&!p.has(I),C=new Set;for(const I of d)g(I)&&C.add(I),g(i[I])&&C.add(i[I]);if(C.size){const I=Ag(i,C);Object.keys(I).length?c.tree=I:delete c.tree}}return JSON.stringify(c)}function Yy(e,t){const n=_n(e);if(!n)return e??(t.length?JSON.stringify({v:Kr,mode:"canvas",main:{x:0,y:0,w:Or},cards:[],elements:t}):null);const r={...n,v:Kr,elements:t};return t.length||delete r.elements,JSON.stringify(r)}function Xy(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)}:{}},r=_n(e);return r?JSON.stringify({...r,v:Kr,main:n}):e??(!n.x&&!n.y&&n.w===Or?null:JSON.stringify({v:Kr,mode:"canvas",main:n,cards:[]}))}function Uy(e,t){const n=Object.keys(t).length,r=_n(e);if(!r)return e??(n?JSON.stringify({v:Kr,mode:"canvas",main:{x:0,y:0,w:Or},cards:[],tree:t}):null);const o={...r,v:Kr,tree:t};return n||delete o.tree,JSON.stringify(o)}const Gy=St(()=>new Ht({key:new jn("AMX_CANVAS_NORMALIZE"),appendTransaction:(e,t,n)=>{if(!e.some(i=>i.docChanged))return null;const r=n.schema.nodes.amadeusCanvasCard;if(!r)return null;const o=[],s=[],c=new Set;if(n.doc.forEach((i,d)=>{if(i.type!==r)return;const p=String(i.attrs.anchor);c.has(p)?s.push(d):c.add(p),i.forEach((g,C)=>{if(g.type.name!=="amadeusColumnRow")return;const I=d+1+C;o.push({from:I,to:I+g.nodeSize,node:g,before:d})})}),!o.length&&!s.length)return null;let a=n.tr;for(const i of s){const d=a.doc.nodeAt(i);d?.type===r&&(a=a.setNodeMarkup(i,void 0,{...d.attrs,anchor:Er(a.doc)}))}for(const i of o)a=a.delete(a.mapping.map(i.from,1),a.mapping.map(i.to,-1)),a=a.insert(a.mapping.map(i.before),i.node);return a.steps.length?a:null}})),Jy=St(()=>new Ht({key:new jn("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 r=!1;if(e.content.descendants(s=>s.type===n?(r=!0,!1):!0),!r)return e;const o=s=>{const c=[];return s.forEach(a=>{a.type===n?o(a.content).forEach(i=>c.push(i)):c.push(a.copy(o(a.content)))}),Sr.fromArray(c)};return Ka.maxOpen(o(e.content))}}})),Zy=St(()=>new Ht({key:new jn("AMX_CANVAS_INTEGRITY"),filterTransaction:(e,t)=>{if(!e.docChanged)return!0;const n=t.schema.nodes.amadeusCanvasCard;if(!n)return!0;let r=!0;return e.doc.descendants((o,s,c)=>!r||o.type!==n?r:c?.type.name!=="doc"?(r=!1,!1):!0),r}})),Qy=[Ky,Gy,Jy,Zy].flat();function ex(e){return[St(()=>new Ht({key:new jn("AMX_CANVAS_SEL_CLAMP"),appendTransaction:(t,n,r)=>{if(!e())return null;const o=r.schema.nodes.amadeusCanvasCard;if(!o)return null;let s=-1;{let N=0;for(let k=0;k<r.doc.childCount;k++){const $=r.doc.child(k);if($.type===o){s=N;break}N+=$.nodeSize}}if(s<0)return null;const c=N=>N.depth>=1&&N.node(1).type===o?N.index(0):-1,a=N=>{if(N<0)return{from:0,to:s};let k=0;for(let $=0;$<N;$++)k+=r.doc.child($).nodeSize;return{from:k+1,to:k+r.doc.child(N).nodeSize-1}},i=N=>N.eq(r.selection)||c(r.doc.resolve(N.anchor))!==c(r.doc.resolve(N.head))?null:r.tr.setSelection(N),d=r.selection;if(d.empty||d instanceof ze)return null;if(d instanceof $l){if(t.some($=>$.docChanged))return null;const N=Math.max(0,Math.min(n.selection.head,r.doc.content.size)),k=a(c(r.doc.resolve(N)));return k.from>=k.to?null:i(Pe.between(r.doc.resolve(k.from),r.doc.resolve(k.to),-1))}if(!(d instanceof Pe))return null;const p=r.doc.resolve(d.anchor),g=c(p);if(g===c(r.doc.resolve(d.head)))return null;const C=a(g),I=Math.max(C.from,Math.min(C.to,d.head));return i(Pe.between(p,r.doc.resolve(I),d.head>=d.anchor?-1:1))}}))].flat()}function tx(){return[St(()=>new Ht({key:new jn("AMX_CARD_ACTIVE"),props:{decorations(e){const t=e.schema.nodes.amadeusCanvasCard;if(!t)return null;const n=e.selection;let r=-1,o=null;if(n instanceof ze){if(n.node.type===t)r=n.from,o=n.node;else if(n.$from.depth>=1){const s=n.$from.node(1);s.type===t&&(r=n.$from.before(1),o=s)}}else if(n.$head.depth>=1){const s=n.$head.node(1);s.type===t&&(r=n.$head.before(1),o=s)}return o?io.create(e.doc,[cr.node(r,r+o.nodeSize,{class:"amx-card-active"})]):null}}}))].flat()}const nx=6,rx=2;function ox(e){return[St(()=>new Ht({key:new jn("AMX_CARD_DEPTH"),props:{decorations(t){const n=t.schema.nodes.amadeusCanvasCard;if(!n)return null;const r=Kt(e()?.tree);if(!Object.keys(r).length)return null;const o=new Set,s=[];t.doc.forEach((i,d,p)=>{if(i.type!==n)return;const g=String(i.attrs.anchor);o.add(g),s.push({pos:d,size:i.nodeSize,anchor:g,idx:p})});const c=[];for(let i=0;i<s.length;i++){const d=Us(s,i,r);d>i+1&&c.push({start:i,end:d})}const a=[];for(let i=0;i<s.length;i++){const d=s[i],p=$g(r,d.anchor,o,nx),g=c.filter(I=>I.start<=i&&i<I.end).slice(0,rx);if(!p&&!g.length)continue;const C=[];p>0&&C.push("amx-card-child",`amx-card-d${p}`),g.forEach((I,N)=>{C.push(`amx-card-f${N}`),I.start===i&&C.push(`amx-card-f${N}-top`),I.end-1===i&&C.push(`amx-card-f${N}-end`)}),a.push(cr.node(d.pos,d.pos+d.size,{class:C.join(" ")}))}return a.length?io.create(t.doc,a):null}}}))].flat()}const sx=200;function ax(e){return[St(()=>new Ht({key:new jn("AMX_CANVAS_HISTORY_TIMELINE"),state:{init:(t,n)=>({depth:Oa(n)}),apply:(t,n,r,o)=>{const s=Oa(o);return t.docChanged&&s>n.depth&&!vd(t)&&(e.log.push("pm"),e.log.length>sx&&e.log.shift(),e.future.length=0),s===n.depth?n:{depth:s}}}}))].flat()}yn({"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 It=e=>`c:${e}`,gn=e=>`e:${e}`,iu=e=>`t:${e}`,tt=e=>e.slice(2),Rs=e=>typeof e=="number"&&Number.isFinite(e)?e:null,Vo=e=>typeof e=="string"&&e?e:null,za=e=>ta(e)?e:null,bc=e=>{const t=ta(e);return t?{"data-color":e,style:{"--amx-color":t}}:{}};function Js(e){if(!e||typeof e!="object")return null;const t=e,n=Vo(t.ref);if(n)return{ref:n};const r=Vo(t.id);return r?{id:r}:t.main===!0?{main:!0}:null}const xo=e=>e.ref?It(e.ref):e.id?gn(e.id):e.main?he:null;function Tn(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=Vo(o.id);if(!s||n.has(s))continue;if(o.type==="connector"){const p=Js(o.from),g=Js(o.to);if(!p||!g)continue;n.add(s),t.push({kind:"connector",id:s,from:p,to:g,label:Vo(o.label),color:za(o.color),fromEnd:o.fromEnd==="arrow"?"arrow":"none",toEnd:o.toEnd==="none"?"none":"arrow"});continue}if(o.type!=="shape"&&o.type!=="text"&&o.type!=="frame")continue;const c=Rs(o.x),a=Rs(o.y),i=Rs(o.w),d=Rs(o.h);if(!(c==null||a==null||i==null||d==null||i<=0||d<=0)){if(n.add(s),o.type==="frame"){t.push({kind:"frame",id:s,x:c,y:a,w:i,h:d,title:Vo(o.title),color:za(o.color)});continue}t.push({kind:o.type==="text"?"text":"shape",id:s,x:c,y:a,w:i,h:d,shape:o.shape==="ellipse"?"ellipse":"rect",text:Vo(o.text),color:za(o.color)})}}return t}function Wi(e,t){const n=e.x+e.w/2,r=e.y+e.h/2,o=t.x+t.w/2-n,s=t.y+t.h/2-r;return Math.abs(o)*e.h>=Math.abs(s)*e.w?{x:o>=0?e.x+e.w:e.x,y:r}:{x:n,y:s>=0?e.y+e.h:e.y}}function vc(e,t){const n=Wi(e,t),r=Wi(t,e),o=Math.abs(r.x-n.x)>=Math.abs(r.y-n.y),s=Math.max(24,Math.abs(o?r.x-n.x:r.y-n.y)/2),c=Math.sign(r.x-n.x||1),a=Math.sign(r.y-n.y||1);return{p1:n,c1:o?{x:n.x+c*s,y:n.y}:{x:n.x,y:n.y+a*s},c2:o?{x:r.x-c*s,y:r.y}:{x:r.x,y:r.y-a*s},p2:r}}function cx(e,t){const{p1:n,c1:r,c2:o,p2:s}=vc(e,t),c=[n.x,r.x,o.x,s.x],a=[n.y,r.y,o.y,s.y],i=Math.min(...c),d=Math.min(...a);return{d:`M${n.x},${n.y} C${r.x},${r.y} ${o.x},${o.y} ${s.x},${s.y}`,mid:{x:(n.x+s.x)/2+(r.x+o.x-n.x-s.x)/8,y:(n.y+s.y)/2+(r.y+o.y-n.y-s.y)/8},tip:s,ang:Math.atan2(s.y-o.y,s.x-o.x),tail:n,tailAng:Math.atan2(n.y-r.y,n.x-r.x),box:{x:i,y:d,w:Math.max(1,Math.max(...c)-i),h:Math.max(1,Math.max(...a)-d)}}}function Ds(e,t,n,r=8){const{p1:o,c1:s,c2:c,p2:a}=vc(e,t);let i=o.x,d=o.y;for(let p=1;p<=24;p++){const g=p/24,C=1-g,I=C*C*C*o.x+3*C*C*g*s.x+3*C*g*g*c.x+g*g*g*a.x,N=C*C*C*o.y+3*C*C*g*s.y+3*C*g*g*c.y+g*g*g*a.y,k=I-i,$=N-d,F=k*k+$*$,J=F?Math.max(0,Math.min(1,((n.x-i)*k+(n.y-d)*$)/F)):0;if(Math.hypot(i+J*k-n.x,d+J*$-n.y)<=r)return!0;i=I,d=N}return!1}function lu(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[];for(const[n,r]of Object.entries(e))!n||typeof r!="string"||!r||r===n||t.push([n,r]);return t}function ix(e,t){const n=[...t].flatMap(a=>a===he?[he]:a.startsWith("c:")?[tt(a)]:[]),r=new Set(n),o=new Set;if(!n.length||!e.length)return{nodes:r,edgeChildren:o};const s=new Map,c=new Map;for(const[a,i]of e){s.set(a,i);const d=c.get(i);d?d.push(a):c.set(i,[a])}for(const a of n){const i=new Set;let d=a;for(;!i.has(d);){i.add(d),r.add(d);const C=s.get(d);if(!C)break;o.add(d),r.add(C),d=C}const p=[a],g=new Set;for(;p.length;){const C=p.shift();if(!g.has(C)){g.add(C);for(const I of c.get(C)??[])o.add(I),r.add(I),p.push(I)}}}return{nodes:r,edgeChildren:o}}const Yi=(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 pn(e){const t=new Map;if(!e)return t;for(const n of e.querySelectorAll(".amx-ucard[data-anchor]")){const r=n.dataset.anchor;r&&t.set(r,{x:n.offsetLeft,y:n.offsetTop,w:n.offsetWidth,h:n.offsetHeight})}return t}function hn(e){const t=e?.querySelector(".ProseMirror");return t?{x:t.offsetLeft,y:t.offsetTop,w:t.offsetWidth,h:t.offsetHeight}:null}function Xi(e,t=!1){const n=i=>!t||!i.closest(".amx-ucard"),r=i=>(i.innerText||i.textContent||"").split(/\r?\n/).map(d=>d.trim()).find(Boolean)??null,o=[...e.querySelectorAll("h1,h2,h3,h4,h5,h6")].filter(n).map(r).filter(i=>!!i),s=[...e.querySelectorAll("p,li,blockquote,pre")].filter(n).map(r).filter(i=>!!i),c=o[0]??s[0];if(!c)return null;const a=s.find((i,d)=>i!==c&&(o.length>0||d>0))??null;return{title:c,detail:a}}function lx(e,t){const n=e.classList.contains("amx-stage-overview");n&&e.classList.remove("amx-stage-overview");try{const r=[];for(const[a,i]of pn(e)){const d=e.querySelector(`.amx-ucard[data-anchor="${CSS.escape(a)}"]`),p=d?Xi(d):null;d&&p&&r.push({key:It(a),anchor:a,...p,h:i.h,autoHeight:Number(d.dataset.h)<=0})}const o=e.querySelector(".ProseMirror"),s=hn(e),c=o?Xi(o,!0):null;return s&&c&&r.push({key:he,anchor:he,...c,h:s.h,autoHeight:t}),r}finally{n&&e.classList.add("amx-stage-overview")}}function ux(e,t){return e.length===t.length&&e.every((n,r)=>{const o=t[r];return n.key===o?.key&&n.anchor===o.anchor&&n.title===o.title&&n.detail===o.detail&&n.h===o.h&&n.autoHeight===o.autoHeight})}const ro=24;function Mo(e,t){const n=new Map;for(const r of e){if(r.kind==="connector")continue;let o={x:r.x,y:r.y,w:r.w,h:r.h};t?.move&&t.move.ids.has(gn(r.id))&&(o={...o,x:o.x+t.move.dx,y:o.y+t.move.dy}),t?.size&&t.size.id===r.id&&(o={x:o.x+t.size.dx,y:o.y+t.size.dy,w:Math.max(ro,o.w+t.size.dw),h:Math.max(ro,o.h+t.size.dh)}),n.set(r.id,o)}return n}function dx({elements:e,hostRef:t,documentKey:n,sel:r,editing:o,tree:s,ghost:c,marquee:a,attach:i,overviewScale:d,mainAutoHeight:p=!0,preview:g,guides:C}){const{t:I}=Zt(),N=v.useMemo(()=>Tn(e),[e]),k=v.useMemo(()=>lu(s),[s]),$=v.useMemo(()=>ix(k,r),[k,r]),F=$.edgeChildren,[J,oe]=v.useState(0),H=N.length+k.length,te=[...r].filter(T=>T.startsWith("c:")).map(tt),Re=r.has(he),Ve=H+te.length+(Re?1:0),m=d!=null&&d>0,[de,ot]=v.useState({documentKey:"",items:[]});v.useEffect(()=>{const T=t.current;if(!T)return;let Z=0;const ie=new ResizeObserver(()=>qe()),we=new Set,Qe=()=>{const st=new Set(T.querySelectorAll(".amx-ucard")),it=T.querySelector(".ProseMirror");it&&st.add(it);for(const mt of st)we.has(mt)||(ie.observe(mt,{box:"border-box"}),we.add(mt));for(const mt of[...we])st.has(mt)||(ie.unobserve(mt),we.delete(mt))},qe=()=>{cancelAnimationFrame(Z),Z=requestAnimationFrame(()=>{Qe(),oe(st=>st+1)})};qe();const zt=new MutationObserver(qe);return zt.observe(T,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["style","data-x","data-y","data-w","data-h"]}),ie.observe(T),()=>{cancelAnimationFrame(Z),zt.disconnect(),ie.disconnect()}},[t]);const ce=v.useMemo(()=>pn(t.current),[t,n,de.documentKey,J,Ve,c]),be=v.useMemo(()=>Mo(N,c),[N,c]),fe=hn(t.current);v.useLayoutEffect(()=>{if(!m)return;const T=t.current,Z=T?.querySelector(".ProseMirror");if(!T||!Z||Z.childElementCount===0)return;const ie=lx(T,p);ot(we=>we.documentKey===n&&ux(we.items,ie)?we:{documentKey:n,items:ie})},[n,t,p,m,J]);const Me=de.documentKey===n?de.items:[],Ke=new Set([...te,...Re?[he]:[]]),me=m?Me.flatMap(T=>{if(Ke.has(T.anchor))return[];const Z=T.anchor===he?fe:ce.get(T.anchor);return Z?[{...T,box:Z}]:[]}):[],Ae=t.current?.dataset.amxDragscope,Ge=m&&Ae?Me.flatMap(T=>{const Z=`.amx-stage[data-amx-dragscope="${CSS.escape(Ae)}"].amx-stage-overview`;if(Ke.has(T.anchor))return[];if(T.anchor===he)return[`${Z} .ProseMirror:not(.unified-embed .ProseMirror) > :not(.amx-ucard){display:none!important;}`,...p?[`${Z} .ProseMirror:not(.unified-embed .ProseMirror){height:${T.h}px;}`]:[]];const ie=`${Z} .amx-ucard[data-anchor="${CSS.escape(T.anchor)}"]`;return[`${ie} > *{display:none!important;}`,...T.autoHeight?[`${ie}[data-h="0"]{height:${T.h}px;}`]:[]]}).join(`
45
- `):"",U=$.nodes.size>0&&Ae?(()=>{const T=`.amx-stage[data-amx-dragscope="${CSS.escape(Ae)}"]:not(.amx-stage-off)`,Z=[...ce.keys()].filter(we=>!$.nodes.has(we)).flatMap(we=>[`${T} .amx-ucard[data-anchor="${CSS.escape(we)}"]`,`${T} .amx-card-overview[data-card-label="${CSS.escape(we)}"]`]),ie=Z.length?[`${Z.join(`,
46
- `)}{opacity:0.44;}`]:[];if(!$.nodes.has(he)){const we=`${T} .ProseMirror:not(.unified-embed .ProseMirror)`;ie.push(`${we}{background-color:color-mix(in srgb,var(--bg) 44%,transparent);border-color:color-mix(in srgb,var(--border) 44%,transparent);box-shadow:none;}`,`${we}>:not(.amx-ucard){opacity:0.44;}`,`${T} .amx-card-overview[data-card-label="${CSS.escape(he)}"]{opacity:0.44;}`)}return ie.push(`${T} .amx-el-conn.is-tree:not(.is-related){opacity:0.18;}`),ie.join(`
47
- `)})():"",ae=T=>T.ref!=null?ce.get(T.ref)??null:T.id!=null?be.get(T.id)??null:T.main?fe:null,$e=T=>T===he?fe:T.startsWith("c:")?ce.get(tt(T))??null:be.get(tt(T))??null;return f.jsxs("div",{className:"amx-el-layer",children:[Ge?f.jsx("style",{"data-amx-overview-rules":!0,children:Ge}):null,U?f.jsx("style",{"data-amx-related-focus-rules":!0,children:U}):null,N.filter(T=>T.kind==="frame").map(T=>f.jsx(hx,{el:T,box:be.get(T.id),sel:r.has(gn(T.id))},T.id)),N.filter(T=>T.kind!=="frame").map(T=>T.kind==="connector"?f.jsx(Ls,{el:T,a:ae(T.from),b:ae(T.to),sel:r.has(gn(T.id))},T.id):f.jsx(gx,{el:T,box:be.get(T.id),sel:r.has(gn(T.id))},T.id)),r.size===1&&[...r][0].startsWith("e:")&&be.has(tt([...r][0]))?f.jsxs(f.Fragment,{children:[f.jsx(mx,{id:tt([...r][0]),box:be.get(tt([...r][0]))}),f.jsx(Na,{node:[...r][0],box:be.get(tt([...r][0]))})]}):null,(()=>{const T=r.size===1?[...r][0]:null,Z=T?.startsWith("e:")?N.find(zt=>zt.kind==="connector"&&zt.id===tt(T)):null,ie=Z?ae(Z.from):null,we=Z?ae(Z.to):null;if(!Z||!ie||!we)return null;const{p1:Qe,p2:qe}=vc(ie,we);return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-conn-end","data-conn-end":"from","data-el":Z.id,style:{left:`${Qe.x}px`,top:`${Qe.y}px`}}),f.jsx("div",{className:"amx-conn-end","data-conn-end":"to","data-el":Z.id,style:{left:`${qe.x}px`,top:`${qe.y}px`}})]})})(),k.map(([T,Z])=>{const ie=Z===he?fe:ce.get(Z),we=ce.get(T),Qe=Z===he?{main:!0}:{ref:Z};return ie&&we?f.jsx(Ls,{el:{kind:"connector",id:`t:${T}`,from:Qe,to:{ref:T},label:null},a:ie,b:we,sel:r.has(iu(T)),related:F.has(T),tree:!0},`t:${T}`):null}),te.map(T=>{const Z=ce.get(T);return Z?f.jsx("div",{className:`amx-el-selbox${o===T?" is-editing":""}`,"data-anchor":T,style:{left:`${Z.x}px`,top:`${Z.y}px`,width:`${Z.w}px`,height:`${Z.h}px`},children:r.size===1&&o!==T?f.jsxs(f.Fragment,{children:[f.jsx(Ui,{anchor:T}),f.jsx(Gi,{node:T}),f.jsx(Na,{node:It(T)})]}):null},`sel:${T}`):null}),Re&&fe?f.jsx("div",{className:`amx-el-selbox${o===he?" is-editing":""}`,"data-main-sel":!0,style:{left:`${fe.x}px`,top:`${fe.y}px`,width:`${fe.w}px`,height:`${fe.h}px`},children:r.size===1&&o!==he?f.jsxs(f.Fragment,{children:[f.jsx(Ui,{anchor:he}),f.jsx(Gi,{node:he}),f.jsx(Na,{node:he})]}):null}):null,me.map(T=>{const Z=T.box.h*d,ie=Z<44?"title":Z<60?"summary":"full",we=ie==="title"?Math.max(8,Math.min(12,(Z-3)/1.2)):12;return f.jsxs("div",{className:"amx-card-overview","data-card-label":T.anchor,"data-overview-density":ie,style:{left:`${T.box.x}px`,top:`${T.box.y}px`,width:`${T.box.w}px`,height:`${T.box.h}px`,"--amx-overview-inv":String(1/d),"--amx-overview-title-screen":`${we}px`},children:[f.jsx("span",{className:"amx-card-overview-title",children:T.title}),T.detail?f.jsx("span",{className:"amx-card-overview-detail",children:T.detail}):null]},`overview:${T.key}`)}),g?(()=>{const T=$e(g.from);if(!T)return null;const Z=g.over?$e(g.over):null,ie=Z??{x:g.x,y:g.y,w:1,h:1};return f.jsxs(f.Fragment,{children:[f.jsx(Ls,{el:{kind:"connector",id:"~preview",from:{},to:{},label:null},a:T,b:ie,sel:!1,preview:!0}),f.jsx("div",{className:"amx-conn-target",style:{left:`${T.x}px`,top:`${T.y}px`,width:`${T.w}px`,height:`${T.h}px`}}),Z?f.jsx("div",{className:"amx-conn-target",style:{left:`${Z.x}px`,top:`${Z.y}px`,width:`${Z.w}px`,height:`${Z.h}px`}}):null]})})():null,i?(()=>{const T=i.node===he?fe:ce.get(i.node),Z=ce.get(i.source);if(!T)return null;const ie=3,we=22,Qe=i.side==="n"||i.side==="s",qe=i.side==="w"?T.x:i.side==="e"?T.x+T.w:T.x+T.w/2,zt=i.side==="n"?T.y:i.side==="s"?T.y+T.h:T.y+T.h/2;return f.jsxs(f.Fragment,{children:[Z?f.jsx(Ls,{el:{kind:"connector",id:"~attach",from:{ref:i.source},to:i.node===he?{main:!0}:{ref:i.node},label:null},a:Z,b:T,sel:!1,preview:!0}):null,f.jsx("div",{className:`amx-el-attach-target is-${i.rel}`,style:{left:`${T.x}px`,top:`${T.y}px`,width:`${T.w}px`,height:`${T.h}px`}}),f.jsx("div",{className:`amx-el-attach is-${i.rel}`,"data-attach":i.side,style:{left:`${i.side==="e"?T.x+T.w-ie:i.side==="w"?T.x:T.x+(T.w-we)/2}px`,top:`${i.side==="s"?T.y+T.h-ie:i.side==="n"?T.y:T.y+(T.h-we)/2}px`,width:`${Qe?we:ie}px`,height:`${Qe?ie:we}px`}}),f.jsxs("div",{className:`amx-el-attach-label is-${i.rel}`,style:{left:`${qe}px`,top:`${zt}px`},children:[i.count&&i.count>1?`${I("canvasel.attach.count",{n:i.count})} · `:"",i.rel==="child"?I("canvasel.attach.child"):I("canvasel.attach.sibling")]})]})})():null,C?.map((T,Z)=>f.jsx("div",{className:`amx-el-guide is-${T.dir}`,style:{left:`${T.x}px`,top:`${T.y}px`,width:`${T.w}px`,height:`${T.h}px`}},`guide:${Z}`)),a?f.jsx("div",{className:"amx-el-marquee",style:{left:`${a.x}px`,top:`${a.y}px`,width:`${a.w}px`,height:`${a.h}px`}}):null]})}const uu=["nw","ne","sw","se"],fx=["n","e","s","w",...uu];function Ui({anchor:e}){return f.jsx(f.Fragment,{children:fx.map(t=>f.jsx("div",{className:`amx-card-size-grip is-${t}`,"data-card-grip":e,"data-card-edge":t},t))})}function mx({id:e,box:t}){return f.jsx(f.Fragment,{children:uu.map(n=>f.jsx("div",{className:`amx-el-grip is-free is-${n}`,"data-grip":e,"data-corner":n,style:{left:`${(n[1]==="e"?t.x+t.w:t.x)-5}px`,top:`${(n[0]==="s"?t.y+t.h:t.y)-5}px`}},n))})}function Gi({node:e}){const{t}=Zt();return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-el-add is-child","data-add":"child","data-node":e,title:t("canvasel.add.child"),children:"+"}),f.jsx("div",{className:"amx-el-add is-sibling","data-add":"sibling","data-node":e,title:t("canvasel.add.sibling"),children:"+"})]})}const px=["n","e","s","w"];function Na({node:e,box:t}){const{t:n}=Zt(),r=o=>t?{left:`${o==="w"?t.x:o==="e"?t.x+t.w:t.x+t.w/2}px`,top:`${o==="n"?t.y:o==="s"?t.y+t.h:t.y+t.h/2}px`}:void 0;return f.jsx(f.Fragment,{children:px.map(o=>f.jsx("div",{className:`amx-link-dot is-${o}${t?" is-free":""}`,"data-link-from":e,title:n("canvasel.link.drag"),style:r(o)},o))})}function hx({el:e,box:t,sel:n}){const r=bc(e.color);return f.jsx("div",{className:`amx-el-frame${n?" is-sel":""}`,"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:f.jsx("div",{className:"amx-el-frame-bar","data-el":e.id,children:e.title??"Frame"})})}function gx({el:e,box:t,sel:n}){const r=e.kind==="text"?"amx-el-text":e.shape==="ellipse"?"amx-el-ellipse":"amx-el-rect",o=bc(e.color);return f.jsx("div",{className:`amx-el-shape ${r}${n?" is-sel":""}`,"data-el":e.id,"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:e.text})}function Ls({el:e,a:t,b:n,sel:r,related:o,tree:s,preview:c}){if(!t||!n)return null;const a=cx(t,n),i=14,d={x:a.box.x-i,y:a.box.y-i,w:a.box.w+i*2,h:a.box.h+i*2},p=9,g=4.5,C=($,F)=>{const J=Math.cos(F),oe=Math.sin(F);return[`${$.x},${$.y}`,`${$.x-p*J+g*oe},${$.y-p*oe-g*J}`,`${$.x-p*J-g*oe},${$.y-p*oe+g*J}`].join(" ")},I=!s&&e.toEnd!=="none",N=!s&&e.fromEnd==="arrow",k=bc(e.color);return f.jsxs(f.Fragment,{children:[f.jsxs("svg",{className:`amx-el-conn${r?" is-sel":""}${o?" is-related":""}${s?" is-tree":""}${c?" is-preview":""}`,"data-el":e.id,"data-color":k["data-color"],style:{left:`${d.x}px`,top:`${d.y}px`,width:`${d.w}px`,height:`${d.h}px`,...k.style},viewBox:`${d.x} ${d.y} ${d.w} ${d.h}`,children:[o?f.jsx("path",{className:"amx-el-conn-halo",d:a.d}):null,f.jsx("path",{className:"amx-el-conn-core",d:a.d}),I?f.jsx("polygon",{points:C(a.tip,a.ang)}):null,N?f.jsx("polygon",{points:C(a.tail,a.tailAng)}):null]}),e.label?f.jsx("div",{className:`amx-el-label${r?" is-sel":""}`,"data-color":k["data-color"],style:{left:`${a.mid.x}px`,top:`${a.mid.y}px`,...k.style},children:e.label}):null]})}const Is=e=>typeof e=="number"&&Number.isFinite(e)?e:null,ns=e=>typeof e=="string"&&e?e:null,Aa=e=>ta(e)?e:null,Ji=e=>e==="none"||e==="arrow"?e:null,rs=e=>({x:Math.round(e.x),y:Math.round(e.y),width:Math.max(1,Math.round(e.w)),height:Math.max(1,Math.round(e.h))});function yx(e){const t=/^!\[\[([^\]\n]+)\]\]$/.exec(e.trim());return t?t[1]:null}function Zi(e,t){const n=t.x+t.w/2-(e.x+e.w/2),r=t.y+t.h/2-(e.y+e.h/2);return Math.abs(n)*e.h>=Math.abs(r)*e.w?n>=0?"right":"left":r>=0?"bottom":"top"}function xx(e){const t=[],n=[],r=[],o=new Map,s=e.pages?[...e.pages].sort():[],c=Array.isArray(e.elements)?e.elements:[],a=new Set,i=[];for(const k of c){if(!k||typeof k!="object"||Array.isArray(k))continue;const $=k,F=ns($.id);if(!F||a.has(F))continue;if($.type==="connector"){a.add(F),i.push($);continue}if($.type!=="shape"&&$.type!=="text"&&$.type!=="frame")continue;const J=Is($.x),oe=Is($.y),H=Is($.w),te=Is($.h);if(J==null||oe==null||H==null||te==null||H<=0||te<=0)continue;a.add(F);const Re=`el-${F}`,Ve={x:J,y:oe,w:H,h:te};o.set(Re,Ve);const m=Aa($.color);if($.type==="frame"){const de=ns($.title);t.push({id:Re,type:"group",...rs(Ve),...de?{label:de}:{},...m?{color:m}:{}})}else n.push({id:Re,type:"text",...rs(Ve),text:typeof $.text=="string"?$.text:"",...m?{color:m}:{}})}for(const k of e.cards){const $=`card-${k.ref}`;o.set($,k);const F=Aa(k.color),J=yx(k.md),oe=J&&s.length?hs(yl(J),s,e.sourcePath):null;if(J&&oe){const H=J.split("|")[0],te=H.indexOf("#"),Re=te>=0?H.slice(te).trim():"";r.push({id:$,type:"file",...rs(k),file:oe,...Re.length>1?{subpath:Re}:{},...F?{color:F}:{}})}else r.push({id:$,type:"text",...rs(k),text:k.md,...F?{color:F}:{}})}const d=[],p=k=>{if(!k||typeof k!="object")return null;const $=k,F=ns($.ref)?`card-${$.ref}`:ns($.id)?`el-${$.id}`:$.main===!0?"main":null;return F&&(o.has(F)||F==="main")?F:null};e.main&&o.set("main",e.main);let g=!1;const C=k=>{const $=o.get(k.fromNode),F=o.get(k.toNode);!$||!F||((k.fromNode==="main"||k.toNode==="main")&&(g=!0),d.push({...k,fromSide:Zi($,F),toSide:Zi(F,$)}))};for(const k of i){const $=p(k.from),F=p(k.to);if(!$||!F||$===F)continue;const J=Ji(k.fromEnd),oe=Ji(k.toEnd),H=ns(k.label),te=Aa(k.color);C({id:`edge-${k.id}`,fromNode:$,toNode:F,...J?{fromEnd:J}:{},...oe?{toEnd:oe}:{},...H?{label:H}:{},...te?{color:te}:{}})}const I=e.tree&&typeof e.tree=="object"&&!Array.isArray(e.tree)?e.tree:{};for(const k of Object.keys(I)){const $=I[k];if(typeof $!="string"||!$||$===k)continue;const F=$==="m:"?"main":`card-${$}`,J=`card-${k}`;o.has(J)&&C({id:`tree-${k}`,fromNode:F,toNode:J,toEnd:"none"})}const N=[...t,...n];return e.main&&(e.main.md.trim()||g)&&N.push({id:"main",type:"text",...rs(e.main),text:e.main.md}),N.push(...r),{nodes:N,edges:d}}const bx=e=>`${JSON.stringify(e,null," ")}
48
- `;function vx(e,t=1){const n=e.lastIndexOf("/"),r=n>=0?e.slice(0,n+1):"",o=e.slice(n+1).replace(/\.md$/i,"");return`${r}${o}${t>1?` ${t}`:""}.canvas`}async function wx(e,t,n){for(let r=1;r<=50;r++){const o=vx(t,r);if(await e.readTextFile(o).catch(()=>null)!=null)continue;const s=await e.writeTextFile(o,n,{create:!0});if(s&&s.ok===!1){if(s.current!=null)continue;throw new Error(`Could not create ${o}`)}return o}throw new Error("Too many exported canvases with the same name")}yn({"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 kx=[{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"}],Qi=[{id:"end",from:"none",to:"arrow",nameKey:"canvasstage.ends.end",icon:f.jsx(Pp,{size:13})},{id:"start",from:"arrow",to:"none",nameKey:"canvasstage.ends.start",icon:f.jsx(Op,{size:13})},{id:"both",from:"arrow",to:"arrow",nameKey:"canvasstage.ends.both",icon:f.jsx(Lp,{size:13})},{id:"none",from:"none",to:"none",nameKey:"canvasstage.ends.none",icon:f.jsx(rp,{size:13})}],Cx=2,Bs=168,du=72,$a=320,el=12,os=".amx-el-shape, .amx-el-frame-bar",tl="button, a[href], input, select, textarea",Sx='li[data-item-type="task"], .wikilink';function Ex(e,t){const n=e.closest(Sx);return n?n.tagName!=="LI"||t-n.getBoundingClientRect().left<=2:!1}const Ta=e=>e.kind==="connector"?"label":e.kind==="frame"?"title":"text",ja=e=>Ce(e.kind==="connector"?"canvasstage.textTitle.connector":e.kind==="frame"?"canvasstage.textTitle.frame":"canvasstage.textTitle.element"),Ps=e=>[...Mo(Tn(e).filter(t=>t.kind!=="frame"),null).values()],nl=50,Ra=new Set(["rect","ellipse","frame"]),ss={rect:"rect",ellipse:"ellipse",text:"text"};let Mx=0;const rl=(e,t,n,r,o,s=Bs)=>Of(e,t,n,r,o,s,du);function wc(e){const t=[];return e.forEach((n,r,o)=>{n.type.name==="amadeusCanvasCard"&&t.push({anchor:String(n.attrs.anchor),pos:r,idx:o,node:n})}),t}function On(e){return wc(e.state.doc)}const rc=(e,t,n)=>Us(e,t,n);function fu(e,t,n){const r=wc(e),o=r.findIndex(c=>c.anchor===n);if(o<0)return e.content.size;const s=r[rc(r,o,t)-1];return s.pos+s.node.nodeSize}function ol(e,t,n,r){const o=wc(e.doc),s=o.findIndex(C=>C.anchor===n);if(s<0)return e;const c=rc(o,s,t),a=o[s].pos,i=o[c-1],d=i.pos+i.node.nodeSize;let p;if(r){const C=o.findIndex(k=>k.anchor===r);if(C<0||C>=s&&C<c)return e;const I=rc(o,C,t);if(s>C&&s<I)return e;const N=o[I-1];p=N.pos+N.node.nodeSize}else if(p=e.doc.content.size,d===p)return e;const g=Sr.fromArray(o.slice(s,c).map(C=>C.node));return e.delete(a,d).insert(p>d?p-(d-a):p,g)}function oo(e,t){e.dispatch(Ws(t).setMeta("amxCanvas",!0))}function bo(e,t,n=!0){const r=On(e);let o=e.state.tr,s=!1;for(const c of r){const a=t.get(c.anchor);a&&(o=o.setNodeMarkup(c.pos,void 0,{...c.node.attrs,...a}),s=!0)}s&&(n?oo(e,o):e.dispatch(o.setMeta("amxCanvas",!0).setMeta("addToHistory",!1)))}function zx(e,t,n,r){const o=On(e).find(a=>a.anchor===t),s=e.state.schema.nodes.paragraph;if(!o||!s||r!=null&&o.node.textContent!==r)return!1;const c=s.create(null,n?e.state.schema.text(n):void 0);return e.dispatch(e.state.tr.replaceWith(o.pos+1,o.pos+o.node.nodeSize-1,c).setMeta("amxCanvas",!0)),!0}function sl(e){if(!e?.childCount)return;const t=[];return e.forEach(n=>{n.type.name==="amadeusCanvasCard"?n.content.forEach(r=>t.push(r)):t.push(n)}),t.length?Sr.fromArray(t):void 0}function al(e,t=!1){return e.kind==="note"?`${t?"":"!"}[[${e.path.replace(/\.md$/i,"")}]]`:e.kind==="session"?`[[session:${e.id}|${e.title}]]`:e.path}const cl="application/x-amx-canvas";let Da=null;function Nx(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"),r={token:t.token,mds:n},o=s=>typeof s=="number"&&Number.isFinite(s);if(Array.isArray(t.cards)&&t.cards.length===n.length&&n.length===t.mds.length){const s=t.cards.flatMap(c=>{const a=c;return!a||typeof a.ref!="string"||!o(a.x)||!o(a.y)||!o(a.w)||a.w<=0?[]:[{ref:a.ref,x:a.x,y:a.y,w:a.w,h:o(a.h)&&a.h>0?a.h:0,...typeof a.color=="string"?{color:a.color}:{}}]});s.length===n.length&&(r.cards=s)}return Array.isArray(t.els)&&(r.els=t.els.filter(s=>!!s&&typeof s=="object"&&!Array.isArray(s))),Array.isArray(t.tree)&&(r.tree=t.tree.filter(s=>Array.isArray(s)&&typeof s[0]=="string"&&typeof s[1]=="string")),r}catch{return null}}const La=(e,t)=>({x:e.x-t,y:e.y-t,w:e.w+t*2,h:e.h+t*2}),il=(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 Ax({hostRef:e,vp:t,elements:n,ghost:r,onCenter:o}){const[,s]=v.useState(0);v.useEffect(()=>{const g=e.current;if(!g)return;let C=0;const I=new Set,N=new ResizeObserver(()=>$()),k=()=>{const J=new Set(g.querySelectorAll(".amx-ucard")),oe=g.querySelector(".ProseMirror");oe&&J.add(oe);for(const H of J)I.has(H)||(N.observe(H,{box:"border-box"}),I.add(H));for(const H of[...I])J.has(H)||(N.unobserve(H),I.delete(H))},$=()=>{cancelAnimationFrame(C),C=requestAnimationFrame(()=>{k(),s(J=>J+1)})},F=new MutationObserver($);return F.observe(g,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["data-x","data-y","data-w"]}),N.observe(g),$(),()=>{cancelAnimationFrame(C),F.disconnect(),N.disconnect()}},[e]);const c=e.current;if(!c)return null;const a=[];for(const[g,C]of pn(c))a.push({key:It(g),kind:"card",box:C});const i=hn(c);i&&a.push({key:he,kind:"main",box:i});const d=Tn(n),p=Mo(d,r);for(const g of d){if(g.kind==="connector")continue;const C=p.get(g.id);C&&a.push({key:gn(g.id),kind:g.kind==="frame"?"frame":"shape",box:C})}return f.jsx(qm,{hostRef:e,vp:t,items:a,onCenter:o})}function $x({path:e,vaultRoot:t=null,active:n,getView:r,main:o,mainStored:s,elements:c,tree:a,onElements:i,onTree:d,onMain:p,timeline:g,histStepRef:C,onCommit:I,saveFile:N,parseMd:k,serializeMd:$,onBlocksDeleted:F,revealSelection:J=0,readOnly:oe=!1,notePages:H,exportRef:te,storedMd:Re,children:Ve}){const m=v.useRef(null),{t:de}=Zt(),ot=Ef(t,e),[ce,be]=v.useState(()=>ei(ot)??{x:0,y:0,z:1}),fe=v.useRef(ce);fe.current=ce;const[Me,Ke]=v.useState(Hm),[me,Ae]=v.useState(Vm),[Ge,U]=v.useState(yi);v.useEffect(()=>Wm(()=>U(yi())),[]);const[ae,$e]=v.useState(Ym),T=v.useRef(ae);T.current=ae;const[Z,ie]=v.useState(Xm),we=v.useRef(Z);we.current=Z;const[Qe,qe]=v.useState(null),zt=v.useCallback(u=>{T.current=u,$e(u),Um(u)},[]),[st,it]=v.useState("select"),mt=v.useRef("select"),ct=v.useRef(oe);ct.current=oe;const dn=v.useCallback(u=>{mt.current=u,it(u)},[]),[ut,Wn]=v.useState([]),bt=v.useRef([]),lt=v.useCallback(u=>{const E=typeof u=="function"?u(bt.current):u;bt.current=E,Wn(E)},[]),[Ot,on]=v.useState(null),Xt=v.useRef(null),Sn=v.useCallback(u=>{Xt.current=u,on(u)},[]),[Zn,fo]=v.useState(null),en=v.useRef(null),Yn=v.useCallback(u=>{en.current=u,fo(u)},[]),En=v.useRef({held:!1,used:!1}),[Qn,Mr]=v.useState(!1);v.useEffect(()=>{const u=m.current;if(!Zn||!u)return;const E=u.dataset.amxDragscope;if(!E)return;const M=document.createElement("style");return M.textContent=Zn===he?`.amx-stage[data-amx-dragscope="${E}"] .ProseMirror{cursor:text;}`:`.amx-stage[data-amx-dragscope="${E}"] .amx-ucard[data-anchor="${CSS.escape(Zn)}"]{cursor:text;}`,document.head.appendChild(M),()=>M.remove()},[Zn]);const qr=v.useRef(0),[Hr,wn]=v.useState(null),[Mn,Rn]=v.useState(null),[hr,gr]=v.useState(null),[rt,jt]=v.useState(null),[yr,ir]=v.useState(null),[Vr,zr]=v.useState(!1),Vn=v.useRef(0),Oe=v.useCallback(()=>{cancelAnimationFrame(Vn.current),Vn.current=0,zr(!1)},[]);v.useEffect(()=>()=>cancelAnimationFrame(Vn.current),[]);const Vt=v.useRef({raf:0,animations:[]}),y=v.useCallback(()=>{cancelAnimationFrame(Vt.current.raf),Vt.current.raf=0;const u=Vt.current.animations.splice(0);for(const E of u)E.cancel()},[]),S=v.useCallback(u=>{const E=m.current;y(),!(!E||!u.length||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Vt.current.raf=requestAnimationFrame(()=>{Vt.current.raf=0;let M=0;const B=O=>{Vt.current.animations.push(O);const _=()=>{Vt.current.animations=Vt.current.animations.filter(V=>V!==O)};O.addEventListener("finish",_,{once:!0}),O.addEventListener("cancel",_,{once:!0})};for(const O of u){const _=E.querySelector(`.amx-ucard[data-anchor="${CSS.escape(O.anchor)}"]`),V=Math.hypot(O.x,O.y);if(!_||V<1)continue;const ee=Math.min(126,Math.max(0,O.depth-1)*42),l=Math.round(Math.max(420,Math.min(620,360+V*.34)));M=Math.max(M,ee+l);const h=_.animate([{transform:`translate(${-O.x}px, ${-O.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(${O.x*.035}px, ${O.y*.035}px) scale(1.003)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-O.x*.008}px, ${-O.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:l,delay:ee,fill:"backwards"});h.id="amx-card-arrange",B(h)}if(M>0)for(const O of E.querySelectorAll(".amx-el-conn, .amx-el-label")){const _=O.animate([{opacity:.12,offset:0},{opacity:.12,offset:.68},{opacity:1,offset:1,easing:"ease-out"}],{duration:M,fill:"backwards"});_.id="amx-card-arrange-line",B(_)}}))},[y]),L=v.useCallback((u,E)=>{const M=m.current,B=Math.hypot(E.x,E.y);y(),!(!M||B<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Vt.current.raf=requestAnimationFrame(()=>{Vt.current.raf=0;const O=l=>{Vt.current.animations.push(l);const h=()=>{Vt.current.animations=Vt.current.animations.filter(x=>x!==l)};l.addEventListener("finish",h,{once:!0}),l.addEventListener("cancel",h,{once:!0})},_=Math.round(Math.max(400,Math.min(520,350+B*.42))),V=M.querySelector(`.amx-ucard[data-anchor="${CSS.escape(u)}"]`);if(V){const l=V.animate([{transform:`translate(${-E.x}px, ${-E.y}px) scale(1.012)`,opacity:.94,boxShadow:"0 12px 32px rgb(0 0 0 / 24%)",offset:0,easing:"ease-in"},{transform:`translate(${-E.x*.54}px, ${-E.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(${E.x*.05}px, ${E.y*.05}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-E.x*.012}px, ${-E.y*.012}px) scale(1.001)`,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:.9,easing:"ease-out"},{transform:"translate(0, 0) scale(1)",opacity:1,boxShadow:"0 2px 10px rgb(0 0 0 / 12%)",offset:1}],{duration:_,fill:"none"});l.id="amx-card-attach",O(l)}const ee=M.querySelector(`.amx-el-conn[data-el="${CSS.escape(`t:${u}`)}"]`);if(ee){const l=ee.animate([{opacity:0,offset:0},{opacity:0,offset:.56},{opacity:1,offset:1,easing:"ease-out"}],{duration:_,fill:"backwards"});l.id="amx-card-attach-line",O(l)}}))},[y]);v.useEffect(()=>y,[y]);const[D,K]=v.useState(null),[X,ne]=v.useState(null);v.useEffect(()=>{Ot||K(null)},[Ot]);const G=new Set(ut),Q=v.useRef(!ei(ot));v.useEffect(()=>{n&&Mf(ot,ce)},[ot,ce,n]),v.useLayoutEffect(()=>{const u=m.current;!n||!Zn||!u||!document.activeElement||!u.contains(document.activeElement)||Kf()},[n,Zn,ce]);const q=v.useRef({getView:r,onCommit:I,onElements:i,onTree:d,onMain:p,timeline:g,elements:c,tree:a,main:o,mainStored:s,saveFile:N,parseMd:k,serializeMd:$,onBlocksDeleted:F,notePages:H,path:e,storedMd:Re});q.current={getView:r,onCommit:I,onElements:i,onTree:d,onMain:p,timeline:g,elements:c,tree:a,main:o,mainStored:s,saveFile:N,parseMd:k,serializeMd:$,onBlocksDeleted:F,notePages:H,path:e,storedMd:Re};const Ne=Tn(c),Fe=u=>{if(!u)return null;const E={x:u.x,y:u.y,w:u.w,...typeof u.h=="number"&&u.h>0?{h:u.h}:{}};return E.x!==0||E.y!==0||E.w!==Or||(E.h??0)>0?E:null},_e=()=>{const u=q.current;return{e:Lr(u.elements),t:Kt(u.tree),m:Fe(u.mainStored?u.main:null)}},Be=v.useRef(null),He=v.useRef({past:[],future:[]}),Ue=()=>He.current;v.useEffect(()=>{const u=_e(),E=JSON.stringify(u);if(!(Be.current!==null&&E===Be.current)){if(Be.current!==null)try{const M=JSON.parse(Be.current),B=(_,V)=>{let ee=M.t[_];const l=new Set([_]);for(;typeof ee=="string"&&ee&&!l.has(ee);){if(ee===V)return!0;l.add(ee),ee=M.t[ee]}return!1};if(JSON.stringify(u.e)===JSON.stringify(M.e)&&JSON.stringify(u.m)===JSON.stringify(M.m)&&Object.keys(u.t).length<=Object.keys(M.t).length&&Object.keys(u.t).every(_=>typeof M.t[_]<"u"&&(JSON.stringify(u.t[_])===JSON.stringify(M.t[_])||B(_,u.t[_])))){Be.current=E;return}}catch{}Be.current=E,He.current={past:[],future:[]},q.current.timeline.log.length=0,q.current.timeline.future.length=0}},[e,c,a,o,s]);const We=v.useCallback((u,E)=>{const M=q.current,B=_e(),O=JSON.stringify(B),_=JSON.stringify({e:u.e??B.e,t:u.t??B.t,m:u.m?Fe(u.m):B.m});if(_!==O){if(E?.snap!==!1){const V=Ue();V.past.push(O),V.past.length>nl&&V.past.shift(),V.future.length=0,M.timeline.log.push("fm"),M.timeline.future.length=0;const ee=M.getView();ee&&ee.dispatch(Ws(ee.state.tr))}Be.current=_,u.e&&M.onElements(u.e),u.t&&M.onTree(u.t),u.m&&M.onMain(u.m)}},[e]),Je=v.useCallback(u=>{const E=Lr(q.current.elements),M=u(E);M!==E&&We({e:M})},[We]),Ut=v.useCallback(u=>{const E=Ue(),M=u==="undo"?E.past:E.future,B=u==="undo"?E.future:E.past,O=M.pop();if(O==null)return!1;const _=q.current;B.push(JSON.stringify(_e()));const V=JSON.parse(O);return Be.current=O,_.onElements(V.e),_.onTree(V.t),_.onMain(V.m??{x:0,y:0,w:Or}),!0},[e]),Et=v.useCallback(()=>{const u=Ue();u.past.push(JSON.stringify(_e())),u.past.length>nl&&u.past.shift(),u.future.length=0;const E=q.current.timeline;E.log.push("fm"),E.future.length=0},[e]),vt=v.useCallback(u=>{const E=Kt(q.current.tree);return u.some(M=>typeof E[M]<"u"||Object.keys(E).some(B=>E[B]===M))},[]),Ze=v.useCallback(()=>{const u=q.current.timeline,E=u.log.length;if(E<2)return;const M=u.log[E-2],B=u.log[E-1];(M==="pm"&&B==="fm"||M==="fm"&&B==="pm")&&u.log.splice(E-2,2,"pair")},[]),Xn=v.useCallback(u=>{const E=q.current.timeline,M=u==="undo"?E.log:E.future,B=u==="undo"?E.future:E.log,O=()=>{const ee=q.current.getView();return!!ee&&(u==="undo"?Oa(ee.state):wd(ee.state))>0},_=()=>(u==="undo"?Ue().past:Ue().future).length>0,V=()=>{const ee=q.current.getView();return!!ee&&(u==="undo"?_a:Cl)(ee.state,ee.dispatch)};for(;M.length;){const ee=M[M.length-1];if(M.pop(),ee==="pair"){if(!O()||!_())continue;return Ut(u),V(),B.push(ee),!0}if(ee==="fm"){if(Ut(u))return B.push(ee),!0;continue}if(V())return B.push("pm"),!0}return V()},[Ut]);v.useEffect(()=>{if(C)return C.current=Xn,()=>{C.current===Xn&&(C.current=null)}},[C,Xn]);const At=v.useCallback((u,E)=>{const M=m.current,B=M?.getBoundingClientRect(),{x:O,y:_,z:V}=fe.current;if(!M||!B)return{x:0,y:0};const ee=Fn(M)||1;return{x:((u-B.left)/ee-O)/V,y:((E-B.top)/ee-_)/V}},[]),sn=v.useCallback(()=>{Oe();const u=m.current,E=r();if(!u||!E)return;const M=[...u.querySelectorAll(".amx-ucard, .amx-el-shape, .amx-el-frame, .amx-el-frame-bar, .amx-el-conn, .amx-el-label"),E.dom].map(ue=>ue.getBoundingClientRect());if(!M.length)return;const{x:B,y:O,z:_}=fe.current,V=u.getBoundingClientRect(),ee=Fn(u)||1,l=(ue,R)=>(ue/ee-R)/_,h=Math.min(...M.map(ue=>l(ue.left-V.left,B))),x=Math.min(...M.map(ue=>l(ue.top-V.top,O))),w=Math.max(...M.map(ue=>l(ue.right-V.left,B))),z=Math.max(...M.map(ue=>l(ue.bottom-V.top,O))),Y=w-h,se=z-x;if(Y<=0||se<=0)return;const ye=48,W=Math.max(Uo,Math.min(1,Math.min((V.width/ee-ye*2)/Y,(V.height/ee-ye*2)/se)));be({z:W,x:(V.width/ee-Y*W)/2-h*W,y:(V.height/ee-se*W)/2-x*W})},[r,Oe]),lr=v.useCallback(u=>{Oe();const E=m.current;if(!E)return;const{x:M,y:B,z:O}=fe.current,_=Math.max(Uo,Math.min($s,O*u));if(_===O)return;const V=Fn(E)||1,ee=E.getBoundingClientRect().width/V/2,l=E.getBoundingClientRect().height/V/2;be({z:_,x:ee-(ee-M)*_/O,y:l-(l-B)*_/O})},[Oe]),Wr=v.useCallback((u,E)=>{Oe();const M=m.current;if(!M)return;const B=Fn(M)||1,O=M.getBoundingClientRect(),_=fe.current.z;be({z:_,x:O.width/B/2-u*_,y:O.height/B/2-E*_})},[Oe]);v.useEffect(()=>{const u=m.current;if(!oe||!u)return;const E=()=>{const M=q.current.getView(),B=document.getSelection();if(!M||!B||B.isCollapsed||!B.rangeCount)return;const O=B.getRangeAt(0),_=l=>M.dom.contains(l.nodeType===3?l.parentNode:l),V=_(O.startContainer),ee=_(O.endContainer);if(!(!V&&!ee))try{const l=M.state.doc,h=V?M.posAtDOM(O.startContainer,O.startOffset):0,x=ee?M.posAtDOM(O.endContainer,O.endOffset):l.content.size,w=Pe.between(l.resolve(Math.min(h,x)),l.resolve(Math.max(h,x)));w.eq(M.state.selection)||M.dispatch(M.state.tr.setSelection(w))}catch{}};return u.addEventListener("copy",E,!0),()=>u.removeEventListener("copy",E,!0)},[oe]),v.useEffect(()=>{const u=m.current;if(!n||!u)return;const E=M=>{const B=M.detail?.rect;if(!B)return;const O=At(B.left+B.width/2,B.top+B.height/2);Wr(O.x,O.y),M.preventDefault()};return u.addEventListener("amx-reveal",E),()=>u.removeEventListener("amx-reveal",E)},[n,At,Wr]);const $o=v.useRef(sn);$o.current=sn,v.useEffect(()=>{if(!n||!Q.current)return;Q.current=!1;const u=setTimeout(()=>$o.current(),220);return()=>clearTimeout(u)},[n]),v.useEffect(()=>{n||(lt([]),dn("select"),Sn(null),jt(null),ir(null),Yn(null))},[n]),v.useEffect(()=>{if(!rt)return;const u=E=>{E.target?.closest?.(".ctx-menu")||jt(null)};return window.addEventListener("pointerdown",u,!0),window.addEventListener("contextmenu",u,!0),()=>{window.removeEventListener("pointerdown",u,!0),window.removeEventListener("contextmenu",u,!0)}},[rt]);const Bn=v.useCallback(u=>{const E=new Map;for(const[B,O]of pn(m.current))E.set(It(B),O);for(const[B,O]of Mo(Tn(q.current.elements),u))E.set(gn(B),O);const M=hn(m.current);return M&&E.set(he,M),E},[]),Kn=v.useRef(!1);v.useEffect(()=>()=>{Kn.current=!0},[]);const xr=v.useCallback(async(u,E,M)=>{const B=Tn(q.current.elements).find(V=>V.id===u);if(!B)return;const O=(B.kind==="connector"?B.label:B.kind==="frame"?B.title:B.text)??"",_=await qa(M,O);_==null||Kn.current||Tn(q.current.elements).some(V=>V.id===u)&&Je(V=>Ng(V,u,E,_.trim()))},[Je]),Yr=v.useCallback((u,E)=>{const M=q.current,B=M.getView(),O=new Set(u.filter(h=>h.startsWith("c:")).map(tt));let _=!1;if(B&&O.size){const h=E??"",x=new Map;for(const w of On(B))O.has(w.anchor)&&String(w.node.attrs.color??"")!==h&&x.set(w.anchor,{color:h});x.size&&(bo(B,x),M.onCommit(),_=!0)}const V=new Set(u.filter(h=>h.startsWith("e:")).map(tt));if(!V.size)return;const ee=Lr(q.current.elements),l=Rg(ee,V,E);l!==ee&&(We({e:l}),_&&Ze())},[We,Ze]),br=v.useCallback((u,E,M,B,O)=>{const _=q.current.getView(),V=_?.state.schema.nodes.amadeusCanvasCard,ee=_?.state.schema.nodes.paragraph;if(!_||!V||!ee)return null;const l=Er(_.state.doc),h={x:u,y:E,w:Jt,h:80},x=[...pn(m.current).values(),...Ps(q.current.elements)],w=hn(m.current);w&&x.push(w);const z=Go([h],x),Y=u+z.x,se=E+z.y,ye=O?.childCount?O:ee.create(null,B?_.state.schema.text(B):void 0),W=V.createAndFill({anchor:l,x:Math.round(Y),y:Math.round(se),w:Jt,h:0},ye);if(!W)return null;const ue=M?fu(_.state.doc,Kt(q.current.tree),M):_.state.doc.content.size;return oo(_,_.state.tr.insert(ue,W)),q.current.onCommit(l),lt([It(l)]),!B&&!O?.childCount&&ve.current.enterNodeEdit(It(l)),l},[Bn]),Xr=v.useCallback((u,E)=>{const M=q.current.saveFile;M&&u.forEach((B,O)=>{const _=B.name||Ce("canvasstage.upload.fileN",{n:O+1}),V=Ce("canvasstage.upload.uploading",{name:_}),ee=ve.current.addCardAt(E.x-Jt/2+O*24,E.y-24+O*24,void 0,V);ee&&M(B).then(l=>{const h=q.current.getView(),x=h?On(h).find(w=>w.anchor===ee&&w.node.textContent===V)??On(h).find(w=>w.node.textContent===V):null;!h||!x||(l?(zx(h,x.anchor,l,V),q.current.onCommit()):ve.current.removeSel([It(x.anchor)]))})})},[]),qn=v.useCallback((u,E,M=0)=>{const B=u.trim();if(!B)return null;const O=q.current.parseMd?.(B)??null;return ve.current.addCardAt(E.x-Jt/2+M*24,E.y-24+M*24,void 0,B,sl(O))},[]),Un=v.useCallback(u=>{const E=Kt(q.current.tree),M=u(E);return M===E?!1:(We({t:M}),!0)},[We]),er=v.useCallback(u=>u===he?hn(m.current):pn(m.current).get(u)??null,[]),Ur=v.useCallback((u,E,M,B,O=0)=>{const _=er(u);if(!_)return null;const V=Kt(q.current.tree),ee=V[u],l=E==="child"?u:typeof ee=="string"&&ee?ee:"",h=(l?wo(V,l):[u]).map(er).filter(Boolean),x=80,w=32,Y=E==="child"?M==="w"?_.x-B-x:_.x+_.w+x:h.length?Math.min(...h.map(R=>R.x)):_.x,se=h.length?Math.min(...h.map(R=>R.y))-w-O:_.y,ye=h.length?Math.max(...h.map(R=>R.y+R.h))+w:_.y,W=M==="n"?se:ye,ue=E==="child"?wo(V,u).length?W:_.y:W;return{parent:l,x:Math.round(Y),y:Math.round(ue)}},[er]),Gr=v.useCallback((u,E,M,B=80)=>{const O=er(u);if(!O)return null;const _=Kt(q.current.tree),V=_[u],ee=E==="child"?u:typeof V=="string"&&V?V:"",l=E==="child"?O:ee?er(ee):O;if(!l)return null;const h=q.current.getView(),x=h?On(h).map(Ee=>Ee.anchor):[],z=(ee?wo(_,ee):E==="child"?wo(_,u):x.filter(Ee=>typeof _[Ee]!="string"||!_[Ee])).map(Ee=>er(Ee)).filter(Boolean),Y=l.x+l.w/2,se=[...pn(m.current).values(),...Ps(q.current.elements)],ye=hn(m.current);ye&&se.push(ye);const W=80,ue=32;let R=null;for(const Ee of[1,-1]){const ke=z.filter(ln=>(ln.x+ln.w/2-Y)*Ee>0),Ye=Ee>0?l.x+l.w+W:l.x-W-M,$t=ke.length?Math.max(...ke.map(ln=>ln.y+ln.h))+ue:l.y,_t=Go([{x:Ye,y:$t,w:M,h:B}],se,{x:Ee,y:0}),kn=Math.hypot(_t.x,_t.y)*100+ke.length*32+(Ee<0?6:0);(!R||kn<R.score)&&(R={x:Ye+_t.x,y:$t+_t.y,score:kn})}return R?{parent:ee,x:Math.round(R.x),y:Math.round(R.y)}:null},[Bn,er]),Nr=v.useCallback((u,E)=>{const M=Gr(u,E,Jt);if(!M)return;const B=br(M.x,M.y,M.parent||void 0);B&&M.parent&&Un(O=>Bo(O,B,M.parent))&&Ze()},[Gr,br,Un,Ze]),Dn=v.useCallback((u,E)=>{const M=[...new Set(typeof u=="string"?[u]:u)],B=new Set(M),O=pn(m.current),_=M[0],V=_?O.get(_):null;if(!V||!_)return null;const ee=Ur(E.node,E.rel,E.side,V.w,V.h);if(!ee)return null;const l=Kt(q.current.tree),h=M.filter(Ee=>!(typeof l[Ee]=="string"&&B.has(l[Ee])));if(!h.length||h.includes(ee.parent))return null;const x=M.flatMap(Ee=>{const ke=O.get(Ee);return ke?[{anchor:Ee,box:ke}]:[]});if(!x.length)return null;const w=ee.x-V.x,z=ee.y-V.y,Y=x.map(({box:Ee})=>({...Ee,x:Ee.x+w,y:Ee.y+z})),se=[...O].filter(([Ee])=>!B.has(Ee)).map(([,Ee])=>Ee),ye=hn(m.current);ye&&se.push(ye),se.push(...Ps(q.current.elements));const W=Go(Y,se,{x:w,y:z}),ue=w+W.x,R=z+W.y;return{sources:M,sourceSet:B,boxes:O,primary:_,roots:h,moving:x,slot:ee,dx:ue,dy:R}},[Ur]),Jr=v.useCallback((u,E)=>{const M=[...new Set(typeof u=="string"?[u]:u)],B=M[0];if(!B)return null;const O=new Set(M),_=48,V=ye=>Math.min(38,Math.max(18,ye*.32)),ee=Kt(q.current.tree),l=ye=>{let W=ye;const ue=new Set;for(;typeof W=="string"&&W&&!ue.has(W);){if(O.has(W))return!0;ue.add(W),W=ee[W]}return!1},x=[...pn(m.current)].filter(([ye])=>!O.has(ye)&&!l(ye)),w=hn(m.current);w&&x.push([he,w]);let z=null;for(const[ye,W]of x){if(E.x<W.x-_||E.x>W.x+W.w+_||E.y<W.y-_||E.y>W.y+W.h+_)continue;const ue=V(W.w),R=V(W.h),Ee=18,ke=[["e",Math.abs(W.x+W.w-E.x),E.x>W.x+W.w?_:ue,E.y>=W.y-Ee&&E.y<=W.y+W.h+Ee],["w",Math.abs(E.x-W.x),E.x<W.x?_:ue,E.y>=W.y-Ee&&E.y<=W.y+W.h+Ee],["s",Math.abs(W.y+W.h-E.y),E.y>W.y+W.h?_:R,E.x>=W.x-Ee&&E.x<=W.x+W.w+Ee],["n",Math.abs(E.y-W.y),E.y<W.y?_:R,E.x>=W.x-Ee&&E.x<=W.x+W.w+Ee]];for(const[Ye,$t,kt,_t]of ke){if(!_t||$t>kt)continue;const kn=$t/Math.max(1,kt);(!z||kn<z.score)&&(z={node:ye,side:Ye,rel:Ye==="e"||Ye==="w"?"child":"sibling",score:kn})}}if(!z)return null;const Y={node:z.node,side:z.side,rel:z.rel};return Dn(M,Y)?{source:B,count:M.length,...Y}:null},[Dn]),Ar=v.useCallback((u,E)=>{const M=q.current.getView(),B=Dn(u,E);if(!M||!B)return!1;const{sources:O,sourceSet:_,boxes:V,primary:ee,roots:l,moving:h,slot:x,dx:w,dy:z}=B,Y=Kt(q.current.tree);let se=Kt(Y);for(const ue of l)if(delete se[ue],x.parent){const R=Bo(se,ue,x.parent);if(R===se)return!1;se=R}let ye=M.state.tr;for(const ue of On(M)){const R=V.get(ue.anchor);_.has(ue.anchor)&&R&&(ye=ye.setNodeMarkup(ue.pos,void 0,{...ue.node.attrs,x:Math.round(R.x+w),y:Math.round(R.y+z)}))}const W=l.filter(ue=>(typeof Y[ue]=="string"?Y[ue]:"")!==x.parent);for(const ue of W)ye=ol(ye,se,ue,x.parent);return oo(M,ye),q.current.onCommit(),W.length&&Un(R=>{let Ee=Kt(R);for(const ke of l)delete Ee[ke],x.parent&&(Ee=Bo(Ee,ke,x.parent));return Ee})&&Ze(),O.length===1?L(ee,{x:w,y:z}):S(h.map(({anchor:ue})=>({anchor:ue,x:w,y:z,depth:l.includes(ue)?1:2}))),lt(O.map(It)),!0},[Dn,Un,Ze,S,L]),vr=v.useCallback((u,E)=>{const M=Kt(q.current.tree);if(M[u]===E)return;const B=Bo(M,u,E);if(B===M)return;const O=q.current.getView();let _=!1;if(O){const V=ol(O.state.tr,B,u,E);V.steps.length&&(oo(O,V),_=!0)}We({t:B}),_&&Ze()},[We,Ze]),wr=v.useCallback((u,E,M)=>{const B=V=>V===he?he:V.startsWith("c:")?tt(V):null,O=B(u),_=B(E);O&&_&&_!==he&&!M?vr(_,O):Je(V=>Eg(V,u,E))},[vr,Je]),To=v.useCallback((u,E,M)=>{Je(B=>Mg(B,new Set(u),{fromEnd:E,toEnd:M}))},[Je]),an=v.useCallback(async()=>{const u=q.current.getView(),E=m.current;if(!u||!E||!n)return;const M=q.current.storedMd,B=x=>M?.(x.content)?.trim()||x.textBetween(0,x.content.size,`
49
-
50
- `),O=pn(E),_=On(u).map(x=>{const w=x.node.attrs,z=O.get(x.anchor)??{x:Number(w.x)||0,y:Number(w.y)||0,w:Number(w.w)||Jt,h:Number(w.h)||80};return{ref:x.anchor,...z,color:w.color,md:B(x.node)}}),V=[];u.state.doc.forEach(x=>{x.type.name!=="amadeusCanvasCard"&&V.push(x)});const ee=hn(E),l=V.length?M?.(Sr.fromArray(V))?.trim()??"":"",h=xx({cards:_,main:ee?{...ee,md:l}:null,elements:q.current.elements,tree:q.current.tree,pages:q.current.notePages?.(),sourcePath:e});try{const x=await wx(vn,e,bx(h));lo({text:Ce("canvasstage.export.done",{path:x}),level:"success"})}catch(x){lo({text:Ce("canvasstage.export.failed",{e:Ll(x)}),level:"error"})}},[n,e]);v.useEffect(()=>{if(!te||!n||oe)return;const u=()=>{an()};return te.current=u,()=>{te.current===u&&(te.current=null)}},[te,n,oe,an]);const tr=v.useCallback((u,E,M,B)=>{let O="";Je(_=>(O=fs(_,"s"),[..._,B?Ul(O,u,B):Sg(O,u,E,M)])),O&&lt([gn(O)])},[Je]),Nt=v.useCallback((u,E,M=480,B=320)=>{let O="";Je(_=>(O=fs(_,"f"),[..._,Tg(O,u,E,M,B)])),O&&lt([gn(O)])},[Je]),cn=v.useCallback(u=>{const E=Bn(null),M=u.map(V=>E.get(V)).filter(V=>!!V);if(!M.length)return;const B=32,O=Math.min(...M.map(V=>V.x))-B,_=Math.min(...M.map(V=>V.y))-B;Nt(O,_,Math.max(...M.map(V=>V.x+V.w))+B-O,Math.max(...M.map(V=>V.y+V.h))+B-_)},[Bn,Nt]),ur=v.useCallback(u=>{const E=Tn(q.current.elements),M=u.filter(_=>_.startsWith("e:")).map(_=>E.find(V=>V.id===tt(_))).filter(_=>_?.kind==="frame");if(!M.length)return u;const B=Bn(null),O=new Set(u);for(const _ of M)for(const[V,ee]of B)O.has(V)||ee.x>=_.x&&ee.y>=_.y&&ee.x+ee.w<=_.x+_.w&&ee.y+ee.h<=_.y+_.h&&O.add(V);return[...O]},[Bn]),nr=v.useCallback((u,E)=>{const M=u.filter(h=>h.startsWith("e:")).map(tt),B=u.filter(h=>h.startsWith("c:")).map(tt),O=u.filter(h=>h.startsWith("t:")).map(tt),_=B.length?q.current.getView():null,V=new Set(B),ee=_?On(_).filter(h=>V.has(h.anchor)).sort((h,x)=>x.pos-h.pos):[],l=ee.length>0&&(M.length>0||O.length>0||vt(B));if(l&&Et(),O.length){const h=Kt(q.current.tree),x=Kt(h);let w=!1;for(const z of O)typeof x[z]<"u"&&(delete x[z],w=!0);w&&We({t:x},l?{snap:!1}:void 0)}if(M.length){const h=Lr(q.current.elements),x=kg(h,new Set(M));x!==h&&We({e:x},l?{snap:!1}:void 0)}if(_&&ee.length){let h=_.state.tr;for(const x of ee)h=h.delete(x.pos,x.pos+x.node.nodeSize);oo(_,h),E?.assets!==!1&&q.current.onBlocksDeleted?.(Sr.from(ee.map(x=>x.node).reverse())),q.current.onCommit(),l&&Ze()}lt([])},[We,Et,vt,Ze]),Ln=v.useCallback(u=>{const E=q.current.getView(),M=new Set(ur(u).filter(W=>W!==he&&!W.startsWith("t:"))),B=new Set([...M].filter(W=>W.startsWith("c:")).map(tt)),O=E?On(E).filter(W=>B.has(W.anchor)):[],_=new Set(O.map(W=>W.anchor)),V=Lr(q.current.elements),ee=W=>{const ue=W&&typeof W=="object"?W.id:null;return typeof ue=="string"&&ue?ue:null},l=W=>!!W&&typeof W=="object"&&W.type==="connector",h=V.filter(W=>!l(W)&&M.has(gn(ee(W)??""))),x=new Set(h.map(ee)),w=W=>{const ue=Js(W);return!!ue&&(ue.ref?_.has(ue.ref):ue.id?x.has(ue.id):!1)},z=V.filter(W=>l(W)&&ee(W)&&w(W.from)&&w(W.to)),Y=Kt(q.current.tree),se=[..._].flatMap(W=>typeof Y[W]=="string"&&_.has(Y[W])?[[W,Y[W]]]:[]);if(!O.length&&!h.length&&!z.length)return null;const ye=[...h,...z];return{cards:O,els:ye,tree:se,keys:[...O.map(W=>It(W.anchor)),...ye.map(W=>gn(ee(W)))]}},[ur]),Gn=v.useCallback((u,E,M,B,O)=>{const _=q.current,V=_.getView(),ee=V?.state.schema.nodes.amadeusCanvasCard,l=V?.state.schema.nodes.paragraph;if(!V||!ee||!l)return;const h=new Map,x=[];let w=V.state.tr;for(const ke of u){const Ye=Er(w.doc),$t=Math.round(ke.x+B),kt=Math.round(ke.y+O);let _t=null;if(ke.node&&ke.node.type===ee)_t=ee.create({...ke.node.attrs,anchor:Ye,x:$t,y:kt},ke.node.content);else{const kn=sl(ke.md?.trim()?_.parseMd?.(ke.md.trim())??null:null)??l.create(null,ke.md?.trim()?V.state.schema.text(ke.md.trim()):void 0);_t=ee.createAndFill({anchor:Ye,x:$t,y:kt,w:Math.round(ke.w)||Jt,h:Math.round(ke.h)||0,color:typeof ke.color=="string"?ke.color:""},kn)}_t&&(w=w.insert(w.doc.content.size,_t),h.set(ke.ref,Ye),x.push(Ye))}const z=x.length>0;z&&(oo(V,w),x.forEach(ke=>_.onCommit(ke)));const Y=Lr(q.current.elements),se=new Map,ye=[],W=ke=>ke.type==="frame"?"f":ke.type==="connector"?"e":"s",ue=[];for(const ke of E){const Ye=ke;if(typeof Ye.id!="string"||!Ye.id)continue;if(Ye.type==="connector"){ue.push(Ye);continue}const $t=fs(Y,W(Ye));se.set(Ye.id,$t),Y.push({...Ye,id:$t,...typeof Ye.x=="number"?{x:Math.round(Ye.x+B)}:{},...typeof Ye.y=="number"?{y:Math.round(Ye.y+O)}:{}}),ye.push($t)}const R=ke=>{const Ye=Js(ke);if(!Ye)return null;const $t=ke;if(Ye.ref){const kt=h.get(Ye.ref);return kt?{...$t,ref:kt}:null}if(Ye.id){const kt=se.get(Ye.id);return kt?{...$t,id:kt}:null}return null};for(const ke of ue){const Ye=R(ke.from),$t=R(ke.to);if(!Ye||!$t)continue;const kt=fs(Y,"e");Y.push({...ke,id:kt,from:Ye,to:$t}),ye.push(kt)}let Ee=null;for(const[ke,Ye]of M){const $t=h.get(ke),kt=h.get(Ye);if(!$t||!kt)continue;const _t=Bo(Ee??Kt(q.current.tree),$t,kt);_t!==Ee&&(Ee=_t)}(ye.length||Ee)&&(We({...ye.length?{e:Y}:{},...Ee?{t:Ee}:{}}),z&&Ze()),lt([...x.map(It),...ye.map(gn)])},[We,Ze]),A=v.useCallback((u,E)=>{u.clearData();const M=Ln(E);if(!M)return Da=null,u.setData("text/plain",""),null;const B=q.current.serializeMd,O=M.cards.map(h=>B?.(h.node.content)?.trim()||h.node.textBetween(0,h.node.content.size,`
51
-
52
- `)),_=M.els.flatMap(h=>{const x=h,w=x.type==="connector"?x.label:x.type==="frame"?x.title:x.text;return typeof w=="string"&&w.trim()?[w.trim()]:[]});u.setData("text/plain",[...O,..._].join(`
53
-
54
- `));const V=`t${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,ee=M.cards.map(h=>{const x=h.node.attrs;return{ref:h.anchor,x:Number(x.x)||0,y:Number(x.y)||0,w:Number(x.w)||Jt,h:Number(x.h)||0,...typeof x.color=="string"&&x.color?{color:x.color}:{}}}),l={token:V,mds:O,cards:ee,...M.els.length?{els:M.els}:{},...M.tree.length?{tree:M.tree}:{}};try{u.setData(cl,JSON.stringify(l))}catch{}return Da={token:V,nodes:M.cards.map(h=>h.node)},qr.current=0,M},[Ln]),P=v.useCallback((u,E)=>{const M=q.current.getView();if(!M)return!1;const B=Da,O=!!B&&B.token===u.token&&(B.nodes.length===0||B.nodes[0].type===M.state.schema.nodes.amadeusCanvasCard);let _;if(O&&B)_=B.nodes.map(h=>({ref:String(h.attrs.anchor),x:Number(h.attrs.x)||0,y:Number(h.attrs.y)||0,w:Number(h.attrs.w)||Jt,h:Number(h.attrs.h)||0,node:h}));else if(u.cards)_=u.cards.map((h,x)=>({...h,md:u.mds[x]}));else{const h=u.mds.filter(x=>x.trim());return h.length?(h.forEach((x,w)=>ve.current.addCardMd(x,E,w)),!0):!1}const V=u.els??[],ee=_.map(h=>h.x),l=_.map(h=>h.y);for(const h of V){const x=h;typeof x.x=="number"&&typeof x.y=="number"&&(ee.push(x.x),l.push(x.y))}return ee.length?(Gn(_,V,u.tree??[],E.x-Math.min(...ee),E.y-Math.min(...l)),!0):!1},[Gn]),le=v.useCallback(u=>{const E=Ln(u);E&&Gn(E.cards.map(M=>({ref:M.anchor,x:Number(M.node.attrs.x)||0,y:Number(M.node.attrs.y)||0,w:Number(M.node.attrs.w)||Jt,h:Number(M.node.attrs.h)||0,node:M.node})),E.els,E.tree,ti,ti)},[Ln,Gn]),pe=v.useCallback(u=>{const E=M=>{M.clipboardData&&(M.preventDefault(),M.stopImmediatePropagation(),A(M.clipboardData,u))};document.addEventListener("copy",E,{capture:!0,once:!0});try{document.execCommand("copy")}finally{document.removeEventListener("copy",E,{capture:!0})}m.current?.focus({preventScroll:!0})},[A]),Te=v.useCallback((u,E)=>{const M=q.current.getView();if(!M||u!==he&&!u.startsWith("c:"))return;let B=null,O=null;if(u===he)M.state.doc.forEach((_,V)=>{B==null&&_.type.name!=="amadeusCanvasCard"&&(B=Math.min(M.state.doc.content.size,V+_.nodeSize-1))}),O=_=>{const V=M.state.doc.resolve(_);for(let ee=V.depth;ee>0;ee--)if(V.node(ee).type.name==="amadeusCanvasCard")return!1;return!0};else{const _=On(M).find(V=>V.anchor===tt(u));_&&(B=Math.min(M.state.doc.content.size,_.pos+_.node.nodeSize-1),O=V=>V>_.pos&&V<_.pos+_.node.nodeSize)}if(B!=null){if(E){const _=M.posAtCoords({left:E.x,top:E.y});_&&O?.(_.pos)&&(B=_.pos)}try{M.dispatch(Ws(M.state.tr.setSelection(Pe.near(M.state.doc.resolve(B),-1))))}catch{}Yn(u===he?he:tt(u)),M.focus()}},[]),De=v.useCallback((u,E=!1)=>{const M=m.current;if(!M)return;const B=u===he?hn(M):u.startsWith("c:")?pn(M).get(tt(u))??null:null;if(!B)return;const O=Fn(M)||1,_=M.getBoundingClientRect(),V=_.width/O,ee=_.height/O,l=Math.max(Uo,Math.min(1.5,$s,V*.62/Math.max(1,B.w),ee*.72/Math.max(1,B.h))),h={z:l,x:V/2-(B.x+B.w/2)*l,y:ee/2-(B.y+B.h/2)*l},x={...fe.current};if(Oe(),window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)fe.current=h,be(h);else{const w=Math.hypot(h.x-x.x,h.y-x.y),z=Math.round(Math.max(460,Math.min(560,420+w*.12+Math.abs(h.z-x.z)*120))),Y=performance.now();zr(!0);const se=ye=>{const W=Math.min(1,(ye-Y)/z),ue=W>=1?1:1-Math.exp(-8*W)*(Math.cos(6*W)+8/6*Math.sin(6*W)),R={x:x.x+(h.x-x.x)*ue,y:x.y+(h.y-x.y)*ue,z:x.z+(h.z-x.z)*ue};fe.current=R,be(R),W<1?Vn.current=requestAnimationFrame(se):(Vn.current=0,zr(!1))};Vn.current=requestAnimationFrame(se)}E||(Yn(null),lt([u]),M.focus({preventScroll:!0}))},[Oe]),ge=v.useCallback(u=>{const E=m.current,M=q.current.getView();if(!E||!M)return!1;const B=Kt(q.current.tree),O=pn(E),_=new Set(O.keys()),V=at=>wo(B,at).filter(et=>_.has(et)).sort((et,Tt)=>(O.get(et)?.y??0)-(O.get(Tt)?.y??0)),ee=[],l=new Map,h=new Set([u]),x=(at,et)=>{for(const Tt of V(at))h.has(Tt)||(h.add(Tt),ee.push(Tt),l.set(Tt,et+1),x(Tt,et+1))};if(x(u,0),!ee.length)return!1;const w=u===he?hn(E):O.get(u);if(!w)return!1;const z=96,Y=32,se=new Map,ye=at=>{const et=at===u?w:O.get(at);if(!et)return 0;const Tt=V(at).filter(In=>In!==u&&h.has(In)),xn=Tt.reduce((In,fn)=>In+ye(fn),0)+Math.max(0,Tt.length-1)*Y,Lt=Math.max(et.h,xn);return se.set(at,Lt),Lt};ye(u);const W=V(u).filter(at=>at!==u&&h.has(at)),ue=at=>{const et=new Map,Tt=(xn,Lt,In)=>{const fn=V(xn).filter(Gt=>Gt!==u&&h.has(Gt));if(!fn.length)return;const dt=fn.reduce((Gt,Nn)=>Gt+(se.get(Nn)??ye(Nn)),0)+(fn.length-1)*Y;let mn=Lt.y+Lt.h/2-dt/2;for(const Gt of fn){const Nn=O.get(Gt);if(!Nn)continue;const mo=se.get(Gt)??Nn.h,Tr={x:In>0?Lt.x+Lt.w+z:Lt.x-z-Nn.w,y:mn+(mo-Nn.h)/2,w:Nn.w,h:Nn.h};et.set(Gt,Tr),Tt(Gt,Tr,In),mn+=mo+Y}};for(const xn of[1,-1]){const Lt=W.filter(dt=>at.get(dt)===xn),In=Lt.reduce((dt,mn)=>dt+(se.get(mn)??ye(mn)),0)+Math.max(0,Lt.length-1)*Y;let fn=w.y+w.h/2-In/2;for(const dt of Lt){const mn=O.get(dt);if(!mn)continue;const Gt=se.get(dt)??mn.h,Nn={x:xn>0?w.x+w.w+z:w.x-z-mn.w,y:fn+(Gt-mn.h)/2,w:mn.w,h:mn.h};et.set(dt,Nn),Tt(dt,Nn,xn),fn+=Gt+Y}}return et},R=[],Ee=new Set,ke=at=>{const et=at.join(",");Ee.has(et)||(Ee.add(et),R.push(new Map(W.map((Tt,xn)=>[Tt,at[xn]]))))};if(W.length<=9)for(let at=0;at<2**W.length;at++)ke(W.map((et,Tt)=>at&1<<Tt?-1:1));else ke(W.map((at,et)=>et%2?-1:1)),ke(W.map((at,et)=>et<Math.ceil(W.length/2)?1:-1)),ke(W.map(()=>1)),ke(W.map(()=>-1));ke(W.map(at=>(O.get(at)?.x??w.x)<w.x?-1:1));const Ye=Bn(null),$t=new Set(ee.map(It)),kt=[...Ye].filter(([at])=>!$t.has(at)).map(([,at])=>La(at,24));let _t=null;for(const at of R){const et=W.filter(dt=>at.get(dt)===-1).length;if(W.length>1&&(et===0||et===W.length))continue;const Tt=ue(at),xn=[...Tt.values()],Lt=Math.min(...xn.map(dt=>dt.y)),In=Math.max(...xn.map(dt=>dt.y+dt.h)),fn=new Set([0]);for(let dt=1;dt<=20;dt++)fn.add(dt*72),fn.add(-dt*72);for(const dt of kt)fn.add(Math.ceil(dt.y+dt.h+12-Lt)),fn.add(Math.floor(dt.y-12-In));kt.length&&(fn.add(Math.ceil(Math.max(...kt.map(dt=>dt.y+dt.h))+12-Lt)),fn.add(Math.floor(Math.min(...kt.map(dt=>dt.y))-12-In)));for(const dt of[...fn].sort((mn,Gt)=>Math.abs(mn)-Math.abs(Gt))){const mn=new Map([...Tt].map(([Jn,rr])=>[Jn,{...rr,y:rr.y+dt}]));let Gt=0;for(const Jn of mn.values())for(const rr of kt)il(La(Jn,12),rr)&&Gt++;const Nn=Jn=>{const rr=W.filter(dr=>at.get(dr)===Jn).map(dr=>se.get(dr)??0);return rr.reduce((dr,Qr)=>dr+Qr,0)+Math.max(0,rr.length-1)*Y},mo=Nn(1),Tr=Nn(-1),Ss=[...mn].reduce((Jn,[rr,dr])=>{const Qr=O.get(rr);return Jn+(Qr?Math.hypot(dr.x-Qr.x,dr.y-Qr.y):0)},0),Yt=Gt*1e6+Math.abs(dt)+Math.max(mo,Tr)*.18+Math.abs(mo-Tr)*.04+Ss*.002+et*2;(!_t||Yt<_t.score)&&(_t={plan:mn,score:Yt})}}if(!_t)return!1;const kn=new Map([..._t.plan].map(([at,et])=>[at,{x:Math.round(et.x),y:Math.round(et.y)}])),ln=[...kn].flatMap(([at,et])=>{const Tt=O.get(at);return Tt?[{anchor:at,x:et.x-Tt.x,y:et.y-Tt.y,depth:l.get(at)??1}]:[]});return bo(M,kn),S(ln),q.current.onCommit(),E.focus({preventScroll:!0}),!0},[Bn,S]);v.useEffect(()=>{const u=m.current;!n||!u||document.activeElement&&u.contains(document.activeElement)||u.focus({preventScroll:!0})},[n]);const ve=v.useRef({mutate:Je,writeFm:We,mergePair:Ze,pushFmCheckpoint:Et,treeTouches:vt,removeSel:nr,editText:xr,boxesNow:Bn,fit:sn,zoomBy:lr,addCardAt:br,addShapeAt:tr,addFrame:Nt,addRelated:Nr,attachHit:Jr,applyAttach:Ar,setNodeParent:vr,expandFrames:ur,enterNodeEdit:Te,focusNode:De,arrangeChildren:ge,stopArrangeMotion:y,stopFocusMotion:Oe,dropFilesAt:Xr,addCardMd:qn,writeClip:A,pastePayload:P,linkNodes:wr});ve.current={mutate:Je,writeFm:We,mergePair:Ze,pushFmCheckpoint:Et,treeTouches:vt,removeSel:nr,editText:xr,boxesNow:Bn,fit:sn,zoomBy:lr,addCardAt:br,addShapeAt:tr,addFrame:Nt,addRelated:Nr,attachHit:Jr,applyAttach:Ar,setNodeParent:vr,expandFrames:ur,enterNodeEdit:Te,focusNode:De,arrangeChildren:ge,stopArrangeMotion:y,stopFocusMotion:Oe,dropFilesAt:Xr,addCardMd:qn,writeClip:A,pastePayload:P,linkNodes:wr},v.useEffect(()=>{const u=m.current;if(!n||!u||typeof ResizeObserver>"u")return;const E=new Set,M=new WeakMap;let B=0,O=!1;const _=()=>{if(B=0,O)return;const x=en.current,w=q.current.getView();if(!x||!w)return;const z=pn(u),Y=x===he?hn(u):z.get(x);if(!Y)return;const se=[...z].filter(([R,Ee])=>R!==x&&il(La(Y,18),Ee));if(!se.length)return;const ye=new Map(z),W=new Map,ue=[];for(const[R,Ee]of se){const ke=[...ye].filter(([kn])=>kn!==R).map(([,kn])=>kn),Ye=hn(u);Ye&&x!==he&&ke.push(Ye),ke.push(...Ps(q.current.elements));const $t={x:Ee.x+Ee.w/2-(Y.x+Y.w/2),y:Ee.y+Ee.h/2-(Y.y+Y.h/2)},kt=Go([Ee],ke,$t);if(!kt.x&&!kt.y)continue;const _t={...Ee,x:Ee.x+kt.x,y:Ee.y+kt.y};ye.set(R,_t),W.set(R,{x:Math.round(_t.x),y:Math.round(_t.y)}),ue.push({anchor:R,x:kt.x,y:kt.y,depth:1})}W.size&&(O=!0,bo(w,W,!1),S(ue),q.current.onCommit(),requestAnimationFrame(()=>{O=!1}))},V=()=>{window.clearTimeout(B),B=window.setTimeout(_,90)},ee=new ResizeObserver(x=>{for(const w of x){const z=w.target,Y={w:z.offsetWidth,h:z.offsetHeight},se=M.get(z);if(M.set(z,Y),se&&(se.w!==Y.w||se.h!==Y.h)){const ye=z.classList.contains("amx-ucard")?z.dataset.anchor:he;ye&&ye===en.current&&V()}}}),l=()=>{const x=new Set(u.querySelectorAll(".amx-ucard")),w=u.querySelector(".ProseMirror");w&&x.add(w);for(const z of x)E.has(z)||(E.add(z),M.set(z,{w:z.offsetWidth,h:z.offsetHeight}),ee.observe(z,{box:"border-box"}));for(const z of[...E])x.has(z)||(E.delete(z),ee.unobserve(z))};l();const h=new MutationObserver(l);return h.observe(u,{subtree:!0,childList:!0}),()=>{window.clearTimeout(B),h.disconnect(),ee.disconnect()}},[n,e,S]),v.useEffect(()=>{if(!n||J<=0)return;Q.current=!1;let u=0;const E=requestAnimationFrame(()=>{u=requestAnimationFrame(()=>{const M=q.current.getView();if(!M)return;const{$from:B}=M.state.selection;let O=he;for(let _=B.depth;_>0;_--){const V=B.node(_);if(V.type.name==="amadeusCanvasCard"){O=It(String(V.attrs.anchor));break}}lt([O]),Yn(O===he?he:tt(O)),ve.current.focusNode(O,!0),M.focus()})});return()=>{cancelAnimationFrame(E),cancelAnimationFrame(u)}},[n,J]),v.useEffect(()=>{const u=m.current;if(!u||!n)return;const E=()=>q.current.getView(),M=b=>q.current.onCommit(b),B=()=>u.focus({preventScroll:!0}),O=`s${++Mx}`;u.dataset.amxDragscope=O;const _=document.createElement("style");document.head.appendChild(_);let V=[],ee=0;const l=(b,j=!1)=>`left:${b.x}px!important;top:${b.y}px!important;${j&&"w"in b&&"h"in b?`width:${b.w}px!important;height:${b.h}px!important;`:""}`,h=`.amx-stage[data-amx-dragscope="${O}"] .unified-gutter{visibility:hidden!important;pointer-events:none!important}`,x=(b,j)=>{const re=[];for(const Se of b){const xe=CSS.escape(Se.anchor);re.push(`.amx-stage[data-amx-dragscope="${O}"] .amx-ucard[data-anchor="${xe}"]{${Se.decl}}`),re.push(`.amx-stage[data-amx-dragscope="${O}"] .amx-el-selbox[data-anchor="${xe}"]{${l(Se.selection)}}`)}j&&re.push(`.amx-stage[data-amx-dragscope="${O}"] .amx-el-selbox[data-main-sel]{${l(j)}}`),re.push(h),_.textContent=re.join(`
55
- `)},w=(b,j,re)=>{const Se=b===he?`.amx-stage[data-amx-dragscope="${O}"] .ProseMirror:not(.unified-embed .ProseMirror){${j}}`:`.amx-stage[data-amx-dragscope="${O}"] .amx-ucard[data-anchor="${CSS.escape(b)}"]{${j}}`,xe=b===he?`.amx-stage[data-amx-dragscope="${O}"] .amx-el-selbox[data-main-sel]{${l(re,!0)}}`:`.amx-stage[data-amx-dragscope="${O}"] .amx-el-selbox[data-anchor="${CSS.escape(b)}"]{${l(re,!0)}}`;_.textContent=`${Se}
56
- ${xe}
57
- ${h}`},z="cursor:grabbing;opacity:.94;box-shadow:0 12px 32px rgb(0 0 0 / 24%);z-index:1;",Y=()=>{_.textContent=""},se=()=>{cancelAnimationFrame(ee),ee=0;for(const b of V)b.cancel();V=[]},ye=(b,j,re,Se="amx-card-repel")=>{const xe=Math.hypot(re.x,re.y);if(xe<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;se();const Ie=Math.round(Math.max(340,Math.min(480,320+xe*.55))),Le=[{transform:`translate(${-re.x}px, ${-re.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(${re.x*.06}px, ${re.y*.06}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-re.x*.015}px, ${-re.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}];ee=requestAnimationFrame(()=>{ee=0;const nt=b.map(pt=>u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(pt)}"]`)).filter(pt=>!!pt);if(j){const pt=u.querySelector(".ProseMirror");pt&&nt.push(pt)}for(const pt of nt){const je=pt.animate(Le,{duration:Ie,fill:"none"});je.id=Se,V.push(je);const Xe=()=>{V=V.filter(ht=>ht!==je)};je.addEventListener("finish",Xe,{once:!0}),je.addEventListener("cancel",Xe,{once:!0})}})},W=(b,j,re)=>{Math.max(Math.abs(j.x-re.x),Math.abs(j.y-re.y),Math.abs(j.w-re.w),Math.abs(j.h-re.h))<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(se(),ee=requestAnimationFrame(()=>{ee=0;const xe=b===he?u.querySelector(".ProseMirror"):u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(b)}"]`);if(!xe)return;const Ie=b===he?{marginLeft:`${j.x}px`,marginTop:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`},Le=b===he?{marginLeft:`${re.x}px`,marginTop:`${re.y}px`,width:`${re.w}px`,height:`${re.h}px`}:{left:`${re.x}px`,top:`${re.y}px`,width:`${re.w}px`,height:`${re.h}px`},nt=xe.animate([Ie,Le],{duration:220,easing:"cubic-bezier(0.2, 0.78, 0.28, 1)",fill:"none"});nt.id="amx-card-snap",V.push(nt);const pt=()=>{V=V.filter(je=>je!==nt)};nt.addEventListener("finish",pt,{once:!0}),nt.addEventListener("cancel",pt,{once:!0})}))},ue=b=>{if(b.target?.closest?.(".amx-stage-minimap"))return;ve.current.stopFocusMotion(),b.preventDefault();const{x:j,y:re,z:Se}=fe.current,xe=Fn(u)||1;if(b.metaKey||b.ctrlKey){const Ie=b.ctrlKey&&!b.metaKey?Cx:1,Le=Math.max(Uo,Math.min($s,Se*Math.exp(-b.deltaY*Ie/300))),nt=u.getBoundingClientRect(),pt=(b.clientX-nt.left)/xe,je=(b.clientY-nt.top)/xe;be({z:Le,x:pt-(pt-j)*Le/Se,y:je-(je-re)*Le/Se})}else{const Ie=b.shiftKey&&!b.deltaX?b.deltaY:b.deltaX,Le=b.shiftKey?0:b.deltaY;be({z:Se,x:j-Ie/xe,y:re-Le/xe})}};u.addEventListener("wheel",ue,{passive:!1});let R=null,Ee=-1;const ke=b=>{Ee=b;try{u.setPointerCapture(b)}catch{}},Ye=b=>{try{u.hasPointerCapture(b)&&u.releasePointerCapture(b)}catch{}},$t=()=>Bf/(fe.current.z*(Fn(u)||1)),kt=(b,j,re)=>{const Se=[];for(const[Ie,Le]of pn(u))b.has(Ie)||Se.push(Le);const xe=j?null:hn(u);xe&&Se.push(xe);for(const[Ie,Le]of Mo(Tn(q.current.elements),null))re.has(Ie)||Se.push(Le);return Se},_t=(b,j)=>{const re=document.elementFromPoint(b,j);if(!re||!u.contains(re))return null;const Se=re.closest(os);if(Se?.dataset.el)return gn(Se.dataset.el);const xe=re.closest("[data-card-grip]");if(xe?.dataset.cardGrip)return xe.dataset.cardGrip===he?he:It(xe.dataset.cardGrip);const Ie=re.closest(".amx-ucard");return Ie?.dataset.anchor?It(Ie.dataset.anchor):re.closest(".ProseMirror")?he:null},kn=b=>b===u||b.classList.contains("amx-stage-inner")||b.classList.contains("amx-el-layer"),ln=new Map;let at=null,et=null,Tt=0,xn=null,Lt=ni;const In=()=>{Jn();const b=R;R=null,b&&b.kind!=="pan"&&eo(b)},fn=()=>{const[b,j]=[...ln.keys()],re=ln.get(b),Se=ln.get(j);if(!re||!Se)return null;const xe=Fn(u)||1,Ie=u.getBoundingClientRect();return{x:((re.x+Se.x)/2-Ie.left)/xe,y:((re.y+Se.y)/2-Ie.top)/xe,d:Math.hypot(re.x-Se.x,re.y-Se.y)/xe,ids:`${b}/${j}`}},dt=()=>{const b=fn();if(!b)return;const{x:j,y:re,z:Se}=fe.current;et={d0:Math.max(1,b.d),z0:Se,sx:(b.x-j)/Se,sy:(b.y-re)/Se,ids:b.ids}},mn=()=>{const b=fn();if(!b||!et)return;if(b.ids!==et.ids){dt();return}const j=Math.max(Uo,Math.min($s,et.z0*b.d/et.d0));be({z:j,x:b.x-et.sx*j,y:b.y-et.sy*j})},Gt=()=>{Tt&&window.clearTimeout(Tt),Tt=0,xn=null},Nn=b=>{const j=b.target,{clientX:re,clientY:Se}=b;xn={x:re,y:Se},Tt=window.setTimeout(()=>{Tt=0,xn=null,Nc(j,re,Se)==="open"&&In()},Df)},mo=b=>{const j=E(),re=j?On(j).map(Le=>Le.anchor):[],Se=new Set([...re,he]),xe=Kt(q.current.tree);return[b===he?he:It(b),...re.filter(Le=>Gl(xe,Le,b,Se)).map(It)]},Tr=(b,j)=>{const re=bt.current;if(j.shiftKey||j.metaKey||j.ctrlKey){const Se=j.shiftKey&&(b===he||b.startsWith("c:"))?mo(b===he?he:tt(b)):[b],xe=re.includes(b)?re.filter(Ie=>!Se.includes(Ie)):[...re,...Se.filter(Ie=>!re.includes(Ie))];return lt(xe),xe.includes(b)?xe:null}return re.includes(b)?re:(lt([b]),[b])},Ss=b=>{jt(null);const j=b.target;if(j.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;if(se(),ve.current.stopArrangeMotion(),ve.current.stopFocusMotion(),b.pointerType==="touch"){if(ln.set(b.pointerId,{x:b.clientX,y:b.clientY}),Gt(),ln.size>=2){b.preventDefault(),In(),dt();return}Nn(b)}if(et)return;Lt=b.pointerType==="touch"?ri/(fe.current.z*(Fn(u)||1)):ni;const re=b.button===1;if(b.button!==0&&!re)return;const Se=mt.current,xe=At(b.clientX,b.clientY);if(ct.current){if(j.closest(`${tl}, .wikilink`))return;const xt=performance.now(),Mt=at;if(at=b.pointerType==="mouse"?{t:xt,x:b.clientX,y:b.clientY}:null,Mt&&xt-Mt.t<500&&Math.hypot(b.clientX-Mt.x,b.clientY-Mt.y)<6&&j.closest(".ProseMirror"))return;b.preventDefault(),R={kind:"pan",x0:b.clientX,y0:b.clientY,vx:fe.current.x,vy:fe.current.y},ke(b.pointerId);return}const Ie=en.current,Le=En.current.held;Le&&(En.current.used=!0);const nt=Se==="pan"||b.altKey||re||Le,pt=Se!=="select"&&!nt,je=Ie===he?!!j.closest(".ProseMirror")&&!j.closest(".amx-ucard"):!!j.closest(`.amx-ucard[data-anchor="${CSS.escape(Ie??"")}"]`);if(Ie&&!nt&&(pt||!je)&&Yn(null),nt){b.preventDefault(),R={kind:"pan",x0:b.clientX,y0:b.clientY,vx:fe.current.x,vy:fe.current.y},ke(b.pointerId);return}if(Ra.has(Se)){b.preventDefault(),R={kind:"create",tool:Se,x0:xe.x,y0:xe.y,x1:xe.x,y1:xe.y},ke(b.pointerId);return}if(b.pointerType==="touch"&&(Se==="card"||ss[Se])){b.preventDefault(),R={kind:"create",tool:Se,x0:xe.x,y0:xe.y,x1:xe.x,y1:xe.y},ke(b.pointerId);return}if(ss[Se]){b.preventDefault(),ve.current.addShapeAt(ss[Se],xe.x,xe.y),dn("select"),B();return}if(Se==="card"){b.preventDefault();const xt=ve.current.addCardAt(xe.x-Jt/2,xe.y-24);dn("select"),xt||B();return}const Xe=j.closest("[data-grip]"),ht=j.closest("[data-card-grip][data-card-edge]"),Ft=j.closest(os),gt=j.closest(".amx-ucard"),An=j.closest(".ProseMirror"),fr=!gt&&!Ft&&!!An&&j===An,kr=!gt&&!Ft&&!!An&&j!==An,po=!!gt&&j===gt,Pn=gt?.dataset.anchor??null;if(Se==="select"&&ht?.dataset.cardGrip&&ht.dataset.cardEdge){const xt=ht.dataset.cardGrip,Mt=xt===he,nn=Mt?hn(u):pn(u).get(xt),rn=Mt?null:E(),Hn=rn?On(rn).find(or=>or.anchor===xt):null;nn&&(Mt||Hn)&&(b.preventDefault(),B(),lt([Mt?he:It(xt)]),R={kind:"card-size",key:xt,edge:ht.dataset.cardEdge,b0:nn,h0:Mt?Number(q.current.main.h)||0:Number(Hn.node.attrs.h)||0,x0:xe.x,y0:xe.y,dx:0,dy:0,next:nn},ke(b.pointerId));return}const ho=Se==="select"?j.closest("[data-link-from]"):null;if(ho?.dataset.linkFrom){b.preventDefault(),B(),R={kind:"link",from:ho.dataset.linkFrom,x0:xe.x,y0:xe.y},ke(b.pointerId);return}const to=Se==="select"?j.closest("[data-conn-end]"):null;if(to?.dataset.connEnd&&to.dataset.el){const xt=Tn(q.current.elements).find(rn=>rn.id===to.dataset.el),Mt=to.dataset.connEnd==="from"?"from":"to",nn=xt?.kind==="connector"?xo(Mt==="from"?xt.to:xt.from):null;b.preventDefault(),B(),xt&&nn&&(R={kind:"reconnect",id:xt.id,end:Mt,fixed:nn,x0:xe.x,y0:xe.y},ke(b.pointerId));return}const Ro=j.closest(tl)?Pn??(An?he:null):null;if(Se==="select"&&Ro){Yn(Ro);return}const Do=gt&&Pn?Pn:kr?he:null;Se==="select"&&Do&&en.current!==Do&&Ex(j,b.clientX)&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("canvasstage.toast.needEdit")}}));const yt=b.pointerType==="touch"&&Se==="select"?Ft?.dataset.el?gn(Ft.dataset.el):Pn?It(Pn):!gt&&An?he:null:null;if(yt&&!bt.current.includes(yt)&&en.current!==(Pn??he)){b.preventDefault(),R={kind:"pan",x0:b.clientX,y0:b.clientY,vx:fe.current.x,vy:fe.current.y,tapKey:yt},ke(b.pointerId);return}if(gt&&Pn&&!po&&Se==="select"){if(en.current===Pn)return;b.preventDefault(),B();const xt=b.shiftKey||b.metaKey||b.ctrlKey,Mt=It(Pn),nn=Tr(Mt,b);if(!nn)return;const rn=nn,Hn=[];for(const or of rn){if(!or.startsWith("c:"))continue;const mr=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(tt(or))}"]`);mr&&Hn.push({anchor:tt(or),ox:Number(mr.dataset.x)||0,oy:Number(mr.dataset.y)||0})}R={kind:"move",cards:Hn,ids:new Set(rn),hit:Mt,x0:xe.x,y0:xe.y,dx:0,dy:0,mainStart:null,mainEl:null,additive:xt},ke(b.pointerId);return}if(kr&&Se==="select"){if(en.current===he)return;b.preventDefault(),B();const xt=b.shiftKey||b.metaKey||b.ctrlKey,Mt=Tr(he,b);if(!Mt)return;const nn=Mt,rn=[];for(const Hn of nn){if(!Hn.startsWith("c:"))continue;const or=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(tt(Hn))}"]`);or&&rn.push({anchor:tt(Hn),ox:Number(or.dataset.x)||0,oy:Number(or.dataset.y)||0})}R={kind:"move",cards:rn,ids:new Set(nn),hit:he,x0:xe.x,y0:xe.y,dx:0,dy:0,mainStart:{x:q.current.main.x,y:q.current.main.y},mainEl:An,additive:xt},ke(b.pointerId);return}const Cr=Ft?.dataset.el?gn(Ft.dataset.el):Pn?It(Pn):fr?he:null;if(Se==="conn"){b.preventDefault(),B();const xt=Cr??(!gt&&!Ft&&j.closest(".ProseMirror")?he:null);if(!xt){Sn(null);return}const Mt=Xt.current;Mt?(ve.current.linkNodes(Mt,xt,b.shiftKey),Sn(null),dn("select")):Sn(xt);return}const zs=j.closest("[data-add]");if(zs?.dataset.add&&zs.dataset.node){b.preventDefault(),B(),ve.current.addRelated(zs.dataset.node,zs.dataset.add==="child"?"child":"sibling");return}if(Xe?.dataset.grip){b.preventDefault();const xt=Mo(Tn(q.current.elements),null).get(Xe.dataset.grip);if(!xt)return;R={kind:"size",id:Xe.dataset.grip,corner:Xe.dataset.corner??"se",b0:xt,dx:0,dy:0,dw:0,dh:0},ke(b.pointerId);return}if(Cr){b.preventDefault(),B();const xt=b.shiftKey||b.metaKey||b.ctrlKey,Mt=Tr(Cr,b);if(!Mt)return;const nn=Mt;if(po&&nn.length===1&&gt.dataset.anchor){const mr=gt.getBoundingClientRect(),Rr=el*fe.current.z*(Fn(u)||1);if(b.clientX>=mr.right-Rr){const ca=pn(u).get(gt.dataset.anchor),Fc=On(E()).find(Nu=>Nu.anchor===gt.dataset.anchor);if(!ca||!Fc)return;R={kind:"card-size",key:gt.dataset.anchor,edge:"e",b0:ca,h0:Number(Fc.node.attrs.h)||0,x0:xe.x,y0:xe.y,dx:0,dy:0,next:ca},ke(b.pointerId);return}}if(Cr===he&&nn.length===1&&An){const mr=An.getBoundingClientRect();if(b.clientX>mr.right-el*fe.current.z*(Fn(u)||1)){const Rr=hn(u);if(!Rr)return;R={kind:"card-size",key:he,edge:"e",b0:Rr,h0:Number(q.current.main.h)||0,x0:xe.x,y0:xe.y,dx:0,dy:0,next:Rr},ke(b.pointerId);return}}const rn=ve.current.expandFrames(nn),Hn=[];for(const mr of rn){if(!mr.startsWith("c:"))continue;const Rr=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(tt(mr))}"]`);Rr&&Hn.push({anchor:tt(mr),ox:Number(Rr.dataset.x)||0,oy:Number(Rr.dataset.y)||0})}const or=rn.includes(he);R={kind:"move",cards:Hn,ids:new Set(rn),hit:Cr,x0:xe.x,y0:xe.y,dx:0,dy:0,mainStart:or?{x:q.current.main.x,y:q.current.main.y}:null,mainEl:or?u.querySelector(".ProseMirror"):null,additive:xt,growSel:rn.length>Mt.length?[...rn]:void 0},ke(b.pointerId);return}if(!kn(j))return;const Ns=ve.current.boxesNow(null),sa=Tn(q.current.elements).find(xt=>{if(xt.kind!=="connector")return!1;const Mt=xo(xt.from),nn=xo(xt.to),rn=Mt?Ns.get(Mt):null,Hn=nn?Ns.get(nn):null;return!!rn&&!!Hn&&Ds(rn,Hn,xe,8/fe.current.z)}),Pc=sa?null:lu(q.current.tree).find(([xt,Mt])=>{const nn=Ns.get(It(xt)),rn=Ns.get(Mt===he?he:It(Mt));return!!nn&&!!rn&&Ds(rn,nn,xe,8/fe.current.z)});if(b.preventDefault(),B(),sa){lt([gn(sa.id)]);return}if(Pc){lt([iu(Pc[0])]);return}const aa=b.shiftKey||b.metaKey||b.ctrlKey,zu=aa?[...bt.current]:[];if(aa||lt([]),b.pointerType==="touch"){R={kind:"pan",x0:b.clientX,y0:b.clientY,vx:fe.current.x,vy:fe.current.y},ke(b.pointerId);return}R={kind:"marquee",x0:xe.x,y0:xe.y,additive:aa,base:zu},ke(b.pointerId)},Yt={raf:0,t:0,x:0,y:0,id:-1,type:"mouse"},Jn=()=>{Yt.raf&&cancelAnimationFrame(Yt.raf),Yt.raf=0},rr=()=>{const b=u.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)}},dr=b=>ct.current||et?!1:R?R.kind!=="pan"&&R.live===!0:mt.current==="conn"&&!!Xt.current&&!b?.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"),Qr=b=>{Yt.raf=0;const j=document.elementFromPoint(Yt.x,Yt.y);if(!dr(j))return;const{vx:re,vy:Se}=ai(rr(),Yt.x,Yt.y);if(!re&&!Se)return;const xe=Math.min(.05,Math.max(0,(b-Yt.t)/1e3));Yt.t=b;const Ie=Fn(u)||1,Le={...fe.current,x:fe.current.x-re*xe/Ie,y:fe.current.y-Se*xe/Ie};fe.current=Le,be(Le),Ec({clientX:Yt.x,clientY:Yt.y,pointerId:Yt.id,pointerType:Yt.type,target:j??u}),Yt.raf=requestAnimationFrame(Qr)},Su=b=>{if(R&&Ee!==b.pointerId)return;Yt.x=b.clientX,Yt.y=b.clientY,Yt.id=b.pointerId,Yt.type=b.pointerType;const{vx:j,vy:re}=dr(b.target)?ai(rr(),b.clientX,b.clientY):{vx:0,vy:0};if(!j&&!re){Jn();return}Yt.raf||(Yt.t=performance.now(),Yt.raf=requestAnimationFrame(Qr))},Cc=()=>{R||Jn()},Sc=b=>{Ec(b),Su(b)},Ec=b=>{if(b.pointerType==="touch"&&(ln.has(b.pointerId)&&ln.set(b.pointerId,{x:b.clientX,y:b.clientY}),xn&&Math.hypot(b.clientX-xn.x,b.clientY-xn.y)>Lf&&Gt()),et){mn();return}if(R&&Ee!==b.pointerId)return;if(!R&&mt.current==="conn"&&Xt.current){const je=b.target,Xe=je.closest?.(os),ht=je.closest?.(".amx-ucard");let Ft=Xe?.dataset.el?gn(Xe.dataset.el):ht?.dataset.anchor?It(ht.dataset.anchor):!ht&&je.closest?.(".ProseMirror")?he:null;Ft===Xt.current&&(Ft=null);const gt=At(b.clientX,b.clientY);K({x:gt.x,y:gt.y,over:Ft});return}if(!R)return;const j=Fn(u)||1;if(R.kind==="pan"){be({...fe.current,x:R.vx+(b.clientX-R.x0)/j,y:R.vy+(b.clientY-R.y0)/j});return}const re=At(b.clientX,b.clientY);if(R.kind==="link"||R.kind==="reconnect"){(Math.abs(re.x-R.x0)>Lt||Math.abs(re.y-R.y0)>Lt)&&(R.live=!0);const je=R.kind==="link"?R.from:R.fixed,Xe=_t(b.clientX,b.clientY);ne({from:je,x:re.x,y:re.y,over:Xe===je?null:Xe});return}if(R.kind==="card-size"){R.dx=re.x-R.x0,R.dy=re.y-R.y0;const je=R.key===he;let Xe=rl(R.b0,R.edge,R.dx,R.dy,!1,je?$a:Bs);if((Math.abs(Xe.x-R.b0.x)>Lt||Math.abs(Xe.y-R.b0.y)>Lt||Math.abs(Xe.w-R.b0.w)>Lt||Math.abs(Xe.h-R.b0.h)>Lt)&&(R.live=!0),R.gx=!1,R.gy=!1,we.current&&R.live){R.others||(R.others=kt(new Set(je?[]:[R.key]),je,new Set));const ht=If(Xe,R.edge,R.others,$t(),je?$a:Bs,du);Xe=ht.box,R.gx=ht.guides.v.length>0,R.gy=ht.guides.h.length>0,qe(R.gx||R.gy?si(Xe,R.others,ht.guides,1/fe.current.z):null)}else qe(null);R.next=Xe,w(R.key,je?`margin-left:${Xe.x}px;margin-top:${Xe.y}px;width:${Xe.w}px;height:${Xe.h}px;${z}`:`left:${Xe.x}px;top:${Xe.y}px;width:${Xe.w}px;height:${Xe.h}px;${z}`,Xe),wn({move:{ids:new Set([je?he:It(R.key)]),dx:0,dy:0},size:null});return}if(R.kind==="size"){const je=R.b0,Xe=R.corner.includes("e"),ht=R.corner.includes("s"),Ft=Math.max(ro,Math.round(Xe?re.x-je.x:je.x+je.w-re.x)),gt=Math.max(ro,Math.round(ht?re.y-je.y:je.y+je.h-re.y));R.dx=Xe?0:je.w-Ft,R.dy=ht?0:je.h-gt,R.dw=Ft-je.w,R.dh=gt-je.h,(Math.abs(R.dw)>Lt||Math.abs(R.dh)>Lt)&&(R.live=!0),wn({move:null,size:{id:R.id,dx:R.dx,dy:R.dy,dw:R.dw,dh:R.dh}});return}if(R.kind==="create"){R.x1=re.x,R.y1=re.y,(Math.abs(R.x1-R.x0)>Lt||Math.abs(R.y1-R.y0)>Lt)&&(R.live=!0),Ra.has(R.tool)&&Rn({x:Math.min(R.x0,re.x),y:Math.min(R.y0,re.y),w:Math.abs(re.x-R.x0),h:Math.abs(re.y-R.y0)});return}if(R.kind==="marquee"){R.live=!0;const je={x:Math.min(R.x0,re.x),y:Math.min(R.y0,re.y),w:Math.abs(re.x-R.x0),h:Math.abs(re.y-R.y0)};Rn(je);const Xe=[];for(const[ht,Ft]of ve.current.boxesNow(null))Yi(je,Ft)&&Xe.push(ht);lt(R.additive?[...new Set([...R.base,...Xe])]:Xe);return}if(R.dx=Math.round(re.x-R.x0),R.dy=Math.round(re.y-R.y0),(Math.abs(R.dx)>Lt||Math.abs(R.dy)>Lt)&&(R.live=!0),!R.align){const je=new Set(R.cards.map(fr=>fr.anchor)),Xe=new Set([...R.ids].filter(fr=>fr.startsWith("e:")).map(tt)),ht=pn(u),Ft=Mo(Tn(q.current.elements),null),gt=[];for(const fr of je){const kr=ht.get(fr);kr&&gt.push(kr)}const An=R.mainStart?hn(u):null;An&&gt.push(An);for(const fr of Xe){const kr=Ft.get(fr);kr&&gt.push(kr)}R.align={base:Pf(gt),others:kt(je,!!R.mainStart,Xe)}}R.gx=!1,R.gy=!1;const Se=R.align.base;if(we.current&&R.live&&Se){const je=Ff({...Se,x:Se.x+R.dx,y:Se.y+R.dy},R.align.others,$t());R.dx+=Math.round(je.dx),R.dy+=Math.round(je.dy),R.gx=je.guides.v.length>0,R.gy=je.guides.h.length>0,qe(R.gx||R.gy?si({...Se,x:Se.x+R.dx,y:Se.y+R.dy},R.align.others,je.guides,1/fe.current.z):null)}else qe(null);R.live&&R.kind==="move"&&R.growSel&&(lt(R.growSel),R.growSel=void 0);const{dx:xe,dy:Ie}=R;x(R.cards.map(je=>({anchor:je.anchor,decl:`left:${je.ox+xe}px;top:${je.oy+Ie}px;${z}`,selection:{x:je.ox+xe,y:je.oy+Ie}})),R.mainStart?{x:R.mainStart.x+xe,y:R.mainStart.y+Ie}:void 0),R.mainStart&&R.mainEl&&(R.mainEl.style.marginLeft=`${R.mainStart.x+R.dx}px`,R.mainEl.style.marginTop=`${R.mainStart.y+R.dy}px`),wn({move:{ids:R.ids,dx:R.dx,dy:R.dy},size:null});const Le=tt(R.hit),nt=!R.mainStart&&R.cards.length>0&&R.ids.size===R.cards.length?R.cards.map(je=>je.anchor).sort((je,Xe)=>+(Xe===Le)-+(je===Le)):[],pt=nt.length&&R.live?ve.current.attachHit(nt,re):null;gr(pt)},eo=b=>{Y(),b.kind==="move"&&b.mainEl&&(b.mainEl.style.marginLeft="",b.mainEl.style.marginTop=""),wn(null),Rn(null),gr(null),qe(null),ne(null)},Mc=b=>{if(b.pointerType==="touch"&&(ln.delete(b.pointerId),Gt(),et)){ln.size===0&&(et=null),Ye(b.pointerId),R=null;return}if(R&&Ee!==b.pointerId){Ye(b.pointerId);return}Jn();const j=R;if(R=null,Ye(b.pointerId),!j)return;if(j.kind==="pan"){j.tapKey&&Math.hypot(b.clientX-j.x0,b.clientY-j.y0)<ri&&lt([j.tapKey]);return}if(j.kind==="link"||j.kind==="reconnect"){if(eo(j),!j.live)return;const Ie=j.kind==="link"?j.from:j.fixed,Le=_t(b.clientX,b.clientY);if(!Le||Le===Ie)return;j.kind==="reconnect"?ve.current.mutate(nt=>zg(nt,j.id,j.end,Le)):ve.current.linkNodes(Ie,Le,b.shiftKey);return}if(j.kind==="create"){const Ie=Math.abs(j.x1-j.x0),Le=Math.abs(j.y1-j.y0),nt=Ra.has(j.tool)&&Ie>=ro&&Le>=ro?{x:Math.min(j.x0,j.x1),y:Math.min(j.y0,j.y1),w:Ie,h:Le}:null;let pt=null;j.tool==="frame"?nt?ve.current.addFrame(nt.x,nt.y,nt.w,nt.h):ve.current.addFrame(j.x0-Ri.w/2,j.y0-Ri.h/2):j.tool==="card"?pt=ve.current.addCardAt(j.x0-Jt/2,j.y0-24):ss[j.tool]&&ve.current.addShapeAt(ss[j.tool],j.x0,j.y0,nt??void 0),dn("select"),pt||B(),eo(j);return}if(!j.live){j.kind==="move"&&j.ids.size>1&&!j.additive&&lt([j.hit]),eo(j);return}const re=E();if(j.kind==="marquee"){const Ie=At(b.clientX,b.clientY),Le={x:Math.min(j.x0,Ie.x),y:Math.min(j.y0,Ie.y),w:Math.abs(Ie.x-j.x0),h:Math.abs(Ie.y-j.y0)},nt=[];for(const[pt,je]of ve.current.boxesNow(null))Yi(Le,je)&&nt.push(pt);lt(j.additive?[...new Set([...j.base,...nt])]:nt),eo(j);return}if(!re){eo(j);return}let Se=null,xe=null;if(j.kind==="card-size"){const Ie=j.key===he;let Le=T.current?rl(j.b0,j.edge,j.dx,j.dy,!0,Ie?$a:Bs):j.next;j.gx&&(Le={...Le,x:j.next.x,w:j.next.w}),j.gy&&(Le={...Le,y:j.next.y,h:j.next.h});const nt=j.edge.includes("n")||j.edge.includes("s");Ie?ve.current.writeFm({m:{...q.current.main,x:Math.round(Le.x),y:Math.round(Le.y),w:Math.round(Le.w),...nt?{h:Math.round(Le.h)}:{}}}):bo(re,new Map([[j.key,{x:Math.round(Le.x),y:Math.round(Le.y),w:Math.round(Le.w),h:nt?Math.round(Le.h):j.h0}]])),T.current&&(xe={key:j.key,from:j.next,to:Le})}else if(j.kind==="size"){const Ie=Tn(q.current.elements).find(Le=>Le.id===j.id);Ie&&Ie.kind!=="connector"&&ve.current.mutate(Le=>Xl(Le,j.id,{x:Math.round(Ie.x+j.dx),y:Math.round(Ie.y+j.dy),w:Math.max(ro,Math.round(Ie.w+j.dw)),h:Math.max(ro,Math.round(Ie.h+j.dh))}))}else{const Ie=!j.mainStart&&j.cards.length>0&&j.ids.size===j.cards.length?j.cards.map(yt=>yt.anchor).sort((yt,Cr)=>+(Cr===tt(j.hit))-+(yt===tt(j.hit))):[],Le=Ie.length?ve.current.attachHit(Ie,At(b.clientX,b.clientY)):null;if(Ie.length&&Le&&ve.current.applyAttach(Ie,Le)){eo(j);return}const nt=pn(u),pt=[];for(const yt of j.cards){const Cr=nt.get(yt.anchor);Cr&&pt.push(Cr)}if(j.mainStart){const yt=hn(u);yt&&pt.push(yt)}const je=new Set(j.cards.map(yt=>yt.anchor)),Xe=[...nt].filter(([yt])=>!je.has(yt)).map(([,yt])=>yt);if(!j.mainStart){const yt=hn(u);yt&&Xe.push(yt)}const ht=(j.hit.startsWith("c:")?j.cards.find(yt=>yt.anchor===tt(j.hit)):null)??j.cards[0]??(j.mainStart?{ox:j.mainStart.x,oy:j.mainStart.y}:null),Ft=j.gx?j.dx:T.current&&ht?oi(ht.ox+j.dx)-ht.ox:j.dx,gt=j.gy?j.dy:T.current&&ht?oi(ht.oy+j.dy)-ht.oy:j.dy,An=Ft-j.dx,fr=gt-j.dy,kr=pt.map(yt=>({...yt,x:yt.x+An,y:yt.y+fr})),po=Go(kr,Xe,{x:Ft,y:gt}),Pn=Ft+po.x,ho=gt+po.y,to={x:Pn-j.dx,y:ho-j.dy};(to.x||to.y)&&(Se={anchors:j.cards.map(yt=>yt.anchor),main:!!j.mainStart,push:to,repel:!!(po.x||po.y)}),j.cards.length&&bo(re,new Map(j.cards.map(yt=>[yt.anchor,{x:Math.round(yt.ox+Pn),y:Math.round(yt.oy+ho)}])));const Ro=new Set([...j.ids].filter(yt=>yt.startsWith("e:")).map(tt)),Do=j.mainStart?{...q.current.main,x:Math.round(j.mainStart.x+Pn),y:Math.round(j.mainStart.y+ho)}:void 0;(Ro.size||Do)&&(ve.current.writeFm({...Ro.size?{e:ji(Lr(q.current.elements),Ro,Pn,ho)}:{},...Do?{m:Do}:{}}),j.cards.length&&ve.current.mergePair())}eo(j),xe&&W(xe.key,xe.from,xe.to),Se&&ye(Se.anchors,Se.main,Se.push,Se.repel?"amx-card-repel":"amx-card-snap"),M()},zc=b=>{if(ct.current)return;const j=document.elementFromPoint(b.clientX,b.clientY)??b.target;if(j.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;const re=j.closest(".amx-ucard"),Se=!re&&!!j.closest(".ProseMirror"),xe=re?.dataset.anchor?It(re.dataset.anchor):Se?he:null;if(xe){if(en.current===(xe===he?he:tt(xe)))return;b.preventDefault(),b.stopPropagation(),ve.current.enterNodeEdit(xe,{x:b.clientX,y:b.clientY}),Qm()&&ve.current.focusNode(xe,!0);return}const Ie=j.closest(os);if(Ie?.dataset.el){b.preventDefault(),b.stopPropagation();const je=Tn(q.current.elements).find(Xe=>Xe.id===Ie.dataset.el);je&&ve.current.editText(je.id,Ta(je),ja(je));return}if(!kn(j))return;const Le=At(b.clientX,b.clientY),nt=ve.current.boxesNow(null),pt=Tn(q.current.elements).find(je=>{if(je.kind!=="connector")return!1;const Xe=xo(je.from),ht=xo(je.to),Ft=Xe?nt.get(Xe):null,gt=ht?nt.get(ht):null;return!!Ft&&!!gt&&Ds(Ft,gt,Le,8/fe.current.z)});b.preventDefault(),pt?ve.current.editText(pt.id,"label",Ce("canvasstage.textTitle.connector")):ve.current.addCardAt(Le.x-Jt/2,Le.y-24)},Nc=(b,j,re)=>{if(ct.current||b.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"))return"skip";const Se=b.closest(os),xe=b.closest(".amx-ucard"),Ie=!xe&&!Se&&!!b.closest(".ProseMirror");if(xe?.dataset.anchor&&en.current===xe.dataset.anchor||Ie&&en.current===he)return"native";let Le=Se?.dataset.el?gn(Se.dataset.el):xe?.dataset.anchor?It(xe.dataset.anchor):Ie?he:null;if(!Le&&!kn(b))return"skip";if(!Le){const nt=At(j,re),pt=ve.current.boxesNow(null),je=Tn(q.current.elements).find(Xe=>{if(Xe.kind!=="connector")return!1;const ht=xo(Xe.from),Ft=xo(Xe.to),gt=ht?pt.get(ht):null,An=Ft?pt.get(Ft):null;return!!gt&&!!An&&Ds(gt,An,nt,8/fe.current.z)});je&&(Le=gn(je.id))}return Le&&!bt.current.includes(Le)&&lt([Le]),jt({x:j,y:re,key:Le,at:At(j,re)}),"open"},Ac=b=>{const j=Nc(b.target,b.clientX,b.clientY);j!=="skip"&&(b.stopPropagation(),j==="open"&&b.preventDefault())},Eu=b=>{const j=b.target,re=en.current;return!re||!j?!1:re===he?!!j.closest(".ProseMirror")&&!j.closest(".amx-ucard"):!!j.closest(`.amx-ucard[data-anchor="${CSS.escape(re)}"]`)};let oa=!1;const $c=b=>{b.target?.closest?.(".ProseMirror")&&(oa=!0)},jo=()=>{oa=!1},Tc=b=>{const j=b.dataTransfer,re=j?Array.from(j.types):[];return oa||E()?.dragging?null:q.current.saveFile&&re.includes("Files")?"files":_f(j)?"refs":Eu(b)?null:re.includes("text/uri-list")||re.includes("text/plain")?"text":null},jc=b=>{if(ct.current)return;const j=E();if(Tc(b)){b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="copy"),u.classList.add("amx-dropzone");return}!j?.dragging||b.target?.closest?.(".ProseMirror")||(b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="move"),u.classList.add("amx-dropzone"))},jr=()=>u.classList.remove("amx-dropzone"),Rc=b=>{u.contains(b.relatedTarget)||jr()},Dc=b=>{if(jr(),ct.current){b.preventDefault();return}const j=E(),re=Tc(b);if(re){b.preventDefault(),b.stopPropagation();const Ie=At(b.clientX,b.clientY),Le=Array.from(b.dataTransfer?.files??[]);if(re==="files"&&Le.length){ve.current.dropFilesAt(Le,Ie);return}if(re==="refs"){const pt=q.current.path;jf(b.dataTransfer).forEach((je,Xe)=>ve.current.addCardMd(al(je,b.altKey||je.kind==="note"&&je.path===pt),Ie,Xe));return}const nt=b.dataTransfer?.getData("text/uri-list")||b.dataTransfer?.getData("text/plain")||"";ve.current.addCardMd(nt,Ie);return}if(!j?.dragging||b.target?.closest?.(".ProseMirror"))return;b.preventDefault(),b.stopPropagation();const Se=At(b.clientX,b.clientY),xe=j.state.selection;if(xe instanceof ze&&xe.node.type.name==="amadeusCanvasCard")bo(j,new Map([[String(xe.node.attrs.anchor),{x:Math.round(Se.x),y:Math.round(Se.y)}]])),M();else{const Ie=mu(j,Math.round(Se.x),Math.round(Se.y));Ie&&M(Ie)}j.dragging=null,j.dom.dataset.dragging="false"},Mu=()=>{const b=u.getBoundingClientRect();return At(b.left+b.width/2,b.top+b.height/2)},Es=b=>{if(en.current||!b.clipboardData||!E())return;const j=bt.current;if(!j.length)return;b.preventDefault();const re=ve.current.writeClip(b.clipboardData,j);b.type==="cut"&&re&&ve.current.removeSel(re.keys,{assets:!1})},Lc=b=>{if(ct.current||en.current||!b.clipboardData)return;const j=Array.from(b.clipboardData.files??[]),re=b.clipboardData.getData("text/plain")??"",Se=Nx(b.clipboardData.getData(cl));if(!j.length&&!re.trim()&&!Se)return;b.preventDefault();const xe=qr.current++,Ie=Mu(),Le={x:Ie.x+xe*24,y:Ie.y+xe*24};if(j.length){ve.current.dropFilesAt(j,Le);return}Se&&ve.current.pastePayload(Se,Le)||re.trim()&&ve.current.addCardMd(re,Le)},Ms=b=>{b.pointerType==="touch"&&(ln.delete(b.pointerId),Gt(),et&&ln.size===0&&(et=null))};window.addEventListener("pointerup",Ms,!0),window.addEventListener("pointercancel",Ms,!0);const Ic=b=>{b.pointerType==="touch"&&(ln.delete(b.pointerId),Gt(),et&&ln.size===0&&(et=null)),Ye(b.pointerId),!(R&&Ee!==b.pointerId)&&In()};return u.addEventListener("pointerdown",Ss),u.addEventListener("pointermove",Sc),u.addEventListener("pointerleave",Cc),u.addEventListener("pointerup",Mc),u.addEventListener("pointercancel",Ic),u.addEventListener("dblclick",zc),u.addEventListener("contextmenu",Ac,!0),u.addEventListener("dragover",jc),u.addEventListener("dragleave",Rc),u.addEventListener("drop",Dc),u.addEventListener("dragstart",$c),window.addEventListener("dragend",jr),window.addEventListener("drop",jr),window.addEventListener("blur",jr),window.addEventListener("dragend",jo),window.addEventListener("drop",jo),window.addEventListener("blur",jo),u.addEventListener("copy",Es,!0),u.addEventListener("cut",Es,!0),u.addEventListener("paste",Lc,!0),()=>{window.removeEventListener("pointerup",Ms,!0),window.removeEventListener("pointercancel",Ms,!0),Gt(),_.remove(),se(),delete u.dataset.amxDragscope,u.removeEventListener("wheel",ue),u.removeEventListener("pointerdown",Ss),u.removeEventListener("pointermove",Sc),u.removeEventListener("pointerleave",Cc),Jn(),u.removeEventListener("pointerup",Mc),u.removeEventListener("pointercancel",Ic),u.removeEventListener("dblclick",zc),u.removeEventListener("contextmenu",Ac,!0),u.removeEventListener("dragover",jc),u.removeEventListener("dragleave",Rc),u.removeEventListener("drop",Dc),u.removeEventListener("dragstart",$c),window.removeEventListener("dragend",jr),window.removeEventListener("drop",jr),window.removeEventListener("blur",jr),window.removeEventListener("dragend",jo),window.removeEventListener("drop",jo),window.removeEventListener("blur",jo),jr(),u.removeEventListener("copy",Es,!0),u.removeEventListener("cut",Es,!0),u.removeEventListener("paste",Lc,!0)}},[n,At]),v.useEffect(()=>{if(!n)return;const u=()=>{En.current={held:!1,used:!1},Mr(!1)},E=M=>{if(M.code!=="Space"||!En.current.held)return;const{used:B}=En.current;u(),M.preventDefault();const O=m.current,_=M.target;if(B||ct.current||!O||!_||!O.contains(_)||_.closest(".ProseMirror"))return;const V=bt.current;V.length===1&&(V[0].startsWith("c:")||V[0]===he)&&ve.current.enterNodeEdit(V[0])};return window.addEventListener("keyup",E,!0),window.addEventListener("blur",u),()=>{window.removeEventListener("keyup",E,!0),window.removeEventListener("blur",u),u()}},[n]);const ft=u=>{if(!n||oe||u.nativeEvent.isComposing)return;const E=u.target;if((u.metaKey||u.ctrlKey)&&(u.key==="z"||u.key==="Z")){if(E.tagName==="INPUT"||E.tagName==="TEXTAREA")return;u.preventDefault(),u.stopPropagation(),Xn(u.shiftKey?"redo":"undo");return}if((u.metaKey||u.ctrlKey)&&!u.shiftKey&&!u.altKey&&(u.key==="y"||u.key==="Y")){if(E.tagName==="INPUT"||E.tagName==="TEXTAREA")return;u.preventDefault(),u.stopPropagation(),Xn("redo");return}if(u.key!=="Escape")return;const M=en.current;!M||!E.closest(".ProseMirror")||(u.preventDefault(),u.stopPropagation(),Yn(null),lt([M===he?he:It(M)]),m.current?.focus({preventScroll:!0}))},Bt=u=>{if(!n)return;const E=u.target;if(E.closest(".ProseMirror")||E.tagName==="INPUT"||E.tagName==="TEXTAREA")return;const M=u.metaKey||u.ctrlKey;if(!u.altKey&&(M?u.key==="="||u.key==="+"||u.key==="-"||u.key==="0":u.shiftKey&&u.code==="Digit1")){u.preventDefault(),M?u.key==="0"?lr(1/fe.current.z):lr(u.key==="-"?1/1.2:1.2):sn();return}if(!oe){if(M&&(u.key==="a"||u.key==="A")){u.preventDefault(),lt([...pn(m.current).keys()].map(It).concat(Ne.filter(B=>B.kind!=="connector").map(B=>gn(B.id)),[he]));return}if(M&&!u.shiftKey&&!u.altKey&&(u.key==="d"||u.key==="D")){u.preventDefault(),ut.length&&le(ut);return}if(u.key==="Escape"){u.preventDefault(),rt?jt(null):Ot?Sn(null):st!=="select"?dn("select"):lt([]);return}if(u.code==="Space"&&!M&&!u.target?.closest?.("button")){u.preventDefault(),!u.repeat&&!En.current.held&&(En.current={held:!0,used:!1},Mr(!0));return}if(ut.length){if(u.key==="Delete"||u.key==="Backspace"){u.preventDefault(),nr(ut);return}if((u.key==="Enter"||u.key==="F2")&&ut.length===1&&ut[0].startsWith("e:")){u.preventDefault();const B=Ne.find(O=>O.id===tt(ut[0]));B&&xr(B.id,Ta(B),ja(B));return}if((u.key==="Tab"||u.key==="Enter")&&ut.length===1&&(ut[0].startsWith("c:")||ut[0]===he)){u.preventDefault(),Nr(ut[0]===he?he:tt(ut[0]),u.key==="Tab"?"child":"sibling");return}if(u.key.startsWith("Arrow")){u.preventDefault();const B=Rf(T.current,u.shiftKey),O=u.key==="ArrowLeft"?-B:u.key==="ArrowRight"?B:0,_=u.key==="ArrowUp"?-B:u.key==="ArrowDown"?B:0;if(!O&&!_)return;const V=r(),ee=ur(ut),l=ee.filter(w=>w.startsWith("c:")).map(tt);if(V&&l.length){const w=pn(m.current);bo(V,new Map(l.map(z=>{const Y=w.get(z);return[z,{x:Math.round((Y?.x??0)+O),y:Math.round((Y?.y??0)+_)}]}))),I()}const h=new Set(ee.filter(w=>w.startsWith("e:")).map(tt)),x=ee.includes(he)?{...o,x:Math.round(o.x+O),y:Math.round(o.y+_)}:void 0;(h.size||x)&&(We({...h.size?{e:ji(Lr(c),h,O,_)}:{},...x?{m:x}:{}}),l.length&&Ze())}}}},wt=[{id:"select",icon:f.jsx(zf,{size:14}),title:de("canvasstage.tool.select")},{id:"pan",icon:f.jsx(ep,{size:14}),title:de("canvasstage.tool.pan")},{id:"card",icon:f.jsx(Wa,{size:14}),title:de("canvasstage.tool.card")},{id:"rect",icon:f.jsx(Nf,{size:14}),title:de("canvasstage.shape.rect")},{id:"ellipse",icon:f.jsx(Af,{size:14}),title:de("canvasstage.shape.ellipse")},{id:"text",icon:f.jsx(tp,{size:14}),title:de("canvasstage.shape.text")},{id:"frame",icon:f.jsx(np,{size:14}),title:de("canvasstage.tool.frame")},{id:"conn",icon:f.jsx(Gp,{size:14}),title:de("canvasstage.tool.conn")}],Wt=$f(ce),Rt=(rt?.key?.startsWith("e:")?Ne.find(u=>u.id===tt(rt.key))??null:null)?.kind==="connector",zn=rt?.key?(ut.length?ut:[rt.key]).filter(u=>u.startsWith("c:")||u.startsWith("e:")):[],Dt=(()=>{if(!zn.length)return null;const u=rt?r():null,E=Lr(c),M=O=>{if(O.startsWith("c:"))return String((u?On(u).find(V=>V.anchor===tt(O))?.node.attrs.color:"")??"");const _=E.find(V=>!!V&&typeof V=="object"&&V.id===tt(O));return typeof _?.color=="string"?_.color:""},B=M(zn[0]);return zn.every(O=>M(O)===B)?B:null})(),tn=Dt&&Dt.startsWith("#")?Dt:null,Zr=Rt?(ut.length?ut:[rt.key]).filter(u=>u.startsWith("e:")).map(tt).filter(u=>Ne.some(E=>E.kind==="connector"&&E.id===u)):[],$r=(()=>{const u=Zr.map(E=>{const M=Ne.find(_=>_.kind==="connector"&&_.id===E),B=M?.kind==="connector"?M.fromEnd??ms.fromEnd:ms.fromEnd,O=M?.kind==="connector"?M.toEnd??ms.toEnd:ms.toEnd;return Qi.find(_=>_.from===B&&_.to===O)?.id??null});return u.length&&u.every(E=>E===u[0])?u[0]:null})();return f.jsxs("div",{className:`amx-stage${n?"":" amx-stage-off"}${n?` amx-tool-${oe?"pan":st}`:""}${oe?" amx-stage-ro":""}${n&&Qn?" amx-space-pan":""}${Vr?" amx-vp-focus":""}${n&&me&&ce.z<=Ge?" amx-stage-overview":""}`,ref:m,tabIndex:-1,onKeyDownCapture:ft,onKeyDown:Bt,children:[n?f.jsx("div",{className:"amx-stage-grid","aria-hidden":"true",style:Wt}):null,f.jsxs("div",{className:"amx-stage-inner",style:n?{transform:`translate(${ce.x}px, ${ce.y}px) scale(${ce.z})`,"--amx-main-x":`${o.x}px`,"--amx-main-y":`${o.y}px`,"--amx-main-w":`${o.w}px`,"--amx-main-h":typeof o.h=="number"&&o.h>0?`${o.h}px`:"auto"}:void 0,children:[n?f.jsx(dx,{elements:c,hostRef:m,documentKey:e,sel:G,editing:Zn,tree:a,ghost:Hr,marquee:Mn,attach:hr,overviewScale:me&&ce.z<=Ge?ce.z:null,mainAutoHeight:!(typeof o.h=="number"&&o.h>0),preview:X??(Ot&&D?{from:Ot,x:D.x,y:D.y,over:D.over}:null),guides:Qe}):null,Ve]}),n&&Me?f.jsx(Ax,{hostRef:m,vp:ce,elements:c,ghost:Hr,onCenter:Wr}):null,n&&!oe?f.jsx("div",{className:"amx-stage-tools",role:"toolbar","aria-label":de("canvasstage.toolbar.label"),children:wt.map(u=>f.jsx("button",{type:"button",title:u.title,className:st===u.id?"on":"","aria-pressed":st===u.id,onClick:()=>{dn(u.id),Sn(null),m.current?.focus({preventScroll:!0})},children:u.icon},u.id))}):null,n&&Ot?f.jsx("div",{className:"amx-stage-hint",children:de("canvasstage.conn.hint")}):null,n?f.jsx(Km,{zoom:ce.z,onZoomBy:lr,onFit:sn,snap:ae,onSnap:u=>{zt(u),m.current?.focus({preventScroll:!0})},mini:Me,onMini:u=>{Ke(u),Zm(u),m.current?.focus({preventScroll:!0})},extra:f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:Z?"is-on":"","aria-pressed":Z,"aria-label":de("canvasstage.guides.label"),title:de(Z?"canvasstage.guides.off":"canvasstage.guides.on"),onClick:()=>{const u=!Z;we.current=u,ie(u),Gm(u),m.current?.focus({preventScroll:!0})},children:f.jsx(dp,{size:12})}),f.jsx("button",{type:"button",className:me?"is-on":"","aria-pressed":me,"aria-label":de("canvasstage.overview.label"),title:de(me?"canvasstage.overview.off":"canvasstage.overview.on"),onClick:()=>{const u=!me;Ae(u),Jm(u),m.current?.focus({preventScroll:!0})},children:f.jsx(Tp,{size:12})})]})}):null,n&&rt?f.jsx(ao,{children:f.jsx(zo,{className:"ctx-menu amx-canvas-menu",x:rt.x,y:rt.y,onClick:u=>u.stopPropagation(),children:rt.key?f.jsxs(f.Fragment,{children:[zn.length>0&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"amx-color-row",role:"group","aria-label":de("canvasstage.color.label"),children:[kx.map(u=>f.jsx("button",{type:"button",className:"amx-color-swatch","data-swatch":u.v||"none",title:de(u.nameKey),"aria-label":de(u.nameKey),"aria-pressed":Dt===u.v,style:u.v?{"--amx-swatch":`var(--amx-cv-${u.v})`}:void 0,onClick:()=>{const E=zn;jt(null),Yr(E,u.v||null)}},u.v||"none")),f.jsxs("label",{className:"amx-color-swatch is-custom",title:de("canvasstage.color.custom"),"data-active":tn?"":void 0,style:tn?{"--amx-swatch":tn}:void 0,children:[tn?null:f.jsx(Tf,{size:11}),f.jsx("input",{type:"color","aria-label":de("canvasstage.color.custom"),defaultValue:tn??"#7b5ce5",ref:u=>{if(!u)return;const E=zn;u.onchange=()=>{jt(null),Yr(E,u.value)}}})]})]}),f.jsx("div",{className:"ctx-separator"})]}),Rt&&Zr.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"amx-color-row amx-end-row",role:"group","aria-label":de("canvasstage.ends.label"),children:Qi.map(u=>f.jsx("button",{type:"button",className:"amx-end-btn","data-ends":u.id,title:de(u.nameKey),"aria-label":de(u.nameKey),"aria-pressed":$r===u.id,onClick:()=>{const E=Zr;jt(null),To(E,u.from,u.to),m.current?.focus({preventScroll:!0})},children:u.icon},u.id))}),f.jsx("div",{className:"ctx-separator"})]}),rt.key.startsWith("e:")&&f.jsx("button",{onClick:()=>{const u=Ne.find(E=>E.id===tt(rt.key));jt(null),u&&xr(u.id,Ta(u),ja(u))},children:de("canvasstage.menu.editText")}),rt.key!==he&&!Rt&&f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:()=>{const u=ut.length?ut:[rt.key];jt(null),pe(u)},children:de("canvasstage.menu.copy")}),f.jsx("button",{onClick:()=>{const u=ut.length?ut:[rt.key];jt(null),le(u),m.current?.focus({preventScroll:!0})},children:de("canvasstage.menu.duplicate")})]}),!Rt&&f.jsx("button",{onClick:()=>{Sn(rt.key),dn("conn"),jt(null)},children:de("canvasstage.menu.connectTo")}),(rt.key===he||rt.key.startsWith("c:"))&&wo(Kt(a),rt.key===he?he:tt(rt.key)).length>0&&f.jsx("button",{onClick:()=>{const u=rt.key===he?he:tt(rt.key);jt(null),ge(u)},children:de("canvasstage.menu.arrange")}),!Rt&&f.jsx("button",{onClick:()=>{const u=ut.length?ut:[rt.key];jt(null),cn(u)},children:de("canvasstage.menu.groupFrame")}),rt.key.startsWith("c:")&&f.jsx("button",{onClick:()=>{const u=tt(rt.key);jt(null);const E=r();if(!E)return;const M=vt([u]);M&&Et(),pu(E,u),lt([]),I(),M&&Ze()},children:de("canvasstage.menu.unwrap")}),rt.key!==he&&f.jsx("button",{className:"danger",onClick:()=>{const u=ut.length?ut:[rt.key];jt(null),nr(u)},children:de("canvasstage.menu.delete")})]}):f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:()=>{const u=rt.at;jt(null),br(u.x-Jt/2,u.y-24)},children:de("canvasstage.menu.newCard")}),H&&f.jsx("button",{onClick:()=>{const u=rt.at;jt(null),ir(u)},children:de("canvasstage.menu.addNote")}),f.jsx("button",{onClick:()=>{const u=rt.at;jt(null),tr("rect",u.x,u.y)},children:de("canvasstage.shape.rect")}),f.jsx("button",{onClick:()=>{const u=rt.at;jt(null),tr("ellipse",u.x,u.y)},children:de("canvasstage.shape.ellipse")}),f.jsx("button",{onClick:()=>{const u=rt.at;jt(null),tr("text",u.x,u.y)},children:de("canvasstage.shape.text")}),f.jsx("button",{onClick:()=>{const u=rt.at;jt(null),Nt(u.x,u.y)},children:"Frame"}),f.jsx("button",{onClick:()=>{jt(null),sn()},children:de("canvasstage.menu.fit")}),f.jsx("div",{className:"ctx-separator"}),f.jsx("button",{onClick:()=>{jt(null),an()},children:de("canvasstage.menu.exportCanvas")})]})})}):null,n&&!oe&&yr&&H?f.jsx(Yl,{pages:H(),exclude:e,onClose:()=>{ir(null),m.current?.focus({preventScroll:!0})},onPick:u=>{const E=yr;ir(null),m.current?.focus({preventScroll:!0}),qn(al({kind:"note",path:u}),E)}}):null]})}function mu(e,t,n,r){const o=e.state.selection,s=e.state.schema.nodes.amadeusCanvasCard;if(!s||!(o instanceof ze))return null;const c=o.node;if(!c.isBlock||["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(c.type.name))return null;const a=e.state.doc.resolve(o.from);for(let I=a.depth;I>=1;I--)if(a.node(I).type.name==="amadeusColumnCell")return null;const i=Er(e.state.doc),d=s.createAndFill({anchor:i,x:t,y:n,w:Jt,h:0},c);if(!d)return null;const p=a.depth>=1?a.node(a.depth):null,g=e.state.schema.nodes.paragraph;let C=p?.type.name==="amadeusCanvasCard"&&p.childCount===1&&g?e.state.tr.replaceWith(o.from,o.to,g.create()):e.state.tr.delete(o.from,o.to);return C=C.insert(r?fu(C.doc,r.tree,r.parent):C.doc.content.size,d),oo(e,C.scrollIntoView()),i}function pu(e,t){const r=On(e).find(p=>p.anchor===t);if(!r)return;const{paragraph:o,html:s}=e.state.schema.nodes,c=[];r.node.forEach(p=>c.push(p));const i=[...t&&o&&s?[o.create(null,s.create({value:`<!-- a ${t} -->`}))]:[],...c.length?c:[o.create()]],d=e.state.tr.delete(r.pos,r.pos+r.node.nodeSize);oo(e,d.insert(r.pos,i).scrollIntoView())}const Tx={heading:["id"]};function kc(e,t){if(e.type!==t.type)return!1;const n=Tx[e.type.name];if(!n)return e.sameMarkup(t);const r={...t.attrs};for(const o of n)r[o]=e.attrs[o];return e.hasMarkup(t.type,r,t.marks)}function Wo(e,t){if(e===t)return!0;if(!kc(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(!Wo(e.child(n),t.child(n)))return!1;return!0}function hu(e,t,n){for(let r=0;;r++){if(r===e.childCount||r===t.childCount)return e.childCount===t.childCount?null:n;const o=e.child(r),s=t.child(r);if(o===s){n+=o.nodeSize;continue}if(!kc(o,s))return n;if(o.isText&&o.text!==s.text){const c=o.text??"",a=s.text??"";for(let i=0;c[i]===a[i];i++)n++;return n}if(o.content.size||s.content.size){const c=hu(o.content,s.content,n+1);if(c!=null)return c}n+=o.nodeSize}}function gu(e,t,n,r){for(let o=e.childCount,s=t.childCount;;){if(o===0||s===0)return o===s?null:{a:n,b:r};const c=e.child(--o),a=t.child(--s),i=c.nodeSize;if(c===a){n-=i,r-=i;continue}if(!kc(c,a))return{a:n,b:r};if(c.isText&&c.text!==a.text){const d=c.text??"",p=a.text??"";let g=0;const C=Math.min(d.length,p.length);for(;g<C&&d[d.length-g-1]===p[p.length-g-1];)g++,n--,r--;return{a:n,b:r}}if(c.content.size||a.content.size){const d=gu(c.content,a.content,n-1,r-1);if(d)return d}n-=i,r-=i}}const jx=25e4;function Rx(e,t){const n=e.childCount,r=t.childCount;let o=0;for(;o<n&&o<r&&Wo(e.child(o),t.child(o));)o++;let s=0;for(;s<n-o&&s<r-o&&Wo(e.child(n-1-s),t.child(r-1-s));)s++;const c=o,a=n-s,i=o,d=r-s,p=a-c,g=d-i;if(p===0&&g===0)return[];if(p===0||g===0||p*g>jx)return[[c,a,i,d]];const C=g+1,I=new Uint32Array((p+1)*C);for(let oe=p-1;oe>=0;oe--)for(let H=g-1;H>=0;H--)I[oe*C+H]=Wo(e.child(c+oe),t.child(i+H))?I[(oe+1)*C+H+1]+1:Math.max(I[(oe+1)*C+H],I[oe*C+H+1]);const N=[];let k=0,$=0,F=0,J=0;for(;k<p&&$<g;)Wo(e.child(c+k),t.child(i+$))&&I[k*C+$]===I[(k+1)*C+$+1]+1?((F<k||J<$)&&N.push([c+F,c+k,i+J,i+$]),k++,$++,F=k,J=$):I[(k+1)*C+$]>=I[k*C+$+1]?k++:$++;return(F<p||J<g)&&N.push([c+F,a,i+J,d]),N}const Fs=(e,t)=>{let n=0;for(let r=0;r<t;r++)n+=e.child(r).nodeSize;return n};function Dx(e,t){const n=[];for(const[r,o,s,c]of Rx(e,t)){const a=Fs(e,r),i=Fs(t,s),d=e.content.cut(a,Fs(e,o)),p=t.content.cut(i,Fs(t,c)),g=hu(d,p,a);if(g==null)continue;const C=gu(d,p,a+d.size,i+p.size);let I=C?C.a:a+d.size,N=C?C.b:i+p.size;const k=i-a;I<g&&(N+=g-I,I=g),N-k<g&&(I+=g-(N-k),N=g+k),n.push({from:g,to:I,slice:t.slice(g+k,N)})}return n}function Lx(e,t,n){const r=Dx(e.doc,t);if(!r.length)return null;const o=e.selection,s=e.tr;for(let c=r.length-1;c>=0;c--){const a=r[c];s.replace(a.from,a.to,a.slice)}if(n)for(const c of r)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(o instanceof Pe){const c=d=>{for(const p of r)if(d>p.from&&d<p.to){const g=s.mapping.map(p.from,-1);return Math.min(g+(d-p.from),g+p.slice.size,s.doc.content.size)}return null},a=c(o.head),i=c(o.anchor);if(a!=null||i!=null){const d=a??s.mapping.map(o.head),p=i??s.mapping.map(o.anchor);try{s.setSelection(Pe.between(s.doc.resolve(p),s.doc.resolve(d)))}catch{}}}return s.setMeta("addToHistory",!1)}const sr=new jn("amAgentChanges");let ll=0;function yu(e,t){if(e.childCount!==t.childCount)return!1;for(let n=0;n<e.childCount;n++)if(!Wo(e.child(n),t.child(n)))return!1;return!0}function Ix(e,t,n,r){const o=[...e.map(a=>({a:a.from,b:a.to,e:a})),...t.map(a=>({a:a.oldFrom,b:a.oldTo,c:a}))].sort((a,i)=>a.a-i.a||a.b-i.b),s=[];for(const a of o){const i=s[s.length-1],d=i?Math.max(...i.map(p=>p.b)):-1;i&&a.a<=d&&(a.c||i.some(p=>p.c))?i.push(a):s.push([a])}const c=[];for(const a of s){const i=a.filter(oe=>oe.e).map(oe=>oe.e),d=a.filter(oe=>oe.c).map(oe=>oe.c);if(!d.length){for(const oe of i){const H=r.mapping.map(oe.from,1);c.push({...oe,from:H,to:Math.max(H,r.mapping.map(oe.to,-1))})}continue}if(!i.length&&d.length===1){const oe=d[0];c.push({id:++ll,from:oe.from,to:oe.to,old:oe.old,after:r.doc.slice(oe.from,oe.to).content});continue}const p=Math.min(...a.map(oe=>oe.a)),g=Math.max(...a.map(oe=>oe.b)),C=i.filter(oe=>yu(n.slice(oe.from,oe.to).content,oe.after)),I=i.reduce((oe,H)=>oe+(H.locked??0)+(C.includes(H)?0:1),0),N=new qf(n);for(const oe of[...C].sort((H,te)=>te.from-H.from))N.replace(oe.from,oe.to,oe.old);const k=N.mapping.map(p,-1),$=N.mapping.map(g,1),F=r.mapping.map(p,-1),J=r.mapping.map(g,1);c.push({id:++ll,from:F,to:J,old:N.doc.slice(k,$),after:r.doc.slice(F,J).content,...I?{locked:I}:{}})}return c.sort((a,i)=>a.from-i.from)}function Px(e,t){if(!t.changes.length)return null;const n=[],r=e.doc.content.size;for(const o of t.changes){const s=`am-agent-change${t.current===o.id?" is-current":""}`,c=Math.min(o.from,r),a=Math.min(o.to,r);a>c?(n.push(cr.inline(c,a,{class:s,"data-agent-change":String(o.id)})),e.doc.nodesBetween(c,a,(i,d)=>(i.isBlock&&i.isLeaf&&d>=c&&d+i.nodeSize<=a&&n.push(cr.node(d,d+i.nodeSize,{class:`${s} am-agent-change-block`})),!i.isTextblock))):n.push(cr.widget(c,()=>{const i=document.createElement("span");return i.className=`am-agent-del${t.current===o.id?" is-current":""}`,i.setAttribute("data-agent-change",String(o.id)),i},{side:-1,key:`am-agent-del-${o.id}-${t.current===o.id?1:0}`,ignoreSelection:!0}))}return io.create(e.doc,n)}function Fx(e){return[St(()=>Ox(e))].flat()}function Ox(e){return new Ht({key:sr,state:{init:()=>({changes:[],current:null}),apply(t,n){const r=t.getMeta(sr);if(r&&"clear"in r)return{changes:[],current:null};if(r&&"add"in r){const s=Ix(n.changes,r.add,r.before,t);return{changes:s,current:s.some(c=>c.id===n.current)?n.current:null}}let o=n;return t.docChanged&&n.changes.length&&(o={...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))}})}),r&&"current"in r&&(o={...o,current:r.current}),o}},props:{decorations(t){const n=sr.getState(t);return n?Px(t,n):null}},view:t=>{const n=sr.getState(t.state);return n&&e.current(n),{update(r,o){const s=sr.getState(r.state);s&&s!==sr.getState(o)&&e.current(s)}}}})}function _x(e,t,n){return n.length?e.setMeta(sr,{add:n,before:t}):e}function Bx(e){const t=sr.getState(e.state);if(!t?.changes.length)return{reverted:0,skipped:0};const n=e.state.tr;let r=0,o=0;for(const s of[...t.changes].sort((c,a)=>a.from-c.from)){if(!yu(e.state.doc.slice(s.from,s.to).content,s.after)){o+=1+(s.locked??0);continue}n.replace(s.from,s.to,s.old),r++,o+=s.locked??0}return e.dispatch(n.setMeta(sr,{clear:!0}).scrollIntoView()),{reverted:r,skipped:o}}function Kx(e){e.dispatch(e.state.tr.setMeta(sr,{clear:!0}))}function qx(e){const t=sr.getState(e.state);if(!t?.changes.length)return null;const n=t.changes.findIndex(o=>o.id===t.current),r=t.changes[(n+1)%t.changes.length];return e.dispatch(e.state.tr.setMeta(sr,{current:r.id})),r}yn({"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 Hx(){const{t:e}=Zt();return f.jsxs("div",{className:"am-agent-capsule is-live",role:"status","aria-live":"polite","data-testid":"agent-live-capsule",children:[f.jsx("span",{className:"amx-pending-insert-spin","aria-hidden":!0}),f.jsx("span",{className:"am-agent-capsule-text",children:e("agentchg.live")}),f.jsx("span",{className:"am-agent-capsule-hint",children:e("agentchg.liveHint")})]})}function Vx({count:e,index:t,onReview:n,onRevert:r,onKeep:o}){const{t:s}=Zt();return f.jsxs("div",{className:"am-agent-capsule",role:"status","aria-label":s("agentchg.label"),"data-testid":"agent-change-capsule",children:[f.jsx(ic,{size:14,"aria-hidden":!0}),f.jsx("span",{className:"am-agent-capsule-text",children:s("agentchg.summary",{n:String(e)})}),f.jsx("span",{className:"am-agent-capsule-sep","aria-hidden":!0}),f.jsx("button",{type:"button",className:"btn sm","data-act":"review",onClick:n,children:t?s("agentchg.next",{i:String(t),n:String(e)}):s("agentchg.review")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"revert",onClick:r,children:s("agentchg.revert")}),f.jsx("button",{type:"button",className:"btn sm primary","data-act":"keep",onClick:o,children:s("agentchg.keep")})]})}yn({"inlineai.action.improve":{zh:"润色",en:"Improve writing"},"inlineai.action.fix":{zh:"修正拼写与语法",en:"Fix spelling and grammar"},"inlineai.action.shorter":{zh:"精简",en:"Make shorter"},"inlineai.action.longer":{zh:"扩写",en:"Make longer"},"inlineai.action.summarize":{zh:"总结",en:"Summarize"},"inlineai.action.translate":{zh:"翻译",en:"Translate"},"inlineai.action.continue":{zh:"续写",en:"Continue writing"},"inlineai.action.custom":{zh:"自定义指令…",en:"Custom instruction…"},"inlineai.label":{zh:"AI 写作",en:"AI writing"},"inlineai.placeholder":{zh:"告诉 Tangu 要写什么,留空则续写",en:"Tell Tangu what to write, or leave empty to continue"},"inlineai.placeholderSel":{zh:"告诉 Tangu 怎么改选中的文字",en:"Tell Tangu how to change the selection"},"inlineai.send":{zh:"生成",en:"Generate"},"inlineai.generating":{zh:"正在生成…",en:"Generating…"},"inlineai.stop":{zh:"停止",en:"Stop"},"inlineai.replace":{zh:"替换",en:"Replace"},"inlineai.insertBelow":{zh:"插入下方",en:"Insert below"},"inlineai.insert":{zh:"插入",en:"Insert"},"inlineai.discard":{zh:"丢弃",en:"Discard"},"inlineai.retry":{zh:"重试",en:"Try again"},"inlineai.hint":{zh:"预览:确认后才写入笔记",en:"Preview: nothing is written until you confirm"},"inlineai.toolText":{zh:"模型写出了工具调用的样子,但这里什么都没有执行",en:"The model wrote something that looks like a tool call, but nothing was run"},"inlineai.errEmptyResult":{zh:"没有生成任何内容",en:"Nothing was generated"},"inlineai.unavailable":{zh:"这里用不了正文 AI",en:"In-note AI is not available here"},"inlineai.targetChanged":{zh:"选中的文字在生成期间被改过,结果已插入到下方",en:"The selection changed while generating, so the result was inserted below it"}});function Wx({x:e,y:t,anchorTop:n,title:r,hasSelection:o,askFirst:s,run:c,onApply:a,onClose:i,editorEl:d}){const{t:p}=Zt(),[g,C]=v.useState(s?"ask":"running"),[I,N]=v.useState(""),[k,$]=v.useState(""),[F,J]=v.useState(""),[oe,H]=v.useState(!1),te=v.useRef(null),Re=v.useRef(""),Ve=v.useRef(void 0),m=v.useRef(null),de=v.useRef(null),ot=v.useRef(d);ot.current=d;const ce=me=>{te.current?.abort();const Ae=new AbortController;te.current=Ae,Ve.current=me,Re.current="",$(""),J(""),H(!1),C("running"),c(me,Ge=>{Ae.signal.aborted||(Re.current+=Ge,$(Re.current))},Ae.signal).then(Ge=>{if(Ae.signal.aborted)return;const U=String(Ge.text??"");$(U),H(!!Ge.toolCallText),U.trim()?C("done"):(J(p("inlineai.errEmptyResult")),C("error"))}).catch(Ge=>{Ae.signal.aborted||(J(String(Ge?.message||Ge)),C("error"))})},be=()=>{te.current?.abort(),Re.current.trim()?($(Re.current),C("done")):s?C("ask"):i()};v.useEffect(()=>(s?requestAnimationFrame(()=>m.current?.focus()):ce(void 0),()=>te.current?.abort()),[]);const fe=o?"replace":"insert",Me=me=>{const Ae=document.activeElement;return!Ae||Ae===document.body||Ae===document.documentElement?!0:de.current?.contains(Ae)?!me||Ae===de.current:!!ot.current?.contains(Ae)},Ke=v.useRef({phase:g,text:k,primary:fe});return Ke.current={phase:g,text:k,primary:fe},v.useEffect(()=>{const me=Ae=>{Ae.isComposing||Ae.keyCode===229||(Ae.key==="Escape"&&Me(!1)?(Ae.preventDefault(),Ae.stopPropagation(),i()):Ae.key==="Enter"&&!Ae.shiftKey&&!Ae.metaKey&&!Ae.ctrlKey&&!Ae.altKey&&Ke.current.phase==="done"&&Me(!0)&&(Ae.preventDefault(),Ae.stopPropagation(),a(Ke.current.primary,Ke.current.text)))};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[i,a]),f.jsxs(zo,{innerRef:me=>{de.current=me},className:"ui-popover am-ai-panel",x:e,y:t,anchorTop:n,prefer:"below",role:"dialog","aria-label":p("inlineai.label"),"data-testid":"inline-ai-panel","data-phase":g,children:[f.jsxs("div",{className:"am-ai-head",children:[f.jsx(ic,{size:14,"aria-hidden":!0}),f.jsx("span",{className:"am-ai-title",children:r}),g!=="ask"&&f.jsx("span",{className:"am-ai-hint",children:p(g==="running"?"inlineai.generating":"inlineai.hint")})]}),g==="ask"&&f.jsxs("div",{className:"am-ai-ask",children:[f.jsx("textarea",{ref:m,className:"am-ai-input",rows:2,value:I,placeholder:p(o?"inlineai.placeholderSel":"inlineai.placeholder"),onChange:me=>N(me.target.value),onKeyDown:me=>{if(me.key!=="Enter"||me.shiftKey||me.nativeEvent.isComposing||me.keyCode===229)return;me.preventDefault(),me.stopPropagation();const Ae=I.trim();!Ae&&o||ce(Ae||void 0)}}),f.jsxs("div",{className:"am-ai-actions",children:[f.jsx("button",{type:"button",className:"btn sm primary","data-act":"send",disabled:o&&!I.trim(),onClick:()=>ce(I.trim()||void 0),children:p("inlineai.send")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"discard",onClick:i,children:p("inlineai.discard")})]})]}),g!=="ask"&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"am-ai-preview","data-testid":"inline-ai-preview",children:k||(g==="running"?"…":"")}),g==="error"&&f.jsx("div",{className:"am-ai-error",role:"alert",children:F}),oe&&g==="done"&&f.jsx("div",{className:"am-ai-error",children:p("inlineai.toolText")}),f.jsxs("div",{className:"am-ai-actions",children:[g==="running"&&f.jsx("button",{type:"button",className:"btn sm","data-act":"stop",onClick:be,children:p("inlineai.stop")}),g==="done"&&o&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:"btn sm primary","data-act":"replace",onClick:()=>a("replace",k),children:p("inlineai.replace")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"below",onClick:()=>a("below",k),children:p("inlineai.insertBelow")})]}),g==="done"&&!o&&f.jsx("button",{type:"button",className:"btn sm primary","data-act":"insert",onClick:()=>a("insert",k),children:p("inlineai.insert")}),(g==="done"||g==="error")&&f.jsx("button",{type:"button",className:"btn sm","data-act":"retry",onClick:()=>ce(Ve.current),children:p("inlineai.retry")}),f.jsx("button",{type:"button",className:"btn sm","data-act":"discard",onClick:i,children:p("inlineai.discard")})]})]})]})}yn({"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 No=new jn("UNIFIED_PENDING_INSERT");function Yx(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 r=document.createElement("span");r.textContent=Ce("pendins.busy",{label:e.label});const o=document.createElement("button");return o.type="button",o.className="btn sm",o.textContent=Ce("pendins.cancel"),o.addEventListener("mousedown",s=>s.preventDefault()),o.addEventListener("click",s=>{s.preventDefault(),e.onCancel()}),t.append(n,r,o),t}function Xx(){return[St(()=>new Ht({key:No,state:{init:()=>io.empty,apply(e,t){let n=t.map(e.mapping,e.doc);const r=e.getMeta(No);return r&&"add"in r?n=n.add(e.doc,[cr.widget(r.add.pos,()=>Yx(r.add),{id:r.add.id,key:`pending:${r.add.id}`,side:-1,ignoreSelection:!0,stopEvent:()=>!0})]):r&&"remove"in r&&(n=n.remove(n.find(void 0,void 0,o=>o.id===r.remove))),n}},props:{decorations:e=>No.getState(e)}}))]}function xu(e,t){const r=No.getState(e)?.find(void 0,void 0,o=>o.id===t)[0];return r?r.from:null}let Ux=0;function Gx(e,t,n=!0){const r=`p${Date.now().toString(36)}${(Ux++).toString(36)}`;let o=!1;const s=()=>{o=!0,bu(e,r)};return e.dispatch(e.state.tr.setMeta(No,{add:{id:r,pos:e.state.selection.head,label:t,visible:n,onCancel:s}})),{id:r,label:t,cancelled:()=>o}}function bu(e,t){e.isDestroyed||xu(e.state,t)==null||e.dispatch(e.state.tr.setMeta(No,{remove:t}))}function Jx(e,t,n){const r=xu(e.state,t);if(r==null)return!1;let o=e.state.tr.setMeta(No,{remove:t});if(!n?.size)return e.dispatch(o),!0;const s=e.state.doc.resolve(r);let c=s.depth;for(;c>=1&&!["doc","amadeusColumnCell","blockquote"].includes(s.node(c-1).type.name);)c--;const a=e.state.selection;let i,d,p;if(c<1)i=r,o=o.insert(r,n),d=r+n.size,p=e.hasFocus()&&a.empty&&a.head===r;else{const g=s.before(c),C=s.after(c),I=s.node(c).textContent.trim()==="";p=e.hasFocus()&&a.from>=g&&a.to<=C,i=I?g:C,o=I?o.replaceWith(g,C,n):o.insert(C,n),d=i+n.size}return Vs(o,i,d),p&&(o=o.setSelection(Pe.near(o.doc.resolve(Math.min(d,o.doc.content.size)),-1)).scrollIntoView()),e.dispatch(o),!0}function ul(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{level:"warning",text:Ce("pendins.sourceMode",{label:e})}}))}function Zx(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("pendins.lost",{label:e})}}))}function vu(e,t,n){return JSON.stringify(e.slice(t,n).content.toJSON()??[],(r,o)=>{if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="heading"&&o.attrs){const{id:s,...c}=o.attrs;return{...o,attrs:c}}return o})}const co=new jn("amInlineAi");function Qx(e){const t=e.state.selection;if(!(t instanceof Pe)||!t.empty)return!1;const n=t.$from;if(n.parent.type.name!=="paragraph"||n.parent.content.size!==0)return!1;const r=n.depth>=1?n.node(n.depth-1).type.name:"";return r==="doc"||r==="amadeusColumnCell"||r==="amadeusCanvasCard"}function eb(e){return new Ht({key:co,state:{init:()=>null,apply(t,n){const r=t.getMeta(co);if(r&&"clear"in r)return null;if(r&&"set"in r)return r.set;if(!n||!t.docChanged)return n;const o=t.mapping.map(n.from,1);return{...n,from:o,to:Math.max(o,t.mapping.map(n.to,-1))}}},props:{decorations(t){const n=co.getState(t);return!n||n.to<=n.from?null:io.create(t.doc,[cr.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()||!Qx(t)?!1:(e.onSpace(t),!0)}}})}function tb(e){return[St(()=>eb({spaceTrigger:e.spaceTrigger,onSpace:t=>e.onSpace.current(t)}))].flat()}function nb(e,t,n){const r={from:t,to:n,text:e.state.doc.textBetween(t,n,`
58
- `,""),sig:vu(e.state.doc,t,n)},o=e.state.tr.setMeta(co,{set:r});return n>t&&o.setSelection(Pe.create(o.doc,n)),e.dispatch(o),r}function dl(e){const t=co.getState(e.state);if(!t)return;const n=e.state.tr.setMeta(co,{clear:!0});if(t.to>t.from&&t.to<=n.doc.content.size)try{n.setSelection(Pe.create(n.doc,t.from,t.to))}catch{}e.dispatch(n)}function fl(e){return co.getState(e.state)??null}function rb(e,t,n){const r=e.content.size,o=e.textBetween(Math.max(0,t-8e3),t,`
59
- `,"").slice(-2e3),s=e.textBetween(n,Math.min(r,n+4e3),`
60
- `,"").slice(0,1e3);return{before:o,after:s}}function ob(e){const t=e.replace(/[\s\p{P}\p{S}\d]/gu,"");return t?(t.match(/[぀-ヿ㐀-鿿豈-﫿]/g)||[]).length/t.length>.3?"English":"Chinese (Simplified)":"English"}function sb(e,t){const n=e.resolve(t);let r=n.depth;for(;r>=1&&!["doc","amadeusColumnCell"].includes(n.node(r-1).type.name);)r--;return r<1?null:{from:n.before(r),to:n.after(r),blank:n.node(r).textContent.trim()===""}}function ab(e,t,n,r){if(!n.childCount)return null;const{doc:o}=e.state,s=o.content.size,c=Math.min(t.from,s),a=Math.min(Math.max(t.to,c),s);let i=r;i==="replace"&&vu(o,c,a)!==t.sig&&(i="below");let d=e.state.tr,p;if(i==="replace"){const g=n.childCount===1&&!!n.firstChild?.isTextblock&&o.resolve(c).sameParent(o.resolve(a));d=d.replaceRange(c,a,g?new Ka(n,1,1):new Ka(n,0,0)),p=d.mapping.map(a,1)}else{const g=sb(o,i==="below"?a:c);if(!g)return null;i==="insert"&&g.blank?(d=d.replaceWith(g.from,g.to,n),p=g.from+n.size):(d=d.insert(g.to,n),p=g.to+n.size)}return d=d.setSelection(Pe.near(d.doc.resolve(Math.min(p,d.doc.content.size)),-1)),e.dispatch(d.setMeta(co,{clear:!0}).scrollIntoView()),i}yn({"unipage.menu.askTangu":{zh:"问 Tangu",en:"Ask Tangu"}});const cb=2e4;function ib(e,t){let n=null;for(const r of Xs(e)){if(r.pos>t)break;n=r.text}return n}function lb(e,t,n,r){const o=e.textBetween(t,n,`
61
- `,"").trim().slice(0,cb);if(!o)return"";const s=ib(e,t),c=s&&!/[[\]|#^\n]/.test(s)?`#${s}`:"";return r?`${o}
62
- — [[${r}${c}]]`:o}function wu(e,t){const n=e.resolve(t);let r=n.depth;for(;r>=1&&!["doc","amadeusColumnCell"].includes(n.node(r-1).type.name);)r--;return r>=1?n.after(r):null}function ub(e,t,n){if(e.resolve(t).depth!==0)return wu(e,t+1)??e.content.size;let r=e.content.size,o=!1;return e.forEach((s,c)=>{if(r!==e.content.size)return;if(c===t){o=!0;return}if(!o||s.type.name!=="heading")return;(Number(s.attrs.level)||1)<=n&&(r=c)}),r}function db(e,t){if(!t)return null;const n=Xs(e),r=t.heading?n.findIndex(i=>i.text===t.heading.trim()):-1,o=r>=0?n[r]:null,s=o?o.pos:0,c=o?ub(e,o.pos,o.level):e.content.size,a=(t.text??"").split(`
63
- `).map(i=>i.trim()).filter(Boolean);if(a.length){const i=[];e.nodesBetween(s,c,(p,g)=>p.isTextblock?(g>=s&&i.push({pos:g,text:p.textContent}),!1):!0);const d=i.findIndex(p=>p.text.includes(a[0]));if(d>=0){const p=a[a.length-1],g=i.findIndex((I,N)=>N>=d&&I.text.includes(p)),C=wu(e,i[g>=0?g:d].pos+1);if(C!=null)return C}}return o?c:null}yn({"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 ml=500,Ia=250,pl='a[href], sup[data-type="footnote_reference"]';function ku(e,t,n){const r=e.resolve(Math.max(0,Math.min(t,e.content.size)));if(!r.parent.isTextblock)return null;const o=r.start(),s=[];r.parent.forEach((g,C)=>s.push({node:g,from:o+C,to:o+C+g.nodeSize}));const c=g=>!!n.isInSet(g.node.marks);let a=s.findIndex(g=>c(g)&&t>=g.from&&t<g.to);if(a<0&&(a=s.findIndex(g=>c(g)&&t>=g.from&&t<=g.to)),a<0)return null;const i=n.isInSet(s[a].node.marks);let d=a,p=a;for(;d>0&&i.isInSet(s[d-1].node.marks);)d--;for(;p<s.length-1&&i.isInSet(s[p+1].node.marks);)p++;return{from:s[d].from,to:s[p].to,mark:i}}function fb(e,t){const n=e.state.schema.marks.link;if(!n)return null;let r;try{r=e.posAtDOM(t,0)}catch{return null}const o=ku(e.state.doc,r,n);return o&&o.from<o.to?{from:o.from,to:o.to}:null}function mb({getView:e,onOpenNote:t}){const{t:n}=Zt(),[r,o]=v.useState(null),[s,c]=v.useState(null),[a,i]=v.useState(null),d=v.useRef(null),p=v.useRef(null);v.useEffect(()=>{const N=()=>{d.current&&clearTimeout(d.current),p.current&&clearTimeout(p.current),d.current=null,p.current=null},k=J=>{const oe=e()?.dom.closest(".unified-body");return!!oe&&J.closest(".unified-body")===oe},$=J=>{const H=J.target?.closest?.(pl);if(!H||!k(H))return;if(p.current&&(clearTimeout(p.current),p.current=null),d.current&&clearTimeout(d.current),H.tagName==="SUP"){d.current=setTimeout(()=>{const Re=e(),Ve=H.getBoundingClientRect();o(null),c({num:H.textContent??"",text:Re?Cd(Re.state.doc,H.getAttribute("data-label")??""):null,x:Ve.left,y:Ve.bottom+6})},ml);return}const te=H;d.current=setTimeout(()=>{const Re=e();c(null);const Ve=te.getBoundingClientRect(),m=Re?fb(Re,te):null;o({href:te.getAttribute("href")??"",text:m&&Re?Re.state.doc.textBetween(m.from,m.to):te.textContent??"",from:m?.from??-1,to:m?.to??-1,x:Ve.left,y:Ve.bottom+6})},ml)},F=J=>{!J.target?.closest?.(pl)||J.relatedTarget?.closest?.(".amx-linkcard")||(d.current&&clearTimeout(d.current),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{o(null),c(null)},Ia))};return document.addEventListener("mouseover",$,!0),document.addEventListener("mouseout",F,!0),()=>{document.removeEventListener("mouseover",$,!0),document.removeEventListener("mouseout",F,!0),N()}},[e]),v.useEffect(()=>{if(!r&&!s||a)return;const N=()=>{o(null),c(null)};return document.addEventListener("scroll",N,!0),()=>document.removeEventListener("scroll",N,!0)},[r,s,a]);const g=(N,k,$,F,J)=>{const oe=e(),H=oe?.state.schema.marks.link;if(!oe||!H)return;const{doc:te}=oe.state;if(k>te.content.size||N>=k)return;const Re=ku(te,N,H);if(!Re||Re.from!==N||Re.to!==k||Re.mark.attrs.href!==$)return;const Ve=te.textBetween(N,k),m=ot=>H.create({...Re.mark.attrs,href:ot,..."ref"in Re.mark.attrs?{ref:null}:{}});let de=oe.state.tr;if(F==="")de=de.delete(N,k);else if(F!==null&&F!==Ve){let ot=null;te.nodesBetween(N,k,be=>be.isInline?(ot=ot===null?be.marks:ot.filter(fe=>fe.isInSet(be.marks)),!1):!0);const ce=(ot??[]).filter(be=>be.type!==H);de=de.replaceWith(N,k,oe.state.schema.text(F,J?m(J).addToSet(ce):ce)),de.setSelection(Pe.near(de.doc.resolve(N+F.length)))}else if(J){if(J===Re.mark.attrs.href){oe.focus();return}de=de.removeMark(N,k,Re.mark).addMark(N,k,m(J))}else de=de.removeMark(N,k,Re.mark);oe.dispatch(de.scrollIntoView()),oe.focus()};if(a){const N=!!Wc(a.href)&&!!a.text.trim(),k=()=>{i(null),o(null),e()?.focus()};return f.jsxs(ao,{children:[f.jsx("div",{className:"amx-linkedit-backdrop",onMouseDown:()=>i(null),role:"presentation"}),f.jsx(zo,{className:"amx-linkedit",x:window.innerWidth/2,y:Math.round(window.innerHeight*.3),center:!0,children:f.jsxs("form",{className:"amx-linkedit-form",onSubmit:$=>{$.preventDefault();const F=Wc(a.href);!F||!a.text.trim()||(g(a.from,a.to,a.wasHref,a.text,F),i(null),o(null))},onKeyDown:$=>{$.key==="Escape"&&($.preventDefault(),$.stopPropagation(),k())},children:[f.jsxs("label",{children:[n("linkcard.text"),f.jsx("input",{autoFocus:!0,value:a.text,onChange:$=>i({...a,text:$.target.value}),onFocus:$=>$.currentTarget.select()})]}),f.jsxs("label",{children:[n("linkcard.link"),f.jsx("input",{value:a.href,onChange:$=>i({...a,href:$.target.value})})]}),f.jsxs("div",{className:"amx-linkedit-row",children:[f.jsx("button",{type:"button",onClick:k,children:n("common.cancel")}),f.jsx("button",{type:"submit",className:"primary",disabled:!N,children:n("common.save")})]})]})})]})}if(s)return f.jsx(ao,{children:f.jsxs(zo,{className:"amx-linkcard amx-fncard",x:s.x,y:s.y,onMouseEnter:()=>{p.current&&clearTimeout(p.current),p.current=null},onMouseLeave:()=>{p.current=setTimeout(()=>c(null),Ia)},children:[f.jsx("span",{className:"amx-fncard-num",children:s.num}),f.jsx("span",{className:`amx-fncard-text${s.text?"":" muted"}`,children:s.text==null?n("linkcard.fnMissing"):s.text||n("linkcard.fnEmpty")})]})});if(!r)return null;let C=r.href;try{C=new URL(r.href).host||r.href}catch{}const I=r.from>=0&&(e()?.editable??!0);return f.jsx(ao,{children:f.jsxs(zo,{className:"amx-linkcard",x:r.x,y:r.y,onMouseEnter:()=>{p.current&&clearTimeout(p.current),p.current=null},onMouseLeave:()=>{p.current=setTimeout(()=>o(null),Ia)},children:[f.jsx("button",{className:"amx-linkcard-host",title:r.href,onClick:()=>{t&&kd(r.href)==="note"?(o(null),t(r.href)):window.open(r.href,"_blank","noopener")},children:C}),f.jsx("span",{className:"amx-linkcard-sep"}),f.jsx("button",{onClick:()=>{navigator.clipboard.writeText(r.href)},children:n("linkcard.copy")}),I&&f.jsx("button",{onClick:()=>i({from:r.from,to:r.to,text:r.text,href:r.href,wasHref:r.href}),children:n("common.edit")}),I&&f.jsx("button",{onClick:()=>{g(r.from,r.to,r.href,null,null),o(null)},children:n("linkcard.unlink")}),I&&f.jsx("button",{className:"danger",onClick:()=>{g(r.from,r.to,r.href,"",null),o(null)},children:n("common.delete")})]})})}yn({"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 oc(e){const t=e?.state.selection;return t instanceof ze&&t.node.type.spec.tableRole==="table"}function pb(e,t,n){if(!e||!oc(e))return null;const r=document.elementFromPoint(t,n)?.closest?.("td,th");if(!r||!e.dom.contains(r))return null;try{return Ad(e.state.doc,e.posAtDOM(r,0))}catch{return null}}const hb=[{op:"rowAbove",key:"unipage.table.rowAbove",Icon:hp},{op:"rowBelow",key:"unipage.table.rowBelow",Icon:mp},{op:"colLeft",key:"unipage.table.colLeft",Icon:bp},{op:"colRight",key:"unipage.table.colRight",Icon:yp},{op:"deleteRow",key:"unipage.table.deleteRow",Icon:Ha},{op:"deleteCol",key:"unipage.table.deleteCol",Icon:Ha}],gb=[{align:"left",key:"unipage.table.alignLeft",Icon:Hf},{align:"center",key:"unipage.table.alignCenter",Icon:Ed},{align:"right",key:"unipage.table.alignRight",Icon:Md}];function yb({view:e,cell:t,onDone:n}){const{t:r}=Zt(),o=e.state.selection;if(!(o instanceof ze)||o.node.type.spec.tableRole!=="table")return null;const s=Sd(e.state.doc,o.from,t);if(!s)return null;const c=a=>{n();const i=a();i&&e.dispatch(i),e.focus()};return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"ubm-sep",role:"separator"}),f.jsx("div",{className:"ubm-label",role:"presentation",children:r("unipage.table.label")}),hb.filter(a=>s.ops.includes(a.op)).map(({op:a,key:i,Icon:d})=>f.jsxs("button",{"data-table-op":a,role:"menuitem",tabIndex:-1,onClick:()=>c(()=>zd(e.state,s.cellPos,a)),children:[f.jsx(d,{size:13})," ",r(i)]},a)),s.align&&gb.map(({align:a,key:i,Icon:d})=>f.jsxs("button",{"data-table-align":a,"aria-checked":s.align===a,role:"menuitemcheckbox",tabIndex:-1,onClick:()=>c(()=>Nd(e.state,s.cellPos,a)),children:[f.jsx(d,{size:13})," ",r(i),s.align===a&&f.jsx(ea,{size:13,className:"ubm-check"})]},a))]})}function xb(e,t){return{el:e,owns:n=>{const r=t();if(!r||!r.dom.contains(n))return!1;for(let o=n.nodeType===1?n:n.parentElement;o&&o!==r.dom;o=o.parentElement)if(o.contentEditable==="false"||o.classList.contains("ProseMirror"))return!1;return!0},replace:n=>{const r=t();if(!r||!r.editable)return 0;const o=[];for(const{range:c,text:a}of n){let i,d;try{i=r.posAtDOM(c.startContainer,c.startOffset),d=r.posAtDOM(c.endContainer,c.endOffset)}catch{continue}d<=i||r.state.doc.textBetween(i,d,`
64
- `,"")!==c.toString()||o.push({from:i,to:d,text:a})}if(!o.length)return 0;o.sort((c,a)=>a.from-c.from);const s=r.state.tr;for(const c of o)c.text?s.insertText(c.text,c.from,c.to):s.delete(c.from,c.to);return r.dispatch(s),o.length}}}yn({"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 bb=800;let Os=null,Pa=null;const vb={insertAfter:()=>{},deleteEmpty:()=>{},mergePrev:()=>{},arrow:()=>{},moveDir:()=>{},selfFocus:()=>{}};async function Cu(e,t){try{const n=new Uint8Array(await t.arrayBuffer()),{opts:r}=await Va(),{base:o}=await vn.saveAttachment(e,t.name||"file",n,r);return`![[${o}]]`}catch{return null}}let ko=null;function Co(){ko&&(clearTimeout(ko.timer),clearTimeout(ko.arm),ko.off(),ko.el.remove(),ko=null)}function Ks(e){if(Co(),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 r=()=>{window.removeEventListener("scroll",Co,!0),window.removeEventListener("wheel",Co,!0)},o=window.setTimeout(()=>{window.addEventListener("scroll",Co,!0),window.addEventListener("wheel",Co,!0)},300);ko={el:t,timer:window.setTimeout(Co,1400),arm:o,off:r}}function wb(e,t,n=!1,r=!1){const o=[],s=Lx(e.state,t,n?o:void 0);s&&(r&&s.setMeta("addToHistory",!0),e.dispatch(n?_x(s,e.state.doc,o):s))}function kb({path:e,pageDir:t,body:n,onChange:r,onFinalFlush:o,skipFinalFlush:s,hidden:c,apiRef:a,probe:i,extraPlugins:d,focusPlace:p,onFocused:g,onCard:C,readOnly:I=!1,onAskTangu:N,aiMenu:k,onAiPrompt:$}){const[,F]=Dd(),J=ac(),oe=v.useRef(null),[H,te]=v.useState(!1),Re=v.useRef({onFinalFlush:o,skipFinalFlush:s});Re.current={onFinalFlush:o,skipFinalFlush:s};const Ve=v.useRef(C);Ve.current=C;const m=v.useRef($);m.current=$,v.useEffect(()=>(a.current={applySlashItem:U=>Ae.current(U),applyBody:(U,ae,$e)=>{let T=!1;return F()?.action(Z=>{const ie=Z.get(bn),we=Z.get(Lo)(go(U,t));we&&(wb(ie,we,ae,$e),Id(ie.state.doc,we),T=!0,i&&(i.reconciled=(i.reconciled??0)+1))}),T},serializeNow:()=>{let U=null;return F()?.action(ae=>{const $e=ae.get(bn);U=Oo(As(ae,$e.state.doc),t)}),U},canonical:U=>{let ae=null;return F()?.action($e=>{const T=$e.get(Lo)(go(U,t));T&&(ae=Oo(As($e,T),t))}),ae},insertFiles:U=>{ot(U)},insertMarkdown:(U,ae,$e)=>ce(U,ae,$e),parseMd:U=>{let ae=null;return F()?.action($e=>{const T=$e.get(Lo)(go(U,t));ae=T?.childCount?T.content:null}),ae},serializeMd:U=>{let ae=null;try{F()?.action($e=>{const Z=$e.get(bn).state.schema.topNodeType.createAndFill(void 0,U);Z&&(ae=Ld($e.get(gm)(Z)))})}catch{return null}return ae},serializeStored:U=>{let ae=null;try{F()?.action($e=>{const T=$e.get(bn).state.schema.topNodeType.createAndFill(void 0,U);T&&(ae=Oo(As($e,T),t))})}catch{return null}return ae},focusStart:()=>{F()?.action(U=>{const ae=U.get(bn);ae.dispatch(ae.state.tr.setSelection(Pe.atStart(ae.state.doc))),ae.focus()})},focusEnd:()=>{F()?.action(U=>{const ae=U.get(bn);ae.dispatch(ae.state.tr.setSelection(Pe.atEnd(ae.state.doc))),ae.focus()})},focusTail:()=>{F()?.action(U=>{const ae=U.get(bn),{doc:$e,schema:T}=ae.state,Z=T.nodes.paragraph,ie=qe=>!!qe&&qe.type===Z&&qe.content.size===0,we=$e.lastChild;let Qe=ae.state.tr;ie(we)||(Qe=Qe.insert($e.content.size,Z.create())),ae.dispatch(Qe.setSelection(Pe.atEnd(Qe.doc)).scrollIntoView()),ae.focus()})},hasFocus:()=>{let U=!1;return F()?.action(ae=>{U=ae.get(bn).hasFocus()}),U},revealSelection:()=>{F()?.action(U=>{const ae=U.get(bn);ae.dispatch(ae.state.tr.scrollIntoView()),ae.focus()})},serializePrefix:U=>{let ae=null;try{F()?.action($e=>{const T=$e.get(bn);ae=Oo(As($e,T.state.doc.cut(0,Math.min(U,T.state.doc.content.size))),t)})}catch{return null}return ae},posAfterPrefix:U=>{let ae=null;try{F()?.action($e=>{const T=$e.get(Lo)(go(U,t));T&&(ae=Pe.atEnd(T).head)})}catch{return null}return ae}},()=>{if(!Re.current.skipFinalFlush()){const U=a.current?.serializeNow()??null;U!=null&&Re.current.onFinalFlush(U)}a.current=null}),[F,t]);const de=async U=>{try{const ae=new Uint8Array(await U.arrayBuffer()),{opts:$e}=await Va(),{pageRel:T}=await vn.saveAttachment(e,U.name||"pasted.png",ae,$e);return vl(bl(t,T))}catch{return null}},ot=async U=>{if(!U.length)return;const ae=U.map((T,Z)=>`​${Ce("unipage.upload.uploading",{name:T.name||Ce("unipage.upload.fileN",{n:Z+1})})}​`);F()?.action(T=>{const Z=T.get(bn),ie=Z.state.schema.nodes.paragraph;if(!ie)return;const{$to:we}=Z.state.selection;let Qe=we.depth>=1?we.after(1):we.pos,qe=Z.state.tr;for(const zt of ae){const st=ie.create(null,Z.state.schema.text(zt));qe=qe.insert(Qe,st),Qe+=st.nodeSize}Z.dispatch(qe.scrollIntoView())});const $e=(T,Z)=>{F()?.action(ie=>{const we=ie.get(bn);let Qe=-1,qe=-1;if(we.state.doc.descendants((mt,ct)=>Qe>=0||!mt.isTextblock||mt.textContent!==T?!0:(Qe=ct,qe=ct+mt.nodeSize,!1)),Qe<0)return;const zt={from:Qe,to:qe},st=we.state.schema.nodes.paragraph,it=Z&&st?we.state.tr.replaceWith(zt.from,zt.to,st.create(null,we.state.schema.text(Z))):we.state.tr.delete(zt.from,zt.to);we.dispatch(it)})};for(let T=0;T<U.length;T++)$e(ae[T],await Cu(e,U[T]))},ce=(U,ae="cursor",$e)=>{let T=!1;return F()?.action(Z=>{const ie=Z.get(bn),we=Z.get(Lo)(go(U,t));if(!we?.childCount)return;const Qe=we.content,qe=!!$e?.quiet,zt=qe?db(ie.state.doc,$e?.after):null;if(qe&&zt==null&&$e?.caretless&&(ae="end"),ae!=="cursor"||zt!=null){const bt=zt??(ae==="start"?0:ie.state.doc.content.size),lt=ie.state.tr.insert(bt,Qe);qe?be(ie,lt,bt):ie.dispatch(lt),T=!0;return}const{$from:st}=ie.state.selection;let it=st.depth;for(;it>=1&&!["doc","amadeusColumnCell","blockquote"].includes(st.node(it-1).type.name);)it--;if(it<1)return;const mt=(bt,lt)=>{const Ot=Pe.near(bt.doc.resolve(Math.min(lt,bt.doc.content.size)),-1),on=$e?.caretBack??0;bt.setSelection(on&&Ot.$from.parentOffset>=on?Pe.create(bt.doc,Ot.from-on):Ot)};if(st.depth>it&&st.parent.isTextblock&&st.parent.content.size===0){const bt=ie.state.tr,lt=on=>{const Xt=bt.doc.resolve(on),Sn=Xt.index(-1);return Xt.parent.isTextblock&&Xt.parent.content.size===0&&Xt.node(-1).canReplace(Sn,Sn+1,Qe)};let Ot=st.pos;if(!lt(Ot)){for(let on=bt.doc.resolve(Ot).depth;on>0;on--)if(bt.doc.resolve(Ot).node(on).type.name==="list_item"){Ot=Pd(bt,Ot,["list_item"]);break}}if(lt(Ot)){const on=bt.doc.resolve(Ot),Xt=on.before();bt.replaceWith(Xt,on.after(),Qe),Vs(bt,Xt,Xt+Qe.size),mt(bt,Xt+Qe.size),qe?be(ie,bt,Xt):(ie.dispatch(bt.scrollIntoView()),ie.focus()),T=!0;return}}const ct=st.before(it),dn=st.after(it),ut=st.node(it).textContent.trim()==="",Wn=ut?ie.state.tr.replaceWith(ct,dn,Qe):ie.state.tr.insert(dn,Qe);Vs(Wn,ut?ct:dn,(ut?ct:dn)+Qe.size),mt(Wn,(ut?ct:dn)+Qe.size),qe?be(ie,Wn,ut?ct:dn):(ie.dispatch(Wn.scrollIntoView()),ie.focus()),T=!0}),T},be=(U,ae,$e)=>{U.dispatch(Ws(ae)),El(U,Math.min($e+1,U.state.doc.content.size));const T=U.nodeDOM($e);if(!(T instanceof HTMLElement))return;const Z=T.getBoundingClientRect();(Z.top<0||Z.top>window.innerHeight-40)&&as(T),Ks(T.getBoundingClientRect())},fe=(U,ae=!0)=>{let $e=null;return F()?.action(T=>{$e=Gx(T.get(bn),U,ae)}),$e},Me=U=>{U&&F()?.action(ae=>bu(ae.get(bn),U.id))},Ke=(U,ae,$e=!0)=>{if(ae?.cancelled())return;if(c?.()){Me(ae),ul(ae?.label??"");return}const T=()=>{$e||!ae?window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.insertPointLost")}})):Zx(ae.label)};if(!a.current||!ae){T();return}let Z=!1;F()?.action(ie=>{const we=ie.get(Lo)(go(U,t));Z=Jx(ie.get(bn),ae.id,we?.childCount?we.content:null)}),Z||T()},me=async(U,ae,$e,T=!1)=>{try{const{base:Z}=await vn.saveAttachment(e,U,ae,{mode:"vault",folder:pa(e)});Ke(`![[${T?Z.replace(/\.md$/i,""):Z}]]`,$e),J.getState().syncFdChildren(e)}catch{Me($e)}},Ae=v.useRef(()=>{}),Ge=U=>{const ae=oe.current;if(!ae)return;const $e=U.run?void 0:_d[U.scaffold];if($e){ae.transform($e)||Bd(U.label);return}ae.consume();const T=Kd;if(U.scaffold===T.template){window.dispatchEvent(new CustomEvent("amadeus:template-picker",{detail:{v4Path:e}}));return}if(U.scaffold===T.card){F()?.action(Z=>Ve.current(Z.get(bn)));return}if(U.scaffold===T.instructions||U.scaffold===T.agentTask||U.scaffold===T.prompt){const Z=U.scaffold===T.instructions?"instructions":U.scaffold===T.agentTask?"task":"prompt";ce(qd(Z,Z==="instructions"?"":ps(Hd())));return}if(U.scaffold===T.ai){F()?.action(Z=>m.current?.(Z.get(bn)));return}if(U.run){const Z=fe(U.label);(async()=>{try{const ie=await U.run({pagePath:e,folder:pa(e)});if(ie===""||ie==null){Me(Z);return}if(typeof ie!="string")throw new Error(Ce("unipage.plugin.notString",{type:typeof ie}));if(ie.length>8192)throw new Error(Ce("unipage.plugin.tooLong"));if(Array.from(ie).some(we=>we.charCodeAt(0)<32&&we!==" "&&we!==`
65
- `))throw new Error(Ce("unipage.plugin.controlChars"));Ke(ie,Z,!1),J.getState().syncFdChildren(e)}catch(ie){if(Me(Z),Z?.cancelled())return;console.error("[plugin] slash item failed",ie),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.plugin.failed",{label:U.label,err:ie instanceof Error?ie.message:String(ie)}),error:!0}}))}})();return}if(U.scaffold===T.image){const Z=document.createElement("input");Z.type="file",Z.accept="image/*",Z.onchange=()=>{const ie=Z.files?.[0];if(!ie)return;const we=fe(U.label);(async()=>{try{const Qe=new Uint8Array(await ie.arrayBuffer()),{opts:qe}=await Va(),{base:zt}=await vn.saveAttachment(e,ie.name||"image.png",Qe,qe);Ke(`![[${zt}]]`,we)}catch{Me(we)}})()},Z.click();return}if(U.scaffold===T.column){F()?.action(Z=>{const ie=Z.get(bn),{$from:we}=ie.state.selection;if(we.depth!==1){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.columnTopLevelOnly")}}));return}Jl(ie,we.before(1),we.after(1),we.node(1)),ie.focus()});return}if(U.scaffold===T.page){const Z=fe(U.label);(async()=>{try{const ie=J.getState(),we=await ie.createChildNote(e,Ce("amadeus.default.note"));Ke(`[[${we.split("/").pop().replace(/\.md$/i,"")}]]`,Z),ie.loadPage(we)}catch{Me(Z)}})();return}if(U.scaffold===T.database){const Z=Ce("amadeus.default.database");me(`${Z}.db`,new TextEncoder().encode(Vc(nd(Z))),fe(U.label));return}if(U.scaffold===T.drawing){me(`${Vd(Ce("unipage.file.drawing"))}.excalidraw.md`,new TextEncoder().encode(rd(sd)),fe(U.label),!0);return}if(U.scaffold===T.noteview){const Z=fe(U.label);(async()=>{const ie=pa(e);let we=null;for(let qe=1;qe<=20&&we===null;qe++)try{we=await vn.createFolder(ie,qe===1?Ce("unipage.file.noteView"):Ce("unipage.file.noteViewN",{n:qe}))}catch{}if(we===null){Me(Z);return}const Qe=Ce("unipage.file.untitledView");await me(`${Qe}.db`,new TextEncoder().encode(Vc(ad(Qe,we))),Z)})();return}if(U.scaffold===T.linkdb){te(!0);return}if(U.scaffold===T.bookmark){const Z=fe(U.label,!1);qa(Ce("unipage.bookmark.title"),"",{label:Ce("unipage.bookmark.label")}).then(ie=>{const we=ie?.trim();we&&/^https?:\/\/\S+$/i.test(we)?Ke(we,Z,!1):Me(Z)});return}if(U.scaffold===T.embed){const Z=fe(U.label,!1);(async()=>{let ie="";try{const qe=/!?\[\[([^\]\n]+)\]\]/.exec(await navigator.clipboard.readText());qe&&(ie=qe[1].trim())}catch{}const Qe=(await qa(Ce("unipage.embed.title"),ie,{label:Ce("unipage.embed.label"),confirmLabel:Ce("unipage.embed.confirm")}))?.trim().replace(/^!?\[\[/,"").replace(/\]\]$/,"").trim();Qe?Ke(`![[${Qe}]]`,Z,!1):Me(Z)})();return}ce(U.scaffold,"cursor",U.key==="math"?{caretBack:3}:void 0)};return Ae.current=Ge,f.jsxs(f.Fragment,{children:[f.jsx(Fd,{initial:go(n,t),onChange:U=>r(Oo(U,t)),keys:vb,saveImage:de,saveFiles:ot,onOpenWiki:(U,ae)=>{J.getState().openWikiLink(U,e,ae)},getPageNames:()=>J.getState().pages,slashOpsRef:oe,onSlashPick:Ge,getFiles:()=>ym()?J.getState().files:[],isWikiResolved:U=>!!hs(U,J.getState().pages,e)||!!Al(U,J.getState().files,e),wikiIcon:U=>{const ae=hs(U,J.getState().pages,e);return ae?J.getState().icons[ae]:void 0},focusPlace:p,onFocused:g,unified:!0,attachmentPagePath:e,extraPlugins:d,readOnly:I,onAskTangu:N,aiMenu:k}),H&&f.jsx(ao,{children:f.jsx(Od,{onClose:()=>te(!1),onPick:U=>{te(!1),c?.()?ul(Ce("mdblock.slash.linkdb")):ce(`![[${U}]]`)}})})]})}function hl(e){e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)}function Cb(e){const t=e.selectionEnd;if(t>=e.value.length)return!0;const n=getComputedStyle(e),r=document.createElement("div");for(const i of["fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","wordSpacing","lineHeight","textTransform","textIndent","tabSize","paddingLeft","paddingRight","borderLeftWidth","borderRightWidth","boxSizing","wordBreak","overflowWrap"])r.style[i]=n[i];Object.assign(r.style,{position:"absolute",visibility:"hidden",left:"-99999px",top:"0",width:`${e.offsetWidth}px`,whiteSpace:"pre-wrap",borderStyle:"solid",borderColor:"transparent"});const o=document.createElement("span"),s=document.createElement("span"),c=String.fromCodePoint(e.value.codePointAt(t)??32);o.textContent=c,s.textContent="​",r.append(e.value.slice(0,t),o,e.value.slice(t+c.length),s),document.body.appendChild(r);const a=o.offsetTop>=s.offsetTop;return r.remove(),a}function Sb({path:e,icon:t,cover:n,onSetIcon:r,onSetCover:o,onRename:s,onDetachedRename:c,onEnterBody:a,focusSignal:i,compact:d=!1,readOnly:p=!1}){const{t:g}=Zt(),C=Sl(),I=(e.split("/").pop()??e).replace(/\.md$/i,""),N=Nm.test(I)?"":I,[k,$]=v.useState(N),[F,J]=v.useState(null),[oe,H]=v.useState(null),te=v.useRef(null),Re=v.useRef(null),Ve=v.useRef(c);Ve.current=c,v.useEffect(()=>{$(N),Re.current=null},[e]),v.useLayoutEffect(()=>()=>{const ce=Re.current;Re.current=null,ce!=null&&Ve.current(ce)},[]),v.useLayoutEffect(()=>{hl(te.current)},[k]),v.useEffect(()=>{const ce=te.current;if(!ce)return;let be=ce.clientWidth;const fe=new ResizeObserver(()=>{ce.clientWidth!==be&&(be=ce.clientWidth,hl(ce))});return fe.observe(ce),()=>fe.disconnect()},[]),v.useEffect(()=>{if(!i)return;const ce=te.current;if(ce){ce.focus();const be=ce.value.length;ce.setSelectionRange(be,be)}},[i]);const m=v.useRef(null),de=v.useRef(!1),ot=()=>{const ce=m.current;if(m.current=null,Re.current=null,de.current){de.current=!1,$(N);return}const be=k.trim();be&&be!==I?s(be,ce).then(fe=>{fe||$(N)}):$(N)};return p?f.jsxs("div",{className:"amx-title-wrap amx-title-ro",children:[t&&f.jsx("span",{className:"amx-title-bigicon","aria-hidden":!0,children:t}),f.jsx("div",{className:"amx-title-row",children:f.jsx("h1",{className:"amx-title-input amx-title-static",children:N||I})})]}):f.jsxs("div",{className:"amx-title-wrap",children:[!d&&t&&f.jsx("button",{className:"amx-title-bigicon",title:g("unipage.title.iconAction"),onClick:ce=>{const be=ce.currentTarget.getBoundingClientRect();J({x:be.left,y:be.bottom+6})},children:t}),!d&&(!t||!n)&&f.jsxs("div",{className:"amx-title-actions",children:[!t&&f.jsxs("button",{onClick:()=>r(Em()),children:[f.jsx(Sm,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),g("unipage.title.addIcon")]}),!n&&f.jsxs("button",{onClick:ce=>{const be=ce.currentTarget.getBoundingClientRect();H({x:be.right,y:be.bottom+6})},children:[f.jsx(dm,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),g("unipage.title.addCover")]})]}),f.jsx("div",{className:"amx-title-row",children:f.jsx("textarea",{ref:te,className:"amx-title-input",rows:1,spellCheck:C,value:k,placeholder:"New Page",onChange:ce=>{const be=ce.target.value.replace(/[\r\n]+/g," ");Re.current=be,$(be)},onBlur:ot,onKeyDown:ce=>{if(ce.nativeEvent.isComposing||ce.keyCode===229)return;const be=ce.currentTarget;if(ce.key==="Tab"){ce.preventDefault();return}const fe=be.selectionStart===be.selectionEnd,Me=fe&&be.selectionEnd===be.value.length,Ke=!ce.shiftKey&&!ce.altKey&&!ce.metaKey&&!ce.ctrlKey,me=ce.key==="ArrowDown"&&Ke&&fe&&Cb(be);(ce.key==="Enter"||ce.key==="ArrowRight"&&Ke&&Me||me)&&(ce.preventDefault(),m.current=ce.key==="Enter"?"enter":"move",be.blur(),a(ce.key==="Enter"?"enter":"move")),ce.key==="Escape"&&(Re.current=null,de.current=!0,$(N),be.blur())}})}),F&&f.jsx(Mm,{x:F.x,y:F.y,current:t,onPick:ce=>{r(ce),J(null)},onClose:()=>J(null)}),oe&&f.jsx(zm,{page:e,x:oe.x,y:oe.y,onApply:ce=>o(ce),onClose:()=>H(null)})]})}function Eb({path:e,initial:t,diskRaw:n,probe:r,onRenamed:o,onCanvasMode:s,historyRef:c,filesRef:a,mdRef:i,onUnlock:d,compact:p=!1,readOnly:g=!1,hardBreaks:C=!1}){const I=e.split("/").slice(0,-1).join("/"),N=ac(),k=N.getState().vaultRoot,$=v.useContext(Vf),F=Wf(),J=$??F,oe=Yf(l=>Xf(l,J)),H=g?"wysiwyg":oe,{t:te}=Zt(),Re=Sl(),Ve=v.useRef(null);if(!Ve.current){const l=qo(n??t),{fmText:h,body:x}=vo(n==null?l.text:qo(t).text);Ve.current={fm:h,body:x,lastSaved:l.text,eol:l.eol,pending:!1,timer:null,reconcileBusy:0,unpreserved:null,preserved:new Set,failed:!1,retryTimer:null,retryN:0,stashed:null,writing:0,dead:!1,retired:!1,sawRows:!1,ownedCards:new Set,chain:Promise.resolve(),readOnly:g,slot:$,peerPatch:null}}const m=Ve.current,de=v.useRef(0),ot=v.useRef(null),ce=v.useRef(()=>{ot.current?.()}).current,be=()=>{de.current=performance.now(),fi(ce)},fe=v.useRef(!1);v.useEffect(()=>{$!=null&&$===F&&be()},[$,F]);const[Me]=v.useState(()=>new Set),Ke=()=>{for(const l of[...Me])l()},[me,Ae]=v.useState(0),[Ge,U]=v.useState(0),ae=v.useRef(null),$e=v.useRef(H==="source"),T=v.useMemo(()=>({get current(){return $e.current?null:ae.current}}),[]);if($e.current!==(H==="source")){if(H==="source"){const l=ae.current?.serializeNow();l!=null&&(m.body=l)}$e.current=H==="source"}const Z=v.useRef(null),ie=v.useRef(null),[we,Qe]=v.useState(null),[qe,zt]=v.useState(()=>{if(Ko())return!1;const l=Uf(k,e);return l?l==="canvas":_n(un(m.fm))?.mode==="canvas"}),[st,it]=v.useState(0),mt=v.useRef(!1),ct=v.useRef(qe);ct.current=qe;const dn=v.useRef(!1),ut=un(m.fm),Wn=v.useMemo(()=>_n(ut),[ut]),bt=Wn?.main??{x:0,y:0,w:Or},lt=()=>{const l=!qe;if((T.current?.hasFocus()??!1)&&(l?it(x=>x+1):mt.current=!0),l){const x=ie.current?.closest(".amx-pane");x&&ui(k,e,x.scrollTop)}ct.current=l,dn.current=!0,im(k,e,l?"canvas":"doc"),zt(l),un(m.fm)!=null&&(Nt(),cn())},Ot=v.useRef(lt);Ot.current=lt,ot.current=H==="source"?null:()=>Ot.current(),v.useEffect(()=>(fi(ce),()=>Gf(ce)),[ce]);const on=v.useRef(l=>T.current?.applySlashItem(l)).current;v.useEffect(()=>(da(on),()=>{Wd()===on&&da(null)}),[on]),v.useEffect(()=>(s?.({on:qe,toggle:()=>Ot.current(),...qe&&H!=="source"&&!g?{exportCanvas:()=>Sn.current?.()}:{}}),()=>s?.(null)),[qe,s,H,g]);const Xt=v.useRef(null),Sn=v.useRef(null);v.useEffect(()=>{if(!c)return;const l=w=>{if(m.readOnly)return!1;if(ct.current&&Xt.current)return Xt.current(w);const z=Vt();return!!z&&(w==="undo"?_a:Cl)(z.state,z.dispatch)},x={undo:()=>l("undo"),redo:()=>l("redo"),indent:w=>{const z=Vt();return!m.readOnly&&!!z&&Oe.indent(z,w)}};return c.current=x,()=>{c.current===x&&(c.current=null)}},[c]);const Zn=l=>{const h=un(m.fm);if(h!=null&&_n(h)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.canvasElementsFailed"),error:!0}}));return}m.fm=us(m.fm,pr(m.fm),Yy(h,l)),Ae(x=>x+1),Ln(),cn()},fo=l=>{const h=un(m.fm);if(h!=null&&_n(h)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.canvasTreeFailed"),error:!0}}));return}m.fm=us(m.fm,pr(m.fm),Uy(h,l)),Ae(x=>x+1),Ln(),cn()},en=l=>{const h=un(m.fm);if(h!=null&&_n(h)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.canvasMainFailed"),error:!0}}));return}m.fm=us(m.fm,pr(m.fm),Xy(h,l)),Ae(x=>x+1),Ln(),cn()},Yn=v.useMemo(()=>({log:[],future:[]}),[e]),En=qe&&H!=="source";v.useEffect(()=>{Qe(ie.current)},[]),v.useEffect(()=>{const l=Z.current?.closest(".amx-pane");if(l)return l.classList.toggle("amx-canvas-pane",En),()=>l.classList.remove("amx-canvas-pane")},[En]),v.useEffect(()=>{if(qe)return;const l=ie.current?.closest(".amx-pane");if(!l)return;const h=Jf(k,e);let x=!1,w=0;const z=performance.now()+1500,Y=()=>{if(l.scrollTop=h,l.scrollTop!==h&&performance.now()<z){w=requestAnimationFrame(Y);return}x=!0};w=requestAnimationFrame(Y);const se=()=>{cancelAnimationFrame(w),x=!0},ye=()=>{x&&ui(k,e,l.scrollTop)};return l.addEventListener("scroll",ye,{passive:!0}),l.addEventListener("wheel",se,{passive:!0}),l.addEventListener("pointerdown",se),l.addEventListener("keydown",se),()=>{cancelAnimationFrame(w),l.removeEventListener("scroll",ye),l.removeEventListener("wheel",se),l.removeEventListener("pointerdown",se),l.removeEventListener("keydown",se)}},[qe,e,k]),v.useEffect(()=>{if(qe||!mt.current)return;mt.current=!1;let l=0;const h=requestAnimationFrame(()=>{l=requestAnimationFrame(()=>T.current?.revealSelection())});return()=>{cancelAnimationFrame(h),cancelAnimationFrame(l)}},[qe]);const[Qn,Mr]=v.useState(()=>{const l=Os;return l?.path===e&&l.scope===$?(Os=null,Date.now()-l.at<1e4?l.req:null):null}),qr=v.useRef(Qn);qr.current=Qn;const Hr=v.useRef(null),[wn,Mn]=v.useState(null),[Rn,hr]=v.useState(null),gr=v.useRef(0);v.useEffect(()=>{wn||(hr(null),clearTimeout(gr.current))},[wn]);const rt=(l,h)=>{if(clearTimeout(gr.current),Rn&&!h)return;const x=l.closest(".unified-block-menu");if(!x)return;const w=x.getBoundingClientRect(),z=l.getBoundingClientRect(),Y=w.right+4+w.width>window.innerWidth-8;hr({x:Y?w.left-4-w.width:w.right+4,y:z.top-5,anchorTop:z.bottom+5,focus:h})},jt=()=>{clearTimeout(gr.current),gr.current=window.setTimeout(()=>{document.querySelector(".unified-block-submenu")?.contains(document.activeElement)&&document.querySelector('.unified-block-menu [data-sub="turnInto"]')?.focus(),hr(null)},180)};v.useLayoutEffect(()=>{if(!Rn?.focus)return;let l=0,h=0;const x=()=>{const w=document.querySelector(".unified-block-submenu button");w?.focus(),document.activeElement!==w&&++l<10&&(h=requestAnimationFrame(x))};return x(),()=>cancelAnimationFrame(h)},[Rn]);const yr=v.useRef(null),[ir,Vr]=v.useState(null),zr=v.useRef(()=>{}),Vn=v.useRef({tree:()=>({}),detach:()=>{},minted:()=>{}}),Oe=v.useMemo(()=>Iy({onMenu:l=>{const h=Oe.getView();yr.current=h?{doc:h.state.doc,sel:h.state.selection}:null,Mn({...l,cell:pb(h,l.x,l.y)})},onBlocksDeleted:l=>zr.current(l),canvasTree:()=>Vn.current.tree(),onCardDetach:l=>Vn.current.detach(l),onCardsMinted:l=>Vn.current.minted(l)}),[]),Vt=()=>$e.current?null:Oe.getView(),[y]=v.useState(()=>Rh(Vt)),S=l=>{const h=Oe.getView();h&&Py(e,Hi(l),Hi(h.state.doc.content))};zr.current=S,Vn.current={tree:()=>Kt(_n(un(m.fm))?.tree),detach:l=>{const h=Kt(_n(un(m.fm))?.tree);let x=!1;for(const w of l)w in h&&(delete h[w],x=!0);x&&fo(h)},minted:l=>{for(const h of l)m.ownedCards.add(h)}};const L=v.useRef({vaultRoot:k,path:e});L.current={vaultRoot:k,path:e};const D=v.useRef(!1),K=v.useRef(()=>{}),[X,ne]=v.useState({count:0,index:0}),G=v.useRef(()=>{}),Q=k?`${k.replace(/[\\/]+$/,"")}/${e}`:e,q=v.useSyncExternalStore(Zf,()=>!g&&Qf(Q));G.current=l=>{const h=l.current==null?0:l.changes.findIndex(x=>x.id===l.current)+1;ne(x=>x.count===l.changes.length&&x.index===h?x:{count:l.changes.length,index:h})};const Ne=v.useMemo(()=>[...Oe.plugins,...Vg,...Pg(()=>Sa(pr(m.fm)),()=>{m.sawRows=!0}),...Qy,...Hy(()=>_n(un(m.fm)),()=>Sa(pr(m.fm)),l=>{for(const h of l)m.ownedCards.add(h)}),...ay({path:e,readOnly:g,alive:()=>!m.dead&&!m.retired&&!m.readOnly&&!$e.current,flush:async()=>{if(m.dead||m.retired||m.readOnly||$e.current)throw new Error(Ce("documentTask.sourceGone"));if(Nt(),Ke(),m.timer&&(clearTimeout(m.timer),m.timer=null),await an(!0),m.dead||m.retired||m.failed)throw new Error(Ce("documentTask.sourceGone"))}}),jh(),...Xx(),...ex(()=>ct.current),...ax(Yn),...tx(),...ox(()=>_n(un(m.fm))),...Fx(G),...tb({spaceTrigger:()=>sh()&&D.current,onSpace:K}),...Rm,...Dm,...op(()=>L.current),...Dh(),...Lh(()=>Pt.current()),...Ih({where:()=>L.current,restore:()=>Bt.current(),focus:()=>wt.current()}),...C?$d:[]],[Oe,e,g,C]);v.useEffect(()=>{if(!wn)return;const l=w=>{w.target?.closest?.(".ctx-menu")||Mn(null)},h=w=>{const z=document.querySelector(".unified-block-menu"),Y=document.querySelector(".unified-block-submenu"),se=!!Y&&Y.contains(document.activeElement),ye=!!z&&z.contains(document.activeElement)||se,W=z?.querySelector('[data-sub="turnInto"]');if(w.key==="Escape"){if(w.stopPropagation(),se){hr(null),W?.focus();return}Mn(null),Oe.getView()?.focus();return}if(!z||w.isComposing)return;const ue=!w.metaKey&&!w.ctrlKey&&!w.altKey&&!w.shiftKey;if(ue&&se&&w.key==="ArrowLeft"){w.preventDefault(),w.stopPropagation(),hr(null),W?.focus();return}if(ue&&!se&&w.key==="ArrowRight"&&W&&document.activeElement===W){w.preventDefault(),w.stopPropagation(),rt(W,!0);return}if(ue&&["ArrowDown","ArrowUp","Home","End"].includes(w.key)){w.preventDefault(),w.stopPropagation();const R=[...(se?Y:z).querySelectorAll('button:not([aria-disabled="true"])')],Ee=R.indexOf(document.activeElement),ke=R.length,Ye=w.key==="Home"?0:w.key==="End"?ke-1:Ee<0?w.key==="ArrowUp"?ke-1:0:(Ee+(w.key==="ArrowDown"?1:-1)+ke)%ke;R[Ye]?.focus();return}ye&&(w.key==="Enter"||w.key===" ")||["Shift","Meta","Control","Alt","CapsLock"].includes(w.key)||(Mn(null),ye&&(w.preventDefault(),Oe.getView()?.focus()))};let x=0;if(wn.keyboard){let w=0;const z=()=>{const Y=document.querySelector(".unified-block-menu");if(!Y){++w<10&&(x=requestAnimationFrame(z));return}const se=wn.focus==="turnInto"?Y.querySelector('[data-sub="turnInto"]'):null;if(se){rt(se,!0);return}Y.querySelector("button")?.focus()};x=requestAnimationFrame(z)}return window.addEventListener("pointerdown",l,!0),window.addEventListener("contextmenu",l,!0),window.addEventListener("keydown",h,!0),()=>{cancelAnimationFrame(x),window.removeEventListener("pointerdown",l,!0),window.removeEventListener("contextmenu",l,!0),window.removeEventListener("keydown",h,!0)}},[wn]);const Fe=l=>{const h=yr.current;return yr.current=null,h?l.state.doc!==h.doc?(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.menu.stale")}})),!1):(l.state.selection.eq(h.sel)||l.dispatch(l.state.tr.setSelection(h.sel)),!0):!0},_e=l=>{Mn(null);const h=Oe.getView();if(!h||!Fe(h))return;const x=h.state.selection;x instanceof ze&&(l(h,x),h.focus())},Be=(l,h)=>{Mn(null);const x=Oe.getView();if(!x||!Fe(x))return;const w=Oe.topRangeOf(x);w?l(x,w):x.state.selection instanceof ze&&h(x,x.state.selection),x.focus()},He=l=>{const h=l.state.selection,x=Oe.topRangeOf(l)??(h instanceof ze?{from:h.from,to:h.to}:null);return x&&{from:x.from,to:ds(l.state,x.from,x.to)}},Ue=!g&&!!Eo()?.askInChat,We=(l,h,x)=>{const w=lb(l.state.doc,h,x,e);w&&Eo()?.askInChat?.([Ql(tc(l.state.doc),e),w].filter(Boolean).join(`
66
-
67
- `).slice(0,2e4))},Je=!g&&!!Eo()?.complete;D.current=Je;const Ut=Ba(l=>l.selectionActions),[Et,vt]=v.useState(null),Xn=[...["improve","fix","shorter","longer","summarize","translate","continue","custom"].map(l=>({id:l,label:te(`inlineai.action.${l}`)})),...Ut.map(l=>({id:`plugin:${l.pluginId}:${l.item.id}`,label:l.item.title,plugin:!0}))],At=(l,h)=>{if(!Je)return;const x=l.state.selection,w=h==="prompt",z=w?x.head:x.from,Y=w?x.head:x.to;if(!w&&Y<=z)return;nb(l,z,Y);const se=l.coordsAtPos(z),ye=l.coordsAtPos(Y),W=h.startsWith("plugin:")?h.slice(7):void 0,ue=W||w?w?"prompt":"custom":h,R=W?Ut.find(Ee=>`${Ee.pluginId}:${Ee.item.id}`===W)?.item.title??te("inlineai.label"):te(w?"inlineai.label":`inlineai.action.${h}`);vt({key:Date.now(),x:se.left,y:ye.bottom+6,top:se.top-6,title:R,hasSelection:!w,askFirst:w||h==="custom",action:ue,plugin:W})};K.current=l=>At(l,"prompt");const sn=l=>async(h,x,w)=>{const z=Oe.getView(),Y=z?fl(z):null;if(!z||!Y)throw new Error(Ce("unipage.toast.insertPointLost"));const se=Y.to>Y.from?T.current?.serializeMd(z.state.doc.slice(Y.from,Y.to).content)??Y.text:"";if(l.plugin){const Ee=Ba.getState().selectionActions.find(Ye=>`${Ye.pluginId}:${Ye.item.id}`===l.plugin);if(!Ee)throw new Error(Ce("unipage.toast.insertPointLost"));const ke=await Ee.item.run({text:Y.text,markdown:se,pagePath:e});if(ke==null||ke==="")return{text:""};if(typeof ke!="string")throw new Error(Ce("unipage.plugin.notString",{type:typeof ke}));if(Array.from(ke).some(Ye=>Ye.charCodeAt(0)<32&&Ye!==" "&&Ye!==`
68
- `))throw new Error(Ce("unipage.plugin.controlChars"));return{text:ke}}const ye=Eo();if(!ye?.complete)throw new Error(Ce("inlineai.unavailable"));const{before:W,after:ue}=rb(z.state.doc,Y.from,Y.to),R=l.action==="prompt"?h?"custom":"continue":l.action;return ye.complete({action:R,...h?{instruction:h}:{},...se?{selection:se}:{},...W?{before:W}:{},...ue?{after:ue}:{},title:e.split("/").pop().replace(/\.md$/i,""),pagePath:e,pageInstructions:tc(z.state.doc),...R==="translate"?{language:ob(Y.text)}:{}},{signal:w,onDelta:x})},lr=()=>{vt(null);const l=Oe.getView();l&&(dl(l),l.focus())},Wr=(l,h)=>{const x=Oe.getView(),w=x?fl(x):null,z=T.current?.parseMd(h);if(vt(null),!x||!w||!z){x&&dl(x),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.insertPointLost")}}));return}const Y=ab(x,w,z,l);x.focus(),Nt(),cn(),l==="replace"&&Y==="below"&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("inlineai.targetChanged")}}))},$o=()=>{const l=Oe.getView();if(!l)return;const h=qx(l),x=h?Z.current?.querySelector(`[data-agent-change="${h.id}"]`):null;x instanceof HTMLElement&&as(x,48)},Bn=()=>{const l=Oe.getView();if(!l)return;const{skipped:h}=Bx(l);Nt(),cn(),h&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("agentchg.skipped",{n:String(h)})}}))},Kn=(l,h)=>{let x=!0;Be((w,z)=>{x=Hl(w,z.from,z.to,l)},(w,z)=>{const Y=Ni(w,z.from,z.to,l);if(Y!=null){x=Y;return}z.node.type.spec.code&&Xd(w,z.from,l)||(w.dispatch(w.state.tr.setSelection(Pe.near(w.state.doc.resolve(z.from+1)))),x=Qs(w,l,null))}),x||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("mdblock.turn.failed",{kind:h})}}))},xr=(l,h)=>{let x=!0;Be((w,z)=>{x=l==="code"?Qa(w,z.from,z.to):zi(w,z.from,z.to,!0)},(w,z)=>{x=l==="code"?Ni(w,z.from,z.to,"code")??Qa(w,z.from,z.to):zi(w,z.from,z.to,!1)}),x||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("mdblock.turn.failed",{kind:h})}}))},Yr=()=>{const l=Oe.getView();if(!l)return[];const h=[];if(!oc(l)){const w=(z,Y,se,ye)=>{const W=te(se);h.push({k:z,icon:Y,label:W,run:()=>ye(W)})};w("text",xi,"unipage.menu.text",z=>Kn({kind:"text"},z)),w("h1",Ep,"unipage.menu.h1",z=>Kn({kind:"heading",level:1},z)),w("h2",zp,"unipage.menu.h2",z=>Kn({kind:"heading",level:2},z)),w("h3",Ap,"unipage.menu.h3",z=>Kn({kind:"heading",level:3},z)),w("bullet",xm,"unipage.menu.bullet",z=>Kn({kind:"bullet"},z)),w("ordered",Rp,"unipage.menu.ordered",z=>Kn({kind:"ordered"},z)),w("task",bm,"unipage.menu.task",z=>Kn({kind:"task"},z)),w("quote",Qp,"unipage.menu.quote",z=>Kn({kind:"quote"},z)),w("callout",Am,"unipage.menu.callout",z=>xr("callout",z)),w("fold",Cp,"unipage.menu.fold",z=>Kn({kind:"fold"},z)),w("code",ip,"unipage.menu.code",z=>xr("code",z))}const x=l.state.selection;if(x instanceof ze&&!["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(x.node.type.name)){const w=l.state.doc.resolve(x.from);let z=!1;for(let Y=w.depth;Y>=1;Y--)w.node(Y).type.name==="amadeusColumnCell"&&(z=!0);z||h.push({k:"card",icon:Wa,label:te("unipage.menu.card"),run:()=>_e(Y=>{Xr(Y)})})}return h},br=()=>{const l=Oe.getView();if(!l||Oe.topRangeOf(l))return null;const h=l.state.selection;return h instanceof ze?h.node.type.name==="list_item"?h.node.attrs.checked!=null?"task":h.$from.parent.type.name==="ordered_list"?"ordered":"bullet":Qh(h.node):null},Xr=l=>{const h=()=>(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.cardUnavailable")}})),!1);if(!(l.state.selection instanceof ze)){const{$from:Ee}=l.state.selection;for(let Ye=Ee.depth;Ye>=1;Ye--)if(Ee.node(Ye).type.name==="list_item")return h();let ke=Ee.depth;for(;ke>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard"].includes(Ee.node(ke-1).type.name);)ke--;if(ke<1)return!1;l.dispatch(l.state.tr.setSelection(ze.create(l.state.doc,Ee.before(ke))))}const x=l.state.selection,w=l.state.doc.resolve(x.from),z=w.depth>=1?w.node(w.depth):null,Y=z?.type.name==="amadeusCanvasCard"?String(z.attrs.anchor):"",se=Kt(_n(un(m.fm))?.tree);let ye=0;l.state.doc.forEach(Ee=>{Ee.type.name==="amadeusCanvasCard"&&ye++});const W=Y?(Number(z.attrs.x)||0)+(Number(z.attrs.w)||Jt)+80:bt.x+bt.w+80,ue=Y?(Number(z.attrs.y)||0)+wo(se,Y).length*72:bt.y+ye*72,R=mu(l,Math.round(W),Math.round(ue),Y?{parent:Y,tree:se}:void 0);return R?(m.ownedCards.add(R),Nt(),cn(),Y&&fo(Bo(Kt(_n(un(m.fm))?.tree),R,Y)),!ct.current&&!Y&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.cardMade")}})),!0):h()},qn=()=>{const l=vo(m.lastSaved);if(l.fmText!==m.fm&&(m.peerPatch==null||wa(l.fmText,m.peerPatch)!==m.fm))return!1;if(l.body===m.body)return!0;if(pr(m.fm)!=null||un(m.fm)!=null)return!1;const h=T.current?.canonical(l.body);return h!=null&&h===m.body},Un=v.useRef(null),er=()=>{Un.current?.()},[Ur,Gr]=v.useState(!1),Nr=async l=>{const h=So(l);if(m.preserved.has(h))return;const x=await ba(e,Ir(l,m.eol));m.preserved.add(h),yh(e,x,!m.readOnly&&di(Q,l)),N.getState().refreshPages()},Dn=async l=>{const h=await ba(e,Ir(l,m.eol));xh(e,h),N.getState().refreshPages()},Jr=()=>{if(m.gone==null||m.readOnly)return;Nt();const l=$n(m.fm,m.body);l!==m.gone&&(m.gone=l,Ar(l))},Ar=async l=>{try{await Dn(l)}catch{Dr(k,e,l,m.lastSaved,m.slot),vh(e,l)}},vr=l=>{if(m.retired||(m.stashed=$n(m.fm,m.body),Dr(k,e,m.stashed,m.lastSaved,m.slot)),m.failed||(m.failed=!0,Gr(!0),va(e,l)),m.retryTimer||m.dead||m.retired)return;const h=Si[Math.min(m.retryN,Si.length-1)];m.retryN++,m.retryTimer=setTimeout(()=>{m.retryTimer=null,!(m.dead||m.retired||!m.pending)&&(m.reconcileBusy||an())},h)},wr=l=>{m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null),m.retryN=0,m.failed&&(m.failed=!1,Gr(!1)),m.stashed!=null&&(l==null||m.stashed===l||$n(m.fm,m.body)===l)&&(Jo(k,e,m.stashed,m.slot),m.stashed=null)},To=l=>{m.peerPatch=null,wr(l),od(e,m)},an=(l=!1)=>{if(m.readOnly)return Promise.resolve();const h=async()=>{let z=0;for(;!m.retired;){const Y=$n(m.fm,m.body);if(Y===m.lastSaved){m.pending=!1,wr();return}let se;try{m.unpreserved!=null&&m.unpreserved!==Y&&await Nr(m.unpreserved),m.unpreserved=null,se=await vn.writeTextFile(e,Ir(Y,m.eol),{base:So(Ir(m.lastSaved,m.eol))})}catch(ye){if(m.pending=!0,vr(ye),l)throw ye;return}if(se&&se.ok===!1&&se.current==null){m.retired||(m.retired=!0,m.pending=!1,Nt(),m.gone=$n(m.fm,m.body),await Ar(m.gone));return}if(se&&se.ok===!1&&se.current!=null){const ye=qo(se.current);m.eol=ye.eol;const W=ye.text;if(W===Y){m.lastSaved=Y;continue}if(++z>3){const ue=new Error("The note kept changing on disk while saving");if(m.pending=!0,vr(ue),l)throw ue;return}if(qn()){m.pending=!1,er();return}m.unpreserved=W,m.lastSaved=W;continue}if(m.lastSaved=Y,N.getState().bumpLinkGraph(),$n(m.fm,m.body)===Y&&(m.pending=!1),To(Y),!l)return}},x=async()=>{m.writing++;try{await h()}finally{m.writing--}},w=m.chain.then(x,x);return m.chain=w.catch(()=>{}),w},tr=()=>{const l=Vt();if(!l)return;const h=pr(m.fm),x=Og(l.state.doc);let w=h;x!=null?(w=x,m.sawRows=!0):m.sawRows&&h!=null&&Sa(h)!=null&&(w=null);const z=Wy(l.state.doc,un(m.fm),dn.current?ct.current?"canvas":"doc":null,m.ownedCards),Y=un(m.fm);m.fm=us(m.fm,w,z),un(m.fm)!==Y&&Ae(se=>se+1)},Nt=()=>{const l=T.current?.serializeNow();l!=null&&(m.body=l,tr())},cn=()=>{m.dead||m.retired||g||!m.writing&&$n(m.fm,m.body)===m.lastSaved||(m.pending=!0,m.timer&&clearTimeout(m.timer),m.timer=setTimeout(()=>{m.timer=null,!m.reconcileBusy&&an()},bb))},[ur,nr]=v.useState(null),Ln=()=>{nr(l=>l==null?l:$n(m.fm,m.body))},Gn=(l,h=!0)=>{g||(m.fm=wa(m.fm,l),Ae(x=>x+1),Ln(),h?(m.pending=!0,an().then(()=>{const x=Cn.getState();x.refreshPages(),x.refreshIcons()})):cn())};v.useEffect(()=>{em(document)},[]);const[A,P]=v.useState(null);v.useEffect(()=>{const l=h=>{const x=document.elementFromPoint(h.clientX,h.clientY)??h.target,w=x?.tagName==="IMG"?x:null;if(!w||!w.closest(".unified-body"))return;const z=w.currentSrc||w.src;z&&(h.preventDefault(),h.stopPropagation(),P(z))};return document.addEventListener("dblclick",l,!0),()=>document.removeEventListener("dblclick",l,!0)},[]),ci(!!A,()=>P(null)),ci(!!wn&&!g,()=>Mn(null)),v.useEffect(()=>{if(!A)return;const l=h=>{h.key==="Escape"&&P(null)};return window.addEventListener("keydown",l,!0),()=>window.removeEventListener("keydown",l,!0)},[A]),v.useEffect(()=>{const l=async()=>{m.reconcileBusy++;try{await lm(),await m.chain;const x=await vn.readTextFile(e);if(x==null||m.dead||m.retired)return;const w=qo(x);m.eol=w.eol;const z=w.text;if(z===m.lastSaved&&!m.pending)return;if(m.pending&&Nt(),m.pending&&!qn()){z!==m.lastSaved&&z!==$n(m.fm,m.body)&&(m.unpreserved=z),m.lastSaved=z;return}const{fmText:Y,body:se}=vo(z),ye=pr(Y)!==pr(m.fm)||un(Y)!==un(m.fm);if(m.fm=Y,m.peerPatch=null,Ae(W=>W+1),se!==m.body){m.ownedCards.clear();const W=!m.readOnly&&di(Q,x);(T.current??($e.current?ae.current:null))?.applyBody(se,W)?m.body=se:(m.body=se,U(ue=>ue+1))}else ye&&(m.ownedCards.clear(),U(W=>W+1));m.lastSaved=z,m.pending=!1,wr(),Ln()}finally{m.reconcileBusy--,m.reconcileBusy===0&&m.pending&&an()}};Un.current=()=>{l()};const h=vn.onExternalChange?.(x=>{x===e&&l()});return l(),()=>{Un.current=null,h?.()}},[e]),v.useEffect(()=>{const l=()=>{if(Nt(),Ke(),m.timer&&clearTimeout(m.timer),m.timer=null,m.readOnly)return;if(m.retired){m.gone!=null&&Jr(),m.stashed!=null&&Jo(k,e,m.stashed,m.slot),m.stashed=null;return}const x=$n(m.fm,m.body);if(!m.writing&&x===m.lastSaved){wr();return}if(!m.writing&&qn()){m.pending=!1;return}m.stashed=x,Dr(k,e,x,m.lastSaved,m.slot),an()},h=x=>{l(),m.failed&&m.pending&&!kh()&&(x.preventDefault(),x.returnValue="")};return window.addEventListener("beforeunload",h),()=>{m.dead=!0,window.removeEventListener("beforeunload",h),l();const x=Hr.current,w=Oe.getView();x&&w&&(x.doc=w.state.doc.toJSON(),x.anchor=w.state.selection.anchor,x.head=w.state.selection.head)}},[e]),v.useEffect(()=>{const l=()=>{!m.failed||!m.pending||m.dead||m.retired||typeof document<"u"&&document.visibilityState==="hidden"||(m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null),!m.reconcileBusy&&an())};return window.addEventListener("online",l),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("online",l),window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l),m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null)}},[e]),v.useEffect(()=>{const l=ye=>{if(m.readOnly||m.retired||m.dead)return!1;Nt(),ye&&Ke();const W=$n(m.fm,m.body);return!m.writing&&(W===m.lastSaved||qn())?!1:(m.pending=!0,m.stashed=W,Dr(k,e,W,m.lastSaved,m.slot),!0)},h=ye=>{l(ye)&&(m.timer&&(clearTimeout(m.timer),m.timer=null),!m.reconcileBusy&&an())},x=()=>{document.visibilityState==="hidden"&&h(!0)},w=()=>h(!0);let z=0,Y=null;const se=()=>{const ye=z+1e3-Date.now();if(ye>0){l(!1),Y||(Y=setTimeout(()=>{Y=null,z=Date.now(),h(!1)},ye));return}z=Date.now(),h(!1)};return document.addEventListener("visibilitychange",x),window.addEventListener("pagehide",w),document.addEventListener("freeze",w),document.addEventListener("pause",w),window.addEventListener("blur",se),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pagehide",w),document.removeEventListener("freeze",w),document.removeEventListener("pause",w),window.removeEventListener("blur",se),Y&&clearTimeout(Y)}},[e]);const le=l=>m.readOnly||m.retired||m.dead||!T.current?!1:(T.current.insertFiles(l),!0);v.useEffect(()=>{if(!a)return;const l=h=>le(h);return a.current=l,()=>{a.current===l&&(a.current=null)}},[a]),v.useEffect(()=>{if(!i)return;const l=h=>m.readOnly||m.retired||m.dead?!1:T.current?.insertMarkdown(h,"cursor")??!1;return i.current=l,()=>{i.current===l&&(i.current=null)}},[i]),v.useLayoutEffect(()=>ed({path:e,owner:m,peerWrote:()=>er(),scope:$,lastActive:()=>de.current,dirty:()=>m.readOnly||m.retired||m.dead?!1:(Nt(),$n(m.fm,m.body)!==m.lastSaved&&!qn()),flush:(l=!1)=>m.readOnly?Promise.resolve():(Nt(),Ke(),m.timer&&(clearTimeout(m.timer),m.timer=null),an(l)),insertFiles:l=>le(l),patchFm:(l,h=!1)=>m.readOnly||m.retired||m.dead?null:h?(m.fm=wa(m.fm,l),m.peerPatch={...m.peerPatch??{},...l},Ae(x=>x+1),Ln(),Promise.resolve()):(Gn(l),m.chain),fmNow:()=>ws(m.fm),insertMarkdown:(l,h)=>m.retired||m.readOnly?!1:T.current?.insertMarkdown(l,h)??!1,insertReply:g?void 0:(l,h)=>{if(m.retired||m.dead||m.readOnly||!T.current?.insertMarkdown(l,"cursor",{quiet:!0,after:h,caretless:!fe.current}))return null;const x=Vt()?.state.doc,w=Yn,z={n:w.log.length,top:w.log[w.log.length-1],future:w.future.length};return{undo:()=>{const Y=Vt();return!Y||!x||Y.state.doc!==x||m.retired||m.dead||z.top!=="pm"||w.log.length!==z.n||w.log[w.log.length-1]!=="pm"||w.future.length!==z.future?!1:ct.current&&Xt.current?Xt.current("undo"):_a(Y.state,Y.dispatch)}}},bodyNow:()=>m.body,statsNow:()=>y(),headings:()=>{const l=Vt();return l?Xs(l.state.doc):[]},revealHeading:(l,h,x)=>{const w=Vt();if(!w)return;const z=Xs(w.state.doc),Y=z[l]?.text===h?z[l]:z.find(ye=>ye.text===h);if(!Y)return;w.focus(),w.dispatch(w.state.tr.setSelection(Pe.near(w.state.tr.doc.resolve(Y.pos+1))));const se=w.nodeDOM(Y.pos);se instanceof HTMLElement&&(as(se),x&&Ks(se.getBoundingClientRect()))},revealBlock:(l,h)=>{const x=Vt();if(!x)return!1;const w=[];x.state.doc.descendants((ye,W,ue)=>ye.isTextblock?(w.push({pos:W,text:ye.textContent,parent:ue}),!1):!0);let z=w.findIndex(ye=>xl(ye.text)===l);if(z<0)return!1;cd(w[z].text)&&z>0&&w[z-1].parent===w[z].parent&&(z-=1);const Y=w[z].pos;x.focus(),x.dispatch(x.state.tr.setSelection(Pe.near(x.state.tr.doc.resolve(Y+1))));const se=x.nodeDOM(Y);return se instanceof HTMLElement&&(as(se),h&&Ks(se.getBoundingClientRect())),!0},focusBody:()=>{if(m.readOnly||m.retired||m.dead)return!0;const l=Oe.getView();return l?(l.hasFocus()||l.focus(),!0):!1},revealText:(l,h)=>{const x=Vt();if(!x)return!1;const w=Yd(x.state.doc,l,!!h?.tag);if(!w)return!1;El(x,w.from),x.focus(),x.dispatch(x.state.tr.setSelection(Pe.create(x.state.doc,w.from,w.to)));let z=x.nodeDOM(w.block);for(;z instanceof HTMLElement&&z!==x.dom;){const Y=z.getBoundingClientRect();if(Y.width||Y.height)break;z=z.parentElement}return!(z instanceof HTMLElement)||z===x.dom||(as(z),h?.flash&&Ks(z.getBoundingClientRect())),!0},retire:l=>{if(Co(),!m.retired&&!m.readOnly&&!m.dead){Nt();const h=$n(m.fm,m.body);h!==m.lastSaved&&!qn()&&(l?Dr(k,l,h,m.lastSaved,m.slot):(N.getState().vaultRoot??null)!==(k??null)?Dr(k,e,h,m.lastSaved,m.slot):Ar(h))}else m.retired&&m.gone!=null&&Jr();m.retired=!0,m.timer&&(clearTimeout(m.timer),m.timer=null),m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null)}}),[e]);const[pe,Te]=v.useState(()=>{if(g)return null;const l=x=>x==null?Hc(e,null):um(x)||Hc(e,x),h=wh(k,e,m.slot,l);return h?h.text===m.lastSaved||h.text===(n??t)?(Jo(k,e,void 0,h.slot),null):h:null}),De=()=>{pe&&Jo(k,e,void 0,pe.slot),Te(null)},ge=()=>{const l=pe;if(Te(null),!l||g||m.retired)return;(l.slot??null)!==m.slot&&(Jo(k,e,l.text,l.slot),Dr(k,e,l.text,m.lastSaved,m.slot)),Nt();const h=m.lastSaved,x=$n(m.fm,m.body),w=x!==h?x:So(h)!==l.base?h:null;w!=null&&w!==l.text&&(m.unpreserved=w);const{fmText:z,body:Y}=vo(l.text);m.fm=z,Ae(se=>se+1),Y!==m.body&&(m.ownedCards.clear(),m.body=Y,(T.current??($e.current?ae.current:null))?.applyBody(Y)||U(se=>se+1)),Ln(),m.pending=!0,m.stashed=l.text,an()};v.useEffect(()=>{r&&(r.scheduleState=()=>({pending:m.pending,lastSaved:m.lastSaved}),r.flush=()=>(Nt(),m.timer&&clearTimeout(m.timer),m.timer=null,an()),r.fmState=()=>({fm:m.fm,body:m.body}),r.setFm=l=>Gn(l,!1),r.view=()=>Oe.getView(),r.serializeNow=()=>T.current?.serializeNow()??null)},[r]);const[ve,ft]=v.useState(0);v.useEffect(()=>{tm(e)&&ft(l=>l+1)},[e]);const Bt=v.useRef(()=>!1);Bt.current=()=>!g&&!p&&!ct.current&&qr.current==null&&ve===0;const wt=v.useRef(()=>!1);wt.current=()=>{const l=Pa;if(!l||l.scope!==$||Date.now()-l.at>5e3)return!1;Pa=null;const h=document.activeElement;return(!h||h===document.body)&&($==null||$===vm())};const Wt=v.useRef(null);v.useLayoutEffect(()=>()=>{const l=document.activeElement;l&&l!==document.body&&(Z.current?.contains(l)||Wt.current?.contains(l))&&(Pa={scope:$,at:Date.now()})},[]);const Pt=v.useRef(()=>!1);Pt.current=()=>En||g?!1:(ft(l=>l+1),!0);const Rt=l=>{const h=Oe.getView();if(!h)return;let x=h.state.tr;if(m.body===l.body)try{const Y=h.state.schema.nodeFromJSON(l.doc);Y.eq(x.doc)||(x=x.replaceWith(0,x.doc.content.size,Y.content))}catch{}const w=x.doc.content.size,z=Y=>x.doc.resolve(Math.max(0,Math.min(Y,w)));try{x=x.setSelection(Pe.between(z(l.anchor),z(l.head)))}catch{}h.dispatch(x.setMeta("addToHistory",!1).scrollIntoView())},zn=async(l,h=null,x=!1)=>{if(g||x&&m.retired)return!1;const w=k;try{if(Nt(),await an(),await fm(),x&&(await m.chain,m.retired||Cn.getState().vaultRoot!==w))return!1;const z=await vn.renamePageFile(e,l);if(z!==e){mm(k,e,z),sp(k,e,z),m.retired=!0,Nt();const Y=$n(m.fm,m.body),se=m.body;if(Y!==m.lastSaved)try{const ue=await vn.writeTextFile(z,Ir(Y,m.eol),{base:So(Ir(m.lastSaved,m.eol))});if(ue&&ue.ok===!1&&ue.current!==Ir(Y,m.eol))try{bh(z,await ba(z,Ir(Y,m.eol))),Cn.getState().refreshPages()}catch(R){Dr(k,z,Y,m.lastSaved,m.slot),va(z,R)}}catch(ue){Dr(k,z,Y,m.lastSaved,m.slot),va(z,ue)}const ye=qr.current,W=Oe.getView();if(!x&&h&&ye!=null&&typeof ye!="object")Os={path:z,scope:$,req:ye,at:Date.now()};else if(!x&&W?.hasFocus()){const ue={place:"restore",body:se,doc:W.state.doc.toJSON(),anchor:W.state.selection.anchor,head:W.state.selection.head};Hr.current=ue,Os={path:z,scope:$,req:ue,at:Date.now()}}td(e,"file",z),pm(e,z,"file"),await hm(e,z),Cn.getState().refreshPages(),x||o?.(z)}return!0}catch{return x&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.toast.renameDetachedFailed",{name:l})}})),!1}},Dt=v.useRef("");v.useEffect(()=>{const l=JSON.stringify(_n(un(m.fm))?.tree??null);if(l===Dt.current)return;Dt.current=l;const h=Oe.getView();h&&h.updateState(h.state)},[me,Oe]);const tn=$h(m.fm),Zr=typeof tn.icon=="string"&&tn.icon.trim()?tn.icon.trim():null,$r=typeof tn.cover=="string"&&tn.cover.trim()?tn.cover.trim():null,u=tn.cover_y,E=typeof u=="number"?u:typeof u=="string"?parseFloat(u):NaN,M=Number.isFinite(E)?Math.max(0,Math.min(100,E)):50,B=v.useMemo(()=>H==="source"?$n(m.fm,m.body):"",[H,me]),O=v.useRef(null),_=()=>`${pr(m.fm)??""}\0${un(m.fm)??""}`;v.useEffect(()=>{if(!g)return nm(J,l=>{const h=fa(ie.current),x=ma(h);if(l==="source"){Nt();const se=Oe.getView(),ye=$n(m.fm,m.body);let W=m.fm.length,ue=0,R=!1;if(se){const{head:Ee,$head:ke}=se.state.selection;R=se.hasFocus();try{ue=se.coordsAtPos(Ee).top-x}catch{}const Ye=ke.parent.isTextblock?ke.parent.textBetween(Math.max(0,ke.parentOffset-16),ke.parentOffset,void 0,""):"",$t=ae.current?.serializePrefix(Ee);W=wm(ye,m.fm.length+($t?.trimEnd().length??0),Ye)}O.current={to:l,offset:W,y:ue,focused:R,bodyAtEnter:m.body,struct:_()};return}const w=ee.current;if(!w)return;const z=w.selectionStart??0;let Y=0;try{Y=ii(w,z)-x}catch{}O.current={...O.current??{},to:l,offset:z,bodyOff:z-vo(w.value).fmText.length,y:Y,focused:document.activeElement===w}})},[J,g]);const V=v.useRef(H);v.useLayoutEffect(()=>{const l=V.current;if(V.current=H,l===H)return;const h=O.current,x=fa(ie.current);if(H==="source"){cn();const ue=ee.current;if(!ue||h?.to!=="source")return;const R=x.scrollTop;ue.style.height="auto",ue.style.height=`${ue.scrollHeight}px`,x.scrollTop=R;const Ee=Math.min(h.offset,ue.value.length);ue.setSelectionRange(Ee,Ee),h.focused&&ue.focus({preventScroll:!0}),x.scrollTop+=ii(ue,Ee)-ma(x)-h.y;return}O.current=null,nr(null);const w=ae.current,z=Oe.getView();if(!w||!z||!h||h.struct!==_()){m.ownedCards.clear(),U(ue=>ue+1);return}if(m.body!==h.bodyAtEnter&&w.applyBody(m.body,!1,!0),h.to!=="wysiwyg"||h.bodyOff==null)return;const Y=Oe.getView();if(!Y)return;const se=Y.state.doc.content.size,ye=h.bodyOff<=0?0:w.posAfterPrefix(m.body.slice(0,h.bodyOff))??0,W=Pe.near(Y.state.doc.resolve(Math.max(0,Math.min(ye,se))),-1);Y.dispatch(Y.state.tr.setSelection(W).setMeta("addToHistory",!1)),h.focused&&Y.focus();try{x.scrollTop+=Y.coordsAtPos(W.head).top-ma(x)-h.y}catch{}},[H]);const ee=v.useRef(null);return v.useEffect(()=>{const l=ee.current;if(H==="source"&&l){const h=fa(l),x=h.scrollTop;l.style.height="auto",l.style.height=`${l.scrollHeight}px`,h.scrollTop=x}},[H,ur,B]),v.useEffect(()=>{if(g)return;if(H==="source"){const h=ee.current;return h?vi(ah(h)):void 0}const l=Z.current;return l?vi(xb(l,()=>Oe.getView())):void 0},[g,H,Oe]),f.jsxs(f.Fragment,{children:[f.jsx("span",{ref:ie,className:"amx-seg-anchor","aria-hidden":!0}),H==="source"?null:f.jsx(Oh,{anchor:we,on:qe,toggle:()=>Ot.current()}),En||p?null:f.jsx(Cm,{page:e,cover:$r,coverY:M,readOnly:g,onSetCover:l=>Gn({cover:l??void 0,...l?{}:{cover_y:void 0}}),onSetCoverY:l=>Gn({cover_y:l})}),En?null:f.jsxs("div",{ref:Wt,className:"amx-doc unified-page","data-unified-path":e,onFocusCapture:be,onPointerDownCapture:be,children:[f.jsx(Sb,{compact:p,path:e,icon:Zr,cover:$r,readOnly:g,onSetIcon:l=>Gn({icon:l??void 0}),onSetCover:l=>Gn({cover:l}),onRename:zn,onDetachedRename:l=>{const h=l.trim();h&&h!==(e.split("/").pop()??e).replace(/\.md$/i,"")&&zn(h,null,!0)},onEnterBody:l=>Mr(l==="enter"?"body-enter":"start"),focusSignal:ve}),!p&&f.jsx(Kl.Provider,{value:Me,children:f.jsx(qh,{fmExtra:ws(m.fm),readOnly:g,notePath:e,onCommit:l=>{m.fm=Sh(m.fm,l),Ae(h=>h+1),Ln(),m.pending=!0,an()}})}),g&&d&&f.jsxs("div",{className:"mk-notice unified-savebar","data-lock":"on",role:"status",children:[f.jsx(ap,{size:15}),f.jsx("div",{className:"mk-notice-body",children:f.jsx("span",{children:te("unipage.lock.bar")})}),f.jsx("button",{type:"button",className:"btn sm",onClick:d,children:te("unipage.lock.unlock")})]}),!g&&Ur&&f.jsxs("div",{className:"mk-notice is-error unified-savebar","data-save":"failed",role:"alert",children:[f.jsx(rm,{size:15}),f.jsx("div",{className:"mk-notice-body",children:f.jsx("span",{children:te("unisave.failed.bar")})}),f.jsx("button",{type:"button",className:"btn sm",onClick:()=>{m.retryTimer&&(clearTimeout(m.retryTimer),m.retryTimer=null),an()},children:te("unisave.failed.retry")})]}),!g&&pe&&f.jsxs("div",{className:"mk-notice unified-savebar","data-save":"draft",role:"status",children:[f.jsx(om,{size:15}),f.jsxs("div",{className:"mk-notice-body",children:[f.jsx("span",{children:te("unisave.draft.bar",{time:sm(pe.at)})}),f.jsx("small",{children:te("unisave.draft.hint")})]}),f.jsx("button",{type:"button",className:"btn sm primary",onClick:ge,children:te("unisave.draft.restore")}),f.jsx("button",{type:"button",className:"btn sm",onClick:De,children:te("unisave.draft.discard")})]})]}),H==="source"?f.jsx("textarea",{ref:ee,className:"amx-source",value:ur??B,spellCheck:Re,onFocus:be,onChange:l=>{const h=l.target.value;nr(h);const{fmText:x,body:w}=vo(h);m.fm=Nh(x),m.body=w,cn()}}):null,f.jsxs("div",{ref:Z,className:`page-view unified-body${qe?" amx-canvas":""}${En?" amx-canvas-full":""}`,style:H==="source"?{display:"none"}:void 0,"aria-hidden":H==="source"||void 0,"data-bare":!0,onFocusCapture:()=>{be(),fe.current=!0,da(on)},onPointerDownCapture:be,children:[f.jsx($x,{path:e,vaultRoot:k,active:qe&&H!=="source",readOnly:g,revealSelection:st,getView:()=>Oe.getView(),main:bt,mainStored:Wn?.main!=null,elements:Wn?.elements,tree:Wn?.tree,onElements:Zn,onTree:fo,onMain:en,timeline:Yn,histStepRef:Xt,exportRef:Sn,saveFile:l=>Cu(e,l),parseMd:l=>T.current?.parseMd(l)??null,serializeMd:l=>T.current?.serializeMd(l)??null,storedMd:l=>T.current?.serializeStored(l)??null,onBlocksDeleted:S,notePages:()=>N.getState().pages,onCommit:l=>{l&&m.ownedCards.add(l),Nt(),cn()},children:f.jsx(Td,{children:f.jsx(kb,{path:e,pageDir:I,body:m.body,onChange:l=>{$e.current||(m.body=l,tr(),cn())},onFinalFlush:l=>{m.body=l,tr(),cn(),Ae(h=>h+1)},skipFinalFlush:()=>m.reconcileBusy>0||$e.current,hidden:()=>$e.current,apiRef:ae,probe:r,extraPlugins:Ne,focusPlace:Qn!=null&&typeof Qn=="object"?"start":Qn,onFocused:()=>{Qn!=null&&typeof Qn=="object"&&Rt(Qn),Mr(null)},onCard:Xr,readOnly:g,onAskTangu:Ue?l=>We(l,l.state.selection.from,l.state.selection.to):void 0,aiMenu:Je?{items:Xn,onPick:(l,h)=>At(h,l)}:void 0,onAiPrompt:Je?l=>At(l,"prompt"):void 0})},`${e}:${Ge}${g?":ro":""}`)}),!qe&&!g&&f.jsx("div",{className:"page-tail",onClick:()=>T.current?.focusTail()}),q&&f.jsx(Hx,{}),!g&&X.count>0&&f.jsx(Vx,{count:X.count,index:X.index,onReview:$o,onRevert:Bn,onKeep:()=>{const l=Oe.getView();l&&Kx(l)}})]}),f.jsx(mb,{getView:()=>Oe.getView(),onOpenNote:l=>{N.getState().openWikiLink(jd(l,e,N.getState().pages),e)}}),A&&f.jsx(ao,{children:f.jsx("div",{className:"amx-lightbox",onClick:()=>P(null),role:"presentation",children:f.jsx("img",{src:A,alt:""})})}),Et&&Je&&f.jsx(ao,{children:f.jsx(Wx,{x:Et.x,y:Et.y,anchorTop:Et.top,title:Et.title,hasSelection:Et.hasSelection,askFirst:Et.askFirst,run:sn(Et),onApply:Wr,onClose:lr,editorEl:Z.current},Et.key)}),ir&&!g&&f.jsx(Yl,{pages:N.getState().pages,exclude:e,onClose:()=>{Vr(null),Oe.getView()?.focus()},onPick:l=>{const h=ir;Vr(null);const x=Oe.getView();if(x){if(x.state.doc!==h.doc){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.menu.stale")}}));return}fg({view:x,from:h.from,to:h.to,source:e,target:l,pages:[...N.getState().pages].sort(),serialize:w=>T.current?.serializeMd(w)??null}).then(w=>{w&&(Nt(),cn())}),x.focus()}}}),wn&&!g&&f.jsxs(ao,{children:[f.jsxs(zo,{className:"ctx-menu unified-block-menu",role:"menu","aria-label":te("unipage.menu.aria"),x:wn.x,y:wn.y,onClick:l=>l.stopPropagation(),onMouseOver:l=>{Rn&&!l.target.closest("[data-sub]")&&jt()},children:[Ue&&f.jsxs(f.Fragment,{children:[f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"ask",onClick:()=>{Mn(null);const l=Oe.getView();if(!l||!Fe(l))return;const h=Oe.topRangeOf(l),x=l.state.selection;h?We(l,h.from,h.to):x instanceof ze&&We(l,x.from,x.to)},children:[f.jsx(lp,{size:13})," ",te("unipage.menu.askTangu")]}),f.jsx("div",{className:"ubm-sep",role:"separator"})]}),(()=>{const l=Yr();if(!l.length)return null;const h=br(),x=l.find(z=>z.k===h)??(h==="card"?{icon:Wa,label:te("unipage.menu.card")}:void 0),w=x?.icon??xi;return f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-sub":"turnInto","aria-haspopup":"menu","aria-expanded":!!Rn,className:Rn?"is-open":void 0,onMouseEnter:z=>rt(z.currentTarget,!1),onClick:z=>rt(z.currentTarget,!0),children:[f.jsx(w,{size:13})," ",te("unipage.menu.turnInto"),f.jsxs("span",{className:"ubm-sub-tail",children:[x?.label,f.jsx(Ml,{size:13})]})]})})(),oc(Oe.getView())&&f.jsx(yb,{view:Oe.getView(),cell:wn.cell??null,onDone:()=>Mn(null)}),f.jsx("div",{className:"ubm-sep",role:"separator"}),Oe.getView()&&Oe.topRangeOf(Oe.getView())?f.jsxs("button",{role:"menuitem",tabIndex:-1,"aria-disabled":"true",title:te("unipage.menu.toNewColumnMulti"),"data-act":"toNewColumn",onClick:()=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:Ce("unipage.menu.toNewColumnMulti")}}))},children:[f.jsx(li,{size:13})," ",te("unipage.menu.toNewColumn")]}):Oe.getView()&&Rd(Oe.getView().state.selection)&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"toNewColumn",onClick:()=>_e((l,h)=>{Jl(l,h.from,h.to,h.node)}),children:[f.jsx(li,{size:13})," ",te("unipage.menu.toNewColumn")]}),Oe.getView()&&Yc(Oe.getView().state.selection)!=null&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"unsplit",onClick:()=>{Mn(null);const l=Oe.getView();if(!l||!Fe(l))return;const h=Yc(l.state.selection);h!=null&&Hg(l,h),l.focus()},children:[f.jsx(Xp,{size:13})," ",te("unipage.menu.unsplit")]}),Oe.getView()?.state.selection instanceof ze&&Oe.getView().state.selection.node.type.name==="amadeusCanvasCard"&&f.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>_e((l,h)=>{h.node.type.name==="amadeusCanvasCard"&&(pu(l,String(h.node.attrs.anchor)),Nt(),cn())}),children:[f.jsx(cp,{size:13})," ",te("unipage.menu.backToDoc")]}),f.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>{Mn(null);const l=Oe.getView();!l||!Fe(l)||(Oe.duplicate(l)&&(Nt(),cn()),l.focus())},children:[f.jsx(am,{size:13})," ",te("unipage.menu.duplicate")]}),(()=>{const l=Oe.getView();if(!l)return null;const h=l.state.selection,x=He(l),w=h instanceof ze?lg(h.node,e,N.getState().pages):null,z=!!x&&dg(l.state.doc.slice(x.from,x.to).content);return f.jsxs(f.Fragment,{children:[w&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"copyLink",onClick:()=>{Mn(null),ug(w.link),Oe.getView()?.focus()},children:[f.jsx(cm,{size:13})," ",te(w.kind==="heading"?"blocklinks.copyHeading":"blocklinks.copyBlock")]}),z&&f.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"moveTo",onClick:()=>{Mn(null);const Y=Oe.getView();if(!Y||!Fe(Y))return;const se=He(Y);se&&Vr({doc:Y.state.doc,...se})},children:[f.jsx(Bm,{size:13})," ",te("blocklinks.moveTo")]})]})})(),f.jsxs("button",{role:"menuitem",tabIndex:-1,className:"danger",onClick:()=>Be((l,h)=>{const x=l.state.doc.slice(h.from,h.to).content;l.dispatch(l.state.tr.delete(h.from,h.to).scrollIntoView()),S(x)},(l,h)=>{const x=Sr.from(h.node),w=h.$from.parent,z=w.type.name==="amadeusColumnCell"&&w.childCount===1?Zl(l.state,h.$from.before(),-1,!0):null;l.dispatch(z??l.state.tr.deleteSelection().scrollIntoView()),S(x)}),children:[f.jsx(Ha,{size:13})," ",te("unipage.menu.delete")]})]}),Rn&&(()=>{const l=br();return f.jsx(zo,{className:"ctx-menu unified-block-submenu",role:"menu","aria-label":te("unipage.menu.turnInto"),x:Rn.x,y:Rn.y,anchorTop:Rn.anchorTop,onClick:h=>h.stopPropagation(),onMouseEnter:()=>clearTimeout(gr.current),children:Yr().map(({k:h,icon:x,label:w,run:z})=>f.jsxs("button",{role:"menuitemradio","aria-checked":h===l,tabIndex:-1,"data-kind":h,onClick:z,children:[f.jsx(x,{size:13})," ",w,h===l&&f.jsx(ea,{size:13,className:"ubm-check"})]},h))})})()]})]})}const Zb=Object.freeze(Object.defineProperty({__proto__:null,UnifiedPage:Eb},Symbol.toStringTag,{value:"Module"}));export{qh as A,Cp as C,Xb as D,Jb as F,Lp as M,Ph as S,Eb as U,sh as a,nh as b,Rl as c,Yb as d,Ll as e,th as f,lo as g,vo as h,rh as i,Zb as j,Gb as o,Ub as s};