texlite 0.11.0 → 0.13.0
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/DESIGN.md +64 -12
- package/dist/client/assets/AdminUsers-CfKlKMUu.js +1 -0
- package/dist/client/assets/{CitationLibraryDialog-tVD3i2gg.js → CitationLibraryDialog-BpnX28Le.js} +1 -1
- package/dist/client/assets/Dashboard-nbu54S0M.js +2 -0
- package/dist/client/assets/GitDialog-CrLMkNSh.js +3 -0
- package/dist/client/assets/GitHubAccountDialog-Bt0c8yBQ.js +1 -0
- package/dist/client/assets/HistoryDialog-CNEHivv5.js +7 -0
- package/dist/client/assets/LatexEditor-Dq9cqkpP.js +138 -0
- package/dist/client/assets/{PdfPreview-CMkO72I5.js → PdfPreview-xiB5Piyv.js} +1 -1
- package/dist/client/assets/ProjectIconPickerDialog-BSdiBwtv.js +1 -0
- package/dist/client/assets/{ProjectNavigationDialogs-isGMXCfG.js → ProjectNavigationDialogs-C7cD7PvT.js} +1 -1
- package/dist/client/assets/ProjectSettings-CRHG-jAZ.js +1 -0
- package/dist/client/assets/ProjectWorkspace-BdmKRaK2.js +32 -0
- package/dist/client/assets/{SelectionHistoryDialog-ZvAhIJMy.js → SelectionHistoryDialog-JL_2qLGf.js} +1 -1
- package/dist/client/assets/SystemMetricsDialog-BIWJwsxD.js +1 -0
- package/dist/client/assets/{TagManagementDialog-qhZfHgTr.js → TagManagementDialog-CJXWtqXN.js} +1 -1
- package/dist/client/assets/{WordCountDialog-tFhMCGyn.js → WordCountDialog-sr21g-ex.js} +1 -1
- package/dist/client/assets/check-CzfkSYah.js +1 -0
- package/dist/client/assets/{chktex-tM1XXPk2.js → chktex-BEVGf49u.js} +1 -1
- package/dist/client/assets/{editor-B9HNwtsd.js → editor-taw1iptB.js} +1 -1
- package/dist/client/assets/external-link-DuxFggPh.js +1 -0
- package/dist/client/assets/github-D805ABUR.js +1 -0
- package/dist/client/assets/{hard-drive-CkIPwUSV.js → hard-drive-De8wdQpw.js} +1 -1
- package/dist/client/assets/index-BYAZKPNO.js +10 -0
- package/dist/client/assets/{index-DTYEGzB7.js → index-CXWzCgcU.js} +1 -1
- package/dist/client/assets/index-Cc9-JFj7.css +1 -0
- package/dist/client/assets/{minimize-2-CLuDohEf.js → minimize-2-DP0ZJHGp.js} +1 -1
- package/dist/client/assets/{minus-BpuvzV2m.js → minus-BDK-NFbs.js} +1 -1
- package/dist/client/assets/{plus-BFr75l91.js → plus-GB_3iSP8.js} +1 -1
- package/dist/client/assets/{refresh-cw-DyA4NKh7.js → refresh-cw-DwUVAz9L.js} +1 -1
- package/dist/client/assets/{search-Nu4OcY_n.js → search-BJ0HR5pC.js} +1 -1
- package/dist/client/assets/{sigma-B-wjepsY.js → sigma-DOfd27T4.js} +1 -1
- package/dist/client/assets/{spellCheck-C-bNJsIU.js → spellCheck-CRN7y5Qf.js} +1 -1
- package/dist/client/assets/{tags-BSA08jK3.js → tags-BdjO5Lmr.js} +1 -1
- package/dist/client/assets/{type-BCdIbDmF.js → type-qV4gbXDh.js} +1 -1
- package/dist/client/assets/{user-plus-gFwY-NA3.js → user-plus-CPne6OnV.js} +1 -1
- package/dist/client/assets/x-DPtqmVM9.js +1 -0
- package/dist/client/index.html +3 -3
- package/dist/server/db.js +30 -1
- package/dist/server/git.js +64 -29
- package/dist/server/harper.js +14 -0
- package/dist/server/history.js +14 -5
- package/dist/server/i18n.js +2 -2
- package/dist/server/routes/projectGit.js +10 -11
- package/dist/server/routes/projectHistory.js +32 -5
- package/dist/server/routes/projectMembers.js +0 -5
- package/dist/server/routes/projects.js +10 -0
- package/dist/server/routes/users.js +0 -2
- package/dist/shared/historyFiles.js +6 -0
- package/package.json +3 -1
- package/dist/client/assets/AdminUsers-BExOMZsW.js +0 -1
- package/dist/client/assets/Dashboard-DRt4rjKP.js +0 -2
- package/dist/client/assets/GitDialog-CjDCi1uh.js +0 -3
- package/dist/client/assets/HistoryDialog-Pa9mK3Ky.js +0 -7
- package/dist/client/assets/LatexEditor-8r486VeG.js +0 -138
- package/dist/client/assets/ProjectIconPickerDialog-B52xbSyr.js +0 -1
- package/dist/client/assets/ProjectSettings-Br_kJ113.js +0 -1
- package/dist/client/assets/ProjectWorkspace-CcbrdCy8.js +0 -32
- package/dist/client/assets/SystemMetricsDialog-D4ouU4HI.js +0 -1
- package/dist/client/assets/check-DKIW1zpR.js +0 -1
- package/dist/client/assets/index-90X2GUd_.css +0 -1
- package/dist/client/assets/index-CqBmQAzW.js +0 -10
- package/dist/client/assets/key-round-BEnQo7IM.js +0 -1
- package/dist/client/assets/x-Cspw_pa4.js +0 -1
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./spellCheck-C-bNJsIU.js","./index-CqBmQAzW.js","./react-BVUjbTTn.js","./index-90X2GUd_.css","./check-DKIW1zpR.js","./x-Cspw_pa4.js","./search-Nu4OcY_n.js","./user-plus-gFwY-NA3.js","./refresh-cw-DyA4NKh7.js","./chktex-tM1XXPk2.js","./LatexEditor-8r486VeG.js","./editor-B9HNwtsd.js","./CitationLibraryDialog-tVD3i2gg.js","./citationLibrary-ZeQPCv5O.js","./plus-BFr75l91.js","./tags-BSA08jK3.js","./GitDialog-CjDCi1uh.js","./key-round-BEnQo7IM.js","./minus-BpuvzV2m.js","./minimize-2-CLuDohEf.js","./HistoryDialog-Pa9mK3Ky.js","./index-DTYEGzB7.js","./hard-drive-CkIPwUSV.js","./SelectionHistoryDialog-ZvAhIJMy.js","./ProjectNavigationDialogs-isGMXCfG.js","./ProjectSettings-Br_kJ113.js","./type-BCdIbDmF.js","./sigma-B-wjepsY.js","./WordCountDialog-tFhMCGyn.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{c as Le,s as Cn,g as me,h as pe,a as fs,A as Ji,n as Xh,l as Zh,r as Qh,_ as Ct,S as ef,d as lt,i as Rs,k as nc,C as Ns,M as nn,e as sc,m as tf}from"./index-CqBmQAzW.js";import{r as u,u as et,j as o,P as zr,d as xo,e as nf}from"./react-BVUjbTTn.js";import{C as sf}from"./check-DKIW1zpR.js";import{f as rf,U as Yi,B as of,M as lf,G as af,X as Dn,e as Ur,j as Xi,b as cf,c as Xl,N as uf,d as rc,F as df,g as Zl,h as hf,k as Dt,C as ko,a as ff,T as ln,L as pf,S as Zi,D as kr,A as Sr,P as Ql,i as mf}from"./x-Cspw_pa4.js";import{S as gf}from"./search-Nu4OcY_n.js";import{U as wf}from"./user-plus-gFwY-NA3.js";import{R as yf}from"./refresh-cw-DyA4NKh7.js";const bf=Le("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const So=Le("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const ic=Le("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Co=Le("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);const ea=Le("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const Qi=Le("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);const xf=Le("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]]);const kf=Le("FileClock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"37hlfg"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}],["path",{d:"M9.5 17.5 8 16.25V14",key:"1o80t2"}]]);const Sf=Le("FileCog",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3.2 12.9-.9-.4",key:"1i3dj5"}],["path",{d:"m3.2 15.1-.9.4",key:"1fvgj0"}],["path",{d:"M4.677 21.5a2 2 0 0 0 1.313.5H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2.5",key:"1yo3oz"}],["path",{d:"m4.9 11.2-.4-.9",key:"otmhb9"}],["path",{d:"m4.9 16.8-.4.9",key:"1b8z07"}],["path",{d:"m7.5 10.3-.4.9",key:"11k65u"}],["path",{d:"m7.5 17.7-.4-.9",key:"431x55"}],["path",{d:"m9.7 12.5-.9.4",key:"87sjan"}],["path",{d:"m9.7 15.5-.9-.4",key:"khqm91"}],["circle",{cx:"6",cy:"14",r:"3",key:"a1xfv6"}]]);const Cf=Le("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);const vf=Le("FilePlus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);const jf=Le("FileType2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 13v-1h6v1",key:"1dh9dg"}],["path",{d:"M5 12v6",key:"150t9c"}],["path",{d:"M4 18h2",key:"1xrofg"}]]);const Ef=Le("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]]);const Df=Le("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);const oc=Le("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);const ta=Le("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);const _f=Le("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);const Tf=Le("LibraryBig",[["rect",{width:"8",height:"18",x:"3",y:"3",rx:"1",key:"oynpb5"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",key:"1qboyk"}]]);const na=Le("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);const lc=Le("PackageOpen",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]);const ac=Le("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);const Rf=Le("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);const Lf=Le("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const Af=Le("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const Nf=Le("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const Ff=Le("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);const Mf=Le("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);const sa=Le("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);const Of=Le("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);const $f=Le("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),If="wrap = false",eo=[{id:"jetbrains",labelKey:"projectSettings.fontJetBrains",stack:'"JetBrains Mono", ui-monospace, monospace'},{id:"source-code",labelKey:"projectSettings.fontSourceCode",stack:'"Source Code Pro", ui-monospace, monospace'},{id:"ibm-plex",labelKey:"projectSettings.fontIbmPlex",stack:'"IBM Plex Mono", ui-monospace, monospace'},{id:"fira-code",labelKey:"projectSettings.fontFiraCode",stack:'"Fira Code", ui-monospace, monospace'},{id:"iosevka",labelKey:"projectSettings.fontIosevka",stack:'"Iosevka", ui-monospace, monospace'}],xt={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,showTooltips:!1,spellCheck:!0,mathPreviewOnHover:!1,vimMode:!1,formatOnCompile:!1,texFmtConfig:If,texFmtConfigInitialized:!0,openFilesInTabs:!1},Pf="texlite-editor-preferences";function cc(t,e){return Cn(`${Pf}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function vx(t){return eo.find(e=>e.id===t)?.stack??eo[0].stack}function ra(t,e){try{const n=JSON.parse(localStorage.getItem(cc(t,e))??"{}"),s=typeof n.texFmtConfig=="string"&&n.texFmtConfig.length<=16*1024?n.texFmtConfig:null,r=s!==null&&(n.texFmtConfigInitialized===!0||s.trim().length>0)?s:xt.texFmtConfig;return{font:eo.some(i=>i.id===n.font)?n.font:xt.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):xt.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):xt.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:xt.lineWrapping,showTooltips:typeof n.showTooltips=="boolean"?n.showTooltips:xt.showTooltips,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:xt.spellCheck,mathPreviewOnHover:typeof n.mathPreviewOnHover=="boolean"?n.mathPreviewOnHover:xt.mathPreviewOnHover,vimMode:typeof n.vimMode=="boolean"?n.vimMode:xt.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:xt.formatOnCompile,texFmtConfig:r,texFmtConfigInitialized:!0,openFilesInTabs:typeof n.openFilesInTabs=="boolean"?n.openFilesInTabs:xt.openFilesInTabs}}catch{return xt}}function zf(t,e,n){localStorage.setItem(cc(t,e),JSON.stringify(n))}function Uf(){let t={status:"loading",error:""};const e=new Set,n=(s,r="")=>{if(!(t.status===s&&t.error===r)){t={status:s,error:r};for(const i of e)i()}};return{getSnapshot:()=>t,subscribe:s=>(e.add(s),()=>e.delete(s)),loading:()=>n("loading"),working:()=>n("working"),failed:s=>n("error",s instanceof Error?s.message:String(s))}}const sn=Uf(),Bf=/\.(?:tex|bib|cls|sty)$/i,uc=3e4;let Et=null,Cr=!1,vn=null,qf=1;const Tn=new Map,vr=[];let Jn=null,_s=null;class yt extends Error{constructor(e,n){super(n),this.kind=e,this.name="TexFmtError"}kind}function Di(t){return t instanceof yt}function Kt(t){Et?.terminate(),Et=null,Cr=!1,vn!==null&&window.clearTimeout(vn),vn=null,Jn=null,vr.length=0,_s=null,sn.failed(t);for(const e of Tn.values())e.timeout!==null&&window.clearTimeout(e.timeout),e.reject(t);Tn.clear()}function Ls(){if(Jn!==null||vr.length===0)return;let t;try{t=Wf()}catch(s){Kt(s instanceof yt?s:new yt("load","The bundled tex-fmt formatter could not be loaded."));return}if(!Cr)return;const e=vr.shift();if(e===void 0)return;const n=Tn.get(e);if(!n){Ls();return}Jn=e,n.timeout=window.setTimeout(()=>{Jn===e&&Kt(new yt("result","The formatter did not respond within 30 seconds."))},uc);try{t.postMessage({...n.request,id:e})}catch{Kt(new yt("load","The formatter worker could not receive the source."))}}function Wf(){if(Et)return Et;if(typeof Worker>"u"){const t=new yt("load","This browser does not support formatter workers.");throw sn.failed(t),t}sn.loading();try{Et=new Worker(new URL(""+new URL("latexFormatterWorker-BRmsns8a.js",import.meta.url).href,import.meta.url),{type:"module",name:"texlite-latex-formatter"}),vn=window.setTimeout(()=>{Cr||Kt(new yt("load","The formatter did not finish loading within 30 seconds."))},uc)}catch{const t=new yt("load","The bundled tex-fmt formatter could not be loaded.");throw sn.failed(t),t}return Et.onmessage=t=>{const e=t.data;if(e&&"type"in e){e.type==="ready"&&(Cr=!0,vn!==null&&window.clearTimeout(vn),vn=null,Ls());return}if(!e||typeof e.id!="number"){Kt(new yt("result","The formatter worker returned an invalid response."));return}const n=Tn.get(e.id);if(n)if(Tn.delete(e.id),n.timeout!==null&&window.clearTimeout(n.timeout),Jn===e.id&&(Jn=null),e.ok)sn.working(),n.resolve(e.result),Ls();else{const s=new yt(e.kind,e.message);e.kind==="format"?(sn.working(),n.reject(s),Ls()):(n.reject(s),Kt(s))}},Et.onerror=()=>{Kt(new yt("load","The bundled tex-fmt formatter could not be loaded."))},Et.onmessageerror=()=>{Kt(new yt("result","The formatter worker returned an unreadable response."))},Et}function vo(t){const e=qf++;return new Promise((n,s)=>{Tn.set(e,{request:t,resolve:n,reject:s,timeout:null}),vr.push(e),Ls()})}function Vf(t,e=""){return vo({action:"format",source:t,config:e})}async function Hf(){Et&&sn.getSnapshot().status==="working"||(_s||(_s=vo({action:"probe"}).then(()=>{}).finally(()=>{_s=null})),await _s)}async function jx(){(Et||Tn.size)&&Kt(new yt("load","The formatter runtime was reloaded.")),sn.loading(),await Hf()}function dr(t){return Bf.test(t)}function Kf(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function Gf(t,e){const n=Kf(t),l=(n?t.slice(0,-n.length):t).split(/\r?\n/).find(f=>f.trim())?.match(/^[\t ]*/)?.[0]??"",a=e.replace(/(?:\r?\n)+$/,"");return`${l?a.split(`
|
|
3
|
-
`).map(f=>f&&`${l}${f}`).join(`
|
|
4
|
-
`):a}${n}`}async function _i(t,e,n=0){return vo({action:"diff",source:t,formatted:e,baseOffset:n})}function Jf(t,e=null){const n=ia(t),r=e==="succeeded"||e===null&&Xf(t)?[]:oa(n.filter(la)),i=ia(Yf(t));return{warnings:oa(i.filter(a=>!la(a)&&Zf(a))),errors:r}}function ia(t){return t.split(`
|
|
5
|
-
`).map(e=>e.trim()).filter(Boolean)}function oa(t){return[...new Set(t)]}function Yf(t){const e=/^Running ['"][^\n]*(?:pdf|xe|lua)latex(?:\s|['"])[^\n]*$/gim;let n=-1;for(const s of t.matchAll(e))n=s.index;return n>=0?t.slice(n):t}function Xf(t){return/Latexmk: All targets .* are up-to-date/i.test(t)&&/Output written on .*\.pdf/i.test(t)}function la(t){return/^!\s/.test(t)||/(?:^|:\s)(?:LaTeX|Package|Class|pdfTeX|XeTeX|LuaTeX)?\s*Error:/i.test(t)||/^Latexmk:.*(?:\bErrors?,|did not complete making targets|failure)/i.test(t)||/^Collected error summary/i.test(t)||/\b(?:fatal error|emergency stop|undefined control sequence|no output pdf|no pages of output)\b/i.test(t)||/\b(?:bibtex|biber) errors?:/i.test(t)||/^error, and then rerun latexmk/i.test(t)}function Zf(t){return/\bwarnings?\b|overfull|underfull|badness/i.test(t)}const aa=1,ca=2,Ti=4,Ri=8,Fs=32,Gt=64,ut=128,Qf=1<<29,Br=31,to=63,_n=127,ep=2147483647,Ft=(t,e)=>t>>>e|t<<32-e,tp=t=>Ft(t,2)^Ft(t,13)^Ft(t,22),np=t=>Ft(t,6)^Ft(t,11)^Ft(t,25),sp=t=>Ft(t,7)^Ft(t,18)^t>>>3,rp=t=>Ft(t,17)^Ft(t,19)^t>>>10,ip=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),op=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);class lp{constructor(){const e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(op),this._W=new Uint32Array(e,64,64)}_updateHash(){const e=this._H,n=this._W;for(let h=16;h<64;h++)n[h]=rp(n[h-2])+n[h-7]+sp(n[h-15])+n[h-16];let s=e[0],r=e[1],i=e[2],l=e[3],a=e[4],c=e[5],f=e[6],d=e[7];for(let h=0,m,g;h<64;h++)m=d+np(a)+(a&c^~a&f)+ip[h]+n[h]>>>0,g=tp(s)+(s&r^s&i^r&i)>>>0,d=f,f=c,c=a,a=l+m>>>0,l=i,i=r,r=s,s=m+g>>>0;e[0]+=s,e[1]+=r,e[2]+=i,e[3]+=l,e[4]+=a,e[5]+=c,e[6]+=f,e[7]+=d}digest(e){let n=0;for(;n+56<=e.length;){let l=0;for(;l<16&&n+3<e.length;l++)this._W[l]=e[n++]<<24|e[n++]<<16|e[n++]<<8|e[n++];if(n%64!==0){for(this._W.fill(0,l,16);n<e.length;)this._W[l]|=e[n]<<(3-n%4)*8,n++;this._W[l]|=ut<<(3-n%4)*8}this._updateHash()}const s=n%64!==0;this._W.fill(0,0,16);let r=0;for(;n<e.length;r++)for(let l=3;l>=0&&n<e.length;l--)this._W[r]|=e[n++]<<l*8;s||(this._W[r-(n%4===0?0:1)]|=ut<<(3-n%4)*8),this._W[14]=e.byteLength/Qf,this._W[15]=e.byteLength*8,this._updateHash();const i=new Uint8Array(32);for(let l=0;l<this._H.length;l++)for(let a=0;a<4;a++)i[l*4+a]=this._H[l]>>>(3-a)*8;return i}}const ap=t=>new lp().digest(t);function cp(t){return Array.from(ap(new TextEncoder().encode(t)),e=>e.toString(16).padStart(2,"0")).join("")}function ua(t){return t instanceof Error&&t.name==="AbortError"}function up({projectId:t,activeFile:e,content:n,permission:s,revision:r,selection:i,save:l,saveFailureMessage:a,onError:c,onAdded:f,onChanged:d}){const[h,m]=u.useState({filePath:"",comments:[],loading:!1}),[g,w]=u.useState([]),[v,D]=u.useState(!1),[k,B]=u.useState(""),[A,b]=u.useState("file"),[O,S]=u.useState(null),[T,z]=u.useState(!1),[Z,X]=u.useState(""),[ce,W]=u.useState(null),[ge,Q]=u.useState(!1),[I,ee]=u.useState(""),we=u.useRef(null),K=u.useRef(null),G=u.useRef(!1),V=u.useRef(e),he=u.useRef(A),se=u.useRef(l),ie=u.useRef(c),C=u.useRef(f),fe=u.useRef(d);V.current=e,he.current=A,se.current=l,ie.current=c,C.current=f,fe.current=d;const te=h.filePath===e?h.comments:[],H=h.filePath,ve=H===e&&!h.loading,De=async N=>{we.current?.abort();const q=new AbortController;we.current=q,V.current===N&&m(xe=>xe.filePath===N?{...xe,loading:!0}:{filePath:"",comments:[],loading:!0});try{const xe=await me(`/api/projects/${t}/comments?path=${encodeURIComponent(N)}`,{signal:q.signal});we.current===q&&V.current===N&&m({filePath:N,comments:xe.comments,loading:!1})}catch(xe){!ua(xe)&&we.current===q&&V.current===N&&m({filePath:N,comments:[],loading:!1})}finally{we.current===q&&(we.current=null)}},oe=async()=>{K.current?.abort();const N=new AbortController;K.current=N,he.current==="project"&&(D(!0),B(""));try{const q=await me(`/api/projects/${t}/comments?scope=project`,{signal:N.signal});K.current===N&&he.current==="project"&&w(q.comments)}catch(q){!ua(q)&&K.current===N&&he.current==="project"&&B(pe(q))}finally{K.current===N&&(K.current=null,he.current==="project"&&D(!1))}};u.useEffect(()=>{we.current?.abort(),we.current=null,K.current?.abort(),K.current=null,S(null),m({filePath:"",comments:[],loading:!1}),w([]),D(!1),B(""),b("file"),z(!1),W(null),ee("")},[t]),u.useEffect(()=>{z(!1),W(null),ee("")},[e]),u.useEffect(()=>(e?De(e):m({filePath:"",comments:[],loading:!1}),()=>{we.current?.abort(),we.current=null}),[t,e,r]),u.useEffect(()=>{if(A!=="project"){K.current?.abort(),K.current=null,w([]),D(!1),B("");return}return oe(),()=>{K.current?.abort(),K.current=null}},[t,A,r]);const Ce=async N=>{const q=[];V.current===N&&q.push(De(N)),he.current==="project"&&q.push(oe()),await Promise.all(q)},Ae=(N,q)=>{e&&(ee(""),W({filePath:e,selection:{...N??i},sourceHash:cp(q??n)}),z(!0))},P=()=>{G.current||(z(!1),W(null),ee(""))},_e=async()=>{const N=ce;if(!(!Z.trim()||!N||G.current)){G.current=!0,Q(!0),ee("");try{if(s!=="read"&&!await se.current()){ee(a);return}await me(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:N.filePath,content:Z,...N.selection,sourceHash:N.sourceHash})}),await Ce(N.filePath),z(!1),W(null),X(""),C.current(),fe.current?.()}catch(q){ee(pe(q))}finally{G.current=!1,Q(!1)}}},R=async N=>{try{await me(`/api/projects/${t}/comments/${N.id}`,{method:"PATCH",body:JSON.stringify({resolved:!N.resolved})}),await Ce(N.filePath),fe.current?.()}catch(q){ie.current(pe(q))}},be=async(N,q)=>{try{return await me(`/api/projects/${t}/comments/${N.id}/replies`,{method:"POST",body:JSON.stringify({content:q})}),await Ce(N.filePath),fe.current?.(),!0}catch(xe){return ie.current(pe(xe)),!1}},Te=async(N,q)=>{try{return await me(`/api/projects/${t}/comments/${N.id}`,{method:"PATCH",body:JSON.stringify({content:q})}),await Ce(N.filePath),fe.current?.(),!0}catch(xe){return ie.current(pe(xe)),!1}},F=async N=>{try{return await me(`/api/projects/${t}/comments/${N.id}`,{method:"DELETE"}),await Ce(N.filePath),S(q=>q?.id===N.id?null:q),fe.current?.(),!0}catch(q){return ie.current(pe(q)),!1}},je=async(N,q,xe)=>{try{return await me(`/api/projects/${t}/comments/${N.id}/replies/${q}`,{method:"PATCH",body:JSON.stringify({content:xe})}),await Ce(N.filePath),fe.current?.(),!0}catch(Re){return ie.current(pe(Re)),!1}},re=async(N,q)=>{try{return await me(`/api/projects/${t}/comments/${N.id}/replies/${q}`,{method:"DELETE"}),await Ce(N.filePath),fe.current?.(),!0}catch(xe){return ie.current(pe(xe)),!1}};return{comments:te,commentsFilePath:H,commentsReady:ve,reviewComments:A==="file"?te:g,reviewCommentsLoading:A==="project"&&v,reviewCommentsError:A==="project"?k:"",retryReviewComments:oe,commentScope:A,setCommentScope:b,focusComment:O,setFocusComment:S,commentOpen:T,openComment:Ae,closeComment:P,commentText:Z,setCommentText:X,commentSelection:ce?.selection??i,commentSubmitting:ge,commentError:I,addComment:_e,toggleComment:R,replyToComment:be,editComment:Te,deleteComment:F,editCommentReply:je,deleteCommentReply:re}}function dc(t,e){return e.scope==="project"||t.filePath===e.activeFile}function jo(t,e,n){return e==="unresolved"?!t.resolved:e==="resolved"?t.resolved:n.some(s=>s.commentId===t.id)}function Li(t,e){return t.filter(n=>dc(n,e)&&jo(n,e.filter,e.unreadMentions))}function dp(t,e,n=[]){const s=new Set(n.filter(r=>!!r));return t.filter(r=>dc(r,e)?s.has(r.id)||jo(r,e.filter,e.unreadMentions):!1)}function hp(t,e){return t.filter(n=>n.filePath===e)}function fp(t,e,n){return!t||t.filePath!==e||n!==e?null:t}function pp(t,e,n,s,r,i){return!t||t.filePath!==e||n!==e||s!==e||!r?null:i.find(l=>l.id===t.id&&l.filePath===e)??null}function mp(t,e,n){return!jo({...t,resolved:!t.resolved},e,n)}function gp(t,e){if(!e)return 0;const n=t.findIndex(s=>s.id===e);return n<0?0:n+1}function wp(t,e,n){if(!t.length)return null;const s=e?t.findIndex(i=>i.id===e):-1;if(s<0)return n===1?t[0]:null;const r=s+n;return r>=0&&r<t.length?t[r]:null}function yp(t){return t instanceof Error&&t.name==="AbortError"}function bp(t,e,n){const[s,r]=u.useState([]),i=u.useRef(null),l=u.useRef(n);l.current=n;const a=u.useCallback(async(d=!1)=>{i.current?.abort();const h=new AbortController;i.current=h;try{const m=await me(`/api/projects/${t}/mentions?unread=1&limit=100`,{signal:h.signal});i.current===h&&r(m.mentions)}catch(m){i.current===h&&!yp(m)&&(r([]),d&&l.current(pe(m)))}finally{i.current===h&&(i.current=null)}},[t]);return u.useEffect(()=>(a(),()=>{i.current?.abort(),i.current=null}),[a,e]),{unreadMentions:s,refresh:a,markMentionRead:async d=>{try{return await me(`/api/projects/${t}/mentions/${encodeURIComponent(d)}/read`,{method:"POST"}),r(h=>h.filter(m=>m.id!==d)),!0}catch(h){return l.current(pe(h)),!1}},markAllMentionsRead:async()=>{if(!s.length)return!0;try{return await me(`/api/projects/${t}/mentions/read-all`,{method:"POST"}),r([]),!0}catch(d){return l.current(pe(d)),!1}}}}const pt=()=>new Map,no=t=>{const e=pt();return t.forEach((n,s)=>{e.set(s,n)}),e},$t=(t,e,n)=>{let s=t.get(e);return s===void 0&&t.set(e,s=n()),s},xp=(t,e)=>{const n=[];for(const[s,r]of t)n.push(e(r,s));return n},kp=(t,e)=>{for(const[n,s]of t)if(e(s,n))return!0;return!1},an=()=>new Set,Ai=t=>t[t.length-1],Sp=(t,e)=>{for(let n=0;n<e.length;n++)t.push(e[n])},Jt=Array.from,Eo=(t,e)=>{for(let n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0},Do=(t,e)=>{for(let n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1},Cp=(t,e)=>{const n=new Array(t);for(let s=0;s<t;s++)n[s]=e(s,n);return n},rs=Array.isArray;class _o{constructor(){this._observers=pt()}on(e,n){return $t(this._observers,e,an).add(n),n}once(e,n){const s=(...r)=>{this.off(e,s),n(...r)};this.on(e,s)}off(e,n){const s=this._observers.get(e);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(e))}emit(e,n){return Jt((this._observers.get(e)||pt()).values()).forEach(s=>s(...n))}destroy(){this._observers=pt()}}class hc{constructor(){this._observers=pt()}on(e,n){$t(this._observers,e,an).add(n)}once(e,n){const s=(...r)=>{this.off(e,s),n(...r)};this.on(e,s)}off(e,n){const s=this._observers.get(e);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(e))}emit(e,n){return Jt((this._observers.get(e)||pt()).values()).forEach(s=>s(...n))}destroy(){this._observers=pt()}}const Tt=Math.floor,gr=Math.abs,To=(t,e)=>t<e?t:e,Nn=(t,e)=>t>e?t:e,vp=Math.pow,fc=t=>t!==0?t<0:1/t<0,jr=Number.MAX_SAFE_INTEGER,da=Number.MIN_SAFE_INTEGER,jp=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Tt(t)===t),pc=String.fromCharCode,Ep=t=>t.toLowerCase(),Dp=/^\s*/g,_p=t=>t.replace(Dp,""),Tp=/([A-Z])/g,ha=(t,e)=>_p(t.replace(Tp,n=>`${e}${Ep(n)}`)),Rp=t=>{const e=unescape(encodeURIComponent(t)),n=e.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=e.codePointAt(r);return s},Ms=typeof TextEncoder<"u"?new TextEncoder:null,Lp=t=>Ms.encode(t),Ap=Ms?Lp:Rp;let As=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});As&&As.decode(new Uint8Array).length===1&&(As=null);const Np=(t,e)=>Cp(e,()=>t).join("");class Vs{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Be=()=>new Vs,Ro=t=>{let e=t.cpos;for(let n=0;n<t.bufs.length;n++)e+=t.bufs[n].length;return e},Me=t=>{const e=new Uint8Array(Ro(t));let n=0;for(let s=0;s<t.bufs.length;s++){const r=t.bufs[s];e.set(r,n),n+=r.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),n),e},Fp=(t,e)=>{const n=t.cbuf.length;n-t.cpos<e&&(t.bufs.push(new Uint8Array(t.cbuf.buffer,0,t.cpos)),t.cbuf=new Uint8Array(Nn(n,e)*2),t.cpos=0)},Ze=(t,e)=>{const n=t.cbuf.length;t.cpos===n&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(n*2),t.cpos=0),t.cbuf[t.cpos++]=e},so=Ze,Y=(t,e)=>{for(;e>_n;)Ze(t,ut|_n&e),e=Tt(e/128);Ze(t,_n&e)},Lo=(t,e)=>{const n=fc(e);for(n&&(e=-e),Ze(t,(e>to?ut:0)|(n?Gt:0)|to&e),e=Tt(e/64);e>0;)Ze(t,(e>_n?ut:0)|_n&e),e=Tt(e/128)},ro=new Uint8Array(3e4),Mp=ro.length/3,Op=(t,e)=>{if(e.length<Mp){const n=Ms.encodeInto(e,ro).written||0;Y(t,n);for(let s=0;s<n;s++)Ze(t,ro[s])}else Ue(t,Ap(e))},$p=(t,e)=>{const n=unescape(encodeURIComponent(e)),s=n.length;Y(t,s);for(let r=0;r<s;r++)Ze(t,n.codePointAt(r))},rt=Ms&&Ms.encodeInto?Op:$p,qr=(t,e)=>{const n=t.cbuf.length,s=t.cpos,r=To(n-s,e.length),i=e.length-r;t.cbuf.set(e.subarray(0,r),s),t.cpos+=r,i>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(Nn(n*2,i)),t.cbuf.set(e.subarray(r)),t.cpos=i)},Ue=(t,e)=>{Y(t,e.byteLength),qr(t,e)},Ao=(t,e)=>{Fp(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},Ip=(t,e)=>Ao(t,4).setFloat32(0,e,!1),Pp=(t,e)=>Ao(t,8).setFloat64(0,e,!1),zp=(t,e)=>Ao(t,8).setBigInt64(0,e,!1),fa=new DataView(new ArrayBuffer(4)),Up=t=>(fa.setFloat32(0,t),fa.getFloat32(0)===t),Os=(t,e)=>{switch(typeof e){case"string":Ze(t,119),rt(t,e);break;case"number":jp(e)&&gr(e)<=ep?(Ze(t,125),Lo(t,e)):Up(e)?(Ze(t,124),Ip(t,e)):(Ze(t,123),Pp(t,e));break;case"bigint":Ze(t,122),zp(t,e);break;case"object":if(e===null)Ze(t,126);else if(rs(e)){Ze(t,117),Y(t,e.length);for(let n=0;n<e.length;n++)Os(t,e[n])}else if(e instanceof Uint8Array)Ze(t,116),Ue(t,e);else{Ze(t,118);const n=Object.keys(e);Y(t,n.length);for(let s=0;s<n.length;s++){const r=n[s];rt(t,r),Os(t,e[r])}}break;case"boolean":Ze(t,e?120:121);break;default:Ze(t,127)}};class pa extends Vs{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Y(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const ma=t=>{t.count>0&&(Lo(t.encoder,t.count===1?t.s:-t.s),t.count>1&&Y(t.encoder,t.count-2))};class wr{constructor(){this.encoder=new Vs,this.s=0,this.count=0}write(e){this.s===e?this.count++:(ma(this),this.count=1,this.s=e)}toUint8Array(){return ma(this),Me(this.encoder)}}const ga=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Lo(t.encoder,e),t.count>1&&Y(t.encoder,t.count-2)}};class Ni{constructor(){this.encoder=new Vs,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(ga(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return ga(this),Me(this.encoder)}}class Bp{constructor(){this.sarr=[],this.s="",this.lensE=new wr}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new Vs;return this.sarr.push(this.s),this.s="",rt(e,this.sarr.join("")),qr(e,this.lensE.toUint8Array()),Me(e)}}const Rt=t=>new Error(t),_t=()=>{throw Rt("Method unimplemented")},bt=()=>{throw Rt("Unexpected case")},mc=Rt("Unexpected end of array"),gc=Rt("Integer out of Range");class Wr{constructor(e){this.arr=e,this.pos=0}}const dn=t=>new Wr(t),io=t=>t.pos!==t.arr.length,qp=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},ot=t=>qp(t,de(t)),is=t=>t.arr[t.pos++],de=t=>{let e=0,n=1;const s=t.arr.length;for(;t.pos<s;){const r=t.arr[t.pos++];if(e=e+(r&_n)*n,n*=128,r<ut)return e;if(e>jr)throw gc}throw mc},No=t=>{let e=t.arr[t.pos++],n=e&to,s=64;const r=(e&Gt)>0?-1:1;if((e&ut)===0)return r*n;const i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],n=n+(e&_n)*s,s*=128,e<ut)return r*n;if(n>jr)throw gc}throw mc},Wp=t=>{let e=de(t);if(e===0)return"";{let n=String.fromCodePoint(is(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(is(t));else for(;e>0;){const s=e<1e4?e:1e4,r=t.arr.subarray(t.pos,t.pos+s);t.pos+=s,n+=String.fromCodePoint.apply(null,r),e-=s}return decodeURIComponent(escape(n))}},Vp=t=>As.decode(ot(t)),ze=As?Vp:Wp,Fo=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},Hp=t=>Fo(t,4).getFloat32(0,!1),Kp=t=>Fo(t,8).getFloat64(0,!1),Gp=t=>Fo(t,8).getBigInt64(0,!1),Jp=[t=>{},t=>null,No,Hp,Kp,Gp,t=>!1,t=>!0,ze,t=>{const e=de(t),n={};for(let s=0;s<e;s++){const r=ze(t);n[r]=$s(t)}return n},t=>{const e=de(t),n=[];for(let s=0;s<e;s++)n.push($s(t));return n},ot],$s=t=>Jp[127-is(t)](t);class wa extends Wr{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),io(this)?this.count=de(this)+1:this.count=-1),this.count--,this.s}}class yr extends Wr{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=No(this);const e=fc(this.s);this.count=1,e&&(this.s=-this.s,this.count=de(this)+2)}return this.count--,this.s}}class Fi extends Wr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=No(this),n=e&1;this.diff=Tt(e/2),this.count=1,n&&(this.count=de(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Yp{constructor(e){this.decoder=new yr(e),this.str=ze(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),n=this.str.slice(this.spos,e);return this.spos=e,n}}const Xp=crypto.getRandomValues.bind(crypto),wc=()=>Xp(new Uint32Array(1))[0],Zp="10000000-1000-4000-8000"+-1e11,Qp=()=>Zp.replace(/[018]/g,t=>(t^wc()&15>>t/4).toString(16)),cn=Date.now,os=t=>new Promise(t);Promise.all.bind(Promise);const ya=t=>t===void 0?null:t;class em{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let yc=new em,Mo=!0;try{typeof localStorage<"u"&&localStorage&&(yc=localStorage,Mo=!1)}catch{}const bc=yc,tm=t=>Mo||addEventListener("storage",t),nm=t=>Mo||removeEventListener("storage",t),Is=Symbol("Equality"),xc=(t,e)=>t===e||!!t?.[Is]?.(e)||!1,sm=t=>typeof t=="object",rm=Object.assign,im=Object.keys,om=(t,e)=>{for(const n in t)e(t[n],n)},lm=(t,e)=>{const n=[];for(const s in t)n.push(e(t[s],s));return n},Er=t=>im(t).length,am=t=>{for(const e in t)return!1;return!0},Hs=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},Oo=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),cm=(t,e)=>t===e||Er(t)===Er(e)&&Hs(t,(n,s)=>(n!==void 0||Oo(e,s))&&xc(e[s],n)),um=Object.freeze,kc=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&kc(t[e])}return um(t)},$o=(t,e,n=0)=>{try{for(;n<t.length;n++)t[n](...e)}finally{n<t.length&&$o(t,e,n+1)}},dm=t=>t,Yn=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[Is]!=null)return t[Is](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;break}case Set:{if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;break}case Map:{if(t.size!==e.size)return!1;for(const n of t.keys())if(!e.has(n)||!Yn(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(Er(t)!==Er(e))return!1;for(const n in t)if(!Oo(t,n)||!Yn(t[n],e[n]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!Yn(t[n],e[n]))return!1;break;default:return!1}return!0},hm=(t,e)=>e.includes(t);var Sc={};const un=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Cc=typeof window<"u"&&typeof document<"u"&&!un;let Nt;const fm=()=>{if(Nt===void 0)if(un){Nt=pt();const t=process.argv;let e=null;for(let n=0;n<t.length;n++){const s=t[n];s[0]==="-"?(e!==null&&Nt.set(e,""),e=s):e!==null&&(Nt.set(e,s),e=null)}e!==null&&Nt.set(e,"")}else typeof location=="object"?(Nt=pt(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,n]=t.split("=");Nt.set(`--${ha(e,"-")}`,n),Nt.set(`-${ha(e,"-")}`,n)}})):Nt=pt();return Nt},oo=t=>fm().has(t),Dr=t=>ya(un?Sc[t.toUpperCase().replaceAll("-","_")]:bc.getItem(t)),vc=t=>oo("--"+t)||Dr(t)!==null,pm=vc("production"),mm=un&&hm(Sc.FORCE_COLOR,["true","1","2"]),gm=mm||!oo("--no-colors")&&!vc("no-color")&&(!un||process.stdout.isTTY)&&(!un||oo("--color")||Dr("COLORTERM")!==null||(Dr("TERM")||"").includes("color")),jc=t=>new Uint8Array(t),wm=(t,e,n)=>new Uint8Array(t,e,n),ym=t=>new Uint8Array(t),bm=t=>{let e="";for(let n=0;n<t.byteLength;n++)e+=pc(t[n]);return btoa(e)},xm=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),km=t=>{const e=atob(t),n=jc(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n},Sm=t=>{const e=Buffer.from(t,"base64");return wm(e.buffer,e.byteOffset,e.byteLength)},Cm=Cc?bm:xm,vm=Cc?km:Sm,jm=t=>{const e=jc(t.byteLength);return e.set(t),e};class Em{constructor(e,n){this.left=e,this.right=n}}const Vt=(t,e)=>new Em(t,e),Dm=(t,e)=>t.forEach(n=>e(n.left,n.right)),ba=t=>t.next()>=.5,Mi=(t,e,n)=>Tt(t.next()*(n+1-e)+e),Ec=(t,e,n)=>Tt(t.next()*(n+1-e)+e),Io=(t,e,n)=>Ec(t,e,n),_m=t=>pc(Io(t,97,122)),Tm=(t,e=0,n=20)=>{const s=Io(t,e,n);let r="";for(let i=0;i<s;i++)r+=_m(t);return r},Oi=(t,e)=>e[Io(t,0,e.length-1)],Rm=Symbol("0schema");class Lm{constructor(){this._rerrs=[]}extend(e,n,s,r=null){this._rerrs.push({path:e,expected:n,has:s,message:r})}toString(){const e=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];e.push(Np(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return e.join(`
|
|
6
|
-
`)}}const lo=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[Is]?xc(t,e):rs(t)?Eo(t,n=>Do(e,s=>lo(n,s))):sm(t)?Hs(t,(n,s)=>lo(n,e[s])):!1;class dt{static _dilutes=!1;extends(e){let[n,s]=[this.shape,e.shape];return this.constructor._dilutes&&([s,n]=[n,s]),lo(n,s)}equals(e){return this.constructor===e.constructor&&Yn(this.shape,e.shape)}[Rm](){return!0}[Is](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){_t()}get nullable(){return ps(this,Jr)}get optional(){return new Tc(this)}cast(e){return xa(e,this),e}expect(e){return xa(e,this),e}}class Po extends dt{constructor(e,n){super(),this.shape=e,this._c=n}check(e,n=void 0){const s=e?.constructor===this.shape&&(this._c==null||this._c(e));return!s&&n?.extend(null,this.shape.name,e?.constructor.name,e?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const Ge=(t,e=null)=>new Po(t,e);Ge(Po);class zo extends dt{constructor(e){super(),this.shape=e}check(e,n){const s=this.shape(e);return!s&&n?.extend(null,"custom prop",e?.constructor.name,"failed to check custom prop"),s}}const tt=t=>new zo(t);Ge(zo);class Vr extends dt{constructor(e){super(),this.shape=e}check(e,n){const s=this.shape.some(r=>r===e);return!s&&n?.extend(null,this.shape.join(" | "),e.toString()),s}}const Hr=(...t)=>new Vr(t),Dc=Ge(Vr),Am=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),_c=t=>{if(ls.check(t))return[Am(t)];if(Dc.check(t))return t.shape.map(e=>e+"");if(Ic.check(t))return["[+-]?\\d+.?\\d*"];if(Pc.check(t))return[".*"];if(_r.check(t))return t.shape.map(_c).flat(1);bt()};class Nm extends dt{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(_c).map(n=>`(${n.join("|")})`).join("")+"$")}check(e,n){const s=this._r.exec(e)!=null;return!s&&n?.extend(null,this._r.toString(),e.toString(),"String doesn't match string template."),s}}Ge(Nm);const Fm=Symbol("optional");class Tc extends dt{constructor(e){super(),this.shape=e}check(e,n){const s=e===void 0||this.shape.check(e);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[Fm](){return!0}}const Mm=Ge(Tc);class Om extends dt{check(e,n){return n?.extend(null,"never",typeof e),!1}}Ge(Om);class Kr extends dt{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}static _dilutes=!0;get partial(){return new Kr(this.shape,!0)}check(e,n){return e==null?(n?.extend(null,"object","null"),!1):Hs(this.shape,(s,r)=>{const i=this._isPartial&&!Oo(e,r)||s.check(e[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof e[r],"Object property does not match"),i})}}const $m=t=>new Kr(t),Im=Ge(Kr),Pm=tt(t=>t!=null&&(t.constructor===Object||t.constructor==null));class Rc extends dt{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&Hs(e,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof e,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const Lc=(t,e)=>new Rc(t,e),zm=Ge(Rc);class Ac extends dt{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&Hs(this.shape,(s,r)=>{const i=s.check(e[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Um=(...t)=>new Ac(t);Ge(Ac);class Nc extends dt{constructor(e){super(),this.shape=e.length===1?e[0]:new Uo(e)}check(e,n){const s=rs(e)&&Eo(e,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Fc=(...t)=>new Nc(t),Bm=Ge(Nc),qm=tt(t=>rs(t));class Mc extends dt{constructor(e,n){super(),this.shape=e,this._c=n}check(e,n){const s=e instanceof this.shape&&(this._c==null||this._c(e));return!s&&n?.extend(null,this.shape.name,e?.constructor.name),s}}const Wm=(t,e=null)=>new Mc(t,e);Ge(Mc);const Vm=Wm(dt);class Hm extends dt{constructor(e){super(),this.len=e.length-1,this.args=Um(...e.slice(-1)),this.res=e[this.len]}check(e,n){const s=e.constructor===Function&&e.length<=this.len;return!s&&n?.extend(null,"function",typeof e),s}}const Km=Ge(Hm),Gm=tt(t=>typeof t=="function");class Jm extends dt{constructor(e){super(),this.shape=e}check(e,n){const s=Eo(this.shape,r=>r.check(e,n));return!s&&n?.extend(null,"Intersectinon",typeof e),s}}Ge(Jm,t=>t.shape.length>0);class Uo extends dt{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,n){const s=Do(this.shape,r=>r.check(e,n));return n?.extend(null,"Union",typeof e),s}}const ps=(...t)=>t.findIndex(e=>_r.check(e))>=0?ps(...t.map(e=>Ps(e)).map(e=>_r.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new Uo(t),_r=Ge(Uo),Oc=()=>!0,Tr=tt(Oc),Ym=Ge(zo,t=>t.shape===Oc),Bo=tt(t=>typeof t=="bigint"),Xm=tt(t=>t===Bo),$c=tt(t=>typeof t=="symbol");tt(t=>t===$c);const Xn=tt(t=>typeof t=="number"),Ic=tt(t=>t===Xn),ls=tt(t=>typeof t=="string"),Pc=tt(t=>t===ls),Gr=tt(t=>typeof t=="boolean"),Zm=tt(t=>t===Gr),zc=Hr(void 0);Ge(Vr,t=>t.shape.length===1&&t.shape[0]===void 0);Hr(void 0);const Jr=Hr(null),Qm=Ge(Vr,t=>t.shape.length===1&&t.shape[0]===null);Ge(Uint8Array);Ge(Po,t=>t.shape===Uint8Array);const eg=ps(Xn,ls,Jr,zc,Bo,Gr,$c);(()=>{const t=Fc(Tr),e=Lc(ls,Tr),n=ps(Xn,ls,Jr,Gr,t,e);return t.shape=n,e.shape.values=n,n})();const Ps=t=>{if(Vm.check(t))return t;if(Pm.check(t)){const e={};for(const n in t)e[n]=Ps(t[n]);return $m(e)}else{if(qm.check(t))return ps(...t.map(Ps));if(eg.check(t))return Hr(t);if(Gm.check(t))return Ge(t)}bt()},xa=pm?()=>{}:(t,e)=>{const n=new Lm;if(!e.check(t,n))throw Rt(`Expected value to be of type ${e.constructor.name}.
|
|
7
|
-
${n.toString()}`)};class tg{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:Ps(e),h:n}),this}else(e){return this.if(Tr,e)}done(){return(e,n)=>{for(let s=0;s<this.patterns.length;s++){const r=this.patterns[s];if(r.if.check(e))return r.h(e,n)}throw Rt("Unhandled pattern")}}}const ng=t=>new tg(t),Uc=ng(Tr).if(Ic,(t,e)=>Mi(e,da,jr)).if(Pc,(t,e)=>Tm(e)).if(Zm,(t,e)=>ba(e)).if(Xm,(t,e)=>BigInt(Mi(e,da,jr))).if(_r,(t,e)=>Vn(e,Oi(e,t.shape))).if(Im,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(Mm.check(r)){if(ba(e))continue;r=r.shape}n[s]=Uc(r,e)}return n}).if(Bm,(t,e)=>{const n=[],s=Ec(e,0,42);for(let r=0;r<s;r++)n.push(Vn(e,t.shape));return n}).if(Dc,(t,e)=>Oi(e,t.shape)).if(Qm,(t,e)=>null).if(Km,(t,e)=>{const n=Vn(e,t.res);return()=>n}).if(Ym,(t,e)=>Vn(e,Oi(e,[Xn,ls,Jr,zc,Bo,Gr,Fc(Xn),Lc(ps("a","b","c"),Xn)]))).if(zm,(t,e)=>{const n={},s=Mi(e,0,3);for(let r=0;r<s;r++){const i=Vn(e,t.shape.keys),l=Vn(e,t.shape.values);n[i]=l}return n}).done(),Vn=(t,e)=>Uc(Ps(e),t),It=typeof document<"u"?document:{},sg=t=>It.createElement(t),rg=()=>It.createDocumentFragment();tt(t=>t.nodeType===fg);const ig=t=>It.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const og=(t,e)=>(Dm(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),lg=t=>{const e=rg();for(let n=0;n<t.length;n++)Bc(e,t[n]);return e},ag=(t,e)=>(Bc(t,lg(e)),t),Ex=(t,e=[],n=[])=>ag(og(sg(t),e),n);tt(t=>t.nodeType===ug);const Dx=ig;tt(t=>t.nodeType===dg);const cg=t=>xp(t,(e,n)=>`${n}:${e};`).join(""),Bc=(t,e)=>t.appendChild(e),ug=It.ELEMENT_NODE,dg=It.TEXT_NODE;It.CDATA_SECTION_NODE;It.COMMENT_NODE;const hg=It.DOCUMENT_NODE;It.DOCUMENT_TYPE_NODE;const fg=It.DOCUMENT_FRAGMENT_NODE;tt(t=>t.nodeType===hg);const Yt=Symbol,qc=Yt(),Wc=Yt(),pg=Yt(),mg=Yt(),gg=Yt(),Vc=Yt(),wg=Yt(),qo=Yt(),yg=Yt(),bg=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[];let s=0;for(;s<t.length;s++){const r=t[s];if(r===void 0)break;if(r.constructor===String||r.constructor===Number)e.push(r);else if(r.constructor===Object)break}for(s>0&&n.push(e.join(""));s<t.length;s++){const r=t[s];r instanceof Symbol||n.push(r)}return n},xg={[qc]:Vt("font-weight","bold"),[Wc]:Vt("font-weight","normal"),[pg]:Vt("color","blue"),[gg]:Vt("color","green"),[mg]:Vt("color","grey"),[Vc]:Vt("color","red"),[wg]:Vt("color","purple"),[qo]:Vt("color","orange"),[yg]:Vt("color","black")},kg=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=pt();let r=[],i=0;for(;i<t.length;i++){const l=t[i],a=xg[l];if(a!==void 0)s.set(a.left,a.right);else{if(l===void 0)break;if(l.constructor===String||l.constructor===Number){const c=cg(s);i>0||c.length>0?(e.push("%c"+l),n.push(c)):e.push(l)}else break}}for(i>0&&(r=n,r.unshift(e.join("")));i<t.length;i++){const l=t[i];l instanceof Symbol||r.push(l)}return r},Hc=gm?kg:bg,Sg=(...t)=>{console.log(...Hc(t)),Gc.forEach(e=>e.print(t))},Kc=(...t)=>{console.warn(...Hc(t)),t.unshift(qo),Gc.forEach(e=>e.print(t))},Gc=an(),Jc=t=>({[Symbol.iterator](){return this},next:t}),Cg=(t,e)=>Jc(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),$i=(t,e)=>Jc(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class Yr{constructor(e,n){this.clock=e,this.len=n}}class ms{constructor(){this.clients=new Map}}const as=(t,e,n)=>e.clients.forEach((s,r)=>{const i=t.doc.store.clients.get(r);if(i!=null){const l=i[i.length-1],a=l.id.clock+l.length;for(let c=0,f=s[c];c<s.length&&f.clock<a;f=s[++c])uu(t,i,f.clock,f.len,n)}}),vg=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=Tt((n+s)/2),i=t[r],l=i.clock;if(l<=e){if(e<l+i.len)return r;n=r+1}else s=r-1}return null},Ks=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&vg(n,e.clock)!==null},Wo=t=>{t.clients.forEach(e=>{e.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n<e.length;n++){const r=e[s-1],i=e[n];r.clock+r.len>=i.clock?e[s-1]=new Yr(r.clock,Nn(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},ao=t=>{const e=new ms;for(let n=0;n<t.length;n++)t[n].clients.forEach((s,r)=>{if(!e.clients.has(r)){const i=s.slice();for(let l=n+1;l<t.length;l++)Sp(i,t[l].clients.get(r)||[]);e.clients.set(r,i)}});return Wo(e),e},zs=(t,e,n,s)=>{$t(t.clients,e,()=>[]).push(new Yr(n,s))},jg=()=>new ms,Eg=t=>{const e=jg();return t.clients.forEach((n,s)=>{const r=[];for(let i=0;i<n.length;i++){const l=n[i];if(l.deleted){const a=l.id.clock;let c=l.length;if(i+1<n.length)for(let f=n[i+1];i+1<n.length&&f.deleted;f=n[++i+1])c+=f.length;r.push(new Yr(a,c))}}r.length>0&&e.clients.set(s,r)}),e},gs=(t,e)=>{Y(t.restEncoder,e.clients.size),Jt(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),Y(t.restEncoder,n);const r=s.length;Y(t.restEncoder,r);for(let i=0;i<r;i++){const l=s[i];t.writeDsClock(l.clock),t.writeDsLen(l.len)}})},Vo=t=>{const e=new ms,n=de(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=de(t.restDecoder),i=de(t.restDecoder);if(i>0){const l=$t(e.clients,r,()=>[]);for(let a=0;a<i;a++)l.push(new Yr(t.readDsClock(),t.readDsLen()))}}return e},ka=(t,e,n)=>{const s=new ms,r=de(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const l=de(t.restDecoder),a=de(t.restDecoder),c=n.clients.get(l)||[],f=qe(n,l);for(let d=0;d<a;d++){const h=t.readDsClock(),m=h+t.readDsLen();if(h<f){f<m&&zs(s,l,f,m-f);let g=Mt(c,h),w=c[g];for(!w.deleted&&w.id.clock<h&&(c.splice(g+1,0,$r(e,w,h-w.id.clock)),g++);g<c.length&&(w=c[g++],w.id.clock<m);)w.deleted||(m<w.id.clock+w.length&&c.splice(g,0,$r(e,w,m-w.id.clock)),w.delete(e))}else zs(s,l,h,m-h)}}if(s.clients.size>0){const i=new Rn;return Y(i.restEncoder,0),gs(i,s),i.toUint8Array()}return null},Yc=wc;class Fn extends _o{constructor({guid:e=Qp(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:l=!1,shouldLoad:a=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Yc(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new au,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=l,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=os(f=>{this.on("load",()=>{this.isLoaded=!0,f(this)})});const c=()=>os(f=>{const d=h=>{(h===void 0||h===!0)&&(this.off("sync",d),f())};this.on("sync",d)});this.on("sync",f=>{f===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=f===void 0||f===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&Oe(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Jt(this.subdocs).map(e=>e.guid))}transact(e,n=null){return Oe(this,e,n)}get(e,n=Qe){const s=$t(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==Qe&&r!==n)if(r===Qe){const i=new n;i._map=s._map,s._map.forEach(l=>{for(;l!==null;l=l.left)l.parent=i}),i._start=s._start;for(let l=i._start;l!==null;l=l.right)l.parent=i;return i._length=s._length,this.share.set(e,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return s}getArray(e=""){return this.get(e,es)}getText(e=""){return this.get(e,ds)}getMap(e=""){return this.get(e,us)}getXmlElement(e=""){return this.get(e,hs)}getXmlFragment(e=""){return this.get(e,Ln)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,Jt(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new Fn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,Oe(e.parent.doc,s=>{const r=n.doc;e.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Xc{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return de(this.restDecoder)}readDsLen(){return de(this.restDecoder)}}class Zc extends Xc{readLeftID(){return ye(de(this.restDecoder),de(this.restDecoder))}readRightID(){return ye(de(this.restDecoder),de(this.restDecoder))}readClient(){return de(this.restDecoder)}readInfo(){return is(this.restDecoder)}readString(){return ze(this.restDecoder)}readParentInfo(){return de(this.restDecoder)===1}readTypeRef(){return de(this.restDecoder)}readLen(){return de(this.restDecoder)}readAny(){return $s(this.restDecoder)}readBuf(){return jm(ot(this.restDecoder))}readJSON(){return JSON.parse(ze(this.restDecoder))}readKey(){return ze(this.restDecoder)}}class Dg{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=de(this.restDecoder),this.dsCurrVal}readDsLen(){const e=de(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class cs extends Dg{constructor(e){super(e),this.keys=[],de(e),this.keyClockDecoder=new Fi(ot(e)),this.clientDecoder=new yr(ot(e)),this.leftClockDecoder=new Fi(ot(e)),this.rightClockDecoder=new Fi(ot(e)),this.infoDecoder=new wa(ot(e),is),this.stringDecoder=new Yp(ot(e)),this.parentInfoDecoder=new wa(ot(e),is),this.typeRefDecoder=new yr(ot(e)),this.lenDecoder=new yr(ot(e))}readLeftID(){return new Zn(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Zn(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return $s(this.restDecoder)}readBuf(){return ot(this.restDecoder)}readJSON(){return $s(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const n=this.stringDecoder.read();return this.keys.push(n),n}}}class Qc{constructor(){this.restEncoder=Be()}toUint8Array(){return Me(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Y(this.restEncoder,e)}writeDsLen(e){Y(this.restEncoder,e)}}class Gs extends Qc{writeLeftID(e){Y(this.restEncoder,e.client),Y(this.restEncoder,e.clock)}writeRightID(e){Y(this.restEncoder,e.client),Y(this.restEncoder,e.clock)}writeClient(e){Y(this.restEncoder,e)}writeInfo(e){so(this.restEncoder,e)}writeString(e){rt(this.restEncoder,e)}writeParentInfo(e){Y(this.restEncoder,e?1:0)}writeTypeRef(e){Y(this.restEncoder,e)}writeLen(e){Y(this.restEncoder,e)}writeAny(e){Os(this.restEncoder,e)}writeBuf(e){Ue(this.restEncoder,e)}writeJSON(e){rt(this.restEncoder,JSON.stringify(e))}writeKey(e){rt(this.restEncoder,e)}}class eu{constructor(){this.restEncoder=Be(),this.dsCurrVal=0}toUint8Array(){return Me(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,Y(this.restEncoder,n)}writeDsLen(e){e===0&&bt(),Y(this.restEncoder,e-1),this.dsCurrVal+=e}}class Rn extends eu{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Ni,this.clientEncoder=new wr,this.leftClockEncoder=new Ni,this.rightClockEncoder=new Ni,this.infoEncoder=new pa(so),this.stringEncoder=new Bp,this.parentInfoEncoder=new pa(so),this.typeRefEncoder=new wr,this.lenEncoder=new wr}toUint8Array(){const e=Be();return Y(e,0),Ue(e,this.keyClockEncoder.toUint8Array()),Ue(e,this.clientEncoder.toUint8Array()),Ue(e,this.leftClockEncoder.toUint8Array()),Ue(e,this.rightClockEncoder.toUint8Array()),Ue(e,Me(this.infoEncoder)),Ue(e,this.stringEncoder.toUint8Array()),Ue(e,Me(this.parentInfoEncoder)),Ue(e,this.typeRefEncoder.toUint8Array()),Ue(e,this.lenEncoder.toUint8Array()),qr(e,Me(this.restEncoder)),Me(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Os(this.restEncoder,e)}writeBuf(e){Ue(this.restEncoder,e)}writeJSON(e){Os(this.restEncoder,e)}writeKey(e){const n=this.keyMap.get(e);n===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(n)}}const _g=(t,e,n,s)=>{s=Nn(s,e[0].id.clock);const r=Mt(e,s);Y(t.restEncoder,e.length-r),t.writeClient(n),Y(t.restEncoder,s);const i=e[r];i.write(t,s-i.id.clock);for(let l=r+1;l<e.length;l++)e[l].write(t,0)},Ho=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{qe(e,i)>r&&s.set(i,r)}),Xr(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),Y(t.restEncoder,s.size),Jt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{_g(t,e.clients.get(r),r,i)})},Tg=(t,e)=>{const n=pt(),s=de(t.restDecoder);for(let r=0;r<s;r++){const i=de(t.restDecoder),l=new Array(i),a=t.readClient();let c=de(t.restDecoder);n.set(a,{i:0,refs:l});for(let f=0;f<i;f++){const d=t.readInfo();switch(Br&d){case 0:{const h=t.readLen();l[f]=new kt(ye(a,c),h),c+=h;break}case 10:{const h=de(t.restDecoder);l[f]=new St(ye(a,c),h),c+=h;break}default:{const h=(d&(Gt|ut))===0,m=new $e(ye(a,c),null,(d&ut)===ut?t.readLeftID():null,null,(d&Gt)===Gt?t.readRightID():null,h?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,h&&(d&Fs)===Fs?t.readString():null,Ru(t,d));l[f]=m,c+=m.length}}}}return n},Rg=(t,e,n)=>{const s=[];let r=Jt(n.keys()).sort((g,w)=>g-w);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let g=n.get(r[r.length-1]);for(;g.refs.length===g.i;)if(r.pop(),r.length>0)g=n.get(r[r.length-1]);else return null;return g};let l=i();if(l===null)return null;const a=new au,c=new Map,f=(g,w)=>{const v=c.get(g);(v==null||v>w)&&c.set(g,w)};let d=l.refs[l.i++];const h=new Map,m=()=>{for(const g of s){const w=g.id.client,v=n.get(w);v?(v.i--,a.clients.set(w,v.refs.slice(v.i)),n.delete(w),v.i=0,v.refs=[]):a.clients.set(w,[g]),r=r.filter(D=>D!==w)}s.length=0};for(;;){if(d.constructor!==St){const w=$t(h,d.id.client,()=>qe(e,d.id.client))-d.id.clock;if(w<0)s.push(d),f(d.id.client,d.id.clock-1),m();else{const v=d.getMissing(t,e);if(v!==null){s.push(d);const D=n.get(v)||{refs:[],i:0};if(D.refs.length===D.i)f(v,qe(e,v)),m();else{d=D.refs[D.i++];continue}}else(w===0||w<d.length)&&(d.integrate(t,w),h.set(d.id.client,d.id.clock+d.length))}}if(s.length>0)d=s.pop();else if(l!==null&&l.i<l.refs.length)d=l.refs[l.i++];else{if(l=i(),l===null)break;d=l.refs[l.i++]}}if(a.clients.size>0){const g=new Rn;return Ho(g,a,new Map),Y(g.restEncoder,0),{missing:c,update:g.toUint8Array()}}return null},Lg=(t,e)=>Ho(t,e.doc.store,e.beforeState),Ag=(t,e,n,s=new cs(t))=>Oe(e,r=>{r.local=!1;let i=!1;const l=r.doc,a=l.store,c=Tg(s,l),f=Rg(r,a,c),d=a.pendingStructs;if(d){for(const[m,g]of d.missing)if(g<qe(a,m)){i=!0;break}if(f){for(const[m,g]of f.missing){const w=d.missing.get(m);(w==null||w>g)&&d.missing.set(m,g)}d.update=Lr([d.update,f.update])}}else a.pendingStructs=f;const h=ka(s,r,a);if(a.pendingDs){const m=new cs(dn(a.pendingDs));de(m.restDecoder);const g=ka(m,r,a);h&&g?a.pendingDs=Lr([h,g]):a.pendingDs=h||g}else a.pendingDs=h;if(i){const m=a.pendingStructs.update;a.pendingStructs=null,tu(r.doc,m)}},n,!1),tu=(t,e,n,s=cs)=>{const r=dn(e);Ag(r,t,n,new s(r))},nu=(t,e,n)=>tu(t,e,n,Zc),Ng=(t,e,n=new Map)=>{Ho(t,e.store,n),gs(t,Eg(e.store))},Fg=(t,e=new Uint8Array([0]),n=new Rn)=>{const s=su(e);Ng(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(Qg(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===Gs)return Xg(r.map((i,l)=>l===0?i:tw(i)));if(n.constructor===Rn)return Lr(r)}return r[0]},Ko=(t,e)=>Fg(t,e,new Gs),Mg=t=>{const e=new Map,n=de(t.restDecoder);for(let s=0;s<n;s++){const r=de(t.restDecoder),i=de(t.restDecoder);e.set(r,i)}return e},su=t=>Mg(new Xc(dn(t))),ru=(t,e)=>(Y(t.restEncoder,e.size),Jt(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{Y(t.restEncoder,n),Y(t.restEncoder,s)}),t),Og=(t,e)=>ru(t,Xr(e.store)),$g=(t,e=new eu)=>(t instanceof Map?ru(e,t):Og(e,t),e.toUint8Array()),Ig=t=>$g(t,new Qc);class Pg{constructor(){this.l=[]}}const Sa=()=>new Pg,Ca=(t,e)=>t.l.push(e),va=(t,e)=>{const n=t.l,s=n.length;t.l=n.filter(r=>e!==r),s===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},iu=(t,e,n)=>$o(t.l,[e,n]);class Zn{constructor(e,n){this.client=e,this.clock=n}}const Gn=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,ye=(t,e)=>new Zn(t,e),ou=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw bt()},Rr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class lu{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const _x=t=>{const e={};return t.type&&(e.type=t.type),t.tname&&(e.tname=t.tname),t.item&&(e.item=t.item),t.assoc!=null&&(e.assoc=t.assoc),e},Tx=t=>new lu(t.type==null?null:ye(t.type.client,t.type.clock),t.tname??null,t.item==null?null:ye(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class zg{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const Ug=(t,e,n=0)=>new zg(t,e,n),hr=(t,e,n)=>{let s=null,r=null;return t._item===null?r=ou(t):s=ye(t._item.id.client,t._item.id.clock),new lu(s,r,e,n)},Rx=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return hr(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return hr(t,ye(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return hr(t,s.lastId,n);s=s.right}return hr(t,null,n)},Bg=(t,e)=>{const n=Qn(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},Lx=(t,e,n=!0)=>{const s=e.store,r=t.item,i=t.type,l=t.tname,a=t.assoc;let c=null,f=0;if(r!==null){if(qe(s,r.client)<=r.clock)return null;const d=n?fo(s,r):Bg(s,r),h=d.item;if(!(h instanceof $e))return null;if(c=h.parent,c._item===null||!c._item.deleted){f=h.deleted||!h.countable?0:d.diff+(a>=0?0:1);let m=h.left;for(;m!==null;)!m.deleted&&m.countable&&(f+=m.length),m=m.left}}else{if(l!==null)c=e.get(l);else if(i!==null){if(qe(s,i.client)<=i.clock)return null;const{item:d}=n?fo(s,i):{item:Qn(s,i)};if(d instanceof $e&&d.content instanceof Pt)c=d.content.type;else return null}else throw bt();a>=0?f=c._length:f=0}return Ug(c,f,t.assoc)},Ax=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&Gn(t.item,e.item)&&Gn(t.type,e.type)&&t.assoc===e.assoc,Hn=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Ks(e.ds,t.id),co=(t,e)=>{const n=$t(t.meta,co,an),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<qe(s,i)&&ft(t,ye(i,r))}),as(t,e.ds,r=>{}),n.add(e))};class au{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Xr=t=>{const e=new Map;return t.clients.forEach((n,s)=>{const r=n[n.length-1];e.set(s,r.id.clock+r.length)}),e},qe=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},cu=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==e.id.clock)throw bt()}n.push(e)},Mt=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let l=Tt(e/(i+r.length-1)*s);for(;n<=s;){if(r=t[l],i=r.id.clock,i<=e){if(e<i+r.length)return l;n=l+1}else s=l-1;l=Tt((n+s)/2)}throw bt()},qg=(t,e)=>{const n=t.clients.get(e.client);return n[Mt(n,e.clock)]},Qn=qg,uo=(t,e,n)=>{const s=Mt(e,n),r=e[s];return r.id.clock<n&&r instanceof $e?(e.splice(s+1,0,$r(t,r,n-r.id.clock)),s+1):s},ft=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[uo(t,n,e.clock)]},ja=(t,e,n)=>{const s=e.clients.get(n.client),r=Mt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==kt&&s.splice(r+1,0,$r(t,i,n.clock-i.id.clock+1)),i},Wg=(t,e,n)=>{const s=t.clients.get(e.id.client);s[Mt(s,e.id.clock)]=n},uu=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let l=uo(t,e,n),a;do a=e[l++],i<a.id.clock+a.length&&uo(t,e,i),r(a);while(l<e.length&&e[l].id.clock<i)};class Vg{constructor(e,n,s){this.doc=e,this.deleteSet=new ms,this.beforeState=Xr(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=n,this.meta=new Map,this.local=s,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Ea=(t,e)=>e.deleteSet.clients.size===0&&!kp(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(Wo(e.deleteSet),Lg(t,e),gs(t,e.deleteSet),!0),Da=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&$t(t.changed,e,an).add(n)},br=(t,e)=>{let n=t[e],s=t[e-1],r=e;for(;r>0;n=s,s=t[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof $e&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=e-r;return i&&t.splice(e+1-i,i),i},Hg=(t,e,n)=>{for(const[s,r]of t.clients.entries()){const i=e.clients.get(s);for(let l=r.length-1;l>=0;l--){const a=r[l],c=a.clock+a.len;for(let f=Mt(i,a.clock),d=i[f];f<i.length&&d.id.clock<c;d=i[++f]){const h=i[f];if(a.clock+a.len<=h.id.clock)break;h instanceof $e&&h.deleted&&!h.keep&&n(h)&&h.gc(e,!1)}}}},Kg=(t,e)=>{t.clients.forEach((n,s)=>{const r=e.clients.get(s);for(let i=n.length-1;i>=0;i--){const l=n[i],a=To(r.length-1,1+Mt(r,l.clock+l.len-1));for(let c=a,f=r[c];c>0&&f.id.clock>=l.clock;f=r[c])c-=1+br(r,c)}})},du=(t,e)=>{if(e<t.length){const n=t[e],s=n.doc,r=s.store,i=n.deleteSet,l=n._mergeStructs;try{Wo(i),n.afterState=Xr(n.doc.store),s.emit("beforeObserverCalls",[n,s]);const a=[];n.changed.forEach((c,f)=>a.push(()=>{(f._item===null||!f._item.deleted)&&f._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,f)=>{f._dEH.l.length>0&&(f._item===null||!f._item.deleted)&&(c=c.filter(d=>d.target._item===null||!d.target._item.deleted),c.forEach(d=>{d.currentTarget=f,d._path=null}),c.sort((d,h)=>d.path.length-h.path.length),a.push(()=>{iu(f._dEH,c,n)}))}),a.push(()=>s.emit("afterTransaction",[n,s])),a.push(()=>{n._needFormattingCleanup&&mw(n)})}),$o(a,[])}finally{s.gc&&Hg(i,r,s.gcFilter),Kg(i,r),n.afterState.forEach((d,h)=>{const m=n.beforeState.get(h)||0;if(m!==d){const g=r.clients.get(h),w=Nn(Mt(g,m),1);for(let v=g.length-1;v>=w;)v-=1+br(g,v)}});for(let d=l.length-1;d>=0;d--){const{client:h,clock:m}=l[d].id,g=r.clients.get(h),w=Mt(g,m);w+1<g.length&&br(g,w+1)>1||w>0&&br(g,w)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(Sg(qo,qc,"[yjs] ",Wc,Vc,"Changed the client-id because another client seems to be using it."),s.clientID=Yc()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const d=new Gs;Ea(d,n)&&s.emit("update",[d.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const d=new Rn;Ea(d,n)&&s.emit("updateV2",[d.toUint8Array(),n.origin,s,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:f}=n;(a.size>0||f.size>0||c.size>0)&&(a.forEach(d=>{d.clientID=s.clientID,d.collectionid==null&&(d.collectionid=s.collectionid),s.subdocs.add(d)}),f.forEach(d=>s.subdocs.delete(d)),s.emit("subdocs",[{loaded:c,added:a,removed:f},s,n]),f.forEach(d=>d.destroy())),t.length<=e+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,t])):du(t,e+1)}}},Oe=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,l=null;t._transaction===null&&(i=!0,t._transaction=new Vg(t,n,s),r.push(t._transaction),r.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{l=e(t._transaction)}finally{if(i){const a=t._transaction===r[0];t._transaction=null,a&&du(r,0)}}return l};class Gg{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const _a=(t,e,n)=>{as(t,n.deletions,s=>{s instanceof $e&&e.scope.some(r=>r===t.doc||Rr(r,s))&&tl(s,!1)})},Ta=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;Oe(r,a=>{for(;e.length>0&&t.currStackItem===null;){const c=r.store,f=e.pop(),d=new Set,h=[];let m=!1;as(a,f.insertions,g=>{if(g instanceof $e){if(g.redone!==null){let{item:w,diff:v}=fo(c,g.id);v>0&&(w=ft(a,ye(w.id.client,w.id.clock+v))),g=w}!g.deleted&&i.some(w=>w===a.doc||Rr(w,g))&&h.push(g)}}),as(a,f.deletions,g=>{g instanceof $e&&i.some(w=>w===a.doc||Rr(w,g))&&!Ks(f.insertions,g.id)&&d.add(g)}),d.forEach(g=>{m=Tu(a,g,d,f.insertions,t.ignoreRemoteMapChanges,t)!==null||m});for(let g=h.length-1;g>=0;g--){const w=h[g];t.deleteFilter(w)&&(w.delete(a),m=!0)}t.currStackItem=m?f:null}a.changed.forEach((c,f)=>{c.has(null)&&f._searchMarker&&(f._searchMarker.length=0)}),s=a},t);const l=t.currStackItem;if(l!=null){const a=s.changedParentTypes;t.emit("stack-item-popped",[{stackItem:l,type:n,changedParentTypes:a,origin:t},t]),t.currStackItem=null}return l};class Jg extends _o{constructor(e,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:l=!1,doc:a=rs(e)?e[0].doc:e instanceof Fn?e:e.doc}={}){super(),this.scope=[],this.doc=a,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=l,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(D=>c.changedParentTypes.has(D)||D===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const f=this.undoing,d=this.redoing,h=f?this.redoStack:this.undoStack;f?this.stopCapturing():d||this.clear(!1,!0);const m=new ms;c.afterState.forEach((D,k)=>{const B=c.beforeState.get(k)||0,A=D-B;A>0&&zs(m,k,B,A)});const g=cn();let w=!1;if(this.lastChange>0&&g-this.lastChange<this.captureTimeout&&h.length>0&&!f&&!d){const D=h[h.length-1];D.deletions=ao([D.deletions,c.deleteSet]),D.insertions=ao([D.insertions,m])}else h.push(new Gg(c.deleteSet,m)),w=!0;!f&&!d&&(this.lastChange=g),as(c,c.deleteSet,D=>{D instanceof $e&&this.scope.some(k=>k===c.doc||Rr(k,D))&&tl(D,!0)});const v=[{stackItem:h[h.length-1],origin:c.origin,type:f?"redo":"undo",changedParentTypes:c.changedParentTypes},this];w?this.emit("stack-item-added",v):this.emit("stack-item-updated",v)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=rs(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof Qe?s.doc!==this.doc:s!==this.doc)&&Kc("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,n=!0){(e&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{e&&(this.undoStack.forEach(r=>_a(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>_a(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Ta(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Ta(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}}function*Yg(t){const e=de(t.restDecoder);for(let n=0;n<e;n++){const s=de(t.restDecoder),r=t.readClient();let i=de(t.restDecoder);for(let l=0;l<s;l++){const a=t.readInfo();if(a===10){const c=de(t.restDecoder);yield new St(ye(r,i),c),i+=c}else if((Br&a)!==0){const c=(a&(Gt|ut))===0,f=new $e(ye(r,i),null,(a&ut)===ut?t.readLeftID():null,null,(a&Gt)===Gt?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(a&Fs)===Fs?t.readString():null,Ru(t,a));yield f,i+=f.length}else{const c=t.readLen();yield new kt(ye(r,i),c),i+=c}}}}class Go{constructor(e,n){this.gen=Yg(e),this.curr=null,this.done=!1,this.filterSkips=n,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===St);return this.curr}}class Jo{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Xg=t=>Lr(t,Zc,Gs),Zg=(t,e)=>{if(t.constructor===kt){const{client:n,clock:s}=t.id;return new kt(ye(n,s+e),t.length-e)}else if(t.constructor===St){const{client:n,clock:s}=t.id;return new St(ye(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new $e(ye(s,r+e),null,ye(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},Lr=(t,e=cs,n=Rn)=>{if(t.length===1)return t[0];const s=t.map(d=>new e(dn(d)));let r=s.map(d=>new Go(d,!0)),i=null;const l=new n,a=new Jo(l);for(;r=r.filter(m=>m.curr!==null),r.sort((m,g)=>{if(m.curr.id.client===g.curr.id.client){const w=m.curr.id.clock-g.curr.id.clock;return w===0?m.curr.constructor===g.curr.constructor?0:m.curr.constructor===St?1:-1:w}else return g.curr.id.client-m.curr.id.client}),r.length!==0;){const d=r[0],h=d.curr.id.client;if(i!==null){let m=d.curr,g=!1;for(;m!==null&&m.id.clock+m.length<=i.struct.id.clock+i.struct.length&&m.id.client>=i.struct.id.client;)m=d.next(),g=!0;if(m===null||m.id.client!==h||g&&m.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)rn(a,i.struct,i.offset),i={struct:m,offset:0},d.next();else if(i.struct.id.clock+i.struct.length<m.id.clock)if(i.struct.constructor===St)i.struct.length=m.id.clock+m.length-i.struct.id.clock;else{rn(a,i.struct,i.offset);const w=m.id.clock-i.struct.id.clock-i.struct.length;i={struct:new St(ye(h,i.struct.id.clock+i.struct.length),w),offset:0}}else{const w=i.struct.id.clock+i.struct.length-m.id.clock;w>0&&(i.struct.constructor===St?i.struct.length-=w:m=Zg(m,w)),i.struct.mergeWith(m)||(rn(a,i.struct,i.offset),i={struct:m,offset:0},d.next())}}else i={struct:d.curr,offset:0},d.next();for(let m=d.curr;m!==null&&m.id.client===h&&m.id.clock===i.struct.id.clock+i.struct.length&&m.constructor!==St;m=d.next())rn(a,i.struct,i.offset),i={struct:m,offset:0}}i!==null&&(rn(a,i.struct,i.offset),i=null),Yo(a);const c=s.map(d=>Vo(d)),f=ao(c);return gs(l,f),l.toUint8Array()},Qg=(t,e,n=cs,s=Rn)=>{const r=su(e),i=new s,l=new Jo(i),a=new n(dn(t)),c=new Go(a,!1);for(;c.curr;){const d=c.curr,h=d.id.client,m=r.get(h)||0;if(c.curr.constructor===St){c.next();continue}if(d.id.clock+d.length>m)for(rn(l,d,Nn(m-d.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)rn(l,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=m;)c.next()}Yo(l);const f=Vo(a);return gs(i,f),i.toUint8Array()},hu=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Me(t.encoder.restEncoder)}),t.encoder.restEncoder=Be(),t.written=0)},rn=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&hu(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),Y(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},Yo=t=>{hu(t);const e=t.encoder.restEncoder;Y(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];Y(e,s.written),qr(e,s.restEncoder)}},ew=(t,e,n,s)=>{const r=new n(dn(t)),i=new Go(r,!1),l=new s,a=new Jo(l);for(let f=i.curr;f!==null;f=i.next())rn(a,e(f),0);Yo(a);const c=Vo(r);return gs(l,c),l.toUint8Array()},tw=t=>ew(t,dm,cs,Gs),Ra="You must not compute changes after the event-handler fired.";class Zr{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=nw(this.currentTarget,this.target))}deletes(e){return Ks(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Rt(Ra);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let l,a;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))l="delete",a=Ai(c.content.getContent());else return;else c!==null&&this.deletes(c)?(l="update",a=Ai(c.content.getContent())):(l="add",a=void 0)}else if(this.deletes(i))l="delete",a=Ai(i.content.getContent());else return;e.set(r,{action:l,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Rt(Ra);const n=this.target,s=an(),r=an(),i=[];if(e={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const c=()=>{a&&i.push(a)};for(let f=n._start;f!==null;f=f.right)f.deleted?this.deletes(f)&&!this.adds(f)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=f.length,r.add(f)):this.adds(f)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(f.content.getContent()),s.add(f)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=f.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}}const nw=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let s=0,r=e._item.parent._start;for(;r!==e._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}e=e._item.parent}return n},at=()=>{Kc("Invalid access: Add Yjs type to a document before reading data.")},fu=80;let Xo=0;class sw{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=Xo++}}const rw=t=>{t.timestamp=Xo++},pu=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=Xo++},iw=(t,e,n)=>{if(t.length>=fu){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return pu(s,e,n),s}else{const s=new sw(e,n);return t.push(s),s}},Qr=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((i,l)=>gr(e-i.index)<gr(e-l.index)?i:l);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,rw(n));s.right!==null&&r<e;){if(!s.deleted&&s.countable){if(e<r+s.length)break;r+=s.length}s=s.right}for(;s.left!==null&&r>e;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&gr(n.index-r)<s.parent.length/fu?(pu(n,s,r),n):iw(t._searchMarker,s,r)},Us=(t,e,n)=>{for(let s=t.length-1;s>=0;s--){const r=t[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){t.splice(s,1);continue}r.p=i,i.marker=!0}(e<r.index||n>0&&e===r.index)&&(r.index=Nn(e,r.index+n))}},ei=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;$t(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;iu(s._eH,n,e)};class Qe{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Sa(),this._dEH=Sa(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw _t()}clone(){throw _t()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Ca(this._eH,e)}observeDeep(e){Ca(this._dEH,e)}unobserve(e){va(this._eH,e)}unobserveDeep(e){va(this._dEH,e)}toJSON(){}}const mu=(t,e,n)=>{t.doc??at(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let s=n-e;const r=[];let i=t._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const l=i.content.getContent();if(l.length<=e)e-=l.length;else{for(let a=e;a<l.length&&s>0;a++)r.push(l[a]),s--;e=0}}i=i.right}return r},gu=t=>{t.doc??at();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r<s.length;r++)e.push(s[r])}n=n.right}return e},Bs=(t,e)=>{let n=0,s=t._start;for(t.doc??at();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i<r.length;i++)e(r[i],n++,t)}s=s.right}},wu=(t,e)=>{const n=[];return Bs(t,(s,r)=>{n.push(e(s,r,t))}),n},ow=t=>{let e=t._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),s=0,e=e.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},yu=(t,e)=>{t.doc??at();const n=Qr(t,e);let s=t._start;for(n!==null&&(s=n.p,e-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(e<s.length)return s.content.getContent()[e];e-=s.length}},Ar=(t,e,n,s)=>{let r=n;const i=t.doc,l=i.clientID,a=i.store,c=n===null?e._start:n.right;let f=[];const d=()=>{f.length>0&&(r=new $e(ye(l,qe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new An(f)),r.integrate(t,0),f=[])};s.forEach(h=>{if(h===null)f.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:f.push(h);break;default:switch(d(),h.constructor){case Uint8Array:case ArrayBuffer:r=new $e(ye(l,qe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Js(new Uint8Array(h))),r.integrate(t,0);break;case Fn:r=new $e(ye(l,qe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Ys(h)),r.integrate(t,0);break;default:if(h instanceof Qe)r=new $e(ye(l,qe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Pt(h)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),d()},bu=()=>Rt("Length exceeded!"),xu=(t,e,n,s)=>{if(n>e._length)throw bu();if(n===0)return e._searchMarker&&Us(e._searchMarker,n,s.length),Ar(t,e,null,s);const r=n,i=Qr(e,n);let l=e._start;for(i!==null&&(l=i.p,n-=i.index,n===0&&(l=l.prev,n+=l&&l.countable&&!l.deleted?l.length:0));l!==null;l=l.right)if(!l.deleted&&l.countable){if(n<=l.length){n<l.length&&ft(t,ye(l.id.client,l.id.clock+n));break}n-=l.length}return e._searchMarker&&Us(e._searchMarker,r,s.length),Ar(t,e,l,s)},lw=(t,e,n)=>{let r=(e._searchMarker||[]).reduce((i,l)=>l.index>i.index?l:i,{index:0,p:e._start}).p;if(r)for(;r.right;)r=r.right;return Ar(t,e,r,n)},ku=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,l=Qr(e,n);let a=e._start;for(l!==null&&(a=l.p,n-=l.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&ft(t,ye(a.id.client,a.id.clock+n)),n-=a.length);for(;s>0&&a!==null;)a.deleted||(s<a.length&&ft(t,ye(a.id.client,a.id.clock+s)),a.delete(t),s-=a.length),a=a.right;if(s>0)throw bu();e._searchMarker&&Us(e._searchMarker,r,-i+s)},Nr=(t,e,n)=>{const s=e._map.get(n);s!==void 0&&s.delete(t)},Zo=(t,e,n,s)=>{const r=e._map.get(n)||null,i=t.doc,l=i.clientID;let a;if(s==null)a=new An([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new An([s]);break;case Uint8Array:a=new Js(s);break;case Fn:a=new Ys(s);break;default:if(s instanceof Qe)a=new Pt(s);else throw new Error("Unexpected content type")}new $e(ye(l,qe(i.store,l)),r,r&&r.lastId,null,null,e,n,a).integrate(t,0)},Qo=(t,e)=>{t.doc??at();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Su=t=>{const e={};return t.doc??at(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},Cu=(t,e)=>{t.doc??at();const n=t._map.get(e);return n!==void 0&&!n.deleted},aw=(t,e)=>{const n={};return t._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!e.sv.has(i.id.client)||i.id.clock>=(e.sv.get(i.id.client)||0));)i=i.left;i!==null&&Hn(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},fr=t=>(t.doc??at(),Cg(t._map.entries(),e=>!e[1].deleted));class cw extends Zr{}class es extends Qe{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new es;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new es}clone(){const e=new es;return e.insert(0,this.toArray().map(n=>n instanceof Qe?n.clone():n)),e}get length(){return this.doc??at(),this._length}_callObserver(e,n){super._callObserver(e,n),ei(this,e,new cw(this,e))}insert(e,n){this.doc!==null?Oe(this.doc,s=>{xu(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?Oe(this.doc,n=>{lw(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?Oe(this.doc,s=>{ku(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return yu(this,e)}toArray(){return gu(this)}slice(e=0,n=this.length){return mu(this,e,n)}toJSON(){return this.map(e=>e instanceof Qe?e.toJSON():e)}map(e){return wu(this,e)}forEach(e){Bs(this,e)}[Symbol.iterator](){return ow(this)}_write(e){e.writeTypeRef(Fw)}}const uw=t=>new es;class dw extends Zr{constructor(e,n,s){super(e,n),this.keysChanged=s}}class us extends Qe{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new us}clone(){const e=new us;return this.forEach((n,s)=>{e.set(s,n instanceof Qe?n.clone():n)}),e}_callObserver(e,n){ei(this,e,new dw(this,e,n))}toJSON(){this.doc??at();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof Qe?r.toJSON():r}}),e}get size(){return[...fr(this)].length}keys(){return $i(fr(this),e=>e[0])}values(){return $i(fr(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return $i(fr(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??at(),this._map.forEach((n,s)=>{n.deleted||e(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?Oe(this.doc,n=>{Nr(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?Oe(this.doc,s=>{Zo(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return Qo(this,e)}has(e){return Cu(this,e)}clear(){this.doc!==null?Oe(this.doc,e=>{this.forEach(function(n,s,r){Nr(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Mw)}}const hw=t=>new us,on=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&cm(t,e);class ho{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&bt(),this.right.content.constructor===Xe?this.right.deleted||ws(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const La=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===Xe?e.right.deleted||ws(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&ft(t,ye(e.right.id.client,e.right.id.clock+n)),e.index+=e.right.length,n-=e.right.length),e.left=e.right,e.right=e.right.right;return e},pr=(t,e,n,s)=>{const r=new Map,i=s?Qr(e,n):null;if(i){const l=new ho(i.p.left,i.p,i.index,r);return La(t,l,n-i.index)}else{const l=new ho(null,e._start,0,r);return La(t,l,n)}},vu=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Xe&&on(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=t.doc,i=r.clientID;s.forEach((l,a)=>{const c=n.left,f=n.right,d=new $e(ye(i,qe(r.store,i)),c,c&&c.lastId,f,f&&f.id,e,null,new Xe(a,l));d.integrate(t,0),n.right=d,n.forward()})},ws=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},ju=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Xe&&on(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Eu=(t,e,n,s)=>{const r=t.doc,i=r.clientID,l=new Map;for(const a in s){const c=s[a],f=n.currentAttributes.get(a)??null;if(!on(f,c)){l.set(a,f);const{left:d,right:h}=n;n.right=new $e(ye(i,qe(r.store,i)),d,d&&d.lastId,h,h&&h.id,e,null,new Xe(a,c)),n.right.integrate(t,0),n.forward()}}return l},Ii=(t,e,n,s,r)=>{n.currentAttributes.forEach((m,g)=>{r[g]===void 0&&(r[g]=null)});const i=t.doc,l=i.clientID;ju(n,r);const a=Eu(t,e,n,r),c=s.constructor===String?new Ot(s):s instanceof Qe?new Pt(s):new Mn(s);let{left:f,right:d,index:h}=n;e._searchMarker&&Us(e._searchMarker,n.index,c.getLength()),d=new $e(ye(l,qe(i.store,l)),f,f&&f.lastId,d,d&&d.id,e,null,c),d.integrate(t,0),n.right=d,n.index=h,n.forward(),vu(t,e,n,a)},Aa=(t,e,n,s,r)=>{const i=t.doc,l=i.clientID;ju(n,r);const a=Eu(t,e,n,r);e:for(;n.right!==null&&(s>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Xe));){if(!n.right.deleted)switch(n.right.content.constructor){case Xe:{const{key:c,value:f}=n.right.content,d=r[c];if(d!==void 0){if(on(d,f))a.delete(c);else{if(s===0)break e;a.set(c,f)}n.right.delete(t)}else n.currentAttributes.set(c,f);break}default:s<n.right.length&&ft(t,ye(n.right.id.client,n.right.id.clock+s)),s-=n.right.length;break}n.forward()}if(s>0){let c="";for(;s>0;s--)c+=`
|
|
8
|
-
`;n.right=new $e(ye(l,qe(i.store,l)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Ot(c)),n.right.integrate(t,0),n.forward()}vu(t,e,n,a)},Du=(t,e,n,s,r)=>{let i=e;const l=pt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Xe){const f=i.content;l.set(f.key,f)}i=i.right}let a=0,c=!1;for(;e!==i;){if(n===e&&(c=!0),!e.deleted){const f=e.content;if(f.constructor===Xe){const{key:d,value:h}=f,m=s.get(d)??null;(l.get(d)!==f||m===h)&&(e.delete(t),a++,!c&&(r.get(d)??null)===h&&m!==h&&(m===null?r.delete(d):r.set(d,m))),!c&&!e.deleted&&ws(r,f)}}e=e.right}return a},fw=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const n=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Xe){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},pw=t=>{let e=0;return Oe(t.doc,n=>{let s=t._start,r=t._start,i=pt();const l=no(i);for(;r;)r.deleted===!1&&(r.content.constructor===Xe?ws(l,r.content):(e+=Du(n,s,r,i,l),i=no(l),s=r)),r=r.right}),e},mw=t=>{const e=new Set,n=t.doc;for(const[s,r]of t.afterState.entries()){const i=t.beforeState.get(s)||0;r!==i&&uu(t,n.store.clients.get(s),i,r,l=>{!l.deleted&&l.content.constructor===Xe&&l.constructor!==kt&&e.add(l.parent)})}Oe(n,s=>{as(t,t.deleteSet,r=>{if(r instanceof kt||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===Xe?e.add(i):fw(s,r)});for(const r of e)pw(r)})},Na=(t,e,n)=>{const s=n,r=no(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Pt:case Mn:case Ot:n<e.right.length&&ft(t,ye(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&Du(t,i,e.right,r,e.currentAttributes);const l=(e.left||e.right).parent;return l._searchMarker&&Us(l._searchMarker,e.index,-s+n),e};class gw extends Zr{constructor(e,n,s){super(e,n),this.childListChanged=!1,this.keysChanged=new Set,s.forEach(r=>{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,n=[];Oe(e,s=>{const r=new Map,i=new Map;let l=this.target._start,a=null;const c={};let f="",d=0,h=0;const m=()=>{if(a!==null){let g=null;switch(a){case"delete":h>0&&(g={delete:h}),h=0;break;case"insert":(typeof f=="object"||f.length>0)&&(g={insert:f},r.size>0&&(g.attributes={},r.forEach((w,v)=>{w!==null&&(g.attributes[v]=w)}))),f="";break;case"retain":d>0&&(g={retain:d},am(c)||(g.attributes=rm({},c))),d=0;break}g&&n.push(g),a=null}};for(;l!==null;){switch(l.content.constructor){case Pt:case Mn:this.adds(l)?this.deletes(l)||(m(),a="insert",f=l.content.getContent()[0],m()):this.deletes(l)?(a!=="delete"&&(m(),a="delete"),h+=1):l.deleted||(a!=="retain"&&(m(),a="retain"),d+=1);break;case Ot:this.adds(l)?this.deletes(l)||(a!=="insert"&&(m(),a="insert"),f+=l.content.str):this.deletes(l)?(a!=="delete"&&(m(),a="delete"),h+=l.length):l.deleted||(a!=="retain"&&(m(),a="retain"),d+=l.length);break;case Xe:{const{key:g,value:w}=l.content;if(this.adds(l)){if(!this.deletes(l)){const v=r.get(g)??null;on(v,w)?w!==null&&l.delete(s):(a==="retain"&&m(),on(w,i.get(g)??null)?delete c[g]:c[g]=w)}}else if(this.deletes(l)){i.set(g,w);const v=r.get(g)??null;on(v,w)||(a==="retain"&&m(),c[g]=v)}else if(!l.deleted){i.set(g,w);const v=c[g];v!==void 0&&(on(v,w)?v!==null&&l.delete(s):(a==="retain"&&m(),w===null?delete c[g]:c[g]=w))}l.deleted||(a==="insert"&&m(),ws(r,l.content));break}}l=l.right}for(m();n.length>0;){const g=n[n.length-1];if(g.retain!==void 0&&g.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class ds extends Qe{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??at(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new ds}clone(){const e=new ds;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new gw(this,e,n);ei(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??at();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Ot&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?Oe(this.doc,s=>{const r=new ho(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const l=e[i];if(l.insert!==void 0){const a=!n&&typeof l.insert=="string"&&i===e.length-1&&r.right===null&&l.insert.slice(-1)===`
|
|
9
|
-
`?l.insert.slice(0,-1):l.insert;(typeof a!="string"||a.length>0)&&Ii(s,this,r,a,l.attributes||{})}else l.retain!==void 0?Aa(s,this,r,l.retain,l.attributes||{}):l.delete!==void 0&&Na(s,r,l.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??at();const r=[],i=new Map,l=this.doc;let a="",c=this._start;function f(){if(a.length>0){const h={};let m=!1;i.forEach((w,v)=>{m=!0,h[v]=w});const g={insert:a};m&&(g.attributes=h),r.push(g),a=""}}const d=()=>{for(;c!==null;){if(Hn(c,e)||n!==void 0&&Hn(c,n))switch(c.content.constructor){case Ot:{const h=i.get("ychange");e!==void 0&&!Hn(c,e)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(f(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!Hn(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(f(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(f(),i.delete("ychange")),a+=c.content.str;break}case Pt:case Mn:{f();const h={insert:c.content.getContent()[0]};if(i.size>0){const m={};h.attributes=m,i.forEach((g,w)=>{m[w]=g})}r.push(h);break}case Xe:Hn(c,e)&&(f(),ws(i,c.content));break}c=c.right}f()};return e||n?Oe(l,h=>{e&&co(h,e),n&&co(h,n),d()},"cleanup"):d(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?Oe(r,i=>{const l=pr(i,this,e,!s);s||(s={},l.currentAttributes.forEach((a,c)=>{s[c]=a})),Ii(i,this,l,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?Oe(r,i=>{const l=pr(i,this,e,!s);Ii(i,this,l,n,s||{})}):this._pending.push(()=>this.insertEmbed(e,n,s||{}))}delete(e,n){if(n===0)return;const s=this.doc;s!==null?Oe(s,r=>{Na(r,pr(r,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,s){if(n===0)return;const r=this.doc;r!==null?Oe(r,i=>{const l=pr(i,this,e,!1);l.right!==null&&Aa(i,this,l,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?Oe(this.doc,n=>{Nr(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?Oe(this.doc,s=>{Zo(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return Qo(this,e)}getAttributes(){return Su(this)}_write(e){e.writeTypeRef(Ow)}}const ww=t=>new ds;class Pi{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??at()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===hs||n.constructor===Ln)&&n._start!==null)e=n._start;else for(;e!==null;){const s=e.next;if(s!==null){e=s;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Ln extends Qe{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ln}clone(){const e=new Ln;return e.insert(0,this.toArray().map(n=>n instanceof Qe?n.clone():n)),e}get length(){return this.doc??at(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Pi(this,e)}querySelector(e){e=e.toUpperCase();const s=new Pi(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),Jt(new Pi(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){ei(this,e,new xw(this,n,e))}toString(){return wu(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,n={},s){const r=e.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),Bs(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?Oe(this.doc,s=>{xu(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)Oe(this.doc,s=>{const r=e&&e instanceof Qe?e._item:e;Ar(s,this,r,n)});else{const s=this._prelimContent,r=e===null?0:s.findIndex(i=>i===e)+1;if(r===0&&e!==null)throw Rt("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?Oe(this.doc,s=>{ku(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return gu(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return yu(this,e)}slice(e=0,n=this.length){return mu(this,e,n)}forEach(e){Bs(this,e)}_write(e){e.writeTypeRef(Iw)}}const yw=t=>new Ln;class hs extends Ln{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new hs(this.nodeName)}clone(){const e=new hs(this.nodeName),n=this.getAttributes();return om(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof Qe?s.clone():s)),e}toString(){const e=this.getAttributes(),n=[],s=[];for(const a in e)s.push(a);s.sort();const r=s.length;for(let a=0;a<r;a++){const c=s[a];n.push(c+'="'+e[c]+'"')}const i=this.nodeName.toLocaleLowerCase(),l=n.length>0?" "+n.join(" "):"";return`<${i}${l}>${super.toString()}</${i}>`}removeAttribute(e){this.doc!==null?Oe(this.doc,n=>{Nr(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?Oe(this.doc,s=>{Zo(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return Qo(this,e)}hasAttribute(e){return Cu(this,e)}getAttributes(e){return e?aw(this,e):Su(this)}toDOM(e=document,n={},s){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const l in i){const a=i[l];typeof a=="string"&&r.setAttribute(l,a)}return Bs(this,l=>{r.appendChild(l.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef($w),e.writeKey(this.nodeName)}}const bw=t=>new hs(t.readKey());class xw extends Zr{constructor(e,n,s){super(e,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class Fr extends us{constructor(e){super(),this.hookName=e}_copy(){return new Fr(this.hookName)}clone(){const e=new Fr(this.hookName);return this.forEach((n,s)=>{e.set(s,n)}),e}toDOM(e=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(e){e.writeTypeRef(Pw),e.writeKey(this.hookName)}}const kw=t=>new Fr(t.readKey());class Mr extends ds{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new Mr}clone(){const e=new Mr;return e.applyDelta(this.toDelta()),e}toDOM(e=document,n,s){const r=e.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const n=[];for(const r in e.attributes){const i=[];for(const l in e.attributes[r])i.push({key:l,value:e.attributes[r][l]});i.sort((l,a)=>l.key<a.key?-1:1),n.push({nodeName:r,attrs:i})}n.sort((r,i)=>r.nodeName<i.nodeName?-1:1);let s="";for(let r=0;r<n.length;r++){const i=n[r];s+=`<${i.nodeName}`;for(let l=0;l<i.attrs.length;l++){const a=i.attrs[l];s+=` ${a.key}="${a.value}"`}s+=">"}s+=e.insert;for(let r=n.length-1;r>=0;r--)s+=`</${n[r].nodeName}>`;return s}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(zw)}}const Sw=t=>new Mr;class el{constructor(e,n){this.id=e,this.length=n}get deleted(){throw _t()}mergeWith(e){return!1}write(e,n,s){throw _t()}integrate(e,n){throw _t()}}const Cw=0;class kt extends el{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){n>0&&(this.id.clock+=n,this.length-=n),cu(e.doc.store,this)}write(e,n){e.writeInfo(Cw),e.writeLen(this.length-n)}getMissing(e,n){return null}}class Js{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Js(this.content)}splice(e){throw _t()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const vw=t=>new Js(t.readBuf());class qs{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new qs(this.len)}splice(e){const n=new qs(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){zs(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const jw=t=>new qs(t.readLen()),_u=(t,e)=>new Fn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Ys{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const n={};this.opts=n,e.gc||(n.gc=!1),e.autoLoad&&(n.autoLoad=!0),e.meta!==null&&(n.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Ys(_u(this.doc.guid,this.opts))}splice(e){throw _t()}mergeWith(e){return!1}integrate(e,n){this.doc._item=n,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,n){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const Ew=t=>new Ys(_u(t.readString(),t.readAny()));class Mn{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Mn(this.embed)}splice(e){throw _t()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const Dw=t=>new Mn(t.readJSON());class Xe{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Xe(this.key,this.value)}splice(e){throw _t()}mergeWith(e){return!1}integrate(e,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(e){}gc(e){}write(e,n){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const _w=t=>new Xe(t.readKey(),t.readJSON());class Or{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Or(this.arr)}splice(e){const n=new Or(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const s=this.arr.length;e.writeLen(s-n);for(let r=n;r<s;r++){const i=this.arr[r];e.writeString(i===void 0?"undefined":JSON.stringify(i))}}getRef(){return 2}}const Tw=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++){const r=t.readString();r==="undefined"?n.push(void 0):n.push(JSON.parse(r))}return new Or(n)},Rw=Dr("node_env")==="development";class An{constructor(e){this.arr=e,Rw&&kc(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new An(this.arr)}splice(e){const n=new An(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const s=this.arr.length;e.writeLen(s-n);for(let r=n;r<s;r++){const i=this.arr[r];e.writeAny(i)}}getRef(){return 8}}const Lw=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new An(n)};class Ot{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Ot(this.str)}splice(e){const n=new Ot(this.str.slice(e));this.str=this.str.slice(0,e);const s=this.str.charCodeAt(e-1);return s>=55296&&s<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const Aw=t=>new Ot(t.readString()),Nw=[uw,hw,ww,bw,yw,kw,Sw],Fw=0,Mw=1,Ow=2,$w=3,Iw=4,Pw=5,zw=6;class Pt{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Pt(this.type._copy())}splice(e){throw _t()}mergeWith(e){return!1}integrate(e,n){this.type._integrate(e.doc,n)}delete(e){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(e.beforeState.get(s.id.client)||0)&&e._mergeStructs.push(s):s.delete(e)}),e.changed.delete(this.type)}gc(e){let n=this.type._start;for(;n!==null;)n.gc(e,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(e,!0),s=s.left}),this.type._map=new Map}write(e,n){this.type._write(e)}getRef(){return 7}}const Uw=t=>new Pt(Nw[t.readTypeRef()](t)),fo=(t,e)=>{let n=e,s=0,r;do s>0&&(n=ye(n.client,n.clock+s)),r=Qn(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof $e);return{item:r,diff:s}},tl=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},$r=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new $e(ye(s,r+n),e,ye(s,r+n-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(n));return e.deleted&&i.markDeleted(),e.keep&&(i.keep=!0),e.redone!==null&&(i.redone=ye(e.redone.client,e.redone.clock+n)),e.right=i,i.right!==null&&(i.right.left=i),t._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),e.length=n,i},Fa=(t,e)=>Do(t,n=>Ks(n.deletions,e)),Tu=(t,e,n,s,r,i)=>{const l=t.doc,a=l.store,c=l.clientID,f=e.redone;if(f!==null)return ft(t,f);let d=e.parent._item,h=null,m;if(d!==null&&d.deleted===!0){if(d.redone===null&&(!n.has(d)||Tu(t,d,n,s,r,i)===null))return null;for(;d.redone!==null;)d=ft(t,d.redone)}const g=d===null?e.parent:d.content.type;if(e.parentSub===null){for(h=e.left,m=e;h!==null;){let k=h;for(;k!==null&&k.parent._item!==d;)k=k.redone===null?null:ft(t,k.redone);if(k!==null&&k.parent._item===d){h=k;break}h=h.left}for(;m!==null;){let k=m;for(;k!==null&&k.parent._item!==d;)k=k.redone===null?null:ft(t,k.redone);if(k!==null&&k.parent._item===d){m=k;break}m=m.right}}else{if(m=null,e.right&&!r){for(h=e;h!==null&&h.right!==null&&(h.right.redone||Ks(s,h.right.id)||Fa(i.undoStack,h.right.id)||Fa(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=ft(t,h.redone);if(h&&h.right!==null)return null}else h=g._map.get(e.parentSub)||null;h!==null&&h.parent._item!==d&&(h=g._map.get(e.parentSub)||null)}const w=qe(a,c),v=ye(c,w),D=new $e(v,h,h&&h.lastId,m,m&&m.id,g,e.parentSub,e.content.copy());return e.redone=v,tl(D,!0),D.integrate(t,0),D};class $e extends el{constructor(e,n,s,r,i,l,a,c){super(e,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=l,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?ca:0}set marker(e){(this.info&Ri)>0!==e&&(this.info^=Ri)}get marker(){return(this.info&Ri)>0}get keep(){return(this.info&aa)>0}set keep(e){this.keep!==e&&(this.info^=aa)}get countable(){return(this.info&ca)>0}get deleted(){return(this.info&Ti)>0}set deleted(e){this.deleted!==e&&(this.info^=Ti)}markDeleted(){this.info|=Ti}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=qe(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=qe(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Zn&&this.id.client!==this.parent.client&&this.parent.clock>=qe(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=ja(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=ft(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===kt||this.right&&this.right.constructor===kt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===$e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===$e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Zn){const s=Qn(n,this.parent);s.constructor===kt?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=ja(e,e.doc.store,ye(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,l=new Set;for(;r!==null&&r!==this.right;){if(l.add(r),i.add(r),Gn(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Gn(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&l.has(Qn(e.doc.store,r.origin)))i.has(Qn(e.doc.store,r.origin))||(s=r,i.clear());else break;r=r.right}this.left=s}if(this.left!==null){const s=this.left.right;this.right=s,this.left.right=this}else{let s;if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start,this.parent._start=this;this.right=s}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),cu(e.doc.store,this),this.content.integrate(e,this),Da(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new kt(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:ye(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Gn(e.origin,this.lastId)&&this.right===e&&Gn(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const n=this.parent._searchMarker;return n&&n.forEach(s=>{s.p===e&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),zs(e.deleteSet,this.id.client,this.id.clock,this.length),Da(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw bt();this.content.gc(e),n?Wg(e,this,new kt(this.id,this.length)):this.content=new qs(this.length)}write(e,n){const s=n>0?ye(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,l=this.content.getRef()&Br|(s===null?0:ut)|(r===null?0:Gt)|(i===null?0:Fs);if(e.writeInfo(l),s!==null&&e.writeLeftID(s),r!==null&&e.writeRightID(r),s===null&&r===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const f=ou(a);e.writeParentInfo(!0),e.writeString(f)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===Zn?(e.writeParentInfo(!1),e.writeLeftID(a)):bt();i!==null&&e.writeString(i)}this.content.write(e,n)}}const Ru=(t,e)=>Bw[e&Br](t),Bw=[()=>{bt()},jw,Tw,vw,Aw,Dw,_w,Uw,Lw,Ew,()=>{bt()}],qw=10;class St extends el{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){bt()}write(e,n){e.writeInfo(qw),Y(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const Lu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Au="__ $YJS$ __";Lu[Au]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Lu[Au]=!0;function Ww(t){for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t}function Vw(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function po(t=globalThis.crypto){if(typeof t?.randomUUID=="function")return t.randomUUID();const e=new Uint8Array(16),n=typeof t?.getRandomValues=="function"?t.getRandomValues(e):Ww(e);return Vw(n)}const Nu=new Map;class Hw{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:vm(n.newValue||"")}),tm(this._onChange)}postMessage(e){bc.setItem(this.room,Cm(ym(e)))}close(){nm(this._onChange)}}const Kw=typeof BroadcastChannel>"u"?Hw:BroadcastChannel,nl=t=>$t(Nu,t,()=>{const e=an(),n=new Kw(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),Gw=(t,e)=>(nl(t).subs.add(e),e),Jw=(t,e)=>{const n=nl(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),Nu.delete(t)),s},Kn=(t,e,n=null)=>{const s=nl(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},Fu=0,sl=1,Mu=2,Ir=(t,e)=>{Y(t,Fu);const n=Ig(e);Ue(t,n)},Ou=(t,e,n)=>{Y(t,sl),Ue(t,Ko(e,n))},Yw=(t,e,n)=>Ou(e,n,ot(t)),$u=(t,e,n,s)=>{try{nu(e,ot(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Xw=(t,e)=>{Y(t,Mu),Ue(t,e)},Zw=$u,Qw=(t,e,n,s,r)=>{const i=de(t);switch(i){case Fu:Yw(t,e,n);break;case sl:$u(t,n,s,r);break;case Mu:Zw(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},ey=0,ty=(t,e,n)=>{de(t)===ey&&n(e,ze(t))},zi=3e4;class ny extends hc{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=cn();this.getLocalState()!==null&&zi/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&zi<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&rl(this,s,"timeout")},Tt(zi/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);e===null?this.states.delete(n):this.states.set(n,e),this.meta.set(n,{clock:r,lastUpdated:cn()});const l=[],a=[],c=[],f=[];e===null?f.push(n):i==null?e!=null&&l.push(n):(a.push(n),Yn(i,e)||c.push(n)),(l.length>0||c.length>0||f.length>0)&&this.emit("change",[{added:l,updated:c,removed:f},"local"]),this.emit("update",[{added:l,updated:a,removed:f},"local"])}setLocalStateField(e,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:n})}getStates(){return this.states}}const rl=(t,e,n)=>{const s=[];for(let r=0;r<e.length;r++){const i=e[r];if(t.states.has(i)){if(t.states.delete(i),i===t.clientID){const l=t.meta.get(i);t.meta.set(i,{clock:l.clock+1,lastUpdated:cn()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},ts=(t,e,n=t.states)=>{const s=e.length,r=Be();Y(r,s);for(let i=0;i<s;i++){const l=e[i],a=n.get(l)||null,c=t.meta.get(l).clock;Y(r,l),Y(r,c),rt(r,JSON.stringify(a))}return Me(r)},sy=(t,e,n)=>{const s=dn(e),r=cn(),i=[],l=[],a=[],c=[],f=de(s);for(let d=0;d<f;d++){const h=de(s);let m=de(s);const g=JSON.parse(ze(s)),w=t.meta.get(h),v=t.states.get(h),D=w===void 0?0:w.clock;(D<m||D===m&&g===null&&t.states.has(h))&&(g===null?h===t.clientID&&t.getLocalState()!=null?m++:t.states.delete(h):t.states.set(h,g),t.meta.set(h,{clock:m,lastUpdated:r}),w===void 0&&g!==null?i.push(h):w!==void 0&&g===null?c.push(h):g!==null&&(Yn(g,v)||a.push(h),l.push(h)))}(i.length>0||a.length>0||c.length>0)&&t.emit("change",[{added:i,updated:a,removed:c},n]),(i.length>0||l.length>0||c.length>0)&&t.emit("update",[{added:i,updated:l,removed:c},n])},ry=t=>lm(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),jn=0,Iu=3,ns=1,iy=2,Xs=[];Xs[jn]=(t,e,n,s,r)=>{Y(t,jn);const i=Qw(e,t,n.doc,n);s&&i===sl&&!n.synced&&(n.synced=!0)};Xs[Iu]=(t,e,n,s,r)=>{Y(t,ns),Ue(t,ts(n.awareness,Array.from(n.awareness.getStates().keys())))};Xs[ns]=(t,e,n,s,r)=>{sy(n.awareness,ot(e),n)};Xs[iy]=(t,e,n,s,r)=>{ty(e,n.doc,(i,l)=>oy(n,l))};const Ma=3e4,oy=(t,e)=>console.warn(`Permission denied to access ${t.url}.
|
|
10
|
-
${e}`),Pu=(t,e,n)=>{const s=dn(e),r=Be(),i=de(s),l=t.messageHandlers[i];return l?l(r,s,t,n,i):console.error("Unable to compute message"),r},mo=(t,e,n)=>{e===t.ws&&(t.emit("connection-close",[n,t]),t.ws=null,e.close(),t.wsconnecting=!1,t.wsconnected?(t.wsconnected=!1,t.synced=!1,rl(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(zu,To(vp(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},zu=t=>{if(t.shouldConnect&&t.ws===null){const e=new t._WS(t.url,t.protocols);e.binaryType="arraybuffer",t.ws=e,t.wsconnecting=!0,t.wsconnected=!1,t.synced=!1,e.onmessage=n=>{t.wsLastMessageReceived=cn();const s=Pu(t,new Uint8Array(n.data),!0);Ro(s)>1&&e.send(Me(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{mo(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=cn(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Be();if(Y(n,jn),Ir(n,t.doc),e.send(Me(n)),t.awareness.getLocalState()!==null){const s=Be();Y(s,ns),Ue(s,ts(t.awareness,[t.doc.clientID])),e.send(Me(s))}},t.emit("status",[{status:"connecting"}])}},Ui=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&Kn(t.bcChannel,e,t)};class ly extends _o{constructor(e,n,s,{connect:r=!0,awareness:i=new ny(s),params:l={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:f=-1,maxBackoffTime:d=2500,disableBc:h=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+n,this.maxBackoffTime=d,this.params=l,this.protocols=a,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Xs.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,f>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const m=Be();Y(m,jn),Ir(m,s),this.ws.send(Me(m))}},f)),this._bcSubscriber=(m,g)=>{if(g!==this){const w=Pu(this,new Uint8Array(m),!1);Ro(w)>1&&Kn(this.bcChannel,Me(w),this)}},this._updateHandler=(m,g)=>{if(g!==this){const w=Be();Y(w,jn),Xw(w,m),Ui(this,Me(w))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:m,updated:g,removed:w},v)=>{const D=m.concat(g).concat(w),k=Be();Y(k,ns),Ue(k,ts(i,D)),Ui(this,Me(k))},this._exitHandler=()=>{rl(this.awareness,[s.clientID],"app closed")},un&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Ma<cn()-this.wsLastMessageReceived&&mo(this,this.ws,null)},Ma/10),r&&this.connect()}get url(){const e=ry(this.params);return this.serverUrl+"/"+this.roomname+(e.length===0?"":"?"+e)}get synced(){return this._synced}set synced(e){this._synced!==e&&(this._synced=e,this.emit("synced",[e]),this.emit("sync",[e]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),un&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(Gw(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Be();Y(e,jn),Ir(e,this.doc),Kn(this.bcChannel,Me(e),this);const n=Be();Y(n,jn),Ou(n,this.doc),Kn(this.bcChannel,Me(n),this);const s=Be();Y(s,Iu),Kn(this.bcChannel,Me(s),this);const r=Be();Y(r,ns),Ue(r,ts(this.awareness,[this.doc.clientID])),Kn(this.bcChannel,Me(r),this)}disconnectBc(){const e=Be();Y(e,ns),Ue(e,ts(this.awareness,[this.doc.clientID],new Map)),Ui(this,Me(e)),this.bcconnected&&(Jw(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&mo(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(zu(this),this.connectBc())}}const On=t=>os((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),ay=(t,e)=>os((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(Rt(i.target.error)),r.onsuccess=i=>{const l=i.target.result;l.onversionchange=()=>{l.close()},n(l)}}),cy=t=>On(indexedDB.deleteDatabase(t)),uy=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),Ts=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>yy(s,r))},Uu=(t,e)=>On(t.count(e)),dy=(t,e)=>On(t.get(e)),Bu=(t,e)=>On(t.delete(e)),hy=(t,e,n)=>On(t.put(e,n)),go=(t,e)=>On(t.add(e)),fy=(t,e,n)=>On(t.getAll(e,n)),py=(t,e,n)=>{let s=null;return wy(t,e,r=>(s=r,!1),n).then(()=>s)},my=(t,e=null)=>py(t,e,"prev"),gy=(t,e)=>os((n,s)=>{t.onerror=s,t.onsuccess=async r=>{const i=r.target.result;if(i===null||await e(i)===!1)return n();i.continue()}}),wy=(t,e,n,s="next")=>gy(t.openKeyCursor(e,s),r=>n(r.key)),yy=(t,e)=>t.objectStore(e),by=(t,e)=>IDBKeyRange.upperBound(t,e),xy=(t,e)=>IDBKeyRange.lowerBound(t,e),Bi="custom",qu="updates",Wu=500,Vu=(t,e=()=>{},n=()=>{})=>{const[s]=Ts(t.db,[qu]);return fy(s,xy(t._dbref,!1)).then(r=>{t._destroyed||(e(s),Oe(t.doc,()=>{r.forEach(i=>nu(t.doc,i))},t,!1),n(s))}).then(()=>my(s).then(r=>{t._dbref=r+1})).then(()=>Uu(s).then(r=>{t._dbsize=r})).then(()=>s)},ky=(t,e=!0)=>Vu(t).then(n=>{(e||t._dbsize>=Wu)&&go(n,Ko(t.doc)).then(()=>Bu(n,by(t._dbref,!0))).then(()=>Uu(n).then(s=>{t._dbsize=s}))});class Sy extends hc{constructor(e,n){super(),this.doc=n,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=ay(e,s=>uy(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=os(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Vu(this,l=>go(l,Ko(n)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(s,r)=>{if(this.db&&r!==this){const[i]=Ts(this.db,[qu]);go(i,s),++this._dbsize>=Wu&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{ky(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},n.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),n.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{cy(this.name)})}get(e){return this._db.then(n=>{const[s]=Ts(n,[Bi],"readonly");return dy(s,e)})}set(e,n){return this._db.then(s=>{const[r]=Ts(s,[Bi]);return hy(r,n,e)})}del(e){return this._db.then(n=>{const[s]=Ts(n,[Bi]);return Bu(s,e)})}}const Cy={Sync:0,Awareness:1,Flush:4,Protocol:5,Maintenance:6,Permission:7,CompileStates:8,FormatLease:9},qi=3,vy=["queued","running","succeeded","failed","cleaned"],jy=["cache","artifacts"];function Ey(t){return typeof t=="string"&&vy.includes(t)}function Dy(t){return typeof t=="string"&&jy.includes(t)}const Oa=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],{Sync:_y,Awareness:Ty,Flush:$a,Protocol:Ia,Maintenance:Ry,Permission:Ly,CompileStates:Ay,FormatLease:Wi}=Cy,Ny=6e4,Fy=720*60*60*1e3,My=15e3,Oy=5*6e4;function $y(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!Ey(e.status)||e.status==="cleaned"&&!Dy(e.cleanMode)||e.stale!==void 0&&typeof e.stale!="boolean"||typeof e.updatedAt!="string"||!n||typeof n.id!="string"||typeof n.username!="string"||typeof n.name!="string"?null:e}function Pa(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=$y(s);r&&r.mainFile===n&&(e[n]=r)}return e}function Iy(t,e,n){return t<=n&&e<=n}function za(t,e,n){const s=r=>r>0&&n-r<=Oy;return{recoverable:t.some(r=>r.tabId===e||!s(r.activeAt)),otherActive:t.some(r=>r.tabId!==e&&s(r.activeAt))}}class Py{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.draftTabId=qy(Cn(`texlite:collaboration-tab:${n.id}:${e}`));const r=this.readOwnWritableDraftMarker();this.draftGeneration=r?.generation??0,this.draftUpdatedAt=r?.updatedAt??0,this.draftMarkerPresent=r!==null,this.markDraftTabInactive=()=>this.setOwnDraftActivity(!1),this.markDraftTabActive=()=>this.resumeOwnDraftActivity(),window.addEventListener("pagehide",this.markDraftTabInactive),window.addEventListener("pageshow",this.markDraftTabActive),r&&(this.setOwnDraftActivity(!0),this.startDraftHeartbeat()),this.persistence=new Sy(Cn(`texlite:${n.id}:${e}`),this.doc),this.localDraftTransactionObserver=l=>{if(l.local){for(const[a,c]of this.doc.share)if(a.startsWith("source:")&&(l.changed.has(c)||l.changedParentTypes.has(c))){this.markWritableDraft();return}}},this.doc.on("afterTransaction",this.localDraftTransactionObserver),this.persistence.on("synced",()=>{this.localDraftReady=!0;for(const l of this.draftListeners)l()}),this.provider=new ly(`${s}//${window.location.host}${fs("/api/collaboration")}`,e,this.doc,{connect:!1,disableBc:!0,maxBackoffTime:2500}),this.awareness=this.provider.awareness;const i=this.doc.getMap("texlite:meta");this.metaObserver=(l,a)=>{a.origin===this.provider&&l.keysChanged.has("compileStates")&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners())},i.observe(this.metaObserver),this.provider.messageHandlers[$a]=(l,a)=>{const c=ze(a),f=this.flushRequests.get(c);if(!f)return;const d=de(a)===1,h=de(a),m=ze(a),g=de(a),w=[];for(let v=0;v<g;v++)w.push(ze(a));if(window.clearTimeout(f.timer),this.flushRequests.delete(c),d)this.clearOwnWritableDraftMarker(f.draftGeneration),f.resolve({revision:h,persistedAt:m,ok:!0,failedPaths:[]});else{const v=Object.assign(new Error(w.length?`保存失败:${w.join(", ")}`:"源码保存到服务器磁盘失败"),{failedPaths:w});f.reject(v)}},this.provider.messageHandlers[Ia]=(l,a)=>{const c=ze(a),f=this.epochStorageKey(),d=Ua(f),h=/^([0-9]+):/.exec(c)?.[1]??null,m=d?/^([0-9]+):/.exec(d)?.[1]??null:null,g=!this.epoch&&h===String(qi)&&m!==null&&m!==h;if((this.epoch&&this.epoch!==c||d&&d!==c)&&!g){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed"));const B=c.endsWith(":reload")||h!==null&&h!==String(qi),A=()=>{Vi(f,c.replace(/:reload$/,"")),window.location.reload()};if(B)for(const b of this.protocolUpgradeListeners)b();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),A()});return}this.epoch=c,Vi(f,c);const w=this.provider.ws;if(!w||w.readyState!==WebSocket.OPEN)return;const v=Be();Y(v,Ia),rt(v,c),Y(v,qi),w.send(Me(v));const D=Be();Y(D,_y),Ir(D,this.doc),w.send(Me(D));const k=Be();Y(k,Ty),Ue(k,ts(this.awareness,[this.doc.clientID])),w.send(Me(k))},this.provider.messageHandlers[Ly]=(l,a)=>{const c=ze(a),f=ze(a);if(c!==this.user.id)return;if(f==="revoked"){this.rejectFlushes(new Error("Project access revoked")),this.provider.disconnect();for(const h of this.permissionListeners)h("revoked",this.permission);return}if(f!=="read"&&f!=="edit"&&f!=="owner")return;const d=this.permission;if(this.setPermission(f),d!==f){f==="read"&&this.rejectFlushes(new Error("Project permission changed to read-only"));for(const h of this.permissionListeners)h(f,d)}},this.provider.messageHandlers[Ry]=(l,a)=>{ze(a)},this.provider.messageHandlers[Ay]=(l,a)=>{let c={};try{c=Pa(JSON.parse(ze(a)))}catch{}this.authoritativeCompileStates=c,this.notifyCompileStateListeners()},this.provider.messageHandlers[Wi]=(l,a)=>{const c=ze(a),f=ze(a),d=ze(a),h=ze(a),m=ze(a),g=ze(a);if(c==="state"){const v=io(a)?ze(a):"",D=io(a)?ze(a):"",k=Number(m);if(!v||!Number.isFinite(k)||k<=Date.now())this.removeFormatLeaseState(d),this.notifyFormatLeaseListeners(null);else{const B={path:d,holderUserId:v,holderName:D,expiresAt:k};this.formatLeaseStatesByPath.set(d,B);const A=this.formatLeaseExpiryTimers.get(d);A!==void 0&&window.clearTimeout(A);const b=window.setTimeout(()=>{const O=this.formatLeaseStatesByPath.get(d);!O||O.expiresAt>Date.now()||(this.removeFormatLeaseState(d),this.notifyFormatLeaseListeners(null))},Math.max(0,k-Date.now())+25);this.formatLeaseExpiryTimers.set(d,b),this.notifyFormatLeaseListeners(B)}return}const w=this.formatLeaseRequests.get(f);w&&(window.clearTimeout(w.timer),this.formatLeaseRequests.delete(f),c==="denied"?w.reject(new Error(g||"Format lease request was denied")):w.resolve({status:c,filePath:d,token:h,expiresAt:Number(m)}))},this.provider.on("status",({status:l})=>{l==="disconnected"&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners(),this.rejectFlushes(new Error("Collaboration connection closed")),this.rejectFormatLeaseRequests(new Error("Collaboration connection closed")),this.clearFormatLeaseStates())}),this.updateLocalAwareness()}projectId;user;doc=new Fn;provider;awareness;persistence;permission="read";activeFile="";epoch=null;destroyed=!1;localDraftReady=!1;draftListeners=new Set;permissionListeners=new Set;protocolUpgradeListeners=new Set;compileStateListeners=new Set;flushRequests=new Map;formatLeaseRequests=new Map;formatLeaseListeners=new Set;formatLeaseStatesByPath=new Map;formatLeaseExpiryTimers=new Map;draftTabId;draftGeneration=0;draftUpdatedAt=0;draftMarkerPresent=!1;draftHeartbeatTimer=null;markDraftTabInactive;markDraftTabActive;undoManagers=new Map;authoritativeCompileStates=null;metaObserver;localDraftTransactionObserver;connect(){this.destroyed||(this.provider.connect(),this.updateLocalAwareness())}getText(e){return this.doc.getText(`source:${e}`)}getUndoManager(e){const n=this.undoManagers.get(e);if(n)return n;const s=new Jg(this.getText(e));return this.undoManagers.set(e,s),s}applyTextEdits(e,n){if(this.permission==="read")throw new Error("Read-only collaborators cannot edit source files");const s=this.getText(e);let r=0;for(const i of n){if(!Number.isInteger(i.from)||!Number.isInteger(i.to)||i.from<r||i.to<i.from||i.to>s.length)throw new RangeError("Invalid collaborative text edits");r=i.to}this.doc.transact(()=>{for(let i=n.length-1;i>=0;i-=1){const l=n[i];l.to>l.from&&s.delete(l.from,l.to-l.from),l.replacement&&s.insert(l.from,l.replacement)}})}get meta(){return this.doc.getMap("texlite:meta")}compileStates(){return this.authoritativeCompileStates??Pa(this.meta.get("compileStates"))}onCompileStates(e){return this.compileStateListeners.add(e),()=>this.compileStateListeners.delete(e)}get synced(){return this.provider.synced}get connected(){return this.provider.wsconnected}get draftReady(){return this.localDraftReady}get currentPermission(){return this.permission}onDraftReady(e){return this.draftListeners.add(e),this.localDraftReady&&e(),()=>this.draftListeners.delete(e)}onPermissionChanged(e){return this.permissionListeners.add(e),()=>this.permissionListeners.delete(e)}onProtocolUpgrade(e){return this.protocolUpgradeListeners.add(e),()=>this.protocolUpgradeListeners.delete(e)}async discardLocalDraft(){return this.hasOtherWritableDraft?!1:(await this.persistence.clearData(),this.localDraftReady=!1,this.clearWritableDraftMarkers(),!0)}get hasWritableDraft(){const e=this.readWritableDraftMarkers();return za(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){const e=this.readWritableDraftMarkers();return za(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).otherActive}setPermission(e,n=!1){const s=this.permission;if(this.permission=e,e==="read"&&(s!=="read"&&this.rejectFlushes(new Error("Project permission changed to read-only")),this.destroyUndoManagers(),this.clearFormatLeaseStates()),this.updateLocalAwareness(),n&&s!==e)for(const r of this.permissionListeners)r(e,s)}setActiveFile(e){this.activeFile!==e&&(this.activeFile=e,this.awareness.setLocalStateField("cursor",null),this.updateLocalAwareness())}sessions(){const e=[];return this.awareness.getStates().forEach((n,s)=>{const r=n?.user;!r||typeof r.id!="string"||typeof r.name!="string"||e.push({clientId:s,userId:r.id,username:typeof r.username=="string"?r.username:r.name,name:r.name,color:typeof r.color=="string"?r.color:"#1677c8",colorLight:typeof r.colorLight=="string"?r.colorLight:"#1677c833",permission:r.permission==="owner"||r.permission==="edit"?r.permission:"read",filePath:typeof n.filePath=="string"?n.filePath:"",editing:!!n.cursor,local:s===this.doc.clientID})}),e.sort((n,s)=>Number(s.local)-Number(n.local)||n.name.localeCompare(s.name))}flush(){const e=this.provider.ws;if(!this.provider.synced||!e||e.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Collaboration connection is unavailable"));const n=po(),s=this.draftGeneration,r=Be();return Y(r,$a),rt(r,n),new Promise((i,l)=>{const a=window.setTimeout(()=>{this.flushRequests.delete(n),l(new Error("Collaboration save timed out"))},5e3);this.flushRequests.set(n,{resolve:i,reject:l,timer:a,draftGeneration:s}),e.send(Me(r))})}onFormatLeaseState(e){this.formatLeaseListeners.add(e);for(const n of this.formatLeaseStatesByPath.values())e(n);return()=>this.formatLeaseListeners.delete(e)}formatLeaseStates(){const e=Date.now();for(const[n,s]of this.formatLeaseStatesByPath)s.expiresAt<=e&&this.removeFormatLeaseState(n);return[...this.formatLeaseStatesByPath.values()]}async acquireFormatLease(e){if(this.permission==="read")throw new Error("Formatting requires write permission");const n=await this.requestFormatLease("acquire",e);if(n.status!=="grant"||!n.token||!Number.isFinite(n.expiresAt))throw new Error("Format lease was not granted");let s=n.token,r=n.expiresAt,i=!1;const l=async()=>{if(i)throw new Error("Format lease has already been released");const c=await this.requestFormatLease("renew",e,s);if(c.status!=="renewed"||!Number.isFinite(c.expiresAt))throw new Error("Format lease renewal failed");s=c.token||s,r=c.expiresAt};return{path:e,get token(){return s},get expiresAt(){return r},confirm:l,renew:l,release:async()=>{if(i)return;i=!0;const c=this.provider.ws;if(!(!c||c.readyState!==WebSocket.OPEN))try{await this.requestFormatLease("release",e,s)}catch{}}}}reconnect(){this.destroyed||(this.rejectFlushes(new Error("Collaboration connection reset")),this.provider.disconnect(),this.provider.connect(),this.updateLocalAwareness())}destroy(){this.destroyed=!0,this.setOwnDraftActivity(!1),this.stopDraftHeartbeat(),window.removeEventListener("pagehide",this.markDraftTabInactive),window.removeEventListener("pageshow",this.markDraftTabActive),this.rejectFlushes(new Error("Collaboration connection closed")),this.provider.destroy(),this.persistence.destroy(),this.draftListeners.clear(),this.protocolUpgradeListeners.clear(),this.compileStateListeners.clear(),this.rejectFormatLeaseRequests(new Error("Collaboration connection closed")),this.clearFormatLeaseStates(),this.formatLeaseListeners.clear(),this.meta.unobserve(this.metaObserver),this.doc.off("afterTransaction",this.localDraftTransactionObserver),this.destroyUndoManagers(),this.doc.destroy()}destroyUndoManagers(){for(const e of this.undoManagers.values())e.destroy();this.undoManagers.clear()}notifyCompileStateListeners(){for(const e of this.compileStateListeners)e()}rejectFlushes(e){for(const n of this.flushRequests.values())window.clearTimeout(n.timer),n.reject(e);this.flushRequests.clear()}requestFormatLease(e,n,s=""){const r=this.provider.ws;if(!this.provider.synced||!r||r.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Collaboration connection is unavailable"));const i=po(),l=Be();return Y(l,Wi),rt(l,e),rt(l,i),rt(l,n),rt(l,s),new Promise((a,c)=>{const f=window.setTimeout(()=>{if(this.formatLeaseRequests.delete(i),e==="acquire"){const d=this.provider.ws;if(d?.readyState===WebSocket.OPEN){const h=Be();Y(h,Wi),rt(h,"cancel"),rt(h,i),rt(h,n),rt(h,""),d.send(Me(h))}}c(new Error("Format lease request timed out"))},e==="acquire"?Ny:5e3);this.formatLeaseRequests.set(i,{resolve:a,reject:c,timer:f}),r.send(Me(l))})}rejectFormatLeaseRequests(e){for(const n of this.formatLeaseRequests.values())window.clearTimeout(n.timer),n.reject(e);this.formatLeaseRequests.clear()}clearFormatLeaseStates(){for(const e of this.formatLeaseExpiryTimers.values())window.clearTimeout(e);this.formatLeaseExpiryTimers.clear(),this.formatLeaseStatesByPath.size&&(this.formatLeaseStatesByPath.clear(),this.notifyFormatLeaseListeners(null))}removeFormatLeaseState(e){const n=this.formatLeaseExpiryTimers.get(e);n!==void 0&&window.clearTimeout(n),this.formatLeaseExpiryTimers.delete(e),this.formatLeaseStatesByPath.delete(e)}notifyFormatLeaseListeners(e){for(const n of this.formatLeaseListeners)n(e)}updateLocalAwareness(){const[e,n]=Oa[Math.abs(this.doc.clientID)%Oa.length];this.awareness.setLocalStateField("user",{id:this.user.id,username:this.user.username,name:this.user.displayName,color:e,colorLight:n,permission:this.permission,sessionId:String(this.doc.clientID)}),this.awareness.setLocalStateField("filePath",this.activeFile)}epochStorageKey(){return Cn(`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`)}writableDraftStoragePrefix(){return`${Cn(`texlite:collaboration-writable:${this.user.id}:${this.projectId}`)}:`}ownWritableDraftStorageKey(){return`${this.writableDraftStoragePrefix()}${this.draftTabId}`}markWritableDraft(){this.draftGeneration+=1,this.draftUpdatedAt=Date.now(),this.draftMarkerPresent||this.writeOwnWritableDraftMarker(!0),this.startDraftHeartbeat()}clearWritableDraftMarkers(){for(const{key:e}of this.readWritableDraftMarkers())Ds(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),Ds(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){const n=this.readOwnWritableDraftMarker();!n||!Iy(n.generation,this.draftGeneration,e)||(Ds(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){const e=this.writableDraftStoragePrefix(),n=[];for(const s of zy()){if(!s.startsWith(e))continue;const r=this.readWritableDraftMarker(s);r&&n.push({key:s,tabId:s.slice(e.length),marker:r})}return n}readWritableDraftMarker(e){const n=Ua(e);if(!n)return null;try{const s=JSON.parse(n);if(!s||typeof s!="object"||Array.isArray(s))return null;const r=s,i=Date.now();if(!Number.isInteger(r.generation)||(r.generation??0)<0||typeof r.updatedAt!="number"||!Number.isFinite(r.updatedAt)||r.updatedAt<=0||i-r.updatedAt>Fy)return Ds(e),null;const l=typeof r.activeAt=="number"&&Number.isFinite(r.activeAt)?Math.max(0,r.activeAt):0;return{generation:r.generation,updatedAt:r.updatedAt,activeAt:l}}catch{return Ds(e),null}}writeOwnWritableDraftMarker(e){if(!this.draftMarkerPresent&&this.draftUpdatedAt<=0)return;const n={generation:this.draftGeneration,updatedAt:this.draftUpdatedAt||Date.now(),activeAt:e?Date.now():0};Vi(this.ownWritableDraftStorageKey(),JSON.stringify(n)),this.draftMarkerPresent=!0}setOwnDraftActivity(e){this.draftMarkerPresent&&(this.writeOwnWritableDraftMarker(e),e?this.startDraftHeartbeat():this.stopDraftHeartbeat())}resumeOwnDraftActivity(){const e=this.readOwnWritableDraftMarker();if(!e){this.draftMarkerPresent=!1,this.stopDraftHeartbeat();return}this.draftGeneration=Math.max(this.draftGeneration,e.generation),this.draftUpdatedAt=e.updatedAt,this.draftMarkerPresent=!0,this.setOwnDraftActivity(!0)}startDraftHeartbeat(){this.draftHeartbeatTimer!==null||!this.draftMarkerPresent||(this.draftHeartbeatTimer=window.setInterval(()=>{this.writeOwnWritableDraftMarker(!0)},My))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}}function Ua(t){try{return window.localStorage.getItem(t)}catch{return null}}function Vi(t,e){try{window.localStorage.setItem(t,e)}catch{}}function Ds(t){try{window.localStorage.removeItem(t)}catch{}}function zy(){try{const t=[];for(let e=0;e<window.localStorage.length;e+=1){const n=window.localStorage.key(e);n&&t.push(n)}return t}catch{return[]}}function Uy(t){try{return window.sessionStorage.getItem(t)}catch{return null}}function By(t,e){try{window.sessionStorage.setItem(t,e)}catch{}}function qy(t){const e=Uy(t);if(e)return e;const n=po();return By(t,n),n}function Wy(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function Vy(t){if(!t||typeof t!="object")return!1;const e=t;return(e.kind==="update"||e.kind==="move"||e.kind==="delete")&&typeof e.revision=="string"}function Hy(t,e,n,s,r,i){const[l]=u.useState(()=>new Py(t,e)),[a,c]=u.useState("connecting"),[f,d]=u.useState(!1),[h,m]=u.useState([]),[g,w]=u.useState(null),[v,D]=u.useState(null),[k,B]=u.useState(""),[A,b]=u.useState(!1),[O,S]=u.useState(""),[T,z]=u.useState(""),[Z,X]=u.useState([]),[ce,W]=u.useState(!1),[ge,Q]=u.useState(s),[I,ee]=u.useState(null),[we,K]=u.useState(!1),G=u.useRef(n),V=u.useRef(i),he=u.useRef(r);G.current=n,V.current=i,he.current=r,u.useEffect(()=>{const te=l.compileStates();w(te[n]??null)},[n,l]),u.useEffect(()=>{const te=()=>m(l.sessions()),H=()=>{d(!1),m([]),w(null),D(null),B(""),b(!1),S(""),z(""),X([]),V.current()},ve=({status:re})=>{c(re),re!=="connected"&&H()},De=re=>{d(re),re||H()},oe=()=>{c("disconnected"),H()},Ce=()=>{b(l.meta.get("historyWarning")===!0);const re=l.meta.get("filesEvent");Vy(re)&&D(re);const N=l.meta.get("commentsRevision");typeof N=="string"&&B(N);const q=l.meta.get("dictionaryRevision");typeof q=="string"&&S(q);const xe=l.meta.get("chktexSettingsRevision");typeof xe=="string"&&z(xe);const Re=l.compileStates();w(Re[G.current]??null)},Ae=()=>{const re=l.compileStates();w(re[G.current]??null)};l.awareness.on("change",te),l.provider.on("status",ve),l.provider.on("sync",De),l.provider.on("connection-close",oe),l.provider.on("connection-error",oe),l.meta.observe(Ce);const P=l.onCompileStates(Ae),_e=l.onProtocolUpgrade(()=>{K(!0),c("disconnected"),H()}),R=()=>X(l.formatLeaseStates()),be=l.onFormatLeaseState(R),Te=()=>{if(!he.current||l.currentPermission!=="read")return;const re=l.hasWritableDraft,N=l.hasOtherWritableDraft;!re&&!N||ee({previous:"edit",localDraftReady:re,otherTabDraft:N})},F=l.onDraftReady(()=>{W(!0),Te()}),je=l.onPermissionChanged((re,N)=>{if(re==="revoked"){c("disconnected"),d(!1),V.current();return}Q(re),re==="read"&&N!=="read"?ee({previous:N,localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):re!=="read"&&ee(null)});return te(),Ce(),c(l.connected?"connected":"connecting"),d(l.synced),()=>{l.awareness.off("change",te),l.provider.off("status",ve),l.provider.off("sync",De),l.provider.off("connection-close",oe),l.provider.off("connection-error",oe),l.meta.unobserve(Ce),P(),_e(),be(),F(),je(),l.destroy()}},[l]),u.useEffect(()=>{r&&l.connect()},[l,r]),u.useEffect(()=>{l.setPermission(s),Q(s),r&&s==="read"&&(l.hasWritableDraft||l.hasOtherWritableDraft)?ee({previous:"edit",localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):s!=="read"&&ee(null)},[l,s,r]);const se=I!==null;return u.useEffect(()=>{if(!se)return;const te=()=>{if(l.currentPermission!=="read")return;const ve=l.hasWritableDraft,De=l.hasOtherWritableDraft;ee(oe=>!oe||oe.localDraftReady===ve&&oe.otherTabDraft===De?oe:{...oe,localDraftReady:ve,otherTabDraft:De})};te();const H=window.setInterval(te,2e3);return()=>window.clearInterval(H)},[l,se]),{collaboration:l,status:a,synced:f,activeSessions:h,compileState:g,setCompileState:w,formatLeaseStates:Z,filesEvent:v,commentsRevision:k,historyWarning:A,dictionaryRevision:O,chktexSettingsRevision:T,localDraftReady:ce,permission:ge,protocolUpgradeRequired:we,reconnect:()=>{we||(c("connecting"),d(!1),m([]),w(null),X([]),l.reconnect())},permissionDowngrade:I,dismissPermissionDowngrade:()=>ee(null),discardLocalDraft:async()=>await l.discardLocalDraft()?(ee(null),window.location.reload(),!0):(ee(H=>H&&{...H,otherTabDraft:!0}),!1)}}function Ba(t){return t?.status==="succeeded"?"succeeded":t?.log.includes("Compilation was cancelled.")?"cancelled":t?.status==="failed"?"failed":null}function xn(t){return t instanceof Error&&t.name==="AbortError"}function Ky(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}function Gy(t){return t instanceof Element&&!!t.closest('[role="dialog"], [role="alertdialog"]')}function Jy({projectId:t,project:e,mainFile:n,resolveCompileMainFile:s,getCurrentMainFile:r,initialLatest:i,collaborationSynced:l,sharedState:a,onSharedState:c,save:f,loadOutline:d,onPreviewTab:h,onError:m,onCompileStart:g,onCompileSuccess:w,onPdfChanged:v}){const{t:D}=et(),[k,B]=u.useState(""),[A,b]=u.useState(!0),[O,S]=u.useState(null),[T,z]=u.useState(null),[Z,X]=u.useState("full"),[ce,W]=u.useState(""),[ge,Q]=u.useState(null),[I,ee]=u.useState(null),[we,K]=u.useState([]),[G,V]=u.useState(null),[he,se]=u.useState(!1),[ie,C]=u.useState(!1),[fe,te]=u.useState(()=>new Set),[H,ve]=u.useState(()=>new Set),[De,oe]=u.useState(""),[Ce,Ae]=u.useState({projectId:t,mainFile:n}),P=u.useRef(n),_e=u.useRef(""),R=u.useRef(""),be=u.useRef({projectId:t,mainFile:n}),Te=u.useRef(!0),F=u.useRef(null),je=u.useRef(null),re=u.useRef(null),N=u.useRef(i),q=u.useRef(!1),xe=u.useRef(null),Re=u.useRef(null),L=u.useRef(new Set),Ne=u.useRef(new Map),mt=u.useRef(null),Lt=u.useRef(()=>{}),ke=u.useRef({onSharedState:c,save:f,loadOutline:d,onPreviewTab:h,onError:m,onCompileStart:g,onCompileSuccess:w,onPdfChanged:v,resolveCompileMainFile:s,getCurrentMainFile:r});P.current=n,ke.current={onSharedState:c,save:f,loadOutline:d,onPreviewTab:h,onError:m,onCompileStart:g,onCompileSuccess:w,onPdfChanged:v,resolveCompileMainFile:s,getCurrentMainFile:r};const M=()=>ke.current.getCurrentMainFile?.()||P.current,U=Ce.projectId===t&&Ce.mainFile===n,Ee=$=>{mt.current!==$&&(mt.current=$,ke.current.onCompileSuccess())},We=($,J,x,j,nt)=>{(R.current!==J||_e.current!==$)&&ke.current.onPdfChanged(),R.current=J,_e.current=$,B(J),S(x),z(j),X(nt??"full")},Pe=async($,J)=>{J||(xe.current?.abort(),xe.current=new AbortController,J=xe.current.signal);try{const x=$?`?mainFile=${encodeURIComponent($)}`:"",j=await me(`/api/projects/${t}/compile/artifacts${x}`,{signal:J});P.current===$&&(K(j.artifacts),V(null))}catch(x){!xn(x)&&P.current===$&&(K([]),V(null))}finally{xe.current?.signal===J&&(xe.current=null)}};u.useEffect(()=>{F.current?.abort(),F.current=null;const $=be.current,J=$.projectId===t,x=J&&!!$.mainFile&&!!n&&$.mainFile!==n;if(be.current={projectId:t,mainFile:n},Ae(Se=>Se.projectId===t&&Se.mainFile===n?Se:{projectId:t,mainFile:n}),J||(N.current=i,q.current=!1,re.current=null,_e.current="",R.current=""),!n){b(!1),R.current="",B(""),S(null),z(null),X("full"),W(""),Q(null),ee(null),K([]),V(null),se(!1),oe(""),re.current=null,ke.current.onPdfChanged();return}if(re.current?.mainFile!==n&&(re.current=null),W(""),Q(null),ee(null),x){Te.current=!1,je.current?.abort(),xe.current?.abort(),Re.current?.abort(),_e.current="",R.current="",B(""),S(null),z(null),X("full"),b(!1),K([]),V(null),se(!1),oe(""),ke.current.onPdfChanged(),ke.current.onPreviewTab("pdf");const Se=new AbortController;return ke.current.loadOutline(Se.signal,n).catch(()=>{}),()=>Se.abort()}Te.current=!0;const j=new AbortController;F.current=j,b(!0),J&&k&&n&&_e.current===n||(R.current="",B(""),S(null),z(null),X("full")),K([]),V(null),ke.current.onPdfChanged();let Ye=null;const zt=`?mainFile=${encodeURIComponent(n)}`,Ut=q.current?null:N.current;Ut&&(q.current=!0);const hn=()=>me(`/api/projects/${t}/compile/latest${zt}`,{signal:j.signal}),$n=Ut?Ut.then(Se=>Se.mainFile!==n?hn():Se,()=>hn()):hn();let gt=!1;const bs=()=>{if(gt||j.signal.aborted||!n)return;gt=!0;const Se=new AbortController;L.current.add(Se),Pe(n,Se.signal).finally(()=>{L.current.delete(Se)}),ke.current.loadOutline(j.signal,n).catch(()=>{})};return $n.then(Se=>{if(j.signal.aborted||n&&Se.mainFile!==P.current)return;const xs=re.current;xs&&xs.mainFile===n&&Se.latestRun?.id!==xs.runId||(W(Se.latestRun?.log??""),Q(Se.latestRun?.diagnostics??null),ee(Ba(Se.latestRun)),n&&Se.latestRun?.requestedBy&&(Se.latestRun.status==="queued"||Se.latestRun.status==="running")&&ke.current.onSharedState({mainFile:n,runId:Se.latestRun.id,status:Se.latestRun.status,requestedBy:Se.latestRun.requestedBy,updatedAt:new Date().toISOString()}),Se.pdfUrl&&(We(Se.mainFile,Se.pdfUrl,Se.pdfCompiledAt,Se.pdfSizeBytes,Se.pdfLoadingMode),ke.current.onPreviewTab("pdf")))}).catch(Se=>{!xn(Se)&&P.current===n&&ke.current.onError(pe(Se))}).finally(()=>{F.current===j&&(F.current=null),j.signal.aborted||(b(!1),Ye=window.setTimeout(bs,0))}),()=>{Ye!==null&&window.clearTimeout(Ye),j.abort(),Re.current?.abort();for(const Se of L.current)Se.abort();L.current.clear()}},[t,n]),u.useEffect(()=>{if(!(!a||a.mainFile!==n||a.status!=="cleaned"||!a.cleanMode)){F.current?.abort(),je.current?.abort(),xe.current?.abort(),Re.current?.abort();for(const $ of L.current)$.abort();L.current.clear(),a.cleanMode==="artifacts"?(re.current=null,W(""),Q(null),ee(null),R.current="",B(""),S(null),z(null),X("full"),K([]),V(null),ke.current.onPdfChanged(),ke.current.onPreviewTab("pdf"),oe(D("editor.cleanArtifactsComplete"))):oe(D("editor.cleanCacheComplete"))}},[a?.runId,a?.status,a?.cleanMode,a?.mainFile,n,D]),u.useEffect(()=>{!n||a?.mainFile===n&&(a.status==="queued"||a.status==="running")||ve($=>{if(!$.has(n))return $;const J=new Set($);return J.delete(n),J})},[n,a?.mainFile,a?.status]),u.useEffect(()=>{a?.mainFile===n&&(a.status==="queued"||a.status==="running")&&(Te.current=!0)},[n,a?.mainFile,a?.status,a?.runId]),u.useEffect(()=>{if(!a||a.mainFile!==n||a.status!=="succeeded"&&a.status!=="failed"||!Te.current)return;let $=!1;je.current?.abort(),Re.current?.abort();const J=new AbortController;return je.current=J,b(!0),me(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:J.signal}).then(x=>{$||x.mainFile!==P.current||x.latestRun?.id!==a.runId||(W(x.latestRun.log),Q(x.latestRun.diagnostics),ee(Ba(x.latestRun)),a.status==="succeeded"&&a.stale&&oe(D("editor.compileSnapshotStale")),a.status==="succeeded"&&x.pdfUrl?(re.current={mainFile:n,runId:a.runId},We(n,x.pdfUrl,x.pdfCompiledAt,x.pdfSizeBytes,x.pdfLoadingMode),ke.current.onPreviewTab("pdf"),Ee(a.runId),Pe(n)):a.status==="failed"&&ke.current.onPreviewTab(x.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(x=>{!xn(x)&&!$&&ke.current.onError(pe(x))}).finally(()=>{je.current===J&&(je.current=null),$||b(!1)}),()=>{$=!0,J.abort(),je.current===J&&(je.current=null)}},[a?.runId,a?.status,a?.mainFile,a?.stale,n,t,D]);const Je=async()=>{if(!e||e.permission==="read"||!l)return;const $=ke.current.resolveCompileMainFile?.()||M();if(!$||Ne.current.has($)||a?.mainFile===$&&(a.status==="queued"||a.status==="running"))return;te(x=>new Set([...x,$])),ke.current.onCompileStart(),oe(""),Re.current?.abort(),Re.current=null,W(""),Q(null),ee(null),ke.current.onPreviewTab(U&&k?"pdf":"log");const J=new AbortController;Ne.current.set($,J);try{if(!await ke.current.save())return;Te.current=!0;const x=await me(`/api/projects/${t}/compile`,{method:"POST",signal:J.signal,body:JSON.stringify({mainFile:$})});if(x.mainFile!==$||M()!==$)return;W(x.log),Q(x.diagnostics),ee(x.cancelled?"cancelled":x.ok?"succeeded":"failed"),x.cancelled&&oe(D("compileControls.cancelled")),x.skipped&&oe(D("editor.upToDate")),x.ok&&x.stale&&oe(D("editor.compileSnapshotStale")),x.pdfUrl?(x.ok&&(re.current={mainFile:$,runId:x.runId}),We($,x.pdfUrl,x.pdfCompiledAt,x.pdfSizeBytes,x.pdfLoadingMode),ke.current.onPreviewTab("pdf"),x.ok&&(x.skipped?ke.current.onCompileSuccess():Ee(x.runId))):ke.current.onPreviewTab(x.diagnostics.errors.length?"errors":"log")}catch(x){!xn(x)&&M()===$&&ke.current.onError(pe(x))}finally{Ne.current.get($)===J&&(Ne.current.delete($),te(x=>{const j=new Set(x);return j.delete($),j}),ve(x=>{if(!x.has($))return x;const j=new Set(x);return j.delete($),j}))}},ct=async()=>{if(!e||e.permission==="read"||!l)return;const $=M();if($){ve(J=>new Set([...J,$]));try{(await me(`/api/projects/${t}/compile/cancel`,{method:"POST",body:JSON.stringify({mainFile:$})})).cancelled||ve(x=>{const j=new Set(x);return j.delete($),j})}catch(J){ve(x=>{const j=new Set(x);return j.delete($),j}),!xn(J)&&M()===$&&ke.current.onError(pe(J))}}},ue=async $=>{if(!e||e.permission==="read"||!l||ie)return;const J=M();if(!(!J||Ne.current.has(J)||a?.mainFile===J&&(a.status==="queued"||a.status==="running"))){C(!0),F.current?.abort(),je.current?.abort(),xe.current?.abort(),Re.current?.abort();try{if((await me(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:J,mode:$})})).mainFile!==J||M()!==J)return;ke.current.onSharedState(null),$==="artifacts"&&(re.current=null,W(""),Q(null),ee(null),R.current="",B(""),S(null),z(null),X("full"),K([]),V(null),ke.current.onPdfChanged()),oe(D($==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(x){!xn(x)&&M()===J&&ke.current.onError(pe(x))}finally{C(!1)}}};Lt.current=()=>{Je()},u.useEffect(()=>{if(!De)return;const $=window.setTimeout(()=>oe(""),3e3);return()=>window.clearTimeout($)},[De]),u.useEffect(()=>{const $=J=>{if(!(!(J.ctrlKey||J.metaKey)||J.key.toLocaleLowerCase()!=="s")){if(Ky(J.target)||Gy(J.target)){J.preventDefault();return}J.preventDefault(),J.stopPropagation(),J.repeat||Lt.current()}};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[]),u.useEffect(()=>()=>{F.current?.abort(),je.current?.abort(),xe.current?.abort(),Re.current?.abort();for(const $ of L.current)$.abort();L.current.clear();for(const $ of Ne.current.values())$.abort();Ne.current.clear()},[]);const vt=async $=>{if(!$.viewable)return;Re.current?.abort();const J=new AbortController;Re.current=J,se(!0);try{const x=await me(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent($.path)}`,{signal:J.signal});!J.signal.aborted&&Re.current===J&&P.current===n&&V(x)}catch(x){xn(x)||ke.current.onError(pe(x))}finally{Re.current===J&&(Re.current=null,se(!1))}};return{pdfUrl:U?k:"",pdfCompiledAt:U?O:null,pdfSizeBytes:U?T:null,pdfLoadingMode:Z,pdfLoading:U?A:!1,compileLog:U?ce:"",compileDiagnostics:U?ge:null,compileOutcome:U?I:null,artifacts:U?we:[],artifactPreview:U?G:null,artifactLoading:U&&he,editorNotice:U?De:"",localCompiling:fe.has(n),cancelling:H.has(n),cleaning:ie,compile:Je,cancelCompile:ct,cleanCompile:ue,viewArtifact:vt}}const wo=10*1024*1024,Yy=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".bmp",".ico",".avif",".pdf",".zip",".gz",".bz2",".xz",".tar",".rar",".7z",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".odt",".ods",".odp",".mp3",".mp4",".wav",".ogg",".webm",".mov",".avi",".wasm",".exe",".bin",".so",".dll",".class",".jar"]);function qa(t){return t instanceof Error&&t.name==="AbortError"}function En(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function kn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function Xy(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!Yy.has(e)}function ss(t){return/(?:\.(?:tex|bib|bst|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function Wa(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":Xy(t)?"text":"unsupported"}function Zy(t,e){return fs(`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`)}function Qy({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:l,onActiveFile:a,onActiveMainFile:c}){const{t:f}=et(),[d,h]=u.useState([]),[m,g]=u.useState(!1),[w,v]=u.useState(""),[D,k]=u.useState(null),[B,A]=u.useState(!1),[b,O]=u.useState(!1),[S,T]=u.useState(""),[z,Z]=u.useState(""),[X,ce]=u.useState(null),[W,ge]=u.useState(""),[Q,I]=u.useState(new Set),[ee,we]=u.useState(null),[K,G]=u.useState(""),[V,he]=u.useState(""),[se,ie]=u.useState(null),[C,fe]=u.useState(!1),[te,H]=u.useState(null),[ve,De]=u.useState(!1),[oe,Ce]=u.useState(null),Ae=u.useRef(!1),P=u.useRef(null),_e=u.useRef(null),R=u.useRef(null),be=async(M={})=>{_e.current?.abort(),_e.current=null;const U=M.signal?null:new AbortController;U&&(_e.current=U);try{const Ee=await me(`/api/projects/${t}/files`,{signal:M.signal??U?.signal});return(!M.isCurrent||M.isCurrent())&&h(Ee.files),Ee.files}catch(Ee){if(!qa(Ee))throw Ee;return}finally{U&&_e.current===U&&(_e.current=null)}},Te=async()=>{if(!(!w.trim()||w.trim().endsWith("/"))){Z("");try{await me(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:w,content:""})}),await be(),a(w),ce(null),I(M=>new Set([...M,...En(w)])),g(!1),v("")}catch(M){Z(pe(M))}}},F=async()=>{if(!S.trim())return;Z("");const M=X?`${X}/${S.trim()}`:S.trim();try{const U=await me(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:M})});await be(),I(Ee=>new Set([...Ee,...En(U.path),U.path])),ce(U.path),O(!1),T("")}catch(U){Z(pe(U))}},je=async(M,U=new Set,Ee=X)=>{if(!M.length||Ae.current)return;const We=e.maxUploadSizeMB;if(M.find(j=>j.size>We*1024*1024)){Ce({kind:"error",message:f("errors.fileTooLarge",{size:We})});return}const Je=Ee??"",ct=M.map(j=>Je?`${Je}/${j.name}`:j.name),ue=new Map;for(const j of ct)ue.set(j,(ue.get(j)??0)+1);const vt=[...ue.entries()].filter(([,j])=>j>1).map(([j])=>j);if(vt.length){Ce({kind:"error",message:f("errors.duplicateUploadNames",{files:vt.join(", ")})});return}const $=new Set(d.map(j=>j.path)),J=[...new Set(ct.filter(j=>$.has(j)&&!U.has(j)))];if(J.length){Ce(null),H({files:M,directory:Je,collisions:J});return}H(null),P.current!==null&&window.clearTimeout(P.current),P.current=null,Ce(null),Ae.current=!0,De(!0);let x=0;try{const j=new URLSearchParams;Je&&j.set("directory",Je);let nt="";for(const[Ye,zt]of M.entries()){const Ut=ct[Ye];j.delete("overwrite"),U.has(Ut)&&j.set("overwrite","1");const hn=j.toString()?`?${j.toString()}`:"",$n=new FormData;$n.append("file",zt);try{Ce({kind:"uploading",fileName:zt.name,current:Ye+1,total:M.length});const gt=await me(`/api/projects/${t}/upload${hn}`,{method:"POST",body:$n});x+=1,typeof gt.path=="string"&&ss(gt.path)&&(nt=gt.path)}catch(gt){if(gt instanceof Ji&>.status===409&&!U.has(Ut)&>.code==="FILE_EXISTS"){if(Ce(null),Ye>0)try{await be()}catch{}H({files:M.slice(Ye),directory:Je,collisions:[Ut]});return}throw gt}}try{await be()}catch(Ye){Ce({kind:"error",message:f("editor.uploadSucceededRefreshFailed",{message:pe(Ye)})});return}nt&&(a(nt),ce(null)),Ce({kind:"success",count:x}),P.current=window.setTimeout(()=>{Ce(Ye=>Ye?.kind==="success"?null:Ye),P.current=null},3e3)}catch(j){try{await be()}catch{}const nt=x>0?f("editor.uploadFailedPartial",{uploaded:x,total:M.length,message:pe(j)}):f("editor.uploadFailed",{message:pe(j)});Ce({kind:"error",message:nt})}finally{Ae.current=!1,De(!1)}},re=()=>{P.current!==null&&window.clearTimeout(P.current),P.current=null,Ce(null)},N=async M=>{await je(Array.from(M.target.files??[])),M.target.value=""},q=async M=>{R.current?.abort(),R.current=null,A(!1);const U=Zy(t,M.path);if((M.size??0)>wo){k({path:M.path,kind:"large",size:M.size??0,url:U});return}const Ee=Wa(M.path);if(Ee!=="text"){k({path:M.path,kind:Ee,size:M.size??0,url:U});return}k({path:M.path,kind:Ee,size:M.size??0,url:U,content:""}),A(!0);const We=new AbortController;R.current=We;try{let Pe;try{Pe=await fetch(U,{signal:We.signal})}catch(ue){throw Xh(ue)}const Je=Pe.headers.get("content-type")??"";if(!Pe.ok){let ue=null;try{ue=Je.includes("application/json")?await Pe.json():await Pe.text()}catch{}throw new Ji(Zh(ue,Pe.status),Pe.status,Qh(ue))}const ct=await Pe.text();k(ue=>ue?.path===M.path?{...ue,content:ct}:ue)}catch(Pe){qa(Pe)||(k(null),i(pe(Pe)))}finally{R.current===We&&(R.current=null,A(!1))}},xe=M=>{ce(null),ge(M.path);const U=Wa(M.path),Ee=e.maxCollaborativeFileSizeMB*1024*1024;(M.size??0)>wo||ss(M.path)&&(M.size??0)>Ee||U!=="text"||!ss(M.path)?q(M):a(M.path)},Re=async(M,U,Ee)=>{if(!await r())return null;const We=await me(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:M.path,destinationDirectory:U,destinationName:Ee})}),Pe=ue=>ue===M.path?We.path:ue.startsWith(`${M.path}/`)?`${We.path}${ue.slice(M.path.length)}`:ue;a(ue=>Pe(ue)),c(ue=>Pe(ue)),ce(ue=>ue&&Pe(ue)),ge(ue=>ue&&Pe(ue));const[Je,ct]=await Promise.all([me(`/api/projects/${t}/files`),me(`/api/projects/${t}`)]);return h(Je.files),l(ct.project),I(ue=>new Set([...ue,...En(We.path),U].filter(Boolean))),We.path},L=async()=>{if(!ee)return;const M=K.trim();if(M){Z("");try{if(!await Re(ee,V,M))return;we(null),G(""),he("")}catch(U){Z(pe(U))}}},Ne=async(M,U)=>{if(eb(M.path)!==U&&!(M.type==="directory"&&(U===M.path||U.startsWith(`${M.path}/`))))try{await Re(M,U,M.path.split("/").at(-1)??M.path)}catch(Ee){i(pe(Ee))}},mt=async()=>{if(se){Z("");try{if(s&&!await r())return;await me(`/api/projects/${t}/file?path=${encodeURIComponent(se.path)}`,{method:"DELETE"}),ie(null)}catch(M){Z(pe(M))}}};u.useEffect(()=>()=>{_e.current?.abort(),R.current?.abort(),P.current!==null&&window.clearTimeout(P.current)},[]),u.useEffect(()=>{R.current?.abort(),R.current=null,A(!1)},[n]),u.useEffect(()=>{n&&ge(n)},[n]);const Lt=d.filter(M=>M.type==="directory"),ke=d.filter(M=>En(M.path).every(U=>Q.has(U)));return{files:d,setFiles:h,loadFiles:be,newFileOpen:m,setNewFileOpen:g,newFilePath:w,setNewFilePath:v,resourcePreview:D,setResourcePreview:k,resourcePreviewLoading:B,setResourcePreviewLoading:A,newFolderOpen:b,setNewFolderOpen:O,newFolderName:S,setNewFolderName:T,fileDialogError:z,setFileDialogError:Z,selectedFolder:X,setSelectedFolder:ce,selectedFile:W,setSelectedFile:ge,expandedFolders:Q,setExpandedFolders:I,moveEntry:ee,setMoveEntry:we,moveName:K,setMoveName:G,moveDestination:V,setMoveDestination:he,deleteEntry:se,setDeleteEntry:ie,fileDragActive:C,setFileDragActive:fe,uploadConflict:te,setUploadConflict:H,uploadingFiles:ve,uploadFeedback:oe,dismissUploadFeedback:re,directoryEntries:Lt,visibleEntries:ke,createFile:Te,createFolder:F,uploadFiles:je,upload:N,openFile:xe,movePath:L,movePathToFolder:Ne,removePath:mt}}function eb(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function tb({active:t,harperEnabled:e=!0,projectId:n,activeFile:s,content:r,dictionaryWords:i,additionalIssues:l=[],additionalIssuesReady:a=!0}){const[c,f]=u.useState([]),[d,h]=u.useState(""),[m,g]=u.useState(""),[w,v]=u.useState(0),[D,k]=u.useState(null),[B,A]=u.useState(null),[b,O]=u.useState(!1),[S,T]=u.useState(0),z=u.useRef(0),Z=u.useRef(!1),X=u.useRef(!1),ce=u.useRef(r),W=u.useRef(s),ge=u.useRef(0);ce.current=r,W.current=s,X.current=b,u.useEffect(()=>{f([]),h(""),g(""),k(null),A(null),O(!1)},[s,i,e]),u.useEffect(()=>{A(null),O(!1)},[n]),u.useEffect(()=>{const K=++z.current;if(!t||!s){f([]),h(""),g(""),k(null);return}if(!e){f([]),h(""),g("");return}if(B){f([]),h(""),g("");return}const G=r,V=s;let he=!1;const se=window.setTimeout(()=>{A(null),(async()=>{try{const{lintLatex:ie,isHarperLintSupersededError:C}=await Ct(async()=>{const{lintLatex:te,isHarperLintSupersededError:H}=await import("./spellCheck-C-bNJsIU.js");return{lintLatex:te,isHarperLintSupersededError:H}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url);if(he||K!==z.current||ce.current!==G||W.current!==V)return;let fe;try{fe=await ie(n,V,G,i)}catch(te){if(C(te))return;throw te}if(he||K!==z.current||ce.current!==G||W.current!==V)return;Z.current=!1,O(!1),f(fe),h(G),g(V),v(0),k(null)}catch(ie){if(he||K!==z.current||ce.current!==G||W.current!==V)return;f([]),h(""),g(""),A(ie instanceof Error?ie.message:String(ie));const C=Z.current;Z.current=!1,O(C?X.current:!1)}})()},700);return()=>{he=!0,window.clearTimeout(se)}},[t,e,n,s,r,i,S,B]),u.useEffect(()=>{if(!B||!t||!e)return;let K=!1;const G=()=>{K||(K=!0,Z.current=!0,A(null),T(he=>he+1))},V=window.setTimeout(G,15e3);return window.addEventListener("online",G,{once:!0}),()=>{window.clearTimeout(V),window.removeEventListener("online",G)}},[B,t,e]);const Q=e&&t&&m===s&&d===r,I=u.useMemo(()=>{if(!t)return[];const K=[...Q?c:[],...l].sort((V,he)=>V.from-he.from||V.to-he.to),G=new Set;return K.filter(V=>{const he=`${V.from}:${V.to}:${V.kind}:${V.message}`;return G.has(he)?!1:(G.add(he),!0)})},[t,l,Q,c]),ee=u.useMemo(()=>t&&(!e||Q)&&a?{total:I.length,unique:new Set(I.map(K=>`${K.kind}:${K.word.toLocaleLowerCase("en-US")}`)).size}:null,[t,a,e,Q,I]);return u.useEffect(()=>{v(K=>I.length?Math.min(K,I.length-1):0)},[I]),{issues:I,jump:t?D:null,index:w,summary:ee,jumpToIssue:K=>{if(!I.length)return;const G=Math.max(0,Math.min(K,I.length-1)),V=I[G];v(G),k({from:V.from,to:V.to,nonce:++ge.current})},error:t&&e&&!b?B:null,nativeFallback:t&&e&&!!B,retry:()=>{Z.current=!1,A(null),O(!1),T(K=>K+1)},dismissError:()=>{Z.current=!1,O(!0)}}}function nb({active:t,projectId:e,activeFile:n,content:s}){const[r,i]=u.useState([]),[l,a]=u.useState(""),[c,f]=u.useState(""),[d,h]=u.useState(null),[m,g]=u.useState(!1),[w,v]=u.useState(0),D=u.useRef(0),k=u.useRef(s),B=u.useRef(n);k.current=s,B.current=n,u.useEffect(()=>{i([]),a(""),f(""),h(null),g(!1)},[e,n]),u.useEffect(()=>{const b=++D.current;if(!t||!n){i([]),a(""),f("");return}const O=s,S=n;let T=!1;const z=window.setTimeout(()=>{(async()=>{try{const{lintChktex:Z,isChktexLintSupersededError:X}=await Ct(async()=>{const{lintChktex:W,isChktexLintSupersededError:ge}=await import("./chktex-tM1XXPk2.js");return{lintChktex:W,isChktexLintSupersededError:ge}},__vite__mapDeps([9,1,2,3,4,5,6,7,8]),import.meta.url);if(T||b!==D.current||k.current!==O||B.current!==S)return;let ce;try{ce=await Z(e,S,O)}catch(W){if(X(W))return;throw W}if(T||b!==D.current||k.current!==O||B.current!==S)return;i(ce),a(O),f(S),h(null),g(!1)}catch(Z){if(T||b!==D.current||k.current!==O||B.current!==S)return;i([]),a(""),f(""),h(Z instanceof Error?Z.message:String(Z))}})()},2e3);return()=>{T=!0,window.clearTimeout(z)}},[t,e,n,s,w]);const A=t&&c===n&&l===s;return{issues:A?r:[],checked:A,error:t&&!m?d:null,retry:()=>{h(null),g(!1),v(b=>b+1)},dismissError:()=>g(!0)}}function Va(t){return t instanceof Error&&t.name==="AbortError"}function sb({projectId:t,mainFile:e,activeFile:n,onOpenSourceFile:s,onError:r,onShowPdf:i,onShowEditor:l}){const[a,c]=u.useState(null),[f,d]=u.useState(null),[h,m]=u.useState(null),g=u.useRef(null),w=u.useRef(0),v=u.useRef(n),D=u.useRef(s),k=u.useRef(r),B=u.useRef(i),A=u.useRef(l),b=X=>X===e&&/\.tex$/i.test(X);v.current=n,D.current=s,k.current=r,B.current=i,A.current=l,u.useEffect(()=>(g.current?.abort(),g.current=null,c(null),d(null),m(null),()=>g.current?.abort()),[t,e]);const O=(X,ce,W)=>{m({path:X,line:ce,column:W,nonce:++w.current}),D.current(X)},S=async(X,ce,W,ge={})=>{if(!b(X))return;g.current?.abort();const Q=new AbortController;g.current=Q;try{const I=await me(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(X)}&line=${ce}&column=${W}`,{signal:Q.signal});if(g.current!==Q||!I)return;c({...I,nonce:++w.current}),B.current()}catch(I){!Va(I)&&!ge.silent&&k.current(pe(I))}finally{g.current===Q&&(g.current=null)}},T=async(X,ce,W)=>{const ge=v.current;g.current?.abort();const Q=new AbortController;g.current=Q;try{const I=await me(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${X}&x=${ce}&y=${W}`,{signal:Q.signal});if(g.current!==Q||v.current!==ge)return;A.current(),O(I.path,I.line,I.column)}catch(I){Va(I)||k.current(pe(I))}finally{g.current===Q&&(g.current=null)}};return{pdfTarget:a,pdfViewport:f,sourceJump:h,setPdfViewport:d,resetPdfViewport:()=>d(null),clearPdfViewport:()=>{g.current?.abort(),g.current=null,d(null),c(null)},jumpToSource:O,syncSourceToPdf:S,syncPdfToSource:T,syncVisiblePdfToSource:()=>{f&&T(f.page,f.x,f.y)}}}function Hu(t,e){return Cn(`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function Ha(t,e){try{const n=window.localStorage.getItem(Hu(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function rb(t,e){const[n,s]=u.useState(()=>Ha(t,e));return u.useEffect(()=>{s(Ha(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Hu(t,e),i)}catch{}}}}function ib(t){return!/\.(?:bib|bst)$/i.test(t.trim())}function Ka(t){return/\.(?:tex|sty|cls)$/i.test(t.trim())}const Ku=["verbatim","verbatim*","Verbatim","BVerbatim","LVerbatim","SaveVerbatim","VerbatimOut","bverbatim","bverbatim*","lverbatim","lverbatim*","saveverbatim","saveverbatim*","verbatimout","verbatimwrite","lstlisting","lstlisting*","minted","minted*","tcblisting","tcblisting*","pygmented","alltt","filecontents","filecontents*","luacode","luacodestar","comment"],ob=new Set(Ku);function lb(t){return ob.has(t)}function ab(t,e,n){if(t[e]!=="[")return e;let s=1;for(let r=e+1;r<n;r+=1){if(t[r]==="\\"){r+=1;continue}if(t[r]==="["&&(s+=1),t[r]==="]"&&(s-=1,s===0))return r+1}return null}function Ga(t,e,n){if(t[e]!=="{")return null;let s=1;for(let r=e+1;r<n;r+=1){if(t[r]==="\\"){r+=1;continue}if(t[r]==="{"&&(s+=1),t[r]==="}"&&(s-=1,s===0))return r+1}return null}function Gu(t,e,n=t.length){const s=t.indexOf(`
|
|
11
|
-
`,e);s>=0&&(n=Math.min(n,s));const r=/^\\(verb\*?|Verb\*?|lstinline\*?|mintinline\*?)(?![A-Za-z@])/.exec(t.slice(e,n));if(!r)return null;const i=r[1].replace(/\*$/,"");let l=e+r[0].length;if(i!=="verb"){const f=ab(t,l,n);if(f===null)return null;l=f}if(i==="mintinline"){const f=Ga(t,l,n);if(f===null)return null;l=f}const a=t[l];if(!a||/\s/.test(a))return null;if(a==="{"&&i!=="verb"){const f=Ga(t,l,n);return{end:f??n,closed:f!==null}}const c=t.indexOf(a,l+1);return c<0||c>=n?{end:n,closed:!1}:{end:c+1,closed:!0}}function Ju(t,e,n=t.length){return Gu(t,e,n)?.end??null}function il(t,e,n){const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(String.raw`\\end\s*\{\s*${s}\s*\}`,"g");r.lastIndex=e;const i=r.exec(t);return i?{from:i.index,to:i.index+i[0].length}:null}function Ws(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function cb(t,e){let n=e+1;if(/[A-Za-z@]/.test(t[n]??"")){for(;/[A-Za-z@]/.test(t[n]??"");)n+=1;return t[n]==="*"&&(n+=1),n}return Math.min(t.length,n+1)}function Yu(t,e){const n=/^\\begin\s*\{\s*([A-Za-z0-9@:_*.\-]+)\s*\}/.exec(t.slice(e));return!n||!lb(n[1])?null:{name:n[1],to:e+n[0].length}}function Nx(t,e){const n=Math.max(0,Math.min(t.length,e));for(let s=0;s<n;){if(t[s]==="%"&&!Ws(t,s)){const l=t.indexOf(`
|
|
12
|
-
`,s),a=l<0?t.length:l;if(n<=a)return"comment";s=a+1;continue}if(t[s]!=="\\"||Ws(t,s)){s+=1;continue}const r=Gu(t,s);if(r!==null){if(n<r.end||!r.closed&&n<=r.end)return"literal";s=r.end;continue}const i=Yu(t,s);if(i){const l=il(t,i.to,i.name),a=l?.to??t.length;if(n<a||!l&&n<=a)return"literal";s=a;continue}s=cb(t,s)}return null}function Ja(t,e,n){return t.slice(e,n).replace(/[^\r\n]/g," ")}function ub(t){const e=t.split("");for(let n=0;n<t.length;n+=1){if(t[n]!=="%"||Ws(t,n))continue;const s=t.indexOf(`
|
|
13
|
-
`,n),r=s<0?t.length:s;for(let i=n;i<r;i+=1)e[i]=" ";n=r}return e.join("")}function db(t){let e="",n=0;for(;n<t.length;){if(t[n]==="%"&&!Ws(t,n)){const i=t.indexOf(`
|
|
14
|
-
`,n),l=i<0?t.length:i;e+=t.slice(n,l),n=l;continue}if(t[n]!=="\\"||Ws(t,n)){e+=t[n],n+=1;continue}const s=Ju(t,n);if(s!==null){e+=Ja(t,n,s),n=s;continue}const r=Yu(t,n);if(r){const l=il(t,r.to,r.name)?.to??t.length;e+=Ja(t,n,l),n=l;continue}e+=t[n],n+=1}return e}function hb(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function Ya(t){const e=ub(db(t)),n=/\\documentclass(?![A-Za-z@])\s*(?:\[[^\]]*\]\s*)?\{/g;for(const s of e.matchAll(n))if(s.index!==void 0&&!hb(e,s.index))return!0;return!1}const fb=new Set(Ku);function pb(t){return/[A-Za-z@0-9:_-]/.test(t)}function mb(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function ys(t,e){return t[e]==="%"&&!mb(t,e)}function Zs(t,e){const n=t.indexOf(`
|
|
15
|
-
`,e);return n===-1?t.length:n}function Pr(t,e){let n=e;for(;n<t.length;){if(/\s/.test(t[n])){n+=1;continue}if(ys(t,n)){n=Zs(t,n);continue}break}return n}function yo(t,e,n,s){if(t[e]!==n)return null;let r=0,i=0;for(let l=e;l<t.length;l+=1){const a=t[l];if(a==="\\"&&l+1<t.length){l+=1;continue}if(ys(t,l)){l=Zs(t,l)-1;continue}if(n==="["){if(a==="{"){i+=1;continue}if(a==="}"&&i>0){i-=1;continue}if(i>0)continue}if(a===n){r+=1;continue}if(a===s&&(r-=1,r===0))return{from:e,to:l+1,contentFrom:e+1,contentTo:l}}return null}function bo(t,e,n){const s=[];let r=e;for(;s.length<n;){for(r=Pr(t,r);t[r]==="[";){const l=yo(t,r,"[","]");if(!l)return s;r=Pr(t,l.to)}if(t[r]!=="{")break;const i=yo(t,r,"{","}");if(!i)break;s.push(i),r=i.to}return s}function Fx(t,e,n){const s=[];let r=e;for(;s.length<n&&(r=Pr(t,r),t[r]==="[");){const i=yo(t,r,"[","]");if(!i)break;s.push(i),r=i.to}return s}function gb(t,e){if(t[e]!=="\\"||e+1>=t.length)return null;let n=e+1;if(!/[A-Za-z@]/.test(t[n]))return{name:t[n],from:e,to:n+1};for(;n<t.length&&pb(t[n]);)n+=1;const s=t.slice(e+1,n);return t[n]==="*"&&(n+=1),{name:s,from:e,to:n}}function wb(t,e){if(e.name!=="begin")return e.to;const n=bo(t,e.to,1)[0];if(!n)return e.to;const s=t.slice(n.contentFrom,n.contentTo).trim();return fb.has(s)?il(t,n.to,s)?.to??t.length:e.to}function yb(t,e){let n=0;for(;n<t.length;){if(ys(t,n)){n=Zs(t,n);continue}if(t[n]!=="\\"){n+=1;continue}const s=gb(t,n);if(!s){n+=1;continue}const r=Ju(t,s.from);if(r!==null&&r>s.to){n=r;continue}const i=wb(t,s);if(i>s.to){n=i;continue}e(s),n=s.to}}function Hi(t,e,n){const s=[];let r=e.contentFrom,i=e.contentFrom;for(;i<=e.contentTo;){if(i<e.contentTo&&ys(t,i)){i=Zs(t,i),t[i]===`
|
|
16
|
-
`&&(i+=1);continue}if(i!==e.contentTo){i+=1;continue}const l=bb(t,r,i);l&&s.push(l),r=i+1,i+=1}return s}function bb(t,e,n){const s=[];let r=e;for(;r<n;){if(ys(t,r)){r=Zs(t,r),t[r]===`
|
|
17
|
-
`&&(r+=1);continue}s.push({character:t[r],index:r}),r+=1}let i=0,l=s.length;for(;i<l&&/\s/.test(s[i].character);)i+=1;for(;l>i&&/\s/.test(s[l-1].character);)l-=1;return i===l?null:{path:s.slice(i,l).map(a=>a.character).join(""),command:"",from:s[i].index,to:s[l-1].index+1}}function xb(t,e){const n=Pr(t,e);if(n>=t.length||/[\\{}\[\]#~]/.test(t[n]))return null;let s=n;for(;s<t.length&&!/\s/.test(t[s])&&!ys(t,s)&&!/[\\{}\[\]#~]/.test(t[s]);)s+=1;return s===n?null:{path:t.slice(n,s),command:"",from:n,to:s}}function Xa(t){const e=[];return yb(t,n=>{const s=n.name.toLowerCase();if(s==="input"||s==="include"||s==="subfile"){const c=bo(t,n.to,1)[0];if(c)for(const f of Hi(t,c))e.push({...f,command:n.name});else if(s==="input"){const f=xb(t,n.to);f&&e.push({...f,command:n.name})}return}if(s!=="import"&&s!=="subimport"&&s!=="includefrom"&&s!=="inputfrom"&&s!=="subinputfrom"&&s!=="subincludefrom")return;const r=bo(t,n.to,2);if(r.length!==2)return;const i=Hi(t,r[0])[0]?.path??"",l=Hi(t,r[1])[0];if(!l)return;const a=i&&!i.endsWith("/")?"/":"";e.push({path:i+a+l.path,command:n.name,from:l.from,to:l.to,directory:i})}),e}function kb({sessions:t,status:e}){const{t:n}=et(),[s,r]=u.useState(!1),i=Math.max(0,t.length-5),l=s&&i>0,a=l?t:t.slice(0,5);return u.useEffect(()=>{t.length<=5&&r(!1)},[t.length]),t.length<=1?null:o.jsxs("div",{className:`collaboration-presence collaboration-${e}`,children:[o.jsx("span",{className:"collaboration-status-dot","data-tooltip":n(`editor.collaboration.${e}`),"aria-label":n(`editor.collaboration.${e}`)}),o.jsxs("div",{className:"collaboration-avatars","aria-label":n("editor.collaboration.activeSessions",{count:t.length}),children:[a.map(c=>{const f=c.editing?n("editor.collaboration.editing"):n("editor.collaboration.viewing"),d=c.permission==="read"?n("common.readOnly"):n("common.readWrite"),h=n("editor.collaboration.sessionTooltip",{name:c.name,username:c.username,file:c.filePath||n("editor.collaboration.joining"),activity:f,permission:d});return o.jsxs("span",{className:`collaboration-avatar${c.editing?" editing":""}${c.local?" local":""}`,style:{"--session-color":c.color},"aria-label":h,tabIndex:0,children:[Wy(c.name,c.username),o.jsxs("span",{className:"collaboration-avatar-tooltip",role:"tooltip",children:[o.jsx("strong",{children:c.name}),o.jsxs("span",{children:["@",c.username]}),o.jsxs("small",{children:[c.filePath||n("editor.collaboration.joining")," · ",f," · ",d]})]})]},c.clientId)}),i>0&&o.jsx("button",{type:"button",className:"collaboration-avatar collaboration-avatar-overflow","aria-expanded":l,"aria-label":l?n("editor.collaboration.showFewerSessions"):n("editor.collaboration.showMoreSessions",{count:i}),title:l?n("editor.collaboration.showFewerSessions"):n("editor.collaboration.showMoreSessions",{count:i}),onClick:()=>r(c=>!c),children:l?"−":`+${i}`})]})]})}function Sb({value:t,onChange:e}){const{t:n}=et(),[s,r]=u.useState(!1),i=u.useRef(null),l=[{value:"editor-pdf",icon:ea},{value:"editor-only",icon:Lf},{value:"pdf-only",icon:Af}];return u.useEffect(()=>{if(!s)return;const a=f=>{i.current?.contains(f.target)||r(!1)},c=f=>{f.key==="Escape"&&r(!1)};return document.addEventListener("pointerdown",a),document.addEventListener("keydown",c),()=>{document.removeEventListener("pointerdown",a),document.removeEventListener("keydown",c)}},[s]),o.jsxs("div",{className:"layout-menu",ref:i,children:[o.jsxs("button",{type:"button",className:`layout-trigger${s?" active":""}`,"aria-haspopup":"menu","aria-expanded":s,title:n("editor.layout.current",{layout:n(`editor.layout.${t}.name`)}),onClick:()=>r(a=>!a),children:[o.jsx(ea,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(So,{size:13})]}),s&&o.jsxs("div",{className:"layout-popover",role:"menu","aria-label":n("editor.layout.label"),children:[o.jsx("div",{className:"layout-popover-title",children:n("editor.layout.choose")}),l.map(a=>{const c=a.icon,f=a.value===t;return o.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":f,className:`layout-option${f?" selected":""}`,onClick:()=>{e(a.value),r(!1)},children:[o.jsx(c,{size:19}),o.jsxs("span",{children:[o.jsx("strong",{children:n(`editor.layout.${a.value}.name`)}),o.jsx("small",{children:n(`editor.layout.${a.value}.description`)})]}),f&&o.jsx(sf,{size:16})]},a.value)})]})]})}function Cb({site:t,project:e,activeFile:n,saveStateLabel:s,editorPreferences:r,activeSessions:i,collaborationStatus:l,reconnectCollaboration:a,protocolUpgradeRequired:c,showEditor:f,filesCollapsed:d,toggleFilesPanel:h,workspaceLayout:m,changeWorkspaceLayout:g,onBack:w,onShare:v,showCitationLibrary:D,citationLibraryOpen:k,onCitationLibrary:B,onSelectionHistory:A,onHistory:b,onGit:O,canManageGit:S,formatting:T,readOnly:z,collaborationSynced:Z,hasSelection:X,onToggleComments:ce,commentsOpen:W,unresolvedCommentCount:ge,hasActiveFile:Q,onToggleSettings:I,settingsOpen:ee,compileBusy:we,sharedCompiling:K,localCompiling:G,cancelling:V,compileState:he,onCompile:se,onCancelCompile:ie}){const{t:C}=et();return o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:C("editor.backToProjects"),"aria-label":C("editor.backToProjects"),onClick:w,children:o.jsx(rf,{size:18})}),o.jsx("a",{className:"brand-link compact-brand-link",href:fs("/"),"aria-label":t.siteName,onClick:fe=>{fe.preventDefault(),w()},children:o.jsx(ef,{siteName:t.siteName,compact:!0})}),o.jsxs("div",{className:"project-heading",children:[o.jsx("strong",{children:e.name}),o.jsxs("small",{children:[n," · ",s]})]}),r.vimMode&&o.jsxs("span",{className:"vim-status-badge",title:C("editor.vimOnHint"),children:[o.jsx(_f,{size:14}),C("editor.vimOn")]}),o.jsx(kb,{sessions:i,status:l}),l==="disconnected"&&!c&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:C("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:a,children:C("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[f&&o.jsxs("button",{className:d?"":"active",onClick:h,children:[d?o.jsx(Rf,{size:15}):o.jsx(ac,{size:15}),C("common.files")]}),o.jsx(Sb,{value:m,onChange:g}),o.jsxs("button",{onClick:v,children:[o.jsx(Yi,{size:15}),C("projectSettings.share")]}),D&&o.jsxs("button",{className:k?"active":"",onClick:B,children:[o.jsx(of,{size:15}),C("citationLibrary.title")]}),o.jsxs("div",{className:"history-action",role:"group","aria-label":C("history.title"),children:[o.jsxs("div",{className:"history-action-label",children:[o.jsx(kf,{size:14}),o.jsx("span",{children:C("history.title")})]}),o.jsxs("div",{className:"history-action-options",children:[o.jsx("button",{type:"button",className:"history-action-selection",title:C(X?"selectionHistory.title":"selectionHistory.selectSourceHint"),onMouseDown:fe=>fe.preventDefault(),onClick:A,disabled:!X||!Q,children:C("selectionHistory.buttonLabel")}),o.jsx("button",{type:"button",className:"history-action-snapshots",title:C("history.projectSnapshots"),onClick:b,children:C("history.projectSnapshotsButton")})]})]}),o.jsxs("button",{type:"button",className:`comments-action${W?" active":""}`,title:C("editor.commentsAll"),"aria-label":ge>0?`${C("common.comments")} (${ge})`:C("common.comments"),onClick:ce,children:[o.jsx(lf,{size:15}),o.jsx("span",{children:C("common.comments")}),ge>0&&o.jsx("sup",{className:"comments-action-count",children:ge})]}),o.jsxs("button",{className:"git-action",title:C(S?"git.title":"git.ownerOnly"),disabled:!S,onClick:O,children:[o.jsx(af,{size:15}),"Git"]}),o.jsxs("button",{className:ee?"active":"",onClick:I,children:[o.jsx($f,{size:15}),C("common.settings")]}),K||G?o.jsxs("button",{className:"compile cancel-compile",title:C("compileControls.cancel"),onClick:ie,disabled:V||T||z||!Z,children:[V?o.jsx(lt,{className:"spin",size:15}):o.jsx(Dn,{size:15}),C(V?"compileControls.cancelling":"compileControls.cancel")]}):o.jsxs("button",{className:"compile",title:C("editor.compileShortcut"),onClick:se,disabled:we||T||z||!Z,children:[we?o.jsx(lt,{className:"spin",size:15}):o.jsx(Nf,{size:15}),C("editor.compile",{engine:e.engine})]})]})]})}function vb(t){return`${t.path}\0${t.line}`}function jb(t){const e=[],n=[];for(const s of t){for(;n.length&&n.at(-1).level>=s.level;)n.pop();const r=n.at(-1);r&&(e[r.index].hasChildren=!0),e.push({item:s,key:vb(s),ancestorKeys:n.map(({index:i})=>e[i].key),hasChildren:!1}),n.push({level:s.level,index:e.length-1})}return e}function Eb(t,e){return t.filter(n=>!n.ancestorKeys.some(s=>e.has(s)))}const Db=new Set(["avif","bmp","gif","ico","jpeg","jpg","png","svg","webp","eps"]),_b=new Set(["latex","ltx","tex"]),Tb=new Set(["aux","blg","bbl","bst","c","cc","cls","cpp","css","dtx","go","h","hpp","html","idx","ilg","ind","ins","java","js","json","jsx","lof","log","lot","lua","ltx","nav","out","php","py","r","rs","sh","snm","sql","sty","tex","toc","ts","tsx","vrb","xml","yaml","yml"]),Rb=new Set(["cfg","conf","dat","env","ini","text","toml","txt"]),Lb=new Set(["csv","ods","tsv","xls","xlsx"]),Ab=new Set(["7z","bz2","gz","rar","tar","xz","zip"]),Nb=new Set(["m4a","mp3","ogg","wav"]),Fb=new Set(["avi","mkv","mov","mp4","webm"]);function Mb(t){const e=t.split("/").at(-1)?.toLocaleLowerCase()??"";if(e===".latexmkrc"||e==="latexmkrc")return"latexmkrc";if(e==="makefile"||e==="dockerfile")return"code";if(e==="readme"||e.startsWith("readme."))return"markdown";const n=e.includes(".")?e.slice(e.lastIndexOf(".")+1):"";return n==="pdf"?"pdf":Db.has(n)?"image":n==="md"||n==="markdown"||n==="mdown"||n==="mkdn"?"markdown":_b.has(n)?"tex":n==="bib"||n==="bibtex"?"bib":Tb.has(n)?"code":Rb.has(n)?"text":Lb.has(n)?"spreadsheet":Ab.has(n)?"archive":Nb.has(n)?"audio":Fb.has(n)?"video":"file"}const Ob={pdf:jf,tex:Xl,bib:Tf,latexmkrc:Sf,image:Cf,markdown:rc,text:uf,code:Xl,spreadsheet:cf,archive:Xi,audio:xf,video:Ef,file:Ur};function Xu({path:t,size:e=13}){const n=Mb(t);if(n==="pdf"||n==="tex")return o.jsx("img",{className:`file-type-icon file-type-icon-${n}`,src:fs(`/${n==="pdf"?"pdf-file":"tex-file"}.svg`),width:e,height:e,alt:"","aria-hidden":"true"});const s=Ob[n]??Df;return o.jsx(s,{className:`file-type-icon file-type-icon-${n}`,size:e,"aria-hidden":"true"})}const Zu="application/x-texlite-project-path",Qu="texlite-path:";function $b({project:t,filesPanel:e,files:n,visibleEntries:s,activeFile:r,activeMainFile:i,selectedFile:l,selectedFolder:a,expandedFolders:c,fileDragActive:f,uploadingFiles:d,uploadFeedback:h,readOnly:m,formatting:g,canFormat:w,activeFormatLease:v,collaborationSynced:D,editorFontSize:k,outline:B,sourceCursorStore:A,wordCountBusy:b,hasSelection:O,hasFormatSelection:S,uploadInput:T,setSelectedFolder:z,setExpandedFolders:Z,setMoveEntry:X,setMoveName:ce,setMoveDestination:W,setDeleteEntry:ge,setFileDialogError:Q,setNewFolderName:I,setNewFolderOpen:ee,setNewFilePath:we,setNewFileOpen:K,setQuickOpen:G,setProjectSearchOpen:V,setFileDragActive:he,dismissUploadFeedback:se,setFilesCollapsed:ie,toggleFilesPanel:C,uploadFiles:fe,upload:te,openFile:H,movePathToFolder:ve,onError:De,onFormatFile:oe,onFormatSelection:Ce,jumpToSource:Ae,syncSourceToPdf:P,onWordCount:_e}){const{t:R}=et(),[be,Te]=u.useState(!1),[F,je]=u.useState(null),[re,N]=u.useState(null),q=u.useRef(0),xe=(L,Ne)=>Pb(L.path)!==Ne&&(L.type!=="directory"||Ne!==L.path&&!Ne.startsWith(`${L.path}/`)),Re=()=>{je(null),N(null)};return o.jsx(zr,{id:"files",order:1,ref:e,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>ie(!0),onExpand:()=>ie(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${f?" drop-active":""}`,onDragEnter:L=>{if(Sn(L.dataTransfer)){L.preventDefault();return}L.dataTransfer.types.includes("Files")&&(L.preventDefault(),!m&&!d&&he(!0))},onDragOver:L=>{if(Sn(L.dataTransfer)){L.preventDefault(),L.dataTransfer.dropEffect="move";return}L.dataTransfer.types.includes("Files")&&(L.preventDefault(),L.dataTransfer.dropEffect=m||d?"none":"copy")},onDragLeave:L=>{L.currentTarget.contains(L.relatedTarget)||he(!1)},onDrop:L=>{if(Sn(L.dataTransfer)){L.preventDefault(),L.stopPropagation();return}if(L.preventDefault(),he(!1),m||d)return;const Ne=Array.from(L.dataTransfer.files);if(Ib(L.dataTransfer)||Ne.length===0){De(R("editor.dropFoldersUnsupported"));return}fe(Ne)},children:[o.jsxs("div",{className:"panel-title",children:[o.jsx("button",{className:"file-size-toggle",type:"button","aria-pressed":be,title:R(be?"editor.hideFileSizes":"editor.showFileSizes"),onClick:()=>Te(L=>!L),children:R("common.files")}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{type:"button","aria-label":R("navigation.quickOpen"),title:`${R("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>G(!0),children:o.jsx(df,{size:15})}),o.jsx("button",{type:"button","aria-label":R("navigation.projectSearch"),title:`${R("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>V(!0),children:o.jsx(gf,{size:15})}),!m&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:d,"aria-label":R("editor.uploadAttachment"),title:R("editor.uploadTo",{folder:a||R("editor.projectRoot")}),onClick:()=>T.current?.click(),children:o.jsx(Zl,{size:15})}),o.jsx("button",{type:"button","aria-label":R("editor.newFolder"),title:R("editor.newFolder"),onClick:()=>{I(""),ee(!0)},children:o.jsx(hf,{size:15})}),o.jsx("button",{type:"button","aria-label":R("editor.newFile"),title:R("editor.newFile"),onClick:()=>{we(a?`${a}/`:""),K(!0)},children:o.jsx(vf,{size:15})}),o.jsx("input",{ref:T,type:"file",multiple:!0,hidden:!0,onChange:L=>{te(L)}})]}),o.jsx("button",{type:"button","aria-label":R("editor.collapseFiles"),title:R("editor.collapseFiles"),onClick:C,children:o.jsx(ac,{size:15})})]})]}),h&&o.jsxs("div",{className:`file-upload-feedback ${h.kind}`,role:h.kind==="error"?"alert":"status","aria-live":h.kind==="error"?"assertive":"polite","aria-busy":h.kind==="uploading",children:[h.kind==="uploading"?o.jsx(lt,{className:"spin",size:14}):h.kind==="success"?o.jsx(ic,{size:14}):o.jsx(Dt,{size:14}),o.jsxs("span",{className:"file-upload-feedback-text",children:[h.kind==="uploading"&&R("editor.uploadingFile",{file:h.fileName,current:h.current,total:h.total}),h.kind==="success"&&R("editor.uploadSucceeded",{count:h.count}),h.kind==="error"&&h.message]}),h.kind!=="uploading"&&o.jsx("button",{type:"button",className:"file-upload-feedback-dismiss","aria-label":R("common.close"),title:R("common.close"),onClick:se,children:o.jsx(Dn,{size:13})})]}),f&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(Zl,{size:24}),o.jsx("strong",{children:R("editor.dropFiles")}),o.jsx("span",{children:R("editor.uploadTo",{folder:a||R("editor.projectRoot")})})]}),o.jsx("div",{className:`file-list${a!==null?" folder-selected":""}${re===""?" root-drop-target":""}`,style:{fontSize:`${k}px`},onDragOver:L=>{if(!(!F&&!Sn(L.dataTransfer))&&(L.preventDefault(),L.stopPropagation(),!!F)){if(!xe(F,"")){L.dataTransfer.dropEffect="none";return}L.dataTransfer.dropEffect="move",N("")}},onDragLeave:L=>{L.currentTarget.contains(L.relatedTarget)||N(Ne=>Ne===""?null:Ne)},onDrop:L=>{if(!F&&!Sn(L.dataTransfer)||(L.preventDefault(),L.stopPropagation(),!F))return;const Ne=F;Re(),xe(Ne,"")&&ve(Ne,"")},children:s.map(L=>{const Ne=L.path.split("/").length-1,mt=L.path.split("/").at(-1),Lt=c.has(L.path),ke=t.mainFile===L.path,M=L.path!==t.mainFile&&!t.mainFile.startsWith(`${L.path}/`);return L.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${a===L.path?" selected":""}${re===L.path?" move-drop-target":""}`,style:{paddingLeft:`${Ne*13+5}px`},onDragOver:U=>{if(!(!F&&!Sn(U.dataTransfer))&&(U.preventDefault(),U.stopPropagation(),!!F)){if(!xe(F,L.path)){U.dataTransfer.dropEffect="none";return}U.dataTransfer.dropEffect="move",N(L.path)}},onDragLeave:U=>{U.currentTarget.contains(U.relatedTarget)||N(Ee=>Ee===L.path?null:Ee)},onDrop:U=>{if(!F&&!Sn(U.dataTransfer)||(U.preventDefault(),U.stopPropagation(),!F))return;const Ee=F;Re(),xe(Ee,L.path)&&ve(Ee,L.path)},children:[o.jsxs("button",{type:"button",className:"file-entry-main",onClick:()=>{z(L.path),Z(U=>{const Ee=new Set(U);return Ee.has(L.path)?Ee.delete(L.path):Ee.add(L.path),Ee})},children:[Lt?o.jsx(So,{size:13}):o.jsx(ko,{size:13}),o.jsx(ff,{size:14}),o.jsx("span",{children:mt})]}),!m&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"file-entry-action",title:R("editor.move"),"aria-label":R("editor.move"),onClick:()=>{X(L),ce(mt??""),W("")},children:o.jsx(na,{size:13})}),M&&o.jsx("button",{type:"button",className:"file-entry-action danger-text",title:R("editor.deletePath"),"aria-label":R("editor.deletePath"),onClick:()=>{ge(L),Q("")},children:o.jsx(ln,{size:13})})]})]},L.path):o.jsxs("div",{className:`file-entry${a===null&&l===L.path?" active":""}${F?.path===L.path?" move-drag-source":""}`,style:{paddingLeft:`${Ne*13+18}px`},children:[o.jsxs("button",{type:"button",className:"file-entry-main",draggable:!m,onDragStart:U=>{q.current=Date.now()+500,zb(U,L,je)},onDragEnd:Re,onClick:()=>{if(q.current>Date.now()){q.current=0;return}H(L)},children:[o.jsx(Xu,{path:L.path}),o.jsx("span",{children:mt}),ke&&o.jsx("small",{children:R("editor.currentMainShort")})]}),be&&typeof L.size=="number"&&o.jsx("span",{className:"file-entry-size",children:Bb(L.size)}),!m&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"file-entry-action",title:R("editor.move"),"aria-label":R("editor.move"),onClick:()=>{X(L),ce(mt??""),W("")},children:o.jsx(na,{size:13})}),M&&o.jsx("button",{type:"button",className:"file-entry-action danger-text",title:R("editor.deletePath"),"aria-label":R("editor.deletePath"),onClick:()=>{ge(L),Q("")},children:o.jsx(ln,{size:13})})]})]},L.path)})}),!m&&w&&o.jsxs("div",{className:"file-format-footer",role:"group","aria-label":R("editor.format"),"aria-busy":g,children:[o.jsxs("div",{className:"file-format-label",children:[o.jsx(bf,{size:13}),R("editor.format")]}),o.jsxs("div",{className:"file-format-actions",children:[o.jsx("button",{className:S?"":"active",type:"button",title:R("editor.formatFileHint"),onMouseDown:L=>L.preventDefault(),onClick:oe,disabled:g||v||!D,children:R("editor.formatFile")}),o.jsx("button",{className:S?"active":"",type:"button",title:R(S?"editor.formatSelection":"editor.formatSelectionHint"),onMouseDown:L=>L.preventDefault(),onClick:Ce,disabled:g||v||!D||!S,children:R("editor.formatSelected")})]})]})]}),o.jsx(Ub,{outline:B,activeFile:r,activeMainFile:i,sourceCursorStore:A,wordCountBusy:b,hasSelection:O,jumpToSource:Ae,syncSourceToPdf:P,onWordCount:_e})]})})}function Ib(t){return Array.from(t.items).some(e=>e.webkitGetAsEntry?.()?.isDirectory===!0)}function Sn(t){return Array.from(t.types).includes(Zu)?!0:Array.from(t.types).includes("text/plain")&&t.getData("text/plain").startsWith(Qu)}function Pb(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function zb(t,e,n){t.dataTransfer.effectAllowed="move",t.dataTransfer.setData(Zu,e.path),t.dataTransfer.setData("text/plain",`${Qu}${e.path}`),n(e)}function Ub({outline:t,activeFile:e,activeMainFile:n,sourceCursorStore:s,wordCountBusy:r,hasSelection:i,jumpToSource:l,syncSourceToPdf:a,onWordCount:c}){const{t:f}=et(),d=u.useSyncExternalStore(s.subscribe,s.getOutlineLine,s.getOutlineLine),h=u.useMemo(()=>jb(t),[t]),m=u.useMemo(()=>h.filter(A=>A.hasChildren).map(A=>A.key),[h]),[g,w]=u.useState(()=>new Set);u.useEffect(()=>{const A=new Set(m);w(b=>{const O=new Set([...b].filter(S=>A.has(S)));return O.size===b.size?b:O})},[m]);const v=m.length>0&&m.every(A=>g.has(A)),D=u.useMemo(()=>Eb(h,g),[h,g]),k=()=>w(A=>v?new Set([...A].filter(b=>!m.includes(b))):new Set([...A,...m])),B=A=>w(b=>{const O=new Set(b);return O.has(A)?O.delete(A):O.add(A),O});return o.jsxs("section",{className:"outline-panel",children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("button",{className:"outline-heading",type:"button","aria-expanded":!v,title:f(v?"editor.expandOutline":"editor.collapseOutline"),onClick:k,disabled:m.length===0,children:[o.jsx(pf,{size:14}),f("common.outline")]}),o.jsxs("span",{className:"word-count-actions",role:"group","aria-label":f("editor.wordCountTitle"),children:[o.jsxs("button",{type:"button",title:f("editor.wordCountFullHint"),onClick:()=>c("full"),disabled:r||!n,children:[r?o.jsx(lt,{className:"spin",size:12}):o.jsx(ta,{size:12}),f("editor.wordCountFull")]}),o.jsxs("button",{type:"button",title:f("editor.wordCountSelectionHint"),onClick:()=>c("selection"),disabled:r||!i,children:[r?o.jsx(lt,{className:"spin",size:12}):o.jsx(ta,{size:12}),f("editor.wordCountSelection")]})]})]}),o.jsxs("div",{className:"outline",children:[D.map(A=>{const{item:b}=A,O=g.has(A.key),S=e===b.path&&d===b.line,T=b.path===n||b.path===e;return o.jsxs("div",{className:`outline-row${S?" current":""}`,children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${b.level*12}px`}}),A.hasChildren?o.jsx("button",{className:"outline-toggle",type:"button","aria-label":f(O?"editor.expandOutlineItem":"editor.collapseOutlineItem",{title:b.title}),"aria-expanded":!O,onClick:()=>B(A.key),children:O?o.jsx(ko,{size:13}):o.jsx(So,{size:13})}):o.jsx("span",{className:"outline-toggle-spacer","aria-hidden":!0}),o.jsxs("button",{className:"outline-item",type:"button",onClick:()=>{l(b.path,b.line,1),a(b.path,b.line,1)},children:[o.jsx("small",{children:T?b.line:b.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:b.title})]})]},A.key)}),t.length===0&&o.jsx("p",{className:"muted padded",children:f("editor.noOutline")})]})]})}function Bb(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${(t/1024/1024/1024).toFixed(1)} GB`}const qb=u.lazy(()=>Ct(()=>import("./LatexEditor-8r486VeG.js"),__vite__mapDeps([10,2,11,1,3,4,5,6,7,8]),import.meta.url).then(t=>({default:t.LatexEditor})));function Wb({project:t,activeFile:e,openTabs:n,content:s,loadedFile:r,readOnly:i,comments:l,focusComment:a,editorPreferences:c,completionIndex:f,nativeSpellCheck:d,spellCheckIssues:h,spellCheckJump:m,sourceJump:g,collaborativeText:w,collaborationAwareness:v,undoManager:D,editorNotice:k,activateTab:B,closeTab:A,handleTabKeyDown:b,updateEditorContent:O,setSelection:S,onAddComment:T,onCommentClick:z,onSpellCheckReplace:Z,onReferenceNavigate:X,onCursor:ce}){const{t:W}=et(),ge=hp(l,e),Q=fp(a,e,r);return o.jsx(zr,{id:"source",order:2,defaultSize:42,minSize:22,children:o.jsxs("main",{className:"source-panel",children:[c.openFilesInTabs&&n.length>0&&o.jsx("div",{className:"editor-tabs-bar",role:"tablist","aria-label":W("editor.openFiles"),children:o.jsx("div",{className:"editor-tabs-scroll",children:n.map((I,ee)=>{const we=I===e,K=I===t.mainFile,G=I.split("/").at(-1)||I;return o.jsxs("div",{className:`editor-tab-item${we?" active":""}`,role:"presentation",children:[o.jsxs("button",{id:`editor-tab-${encodeURIComponent(I)}`,type:"button",role:"tab","aria-selected":we,"aria-controls":"editor-source-content",tabIndex:we?0:-1,className:`editor-tab${we?" active":""}${K?" main-tab":""}`,onClick:()=>B(I),onKeyDown:V=>b(V,ee),title:I,children:[o.jsx("span",{className:"editor-tab-icon",children:K?o.jsx(rc,{size:13}):o.jsx(Ur,{size:13})}),o.jsx("span",{className:"editor-tab-title",children:G}),K&&o.jsx("small",{className:"editor-tab-badge",children:W("editor.currentMainShort")})]}),o.jsx("button",{type:"button",className:"editor-tab-close",title:W("common.close"),"aria-label":`${W("common.close")} ${G}`,onClick:()=>A(I),children:o.jsx(Dn,{size:12})})]},I)})})}),o.jsxs("div",{id:"editor-source-content",className:"editor-content-container",children:[o.jsx(u.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(lt,{className:"spin",size:22}),o.jsx("span",{children:W("common.loading")})]}),children:o.jsx(qb,{value:s,filePath:e,readOnly:i,comments:ge,focusComment:Q,preferences:c,nativeSpellCheck:d,completionIndex:f,spellCheckIssues:h,spellCheckJump:m,jumpTo:r===e&&g?.path===e?g:null,searchRequest:0,collaboration:w?{text:w,awareness:v,undoManager:i?void 0:D}:void 0,onChange:O,onSelection:S,onAddComment:T,onCommentClick:z,onSpellCheckReplace:Z,onReferenceNavigate:X,onCursor:ce},e)}),k&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:k})]})]})})}function Za({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=et(),l=s==="error"?Co:Dt;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((a,c)=>{const f=Kb(a.file,e),d=!!(f&&a.line);return o.jsxs("button",{type:"button",disabled:!d,className:"compile-diagnostic-row",onClick:()=>{f&&a.line&&r(f,a.line,a.column??1)},children:[o.jsx(l,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:a.message}),o.jsxs("small",{children:[a.phase,f?` · ${f}${a.line?`:${a.line}`:""}`:a.line?` · ${i("editor.lineNumber",{line:a.line})}`:""]})]})]},`${a.phase}-${a.file??""}-${a.line??0}-${c}`)})}):o.jsxs("div",{className:`compile-empty compile-${s}`,children:[o.jsx(l,{size:26}),o.jsx("span",{children:n})]})}function Ki({lines:t,empty:e,tone:n="log"}){const s=n==="error"?Co:n==="warning"?Dt:Zi;return t.length?o.jsx("pre",{className:`compile-output compile-${n}`,children:t.join(`
|
|
18
|
-
`)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function Vb({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:l}=et(),a=c=>fs(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(c)}&download=1`);return n.length?o.jsxs("div",{className:"artifact-browser",children:[o.jsx("div",{className:"artifact-list",children:n.map(c=>o.jsxs("div",{className:`artifact-row${s?.path===c.path?" active":""}`,children:[o.jsxs("button",{type:"button",disabled:!c.viewable,title:c.viewable?l("editor.viewArtifact"):l("editor.downloadToView"),onClick:()=>i(c),children:[o.jsx(Xu,{path:c.path,size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:c.path}),o.jsx("small",{children:Gb(c.size)})]})]}),o.jsx("a",{href:a(c.path),title:l("editor.downloadArtifact"),"aria-label":l("editor.downloadArtifact"),children:o.jsx(kr,{size:14})})]},c.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(lt,{className:"spin",size:24}),o.jsx("span",{children:l("common.loading")})]}):s?o.jsxs(o.Fragment,{children:[o.jsxs("header",{children:[o.jsx("strong",{children:s.path}),o.jsxs("a",{href:a(s.path),children:[o.jsx(kr,{size:13}),l("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Ur,{size:24}),o.jsx("span",{children:l("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(lc,{size:26}),o.jsx("span",{children:l("editor.noArtifacts")})]})}function Hb({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=et();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(Dt,{size:28}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanTitle")}),o.jsx("p",{children:i("editor.cleanDescription",{file:t})})]})]}),o.jsxs("div",{className:"compile-clean-actions",children:[o.jsxs("article",{children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(Qi,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanCache")}),o.jsx("p",{children:i("editor.cleanCacheDescription")}),o.jsxs("button",{type:"button",disabled:e||n,onClick:s,children:[n?o.jsx(lt,{className:"spin",size:14}):o.jsx(Qi,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(ln,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanArtifacts")}),o.jsx("p",{children:i("editor.cleanArtifactsDescription")}),o.jsxs("button",{type:"button",className:"danger",disabled:e||n,onClick:r,children:[n?o.jsx(lt,{className:"spin",size:14}):o.jsx(ln,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function Kb(t,e){if(!t)return null;const n=e.filter(a=>a.type==="file").map(a=>a.path),s=t.replaceAll("\\","/").replace(/^\.\//,"");if(n.includes(s))return s;const r=n.filter(a=>s.endsWith(`/${a}`));if(r.length===1)return r[0];const i=s.split("/").at(-1),l=n.filter(a=>a.split("/").at(-1)===i);return l.length===1?l[0]:null}function Gb(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const Jb=u.lazy(()=>nc().then(t=>({default:t.PdfPreview})));function Yb({projectId:t,activeMainFile:e,previewTab:n,diagnosticTab:s,pdfUrl:r,pdfLoadingMode:i,pdfLoading:l,pdfCompiledAt:a,pdfSizeBytes:c,pdfCompiledLabel:f,pdfTargetLabel:d,pdfDownloadUrl:h,pdfTarget:m,pdfViewport:g,activeFile:w,compileBusy:v,compileLog:D,compileDiagnostics:k,compileMessages:B,artifacts:A,artifactPreview:b,artifactLoading:O,cleaning:S,readOnly:T,collaborationSynced:z,workspaceLayout:Z,showSyncResize:X,diagnosticCount:ce,selectPreviewTab:W,changeWorkspaceLayout:ge,onSetNotice:Q,onSetPdfViewport:I,onResetPdfViewport:ee,syncVisiblePdfToSource:we,syncCurrentSourceToPdf:K,syncPdfToSource:G,canSyncWithPdf:V,canSyncPdfToSource:he,files:se,jumpToSource:ie,onSetCleanMode:C,cleanCompile:fe,viewArtifact:te}){const{t:H}=et(),[ve,De]=u.useState(""),oe=u.useRef(""),Ce=R=>{oe.current!==R&&(oe.current=R,De(R),ee())},Ae=he&&!!r&&ve===r,_e=[c==null?"":Xb(c),f?H("editor.pdfUpdatedAt",{time:f}):""].filter(Boolean).join(" · ");return o.jsxs(o.Fragment,{children:[X&&o.jsxs(xo,{className:"resize-handle sync-resize-handle",children:[o.jsx(oc,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:R=>R.stopPropagation(),children:[o.jsx("button",{disabled:!r||!g||!Ae,title:H(he?Ae?"editor.showInSource":"editor.syncTexWaitingForPdf":"editor.syncTexOnlyForMain"),"aria-label":H("editor.showInSource"),onClick:()=>{Ae&&we()},children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!w||!r||!V,title:H(V?"editor.showInPdf":"editor.syncTexOnlyForMain"),"aria-label":H("editor.showInPdf"),onClick:()=>{!w||!r||!V||K()},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),o.jsx(zr,{id:"preview",order:3,defaultSize:42,minSize:22,children:o.jsxs("section",{className:"preview-panel",children:[o.jsxs("div",{className:"preview-tabs",children:[o.jsxs("div",{className:"preview-tab-list",role:"tablist","aria-label":H("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":n==="pdf",className:`pdf-tab${n==="pdf"?" active":""}`,onClick:()=>W("pdf"),title:a?H("editor.pdfCompiledAtFor",{file:e,time:new Date(a).toLocaleString(Rs.resolvedLanguage)}):H("editor.currentMainDocument",{path:e}),children:[o.jsx("img",{className:"pdf-tab-icon",src:fs("/pdf-download.svg"),alt:"","aria-hidden":"true"}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",d,_e&&o.jsx("small",{children:_e})]})]}),o.jsxs("button",{role:"tab","aria-selected":n==="diagnostics",className:`diagnostics-tab${n==="diagnostics"?" active":""}`,onClick:()=>W("diagnostics"),children:[o.jsx(Zi,{size:14}),H("editor.outputTabs"),o.jsx("span",{children:ce})]})]}),h&&o.jsxs("a",{className:"pdf-download-top",href:h,download:!0,title:H("editor.downloadPdf"),"aria-label":H("editor.downloadPdf"),children:[o.jsx(kr,{size:15}),o.jsx("span",{children:H("editor.downloadPdf")})]})]}),n==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":H("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":s==="log",className:s==="log"?"active":"",onClick:()=>W("log"),children:[o.jsx(Zi,{size:13}),H("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":s==="warnings",className:s==="warnings"?"active":"",onClick:()=>W("warnings"),children:[o.jsx(Dt,{size:13}),H("editor.warnings"),o.jsx("span",{children:B.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="errors",className:s==="errors"?"active":"",onClick:()=>W("errors"),children:[o.jsx(Co,{size:13}),H("editor.errors"),o.jsx("span",{children:B.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="artifacts",className:s==="artifacts"?"active":"",onClick:()=>W("artifacts"),children:[o.jsx(lc,{size:13}),H("editor.artifacts"),o.jsx("span",{children:A.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="clean",className:s==="clean"?"active":"",onClick:()=>W("clean"),children:[o.jsx(Qi,{size:13}),H("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${n} ${n==="diagnostics"?`preview-${s}`:""}`,children:[n==="pdf"&&(r?o.jsx(u.Suspense,{fallback:o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(lt,{className:"spin",size:24}),o.jsx("span",{children:H("editor.loadingPdf")})]}),children:o.jsx(Jb,{url:r,loadingMode:i,target:m,compiling:v,onDisplayedUrlChange:Ce,onViewportLocation:(R,be,Te)=>{oe.current===r&&I({page:R,x:be,y:Te})},onDoubleClickLocation:(R,be,Te)=>{oe.current!==r||!Ae||(I({page:R,x:be,y:Te}),G(R,be,Te))}})}):l?o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(lt,{className:"spin",size:24}),o.jsx("span",{children:H("editor.loadingPdf")})]}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Ur,{size:28}),o.jsx("strong",{children:H("editor.preview")}),o.jsx("span",{children:H("editor.previewHint")})]})),n==="diagnostics"&&s==="log"&&o.jsx(Ki,{lines:D?D.split(`
|
|
19
|
-
`):[],empty:H(v?"editor.compiling":"editor.noLog")}),n==="diagnostics"&&s==="warnings"&&(k?o.jsx(Za,{tone:"warning",diagnostics:k.warnings,files:se,empty:H("editor.noWarnings"),onJump:(R,be,Te)=>{Z==="pdf-only"&&ge("editor-pdf"),ie(R,be,Te)}}):o.jsx(Ki,{tone:"warning",lines:B.warnings,empty:H("editor.noWarnings")})),n==="diagnostics"&&s==="errors"&&(k?o.jsx(Za,{tone:"error",diagnostics:k.errors,files:se,empty:H("editor.noErrors"),onJump:(R,be,Te)=>{Z==="pdf-only"&&ge("editor-pdf"),ie(R,be,Te)}}):o.jsx(Ki,{tone:"error",lines:B.errors,empty:H("editor.noErrors")})),n==="diagnostics"&&s==="artifacts"&&o.jsx(Vb,{projectId:t,mainFile:e,artifacts:A,preview:b,loading:O,onView:R=>{te(R)}}),n==="diagnostics"&&s==="clean"&&o.jsx(Hb,{mainFile:e,disabled:T||!z||v,cleaning:S,onCleanCache:()=>C("cache"),onCleanArtifacts:()=>C("artifacts")})]})]})})]})}function Xb(t){return!Number.isFinite(t)||t<0?"":t<1024?`${Math.round(t)} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function Zb(t,e){const n=t.slice(0,e),s=/(^|[^\p{L}\p{N}_.-])@([\p{L}\p{N}_.-]*)$/u.exec(n);return s?{start:e-s[2].length-1,end:e,query:s[2]}:null}function xr({projectId:t,value:e,onChange:n,onKeyDown:s,onFocus:r,...i}){const{t:l}=et(),a=u.useRef(null),[c,f]=u.useState(null),[d,h]=u.useState(!1),[m,g]=u.useState(null),[w,v]=u.useState(0),D=u.useMemo(()=>{if(!m||!c)return[];const S=m.query.toLocaleLowerCase();return(S?c.filter(z=>z.username.toLocaleLowerCase().includes(S)||z.displayName.toLocaleLowerCase().includes(S)):c).slice(0,8)},[c,m]),k=!!(m&&D.length),B=async()=>{if(!(c||d)){h(!0);try{const S=await me(`/api/projects/${t}/mention-candidates`);f(S.users)}catch{f([])}finally{h(!1)}}},A=(S,T)=>{const z=Zb(S,T);g(z),v(0),z&&B()},b=S=>{if(!m)return;const T=`@${S.username} `,z=`${e.slice(0,m.start)}${T}${e.slice(m.end)}`,Z=m.start+T.length;n(z),g(null),v(0),window.requestAnimationFrame(()=>{a.current?.focus(),a.current?.setSelectionRange(Z,Z)})},O=S=>{if(!S.nativeEvent.isComposing&&k){if(S.key==="ArrowDown"){S.preventDefault(),v(T=>(T+1)%D.length);return}if(S.key==="ArrowUp"){S.preventDefault(),v(T=>(T-1+D.length)%D.length);return}if(S.key==="Enter"&&!S.ctrlKey&&!S.metaKey&&!S.shiftKey){S.preventDefault(),b(D[w]??D[0]);return}if(S.key==="Escape"){g(null);return}}s?.(S)};return o.jsxs("span",{className:"mention-textarea",children:[o.jsx("textarea",{...i,ref:a,value:e,onFocus:S=>{r?.(S),A(e,S.currentTarget.selectionStart??e.length)},onClick:S=>A(e,S.currentTarget.selectionStart??e.length),onChange:S=>{const T=S.currentTarget.value;n(T),A(T,S.currentTarget.selectionStart??T.length)},onKeyDown:O}),k&&o.jsx("span",{className:"mention-menu",role:"listbox","aria-label":l("editor.mentionUsers"),children:D.map((S,T)=>o.jsxs("button",{type:"button",role:"option","aria-selected":T===w,className:T===w?"active":"",onMouseDown:z=>z.preventDefault(),onClick:()=>b(S),children:[o.jsx(Sr,{"aria-hidden":!0,size:13}),o.jsxs("span",{children:[o.jsx("strong",{children:S.displayName}),o.jsxs("small",{children:["(",S.username,")"]})]})]},S.id))})]})}function Gi(t,e){!(t.ctrlKey||t.metaKey)||t.key!=="Enter"||t.nativeEvent.isComposing||(t.preventDefault(),t.stopPropagation(),e())}function Qa(t){const e=/(^|\s)(@[\p{L}\p{N}_.-]+)/gu,n=[];let s=0;for(const r of t.matchAll(e)){const i=r.index??0,l=r[1],a=r[2],c=i+l.length;c>s&&n.push(t.slice(s,c)),n.push(o.jsx("span",{className:"comment-inline-mention",children:a},`${c}:${a}`)),s=c+a.length}return n.length?(s<t.length&&n.push(t.slice(s)),n):t}function Qb({projectId:t,comment:e,currentUserId:n,unreadCommentMentionId:s,unreadReplyMentionIds:r,highlightedComment:i,highlightedReplyId:l,currentComment:a,showFilePath:c,onMarkMentionRead:f,onFocus:d,onToggle:h,onReply:m,onEdit:g,onDelete:w,onEditReply:v,onDeleteReply:D}){const{t:k}=et(),[B,A]=u.useState(!1),[b,O]=u.useState(""),[S,T]=u.useState(!1),[z,Z]=u.useState(e.content),[X,ce]=u.useState(!1),[W,ge]=u.useState(null),[Q,I]=u.useState(""),[ee,we]=u.useState(null),K=async C=>{C?.preventDefault(),b.trim()&&await m(b)&&(O(""),A(!1))},G=async C=>{C?.preventDefault(),z.trim()&&await g(z)&&T(!1)},V=async C=>{C?.preventDefault(),!(!W||!Q.trim())&&await v(W,Q)&&ge(null)},he=e.authorUsername,se=C=>new Date(C).toLocaleString(Rs.resolvedLanguage),ie=async(C,fe)=>{fe.stopPropagation(),await f(C)};return o.jsxs(o.Fragment,{children:[o.jsxs("article",{"data-comment-id":e.id,className:`comment-thread${e.resolved?" resolved":""}${e.orphaned?" orphaned":""}${i?" mention-target":""}${a?" review-current":""}`,onClick:()=>{window.getSelection()?.toString()||d()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:e.authorDisplayName??he??k("editor.deletedUser")}),he&&o.jsxs("small",{children:["@",he]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toISOString(),children:se(e.createdAt)}),e.editedAt&&o.jsx("small",{children:k("editor.editedAt",{time:se(e.editedAt)})})]})]}),o.jsx("div",{className:"comment-location",children:e.orphaned?k("editor.orphaned"):c?k("editor.commentLocation",{path:e.filePath,line:e.startLine}):k("editor.line",{line:e.startLine})}),e.selectedText&&o.jsx("blockquote",{className:"comment-selected-text",children:e.selectedText}),S?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:C=>{G(C)},onClick:C=>C.stopPropagation(),children:[o.jsx(xr,{projectId:t,autoFocus:!0,rows:4,value:z,onChange:Z,onKeyDown:C=>Gi(C,G)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>T(!1),children:k("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!z.trim(),children:[o.jsx(sa,{size:13}),k("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:Qa(e.content)}),s&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(Sr,{"aria-hidden":!0,size:12}),k("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:C=>{ie(s,C)},children:k("editor.markMentionRead")})]}),e.replies.length>0&&o.jsx("div",{className:"comment-replies",children:e.replies.map(C=>{const fe=r?.get(C.id);return o.jsxs("div",{"data-comment-reply-id":C.id,className:`comment-reply${l===C.id?" mention-target":""}`,children:[o.jsxs("header",{children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:C.authorDisplayName??C.authorUsername??k("editor.deletedUser")}),C.authorUsername&&o.jsxs("small",{children:["@",C.authorUsername]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:C.createdAt,title:new Date(C.createdAt).toISOString(),children:se(C.createdAt)}),C.editedAt&&o.jsx("small",{children:k("editor.editedAt",{time:se(C.editedAt)})})]})]}),W===C.id?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:te=>{V(te)},onClick:te=>te.stopPropagation(),children:[o.jsx(xr,{projectId:t,autoFocus:!0,rows:3,value:Q,onChange:I,onKeyDown:te=>Gi(te,V)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>ge(null),children:k("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!Q.trim(),children:[o.jsx(sa,{size:13}),k("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:Qa(C.content)}),fe&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(Sr,{"aria-hidden":!0,size:12}),k("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:te=>{ie(fe,te)},children:k("editor.markMentionRead")})]}),C.authorId===n&&W!==C.id&&o.jsxs("div",{className:"comment-owner-actions",children:[o.jsx("button",{title:k("editor.editReply"),"aria-label":k("editor.editReply"),onClick:te=>{te.stopPropagation(),ge(C.id),I(C.content)},children:o.jsx(Ql,{size:12})}),o.jsx("button",{className:"danger-text",title:k("editor.deleteReply"),"aria-label":k("editor.deleteReply"),onClick:te=>{te.stopPropagation(),we(C.id)},children:o.jsx(ln,{size:12})})]})]},C.id)})}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",onClick:C=>{C.stopPropagation(),h()},children:[e.resolved?o.jsx(Mf,{size:13}):o.jsx(ic,{size:13}),e.resolved?k("editor.reopen"):k("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:C=>{C.stopPropagation(),A(fe=>!fe)},children:[o.jsx(Ff,{size:13}),k("editor.reply")]}),e.authorId===n&&!S&&o.jsxs("span",{className:"comment-owner-actions",children:[o.jsx("button",{title:k("editor.editComment"),"aria-label":k("editor.editComment"),onClick:C=>{C.stopPropagation(),Z(e.content),T(!0)},children:o.jsx(Ql,{size:13})}),o.jsx("button",{className:"danger-text",title:k("editor.deleteComment"),"aria-label":k("editor.deleteComment"),onClick:C=>{C.stopPropagation(),ce(!0)},children:o.jsx(ln,{size:13})})]})]}),B&&o.jsxs("form",{className:"comment-reply-form",onSubmit:C=>{K(C)},onClick:C=>C.stopPropagation(),children:[o.jsx(xr,{projectId:t,autoFocus:!0,rows:3,value:b,placeholder:k("editor.replyPlaceholder"),onChange:O,onKeyDown:C=>Gi(C,K)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>{A(!1),O("")},children:k("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!b.trim(),children:[o.jsx(Of,{size:13}),k("editor.sendReply")]})]})]})]}),o.jsx(Ns,{open:X,title:k("editor.deleteCommentTitle"),description:k("editor.deleteCommentDescription",{count:e.replies.length}),confirmLabel:k("common.delete"),danger:!0,onCancel:()=>ce(!1),onConfirm:()=>{w().then(C=>{C&&ce(!1)})}}),o.jsx(Ns,{open:!!ee,title:k("editor.deleteReplyTitle"),description:k("editor.deleteReplyDescription"),confirmLabel:k("common.delete"),danger:!0,onCancel:()=>we(null),onConfirm:()=>{ee&&D(ee).then(C=>{C&&we(null)})}})]})}function ex({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=et(),[i,l]=u.useState([]),[a,c]=u.useState([]),[f,d]=u.useState(""),[h,m]=u.useState("read"),[g,w]=u.useState(null),[v,D]=u.useState(""),k=n.permission==="owner",B=async()=>{try{const[T,z]=await Promise.all([me(`/api/projects/${s}/members`),me("/api/users")]);l(T.members),c(z.users.filter(Z=>Z.id!==n.ownerId))}catch(T){D(pe(T))}};u.useEffect(()=>{t&&B()},[t,s]);const A=async()=>{if(f)try{await me(`/api/projects/${s}/members/${f}`,{method:"PUT",body:JSON.stringify({permission:h})}),d(""),m("read"),await B()}catch(T){D(pe(T))}},b=async(T,z)=>{try{await me(`/api/projects/${s}/members/${T.id}`,{method:"PUT",body:JSON.stringify({permission:z})}),await B()}catch(Z){D(pe(Z))}},O=async()=>{if(g)try{await me(`/api/projects/${s}/members/${g.id}`,{method:"DELETE"}),w(null),await B()}catch(T){D(pe(T))}},S=a.filter(T=>!i.some(z=>z.id===T.id));return o.jsxs(o.Fragment,{children:[o.jsx(nn,{open:t,wide:!0,title:r("projectSettings.share"),description:r("projectSettings.shareDescription"),onOpenChange:e,footer:o.jsx("button",{onClick:()=>e(!1),children:r("common.close")}),children:o.jsxs("div",{className:"share-dialog",children:[v&&o.jsx("p",{className:"error",children:v}),o.jsxs("div",{className:"share-owner",children:[o.jsx(Yi,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),k&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:f,onChange:T=>d(T.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),S.map(T=>o.jsx("option",{value:T.id,children:T.displayName??T.username},T.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:h,onChange:T=>m(T.target.value),children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]})]}),o.jsxs("button",{className:"primary icon-button",disabled:!f,onClick:()=>{A()},children:[o.jsx(wf,{size:15}),r("projectSettings.addMember")]})]}),o.jsxs("div",{className:"shared-members-heading",children:[o.jsx("strong",{children:r("projectSettings.members")}),o.jsx("span",{children:i.length})]}),o.jsxs("div",{className:"shared-members",children:[i.map(T=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(T.displayName??T.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:T.displayName??T.username}),o.jsxs("small",{children:["@",T.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!k,value:T.permission,onChange:z=>{b(T,z.target.value)},children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]}),k&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>w(T),children:o.jsx(ln,{size:15})})]})]},T.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(Yi,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(Ns,{open:!!g,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:g?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>w(null),onConfirm:()=>{O()}})]})}const tx=u.lazy(()=>Ct(()=>import("./CitationLibraryDialog-tVD3i2gg.js"),__vite__mapDeps([12,2,1,3,13,5,14,4,6,15]),import.meta.url).then(t=>({default:t.CitationLibraryDialog}))),nx=u.lazy(()=>Ct(()=>import("./GitDialog-CjDCi1uh.js"),__vite__mapDeps([16,2,1,3,5,17,18,14,19,4,6,7,8]),import.meta.url).then(t=>({default:t.GitDialog}))),sx=u.lazy(()=>Ct(()=>import("./HistoryDialog-Pa9mK3Ky.js"),__vite__mapDeps([20,2,1,3,21,22,5,18,14,19,4,6,7,8]),import.meta.url).then(t=>({default:t.HistoryDialog}))),rx=u.lazy(()=>Ct(()=>import("./SelectionHistoryDialog-ZvAhIJMy.js"),__vite__mapDeps([23,2,1,3,21,4,5,6,7,8]),import.meta.url).then(t=>({default:t.SelectionHistoryDialog}))),ix=u.lazy(()=>Ct(()=>import("./ProjectNavigationDialogs-isGMXCfG.js"),__vite__mapDeps([24,2,1,3,6,5,4]),import.meta.url).then(t=>({default:t.ProjectSearchDialog}))),ox=u.lazy(()=>Ct(()=>import("./ProjectNavigationDialogs-isGMXCfG.js"),__vite__mapDeps([24,2,1,3,6,5,4]),import.meta.url).then(t=>({default:t.QuickOpenDialog})));function lx({user:t,project:e,projectId:n,activeFile:s,content:r,maxCitationBibtexBytes:i,files:l,directoryEntries:a,readOnly:c,workspaceLayout:f,changeWorkspaceLayout:d,resourcePreview:h,resourcePreviewLoading:m,setResourcePreview:g,setResourcePreviewLoading:w,uploadConflict:v,setUploadConflict:D,dismissUploadFeedback:k,uploadFiles:B,cleanMode:A,setCleanMode:b,cleanCompile:O,newFileOpen:S,setNewFileOpen:T,newFilePath:z,setNewFilePath:Z,newFolderOpen:X,setNewFolderOpen:ce,newFolderName:W,setNewFolderName:ge,selectedFolder:Q,fileDialogError:I,setFileDialogError:ee,createFile:we,createFolder:K,moveEntry:G,setMoveEntry:V,moveName:he,setMoveName:se,moveDestination:ie,setMoveDestination:C,movePath:fe,deleteEntry:te,setDeleteEntry:H,deleteActiveSessions:ve,removePath:De,commentOpen:oe,closeComment:Ce,commentSelection:Ae,selection:P,commentText:_e,setCommentText:R,commentSubmitting:be,commentError:Te,addComment:F,shareOpen:je,setShareOpen:re,citationLibraryOpen:N,setCitationLibraryOpen:q,insertCitationAtCursor:xe,quickOpen:Re,setQuickOpen:L,projectSearchOpen:Ne,setProjectSearchOpen:mt,openFile:Lt,jumpToSource:ke,selectionHistoryOpen:M,setSelectionHistoryOpen:U,historyOpen:Ee,setHistoryOpen:We,gitOpen:Pe,setGitOpen:Je,save:ct,permissionDowngrade:ue,permissionDowngradeBusy:vt,dismissPermissionDowngrade:$,discardPermissionDraft:J}){const{t:x}=et();return o.jsxs(o.Fragment,{children:[ue&&o.jsx(nn,{open:!0,title:x("editor.collaboration.permissionDowngradeTitle"),description:ue.localDraftReady&&ue.otherTabDraft?x("editor.collaboration.permissionDowngradeMultipleDrafts"):ue.otherTabDraft?x("editor.collaboration.permissionDowngradeOtherTab"):ue.localDraftReady?x("editor.collaboration.permissionDowngradeDescription",{previous:x("common.readWrite")}):x("editor.collaboration.permissionDowngradeNoDraft"),onOpenChange:j=>{!j&&!vt&&$()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:vt,onClick:$,children:ue.localDraftReady?x("editor.collaboration.permissionDowngradeKeep"):x("common.close")}),!ue.otherTabDraft&&o.jsxs("button",{type:"button",className:"danger",disabled:vt,onClick:()=>{J()},children:[vt?o.jsx(lt,{className:"spin",size:14}):ue.localDraftReady?o.jsx(ln,{size:14}):o.jsx(yf,{size:14}),ue.localDraftReady?x("editor.collaboration.permissionDowngradeDiscard"):x("editor.collaboration.permissionDowngradeReload")]})]}),children:o.jsx("div",{})}),o.jsxs(nn,{open:!!h,extraWide:h?.kind==="image"||h?.kind==="pdf"||h?.kind==="text",title:h?.path??"",description:h?.kind==="large"?x("editor.resourceTooLarge",{size:ax(h.size),limit:`${wo/1024/1024} MB`}):x(`editor.resourcePreview.${h?.kind??"text"}`),onOpenChange:j=>{j||(g(null),w(!1))},footer:h&&o.jsxs("a",{className:"primary resource-download",href:`${h.url}&download=1`,download:!0,children:[o.jsx(kr,{size:14}),x("editor.downloadResource")]}),children:[h?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Xi,{size:34}),o.jsx("strong",{children:x("editor.resourceTooLargeTitle")}),o.jsx("span",{children:x("editor.resourceTooLargeDescription")})]}),h?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Xi,{size:34}),o.jsx("strong",{children:x("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:x("editor.resourceUnsupportedDescription")})]}),h?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:h.url,alt:h.path})}),h?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:h.url,title:h.path}),h?.kind==="text"&&(m?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(lt,{className:"spin",size:24}),o.jsx("span",{children:x("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:h.content}))]}),o.jsx(Ns,{open:!!v,title:x("editor.uploadOverwriteTitle"),description:x("editor.uploadOverwriteDescription",{files:v?.collisions.join(", ")??""}),confirmLabel:x("editor.uploadOverwrite"),danger:!0,onCancel:()=>{D(null),k()},onConfirm:()=>{const j=v;D(null),j&&B(j.files,new Set(j.collisions),j.directory)}}),o.jsx(Ns,{open:!!A,title:x(A==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:x(A==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:x("editor.cleanConfirm"),danger:A==="artifacts",onCancel:()=>b(null),onConfirm:()=>{const j=A;b(null),j&&O(j)}}),o.jsx(nn,{open:S,title:x("editor.newFile"),description:x("editor.newFileDescription"),onOpenChange:j=>{T(j),j||ee("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>T(!1),children:x("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{we()},children:x("common.create")})]}),children:o.jsxs(o.Fragment,{children:[I&&o.jsx("p",{className:"error dialog-error",children:I}),o.jsxs("label",{className:"form-field",children:[x("editor.filePath"),o.jsx("input",{autoFocus:!0,value:z,onChange:j=>Z(j.target.value),onKeyDown:j=>{j.key==="Enter"&&!j.nativeEvent.isComposing&&(j.preventDefault(),we())}})]})]})}),o.jsx(nn,{open:X,title:x("editor.newFolder"),description:x("editor.folderDestination",{folder:Q||x("editor.projectRoot")}),onOpenChange:j=>{ce(j),j||ee("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>ce(!1),children:x("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{K()},children:x("common.create")})]}),children:o.jsxs(o.Fragment,{children:[I&&o.jsx("p",{className:"error dialog-error",children:I}),o.jsxs("label",{className:"form-field",children:[x("editor.folderName"),o.jsx("input",{autoFocus:!0,value:W,onChange:j=>ge(j.target.value),onKeyDown:j=>{j.key==="Enter"&&K()}})]})]})}),o.jsx(nn,{open:!!G,title:x("editor.moveTitle",{name:G?.path.split("/").at(-1)??""}),description:x("editor.moveDescription"),onOpenChange:j=>{j||(V(null),se(""),ee(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>V(null),children:x("common.cancel")}),o.jsx("button",{className:"primary",disabled:!he.trim(),onClick:()=>{fe()},children:x("editor.moveApply")})]}),children:o.jsxs(o.Fragment,{children:[I&&o.jsx("p",{className:"error dialog-error",children:I}),o.jsxs("label",{className:"form-field",children:[x("editor.pathName"),o.jsx("input",{autoFocus:!0,value:he,onChange:j=>se(j.target.value),onKeyDown:j=>{j.key==="Enter"&&fe()}})]}),o.jsxs("label",{className:"form-field",children:[x("editor.destinationFolder"),o.jsxs("select",{value:ie,onChange:j=>C(j.target.value),children:[o.jsx("option",{value:"",children:x("editor.projectRoot")}),a.filter(j=>G?.type!=="directory"||j.path!==G.path&&!j.path.startsWith(`${G.path}/`)).map(j=>o.jsx("option",{value:j.path,children:j.path},j.path))]})]})]})}),o.jsx(nn,{open:!!te,title:x("editor.deletePathTitle",{name:te?.path.split("/").at(-1)??""}),description:ve.length?x("editor.deletePathActiveDescription",{path:te?.path??"",users:[...new Set(ve.map(j=>j.name))].join(", ")}):x("editor.deletePathDescription",{path:te?.path??""}),onOpenChange:j=>{j||(H(null),ee(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>H(null),children:x("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{De()},children:x("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[I&&o.jsx("p",{className:"error dialog-error",children:I}),ve.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(Dt,{size:15}),x("editor.deletePathWillClose")]})]})}),o.jsxs(nn,{open:oe,draggable:!0,title:x("editor.addComment"),description:Ae.selectedText?x("editor.commentDescription",{count:Ae.endOffset-Ae.startOffset}):x("editor.pointComment"),onOpenChange:j=>{j||Ce()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:be,onClick:Ce,children:x("common.cancel")}),o.jsxs("button",{type:"button",className:"primary",disabled:be||!_e.trim(),onClick:()=>{F()},children:[be&&o.jsx(lt,{className:"spin",size:14}),x("editor.addComment")]})]}),children:[Te&&o.jsx("p",{className:"error dialog-error",children:Te}),o.jsxs("label",{className:"form-field",children:[x("editor.commentContent"),o.jsx(xr,{projectId:n,autoFocus:!0,rows:5,disabled:be,value:_e,onChange:R,onKeyDown:j=>{(j.ctrlKey||j.metaKey)&&j.key==="Enter"&&!j.nativeEvent.isComposing&&(j.preventDefault(),j.stopPropagation(),F())}})]}),Ae.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:Ae.selectedText})]}),o.jsx(ex,{open:je,onOpenChange:re,project:e,projectId:n}),N&&o.jsx(sc,{title:x("citationLibrary.title"),onClose:()=>q(!1),children:o.jsx(tx,{open:!0,onOpenChange:q,currentFile:s,currentSource:r,readOnly:c,currentUserId:t.id,maxBibtexBytes:i,onInsert:xe})}),Re&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(ox,{open:!0,files:l,onOpenChange:L,onOpenFile:j=>{const nt=l.find(Ye=>Ye.path===j);nt&&Lt(nt)}})}),Ne&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(ix,{open:!0,project:e,onOpenChange:mt,onJump:(j,nt,Ye)=>{f==="pdf-only"&&d("editor-pdf"),ke(j,nt,Ye)}})}),M&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(rx,{open:!0,onOpenChange:U,project:e,filePath:s,selection:P,currentSource:r})}),Ee&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(sx,{open:!0,onOpenChange:We,project:e,onBeforeMutation:e.permission==="read"?async()=>!0:ct})}),e.ownerId===t.id&&Pe&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(nx,{open:!0,onOpenChange:Je,project:e,onBeforeMutation:ct})})]})}function ax(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const cx=u.lazy(()=>Ct(()=>import("./ProjectSettings-Br_kJ113.js"),__vite__mapDeps([25,2,1,3,5,26,27,8,4,6,7]),import.meta.url).then(t=>({default:t.ProjectSettings})));function ux({sidePanel:t,onClose:e,project:n,projectId:s,site:r,files:i,currentUserId:l,comments:a,commentsLoading:c,commentsError:f,onRetryComments:d,unreadMentions:h,activeFile:m,hasProjectCommentsScope:g,commentScope:w,onCommentScopeChange:v,focusedCommentId:D,onMarkMentionRead:k,onMarkAllMentionsRead:B,onClearFocusComment:A,targetCommentId:b,targetReplyId:O,onFocusComment:S,onToggleComment:T,onReplyComment:z,onEditComment:Z,onDeleteComment:X,onEditCommentReply:ce,onDeleteCommentReply:W,dictionaryWords:ge,onDictionaryChange:Q,editorPreferences:I,onEditorPreferences:ee,spellCheckCount:we,spellCheckUniqueCount:K,spellCheckIndex:G,onSpellCheckNavigate:V,onProject:he}){const{t:se}=et(),[ie,C]=u.useState("unresolved"),[fe,te]=u.useState(null),H=u.useMemo(()=>({unresolved:Li(a,{activeFile:m,scope:w,filter:"unresolved",unreadMentions:h}).length,mentions:Li(a,{activeFile:m,scope:w,filter:"mentions",unreadMentions:h}).length,resolved:Li(a,{activeFile:m,scope:w,filter:"resolved",unreadMentions:h}).length}),[m,w,a,h]),ve=u.useMemo(()=>dp(a,{activeFile:m,scope:w,filter:ie,unreadMentions:h},[fe,b,D]),[m,ie,w,a,D,fe,b,h]),De=D&&ve.some(F=>F.id===D)?D:fe&&ve.some(F=>F.id===fe)?fe:b&&ve.some(F=>F.id===b)?b:null,oe=gp(ve,De);u.useEffect(()=>{fe&&!a.some(F=>F.id===fe)&&te(null)},[a,fe]),u.useEffect(()=>{!g&&w!=="file"&&(te(null),A(),v("file"))},[w,g,A,v]),u.useEffect(()=>{const F=b&&O?`[data-comment-reply-id="${O}"]`:b?`[data-comment-id="${b}"]`:De?`[data-comment-id="${De}"]`:"";if(!F)return;const je=document.querySelector(F);if(!je)return;const re=window.requestAnimationFrame(()=>je.scrollIntoView({block:b?"center":"nearest",behavior:"smooth"}));return()=>window.cancelAnimationFrame(re)},[De,b,O,ve]);const Ce=F=>{fe!==F.id&&te(null),S(F)},Ae=async F=>{S(F),te(mp(F,ie,h)?F.id:null),await T(F)},P=F=>{const je=wp(ve,De,F);te(null),je?Ce(je):A()},_e=async F=>{const je=await k(F);if(!je||ie!=="mentions")return je;const re=h.find(q=>q.id===F)?.commentId;return re&&(h.some(q=>q.id!==F&&q.commentId===re)||(fe===re&&te(null),D===re&&A())),je},R=async()=>{await B()&&ie==="mentions"&&(te(null),A())},be=F=>{F!==w&&(te(null),A(),v(F))},Te=F=>{F!==ie&&(te(null),A(),C(F))};return t?o.jsxs(o.Fragment,{children:[o.jsx(xo,{className:"resize-handle"}),o.jsx(zr,{id:"context",order:4,defaultSize:20,minSize:15,maxSize:38,children:o.jsxs("aside",{className:"context-panel",children:[t==="comments"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"drawer-title",children:[o.jsx("strong",{children:se("editor.sourceComments")}),o.jsxs("span",{className:"drawer-title-actions",children:[h.length>0&&o.jsxs("button",{className:"drawer-mention-read-all",type:"button",onClick:()=>{R()},title:se("editor.markAllMentionsRead"),children:[o.jsx(Sr,{"aria-hidden":!0,size:13}),o.jsx("span",{children:se("editor.markAllMentionsRead")})]}),o.jsx("button",{"aria-label":se("common.close"),onClick:e,children:o.jsx(Dn,{size:17})})]})]}),o.jsxs("div",{className:"comment-review-controls",children:[g&&o.jsxs("div",{className:"comment-review-group",role:"group","aria-label":se("editor.commentScope"),children:[o.jsx("button",{type:"button",className:w==="file"?"active":"","aria-pressed":w==="file",onClick:()=>be("file"),children:se("editor.commentScopeFile")}),o.jsx("button",{type:"button",className:w==="project"?"active":"","aria-pressed":w==="project",onClick:()=>be("project"),children:se("editor.commentScopeProject")})]}),o.jsxs("div",{className:"comment-review-group",role:"group","aria-label":se("editor.commentFilter"),children:[o.jsx("button",{type:"button",className:ie==="unresolved"?"active":"","aria-pressed":ie==="unresolved",onClick:()=>Te("unresolved"),children:se("editor.commentFilterUnresolved",{count:H.unresolved})}),o.jsx("button",{type:"button",className:ie==="mentions"?"active":"","aria-pressed":ie==="mentions",onClick:()=>Te("mentions"),children:se("editor.commentFilterMentions",{count:H.mentions})}),o.jsx("button",{type:"button",className:ie==="resolved"?"active":"","aria-pressed":ie==="resolved",onClick:()=>Te("resolved"),children:se("editor.commentFilterResolved",{count:H.resolved})})]}),o.jsxs("div",{className:"comment-review-navigation",children:[o.jsx("button",{type:"button",disabled:oe<=1,"aria-label":se("editor.commentPrevious"),title:se("editor.commentPrevious"),onClick:()=>P(-1),children:o.jsx(mf,{size:14})}),o.jsx("output",{"aria-live":"polite",children:se("editor.commentPosition",{current:oe,total:ve.length})}),o.jsx("button",{type:"button",disabled:ve.length===0||oe>0&&oe>=ve.length,"aria-label":se("editor.commentNext"),title:se("editor.commentNext"),onClick:()=>P(1),children:o.jsx(ko,{size:14})})]})]}),f&&o.jsxs("div",{className:"comment-review-error",role:"alert",children:[o.jsx("span",{children:f}),o.jsx("button",{type:"button",onClick:()=>{d()},children:se("common.retry")})]}),c&&o.jsx("div",{className:"comment-review-loading",role:"status",children:se("common.loading")}),o.jsxs("div",{className:"comments",children:[ve.map(F=>{const je=h.find(N=>N.commentId===F.id&&!N.replyId)?.id,re=new Map(h.filter(N=>N.commentId===F.id&&N.replyId).map(N=>[N.replyId,N.id]));return o.jsx(Qb,{projectId:s,comment:F,currentUserId:l,unreadCommentMentionId:je,unreadReplyMentionIds:re,highlightedComment:b===F.id&&!O,highlightedReplyId:b===F.id?O:null,currentComment:De===F.id,showFilePath:w==="project",onMarkMentionRead:_e,onFocus:()=>Ce(F),onToggle:()=>{Ae(F)},onReply:N=>z(F,N),onEdit:N=>Z(F,N),onDelete:()=>X(F),onEditReply:(N,q)=>ce(F,N,q),onDeleteReply:N=>W(F,N)},F.id)}),ve.length===0&&!c&&!f&&o.jsx("p",{className:"muted padded",children:a.length?se("editor.commentNoMatches"):se("editor.noComments")})]})]}),t==="settings"&&o.jsx(tf,{onClose:e,children:o.jsx(cx,{onClose:e,project:n,projectId:s,site:r,files:i,dictionaryWords:ge,onDictionaryChange:Q,editorPreferences:I,onEditorPreferences:ee,spellCheckCount:we,spellCheckUniqueCount:K,spellCheckIndex:G,onSpellCheckNavigate:V,onProject:he},s)})]})})]}):null}function dx(t){if(typeof globalThis.requestAnimationFrame=="function"){const n=globalThis.requestAnimationFrame(t);return()=>globalThis.cancelAnimationFrame(n)}const e=globalThis.setTimeout(t,0);return()=>globalThis.clearTimeout(e)}function hx(){let t={line:1,column:1,offset:0},e=t.line,n=null,s=null;const r=new Set,i=()=>{for(const c of r)c()},l=()=>{s=null;const c=n;n=null,!(c===null||c===e)&&(e=c,i())},a=c=>{n=c,s===null&&(s=dx(l))};return{getCursor:()=>t,getOutlineLine:()=>e,subscribe:c=>(r.add(c),()=>r.delete(c)),update:(c,f,d)=>{t.line===c&&t.column===f&&t.offset===d||(t={line:c,column:f,offset:d},(c!==e||s!==null)&&a(c))},reset:()=>{s?.(),s=null,n=null,t={line:1,column:1,offset:0},e!==1&&(e=1,i())},dispose:()=>{s?.(),s=null,n=null}}}function fx(t,e,n){return t.mainFile===e?t.items:!e||n.filePath!==e?[]:px(n.content).map(s=>({...s,path:e}))}function px(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`
|
|
20
|
-
`).forEach((r,i)=>{const l=r.match(n);l&&e.push({level:s[l[1]],title:l[2],line:i+1})}),e}const mx=u.lazy(()=>Ct(()=>import("./WordCountDialog-tFhMCGyn.js"),__vite__mapDeps([28,2,1,3,26,5,4,6,7,8]),import.meta.url).then(t=>({default:t.WordCountDialog})));let mr=null;function ec(){return mr||(mr=Ct(()=>import("./citationLibrary-ZeQPCv5O.js"),[],import.meta.url).catch(t=>{throw mr=null,t})),mr}function Ht(t){return t instanceof Error&&t.name==="AbortError"}const tc=300;function gx({site:t,user:e,projectId:n,preload:s,mentionId:r=null,onMentionTargeted:i,onMentionsRead:l,onBack:a}){const{t:c}=et(),f=u.useRef(n);f.current=n;const[d,h]=u.useState(null);u.useEffect(()=>(document.title=d?.name?`${t.siteName} | ${d.name}`:t.siteName,()=>{document.title=t.siteName}),[d?.name,t.siteName]);const[m,g]=u.useState(!1),[w,v]=u.useState([]),[D,k]=u.useState(null),[B,A]=u.useState({mainFile:"",items:[]}),[b,O]=u.useState(""),[S,T]=u.useState(""),[z,Z]=u.useState(""),[X,ce]=u.useState({filePath:"",content:""}),[W,ge]=u.useState({path:"",hasIncludes:!1}),[Q,I]=u.useState(""),[ee,we]=u.useState(!1),[K,G]=u.useState("editor.saved"),[V,he]=u.useState(null),se=u.useRef(V);se.current=V;const ie=u.useRef(null);ie.current||(ie.current=hx());const C=ie.current,[fe,te]=u.useState("pdf"),[H,ve]=u.useState("log"),De=p=>{if(p==="pdf"){te("pdf");return}if(p==="diagnostics"){te("diagnostics");return}ve(p),te("diagnostics")},{workspaceLayout:oe,setWorkspaceLayout:Ce}=rb(e.id,n),[Ae,P]=u.useState(""),[_e,R]=u.useState(""),[be,Te]=u.useState({selectedText:"",startOffset:0,endOffset:0}),F=u.useRef({selectedText:"",startOffset:0,endOffset:0}),je=p=>{const y=F.current;y.selectedText===p.selectedText&&y.startOffset===p.startOffset&&y.endOffset===p.endOffset||(F.current=p,Te(p))},[re,N]=u.useState(null),[q,xe]=u.useState(null),[Re,L]=u.useState(null),[Ne,mt]=u.useState(!1),[Lt,ke]=u.useState(!1),[M,U]=u.useState(!1),[Ee,We]=u.useState(!1),[Pe,Je]=u.useState(!1),[ct,ue]=u.useState(!1),[vt,$]=u.useState(null),[J,x]=u.useState(!1),[j,nt]=u.useState(!1),[Ye,zt]=u.useState(!1),[Ut,hn]=u.useState("full"),[$n,gt]=u.useState(""),[bs,Se]=u.useState(!1),[xs,ti]=u.useState(""),[ed,ni]=u.useState(null),[ks,In]=u.useState(!1),[fn,Bt]=u.useState(null),[td,si]=u.useState(!1),[st,ol]=u.useState(()=>ra(e.id,n));u.useEffect(()=>{const p=document.documentElement,y=st.showTooltips?"on":"off";return p.setAttribute("data-texlite-tooltips",y),()=>{p.getAttribute("data-texlite-tooltips")===y&&p.removeAttribute("data-texlite-tooltips")}},[st.showTooltips]);const[Pn,Qs]=u.useState([]),Xt=u.useRef([]);Xt.current=Pn;const nd=u.useRef(null),er=u.useRef(null),tr=u.useRef(0),ri=u.useRef(0),Fe=u.useRef(""),it=u.useRef(""),ll=u.useRef(()=>{}),ii=u.useRef(oe),al=u.useRef(0),pn=u.useRef(null),cl=u.useRef(null),mn=u.useRef(null),gn=u.useRef(null),zn=u.useRef(null),Un=u.useRef(null),Bn=u.useRef(null),Zt=u.useRef(null),oi=u.useRef(null),qt=u.useRef(!1),Qt=u.useRef(null),ul=u.useRef(a),li=u.useRef(i),ai=u.useRef(l);ul.current=a,li.current=i,ai.current=l,Fe.current=b,it.current=S,ii.current=oe,u.useEffect(()=>{if(!_e)return;const p=window.setTimeout(()=>R(""),3e3);return()=>window.clearTimeout(p)},[_e]);const sd=u.useCallback((p,y,E=0)=>{C.update(p,y,E)},[C]);u.useEffect(()=>()=>C.dispose(),[C]),u.useEffect(()=>()=>{Zt.current?.abort(),Zt.current=null},[]);const nr=p=>{const y=Xt.current,E=p(y);E!==y&&(Xt.current=E,Qs(E))};u.useEffect(()=>{Xt.current=[],Qs([]),Bt(null),Je(!1),Un.current?.abort(),Un.current=null,Bn.current?.abort(),Bn.current=null,Zt.current?.abort(),Zt.current=null,oi.current=null,xe(null),L(null),zt(!1),Se(!1),ti(""),ni(null)},[n]);const dl=p=>{const y=Xt.current,E=y.indexOf(p);if(E<0)return;const _=y.filter(ne=>ne!==p);if(Xt.current=_,Qs(_),Fe.current!==p)return;const ae=_.length>0?_[Math.min(E,_.length-1)]:d?.mainFile??"";O(ae)},{collaboration:Ie,status:sr,synced:Ve,activeSessions:hl,formatLeaseStates:rd,compileState:wn,setCompileState:fl,filesEvent:He,commentsRevision:pl,historyWarning:id,dictionaryRevision:ml,chktexSettingsRevision:gl,localDraftReady:wl,permission:ci,reconnect:od,protocolUpgradeRequired:yl,permissionDowngrade:ld,dismissPermissionDowngrade:ad,discardLocalDraft:cd}=Hy(n,e,S,d?.permission??"read",m,()=>G("editor.offlineDraft")),{unreadMentions:bl,refresh:ud,markMentionRead:dd,markAllMentionsRead:hd}=bp(n,pl,P),{pdfTarget:fd,pdfViewport:pd,sourceJump:md,setPdfViewport:gd,resetPdfViewport:wd,clearPdfViewport:xl,jumpToSource:qn,syncSourceToPdf:ui,syncPdfToSource:yd,syncVisiblePdfToSource:bd}=sb({projectId:n,mainFile:S,activeFile:b,onOpenSourceFile:p=>ll.current(p),onError:P,onShowPdf:()=>De("pdf"),onShowEditor:()=>{ii.current==="pdf-only"&&Ce("editor-pdf")}}),kl=!!(d&&d.chktexEnabled&&b&&Ve&&Ka(b)),yn=nb({active:kl,projectId:n,activeFile:b,content:z}),xd=!!(d&&b&&Ve&&ib(b)&&(st.spellCheck||d.chktexEnabled&&Ka(b))),wt=tb({active:xd,harperEnabled:st.spellCheck,projectId:n,activeFile:b,content:z,dictionaryWords:w,additionalIssues:yn.issues,additionalIssuesReady:!kl||yn.checked});u.useEffect(()=>{ol(ra(e.id,n))},[e.id,n]);const di=p=>{Z(p)};u.useEffect(()=>{if(!b||Q!==b){ce(_=>_.filePath||_.content?{filePath:"",content:""}:_);return}const p=b,y=z,E=window.setTimeout(()=>{ce(_=>_.filePath===p&&_.content===y?_:{filePath:p,content:y})},tc);return()=>window.clearTimeout(E)},[b,Q,z]),u.useEffect(()=>{if(Fe.current=b,C.reset(),je({selectedText:"",startOffset:0,endOffset:0}),!st.openFilesInTabs){Xt.current.length>0&&(Xt.current=[],Qs([]));return}b&&nr(p=>p.includes(b)?p:[...p,b])},[b,st.openFilesInTabs,n,C]),u.useEffect(()=>{if(!ee)return;const p=y=>{y.preventDefault(),y.returnValue=""};return window.addEventListener("beforeunload",p),()=>window.removeEventListener("beforeunload",p)},[ee]),u.useEffect(()=>{if(sr!=="disconnected")return;const p=new AbortController;return me(`/api/projects/${n}`,{signal:p.signal}).then(({project:y})=>{p.signal.aborted||(h(y),P(""))}).catch(y=>{if(!Ht(y)){if(y instanceof Ji&&[401,403,404].includes(y.status)){P(pe(y)),ul.current();return}P(c("errors.collaborationUnavailable"))}}),()=>p.abort()},[sr,n,c]);const rr=async(p={},y=it.current)=>{pn.current?.abort(),pn.current=null;const E=p.signal?null:new AbortController;E&&(pn.current=E);try{const _=y?`?mainFile=${encodeURIComponent(y)}`:"",ae=await me(`/api/projects/${n}/completions${_}`,{signal:p.signal??E?.signal});(!p.isCurrent||p.isCurrent())&&k(ae.index)}catch(_){if(Ht(_))return;(!p.isCurrent||p.isCurrent())&&k(null)}finally{E&&pn.current===E&&(pn.current=null)}},hi=async(p={},y=it.current)=>{mn.current?.abort(),mn.current=null;const E=p.signal?null:new AbortController;E&&(mn.current=E);try{const _=y?`?mainFile=${encodeURIComponent(y)}`:"",ae=await me(`/api/projects/${n}/outline${_}`,{signal:p.signal??E?.signal});(!p.isCurrent||p.isCurrent())&&it.current===y&&A({mainFile:y,items:ae.outline})}catch(_){if(Ht(_))return}finally{E&&mn.current===E&&(mn.current=null)}},Sl=async(p={})=>{gn.current?.abort(),gn.current=null;const y=p.signal?null:new AbortController;y&&(gn.current=y);try{const E=await me(`/api/projects/${n}/dictionary`,{signal:p.signal??y?.signal});(!p.isCurrent||p.isCurrent())&&v(E.words)}catch(E){if(Ht(E))return;(!p.isCurrent||p.isCurrent())&&v([])}finally{y&&gn.current===y&&(gn.current=null)}};u.useEffect(()=>{let p=!1;const y=++al.current,E=new AbortController,_=()=>!p&&al.current===y;let ae=!1,ne="";h(null),jl([]),A({mainFile:"",items:[]}),O(""),T(""),ge({path:"",hasIncludes:!1}),Z(""),I(""),fl(null),xl(),k(null),v([]),nc();const le=(s?.projectId===n?s.project:me(`/api/projects/${n}`,{signal:E.signal})).then(Ke=>{_()&&(ae=!0,ne=Ke.project.mainFile,h(Ke.project),O(Ke.project.mainFile),it.current=Ke.project.mainFile,T(Ke.project.mainFile),lr(new Set(En(Ke.project.mainFile))))}).catch(Ke=>{_()&&P(pe(Ke))}),At=me(`/api/projects/${n}/files`,{signal:E.signal}).then(Ke=>{_()&&jl(Ke.files)}).catch(Ke=>{_()&&P(pe(Ke))});let ht=null;return Promise.allSettled([le,At]).then(()=>{!_()||!ae||(ht=window.setTimeout(()=>{_()&&Promise.all([rr({signal:E.signal,isCurrent:_},it.current||ne),Sl({signal:E.signal,isCurrent:_})])},0))}),()=>{p=!0,ht!==null&&window.clearTimeout(ht),E.abort(),pn.current?.abort(),pn.current=null,mn.current?.abort(),mn.current=null,gn.current?.abort(),gn.current=null,zn.current?.abort(),zn.current=null}},[n,s]),u.useEffect(()=>{if(!(!d||!S)){if(cl.current!==n){cl.current=n;return}rr({},S)}},[S,d?.id,n]),u.useEffect(()=>{if(!r||!d)return;Bn.current?.abort();const p=new AbortController;return Bn.current=p,me(`/api/projects/${n}/mentions/${encodeURIComponent(r)}`,{signal:p.signal}).then(({mention:y})=>{p.signal.aborted||(xe(y),N("comments"),O(y.filePath),li.current?.(y.id))}).catch(y=>{Ht(y)||p.signal.aborted||(P(pe(y)),li.current?.(r))}).finally(()=>{Bn.current===p&&(Bn.current=null)}),()=>p.abort()},[r,d?.id,n]),u.useEffect(()=>{ml&&Sl()},[ml,n]),u.useEffect(()=>{if(!gl)return;const p=new AbortController;return me(`/api/projects/${n}`,{signal:p.signal}).then(({project:y})=>{p.signal.aborted||h(E=>E?{...E,chktexEnabled:y.chktexEnabled}:y)}).catch(y=>{Ht(y)||P(pe(y))}),()=>p.abort()},[gl,n]),u.useEffect(()=>{!d||sr!=="connected"||ci===d.permission||h(p=>p&&{...p,permission:ci})},[ci,d?.permission]),u.useEffect(()=>{if(!He)return;const p=He.kind==="delete"&&!!He.path&&kn(He.path,Fe.current),y=He.kind==="delete"&&!!He.path&&kn(He.path,it.current);if(He.kind==="move"&&He.source&&He.destination){const _=He.source,ae=He.destination,ne=le=>le===_?ae:le.startsWith(`${_}/`)?`${ae}${le.slice(_.length)}`:le;O(le=>ne(le)),T(le=>ne(le)),Cs(le=>le&&ne(le)),or(le=>le&&ne(le)),nr(le=>le.map(ne))}p&&(O(""),I(""),di(""),R(c("editor.fileDeletedByCollaborator",{path:He.path}))),He.kind==="delete"&&He.path&&(Cs(_=>_&&kn(He.path,_)?null:_),or(_=>kn(He.path,_)?"":_),_l(_=>_&&kn(He.path,_.path)?null:_),nr(_=>_.filter(ae=>!kn(He.path,ae)))),zn.current?.abort();const E=new AbortController;zn.current=E,Promise.all([jd({signal:E.signal}),me(`/api/projects/${n}`,{signal:E.signal})]).then(([_,ae])=>{if(h(ae.project),y&&T(ae.project.mainFile),p&&_){const ne=_.find(le=>le.type==="file"&&le.path===ae.project.mainFile)??_.find(le=>le.type==="file"&&ss(le.path));O(ne?.path??"")}rr({signal:E.signal}),hi({signal:E.signal},y?ae.project.mainFile:it.current)}).catch(_=>{Ht(_)}).finally(()=>{zn.current===E&&(zn.current=null)})},[He?.revision]),u.useEffect(()=>{if(Ie.setActiveFile(b),!b)return;I(""),G("editor.loading");const p=Ie.getText(b),y=(E,_)=>{di(p.toString()),I(b),_?.local&&d?.permission!=="read"?(tr.current+=1,we(!0),G("editor.pending")):tr.current<=ri.current&&G(se.current?"editor.savedAt":"editor.saved")};return p.observe(y),(Ve||wl)&&y(),()=>{p.unobserve(y)}},[b,Ie,Ve,wl,d?.permission]);const ir=async()=>{if(!Ve)throw new Error("Collaboration is not synchronized");const p=tr.current,y=await Ie.flush();return ri.current=Math.max(ri.current,p),he(y.persistedAt),/\.tex$/i.test(Fe.current)&&hi(),tr.current===p?(we(!1),G("editor.savedAt")):G("editor.pending"),y};u.useEffect(()=>{if(!ee||!b)return;if(!Ve){G("editor.offlineDraft");return}G("editor.pending");const p=window.setTimeout(()=>{G("editor.saving"),ir().catch(()=>{G(Ie.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(p)},[z,ee,b,Ve]);const Ss=async()=>{if(!d||d.permission==="read"||!Ve||!b)return!1;G("editor.saving");try{return await ir(),rr(),!0}catch(p){return G("editor.saveFailed"),P(pe(p)||c("errors.collaborationUnavailable")),!1}},kd=async p=>{if(!d||bs)return;const y=p==="full"?it.current||d.mainFile:Fe.current,E=p==="selection"?F.current.selectedText:"";if(!y)return;if(p==="selection"&&(!E.trim()||!/\.(?:tex|sty|cls)$/i.test(y))){R(c("editor.wordCountSelectionEmpty"));return}Un.current?.abort();const _=new AbortController;Un.current=_,hn(p),gt(y),ni(null),ti(""),zt(!0),Se(!0);try{if(p==="full"&&ee&&d.permission!=="read"&&!await Ss())throw new Error(c("editor.wordCountSaveRequired"));const ae=p==="selection"?{mode:p,path:y,source:E}:{mode:p,mainFile:y},ne=await me(`/api/projects/${n}/word-count`,{method:"POST",body:JSON.stringify(ae),signal:_.signal});if(_.signal.aborted)return;ni(ne)}catch(ae){if(Ht(ae))return;_.signal.aborted||ti(pe(ae))}finally{Un.current===_&&(Un.current=null,Se(!1))}},fi=async(p,y,E=st.texFmtConfig)=>{if(/\.bib$/i.test(p)){const ae=await ec();try{return{formatted:ae.formatBibtex(y,t.maxCitationBibtexBytes)}}catch(ne){throw ne instanceof ae.BibtexFormatError?ne.kind==="too-large"?new Error(c("citationLibrary.fileTooLarge",{size:ae.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})):new Error(c("citationLibrary.fileInvalid")):ne}}return{formatted:(await Vf(y,E)).output}},Cl=async p=>{if(!d||d.permission==="read"||!Ve||qt.current||!dr(Fe.current))return;const y=Fe.current,E=Ie.getText(y);qt.current=!0,In(!0);let _=()=>{};const ae=new Promise(le=>{_=le});Qt.current=ae;let ne=null;try{ne=await Ie.acquireFormatLease(y);const le=E.toString(),{formatted:At}=await fi(y,le,p);if(Fe.current!==y||E.toString()!==le){P(c("editor.formatSourceChanged"));return}await ne.confirm();const ht=await _i(le,At);if(Fe.current!==y||E.toString()!==le){P(c("editor.formatSourceChanged"));return}if(await ne.confirm(),Fe.current!==y||E.toString()!==le){P(c("editor.formatSourceChanged"));return}ht.length&&Ie.applyTextEdits(y,ht),ht.length&&await ir(),Bt(null),P(""),R(c("editor.formatFileComplete"))}catch(le){Di(le)?(Bt({action:"file",kind:le.kind,detail:le.message}),P("")):P(c("editor.formatFileFailed",{message:pe(le)}))}finally{ne&&await ne.release(),qt.current=!1,In(!1),_(),Qt.current===ae&&(Qt.current=null)}},Sd=async()=>{if(!st.formatOnCompile||!d||d.permission==="read"||!Ve||!dr(Fe.current)||qt.current)return;const p=Fe.current,y=Ie.getText(p);qt.current=!0,In(!0);let E=null;try{E=await Ie.acquireFormatLease(p);const _=y.toString(),{formatted:ae}=await fi(p,_);await E.confirm();const ne=await _i(_,ae);if(Fe.current!==p||y.toString()!==_)throw new Error(c("editor.formatSourceChanged"));if(await E.confirm(),Fe.current!==p||y.toString()!==_)throw new Error(c("editor.formatSourceChanged"));ne.length&&Ie.applyTextEdits(p,ne),ne.length&&await Ie.flush(),Bt(null)}catch(_){Di(_)?(Bt({action:"file",kind:_.kind,detail:_.message}),P("")):P(c("editor.formatFailedContinue",{message:pe(_)}))}finally{E&&await E.release(),qt.current=!1,In(!1)}},Cd=async()=>(Qt.current&&await Qt.current,await Sd(),Ss()),vl=async p=>{if(!d||d.permission==="read"||!Ve||qt.current||!dr(Fe.current))return;const y=F.current;if(!y.selectedText.trim()){R(c("editor.formatSelectionRequired"));return}const E=Fe.current,{startOffset:_,endOffset:ae,selectedText:ne}=y,le=Ie.getText(E);if(le.toString().slice(_,ae)!==ne){P(c("editor.formatSelectionChanged"));return}qt.current=!0,In(!0);let At=()=>{};const ht=new Promise(Wt=>{At=Wt});Qt.current=ht;let Ke=null;try{if(Ke=await Ie.acquireFormatLease(E),le.toString().slice(_,ae)!==ne){P(c("editor.formatSelectionChanged"));return}const Es=await fi(E,ne,p),Yh=Gf(ne,Es.formatted);await Ke.confirm();const Ei=await _i(ne,Yh,_);if(Fe.current!==E||le.toString().slice(_,ae)!==ne){P(c("editor.formatSelectionChanged"));return}if(await Ke.confirm(),Fe.current!==E||le.toString().slice(_,ae)!==ne){P(c("editor.formatSelectionChanged"));return}Ei.length&&Ie.applyTextEdits(E,Ei),Ei.length&&await ir(),Bt(null),P(""),R(c("editor.formatSelectionComplete"))}catch(Wt){Di(Wt)?(Bt({action:"selection",kind:Wt.kind,detail:Wt.message}),P("")):P(c("editor.formatFailed",{message:pe(Wt)}))}finally{Ke&&await Ke.release(),qt.current=!1,In(!1),At(),Qt.current===ht&&(Qt.current=null)}},vd=async p=>{const y=Fe.current;if(!/\.bib$/i.test(y)||d?.permission==="read"||!Ve)return R(c("citationLibrary.importRequiresWrite")),!1;const E=Ie.getText(y);let _;try{_=await ec()}catch(Es){return P(pe(Es)),!1}if(Fe.current!==y||!Ve)return!1;const ae=E.toString(),ne=_.parseBibEntriesResult(ae,t.maxCitationBibtexBytes);if(ne.status==="too-large")return R(c("citationLibrary.fileTooLarge",{size:_.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})),!1;if(ne.status==="invalid")return R(c("citationLibrary.fileInvalid")),!1;if(ne.entries.some(Es=>Es.citationKey.toLowerCase()===p.citationKey.toLowerCase()))return R(c("citationErrors.alreadyInFile",{key:p.citationKey})),!1;const le=Math.max(0,Math.min(ae.length,C.getCursor().offset)),At=ae.slice(0,le),ht=ae.slice(le),Ke=At?At.endsWith(`
|
|
21
|
-
|
|
22
|
-
`)?"":At.endsWith(`
|
|
23
|
-
`)?`
|
|
24
|
-
`:`
|
|
25
|
-
|
|
26
|
-
`:"",Wt=ht?ht.startsWith(`
|
|
27
|
-
|
|
28
|
-
`)?"":ht.startsWith(`
|
|
29
|
-
`)?`
|
|
30
|
-
`:`
|
|
31
|
-
|
|
32
|
-
`:"";return Ie.applyTextEdits(y,[{from:le,to:le,replacement:`${Ke}${p.bibtex.trim()}${Wt}`}]),R(c("citationLibrary.imported",{key:p.citationKey})),!0},{files:jt,setFiles:jl,loadFiles:jd,newFileOpen:Ed,setNewFileOpen:El,newFilePath:Dd,setNewFilePath:Dl,resourcePreview:_d,setResourcePreview:_l,resourcePreviewLoading:Td,setResourcePreviewLoading:Rd,newFolderOpen:Ld,setNewFolderOpen:Tl,newFolderName:Ad,setNewFolderName:Rl,fileDialogError:Nd,setFileDialogError:Ll,selectedFolder:Al,setSelectedFolder:Cs,selectedFile:Fd,setSelectedFile:or,expandedFolders:Md,setExpandedFolders:lr,moveEntry:Od,setMoveEntry:Nl,moveName:$d,setMoveName:Fl,moveDestination:Id,setMoveDestination:Ml,deleteEntry:pi,setDeleteEntry:Ol,fileDragActive:Pd,setFileDragActive:zd,uploadConflict:Ud,setUploadConflict:Bd,uploadingFiles:qd,uploadFeedback:Wd,dismissUploadFeedback:$l,directoryEntries:Vd,visibleEntries:Hd,createFile:Kd,createFolder:Gd,uploadFiles:Il,upload:Jd,openFile:mi,movePath:Yd,movePathToFolder:Xd,removePath:Zd}=Qy({projectId:n,site:t,activeFile:b,dirty:ee,save:Ss,onError:P,onProject:h,onActiveFile:O,onActiveMainFile:T});ll.current=p=>{Cs(null),or(p),lr(y=>new Set([...y,...En(p)])),O(p)};const Qd=p=>{if(p.id!==f.current)return;const y=p.mainFile!==d?.mainFile;h(p),y&&(it.current=p.mainFile,Fe.current=p.mainFile,T(p.mainFile),O(p.mainFile),Cs(null),or(p.mainFile),lr(E=>new Set([...E,...En(p.mainFile)])))},Pl=()=>it.current||d?.mainFile||"",eh=()=>{const p=Pl(),y=Fe.current;if(!y||!/\.tex$/i.test(y))return p;const E=jt.filter(ne=>ne.type==="file"&&/\.tex$/i.test(ne.path)).length,_=Ie.getText(y).toString();return Ya(_)||E===1?(p!==y&&(it.current=y,T(y)),y):p===y&&d?.mainFile&&d.mainFile!==y?(it.current=d.mainFile,T(d.mainFile),d.mainFile):p};u.useEffect(()=>{!b||b!==S||Q!==b||X.filePath!==b||!b.toLocaleLowerCase().endsWith(".tex")||jt.filter(y=>y.type==="file"&&/\.tex$/i.test(y.path)).length===0||b===d?.mainFile||!Ya(X.content)&&d?.mainFile&&(it.current=d.mainFile,T(d.mainFile))},[b,S,Q,X,jt,d?.mainFile]),u.useEffect(()=>{if(!st.openFilesInTabs||jt.length===0)return;const p=new Set(jt.filter(y=>y.type==="file"&&ss(y.path)).map(y=>y.path));nr(y=>{const E=y.filter(_=>p.has(_));return E.length===y.length?y:E})},[jt,st.openFilesInTabs]);const{comments:bn,commentsFilePath:gi,commentsReady:wi,reviewComments:th,reviewCommentsLoading:nh,reviewCommentsError:sh,retryReviewComments:rh,commentScope:ih,setCommentScope:oh,focusComment:zl,setFocusComment:ar,commentOpen:lh,openComment:ah,closeComment:ch,commentText:uh,setCommentText:dh,commentSelection:hh,commentSubmitting:fh,commentError:ph,addComment:mh,toggleComment:gh,replyToComment:wh,editComment:yh,deleteComment:bh,editCommentReply:xh,deleteCommentReply:kh}=up({projectId:n,activeFile:b,content:z,permission:d?.permission,revision:pl,selection:be,save:Ss,saveFailureMessage:c("errors.collaborationUnavailable"),onError:P,onAdded:()=>N("comments"),onChanged:()=>{ud()}});u.useEffect(()=>{if(!S||X.filePath!==S)return;const p=Xa(X.content).length>0;ge(y=>y.path===S&&y.hasIncludes===p?y:{path:S,hasIncludes:p})},[S,X]),u.useEffect(()=>{if(!S||!Ve||b===S)return;const p=Ie.getText(S);let y=null;const E=()=>{const ae=Xa(p.toString()).length>0;ge(ne=>ne.path===S&&ne.hasIncludes===ae?ne:{path:S,hasIncludes:ae})},_=()=>{y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>{y=null,E()},tc)};return E(),p.observe(_),()=>{y!==null&&window.clearTimeout(y),p.unobserve(_)}},[b,S,Ie,Ve]);const Sh=u.useMemo(()=>W.path===S&&W.hasIncludes,[S,W]),yi=p=>{N("comments"),ar(null),L(p),Fe.current!==p.filePath&&qn(p.filePath,p.startLine,1)};u.useEffect(()=>{if(!Re)return;const p=pp(Re,b,Q,gi,wi,bn);if(p){ar({...p}),L(null);return}Re.filePath===b&&Q===b&&gi===b&&wi&&L(null)},[b,bn,gi,wi,Q,Re,ar]);const Ch=async p=>{const y=await dd(p);return y&&ai.current?.(1),y},vh=async()=>{const p=bl.length,y=await hd();return y&&p&&ai.current?.(p,!0),y};u.useEffect(()=>{if(!q||b!==q.filePath||re!=="comments")return;const p=bn.find(E=>E.id===q.commentId);if(!p||q.replyId&&!p.replies.some(E=>E.id===q.replyId)||oi.current===q.id)return;oi.current=q.id,yi(p);const y=window.setTimeout(()=>xe(E=>E?.id===q.id?null:E),3e3);return()=>window.clearTimeout(y)},[b,bn,re,q]);const{pdfUrl:en,pdfCompiledAt:vs,pdfSizeBytes:jh,pdfLoadingMode:Eh,pdfLoading:bi,compileLog:xi,compileDiagnostics:Dh,compileOutcome:js,artifacts:Ul,artifactPreview:_h,artifactLoading:Th,editorNotice:Rh,localCompiling:Bl,cancelling:Lh,cleaning:ql,compile:Ah,cancelCompile:Nh,cleanCompile:Wl,viewArtifact:Fh}=Jy({projectId:n,project:d,mainFile:S,resolveCompileMainFile:eh,getCurrentMainFile:Pl,initialLatest:s?.projectId===n?s.latestCompile:null,collaborationSynced:Ve,sharedState:wn,onSharedState:fl,save:Cd,loadOutline:(p,y)=>hi({signal:p},y),onPreviewTab:De,onError:P,onCompileStart:()=>{P(""),R("")},onCompileSuccess:()=>{const p=Fe.current;if(p){const y=C.getCursor();ui(p,y.line,y.column,{silent:!0})}},onPdfChanged:xl});u.useEffect(()=>{if(!d||!S||!en&&bi)return;const p=window.setTimeout(()=>g(!0),en?150:0);return()=>window.clearTimeout(p)},[d,bi,en]),u.useEffect(()=>{const p=y=>{(y.ctrlKey||y.metaKey)&&(!y.shiftKey&&y.key.toLocaleLowerCase()==="p"?(y.preventDefault(),x(!0)):y.shiftKey&&y.key.toLocaleLowerCase()==="f"&&(y.preventDefault(),nt(!0)))};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[]);const Vl=p=>{ol(p),zf(e.id,n,p)},Hl=(p=!1)=>{const y=fn;if(!y)return;Bt(null),P(""),p&&Vl({...st,texFmtConfig:""});const E=p?"":void 0;y.action==="selection"?vl(E):Cl(E)},Mh=async()=>{si(!0);try{await cd()||(P(c("editor.collaboration.permissionDowngradeOtherTabBlocked")),si(!1))}catch(p){P(pe(p)),si(!1)}},Kl=()=>{er.current?.isCollapsed()?er.current.expand():er.current?.collapse()},Oh=u.useMemo(()=>fx(B,S,X),[B,S,X]),ki=u.useMemo(()=>Jf(xi,js),[xi,js]),Wn=oe!=="pdf-only",Gl=oe!=="editor-only",cr=p=>{Ce(p),p==="pdf-only"&&De("pdf")},$h=u.useCallback(p=>{Zt.current?.abort();const y=new AbortController;Zt.current=y;const E=Fe.current,_=it.current,ae=new URLSearchParams({kind:p.kind,key:p.key,...E?{path:E}:{},..._?{mainFile:_}:{}});me(`/api/projects/${n}/references/resolve?${ae}`,{signal:y.signal}).then(({target:ne})=>{if(!(y.signal.aborted||Fe.current!==E||it.current!==_)){if(!ne){P(c(p.kind==="citation"?"editor.citationTargetNotFound":"editor.labelTargetNotFound",{key:p.key}));return}ii.current==="pdf-only"&&cr("editor-pdf"),qn(ne.path,ne.line,ne.column)}}).catch(ne=>{!y.signal.aborted&&!Ht(ne)&&P(pe(ne))}).finally(()=>{Zt.current===y&&(Zt.current=null)})},[qn,n,c]),Ih=pi?hl.filter(p=>p.filePath&&kn(pi.path,p.filePath)):[];if(!d)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:Ae||c("common.loading")}),Ae&&o.jsx("button",{className:"primary",onClick:a,children:c("editor.backToProjects")})]});const tn=d.permission==="read"||!Ve,Si=rd.find(p=>p.path===b),Ci=Si&&!ks?Si:null,Ph=(p,y)=>{if(tn)return;const E=Fe.current;if(!E)return;if(Ie.getText(E).toString().slice(p.from,p.to)!==p.word){P(c("editor.spellCheckSourceChanged"));return}try{Ie.applyTextEdits(E,[{from:p.from,to:p.to,replacement:y}])}catch(ne){P(pe(ne))}},vi=wn?.mainFile===S&&(wn.status==="queued"||wn.status==="running"),ur=Bl||vi||ql,zh=b?Ie.getText(b):null,Uh=vs?new Date(vs).toLocaleString(Rs.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Bh=S.split("/").at(-1)??S,qh=ki.warnings.length+ki.errors.length+Ul.length,Wh=en?`${en}${en.includes("?")?"&":"?"}download=1`:"",ji=S||d.mainFile,Vh=!!(b&&b===ji&&/\.tex$/i.test(b)),Hh=!!(ji&&/\.tex$/i.test(ji)),Jl=p=>{const y=jt.find(E=>E.path===p);y&&ss(y.path)?mi(y):dl(p)},Kh=p=>{document.getElementById(`editor-tab-${encodeURIComponent(p)}`)?.focus()},Gh=(p,y)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(p.key))return;p.preventDefault();const E=p.key==="Home"?0:p.key==="End"?Pn.length-1:(y+(p.key==="ArrowLeft"?-1:1)+Pn.length)%Pn.length,_=Pn[E];_&&(Jl(_),window.requestAnimationFrame(()=>Kh(_)))},Yl=ur?vi?wn?.status==="queued"?c("editor.compileQueued"):c("editor.compilingBy",{name:wn?.requestedBy.name??c("common.user")}):c("editor.compiling"):js==="failed"?en&&vs?c("editor.compileFailedRetained",{time:new Date(vs).toLocaleString(Rs.resolvedLanguage)}):c("editor.compileFailedNoPdf"):js==="cancelled"?c("compileControls.cancelled"):"",Jh=K==="editor.savedAt"&&V?c("editor.savedAt",{time:new Date(V).toLocaleTimeString(Rs.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):c(K);return o.jsxs("div",{className:"workspace","data-texlite-tooltips":st.showTooltips?"on":"off",children:[o.jsx(Cb,{site:t,project:d,activeFile:b,saveStateLabel:Jh,editorPreferences:st,activeSessions:hl,collaborationStatus:sr,reconnectCollaboration:od,protocolUpgradeRequired:yl,showEditor:Wn,filesCollapsed:Ne,toggleFilesPanel:Kl,workspaceLayout:oe,changeWorkspaceLayout:cr,onBack:a,onShare:()=>ke(!0),showCitationLibrary:Wn&&/\.bib$/i.test(b),citationLibraryOpen:ct,onCitationLibrary:()=>ue(!0),onSelectionHistory:()=>Je(!0),onHistory:()=>We(!0),onGit:()=>U(!0),canManageGit:d.ownerId===e.id,formatting:ks,readOnly:tn,collaborationSynced:Ve,hasSelection:!!be.selectedText.trim(),onToggleComments:()=>N(re==="comments"?null:"comments"),commentsOpen:re==="comments",unresolvedCommentCount:bn.filter(p=>!p.resolved).length,hasActiveFile:!!b,onToggleSettings:()=>N(re==="settings"?null:"settings"),settingsOpen:re==="settings",compileBusy:ur,sharedCompiling:vi,localCompiling:Bl,cancelling:Lh,compileState:wn,onCompile:Ah,onCancelCompile:()=>{Nh()}}),yl&&o.jsxs("div",{className:"workspace-update-banner",role:"alert",children:[o.jsx(Dt,{size:15}),o.jsx("span",{children:c("workspaceUpdates.protocolUpgrade")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),Yl&&o.jsxs("div",{className:`compile-status-strip${js==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(lt,{className:ur?"spin":"",size:14}),o.jsx("span",{children:Yl})]}),(wt.error||yn.error||fn||Ci)&&o.jsxs("div",{className:"client-tool-recoveries",children:[wt.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:wt.error,children:[o.jsx(Dt,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c("editor.harperRecoveryTitle")}),c("editor.harperFallbackHint")]}),o.jsx("div",{className:"client-tool-recovery-actions",children:o.jsx("button",{type:"button",onClick:wt.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:wt.dismissError,children:o.jsx(Dn,{size:13})})]}),yn.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:yn.error,children:[o.jsx(Dt,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c("chktex.recoveryTitle")}),c("chktex.recoveryHint")]}),o.jsx("div",{className:"client-tool-recovery-actions",children:o.jsx("button",{type:"button",onClick:yn.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:yn.dismissError,children:o.jsx(Dn,{size:13})})]}),fn&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:fn.detail,children:[o.jsx(Dt,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c(fn.kind==="format"?"editor.texFmtOptionsRecoveryTitle":fn.kind==="load"?"editor.texFmtRecoveryTitle":"editor.texFmtRuntimeRecoveryTitle")}),c("editor.clientToolRecoveryHint")]}),o.jsxs("div",{className:"client-tool-recovery-actions",children:[o.jsx("button",{type:"button",disabled:ks||tn,onClick:()=>Hl(),children:c("common.retry")}),fn.kind==="format"&&st.texFmtConfig.trim()&&o.jsx("button",{type:"button",disabled:ks||tn,onClick:()=>Hl(!0),children:c("editor.resetFormatterOptions")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:()=>Bt(null),children:o.jsx(Dn,{size:13})})]}),Ci&&o.jsxs("div",{className:"client-tool-recovery format-lease-status",role:"status",children:[o.jsx(lt,{className:"spin",size:15}),o.jsx("span",{children:c("editor.formattingBy",{name:Ci.holderName})})]})]}),id&&o.jsxs("div",{className:"client-tool-recovery",role:"status",children:[o.jsx(Dt,{size:15}),o.jsx("span",{children:c("history.saveWarning")})]}),Ae&&o.jsx("div",{className:"toast",onClick:()=>P(""),children:Ae}),_e&&o.jsx("div",{className:"toast success",onClick:()=>R(""),children:_e}),o.jsxs(nf,{autoSaveId:Cn("texlite-workspace-layout"),direction:"horizontal",className:"work-grid",children:[Wn&&o.jsx($b,{project:d,filesPanel:er,files:jt,visibleEntries:Hd,activeFile:b,activeMainFile:S,selectedFile:Fd,selectedFolder:Al,expandedFolders:Md,fileDragActive:Pd,uploadingFiles:qd,uploadFeedback:Wd,readOnly:tn,formatting:ks,canFormat:dr(b),activeFormatLease:!!Si,collaborationSynced:Ve,editorFontSize:st.fontSize,outline:Oh,sourceCursorStore:C,wordCountBusy:bs,hasSelection:!!be.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(b),hasFormatSelection:!!be.selectedText.trim(),uploadInput:nd,setSelectedFolder:Cs,setExpandedFolders:lr,setMoveEntry:Nl,setMoveName:Fl,setMoveDestination:Ml,setDeleteEntry:Ol,setFileDialogError:Ll,setNewFolderName:Rl,setNewFolderOpen:Tl,setNewFilePath:Dl,setNewFileOpen:El,setQuickOpen:x,setProjectSearchOpen:nt,setFileDragActive:zd,dismissUploadFeedback:$l,setFilesCollapsed:mt,toggleFilesPanel:Kl,onError:P,uploadFiles:Il,upload:Jd,openFile:mi,movePathToFolder:Xd,onFormatFile:()=>{Cl()},onFormatSelection:()=>{vl()},jumpToSource:qn,syncSourceToPdf:ui,onWordCount:p=>{kd(p)}}),Wn&&o.jsx(xo,{className:"resize-handle",children:o.jsx(oc,{size:12})}),Wn&&o.jsx(Wb,{project:d,activeFile:b,openTabs:Pn,content:z,loadedFile:Q,readOnly:tn,comments:bn,focusComment:zl,editorPreferences:st,completionIndex:D,nativeSpellCheck:wt.nativeFallback,spellCheckIssues:wt.issues,spellCheckJump:wt.jump,sourceJump:md,collaborativeText:zh,collaborationAwareness:Ie.awareness,undoManager:b?Ie.getUndoManager(b):void 0,editorNotice:Rh,activateTab:Jl,closeTab:dl,handleTabKeyDown:Gh,updateEditorContent:di,setSelection:(p,y,E)=>je({selectedText:p,startOffset:y,endOffset:E}),onAddComment:(p,y,E,_)=>ah({selectedText:p,startOffset:y,endOffset:E},_),onCommentClick:p=>{const y=bn.find(E=>E.id===p);y&&yi(y)},onSpellCheckReplace:Ph,onReferenceNavigate:$h,onCursor:sd}),Gl&&o.jsx(Yb,{projectId:n,activeMainFile:S,previewTab:fe,diagnosticTab:H,pdfUrl:en,pdfLoadingMode:Eh,pdfLoading:bi,pdfCompiledAt:vs,pdfSizeBytes:jh,pdfCompiledLabel:Uh,pdfTargetLabel:Bh,pdfDownloadUrl:Wh,pdfTarget:fd,pdfViewport:pd,activeFile:b,compileBusy:ur,compileLog:xi,compileDiagnostics:Dh,compileMessages:ki,artifacts:Ul,artifactPreview:_h,artifactLoading:Th,cleaning:ql,readOnly:tn,collaborationSynced:Ve,workspaceLayout:oe,showSyncResize:Wn&&Gl,diagnosticCount:qh,selectPreviewTab:De,changeWorkspaceLayout:cr,onSetNotice:R,onSetPdfViewport:gd,onResetPdfViewport:wd,syncVisiblePdfToSource:bd,syncCurrentSourceToPdf:()=>{const p=Fe.current;if(!p)return Promise.resolve();const y=C.getCursor();return ui(p,y.line,y.column)},syncPdfToSource:yd,canSyncWithPdf:Vh,canSyncPdfToSource:Hh,files:jt,jumpToSource:qn,onSetCleanMode:$,cleanCompile:Wl,viewArtifact:Fh}),o.jsx(ux,{sidePanel:re,onClose:()=>N(null),project:d,projectId:n,site:t,files:jt,currentUserId:e.id,comments:th,commentsLoading:nh,commentsError:sh,onRetryComments:rh,activeFile:b,hasProjectCommentsScope:Sh,commentScope:ih,onCommentScopeChange:oh,focusedCommentId:zl?.id,onClearFocusComment:()=>ar(null),unreadMentions:bl,onMarkMentionRead:Ch,onMarkAllMentionsRead:vh,targetCommentId:q?.commentId,targetReplyId:q?.replyId,onFocusComment:yi,onToggleComment:gh,onReplyComment:wh,onEditComment:yh,onDeleteComment:bh,onEditCommentReply:xh,onDeleteCommentReply:kh,dictionaryWords:w,onDictionaryChange:v,editorPreferences:st,onEditorPreferences:Vl,spellCheckCount:wt.summary?.total??null,spellCheckUniqueCount:wt.summary?.unique??null,spellCheckIndex:wt.summary?wt.index:-1,onSpellCheckNavigate:wt.jumpToIssue,onProject:Qd})]}),Ye&&o.jsx(sc,{title:c("editor.wordCountTitle"),onClose:()=>zt(!1),children:o.jsx(mx,{open:!0,mode:Ut,path:$n,busy:bs,error:xs,result:ed,onOpenChange:zt})}),o.jsx(lx,{user:e,project:d,projectId:n,activeFile:b,content:z,maxCitationBibtexBytes:t.maxCitationBibtexBytes,files:jt,directoryEntries:Vd,readOnly:tn,workspaceLayout:oe,changeWorkspaceLayout:cr,resourcePreview:_d,resourcePreviewLoading:Td,setResourcePreview:_l,setResourcePreviewLoading:Rd,uploadConflict:Ud,setUploadConflict:Bd,dismissUploadFeedback:$l,uploadFiles:Il,cleanMode:vt,setCleanMode:$,cleanCompile:Wl,newFileOpen:Ed,setNewFileOpen:El,newFilePath:Dd,setNewFilePath:Dl,newFolderOpen:Ld,setNewFolderOpen:Tl,newFolderName:Ad,setNewFolderName:Rl,selectedFolder:Al,fileDialogError:Nd,setFileDialogError:Ll,createFile:Kd,createFolder:Gd,moveEntry:Od,setMoveEntry:Nl,moveName:$d,setMoveName:Fl,moveDestination:Id,setMoveDestination:Ml,movePath:Yd,deleteEntry:pi,setDeleteEntry:Ol,deleteActiveSessions:Ih,removePath:Zd,commentOpen:lh,closeComment:ch,commentSelection:hh,selection:be,commentText:uh,setCommentText:dh,commentSubmitting:fh,commentError:ph,addComment:mh,shareOpen:Lt,setShareOpen:ke,citationLibraryOpen:ct,setCitationLibraryOpen:ue,insertCitationAtCursor:vd,quickOpen:J,setQuickOpen:x,projectSearchOpen:j,setProjectSearchOpen:nt,openFile:mi,jumpToSource:qn,selectionHistoryOpen:Pe,setSelectionHistoryOpen:Je,historyOpen:Ee,setHistoryOpen:We,gitOpen:M,setGitOpen:U,save:Ss,permissionDowngrade:ld,permissionDowngradeBusy:td,dismissPermissionDowngrade:ad,discardPermissionDraft:Mh})]})}const Mx=Object.freeze(Object.defineProperty({__proto__:null,ProjectWorkspace:gx},Symbol.toStringTag,{value:"Module"}));export{vx as A,ic as B,So as C,cp as D,sn as E,kf as F,Hf as G,ta as H,$f as I,eo as J,bf as K,jx as L,Mx as P,Mf as R,sa as S,Jg as U,Ka as a,Tx as b,po as c,Rx as d,Lx as e,Ax as f,Nn as g,Ex as h,Vt as i,Ju as j,lb as k,il as l,To as m,Nx as n,ys as o,Zs as p,Pr as q,_x as r,ib as s,Dx as t,yb as u,Fx as v,bo as w,ub as x,yo as y,db as z};
|