texlite 0.9.1 → 0.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +36 -6
- package/OPERATIONS.md +70 -3
- package/README.md +11 -3
- package/README.zh-CN.md +11 -2
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/dist/client/assets/AdminUsers-huwQK7Ly.js +1 -0
- package/dist/client/assets/CitationLibraryDialog-C5C3sPdw.js +1 -0
- package/dist/client/assets/Dashboard-DtHSc55D.js +2 -0
- package/dist/client/assets/{GitDialog-C9Loz4Al.js → GitDialog-BI7QIMsh.js} +1 -1
- package/dist/client/assets/{HistoryDialog-3UNN_jhU.js → HistoryDialog-DA7O9aF2.js} +1 -1
- package/dist/client/assets/LatexEditor-BYWWx5Km.js +138 -0
- package/dist/client/assets/{PdfPreview-BKhcS-2c.js → PdfPreview-mO9WS01q.js} +1 -1
- package/dist/client/assets/ProjectIconPickerDialog-B0q_r5dX.js +1 -0
- package/dist/client/assets/{ProjectNavigationDialogs-CZKTnxrl.js → ProjectNavigationDialogs-DwWYbB1A.js} +1 -1
- package/dist/client/assets/ProjectSettings-BpPFgdoj.js +1 -0
- package/dist/client/assets/ProjectWorkspace-CI2zKon5.js +32 -0
- package/dist/client/assets/{SelectionHistoryDialog-D3dO83lg.js → SelectionHistoryDialog-pWMI5izu.js} +2 -2
- package/dist/client/assets/SystemMetricsDialog-BmlO7oNg.js +1 -0
- package/dist/client/assets/TagManagementDialog-h4Ves4FR.js +1 -0
- package/dist/client/assets/{WordCountDialog-TwpyAP3m.js → WordCountDialog-DlBSP4y7.js} +1 -1
- package/dist/client/assets/check-BAdi_Lxq.js +1 -0
- package/dist/client/assets/editor-DZS7-wrd.js +14 -0
- package/dist/client/assets/{hard-drive-XHSiS_A7.js → hard-drive-DP2OHKMC.js} +1 -1
- package/dist/client/assets/index-CBrIrzgg.css +1 -0
- package/dist/client/assets/{index-Cd6-F29b.js → index-i5IY_PMw.js} +1 -1
- package/dist/client/assets/index-teah8iB2.js +12 -0
- package/dist/client/assets/katex-D9PXdmFF.css +1 -0
- package/dist/client/assets/{key-round-C-CXCWnz.js → key-round-D8sCqL2b.js} +1 -1
- package/dist/client/assets/{latexFormatterWorker-DYkYtcFy.js → latexFormatterWorker-BRmsns8a.js} +2 -2
- package/dist/client/assets/{minimize-2-BMDPVaF-.js → minimize-2-6tf519Ts.js} +1 -1
- package/dist/client/assets/{minus-BIa7-KuM.js → minus-CqvESp9M.js} +1 -1
- package/dist/client/assets/{pdf-BB1XvBIF.js → pdf-DUYcbPMK.js} +1 -1
- package/dist/client/assets/{plus-BKDWy4Ui.js → plus-DIrweesj.js} +1 -1
- package/dist/client/assets/{refresh-cw-Bo7-a7-I.js → refresh-cw-BDcwKu_d.js} +1 -1
- package/dist/client/assets/{search-Bz9Ob5mT.js → search-C9_Jyrnx.js} +1 -1
- package/dist/client/assets/{sigma-DxlHf9gv.js → sigma-p9-fBP0d.js} +1 -1
- package/dist/client/assets/spellCheck-Y0RlmXbl.js +1 -0
- package/dist/client/assets/{tags-IMZehjzE.js → tags-DjF3z21M.js} +1 -1
- package/dist/client/assets/{type-DTWpFQNQ.js → type-CNrDJnzR.js} +1 -1
- package/dist/client/assets/{user-plus--aVpd8K6.js → user-plus-C7exNawX.js} +1 -1
- package/dist/client/assets/x-BEVz0wdw.js +1 -0
- package/dist/client/index.html +6 -4
- package/dist/server/app.js +130 -83
- package/dist/server/cli.js +4 -2
- package/dist/server/collaboration.js +6 -19
- package/dist/server/compileArtifacts.js +3 -2
- package/dist/server/config.js +27 -0
- package/dist/server/db.js +91 -10
- package/dist/server/index.js +4 -2
- package/dist/server/instanceLock.js +4 -2
- package/dist/server/latexCompletion.js +126 -63
- package/dist/server/latexDocumentGraph.js +217 -0
- package/dist/server/latexSpellMask.js +3 -4
- package/dist/server/pm2.js +3 -2
- package/dist/server/projectOutline.js +103 -91
- package/dist/server/projectReferences.js +109 -0
- package/dist/server/routes/auth.js +5 -2
- package/dist/server/routes/comments.js +10 -4
- package/dist/server/routes/compile.js +2 -2
- package/dist/server/routes/projectFiles.js +12 -3
- package/dist/server/routes/projectReferences.js +36 -0
- package/dist/server/routes/projectShared.js +33 -12
- package/dist/server/routes/projects.js +5 -0
- package/dist/server/routes/system.js +1 -0
- package/dist/server/zip.js +2 -16
- package/dist/shared/basePath.js +44 -0
- package/dist/shared/bibtexReferences.js +135 -0
- package/dist/shared/collaborationProtocol.js +31 -0
- package/dist/shared/latexCommandSnippets.js +91 -0
- package/dist/shared/latexDependencies.js +131 -0
- package/dist/shared/latexLiterals.js +215 -0
- package/dist/shared/latexReferenceCommands.js +75 -0
- package/dist/shared/latexReferences.js +193 -0
- package/dist/shared/latexRoot.js +21 -0
- package/dist/shared/latexScanner.js +183 -0
- package/dist/shared/writingChecks.js +4 -0
- package/package.json +11 -4
- package/texlite.config.example.json +2 -4
- package/dist/client/assets/AdminUsers-Dazar9cj.js +0 -1
- package/dist/client/assets/CitationLibraryDialog-VSUiSPgG.js +0 -1
- package/dist/client/assets/Dashboard-CoE5ESfb.js +0 -2
- package/dist/client/assets/LatexEditor-Bq76v8sO.js +0 -65
- package/dist/client/assets/ProjectIconPickerDialog-BoWMjQVm.js +0 -1
- package/dist/client/assets/ProjectSettings-DiOQVJ40.js +0 -1
- package/dist/client/assets/ProjectWorkspace-DqLwkGpT.js +0 -27
- package/dist/client/assets/SystemMetricsDialog-0zCwLtH_.js +0 -1
- package/dist/client/assets/TagManagementDialog-C6KDwtvd.js +0 -1
- package/dist/client/assets/check-sZxOOKtS.js +0 -1
- package/dist/client/assets/chevron-left-32SrOwa5.js +0 -1
- package/dist/client/assets/editor-CiK7TK0p.js +0 -14
- package/dist/client/assets/index-BRr3Kuxh.css +0 -1
- package/dist/client/assets/index-BjzELSQ-.js +0 -12
- package/dist/client/assets/katex-CEK31ho9.css +0 -1
- package/dist/client/assets/spellCheck-BfZEnpwY.js +0 -1
- package/dist/client/assets/x-Tbo3aA0J.js +0 -1
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/spellCheck-BfZEnpwY.js","assets/index-BjzELSQ-.js","assets/react-BVUjbTTn.js","assets/index-BRr3Kuxh.css","assets/check-sZxOOKtS.js","assets/x-Tbo3aA0J.js","assets/search-Bz9Ob5mT.js","assets/user-plus--aVpd8K6.js","assets/refresh-cw-Bo7-a7-I.js","assets/LatexEditor-Bq76v8sO.js","assets/editor-CiK7TK0p.js","assets/CitationLibraryDialog-VSUiSPgG.js","assets/citationLibrary-ZeQPCv5O.js","assets/plus-BKDWy4Ui.js","assets/chevron-left-32SrOwa5.js","assets/tags-IMZehjzE.js","assets/GitDialog-C9Loz4Al.js","assets/key-round-C-CXCWnz.js","assets/minus-BIa7-KuM.js","assets/minimize-2-BMDPVaF-.js","assets/HistoryDialog-3UNN_jhU.js","assets/index-Cd6-F29b.js","assets/hard-drive-XHSiS_A7.js","assets/SelectionHistoryDialog-D3dO83lg.js","assets/ProjectNavigationDialogs-CZKTnxrl.js","assets/ProjectSettings-DiOQVJ40.js","assets/type-DTWpFQNQ.js","assets/sigma-DxlHf9gv.js","assets/WordCountDialog-TwpyAP3m.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{c as Le,f as ce,g as de,A as ji,n as Wd,l as qd,r as Hd,_ as Ct,S as Vd,b as tt,i as fs,h as ha,C as gs,M as Kt,d as fa,j as Kd}from"./index-BjzELSQ-.js";import{r as h,u as Ke,j as o,P as gr,d as Hi,e as Jd}from"./react-BVUjbTTn.js";import{C as Gd}from"./check-sZxOOKtS.js";import{e as Yd,U as vi,B as Xd,M as Qd,G as Zd,X as ws,F as eh,f as pl,g as th,a as nh,C as sh,b as rh,T as Xt,c as pa,d as Wn,L as ih,i as Pt,S as Ei,D as Qs,A as Zs,P as ml,h as gl}from"./x-Tbo3aA0J.js";import{S as oh}from"./search-Bz9Ob5mT.js";import{U as lh}from"./user-plus--aVpd8K6.js";import{R as ah}from"./refresh-cw-Bo7-a7-I.js";const ch=Le("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const ma=Le("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const uh=Le("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Vi=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 wl=Le("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const Di=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 dh=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 hh=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 ga=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 yl=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 fh=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 bl=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 wa=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 ya=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 ph=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 mh=Le("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const gh=Le("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const wh=Le("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const yh=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 bh=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 xl=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 xh=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 Sh=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"}]]),kh="wrap = false",_i=[{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'}],yt={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,spellCheck:!0,mathPreviewOnHover:!1,vimMode:!1,formatOnCompile:!1,texFmtConfig:kh,texFmtConfigInitialized:!0,openFilesInTabs:!1},Ch="texlite-editor-preferences";function ba(t,e){return`${Ch}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function py(t){return _i.find(e=>e.id===t)?.stack??_i[0].stack}function Sl(t,e){try{const n=JSON.parse(localStorage.getItem(ba(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:yt.texFmtConfig;return{font:_i.some(i=>i.id===n.font)?n.font:yt.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):yt.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):yt.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:yt.lineWrapping,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:yt.spellCheck,mathPreviewOnHover:typeof n.mathPreviewOnHover=="boolean"?n.mathPreviewOnHover:yt.mathPreviewOnHover,vimMode:typeof n.vimMode=="boolean"?n.vimMode:yt.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:yt.formatOnCompile,texFmtConfig:r,texFmtConfigInitialized:!0,openFilesInTabs:typeof n.openFilesInTabs=="boolean"?n.openFilesInTabs:yt.openFilesInTabs}}catch{return yt}}function jh(t,e,n){localStorage.setItem(ba(t,e),JSON.stringify(n))}function vh(){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 Jt=vh(),Eh=/\.(?:tex|bib|cls|sty)$/i,xa=3e4;let bt=null,er=!1,hn=null,Dh=1;const mn=new Map,tr=[];let On=null,us=null;class ct extends Error{constructor(e,n){super(n),this.kind=e,this.name="TexFmtError"}kind}function ri(t){return t instanceof ct}function It(t){bt?.terminate(),bt=null,er=!1,hn!==null&&window.clearTimeout(hn),hn=null,On=null,tr.length=0,us=null,Jt.failed(t);for(const e of mn.values())e.timeout!==null&&window.clearTimeout(e.timeout),e.reject(t);mn.clear()}function ps(){if(On!==null||tr.length===0)return;let t;try{t=_h()}catch(s){It(s instanceof ct?s:new ct("load","The bundled tex-fmt formatter could not be loaded."));return}if(!er)return;const e=tr.shift();if(e===void 0)return;const n=mn.get(e);if(!n){ps();return}On=e,n.timeout=window.setTimeout(()=>{On===e&&It(new ct("result","The formatter did not respond within 30 seconds."))},xa);try{t.postMessage({...n.request,id:e})}catch{It(new ct("load","The formatter worker could not receive the source."))}}function _h(){if(bt)return bt;if(typeof Worker>"u"){const t=new ct("load","This browser does not support formatter workers.");throw Jt.failed(t),t}Jt.loading();try{bt=new Worker(new URL("/assets/latexFormatterWorker-DYkYtcFy.js",import.meta.url),{type:"module",name:"texlite-latex-formatter"}),hn=window.setTimeout(()=>{er||It(new ct("load","The formatter did not finish loading within 30 seconds."))},xa)}catch{const t=new ct("load","The bundled tex-fmt formatter could not be loaded.");throw Jt.failed(t),t}return bt.onmessage=t=>{const e=t.data;if(e&&"type"in e){e.type==="ready"&&(er=!0,hn!==null&&window.clearTimeout(hn),hn=null,ps());return}if(!e||typeof e.id!="number"){It(new ct("result","The formatter worker returned an invalid response."));return}const n=mn.get(e.id);if(n)if(mn.delete(e.id),n.timeout!==null&&window.clearTimeout(n.timeout),On===e.id&&(On=null),e.ok)Jt.working(),n.resolve(e.result),ps();else{const s=new ct(e.kind,e.message);e.kind==="format"?(Jt.working(),n.reject(s),ps()):(n.reject(s),It(s))}},bt.onerror=()=>{It(new ct("load","The bundled tex-fmt formatter could not be loaded."))},bt.onmessageerror=()=>{It(new ct("result","The formatter worker returned an unreadable response."))},bt}function Ki(t){const e=Dh++;return new Promise((n,s)=>{mn.set(e,{request:t,resolve:n,reject:s,timeout:null}),tr.push(e),ps()})}function Th(t,e=""){return Ki({action:"format",source:t,config:e})}async function Lh(){bt&&Jt.getSnapshot().status==="working"||(us||(us=Ki({action:"probe"}).then(()=>{}).finally(()=>{us=null})),await us)}async function my(){(bt||mn.size)&&It(new ct("load","The formatter runtime was reloaded.")),Jt.loading(),await Lh()}function Bs(t){return Eh.test(t)}function Rh(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function Ah(t,e){const n=Rh(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 ii(t,e,n=0){return Ki({action:"diff",source:t,formatted:e,baseOffset:n})}function Nh(t,e=null){const n=kl(t),r=e==="succeeded"||e===null&&Fh(t)?[]:Cl(n.filter(jl)),i=kl(Oh(t));return{warnings:Cl(i.filter(a=>!jl(a)&&Mh(a))),errors:r}}function kl(t){return t.split(`
|
|
5
|
-
`).map(e=>e.trim()).filter(Boolean)}function Cl(t){return[...new Set(t)]}function Oh(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 Fh(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 Mh(t){return/\bwarnings?\b|overfull|underfull|badness/i.test(t)}const vl=1,El=2,oi=4,li=8,ys=32,Ut=64,nt=128,$h=1<<29,wr=31,Ti=63,pn=127,Ih=2147483647,Dt=(t,e)=>t>>>e|t<<32-e,Ph=t=>Dt(t,2)^Dt(t,13)^Dt(t,22),Uh=t=>Dt(t,6)^Dt(t,11)^Dt(t,25),zh=t=>Dt(t,7)^Dt(t,18)^t>>>3,Bh=t=>Dt(t,17)^Dt(t,19)^t>>>10,Wh=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]),qh=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);class Hh{constructor(){const e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(qh),this._W=new Uint32Array(e,64,64)}_updateHash(){const e=this._H,n=this._W;for(let d=16;d<64;d++)n[d]=Bh(n[d-2])+n[d-7]+zh(n[d-15])+n[d-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 d=0,p,w;d<64;d++)p=f+Uh(a)+(a&c^~a&u)+Wh[d]+n[d]>>>0,w=Ph(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]|=nt<<(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)]|=nt<<(3-n%4)*8),this._W[14]=e.byteLength/$h,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 Vh=t=>new Hh().digest(t);function Kh(t){return Array.from(Vh(new TextEncoder().encode(t)),e=>e.toString(16).padStart(2,"0")).join("")}function Jh(t){return t instanceof Error&&t.name==="AbortError"}function Gh({projectId:t,activeFile:e,content:n,permission:s,revision:r,selection:i,save:l,saveFailureMessage:a,onError:c,onAdded:u,onChanged:f}){const[d,p]=h.useState([]),[w,g]=h.useState(null),[b,x]=h.useState(!1),[_,O]=h.useState(""),[S,V]=h.useState(null),[Y,C]=h.useState(!1),[j,L]=h.useState(""),K=h.useRef(null),X=h.useRef(!1),B=h.useRef(e),P=h.useRef(l),oe=h.useRef(c),D=h.useRef(u),U=h.useRef(f);B.current=e,P.current=l,oe.current=c,D.current=u,U.current=f;const ee=async z=>{K.current?.abort();const se=new AbortController;K.current=se;try{const le=await ce(`/api/projects/${t}/comments?path=${encodeURIComponent(z)}`,{signal:se.signal});B.current===z&&p(le.comments)}catch(le){!Jh(le)&&B.current===z&&p([])}finally{K.current===se&&(K.current=null)}};h.useEffect(()=>{g(null),x(!1),V(null),L("")},[t,e]),h.useEffect(()=>(e?ee(e):p([]),()=>{K.current?.abort(),K.current=null}),[t,e,r]);const te=()=>{e&&(L(""),V({filePath:e,selection:{...i},sourceHash:Kh(n)}),x(!0))},J=()=>{X.current||(x(!1),V(null),L(""))},fe=async()=>{const z=S;if(!(!_.trim()||!z||X.current)){X.current=!0,C(!0),L("");try{if(s!=="read"&&!await P.current()){L(a);return}await ce(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:z.filePath,content:_,...z.selection,sourceHash:z.sourceHash})}),await ee(z.filePath),x(!1),V(null),O(""),D.current(),U.current?.()}catch(se){L(de(se))}finally{X.current=!1,C(!1)}}},ge=async z=>{try{await ce(`/api/projects/${t}/comments/${z.id}`,{method:"PATCH",body:JSON.stringify({resolved:!z.resolved})}),await ee(e),U.current?.()}catch(se){oe.current(de(se))}},ye=async(z,se)=>{try{return await ce(`/api/projects/${t}/comments/${z.id}/replies`,{method:"POST",body:JSON.stringify({content:se})}),await ee(e),U.current?.(),!0}catch(le){return oe.current(de(le)),!1}},T=async(z,se)=>{try{return await ce(`/api/projects/${t}/comments/${z.id}`,{method:"PATCH",body:JSON.stringify({content:se})}),await ee(e),U.current?.(),!0}catch(le){return oe.current(de(le)),!1}},me=async z=>{try{return await ce(`/api/projects/${t}/comments/${z.id}`,{method:"DELETE"}),await ee(e),g(se=>se?.id===z.id?null:se),U.current?.(),!0}catch(se){return oe.current(de(se)),!1}},$=async(z,se,le)=>{try{return await ce(`/api/projects/${t}/comments/${z.id}/replies/${se}`,{method:"PATCH",body:JSON.stringify({content:le})}),await ee(e),U.current?.(),!0}catch(be){return oe.current(de(be)),!1}},M=async(z,se)=>{try{return await ce(`/api/projects/${t}/comments/${z.id}/replies/${se}`,{method:"DELETE"}),await ee(e),U.current?.(),!0}catch(le){return oe.current(de(le)),!1}};return{comments:d,focusComment:w,setFocusComment:g,commentOpen:b,openComment:te,closeComment:J,commentText:_,setCommentText:O,commentSelection:S?.selection??i,commentSubmitting:Y,commentError:j,addComment:fe,toggleComment:ge,replyToComment:ye,editComment:T,deleteComment:me,editCommentReply:$,deleteCommentReply:M}}function Yh(t){return t instanceof Error&&t.name==="AbortError"}function Xh(t,e,n){const[s,r]=h.useState([]),i=h.useRef(null),l=h.useRef(n);l.current=n;const a=h.useCallback(async(f=!1)=>{i.current?.abort();const d=new AbortController;i.current=d;try{const p=await ce(`/api/projects/${t}/mentions?unread=1&limit=100`,{signal:d.signal});i.current===d&&r(p.mentions)}catch(p){i.current===d&&!Yh(p)&&(r([]),f&&l.current(de(p)))}finally{i.current===d&&(i.current=null)}},[t]);return h.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(d=>d.filter(p=>p.id!==f)),!0}catch(d){return l.current(de(d)),!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(de(f)),!1}}}}const it=()=>new Map,Li=t=>{const e=it();return t.forEach((n,s)=>{e.set(s,n)}),e},Lt=(t,e,n)=>{let s=t.get(e);return s===void 0&&t.set(e,s=n()),s},Qh=(t,e)=>{const n=[];for(const[s,r]of t)n.push(e(r,s));return n},Zh=(t,e)=>{for(const[n,s]of t)if(e(s,n))return!0;return!1},Qt=()=>new Set,ai=t=>t[t.length-1],ef=(t,e)=>{for(let n=0;n<e.length;n++)t.push(e[n])},zt=Array.from,Ji=(t,e)=>{for(let n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0},Gi=(t,e)=>{for(let n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1},tf=(t,e)=>{const n=new Array(t);for(let s=0;s<t;s++)n[s]=e(s,n);return n},qn=Array.isArray;class Yi{constructor(){this._observers=it()}on(e,n){return Lt(this._observers,e,Qt).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 zt((this._observers.get(e)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}class Sa{constructor(){this._observers=it()}on(e,n){Lt(this._observers,e,Qt).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 zt((this._observers.get(e)||it()).values()).forEach(s=>s(...n))}destroy(){this._observers=it()}}const St=Math.floor,Ks=Math.abs,Xi=(t,e)=>t<e?t:e,bn=(t,e)=>t>e?t:e,nf=Math.pow,ka=t=>t!==0?t<0:1/t<0,nr=Number.MAX_SAFE_INTEGER,Dl=Number.MIN_SAFE_INTEGER,sf=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&St(t)===t),Ca=String.fromCharCode,rf=t=>t.toLowerCase(),of=/^\s*/g,lf=t=>t.replace(of,""),af=/([A-Z])/g,_l=(t,e)=>lf(t.replace(af,n=>`${e}${rf(n)}`)),cf=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},bs=typeof TextEncoder<"u"?new TextEncoder:null,uf=t=>bs.encode(t),df=bs?uf:cf;let ms=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ms&&ms.decode(new Uint8Array).length===1&&(ms=null);const hf=(t,e)=>tf(e,()=>t).join("");class _s{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Fe=()=>new _s,Qi=t=>{let e=t.cpos;for(let n=0;n<t.bufs.length;n++)e+=t.bufs[n].length;return e},Se=t=>{const e=new Uint8Array(Qi(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},ff=(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(bn(n,e)*2),t.cpos=0)},He=(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},Ri=He,q=(t,e)=>{for(;e>pn;)He(t,nt|pn&e),e=St(e/128);He(t,pn&e)},Zi=(t,e)=>{const n=ka(e);for(n&&(e=-e),He(t,(e>Ti?nt:0)|(n?Ut:0)|Ti&e),e=St(e/64);e>0;)He(t,(e>pn?nt:0)|pn&e),e=St(e/128)},Ai=new Uint8Array(3e4),pf=Ai.length/3,mf=(t,e)=>{if(e.length<pf){const n=bs.encodeInto(e,Ai).written||0;q(t,n);for(let s=0;s<n;s++)He(t,Ai[s])}else Oe(t,df(e))},gf=(t,e)=>{const n=unescape(encodeURIComponent(e)),s=n.length;q(t,s);for(let r=0;r<s;r++)He(t,n.codePointAt(r))},Ye=bs&&bs.encodeInto?mf:gf,yr=(t,e)=>{const n=t.cbuf.length,s=t.cpos,r=Xi(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(bn(n*2,i)),t.cbuf.set(e.subarray(r)),t.cpos=i)},Oe=(t,e)=>{q(t,e.byteLength),yr(t,e)},eo=(t,e)=>{ff(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},wf=(t,e)=>eo(t,4).setFloat32(0,e,!1),yf=(t,e)=>eo(t,8).setFloat64(0,e,!1),bf=(t,e)=>eo(t,8).setBigInt64(0,e,!1),Tl=new DataView(new ArrayBuffer(4)),xf=t=>(Tl.setFloat32(0,t),Tl.getFloat32(0)===t),xs=(t,e)=>{switch(typeof e){case"string":He(t,119),Ye(t,e);break;case"number":sf(e)&&Ks(e)<=Ih?(He(t,125),Zi(t,e)):xf(e)?(He(t,124),wf(t,e)):(He(t,123),yf(t,e));break;case"bigint":He(t,122),bf(t,e);break;case"object":if(e===null)He(t,126);else if(qn(e)){He(t,117),q(t,e.length);for(let n=0;n<e.length;n++)xs(t,e[n])}else if(e instanceof Uint8Array)He(t,116),Oe(t,e);else{He(t,118);const n=Object.keys(e);q(t,n.length);for(let s=0;s<n.length;s++){const r=n[s];Ye(t,r),xs(t,e[r])}}break;case"boolean":He(t,e?120:121);break;default:He(t,127)}};class Ll extends _s{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&q(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Rl=t=>{t.count>0&&(Zi(t.encoder,t.count===1?t.s:-t.s),t.count>1&&q(t.encoder,t.count-2))};class Js{constructor(){this.encoder=new _s,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Rl(this),this.count=1,this.s=e)}toUint8Array(){return Rl(this),Se(this.encoder)}}const Al=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Zi(t.encoder,e),t.count>1&&q(t.encoder,t.count-2)}};class ci{constructor(){this.encoder=new _s,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Al(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Al(this),Se(this.encoder)}}class Sf{constructor(){this.sarr=[],this.s="",this.lensE=new Js}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 _s;return this.sarr.push(this.s),this.s="",Ye(e,this.sarr.join("")),yr(e,this.lensE.toUint8Array()),Se(e)}}const kt=t=>new Error(t),xt=()=>{throw kt("Method unimplemented")},ut=()=>{throw kt("Unexpected case")},ja=kt("Unexpected end of array"),va=kt("Integer out of Range");class br{constructor(e){this.arr=e,this.pos=0}}const tn=t=>new br(t),Ni=t=>t.pos!==t.arr.length,kf=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},Qe=t=>kf(t,re(t)),Hn=t=>t.arr[t.pos++],re=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&pn)*n,n*=128,r<nt)return e;if(e>nr)throw va}throw ja},to=t=>{let e=t.arr[t.pos++],n=e&Ti,s=64;const r=(e&Ut)>0?-1:1;if((e&nt)===0)return r*n;const i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],n=n+(e&pn)*s,s*=128,e<nt)return r*n;if(n>nr)throw va}throw ja},Cf=t=>{let e=re(t);if(e===0)return"";{let n=String.fromCodePoint(Hn(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(Hn(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))}},jf=t=>ms.decode(Qe(t)),_e=ms?jf:Cf,no=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},vf=t=>no(t,4).getFloat32(0,!1),Ef=t=>no(t,8).getFloat64(0,!1),Df=t=>no(t,8).getBigInt64(0,!1),_f=[t=>{},t=>null,to,vf,Ef,Df,t=>!1,t=>!0,_e,t=>{const e=re(t),n={};for(let s=0;s<e;s++){const r=_e(t);n[r]=Ss(t)}return n},t=>{const e=re(t),n=[];for(let s=0;s<e;s++)n.push(Ss(t));return n},Qe],Ss=t=>_f[127-Hn(t)](t);class Nl extends br{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Ni(this)?this.count=re(this)+1:this.count=-1),this.count--,this.s}}class Gs extends br{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=to(this);const e=ka(this.s);this.count=1,e&&(this.s=-this.s,this.count=re(this)+2)}return this.count--,this.s}}class ui extends br{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=to(this),n=e&1;this.diff=St(e/2),this.count=1,n&&(this.count=re(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Tf{constructor(e){this.decoder=new Gs(e),this.str=_e(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 Lf=crypto.getRandomValues.bind(crypto),Ea=()=>Lf(new Uint32Array(1))[0],Rf="10000000-1000-4000-8000"+-1e11,Af=()=>Rf.replace(/[018]/g,t=>(t^Ea()&15>>t/4).toString(16)),Zt=Date.now,Vn=t=>new Promise(t);Promise.all.bind(Promise);const Ol=t=>t===void 0?null:t;class Nf{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let Da=new Nf,so=!0;try{typeof localStorage<"u"&&localStorage&&(Da=localStorage,so=!1)}catch{}const _a=Da,Of=t=>so||addEventListener("storage",t),Ff=t=>so||removeEventListener("storage",t),ks=Symbol("Equality"),Ta=(t,e)=>t===e||!!t?.[ks]?.(e)||!1,Mf=t=>typeof t=="object",$f=Object.assign,If=Object.keys,Pf=(t,e)=>{for(const n in t)e(t[n],n)},Uf=(t,e)=>{const n=[];for(const s in t)n.push(e(t[s],s));return n},sr=t=>If(t).length,zf=t=>{for(const e in t)return!1;return!0},Ts=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},ro=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Bf=(t,e)=>t===e||sr(t)===sr(e)&&Ts(t,(n,s)=>(n!==void 0||ro(e,s))&&Ta(e[s],n)),Wf=Object.freeze,La=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&La(t[e])}return Wf(t)},io=(t,e,n=0)=>{try{for(;n<t.length;n++)t[n](...e)}finally{n<t.length&&io(t,e,n+1)}},qf=t=>t,Fn=(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[ks]!=null)return t[ks](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)||!Fn(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(sr(t)!==sr(e))return!1;for(const n in t)if(!ro(t,n)||!Fn(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(!Fn(t[n],e[n]))return!1;break;default:return!1}return!0},Hf=(t,e)=>e.includes(t);var Ra={};const en=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Aa=typeof window<"u"&&typeof document<"u"&&!en;let Et;const Vf=()=>{if(Et===void 0)if(en){Et=it();const t=process.argv;let e=null;for(let n=0;n<t.length;n++){const s=t[n];s[0]==="-"?(e!==null&&Et.set(e,""),e=s):e!==null&&(Et.set(e,s),e=null)}e!==null&&Et.set(e,"")}else typeof location=="object"?(Et=it(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,n]=t.split("=");Et.set(`--${_l(e,"-")}`,n),Et.set(`-${_l(e,"-")}`,n)}})):Et=it();return Et},Oi=t=>Vf().has(t),rr=t=>Ol(en?Ra[t.toUpperCase().replaceAll("-","_")]:_a.getItem(t)),Na=t=>Oi("--"+t)||rr(t)!==null,Kf=Na("production"),Jf=en&&Hf(Ra.FORCE_COLOR,["true","1","2"]),Gf=Jf||!Oi("--no-colors")&&!Na("no-color")&&(!en||process.stdout.isTTY)&&(!en||Oi("--color")||rr("COLORTERM")!==null||(rr("TERM")||"").includes("color")),Oa=t=>new Uint8Array(t),Yf=(t,e,n)=>new Uint8Array(t,e,n),Xf=t=>new Uint8Array(t),Qf=t=>{let e="";for(let n=0;n<t.byteLength;n++)e+=Ca(t[n]);return btoa(e)},Zf=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),ep=t=>{const e=atob(t),n=Oa(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n},tp=t=>{const e=Buffer.from(t,"base64");return Yf(e.buffer,e.byteOffset,e.byteLength)},np=Aa?Qf:Zf,sp=Aa?ep:tp,rp=t=>{const e=Oa(t.byteLength);return e.set(t),e};class ip{constructor(e,n){this.left=e,this.right=n}}const $t=(t,e)=>new ip(t,e),op=(t,e)=>t.forEach(n=>e(n.left,n.right)),Fl=t=>t.next()>=.5,di=(t,e,n)=>St(t.next()*(n+1-e)+e),Fa=(t,e,n)=>St(t.next()*(n+1-e)+e),oo=(t,e,n)=>Fa(t,e,n),lp=t=>Ca(oo(t,97,122)),ap=(t,e=0,n=20)=>{const s=oo(t,e,n);let r="";for(let i=0;i<s;i++)r+=lp(t);return r},hi=(t,e)=>e[oo(t,0,e.length-1)],cp=Symbol("0schema");class up{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(hf(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return e.join(`
|
|
6
|
-
`)}}const Fi=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[ks]?Ta(t,e):qn(t)?Ji(t,n=>Gi(e,s=>Fi(n,s))):Mf(t)?Ts(t,(n,s)=>Fi(n,e[s])):!1;class st{static _dilutes=!1;extends(e){let[n,s]=[this.shape,e.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Fi(n,s)}equals(e){return this.constructor===e.constructor&&Fn(this.shape,e.shape)}[cp](){return!0}[ks](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){xt()}get nullable(){return Zn(this,jr)}get optional(){return new Ia(this)}cast(e){return Ml(e,this),e}expect(e){return Ml(e,this),e}}class lo extends st{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 ze=(t,e=null)=>new lo(t,e);ze(lo);class ao extends st{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 Je=t=>new ao(t);ze(ao);class xr extends st{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 Sr=(...t)=>new xr(t),Ma=ze(xr),dp=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),$a=t=>{if(Kn.check(t))return[dp(t)];if(Ma.check(t))return t.shape.map(e=>e+"");if(Ka.check(t))return["[+-]?\\d+.?\\d*"];if(Ja.check(t))return[".*"];if(ir.check(t))return t.shape.map($a).flat(1);ut()};class hp extends st{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map($a).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}}ze(hp);const fp=Symbol("optional");class Ia extends st{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[fp](){return!0}}const pp=ze(Ia);class mp extends st{check(e,n){return n?.extend(null,"never",typeof e),!1}}ze(mp);class kr extends st{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}static _dilutes=!0;get partial(){return new kr(this.shape,!0)}check(e,n){return e==null?(n?.extend(null,"object","null"),!1):Ts(this.shape,(s,r)=>{const i=this._isPartial&&!ro(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 gp=t=>new kr(t),wp=ze(kr),yp=Je(t=>t!=null&&(t.constructor===Object||t.constructor==null));class Pa extends st{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&Ts(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 Ua=(t,e)=>new Pa(t,e),bp=ze(Pa);class za extends st{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&Ts(this.shape,(s,r)=>{const i=s.check(e[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const xp=(...t)=>new za(t);ze(za);class Ba extends st{constructor(e){super(),this.shape=e.length===1?e[0]:new co(e)}check(e,n){const s=qn(e)&&Ji(e,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Wa=(...t)=>new Ba(t),Sp=ze(Ba),kp=Je(t=>qn(t));class qa extends st{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 Cp=(t,e=null)=>new qa(t,e);ze(qa);const jp=Cp(st);class vp extends st{constructor(e){super(),this.len=e.length-1,this.args=xp(...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 Ep=ze(vp),Dp=Je(t=>typeof t=="function");class _p extends st{constructor(e){super(),this.shape=e}check(e,n){const s=Ji(this.shape,r=>r.check(e,n));return!s&&n?.extend(null,"Intersectinon",typeof e),s}}ze(_p,t=>t.shape.length>0);class co extends st{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,n){const s=Gi(this.shape,r=>r.check(e,n));return n?.extend(null,"Union",typeof e),s}}const Zn=(...t)=>t.findIndex(e=>ir.check(e))>=0?Zn(...t.map(e=>Cs(e)).map(e=>ir.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new co(t),ir=ze(co),Ha=()=>!0,or=Je(Ha),Tp=ze(ao,t=>t.shape===Ha),uo=Je(t=>typeof t=="bigint"),Lp=Je(t=>t===uo),Va=Je(t=>typeof t=="symbol");Je(t=>t===Va);const Mn=Je(t=>typeof t=="number"),Ka=Je(t=>t===Mn),Kn=Je(t=>typeof t=="string"),Ja=Je(t=>t===Kn),Cr=Je(t=>typeof t=="boolean"),Rp=Je(t=>t===Cr),Ga=Sr(void 0);ze(xr,t=>t.shape.length===1&&t.shape[0]===void 0);Sr(void 0);const jr=Sr(null),Ap=ze(xr,t=>t.shape.length===1&&t.shape[0]===null);ze(Uint8Array);ze(lo,t=>t.shape===Uint8Array);const Np=Zn(Mn,Kn,jr,Ga,uo,Cr,Va);(()=>{const t=Wa(or),e=Ua(Kn,or),n=Zn(Mn,Kn,jr,Cr,t,e);return t.shape=n,e.shape.values=n,n})();const Cs=t=>{if(jp.check(t))return t;if(yp.check(t)){const e={};for(const n in t)e[n]=Cs(t[n]);return gp(e)}else{if(kp.check(t))return Zn(...t.map(Cs));if(Np.check(t))return Sr(t);if(Dp.check(t))return ze(t)}ut()},Ml=Kf?()=>{}:(t,e)=>{const n=new up;if(!e.check(t,n))throw kt(`Expected value to be of type ${e.constructor.name}.
|
|
7
|
-
${n.toString()}`)};class Op{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:Cs(e),h:n}),this}else(e){return this.if(or,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 kt("Unhandled pattern")}}}const Fp=t=>new Op(t),Ya=Fp(or).if(Ka,(t,e)=>di(e,Dl,nr)).if(Ja,(t,e)=>ap(e)).if(Rp,(t,e)=>Fl(e)).if(Lp,(t,e)=>BigInt(di(e,Dl,nr))).if(ir,(t,e)=>Ln(e,hi(e,t.shape))).if(wp,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(pp.check(r)){if(Fl(e))continue;r=r.shape}n[s]=Ya(r,e)}return n}).if(Sp,(t,e)=>{const n=[],s=Fa(e,0,42);for(let r=0;r<s;r++)n.push(Ln(e,t.shape));return n}).if(Ma,(t,e)=>hi(e,t.shape)).if(Ap,(t,e)=>null).if(Ep,(t,e)=>{const n=Ln(e,t.res);return()=>n}).if(Tp,(t,e)=>Ln(e,hi(e,[Mn,Kn,jr,Ga,uo,Cr,Wa(Mn),Ua(Zn("a","b","c"),Mn)]))).if(bp,(t,e)=>{const n={},s=di(e,0,3);for(let r=0;r<s;r++){const i=Ln(e,t.shape.keys),l=Ln(e,t.shape.values);n[i]=l}return n}).done(),Ln=(t,e)=>Ya(Cs(e),t),Rt=typeof document<"u"?document:{},Mp=t=>Rt.createElement(t),$p=()=>Rt.createDocumentFragment();Je(t=>t.nodeType===Vp);const Ip=t=>Rt.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const Pp=(t,e)=>(op(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),Up=t=>{const e=$p();for(let n=0;n<t.length;n++)Xa(e,t[n]);return e},zp=(t,e)=>(Xa(t,Up(e)),t),gy=(t,e=[],n=[])=>zp(Pp(Mp(t),e),n);Je(t=>t.nodeType===Wp);const wy=Ip;Je(t=>t.nodeType===qp);const Bp=t=>Qh(t,(e,n)=>`${n}:${e};`).join(""),Xa=(t,e)=>t.appendChild(e),Wp=Rt.ELEMENT_NODE,qp=Rt.TEXT_NODE;Rt.CDATA_SECTION_NODE;Rt.COMMENT_NODE;const Hp=Rt.DOCUMENT_NODE;Rt.DOCUMENT_TYPE_NODE;const Vp=Rt.DOCUMENT_FRAGMENT_NODE;Je(t=>t.nodeType===Hp);const Bt=Symbol,Qa=Bt(),Za=Bt(),Kp=Bt(),Jp=Bt(),Gp=Bt(),ec=Bt(),Yp=Bt(),ho=Bt(),Xp=Bt(),Qp=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},Zp={[Qa]:$t("font-weight","bold"),[Za]:$t("font-weight","normal"),[Kp]:$t("color","blue"),[Gp]:$t("color","green"),[Jp]:$t("color","grey"),[ec]:$t("color","red"),[Yp]:$t("color","purple"),[ho]:$t("color","orange"),[Xp]:$t("color","black")},em=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=it();let r=[],i=0;for(;i<t.length;i++){const l=t[i],a=Zp[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=Bp(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},tc=Gf?em:Qp,tm=(...t)=>{console.log(...tc(t)),sc.forEach(e=>e.print(t))},nc=(...t)=>{console.warn(...tc(t)),t.unshift(ho),sc.forEach(e=>e.print(t))},sc=Qt(),rc=t=>({[Symbol.iterator](){return this},next:t}),nm=(t,e)=>rc(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),fi=(t,e)=>rc(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class vr{constructor(e,n){this.clock=e,this.len=n}}class es{constructor(){this.clients=new Map}}const Jn=(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])bc(t,i,u.clock,u.len,n)}}),sm=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=St((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},Ls=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&sm(n,e.clock)!==null},fo=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 vr(r.clock,bn(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},Mi=t=>{const e=new es;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++)ef(i,t[l].clients.get(r)||[]);e.clients.set(r,i)}});return fo(e),e},js=(t,e,n,s)=>{Lt(t.clients,e,()=>[]).push(new vr(n,s))},rm=()=>new es,im=t=>{const e=rm();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 vr(a,c))}}r.length>0&&e.clients.set(s,r)}),e},ts=(t,e)=>{q(t.restEncoder,e.clients.size),zt(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),q(t.restEncoder,n);const r=s.length;q(t.restEncoder,r);for(let i=0;i<r;i++){const l=s[i];t.writeDsClock(l.clock),t.writeDsLen(l.len)}})},po=t=>{const e=new es,n=re(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=re(t.restDecoder),i=re(t.restDecoder);if(i>0){const l=Lt(e.clients,r,()=>[]);for(let a=0;a<i;a++)l.push(new vr(t.readDsClock(),t.readDsLen()))}}return e},$l=(t,e,n)=>{const s=new es,r=re(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const l=re(t.restDecoder),a=re(t.restDecoder),c=n.clients.get(l)||[],u=$e(n,l);for(let f=0;f<a;f++){const d=t.readDsClock(),p=d+t.readDsLen();if(d<u){u<p&&js(s,l,u,p-u);let w=_t(c,d),g=c[w];for(!g.deleted&&g.id.clock<d&&(c.splice(w+1,0,pr(e,g,d-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,pr(e,g,p-g.id.clock)),g.delete(e))}else js(s,l,d,p-d)}}if(s.clients.size>0){const i=new gn;return q(i.restEncoder,0),ts(i,s),i.toUint8Array()}return null},ic=Ea;class xn extends Yi{constructor({guid:e=Af(),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=ic(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new wc,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=Vn(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>Vn(u=>{const f=d=>{(d===void 0||d===!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&&ke(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(zt(this.subdocs).map(e=>e.guid))}transact(e,n=null){return ke(this,e,n)}get(e,n=Ve){const s=Lt(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==Ve&&r!==n)if(r===Ve){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,Pn)}getText(e=""){return this.get(e,Xn)}getMap(e=""){return this.get(e,Yn)}getXmlElement(e=""){return this.get(e,Qn)}getXmlFragment(e=""){return this.get(e,wn)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,zt(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new xn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,ke(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 oc{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return re(this.restDecoder)}readDsLen(){return re(this.restDecoder)}}class lc extends oc{readLeftID(){return ue(re(this.restDecoder),re(this.restDecoder))}readRightID(){return ue(re(this.restDecoder),re(this.restDecoder))}readClient(){return re(this.restDecoder)}readInfo(){return Hn(this.restDecoder)}readString(){return _e(this.restDecoder)}readParentInfo(){return re(this.restDecoder)===1}readTypeRef(){return re(this.restDecoder)}readLen(){return re(this.restDecoder)}readAny(){return Ss(this.restDecoder)}readBuf(){return rp(Qe(this.restDecoder))}readJSON(){return JSON.parse(_e(this.restDecoder))}readKey(){return _e(this.restDecoder)}}class om{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=re(this.restDecoder),this.dsCurrVal}readDsLen(){const e=re(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Gn extends om{constructor(e){super(e),this.keys=[],re(e),this.keyClockDecoder=new ui(Qe(e)),this.clientDecoder=new Gs(Qe(e)),this.leftClockDecoder=new ui(Qe(e)),this.rightClockDecoder=new ui(Qe(e)),this.infoDecoder=new Nl(Qe(e),Hn),this.stringDecoder=new Tf(Qe(e)),this.parentInfoDecoder=new Nl(Qe(e),Hn),this.typeRefDecoder=new Gs(Qe(e)),this.lenDecoder=new Gs(Qe(e))}readLeftID(){return new $n(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new $n(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 Ss(this.restDecoder)}readBuf(){return Qe(this.restDecoder)}readJSON(){return Ss(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 ac{constructor(){this.restEncoder=Fe()}toUint8Array(){return Se(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){q(this.restEncoder,e)}writeDsLen(e){q(this.restEncoder,e)}}class Rs extends ac{writeLeftID(e){q(this.restEncoder,e.client),q(this.restEncoder,e.clock)}writeRightID(e){q(this.restEncoder,e.client),q(this.restEncoder,e.clock)}writeClient(e){q(this.restEncoder,e)}writeInfo(e){Ri(this.restEncoder,e)}writeString(e){Ye(this.restEncoder,e)}writeParentInfo(e){q(this.restEncoder,e?1:0)}writeTypeRef(e){q(this.restEncoder,e)}writeLen(e){q(this.restEncoder,e)}writeAny(e){xs(this.restEncoder,e)}writeBuf(e){Oe(this.restEncoder,e)}writeJSON(e){Ye(this.restEncoder,JSON.stringify(e))}writeKey(e){Ye(this.restEncoder,e)}}class cc{constructor(){this.restEncoder=Fe(),this.dsCurrVal=0}toUint8Array(){return Se(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,q(this.restEncoder,n)}writeDsLen(e){e===0&&ut(),q(this.restEncoder,e-1),this.dsCurrVal+=e}}class gn extends cc{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new ci,this.clientEncoder=new Js,this.leftClockEncoder=new ci,this.rightClockEncoder=new ci,this.infoEncoder=new Ll(Ri),this.stringEncoder=new Sf,this.parentInfoEncoder=new Ll(Ri),this.typeRefEncoder=new Js,this.lenEncoder=new Js}toUint8Array(){const e=Fe();return q(e,0),Oe(e,this.keyClockEncoder.toUint8Array()),Oe(e,this.clientEncoder.toUint8Array()),Oe(e,this.leftClockEncoder.toUint8Array()),Oe(e,this.rightClockEncoder.toUint8Array()),Oe(e,Se(this.infoEncoder)),Oe(e,this.stringEncoder.toUint8Array()),Oe(e,Se(this.parentInfoEncoder)),Oe(e,this.typeRefEncoder.toUint8Array()),Oe(e,this.lenEncoder.toUint8Array()),yr(e,Se(this.restEncoder)),Se(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){xs(this.restEncoder,e)}writeBuf(e){Oe(this.restEncoder,e)}writeJSON(e){xs(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 lm=(t,e,n,s)=>{s=bn(s,e[0].id.clock);const r=_t(e,s);q(t.restEncoder,e.length-r),t.writeClient(n),q(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)},mo=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{$e(e,i)>r&&s.set(i,r)}),Er(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),q(t.restEncoder,s.size),zt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{lm(t,e.clients.get(r),r,i)})},am=(t,e)=>{const n=it(),s=re(t.restDecoder);for(let r=0;r<s;r++){const i=re(t.restDecoder),l=new Array(i),a=t.readClient();let c=re(t.restDecoder);n.set(a,{i:0,refs:l});for(let u=0;u<i;u++){const f=t.readInfo();switch(wr&f){case 0:{const d=t.readLen();l[u]=new mt(ue(a,c),d),c+=d;break}case 10:{const d=re(t.restDecoder);l[u]=new gt(ue(a,c),d),c+=d;break}default:{const d=(f&(Ut|nt))===0,p=new je(ue(a,c),null,(f&nt)===nt?t.readLeftID():null,null,(f&Ut)===Ut?t.readRightID():null,d?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,d&&(f&ys)===ys?t.readString():null,Pc(t,f));l[u]=p,c+=p.length}}}}return n},cm=(t,e,n)=>{const s=[];let r=zt(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 wc,c=new Map,u=(w,g)=>{const b=c.get(w);(b==null||b>g)&&c.set(w,g)};let f=l.refs[l.i++];const d=new Map,p=()=>{for(const w of s){const g=w.id.client,b=n.get(g);b?(b.i--,a.clients.set(g,b.refs.slice(b.i)),n.delete(g),b.i=0,b.refs=[]):a.clients.set(g,[w]),r=r.filter(x=>x!==g)}s.length=0};for(;;){if(f.constructor!==gt){const g=Lt(d,f.id.client,()=>$e(e,f.id.client))-f.id.clock;if(g<0)s.push(f),u(f.id.client,f.id.clock-1),p();else{const b=f.getMissing(t,e);if(b!==null){s.push(f);const x=n.get(b)||{refs:[],i:0};if(x.refs.length===x.i)u(b,$e(e,b)),p();else{f=x.refs[x.i++];continue}}else(g===0||g<f.length)&&(f.integrate(t,g),d.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 gn;return mo(w,a,new Map),q(w.restEncoder,0),{missing:c,update:w.toUint8Array()}}return null},um=(t,e)=>mo(t,e.doc.store,e.beforeState),dm=(t,e,n,s=new Gn(t))=>ke(e,r=>{r.local=!1;let i=!1;const l=r.doc,a=l.store,c=am(s,l),u=cm(r,a,c),f=a.pendingStructs;if(f){for(const[p,w]of f.missing)if(w<$e(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=ar([f.update,u.update])}}else a.pendingStructs=u;const d=$l(s,r,a);if(a.pendingDs){const p=new Gn(tn(a.pendingDs));re(p.restDecoder);const w=$l(p,r,a);d&&w?a.pendingDs=ar([d,w]):a.pendingDs=d||w}else a.pendingDs=d;if(i){const p=a.pendingStructs.update;a.pendingStructs=null,uc(r.doc,p)}},n,!1),uc=(t,e,n,s=Gn)=>{const r=tn(e);dm(r,t,n,new s(r))},dc=(t,e,n)=>uc(t,e,n,lc),hm=(t,e,n=new Map)=>{mo(t,e.store,n),ts(t,im(e.store))},fm=(t,e=new Uint8Array([0]),n=new gn)=>{const s=hc(e);hm(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(Am(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===Rs)return Lm(r.map((i,l)=>l===0?i:Om(i)));if(n.constructor===gn)return ar(r)}return r[0]},go=(t,e)=>fm(t,e,new Rs),pm=t=>{const e=new Map,n=re(t.restDecoder);for(let s=0;s<n;s++){const r=re(t.restDecoder),i=re(t.restDecoder);e.set(r,i)}return e},hc=t=>pm(new oc(tn(t))),fc=(t,e)=>(q(t.restEncoder,e.size),zt(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{q(t.restEncoder,n),q(t.restEncoder,s)}),t),mm=(t,e)=>fc(t,Er(e.store)),gm=(t,e=new cc)=>(t instanceof Map?fc(e,t):mm(e,t),e.toUint8Array()),wm=t=>gm(t,new ac);class ym{constructor(){this.l=[]}}const Il=()=>new ym,Pl=(t,e)=>t.l.push(e),Ul=(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.")},pc=(t,e,n)=>io(t.l,[e,n]);class $n{constructor(e,n){this.client=e,this.clock=n}}const Nn=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,ue=(t,e)=>new $n(t,e),mc=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw ut()},lr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class gc{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const yy=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},by=t=>new gc(t.type==null?null:ue(t.type.client,t.type.clock),t.tname??null,t.item==null?null:ue(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class bm{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const xm=(t,e,n=0)=>new bm(t,e,n),Ws=(t,e,n)=>{let s=null,r=null;return t._item===null?r=mc(t):s=ue(t._item.id.client,t._item.id.clock),new gc(s,r,e,n)},xy=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return Ws(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return Ws(t,ue(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return Ws(t,s.lastId,n);s=s.right}return Ws(t,null,n)},Sm=(t,e)=>{const n=In(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},Sy=(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($e(s,r.client)<=r.clock)return null;const f=n?Ui(s,r):Sm(s,r),d=f.item;if(!(d instanceof je))return null;if(c=d.parent,c._item===null||!c._item.deleted){u=d.deleted||!d.countable?0:f.diff+(a>=0?0:1);let p=d.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($e(s,i.client)<=i.clock)return null;const{item:f}=n?Ui(s,i):{item:In(s,i)};if(f instanceof je&&f.content instanceof At)c=f.content.type;else return null}else throw ut();a>=0?u=c._length:u=0}return xm(c,u,t.assoc)},ky=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&Nn(t.item,e.item)&&Nn(t.type,e.type)&&t.assoc===e.assoc,Rn=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Ls(e.ds,t.id),$i=(t,e)=>{const n=Lt(t.meta,$i,Qt),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<$e(s,i)&&rt(t,ue(i,r))}),Jn(t,e.ds,r=>{}),n.add(e))};class wc{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Er=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},$e=(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},yc=(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 ut()}n.push(e)},_t=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let l=St(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=St((n+s)/2)}throw ut()},km=(t,e)=>{const n=t.clients.get(e.client);return n[_t(n,e.clock)]},In=km,Ii=(t,e,n)=>{const s=_t(e,n),r=e[s];return r.id.clock<n&&r instanceof je?(e.splice(s+1,0,pr(t,r,n-r.id.clock)),s+1):s},rt=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[Ii(t,n,e.clock)]},zl=(t,e,n)=>{const s=e.clients.get(n.client),r=_t(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==mt&&s.splice(r+1,0,pr(t,i,n.clock-i.id.clock+1)),i},Cm=(t,e,n)=>{const s=t.clients.get(e.id.client);s[_t(s,e.id.clock)]=n},bc=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let l=Ii(t,e,n),a;do a=e[l++],i<a.id.clock+a.length&&Ii(t,e,i),r(a);while(l<e.length&&e[l].id.clock<i)};class jm{constructor(e,n,s){this.doc=e,this.deleteSet=new es,this.beforeState=Er(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 Bl=(t,e)=>e.deleteSet.clients.size===0&&!Zh(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(fo(e.deleteSet),um(t,e),ts(t,e.deleteSet),!0),Wl=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&Lt(t.changed,e,Qt).add(n)},Ys=(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 je&&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},vm=(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=_t(i,a.clock),f=i[u];u<i.length&&f.id.clock<c;f=i[++u]){const d=i[u];if(a.clock+a.len<=d.id.clock)break;d instanceof je&&d.deleted&&!d.keep&&n(d)&&d.gc(e,!1)}}}},Em=(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=Xi(r.length-1,1+_t(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+Ys(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{fo(i),n.afterState=Er(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,d)=>f.path.length-d.path.length),a.push(()=>{pc(u._dEH,c,n)}))}),a.push(()=>s.emit("afterTransaction",[n,s])),a.push(()=>{n._needFormattingCleanup&&Jm(n)})}),io(a,[])}finally{s.gc&&vm(i,r,s.gcFilter),Em(i,r),n.afterState.forEach((f,d)=>{const p=n.beforeState.get(d)||0;if(p!==f){const w=r.clients.get(d),g=bn(_t(w,p),1);for(let b=w.length-1;b>=g;)b-=1+Ys(w,b)}});for(let f=l.length-1;f>=0;f--){const{client:d,clock:p}=l[f].id,w=r.clients.get(d),g=_t(w,p);g+1<w.length&&Ys(w,g+1)>1||g>0&&Ys(w,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(tm(ho,Qa,"[yjs] ",Za,ec,"Changed the client-id because another client seems to be using it."),s.clientID=ic()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const f=new Rs;Bl(f,n)&&s.emit("update",[f.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const f=new gn;Bl(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)}}},ke=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,l=null;t._transaction===null&&(i=!0,t._transaction=new jm(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 Dm{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const ql=(t,e,n)=>{Jn(t,n.deletions,s=>{s instanceof je&&e.scope.some(r=>r===t.doc||lr(r,s))&&jo(s,!1)})},Hl=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;ke(r,a=>{for(;e.length>0&&t.currStackItem===null;){const c=r.store,u=e.pop(),f=new Set,d=[];let p=!1;Jn(a,u.insertions,w=>{if(w instanceof je){if(w.redone!==null){let{item:g,diff:b}=Ui(c,w.id);b>0&&(g=rt(a,ue(g.id.client,g.id.clock+b))),w=g}!w.deleted&&i.some(g=>g===a.doc||lr(g,w))&&d.push(w)}}),Jn(a,u.deletions,w=>{w instanceof je&&i.some(g=>g===a.doc||lr(g,w))&&!Ls(u.insertions,w.id)&&f.add(w)}),f.forEach(w=>{p=Ic(a,w,f,u.insertions,t.ignoreRemoteMapChanges,t)!==null||p});for(let w=d.length-1;w>=0;w--){const g=d[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 _m extends Yi{constructor(e,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:l=!1,doc:a=qn(e)?e[0].doc:e instanceof xn?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(x=>c.changedParentTypes.has(x)||x===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,f=this.redoing,d=u?this.redoStack:this.undoStack;u?this.stopCapturing():f||this.clear(!1,!0);const p=new es;c.afterState.forEach((x,_)=>{const O=c.beforeState.get(_)||0,S=x-O;S>0&&js(p,_,O,S)});const w=Zt();let g=!1;if(this.lastChange>0&&w-this.lastChange<this.captureTimeout&&d.length>0&&!u&&!f){const x=d[d.length-1];x.deletions=Mi([x.deletions,c.deleteSet]),x.insertions=Mi([x.insertions,p])}else d.push(new Dm(c.deleteSet,p)),g=!0;!u&&!f&&(this.lastChange=w),Jn(c,c.deleteSet,x=>{x instanceof je&&this.scope.some(_=>_===c.doc||lr(_,x))&&jo(x,!0)});const b=[{stackItem:d[d.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",b):this.emit("stack-item-updated",b)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=qn(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof Ve?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=>ql(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>ql(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=Hl(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Hl(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*Tm(t){const e=re(t.restDecoder);for(let n=0;n<e;n++){const s=re(t.restDecoder),r=t.readClient();let i=re(t.restDecoder);for(let l=0;l<s;l++){const a=t.readInfo();if(a===10){const c=re(t.restDecoder);yield new gt(ue(r,i),c),i+=c}else if((wr&a)!==0){const c=(a&(Ut|nt))===0,u=new je(ue(r,i),null,(a&nt)===nt?t.readLeftID():null,null,(a&Ut)===Ut?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(a&ys)===ys?t.readString():null,Pc(t,a));yield u,i+=u.length}else{const c=t.readLen();yield new mt(ue(r,i),c),i+=c}}}}class wo{constructor(e,n){this.gen=Tm(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===gt);return this.curr}}class yo{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Lm=t=>ar(t,lc,Rs),Rm=(t,e)=>{if(t.constructor===mt){const{client:n,clock:s}=t.id;return new mt(ue(n,s+e),t.length-e)}else if(t.constructor===gt){const{client:n,clock:s}=t.id;return new gt(ue(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new je(ue(s,r+e),null,ue(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},ar=(t,e=Gn,n=gn)=>{if(t.length===1)return t[0];const s=t.map(f=>new e(tn(f)));let r=s.map(f=>new wo(f,!0)),i=null;const l=new n,a=new yo(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===gt?1:-1:g}else return w.curr.id.client-p.curr.id.client}),r.length!==0;){const f=r[0],d=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!==d||w&&p.id.clock>i.struct.id.clock+i.struct.length)continue;if(d!==i.struct.id.client)Gt(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===gt)i.struct.length=p.id.clock+p.length-i.struct.id.clock;else{Gt(a,i.struct,i.offset);const g=p.id.clock-i.struct.id.clock-i.struct.length;i={struct:new gt(ue(d,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===gt?i.struct.length-=g:p=Rm(p,g)),i.struct.mergeWith(p)||(Gt(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===d&&p.id.clock===i.struct.id.clock+i.struct.length&&p.constructor!==gt;p=f.next())Gt(a,i.struct,i.offset),i={struct:p,offset:0}}i!==null&&(Gt(a,i.struct,i.offset),i=null),bo(a);const c=s.map(f=>po(f)),u=Mi(c);return ts(l,u),l.toUint8Array()},Am=(t,e,n=Gn,s=gn)=>{const r=hc(e),i=new s,l=new yo(i),a=new n(tn(t)),c=new wo(a,!1);for(;c.curr;){const f=c.curr,d=f.id.client,p=r.get(d)||0;if(c.curr.constructor===gt){c.next();continue}if(f.id.clock+f.length>p)for(Gt(l,f,bn(p-f.id.clock,0)),c.next();c.curr&&c.curr.id.client===d;)Gt(l,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===d&&c.curr.id.clock+c.curr.length<=p;)c.next()}bo(l);const u=po(a);return ts(i,u),i.toUint8Array()},Sc=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Se(t.encoder.restEncoder)}),t.encoder.restEncoder=Fe(),t.written=0)},Gt=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&Sc(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),q(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},bo=t=>{Sc(t);const e=t.encoder.restEncoder;q(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];q(e,s.written),yr(e,s.restEncoder)}},Nm=(t,e,n,s)=>{const r=new n(tn(t)),i=new wo(r,!1),l=new s,a=new yo(l);for(let u=i.curr;u!==null;u=i.next())Gt(a,e(u),0);bo(a);const c=po(r);return ts(l,c),l.toUint8Array()},Om=t=>Nm(t,qf,Gn,Rs),Vl="You must not compute changes after the event-handler fired.";class Dr{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=Fm(this.currentTarget,this.target))}deletes(e){return Ls(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw kt(Vl);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let l,a;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))l="delete",a=ai(c.content.getContent());else return;else c!==null&&this.deletes(c)?(l="update",a=ai(c.content.getContent())):(l="add",a=void 0)}else if(this.deletes(i))l="delete",a=ai(i.content.getContent());else return;e.set(r,{action:l,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw kt(Vl);const n=this.target,s=Qt(),r=Qt(),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 Fm=(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},Ze=()=>{nc("Invalid access: Add Yjs type to a document before reading data.")},kc=80;let xo=0;class Mm{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=xo++}}const $m=t=>{t.timestamp=xo++},Cc=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=xo++},Im=(t,e,n)=>{if(t.length>=kc){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return Cc(s,e,n),s}else{const s=new Mm(e,n);return t.push(s),s}},_r=(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)=>Ks(e-i.index)<Ks(e-l.index)?i:l);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,$m(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&&Ks(n.index-r)<s.parent.length/kc?(Cc(n,s,r),n):Im(t._searchMarker,s,r)},vs=(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=bn(e,r.index+n))}},Tr=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;Lt(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;pc(s._eH,n,e)};class Ve{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Il(),this._dEH=Il(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw xt()}clone(){throw xt()}_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){Pl(this._eH,e)}observeDeep(e){Pl(this._dEH,e)}unobserve(e){Ul(this._eH,e)}unobserveDeep(e){Ul(this._dEH,e)}toJSON(){}}const jc=(t,e,n)=>{t.doc??Ze(),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},vc=t=>{t.doc??Ze();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},Es=(t,e)=>{let n=0,s=t._start;for(t.doc??Ze();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}},Ec=(t,e)=>{const n=[];return Es(t,(s,r)=>{n.push(e(s,r,t))}),n},Pm=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}}}},Dc=(t,e)=>{t.doc??Ze();const n=_r(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}},cr=(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 je(ue(l,$e(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new yn(u)),r.integrate(t,0),u=[])};s.forEach(d=>{if(d===null)u.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(d);break;default:switch(f(),d.constructor){case Uint8Array:case ArrayBuffer:r=new je(ue(l,$e(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new As(new Uint8Array(d))),r.integrate(t,0);break;case xn:r=new je(ue(l,$e(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Ns(d)),r.integrate(t,0);break;default:if(d instanceof Ve)r=new je(ue(l,$e(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new At(d)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),f()},_c=()=>kt("Length exceeded!"),Tc=(t,e,n,s)=>{if(n>e._length)throw _c();if(n===0)return e._searchMarker&&vs(e._searchMarker,n,s.length),cr(t,e,null,s);const r=n,i=_r(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&&rt(t,ue(l.id.client,l.id.clock+n));break}n-=l.length}return e._searchMarker&&vs(e._searchMarker,r,s.length),cr(t,e,l,s)},Um=(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 cr(t,e,r,n)},Lc=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,l=_r(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&&rt(t,ue(a.id.client,a.id.clock+n)),n-=a.length);for(;s>0&&a!==null;)a.deleted||(s<a.length&&rt(t,ue(a.id.client,a.id.clock+s)),a.delete(t),s-=a.length),a=a.right;if(s>0)throw _c();e._searchMarker&&vs(e._searchMarker,r,-i+s)},ur=(t,e,n)=>{const s=e._map.get(n);s!==void 0&&s.delete(t)},So=(t,e,n,s)=>{const r=e._map.get(n)||null,i=t.doc,l=i.clientID;let a;if(s==null)a=new yn([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new yn([s]);break;case Uint8Array:a=new As(s);break;case xn:a=new Ns(s);break;default:if(s instanceof Ve)a=new At(s);else throw new Error("Unexpected content type")}new je(ue(l,$e(i.store,l)),r,r&&r.lastId,null,null,e,n,a).integrate(t,0)},ko=(t,e)=>{t.doc??Ze();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Rc=t=>{const e={};return t.doc??Ze(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},Ac=(t,e)=>{t.doc??Ze();const n=t._map.get(e);return n!==void 0&&!n.deleted},zm=(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&&Rn(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},qs=t=>(t.doc??Ze(),nm(t._map.entries(),e=>!e[1].deleted));class Bm extends Dr{}class Pn extends Ve{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new Pn;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Pn}clone(){const e=new Pn;return e.insert(0,this.toArray().map(n=>n instanceof Ve?n.clone():n)),e}get length(){return this.doc??Ze(),this._length}_callObserver(e,n){super._callObserver(e,n),Tr(this,e,new Bm(this,e))}insert(e,n){this.doc!==null?ke(this.doc,s=>{Tc(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?ke(this.doc,n=>{Um(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?ke(this.doc,s=>{Lc(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return Dc(this,e)}toArray(){return vc(this)}slice(e=0,n=this.length){return jc(this,e,n)}toJSON(){return this.map(e=>e instanceof Ve?e.toJSON():e)}map(e){return Ec(this,e)}forEach(e){Es(this,e)}[Symbol.iterator](){return Pm(this)}_write(e){e.writeTypeRef(fg)}}const Wm=t=>new Pn;class qm extends Dr{constructor(e,n,s){super(e,n),this.keysChanged=s}}class Yn extends Ve{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 Yn}clone(){const e=new Yn;return this.forEach((n,s)=>{e.set(s,n instanceof Ve?n.clone():n)}),e}_callObserver(e,n){Tr(this,e,new qm(this,e,n))}toJSON(){this.doc??Ze();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof Ve?r.toJSON():r}}),e}get size(){return[...qs(this)].length}keys(){return fi(qs(this),e=>e[0])}values(){return fi(qs(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return fi(qs(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ze(),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?ke(this.doc,n=>{ur(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?ke(this.doc,s=>{So(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return ko(this,e)}has(e){return Ac(this,e)}clear(){this.doc!==null?ke(this.doc,e=>{this.forEach(function(n,s,r){ur(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(pg)}}const Hm=t=>new Yn,Yt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Bf(t,e);class Pi{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ut(),this.right.content.constructor===qe?this.right.deleted||ns(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Kl=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===qe?e.right.deleted||ns(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&rt(t,ue(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},Hs=(t,e,n,s)=>{const r=new Map,i=s?_r(e,n):null;if(i){const l=new Pi(i.p.left,i.p,i.index,r);return Kl(t,l,n-i.index)}else{const l=new Pi(null,e._start,0,r);return Kl(t,l,n)}},Nc=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===qe&&Yt(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 je(ue(i,$e(r.store,i)),c,c&&c.lastId,u,u&&u.id,e,null,new qe(a,l));f.integrate(t,0),n.right=f,n.forward()})},ns=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},Oc=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===qe&&Yt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Fc=(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(!Yt(u,c)){l.set(a,u);const{left:f,right:d}=n;n.right=new je(ue(i,$e(r.store,i)),f,f&&f.lastId,d,d&&d.id,e,null,new qe(a,c)),n.right.integrate(t,0),n.forward()}}return l},pi=(t,e,n,s,r)=>{n.currentAttributes.forEach((p,w)=>{r[w]===void 0&&(r[w]=null)});const i=t.doc,l=i.clientID;Oc(n,r);const a=Fc(t,e,n,r),c=s.constructor===String?new Tt(s):s instanceof Ve?new At(s):new Sn(s);let{left:u,right:f,index:d}=n;e._searchMarker&&vs(e._searchMarker,n.index,c.getLength()),f=new je(ue(l,$e(i.store,l)),u,u&&u.lastId,f,f&&f.id,e,null,c),f.integrate(t,0),n.right=f,n.index=d,n.forward(),Nc(t,e,n,a)},Jl=(t,e,n,s,r)=>{const i=t.doc,l=i.clientID;Oc(n,r);const a=Fc(t,e,n,r);e:for(;n.right!==null&&(s>0||a.size>0&&(n.right.deleted||n.right.content.constructor===qe));){if(!n.right.deleted)switch(n.right.content.constructor){case qe:{const{key:c,value:u}=n.right.content,f=r[c];if(f!==void 0){if(Yt(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&&rt(t,ue(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 je(ue(l,$e(i.store,l)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Tt(c)),n.right.integrate(t,0),n.forward()}Nc(t,e,n,a)},Mc=(t,e,n,s,r)=>{let i=e;const l=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===qe){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===qe){const{key:f,value:d}=u,p=s.get(f)??null;(l.get(f)!==u||p===d)&&(e.delete(t),a++,!c&&(r.get(f)??null)===d&&p!==d&&(p===null?r.delete(f):r.set(f,p))),!c&&!e.deleted&&ns(r,u)}}e=e.right}return a},Vm=(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===qe){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},Km=t=>{let e=0;return ke(t.doc,n=>{let s=t._start,r=t._start,i=it();const l=Li(i);for(;r;)r.deleted===!1&&(r.content.constructor===qe?ns(l,r.content):(e+=Mc(n,s,r,i,l),i=Li(l),s=r)),r=r.right}),e},Jm=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&&bc(t,n.store.clients.get(s),i,r,l=>{!l.deleted&&l.content.constructor===qe&&l.constructor!==mt&&e.add(l.parent)})}ke(n,s=>{Jn(t,t.deleteSet,r=>{if(r instanceof mt||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===qe?e.add(i):Vm(s,r)});for(const r of e)Km(r)})},Gl=(t,e,n)=>{const s=n,r=Li(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case At:case Sn:case Tt:n<e.right.length&&rt(t,ue(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&Mc(t,i,e.right,r,e.currentAttributes);const l=(e.left||e.right).parent;return l._searchMarker&&vs(l._searchMarker,e.index,-s+n),e};class Gm extends Dr{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=[];ke(e,s=>{const r=new Map,i=new Map;let l=this.target._start,a=null;const c={};let u="",f=0,d=0;const p=()=>{if(a!==null){let w=null;switch(a){case"delete":d>0&&(w={delete:d}),d=0;break;case"insert":(typeof u=="object"||u.length>0)&&(w={insert:u},r.size>0&&(w.attributes={},r.forEach((g,b)=>{g!==null&&(w.attributes[b]=g)}))),u="";break;case"retain":f>0&&(w={retain:f},zf(c)||(w.attributes=$f({},c))),f=0;break}w&&n.push(w),a=null}};for(;l!==null;){switch(l.content.constructor){case At:case Sn:this.adds(l)?this.deletes(l)||(p(),a="insert",u=l.content.getContent()[0],p()):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),d+=1):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=1);break;case Tt:this.adds(l)?this.deletes(l)||(a!=="insert"&&(p(),a="insert"),u+=l.content.str):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),d+=l.length):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=l.length);break;case qe:{const{key:w,value:g}=l.content;if(this.adds(l)){if(!this.deletes(l)){const b=r.get(w)??null;Yt(b,g)?g!==null&&l.delete(s):(a==="retain"&&p(),Yt(g,i.get(w)??null)?delete c[w]:c[w]=g)}}else if(this.deletes(l)){i.set(w,g);const b=r.get(w)??null;Yt(b,g)||(a==="retain"&&p(),c[w]=b)}else if(!l.deleted){i.set(w,g);const b=c[w];b!==void 0&&(Yt(b,g)?b!==null&&l.delete(s):(a==="retain"&&p(),g===null?delete c[w]:c[w]=g))}l.deleted||(a==="insert"&&p(),ns(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 Xn extends Ve{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ze(),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 Xn}clone(){const e=new Xn;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new Gm(this,e,n);Tr(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ze();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Tt&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?ke(this.doc,s=>{const r=new Pi(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)&&pi(s,this,r,a,l.attributes||{})}else l.retain!==void 0?Jl(s,this,r,l.retain,l.attributes||{}):l.delete!==void 0&&Gl(s,r,l.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??Ze();const r=[],i=new Map,l=this.doc;let a="",c=this._start;function u(){if(a.length>0){const d={};let p=!1;i.forEach((g,b)=>{p=!0,d[b]=g});const w={insert:a};p&&(w.attributes=d),r.push(w),a=""}}const f=()=>{for(;c!==null;){if(Rn(c,e)||n!==void 0&&Rn(c,n))switch(c.content.constructor){case Tt:{const d=i.get("ychange");e!==void 0&&!Rn(c,e)?(d===void 0||d.user!==c.id.client||d.type!=="removed")&&(u(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!Rn(c,n)?(d===void 0||d.user!==c.id.client||d.type!=="added")&&(u(),i.set("ychange",s?s("added",c.id):{type:"added"})):d!==void 0&&(u(),i.delete("ychange")),a+=c.content.str;break}case At:case Sn:{u();const d={insert:c.content.getContent()[0]};if(i.size>0){const p={};d.attributes=p,i.forEach((w,g)=>{p[g]=w})}r.push(d);break}case qe:Rn(c,e)&&(u(),ns(i,c.content));break}c=c.right}u()};return e||n?ke(l,d=>{e&&$i(d,e),n&&$i(d,n),f()},"cleanup"):f(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?ke(r,i=>{const l=Hs(i,this,e,!s);s||(s={},l.currentAttributes.forEach((a,c)=>{s[c]=a})),pi(i,this,l,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?ke(r,i=>{const l=Hs(i,this,e,!s);pi(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?ke(s,r=>{Gl(r,Hs(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?ke(r,i=>{const l=Hs(i,this,e,!1);l.right!==null&&Jl(i,this,l,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?ke(this.doc,n=>{ur(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?ke(this.doc,s=>{So(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return ko(this,e)}getAttributes(){return Rc(this)}_write(e){e.writeTypeRef(mg)}}const Ym=t=>new Xn;class mi{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ze()}[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===Qn||n.constructor===wn)&&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 wn extends Ve{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 wn}clone(){const e=new wn;return e.insert(0,this.toArray().map(n=>n instanceof Ve?n.clone():n)),e}get length(){return this.doc??Ze(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new mi(this,e)}querySelector(e){e=e.toUpperCase();const s=new mi(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),zt(new mi(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Tr(this,e,new Zm(this,n,e))}toString(){return Ec(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),Es(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?ke(this.doc,s=>{Tc(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)ke(this.doc,s=>{const r=e&&e instanceof Ve?e._item:e;cr(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 kt("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?ke(this.doc,s=>{Lc(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return vc(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Dc(this,e)}slice(e=0,n=this.length){return jc(this,e,n)}forEach(e){Es(this,e)}_write(e){e.writeTypeRef(wg)}}const Xm=t=>new wn;class Qn extends wn{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 Qn(this.nodeName)}clone(){const e=new Qn(this.nodeName),n=this.getAttributes();return Pf(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof Ve?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?ke(this.doc,n=>{ur(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?ke(this.doc,s=>{So(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return ko(this,e)}hasAttribute(e){return Ac(this,e)}getAttributes(e){return e?zm(this,e):Rc(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 Es(this,l=>{r.appendChild(l.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(gg),e.writeKey(this.nodeName)}}const Qm=t=>new Qn(t.readKey());class Zm extends Dr{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 dr extends Yn{constructor(e){super(),this.hookName=e}_copy(){return new dr(this.hookName)}clone(){const e=new dr(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(yg),e.writeKey(this.hookName)}}const eg=t=>new dr(t.readKey());class hr extends Xn{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 hr}clone(){const e=new hr;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(bg)}}const tg=t=>new hr;class Co{constructor(e,n){this.id=e,this.length=n}get deleted(){throw xt()}mergeWith(e){return!1}write(e,n,s){throw xt()}integrate(e,n){throw xt()}}const ng=0;class mt extends Co{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),yc(e.doc.store,this)}write(e,n){e.writeInfo(ng),e.writeLen(this.length-n)}getMissing(e,n){return null}}class As{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new As(this.content)}splice(e){throw xt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const sg=t=>new As(t.readBuf());class Ds{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ds(this.len)}splice(e){const n=new Ds(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){js(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 rg=t=>new Ds(t.readLen()),$c=(t,e)=>new xn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Ns{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 Ns($c(this.doc.guid,this.opts))}splice(e){throw xt()}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 ig=t=>new Ns($c(t.readString(),t.readAny()));class Sn{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Sn(this.embed)}splice(e){throw xt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const og=t=>new Sn(t.readJSON());class qe{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new qe(this.key,this.value)}splice(e){throw xt()}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 lg=t=>new qe(t.readKey(),t.readJSON());class fr{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new fr(this.arr)}splice(e){const n=new fr(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 ag=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 fr(n)},cg=rr("node_env")==="development";class yn{constructor(e){this.arr=e,cg&&La(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new yn(this.arr)}splice(e){const n=new yn(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 ug=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new yn(n)};class Tt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Tt(this.str)}splice(e){const n=new Tt(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 dg=t=>new Tt(t.readString()),hg=[Wm,Hm,Ym,Qm,Xm,eg,tg],fg=0,pg=1,mg=2,gg=3,wg=4,yg=5,bg=6;class At{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new At(this.type._copy())}splice(e){throw xt()}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 xg=t=>new At(hg[t.readTypeRef()](t)),Ui=(t,e)=>{let n=e,s=0,r;do s>0&&(n=ue(n.client,n.clock+s)),r=In(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof je);return{item:r,diff:s}},jo=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},pr=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new je(ue(s,r+n),e,ue(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=ue(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},Yl=(t,e)=>Gi(t,n=>Ls(n.deletions,e)),Ic=(t,e,n,s,r,i)=>{const l=t.doc,a=l.store,c=l.clientID,u=e.redone;if(u!==null)return rt(t,u);let f=e.parent._item,d=null,p;if(f!==null&&f.deleted===!0){if(f.redone===null&&(!n.has(f)||Ic(t,f,n,s,r,i)===null))return null;for(;f.redone!==null;)f=rt(t,f.redone)}const w=f===null?e.parent:f.content.type;if(e.parentSub===null){for(d=e.left,p=e;d!==null;){let _=d;for(;_!==null&&_.parent._item!==f;)_=_.redone===null?null:rt(t,_.redone);if(_!==null&&_.parent._item===f){d=_;break}d=d.left}for(;p!==null;){let _=p;for(;_!==null&&_.parent._item!==f;)_=_.redone===null?null:rt(t,_.redone);if(_!==null&&_.parent._item===f){p=_;break}p=p.right}}else{if(p=null,e.right&&!r){for(d=e;d!==null&&d.right!==null&&(d.right.redone||Ls(s,d.right.id)||Yl(i.undoStack,d.right.id)||Yl(i.redoStack,d.right.id));)for(d=d.right;d.redone;)d=rt(t,d.redone);if(d&&d.right!==null)return null}else d=w._map.get(e.parentSub)||null;d!==null&&d.parent._item!==f&&(d=w._map.get(e.parentSub)||null)}const g=$e(a,c),b=ue(c,g),x=new je(b,d,d&&d.lastId,p,p&&p.id,w,e.parentSub,e.content.copy());return e.redone=b,jo(x,!0),x.integrate(t,0),x};class je extends Co{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()?El:0}set marker(e){(this.info&li)>0!==e&&(this.info^=li)}get marker(){return(this.info&li)>0}get keep(){return(this.info&vl)>0}set keep(e){this.keep!==e&&(this.info^=vl)}get countable(){return(this.info&El)>0}get deleted(){return(this.info&oi)>0}set deleted(e){this.deleted!==e&&(this.info^=oi)}markDeleted(){this.info|=oi}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=$e(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=$e(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===$n&&this.id.client!==this.parent.client&&this.parent.clock>=$e(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=zl(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=rt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===mt||this.right&&this.right.constructor===mt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===je?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===je&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===$n){const s=In(n,this.parent);s.constructor===mt?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=zl(e,e.doc.store,ue(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),Nn(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Nn(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&l.has(In(e.doc.store,r.origin)))i.has(In(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),yc(e.doc.store,this),this.content.integrate(e,this),Wl(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new mt(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:ue(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Nn(e.origin,this.lastId)&&this.right===e&&Nn(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(),js(e.deleteSet,this.id.client,this.id.clock,this.length),Wl(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw ut();this.content.gc(e),n?Cm(e,this,new mt(this.id,this.length)):this.content=new Ds(this.length)}write(e,n){const s=n>0?ue(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,l=this.content.getRef()&wr|(s===null?0:nt)|(r===null?0:Ut)|(i===null?0:ys);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=mc(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===$n?(e.writeParentInfo(!1),e.writeLeftID(a)):ut();i!==null&&e.writeString(i)}this.content.write(e,n)}}const Pc=(t,e)=>Sg[e&wr](t),Sg=[()=>{ut()},rg,ag,sg,dg,og,lg,xg,ug,ig,()=>{ut()}],kg=10;class gt extends Co{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){ut()}write(e,n){e.writeInfo(kg),q(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const Uc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},zc="__ $YJS$ __";Uc[zc]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Uc[zc]=!0;function Cg(t){for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t}function jg(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 zi(t=globalThis.crypto){if(typeof t?.randomUUID=="function")return t.randomUUID();const e=new Uint8Array(16),n=typeof t?.getRandomValues=="function"?t.getRandomValues(e):Cg(e);return jg(n)}const Bc=new Map;class vg{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:sp(n.newValue||"")}),Of(this._onChange)}postMessage(e){_a.setItem(this.room,np(Xf(e)))}close(){Ff(this._onChange)}}const Eg=typeof BroadcastChannel>"u"?vg:BroadcastChannel,vo=t=>Lt(Bc,t,()=>{const e=Qt(),n=new Eg(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),Dg=(t,e)=>(vo(t).subs.add(e),e),_g=(t,e)=>{const n=vo(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),Bc.delete(t)),s},An=(t,e,n=null)=>{const s=vo(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},Wc=0,Eo=1,qc=2,mr=(t,e)=>{q(t,Wc);const n=wm(e);Oe(t,n)},Hc=(t,e,n)=>{q(t,Eo),Oe(t,go(e,n))},Tg=(t,e,n)=>Hc(e,n,Qe(t)),Vc=(t,e,n,s)=>{try{dc(e,Qe(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Lg=(t,e)=>{q(t,qc),Oe(t,e)},Rg=Vc,Ag=(t,e,n,s,r)=>{const i=re(t);switch(i){case Wc:Tg(t,e,n);break;case Eo:Vc(t,n,s,r);break;case qc:Rg(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},Ng=0,Og=(t,e,n)=>{re(t)===Ng&&n(e,_e(t))},gi=3e4;class Fg extends Sa{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Zt();this.getLocalState()!==null&&gi/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&gi<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Do(this,s,"timeout")},St(gi/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:Zt()});const l=[],a=[],c=[],u=[];e===null?u.push(n):i==null?e!=null&&l.push(n):(a.push(n),Fn(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 Do=(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:Zt()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},Un=(t,e,n=t.states)=>{const s=e.length,r=Fe();q(r,s);for(let i=0;i<s;i++){const l=e[i],a=n.get(l)||null,c=t.meta.get(l).clock;q(r,l),q(r,c),Ye(r,JSON.stringify(a))}return Se(r)},Mg=(t,e,n)=>{const s=tn(e),r=Zt(),i=[],l=[],a=[],c=[],u=re(s);for(let f=0;f<u;f++){const d=re(s);let p=re(s);const w=JSON.parse(_e(s)),g=t.meta.get(d),b=t.states.get(d),x=g===void 0?0:g.clock;(x<p||x===p&&w===null&&t.states.has(d))&&(w===null?d===t.clientID&&t.getLocalState()!=null?p++:t.states.delete(d):t.states.set(d,w),t.meta.set(d,{clock:p,lastUpdated:r}),g===void 0&&w!==null?i.push(d):g!==void 0&&w===null?c.push(d):w!==null&&(Fn(w,b)||a.push(d),l.push(d)))}(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])},$g=t=>Uf(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),fn=0,Kc=3,zn=1,Ig=2,Os=[];Os[fn]=(t,e,n,s,r)=>{q(t,fn);const i=Ag(e,t,n.doc,n);s&&i===Eo&&!n.synced&&(n.synced=!0)};Os[Kc]=(t,e,n,s,r)=>{q(t,zn),Oe(t,Un(n.awareness,Array.from(n.awareness.getStates().keys())))};Os[zn]=(t,e,n,s,r)=>{Mg(n.awareness,Qe(e),n)};Os[Ig]=(t,e,n,s,r)=>{Og(e,n.doc,(i,l)=>Pg(n,l))};const Xl=3e4,Pg=(t,e)=>console.warn(`Permission denied to access ${t.url}.
|
|
10
|
-
${e}`),Jc=(t,e,n)=>{const s=tn(e),r=Fe(),i=re(s),l=t.messageHandlers[i];return l?l(r,s,t,n,i):console.error("Unable to compute message"),r},Bi=(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,Do(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(Gc,Xi(nf(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},Gc=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=Zt();const s=Jc(t,new Uint8Array(n.data),!0);Qi(s)>1&&e.send(Se(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{Bi(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=Zt(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Fe();if(q(n,fn),mr(n,t.doc),e.send(Se(n)),t.awareness.getLocalState()!==null){const s=Fe();q(s,zn),Oe(s,Un(t.awareness,[t.doc.clientID])),e.send(Se(s))}},t.emit("status",[{status:"connecting"}])}},wi=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&An(t.bcChannel,e,t)};class Ug extends Yi{constructor(e,n,s,{connect:r=!0,awareness:i=new Fg(s),params:l={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:u=-1,maxBackoffTime:f=2500,disableBc:d=!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=d,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Os.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=Fe();q(p,fn),mr(p,s),this.ws.send(Se(p))}},u)),this._bcSubscriber=(p,w)=>{if(w!==this){const g=Jc(this,new Uint8Array(p),!1);Qi(g)>1&&An(this.bcChannel,Se(g),this)}},this._updateHandler=(p,w)=>{if(w!==this){const g=Fe();q(g,fn),Lg(g,p),wi(this,Se(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:p,updated:w,removed:g},b)=>{const x=p.concat(w).concat(g),_=Fe();q(_,zn),Oe(_,Un(i,x)),wi(this,Se(_))},this._exitHandler=()=>{Do(this.awareness,[s.clientID],"app closed")},en&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Xl<Zt()-this.wsLastMessageReceived&&Bi(this,this.ws,null)},Xl/10),r&&this.connect()}get url(){const e=$g(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(),en&&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||(Dg(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Fe();q(e,fn),mr(e,this.doc),An(this.bcChannel,Se(e),this);const n=Fe();q(n,fn),Hc(n,this.doc),An(this.bcChannel,Se(n),this);const s=Fe();q(s,Kc),An(this.bcChannel,Se(s),this);const r=Fe();q(r,zn),Oe(r,Un(this.awareness,[this.doc.clientID])),An(this.bcChannel,Se(r),this)}disconnectBc(){const e=Fe();q(e,zn),Oe(e,Un(this.awareness,[this.doc.clientID],new Map)),wi(this,Se(e)),this.bcconnected&&(_g(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Bi(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Gc(this),this.connectBc())}}const kn=t=>Vn((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),zg=(t,e)=>Vn((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(kt(i.target.error)),r.onsuccess=i=>{const l=i.target.result;l.onversionchange=()=>{l.close()},n(l)}}),Bg=t=>kn(indexedDB.deleteDatabase(t)),Wg=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),ds=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>Xg(s,r))},Yc=(t,e)=>kn(t.count(e)),qg=(t,e)=>kn(t.get(e)),Xc=(t,e)=>kn(t.delete(e)),Hg=(t,e,n)=>kn(t.put(e,n)),Wi=(t,e)=>kn(t.add(e)),Vg=(t,e,n)=>kn(t.getAll(e,n)),Kg=(t,e,n)=>{let s=null;return Yg(t,e,r=>(s=r,!1),n).then(()=>s)},Jg=(t,e=null)=>Kg(t,e,"prev"),Gg=(t,e)=>Vn((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()}}),Yg=(t,e,n,s="next")=>Gg(t.openKeyCursor(e,s),r=>n(r.key)),Xg=(t,e)=>t.objectStore(e),Qg=(t,e)=>IDBKeyRange.upperBound(t,e),Zg=(t,e)=>IDBKeyRange.lowerBound(t,e),yi="custom",Qc="updates",Zc=500,eu=(t,e=()=>{},n=()=>{})=>{const[s]=ds(t.db,[Qc]);return Vg(s,Zg(t._dbref,!1)).then(r=>{t._destroyed||(e(s),ke(t.doc,()=>{r.forEach(i=>dc(t.doc,i))},t,!1),n(s))}).then(()=>Jg(s).then(r=>{t._dbref=r+1})).then(()=>Yc(s).then(r=>{t._dbsize=r})).then(()=>s)},ew=(t,e=!0)=>eu(t).then(n=>{(e||t._dbsize>=Zc)&&Wi(n,go(t.doc)).then(()=>Xc(n,Qg(t._dbref,!0))).then(()=>Yc(n).then(s=>{t._dbsize=s}))});class tw extends Sa{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=zg(e,s=>Wg(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Vn(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,eu(this,l=>Wi(l,go(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]=ds(this.db,[Qc]);Wi(i,s),++this._dbsize>=Zc&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{ew(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(()=>{Bg(this.name)})}get(e){return this._db.then(n=>{const[s]=ds(n,[yi],"readonly");return qg(s,e)})}set(e,n){return this._db.then(s=>{const[r]=ds(s,[yi]);return Hg(r,n,e)})}del(e){return this._db.then(n=>{const[s]=ds(n,[yi]);return Xc(s,e)})}}const Ql=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],Zl=4,ea=5,nw=6,sw=7,rw=8,bi=9,xi=3,iw=6e4,ow=720*60*60*1e3,lw=15e3,aw=5*6e4;function cw(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!["queued","running","succeeded","failed","cleaned"].includes(e.status??"")||e.status==="cleaned"&&e.cleanMode!=="cache"&&e.cleanMode!=="artifacts"||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 ta(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=cw(s);r&&r.mainFile===n&&(e[n]=r)}return e}function uw(t,e,n){return t<=n&&e<=n}function na(t,e,n){const s=r=>r>0&&n-r<=aw;return{recoverable:t.some(r=>r.tabId===e||!s(r.activeAt)),otherActive:t.some(r=>r.tabId!==e&&s(r.activeAt))}}class dw{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.draftTabId=mw(`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 tw(`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 Ug(`${s}//${window.location.host}/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[Zl]=(l,a)=>{const c=_e(a),u=this.flushRequests.get(c);if(!u)return;const f=re(a)===1,d=re(a),p=_e(a),w=re(a),g=[];for(let b=0;b<w;b++)g.push(_e(a));if(window.clearTimeout(u.timer),this.flushRequests.delete(c),f)this.clearOwnWritableDraftMarker(u.draftGeneration),u.resolve({revision:d,persistedAt:p,ok:!0,failedPaths:[]});else{const b=Object.assign(new Error(g.length?`保存失败:${g.join(", ")}`:"源码保存到服务器磁盘失败"),{failedPaths:g});u.reject(b)}},this.provider.messageHandlers[ea]=(l,a)=>{const c=_e(a),u=this.epochStorageKey(),f=sa(u),d=/^([0-9]+):/.exec(c)?.[1]??null,p=f?/^([0-9]+):/.exec(f)?.[1]??null:null,w=!this.epoch&&d===String(xi)&&p!==null&&p!==d;if((this.epoch&&this.epoch!==c||f&&f!==c)&&!w){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed"));const O=c.endsWith(":reload")||d!==null&&d!==String(xi),S=()=>{Si(u,c.replace(/:reload$/,"")),window.location.reload()};if(O)for(const V of this.protocolUpgradeListeners)V();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),S()});return}this.epoch=c,Si(u,c);const g=this.provider.ws;if(!g||g.readyState!==WebSocket.OPEN)return;const b=Fe();q(b,ea),Ye(b,c),q(b,xi),g.send(Se(b));const x=Fe();q(x,0),mr(x,this.doc),g.send(Se(x));const _=Fe();q(_,1),Oe(_,Un(this.awareness,[this.doc.clientID])),g.send(Se(_))},this.provider.messageHandlers[sw]=(l,a)=>{const c=_e(a),u=_e(a);if(c!==this.user.id)return;if(u==="revoked"){this.rejectFlushes(new Error("Project access revoked")),this.provider.disconnect();for(const d of this.permissionListeners)d("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 d of this.permissionListeners)d(u,f)}},this.provider.messageHandlers[nw]=(l,a)=>{_e(a)},this.provider.messageHandlers[rw]=(l,a)=>{let c={};try{c=ta(JSON.parse(_e(a)))}catch{}this.authoritativeCompileStates=c,this.notifyCompileStateListeners()},this.provider.messageHandlers[bi]=(l,a)=>{const c=_e(a),u=_e(a),f=_e(a),d=_e(a),p=_e(a),w=_e(a);if(c==="state"){const b=Ni(a)?_e(a):"",x=Ni(a)?_e(a):"",_=Number(p);if(!b||!Number.isFinite(_)||_<=Date.now())this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null);else{const O={path:f,holderUserId:b,holderName:x,expiresAt:_};this.formatLeaseStatesByPath.set(f,O);const S=this.formatLeaseExpiryTimers.get(f);S!==void 0&&window.clearTimeout(S);const V=window.setTimeout(()=>{const Y=this.formatLeaseStatesByPath.get(f);!Y||Y.expiresAt>Date.now()||(this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null))},Math.max(0,_-Date.now())+25);this.formatLeaseExpiryTimers.set(f,V),this.notifyFormatLeaseListeners(O)}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:d,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 xn;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 _m(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??ta(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 na(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){const e=this.readWritableDraftMarkers();return na(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=zi(),s=this.draftGeneration,r=Fe();return q(r,Zl),Ye(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(Se(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=zi(),l=Fe();return q(l,bi),Ye(l,e),Ye(l,i),Ye(l,n),Ye(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 d=Fe();q(d,bi),Ye(d,"cancel"),Ye(d,i),Ye(d,n),Ye(d,""),f.send(Se(d))}}c(new Error("Format lease request timed out"))},e==="acquire"?iw:5e3);this.formatLeaseRequests.set(i,{resolve:a,reject:c,timer:u}),r.send(Se(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]=Ql[Math.abs(this.doc.clientID)%Ql.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`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`}writableDraftStoragePrefix(){return`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())cs(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),cs(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){const n=this.readOwnWritableDraftMarker();!n||!uw(n.generation,this.draftGeneration,e)||(cs(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){const e=this.writableDraftStoragePrefix(),n=[];for(const s of hw()){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=sa(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>ow)return cs(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 cs(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};Si(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)},lw))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}}function sa(t){try{return window.localStorage.getItem(t)}catch{return null}}function Si(t,e){try{window.localStorage.setItem(t,e)}catch{}}function cs(t){try{window.localStorage.removeItem(t)}catch{}}function hw(){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 fw(t){try{return window.sessionStorage.getItem(t)}catch{return null}}function pw(t,e){try{window.sessionStorage.setItem(t,e)}catch{}}function mw(t){const e=fw(t);if(e)return e;const n=zi();return pw(t,n),n}function gw(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function ww(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 yw(t,e,n,s,r,i){const[l]=h.useState(()=>new dw(t,e)),[a,c]=h.useState("connecting"),[u,f]=h.useState(!1),[d,p]=h.useState([]),[w,g]=h.useState(null),[b,x]=h.useState(null),[_,O]=h.useState(""),[S,V]=h.useState(!1),[Y,C]=h.useState(""),[j,L]=h.useState([]),[K,X]=h.useState(!1),[B,P]=h.useState(s),[oe,D]=h.useState(null),[U,ee]=h.useState(!1),te=h.useRef(n),J=h.useRef(i),fe=h.useRef(r);te.current=n,J.current=i,fe.current=r,h.useEffect(()=>{const $=l.compileStates();g($[n]??null)},[n,l]),h.useEffect(()=>{const $=()=>p(l.sessions()),M=()=>{f(!1),p([]),g(null),x(null),O(""),V(!1),C(""),L([]),J.current()},z=({status:he})=>{c(he),he!=="connected"&&M()},se=he=>{f(he),he||M()},le=()=>{c("disconnected"),M()},be=()=>{V(l.meta.get("historyWarning")===!0);const he=l.meta.get("filesEvent");ww(he)&&x(he);const we=l.meta.get("commentsRevision");typeof we=="string"&&O(we);const Be=l.meta.get("dictionaryRevision");typeof Be=="string"&&C(Be);const Ee=l.compileStates();g(Ee[te.current]??null)},Ie=()=>{const he=l.compileStates();g(he[te.current]??null)};l.awareness.on("change",$),l.provider.on("status",z),l.provider.on("sync",se),l.provider.on("connection-close",le),l.provider.on("connection-error",le),l.meta.observe(be);const I=l.onCompileStates(Ie),G=l.onProtocolUpgrade(()=>{ee(!0),c("disconnected"),M()}),Re=()=>L(l.formatLeaseStates()),F=l.onFormatLeaseState(Re),Pe=()=>{if(!fe.current||l.currentPermission!=="read")return;const he=l.hasWritableDraft,we=l.hasOtherWritableDraft;!he&&!we||D({previous:"edit",localDraftReady:he,otherTabDraft:we})},Ae=l.onDraftReady(()=>{X(!0),Pe()}),ve=l.onPermissionChanged((he,we)=>{if(he==="revoked"){c("disconnected"),f(!1),J.current();return}P(he),he==="read"&&we!=="read"?D({previous:we,localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):he!=="read"&&D(null)});return $(),be(),c(l.connected?"connected":"connecting"),f(l.synced),()=>{l.awareness.off("change",$),l.provider.off("status",z),l.provider.off("sync",se),l.provider.off("connection-close",le),l.provider.off("connection-error",le),l.meta.unobserve(be),I(),G(),F(),Ae(),ve(),l.destroy()}},[l]),h.useEffect(()=>{r&&l.connect()},[l,r]),h.useEffect(()=>{l.setPermission(s),P(s),r&&s==="read"&&(l.hasWritableDraft||l.hasOtherWritableDraft)?D({previous:"edit",localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):s!=="read"&&D(null)},[l,s,r]);const ge=oe!==null;return h.useEffect(()=>{if(!ge)return;const $=()=>{if(l.currentPermission!=="read")return;const z=l.hasWritableDraft,se=l.hasOtherWritableDraft;D(le=>!le||le.localDraftReady===z&&le.otherTabDraft===se?le:{...le,localDraftReady:z,otherTabDraft:se})};$();const M=window.setInterval($,2e3);return()=>window.clearInterval(M)},[l,ge]),{collaboration:l,status:a,synced:u,activeSessions:d,compileState:w,setCompileState:g,formatLeaseStates:j,filesEvent:b,commentsRevision:_,historyWarning:S,dictionaryRevision:Y,localDraftReady:K,permission:B,protocolUpgradeRequired:U,reconnect:()=>{U||(c("connecting"),f(!1),p([]),g(null),L([]),l.reconnect())},permissionDowngrade:oe,dismissPermissionDowngrade:()=>D(null),discardLocalDraft:async()=>await l.discardLocalDraft()?(D(null),window.location.reload(),!0):(D(M=>M&&{...M,otherTabDraft:!0}),!1)}}function ra(t){return t?.status==="succeeded"?"succeeded":t?.log.includes("Compilation was cancelled.")?"cancelled":t?.status==="failed"?"failed":null}function cn(t){return t instanceof Error&&t.name==="AbortError"}function bw(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}function xw({projectId:t,project:e,mainFile:n,resolveCompileMainFile:s,getCurrentMainFile:r,initialLatest:i,collaborationSynced:l,sharedState:a,onSharedState:c,save:u,loadOutline:f,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b}){const{t:x}=Ke(),[_,O]=h.useState(""),[S,V]=h.useState(!0),[Y,C]=h.useState(null),[j,L]=h.useState("full"),[K,X]=h.useState(""),[B,P]=h.useState(null),[oe,D]=h.useState(null),[U,ee]=h.useState([]),[te,J]=h.useState(null),[fe,ge]=h.useState(!1),[ye,T]=h.useState(!1),[me,$]=h.useState(()=>new Set),[M,z]=h.useState(()=>new Set),[se,le]=h.useState(""),be=h.useRef(n),Ie=h.useRef(""),I=h.useRef(null),G=h.useRef(null),Re=h.useRef(null),F=h.useRef(i),Pe=h.useRef(!1),Ae=h.useRef(null),ve=h.useRef(null),he=h.useRef(new Set),we=h.useRef(new Map),Be=h.useRef(null),Ee=h.useRef(()=>{}),v=h.useRef({onSharedState:c,save:u,loadOutline:f,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b,resolveCompileMainFile:s,getCurrentMainFile:r});be.current=n,v.current={onSharedState:c,save:u,loadOutline:f,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b,resolveCompileMainFile:s,getCurrentMainFile:r};const ae=()=>v.current.getCurrentMainFile?.()||be.current,Ce=R=>{Be.current!==R&&(Be.current=R,v.current.onCompileSuccess())},et=async(R,Q)=>{Q||(Ae.current?.abort(),Ae.current=new AbortController,Q=Ae.current.signal);try{const A=R?`?mainFile=${encodeURIComponent(R)}`:"",ie=await ce(`/api/projects/${t}/compile/artifacts${A}`,{signal:Q});be.current===R&&(ee(ie.artifacts),J(null))}catch(A){!cn(A)&&be.current===R&&(ee([]),J(null))}finally{Ae.current?.signal===Q&&(Ae.current=null)}};h.useEffect(()=>{if(I.current?.abort(),!n){V(!1),O(""),C(null),L("full"),X(""),P(null),D(null),ee([]),J(null),Re.current=null,v.current.onPdfChanged();return}Re.current?.mainFile!==n&&(Re.current=null);const R=new AbortController;I.current=R,V(!0),X(""),P(null),D(null),_&&n&&Ie.current===n||(O(""),C(null),L("full")),ee([]),J(null),v.current.onPdfChanged();let A=null;const ie=`?mainFile=${encodeURIComponent(n)}`,ht=Pe.current?null:F.current;ht&&(Pe.current=!0);const ft=()=>ce(`/api/projects/${t}/compile/latest${ie}`,{signal:R.signal}),Xe=ht?ht.then(pe=>pe.mainFile!==n?ft():pe,()=>ft()):ft();let ot=!1;const jt=()=>{if(ot||R.signal.aborted||!n)return;ot=!0;const pe=new AbortController;he.current.add(pe),et(n,pe.signal).finally(()=>{he.current.delete(pe)}),v.current.loadOutline(R.signal,n).catch(()=>{})};return Xe.then(pe=>{if(R.signal.aborted||n&&pe.mainFile!==be.current)return;const N=Re.current;N&&N.mainFile===n&&pe.latestRun?.id!==N.runId||(X(pe.latestRun?.log??""),P(pe.latestRun?.diagnostics??null),D(ra(pe.latestRun)),n&&pe.latestRun?.requestedBy&&(pe.latestRun.status==="queued"||pe.latestRun.status==="running")&&v.current.onSharedState({mainFile:n,runId:pe.latestRun.id,status:pe.latestRun.status,requestedBy:pe.latestRun.requestedBy,updatedAt:new Date().toISOString()}),pe.pdfUrl&&(Ie.current=pe.mainFile,O(pe.pdfUrl),C(pe.pdfCompiledAt),L(pe.pdfLoadingMode??"full"),v.current.onPreviewTab("pdf")))}).catch(pe=>{!cn(pe)&&be.current===n&&v.current.onError(de(pe))}).finally(()=>{I.current===R&&(I.current=null),R.signal.aborted||(V(!1),A=window.setTimeout(jt,0))}),()=>{A!==null&&window.clearTimeout(A),R.abort(),ve.current?.abort();for(const pe of he.current)pe.abort();he.current.clear()}},[t,n]),h.useEffect(()=>{if(!(!a||a.mainFile!==n||a.status!=="cleaned"||!a.cleanMode)){I.current?.abort(),G.current?.abort(),Ae.current?.abort(),ve.current?.abort();for(const R of he.current)R.abort();he.current.clear(),a.cleanMode==="artifacts"?(Re.current=null,X(""),P(null),D(null),O(""),C(null),L("full"),ee([]),J(null),v.current.onPdfChanged(),v.current.onPreviewTab("pdf"),le(x("editor.cleanArtifactsComplete"))):le(x("editor.cleanCacheComplete"))}},[a?.runId,a?.status,a?.cleanMode,a?.mainFile,n,x]),h.useEffect(()=>{!n||a?.mainFile===n&&(a.status==="queued"||a.status==="running")||z(R=>{if(!R.has(n))return R;const Q=new Set(R);return Q.delete(n),Q})},[n,a?.mainFile,a?.status]),h.useEffect(()=>{if(!a||a.mainFile!==n||a.status!=="succeeded"&&a.status!=="failed")return;let R=!1;G.current?.abort(),ve.current?.abort();const Q=new AbortController;return G.current=Q,V(!0),ce(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:Q.signal}).then(A=>{R||A.mainFile!==be.current||A.latestRun?.id!==a.runId||(X(A.latestRun.log),P(A.latestRun.diagnostics),D(ra(A.latestRun)),a.status==="succeeded"&&a.stale&&le(x("editor.compileSnapshotStale")),a.status==="succeeded"&&A.pdfUrl?(Re.current={mainFile:n,runId:a.runId},v.current.onPdfChanged(),O(A.pdfUrl),C(A.pdfCompiledAt),L(A.pdfLoadingMode??"full"),v.current.onPreviewTab("pdf"),Ce(a.runId),et(n)):a.status==="failed"&&v.current.onPreviewTab(A.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(A=>{!cn(A)&&!R&&v.current.onError(de(A))}).finally(()=>{G.current===Q&&(G.current=null),R||V(!1)}),()=>{R=!0,Q.abort(),G.current===Q&&(G.current=null)}},[a?.runId,a?.status,a?.mainFile,a?.stale,n,t,x]);const Ne=async()=>{if(!e||e.permission==="read"||!l)return;const R=v.current.resolveCompileMainFile?.()||ae();if(!R||we.current.has(R)||a?.mainFile===R&&(a.status==="queued"||a.status==="running"))return;$(A=>new Set([...A,R])),v.current.onCompileStart(),le(""),ve.current?.abort(),ve.current=null,X(""),P(null),D(null),v.current.onPreviewTab(_?"pdf":"log");const Q=new AbortController;we.current.set(R,Q);try{if(!await v.current.save())return;const A=await ce(`/api/projects/${t}/compile`,{method:"POST",signal:Q.signal,body:JSON.stringify({mainFile:R})});if(A.mainFile!==R||ae()!==R)return;X(A.log),P(A.diagnostics),D(A.cancelled?"cancelled":A.ok?"succeeded":"failed"),A.cancelled&&le(x("compileControls.cancelled")),A.skipped&&le(x("editor.upToDate")),A.ok&&A.stale&&le(x("editor.compileSnapshotStale")),A.pdfUrl?(A.ok&&(Re.current={mainFile:R,runId:A.runId}),v.current.onPdfChanged(),O(A.pdfUrl),C(A.pdfCompiledAt),L(A.pdfLoadingMode??"full"),v.current.onPreviewTab("pdf"),A.ok&&(A.skipped?v.current.onCompileSuccess():Ce(A.runId))):v.current.onPreviewTab(A.diagnostics.errors.length?"errors":"log")}catch(A){!cn(A)&&ae()===R&&v.current.onError(de(A))}finally{we.current.get(R)===Q&&(we.current.delete(R),$(A=>{const ie=new Set(A);return ie.delete(R),ie}),z(A=>{if(!A.has(R))return A;const ie=new Set(A);return ie.delete(R),ie}))}},xe=async()=>{if(!e||e.permission==="read"||!l)return;const R=ae();if(R){z(Q=>new Set([...Q,R]));try{(await ce(`/api/projects/${t}/compile/cancel`,{method:"POST",body:JSON.stringify({mainFile:R})})).cancelled||z(A=>{const ie=new Set(A);return ie.delete(R),ie})}catch(Q){z(A=>{const ie=new Set(A);return ie.delete(R),ie}),!cn(Q)&&ae()===R&&v.current.onError(de(Q))}}},dt=async R=>{if(!e||e.permission==="read"||!l||ye)return;const Q=ae();if(!(!Q||we.current.has(Q)||a?.mainFile===Q&&(a.status==="queued"||a.status==="running"))){T(!0),I.current?.abort(),G.current?.abort(),Ae.current?.abort(),ve.current?.abort();try{if((await ce(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:Q,mode:R})})).mainFile!==Q||ae()!==Q)return;v.current.onSharedState(null),R==="artifacts"&&(Re.current=null,X(""),P(null),D(null),O(""),C(null),L("full"),ee([]),J(null),v.current.onPdfChanged()),le(x(R==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(A){!cn(A)&&ae()===Q&&v.current.onError(de(A))}finally{T(!1)}}};Ee.current=()=>{Ne()},h.useEffect(()=>{if(!se)return;const R=window.setTimeout(()=>le(""),3e3);return()=>window.clearTimeout(R)},[se]),h.useEffect(()=>{const R=Q=>{if(!(!(Q.ctrlKey||Q.metaKey)||Q.key.toLocaleLowerCase()!=="s")){if(bw(Q.target)){Q.preventDefault();return}Q.preventDefault(),Q.stopPropagation(),Q.repeat||Ee.current()}};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[]),h.useEffect(()=>()=>{I.current?.abort(),G.current?.abort(),Ae.current?.abort(),ve.current?.abort();for(const R of he.current)R.abort();he.current.clear();for(const R of we.current.values())R.abort();we.current.clear()},[]);const We=async R=>{if(!R.viewable)return;ve.current?.abort();const Q=new AbortController;ve.current=Q,ge(!0);try{const A=await ce(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(R.path)}`,{signal:Q.signal});!Q.signal.aborted&&ve.current===Q&&be.current===n&&J(A)}catch(A){cn(A)||v.current.onError(de(A))}finally{ve.current===Q&&(ve.current=null,ge(!1))}};return{pdfUrl:_,pdfCompiledAt:Y,pdfLoadingMode:j,pdfLoading:S,compileLog:K,compileDiagnostics:B,compileOutcome:oe,artifacts:U,artifactPreview:te,artifactLoading:fe,editorNotice:se,localCompiling:me.has(n),cancelling:M.has(n),cleaning:ye,compile:Ne,cancelCompile:xe,cleanCompile:dt,viewArtifact:We}}const qi=10*1024*1024,Sw=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 ia(t){return t instanceof Error&&t.name==="AbortError"}function hs(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function un(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function kw(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!Sw.has(e)}function Bn(t){return/(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function oa(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":kw(t)?"text":"unsupported"}function Cw(t,e){return`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`}function jw({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:l,onActiveFile:a,onActiveMainFile:c,onRootDocuments:u}){const{t:f}=Ke(),[d,p]=h.useState([]),[w,g]=h.useState(!1),[b,x]=h.useState(""),[_,O]=h.useState(null),[S,V]=h.useState(!1),[Y,C]=h.useState(!1),[j,L]=h.useState(""),[K,X]=h.useState(""),[B,P]=h.useState(""),[oe,D]=h.useState(new Set),[U,ee]=h.useState(null),[te,J]=h.useState(""),[fe,ge]=h.useState(""),[ye,T]=h.useState(null),[me,$]=h.useState(!1),[M,z]=h.useState(null),[se,le]=h.useState(!1),be=h.useRef(null),Ie=h.useRef(null),I=async(v={})=>{be.current?.abort(),be.current=null;const ae=v.signal?null:new AbortController;ae&&(be.current=ae);try{const Ce=await ce(`/api/projects/${t}/files`,{signal:v.signal??ae?.signal});return(!v.isCurrent||v.isCurrent())&&p(Ce.files),Ce.files}catch(Ce){if(!ia(Ce))throw Ce;return}finally{ae&&be.current===ae&&(be.current=null)}},G=async()=>{if(!(!b.trim()||b.trim().endsWith("/"))){X("");try{await ce(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:b,content:""})}),await I(),a(b),D(v=>new Set([...v,...hs(b)])),g(!1),x("")}catch(v){X(de(v))}}},Re=async()=>{if(!j.trim())return;X("");const v=B?`${B}/${j.trim()}`:j.trim();try{const ae=await ce(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:v})});await I(),D(Ce=>new Set([...Ce,...hs(ae.path),ae.path])),P(ae.path),C(!1),L("")}catch(ae){X(de(ae))}},F=async(v,ae=new Set,Ce=B)=>{if(!v.length)return;const et=e.maxUploadSizeMB;if(v.find(ie=>ie.size>et*1024*1024))return i(f("errors.fileTooLarge",{size:et}));const xe=Ce,dt=v.map(ie=>xe?`${xe}/${ie.name}`:ie.name),We=new Map;for(const ie of dt)We.set(ie,(We.get(ie)??0)+1);const R=[...We.entries()].filter(([,ie])=>ie>1).map(([ie])=>ie);if(R.length)return i(f("errors.duplicateUploadNames",{files:R.join(", ")}));const Q=new Set(d.map(ie=>ie.path)),A=[...new Set(dt.filter(ie=>Q.has(ie)&&!ae.has(ie)))];if(A.length){z({files:v,directory:xe,collisions:A});return}z(null),le(!0);try{const ie=new URLSearchParams;xe&&ie.set("directory",xe);let ht="";for(const[ft,Xe]of v.entries()){const ot=dt[ft];ie.delete("overwrite"),ae.has(ot)&&ie.set("overwrite","1");const jt=ie.toString()?`?${ie.toString()}`:"",pe=new FormData;pe.append("file",Xe);try{const N=await ce(`/api/projects/${t}/upload${jt}`,{method:"POST",body:pe});typeof N.path=="string"&&Bn(N.path)&&(ht=N.path)}catch(N){if(N instanceof ji&&N.status===409&&!ae.has(ot)&&N.code==="FILE_EXISTS"){ft>0&&await I(),z({files:v.slice(ft),directory:xe,collisions:[ot]});return}throw N}}await I(),ht&&a(ht)}catch(ie){i(de(ie))}finally{le(!1)}},Pe=async v=>{await F(Array.from(v.target.files??[])),v.target.value=""},Ae=async v=>{Ie.current?.abort(),Ie.current=null,V(!1);const ae=Cw(t,v.path);if((v.size??0)>qi){O({path:v.path,kind:"large",size:v.size??0,url:ae});return}const Ce=oa(v.path);if(Ce!=="text"){O({path:v.path,kind:Ce,size:v.size??0,url:ae});return}O({path:v.path,kind:Ce,size:v.size??0,url:ae,content:""}),V(!0);const et=new AbortController;Ie.current=et;try{let Ne;try{Ne=await fetch(ae,{signal:et.signal})}catch(We){throw Wd(We)}const xe=Ne.headers.get("content-type")??"";if(!Ne.ok){let We=null;try{We=xe.includes("application/json")?await Ne.json():await Ne.text()}catch{}throw new ji(qd(We,Ne.status),Ne.status,Hd(We))}const dt=await Ne.text();O(We=>We?.path===v.path?{...We,content:dt}:We)}catch(Ne){ia(Ne)||(O(null),i(de(Ne)))}finally{Ie.current===et&&(Ie.current=null,V(!1))}},ve=v=>{const ae=oa(v.path),Ce=e.maxCollaborativeFileSizeMB*1024*1024;(v.size??0)>qi||Bn(v.path)&&(v.size??0)>Ce||ae!=="text"||!Bn(v.path)?Ae(v):a(v.path)},he=async()=>{if(!U)return;const v=te.trim();if(v){X("");try{if(!await r())return;const ae=await ce(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:U.path,destinationDirectory:fe,destinationName:v})}),Ce=xe=>xe===U.path?ae.path:xe.startsWith(`${U.path}/`)?`${ae.path}${xe.slice(U.path.length)}`:xe;a(xe=>Ce(xe)),c(xe=>Ce(xe)),u(xe=>new Set([...xe].map(Ce))),P(xe=>xe&&Ce(xe));const[et,Ne]=await Promise.all([ce(`/api/projects/${t}/files`),ce(`/api/projects/${t}`)]);p(et.files),l(Ne.project),D(xe=>new Set([...xe,...hs(ae.path),fe].filter(Boolean))),ee(null),J(""),ge("")}catch(ae){X(de(ae))}}},we=async()=>{if(ye){X("");try{if(s&&!await r())return;await ce(`/api/projects/${t}/file?path=${encodeURIComponent(ye.path)}`,{method:"DELETE"}),T(null)}catch(v){X(de(v))}}};h.useEffect(()=>()=>{be.current?.abort(),Ie.current?.abort()},[]),h.useEffect(()=>{Ie.current?.abort(),Ie.current=null,V(!1)},[n]);const Be=d.filter(v=>v.type==="directory"),Ee=d.filter(v=>hs(v.path).every(ae=>oe.has(ae)));return{files:d,setFiles:p,loadFiles:I,newFileOpen:w,setNewFileOpen:g,newFilePath:b,setNewFilePath:x,resourcePreview:_,setResourcePreview:O,resourcePreviewLoading:S,setResourcePreviewLoading:V,newFolderOpen:Y,setNewFolderOpen:C,newFolderName:j,setNewFolderName:L,fileDialogError:K,setFileDialogError:X,selectedFolder:B,setSelectedFolder:P,expandedFolders:oe,setExpandedFolders:D,moveEntry:U,setMoveEntry:ee,moveName:te,setMoveName:J,moveDestination:fe,setMoveDestination:ge,deleteEntry:ye,setDeleteEntry:T,fileDragActive:me,setFileDragActive:$,uploadConflict:M,setUploadConflict:z,uploadingFiles:se,directoryEntries:Be,visibleEntries:Ee,createFile:G,createFolder:Re,uploadFiles:F,upload:Pe,openFile:ve,movePath:he,removePath:we}}function vw({active:t,projectId:e,activeFile:n,content:s,dictionaryWords:r}){const[i,l]=h.useState([]),[a,c]=h.useState(""),[u,f]=h.useState(""),[d,p]=h.useState(0),[w,g]=h.useState(null),[b,x]=h.useState(null),[_,O]=h.useState(!1),[S,V]=h.useState(0),Y=h.useRef(0),C=h.useRef(!1),j=h.useRef(!1),L=h.useRef(s),K=h.useRef(n),X=h.useRef(0);L.current=s,K.current=n,j.current=_,h.useEffect(()=>{l([]),c(""),f(""),g(null),x(null),O(!1)},[n,r]),h.useEffect(()=>{x(null),O(!1)},[e]),h.useEffect(()=>{p(D=>i.length?Math.min(D,i.length-1):0)},[i]),h.useEffect(()=>{const D=++Y.current;if(!t||!n){l([]),c(""),f(""),g(null);return}if(b){l([]),c(""),f("");return}const U=s,ee=n;let te=!1;const J=window.setTimeout(()=>{x(null),(async()=>{try{const{lintLatex:fe,isHarperLintSupersededError:ge}=await Ct(async()=>{const{lintLatex:T,isHarperLintSupersededError:me}=await import("./spellCheck-BfZEnpwY.js");return{lintLatex:T,isHarperLintSupersededError:me}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));if(te||D!==Y.current||L.current!==U||K.current!==ee)return;let ye;try{ye=await fe(e,ee,U,r)}catch(T){if(ge(T))return;throw T}if(te||D!==Y.current||L.current!==U||K.current!==ee)return;C.current=!1,O(!1),l(ye),c(U),f(ee),p(0),g(null)}catch(fe){if(te||D!==Y.current||L.current!==U||K.current!==ee)return;l([]),c(""),f(""),x(fe instanceof Error?fe.message:String(fe));const ge=C.current;C.current=!1,O(ge?j.current:!1)}})()},700);return()=>{te=!0,window.clearTimeout(J)}},[t,e,n,s,r,S,b]),h.useEffect(()=>{if(!b||!t)return;let D=!1;const U=()=>{D||(D=!0,C.current=!0,x(null),V(te=>te+1))},ee=window.setTimeout(U,15e3);return window.addEventListener("online",U,{once:!0}),()=>{window.clearTimeout(ee),window.removeEventListener("online",U)}},[b,t]);const B=u===n&&a===s,P=h.useMemo(()=>B?{total:i.length,unique:new Set(i.map(D=>`${D.kind}:${D.word.toLocaleLowerCase("en-US")}`)).size}:null,[B,i]);return{issues:B?i:[],jump:B?w:null,index:d,summary:P,jumpToIssue:D=>{if(!i.length)return;const U=Math.max(0,Math.min(D,i.length-1)),ee=i[U];p(U),g({from:ee.from,to:ee.to,nonce:++X.current})},error:_?null:b,nativeFallback:t&&!!b,retry:()=>{C.current=!1,x(null),O(!1),V(D=>D+1)},dismissError:()=>{C.current=!1,O(!0)}}}function la(t){return t instanceof Error&&t.name==="AbortError"}function Ew({projectId:t,mainFile:e,activeFile:n,onActiveFile:s,onError:r,onShowPdf:i}){const[l,a]=h.useState(null),[c,u]=h.useState(null),[f,d]=h.useState(null),p=h.useRef(null),w=h.useRef(0),g=h.useRef(n),b=h.useRef(s),x=h.useRef(r),_=h.useRef(i),O=j=>j===e&&/\.tex$/i.test(j);g.current=n,b.current=s,x.current=r,_.current=i,h.useEffect(()=>(p.current?.abort(),p.current=null,a(null),u(null),d(null),()=>p.current?.abort()),[t,e]);const S=(j,L,K)=>{d({path:j,line:L,column:K,nonce:++w.current}),g.current!==j&&b.current(j)},V=async(j,L,K,X={})=>{if(!O(j))return;p.current?.abort();const B=new AbortController;p.current=B;try{const P=await ce(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(j)}&line=${L}&column=${K}`,{signal:B.signal});if(p.current!==B||!P)return;a({...P,nonce:++w.current}),_.current()}catch(P){!la(P)&&!X.silent&&x.current(de(P))}finally{p.current===B&&(p.current=null)}},Y=async(j,L,K)=>{if(!O(g.current))return;const X=g.current;p.current?.abort();const B=new AbortController;p.current=B;try{const P=await ce(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${j}&x=${L}&y=${K}`,{signal:B.signal});if(p.current!==B||g.current!==X||!O(g.current))return;S(P.path,P.line,P.column)}catch(P){la(P)||x.current(de(P))}finally{p.current===B&&(p.current=null)}};return{pdfTarget:l,pdfViewport:c,sourceJump:f,setPdfViewport:u,clearPdfViewport:()=>u(null),jumpToSource:S,syncSourceToPdf:V,syncPdfToSource:Y,syncVisiblePdfToSource:()=>{c&&Y(c.page,c.x,c.y)}}}function tu(t,e){return`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function aa(t,e){try{const n=window.localStorage.getItem(tu(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function Dw(t,e){const[n,s]=h.useState(()=>aa(t,e));return h.useEffect(()=>{s(aa(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(tu(t,e),i)}catch{}}}}function ca(t){const n=t.split(/(?<=\n)/).map(s=>{for(let r=0;r<s.length;r+=1){if(s[r]!=="%")continue;let i=0;for(let l=r-1;l>=0&&s[l]==="\\";l-=1)i+=1;if(i%2===0)return s.slice(0,r)+(s.endsWith(`
|
|
11
|
-
`)?`
|
|
12
|
-
`:"")}return s}).join("").replace(/\\verb\*?([^\s]).*?\1/g,"").replace(/\\begin\{(?:verbatim\*?|Verbatim|lstlisting|minted)\}(?:\[[^\]]*\])?[\s\S]*?\\end\{(?:verbatim\*?|Verbatim|lstlisting|minted)\}/g,"");return/\\documentclass\s*(?:\[[^\]]*\]\s*)?\{/.test(n)}function _w({sessions:t,status:e}){const{t:n}=Ke(),[s,r]=h.useState(!1),i=Math.max(0,t.length-5),l=s&&i>0,a=l?t:t.slice(0,5);return h.useEffect(()=>{t.length<=5&&r(!1)},[t.length]),t.length<=1?null:o.jsxs("div",{className:`collaboration-presence collaboration-${e}`,title:n(`editor.collaboration.${e}`),children:[o.jsx("span",{className:"collaboration-status-dot","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"),d=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},title:d,"aria-label":d,tabIndex:0,children:[gw(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 Tw({value:t,onChange:e}){const{t:n}=Ke(),[s,r]=h.useState(!1),i=h.useRef(null),l=[{value:"editor-pdf",icon:wl},{value:"editor-only",icon:mh},{value:"pdf-only",icon:gh}];return h.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(wl,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(ma,{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(Gd,{size:16})]},a.value)})]})]})}function Lw({site:t,project:e,activeFile:n,saveStateLabel:s,editorPreferences:r,activeSessions:i,collaborationStatus:l,reconnectCollaboration:a,protocolUpgradeRequired:c,showEditor:u,filesCollapsed:f,toggleFilesPanel:d,workspaceLayout:p,changeWorkspaceLayout:w,onBack:g,onShare:b,showCitationLibrary:x,citationLibraryOpen:_,onCitationLibrary:O,onSelectionHistory:S,onHistory:V,onGit:Y,canManageGit:C,formatting:j,readOnly:L,collaborationSynced:K,hasSelection:X,onAddComment:B,onToggleComments:P,commentsOpen:oe,unresolvedCommentCount:D,hasActiveFile:U,onToggleSettings:ee,settingsOpen:te,compileBusy:J,sharedCompiling:fe,localCompiling:ge,cancelling:ye,compileState:T,onCompile:me,onCancelCompile:$}){const{t:M}=Ke();return o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:M("editor.backToProjects"),"aria-label":M("editor.backToProjects"),onClick:g,children:o.jsx(Yd,{size:18})}),o.jsx("a",{className:"brand-link compact-brand-link",href:"/","aria-label":t.siteName,onClick:z=>{z.preventDefault(),g()},children:o.jsx(Vd,{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:M("editor.vimOnHint"),children:[o.jsx(fh,{size:14}),M("editor.vimOn")]}),o.jsx(_w,{sessions:i,status:l}),l==="disconnected"&&!c&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:M("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:a,children:M("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[u&&o.jsxs("button",{className:f?"":"active",onClick:d,children:[f?o.jsx(ph,{size:15}):o.jsx(ya,{size:15}),M("common.files")]}),o.jsx(Tw,{value:p,onChange:w}),o.jsxs("button",{onClick:b,children:[o.jsx(vi,{size:15}),M("projectSettings.share")]}),x&&o.jsxs("button",{className:_?"active":"",onClick:O,children:[o.jsx(Xd,{size:15}),M("citationLibrary.title")]}),o.jsxs("div",{className:"history-action",role:"group","aria-label":M("history.title"),children:[o.jsxs("div",{className:"history-action-label",children:[o.jsx(dh,{size:14}),o.jsx("span",{children:M("history.title")})]}),o.jsxs("div",{className:"history-action-options",children:[o.jsx("button",{type:"button",className:"history-action-selection",title:M(X?"selectionHistory.title":"selectionHistory.selectSourceHint"),onMouseDown:z=>z.preventDefault(),onClick:S,disabled:!X||!U,children:M("selectionHistory.buttonLabel")}),o.jsx("button",{type:"button",className:"history-action-snapshots",title:M("history.projectSnapshots"),onClick:V,children:M("history.projectSnapshotsButton")})]})]}),o.jsxs("div",{className:"comments-action",role:"group","aria-label":M("common.comments"),children:[o.jsxs("div",{className:"comments-action-label",children:[o.jsx(Qd,{size:14}),o.jsx("span",{children:M("common.comments")})]}),o.jsxs("div",{className:"comments-action-options",children:[o.jsx("button",{type:"button",className:"comments-action-add",title:M("editor.addComment"),"aria-label":M("editor.addComment"),onMouseDown:z=>z.preventDefault(),onClick:B,disabled:!U,children:M("editor.commentsAdd")}),o.jsxs("button",{type:"button",className:`comments-action-all${oe?" active":""}`,title:M("editor.commentsAll"),onClick:P,children:[M("editor.commentsAll")," ",D||""]})]})]}),o.jsxs("button",{className:"git-action",title:M(C?"git.title":"git.ownerOnly"),disabled:!C,onClick:Y,children:[o.jsx(Zd,{size:15}),"Git"]}),o.jsxs("button",{className:te?"active":"",onClick:ee,children:[o.jsx(Sh,{size:15}),M("common.settings")]}),fe||ge?o.jsxs("button",{className:"compile cancel-compile",title:M("compileControls.cancel"),onClick:$,disabled:ye||j||L||!K,children:[ye?o.jsx(tt,{className:"spin",size:15}):o.jsx(ws,{size:15}),M(ye?"compileControls.cancelling":"compileControls.cancel")]}):o.jsxs("button",{className:"compile",title:M("editor.compileShortcut"),onClick:me,disabled:J||j||L||!K,children:[J?o.jsx(tt,{className:"spin",size:15}):o.jsx(wh,{size:15}),M("editor.compile",{engine:e.engine})]})]})]})}function Rw({project:t,filesPanel:e,files:n,visibleEntries:s,activeFile:r,activeMainFile:i,rootDocuments:l,selectedFolder:a,expandedFolders:c,fileDragActive:u,uploadingFiles:f,readOnly:d,formatting:p,canFormat:w,activeFormatLease:g,collaborationSynced:b,editorFontSize:x,outline:_,sourceCursorStore:O,wordCountBusy:S,hasSelection:V,hasFormatSelection:Y,uploadInput:C,setSelectedFolder:j,setExpandedFolders:L,setMoveEntry:K,setMoveName:X,setMoveDestination:B,setDeleteEntry:P,setFileDialogError:oe,setNewFolderName:D,setNewFolderOpen:U,setNewFilePath:ee,setNewFileOpen:te,setQuickOpen:J,setProjectSearchOpen:fe,setFileDragActive:ge,setFilesCollapsed:ye,toggleFilesPanel:T,uploadFiles:me,upload:$,openFile:M,onFormatFile:z,onFormatSelection:se,jumpToSource:le,syncSourceToPdf:be,onWordCount:Ie}){const{t:I}=Ke(),[G,Re]=h.useState(!1);return o.jsx(gr,{id:"files",order:1,ref:e,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>ye(!0),onExpand:()=>ye(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${u?" drop-active":""}`,onDragEnter:F=>{F.dataTransfer.types.includes("Files")&&(F.preventDefault(),!d&&!f&&ge(!0))},onDragOver:F=>{F.dataTransfer.types.includes("Files")&&(F.preventDefault(),F.dataTransfer.dropEffect=d||f?"none":"copy")},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||ge(!1)},onDrop:F=>{F.preventDefault(),ge(!1),!d&&!f&&me(Array.from(F.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsx("button",{className:"file-size-toggle",type:"button","aria-pressed":G,title:I(G?"editor.hideFileSizes":"editor.showFileSizes"),onClick:()=>Re(F=>!F),children:I("common.files")}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{"aria-label":I("navigation.quickOpen"),title:`${I("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>J(!0),children:o.jsx(eh,{size:15})}),o.jsx("button",{"aria-label":I("navigation.projectSearch"),title:`${I("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>fe(!0),children:o.jsx(oh,{size:15})}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:f,"aria-label":I("editor.uploadAttachment"),title:I("editor.uploadTo",{folder:a||I("editor.projectRoot")}),onClick:()=>C.current?.click(),children:o.jsx(pl,{size:15})}),o.jsx("button",{"aria-label":I("editor.newFolder"),title:I("editor.newFolder"),onClick:()=>{D(""),U(!0)},children:o.jsx(th,{size:15})}),o.jsx("button",{"aria-label":I("editor.newFile"),title:I("editor.newFile"),onClick:()=>{ee(a?`${a}/`:""),te(!0)},children:o.jsx(hh,{size:15})}),o.jsx("input",{ref:C,type:"file",multiple:!0,hidden:!0,onChange:F=>{$(F)}})]}),o.jsx("button",{"aria-label":I("editor.collapseFiles"),title:I("editor.collapseFiles"),onClick:T,children:o.jsx(ya,{size:15})})]})]}),u&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(pl,{size:24}),o.jsx("strong",{children:I("editor.dropFiles")}),o.jsx("span",{children:I("editor.uploadTo",{folder:a||I("editor.projectRoot")})})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${x}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${a===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>j(""),children:[o.jsx(nh,{size:15}),o.jsx("span",{children:I("editor.projectRoot")})]})}),s.map(F=>{const Pe=F.path.split("/").length-1,Ae=F.path.split("/").at(-1),ve=c.has(F.path),he=l.has(F.path),we=i===F.path,Be=F.path!==t.mainFile&&!t.mainFile.startsWith(`${F.path}/`);return F.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${a===F.path?" selected":""}`,style:{paddingLeft:`${Pe*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",title:F.path,onClick:()=>{j(F.path),L(Ee=>{const v=new Set(Ee);return v.has(F.path)?v.delete(F.path):v.add(F.path),v})},children:[ve?o.jsx(ma,{size:13}):o.jsx(sh,{size:13}),o.jsx(rh,{size:14}),o.jsx("span",{children:Ae})]}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:I("editor.move"),"aria-label":I("editor.move"),onClick:()=>{K(F),X(Ae??""),B("")},children:o.jsx(bl,{size:13})}),Be&&o.jsx("button",{className:"file-entry-action danger-text",title:I("editor.deletePath"),"aria-label":I("editor.deletePath"),onClick:()=>{P(F),oe("")},children:o.jsx(Xt,{size:13})})]})]},F.path):o.jsxs("div",{className:`file-entry${r===F.path?" active":""}${he?" root-document":""}${we?" compile-target":""}`,style:{paddingLeft:`${Pe*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",title:we?I("editor.currentMainDocument",{path:F.path}):he?I("editor.mainDocumentCandidate",{path:F.path}):F.path,onClick:()=>M(F),children:[he?o.jsx(pa,{size:13}):o.jsx(Wn,{size:13}),o.jsx("span",{children:Ae}),we&&o.jsx("small",{children:I("editor.currentMainShort")})]}),G&&typeof F.size=="number"&&o.jsx("span",{className:"file-entry-size",title:`${F.size.toLocaleString()} B`,children:Nw(F.size)}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:I("editor.move"),"aria-label":I("editor.move"),onClick:()=>{K(F),X(Ae??""),B("")},children:o.jsx(bl,{size:13})}),Be&&o.jsx("button",{className:"file-entry-action danger-text",title:I("editor.deletePath"),"aria-label":I("editor.deletePath"),onClick:()=>{P(F),oe("")},children:o.jsx(Xt,{size:13})})]})]},F.path)})]}),!d&&w&&o.jsxs("div",{className:"file-format-footer",role:"group","aria-label":I("editor.format"),"aria-busy":p,children:[o.jsxs("div",{className:"file-format-label",children:[o.jsx(ch,{size:13}),I("editor.format")]}),o.jsxs("div",{className:"file-format-actions",children:[o.jsx("button",{className:Y?"":"active",type:"button",title:I("editor.formatFileHint"),onMouseDown:F=>F.preventDefault(),onClick:z,disabled:p||g||!b,children:I("editor.formatFile")}),o.jsx("button",{className:Y?"active":"",type:"button",title:I(Y?"editor.formatSelection":"editor.formatSelectionHint"),onMouseDown:F=>F.preventDefault(),onClick:se,disabled:p||g||!b||!Y,children:I("editor.formatSelected")})]})]})]}),o.jsx(Aw,{outline:_,activeFile:r,activeMainFile:i,sourceCursorStore:O,wordCountBusy:S,hasSelection:V,jumpToSource:le,syncSourceToPdf:be,onWordCount:Ie})]})})}function Aw({outline:t,activeFile:e,activeMainFile:n,sourceCursorStore:s,wordCountBusy:r,hasSelection:i,jumpToSource:l,syncSourceToPdf:a,onWordCount:c}){const{t:u}=Ke(),f=h.useSyncExternalStore(s.subscribe,s.getOutlineLine,s.getOutlineLine);return o.jsxs("section",{className:"outline-panel",children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("span",{className:"outline-heading",children:[o.jsx(ih,{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(tt,{className:"spin",size:12}):o.jsx(yl,{size:12}),u("editor.wordCountFull")]}),o.jsxs("button",{type:"button",title:u("editor.wordCountSelectionHint"),onClick:()=>c("selection"),disabled:r||!i,children:[r?o.jsx(tt,{className:"spin",size:12}):o.jsx(yl,{size:12}),u("editor.wordCountSelection")]})]})]}),o.jsxs("div",{className:"outline",children:[t.map((d,p)=>o.jsxs("button",{className:`outline-item${e===d.path&&f===d.line?" current":""}`,title:`${d.path}:${d.line}`,onClick:()=>{l(d.path,d.line,1),a(d.path,d.line,1)},children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${d.level*12}px`}}),o.jsx("small",{children:d.path===e?d.line:d.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:d.title})]},`${d.path}-${d.line}-${p}`)),t.length===0&&o.jsx("p",{className:"muted padded",children:u("editor.noOutline")})]})]})}function Nw(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 Ow=h.lazy(()=>Ct(()=>import("./LatexEditor-Bq76v8sO.js"),__vite__mapDeps([9,2,10,1,3,4,5,6,7,8])).then(t=>({default:t.LatexEditor})));function Fw({project:t,activeFile:e,activeMainFile:n,openTabs:s,content:r,loadedFile:i,readOnly:l,comments:a,focusComment:c,editorPreferences:u,completionIndex:f,nativeSpellCheck:d,spellCheckIssues:p,spellCheckJump:w,sourceJump:g,collaborativeText:b,collaborationAwareness:x,undoManager:_,editorNotice:O,activateTab:S,closeTab:V,handleTabKeyDown:Y,updateEditorContent:C,setSelection:j,onCommentClick:L,onSpellCheckReplace:K,onCursor:X}){const{t:B}=Ke();return o.jsx(gr,{id:"source",order:2,defaultSize:42,minSize:22,children:o.jsxs("main",{className:"source-panel",children:[u.openFilesInTabs&&s.length>0&&o.jsx("div",{className:"editor-tabs-bar",role:"tablist","aria-label":B("editor.openFiles"),children:o.jsx("div",{className:"editor-tabs-scroll",children:s.map((P,oe)=>{const D=P===e,U=P===(n||t.mainFile),ee=P.split("/").at(-1)||P;return o.jsxs("div",{className:`editor-tab-item${D?" active":""}`,role:"presentation",children:[o.jsxs("button",{id:`editor-tab-${encodeURIComponent(P)}`,type:"button",role:"tab","aria-selected":D,"aria-controls":"editor-source-content",tabIndex:D?0:-1,className:`editor-tab${D?" active":""}${U?" main-tab":""}`,onClick:()=>S(P),onKeyDown:te=>Y(te,oe),title:P,children:[o.jsx("span",{className:"editor-tab-icon",children:U?o.jsx(pa,{size:13}):o.jsx(Wn,{size:13})}),o.jsx("span",{className:"editor-tab-title",children:ee}),U&&o.jsx("small",{className:"editor-tab-badge",children:B("editor.currentMainShort")})]}),o.jsx("button",{type:"button",className:"editor-tab-close",title:B("common.close"),"aria-label":`${B("common.close")} ${ee}`,onClick:()=>V(P),children:o.jsx(ws,{size:12})})]},P)})})}),o.jsxs("div",{id:"editor-source-content",className:"editor-content-container",children:[o.jsx(h.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(tt,{className:"spin",size:22}),o.jsx("span",{children:B("common.loading")})]}),children:o.jsx(Ow,{value:r,filePath:e,readOnly:l,comments:a,focusComment:c,preferences:u,nativeSpellCheck:d,completionIndex:f,spellCheckIssues:p,spellCheckJump:w,jumpTo:i===e&&g?.path===e?g:null,searchRequest:0,collaboration:b?{text:b,awareness:x,undoManager:l?void 0:_}:void 0,onChange:C,onSelection:j,onCommentClick:L,onSpellCheckReplace:K,onCursor:X},e)}),O&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:O})]})]})})}function ua({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=Ke(),l=s==="error"?Vi:Pt;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((a,c)=>{const u=Iw(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 ki({lines:t,empty:e,tone:n="log"}){const s=n==="error"?Vi:n==="warning"?Pt:Ei;return t.length?o.jsx("pre",{className:`compile-output compile-${n}`,children:t.join(`
|
|
13
|
-
`)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function Mw({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:l}=Ke(),a=c=>`/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(Wn,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:c.path}),o.jsx("small",{children:Pw(c.size)})]})]}),o.jsx("a",{href:a(c.path),title:l("editor.downloadArtifact"),"aria-label":l("editor.downloadArtifact"),children:o.jsx(Qs,{size:14})})]},c.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(tt,{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(Qs,{size:13}),l("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Wn,{size:24}),o.jsx("span",{children:l("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(wa,{size:26}),o.jsx("span",{children:l("editor.noArtifacts")})]})}function $w({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=Ke();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(Pt,{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(Di,{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(tt,{className:"spin",size:14}):o.jsx(Di,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(Xt,{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(tt,{className:"spin",size:14}):o.jsx(Xt,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function Iw(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 Pw(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const Uw=h.lazy(()=>ha().then(t=>({default:t.PdfPreview})));function zw({projectId:t,activeMainFile:e,previewTab:n,diagnosticTab:s,pdfUrl:r,pdfLoadingMode:i,pdfLoading:l,pdfCompiledAt:a,pdfCompiledLabel:c,pdfTargetLabel:u,pdfDownloadUrl:f,pdfTarget:d,pdfViewport:p,activeFile:w,compileBusy:g,compileLog:b,compileDiagnostics:x,compileMessages:_,artifacts:O,artifactPreview:S,artifactLoading:V,cleaning:Y,readOnly:C,collaborationSynced:j,workspaceLayout:L,showSyncResize:K,diagnosticCount:X,selectPreviewTab:B,changeWorkspaceLayout:P,onSetNotice:oe,onSetPdfViewport:D,syncVisiblePdfToSource:U,syncCurrentSourceToPdf:ee,syncPdfToSource:te,canSyncWithPdf:J,files:fe,jumpToSource:ge,onSetCleanMode:ye,cleanCompile:T,viewArtifact:me}){const{t:$}=Ke();return o.jsxs(o.Fragment,{children:[K&&o.jsxs(Hi,{className:"resize-handle sync-resize-handle",children:[o.jsx(ga,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:M=>M.stopPropagation(),children:[o.jsx("button",{disabled:!p||!J,title:$(J?"editor.showInSource":"editor.syncTexOnlyForMain"),"aria-label":$("editor.showInSource"),onClick:()=>{if(!J){oe($("editor.syncTexOnlyForMain"));return}U()},children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!w||!r||!J,title:$(J?"editor.showInPdf":"editor.syncTexOnlyForMain"),"aria-label":$("editor.showInPdf"),onClick:()=>{if(!J){oe($("editor.syncTexOnlyForMain"));return}ee()},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),o.jsx(gr,{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":$("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":n==="pdf",className:`pdf-tab${n==="pdf"?" active":""}`,onClick:()=>B("pdf"),title:a?$("editor.pdfCompiledAtFor",{file:e,time:new Date(a).toLocaleString(fs.resolvedLanguage)}):$("editor.currentMainDocument",{path:e}),children:[o.jsx(Wn,{size:16}),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:()=>B("diagnostics"),children:[o.jsx(Ei,{size:14}),$("editor.outputTabs"),o.jsx("span",{children:X})]})]}),f&&o.jsxs("a",{className:"pdf-download-top",href:f,download:!0,title:$("editor.downloadPdf"),"aria-label":$("editor.downloadPdf"),children:[o.jsx(Qs,{size:15}),o.jsx("span",{children:$("editor.downloadPdf")})]})]}),n==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":$("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":s==="log",className:s==="log"?"active":"",onClick:()=>B("log"),children:[o.jsx(Ei,{size:13}),$("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":s==="warnings",className:s==="warnings"?"active":"",onClick:()=>B("warnings"),children:[o.jsx(Pt,{size:13}),$("editor.warnings"),o.jsx("span",{children:_.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="errors",className:s==="errors"?"active":"",onClick:()=>B("errors"),children:[o.jsx(Vi,{size:13}),$("editor.errors"),o.jsx("span",{children:_.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="artifacts",className:s==="artifacts"?"active":"",onClick:()=>B("artifacts"),children:[o.jsx(wa,{size:13}),$("editor.artifacts"),o.jsx("span",{children:O.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="clean",className:s==="clean"?"active":"",onClick:()=>B("clean"),children:[o.jsx(Di,{size:13}),$("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${n} ${n==="diagnostics"?`preview-${s}`:""}`,children:[n==="pdf"&&(r?o.jsx(h.Suspense,{fallback:o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(tt,{className:"spin",size:24}),o.jsx("span",{children:$("editor.loadingPdf")})]}),children:o.jsx(Uw,{url:r,loadingMode:i,target:d,compiling:g,onViewportLocation:(M,z,se)=>D({page:M,x:z,y:se}),onDoubleClickLocation:(M,z,se)=>{if(D({page:M,x:z,y:se}),!J){oe($("editor.syncTexOnlyForMain"));return}te(M,z,se)}})}):l?o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(tt,{className:"spin",size:24}),o.jsx("span",{children:$("editor.loadingPdf")})]}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Wn,{size:28}),o.jsx("strong",{children:$("editor.preview")}),o.jsx("span",{children:$("editor.previewHint")})]})),n==="diagnostics"&&s==="log"&&o.jsx(ki,{lines:b?b.split(`
|
|
14
|
-
`):[],empty:$(g?"editor.compiling":"editor.noLog")}),n==="diagnostics"&&s==="warnings"&&(x?o.jsx(ua,{tone:"warning",diagnostics:x.warnings,files:fe,empty:$("editor.noWarnings"),onJump:(M,z,se)=>{L==="pdf-only"&&P("editor-pdf"),ge(M,z,se)}}):o.jsx(ki,{tone:"warning",lines:_.warnings,empty:$("editor.noWarnings")})),n==="diagnostics"&&s==="errors"&&(x?o.jsx(ua,{tone:"error",diagnostics:x.errors,files:fe,empty:$("editor.noErrors"),onJump:(M,z,se)=>{L==="pdf-only"&&P("editor-pdf"),ge(M,z,se)}}):o.jsx(ki,{tone:"error",lines:_.errors,empty:$("editor.noErrors")})),n==="diagnostics"&&s==="artifacts"&&o.jsx(Mw,{projectId:t,mainFile:e,artifacts:O,preview:S,loading:V,onView:M=>{me(M)}}),n==="diagnostics"&&s==="clean"&&o.jsx($w,{mainFile:e,disabled:C||!j||g,cleaning:Y,onCleanCache:()=>ye("cache"),onCleanArtifacts:()=>ye("artifacts")})]})]})})]})}function Bw(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 Xs({projectId:t,value:e,onChange:n,onKeyDown:s,onFocus:r,...i}){const{t:l}=Ke(),a=h.useRef(null),[c,u]=h.useState(null),[f,d]=h.useState(!1),[p,w]=h.useState(null),[g,b]=h.useState(0),x=h.useMemo(()=>{if(!p||!c)return[];const C=p.query.toLocaleLowerCase();return(C?c.filter(L=>L.username.toLocaleLowerCase().includes(C)||L.displayName.toLocaleLowerCase().includes(C)):c).slice(0,8)},[c,p]),_=!!(p&&x.length),O=async()=>{if(!(c||f)){d(!0);try{const C=await ce(`/api/projects/${t}/mention-candidates`);u(C.users)}catch{u([])}finally{d(!1)}}},S=(C,j)=>{const L=Bw(C,j);w(L),b(0),L&&O()},V=C=>{if(!p)return;const j=`@${C.username} `,L=`${e.slice(0,p.start)}${j}${e.slice(p.end)}`,K=p.start+j.length;n(L),w(null),b(0),window.requestAnimationFrame(()=>{a.current?.focus(),a.current?.setSelectionRange(K,K)})},Y=C=>{if(!C.nativeEvent.isComposing&&_){if(C.key==="ArrowDown"){C.preventDefault(),b(j=>(j+1)%x.length);return}if(C.key==="ArrowUp"){C.preventDefault(),b(j=>(j-1+x.length)%x.length);return}if(C.key==="Enter"&&!C.ctrlKey&&!C.metaKey&&!C.shiftKey){C.preventDefault(),V(x[g]??x[0]);return}if(C.key==="Escape"){w(null);return}}s?.(C)};return o.jsxs("span",{className:"mention-textarea",children:[o.jsx("textarea",{...i,ref:a,value:e,onFocus:C=>{r?.(C),S(e,C.currentTarget.selectionStart??e.length)},onClick:C=>S(e,C.currentTarget.selectionStart??e.length),onChange:C=>{const j=C.currentTarget.value;n(j),S(j,C.currentTarget.selectionStart??j.length)},onKeyDown:Y}),_&&o.jsx("span",{className:"mention-menu",role:"listbox","aria-label":l("editor.mentionUsers"),children:x.map((C,j)=>o.jsxs("button",{type:"button",role:"option","aria-selected":j===g,className:j===g?"active":"",onMouseDown:L=>L.preventDefault(),onClick:()=>V(C),children:[o.jsx(Zs,{"aria-hidden":!0,size:13}),o.jsxs("span",{children:[o.jsx("strong",{children:C.displayName}),o.jsxs("small",{children:["(",C.username,")"]})]})]},C.id))})]})}function Ci(t,e){!(t.ctrlKey||t.metaKey)||t.key!=="Enter"||t.nativeEvent.isComposing||(t.preventDefault(),t.stopPropagation(),e())}function Ww({projectId:t,comment:e,currentUserId:n,unreadCommentMentionId:s,unreadReplyMentionIds:r,highlightedComment:i,highlightedReplyId:l,onMarkMentionRead:a,onFocus:c,onToggle:u,onReply:f,onEdit:d,onDelete:p,onEditReply:w,onDeleteReply:g}){const{t:b}=Ke(),[x,_]=h.useState(!1),[O,S]=h.useState(""),[V,Y]=h.useState(!1),[C,j]=h.useState(e.content),[L,K]=h.useState(!1),[X,B]=h.useState(null),[P,oe]=h.useState(""),[D,U]=h.useState(null),ee=async T=>{T?.preventDefault(),O.trim()&&await f(O)&&(S(""),_(!1))},te=async T=>{T?.preventDefault(),C.trim()&&await d(C)&&Y(!1)},J=async T=>{T?.preventDefault(),!(!X||!P.trim())&&await w(X,P)&&B(null)},fe=e.authorUsername,ge=T=>new Date(T).toLocaleString(fs.resolvedLanguage),ye=async(T,me)=>{me.stopPropagation(),await a(T)};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":""}`,onClick:()=>{window.getSelection()?.toString()||c()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:e.authorDisplayName??fe??b("editor.deletedUser")}),fe&&o.jsxs("small",{children:["@",fe]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toISOString(),children:ge(e.createdAt)}),e.editedAt&&o.jsx("small",{children:b("editor.editedAt",{time:ge(e.editedAt)})})]})]}),o.jsx("div",{className:"comment-location",children:e.orphaned?b("editor.orphaned"):b("editor.line",{line:e.startLine})}),e.selectedText&&o.jsx("blockquote",{className:"comment-selected-text",children:e.selectedText}),V?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:T=>{te(T)},onClick:T=>T.stopPropagation(),children:[o.jsx(Xs,{projectId:t,autoFocus:!0,rows:4,value:C,onChange:j,onKeyDown:T=>Ci(T,te)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>Y(!1),children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!C.trim(),children:[o.jsx(xl,{size:13}),b("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:e.content}),s&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(Zs,{"aria-hidden":!0,size:12}),b("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:T=>{ye(s,T)},children:b("editor.markMentionRead")})]}),e.replies.length>0&&o.jsx("div",{className:"comment-replies",children:e.replies.map(T=>{const me=r?.get(T.id);return o.jsxs("div",{"data-comment-reply-id":T.id,className:`comment-reply${l===T.id?" mention-target":""}`,children:[o.jsxs("header",{children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:T.authorDisplayName??T.authorUsername??b("editor.deletedUser")}),T.authorUsername&&o.jsxs("small",{children:["@",T.authorUsername]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:T.createdAt,title:new Date(T.createdAt).toISOString(),children:ge(T.createdAt)}),T.editedAt&&o.jsx("small",{children:b("editor.editedAt",{time:ge(T.editedAt)})})]})]}),X===T.id?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:$=>{J($)},onClick:$=>$.stopPropagation(),children:[o.jsx(Xs,{projectId:t,autoFocus:!0,rows:3,value:P,onChange:oe,onKeyDown:$=>Ci($,J)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>B(null),children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!P.trim(),children:[o.jsx(xl,{size:13}),b("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:T.content}),me&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(Zs,{"aria-hidden":!0,size:12}),b("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:$=>{ye(me,$)},children:b("editor.markMentionRead")})]}),T.authorId===n&&X!==T.id&&o.jsxs("div",{className:"comment-owner-actions",children:[o.jsx("button",{title:b("editor.editReply"),"aria-label":b("editor.editReply"),onClick:$=>{$.stopPropagation(),B(T.id),oe(T.content)},children:o.jsx(ml,{size:12})}),o.jsx("button",{className:"danger-text",title:b("editor.deleteReply"),"aria-label":b("editor.deleteReply"),onClick:$=>{$.stopPropagation(),U(T.id)},children:o.jsx(Xt,{size:12})})]})]},T.id)})}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",onClick:T=>{T.stopPropagation(),u()},children:[e.resolved?o.jsx(bh,{size:13}):o.jsx(uh,{size:13}),e.resolved?b("editor.reopen"):b("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:T=>{T.stopPropagation(),_(me=>!me)},children:[o.jsx(yh,{size:13}),b("editor.reply")]}),e.authorId===n&&!V&&o.jsxs("span",{className:"comment-owner-actions",children:[o.jsx("button",{title:b("editor.editComment"),"aria-label":b("editor.editComment"),onClick:T=>{T.stopPropagation(),j(e.content),Y(!0)},children:o.jsx(ml,{size:13})}),o.jsx("button",{className:"danger-text",title:b("editor.deleteComment"),"aria-label":b("editor.deleteComment"),onClick:T=>{T.stopPropagation(),K(!0)},children:o.jsx(Xt,{size:13})})]})]}),x&&o.jsxs("form",{className:"comment-reply-form",onSubmit:T=>{ee(T)},onClick:T=>T.stopPropagation(),children:[o.jsx(Xs,{projectId:t,autoFocus:!0,rows:3,value:O,placeholder:b("editor.replyPlaceholder"),onChange:S,onKeyDown:T=>Ci(T,ee)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>{_(!1),S("")},children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!O.trim(),children:[o.jsx(xh,{size:13}),b("editor.sendReply")]})]})]})]}),o.jsx(gs,{open:L,title:b("editor.deleteCommentTitle"),description:b("editor.deleteCommentDescription",{count:e.replies.length}),confirmLabel:b("common.delete"),danger:!0,onCancel:()=>K(!1),onConfirm:()=>{p().then(T=>{T&&K(!1)})}}),o.jsx(gs,{open:!!D,title:b("editor.deleteReplyTitle"),description:b("editor.deleteReplyDescription"),confirmLabel:b("common.delete"),danger:!0,onCancel:()=>U(null),onConfirm:()=>{D&&g(D).then(T=>{T&&U(null)})}})]})}function qw({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=Ke(),[i,l]=h.useState([]),[a,c]=h.useState([]),[u,f]=h.useState(""),[d,p]=h.useState("read"),[w,g]=h.useState(null),[b,x]=h.useState(""),_=n.permission==="owner",O=async()=>{try{const[j,L]=await Promise.all([ce(`/api/projects/${s}/members`),ce("/api/users")]);l(j.members),c(L.users.filter(K=>K.id!==n.ownerId))}catch(j){x(de(j))}};h.useEffect(()=>{t&&O()},[t,s]);const S=async()=>{if(u)try{await ce(`/api/projects/${s}/members/${u}`,{method:"PUT",body:JSON.stringify({permission:d})}),f(""),p("read"),await O()}catch(j){x(de(j))}},V=async(j,L)=>{try{await ce(`/api/projects/${s}/members/${j.id}`,{method:"PUT",body:JSON.stringify({permission:L})}),await O()}catch(K){x(de(K))}},Y=async()=>{if(w)try{await ce(`/api/projects/${s}/members/${w.id}`,{method:"DELETE"}),g(null),await O()}catch(j){x(de(j))}},C=a.filter(j=>!i.some(L=>L.id===j.id));return o.jsxs(o.Fragment,{children:[o.jsx(Kt,{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:[b&&o.jsx("p",{className:"error",children:b}),o.jsxs("div",{className:"share-owner",children:[o.jsx(vi,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),_&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:u,onChange:j=>f(j.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),C.map(j=>o.jsx("option",{value:j.id,children:j.displayName??j.username},j.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:d,onChange:j=>p(j.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:()=>{S()},children:[o.jsx(lh,{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(j=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(j.displayName??j.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:j.displayName??j.username}),o.jsxs("small",{children:["@",j.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!_,value:j.permission,onChange:L=>{V(j,L.target.value)},children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]}),_&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(j),children:o.jsx(Xt,{size:15})})]})]},j.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(vi,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(gs,{open:!!w,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:w?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{Y()}})]})}const Hw=h.lazy(()=>Ct(()=>import("./CitationLibraryDialog-VSUiSPgG.js"),__vite__mapDeps([11,2,1,3,12,5,13,4,6,14,15])).then(t=>({default:t.CitationLibraryDialog}))),Vw=h.lazy(()=>Ct(()=>import("./GitDialog-C9Loz4Al.js"),__vite__mapDeps([16,2,1,3,5,17,18,13,19,4,6,7,8])).then(t=>({default:t.GitDialog}))),Kw=h.lazy(()=>Ct(()=>import("./HistoryDialog-3UNN_jhU.js"),__vite__mapDeps([20,2,1,3,21,22,5,18,13,19,4,6,7,8])).then(t=>({default:t.HistoryDialog}))),Jw=h.lazy(()=>Ct(()=>import("./SelectionHistoryDialog-D3dO83lg.js"),__vite__mapDeps([23,2,1,3,21,4,5,6,7,8])).then(t=>({default:t.SelectionHistoryDialog}))),Gw=h.lazy(()=>Ct(()=>import("./ProjectNavigationDialogs-CZKTnxrl.js"),__vite__mapDeps([24,2,1,3,6,5,4])).then(t=>({default:t.ProjectSearchDialog}))),Yw=h.lazy(()=>Ct(()=>import("./ProjectNavigationDialogs-CZKTnxrl.js"),__vite__mapDeps([24,2,1,3,6,5,4])).then(t=>({default:t.QuickOpenDialog})));function Xw({user:t,project:e,projectId:n,activeFile:s,content:r,maxCitationBibtexBytes:i,files:l,directoryEntries:a,readOnly:c,workspaceLayout:u,changeWorkspaceLayout:f,resourcePreview:d,resourcePreviewLoading:p,setResourcePreview:w,setResourcePreviewLoading:g,uploadConflict:b,setUploadConflict:x,uploadFiles:_,cleanMode:O,setCleanMode:S,cleanCompile:V,newFileOpen:Y,setNewFileOpen:C,newFilePath:j,setNewFilePath:L,newFolderOpen:K,setNewFolderOpen:X,newFolderName:B,setNewFolderName:P,selectedFolder:oe,fileDialogError:D,setFileDialogError:U,createFile:ee,createFolder:te,moveEntry:J,setMoveEntry:fe,moveName:ge,setMoveName:ye,moveDestination:T,setMoveDestination:me,movePath:$,deleteEntry:M,setDeleteEntry:z,deleteActiveSessions:se,removePath:le,commentOpen:be,closeComment:Ie,commentSelection:I,selection:G,commentText:Re,setCommentText:F,commentSubmitting:Pe,commentError:Ae,addComment:ve,shareOpen:he,setShareOpen:we,citationLibraryOpen:Be,setCitationLibraryOpen:Ee,insertCitationAtCursor:v,quickOpen:ae,setQuickOpen:Ce,projectSearchOpen:et,setProjectSearchOpen:Ne,openFile:xe,jumpToSource:dt,selectionHistoryOpen:We,setSelectionHistoryOpen:R,historyOpen:Q,setHistoryOpen:A,gitOpen:ie,setGitOpen:ht,save:ft,permissionDowngrade:Xe,permissionDowngradeBusy:ot,dismissPermissionDowngrade:jt,discardPermissionDraft:pe}){const{t:N}=Ke();return o.jsxs(o.Fragment,{children:[Xe&&o.jsx(Kt,{open:!0,title:N("editor.collaboration.permissionDowngradeTitle"),description:Xe.localDraftReady&&Xe.otherTabDraft?N("editor.collaboration.permissionDowngradeMultipleDrafts"):Xe.otherTabDraft?N("editor.collaboration.permissionDowngradeOtherTab"):Xe.localDraftReady?N("editor.collaboration.permissionDowngradeDescription",{previous:N("common.readWrite")}):N("editor.collaboration.permissionDowngradeNoDraft"),onOpenChange:W=>{!W&&!ot&&jt()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:ot,onClick:jt,children:Xe.localDraftReady?N("editor.collaboration.permissionDowngradeKeep"):N("common.close")}),!Xe.otherTabDraft&&o.jsxs("button",{type:"button",className:"danger",disabled:ot,onClick:()=>{pe()},children:[ot?o.jsx(tt,{className:"spin",size:14}):Xe.localDraftReady?o.jsx(Xt,{size:14}):o.jsx(ah,{size:14}),Xe.localDraftReady?N("editor.collaboration.permissionDowngradeDiscard"):N("editor.collaboration.permissionDowngradeReload")]})]}),children:o.jsx("div",{})}),o.jsxs(Kt,{open:!!d,extraWide:d?.kind==="image"||d?.kind==="pdf"||d?.kind==="text",title:d?.path??"",description:d?.kind==="large"?N("editor.resourceTooLarge",{size:Qw(d.size),limit:`${qi/1024/1024} MB`}):N(`editor.resourcePreview.${d?.kind??"text"}`),onOpenChange:W=>{W||(w(null),g(!1))},footer:d&&o.jsxs("a",{className:"primary resource-download",href:`${d.url}&download=1`,download:!0,children:[o.jsx(Qs,{size:14}),N("editor.downloadResource")]}),children:[d?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(gl,{size:34}),o.jsx("strong",{children:N("editor.resourceTooLargeTitle")}),o.jsx("span",{children:N("editor.resourceTooLargeDescription")})]}),d?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(gl,{size:34}),o.jsx("strong",{children:N("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:N("editor.resourceUnsupportedDescription")})]}),d?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:d.url,alt:d.path})}),d?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:d.url,title:d.path}),d?.kind==="text"&&(p?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(tt,{className:"spin",size:24}),o.jsx("span",{children:N("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:d.content}))]}),o.jsx(gs,{open:!!b,title:N("editor.uploadOverwriteTitle"),description:N("editor.uploadOverwriteDescription",{files:b?.collisions.join(", ")??""}),confirmLabel:N("editor.uploadOverwrite"),danger:!0,onCancel:()=>x(null),onConfirm:()=>{const W=b;x(null),W&&_(W.files,new Set(W.collisions),W.directory)}}),o.jsx(gs,{open:!!O,title:N(O==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:N(O==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:N("editor.cleanConfirm"),danger:O==="artifacts",onCancel:()=>S(null),onConfirm:()=>{const W=O;S(null),W&&V(W)}}),o.jsx(Kt,{open:Y,title:N("editor.newFile"),description:N("editor.newFileDescription"),onOpenChange:W=>{C(W),W||U("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>C(!1),children:N("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ee()},children:N("common.create")})]}),children:o.jsxs(o.Fragment,{children:[D&&o.jsx("p",{className:"error dialog-error",children:D}),o.jsxs("label",{className:"form-field",children:[N("editor.filePath"),o.jsx("input",{autoFocus:!0,value:j,onChange:W=>L(W.target.value),onKeyDown:W=>{W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),ee())}})]})]})}),o.jsx(Kt,{open:K,title:N("editor.newFolder"),description:N("editor.folderDestination",{folder:oe||N("editor.projectRoot")}),onOpenChange:W=>{X(W),W||U("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>X(!1),children:N("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{te()},children:N("common.create")})]}),children:o.jsxs(o.Fragment,{children:[D&&o.jsx("p",{className:"error dialog-error",children:D}),o.jsxs("label",{className:"form-field",children:[N("editor.folderName"),o.jsx("input",{autoFocus:!0,value:B,onChange:W=>P(W.target.value),onKeyDown:W=>{W.key==="Enter"&&te()}})]})]})}),o.jsx(Kt,{open:!!J,title:N("editor.moveTitle",{name:J?.path.split("/").at(-1)??""}),description:N("editor.moveDescription"),onOpenChange:W=>{W||(fe(null),ye(""),U(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>fe(null),children:N("common.cancel")}),o.jsx("button",{className:"primary",disabled:!ge.trim(),onClick:()=>{$()},children:N("editor.moveApply")})]}),children:o.jsxs(o.Fragment,{children:[D&&o.jsx("p",{className:"error dialog-error",children:D}),o.jsxs("label",{className:"form-field",children:[N("editor.pathName"),o.jsx("input",{autoFocus:!0,value:ge,onChange:W=>ye(W.target.value),onKeyDown:W=>{W.key==="Enter"&&$()}})]}),o.jsxs("label",{className:"form-field",children:[N("editor.destinationFolder"),o.jsxs("select",{value:T,onChange:W=>me(W.target.value),children:[o.jsx("option",{value:"",children:N("editor.projectRoot")}),a.filter(W=>J?.type!=="directory"||W.path!==J.path&&!W.path.startsWith(`${J.path}/`)).map(W=>o.jsx("option",{value:W.path,children:W.path},W.path))]})]})]})}),o.jsx(Kt,{open:!!M,title:N("editor.deletePathTitle",{name:M?.path.split("/").at(-1)??""}),description:se.length?N("editor.deletePathActiveDescription",{path:M?.path??"",users:[...new Set(se.map(W=>W.name))].join(", ")}):N("editor.deletePathDescription",{path:M?.path??""}),onOpenChange:W=>{W||(z(null),U(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>z(null),children:N("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{le()},children:N("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[D&&o.jsx("p",{className:"error dialog-error",children:D}),se.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(Pt,{size:15}),N("editor.deletePathWillClose")]})]})}),o.jsxs(Kt,{open:be,title:N("editor.addComment"),description:I.selectedText?N("editor.commentDescription",{count:I.endOffset-I.startOffset}):N("editor.pointComment"),onOpenChange:W=>{W||Ie()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:Pe,onClick:Ie,children:N("common.cancel")}),o.jsxs("button",{type:"button",className:"primary",disabled:Pe||!Re.trim(),onClick:()=>{ve()},children:[Pe&&o.jsx(tt,{className:"spin",size:14}),N("editor.addComment")]})]}),children:[Ae&&o.jsx("p",{className:"error dialog-error",children:Ae}),o.jsxs("label",{className:"form-field",children:[N("editor.commentContent"),o.jsx(Xs,{projectId:n,autoFocus:!0,rows:5,disabled:Pe,value:Re,onChange:F,onKeyDown:W=>{(W.ctrlKey||W.metaKey)&&W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),W.stopPropagation(),ve())}})]}),I.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:I.selectedText})]}),o.jsx(qw,{open:he,onOpenChange:we,project:e,projectId:n}),Be&&o.jsx(fa,{title:N("citationLibrary.title"),onClose:()=>Ee(!1),children:o.jsx(Hw,{open:!0,onOpenChange:Ee,currentFile:s,currentSource:r,readOnly:c,currentUserId:t.id,maxBibtexBytes:i,onInsert:v})}),ae&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Yw,{open:!0,files:l,onOpenChange:Ce,onOpenFile:W=>{const Nt=l.find(ss=>ss.path===W);Nt&&xe(Nt)}})}),et&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Gw,{open:!0,project:e,onOpenChange:Ne,onJump:(W,Nt,ss)=>{u==="pdf-only"&&f("editor-pdf"),dt(W,Nt,ss)}})}),We&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Jw,{open:!0,onOpenChange:R,project:e,filePath:s,selection:G,currentSource:r})}),Q&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Kw,{open:!0,onOpenChange:A,project:e,onBeforeMutation:e.permission==="read"?async()=>!0:ft})}),e.ownerId===t.id&&ie&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Vw,{open:!0,onOpenChange:ht,project:e,onBeforeMutation:ft})})]})}function Qw(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const Zw=h.lazy(()=>Ct(()=>import("./ProjectSettings-DiOQVJ40.js"),__vite__mapDeps([25,2,1,3,5,26,27,14,8,4,6,7])).then(t=>({default:t.ProjectSettings})));function ey({sidePanel:t,onClose:e,project:n,projectId:s,site:r,files:i,currentUserId:l,comments:a,unreadMentions:c,onMarkMentionRead:u,onMarkAllMentionsRead:f,targetCommentId:d,targetReplyId:p,onFocusComment:w,onToggleComment:g,onReplyComment:b,onEditComment:x,onDeleteComment:_,onEditCommentReply:O,onDeleteCommentReply:S,dictionaryWords:V,onDictionaryChange:Y,editorPreferences:C,onEditorPreferences:j,spellCheckCount:L,spellCheckUniqueCount:K,spellCheckIndex:X,onSpellCheckNavigate:B,onProject:P}){const{t:oe}=Ke();return t?o.jsxs(o.Fragment,{children:[o.jsx(Hi,{className:"resize-handle"}),o.jsx(gr,{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:oe("editor.sourceComments")}),o.jsxs("span",{className:"drawer-title-actions",children:[c.length>0&&o.jsxs("button",{className:"drawer-mention-read-all",type:"button",onClick:()=>{f()},title:oe("editor.markAllMentionsRead"),children:[o.jsx(Zs,{"aria-hidden":!0,size:13}),o.jsx("span",{children:oe("editor.markAllMentionsRead")})]}),o.jsx("button",{"aria-label":oe("common.close"),onClick:e,children:o.jsx(ws,{size:17})})]})]}),o.jsxs("div",{className:"comments",children:[a.map(D=>{const U=c.find(te=>te.commentId===D.id&&!te.replyId)?.id,ee=new Map(c.filter(te=>te.commentId===D.id&&te.replyId).map(te=>[te.replyId,te.id]));return o.jsx(Ww,{projectId:s,comment:D,currentUserId:l,unreadCommentMentionId:U,unreadReplyMentionIds:ee,highlightedComment:d===D.id&&!p,highlightedReplyId:d===D.id?p:null,onMarkMentionRead:u,onFocus:()=>w(D),onToggle:()=>{g(D)},onReply:te=>b(D,te),onEdit:te=>x(D,te),onDelete:()=>_(D),onEditReply:(te,J)=>O(D,te,J),onDeleteReply:te=>S(D,te)},D.id)}),a.length===0&&o.jsx("p",{className:"muted padded",children:oe("editor.noComments")})]})]}),t==="settings"&&o.jsx(Kd,{onClose:e,children:o.jsx(Zw,{onClose:e,project:n,projectId:s,site:r,files:i,dictionaryWords:V,onDictionaryChange:Y,editorPreferences:C,onEditorPreferences:j,spellCheckCount:L,spellCheckUniqueCount:K,spellCheckIndex:X,onSpellCheckNavigate:B,onProject:P})})]})})]}):null}function ty(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 ny(){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=ty(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}}}const sy=h.lazy(()=>Ct(()=>import("./WordCountDialog-TwpyAP3m.js"),__vite__mapDeps([28,2,1,3,26,5,4,6,7,8])).then(t=>({default:t.WordCountDialog})));let Vs=null;function da(){return Vs||(Vs=Ct(()=>import("./citationLibrary-ZeQPCv5O.js"),[]).catch(t=>{throw Vs=null,t})),Vs}function dn(t){return t instanceof Error&&t.name==="AbortError"}const ry=300;function iy({site:t,user:e,projectId:n,preload:s,mentionId:r=null,onMentionTargeted:i,onMentionsRead:l,onBack:a}){const{t:c}=Ke(),[u,f]=h.useState(null),[d,p]=h.useState(!1),[w,g]=h.useState([]),[b,x]=h.useState(null),[_,O]=h.useState([]),[S,V]=h.useState(""),[Y,C]=h.useState(""),[j,L]=h.useState(new Set),[K,X]=h.useState(""),[B,P]=h.useState({filePath:"",content:""}),[oe,D]=h.useState(""),[U,ee]=h.useState(!1),[te,J]=h.useState("editor.saved"),[fe,ge]=h.useState(null),ye=h.useRef(fe);ye.current=fe;const T=h.useRef(null);T.current||(T.current=ny());const me=T.current,[$,M]=h.useState("pdf"),[z,se]=h.useState("log"),le=m=>{if(m==="pdf"){M("pdf");return}if(m==="diagnostics"){M("diagnostics");return}se(m),M("diagnostics")},{workspaceLayout:be,setWorkspaceLayout:Ie}=Dw(e.id,n),[I,G]=h.useState(""),[Re,F]=h.useState(""),[Pe,Ae]=h.useState({selectedText:"",startOffset:0,endOffset:0}),ve=h.useRef({selectedText:"",startOffset:0,endOffset:0}),he=m=>{const y=ve.current;y.selectedText===m.selectedText&&y.startOffset===m.startOffset&&y.endOffset===m.endOffset||(ve.current=m,Ae(m))},[we,Be]=h.useState(null),[Ee,v]=h.useState(null),[ae,Ce]=h.useState(!1),[et,Ne]=h.useState(!1),[xe,dt]=h.useState(!1),[We,R]=h.useState(!1),[Q,A]=h.useState(!1),[ie,ht]=h.useState(!1),[ft,Xe]=h.useState(null),[ot,jt]=h.useState(!1),[pe,N]=h.useState(!1),[W,Nt]=h.useState(!1),[ss,nu]=h.useState("full"),[su,ru]=h.useState(""),[Lr,Rr]=h.useState(!1),[iu,Ar]=h.useState(""),[ou,Nr]=h.useState(null),[rs,Cn]=h.useState(!1),[nn,Ot]=h.useState(null),[lu,Or]=h.useState(!1),[lt,_o]=h.useState(()=>Sl(e.id,n)),[jn,Fs]=h.useState([]),Wt=h.useRef([]);Wt.current=jn;const au=h.useRef(null),Ms=h.useRef(null),$s=h.useRef(0),Fr=h.useRef(0),De=h.useRef(""),vt=h.useRef(""),To=h.useRef(0),sn=h.useRef(null),rn=h.useRef(null),on=h.useRef(null),vn=h.useRef(null),En=h.useRef(null),Dn=h.useRef(null),Mr=h.useRef(null),Ft=h.useRef(!1),qt=h.useRef(null),Lo=h.useRef(a),$r=h.useRef(i),Ir=h.useRef(l);Lo.current=a,$r.current=i,Ir.current=l,vt.current=Y,h.useEffect(()=>{if(!Re)return;const m=window.setTimeout(()=>F(""),3e3);return()=>window.clearTimeout(m)},[Re]);const cu=h.useCallback((m,y,E=0)=>{me.update(m,y,E)},[me]);h.useEffect(()=>()=>me.dispose(),[me]);const Is=m=>{const y=Wt.current,E=m(y);E!==y&&(Wt.current=E,Fs(E))};h.useEffect(()=>{Wt.current=[],Fs([]),Ot(null),A(!1),En.current?.abort(),En.current=null,Dn.current?.abort(),Dn.current=null,Mr.current=null,v(null),Nt(!1),Rr(!1),Ar(""),Nr(null)},[n]);const Ro=m=>{const y=Wt.current,E=y.indexOf(m);if(E<0)return;const k=y.filter(H=>H!==m);if(Wt.current=k,Fs(k),De.current!==m)return;const Z=k.length>0?k[Math.min(E,k.length-1)]:u?.mainFile??"";V(Z)},{collaboration:Te,status:Ps,synced:Ge,activeSessions:Ao,formatLeaseStates:uu,compileState:ln,setCompileState:No,filesEvent:Ue,commentsRevision:Oo,historyWarning:du,dictionaryRevision:Fo,localDraftReady:Mo,permission:Pr,reconnect:hu,protocolUpgradeRequired:$o,permissionDowngrade:fu,dismissPermissionDowngrade:pu,discardLocalDraft:mu}=yw(n,e,Y,u?.permission??"read",d,()=>J("editor.offlineDraft")),{unreadMentions:Io,refresh:gu,markMentionRead:wu,markAllMentionsRead:yu}=Xh(n,Oo,G),{pdfTarget:bu,pdfViewport:xu,sourceJump:Su,setPdfViewport:ku,clearPdfViewport:Po,jumpToSource:Ur,syncSourceToPdf:zr,syncPdfToSource:Cu,syncVisiblePdfToSource:ju}=Ew({projectId:n,mainFile:Y,activeFile:S,onActiveFile:V,onError:G,onShowPdf:()=>le("pdf")}),at=vw({active:!!(u&&S&&Ge&<.spellCheck),projectId:n,activeFile:S,content:K,dictionaryWords:w});h.useEffect(()=>{_o(Sl(e.id,n))},[e.id,n]);const Br=m=>{X(m)};h.useEffect(()=>{if(!S||oe!==S){P(k=>k.filePath||k.content?{filePath:"",content:""}:k);return}const m=S,y=K,E=window.setTimeout(()=>{P(k=>k.filePath===m&&k.content===y?k:{filePath:m,content:y})},ry);return()=>window.clearTimeout(E)},[S,oe,K]),h.useEffect(()=>{if(De.current=S,me.reset(),he({selectedText:"",startOffset:0,endOffset:0}),!lt.openFilesInTabs){Wt.current.length>0&&(Wt.current=[],Fs([]));return}S&&Is(m=>m.includes(S)?m:[...m,S])},[S,lt.openFilesInTabs,n,me]),h.useEffect(()=>{if(!U)return;const m=y=>{y.preventDefault(),y.returnValue=""};return window.addEventListener("beforeunload",m),()=>window.removeEventListener("beforeunload",m)},[U]),h.useEffect(()=>{if(Ps!=="disconnected")return;const m=new AbortController;return ce(`/api/projects/${n}`,{signal:m.signal}).then(({project:y})=>{m.signal.aborted||(f(y),G(""))}).catch(y=>{if(!dn(y)){if(y instanceof ji&&[401,403,404].includes(y.status)){G(de(y)),Lo.current();return}G(c("errors.collaborationUnavailable"))}}),()=>m.abort()},[Ps,n,c]);const Wr=async(m={})=>{sn.current?.abort(),sn.current=null;const y=m.signal?null:new AbortController;y&&(sn.current=y);try{const E=await ce(`/api/projects/${n}/completions`,{signal:m.signal??y?.signal});(!m.isCurrent||m.isCurrent())&&x(E.index)}catch(E){if(dn(E))return;(!m.isCurrent||m.isCurrent())&&x(null)}finally{y&&sn.current===y&&(sn.current=null)}},qr=async(m={},y=vt.current)=>{rn.current?.abort(),rn.current=null;const E=m.signal?null:new AbortController;E&&(rn.current=E);try{const k=y?`?mainFile=${encodeURIComponent(y)}`:"",Z=await ce(`/api/projects/${n}/outline${k}`,{signal:m.signal??E?.signal});(!m.isCurrent||m.isCurrent())&&O(Z.outline)}catch(k){!dn(k)&&(!m.isCurrent||m.isCurrent())&&O([])}finally{E&&rn.current===E&&(rn.current=null)}},Uo=async(m={})=>{on.current?.abort(),on.current=null;const y=m.signal?null:new AbortController;y&&(on.current=y);try{const E=await ce(`/api/projects/${n}/dictionary`,{signal:m.signal??y?.signal});(!m.isCurrent||m.isCurrent())&&g(E.words)}catch(E){if(dn(E))return;(!m.isCurrent||m.isCurrent())&&g([])}finally{y&&on.current===y&&(on.current=null)}};h.useEffect(()=>{let m=!1;const y=++To.current,E=new AbortController,k=()=>!m&&To.current===y;let Z=!1;f(null),Wo([]),O([]),V(""),C(""),L(new Set),X(""),D(""),No(null),Po(),x(null),g([]),ha();const H=(s?.projectId===n?s.project:ce(`/api/projects/${n}`,{signal:E.signal})).then(Me=>{k()&&(Z=!0,f(Me.project),V(Me.project.mainFile),C(Me.project.mainFile),L(new Set),Xo(new Set(hs(Me.project.mainFile))))}).catch(Me=>{k()&&G(de(Me))}),ne=ce(`/api/projects/${n}/files`,{signal:E.signal}).then(Me=>{k()&&Wo(Me.files)}).catch(Me=>{k()&&G(de(Me))});let pt=null;return Promise.allSettled([H,ne]).then(()=>{!k()||!Z||(pt=window.setTimeout(()=>{k()&&Promise.all([Wr({signal:E.signal,isCurrent:k}),Uo({signal:E.signal,isCurrent:k})])},0))}),()=>{m=!0,pt!==null&&window.clearTimeout(pt),E.abort(),sn.current?.abort(),sn.current=null,rn.current?.abort(),rn.current=null,on.current?.abort(),on.current=null,vn.current?.abort(),vn.current=null}},[n,s]),h.useEffect(()=>{if(!r||!u)return;Dn.current?.abort();const m=new AbortController;return Dn.current=m,ce(`/api/projects/${n}/mentions/${encodeURIComponent(r)}`,{signal:m.signal}).then(({mention:y})=>{m.signal.aborted||(v(y),Be("comments"),V(y.filePath),$r.current?.(y.id))}).catch(y=>{dn(y)||m.signal.aborted||(G(de(y)),$r.current?.(r))}).finally(()=>{Dn.current===m&&(Dn.current=null)}),()=>m.abort()},[r,u?.id,n]),h.useEffect(()=>{Fo&&Uo()},[Fo,n]),h.useEffect(()=>{!u||Ps!=="connected"||Pr===u.permission||f(m=>m&&{...m,permission:Pr})},[Pr,u?.permission]),h.useEffect(()=>{if(!Ue)return;const m=Ue.kind==="delete"&&!!Ue.path&&un(Ue.path,De.current),y=Ue.kind==="delete"&&!!Ue.path&&un(Ue.path,vt.current);if(Ue.kind==="move"&&Ue.source&&Ue.destination){const k=Ue.source,Z=Ue.destination,H=ne=>ne===k?Z:ne.startsWith(`${k}/`)?`${Z}${ne.slice(k.length)}`:ne;V(ne=>H(ne)),C(ne=>H(ne)),L(ne=>new Set([...ne].map(H))),Vr(ne=>ne&&H(ne)),Is(ne=>ne.map(H))}m&&(V(""),D(""),Br(""),F(c("editor.fileDeletedByCollaborator",{path:Ue.path}))),Ue.kind==="delete"&&Ue.path&&(L(k=>new Set([...k].filter(Z=>!un(Ue.path,Z)))),Vr(k=>un(Ue.path,k)?"":k),Vo(k=>k&&un(Ue.path,k.path)?null:k),Is(k=>k.filter(Z=>!un(Ue.path,Z)))),vn.current?.abort();const E=new AbortController;vn.current=E,Promise.all([Tu({signal:E.signal}),ce(`/api/projects/${n}`,{signal:E.signal})]).then(([k,Z])=>{if(f(Z.project),y&&C(Z.project.mainFile),m&&k){const H=k.find(ne=>ne.type==="file"&&ne.path===Z.project.mainFile)??k.find(ne=>ne.type==="file"&&Bn(ne.path));V(H?.path??"")}Wr({signal:E.signal}),qr({signal:E.signal},y?Z.project.mainFile:vt.current)}).catch(k=>{dn(k)}).finally(()=>{vn.current===E&&(vn.current=null)})},[Ue?.revision]),h.useEffect(()=>{if(Te.setActiveFile(S),!S)return;D(""),J("editor.loading");const m=Te.getText(S),y=(E,k)=>{Br(m.toString()),D(S),k?.local&&u?.permission!=="read"?($s.current+=1,ee(!0),J("editor.pending")):$s.current<=Fr.current&&J(ye.current?"editor.savedAt":"editor.saved")};return m.observe(y),(Ge||Mo)&&y(),()=>{m.unobserve(y)}},[S,Te,Ge,Mo,u?.permission]);const Us=async()=>{if(!Ge)throw new Error("Collaboration is not synchronized");const m=$s.current,y=await Te.flush();return Fr.current=Math.max(Fr.current,m),ge(y.persistedAt),/\.tex$/i.test(De.current)&&qr(),$s.current===m?(ee(!1),J("editor.savedAt")):J("editor.pending"),y};h.useEffect(()=>{if(!U||!S)return;if(!Ge){J("editor.offlineDraft");return}J("editor.pending");const m=window.setTimeout(()=>{J("editor.saving"),Us().catch(()=>{J(Te.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(m)},[K,U,S,Ge]);const is=async()=>{if(!u||u.permission==="read"||!Ge||!S)return!1;J("editor.saving");try{return await Us(),Wr(),!0}catch(m){return J("editor.saveFailed"),G(de(m)||c("errors.collaborationUnavailable")),!1}},vu=async m=>{if(!u||Lr)return;const y=m==="full"?vt.current||u.mainFile:De.current,E=m==="selection"?ve.current.selectedText:"";if(!y)return;if(m==="selection"&&(!E.trim()||!/\.(?:tex|sty|cls)$/i.test(y))){F(c("editor.wordCountSelectionEmpty"));return}En.current?.abort();const k=new AbortController;En.current=k,nu(m),ru(y),Nr(null),Ar(""),Nt(!0),Rr(!0);try{if(m==="full"&&U&&u.permission!=="read"&&!await is())throw new Error(c("editor.wordCountSaveRequired"));const Z=m==="selection"?{mode:m,path:y,source:E}:{mode:m,mainFile:y},H=await ce(`/api/projects/${n}/word-count`,{method:"POST",body:JSON.stringify(Z),signal:k.signal});if(k.signal.aborted)return;Nr(H)}catch(Z){if(dn(Z))return;k.signal.aborted||Ar(de(Z))}finally{En.current===k&&(En.current=null,Rr(!1))}},Hr=async(m,y,E=lt.texFmtConfig)=>{if(/\.bib$/i.test(m)){const Z=await da();try{return{formatted:Z.formatBibtex(y,t.maxCitationBibtexBytes)}}catch(H){throw H instanceof Z.BibtexFormatError?H.kind==="too-large"?new Error(c("citationLibrary.fileTooLarge",{size:Z.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})):new Error(c("citationLibrary.fileInvalid")):H}}return{formatted:(await Th(y,E)).output}},zo=async m=>{if(!u||u.permission==="read"||!Ge||Ft.current||!Bs(De.current))return;const y=De.current,E=Te.getText(y);Ft.current=!0,Cn(!0);let k=()=>{};const Z=new Promise(ne=>{k=ne});qt.current=Z;let H=null;try{H=await Te.acquireFormatLease(y);const ne=E.toString(),{formatted:pt}=await Hr(y,ne,m);if(De.current!==y||E.toString()!==ne){G(c("editor.formatSourceChanged"));return}await H.confirm();const Me=await ii(ne,pt);if(De.current!==y||E.toString()!==ne){G(c("editor.formatSourceChanged"));return}if(await H.confirm(),De.current!==y||E.toString()!==ne){G(c("editor.formatSourceChanged"));return}Me.length&&Te.applyTextEdits(y,Me),Me.length&&await Us(),Ot(null),G(""),F(c("editor.formatFileComplete"))}catch(ne){ri(ne)?(Ot({action:"file",kind:ne.kind,detail:ne.message}),G("")):G(c("editor.formatFileFailed",{message:de(ne)}))}finally{H&&await H.release(),Ft.current=!1,Cn(!1),k(),qt.current===Z&&(qt.current=null)}},Eu=async()=>{if(!lt.formatOnCompile||!u||u.permission==="read"||!Ge||!Bs(De.current)||Ft.current)return;const m=De.current,y=Te.getText(m);Ft.current=!0,Cn(!0);let E=null;try{E=await Te.acquireFormatLease(m);const k=y.toString(),{formatted:Z}=await Hr(m,k);await E.confirm();const H=await ii(k,Z);if(De.current!==m||y.toString()!==k)throw new Error(c("editor.formatSourceChanged"));if(await E.confirm(),De.current!==m||y.toString()!==k)throw new Error(c("editor.formatSourceChanged"));H.length&&Te.applyTextEdits(m,H),H.length&&await Te.flush(),Ot(null)}catch(k){ri(k)?(Ot({action:"file",kind:k.kind,detail:k.message}),G("")):G(c("editor.formatFailedContinue",{message:de(k)}))}finally{E&&await E.release(),Ft.current=!1,Cn(!1)}},Du=async()=>(qt.current&&await qt.current,await Eu(),is()),Bo=async m=>{if(!u||u.permission==="read"||!Ge||Ft.current||!Bs(De.current))return;const y=ve.current;if(!y.selectedText.trim()){F(c("editor.formatSelectionRequired"));return}const E=De.current,{startOffset:k,endOffset:Z,selectedText:H}=y,ne=Te.getText(E);if(ne.toString().slice(k,Z)!==H){G(c("editor.formatSelectionChanged"));return}Ft.current=!0,Cn(!0);let pt=()=>{};const Me=new Promise(Mt=>{pt=Mt});qt.current=Me;let an=null;try{if(an=await Te.acquireFormatLease(E),ne.toString().slice(k,Z)!==H){G(c("editor.formatSelectionChanged"));return}const as=await Hr(E,H,m),Bd=Ah(H,as.formatted);await an.confirm();const si=await ii(H,Bd,k);if(De.current!==E||ne.toString().slice(k,Z)!==H){G(c("editor.formatSelectionChanged"));return}if(await an.confirm(),De.current!==E||ne.toString().slice(k,Z)!==H){G(c("editor.formatSelectionChanged"));return}si.length&&Te.applyTextEdits(E,si),si.length&&await Us(),Ot(null),G(""),F(c("editor.formatSelectionComplete"))}catch(Mt){ri(Mt)?(Ot({action:"selection",kind:Mt.kind,detail:Mt.message}),G("")):G(c("editor.formatFailed",{message:de(Mt)}))}finally{an&&await an.release(),Ft.current=!1,Cn(!1),pt(),qt.current===Me&&(qt.current=null)}},_u=async m=>{const y=De.current;if(!/\.bib$/i.test(y)||u?.permission==="read"||!Ge)return F(c("citationLibrary.importRequiresWrite")),!1;const E=Te.getText(y);let k;try{k=await da()}catch(as){return G(de(as)),!1}if(De.current!==y||!Ge)return!1;const Z=E.toString(),H=k.parseBibEntriesResult(Z,t.maxCitationBibtexBytes);if(H.status==="too-large")return F(c("citationLibrary.fileTooLarge",{size:k.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})),!1;if(H.status==="invalid")return F(c("citationLibrary.fileInvalid")),!1;if(H.entries.some(as=>as.citationKey.toLowerCase()===m.citationKey.toLowerCase()))return F(c("citationErrors.alreadyInFile",{key:m.citationKey})),!1;const ne=Math.max(0,Math.min(Z.length,me.getCursor().offset)),pt=Z.slice(0,ne),Me=Z.slice(ne),an=pt?pt.endsWith(`
|
|
15
|
-
|
|
16
|
-
`)?"":pt.endsWith(`
|
|
17
|
-
`)?`
|
|
18
|
-
`:`
|
|
19
|
-
|
|
20
|
-
`:"",Mt=Me?Me.startsWith(`
|
|
21
|
-
|
|
22
|
-
`)?"":Me.startsWith(`
|
|
23
|
-
`)?`
|
|
24
|
-
`:`
|
|
25
|
-
|
|
26
|
-
`:"";return Te.applyTextEdits(y,[{from:ne,to:ne,replacement:`${an}${m.bibtex.trim()}${Mt}`}]),F(c("citationLibrary.imported",{key:m.citationKey})),!0},{files:wt,setFiles:Wo,loadFiles:Tu,newFileOpen:Lu,setNewFileOpen:qo,newFilePath:Ru,setNewFilePath:Ho,resourcePreview:Au,setResourcePreview:Vo,resourcePreviewLoading:Nu,setResourcePreviewLoading:Ou,newFolderOpen:Fu,setNewFolderOpen:Ko,newFolderName:Mu,setNewFolderName:Jo,fileDialogError:$u,setFileDialogError:Go,selectedFolder:Yo,setSelectedFolder:Vr,expandedFolders:Iu,setExpandedFolders:Xo,moveEntry:Pu,setMoveEntry:Qo,moveName:Uu,setMoveName:Zo,moveDestination:zu,setMoveDestination:el,deleteEntry:Kr,setDeleteEntry:tl,fileDragActive:Bu,setFileDragActive:Wu,uploadConflict:qu,setUploadConflict:Hu,uploadingFiles:Vu,directoryEntries:Ku,visibleEntries:Ju,createFile:Gu,createFolder:Yu,uploadFiles:nl,upload:Xu,openFile:Jr,movePath:Qu,removePath:Zu}=jw({projectId:n,site:t,activeFile:S,dirty:U,save:is,onError:G,onProject:f,onActiveFile:V,onActiveMainFile:C,onRootDocuments:L}),sl=()=>vt.current||u?.mainFile||"",ed=()=>{const m=sl(),y=De.current;if(!y||!/\.tex$/i.test(y))return m;const E=wt.filter(H=>H.type==="file"&&/\.tex$/i.test(H.path)).length,k=Te.getText(y).toString();return ca(k)||E===1?(L(H=>{if(H.has(y))return H;const ne=new Set(H);return ne.add(y),ne}),m!==y&&(vt.current=y,C(y)),y):m===y&&u?.mainFile&&u.mainFile!==y?(vt.current=u.mainFile,C(u.mainFile),u.mainFile):m};h.useEffect(()=>{if(!S||oe!==S||B.filePath!==S||!S.toLocaleLowerCase().endsWith(".tex"))return;const m=wt.filter(Z=>Z.type==="file"&&/\.tex$/i.test(Z.path)).length;if(m===0)return;const y=S===u?.mainFile,k=ca(B.content)||m===1;L(Z=>{if(Z.has(S)===k)return Z;const H=new Set(Z);return k?H.add(S):H.delete(S),H}),k&&!y&&vt.current!==S?C(S):!k&&vt.current===S&&u?.mainFile&&C(u.mainFile)},[S,oe,B,wt,u?.mainFile]),h.useEffect(()=>{if(!lt.openFilesInTabs||wt.length===0)return;const m=new Set(wt.filter(y=>y.type==="file"&&Bn(y.path)).map(y=>y.path));Is(y=>{const E=y.filter(k=>m.has(k));return E.length===y.length?y:E})},[wt,lt.openFilesInTabs]);const{comments:_n,focusComment:td,setFocusComment:Gr,commentOpen:nd,openComment:sd,closeComment:rd,commentText:id,setCommentText:od,commentSelection:ld,commentSubmitting:ad,commentError:cd,addComment:ud,toggleComment:dd,replyToComment:hd,editComment:fd,deleteComment:pd,editCommentReply:md,deleteCommentReply:gd}=Gh({projectId:n,activeFile:S,content:K,permission:u?.permission,revision:Oo,selection:Pe,save:is,saveFailureMessage:c("errors.collaborationUnavailable"),onError:G,onAdded:()=>Be("comments"),onChanged:()=>{gu()}}),wd=async m=>{const y=await wu(m);return y&&Ir.current?.(1),y},yd=async()=>{const m=Io.length,y=await yu();return y&&m&&Ir.current?.(m,!0),y};h.useEffect(()=>{if(!Ee||S!==Ee.filePath||we!=="comments")return;const m=_n.find(H=>H.id===Ee.commentId);if(!m||Ee.replyId&&!m.replies.some(H=>H.id===Ee.replyId))return;const y=Ee.replyId?`[data-comment-reply-id="${Ee.replyId}"]`:`[data-comment-id="${Ee.commentId}"]`,E=document.querySelector(y);if(!E||Mr.current===Ee.id)return;Mr.current=Ee.id,Gr({...m});const k=window.requestAnimationFrame(()=>E.scrollIntoView({block:"center",behavior:"smooth"})),Z=window.setTimeout(()=>v(H=>H?.id===Ee.id?null:H),3e3);return()=>{window.cancelAnimationFrame(k),window.clearTimeout(Z)}},[S,_n,we,Ee]);const{pdfUrl:Ht,pdfCompiledAt:os,pdfLoadingMode:bd,pdfLoading:Yr,compileLog:Xr,compileDiagnostics:xd,compileOutcome:ls,artifacts:rl,artifactPreview:Sd,artifactLoading:kd,editorNotice:Cd,localCompiling:il,cancelling:jd,cleaning:ol,compile:vd,cancelCompile:Ed,cleanCompile:ll,viewArtifact:Dd}=xw({projectId:n,project:u,mainFile:Y,resolveCompileMainFile:ed,getCurrentMainFile:sl,initialLatest:s?.projectId===n?s.latestCompile:null,collaborationSynced:Ge,sharedState:ln,onSharedState:No,save:Du,loadOutline:(m,y)=>qr({signal:m},y),onPreviewTab:le,onError:G,onCompileStart:()=>{G(""),F("")},onCompileSuccess:()=>{const m=De.current;if(m){const y=me.getCursor();zr(m,y.line,y.column,{silent:!0})}},onPdfChanged:Po});h.useEffect(()=>{if(!u||!Y||!Ht&&Yr)return;const m=window.setTimeout(()=>p(!0),Ht?150:0);return()=>window.clearTimeout(m)},[u,Yr,Ht]),h.useEffect(()=>{const m=y=>{(y.ctrlKey||y.metaKey)&&(!y.shiftKey&&y.key.toLocaleLowerCase()==="p"?(y.preventDefault(),jt(!0)):y.shiftKey&&y.key.toLocaleLowerCase()==="f"&&(y.preventDefault(),N(!0)))};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[]);const al=m=>{_o(m),jh(e.id,n,m)},cl=(m=!1)=>{const y=nn;if(!y)return;Ot(null),G(""),m&&al({...lt,texFmtConfig:""});const E=m?"":void 0;y.action==="selection"?Bo(E):zo(E)},_d=async()=>{Or(!0);try{await mu()||(G(c("editor.collaboration.permissionDowngradeOtherTabBlocked")),Or(!1))}catch(m){G(de(m)),Or(!1)}},ul=()=>{Ms.current?.isCollapsed()?Ms.current.expand():Ms.current?.collapse()},Td=h.useMemo(()=>_.length?_:B.filePath!==S?[]:oy(B.content).map(m=>({...m,path:S})),[_,B,S]),Qr=h.useMemo(()=>Nh(Xr,ls),[Xr,ls]),Tn=be!=="pdf-only",dl=be!=="editor-only",Zr=m=>{Ie(m),m==="pdf-only"&&le("pdf")},Ld=Kr?Ao.filter(m=>m.filePath&&un(Kr.path,m.filePath)):[];if(!u)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:I||c("common.loading")}),I&&o.jsx("button",{className:"primary",onClick:a,children:c("editor.backToProjects")})]});const Vt=u.permission==="read"||!Ge,ei=uu.find(m=>m.path===S),ti=ei&&!rs?ei:null,Rd=(m,y)=>{if(Vt)return;const E=De.current;if(!E)return;if(Te.getText(E).toString().slice(m.from,m.to)!==m.word){G(c("editor.spellCheckSourceChanged"));return}try{Te.applyTextEdits(E,[{from:m.from,to:m.to,replacement:y}])}catch(H){G(de(H))}},ni=ln?.mainFile===Y&&(ln.status==="queued"||ln.status==="running"),zs=il||ni||ol,Ad=S?Te.getText(S):null,Nd=os?new Date(os).toLocaleString(fs.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Od=Y.split("/").at(-1)??Y,Fd=Qr.warnings.length+Qr.errors.length+rl.length,Md=Ht?`${Ht}${Ht.includes("?")?"&":"?"}download=1`:"",$d=Y||u.mainFile,Id=!!(S&&S===$d&&/\.tex$/i.test(S)),hl=m=>{const y=wt.find(E=>E.path===m);y&&Bn(y.path)?Jr(y):Ro(m)},Pd=m=>{document.getElementById(`editor-tab-${encodeURIComponent(m)}`)?.focus()},Ud=(m,y)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(m.key))return;m.preventDefault();const E=m.key==="Home"?0:m.key==="End"?jn.length-1:(y+(m.key==="ArrowLeft"?-1:1)+jn.length)%jn.length,k=jn[E];k&&(hl(k),window.requestAnimationFrame(()=>Pd(k)))},fl=zs?ni?ln?.status==="queued"?c("editor.compileQueued"):c("editor.compilingBy",{name:ln?.requestedBy.name??c("common.user")}):c("editor.compiling"):ls==="failed"?Ht&&os?c("editor.compileFailedRetained",{time:new Date(os).toLocaleString(fs.resolvedLanguage)}):c("editor.compileFailedNoPdf"):ls==="cancelled"?c("compileControls.cancelled"):"",zd=te==="editor.savedAt"&&fe?c("editor.savedAt",{time:new Date(fe).toLocaleTimeString(fs.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):c(te);return o.jsxs("div",{className:"workspace",children:[o.jsx(Lw,{site:t,project:u,activeFile:S,saveStateLabel:zd,editorPreferences:lt,activeSessions:Ao,collaborationStatus:Ps,reconnectCollaboration:hu,protocolUpgradeRequired:$o,showEditor:Tn,filesCollapsed:ae,toggleFilesPanel:ul,workspaceLayout:be,changeWorkspaceLayout:Zr,onBack:a,onShare:()=>Ne(!0),showCitationLibrary:Tn&&/\.bib$/i.test(S),citationLibraryOpen:ie,onCitationLibrary:()=>ht(!0),onSelectionHistory:()=>A(!0),onHistory:()=>R(!0),onGit:()=>dt(!0),canManageGit:u.ownerId===e.id,formatting:rs,readOnly:Vt,collaborationSynced:Ge,hasSelection:!!Pe.selectedText.trim(),onAddComment:sd,onToggleComments:()=>Be(we==="comments"?null:"comments"),commentsOpen:we==="comments",unresolvedCommentCount:_n.filter(m=>!m.resolved).length,hasActiveFile:!!S,onToggleSettings:()=>Be(we==="settings"?null:"settings"),settingsOpen:we==="settings",compileBusy:zs,sharedCompiling:ni,localCompiling:il,cancelling:jd,compileState:ln,onCompile:vd,onCancelCompile:()=>{Ed()}}),$o&&o.jsxs("div",{className:"workspace-update-banner",role:"alert",children:[o.jsx(Pt,{size:15}),o.jsx("span",{children:c("workspaceUpdates.protocolUpgrade")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),fl&&o.jsxs("div",{className:`compile-status-strip${ls==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(tt,{className:zs?"spin":"",size:14}),o.jsx("span",{children:fl})]}),(at.error||nn||ti)&&o.jsxs("div",{className:"client-tool-recoveries",children:[at.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:at.error,children:[o.jsx(Pt,{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:at.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:at.dismissError,children:o.jsx(ws,{size:13})})]}),nn&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:nn.detail,children:[o.jsx(Pt,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c(nn.kind==="format"?"editor.texFmtOptionsRecoveryTitle":nn.kind==="load"?"editor.texFmtRecoveryTitle":"editor.texFmtRuntimeRecoveryTitle")}),c("editor.clientToolRecoveryHint")]}),o.jsxs("div",{className:"client-tool-recovery-actions",children:[o.jsx("button",{type:"button",disabled:rs||Vt,onClick:()=>cl(),children:c("common.retry")}),nn.kind==="format"&<.texFmtConfig.trim()&&o.jsx("button",{type:"button",disabled:rs||Vt,onClick:()=>cl(!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:()=>Ot(null),children:o.jsx(ws,{size:13})})]}),ti&&o.jsxs("div",{className:"client-tool-recovery format-lease-status",role:"status",children:[o.jsx(tt,{className:"spin",size:15}),o.jsx("span",{children:c("editor.formattingBy",{name:ti.holderName})})]})]}),du&&o.jsxs("div",{className:"client-tool-recovery",role:"status",children:[o.jsx(Pt,{size:15}),o.jsx("span",{children:c("history.saveWarning")})]}),I&&o.jsx("div",{className:"toast",onClick:()=>G(""),children:I}),Re&&o.jsx("div",{className:"toast success",onClick:()=>F(""),children:Re}),o.jsxs(Jd,{autoSaveId:"texlite-workspace-layout",direction:"horizontal",className:"work-grid",children:[Tn&&o.jsx(Rw,{project:u,filesPanel:Ms,files:wt,visibleEntries:Ju,activeFile:S,activeMainFile:Y,rootDocuments:j,selectedFolder:Yo,expandedFolders:Iu,fileDragActive:Bu,uploadingFiles:Vu,readOnly:Vt,formatting:rs,canFormat:Bs(S),activeFormatLease:!!ei,collaborationSynced:Ge,editorFontSize:lt.fontSize,outline:Td,sourceCursorStore:me,wordCountBusy:Lr,hasSelection:!!Pe.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(S),hasFormatSelection:!!Pe.selectedText.trim(),uploadInput:au,setSelectedFolder:Vr,setExpandedFolders:Xo,setMoveEntry:Qo,setMoveName:Zo,setMoveDestination:el,setDeleteEntry:tl,setFileDialogError:Go,setNewFolderName:Jo,setNewFolderOpen:Ko,setNewFilePath:Ho,setNewFileOpen:qo,setQuickOpen:jt,setProjectSearchOpen:N,setFileDragActive:Wu,setFilesCollapsed:Ce,toggleFilesPanel:ul,uploadFiles:nl,upload:Xu,openFile:Jr,onFormatFile:()=>{zo()},onFormatSelection:()=>{Bo()},jumpToSource:Ur,syncSourceToPdf:zr,onWordCount:m=>{vu(m)}}),Tn&&o.jsx(Hi,{className:"resize-handle",children:o.jsx(ga,{size:12})}),Tn&&o.jsx(Fw,{project:u,activeFile:S,activeMainFile:Y,openTabs:jn,content:K,loadedFile:oe,readOnly:Vt,comments:_n,focusComment:td,editorPreferences:lt,completionIndex:b,nativeSpellCheck:at.nativeFallback,spellCheckIssues:at.issues,spellCheckJump:at.jump,sourceJump:Su,collaborativeText:Ad,collaborationAwareness:Te.awareness,undoManager:S?Te.getUndoManager(S):void 0,editorNotice:Cd,activateTab:hl,closeTab:Ro,handleTabKeyDown:Ud,updateEditorContent:Br,setSelection:(m,y,E)=>he({selectedText:m,startOffset:y,endOffset:E}),onCommentClick:m=>{const y=_n.find(E=>E.id===m);y&&(Gr({...y}),Be("comments"))},onSpellCheckReplace:Rd,onCursor:cu}),dl&&o.jsx(zw,{projectId:n,activeMainFile:Y,previewTab:$,diagnosticTab:z,pdfUrl:Ht,pdfLoadingMode:bd,pdfLoading:Yr,pdfCompiledAt:os,pdfCompiledLabel:Nd,pdfTargetLabel:Od,pdfDownloadUrl:Md,pdfTarget:bu,pdfViewport:xu,activeFile:S,compileBusy:zs,compileLog:Xr,compileDiagnostics:xd,compileMessages:Qr,artifacts:rl,artifactPreview:Sd,artifactLoading:kd,cleaning:ol,readOnly:Vt,collaborationSynced:Ge,workspaceLayout:be,showSyncResize:Tn&&dl,diagnosticCount:Fd,selectPreviewTab:le,changeWorkspaceLayout:Zr,onSetNotice:F,onSetPdfViewport:ku,syncVisiblePdfToSource:ju,syncCurrentSourceToPdf:()=>{const m=De.current;if(!m)return Promise.resolve();const y=me.getCursor();return zr(m,y.line,y.column)},syncPdfToSource:Cu,canSyncWithPdf:Id,files:wt,jumpToSource:Ur,onSetCleanMode:Xe,cleanCompile:ll,viewArtifact:Dd}),o.jsx(ey,{sidePanel:we,onClose:()=>Be(null),project:u,projectId:n,site:t,files:wt,currentUserId:e.id,comments:_n,unreadMentions:Io,onMarkMentionRead:wd,onMarkAllMentionsRead:yd,targetCommentId:Ee?.commentId,targetReplyId:Ee?.replyId,onFocusComment:m=>Gr({...m}),onToggleComment:dd,onReplyComment:hd,onEditComment:fd,onDeleteComment:pd,onEditCommentReply:md,onDeleteCommentReply:gd,dictionaryWords:w,onDictionaryChange:g,editorPreferences:lt,onEditorPreferences:al,spellCheckCount:at.summary?.total??null,spellCheckUniqueCount:at.summary?.unique??null,spellCheckIndex:at.summary?at.index:-1,onSpellCheckNavigate:at.jumpToIssue,onProject:f})]}),W&&o.jsx(fa,{title:c("editor.wordCountTitle"),onClose:()=>Nt(!1),children:o.jsx(sy,{open:!0,mode:ss,path:su,busy:Lr,error:iu,result:ou,onOpenChange:Nt})}),o.jsx(Xw,{user:e,project:u,projectId:n,activeFile:S,content:K,maxCitationBibtexBytes:t.maxCitationBibtexBytes,files:wt,directoryEntries:Ku,readOnly:Vt,workspaceLayout:be,changeWorkspaceLayout:Zr,resourcePreview:Au,resourcePreviewLoading:Nu,setResourcePreview:Vo,setResourcePreviewLoading:Ou,uploadConflict:qu,setUploadConflict:Hu,uploadFiles:nl,cleanMode:ft,setCleanMode:Xe,cleanCompile:ll,newFileOpen:Lu,setNewFileOpen:qo,newFilePath:Ru,setNewFilePath:Ho,newFolderOpen:Fu,setNewFolderOpen:Ko,newFolderName:Mu,setNewFolderName:Jo,selectedFolder:Yo,fileDialogError:$u,setFileDialogError:Go,createFile:Gu,createFolder:Yu,moveEntry:Pu,setMoveEntry:Qo,moveName:Uu,setMoveName:Zo,moveDestination:zu,setMoveDestination:el,movePath:Qu,deleteEntry:Kr,setDeleteEntry:tl,deleteActiveSessions:Ld,removePath:Zu,commentOpen:nd,closeComment:rd,commentSelection:ld,selection:Pe,commentText:id,setCommentText:od,commentSubmitting:ad,commentError:cd,addComment:ud,shareOpen:et,setShareOpen:Ne,citationLibraryOpen:ie,setCitationLibraryOpen:ht,insertCitationAtCursor:_u,quickOpen:ot,setQuickOpen:jt,projectSearchOpen:pe,setProjectSearchOpen:N,openFile:Jr,jumpToSource:Ur,selectionHistoryOpen:Q,setSelectionHistoryOpen:A,historyOpen:We,setHistoryOpen:R,gitOpen:xe,setGitOpen:dt,save:is,permissionDowngrade:fu,permissionDowngradeBusy:lu,dismissPermissionDowngrade:pu,discardPermissionDraft:_d})]})}function oy(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`
|
|
27
|
-
`).forEach((r,i)=>{const l=r.match(n);l&&e.push({level:s[l[1]],title:l[2],line:i+1})}),e}const Cy=Object.freeze(Object.defineProperty({__proto__:null,ProjectWorkspace:iy},Symbol.toStringTag,{value:"Module"}));export{ch as A,ma as C,dh as F,yl as H,Cy as P,bh as R,xl as S,_m as U,by as a,xy as b,zi as c,Sy as d,ky as e,bn as f,gy as g,$t as h,py as i,uh as j,Jt as k,Sh as l,Xi as m,_i as n,my as o,Lh as p,yy as r,Kh as s,wy as t};
|