@forsion/unit 2.12.2 → 2.13.1
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.
- package/README.md +61 -0
- package/backendWorker.mjs +6 -2
- package/main.mjs +991 -497
- package/package.json +1 -1
- package/release.json +5 -5
- package/web/assets/ArtificialView-XwHMLUFb.js +1 -0
- package/web/assets/{AutomationBuilder-sxWdUa0L.js → AutomationBuilder-hqs0QhMt.js} +1 -1
- package/web/assets/CalendarConfigView-DKib8Oed.js +1 -0
- package/web/assets/CalendarView-DJ5iOzvu.js +1 -0
- package/web/assets/CapabilityMenu-SwVlZ06x.js +1 -0
- package/web/assets/{CheckboxInput-BsaoUHZ0.js → CheckboxInput-BC-5a_C9.js} +1 -1
- package/web/assets/Chrome-HdfyYV3i.js +1 -0
- package/web/assets/{CodeView-j065KtVh.js → CodeView-CFL6yQ-6.js} +3 -3
- package/web/assets/DashboardGridView-B9DCWYVb.js +17 -0
- package/web/assets/{EventCard-BmDQkEj9.js → EventCard-B_ndpqH_.js} +1 -1
- package/web/assets/ExcalidrawCanvas-BQ4KKLJP.js +1 -0
- package/web/assets/{FloatingToc-CENybkAA.js → FloatingToc-Ce9GamvH.js} +1 -1
- package/web/assets/HomepageView-RCOfcVbE.js +1 -0
- package/web/assets/ImageStudioPanels-lkS_y2uM.js +3 -0
- package/web/assets/ImageStudioView-UPv52acl.js +1 -0
- package/web/assets/InlineFiles-CQbQumkf.js +1 -0
- package/web/assets/MarkdownBlock--__nPQGh.css +1 -0
- package/web/assets/MarkdownBlock-CkqiwPXa.js +58 -0
- package/web/assets/ModelPill-CY-rU1RU.js +2 -0
- package/web/assets/MuseLibraryView-CtTHlVnT.js +2 -0
- package/web/assets/{MuseView-d-iBk3sc.js → MuseView-CC2A7MBs.js} +2 -2
- package/web/assets/{PageHistoryPanel-CR-k1AM7.js → PageHistoryPanel-KhKT1DLy.js} +2 -2
- package/web/assets/PdfAnnotator-C_kglLCA.css +1 -0
- package/web/assets/PdfAnnotator-DUyrgY-t.js +505 -0
- package/web/assets/{ProductView-u2aezVsl.js → ProductView-CgsIYZqD.js} +1 -1
- package/web/assets/RightPanel-BHDgqTFs.js +4 -0
- package/web/assets/RunLocationPicker-BE5mxnab.css +1 -0
- package/web/assets/RunLocationPicker-DBnXYV5B.js +38 -0
- package/web/assets/{SidebarRow-BuSkKH5q.js → SidebarRow-BAJxbMcx.js} +1 -1
- package/web/assets/{SketchCard-D87GADyG.js → SketchCard-BGYz-bXP.js} +5 -5
- package/web/assets/{StudioGuestSurface-BijU_EEb.js → StudioGuestSurface-lt6znmkl.js} +1 -1
- package/web/assets/{TodoListView-DPPVpPUn.js → TodoListView-DPKhee6i.js} +1 -1
- package/web/assets/{Tooltip-DY4ISA-e.js → Tooltip-ZxrDqN4p.js} +1 -1
- package/web/assets/UnifiedPage-BX6ZQL0h.js +68 -0
- package/web/assets/UnifiedPage-CWXc_mo1.css +1 -0
- package/web/assets/{amadeus-manual.en-DWaN2fPs.js → amadeus-manual.en-DzRWr4BL.js} +18 -18
- package/web/assets/{amadeus-manual.zh--7D5TS8X.js → amadeus-manual.zh-DW32DkL7.js} +18 -18
- package/web/assets/{appStore-Dg9WALEA.js → appStore-DWP8UET9.js} +208 -122
- package/web/assets/appStore-wtOILggO.css +1 -0
- package/web/assets/{arrow-up-right-CpQs92mu.js → arrow-up-right-DrCXuWS7.js} +1 -1
- package/web/assets/{astryxBridge-BZhaZPs4.js → astryxBridge-D-m4_kYt.js} +3 -3
- package/web/assets/automationListSource-C8BNy6RY.js +1 -0
- package/web/assets/book-open-OLNm7OaB.js +1 -0
- package/web/assets/{calendarNavStore-C7fGRpoH.js → calendarNavStore-Cylfvv3s.js} +1 -1
- package/web/assets/{canvasPrefs-BeG4oEgP.js → canvasPrefs-8taQ42Cz.js} +1 -1
- package/web/assets/chatBoxSurface-CIlzs45H.js +1 -0
- package/web/assets/{circle-question-mark-WL3vbp-Z.js → circle-question-mark-XbAFplz1.js} +1 -1
- package/web/assets/{circle-x-D7s-M5sB.js → circle-x-fcReAZaE.js} +1 -1
- package/web/assets/{client-BSKpsyAw.js → client-0MPbodA6.js} +1 -1
- package/web/assets/{code-xml-BALV9u_c.js → code-xml-Cuna8Kh4.js} +1 -1
- package/web/assets/{codeStudioStore-C2mWfm32.js → codeStudioStore-BBU62GTy.js} +1 -1
- package/web/assets/codingNavigation-CZB4v1ZW.css +1 -0
- package/web/assets/codingNavigation-DDlPpPk5.js +47 -0
- package/web/assets/{create-4xUyKtAF.js → create-BGtEfCcg.js} +4 -4
- package/web/assets/dashboardSurface-BYM3C7WG.js +1 -0
- package/web/assets/{deskCapture-Df701U8L.js → deskCapture-BiUCmqfc.js} +1 -1
- package/web/assets/{diff2html-BV-zCH4d.js → diff2html-BNp2FTbk.js} +1 -1
- package/web/assets/{docx-preview-DW4IyU_Q.js → docx-preview-CFznGVOU.js} +1 -1
- package/web/assets/{emoji-DGaxpCIu.js → emoji-6zl4yfOS.js} +1 -1
- package/web/assets/floatingTocSurface-DreXPCa6.js +1 -0
- package/web/assets/{foldActions-B7KByFdN.js → foldActions-05QcQziQ.js} +1 -1
- package/web/assets/folder-BpsfOHD4.js +1 -0
- package/web/assets/{folder-plus-D1TDb7k9.js → folder-plus-BeQHr4AZ.js} +1 -1
- package/web/assets/gestures-DQBCcK4y.js +1 -0
- package/web/assets/{hand-Crrw-nSn.js → hand-Bko7ms15.js} +1 -1
- package/web/assets/{hard-drive-BbyVSbfP.js → hard-drive-BpuI5ebj.js} +1 -1
- package/web/assets/i18n-ecQQxiMQ.css +1 -0
- package/web/assets/i18n.generated-BuLjnmY8.js +15 -0
- package/web/assets/imageStudio--KF9gwHA.css +1 -0
- package/web/assets/imageStudio-BLVNKmEG.js +2 -0
- package/web/assets/{index-DKhyDkGB.js → index-BF10xp_K.js} +1 -1
- package/web/assets/{index-C7U6T-k8.js → index-BHm6K743.js} +1 -1
- package/web/assets/{index-CF4RV4mh.js → index-BM2o7PeV.js} +90 -90
- package/web/assets/{index-Brik2pf9.js → index-BgnNNv3e.js} +1 -1
- package/web/assets/{index--drOLtq7.js → index-C0Gy2NQ6.js} +1 -1
- package/web/assets/{index-CflzrdSt.js → index-C1doZp5H.js} +1 -1
- package/web/assets/{index-SZ5waGAq.js → index-C4L6vjd_.js} +1 -1
- package/web/assets/{index-Cmr7gVZQ.js → index-CD3yIkOA.js} +1 -1
- package/web/assets/{index-BYsdKR_1.js → index-CJeUgjPU.js} +1 -1
- package/web/assets/{index-CzM-C2Sd.js → index-CLHoq1w-.js} +1 -1
- package/web/assets/{index-tAXBa_fN.js → index-CUZI62qU.js} +1 -1
- package/web/assets/{index-C6GJulug.js → index-Cff42k7q.js} +1 -1
- package/web/assets/index-Ck_O3Jdd.js +1 -0
- package/web/assets/index-CuiYK18N.js +1 -0
- package/web/assets/{index-BRW82CsP.js → index-CwcOeZdT.js} +1 -1
- package/web/assets/{index-DUWR2nZi.js → index-D6AycQIz.js} +1 -1
- package/web/assets/{index-BCZZVJ_w.js → index-D7gVhvNY.js} +1 -1
- package/web/assets/{index-DjzSBM0U.js → index-D9UZQy42.js} +1 -1
- package/web/assets/{index-KL5Rj9kP.js → index-DuBQ0j2g.js} +1 -1
- package/web/assets/{index-Dg9oixs4.js → index-OD1gSX3h.js} +1 -1
- package/web/assets/{index-gPSbFSUn.js → index-Uo5tswys.js} +1 -1
- package/web/assets/{index-D1f_JwPH.js → index-o8cj0pRH.js} +1 -1
- package/web/assets/{index-OHi69jDq.js → index-rHjhbwvm.js} +1 -1
- package/web/assets/{index-CqyM6tQ0.js → index-rggq2czF.js} +1 -1
- package/web/assets/{index-Czu_bbDM.js → index-sCXThwqZ.js} +1 -1
- package/web/assets/{invitePage-lLQ-e0pj.js → invitePage-b0HGvMj6.js} +1 -1
- package/web/assets/{ipc-DQOD2UKk.js → ipc-CxAyeo8q.js} +1 -1
- package/web/assets/{jszip.min-DZxV9uZ_.js → jszip.min-B94KpE21.js} +1 -1
- package/web/assets/launchpad-C2c1MSVX.css +1 -0
- package/web/assets/{layout-grid-B_pjJwz4.js → layout-grid-BBVuEdWG.js} +1 -1
- package/web/assets/{linkFollow-C0_3k_PC.js → linkFollow-B7ivDZMM.js} +4 -4
- package/web/assets/{list-tree-DkAJYEXd.js → list-tree-4-0QDbLu.js} +1 -1
- package/web/assets/{listFold-BsOVn9UZ.js → listFold-DLuxXiIj.js} +1 -1
- package/web/assets/{lock-BnGHxjeE.js → lock-CnbZm4vo.js} +1 -1
- package/web/assets/{log-out-DBuMeqik.js → log-out-BEynWaHa.js} +1 -1
- package/web/assets/{main-NgUPPqDn.css → main-BiS_5wrB.css} +1 -1
- package/web/assets/main-sIq2N9Z5.js +20 -0
- package/web/assets/markdownEditorSurface-ZSJ3RHAv.js +3 -0
- package/web/assets/mdMarkStore-DQHDjG7s.js +2 -0
- package/web/assets/{mdMarks-Bq7Hl-4C.js → mdMarks-DbIcRa0O.js} +1 -1
- package/web/assets/{message-square-plus-BiAZAvcw.js → message-square-plus-CpiKDvle.js} +1 -1
- package/web/assets/{messages-BH5MfQdZ.js → messages-_jta1lSI.js} +1 -1
- package/web/assets/minus-C9ndHJ9O.js +1 -0
- package/web/assets/mobileEntry-CPmU_c4m.js +13 -0
- package/web/assets/nativeDownload-BYT082bY.js +1 -0
- package/web/assets/{pageChrome-xLNdFaSg.css → pageChrome-CovzZPdb.css} +1 -1
- package/web/assets/pageChrome-D3Niv1JM.js +1 -0
- package/web/assets/{pageTree-CZH2J6cc.js → pageTree-CgfvpzIj.js} +2 -2
- package/web/assets/{pen-tool-lkmBqliH.js → pen-tool-BXEFnU2i.js} +1 -1
- package/web/assets/{pencil-Cvk91P_Z.js → pencil-cqvCkekG.js} +1 -1
- package/web/assets/pluginChat-BbBukMuN.js +2 -0
- package/web/assets/{redo-2-DSi54z4e.js → redo-2-BO7wCDwy.js} +1 -1
- package/web/assets/{rotate-ccw-CUlnplr0.js → rotate-ccw-BvipPIjC.js} +1 -1
- package/web/assets/{sharePage-MM6UpPJ9.js → sharePage-XbN50US7.js} +2 -2
- package/web/assets/{shareViewer-CDZ8lTdy.js → shareViewer-BaYogetW.js} +1 -1
- package/web/assets/{star-CwDiGyUW.js → star-BQWMXnn7.js} +1 -1
- package/web/assets/tableSurface-BXqqidd1.js +1 -0
- package/web/assets/{terminal-DIXogYJY.js → terminal-l9k6RDrH.js} +1 -1
- package/web/assets/{terminalView-B3aZSsrQ.js → terminalView-Cpnt5_0P.js} +1 -1
- package/web/assets/theme-C6D3tMGV.css +1 -0
- package/web/assets/type-CFoaj2eD.js +1 -0
- package/web/assets/{undo-2-tUKCv5Gs.js → undo-2-DusxpdLa.js} +1 -1
- package/web/assets/{unitAccount-D8lVwaaT.js → unitAccount-DwutFPPw.js} +1 -1
- package/web/assets/{unitBridge-D547ublk.js → unitBridge-CcgQpkqV.js} +1 -1
- package/web/assets/{unitCloudTransport-BVF6lVp4.js → unitCloudTransport-vA7cLDts.js} +1 -1
- package/web/assets/{unitOwnerAccess-BfnEjsZb.js → unitOwnerAccess-LBlJ1YfA.js} +1 -1
- package/web/assets/{unitShim-DxetRgmP.js → unitShim-B_M9IrbC.js} +3 -3
- package/web/assets/{upload-BbeAsMuD.js → upload-ZrOj6tXA.js} +1 -1
- package/web/assets/userSpaces-uJOnsedR.js +1 -0
- package/web/assets/viewportLock-D3SNkwS2.js +631 -0
- package/web/assets/viewportLock-IP1zaVkz.css +1 -0
- package/web/assets/{workflow-DuoVRSSX.js → workflow-DPoG4QE2.js} +1 -1
- package/web/assets/{zoom-in-hr5bRpDL.js → zoom-in-lbTgzdQP.js} +1 -1
- package/web/index.html +232 -13
- package/web/assets/ArtificialView-B4ESD4iK.js +0 -1
- package/web/assets/CalendarConfigView-cCfo_EvZ.js +0 -1
- package/web/assets/CalendarView-wgLapctk.js +0 -1
- package/web/assets/CapabilityMenu-BQBsM638.js +0 -1
- package/web/assets/ChatView-BIUk0OJd.css +0 -1
- package/web/assets/ChatView-C-jCJnyS.js +0 -47
- package/web/assets/Chrome-CwFiDmre.js +0 -1
- package/web/assets/DashboardGridView-DXqe0vPd.js +0 -17
- package/web/assets/ExcalidrawCanvas-C3egkikA.js +0 -1
- package/web/assets/HomepageView-CRdhjLXu.js +0 -1
- package/web/assets/ImageStudioPanels-Dke7xf8E.js +0 -3
- package/web/assets/ImageStudioView-g38V8gaj.js +0 -1
- package/web/assets/InlineFiles-C_hjvn3u.js +0 -1
- package/web/assets/MarkdownBlock-DIjYEhTK.js +0 -56
- package/web/assets/ModelPill-BPlgovPo.js +0 -1
- package/web/assets/MuseLibraryView-CenyTTim.js +0 -2
- package/web/assets/PdfAnnotator-CGzC_o1Q.css +0 -1
- package/web/assets/PdfAnnotator-D79ip27w.js +0 -560
- package/web/assets/RightPanel-C3OJTIqT.js +0 -4
- package/web/assets/RunLocationPicker-BNcZ7KKF.css +0 -1
- package/web/assets/RunLocationPicker-CTYXUH2z.js +0 -34
- package/web/assets/UnifiedPage-CKNtVD_n.js +0 -57
- package/web/assets/UnifiedPage-DX_sTpyZ.css +0 -1
- package/web/assets/appStore-Di8LXuJ9.css +0 -1
- package/web/assets/automationListSource-DP5xZBxo.js +0 -1
- package/web/assets/chatBoxSurface-zvcyfrxE.js +0 -1
- package/web/assets/dashboardSurface-CFTH5z4c.js +0 -1
- package/web/assets/ellipsis-r1EcXsFq.js +0 -1
- package/web/assets/floatingTocSurface-C6RJ6i41.js +0 -1
- package/web/assets/folder-DlxnPmWY.js +0 -1
- package/web/assets/frame-_xBVYe3P.js +0 -1
- package/web/assets/gestures-CkW1Kfs9.js +0 -1
- package/web/assets/i18n-D-eU58uw.css +0 -1
- package/web/assets/i18n.generated-Bbsz16cl.js +0 -15
- package/web/assets/imageStudio-BqbNOvpu.css +0 -1
- package/web/assets/imageStudio-C_Rs630L.js +0 -2
- package/web/assets/index-BCubCwdT.js +0 -1
- package/web/assets/index-DZfZTksa.js +0 -1
- package/web/assets/main-Dki8NlsT.js +0 -21
- package/web/assets/markdownEditorSurface-B4PeUzed.js +0 -3
- package/web/assets/mdMarkStore-CsKl7C8O.js +0 -2
- package/web/assets/minus-Cyv1YzOU.js +0 -1
- package/web/assets/mobileEntry-Bd_nKr0D.js +0 -13
- package/web/assets/nativeDownload-D-f1_L2S.js +0 -1
- package/web/assets/pageChrome-C9_azUYW.js +0 -1
- package/web/assets/panel-left-rOc8As0s.js +0 -1
- package/web/assets/pen-line-m6_HvWZ9.js +0 -1
- package/web/assets/sticky-note-BIuPUSOU.js +0 -1
- package/web/assets/tableSurface-Y_JBQsuz.js +0 -1
- package/web/assets/theme-DfEi_DND.css +0 -1
- package/web/assets/type-Cqoabh7H.js +0 -1
- package/web/assets/userSpaces-DyyAn7vj.js +0 -1
- package/web/assets/viewportLock-C4SX-9PO.js +0 -103
- package/web/assets/viewportLock-DYSe7Jsn.css +0 -1
- package/web/assets/waves-horizontal-B8ZpHQ5H.js +0 -1
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PdfAnnotator-D79ip27w.js","./index-CF4RV4mh.js","./pdf-C2_sJa3b.js","./pdf.worker.min-CGb3BKV9.js","./appStore-Dg9WALEA.js","./nativeDownload-D-f1_L2S.js","./ipc-DQOD2UKk.js","./client-BSKpsyAw.js","./appStore-Di8LXuJ9.css","./panel-left-rOc8As0s.js","./pen-line-m6_HvWZ9.js","./waves-horizontal-B8ZpHQ5H.js","./type-Cqoabh7H.js","./sticky-note-BIuPUSOU.js","./minus-Cyv1YzOU.js","./PdfAnnotator-CGzC_o1Q.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as vn,j as m,u as nn,d as k,N as So,t as we,bB as wu,bC as ku,bD as Cu,bE as Bs,b2 as Su,a_ as cl,bF as Eu,b5 as Mu,bG as Gs,bH as zu,bI as Rc,bJ as Nu,bK as $u,l as il,bL as Au,bM as Po,bN as Tu,aG as ju,aT as Ru,bO as Lu,bP as ll,n as Du,bQ as Iu,m as ms,aO as ul,aS as Pu,bv as sa,I as Fu,ag as Lc,V as Ou,_ as _u,bR as Bu,J as Ku,bS as Hu,bT as Vu,ab as qu,q as dl,as as Dc,B as fl,bU as Ic,bV as Ks,bW as Pc,bX as Wu,bY as Fc,ad as Yu,bZ as go,b_ as Oc,b$ as Xu,aw as Uu,c0 as Gu,ax as Ju,c1 as Zu,c2 as Qu}from"./index-CF4RV4mh.js";import{F as ed,c as Js,d as td,t as nd,e as rd,f as od,g as sd,p as ec,l as ml,h as ad,i as Da,j as cd,k as id,m as ld,n as ud,o as aa,q as ca,r as dd,v as Hs,w as Ia,x as fd,y as Vs,z as md,A as Pa,B as pl,C as _c,D as pd,E as hd,G as gd,T as yd,H as xd,I as bd,J as vd,K as wd,u as hl,L as kd,M as Cd,N as Sd,O as Ed,Q as Bc,R as Md,S as Ms,U as zd,V as Nd,W as $d,X as gl,Y as ss,Z as Ad,_ as Td,$ as jd,a0 as Rd,a1 as Ld,a2 as Dd,a3 as ia,a4 as Id,a5 as Pd,a6 as Fd}from"./MarkdownBlock-DIjYEhTK.js";import{z as rn,lJ as Od,ag as _d,cp as Bd,d4 as bn,lK as Kd,cl as _o,lL as Ht,a7 as Fn,lM as Kc,lN as Fr,lO as Ae,lP as No,lQ as Hd,lR as Vd,lS as qd,bp as yl,da as Bn,eS as tc,lT as Hc,hT as Wd,af as Yd,au as nc,lU as Xd,aI as xl,lV as Ud,lW as Gd,lX as Jd,lY as jn,lZ as ye,l_ as wr,l$ as bl,aB as Fa,m0 as Vc,m1 as Zd,fA as Qd,m2 as oo,m3 as ir,m4 as ef,m5 as tf,m6 as nf,m7 as rf,m8 as qc,m9 as of,eQ as sf,eP as af,ma as cf,ez as vl,mb as Wc,fB as lf,mc as uf,ka as df,md as wl,me as ff,mf,mg as pf,mh as Oa,mi as hf,mj as Yc,mk as gf,ml as Xo,fa as _a,mm as Xc,mn as zs,dw as yf,eN as xf,jz as bf,jy as vf,mo as no,a8 as qo,P as wf,mp as Uc,mq as Gc,fo as Jc,kK as kf,mr as Cf,ms as Sf,mt as Ef,mu as Mf,mv as Zc,lp as zf,mw as Nf,mx as Qc,my as $f,kJ as Af,mz as Tf,mA as jf,mB as Rf,S as kl,aQ as Ba,mC as Lf,eR as Df,mD as If,es as Pf,mE as Ff,mF as Of,mG as _f,mH as Bf,mI as Kf,mJ as Hf,mK as Vf,mL as ei,mM as qf,mN as Wf,mO as la,mP as ti,mQ as ua,aH as Yf,cG as Xf,ck as Uf,lu as Gf,h2 as Jf,hF as ni,c0 as Zf,db as Qf,mR as ri,mS as em,mT as tm,mU as oi,mV as nm,K as rm,bj as om,mW as sm,mX as am,mY as cm,mZ as Ro,m_ as xn,m$ as im,n0 as lm,n1 as Ka,eE as da,n2 as si,n3 as um,n4 as dm,kg as Ns}from"./appStore-Dg9WALEA.js";import{$ as bt,a as Cl,b as rc}from"./index-BCubCwdT.js";import{N as fm,I as mm,S as pm,r as hm,a as gm,C as ym,U as xm}from"./pageChrome-C9_azUYW.js";import{h as Wo,l as bm,f as Yo,a as ai,i as oc,b as Fs,c as vm,d as yo,t as $s,e as As,g as fa,s as wm,j as km,k as Cm}from"./listFold-BsOVn9UZ.js";import{a as Sm,b as Em,c as ci,v as ii,i as Mm}from"./linkFollow-C0_3k_PC.js";import{c as zm}from"./client-BSKpsyAw.js";import{a as Nm,S as $m,F as Am}from"./SketchCard-D87GADyG.js";import{c as Sl}from"./nativeDownload-D-f1_L2S.js";import{r as Uo,a as Tm,C as jm}from"./Chrome-CwFiDmre.js";import{e as Rm,h as Lm,a as li,o as Dm,d as Im,i as Pm,g as Fm,j as Om,k as _m,f as Bm,c as Km}from"./canvasPrefs-BeG4oEgP.js";import{H as Hm}from"./hand-Crrw-nSn.js";import{S as El}from"./sticky-note-BIuPUSOU.js";import{T as Vm}from"./type-Cqoabh7H.js";import{F as qm}from"./frame-_xBVYe3P.js";import{M as Wm}from"./minus-Cyv1YzOU.js";import{createFoldMemory as Ym,remapFoldMemory as Xm}from"./foldActions-B7KByFdN.js";import{L as Um}from"./lock-BnGHxjeE.js";import{C as Gm}from"./code-xml-BALV9u_c.js";import{U as Jm}from"./undo-2-tUKCv5Gs.js";import{M as Zm}from"./message-square-plus-BiAZAvcw.js";const Qm=[["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"}]],ep=rn("align-center-vertical",Qm);const tp=[["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"}]],np=rn("between-horizontal-end",tp);const rp=[["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"}]],op=rn("between-horizontal-start",rp);const sp=[["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"}]],ap=rn("between-vertical-end",sp);const cp=[["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"}]],ip=rn("between-vertical-start",cp);const lp=[["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"}]],up=rn("case-sensitive",lp);const dp=[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]],fp=rn("chevrons-down",dp);const mp=[["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"}]],pp=rn("heading-1",mp);const hp=[["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"}]],gp=rn("heading-2",hp);const yp=[["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"}]],xp=rn("heading-3",yp);const bp=[["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"}]],vp=rn("list-collapse",bp);const wp=[["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"}]],kp=rn("list-ordered",wp);const Cp=[["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"}]],Sp=rn("move-horizontal",Cp);const Ep=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Mp=rn("move-right",Ep);const zp=[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Np=rn("move-left",zp);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"}]],Ap=rn("pilcrow",$p);const Tp=[["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"}]],jp=rn("regex",Tp);const Rp=[["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"}]],Lp=rn("replace-all",Rp);const Dp=[["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"}]],Ip=rn("replace",Dp);const Pp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],Fp=rn("rows-2",Pp);const Op=[["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"}]],_p=rn("spline",Op);const Bp=[["path",{d:"M17 5H3",key:"1cn7zz"}],["path",{d:"M21 12H8",key:"scolzb"}],["path",{d:"M21 19H8",key:"13qgcb"}],["path",{d:"M3 12v7",key:"1ri8j3"}]],Kp=rn("text-quote",Bp);function Hp(e,t){const n=e.trim().toLowerCase(),r=t.toLowerCase();if(!n)return 1;let o=0,s=0,c=-2,l=-1;for(let i=0;i<r.length&&s<n.length;i++)if(r[i]===n[s]){l<0&&(l=i);let f=1;i===c+1&&(f+=4),(i===0||/[\s/\-_.]/.test(r[i-1]))&&(f+=3),o+=f,c=i,s++}return s<n.length?null:(o-=l*.1,o-=r.length*.02,r===n&&(o+=10),o)}function Vp(e,t,n){if(!e.trim())return t;const r=[];for(const o of t){const s=Hp(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)}vn({"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 Ha="amadeus_delete_assets";function Rb(){try{const e=localStorage.getItem(Ha);return e==="yes"?!0:e==="no"?!1:null}catch{return null}}function qp(e){try{e===null?localStorage.removeItem(Ha):localStorage.setItem(Ha,e?"yes":"no")}catch{}}const ps=Sl(e=>({req:null,open:t=>e({req:t}),clear:()=>e({req:null})}));function Wp(e,t,n){return new Promise(r=>{ps.getState().req?.resolve(null),ps.getState().open({note:e,assets:t,block:n?.block,resolve:r})})}function Lb(){const e=ps(t=>t.req);return e?m.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},children:m.jsx(Yp,{req:e},e.note)}):null}function Yp({req:e}){const{t}=nn(),[n,r]=k.useState(!1),o=c=>{ps.getState().req===e&&(n&&c!==null&&qp(c==="with"),ps.getState().clear(),e.resolve(c))};Od(()=>o(null));const s=e.assets.slice(0,6);return m.jsx("div",{className:"dialog-overlay",onMouseDown:()=>o(null),children:m.jsxs("div",{className:"dialog",onMouseDown:c=>c.stopPropagation(),children:[m.jsx("div",{className:"dialog-title",children:e.block?t("delassets.blockTitle"):t("delassets.noteTitle",{name:e.note})}),m.jsxs("div",{className:"dialog-msg",children:[e.block?t("delassets.blockMsg",{n:e.assets.length}):t("delassets.noteMsg",{n:e.assets.length}),m.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18,opacity:.8},children:[s.map(c=>m.jsx("li",{children:c},c)),e.assets.length>s.length&&m.jsx("li",{children:t("delassets.more",{n:e.assets.length-s.length})})]})]}),!e.block&&m.jsxs("label",{className:"inline-check",style:{display:"flex",gap:6,alignItems:"center",marginTop:10},children:[m.jsx("input",{type:"checkbox",checked:n,onChange:c=>r(c.target.checked)}),t("delassets.remember")]}),m.jsxs("div",{className:"dialog-actions",children:[e.block?m.jsx("button",{className:"dialog-btn",autoFocus:!0,onClick:()=>o("only"),children:t("delassets.keepFiles")}):m.jsxs(m.Fragment,{children:[m.jsx("button",{className:"dialog-btn",onClick:()=>o(null),children:t("delassets.cancel")}),m.jsx("button",{className:"dialog-btn",onClick:()=>o("only"),children:t("delassets.noteOnly")})]}),m.jsx("button",{className:"dialog-btn","data-danger":!0,autoFocus:!e.block,onClick:()=>o("with"),children:t("delassets.deleteAll")})]})]})})}vn({"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 Va="forsion.amadeus.aiSpaceTrigger";let as=null;function Xp(){if(as===null)try{as=localStorage.getItem(Va)==="1"}catch{as=!1}return as}function Db(e){as=e;try{e?localStorage.setItem(Va,"1"):localStorage.removeItem(Va)}catch{}}vn({"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 Ml=typeof CSS<"u"&&"highlights"in CSS;let Kt=[],hs=[];const xt=Sl(()=>({open:!1,query:"",active:0,total:0,root:null,caseSensitive:!1,regex:!1,bad:!1,replaceOpen:!1,replacement:"",replaceable:0,providerVer:0})),gs=new Set,ui=()=>xt.setState(e=>({providerVer:e.providerVer+1}));function di(e){return gs.add(e),ui(),()=>{gs.delete(e),ui()}}function sc(e){const t=e.startContainer;for(const n of gs)if(n.el.isConnected&&(n.owns?n.owns(t):n.el.contains(t)))return n;return null}function fi(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 l=Number(c);if(l>=1&&l<t.length)return t[l]??"";if(c.length===2&&Number(c[0])>=1&&Number(c[0])<t.length)return(t[Number(c[0])]??"")+c[1]}return r})}function zl(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 Up(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:D,text:N})=>({from:D.startOffset,to:D.endOffset,text:N,was:D.toString()})).filter(D=>s.slice(D.from,D.to)===D.was).sort((D,N)=>D.from-N.from);if(!c.length)return 0;const l=c[0].from,i=c[c.length-1].to;let f="",p=l;for(const D of c)f+=s.slice(p,D.from)+D.text,p=D.to;f+=s.slice(p,i);const y=document.activeElement;return e.focus(),e.setSelectionRange(l,i),(f?document.execCommand("insertText",!1,f):document.execCommand("delete"))||(e.setRangeText(f,l,i,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))),y?.focus(),r(),c.length},focusAt:o=>t?.contains(o.startContainer)?(e.focus({preventScroll:!0}),e.setSelectionRange(o.startOffset,o.endOffset),!0):!1}}function Gp(){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 Jp(){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 ys=null;function Zp(){const e=document.activeElement;if(!(e instanceof HTMLElement)||e===document.body||e.closest(".amx-findbar")){ys=null;return}const t=window.getSelection(),n=t&&t.rangeCount?t.getRangeAt(0):null;ys={el:e,range:e.isContentEditable&&n&&e.contains(n.startContainer)?n.cloneRange():null}}function Qp(e){const t=e.startContainer.parentElement;if(!t?.isContentEditable)return null;let n=t;for(;n.parentElement?.isContentEditable;)n=n.parentElement;return n}function eh(e){const t=ys;ys=null;const n=document.activeElement;if(!(n&&n!==document.body&&!n.closest(".amx-findbar"))){if(e){if(sc(e)?.focusAt?.(e))return;const o=Qp(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 Ib(e={}){if(!Ml)return;const t=Jp();if(xt.getState().open){xt.setState({...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}});const n=document.querySelector(".amx-findbar input");n?.focus(),n?.select();return}Zp(),xt.setState({open:!0,root:Gp(),...t?{query:t}:{},...e.replace?{replaceOpen:!0}:{}})}function ma(e){const t=e==="keyboard"?Kt[xt.getState().active]??null:null;Kt=[],hs=[],cs(-1),xt.setState({open:!1,query:"",active:0,total:0,root:null,bad:!1,replaceable:0}),e?eh(t):ys=null}const th=/^(inline|contents|ruby)/;function nh(e,t){let n=e.parentElement;for(;n;){let r=t.get(n);if(r===void 0&&(r=th.test(getComputedStyle(n).display),t.set(n,r)),!r)return n;n=n.parentElement}return null}function rh(e,t){if(hs=[],!t)return[];const n=new WeakMap,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(f){const p=f.parentElement;if(!p||!f.nodeValue||p.closest(".amx-findbar"))return NodeFilter.FILTER_REJECT;const y=p.tagName;return y==="SCRIPT"||y==="STYLE"||y==="NOSCRIPT"||y==="TEXTAREA"||!p.checkVisibility()?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let o="";const s=[];let c=null;for(let f=r.nextNode();f;f=r.nextNode()){const p=f,y=nh(p,n);s.length&&y!==c&&(o+=`
|
|
3
|
-
`),c=y,s.push({node:p,at:o.length}),o+=p.nodeValue??""}const l=[];let i=0;t.lastIndex=0;for(let f=t.exec(o);f;f=t.exec(o)){if(!f[0]){t.lastIndex++;continue}if(f[0].includes(`
|
|
4
|
-
`))continue;const p=f.index,y=p+f[0].length;for(;i>0&&s[i].at>p;)i--;for(;i+1<s.length&&s[i+1].at<=p;)i++;let E=i;for(;E+1<s.length&&s[E+1].at<y;)E++;const D=document.createRange();D.setStart(s[i].node,p-s[i].at),D.setEnd(s[E].node,Math.min(y-s[E].at,s[E].node.length)),l.push(D),hs.push(f)}return l}function pa(e){const t=xt.getState(),n=zl(t.query,t);return Kt=rh(e,n==="bad"?null:n),xt.setState({bad:n==="bad",replaceable:Kt.filter(r=>sc(r)).length}),Kt.length}function cs(e){if(!Ml)return;const t=CSS.highlights;if(!Kt.length){t.delete("amx-find"),t.delete("amx-find-active");return}t.set("amx-find",new Highlight(...Kt));const n=Kt[e],r=n?new Highlight(n):new Highlight;r.priority=1,t.set("amx-find-active",r)}function oh(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 ha(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=oh(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 Pb(){return xt(t=>t.open)?m.jsx(sh,{}):null}function sh(){const{t:e}=nn(),t=xt(B=>B.query),n=xt(B=>B.active),r=xt(B=>B.total),o=xt(B=>B.root),s=xt(B=>B.caseSensitive),c=xt(B=>B.regex),l=xt(B=>B.bad),i=xt(B=>B.replaceOpen),f=xt(B=>B.replacement),p=xt(B=>B.replaceable),y=xt(B=>B.providerVer),[E,D]=k.useState({top:12,right:12}),N=k.useRef(null),S=!!o&&[...gs].some(B=>B.el.isConnected&&o.contains(B.el));k.useLayoutEffect(()=>{const B=()=>{const Y=o?.getBoundingClientRect();Y&&D({top:Y.top+8,right:Math.max(8,window.innerWidth-Y.right+8)})};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[o]),k.useLayoutEffect(()=>{if(!o)return;const B=[...gs].filter(Y=>Y.attach&&o.contains(Y.el)).map(Y=>Y.attach());return()=>B.forEach(Y=>Y())},[o,y]),k.useEffect(()=>{o&&(pa(o),xt.setState({total:Kt.length,active:0}),cs(0),Kt.length&&ha(Kt[0]))},[o,t,s,c,y]),k.useEffect(()=>{if(!o)return;const B=()=>{o.isConnected||ma()};window.addEventListener("focusin",B);const Y=window.setInterval(B,1e3);return()=>{window.removeEventListener("focusin",B),window.clearInterval(Y)}},[o]),k.useEffect(()=>{if(!o||!t.trim())return;let B=0;const Y=new MutationObserver(()=>{window.clearTimeout(B),B=window.setTimeout(()=>{pa(o);const Te=Math.min(xt.getState().active,Math.max(0,Kt.length-1));xt.setState({total:Kt.length,active:Te}),cs(Te)},150)});return Y.observe(o,{childList:!0,subtree:!0,characterData:!0}),()=>{window.clearTimeout(B),Y.disconnect()}},[o,t,s,c]);const A=B=>{if(!Kt.length)return;const Y=(xt.getState().active+B+Kt.length)%Kt.length;xt.setState({active:Y}),cs(Y),ha(Kt[Y])},_=B=>{if(!o||!Kt.length)return;const Y=xt.getState(),Te=B?Kt.map((de,ce)=>ce):[Y.active],Ve=new Map;for(const de of Te){const ce=sc(Kt[de]);if(!ce)continue;const be=Ve.get(ce)??[];be.push({range:Kt[de],text:fi(Y.replacement,hs[de],Y.regex)}),Ve.set(ce,be)}let h=0;for(const[de,ce]of Ve)h+=de.replace(ce);if(!h&&!B){A(1);return}const Se=Y.active,lt=B?"":fi(Y.replacement,hs[Y.active],Y.regex);pa(o);let ne=0;if(!B&&Kt.length){const de=zl(Y.query,Y),ce=de&&de!=="bad"?(lt.match(new RegExp(de.source,de.flags))??[]).length:0;ne=(Se+ce)%Kt.length}xt.setState({total:Kt.length,active:ne}),cs(ne),Kt.length&&ha(Kt[ne])},X=B=>B.key==="Escape"?(ma("keyboard"),!0):(B.metaKey||B.ctrlKey)&&B.altKey&&B.code==="KeyF"?(B.preventDefault(),S&&xt.setState({replaceOpen:!xt.getState().replaceOpen}),!0):!1,te=B=>{xt.setState({[B]:!xt.getState()[B]}),N.current?.focus()};return m.jsxs("div",{className:`amx-findbar${i&&S?" amx-findbar--replace":""}`,style:{top:E.top,right:E.right},children:[S&&m.jsx("button",{className:"amx-findbar-expand",onClick:()=>xt.setState({replaceOpen:!i}),title:e("find.toggleReplace"),"aria-label":e("find.toggleReplace"),"aria-expanded":i,children:i?m.jsx(_d,{size:14}):m.jsx(Bd,{size:14})}),m.jsxs("div",{className:"amx-findbar-rows",children:[m.jsxs("div",{className:"amx-findbar-row",children:[m.jsx("input",{ref:N,autoFocus:!0,placeholder:e("find.placeholder"),value:t,"aria-invalid":l||void 0,title:l?e("find.badRegex"):void 0,onFocus:B=>B.currentTarget.select(),onChange:B=>xt.setState({query:B.target.value}),onKeyDown:B=>{!X(B)&&B.key==="Enter"&&A(B.shiftKey?-1:1),B.stopPropagation()}}),m.jsx("button",{className:"amx-findbar-opt",onClick:()=>te("caseSensitive"),"aria-pressed":s,title:e("find.case"),"aria-label":e("find.case"),children:m.jsx(up,{size:15})}),m.jsx("button",{className:"amx-findbar-opt",onClick:()=>te("regex"),"aria-pressed":c,title:e("find.regex"),"aria-label":e("find.regex"),children:m.jsx(jp,{size:14})}),m.jsx("span",{className:"amx-findbar-count",children:r?`${n+1}/${r}`:t.trim()?"0":""}),m.jsx("button",{onClick:()=>A(-1),title:e("find.prev"),"aria-label":e("find.prev"),children:"‹"}),m.jsx("button",{onClick:()=>A(1),title:e("find.next"),"aria-label":e("find.next"),children:"›"}),m.jsx("button",{onClick:()=>ma("pointer"),title:e("find.close"),"aria-label":e("find.close"),children:"✕"})]}),i&&S&&m.jsxs("div",{className:"amx-findbar-row",children:[m.jsx("input",{className:"amx-findbar-replace",placeholder:e("find.replacePlaceholder"),value:f,onChange:B=>xt.setState({replacement:B.target.value}),onKeyDown:B=>{!X(B)&&B.key==="Enter"&&_(B.metaKey||B.ctrlKey),B.stopPropagation()}}),m.jsx("button",{className:"amx-findbar-act",onClick:()=>_(!1),disabled:!p,title:e("find.replaceOne"),"aria-label":e("find.replaceOne"),children:m.jsx(Ip,{size:14})}),m.jsx("button",{className:"amx-findbar-act",onClick:()=>_(!0),disabled:!p,title:e("find.replaceAll"),"aria-label":e("find.replaceAll"),children:m.jsx(Lp,{size:14})})]})]})]})}vn({"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 so(e){typeof window>"u"||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:e}))}const ao=e=>(e.split("/").pop()??e).replace(/\.md$/i,"");let mi=Promise.resolve();function ga(e,t,n=new Date){const r=mi.then(()=>pi(e,t,n),()=>pi(e,t,n));return mi=r.catch(()=>{}),r}async function pi(e,t,n){const r=wu(e,n);for(let o=1;o<=50;o++){const s=ku(r,o),c=await bn.readTextFile(s);if(c===t)return s;if(c!=null)continue;const l=await bn.writeTextFile(s,t,{create:!0});if(l&&l.ok===!1){if(l.current===t)return s;if(l.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 ah(e,t,n=!1){so({level:"error",dedupeKey:`amx-conflict:${e}`,text:we(n?"unisave.conflict.agentToast":"unisave.conflict.toast",{name:ao(e),copy:ao(t)}),action:{label:we("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function Nl(e){const n=(e instanceof Error?e.message:typeof e=="string"?e:"").replace(/^Error invoking remote method '[^']*':\s*/,"").replace(/^(?:[A-Za-z]*Error:\s*)+/,"").trim();return n?n.length>80?`${n.slice(0,79)}…`:n:we("unisave.failed.unknown")}function ya(e,t){so({level:"warning",dedupeKey:`amx-savefail:${e}`,text:we("unisave.failed.toast",{name:ao(e),reason:Nl(t)})})}function ch(e,t){so({level:"error",dedupeKey:`amx-rescued:${t}`,text:we("unisave.rescued.toast",{name:ao(e),copy:ao(t)}),action:{label:we("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function ih(e,t){so({level:"error",dedupeKey:`amx-renamecopy:${t}`,text:we("unisave.renameCopy.toast",{name:ao(e),copy:ao(t)}),action:{label:we("unisave.conflict.open"),run:()=>{window.dispatchEvent(new CustomEvent("amadeus:navigate-note",{detail:{path:t},cancelable:!0}))}}})}function lh(e,t){so({level:"error",dedupeKey:`amx-gone:${e}:${So(t)}`,text:we("unisave.gone.toast",{name:ao(e)}),action:{label:we("unisave.gone.copy"),run:()=>{navigator.clipboard?.writeText(t).then(()=>so({text:we("unisave.gone.copied")}),()=>{})}}})}const hi=[2e3,5e3,1e4,3e4,6e4],$l=(e,t)=>`amadeus.unsavedDraft:${e??""}:${t}`,qs=(e,t,n)=>$l(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(qs(e,t,o),JSON.stringify(s))}catch{}}function is(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 uh(e,t,n,r=()=>!0){try{const o=qs(e,t);if(n){const l=is(localStorage.getItem(qs(e,t,n)),n);if(l)return l;const i=r(null)?null:is(localStorage.getItem(o),null);if(i)return i}else{const l=is(localStorage.getItem(o),null);if(l)return l}const s=$l(e,t)+"\0";let c=null;for(let l=0;l<localStorage.length;l++){const i=localStorage.key(l);if(!i||!i.startsWith(s))continue;const f=i.slice(s.length);if(f===n||r(f))continue;const p=is(localStorage.getItem(i),f);p&&(!c||p.at>c.at)&&(c=p)}return c}catch{return null}}function Go(e,t,n,r){try{const o=qs(e,t,r);if(n!=null){const s=is(localStorage.getItem(o),r??null);if(!s||s.text!==n)return}localStorage.removeItem(o)}catch{}}function dh(){return typeof navigator<"u"&&/\bElectron\//.test(navigator.userAgent)}function vo(e){const t=Cu(e);return t.length===e.length&&e.startsWith(Bs)?{fmText:Bs,body:e.slice(1)}:{fmText:e.slice(0,e.length-t.length),body:t}}function An(e,t){return e+t}function xa(e,t){const n=bs(e);return n.trim()&&!fh(n)?e:vo(Eu(e,t)).fmText}function fh(e){try{const t=Gs(e);return t==null||typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function mh(e,t){const n=ph(e,t);if(n!==null)return Wa(e,n);const{bom:r}=xs(e),o=Ya(e),s=t.replace(/\n+$/,"");if(!o.length&&!s.trim())return r;const c=r+["---",...o,...s.trim()?[s]:[],"---",""].join(`
|
|
5
|
-
`);return qa(s)?Wa(e,c):c}function ph(e,t){const n=bs(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 bs(c)===r&&Ya(c).join(`
|
|
7
|
-
`)===Ya(e).join(`
|
|
8
|
-
`)?c:null}function qa(e){try{return Gs(e),!0}catch{return!1}}function Wa(e,t){if(t===e)return t;const n=xs(t).inner;if(n==null||qa(n))return t;const r=xs(e).inner;return r==null||!qa(r)?t:(console.warn("[amadeus] frontmatter rewrite would produce invalid YAML; keeping the original block"),e)}const hh=/^---\r?\n([\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)$/;function xs(e){const t=e.startsWith(Bs)?Bs:"",n=hh.exec(e.slice(t.length));return{bom:t,inner:n?n[1]??"":null}}function ac(e){const{inner:t}=xs(e);return t==null?null:t?zu(t.replace(/\r?\n$/,"").split(/\r?\n/)):[]}function Ya(e){return(ac(e)??[]).filter(t=>Mu.test(t[0])).flat()}const gh=/^["']?amadeus_(schema|layout|canvas)["']?\s*:/;function ls(e,t,n){const{bom:r}=xs(e),o=ac(e)??[],s=o.filter(i=>!gh.test(i[0])).flat(),l=[...Kd(t,n).flatMap(i=>{const f=xh.exec(i)?.[1],p=f?Tl(o,f):null;return p&&p.length>1&&jl(p,f)===(f==="layout"?t:n)?p:[i]}),...s];return l.length?Wa(e,r+["---",...l,"---",""].join(`
|
|
9
|
-
`)):r}function yh(e){const t=yr(e),n=cn(e);return t==null&&n==null||/^["']?amadeus_schema["']?\s*:/m.test(e)?e:ls(e,t,n)}function yr(e){return Al(e,"layout")}function cn(e){return Al(e,"canvas")}const xh=/^amadeus_(layout|canvas):/;function Al(e,t){const n=ac(e),r=n&&Tl(n,t);return r?jl(r,t):null}function Tl(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 jl(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=Gs(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 bh(e){return e?Su(cl(e)):{}}function bs(e){return e?cl(e):""}const vh=80;function wh(){return bt(()=>{if(!_o())return new Ht({});const e=Math.round(vh*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 Ws(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 gi(e,t=0,n=e.content.size){return e.textBetween(t,n,`
|
|
11
|
-
`,()=>"").replace(/!\[\[[^\]\n]*\]\]/g,"").replace(/\[\[(?:[^\]|\n]*\|)?([^\]\n]*)\]\]/g,"$1")}function kh(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=Kc(gi(t)));const{from:o,to:s,empty:c}=r.state.selection;return{all:n,sel:c?null:Kc(gi(r.state.doc,o,s))}}}function Ch(){return[bt(()=>new Ht({view:()=>{let e=0;const t=()=>{e||(e=requestAnimationFrame(()=>{e=0,Rc()}))};return t(),{update:(n,r)=>{(n.state.doc!==r.doc||!n.state.selection.eq(r.selection))&&t()},destroy:()=>{e&&cancelAnimationFrame(e),Rc()}}}}))]}function Sh(e){const t=(r,o,s)=>{const c=r.selection;return!(c instanceof Ae)||!c.empty||!s||No.atStart(r.doc).$from.start()!==c.$from.start()||!s.endOfTextblock("up")?!1:e()},n=r=>{const o=r.selection;if(!(o instanceof Ae)||!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[bt(()=>Fr({ArrowUp:t,ArrowLeft:n}))]}function yi(e,t){const n=e.content.size;return e.textBetween(Math.max(0,t-12),Math.min(n,t+12),`
|
|
12
|
-
`,"")}function Eh(e){return[bt(()=>new Ht({view:t=>{let n=!0,r=null;const o=()=>{r=null;const{vaultRoot:c,path:l}=e.where(),i=t.state.selection;Vd(c,l,{a:i.anchor,h:i.head,t:yi(t.state.doc,i.head)})};queueMicrotask(()=>{if(!n||!e.restore())return;const{vaultRoot:c,path:l}=e.where(),i=Hd(c,l),f=t.state.doc;let p=null;if(i&&i.a<=f.content.size&&i.h<=f.content.size&&yi(f,i.h)===i.t){try{p=Ae.between(f.resolve(i.a),f.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(),qd())};return window.addEventListener("pagehide",s),{update:(c,l)=>{c.state.selection.eq(l.selection)&&c.state.doc===l.doc||(r&&clearTimeout(r),r=setTimeout(o,300))},destroy:()=>{n=!1,window.removeEventListener("pagehide",s),r&&(clearTimeout(r),o())}}}}))]}vn({"canvasseg.aria":{zh:"编辑模式",en:"Editing mode"},"canvasseg.doc":{zh:"文档",en:"Document"},"canvasseg.canvas":{zh:"画布",en:"Canvas"}});const Mh="amx-modeseg-slot";function zh({on:e,toggle:t}){const{t:n}=nn();return m.jsxs("div",{className:"t2s-vaultseg amx-modeseg",role:"tablist","aria-label":n("canvasseg.aria"),children:[m.jsx("div",{className:"t2s-vaultseg-thumb","data-side":e?"canvas":"doc"}),m.jsx("button",{type:"button",role:"tab","aria-selected":!e,className:e?"":"on",onMouseDown:r=>r.preventDefault(),onClick:()=>{e&&t()},children:n("canvasseg.doc")}),m.jsx("button",{type:"button",role:"tab","aria-selected":e,className:e?"on":"",onMouseDown:r=>r.preventDefault(),onClick:()=>{e||t()},children:n("canvasseg.canvas")})]})}function Nh({anchor:e,on:t,toggle:n}){const[r,o]=k.useState(null);return k.useEffect(()=>{const s=e?.closest(".amx-pane")??e?.ownerDocument?.body;if(!s)return;const c=()=>o(s.querySelector(`.${Mh}`));c();const l=new MutationObserver(c);return l.observe(s,{childList:!0,subtree:!0}),()=>l.disconnect()},[e]),r?yl.createPortal(m.jsx(zh,{on:t,toggle:n}),r):null}vn({"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 Ah(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 Th=e=>/^(tags?|alias(es)?|cssclass(es)?)$/i.test(e.trim())?"list":"text",Rl=e=>/\[\[[^\]\n]+\]\]/.test(e);function ba(e){if(!e.trim())return{ok:!0,entries:[]};try{const t=Gs(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 Ll=e=>Array.isArray(e)&&e.every(t=>t===null||typeof t!="object");function va(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 Dl=k.createContext(null);function cc(e,t,{escDiscards:n="conflict",norm:r=s=>s,enterCommits:o=!1}={}){const[s,c]=k.useState(null),[l,i]=k.useState(e),f=k.useRef({draft:s,base:l,current:e,norm:r,commit:t});f.current.current=e,f.current.norm=r,f.current.commit=t;const p=S=>{f.current.draft=S,c(S)},y=S=>{f.current.base=S,i(S)},E=k.useContext(Dl);k.useLayoutEffect(()=>{if(!E)return;const S=()=>{const A=f.current,_=va(A.draft,A.base,A.current,A.norm);_!==null&&(y(_),A.commit(_))};return E.add(S),()=>{E.delete(S),S()}},[E]);const D=s!==null&&e!==l&&va(s,l,e,r)!==null;return{shown:s??e,conflict:D,change:S=>{f.current.draft===null&&y(f.current.current),p(S)},settle:()=>{const S=f.current,A=va(S.draft,S.base,S.current,S.norm);return p(null),A},onKeyDown:S=>{if(!(S.nativeEvent.isComposing||S.keyCode===229)){if(S.key==="Enter"&&o){S.preventDefault(),S.currentTarget.blur();return}S.key!=="Escape"||n==="never"||!D||(S.preventDefault(),S.stopPropagation(),p(null))}}}}function jh({fmExtra:e,onCommit:t,readOnly:n=!1,notePath:r}={}){const{t:o}=nn(),s=Bn(be=>be.activePage),c=Bn(be=>be.vaultRoot),l=Bn(be=>be.manifest?.fmExtra??""),i=tc(),f=e!==void 0,p=f?e:l,y=k.useRef(p);y.current=p;const[E,D]=k.useState(()=>Hc(c)??!1);k.useEffect(()=>{D(Hc(c)??!1)},[c]);const N=be=>{D(Ee=>{const ve=typeof be=="function"?be(Ee):be;return Xd(c,ve),ve})},[S,A]=k.useState(!1),[_,X]=k.useState(null),te=k.useRef(null),B=r??s??void 0,Y=be=>{const Ee=il(be);Ee&&i.getState().openWikiLink(Ee,B)},Te=k.useMemo(()=>ba(p),[p]),Ve=k.useMemo(()=>{const be=!f&&s?Wd(s):void 0;return new Set(be?.fmKeys??[])},[f,s]),h=k.useMemo(()=>Te.entries.map((be,Ee)=>({...be,idx:Ee})).filter(be=>!Ve.has(be.key)),[Te,Ve]);if(k.useEffect(()=>{if(!_)return;const Ee=[...te.current?.querySelectorAll(".amx-prop-row[data-key]")??[]].find(ve=>ve.dataset.key===_)?.querySelector("input:not(.amx-prop-key), textarea, .amx-prop-links");Ee&&(Ee.focus(),Ee.classList.contains("amx-prop-links")&&Ee.click(),X(null))},[_,Te]),!f&&!s)return null;const Se=be=>{t?t(be):i.getState().setFmExtra(be)},lt=be=>{be!==null&&Se(be)},ne=(be,Ee)=>lt(Au(y.current,{[be]:Ee})),de=(be,Ee)=>{const ve=be.trim();return ve?/^amadeus_/.test(ve)?(window.alert(o("amprops.reservedKey")),!1):Ve.has(ve)?(window.alert(o("amprops.pluginManaged")),!1):(ba(y.current).entries.some(Ce=>Ce.key===ve)||ne(ve,Ah(Ee)),X(ve),!0):!1},ce=Te.ok?h.length:null;return m.jsxs("div",{className:`amx-props${ce===0&&!E?" is-empty":""}`,ref:te,children:[m.jsxs("div",{className:"amx-props-bar",children:[m.jsxs("button",{className:"amx-props-chip",onClick:()=>N(be=>!be),children:[ce===null?o("amprops.chipRaw"):o("amprops.chipCount",{n:ce}),E?" ▾":" ▸"]}),!n&&m.jsx("button",{className:"amx-props-add",title:o("amprops.add"),onClick:()=>{N(!0),Te.ok&&A(!0)},children:m.jsx(Yd,{size:12})})]}),E&&(Te.ok?m.jsxs("div",{className:"amx-props-rows",children:[h.length===0&&!S&&m.jsx("div",{className:"amx-props-empty",children:o("amprops.empty")}),h.map(be=>n?m.jsxs("div",{className:"amx-prop-row amx-prop-row-ro",children:[m.jsx("span",{className:"amx-prop-key",children:be.key}),m.jsx(Dh,{value:be.value})]},`${s}:${be.idx}:${be.key}`):m.jsxs("div",{className:"amx-prop-row","data-key":be.key,children:[m.jsx(Lh,{name:be.key,onRename:Ee=>{const ve=/^(amadeus_page|amadeus_schema|amadeus_layout|amadeus_canvas|amadeus_next_id)$/.test(Ee)||Ve.has(Ee)||ba(y.current).entries.some(Ce=>Ce.key!==be.key&&Ce.key===Ee);!Ee||ve||lt(Nu(y.current,be.key,Ee))}}),m.jsx(Fh,{value:be.value,onCommit:Ee=>ne(be.key,Ee),onOpenLink:Y}),m.jsx("button",{className:"amx-prop-del",title:o("amprops.delete"),onClick:()=>ne(be.key,void 0),children:m.jsx(nc,{size:12})})]},`${s}:${be.key}`)),S&&!n&&m.jsx(Ih,{onAdd:(be,Ee)=>{de(be,Ee)&&A(!1)},onCancel:()=>A(!1)})]}):m.jsxs(m.Fragment,{children:[Ve.size>0&&m.jsx("div",{className:"amx-props-empty",children:o("amprops.pluginKeysWarn",{keys:[...Ve].join(", ")})}),m.jsx(Rh,{text:p,readOnly:n,onCommit:Se})]}))]})}function Rh({text:e,readOnly:t,onCommit:n}){const{t:r}=nn(),o=c=>{t||n(c)},s=cc(e,o,{escDiscards:"never"});return m.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 Lh({name:e,onRename:t}){const n=cc(e,t,{norm:r=>r.trim(),enterCommits:!0});return m.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 Dh({value:e}){return typeof e=="boolean"?m.jsx("span",{className:"amx-prop-check","aria-hidden":!0,children:e?"☑":"☐"}):Ll(e)?m.jsx("span",{className:"amx-prop-chips",children:e.map((t,n)=>m.jsx("span",{className:"amx-chip",children:String(t??"")},n))}):e==null?m.jsx("span",{className:"amx-prop-input"}):typeof e=="object"?m.jsx("span",{className:"amx-prop-input",children:JSON.stringify(e)}):m.jsx("span",{className:"amx-prop-input",children:String(e)})}function Ih({onAdd:e,onCancel:t}){const{t:n}=nn(),[r,o]=k.useState(""),[s,c]=k.useState("text"),[l,i]=k.useState(!1),f=l?s:Th(r);return m.jsxs("div",{className:"amx-prop-row amx-prop-new",children:[m.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,f)):p.key==="Escape"&&(p.preventDefault(),t()))}}),m.jsx("select",{className:"amx-prop-type","aria-label":n("amprops.type"),value:f,onChange:p=>{c(p.target.value),i(!0)},onKeyDown:p=>{p.key==="Escape"&&(p.preventDefault(),t())},children:$h.map(p=>m.jsx("option",{value:p,children:n(`amprops.type.${p}`)},p))}),m.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addConfirm"),"aria-label":n("amprops.addConfirm"),onClick:()=>e(r,f),children:m.jsx(xl,{size:12})}),m.jsx("button",{className:"amx-prop-del amx-prop-new-btn",title:n("amprops.addCancel"),"aria-label":n("amprops.addCancel"),onClick:t,children:m.jsx(nc,{size:12})})]})}function Il({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],l=c.indexOf("|");n.push(m.jsx("span",{className:"amx-prop-link",onMouseDown:i=>{i.preventDefault(),i.stopPropagation(),t(c)},onClick:i=>i.stopPropagation(),children:l>=0?c.slice(l+1):c},s.index)),o=s.index+s[0].length}return o<e.length&&n.push(e.slice(o)),m.jsx(m.Fragment,{children:n})}function Ph({value:e,onCommit:t,onOpenLink:n}){const{t:r}=nn(),[o,s]=k.useState(!1);return o?m.jsx(Xa,{current:e,autoFocus:!0,onCommit:t,onDone:()=>s(!1)}):m.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:m.jsx(Il,{text:e,onOpenLink:n})})}function Fh({value:e,onCommit:t,onOpenLink:n}){const{t:r}=nn();return typeof e=="boolean"?m.jsx("input",{type:"checkbox",className:"amx-prop-check",checked:e,onChange:o=>t(o.target.checked)}):Ll(e)?m.jsx(_h,{items:e.map(o=>String(o??"")),onCommit:t,onOpenLink:n}):typeof e=="number"?m.jsx(Xa,{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)?m.jsx(Oh,{value:e,onCommit:t}):typeof e=="string"&&!e.includes(`
|
|
13
|
-
`)&&Rl(e)?m.jsx(Ph,{value:e,onCommit:t,onOpenLink:n}):typeof e=="string"||e==null?m.jsx(Xa,{current:e??"",multiline:typeof e=="string"&&e.includes(`
|
|
14
|
-
`),onCommit:t}):m.jsx("span",{className:"amx-prop-nested",title:r("amprops.nestedHint"),children:$u(e).trimEnd()})}function Xa({current:e,norm:t,multiline:n=!1,autoFocus:r,onCommit:o,onDone:s}){const{t:c}=nn(),l=cc(e,o,{norm:t,enterCommits:!n}),i={className:`amx-prop-input${n?" amx-prop-multiline":""}${l.conflict?" amx-prop-conflict":""}`,value:l.shown,title:l.conflict?c("amprops.conflict",{v:e}):void 0,autoFocus:r,onKeyDown:l.onKeyDown,onBlur:()=>{const f=l.settle();f!==null&&o(f),s?.()}};return n?m.jsx("textarea",{...i,rows:Math.min(8,l.shown.replace(/\n$/,"").split(`
|
|
15
|
-
`).length),spellCheck:!1,onChange:f=>l.change(f.target.value)}):m.jsx("input",{...i,onChange:f=>l.change(f.target.value)})}function Oh({value:e,onCommit:t}){const[n,r]=k.useState(!1);return m.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 _h({items:e,onCommit:t,onOpenLink:n}){const{t:r}=nn(),[o,s]=k.useState(""),c=()=>{const i=o.trim();s(""),i&&!e.includes(i)&&t([...e,i])},l=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 m.jsxs("div",{className:"amx-prop-chips",children:[e.map((i,f)=>m.jsxs("span",{className:"amx-chip",children:[n&&Rl(i)?m.jsx(Il,{text:i,onOpenLink:n}):i,m.jsx("button",{className:"amx-chip-x",onClick:()=>t(e.filter((p,y)=>y!==f)),children:m.jsx(nc,{size:10})})]},`${f}:${i}`)),m.jsx("input",{value:o,placeholder:e.length?"":r("amprops.chipsPlaceholder"),onChange:i=>s(i.target.value),onKeyDown:l,onBlur:c})]})}const Bh=new Set(["bullet","ordered","task"]);function Pl(e,t,n,r){if(r.kind!=="quote"&&r.kind!=="fold"){const l=e.state.tr,i=l.doc.content.size;e.state.doc.nodesBetween(t,n,(f,p)=>f.type.name==="blockquote"?(Ol(l,l.mapping.map(p)),!1):!f.isTextblock),l.docChanged&&(e.dispatch(l),n+=l.doc.content.size-i)}const o=[];e.state.doc.nodesBetween(t,n,(l,i)=>l.isTextblock?(o.push(i+1),!1):!0);const s=e.state.doc.content.size;let c=!1;for(const l of o.reverse())e.dispatch(e.state.tr.setSelection(Ae.near(e.state.doc.resolve(l)))),Js(e,r,null)&&(c=!0);return c&&Bh.has(r.kind)&&Kh(e,t,n+(e.state.doc.content.size-s)),c}function Kh(e,t,n){const{doc:r}=e.state,o=r.resolve(t),s=o.parent,c=[];let l=o.start();for(let f=0;f<o.index();f++)l+=s.child(f).nodeSize;for(let f=o.index();f<s.childCount-1;f++){const p=s.child(f);if(l+=p.nodeSize,l>=n)break;const y=s.child(f+1);p.type===y.type&&/_list$/.test(p.type.name)&&c.push(l)}if(!c.length)return;const i=e.state.tr;for(const f of c.reverse())Jd(i.doc,f)&&i.join(f);i.docChanged&&e.dispatch(i)}function Ua(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 l=r.doc.textBetween(t,n,`
|
|
16
|
-
`,`
|
|
17
|
-
`).replace(/^\n+|\n+$/g,""),i=r.tr.replaceWith(t,n,o.create(null,l?r.schema.text(l):void 0));return i.setSelection(Ae.near(i.doc.resolve(t+1))),e.dispatch(i.scrollIntoView()),!0}const Hh=/^\[![\w-]+\]/;function xi(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 f=e.state.doc.resolve(t).blockRange(e.state.doc.resolve(n)),p=f&&Gd(f,o);if(!f||!p)return!1;e.dispatch(e.state.tr.wrap(f,p)),s=t}else{if(e.dispatch(e.state.tr.setSelection(Ae.near(e.state.doc.resolve(t+1)))),!Js(e,{kind:"quote"},null))return!1;const f=e.state.selection.$from;let p=f.depth;for(;p>0&&f.node(p).type!==o;)p--;if(p<1)return!1;s=f.before(p)}const l=e.state.doc.nodeAt(s),i=l?.firstChild;return!l||l.type!==o||!i?.isTextblock||Hh.test(i.textContent)?!!l:(e.dispatch(e.state.tr.insertText(i.content.size?"[!note] ":"[!note]",s+2)),!0)}const Fl=/^\[![\w-]+\]([+-])?[ \u00a0]?/;function Ol(e,t){const n=e.doc.nodeAt(t),r=n?.firstChild,o=n?.type.name==="blockquote"&&r?.isTextblock?Fl.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 bi(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?Fl.exec(s.textContent):null;if(!o||!s||!c)return null;const l=e.state.tr;if(r!=="code"&&r.kind==="fold"){if(/^\[!fold\]/i.test(s.textContent))return!0;const E=c[0].length-(/[ \u00a0]$/.test(c[0])?1:0);return l.replaceWith(t+2,t+2+E,e.state.schema.text(ed)),e.dispatch(l.scrollIntoView()),!0}if(Ol(l,t),r!=="code"&&r.kind==="quote")return l.setSelection(Ae.near(l.doc.resolve(t+1))),e.dispatch(l.scrollIntoView()),!0;const i=l.doc.nodeAt(t),f=i.content.size,p=l.doc.resolve(t+1).blockRange(l.doc.resolve(t+i.nodeSize-1)),y=p?Ud(p):null;return!p||y==null?!1:(l.lift(p,y),l.setSelection(Ae.near(l.doc.resolve(t+1))),e.dispatch(l.scrollIntoView()),r==="code"?Ua(e,t,t+f):r.kind==="text"?!0:r.kind==="heading"?Js(e,r,null):Pl(e,t,t+f,r))}function Vh(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 Bo(e){const t=Vh(e);return{text:t===`\r
|
|
22
|
-
`?e.replace(/\r\n/g,`
|
|
23
|
-
`):e,eol:t}}function Pr(e,t){return t===`\r
|
|
24
|
-
`?e.replace(/\r?\n/g,`\r
|
|
25
|
-
`):e}function us(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 l=o.index();l<s.childCount&&c<r;l++){const i=s.child(l);if(i.type.name==="heading"){const f=Yo(e,c);f!=null&&f>r&&(r=f)}c+=i.nodeSize}return r}function Fo(e,t,n){for(const r of[Wo,bm]){const o=r.getState(e)?.folded;if(!o?.length)continue;const s=[];for(const c of o){const l=c>=n.from&&c<n.to;(!l||n.copy)&&s.push(t.mapping.map(c)),l&&!n.drop&&n.newStart!=null&&s.push(n.newStart+(c-n.from))}t.setMeta(r,{set:s})}}function Jo(e,t,n){const r=t.getMeta(Wo)?.set;if(!r?.length)return;const o=ai(e.doc,Wo.getState(e)?.folded??[]),s=f=>o.some(p=>f>=p.start&&f<p.after),c=n.to-n.from,l=t.mapping.invert(),i=r.filter(f=>ai(t.doc,[f]).every(p=>{const y=t.doc.resolve(p.start),E=y.parent;let D=p.start;for(let N=y.index();N<E.childCount&&D<p.after;N++){const S=D;D+=E.child(N).nodeSize;const A=S>=n.newStart&&S<n.newStart+c?n.from+(S-n.newStart):l.map(S);if(!s(A))return!1}return!0}));i.length!==r.length&&t.setMeta(Wo,{set:i})}vn({"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 Or=e=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:e}}))},ic=e=>(e.split("/").pop()??e).replace(/\.md$/i,""),Zo=e=>e.split("/").slice(0,-1).join("/");function qh(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 Wh(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 Yh(e,t,n){return t===n?e:Iu(e,r=>r.replace(/(^|[^!])\[([^\]\n]*)\]\(([^)\s]+)((?:\s+"[^"]*")?)\)/g,(o,s,c,l,i)=>{if(/^(?:[a-z][a-z0-9+.-]*:|\/|#|<)/i.test(l))return o;const[f,p=""]=l.split(/(?=#)/);return`${s}[${c}](${Wh(n,qh(ul(t,f)))}${p}${i})`}))}function Xh(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 Uh(e,t){const{text:n,eol:r}=Bo(e),o=n?n.endsWith(`
|
|
27
|
-
|
|
28
|
-
`)?"":n.endsWith(`
|
|
29
|
-
`)?`
|
|
30
|
-
`:`
|
|
31
|
-
|
|
32
|
-
`:"";return Pr(`${n}${o}${t}
|
|
33
|
-
`,r)}function Gh(e,t){const n=ic(e);return ms(n,t)===e?n:e.replace(/\.md$/i,"")}function Jh(e,t,n){const r=Gh(t,n);if(e.type.name==="heading"){const s=td(e.textContent);return s?{kind:"heading",link:`[[${r}#${s}]]`}:null}const o=ll(e.textContent);return o?{kind:"block",link:`[[${r}#^${o}]]`}:null}function Zh(e){const t=navigator.clipboard?.writeText(e);if(!t){Or(we("blocklinks.copyFailed"));return}t.then(()=>Or(we("blocklinks.copied",{link:e})),()=>Or(we("blocklinks.copyFailed")))}function Qh(e){let t=!0;return e.descendants(n=>(/^amadeus(CanvasCard|ColumnRow|ColumnCell)$/.test(n.type.name)&&(t=!1),t)),t}async function eg(e){const{view:t,from:n,to:r,source:o,target:s}=e,c=ic(s);if(s===o)return!1;const l=t.state.doc.slice(n,r).content,i=e.serialize(l);if(!i?.trim())return Or(we("blocklinks.moveFailed",{name:c})),!1;let f=Yh(Po(i,Zo(s)).trim(),Zo(o),Zo(s));e.pages&&Zo(o)!==Zo(s)&&(f=Tu(f,o,s,{pairs:new Map,pagesBefore:e.pages,pagesAfter:e.pages}));try{if(ju(s)){if(!Ru(s,f,"end"))throw new Error("insert refused");try{await Lu(s,!0)}catch{return Or(we("blocklinks.targetUnsaved",{name:c})),!1}}else{const y=await bn.readTextFile(s);if(y==null)throw new Error("missing");if(Xh(Bo(y).text))throw new Error("unsafe tail");const E=await bn.writeTextFile(s,Uh(y,f),{base:So(y)});if(E&&!E.ok)return Or(we("blocklinks.moveConflict",{name:c})),!1}}catch{return Or(we("blocklinks.moveFailed",{name:c})),!1}if(t.isDestroyed||r>t.state.doc.content.size||!t.state.doc.slice(n,r).content.eq(l))return Or(we("blocklinks.keptSource",{name:c})),!0;const p=t.state.tr.delete(n,r);return Fo(t.state,p,{from:n,to:r,drop:!0}),t.dispatch(p.scrollIntoView()),Or(we("blocklinks.moved",{name:c})),!0}function _l({pages:e,exclude:t,onPick:n,onClose:r}){const{t:o}=nn(),[s,c]=k.useState(""),[l,i]=k.useState(0),f=Vp(s,e.filter(p=>p!==t&&/\.md$/i.test(p)),Du).slice(0,30);return k.useEffect(()=>{i(0)},[s]),yl.createPortal(m.jsx("div",{className:"cmd-overlay",onMouseDown:r,children:m.jsxs("div",{className:"cmd-panel",role:"dialog","aria-label":o("blocklinks.pickTitle"),"data-testid":"note-picker",onMouseDown:p=>p.stopPropagation(),children:[m.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(y=>Math.min(y+1,f.length-1))):p.key==="ArrowUp"?(p.preventDefault(),i(y=>Math.max(y-1,0))):p.key==="Enter"?(p.preventDefault(),f[l]&&n(f[l])):p.key==="Escape"&&(p.preventDefault(),p.stopPropagation(),r())}}),m.jsxs("div",{className:"cmd-list",role:"listbox",children:[f.map((p,y)=>m.jsx("button",{className:"cmd-item",role:"option","aria-selected":y===l,"data-active":y===l||void 0,onMouseEnter:()=>i(y),onClick:()=>n(p),children:m.jsxs("span",{className:"cmd-row",children:[m.jsx("span",{className:"cmd-title",children:ic(p)}),m.jsx("span",{className:"cmd-path",children:p})]})},p)),!f.length&&m.jsx("div",{className:"cmd-empty",children:o("blocklinks.noMatch")})]})]})}),document.body)}function tg(e){return e.nodeType===1}function ng(e){return tg(e)&&e.namespaceURI==="http://www.w3.org/1999/xhtml"}function rg(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&&ng(s)){const{top:c,bottom:l,left:i,right:f}=s.getBoundingClientRect();n.push([r,[i,c,f,c]],[r+o.nodeSize,[i,l,f,l]])}}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 og(e,t){let n=[],r,o;const s=()=>{const p=e.dom.getBoundingClientRect(),y=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(y)||(o=p,r=y,n=rg(e)),n},c=(p,y)=>{if(!e.editable||e.isDestroyed)return;const E=(S,A)=>{const[_,X]=S,[te,B]=A;return wi(p,X)-wi(p,B)||_-te};let D=s();D.sort(E),D=D.slice(0,8);const N=D.find(S=>t?.({view:e,pos:S[0],event:y})!==!1);if(!(N&&ag(e,N[0])))return N};let l,i;return(p,y)=>(l&&sg(l,p)||(l=p,i=c(p,y)),i)}function sg(e,t){return e[0]===t[0]&&e[1]===t[1]}function vi(e,t){return Math.abs(e[0]-t[0])+Math.abs(e[1]-t[1])}function wi(e,t){return Math.min(vi(e,[t[0],t[1]]),vi(e,[t[2],t[3]]))}function ag(e,t){const n=e.dragging;if(!n)return;const{move:r}=n;if(!r)return;const o=e.state.selection;if(!(o instanceof ye))return;const{from:s,to:c}=o;return s<=t&&t<=c}function cg(e){let t;return new Ht({key:new jn("prosemirror-drop-indicator"),view:n=>(t=og(n,e.onDrag),lg(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 l=c[0],i=n.state.tr;if(s){const{node:D}=n.dragging||{};D?D.replace(i):i.deleteSelection()}const f=i.mapping.map(l),p=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,y=i.doc;if(p?i.replaceRangeWith(f,f,o.content.firstChild):i.replaceRange(f,f,o),i.doc.eq(y))return!0;const E=i.doc.resolve(f);if(p&&ye.isSelectable(o.content.firstChild)&&E.nodeAfter&&E.nodeAfter.sameMarkup(o.content.firstChild))i.setSelection(new ye(E));else{let D=i.mapping.map(l);i.mapping.maps[i.mapping.maps.length-1].forEach((N,S,A,_)=>D=_),i.setSelection(ig(n,E,i.doc.resolve(D)))}return n.focus(),n.dispatch(i.setMeta("uiEvent","drop")),!0}}})}function ig(e,t,n,r){return e.someProp("createSelectionBetween",o=>o(e,t,n))||Ae.between(t,n,r)}function lg(e,t,n){const r=e.dom;let o,s,c,l=!1;const i=()=>{o&&clearTimeout(o),l=!1,o=setTimeout(()=>{l||n.onHide?.()},30)},f=y=>{l=!0;const{clientX:E,clientY:D}=y;if(s===E&&c===D)return;s=E,c=D;const N=t([E,D],y);if(N){const[S,[A,_,X,te]]=N,B={p1:{x:A,y:_},p2:{x:X,y:te}};n.onShow?.({view:e,pos:S,line:B})}else{i();return}};return r.addEventListener("dragover",f),r.addEventListener("dragend",i),r.addEventListener("drop",i),r.addEventListener("dragleave",i),{destroy:()=>{r.removeEventListener("dragover",f),r.removeEventListener("dragend",i),r.removeEventListener("drop",i),r.removeEventListener("dragleave",i)}}}vn({"canvasedit.textDefault":{zh:"文本",en:"Text"}});function Br(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.id;return typeof t=="string"&&t?t:null}function ki(e){if(!e||typeof e!="object")return null;const t=e.id;return typeof t=="string"&&t?t:null}function Ir(e){return Array.isArray(e)?[...e]:[]}function Bl(e,t,n){return e.map(r=>Br(r)===t?{...r,...n}:r)}function ug(e,t){const n=new Set,r=e.filter(o=>{const s=Br(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=ki(s.from),l=ki(s.to);return!(c&&n.has(c)||l&&n.has(l))}):r}function Ci(e,t,n,r){return e.map(o=>{const s=Br(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 ds(e,t){const n=new Set;for(const r of e){const o=Br(r);o&&n.add(o)}for(let r=1;;r++){const o=`${t}${r}`;if(!n.has(o))return o}}const ie="m:",dg={rect:{w:200,h:120},ellipse:{w:180,h:120},text:{w:180,h:40}},Si={w:480,h:320};function Kl(e,t,n){return{id:e,type:t==="text"?"text":"shape",...t==="text"?{}:{shape:t},x:Math.round(n.x),y:Math.round(n.y),w:Math.round(n.w),h:Math.round(n.h),...t==="text"?{text:we("canvasedit.textDefault")}:{}}}function fg(e,t,n,r){const o=dg[t];return Kl(e,t,{x:n-o.w/2,y:r-o.h/2,w:o.w,h:o.h})}function Ga(e){return e==="m:"?{main:!0}:e.startsWith("c:")?{ref:e.slice(2)}:e.startsWith("e:")?{id:e.slice(2)}:null}function mg(e,t,n){if(t===n)return e;const r=Ga(t),o=Ga(n);if(!r||!o)return e;const s=(l,i)=>{const f=i;return!!f&&f.ref===l.ref&&f.id===l.id};return e.some(l=>{if(!l||typeof l!="object"||l.type!=="connector")return!1;const i=l;return s(r,i.from)&&s(o,i.to)||s(r,i.to)&&s(o,i.from)})?e:[...e,{id:ds(e,"e"),type:"connector",from:r,to:o}]}const fs={fromEnd:"none",toEnd:"arrow"};function pg(e,t,n){let r=!1;const o=e.map(s=>{const c=Br(s);if(!c||!t.has(c)||s.type!=="connector")return s;const l=s;let i=null;for(const f of["fromEnd","toEnd"]){const p=n[f];if(p==null)continue;const y=p===fs[f];(y?!(f in l):l[f]===p)||(i??={...l},y?delete i[f]:i[f]=p)}return i?(r=!0,i):s});return r?o:e}const Lo=(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 hg(e,t,n,r){const o=Ga(r);if(!o)return e;const s=e.find(i=>Br(i)===t);if(!s||s.type!=="connector")return e;const c=n==="from"?s.to:s.from;return Lo(o,s[n])||Lo(o,c)||e.some(i=>{if(Br(i)===t||!i||typeof i!="object"||i.type!=="connector")return!1;const f=i;return Lo(o,f.from)&&Lo(c,f.to)||Lo(o,f.to)&&Lo(c,f.from)})?e:Bl(e,t,{[n]:o})}function gg(e,t,n,r){return e.map(o=>{if(Br(o)!==t)return o;const s={...o};return r?s[n]=r:delete s[n],s})}function Bt(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 Oo(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=Bt(e);return s[t]=n,s}function yg(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 Hl(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 xg(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 Ys(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&&Hl(n,e[o].anchor,e[t].anchor,r);)o++;return o}function bg(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 vg=/^(?:[1-6]|#[0-9a-fA-F]{6})$/;function Zs(e){return typeof e!="string"||!vg.test(e)?null:e.length===1?`var(--amx-cv-${e})`:e}function wg(e,t,n){let r=!1;const o=e.map(s=>{const c=Br(s);if(!c||!t.has(c))return s;const l=s;if(n?l.color===n:!("color"in l))return s;r=!0;const i={...l};return n?i.color=n:delete i.color,i});return r?o:e}const lc=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/;function wa(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 kr(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=lc.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 Qo(e,t){const n=[],r=[];return t.forEach(o=>{if(o.type.name==="amadeusCanvasCard"){let s=kr(e);for(;n.includes(s);)s=kr(e);n.push(s),r.push(o.type.create({...o.attrs,anchor:s},o.content,o.marks))}else r.push(o)}),n.length?{content:wr.fromArray(r),minted:n}:{content:t,minted:n}}const kg=rc("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} -->`)}}})),Cg=rc("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 Sg(e,t,n){if(!t?.rows?.length)return;const r=Array.isArray(e?.children)?e.children:[];if(r.length&&!r.some(f=>f?.position))return;const o=f=>{let p=null;if(f?.type==="html"&&typeof f.value=="string")p=f.value;else if(f?.type==="paragraph"&&Array.isArray(f.children)&&f.children.length===1){const E=f.children[0];E?.type==="html"&&typeof E.value=="string"&&(p=E.value)}if(p==null)return null;const y=lc.exec(p.trim());return y?y[1]:null},s=[];if(r.forEach((f,p)=>{const y=o(f);y&&s.push({id:y,idx:p})}),!s.length)return;const c=new Map;s.forEach((f,p)=>{c.has(f.id)?c.set(f.id,-1):c.set(f.id,p)});const l=new Set,i=[];for(const f of t.rows){if(f.columns.length<2)continue;const p=f.columns.flatMap(_=>_.refs);if(!p.length)continue;const y=p.map(_=>c.get(_)??-1);if(y.some(_=>_<0||l.has(_))||new Set(y).size!==y.length||!y.every((_,X)=>X===0||_===y[X-1]+1))continue;const E=y[y.length-1],D=f.tail!=null&&E+1<s.length&&s[E+1].id===f.tail&&!l.has(E+1)?E+1:null,N=D!=null?s[D].idx:E+1<s.length?s[E+1].idx:r.length,S=[];let A=!0;f.columns.forEach((_,X)=>{const te=c.get(_.refs[0]),B=s[te].idx+1,Y=X+1<f.columns.length?c.get(f.columns[X+1].refs[0]):null,Te=Y!=null?s[Y].idx:N;if(Te<B){A=!1;return}const Ve=r.slice(B,Te);S.push({type:"amadeusColumnCell",anchor:_.refs[0],width:_.width||1,children:Ve.length?Ve:[{type:"paragraph",children:[]}]})}),!(!A||S.length<2)&&(y.forEach(_=>l.add(_)),D!=null&&l.add(D),i.push({from:s[y[0]].idx,to:D!=null?s[D].idx+1:N,node:{type:"amadeusColumnRow",tail:D!=null?f.tail:"",children:S}}))}i.sort((f,p)=>p.from-f.from);for(const f of i)r.splice(f.from,f.to-f.from,f.node);i.length&&n?.()}function Eg(e,t){return[Cl("amadeusColumnsFold",()=>()=>n=>{Sg(n,e(),t)})].flat()}function Mg(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=lc.exec(String(r.attrs.value??"").trim());o&&t.push(o[1])}),t}function zg(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusColumnRow")return;const r=[];n.forEach(o=>{r.push({refs:Mg(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 uc=e=>e.childCount===1&&e.firstChild.type.name==="paragraph"&&e.firstChild.content.size===0;function Xs(e,t){const{paragraph:n,html:r}=e.nodes;return t&&n&&r?[n.create(null,r.create({value:`<!-- a ${t} -->`}))]:[]}function dc(e,t,n,r=!1){const o=[];for(const s of t)o.push(...Xs(e,String(s.attrs.anchor))),r&&uc(s)||s.forEach(c=>o.push(c));return o.push(...Xs(e,n)),o}const Ng=bt(()=>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=>Xs(n.schema,i),c=[];if(n.doc.descendants((i,f,p)=>{if(i.type.name==="amadeusColumnRow"&&p?.type.name==="amadeusColumnCell"){const y=[];return i.forEach(E=>E.forEach(D=>y.push(D))),c.push({from:f,to:f+i.nodeSize,content:y.length?y:[o.create()]}),!1}return!0}),n.doc.forEach((i,f)=>{if(i.type.name!=="amadeusColumnRow")return;const p=[];i.forEach(A=>p.push(A));const y=r?p.filter(A=>!uc(A)):p,E=y.some(A=>!A.attrs.anchor);if(y.length===p.length&&y.length>=2&&!E)return;const D=new Set;n.doc.descendants(A=>{A.type.name==="amadeusColumnCell"&&A.attrs.anchor&&D.add(String(A.attrs.anchor)),A.type.name==="amadeusColumnRow"&&A.attrs.tail&&D.add(String(A.attrs.tail))});const N=A=>{if(A.attrs.anchor)return A;let _="c"+Math.random().toString(36).slice(2,6);for(;D.has(_);)_="c"+Math.random().toString(36).slice(2,6);return D.add(_),A.type.create({...A.attrs,anchor:_},A.content)},S=p.filter(A=>!y.includes(A)).flatMap(A=>s(String(A.attrs.anchor)));if(y.length>=2)c.push({from:f,to:f+i.nodeSize,content:[i.type.create(i.attrs,y.map(N)),...S]});else{const A=[...S,...dc(n.schema,y,String(i.attrs.tail??""))];c.push({from:f,to:f+i.nodeSize,content:A.length?A:[o.create()]})}}),!c.length)return null;let l=n.tr;for(const i of c.sort((f,p)=>p.from-f.from))l=l.replaceWith(i.from,i.to,i.content);return l}}));function $g(e,t,n,r=!1){const{state:o}=e,s=o.selection;if(!(s instanceof ye))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 l=o.schema.nodes.amadeusColumnRow,i=o.schema.nodes.amadeusColumnCell;if(!l||!i)return!1;const f=c.type.name==="list_item"?s.$from.parent.type.create(s.$from.parent.attrs,c):c,p=o.doc.resolve(t);let y=null;if(p.depth>0){let _=-1;for(let X=p.depth;X>=1;X--)if(p.node(X).type===l){_=X;break}if(_<0||_!==1)return!1;y={rowPos:p.before(_),cellIndex:p.index(_)}}const E=new Set,D=()=>{let _=kr(o.doc);for(;E.has(_);)_=kr(o.doc);return E.add(_),_},N=D(),S=D();let A=o.tr;if(r||(A=A.delete(s.from,s.to)),y){const _=A.mapping.map(y.rowPos),X=A.doc.nodeAt(_);if(!X||X.type!==l)return!1;const te=n==="left"?y.cellIndex:y.cellIndex+1;let B=_+1;for(let Y=0;Y<Math.min(te,X.childCount);Y++)B+=X.child(Y).nodeSize;A=A.insert(B,i.create({anchor:S,width:1},f))}else{const _=A.mapping.map(t),X=A.doc.nodeAt(_);if(!X)return!1;const te=n==="left"?[i.create({anchor:S,width:1},f),i.create({anchor:N,width:1},X)]:[i.create({anchor:N,width:1},X),i.create({anchor:S,width:1},f)];A=A.replaceWith(_,_+X.nodeSize,l.create({tail:D()},te))}return A.setMeta("amxColumns",!0),e.dispatch(A.scrollIntoView()),!0}function Ag(e,t,n=!1){const{state:r}=e,o=r.selection;if(!(o instanceof ye))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 l=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),l),i.setMeta("amxColumns",!0),e.dispatch(i.scrollIntoView()),!0}function Tg(e,t,n=!1){const{state:r}=e,o=r.selection;if(!(o instanceof ye))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),l=c.parent;if(l.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,f=l.childCount===1&&l.firstChild.type.name==="paragraph"&&l.firstChild.content.size===0;let p=r.tr;return n||(p=p.delete(o.from,o.to)),f?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 Vl(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,l=o.schema.nodes.paragraph;if(!s||!c||!l)return!1;const i=new Set,f=()=>{let E=kr(o.doc);for(;i.has(E);)E=kr(o.doc);return i.add(E),E},p=s.create({tail:f()},[c.create({anchor:f(),width:1},r),c.create({anchor:f(),width:1},l.create())]);let y=o.tr.replaceWith(t,n,p);return y=y.setSelection(Ae.near(y.doc.resolve(t+p.nodeSize-3))),y.setMeta("amxColumns",!0),y.setMeta("amxColumnsKeepEmpty",!0),e.dispatch(y.scrollIntoView()),!0}function ql(e,t,n,r=!1){const o=e.doc.nodeAt(t);if(!o||o.type.name!=="amadeusColumnCell"||!(r||uc(o)))return null;const s=e.doc.resolve(t),c=s.parent;if(c.type.name!=="amadeusColumnRow")return null;const l=s.before(),i=s.after(),f=s.index(),p=[];c.forEach((X,te,B)=>{B!==f&&p.push(X)});const y=Xs(e.schema,String(o.attrs.anchor));if(p.length>=2){const X=e.tr.delete(t,t+o.nodeSize);return y.length&&X.insert(X.mapping.map(i),y),X.setSelection(No.near(X.doc.resolve(Math.min(t,X.doc.content.size)),n)),X.scrollIntoView()}const E=[...dc(e.schema,p,String(c.attrs.tail??"")),...y],D=e.tr.replaceWith(l,i,E),N=p[0],S=n<0?f>0:f>=p.length,A=S?N?.lastChild:N?.firstChild;let _=l;for(const X of E){if(X===A){D.setSelection(No.near(D.doc.resolve(S?_+X.nodeSize-1:_+1),S?-1:1));break}_+=X.nodeSize}return D.scrollIntoView()}function jg(e,t){const{state:n}=e,r=n.doc.nodeAt(t);if(!r||r.type.name!=="amadeusColumnRow")return!1;const o=[];r.forEach(y=>o.push(y));const s=dc(n.schema,o,String(r.attrs.tail??""),!0),c=s.length?s:[n.schema.nodes.paragraph.create()],l=n.selection;let i=null;n.doc.nodesBetween(t,t+r.nodeSize,(y,E,D)=>i||D?.type.name!=="amadeusColumnCell"?!i:(l.from>=E&&l.from<E+y.nodeSize&&(i={node:y,off:l.from-E,nodeSel:l instanceof ye&&l.from===E}),!1));const f=n.tr.replaceWith(t,t+r.nodeSize,c);let p=t;for(const y of c){const E=i;if(E&&y===E.node){f.setSelection(E.nodeSel?ye.create(f.doc,p):No.near(f.doc.resolve(p+E.off)));break}p+=y.nodeSize}return e.dispatch(f.scrollIntoView()),!0}const Rg=[kg,Cg,Ng].flat();vn({"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 (with annotations)"},"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 Wl(){const[,e]=k.useState(0);return k.useEffect(()=>fl(()=>e(t=>t+1)),[]),we}const Lg=Qd(()=>_u(()=>import("./PdfAnnotator-D79ip27w.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]),import.meta.url).then(e=>({default:e.PdfAnnotator}))),Qr=()=>{},Yl=/^!\[\[([^\]\n]+)\]\]$/,Dg=/\.(png|jpe?g|gif|webp|svg|avif|bmp)$/i,Ig=/\.[a-z0-9]{1,8}$/i,Pg=/\.db$/i,Fg=/\.pdf$/i,Og=/^https?:\/\/\S+$/i;function Mo(e){if(e.type.name==="code_block")return e.attrs.language===Nm?e.textContent.trim()?{k:"sketch",src:e.textContent}:null:e.attrs.language!=="forsion-button"||!bl(Xl(e.textContent))?null:{k:"button",src:e.textContent};if(e.type.name!=="paragraph")return null;const t=e.textContent.trim(),n=Yl.exec(t);if(!n)return Og.test(t)?{k:"bookmark",url:t}:null;const r=n[1],[o,s]=r.split("|"),c=o.trim();if(Dg.test(c))return null;const l=Pu(r);if(l)return{k:"web",url:l,w:sa(r)};if(!c.includes("#")&&Pg.test(c))return{k:"db",name:c,view:s?.trim()||null};if(!c.includes("#")&&Fu(c))return{k:"draw",target:c};const i=Fa.getState().embedRenderers;if(Vc(i,r.trim()))return{k:"plugin",target:r.trim()};const f=c.includes("#")?Lc(c)?.target??null:c;if(f&&Vc(i,f))return{k:"plugin",target:f};if(Zd(c))return{k:"note",target:r};const p=Lc(c);return p?{k:"file",name:p.target,fileKind:Ou.test(p.target)?"video":"audio",loc:p.loc,badAnchor:c.includes("#")&&!p.loc,w:sa(r)}:!c.includes("#")&&Ig.test(c)?{k:"file",name:c,fileKind:Fg.test(c)?"pdf":"other",w:sa(r)}:{k:"note",target:r}}function _g({name:e,fileKind:t,pagePath:n,loc:r,badAnchor:o,insertAfter:s}){const c=Wl(),l=Bn(D=>D.files),i=Bn(D=>D.openWikiLink),[f,p]=k.useState(!0),y=t==="pdf"?vl(e,l,n):null;if(t==="other")return!/\.[a-z0-9]+\.md$/i.test(e)&&!Wc()?m.jsxs("div",{className:"embed-file",children:[m.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),m.jsx("span",{className:"embed-file-name",children:e})]}):m.jsxs("button",{className:"embed-file",onClick:()=>{/\.[a-z0-9]+\.md$/i.test(e)?i(e,n):bn.openAttachment(n,e)},title:/\.[a-z0-9]+\.md$/i.test(e)?c("uembed.openInTab"):c("uembed.openWithSystem"),children:[m.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:"📄"}),m.jsx("span",{className:"embed-file-name",children:e}),m.jsx("span",{className:"embed-file-open",children:c("uembed.open")})]});const E=dl(e);return m.jsxs("div",{className:"embed-media",children:[m.jsxs("div",{className:"embed-media-head",children:[m.jsx("span",{className:"embed-file-ic","aria-hidden":!0,children:t==="pdf"?"📕":t==="video"?"🎬":"🎵"}),m.jsx("span",{className:"embed-file-name",children:e}),r&&m.jsxs("span",{className:"embed-media-at",title:c("uembed.startAt"),children:["@",Dc(r.at),r.to?`–${Dc(r.to)}`:""]}),o&&m.jsx("span",{className:"embed-media-warn",title:c("uembed.badAnchorTip"),children:c("uembed.badAnchor")}),m.jsx("button",{className:"embed-media-btn",onClick:()=>p(D=>!D),children:c(f?"uembed.collapse":"uembed.expand")}),(t==="pdf"||Wc())&&m.jsx("button",{className:"embed-media-btn",title:c(t==="pdf"?"uembed.openPdfInTab":"uembed.openWithSystem"),onClick:()=>{t==="pdf"?i(e,n):bn.openAttachment(n,e)},children:c("uembed.open")})]}),f&&t==="pdf"&&(y?m.jsx("div",{className:"embed-pdf embed-pdf-live",children:m.jsx(k.Suspense,{fallback:m.jsx("div",{className:"embed-pdf-loading",children:c("uembed.loadingPdf")}),children:m.jsx(Lg,{pdfPath:y,readOnly:!0})})}):m.jsx("iframe",{className:"embed-pdf",src:E,title:e})),f&&(t==="video"||t==="audio")&&m.jsx(lf,{kind:t,url:E,name:e,pagePath:n,loc:r??null,insertAfter:s})]})}function Bg({target:e,pagePath:t,readOnly:n}){const r=Wl(),o=Bn(_=>_.openWikiLink),s=Bn(_=>_.loadPage),c=Bn(_=>_.pages),l=Bn(_=>_.linkGraphVersion),[i,f]=k.useState("loading"),{note:p,subpath:y}=Vu(e),E=y?`${p}#${y}`:p;k.useEffect(()=>{let _=!0;return f("loading"),Promise.resolve(E?bn.resolveEmbed?.(E,t)??null:null).then(X=>{_&&f(X)}).catch(()=>{_&&f(null)}),()=>{_=!1}},[E,t,l]);const D=!n&&i===null&&!!p&&!ms(p,c,t),N=()=>{Bn.getState().openWikiLink(p,t),Bn.getState().pendingWikiCreate?.name===p&&Bn.getState().confirmWikiCreate()},A=(i&&i!=="loading"?cf(i.type):void 0)?.Editor;return m.jsxs("div",{className:"embed-body",children:[m.jsxs("div",{className:"embed-head",children:[m.jsx("span",{className:"embed-badge",title:r("uembed.crossNote"),children:r("uembed.badge")}),i&&i!=="loading"&&m.jsxs("button",{className:"embed-src",onClick:()=>{s(i.owner)},title:r("uembed.editAtSource"),children:[qu(i.owner)," ↗"]})]}),i==="loading"?m.jsx("div",{className:"embed-loading",children:r("uembed.resolving")}):i&&A?m.jsx(A,{blockId:"uembed",content:i.content,pagePath:i.owner,readOnly:!0,onChange:Qr,onInsertAfter:Qr,onDeleteEmpty:Qr,onMergePrev:Qr,onArrowOut:Qr,onMoveDir:Qr,focusPlace:null,onFocused:Qr,requestSelfFocus:Qr,onOpenWiki:(_,X)=>o(_,i.owner,X),getPageNames:()=>c}):m.jsxs("div",{className:"embed-missing",children:[r("uembed.embedMissing"),m.jsx("code",{children:e}),D&&m.jsx("button",{type:"button",className:"embed-media-btn embed-create",title:r("uembed.createTip",{name:p}),onClick:N,children:r("uembed.create")})]})]})}function Kg({kind:e,pagePath:t,replaceText:n,insertAfter:r,readOnly:o=!1}){const s=o?()=>{}:n;switch(e.k){case"db":return m.jsx(af,{target:e.name,pagePath:t,initialView:e.view??void 0,readOnly:o,onViewChange:c=>s(c?`![[${e.name}|${c}]]`:`![[${e.name}]]`)});case"draw":return m.jsx(sf,{target:e.target,pagePath:t,readOnly:o});case"plugin":return m.jsx(of,{target:e.target,pagePath:t});case"file":return m.jsx(_g,{name:e.name,fileKind:e.fileKind,pagePath:t,loc:e.loc,badAnchor:e.badAnchor,insertAfter:o?()=>{}:r});case"note":return m.jsx(Bg,{target:e.target,pagePath:t,readOnly:o});case"bookmark":return o?m.jsx(qc,{url:e.url}):m.jsx(qc,{url:e.url,onChangeUrl:c=>n(c),onEmbed:()=>n(`![[${Hu(e.url)}]]`)});case"web":return m.jsx(rf,{url:e.url,toCard:()=>s(e.url)});case"button":{const c=bl(Xl(e.src));return c?m.jsx(tf,{spec:c,readOnly:o,onChange:l=>s(Hg(nf(l)))}):m.jsx("span",{})}case"sketch":return m.jsx($m,{items:[{callId:"note-sketch",html:e.src}]})}}function Xl(e){return"```forsion-button\n"+e+"\n```"}function Hg(e){const t=/^```forsion-button[ \t]*\r?\n([\s\S]*?)\r?\n?```$/.exec(e.trim());return t?t[1]:e}const Ei=(e,t)=>e.k==="db"?`db:${e.name}`:`${e.k}:${t}`;function Vg(e,t,n){let r=!0;return e.mapping.maps.forEach((o,s)=>{const c=e.mapping.slice(s+1);o.forEach((l,i,f,p)=>{(c.map(f,-1)<t||c.map(p,1)>n)&&(r=!1)})}),r}function qg(e){return[bt(()=>{const n=new jn("UNIFIED_EMBED_LAYER"),r=new Map,o=(c,l,i,f,p=null)=>{const y=[],E=new Map,D=(N,S)=>{const A=Mo(N);if(!A)return;const _=Ei(A,N.textContent),X=E.get(_)??0;if(E.set(_,X+1),f===S&&i>S&&l<S+N.nodeSize||p===S)return;const te=`${_}#${X}`,B=r.get(te);B&&B.text!==N.textContent&&(B.text=N.textContent,B.render(A)),y.push(ir.inline(S+1,S+N.nodeSize-1,{class:"wikilink-src-hidden"})),y.push(ir.node(S,S+N.nodeSize,{class:"unified-embed-host"})),y.push(ir.widget(S+1,Y=>{const Te=r.get(te);if(Te)return Te.refs++,Te.dom;const Ve=document.createElement("div");Ve.className="unified-embed",Ve.contentEditable="false";const h=Ee=>{let ve=0,Ce=null;return Ee.state.doc.descendants((st,Z)=>{if(Ce)return!1;const oe=Mo(st);return oe&&Ei(oe,st.textContent)===_?ve===X?(Ce={at:Z,size:st.nodeSize},!1):(ve++,!1):!0}),Ce};Ve.addEventListener("mousedown",Ee=>{if(Ee.button!==0)return;const ve=Ee.target;if(ve!==Ve&&ve.parentElement!==Ve||ve.closest('.amx-src-btn, .amx-img-resize, button, a, input, textarea, select, iframe, webview, video, audio, [contenteditable="true"]'))return;const Ce=s;if(!Ce)return;const st=h(Ce);st&&(Ee.preventDefault(),Ee.stopPropagation(),Ce.dispatch(Ce.state.tr.setSelection(ye.create(Ce.state.doc,st.at))),Ce.focus())});const Se=Ee=>{const ve=s;if(!ve)return;const Ce=h(ve);Ce&&ve.dispatch(ve.state.tr.insertText(Ee,Ce.at+1,Ce.at+Ce.size-1))},lt=A.k==="web"||A.k==="file"&&A.fileKind!=="other",ne=A.k==="web"||A.k==="file"?A.w:void 0;ne&&(Ve.style.width=`${ne}px`);const de=document.createElement("div");if(de.className="unified-embed-body",Ve.appendChild(de),lt){const Ee=Yl.exec(N.textContent.trim())?.[1];Ee!==void 0&&ef(Ve,Ve,ve=>Se(`![[${Bu(Ee,ve)}]]`))}const ce=zm.createRoot(de),be=Ee=>ce.render(m.jsx(Ku,{children:m.jsx(Kg,{kind:Ee,pagePath:e.path,readOnly:!!e.readOnly,insertAfter:ve=>{const Ce=s;if(!Ce)return;const st=h(Ce);if(!st)return;const Z=Ce.state.schema.nodes.paragraph;if(!Z)return;const oe=ve.split(/\n{2,}/).map(je=>Z.create(null,je?Ce.state.schema.text(je):null));Ce.dispatch(Ce.state.tr.insert(st.at+st.size,oe))},replaceText:Se})}));return be(A),Sm(Ve,Y,()=>{const Ee=s;if(!Ee)return;const ve=h(Ee);if(!ve)return;const Ce=Ee.state.tr.setSelection(Ae.near(Ee.state.doc.resolve(ve.at+1)));Ce.setMeta(n,{sourcePos:ve.at}),Ee.dispatch(Ce),Ee.focus()}),Ve.querySelector(".amx-src-btn")?.classList.add("amx-src-btn--block"),r.set(te,{root:ce,dom:Ve,text:N.textContent,render:be,refs:1}),Ve},{key:te,side:-1,ignoreSelection:!0,stopEvent:Y=>/^(key|composition|beforeinput|input|paste|cut|copy)/.test(Y.type),destroy:()=>{const Y=r.get(te);Y&&(Y.refs--,!(Y.refs>0)&&queueMicrotask(()=>{Y.refs>0||r.get(te)!==Y||(r.delete(te),Y.root.unmount())}))}}))};return c.descendants((N,S)=>(D(N,S),!0)),oo.create(c,y)};let s=null;return new Ht({key:n,view:c=>(s=c,{destroy:()=>{s=null,queueMicrotask(()=>{if(!s){for(const[,l]of r)l.root.unmount();r.clear()}})}}),state:{init:(c,l)=>({decos:o(l.doc,l.selection.from,l.selection.to,null),sourcePos:null,pendingPos:null}),apply:(c,l,i,f)=>{const p=c.getMeta(n);let y=l.sourcePos;if(y!=null&&c.docChanged&&(y=c.mapping.map(y)),p&&typeof p.sourcePos=="number")y=p.sourcePos;else if(y!=null&&c.selectionSet){const D=f.doc.nodeAt(y);(!D||f.selection.to<=y||f.selection.from>=y+D.nodeSize)&&(y=null)}let E=l.pendingPos;if(E!=null&&c.docChanged&&(E=c.mapping.map(E,-1)),p?.commit)E=null;else if(c.docChanged&&f.selection.empty&&!/^(paste|drop)$/.test(String(c.getMeta("uiEvent")??""))){const D=f.selection.$head,N=D.depth>0?D.before():-1;N>=0&&D.parent.type.name==="paragraph"&&Mo(D.parent)?.k==="bookmark"&&Vg(c,N+1,N+D.parent.nodeSize-1)&&(E=N)}if(E!=null){const D=f.doc.nodeAt(E),{from:N,to:S}=f.selection;(!D||D.type.name!=="paragraph"||S<E+1||N>E+D.nodeSize-1)&&(E=null)}return!c.docChanged&&!c.selectionSet&&!p&&E===l.pendingPos?{sourcePos:y,pendingPos:E,decos:l.decos.map(c.mapping,c.doc)}:{sourcePos:y,pendingPos:E,decos:o(f.doc,f.selection.from,f.selection.to,y,E)}}},props:{decorations(c){return n.getState(c)?.decos??null},handleDOMEvents:{blur:c=>(n.getState(c.state)?.pendingPos!=null&&c.dispatch(c.state.tr.setMeta(n,{commit:!0})),!1)}}})})].flat()}const Wg=[bt(()=>Fr({Enter:od,"Shift-Enter":rd,"Mod-Enter":nd}))].flat();function Qs(e){let t=e.depth;for(;t>=1&&!["doc","amadeusColumnCell"].includes(e.node(t-1).type.name);)t--;return t}function fc(e){if(!e)return!1;const t=e.type.name;return t==="code_block"||t==="hr"||t==="horizontal_rule"||t==="table"?!0:Mo(e)!=null}function Yg(e){if(!e)return!1;const t=e.type.name;return t==="hr"||t==="horizontal_rule"?!0:Mo(e)!=null}function Kr(e){for(let t=e.depth;t>=1;t--)if(e.node(t).type.name==="list_item")return t;return null}function vs(e,t){return Fs(e,t)!=null?!0:vm(e).some(n=>t>n.start&&t<n.after)}function Xg(e){let t=0;for(let n=e.depth;n>=1;n--)e.node(n).type.name==="list_item"&&t++;return t}function Ul(e){for(let t=e.depth;t>=1;t--)if(e.node(t).type.name==="blockquote")return t;return null}function Ko(...e){return(t,n,r)=>e.some(o=>o(t,n,r))}const Ug=(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(Yo(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(Wo,{toggle:o}),t?.(c.scrollIntoView()),!0},Gl=(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),l=e.tr.insert(c,o.create());return l.setSelection(Ae.near(l.doc.resolve(c+1))),t?.(l.scrollIntoView()),!0}const s=e.tr.split(n.pos,1,[{type:o}]);return t?.(s.scrollIntoView()),!0},Gg=(e,t)=>{const n=e.selection;if(!(n instanceof ye)||!n.node.isTextblock||Mo(n.node)!=null)return!1;const r=e.tr.setSelection(Ae.near(e.doc.resolve(n.to-1),-1));return t?.(r.scrollIntoView()),!0},Jg=(e,t,n)=>{const{$from:r,empty:o}=e.selection;if(!o||!n||!t)return!1;const s=id(r);return!s||!ld(r.parent.type.name,s)?!1:ud(n,s)},Zg=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parent.content.size!==0||Kr(n)==null)return!1;const o=e.schema.nodes.list_item;return o?ml(o)(e,t):!1},Qg=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r)return!1;const o=Kr(n);if(o==null||o!==n.depth-1||n.node(o).childCount<2||!oc(e,n.before(o)))return!1;const c=e.schema.nodes.list_item,l=e.schema.nodes.paragraph;if(!c||!l)return!1;const i=e.doc.slice(n.pos,n.end()).content,f=c.createAndFill(null,l.create(null,i));if(!f)return!1;let p=e.tr.delete(n.pos,n.end());const y=p.mapping.map(n.after(o));return p=p.insert(y,f),p.setSelection(Ae.near(p.doc.resolve(y+2))),t?.(p.scrollIntoView()),!0},ey=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset===0)return!1;const o=Kr(n);if(o==null||o!==n.depth-1)return!1;const s=n.node(o);if(s.childCount<2||oc(e,n.before(o)))return!1;const c=s.child(1);if(!/_list$/.test(c.type.name))return!1;const l=e.schema.nodes.list_item,i=e.schema.nodes.paragraph;if(!l||!i)return!1;const f=n.pos,p=n.end(),y=e.doc.slice(f,p).content,E=n.before(o)+1+s.child(0).nodeSize+1,D=l.createAndFill(null,i.create(null,y));if(!D)return!1;let N=e.tr.delete(f,p);const S=N.mapping.map(E);return N=N.insert(S,D),N.setSelection(Ae.near(N.doc.resolve(S+2))),t?.(N.scrollIntoView()),!0},ty=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r)return!1;const o=ec(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},ny=(e,t,n)=>{const{$from:r,empty:o}=e.selection,s=Kr(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 y=c.createAndFill({...r.node(s).attrs,checked:!1});if(!y)return!1;if(!t)return!0;t(e.tr.insert(r.before(s),y).scrollIntoView());const E=n?n.root.getSelection?.():null;if(E&&E.rangeCount){const D=E.getRangeAt(0);E.removeAllRanges(),E.addRange(D)}return!0}if(!t)return Da(c)(e);let l=null;if(!Da(c)(e,y=>{l=y}))return!1;const i=l;if(!i)return!1;const f=i.selection.$from,p=Kr(f);return p!=null&&f.node(p).attrs.checked===!0&&i.setNodeMarkup(f.before(p),void 0,{...f.node(p).attrs,checked:!1}),t(i),!0},ry=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},Jl=(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 ry(Em(n.parent)).some(([l,i])=>s>=l+2&&c<=i-2)?(t?.(e.tr.replaceSelectionWith(o.create({isInline:!0}),!1).scrollIntoView()),!0):!1},oy=Ko(Ug,Gl,Gg,Jl,Jg,Zg,Qg,ey,ny,ty),sy=(e,t)=>{const{$from:n}=e.selection,r=Kr(n),o=Ul(n);if(r!=null&&(o==null||r>o)&&n.node(r).attrs.checked!=null){const p=ad(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&&Kr(n)!=null)return Da(s)(e,t);const c=e.schema.nodes.paragraph,l=Qs(n);if(!c||l<1)return!1;const i=n.after(l),f=e.tr.insert(i,c.create());return f.setSelection(Ae.near(f.doc.resolve(i+1))),t?.(f.scrollIntoView()),!0},ay=(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},cy=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==0)return!1;const o=Ul(n);if(o==null)return!1;if(n.index(o)===0){const E=n.before(o),D=e.doc.nodeAt(E);return!D||!ye.isSelectable(D)?!1:(t?.(e.tr.setSelection(ye.create(e.doc,E))),!0)}const c=n.before(o+1),l=n.after(o+1),i=n.after(o),f=e.doc.nodeAt(c);if(!f)return!1;let p=e.tr.delete(c,l);const y=p.mapping.map(i);return p=p.insert(y,f),p.setSelection(Ae.near(p.doc.resolve(y+1))),t?.(p.scrollIntoView()),!0},iy=(e,t,n)=>{const{$from:r,empty:o}=e.selection;return!o||r.parentOffset!==0||!n||Kr(r)==null?!1:cd(n)},ly=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==0)return!1;const o=Qs(n);if(o<1||o!==n.depth)return!1;const s=n.before(o),l=e.doc.resolve(s).nodeBefore;if(!fc(l)||!l)return!1;const i=s-l.nodeSize;let f=e.tr;n.parent.content.size===0&&(f=f.delete(s,n.after(o)));const p=f.doc.nodeAt(i);return!p||!ye.isSelectable(p)||vs(e,i)?!1:(f=f.setSelection(ye.create(f.doc,i)),t?.(f.scrollIntoView()),!0)},uy=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==0)return!1;const o=ec(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},Ja=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=ql(t,r.before(-1),e);return s?(n?.(s),!0):!1},dy=Ko(Ja(-1),ay,cy,iy,uy,ly),fy=(e,t,n)=>{const{$from:r,empty:o}=e.selection;if(!o||r.parentOffset!==0)return!1;if(ec(r)){const l=r.before(r.depth);return t?.(e.tr.setNodeMarkup(l,void 0,{...r.parent.attrs,indent:0}).scrollIntoView()),!0}const c=e.schema.nodes.list_item;if(!c||Kr(r)==null)return!1;if(!t||!n)return!0;for(let l=0;l<32&&!(Xg(n.state.selection.$from)<=1||!ml(c)(n.state,i=>n.dispatch(i)));l++);return!0},Mi=(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 Yo(e,o)==null?!1:(t?.(e.tr.setMeta(Wo,{toggle:o})),!0)},zi=(e,t)=>{const{$from:n,empty:r}=e.selection;if(!r||n.parentOffset!==n.parent.content.size)return!1;const o=Qs(n);if(o<1)return!1;const s=n.after(o),c=e.doc.resolve(s).nodeAfter;return!c||!fc(c)||!ye.isSelectable(c)||vs(e,s)?!1:(t?.(e.tr.setSelection(ye.create(e.doc,s)).scrollIntoView()),!0)},my=/^\[![\w-]+\]/,Ni=(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 S=N.depth;S>0;S--)if(N.node(S).type.name==="table")return!0;return!1};if(o(n))return!1;const s=n.after(),c=No.findFrom(e.doc.resolve(s),1,!0);if(!(c instanceof Ae))return!1;const l=c.$from;if(l.parentOffset!==0||!l.parent.isTextblock||l.parent.type.name==="code_block"||o(l)||l.depth===n.depth&&l.before()===s||vs(e,l.pos))return!1;const i=N=>{for(let S=N.depth;S>0;S--)if(N.node(S).type.spec.isolating)return N.before(S);return-1};if(i(n)!==i(l))return!1;let f=!1;if(e.doc.nodesBetween(s,l.before(),(N,S)=>(S>=s&&S+N.nodeSize<=l.before()&&(N.isLeaf||N.isTextblock)&&(f=!0),!f)),f)return!1;const p=l.depth>=2&&l.node(-1).type.name==="blockquote"&&l.index(-1)===0?l.before(-1):null;if(p!=null&&my.test(l.parent.textContent)){const N=e.doc.nodeAt(p);return!N||!ye.isSelectable(N)?!1:(t?.(e.tr.setSelection(ye.create(e.doc,p)).scrollIntoView()),!0)}const y=n.parent.textContent+l.parent.textContent,E=e.tr.delete(n.pos,l.pos),D=E.doc.resolve(E.mapping.map(n.pos));return!D.parent.isTextblock||D.parent.textContent!==y||E.doc.textContent!==e.doc.textContent?!1:(t?.(E.setSelection(Ae.create(E.doc,D.pos)).scrollIntoView()),!0)};function $i(e){return(t,n,r)=>{const o=t.selection;if(!o.empty||!r||!r.endOfTextblock(e))return!1;const s=o.$from,c=Qs(s);if(c<1)return!1;const l=e==="down"?s.after(c):s.before(c),i=e==="down"?t.doc.resolve(l).nodeAfter:t.doc.resolve(l).nodeBefore;if(!Yg(i)||!i)return!1;const f=e==="down"?l:l-i.nodeSize,p=t.doc.nodeAt(f);return!p||!ye.isSelectable(p)||vs(t,f)?!1:(n?.(t.tr.setSelection(ye.create(t.doc,f)).scrollIntoView()),!0)}}function Ai(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 l=o.node(-1);if(o.index(-1)!==l.childCount-1)return!1;const i=t.schema.nodes.paragraph,f=o.after();if(!i||!l.canReplaceWith(o.index(-1)+1,o.index(-1)+1,i))return!1;if(!n)return!0;const p=t.tr.insert(f,i.create());return n(p.setSelection(Ae.create(p.doc,f+1)).scrollIntoView()),!0}}const py=(e,t)=>e.selection.$from.parent.type.name!=="code_block"?!1:(t?.(e.tr.insertText(`
|
|
34
|
-
`).scrollIntoView()),!0);function Ti(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 Mo(o)!=null?!ye.isSelectable(o)||vs(t,s)?!1:(n?.(t.tr.setSelection(ye.create(r,s)).scrollIntoView()),!0):o.type.name==="code_block"?(n?.(t.tr.setSelection(Ae.create(r,e==="up"?s+1:s+o.nodeSize-1)).scrollIntoView()),!0):!1}}const hy={"(":")","[":"]","{":"}","<":">",'"':'"',"'":"'","`":"`","(":")","【":"】","「":"」","《":"》","“":"”","‘":"’"},gy=bt(e=>new Ht({props:{handleTextInput:(t,n,r,o)=>{const s=hy[o];if(!s||n===r)return!1;const c=t.state.selection;if(!(c instanceof Ae)||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(uf).call(sd.key);const l=t.state.tr.insertText(s,r).insertText(o,n);return l.setSelection(Ae.create(l.doc,n+1,r+1)),t.dispatch(l.scrollIntoView()),!0}}}));function ka(e){const t=e.selection;if(!(t instanceof ye)||!t.node.isBlock)return null;const n=t.node,r=e.tr;if(n.type.name==="code_block")return r.setSelection(Ae.create(r.doc,t.to-1));if(n.type.name==="table"){const c=No.near(r.doc.resolve(t.from+1),1);return!(c instanceof Ae)||c.from>=t.to?null:r.setSelection(Ae.create(r.doc,c.$from.end()))}if(!fc(n)&&!n.isLeaf){const c=No.near(r.doc.resolve(t.to-1),-1);if(c instanceof Ae&&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(Ae.create(r.doc,t.to+1)))}const yy=bt(()=>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=ka(e.state);return r&&e.dispatch(r.scrollIntoView()),!1},compositionstart:e=>{if(!e.editable)return!1;const t=ka(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=ka(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}}}})),ji=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),xy=[Wg,yy,gy,bt(()=>Fr({Enter:oy,"Shift-Enter":Ko(Gl,py,Jl),"Mod-Enter":sy,Backspace:dy,"Mod-Backspace":fy,Delete:Ko(Ja(1),Mi,zi,Ni),...ji?{"Ctrl-d":Ko(Ja(1),Mi,zi,Ni)}:{},ArrowUp:$i("up"),ArrowDown:Ko(Ai("down"),$i("down")),ArrowRight:Ai("right"),...ji?{"Meta-ArrowUp":Ti("up"),"Meta-ArrowDown":Ti("down")}:{}}))].flat();vn({"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 by(e,t,n,r){const{schema:o}=e,s=o.nodes.paragraph;if(!s)return null;const c=s.create(null,o.text("/"));let l=null;t.type.name==="list_item"?l=n:/_list$/.test(t.type.name)&&t.firstChild?.type.name==="list_item"&&(l=n+1);const i=l==null?null:e.doc.nodeAt(l);if(i&&l!=null){const p={...i.attrs,...i.attrs.checked!=null?{checked:!1}:{}},y=i.type.createAndFill(p,c);if(y){const E=r?l:l+i.nodeSize;return{at:E,node:y,caret:E+3}}}const f=r?n:n+t.nodeSize;return{at:f,node:c,caret:f+2}}function Do(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 Ri(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 Io(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"||Ri(o))&&(n=r)}return n?t(n):{x:0,y:0}}for(let n=e.parentElement;n;n=n.parentElement)if(Ri(getComputedStyle(n)))return t(n);return{x:0,y:0}}const Ca=(e,t)=>{if(!t)return!1;const n=t.type.name;return!(n==="amadeusColumnRow"||n==="amadeusColumnCell"||mf(r=>r.type.name==="table"||r.type.name==="blockquote")(e))};function es(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=l=>{const i=r.depth>=1&&r.index(r.depth)===0&&!["amadeusColumnCell","amadeusCanvasCard"].includes(r.node(r.depth).type.name);if(!(l||i)||r.depth<1)return;const f=r.before(r.depth);o=e.state.doc.nodeAt(f),s=e.nodeDOM(f),r=e.state.doc.resolve(f),Ca(r,o)||c(!0)};if(c(!Ca(r,o)),!o||!Ca(r,o)||!(s instanceof HTMLElement))return null;if(r.depth>=1&&r.node(r.depth).type.name==="amadeusCanvasCard"){const l=r.before(r.depth),i=e.nodeDOM(l);if(i instanceof HTMLElement){const f=i.firstElementChild?.getBoundingClientRect(),p=i.lastElementChild?.getBoundingClientRect();if(f&&t.y<f.top||p&&t.y>p.bottom){const y=e.state.doc.nodeAt(l);if(y)return{node:y,pos:l,el:i}}}}return{node:o,pos:r.pos,el:s}}catch{return null}}function Li(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(ye.isSelectable(r)&&!(r.type.name==="paragraph"&&n>1))return t.before(n)}return null}function vy(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 wy(e){let t=null,n=null;const r=new jn("amx-block-selection-mode");let o=null,s=null;const c=b=>(s&&s.isConnected||(s=document.createElement("div"),s.className="unified-drop-vline",s.style.display="none",(b.dom.parentElement??document.body).appendChild(s)),s),l=(b,M,R)=>{const T=c(b),F=Do(b.dom),V=Io(T),G=M.getBoundingClientRect(),q=(R==="left"?G.left-6:G.right+3)-V.x;T.style.display="block",T.style.height=`${G.height/F}px`,T.style.transform=`translate(${Math.round(q/F)}px, ${Math.round((G.top-V.y)/F)}px)`},i=()=>{s&&(s.style.display="none")},f=28,p=b=>/Mac/i.test(navigator.platform)?b.altKey:b.ctrlKey,y=b=>{const M=b.state.selection;if(!(M instanceof Ae)||M.empty||M.$from.sameParent(M.$to))return null;const R=V=>{let G=V.depth;for(;G>=1&&!["doc","amadeusColumnCell"].includes(V.node(G-1).type.name);)G--;return G},T=R(M.$from),F=R(M.$to);return T<1||F<1||M.$from.node(T-1)!==M.$to.node(F-1)?null:{from:M.$from.before(T),to:M.$to.after(F)}},E=(b,M,R)=>{if(R.type.name!=="paragraph")return null;const T=b.state.doc.resolve(M),F=T.parent;if(!["doc","amadeusColumnCell"].includes(F.type.name))return null;const V=Number(R.attrs.indent??0),G=T.index();let q=M+R.nodeSize,U=0;for(let O=G+1;O<F.childCount;O++){const ge=F.child(O);if(ge.type.name!=="paragraph"||Number(ge.attrs.indent??0)<=V)break;q+=ge.nodeSize,U++}return U?{from:M,to:q}:null};let D=null;const N=(b,M,R,T,F)=>{Fo(b,M,{from:R.from,to:R.to,newStart:T,copy:F}),Jo(b,M,{from:R.from,to:R.to,newStart:T}),D===R.from&&M.doc.nodeAt(T)?.type.name==="heading"&&(M.setSelection(ye.create(M.doc,T)),D=null)},S=(b,M)=>{const{state:R}=b,T=R.doc.content.size,F=y(b);if(F){if(!M&&F.to===T)return!0;let O=R.doc.slice(F.from,F.to).content;if(M){const Ie=Qo(R.doc,O);O=Ie.content,Ie.minted.length&&e.onCardsMinted?.(Ie.minted)}let ge=R.tr;M||(ge=ge.delete(F.from,F.to));const De=ge.mapping.map(T);return ge=ge.insert(De,O),N(R,ge,F,De,M),ge.setMeta("amxColumns",!0),b.dispatch(ge.scrollIntoView()),!0}const V=R.selection;if(!(V instanceof ye))return!1;if(!M&&V.to===T)return!0;const G=V.node,q=G.type.name==="list_item"?V.$from.parent.type.create(V.$from.parent.attrs,G):G;let U=R.tr;return M||(U=U.delete(V.from,V.to)),U=U.insert(U.mapping.map(T),q),U.setMeta("amxColumns",!0),b.dispatch(U.scrollIntoView()),!0},A=(b,M,R)=>{const T=y(b);if(!T)return!1;const F=se(b,M.clientY);if(!F)return!1;const V=F.el.getBoundingClientRect(),G=M.clientY>V.top+V.height/2?F.pos+F.node.nodeSize:F.pos;if(G>=T.from&&G<=T.to)return!0;let q=b.state.doc.slice(T.from,T.to).content;if(R){const ge=Qo(b.state.doc,q);q=ge.content,ge.minted.length&&e.onCardsMinted?.(ge.minted)}Rt(b,G);let U=b.state.tr;R||(U=U.delete(T.from,T.to));const O=U.mapping.map(G);return U=U.insert(O,q),N(b.state,U,T,O,R),U.setMeta("amxColumns",!0),b.dispatch(U.scrollIntoView()),!0},_=(b,M,R)=>{const{state:T}=b,F=T.selection;if(!(F instanceof ye))return!1;const V=T.doc.nodeAt(M);if(!V||V.type.name!=="list_item"||M>=F.from&&M<F.to)return!1;const G=T.schema.nodes.list_item,q=T.schema.nodes.bullet_list;if(!G||!q)return!1;const U=F.node;if(U.type.name==="amadeusColumnRow"||U.type.name==="amadeusColumnCell")return!1;const O=U.type.name==="list_item"?U:G.createAndFill(null,U);if(!O)return!1;const ge=V.child(V.childCount-1),De=V.childCount>1&&/_list$/.test(ge.type.name);let Ie=T.tr;R||(Ie=Ie.delete(F.from,F.to));const Oe=Ie.mapping.map(M),Pe=Ie.doc.nodeAt(Oe);if(!Pe||Pe.type.name!=="list_item")return!1;const We=De?Oe+Pe.nodeSize-2:Oe+Pe.nodeSize-1;return Ie=Ie.insert(We,De?O:(ge.type.name.endsWith("_list")?ge.type:q).create(null,O)),Ie.setMeta("amxColumns",!0),b.dispatch(Ie.scrollIntoView()),!0},X=b=>!!b.dom.closest(".unified-body")?.classList.contains("amx-canvas"),te=(b,M,R,T)=>{let F=R;for(let V=0;V<M.childCount;V++){const G=M.child(V),q=b.nodeDOM(F),U=q instanceof HTMLElement?q.getBoundingClientRect():null;if(U&&T.clientY<=U.bottom)return T.clientY>U.top+U.height/2?F+G.nodeSize:F;F+=G.nodeSize}return F},B=(b,M)=>{const R=b.state.doc,T=b.state.schema.nodes.amadeusCanvasCard;let F=0;for(let V=0;V<R.childCount;V++){const G=R.child(V);if(G.type===T)return F;const q=b.nodeDOM(F),U=q instanceof HTMLElement?q.getBoundingClientRect():null;if(U&&M.clientY<=U.bottom)return M.clientY>U.top+U.height/2?F+G.nodeSize:F;F+=G.nodeSize}return F},Y=(b,M,R)=>{const T=b.state.selection;if(!(T instanceof ye))return!1;const F=b.state.schema.nodes.amadeusCanvasCard;if(!F)return!1;const V=M.target;if(!V||!b.dom.contains(V))return!1;if(T.node.type===F)return!0;const G=V.closest?.(".amx-ucard");let q;if(G){let O;try{O=b.posAtDOM(G,0)-1}catch{return!1}const ge=b.state.doc.nodeAt(O);if(ge?.type!==F)return!1;q=te(b,ge,O+1,M)}else q=B(b,M);if(q>=T.from&&q<=T.to)return!0;let U=b.state.tr;return R||(U=U.delete(T.from,T.to)),U=U.insert(U.mapping.map(q),T.node),U.setMeta("amxColumns",!0),b.dispatch(U.scrollIntoView()),!0},Te=b=>{const M=b.state.schema.nodes.amadeusCanvasCard,R=[];return M&&b.state.doc.forEach((T,F,V)=>{T.type===M&&R.push({anchor:String(T.attrs.anchor),idx:V,pos:F,size:T.nodeSize})}),R},Ve=(b,M)=>{const R=b.state.doc,T=b.state.schema.nodes.amadeusCanvasCard;if(!T)return null;const F=e.canvasTree?.()??{},V=Te(b),G=new Map;for(let Oe=0;Oe<V.length;){const Pe=Ys(V,Oe,F);G.set(Oe,Pe),Oe=Pe}const q=Oe=>{const Pe=b.nodeDOM(Oe);return Pe instanceof HTMLElement?Pe:null},U=[];let O=0,ge=0,De=-1;for(let Oe=0;Oe<R.childCount;Oe++){const Pe=R.child(Oe);if(O<De){Pe.type===T&&ge++,O+=Pe.nodeSize;continue}if(Pe.type===T){const We=G.get(ge);if(We!=null){const Ye=V[We-1];U.push({from:O,to:Ye.pos+Ye.size,firstEl:q(O),lastEl:q(Ye.pos)})}ge++}else{let We=O+Pe.nodeSize,Ye;if(Pe.type.name==="heading"&&yo(b,O)==="folded"){const Ge=Yo(b.state,O);Ge!=null&&(We=Ge,De=Ge,Ye=O)}U.push({from:O,to:We,firstEl:q(O),lastEl:q(O),foldPos:Ye})}O+=Pe.nodeSize}let Ie=null;for(let Oe=0;Oe<U.length;Oe++){const Pe=U[Oe];if(!Pe.firstEl||!Pe.lastEl)continue;const We=Pe.firstEl.getBoundingClientRect().top,Ye=Pe.lastEl.getBoundingClientRect().bottom;if(Ie={at:Pe.to,lineEl:Pe.lastEl,edge:"bottom",expandFold:Pe.foldPos},M.clientY>Ye)continue;const Ge=Oe>0?U[Oe-1]:null;return M.clientY<=(We+Ye)/2?{at:Pe.from,lineEl:Pe.firstEl,edge:"top",expandFold:Ge&&Ge.foldPos!=null&&Ge.to===Pe.from?Ge.foldPos:void 0}:Ie}return Ie},h=(b,M)=>{const R=b.state.selection,T=b.state.schema.nodes.amadeusCanvasCard;if(!T||!(R instanceof ye)||R.node.type!==T)return null;const F=Ve(b,M);if(!F)return null;const V=e.canvasTree?.()??{},G=Te(b),q=G.findIndex(ge=>ge.pos===R.from);if(q<0)return null;const U=G[Ys(G,q,V)-1],O={from:R.from,to:U.pos+U.size};return{drop:F,range:O,self:F.at>=O.from&&F.at<=O.to}},Se=(b,M,R)=>{const T=b.state.selection,F=b.state.schema.nodes.amadeusCanvasCard;if(!F||!(T instanceof ye)||T.node.type!==F)return!1;const V=h(b,M);if(!V||V.self)return!0;let G=b.state.doc.slice(V.range.from,V.range.to).content;if(R){const U=Qo(b.state.doc,G);G=U.content,U.minted.length&&e.onCardsMinted?.(U.minted)}V.drop.expandFold!=null&&yo(b,V.drop.expandFold)==="folded"&&$s(b,V.drop.expandFold);let q=b.state.tr;if(R||(q=q.delete(V.range.from,V.range.to)),q=q.insert(q.mapping.map(V.drop.at),G),q.setMeta("amxColumns",!0),b.dispatch(q.scrollIntoView()),!R){const U=String(T.node.attrs.anchor),ge=(e.canvasTree?.()??{})[U];typeof ge=="string"&&Te(b).some(De=>De.anchor===ge)&&e.onCardDetach?.([U])}return!0};let lt=null,ne=null,de=null,ce=null,be=!1,Ee=!1,ve=null;const Ce=b=>(ve&&ve.isConnected||(ve=document.createElement("div"),ve.className="unified-drop-line",ve.style.display="none",ve.style.animation="none",(b.dom.parentElement??document.body).appendChild(ve)),ve),st=(b,M,R=0,T="bottom")=>{const F=Ce(b),V=Do(b.dom),G=Io(F),q=M.getBoundingClientRect(),U=T==="top"?q.top-6:q.bottom+6;F.style.display="block",F.style.width=`${Math.max(0,q.width-R)/V}px`,F.style.transform=`translate(${Math.round((q.left+R-G.x)/V)}px, ${Math.round((U-G.y)/V)}px)`},Z=()=>{ve&&(ve.style.display="none")},oe=(b,M)=>{const R=b.state.doc.resolve(M);if(R.depth===0)return b.state.doc.nodeAt(M)?.type.name!=="amadeusCanvasCard";for(let T=R.depth;T>=1;T--)if(R.node(T).type.name==="amadeusColumnRow")return T===1;return!1},je=b=>b instanceof HTMLElement&&b.getClientRects().length>0,j=(b,M)=>{if(X(b))return null;const R=b.state.selection,T=R instanceof ye?{from:R.from,to:R.to}:y(b);if(!T)return null;const F=M.target instanceof Element?M.target.closest("blockquote"):null;if(!(F instanceof HTMLElement)||!b.dom.contains(F))return null;let V;try{V=b.posAtDOM(F,0)-1}catch{return null}const G=b.state.doc.nodeAt(V);if(G?.type.name!=="blockquote"||b.nodeDOM(V)!==F)return null;const q=b.state.doc.slice(T.from,T.to).content;let U=!1;if(q.descendants(Oe=>{["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell"].includes(Oe.type.name)&&(U=!0)}),U)return null;const O=!!G.firstChild?.isTextblock&&/^\[![\w-]+\]/.test(G.firstChild.textContent),ge=b.nodeDOM(V+1);if(O&&je(ge)){const Oe=ge.getBoundingClientRect();if(M.clientY<Oe.top+Oe.height/2)return null}let De=null;if(G.forEach((Oe,Pe)=>{const We=V+1+Pe,Ye=b.nodeDOM(We);if(!je(Ye))return;const Ge=Ye.getBoundingClientRect(),qt=M.clientY<Ge.top+Ge.height/2?"top":"bottom",Wt=Math.abs(M.clientY-(qt==="top"?Ge.top:Ge.bottom));(!De||Wt<De.distance)&&(De={at:qt==="top"?We:We+Oe.nodeSize,lineEl:Ye,edge:qt,distance:Wt})}),!De)return null;const Ie=De;return{...Ie,self:Ie.at>=T.from&&Ie.at<=T.to}},J=(b,M,R)=>{const T=j(b,M);if(!T)return!1;if(T.self)return!0;const{state:F}=b,V=F.selection,G=V instanceof ye?{from:V.from,to:V.to}:y(b);if(!G)return!1;const q=V instanceof ye&&V.node.type.name==="list_item"?wr.from(V.$from.parent.type.create(V.$from.parent.attrs,V.node)):F.doc.slice(G.from,G.to).content,U=R?F.tr:F.tr.delete(G.from,G.to),O=U.mapping.map(T.at),ge=U.doc.resolve(O);return ge.parent.type.name!=="blockquote"||!ge.parent.canReplace(ge.index(),ge.index(),q)?!1:(U.insert(O,q),N(F,U,G,O,R),Hs(U,O,O+q.size),U.setSelection(q.childCount===1&&ye.isSelectable(q.firstChild)?ye.create(U.doc,O):Ae.between(U.doc.resolve(O),U.doc.resolve(O+q.size))),U.setMeta("amxColumns",!0).setMeta("uiEvent","drop"),b.dispatch(U.scrollIntoView()),b.focus(),!0)},se=(b,M)=>{const R=b.state.doc;let T=null,F=1/0;for(let V=0,G=0;V<R.childCount;G+=R.child(V).nodeSize,V++){const q=b.nodeDOM(G);if(!je(q))continue;const U=q.getBoundingClientRect(),O=M<U.top?U.top-M:M>U.bottom?M-U.bottom:0;if(O===0)return{pos:G,node:R.child(V),el:q};O<F&&(F=O,T={pos:G,node:R.child(V),el:q})}return T},xe=(b,M)=>{const R=b.state.selection,T=p(M),F=V=>!T&&R instanceof ye&&V>=R.from&&V<=R.to;for(const V of b.dom.querySelectorAll(":scope > .amx-ucolrow")){const G=V.getBoundingClientRect();if(!(M.clientY<G.top||M.clientY>G.bottom||M.clientX<G.left||M.clientX>G.right)){for(const q of Array.from(V.children)){if(!je(q)||!("amxColcell"in q.dataset))continue;const U=q.getBoundingClientRect();if(!(M.clientX<U.left||M.clientX>U.right))try{const O=b.posAtDOM(q,0)-1,ge=b.state.doc.nodeAt(O);if(ge?.type.name!=="amadeusColumnCell")return null;let De=O+1,Ie=null;for(let Oe=0;Oe<ge.childCount;Oe++){const Pe=ge.child(Oe),We=b.nodeDOM(De);if(je(We)){const Ye=We.getBoundingClientRect();if(M.clientY<=Ye.bottom){if(M.clientY>=Ye.top&&(!Pe.isTextblock&&!Pe.isAtom||M.clientX<=Ye.left+f||M.clientX>=Ye.right-f))return null;const Ge=M.clientY<=Ye.top+Ye.height/2,qt=Ge?De:De+Pe.nodeSize;return{cellEl:q,lineEl:We,pos:De,edge:Ge?"top":"bottom",tail:!1,self:F(qt)}}Ie=We}De+=Pe.nodeSize}return Ie?{cellEl:q,lineEl:Ie,pos:O,edge:"bottom",tail:!0,self:F(O+ge.nodeSize-1)}:null}catch{return null}}return null}}return null},Qe=(b,M)=>{if(!M.cellEl.isConnected||!M.lineEl.isConnected)return null;try{if(M.tail){const F=b.posAtDOM(M.cellEl,0)-1,V=b.state.doc.nodeAt(F);return V?.type.name==="amadeusColumnCell"?F+V.nodeSize-1:null}const R=b.state.doc.nodeAt(M.pos);if(!R||b.nodeDOM(M.pos)!==M.lineEl)return null;const T=M.edge==="top"?M.pos:M.pos+R.nodeSize;return b.state.doc.resolve(T).parent.type.name==="amadeusColumnCell"?T:null}catch{return null}},He=(b,M)=>{try{const R=b.state.doc.resolve(M),T=R.parent;let F=R.start();for(let V=0;V<T.childCount&&F<M;V++){const G=T.child(V);if(G.type.name==="heading"&&yo(b,F)==="folded"){const q=Yo(b.state,F);if(q!=null&&M>F&&M<=q)return F}F+=G.nodeSize}}catch{}return null},Rt=(b,M)=>{for(let R=He(b,M),T=-1;R!=null&&R!==T;T=R,R=He(b,M))$s(b,R)};let at=null;const Vt=()=>{at&&(at.style.display="none")};let Pt=!1,St=!1;const ln=()=>{St||(St=!0,Pt=!1,queueMicrotask(()=>{St=!1,Pt||Vt()}))},ct=bt(()=>new Ht({key:new jn("UNIFIED_BLOCK_HANDLE"),view:b=>{t=b,ci.add(b);const M=b.dom.parentElement??document.body,R=M.closest(".unified-body")??M,T=z=>{for(const L of R.querySelectorAll(".amx-ucard.amx-droptarget"))L.classList.remove("amx-droptarget");z?.classList.add("amx-droptarget")},F=document.createElement("div");F.className="unified-gutter",F.dataset.show="false";const V=()=>{F.dataset.show="false",n=null},G=z=>{if(!b.editable)return;n=z,Wt(z),Ue.style.display=Xn(z)?"":"none";const L=Do(b.dom),re=Io(F),fe=ii(z.el),ke=fe.getBoundingClientRect(),le=(z.el.tagName==="LI"&&/^(UL|OL)$/.test(z.el.parentElement?.tagName??"")?z.el.parentElement:null)?.getBoundingClientRect().left??ke.left,me=getComputedStyle(fe),ut=Number.parseFloat(me.lineHeight)||24,vt=(Number.parseFloat(me.paddingTop)||0)+Math.max(0,(ut-24)/2),Yt=ke.height/L,Mt=Math.max(24,Yt-16),zt=Mt>24?Mt/2-4-vt:0;F.dataset.show="true",F.style.setProperty("--amx-block-h",`${Yt}px`),F.style.setProperty("--amx-block-grow-y",`${zt}px`);const Dn=F.offsetWidth||52;F.style.top=`${(ke.top-re.y)/L+vt}px`;let At=(le-re.x)/L-Dn-8;_o()&&(At=Math.max(At,(2-re.x)/L-q.offsetLeft)),F.style.left=`${At}px`},q=document.createElement("button");q.type="button",q.className="drag-handle",q.textContent="⠿",q.draggable=!0,q.title=we("blocklayer.dragHandle"),q.setAttribute("aria-label",q.title),q.addEventListener("click",z=>{z.stopPropagation();const L=q.getBoundingClientRect();if(z.detail===0&&t&&n){const re=t.state.selection;re instanceof ye&&re.from<=n.pos&&n.pos+n.node.nodeSize<=re.to||U(t,n)}e.onMenu({x:L.left,y:L.bottom+4,keyboard:z.detail===0}),_o()||t?.focus()}),F.addEventListener("mousedown",()=>{t&&n&&U(t,n)});const U=(z,L)=>{const re=z.state.selection,fe=L.pos+1,ke=L.pos+L.node.nodeSize-1;if(re instanceof Ae&&!re.empty&&!re.$from.sameParent(re.$to)&&re.from<=fe&&re.to>=ke){z.focus();return}const ze=E(z,L.pos,L.node);if(ze){const le=z.state.doc;z.dispatch(z.state.tr.setSelection(Ae.between(le.resolve(ze.from+1),le.resolve(ze.to-1))).setMeta(r,!0)),z.focus();return}ye.isSelectable(L.node)&&(z.dispatch(z.state.tr.setSelection(ye.create(z.state.doc,L.pos))),z.focus())};let O=null;const ge=()=>{const z=t,L=n;if(!z||!L)return;(!O||!O.isConnected)&&(O=document.createElement("div"),O.className="unified-press-rect",(z.dom.parentElement??document.body).appendChild(O));const re=Do(z.dom),fe=Io(O),ke=ii(L.el).getBoundingClientRect(),ze=y(z);let le={left:ke.left-fe.x,top:ke.top-fe.y,right:ke.right-fe.x,bottom:ke.bottom-fe.y};if(ze)for(const me of Array.from(z.dom.children)){if(!me.classList.contains("amx-block-selected"))continue;const ut=me.getBoundingClientRect();le={left:Math.min(le.left,ut.left-fe.x),top:Math.min(le.top,ut.top-fe.y),right:Math.max(le.right,ut.right-fe.x),bottom:Math.max(le.bottom,ut.bottom-fe.y)}}Object.assign(O.style,{display:"block",transform:`translate(${Math.round((le.left-4)/re)}px, ${Math.round((le.top-4)/re)}px)`,width:`${(le.right-le.left+8)/re}px`,height:`${(le.bottom-le.top+8)/re}px`})},De=()=>{O&&(O.style.display="none")};F.addEventListener("mousedown",ge),window.addEventListener("mouseup",De);const Ie=(z,L,re)=>{z.dom.dataset.dragging="true";let fe=z.state.selection;if(D=null,fe instanceof ye&&yo(z,fe.from)==="folded"){const ze=fe.from,le=Yo(z.state,ze),me=z.state.doc;if(le!=null){z.dispatch(z.state.tr.setSelection(Ae.between(me.resolve(ze+1),me.resolve(le-1))).setMeta(r,!0));const ut=y(z);ut&&ut.from===ze&&ut.to===le?D=ze:z.dispatch(z.state.tr.setSelection(ye.create(z.state.doc,ze)))}D==null&&$s(z,ze),fe=z.state.selection}fe instanceof ye&&As(z,fe.from)==="folded"&&fa(z,fe.from);const ke=fe instanceof Ae&&!fe.empty&&!fe.$from.sameParent(fe.$to);if(L.dataTransfer&&(fe instanceof ye||ke)){const ze=fe.content();L.dataTransfer.effectAllowed="copyMove";const{dom:le,text:me}=z.serializeForClipboard(ze);L.dataTransfer.clearData(),L.dataTransfer.setData("text/html",le.innerHTML),L.dataTransfer.setData("text/plain",me),re&&L.dataTransfer.setDragImage(re,0,0),z.dragging={slice:ze,move:!0}}};F.addEventListener("dragstart",z=>{t&&Ie(t,z,n?.el??null)});const Oe=z=>{const L=t;if(!L||!(z.target instanceof Node)||!L.dom.contains(z.target)||!z.target.closest?.(".wiki-inline-img-wrap"))return;const re=Mm(z.target);let fe=-1;try{re&&(fe=L.posAtDOM(re,0)-1)}catch{}const ke=re?.querySelector(":scope > .wiki-inline-img-wrap")?.getBoundingClientRect(),ze=ke?es(L,{x:ke.left+ke.width/2,y:ke.top+ke.height/2}):null;if(!re||!z.dataTransfer||L.nodeDOM(fe)!==re||!ze||fe<ze.pos||fe>=ze.pos+ze.node.nodeSize){z.preventDefault();return}z.stopPropagation(),U(L,ze),Ie(L,z,null),z.target.addEventListener("dragend",Pe,{once:!0})};R.addEventListener("dragstart",Oe,!0);const Pe=()=>{const z=t;if(z&&D!=null){const L=y(z);L&&L.from===D&&z.state.doc.nodeAt(D)?.type.name==="heading"&&z.dispatch(z.state.tr.setSelection(ye.create(z.state.doc,D))),D=null}De(),T(null),o=null,de=null,ce=null,ne=null,Ee=!1,be=!1,i(),Z(),Vt(),z&&(z.dom.dataset.dragging="false",z.dragging=null)};F.addEventListener("dragend",Pe);const We=document.createElement("button");We.type="button",We.className="block-add block-fold",We.textContent="▾",We.style.display="none";const Ye=z=>{const L=t;return L?As(L,z.pos)?z.pos:/_list$/.test(z.node.type.name)&&As(L,z.pos+1)?z.pos+1:null:null},Ge=z=>{const L=t;return L?yo(L,z.pos)?z.pos:!z.node.isTextblock&&z.node.childCount>0&&yo(L,z.pos+1)?z.pos+1:null:null},qt=z=>!t||!z?null:Ge(z)!=null?"heading":Ye(z)!=null?"list":null,Wt=z=>{const L=t,re=qt(z),fe=z?Ye(z):null,ke=z?Ge(z):null,ze=!L||!z||!re?null:re==="heading"?ke==null?null:yo(L,ke):fe==null?null:As(L,fe);We.style.display=ze?"":"none",We.textContent=ze==="folded"?"▸":"▾",We.title=re==="list"?ze==="folded"?we("blocklayer.expandChildren"):we("blocklayer.foldChildren"):ze==="folded"?we("blocklayer.expandSection"):we("blocklayer.foldSection"),We.setAttribute("aria-label",We.title),We.setAttribute("aria-expanded",String(ze!=="folded"))};We.addEventListener("click",z=>{z.stopPropagation();const L=t,re=n;if(!L||!re)return;const fe=qt(re)==="list"?Ye(re):null;if(fe!=null)fa(L,fe);else{const ke=Ge(re);if(ke==null)return;$s(L,ke)}Wt(re)});const kt=document.createElement("button");kt.type="button",kt.className="block-add",kt.textContent="+",kt.title=we("blocklayer.addBelow"),kt.setAttribute("aria-label",kt.title),kt.addEventListener("click",z=>{z.stopPropagation();const L=t,re=n;if(!L||!re)return;const fe=by(L.state,re.node,re.pos,z.altKey);if(!fe)return;L.focus();let ke=L.state.tr.insert(fe.at,fe.node);ke=ke.setSelection(Ae.create(ke.doc,fe.caret)).scrollIntoView(),dd(L,fe.caret),L.dispatch(ke),V()});const Ue=document.createElement("button");Ue.type="button",Ue.className="card-grab",Ue.textContent="❏",Ue.draggable=!0,Ue.title=we("blocklayer.cardGrab"),Ue.setAttribute("aria-label",Ue.title),Ue.style.display="none";const Xn=z=>{const L=t;if(!L||!z||z.node.type.name==="amadeusCanvasCard")return null;try{const re=L.state.doc.resolve(z.pos);for(let fe=re.depth;fe>=1;fe--){if(re.node(fe).type.name!=="amadeusCanvasCard")continue;const ke=re.before(fe),ze=L.state.doc.nodeAt(ke),le=L.nodeDOM(ke);return ze&&le instanceof HTMLElement?{node:ze,pos:ke,el:le}:null}}catch{}return null};Ue.addEventListener("mousedown",z=>{const L=t,re=Xn(n);!L||!re||(z.stopPropagation(),n=re,L.dispatch(L.state.tr.setSelection(ye.create(L.state.doc,re.pos))),L.focus(),ge())}),Ue.addEventListener("click",z=>{if(z.stopPropagation(),!n)return;const L=Ue.getBoundingClientRect();e.onMenu({x:L.left,y:L.bottom+4,keyboard:z.detail===0}),_o()||t?.focus()}),F.append(Ue,q,kt,We);let Lt=null,$t=null,nr=null;const Er=()=>{const z=[];for(const L of Array.from(b.dom.children))if(L.classList.contains("amx-ucolrow"))for(const re of Array.from(L.querySelectorAll(".amx-ucolcell")))z.push(...Array.from(re.children));else z.push(L);return z},ur=(z,L,re)=>{const fe=z.getBoundingClientRect();if(L<fe.left||L>fe.right||re<fe.top||re>fe.bottom)return!1;if(z.matches("hr, table, pre, .amx-ucard"))return!0;const ke=le=>L>=le.left-2&&L<=le.right+2&&re>=le.top-2&&re<=le.bottom+2;for(const le of z.querySelectorAll(".unified-embed, .wiki-inline-img-wrap, .wikilink, img, video, iframe, canvas"))if(ke(le.getBoundingClientRect()))return!0;const ze=document.createTreeWalker(z,NodeFilter.SHOW_TEXT);for(let le=ze.nextNode();le;le=ze.nextNode()){if(!le.textContent?.length)continue;const me=document.createRange();me.selectNodeContents(le);for(const ut of me.getClientRects())if(ke(ut))return!0}return!1},zn=z=>{if(z.button!==0||z.pointerType==="touch"||R.classList.contains("amx-canvas"))return;const L=z.target;if(!L||L.closest(".unified-gutter")||L.closest(".amx-embed")||L.closest("button, input, textarea, a")||!b.editable)return;const re=Er();if(re.some(ze=>ur(ze,z.clientX,z.clientY)))return;const fe=L.closest('li[data-item-type="task"]');if(fe&&z.clientX-fe.getBoundingClientRect().left<=2)return;if(re.some(ze=>{const le=ze.getBoundingClientRect();return z.clientX>=le.left&&z.clientX<=le.right&&z.clientY>=le.top&&z.clientY<=le.bottom})){nr={x:z.clientX,y:z.clientY},window.addEventListener("pointermove",lo),window.addEventListener("pointerup",Xr,{once:!0});return}z.preventDefault(),Yr(z.clientX,z.clientY)},Yr=(z,L)=>{$t={x:z,y:L},Lt=document.createElement("div"),Lt.className="amx-marquee",document.body.appendChild(Lt),document.body.classList.add("amx-marquee-active"),window.addEventListener("pointermove",fr),window.addEventListener("pointerup",uo,{once:!0})},Mr=()=>{nr=null,window.removeEventListener("pointermove",lo),window.removeEventListener("pointerup",Xr)},Xr=()=>{Mr(),window.addEventListener("mouseup",zr,{once:!0})},zr=()=>{b.isDestroyed||b.domObserver?.flush?.()},lo=z=>{const L=nr;!L||Math.abs(z.clientX-L.x)<=4&&Math.abs(z.clientY-L.y)<=4||(Mr(),Yr(L.x,L.y),dr=!0,window.addEventListener("dragstart",Un,!0),window.addEventListener("selectionchange",Un,!0),fr(z))};let dr=!1;const Un=z=>{z.type==="dragstart"?z.preventDefault():z.stopImmediatePropagation()},rr=()=>{if(!dr)return;dr=!1,window.removeEventListener("dragstart",Un,!0);let z=!1;const L=()=>{if(z)return;z=!0,window.removeEventListener("mouseup",re,!0),clearTimeout(fe);const ke=t;ke&&!ke.isDestroyed&&ke.focus(),dr||window.removeEventListener("selectionchange",Un,!0)},re=()=>{setTimeout(L,0)},fe=setTimeout(L,300);window.addEventListener("mouseup",re,{capture:!0,once:!0})},fr=z=>{if(!Lt||!$t)return;const L=Math.min($t.x,z.clientX),re=Math.min($t.y,z.clientY),fe=Math.abs(z.clientX-$t.x),ke=Math.abs(z.clientY-$t.y);Object.assign(Lt.style,{left:`${L}px`,top:`${re}px`,width:`${fe}px`,height:`${ke}px`});const ze=[],le=[];for(const Mt of Er()){const zt=Mt.getBoundingClientRect();if(!(zt.bottom<re||zt.top>re+ke||zt.right<L||zt.left>L+fe))try{ze.push(b.posAtDOM(Mt,0)),le.push(Mt)}catch{}}if(!ze.length)return;const me=b.state.doc;if(le.length===1){const Mt=le[0];try{const zt=Array.prototype.indexOf.call(Mt.parentNode?.childNodes,Mt),Dn=b.posAtDOM(Mt.parentNode,zt),At=me.nodeAt(Dn);if(At&&ye.isSelectable(At)){const un=ye.create(me,Dn);un.eq(b.state.selection)||b.dispatch(b.state.tr.setSelection(un));return}}catch{}}const ut=Math.min(...ze),Et=le[le.length-1];if(!Et)return;let vt=ut;try{const Mt=b.posAtDOM(Et,0),zt=b.state.doc.nodeAt(Mt-1);vt=zt?Mt+zt.content.size:Mt}catch{}const Yt=Ae.between(me.resolve(Math.min(ut,me.content.size)),me.resolve(Math.min(vt,me.content.size)));(!Yt.eq(b.state.selection)||!r.getState(b.state))&&b.dispatch(b.state.tr.setSelection(Yt).setMeta(r,!0))},uo=z=>{window.removeEventListener("pointermove",fr),rr();const L=!!(z&&$t&&(Math.abs(z.clientX-$t.x)>4||Math.abs(z.clientY-$t.y)>4)),re=$t;if(Lt?.remove(),Lt=null,$t=null,document.body.classList.remove("amx-marquee-active"),L){b.focus();return}if(!re||!z)return;const fe=b.dom.getBoundingClientRect(),ke=Math.min(Math.max(z.clientX,fe.left+8),fe.right-8),ze=b.posAtCoords({left:ke,top:z.clientY});if(!ze)return;const le=b.state.doc.resolve(ze.pos);if(!le.parent.isTextblock)return;const me=z.clientX<fe.left+fe.width/2?le.start():le.end();b.dispatch(b.state.tr.setSelection(Ae.near(b.state.doc.resolve(me)))),b.focus()};R.addEventListener("pointerdown",zn),M.appendChild(F);let sn=0,wn=null;const Ot=z=>{if(F.contains(z.target)){wn&&clearTimeout(wn),wn=null;return}const L=Date.now();if(L-sn<80){const{clientX:re,clientY:fe}=z;wn&&clearTimeout(wn),wn=setTimeout(()=>{wn=null,sn=Date.now(),Qt(re,fe)},80);return}sn=L,Qt(z.clientX,z.clientY)},Qt=(z,L)=>{const re={clientX:z,clientY:L};if(b.dom.dataset.dragging==="true")return;let fe=es(b,{x:re.clientX,y:re.clientY});if(!fe){const ke=b.dom.getBoundingClientRect();if(re.clientY>=ke.top&&re.clientY<=ke.bottom&&(re.clientX<ke.left+8||re.clientX>ke.right-8)){const ze=Math.min(Math.max(re.clientX,ke.left+8),ke.right-8);fe=es(b,{x:ze,y:re.clientY})}}fe&&G(fe)};R.addEventListener("mousemove",Ot,{passive:!0});const xr=z=>{const L=z.relatedTarget;L&&(F.contains(L)||R.contains(L))||V()};R.addEventListener("mouseleave",xr);const Nr=()=>{b.dom.dataset.dragging!=="true"&&V()};b.dom.addEventListener("keydown",Nr);const Gn=z=>{const L=t;if(!L||!L.editable)return;const re=L.state.selection,fe=re instanceof ye?{from:re.from,to:re.to}:r.getState(L.state)?y(L):null;let ke=!1;if(fe){const ze=re instanceof ye?L.nodeDOM(re.from):null,le=L.posAtCoords({left:z.clientX,top:z.clientY});ke=ze instanceof Node&&z.target instanceof Node&&ze.contains(z.target)||!!le&&le.pos>=fe.from&&le.pos<=fe.to}if(!ke){const ze=z.target instanceof Element?z.target:null,le=ze?.closest('[contenteditable="false"]'),me=!!ze&&(!!le&&le!==L.dom&&L.dom.contains(le)||/^(IMG|VIDEO|AUDIO|HR|CANVAS|IFRAME)$/.test(ze.tagName)),ut=L.state.selection.empty?ze?.closest("td, th"):null;let Et=null;if(ut&&L.dom.contains(ut)){const Mt=L.state.doc.resolve(L.posAtDOM(ut,0));for(let zt=Mt.depth;zt>0;zt--)if(Mt.node(zt).type.spec.tableRole==="table"){Et=Mt.before(zt);break}}if(!me&&Et==null)return;const vt=Et??es(L,{x:z.clientX,y:z.clientY})?.pos,Yt=vt==null?null:L.state.doc.nodeAt(vt);if(vt==null||!Yt||!ye.isSelectable(Yt))return;L.dispatch(L.state.tr.setSelection(ye.create(L.state.doc,vt)))}z.preventDefault(),L.focus(),e.onMenu({x:z.clientX,y:z.clientY})};b.dom.addEventListener("contextmenu",Gn),F.addEventListener("contextmenu",z=>{const L=t;!L||!L.editable||!n||(z.preventDefault(),_o()||L.focus(),e.onMenu({x:z.clientX,y:z.clientY}))});const Jn=()=>{b.dom.dataset.dragging!=="true"&&V()};window.addEventListener("scroll",Jn,{capture:!0,passive:!0});const Hn=z=>{if(b.dom.dataset.dragging!=="true")return;const L=vy(b.dom);if(!L)return;const re=L.getBoundingClientRect();z.clientY<re.top+56?L.scrollTop-=14:z.clientY>re.bottom-56&&(L.scrollTop+=14)};window.addEventListener("dragover",Hn);const Zn=z=>{const L=t,re=z.dataTransfer?Array.from(z.dataTransfer.types):[];if(re.includes("Files")||re.includes(df)&&L&&!X(L)){if(!L)return;const le=se(L,z.clientY);if(!le)return;const me=le.el.getBoundingClientRect();lt={pos:le.pos,el:le.el,lower:z.clientY>me.top+me.height/2},st(L,le.el);return}if(!L||L.dom.dataset.dragging!=="true")return;be&&Z(),be=!1;{const le=L.state.selection;if(!X(L)&&le instanceof ye&&le.node.type===L.state.schema.nodes.amadeusCanvasCard){Ee=!1,o=null,ne=null,de=null,ce=null,i();const me=h(L,z);me&&!me.self?(st(L,me.drop.lineEl,0,me.drop.edge),z.preventDefault()):Z();return}}const fe=j(L,z);if(fe){be=!0,o=null,ne=null,de=null,ce=null,Ee=!1,i(),Vt(),fe.self?Z():st(L,fe.lineEl,0,fe.edge),z.preventDefault();return}if(Ee=!1,ce=null,!X(L)){const me=L.state.selection instanceof ye||!!y(L),ut=L.dom.lastElementChild;if(me&&je(ut)){const Et=ut.getBoundingClientRect(),vt=L.dom.getBoundingClientRect();if(z.clientY>Et.bottom+2&&z.clientX>=vt.left&&z.clientX<=vt.right){Ee=!0,o=null,ne=null,de=null,i(),st(L,ut),z.preventDefault();return}}}if(!(L.state.selection instanceof ye))return;if(X(L)){T(z.target?.closest?.(".amx-ucard")),de=null,Z(),z.preventDefault();return}const ke=xe(L,z);if(ke){ce={cellEl:ke.cellEl,lineEl:ke.lineEl,pos:ke.pos,edge:ke.edge,tail:ke.tail,self:ke.self},de=null,o=null,ne=null,i(),Vt(),ke.self?Z():st(L,ke.lineEl,0,ke.edge),z.preventDefault();return}let ze=null;for(const le of L.dom.querySelectorAll(":scope > .amx-ucolrow")){const me=le.getBoundingClientRect();if(z.clientX<me.left||z.clientX>me.right||z.clientY<=me.bottom+2)continue;const ut=le.nextElementSibling;ut&&z.clientY>=ut.getBoundingClientRect().top-2||(ze=le)}if(ze)try{const le=L.posAtDOM(ze,0)-1;if(L.state.doc.nodeAt(le)?.type.name==="amadeusColumnRow"){de={rowEl:ze},st(L,ze),z.preventDefault();return}}catch{}de=null,Z()};R.addEventListener("dragover",Zn,!0);const fo=z=>{const L=z.relatedTarget;L&&R.contains(L)||(de=null,ce=null,lt=null,ne=null,o=null,be=!1,i(),Z(),Vt(),T(null))};R.addEventListener("dragleave",fo,!0);const Vn=z=>{const L=t,re=o,fe=de,ke=ce,ze=ne,le=lt,me=Ee,ut=be;if(o=null,de=null,ce=null,ne=null,lt=null,Ee=!1,be=!1,i(),Z(),Vt(),T(null),!L)return;if(le){try{const Yt=L.nodeDOM(le.pos)===le.el?L.state.doc.nodeAt(le.pos):null;if(Yt){Rt(L,le.pos+Yt.nodeSize);const Mt=L.state.doc;L.dispatch(L.state.tr.setSelection(Yt.isAtom?ye.create(Mt,le.pos):Ae.near(Mt.resolve(le.lower?le.pos+1+Yt.content.size:le.pos+1),le.lower?-1:1)))}}catch{}return}const Et=p(z);let vt=X(L)?Y(L,z,Et):Se(L,z,Et);if(!vt)if(me)vt=S(L,Et);else if(ut)vt=J(L,z,Et);else if(y(L))vt=A(L,z,Et);else if(ze)vt=_(L,ze.targetPos,Et);else if(fe)try{fe.rowEl.isConnected&&(vt=Ag(L,L.posAtDOM(fe.rowEl,0)-1,Et))}catch{vt=!1}else if(ke){const Yt=Qe(L,ke);Yt!=null&&(ke.self||Rt(L,Yt),vt=Tg(L,Yt,Et))}else re&&(vt=$g(L,re.targetPos,re.side,Et));vt&&(z.preventDefault(),z.stopPropagation(),L.dom.dataset.dragging="false",L.dragging=null)};R.addEventListener("drop",Vn,!0);let mr=null;const $r=z=>{const L=t,re=z.target;if(!L||!re||!re.classList?.contains("amx-ucolrow"))return;const fe=re,ke=[...fe.children].filter(At=>At instanceof HTMLElement&&"amxColcell"in At.dataset);let ze=-1;for(let At=0;At<ke.length-1;At++)if(z.clientX>=ke[At].getBoundingClientRect().right-2&&z.clientX<=ke[At+1].getBoundingClientRect().left+2){ze=At;break}if(ze<0)return;z.preventDefault();const le=ke[ze],me=ke[ze+1],ut=le.getBoundingClientRect().left,Et=me.getBoundingClientRect().right-ut,vt=(Number(le.dataset.width)||1)+(Number(me.dataset.width)||1),Yt=At=>Math.min(.85,Math.max(.15,(At.clientX-ut)/Et)),Mt=At=>{const un=Yt(At);le.style.flexGrow=String(vt*un),me.style.flexGrow=String(vt*(1-un))},zt=()=>{window.removeEventListener("pointermove",Mt),window.removeEventListener("pointerup",Dn),window.removeEventListener("pointercancel",zt),mr=null},Dn=At=>{zt();const un=Yt(At),Ar=Tr=>Math.round(Tr*1e4)/1e4;try{const Tr=L.posAtDOM(fe,0)-1,u=L.state.doc.nodeAt(Tr);if(!u||u.type.name!=="amadeusColumnRow")return;let a=Tr+1,d=L.state.tr;for(let g=0;g<u.childCount;g++){const x=u.child(g);g===ze&&(d=d.setNodeMarkup(a,void 0,{...x.attrs,width:Ar(vt*un)})),g===ze+1&&(d=d.setNodeMarkup(a,void 0,{...x.attrs,width:Ar(vt*(1-un))})),a+=x.nodeSize}d.setMeta("amxColumns",!0),L.dispatch(d)}catch{}};window.addEventListener("pointermove",Mt),window.addEventListener("pointerup",Dn),window.addEventListener("pointercancel",zt),mr=zt};M.addEventListener("pointerdown",$r);const Ur=fl(()=>{q.title=we("blocklayer.dragHandle"),kt.title=we("blocklayer.addBelow"),Ue.title=we("blocklayer.cardGrab");for(const z of[q,kt,Ue])z.setAttribute("aria-label",z.title)});return{update:z=>{const L=n;if(!L)return;let re=!1;try{re=L.pos<=z.state.doc.content.size&&z.state.doc.nodeAt(L.pos)===L.node}catch{}re||V()},destroy:()=>{window.removeEventListener("mouseup",De),O?.remove(),O=null,wn&&clearTimeout(wn),uo(),R.removeEventListener("pointerdown",zn),R.removeEventListener("mousemove",Ot),b.dom.removeEventListener("keydown",Nr),b.dom.removeEventListener("contextmenu",Gn),R.removeEventListener("dragover",Zn,!0),R.removeEventListener("dragleave",fo,!0),R.removeEventListener("drop",Vn,!0),R.removeEventListener("dragstart",Oe,!0),ci.delete(b),R.removeEventListener("mouseleave",xr),M.removeEventListener("pointerdown",$r),Ur(),mr?.(),window.removeEventListener("scroll",Jn,{capture:!0}),window.removeEventListener("dragover",Hn),F.remove(),s?.remove(),s=null,ve?.remove(),ve=null,at?.remove(),at=null,o=null,de=null,ce=null,be=!1,n=null,t===b&&(t=null)}}}})),qn=bt(()=>{const b=R=>{if(at&&at.isConnected)return at;const T=document.createElement("div");return T.className="unified-drop-line",T.style.display="none",T.style.animation="none",(R.dom.parentElement??document.body).appendChild(T),at=T,T};return cg({onDrag:({view:R,event:T,pos:F})=>{if(ln(),(T.dataTransfer?Array.from(T.dataTransfer.types):[]).includes("Files"))return!1;if(X(R))return i(),!1;if(!R.dragging||!(R.state.selection instanceof ye)||R.state.selection.node.type===R.state.schema.nodes.amadeusCanvasCard)return!1;if(de||Ee||ce||be)return o=null,ne=null,i(),!1;const G=R.state.selection,q=es(R,{x:T.clientX,y:T.clientY});if(q&&q.node.type.name==="list_item"&&!(q.pos>=G.from&&q.pos<G.to)){const O=q.el.getBoundingClientRect();if(T.clientX>O.left+24&&T.clientY>O.top+O.height/2)return ne={targetPos:q.pos,el:q.el},o=null,i(),st(R,q.el,24),!1}if(ne=null,q&&!(q.pos>=G.from&&q.pos<G.to)&&oe(R,q.pos)){const O=q.el.getBoundingClientRect(),ge=T.clientX<=O.left+f?"left":T.clientX>=O.right-f?"right":null;if(ge)return o={targetPos:q.pos,side:ge},l(R,q.el,ge),!1}o=null,i();const U=R.state.doc.resolve(F);if(U.parent.type.name==="amadeusColumnRow")return!1;for(let O=U.depth;O>=1;O--){if(U.node(O).type.name!=="amadeusColumnCell")continue;const ge=R.nodeDOM(U.before(O));if(ge instanceof HTMLElement){const De=ge.getBoundingClientRect();if(T.clientX<De.left||T.clientX>De.right)return!1}break}return!0},onShow:({view:R,line:T})=>{Pt=!0;const F=b(R),V=Do(R.dom),G=Io(F),q=(T.p1.x-G.x)/V,U=(T.p2.x-G.x)/V,O=(T.p1.y-G.y)/V;F.style.display="block",F.style.width=`${Math.max(0,U-q)}px`,F.style.transform=`translate(${Math.round(q)}px, ${Math.round(O-1.5)}px)`},onHide:Vt})}),gt=bt(()=>new Ht({key:new jn("UNIFIED_DROP_GUARD"),props:{handleDrop:b=>b.dom.dataset.dragging==="true"&&!!b.dragging}})),ot=bt(()=>{let b=null,M=null;const R=()=>{b&&(b.style.display="none")};return new Ht({key:new jn("AMX_GAP_INSERT"),view:T=>{const F=()=>(b&&b.isConnected||(b=document.createElement("div"),b.className="amx-gap-insert",b.innerHTML="<span>+</span>",b.addEventListener("mousedown",q=>{q.preventDefault(),q.stopPropagation()}),b.addEventListener("click",q=>{if(q.preventDefault(),q.stopPropagation(),!M)return;let U=-1;T.state.doc.forEach((De,Ie)=>{U<0&&De.type.name==="amadeusCanvasCard"&&String(De.attrs.anchor)===M&&(U=Ie)});const O=T.state.schema.nodes.paragraph;if(U<0||!O){R();return}let ge=T.state.tr.insert(U,O.create());ge=ge.setSelection(Ae.create(ge.doc,U+1)).scrollIntoView(),T.dispatch(ge),T.focus(),R()}),(T.dom.parentElement??document.body).appendChild(b)),b),V=q=>{if(X(T)||T.dragging){R();return}const U=T.state.schema.nodes.amadeusCanvasCard;if(!U){R();return}const O=T.state.doc;let ge=0,De=null,Ie=null;for(let Ge=0;Ge<O.childCount&&!Ie;Ge++){const qt=O.child(Ge);if(qt.type===U){const Wt=T.nodeDOM(ge);if(Wt instanceof HTMLElement){if(Wt.classList.contains("amx-card-f0")&&!Wt.classList.contains("amx-card-f0-top")){De=Wt,ge+=qt.nodeSize;continue}if(De){const kt=De.getBoundingClientRect(),Ue=Wt.getBoundingClientRect();q.clientY>=kt.bottom-3&&q.clientY<=Ue.top+3&&q.clientX>=Math.min(kt.left,Ue.left)&&q.clientX<=Math.max(kt.right,Ue.right)&&(Ie={top:kt.bottom,bottom:Ue.top,left:Math.min(kt.left,Ue.left),right:Math.max(kt.right,Ue.right),anchor:String(qt.attrs.anchor)})}De=Wt}else De=null}else De=null;ge+=qt.nodeSize}if(!Ie){R();return}const Oe=F(),Pe=Do(T.dom),We=Io(Oe),Ye=(Ie.top+Ie.bottom)/2;Oe.style.display="flex",Oe.style.width=`${(Ie.right-Ie.left)/Pe}px`,Oe.style.transform=`translate(${Math.round((Ie.left-We.x)/Pe)}px, ${Math.round((Ye-We.y)/Pe-9)}px)`,M=Ie.anchor},G=T.dom.parentElement??T.dom;return G.addEventListener("mousemove",V),G.addEventListener("mouseleave",R),{update:(q,U)=>{q.state.doc.eq(U.doc)||R()},destroy:()=>{G.removeEventListener("mousemove",V),G.removeEventListener("mouseleave",R),b?.remove(),b=null}}}})}),Ft={listFoldedAt:(b,M)=>oc(b,M),unfoldList:(b,M)=>fa(b,M)},on=bt(()=>Fr({Tab:(b,M,R)=>aa(b,M,R,Ft),"Shift-Tab":(b,M)=>ca(b,M)})),Ut=bt(()=>new Ht({props:{decorations:b=>{const M=b.selection;if(!M.empty)return null;const R=M.$from,T=R.parent;if(!T.isTextblock||T.content.size>0)return null;for(let V=R.depth;V>=1;V--)if(R.node(V).type.name==="blockquote")return null;const F=T.type.name==="paragraph"?we("blocklayer.phParagraph"):T.type.name==="heading"?we("blocklayer.phHeading",{n:T.attrs.level??1}):null;return F?oo.create(b.doc,[ir.node(R.before(),R.after(),{class:"is-empty","data-placeholder":F})]):null}}})),Cn=["doc","amadeusColumnCell","bullet_list","ordered_list"],er=b=>{let M=b.depth;for(;M>=1&&!Cn.includes(b.node(M-1).type.name);)M--;return M},co=b=>{const M=b.selection;if(M instanceof ye){if(!M.node.isBlock)return null;if(Cn.includes(M.$from.parent.type.name))return{from:M.from,to:M.to};const V=er(M.$from);return V<1?null:{from:M.$from.before(V),to:M.$from.after(V)}}const{$from:R,$to:T}=M;if(!R.sameParent(T)){let V=R.sharedDepth(T.pos);for(;V>0&&!Cn.includes(R.node(V).type.name);)V--;return{from:R.before(V+1),to:T.after(V+1)}}const F=er(R);return F<1?null:{from:R.before(F),to:R.after(F)}},Zt=b=>(M,R)=>{const T=co(M);if(!T)return!1;const{from:F}=T,V=us(M,T.from,T.to),G=M.doc.resolve(F),q=G.parent,U=G.index(),O=M.doc.resolve(V).index()-1,ge=q.child(U),De=V>T.to&&ge.type.name==="heading"?Number(ge.attrs.level)||1:null;let Ie,Oe;if(b<0){if(U===0)return!0;Oe=F,Ie=F-q.child(U-1).nodeSize;let kt=null;if(De!=null)for(let Ue=U-1,Xn=F;Ue>=0;Ue--){const Lt=q.child(Ue);if(Xn-=Lt.nodeSize,Lt.type.name==="heading"&&(Number(Lt.attrs.level)||1)<=De){kt=Xn;break}}if(kt!=null)Ie=kt;else for(let Ue=Fs(M,Ie+1);Ue!=null&&Ue<Ie;Ue=Fs(M,Ie+1))Ie=Ue}else{if(O+1>=q.childCount)return!0;Ie=V;const kt=q.child(O+1);Oe=V+kt.nodeSize,De!=null&&kt.type.name==="heading"&&(Oe=wm(M.doc,Ie)??Oe)}if(!R)return!0;const Pe=V-F,We=M.doc.slice(F,V).content,Ye=b<0?Ie:Oe-Pe,Ge=M.tr.delete(F,V).insert(Ye,We),qt=Ye-F;Fo(M,Ge,{from:F,to:V,newStart:Ye}),Jo(M,Ge,{from:F,to:V,newStart:Ye});const Wt=M.selection;return Wt instanceof ye?Ge.setSelection(ye.create(Ge.doc,Wt.from+qt)):Ge.setSelection(Ae.create(Ge.doc,Wt.anchor+qt,Wt.head+qt)),r.getState(M)&&Ge.setMeta(r,!0),R(Ge.scrollIntoView()),!0},Wn=bt(()=>Fr({"Mod-Alt-ArrowUp":Zt(-1),"Mod-Alt-ArrowDown":Zt(1),"Mod-Shift-ArrowUp":Zt(-1),"Mod-Shift-ArrowDown":Zt(1)})),Sn=(b,M,R)=>{const T=b.selection,F=R?y(R):null;if(F){if(!M)return!0;const De=us(b,F.from,F.to),{content:Ie,minted:Oe}=Qo(b.doc,b.doc.slice(F.from,De).content);Oe.length&&e.onCardsMinted?.(Oe);const Pe=De-F.from,We=b.tr.insert(De,Ie);return Fo(b,We,{from:F.from,to:De,newStart:De,copy:!0}),Jo(b,We,{from:F.from,to:De,newStart:De}),We.setSelection(Ae.create(We.doc,T.anchor+Pe,T.head+Pe)),r.getState(b)&&We.setMeta(r,!0),M(We.scrollIntoView()),!0}if(T instanceof ye){if(!T.node.isBlock)return!1;if(!M)return!0;const De=us(b,T.from,T.to);if(De>T.to){const Pe=b.tr.insert(De,b.doc.slice(T.from,De).content);return Fo(b,Pe,{from:T.from,to:De,newStart:De,copy:!0}),Jo(b,Pe,{from:T.from,to:De,newStart:De}),Pe.setSelection(ye.create(Pe.doc,De)),M(Pe.scrollIntoView()),!0}let Ie=T.node;if(Ie.type.name==="amadeusCanvasCard"){const{content:Pe,minted:We}=Qo(b.doc,wr.from(Ie)),Ye=Pe.firstChild??Ie;Ie=Ye.type.create({...Ye.attrs,x:Number(Ye.attrs.x)+40,y:Number(Ye.attrs.y)+40},Ye.content,Ye.marks),We.length&&e.onCardsMinted?.(We)}const Oe=b.tr.insert(T.to,Ie);return Oe.setSelection(ye.create(Oe.doc,T.to)),M(Oe.scrollIntoView()),!0}if(!(T instanceof Ae)||!T.$from.sameParent(T.$to))return!1;const{$from:V}=T;let G=V.depth;for(;G>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard","bullet_list","ordered_list"].includes(V.node(G-1).type.name);)G--;if(G<1)return!1;const q=V.before(G),U=us(b,q,V.after(G));if(!b.doc.nodeAt(q))return!1;if(!M)return!0;const O=U-q,ge=b.tr.insert(U,b.doc.slice(q,U).content);return Fo(b,ge,{from:q,to:U,newStart:U,copy:!0}),Jo(b,ge,{from:q,to:U,newStart:U}),ge.setSelection(Ae.create(ge.doc,T.anchor+O,T.head+O)),M(ge.scrollIntoView()),!0},tr=bt(()=>Fr({"Mod-d":Sn})),Cr=(b,M,R,T=!1)=>{const F=R?y(R):null;if(!F)return!1;const V=b.doc.resolve(F.from);if(b.doc.resolve(F.to).index()-V.index()<2)return!1;const q=b.selection;if(q.from>F.from+1||q.to<F.to-1)return!1;if(!M)return!0;const U=b.doc.slice(F.from,F.to).content;return M(b.tr.delete(F.from,F.to).scrollIntoView()),T||e.onBlocksDeleted?.(U),!0},Vr=(b,M)=>{const R=b.selection;if(!(R instanceof ye))return!1;if(!M)return!0;const T=wr.from(R.node);return M(b.tr.deleteSelection().scrollIntoView()),e.onBlocksDeleted?.(T),!0},qr=(b,M,R)=>Cr(b,M,R)||Vr(b,M),Rn=bt(()=>Fr({Backspace:qr,Delete:qr})),En=bt(()=>new Ht({props:{handleDOMEvents:{cut:(b,M)=>{const R=M;if(!R.clipboardData||!Cr(b.state,void 0,b,!0))return!1;const{dom:T,text:F}=b.serializeForClipboard(b.state.selection.content());return R.preventDefault(),R.clipboardData.clearData(),R.clipboardData.setData("text/html",T.innerHTML),R.clipboardData.setData("text/plain",F),Cr(b.state,b.dispatch.bind(b),b,!0),!0}}}})),Sr=bt(()=>Fr({"Mod-a":(b,M)=>{const{$from:R}=b.selection,T=(G,q)=>b.selection.from<=G&&b.selection.to>=q,F=[];R.parent.isTextblock&&F.push([R.start(),R.end()]);let V=R.depth;for(;V>=1&&!["doc","amadeusColumnCell"].includes(R.node(V-1).type.name);)V--;V>=1&&F.push([R.start(V),R.end(V)]);for(const[G,q]of F)if(!T(G,q))return M?.(b.tr.setSelection(Ae.create(b.doc,G,q))),!0;return M?.(b.tr.setSelection(new wl(b.doc))),!0}})),io=b=>{const M=b.selection;if(!(M instanceof Ae)||M.empty)return[];const R=!!r.getState(b);if(!R&&M.$from.sameParent(M.$to))return[];const T=[],F=G=>{if(["bullet_list","ordered_list","table","blockquote","horizontal_rule","code_block","amadeusCanvasCard"].includes(G.type.name))return!0;if(G.type.name!=="paragraph")return!1;const q=G.textContent.trim();return/^!?\[\[[^\]\n]+\]\]$/.test(q)||G.childCount===1&&G.firstChild?.type.name==="image"},V=(G,q)=>{G.forEach((U,O)=>{const ge=q+O,De=ge+U.nodeSize;if(!(De<=M.from||ge>=M.to)){if(U.type.name==="amadeusColumnRow"){U.forEach((Ie,Oe)=>V(Ie,ge+1+Oe+1));return}(R||F(U))&&T.push([ge,De,R])}})};return V(b.doc,0),T},Wr=bt(()=>new Ht({key:r,state:{init:()=>!1,apply:(b,M,R)=>b.getMeta(r)===!0?!0:b.docChanged||b.selectionSet&&!b.selection.eq(R.selection)?!1:M},props:{decorations:b=>{const M=io(b);return M.length?oo.create(b.doc,M.map(([R,T,F])=>ir.node(R,T,{class:F?"amx-block-selected":"amx-rendered-selected"}))):null},attributes:b=>r.getState(b)&&io(b).length?{"data-blocksel":"true"}:{}}})),nt=bt(()=>Fr({Escape:(b,M)=>{const R=b.selection;if(R instanceof ye){const T=Ae.near(b.doc.resolve(R.from+1));return M?.(b.tr.setSelection(T)),!0}if(R instanceof Ae){const T=Li(b);return T==null?!1:(M?.(b.tr.setSelection(ye.create(b.doc,T))),!0)}return!1}})),wt=["doc","amadeusColumnCell"],Be=b=>{const M=b.selection;return M instanceof ye?M.node.isBlock:M instanceof Ae&&!M.empty&&!!r.getState(b)},gn=(b,M)=>{const R=b.resolve(M);if(wt.includes(R.parent.type.name)){const F=R.nodeAfter;return F?{from:M,to:M+F.nodeSize}:null}let T=R.depth;for(;T>=1&&!wt.includes(R.node(T-1).type.name);)T--;return T>=1?{from:R.before(T),to:R.after(T)}:null},$o=b=>{const M=b.selection,R=b.doc,T=gn(R,M instanceof ye?M.from:M.anchor),F=M instanceof ye?T:gn(R,M.head);return!T||!F||R.resolve(T.from).parent!==R.resolve(F.from).parent?null:{a:T,h:F}},lr=(b,M,R)=>{const T=b.doc,F=M.from===R.from?T.nodeAt(M.from):null;if(F&&ye.isSelectable(F))return b.tr.setSelection(ye.create(T,M.from));const V=R.from>=M.from,G=T.resolve(V?M.from+1:M.to-1),q=T.resolve(V?R.to-1:R.from+1);return b.tr.setSelection(Ae.between(G,q)).setMeta(r,!0)},Yn=b=>(M,R)=>{if(!Be(M))return!1;const T=$o(M);if(!T)return!1;const F=M.doc.resolve(T.h.from),V=F.parent;let G=F.index()+b,q=b>0?T.h.to:T.h.from;for(;G>=0&&G<V.childCount;){const U=V.child(G).nodeSize,O=b>0?q:q-U;if(Fs(M,O+1)==null)return R?.(lr(M,T.a,{from:O,to:O+U}).scrollIntoView()),!0;q=b>0?q+U:q-U,G+=b}return!0},Ln=b=>b.selection.$from.parent.type.name==="code_block";return{plugins:[bt(()=>new Ht({props:{handleKeyDown:ff({"Shift-ArrowDown":Yn(1),"Shift-ArrowUp":Yn(-1),"Mod-Alt-/":(b,M,R)=>{if(!R||!R.editable||!M)return!1;if(!Be(b)){const G=Li(b);if(G==null)return!1;M(b.tr.setSelection(ye.create(b.doc,G)))}const T=R.state,F=T.selection instanceof ye?R.nodeDOM(T.selection.from):null,V=F instanceof HTMLElement?F.getBoundingClientRect():R.coordsAtPos(T.selection.from);return e.onMenu({x:V.left,y:V.bottom+4,keyboard:!0,focus:"turnInto"}),!0},"Mod-]":(b,M,R)=>Ln(b)?!1:aa(b,M,R,Ft),"Mod-[":(b,M)=>Ln(b)?!1:ca(b,M)}),handleDOMEvents:{mousedown:(b,M)=>{if(!M.shiftKey||M.button!==0||!b.editable||!Be(b.state))return!1;const R=b.posAtCoords({left:M.clientX,top:M.clientY}),T=$o(b.state),F=R?gn(b.state.doc,R.pos):null;return!T||!F||b.state.doc.resolve(F.from).parent!==b.state.doc.resolve(T.a.from).parent?!1:(M.preventDefault(),b.dispatch(lr(b.state,T.a,F)),b.focus(),!0)}}}})),ct,qn,gt,ot,Wr,Ut,nt,on,Sr,Rn,En,Wn,tr,xy].flat(),getView:()=>t,topRangeOf:y,duplicate:b=>Sn(b.state,b.dispatch.bind(b),b),indent:(b,M)=>M>0?aa(b.state,b.dispatch.bind(b),b,Ft):ca(b.state,b.dispatch.bind(b))}}async function ky(e,t,n){const r=Ic(t);if(!r.length)return;const o=new Set(Ic(n).map(Ks)),s=r.filter(i=>!o.has(Ks(i)));if(!s.length)return;const l=(await bn.exclusiveAssets?.(e).catch(()=>[])??[]).filter(i=>s.some(f=>Cy(f,i)));l.length&&await Wp(e,l,{block:!0})==="with"&&await pf(l)}function Cy(e,t){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase(),r=t.replace(/\\/g,"/").toLowerCase();return n.includes("/")?r===n||r.endsWith(`/${n}`):Ks(e)===Ks(t)}function Di(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(`[](${Pc(c)??c})`)}return}const o=String(r.attrs?.src??"");o&&t.push(`??o})`),r.forEach(n)};return e.forEach(n),t.join(`
|
|
35
|
-
`)}const Hr=1,Jt=400,_r=720,Sy=/^<!--\s*a\s+([A-Za-z0-9_-]+)\s*-->$/,Ey=/^<!--\s*\/a\s+([A-Za-z0-9_-]+)\s*-->$/,ea=/^[A-Za-z0-9_-]+$/,cr=(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!==Hr||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"||!ea.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 My(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 zy=rc("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:cr(Number(t.x),0),y:cr(Number(t.y),0),w:cr(Number(t.w),Jt)||Jt,h:cr(Number(t.h),0),color:t.color??""}}}],toDOM:e=>{const t=Zs(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 Ny(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 S=null;if(N?.type==="html"&&typeof N.value=="string")S=N.value;else if(N?.type==="paragraph"&&Array.isArray(N.children)&&N.children.length===1){const _=N.children[0];_?.type==="html"&&typeof _.value=="string"&&(S=_.value)}if(S==null)return null;const A=Sy.exec(S.trim());return A?A[1]:null},l=N=>{let S=null;if(N?.type==="html"&&typeof N.value=="string")S=N.value;else if(N?.type==="paragraph"&&Array.isArray(N.children)&&N.children.length===1){const _=N.children[0];_?.type==="html"&&typeof _.value=="string"&&(S=_.value)}if(S==null)return null;const A=Ey.exec(S.trim());return A?A[1]:null},i=new Map(o.map(N=>[N.ref,N])),f=Zl(t?.cardColors),p=[];if(s.forEach((N,S)=>{const A=c(N);A&&p.push({id:A,idx:S})}),!p.length)return;const y=new Map;p.forEach(N=>y.set(N.id,(y.get(N.id)??0)+1));const E=[];for(const N of p){if((y.get(N.id)??0)>1||n.has(N.id)||!i.has(N.id))continue;let S=s.length,A=-1;for(let _=N.idx+1;_<s.length;_++){if(c(s[_])){S=_;break}if(l(s[_])===N.id){S=_,A=_;break}}E.push({id:N.id,open:N.idx,end:S,closer:A})}if(!E.length)return;const D=[];for(const N of[...E].reverse()){const S=i.get(N.id),A=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:cr(S.x,0),y:cr(S.y,0),w:cr(S.w,Jt)||Jt,h:cr(S.h,0),color:f&&Object.prototype.hasOwnProperty.call(f,N.id)&&Ql(f[N.id])?f[N.id]:typeof S.color=="string"?S.color:"",children:A.length?A:[{type:"paragraph",children:[]}]}),D.unshift(N.id)}r?.(D)}function $y(e,t,n){return[Cl("amadeusCanvasFold",()=>()=>r=>{Ny(r,e(),My(t()),n)})].flat()}function Ay(e){const t=[];return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const r=String(n.attrs.anchor);if(!ea.test(r))return;const o=cr(n.attrs.h,0);t.push({ref:r,x:cr(n.attrs.x,0),y:cr(n.attrs.y,0),w:cr(n.attrs.w,Jt)||Jt,...o>0?{h:o}:{}})}),t}function Zl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}const Ql=e=>e!==""&&e!=null;function Ii(e){const t=Object.create(null);return e.forEach(n=>{if(n.type.name!=="amadeusCanvasCard")return;const r=String(n.attrs.anchor);ea.test(r)&&Ql(n.attrs.color)&&(t[r]=n.attrs.color)}),t}function Ty(e,t,n,r){const o=Ay(e),s=_n(t);if(!s){if(t!=null)return t;if(!o.length)return null;const p=Ii(e);return JSON.stringify({v:Hr,mode:n??"canvas",main:{x:0,y:0,w:_r},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===_r)return null}const c={...s,v:Hr,cards:o},l=Ii(e);Object.keys(l).length?c.cardColors={...l}:(c.cardColors===void 0||Zl(c.cardColors))&&delete c.cardColors,n&&(c.mode=n),c.main||(c.main={x:0,y:0,w:_r}),c.elements?.length||delete c.elements;const i=Bt(c.tree),f=Object.keys(i);if(f.length){const p=new Set(o.map(D=>D.ref)),y=D=>typeof D=="string"&&ea.test(D)&&!p.has(D),E=new Set;for(const D of f)y(D)&&E.add(D),y(i[D])&&E.add(i[D]);if(E.size){const D=yg(i,E);Object.keys(D).length?c.tree=D:delete c.tree}}return JSON.stringify(c)}function jy(e,t){const n=_n(e);if(!n)return e??(t.length?JSON.stringify({v:Hr,mode:"canvas",main:{x:0,y:0,w:_r},cards:[],elements:t}):null);const r={...n,v:Hr,elements:t};return t.length||delete r.elements,JSON.stringify(r)}function Ry(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:Hr,main:n}):e??(!n.x&&!n.y&&n.w===_r?null:JSON.stringify({v:Hr,mode:"canvas",main:n,cards:[]}))}function Ly(e,t){const n=Object.keys(t).length,r=_n(e);if(!r)return e??(n?JSON.stringify({v:Hr,mode:"canvas",main:{x:0,y:0,w:_r},cards:[],tree:t}):null);const o={...r,v:Hr,tree:t};return n||delete o.tree,JSON.stringify(o)}const Dy=bt(()=>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,f)=>{if(i.type!==r)return;const p=String(i.attrs.anchor);c.has(p)?s.push(f):c.add(p),i.forEach((y,E)=>{if(y.type.name!=="amadeusColumnRow")return;const D=f+1+E;o.push({from:D,to:D+y.nodeSize,node:y,before:f})})}),!o.length&&!s.length)return null;let l=n.tr;for(const i of s){const f=l.doc.nodeAt(i);f?.type===r&&(l=l.setNodeMarkup(i,void 0,{...f.attrs,anchor:kr(l.doc)}))}for(const i of o)l=l.delete(l.mapping.map(i.from,1),l.mapping.map(i.to,-1)),l=l.insert(l.mapping.map(i.before),i.node);return l.steps.length?l:null}})),Iy=bt(()=>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(l=>{l.type===n?o(l.content).forEach(i=>c.push(i)):c.push(l.copy(o(l.content)))}),wr.fromArray(c)};return Oa.maxOpen(o(e.content))}}})),Py=bt(()=>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}})),Fy=[zy,Dy,Iy,Py].flat();function Oy(e){return[bt(()=>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 S=0;S<r.doc.childCount;S++){const A=r.doc.child(S);if(A.type===o){s=N;break}N+=A.nodeSize}}if(s<0)return null;const c=N=>N.depth>=1&&N.node(1).type===o?N.index(0):-1,l=N=>{if(N<0)return{from:0,to:s};let S=0;for(let A=0;A<N;A++)S+=r.doc.child(A).nodeSize;return{from:S+1,to:S+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),f=r.selection;if(f.empty||f instanceof ye)return null;if(f instanceof wl){if(t.some(A=>A.docChanged))return null;const N=Math.max(0,Math.min(n.selection.head,r.doc.content.size)),S=l(c(r.doc.resolve(N)));return S.from>=S.to?null:i(Ae.between(r.doc.resolve(S.from),r.doc.resolve(S.to),-1))}if(!(f instanceof Ae))return null;const p=r.doc.resolve(f.anchor),y=c(p);if(y===c(r.doc.resolve(f.head)))return null;const E=l(y),D=Math.max(E.from,Math.min(E.to,f.head));return i(Ae.between(p,r.doc.resolve(D),f.head>=f.anchor?-1:1))}}))].flat()}function _y(){return[bt(()=>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 ye){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?oo.create(e.doc,[ir.node(r,r+o.nodeSize,{class:"amx-card-active"})]):null}}}))].flat()}const By=6,Ky=2;function Hy(e){return[bt(()=>new Ht({key:new jn("AMX_CARD_DEPTH"),props:{decorations(t){const n=t.schema.nodes.amadeusCanvasCard;if(!n)return null;const r=Bt(e()?.tree);if(!Object.keys(r).length)return null;const o=new Set,s=[];t.doc.forEach((i,f,p)=>{if(i.type!==n)return;const y=String(i.attrs.anchor);o.add(y),s.push({pos:f,size:i.nodeSize,anchor:y,idx:p})});const c=[];for(let i=0;i<s.length;i++){const f=Ys(s,i,r);f>i+1&&c.push({start:i,end:f})}const l=[];for(let i=0;i<s.length;i++){const f=s[i],p=xg(r,f.anchor,o,By),y=c.filter(D=>D.start<=i&&i<D.end).slice(0,Ky);if(!p&&!y.length)continue;const E=[];p>0&&E.push("amx-card-child",`amx-card-d${p}`),y.forEach((D,N)=>{E.push(`amx-card-f${N}`),D.start===i&&E.push(`amx-card-f${N}-top`),D.end-1===i&&E.push(`amx-card-f${N}-end`)}),l.push(ir.node(f.pos,f.pos+f.size,{class:E.join(" ")}))}return l.length?oo.create(t.doc,l):null}}}))].flat()}const Vy=200;function qy(e){return[bt(()=>new Ht({key:new jn("AMX_CANVAS_HISTORY_TIMELINE"),state:{init:(t,n)=>({depth:Ia(n)}),apply:(t,n,r,o)=>{const s=Ia(o);return t.docChanged&&s>n.depth&&!fd(t)&&(e.log.push("pm"),e.log.length>Vy&&e.log.shift(),e.future.length=0),s===n.depth?n:{depth:s}}}}))].flat()}vn({"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 jt=e=>`c:${e}`,hn=e=>`e:${e}`,eu=e=>`t:${e}`,Ze=e=>e.slice(2),Ts=e=>typeof e=="number"&&Number.isFinite(e)?e:null,Ho=e=>typeof e=="string"&&e?e:null,Sa=e=>Zs(e)?e:null,mc=e=>{const t=Zs(e);return t?{"data-color":e,style:{"--amx-color":t}}:{}};function Us(e){if(!e||typeof e!="object")return null;const t=e,n=Ho(t.ref);if(n)return{ref:n};const r=Ho(t.id);return r?{id:r}:t.main===!0?{main:!0}:null}const xo=e=>e.ref?jt(e.ref):e.id?hn(e.id):e.main?ie: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=Ho(o.id);if(!s||n.has(s))continue;if(o.type==="connector"){const p=Us(o.from),y=Us(o.to);if(!p||!y)continue;n.add(s),t.push({kind:"connector",id:s,from:p,to:y,label:Ho(o.label),color:Sa(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=Ts(o.x),l=Ts(o.y),i=Ts(o.w),f=Ts(o.h);if(!(c==null||l==null||i==null||f==null||i<=0||f<=0)){if(n.add(s),o.type==="frame"){t.push({kind:"frame",id:s,x:c,y:l,w:i,h:f,title:Ho(o.title),color:Sa(o.color)});continue}t.push({kind:o.type==="text"?"text":"shape",id:s,x:c,y:l,w:i,h:f,shape:o.shape==="ellipse"?"ellipse":"rect",text:Ho(o.text),color:Sa(o.color)})}}return t}function Pi(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 pc(e,t){const n=Pi(e,t),r=Pi(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),l=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+l*s},c2:o?{x:r.x-c*s,y:r.y}:{x:r.x,y:r.y-l*s},p2:r}}function Wy(e,t){const{p1:n,c1:r,c2:o,p2:s}=pc(e,t),c=[n.x,r.x,o.x,s.x],l=[n.y,r.y,o.y,s.y],i=Math.min(...c),f=Math.min(...l);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:f,w:Math.max(1,Math.max(...c)-i),h:Math.max(1,Math.max(...l)-f)}}}function js(e,t,n,r=8){const{p1:o,c1:s,c2:c,p2:l}=pc(e,t);let i=o.x,f=o.y;for(let p=1;p<=24;p++){const y=p/24,E=1-y,D=E*E*E*o.x+3*E*E*y*s.x+3*E*y*y*c.x+y*y*y*l.x,N=E*E*E*o.y+3*E*E*y*s.y+3*E*y*y*c.y+y*y*y*l.y,S=D-i,A=N-f,_=S*S+A*A,X=_?Math.max(0,Math.min(1,((n.x-i)*S+(n.y-f)*A)/_)):0;if(Math.hypot(i+X*S-n.x,f+X*A-n.y)<=r)return!0;i=D,f=N}return!1}function tu(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 Yy(e,t){const n=[...t].flatMap(l=>l===ie?[ie]:l.startsWith("c:")?[Ze(l)]:[]),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[l,i]of e){s.set(l,i);const f=c.get(i);f?f.push(l):c.set(i,[l])}for(const l of n){const i=new Set;let f=l;for(;!i.has(f);){i.add(f),r.add(f);const E=s.get(f);if(!E)break;o.add(f),r.add(E),f=E}const p=[l],y=new Set;for(;p.length;){const E=p.shift();if(!y.has(E)){y.add(E);for(const D of c.get(E)??[])o.add(D),r.add(D),p.push(D)}}}return{nodes:r,edgeChildren:o}}const Fi=(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 mn(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 pn(e){const t=e?.querySelector(".ProseMirror");return t?{x:t.offsetLeft,y:t.offsetTop,w:t.offsetWidth,h:t.offsetHeight}:null}function Oi(e,t=!1){const n=i=>!t||!i.closest(".amx-ucard"),r=i=>(i.innerText||i.textContent||"").split(/\r?\n/).map(f=>f.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 l=s.find((i,f)=>i!==c&&(o.length>0||f>0))??null;return{title:c,detail:l}}function Xy(e,t){const n=e.classList.contains("amx-stage-overview");n&&e.classList.remove("amx-stage-overview");try{const r=[];for(const[l,i]of mn(e)){const f=e.querySelector(`.amx-ucard[data-anchor="${CSS.escape(l)}"]`),p=f?Oi(f):null;f&&p&&r.push({key:jt(l),anchor:l,...p,h:i.h,autoHeight:Number(f.dataset.h)<=0})}const o=e.querySelector(".ProseMirror"),s=pn(e),c=o?Oi(o,!0):null;return s&&c&&r.push({key:ie,anchor:ie,...c,h:s.h,autoHeight:t}),r}finally{n&&e.classList.add("amx-stage-overview")}}function Uy(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 eo=24;function Eo(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(hn(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(eo,o.w+t.size.dw),h:Math.max(eo,o.h+t.size.dh)}),n.set(r.id,o)}return n}function Gy({elements:e,hostRef:t,documentKey:n,sel:r,editing:o,tree:s,ghost:c,marquee:l,attach:i,overviewScale:f,mainAutoHeight:p=!0,preview:y,guides:E}){const{t:D}=nn(),N=k.useMemo(()=>Tn(e),[e]),S=k.useMemo(()=>tu(s),[s]),A=k.useMemo(()=>Yy(S,r),[S,r]),_=A.edgeChildren,[X,te]=k.useState(0),B=N.length+S.length,Y=[...r].filter(j=>j.startsWith("c:")).map(Ze),Te=r.has(ie),Ve=B+Y.length+(Te?1:0),h=f!=null&&f>0,[Se,lt]=k.useState({documentKey:"",items:[]});k.useEffect(()=>{const j=t.current;if(!j)return;let J=0;const se=new ResizeObserver(()=>He()),xe=new Set,Qe=()=>{const at=new Set(j.querySelectorAll(".amx-ucard")),Vt=j.querySelector(".ProseMirror");Vt&&at.add(Vt);for(const Pt of at)xe.has(Pt)||(se.observe(Pt,{box:"border-box"}),xe.add(Pt));for(const Pt of[...xe])at.has(Pt)||(se.unobserve(Pt),xe.delete(Pt))},He=()=>{cancelAnimationFrame(J),J=requestAnimationFrame(()=>{Qe(),te(at=>at+1)})};He();const Rt=new MutationObserver(He);return Rt.observe(j,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["style","data-x","data-y","data-w","data-h"]}),se.observe(j),()=>{cancelAnimationFrame(J),Rt.disconnect(),se.disconnect()}},[t]);const ne=k.useMemo(()=>mn(t.current),[t,n,Se.documentKey,X,Ve,c]),de=k.useMemo(()=>Eo(N,c),[N,c]),ce=pn(t.current);k.useLayoutEffect(()=>{if(!h)return;const j=t.current,J=j?.querySelector(".ProseMirror");if(!j||!J||J.childElementCount===0)return;const se=Xy(j,p);lt(xe=>xe.documentKey===n&&Uy(xe.items,se)?xe:{documentKey:n,items:se})},[n,t,p,h,X]);const be=Se.documentKey===n?Se.items:[],Ee=new Set([...Y,...Te?[ie]:[]]),ve=h?be.flatMap(j=>{if(Ee.has(j.anchor))return[];const J=j.anchor===ie?ce:ne.get(j.anchor);return J?[{...j,box:J}]:[]}):[],Ce=t.current?.dataset.amxDragscope,st=h&&Ce?be.flatMap(j=>{const J=`.amx-stage[data-amx-dragscope="${CSS.escape(Ce)}"].amx-stage-overview`;if(Ee.has(j.anchor))return[];if(j.anchor===ie)return[`${J} .ProseMirror:not(.unified-embed .ProseMirror) > :not(.amx-ucard){display:none!important;}`,...p?[`${J} .ProseMirror:not(.unified-embed .ProseMirror){height:${j.h}px;}`]:[]];const se=`${J} .amx-ucard[data-anchor="${CSS.escape(j.anchor)}"]`;return[`${se} > *{display:none!important;}`,...j.autoHeight?[`${se}[data-h="0"]{height:${j.h}px;}`]:[]]}).join(`
|
|
36
|
-
`):"",Z=A.nodes.size>0&&Ce?(()=>{const j=`.amx-stage[data-amx-dragscope="${CSS.escape(Ce)}"]:not(.amx-stage-off)`,J=[...ne.keys()].filter(xe=>!A.nodes.has(xe)).flatMap(xe=>[`${j} .amx-ucard[data-anchor="${CSS.escape(xe)}"]`,`${j} .amx-card-overview[data-card-label="${CSS.escape(xe)}"]`]),se=J.length?[`${J.join(`,
|
|
37
|
-
`)}{opacity:0.44;}`]:[];if(!A.nodes.has(ie)){const xe=`${j} .ProseMirror:not(.unified-embed .ProseMirror)`;se.push(`${xe}{background-color:color-mix(in srgb,var(--bg) 44%,transparent);border-color:color-mix(in srgb,var(--border) 44%,transparent);box-shadow:none;}`,`${xe}>:not(.amx-ucard){opacity:0.44;}`,`${j} .amx-card-overview[data-card-label="${CSS.escape(ie)}"]{opacity:0.44;}`)}return se.push(`${j} .amx-el-conn.is-tree:not(.is-related){opacity:0.18;}`),se.join(`
|
|
38
|
-
`)})():"",oe=j=>j.ref!=null?ne.get(j.ref)??null:j.id!=null?de.get(j.id)??null:j.main?ce:null,je=j=>j===ie?ce:j.startsWith("c:")?ne.get(Ze(j))??null:de.get(Ze(j))??null;return m.jsxs("div",{className:"amx-el-layer",children:[st?m.jsx("style",{"data-amx-overview-rules":!0,children:st}):null,Z?m.jsx("style",{"data-amx-related-focus-rules":!0,children:Z}):null,N.filter(j=>j.kind==="frame").map(j=>m.jsx(ex,{el:j,box:de.get(j.id),sel:r.has(hn(j.id))},j.id)),N.filter(j=>j.kind!=="frame").map(j=>j.kind==="connector"?m.jsx(Rs,{el:j,a:oe(j.from),b:oe(j.to),sel:r.has(hn(j.id))},j.id):m.jsx(tx,{el:j,box:de.get(j.id),sel:r.has(hn(j.id))},j.id)),r.size===1&&[...r][0].startsWith("e:")&&de.has(Ze([...r][0]))?m.jsxs(m.Fragment,{children:[m.jsx(Zy,{id:Ze([...r][0]),box:de.get(Ze([...r][0]))}),m.jsx(Ea,{node:[...r][0],box:de.get(Ze([...r][0]))})]}):null,(()=>{const j=r.size===1?[...r][0]:null,J=j?.startsWith("e:")?N.find(Rt=>Rt.kind==="connector"&&Rt.id===Ze(j)):null,se=J?oe(J.from):null,xe=J?oe(J.to):null;if(!J||!se||!xe)return null;const{p1:Qe,p2:He}=pc(se,xe);return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"amx-conn-end","data-conn-end":"from","data-el":J.id,style:{left:`${Qe.x}px`,top:`${Qe.y}px`}}),m.jsx("div",{className:"amx-conn-end","data-conn-end":"to","data-el":J.id,style:{left:`${He.x}px`,top:`${He.y}px`}})]})})(),S.map(([j,J])=>{const se=J===ie?ce:ne.get(J),xe=ne.get(j),Qe=J===ie?{main:!0}:{ref:J};return se&&xe?m.jsx(Rs,{el:{kind:"connector",id:`t:${j}`,from:Qe,to:{ref:j},label:null},a:se,b:xe,sel:r.has(eu(j)),related:_.has(j),tree:!0},`t:${j}`):null}),Y.map(j=>{const J=ne.get(j);return J?m.jsx("div",{className:`amx-el-selbox${o===j?" is-editing":""}`,"data-anchor":j,style:{left:`${J.x}px`,top:`${J.y}px`,width:`${J.w}px`,height:`${J.h}px`},children:r.size===1&&o!==j?m.jsxs(m.Fragment,{children:[m.jsx(_i,{anchor:j}),m.jsx(Bi,{node:j}),m.jsx(Ea,{node:jt(j)})]}):null},`sel:${j}`):null}),Te&&ce?m.jsx("div",{className:`amx-el-selbox${o===ie?" is-editing":""}`,"data-main-sel":!0,style:{left:`${ce.x}px`,top:`${ce.y}px`,width:`${ce.w}px`,height:`${ce.h}px`},children:r.size===1&&o!==ie?m.jsxs(m.Fragment,{children:[m.jsx(_i,{anchor:ie}),m.jsx(Bi,{node:ie}),m.jsx(Ea,{node:ie})]}):null}):null,ve.map(j=>{const J=j.box.h*f,se=J<44?"title":J<60?"summary":"full",xe=se==="title"?Math.max(8,Math.min(12,(J-3)/1.2)):12;return m.jsxs("div",{className:"amx-card-overview","data-card-label":j.anchor,"data-overview-density":se,style:{left:`${j.box.x}px`,top:`${j.box.y}px`,width:`${j.box.w}px`,height:`${j.box.h}px`,"--amx-overview-inv":String(1/f),"--amx-overview-title-screen":`${xe}px`},children:[m.jsx("span",{className:"amx-card-overview-title",children:j.title}),j.detail?m.jsx("span",{className:"amx-card-overview-detail",children:j.detail}):null]},`overview:${j.key}`)}),y?(()=>{const j=je(y.from);if(!j)return null;const J=y.over?je(y.over):null,se=J??{x:y.x,y:y.y,w:1,h:1};return m.jsxs(m.Fragment,{children:[m.jsx(Rs,{el:{kind:"connector",id:"~preview",from:{},to:{},label:null},a:j,b:se,sel:!1,preview:!0}),m.jsx("div",{className:"amx-conn-target",style:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}}),J?m.jsx("div",{className:"amx-conn-target",style:{left:`${J.x}px`,top:`${J.y}px`,width:`${J.w}px`,height:`${J.h}px`}}):null]})})():null,i?(()=>{const j=i.node===ie?ce:ne.get(i.node),J=ne.get(i.source);if(!j)return null;const se=3,xe=22,Qe=i.side==="n"||i.side==="s",He=i.side==="w"?j.x:i.side==="e"?j.x+j.w:j.x+j.w/2,Rt=i.side==="n"?j.y:i.side==="s"?j.y+j.h:j.y+j.h/2;return m.jsxs(m.Fragment,{children:[J?m.jsx(Rs,{el:{kind:"connector",id:"~attach",from:{ref:i.source},to:i.node===ie?{main:!0}:{ref:i.node},label:null},a:J,b:j,sel:!1,preview:!0}):null,m.jsx("div",{className:`amx-el-attach-target is-${i.rel}`,style:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}}),m.jsx("div",{className:`amx-el-attach is-${i.rel}`,"data-attach":i.side,style:{left:`${i.side==="e"?j.x+j.w-se:i.side==="w"?j.x:j.x+(j.w-xe)/2}px`,top:`${i.side==="s"?j.y+j.h-se:i.side==="n"?j.y:j.y+(j.h-xe)/2}px`,width:`${Qe?xe:se}px`,height:`${Qe?se:xe}px`}}),m.jsxs("div",{className:`amx-el-attach-label is-${i.rel}`,style:{left:`${He}px`,top:`${Rt}px`},children:[i.count&&i.count>1?`${D("canvasel.attach.count",{n:i.count})} · `:"",i.rel==="child"?D("canvasel.attach.child"):D("canvasel.attach.sibling")]})]})})():null,E?.map((j,J)=>m.jsx("div",{className:`amx-el-guide is-${j.dir}`,style:{left:`${j.x}px`,top:`${j.y}px`,width:`${j.w}px`,height:`${j.h}px`}},`guide:${J}`)),l?m.jsx("div",{className:"amx-el-marquee",style:{left:`${l.x}px`,top:`${l.y}px`,width:`${l.w}px`,height:`${l.h}px`}}):null]})}const nu=["nw","ne","sw","se"],Jy=["n","e","s","w",...nu];function _i({anchor:e}){return m.jsx(m.Fragment,{children:Jy.map(t=>m.jsx("div",{className:`amx-card-size-grip is-${t}`,"data-card-grip":e,"data-card-edge":t},t))})}function Zy({id:e,box:t}){return m.jsx(m.Fragment,{children:nu.map(n=>m.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 Bi({node:e}){const{t}=nn();return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"amx-el-add is-child","data-add":"child","data-node":e,title:t("canvasel.add.child"),children:"+"}),m.jsx("div",{className:"amx-el-add is-sibling","data-add":"sibling","data-node":e,title:t("canvasel.add.sibling"),children:"+"})]})}const Qy=["n","e","s","w"];function Ea({node:e,box:t}){const{t:n}=nn(),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 m.jsx(m.Fragment,{children:Qy.map(o=>m.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 ex({el:e,box:t,sel:n}){const r=mc(e.color);return m.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:m.jsx("div",{className:"amx-el-frame-bar","data-el":e.id,children:e.title??"Frame"})})}function tx({el:e,box:t,sel:n}){const r=e.kind==="text"?"amx-el-text":e.shape==="ellipse"?"amx-el-ellipse":"amx-el-rect",o=mc(e.color);return m.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 Rs({el:e,a:t,b:n,sel:r,related:o,tree:s,preview:c}){if(!t||!n)return null;const l=Wy(t,n),i=14,f={x:l.box.x-i,y:l.box.y-i,w:l.box.w+i*2,h:l.box.h+i*2},p=9,y=4.5,E=(A,_)=>{const X=Math.cos(_),te=Math.sin(_);return[`${A.x},${A.y}`,`${A.x-p*X+y*te},${A.y-p*te-y*X}`,`${A.x-p*X-y*te},${A.y-p*te+y*X}`].join(" ")},D=!s&&e.toEnd!=="none",N=!s&&e.fromEnd==="arrow",S=mc(e.color);return m.jsxs(m.Fragment,{children:[m.jsxs("svg",{className:`amx-el-conn${r?" is-sel":""}${o?" is-related":""}${s?" is-tree":""}${c?" is-preview":""}`,"data-el":e.id,"data-color":S["data-color"],style:{left:`${f.x}px`,top:`${f.y}px`,width:`${f.w}px`,height:`${f.h}px`,...S.style},viewBox:`${f.x} ${f.y} ${f.w} ${f.h}`,children:[o?m.jsx("path",{className:"amx-el-conn-halo",d:l.d}):null,m.jsx("path",{className:"amx-el-conn-core",d:l.d}),D?m.jsx("polygon",{points:E(l.tip,l.ang)}):null,N?m.jsx("polygon",{points:E(l.tail,l.tailAng)}):null]}),e.label?m.jsx("div",{className:`amx-el-label${r?" is-sel":""}`,"data-color":S["data-color"],style:{left:`${l.mid.x}px`,top:`${l.mid.y}px`,...S.style},children:e.label}):null]})}const Ls=e=>typeof e=="number"&&Number.isFinite(e)?e:null,ts=e=>typeof e=="string"&&e?e:null,Ma=e=>Zs(e)?e:null,Ki=e=>e==="none"||e==="arrow"?e:null,ns=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 nx(e){const t=/^!\[\[([^\]\n]+)\]\]$/.exec(e.trim());return t?t[1]:null}function Hi(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 rx(e){const t=[],n=[],r=[],o=new Map,s=e.pages?[...e.pages].sort():[],c=Array.isArray(e.elements)?e.elements:[],l=new Set,i=[];for(const S of c){if(!S||typeof S!="object"||Array.isArray(S))continue;const A=S,_=ts(A.id);if(!_||l.has(_))continue;if(A.type==="connector"){l.add(_),i.push(A);continue}if(A.type!=="shape"&&A.type!=="text"&&A.type!=="frame")continue;const X=Ls(A.x),te=Ls(A.y),B=Ls(A.w),Y=Ls(A.h);if(X==null||te==null||B==null||Y==null||B<=0||Y<=0)continue;l.add(_);const Te=`el-${_}`,Ve={x:X,y:te,w:B,h:Y};o.set(Te,Ve);const h=Ma(A.color);if(A.type==="frame"){const Se=ts(A.title);t.push({id:Te,type:"group",...ns(Ve),...Se?{label:Se}:{},...h?{color:h}:{}})}else n.push({id:Te,type:"text",...ns(Ve),text:typeof A.text=="string"?A.text:"",...h?{color:h}:{}})}for(const S of e.cards){const A=`card-${S.ref}`;o.set(A,S);const _=Ma(S.color),X=nx(S.md),te=X&&s.length?ms(il(X),s,e.sourcePath):null;if(X&&te){const B=X.split("|")[0],Y=B.indexOf("#"),Te=Y>=0?B.slice(Y).trim():"";r.push({id:A,type:"file",...ns(S),file:te,...Te.length>1?{subpath:Te}:{},..._?{color:_}:{}})}else r.push({id:A,type:"text",...ns(S),text:S.md,..._?{color:_}:{}})}const f=[],p=S=>{if(!S||typeof S!="object")return null;const A=S,_=ts(A.ref)?`card-${A.ref}`:ts(A.id)?`el-${A.id}`:A.main===!0?"main":null;return _&&(o.has(_)||_==="main")?_:null};e.main&&o.set("main",e.main);let y=!1;const E=S=>{const A=o.get(S.fromNode),_=o.get(S.toNode);!A||!_||((S.fromNode==="main"||S.toNode==="main")&&(y=!0),f.push({...S,fromSide:Hi(A,_),toSide:Hi(_,A)}))};for(const S of i){const A=p(S.from),_=p(S.to);if(!A||!_||A===_)continue;const X=Ki(S.fromEnd),te=Ki(S.toEnd),B=ts(S.label),Y=Ma(S.color);E({id:`edge-${S.id}`,fromNode:A,toNode:_,...X?{fromEnd:X}:{},...te?{toEnd:te}:{},...B?{label:B}:{},...Y?{color:Y}:{}})}const D=e.tree&&typeof e.tree=="object"&&!Array.isArray(e.tree)?e.tree:{};for(const S of Object.keys(D)){const A=D[S];if(typeof A!="string"||!A||A===S)continue;const _=A==="m:"?"main":`card-${A}`,X=`card-${S}`;o.has(X)&&E({id:`tree-${S}`,fromNode:_,toNode:X,toEnd:"none"})}const N=[...t,...n];return e.main&&(e.main.md.trim()||y)&&N.push({id:"main",type:"text",...ns(e.main),text:e.main.md}),N.push(...r),{nodes:N,edges:f}}const ox=e=>`${JSON.stringify(e,null," ")}
|
|
39
|
-
`;function sx(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 ax(e,t,n){for(let r=1;r<=50;r++){const o=sx(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")}vn({"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 cx=[{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"}],Vi=[{id:"end",from:"none",to:"arrow",nameKey:"canvasstage.ends.end",icon:m.jsx(Mp,{size:13})},{id:"start",from:"arrow",to:"none",nameKey:"canvasstage.ends.start",icon:m.jsx(Np,{size:13})},{id:"both",from:"arrow",to:"arrow",nameKey:"canvasstage.ends.both",icon:m.jsx(Sp,{size:13})},{id:"none",from:"none",to:"none",nameKey:"canvasstage.ends.none",icon:m.jsx(Wm,{size:13})}],ix=2,Os=168,ru=72,za=320,qi=12,rs=".amx-el-shape, .amx-el-frame-bar",Wi="button, a[href], input, select, textarea",lx='li[data-item-type="task"], .wikilink';function ux(e,t){const n=e.closest(lx);return n?n.tagName!=="LI"||t-n.getBoundingClientRect().left<=2:!1}const Na=e=>e.kind==="connector"?"label":e.kind==="frame"?"title":"text",$a=e=>we(e.kind==="connector"?"canvasstage.textTitle.connector":e.kind==="frame"?"canvasstage.textTitle.frame":"canvasstage.textTitle.element"),Ds=e=>[...Eo(Tn(e).filter(t=>t.kind!=="frame"),null).values()],Yi=50,Aa=new Set(["rect","ellipse","frame"]),os={rect:"rect",ellipse:"ellipse",text:"text"};let dx=0;const Xi=(e,t,n,r,o,s=Os)=>$f(e,t,n,r,o,s,ru);function hc(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 hc(e.state.doc)}const Za=(e,t,n)=>Ys(e,t,n);function ou(e,t,n){const r=hc(e),o=r.findIndex(c=>c.anchor===n);if(o<0)return e.content.size;const s=r[Za(r,o,t)-1];return s.pos+s.node.nodeSize}function Ui(e,t,n,r){const o=hc(e.doc),s=o.findIndex(E=>E.anchor===n);if(s<0)return e;const c=Za(o,s,t),l=o[s].pos,i=o[c-1],f=i.pos+i.node.nodeSize;let p;if(r){const E=o.findIndex(S=>S.anchor===r);if(E<0||E>=s&&E<c)return e;const D=Za(o,E,t);if(s>E&&s<D)return e;const N=o[D-1];p=N.pos+N.node.nodeSize}else if(p=e.doc.content.size,f===p)return e;const y=wr.fromArray(o.slice(s,c).map(E=>E.node));return e.delete(l,f).insert(p>f?p-(f-l):p,y)}function to(e,t){e.dispatch(Vs(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 l=t.get(c.anchor);l&&(o=o.setNodeMarkup(c.pos,void 0,{...c.node.attrs,...l}),s=!0)}s&&(n?to(e,o):e.dispatch(o.setMeta("amxCanvas",!0).setMeta("addToHistory",!1)))}function fx(e,t,n,r){const o=On(e).find(l=>l.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 Gi(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?wr.fromArray(t):void 0}function Ji(e,t=!1){return e.kind==="note"?`${t?"":"!"}[[${e.path.replace(/\.md$/i,"")}]]`:e.kind==="session"?`[[session:${e.id}|${e.title}]]`:e.path}const Zi="application/x-amx-canvas";let Ta=null;function mx(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 l=c;return!l||typeof l.ref!="string"||!o(l.x)||!o(l.y)||!o(l.w)||l.w<=0?[]:[{ref:l.ref,x:l.x,y:l.y,w:l.w,h:o(l.h)&&l.h>0?l.h:0,...typeof l.color=="string"?{color:l.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 ja=(e,t)=>({x:e.x-t,y:e.y-t,w:e.w+t*2,h:e.h+t*2}),Qi=(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 px({hostRef:e,vp:t,elements:n,ghost:r,onCenter:o}){const[,s]=k.useState(0);k.useEffect(()=>{const y=e.current;if(!y)return;let E=0;const D=new Set,N=new ResizeObserver(()=>A()),S=()=>{const X=new Set(y.querySelectorAll(".amx-ucard")),te=y.querySelector(".ProseMirror");te&&X.add(te);for(const B of X)D.has(B)||(N.observe(B,{box:"border-box"}),D.add(B));for(const B of[...D])X.has(B)||(N.unobserve(B),D.delete(B))},A=()=>{cancelAnimationFrame(E),E=requestAnimationFrame(()=>{S(),s(X=>X+1)})},_=new MutationObserver(A);return _.observe(y,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["data-x","data-y","data-w"]}),N.observe(y),A(),()=>{cancelAnimationFrame(E),_.disconnect(),N.disconnect()}},[e]);const c=e.current;if(!c)return null;const l=[];for(const[y,E]of mn(c))l.push({key:jt(y),kind:"card",box:E});const i=pn(c);i&&l.push({key:ie,kind:"main",box:i});const f=Tn(n),p=Eo(f,r);for(const y of f){if(y.kind==="connector")continue;const E=p.get(y.id);E&&l.push({key:hn(y.id),kind:y.kind==="frame"?"frame":"shape",box:E})}return m.jsx(jm,{hostRef:e,vp:t,items:l,onCenter:o})}function hx({path:e,vaultRoot:t=null,active:n,getView:r,main:o,mainStored:s,elements:c,tree:l,onElements:i,onTree:f,onMain:p,timeline:y,histStepRef:E,onCommit:D,saveFile:N,parseMd:S,serializeMd:A,onBlocksDeleted:_,revealSelection:X=0,readOnly:te=!1,notePages:B,exportRef:Y,storedMd:Te,children:Ve}){const h=k.useRef(null),{t:Se}=nn(),lt=hf(t,e),[ne,de]=k.useState(()=>Yc(lt)??{x:0,y:0,z:1}),ce=k.useRef(ne);ce.current=ne;const[be,Ee]=k.useState(Rm),[ve,Ce]=k.useState(Lm),[st,Z]=k.useState(li);k.useEffect(()=>Dm(()=>Z(li())),[]);const[oe,je]=k.useState(Im),j=k.useRef(oe);j.current=oe;const[J,se]=k.useState(Pm),xe=k.useRef(J);xe.current=J;const[Qe,He]=k.useState(null),Rt=k.useCallback(u=>{j.current=u,je(u),Fm(u)},[]),[at,Vt]=k.useState("select"),Pt=k.useRef("select"),St=k.useRef(te);St.current=te;const ln=k.useCallback(u=>{Pt.current=u,Vt(u)},[]),[ct,qn]=k.useState([]),gt=k.useRef([]),ot=k.useCallback(u=>{const a=typeof u=="function"?u(gt.current):u;gt.current=a,qn(a)},[]),[Ft,on]=k.useState(null),Ut=k.useRef(null),Cn=k.useCallback(u=>{Ut.current=u,on(u)},[]),[er,co]=k.useState(null),Zt=k.useRef(null),Wn=k.useCallback(u=>{Zt.current=u,co(u)},[]),Sn=k.useRef({held:!1,used:!1}),[tr,Cr]=k.useState(!1);k.useEffect(()=>{const u=h.current;if(!er||!u)return;const a=u.dataset.amxDragscope;if(!a)return;const d=document.createElement("style");return d.textContent=er===ie?`.amx-stage[data-amx-dragscope="${a}"] .ProseMirror{cursor:text;}`:`.amx-stage[data-amx-dragscope="${a}"] .amx-ucard[data-anchor="${CSS.escape(er)}"]{cursor:text;}`,document.head.appendChild(d),()=>d.remove()},[er]);const Vr=k.useRef(0),[qr,Rn]=k.useState(null),[En,Sr]=k.useState(null),[io,Wr]=k.useState(null),[nt,wt]=k.useState(null),[Be,gn]=k.useState(null),[$o,lr]=k.useState(!1),Yn=k.useRef(0),Ln=k.useCallback(()=>{cancelAnimationFrame(Yn.current),Yn.current=0,lr(!1)},[]);k.useEffect(()=>()=>cancelAnimationFrame(Yn.current),[]);const Mn=k.useRef({raf:0,animations:[]}),b=k.useCallback(()=>{cancelAnimationFrame(Mn.current.raf),Mn.current.raf=0;const u=Mn.current.animations.splice(0);for(const a of u)a.cancel()},[]),M=k.useCallback(u=>{const a=h.current;b(),!(!a||!u.length||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Mn.current.raf=requestAnimationFrame(()=>{Mn.current.raf=0;let d=0;const g=x=>{Mn.current.animations.push(x);const v=()=>{Mn.current.animations=Mn.current.animations.filter(C=>C!==x)};x.addEventListener("finish",v,{once:!0}),x.addEventListener("cancel",v,{once:!0})};for(const x of u){const v=a.querySelector(`.amx-ucard[data-anchor="${CSS.escape(x.anchor)}"]`),C=Math.hypot(x.x,x.y);if(!v||C<1)continue;const P=Math.min(126,Math.max(0,x.depth-1)*42),W=Math.round(Math.max(420,Math.min(620,360+C*.34)));d=Math.max(d,P+W);const H=v.animate([{transform:`translate(${-x.x}px, ${-x.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(${x.x*.035}px, ${x.y*.035}px) scale(1.003)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-x.x*.008}px, ${-x.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:W,delay:P,fill:"backwards"});H.id="amx-card-arrange",g(H)}if(d>0)for(const x of a.querySelectorAll(".amx-el-conn, .amx-el-label")){const v=x.animate([{opacity:.12,offset:0},{opacity:.12,offset:.68},{opacity:1,offset:1,easing:"ease-out"}],{duration:d,fill:"backwards"});v.id="amx-card-arrange-line",g(v)}}))},[b]),R=k.useCallback((u,a)=>{const d=h.current,g=Math.hypot(a.x,a.y);b(),!(!d||g<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)&&(Mn.current.raf=requestAnimationFrame(()=>{Mn.current.raf=0;const x=W=>{Mn.current.animations.push(W);const H=()=>{Mn.current.animations=Mn.current.animations.filter(K=>K!==W)};W.addEventListener("finish",H,{once:!0}),W.addEventListener("cancel",H,{once:!0})},v=Math.round(Math.max(400,Math.min(520,350+g*.42))),C=d.querySelector(`.amx-ucard[data-anchor="${CSS.escape(u)}"]`);if(C){const W=C.animate([{transform:`translate(${-a.x}px, ${-a.y}px) scale(1.012)`,opacity:.94,boxShadow:"0 12px 32px rgb(0 0 0 / 24%)",offset:0,easing:"ease-in"},{transform:`translate(${-a.x*.54}px, ${-a.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(${a.x*.05}px, ${a.y*.05}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-a.x*.012}px, ${-a.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:v,fill:"none"});W.id="amx-card-attach",x(W)}const P=d.querySelector(`.amx-el-conn[data-el="${CSS.escape(`t:${u}`)}"]`);if(P){const W=P.animate([{opacity:0,offset:0},{opacity:0,offset:.56},{opacity:1,offset:1,easing:"ease-out"}],{duration:v,fill:"backwards"});W.id="amx-card-attach-line",x(W)}}))},[b]);k.useEffect(()=>b,[b]);const[T,F]=k.useState(null),[V,G]=k.useState(null);k.useEffect(()=>{Ft||F(null)},[Ft]);const q=new Set(ct),U=k.useRef(!Yc(lt));k.useEffect(()=>{n&&gf(lt,ne)},[lt,ne,n]),k.useLayoutEffect(()=>{const u=h.current;!n||!er||!u||!document.activeElement||!u.contains(document.activeElement)||jf()},[n,er,ne]);const O=k.useRef({getView:r,onCommit:D,onElements:i,onTree:f,onMain:p,timeline:y,elements:c,tree:l,main:o,mainStored:s,saveFile:N,parseMd:S,serializeMd:A,onBlocksDeleted:_,notePages:B,path:e,storedMd:Te});O.current={getView:r,onCommit:D,onElements:i,onTree:f,onMain:p,timeline:y,elements:c,tree:l,main:o,mainStored:s,saveFile:N,parseMd:S,serializeMd:A,onBlocksDeleted:_,notePages:B,path:e,storedMd:Te};const ge=Tn(c),De=u=>{if(!u)return null;const a={x:u.x,y:u.y,w:u.w,...typeof u.h=="number"&&u.h>0?{h:u.h}:{}};return a.x!==0||a.y!==0||a.w!==_r||(a.h??0)>0?a:null},Ie=()=>{const u=O.current;return{e:Ir(u.elements),t:Bt(u.tree),m:De(u.mainStored?u.main:null)}},Oe=k.useRef(null),Pe=k.useRef({past:[],future:[]}),We=()=>Pe.current;k.useEffect(()=>{const u=Ie(),a=JSON.stringify(u);if(!(Oe.current!==null&&a===Oe.current)){if(Oe.current!==null)try{const d=JSON.parse(Oe.current),g=(v,C)=>{let P=d.t[v];const W=new Set([v]);for(;typeof P=="string"&&P&&!W.has(P);){if(P===C)return!0;W.add(P),P=d.t[P]}return!1};if(JSON.stringify(u.e)===JSON.stringify(d.e)&&JSON.stringify(u.m)===JSON.stringify(d.m)&&Object.keys(u.t).length<=Object.keys(d.t).length&&Object.keys(u.t).every(v=>typeof d.t[v]<"u"&&(JSON.stringify(u.t[v])===JSON.stringify(d.t[v])||g(v,u.t[v])))){Oe.current=a;return}}catch{}Oe.current=a,Pe.current={past:[],future:[]},O.current.timeline.log.length=0,O.current.timeline.future.length=0}},[e,c,l,o,s]);const Ye=k.useCallback((u,a)=>{const d=O.current,g=Ie(),x=JSON.stringify(g),v=JSON.stringify({e:u.e??g.e,t:u.t??g.t,m:u.m?De(u.m):g.m});if(v!==x){if(a?.snap!==!1){const C=We();C.past.push(x),C.past.length>Yi&&C.past.shift(),C.future.length=0,d.timeline.log.push("fm"),d.timeline.future.length=0;const P=d.getView();P&&P.dispatch(Vs(P.state.tr))}Oe.current=v,u.e&&d.onElements(u.e),u.t&&d.onTree(u.t),u.m&&d.onMain(u.m)}},[e]),Ge=k.useCallback(u=>{const a=Ir(O.current.elements),d=u(a);d!==a&&Ye({e:d})},[Ye]),qt=k.useCallback(u=>{const a=We(),d=u==="undo"?a.past:a.future,g=u==="undo"?a.future:a.past,x=d.pop();if(x==null)return!1;const v=O.current;g.push(JSON.stringify(Ie()));const C=JSON.parse(x);return Oe.current=x,v.onElements(C.e),v.onTree(C.t),v.onMain(C.m??{x:0,y:0,w:_r}),!0},[e]),Wt=k.useCallback(()=>{const u=We();u.past.push(JSON.stringify(Ie())),u.past.length>Yi&&u.past.shift(),u.future.length=0;const a=O.current.timeline;a.log.push("fm"),a.future.length=0},[e]),kt=k.useCallback(u=>{const a=Bt(O.current.tree);return u.some(d=>typeof a[d]<"u"||Object.keys(a).some(g=>a[g]===d))},[]),Ue=k.useCallback(()=>{const u=O.current.timeline,a=u.log.length;if(a<2)return;const d=u.log[a-2],g=u.log[a-1];(d==="pm"&&g==="fm"||d==="fm"&&g==="pm")&&u.log.splice(a-2,2,"pair")},[]),Xn=k.useCallback(u=>{const a=O.current.timeline,d=u==="undo"?a.log:a.future,g=u==="undo"?a.future:a.log,x=()=>{const P=O.current.getView();return!!P&&(u==="undo"?Ia(P.state):md(P.state))>0},v=()=>(u==="undo"?We().past:We().future).length>0,C=()=>{const P=O.current.getView();return!!P&&(u==="undo"?Pa:pl)(P.state,P.dispatch)};for(;d.length;){const P=d[d.length-1];if(d.pop(),P==="pair"){if(!x()||!v())continue;return qt(u),C(),g.push(P),!0}if(P==="fm"){if(qt(u))return g.push(P),!0;continue}if(C())return g.push("pm"),!0}return C()},[qt]);k.useEffect(()=>{if(E)return E.current=Xn,()=>{E.current===Xn&&(E.current=null)}},[E,Xn]);const Lt=k.useCallback((u,a)=>{const d=h.current,g=d?.getBoundingClientRect(),{x,y:v,z:C}=ce.current;if(!d||!g)return{x:0,y:0};const P=Fn(d)||1;return{x:((u-g.left)/P-x)/C,y:((a-g.top)/P-v)/C}},[]),$t=k.useCallback(()=>{Ln();const u=h.current,a=r();if(!u||!a)return;const d=[...u.querySelectorAll(".amx-ucard, .amx-el-shape, .amx-el-frame, .amx-el-frame-bar, .amx-el-conn, .amx-el-label"),a.dom].map(Fe=>Fe.getBoundingClientRect());if(!d.length)return;const{x:g,y:x,z:v}=ce.current,C=u.getBoundingClientRect(),P=Fn(u)||1,W=(Fe,I)=>(Fe/P-I)/v,H=Math.min(...d.map(Fe=>W(Fe.left-C.left,g))),K=Math.min(...d.map(Fe=>W(Fe.top-C.top,x))),ae=Math.max(...d.map(Fe=>W(Fe.right-C.left,g))),he=Math.max(...d.map(Fe=>W(Fe.bottom-C.top,x))),Re=ae-H,Ke=he-K;if(Re<=0||Ke<=0)return;const Xe=48,Q=Math.max(Xo,Math.min(1,Math.min((C.width/P-Xe*2)/Re,(C.height/P-Xe*2)/Ke)));de({z:Q,x:(C.width/P-Re*Q)/2-H*Q,y:(C.height/P-Ke*Q)/2-K*Q})},[r,Ln]),nr=k.useCallback(u=>{Ln();const a=h.current;if(!a)return;const{x:d,y:g,z:x}=ce.current,v=Math.max(Xo,Math.min(zs,x*u));if(v===x)return;const C=Fn(a)||1,P=a.getBoundingClientRect().width/C/2,W=a.getBoundingClientRect().height/C/2;de({z:v,x:P-(P-d)*v/x,y:W-(W-g)*v/x})},[Ln]),Er=k.useCallback((u,a)=>{Ln();const d=h.current;if(!d)return;const g=Fn(d)||1,x=d.getBoundingClientRect(),v=ce.current.z;de({z:v,x:x.width/g/2-u*v,y:x.height/g/2-a*v})},[Ln]);k.useEffect(()=>{const u=h.current;if(!te||!u)return;const a=()=>{const d=O.current.getView(),g=document.getSelection();if(!d||!g||g.isCollapsed||!g.rangeCount)return;const x=g.getRangeAt(0),v=W=>d.dom.contains(W.nodeType===3?W.parentNode:W),C=v(x.startContainer),P=v(x.endContainer);if(!(!C&&!P))try{const W=d.state.doc,H=C?d.posAtDOM(x.startContainer,x.startOffset):0,K=P?d.posAtDOM(x.endContainer,x.endOffset):W.content.size,ae=Ae.between(W.resolve(Math.min(H,K)),W.resolve(Math.max(H,K)));ae.eq(d.state.selection)||d.dispatch(d.state.tr.setSelection(ae))}catch{}};return u.addEventListener("copy",a,!0),()=>u.removeEventListener("copy",a,!0)},[te]),k.useEffect(()=>{const u=h.current;if(!n||!u)return;const a=d=>{const g=d.detail?.rect;if(!g)return;const x=Lt(g.left+g.width/2,g.top+g.height/2);Er(x.x,x.y),d.preventDefault()};return u.addEventListener("amx-reveal",a),()=>u.removeEventListener("amx-reveal",a)},[n,Lt,Er]);const ur=k.useRef($t);ur.current=$t,k.useEffect(()=>{if(!n||!U.current)return;U.current=!1;const u=setTimeout(()=>ur.current(),220);return()=>clearTimeout(u)},[n]),k.useEffect(()=>{n||(ot([]),ln("select"),Cn(null),wt(null),gn(null),Wn(null))},[n]),k.useEffect(()=>{if(!nt)return;const u=a=>{a.target?.closest?.(".ctx-menu")||wt(null)};return window.addEventListener("pointerdown",u,!0),window.addEventListener("contextmenu",u,!0),()=>{window.removeEventListener("pointerdown",u,!0),window.removeEventListener("contextmenu",u,!0)}},[nt]);const zn=k.useCallback(u=>{const a=new Map;for(const[g,x]of mn(h.current))a.set(jt(g),x);for(const[g,x]of Eo(Tn(O.current.elements),u))a.set(hn(g),x);const d=pn(h.current);return d&&a.set(ie,d),a},[]),Yr=k.useRef(!1);k.useEffect(()=>()=>{Yr.current=!0},[]);const Mr=k.useCallback(async(u,a,d)=>{const g=Tn(O.current.elements).find(C=>C.id===u);if(!g)return;const x=(g.kind==="connector"?g.label:g.kind==="frame"?g.title:g.text)??"",v=await _a(d,x);v==null||Yr.current||Tn(O.current.elements).some(C=>C.id===u)&&Ge(C=>gg(C,u,a,v.trim()))},[Ge]),Xr=k.useCallback((u,a)=>{const d=O.current,g=d.getView(),x=new Set(u.filter(H=>H.startsWith("c:")).map(Ze));let v=!1;if(g&&x.size){const H=a??"",K=new Map;for(const ae of On(g))x.has(ae.anchor)&&String(ae.node.attrs.color??"")!==H&&K.set(ae.anchor,{color:H});K.size&&(bo(g,K),d.onCommit(),v=!0)}const C=new Set(u.filter(H=>H.startsWith("e:")).map(Ze));if(!C.size)return;const P=Ir(O.current.elements),W=wg(P,C,a);W!==P&&(Ye({e:W}),v&&Ue())},[Ye,Ue]),zr=k.useCallback((u,a,d,g,x)=>{const v=O.current.getView(),C=v?.state.schema.nodes.amadeusCanvasCard,P=v?.state.schema.nodes.paragraph;if(!v||!C||!P)return null;const W=kr(v.state.doc),H={x:u,y:a,w:Jt,h:80},K=[...mn(h.current).values(),...Ds(O.current.elements)],ae=pn(h.current);ae&&K.push(ae);const he=Uo([H],K),Re=u+he.x,Ke=a+he.y,Xe=x?.childCount?x:P.create(null,g?v.state.schema.text(g):void 0),Q=C.createAndFill({anchor:W,x:Math.round(Re),y:Math.round(Ke),w:Jt,h:0},Xe);if(!Q)return null;const Fe=d?ou(v.state.doc,Bt(O.current.tree),d):v.state.doc.content.size;return to(v,v.state.tr.insert(Fe,Q)),O.current.onCommit(W),ot([jt(W)]),!g&&!x?.childCount&&me.current.enterNodeEdit(jt(W)),W},[zn]),lo=k.useCallback((u,a)=>{const d=O.current.saveFile;d&&u.forEach((g,x)=>{const v=g.name||we("canvasstage.upload.fileN",{n:x+1}),C=we("canvasstage.upload.uploading",{name:v}),P=me.current.addCardAt(a.x-Jt/2+x*24,a.y-24+x*24,void 0,C);P&&d(g).then(W=>{const H=O.current.getView(),K=H?On(H).find(ae=>ae.anchor===P&&ae.node.textContent===C)??On(H).find(ae=>ae.node.textContent===C):null;!H||!K||(W?(fx(H,K.anchor,W,C),O.current.onCommit()):me.current.removeSel([jt(K.anchor)]))})})},[]),dr=k.useCallback((u,a,d=0)=>{const g=u.trim();if(!g)return null;const x=O.current.parseMd?.(g)??null;return me.current.addCardAt(a.x-Jt/2+d*24,a.y-24+d*24,void 0,g,Gi(x))},[]),Un=k.useCallback(u=>{const a=Bt(O.current.tree),d=u(a);return d===a?!1:(Ye({t:d}),!0)},[Ye]),rr=k.useCallback(u=>u===ie?pn(h.current):mn(h.current).get(u)??null,[]),fr=k.useCallback((u,a,d,g,x=0)=>{const v=rr(u);if(!v)return null;const C=Bt(O.current.tree),P=C[u],W=a==="child"?u:typeof P=="string"&&P?P:"",H=(W?wo(C,W):[u]).map(rr).filter(Boolean),K=80,ae=32,Re=a==="child"?d==="w"?v.x-g-K:v.x+v.w+K:H.length?Math.min(...H.map(I=>I.x)):v.x,Ke=H.length?Math.min(...H.map(I=>I.y))-ae-x:v.y,Xe=H.length?Math.max(...H.map(I=>I.y+I.h))+ae:v.y,Q=d==="n"?Ke:Xe,Fe=a==="child"?wo(C,u).length?Q:v.y:Q;return{parent:W,x:Math.round(Re),y:Math.round(Fe)}},[rr]),uo=k.useCallback((u,a,d,g=80)=>{const x=rr(u);if(!x)return null;const v=Bt(O.current.tree),C=v[u],P=a==="child"?u:typeof C=="string"&&C?C:"",W=a==="child"?x:P?rr(P):x;if(!W)return null;const H=O.current.getView(),K=H?On(H).map(_e=>_e.anchor):[],he=(P?wo(v,P):a==="child"?wo(v,u):K.filter(_e=>typeof v[_e]!="string"||!v[_e])).map(_e=>rr(_e)).filter(Boolean),Re=W.x+W.w/2,Ke=[...mn(h.current).values(),...Ds(O.current.elements)],Xe=pn(h.current);Xe&&Ke.push(Xe);const Q=80,Fe=32;let I=null;for(const _e of[1,-1]){const Le=he.filter(an=>(an.x+an.w/2-Re)*_e>0),et=_e>0?W.x+W.w+Q:W.x-Q-d,Dt=Le.length?Math.max(...Le.map(an=>an.y+an.h))+Fe:W.y,_t=Uo([{x:et,y:Dt,w:d,h:g}],Ke,{x:_e,y:0}),kn=Math.hypot(_t.x,_t.y)*100+Le.length*32+(_e<0?6:0);(!I||kn<I.score)&&(I={x:et+_t.x,y:Dt+_t.y,score:kn})}return I?{parent:P,x:Math.round(I.x),y:Math.round(I.y)}:null},[zn,rr]),sn=k.useCallback((u,a)=>{const d=uo(u,a,Jt);if(!d)return;const g=zr(d.x,d.y,d.parent||void 0);g&&d.parent&&Un(x=>Oo(x,g,d.parent))&&Ue()},[uo,zr,Un,Ue]),wn=k.useCallback((u,a)=>{const d=[...new Set(typeof u=="string"?[u]:u)],g=new Set(d),x=mn(h.current),v=d[0],C=v?x.get(v):null;if(!C||!v)return null;const P=fr(a.node,a.rel,a.side,C.w,C.h);if(!P)return null;const W=Bt(O.current.tree),H=d.filter(_e=>!(typeof W[_e]=="string"&&g.has(W[_e])));if(!H.length||H.includes(P.parent))return null;const K=d.flatMap(_e=>{const Le=x.get(_e);return Le?[{anchor:_e,box:Le}]:[]});if(!K.length)return null;const ae=P.x-C.x,he=P.y-C.y,Re=K.map(({box:_e})=>({..._e,x:_e.x+ae,y:_e.y+he})),Ke=[...x].filter(([_e])=>!g.has(_e)).map(([,_e])=>_e),Xe=pn(h.current);Xe&&Ke.push(Xe),Ke.push(...Ds(O.current.elements));const Q=Uo(Re,Ke,{x:ae,y:he}),Fe=ae+Q.x,I=he+Q.y;return{sources:d,sourceSet:g,boxes:x,primary:v,roots:H,moving:K,slot:P,dx:Fe,dy:I}},[fr]),Ot=k.useCallback((u,a)=>{const d=[...new Set(typeof u=="string"?[u]:u)],g=d[0];if(!g)return null;const x=new Set(d),v=48,C=Xe=>Math.min(38,Math.max(18,Xe*.32)),P=Bt(O.current.tree),W=Xe=>{let Q=Xe;const Fe=new Set;for(;typeof Q=="string"&&Q&&!Fe.has(Q);){if(x.has(Q))return!0;Fe.add(Q),Q=P[Q]}return!1},K=[...mn(h.current)].filter(([Xe])=>!x.has(Xe)&&!W(Xe)),ae=pn(h.current);ae&&K.push([ie,ae]);let he=null;for(const[Xe,Q]of K){if(a.x<Q.x-v||a.x>Q.x+Q.w+v||a.y<Q.y-v||a.y>Q.y+Q.h+v)continue;const Fe=C(Q.w),I=C(Q.h),_e=18,Le=[["e",Math.abs(Q.x+Q.w-a.x),a.x>Q.x+Q.w?v:Fe,a.y>=Q.y-_e&&a.y<=Q.y+Q.h+_e],["w",Math.abs(a.x-Q.x),a.x<Q.x?v:Fe,a.y>=Q.y-_e&&a.y<=Q.y+Q.h+_e],["s",Math.abs(Q.y+Q.h-a.y),a.y>Q.y+Q.h?v:I,a.x>=Q.x-_e&&a.x<=Q.x+Q.w+_e],["n",Math.abs(a.y-Q.y),a.y<Q.y?v:I,a.x>=Q.x-_e&&a.x<=Q.x+Q.w+_e]];for(const[et,Dt,yt,_t]of Le){if(!_t||Dt>yt)continue;const kn=Dt/Math.max(1,yt);(!he||kn<he.score)&&(he={node:Xe,side:et,rel:et==="e"||et==="w"?"child":"sibling",score:kn})}}if(!he)return null;const Re={node:he.node,side:he.side,rel:he.rel};return wn(d,Re)?{source:g,count:d.length,...Re}:null},[wn]),Qt=k.useCallback((u,a)=>{const d=O.current.getView(),g=wn(u,a);if(!d||!g)return!1;const{sources:x,sourceSet:v,boxes:C,primary:P,roots:W,moving:H,slot:K,dx:ae,dy:he}=g,Re=Bt(O.current.tree);let Ke=Bt(Re);for(const Fe of W)if(delete Ke[Fe],K.parent){const I=Oo(Ke,Fe,K.parent);if(I===Ke)return!1;Ke=I}let Xe=d.state.tr;for(const Fe of On(d)){const I=C.get(Fe.anchor);v.has(Fe.anchor)&&I&&(Xe=Xe.setNodeMarkup(Fe.pos,void 0,{...Fe.node.attrs,x:Math.round(I.x+ae),y:Math.round(I.y+he)}))}const Q=W.filter(Fe=>(typeof Re[Fe]=="string"?Re[Fe]:"")!==K.parent);for(const Fe of Q)Xe=Ui(Xe,Ke,Fe,K.parent);return to(d,Xe),O.current.onCommit(),Q.length&&Un(I=>{let _e=Bt(I);for(const Le of W)delete _e[Le],K.parent&&(_e=Oo(_e,Le,K.parent));return _e})&&Ue(),x.length===1?R(P,{x:ae,y:he}):M(H.map(({anchor:Fe})=>({anchor:Fe,x:ae,y:he,depth:W.includes(Fe)?1:2}))),ot(x.map(jt)),!0},[wn,Un,Ue,M,R]),xr=k.useCallback((u,a)=>{const d=Bt(O.current.tree);if(d[u]===a)return;const g=Oo(d,u,a);if(g===d)return;const x=O.current.getView();let v=!1;if(x){const C=Ui(x.state.tr,g,u,a);C.steps.length&&(to(x,C),v=!0)}Ye({t:g}),v&&Ue()},[Ye,Ue]),Nr=k.useCallback((u,a,d)=>{const g=C=>C===ie?ie:C.startsWith("c:")?Ze(C):null,x=g(u),v=g(a);x&&v&&v!==ie&&!d?xr(v,x):Ge(C=>mg(C,u,a))},[xr,Ge]),Gn=k.useCallback((u,a,d)=>{Ge(g=>pg(g,new Set(u),{fromEnd:a,toEnd:d}))},[Ge]),Jn=k.useCallback(async()=>{const u=O.current.getView(),a=h.current;if(!u||!a||!n)return;const d=O.current.storedMd,g=K=>d?.(K.content)?.trim()||K.textBetween(0,K.content.size,`
|
|
40
|
-
|
|
41
|
-
`),x=mn(a),v=On(u).map(K=>{const ae=K.node.attrs,he=x.get(K.anchor)??{x:Number(ae.x)||0,y:Number(ae.y)||0,w:Number(ae.w)||Jt,h:Number(ae.h)||80};return{ref:K.anchor,...he,color:ae.color,md:g(K.node)}}),C=[];u.state.doc.forEach(K=>{K.type.name!=="amadeusCanvasCard"&&C.push(K)});const P=pn(a),W=C.length?d?.(wr.fromArray(C))?.trim()??"":"",H=rx({cards:v,main:P?{...P,md:W}:null,elements:O.current.elements,tree:O.current.tree,pages:O.current.notePages?.(),sourcePath:e});try{const K=await ax(bn,e,ox(H));so({text:we("canvasstage.export.done",{path:K}),level:"success"})}catch(K){so({text:we("canvasstage.export.failed",{e:Nl(K)}),level:"error"})}},[n,e]);k.useEffect(()=>{if(!Y||!n||te)return;const u=()=>{Jn()};return Y.current=u,()=>{Y.current===u&&(Y.current=null)}},[Y,n,te,Jn]);const Hn=k.useCallback((u,a,d,g)=>{let x="";Ge(v=>(x=ds(v,"s"),[...v,g?Kl(x,u,g):fg(x,u,a,d)])),x&&ot([hn(x)])},[Ge]),Zn=k.useCallback((u,a,d=480,g=320)=>{let x="";Ge(v=>(x=ds(v,"f"),[...v,bg(x,u,a,d,g)])),x&&ot([hn(x)])},[Ge]),fo=k.useCallback(u=>{const a=zn(null),d=u.map(C=>a.get(C)).filter(C=>!!C);if(!d.length)return;const g=32,x=Math.min(...d.map(C=>C.x))-g,v=Math.min(...d.map(C=>C.y))-g;Zn(x,v,Math.max(...d.map(C=>C.x+C.w))+g-x,Math.max(...d.map(C=>C.y+C.h))+g-v)},[zn,Zn]),Vn=k.useCallback(u=>{const a=Tn(O.current.elements),d=u.filter(v=>v.startsWith("e:")).map(v=>a.find(C=>C.id===Ze(v))).filter(v=>v?.kind==="frame");if(!d.length)return u;const g=zn(null),x=new Set(u);for(const v of d)for(const[C,P]of g)x.has(C)||P.x>=v.x&&P.y>=v.y&&P.x+P.w<=v.x+v.w&&P.y+P.h<=v.y+v.h&&x.add(C);return[...x]},[zn]),mr=k.useCallback((u,a)=>{const d=u.filter(H=>H.startsWith("e:")).map(Ze),g=u.filter(H=>H.startsWith("c:")).map(Ze),x=u.filter(H=>H.startsWith("t:")).map(Ze),v=g.length?O.current.getView():null,C=new Set(g),P=v?On(v).filter(H=>C.has(H.anchor)).sort((H,K)=>K.pos-H.pos):[],W=P.length>0&&(d.length>0||x.length>0||kt(g));if(W&&Wt(),x.length){const H=Bt(O.current.tree),K=Bt(H);let ae=!1;for(const he of x)typeof K[he]<"u"&&(delete K[he],ae=!0);ae&&Ye({t:K},W?{snap:!1}:void 0)}if(d.length){const H=Ir(O.current.elements),K=ug(H,new Set(d));K!==H&&Ye({e:K},W?{snap:!1}:void 0)}if(v&&P.length){let H=v.state.tr;for(const K of P)H=H.delete(K.pos,K.pos+K.node.nodeSize);to(v,H),a?.assets!==!1&&O.current.onBlocksDeleted?.(wr.from(P.map(K=>K.node).reverse())),O.current.onCommit(),W&&Ue()}ot([])},[Ye,Wt,kt,Ue]),$r=k.useCallback(u=>{const a=O.current.getView(),d=new Set(Vn(u).filter(Q=>Q!==ie&&!Q.startsWith("t:"))),g=new Set([...d].filter(Q=>Q.startsWith("c:")).map(Ze)),x=a?On(a).filter(Q=>g.has(Q.anchor)):[],v=new Set(x.map(Q=>Q.anchor)),C=Ir(O.current.elements),P=Q=>{const Fe=Q&&typeof Q=="object"?Q.id:null;return typeof Fe=="string"&&Fe?Fe:null},W=Q=>!!Q&&typeof Q=="object"&&Q.type==="connector",H=C.filter(Q=>!W(Q)&&d.has(hn(P(Q)??""))),K=new Set(H.map(P)),ae=Q=>{const Fe=Us(Q);return!!Fe&&(Fe.ref?v.has(Fe.ref):Fe.id?K.has(Fe.id):!1)},he=C.filter(Q=>W(Q)&&P(Q)&&ae(Q.from)&&ae(Q.to)),Re=Bt(O.current.tree),Ke=[...v].flatMap(Q=>typeof Re[Q]=="string"&&v.has(Re[Q])?[[Q,Re[Q]]]:[]);if(!x.length&&!H.length&&!he.length)return null;const Xe=[...H,...he];return{cards:x,els:Xe,tree:Ke,keys:[...x.map(Q=>jt(Q.anchor)),...Xe.map(Q=>hn(P(Q)))]}},[Vn]),Ur=k.useCallback((u,a,d,g,x)=>{const v=O.current,C=v.getView(),P=C?.state.schema.nodes.amadeusCanvasCard,W=C?.state.schema.nodes.paragraph;if(!C||!P||!W)return;const H=new Map,K=[];let ae=C.state.tr;for(const Le of u){const et=kr(ae.doc),Dt=Math.round(Le.x+g),yt=Math.round(Le.y+x);let _t=null;if(Le.node&&Le.node.type===P)_t=P.create({...Le.node.attrs,anchor:et,x:Dt,y:yt},Le.node.content);else{const kn=Gi(Le.md?.trim()?v.parseMd?.(Le.md.trim())??null:null)??W.create(null,Le.md?.trim()?C.state.schema.text(Le.md.trim()):void 0);_t=P.createAndFill({anchor:et,x:Dt,y:yt,w:Math.round(Le.w)||Jt,h:Math.round(Le.h)||0,color:typeof Le.color=="string"?Le.color:""},kn)}_t&&(ae=ae.insert(ae.doc.content.size,_t),H.set(Le.ref,et),K.push(et))}const he=K.length>0;he&&(to(C,ae),K.forEach(Le=>v.onCommit(Le)));const Re=Ir(O.current.elements),Ke=new Map,Xe=[],Q=Le=>Le.type==="frame"?"f":Le.type==="connector"?"e":"s",Fe=[];for(const Le of a){const et=Le;if(typeof et.id!="string"||!et.id)continue;if(et.type==="connector"){Fe.push(et);continue}const Dt=ds(Re,Q(et));Ke.set(et.id,Dt),Re.push({...et,id:Dt,...typeof et.x=="number"?{x:Math.round(et.x+g)}:{},...typeof et.y=="number"?{y:Math.round(et.y+x)}:{}}),Xe.push(Dt)}const I=Le=>{const et=Us(Le);if(!et)return null;const Dt=Le;if(et.ref){const yt=H.get(et.ref);return yt?{...Dt,ref:yt}:null}if(et.id){const yt=Ke.get(et.id);return yt?{...Dt,id:yt}:null}return null};for(const Le of Fe){const et=I(Le.from),Dt=I(Le.to);if(!et||!Dt)continue;const yt=ds(Re,"e");Re.push({...Le,id:yt,from:et,to:Dt}),Xe.push(yt)}let _e=null;for(const[Le,et]of d){const Dt=H.get(Le),yt=H.get(et);if(!Dt||!yt)continue;const _t=Oo(_e??Bt(O.current.tree),Dt,yt);_t!==_e&&(_e=_t)}(Xe.length||_e)&&(Ye({...Xe.length?{e:Re}:{},..._e?{t:_e}:{}}),he&&Ue()),ot([...K.map(jt),...Xe.map(hn)])},[Ye,Ue]),z=k.useCallback((u,a)=>{u.clearData();const d=$r(a);if(!d)return Ta=null,u.setData("text/plain",""),null;const g=O.current.serializeMd,x=d.cards.map(H=>g?.(H.node.content)?.trim()||H.node.textBetween(0,H.node.content.size,`
|
|
42
|
-
|
|
43
|
-
`)),v=d.els.flatMap(H=>{const K=H,ae=K.type==="connector"?K.label:K.type==="frame"?K.title:K.text;return typeof ae=="string"&&ae.trim()?[ae.trim()]:[]});u.setData("text/plain",[...x,...v].join(`
|
|
44
|
-
|
|
45
|
-
`));const C=`t${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,P=d.cards.map(H=>{const K=H.node.attrs;return{ref:H.anchor,x:Number(K.x)||0,y:Number(K.y)||0,w:Number(K.w)||Jt,h:Number(K.h)||0,...typeof K.color=="string"&&K.color?{color:K.color}:{}}}),W={token:C,mds:x,cards:P,...d.els.length?{els:d.els}:{},...d.tree.length?{tree:d.tree}:{}};try{u.setData(Zi,JSON.stringify(W))}catch{}return Ta={token:C,nodes:d.cards.map(H=>H.node)},Vr.current=0,d},[$r]),L=k.useCallback((u,a)=>{const d=O.current.getView();if(!d)return!1;const g=Ta,x=!!g&&g.token===u.token&&(g.nodes.length===0||g.nodes[0].type===d.state.schema.nodes.amadeusCanvasCard);let v;if(x&&g)v=g.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)v=u.cards.map((H,K)=>({...H,md:u.mds[K]}));else{const H=u.mds.filter(K=>K.trim());return H.length?(H.forEach((K,ae)=>me.current.addCardMd(K,a,ae)),!0):!1}const C=u.els??[],P=v.map(H=>H.x),W=v.map(H=>H.y);for(const H of C){const K=H;typeof K.x=="number"&&typeof K.y=="number"&&(P.push(K.x),W.push(K.y))}return P.length?(Ur(v,C,u.tree??[],a.x-Math.min(...P),a.y-Math.min(...W)),!0):!1},[Ur]),re=k.useCallback(u=>{const a=$r(u);a&&Ur(a.cards.map(d=>({ref:d.anchor,x:Number(d.node.attrs.x)||0,y:Number(d.node.attrs.y)||0,w:Number(d.node.attrs.w)||Jt,h:Number(d.node.attrs.h)||0,node:d.node})),a.els,a.tree,Xc,Xc)},[$r,Ur]),fe=k.useCallback(u=>{const a=d=>{d.clipboardData&&(d.preventDefault(),d.stopImmediatePropagation(),z(d.clipboardData,u))};document.addEventListener("copy",a,{capture:!0,once:!0});try{document.execCommand("copy")}finally{document.removeEventListener("copy",a,{capture:!0})}h.current?.focus({preventScroll:!0})},[z]),ke=k.useCallback((u,a)=>{const d=O.current.getView();if(!d||u!==ie&&!u.startsWith("c:"))return;let g=null,x=null;if(u===ie)d.state.doc.forEach((v,C)=>{g==null&&v.type.name!=="amadeusCanvasCard"&&(g=Math.min(d.state.doc.content.size,C+v.nodeSize-1))}),x=v=>{const C=d.state.doc.resolve(v);for(let P=C.depth;P>0;P--)if(C.node(P).type.name==="amadeusCanvasCard")return!1;return!0};else{const v=On(d).find(C=>C.anchor===Ze(u));v&&(g=Math.min(d.state.doc.content.size,v.pos+v.node.nodeSize-1),x=C=>C>v.pos&&C<v.pos+v.node.nodeSize)}if(g!=null){if(a){const v=d.posAtCoords({left:a.x,top:a.y});v&&x?.(v.pos)&&(g=v.pos)}try{d.dispatch(Vs(d.state.tr.setSelection(Ae.near(d.state.doc.resolve(g),-1))))}catch{}Wn(u===ie?ie:Ze(u)),d.focus()}},[]),ze=k.useCallback((u,a=!1)=>{const d=h.current;if(!d)return;const g=u===ie?pn(d):u.startsWith("c:")?mn(d).get(Ze(u))??null:null;if(!g)return;const x=Fn(d)||1,v=d.getBoundingClientRect(),C=v.width/x,P=v.height/x,W=Math.max(Xo,Math.min(1.5,zs,C*.62/Math.max(1,g.w),P*.72/Math.max(1,g.h))),H={z:W,x:C/2-(g.x+g.w/2)*W,y:P/2-(g.y+g.h/2)*W},K={...ce.current};if(Ln(),window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)ce.current=H,de(H);else{const ae=Math.hypot(H.x-K.x,H.y-K.y),he=Math.round(Math.max(460,Math.min(560,420+ae*.12+Math.abs(H.z-K.z)*120))),Re=performance.now();lr(!0);const Ke=Xe=>{const Q=Math.min(1,(Xe-Re)/he),Fe=Q>=1?1:1-Math.exp(-8*Q)*(Math.cos(6*Q)+8/6*Math.sin(6*Q)),I={x:K.x+(H.x-K.x)*Fe,y:K.y+(H.y-K.y)*Fe,z:K.z+(H.z-K.z)*Fe};ce.current=I,de(I),Q<1?Yn.current=requestAnimationFrame(Ke):(Yn.current=0,lr(!1))};Yn.current=requestAnimationFrame(Ke)}a||(Wn(null),ot([u]),d.focus({preventScroll:!0}))},[Ln]),le=k.useCallback(u=>{const a=h.current,d=O.current.getView();if(!a||!d)return!1;const g=Bt(O.current.tree),x=mn(a),v=new Set(x.keys()),C=rt=>wo(g,rt).filter(Je=>v.has(Je)).sort((Je,Nt)=>(x.get(Je)?.y??0)-(x.get(Nt)?.y??0)),P=[],W=new Map,H=new Set([u]),K=(rt,Je)=>{for(const Nt of C(rt))H.has(Nt)||(H.add(Nt),P.push(Nt),W.set(Nt,Je+1),K(Nt,Je+1))};if(K(u,0),!P.length)return!1;const ae=u===ie?pn(a):x.get(u);if(!ae)return!1;const he=96,Re=32,Ke=new Map,Xe=rt=>{const Je=rt===u?ae:x.get(rt);if(!Je)return 0;const Nt=C(rt).filter(In=>In!==u&&H.has(In)),yn=Nt.reduce((In,dn)=>In+Xe(dn),0)+Math.max(0,Nt.length-1)*Re,Tt=Math.max(Je.h,yn);return Ke.set(rt,Tt),Tt};Xe(u);const Q=C(u).filter(rt=>rt!==u&&H.has(rt)),Fe=rt=>{const Je=new Map,Nt=(yn,Tt,In)=>{const dn=C(yn).filter(Gt=>Gt!==u&&H.has(Gt));if(!dn.length)return;const it=dn.reduce((Gt,Nn)=>Gt+(Ke.get(Nn)??Xe(Nn)),0)+(dn.length-1)*Re;let fn=Tt.y+Tt.h/2-it/2;for(const Gt of dn){const Nn=x.get(Gt);if(!Nn)continue;const mo=Ke.get(Gt)??Nn.h,jr={x:In>0?Tt.x+Tt.w+he:Tt.x-he-Nn.w,y:fn+(mo-Nn.h)/2,w:Nn.w,h:Nn.h};Je.set(Gt,jr),Nt(Gt,jr,In),fn+=mo+Re}};for(const yn of[1,-1]){const Tt=Q.filter(it=>rt.get(it)===yn),In=Tt.reduce((it,fn)=>it+(Ke.get(fn)??Xe(fn)),0)+Math.max(0,Tt.length-1)*Re;let dn=ae.y+ae.h/2-In/2;for(const it of Tt){const fn=x.get(it);if(!fn)continue;const Gt=Ke.get(it)??fn.h,Nn={x:yn>0?ae.x+ae.w+he:ae.x-he-fn.w,y:dn+(Gt-fn.h)/2,w:fn.w,h:fn.h};Je.set(it,Nn),Nt(it,Nn,yn),dn+=Gt+Re}}return Je},I=[],_e=new Set,Le=rt=>{const Je=rt.join(",");_e.has(Je)||(_e.add(Je),I.push(new Map(Q.map((Nt,yn)=>[Nt,rt[yn]]))))};if(Q.length<=9)for(let rt=0;rt<2**Q.length;rt++)Le(Q.map((Je,Nt)=>rt&1<<Nt?-1:1));else Le(Q.map((rt,Je)=>Je%2?-1:1)),Le(Q.map((rt,Je)=>Je<Math.ceil(Q.length/2)?1:-1)),Le(Q.map(()=>1)),Le(Q.map(()=>-1));Le(Q.map(rt=>(x.get(rt)?.x??ae.x)<ae.x?-1:1));const et=zn(null),Dt=new Set(P.map(jt)),yt=[...et].filter(([rt])=>!Dt.has(rt)).map(([,rt])=>ja(rt,24));let _t=null;for(const rt of I){const Je=Q.filter(it=>rt.get(it)===-1).length;if(Q.length>1&&(Je===0||Je===Q.length))continue;const Nt=Fe(rt),yn=[...Nt.values()],Tt=Math.min(...yn.map(it=>it.y)),In=Math.max(...yn.map(it=>it.y+it.h)),dn=new Set([0]);for(let it=1;it<=20;it++)dn.add(it*72),dn.add(-it*72);for(const it of yt)dn.add(Math.ceil(it.y+it.h+12-Tt)),dn.add(Math.floor(it.y-12-In));yt.length&&(dn.add(Math.ceil(Math.max(...yt.map(it=>it.y+it.h))+12-Tt)),dn.add(Math.floor(Math.min(...yt.map(it=>it.y))-12-In)));for(const it of[...dn].sort((fn,Gt)=>Math.abs(fn)-Math.abs(Gt))){const fn=new Map([...Nt].map(([Qn,or])=>[Qn,{...or,y:or.y+it}]));let Gt=0;for(const Qn of fn.values())for(const or of yt)Qi(ja(Qn,12),or)&&Gt++;const Nn=Qn=>{const or=Q.filter(pr=>rt.get(pr)===Qn).map(pr=>Ke.get(pr)??0);return or.reduce((pr,Gr)=>pr+Gr,0)+Math.max(0,or.length-1)*Re},mo=Nn(1),jr=Nn(-1),ws=[...fn].reduce((Qn,[or,pr])=>{const Gr=x.get(or);return Qn+(Gr?Math.hypot(pr.x-Gr.x,pr.y-Gr.y):0)},0),Xt=Gt*1e6+Math.abs(it)+Math.max(mo,jr)*.18+Math.abs(mo-jr)*.04+ws*.002+Je*2;(!_t||Xt<_t.score)&&(_t={plan:fn,score:Xt})}}if(!_t)return!1;const kn=new Map([..._t.plan].map(([rt,Je])=>[rt,{x:Math.round(Je.x),y:Math.round(Je.y)}])),an=[...kn].flatMap(([rt,Je])=>{const Nt=x.get(rt);return Nt?[{anchor:rt,x:Je.x-Nt.x,y:Je.y-Nt.y,depth:W.get(rt)??1}]:[]});return bo(d,kn),M(an),O.current.onCommit(),a.focus({preventScroll:!0}),!0},[zn,M]);k.useEffect(()=>{const u=h.current;!n||!u||document.activeElement&&u.contains(document.activeElement)||u.focus({preventScroll:!0})},[n]);const me=k.useRef({mutate:Ge,writeFm:Ye,mergePair:Ue,pushFmCheckpoint:Wt,treeTouches:kt,removeSel:mr,editText:Mr,boxesNow:zn,fit:$t,zoomBy:nr,addCardAt:zr,addShapeAt:Hn,addFrame:Zn,addRelated:sn,attachHit:Ot,applyAttach:Qt,setNodeParent:xr,expandFrames:Vn,enterNodeEdit:ke,focusNode:ze,arrangeChildren:le,stopArrangeMotion:b,stopFocusMotion:Ln,dropFilesAt:lo,addCardMd:dr,writeClip:z,pastePayload:L,linkNodes:Nr});me.current={mutate:Ge,writeFm:Ye,mergePair:Ue,pushFmCheckpoint:Wt,treeTouches:kt,removeSel:mr,editText:Mr,boxesNow:zn,fit:$t,zoomBy:nr,addCardAt:zr,addShapeAt:Hn,addFrame:Zn,addRelated:sn,attachHit:Ot,applyAttach:Qt,setNodeParent:xr,expandFrames:Vn,enterNodeEdit:ke,focusNode:ze,arrangeChildren:le,stopArrangeMotion:b,stopFocusMotion:Ln,dropFilesAt:lo,addCardMd:dr,writeClip:z,pastePayload:L,linkNodes:Nr},k.useEffect(()=>{const u=h.current;if(!n||!u||typeof ResizeObserver>"u")return;const a=new Set,d=new WeakMap;let g=0,x=!1;const v=()=>{if(g=0,x)return;const K=Zt.current,ae=O.current.getView();if(!K||!ae)return;const he=mn(u),Re=K===ie?pn(u):he.get(K);if(!Re)return;const Ke=[...he].filter(([I,_e])=>I!==K&&Qi(ja(Re,18),_e));if(!Ke.length)return;const Xe=new Map(he),Q=new Map,Fe=[];for(const[I,_e]of Ke){const Le=[...Xe].filter(([kn])=>kn!==I).map(([,kn])=>kn),et=pn(u);et&&K!==ie&&Le.push(et),Le.push(...Ds(O.current.elements));const Dt={x:_e.x+_e.w/2-(Re.x+Re.w/2),y:_e.y+_e.h/2-(Re.y+Re.h/2)},yt=Uo([_e],Le,Dt);if(!yt.x&&!yt.y)continue;const _t={..._e,x:_e.x+yt.x,y:_e.y+yt.y};Xe.set(I,_t),Q.set(I,{x:Math.round(_t.x),y:Math.round(_t.y)}),Fe.push({anchor:I,x:yt.x,y:yt.y,depth:1})}Q.size&&(x=!0,bo(ae,Q,!1),M(Fe),O.current.onCommit(),requestAnimationFrame(()=>{x=!1}))},C=()=>{window.clearTimeout(g),g=window.setTimeout(v,90)},P=new ResizeObserver(K=>{for(const ae of K){const he=ae.target,Re={w:he.offsetWidth,h:he.offsetHeight},Ke=d.get(he);if(d.set(he,Re),Ke&&(Ke.w!==Re.w||Ke.h!==Re.h)){const Xe=he.classList.contains("amx-ucard")?he.dataset.anchor:ie;Xe&&Xe===Zt.current&&C()}}}),W=()=>{const K=new Set(u.querySelectorAll(".amx-ucard")),ae=u.querySelector(".ProseMirror");ae&&K.add(ae);for(const he of K)a.has(he)||(a.add(he),d.set(he,{w:he.offsetWidth,h:he.offsetHeight}),P.observe(he,{box:"border-box"}));for(const he of[...a])K.has(he)||(a.delete(he),P.unobserve(he))};W();const H=new MutationObserver(W);return H.observe(u,{subtree:!0,childList:!0}),()=>{window.clearTimeout(g),H.disconnect(),P.disconnect()}},[n,e,M]),k.useEffect(()=>{if(!n||X<=0)return;U.current=!1;let u=0;const a=requestAnimationFrame(()=>{u=requestAnimationFrame(()=>{const d=O.current.getView();if(!d)return;const{$from:g}=d.state.selection;let x=ie;for(let v=g.depth;v>0;v--){const C=g.node(v);if(C.type.name==="amadeusCanvasCard"){x=jt(String(C.attrs.anchor));break}}ot([x]),Wn(x===ie?ie:Ze(x)),me.current.focusNode(x,!0),d.focus()})});return()=>{cancelAnimationFrame(a),cancelAnimationFrame(u)}},[n,X]),k.useEffect(()=>{const u=h.current;if(!u||!n)return;const a=()=>O.current.getView(),d=w=>O.current.onCommit(w),g=()=>u.focus({preventScroll:!0}),x=`s${++dx}`;u.dataset.amxDragscope=x;const v=document.createElement("style");document.head.appendChild(v);let C=[],P=0;const W=(w,$=!1)=>`left:${w.x}px!important;top:${w.y}px!important;${$&&"w"in w&&"h"in w?`width:${w.w}px!important;height:${w.h}px!important;`:""}`,H=`.amx-stage[data-amx-dragscope="${x}"] .unified-gutter{visibility:hidden!important;pointer-events:none!important}`,K=(w,$)=>{const ee=[];for(const pe of w){const ue=CSS.escape(pe.anchor);ee.push(`.amx-stage[data-amx-dragscope="${x}"] .amx-ucard[data-anchor="${ue}"]{${pe.decl}}`),ee.push(`.amx-stage[data-amx-dragscope="${x}"] .amx-el-selbox[data-anchor="${ue}"]{${W(pe.selection)}}`)}$&&ee.push(`.amx-stage[data-amx-dragscope="${x}"] .amx-el-selbox[data-main-sel]{${W($)}}`),ee.push(H),v.textContent=ee.join(`
|
|
46
|
-
`)},ae=(w,$,ee)=>{const pe=w===ie?`.amx-stage[data-amx-dragscope="${x}"] .ProseMirror:not(.unified-embed .ProseMirror){${$}}`:`.amx-stage[data-amx-dragscope="${x}"] .amx-ucard[data-anchor="${CSS.escape(w)}"]{${$}}`,ue=w===ie?`.amx-stage[data-amx-dragscope="${x}"] .amx-el-selbox[data-main-sel]{${W(ee,!0)}}`:`.amx-stage[data-amx-dragscope="${x}"] .amx-el-selbox[data-anchor="${CSS.escape(w)}"]{${W(ee,!0)}}`;v.textContent=`${pe}
|
|
47
|
-
${ue}
|
|
48
|
-
${H}`},he="cursor:grabbing;opacity:.94;box-shadow:0 12px 32px rgb(0 0 0 / 24%);z-index:1;",Re=()=>{v.textContent=""},Ke=()=>{cancelAnimationFrame(P),P=0;for(const w of C)w.cancel();C=[]},Xe=(w,$,ee,pe="amx-card-repel")=>{const ue=Math.hypot(ee.x,ee.y);if(ue<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;Ke();const $e=Math.round(Math.max(340,Math.min(480,320+ue*.55))),Ne=[{transform:`translate(${-ee.x}px, ${-ee.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(${ee.x*.06}px, ${ee.y*.06}px) scale(0.998)`,opacity:1,boxShadow:"0 3px 12px rgb(0 0 0 / 14%)",offset:.72,easing:"ease-out"},{transform:`translate(${-ee.x*.015}px, ${-ee.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}];P=requestAnimationFrame(()=>{P=0;const tt=w.map(dt=>u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(dt)}"]`)).filter(dt=>!!dt);if($){const dt=u.querySelector(".ProseMirror");dt&&tt.push(dt)}for(const dt of tt){const Me=dt.animate(Ne,{duration:$e,fill:"none"});Me.id=pe,C.push(Me);const qe=()=>{C=C.filter(ft=>ft!==Me)};Me.addEventListener("finish",qe,{once:!0}),Me.addEventListener("cancel",qe,{once:!0})}})},Q=(w,$,ee)=>{Math.max(Math.abs($.x-ee.x),Math.abs($.y-ee.y),Math.abs($.w-ee.w),Math.abs($.h-ee.h))<1||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(Ke(),P=requestAnimationFrame(()=>{P=0;const ue=w===ie?u.querySelector(".ProseMirror"):u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(w)}"]`);if(!ue)return;const $e=w===ie?{marginLeft:`${$.x}px`,marginTop:`${$.y}px`,width:`${$.w}px`,height:`${$.h}px`}:{left:`${$.x}px`,top:`${$.y}px`,width:`${$.w}px`,height:`${$.h}px`},Ne=w===ie?{marginLeft:`${ee.x}px`,marginTop:`${ee.y}px`,width:`${ee.w}px`,height:`${ee.h}px`}:{left:`${ee.x}px`,top:`${ee.y}px`,width:`${ee.w}px`,height:`${ee.h}px`},tt=ue.animate([$e,Ne],{duration:220,easing:"cubic-bezier(0.2, 0.78, 0.28, 1)",fill:"none"});tt.id="amx-card-snap",C.push(tt);const dt=()=>{C=C.filter(Me=>Me!==tt)};tt.addEventListener("finish",dt,{once:!0}),tt.addEventListener("cancel",dt,{once:!0})}))},Fe=w=>{if(w.target?.closest?.(".amx-stage-minimap"))return;me.current.stopFocusMotion(),w.preventDefault();const{x:$,y:ee,z:pe}=ce.current,ue=Fn(u)||1;if(w.metaKey||w.ctrlKey){const $e=w.ctrlKey&&!w.metaKey?ix:1,Ne=Math.max(Xo,Math.min(zs,pe*Math.exp(-w.deltaY*$e/300))),tt=u.getBoundingClientRect(),dt=(w.clientX-tt.left)/ue,Me=(w.clientY-tt.top)/ue;de({z:Ne,x:dt-(dt-$)*Ne/pe,y:Me-(Me-ee)*Ne/pe})}else{const $e=w.shiftKey&&!w.deltaX?w.deltaY:w.deltaX,Ne=w.shiftKey?0:w.deltaY;de({z:pe,x:$-$e/ue,y:ee-Ne/ue})}};u.addEventListener("wheel",Fe,{passive:!1});let I=null,_e=-1;const Le=w=>{_e=w;try{u.setPointerCapture(w)}catch{}},et=w=>{try{u.hasPointerCapture(w)&&u.releasePointerCapture(w)}catch{}},Dt=()=>Tf/(ce.current.z*(Fn(u)||1)),yt=(w,$,ee)=>{const pe=[];for(const[$e,Ne]of mn(u))w.has($e)||pe.push(Ne);const ue=$?null:pn(u);ue&&pe.push(ue);for(const[$e,Ne]of Eo(Tn(O.current.elements),null))ee.has($e)||pe.push(Ne);return pe},_t=(w,$)=>{const ee=document.elementFromPoint(w,$);if(!ee||!u.contains(ee))return null;const pe=ee.closest(rs);if(pe?.dataset.el)return hn(pe.dataset.el);const ue=ee.closest("[data-card-grip]");if(ue?.dataset.cardGrip)return ue.dataset.cardGrip===ie?ie:jt(ue.dataset.cardGrip);const $e=ee.closest(".amx-ucard");return $e?.dataset.anchor?jt($e.dataset.anchor):ee.closest(".ProseMirror")?ie:null},kn=w=>w===u||w.classList.contains("amx-stage-inner")||w.classList.contains("amx-el-layer"),an=new Map;let rt=null,Je=null,Nt=0,yn=null,Tt=Uc;const In=()=>{Qn();const w=I;I=null,w&&w.kind!=="pan"&&Jr(w)},dn=()=>{const[w,$]=[...an.keys()],ee=an.get(w),pe=an.get($);if(!ee||!pe)return null;const ue=Fn(u)||1,$e=u.getBoundingClientRect();return{x:((ee.x+pe.x)/2-$e.left)/ue,y:((ee.y+pe.y)/2-$e.top)/ue,d:Math.hypot(ee.x-pe.x,ee.y-pe.y)/ue,ids:`${w}/${$}`}},it=()=>{const w=dn();if(!w)return;const{x:$,y:ee,z:pe}=ce.current;Je={d0:Math.max(1,w.d),z0:pe,sx:(w.x-$)/pe,sy:(w.y-ee)/pe,ids:w.ids}},fn=()=>{const w=dn();if(!w||!Je)return;if(w.ids!==Je.ids){it();return}const $=Math.max(Xo,Math.min(zs,Je.z0*w.d/Je.d0));de({z:$,x:w.x-Je.sx*$,y:w.y-Je.sy*$})},Gt=()=>{Nt&&window.clearTimeout(Nt),Nt=0,yn=null},Nn=w=>{const $=w.target,{clientX:ee,clientY:pe}=w;yn={x:ee,y:pe},Nt=window.setTimeout(()=>{Nt=0,yn=null,kc($,ee,pe)==="open"&&In()},Sf)},mo=w=>{const $=a(),ee=$?On($).map(Ne=>Ne.anchor):[],pe=new Set([...ee,ie]),ue=Bt(O.current.tree);return[w===ie?ie:jt(w),...ee.filter(Ne=>Hl(ue,Ne,w,pe)).map(jt)]},jr=(w,$)=>{const ee=gt.current;if($.shiftKey||$.metaKey||$.ctrlKey){const pe=$.shiftKey&&(w===ie||w.startsWith("c:"))?mo(w===ie?ie:Ze(w)):[w],ue=ee.includes(w)?ee.filter($e=>!pe.includes($e)):[...ee,...pe.filter($e=>!ee.includes($e))];return ot(ue),ue.includes(w)?ue:null}return ee.includes(w)?ee:(ot([w]),[w])},ws=w=>{wt(null);const $=w.target;if($.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;if(Ke(),me.current.stopArrangeMotion(),me.current.stopFocusMotion(),w.pointerType==="touch"){if(an.set(w.pointerId,{x:w.clientX,y:w.clientY}),Gt(),an.size>=2){w.preventDefault(),In(),it();return}Nn(w)}if(Je)return;Tt=w.pointerType==="touch"?Gc/(ce.current.z*(Fn(u)||1)):Uc;const ee=w.button===1;if(w.button!==0&&!ee)return;const pe=Pt.current,ue=Lt(w.clientX,w.clientY);if(St.current){if($.closest(`${Wi}, .wikilink`))return;const ht=performance.now(),Ct=rt;if(rt=w.pointerType==="mouse"?{t:ht,x:w.clientX,y:w.clientY}:null,Ct&&ht-Ct.t<500&&Math.hypot(w.clientX-Ct.x,w.clientY-Ct.y)<6&&$.closest(".ProseMirror"))return;w.preventDefault(),I={kind:"pan",x0:w.clientX,y0:w.clientY,vx:ce.current.x,vy:ce.current.y},Le(w.pointerId);return}const $e=Zt.current,Ne=Sn.current.held;Ne&&(Sn.current.used=!0);const tt=pe==="pan"||w.altKey||ee||Ne,dt=pe!=="select"&&!tt,Me=$e===ie?!!$.closest(".ProseMirror")&&!$.closest(".amx-ucard"):!!$.closest(`.amx-ucard[data-anchor="${CSS.escape($e??"")}"]`);if($e&&!tt&&(dt||!Me)&&Wn(null),tt){w.preventDefault(),I={kind:"pan",x0:w.clientX,y0:w.clientY,vx:ce.current.x,vy:ce.current.y},Le(w.pointerId);return}if(Aa.has(pe)){w.preventDefault(),I={kind:"create",tool:pe,x0:ue.x,y0:ue.y,x1:ue.x,y1:ue.y},Le(w.pointerId);return}if(w.pointerType==="touch"&&(pe==="card"||os[pe])){w.preventDefault(),I={kind:"create",tool:pe,x0:ue.x,y0:ue.y,x1:ue.x,y1:ue.y},Le(w.pointerId);return}if(os[pe]){w.preventDefault(),me.current.addShapeAt(os[pe],ue.x,ue.y),ln("select"),g();return}if(pe==="card"){w.preventDefault();const ht=me.current.addCardAt(ue.x-Jt/2,ue.y-24);ln("select"),ht||g();return}const qe=$.closest("[data-grip]"),ft=$.closest("[data-card-grip][data-card-edge]"),It=$.closest(rs),mt=$.closest(".amx-ucard"),$n=$.closest(".ProseMirror"),hr=!mt&&!It&&!!$n&&$===$n,br=!mt&&!It&&!!$n&&$!==$n,po=!!mt&&$===mt,Pn=mt?.dataset.anchor??null;if(pe==="select"&&ft?.dataset.cardGrip&&ft.dataset.cardEdge){const ht=ft.dataset.cardGrip,Ct=ht===ie,en=Ct?pn(u):mn(u).get(ht),tn=Ct?null:a(),Kn=tn?On(tn).find(sr=>sr.anchor===ht):null;en&&(Ct||Kn)&&(w.preventDefault(),g(),ot([Ct?ie:jt(ht)]),I={kind:"card-size",key:ht,edge:ft.dataset.cardEdge,b0:en,h0:Ct?Number(O.current.main.h)||0:Number(Kn.node.attrs.h)||0,x0:ue.x,y0:ue.y,dx:0,dy:0,next:en},Le(w.pointerId));return}const ho=pe==="select"?$.closest("[data-link-from]"):null;if(ho?.dataset.linkFrom){w.preventDefault(),g(),I={kind:"link",from:ho.dataset.linkFrom,x0:ue.x,y0:ue.y},Le(w.pointerId);return}const Zr=pe==="select"?$.closest("[data-conn-end]"):null;if(Zr?.dataset.connEnd&&Zr.dataset.el){const ht=Tn(O.current.elements).find(tn=>tn.id===Zr.dataset.el),Ct=Zr.dataset.connEnd==="from"?"from":"to",en=ht?.kind==="connector"?xo(Ct==="from"?ht.to:ht.from):null;w.preventDefault(),g(),ht&&en&&(I={kind:"reconnect",id:ht.id,end:Ct,fixed:en,x0:ue.x,y0:ue.y},Le(w.pointerId));return}const To=$.closest(Wi)?Pn??($n?ie:null):null;if(pe==="select"&&To){Wn(To);return}const jo=mt&&Pn?Pn:br?ie:null;pe==="select"&&jo&&Zt.current!==jo&&ux($,w.clientX)&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("canvasstage.toast.needEdit")}}));const pt=w.pointerType==="touch"&&pe==="select"?It?.dataset.el?hn(It.dataset.el):Pn?jt(Pn):!mt&&$n?ie:null:null;if(pt&&!gt.current.includes(pt)&&Zt.current!==(Pn??ie)){w.preventDefault(),I={kind:"pan",x0:w.clientX,y0:w.clientY,vx:ce.current.x,vy:ce.current.y,tapKey:pt},Le(w.pointerId);return}if(mt&&Pn&&!po&&pe==="select"){if(Zt.current===Pn)return;w.preventDefault(),g();const ht=w.shiftKey||w.metaKey||w.ctrlKey,Ct=jt(Pn),en=jr(Ct,w);if(!en)return;const tn=en,Kn=[];for(const sr of tn){if(!sr.startsWith("c:"))continue;const gr=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(Ze(sr))}"]`);gr&&Kn.push({anchor:Ze(sr),ox:Number(gr.dataset.x)||0,oy:Number(gr.dataset.y)||0})}I={kind:"move",cards:Kn,ids:new Set(tn),hit:Ct,x0:ue.x,y0:ue.y,dx:0,dy:0,mainStart:null,mainEl:null,additive:ht},Le(w.pointerId);return}if(br&&pe==="select"){if(Zt.current===ie)return;w.preventDefault(),g();const ht=w.shiftKey||w.metaKey||w.ctrlKey,Ct=jr(ie,w);if(!Ct)return;const en=Ct,tn=[];for(const Kn of en){if(!Kn.startsWith("c:"))continue;const sr=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(Ze(Kn))}"]`);sr&&tn.push({anchor:Ze(Kn),ox:Number(sr.dataset.x)||0,oy:Number(sr.dataset.y)||0})}I={kind:"move",cards:tn,ids:new Set(en),hit:ie,x0:ue.x,y0:ue.y,dx:0,dy:0,mainStart:{x:O.current.main.x,y:O.current.main.y},mainEl:$n,additive:ht},Le(w.pointerId);return}const vr=It?.dataset.el?hn(It.dataset.el):Pn?jt(Pn):hr?ie:null;if(pe==="conn"){w.preventDefault(),g();const ht=vr??(!mt&&!It&&$.closest(".ProseMirror")?ie:null);if(!ht){Cn(null);return}const Ct=Ut.current;Ct?(me.current.linkNodes(Ct,ht,w.shiftKey),Cn(null),ln("select")):Cn(ht);return}const Ss=$.closest("[data-add]");if(Ss?.dataset.add&&Ss.dataset.node){w.preventDefault(),g(),me.current.addRelated(Ss.dataset.node,Ss.dataset.add==="child"?"child":"sibling");return}if(qe?.dataset.grip){w.preventDefault();const ht=Eo(Tn(O.current.elements),null).get(qe.dataset.grip);if(!ht)return;I={kind:"size",id:qe.dataset.grip,corner:qe.dataset.corner??"se",b0:ht,dx:0,dy:0,dw:0,dh:0},Le(w.pointerId);return}if(vr){w.preventDefault(),g();const ht=w.shiftKey||w.metaKey||w.ctrlKey,Ct=jr(vr,w);if(!Ct)return;const en=Ct;if(po&&en.length===1&&mt.dataset.anchor){const gr=mt.getBoundingClientRect(),Lr=qi*ce.current.z*(Fn(u)||1);if(w.clientX>=gr.right-Lr){const oa=mn(u).get(mt.dataset.anchor),jc=On(a()).find(vu=>vu.anchor===mt.dataset.anchor);if(!oa||!jc)return;I={kind:"card-size",key:mt.dataset.anchor,edge:"e",b0:oa,h0:Number(jc.node.attrs.h)||0,x0:ue.x,y0:ue.y,dx:0,dy:0,next:oa},Le(w.pointerId);return}}if(vr===ie&&en.length===1&&$n){const gr=$n.getBoundingClientRect();if(w.clientX>gr.right-qi*ce.current.z*(Fn(u)||1)){const Lr=pn(u);if(!Lr)return;I={kind:"card-size",key:ie,edge:"e",b0:Lr,h0:Number(O.current.main.h)||0,x0:ue.x,y0:ue.y,dx:0,dy:0,next:Lr},Le(w.pointerId);return}}const tn=me.current.expandFrames(en),Kn=[];for(const gr of tn){if(!gr.startsWith("c:"))continue;const Lr=u.querySelector(`.amx-ucard[data-anchor="${CSS.escape(Ze(gr))}"]`);Lr&&Kn.push({anchor:Ze(gr),ox:Number(Lr.dataset.x)||0,oy:Number(Lr.dataset.y)||0})}const sr=tn.includes(ie);I={kind:"move",cards:Kn,ids:new Set(tn),hit:vr,x0:ue.x,y0:ue.y,dx:0,dy:0,mainStart:sr?{x:O.current.main.x,y:O.current.main.y}:null,mainEl:sr?u.querySelector(".ProseMirror"):null,additive:ht,growSel:tn.length>Ct.length?[...tn]:void 0},Le(w.pointerId);return}if(!kn($))return;const Es=me.current.boxesNow(null),na=Tn(O.current.elements).find(ht=>{if(ht.kind!=="connector")return!1;const Ct=xo(ht.from),en=xo(ht.to),tn=Ct?Es.get(Ct):null,Kn=en?Es.get(en):null;return!!tn&&!!Kn&&js(tn,Kn,ue,8/ce.current.z)}),Tc=na?null:tu(O.current.tree).find(([ht,Ct])=>{const en=Es.get(jt(ht)),tn=Es.get(Ct===ie?ie:jt(Ct));return!!en&&!!tn&&js(tn,en,ue,8/ce.current.z)});if(w.preventDefault(),g(),na){ot([hn(na.id)]);return}if(Tc){ot([eu(Tc[0])]);return}const ra=w.shiftKey||w.metaKey||w.ctrlKey,bu=ra?[...gt.current]:[];if(ra||ot([]),w.pointerType==="touch"){I={kind:"pan",x0:w.clientX,y0:w.clientY,vx:ce.current.x,vy:ce.current.y},Le(w.pointerId);return}I={kind:"marquee",x0:ue.x,y0:ue.y,additive:ra,base:bu},Le(w.pointerId)},Xt={raf:0,t:0,x:0,y:0,id:-1,type:"mouse"},Qn=()=>{Xt.raf&&cancelAnimationFrame(Xt.raf),Xt.raf=0},or=()=>{const w=u.getBoundingClientRect();return{left:Math.max(w.left,0),top:Math.max(w.top,0),right:Math.min(w.right,window.innerWidth),bottom:Math.min(w.bottom,window.innerHeight)}},pr=w=>St.current||Je?!1:I?I.kind!=="pan"&&I.live===!0:Pt.current==="conn"&&!!Ut.current&&!w?.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"),Gr=w=>{Xt.raf=0;const $=document.elementFromPoint(Xt.x,Xt.y);if(!pr($))return;const{vx:ee,vy:pe}=Qc(or(),Xt.x,Xt.y);if(!ee&&!pe)return;const ue=Math.min(.05,Math.max(0,(w-Xt.t)/1e3));Xt.t=w;const $e=Fn(u)||1,Ne={...ce.current,x:ce.current.x-ee*ue/$e,y:ce.current.y-pe*ue/$e};ce.current=Ne,de(Ne),bc({clientX:Xt.x,clientY:Xt.y,pointerId:Xt.id,pointerType:Xt.type,target:$??u}),Xt.raf=requestAnimationFrame(Gr)},gu=w=>{if(I&&_e!==w.pointerId)return;Xt.x=w.clientX,Xt.y=w.clientY,Xt.id=w.pointerId,Xt.type=w.pointerType;const{vx:$,vy:ee}=pr(w.target)?Qc(or(),w.clientX,w.clientY):{vx:0,vy:0};if(!$&&!ee){Qn();return}Xt.raf||(Xt.t=performance.now(),Xt.raf=requestAnimationFrame(Gr))},yc=()=>{I||Qn()},xc=w=>{bc(w),gu(w)},bc=w=>{if(w.pointerType==="touch"&&(an.has(w.pointerId)&&an.set(w.pointerId,{x:w.clientX,y:w.clientY}),yn&&Math.hypot(w.clientX-yn.x,w.clientY-yn.y)>Ef&&Gt()),Je){fn();return}if(I&&_e!==w.pointerId)return;if(!I&&Pt.current==="conn"&&Ut.current){const Me=w.target,qe=Me.closest?.(rs),ft=Me.closest?.(".amx-ucard");let It=qe?.dataset.el?hn(qe.dataset.el):ft?.dataset.anchor?jt(ft.dataset.anchor):!ft&&Me.closest?.(".ProseMirror")?ie:null;It===Ut.current&&(It=null);const mt=Lt(w.clientX,w.clientY);F({x:mt.x,y:mt.y,over:It});return}if(!I)return;const $=Fn(u)||1;if(I.kind==="pan"){de({...ce.current,x:I.vx+(w.clientX-I.x0)/$,y:I.vy+(w.clientY-I.y0)/$});return}const ee=Lt(w.clientX,w.clientY);if(I.kind==="link"||I.kind==="reconnect"){(Math.abs(ee.x-I.x0)>Tt||Math.abs(ee.y-I.y0)>Tt)&&(I.live=!0);const Me=I.kind==="link"?I.from:I.fixed,qe=_t(w.clientX,w.clientY);G({from:Me,x:ee.x,y:ee.y,over:qe===Me?null:qe});return}if(I.kind==="card-size"){I.dx=ee.x-I.x0,I.dy=ee.y-I.y0;const Me=I.key===ie;let qe=Xi(I.b0,I.edge,I.dx,I.dy,!1,Me?za:Os);if((Math.abs(qe.x-I.b0.x)>Tt||Math.abs(qe.y-I.b0.y)>Tt||Math.abs(qe.w-I.b0.w)>Tt||Math.abs(qe.h-I.b0.h)>Tt)&&(I.live=!0),I.gx=!1,I.gy=!1,xe.current&&I.live){I.others||(I.others=yt(new Set(Me?[]:[I.key]),Me,new Set));const ft=Mf(qe,I.edge,I.others,Dt(),Me?za:Os,ru);qe=ft.box,I.gx=ft.guides.v.length>0,I.gy=ft.guides.h.length>0,He(I.gx||I.gy?Zc(qe,I.others,ft.guides,1/ce.current.z):null)}else He(null);I.next=qe,ae(I.key,Me?`margin-left:${qe.x}px;margin-top:${qe.y}px;width:${qe.w}px;height:${qe.h}px;${he}`:`left:${qe.x}px;top:${qe.y}px;width:${qe.w}px;height:${qe.h}px;${he}`,qe),Rn({move:{ids:new Set([Me?ie:jt(I.key)]),dx:0,dy:0},size:null});return}if(I.kind==="size"){const Me=I.b0,qe=I.corner.includes("e"),ft=I.corner.includes("s"),It=Math.max(eo,Math.round(qe?ee.x-Me.x:Me.x+Me.w-ee.x)),mt=Math.max(eo,Math.round(ft?ee.y-Me.y:Me.y+Me.h-ee.y));I.dx=qe?0:Me.w-It,I.dy=ft?0:Me.h-mt,I.dw=It-Me.w,I.dh=mt-Me.h,(Math.abs(I.dw)>Tt||Math.abs(I.dh)>Tt)&&(I.live=!0),Rn({move:null,size:{id:I.id,dx:I.dx,dy:I.dy,dw:I.dw,dh:I.dh}});return}if(I.kind==="create"){I.x1=ee.x,I.y1=ee.y,(Math.abs(I.x1-I.x0)>Tt||Math.abs(I.y1-I.y0)>Tt)&&(I.live=!0),Aa.has(I.tool)&&Sr({x:Math.min(I.x0,ee.x),y:Math.min(I.y0,ee.y),w:Math.abs(ee.x-I.x0),h:Math.abs(ee.y-I.y0)});return}if(I.kind==="marquee"){I.live=!0;const Me={x:Math.min(I.x0,ee.x),y:Math.min(I.y0,ee.y),w:Math.abs(ee.x-I.x0),h:Math.abs(ee.y-I.y0)};Sr(Me);const qe=[];for(const[ft,It]of me.current.boxesNow(null))Fi(Me,It)&&qe.push(ft);ot(I.additive?[...new Set([...I.base,...qe])]:qe);return}if(I.dx=Math.round(ee.x-I.x0),I.dy=Math.round(ee.y-I.y0),(Math.abs(I.dx)>Tt||Math.abs(I.dy)>Tt)&&(I.live=!0),!I.align){const Me=new Set(I.cards.map(hr=>hr.anchor)),qe=new Set([...I.ids].filter(hr=>hr.startsWith("e:")).map(Ze)),ft=mn(u),It=Eo(Tn(O.current.elements),null),mt=[];for(const hr of Me){const br=ft.get(hr);br&&mt.push(br)}const $n=I.mainStart?pn(u):null;$n&&mt.push($n);for(const hr of qe){const br=It.get(hr);br&&mt.push(br)}I.align={base:zf(mt),others:yt(Me,!!I.mainStart,qe)}}I.gx=!1,I.gy=!1;const pe=I.align.base;if(xe.current&&I.live&&pe){const Me=Nf({...pe,x:pe.x+I.dx,y:pe.y+I.dy},I.align.others,Dt());I.dx+=Math.round(Me.dx),I.dy+=Math.round(Me.dy),I.gx=Me.guides.v.length>0,I.gy=Me.guides.h.length>0,He(I.gx||I.gy?Zc({...pe,x:pe.x+I.dx,y:pe.y+I.dy},I.align.others,Me.guides,1/ce.current.z):null)}else He(null);I.live&&I.kind==="move"&&I.growSel&&(ot(I.growSel),I.growSel=void 0);const{dx:ue,dy:$e}=I;K(I.cards.map(Me=>({anchor:Me.anchor,decl:`left:${Me.ox+ue}px;top:${Me.oy+$e}px;${he}`,selection:{x:Me.ox+ue,y:Me.oy+$e}})),I.mainStart?{x:I.mainStart.x+ue,y:I.mainStart.y+$e}:void 0),I.mainStart&&I.mainEl&&(I.mainEl.style.marginLeft=`${I.mainStart.x+I.dx}px`,I.mainEl.style.marginTop=`${I.mainStart.y+I.dy}px`),Rn({move:{ids:I.ids,dx:I.dx,dy:I.dy},size:null});const Ne=Ze(I.hit),tt=!I.mainStart&&I.cards.length>0&&I.ids.size===I.cards.length?I.cards.map(Me=>Me.anchor).sort((Me,qe)=>+(qe===Ne)-+(Me===Ne)):[],dt=tt.length&&I.live?me.current.attachHit(tt,ee):null;Wr(dt)},Jr=w=>{Re(),w.kind==="move"&&w.mainEl&&(w.mainEl.style.marginLeft="",w.mainEl.style.marginTop=""),Rn(null),Sr(null),Wr(null),He(null),G(null)},vc=w=>{if(w.pointerType==="touch"&&(an.delete(w.pointerId),Gt(),Je)){an.size===0&&(Je=null),et(w.pointerId),I=null;return}if(I&&_e!==w.pointerId){et(w.pointerId);return}Qn();const $=I;if(I=null,et(w.pointerId),!$)return;if($.kind==="pan"){$.tapKey&&Math.hypot(w.clientX-$.x0,w.clientY-$.y0)<Gc&&ot([$.tapKey]);return}if($.kind==="link"||$.kind==="reconnect"){if(Jr($),!$.live)return;const $e=$.kind==="link"?$.from:$.fixed,Ne=_t(w.clientX,w.clientY);if(!Ne||Ne===$e)return;$.kind==="reconnect"?me.current.mutate(tt=>hg(tt,$.id,$.end,Ne)):me.current.linkNodes($e,Ne,w.shiftKey);return}if($.kind==="create"){const $e=Math.abs($.x1-$.x0),Ne=Math.abs($.y1-$.y0),tt=Aa.has($.tool)&&$e>=eo&&Ne>=eo?{x:Math.min($.x0,$.x1),y:Math.min($.y0,$.y1),w:$e,h:Ne}:null;let dt=null;$.tool==="frame"?tt?me.current.addFrame(tt.x,tt.y,tt.w,tt.h):me.current.addFrame($.x0-Si.w/2,$.y0-Si.h/2):$.tool==="card"?dt=me.current.addCardAt($.x0-Jt/2,$.y0-24):os[$.tool]&&me.current.addShapeAt(os[$.tool],$.x0,$.y0,tt??void 0),ln("select"),dt||g(),Jr($);return}if(!$.live){$.kind==="move"&&$.ids.size>1&&!$.additive&&ot([$.hit]),Jr($);return}const ee=a();if($.kind==="marquee"){const $e=Lt(w.clientX,w.clientY),Ne={x:Math.min($.x0,$e.x),y:Math.min($.y0,$e.y),w:Math.abs($e.x-$.x0),h:Math.abs($e.y-$.y0)},tt=[];for(const[dt,Me]of me.current.boxesNow(null))Fi(Ne,Me)&&tt.push(dt);ot($.additive?[...new Set([...$.base,...tt])]:tt),Jr($);return}if(!ee){Jr($);return}let pe=null,ue=null;if($.kind==="card-size"){const $e=$.key===ie;let Ne=j.current?Xi($.b0,$.edge,$.dx,$.dy,!0,$e?za:Os):$.next;$.gx&&(Ne={...Ne,x:$.next.x,w:$.next.w}),$.gy&&(Ne={...Ne,y:$.next.y,h:$.next.h});const tt=$.edge.includes("n")||$.edge.includes("s");$e?me.current.writeFm({m:{...O.current.main,x:Math.round(Ne.x),y:Math.round(Ne.y),w:Math.round(Ne.w),...tt?{h:Math.round(Ne.h)}:{}}}):bo(ee,new Map([[$.key,{x:Math.round(Ne.x),y:Math.round(Ne.y),w:Math.round(Ne.w),h:tt?Math.round(Ne.h):$.h0}]])),j.current&&(ue={key:$.key,from:$.next,to:Ne})}else if($.kind==="size"){const $e=Tn(O.current.elements).find(Ne=>Ne.id===$.id);$e&&$e.kind!=="connector"&&me.current.mutate(Ne=>Bl(Ne,$.id,{x:Math.round($e.x+$.dx),y:Math.round($e.y+$.dy),w:Math.max(eo,Math.round($e.w+$.dw)),h:Math.max(eo,Math.round($e.h+$.dh))}))}else{const $e=!$.mainStart&&$.cards.length>0&&$.ids.size===$.cards.length?$.cards.map(pt=>pt.anchor).sort((pt,vr)=>+(vr===Ze($.hit))-+(pt===Ze($.hit))):[],Ne=$e.length?me.current.attachHit($e,Lt(w.clientX,w.clientY)):null;if($e.length&&Ne&&me.current.applyAttach($e,Ne)){Jr($);return}const tt=mn(u),dt=[];for(const pt of $.cards){const vr=tt.get(pt.anchor);vr&&dt.push(vr)}if($.mainStart){const pt=pn(u);pt&&dt.push(pt)}const Me=new Set($.cards.map(pt=>pt.anchor)),qe=[...tt].filter(([pt])=>!Me.has(pt)).map(([,pt])=>pt);if(!$.mainStart){const pt=pn(u);pt&&qe.push(pt)}const ft=($.hit.startsWith("c:")?$.cards.find(pt=>pt.anchor===Ze($.hit)):null)??$.cards[0]??($.mainStart?{ox:$.mainStart.x,oy:$.mainStart.y}:null),It=$.gx?$.dx:j.current&&ft?Jc(ft.ox+$.dx)-ft.ox:$.dx,mt=$.gy?$.dy:j.current&&ft?Jc(ft.oy+$.dy)-ft.oy:$.dy,$n=It-$.dx,hr=mt-$.dy,br=dt.map(pt=>({...pt,x:pt.x+$n,y:pt.y+hr})),po=Uo(br,qe,{x:It,y:mt}),Pn=It+po.x,ho=mt+po.y,Zr={x:Pn-$.dx,y:ho-$.dy};(Zr.x||Zr.y)&&(pe={anchors:$.cards.map(pt=>pt.anchor),main:!!$.mainStart,push:Zr,repel:!!(po.x||po.y)}),$.cards.length&&bo(ee,new Map($.cards.map(pt=>[pt.anchor,{x:Math.round(pt.ox+Pn),y:Math.round(pt.oy+ho)}])));const To=new Set([...$.ids].filter(pt=>pt.startsWith("e:")).map(Ze)),jo=$.mainStart?{...O.current.main,x:Math.round($.mainStart.x+Pn),y:Math.round($.mainStart.y+ho)}:void 0;(To.size||jo)&&(me.current.writeFm({...To.size?{e:Ci(Ir(O.current.elements),To,Pn,ho)}:{},...jo?{m:jo}:{}}),$.cards.length&&me.current.mergePair())}Jr($),ue&&Q(ue.key,ue.from,ue.to),pe&&Xe(pe.anchors,pe.main,pe.push,pe.repel?"amx-card-repel":"amx-card-snap"),d()},wc=w=>{if(St.current)return;const $=document.elementFromPoint(w.clientX,w.clientY)??w.target;if($.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap, .ctx-menu"))return;const ee=$.closest(".amx-ucard"),pe=!ee&&!!$.closest(".ProseMirror"),ue=ee?.dataset.anchor?jt(ee.dataset.anchor):pe?ie:null;if(ue){if(Zt.current===(ue===ie?ie:Ze(ue)))return;w.preventDefault(),w.stopPropagation(),me.current.enterNodeEdit(ue,{x:w.clientX,y:w.clientY}),Km()&&me.current.focusNode(ue,!0);return}const $e=$.closest(rs);if($e?.dataset.el){w.preventDefault(),w.stopPropagation();const Me=Tn(O.current.elements).find(qe=>qe.id===$e.dataset.el);Me&&me.current.editText(Me.id,Na(Me),$a(Me));return}if(!kn($))return;const Ne=Lt(w.clientX,w.clientY),tt=me.current.boxesNow(null),dt=Tn(O.current.elements).find(Me=>{if(Me.kind!=="connector")return!1;const qe=xo(Me.from),ft=xo(Me.to),It=qe?tt.get(qe):null,mt=ft?tt.get(ft):null;return!!It&&!!mt&&js(It,mt,Ne,8/ce.current.z)});w.preventDefault(),dt?me.current.editText(dt.id,"label",we("canvasstage.textTitle.connector")):me.current.addCardAt(Ne.x-Jt/2,Ne.y-24)},kc=(w,$,ee)=>{if(St.current||w.closest(".amx-stage-tools, .amx-stage-hud, .amx-stage-minimap"))return"skip";const pe=w.closest(rs),ue=w.closest(".amx-ucard"),$e=!ue&&!pe&&!!w.closest(".ProseMirror");if(ue?.dataset.anchor&&Zt.current===ue.dataset.anchor||$e&&Zt.current===ie)return"native";let Ne=pe?.dataset.el?hn(pe.dataset.el):ue?.dataset.anchor?jt(ue.dataset.anchor):$e?ie:null;if(!Ne&&!kn(w))return"skip";if(!Ne){const tt=Lt($,ee),dt=me.current.boxesNow(null),Me=Tn(O.current.elements).find(qe=>{if(qe.kind!=="connector")return!1;const ft=xo(qe.from),It=xo(qe.to),mt=ft?dt.get(ft):null,$n=It?dt.get(It):null;return!!mt&&!!$n&&js(mt,$n,tt,8/ce.current.z)});Me&&(Ne=hn(Me.id))}return Ne&&!gt.current.includes(Ne)&&ot([Ne]),wt({x:$,y:ee,key:Ne,at:Lt($,ee)}),"open"},Cc=w=>{const $=kc(w.target,w.clientX,w.clientY);$!=="skip"&&(w.stopPropagation(),$==="open"&&w.preventDefault())},yu=w=>{const $=w.target,ee=Zt.current;return!ee||!$?!1:ee===ie?!!$.closest(".ProseMirror")&&!$.closest(".amx-ucard"):!!$.closest(`.amx-ucard[data-anchor="${CSS.escape(ee)}"]`)};let ta=!1;const Sc=w=>{w.target?.closest?.(".ProseMirror")&&(ta=!0)},Ao=()=>{ta=!1},Ec=w=>{const $=w.dataTransfer,ee=$?Array.from($.types):[];return ta||a()?.dragging?null:O.current.saveFile&&ee.includes("Files")?"files":Af($)?"refs":yu(w)?null:ee.includes("text/uri-list")||ee.includes("text/plain")?"text":null},Mc=w=>{if(St.current)return;const $=a();if(Ec(w)){w.preventDefault(),w.dataTransfer&&(w.dataTransfer.dropEffect="copy"),u.classList.add("amx-dropzone");return}!$?.dragging||w.target?.closest?.(".ProseMirror")||(w.preventDefault(),w.dataTransfer&&(w.dataTransfer.dropEffect="move"),u.classList.add("amx-dropzone"))},Rr=()=>u.classList.remove("amx-dropzone"),zc=w=>{u.contains(w.relatedTarget)||Rr()},Nc=w=>{if(Rr(),St.current){w.preventDefault();return}const $=a(),ee=Ec(w);if(ee){w.preventDefault(),w.stopPropagation();const $e=Lt(w.clientX,w.clientY),Ne=Array.from(w.dataTransfer?.files??[]);if(ee==="files"&&Ne.length){me.current.dropFilesAt(Ne,$e);return}if(ee==="refs"){const dt=O.current.path;kf(w.dataTransfer).forEach((Me,qe)=>me.current.addCardMd(Ji(Me,w.altKey||Me.kind==="note"&&Me.path===dt),$e,qe));return}const tt=w.dataTransfer?.getData("text/uri-list")||w.dataTransfer?.getData("text/plain")||"";me.current.addCardMd(tt,$e);return}if(!$?.dragging||w.target?.closest?.(".ProseMirror"))return;w.preventDefault(),w.stopPropagation();const pe=Lt(w.clientX,w.clientY),ue=$.state.selection;if(ue instanceof ye&&ue.node.type.name==="amadeusCanvasCard")bo($,new Map([[String(ue.node.attrs.anchor),{x:Math.round(pe.x),y:Math.round(pe.y)}]])),d();else{const $e=su($,Math.round(pe.x),Math.round(pe.y));$e&&d($e)}$.dragging=null,$.dom.dataset.dragging="false"},xu=()=>{const w=u.getBoundingClientRect();return Lt(w.left+w.width/2,w.top+w.height/2)},ks=w=>{if(Zt.current||!w.clipboardData||!a())return;const $=gt.current;if(!$.length)return;w.preventDefault();const ee=me.current.writeClip(w.clipboardData,$);w.type==="cut"&&ee&&me.current.removeSel(ee.keys,{assets:!1})},$c=w=>{if(St.current||Zt.current||!w.clipboardData)return;const $=Array.from(w.clipboardData.files??[]),ee=w.clipboardData.getData("text/plain")??"",pe=mx(w.clipboardData.getData(Zi));if(!$.length&&!ee.trim()&&!pe)return;w.preventDefault();const ue=Vr.current++,$e=xu(),Ne={x:$e.x+ue*24,y:$e.y+ue*24};if($.length){me.current.dropFilesAt($,Ne);return}pe&&me.current.pastePayload(pe,Ne)||ee.trim()&&me.current.addCardMd(ee,Ne)},Cs=w=>{w.pointerType==="touch"&&(an.delete(w.pointerId),Gt(),Je&&an.size===0&&(Je=null))};window.addEventListener("pointerup",Cs,!0),window.addEventListener("pointercancel",Cs,!0);const Ac=w=>{w.pointerType==="touch"&&(an.delete(w.pointerId),Gt(),Je&&an.size===0&&(Je=null)),et(w.pointerId),!(I&&_e!==w.pointerId)&&In()};return u.addEventListener("pointerdown",ws),u.addEventListener("pointermove",xc),u.addEventListener("pointerleave",yc),u.addEventListener("pointerup",vc),u.addEventListener("pointercancel",Ac),u.addEventListener("dblclick",wc),u.addEventListener("contextmenu",Cc,!0),u.addEventListener("dragover",Mc),u.addEventListener("dragleave",zc),u.addEventListener("drop",Nc),u.addEventListener("dragstart",Sc),window.addEventListener("dragend",Rr),window.addEventListener("drop",Rr),window.addEventListener("blur",Rr),window.addEventListener("dragend",Ao),window.addEventListener("drop",Ao),window.addEventListener("blur",Ao),u.addEventListener("copy",ks,!0),u.addEventListener("cut",ks,!0),u.addEventListener("paste",$c,!0),()=>{window.removeEventListener("pointerup",Cs,!0),window.removeEventListener("pointercancel",Cs,!0),Gt(),v.remove(),Ke(),delete u.dataset.amxDragscope,u.removeEventListener("wheel",Fe),u.removeEventListener("pointerdown",ws),u.removeEventListener("pointermove",xc),u.removeEventListener("pointerleave",yc),Qn(),u.removeEventListener("pointerup",vc),u.removeEventListener("pointercancel",Ac),u.removeEventListener("dblclick",wc),u.removeEventListener("contextmenu",Cc,!0),u.removeEventListener("dragover",Mc),u.removeEventListener("dragleave",zc),u.removeEventListener("drop",Nc),u.removeEventListener("dragstart",Sc),window.removeEventListener("dragend",Rr),window.removeEventListener("drop",Rr),window.removeEventListener("blur",Rr),window.removeEventListener("dragend",Ao),window.removeEventListener("drop",Ao),window.removeEventListener("blur",Ao),Rr(),u.removeEventListener("copy",ks,!0),u.removeEventListener("cut",ks,!0),u.removeEventListener("paste",$c,!0)}},[n,Lt]),k.useEffect(()=>{if(!n)return;const u=()=>{Sn.current={held:!1,used:!1},Cr(!1)},a=d=>{if(d.code!=="Space"||!Sn.current.held)return;const{used:g}=Sn.current;u(),d.preventDefault();const x=h.current,v=d.target;if(g||St.current||!x||!v||!x.contains(v)||v.closest(".ProseMirror"))return;const C=gt.current;C.length===1&&(C[0].startsWith("c:")||C[0]===ie)&&me.current.enterNodeEdit(C[0])};return window.addEventListener("keyup",a,!0),window.addEventListener("blur",u),()=>{window.removeEventListener("keyup",a,!0),window.removeEventListener("blur",u),u()}},[n]);const ut=u=>{if(!n||te||u.nativeEvent.isComposing)return;const a=u.target;if((u.metaKey||u.ctrlKey)&&(u.key==="z"||u.key==="Z")){if(a.tagName==="INPUT"||a.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(a.tagName==="INPUT"||a.tagName==="TEXTAREA")return;u.preventDefault(),u.stopPropagation(),Xn("redo");return}if(u.key!=="Escape")return;const d=Zt.current;!d||!a.closest(".ProseMirror")||(u.preventDefault(),u.stopPropagation(),Wn(null),ot([d===ie?ie:jt(d)]),h.current?.focus({preventScroll:!0}))},Et=u=>{if(!n)return;const a=u.target;if(a.closest(".ProseMirror")||a.tagName==="INPUT"||a.tagName==="TEXTAREA")return;const d=u.metaKey||u.ctrlKey;if(!u.altKey&&(d?u.key==="="||u.key==="+"||u.key==="-"||u.key==="0":u.shiftKey&&u.code==="Digit1")){u.preventDefault(),d?u.key==="0"?nr(1/ce.current.z):nr(u.key==="-"?1/1.2:1.2):$t();return}if(!te){if(d&&(u.key==="a"||u.key==="A")){u.preventDefault(),ot([...mn(h.current).keys()].map(jt).concat(ge.filter(g=>g.kind!=="connector").map(g=>hn(g.id)),[ie]));return}if(d&&!u.shiftKey&&!u.altKey&&(u.key==="d"||u.key==="D")){u.preventDefault(),ct.length&&re(ct);return}if(u.key==="Escape"){u.preventDefault(),nt?wt(null):Ft?Cn(null):at!=="select"?ln("select"):ot([]);return}if(u.code==="Space"&&!d&&!u.target?.closest?.("button")){u.preventDefault(),!u.repeat&&!Sn.current.held&&(Sn.current={held:!0,used:!1},Cr(!0));return}if(ct.length){if(u.key==="Delete"||u.key==="Backspace"){u.preventDefault(),mr(ct);return}if((u.key==="Enter"||u.key==="F2")&&ct.length===1&&ct[0].startsWith("e:")){u.preventDefault();const g=ge.find(x=>x.id===Ze(ct[0]));g&&Mr(g.id,Na(g),$a(g));return}if((u.key==="Tab"||u.key==="Enter")&&ct.length===1&&(ct[0].startsWith("c:")||ct[0]===ie)){u.preventDefault(),sn(ct[0]===ie?ie:Ze(ct[0]),u.key==="Tab"?"child":"sibling");return}if(u.key.startsWith("Arrow")){u.preventDefault();const g=Cf(j.current,u.shiftKey),x=u.key==="ArrowLeft"?-g:u.key==="ArrowRight"?g:0,v=u.key==="ArrowUp"?-g:u.key==="ArrowDown"?g:0;if(!x&&!v)return;const C=r(),P=Vn(ct),W=P.filter(ae=>ae.startsWith("c:")).map(Ze);if(C&&W.length){const ae=mn(h.current);bo(C,new Map(W.map(he=>{const Re=ae.get(he);return[he,{x:Math.round((Re?.x??0)+x),y:Math.round((Re?.y??0)+v)}]}))),D()}const H=new Set(P.filter(ae=>ae.startsWith("e:")).map(Ze)),K=P.includes(ie)?{...o,x:Math.round(o.x+x),y:Math.round(o.y+v)}:void 0;(H.size||K)&&(Ye({...H.size?{e:Ci(Ir(c),H,x,v)}:{},...K?{m:K}:{}}),W.length&&Ue())}}}},vt=[{id:"select",icon:m.jsx(yf,{size:14}),title:Se("canvasstage.tool.select")},{id:"pan",icon:m.jsx(Hm,{size:14}),title:Se("canvasstage.tool.pan")},{id:"card",icon:m.jsx(El,{size:14}),title:Se("canvasstage.tool.card")},{id:"rect",icon:m.jsx(xf,{size:14}),title:Se("canvasstage.shape.rect")},{id:"ellipse",icon:m.jsx(bf,{size:14}),title:Se("canvasstage.shape.ellipse")},{id:"text",icon:m.jsx(Vm,{size:14}),title:Se("canvasstage.shape.text")},{id:"frame",icon:m.jsx(qm,{size:14}),title:Se("canvasstage.tool.frame")},{id:"conn",icon:m.jsx(_p,{size:14}),title:Se("canvasstage.tool.conn")}],Yt=vf(ne),zt=(nt?.key?.startsWith("e:")?ge.find(u=>u.id===Ze(nt.key))??null:null)?.kind==="connector",Dn=nt?.key?(ct.length?ct:[nt.key]).filter(u=>u.startsWith("c:")||u.startsWith("e:")):[],At=(()=>{if(!Dn.length)return null;const u=nt?r():null,a=Ir(c),d=x=>{if(x.startsWith("c:"))return String((u?On(u).find(C=>C.anchor===Ze(x))?.node.attrs.color:"")??"");const v=a.find(C=>!!C&&typeof C=="object"&&C.id===Ze(x));return typeof v?.color=="string"?v.color:""},g=d(Dn[0]);return Dn.every(x=>d(x)===g)?g:null})(),un=At&&At.startsWith("#")?At:null,Ar=zt?(ct.length?ct:[nt.key]).filter(u=>u.startsWith("e:")).map(Ze).filter(u=>ge.some(a=>a.kind==="connector"&&a.id===u)):[],Tr=(()=>{const u=Ar.map(a=>{const d=ge.find(v=>v.kind==="connector"&&v.id===a),g=d?.kind==="connector"?d.fromEnd??fs.fromEnd:fs.fromEnd,x=d?.kind==="connector"?d.toEnd??fs.toEnd:fs.toEnd;return Vi.find(v=>v.from===g&&v.to===x)?.id??null});return u.length&&u.every(a=>a===u[0])?u[0]:null})();return m.jsxs("div",{className:`amx-stage${n?"":" amx-stage-off"}${n?` amx-tool-${te?"pan":at}`:""}${te?" amx-stage-ro":""}${n&&tr?" amx-space-pan":""}${$o?" amx-vp-focus":""}${n&&ve&&ne.z<=st?" amx-stage-overview":""}`,ref:h,tabIndex:-1,onKeyDownCapture:ut,onKeyDown:Et,children:[n?m.jsx("div",{className:"amx-stage-grid","aria-hidden":"true",style:Yt}):null,m.jsxs("div",{className:"amx-stage-inner",style:n?{transform:`translate(${ne.x}px, ${ne.y}px) scale(${ne.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?m.jsx(Gy,{elements:c,hostRef:h,documentKey:e,sel:q,editing:er,tree:l,ghost:qr,marquee:En,attach:io,overviewScale:ve&&ne.z<=st?ne.z:null,mainAutoHeight:!(typeof o.h=="number"&&o.h>0),preview:V??(Ft&&T?{from:Ft,x:T.x,y:T.y,over:T.over}:null),guides:Qe}):null,Ve]}),n&&be?m.jsx(px,{hostRef:h,vp:ne,elements:c,ghost:qr,onCenter:Er}):null,n&&!te?m.jsx("div",{className:"amx-stage-tools",role:"toolbar","aria-label":Se("canvasstage.toolbar.label"),children:vt.map(u=>m.jsx("button",{type:"button",title:u.title,className:at===u.id?"on":"","aria-pressed":at===u.id,onClick:()=>{ln(u.id),Cn(null),h.current?.focus({preventScroll:!0})},children:u.icon},u.id))}):null,n&&Ft?m.jsx("div",{className:"amx-stage-hint",children:Se("canvasstage.conn.hint")}):null,n?m.jsx(Tm,{zoom:ne.z,onZoomBy:nr,onFit:$t,snap:oe,onSnap:u=>{Rt(u),h.current?.focus({preventScroll:!0})},mini:be,onMini:u=>{Ee(u),Bm(u),h.current?.focus({preventScroll:!0})},extra:m.jsxs(m.Fragment,{children:[m.jsx("button",{type:"button",className:J?"is-on":"","aria-pressed":J,"aria-label":Se("canvasstage.guides.label"),title:Se(J?"canvasstage.guides.off":"canvasstage.guides.on"),onClick:()=>{const u=!J;xe.current=u,se(u),Om(u),h.current?.focus({preventScroll:!0})},children:m.jsx(ep,{size:12})}),m.jsx("button",{type:"button",className:ve?"is-on":"","aria-pressed":ve,"aria-label":Se("canvasstage.overview.label"),title:Se(ve?"canvasstage.overview.off":"canvasstage.overview.on"),onClick:()=>{const u=!ve;Ce(u),_m(u),h.current?.focus({preventScroll:!0})},children:m.jsx(vp,{size:12})})]})}):null,n&&nt?m.jsx(no,{children:m.jsx(qo,{className:"ctx-menu amx-canvas-menu",x:nt.x,y:nt.y,onClick:u=>u.stopPropagation(),children:nt.key?m.jsxs(m.Fragment,{children:[Dn.length>0&&m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"amx-color-row",role:"group","aria-label":Se("canvasstage.color.label"),children:[cx.map(u=>m.jsx("button",{type:"button",className:"amx-color-swatch","data-swatch":u.v||"none",title:Se(u.nameKey),"aria-label":Se(u.nameKey),"aria-pressed":At===u.v,style:u.v?{"--amx-swatch":`var(--amx-cv-${u.v})`}:void 0,onClick:()=>{const a=Dn;wt(null),Xr(a,u.v||null)}},u.v||"none")),m.jsxs("label",{className:"amx-color-swatch is-custom",title:Se("canvasstage.color.custom"),"data-active":un?"":void 0,style:un?{"--amx-swatch":un}:void 0,children:[un?null:m.jsx(wf,{size:11}),m.jsx("input",{type:"color","aria-label":Se("canvasstage.color.custom"),defaultValue:un??"#7b5ce5",ref:u=>{if(!u)return;const a=Dn;u.onchange=()=>{wt(null),Xr(a,u.value)}}})]})]}),m.jsx("div",{className:"ctx-separator"})]}),zt&&Ar.length>0&&m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"amx-color-row amx-end-row",role:"group","aria-label":Se("canvasstage.ends.label"),children:Vi.map(u=>m.jsx("button",{type:"button",className:"amx-end-btn","data-ends":u.id,title:Se(u.nameKey),"aria-label":Se(u.nameKey),"aria-pressed":Tr===u.id,onClick:()=>{const a=Ar;wt(null),Gn(a,u.from,u.to),h.current?.focus({preventScroll:!0})},children:u.icon},u.id))}),m.jsx("div",{className:"ctx-separator"})]}),nt.key.startsWith("e:")&&m.jsx("button",{onClick:()=>{const u=ge.find(a=>a.id===Ze(nt.key));wt(null),u&&Mr(u.id,Na(u),$a(u))},children:Se("canvasstage.menu.editText")}),nt.key!==ie&&!zt&&m.jsxs(m.Fragment,{children:[m.jsx("button",{onClick:()=>{const u=ct.length?ct:[nt.key];wt(null),fe(u)},children:Se("canvasstage.menu.copy")}),m.jsx("button",{onClick:()=>{const u=ct.length?ct:[nt.key];wt(null),re(u),h.current?.focus({preventScroll:!0})},children:Se("canvasstage.menu.duplicate")})]}),!zt&&m.jsx("button",{onClick:()=>{Cn(nt.key),ln("conn"),wt(null)},children:Se("canvasstage.menu.connectTo")}),(nt.key===ie||nt.key.startsWith("c:"))&&wo(Bt(l),nt.key===ie?ie:Ze(nt.key)).length>0&&m.jsx("button",{onClick:()=>{const u=nt.key===ie?ie:Ze(nt.key);wt(null),le(u)},children:Se("canvasstage.menu.arrange")}),!zt&&m.jsx("button",{onClick:()=>{const u=ct.length?ct:[nt.key];wt(null),fo(u)},children:Se("canvasstage.menu.groupFrame")}),nt.key.startsWith("c:")&&m.jsx("button",{onClick:()=>{const u=Ze(nt.key);wt(null);const a=r();if(!a)return;const d=kt([u]);d&&Wt(),au(a,u),ot([]),D(),d&&Ue()},children:Se("canvasstage.menu.unwrap")}),nt.key!==ie&&m.jsx("button",{className:"danger",onClick:()=>{const u=ct.length?ct:[nt.key];wt(null),mr(u)},children:Se("canvasstage.menu.delete")})]}):m.jsxs(m.Fragment,{children:[m.jsx("button",{onClick:()=>{const u=nt.at;wt(null),zr(u.x-Jt/2,u.y-24)},children:Se("canvasstage.menu.newCard")}),B&&m.jsx("button",{onClick:()=>{const u=nt.at;wt(null),gn(u)},children:Se("canvasstage.menu.addNote")}),m.jsx("button",{onClick:()=>{const u=nt.at;wt(null),Hn("rect",u.x,u.y)},children:Se("canvasstage.shape.rect")}),m.jsx("button",{onClick:()=>{const u=nt.at;wt(null),Hn("ellipse",u.x,u.y)},children:Se("canvasstage.shape.ellipse")}),m.jsx("button",{onClick:()=>{const u=nt.at;wt(null),Hn("text",u.x,u.y)},children:Se("canvasstage.shape.text")}),m.jsx("button",{onClick:()=>{const u=nt.at;wt(null),Zn(u.x,u.y)},children:"Frame"}),m.jsx("button",{onClick:()=>{wt(null),$t()},children:Se("canvasstage.menu.fit")}),m.jsx("div",{className:"ctx-separator"}),m.jsx("button",{onClick:()=>{wt(null),Jn()},children:Se("canvasstage.menu.exportCanvas")})]})})}):null,n&&!te&&Be&&B?m.jsx(_l,{pages:B(),exclude:e,onClose:()=>{gn(null),h.current?.focus({preventScroll:!0})},onPick:u=>{const a=Be;gn(null),h.current?.focus({preventScroll:!0}),dr(Ji({kind:"note",path:u}),a)}}):null]})}function su(e,t,n,r){const o=e.state.selection,s=e.state.schema.nodes.amadeusCanvasCard;if(!s||!(o instanceof ye))return null;const c=o.node;if(!c.isBlock||["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(c.type.name))return null;const l=e.state.doc.resolve(o.from);for(let D=l.depth;D>=1;D--)if(l.node(D).type.name==="amadeusColumnCell")return null;const i=kr(e.state.doc),f=s.createAndFill({anchor:i,x:t,y:n,w:Jt,h:0},c);if(!f)return null;const p=l.depth>=1?l.node(l.depth):null,y=e.state.schema.nodes.paragraph;let E=p?.type.name==="amadeusCanvasCard"&&p.childCount===1&&y?e.state.tr.replaceWith(o.from,o.to,y.create()):e.state.tr.delete(o.from,o.to);return E=E.insert(r?ou(E.doc,r.tree,r.parent):E.doc.content.size,f),to(e,E.scrollIntoView()),i}function au(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()]],f=e.state.tr.delete(r.pos,r.pos+r.node.nodeSize);to(e,f.insert(r.pos,i).scrollIntoView())}const gx={heading:["id"]};function gc(e,t){if(e.type!==t.type)return!1;const n=gx[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 Vo(e,t){if(e===t)return!0;if(!gc(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(!Vo(e.child(n),t.child(n)))return!1;return!0}function cu(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(!gc(o,s))return n;if(o.isText&&o.text!==s.text){const c=o.text??"",l=s.text??"";for(let i=0;c[i]===l[i];i++)n++;return n}if(o.content.size||s.content.size){const c=cu(o.content,s.content,n+1);if(c!=null)return c}n+=o.nodeSize}}function iu(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),l=t.child(--s),i=c.nodeSize;if(c===l){n-=i,r-=i;continue}if(!gc(c,l))return{a:n,b:r};if(c.isText&&c.text!==l.text){const f=c.text??"",p=l.text??"";let y=0;const E=Math.min(f.length,p.length);for(;y<E&&f[f.length-y-1]===p[p.length-y-1];)y++,n--,r--;return{a:n,b:r}}if(c.content.size||l.content.size){const f=iu(c.content,l.content,n-1,r-1);if(f)return f}n-=i,r-=i}}const yx=25e4;function xx(e,t){const n=e.childCount,r=t.childCount;let o=0;for(;o<n&&o<r&&Vo(e.child(o),t.child(o));)o++;let s=0;for(;s<n-o&&s<r-o&&Vo(e.child(n-1-s),t.child(r-1-s));)s++;const c=o,l=n-s,i=o,f=r-s,p=l-c,y=f-i;if(p===0&&y===0)return[];if(p===0||y===0||p*y>yx)return[[c,l,i,f]];const E=y+1,D=new Uint32Array((p+1)*E);for(let te=p-1;te>=0;te--)for(let B=y-1;B>=0;B--)D[te*E+B]=Vo(e.child(c+te),t.child(i+B))?D[(te+1)*E+B+1]+1:Math.max(D[(te+1)*E+B],D[te*E+B+1]);const N=[];let S=0,A=0,_=0,X=0;for(;S<p&&A<y;)Vo(e.child(c+S),t.child(i+A))&&D[S*E+A]===D[(S+1)*E+A+1]+1?((_<S||X<A)&&N.push([c+_,c+S,i+X,i+A]),S++,A++,_=S,X=A):D[(S+1)*E+A]>=D[S*E+A+1]?S++:A++;return(_<p||X<y)&&N.push([c+_,l,i+X,f]),N}const Is=(e,t)=>{let n=0;for(let r=0;r<t;r++)n+=e.child(r).nodeSize;return n};function bx(e,t){const n=[];for(const[r,o,s,c]of xx(e,t)){const l=Is(e,r),i=Is(t,s),f=e.content.cut(l,Is(e,o)),p=t.content.cut(i,Is(t,c)),y=cu(f,p,l);if(y==null)continue;const E=iu(f,p,l+f.size,i+p.size);let D=E?E.a:l+f.size,N=E?E.b:i+p.size;const S=i-l;D<y&&(N+=y-D,D=y),N-S<y&&(D+=y-(N-S),N=y+S),n.push({from:y,to:D,slice:t.slice(y+S,N)})}return n}function vx(e,t,n){const r=bx(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 l=r[c];s.replace(l.from,l.to,l.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 Ae){const c=f=>{for(const p of r)if(f>p.from&&f<p.to){const y=s.mapping.map(p.from,-1);return Math.min(y+(f-p.from),y+p.slice.size,s.doc.content.size)}return null},l=c(o.head),i=c(o.anchor);if(l!=null||i!=null){const f=l??s.mapping.map(o.head),p=i??s.mapping.map(o.anchor);try{s.setSelection(Ae.between(s.doc.resolve(p),s.doc.resolve(f)))}catch{}}}return s.setMeta("addToHistory",!1)}const ar=new jn("amAgentChanges");let el=0;function lu(e,t){if(e.childCount!==t.childCount)return!1;for(let n=0;n<e.childCount;n++)if(!Vo(e.child(n),t.child(n)))return!1;return!0}function wx(e,t,n,r){const o=[...e.map(l=>({a:l.from,b:l.to,e:l})),...t.map(l=>({a:l.oldFrom,b:l.oldTo,c:l}))].sort((l,i)=>l.a-i.a||l.b-i.b),s=[];for(const l of o){const i=s[s.length-1],f=i?Math.max(...i.map(p=>p.b)):-1;i&&l.a<=f&&(l.c||i.some(p=>p.c))?i.push(l):s.push([l])}const c=[];for(const l of s){const i=l.filter(te=>te.e).map(te=>te.e),f=l.filter(te=>te.c).map(te=>te.c);if(!f.length){for(const te of i){const B=r.mapping.map(te.from,1);c.push({...te,from:B,to:Math.max(B,r.mapping.map(te.to,-1))})}continue}if(!i.length&&f.length===1){const te=f[0];c.push({id:++el,from:te.from,to:te.to,old:te.old,after:r.doc.slice(te.from,te.to).content});continue}const p=Math.min(...l.map(te=>te.a)),y=Math.max(...l.map(te=>te.b)),E=i.filter(te=>lu(n.slice(te.from,te.to).content,te.after)),D=i.reduce((te,B)=>te+(B.locked??0)+(E.includes(B)?0:1),0),N=new Rf(n);for(const te of[...E].sort((B,Y)=>Y.from-B.from))N.replace(te.from,te.to,te.old);const S=N.mapping.map(p,-1),A=N.mapping.map(y,1),_=r.mapping.map(p,-1),X=r.mapping.map(y,1);c.push({id:++el,from:_,to:X,old:N.doc.slice(S,A),after:r.doc.slice(_,X).content,...D?{locked:D}:{}})}return c.sort((l,i)=>l.from-i.from)}function kx(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),l=Math.min(o.to,r);l>c?(n.push(ir.inline(c,l,{class:s,"data-agent-change":String(o.id)})),e.doc.nodesBetween(c,l,(i,f)=>(i.isBlock&&i.isLeaf&&f>=c&&f+i.nodeSize<=l&&n.push(ir.node(f,f+i.nodeSize,{class:`${s} am-agent-change-block`})),!i.isTextblock))):n.push(ir.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 oo.create(e.doc,n)}function Cx(e){return[bt(()=>Sx(e))].flat()}function Sx(e){return new Ht({key:ar,state:{init:()=>({changes:[],current:null}),apply(t,n){const r=t.getMeta(ar);if(r&&"clear"in r)return{changes:[],current:null};if(r&&"add"in r){const s=wx(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=ar.getState(t);return n?kx(t,n):null}},view:t=>{const n=ar.getState(t.state);return n&&e.current(n),{update(r,o){const s=ar.getState(r.state);s&&s!==ar.getState(o)&&e.current(s)}}}})}function Ex(e,t,n){return n.length?e.setMeta(ar,{add:n,before:t}):e}function Mx(e){const t=ar.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,l)=>l.from-c.from)){if(!lu(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(ar,{clear:!0}).scrollIntoView()),{reverted:r,skipped:o}}function zx(e){e.dispatch(e.state.tr.setMeta(ar,{clear:!0}))}function Nx(e){const t=ar.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(ar,{current:r.id})),r}vn({"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 $x(){const{t:e}=nn();return m.jsxs("div",{className:"am-agent-capsule is-live",role:"status","aria-live":"polite","data-testid":"agent-live-capsule",children:[m.jsx("span",{className:"amx-pending-insert-spin","aria-hidden":!0}),m.jsx("span",{className:"am-agent-capsule-text",children:e("agentchg.live")}),m.jsx("span",{className:"am-agent-capsule-hint",children:e("agentchg.liveHint")})]})}function Ax({count:e,index:t,onReview:n,onRevert:r,onKeep:o}){const{t:s}=nn();return m.jsxs("div",{className:"am-agent-capsule",role:"status","aria-label":s("agentchg.label"),"data-testid":"agent-change-capsule",children:[m.jsx(kl,{size:14,"aria-hidden":!0}),m.jsx("span",{className:"am-agent-capsule-text",children:s("agentchg.summary",{n:String(e)})}),m.jsx("span",{className:"am-agent-capsule-sep","aria-hidden":!0}),m.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")}),m.jsx("button",{type:"button",className:"btn sm","data-act":"revert",onClick:r,children:s("agentchg.revert")}),m.jsx("button",{type:"button",className:"btn sm primary","data-act":"keep",onClick:o,children:s("agentchg.keep")})]})}vn({"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 Tx({x:e,y:t,anchorTop:n,title:r,hasSelection:o,askFirst:s,run:c,onApply:l,onClose:i,editorEl:f}){const{t:p}=nn(),[y,E]=k.useState(s?"ask":"running"),[D,N]=k.useState(""),[S,A]=k.useState(""),[_,X]=k.useState(""),[te,B]=k.useState(!1),Y=k.useRef(null),Te=k.useRef(""),Ve=k.useRef(void 0),h=k.useRef(null),Se=k.useRef(null),lt=k.useRef(f);lt.current=f;const ne=ve=>{Y.current?.abort();const Ce=new AbortController;Y.current=Ce,Ve.current=ve,Te.current="",A(""),X(""),B(!1),E("running"),c(ve,st=>{Ce.signal.aborted||(Te.current+=st,A(Te.current))},Ce.signal).then(st=>{if(Ce.signal.aborted)return;const Z=String(st.text??"");A(Z),B(!!st.toolCallText),Z.trim()?E("done"):(X(p("inlineai.errEmptyResult")),E("error"))}).catch(st=>{Ce.signal.aborted||(X(String(st?.message||st)),E("error"))})},de=()=>{Y.current?.abort(),Te.current.trim()?(A(Te.current),E("done")):s?E("ask"):i()};k.useEffect(()=>(s?requestAnimationFrame(()=>h.current?.focus()):ne(void 0),()=>Y.current?.abort()),[]);const ce=o?"replace":"insert",be=ve=>{const Ce=document.activeElement;return!Ce||Ce===document.body||Ce===document.documentElement?!0:Se.current?.contains(Ce)?!ve||Ce===Se.current:!!lt.current?.contains(Ce)},Ee=k.useRef({phase:y,text:S,primary:ce});return Ee.current={phase:y,text:S,primary:ce},k.useEffect(()=>{const ve=Ce=>{Ce.isComposing||Ce.keyCode===229||(Ce.key==="Escape"&&be(!1)?(Ce.preventDefault(),Ce.stopPropagation(),i()):Ce.key==="Enter"&&!Ce.shiftKey&&!Ce.metaKey&&!Ce.ctrlKey&&!Ce.altKey&&Ee.current.phase==="done"&&be(!0)&&(Ce.preventDefault(),Ce.stopPropagation(),l(Ee.current.primary,Ee.current.text)))};return window.addEventListener("keydown",ve,!0),()=>window.removeEventListener("keydown",ve,!0)},[i,l]),m.jsxs(qo,{innerRef:ve=>{Se.current=ve},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":y,children:[m.jsxs("div",{className:"am-ai-head",children:[m.jsx(kl,{size:14,"aria-hidden":!0}),m.jsx("span",{className:"am-ai-title",children:r}),y!=="ask"&&m.jsx("span",{className:"am-ai-hint",children:p(y==="running"?"inlineai.generating":"inlineai.hint")})]}),y==="ask"&&m.jsxs("div",{className:"am-ai-ask",children:[m.jsx("textarea",{ref:h,className:"am-ai-input",rows:2,value:D,placeholder:p(o?"inlineai.placeholderSel":"inlineai.placeholder"),onChange:ve=>N(ve.target.value),onKeyDown:ve=>{if(ve.key!=="Enter"||ve.shiftKey||ve.nativeEvent.isComposing||ve.keyCode===229)return;ve.preventDefault(),ve.stopPropagation();const Ce=D.trim();!Ce&&o||ne(Ce||void 0)}}),m.jsxs("div",{className:"am-ai-actions",children:[m.jsx("button",{type:"button",className:"btn sm primary","data-act":"send",disabled:o&&!D.trim(),onClick:()=>ne(D.trim()||void 0),children:p("inlineai.send")}),m.jsx("button",{type:"button",className:"btn sm","data-act":"discard",onClick:i,children:p("inlineai.discard")})]})]}),y!=="ask"&&m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"am-ai-preview","data-testid":"inline-ai-preview",children:S||(y==="running"?"…":"")}),y==="error"&&m.jsx("div",{className:"am-ai-error",role:"alert",children:_}),te&&y==="done"&&m.jsx("div",{className:"am-ai-error",children:p("inlineai.toolText")}),m.jsxs("div",{className:"am-ai-actions",children:[y==="running"&&m.jsx("button",{type:"button",className:"btn sm","data-act":"stop",onClick:de,children:p("inlineai.stop")}),y==="done"&&o&&m.jsxs(m.Fragment,{children:[m.jsx("button",{type:"button",className:"btn sm primary","data-act":"replace",onClick:()=>l("replace",S),children:p("inlineai.replace")}),m.jsx("button",{type:"button",className:"btn sm","data-act":"below",onClick:()=>l("below",S),children:p("inlineai.insertBelow")})]}),y==="done"&&!o&&m.jsx("button",{type:"button",className:"btn sm primary","data-act":"insert",onClick:()=>l("insert",S),children:p("inlineai.insert")}),(y==="done"||y==="error")&&m.jsx("button",{type:"button",className:"btn sm","data-act":"retry",onClick:()=>ne(Ve.current),children:p("inlineai.retry")}),m.jsx("button",{type:"button",className:"btn sm","data-act":"discard",onClick:i,children:p("inlineai.discard")})]})]})]})}vn({"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 zo=new jn("UNIFIED_PENDING_INSERT");function jx(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=we("pendins.busy",{label:e.label});const o=document.createElement("button");return o.type="button",o.className="btn sm",o.textContent=we("pendins.cancel"),o.addEventListener("mousedown",s=>s.preventDefault()),o.addEventListener("click",s=>{s.preventDefault(),e.onCancel()}),t.append(n,r,o),t}function Rx(){return[bt(()=>new Ht({key:zo,state:{init:()=>oo.empty,apply(e,t){let n=t.map(e.mapping,e.doc);const r=e.getMeta(zo);return r&&"add"in r?n=n.add(e.doc,[ir.widget(r.add.pos,()=>jx(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=>zo.getState(e)}}))]}function uu(e,t){const r=zo.getState(e)?.find(void 0,void 0,o=>o.id===t)[0];return r?r.from:null}let Lx=0;function Dx(e,t,n=!0){const r=`p${Date.now().toString(36)}${(Lx++).toString(36)}`;let o=!1;const s=()=>{o=!0,du(e,r)};return e.dispatch(e.state.tr.setMeta(zo,{add:{id:r,pos:e.state.selection.head,label:t,visible:n,onCancel:s}})),{id:r,label:t,cancelled:()=>o}}function du(e,t){e.isDestroyed||uu(e.state,t)==null||e.dispatch(e.state.tr.setMeta(zo,{remove:t}))}function Ix(e,t,n){const r=uu(e.state,t);if(r==null)return!1;let o=e.state.tr.setMeta(zo,{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 l=e.state.selection;let i,f,p;if(c<1)i=r,o=o.insert(r,n),f=r+n.size,p=e.hasFocus()&&l.empty&&l.head===r;else{const y=s.before(c),E=s.after(c),D=s.node(c).textContent.trim()==="";p=e.hasFocus()&&l.from>=y&&l.to<=E,i=D?y:E,o=D?o.replaceWith(y,E,n):o.insert(E,n),f=i+n.size}return Hs(o,i,f),p&&(o=o.setSelection(Ae.near(o.doc.resolve(Math.min(f,o.doc.content.size)),-1)).scrollIntoView()),e.dispatch(o),!0}function tl(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{level:"warning",text:we("pendins.sourceMode",{label:e})}}))}function Px(e){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("pendins.lost",{label:e})}}))}function fu(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 ro=new jn("amInlineAi");function Fx(e){const t=e.state.selection;if(!(t instanceof Ae)||!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 Ox(e){return new Ht({key:ro,state:{init:()=>null,apply(t,n){const r=t.getMeta(ro);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=ro.getState(t);return!n||n.to<=n.from?null:oo.create(t.doc,[ir.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()||!Fx(t)?!1:(e.onSpace(t),!0)}}})}function _x(e){return[bt(()=>Ox({spaceTrigger:e.spaceTrigger,onSpace:t=>e.onSpace.current(t)}))].flat()}function Bx(e,t,n){const r={from:t,to:n,text:e.state.doc.textBetween(t,n,`
|
|
49
|
-
`,""),sig:fu(e.state.doc,t,n)},o=e.state.tr.setMeta(ro,{set:r});return n>t&&o.setSelection(Ae.create(o.doc,n)),e.dispatch(o),r}function nl(e){const t=ro.getState(e.state);if(!t)return;const n=e.state.tr.setMeta(ro,{clear:!0});if(t.to>t.from&&t.to<=n.doc.content.size)try{n.setSelection(Ae.create(n.doc,t.from,t.to))}catch{}e.dispatch(n)}function rl(e){return ro.getState(e.state)??null}function Kx(e,t,n){const r=e.content.size,o=e.textBetween(Math.max(0,t-8e3),t,`
|
|
50
|
-
`,"").slice(-2e3),s=e.textBetween(n,Math.min(r,n+4e3),`
|
|
51
|
-
`,"").slice(0,1e3);return{before:o,after:s}}function Hx(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 Vx(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 qx(e,t,n,r){if(!n.childCount)return null;const{doc:o}=e.state,s=o.content.size,c=Math.min(t.from,s),l=Math.min(Math.max(t.to,c),s);let i=r;i==="replace"&&fu(o,c,l)!==t.sig&&(i="below");let f=e.state.tr,p;if(i==="replace"){const y=n.childCount===1&&!!n.firstChild?.isTextblock&&o.resolve(c).sameParent(o.resolve(l));f=f.replaceRange(c,l,y?new Oa(n,1,1):new Oa(n,0,0)),p=f.mapping.map(l,1)}else{const y=Vx(o,i==="below"?l:c);if(!y)return null;i==="insert"&&y.blank?(f=f.replaceWith(y.from,y.to,n),p=y.from+n.size):(f=f.insert(y.to,n),p=y.to+n.size)}return f=f.setSelection(Ae.near(f.doc.resolve(Math.min(p,f.doc.content.size)),-1)),e.dispatch(f.setMeta(ro,{clear:!0}).scrollIntoView()),i}vn({"unipage.menu.askTangu":{zh:"问 Tangu",en:"Ask Tangu"}});const Wx=2e4;function Yx(e,t){let n=null;for(const r of Ws(e)){if(r.pos>t)break;n=r.text}return n}function Xx(e,t,n,r){const o=e.textBetween(t,n,`
|
|
52
|
-
`,"").trim().slice(0,Wx);if(!o)return"";const s=Yx(e,t),c=s&&!/[[\]|#^\n]/.test(s)?`#${s}`:"";return r?`${o}
|
|
53
|
-
— [[${r}${c}]]`:o}function mu(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 Ux(e,t,n){if(e.resolve(t).depth!==0)return mu(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 Gx(e,t){if(!t)return null;const n=Ws(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?Ux(e,o.pos,o.level):e.content.size,l=(t.text??"").split(`
|
|
54
|
-
`).map(i=>i.trim()).filter(Boolean);if(l.length){const i=[];e.nodesBetween(s,c,(p,y)=>p.isTextblock?(y>=s&&i.push({pos:y,text:p.textContent}),!1):!0);const f=i.findIndex(p=>p.text.includes(l[0]));if(f>=0){const p=l[l.length-1],y=i.findIndex((D,N)=>N>=f&&D.text.includes(p)),E=mu(e,i[y>=0?y:f].pos+1);if(E!=null)return E}}return o?c:null}vn({"linkcard.text":{zh:"文字",en:"Text"},"linkcard.link":{zh:"链接",en:"Link"},"linkcard.copy":{zh:"复制链接",en:"Copy link"},"linkcard.unlink":{zh:"移除链接",en:"Remove link"},"linkcard.fnEmpty":{zh:"脚注还是空的",en:"This footnote is empty"},"linkcard.fnMissing":{zh:"找不到这条脚注的定义",en:"Footnote definition not found"}});const ol=500,Ra=250,sl='a[href], sup[data-type="footnote_reference"]';function pu(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((y,E)=>s.push({node:y,from:o+E,to:o+E+y.nodeSize}));const c=y=>!!n.isInSet(y.node.marks);let l=s.findIndex(y=>c(y)&&t>=y.from&&t<y.to);if(l<0&&(l=s.findIndex(y=>c(y)&&t>=y.from&&t<=y.to)),l<0)return null;const i=n.isInSet(s[l].node.marks);let f=l,p=l;for(;f>0&&i.isInSet(s[f-1].node.marks);)f--;for(;p<s.length-1&&i.isInSet(s[p+1].node.marks);)p++;return{from:s[f].from,to:s[p].to,mark:i}}function Jx(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=pu(e.state.doc,r,n);return o&&o.from<o.to?{from:o.from,to:o.to}:null}function Zx({getView:e,onOpenNote:t}){const{t:n}=nn(),[r,o]=k.useState(null),[s,c]=k.useState(null),[l,i]=k.useState(null),f=k.useRef(null),p=k.useRef(null);k.useEffect(()=>{const N=()=>{f.current&&clearTimeout(f.current),p.current&&clearTimeout(p.current),f.current=null,p.current=null},S=X=>{const te=e()?.dom.closest(".unified-body");return!!te&&X.closest(".unified-body")===te},A=X=>{const B=X.target?.closest?.(sl);if(!B||!S(B))return;if(p.current&&(clearTimeout(p.current),p.current=null),f.current&&clearTimeout(f.current),B.tagName==="SUP"){f.current=setTimeout(()=>{const Te=e(),Ve=B.getBoundingClientRect();o(null),c({num:B.textContent??"",text:Te?hd(Te.state.doc,B.getAttribute("data-label")??""):null,x:Ve.left,y:Ve.bottom+6})},ol);return}const Y=B;f.current=setTimeout(()=>{const Te=e();c(null);const Ve=Y.getBoundingClientRect(),h=Te?Jx(Te,Y):null;o({href:Y.getAttribute("href")??"",text:h&&Te?Te.state.doc.textBetween(h.from,h.to):Y.textContent??"",from:h?.from??-1,to:h?.to??-1,x:Ve.left,y:Ve.bottom+6})},ol)},_=X=>{!X.target?.closest?.(sl)||X.relatedTarget?.closest?.(".amx-linkcard")||(f.current&&clearTimeout(f.current),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{o(null),c(null)},Ra))};return document.addEventListener("mouseover",A,!0),document.addEventListener("mouseout",_,!0),()=>{document.removeEventListener("mouseover",A,!0),document.removeEventListener("mouseout",_,!0),N()}},[e]),k.useEffect(()=>{if(!r&&!s||l)return;const N=()=>{o(null),c(null)};return document.addEventListener("scroll",N,!0),()=>document.removeEventListener("scroll",N,!0)},[r,s,l]);const y=(N,S,A,_,X)=>{const te=e(),B=te?.state.schema.marks.link;if(!te||!B)return;const{doc:Y}=te.state;if(S>Y.content.size||N>=S)return;const Te=pu(Y,N,B);if(!Te||Te.from!==N||Te.to!==S||Te.mark.attrs.href!==A)return;const Ve=Y.textBetween(N,S),h=lt=>B.create({...Te.mark.attrs,href:lt,..."ref"in Te.mark.attrs?{ref:null}:{}});let Se=te.state.tr;if(_==="")Se=Se.delete(N,S);else if(_!==null&&_!==Ve){let lt=null;Y.nodesBetween(N,S,de=>de.isInline?(lt=lt===null?de.marks:lt.filter(ce=>ce.isInSet(de.marks)),!1):!0);const ne=(lt??[]).filter(de=>de.type!==B);Se=Se.replaceWith(N,S,te.state.schema.text(_,X?h(X).addToSet(ne):ne)),Se.setSelection(Ae.near(Se.doc.resolve(N+_.length)))}else if(X){if(X===Te.mark.attrs.href){te.focus();return}Se=Se.removeMark(N,S,Te.mark).addMark(N,S,h(X))}else Se=Se.removeMark(N,S,Te.mark);te.dispatch(Se.scrollIntoView()),te.focus()};if(l){const N=!!_c(l.href)&&!!l.text.trim(),S=()=>{i(null),o(null),e()?.focus()};return m.jsxs(no,{children:[m.jsx("div",{className:"amx-linkedit-backdrop",onMouseDown:()=>i(null),role:"presentation"}),m.jsx(qo,{className:"amx-linkedit",x:window.innerWidth/2,y:Math.round(window.innerHeight*.3),center:!0,children:m.jsxs("form",{className:"amx-linkedit-form",onSubmit:A=>{A.preventDefault();const _=_c(l.href);!_||!l.text.trim()||(y(l.from,l.to,l.wasHref,l.text,_),i(null),o(null))},onKeyDown:A=>{A.key==="Escape"&&(A.preventDefault(),A.stopPropagation(),S())},children:[m.jsxs("label",{children:[n("linkcard.text"),m.jsx("input",{autoFocus:!0,value:l.text,onChange:A=>i({...l,text:A.target.value}),onFocus:A=>A.currentTarget.select()})]}),m.jsxs("label",{children:[n("linkcard.link"),m.jsx("input",{value:l.href,onChange:A=>i({...l,href:A.target.value})})]}),m.jsxs("div",{className:"amx-linkedit-row",children:[m.jsx("button",{type:"button",onClick:S,children:n("common.cancel")}),m.jsx("button",{type:"submit",className:"primary",disabled:!N,children:n("common.save")})]})]})})]})}if(s)return m.jsx(no,{children:m.jsxs(qo,{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),Ra)},children:[m.jsx("span",{className:"amx-fncard-num",children:s.num}),m.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 E=r.href;try{E=new URL(r.href).host||r.href}catch{}const D=r.from>=0&&(e()?.editable??!0);return m.jsx(no,{children:m.jsxs(qo,{className:"amx-linkcard",x:r.x,y:r.y,onMouseEnter:()=>{p.current&&clearTimeout(p.current),p.current=null},onMouseLeave:()=>{p.current=setTimeout(()=>o(null),Ra)},children:[m.jsx("button",{className:"amx-linkcard-host",title:r.href,onClick:()=>{t&&pd(r.href)==="note"?(o(null),t(r.href)):window.open(r.href,"_blank","noopener")},children:E}),m.jsx("span",{className:"amx-linkcard-sep"}),m.jsx("button",{onClick:()=>{navigator.clipboard.writeText(r.href)},children:n("linkcard.copy")}),D&&m.jsx("button",{onClick:()=>i({from:r.from,to:r.to,text:r.text,href:r.href,wasHref:r.href}),children:n("common.edit")}),D&&m.jsx("button",{onClick:()=>{y(r.from,r.to,r.href,null,null),o(null)},children:n("linkcard.unlink")}),D&&m.jsx("button",{className:"danger",onClick:()=>{y(r.from,r.to,r.href,"",null),o(null)},children:n("common.delete")})]})})}vn({"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 Qa(e){const t=e?.state.selection;return t instanceof ye&&t.node.type.spec.tableRole==="table"}function Qx(e,t,n){if(!e||!Qa(e))return null;const r=document.elementFromPoint(t,n)?.closest?.("td,th");if(!r||!e.dom.contains(r))return null;try{return wd(e.state.doc,e.posAtDOM(r,0))}catch{return null}}const eb=[{op:"rowAbove",key:"unipage.table.rowAbove",Icon:op},{op:"rowBelow",key:"unipage.table.rowBelow",Icon:np},{op:"colLeft",key:"unipage.table.colLeft",Icon:ip},{op:"colRight",key:"unipage.table.colRight",Icon:ap},{op:"deleteRow",key:"unipage.table.deleteRow",Icon:Ba},{op:"deleteCol",key:"unipage.table.deleteCol",Icon:Ba}],tb=[{align:"left",key:"unipage.table.alignLeft",Icon:Lf},{align:"center",key:"unipage.table.alignCenter",Icon:yd},{align:"right",key:"unipage.table.alignRight",Icon:xd}];function nb({view:e,cell:t,onDone:n}){const{t:r}=nn(),o=e.state.selection;if(!(o instanceof ye)||o.node.type.spec.tableRole!=="table")return null;const s=gd(e.state.doc,o.from,t);if(!s)return null;const c=l=>{n();const i=l();i&&e.dispatch(i),e.focus()};return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"ubm-sep",role:"separator"}),m.jsx("div",{className:"ubm-label",role:"presentation",children:r("unipage.table.label")}),eb.filter(l=>s.ops.includes(l.op)).map(({op:l,key:i,Icon:f})=>m.jsxs("button",{"data-table-op":l,role:"menuitem",tabIndex:-1,onClick:()=>c(()=>bd(e.state,s.cellPos,l)),children:[m.jsx(f,{size:13})," ",r(i)]},l)),s.align&&tb.map(({align:l,key:i,Icon:f})=>m.jsxs("button",{"data-table-align":l,"aria-checked":s.align===l,role:"menuitemcheckbox",tabIndex:-1,onClick:()=>c(()=>vd(e.state,s.cellPos,l)),children:[m.jsx(f,{size:13})," ",r(i),s.align===l&&m.jsx(xl,{size:13,className:"ubm-check"})]},l))]})}function rb(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:l}of n){let i,f;try{i=r.posAtDOM(c.startContainer,c.startOffset),f=r.posAtDOM(c.endContainer,c.endOffset)}catch{continue}f<=i||r.state.doc.textBetween(i,f,`
|
|
55
|
-
`,"")!==c.toString()||o.push({from:i,to:f,text:l})}if(!o.length)return 0;o.sort((c,l)=>l.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}}}vn({"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 ob=800;let Ps=null,La=null;const sb={insertAfter:()=>{},deleteEmpty:()=>{},mergePrev:()=>{},arrow:()=>{},moveDir:()=>{},selfFocus:()=>{}};async function hu(e,t){try{const n=new Uint8Array(await t.arrayBuffer()),{opts:r}=await Ka(),{base:o}=await bn.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 _s(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 ab(e,t,n=!1,r=!1){const o=[],s=vx(e.state,t,n?o:void 0);s&&(r&&s.setMeta("addToHistory",!0),e.dispatch(n?Ex(s,e.state.doc,o):s))}function cb({path:e,pageDir:t,body:n,onChange:r,onFinalFlush:o,skipFinalFlush:s,hidden:c,apiRef:l,probe:i,extraPlugins:f,focusPlace:p,onFocused:y,onCard:E,readOnly:D=!1,onAskTangu:N,aiMenu:S,onAiPrompt:A}){const[,_]=Md(),X=tc(),te=k.useRef(null),[B,Y]=k.useState(!1),Te=k.useRef({onFinalFlush:o,skipFinalFlush:s});Te.current={onFinalFlush:o,skipFinalFlush:s};const Ve=k.useRef(E);Ve.current=E;const h=k.useRef(A);h.current=A,k.useEffect(()=>(l.current={applySlashItem:Z=>Ce.current(Z),applyBody:(Z,oe,je)=>{let j=!1;return _()?.action(J=>{const se=J.get(xn),xe=J.get(Ro)(go(Z,t));xe&&(ab(se,xe,oe,je),Nd(se.state.doc,xe),j=!0,i&&(i.reconciled=(i.reconciled??0)+1))}),j},serializeNow:()=>{let Z=null;return _()?.action(oe=>{const je=oe.get(xn);Z=Po(Ms(oe,je.state.doc),t)}),Z},canonical:Z=>{let oe=null;return _()?.action(je=>{const j=je.get(Ro)(go(Z,t));j&&(oe=Po(Ms(je,j),t))}),oe},insertFiles:Z=>{lt(Z)},insertMarkdown:(Z,oe,je)=>ne(Z,oe,je),parseMd:Z=>{let oe=null;return _()?.action(je=>{const j=je.get(Ro)(go(Z,t));oe=j?.childCount?j.content:null}),oe},serializeMd:Z=>{let oe=null;try{_()?.action(je=>{const J=je.get(xn).state.schema.topNodeType.createAndFill(void 0,Z);J&&(oe=zd(je.get(im)(J)))})}catch{return null}return oe},serializeStored:Z=>{let oe=null;try{_()?.action(je=>{const j=je.get(xn).state.schema.topNodeType.createAndFill(void 0,Z);j&&(oe=Po(Ms(je,j),t))})}catch{return null}return oe},focusStart:()=>{_()?.action(Z=>{const oe=Z.get(xn);oe.dispatch(oe.state.tr.setSelection(Ae.atStart(oe.state.doc))),oe.focus()})},focusEnd:()=>{_()?.action(Z=>{const oe=Z.get(xn);oe.dispatch(oe.state.tr.setSelection(Ae.atEnd(oe.state.doc))),oe.focus()})},focusTail:()=>{_()?.action(Z=>{const oe=Z.get(xn),{doc:je,schema:j}=oe.state,J=j.nodes.paragraph,se=He=>!!He&&He.type===J&&He.content.size===0,xe=je.lastChild;let Qe=oe.state.tr;se(xe)||(Qe=Qe.insert(je.content.size,J.create())),oe.dispatch(Qe.setSelection(Ae.atEnd(Qe.doc)).scrollIntoView()),oe.focus()})},hasFocus:()=>{let Z=!1;return _()?.action(oe=>{Z=oe.get(xn).hasFocus()}),Z},revealSelection:()=>{_()?.action(Z=>{const oe=Z.get(xn);oe.dispatch(oe.state.tr.scrollIntoView()),oe.focus()})},serializePrefix:Z=>{let oe=null;try{_()?.action(je=>{const j=je.get(xn);oe=Po(Ms(je,j.state.doc.cut(0,Math.min(Z,j.state.doc.content.size))),t)})}catch{return null}return oe},posAfterPrefix:Z=>{let oe=null;try{_()?.action(je=>{const j=je.get(Ro)(go(Z,t));j&&(oe=Ae.atEnd(j).head)})}catch{return null}return oe}},()=>{if(!Te.current.skipFinalFlush()){const Z=l.current?.serializeNow()??null;Z!=null&&Te.current.onFinalFlush(Z)}l.current=null}),[_,t]);const Se=async Z=>{try{const oe=new Uint8Array(await Z.arrayBuffer()),{opts:je}=await Ka(),{pageRel:j}=await bn.saveAttachment(e,Z.name||"pasted.png",oe,je);return dl(ul(t,j))}catch{return null}},lt=async Z=>{if(!Z.length)return;const oe=Z.map((j,J)=>`${we("unipage.upload.uploading",{name:j.name||we("unipage.upload.fileN",{n:J+1})})}`);_()?.action(j=>{const J=j.get(xn),se=J.state.schema.nodes.paragraph;if(!se)return;const{$to:xe}=J.state.selection;let Qe=xe.depth>=1?xe.after(1):xe.pos,He=J.state.tr;for(const Rt of oe){const at=se.create(null,J.state.schema.text(Rt));He=He.insert(Qe,at),Qe+=at.nodeSize}J.dispatch(He.scrollIntoView())});const je=(j,J)=>{_()?.action(se=>{const xe=se.get(xn);let Qe=-1,He=-1;if(xe.state.doc.descendants((Pt,St)=>Qe>=0||!Pt.isTextblock||Pt.textContent!==j?!0:(Qe=St,He=St+Pt.nodeSize,!1)),Qe<0)return;const Rt={from:Qe,to:He},at=xe.state.schema.nodes.paragraph,Vt=J&&at?xe.state.tr.replaceWith(Rt.from,Rt.to,at.create(null,xe.state.schema.text(J))):xe.state.tr.delete(Rt.from,Rt.to);xe.dispatch(Vt)})};for(let j=0;j<Z.length;j++)je(oe[j],await hu(e,Z[j]))},ne=(Z,oe="cursor",je)=>{let j=!1;return _()?.action(J=>{const se=J.get(xn),xe=J.get(Ro)(go(Z,t));if(!xe?.childCount)return;const Qe=xe.content,He=!!je?.quiet,Rt=He?Gx(se.state.doc,je?.after):null;if(He&&Rt==null&&je?.caretless&&(oe="end"),oe!=="cursor"||Rt!=null){const gt=Rt??(oe==="start"?0:se.state.doc.content.size),ot=se.state.tr.insert(gt,Qe);He?de(se,ot,gt):se.dispatch(ot),j=!0;return}const{$from:at}=se.state.selection;let Vt=at.depth;for(;Vt>=1&&!["doc","amadeusColumnCell","blockquote"].includes(at.node(Vt-1).type.name);)Vt--;if(Vt<1)return;const Pt=(gt,ot)=>{const Ft=Ae.near(gt.doc.resolve(Math.min(ot,gt.doc.content.size)),-1),on=je?.caretBack??0;gt.setSelection(on&&Ft.$from.parentOffset>=on?Ae.create(gt.doc,Ft.from-on):Ft)};if(at.depth>Vt&&at.parent.isTextblock&&at.parent.content.size===0){const gt=se.state.tr,ot=on=>{const Ut=gt.doc.resolve(on),Cn=Ut.index(-1);return Ut.parent.isTextblock&&Ut.parent.content.size===0&&Ut.node(-1).canReplace(Cn,Cn+1,Qe)};let Ft=at.pos;if(!ot(Ft)){for(let on=gt.doc.resolve(Ft).depth;on>0;on--)if(gt.doc.resolve(Ft).node(on).type.name==="list_item"){Ft=$d(gt,Ft,["list_item"]);break}}if(ot(Ft)){const on=gt.doc.resolve(Ft),Ut=on.before();gt.replaceWith(Ut,on.after(),Qe),Hs(gt,Ut,Ut+Qe.size),Pt(gt,Ut+Qe.size),He?de(se,gt,Ut):(se.dispatch(gt.scrollIntoView()),se.focus()),j=!0;return}}const St=at.before(Vt),ln=at.after(Vt),ct=at.node(Vt).textContent.trim()==="",qn=ct?se.state.tr.replaceWith(St,ln,Qe):se.state.tr.insert(ln,Qe);Hs(qn,ct?St:ln,(ct?St:ln)+Qe.size),Pt(qn,(ct?St:ln)+Qe.size),He?de(se,qn,ct?St:ln):(se.dispatch(qn.scrollIntoView()),se.focus()),j=!0}),j},de=(Z,oe,je)=>{Z.dispatch(Vs(oe)),gl(Z,Math.min(je+1,Z.state.doc.content.size));const j=Z.nodeDOM(je);if(!(j instanceof HTMLElement))return;const J=j.getBoundingClientRect();(J.top<0||J.top>window.innerHeight-40)&&ss(j),_s(j.getBoundingClientRect())},ce=(Z,oe=!0)=>{let je=null;return _()?.action(j=>{je=Dx(j.get(xn),Z,oe)}),je},be=Z=>{Z&&_()?.action(oe=>du(oe.get(xn),Z.id))},Ee=(Z,oe,je=!0)=>{if(oe?.cancelled())return;if(c?.()){be(oe),tl(oe?.label??"");return}const j=()=>{je||!oe?window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.insertPointLost")}})):Px(oe.label)};if(!l.current||!oe){j();return}let J=!1;_()?.action(se=>{const xe=se.get(Ro)(go(Z,t));J=Ix(se.get(xn),oe.id,xe?.childCount?xe.content:null)}),J||j()},ve=async(Z,oe,je,j=!1)=>{try{const{base:J}=await bn.saveAttachment(e,Z,oe,{mode:"vault",folder:da(e)});Ee(`![[${j?J.replace(/\.md$/i,""):J}]]`,je),X.getState().syncFdChildren(e)}catch{be(je)}},Ce=k.useRef(()=>{}),st=Z=>{const oe=te.current;if(!oe)return;const je=Z.run?void 0:jd[Z.scaffold];if(je){oe.transform(je)||Rd(Z.label);return}oe.consume();const j=Ld;if(Z.scaffold===j.template){window.dispatchEvent(new CustomEvent("amadeus:template-picker",{detail:{v4Path:e}}));return}if(Z.scaffold===j.card){_()?.action(J=>Ve.current(J.get(xn)));return}if(Z.scaffold===j.ai){_()?.action(J=>h.current?.(J.get(xn)));return}if(Z.run){const J=ce(Z.label);(async()=>{try{const se=await Z.run({pagePath:e,folder:da(e)});if(se===""||se==null){be(J);return}if(typeof se!="string")throw new Error(we("unipage.plugin.notString",{type:typeof se}));if(se.length>8192)throw new Error(we("unipage.plugin.tooLong"));if(Array.from(se).some(xe=>xe.charCodeAt(0)<32&&xe!==" "&&xe!==`
|
|
56
|
-
`))throw new Error(we("unipage.plugin.controlChars"));Ee(se,J,!1),X.getState().syncFdChildren(e)}catch(se){if(be(J),J?.cancelled())return;console.error("[plugin] slash item failed",se),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.plugin.failed",{label:Z.label,err:se instanceof Error?se.message:String(se)}),error:!0}}))}})();return}if(Z.scaffold===j.image){const J=document.createElement("input");J.type="file",J.accept="image/*",J.onchange=()=>{const se=J.files?.[0];if(!se)return;const xe=ce(Z.label);(async()=>{try{const Qe=new Uint8Array(await se.arrayBuffer()),{opts:He}=await Ka(),{base:Rt}=await bn.saveAttachment(e,se.name||"image.png",Qe,He);Ee(`![[${Rt}]]`,xe)}catch{be(xe)}})()},J.click();return}if(Z.scaffold===j.column){_()?.action(J=>{const se=J.get(xn),{$from:xe}=se.state.selection;if(xe.depth!==1){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.columnTopLevelOnly")}}));return}Vl(se,xe.before(1),xe.after(1),xe.node(1)),se.focus()});return}if(Z.scaffold===j.page){const J=ce(Z.label);(async()=>{try{const se=X.getState(),xe=await se.createChildNote(e,we("amadeus.default.note"));Ee(`[[${xe.split("/").pop().replace(/\.md$/i,"")}]]`,J),se.loadPage(xe)}catch{be(J)}})();return}if(Z.scaffold===j.database){const J=we("amadeus.default.database");ve(`${J}.db`,new TextEncoder().encode(Oc(Xu(J))),ce(Z.label));return}if(Z.scaffold===j.drawing){ve(`${Dd(we("unipage.file.drawing"))}.excalidraw.md`,new TextEncoder().encode(Uu(Ju)),ce(Z.label),!0);return}if(Z.scaffold===j.noteview){const J=ce(Z.label);(async()=>{const se=da(e);let xe=null;for(let He=1;He<=20&&xe===null;He++)try{xe=await bn.createFolder(se,He===1?we("unipage.file.noteView"):we("unipage.file.noteViewN",{n:He}))}catch{}if(xe===null){be(J);return}const Qe=we("unipage.file.untitledView");await ve(`${Qe}.db`,new TextEncoder().encode(Oc(Zu(Qe,xe))),J)})();return}if(Z.scaffold===j.linkdb){Y(!0);return}if(Z.scaffold===j.bookmark){const J=ce(Z.label,!1);_a(we("unipage.bookmark.title"),"",{label:we("unipage.bookmark.label")}).then(se=>{const xe=se?.trim();xe&&/^https?:\/\/\S+$/i.test(xe)?Ee(xe,J,!1):be(J)});return}if(Z.scaffold===j.embed){const J=ce(Z.label,!1);(async()=>{let se="";try{const He=/!?\[\[([^\]\n]+)\]\]/.exec(await navigator.clipboard.readText());He&&(se=He[1].trim())}catch{}const Qe=(await _a(we("unipage.embed.title"),se,{label:we("unipage.embed.label"),confirmLabel:we("unipage.embed.confirm")}))?.trim().replace(/^!?\[\[/,"").replace(/\]\]$/,"").trim();Qe?Ee(`![[${Qe}]]`,J,!1):be(J)})();return}ne(Z.scaffold,"cursor",Z.key==="math"?{caretBack:3}:void 0)};return Ce.current=st,m.jsxs(m.Fragment,{children:[m.jsx(Ad,{initial:go(n,t),onChange:Z=>r(Po(Z,t)),keys:sb,saveImage:Se,saveFiles:lt,onOpenWiki:(Z,oe)=>{X.getState().openWikiLink(Z,e,oe)},getPageNames:()=>X.getState().pages,slashOpsRef:te,onSlashPick:st,getFiles:()=>lm()?X.getState().files:[],isWikiResolved:Z=>!!ms(Z,X.getState().pages,e)||!!vl(Z,X.getState().files,e),wikiIcon:Z=>{const oe=ms(Z,X.getState().pages,e);return oe?X.getState().icons[oe]:void 0},focusPlace:p,onFocused:y,unified:!0,attachmentPagePath:e,extraPlugins:f,readOnly:D,onAskTangu:N,aiMenu:S}),B&&m.jsx(no,{children:m.jsx(Td,{onClose:()=>Y(!1),onPick:Z=>{Y(!1),c?.()?tl(we("mdblock.slash.linkdb")):ne(`![[${Z}]]`)}})})]})}function al(e){e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)}function ib(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 l=o.offsetTop>=s.offsetTop;return r.remove(),l}function lb({path:e,icon:t,cover:n,onSetIcon:r,onSetCover:o,onRename:s,onDetachedRename:c,onEnterBody:l,focusSignal:i,compact:f=!1,readOnly:p=!1}){const{t:y}=nn(),E=hl(),D=(e.split("/").pop()??e).replace(/\.md$/i,""),N=xm.test(D)?"":D,[S,A]=k.useState(N),[_,X]=k.useState(null),[te,B]=k.useState(null),Y=k.useRef(null),Te=k.useRef(null),Ve=k.useRef(c);Ve.current=c,k.useEffect(()=>{A(N),Te.current=null},[e]),k.useLayoutEffect(()=>()=>{const ne=Te.current;Te.current=null,ne!=null&&Ve.current(ne)},[]),k.useLayoutEffect(()=>{al(Y.current)},[S]),k.useEffect(()=>{const ne=Y.current;if(!ne)return;let de=ne.clientWidth;const ce=new ResizeObserver(()=>{ne.clientWidth!==de&&(de=ne.clientWidth,al(ne))});return ce.observe(ne),()=>ce.disconnect()},[]),k.useEffect(()=>{if(!i)return;const ne=Y.current;if(ne){ne.focus();const de=ne.value.length;ne.setSelectionRange(de,de)}},[i]);const h=k.useRef(null),Se=k.useRef(!1),lt=()=>{const ne=h.current;if(h.current=null,Te.current=null,Se.current){Se.current=!1,A(N);return}const de=S.trim();de&&de!==D?s(de,ne).then(ce=>{ce||A(N)}):A(N)};return p?m.jsxs("div",{className:"amx-title-wrap amx-title-ro",children:[t&&m.jsx("span",{className:"amx-title-bigicon","aria-hidden":!0,children:t}),m.jsx("div",{className:"amx-title-row",children:m.jsx("h1",{className:"amx-title-input amx-title-static",children:N||D})})]}):m.jsxs("div",{className:"amx-title-wrap",children:[!f&&t&&m.jsx("button",{className:"amx-title-bigicon",title:y("unipage.title.iconAction"),onClick:ne=>{const de=ne.currentTarget.getBoundingClientRect();X({x:de.left,y:de.bottom+6})},children:t}),!f&&(!t||!n)&&m.jsxs("div",{className:"amx-title-actions",children:[!t&&m.jsxs("button",{onClick:()=>r(hm()),children:[m.jsx(pm,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),y("unipage.title.addIcon")]}),!n&&m.jsxs("button",{onClick:ne=>{const de=ne.currentTarget.getBoundingClientRect();B({x:de.right,y:de.bottom+6})},children:[m.jsx(rm,{size:14,strokeWidth:1.7,"aria-hidden":"true"}),y("unipage.title.addCover")]})]}),m.jsx("div",{className:"amx-title-row",children:m.jsx("textarea",{ref:Y,className:"amx-title-input",rows:1,spellCheck:E,value:S,placeholder:"New Page",onChange:ne=>{const de=ne.target.value.replace(/[\r\n]+/g," ");Te.current=de,A(de)},onBlur:lt,onKeyDown:ne=>{if(ne.nativeEvent.isComposing||ne.keyCode===229)return;const de=ne.currentTarget;if(ne.key==="Tab"){ne.preventDefault();return}const ce=de.selectionStart===de.selectionEnd,be=ce&&de.selectionEnd===de.value.length,Ee=!ne.shiftKey&&!ne.altKey&&!ne.metaKey&&!ne.ctrlKey,ve=ne.key==="ArrowDown"&&Ee&&ce&&ib(de);(ne.key==="Enter"||ne.key==="ArrowRight"&&Ee&&be||ve)&&(ne.preventDefault(),h.current=ne.key==="Enter"?"enter":"move",de.blur(),l(ne.key==="Enter"?"enter":"move")),ne.key==="Escape"&&(Te.current=null,Se.current=!0,A(N),de.blur())}})}),_&&m.jsx(gm,{x:_.x,y:_.y,current:t,onPick:ne=>{r(ne),X(null)},onClose:()=>X(null)}),te&&m.jsx(ym,{page:e,x:te.x,y:te.y,onApply:ne=>o(ne),onClose:()=>B(null)})]})}function ub({path:e,initial:t,diskRaw:n,probe:r,onRenamed:o,onCanvasMode:s,historyRef:c,filesRef:l,mdRef:i,onUnlock:f,compact:p=!1,readOnly:y=!1,hardBreaks:E=!1}){const D=e.split("/").slice(0,-1).join("/"),N=tc(),S=N.getState().vaultRoot,A=k.useContext(Df),_=If(),X=A??_,te=Pf(a=>Ff(a,X)),B=y?"wysiwyg":te,{t:Y}=nn(),Te=hl(),Ve=k.useRef(null);if(!Ve.current){const a=Bo(n??t),{fmText:d,body:g}=vo(n==null?a.text:Bo(t).text);Ve.current={fm:d,body:g,lastSaved:a.text,eol:a.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:y,slot:A,peerPatch:null}}const h=Ve.current,Se=k.useRef(0),lt=k.useRef(null),ne=k.useRef(()=>{lt.current?.()}).current,de=()=>{Se.current=performance.now(),si(ne)},ce=k.useRef(!1);k.useEffect(()=>{A!=null&&A===_&&de()},[A,_]);const[be]=k.useState(()=>new Set),Ee=()=>{for(const a of[...be])a()},[ve,Ce]=k.useState(0),[st,Z]=k.useState(0),oe=k.useRef(null),je=k.useRef(B==="source"),j=k.useMemo(()=>({get current(){return je.current?null:oe.current}}),[]);if(je.current!==(B==="source")){if(B==="source"){const a=oe.current?.serializeNow();a!=null&&(h.body=a)}je.current=B==="source"}const J=k.useRef(null),se=k.useRef(null),[xe,Qe]=k.useState(null),[He,Rt]=k.useState(()=>{if(_o())return!1;const a=Of(S,e);return a?a==="canvas":_n(cn(h.fm))?.mode==="canvas"}),[at,Vt]=k.useState(0),Pt=k.useRef(!1),St=k.useRef(He);St.current=He;const ln=k.useRef(!1),ct=cn(h.fm),qn=k.useMemo(()=>_n(ct),[ct]),gt=qn?.main??{x:0,y:0,w:_r},ot=()=>{const a=!He;if((j.current?.hasFocus()??!1)&&(a?Vt(g=>g+1):Pt.current=!0),a){const g=se.current?.closest(".amx-pane");g&&ri(S,e,g.scrollTop)}St.current=a,ln.current=!0,em(S,e,a?"canvas":"doc"),Rt(a),cn(h.fm)!=null&&(Ot(),Qt())},Ft=k.useRef(ot);Ft.current=ot,lt.current=B==="source"?null:()=>Ft.current(),k.useEffect(()=>(si(ne),()=>_f(ne)),[ne]);const on=k.useRef(a=>j.current?.applySlashItem(a)).current;k.useEffect(()=>(ia(on),()=>{Id()===on&&ia(null)}),[on]),k.useEffect(()=>(s?.({on:He,toggle:()=>Ft.current(),...He&&B!=="source"&&!y?{exportCanvas:()=>Cn.current?.()}:{}}),()=>s?.(null)),[He,s,B,y]);const Ut=k.useRef(null),Cn=k.useRef(null);k.useEffect(()=>{if(!c)return;const a=x=>{if(h.readOnly)return!1;if(St.current&&Ut.current)return Ut.current(x);const v=gn();return!!v&&(x==="undo"?Pa:pl)(v.state,v.dispatch)},g={undo:()=>a("undo"),redo:()=>a("redo"),indent:x=>{const v=gn();return!h.readOnly&&!!v&&Be.indent(v,x)}};return c.current=g,()=>{c.current===g&&(c.current=null)}},[c]);const er=a=>{const d=cn(h.fm);if(d!=null&&_n(d)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.canvasElementsFailed"),error:!0}}));return}h.fm=ls(h.fm,yr(h.fm),jy(d,a)),Ce(g=>g+1),Gn(),Qt()},co=a=>{const d=cn(h.fm);if(d!=null&&_n(d)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.canvasTreeFailed"),error:!0}}));return}h.fm=ls(h.fm,yr(h.fm),Ly(d,a)),Ce(g=>g+1),Gn(),Qt()},Zt=a=>{const d=cn(h.fm);if(d!=null&&_n(d)==null){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.canvasMainFailed"),error:!0}}));return}h.fm=ls(h.fm,yr(h.fm),Ry(d,a)),Ce(g=>g+1),Gn(),Qt()},Wn=k.useMemo(()=>({log:[],future:[]}),[e]),Sn=He&&B!=="source";k.useEffect(()=>{Qe(se.current)},[]),k.useEffect(()=>{const a=J.current?.closest(".amx-pane");if(a)return a.classList.toggle("amx-canvas-pane",Sn),()=>a.classList.remove("amx-canvas-pane")},[Sn]),k.useEffect(()=>{if(He)return;const a=se.current?.closest(".amx-pane");if(!a)return;const d=Bf(S,e);let g=!1,x=0;const v=performance.now()+1500,C=()=>{if(a.scrollTop=d,a.scrollTop!==d&&performance.now()<v){x=requestAnimationFrame(C);return}g=!0};x=requestAnimationFrame(C);const P=()=>{cancelAnimationFrame(x),g=!0},W=()=>{g&&ri(S,e,a.scrollTop)};return a.addEventListener("scroll",W,{passive:!0}),a.addEventListener("wheel",P,{passive:!0}),a.addEventListener("pointerdown",P),a.addEventListener("keydown",P),()=>{cancelAnimationFrame(x),a.removeEventListener("scroll",W),a.removeEventListener("wheel",P),a.removeEventListener("pointerdown",P),a.removeEventListener("keydown",P)}},[He,e,S]),k.useEffect(()=>{if(He||!Pt.current)return;Pt.current=!1;let a=0;const d=requestAnimationFrame(()=>{a=requestAnimationFrame(()=>j.current?.revealSelection())});return()=>{cancelAnimationFrame(d),cancelAnimationFrame(a)}},[He]);const[tr,Cr]=k.useState(()=>{const a=Ps;return a?.path===e&&a.scope===A?(Ps=null,Date.now()-a.at<1e4?a.req:null):null}),Vr=k.useRef(tr);Vr.current=tr;const qr=k.useRef(null),[Rn,En]=k.useState(null),Sr=k.useRef(null),[io,Wr]=k.useState(null),nt=k.useRef(()=>{}),wt=k.useRef({tree:()=>({}),detach:()=>{},minted:()=>{}}),Be=k.useMemo(()=>wy({onMenu:a=>{const d=Be.getView();Sr.current=d?{doc:d.state.doc,sel:d.state.selection}:null,En({...a,cell:Qx(d,a.x,a.y)})},onBlocksDeleted:a=>nt.current(a),canvasTree:()=>wt.current.tree(),onCardDetach:a=>wt.current.detach(a),onCardsMinted:a=>wt.current.minted(a)}),[]),gn=()=>je.current?null:Be.getView(),[$o]=k.useState(()=>kh(gn)),lr=a=>{const d=Be.getView();d&&ky(e,Di(a),Di(d.state.doc.content))};nt.current=lr,wt.current={tree:()=>Bt(_n(cn(h.fm))?.tree),detach:a=>{const d=Bt(_n(cn(h.fm))?.tree);let g=!1;for(const x of a)x in d&&(delete d[x],g=!0);g&&co(d)},minted:a=>{for(const d of a)h.ownedCards.add(d)}};const Yn=k.useRef({vaultRoot:S,path:e});Yn.current={vaultRoot:S,path:e};const Ln=k.useRef(!1),Mn=k.useRef(()=>{}),[b,M]=k.useState({count:0,index:0}),R=k.useRef(()=>{}),T=S?`${S.replace(/[\\/]+$/,"")}/${e}`:e,F=k.useSyncExternalStore(Kf,()=>!y&&Hf(T));R.current=a=>{const d=a.current==null?0:a.changes.findIndex(g=>g.id===a.current)+1;M(g=>g.count===a.changes.length&&g.index===d?g:{count:a.changes.length,index:d})};const V=k.useMemo(()=>[...Be.plugins,...Rg,...Eg(()=>wa(yr(h.fm)),()=>{h.sawRows=!0}),...Fy,...$y(()=>_n(cn(h.fm)),()=>wa(yr(h.fm)),a=>{for(const d of a)h.ownedCards.add(d)}),...qg({path:e,readOnly:y}),wh(),...Rx(),...Oy(()=>St.current),...qy(Wn),..._y(),...Hy(()=>_n(cn(h.fm))),...Cx(R),..._x({spaceTrigger:()=>Xp()&&Ln.current,onSpace:Mn}),...km,...Cm,...Ym(()=>Yn.current),...Ch(),...Sh(()=>ze.current()),...Eh({where:()=>Yn.current,restore:()=>re.current(),focus:()=>fe.current()}),...E?kd:[]],[Be,e,y,E]);k.useEffect(()=>{if(!Rn)return;const a=x=>{x.target?.closest?.(".ctx-menu")||En(null)},d=x=>{const v=document.querySelector(".unified-block-menu"),C=!!v&&v.contains(document.activeElement);if(x.key==="Escape"){x.stopPropagation(),En(null),Be.getView()?.focus();return}if(!v||x.isComposing)return;if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!x.shiftKey&&["ArrowDown","ArrowUp","Home","End"].includes(x.key)){x.preventDefault(),x.stopPropagation();const W=[...v.querySelectorAll('button:not([aria-disabled="true"])')],H=W.indexOf(document.activeElement),K=W.length,ae=x.key==="Home"?0:x.key==="End"?K-1:H<0?x.key==="ArrowUp"?K-1:0:(H+(x.key==="ArrowDown"?1:-1)+K)%K;W[ae]?.focus();return}C&&(x.key==="Enter"||x.key===" ")||["Shift","Meta","Control","Alt","CapsLock"].includes(x.key)||(En(null),C&&(x.preventDefault(),Be.getView()?.focus()))};let g=0;if(Rn.keyboard){let x=0;const v=()=>{const C=document.querySelector(".unified-block-menu");if(!C){++x<10&&(g=requestAnimationFrame(v));return}let P=Rn.focus==="turnInto"?C.querySelector('[data-sec="turnInto"]')?.nextElementSibling??null:null;for(;P&&P.tagName!=="BUTTON";)P=P.nextElementSibling;(P??C.querySelector("button"))?.focus()};g=requestAnimationFrame(v)}return window.addEventListener("pointerdown",a,!0),window.addEventListener("contextmenu",a,!0),window.addEventListener("keydown",d,!0),()=>{cancelAnimationFrame(g),window.removeEventListener("pointerdown",a,!0),window.removeEventListener("contextmenu",a,!0),window.removeEventListener("keydown",d,!0)}},[Rn]);const G=a=>{const d=Sr.current;return Sr.current=null,d?a.state.doc!==d.doc?(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.menu.stale")}})),!1):(a.state.selection.eq(d.sel)||a.dispatch(a.state.tr.setSelection(d.sel)),!0):!0},q=a=>{En(null);const d=Be.getView();if(!d||!G(d))return;const g=d.state.selection;g instanceof ye&&(a(d,g),d.focus())},U=(a,d)=>{En(null);const g=Be.getView();if(!g||!G(g))return;const x=Be.topRangeOf(g);x?a(g,x):g.state.selection instanceof ye&&d(g,g.state.selection),g.focus()},O=a=>{const d=a.state.selection,g=Be.topRangeOf(a)??(d instanceof ye?{from:d.from,to:d.to}:null);return g&&{from:g.from,to:us(a.state,g.from,g.to)}},ge=!y&&!!Ns()?.askInChat,De=(a,d,g)=>{const x=Xx(a.state.doc,d,g,e);x&&Ns()?.askInChat?.(x)},Ie=!y&&!!Ns()?.complete;Ln.current=Ie;const Oe=Fa(a=>a.selectionActions),[Pe,We]=k.useState(null),Ge=[...["improve","fix","shorter","longer","summarize","translate","continue","custom"].map(a=>({id:a,label:Y(`inlineai.action.${a}`)})),...Oe.map(a=>({id:`plugin:${a.pluginId}:${a.item.id}`,label:a.item.title,plugin:!0}))],qt=(a,d)=>{if(!Ie)return;const g=a.state.selection,x=d==="prompt",v=x?g.head:g.from,C=x?g.head:g.to;if(!x&&C<=v)return;Bx(a,v,C);const P=a.coordsAtPos(v),W=a.coordsAtPos(C),H=d.startsWith("plugin:")?d.slice(7):void 0,K=H||x?x?"prompt":"custom":d,ae=H?Oe.find(he=>`${he.pluginId}:${he.item.id}`===H)?.item.title??Y("inlineai.label"):Y(x?"inlineai.label":`inlineai.action.${d}`);We({key:Date.now(),x:P.left,y:W.bottom+6,top:P.top-6,title:ae,hasSelection:!x,askFirst:x||d==="custom",action:K,plugin:H})};Mn.current=a=>qt(a,"prompt");const Wt=a=>async(d,g,x)=>{const v=Be.getView(),C=v?rl(v):null;if(!v||!C)throw new Error(we("unipage.toast.insertPointLost"));const P=C.to>C.from?j.current?.serializeMd(v.state.doc.slice(C.from,C.to).content)??C.text:"";if(a.plugin){const he=Fa.getState().selectionActions.find(Ke=>`${Ke.pluginId}:${Ke.item.id}`===a.plugin);if(!he)throw new Error(we("unipage.toast.insertPointLost"));const Re=await he.item.run({text:C.text,markdown:P,pagePath:e});if(Re==null||Re==="")return{text:""};if(typeof Re!="string")throw new Error(we("unipage.plugin.notString",{type:typeof Re}));if(Array.from(Re).some(Ke=>Ke.charCodeAt(0)<32&&Ke!==" "&&Ke!==`
|
|
57
|
-
`))throw new Error(we("unipage.plugin.controlChars"));return{text:Re}}const W=Ns();if(!W?.complete)throw new Error(we("inlineai.unavailable"));const{before:H,after:K}=Kx(v.state.doc,C.from,C.to),ae=a.action==="prompt"?d?"custom":"continue":a.action;return W.complete({action:ae,...d?{instruction:d}:{},...P?{selection:P}:{},...H?{before:H}:{},...K?{after:K}:{},title:e.split("/").pop().replace(/\.md$/i,""),...ae==="translate"?{language:Hx(C.text)}:{}},{signal:x,onDelta:g})},kt=()=>{We(null);const a=Be.getView();a&&(nl(a),a.focus())},Ue=(a,d)=>{const g=Be.getView(),x=g?rl(g):null,v=j.current?.parseMd(d);if(We(null),!g||!x||!v){g&&nl(g),window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.insertPointLost")}}));return}const C=qx(g,x,v,a);g.focus(),Ot(),Qt(),a==="replace"&&C==="below"&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("inlineai.targetChanged")}}))},Xn=()=>{const a=Be.getView();if(!a)return;const d=Nx(a),g=d?J.current?.querySelector(`[data-agent-change="${d.id}"]`):null;g instanceof HTMLElement&&ss(g,48)},Lt=()=>{const a=Be.getView();if(!a)return;const{skipped:d}=Mx(a);Ot(),Qt(),d&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("agentchg.skipped",{n:String(d)})}}))},$t=(a,d)=>{let g=!0;U((x,v)=>{g=Pl(x,v.from,v.to,a)},(x,v)=>{const C=bi(x,v.from,v.to,a);if(C!=null){g=C;return}v.node.type.spec.code&&Pd(x,v.from,a)||(x.dispatch(x.state.tr.setSelection(Ae.near(x.state.doc.resolve(v.from+1)))),g=Js(x,a,null))}),g||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("mdblock.turn.failed",{kind:d})}}))},nr=(a,d)=>{let g=!0;U((x,v)=>{g=a==="code"?Ua(x,v.from,v.to):xi(x,v.from,v.to,!0)},(x,v)=>{g=a==="code"?bi(x,v.from,v.to,"code")??Ua(x,v.from,v.to):xi(x,v.from,v.to,!1)}),g||window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("mdblock.turn.failed",{kind:d})}}))},Er=a=>{const d=()=>(window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.cardUnavailable")}})),!1);if(!(a.state.selection instanceof ye)){const{$from:he}=a.state.selection;for(let Ke=he.depth;Ke>=1;Ke--)if(he.node(Ke).type.name==="list_item")return d();let Re=he.depth;for(;Re>=1&&!["doc","amadeusColumnCell","amadeusCanvasCard"].includes(he.node(Re-1).type.name);)Re--;if(Re<1)return!1;a.dispatch(a.state.tr.setSelection(ye.create(a.state.doc,he.before(Re))))}const g=a.state.selection,x=a.state.doc.resolve(g.from),v=x.depth>=1?x.node(x.depth):null,C=v?.type.name==="amadeusCanvasCard"?String(v.attrs.anchor):"",P=Bt(_n(cn(h.fm))?.tree);let W=0;a.state.doc.forEach(he=>{he.type.name==="amadeusCanvasCard"&&W++});const H=C?(Number(v.attrs.x)||0)+(Number(v.attrs.w)||Jt)+80:gt.x+gt.w+80,K=C?(Number(v.attrs.y)||0)+wo(P,C).length*72:gt.y+W*72,ae=su(a,Math.round(H),Math.round(K),C?{parent:C,tree:P}:void 0);return ae?(h.ownedCards.add(ae),Ot(),Qt(),C&&co(Oo(Bt(_n(cn(h.fm))?.tree),ae,C)),!St.current&&!C&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.cardMade")}})),!0):d()},ur=()=>{const a=vo(h.lastSaved);if(a.fmText!==h.fm&&(h.peerPatch==null||xa(a.fmText,h.peerPatch)!==h.fm))return!1;if(a.body===h.body)return!0;if(yr(h.fm)!=null||cn(h.fm)!=null)return!1;const d=j.current?.canonical(a.body);return d!=null&&d===h.body},zn=k.useRef(null),Yr=()=>{zn.current?.()},[Mr,Xr]=k.useState(!1),zr=async a=>{const d=So(a);if(h.preserved.has(d))return;const g=await ga(e,Pr(a,h.eol));h.preserved.add(d),ah(e,g,!h.readOnly&&oi(T,a)),N.getState().refreshPages()},lo=async a=>{const d=await ga(e,Pr(a,h.eol));ch(e,d),N.getState().refreshPages()},dr=()=>{if(h.gone==null||h.readOnly)return;Ot();const a=An(h.fm,h.body);a!==h.gone&&(h.gone=a,Un(a))},Un=async a=>{try{await lo(a)}catch{Dr(S,e,a,h.lastSaved,h.slot),lh(e,a)}},rr=a=>{if(h.retired||(h.stashed=An(h.fm,h.body),Dr(S,e,h.stashed,h.lastSaved,h.slot)),h.failed||(h.failed=!0,Xr(!0),ya(e,a)),h.retryTimer||h.dead||h.retired)return;const d=hi[Math.min(h.retryN,hi.length-1)];h.retryN++,h.retryTimer=setTimeout(()=>{h.retryTimer=null,!(h.dead||h.retired||!h.pending)&&(h.reconcileBusy||sn())},d)},fr=a=>{h.retryTimer&&(clearTimeout(h.retryTimer),h.retryTimer=null),h.retryN=0,h.failed&&(h.failed=!1,Xr(!1)),h.stashed!=null&&(a==null||h.stashed===a||An(h.fm,h.body)===a)&&(Go(S,e,h.stashed,h.slot),h.stashed=null)},uo=a=>{h.peerPatch=null,fr(a),Gu(e,h)},sn=(a=!1)=>{if(h.readOnly)return Promise.resolve();const d=async()=>{let v=0;for(;!h.retired;){const C=An(h.fm,h.body);if(C===h.lastSaved){h.pending=!1,fr();return}let P;try{h.unpreserved!=null&&h.unpreserved!==C&&await zr(h.unpreserved),h.unpreserved=null,P=await bn.writeTextFile(e,Pr(C,h.eol),{base:So(Pr(h.lastSaved,h.eol))})}catch(W){if(h.pending=!0,rr(W),a)throw W;return}if(P&&P.ok===!1&&P.current==null){h.retired||(h.retired=!0,h.pending=!1,Ot(),h.gone=An(h.fm,h.body),await Un(h.gone));return}if(P&&P.ok===!1&&P.current!=null){const W=Bo(P.current);h.eol=W.eol;const H=W.text;if(H===C){h.lastSaved=C;continue}if(++v>3){const K=new Error("The note kept changing on disk while saving");if(h.pending=!0,rr(K),a)throw K;return}if(ur()){h.pending=!1,Yr();return}h.unpreserved=H,h.lastSaved=H;continue}if(h.lastSaved=C,N.getState().bumpLinkGraph(),An(h.fm,h.body)===C&&(h.pending=!1),uo(C),!a)return}},g=async()=>{h.writing++;try{await d()}finally{h.writing--}},x=h.chain.then(g,g);return h.chain=x.catch(()=>{}),x},wn=()=>{const a=gn();if(!a)return;const d=yr(h.fm),g=zg(a.state.doc);let x=d;g!=null?(x=g,h.sawRows=!0):h.sawRows&&d!=null&&wa(d)!=null&&(x=null);const v=Ty(a.state.doc,cn(h.fm),ln.current?St.current?"canvas":"doc":null,h.ownedCards),C=cn(h.fm);h.fm=ls(h.fm,x,v),cn(h.fm)!==C&&Ce(P=>P+1)},Ot=()=>{const a=j.current?.serializeNow();a!=null&&(h.body=a,wn())},Qt=()=>{h.dead||h.retired||y||!h.writing&&An(h.fm,h.body)===h.lastSaved||(h.pending=!0,h.timer&&clearTimeout(h.timer),h.timer=setTimeout(()=>{h.timer=null,!h.reconcileBusy&&sn()},ob))},[xr,Nr]=k.useState(null),Gn=()=>{Nr(a=>a==null?a:An(h.fm,h.body))},Jn=(a,d=!0)=>{y||(h.fm=xa(h.fm,a),Ce(g=>g+1),Gn(),d?(h.pending=!0,sn().then(()=>{const g=Bn.getState();g.refreshPages(),g.refreshIcons()})):Qt())};k.useEffect(()=>{Vf(document)},[]);const[Hn,Zn]=k.useState(null);k.useEffect(()=>{const a=d=>{const g=document.elementFromPoint(d.clientX,d.clientY)??d.target,x=g?.tagName==="IMG"?g:null;if(!x||!x.closest(".unified-body"))return;const v=x.currentSrc||x.src;v&&(d.preventDefault(),d.stopPropagation(),Zn(v))};return document.addEventListener("dblclick",a,!0),()=>document.removeEventListener("dblclick",a,!0)},[]),ei(!!Hn,()=>Zn(null)),ei(!!Rn&&!y,()=>En(null)),k.useEffect(()=>{if(!Hn)return;const a=d=>{d.key==="Escape"&&Zn(null)};return window.addEventListener("keydown",a,!0),()=>window.removeEventListener("keydown",a,!0)},[Hn]),k.useEffect(()=>{const a=async()=>{h.reconcileBusy++;try{await tm(),await h.chain;const g=await bn.readTextFile(e);if(g==null||h.dead||h.retired)return;const x=Bo(g);h.eol=x.eol;const v=x.text;if(v===h.lastSaved&&!h.pending)return;if(h.pending&&Ot(),h.pending&&!ur()){v!==h.lastSaved&&v!==An(h.fm,h.body)&&(h.unpreserved=v),h.lastSaved=v;return}const{fmText:C,body:P}=vo(v),W=yr(C)!==yr(h.fm)||cn(C)!==cn(h.fm);if(h.fm=C,h.peerPatch=null,Ce(H=>H+1),P!==h.body){h.ownedCards.clear();const H=!h.readOnly&&oi(T,g);(j.current??(je.current?oe.current:null))?.applyBody(P,H)?h.body=P:(h.body=P,Z(K=>K+1))}else W&&(h.ownedCards.clear(),Z(H=>H+1));h.lastSaved=v,h.pending=!1,fr(),Gn()}finally{h.reconcileBusy--,h.reconcileBusy===0&&h.pending&&sn()}};zn.current=()=>{a()};const d=bn.onExternalChange?.(g=>{g===e&&a()});return a(),()=>{zn.current=null,d?.()}},[e]),k.useEffect(()=>{const a=()=>{if(Ot(),Ee(),h.timer&&clearTimeout(h.timer),h.timer=null,h.readOnly)return;if(h.retired){h.gone!=null&&dr(),h.stashed!=null&&Go(S,e,h.stashed,h.slot),h.stashed=null;return}const g=An(h.fm,h.body);if(!h.writing&&g===h.lastSaved){fr();return}if(!h.writing&&ur()){h.pending=!1;return}h.stashed=g,Dr(S,e,g,h.lastSaved,h.slot),sn()},d=g=>{a(),h.failed&&h.pending&&!dh()&&(g.preventDefault(),g.returnValue="")};return window.addEventListener("beforeunload",d),()=>{h.dead=!0,window.removeEventListener("beforeunload",d),a();const g=qr.current,x=Be.getView();g&&x&&(g.doc=x.state.doc.toJSON(),g.anchor=x.state.selection.anchor,g.head=x.state.selection.head)}},[e]),k.useEffect(()=>{const a=()=>{!h.failed||!h.pending||h.dead||h.retired||typeof document<"u"&&document.visibilityState==="hidden"||(h.retryTimer&&(clearTimeout(h.retryTimer),h.retryTimer=null),!h.reconcileBusy&&sn())};return window.addEventListener("online",a),window.addEventListener("focus",a),document.addEventListener("visibilitychange",a),()=>{window.removeEventListener("online",a),window.removeEventListener("focus",a),document.removeEventListener("visibilitychange",a),h.retryTimer&&(clearTimeout(h.retryTimer),h.retryTimer=null)}},[e]),k.useEffect(()=>{const a=W=>{if(h.readOnly||h.retired||h.dead)return!1;Ot(),W&&Ee();const H=An(h.fm,h.body);return!h.writing&&(H===h.lastSaved||ur())?!1:(h.pending=!0,h.stashed=H,Dr(S,e,H,h.lastSaved,h.slot),!0)},d=W=>{a(W)&&(h.timer&&(clearTimeout(h.timer),h.timer=null),!h.reconcileBusy&&sn())},g=()=>{document.visibilityState==="hidden"&&d(!0)},x=()=>d(!0);let v=0,C=null;const P=()=>{const W=v+1e3-Date.now();if(W>0){a(!1),C||(C=setTimeout(()=>{C=null,v=Date.now(),d(!1)},W));return}v=Date.now(),d(!1)};return document.addEventListener("visibilitychange",g),window.addEventListener("pagehide",x),document.addEventListener("freeze",x),document.addEventListener("pause",x),window.addEventListener("blur",P),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("pagehide",x),document.removeEventListener("freeze",x),document.removeEventListener("pause",x),window.removeEventListener("blur",P),C&&clearTimeout(C)}},[e]);const fo=a=>h.readOnly||h.retired||h.dead||!j.current?!1:(j.current.insertFiles(a),!0);k.useEffect(()=>{if(!l)return;const a=d=>fo(d);return l.current=a,()=>{l.current===a&&(l.current=null)}},[l]),k.useEffect(()=>{if(!i)return;const a=d=>h.readOnly||h.retired||h.dead?!1:j.current?.insertMarkdown(d,"cursor")??!1;return i.current=a,()=>{i.current===a&&(i.current=null)}},[i]),k.useLayoutEffect(()=>Wu({path:e,owner:h,peerWrote:()=>Yr(),scope:A,lastActive:()=>Se.current,dirty:()=>h.readOnly||h.retired||h.dead?!1:(Ot(),An(h.fm,h.body)!==h.lastSaved&&!ur()),flush:(a=!1)=>h.readOnly?Promise.resolve():(Ot(),Ee(),h.timer&&(clearTimeout(h.timer),h.timer=null),sn(a)),insertFiles:a=>fo(a),patchFm:(a,d=!1)=>h.readOnly||h.retired||h.dead?null:d?(h.fm=xa(h.fm,a),h.peerPatch={...h.peerPatch??{},...a},Ce(g=>g+1),Gn(),Promise.resolve()):(Jn(a),h.chain),fmNow:()=>bs(h.fm),insertMarkdown:(a,d)=>h.retired||h.readOnly?!1:j.current?.insertMarkdown(a,d)??!1,insertReply:y?void 0:(a,d)=>{if(h.retired||h.dead||h.readOnly||!j.current?.insertMarkdown(a,"cursor",{quiet:!0,after:d,caretless:!ce.current}))return null;const g=gn()?.state.doc,x=Wn,v={n:x.log.length,top:x.log[x.log.length-1],future:x.future.length};return{undo:()=>{const C=gn();return!C||!g||C.state.doc!==g||h.retired||h.dead||v.top!=="pm"||x.log.length!==v.n||x.log[x.log.length-1]!=="pm"||x.future.length!==v.future?!1:St.current&&Ut.current?Ut.current("undo"):Pa(C.state,C.dispatch)}}},bodyNow:()=>h.body,statsNow:()=>$o(),headings:()=>{const a=gn();return a?Ws(a.state.doc):[]},revealHeading:(a,d,g)=>{const x=gn();if(!x)return;const v=Ws(x.state.doc),C=v[a]?.text===d?v[a]:v.find(W=>W.text===d);if(!C)return;x.focus(),x.dispatch(x.state.tr.setSelection(Ae.near(x.state.tr.doc.resolve(C.pos+1))));const P=x.nodeDOM(C.pos);P instanceof HTMLElement&&(ss(P),g&&_s(P.getBoundingClientRect()))},revealBlock:(a,d)=>{const g=gn();if(!g)return!1;const x=[];g.state.doc.descendants((W,H,K)=>W.isTextblock?(x.push({pos:H,text:W.textContent,parent:K}),!1):!0);let v=x.findIndex(W=>ll(W.text)===a);if(v<0)return!1;Qu(x[v].text)&&v>0&&x[v-1].parent===x[v].parent&&(v-=1);const C=x[v].pos;g.focus(),g.dispatch(g.state.tr.setSelection(Ae.near(g.state.tr.doc.resolve(C+1))));const P=g.nodeDOM(C);return P instanceof HTMLElement&&(ss(P),d&&_s(P.getBoundingClientRect())),!0},focusBody:()=>{if(h.readOnly||h.retired||h.dead)return!0;const a=Be.getView();return a?(a.hasFocus()||a.focus(),!0):!1},revealText:(a,d)=>{const g=gn();if(!g)return!1;const x=Fd(g.state.doc,a,!!d?.tag);if(!x)return!1;gl(g,x.from),g.focus(),g.dispatch(g.state.tr.setSelection(Ae.create(g.state.doc,x.from,x.to)));let v=g.nodeDOM(x.block);for(;v instanceof HTMLElement&&v!==g.dom;){const C=v.getBoundingClientRect();if(C.width||C.height)break;v=v.parentElement}return!(v instanceof HTMLElement)||v===g.dom||(ss(v),d?.flash&&_s(v.getBoundingClientRect())),!0},retire:a=>{if(Co(),!h.retired&&!h.readOnly&&!h.dead){Ot();const d=An(h.fm,h.body);d!==h.lastSaved&&!ur()&&(a?Dr(S,a,d,h.lastSaved,h.slot):(N.getState().vaultRoot??null)!==(S??null)?Dr(S,e,d,h.lastSaved,h.slot):Un(d))}else h.retired&&h.gone!=null&&dr();h.retired=!0,h.timer&&(clearTimeout(h.timer),h.timer=null),h.retryTimer&&(clearTimeout(h.retryTimer),h.retryTimer=null)}}),[e]);const[Vn,mr]=k.useState(()=>{if(y)return null;const a=g=>g==null?Fc(e,null):nm(g)||Fc(e,g),d=uh(S,e,h.slot,a);return d?d.text===h.lastSaved||d.text===(n??t)?(Go(S,e,void 0,d.slot),null):d:null}),$r=()=>{Vn&&Go(S,e,void 0,Vn.slot),mr(null)},Ur=()=>{const a=Vn;if(mr(null),!a||y||h.retired)return;(a.slot??null)!==h.slot&&(Go(S,e,a.text,a.slot),Dr(S,e,a.text,h.lastSaved,h.slot)),Ot();const d=h.lastSaved,g=An(h.fm,h.body),x=g!==d?g:So(d)!==a.base?d:null;x!=null&&x!==a.text&&(h.unpreserved=x);const{fmText:v,body:C}=vo(a.text);h.fm=v,Ce(P=>P+1),C!==h.body&&(h.ownedCards.clear(),h.body=C,(j.current??(je.current?oe.current:null))?.applyBody(C)||Z(P=>P+1)),Gn(),h.pending=!0,h.stashed=a.text,sn()};k.useEffect(()=>{r&&(r.scheduleState=()=>({pending:h.pending,lastSaved:h.lastSaved}),r.flush=()=>(Ot(),h.timer&&clearTimeout(h.timer),h.timer=null,sn()),r.fmState=()=>({fm:h.fm,body:h.body}),r.setFm=a=>Jn(a,!1),r.view=()=>Be.getView(),r.serializeNow=()=>j.current?.serializeNow()??null)},[r]);const[z,L]=k.useState(0);k.useEffect(()=>{qf(e)&&L(a=>a+1)},[e]);const re=k.useRef(()=>!1);re.current=()=>!y&&!p&&!St.current&&Vr.current==null&&z===0;const fe=k.useRef(()=>!1);fe.current=()=>{const a=La;if(!a||a.scope!==A||Date.now()-a.at>5e3)return!1;La=null;const d=document.activeElement;return(!d||d===document.body)&&(A==null||A===um())};const ke=k.useRef(null);k.useLayoutEffect(()=>()=>{const a=document.activeElement;a&&a!==document.body&&(J.current?.contains(a)||ke.current?.contains(a))&&(La={scope:A,at:Date.now()})},[]);const ze=k.useRef(()=>!1);ze.current=()=>Sn||y?!1:(L(a=>a+1),!0);const le=a=>{const d=Be.getView();if(!d)return;let g=d.state.tr;if(h.body===a.body)try{const C=d.state.schema.nodeFromJSON(a.doc);C.eq(g.doc)||(g=g.replaceWith(0,g.doc.content.size,C.content))}catch{}const x=g.doc.content.size,v=C=>g.doc.resolve(Math.max(0,Math.min(C,x)));try{g=g.setSelection(Ae.between(v(a.anchor),v(a.head)))}catch{}d.dispatch(g.setMeta("addToHistory",!1).scrollIntoView())},me=async(a,d=null,g=!1)=>{if(y||g&&h.retired)return!1;const x=S;try{if(Ot(),await sn(),await om(),g&&(await h.chain,h.retired||Bn.getState().vaultRoot!==x))return!1;const v=await bn.renamePageFile(e,a);if(v!==e){sm(S,e,v),Xm(S,e,v),h.retired=!0,Ot();const C=An(h.fm,h.body),P=h.body;if(C!==h.lastSaved)try{const K=await bn.writeTextFile(v,Pr(C,h.eol),{base:So(Pr(h.lastSaved,h.eol))});if(K&&K.ok===!1&&K.current!==Pr(C,h.eol))try{ih(v,await ga(v,Pr(C,h.eol))),Bn.getState().refreshPages()}catch(ae){Dr(S,v,C,h.lastSaved,h.slot),ya(v,ae)}}catch(K){Dr(S,v,C,h.lastSaved,h.slot),ya(v,K)}const W=Vr.current,H=Be.getView();if(!g&&d&&W!=null&&typeof W!="object")Ps={path:v,scope:A,req:W,at:Date.now()};else if(!g&&H?.hasFocus()){const K={place:"restore",body:P,doc:H.state.doc.toJSON(),anchor:H.state.selection.anchor,head:H.state.selection.head};qr.current=K,Ps={path:v,scope:A,req:K,at:Date.now()}}Yu(e,"file",v),am(e,v,"file"),await cm(e,v),Bn.getState().refreshPages(),g||o?.(v)}return!0}catch{return g&&window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.toast.renameDetachedFailed",{name:a})}})),!1}},ut=k.useRef("");k.useEffect(()=>{const a=JSON.stringify(_n(cn(h.fm))?.tree??null);if(a===ut.current)return;ut.current=a;const d=Be.getView();d&&d.updateState(d.state)},[ve,Be]);const Et=bh(h.fm),vt=typeof Et.icon=="string"&&Et.icon.trim()?Et.icon.trim():null,Yt=typeof Et.cover=="string"&&Et.cover.trim()?Et.cover.trim():null,Mt=Et.cover_y,zt=typeof Mt=="number"?Mt:typeof Mt=="string"?parseFloat(Mt):NaN,Dn=Number.isFinite(zt)?Math.max(0,Math.min(100,zt)):50,At=k.useMemo(()=>B==="source"?An(h.fm,h.body):"",[B,ve]),un=k.useRef(null),Ar=()=>`${yr(h.fm)??""}\0${cn(h.fm)??""}`;k.useEffect(()=>{if(!y)return Wf(X,a=>{const d=la(se.current),g=ua(d);if(a==="source"){Ot();const P=Be.getView(),W=An(h.fm,h.body);let H=h.fm.length,K=0,ae=!1;if(P){const{head:he,$head:Re}=P.state.selection;ae=P.hasFocus();try{K=P.coordsAtPos(he).top-g}catch{}const Ke=Re.parent.isTextblock?Re.parent.textBetween(Math.max(0,Re.parentOffset-16),Re.parentOffset,void 0,""):"",Xe=oe.current?.serializePrefix(he);H=dm(W,h.fm.length+(Xe?.trimEnd().length??0),Ke)}un.current={to:a,offset:H,y:K,focused:ae,bodyAtEnter:h.body,struct:Ar()};return}const x=u.current;if(!x)return;const v=x.selectionStart??0;let C=0;try{C=ti(x,v)-g}catch{}un.current={...un.current??{},to:a,offset:v,bodyOff:v-vo(x.value).fmText.length,y:C,focused:document.activeElement===x}})},[X,y]);const Tr=k.useRef(B);k.useLayoutEffect(()=>{const a=Tr.current;if(Tr.current=B,a===B)return;const d=un.current,g=la(se.current);if(B==="source"){Qt();const K=u.current;if(!K||d?.to!=="source")return;const ae=g.scrollTop;K.style.height="auto",K.style.height=`${K.scrollHeight}px`,g.scrollTop=ae;const he=Math.min(d.offset,K.value.length);K.setSelectionRange(he,he),d.focused&&K.focus({preventScroll:!0}),g.scrollTop+=ti(K,he)-ua(g)-d.y;return}un.current=null,Nr(null);const x=oe.current,v=Be.getView();if(!x||!v||!d||d.struct!==Ar()){h.ownedCards.clear(),Z(K=>K+1);return}if(h.body!==d.bodyAtEnter&&x.applyBody(h.body,!1,!0),d.to!=="wysiwyg"||d.bodyOff==null)return;const C=Be.getView();if(!C)return;const P=C.state.doc.content.size,W=d.bodyOff<=0?0:x.posAfterPrefix(h.body.slice(0,d.bodyOff))??0,H=Ae.near(C.state.doc.resolve(Math.max(0,Math.min(W,P))),-1);C.dispatch(C.state.tr.setSelection(H).setMeta("addToHistory",!1)),d.focused&&C.focus();try{g.scrollTop+=C.coordsAtPos(H.head).top-ua(g)-d.y}catch{}},[B]);const u=k.useRef(null);return k.useEffect(()=>{const a=u.current;if(B==="source"&&a){const d=la(a),g=d.scrollTop;a.style.height="auto",a.style.height=`${a.scrollHeight}px`,d.scrollTop=g}},[B,xr,At]),k.useEffect(()=>{if(y)return;if(B==="source"){const d=u.current;return d?di(Up(d)):void 0}const a=J.current;return a?di(rb(a,()=>Be.getView())):void 0},[y,B,Be]),m.jsxs(m.Fragment,{children:[m.jsx("span",{ref:se,className:"amx-seg-anchor","aria-hidden":!0}),B==="source"?null:m.jsx(Nh,{anchor:xe,on:He,toggle:()=>Ft.current()}),Sn||p?null:m.jsx(fm,{page:e,cover:Yt,coverY:Dn,readOnly:y,onSetCover:a=>Jn({cover:a??void 0,...a?{}:{cover_y:void 0}}),onSetCoverY:a=>Jn({cover_y:a})}),Sn?null:m.jsxs("div",{ref:ke,className:"amx-doc unified-page","data-unified-path":e,onFocusCapture:de,onPointerDownCapture:de,children:[m.jsx(lb,{compact:p,path:e,icon:vt,cover:Yt,readOnly:y,onSetIcon:a=>Jn({icon:a??void 0}),onSetCover:a=>Jn({cover:a}),onRename:me,onDetachedRename:a=>{const d=a.trim();d&&d!==(e.split("/").pop()??e).replace(/\.md$/i,"")&&me(d,null,!0)},onEnterBody:a=>Cr(a==="enter"?"body-enter":"start"),focusSignal:z}),!p&&m.jsx(Dl.Provider,{value:be,children:m.jsx(jh,{fmExtra:bs(h.fm),readOnly:y,notePath:e,onCommit:a=>{h.fm=mh(h.fm,a),Ce(d=>d+1),Gn(),h.pending=!0,sn()}})}),y&&f&&m.jsxs("div",{className:"mk-notice unified-savebar","data-lock":"on",role:"status",children:[m.jsx(Um,{size:15}),m.jsx("div",{className:"mk-notice-body",children:m.jsx("span",{children:Y("unipage.lock.bar")})}),m.jsx("button",{type:"button",className:"btn sm",onClick:f,children:Y("unipage.lock.unlock")})]}),!y&&Mr&&m.jsxs("div",{className:"mk-notice is-error unified-savebar","data-save":"failed",role:"alert",children:[m.jsx(Yf,{size:15}),m.jsx("div",{className:"mk-notice-body",children:m.jsx("span",{children:Y("unisave.failed.bar")})}),m.jsx("button",{type:"button",className:"btn sm",onClick:()=>{h.retryTimer&&(clearTimeout(h.retryTimer),h.retryTimer=null),sn()},children:Y("unisave.failed.retry")})]}),!y&&Vn&&m.jsxs("div",{className:"mk-notice unified-savebar","data-save":"draft",role:"status",children:[m.jsx(Xf,{size:15}),m.jsxs("div",{className:"mk-notice-body",children:[m.jsx("span",{children:Y("unisave.draft.bar",{time:Uf(Vn.at)})}),m.jsx("small",{children:Y("unisave.draft.hint")})]}),m.jsx("button",{type:"button",className:"btn sm primary",onClick:Ur,children:Y("unisave.draft.restore")}),m.jsx("button",{type:"button",className:"btn sm",onClick:$r,children:Y("unisave.draft.discard")})]})]}),B==="source"?m.jsx("textarea",{ref:u,className:"amx-source",value:xr??At,spellCheck:Te,onFocus:de,onChange:a=>{const d=a.target.value;Nr(d);const{fmText:g,body:x}=vo(d);h.fm=yh(g),h.body=x,Qt()}}):null,m.jsxs("div",{ref:J,className:`page-view unified-body${He?" amx-canvas":""}${Sn?" amx-canvas-full":""}`,style:B==="source"?{display:"none"}:void 0,"aria-hidden":B==="source"||void 0,"data-bare":!0,onFocusCapture:()=>{de(),ce.current=!0,ia(on)},onPointerDownCapture:de,children:[m.jsx(hx,{path:e,vaultRoot:S,active:He&&B!=="source",readOnly:y,revealSelection:at,getView:()=>Be.getView(),main:gt,mainStored:qn?.main!=null,elements:qn?.elements,tree:qn?.tree,onElements:er,onTree:co,onMain:Zt,timeline:Wn,histStepRef:Ut,exportRef:Cn,saveFile:a=>hu(e,a),parseMd:a=>j.current?.parseMd(a)??null,serializeMd:a=>j.current?.serializeMd(a)??null,storedMd:a=>j.current?.serializeStored(a)??null,onBlocksDeleted:lr,notePages:()=>N.getState().pages,onCommit:a=>{a&&h.ownedCards.add(a),Ot(),Qt()},children:m.jsx(Cd,{children:m.jsx(cb,{path:e,pageDir:D,body:h.body,onChange:a=>{je.current||(h.body=a,wn(),Qt())},onFinalFlush:a=>{h.body=a,wn(),Qt(),Ce(d=>d+1)},skipFinalFlush:()=>h.reconcileBusy>0||je.current,hidden:()=>je.current,apiRef:oe,probe:r,extraPlugins:V,focusPlace:tr!=null&&typeof tr=="object"?"start":tr,onFocused:()=>{tr!=null&&typeof tr=="object"&&le(tr),Cr(null)},onCard:Er,readOnly:y,onAskTangu:ge?a=>De(a,a.state.selection.from,a.state.selection.to):void 0,aiMenu:Ie?{items:Ge,onPick:(a,d)=>qt(d,a)}:void 0,onAiPrompt:Ie?a=>qt(a,"prompt"):void 0})},`${e}:${st}${y?":ro":""}`)}),!He&&!y&&m.jsx("div",{className:"page-tail",onClick:()=>j.current?.focusTail()}),F&&m.jsx($x,{}),!y&&b.count>0&&m.jsx(Ax,{count:b.count,index:b.index,onReview:Xn,onRevert:Lt,onKeep:()=>{const a=Be.getView();a&&zx(a)}})]}),m.jsx(Zx,{getView:()=>Be.getView(),onOpenNote:a=>{N.getState().openWikiLink(Sd(a,e,N.getState().pages),e)}}),Hn&&m.jsx(no,{children:m.jsx("div",{className:"amx-lightbox",onClick:()=>Zn(null),role:"presentation",children:m.jsx("img",{src:Hn,alt:""})})}),Pe&&Ie&&m.jsx(no,{children:m.jsx(Tx,{x:Pe.x,y:Pe.y,anchorTop:Pe.top,title:Pe.title,hasSelection:Pe.hasSelection,askFirst:Pe.askFirst,run:Wt(Pe),onApply:Ue,onClose:kt,editorEl:J.current},Pe.key)}),io&&!y&&m.jsx(_l,{pages:N.getState().pages,exclude:e,onClose:()=>{Wr(null),Be.getView()?.focus()},onPick:a=>{const d=io;Wr(null);const g=Be.getView();if(g){if(g.state.doc!==d.doc){window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.menu.stale")}}));return}eg({view:g,from:d.from,to:d.to,source:e,target:a,pages:[...N.getState().pages].sort(),serialize:x=>j.current?.serializeMd(x)??null}).then(x=>{x&&(Ot(),Qt())}),g.focus()}}}),Rn&&!y&&m.jsx(no,{children:m.jsxs(qo,{className:"ctx-menu unified-block-menu",role:"menu","aria-label":Y("unipage.menu.aria"),x:Rn.x,y:Rn.y,onClick:a=>a.stopPropagation(),children:[ge&&m.jsxs(m.Fragment,{children:[m.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"ask",onClick:()=>{En(null);const a=Be.getView();if(!a||!G(a))return;const d=Be.topRangeOf(a),g=a.state.selection;d?De(a,d.from,d.to):g instanceof ye&&De(a,g.from,g.to)},children:[m.jsx(Zm,{size:13})," ",Y("unipage.menu.askTangu")]}),m.jsx("div",{className:"ubm-sep",role:"separator"})]}),m.jsx("div",{className:"ubm-label",role:"presentation","data-sec":"turnInto",children:Y("unipage.menu.turnInto")}),!Qa(Be.getView())&&m.jsxs(m.Fragment,{children:[m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"text"},Y("unipage.menu.text")),children:[m.jsx(Ap,{size:13})," ",Y("unipage.menu.text")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"heading",level:1},Y("unipage.menu.h1")),children:[m.jsx(pp,{size:13})," ",Y("unipage.menu.h1")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"heading",level:2},Y("unipage.menu.h2")),children:[m.jsx(gp,{size:13})," ",Y("unipage.menu.h2")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"heading",level:3},Y("unipage.menu.h3")),children:[m.jsx(xp,{size:13})," ",Y("unipage.menu.h3")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"bullet"},Y("unipage.menu.bullet")),children:[m.jsx(Gf,{size:13})," ",Y("unipage.menu.bullet")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"ordered"},Y("unipage.menu.ordered")),children:[m.jsx(kp,{size:13})," ",Y("unipage.menu.ordered")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"task"},Y("unipage.menu.task")),children:[m.jsx(Jf,{size:13})," ",Y("unipage.menu.task")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"quote"},Y("unipage.menu.quote")),children:[m.jsx(Kp,{size:13})," ",Y("unipage.menu.quote")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>nr("callout",Y("unipage.menu.callout")),children:[m.jsx(mm,{size:13})," ",Y("unipage.menu.callout")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>$t({kind:"fold"},Y("unipage.menu.fold")),children:[m.jsx(fp,{size:13})," ",Y("unipage.menu.fold")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>nr("code",Y("unipage.menu.code")),children:[m.jsx(Gm,{size:13})," ",Y("unipage.menu.code")]})]}),(()=>{const a=Be.getView(),d=a?.state.selection;if(!a||!(d instanceof ye)||["amadeusCanvasCard","amadeusColumnRow","amadeusColumnCell","list_item"].includes(d.node.type.name))return null;const g=a.state.doc.resolve(d.from);for(let x=g.depth;x>=1;x--)if(g.node(x).type.name==="amadeusColumnCell")return null;return m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>q(x=>{Er(x)}),children:[m.jsx(El,{size:13})," ",Y("unipage.menu.card")]})})(),Qa(Be.getView())&&m.jsx(nb,{view:Be.getView(),cell:Rn.cell??null,onDone:()=>En(null)}),m.jsx("div",{className:"ubm-sep",role:"separator"}),Be.getView()&&Be.topRangeOf(Be.getView())?m.jsxs("button",{role:"menuitem",tabIndex:-1,"aria-disabled":"true",title:Y("unipage.menu.toNewColumnMulti"),"data-act":"toNewColumn",onClick:()=>{window.dispatchEvent(new CustomEvent("amadeus:toast",{detail:{text:we("unipage.menu.toNewColumnMulti")}}))},children:[m.jsx(ni,{size:13})," ",Y("unipage.menu.toNewColumn")]}):Be.getView()&&Ed(Be.getView().state.selection)&&m.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"toNewColumn",onClick:()=>q((a,d)=>{Vl(a,d.from,d.to,d.node)}),children:[m.jsx(ni,{size:13})," ",Y("unipage.menu.toNewColumn")]}),Be.getView()&&Bc(Be.getView().state.selection)!=null&&m.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"unsplit",onClick:()=>{En(null);const a=Be.getView();if(!a||!G(a))return;const d=Bc(a.state.selection);d!=null&&jg(a,d),a.focus()},children:[m.jsx(Fp,{size:13})," ",Y("unipage.menu.unsplit")]}),Be.getView()?.state.selection instanceof ye&&Be.getView().state.selection.node.type.name==="amadeusCanvasCard"&&m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>q((a,d)=>{d.node.type.name==="amadeusCanvasCard"&&(au(a,String(d.node.attrs.anchor)),Ot(),Qt())}),children:[m.jsx(Jm,{size:13})," ",Y("unipage.menu.backToDoc")]}),m.jsxs("button",{role:"menuitem",tabIndex:-1,onClick:()=>{En(null);const a=Be.getView();!a||!G(a)||(Be.duplicate(a)&&(Ot(),Qt()),a.focus())},children:[m.jsx(Zf,{size:13})," ",Y("unipage.menu.duplicate")]}),(()=>{const a=Be.getView();if(!a)return null;const d=a.state.selection,g=O(a),x=d instanceof ye?Jh(d.node,e,N.getState().pages):null,v=!!g&&Qh(a.state.doc.slice(g.from,g.to).content);return m.jsxs(m.Fragment,{children:[x&&m.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"copyLink",onClick:()=>{En(null),Zh(x.link),Be.getView()?.focus()},children:[m.jsx(Qf,{size:13})," ",Y(x.kind==="heading"?"blocklinks.copyHeading":"blocklinks.copyBlock")]}),v&&m.jsxs("button",{role:"menuitem",tabIndex:-1,"data-act":"moveTo",onClick:()=>{En(null);const C=Be.getView();if(!C||!G(C))return;const P=O(C);P&&Wr({doc:C.state.doc,...P})},children:[m.jsx(Am,{size:13})," ",Y("blocklinks.moveTo")]})]})})(),m.jsxs("button",{role:"menuitem",tabIndex:-1,className:"danger",onClick:()=>U((a,d)=>{const g=a.state.doc.slice(d.from,d.to).content;a.dispatch(a.state.tr.delete(d.from,d.to).scrollIntoView()),lr(g)},(a,d)=>{const g=wr.from(d.node),x=d.$from.parent,v=x.type.name==="amadeusColumnCell"&&x.childCount===1?ql(a.state,d.$from.before(),-1,!0):null;a.dispatch(v??a.state.tr.deleteSelection().scrollIntoView()),lr(g)}),children:[m.jsx(Ba,{size:13})," ",Y("unipage.menu.delete")]})]})})]})}const Fb=Object.freeze(Object.defineProperty({__proto__:null,UnifiedPage:ub},Symbol.toStringTag,{value:"Module"}));export{jh as A,fp as C,Lb as D,Pb as F,Sp as M,Mh as S,ub as U,Xp as a,qp as b,Ml as c,Rb as d,Nl as e,Vp as f,so as g,vo as h,Wp as i,Fb as j,Ib as o,Db as s};
|