texlite 0.9.3 → 0.10.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/OPERATIONS.md +9 -7
- package/README.md +64 -40
- package/README.zh-CN.md +56 -34
- package/dist/client/assets/{AdminUsers-huwQK7Ly.js → AdminUsers-C7oU_1Y_.js} +1 -1
- package/dist/client/assets/{CitationLibraryDialog-C5C3sPdw.js → CitationLibraryDialog-CU2b0xtm.js} +1 -1
- package/dist/client/assets/Dashboard-BB4RO4x2.js +2 -0
- package/dist/client/assets/{GitDialog-BI7QIMsh.js → GitDialog-C2Np1i8v.js} +1 -1
- package/dist/client/assets/{HistoryDialog-DA7O9aF2.js → HistoryDialog-CdoYeLyX.js} +1 -1
- package/dist/client/assets/LatexEditor-Dmy6_gqt.js +138 -0
- package/dist/client/assets/{PdfPreview-mO9WS01q.js → PdfPreview-fDxKh6hP.js} +1 -1
- package/dist/client/assets/{ProjectIconPickerDialog-B0q_r5dX.js → ProjectIconPickerDialog-CsjMKq7h.js} +1 -1
- package/dist/client/assets/{ProjectNavigationDialogs-DwWYbB1A.js → ProjectNavigationDialogs-_JY0yVob.js} +1 -1
- package/dist/client/assets/{ProjectSettings-BpPFgdoj.js → ProjectSettings-DXGA-lmB.js} +1 -1
- package/dist/client/assets/ProjectWorkspace-mCYjyc6e.js +32 -0
- package/dist/client/assets/{SelectionHistoryDialog-pWMI5izu.js → SelectionHistoryDialog-D8CeqjLD.js} +1 -1
- package/dist/client/assets/{SystemMetricsDialog-BmlO7oNg.js → SystemMetricsDialog-BZx7ZMQt.js} +1 -1
- package/dist/client/assets/{TagManagementDialog-h4Ves4FR.js → TagManagementDialog-4R1Gs43j.js} +1 -1
- package/dist/client/assets/{WordCountDialog-DlBSP4y7.js → WordCountDialog-C-MCscAu.js} +1 -1
- package/dist/client/assets/check-Jf8WBxDX.js +1 -0
- package/dist/client/assets/{editor-DZS7-wrd.js → editor-B9HNwtsd.js} +1 -1
- package/dist/client/assets/hard-drive-Bsk-RETn.js +1 -0
- package/dist/client/assets/{index-teah8iB2.js → index-B6rP7QsM.js} +4 -4
- package/dist/client/assets/{index-i5IY_PMw.js → index-Csp5J5aI.js} +1 -1
- package/dist/client/assets/index-DGZNAyxW.css +1 -0
- package/dist/client/assets/{key-round-D8sCqL2b.js → key-round-DqptHHKC.js} +1 -1
- package/dist/client/assets/{minimize-2-6tf519Ts.js → minimize-2-92UqFWI9.js} +1 -1
- package/dist/client/assets/{minus-CqvESp9M.js → minus-bx4ZLZnb.js} +1 -1
- package/dist/client/assets/{plus-DIrweesj.js → plus-DQg_bV50.js} +1 -1
- package/dist/client/assets/{refresh-cw-BDcwKu_d.js → refresh-cw-BoMEkk5J.js} +1 -1
- package/dist/client/assets/{search-C9_Jyrnx.js → search-UZspmceH.js} +1 -1
- package/dist/client/assets/{sigma-p9-fBP0d.js → sigma-C0IvFdKV.js} +1 -1
- package/dist/client/assets/{spellCheck-Y0RlmXbl.js → spellCheck-DyKIHf5C.js} +1 -1
- package/dist/client/assets/{tags-DjF3z21M.js → tags-BTUtvaAc.js} +1 -1
- package/dist/client/assets/{type-CNrDJnzR.js → type-XvvfEJRs.js} +1 -1
- package/dist/client/assets/{user-plus-C7exNawX.js → user-plus-Chr9T97G.js} +1 -1
- package/dist/client/assets/x-DlFXD9Vl.js +1 -0
- package/dist/client/index.html +2 -2
- package/dist/client/pdf-download.svg +2 -0
- package/dist/client/pdf-file.svg +19 -0
- package/dist/client/tex-file.svg +7 -0
- package/dist/server/cli.js +5 -2
- package/dist/server/routes/projectFiles.js +6 -1
- package/package.json +4 -3
- package/dist/client/assets/Dashboard-DtHSc55D.js +0 -2
- package/dist/client/assets/LatexEditor-BYWWx5Km.js +0 -138
- package/dist/client/assets/ProjectWorkspace-CI2zKon5.js +0 -32
- package/dist/client/assets/check-BAdi_Lxq.js +0 -1
- package/dist/client/assets/hard-drive-DP2OHKMC.js +0 -1
- package/dist/client/assets/index-CBrIrzgg.css +0 -1
- package/dist/client/assets/x-BEVz0wdw.js +0 -1
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./spellCheck-DyKIHf5C.js","./index-B6rP7QsM.js","./react-BVUjbTTn.js","./index-DGZNAyxW.css","./check-Jf8WBxDX.js","./x-DlFXD9Vl.js","./search-UZspmceH.js","./user-plus-Chr9T97G.js","./refresh-cw-BoMEkk5J.js","./LatexEditor-Dmy6_gqt.js","./editor-B9HNwtsd.js","./CitationLibraryDialog-CU2b0xtm.js","./citationLibrary-ZeQPCv5O.js","./plus-DQg_bV50.js","./tags-BTUtvaAc.js","./GitDialog-C2Np1i8v.js","./key-round-DqptHHKC.js","./minus-bx4ZLZnb.js","./minimize-2-92UqFWI9.js","./HistoryDialog-CdoYeLyX.js","./index-Csp5J5aI.js","./hard-drive-Bsk-RETn.js","./SelectionHistoryDialog-D8CeqjLD.js","./ProjectNavigationDialogs-_JY0yVob.js","./ProjectSettings-DXGA-lmB.js","./type-XvvfEJRs.js","./sigma-C0IvFdKV.js","./WordCountDialog-C-MCscAu.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as Le,s as gn,g as ce,h as fe,a as ss,A as Ii,n as $h,l as Ih,r as Ph,_ as Dt,S as Uh,d as rt,i as ys,j as qa,C as ks,M as Xt,e as Wa,k as zh}from"./index-B6rP7QsM.js";import{r as d,u as Xe,j as o,P as _r,d as ao,e as Bh}from"./react-BVUjbTTn.js";import{C as qh}from"./check-Jf8WBxDX.js";import{f as Wh,U as Pi,B as Hh,M as Vh,G as Kh,X as Ss,e as Tr,j as Ui,b as Gh,c as Pl,N as Jh,d as Ha,F as Yh,g as Ul,h as Xh,C as co,a as Zh,T as tn,L as Qh,k as zt,S as zi,D as cr,A as ur,P as zl,i as ef}from"./x-DlFXD9Vl.js";import{S as tf}from"./search-UZspmceH.js";import{U as nf}from"./user-plus-Chr9T97G.js";import{R as sf}from"./refresh-cw-BoMEkk5J.js";const rf=Le("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const uo=Le("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const of=Le("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const ho=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 Bl=Le("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const Bi=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 lf=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 af=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 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 uf=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 df=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 hf=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 ff=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 Va=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 ql=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 pf=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 mf=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 Wl=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 Ka=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 Ga=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 gf=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 wf=Le("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const yf=Le("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const bf=Le("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const xf=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 kf=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 Hl=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 Sf=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 Cf=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"}]]),vf="wrap = false",qi=[{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'}],gt={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,showTooltips:!1,spellCheck:!0,mathPreviewOnHover:!1,vimMode:!1,formatOnCompile:!1,texFmtConfig:vf,texFmtConfigInitialized:!0,openFilesInTabs:!1},jf="texlite-editor-preferences";function Ja(t,e){return gn(`${jf}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function lx(t){return qi.find(e=>e.id===t)?.stack??qi[0].stack}function Vl(t,e){try{const n=JSON.parse(localStorage.getItem(Ja(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:gt.texFmtConfig;return{font:qi.some(i=>i.id===n.font)?n.font:gt.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):gt.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):gt.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:gt.lineWrapping,showTooltips:typeof n.showTooltips=="boolean"?n.showTooltips:gt.showTooltips,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:gt.spellCheck,mathPreviewOnHover:typeof n.mathPreviewOnHover=="boolean"?n.mathPreviewOnHover:gt.mathPreviewOnHover,vimMode:typeof n.vimMode=="boolean"?n.vimMode:gt.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:gt.formatOnCompile,texFmtConfig:r,texFmtConfigInitialized:!0,openFilesInTabs:typeof n.openFilesInTabs=="boolean"?n.openFilesInTabs:gt.openFilesInTabs}}catch{return gt}}function Ef(t,e,n){localStorage.setItem(Ja(t,e),JSON.stringify(n))}function Df(){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 Zt=Df(),_f=/\.(?:tex|bib|cls|sty)$/i,Ya=3e4;let Ct=null,dr=!1,wn=null,Tf=1;const xn=new Map,hr=[];let Pn=null,ms=null;class ft extends Error{constructor(e,n){super(n),this.kind=e,this.name="TexFmtError"}kind}function gi(t){return t instanceof ft}function Ut(t){Ct?.terminate(),Ct=null,dr=!1,wn!==null&&window.clearTimeout(wn),wn=null,Pn=null,hr.length=0,ms=null,Zt.failed(t);for(const e of xn.values())e.timeout!==null&&window.clearTimeout(e.timeout),e.reject(t);xn.clear()}function bs(){if(Pn!==null||hr.length===0)return;let t;try{t=Lf()}catch(s){Ut(s instanceof ft?s:new ft("load","The bundled tex-fmt formatter could not be loaded."));return}if(!dr)return;const e=hr.shift();if(e===void 0)return;const n=xn.get(e);if(!n){bs();return}Pn=e,n.timeout=window.setTimeout(()=>{Pn===e&&Ut(new ft("result","The formatter did not respond within 30 seconds."))},Ya);try{t.postMessage({...n.request,id:e})}catch{Ut(new ft("load","The formatter worker could not receive the source."))}}function Lf(){if(Ct)return Ct;if(typeof Worker>"u"){const t=new ft("load","This browser does not support formatter workers.");throw Zt.failed(t),t}Zt.loading();try{Ct=new Worker(new URL(""+new URL("latexFormatterWorker-BRmsns8a.js",import.meta.url).href,import.meta.url),{type:"module",name:"texlite-latex-formatter"}),wn=window.setTimeout(()=>{dr||Ut(new ft("load","The formatter did not finish loading within 30 seconds."))},Ya)}catch{const t=new ft("load","The bundled tex-fmt formatter could not be loaded.");throw Zt.failed(t),t}return Ct.onmessage=t=>{const e=t.data;if(e&&"type"in e){e.type==="ready"&&(dr=!0,wn!==null&&window.clearTimeout(wn),wn=null,bs());return}if(!e||typeof e.id!="number"){Ut(new ft("result","The formatter worker returned an invalid response."));return}const n=xn.get(e.id);if(n)if(xn.delete(e.id),n.timeout!==null&&window.clearTimeout(n.timeout),Pn===e.id&&(Pn=null),e.ok)Zt.working(),n.resolve(e.result),bs();else{const s=new ft(e.kind,e.message);e.kind==="format"?(Zt.working(),n.reject(s),bs()):(n.reject(s),Ut(s))}},Ct.onerror=()=>{Ut(new ft("load","The bundled tex-fmt formatter could not be loaded."))},Ct.onmessageerror=()=>{Ut(new ft("result","The formatter worker returned an unreadable response."))},Ct}function fo(t){const e=Tf++;return new Promise((n,s)=>{xn.set(e,{request:t,resolve:n,reject:s,timeout:null}),hr.push(e),bs()})}function Rf(t,e=""){return fo({action:"format",source:t,config:e})}async function Af(){Ct&&Zt.getSnapshot().status==="working"||(ms||(ms=fo({action:"probe"}).then(()=>{}).finally(()=>{ms=null})),await ms)}async function ax(){(Ct||xn.size)&&Ut(new ft("load","The formatter runtime was reloaded.")),Zt.loading(),await Af()}function Qs(t){return _f.test(t)}function Nf(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function Ff(t,e){const n=Nf(t),l=(n?t.slice(0,-n.length):t).split(/\r?\n/).find(u=>u.trim())?.match(/^[\t ]*/)?.[0]??"",a=e.replace(/(?:\r?\n)+$/,"");return`${l?a.split(`
|
|
3
|
+
`).map(u=>u&&`${l}${u}`).join(`
|
|
4
|
+
`):a}${n}`}async function wi(t,e,n=0){return fo({action:"diff",source:t,formatted:e,baseOffset:n})}function Of(t,e=null){const n=Kl(t),r=e==="succeeded"||e===null&&$f(t)?[]:Gl(n.filter(Jl)),i=Kl(Mf(t));return{warnings:Gl(i.filter(a=>!Jl(a)&&If(a))),errors:r}}function Kl(t){return t.split(`
|
|
5
|
+
`).map(e=>e.trim()).filter(Boolean)}function Gl(t){return[...new Set(t)]}function Mf(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 $f(t){return/Latexmk: All targets .* are up-to-date/i.test(t)&&/Output written on .*\.pdf/i.test(t)}function Jl(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 If(t){return/\bwarnings?\b|overfull|underfull|badness/i.test(t)}const Yl=1,Xl=2,yi=4,bi=8,Cs=32,Bt=64,it=128,Pf=1<<29,Lr=31,Wi=63,bn=127,Uf=2147483647,Lt=(t,e)=>t>>>e|t<<32-e,zf=t=>Lt(t,2)^Lt(t,13)^Lt(t,22),Bf=t=>Lt(t,6)^Lt(t,11)^Lt(t,25),qf=t=>Lt(t,7)^Lt(t,18)^t>>>3,Wf=t=>Lt(t,17)^Lt(t,19)^t>>>10,Hf=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]),Vf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);class Kf{constructor(){const e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(Vf),this._W=new Uint32Array(e,64,64)}_updateHash(){const e=this._H,n=this._W;for(let h=16;h<64;h++)n[h]=Wf(n[h-2])+n[h-7]+qf(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],u=e[6],f=e[7];for(let h=0,p,w;h<64;h++)p=f+Bf(a)+(a&c^~a&u)+Hf[h]+n[h]>>>0,w=zf(s)+(s&r^s&i^r&i)>>>0,f=u,u=c,c=a,a=l+p>>>0,l=i,i=r,r=s,s=p+w>>>0;e[0]+=s,e[1]+=r,e[2]+=i,e[3]+=l,e[4]+=a,e[5]+=c,e[6]+=u,e[7]+=f}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]|=it<<(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)]|=it<<(3-n%4)*8),this._W[14]=e.byteLength/Pf,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 Gf=t=>new Kf().digest(t);function Jf(t){return Array.from(Gf(new TextEncoder().encode(t)),e=>e.toString(16).padStart(2,"0")).join("")}function Zl(t){return t instanceof Error&&t.name==="AbortError"}function Yf({projectId:t,activeFile:e,content:n,permission:s,revision:r,selection:i,save:l,saveFailureMessage:a,onError:c,onAdded:u,onChanged:f}){const[h,p]=d.useState({filePath:"",comments:[],loading:!1}),[w,g]=d.useState([]),[C,v]=d.useState(!1),[k,B]=d.useState(""),[x,N]=d.useState("file"),[R,T]=d.useState(null),[_,$]=d.useState(!1),[H,ue]=d.useState(""),[Z,V]=d.useState(null),[de,I]=d.useState(!1),[Y,te]=d.useState(""),ne=d.useRef(null),P=d.useRef(null),ge=d.useRef(!1),we=d.useRef(e),Ce=d.useRef(x),ee=d.useRef(l),se=d.useRef(c),b=d.useRef(u),U=d.useRef(f);we.current=e,Ce.current=x,ee.current=l,se.current=c,b.current=u,U.current=f;const Q=h.filePath===e?h.comments:[],xe=h.filePath,ae=xe===e&&!h.loading,ke=async A=>{ne.current?.abort();const O=new AbortController;ne.current=O,we.current===A&&p(S=>S.filePath===A?{...S,loading:!0}:{filePath:"",comments:[],loading:!0});try{const S=await ce(`/api/projects/${t}/comments?path=${encodeURIComponent(A)}`,{signal:O.signal});ne.current===O&&we.current===A&&p({filePath:A,comments:S.comments,loading:!1})}catch(S){!Zl(S)&&ne.current===O&&we.current===A&&p({filePath:A,comments:[],loading:!1})}finally{ne.current===O&&(ne.current=null)}},Ne=async()=>{P.current?.abort();const A=new AbortController;P.current=A,Ce.current==="project"&&(v(!0),B(""));try{const O=await ce(`/api/projects/${t}/comments?scope=project`,{signal:A.signal});P.current===A&&Ce.current==="project"&&g(O.comments)}catch(O){!Zl(O)&&P.current===A&&Ce.current==="project"&&B(fe(O))}finally{P.current===A&&(P.current=null,Ce.current==="project"&&v(!1))}};d.useEffect(()=>{ne.current?.abort(),ne.current=null,P.current?.abort(),P.current=null,T(null),p({filePath:"",comments:[],loading:!1}),g([]),v(!1),B(""),N("file"),$(!1),V(null),te("")},[t]),d.useEffect(()=>{$(!1),V(null),te("")},[e]),d.useEffect(()=>(e?ke(e):p({filePath:"",comments:[],loading:!1}),()=>{ne.current?.abort(),ne.current=null}),[t,e,r]),d.useEffect(()=>{if(x!=="project"){P.current?.abort(),P.current=null,g([]),v(!1),B("");return}return Ne(),()=>{P.current?.abort(),P.current=null}},[t,x,r]);const pe=async A=>{const O=[];we.current===A&&O.push(ke(A)),Ce.current==="project"&&O.push(Ne()),await Promise.all(O)},q=(A,O)=>{e&&(te(""),V({filePath:e,selection:{...A??i},sourceHash:Jf(O??n)}),$(!0))},K=()=>{ge.current||($(!1),V(null),te(""))},De=async()=>{const A=Z;if(!(!H.trim()||!A||ge.current)){ge.current=!0,I(!0),te("");try{if(s!=="read"&&!await ee.current()){te(a);return}await ce(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:A.filePath,content:H,...A.selection,sourceHash:A.sourceHash})}),await pe(A.filePath),$(!1),V(null),ue(""),b.current(),U.current?.()}catch(O){te(fe(O))}finally{ge.current=!1,I(!1)}}},$e=async A=>{try{await ce(`/api/projects/${t}/comments/${A.id}`,{method:"PATCH",body:JSON.stringify({resolved:!A.resolved})}),await pe(A.filePath),U.current?.()}catch(O){se.current(fe(O))}},Se=async(A,O)=>{try{return await ce(`/api/projects/${t}/comments/${A.id}/replies`,{method:"POST",body:JSON.stringify({content:O})}),await pe(A.filePath),U.current?.(),!0}catch(S){return se.current(fe(S)),!1}},je=async(A,O)=>{try{return await ce(`/api/projects/${t}/comments/${A.id}`,{method:"PATCH",body:JSON.stringify({content:O})}),await pe(A.filePath),U.current?.(),!0}catch(S){return se.current(fe(S)),!1}},F=async A=>{try{return await ce(`/api/projects/${t}/comments/${A.id}`,{method:"DELETE"}),await pe(A.filePath),T(O=>O?.id===A.id?null:O),U.current?.(),!0}catch(O){return se.current(fe(O)),!1}},re=async(A,O,S)=>{try{return await ce(`/api/projects/${t}/comments/${A.id}/replies/${O}`,{method:"PATCH",body:JSON.stringify({content:S})}),await pe(A.filePath),U.current?.(),!0}catch(_e){return se.current(fe(_e)),!1}},Ee=async(A,O)=>{try{return await ce(`/api/projects/${t}/comments/${A.id}/replies/${O}`,{method:"DELETE"}),await pe(A.filePath),U.current?.(),!0}catch(S){return se.current(fe(S)),!1}};return{comments:Q,commentsFilePath:xe,commentsReady:ae,reviewComments:x==="file"?Q:w,reviewCommentsLoading:x==="project"&&C,reviewCommentsError:x==="project"?k:"",retryReviewComments:Ne,commentScope:x,setCommentScope:N,focusComment:R,setFocusComment:T,commentOpen:_,openComment:q,closeComment:K,commentText:H,setCommentText:ue,commentSelection:Z?.selection??i,commentSubmitting:de,commentError:Y,addComment:De,toggleComment:$e,replyToComment:Se,editComment:je,deleteComment:F,editCommentReply:re,deleteCommentReply:Ee}}function Xa(t,e){return e.scope==="project"||t.filePath===e.activeFile}function po(t,e,n){return e==="unresolved"?!t.resolved:e==="resolved"?t.resolved:n.some(s=>s.commentId===t.id)}function xi(t,e){return t.filter(n=>Xa(n,e)&&po(n,e.filter,e.unreadMentions))}function Xf(t,e,n=[]){const s=new Set(n.filter(r=>!!r));return t.filter(r=>Xa(r,e)?s.has(r.id)||po(r,e.filter,e.unreadMentions):!1)}function Zf(t,e){return t.filter(n=>n.filePath===e)}function Qf(t,e,n){return!t||t.filePath!==e||n!==e?null:t}function ep(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 tp(t,e,n){return!po({...t,resolved:!t.resolved},e,n)}function np(t,e){if(!e)return 0;const n=t.findIndex(s=>s.id===e);return n<0?0:n+1}function sp(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 rp(t){return t instanceof Error&&t.name==="AbortError"}function ip(t,e,n){const[s,r]=d.useState([]),i=d.useRef(null),l=d.useRef(n);l.current=n;const a=d.useCallback(async(f=!1)=>{i.current?.abort();const h=new AbortController;i.current=h;try{const p=await ce(`/api/projects/${t}/mentions?unread=1&limit=100`,{signal:h.signal});i.current===h&&r(p.mentions)}catch(p){i.current===h&&!rp(p)&&(r([]),f&&l.current(fe(p)))}finally{i.current===h&&(i.current=null)}},[t]);return d.useEffect(()=>(a(),()=>{i.current?.abort(),i.current=null}),[a,e]),{unreadMentions:s,refresh:a,markMentionRead:async f=>{try{return await ce(`/api/projects/${t}/mentions/${encodeURIComponent(f)}/read`,{method:"POST"}),r(h=>h.filter(p=>p.id!==f)),!0}catch(h){return l.current(fe(h)),!1}},markAllMentionsRead:async()=>{if(!s.length)return!0;try{return await ce(`/api/projects/${t}/mentions/read-all`,{method:"POST"}),r([]),!0}catch(f){return l.current(fe(f)),!1}}}}const ut=()=>new Map,Hi=t=>{const e=ut();return t.forEach((n,s)=>{e.set(s,n)}),e},Nt=(t,e,n)=>{let s=t.get(e);return s===void 0&&t.set(e,s=n()),s},op=(t,e)=>{const n=[];for(const[s,r]of t)n.push(e(r,s));return n},lp=(t,e)=>{for(const[n,s]of t)if(e(s,n))return!0;return!1},nn=()=>new Set,ki=t=>t[t.length-1],ap=(t,e)=>{for(let n=0;n<e.length;n++)t.push(e[n])},qt=Array.from,mo=(t,e)=>{for(let n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0},go=(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},Gn=Array.isArray;class wo{constructor(){this._observers=ut()}on(e,n){return Nt(this._observers,e,nn).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 qt((this._observers.get(e)||ut()).values()).forEach(s=>s(...n))}destroy(){this._observers=ut()}}class Za{constructor(){this._observers=ut()}on(e,n){Nt(this._observers,e,nn).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 qt((this._observers.get(e)||ut()).values()).forEach(s=>s(...n))}destroy(){this._observers=ut()}}const jt=Math.floor,rr=Math.abs,yo=(t,e)=>t<e?t:e,vn=(t,e)=>t>e?t:e,up=Math.pow,Qa=t=>t!==0?t<0:1/t<0,fr=Number.MAX_SAFE_INTEGER,Ql=Number.MIN_SAFE_INTEGER,dp=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&jt(t)===t),ec=String.fromCharCode,hp=t=>t.toLowerCase(),fp=/^\s*/g,pp=t=>t.replace(fp,""),mp=/([A-Z])/g,ea=(t,e)=>pp(t.replace(mp,n=>`${e}${hp(n)}`)),gp=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},vs=typeof TextEncoder<"u"?new TextEncoder:null,wp=t=>vs.encode(t),yp=vs?wp:gp;let xs=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});xs&&xs.decode(new Uint8Array).length===1&&(xs=null);const bp=(t,e)=>cp(e,()=>t).join("");class Fs{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const ze=()=>new Fs,bo=t=>{let e=t.cpos;for(let n=0;n<t.bufs.length;n++)e+=t.bufs[n].length;return e},Te=t=>{const e=new Uint8Array(bo(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},xp=(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(vn(n,e)*2),t.cpos=0)},Je=(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},Vi=Je,G=(t,e)=>{for(;e>bn;)Je(t,it|bn&e),e=jt(e/128);Je(t,bn&e)},xo=(t,e)=>{const n=Qa(e);for(n&&(e=-e),Je(t,(e>Wi?it:0)|(n?Bt:0)|Wi&e),e=jt(e/64);e>0;)Je(t,(e>bn?it:0)|bn&e),e=jt(e/128)},Ki=new Uint8Array(3e4),kp=Ki.length/3,Sp=(t,e)=>{if(e.length<kp){const n=vs.encodeInto(e,Ki).written||0;G(t,n);for(let s=0;s<n;s++)Je(t,Ki[s])}else Ue(t,yp(e))},Cp=(t,e)=>{const n=unescape(encodeURIComponent(e)),s=n.length;G(t,s);for(let r=0;r<s;r++)Je(t,n.codePointAt(r))},Qe=vs&&vs.encodeInto?Sp:Cp,Rr=(t,e)=>{const n=t.cbuf.length,s=t.cpos,r=yo(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(vn(n*2,i)),t.cbuf.set(e.subarray(r)),t.cpos=i)},Ue=(t,e)=>{G(t,e.byteLength),Rr(t,e)},ko=(t,e)=>{xp(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},vp=(t,e)=>ko(t,4).setFloat32(0,e,!1),jp=(t,e)=>ko(t,8).setFloat64(0,e,!1),Ep=(t,e)=>ko(t,8).setBigInt64(0,e,!1),ta=new DataView(new ArrayBuffer(4)),Dp=t=>(ta.setFloat32(0,t),ta.getFloat32(0)===t),js=(t,e)=>{switch(typeof e){case"string":Je(t,119),Qe(t,e);break;case"number":dp(e)&&rr(e)<=Uf?(Je(t,125),xo(t,e)):Dp(e)?(Je(t,124),vp(t,e)):(Je(t,123),jp(t,e));break;case"bigint":Je(t,122),Ep(t,e);break;case"object":if(e===null)Je(t,126);else if(Gn(e)){Je(t,117),G(t,e.length);for(let n=0;n<e.length;n++)js(t,e[n])}else if(e instanceof Uint8Array)Je(t,116),Ue(t,e);else{Je(t,118);const n=Object.keys(e);G(t,n.length);for(let s=0;s<n.length;s++){const r=n[s];Qe(t,r),js(t,e[r])}}break;case"boolean":Je(t,e?120:121);break;default:Je(t,127)}};class na extends Fs{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&G(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const sa=t=>{t.count>0&&(xo(t.encoder,t.count===1?t.s:-t.s),t.count>1&&G(t.encoder,t.count-2))};class ir{constructor(){this.encoder=new Fs,this.s=0,this.count=0}write(e){this.s===e?this.count++:(sa(this),this.count=1,this.s=e)}toUint8Array(){return sa(this),Te(this.encoder)}}const ra=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);xo(t.encoder,e),t.count>1&&G(t.encoder,t.count-2)}};class Si{constructor(){this.encoder=new Fs,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(ra(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return ra(this),Te(this.encoder)}}class _p{constructor(){this.sarr=[],this.s="",this.lensE=new ir}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 Fs;return this.sarr.push(this.s),this.s="",Qe(e,this.sarr.join("")),Rr(e,this.lensE.toUint8Array()),Te(e)}}const Et=t=>new Error(t),vt=()=>{throw Et("Method unimplemented")},pt=()=>{throw Et("Unexpected case")},tc=Et("Unexpected end of array"),nc=Et("Integer out of Range");class Ar{constructor(e){this.arr=e,this.pos=0}}const on=t=>new Ar(t),Gi=t=>t.pos!==t.arr.length,Tp=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},tt=t=>Tp(t,le(t)),Jn=t=>t.arr[t.pos++],le=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&bn)*n,n*=128,r<it)return e;if(e>fr)throw nc}throw tc},So=t=>{let e=t.arr[t.pos++],n=e&Wi,s=64;const r=(e&Bt)>0?-1:1;if((e&it)===0)return r*n;const i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],n=n+(e&bn)*s,s*=128,e<it)return r*n;if(n>fr)throw nc}throw tc},Lp=t=>{let e=le(t);if(e===0)return"";{let n=String.fromCodePoint(Jn(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(Jn(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))}},Rp=t=>xs.decode(tt(t)),Ie=xs?Rp:Lp,Co=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},Ap=t=>Co(t,4).getFloat32(0,!1),Np=t=>Co(t,8).getFloat64(0,!1),Fp=t=>Co(t,8).getBigInt64(0,!1),Op=[t=>{},t=>null,So,Ap,Np,Fp,t=>!1,t=>!0,Ie,t=>{const e=le(t),n={};for(let s=0;s<e;s++){const r=Ie(t);n[r]=Es(t)}return n},t=>{const e=le(t),n=[];for(let s=0;s<e;s++)n.push(Es(t));return n},tt],Es=t=>Op[127-Jn(t)](t);class ia extends Ar{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Gi(this)?this.count=le(this)+1:this.count=-1),this.count--,this.s}}class or extends Ar{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=So(this);const e=Qa(this.s);this.count=1,e&&(this.s=-this.s,this.count=le(this)+2)}return this.count--,this.s}}class Ci extends Ar{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=So(this),n=e&1;this.diff=jt(e/2),this.count=1,n&&(this.count=le(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Mp{constructor(e){this.decoder=new or(e),this.str=Ie(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 $p=crypto.getRandomValues.bind(crypto),sc=()=>$p(new Uint32Array(1))[0],Ip="10000000-1000-4000-8000"+-1e11,Pp=()=>Ip.replace(/[018]/g,t=>(t^sc()&15>>t/4).toString(16)),sn=Date.now,Yn=t=>new Promise(t);Promise.all.bind(Promise);const oa=t=>t===void 0?null:t;class Up{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let rc=new Up,vo=!0;try{typeof localStorage<"u"&&localStorage&&(rc=localStorage,vo=!1)}catch{}const ic=rc,zp=t=>vo||addEventListener("storage",t),Bp=t=>vo||removeEventListener("storage",t),Ds=Symbol("Equality"),oc=(t,e)=>t===e||!!t?.[Ds]?.(e)||!1,qp=t=>typeof t=="object",Wp=Object.assign,Hp=Object.keys,Vp=(t,e)=>{for(const n in t)e(t[n],n)},Kp=(t,e)=>{const n=[];for(const s in t)n.push(e(t[s],s));return n},pr=t=>Hp(t).length,Gp=t=>{for(const e in t)return!1;return!0},Os=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},jo=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Jp=(t,e)=>t===e||pr(t)===pr(e)&&Os(t,(n,s)=>(n!==void 0||jo(e,s))&&oc(e[s],n)),Yp=Object.freeze,lc=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&lc(t[e])}return Yp(t)},Eo=(t,e,n=0)=>{try{for(;n<t.length;n++)t[n](...e)}finally{n<t.length&&Eo(t,e,n+1)}},Xp=t=>t,Un=(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[Ds]!=null)return t[Ds](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)||!Un(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(pr(t)!==pr(e))return!1;for(const n in t)if(!jo(t,n)||!Un(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(!Un(t[n],e[n]))return!1;break;default:return!1}return!0},Zp=(t,e)=>e.includes(t);var ac={};const rn=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"&&!rn;let Tt;const Qp=()=>{if(Tt===void 0)if(rn){Tt=ut();const t=process.argv;let e=null;for(let n=0;n<t.length;n++){const s=t[n];s[0]==="-"?(e!==null&&Tt.set(e,""),e=s):e!==null&&(Tt.set(e,s),e=null)}e!==null&&Tt.set(e,"")}else typeof location=="object"?(Tt=ut(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,n]=t.split("=");Tt.set(`--${ea(e,"-")}`,n),Tt.set(`-${ea(e,"-")}`,n)}})):Tt=ut();return Tt},Ji=t=>Qp().has(t),mr=t=>oa(rn?ac[t.toUpperCase().replaceAll("-","_")]:ic.getItem(t)),uc=t=>Ji("--"+t)||mr(t)!==null,em=uc("production"),tm=rn&&Zp(ac.FORCE_COLOR,["true","1","2"]),nm=tm||!Ji("--no-colors")&&!uc("no-color")&&(!rn||process.stdout.isTTY)&&(!rn||Ji("--color")||mr("COLORTERM")!==null||(mr("TERM")||"").includes("color")),dc=t=>new Uint8Array(t),sm=(t,e,n)=>new Uint8Array(t,e,n),rm=t=>new Uint8Array(t),im=t=>{let e="";for(let n=0;n<t.byteLength;n++)e+=ec(t[n]);return btoa(e)},om=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),lm=t=>{const e=atob(t),n=dc(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n},am=t=>{const e=Buffer.from(t,"base64");return sm(e.buffer,e.byteOffset,e.byteLength)},cm=cc?im:om,um=cc?lm:am,dm=t=>{const e=dc(t.byteLength);return e.set(t),e};class hm{constructor(e,n){this.left=e,this.right=n}}const Pt=(t,e)=>new hm(t,e),fm=(t,e)=>t.forEach(n=>e(n.left,n.right)),la=t=>t.next()>=.5,vi=(t,e,n)=>jt(t.next()*(n+1-e)+e),hc=(t,e,n)=>jt(t.next()*(n+1-e)+e),Do=(t,e,n)=>hc(t,e,n),pm=t=>ec(Do(t,97,122)),mm=(t,e=0,n=20)=>{const s=Do(t,e,n);let r="";for(let i=0;i<s;i++)r+=pm(t);return r},ji=(t,e)=>e[Do(t,0,e.length-1)],gm=Symbol("0schema");class wm{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(bp(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return e.join(`
|
|
6
|
+
`)}}const Yi=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[Ds]?oc(t,e):Gn(t)?mo(t,n=>go(e,s=>Yi(n,s))):qp(t)?Os(t,(n,s)=>Yi(n,e[s])):!1;class ot{static _dilutes=!1;extends(e){let[n,s]=[this.shape,e.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Yi(n,s)}equals(e){return this.constructor===e.constructor&&Un(this.shape,e.shape)}[gm](){return!0}[Ds](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){vt()}get nullable(){return rs(this,$r)}get optional(){return new mc(this)}cast(e){return aa(e,this),e}expect(e){return aa(e,this),e}}class _o extends ot{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 Ve=(t,e=null)=>new _o(t,e);Ve(_o);class To extends ot{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 Ze=t=>new To(t);Ve(To);class Nr extends ot{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 Fr=(...t)=>new Nr(t),fc=Ve(Nr),ym=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),pc=t=>{if(Xn.check(t))return[ym(t)];if(fc.check(t))return t.shape.map(e=>e+"");if(vc.check(t))return["[+-]?\\d+.?\\d*"];if(jc.check(t))return[".*"];if(gr.check(t))return t.shape.map(pc).flat(1);pt()};class bm extends ot{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(pc).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}}Ve(bm);const xm=Symbol("optional");class mc extends ot{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[xm](){return!0}}const km=Ve(mc);class Sm extends ot{check(e,n){return n?.extend(null,"never",typeof e),!1}}Ve(Sm);class Or extends ot{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}static _dilutes=!0;get partial(){return new Or(this.shape,!0)}check(e,n){return e==null?(n?.extend(null,"object","null"),!1):Os(this.shape,(s,r)=>{const i=this._isPartial&&!jo(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 Cm=t=>new Or(t),vm=Ve(Or),jm=Ze(t=>t!=null&&(t.constructor===Object||t.constructor==null));class gc extends ot{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&Os(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 wc=(t,e)=>new gc(t,e),Em=Ve(gc);class yc extends ot{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&Os(this.shape,(s,r)=>{const i=s.check(e[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Dm=(...t)=>new yc(t);Ve(yc);class bc extends ot{constructor(e){super(),this.shape=e.length===1?e[0]:new Lo(e)}check(e,n){const s=Gn(e)&&mo(e,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const xc=(...t)=>new bc(t),_m=Ve(bc),Tm=Ze(t=>Gn(t));class kc extends ot{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 Lm=(t,e=null)=>new kc(t,e);Ve(kc);const Rm=Lm(ot);class Am extends ot{constructor(e){super(),this.len=e.length-1,this.args=Dm(...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 Nm=Ve(Am),Fm=Ze(t=>typeof t=="function");class Om extends ot{constructor(e){super(),this.shape=e}check(e,n){const s=mo(this.shape,r=>r.check(e,n));return!s&&n?.extend(null,"Intersectinon",typeof e),s}}Ve(Om,t=>t.shape.length>0);class Lo extends ot{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,n){const s=go(this.shape,r=>r.check(e,n));return n?.extend(null,"Union",typeof e),s}}const rs=(...t)=>t.findIndex(e=>gr.check(e))>=0?rs(...t.map(e=>_s(e)).map(e=>gr.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new Lo(t),gr=Ve(Lo),Sc=()=>!0,wr=Ze(Sc),Mm=Ve(To,t=>t.shape===Sc),Ro=Ze(t=>typeof t=="bigint"),$m=Ze(t=>t===Ro),Cc=Ze(t=>typeof t=="symbol");Ze(t=>t===Cc);const zn=Ze(t=>typeof t=="number"),vc=Ze(t=>t===zn),Xn=Ze(t=>typeof t=="string"),jc=Ze(t=>t===Xn),Mr=Ze(t=>typeof t=="boolean"),Im=Ze(t=>t===Mr),Ec=Fr(void 0);Ve(Nr,t=>t.shape.length===1&&t.shape[0]===void 0);Fr(void 0);const $r=Fr(null),Pm=Ve(Nr,t=>t.shape.length===1&&t.shape[0]===null);Ve(Uint8Array);Ve(_o,t=>t.shape===Uint8Array);const Um=rs(zn,Xn,$r,Ec,Ro,Mr,Cc);(()=>{const t=xc(wr),e=wc(Xn,wr),n=rs(zn,Xn,$r,Mr,t,e);return t.shape=n,e.shape.values=n,n})();const _s=t=>{if(Rm.check(t))return t;if(jm.check(t)){const e={};for(const n in t)e[n]=_s(t[n]);return Cm(e)}else{if(Tm.check(t))return rs(...t.map(_s));if(Um.check(t))return Fr(t);if(Fm.check(t))return Ve(t)}pt()},aa=em?()=>{}:(t,e)=>{const n=new wm;if(!e.check(t,n))throw Et(`Expected value to be of type ${e.constructor.name}.
|
|
7
|
+
${n.toString()}`)};class zm{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:_s(e),h:n}),this}else(e){return this.if(wr,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 Et("Unhandled pattern")}}}const Bm=t=>new zm(t),Dc=Bm(wr).if(vc,(t,e)=>vi(e,Ql,fr)).if(jc,(t,e)=>mm(e)).if(Im,(t,e)=>la(e)).if($m,(t,e)=>BigInt(vi(e,Ql,fr))).if(gr,(t,e)=>On(e,ji(e,t.shape))).if(vm,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(km.check(r)){if(la(e))continue;r=r.shape}n[s]=Dc(r,e)}return n}).if(_m,(t,e)=>{const n=[],s=hc(e,0,42);for(let r=0;r<s;r++)n.push(On(e,t.shape));return n}).if(fc,(t,e)=>ji(e,t.shape)).if(Pm,(t,e)=>null).if(Nm,(t,e)=>{const n=On(e,t.res);return()=>n}).if(Mm,(t,e)=>On(e,ji(e,[zn,Xn,$r,Ec,Ro,Mr,xc(zn),wc(rs("a","b","c"),zn)]))).if(Em,(t,e)=>{const n={},s=vi(e,0,3);for(let r=0;r<s;r++){const i=On(e,t.shape.keys),l=On(e,t.shape.values);n[i]=l}return n}).done(),On=(t,e)=>Dc(_s(e),t),Ft=typeof document<"u"?document:{},qm=t=>Ft.createElement(t),Wm=()=>Ft.createDocumentFragment();Ze(t=>t.nodeType===Qm);const Hm=t=>Ft.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const Vm=(t,e)=>(fm(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),Km=t=>{const e=Wm();for(let n=0;n<t.length;n++)_c(e,t[n]);return e},Gm=(t,e)=>(_c(t,Km(e)),t),cx=(t,e=[],n=[])=>Gm(Vm(qm(t),e),n);Ze(t=>t.nodeType===Ym);const ux=Hm;Ze(t=>t.nodeType===Xm);const Jm=t=>op(t,(e,n)=>`${n}:${e};`).join(""),_c=(t,e)=>t.appendChild(e),Ym=Ft.ELEMENT_NODE,Xm=Ft.TEXT_NODE;Ft.CDATA_SECTION_NODE;Ft.COMMENT_NODE;const Zm=Ft.DOCUMENT_NODE;Ft.DOCUMENT_TYPE_NODE;const Qm=Ft.DOCUMENT_FRAGMENT_NODE;Ze(t=>t.nodeType===Zm);const Wt=Symbol,Tc=Wt(),Lc=Wt(),eg=Wt(),tg=Wt(),ng=Wt(),Rc=Wt(),sg=Wt(),Ao=Wt(),rg=Wt(),ig=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},og={[Tc]:Pt("font-weight","bold"),[Lc]:Pt("font-weight","normal"),[eg]:Pt("color","blue"),[ng]:Pt("color","green"),[tg]:Pt("color","grey"),[Rc]:Pt("color","red"),[sg]:Pt("color","purple"),[Ao]:Pt("color","orange"),[rg]:Pt("color","black")},lg=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=ut();let r=[],i=0;for(;i<t.length;i++){const l=t[i],a=og[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=Jm(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},Ac=nm?lg:ig,ag=(...t)=>{console.log(...Ac(t)),Fc.forEach(e=>e.print(t))},Nc=(...t)=>{console.warn(...Ac(t)),t.unshift(Ao),Fc.forEach(e=>e.print(t))},Fc=nn(),Oc=t=>({[Symbol.iterator](){return this},next:t}),cg=(t,e)=>Oc(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),Ei=(t,e)=>Oc(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class Ir{constructor(e,n){this.clock=e,this.len=n}}class is{constructor(){this.clients=new Map}}const Zn=(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,u=s[c];c<s.length&&u.clock<a;u=s[++c])Yc(t,i,u.clock,u.len,n)}}),ug=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=jt((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},Ms=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&ug(n,e.clock)!==null},No=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 Ir(r.clock,vn(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},Xi=t=>{const e=new is;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++)ap(i,t[l].clients.get(r)||[]);e.clients.set(r,i)}});return No(e),e},Ts=(t,e,n,s)=>{Nt(t.clients,e,()=>[]).push(new Ir(n,s))},dg=()=>new is,hg=t=>{const e=dg();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 u=n[i+1];i+1<n.length&&u.deleted;u=n[++i+1])c+=u.length;r.push(new Ir(a,c))}}r.length>0&&e.clients.set(s,r)}),e},os=(t,e)=>{G(t.restEncoder,e.clients.size),qt(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),G(t.restEncoder,n);const r=s.length;G(t.restEncoder,r);for(let i=0;i<r;i++){const l=s[i];t.writeDsClock(l.clock),t.writeDsLen(l.len)}})},Fo=t=>{const e=new is,n=le(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=le(t.restDecoder),i=le(t.restDecoder);if(i>0){const l=Nt(e.clients,r,()=>[]);for(let a=0;a<i;a++)l.push(new Ir(t.readDsClock(),t.readDsLen()))}}return e},ca=(t,e,n)=>{const s=new is,r=le(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const l=le(t.restDecoder),a=le(t.restDecoder),c=n.clients.get(l)||[],u=qe(n,l);for(let f=0;f<a;f++){const h=t.readDsClock(),p=h+t.readDsLen();if(h<u){u<p&&Ts(s,l,u,p-u);let w=Rt(c,h),g=c[w];for(!g.deleted&&g.id.clock<h&&(c.splice(w+1,0,jr(e,g,h-g.id.clock)),w++);w<c.length&&(g=c[w++],g.id.clock<p);)g.deleted||(p<g.id.clock+g.length&&c.splice(w,0,jr(e,g,p-g.id.clock)),g.delete(e))}else Ts(s,l,h,p-h)}}if(s.clients.size>0){const i=new kn;return G(i.restEncoder,0),os(i,s),i.toUint8Array()}return null},Mc=sc;class jn extends wo{constructor({guid:e=Pp(),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=Mc(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new Gc,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=Yn(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>Yn(u=>{const f=h=>{(h===void 0||h===!0)&&(this.off("sync",f),u())};this.on("sync",f)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&Ae(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(qt(this.subdocs).map(e=>e.guid))}transact(e,n=null){return Ae(this,e,n)}get(e,n=Ye){const s=Nt(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==Ye&&r!==n)if(r===Ye){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,Wn)}getText(e=""){return this.get(e,ts)}getMap(e=""){return this.get(e,es)}getXmlElement(e=""){return this.get(e,ns)}getXmlFragment(e=""){return this.get(e,Sn)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,qt(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new jn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,Ae(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 $c{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return le(this.restDecoder)}readDsLen(){return le(this.restDecoder)}}class Ic extends $c{readLeftID(){return me(le(this.restDecoder),le(this.restDecoder))}readRightID(){return me(le(this.restDecoder),le(this.restDecoder))}readClient(){return le(this.restDecoder)}readInfo(){return Jn(this.restDecoder)}readString(){return Ie(this.restDecoder)}readParentInfo(){return le(this.restDecoder)===1}readTypeRef(){return le(this.restDecoder)}readLen(){return le(this.restDecoder)}readAny(){return Es(this.restDecoder)}readBuf(){return dm(tt(this.restDecoder))}readJSON(){return JSON.parse(Ie(this.restDecoder))}readKey(){return Ie(this.restDecoder)}}class fg{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=le(this.restDecoder),this.dsCurrVal}readDsLen(){const e=le(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Qn extends fg{constructor(e){super(e),this.keys=[],le(e),this.keyClockDecoder=new Ci(tt(e)),this.clientDecoder=new or(tt(e)),this.leftClockDecoder=new Ci(tt(e)),this.rightClockDecoder=new Ci(tt(e)),this.infoDecoder=new ia(tt(e),Jn),this.stringDecoder=new Mp(tt(e)),this.parentInfoDecoder=new ia(tt(e),Jn),this.typeRefDecoder=new or(tt(e)),this.lenDecoder=new or(tt(e))}readLeftID(){return new Bn(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Bn(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 Es(this.restDecoder)}readBuf(){return tt(this.restDecoder)}readJSON(){return Es(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 Pc{constructor(){this.restEncoder=ze()}toUint8Array(){return Te(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){G(this.restEncoder,e)}writeDsLen(e){G(this.restEncoder,e)}}class $s extends Pc{writeLeftID(e){G(this.restEncoder,e.client),G(this.restEncoder,e.clock)}writeRightID(e){G(this.restEncoder,e.client),G(this.restEncoder,e.clock)}writeClient(e){G(this.restEncoder,e)}writeInfo(e){Vi(this.restEncoder,e)}writeString(e){Qe(this.restEncoder,e)}writeParentInfo(e){G(this.restEncoder,e?1:0)}writeTypeRef(e){G(this.restEncoder,e)}writeLen(e){G(this.restEncoder,e)}writeAny(e){js(this.restEncoder,e)}writeBuf(e){Ue(this.restEncoder,e)}writeJSON(e){Qe(this.restEncoder,JSON.stringify(e))}writeKey(e){Qe(this.restEncoder,e)}}class Uc{constructor(){this.restEncoder=ze(),this.dsCurrVal=0}toUint8Array(){return Te(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,G(this.restEncoder,n)}writeDsLen(e){e===0&&pt(),G(this.restEncoder,e-1),this.dsCurrVal+=e}}class kn extends Uc{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Si,this.clientEncoder=new ir,this.leftClockEncoder=new Si,this.rightClockEncoder=new Si,this.infoEncoder=new na(Vi),this.stringEncoder=new _p,this.parentInfoEncoder=new na(Vi),this.typeRefEncoder=new ir,this.lenEncoder=new ir}toUint8Array(){const e=ze();return G(e,0),Ue(e,this.keyClockEncoder.toUint8Array()),Ue(e,this.clientEncoder.toUint8Array()),Ue(e,this.leftClockEncoder.toUint8Array()),Ue(e,this.rightClockEncoder.toUint8Array()),Ue(e,Te(this.infoEncoder)),Ue(e,this.stringEncoder.toUint8Array()),Ue(e,Te(this.parentInfoEncoder)),Ue(e,this.typeRefEncoder.toUint8Array()),Ue(e,this.lenEncoder.toUint8Array()),Rr(e,Te(this.restEncoder)),Te(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){js(this.restEncoder,e)}writeBuf(e){Ue(this.restEncoder,e)}writeJSON(e){js(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 pg=(t,e,n,s)=>{s=vn(s,e[0].id.clock);const r=Rt(e,s);G(t.restEncoder,e.length-r),t.writeClient(n),G(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)},Oo=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{qe(e,i)>r&&s.set(i,r)}),Pr(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),G(t.restEncoder,s.size),qt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{pg(t,e.clients.get(r),r,i)})},mg=(t,e)=>{const n=ut(),s=le(t.restDecoder);for(let r=0;r<s;r++){const i=le(t.restDecoder),l=new Array(i),a=t.readClient();let c=le(t.restDecoder);n.set(a,{i:0,refs:l});for(let u=0;u<i;u++){const f=t.readInfo();switch(Lr&f){case 0:{const h=t.readLen();l[u]=new wt(me(a,c),h),c+=h;break}case 10:{const h=le(t.restDecoder);l[u]=new yt(me(a,c),h),c+=h;break}default:{const h=(f&(Bt|it))===0,p=new Oe(me(a,c),null,(f&it)===it?t.readLeftID():null,null,(f&Bt)===Bt?t.readRightID():null,h?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,h&&(f&Cs)===Cs?t.readString():null,gu(t,f));l[u]=p,c+=p.length}}}}return n},gg=(t,e,n)=>{const s=[];let r=qt(n.keys()).sort((w,g)=>w-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let w=n.get(r[r.length-1]);for(;w.refs.length===w.i;)if(r.pop(),r.length>0)w=n.get(r[r.length-1]);else return null;return w};let l=i();if(l===null)return null;const a=new Gc,c=new Map,u=(w,g)=>{const C=c.get(w);(C==null||C>g)&&c.set(w,g)};let f=l.refs[l.i++];const h=new Map,p=()=>{for(const w of s){const g=w.id.client,C=n.get(g);C?(C.i--,a.clients.set(g,C.refs.slice(C.i)),n.delete(g),C.i=0,C.refs=[]):a.clients.set(g,[w]),r=r.filter(v=>v!==g)}s.length=0};for(;;){if(f.constructor!==yt){const g=Nt(h,f.id.client,()=>qe(e,f.id.client))-f.id.clock;if(g<0)s.push(f),u(f.id.client,f.id.clock-1),p();else{const C=f.getMissing(t,e);if(C!==null){s.push(f);const v=n.get(C)||{refs:[],i:0};if(v.refs.length===v.i)u(C,qe(e,C)),p();else{f=v.refs[v.i++];continue}}else(g===0||g<f.length)&&(f.integrate(t,g),h.set(f.id.client,f.id.clock+f.length))}}if(s.length>0)f=s.pop();else if(l!==null&&l.i<l.refs.length)f=l.refs[l.i++];else{if(l=i(),l===null)break;f=l.refs[l.i++]}}if(a.clients.size>0){const w=new kn;return Oo(w,a,new Map),G(w.restEncoder,0),{missing:c,update:w.toUint8Array()}}return null},wg=(t,e)=>Oo(t,e.doc.store,e.beforeState),yg=(t,e,n,s=new Qn(t))=>Ae(e,r=>{r.local=!1;let i=!1;const l=r.doc,a=l.store,c=mg(s,l),u=gg(r,a,c),f=a.pendingStructs;if(f){for(const[p,w]of f.missing)if(w<qe(a,p)){i=!0;break}if(u){for(const[p,w]of u.missing){const g=f.missing.get(p);(g==null||g>w)&&f.missing.set(p,w)}f.update=br([f.update,u.update])}}else a.pendingStructs=u;const h=ca(s,r,a);if(a.pendingDs){const p=new Qn(on(a.pendingDs));le(p.restDecoder);const w=ca(p,r,a);h&&w?a.pendingDs=br([h,w]):a.pendingDs=h||w}else a.pendingDs=h;if(i){const p=a.pendingStructs.update;a.pendingStructs=null,zc(r.doc,p)}},n,!1),zc=(t,e,n,s=Qn)=>{const r=on(e);yg(r,t,n,new s(r))},Bc=(t,e,n)=>zc(t,e,n,Ic),bg=(t,e,n=new Map)=>{Oo(t,e.store,n),os(t,hg(e.store))},xg=(t,e=new Uint8Array([0]),n=new kn)=>{const s=qc(e);bg(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(Pg(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===$s)return $g(r.map((i,l)=>l===0?i:zg(i)));if(n.constructor===kn)return br(r)}return r[0]},Mo=(t,e)=>xg(t,e,new $s),kg=t=>{const e=new Map,n=le(t.restDecoder);for(let s=0;s<n;s++){const r=le(t.restDecoder),i=le(t.restDecoder);e.set(r,i)}return e},qc=t=>kg(new $c(on(t))),Wc=(t,e)=>(G(t.restEncoder,e.size),qt(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{G(t.restEncoder,n),G(t.restEncoder,s)}),t),Sg=(t,e)=>Wc(t,Pr(e.store)),Cg=(t,e=new Uc)=>(t instanceof Map?Wc(e,t):Sg(e,t),e.toUint8Array()),vg=t=>Cg(t,new Pc);class jg{constructor(){this.l=[]}}const ua=()=>new jg,da=(t,e)=>t.l.push(e),ha=(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.")},Hc=(t,e,n)=>Eo(t.l,[e,n]);class Bn{constructor(e,n){this.client=e,this.clock=n}}const In=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,me=(t,e)=>new Bn(t,e),Vc=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw pt()},yr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class Kc{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const dx=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},hx=t=>new Kc(t.type==null?null:me(t.type.client,t.type.clock),t.tname??null,t.item==null?null:me(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class Eg{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const Dg=(t,e,n=0)=>new Eg(t,e,n),er=(t,e,n)=>{let s=null,r=null;return t._item===null?r=Vc(t):s=me(t._item.id.client,t._item.id.clock),new Kc(s,r,e,n)},fx=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return er(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return er(t,me(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return er(t,s.lastId,n);s=s.right}return er(t,null,n)},_g=(t,e)=>{const n=qn(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},px=(t,e,n=!0)=>{const s=e.store,r=t.item,i=t.type,l=t.tname,a=t.assoc;let c=null,u=0;if(r!==null){if(qe(s,r.client)<=r.clock)return null;const f=n?to(s,r):_g(s,r),h=f.item;if(!(h instanceof Oe))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:f.diff+(a>=0?0:1);let p=h.left;for(;p!==null;)!p.deleted&&p.countable&&(u+=p.length),p=p.left}}else{if(l!==null)c=e.get(l);else if(i!==null){if(qe(s,i.client)<=i.clock)return null;const{item:f}=n?to(s,i):{item:qn(s,i)};if(f instanceof Oe&&f.content instanceof Ot)c=f.content.type;else return null}else throw pt();a>=0?u=c._length:u=0}return Dg(c,u,t.assoc)},mx=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&In(t.item,e.item)&&In(t.type,e.type)&&t.assoc===e.assoc,Mn=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Ms(e.ds,t.id),Zi=(t,e)=>{const n=Nt(t.meta,Zi,nn),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<qe(s,i)&&ct(t,me(i,r))}),Zn(t,e.ds,r=>{}),n.add(e))};class Gc{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Pr=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},Jc=(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 pt()}n.push(e)},Rt=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let l=jt(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=jt((n+s)/2)}throw pt()},Tg=(t,e)=>{const n=t.clients.get(e.client);return n[Rt(n,e.clock)]},qn=Tg,Qi=(t,e,n)=>{const s=Rt(e,n),r=e[s];return r.id.clock<n&&r instanceof Oe?(e.splice(s+1,0,jr(t,r,n-r.id.clock)),s+1):s},ct=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[Qi(t,n,e.clock)]},fa=(t,e,n)=>{const s=e.clients.get(n.client),r=Rt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==wt&&s.splice(r+1,0,jr(t,i,n.clock-i.id.clock+1)),i},Lg=(t,e,n)=>{const s=t.clients.get(e.id.client);s[Rt(s,e.id.clock)]=n},Yc=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let l=Qi(t,e,n),a;do a=e[l++],i<a.id.clock+a.length&&Qi(t,e,i),r(a);while(l<e.length&&e[l].id.clock<i)};class Rg{constructor(e,n,s){this.doc=e,this.deleteSet=new is,this.beforeState=Pr(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 pa=(t,e)=>e.deleteSet.clients.size===0&&!lp(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(No(e.deleteSet),wg(t,e),os(t,e.deleteSet),!0),ma=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&Nt(t.changed,e,nn).add(n)},lr=(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 Oe&&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},Ag=(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 u=Rt(i,a.clock),f=i[u];u<i.length&&f.id.clock<c;f=i[++u]){const h=i[u];if(a.clock+a.len<=h.id.clock)break;h instanceof Oe&&h.deleted&&!h.keep&&n(h)&&h.gc(e,!1)}}}},Ng=(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=yo(r.length-1,1+Rt(r,l.clock+l.len-1));for(let c=a,u=r[c];c>0&&u.id.clock>=l.clock;u=r[c])c-=1+lr(r,c)}})},Xc=(t,e)=>{if(e<t.length){const n=t[e],s=n.doc,r=s.store,i=n.deleteSet,l=n._mergeStructs;try{No(i),n.afterState=Pr(n.doc.store),s.emit("beforeObserverCalls",[n,s]);const a=[];n.changed.forEach((c,u)=>a.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(f=>f.target._item===null||!f.target._item.deleted),c.forEach(f=>{f.currentTarget=u,f._path=null}),c.sort((f,h)=>f.path.length-h.path.length),a.push(()=>{Hc(u._dEH,c,n)}))}),a.push(()=>s.emit("afterTransaction",[n,s])),a.push(()=>{n._needFormattingCleanup&&tw(n)})}),Eo(a,[])}finally{s.gc&&Ag(i,r,s.gcFilter),Ng(i,r),n.afterState.forEach((f,h)=>{const p=n.beforeState.get(h)||0;if(p!==f){const w=r.clients.get(h),g=vn(Rt(w,p),1);for(let C=w.length-1;C>=g;)C-=1+lr(w,C)}});for(let f=l.length-1;f>=0;f--){const{client:h,clock:p}=l[f].id,w=r.clients.get(h),g=Rt(w,p);g+1<w.length&&lr(w,g+1)>1||g>0&&lr(w,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(ag(Ao,Tc,"[yjs] ",Lc,Rc,"Changed the client-id because another client seems to be using it."),s.clientID=Mc()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const f=new $s;pa(f,n)&&s.emit("update",[f.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const f=new kn;pa(f,n)&&s.emit("updateV2",[f.toUint8Array(),n.origin,s,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:u}=n;(a.size>0||u.size>0||c.size>0)&&(a.forEach(f=>{f.clientID=s.clientID,f.collectionid==null&&(f.collectionid=s.collectionid),s.subdocs.add(f)}),u.forEach(f=>s.subdocs.delete(f)),s.emit("subdocs",[{loaded:c,added:a,removed:u},s,n]),u.forEach(f=>f.destroy())),t.length<=e+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,t])):Xc(t,e+1)}}},Ae=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,l=null;t._transaction===null&&(i=!0,t._transaction=new Rg(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&&Xc(r,0)}}return l};class Fg{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const ga=(t,e,n)=>{Zn(t,n.deletions,s=>{s instanceof Oe&&e.scope.some(r=>r===t.doc||yr(r,s))&&Wo(s,!1)})},wa=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;Ae(r,a=>{for(;e.length>0&&t.currStackItem===null;){const c=r.store,u=e.pop(),f=new Set,h=[];let p=!1;Zn(a,u.insertions,w=>{if(w instanceof Oe){if(w.redone!==null){let{item:g,diff:C}=to(c,w.id);C>0&&(g=ct(a,me(g.id.client,g.id.clock+C))),w=g}!w.deleted&&i.some(g=>g===a.doc||yr(g,w))&&h.push(w)}}),Zn(a,u.deletions,w=>{w instanceof Oe&&i.some(g=>g===a.doc||yr(g,w))&&!Ms(u.insertions,w.id)&&f.add(w)}),f.forEach(w=>{p=mu(a,w,f,u.insertions,t.ignoreRemoteMapChanges,t)!==null||p});for(let w=h.length-1;w>=0;w--){const g=h[w];t.deleteFilter(g)&&(g.delete(a),p=!0)}t.currStackItem=p?u:null}a.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._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 Og extends wo{constructor(e,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:l=!1,doc:a=Gn(e)?e[0].doc:e instanceof jn?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(v=>c.changedParentTypes.has(v)||v===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,f=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():f||this.clear(!1,!0);const p=new is;c.afterState.forEach((v,k)=>{const B=c.beforeState.get(k)||0,x=v-B;x>0&&Ts(p,k,B,x)});const w=sn();let g=!1;if(this.lastChange>0&&w-this.lastChange<this.captureTimeout&&h.length>0&&!u&&!f){const v=h[h.length-1];v.deletions=Xi([v.deletions,c.deleteSet]),v.insertions=Xi([v.insertions,p])}else h.push(new Fg(c.deleteSet,p)),g=!0;!u&&!f&&(this.lastChange=w),Zn(c,c.deleteSet,v=>{v instanceof Oe&&this.scope.some(k=>k===c.doc||yr(k,v))&&Wo(v,!0)});const C=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",C):this.emit("stack-item-updated",C)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=Gn(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof Ye?s.doc!==this.doc:s!==this.doc)&&Nc("[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=>ga(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>ga(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=wa(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=wa(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*Mg(t){const e=le(t.restDecoder);for(let n=0;n<e;n++){const s=le(t.restDecoder),r=t.readClient();let i=le(t.restDecoder);for(let l=0;l<s;l++){const a=t.readInfo();if(a===10){const c=le(t.restDecoder);yield new yt(me(r,i),c),i+=c}else if((Lr&a)!==0){const c=(a&(Bt|it))===0,u=new Oe(me(r,i),null,(a&it)===it?t.readLeftID():null,null,(a&Bt)===Bt?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(a&Cs)===Cs?t.readString():null,gu(t,a));yield u,i+=u.length}else{const c=t.readLen();yield new wt(me(r,i),c),i+=c}}}}class $o{constructor(e,n){this.gen=Mg(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===yt);return this.curr}}class Io{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const $g=t=>br(t,Ic,$s),Ig=(t,e)=>{if(t.constructor===wt){const{client:n,clock:s}=t.id;return new wt(me(n,s+e),t.length-e)}else if(t.constructor===yt){const{client:n,clock:s}=t.id;return new yt(me(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new Oe(me(s,r+e),null,me(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},br=(t,e=Qn,n=kn)=>{if(t.length===1)return t[0];const s=t.map(f=>new e(on(f)));let r=s.map(f=>new $o(f,!0)),i=null;const l=new n,a=new Io(l);for(;r=r.filter(p=>p.curr!==null),r.sort((p,w)=>{if(p.curr.id.client===w.curr.id.client){const g=p.curr.id.clock-w.curr.id.clock;return g===0?p.curr.constructor===w.curr.constructor?0:p.curr.constructor===yt?1:-1:g}else return w.curr.id.client-p.curr.id.client}),r.length!==0;){const f=r[0],h=f.curr.id.client;if(i!==null){let p=f.curr,w=!1;for(;p!==null&&p.id.clock+p.length<=i.struct.id.clock+i.struct.length&&p.id.client>=i.struct.id.client;)p=f.next(),w=!0;if(p===null||p.id.client!==h||w&&p.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Qt(a,i.struct,i.offset),i={struct:p,offset:0},f.next();else if(i.struct.id.clock+i.struct.length<p.id.clock)if(i.struct.constructor===yt)i.struct.length=p.id.clock+p.length-i.struct.id.clock;else{Qt(a,i.struct,i.offset);const g=p.id.clock-i.struct.id.clock-i.struct.length;i={struct:new yt(me(h,i.struct.id.clock+i.struct.length),g),offset:0}}else{const g=i.struct.id.clock+i.struct.length-p.id.clock;g>0&&(i.struct.constructor===yt?i.struct.length-=g:p=Ig(p,g)),i.struct.mergeWith(p)||(Qt(a,i.struct,i.offset),i={struct:p,offset:0},f.next())}}else i={struct:f.curr,offset:0},f.next();for(let p=f.curr;p!==null&&p.id.client===h&&p.id.clock===i.struct.id.clock+i.struct.length&&p.constructor!==yt;p=f.next())Qt(a,i.struct,i.offset),i={struct:p,offset:0}}i!==null&&(Qt(a,i.struct,i.offset),i=null),Po(a);const c=s.map(f=>Fo(f)),u=Xi(c);return os(l,u),l.toUint8Array()},Pg=(t,e,n=Qn,s=kn)=>{const r=qc(e),i=new s,l=new Io(i),a=new n(on(t)),c=new $o(a,!1);for(;c.curr;){const f=c.curr,h=f.id.client,p=r.get(h)||0;if(c.curr.constructor===yt){c.next();continue}if(f.id.clock+f.length>p)for(Qt(l,f,vn(p-f.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Qt(l,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=p;)c.next()}Po(l);const u=Fo(a);return os(i,u),i.toUint8Array()},Zc=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Te(t.encoder.restEncoder)}),t.encoder.restEncoder=ze(),t.written=0)},Qt=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&Zc(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),G(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},Po=t=>{Zc(t);const e=t.encoder.restEncoder;G(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];G(e,s.written),Rr(e,s.restEncoder)}},Ug=(t,e,n,s)=>{const r=new n(on(t)),i=new $o(r,!1),l=new s,a=new Io(l);for(let u=i.curr;u!==null;u=i.next())Qt(a,e(u),0);Po(a);const c=Fo(r);return os(l,c),l.toUint8Array()},zg=t=>Ug(t,Xp,Qn,$s),ya="You must not compute changes after the event-handler fired.";class Ur{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=Bg(this.currentTarget,this.target))}deletes(e){return Ms(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Et(ya);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=ki(c.content.getContent());else return;else c!==null&&this.deletes(c)?(l="update",a=ki(c.content.getContent())):(l="add",a=void 0)}else if(this.deletes(i))l="delete",a=ki(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 Et(ya);const n=this.target,s=nn(),r=nn(),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 u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=u.length,r.add(u)):this.adds(u)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(u.content.getContent()),s.add(u)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=u.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}}const Bg=(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},nt=()=>{Nc("Invalid access: Add Yjs type to a document before reading data.")},Qc=80;let Uo=0;class qg{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=Uo++}}const Wg=t=>{t.timestamp=Uo++},eu=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=Uo++},Hg=(t,e,n)=>{if(t.length>=Qc){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return eu(s,e,n),s}else{const s=new qg(e,n);return t.push(s),s}},zr=(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)=>rr(e-i.index)<rr(e-l.index)?i:l);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,Wg(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&&rr(n.index-r)<s.parent.length/Qc?(eu(n,s,r),n):Hg(t._searchMarker,s,r)},Ls=(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=vn(e,r.index+n))}},Br=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;Nt(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;Hc(s._eH,n,e)};class Ye{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ua(),this._dEH=ua(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw vt()}clone(){throw vt()}_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){da(this._eH,e)}observeDeep(e){da(this._dEH,e)}unobserve(e){ha(this._eH,e)}unobserveDeep(e){ha(this._dEH,e)}toJSON(){}}const tu=(t,e,n)=>{t.doc??nt(),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},nu=t=>{t.doc??nt();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},Rs=(t,e)=>{let n=0,s=t._start;for(t.doc??nt();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}},su=(t,e)=>{const n=[];return Rs(t,(s,r)=>{n.push(e(s,r,t))}),n},Vg=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}}}},ru=(t,e)=>{t.doc??nt();const n=zr(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}},xr=(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 u=[];const f=()=>{u.length>0&&(r=new Oe(me(l,qe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Cn(u)),r.integrate(t,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(f(),h.constructor){case Uint8Array:case ArrayBuffer:r=new Oe(me(l,qe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Is(new Uint8Array(h))),r.integrate(t,0);break;case jn:r=new Oe(me(l,qe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Ps(h)),r.integrate(t,0);break;default:if(h instanceof Ye)r=new Oe(me(l,qe(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Ot(h)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),f()},iu=()=>Et("Length exceeded!"),ou=(t,e,n,s)=>{if(n>e._length)throw iu();if(n===0)return e._searchMarker&&Ls(e._searchMarker,n,s.length),xr(t,e,null,s);const r=n,i=zr(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&&ct(t,me(l.id.client,l.id.clock+n));break}n-=l.length}return e._searchMarker&&Ls(e._searchMarker,r,s.length),xr(t,e,l,s)},Kg=(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 xr(t,e,r,n)},lu=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,l=zr(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&&ct(t,me(a.id.client,a.id.clock+n)),n-=a.length);for(;s>0&&a!==null;)a.deleted||(s<a.length&&ct(t,me(a.id.client,a.id.clock+s)),a.delete(t),s-=a.length),a=a.right;if(s>0)throw iu();e._searchMarker&&Ls(e._searchMarker,r,-i+s)},kr=(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 Cn([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new Cn([s]);break;case Uint8Array:a=new Is(s);break;case jn:a=new Ps(s);break;default:if(s instanceof Ye)a=new Ot(s);else throw new Error("Unexpected content type")}new Oe(me(l,qe(i.store,l)),r,r&&r.lastId,null,null,e,n,a).integrate(t,0)},Bo=(t,e)=>{t.doc??nt();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},au=t=>{const e={};return t.doc??nt(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},cu=(t,e)=>{t.doc??nt();const n=t._map.get(e);return n!==void 0&&!n.deleted},Gg=(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&&Mn(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},tr=t=>(t.doc??nt(),cg(t._map.entries(),e=>!e[1].deleted));class Jg extends Ur{}class Wn extends Ye{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new Wn;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Wn}clone(){const e=new Wn;return e.insert(0,this.toArray().map(n=>n instanceof Ye?n.clone():n)),e}get length(){return this.doc??nt(),this._length}_callObserver(e,n){super._callObserver(e,n),Br(this,e,new Jg(this,e))}insert(e,n){this.doc!==null?Ae(this.doc,s=>{ou(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?Ae(this.doc,n=>{Kg(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?Ae(this.doc,s=>{lu(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return ru(this,e)}toArray(){return nu(this)}slice(e=0,n=this.length){return tu(this,e,n)}toJSON(){return this.map(e=>e instanceof Ye?e.toJSON():e)}map(e){return su(this,e)}forEach(e){Rs(this,e)}[Symbol.iterator](){return Vg(this)}_write(e){e.writeTypeRef(xw)}}const Yg=t=>new Wn;class Xg extends Ur{constructor(e,n,s){super(e,n),this.keysChanged=s}}class es extends Ye{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 es}clone(){const e=new es;return this.forEach((n,s)=>{e.set(s,n instanceof Ye?n.clone():n)}),e}_callObserver(e,n){Br(this,e,new Xg(this,e,n))}toJSON(){this.doc??nt();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof Ye?r.toJSON():r}}),e}get size(){return[...tr(this)].length}keys(){return Ei(tr(this),e=>e[0])}values(){return Ei(tr(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Ei(tr(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??nt(),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?Ae(this.doc,n=>{kr(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?Ae(this.doc,s=>{zo(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return Bo(this,e)}has(e){return cu(this,e)}clear(){this.doc!==null?Ae(this.doc,e=>{this.forEach(function(n,s,r){kr(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(kw)}}const Zg=t=>new es,en=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Jp(t,e);class eo{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&pt(),this.right.content.constructor===Ge?this.right.deleted||ls(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ba=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===Ge?e.right.deleted||ls(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&ct(t,me(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},nr=(t,e,n,s)=>{const r=new Map,i=s?zr(e,n):null;if(i){const l=new eo(i.p.left,i.p,i.index,r);return ba(t,l,n-i.index)}else{const l=new eo(null,e._start,0,r);return ba(t,l,n)}},uu=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Ge&&en(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,u=n.right,f=new Oe(me(i,qe(r.store,i)),c,c&&c.lastId,u,u&&u.id,e,null,new Ge(a,l));f.integrate(t,0),n.right=f,n.forward()})},ls=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},du=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Ge&&en(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},hu=(t,e,n,s)=>{const r=t.doc,i=r.clientID,l=new Map;for(const a in s){const c=s[a],u=n.currentAttributes.get(a)??null;if(!en(u,c)){l.set(a,u);const{left:f,right:h}=n;n.right=new Oe(me(i,qe(r.store,i)),f,f&&f.lastId,h,h&&h.id,e,null,new Ge(a,c)),n.right.integrate(t,0),n.forward()}}return l},Di=(t,e,n,s,r)=>{n.currentAttributes.forEach((p,w)=>{r[w]===void 0&&(r[w]=null)});const i=t.doc,l=i.clientID;du(n,r);const a=hu(t,e,n,r),c=s.constructor===String?new At(s):s instanceof Ye?new Ot(s):new En(s);let{left:u,right:f,index:h}=n;e._searchMarker&&Ls(e._searchMarker,n.index,c.getLength()),f=new Oe(me(l,qe(i.store,l)),u,u&&u.lastId,f,f&&f.id,e,null,c),f.integrate(t,0),n.right=f,n.index=h,n.forward(),uu(t,e,n,a)},xa=(t,e,n,s,r)=>{const i=t.doc,l=i.clientID;du(n,r);const a=hu(t,e,n,r);e:for(;n.right!==null&&(s>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Ge));){if(!n.right.deleted)switch(n.right.content.constructor){case Ge:{const{key:c,value:u}=n.right.content,f=r[c];if(f!==void 0){if(en(f,u))a.delete(c);else{if(s===0)break e;a.set(c,u)}n.right.delete(t)}else n.currentAttributes.set(c,u);break}default:s<n.right.length&&ct(t,me(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 Oe(me(l,qe(i.store,l)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new At(c)),n.right.integrate(t,0),n.forward()}uu(t,e,n,a)},fu=(t,e,n,s,r)=>{let i=e;const l=ut();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Ge){const u=i.content;l.set(u.key,u)}i=i.right}let a=0,c=!1;for(;e!==i;){if(n===e&&(c=!0),!e.deleted){const u=e.content;if(u.constructor===Ge){const{key:f,value:h}=u,p=s.get(f)??null;(l.get(f)!==u||p===h)&&(e.delete(t),a++,!c&&(r.get(f)??null)===h&&p!==h&&(p===null?r.delete(f):r.set(f,p))),!c&&!e.deleted&&ls(r,u)}}e=e.right}return a},Qg=(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===Ge){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},ew=t=>{let e=0;return Ae(t.doc,n=>{let s=t._start,r=t._start,i=ut();const l=Hi(i);for(;r;)r.deleted===!1&&(r.content.constructor===Ge?ls(l,r.content):(e+=fu(n,s,r,i,l),i=Hi(l),s=r)),r=r.right}),e},tw=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&&Yc(t,n.store.clients.get(s),i,r,l=>{!l.deleted&&l.content.constructor===Ge&&l.constructor!==wt&&e.add(l.parent)})}Ae(n,s=>{Zn(t,t.deleteSet,r=>{if(r instanceof wt||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===Ge?e.add(i):Qg(s,r)});for(const r of e)ew(r)})},ka=(t,e,n)=>{const s=n,r=Hi(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Ot:case En:case At:n<e.right.length&&ct(t,me(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&fu(t,i,e.right,r,e.currentAttributes);const l=(e.left||e.right).parent;return l._searchMarker&&Ls(l._searchMarker,e.index,-s+n),e};class nw extends Ur{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=[];Ae(e,s=>{const r=new Map,i=new Map;let l=this.target._start,a=null;const c={};let u="",f=0,h=0;const p=()=>{if(a!==null){let w=null;switch(a){case"delete":h>0&&(w={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(w={insert:u},r.size>0&&(w.attributes={},r.forEach((g,C)=>{g!==null&&(w.attributes[C]=g)}))),u="";break;case"retain":f>0&&(w={retain:f},Gp(c)||(w.attributes=Wp({},c))),f=0;break}w&&n.push(w),a=null}};for(;l!==null;){switch(l.content.constructor){case Ot:case En:this.adds(l)?this.deletes(l)||(p(),a="insert",u=l.content.getContent()[0],p()):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),h+=1):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=1);break;case At:this.adds(l)?this.deletes(l)||(a!=="insert"&&(p(),a="insert"),u+=l.content.str):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),h+=l.length):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=l.length);break;case Ge:{const{key:w,value:g}=l.content;if(this.adds(l)){if(!this.deletes(l)){const C=r.get(w)??null;en(C,g)?g!==null&&l.delete(s):(a==="retain"&&p(),en(g,i.get(w)??null)?delete c[w]:c[w]=g)}}else if(this.deletes(l)){i.set(w,g);const C=r.get(w)??null;en(C,g)||(a==="retain"&&p(),c[w]=C)}else if(!l.deleted){i.set(w,g);const C=c[w];C!==void 0&&(en(C,g)?C!==null&&l.delete(s):(a==="retain"&&p(),g===null?delete c[w]:c[w]=g))}l.deleted||(a==="insert"&&p(),ls(r,l.content));break}}l=l.right}for(p();n.length>0;){const w=n[n.length-1];if(w.retain!==void 0&&w.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class ts extends Ye{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??nt(),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 ts}clone(){const e=new ts;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new nw(this,e,n);Br(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??nt();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===At&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?Ae(this.doc,s=>{const r=new eo(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)&&Di(s,this,r,a,l.attributes||{})}else l.retain!==void 0?xa(s,this,r,l.retain,l.attributes||{}):l.delete!==void 0&&ka(s,r,l.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??nt();const r=[],i=new Map,l=this.doc;let a="",c=this._start;function u(){if(a.length>0){const h={};let p=!1;i.forEach((g,C)=>{p=!0,h[C]=g});const w={insert:a};p&&(w.attributes=h),r.push(w),a=""}}const f=()=>{for(;c!==null;){if(Mn(c,e)||n!==void 0&&Mn(c,n))switch(c.content.constructor){case At:{const h=i.get("ychange");e!==void 0&&!Mn(c,e)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(u(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!Mn(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(u(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(u(),i.delete("ychange")),a+=c.content.str;break}case Ot:case En:{u();const h={insert:c.content.getContent()[0]};if(i.size>0){const p={};h.attributes=p,i.forEach((w,g)=>{p[g]=w})}r.push(h);break}case Ge:Mn(c,e)&&(u(),ls(i,c.content));break}c=c.right}u()};return e||n?Ae(l,h=>{e&&Zi(h,e),n&&Zi(h,n),f()},"cleanup"):f(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?Ae(r,i=>{const l=nr(i,this,e,!s);s||(s={},l.currentAttributes.forEach((a,c)=>{s[c]=a})),Di(i,this,l,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?Ae(r,i=>{const l=nr(i,this,e,!s);Di(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?Ae(s,r=>{ka(r,nr(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?Ae(r,i=>{const l=nr(i,this,e,!1);l.right!==null&&xa(i,this,l,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?Ae(this.doc,n=>{kr(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?Ae(this.doc,s=>{zo(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return Bo(this,e)}getAttributes(){return au(this)}_write(e){e.writeTypeRef(Sw)}}const sw=t=>new ts;class _i{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??nt()}[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===ns||n.constructor===Sn)&&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 Sn extends Ye{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 Sn}clone(){const e=new Sn;return e.insert(0,this.toArray().map(n=>n instanceof Ye?n.clone():n)),e}get length(){return this.doc??nt(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new _i(this,e)}querySelector(e){e=e.toUpperCase();const s=new _i(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),qt(new _i(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Br(this,e,new ow(this,n,e))}toString(){return su(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),Rs(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?Ae(this.doc,s=>{ou(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)Ae(this.doc,s=>{const r=e&&e instanceof Ye?e._item:e;xr(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 Et("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?Ae(this.doc,s=>{lu(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return nu(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return ru(this,e)}slice(e=0,n=this.length){return tu(this,e,n)}forEach(e){Rs(this,e)}_write(e){e.writeTypeRef(vw)}}const rw=t=>new Sn;class ns extends Sn{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 ns(this.nodeName)}clone(){const e=new ns(this.nodeName),n=this.getAttributes();return Vp(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof Ye?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?Ae(this.doc,n=>{kr(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?Ae(this.doc,s=>{zo(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return Bo(this,e)}hasAttribute(e){return cu(this,e)}getAttributes(e){return e?Gg(this,e):au(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 Rs(this,l=>{r.appendChild(l.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(Cw),e.writeKey(this.nodeName)}}const iw=t=>new ns(t.readKey());class ow extends Ur{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 Sr extends es{constructor(e){super(),this.hookName=e}_copy(){return new Sr(this.hookName)}clone(){const e=new Sr(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(jw),e.writeKey(this.hookName)}}const lw=t=>new Sr(t.readKey());class Cr extends ts{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 Cr}clone(){const e=new Cr;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(Ew)}}const aw=t=>new Cr;class qo{constructor(e,n){this.id=e,this.length=n}get deleted(){throw vt()}mergeWith(e){return!1}write(e,n,s){throw vt()}integrate(e,n){throw vt()}}const cw=0;class wt extends qo{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),Jc(e.doc.store,this)}write(e,n){e.writeInfo(cw),e.writeLen(this.length-n)}getMissing(e,n){return null}}class Is{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Is(this.content)}splice(e){throw vt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const uw=t=>new Is(t.readBuf());class As{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new As(this.len)}splice(e){const n=new As(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){Ts(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 dw=t=>new As(t.readLen()),pu=(t,e)=>new jn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Ps{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 Ps(pu(this.doc.guid,this.opts))}splice(e){throw vt()}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 hw=t=>new Ps(pu(t.readString(),t.readAny()));class En{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new En(this.embed)}splice(e){throw vt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const fw=t=>new En(t.readJSON());class Ge{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Ge(this.key,this.value)}splice(e){throw vt()}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 pw=t=>new Ge(t.readKey(),t.readJSON());class vr{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new vr(this.arr)}splice(e){const n=new vr(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 mw=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 vr(n)},gw=mr("node_env")==="development";class Cn{constructor(e){this.arr=e,gw&&lc(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Cn(this.arr)}splice(e){const n=new Cn(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 ww=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new Cn(n)};class At{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new At(this.str)}splice(e){const n=new At(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 yw=t=>new At(t.readString()),bw=[Yg,Zg,sw,iw,rw,lw,aw],xw=0,kw=1,Sw=2,Cw=3,vw=4,jw=5,Ew=6;class Ot{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Ot(this.type._copy())}splice(e){throw vt()}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 Dw=t=>new Ot(bw[t.readTypeRef()](t)),to=(t,e)=>{let n=e,s=0,r;do s>0&&(n=me(n.client,n.clock+s)),r=qn(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof Oe);return{item:r,diff:s}},Wo=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},jr=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new Oe(me(s,r+n),e,me(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=me(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},Sa=(t,e)=>go(t,n=>Ms(n.deletions,e)),mu=(t,e,n,s,r,i)=>{const l=t.doc,a=l.store,c=l.clientID,u=e.redone;if(u!==null)return ct(t,u);let f=e.parent._item,h=null,p;if(f!==null&&f.deleted===!0){if(f.redone===null&&(!n.has(f)||mu(t,f,n,s,r,i)===null))return null;for(;f.redone!==null;)f=ct(t,f.redone)}const w=f===null?e.parent:f.content.type;if(e.parentSub===null){for(h=e.left,p=e;h!==null;){let k=h;for(;k!==null&&k.parent._item!==f;)k=k.redone===null?null:ct(t,k.redone);if(k!==null&&k.parent._item===f){h=k;break}h=h.left}for(;p!==null;){let k=p;for(;k!==null&&k.parent._item!==f;)k=k.redone===null?null:ct(t,k.redone);if(k!==null&&k.parent._item===f){p=k;break}p=p.right}}else{if(p=null,e.right&&!r){for(h=e;h!==null&&h.right!==null&&(h.right.redone||Ms(s,h.right.id)||Sa(i.undoStack,h.right.id)||Sa(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=ct(t,h.redone);if(h&&h.right!==null)return null}else h=w._map.get(e.parentSub)||null;h!==null&&h.parent._item!==f&&(h=w._map.get(e.parentSub)||null)}const g=qe(a,c),C=me(c,g),v=new Oe(C,h,h&&h.lastId,p,p&&p.id,w,e.parentSub,e.content.copy());return e.redone=C,Wo(v,!0),v.integrate(t,0),v};class Oe extends qo{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()?Xl:0}set marker(e){(this.info&bi)>0!==e&&(this.info^=bi)}get marker(){return(this.info&bi)>0}get keep(){return(this.info&Yl)>0}set keep(e){this.keep!==e&&(this.info^=Yl)}get countable(){return(this.info&Xl)>0}get deleted(){return(this.info&yi)>0}set deleted(e){this.deleted!==e&&(this.info^=yi)}markDeleted(){this.info|=yi}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===Bn&&this.id.client!==this.parent.client&&this.parent.clock>=qe(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=fa(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=ct(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===wt||this.right&&this.right.constructor===wt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Oe?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Oe&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Bn){const s=qn(n,this.parent);s.constructor===wt?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=fa(e,e.doc.store,me(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),In(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(In(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),Jc(e.doc.store,this),this.content.integrate(e,this),ma(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new wt(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:me(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&In(e.origin,this.lastId)&&this.right===e&&In(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(),Ts(e.deleteSet,this.id.client,this.id.clock,this.length),ma(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw pt();this.content.gc(e),n?Lg(e,this,new wt(this.id,this.length)):this.content=new As(this.length)}write(e,n){const s=n>0?me(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,l=this.content.getRef()&Lr|(s===null?0:it)|(r===null?0:Bt)|(i===null?0:Cs);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 u=Vc(a);e.writeParentInfo(!0),e.writeString(u)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===Bn?(e.writeParentInfo(!1),e.writeLeftID(a)):pt();i!==null&&e.writeString(i)}this.content.write(e,n)}}const gu=(t,e)=>_w[e&Lr](t),_w=[()=>{pt()},dw,mw,uw,yw,fw,pw,Dw,ww,hw,()=>{pt()}],Tw=10;class yt extends qo{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){pt()}write(e,n){e.writeInfo(Tw),G(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const wu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},yu="__ $YJS$ __";wu[yu]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");wu[yu]=!0;function Lw(t){for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t}function Rw(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 no(t=globalThis.crypto){if(typeof t?.randomUUID=="function")return t.randomUUID();const e=new Uint8Array(16),n=typeof t?.getRandomValues=="function"?t.getRandomValues(e):Lw(e);return Rw(n)}const bu=new Map;class Aw{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:um(n.newValue||"")}),zp(this._onChange)}postMessage(e){ic.setItem(this.room,cm(rm(e)))}close(){Bp(this._onChange)}}const Nw=typeof BroadcastChannel>"u"?Aw:BroadcastChannel,Ho=t=>Nt(bu,t,()=>{const e=nn(),n=new Nw(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),Fw=(t,e)=>(Ho(t).subs.add(e),e),Ow=(t,e)=>{const n=Ho(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),bu.delete(t)),s},$n=(t,e,n=null)=>{const s=Ho(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},xu=0,Vo=1,ku=2,Er=(t,e)=>{G(t,xu);const n=vg(e);Ue(t,n)},Su=(t,e,n)=>{G(t,Vo),Ue(t,Mo(e,n))},Mw=(t,e,n)=>Su(e,n,tt(t)),Cu=(t,e,n,s)=>{try{Bc(e,tt(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},$w=(t,e)=>{G(t,ku),Ue(t,e)},Iw=Cu,Pw=(t,e,n,s,r)=>{const i=le(t);switch(i){case xu:Mw(t,e,n);break;case Vo:Cu(t,n,s,r);break;case ku:Iw(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},Uw=0,zw=(t,e,n)=>{le(t)===Uw&&n(e,Ie(t))},Ti=3e4;class Bw extends Za{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=sn();this.getLocalState()!==null&&Ti/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&Ti<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Ko(this,s,"timeout")},jt(Ti/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:sn()});const l=[],a=[],c=[],u=[];e===null?u.push(n):i==null?e!=null&&l.push(n):(a.push(n),Un(i,e)||c.push(n)),(l.length>0||c.length>0||u.length>0)&&this.emit("change",[{added:l,updated:c,removed:u},"local"]),this.emit("update",[{added:l,updated:a,removed:u},"local"])}setLocalStateField(e,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:n})}getStates(){return this.states}}const Ko=(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:sn()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},Hn=(t,e,n=t.states)=>{const s=e.length,r=ze();G(r,s);for(let i=0;i<s;i++){const l=e[i],a=n.get(l)||null,c=t.meta.get(l).clock;G(r,l),G(r,c),Qe(r,JSON.stringify(a))}return Te(r)},qw=(t,e,n)=>{const s=on(e),r=sn(),i=[],l=[],a=[],c=[],u=le(s);for(let f=0;f<u;f++){const h=le(s);let p=le(s);const w=JSON.parse(Ie(s)),g=t.meta.get(h),C=t.states.get(h),v=g===void 0?0:g.clock;(v<p||v===p&&w===null&&t.states.has(h))&&(w===null?h===t.clientID&&t.getLocalState()!=null?p++:t.states.delete(h):t.states.set(h,w),t.meta.set(h,{clock:p,lastUpdated:r}),g===void 0&&w!==null?i.push(h):g!==void 0&&w===null?c.push(h):w!==null&&(Un(w,C)||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])},Ww=t=>Kp(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),yn=0,vu=3,Vn=1,Hw=2,Us=[];Us[yn]=(t,e,n,s,r)=>{G(t,yn);const i=Pw(e,t,n.doc,n);s&&i===Vo&&!n.synced&&(n.synced=!0)};Us[vu]=(t,e,n,s,r)=>{G(t,Vn),Ue(t,Hn(n.awareness,Array.from(n.awareness.getStates().keys())))};Us[Vn]=(t,e,n,s,r)=>{qw(n.awareness,tt(e),n)};Us[Hw]=(t,e,n,s,r)=>{zw(e,n.doc,(i,l)=>Vw(n,l))};const Ca=3e4,Vw=(t,e)=>console.warn(`Permission denied to access ${t.url}.
|
|
10
|
+
${e}`),ju=(t,e,n)=>{const s=on(e),r=ze(),i=le(s),l=t.messageHandlers[i];return l?l(r,s,t,n,i):console.error("Unable to compute message"),r},so=(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,Ko(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(Eu,yo(up(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},Eu=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=sn();const s=ju(t,new Uint8Array(n.data),!0);bo(s)>1&&e.send(Te(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{so(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=sn(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=ze();if(G(n,yn),Er(n,t.doc),e.send(Te(n)),t.awareness.getLocalState()!==null){const s=ze();G(s,Vn),Ue(s,Hn(t.awareness,[t.doc.clientID])),e.send(Te(s))}},t.emit("status",[{status:"connecting"}])}},Li=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&$n(t.bcChannel,e,t)};class Kw extends wo{constructor(e,n,s,{connect:r=!0,awareness:i=new Bw(s),params:l={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:u=-1,maxBackoffTime:f=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=f,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=Us.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,u>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const p=ze();G(p,yn),Er(p,s),this.ws.send(Te(p))}},u)),this._bcSubscriber=(p,w)=>{if(w!==this){const g=ju(this,new Uint8Array(p),!1);bo(g)>1&&$n(this.bcChannel,Te(g),this)}},this._updateHandler=(p,w)=>{if(w!==this){const g=ze();G(g,yn),$w(g,p),Li(this,Te(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:p,updated:w,removed:g},C)=>{const v=p.concat(w).concat(g),k=ze();G(k,Vn),Ue(k,Hn(i,v)),Li(this,Te(k))},this._exitHandler=()=>{Ko(this.awareness,[s.clientID],"app closed")},rn&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Ca<sn()-this.wsLastMessageReceived&&so(this,this.ws,null)},Ca/10),r&&this.connect()}get url(){const e=Ww(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(),rn&&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||(Fw(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=ze();G(e,yn),Er(e,this.doc),$n(this.bcChannel,Te(e),this);const n=ze();G(n,yn),Su(n,this.doc),$n(this.bcChannel,Te(n),this);const s=ze();G(s,vu),$n(this.bcChannel,Te(s),this);const r=ze();G(r,Vn),Ue(r,Hn(this.awareness,[this.doc.clientID])),$n(this.bcChannel,Te(r),this)}disconnectBc(){const e=ze();G(e,Vn),Ue(e,Hn(this.awareness,[this.doc.clientID],new Map)),Li(this,Te(e)),this.bcconnected&&(Ow(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&so(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Eu(this),this.connectBc())}}const Dn=t=>Yn((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),Gw=(t,e)=>Yn((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(Et(i.target.error)),r.onsuccess=i=>{const l=i.target.result;l.onversionchange=()=>{l.close()},n(l)}}),Jw=t=>Dn(indexedDB.deleteDatabase(t)),Yw=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),gs=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>ry(s,r))},Du=(t,e)=>Dn(t.count(e)),Xw=(t,e)=>Dn(t.get(e)),_u=(t,e)=>Dn(t.delete(e)),Zw=(t,e,n)=>Dn(t.put(e,n)),ro=(t,e)=>Dn(t.add(e)),Qw=(t,e,n)=>Dn(t.getAll(e,n)),ey=(t,e,n)=>{let s=null;return sy(t,e,r=>(s=r,!1),n).then(()=>s)},ty=(t,e=null)=>ey(t,e,"prev"),ny=(t,e)=>Yn((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()}}),sy=(t,e,n,s="next")=>ny(t.openKeyCursor(e,s),r=>n(r.key)),ry=(t,e)=>t.objectStore(e),iy=(t,e)=>IDBKeyRange.upperBound(t,e),oy=(t,e)=>IDBKeyRange.lowerBound(t,e),Ri="custom",Tu="updates",Lu=500,Ru=(t,e=()=>{},n=()=>{})=>{const[s]=gs(t.db,[Tu]);return Qw(s,oy(t._dbref,!1)).then(r=>{t._destroyed||(e(s),Ae(t.doc,()=>{r.forEach(i=>Bc(t.doc,i))},t,!1),n(s))}).then(()=>ty(s).then(r=>{t._dbref=r+1})).then(()=>Du(s).then(r=>{t._dbsize=r})).then(()=>s)},ly=(t,e=!0)=>Ru(t).then(n=>{(e||t._dbsize>=Lu)&&ro(n,Mo(t.doc)).then(()=>_u(n,iy(t._dbref,!0))).then(()=>Du(n).then(s=>{t._dbsize=s}))});class ay extends Za{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=Gw(e,s=>Yw(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Yn(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Ru(this,l=>ro(l,Mo(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]=gs(this.db,[Tu]);ro(i,s),++this._dbsize>=Lu&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{ly(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(()=>{Jw(this.name)})}get(e){return this._db.then(n=>{const[s]=gs(n,[Ri],"readonly");return Xw(s,e)})}set(e,n){return this._db.then(s=>{const[r]=gs(s,[Ri]);return Zw(r,n,e)})}del(e){return this._db.then(n=>{const[s]=gs(n,[Ri]);return _u(s,e)})}}const cy={Sync:0,Awareness:1,Flush:4,Protocol:5,Maintenance:6,Permission:7,CompileStates:8,FormatLease:9},Ai=3,uy=["queued","running","succeeded","failed","cleaned"],dy=["cache","artifacts"];function hy(t){return typeof t=="string"&&uy.includes(t)}function fy(t){return typeof t=="string"&&dy.includes(t)}const va=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],{Sync:py,Awareness:my,Flush:ja,Protocol:Ea,Maintenance:gy,Permission:wy,CompileStates:yy,FormatLease:Ni}=cy,by=6e4,xy=720*60*60*1e3,ky=15e3,Sy=5*6e4;function Cy(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!hy(e.status)||e.status==="cleaned"&&!fy(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 Da(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=Cy(s);r&&r.mainFile===n&&(e[n]=r)}return e}function vy(t,e,n){return t<=n&&e<=n}function _a(t,e,n){const s=r=>r>0&&n-r<=Sy;return{recoverable:t.some(r=>r.tabId===e||!s(r.activeAt)),otherActive:t.some(r=>r.tabId!==e&&s(r.activeAt))}}class jy{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.draftTabId=Ty(gn(`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 ay(gn(`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 Kw(`${s}//${window.location.host}${ss("/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[ja]=(l,a)=>{const c=Ie(a),u=this.flushRequests.get(c);if(!u)return;const f=le(a)===1,h=le(a),p=Ie(a),w=le(a),g=[];for(let C=0;C<w;C++)g.push(Ie(a));if(window.clearTimeout(u.timer),this.flushRequests.delete(c),f)this.clearOwnWritableDraftMarker(u.draftGeneration),u.resolve({revision:h,persistedAt:p,ok:!0,failedPaths:[]});else{const C=Object.assign(new Error(g.length?`保存失败:${g.join(", ")}`:"源码保存到服务器磁盘失败"),{failedPaths:g});u.reject(C)}},this.provider.messageHandlers[Ea]=(l,a)=>{const c=Ie(a),u=this.epochStorageKey(),f=Ta(u),h=/^([0-9]+):/.exec(c)?.[1]??null,p=f?/^([0-9]+):/.exec(f)?.[1]??null:null,w=!this.epoch&&h===String(Ai)&&p!==null&&p!==h;if((this.epoch&&this.epoch!==c||f&&f!==c)&&!w){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed"));const B=c.endsWith(":reload")||h!==null&&h!==String(Ai),x=()=>{Fi(u,c.replace(/:reload$/,"")),window.location.reload()};if(B)for(const N of this.protocolUpgradeListeners)N();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),x()});return}this.epoch=c,Fi(u,c);const g=this.provider.ws;if(!g||g.readyState!==WebSocket.OPEN)return;const C=ze();G(C,Ea),Qe(C,c),G(C,Ai),g.send(Te(C));const v=ze();G(v,py),Er(v,this.doc),g.send(Te(v));const k=ze();G(k,my),Ue(k,Hn(this.awareness,[this.doc.clientID])),g.send(Te(k))},this.provider.messageHandlers[wy]=(l,a)=>{const c=Ie(a),u=Ie(a);if(c!==this.user.id)return;if(u==="revoked"){this.rejectFlushes(new Error("Project access revoked")),this.provider.disconnect();for(const h of this.permissionListeners)h("revoked",this.permission);return}if(u!=="read"&&u!=="edit"&&u!=="owner")return;const f=this.permission;if(this.setPermission(u),f!==u){u==="read"&&this.rejectFlushes(new Error("Project permission changed to read-only"));for(const h of this.permissionListeners)h(u,f)}},this.provider.messageHandlers[gy]=(l,a)=>{Ie(a)},this.provider.messageHandlers[yy]=(l,a)=>{let c={};try{c=Da(JSON.parse(Ie(a)))}catch{}this.authoritativeCompileStates=c,this.notifyCompileStateListeners()},this.provider.messageHandlers[Ni]=(l,a)=>{const c=Ie(a),u=Ie(a),f=Ie(a),h=Ie(a),p=Ie(a),w=Ie(a);if(c==="state"){const C=Gi(a)?Ie(a):"",v=Gi(a)?Ie(a):"",k=Number(p);if(!C||!Number.isFinite(k)||k<=Date.now())this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null);else{const B={path:f,holderUserId:C,holderName:v,expiresAt:k};this.formatLeaseStatesByPath.set(f,B);const x=this.formatLeaseExpiryTimers.get(f);x!==void 0&&window.clearTimeout(x);const N=window.setTimeout(()=>{const R=this.formatLeaseStatesByPath.get(f);!R||R.expiresAt>Date.now()||(this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null))},Math.max(0,k-Date.now())+25);this.formatLeaseExpiryTimers.set(f,N),this.notifyFormatLeaseListeners(B)}return}const g=this.formatLeaseRequests.get(u);g&&(window.clearTimeout(g.timer),this.formatLeaseRequests.delete(u),c==="denied"?g.reject(new Error(w||"Format lease request was denied")):g.resolve({status:c,filePath:f,token:h,expiresAt:Number(p)}))},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 jn;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 Og(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??Da(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 _a(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){const e=this.readWritableDraftMarkers();return _a(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=no(),s=this.draftGeneration,r=ze();return G(r,ja),Qe(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(Te(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=no(),l=ze();return G(l,Ni),Qe(l,e),Qe(l,i),Qe(l,n),Qe(l,s),new Promise((a,c)=>{const u=window.setTimeout(()=>{if(this.formatLeaseRequests.delete(i),e==="acquire"){const f=this.provider.ws;if(f?.readyState===WebSocket.OPEN){const h=ze();G(h,Ni),Qe(h,"cancel"),Qe(h,i),Qe(h,n),Qe(h,""),f.send(Te(h))}}c(new Error("Format lease request timed out"))},e==="acquire"?by:5e3);this.formatLeaseRequests.set(i,{resolve:a,reject:c,timer:u}),r.send(Te(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]=va[Math.abs(this.doc.clientID)%va.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 gn(`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`)}writableDraftStoragePrefix(){return`${gn(`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())ps(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),ps(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){const n=this.readOwnWritableDraftMarker();!n||!vy(n.generation,this.draftGeneration,e)||(ps(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){const e=this.writableDraftStoragePrefix(),n=[];for(const s of Ey()){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=Ta(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>xy)return ps(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 ps(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};Fi(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)},ky))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}}function Ta(t){try{return window.localStorage.getItem(t)}catch{return null}}function Fi(t,e){try{window.localStorage.setItem(t,e)}catch{}}function ps(t){try{window.localStorage.removeItem(t)}catch{}}function Ey(){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 Dy(t){try{return window.sessionStorage.getItem(t)}catch{return null}}function _y(t,e){try{window.sessionStorage.setItem(t,e)}catch{}}function Ty(t){const e=Dy(t);if(e)return e;const n=no();return _y(t,n),n}function Ly(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function Ry(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 Ay(t,e,n,s,r,i){const[l]=d.useState(()=>new jy(t,e)),[a,c]=d.useState("connecting"),[u,f]=d.useState(!1),[h,p]=d.useState([]),[w,g]=d.useState(null),[C,v]=d.useState(null),[k,B]=d.useState(""),[x,N]=d.useState(!1),[R,T]=d.useState(""),[_,$]=d.useState([]),[H,ue]=d.useState(!1),[Z,V]=d.useState(s),[de,I]=d.useState(null),[Y,te]=d.useState(!1),ne=d.useRef(n),P=d.useRef(i),ge=d.useRef(r);ne.current=n,P.current=i,ge.current=r,d.useEffect(()=>{const b=l.compileStates();g(b[n]??null)},[n,l]),d.useEffect(()=>{const b=()=>p(l.sessions()),U=()=>{f(!1),p([]),g(null),v(null),B(""),N(!1),T(""),$([]),P.current()},Q=({status:F})=>{c(F),F!=="connected"&&U()},xe=F=>{f(F),F||U()},ae=()=>{c("disconnected"),U()},ke=()=>{N(l.meta.get("historyWarning")===!0);const F=l.meta.get("filesEvent");Ry(F)&&v(F);const re=l.meta.get("commentsRevision");typeof re=="string"&&B(re);const Ee=l.meta.get("dictionaryRevision");typeof Ee=="string"&&T(Ee);const A=l.compileStates();g(A[ne.current]??null)},Ne=()=>{const F=l.compileStates();g(F[ne.current]??null)};l.awareness.on("change",b),l.provider.on("status",Q),l.provider.on("sync",xe),l.provider.on("connection-close",ae),l.provider.on("connection-error",ae),l.meta.observe(ke);const pe=l.onCompileStates(Ne),q=l.onProtocolUpgrade(()=>{te(!0),c("disconnected"),U()}),K=()=>$(l.formatLeaseStates()),De=l.onFormatLeaseState(K),$e=()=>{if(!ge.current||l.currentPermission!=="read")return;const F=l.hasWritableDraft,re=l.hasOtherWritableDraft;!F&&!re||I({previous:"edit",localDraftReady:F,otherTabDraft:re})},Se=l.onDraftReady(()=>{ue(!0),$e()}),je=l.onPermissionChanged((F,re)=>{if(F==="revoked"){c("disconnected"),f(!1),P.current();return}V(F),F==="read"&&re!=="read"?I({previous:re,localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):F!=="read"&&I(null)});return b(),ke(),c(l.connected?"connected":"connecting"),f(l.synced),()=>{l.awareness.off("change",b),l.provider.off("status",Q),l.provider.off("sync",xe),l.provider.off("connection-close",ae),l.provider.off("connection-error",ae),l.meta.unobserve(ke),pe(),q(),De(),Se(),je(),l.destroy()}},[l]),d.useEffect(()=>{r&&l.connect()},[l,r]),d.useEffect(()=>{l.setPermission(s),V(s),r&&s==="read"&&(l.hasWritableDraft||l.hasOtherWritableDraft)?I({previous:"edit",localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):s!=="read"&&I(null)},[l,s,r]);const we=de!==null;return d.useEffect(()=>{if(!we)return;const b=()=>{if(l.currentPermission!=="read")return;const Q=l.hasWritableDraft,xe=l.hasOtherWritableDraft;I(ae=>!ae||ae.localDraftReady===Q&&ae.otherTabDraft===xe?ae:{...ae,localDraftReady:Q,otherTabDraft:xe})};b();const U=window.setInterval(b,2e3);return()=>window.clearInterval(U)},[l,we]),{collaboration:l,status:a,synced:u,activeSessions:h,compileState:w,setCompileState:g,formatLeaseStates:_,filesEvent:C,commentsRevision:k,historyWarning:x,dictionaryRevision:R,localDraftReady:H,permission:Z,protocolUpgradeRequired:Y,reconnect:()=>{Y||(c("connecting"),f(!1),p([]),g(null),$([]),l.reconnect())},permissionDowngrade:de,dismissPermissionDowngrade:()=>I(null),discardLocalDraft:async()=>await l.discardLocalDraft()?(I(null),window.location.reload(),!0):(I(U=>U&&{...U,otherTabDraft:!0}),!1)}}function La(t){return t?.status==="succeeded"?"succeeded":t?.log.includes("Compilation was cancelled.")?"cancelled":t?.status==="failed"?"failed":null}function fn(t){return t instanceof Error&&t.name==="AbortError"}function Ny(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}function Fy({projectId:t,project:e,mainFile:n,resolveCompileMainFile:s,getCurrentMainFile:r,initialLatest:i,collaborationSynced:l,sharedState:a,onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:C}){const{t:v}=Xe(),[k,B]=d.useState(""),[x,N]=d.useState(!0),[R,T]=d.useState(null),[_,$]=d.useState("full"),[H,ue]=d.useState(""),[Z,V]=d.useState(null),[de,I]=d.useState(null),[Y,te]=d.useState([]),[ne,P]=d.useState(null),[ge,we]=d.useState(!1),[Ce,ee]=d.useState(!1),[se,b]=d.useState(()=>new Set),[U,Q]=d.useState(()=>new Set),[xe,ae]=d.useState(""),ke=d.useRef(n),Ne=d.useRef(""),pe=d.useRef(null),q=d.useRef(null),K=d.useRef(null),De=d.useRef(i),$e=d.useRef(!1),Se=d.useRef(null),je=d.useRef(null),F=d.useRef(new Set),re=d.useRef(new Map),Ee=d.useRef(null),A=d.useRef(()=>{}),O=d.useRef({onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:C,resolveCompileMainFile:s,getCurrentMainFile:r});ke.current=n,O.current={onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:C,resolveCompileMainFile:s,getCurrentMainFile:r};const S=()=>O.current.getCurrentMainFile?.()||ke.current,_e=L=>{Ee.current!==L&&(Ee.current=L,O.current.onCompileSuccess())},M=async(L,J)=>{J||(Se.current?.abort(),Se.current=new AbortController,J=Se.current.signal);try{const j=L?`?mainFile=${encodeURIComponent(L)}`:"",Pe=await ce(`/api/projects/${t}/compile/artifacts${j}`,{signal:J});ke.current===L&&(te(Pe.artifacts),P(null))}catch(j){!fn(j)&&ke.current===L&&(te([]),P(null))}finally{Se.current?.signal===J&&(Se.current=null)}};d.useEffect(()=>{if(pe.current?.abort(),!n){N(!1),B(""),T(null),$("full"),ue(""),V(null),I(null),te([]),P(null),K.current=null,O.current.onPdfChanged();return}K.current?.mainFile!==n&&(K.current=null);const L=new AbortController;pe.current=L,N(!0),ue(""),V(null),I(null),k&&n&&Ne.current===n||(B(""),T(null),$("full")),te([]),P(null),O.current.onPdfChanged();let j=null;const Pe=`?mainFile=${encodeURIComponent(n)}`,bt=$e.current?null:De.current;bt&&($e.current=!0);const mt=()=>ce(`/api/projects/${t}/compile/latest${Pe}`,{signal:L.signal}),be=bt?bt.then(ve=>ve.mainFile!==n?mt():ve,()=>mt()):mt();let dt=!1;const xt=()=>{if(dt||L.signal.aborted||!n)return;dt=!0;const ve=new AbortController;F.current.add(ve),M(n,ve.signal).finally(()=>{F.current.delete(ve)}),O.current.loadOutline(L.signal,n).catch(()=>{})};return be.then(ve=>{if(L.signal.aborted||n&&ve.mainFile!==ke.current)return;const z=K.current;z&&z.mainFile===n&&ve.latestRun?.id!==z.runId||(ue(ve.latestRun?.log??""),V(ve.latestRun?.diagnostics??null),I(La(ve.latestRun)),n&&ve.latestRun?.requestedBy&&(ve.latestRun.status==="queued"||ve.latestRun.status==="running")&&O.current.onSharedState({mainFile:n,runId:ve.latestRun.id,status:ve.latestRun.status,requestedBy:ve.latestRun.requestedBy,updatedAt:new Date().toISOString()}),ve.pdfUrl&&(Ne.current=ve.mainFile,B(ve.pdfUrl),T(ve.pdfCompiledAt),$(ve.pdfLoadingMode??"full"),O.current.onPreviewTab("pdf")))}).catch(ve=>{!fn(ve)&&ke.current===n&&O.current.onError(fe(ve))}).finally(()=>{pe.current===L&&(pe.current=null),L.signal.aborted||(N(!1),j=window.setTimeout(xt,0))}),()=>{j!==null&&window.clearTimeout(j),L.abort(),je.current?.abort();for(const ve of F.current)ve.abort();F.current.clear()}},[t,n]),d.useEffect(()=>{if(!(!a||a.mainFile!==n||a.status!=="cleaned"||!a.cleanMode)){pe.current?.abort(),q.current?.abort(),Se.current?.abort(),je.current?.abort();for(const L of F.current)L.abort();F.current.clear(),a.cleanMode==="artifacts"?(K.current=null,ue(""),V(null),I(null),B(""),T(null),$("full"),te([]),P(null),O.current.onPdfChanged(),O.current.onPreviewTab("pdf"),ae(v("editor.cleanArtifactsComplete"))):ae(v("editor.cleanCacheComplete"))}},[a?.runId,a?.status,a?.cleanMode,a?.mainFile,n,v]),d.useEffect(()=>{!n||a?.mainFile===n&&(a.status==="queued"||a.status==="running")||Q(L=>{if(!L.has(n))return L;const J=new Set(L);return J.delete(n),J})},[n,a?.mainFile,a?.status]),d.useEffect(()=>{if(!a||a.mainFile!==n||a.status!=="succeeded"&&a.status!=="failed")return;let L=!1;q.current?.abort(),je.current?.abort();const J=new AbortController;return q.current=J,N(!0),ce(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:J.signal}).then(j=>{L||j.mainFile!==ke.current||j.latestRun?.id!==a.runId||(ue(j.latestRun.log),V(j.latestRun.diagnostics),I(La(j.latestRun)),a.status==="succeeded"&&a.stale&&ae(v("editor.compileSnapshotStale")),a.status==="succeeded"&&j.pdfUrl?(K.current={mainFile:n,runId:a.runId},O.current.onPdfChanged(),B(j.pdfUrl),T(j.pdfCompiledAt),$(j.pdfLoadingMode??"full"),O.current.onPreviewTab("pdf"),_e(a.runId),M(n)):a.status==="failed"&&O.current.onPreviewTab(j.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(j=>{!fn(j)&&!L&&O.current.onError(fe(j))}).finally(()=>{q.current===J&&(q.current=null),L||N(!1)}),()=>{L=!0,J.abort(),q.current===J&&(q.current=null)}},[a?.runId,a?.status,a?.mainFile,a?.stale,n,t,v]);const he=async()=>{if(!e||e.permission==="read"||!l)return;const L=O.current.resolveCompileMainFile?.()||S();if(!L||re.current.has(L)||a?.mainFile===L&&(a.status==="queued"||a.status==="running"))return;b(j=>new Set([...j,L])),O.current.onCompileStart(),ae(""),je.current?.abort(),je.current=null,ue(""),V(null),I(null),O.current.onPreviewTab(k?"pdf":"log");const J=new AbortController;re.current.set(L,J);try{if(!await O.current.save())return;const j=await ce(`/api/projects/${t}/compile`,{method:"POST",signal:J.signal,body:JSON.stringify({mainFile:L})});if(j.mainFile!==L||S()!==L)return;ue(j.log),V(j.diagnostics),I(j.cancelled?"cancelled":j.ok?"succeeded":"failed"),j.cancelled&&ae(v("compileControls.cancelled")),j.skipped&&ae(v("editor.upToDate")),j.ok&&j.stale&&ae(v("editor.compileSnapshotStale")),j.pdfUrl?(j.ok&&(K.current={mainFile:L,runId:j.runId}),O.current.onPdfChanged(),B(j.pdfUrl),T(j.pdfCompiledAt),$(j.pdfLoadingMode??"full"),O.current.onPreviewTab("pdf"),j.ok&&(j.skipped?O.current.onCompileSuccess():_e(j.runId))):O.current.onPreviewTab(j.diagnostics.errors.length?"errors":"log")}catch(j){!fn(j)&&S()===L&&O.current.onError(fe(j))}finally{re.current.get(L)===J&&(re.current.delete(L),b(j=>{const Pe=new Set(j);return Pe.delete(L),Pe}),Q(j=>{if(!j.has(L))return j;const Pe=new Set(j);return Pe.delete(L),Pe}))}},Fe=async()=>{if(!e||e.permission==="read"||!l)return;const L=S();if(L){Q(J=>new Set([...J,L]));try{(await ce(`/api/projects/${t}/compile/cancel`,{method:"POST",body:JSON.stringify({mainFile:L})})).cancelled||Q(j=>{const Pe=new Set(j);return Pe.delete(L),Pe})}catch(J){Q(j=>{const Pe=new Set(j);return Pe.delete(L),Pe}),!fn(J)&&S()===L&&O.current.onError(fe(J))}}},Be=async L=>{if(!e||e.permission==="read"||!l||Ce)return;const J=S();if(!(!J||re.current.has(J)||a?.mainFile===J&&(a.status==="queued"||a.status==="running"))){ee(!0),pe.current?.abort(),q.current?.abort(),Se.current?.abort(),je.current?.abort();try{if((await ce(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:J,mode:L})})).mainFile!==J||S()!==J)return;O.current.onSharedState(null),L==="artifacts"&&(K.current=null,ue(""),V(null),I(null),B(""),T(null),$("full"),te([]),P(null),O.current.onPdfChanged()),ae(v(L==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(j){!fn(j)&&S()===J&&O.current.onError(fe(j))}finally{ee(!1)}}};A.current=()=>{he()},d.useEffect(()=>{if(!xe)return;const L=window.setTimeout(()=>ae(""),3e3);return()=>window.clearTimeout(L)},[xe]),d.useEffect(()=>{const L=J=>{if(!(!(J.ctrlKey||J.metaKey)||J.key.toLocaleLowerCase()!=="s")){if(Ny(J.target)){J.preventDefault();return}J.preventDefault(),J.stopPropagation(),J.repeat||A.current()}};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[]),d.useEffect(()=>()=>{pe.current?.abort(),q.current?.abort(),Se.current?.abort(),je.current?.abort();for(const L of F.current)L.abort();F.current.clear();for(const L of re.current.values())L.abort();re.current.clear()},[]);const ye=async L=>{if(!L.viewable)return;je.current?.abort();const J=new AbortController;je.current=J,we(!0);try{const j=await ce(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(L.path)}`,{signal:J.signal});!J.signal.aborted&&je.current===J&&ke.current===n&&P(j)}catch(j){fn(j)||O.current.onError(fe(j))}finally{je.current===J&&(je.current=null,we(!1))}};return{pdfUrl:k,pdfCompiledAt:R,pdfLoadingMode:_,pdfLoading:x,compileLog:H,compileDiagnostics:Z,compileOutcome:de,artifacts:Y,artifactPreview:ne,artifactLoading:ge,editorNotice:xe,localCompiling:se.has(n),cancelling:U.has(n),cleaning:Ce,compile:he,cancelCompile:Fe,cleanCompile:Be,viewArtifact:ye}}const io=10*1024*1024,Oy=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 Ra(t){return t instanceof Error&&t.name==="AbortError"}function ws(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function pn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function My(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!Oy.has(e)}function Kn(t){return/(?:\.(?:tex|bib|bst|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function Aa(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":My(t)?"text":"unsupported"}function $y(t,e){return ss(`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`)}function Iy({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:l,onActiveFile:a,onActiveMainFile:c}){const{t:u}=Xe(),[f,h]=d.useState([]),[p,w]=d.useState(!1),[g,C]=d.useState(""),[v,k]=d.useState(null),[B,x]=d.useState(!1),[N,R]=d.useState(!1),[T,_]=d.useState(""),[$,H]=d.useState(""),[ue,Z]=d.useState(null),[V,de]=d.useState(""),[I,Y]=d.useState(new Set),[te,ne]=d.useState(null),[P,ge]=d.useState(""),[we,Ce]=d.useState(""),[ee,se]=d.useState(null),[b,U]=d.useState(!1),[Q,xe]=d.useState(null),[ae,ke]=d.useState(!1),Ne=d.useRef(null),pe=d.useRef(null),q=async(M={})=>{Ne.current?.abort(),Ne.current=null;const he=M.signal?null:new AbortController;he&&(Ne.current=he);try{const Fe=await ce(`/api/projects/${t}/files`,{signal:M.signal??he?.signal});return(!M.isCurrent||M.isCurrent())&&h(Fe.files),Fe.files}catch(Fe){if(!Ra(Fe))throw Fe;return}finally{he&&Ne.current===he&&(Ne.current=null)}},K=async()=>{if(!(!g.trim()||g.trim().endsWith("/"))){H("");try{await ce(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:g,content:""})}),await q(),a(g),Z(null),Y(M=>new Set([...M,...ws(g)])),w(!1),C("")}catch(M){H(fe(M))}}},De=async()=>{if(!T.trim())return;H("");const M=ue?`${ue}/${T.trim()}`:T.trim();try{const he=await ce(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:M})});await q(),Y(Fe=>new Set([...Fe,...ws(he.path),he.path])),Z(he.path),R(!1),_("")}catch(he){H(fe(he))}},$e=async(M,he=new Set,Fe=ue)=>{if(!M.length)return;const Be=e.maxUploadSizeMB;if(M.find(be=>be.size>Be*1024*1024))return i(u("errors.fileTooLarge",{size:Be}));const L=Fe??"",J=M.map(be=>L?`${L}/${be.name}`:be.name),j=new Map;for(const be of J)j.set(be,(j.get(be)??0)+1);const Pe=[...j.entries()].filter(([,be])=>be>1).map(([be])=>be);if(Pe.length)return i(u("errors.duplicateUploadNames",{files:Pe.join(", ")}));const bt=new Set(f.map(be=>be.path)),mt=[...new Set(J.filter(be=>bt.has(be)&&!he.has(be)))];if(mt.length){xe({files:M,directory:L,collisions:mt});return}xe(null),ke(!0);try{const be=new URLSearchParams;L&&be.set("directory",L);let dt="";for(const[xt,ve]of M.entries()){const z=J[xt];be.delete("overwrite"),he.has(z)&&be.set("overwrite","1");const W=be.toString()?`?${be.toString()}`:"",kt=new FormData;kt.append("file",ve);try{const lt=await ce(`/api/projects/${t}/upload${W}`,{method:"POST",body:kt});typeof lt.path=="string"&&Kn(lt.path)&&(dt=lt.path)}catch(lt){if(lt instanceof Ii&<.status===409&&!he.has(z)&<.code==="FILE_EXISTS"){xt>0&&await q(),xe({files:M.slice(xt),directory:L,collisions:[z]});return}throw lt}}await q(),dt&&(a(dt),Z(null))}catch(be){i(fe(be))}finally{ke(!1)}},Se=async M=>{await $e(Array.from(M.target.files??[])),M.target.value=""},je=async M=>{pe.current?.abort(),pe.current=null,x(!1);const he=$y(t,M.path);if((M.size??0)>io){k({path:M.path,kind:"large",size:M.size??0,url:he});return}const Fe=Aa(M.path);if(Fe!=="text"){k({path:M.path,kind:Fe,size:M.size??0,url:he});return}k({path:M.path,kind:Fe,size:M.size??0,url:he,content:""}),x(!0);const Be=new AbortController;pe.current=Be;try{let ye;try{ye=await fetch(he,{signal:Be.signal})}catch(j){throw $h(j)}const L=ye.headers.get("content-type")??"";if(!ye.ok){let j=null;try{j=L.includes("application/json")?await ye.json():await ye.text()}catch{}throw new Ii(Ih(j,ye.status),ye.status,Ph(j))}const J=await ye.text();k(j=>j?.path===M.path?{...j,content:J}:j)}catch(ye){Ra(ye)||(k(null),i(fe(ye)))}finally{pe.current===Be&&(pe.current=null,x(!1))}},F=M=>{Z(null),de(M.path);const he=Aa(M.path),Fe=e.maxCollaborativeFileSizeMB*1024*1024;(M.size??0)>io||Kn(M.path)&&(M.size??0)>Fe||he!=="text"||!Kn(M.path)?je(M):a(M.path)},re=async(M,he,Fe)=>{if(!await r())return null;const Be=await ce(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:M.path,destinationDirectory:he,destinationName:Fe})}),ye=j=>j===M.path?Be.path:j.startsWith(`${M.path}/`)?`${Be.path}${j.slice(M.path.length)}`:j;a(j=>ye(j)),c(j=>ye(j)),Z(j=>j&&ye(j)),de(j=>j&&ye(j));const[L,J]=await Promise.all([ce(`/api/projects/${t}/files`),ce(`/api/projects/${t}`)]);return h(L.files),l(J.project),Y(j=>new Set([...j,...ws(Be.path),he].filter(Boolean))),Be.path},Ee=async()=>{if(!te)return;const M=P.trim();if(M){H("");try{if(!await re(te,we,M))return;ne(null),ge(""),Ce("")}catch(he){H(fe(he))}}},A=async(M,he)=>{if(Py(M.path)!==he&&!(M.type==="directory"&&(he===M.path||he.startsWith(`${M.path}/`))))try{await re(M,he,M.path.split("/").at(-1)??M.path)}catch(Fe){i(fe(Fe))}},O=async()=>{if(ee){H("");try{if(s&&!await r())return;await ce(`/api/projects/${t}/file?path=${encodeURIComponent(ee.path)}`,{method:"DELETE"}),se(null)}catch(M){H(fe(M))}}};d.useEffect(()=>()=>{Ne.current?.abort(),pe.current?.abort()},[]),d.useEffect(()=>{pe.current?.abort(),pe.current=null,x(!1)},[n]),d.useEffect(()=>{n&&de(n)},[n]);const S=f.filter(M=>M.type==="directory"),_e=f.filter(M=>ws(M.path).every(he=>I.has(he)));return{files:f,setFiles:h,loadFiles:q,newFileOpen:p,setNewFileOpen:w,newFilePath:g,setNewFilePath:C,resourcePreview:v,setResourcePreview:k,resourcePreviewLoading:B,setResourcePreviewLoading:x,newFolderOpen:N,setNewFolderOpen:R,newFolderName:T,setNewFolderName:_,fileDialogError:$,setFileDialogError:H,selectedFolder:ue,setSelectedFolder:Z,selectedFile:V,setSelectedFile:de,expandedFolders:I,setExpandedFolders:Y,moveEntry:te,setMoveEntry:ne,moveName:P,setMoveName:ge,moveDestination:we,setMoveDestination:Ce,deleteEntry:ee,setDeleteEntry:se,fileDragActive:b,setFileDragActive:U,uploadConflict:Q,setUploadConflict:xe,uploadingFiles:ae,directoryEntries:S,visibleEntries:_e,createFile:K,createFolder:De,uploadFiles:$e,upload:Se,openFile:F,movePath:Ee,movePathToFolder:A,removePath:O}}function Py(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Uy({active:t,projectId:e,activeFile:n,content:s,dictionaryWords:r}){const[i,l]=d.useState([]),[a,c]=d.useState(""),[u,f]=d.useState(""),[h,p]=d.useState(0),[w,g]=d.useState(null),[C,v]=d.useState(null),[k,B]=d.useState(!1),[x,N]=d.useState(0),R=d.useRef(0),T=d.useRef(!1),_=d.useRef(!1),$=d.useRef(s),H=d.useRef(n),ue=d.useRef(0);$.current=s,H.current=n,_.current=k,d.useEffect(()=>{l([]),c(""),f(""),g(null),v(null),B(!1)},[n,r]),d.useEffect(()=>{v(null),B(!1)},[e]),d.useEffect(()=>{p(I=>i.length?Math.min(I,i.length-1):0)},[i]),d.useEffect(()=>{const I=++R.current;if(!t||!n){l([]),c(""),f(""),g(null);return}if(C){l([]),c(""),f("");return}const Y=s,te=n;let ne=!1;const P=window.setTimeout(()=>{v(null),(async()=>{try{const{lintLatex:ge,isHarperLintSupersededError:we}=await Dt(async()=>{const{lintLatex:ee,isHarperLintSupersededError:se}=await import("./spellCheck-DyKIHf5C.js");return{lintLatex:ee,isHarperLintSupersededError:se}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url);if(ne||I!==R.current||$.current!==Y||H.current!==te)return;let Ce;try{Ce=await ge(e,te,Y,r)}catch(ee){if(we(ee))return;throw ee}if(ne||I!==R.current||$.current!==Y||H.current!==te)return;T.current=!1,B(!1),l(Ce),c(Y),f(te),p(0),g(null)}catch(ge){if(ne||I!==R.current||$.current!==Y||H.current!==te)return;l([]),c(""),f(""),v(ge instanceof Error?ge.message:String(ge));const we=T.current;T.current=!1,B(we?_.current:!1)}})()},700);return()=>{ne=!0,window.clearTimeout(P)}},[t,e,n,s,r,x,C]),d.useEffect(()=>{if(!C||!t)return;let I=!1;const Y=()=>{I||(I=!0,T.current=!0,v(null),N(ne=>ne+1))},te=window.setTimeout(Y,15e3);return window.addEventListener("online",Y,{once:!0}),()=>{window.clearTimeout(te),window.removeEventListener("online",Y)}},[C,t]);const Z=t&&u===n&&a===s,V=d.useMemo(()=>Z?{total:i.length,unique:new Set(i.map(I=>`${I.kind}:${I.word.toLocaleLowerCase("en-US")}`)).size}:null,[Z,i]);return{issues:Z?i:[],jump:Z?w:null,index:h,summary:V,jumpToIssue:I=>{if(!i.length)return;const Y=Math.max(0,Math.min(I,i.length-1)),te=i[Y];p(Y),g({from:te.from,to:te.to,nonce:++ue.current})},error:t&&!k?C:null,nativeFallback:t&&!!C,retry:()=>{T.current=!1,v(null),B(!1),N(I=>I+1)},dismissError:()=>{T.current=!1,B(!0)}}}function Na(t){return t instanceof Error&&t.name==="AbortError"}function zy({projectId:t,mainFile:e,activeFile:n,onActiveFile:s,onError:r,onShowPdf:i}){const[l,a]=d.useState(null),[c,u]=d.useState(null),[f,h]=d.useState(null),p=d.useRef(null),w=d.useRef(0),g=d.useRef(n),C=d.useRef(s),v=d.useRef(r),k=d.useRef(i),B=_=>_===e&&/\.tex$/i.test(_);g.current=n,C.current=s,v.current=r,k.current=i,d.useEffect(()=>(p.current?.abort(),p.current=null,a(null),u(null),h(null),()=>p.current?.abort()),[t,e]);const x=(_,$,H)=>{h({path:_,line:$,column:H,nonce:++w.current}),g.current!==_&&C.current(_)},N=async(_,$,H,ue={})=>{if(!B(_))return;p.current?.abort();const Z=new AbortController;p.current=Z;try{const V=await ce(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(_)}&line=${$}&column=${H}`,{signal:Z.signal});if(p.current!==Z||!V)return;a({...V,nonce:++w.current}),k.current()}catch(V){!Na(V)&&!ue.silent&&v.current(fe(V))}finally{p.current===Z&&(p.current=null)}},R=async(_,$,H)=>{if(!B(g.current))return;const ue=g.current;p.current?.abort();const Z=new AbortController;p.current=Z;try{const V=await ce(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${_}&x=${$}&y=${H}`,{signal:Z.signal});if(p.current!==Z||g.current!==ue||!B(g.current))return;x(V.path,V.line,V.column)}catch(V){Na(V)||v.current(fe(V))}finally{p.current===Z&&(p.current=null)}};return{pdfTarget:l,pdfViewport:c,sourceJump:f,setPdfViewport:u,clearPdfViewport:()=>u(null),jumpToSource:x,syncSourceToPdf:N,syncPdfToSource:R,syncVisiblePdfToSource:()=>{c&&R(c.page,c.x,c.y)}}}function Au(t,e){return gn(`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function Fa(t,e){try{const n=window.localStorage.getItem(Au(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function By(t,e){const[n,s]=d.useState(()=>Fa(t,e));return d.useEffect(()=>{s(Fa(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Au(t,e),i)}catch{}}}}function qy(t){return!/\.(?:bib|bst)$/i.test(t.trim())}const Nu=["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"],Wy=new Set(Nu);function Hy(t){return Wy.has(t)}function Vy(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 Oa(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 Fu(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 u=Vy(t,l,n);if(u===null)return null;l=u}if(i==="mintinline"){const u=Oa(t,l,n);if(u===null)return null;l=u}const a=t[l];if(!a||/\s/.test(a))return null;if(a==="{"&&i!=="verb"){const u=Oa(t,l,n);return{end:u??n,closed:u!==null}}const c=t.indexOf(a,l+1);return c<0||c>=n?{end:n,closed:!1}:{end:c+1,closed:!0}}function Ou(t,e,n=t.length){return Fu(t,e,n)?.end??null}function Go(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 Ns(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function Ky(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 Mu(t,e){const n=/^\\begin\s*\{\s*([A-Za-z0-9@:_*.\-]+)\s*\}/.exec(t.slice(e));return!n||!Hy(n[1])?null:{name:n[1],to:e+n[0].length}}function gx(t,e){const n=Math.max(0,Math.min(t.length,e));for(let s=0;s<n;){if(t[s]==="%"&&!Ns(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]!=="\\"||Ns(t,s)){s+=1;continue}const r=Fu(t,s);if(r!==null){if(n<r.end||!r.closed&&n<=r.end)return"literal";s=r.end;continue}const i=Mu(t,s);if(i){const l=Go(t,i.to,i.name),a=l?.to??t.length;if(n<a||!l&&n<=a)return"literal";s=a;continue}s=Ky(t,s)}return null}function Ma(t,e,n){return t.slice(e,n).replace(/[^\r\n]/g," ")}function Gy(t){const e=t.split("");for(let n=0;n<t.length;n+=1){if(t[n]!=="%"||Ns(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 Jy(t){let e="",n=0;for(;n<t.length;){if(t[n]==="%"&&!Ns(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]!=="\\"||Ns(t,n)){e+=t[n],n+=1;continue}const s=Ou(t,n);if(s!==null){e+=Ma(t,n,s),n=s;continue}const r=Mu(t,n);if(r){const l=Go(t,r.to,r.name)?.to??t.length;e+=Ma(t,n,l),n=l;continue}e+=t[n],n+=1}return e}function Yy(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function $a(t){const e=Gy(Jy(t)),n=/\\documentclass(?![A-Za-z@])\s*(?:\[[^\]]*\]\s*)?\{/g;for(const s of e.matchAll(n))if(s.index!==void 0&&!Yy(e,s.index))return!0;return!1}const Xy=new Set(Nu);function Zy(t){return/[A-Za-z@0-9:_-]/.test(t)}function Qy(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function as(t,e){return t[e]==="%"&&!Qy(t,e)}function zs(t,e){const n=t.indexOf(`
|
|
15
|
+
`,e);return n===-1?t.length:n}function Dr(t,e){let n=e;for(;n<t.length;){if(/\s/.test(t[n])){n+=1;continue}if(as(t,n)){n=zs(t,n);continue}break}return n}function oo(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(as(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 lo(t,e,n){const s=[];let r=e;for(;s.length<n;){for(r=Dr(t,r);t[r]==="[";){const l=oo(t,r,"[","]");if(!l)return s;r=Dr(t,l.to)}if(t[r]!=="{")break;const i=oo(t,r,"{","}");if(!i)break;s.push(i),r=i.to}return s}function wx(t,e,n){const s=[];let r=e;for(;s.length<n&&(r=Dr(t,r),t[r]==="[");){const i=oo(t,r,"[","]");if(!i)break;s.push(i),r=i.to}return s}function eb(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&&Zy(t[n]);)n+=1;const s=t.slice(e+1,n);return t[n]==="*"&&(n+=1),{name:s,from:e,to:n}}function tb(t,e){if(e.name!=="begin")return e.to;const n=lo(t,e.to,1)[0];if(!n)return e.to;const s=t.slice(n.contentFrom,n.contentTo).trim();return Xy.has(s)?Go(t,n.to,s)?.to??t.length:e.to}function nb(t,e){let n=0;for(;n<t.length;){if(as(t,n)){n=zs(t,n);continue}if(t[n]!=="\\"){n+=1;continue}const s=eb(t,n);if(!s){n+=1;continue}const r=Ou(t,s.from);if(r!==null&&r>s.to){n=r;continue}const i=tb(t,s);if(i>s.to){n=i;continue}e(s),n=s.to}}function Oi(t,e,n){const s=[];let r=e.contentFrom,i=e.contentFrom;for(;i<=e.contentTo;){if(i<e.contentTo&&as(t,i)){i=zs(t,i),t[i]===`
|
|
16
|
+
`&&(i+=1);continue}if(i!==e.contentTo){i+=1;continue}const l=sb(t,r,i);l&&s.push(l),r=i+1,i+=1}return s}function sb(t,e,n){const s=[];let r=e;for(;r<n;){if(as(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 rb(t,e){const n=Dr(t,e);if(n>=t.length||/[\\{}\[\]#~]/.test(t[n]))return null;let s=n;for(;s<t.length&&!/\s/.test(t[s])&&!as(t,s)&&!/[\\{}\[\]#~]/.test(t[s]);)s+=1;return s===n?null:{path:t.slice(n,s),command:"",from:n,to:s}}function Ia(t){const e=[];return nb(t,n=>{const s=n.name.toLowerCase();if(s==="input"||s==="include"||s==="subfile"){const c=lo(t,n.to,1)[0];if(c)for(const u of Oi(t,c))e.push({...u,command:n.name});else if(s==="input"){const u=rb(t,n.to);u&&e.push({...u,command:n.name})}return}if(s!=="import"&&s!=="subimport"&&s!=="includefrom"&&s!=="inputfrom"&&s!=="subinputfrom"&&s!=="subincludefrom")return;const r=lo(t,n.to,2);if(r.length!==2)return;const i=Oi(t,r[0])[0]?.path??"",l=Oi(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 ib({sessions:t,status:e}){const{t:n}=Xe(),[s,r]=d.useState(!1),i=Math.max(0,t.length-5),l=s&&i>0,a=l?t:t.slice(0,5);return d.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 u=c.editing?n("editor.collaboration.editing"):n("editor.collaboration.viewing"),f=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:u,permission:f});return o.jsxs("span",{className:`collaboration-avatar${c.editing?" editing":""}${c.local?" local":""}`,style:{"--session-color":c.color},"aria-label":h,tabIndex:0,children:[Ly(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")," · ",u," · ",f]})]})]},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 ob({value:t,onChange:e}){const{t:n}=Xe(),[s,r]=d.useState(!1),i=d.useRef(null),l=[{value:"editor-pdf",icon:Bl},{value:"editor-only",icon:wf},{value:"pdf-only",icon:yf}];return d.useEffect(()=>{if(!s)return;const a=u=>{i.current?.contains(u.target)||r(!1)},c=u=>{u.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(Bl,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(uo,{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,u=a.value===t;return o.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":u,className:`layout-option${u?" 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`)})]}),u&&o.jsx(qh,{size:16})]},a.value)})]})]})}function lb({site:t,project:e,activeFile:n,saveStateLabel:s,editorPreferences:r,activeSessions:i,collaborationStatus:l,reconnectCollaboration:a,protocolUpgradeRequired:c,showEditor:u,filesCollapsed:f,toggleFilesPanel:h,workspaceLayout:p,changeWorkspaceLayout:w,onBack:g,onShare:C,showCitationLibrary:v,citationLibraryOpen:k,onCitationLibrary:B,onSelectionHistory:x,onHistory:N,onGit:R,canManageGit:T,formatting:_,readOnly:$,collaborationSynced:H,hasSelection:ue,onToggleComments:Z,commentsOpen:V,unresolvedCommentCount:de,hasActiveFile:I,onToggleSettings:Y,settingsOpen:te,compileBusy:ne,sharedCompiling:P,localCompiling:ge,cancelling:we,compileState:Ce,onCompile:ee,onCancelCompile:se}){const{t:b}=Xe();return o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:b("editor.backToProjects"),"aria-label":b("editor.backToProjects"),onClick:g,children:o.jsx(Wh,{size:18})}),o.jsx("a",{className:"brand-link compact-brand-link",href:ss("/"),"aria-label":t.siteName,onClick:U=>{U.preventDefault(),g()},children:o.jsx(Uh,{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:b("editor.vimOnHint"),children:[o.jsx(pf,{size:14}),b("editor.vimOn")]}),o.jsx(ib,{sessions:i,status:l}),l==="disconnected"&&!c&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:b("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:a,children:b("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[u&&o.jsxs("button",{className:f?"":"active",onClick:h,children:[f?o.jsx(gf,{size:15}):o.jsx(Ga,{size:15}),b("common.files")]}),o.jsx(ob,{value:p,onChange:w}),o.jsxs("button",{onClick:C,children:[o.jsx(Pi,{size:15}),b("projectSettings.share")]}),v&&o.jsxs("button",{className:k?"active":"",onClick:B,children:[o.jsx(Hh,{size:15}),b("citationLibrary.title")]}),o.jsxs("div",{className:"history-action",role:"group","aria-label":b("history.title"),children:[o.jsxs("div",{className:"history-action-label",children:[o.jsx(af,{size:14}),o.jsx("span",{children:b("history.title")})]}),o.jsxs("div",{className:"history-action-options",children:[o.jsx("button",{type:"button",className:"history-action-selection",title:b(ue?"selectionHistory.title":"selectionHistory.selectSourceHint"),onMouseDown:U=>U.preventDefault(),onClick:x,disabled:!ue||!I,children:b("selectionHistory.buttonLabel")}),o.jsx("button",{type:"button",className:"history-action-snapshots",title:b("history.projectSnapshots"),onClick:N,children:b("history.projectSnapshotsButton")})]})]}),o.jsxs("button",{type:"button",className:`comments-action${V?" active":""}`,title:b("editor.commentsAll"),"aria-label":de>0?`${b("common.comments")} (${de})`:b("common.comments"),onClick:Z,children:[o.jsx(Vh,{size:15}),o.jsx("span",{children:b("common.comments")}),de>0&&o.jsx("sup",{className:"comments-action-count",children:de})]}),o.jsxs("button",{className:"git-action",title:b(T?"git.title":"git.ownerOnly"),disabled:!T,onClick:R,children:[o.jsx(Kh,{size:15}),"Git"]}),o.jsxs("button",{className:te?"active":"",onClick:Y,children:[o.jsx(Cf,{size:15}),b("common.settings")]}),P||ge?o.jsxs("button",{className:"compile cancel-compile",title:b("compileControls.cancel"),onClick:se,disabled:we||_||$||!H,children:[we?o.jsx(rt,{className:"spin",size:15}):o.jsx(Ss,{size:15}),b(we?"compileControls.cancelling":"compileControls.cancel")]}):o.jsxs("button",{className:"compile",title:b("editor.compileShortcut"),onClick:ee,disabled:ne||_||$||!H,children:[ne?o.jsx(rt,{className:"spin",size:15}):o.jsx(bf,{size:15}),b("editor.compile",{engine:e.engine})]})]})]})}function ab(t){return`${t.path}\0${t.line}`}function cb(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:ab(s),ancestorKeys:n.map(({index:i})=>e[i].key),hasChildren:!1}),n.push({level:s.level,index:e.length-1})}return e}function ub(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"]),hb=new Set(["latex","ltx","tex"]),fb=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"]),pb=new Set(["cfg","conf","dat","env","ini","text","toml","txt"]),mb=new Set(["csv","ods","tsv","xls","xlsx"]),gb=new Set(["7z","bz2","gz","rar","tar","xz","zip"]),wb=new Set(["m4a","mp3","ogg","wav"]),yb=new Set(["avi","mkv","mov","mp4","webm"]);function bb(t){const e=t.split("/").at(-1)?.toLocaleLowerCase()??"";if(e===".latexmkrc"||e==="latexmkrc"||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":hb.has(n)?"tex":n==="bib"||n==="bibtex"?"bib":fb.has(n)?"code":pb.has(n)?"text":mb.has(n)?"spreadsheet":gb.has(n)?"archive":wb.has(n)?"audio":yb.has(n)?"video":"file"}const xb={pdf:df,tex:Pl,bib:mf,image:cf,markdown:Ha,text:Jh,code:Pl,spreadsheet:Gh,archive:Ui,audio:lf,video:hf,file:Tr};function $u({path:t,size:e=13}){const n=bb(t);if(n==="pdf"||n==="tex")return o.jsx("img",{className:`file-type-icon file-type-icon-${n}`,src:ss(`/${n==="pdf"?"pdf-file":"tex-file"}.svg`),width:e,height:e,alt:"","aria-hidden":"true"});const s=xb[n]??ff;return o.jsx(s,{className:`file-type-icon file-type-icon-${n}`,size:e,"aria-hidden":"true"})}const Iu="application/x-texlite-project-path",Pu="texlite-path:";function kb({project:t,filesPanel:e,files:n,visibleEntries:s,activeFile:r,activeMainFile:i,selectedFile:l,selectedFolder:a,expandedFolders:c,fileDragActive:u,uploadingFiles:f,readOnly:h,formatting:p,canFormat:w,activeFormatLease:g,collaborationSynced:C,editorFontSize:v,outline:k,sourceCursorStore:B,wordCountBusy:x,hasSelection:N,hasFormatSelection:R,uploadInput:T,setSelectedFolder:_,setExpandedFolders:$,setMoveEntry:H,setMoveName:ue,setMoveDestination:Z,setDeleteEntry:V,setFileDialogError:de,setNewFolderName:I,setNewFolderOpen:Y,setNewFilePath:te,setNewFileOpen:ne,setQuickOpen:P,setProjectSearchOpen:ge,setFileDragActive:we,setFilesCollapsed:Ce,toggleFilesPanel:ee,uploadFiles:se,upload:b,openFile:U,movePathToFolder:Q,onError:xe,onFormatFile:ae,onFormatSelection:ke,jumpToSource:Ne,syncSourceToPdf:pe,onWordCount:q}){const{t:K}=Xe(),[De,$e]=d.useState(!1),[Se,je]=d.useState(null),[F,re]=d.useState(null),Ee=d.useRef(0),A=(S,_e)=>Cb(S.path)!==_e&&(S.type!=="directory"||_e!==S.path&&!_e.startsWith(`${S.path}/`)),O=()=>{je(null),re(null)};return o.jsx(_r,{id:"files",order:1,ref:e,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>Ce(!0),onExpand:()=>Ce(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${u?" drop-active":""}`,onDragEnter:S=>{if(mn(S.dataTransfer)){S.preventDefault();return}S.dataTransfer.types.includes("Files")&&(S.preventDefault(),!h&&!f&&we(!0))},onDragOver:S=>{if(mn(S.dataTransfer)){S.preventDefault(),S.dataTransfer.dropEffect="move";return}S.dataTransfer.types.includes("Files")&&(S.preventDefault(),S.dataTransfer.dropEffect=h||f?"none":"copy")},onDragLeave:S=>{S.currentTarget.contains(S.relatedTarget)||we(!1)},onDrop:S=>{if(mn(S.dataTransfer)){S.preventDefault(),S.stopPropagation();return}if(S.preventDefault(),we(!1),h||f)return;const _e=Array.from(S.dataTransfer.files);if(Sb(S.dataTransfer)||_e.length===0){xe(K("editor.dropFoldersUnsupported"));return}se(_e)},children:[o.jsxs("div",{className:"panel-title",children:[o.jsx("button",{className:"file-size-toggle",type:"button","aria-pressed":De,title:K(De?"editor.hideFileSizes":"editor.showFileSizes"),onClick:()=>$e(S=>!S),children:K("common.files")}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{type:"button","aria-label":K("navigation.quickOpen"),title:`${K("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>P(!0),children:o.jsx(Yh,{size:15})}),o.jsx("button",{type:"button","aria-label":K("navigation.projectSearch"),title:`${K("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>ge(!0),children:o.jsx(tf,{size:15})}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:f,"aria-label":K("editor.uploadAttachment"),title:K("editor.uploadTo",{folder:a||K("editor.projectRoot")}),onClick:()=>T.current?.click(),children:o.jsx(Ul,{size:15})}),o.jsx("button",{type:"button","aria-label":K("editor.newFolder"),title:K("editor.newFolder"),onClick:()=>{I(""),Y(!0)},children:o.jsx(Xh,{size:15})}),o.jsx("button",{type:"button","aria-label":K("editor.newFile"),title:K("editor.newFile"),onClick:()=>{te(a?`${a}/`:""),ne(!0)},children:o.jsx(uf,{size:15})}),o.jsx("input",{ref:T,type:"file",multiple:!0,hidden:!0,onChange:S=>{b(S)}})]}),o.jsx("button",{type:"button","aria-label":K("editor.collapseFiles"),title:K("editor.collapseFiles"),onClick:ee,children:o.jsx(Ga,{size:15})})]})]}),u&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(Ul,{size:24}),o.jsx("strong",{children:K("editor.dropFiles")}),o.jsx("span",{children:K("editor.uploadTo",{folder:a||K("editor.projectRoot")})})]}),o.jsx("div",{className:`file-list${a!==null?" folder-selected":""}${F===""?" root-drop-target":""}`,style:{fontSize:`${v}px`},onDragOver:S=>{if(!(!Se&&!mn(S.dataTransfer))&&(S.preventDefault(),S.stopPropagation(),!!Se)){if(!A(Se,"")){S.dataTransfer.dropEffect="none";return}S.dataTransfer.dropEffect="move",re("")}},onDragLeave:S=>{S.currentTarget.contains(S.relatedTarget)||re(_e=>_e===""?null:_e)},onDrop:S=>{if(!Se&&!mn(S.dataTransfer)||(S.preventDefault(),S.stopPropagation(),!Se))return;const _e=Se;O(),A(_e,"")&&Q(_e,"")},children:s.map(S=>{const _e=S.path.split("/").length-1,M=S.path.split("/").at(-1),he=c.has(S.path),Fe=t.mainFile===S.path,Be=S.path!==t.mainFile&&!t.mainFile.startsWith(`${S.path}/`);return S.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${a===S.path?" selected":""}${F===S.path?" move-drop-target":""}`,style:{paddingLeft:`${_e*13+5}px`},onDragOver:ye=>{if(!(!Se&&!mn(ye.dataTransfer))&&(ye.preventDefault(),ye.stopPropagation(),!!Se)){if(!A(Se,S.path)){ye.dataTransfer.dropEffect="none";return}ye.dataTransfer.dropEffect="move",re(S.path)}},onDragLeave:ye=>{ye.currentTarget.contains(ye.relatedTarget)||re(L=>L===S.path?null:L)},onDrop:ye=>{if(!Se&&!mn(ye.dataTransfer)||(ye.preventDefault(),ye.stopPropagation(),!Se))return;const L=Se;O(),A(L,S.path)&&Q(L,S.path)},children:[o.jsxs("button",{type:"button",className:"file-entry-main",onClick:()=>{_(S.path),$(ye=>{const L=new Set(ye);return L.has(S.path)?L.delete(S.path):L.add(S.path),L})},children:[he?o.jsx(uo,{size:13}):o.jsx(co,{size:13}),o.jsx(Zh,{size:14}),o.jsx("span",{children:M})]}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"file-entry-action",title:K("editor.move"),"aria-label":K("editor.move"),onClick:()=>{H(S),ue(M??""),Z("")},children:o.jsx(Wl,{size:13})}),Be&&o.jsx("button",{type:"button",className:"file-entry-action danger-text",title:K("editor.deletePath"),"aria-label":K("editor.deletePath"),onClick:()=>{V(S),de("")},children:o.jsx(tn,{size:13})})]})]},S.path):o.jsxs("div",{className:`file-entry${a===null&&l===S.path?" active":""}${Se?.path===S.path?" move-drag-source":""}`,style:{paddingLeft:`${_e*13+18}px`},children:[o.jsxs("button",{type:"button",className:"file-entry-main",draggable:!h,onDragStart:ye=>{Ee.current=Date.now()+500,vb(ye,S,je)},onDragEnd:O,onClick:()=>{if(Ee.current>Date.now()){Ee.current=0;return}U(S)},children:[o.jsx($u,{path:S.path}),o.jsx("span",{children:M}),Fe&&o.jsx("small",{children:K("editor.currentMainShort")})]}),De&&typeof S.size=="number"&&o.jsx("span",{className:"file-entry-size",children:Eb(S.size)}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"file-entry-action",title:K("editor.move"),"aria-label":K("editor.move"),onClick:()=>{H(S),ue(M??""),Z("")},children:o.jsx(Wl,{size:13})}),Be&&o.jsx("button",{type:"button",className:"file-entry-action danger-text",title:K("editor.deletePath"),"aria-label":K("editor.deletePath"),onClick:()=>{V(S),de("")},children:o.jsx(tn,{size:13})})]})]},S.path)})}),!h&&w&&o.jsxs("div",{className:"file-format-footer",role:"group","aria-label":K("editor.format"),"aria-busy":p,children:[o.jsxs("div",{className:"file-format-label",children:[o.jsx(rf,{size:13}),K("editor.format")]}),o.jsxs("div",{className:"file-format-actions",children:[o.jsx("button",{className:R?"":"active",type:"button",title:K("editor.formatFileHint"),onMouseDown:S=>S.preventDefault(),onClick:ae,disabled:p||g||!C,children:K("editor.formatFile")}),o.jsx("button",{className:R?"active":"",type:"button",title:K(R?"editor.formatSelection":"editor.formatSelectionHint"),onMouseDown:S=>S.preventDefault(),onClick:ke,disabled:p||g||!C||!R,children:K("editor.formatSelected")})]})]})]}),o.jsx(jb,{outline:k,activeFile:r,activeMainFile:i,sourceCursorStore:B,wordCountBusy:x,hasSelection:N,jumpToSource:Ne,syncSourceToPdf:pe,onWordCount:q})]})})}function Sb(t){return Array.from(t.items).some(e=>e.webkitGetAsEntry?.()?.isDirectory===!0)}function mn(t){return Array.from(t.types).includes(Iu)?!0:Array.from(t.types).includes("text/plain")&&t.getData("text/plain").startsWith(Pu)}function Cb(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function vb(t,e,n){t.dataTransfer.effectAllowed="move",t.dataTransfer.setData(Iu,e.path),t.dataTransfer.setData("text/plain",`${Pu}${e.path}`),n(e)}function jb({outline:t,activeFile:e,activeMainFile:n,sourceCursorStore:s,wordCountBusy:r,hasSelection:i,jumpToSource:l,syncSourceToPdf:a,onWordCount:c}){const{t:u}=Xe(),f=d.useSyncExternalStore(s.subscribe,s.getOutlineLine,s.getOutlineLine),h=d.useMemo(()=>cb(t),[t]),p=d.useMemo(()=>h.filter(x=>x.hasChildren).map(x=>x.key),[h]),[w,g]=d.useState(()=>new Set);d.useEffect(()=>{const x=new Set(p);g(N=>{const R=new Set([...N].filter(T=>x.has(T)));return R.size===N.size?N:R})},[p]);const C=p.length>0&&p.every(x=>w.has(x)),v=d.useMemo(()=>ub(h,w),[h,w]),k=()=>g(x=>C?new Set([...x].filter(N=>!p.includes(N))):new Set([...x,...p])),B=x=>g(N=>{const R=new Set(N);return R.has(x)?R.delete(x):R.add(x),R});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":!C,title:u(C?"editor.expandOutline":"editor.collapseOutline"),onClick:k,disabled:p.length===0,children:[o.jsx(Qh,{size:14}),u("common.outline")]}),o.jsxs("span",{className:"word-count-actions",role:"group","aria-label":u("editor.wordCountTitle"),children:[o.jsxs("button",{type:"button",title:u("editor.wordCountFullHint"),onClick:()=>c("full"),disabled:r||!n,children:[r?o.jsx(rt,{className:"spin",size:12}):o.jsx(ql,{size:12}),u("editor.wordCountFull")]}),o.jsxs("button",{type:"button",title:u("editor.wordCountSelectionHint"),onClick:()=>c("selection"),disabled:r||!i,children:[r?o.jsx(rt,{className:"spin",size:12}):o.jsx(ql,{size:12}),u("editor.wordCountSelection")]})]})]}),o.jsxs("div",{className:"outline",children:[v.map(x=>{const{item:N}=x,R=w.has(x.key),T=e===N.path&&f===N.line,_=N.path===n||N.path===e;return o.jsxs("div",{className:`outline-row${T?" current":""}`,children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${N.level*12}px`}}),x.hasChildren?o.jsx("button",{className:"outline-toggle",type:"button","aria-label":u(R?"editor.expandOutlineItem":"editor.collapseOutlineItem",{title:N.title}),"aria-expanded":!R,onClick:()=>B(x.key),children:R?o.jsx(co,{size:13}):o.jsx(uo,{size:13})}):o.jsx("span",{className:"outline-toggle-spacer","aria-hidden":!0}),o.jsxs("button",{className:"outline-item",type:"button",onClick:()=>{l(N.path,N.line,1),a(N.path,N.line,1)},children:[o.jsx("small",{children:_?N.line:N.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:N.title})]})]},x.key)}),t.length===0&&o.jsx("p",{className:"muted padded",children:u("editor.noOutline")})]})]})}function Eb(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 Db=d.lazy(()=>Dt(()=>import("./LatexEditor-Dmy6_gqt.js"),__vite__mapDeps([9,2,10,1,3,4,5,6,7,8]),import.meta.url).then(t=>({default:t.LatexEditor})));function _b({project:t,activeFile:e,openTabs:n,content:s,loadedFile:r,readOnly:i,comments:l,focusComment:a,editorPreferences:c,completionIndex:u,nativeSpellCheck:f,spellCheckIssues:h,spellCheckJump:p,sourceJump:w,collaborativeText:g,collaborationAwareness:C,undoManager:v,editorNotice:k,activateTab:B,closeTab:x,handleTabKeyDown:N,updateEditorContent:R,setSelection:T,onAddComment:_,onCommentClick:$,onSpellCheckReplace:H,onReferenceNavigate:ue,onCursor:Z}){const{t:V}=Xe(),de=Zf(l,e),I=Qf(a,e,r);return o.jsx(_r,{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":V("editor.openFiles"),children:o.jsx("div",{className:"editor-tabs-scroll",children:n.map((Y,te)=>{const ne=Y===e,P=Y===t.mainFile,ge=Y.split("/").at(-1)||Y;return o.jsxs("div",{className:`editor-tab-item${ne?" active":""}`,role:"presentation",children:[o.jsxs("button",{id:`editor-tab-${encodeURIComponent(Y)}`,type:"button",role:"tab","aria-selected":ne,"aria-controls":"editor-source-content",tabIndex:ne?0:-1,className:`editor-tab${ne?" active":""}${P?" main-tab":""}`,onClick:()=>B(Y),onKeyDown:we=>N(we,te),title:Y,children:[o.jsx("span",{className:"editor-tab-icon",children:P?o.jsx(Ha,{size:13}):o.jsx(Tr,{size:13})}),o.jsx("span",{className:"editor-tab-title",children:ge}),P&&o.jsx("small",{className:"editor-tab-badge",children:V("editor.currentMainShort")})]}),o.jsx("button",{type:"button",className:"editor-tab-close",title:V("common.close"),"aria-label":`${V("common.close")} ${ge}`,onClick:()=>x(Y),children:o.jsx(Ss,{size:12})})]},Y)})})}),o.jsxs("div",{id:"editor-source-content",className:"editor-content-container",children:[o.jsx(d.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(rt,{className:"spin",size:22}),o.jsx("span",{children:V("common.loading")})]}),children:o.jsx(Db,{value:s,filePath:e,readOnly:i,comments:de,focusComment:I,preferences:c,nativeSpellCheck:f,completionIndex:u,spellCheckIssues:h,spellCheckJump:p,jumpTo:r===e&&w?.path===e?w:null,searchRequest:0,collaboration:g?{text:g,awareness:C,undoManager:i?void 0:v}:void 0,onChange:R,onSelection:T,onAddComment:_,onCommentClick:$,onSpellCheckReplace:H,onReferenceNavigate:ue,onCursor:Z},e)}),k&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:k})]})]})})}function Pa({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=Xe(),l=s==="error"?ho:zt;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((a,c)=>{const u=Rb(a.file,e),f=!!(u&&a.line);return o.jsxs("button",{type:"button",disabled:!f,className:"compile-diagnostic-row",onClick:()=>{u&&a.line&&r(u,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,u?` · ${u}${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 Mi({lines:t,empty:e,tone:n="log"}){const s=n==="error"?ho:n==="warning"?zt: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 Tb({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:l}=Xe(),a=c=>ss(`/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($u,{path:c.path,size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:c.path}),o.jsx("small",{children:Ab(c.size)})]})]}),o.jsx("a",{href:a(c.path),title:l("editor.downloadArtifact"),"aria-label":l("editor.downloadArtifact"),children:o.jsx(cr,{size:14})})]},c.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(rt,{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(cr,{size:13}),l("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Tr,{size:24}),o.jsx("span",{children:l("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Ka,{size:26}),o.jsx("span",{children:l("editor.noArtifacts")})]})}function Lb({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=Xe();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(zt,{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(Bi,{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(rt,{className:"spin",size:14}):o.jsx(Bi,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(tn,{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(rt,{className:"spin",size:14}):o.jsx(tn,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function Rb(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 Ab(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const Nb=d.lazy(()=>qa().then(t=>({default:t.PdfPreview})));function Fb({projectId:t,activeMainFile:e,previewTab:n,diagnosticTab:s,pdfUrl:r,pdfLoadingMode:i,pdfLoading:l,pdfCompiledAt:a,pdfCompiledLabel:c,pdfTargetLabel:u,pdfDownloadUrl:f,pdfTarget:h,pdfViewport:p,activeFile:w,compileBusy:g,compileLog:C,compileDiagnostics:v,compileMessages:k,artifacts:B,artifactPreview:x,artifactLoading:N,cleaning:R,readOnly:T,collaborationSynced:_,workspaceLayout:$,showSyncResize:H,diagnosticCount:ue,selectPreviewTab:Z,changeWorkspaceLayout:V,onSetNotice:de,onSetPdfViewport:I,syncVisiblePdfToSource:Y,syncCurrentSourceToPdf:te,syncPdfToSource:ne,canSyncWithPdf:P,files:ge,jumpToSource:we,onSetCleanMode:Ce,cleanCompile:ee,viewArtifact:se}){const{t:b}=Xe();return o.jsxs(o.Fragment,{children:[H&&o.jsxs(ao,{className:"resize-handle sync-resize-handle",children:[o.jsx(Va,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:U=>U.stopPropagation(),children:[o.jsx("button",{disabled:!p||!P,title:b(P?"editor.showInSource":"editor.syncTexOnlyForMain"),"aria-label":b("editor.showInSource"),onClick:()=>{if(!P){de(b("editor.syncTexOnlyForMain"));return}Y()},children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!w||!r||!P,title:b(P?"editor.showInPdf":"editor.syncTexOnlyForMain"),"aria-label":b("editor.showInPdf"),onClick:()=>{if(!P){de(b("editor.syncTexOnlyForMain"));return}te()},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),o.jsx(_r,{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":b("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":n==="pdf",className:`pdf-tab${n==="pdf"?" active":""}`,onClick:()=>Z("pdf"),title:a?b("editor.pdfCompiledAtFor",{file:e,time:new Date(a).toLocaleString(ys.resolvedLanguage)}):b("editor.currentMainDocument",{path:e}),children:[o.jsx("img",{className:"pdf-tab-icon",src:ss("/pdf-download.svg"),alt:"","aria-hidden":"true"}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",u,c&&o.jsx("small",{children:c})]})]}),o.jsxs("button",{role:"tab","aria-selected":n==="diagnostics",className:`diagnostics-tab${n==="diagnostics"?" active":""}`,onClick:()=>Z("diagnostics"),children:[o.jsx(zi,{size:14}),b("editor.outputTabs"),o.jsx("span",{children:ue})]})]}),f&&o.jsxs("a",{className:"pdf-download-top",href:f,download:!0,title:b("editor.downloadPdf"),"aria-label":b("editor.downloadPdf"),children:[o.jsx(cr,{size:15}),o.jsx("span",{children:b("editor.downloadPdf")})]})]}),n==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":b("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":s==="log",className:s==="log"?"active":"",onClick:()=>Z("log"),children:[o.jsx(zi,{size:13}),b("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":s==="warnings",className:s==="warnings"?"active":"",onClick:()=>Z("warnings"),children:[o.jsx(zt,{size:13}),b("editor.warnings"),o.jsx("span",{children:k.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="errors",className:s==="errors"?"active":"",onClick:()=>Z("errors"),children:[o.jsx(ho,{size:13}),b("editor.errors"),o.jsx("span",{children:k.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="artifacts",className:s==="artifacts"?"active":"",onClick:()=>Z("artifacts"),children:[o.jsx(Ka,{size:13}),b("editor.artifacts"),o.jsx("span",{children:B.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="clean",className:s==="clean"?"active":"",onClick:()=>Z("clean"),children:[o.jsx(Bi,{size:13}),b("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${n} ${n==="diagnostics"?`preview-${s}`:""}`,children:[n==="pdf"&&(r?o.jsx(d.Suspense,{fallback:o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(rt,{className:"spin",size:24}),o.jsx("span",{children:b("editor.loadingPdf")})]}),children:o.jsx(Nb,{url:r,loadingMode:i,target:h,compiling:g,onViewportLocation:(U,Q,xe)=>I({page:U,x:Q,y:xe}),onDoubleClickLocation:(U,Q,xe)=>{if(I({page:U,x:Q,y:xe}),!P){de(b("editor.syncTexOnlyForMain"));return}ne(U,Q,xe)}})}):l?o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(rt,{className:"spin",size:24}),o.jsx("span",{children:b("editor.loadingPdf")})]}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Tr,{size:28}),o.jsx("strong",{children:b("editor.preview")}),o.jsx("span",{children:b("editor.previewHint")})]})),n==="diagnostics"&&s==="log"&&o.jsx(Mi,{lines:C?C.split(`
|
|
19
|
+
`):[],empty:b(g?"editor.compiling":"editor.noLog")}),n==="diagnostics"&&s==="warnings"&&(v?o.jsx(Pa,{tone:"warning",diagnostics:v.warnings,files:ge,empty:b("editor.noWarnings"),onJump:(U,Q,xe)=>{$==="pdf-only"&&V("editor-pdf"),we(U,Q,xe)}}):o.jsx(Mi,{tone:"warning",lines:k.warnings,empty:b("editor.noWarnings")})),n==="diagnostics"&&s==="errors"&&(v?o.jsx(Pa,{tone:"error",diagnostics:v.errors,files:ge,empty:b("editor.noErrors"),onJump:(U,Q,xe)=>{$==="pdf-only"&&V("editor-pdf"),we(U,Q,xe)}}):o.jsx(Mi,{tone:"error",lines:k.errors,empty:b("editor.noErrors")})),n==="diagnostics"&&s==="artifacts"&&o.jsx(Tb,{projectId:t,mainFile:e,artifacts:B,preview:x,loading:N,onView:U=>{se(U)}}),n==="diagnostics"&&s==="clean"&&o.jsx(Lb,{mainFile:e,disabled:T||!_||g,cleaning:R,onCleanCache:()=>Ce("cache"),onCleanArtifacts:()=>Ce("artifacts")})]})]})})]})}function Ob(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 ar({projectId:t,value:e,onChange:n,onKeyDown:s,onFocus:r,...i}){const{t:l}=Xe(),a=d.useRef(null),[c,u]=d.useState(null),[f,h]=d.useState(!1),[p,w]=d.useState(null),[g,C]=d.useState(0),v=d.useMemo(()=>{if(!p||!c)return[];const T=p.query.toLocaleLowerCase();return(T?c.filter($=>$.username.toLocaleLowerCase().includes(T)||$.displayName.toLocaleLowerCase().includes(T)):c).slice(0,8)},[c,p]),k=!!(p&&v.length),B=async()=>{if(!(c||f)){h(!0);try{const T=await ce(`/api/projects/${t}/mention-candidates`);u(T.users)}catch{u([])}finally{h(!1)}}},x=(T,_)=>{const $=Ob(T,_);w($),C(0),$&&B()},N=T=>{if(!p)return;const _=`@${T.username} `,$=`${e.slice(0,p.start)}${_}${e.slice(p.end)}`,H=p.start+_.length;n($),w(null),C(0),window.requestAnimationFrame(()=>{a.current?.focus(),a.current?.setSelectionRange(H,H)})},R=T=>{if(!T.nativeEvent.isComposing&&k){if(T.key==="ArrowDown"){T.preventDefault(),C(_=>(_+1)%v.length);return}if(T.key==="ArrowUp"){T.preventDefault(),C(_=>(_-1+v.length)%v.length);return}if(T.key==="Enter"&&!T.ctrlKey&&!T.metaKey&&!T.shiftKey){T.preventDefault(),N(v[g]??v[0]);return}if(T.key==="Escape"){w(null);return}}s?.(T)};return o.jsxs("span",{className:"mention-textarea",children:[o.jsx("textarea",{...i,ref:a,value:e,onFocus:T=>{r?.(T),x(e,T.currentTarget.selectionStart??e.length)},onClick:T=>x(e,T.currentTarget.selectionStart??e.length),onChange:T=>{const _=T.currentTarget.value;n(_),x(_,T.currentTarget.selectionStart??_.length)},onKeyDown:R}),k&&o.jsx("span",{className:"mention-menu",role:"listbox","aria-label":l("editor.mentionUsers"),children:v.map((T,_)=>o.jsxs("button",{type:"button",role:"option","aria-selected":_===g,className:_===g?"active":"",onMouseDown:$=>$.preventDefault(),onClick:()=>N(T),children:[o.jsx(ur,{"aria-hidden":!0,size:13}),o.jsxs("span",{children:[o.jsx("strong",{children:T.displayName}),o.jsxs("small",{children:["(",T.username,")"]})]})]},T.id))})]})}function $i(t,e){!(t.ctrlKey||t.metaKey)||t.key!=="Enter"||t.nativeEvent.isComposing||(t.preventDefault(),t.stopPropagation(),e())}function Ua(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 Mb({projectId:t,comment:e,currentUserId:n,unreadCommentMentionId:s,unreadReplyMentionIds:r,highlightedComment:i,highlightedReplyId:l,currentComment:a,showFilePath:c,onMarkMentionRead:u,onFocus:f,onToggle:h,onReply:p,onEdit:w,onDelete:g,onEditReply:C,onDeleteReply:v}){const{t:k}=Xe(),[B,x]=d.useState(!1),[N,R]=d.useState(""),[T,_]=d.useState(!1),[$,H]=d.useState(e.content),[ue,Z]=d.useState(!1),[V,de]=d.useState(null),[I,Y]=d.useState(""),[te,ne]=d.useState(null),P=async b=>{b?.preventDefault(),N.trim()&&await p(N)&&(R(""),x(!1))},ge=async b=>{b?.preventDefault(),$.trim()&&await w($)&&_(!1)},we=async b=>{b?.preventDefault(),!(!V||!I.trim())&&await C(V,I)&&de(null)},Ce=e.authorUsername,ee=b=>new Date(b).toLocaleString(ys.resolvedLanguage),se=async(b,U)=>{U.stopPropagation(),await u(b)};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()||f()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:e.authorDisplayName??Ce??k("editor.deletedUser")}),Ce&&o.jsxs("small",{children:["@",Ce]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toISOString(),children:ee(e.createdAt)}),e.editedAt&&o.jsx("small",{children:k("editor.editedAt",{time:ee(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}),T?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:b=>{ge(b)},onClick:b=>b.stopPropagation(),children:[o.jsx(ar,{projectId:t,autoFocus:!0,rows:4,value:$,onChange:H,onKeyDown:b=>$i(b,ge)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>_(!1),children:k("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!$.trim(),children:[o.jsx(Hl,{size:13}),k("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:Ua(e.content)}),s&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(ur,{"aria-hidden":!0,size:12}),k("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:b=>{se(s,b)},children:k("editor.markMentionRead")})]}),e.replies.length>0&&o.jsx("div",{className:"comment-replies",children:e.replies.map(b=>{const U=r?.get(b.id);return o.jsxs("div",{"data-comment-reply-id":b.id,className:`comment-reply${l===b.id?" mention-target":""}`,children:[o.jsxs("header",{children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:b.authorDisplayName??b.authorUsername??k("editor.deletedUser")}),b.authorUsername&&o.jsxs("small",{children:["@",b.authorUsername]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:b.createdAt,title:new Date(b.createdAt).toISOString(),children:ee(b.createdAt)}),b.editedAt&&o.jsx("small",{children:k("editor.editedAt",{time:ee(b.editedAt)})})]})]}),V===b.id?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:Q=>{we(Q)},onClick:Q=>Q.stopPropagation(),children:[o.jsx(ar,{projectId:t,autoFocus:!0,rows:3,value:I,onChange:Y,onKeyDown:Q=>$i(Q,we)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>de(null),children:k("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!I.trim(),children:[o.jsx(Hl,{size:13}),k("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:Ua(b.content)}),U&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(ur,{"aria-hidden":!0,size:12}),k("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:Q=>{se(U,Q)},children:k("editor.markMentionRead")})]}),b.authorId===n&&V!==b.id&&o.jsxs("div",{className:"comment-owner-actions",children:[o.jsx("button",{title:k("editor.editReply"),"aria-label":k("editor.editReply"),onClick:Q=>{Q.stopPropagation(),de(b.id),Y(b.content)},children:o.jsx(zl,{size:12})}),o.jsx("button",{className:"danger-text",title:k("editor.deleteReply"),"aria-label":k("editor.deleteReply"),onClick:Q=>{Q.stopPropagation(),ne(b.id)},children:o.jsx(tn,{size:12})})]})]},b.id)})}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",onClick:b=>{b.stopPropagation(),h()},children:[e.resolved?o.jsx(kf,{size:13}):o.jsx(of,{size:13}),e.resolved?k("editor.reopen"):k("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:b=>{b.stopPropagation(),x(U=>!U)},children:[o.jsx(xf,{size:13}),k("editor.reply")]}),e.authorId===n&&!T&&o.jsxs("span",{className:"comment-owner-actions",children:[o.jsx("button",{title:k("editor.editComment"),"aria-label":k("editor.editComment"),onClick:b=>{b.stopPropagation(),H(e.content),_(!0)},children:o.jsx(zl,{size:13})}),o.jsx("button",{className:"danger-text",title:k("editor.deleteComment"),"aria-label":k("editor.deleteComment"),onClick:b=>{b.stopPropagation(),Z(!0)},children:o.jsx(tn,{size:13})})]})]}),B&&o.jsxs("form",{className:"comment-reply-form",onSubmit:b=>{P(b)},onClick:b=>b.stopPropagation(),children:[o.jsx(ar,{projectId:t,autoFocus:!0,rows:3,value:N,placeholder:k("editor.replyPlaceholder"),onChange:R,onKeyDown:b=>$i(b,P)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>{x(!1),R("")},children:k("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!N.trim(),children:[o.jsx(Sf,{size:13}),k("editor.sendReply")]})]})]})]}),o.jsx(ks,{open:ue,title:k("editor.deleteCommentTitle"),description:k("editor.deleteCommentDescription",{count:e.replies.length}),confirmLabel:k("common.delete"),danger:!0,onCancel:()=>Z(!1),onConfirm:()=>{g().then(b=>{b&&Z(!1)})}}),o.jsx(ks,{open:!!te,title:k("editor.deleteReplyTitle"),description:k("editor.deleteReplyDescription"),confirmLabel:k("common.delete"),danger:!0,onCancel:()=>ne(null),onConfirm:()=>{te&&v(te).then(b=>{b&&ne(null)})}})]})}function $b({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=Xe(),[i,l]=d.useState([]),[a,c]=d.useState([]),[u,f]=d.useState(""),[h,p]=d.useState("read"),[w,g]=d.useState(null),[C,v]=d.useState(""),k=n.permission==="owner",B=async()=>{try{const[_,$]=await Promise.all([ce(`/api/projects/${s}/members`),ce("/api/users")]);l(_.members),c($.users.filter(H=>H.id!==n.ownerId))}catch(_){v(fe(_))}};d.useEffect(()=>{t&&B()},[t,s]);const x=async()=>{if(u)try{await ce(`/api/projects/${s}/members/${u}`,{method:"PUT",body:JSON.stringify({permission:h})}),f(""),p("read"),await B()}catch(_){v(fe(_))}},N=async(_,$)=>{try{await ce(`/api/projects/${s}/members/${_.id}`,{method:"PUT",body:JSON.stringify({permission:$})}),await B()}catch(H){v(fe(H))}},R=async()=>{if(w)try{await ce(`/api/projects/${s}/members/${w.id}`,{method:"DELETE"}),g(null),await B()}catch(_){v(fe(_))}},T=a.filter(_=>!i.some($=>$.id===_.id));return o.jsxs(o.Fragment,{children:[o.jsx(Xt,{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:[C&&o.jsx("p",{className:"error",children:C}),o.jsxs("div",{className:"share-owner",children:[o.jsx(Pi,{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:u,onChange:_=>f(_.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),T.map(_=>o.jsx("option",{value:_.id,children:_.displayName??_.username},_.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:h,onChange:_=>p(_.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:!u,onClick:()=>{x()},children:[o.jsx(nf,{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(_=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(_.displayName??_.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:_.displayName??_.username}),o.jsxs("small",{children:["@",_.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!k,value:_.permission,onChange:$=>{N(_,$.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:()=>g(_),children:o.jsx(tn,{size:15})})]})]},_.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(Pi,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(ks,{open:!!w,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:w?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{R()}})]})}const Ib=d.lazy(()=>Dt(()=>import("./CitationLibraryDialog-CU2b0xtm.js"),__vite__mapDeps([11,2,1,3,12,5,13,4,6,14]),import.meta.url).then(t=>({default:t.CitationLibraryDialog}))),Pb=d.lazy(()=>Dt(()=>import("./GitDialog-C2Np1i8v.js"),__vite__mapDeps([15,2,1,3,5,16,17,13,18,4,6,7,8]),import.meta.url).then(t=>({default:t.GitDialog}))),Ub=d.lazy(()=>Dt(()=>import("./HistoryDialog-CdoYeLyX.js"),__vite__mapDeps([19,2,1,3,20,21,5,17,13,18,4,6,7,8]),import.meta.url).then(t=>({default:t.HistoryDialog}))),zb=d.lazy(()=>Dt(()=>import("./SelectionHistoryDialog-D8CeqjLD.js"),__vite__mapDeps([22,2,1,3,20,4,5,6,7,8]),import.meta.url).then(t=>({default:t.SelectionHistoryDialog}))),Bb=d.lazy(()=>Dt(()=>import("./ProjectNavigationDialogs-_JY0yVob.js"),__vite__mapDeps([23,2,1,3,6,5,4]),import.meta.url).then(t=>({default:t.ProjectSearchDialog}))),qb=d.lazy(()=>Dt(()=>import("./ProjectNavigationDialogs-_JY0yVob.js"),__vite__mapDeps([23,2,1,3,6,5,4]),import.meta.url).then(t=>({default:t.QuickOpenDialog})));function Wb({user:t,project:e,projectId:n,activeFile:s,content:r,maxCitationBibtexBytes:i,files:l,directoryEntries:a,readOnly:c,workspaceLayout:u,changeWorkspaceLayout:f,resourcePreview:h,resourcePreviewLoading:p,setResourcePreview:w,setResourcePreviewLoading:g,uploadConflict:C,setUploadConflict:v,uploadFiles:k,cleanMode:B,setCleanMode:x,cleanCompile:N,newFileOpen:R,setNewFileOpen:T,newFilePath:_,setNewFilePath:$,newFolderOpen:H,setNewFolderOpen:ue,newFolderName:Z,setNewFolderName:V,selectedFolder:de,fileDialogError:I,setFileDialogError:Y,createFile:te,createFolder:ne,moveEntry:P,setMoveEntry:ge,moveName:we,setMoveName:Ce,moveDestination:ee,setMoveDestination:se,movePath:b,deleteEntry:U,setDeleteEntry:Q,deleteActiveSessions:xe,removePath:ae,commentOpen:ke,closeComment:Ne,commentSelection:pe,selection:q,commentText:K,setCommentText:De,commentSubmitting:$e,commentError:Se,addComment:je,shareOpen:F,setShareOpen:re,citationLibraryOpen:Ee,setCitationLibraryOpen:A,insertCitationAtCursor:O,quickOpen:S,setQuickOpen:_e,projectSearchOpen:M,setProjectSearchOpen:he,openFile:Fe,jumpToSource:Be,selectionHistoryOpen:ye,setSelectionHistoryOpen:L,historyOpen:J,setHistoryOpen:j,gitOpen:Pe,setGitOpen:bt,save:mt,permissionDowngrade:be,permissionDowngradeBusy:dt,dismissPermissionDowngrade:xt,discardPermissionDraft:ve}){const{t:z}=Xe();return o.jsxs(o.Fragment,{children:[be&&o.jsx(Xt,{open:!0,title:z("editor.collaboration.permissionDowngradeTitle"),description:be.localDraftReady&&be.otherTabDraft?z("editor.collaboration.permissionDowngradeMultipleDrafts"):be.otherTabDraft?z("editor.collaboration.permissionDowngradeOtherTab"):be.localDraftReady?z("editor.collaboration.permissionDowngradeDescription",{previous:z("common.readWrite")}):z("editor.collaboration.permissionDowngradeNoDraft"),onOpenChange:W=>{!W&&!dt&&xt()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:dt,onClick:xt,children:be.localDraftReady?z("editor.collaboration.permissionDowngradeKeep"):z("common.close")}),!be.otherTabDraft&&o.jsxs("button",{type:"button",className:"danger",disabled:dt,onClick:()=>{ve()},children:[dt?o.jsx(rt,{className:"spin",size:14}):be.localDraftReady?o.jsx(tn,{size:14}):o.jsx(sf,{size:14}),be.localDraftReady?z("editor.collaboration.permissionDowngradeDiscard"):z("editor.collaboration.permissionDowngradeReload")]})]}),children:o.jsx("div",{})}),o.jsxs(Xt,{open:!!h,extraWide:h?.kind==="image"||h?.kind==="pdf"||h?.kind==="text",title:h?.path??"",description:h?.kind==="large"?z("editor.resourceTooLarge",{size:Hb(h.size),limit:`${io/1024/1024} MB`}):z(`editor.resourcePreview.${h?.kind??"text"}`),onOpenChange:W=>{W||(w(null),g(!1))},footer:h&&o.jsxs("a",{className:"primary resource-download",href:`${h.url}&download=1`,download:!0,children:[o.jsx(cr,{size:14}),z("editor.downloadResource")]}),children:[h?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Ui,{size:34}),o.jsx("strong",{children:z("editor.resourceTooLargeTitle")}),o.jsx("span",{children:z("editor.resourceTooLargeDescription")})]}),h?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Ui,{size:34}),o.jsx("strong",{children:z("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:z("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"&&(p?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(rt,{className:"spin",size:24}),o.jsx("span",{children:z("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:h.content}))]}),o.jsx(ks,{open:!!C,title:z("editor.uploadOverwriteTitle"),description:z("editor.uploadOverwriteDescription",{files:C?.collisions.join(", ")??""}),confirmLabel:z("editor.uploadOverwrite"),danger:!0,onCancel:()=>v(null),onConfirm:()=>{const W=C;v(null),W&&k(W.files,new Set(W.collisions),W.directory)}}),o.jsx(ks,{open:!!B,title:z(B==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:z(B==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:z("editor.cleanConfirm"),danger:B==="artifacts",onCancel:()=>x(null),onConfirm:()=>{const W=B;x(null),W&&N(W)}}),o.jsx(Xt,{open:R,title:z("editor.newFile"),description:z("editor.newFileDescription"),onOpenChange:W=>{T(W),W||Y("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>T(!1),children:z("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{te()},children:z("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:[z("editor.filePath"),o.jsx("input",{autoFocus:!0,value:_,onChange:W=>$(W.target.value),onKeyDown:W=>{W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),te())}})]})]})}),o.jsx(Xt,{open:H,title:z("editor.newFolder"),description:z("editor.folderDestination",{folder:de||z("editor.projectRoot")}),onOpenChange:W=>{ue(W),W||Y("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>ue(!1),children:z("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ne()},children:z("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:[z("editor.folderName"),o.jsx("input",{autoFocus:!0,value:Z,onChange:W=>V(W.target.value),onKeyDown:W=>{W.key==="Enter"&&ne()}})]})]})}),o.jsx(Xt,{open:!!P,title:z("editor.moveTitle",{name:P?.path.split("/").at(-1)??""}),description:z("editor.moveDescription"),onOpenChange:W=>{W||(ge(null),Ce(""),Y(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>ge(null),children:z("common.cancel")}),o.jsx("button",{className:"primary",disabled:!we.trim(),onClick:()=>{b()},children:z("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:[z("editor.pathName"),o.jsx("input",{autoFocus:!0,value:we,onChange:W=>Ce(W.target.value),onKeyDown:W=>{W.key==="Enter"&&b()}})]}),o.jsxs("label",{className:"form-field",children:[z("editor.destinationFolder"),o.jsxs("select",{value:ee,onChange:W=>se(W.target.value),children:[o.jsx("option",{value:"",children:z("editor.projectRoot")}),a.filter(W=>P?.type!=="directory"||W.path!==P.path&&!W.path.startsWith(`${P.path}/`)).map(W=>o.jsx("option",{value:W.path,children:W.path},W.path))]})]})]})}),o.jsx(Xt,{open:!!U,title:z("editor.deletePathTitle",{name:U?.path.split("/").at(-1)??""}),description:xe.length?z("editor.deletePathActiveDescription",{path:U?.path??"",users:[...new Set(xe.map(W=>W.name))].join(", ")}):z("editor.deletePathDescription",{path:U?.path??""}),onOpenChange:W=>{W||(Q(null),Y(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Q(null),children:z("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{ae()},children:z("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[I&&o.jsx("p",{className:"error dialog-error",children:I}),xe.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(zt,{size:15}),z("editor.deletePathWillClose")]})]})}),o.jsxs(Xt,{open:ke,draggable:!0,title:z("editor.addComment"),description:pe.selectedText?z("editor.commentDescription",{count:pe.endOffset-pe.startOffset}):z("editor.pointComment"),onOpenChange:W=>{W||Ne()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:$e,onClick:Ne,children:z("common.cancel")}),o.jsxs("button",{type:"button",className:"primary",disabled:$e||!K.trim(),onClick:()=>{je()},children:[$e&&o.jsx(rt,{className:"spin",size:14}),z("editor.addComment")]})]}),children:[Se&&o.jsx("p",{className:"error dialog-error",children:Se}),o.jsxs("label",{className:"form-field",children:[z("editor.commentContent"),o.jsx(ar,{projectId:n,autoFocus:!0,rows:5,disabled:$e,value:K,onChange:De,onKeyDown:W=>{(W.ctrlKey||W.metaKey)&&W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),W.stopPropagation(),je())}})]}),pe.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:pe.selectedText})]}),o.jsx($b,{open:F,onOpenChange:re,project:e,projectId:n}),Ee&&o.jsx(Wa,{title:z("citationLibrary.title"),onClose:()=>A(!1),children:o.jsx(Ib,{open:!0,onOpenChange:A,currentFile:s,currentSource:r,readOnly:c,currentUserId:t.id,maxBibtexBytes:i,onInsert:O})}),S&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(qb,{open:!0,files:l,onOpenChange:_e,onOpenFile:W=>{const kt=l.find(lt=>lt.path===W);kt&&Fe(kt)}})}),M&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(Bb,{open:!0,project:e,onOpenChange:he,onJump:(W,kt,lt)=>{u==="pdf-only"&&f("editor-pdf"),Be(W,kt,lt)}})}),ye&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(zb,{open:!0,onOpenChange:L,project:e,filePath:s,selection:q,currentSource:r})}),J&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(Ub,{open:!0,onOpenChange:j,project:e,onBeforeMutation:e.permission==="read"?async()=>!0:mt})}),e.ownerId===t.id&&Pe&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(Pb,{open:!0,onOpenChange:bt,project:e,onBeforeMutation:mt})})]})}function Hb(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const Vb=d.lazy(()=>Dt(()=>import("./ProjectSettings-DXGA-lmB.js"),__vite__mapDeps([24,2,1,3,5,25,26,8,4,6,7]),import.meta.url).then(t=>({default:t.ProjectSettings})));function Kb({sidePanel:t,onClose:e,project:n,projectId:s,site:r,files:i,currentUserId:l,comments:a,commentsLoading:c,commentsError:u,onRetryComments:f,unreadMentions:h,activeFile:p,hasProjectCommentsScope:w,commentScope:g,onCommentScopeChange:C,focusedCommentId:v,onMarkMentionRead:k,onMarkAllMentionsRead:B,onClearFocusComment:x,targetCommentId:N,targetReplyId:R,onFocusComment:T,onToggleComment:_,onReplyComment:$,onEditComment:H,onDeleteComment:ue,onEditCommentReply:Z,onDeleteCommentReply:V,dictionaryWords:de,onDictionaryChange:I,editorPreferences:Y,onEditorPreferences:te,spellCheckCount:ne,spellCheckUniqueCount:P,spellCheckIndex:ge,onSpellCheckNavigate:we,onProject:Ce}){const{t:ee}=Xe(),[se,b]=d.useState("unresolved"),[U,Q]=d.useState(null),xe=d.useMemo(()=>({unresolved:xi(a,{activeFile:p,scope:g,filter:"unresolved",unreadMentions:h}).length,mentions:xi(a,{activeFile:p,scope:g,filter:"mentions",unreadMentions:h}).length,resolved:xi(a,{activeFile:p,scope:g,filter:"resolved",unreadMentions:h}).length}),[p,g,a,h]),ae=d.useMemo(()=>Xf(a,{activeFile:p,scope:g,filter:se,unreadMentions:h},[U,N,v]),[p,se,g,a,v,U,N,h]),ke=v&&ae.some(F=>F.id===v)?v:U&&ae.some(F=>F.id===U)?U:N&&ae.some(F=>F.id===N)?N:null,Ne=np(ae,ke);d.useEffect(()=>{U&&!a.some(F=>F.id===U)&&Q(null)},[a,U]),d.useEffect(()=>{!w&&g!=="file"&&(Q(null),x(),C("file"))},[g,w,x,C]),d.useEffect(()=>{const F=N&&R?`[data-comment-reply-id="${R}"]`:N?`[data-comment-id="${N}"]`:ke?`[data-comment-id="${ke}"]`:"";if(!F)return;const re=document.querySelector(F);if(!re)return;const Ee=window.requestAnimationFrame(()=>re.scrollIntoView({block:N?"center":"nearest",behavior:"smooth"}));return()=>window.cancelAnimationFrame(Ee)},[ke,N,R,ae]);const pe=F=>{U!==F.id&&Q(null),T(F)},q=async F=>{T(F),Q(tp(F,se,h)?F.id:null),await _(F)},K=F=>{const re=sp(ae,ke,F);Q(null),re?pe(re):x()},De=async F=>{const re=await k(F);if(!re||se!=="mentions")return re;const Ee=h.find(O=>O.id===F)?.commentId;return Ee&&(h.some(O=>O.id!==F&&O.commentId===Ee)||(U===Ee&&Q(null),v===Ee&&x())),re},$e=async()=>{await B()&&se==="mentions"&&(Q(null),x())},Se=F=>{F!==g&&(Q(null),x(),C(F))},je=F=>{F!==se&&(Q(null),x(),b(F))};return t?o.jsxs(o.Fragment,{children:[o.jsx(ao,{className:"resize-handle"}),o.jsx(_r,{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:ee("editor.sourceComments")}),o.jsxs("span",{className:"drawer-title-actions",children:[h.length>0&&o.jsxs("button",{className:"drawer-mention-read-all",type:"button",onClick:()=>{$e()},title:ee("editor.markAllMentionsRead"),children:[o.jsx(ur,{"aria-hidden":!0,size:13}),o.jsx("span",{children:ee("editor.markAllMentionsRead")})]}),o.jsx("button",{"aria-label":ee("common.close"),onClick:e,children:o.jsx(Ss,{size:17})})]})]}),o.jsxs("div",{className:"comment-review-controls",children:[w&&o.jsxs("div",{className:"comment-review-group",role:"group","aria-label":ee("editor.commentScope"),children:[o.jsx("button",{type:"button",className:g==="file"?"active":"","aria-pressed":g==="file",onClick:()=>Se("file"),children:ee("editor.commentScopeFile")}),o.jsx("button",{type:"button",className:g==="project"?"active":"","aria-pressed":g==="project",onClick:()=>Se("project"),children:ee("editor.commentScopeProject")})]}),o.jsxs("div",{className:"comment-review-group",role:"group","aria-label":ee("editor.commentFilter"),children:[o.jsx("button",{type:"button",className:se==="unresolved"?"active":"","aria-pressed":se==="unresolved",onClick:()=>je("unresolved"),children:ee("editor.commentFilterUnresolved",{count:xe.unresolved})}),o.jsx("button",{type:"button",className:se==="mentions"?"active":"","aria-pressed":se==="mentions",onClick:()=>je("mentions"),children:ee("editor.commentFilterMentions",{count:xe.mentions})}),o.jsx("button",{type:"button",className:se==="resolved"?"active":"","aria-pressed":se==="resolved",onClick:()=>je("resolved"),children:ee("editor.commentFilterResolved",{count:xe.resolved})})]}),o.jsxs("div",{className:"comment-review-navigation",children:[o.jsx("button",{type:"button",disabled:Ne<=1,"aria-label":ee("editor.commentPrevious"),title:ee("editor.commentPrevious"),onClick:()=>K(-1),children:o.jsx(ef,{size:14})}),o.jsx("output",{"aria-live":"polite",children:ee("editor.commentPosition",{current:Ne,total:ae.length})}),o.jsx("button",{type:"button",disabled:ae.length===0||Ne>0&&Ne>=ae.length,"aria-label":ee("editor.commentNext"),title:ee("editor.commentNext"),onClick:()=>K(1),children:o.jsx(co,{size:14})})]})]}),u&&o.jsxs("div",{className:"comment-review-error",role:"alert",children:[o.jsx("span",{children:u}),o.jsx("button",{type:"button",onClick:()=>{f()},children:ee("common.retry")})]}),c&&o.jsx("div",{className:"comment-review-loading",role:"status",children:ee("common.loading")}),o.jsxs("div",{className:"comments",children:[ae.map(F=>{const re=h.find(A=>A.commentId===F.id&&!A.replyId)?.id,Ee=new Map(h.filter(A=>A.commentId===F.id&&A.replyId).map(A=>[A.replyId,A.id]));return o.jsx(Mb,{projectId:s,comment:F,currentUserId:l,unreadCommentMentionId:re,unreadReplyMentionIds:Ee,highlightedComment:N===F.id&&!R,highlightedReplyId:N===F.id?R:null,currentComment:ke===F.id,showFilePath:g==="project",onMarkMentionRead:De,onFocus:()=>pe(F),onToggle:()=>{q(F)},onReply:A=>$(F,A),onEdit:A=>H(F,A),onDelete:()=>ue(F),onEditReply:(A,O)=>Z(F,A,O),onDeleteReply:A=>V(F,A)},F.id)}),ae.length===0&&!c&&!u&&o.jsx("p",{className:"muted padded",children:a.length?ee("editor.commentNoMatches"):ee("editor.noComments")})]})]}),t==="settings"&&o.jsx(zh,{onClose:e,children:o.jsx(Vb,{onClose:e,project:n,projectId:s,site:r,files:i,dictionaryWords:de,onDictionaryChange:I,editorPreferences:Y,onEditorPreferences:te,spellCheckCount:ne,spellCheckUniqueCount:P,spellCheckIndex:ge,onSpellCheckNavigate:we,onProject:Ce})})]})})]}):null}function Gb(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 Jb(){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=Gb(l))};return{getCursor:()=>t,getOutlineLine:()=>e,subscribe:c=>(r.add(c),()=>r.delete(c)),update:(c,u,f)=>{t.line===c&&t.column===u&&t.offset===f||(t={line:c,column:u,offset:f},(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 Yb(t,e,n){return t.mainFile===e?t.items:!e||n.filePath!==e?[]:Xb(n.content).map(s=>({...s,path:e}))}function Xb(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 Zb=d.lazy(()=>Dt(()=>import("./WordCountDialog-C-MCscAu.js"),__vite__mapDeps([27,2,1,3,25,5,4,6,7,8]),import.meta.url).then(t=>({default:t.WordCountDialog})));let sr=null;function za(){return sr||(sr=Dt(()=>import("./citationLibrary-ZeQPCv5O.js"),[],import.meta.url).catch(t=>{throw sr=null,t})),sr}function Yt(t){return t instanceof Error&&t.name==="AbortError"}const Ba=300;function Qb({site:t,user:e,projectId:n,preload:s,mentionId:r=null,onMentionTargeted:i,onMentionsRead:l,onBack:a}){const{t:c}=Xe(),[u,f]=d.useState(null);d.useEffect(()=>(document.title=u?.name?`${t.siteName} | ${u.name}`:t.siteName,()=>{document.title=t.siteName}),[u?.name,t.siteName]);const[h,p]=d.useState(!1),[w,g]=d.useState([]),[C,v]=d.useState(null),[k,B]=d.useState({mainFile:"",items:[]}),[x,N]=d.useState(""),[R,T]=d.useState(""),[_,$]=d.useState(""),[H,ue]=d.useState({filePath:"",content:""}),[Z,V]=d.useState({path:"",hasIncludes:!1}),[de,I]=d.useState(""),[Y,te]=d.useState(!1),[ne,P]=d.useState("editor.saved"),[ge,we]=d.useState(null),Ce=d.useRef(ge);Ce.current=ge;const ee=d.useRef(null);ee.current||(ee.current=Jb());const se=ee.current,[b,U]=d.useState("pdf"),[Q,xe]=d.useState("log"),ae=m=>{if(m==="pdf"){U("pdf");return}if(m==="diagnostics"){U("diagnostics");return}xe(m),U("diagnostics")},{workspaceLayout:ke,setWorkspaceLayout:Ne}=By(e.id,n),[pe,q]=d.useState(""),[K,De]=d.useState(""),[$e,Se]=d.useState({selectedText:"",startOffset:0,endOffset:0}),je=d.useRef({selectedText:"",startOffset:0,endOffset:0}),F=m=>{const y=je.current;y.selectedText===m.selectedText&&y.startOffset===m.startOffset&&y.endOffset===m.endOffset||(je.current=m,Se(m))},[re,Ee]=d.useState(null),[A,O]=d.useState(null),[S,_e]=d.useState(null),[M,he]=d.useState(!1),[Fe,Be]=d.useState(!1),[ye,L]=d.useState(!1),[J,j]=d.useState(!1),[Pe,bt]=d.useState(!1),[mt,be]=d.useState(!1),[dt,xt]=d.useState(null),[ve,z]=d.useState(!1),[W,kt]=d.useState(!1),[lt,Bs]=d.useState(!1),[Uu,zu]=d.useState("full"),[Bu,qu]=d.useState(""),[qr,Wr]=d.useState(!1),[Wu,Hr]=d.useState(""),[Hu,Vr]=d.useState(null),[cs,_n]=d.useState(!1),[ln,Mt]=d.useState(null),[Vu,Kr]=d.useState(!1),[et,Jo]=d.useState(()=>Vl(e.id,n));d.useEffect(()=>{const m=document.documentElement,y=et.showTooltips?"on":"off";return m.setAttribute("data-texlite-tooltips",y),()=>{m.getAttribute("data-texlite-tooltips")===y&&m.removeAttribute("data-texlite-tooltips")}},[et.showTooltips]);const[Tn,qs]=d.useState([]),Ht=d.useRef([]);Ht.current=Tn;const Ku=d.useRef(null),Ws=d.useRef(null),Hs=d.useRef(0),Gr=d.useRef(0),Re=d.useRef(""),st=d.useRef(""),Yo=d.useRef(ke),Xo=d.useRef(0),an=d.useRef(null),Zo=d.useRef(null),cn=d.useRef(null),un=d.useRef(null),Ln=d.useRef(null),Rn=d.useRef(null),An=d.useRef(null),Vt=d.useRef(null),Jr=d.useRef(null),$t=d.useRef(!1),Kt=d.useRef(null),Qo=d.useRef(a),Yr=d.useRef(i),Xr=d.useRef(l);Qo.current=a,Yr.current=i,Xr.current=l,Re.current=x,st.current=R,Yo.current=ke,d.useEffect(()=>{if(!K)return;const m=window.setTimeout(()=>De(""),3e3);return()=>window.clearTimeout(m)},[K]);const Gu=d.useCallback((m,y,D=0)=>{se.update(m,y,D)},[se]);d.useEffect(()=>()=>se.dispose(),[se]),d.useEffect(()=>()=>{Vt.current?.abort(),Vt.current=null},[]);const Vs=m=>{const y=Ht.current,D=m(y);D!==y&&(Ht.current=D,qs(D))};d.useEffect(()=>{Ht.current=[],qs([]),Mt(null),bt(!1),Rn.current?.abort(),Rn.current=null,An.current?.abort(),An.current=null,Vt.current?.abort(),Vt.current=null,Jr.current=null,O(null),_e(null),Bs(!1),Wr(!1),Hr(""),Vr(null)},[n]);const el=m=>{const y=Ht.current,D=y.indexOf(m);if(D<0)return;const E=y.filter(X=>X!==m);if(Ht.current=E,qs(E),Re.current!==m)return;const oe=E.length>0?E[Math.min(D,E.length-1)]:u?.mainFile??"";N(oe)},{collaboration:Me,status:Ks,synced:Ke,activeSessions:tl,formatLeaseStates:Ju,compileState:dn,setCompileState:nl,filesEvent:We,commentsRevision:sl,historyWarning:Yu,dictionaryRevision:rl,localDraftReady:il,permission:Zr,reconnect:Xu,protocolUpgradeRequired:ol,permissionDowngrade:Zu,dismissPermissionDowngrade:Qu,discardLocalDraft:ed}=Ay(n,e,R,u?.permission??"read",h,()=>P("editor.offlineDraft")),{unreadMentions:ll,refresh:td,markMentionRead:nd,markAllMentionsRead:sd}=ip(n,sl,q),{pdfTarget:rd,pdfViewport:id,sourceJump:od,setPdfViewport:ld,clearPdfViewport:al,jumpToSource:Nn,syncSourceToPdf:Qr,syncPdfToSource:ad,syncVisiblePdfToSource:cd}=zy({projectId:n,mainFile:R,activeFile:x,onActiveFile:N,onError:q,onShowPdf:()=>ae("pdf")}),ht=Uy({active:!!(u&&x&&Ke&&et.spellCheck&&qy(x)),projectId:n,activeFile:x,content:_,dictionaryWords:w});d.useEffect(()=>{Jo(Vl(e.id,n))},[e.id,n]);const ei=m=>{$(m)};d.useEffect(()=>{if(!x||de!==x){ue(E=>E.filePath||E.content?{filePath:"",content:""}:E);return}const m=x,y=_,D=window.setTimeout(()=>{ue(E=>E.filePath===m&&E.content===y?E:{filePath:m,content:y})},Ba);return()=>window.clearTimeout(D)},[x,de,_]),d.useEffect(()=>{if(Re.current=x,se.reset(),F({selectedText:"",startOffset:0,endOffset:0}),!et.openFilesInTabs){Ht.current.length>0&&(Ht.current=[],qs([]));return}x&&Vs(m=>m.includes(x)?m:[...m,x])},[x,et.openFilesInTabs,n,se]),d.useEffect(()=>{if(!Y)return;const m=y=>{y.preventDefault(),y.returnValue=""};return window.addEventListener("beforeunload",m),()=>window.removeEventListener("beforeunload",m)},[Y]),d.useEffect(()=>{if(Ks!=="disconnected")return;const m=new AbortController;return ce(`/api/projects/${n}`,{signal:m.signal}).then(({project:y})=>{m.signal.aborted||(f(y),q(""))}).catch(y=>{if(!Yt(y)){if(y instanceof Ii&&[401,403,404].includes(y.status)){q(fe(y)),Qo.current();return}q(c("errors.collaborationUnavailable"))}}),()=>m.abort()},[Ks,n,c]);const Gs=async(m={},y=st.current)=>{an.current?.abort(),an.current=null;const D=m.signal?null:new AbortController;D&&(an.current=D);try{const E=y?`?mainFile=${encodeURIComponent(y)}`:"",oe=await ce(`/api/projects/${n}/completions${E}`,{signal:m.signal??D?.signal});(!m.isCurrent||m.isCurrent())&&v(oe.index)}catch(E){if(Yt(E))return;(!m.isCurrent||m.isCurrent())&&v(null)}finally{D&&an.current===D&&(an.current=null)}},ti=async(m={},y=st.current)=>{cn.current?.abort(),cn.current=null;const D=m.signal?null:new AbortController;D&&(cn.current=D);try{const E=y?`?mainFile=${encodeURIComponent(y)}`:"",oe=await ce(`/api/projects/${n}/outline${E}`,{signal:m.signal??D?.signal});(!m.isCurrent||m.isCurrent())&&st.current===y&&B({mainFile:y,items:oe.outline})}catch(E){if(Yt(E))return}finally{D&&cn.current===D&&(cn.current=null)}},cl=async(m={})=>{un.current?.abort(),un.current=null;const y=m.signal?null:new AbortController;y&&(un.current=y);try{const D=await ce(`/api/projects/${n}/dictionary`,{signal:m.signal??y?.signal});(!m.isCurrent||m.isCurrent())&&g(D.words)}catch(D){if(Yt(D))return;(!m.isCurrent||m.isCurrent())&&g([])}finally{y&&un.current===y&&(un.current=null)}};d.useEffect(()=>{let m=!1;const y=++Xo.current,D=new AbortController,E=()=>!m&&Xo.current===y;let oe=!1,X="";f(null),hl([]),B({mainFile:"",items:[]}),N(""),T(""),V({path:"",hasIncludes:!1}),$(""),I(""),nl(null),al(),v(null),g([]),qa();const ie=(s?.projectId===n?s.project:ce(`/api/projects/${n}`,{signal:D.signal})).then(He=>{E()&&(oe=!0,X=He.project.mainFile,f(He.project),N(He.project.mainFile),st.current=He.project.mainFile,T(He.project.mainFile),kl(new Set(ws(He.project.mainFile))))}).catch(He=>{E()&&q(fe(He))}),_t=ce(`/api/projects/${n}/files`,{signal:D.signal}).then(He=>{E()&&hl(He.files)}).catch(He=>{E()&&q(fe(He))});let at=null;return Promise.allSettled([ie,_t]).then(()=>{!E()||!oe||(at=window.setTimeout(()=>{E()&&Promise.all([Gs({signal:D.signal,isCurrent:E},st.current||X),cl({signal:D.signal,isCurrent:E})])},0))}),()=>{m=!0,at!==null&&window.clearTimeout(at),D.abort(),an.current?.abort(),an.current=null,cn.current?.abort(),cn.current=null,un.current?.abort(),un.current=null,Ln.current?.abort(),Ln.current=null}},[n,s]),d.useEffect(()=>{if(!(!u||!R)){if(Zo.current!==n){Zo.current=n;return}Gs({},R)}},[R,u?.id,n]),d.useEffect(()=>{if(!r||!u)return;An.current?.abort();const m=new AbortController;return An.current=m,ce(`/api/projects/${n}/mentions/${encodeURIComponent(r)}`,{signal:m.signal}).then(({mention:y})=>{m.signal.aborted||(O(y),Ee("comments"),N(y.filePath),Yr.current?.(y.id))}).catch(y=>{Yt(y)||m.signal.aborted||(q(fe(y)),Yr.current?.(r))}).finally(()=>{An.current===m&&(An.current=null)}),()=>m.abort()},[r,u?.id,n]),d.useEffect(()=>{rl&&cl()},[rl,n]),d.useEffect(()=>{!u||Ks!=="connected"||Zr===u.permission||f(m=>m&&{...m,permission:Zr})},[Zr,u?.permission]),d.useEffect(()=>{if(!We)return;const m=We.kind==="delete"&&!!We.path&&pn(We.path,Re.current),y=We.kind==="delete"&&!!We.path&&pn(We.path,st.current);if(We.kind==="move"&&We.source&&We.destination){const E=We.source,oe=We.destination,X=ie=>ie===E?oe:ie.startsWith(`${E}/`)?`${oe}${ie.slice(E.length)}`:ie;N(ie=>X(ie)),T(ie=>X(ie)),si(ie=>ie&&X(ie)),xl(ie=>ie&&X(ie)),Vs(ie=>ie.map(X))}m&&(N(""),I(""),ei(""),De(c("editor.fileDeletedByCollaborator",{path:We.path}))),We.kind==="delete"&&We.path&&(si(E=>E&&pn(We.path,E)?null:E),xl(E=>pn(We.path,E)?"":E),ml(E=>E&&pn(We.path,E.path)?null:E),Vs(E=>E.filter(oe=>!pn(We.path,oe)))),Ln.current?.abort();const D=new AbortController;Ln.current=D,Promise.all([pd({signal:D.signal}),ce(`/api/projects/${n}`,{signal:D.signal})]).then(([E,oe])=>{if(f(oe.project),y&&T(oe.project.mainFile),m&&E){const X=E.find(ie=>ie.type==="file"&&ie.path===oe.project.mainFile)??E.find(ie=>ie.type==="file"&&Kn(ie.path));N(X?.path??"")}Gs({signal:D.signal}),ti({signal:D.signal},y?oe.project.mainFile:st.current)}).catch(E=>{Yt(E)}).finally(()=>{Ln.current===D&&(Ln.current=null)})},[We?.revision]),d.useEffect(()=>{if(Me.setActiveFile(x),!x)return;I(""),P("editor.loading");const m=Me.getText(x),y=(D,E)=>{ei(m.toString()),I(x),E?.local&&u?.permission!=="read"?(Hs.current+=1,te(!0),P("editor.pending")):Hs.current<=Gr.current&&P(Ce.current?"editor.savedAt":"editor.saved")};return m.observe(y),(Ke||il)&&y(),()=>{m.unobserve(y)}},[x,Me,Ke,il,u?.permission]);const Js=async()=>{if(!Ke)throw new Error("Collaboration is not synchronized");const m=Hs.current,y=await Me.flush();return Gr.current=Math.max(Gr.current,m),we(y.persistedAt),/\.tex$/i.test(Re.current)&&ti(),Hs.current===m?(te(!1),P("editor.savedAt")):P("editor.pending"),y};d.useEffect(()=>{if(!Y||!x)return;if(!Ke){P("editor.offlineDraft");return}P("editor.pending");const m=window.setTimeout(()=>{P("editor.saving"),Js().catch(()=>{P(Me.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(m)},[_,Y,x,Ke]);const us=async()=>{if(!u||u.permission==="read"||!Ke||!x)return!1;P("editor.saving");try{return await Js(),Gs(),!0}catch(m){return P("editor.saveFailed"),q(fe(m)||c("errors.collaborationUnavailable")),!1}},ud=async m=>{if(!u||qr)return;const y=m==="full"?st.current||u.mainFile:Re.current,D=m==="selection"?je.current.selectedText:"";if(!y)return;if(m==="selection"&&(!D.trim()||!/\.(?:tex|sty|cls)$/i.test(y))){De(c("editor.wordCountSelectionEmpty"));return}Rn.current?.abort();const E=new AbortController;Rn.current=E,zu(m),qu(y),Vr(null),Hr(""),Bs(!0),Wr(!0);try{if(m==="full"&&Y&&u.permission!=="read"&&!await us())throw new Error(c("editor.wordCountSaveRequired"));const oe=m==="selection"?{mode:m,path:y,source:D}:{mode:m,mainFile:y},X=await ce(`/api/projects/${n}/word-count`,{method:"POST",body:JSON.stringify(oe),signal:E.signal});if(E.signal.aborted)return;Vr(X)}catch(oe){if(Yt(oe))return;E.signal.aborted||Hr(fe(oe))}finally{Rn.current===E&&(Rn.current=null,Wr(!1))}},ni=async(m,y,D=et.texFmtConfig)=>{if(/\.bib$/i.test(m)){const oe=await za();try{return{formatted:oe.formatBibtex(y,t.maxCitationBibtexBytes)}}catch(X){throw X instanceof oe.BibtexFormatError?X.kind==="too-large"?new Error(c("citationLibrary.fileTooLarge",{size:oe.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})):new Error(c("citationLibrary.fileInvalid")):X}}return{formatted:(await Rf(y,D)).output}},ul=async m=>{if(!u||u.permission==="read"||!Ke||$t.current||!Qs(Re.current))return;const y=Re.current,D=Me.getText(y);$t.current=!0,_n(!0);let E=()=>{};const oe=new Promise(ie=>{E=ie});Kt.current=oe;let X=null;try{X=await Me.acquireFormatLease(y);const ie=D.toString(),{formatted:_t}=await ni(y,ie,m);if(Re.current!==y||D.toString()!==ie){q(c("editor.formatSourceChanged"));return}await X.confirm();const at=await wi(ie,_t);if(Re.current!==y||D.toString()!==ie){q(c("editor.formatSourceChanged"));return}if(await X.confirm(),Re.current!==y||D.toString()!==ie){q(c("editor.formatSourceChanged"));return}at.length&&Me.applyTextEdits(y,at),at.length&&await Js(),Mt(null),q(""),De(c("editor.formatFileComplete"))}catch(ie){gi(ie)?(Mt({action:"file",kind:ie.kind,detail:ie.message}),q("")):q(c("editor.formatFileFailed",{message:fe(ie)}))}finally{X&&await X.release(),$t.current=!1,_n(!1),E(),Kt.current===oe&&(Kt.current=null)}},dd=async()=>{if(!et.formatOnCompile||!u||u.permission==="read"||!Ke||!Qs(Re.current)||$t.current)return;const m=Re.current,y=Me.getText(m);$t.current=!0,_n(!0);let D=null;try{D=await Me.acquireFormatLease(m);const E=y.toString(),{formatted:oe}=await ni(m,E);await D.confirm();const X=await wi(E,oe);if(Re.current!==m||y.toString()!==E)throw new Error(c("editor.formatSourceChanged"));if(await D.confirm(),Re.current!==m||y.toString()!==E)throw new Error(c("editor.formatSourceChanged"));X.length&&Me.applyTextEdits(m,X),X.length&&await Me.flush(),Mt(null)}catch(E){gi(E)?(Mt({action:"file",kind:E.kind,detail:E.message}),q("")):q(c("editor.formatFailedContinue",{message:fe(E)}))}finally{D&&await D.release(),$t.current=!1,_n(!1)}},hd=async()=>(Kt.current&&await Kt.current,await dd(),us()),dl=async m=>{if(!u||u.permission==="read"||!Ke||$t.current||!Qs(Re.current))return;const y=je.current;if(!y.selectedText.trim()){De(c("editor.formatSelectionRequired"));return}const D=Re.current,{startOffset:E,endOffset:oe,selectedText:X}=y,ie=Me.getText(D);if(ie.toString().slice(E,oe)!==X){q(c("editor.formatSelectionChanged"));return}$t.current=!0,_n(!0);let _t=()=>{};const at=new Promise(It=>{_t=It});Kt.current=at;let He=null;try{if(He=await Me.acquireFormatLease(D),ie.toString().slice(E,oe)!==X){q(c("editor.formatSelectionChanged"));return}const fs=await ni(D,X,m),Mh=Ff(X,fs.formatted);await He.confirm();const mi=await wi(X,Mh,E);if(Re.current!==D||ie.toString().slice(E,oe)!==X){q(c("editor.formatSelectionChanged"));return}if(await He.confirm(),Re.current!==D||ie.toString().slice(E,oe)!==X){q(c("editor.formatSelectionChanged"));return}mi.length&&Me.applyTextEdits(D,mi),mi.length&&await Js(),Mt(null),q(""),De(c("editor.formatSelectionComplete"))}catch(It){gi(It)?(Mt({action:"selection",kind:It.kind,detail:It.message}),q("")):q(c("editor.formatFailed",{message:fe(It)}))}finally{He&&await He.release(),$t.current=!1,_n(!1),_t(),Kt.current===at&&(Kt.current=null)}},fd=async m=>{const y=Re.current;if(!/\.bib$/i.test(y)||u?.permission==="read"||!Ke)return De(c("citationLibrary.importRequiresWrite")),!1;const D=Me.getText(y);let E;try{E=await za()}catch(fs){return q(fe(fs)),!1}if(Re.current!==y||!Ke)return!1;const oe=D.toString(),X=E.parseBibEntriesResult(oe,t.maxCitationBibtexBytes);if(X.status==="too-large")return De(c("citationLibrary.fileTooLarge",{size:E.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})),!1;if(X.status==="invalid")return De(c("citationLibrary.fileInvalid")),!1;if(X.entries.some(fs=>fs.citationKey.toLowerCase()===m.citationKey.toLowerCase()))return De(c("citationErrors.alreadyInFile",{key:m.citationKey})),!1;const ie=Math.max(0,Math.min(oe.length,se.getCursor().offset)),_t=oe.slice(0,ie),at=oe.slice(ie),He=_t?_t.endsWith(`
|
|
21
|
+
|
|
22
|
+
`)?"":_t.endsWith(`
|
|
23
|
+
`)?`
|
|
24
|
+
`:`
|
|
25
|
+
|
|
26
|
+
`:"",It=at?at.startsWith(`
|
|
27
|
+
|
|
28
|
+
`)?"":at.startsWith(`
|
|
29
|
+
`)?`
|
|
30
|
+
`:`
|
|
31
|
+
|
|
32
|
+
`:"";return Me.applyTextEdits(y,[{from:ie,to:ie,replacement:`${He}${m.bibtex.trim()}${It}`}]),De(c("citationLibrary.imported",{key:m.citationKey})),!0},{files:St,setFiles:hl,loadFiles:pd,newFileOpen:md,setNewFileOpen:fl,newFilePath:gd,setNewFilePath:pl,resourcePreview:wd,setResourcePreview:ml,resourcePreviewLoading:yd,setResourcePreviewLoading:bd,newFolderOpen:xd,setNewFolderOpen:gl,newFolderName:kd,setNewFolderName:wl,fileDialogError:Sd,setFileDialogError:yl,selectedFolder:bl,setSelectedFolder:si,selectedFile:Cd,setSelectedFile:xl,expandedFolders:vd,setExpandedFolders:kl,moveEntry:jd,setMoveEntry:Sl,moveName:Ed,setMoveName:Cl,moveDestination:Dd,setMoveDestination:vl,deleteEntry:ri,setDeleteEntry:jl,fileDragActive:_d,setFileDragActive:Td,uploadConflict:Ld,setUploadConflict:Rd,uploadingFiles:Ad,directoryEntries:Nd,visibleEntries:Fd,createFile:Od,createFolder:Md,uploadFiles:El,upload:$d,openFile:ii,movePath:Id,movePathToFolder:Pd,removePath:Ud}=Iy({projectId:n,site:t,activeFile:x,dirty:Y,save:us,onError:q,onProject:f,onActiveFile:N,onActiveMainFile:T}),Dl=()=>st.current||u?.mainFile||"",zd=()=>{const m=Dl(),y=Re.current;if(!y||!/\.tex$/i.test(y))return m;const D=St.filter(X=>X.type==="file"&&/\.tex$/i.test(X.path)).length,E=Me.getText(y).toString();return $a(E)||D===1?(m!==y&&(st.current=y,T(y)),y):m===y&&u?.mainFile&&u.mainFile!==y?(st.current=u.mainFile,T(u.mainFile),u.mainFile):m};d.useEffect(()=>{!x||x!==R||de!==x||H.filePath!==x||!x.toLocaleLowerCase().endsWith(".tex")||St.filter(y=>y.type==="file"&&/\.tex$/i.test(y.path)).length===0||x===u?.mainFile||!$a(H.content)&&u?.mainFile&&(st.current=u.mainFile,T(u.mainFile))},[x,R,de,H,St,u?.mainFile]),d.useEffect(()=>{if(!et.openFilesInTabs||St.length===0)return;const m=new Set(St.filter(y=>y.type==="file"&&Kn(y.path)).map(y=>y.path));Vs(y=>{const D=y.filter(E=>m.has(E));return D.length===y.length?y:D})},[St,et.openFilesInTabs]);const{comments:hn,commentsFilePath:oi,commentsReady:li,reviewComments:Bd,reviewCommentsLoading:qd,reviewCommentsError:Wd,retryReviewComments:Hd,commentScope:Vd,setCommentScope:Kd,focusComment:_l,setFocusComment:Ys,commentOpen:Gd,openComment:Jd,closeComment:Yd,commentText:Xd,setCommentText:Zd,commentSelection:Qd,commentSubmitting:eh,commentError:th,addComment:nh,toggleComment:sh,replyToComment:rh,editComment:ih,deleteComment:oh,editCommentReply:lh,deleteCommentReply:ah}=Yf({projectId:n,activeFile:x,content:_,permission:u?.permission,revision:sl,selection:$e,save:us,saveFailureMessage:c("errors.collaborationUnavailable"),onError:q,onAdded:()=>Ee("comments"),onChanged:()=>{td()}});d.useEffect(()=>{if(!R||H.filePath!==R)return;const m=Ia(H.content).length>0;V(y=>y.path===R&&y.hasIncludes===m?y:{path:R,hasIncludes:m})},[R,H]),d.useEffect(()=>{if(!R||!Ke||x===R)return;const m=Me.getText(R);let y=null;const D=()=>{const oe=Ia(m.toString()).length>0;V(X=>X.path===R&&X.hasIncludes===oe?X:{path:R,hasIncludes:oe})},E=()=>{y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>{y=null,D()},Ba)};return D(),m.observe(E),()=>{y!==null&&window.clearTimeout(y),m.unobserve(E)}},[x,R,Me,Ke]);const ch=d.useMemo(()=>Z.path===R&&Z.hasIncludes,[R,Z]),ai=m=>{Ee("comments"),Ys(null),_e(m),Re.current!==m.filePath&&Nn(m.filePath,m.startLine,1)};d.useEffect(()=>{if(!S)return;const m=ep(S,x,de,oi,li,hn);if(m){Ys({...m}),_e(null);return}S.filePath===x&&de===x&&oi===x&&li&&_e(null)},[x,hn,oi,li,de,S,Ys]);const uh=async m=>{const y=await nd(m);return y&&Xr.current?.(1),y},dh=async()=>{const m=ll.length,y=await sd();return y&&m&&Xr.current?.(m,!0),y};d.useEffect(()=>{if(!A||x!==A.filePath||re!=="comments")return;const m=hn.find(D=>D.id===A.commentId);if(!m||A.replyId&&!m.replies.some(D=>D.id===A.replyId)||Jr.current===A.id)return;Jr.current=A.id,ai(m);const y=window.setTimeout(()=>O(D=>D?.id===A.id?null:D),3e3);return()=>window.clearTimeout(y)},[x,hn,re,A]);const{pdfUrl:Gt,pdfCompiledAt:ds,pdfLoadingMode:hh,pdfLoading:ci,compileLog:ui,compileDiagnostics:fh,compileOutcome:hs,artifacts:Tl,artifactPreview:ph,artifactLoading:mh,editorNotice:gh,localCompiling:Ll,cancelling:wh,cleaning:Rl,compile:yh,cancelCompile:bh,cleanCompile:Al,viewArtifact:xh}=Fy({projectId:n,project:u,mainFile:R,resolveCompileMainFile:zd,getCurrentMainFile:Dl,initialLatest:s?.projectId===n?s.latestCompile:null,collaborationSynced:Ke,sharedState:dn,onSharedState:nl,save:hd,loadOutline:(m,y)=>ti({signal:m},y),onPreviewTab:ae,onError:q,onCompileStart:()=>{q(""),De("")},onCompileSuccess:()=>{const m=Re.current;if(m){const y=se.getCursor();Qr(m,y.line,y.column,{silent:!0})}},onPdfChanged:al});d.useEffect(()=>{if(!u||!R||!Gt&&ci)return;const m=window.setTimeout(()=>p(!0),Gt?150:0);return()=>window.clearTimeout(m)},[u,ci,Gt]),d.useEffect(()=>{const m=y=>{(y.ctrlKey||y.metaKey)&&(!y.shiftKey&&y.key.toLocaleLowerCase()==="p"?(y.preventDefault(),z(!0)):y.shiftKey&&y.key.toLocaleLowerCase()==="f"&&(y.preventDefault(),kt(!0)))};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[]);const Nl=m=>{Jo(m),Ef(e.id,n,m)},Fl=(m=!1)=>{const y=ln;if(!y)return;Mt(null),q(""),m&&Nl({...et,texFmtConfig:""});const D=m?"":void 0;y.action==="selection"?dl(D):ul(D)},kh=async()=>{Kr(!0);try{await ed()||(q(c("editor.collaboration.permissionDowngradeOtherTabBlocked")),Kr(!1))}catch(m){q(fe(m)),Kr(!1)}},Ol=()=>{Ws.current?.isCollapsed()?Ws.current.expand():Ws.current?.collapse()},Sh=d.useMemo(()=>Yb(k,R,H),[k,R,H]),di=d.useMemo(()=>Of(ui,hs),[ui,hs]),Fn=ke!=="pdf-only",Ml=ke!=="editor-only",Xs=m=>{Ne(m),m==="pdf-only"&&ae("pdf")},Ch=d.useCallback(m=>{Vt.current?.abort();const y=new AbortController;Vt.current=y;const D=Re.current,E=st.current,oe=new URLSearchParams({kind:m.kind,key:m.key,...D?{path:D}:{},...E?{mainFile:E}:{}});ce(`/api/projects/${n}/references/resolve?${oe}`,{signal:y.signal}).then(({target:X})=>{if(!(y.signal.aborted||Re.current!==D||st.current!==E)){if(!X){q(c(m.kind==="citation"?"editor.citationTargetNotFound":"editor.labelTargetNotFound",{key:m.key}));return}Yo.current==="pdf-only"&&Xs("editor-pdf"),Nn(X.path,X.line,X.column)}}).catch(X=>{!y.signal.aborted&&!Yt(X)&&q(fe(X))}).finally(()=>{Vt.current===y&&(Vt.current=null)})},[Nn,n,c]),vh=ri?tl.filter(m=>m.filePath&&pn(ri.path,m.filePath)):[];if(!u)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:pe||c("common.loading")}),pe&&o.jsx("button",{className:"primary",onClick:a,children:c("editor.backToProjects")})]});const Jt=u.permission==="read"||!Ke,hi=Ju.find(m=>m.path===x),fi=hi&&!cs?hi:null,jh=(m,y)=>{if(Jt)return;const D=Re.current;if(!D)return;if(Me.getText(D).toString().slice(m.from,m.to)!==m.word){q(c("editor.spellCheckSourceChanged"));return}try{Me.applyTextEdits(D,[{from:m.from,to:m.to,replacement:y}])}catch(X){q(fe(X))}},pi=dn?.mainFile===R&&(dn.status==="queued"||dn.status==="running"),Zs=Ll||pi||Rl,Eh=x?Me.getText(x):null,Dh=ds?new Date(ds).toLocaleString(ys.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",_h=R.split("/").at(-1)??R,Th=di.warnings.length+di.errors.length+Tl.length,Lh=Gt?`${Gt}${Gt.includes("?")?"&":"?"}download=1`:"",Rh=R||u.mainFile,Ah=!!(x&&x===Rh&&/\.tex$/i.test(x)),$l=m=>{const y=St.find(D=>D.path===m);y&&Kn(y.path)?ii(y):el(m)},Nh=m=>{document.getElementById(`editor-tab-${encodeURIComponent(m)}`)?.focus()},Fh=(m,y)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(m.key))return;m.preventDefault();const D=m.key==="Home"?0:m.key==="End"?Tn.length-1:(y+(m.key==="ArrowLeft"?-1:1)+Tn.length)%Tn.length,E=Tn[D];E&&($l(E),window.requestAnimationFrame(()=>Nh(E)))},Il=Zs?pi?dn?.status==="queued"?c("editor.compileQueued"):c("editor.compilingBy",{name:dn?.requestedBy.name??c("common.user")}):c("editor.compiling"):hs==="failed"?Gt&&ds?c("editor.compileFailedRetained",{time:new Date(ds).toLocaleString(ys.resolvedLanguage)}):c("editor.compileFailedNoPdf"):hs==="cancelled"?c("compileControls.cancelled"):"",Oh=ne==="editor.savedAt"&&ge?c("editor.savedAt",{time:new Date(ge).toLocaleTimeString(ys.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):c(ne);return o.jsxs("div",{className:"workspace","data-texlite-tooltips":et.showTooltips?"on":"off",children:[o.jsx(lb,{site:t,project:u,activeFile:x,saveStateLabel:Oh,editorPreferences:et,activeSessions:tl,collaborationStatus:Ks,reconnectCollaboration:Xu,protocolUpgradeRequired:ol,showEditor:Fn,filesCollapsed:M,toggleFilesPanel:Ol,workspaceLayout:ke,changeWorkspaceLayout:Xs,onBack:a,onShare:()=>Be(!0),showCitationLibrary:Fn&&/\.bib$/i.test(x),citationLibraryOpen:mt,onCitationLibrary:()=>be(!0),onSelectionHistory:()=>bt(!0),onHistory:()=>j(!0),onGit:()=>L(!0),canManageGit:u.ownerId===e.id,formatting:cs,readOnly:Jt,collaborationSynced:Ke,hasSelection:!!$e.selectedText.trim(),onToggleComments:()=>Ee(re==="comments"?null:"comments"),commentsOpen:re==="comments",unresolvedCommentCount:hn.filter(m=>!m.resolved).length,hasActiveFile:!!x,onToggleSettings:()=>Ee(re==="settings"?null:"settings"),settingsOpen:re==="settings",compileBusy:Zs,sharedCompiling:pi,localCompiling:Ll,cancelling:wh,compileState:dn,onCompile:yh,onCancelCompile:()=>{bh()}}),ol&&o.jsxs("div",{className:"workspace-update-banner",role:"alert",children:[o.jsx(zt,{size:15}),o.jsx("span",{children:c("workspaceUpdates.protocolUpgrade")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),Il&&o.jsxs("div",{className:`compile-status-strip${hs==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(rt,{className:Zs?"spin":"",size:14}),o.jsx("span",{children:Il})]}),(ht.error||ln||fi)&&o.jsxs("div",{className:"client-tool-recoveries",children:[ht.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:ht.error,children:[o.jsx(zt,{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:ht.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:ht.dismissError,children:o.jsx(Ss,{size:13})})]}),ln&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:ln.detail,children:[o.jsx(zt,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c(ln.kind==="format"?"editor.texFmtOptionsRecoveryTitle":ln.kind==="load"?"editor.texFmtRecoveryTitle":"editor.texFmtRuntimeRecoveryTitle")}),c("editor.clientToolRecoveryHint")]}),o.jsxs("div",{className:"client-tool-recovery-actions",children:[o.jsx("button",{type:"button",disabled:cs||Jt,onClick:()=>Fl(),children:c("common.retry")}),ln.kind==="format"&&et.texFmtConfig.trim()&&o.jsx("button",{type:"button",disabled:cs||Jt,onClick:()=>Fl(!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:()=>Mt(null),children:o.jsx(Ss,{size:13})})]}),fi&&o.jsxs("div",{className:"client-tool-recovery format-lease-status",role:"status",children:[o.jsx(rt,{className:"spin",size:15}),o.jsx("span",{children:c("editor.formattingBy",{name:fi.holderName})})]})]}),Yu&&o.jsxs("div",{className:"client-tool-recovery",role:"status",children:[o.jsx(zt,{size:15}),o.jsx("span",{children:c("history.saveWarning")})]}),pe&&o.jsx("div",{className:"toast",onClick:()=>q(""),children:pe}),K&&o.jsx("div",{className:"toast success",onClick:()=>De(""),children:K}),o.jsxs(Bh,{autoSaveId:gn("texlite-workspace-layout"),direction:"horizontal",className:"work-grid",children:[Fn&&o.jsx(kb,{project:u,filesPanel:Ws,files:St,visibleEntries:Fd,activeFile:x,activeMainFile:R,selectedFile:Cd,selectedFolder:bl,expandedFolders:vd,fileDragActive:_d,uploadingFiles:Ad,readOnly:Jt,formatting:cs,canFormat:Qs(x),activeFormatLease:!!hi,collaborationSynced:Ke,editorFontSize:et.fontSize,outline:Sh,sourceCursorStore:se,wordCountBusy:qr,hasSelection:!!$e.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(x),hasFormatSelection:!!$e.selectedText.trim(),uploadInput:Ku,setSelectedFolder:si,setExpandedFolders:kl,setMoveEntry:Sl,setMoveName:Cl,setMoveDestination:vl,setDeleteEntry:jl,setFileDialogError:yl,setNewFolderName:wl,setNewFolderOpen:gl,setNewFilePath:pl,setNewFileOpen:fl,setQuickOpen:z,setProjectSearchOpen:kt,setFileDragActive:Td,setFilesCollapsed:he,toggleFilesPanel:Ol,onError:q,uploadFiles:El,upload:$d,openFile:ii,movePathToFolder:Pd,onFormatFile:()=>{ul()},onFormatSelection:()=>{dl()},jumpToSource:Nn,syncSourceToPdf:Qr,onWordCount:m=>{ud(m)}}),Fn&&o.jsx(ao,{className:"resize-handle",children:o.jsx(Va,{size:12})}),Fn&&o.jsx(_b,{project:u,activeFile:x,openTabs:Tn,content:_,loadedFile:de,readOnly:Jt,comments:hn,focusComment:_l,editorPreferences:et,completionIndex:C,nativeSpellCheck:ht.nativeFallback,spellCheckIssues:ht.issues,spellCheckJump:ht.jump,sourceJump:od,collaborativeText:Eh,collaborationAwareness:Me.awareness,undoManager:x?Me.getUndoManager(x):void 0,editorNotice:gh,activateTab:$l,closeTab:el,handleTabKeyDown:Fh,updateEditorContent:ei,setSelection:(m,y,D)=>F({selectedText:m,startOffset:y,endOffset:D}),onAddComment:(m,y,D,E)=>Jd({selectedText:m,startOffset:y,endOffset:D},E),onCommentClick:m=>{const y=hn.find(D=>D.id===m);y&&ai(y)},onSpellCheckReplace:jh,onReferenceNavigate:Ch,onCursor:Gu}),Ml&&o.jsx(Fb,{projectId:n,activeMainFile:R,previewTab:b,diagnosticTab:Q,pdfUrl:Gt,pdfLoadingMode:hh,pdfLoading:ci,pdfCompiledAt:ds,pdfCompiledLabel:Dh,pdfTargetLabel:_h,pdfDownloadUrl:Lh,pdfTarget:rd,pdfViewport:id,activeFile:x,compileBusy:Zs,compileLog:ui,compileDiagnostics:fh,compileMessages:di,artifacts:Tl,artifactPreview:ph,artifactLoading:mh,cleaning:Rl,readOnly:Jt,collaborationSynced:Ke,workspaceLayout:ke,showSyncResize:Fn&&Ml,diagnosticCount:Th,selectPreviewTab:ae,changeWorkspaceLayout:Xs,onSetNotice:De,onSetPdfViewport:ld,syncVisiblePdfToSource:cd,syncCurrentSourceToPdf:()=>{const m=Re.current;if(!m)return Promise.resolve();const y=se.getCursor();return Qr(m,y.line,y.column)},syncPdfToSource:ad,canSyncWithPdf:Ah,files:St,jumpToSource:Nn,onSetCleanMode:xt,cleanCompile:Al,viewArtifact:xh}),o.jsx(Kb,{sidePanel:re,onClose:()=>Ee(null),project:u,projectId:n,site:t,files:St,currentUserId:e.id,comments:Bd,commentsLoading:qd,commentsError:Wd,onRetryComments:Hd,activeFile:x,hasProjectCommentsScope:ch,commentScope:Vd,onCommentScopeChange:Kd,focusedCommentId:_l?.id,onClearFocusComment:()=>Ys(null),unreadMentions:ll,onMarkMentionRead:uh,onMarkAllMentionsRead:dh,targetCommentId:A?.commentId,targetReplyId:A?.replyId,onFocusComment:ai,onToggleComment:sh,onReplyComment:rh,onEditComment:ih,onDeleteComment:oh,onEditCommentReply:lh,onDeleteCommentReply:ah,dictionaryWords:w,onDictionaryChange:g,editorPreferences:et,onEditorPreferences:Nl,spellCheckCount:ht.summary?.total??null,spellCheckUniqueCount:ht.summary?.unique??null,spellCheckIndex:ht.summary?ht.index:-1,onSpellCheckNavigate:ht.jumpToIssue,onProject:f})]}),lt&&o.jsx(Wa,{title:c("editor.wordCountTitle"),onClose:()=>Bs(!1),children:o.jsx(Zb,{open:!0,mode:Uu,path:Bu,busy:qr,error:Wu,result:Hu,onOpenChange:Bs})}),o.jsx(Wb,{user:e,project:u,projectId:n,activeFile:x,content:_,maxCitationBibtexBytes:t.maxCitationBibtexBytes,files:St,directoryEntries:Nd,readOnly:Jt,workspaceLayout:ke,changeWorkspaceLayout:Xs,resourcePreview:wd,resourcePreviewLoading:yd,setResourcePreview:ml,setResourcePreviewLoading:bd,uploadConflict:Ld,setUploadConflict:Rd,uploadFiles:El,cleanMode:dt,setCleanMode:xt,cleanCompile:Al,newFileOpen:md,setNewFileOpen:fl,newFilePath:gd,setNewFilePath:pl,newFolderOpen:xd,setNewFolderOpen:gl,newFolderName:kd,setNewFolderName:wl,selectedFolder:bl,fileDialogError:Sd,setFileDialogError:yl,createFile:Od,createFolder:Md,moveEntry:jd,setMoveEntry:Sl,moveName:Ed,setMoveName:Cl,moveDestination:Dd,setMoveDestination:vl,movePath:Id,deleteEntry:ri,setDeleteEntry:jl,deleteActiveSessions:vh,removePath:Ud,commentOpen:Gd,closeComment:Yd,commentSelection:Qd,selection:$e,commentText:Xd,setCommentText:Zd,commentSubmitting:eh,commentError:th,addComment:nh,shareOpen:Fe,setShareOpen:Be,citationLibraryOpen:mt,setCitationLibraryOpen:be,insertCitationAtCursor:fd,quickOpen:ve,setQuickOpen:z,projectSearchOpen:W,setProjectSearchOpen:kt,openFile:ii,jumpToSource:Nn,selectionHistoryOpen:Pe,setSelectionHistoryOpen:bt,historyOpen:J,setHistoryOpen:j,gitOpen:ye,setGitOpen:L,save:us,permissionDowngrade:Zu,permissionDowngradeBusy:Vu,dismissPermissionDowngrade:Qu,discardPermissionDraft:kh})]})}const yx=Object.freeze(Object.defineProperty({__proto__:null,ProjectWorkspace:Qb},Symbol.toStringTag,{value:"Module"}));export{of as A,Jf as B,uo as C,Zt as D,Af as E,af as F,Cf as G,ql as H,qi as I,rf as J,ax as K,yx as P,kf as R,Hl as S,Og as U,hx as a,fx as b,no as c,px as d,mx as e,vn as f,cx as g,Pt as h,Ou as i,Hy as j,gx as k,Go as l,yo as m,as as n,zs as o,Dr as p,nb as q,dx as r,qy as s,ux as t,wx as u,lo as v,Gy as w,oo as x,Jy as y,lx as z};
|