texlite 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +11 -0
- package/README.md +6 -0
- package/README.zh-CN.md +6 -0
- package/dist/client/assets/AdminUsers-Dyapv-3c.js +1 -0
- package/dist/client/assets/CitationLibraryDialog-CU7Q7r0Z.js +1 -0
- package/dist/client/assets/Dashboard-DsdhFENx.js +2 -0
- package/dist/client/assets/GitDialog-CZpnKw-J.js +3 -0
- package/dist/client/assets/{GitHubAccountDialog-Cqcezf6G.js → GitHubAccountDialog-CZ8O_PjD.js} +1 -1
- package/dist/client/assets/{HistoryDialog-IurkSJuU.js → HistoryDialog-DWYErBwj.js} +3 -3
- package/dist/client/assets/LatexEditor-CssVgypt.js +141 -0
- package/dist/client/assets/{PdfPreview-BTmvQDCV.js → PdfPreview-BjghzUb1.js} +1 -1
- package/dist/client/assets/{ProjectIconPickerDialog-Cbm-0YQW.js → ProjectIconPickerDialog-CqRmgFBM.js} +1 -1
- package/dist/client/assets/{ProjectNavigationDialogs-CozcEa2v.js → ProjectNavigationDialogs-BZxI3PJO.js} +1 -1
- package/dist/client/assets/ProjectSettings-CZE_xDKn.js +1 -0
- package/dist/client/assets/ProjectWorkspace-CAX3qEYr.js +32 -0
- package/dist/client/assets/{SelectionHistoryDialog-DiRKiMEt.js → SelectionHistoryDialog-CR5c3I8k.js} +2 -2
- package/dist/client/assets/{SystemMetricsDialog-DJJZueSr.js → SystemMetricsDialog-DDpFwgXh.js} +1 -1
- package/dist/client/assets/{TagManagementDialog-3c-WAWQd.js → TagManagementDialog-CXLA9h_j.js} +1 -1
- package/dist/client/assets/WordCountDialog-DUyR24vv.js +1 -0
- package/dist/client/assets/check-CwBYzomT.js +1 -0
- package/dist/client/assets/chevron-up-D5lCNKlk.js +1 -0
- package/dist/client/assets/chktex-CRkLYKcV.js +3 -0
- package/dist/client/assets/{citationLibrary-ZeQPCv5O.js → citationLibrary-C9WnXB-1.js} +2 -2
- package/dist/client/assets/{external-link-DGfNJFKy.js → external-link-C9Td1CCj.js} +1 -1
- package/dist/client/assets/{github-DJezB5ef.js → github-D-JDXb-w.js} +1 -1
- package/dist/client/assets/{hard-drive-B9h-a7KY.js → hard-drive-Ctj3K_zx.js} +1 -1
- package/dist/client/assets/{index-DmBKxZf9.js → index-9hnQ8Q9x.js} +1 -1
- package/dist/client/assets/index-C0qg2Ylw.css +1 -0
- package/dist/client/assets/index-DkpU9Fgs.js +10 -0
- package/dist/client/assets/index-_eYe7K9T.js +1 -0
- package/dist/client/assets/{minimize-2-Crq_SyYM.js → minimize-2-BiVyoWZA.js} +1 -1
- package/dist/client/assets/{minus-Dn3USloe.js → minus-Bl8l4LXq.js} +1 -1
- package/dist/client/assets/{plus-BwKRQJHI.js → plus-CCxK-HNt.js} +1 -1
- package/dist/client/assets/{refresh-cw-C5yVKb1r.js → refresh-cw-BE8IbaHI.js} +1 -1
- package/dist/client/assets/{search-CDyQWr9H.js → search-CPbhRWQE.js} +1 -1
- package/dist/client/assets/{sigma-9fiQHdlo.js → sigma-LxGD9tK2.js} +1 -1
- package/dist/client/assets/spellCheck-hpm8qZTr.js +1 -0
- package/dist/client/assets/{tags-C_3BvsxV.js → tags-DuN89PsZ.js} +1 -1
- package/dist/client/assets/{type-CnT0mBxu.js → type-BiettCiY.js} +1 -1
- package/dist/client/assets/{x-DN0Ol4Ya.js → x-C_3swJOC.js} +1 -1
- package/dist/client/index.html +3 -3
- package/dist/client/texlite-icon.svg +8 -0
- package/dist/server/auth.js +0 -3
- package/dist/server/chktex.js +3 -4
- package/dist/server/i18n.js +4 -0
- package/dist/server/latexCompletion.js +11 -88
- package/dist/server/projectOutline.js +4 -39
- package/dist/server/projectSearch.js +0 -4
- package/dist/server/routes/citations.js +22 -0
- package/dist/server/routes/users.js +21 -3
- package/dist/shared/bibtexReferences.js +5 -1
- package/dist/shared/latexCompletion.js +1 -0
- package/dist/shared/latexReferences.js +13 -3
- package/dist/shared/latexSymbols.js +77 -0
- package/package.json +1 -1
- package/dist/client/assets/AdminUsers-Cau9nlv9.js +0 -1
- package/dist/client/assets/CitationLibraryDialog-Cf_bbSq3.js +0 -1
- package/dist/client/assets/Dashboard-JQ8pJe2d.js +0 -2
- package/dist/client/assets/GitDialog-BcqqWKr-.js +0 -3
- package/dist/client/assets/LatexEditor-msdbtTyG.js +0 -141
- package/dist/client/assets/ProjectSettings-BlthcpdA.js +0 -1
- package/dist/client/assets/ProjectWorkspace-DUPLJCQ3.js +0 -32
- package/dist/client/assets/WordCountDialog-BqlX2s36.js +0 -1
- package/dist/client/assets/check-EZ2H-iDj.js +0 -1
- package/dist/client/assets/chktex-CZIYuMLb.js +0 -3
- package/dist/client/assets/index-BgeOKYIx.js +0 -10
- package/dist/client/assets/index-CMBalIBd.css +0 -1
- package/dist/client/assets/spellCheck-BCpcq-VN.js +0 -1
- package/dist/client/assets/user-plus-pxz36w4w.js +0 -1
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./spellCheck-hpm8qZTr.js","./index-DkpU9Fgs.js","./react-CltQJflK.js","./index-C0qg2Ylw.css","./chevron-up-D5lCNKlk.js","./check-CwBYzomT.js","./x-C_3swJOC.js","./search-CPbhRWQE.js","./index-_eYe7K9T.js","./refresh-cw-BE8IbaHI.js","./chktex-CRkLYKcV.js","./LatexEditor-CssVgypt.js","./editor-CLY5CgkY.js","./CitationLibraryDialog-CU7Q7r0Z.js","./tags-DuN89PsZ.js","./plus-CCxK-HNt.js","./citationLibrary-C9WnXB-1.js","./GitDialog-CZpnKw-J.js","./github-D-JDXb-w.js","./external-link-C9Td1CCj.js","./minus-Bl8l4LXq.js","./minimize-2-BiVyoWZA.js","./HistoryDialog-DWYErBwj.js","./index-9hnQ8Q9x.js","./hard-drive-Ctj3K_zx.js","./SelectionHistoryDialog-CR5c3I8k.js","./ProjectNavigationDialogs-BZxI3PJO.js","./ProjectSettings-CZE_xDKn.js","./type-BiettCiY.js","./sigma-LxGD9tK2.js","./WordCountDialog-DUyR24vv.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as Ae,s as Tn,h as ye,g as be,A as Pr,a as vs,n as Ep,l as jp,r as Dp,_ as _t,S as Tp,d as ut,i as Us,k as Mc,C as Ws,M as dn,e as Ic,u as ks,m as qs,o as An,p as Fr,q as Rp,t as Vi,v as _p,w as Lp,x as Ap,y as Np}from"./index-DkpU9Fgs.js";import{r as u,u as Je,j as o,P as ni,d as Vo,T as Op,R as Pp,a as $c,b as Fp,e as Mp}from"./react-CltQJflK.js";import{C as rr,a as Ip}from"./chevron-up-D5lCNKlk.js";import{C as $p}from"./check-CwBYzomT.js";import{f as Up,U as Mr,B as zp,M as Bp,G as Wp,X as mn,e as si,j as go,b as qp,c as Dl,N as Vp,d as Uc,F as Hp,g as Tl,h as Kp,k as Nt,C as Ho,a as Gp,T as On,L as Jp,S as wo,D as Ir,E as Yp,P as Xp,A as Vs,i as Zp}from"./x-C_3swJOC.js";import{S as Qp}from"./search-CPbhRWQE.js";import{D as em,a as tm,b as nm,c as sm,d as Rl,U as rm,e as zc,P as im,f as om,g as am}from"./index-_eYe7K9T.js";import{R as lm}from"./refresh-cw-BE8IbaHI.js";const cm=Ae("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const um=Ae("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);const dm=Ae("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const bo=Ae("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Ko=Ae("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 _l=Ae("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const yo=Ae("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 fm=Ae("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]]);const hm=Ae("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 pm=Ae("FileCog",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3.2 12.9-.9-.4",key:"1i3dj5"}],["path",{d:"m3.2 15.1-.9.4",key:"1fvgj0"}],["path",{d:"M4.677 21.5a2 2 0 0 0 1.313.5H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2.5",key:"1yo3oz"}],["path",{d:"m4.9 11.2-.4-.9",key:"otmhb9"}],["path",{d:"m4.9 16.8-.4.9",key:"1b8z07"}],["path",{d:"m7.5 10.3-.4.9",key:"11k65u"}],["path",{d:"m7.5 17.7-.4-.9",key:"431x55"}],["path",{d:"m9.7 12.5-.9.4",key:"87sjan"}],["path",{d:"m9.7 15.5-.9-.4",key:"khqm91"}],["circle",{cx:"6",cy:"14",r:"3",key:"a1xfv6"}]]);const mm=Ae("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);const gm=Ae("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 wm=Ae("FileType2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 13v-1h6v1",key:"1dh9dg"}],["path",{d:"M5 12v6",key:"150t9c"}],["path",{d:"M4 18h2",key:"1xrofg"}]]);const bm=Ae("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]]);const ym=Ae("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);const Bc=Ae("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 Ll=Ae("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 xm=Ae("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 Sm=Ae("LibraryBig",[["rect",{width:"8",height:"18",x:"3",y:"3",rx:"1",key:"oynpb5"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",key:"1qboyk"}]]);const vm=Ae("MessagesSquare",[["path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z",key:"p1xzt8"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1",key:"1cx29u"}]]);const Al=Ae("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 Wc=Ae("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 qc=Ae("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 km=Ae("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 Cm=Ae("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const Em=Ae("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const jm=Ae("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const Dm=Ae("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 Tm=Ae("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 Rm=Ae("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 _m=Ae("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 Lm=Ae("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"}]]),Am="wrap = false",xo=[{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'}],Dt={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,showTooltips:!1,spellCheck:!0,mathPreviewOnHover:!1,vimMode:!1,formatOnCompile:!1,texFmtConfig:Am,texFmtConfigInitialized:!0,openFilesInTabs:!1},Nm="texlite-editor-preferences";function Vc(t,e){return Tn(`${Nm}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function lv(t){return xo.find(e=>e.id===t)?.stack??xo[0].stack}function Nl(t,e){try{const n=JSON.parse(localStorage.getItem(Vc(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:Dt.texFmtConfig;return{font:xo.some(i=>i.id===n.font)?n.font:Dt.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):Dt.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):Dt.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:Dt.lineWrapping,showTooltips:typeof n.showTooltips=="boolean"?n.showTooltips:Dt.showTooltips,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:Dt.spellCheck,mathPreviewOnHover:typeof n.mathPreviewOnHover=="boolean"?n.mathPreviewOnHover:Dt.mathPreviewOnHover,vimMode:typeof n.vimMode=="boolean"?n.vimMode:Dt.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:Dt.formatOnCompile,texFmtConfig:r,texFmtConfigInitialized:!0,openFilesInTabs:typeof n.openFilesInTabs=="boolean"?n.openFilesInTabs:Dt.openFilesInTabs}}catch{return Dt}}function Om(t,e,n){localStorage.setItem(Vc(t,e),JSON.stringify(n))}function Pm(){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 fn=Pm(),Fm=/\.(?:tex|bib|cls|sty)$/i,Hc=3e4;let At=null,$r=!1,Rn=null,Mm=1;const Pn=new Map,Ur=[];let rs=null,Is=null;class Et extends Error{constructor(e,n){super(n),this.kind=e,this.name="TexFmtError"}kind}function Hi(t){return t instanceof Et}function Qt(t){At?.terminate(),At=null,$r=!1,Rn!==null&&window.clearTimeout(Rn),Rn=null,rs=null,Ur.length=0,Is=null,fn.failed(t);for(const e of Pn.values())e.timeout!==null&&window.clearTimeout(e.timeout),e.reject(t);Pn.clear()}function zs(){if(rs!==null||Ur.length===0)return;let t;try{t=Im()}catch(s){Qt(s instanceof Et?s:new Et("load","The bundled tex-fmt formatter could not be loaded."));return}if(!$r)return;const e=Ur.shift();if(e===void 0)return;const n=Pn.get(e);if(!n){zs();return}rs=e,n.timeout=window.setTimeout(()=>{rs===e&&Qt(new Et("result","The formatter did not respond within 30 seconds."))},Hc);try{t.postMessage({...n.request,id:e})}catch{Qt(new Et("load","The formatter worker could not receive the source."))}}function Im(){if(At)return At;if(typeof Worker>"u"){const t=new Et("load","This browser does not support formatter workers.");throw fn.failed(t),t}fn.loading();try{At=new Worker(new URL(""+new URL("latexFormatterWorker-BRmsns8a.js",import.meta.url).href,import.meta.url),{type:"module",name:"texlite-latex-formatter"}),Rn=window.setTimeout(()=>{$r||Qt(new Et("load","The formatter did not finish loading within 30 seconds."))},Hc)}catch{const t=new Et("load","The bundled tex-fmt formatter could not be loaded.");throw fn.failed(t),t}return At.onmessage=t=>{const e=t.data;if(e&&"type"in e){e.type==="ready"&&($r=!0,Rn!==null&&window.clearTimeout(Rn),Rn=null,zs());return}if(!e||typeof e.id!="number"){Qt(new Et("result","The formatter worker returned an invalid response."));return}const n=Pn.get(e.id);if(n)if(Pn.delete(e.id),n.timeout!==null&&window.clearTimeout(n.timeout),rs===e.id&&(rs=null),e.ok)fn.working(),n.resolve(e.result),zs();else{const s=new Et(e.kind,e.message);e.kind==="format"?(fn.working(),n.reject(s),zs()):(n.reject(s),Qt(s))}},At.onerror=()=>{Qt(new Et("load","The bundled tex-fmt formatter could not be loaded."))},At.onmessageerror=()=>{Qt(new Et("result","The formatter worker returned an unreadable response."))},At}function Go(t){const e=Mm++;return new Promise((n,s)=>{Pn.set(e,{request:t,resolve:n,reject:s,timeout:null}),Ur.push(e),zs()})}function $m(t,e=""){return Go({action:"format",source:t,config:e})}async function Um(){At&&fn.getSnapshot().status==="working"||(Is||(Is=Go({action:"probe"}).then(()=>{}).finally(()=>{Is=null})),await Is)}async function cv(){(At||Pn.size)&&Qt(new Et("load","The formatter runtime was reloaded.")),fn.loading(),await Um()}function Er(t){return Fm.test(t)}function zm(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function Bm(t,e){const n=zm(t),a=(n?t.slice(0,-n.length):t).split(/\r?\n/).find(d=>d.trim())?.match(/^[\t ]*/)?.[0]??"",l=e.replace(/(?:\r?\n)+$/,"");return`${a?l.split(`
|
|
3
|
+
`).map(d=>d&&`${a}${d}`).join(`
|
|
4
|
+
`):l}${n}`}async function Ki(t,e,n=0){return Go({action:"diff",source:t,formatted:e,baseOffset:n})}function Wm(t,e=null){const n=Ol(t),r=e==="succeeded"||e===null&&Vm(t)?[]:Pl(n.filter(Fl)),i=Ol(qm(t));return{warnings:Pl(i.filter(l=>!Fl(l)&&Hm(l))),errors:r}}function Ol(t){return t.split(`
|
|
5
|
+
`).map(e=>e.trim()).filter(Boolean)}function Pl(t){return[...new Set(t)]}function qm(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 Vm(t){return/Latexmk: All targets .* are up-to-date/i.test(t)&&/Output written on .*\.pdf/i.test(t)}function Fl(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 Hm(t){return/\bwarnings?\b|overfull|underfull|badness/i.test(t)}const Ml=1,Il=2,Gi=4,Ji=8,Hs=32,en=64,gt=128,Km=1<<29,ri=31,So=63,Nn=127,Gm=2147483647,Ut=(t,e)=>t>>>e|t<<32-e,Jm=t=>Ut(t,2)^Ut(t,13)^Ut(t,22),Ym=t=>Ut(t,6)^Ut(t,11)^Ut(t,25),Xm=t=>Ut(t,7)^Ut(t,18)^t>>>3,Zm=t=>Ut(t,17)^Ut(t,19)^t>>>10,Qm=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]),eg=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);class tg{constructor(){const e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(eg),this._W=new Uint32Array(e,64,64)}_updateHash(){const e=this._H,n=this._W;for(let h=16;h<64;h++)n[h]=Zm(n[h-2])+n[h-7]+Xm(n[h-15])+n[h-16];let s=e[0],r=e[1],i=e[2],a=e[3],l=e[4],c=e[5],d=e[6],f=e[7];for(let h=0,p,m;h<64;h++)p=f+Ym(l)+(l&c^~l&d)+Qm[h]+n[h]>>>0,m=Jm(s)+(s&r^s&i^r&i)>>>0,f=d,d=c,c=l,l=a+p>>>0,a=i,i=r,r=s,s=p+m>>>0;e[0]+=s,e[1]+=r,e[2]+=i,e[3]+=a,e[4]+=l,e[5]+=c,e[6]+=d,e[7]+=f}digest(e){let n=0;for(;n+56<=e.length;){let a=0;for(;a<16&&n+3<e.length;a++)this._W[a]=e[n++]<<24|e[n++]<<16|e[n++]<<8|e[n++];if(n%64!==0){for(this._W.fill(0,a,16);n<e.length;)this._W[a]|=e[n]<<(3-n%4)*8,n++;this._W[a]|=gt<<(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 a=3;a>=0&&n<e.length;a--)this._W[r]|=e[n++]<<a*8;s||(this._W[r-(n%4===0?0:1)]|=gt<<(3-n%4)*8),this._W[14]=e.byteLength/Km,this._W[15]=e.byteLength*8,this._updateHash();const i=new Uint8Array(32);for(let a=0;a<this._H.length;a++)for(let l=0;l<4;l++)i[a*4+l]=this._H[a]>>>(3-l)*8;return i}}const ng=t=>new tg().digest(t);function sg(t){return Array.from(ng(new TextEncoder().encode(t)),e=>e.toString(16).padStart(2,"0")).join("")}const $l=Object.freeze({});class rg{threads=new Map;listeners=new Map;newComments=new Map;getThread(e){return this.threads.get(e)??$l}subscribe(e,n){const s=this.listeners.get(e)??new Set;return s.add(n),this.listeners.set(e,s),()=>{s.delete(n),s.size||this.listeners.delete(e)}}publish(e,n){Object.keys(n).length?this.threads.set(e,n):this.threads.delete(e);for(const s of this.listeners.get(e)??[])s()}isPending(e){return Object.values(this.getThread(e)).some(n=>n?.pending)}open(e,n,s=""){if(this.isPending(e))return;const r={...this.getThread(e)};if(n.startsWith("edit-reply:"))for(const[a,l]of Object.entries(r))a.startsWith("edit-reply:")&&l?.open&&(r[a]={...l,open:!1});const i=r[n];r[n]={content:s,pending:!1,error:"",...i,open:!0},this.publish(e,r)}change(e,n,s){const r=this.getThread(e)[n];!r||this.isPending(e)||this.publish(e,{...this.getThread(e),[n]:{...r,content:s}})}hide(e,n){const s=this.getThread(e)[n];!s||this.isPending(e)||this.publish(e,{...this.getThread(e),[n]:{...s,open:!1}})}discard(e,n){const s={...this.getThread(e)};if(n===void 0){this.publish(e,$l);return}delete s[n],this.publish(e,s)}async submit(e,n,s,r){const i=this.getThread(e)[n];if(!i||!i.content.trim()||this.isPending(e))return!1;const a={...i,pending:!0,error:""};this.publish(e,{...this.getThread(e),[n]:a});let l=r;try{if(await s(i.content))return this.getThread(e)[n]===a&&this.discard(e,n),!0}catch(c){l=ye(c)}return this.getThread(e)[n]===a&&this.publish(e,{...this.getThread(e),[n]:{...i,pending:!1,error:l}}),!1}getNew(e){return this.newComments.get(e)}setNew(e){this.newComments.set(e.filePath,{...e,selection:{...e.selection}})}discardNew(e){this.newComments.delete(e)}}function ig(t,e,n){const s=n instanceof Pr&&[401,403,404].includes(n.status);return{filePath:e,comments:!s&&t.filePath===e?t.comments:[],loading:!1,error:ye(n)}}function Ul(t){return t instanceof Error&&t.name==="AbortError"}function og({projectId:t,activeFile:e,content:n,permission:s,revision:r,selection:i,save:a,saveFailureMessage:l,onError:c,onAdded:d,onChanged:f}){const h=u.useMemo(()=>new rg,[t]),[p,m]=u.useState({filePath:"",comments:[],loading:!1,error:""}),[g,x]=u.useState([]),[j,C]=u.useState(!1),[z,k]=u.useState(""),[y,P]=u.useState("file"),[E,S]=u.useState(null),[N,V]=u.useState(!1),[Y,ie]=u.useState(""),[F,le]=u.useState(null),[G,J]=u.useState(null),[Z,Ee]=u.useState(!1),[ce,Q]=u.useState(!1),[$,fe]=u.useState(""),Se=u.useRef(null),ve=u.useRef(null),je=u.useRef(!1),ee=u.useRef(e),q=u.useRef(y),he=u.useRef(a),we=u.useRef(c),U=u.useRef(d),H=u.useRef(f),Te=u.useRef(F),ke=u.useRef(Y);Te.current=F,ke.current=Y,ee.current=e,q.current=y,he.current=a,we.current=c,U.current=d,H.current=f;const O=p.filePath===e?p.comments:[],I=p.filePath,te=I===e?p.error:"",Ne=!!e&&(I!==e||p.loading),_e=I===e&&!p.loading&&!te,Ie=async M=>{Se.current?.abort();const oe=new AbortController;Se.current=oe,ee.current===M&&m(Re=>Re.filePath===M?{...Re,loading:!0,error:""}:{filePath:"",comments:[],loading:!0,error:""});try{const Re=await be(`/api/projects/${t}/comments?path=${encodeURIComponent(M)}`,{signal:oe.signal});Se.current===oe&&ee.current===M&&m({filePath:M,comments:Re.comments,loading:!1,error:""})}catch(Re){!Ul(Re)&&Se.current===oe&&ee.current===M&&m(re=>ig(re,M,Re))}finally{Se.current===oe&&(Se.current=null)}},$e=()=>ee.current?Ie(ee.current):Promise.resolve(),se=async()=>{ve.current?.abort();const M=new AbortController;ve.current=M,q.current==="project"&&(C(!0),k(""));try{const oe=await be(`/api/projects/${t}/comments?scope=project`,{signal:M.signal});ve.current===M&&q.current==="project"&&x(oe.comments)}catch(oe){!Ul(oe)&&ve.current===M&&q.current==="project"&&k(ye(oe))}finally{ve.current===M&&(ve.current=null,q.current==="project"&&C(!1))}};u.useEffect(()=>{Se.current?.abort(),Se.current=null,ve.current?.abort(),ve.current=null,S(null),m({filePath:"",comments:[],loading:!1,error:""}),x([]),C(!1),k(""),P("file"),V(!1),le(null),J(null),ie(""),Ee(!1),fe("")},[t]),u.useEffect(()=>{V(!1),le(null),J(null),ie(""),Ee(!1),fe("")},[e]),u.useEffect(()=>(e?Ie(e):m({filePath:"",comments:[],loading:!1,error:""}),()=>{Se.current?.abort(),Se.current=null}),[t,e,r]),u.useEffect(()=>{if(y!=="project"){ve.current?.abort(),ve.current=null,x([]),C(!1),k("");return}return se(),()=>{ve.current?.abort(),ve.current=null}},[t,y,r]);const xe=async M=>{const oe=[];ee.current===M&&oe.push(Ie(M)),q.current==="project"&&oe.push(se()),await Promise.all(oe)},Pe=(M,oe)=>{if(!e)return;fe("");const Re={filePath:e,selection:{...M??i},sourceHash:sg(oe??n)},re=h.getNew(e);le(re??Re),ie(re?.content??""),J(Re),Ee(!!re),V(!0)},Le=M=>{ie(M),F&&(M?h.setNew({...F,content:M}):h.discardNew(F.filePath))},D=()=>{je.current||(V(!1),fe(""))},ue=()=>{je.current||(F&&h.discardNew(F.filePath),ie(""),le(null),J(null),Ee(!1),D())},Ue=()=>{je.current||!G||G.filePath!==ee.current||(le(G),Y&&h.setNew({...G,content:Y}),Ee(!1),fe(""))},Ye=async()=>{const M=F,oe=Y;if(!Y.trim()||!M||je.current)return;const Re=()=>{const re=Te.current;return re?.filePath===M.filePath&&re.sourceHash===M.sourceHash&&re.selection.startOffset===M.selection.startOffset&&re.selection.endOffset===M.selection.endOffset&&ke.current===oe};je.current=!0,Q(!0),fe("");try{if(s!=="read"&&!await he.current()){Re()&&fe(l);return}await be(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:M.filePath,content:oe,...M.selection,sourceHash:M.sourceHash})}),await xe(M.filePath);const re=h.getNew(M.filePath);re?.content===oe&&re.sourceHash===M.sourceHash&&re.selection.startOffset===M.selection.startOffset&&re.selection.endOffset===M.selection.endOffset&&h.discardNew(M.filePath),Re()&&(V(!1),le(null),ie(""),Ee(!1)),U.current(),H.current?.()}catch(re){Re()&&fe(ye(re))}finally{je.current=!1,Q(!1)}},nt=async M=>{try{await be(`/api/projects/${t}/comments/${M.id}`,{method:"PATCH",body:JSON.stringify({resolved:!M.resolved})}),await xe(M.filePath),H.current?.()}catch(oe){we.current(ye(oe))}},pe=async(M,oe)=>(await be(`/api/projects/${t}/comments/${M.id}/replies`,{method:"POST",body:JSON.stringify({content:oe})}),await xe(M.filePath),H.current?.(),!0),A=async(M,oe)=>(await be(`/api/projects/${t}/comments/${M.id}`,{method:"PATCH",body:JSON.stringify({content:oe})}),await xe(M.filePath),H.current?.(),!0),X=async M=>{try{return await be(`/api/projects/${t}/comments/${M.id}`,{method:"DELETE"}),await xe(M.filePath),S(oe=>oe?.id===M.id?null:oe),h.discard(M.id),H.current?.(),!0}catch(oe){return we.current(ye(oe)),!1}},Oe=async(M,oe,Re)=>(await be(`/api/projects/${t}/comments/${M.id}/replies/${oe}`,{method:"PATCH",body:JSON.stringify({content:Re})}),await xe(M.filePath),H.current?.(),!0),ze=async(M,oe)=>{try{return await be(`/api/projects/${t}/comments/${M.id}/replies/${oe}`,{method:"DELETE"}),await xe(M.filePath),h.discard(M.id,`edit-reply:${oe}`),H.current?.(),!0}catch(Re){return we.current(ye(Re)),!1}};return{commentDraftStore:h,comments:O,commentsFilePath:I,commentsReady:_e,fileCommentsLoading:Ne,fileCommentsError:te,retryFileComments:$e,reviewComments:y==="file"?O:g,reviewCommentsLoading:y==="project"?j:Ne,reviewCommentsError:y==="project"?z:te,retryReviewComments:y==="project"?se:$e,commentScope:y,setCommentScope:P,focusComment:E,setFocusComment:S,commentOpen:N,openComment:Pe,closeComment:D,cancelComment:ue,commentDraftRestored:Z,commentDraftCanRetarget:!!(F&&G&&(F.sourceHash!==G.sourceHash||F.selection.startOffset!==G.selection.startOffset||F.selection.endOffset!==G.selection.endOffset)),useCurrentCommentSelection:Ue,commentText:Y,setCommentText:Le,commentSelection:F?.selection??i,commentSubmitting:ce,commentError:$,addComment:Ye,toggleComment:nt,replyToComment:pe,editComment:A,deleteComment:X,editCommentReply:Oe,deleteCommentReply:ze}}function ag(t){const e=new Map;for(const n of t)for(const s of[n,...n.replies])e.has(s.authorId)||e.set(s.authorId,{authorId:s.authorId,authorUsername:s.authorUsername,authorDisplayName:s.authorDisplayName});return[...e.values()].sort((n,s)=>(n.authorDisplayName??n.authorUsername??"").localeCompare(s.authorDisplayName??s.authorUsername??""))}function Kc(t,e){const n=e.participantIds;return n?.size?n.has(t.authorId)||!e.topLevelOnly&&t.replies.some(s=>n.has(s.authorId)):!0}function lg(t,e="source"){return[...t].sort((n,s)=>e==="time"?Date.parse(s.createdAt)-Date.parse(n.createdAt):n.filePath.localeCompare(s.filePath,"en",{numeric:!0})||n.startLine-s.startLine||n.startOffset-s.startOffset)}function Gc(t,e){return e.scope==="project"||t.filePath===e.activeFile}function Jo(t,e){return e==="unresolved"?!t.resolved:t.resolved}function Jc(t,e){return e.some(n=>n.commentId===t.id&&n.readAt===null)}function Yi(t,e){return t.filter(n=>Gc(n,e)&&Kc(n,e)&&Jo(n,e.filter)&&(!e.unreadMentionsOnly||Jc(n,e.unreadMentions)))}function cg(t,e,n=[]){const s=new Set(n.filter(r=>!!r));return lg(t.filter(r=>Gc(r,e)?s.has(r.id)||Kc(r,e)&&Jo(r,e.filter)&&(!e.unreadMentionsOnly||Jc(r,e.unreadMentions)):!1),e.sort)}function ug(t,e,n){const s=t.find(r=>r.id===e&&r.filePath===n&&!r.resolved);return s?[s]:[]}function dg(t,e){return t.filter(n=>n.filePath===e)}function fg(t,e,n){return!t||t.filePath!==e||n!==e?null:t}function hg(t,e,n,s,r,i){return!t||t.filePath!==e||n!==e||s!==e||!r?null:i.find(a=>a.id===t.id&&a.filePath===e)??null}function pg(t,e){if(!e)return 0;const n=t.findIndex(s=>s.id===e);return n<0?0:n+1}function mg(t,e,n){if(!t.length)return null;const s=e?t.findIndex(i=>i.id===e):-1;if(s<0)return n===1?t[0]:null;const r=s+n;return r>=0&&r<t.length?t[r]:null}function gg(t){return t instanceof Error&&t.name==="AbortError"}function wg(t,e,n){const[s,r]=u.useState([]),i=u.useRef(null),a=u.useRef(n);a.current=n;const l=u.useCallback(async(f=!1)=>{i.current?.abort();const h=new AbortController;i.current=h;try{const p=await be(`/api/projects/${t}/mentions?unread=1&limit=100`,{signal:h.signal});i.current===h&&r(p.mentions)}catch(p){i.current===h&&!gg(p)&&(r([]),f&&a.current(ye(p)))}finally{i.current===h&&(i.current=null)}},[t]);return u.useEffect(()=>(l(),()=>{i.current?.abort(),i.current=null}),[l,e]),{unreadMentions:s,refresh:l,markMentionRead:async f=>{try{return await be(`/api/projects/${t}/mentions/${encodeURIComponent(f)}/read`,{method:"POST"}),r(h=>h.filter(p=>p.id!==f)),!0}catch(h){return a.current(ye(h)),!1}},markAllMentionsRead:async()=>{if(!s.length)return!0;try{return await be(`/api/projects/${t}/mentions/read-all`,{method:"POST"}),r([]),!0}catch(f){return a.current(ye(f)),!1}}}}const St=()=>new Map,vo=t=>{const e=St();return t.forEach((n,s)=>{e.set(s,n)}),e},Wt=(t,e,n)=>{let s=t.get(e);return s===void 0&&t.set(e,s=n()),s},bg=(t,e)=>{const n=[];for(const[s,r]of t)n.push(e(r,s));return n},yg=(t,e)=>{for(const[n,s]of t)if(e(s,n))return!0;return!1},gn=()=>new Set,Xi=t=>t[t.length-1],xg=(t,e)=>{for(let n=0;n<e.length;n++)t.push(e[n])},tn=Array.from,Yo=(t,e)=>{for(let n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0},Xo=(t,e)=>{for(let n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1},Sg=(t,e)=>{const n=new Array(t);for(let s=0;s<t;s++)n[s]=e(s,n);return n},hs=Array.isArray;class Zo{constructor(){this._observers=St()}on(e,n){return Wt(this._observers,e,gn).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 tn((this._observers.get(e)||St()).values()).forEach(s=>s(...n))}destroy(){this._observers=St()}}class Yc{constructor(){this._observers=St()}on(e,n){Wt(this._observers,e,gn).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 tn((this._observers.get(e)||St()).values()).forEach(s=>s(...n))}destroy(){this._observers=St()}}const Pt=Math.floor,Lr=Math.abs,Qo=(t,e)=>t<e?t:e,$n=(t,e)=>t>e?t:e,vg=Math.pow,Xc=t=>t!==0?t<0:1/t<0,zr=Number.MAX_SAFE_INTEGER,zl=Number.MIN_SAFE_INTEGER,kg=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Pt(t)===t),Zc=String.fromCharCode,Cg=t=>t.toLowerCase(),Eg=/^\s*/g,jg=t=>t.replace(Eg,""),Dg=/([A-Z])/g,Bl=(t,e)=>jg(t.replace(Dg,n=>`${e}${Cg(n)}`)),Tg=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},Ks=typeof TextEncoder<"u"?new TextEncoder:null,Rg=t=>Ks.encode(t),_g=Ks?Rg:Tg;let Bs=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Bs&&Bs.decode(new Uint8Array).length===1&&(Bs=null);const Lg=(t,e)=>Sg(e,()=>t).join("");class ir{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Ke=()=>new ir,ea=t=>{let e=t.cpos;for(let n=0;n<t.bufs.length;n++)e+=t.bufs[n].length;return e},Me=t=>{const e=new Uint8Array(ea(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},Ag=(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($n(n,e)*2),t.cpos=0)},rt=(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},ko=rt,ne=(t,e)=>{for(;e>Nn;)rt(t,gt|Nn&e),e=Pt(e/128);rt(t,Nn&e)},ta=(t,e)=>{const n=Xc(e);for(n&&(e=-e),rt(t,(e>So?gt:0)|(n?en:0)|So&e),e=Pt(e/64);e>0;)rt(t,(e>Nn?gt:0)|Nn&e),e=Pt(e/128)},Co=new Uint8Array(3e4),Ng=Co.length/3,Og=(t,e)=>{if(e.length<Ng){const n=Ks.encodeInto(e,Co).written||0;ne(t,n);for(let s=0;s<n;s++)rt(t,Co[s])}else He(t,_g(e))},Pg=(t,e)=>{const n=unescape(encodeURIComponent(e)),s=n.length;ne(t,s);for(let r=0;r<s;r++)rt(t,n.codePointAt(r))},ct=Ks&&Ks.encodeInto?Og:Pg,ii=(t,e)=>{const n=t.cbuf.length,s=t.cpos,r=Qo(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($n(n*2,i)),t.cbuf.set(e.subarray(r)),t.cpos=i)},He=(t,e)=>{ne(t,e.byteLength),ii(t,e)},na=(t,e)=>{Ag(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},Fg=(t,e)=>na(t,4).setFloat32(0,e,!1),Mg=(t,e)=>na(t,8).setFloat64(0,e,!1),Ig=(t,e)=>na(t,8).setBigInt64(0,e,!1),Wl=new DataView(new ArrayBuffer(4)),$g=t=>(Wl.setFloat32(0,t),Wl.getFloat32(0)===t),Gs=(t,e)=>{switch(typeof e){case"string":rt(t,119),ct(t,e);break;case"number":kg(e)&&Lr(e)<=Gm?(rt(t,125),ta(t,e)):$g(e)?(rt(t,124),Fg(t,e)):(rt(t,123),Mg(t,e));break;case"bigint":rt(t,122),Ig(t,e);break;case"object":if(e===null)rt(t,126);else if(hs(e)){rt(t,117),ne(t,e.length);for(let n=0;n<e.length;n++)Gs(t,e[n])}else if(e instanceof Uint8Array)rt(t,116),He(t,e);else{rt(t,118);const n=Object.keys(e);ne(t,n.length);for(let s=0;s<n.length;s++){const r=n[s];ct(t,r),Gs(t,e[r])}}break;case"boolean":rt(t,e?120:121);break;default:rt(t,127)}};class ql extends ir{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&ne(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Vl=t=>{t.count>0&&(ta(t.encoder,t.count===1?t.s:-t.s),t.count>1&&ne(t.encoder,t.count-2))};class Ar{constructor(){this.encoder=new ir,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Vl(this),this.count=1,this.s=e)}toUint8Array(){return Vl(this),Me(this.encoder)}}const Hl=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);ta(t.encoder,e),t.count>1&&ne(t.encoder,t.count-2)}};class Zi{constructor(){this.encoder=new ir,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Hl(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Hl(this),Me(this.encoder)}}class Ug{constructor(){this.sarr=[],this.s="",this.lensE=new Ar}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 ir;return this.sarr.push(this.s),this.s="",ct(e,this.sarr.join("")),ii(e,this.lensE.toUint8Array()),Me(e)}}const Ft=t=>new Error(t),Ot=()=>{throw Ft("Method unimplemented")},jt=()=>{throw Ft("Unexpected case")},Qc=Ft("Unexpected end of array"),eu=Ft("Integer out of Range");class oi{constructor(e){this.arr=e,this.pos=0}}const yn=t=>new oi(t),Eo=t=>t.pos!==t.arr.length,zg=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},pt=t=>zg(t,ge(t)),ps=t=>t.arr[t.pos++],ge=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&Nn)*n,n*=128,r<gt)return e;if(e>zr)throw eu}throw Qc},sa=t=>{let e=t.arr[t.pos++],n=e&So,s=64;const r=(e&en)>0?-1:1;if((e>)===0)return r*n;const i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],n=n+(e&Nn)*s,s*=128,e<gt)return r*n;if(n>zr)throw eu}throw Qc},Bg=t=>{let e=ge(t);if(e===0)return"";{let n=String.fromCodePoint(ps(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(ps(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))}},Wg=t=>Bs.decode(pt(t)),Ve=Bs?Wg:Bg,ra=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},qg=t=>ra(t,4).getFloat32(0,!1),Vg=t=>ra(t,8).getFloat64(0,!1),Hg=t=>ra(t,8).getBigInt64(0,!1),Kg=[t=>{},t=>null,sa,qg,Vg,Hg,t=>!1,t=>!0,Ve,t=>{const e=ge(t),n={};for(let s=0;s<e;s++){const r=Ve(t);n[r]=Js(t)}return n},t=>{const e=ge(t),n=[];for(let s=0;s<e;s++)n.push(Js(t));return n},pt],Js=t=>Kg[127-ps(t)](t);class Kl extends oi{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Eo(this)?this.count=ge(this)+1:this.count=-1),this.count--,this.s}}class Nr extends oi{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=sa(this);const e=Xc(this.s);this.count=1,e&&(this.s=-this.s,this.count=ge(this)+2)}return this.count--,this.s}}class Qi extends oi{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=sa(this),n=e&1;this.diff=Pt(e/2),this.count=1,n&&(this.count=ge(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Gg{constructor(e){this.decoder=new Nr(e),this.str=Ve(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 Jg=crypto.getRandomValues.bind(crypto),tu=()=>Jg(new Uint32Array(1))[0],Yg="10000000-1000-4000-8000"+-1e11,Xg=()=>Yg.replace(/[018]/g,t=>(t^tu()&15>>t/4).toString(16)),wn=Date.now,ms=t=>new Promise(t);Promise.all.bind(Promise);const Gl=t=>t===void 0?null:t;class Zg{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let nu=new Zg,ia=!0;try{typeof localStorage<"u"&&localStorage&&(nu=localStorage,ia=!1)}catch{}const su=nu,Qg=t=>ia||addEventListener("storage",t),ew=t=>ia||removeEventListener("storage",t),Ys=Symbol("Equality"),ru=(t,e)=>t===e||!!t?.[Ys]?.(e)||!1,tw=t=>typeof t=="object",nw=Object.assign,sw=Object.keys,rw=(t,e)=>{for(const n in t)e(t[n],n)},iw=(t,e)=>{const n=[];for(const s in t)n.push(e(t[s],s));return n},Br=t=>sw(t).length,ow=t=>{for(const e in t)return!1;return!0},or=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},oa=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),aw=(t,e)=>t===e||Br(t)===Br(e)&&or(t,(n,s)=>(n!==void 0||oa(e,s))&&ru(e[s],n)),lw=Object.freeze,iu=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&iu(t[e])}return lw(t)},aa=(t,e,n=0)=>{try{for(;n<t.length;n++)t[n](...e)}finally{n<t.length&&aa(t,e,n+1)}},cw=t=>t,is=(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[Ys]!=null)return t[Ys](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)||!is(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(Br(t)!==Br(e))return!1;for(const n in t)if(!oa(t,n)||!is(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(!is(t[n],e[n]))return!1;break;default:return!1}return!0},uw=(t,e)=>e.includes(t);var ou={};const bn=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",au=typeof window<"u"&&typeof document<"u"&&!bn;let $t;const dw=()=>{if($t===void 0)if(bn){$t=St();const t=process.argv;let e=null;for(let n=0;n<t.length;n++){const s=t[n];s[0]==="-"?(e!==null&&$t.set(e,""),e=s):e!==null&&($t.set(e,s),e=null)}e!==null&&$t.set(e,"")}else typeof location=="object"?($t=St(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,n]=t.split("=");$t.set(`--${Bl(e,"-")}`,n),$t.set(`-${Bl(e,"-")}`,n)}})):$t=St();return $t},jo=t=>dw().has(t),Wr=t=>Gl(bn?ou[t.toUpperCase().replaceAll("-","_")]:su.getItem(t)),lu=t=>jo("--"+t)||Wr(t)!==null,fw=lu("production"),hw=bn&&uw(ou.FORCE_COLOR,["true","1","2"]),pw=hw||!jo("--no-colors")&&!lu("no-color")&&(!bn||process.stdout.isTTY)&&(!bn||jo("--color")||Wr("COLORTERM")!==null||(Wr("TERM")||"").includes("color")),cu=t=>new Uint8Array(t),mw=(t,e,n)=>new Uint8Array(t,e,n),gw=t=>new Uint8Array(t),ww=t=>{let e="";for(let n=0;n<t.byteLength;n++)e+=Zc(t[n]);return btoa(e)},bw=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),yw=t=>{const e=atob(t),n=cu(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n},xw=t=>{const e=Buffer.from(t,"base64");return mw(e.buffer,e.byteOffset,e.byteLength)},Sw=au?ww:bw,vw=au?yw:xw,kw=t=>{const e=cu(t.byteLength);return e.set(t),e};class Cw{constructor(e,n){this.left=e,this.right=n}}const Yt=(t,e)=>new Cw(t,e),Ew=(t,e)=>t.forEach(n=>e(n.left,n.right)),Jl=t=>t.next()>=.5,eo=(t,e,n)=>Pt(t.next()*(n+1-e)+e),uu=(t,e,n)=>Pt(t.next()*(n+1-e)+e),la=(t,e,n)=>uu(t,e,n),jw=t=>Zc(la(t,97,122)),Dw=(t,e=0,n=20)=>{const s=la(t,e,n);let r="";for(let i=0;i<s;i++)r+=jw(t);return r},to=(t,e)=>e[la(t,0,e.length-1)],Tw=Symbol("0schema");class Rw{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(Lg(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return e.join(`
|
|
6
|
+
`)}}const Do=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[Ys]?ru(t,e):hs(t)?Yo(t,n=>Xo(e,s=>Do(n,s))):tw(t)?or(t,(n,s)=>Do(n,e[s])):!1;class wt{static _dilutes=!1;extends(e){let[n,s]=[this.shape,e.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Do(n,s)}equals(e){return this.constructor===e.constructor&&is(this.shape,e.shape)}[Tw](){return!0}[Ys](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){Ot()}get nullable(){return Cs(this,di)}get optional(){return new hu(this)}cast(e){return Yl(e,this),e}expect(e){return Yl(e,this),e}}class ca extends wt{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 tt=(t,e=null)=>new ca(t,e);tt(ca);class ua extends wt{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 at=t=>new ua(t);tt(ua);class ai extends wt{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 li=(...t)=>new ai(t),du=tt(ai),_w=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),fu=t=>{if(gs.check(t))return[_w(t)];if(du.check(t))return t.shape.map(e=>e+"");if(vu.check(t))return["[+-]?\\d+.?\\d*"];if(ku.check(t))return[".*"];if(qr.check(t))return t.shape.map(fu).flat(1);jt()};class Lw extends wt{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(fu).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}}tt(Lw);const Aw=Symbol("optional");class hu extends wt{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[Aw](){return!0}}const Nw=tt(hu);class Ow extends wt{check(e,n){return n?.extend(null,"never",typeof e),!1}}tt(Ow);class ci extends wt{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}static _dilutes=!0;get partial(){return new ci(this.shape,!0)}check(e,n){return e==null?(n?.extend(null,"object","null"),!1):or(this.shape,(s,r)=>{const i=this._isPartial&&!oa(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 Pw=t=>new ci(t),Fw=tt(ci),Mw=at(t=>t!=null&&(t.constructor===Object||t.constructor==null));class pu extends wt{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&or(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 mu=(t,e)=>new pu(t,e),Iw=tt(pu);class gu extends wt{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&or(this.shape,(s,r)=>{const i=s.check(e[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const $w=(...t)=>new gu(t);tt(gu);class wu extends wt{constructor(e){super(),this.shape=e.length===1?e[0]:new da(e)}check(e,n){const s=hs(e)&&Yo(e,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const bu=(...t)=>new wu(t),Uw=tt(wu),zw=at(t=>hs(t));class yu extends wt{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 Bw=(t,e=null)=>new yu(t,e);tt(yu);const Ww=Bw(wt);class qw extends wt{constructor(e){super(),this.len=e.length-1,this.args=$w(...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 Vw=tt(qw),Hw=at(t=>typeof t=="function");class Kw extends wt{constructor(e){super(),this.shape=e}check(e,n){const s=Yo(this.shape,r=>r.check(e,n));return!s&&n?.extend(null,"Intersectinon",typeof e),s}}tt(Kw,t=>t.shape.length>0);class da extends wt{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,n){const s=Xo(this.shape,r=>r.check(e,n));return n?.extend(null,"Union",typeof e),s}}const Cs=(...t)=>t.findIndex(e=>qr.check(e))>=0?Cs(...t.map(e=>Xs(e)).map(e=>qr.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new da(t),qr=tt(da),xu=()=>!0,Vr=at(xu),Gw=tt(ua,t=>t.shape===xu),fa=at(t=>typeof t=="bigint"),Jw=at(t=>t===fa),Su=at(t=>typeof t=="symbol");at(t=>t===Su);const os=at(t=>typeof t=="number"),vu=at(t=>t===os),gs=at(t=>typeof t=="string"),ku=at(t=>t===gs),ui=at(t=>typeof t=="boolean"),Yw=at(t=>t===ui),Cu=li(void 0);tt(ai,t=>t.shape.length===1&&t.shape[0]===void 0);li(void 0);const di=li(null),Xw=tt(ai,t=>t.shape.length===1&&t.shape[0]===null);tt(Uint8Array);tt(ca,t=>t.shape===Uint8Array);const Zw=Cs(os,gs,di,Cu,fa,ui,Su);(()=>{const t=bu(Vr),e=mu(gs,Vr),n=Cs(os,gs,di,ui,t,e);return t.shape=n,e.shape.values=n,n})();const Xs=t=>{if(Ww.check(t))return t;if(Mw.check(t)){const e={};for(const n in t)e[n]=Xs(t[n]);return Pw(e)}else{if(zw.check(t))return Cs(...t.map(Xs));if(Zw.check(t))return li(t);if(Hw.check(t))return tt(t)}jt()},Yl=fw?()=>{}:(t,e)=>{const n=new Rw;if(!e.check(t,n))throw Ft(`Expected value to be of type ${e.constructor.name}.
|
|
7
|
+
${n.toString()}`)};class Qw{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:Xs(e),h:n}),this}else(e){return this.if(Vr,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 Ft("Unhandled pattern")}}}const eb=t=>new Qw(t),Eu=eb(Vr).if(vu,(t,e)=>eo(e,zl,zr)).if(ku,(t,e)=>Dw(e)).if(Yw,(t,e)=>Jl(e)).if(Jw,(t,e)=>BigInt(eo(e,zl,zr))).if(qr,(t,e)=>Qn(e,to(e,t.shape))).if(Fw,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(Nw.check(r)){if(Jl(e))continue;r=r.shape}n[s]=Eu(r,e)}return n}).if(Uw,(t,e)=>{const n=[],s=uu(e,0,42);for(let r=0;r<s;r++)n.push(Qn(e,t.shape));return n}).if(du,(t,e)=>to(e,t.shape)).if(Xw,(t,e)=>null).if(Vw,(t,e)=>{const n=Qn(e,t.res);return()=>n}).if(Gw,(t,e)=>Qn(e,to(e,[os,gs,di,Cu,fa,ui,bu(os),mu(Cs("a","b","c"),os)]))).if(Iw,(t,e)=>{const n={},s=eo(e,0,3);for(let r=0;r<s;r++){const i=Qn(e,t.shape.keys),a=Qn(e,t.shape.values);n[i]=a}return n}).done(),Qn=(t,e)=>Eu(Xs(e),t),qt=typeof document<"u"?document:{},tb=t=>qt.createElement(t),nb=()=>qt.createDocumentFragment();at(t=>t.nodeType===db);const sb=t=>qt.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const rb=(t,e)=>(Ew(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),ib=t=>{const e=nb();for(let n=0;n<t.length;n++)ju(e,t[n]);return e},ob=(t,e)=>(ju(t,ib(e)),t),uv=(t,e=[],n=[])=>ob(rb(tb(t),e),n);at(t=>t.nodeType===lb);const dv=sb;at(t=>t.nodeType===cb);const ab=t=>bg(t,(e,n)=>`${n}:${e};`).join(""),ju=(t,e)=>t.appendChild(e),lb=qt.ELEMENT_NODE,cb=qt.TEXT_NODE;qt.CDATA_SECTION_NODE;qt.COMMENT_NODE;const ub=qt.DOCUMENT_NODE;qt.DOCUMENT_TYPE_NODE;const db=qt.DOCUMENT_FRAGMENT_NODE;at(t=>t.nodeType===ub);const sn=Symbol,Du=sn(),Tu=sn(),fb=sn(),hb=sn(),pb=sn(),Ru=sn(),mb=sn(),ha=sn(),gb=sn(),wb=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},bb={[Du]:Yt("font-weight","bold"),[Tu]:Yt("font-weight","normal"),[fb]:Yt("color","blue"),[pb]:Yt("color","green"),[hb]:Yt("color","grey"),[Ru]:Yt("color","red"),[mb]:Yt("color","purple"),[ha]:Yt("color","orange"),[gb]:Yt("color","black")},yb=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=St();let r=[],i=0;for(;i<t.length;i++){const a=t[i],l=bb[a];if(l!==void 0)s.set(l.left,l.right);else{if(a===void 0)break;if(a.constructor===String||a.constructor===Number){const c=ab(s);i>0||c.length>0?(e.push("%c"+a),n.push(c)):e.push(a)}else break}}for(i>0&&(r=n,r.unshift(e.join("")));i<t.length;i++){const a=t[i];a instanceof Symbol||r.push(a)}return r},_u=pw?yb:wb,xb=(...t)=>{console.log(..._u(t)),Au.forEach(e=>e.print(t))},Lu=(...t)=>{console.warn(..._u(t)),t.unshift(ha),Au.forEach(e=>e.print(t))},Au=gn(),Nu=t=>({[Symbol.iterator](){return this},next:t}),Sb=(t,e)=>Nu(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),no=(t,e)=>Nu(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class fi{constructor(e,n){this.clock=e,this.len=n}}class Es{constructor(){this.clients=new Map}}const ws=(t,e,n)=>e.clients.forEach((s,r)=>{const i=t.doc.store.clients.get(r);if(i!=null){const a=i[i.length-1],l=a.id.clock+a.length;for(let c=0,d=s[c];c<s.length&&d.clock<l;d=s[++c])Gu(t,i,d.clock,d.len,n)}}),vb=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=Pt((n+s)/2),i=t[r],a=i.clock;if(a<=e){if(e<a+i.len)return r;n=r+1}else s=r-1}return null},ar=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&vb(n,e.clock)!==null},pa=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 fi(r.clock,$n(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},To=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 a=n+1;a<t.length;a++)xg(i,t[a].clients.get(r)||[]);e.clients.set(r,i)}});return pa(e),e},Zs=(t,e,n,s)=>{Wt(t.clients,e,()=>[]).push(new fi(n,s))},kb=()=>new Es,Cb=t=>{const e=kb();return t.clients.forEach((n,s)=>{const r=[];for(let i=0;i<n.length;i++){const a=n[i];if(a.deleted){const l=a.id.clock;let c=a.length;if(i+1<n.length)for(let d=n[i+1];i+1<n.length&&d.deleted;d=n[++i+1])c+=d.length;r.push(new fi(l,c))}}r.length>0&&e.clients.set(s,r)}),e},js=(t,e)=>{ne(t.restEncoder,e.clients.size),tn(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),ne(t.restEncoder,n);const r=s.length;ne(t.restEncoder,r);for(let i=0;i<r;i++){const a=s[i];t.writeDsClock(a.clock),t.writeDsLen(a.len)}})},ma=t=>{const e=new Es,n=ge(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=ge(t.restDecoder),i=ge(t.restDecoder);if(i>0){const a=Wt(e.clients,r,()=>[]);for(let l=0;l<i;l++)a.push(new fi(t.readDsClock(),t.readDsLen()))}}return e},Xl=(t,e,n)=>{const s=new Es,r=ge(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const a=ge(t.restDecoder),l=ge(t.restDecoder),c=n.clients.get(a)||[],d=Ge(n,a);for(let f=0;f<l;f++){const h=t.readDsClock(),p=h+t.readDsLen();if(h<d){d<p&&Zs(s,a,d,p-d);let m=zt(c,h),g=c[m];for(!g.deleted&&g.id.clock<h&&(c.splice(m+1,0,Qr(e,g,h-g.id.clock)),m++);m<c.length&&(g=c[m++],g.id.clock<p);)g.deleted||(p<g.id.clock+g.length&&c.splice(m,0,Qr(e,g,p-g.id.clock)),g.delete(e))}else Zs(s,a,h,p-h)}}if(s.clients.size>0){const i=new Fn;return ne(i.restEncoder,0),js(i,s),i.toUint8Array()}return null},Ou=tu;class Un extends Zo{constructor({guid:e=Xg(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:l=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Ou(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new Hu,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=ms(d=>{this.on("load",()=>{this.isLoaded=!0,d(this)})});const c=()=>ms(d=>{const f=h=>{(h===void 0||h===!0)&&(this.off("sync",f),d())};this.on("sync",f)});this.on("sync",d=>{d===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=d===void 0||d===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&Be(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(tn(this.subdocs).map(e=>e.guid))}transact(e,n=null){return Be(this,e,n)}get(e,n=ot){const s=Wt(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==ot&&r!==n)if(r===ot){const i=new n;i._map=s._map,s._map.forEach(a=>{for(;a!==null;a=a.left)a.parent=i}),i._start=s._start;for(let a=i._start;a!==null;a=a.right)a.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,cs)}getText(e=""){return this.get(e,xs)}getMap(e=""){return this.get(e,ys)}getXmlElement(e=""){return this.get(e,Ss)}getXmlFragment(e=""){return this.get(e,Mn)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,tn(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new Un({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,Be(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 Pu{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return ge(this.restDecoder)}readDsLen(){return ge(this.restDecoder)}}class Fu extends Pu{readLeftID(){return Ce(ge(this.restDecoder),ge(this.restDecoder))}readRightID(){return Ce(ge(this.restDecoder),ge(this.restDecoder))}readClient(){return ge(this.restDecoder)}readInfo(){return ps(this.restDecoder)}readString(){return Ve(this.restDecoder)}readParentInfo(){return ge(this.restDecoder)===1}readTypeRef(){return ge(this.restDecoder)}readLen(){return ge(this.restDecoder)}readAny(){return Js(this.restDecoder)}readBuf(){return kw(pt(this.restDecoder))}readJSON(){return JSON.parse(Ve(this.restDecoder))}readKey(){return Ve(this.restDecoder)}}class Eb{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=ge(this.restDecoder),this.dsCurrVal}readDsLen(){const e=ge(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class bs extends Eb{constructor(e){super(e),this.keys=[],ge(e),this.keyClockDecoder=new Qi(pt(e)),this.clientDecoder=new Nr(pt(e)),this.leftClockDecoder=new Qi(pt(e)),this.rightClockDecoder=new Qi(pt(e)),this.infoDecoder=new Kl(pt(e),ps),this.stringDecoder=new Gg(pt(e)),this.parentInfoDecoder=new Kl(pt(e),ps),this.typeRefDecoder=new Nr(pt(e)),this.lenDecoder=new Nr(pt(e))}readLeftID(){return new as(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new as(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 Js(this.restDecoder)}readBuf(){return pt(this.restDecoder)}readJSON(){return Js(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 Mu{constructor(){this.restEncoder=Ke()}toUint8Array(){return Me(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ne(this.restEncoder,e)}writeDsLen(e){ne(this.restEncoder,e)}}class lr extends Mu{writeLeftID(e){ne(this.restEncoder,e.client),ne(this.restEncoder,e.clock)}writeRightID(e){ne(this.restEncoder,e.client),ne(this.restEncoder,e.clock)}writeClient(e){ne(this.restEncoder,e)}writeInfo(e){ko(this.restEncoder,e)}writeString(e){ct(this.restEncoder,e)}writeParentInfo(e){ne(this.restEncoder,e?1:0)}writeTypeRef(e){ne(this.restEncoder,e)}writeLen(e){ne(this.restEncoder,e)}writeAny(e){Gs(this.restEncoder,e)}writeBuf(e){He(this.restEncoder,e)}writeJSON(e){ct(this.restEncoder,JSON.stringify(e))}writeKey(e){ct(this.restEncoder,e)}}class Iu{constructor(){this.restEncoder=Ke(),this.dsCurrVal=0}toUint8Array(){return Me(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,ne(this.restEncoder,n)}writeDsLen(e){e===0&&jt(),ne(this.restEncoder,e-1),this.dsCurrVal+=e}}class Fn extends Iu{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Zi,this.clientEncoder=new Ar,this.leftClockEncoder=new Zi,this.rightClockEncoder=new Zi,this.infoEncoder=new ql(ko),this.stringEncoder=new Ug,this.parentInfoEncoder=new ql(ko),this.typeRefEncoder=new Ar,this.lenEncoder=new Ar}toUint8Array(){const e=Ke();return ne(e,0),He(e,this.keyClockEncoder.toUint8Array()),He(e,this.clientEncoder.toUint8Array()),He(e,this.leftClockEncoder.toUint8Array()),He(e,this.rightClockEncoder.toUint8Array()),He(e,Me(this.infoEncoder)),He(e,this.stringEncoder.toUint8Array()),He(e,Me(this.parentInfoEncoder)),He(e,this.typeRefEncoder.toUint8Array()),He(e,this.lenEncoder.toUint8Array()),ii(e,Me(this.restEncoder)),Me(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Gs(this.restEncoder,e)}writeBuf(e){He(this.restEncoder,e)}writeJSON(e){Gs(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 jb=(t,e,n,s)=>{s=$n(s,e[0].id.clock);const r=zt(e,s);ne(t.restEncoder,e.length-r),t.writeClient(n),ne(t.restEncoder,s);const i=e[r];i.write(t,s-i.id.clock);for(let a=r+1;a<e.length;a++)e[a].write(t,0)},ga=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{Ge(e,i)>r&&s.set(i,r)}),hi(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),ne(t.restEncoder,s.size),tn(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{jb(t,e.clients.get(r),r,i)})},Db=(t,e)=>{const n=St(),s=ge(t.restDecoder);for(let r=0;r<s;r++){const i=ge(t.restDecoder),a=new Array(i),l=t.readClient();let c=ge(t.restDecoder);n.set(l,{i:0,refs:a});for(let d=0;d<i;d++){const f=t.readInfo();switch(ri&f){case 0:{const h=t.readLen();a[d]=new Tt(Ce(l,c),h),c+=h;break}case 10:{const h=ge(t.restDecoder);a[d]=new Rt(Ce(l,c),h),c+=h;break}default:{const h=(f&(en|gt))===0,p=new We(Ce(l,c),null,(f>)===gt?t.readLeftID():null,null,(f&en)===en?t.readRightID():null,h?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,h&&(f&Hs)===Hs?t.readString():null,pd(t,f));a[d]=p,c+=p.length}}}}return n},Tb=(t,e,n)=>{const s=[];let r=tn(n.keys()).sort((m,g)=>m-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let m=n.get(r[r.length-1]);for(;m.refs.length===m.i;)if(r.pop(),r.length>0)m=n.get(r[r.length-1]);else return null;return m};let a=i();if(a===null)return null;const l=new Hu,c=new Map,d=(m,g)=>{const x=c.get(m);(x==null||x>g)&&c.set(m,g)};let f=a.refs[a.i++];const h=new Map,p=()=>{for(const m of s){const g=m.id.client,x=n.get(g);x?(x.i--,l.clients.set(g,x.refs.slice(x.i)),n.delete(g),x.i=0,x.refs=[]):l.clients.set(g,[m]),r=r.filter(j=>j!==g)}s.length=0};for(;;){if(f.constructor!==Rt){const g=Wt(h,f.id.client,()=>Ge(e,f.id.client))-f.id.clock;if(g<0)s.push(f),d(f.id.client,f.id.clock-1),p();else{const x=f.getMissing(t,e);if(x!==null){s.push(f);const j=n.get(x)||{refs:[],i:0};if(j.refs.length===j.i)d(x,Ge(e,x)),p();else{f=j.refs[j.i++];continue}}else(g===0||g<f.length)&&(f.integrate(t,g),h.set(f.id.client,f.id.clock+f.length))}}if(s.length>0)f=s.pop();else if(a!==null&&a.i<a.refs.length)f=a.refs[a.i++];else{if(a=i(),a===null)break;f=a.refs[a.i++]}}if(l.clients.size>0){const m=new Fn;return ga(m,l,new Map),ne(m.restEncoder,0),{missing:c,update:m.toUint8Array()}}return null},Rb=(t,e)=>ga(t,e.doc.store,e.beforeState),_b=(t,e,n,s=new bs(t))=>Be(e,r=>{r.local=!1;let i=!1;const a=r.doc,l=a.store,c=Db(s,a),d=Tb(r,l,c),f=l.pendingStructs;if(f){for(const[p,m]of f.missing)if(m<Ge(l,p)){i=!0;break}if(d){for(const[p,m]of d.missing){const g=f.missing.get(p);(g==null||g>m)&&f.missing.set(p,m)}f.update=Kr([f.update,d.update])}}else l.pendingStructs=d;const h=Xl(s,r,l);if(l.pendingDs){const p=new bs(yn(l.pendingDs));ge(p.restDecoder);const m=Xl(p,r,l);h&&m?l.pendingDs=Kr([h,m]):l.pendingDs=h||m}else l.pendingDs=h;if(i){const p=l.pendingStructs.update;l.pendingStructs=null,$u(r.doc,p)}},n,!1),$u=(t,e,n,s=bs)=>{const r=yn(e);_b(r,t,n,new s(r))},Uu=(t,e,n)=>$u(t,e,n,Fu),Lb=(t,e,n=new Map)=>{ga(t,e.store,n),js(t,Cb(e.store))},Ab=(t,e=new Uint8Array([0]),n=new Fn)=>{const s=zu(e);Lb(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(Xb(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===lr)return Jb(r.map((i,a)=>a===0?i:Qb(i)));if(n.constructor===Fn)return Kr(r)}return r[0]},wa=(t,e)=>Ab(t,e,new lr),Nb=t=>{const e=new Map,n=ge(t.restDecoder);for(let s=0;s<n;s++){const r=ge(t.restDecoder),i=ge(t.restDecoder);e.set(r,i)}return e},zu=t=>Nb(new Pu(yn(t))),Bu=(t,e)=>(ne(t.restEncoder,e.size),tn(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{ne(t.restEncoder,n),ne(t.restEncoder,s)}),t),Ob=(t,e)=>Bu(t,hi(e.store)),Pb=(t,e=new Iu)=>(t instanceof Map?Bu(e,t):Ob(e,t),e.toUint8Array()),Fb=t=>Pb(t,new Mu);class Mb{constructor(){this.l=[]}}const Zl=()=>new Mb,Ql=(t,e)=>t.l.push(e),ec=(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.")},Wu=(t,e,n)=>aa(t.l,[e,n]);class as{constructor(e,n){this.client=e,this.clock=n}}const ss=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,Ce=(t,e)=>new as(t,e),qu=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw jt()},Hr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class Vu{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const fv=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},hv=t=>new Vu(t.type==null?null:Ce(t.type.client,t.type.clock),t.tname??null,t.item==null?null:Ce(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class Ib{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const $b=(t,e,n=0)=>new Ib(t,e,n),jr=(t,e,n)=>{let s=null,r=null;return t._item===null?r=qu(t):s=Ce(t._item.id.client,t._item.id.clock),new Vu(s,r,e,n)},pv=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return jr(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return jr(t,Ce(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return jr(t,s.lastId,n);s=s.right}return jr(t,null,n)},Ub=(t,e)=>{const n=ls(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},mv=(t,e,n=!0)=>{const s=e.store,r=t.item,i=t.type,a=t.tname,l=t.assoc;let c=null,d=0;if(r!==null){if(Ge(s,r.client)<=r.clock)return null;const f=n?Ao(s,r):Ub(s,r),h=f.item;if(!(h instanceof We))return null;if(c=h.parent,c._item===null||!c._item.deleted){d=h.deleted||!h.countable?0:f.diff+(l>=0?0:1);let p=h.left;for(;p!==null;)!p.deleted&&p.countable&&(d+=p.length),p=p.left}}else{if(a!==null)c=e.get(a);else if(i!==null){if(Ge(s,i.client)<=i.clock)return null;const{item:f}=n?Ao(s,i):{item:ls(s,i)};if(f instanceof We&&f.content instanceof Vt)c=f.content.type;else return null}else throw jt();l>=0?d=c._length:d=0}return $b(c,d,t.assoc)},gv=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&ss(t.item,e.item)&&ss(t.type,e.type)&&t.assoc===e.assoc,es=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!ar(e.ds,t.id),Ro=(t,e)=>{const n=Wt(t.meta,Ro,gn),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<Ge(s,i)&&xt(t,Ce(i,r))}),ws(t,e.ds,r=>{}),n.add(e))};class Hu{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const hi=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},Ge=(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},Ku=(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 jt()}n.push(e)},zt=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let a=Pt(e/(i+r.length-1)*s);for(;n<=s;){if(r=t[a],i=r.id.clock,i<=e){if(e<i+r.length)return a;n=a+1}else s=a-1;a=Pt((n+s)/2)}throw jt()},zb=(t,e)=>{const n=t.clients.get(e.client);return n[zt(n,e.clock)]},ls=zb,_o=(t,e,n)=>{const s=zt(e,n),r=e[s];return r.id.clock<n&&r instanceof We?(e.splice(s+1,0,Qr(t,r,n-r.id.clock)),s+1):s},xt=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[_o(t,n,e.clock)]},tc=(t,e,n)=>{const s=e.clients.get(n.client),r=zt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==Tt&&s.splice(r+1,0,Qr(t,i,n.clock-i.id.clock+1)),i},Bb=(t,e,n)=>{const s=t.clients.get(e.id.client);s[zt(s,e.id.clock)]=n},Gu=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let a=_o(t,e,n),l;do l=e[a++],i<l.id.clock+l.length&&_o(t,e,i),r(l);while(a<e.length&&e[a].id.clock<i)};class Wb{constructor(e,n,s){this.doc=e,this.deleteSet=new Es,this.beforeState=hi(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 nc=(t,e)=>e.deleteSet.clients.size===0&&!yg(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(pa(e.deleteSet),Rb(t,e),js(t,e.deleteSet),!0),sc=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&Wt(t.changed,e,gn).add(n)},Or=(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 We&&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},qb=(t,e,n)=>{for(const[s,r]of t.clients.entries()){const i=e.clients.get(s);for(let a=r.length-1;a>=0;a--){const l=r[a],c=l.clock+l.len;for(let d=zt(i,l.clock),f=i[d];d<i.length&&f.id.clock<c;f=i[++d]){const h=i[d];if(l.clock+l.len<=h.id.clock)break;h instanceof We&&h.deleted&&!h.keep&&n(h)&&h.gc(e,!1)}}}},Vb=(t,e)=>{t.clients.forEach((n,s)=>{const r=e.clients.get(s);for(let i=n.length-1;i>=0;i--){const a=n[i],l=Qo(r.length-1,1+zt(r,a.clock+a.len-1));for(let c=l,d=r[c];c>0&&d.id.clock>=a.clock;d=r[c])c-=1+Or(r,c)}})},Ju=(t,e)=>{if(e<t.length){const n=t[e],s=n.doc,r=s.store,i=n.deleteSet,a=n._mergeStructs;try{pa(i),n.afterState=hi(n.doc.store),s.emit("beforeObserverCalls",[n,s]);const l=[];n.changed.forEach((c,d)=>l.push(()=>{(d._item===null||!d._item.deleted)&&d._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,d)=>{d._dEH.l.length>0&&(d._item===null||!d._item.deleted)&&(c=c.filter(f=>f.target._item===null||!f.target._item.deleted),c.forEach(f=>{f.currentTarget=d,f._path=null}),c.sort((f,h)=>f.path.length-h.path.length),l.push(()=>{Wu(d._dEH,c,n)}))}),l.push(()=>s.emit("afterTransaction",[n,s])),l.push(()=>{n._needFormattingCleanup&&hy(n)})}),aa(l,[])}finally{s.gc&&qb(i,r,s.gcFilter),Vb(i,r),n.afterState.forEach((f,h)=>{const p=n.beforeState.get(h)||0;if(p!==f){const m=r.clients.get(h),g=$n(zt(m,p),1);for(let x=m.length-1;x>=g;)x-=1+Or(m,x)}});for(let f=a.length-1;f>=0;f--){const{client:h,clock:p}=a[f].id,m=r.clients.get(h),g=zt(m,p);g+1<m.length&&Or(m,g+1)>1||g>0&&Or(m,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(xb(ha,Du,"[yjs] ",Tu,Ru,"Changed the client-id because another client seems to be using it."),s.clientID=Ou()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const f=new lr;nc(f,n)&&s.emit("update",[f.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const f=new Fn;nc(f,n)&&s.emit("updateV2",[f.toUint8Array(),n.origin,s,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:d}=n;(l.size>0||d.size>0||c.size>0)&&(l.forEach(f=>{f.clientID=s.clientID,f.collectionid==null&&(f.collectionid=s.collectionid),s.subdocs.add(f)}),d.forEach(f=>s.subdocs.delete(f)),s.emit("subdocs",[{loaded:c,added:l,removed:d},s,n]),d.forEach(f=>f.destroy())),t.length<=e+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,t])):Ju(t,e+1)}}},Be=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,a=null;t._transaction===null&&(i=!0,t._transaction=new Wb(t,n,s),r.push(t._transaction),r.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{a=e(t._transaction)}finally{if(i){const l=t._transaction===r[0];t._transaction=null,l&&Ju(r,0)}}return a};class Hb{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const rc=(t,e,n)=>{ws(t,n.deletions,s=>{s instanceof We&&e.scope.some(r=>r===t.doc||Hr(r,s))&&Ea(s,!1)})},ic=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;Be(r,l=>{for(;e.length>0&&t.currStackItem===null;){const c=r.store,d=e.pop(),f=new Set,h=[];let p=!1;ws(l,d.insertions,m=>{if(m instanceof We){if(m.redone!==null){let{item:g,diff:x}=Ao(c,m.id);x>0&&(g=xt(l,Ce(g.id.client,g.id.clock+x))),m=g}!m.deleted&&i.some(g=>g===l.doc||Hr(g,m))&&h.push(m)}}),ws(l,d.deletions,m=>{m instanceof We&&i.some(g=>g===l.doc||Hr(g,m))&&!ar(d.insertions,m.id)&&f.add(m)}),f.forEach(m=>{p=hd(l,m,f,d.insertions,t.ignoreRemoteMapChanges,t)!==null||p});for(let m=h.length-1;m>=0;m--){const g=h[m];t.deleteFilter(g)&&(g.delete(l),p=!0)}t.currStackItem=p?d:null}l.changed.forEach((c,d)=>{c.has(null)&&d._searchMarker&&(d._searchMarker.length=0)}),s=l},t);const a=t.currStackItem;if(a!=null){const l=s.changedParentTypes;t.emit("stack-item-popped",[{stackItem:a,type:n,changedParentTypes:l,origin:t},t]),t.currStackItem=null}return a};class Kb extends Zo{constructor(e,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:l=hs(e)?e[0].doc:e instanceof Un?e:e.doc}={}){super(),this.scope=[],this.doc=l,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=a,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(j=>c.changedParentTypes.has(j)||j===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const d=this.undoing,f=this.redoing,h=d?this.redoStack:this.undoStack;d?this.stopCapturing():f||this.clear(!1,!0);const p=new Es;c.afterState.forEach((j,C)=>{const z=c.beforeState.get(C)||0,k=j-z;k>0&&Zs(p,C,z,k)});const m=wn();let g=!1;if(this.lastChange>0&&m-this.lastChange<this.captureTimeout&&h.length>0&&!d&&!f){const j=h[h.length-1];j.deletions=To([j.deletions,c.deleteSet]),j.insertions=To([j.insertions,p])}else h.push(new Hb(c.deleteSet,p)),g=!0;!d&&!f&&(this.lastChange=m),ws(c,c.deleteSet,j=>{j instanceof We&&this.scope.some(C=>C===c.doc||Hr(C,j))&&Ea(j,!0)});const x=[{stackItem:h[h.length-1],origin:c.origin,type:d?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",x):this.emit("stack-item-updated",x)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=hs(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof ot?s.doc!==this.doc:s!==this.doc)&&Lu("[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=>rc(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>rc(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=ic(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=ic(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*Gb(t){const e=ge(t.restDecoder);for(let n=0;n<e;n++){const s=ge(t.restDecoder),r=t.readClient();let i=ge(t.restDecoder);for(let a=0;a<s;a++){const l=t.readInfo();if(l===10){const c=ge(t.restDecoder);yield new Rt(Ce(r,i),c),i+=c}else if((ri&l)!==0){const c=(l&(en|gt))===0,d=new We(Ce(r,i),null,(l>)===gt?t.readLeftID():null,null,(l&en)===en?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(l&Hs)===Hs?t.readString():null,pd(t,l));yield d,i+=d.length}else{const c=t.readLen();yield new Tt(Ce(r,i),c),i+=c}}}}class ba{constructor(e,n){this.gen=Gb(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===Rt);return this.curr}}class ya{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Jb=t=>Kr(t,Fu,lr),Yb=(t,e)=>{if(t.constructor===Tt){const{client:n,clock:s}=t.id;return new Tt(Ce(n,s+e),t.length-e)}else if(t.constructor===Rt){const{client:n,clock:s}=t.id;return new Rt(Ce(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new We(Ce(s,r+e),null,Ce(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},Kr=(t,e=bs,n=Fn)=>{if(t.length===1)return t[0];const s=t.map(f=>new e(yn(f)));let r=s.map(f=>new ba(f,!0)),i=null;const a=new n,l=new ya(a);for(;r=r.filter(p=>p.curr!==null),r.sort((p,m)=>{if(p.curr.id.client===m.curr.id.client){const g=p.curr.id.clock-m.curr.id.clock;return g===0?p.curr.constructor===m.curr.constructor?0:p.curr.constructor===Rt?1:-1:g}else return m.curr.id.client-p.curr.id.client}),r.length!==0;){const f=r[0],h=f.curr.id.client;if(i!==null){let p=f.curr,m=!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(),m=!0;if(p===null||p.id.client!==h||m&&p.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)hn(l,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===Rt)i.struct.length=p.id.clock+p.length-i.struct.id.clock;else{hn(l,i.struct,i.offset);const g=p.id.clock-i.struct.id.clock-i.struct.length;i={struct:new Rt(Ce(h,i.struct.id.clock+i.struct.length),g),offset:0}}else{const g=i.struct.id.clock+i.struct.length-p.id.clock;g>0&&(i.struct.constructor===Rt?i.struct.length-=g:p=Yb(p,g)),i.struct.mergeWith(p)||(hn(l,i.struct,i.offset),i={struct:p,offset:0},f.next())}}else i={struct:f.curr,offset:0},f.next();for(let p=f.curr;p!==null&&p.id.client===h&&p.id.clock===i.struct.id.clock+i.struct.length&&p.constructor!==Rt;p=f.next())hn(l,i.struct,i.offset),i={struct:p,offset:0}}i!==null&&(hn(l,i.struct,i.offset),i=null),xa(l);const c=s.map(f=>ma(f)),d=To(c);return js(a,d),a.toUint8Array()},Xb=(t,e,n=bs,s=Fn)=>{const r=zu(e),i=new s,a=new ya(i),l=new n(yn(t)),c=new ba(l,!1);for(;c.curr;){const f=c.curr,h=f.id.client,p=r.get(h)||0;if(c.curr.constructor===Rt){c.next();continue}if(f.id.clock+f.length>p)for(hn(a,f,$n(p-f.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)hn(a,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=p;)c.next()}xa(a);const d=ma(l);return js(i,d),i.toUint8Array()},Yu=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Me(t.encoder.restEncoder)}),t.encoder.restEncoder=Ke(),t.written=0)},hn=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&Yu(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),ne(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},xa=t=>{Yu(t);const e=t.encoder.restEncoder;ne(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];ne(e,s.written),ii(e,s.restEncoder)}},Zb=(t,e,n,s)=>{const r=new n(yn(t)),i=new ba(r,!1),a=new s,l=new ya(a);for(let d=i.curr;d!==null;d=i.next())hn(l,e(d),0);xa(l);const c=ma(r);return js(a,c),a.toUint8Array()},Qb=t=>Zb(t,cw,bs,lr),oc="You must not compute changes after the event-handler fired.";class pi{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=ey(this.currentTarget,this.target))}deletes(e){return ar(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ft(oc);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let a,l;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))a="delete",l=Xi(c.content.getContent());else return;else c!==null&&this.deletes(c)?(a="update",l=Xi(c.content.getContent())):(a="add",l=void 0)}else if(this.deletes(i))a="delete",l=Xi(i.content.getContent());else return;e.set(r,{action:a,oldValue:l})}}),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 Ft(oc);const n=this.target,s=gn(),r=gn(),i=[];if(e={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null;const c=()=>{l&&i.push(l)};for(let d=n._start;d!==null;d=d.right)d.deleted?this.deletes(d)&&!this.adds(d)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=d.length,r.add(d)):this.adds(d)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(d.content.getContent()),s.add(d)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=d.length);l!==null&&l.retain===void 0&&c()}this._changes=e}return e}}const ey=(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},mt=()=>{Lu("Invalid access: Add Yjs type to a document before reading data.")},Xu=80;let Sa=0;class ty{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=Sa++}}const ny=t=>{t.timestamp=Sa++},Zu=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=Sa++},sy=(t,e,n)=>{if(t.length>=Xu){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return Zu(s,e,n),s}else{const s=new ty(e,n);return t.push(s),s}},mi=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((i,a)=>Lr(e-i.index)<Lr(e-a.index)?i:a);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,ny(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&&Lr(n.index-r)<s.parent.length/Xu?(Zu(n,s,r),n):sy(t._searchMarker,s,r)},Qs=(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=$n(e,r.index+n))}},gi=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;Wt(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;Wu(s._eH,n,e)};class ot{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Zl(),this._dEH=Zl(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw Ot()}clone(){throw Ot()}_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){Ql(this._eH,e)}observeDeep(e){Ql(this._dEH,e)}unobserve(e){ec(this._eH,e)}unobserveDeep(e){ec(this._dEH,e)}toJSON(){}}const Qu=(t,e,n)=>{t.doc??mt(),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 a=i.content.getContent();if(a.length<=e)e-=a.length;else{for(let l=e;l<a.length&&s>0;l++)r.push(a[l]),s--;e=0}}i=i.right}return r},ed=t=>{t.doc??mt();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},er=(t,e)=>{let n=0,s=t._start;for(t.doc??mt();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}},td=(t,e)=>{const n=[];return er(t,(s,r)=>{n.push(e(s,r,t))}),n},ry=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}}}},nd=(t,e)=>{t.doc??mt();const n=mi(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}},Gr=(t,e,n,s)=>{let r=n;const i=t.doc,a=i.clientID,l=i.store,c=n===null?e._start:n.right;let d=[];const f=()=>{d.length>0&&(r=new We(Ce(a,Ge(l,a)),r,r&&r.lastId,c,c&&c.id,e,null,new In(d)),r.integrate(t,0),d=[])};s.forEach(h=>{if(h===null)d.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:d.push(h);break;default:switch(f(),h.constructor){case Uint8Array:case ArrayBuffer:r=new We(Ce(a,Ge(l,a)),r,r&&r.lastId,c,c&&c.id,e,null,new cr(new Uint8Array(h))),r.integrate(t,0);break;case Un:r=new We(Ce(a,Ge(l,a)),r,r&&r.lastId,c,c&&c.id,e,null,new ur(h)),r.integrate(t,0);break;default:if(h instanceof ot)r=new We(Ce(a,Ge(l,a)),r,r&&r.lastId,c,c&&c.id,e,null,new Vt(h)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),f()},sd=()=>Ft("Length exceeded!"),rd=(t,e,n,s)=>{if(n>e._length)throw sd();if(n===0)return e._searchMarker&&Qs(e._searchMarker,n,s.length),Gr(t,e,null,s);const r=n,i=mi(e,n);let a=e._start;for(i!==null&&(a=i.p,n-=i.index,n===0&&(a=a.prev,n+=a&&a.countable&&!a.deleted?a.length:0));a!==null;a=a.right)if(!a.deleted&&a.countable){if(n<=a.length){n<a.length&&xt(t,Ce(a.id.client,a.id.clock+n));break}n-=a.length}return e._searchMarker&&Qs(e._searchMarker,r,s.length),Gr(t,e,a,s)},iy=(t,e,n)=>{let r=(e._searchMarker||[]).reduce((i,a)=>a.index>i.index?a:i,{index:0,p:e._start}).p;if(r)for(;r.right;)r=r.right;return Gr(t,e,r,n)},id=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,a=mi(e,n);let l=e._start;for(a!==null&&(l=a.p,n-=a.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n<l.length&&xt(t,Ce(l.id.client,l.id.clock+n)),n-=l.length);for(;s>0&&l!==null;)l.deleted||(s<l.length&&xt(t,Ce(l.id.client,l.id.clock+s)),l.delete(t),s-=l.length),l=l.right;if(s>0)throw sd();e._searchMarker&&Qs(e._searchMarker,r,-i+s)},Jr=(t,e,n)=>{const s=e._map.get(n);s!==void 0&&s.delete(t)},va=(t,e,n,s)=>{const r=e._map.get(n)||null,i=t.doc,a=i.clientID;let l;if(s==null)l=new In([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new In([s]);break;case Uint8Array:l=new cr(s);break;case Un:l=new ur(s);break;default:if(s instanceof ot)l=new Vt(s);else throw new Error("Unexpected content type")}new We(Ce(a,Ge(i.store,a)),r,r&&r.lastId,null,null,e,n,l).integrate(t,0)},ka=(t,e)=>{t.doc??mt();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},od=t=>{const e={};return t.doc??mt(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},ad=(t,e)=>{t.doc??mt();const n=t._map.get(e);return n!==void 0&&!n.deleted},oy=(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&&es(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dr=t=>(t.doc??mt(),Sb(t._map.entries(),e=>!e[1].deleted));class ay extends pi{}class cs extends ot{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new cs;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new cs}clone(){const e=new cs;return e.insert(0,this.toArray().map(n=>n instanceof ot?n.clone():n)),e}get length(){return this.doc??mt(),this._length}_callObserver(e,n){super._callObserver(e,n),gi(this,e,new ay(this,e))}insert(e,n){this.doc!==null?Be(this.doc,s=>{rd(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?Be(this.doc,n=>{iy(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?Be(this.doc,s=>{id(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return nd(this,e)}toArray(){return ed(this)}slice(e=0,n=this.length){return Qu(this,e,n)}toJSON(){return this.map(e=>e instanceof ot?e.toJSON():e)}map(e){return td(this,e)}forEach(e){er(this,e)}[Symbol.iterator](){return ry(this)}_write(e){e.writeTypeRef(Ay)}}const ly=t=>new cs;class cy extends pi{constructor(e,n,s){super(e,n),this.keysChanged=s}}class ys extends ot{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 ys}clone(){const e=new ys;return this.forEach((n,s)=>{e.set(s,n instanceof ot?n.clone():n)}),e}_callObserver(e,n){gi(this,e,new cy(this,e,n))}toJSON(){this.doc??mt();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof ot?r.toJSON():r}}),e}get size(){return[...Dr(this)].length}keys(){return no(Dr(this),e=>e[0])}values(){return no(Dr(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return no(Dr(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??mt(),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?Be(this.doc,n=>{Jr(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?Be(this.doc,s=>{va(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return ka(this,e)}has(e){return ad(this,e)}clear(){this.doc!==null?Be(this.doc,e=>{this.forEach(function(n,s,r){Jr(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Ny)}}const uy=t=>new ys,pn=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&aw(t,e);class Lo{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&jt(),this.right.content.constructor===st?this.right.deleted||Ds(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ac=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===st?e.right.deleted||Ds(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&xt(t,Ce(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},Tr=(t,e,n,s)=>{const r=new Map,i=s?mi(e,n):null;if(i){const a=new Lo(i.p.left,i.p,i.index,r);return ac(t,a,n-i.index)}else{const a=new Lo(null,e._start,0,r);return ac(t,a,n)}},ld=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===st&&pn(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((a,l)=>{const c=n.left,d=n.right,f=new We(Ce(i,Ge(r.store,i)),c,c&&c.lastId,d,d&&d.id,e,null,new st(l,a));f.integrate(t,0),n.right=f,n.forward()})},Ds=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},cd=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===st&&pn(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},ud=(t,e,n,s)=>{const r=t.doc,i=r.clientID,a=new Map;for(const l in s){const c=s[l],d=n.currentAttributes.get(l)??null;if(!pn(d,c)){a.set(l,d);const{left:f,right:h}=n;n.right=new We(Ce(i,Ge(r.store,i)),f,f&&f.lastId,h,h&&h.id,e,null,new st(l,c)),n.right.integrate(t,0),n.forward()}}return a},so=(t,e,n,s,r)=>{n.currentAttributes.forEach((p,m)=>{r[m]===void 0&&(r[m]=null)});const i=t.doc,a=i.clientID;cd(n,r);const l=ud(t,e,n,r),c=s.constructor===String?new Bt(s):s instanceof ot?new Vt(s):new zn(s);let{left:d,right:f,index:h}=n;e._searchMarker&&Qs(e._searchMarker,n.index,c.getLength()),f=new We(Ce(a,Ge(i.store,a)),d,d&&d.lastId,f,f&&f.id,e,null,c),f.integrate(t,0),n.right=f,n.index=h,n.forward(),ld(t,e,n,l)},lc=(t,e,n,s,r)=>{const i=t.doc,a=i.clientID;cd(n,r);const l=ud(t,e,n,r);e:for(;n.right!==null&&(s>0||l.size>0&&(n.right.deleted||n.right.content.constructor===st));){if(!n.right.deleted)switch(n.right.content.constructor){case st:{const{key:c,value:d}=n.right.content,f=r[c];if(f!==void 0){if(pn(f,d))l.delete(c);else{if(s===0)break e;l.set(c,d)}n.right.delete(t)}else n.currentAttributes.set(c,d);break}default:s<n.right.length&&xt(t,Ce(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 We(Ce(a,Ge(i.store,a)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Bt(c)),n.right.integrate(t,0),n.forward()}ld(t,e,n,l)},dd=(t,e,n,s,r)=>{let i=e;const a=St();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===st){const d=i.content;a.set(d.key,d)}i=i.right}let l=0,c=!1;for(;e!==i;){if(n===e&&(c=!0),!e.deleted){const d=e.content;if(d.constructor===st){const{key:f,value:h}=d,p=s.get(f)??null;(a.get(f)!==d||p===h)&&(e.delete(t),l++,!c&&(r.get(f)??null)===h&&p!==h&&(p===null?r.delete(f):r.set(f,p))),!c&&!e.deleted&&Ds(r,d)}}e=e.right}return l},dy=(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===st){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},fy=t=>{let e=0;return Be(t.doc,n=>{let s=t._start,r=t._start,i=St();const a=vo(i);for(;r;)r.deleted===!1&&(r.content.constructor===st?Ds(a,r.content):(e+=dd(n,s,r,i,a),i=vo(a),s=r)),r=r.right}),e},hy=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&&Gu(t,n.store.clients.get(s),i,r,a=>{!a.deleted&&a.content.constructor===st&&a.constructor!==Tt&&e.add(a.parent)})}Be(n,s=>{ws(t,t.deleteSet,r=>{if(r instanceof Tt||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===st?e.add(i):dy(s,r)});for(const r of e)fy(r)})},cc=(t,e,n)=>{const s=n,r=vo(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Vt:case zn:case Bt:n<e.right.length&&xt(t,Ce(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&dd(t,i,e.right,r,e.currentAttributes);const a=(e.left||e.right).parent;return a._searchMarker&&Qs(a._searchMarker,e.index,-s+n),e};class py extends pi{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=[];Be(e,s=>{const r=new Map,i=new Map;let a=this.target._start,l=null;const c={};let d="",f=0,h=0;const p=()=>{if(l!==null){let m=null;switch(l){case"delete":h>0&&(m={delete:h}),h=0;break;case"insert":(typeof d=="object"||d.length>0)&&(m={insert:d},r.size>0&&(m.attributes={},r.forEach((g,x)=>{g!==null&&(m.attributes[x]=g)}))),d="";break;case"retain":f>0&&(m={retain:f},ow(c)||(m.attributes=nw({},c))),f=0;break}m&&n.push(m),l=null}};for(;a!==null;){switch(a.content.constructor){case Vt:case zn:this.adds(a)?this.deletes(a)||(p(),l="insert",d=a.content.getContent()[0],p()):this.deletes(a)?(l!=="delete"&&(p(),l="delete"),h+=1):a.deleted||(l!=="retain"&&(p(),l="retain"),f+=1);break;case Bt:this.adds(a)?this.deletes(a)||(l!=="insert"&&(p(),l="insert"),d+=a.content.str):this.deletes(a)?(l!=="delete"&&(p(),l="delete"),h+=a.length):a.deleted||(l!=="retain"&&(p(),l="retain"),f+=a.length);break;case st:{const{key:m,value:g}=a.content;if(this.adds(a)){if(!this.deletes(a)){const x=r.get(m)??null;pn(x,g)?g!==null&&a.delete(s):(l==="retain"&&p(),pn(g,i.get(m)??null)?delete c[m]:c[m]=g)}}else if(this.deletes(a)){i.set(m,g);const x=r.get(m)??null;pn(x,g)||(l==="retain"&&p(),c[m]=x)}else if(!a.deleted){i.set(m,g);const x=c[m];x!==void 0&&(pn(x,g)?x!==null&&a.delete(s):(l==="retain"&&p(),g===null?delete c[m]:c[m]=g))}a.deleted||(l==="insert"&&p(),Ds(r,a.content));break}}a=a.right}for(p();n.length>0;){const m=n[n.length-1];if(m.retain!==void 0&&m.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class xs extends ot{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??mt(),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 xs}clone(){const e=new xs;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new py(this,e,n);gi(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??mt();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Bt&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?Be(this.doc,s=>{const r=new Lo(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const a=e[i];if(a.insert!==void 0){const l=!n&&typeof a.insert=="string"&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
|
|
9
|
+
`?a.insert.slice(0,-1):a.insert;(typeof l!="string"||l.length>0)&&so(s,this,r,l,a.attributes||{})}else a.retain!==void 0?lc(s,this,r,a.retain,a.attributes||{}):a.delete!==void 0&&cc(s,r,a.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??mt();const r=[],i=new Map,a=this.doc;let l="",c=this._start;function d(){if(l.length>0){const h={};let p=!1;i.forEach((g,x)=>{p=!0,h[x]=g});const m={insert:l};p&&(m.attributes=h),r.push(m),l=""}}const f=()=>{for(;c!==null;){if(es(c,e)||n!==void 0&&es(c,n))switch(c.content.constructor){case Bt:{const h=i.get("ychange");e!==void 0&&!es(c,e)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(d(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!es(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(d(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(d(),i.delete("ychange")),l+=c.content.str;break}case Vt:case zn:{d();const h={insert:c.content.getContent()[0]};if(i.size>0){const p={};h.attributes=p,i.forEach((m,g)=>{p[g]=m})}r.push(h);break}case st:es(c,e)&&(d(),Ds(i,c.content));break}c=c.right}d()};return e||n?Be(a,h=>{e&&Ro(h,e),n&&Ro(h,n),f()},"cleanup"):f(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?Be(r,i=>{const a=Tr(i,this,e,!s);s||(s={},a.currentAttributes.forEach((l,c)=>{s[c]=l})),so(i,this,a,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?Be(r,i=>{const a=Tr(i,this,e,!s);so(i,this,a,n,s||{})}):this._pending.push(()=>this.insertEmbed(e,n,s||{}))}delete(e,n){if(n===0)return;const s=this.doc;s!==null?Be(s,r=>{cc(r,Tr(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?Be(r,i=>{const a=Tr(i,this,e,!1);a.right!==null&&lc(i,this,a,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?Be(this.doc,n=>{Jr(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?Be(this.doc,s=>{va(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return ka(this,e)}getAttributes(){return od(this)}_write(e){e.writeTypeRef(Oy)}}const my=t=>new xs;class ro{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??mt()}[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===Ss||n.constructor===Mn)&&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 Mn extends ot{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 Mn}clone(){const e=new Mn;return e.insert(0,this.toArray().map(n=>n instanceof ot?n.clone():n)),e}get length(){return this.doc??mt(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new ro(this,e)}querySelector(e){e=e.toUpperCase();const s=new ro(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),tn(new ro(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){gi(this,e,new by(this,n,e))}toString(){return td(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),er(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?Be(this.doc,s=>{rd(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)Be(this.doc,s=>{const r=e&&e instanceof ot?e._item:e;Gr(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 Ft("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?Be(this.doc,s=>{id(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return ed(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return nd(this,e)}slice(e=0,n=this.length){return Qu(this,e,n)}forEach(e){er(this,e)}_write(e){e.writeTypeRef(Fy)}}const gy=t=>new Mn;class Ss extends Mn{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 Ss(this.nodeName)}clone(){const e=new Ss(this.nodeName),n=this.getAttributes();return rw(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof ot?s.clone():s)),e}toString(){const e=this.getAttributes(),n=[],s=[];for(const l in e)s.push(l);s.sort();const r=s.length;for(let l=0;l<r;l++){const c=s[l];n.push(c+'="'+e[c]+'"')}const i=this.nodeName.toLocaleLowerCase(),a=n.length>0?" "+n.join(" "):"";return`<${i}${a}>${super.toString()}</${i}>`}removeAttribute(e){this.doc!==null?Be(this.doc,n=>{Jr(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?Be(this.doc,s=>{va(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return ka(this,e)}hasAttribute(e){return ad(this,e)}getAttributes(e){return e?oy(this,e):od(this)}toDOM(e=document,n={},s){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const a in i){const l=i[a];typeof l=="string"&&r.setAttribute(a,l)}return er(this,a=>{r.appendChild(a.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(Py),e.writeKey(this.nodeName)}}const wy=t=>new Ss(t.readKey());class by extends pi{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 Yr extends ys{constructor(e){super(),this.hookName=e}_copy(){return new Yr(this.hookName)}clone(){const e=new Yr(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(My),e.writeKey(this.hookName)}}const yy=t=>new Yr(t.readKey());class Xr extends xs{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 Xr}clone(){const e=new Xr;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 a in e.attributes[r])i.push({key:a,value:e.attributes[r][a]});i.sort((a,l)=>a.key<l.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 a=0;a<i.attrs.length;a++){const l=i.attrs[a];s+=` ${l.key}="${l.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(Iy)}}const xy=t=>new Xr;class Ca{constructor(e,n){this.id=e,this.length=n}get deleted(){throw Ot()}mergeWith(e){return!1}write(e,n,s){throw Ot()}integrate(e,n){throw Ot()}}const Sy=0;class Tt extends Ca{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),Ku(e.doc.store,this)}write(e,n){e.writeInfo(Sy),e.writeLen(this.length-n)}getMissing(e,n){return null}}class cr{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new cr(this.content)}splice(e){throw Ot()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const vy=t=>new cr(t.readBuf());class tr{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new tr(this.len)}splice(e){const n=new tr(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){Zs(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const ky=t=>new tr(t.readLen()),fd=(t,e)=>new Un({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class ur{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 ur(fd(this.doc.guid,this.opts))}splice(e){throw Ot()}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 Cy=t=>new ur(fd(t.readString(),t.readAny()));class zn{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new zn(this.embed)}splice(e){throw Ot()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const Ey=t=>new zn(t.readJSON());class st{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new st(this.key,this.value)}splice(e){throw Ot()}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 jy=t=>new st(t.readKey(),t.readJSON());class Zr{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Zr(this.arr)}splice(e){const n=new Zr(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 Dy=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 Zr(n)},Ty=Wr("node_env")==="development";class In{constructor(e){this.arr=e,Ty&&iu(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new In(this.arr)}splice(e){const n=new In(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 Ry=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new In(n)};class Bt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Bt(this.str)}splice(e){const n=new Bt(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 _y=t=>new Bt(t.readString()),Ly=[ly,uy,my,wy,gy,yy,xy],Ay=0,Ny=1,Oy=2,Py=3,Fy=4,My=5,Iy=6;class Vt{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Vt(this.type._copy())}splice(e){throw Ot()}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 $y=t=>new Vt(Ly[t.readTypeRef()](t)),Ao=(t,e)=>{let n=e,s=0,r;do s>0&&(n=Ce(n.client,n.clock+s)),r=ls(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof We);return{item:r,diff:s}},Ea=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},Qr=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new We(Ce(s,r+n),e,Ce(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=Ce(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},uc=(t,e)=>Xo(t,n=>ar(n.deletions,e)),hd=(t,e,n,s,r,i)=>{const a=t.doc,l=a.store,c=a.clientID,d=e.redone;if(d!==null)return xt(t,d);let f=e.parent._item,h=null,p;if(f!==null&&f.deleted===!0){if(f.redone===null&&(!n.has(f)||hd(t,f,n,s,r,i)===null))return null;for(;f.redone!==null;)f=xt(t,f.redone)}const m=f===null?e.parent:f.content.type;if(e.parentSub===null){for(h=e.left,p=e;h!==null;){let C=h;for(;C!==null&&C.parent._item!==f;)C=C.redone===null?null:xt(t,C.redone);if(C!==null&&C.parent._item===f){h=C;break}h=h.left}for(;p!==null;){let C=p;for(;C!==null&&C.parent._item!==f;)C=C.redone===null?null:xt(t,C.redone);if(C!==null&&C.parent._item===f){p=C;break}p=p.right}}else{if(p=null,e.right&&!r){for(h=e;h!==null&&h.right!==null&&(h.right.redone||ar(s,h.right.id)||uc(i.undoStack,h.right.id)||uc(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=xt(t,h.redone);if(h&&h.right!==null)return null}else h=m._map.get(e.parentSub)||null;h!==null&&h.parent._item!==f&&(h=m._map.get(e.parentSub)||null)}const g=Ge(l,c),x=Ce(c,g),j=new We(x,h,h&&h.lastId,p,p&&p.id,m,e.parentSub,e.content.copy());return e.redone=x,Ea(j,!0),j.integrate(t,0),j};class We extends Ca{constructor(e,n,s,r,i,a,l,c){super(e,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Il:0}set marker(e){(this.info&Ji)>0!==e&&(this.info^=Ji)}get marker(){return(this.info&Ji)>0}get keep(){return(this.info&Ml)>0}set keep(e){this.keep!==e&&(this.info^=Ml)}get countable(){return(this.info&Il)>0}get deleted(){return(this.info&Gi)>0}set deleted(e){this.deleted!==e&&(this.info^=Gi)}markDeleted(){this.info|=Gi}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Ge(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Ge(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===as&&this.id.client!==this.parent.client&&this.parent.clock>=Ge(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=tc(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=xt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Tt||this.right&&this.right.constructor===Tt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===We?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===We&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===as){const s=ls(n,this.parent);s.constructor===Tt?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=tc(e,e.doc.store,Ce(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,a=new Set;for(;r!==null&&r!==this.right;){if(a.add(r),i.add(r),ss(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(ss(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&a.has(ls(e.doc.store,r.origin)))i.has(ls(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),Ku(e.doc.store,this),this.content.integrate(e,this),sc(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Tt(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:Ce(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&ss(e.origin,this.lastId)&&this.right===e&&ss(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const n=this.parent._searchMarker;return n&&n.forEach(s=>{s.p===e&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Zs(e.deleteSet,this.id.client,this.id.clock,this.length),sc(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw jt();this.content.gc(e),n?Bb(e,this,new Tt(this.id,this.length)):this.content=new tr(this.length)}write(e,n){const s=n>0?Ce(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&ri|(s===null?0:gt)|(r===null?0:en)|(i===null?0:Hs);if(e.writeInfo(a),s!==null&&e.writeLeftID(s),r!==null&&e.writeRightID(r),s===null&&r===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const d=qu(l);e.writeParentInfo(!0),e.writeString(d)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else l.constructor===String?(e.writeParentInfo(!0),e.writeString(l)):l.constructor===as?(e.writeParentInfo(!1),e.writeLeftID(l)):jt();i!==null&&e.writeString(i)}this.content.write(e,n)}}const pd=(t,e)=>Uy[e&ri](t),Uy=[()=>{jt()},ky,Dy,vy,_y,Ey,jy,$y,Ry,Cy,()=>{jt()}],zy=10;class Rt extends Ca{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){jt()}write(e,n){e.writeInfo(zy),ne(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const md=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},gd="__ $YJS$ __";md[gd]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");md[gd]=!0;function By(t){for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t}function Wy(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function No(t=globalThis.crypto){if(typeof t?.randomUUID=="function")return t.randomUUID();const e=new Uint8Array(16),n=typeof t?.getRandomValues=="function"?t.getRandomValues(e):By(e);return Wy(n)}const wd=new Map;class qy{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:vw(n.newValue||"")}),Qg(this._onChange)}postMessage(e){su.setItem(this.room,Sw(gw(e)))}close(){ew(this._onChange)}}const Vy=typeof BroadcastChannel>"u"?qy:BroadcastChannel,ja=t=>Wt(wd,t,()=>{const e=gn(),n=new Vy(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),Hy=(t,e)=>(ja(t).subs.add(e),e),Ky=(t,e)=>{const n=ja(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),wd.delete(t)),s},ts=(t,e,n=null)=>{const s=ja(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},bd=0,Da=1,yd=2,ei=(t,e)=>{ne(t,bd);const n=Fb(e);He(t,n)},xd=(t,e,n)=>{ne(t,Da),He(t,wa(e,n))},Gy=(t,e,n)=>xd(e,n,pt(t)),Sd=(t,e,n,s)=>{try{Uu(e,pt(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Jy=(t,e)=>{ne(t,yd),He(t,e)},Yy=Sd,Xy=(t,e,n,s,r)=>{const i=ge(t);switch(i){case bd:Gy(t,e,n);break;case Da:Sd(t,n,s,r);break;case yd:Yy(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},Zy=0,Qy=(t,e,n)=>{ge(t)===Zy&&n(e,Ve(t))},io=3e4;class ex extends Yc{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=wn();this.getLocalState()!==null&&io/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&io<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Ta(this,s,"timeout")},Pt(io/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:wn()});const a=[],l=[],c=[],d=[];e===null?d.push(n):i==null?e!=null&&a.push(n):(l.push(n),is(i,e)||c.push(n)),(a.length>0||c.length>0||d.length>0)&&this.emit("change",[{added:a,updated:c,removed:d},"local"]),this.emit("update",[{added:a,updated:l,removed:d},"local"])}setLocalStateField(e,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:n})}getStates(){return this.states}}const Ta=(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 a=t.meta.get(i);t.meta.set(i,{clock:a.clock+1,lastUpdated:wn()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},us=(t,e,n=t.states)=>{const s=e.length,r=Ke();ne(r,s);for(let i=0;i<s;i++){const a=e[i],l=n.get(a)||null,c=t.meta.get(a).clock;ne(r,a),ne(r,c),ct(r,JSON.stringify(l))}return Me(r)},tx=(t,e,n)=>{const s=yn(e),r=wn(),i=[],a=[],l=[],c=[],d=ge(s);for(let f=0;f<d;f++){const h=ge(s);let p=ge(s);const m=JSON.parse(Ve(s)),g=t.meta.get(h),x=t.states.get(h),j=g===void 0?0:g.clock;(j<p||j===p&&m===null&&t.states.has(h))&&(m===null?h===t.clientID&&t.getLocalState()!=null?p++:t.states.delete(h):t.states.set(h,m),t.meta.set(h,{clock:p,lastUpdated:r}),g===void 0&&m!==null?i.push(h):g!==void 0&&m===null?c.push(h):m!==null&&(is(m,x)||l.push(h),a.push(h)))}(i.length>0||l.length>0||c.length>0)&&t.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||a.length>0||c.length>0)&&t.emit("update",[{added:i,updated:a,removed:c},n])},nx=t=>iw(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),_n=0,vd=3,ds=1,sx=2,dr=[];dr[_n]=(t,e,n,s,r)=>{ne(t,_n);const i=Xy(e,t,n.doc,n);s&&i===Da&&!n.synced&&(n.synced=!0)};dr[vd]=(t,e,n,s,r)=>{ne(t,ds),He(t,us(n.awareness,Array.from(n.awareness.getStates().keys())))};dr[ds]=(t,e,n,s,r)=>{tx(n.awareness,pt(e),n)};dr[sx]=(t,e,n,s,r)=>{Qy(e,n.doc,(i,a)=>rx(n,a))};const dc=3e4,rx=(t,e)=>console.warn(`Permission denied to access ${t.url}.
|
|
10
|
+
${e}`),kd=(t,e,n)=>{const s=yn(e),r=Ke(),i=ge(s),a=t.messageHandlers[i];return a?a(r,s,t,n,i):console.error("Unable to compute message"),r},Oo=(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,Ta(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(Cd,Qo(vg(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},Cd=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=wn();const s=kd(t,new Uint8Array(n.data),!0);ea(s)>1&&e.send(Me(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{Oo(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=wn(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Ke();if(ne(n,_n),ei(n,t.doc),e.send(Me(n)),t.awareness.getLocalState()!==null){const s=Ke();ne(s,ds),He(s,us(t.awareness,[t.doc.clientID])),e.send(Me(s))}},t.emit("status",[{status:"connecting"}])}},oo=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&ts(t.bcChannel,e,t)};class ix extends Zo{constructor(e,n,s,{connect:r=!0,awareness:i=new ex(s),params:a={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:d=-1,maxBackoffTime:f=2500,disableBc:h=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+n,this.maxBackoffTime=f,this.params=a,this.protocols=l,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=dr.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,d>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const p=Ke();ne(p,_n),ei(p,s),this.ws.send(Me(p))}},d)),this._bcSubscriber=(p,m)=>{if(m!==this){const g=kd(this,new Uint8Array(p),!1);ea(g)>1&&ts(this.bcChannel,Me(g),this)}},this._updateHandler=(p,m)=>{if(m!==this){const g=Ke();ne(g,_n),Jy(g,p),oo(this,Me(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:p,updated:m,removed:g},x)=>{const j=p.concat(m).concat(g),C=Ke();ne(C,ds),He(C,us(i,j)),oo(this,Me(C))},this._exitHandler=()=>{Ta(this.awareness,[s.clientID],"app closed")},bn&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&dc<wn()-this.wsLastMessageReceived&&Oo(this,this.ws,null)},dc/10),r&&this.connect()}get url(){const e=nx(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(),bn&&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||(Hy(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Ke();ne(e,_n),ei(e,this.doc),ts(this.bcChannel,Me(e),this);const n=Ke();ne(n,_n),xd(n,this.doc),ts(this.bcChannel,Me(n),this);const s=Ke();ne(s,vd),ts(this.bcChannel,Me(s),this);const r=Ke();ne(r,ds),He(r,us(this.awareness,[this.doc.clientID])),ts(this.bcChannel,Me(r),this)}disconnectBc(){const e=Ke();ne(e,ds),He(e,us(this.awareness,[this.doc.clientID],new Map)),oo(this,Me(e)),this.bcconnected&&(Ky(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Oo(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Cd(this),this.connectBc())}}const Bn=t=>ms((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),ox=(t,e)=>ms((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(Ft(i.target.error)),r.onsuccess=i=>{const a=i.target.result;a.onversionchange=()=>{a.close()},n(a)}}),ax=t=>Bn(indexedDB.deleteDatabase(t)),lx=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),$s=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>gx(s,r))},Ed=(t,e)=>Bn(t.count(e)),cx=(t,e)=>Bn(t.get(e)),jd=(t,e)=>Bn(t.delete(e)),ux=(t,e,n)=>Bn(t.put(e,n)),Po=(t,e)=>Bn(t.add(e)),dx=(t,e,n)=>Bn(t.getAll(e,n)),fx=(t,e,n)=>{let s=null;return mx(t,e,r=>(s=r,!1),n).then(()=>s)},hx=(t,e=null)=>fx(t,e,"prev"),px=(t,e)=>ms((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()}}),mx=(t,e,n,s="next")=>px(t.openKeyCursor(e,s),r=>n(r.key)),gx=(t,e)=>t.objectStore(e),wx=(t,e)=>IDBKeyRange.upperBound(t,e),bx=(t,e)=>IDBKeyRange.lowerBound(t,e),ao="custom",Dd="updates",Td=500,Rd=(t,e=()=>{},n=()=>{})=>{const[s]=$s(t.db,[Dd]);return dx(s,bx(t._dbref,!1)).then(r=>{t._destroyed||(e(s),Be(t.doc,()=>{r.forEach(i=>Uu(t.doc,i))},t,!1),n(s))}).then(()=>hx(s).then(r=>{t._dbref=r+1})).then(()=>Ed(s).then(r=>{t._dbsize=r})).then(()=>s)},yx=(t,e=!0)=>Rd(t).then(n=>{(e||t._dbsize>=Td)&&Po(n,wa(t.doc)).then(()=>jd(n,wx(t._dbref,!0))).then(()=>Ed(n).then(s=>{t._dbsize=s}))});class xx extends Yc{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=ox(e,s=>lx(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=ms(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Rd(this,a=>Po(a,wa(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]=$s(this.db,[Dd]);Po(i,s),++this._dbsize>=Td&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{yx(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(()=>{ax(this.name)})}get(e){return this._db.then(n=>{const[s]=$s(n,[ao],"readonly");return cx(s,e)})}set(e,n){return this._db.then(s=>{const[r]=$s(s,[ao]);return ux(r,n,e)})}del(e){return this._db.then(n=>{const[s]=$s(n,[ao]);return jd(s,e)})}}const Sx={Sync:0,Awareness:1,Flush:4,Protocol:5,Maintenance:6,Permission:7,CompileStates:8,FormatLease:9},lo=3,vx=["queued","running","succeeded","failed","cleaned"],kx=["cache","artifacts"];function Cx(t){return typeof t=="string"&&vx.includes(t)}function Ex(t){return typeof t=="string"&&kx.includes(t)}const fc=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],{Sync:jx,Awareness:Dx,Flush:hc,Protocol:pc,Maintenance:Tx,Permission:Rx,CompileStates:_x,FormatLease:co}=Sx,Lx=6e4,Ax=720*60*60*1e3,Nx=15e3,Ox=5*6e4;function Px(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!Cx(e.status)||e.status==="cleaned"&&!Ex(e.cleanMode)||e.stale!==void 0&&typeof e.stale!="boolean"||typeof e.updatedAt!="string"||!n||typeof n.id!="string"||typeof n.username!="string"||typeof n.name!="string"?null:e}function mc(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=Px(s);r&&r.mainFile===n&&(e[n]=r)}return e}function Fx(t,e,n){return t<=n&&e<=n}function gc(t,e,n){const s=r=>r>0&&n-r<=Ox;return{recoverable:t.some(r=>r.tabId===e||!s(r.activeAt)),otherActive:t.some(r=>r.tabId!==e&&s(r.activeAt))}}class Mx{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.draftTabId=zx(Tn(`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 xx(Tn(`texlite:${n.id}:${e}`),this.doc),this.localDraftTransactionObserver=a=>{if(a.local){for(const[l,c]of this.doc.share)if(l.startsWith("source:")&&(a.changed.has(c)||a.changedParentTypes.has(c))){this.markWritableDraft();return}}},this.doc.on("afterTransaction",this.localDraftTransactionObserver),this.persistence.on("synced",()=>{this.localDraftReady=!0;for(const a of this.draftListeners)a()}),this.provider=new ix(`${s}//${window.location.host}${vs("/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=(a,l)=>{l.origin===this.provider&&a.keysChanged.has("compileStates")&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners())},i.observe(this.metaObserver),this.provider.messageHandlers[hc]=(a,l)=>{const c=Ve(l),d=this.flushRequests.get(c);if(!d)return;const f=ge(l)===1,h=ge(l),p=Ve(l),m=ge(l),g=[];for(let x=0;x<m;x++)g.push(Ve(l));if(window.clearTimeout(d.timer),this.flushRequests.delete(c),f)this.clearOwnWritableDraftMarker(d.draftGeneration),d.resolve({revision:h,persistedAt:p,ok:!0,failedPaths:[]});else{const x=Object.assign(new Error(g.length?`保存失败:${g.join(", ")}`:"源码保存到服务器磁盘失败"),{failedPaths:g});d.reject(x)}},this.provider.messageHandlers[pc]=(a,l)=>{const c=Ve(l),d=this.epochStorageKey(),f=wc(d),h=/^([0-9]+):/.exec(c)?.[1]??null,p=f?/^([0-9]+):/.exec(f)?.[1]??null:null,m=!this.epoch&&h===String(lo)&&p!==null&&p!==h;if((this.epoch&&this.epoch!==c||f&&f!==c)&&!m){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed"));const z=c.endsWith(":reload")||h!==null&&h!==String(lo),k=()=>{uo(d,c.replace(/:reload$/,"")),window.location.reload()};if(z)for(const y of this.protocolUpgradeListeners)y();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),k()});return}this.epoch=c,uo(d,c);const g=this.provider.ws;if(!g||g.readyState!==WebSocket.OPEN)return;const x=Ke();ne(x,pc),ct(x,c),ne(x,lo),g.send(Me(x));const j=Ke();ne(j,jx),ei(j,this.doc),g.send(Me(j));const C=Ke();ne(C,Dx),He(C,us(this.awareness,[this.doc.clientID])),g.send(Me(C))},this.provider.messageHandlers[Rx]=(a,l)=>{const c=Ve(l),d=Ve(l);if(c!==this.user.id)return;if(d==="revoked"){this.rejectFlushes(new Error("Project access revoked")),this.provider.disconnect();for(const h of this.permissionListeners)h("revoked",this.permission);return}if(d!=="read"&&d!=="edit"&&d!=="owner")return;const f=this.permission;if(this.setPermission(d),f!==d){d==="read"&&this.rejectFlushes(new Error("Project permission changed to read-only"));for(const h of this.permissionListeners)h(d,f)}},this.provider.messageHandlers[Tx]=(a,l)=>{Ve(l)},this.provider.messageHandlers[_x]=(a,l)=>{let c={};try{c=mc(JSON.parse(Ve(l)))}catch{}this.authoritativeCompileStates=c,this.notifyCompileStateListeners()},this.provider.messageHandlers[co]=(a,l)=>{const c=Ve(l),d=Ve(l),f=Ve(l),h=Ve(l),p=Ve(l),m=Ve(l);if(c==="state"){const x=Eo(l)?Ve(l):"",j=Eo(l)?Ve(l):"",C=Number(p);if(!x||!Number.isFinite(C)||C<=Date.now())this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null);else{const z={path:f,holderUserId:x,holderName:j,expiresAt:C};this.formatLeaseStatesByPath.set(f,z);const k=this.formatLeaseExpiryTimers.get(f);k!==void 0&&window.clearTimeout(k);const y=window.setTimeout(()=>{const P=this.formatLeaseStatesByPath.get(f);!P||P.expiresAt>Date.now()||(this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null))},Math.max(0,C-Date.now())+25);this.formatLeaseExpiryTimers.set(f,y),this.notifyFormatLeaseListeners(z)}return}const g=this.formatLeaseRequests.get(d);g&&(window.clearTimeout(g.timer),this.formatLeaseRequests.delete(d),c==="denied"?g.reject(new Error(m||"Format lease request was denied")):g.resolve({status:c,filePath:f,token:h,expiresAt:Number(p)}))},this.provider.on("status",({status:a})=>{a==="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 Un;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 Kb(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 a=n[i];a.to>a.from&&s.delete(a.from,a.to-a.from),a.replacement&&s.insert(a.from,a.replacement)}})}get meta(){return this.doc.getMap("texlite:meta")}compileStates(){return this.authoritativeCompileStates??mc(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 gc(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){const e=this.readWritableDraftMarkers();return gc(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).otherActive}setPermission(e,n=!1){const s=this.permission;if(this.permission=e,e==="read"&&(s!=="read"&&this.rejectFlushes(new Error("Project permission changed to read-only")),this.destroyUndoManagers(),this.clearFormatLeaseStates()),this.updateLocalAwareness(),n&&s!==e)for(const r of this.permissionListeners)r(e,s)}setActiveFile(e){this.activeFile!==e&&(this.activeFile=e,this.awareness.setLocalStateField("cursor",null),this.updateLocalAwareness())}sessions(){const e=[];return this.awareness.getStates().forEach((n,s)=>{const r=n?.user;!r||typeof r.id!="string"||typeof r.name!="string"||e.push({clientId:s,userId:r.id,username:typeof r.username=="string"?r.username:r.name,name:r.name,color:typeof r.color=="string"?r.color:"#1677c8",colorLight:typeof r.colorLight=="string"?r.colorLight:"#1677c833",permission:r.permission==="owner"||r.permission==="edit"?r.permission:"read",filePath:typeof n.filePath=="string"?n.filePath:"",editing:!!n.cursor,local:s===this.doc.clientID})}),e.sort((n,s)=>Number(s.local)-Number(n.local)||n.name.localeCompare(s.name))}flush(){const e=this.provider.ws;if(!this.provider.synced||!e||e.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Collaboration connection is unavailable"));const n=No(),s=this.draftGeneration,r=Ke();return ne(r,hc),ct(r,n),new Promise((i,a)=>{const l=window.setTimeout(()=>{this.flushRequests.delete(n),a(new Error("Collaboration save timed out"))},5e3);this.flushRequests.set(n,{resolve:i,reject:a,timer:l,draftGeneration:s}),e.send(Me(r))})}onFormatLeaseState(e){this.formatLeaseListeners.add(e);for(const n of this.formatLeaseStatesByPath.values())e(n);return()=>this.formatLeaseListeners.delete(e)}formatLeaseStates(){const e=Date.now();for(const[n,s]of this.formatLeaseStatesByPath)s.expiresAt<=e&&this.removeFormatLeaseState(n);return[...this.formatLeaseStatesByPath.values()]}async acquireFormatLease(e){if(this.permission==="read")throw new Error("Formatting requires write permission");const n=await this.requestFormatLease("acquire",e);if(n.status!=="grant"||!n.token||!Number.isFinite(n.expiresAt))throw new Error("Format lease was not granted");let s=n.token,r=n.expiresAt,i=!1;const a=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:a,renew:a,release:async()=>{if(i)return;i=!0;const c=this.provider.ws;if(!(!c||c.readyState!==WebSocket.OPEN))try{await this.requestFormatLease("release",e,s)}catch{}}}}reconnect(){this.destroyed||(this.rejectFlushes(new Error("Collaboration connection reset")),this.provider.disconnect(),this.provider.connect(),this.updateLocalAwareness())}destroy(){this.destroyed=!0,this.setOwnDraftActivity(!1),this.stopDraftHeartbeat(),window.removeEventListener("pagehide",this.markDraftTabInactive),window.removeEventListener("pageshow",this.markDraftTabActive),this.rejectFlushes(new Error("Collaboration connection closed")),this.provider.destroy(),this.persistence.destroy(),this.draftListeners.clear(),this.protocolUpgradeListeners.clear(),this.compileStateListeners.clear(),this.rejectFormatLeaseRequests(new Error("Collaboration connection closed")),this.clearFormatLeaseStates(),this.formatLeaseListeners.clear(),this.meta.unobserve(this.metaObserver),this.doc.off("afterTransaction",this.localDraftTransactionObserver),this.destroyUndoManagers(),this.doc.destroy()}destroyUndoManagers(){for(const e of this.undoManagers.values())e.destroy();this.undoManagers.clear()}notifyCompileStateListeners(){for(const e of this.compileStateListeners)e()}rejectFlushes(e){for(const n of this.flushRequests.values())window.clearTimeout(n.timer),n.reject(e);this.flushRequests.clear()}requestFormatLease(e,n,s=""){const r=this.provider.ws;if(!this.provider.synced||!r||r.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Collaboration connection is unavailable"));const i=No(),a=Ke();return ne(a,co),ct(a,e),ct(a,i),ct(a,n),ct(a,s),new Promise((l,c)=>{const d=window.setTimeout(()=>{if(this.formatLeaseRequests.delete(i),e==="acquire"){const f=this.provider.ws;if(f?.readyState===WebSocket.OPEN){const h=Ke();ne(h,co),ct(h,"cancel"),ct(h,i),ct(h,n),ct(h,""),f.send(Me(h))}}c(new Error("Format lease request timed out"))},e==="acquire"?Lx:5e3);this.formatLeaseRequests.set(i,{resolve:l,reject:c,timer:d}),r.send(Me(a))})}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]=fc[Math.abs(this.doc.clientID)%fc.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 Tn(`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`)}writableDraftStoragePrefix(){return`${Tn(`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())Ms(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),Ms(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){const n=this.readOwnWritableDraftMarker();!n||!Fx(n.generation,this.draftGeneration,e)||(Ms(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){const e=this.writableDraftStoragePrefix(),n=[];for(const s of Ix()){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=wc(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>Ax)return Ms(e),null;const a=typeof r.activeAt=="number"&&Number.isFinite(r.activeAt)?Math.max(0,r.activeAt):0;return{generation:r.generation,updatedAt:r.updatedAt,activeAt:a}}catch{return Ms(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};uo(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)},Nx))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}}function wc(t){try{return window.localStorage.getItem(t)}catch{return null}}function uo(t,e){try{window.localStorage.setItem(t,e)}catch{}}function Ms(t){try{window.localStorage.removeItem(t)}catch{}}function Ix(){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 $x(t){try{return window.sessionStorage.getItem(t)}catch{return null}}function Ux(t,e){try{window.sessionStorage.setItem(t,e)}catch{}}function zx(t){const e=$x(t);if(e)return e;const n=No();return Ux(t,n),n}function Bx(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function Wx(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 qx(t,e,n,s,r,i){const[a]=u.useState(()=>new Mx(t,e)),[l,c]=u.useState("connecting"),[d,f]=u.useState(!1),[h,p]=u.useState([]),[m,g]=u.useState(null),[x,j]=u.useState(null),[C,z]=u.useState(""),[k,y]=u.useState(!1),[P,E]=u.useState(""),[S,N]=u.useState(""),[V,Y]=u.useState([]),[ie,F]=u.useState(!1),[le,G]=u.useState(s),[J,Z]=u.useState(null),[Ee,ce]=u.useState(!1),Q=u.useRef(n),$=u.useRef(i),fe=u.useRef(r);Q.current=n,$.current=i,fe.current=r,u.useEffect(()=>{const q=a.compileStates();g(q[n]??null)},[n,a]),u.useEffect(()=>{const q=()=>p(a.sessions()),he=()=>{f(!1),p([]),g(null),j(null),z(""),y(!1),E(""),N(""),Y([]),$.current()},we=({status:se})=>{c(se),se!=="connected"&&he()},U=se=>{f(se),se||he()},H=()=>{c("disconnected"),he()},Te=()=>{y(a.meta.get("historyWarning")===!0);const se=a.meta.get("filesEvent");Wx(se)&&j(se);const xe=a.meta.get("commentsRevision");typeof xe=="string"&&z(xe);const Pe=a.meta.get("dictionaryRevision");typeof Pe=="string"&&E(Pe);const Le=a.meta.get("chktexSettingsRevision");typeof Le=="string"&&N(Le);const D=a.compileStates();g(D[Q.current]??null)},ke=()=>{const se=a.compileStates();g(se[Q.current]??null)};a.awareness.on("change",q),a.provider.on("status",we),a.provider.on("sync",U),a.provider.on("connection-close",H),a.provider.on("connection-error",H),a.meta.observe(Te);const O=a.onCompileStates(ke),I=a.onProtocolUpgrade(()=>{ce(!0),c("disconnected"),he()}),te=()=>Y(a.formatLeaseStates()),Ne=a.onFormatLeaseState(te),_e=()=>{if(!fe.current||a.currentPermission!=="read")return;const se=a.hasWritableDraft,xe=a.hasOtherWritableDraft;!se&&!xe||Z({previous:"edit",localDraftReady:se,otherTabDraft:xe})},Ie=a.onDraftReady(()=>{F(!0),_e()}),$e=a.onPermissionChanged((se,xe)=>{if(se==="revoked"){c("disconnected"),f(!1),$.current();return}G(se),se==="read"&&xe!=="read"?Z({previous:xe,localDraftReady:a.hasWritableDraft,otherTabDraft:a.hasOtherWritableDraft}):se!=="read"&&Z(null)});return q(),Te(),c(a.connected?"connected":"connecting"),f(a.synced),()=>{a.awareness.off("change",q),a.provider.off("status",we),a.provider.off("sync",U),a.provider.off("connection-close",H),a.provider.off("connection-error",H),a.meta.unobserve(Te),O(),I(),Ne(),Ie(),$e(),a.destroy()}},[a]),u.useEffect(()=>{r&&a.connect()},[a,r]),u.useEffect(()=>{a.setPermission(s),G(s),r&&s==="read"&&(a.hasWritableDraft||a.hasOtherWritableDraft)?Z({previous:"edit",localDraftReady:a.hasWritableDraft,otherTabDraft:a.hasOtherWritableDraft}):s!=="read"&&Z(null)},[a,s,r]);const Se=J!==null;return u.useEffect(()=>{if(!Se)return;const q=()=>{if(a.currentPermission!=="read")return;const we=a.hasWritableDraft,U=a.hasOtherWritableDraft;Z(H=>!H||H.localDraftReady===we&&H.otherTabDraft===U?H:{...H,localDraftReady:we,otherTabDraft:U})};q();const he=window.setInterval(q,2e3);return()=>window.clearInterval(he)},[a,Se]),{collaboration:a,status:l,synced:d,activeSessions:h,compileState:m,setCompileState:g,formatLeaseStates:V,filesEvent:x,commentsRevision:C,historyWarning:k,dictionaryRevision:P,chktexSettingsRevision:S,localDraftReady:ie,permission:le,protocolUpgradeRequired:Ee,reconnect:()=>{Ee||(c("connecting"),f(!1),p([]),g(null),Y([]),a.reconnect())},permissionDowngrade:J,dismissPermissionDowngrade:()=>Z(null),discardLocalDraft:async()=>await a.discardLocalDraft()?(Z(null),window.location.reload(),!0):(Z(he=>he&&{...he,otherTabDraft:!0}),!1)}}function bc(t){return t?.status==="succeeded"?"succeeded":t?.log.includes("Compilation was cancelled.")?"cancelled":t?.status==="failed"?"failed":null}function En(t){return t instanceof Error&&t.name==="AbortError"}function Vx(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}function Hx(t){return t instanceof Element&&!!t.closest('[role="dialog"], [role="alertdialog"]')}function Kx({projectId:t,project:e,mainFile:n,resolveCompileMainFile:s,getCurrentMainFile:r,initialLatest:i,collaborationSynced:a,sharedState:l,onSharedState:c,save:d,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:m,onCompileSuccess:g,onPdfChanged:x}){const{t:j}=Je(),[C,z]=u.useState(""),[k,y]=u.useState(!0),[P,E]=u.useState(null),[S,N]=u.useState(null),[V,Y]=u.useState("full"),[ie,F]=u.useState(""),[le,G]=u.useState(null),[J,Z]=u.useState(null),[Ee,ce]=u.useState([]),[Q,$]=u.useState(null),[fe,Se]=u.useState(!1),[ve,je]=u.useState(!1),[ee,q]=u.useState(()=>new Set),[he,we]=u.useState(()=>new Set),[U,H]=u.useState(""),[Te,ke]=u.useState({projectId:t,mainFile:n}),O=u.useRef(n),I=u.useRef(""),te=u.useRef(""),Ne=u.useRef({projectId:t,mainFile:n}),_e=u.useRef(!0),Ie=u.useRef(null),$e=u.useRef(null),se=u.useRef(null),xe=u.useRef(i),Pe=u.useRef(!1),Le=u.useRef(null),D=u.useRef(null),ue=u.useRef(new Set),Ue=u.useRef(new Map),Ye=u.useRef(null),nt=u.useRef(()=>{}),pe=u.useRef({onSharedState:c,save:d,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:m,onCompileSuccess:g,onPdfChanged:x,resolveCompileMainFile:s,getCurrentMainFile:r});O.current=n,pe.current={onSharedState:c,save:d,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:m,onCompileSuccess:g,onPdfChanged:x,resolveCompileMainFile:s,getCurrentMainFile:r};const A=()=>pe.current.getCurrentMainFile?.()||O.current,X=Te.projectId===t&&Te.mainFile===n,Oe=B=>{Ye.current!==B&&(Ye.current=B,pe.current.onCompileSuccess())},ze=(B,v,_,K,dt)=>{(te.current!==v||I.current!==B)&&pe.current.onPdfChanged(),te.current=v,I.current=B,z(v),E(_),N(K),Y(dt??"full")},M=async(B,v)=>{v||(Le.current?.abort(),Le.current=new AbortController,v=Le.current.signal);try{const _=B?`?mainFile=${encodeURIComponent(B)}`:"",K=await be(`/api/projects/${t}/compile/artifacts${_}`,{signal:v});O.current===B&&(ce(K.artifacts),$(null))}catch(_){!En(_)&&O.current===B&&(ce([]),$(null))}finally{Le.current?.signal===v&&(Le.current=null)}};u.useEffect(()=>{Ie.current?.abort(),Ie.current=null;const B=Ne.current,v=B.projectId===t,_=v&&!!B.mainFile&&!!n&&B.mainFile!==n;if(Ne.current={projectId:t,mainFile:n},ke(De=>De.projectId===t&&De.mainFile===n?De:{projectId:t,mainFile:n}),v||(xe.current=i,Pe.current=!1,se.current=null,I.current="",te.current=""),!n){y(!1),te.current="",z(""),E(null),N(null),Y("full"),F(""),G(null),Z(null),ce([]),$(null),Se(!1),H(""),se.current=null,pe.current.onPdfChanged();return}if(se.current?.mainFile!==n&&(se.current=null),F(""),G(null),Z(null),_){_e.current=!1,$e.current?.abort(),Le.current?.abort(),D.current?.abort(),I.current="",te.current="",z(""),E(null),N(null),Y("full"),y(!1),ce([]),$(null),Se(!1),H(""),pe.current.onPdfChanged(),pe.current.onPreviewTab("pdf");const De=new AbortController;return pe.current.loadOutline(De.signal,n).catch(()=>{}),()=>De.abort()}_e.current=!0;const K=new AbortController;Ie.current=K,y(!0),v&&C&&n&&I.current===n||(te.current="",z(""),E(null),N(null),Y("full")),ce([]),$(null),pe.current.onPdfChanged();let L=null;const W=`?mainFile=${encodeURIComponent(n)}`,bt=Pe.current?null:xe.current;bt&&(Pe.current=!0);const kt=()=>be(`/api/projects/${t}/compile/latest${W}`,{signal:K.signal}),qn=bt?bt.then(De=>De.mainFile!==n?kt():De,()=>kt()):kt();let ft=!1;const wi=()=>{if(ft||K.signal.aborted||!n)return;ft=!0;const De=new AbortController;ue.current.add(De),M(n,De.signal).finally(()=>{ue.current.delete(De)}),pe.current.loadOutline(K.signal,n).catch(()=>{})};return qn.then(De=>{if(K.signal.aborted||n&&De.mainFile!==O.current)return;const Rs=se.current;Rs&&Rs.mainFile===n&&De.latestRun?.id!==Rs.runId||(F(De.latestRun?.log??""),G(De.latestRun?.diagnostics??null),Z(bc(De.latestRun)),n&&De.latestRun?.requestedBy&&(De.latestRun.status==="queued"||De.latestRun.status==="running")&&pe.current.onSharedState({mainFile:n,runId:De.latestRun.id,status:De.latestRun.status,requestedBy:De.latestRun.requestedBy,updatedAt:new Date().toISOString()}),De.pdfUrl&&(ze(De.mainFile,De.pdfUrl,De.pdfCompiledAt,De.pdfSizeBytes,De.pdfLoadingMode),pe.current.onPreviewTab("pdf")))}).catch(De=>{!En(De)&&O.current===n&&pe.current.onError(ye(De))}).finally(()=>{Ie.current===K&&(Ie.current=null),K.signal.aborted||(y(!1),L=window.setTimeout(wi,0))}),()=>{L!==null&&window.clearTimeout(L),K.abort(),D.current?.abort();for(const De of ue.current)De.abort();ue.current.clear()}},[t,n]),u.useEffect(()=>{if(!(!l||l.mainFile!==n||l.status!=="cleaned"||!l.cleanMode)){Ie.current?.abort(),$e.current?.abort(),Le.current?.abort(),D.current?.abort();for(const B of ue.current)B.abort();ue.current.clear(),l.cleanMode==="artifacts"?(se.current=null,F(""),G(null),Z(null),te.current="",z(""),E(null),N(null),Y("full"),ce([]),$(null),pe.current.onPdfChanged(),pe.current.onPreviewTab("pdf"),H(j("editor.cleanArtifactsComplete"))):H(j("editor.cleanCacheComplete"))}},[l?.runId,l?.status,l?.cleanMode,l?.mainFile,n,j]),u.useEffect(()=>{!n||l?.mainFile===n&&(l.status==="queued"||l.status==="running")||we(B=>{if(!B.has(n))return B;const v=new Set(B);return v.delete(n),v})},[n,l?.mainFile,l?.status]),u.useEffect(()=>{l?.mainFile===n&&(l.status==="queued"||l.status==="running")&&(_e.current=!0)},[n,l?.mainFile,l?.status,l?.runId]),u.useEffect(()=>{if(!l||l.mainFile!==n||l.status!=="succeeded"&&l.status!=="failed"||!_e.current)return;let B=!1;$e.current?.abort(),D.current?.abort();const v=new AbortController;return $e.current=v,y(!0),be(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:v.signal}).then(_=>{B||_.mainFile!==O.current||_.latestRun?.id!==l.runId||(F(_.latestRun.log),G(_.latestRun.diagnostics),Z(bc(_.latestRun)),l.status==="succeeded"&&l.stale&&H(j("editor.compileSnapshotStale")),l.status==="succeeded"&&_.pdfUrl?(se.current={mainFile:n,runId:l.runId},ze(n,_.pdfUrl,_.pdfCompiledAt,_.pdfSizeBytes,_.pdfLoadingMode),pe.current.onPreviewTab("pdf"),Oe(l.runId),M(n)):l.status==="failed"&&pe.current.onPreviewTab(_.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(_=>{!En(_)&&!B&&pe.current.onError(ye(_))}).finally(()=>{$e.current===v&&($e.current=null),B||y(!1)}),()=>{B=!0,v.abort(),$e.current===v&&($e.current=null)}},[l?.runId,l?.status,l?.mainFile,l?.stale,n,t,j]);const oe=async()=>{if(!e||e.permission==="read"||!a)return;const B=pe.current.resolveCompileMainFile?.()||A();if(!B||Ue.current.has(B)||l?.mainFile===B&&(l.status==="queued"||l.status==="running"))return;q(_=>new Set([..._,B])),pe.current.onCompileStart(),H(""),D.current?.abort(),D.current=null,F(""),G(null),Z(null),pe.current.onPreviewTab(X&&C?"pdf":"log");const v=new AbortController;Ue.current.set(B,v);try{if(!await pe.current.save())return;_e.current=!0;const _=await be(`/api/projects/${t}/compile`,{method:"POST",signal:v.signal,body:JSON.stringify({mainFile:B})});if(_.mainFile!==B||A()!==B)return;F(_.log),G(_.diagnostics),Z(_.cancelled?"cancelled":_.ok?"succeeded":"failed"),_.cancelled&&H(j("compileControls.cancelled")),_.skipped&&H(j("editor.upToDate")),_.ok&&_.stale&&H(j("editor.compileSnapshotStale")),_.pdfUrl?(_.ok&&(se.current={mainFile:B,runId:_.runId}),ze(B,_.pdfUrl,_.pdfCompiledAt,_.pdfSizeBytes,_.pdfLoadingMode),pe.current.onPreviewTab("pdf"),_.ok&&(_.skipped?pe.current.onCompileSuccess():Oe(_.runId))):pe.current.onPreviewTab(_.diagnostics.errors.length?"errors":"log")}catch(_){!En(_)&&A()===B&&pe.current.onError(ye(_))}finally{Ue.current.get(B)===v&&(Ue.current.delete(B),q(_=>{const K=new Set(_);return K.delete(B),K}),we(_=>{if(!_.has(B))return _;const K=new Set(_);return K.delete(B),K}))}},Re=async()=>{if(!e||e.permission==="read"||!a)return;const B=A();if(B){we(v=>new Set([...v,B]));try{(await be(`/api/projects/${t}/compile/cancel`,{method:"POST",body:JSON.stringify({mainFile:B})})).cancelled||we(_=>{const K=new Set(_);return K.delete(B),K})}catch(v){we(_=>{const K=new Set(_);return K.delete(B),K}),!En(v)&&A()===B&&pe.current.onError(ye(v))}}},re=async B=>{if(!e||e.permission==="read"||!a||ve)return;const v=A();if(!(!v||Ue.current.has(v)||l?.mainFile===v&&(l.status==="queued"||l.status==="running"))){je(!0),Ie.current?.abort(),$e.current?.abort(),Le.current?.abort(),D.current?.abort();try{if((await be(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:v,mode:B})})).mainFile!==v||A()!==v)return;pe.current.onSharedState(null),B==="artifacts"&&(se.current=null,F(""),G(null),Z(null),te.current="",z(""),E(null),N(null),Y("full"),ce([]),$(null),pe.current.onPdfChanged()),H(j(B==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(_){!En(_)&&A()===v&&pe.current.onError(ye(_))}finally{je(!1)}}};nt.current=()=>{oe()},u.useEffect(()=>{if(!U)return;const B=window.setTimeout(()=>H(""),3e3);return()=>window.clearTimeout(B)},[U]),u.useEffect(()=>{const B=v=>{if(!(!(v.ctrlKey||v.metaKey)||v.key.toLocaleLowerCase()!=="s")){if(Vx(v.target)||Hx(v.target)){v.preventDefault();return}v.preventDefault(),v.stopPropagation(),v.repeat||nt.current()}};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[]),u.useEffect(()=>()=>{Ie.current?.abort(),$e.current?.abort(),Le.current?.abort(),D.current?.abort();for(const B of ue.current)B.abort();ue.current.clear();for(const B of Ue.current.values())B.abort();Ue.current.clear()},[]);const vt=async B=>{if(!B.viewable)return;D.current?.abort();const v=new AbortController;D.current=v,Se(!0);try{const _=await be(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(B.path)}`,{signal:v.signal});!v.signal.aborted&&D.current===v&&O.current===n&&$(_)}catch(_){En(_)||pe.current.onError(ye(_))}finally{D.current===v&&(D.current=null,Se(!1))}};return{pdfUrl:X?C:"",pdfCompiledAt:X?P:null,pdfSizeBytes:X?S:null,pdfLoadingMode:V,pdfLoading:X?k:!1,compileLog:X?ie:"",compileDiagnostics:X?le:null,compileOutcome:X?J:null,artifacts:X?Ee:[],artifactPreview:X?Q:null,artifactLoading:X&&fe,editorNotice:X?U:"",localCompiling:ee.has(n),cancelling:he.has(n),cleaning:ve,compile:oe,cancelCompile:Re,cleanCompile:re,viewArtifact:vt}}const Fo=10*1024*1024,Gx=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 yc(t){return t instanceof Error&&t.name==="AbortError"}function Ln(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function jn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function Jx(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!Gx.has(e)}function fs(t){return/(?:\.(?:tex|bib|bst|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function xc(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":Jx(t)?"text":"unsupported"}function Yx(t,e){return vs(`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`)}function Xx({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:a,onActiveFile:l,onActiveMainFile:c}){const{t:d}=Je(),[f,h]=u.useState([]),[p,m]=u.useState(!1),[g,x]=u.useState(""),[j,C]=u.useState(null),[z,k]=u.useState(!1),[y,P]=u.useState(!1),[E,S]=u.useState(""),[N,V]=u.useState(""),[Y,ie]=u.useState(null),[F,le]=u.useState(""),[G,J]=u.useState(new Set),[Z,Ee]=u.useState(null),[ce,Q]=u.useState(""),[$,fe]=u.useState(""),[Se,ve]=u.useState(null),[je,ee]=u.useState(!1),[q,he]=u.useState(null),[we,U]=u.useState(!1),[H,Te]=u.useState(null),ke=u.useRef(!1),O=u.useRef(null),I=u.useRef(null),te=u.useRef(null),Ne=async(A={})=>{I.current?.abort(),I.current=null;const X=A.signal?null:new AbortController;X&&(I.current=X);try{const Oe=await be(`/api/projects/${t}/files`,{signal:A.signal??X?.signal});return(!A.isCurrent||A.isCurrent())&&h(Oe.files),Oe.files}catch(Oe){if(!yc(Oe))throw Oe;return}finally{X&&I.current===X&&(I.current=null)}},_e=async()=>{if(!(!g.trim()||g.trim().endsWith("/"))){V("");try{await be(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:g,content:""})}),await Ne(),l(g),ie(null),J(A=>new Set([...A,...Ln(g)])),m(!1),x("")}catch(A){V(ye(A))}}},Ie=async()=>{if(!E.trim())return;V("");const A=Y?`${Y}/${E.trim()}`:E.trim();try{const X=await be(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:A})});await Ne(),J(Oe=>new Set([...Oe,...Ln(X.path),X.path])),ie(X.path),P(!1),S("")}catch(X){V(ye(X))}},$e=async(A,X=new Set,Oe=Y)=>{if(!A.length||ke.current)return;const ze=e.maxUploadSizeMB;if(A.find(K=>K.size>ze*1024*1024)){Te({kind:"error",message:d("errors.fileTooLarge",{size:ze})});return}const oe=Oe??"",Re=A.map(K=>oe?`${oe}/${K.name}`:K.name),re=new Map;for(const K of Re)re.set(K,(re.get(K)??0)+1);const vt=[...re.entries()].filter(([,K])=>K>1).map(([K])=>K);if(vt.length){Te({kind:"error",message:d("errors.duplicateUploadNames",{files:vt.join(", ")})});return}const B=new Set(f.map(K=>K.path)),v=[...new Set(Re.filter(K=>B.has(K)&&!X.has(K)))];if(v.length){Te(null),he({files:A,directory:oe,collisions:v});return}he(null),O.current!==null&&window.clearTimeout(O.current),O.current=null,Te(null),ke.current=!0,U(!0);let _=0;try{const K=new URLSearchParams;oe&&K.set("directory",oe);let dt="";for(const[L,W]of A.entries()){const bt=Re[L];K.delete("overwrite"),X.has(bt)&&K.set("overwrite","1");const kt=K.toString()?`?${K.toString()}`:"",qn=new FormData;qn.append("file",W);try{Te({kind:"uploading",fileName:W.name,current:L+1,total:A.length});const ft=await be(`/api/projects/${t}/upload${kt}`,{method:"POST",body:qn});_+=1,typeof ft.path=="string"&&fs(ft.path)&&(dt=ft.path)}catch(ft){if(ft instanceof Pr&&ft.status===409&&!X.has(bt)&&ft.code==="FILE_EXISTS"){if(Te(null),L>0)try{await Ne()}catch{}he({files:A.slice(L),directory:oe,collisions:[bt]});return}throw ft}}try{await Ne()}catch(L){Te({kind:"error",message:d("editor.uploadSucceededRefreshFailed",{message:ye(L)})});return}dt&&(l(dt),ie(null)),Te({kind:"success",count:_}),O.current=window.setTimeout(()=>{Te(L=>L?.kind==="success"?null:L),O.current=null},3e3)}catch(K){try{await Ne()}catch{}const dt=_>0?d("editor.uploadFailedPartial",{uploaded:_,total:A.length,message:ye(K)}):d("editor.uploadFailed",{message:ye(K)});Te({kind:"error",message:dt})}finally{ke.current=!1,U(!1)}},se=()=>{O.current!==null&&window.clearTimeout(O.current),O.current=null,Te(null)},xe=async A=>{await $e(Array.from(A.target.files??[])),A.target.value=""},Pe=async A=>{te.current?.abort(),te.current=null,k(!1);const X=Yx(t,A.path);if((A.size??0)>Fo){C({path:A.path,kind:"large",size:A.size??0,url:X});return}const Oe=xc(A.path);if(Oe!=="text"){C({path:A.path,kind:Oe,size:A.size??0,url:X});return}C({path:A.path,kind:Oe,size:A.size??0,url:X,content:""}),k(!0);const ze=new AbortController;te.current=ze;try{let M;try{M=await fetch(X,{signal:ze.signal})}catch(re){throw Ep(re)}const oe=M.headers.get("content-type")??"";if(!M.ok){let re=null;try{re=oe.includes("application/json")?await M.json():await M.text()}catch{}throw new Pr(jp(re,M.status),M.status,Dp(re))}const Re=await M.text();C(re=>re?.path===A.path?{...re,content:Re}:re)}catch(M){yc(M)||(C(null),i(ye(M)))}finally{te.current===ze&&(te.current=null,k(!1))}},Le=A=>{ie(null),le(A.path);const X=xc(A.path),Oe=e.maxCollaborativeFileSizeMB*1024*1024;(A.size??0)>Fo||fs(A.path)&&(A.size??0)>Oe||X!=="text"||!fs(A.path)?Pe(A):l(A.path)},D=async(A,X,Oe)=>{if(!await r())return null;const ze=await be(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:A.path,destinationDirectory:X,destinationName:Oe})}),M=re=>re===A.path?ze.path:re.startsWith(`${A.path}/`)?`${ze.path}${re.slice(A.path.length)}`:re;l(re=>M(re)),c(re=>M(re)),ie(re=>re&&M(re)),le(re=>re&&M(re));const[oe,Re]=await Promise.all([be(`/api/projects/${t}/files`),be(`/api/projects/${t}`)]);return h(oe.files),a(Re.project),J(re=>new Set([...re,...Ln(ze.path),X].filter(Boolean))),ze.path},ue=async()=>{if(!Z)return;const A=ce.trim();if(A){V("");try{if(!await D(Z,$,A))return;Ee(null),Q(""),fe("")}catch(X){V(ye(X))}}},Ue=async(A,X)=>{if(Zx(A.path)!==X&&!(A.type==="directory"&&(X===A.path||X.startsWith(`${A.path}/`))))try{await D(A,X,A.path.split("/").at(-1)??A.path)}catch(Oe){i(ye(Oe))}},Ye=async()=>{if(Se){V("");try{if(s&&!await r())return;await be(`/api/projects/${t}/file?path=${encodeURIComponent(Se.path)}`,{method:"DELETE"}),ve(null)}catch(A){V(ye(A))}}};u.useEffect(()=>()=>{I.current?.abort(),te.current?.abort(),O.current!==null&&window.clearTimeout(O.current)},[]),u.useEffect(()=>{te.current?.abort(),te.current=null,k(!1)},[n]),u.useEffect(()=>{n&&le(n)},[n]);const nt=f.filter(A=>A.type==="directory"),pe=f.filter(A=>Ln(A.path).every(X=>G.has(X)));return{files:f,setFiles:h,loadFiles:Ne,newFileOpen:p,setNewFileOpen:m,newFilePath:g,setNewFilePath:x,resourcePreview:j,setResourcePreview:C,resourcePreviewLoading:z,setResourcePreviewLoading:k,newFolderOpen:y,setNewFolderOpen:P,newFolderName:E,setNewFolderName:S,fileDialogError:N,setFileDialogError:V,selectedFolder:Y,setSelectedFolder:ie,selectedFile:F,setSelectedFile:le,expandedFolders:G,setExpandedFolders:J,moveEntry:Z,setMoveEntry:Ee,moveName:ce,setMoveName:Q,moveDestination:$,setMoveDestination:fe,deleteEntry:Se,setDeleteEntry:ve,fileDragActive:je,setFileDragActive:ee,uploadConflict:q,setUploadConflict:he,uploadingFiles:we,uploadFeedback:H,dismissUploadFeedback:se,directoryEntries:nt,visibleEntries:pe,createFile:_e,createFolder:Ie,uploadFiles:$e,upload:xe,openFile:Le,movePath:ue,movePathToFolder:Ue,removePath:Ye}}function Zx(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Qx({active:t,harperEnabled:e=!0,projectId:n,activeFile:s,content:r,dictionaryWords:i,additionalIssues:a=[],additionalIssuesReady:l=!0}){const[c,d]=u.useState([]),[f,h]=u.useState(""),[p,m]=u.useState(""),[g,x]=u.useState(0),[j,C]=u.useState(null),[z,k]=u.useState(null),[y,P]=u.useState(!1),[E,S]=u.useState(0),N=u.useRef(0),V=u.useRef(!1),Y=u.useRef(!1),ie=u.useRef(r),F=u.useRef(s),le=u.useRef(0);ie.current=r,F.current=s,Y.current=y,u.useEffect(()=>{d([]),h(""),m(""),C(null),k(null),P(!1)},[s,i,e]),u.useEffect(()=>{k(null),P(!1)},[n]),u.useEffect(()=>{const ce=++N.current;if(!t||!s){d([]),h(""),m(""),C(null);return}if(!e){d([]),h(""),m("");return}if(z){d([]),h(""),m("");return}const Q=r,$=s;let fe=!1;const Se=window.setTimeout(()=>{k(null),(async()=>{try{const{lintLatex:ve,isHarperLintSupersededError:je}=await _t(async()=>{const{lintLatex:q,isHarperLintSupersededError:he}=await import("./spellCheck-hpm8qZTr.js");return{lintLatex:q,isHarperLintSupersededError:he}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]),import.meta.url);if(fe||ce!==N.current||ie.current!==Q||F.current!==$)return;let ee;try{ee=await ve(n,$,Q,i)}catch(q){if(je(q))return;throw q}if(fe||ce!==N.current||ie.current!==Q||F.current!==$)return;V.current=!1,P(!1),d(ee),h(Q),m($),x(0),C(null)}catch(ve){if(fe||ce!==N.current||ie.current!==Q||F.current!==$)return;d([]),h(""),m(""),k(ve instanceof Error?ve.message:String(ve));const je=V.current;V.current=!1,P(je?Y.current:!1)}})()},700);return()=>{fe=!0,window.clearTimeout(Se)}},[t,e,n,s,r,i,E,z]),u.useEffect(()=>{if(!z||!t||!e)return;let ce=!1;const Q=()=>{ce||(ce=!0,V.current=!0,k(null),S(fe=>fe+1))},$=window.setTimeout(Q,15e3);return window.addEventListener("online",Q,{once:!0}),()=>{window.clearTimeout($),window.removeEventListener("online",Q)}},[z,t,e]);const G=e&&t&&p===s&&f===r,J=u.useMemo(()=>{if(!t)return[];const ce=[...G?c:[],...a].sort(($,fe)=>$.from-fe.from||$.to-fe.to),Q=new Set;return ce.filter($=>{const fe=`${$.from}:${$.to}:${$.kind}:${$.message}`;return Q.has(fe)?!1:(Q.add(fe),!0)})},[t,a,G,c]),Z=u.useMemo(()=>t&&(!e||G)&&l?{total:J.length,unique:new Set(J.map(ce=>`${ce.kind}:${ce.word.toLocaleLowerCase("en-US")}`)).size}:null,[t,l,e,G,J]);return u.useEffect(()=>{x(ce=>J.length?Math.min(ce,J.length-1):0)},[J]),{issues:J,jump:t?j:null,index:g,summary:Z,jumpToIssue:ce=>{if(!J.length)return;const Q=Math.max(0,Math.min(ce,J.length-1)),$=J[Q];x(Q),C({from:$.from,to:$.to,nonce:++le.current})},error:t&&e&&!y?z:null,nativeFallback:t&&e&&!!z,retry:()=>{V.current=!1,k(null),P(!1),S(ce=>ce+1)},dismissError:()=>{V.current=!1,P(!0)}}}function e0({active:t,projectId:e,activeFile:n,content:s}){const[r,i]=u.useState([]),[a,l]=u.useState(""),[c,d]=u.useState(""),[f,h]=u.useState(null),[p,m]=u.useState(!1),[g,x]=u.useState(0),j=u.useRef(0),C=u.useRef(s),z=u.useRef(n);C.current=s,z.current=n,u.useEffect(()=>{i([]),l(""),d(""),h(null),m(!1)},[e,n]),u.useEffect(()=>{const y=++j.current;if(!t||!n){i([]),l(""),d("");return}const P=s,E=n;let S=!1;const N=window.setTimeout(()=>{(async()=>{try{const{lintChktex:V,isChktexLintSupersededError:Y}=await _t(async()=>{const{lintChktex:F,isChktexLintSupersededError:le}=await import("./chktex-CRkLYKcV.js");return{lintChktex:F,isChktexLintSupersededError:le}},__vite__mapDeps([10,1,2,3,4,5,6,7,8,9]),import.meta.url);if(S||y!==j.current||C.current!==P||z.current!==E)return;let ie;try{ie=await V(e,E,P)}catch(F){if(Y(F))return;throw F}if(S||y!==j.current||C.current!==P||z.current!==E)return;i(ie),l(P),d(E),h(null),m(!1)}catch(V){if(S||y!==j.current||C.current!==P||z.current!==E)return;i([]),l(""),d(""),h(V instanceof Error?V.message:String(V))}})()},2e3);return()=>{S=!0,window.clearTimeout(N)}},[t,e,n,s,g]);const k=t&&c===n&&a===s;return{issues:k?r:[],checked:k,error:t&&!p?f:null,retry:()=>{h(null),m(!1),x(y=>y+1)},dismissError:()=>m(!0)}}function Sc(t){return t instanceof Error&&t.name==="AbortError"}function t0({projectId:t,mainFile:e,activeFile:n,onOpenSourceFile:s,onError:r,onShowPdf:i,onShowEditor:a}){const[l,c]=u.useState(null),[d,f]=u.useState(null),[h,p]=u.useState(null),m=u.useRef(null),g=u.useRef(0),x=u.useRef(n),j=u.useRef(s),C=u.useRef(r),z=u.useRef(i),k=u.useRef(a),y=Y=>Y===e&&/\.tex$/i.test(Y);x.current=n,j.current=s,C.current=r,z.current=i,k.current=a,u.useEffect(()=>(m.current?.abort(),m.current=null,c(null),f(null),p(null),()=>m.current?.abort()),[t,e]);const P=(Y,ie,F)=>{p({path:Y,line:ie,column:F,nonce:++g.current}),j.current(Y)},E=async(Y,ie,F,le={})=>{if(!y(Y))return;m.current?.abort();const G=new AbortController;m.current=G;try{const J=await be(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(Y)}&line=${ie}&column=${F}`,{signal:G.signal});if(m.current!==G||!J)return;c({...J,nonce:++g.current}),z.current()}catch(J){!Sc(J)&&!le.silent&&C.current(ye(J))}finally{m.current===G&&(m.current=null)}},S=async(Y,ie,F)=>{const le=x.current;m.current?.abort();const G=new AbortController;m.current=G;try{const J=await be(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${Y}&x=${ie}&y=${F}`,{signal:G.signal});if(m.current!==G||x.current!==le)return;k.current(),P(J.path,J.line,J.column)}catch(J){Sc(J)||C.current(ye(J))}finally{m.current===G&&(m.current=null)}};return{pdfTarget:l,pdfViewport:d,sourceJump:h,setPdfViewport:f,resetPdfViewport:()=>f(null),clearPdfViewport:()=>{m.current?.abort(),m.current=null,f(null),c(null)},jumpToSource:P,syncSourceToPdf:E,syncPdfToSource:S,syncVisiblePdfToSource:()=>{d&&S(d.page,d.x,d.y)}}}function _d(t,e){return Tn(`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function vc(t,e){try{const n=window.localStorage.getItem(_d(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function n0(t,e){const[n,s]=u.useState(()=>vc(t,e));return u.useEffect(()=>{s(vc(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(_d(t,e),i)}catch{}}}}function s0(t){return!/\.(?:bib|bst)$/i.test(t.trim())}function kc(t){return/\.(?:tex|sty|cls)$/i.test(t.trim())}const Ld=["verbatim","verbatim*","Verbatim","BVerbatim","LVerbatim","SaveVerbatim","VerbatimOut","bverbatim","bverbatim*","lverbatim","lverbatim*","saveverbatim","saveverbatim*","verbatimout","verbatimwrite","lstlisting","lstlisting*","minted","minted*","tcblisting","tcblisting*","pygmented","alltt","filecontents","filecontents*","luacode","luacodestar","comment"],r0=new Set(Ld);function i0(t){return r0.has(t)}function o0(t,e,n){if(t[e]!=="[")return e;let s=1;for(let r=e+1;r<n;r+=1){if(t[r]==="\\"){r+=1;continue}if(t[r]==="["&&(s+=1),t[r]==="]"&&(s-=1,s===0))return r+1}return null}function Cc(t,e,n){if(t[e]!=="{")return null;let s=1;for(let r=e+1;r<n;r+=1){if(t[r]==="\\"){r+=1;continue}if(t[r]==="{"&&(s+=1),t[r]==="}"&&(s-=1,s===0))return r+1}return null}function Ad(t,e,n=t.length){const s=t.indexOf(`
|
|
11
|
+
`,e);s>=0&&(n=Math.min(n,s));const r=/^\\(verb\*?|Verb\*?|lstinline\*?|mintinline\*?)(?![A-Za-z@])/.exec(t.slice(e,n));if(!r)return null;const i=r[1].replace(/\*$/,"");let a=e+r[0].length;if(i!=="verb"){const d=o0(t,a,n);if(d===null)return null;a=d}if(i==="mintinline"){const d=Cc(t,a,n);if(d===null)return null;a=d}const l=t[a];if(!l||/\s/.test(l))return null;if(l==="{"&&i!=="verb"){const d=Cc(t,a,n);return{end:d??n,closed:d!==null}}const c=t.indexOf(l,a+1);return c<0||c>=n?{end:n,closed:!1}:{end:c+1,closed:!0}}function Nd(t,e,n=t.length){return Ad(t,e,n)?.end??null}function Ra(t,e,n){const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(String.raw`\\end\s*\{\s*${s}\s*\}`,"g");r.lastIndex=e;const i=r.exec(t);return i?{from:i.index,to:i.index+i[0].length}:null}function nr(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function a0(t,e){let n=e+1;if(/[A-Za-z@]/.test(t[n]??"")){for(;/[A-Za-z@]/.test(t[n]??"");)n+=1;return t[n]==="*"&&(n+=1),n}return Math.min(t.length,n+1)}function Od(t,e){const n=/^\\begin\s*\{\s*([A-Za-z0-9@:_*.\-]+)\s*\}/.exec(t.slice(e));return!n||!i0(n[1])?null:{name:n[1],to:e+n[0].length}}function wv(t,e){const n=Math.max(0,Math.min(t.length,e));for(let s=0;s<n;){if(t[s]==="%"&&!nr(t,s)){const a=t.indexOf(`
|
|
12
|
+
`,s),l=a<0?t.length:a;if(n<=l)return"comment";s=l+1;continue}if(t[s]!=="\\"||nr(t,s)){s+=1;continue}const r=Ad(t,s);if(r!==null){if(n<r.end||!r.closed&&n<=r.end)return"literal";s=r.end;continue}const i=Od(t,s);if(i){const a=Ra(t,i.to,i.name),l=a?.to??t.length;if(n<l||!a&&n<=l)return"literal";s=l;continue}s=a0(t,s)}return null}function Ec(t,e,n){return t.slice(e,n).replace(/[^\r\n]/g," ")}function l0(t){const e=t.split("");for(let n=0;n<t.length;n+=1){if(t[n]!=="%"||nr(t,n))continue;const s=t.indexOf(`
|
|
13
|
+
`,n),r=s<0?t.length:s;for(let i=n;i<r;i+=1)e[i]=" ";n=r}return e.join("")}function c0(t){let e="",n=0;for(;n<t.length;){if(t[n]==="%"&&!nr(t,n)){const i=t.indexOf(`
|
|
14
|
+
`,n),a=i<0?t.length:i;e+=t.slice(n,a),n=a;continue}if(t[n]!=="\\"||nr(t,n)){e+=t[n],n+=1;continue}const s=Nd(t,n);if(s!==null){e+=Ec(t,n,s),n=s;continue}const r=Od(t,n);if(r){const a=Ra(t,r.to,r.name)?.to??t.length;e+=Ec(t,n,a),n=a;continue}e+=t[n],n+=1}return e}function u0(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function jc(t){const e=l0(c0(t)),n=/\\documentclass(?![A-Za-z@])\s*(?:\[[^\]]*\]\s*)?\{/g;for(const s of e.matchAll(n))if(s.index!==void 0&&!u0(e,s.index))return!0;return!1}const d0=new Set(Ld);function f0(t){return/[A-Za-z@0-9:_-]/.test(t)}function h0(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function Ts(t,e){return t[e]==="%"&&!h0(t,e)}function fr(t,e){const n=t.indexOf(`
|
|
15
|
+
`,e);return n===-1?t.length:n}function ti(t,e){let n=e;for(;n<t.length;){if(/\s/.test(t[n])){n+=1;continue}if(Ts(t,n)){n=fr(t,n);continue}break}return n}function Mo(t,e,n,s){if(t[e]!==n)return null;let r=0,i=0;for(let a=e;a<t.length;a+=1){const l=t[a];if(l==="\\"&&a+1<t.length){a+=1;continue}if(Ts(t,a)){a=fr(t,a)-1;continue}if(n==="["){if(l==="{"){i+=1;continue}if(l==="}"&&i>0){i-=1;continue}if(i>0)continue}if(l===n){r+=1;continue}if(l===s&&(r-=1,r===0))return{from:e,to:a+1,contentFrom:e+1,contentTo:a}}return null}function Io(t,e,n){const s=[];let r=e;for(;s.length<n;){for(r=ti(t,r);t[r]==="[";){const a=Mo(t,r,"[","]");if(!a)return s;r=ti(t,a.to)}if(t[r]!=="{")break;const i=Mo(t,r,"{","}");if(!i)break;s.push(i),r=i.to}return s}function bv(t,e,n){const s=[];let r=e;for(;s.length<n&&(r=ti(t,r),t[r]==="[");){const i=Mo(t,r,"[","]");if(!i)break;s.push(i),r=i.to}return s}function p0(t,e){if(t[e]!=="\\"||e+1>=t.length)return null;let n=e+1;if(!/[A-Za-z@]/.test(t[n]))return{name:t[n],from:e,to:n+1};for(;n<t.length&&f0(t[n]);)n+=1;const s=t.slice(e+1,n);return t[n]==="*"&&(n+=1),{name:s,from:e,to:n}}function m0(t,e){if(e.name!=="begin")return e.to;const n=Io(t,e.to,1)[0];if(!n)return e.to;const s=t.slice(n.contentFrom,n.contentTo).trim();return d0.has(s)?Ra(t,n.to,s)?.to??t.length:e.to}function g0(t,e){let n=0;for(;n<t.length;){if(Ts(t,n)){n=fr(t,n);continue}if(t[n]!=="\\"){n+=1;continue}const s=p0(t,n);if(!s){n+=1;continue}const r=Nd(t,s.from);if(r!==null&&r>s.to){n=r;continue}const i=m0(t,s);if(i>s.to){n=i;continue}e(s),n=s.to}}function fo(t,e,n){const s=[];let r=e.contentFrom,i=e.contentFrom;for(;i<=e.contentTo;){if(i<e.contentTo&&Ts(t,i)){i=fr(t,i),t[i]===`
|
|
16
|
+
`&&(i+=1);continue}if(i!==e.contentTo){i+=1;continue}const a=w0(t,r,i);a&&s.push(a),r=i+1,i+=1}return s}function w0(t,e,n){const s=[];let r=e;for(;r<n;){if(Ts(t,r)){r=fr(t,r),t[r]===`
|
|
17
|
+
`&&(r+=1);continue}s.push({character:t[r],index:r}),r+=1}let i=0,a=s.length;for(;i<a&&/\s/.test(s[i].character);)i+=1;for(;a>i&&/\s/.test(s[a-1].character);)a-=1;return i===a?null:{path:s.slice(i,a).map(l=>l.character).join(""),command:"",from:s[i].index,to:s[a-1].index+1}}function b0(t,e){const n=ti(t,e);if(n>=t.length||/[\\{}\[\]#~]/.test(t[n]))return null;let s=n;for(;s<t.length&&!/\s/.test(t[s])&&!Ts(t,s)&&!/[\\{}\[\]#~]/.test(t[s]);)s+=1;return s===n?null:{path:t.slice(n,s),command:"",from:n,to:s}}function Dc(t){const e=[];return g0(t,n=>{const s=n.name.toLowerCase();if(s==="input"||s==="include"||s==="subfile"){const c=Io(t,n.to,1)[0];if(c)for(const d of fo(t,c))e.push({...d,command:n.name});else if(s==="input"){const d=b0(t,n.to);d&&e.push({...d,command:n.name})}return}if(s!=="import"&&s!=="subimport"&&s!=="includefrom"&&s!=="inputfrom"&&s!=="subinputfrom"&&s!=="subincludefrom")return;const r=Io(t,n.to,2);if(r.length!==2)return;const i=fo(t,r[0])[0]?.path??"",a=fo(t,r[1])[0];if(!a)return;const l=i&&!i.endsWith("/")?"/":"";e.push({path:i+l+a.path,command:n.name,from:a.from,to:a.to,directory:i})}),e}function y0({sessions:t,status:e}){const{t:n}=Je(),[s,r]=u.useState(!1),i=Math.max(0,t.length-5),a=s&&i>0,l=a?t:t.slice(0,5);return u.useEffect(()=>{t.length<=5&&r(!1)},[t.length]),t.length<=1?null:o.jsxs("div",{className:`collaboration-presence collaboration-${e}`,children:[o.jsx("span",{className:"collaboration-status-dot","data-tooltip":n(`editor.collaboration.${e}`),"aria-label":n(`editor.collaboration.${e}`)}),o.jsxs("div",{className:"collaboration-avatars","aria-label":n("editor.collaboration.activeSessions",{count:t.length}),children:[l.map(c=>{const d=c.editing?n("editor.collaboration.editing"):n("editor.collaboration.viewing"),f=c.permission==="read"?n("common.readOnly"):n("common.readWrite"),h=n("editor.collaboration.sessionTooltip",{name:c.name,username:c.username,file:c.filePath||n("editor.collaboration.joining"),activity:d,permission:f});return o.jsxs("span",{className:`collaboration-avatar${c.editing?" editing":""}${c.local?" local":""}`,style:{"--session-color":c.color},"aria-label":h,tabIndex:0,children:[Bx(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")," · ",d," · ",f]})]})]},c.clientId)}),i>0&&o.jsx("button",{type:"button",className:"collaboration-avatar collaboration-avatar-overflow","aria-expanded":a,"aria-label":a?n("editor.collaboration.showFewerSessions"):n("editor.collaboration.showMoreSessions",{count:i}),title:a?n("editor.collaboration.showFewerSessions"):n("editor.collaboration.showMoreSessions",{count:i}),onClick:()=>r(c=>!c),children:a?"−":`+${i}`})]})]})}function x0({value:t,onChange:e}){const{t:n}=Je(),[s,r]=u.useState(!1),i=u.useRef(null),a=[{value:"editor-pdf",icon:_l},{value:"editor-only",icon:Cm},{value:"pdf-only",icon:Em}];return u.useEffect(()=>{if(!s)return;const l=d=>{i.current?.contains(d.target)||r(!1)},c=d=>{d.key==="Escape"&&r(!1)};return document.addEventListener("pointerdown",l),document.addEventListener("keydown",c),()=>{document.removeEventListener("pointerdown",l),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(l=>!l),children:[o.jsx(_l,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(rr,{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")}),a.map(l=>{const c=l.icon,d=l.value===t;return o.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":d,className:`layout-option${d?" selected":""}`,onClick:()=>{e(l.value),r(!1)},children:[o.jsx(c,{size:19}),o.jsxs("span",{children:[o.jsx("strong",{children:n(`editor.layout.${l.value}.name`)}),o.jsx("small",{children:n(`editor.layout.${l.value}.description`)})]}),d&&o.jsx($p,{size:16})]},l.value)})]})]})}function S0({site:t,project:e,activeFile:n,saveStateLabel:s,editorPreferences:r,activeSessions:i,collaborationStatus:a,reconnectCollaboration:l,protocolUpgradeRequired:c,showEditor:d,filesCollapsed:f,toggleFilesPanel:h,workspaceLayout:p,changeWorkspaceLayout:m,onBack:g,onShare:x,showCitationLibrary:j,citationLibraryOpen:C,onCitationLibrary:z,onHistory:k,onGit:y,canManageGit:P,formatting:E,readOnly:S,collaborationSynced:N,onToggleComments:V,commentsOpen:Y,unresolvedCommentCount:ie,onToggleSettings:F,settingsOpen:le,compileBusy:G,sharedCompiling:J,localCompiling:Z,cancelling:Ee,onCompile:ce,onCancelCompile:Q}){const{t:$}=Je();return o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:$("editor.backToProjects"),"aria-label":$("editor.backToProjects"),onClick:g,children:o.jsx(Up,{size:18})}),o.jsx("a",{className:"brand-link compact-brand-link",href:vs("/"),"aria-label":t.siteName,onClick:fe=>{fe.preventDefault(),g()},children:o.jsx(Tp,{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:$("editor.vimOnHint"),children:[o.jsx(xm,{size:14}),$("editor.vimOn")]}),o.jsx(y0,{sessions:i,status:a}),a==="disconnected"&&!c&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:$("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:l,children:$("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[d&&o.jsxs("button",{className:f?"":"active",onClick:h,children:[f?o.jsx(km,{size:15}):o.jsx(qc,{size:15}),$("common.files")]}),o.jsx(x0,{value:p,onChange:m}),o.jsxs("button",{onClick:x,children:[o.jsx(Mr,{size:15}),$("projectSettings.share")]}),j&&o.jsxs("button",{className:C?"active":"",onClick:z,children:[o.jsx(zp,{size:15}),$("citationLibrary.title")]}),o.jsxs("button",{type:"button",className:"snapshots-action",title:$("history.projectSnapshots"),onClick:k,children:[o.jsx(hm,{size:15}),$("history.projectSnapshotsButton")]}),o.jsxs("button",{type:"button",className:`comments-action${Y?" active":""}`,title:$("editor.commentsAll"),"aria-label":ie>0?`${$("common.comments")} (${ie})`:$("common.comments"),onClick:V,children:[o.jsx(Bp,{size:15}),o.jsx("span",{children:$("common.comments")}),ie>0&&o.jsx("sup",{className:"comments-action-count",children:ie})]}),o.jsxs("button",{className:"git-action",title:$(P?"git.title":"git.ownerOnly"),disabled:!P,onClick:y,children:[o.jsx(Wp,{size:15}),"Git"]}),o.jsxs("button",{className:le?"active":"",onClick:F,children:[o.jsx(Lm,{size:15}),$("common.settings")]}),J||Z?o.jsxs("button",{className:"compile cancel-compile",title:$("compileControls.cancel"),onClick:Q,disabled:Ee||E||S||!N,children:[Ee?o.jsx(ut,{className:"spin",size:15}):o.jsx(mn,{size:15}),$(Ee?"compileControls.cancelling":"compileControls.cancel")]}):o.jsxs("button",{className:"compile",title:$("editor.compileShortcut"),onClick:ce,disabled:G||E||S||!N,children:[G?o.jsx(ut,{className:"spin",size:15}):o.jsx(jm,{size:15}),$("editor.compile",{engine:e.engine})]})]})]})}function v0(t){return`${t.path}\0${t.line}`}function k0(t){const e=[],n=[];for(const s of t){for(;n.length&&n.at(-1).level>=s.level;)n.pop();const r=n.at(-1);r&&(e[r.index].hasChildren=!0),e.push({item:s,key:v0(s),ancestorKeys:n.map(({index:i})=>e[i].key),hasChildren:!1}),n.push({level:s.level,index:e.length-1})}return e}function C0(t,e){return t.filter(n=>!n.ancestorKeys.some(s=>e.has(s)))}const E0=new Set(["avif","bmp","gif","ico","jpeg","jpg","png","svg","webp","eps"]),j0=new Set(["latex","ltx","tex"]),D0=new Set(["aux","blg","bbl","bst","c","cc","cls","cpp","css","dtx","go","h","hpp","html","idx","ilg","ind","ins","java","js","json","jsx","lof","log","lot","lua","ltx","nav","out","php","py","r","rs","sh","snm","sql","sty","tex","toc","ts","tsx","vrb","xml","yaml","yml"]),T0=new Set(["cfg","conf","dat","env","ini","text","toml","txt"]),R0=new Set(["csv","ods","tsv","xls","xlsx"]),_0=new Set(["7z","bz2","gz","rar","tar","xz","zip"]),L0=new Set(["m4a","mp3","ogg","wav"]),A0=new Set(["avi","mkv","mov","mp4","webm"]);function N0(t){const e=t.split("/").at(-1)?.toLocaleLowerCase()??"";if(e===".latexmkrc"||e==="latexmkrc")return"latexmkrc";if(e==="makefile"||e==="dockerfile")return"code";if(e==="readme"||e.startsWith("readme."))return"markdown";const n=e.includes(".")?e.slice(e.lastIndexOf(".")+1):"";return n==="pdf"?"pdf":E0.has(n)?"image":n==="md"||n==="markdown"||n==="mdown"||n==="mkdn"?"markdown":j0.has(n)?"tex":n==="bib"||n==="bibtex"?"bib":D0.has(n)?"code":T0.has(n)?"text":R0.has(n)?"spreadsheet":_0.has(n)?"archive":L0.has(n)?"audio":A0.has(n)?"video":"file"}const O0={pdf:wm,tex:Dl,bib:Sm,latexmkrc:pm,image:mm,markdown:Uc,text:Vp,code:Dl,spreadsheet:qp,archive:go,audio:fm,video:bm,file:si};function Pd({path:t,size:e=13}){const n=N0(t);if(n==="pdf"||n==="tex")return o.jsx("img",{className:`file-type-icon file-type-icon-${n}`,src:vs(`/${n==="pdf"?"pdf-file":"tex-file"}.svg`),width:e,height:e,alt:"","aria-hidden":"true"});const s=O0[n]??ym;return o.jsx(s,{className:`file-type-icon file-type-icon-${n}`,size:e,"aria-hidden":"true"})}const Fd="application/x-texlite-project-path",Md="texlite-path:";function P0({project:t,filesPanel:e,visibleEntries:n,activeFile:s,activeMainFile:r,selectedFile:i,selectedFolder:a,expandedFolders:l,fileDragActive:c,uploadingFiles:d,uploadFeedback:f,readOnly:h,formatting:p,canFormat:m,activeFormatLease:g,collaborationSynced:x,editorFontSize:j,outline:C,sourceCursorStore:z,wordCountBusy:k,hasSelection:y,hasFormatSelection:P,uploadInput:E,setSelectedFolder:S,setExpandedFolders:N,setMoveEntry:V,setMoveName:Y,setMoveDestination:ie,setDeleteEntry:F,setFileDialogError:le,setNewFolderName:G,setNewFolderOpen:J,setNewFilePath:Z,setNewFileOpen:Ee,setQuickOpen:ce,setProjectSearchOpen:Q,setFileDragActive:$,dismissUploadFeedback:fe,setFilesCollapsed:Se,toggleFilesPanel:ve,uploadFiles:je,upload:ee,openFile:q,movePathToFolder:he,onError:we,onFormatFile:U,onFormatSelection:H,jumpToSource:Te,syncSourceToPdf:ke,onWordCount:O}){const{t:I}=Je(),[te,Ne]=u.useState(!1),[_e,Ie]=u.useState(null),[$e,se]=u.useState(null),xe=u.useRef(0),Pe=(D,ue)=>M0(D.path)!==ue&&(D.type!=="directory"||ue!==D.path&&!ue.startsWith(`${D.path}/`)),Le=()=>{Ie(null),se(null)};return o.jsx(ni,{id:"files",order:1,ref:e,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>Se(!0),onExpand:()=>Se(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${c?" drop-active":""}`,onDragEnter:D=>{if(Dn(D.dataTransfer)){D.preventDefault();return}D.dataTransfer.types.includes("Files")&&(D.preventDefault(),!h&&!d&&$(!0))},onDragOver:D=>{if(Dn(D.dataTransfer)){D.preventDefault(),D.dataTransfer.dropEffect="move";return}D.dataTransfer.types.includes("Files")&&(D.preventDefault(),D.dataTransfer.dropEffect=h||d?"none":"copy")},onDragLeave:D=>{D.currentTarget.contains(D.relatedTarget)||$(!1)},onDrop:D=>{if(Dn(D.dataTransfer)){D.preventDefault(),D.stopPropagation();return}if(D.preventDefault(),$(!1),h||d)return;const ue=Array.from(D.dataTransfer.files);if(F0(D.dataTransfer)||ue.length===0){we(I("editor.dropFoldersUnsupported"));return}je(ue)},children:[o.jsxs("div",{className:"panel-title",children:[o.jsx("button",{className:"file-size-toggle",type:"button","aria-pressed":te,title:I(te?"editor.hideFileSizes":"editor.showFileSizes"),onClick:()=>Ne(D=>!D),children:I("common.files")}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{type:"button","aria-label":I("navigation.quickOpen"),title:`${I("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>ce(!0),children:o.jsx(Hp,{size:15})}),o.jsx("button",{type:"button","aria-label":I("navigation.projectSearch"),title:`${I("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>Q(!0),children:o.jsx(Qp,{size:15})}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:d,"aria-label":I("editor.uploadAttachment"),title:I("editor.uploadTo",{folder:a||I("editor.projectRoot")}),onClick:()=>E.current?.click(),children:o.jsx(Tl,{size:15})}),o.jsx("button",{type:"button","aria-label":I("editor.newFolder"),title:I("editor.newFolder"),onClick:()=>{G(""),J(!0)},children:o.jsx(Kp,{size:15})}),o.jsx("button",{type:"button","aria-label":I("editor.newFile"),title:I("editor.newFile"),onClick:()=>{Z(a?`${a}/`:""),Ee(!0)},children:o.jsx(gm,{size:15})}),o.jsx("input",{ref:E,type:"file",multiple:!0,hidden:!0,onChange:D=>{ee(D)}})]}),o.jsx("button",{type:"button","aria-label":I("editor.collapseFiles"),title:I("editor.collapseFiles"),onClick:ve,children:o.jsx(qc,{size:15})})]})]}),f&&o.jsxs("div",{className:`file-upload-feedback ${f.kind}`,role:f.kind==="error"?"alert":"status","aria-live":f.kind==="error"?"assertive":"polite","aria-busy":f.kind==="uploading",children:[f.kind==="uploading"?o.jsx(ut,{className:"spin",size:14}):f.kind==="success"?o.jsx(bo,{size:14}):o.jsx(Nt,{size:14}),o.jsxs("span",{className:"file-upload-feedback-text",children:[f.kind==="uploading"&&I("editor.uploadingFile",{file:f.fileName,current:f.current,total:f.total}),f.kind==="success"&&I("editor.uploadSucceeded",{count:f.count}),f.kind==="error"&&f.message]}),f.kind!=="uploading"&&o.jsx("button",{type:"button",className:"file-upload-feedback-dismiss","aria-label":I("common.close"),title:I("common.close"),onClick:fe,children:o.jsx(mn,{size:13})})]}),c&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(Tl,{size:24}),o.jsx("strong",{children:I("editor.dropFiles")}),o.jsx("span",{children:I("editor.uploadTo",{folder:a||I("editor.projectRoot")})})]}),o.jsx("div",{className:`file-list${a!==null?" folder-selected":""}${$e===""?" root-drop-target":""}`,style:{fontSize:`${j}px`},onDragOver:D=>{if(!(!_e&&!Dn(D.dataTransfer))&&(D.preventDefault(),D.stopPropagation(),!!_e)){if(!Pe(_e,"")){D.dataTransfer.dropEffect="none";return}D.dataTransfer.dropEffect="move",se("")}},onDragLeave:D=>{D.currentTarget.contains(D.relatedTarget)||se(ue=>ue===""?null:ue)},onDrop:D=>{if(!_e&&!Dn(D.dataTransfer)||(D.preventDefault(),D.stopPropagation(),!_e))return;const ue=_e;Le(),Pe(ue,"")&&he(ue,"")},children:n.map(D=>{const ue=D.path.split("/").length-1,Ue=D.path.split("/").at(-1),Ye=l.has(D.path),nt=t.mainFile===D.path,pe=D.path!==t.mainFile&&!t.mainFile.startsWith(`${D.path}/`);return D.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${a===D.path?" selected":""}${$e===D.path?" move-drop-target":""}`,style:{paddingLeft:`${ue*13+5}px`},onDragOver:A=>{if(!(!_e&&!Dn(A.dataTransfer))&&(A.preventDefault(),A.stopPropagation(),!!_e)){if(!Pe(_e,D.path)){A.dataTransfer.dropEffect="none";return}A.dataTransfer.dropEffect="move",se(D.path)}},onDragLeave:A=>{A.currentTarget.contains(A.relatedTarget)||se(X=>X===D.path?null:X)},onDrop:A=>{if(!_e&&!Dn(A.dataTransfer)||(A.preventDefault(),A.stopPropagation(),!_e))return;const X=_e;Le(),Pe(X,D.path)&&he(X,D.path)},children:[o.jsxs("button",{type:"button",className:"file-entry-main",onClick:()=>{S(D.path),N(A=>{const X=new Set(A);return X.has(D.path)?X.delete(D.path):X.add(D.path),X})},children:[Ye?o.jsx(rr,{size:13}):o.jsx(Ho,{size:13}),o.jsx(Gp,{size:14}),o.jsx("span",{children:Ue})]}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"file-entry-action","data-texlite-tooltip-always":!0,title:I("editor.move"),"aria-label":I("editor.move"),onClick:()=>{V(D),Y(Ue??""),ie("")},children:o.jsx(Al,{size:13})}),pe&&o.jsx("button",{type:"button",className:"file-entry-action danger-text",title:I("editor.deletePath"),"aria-label":I("editor.deletePath"),onClick:()=>{F(D),le("")},children:o.jsx(On,{size:13})})]})]},D.path):o.jsxs("div",{className:`file-entry${a===null&&i===D.path?" active":""}${_e?.path===D.path?" move-drag-source":""}`,style:{paddingLeft:`${ue*13+18}px`},children:[o.jsxs("button",{type:"button",className:"file-entry-main",draggable:!h,onDragStart:A=>{xe.current=Date.now()+500,I0(A,D,Ie)},onDragEnd:Le,onClick:()=>{if(xe.current>Date.now()){xe.current=0;return}q(D)},children:[o.jsx(Pd,{path:D.path}),o.jsx("span",{children:Ue}),nt&&o.jsx("small",{children:I("editor.currentMainShort")})]}),te&&typeof D.size=="number"&&o.jsx("span",{className:"file-entry-size",children:U0(D.size)}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"file-entry-action","data-texlite-tooltip-always":!0,title:I("editor.move"),"aria-label":I("editor.move"),onClick:()=>{V(D),Y(Ue??""),ie("")},children:o.jsx(Al,{size:13})}),pe&&o.jsx("button",{type:"button",className:"file-entry-action danger-text",title:I("editor.deletePath"),"aria-label":I("editor.deletePath"),onClick:()=>{F(D),le("")},children:o.jsx(On,{size:13})})]})]},D.path)})}),!h&&m&&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(cm,{size:13}),I("editor.format")]}),o.jsxs("div",{className:"file-format-actions",children:[o.jsx("button",{className:P?"":"active",type:"button",title:I("editor.formatFileHint"),onMouseDown:D=>D.preventDefault(),onClick:U,disabled:p||g||!x,children:I("editor.formatFile")}),o.jsx("button",{className:P?"active":"",type:"button",title:I(P?"editor.formatSelection":"editor.formatSelectionHint"),onMouseDown:D=>D.preventDefault(),onClick:H,disabled:p||g||!x||!P,children:I("editor.formatSelected")})]})]})]}),o.jsx($0,{outline:C,activeFile:s,activeMainFile:r,sourceCursorStore:z,wordCountBusy:k,hasSelection:y,jumpToSource:Te,syncSourceToPdf:ke,onWordCount:O})]})})}function F0(t){return Array.from(t.items).some(e=>e.webkitGetAsEntry?.()?.isDirectory===!0)}function Dn(t){return Array.from(t.types).includes(Fd)?!0:Array.from(t.types).includes("text/plain")&&t.getData("text/plain").startsWith(Md)}function M0(t){const e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function I0(t,e,n){t.dataTransfer.effectAllowed="move",t.dataTransfer.setData(Fd,e.path),t.dataTransfer.setData("text/plain",`${Md}${e.path}`),n(e)}function $0({outline:t,activeFile:e,activeMainFile:n,sourceCursorStore:s,wordCountBusy:r,hasSelection:i,jumpToSource:a,syncSourceToPdf:l,onWordCount:c}){const{t:d}=Je(),f=u.useSyncExternalStore(s.subscribe,s.getOutlineLine,s.getOutlineLine),h=u.useMemo(()=>k0(t),[t]),p=u.useMemo(()=>h.filter(k=>k.hasChildren).map(k=>k.key),[h]),[m,g]=u.useState(()=>new Set);u.useEffect(()=>{const k=new Set(p);g(y=>{const P=new Set([...y].filter(E=>k.has(E)));return P.size===y.size?y:P})},[p]);const x=p.length>0&&p.every(k=>m.has(k)),j=u.useMemo(()=>C0(h,m),[h,m]),C=()=>g(k=>x?new Set([...k].filter(y=>!p.includes(y))):new Set([...k,...p])),z=k=>g(y=>{const P=new Set(y);return P.has(k)?P.delete(k):P.add(k),P});return o.jsxs("section",{className:"outline-panel",children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("button",{className:"outline-heading",type:"button","aria-expanded":!x,title:d(x?"editor.expandOutline":"editor.collapseOutline"),onClick:C,disabled:p.length===0,children:[o.jsx(Jp,{size:14}),d("common.outline")]}),o.jsxs("span",{className:"word-count-actions",role:"group","aria-label":d("editor.wordCountTitle"),children:[o.jsxs("button",{type:"button",title:d("editor.wordCountFullHint"),onClick:()=>c("full"),disabled:r||!n,children:[r?o.jsx(ut,{className:"spin",size:12}):o.jsx(Ll,{size:12}),d("editor.wordCountFull")]}),o.jsxs("button",{type:"button",title:d("editor.wordCountSelectionHint"),onClick:()=>c("selection"),disabled:r||!i,children:[r?o.jsx(ut,{className:"spin",size:12}):o.jsx(Ll,{size:12}),d("editor.wordCountSelection")]})]})]}),o.jsxs("div",{className:"outline",children:[j.map(k=>{const{item:y}=k,P=m.has(k.key),E=e===y.path&&f===y.line,S=y.path===n||y.path===e;return o.jsxs("div",{className:`outline-row${E?" current":""}`,children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${y.level*12}px`}}),k.hasChildren?o.jsx("button",{className:"outline-toggle",type:"button","aria-label":d(P?"editor.expandOutlineItem":"editor.collapseOutlineItem",{title:y.title}),"aria-expanded":!P,onClick:()=>z(k.key),children:P?o.jsx(Ho,{size:13}):o.jsx(rr,{size:13})}):o.jsx("span",{className:"outline-toggle-spacer","aria-hidden":!0}),o.jsxs("button",{className:"outline-item",type:"button",onClick:()=>{a(y.path,y.line,1),l(y.path,y.line,1)},children:[o.jsx("small",{children:S?y.line:y.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:y.title})]})]},k.key)}),t.length===0&&o.jsx("p",{className:"muted padded",children:d("editor.noOutline")})]})]})}function U0(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 z0=u.lazy(()=>_t(()=>import("./LatexEditor-CssVgypt.js"),__vite__mapDeps([11,2,12,1,3,4,5,6,7,8,9]),import.meta.url).then(t=>({default:t.LatexEditor})));function B0({project:t,activeFile:e,openTabs:n,content:s,loadedFile:r,readOnly:i,comments:a,focusComment:l,editorPreferences:c,completionIndex:d,nativeSpellCheck:f,spellCheckIssues:h,spellCheckJump:p,sourceJump:m,collaborativeText:g,collaborationAwareness:x,undoManager:j,editorNotice:C,activateTab:z,closeTab:k,handleTabKeyDown:y,updateEditorContent:P,setSelection:E,onAddComment:S,onSelectionHistory:N,onCommentClick:V,onSpellCheckReplace:Y,onReferenceNavigate:ie,onCursor:F}){const{t:le}=Je(),G=dg(a,e),J=fg(l,e,r);return o.jsx(ni,{id:"source",order:2,defaultSize:42,minSize:22,children:o.jsxs("main",{className:"source-panel",children:[c.openFilesInTabs&&n.length>0&&o.jsx("div",{className:"editor-tabs-bar",role:"tablist","aria-label":le("editor.openFiles"),children:o.jsx("div",{className:"editor-tabs-scroll",children:n.map((Z,Ee)=>{const ce=Z===e,Q=Z===t.mainFile,$=Z.split("/").at(-1)||Z;return o.jsxs("div",{className:`editor-tab-item${ce?" active":""}`,role:"presentation",children:[o.jsxs("button",{id:`editor-tab-${encodeURIComponent(Z)}`,type:"button",role:"tab","aria-selected":ce,"aria-controls":"editor-source-content",tabIndex:ce?0:-1,className:`editor-tab${ce?" active":""}${Q?" main-tab":""}`,onClick:()=>z(Z),onKeyDown:fe=>y(fe,Ee),title:Z,children:[o.jsx("span",{className:"editor-tab-icon",children:Q?o.jsx(Uc,{size:13}):o.jsx(si,{size:13})}),o.jsx("span",{className:"editor-tab-title",children:$}),Q&&o.jsx("small",{className:"editor-tab-badge",children:le("editor.currentMainShort")})]}),o.jsx("button",{type:"button",className:"editor-tab-close",title:le("common.close"),"aria-label":`${le("common.close")} ${$}`,onClick:()=>k(Z),children:o.jsx(mn,{size:12})})]},Z)})})}),o.jsxs("div",{id:"editor-source-content",className:"editor-content-container",children:[o.jsx(u.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(ut,{className:"spin",size:22}),o.jsx("span",{children:le("common.loading")})]}),children:o.jsx(z0,{value:s,filePath:e,readOnly:i,comments:G,focusComment:J,preferences:c,nativeSpellCheck:f,completionIndex:d,spellCheckIssues:h,spellCheckJump:p,jumpTo:r===e&&m?.path===e?m:null,searchRequest:0,collaboration:g?{text:g,awareness:x,undoManager:i?void 0:j}:void 0,onChange:P,onSelection:E,onAddComment:S,onSelectionHistory:N,onCommentClick:V,onSpellCheckReplace:Y,onReferenceNavigate:ie,onCursor:F},e)}),C&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:C})]})]})})}function Tc({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=Je(),a=s==="error"?Ko:Nt;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((l,c)=>{const d=V0(l.file,e),f=!!(d&&l.line);return o.jsxs("button",{type:"button",disabled:!f,className:"compile-diagnostic-row",onClick:()=>{d&&l.line&&r(d,l.line,l.column??1)},children:[o.jsx(a,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:l.message}),o.jsxs("small",{children:[l.phase,d?` · ${d}${l.line?`:${l.line}`:""}`:l.line?` · ${i("editor.lineNumber",{line:l.line})}`:""]})]})]},`${l.phase}-${l.file??""}-${l.line??0}-${c}`)})}):o.jsxs("div",{className:`compile-empty compile-${s}`,children:[o.jsx(a,{size:26}),o.jsx("span",{children:n})]})}function ho({lines:t,empty:e,tone:n="log"}){const s=n==="error"?Ko:n==="warning"?Nt:wo;return t.length?o.jsx("pre",{className:`compile-output compile-${n}`,children:t.join(`
|
|
18
|
+
`)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function W0({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:a}=Je(),l=c=>vs(`/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?a("editor.viewArtifact"):a("editor.downloadToView"),onClick:()=>i(c),children:[o.jsx(Pd,{path:c.path,size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:c.path}),o.jsx("small",{children:H0(c.size)})]})]}),o.jsx("a",{href:l(c.path),title:a("editor.downloadArtifact"),"aria-label":a("editor.downloadArtifact"),children:o.jsx(Ir,{size:14})})]},c.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(ut,{className:"spin",size:24}),o.jsx("span",{children:a("common.loading")})]}):s?o.jsxs(o.Fragment,{children:[o.jsxs("header",{children:[o.jsx("strong",{children:s.path}),o.jsxs("a",{href:l(s.path),children:[o.jsx(Ir,{size:13}),a("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(si,{size:24}),o.jsx("span",{children:a("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Wc,{size:26}),o.jsx("span",{children:a("editor.noArtifacts")})]})}function q0({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=Je();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(Nt,{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(yo,{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(ut,{className:"spin",size:14}):o.jsx(yo,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(On,{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(ut,{className:"spin",size:14}):o.jsx(On,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function V0(t,e){if(!t)return null;const n=e.filter(l=>l.type==="file").map(l=>l.path),s=t.replaceAll("\\","/").replace(/^\.\//,"");if(n.includes(s))return s;const r=n.filter(l=>s.endsWith(`/${l}`));if(r.length===1)return r[0];const i=s.split("/").at(-1),a=n.filter(l=>l.split("/").at(-1)===i);return a.length===1?a[0]:null}function H0(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const K0=u.lazy(()=>Mc().then(t=>({default:t.PdfPreview})));function G0({projectId:t,activeMainFile:e,previewTab:n,diagnosticTab:s,pdfUrl:r,pdfLoadingMode:i,pdfLoading:a,pdfCompiledAt:l,pdfSizeBytes:c,pdfCompiledLabel:d,pdfTargetLabel:f,pdfDownloadUrl:h,pdfTarget:p,pdfViewport:m,activeFile:g,compileBusy:x,compileLog:j,compileDiagnostics:C,compileMessages:z,artifacts:k,artifactPreview:y,artifactLoading:P,cleaning:E,readOnly:S,collaborationSynced:N,workspaceLayout:V,showSyncResize:Y,diagnosticCount:ie,selectPreviewTab:F,changeWorkspaceLayout:le,onSetPdfViewport:G,onResetPdfViewport:J,syncVisiblePdfToSource:Z,syncCurrentSourceToPdf:Ee,syncPdfToSource:ce,canSyncWithPdf:Q,canSyncPdfToSource:$,files:fe,jumpToSource:Se,onSetCleanMode:ve,viewArtifact:je}){const{t:ee}=Je(),[q,he]=u.useState(""),we=u.useRef(""),U=O=>{we.current!==O&&(we.current=O,he(O),J())},H=$&&!!r&&q===r,ke=[c==null?"":J0(c),d?ee("editor.pdfUpdatedAt",{time:d}):""].filter(Boolean).join(" · ");return o.jsxs(o.Fragment,{children:[Y&&o.jsxs(Vo,{className:"resize-handle sync-resize-handle",children:[o.jsx(Bc,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:O=>O.stopPropagation(),children:[o.jsx("button",{disabled:!r||!m||!H,title:ee($?H?"editor.showInSource":"editor.syncTexWaitingForPdf":"editor.syncTexOnlyForMain"),"aria-label":ee("editor.showInSource"),onClick:()=>{H&&Z()},children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!g||!r||!Q,title:ee(Q?"editor.showInPdf":"editor.syncTexOnlyForMain"),"aria-label":ee("editor.showInPdf"),onClick:()=>{!g||!r||!Q||Ee()},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),o.jsx(ni,{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":ee("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":n==="pdf",className:`pdf-tab${n==="pdf"?" active":""}`,onClick:()=>F("pdf"),title:l?ee("editor.pdfCompiledAtFor",{file:e,time:new Date(l).toLocaleString(Us.resolvedLanguage)}):ee("editor.currentMainDocument",{path:e}),children:[o.jsx("img",{className:"pdf-tab-icon",src:vs("/pdf-download.svg"),alt:"","aria-hidden":"true"}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",f,ke&&o.jsx("small",{children:ke})]})]}),o.jsxs("button",{role:"tab","aria-selected":n==="diagnostics",className:`diagnostics-tab${n==="diagnostics"?" active":""}`,onClick:()=>F("diagnostics"),children:[o.jsx(wo,{size:14}),ee("editor.outputTabs"),o.jsx("span",{children:ie})]})]}),h&&o.jsxs("a",{className:"pdf-download-top",href:h,download:!0,title:ee("editor.downloadPdf"),"aria-label":ee("editor.downloadPdf"),children:[o.jsx(Ir,{size:15}),o.jsx("span",{children:ee("editor.downloadPdf")})]})]}),n==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":ee("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":s==="log",className:s==="log"?"active":"",onClick:()=>F("log"),children:[o.jsx(wo,{size:13}),ee("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":s==="warnings",className:s==="warnings"?"active":"",onClick:()=>F("warnings"),children:[o.jsx(Nt,{size:13}),ee("editor.warnings"),o.jsx("span",{children:z.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="errors",className:s==="errors"?"active":"",onClick:()=>F("errors"),children:[o.jsx(Ko,{size:13}),ee("editor.errors"),o.jsx("span",{children:z.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="artifacts",className:s==="artifacts"?"active":"",onClick:()=>F("artifacts"),children:[o.jsx(Wc,{size:13}),ee("editor.artifacts"),o.jsx("span",{children:k.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="clean",className:s==="clean"?"active":"",onClick:()=>F("clean"),children:[o.jsx(yo,{size:13}),ee("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${n} ${n==="diagnostics"?`preview-${s}`:""}`,children:[n==="pdf"&&(r?o.jsx(u.Suspense,{fallback:o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(ut,{className:"spin",size:24}),o.jsx("span",{children:ee("editor.loadingPdf")})]}),children:o.jsx(K0,{url:r,loadingMode:i,target:p,compiling:x,onDisplayedUrlChange:U,onViewportLocation:(O,I,te)=>{we.current===r&&G({page:O,x:I,y:te})},onDoubleClickLocation:(O,I,te)=>{we.current!==r||!H||(G({page:O,x:I,y:te}),ce(O,I,te))}})}):a?o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(ut,{className:"spin",size:24}),o.jsx("span",{children:ee("editor.loadingPdf")})]}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(si,{size:28}),o.jsx("strong",{children:ee("editor.preview")}),o.jsx("span",{children:ee("editor.previewHint")})]})),n==="diagnostics"&&s==="log"&&o.jsx(ho,{lines:j?j.split(`
|
|
19
|
+
`):[],empty:ee(x?"editor.compiling":"editor.noLog")}),n==="diagnostics"&&s==="warnings"&&(C?o.jsx(Tc,{tone:"warning",diagnostics:C.warnings,files:fe,empty:ee("editor.noWarnings"),onJump:(O,I,te)=>{V==="pdf-only"&&le("editor-pdf"),Se(O,I,te)}}):o.jsx(ho,{tone:"warning",lines:z.warnings,empty:ee("editor.noWarnings")})),n==="diagnostics"&&s==="errors"&&(C?o.jsx(Tc,{tone:"error",diagnostics:C.errors,files:fe,empty:ee("editor.noErrors"),onJump:(O,I,te)=>{V==="pdf-only"&&le("editor-pdf"),Se(O,I,te)}}):o.jsx(ho,{tone:"error",lines:z.errors,empty:ee("editor.noErrors")})),n==="diagnostics"&&s==="artifacts"&&o.jsx(W0,{projectId:t,mainFile:e,artifacts:k,preview:y,loading:P,onView:O=>{je(O)}}),n==="diagnostics"&&s==="clean"&&o.jsx(q0,{mainFile:e,disabled:S||!N||x,cleaning:E,onCleanCache:()=>ve("cache"),onCleanArtifacts:()=>ve("artifacts")})]})]})})]})}function J0(t){return!Number.isFinite(t)||t<0?"":t<1024?`${Math.round(t)} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function Rc({kind:t,onEdit:e,onDelete:n,disabled:s=!1}){const{t:r}=Je(),i=u.useRef(!1);return o.jsx("span",{className:"comment-actions-menu",onClick:a=>a.stopPropagation(),children:o.jsxs(em,{modal:!1,children:[o.jsx(tm,{asChild:!0,children:o.jsx("button",{type:"button",disabled:s,className:"comment-actions-menu-trigger","aria-label":r(t==="comment"?"editor.commentActions":"editor.replyActions"),children:o.jsx(Yp,{size:16,"aria-hidden":!0})})}),o.jsx(nm,{children:o.jsxs(sm,{className:"comment-actions-menu-content",align:"end",sideOffset:4,collisionPadding:8,onCloseAutoFocus:a=>{i.current&&a.preventDefault(),i.current=!1},children:[o.jsxs(Rl,{onSelect:()=>{i.current=!0,e()},children:[o.jsx(Xp,{size:13,"aria-hidden":!0}),r(t==="comment"?"editor.editComment":"editor.editReply")]}),o.jsxs(Rl,{className:"danger-text",onSelect:()=>{i.current=!0,n()},children:[o.jsx(On,{size:13,"aria-hidden":!0}),r(t==="comment"?"editor.deleteComment":"editor.deleteReply")]})]})})]})})}function Y0(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 Id({projectId:t,value:e,onChange:n,onKeyDown:s,onFocus:r,...i}){const{t:a}=Je(),l=u.useRef(null),[c,d]=u.useState(null),[f,h]=u.useState(!1),[p,m]=u.useState(null),[g,x]=u.useState(0),j=u.useMemo(()=>{if(!p||!c)return[];const E=p.query.toLocaleLowerCase();return(E?c.filter(N=>N.username.toLocaleLowerCase().includes(E)||N.displayName.toLocaleLowerCase().includes(E)):c).slice(0,8)},[c,p]),C=!!(p&&j.length),z=async()=>{if(!(c||f)){h(!0);try{const E=await be(`/api/projects/${t}/mention-candidates`);d(E.users)}catch{d([])}finally{h(!1)}}},k=(E,S)=>{const N=Y0(E,S);m(N),x(0),N&&z()},y=E=>{if(!p)return;const S=`@${E.username} `,N=`${e.slice(0,p.start)}${S}${e.slice(p.end)}`,V=p.start+S.length;n(N),m(null),x(0),window.requestAnimationFrame(()=>{l.current?.focus(),l.current?.setSelectionRange(V,V)})},P=E=>{if(!E.nativeEvent.isComposing&&C){if(E.key==="ArrowDown"){E.preventDefault(),x(S=>(S+1)%j.length);return}if(E.key==="ArrowUp"){E.preventDefault(),x(S=>(S-1+j.length)%j.length);return}if(E.key==="Enter"&&!E.ctrlKey&&!E.metaKey&&!E.shiftKey){E.preventDefault(),y(j[g]??j[0]);return}if(E.key==="Escape"){m(null);return}}s?.(E)};return o.jsxs("span",{className:"mention-textarea",children:[o.jsx("textarea",{...i,ref:l,value:e,onFocus:E=>{r?.(E),k(e,E.currentTarget.selectionStart??e.length)},onClick:E=>k(e,E.currentTarget.selectionStart??e.length),onChange:E=>{const S=E.currentTarget.value;n(S),k(S,E.currentTarget.selectionStart??S.length)},onKeyDown:P}),C&&o.jsx("span",{className:"mention-menu",role:"listbox","aria-label":a("editor.mentionUsers"),children:j.map((E,S)=>o.jsxs("button",{type:"button",role:"option","aria-selected":S===g,className:S===g?"active":"",onMouseDown:N=>N.preventDefault(),onClick:()=>y(E),children:[o.jsx(Vs,{"aria-hidden":!0,size:13}),o.jsxs("span",{children:[o.jsx("strong",{children:E.displayName}),o.jsxs("small",{children:["(",E.username,")"]})]})]},E.id))})]})}function X0({projectId:t,value:e,onChange:n,onSubmit:s,onCancel:r,pending:i=!1,error:a="",label:l,editing:c=!1,disabled:d=!1,autoFocus:f=!0}){const{t:h}=Je(),p=u.useId(),m=i||d,g=x=>{x?.preventDefault(),!(m||!e.trim())&&s()};return o.jsxs("form",{className:`comment-reply-form${c?" comment-edit-form":""}`,"aria-busy":i,onSubmit:x=>{g(x)},onClick:x=>x.stopPropagation(),children:[o.jsx(Id,{projectId:t,autoFocus:f,rows:c?4:3,value:e,onChange:n,disabled:m,"aria-label":l,"aria-invalid":!!a,"aria-describedby":a?p:void 0,placeholder:c?void 0:h("editor.replyPlaceholder"),onKeyDown:x=>{!(x.ctrlKey||x.metaKey)||x.key!=="Enter"||x.nativeEvent.isComposing||(x.preventDefault(),x.stopPropagation(),g())}}),a&&o.jsx("p",{id:p,className:"comment-form-error",role:"alert",children:a}),o.jsxs("div",{children:[o.jsx("button",{type:"button",disabled:m,onClick:r,children:h("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:m||!e.trim(),children:[i?o.jsx(ut,{className:"spin","aria-hidden":!0,size:13}):c?o.jsx(Rm,{"aria-hidden":!0,size:13}):o.jsx(_m,{"aria-hidden":!0,size:13}),h(i?c?"editor.commentSaving":"editor.commentSending":c?"editor.saveChanges":"editor.sendReply")]})]})]})}const _c=2;function Z0(t,e={}){const n=t.slice(0,Math.max(0,t.length-_c)),s=!!(e.activeDraft||e.targetReplyId&&t.some(a=>a.id===e.targetReplyId)||n.some(a=>e.unreadReplyMentionIds?.has(a.id)||e.highlightReplyParticipants&&e.selectedParticipantIds?.has(a.authorId))),r=s||(e.expansion??!!e.current),i=r?0:n.length;return{replies:i?t.slice(-_c):t,hiddenCount:i,expanded:r,canToggle:n.length>0&&!s}}function Lc(t){const e=/(^|\s)(@[\p{L}\p{N}_.-]+)/gu,n=[];let s=0;for(const r of t.matchAll(e)){const i=r.index??0,a=r[1],l=r[2],c=i+a.length;c>s&&n.push(t.slice(s,c)),n.push(o.jsx("span",{className:"comment-inline-mention",children:l},`${c}:${l}`)),s=c+l.length}return n.length?(s<t.length&&n.push(t.slice(s)),n):t}function Q0({projectId:t,comment:e,draftStore:n,currentUserId:s,unreadCommentMentionId:r,unreadReplyMentionIds:i,highlightedComment:a,highlightedReplyId:l,currentComment:c,showFilePath:d,onMarkMentionRead:f,onFocus:h,onActivate:p,onToggle:m,onReply:g,onEdit:x,onDelete:j,onEditReply:C,onDeleteReply:z,selectedParticipantIds:k,highlightReplyParticipants:y,replyExpansion:P,onReplyExpansionChange:E}){const{t:S}=Je(),[N,V]=u.useState(!1),Y=u.useCallback(U=>n.subscribe(e.id,U),[n,e.id]),ie=u.useCallback(()=>n.getThread(e.id),[n,e.id]),F=u.useSyncExternalStore(Y,ie,ie),le=F.reply,G=F["edit-comment"],J=u.useId(),Z=Z0(e.replies,{expansion:P,current:c,targetReplyId:l,unreadReplyMentionIds:i,selectedParticipantIds:k,highlightReplyParticipants:y,activeDraft:!!(le?.open||le?.pending||e.authorId===s&&G?.open||e.replies.some(U=>U.authorId===s&&F[`edit-reply:${U.id}`]?.open))}),Ee=n.isPending(e.id),[ce,Q]=u.useState(null),[$,fe]=u.useState(!1),[Se,ve]=u.useState(null),je=(U,H="")=>{p(),E(!0),Q(U),n.open(e.id,U,H)},ee=(U,H,Te)=>{const ke=F[U];return ke?.open?o.jsx(X0,{projectId:t,editing:U!=="reply",label:H,value:ke.content,pending:ke.pending,error:ke.error,disabled:Ee||N,autoFocus:ce===U,onChange:O=>n.change(e.id,U,O),onSubmit:()=>n.submit(e.id,U,Te,S("editor.commentSubmitFailed")),onCancel:()=>n.discard(e.id,U)},U):null},q=e.authorUsername,he=U=>new Date(U).toLocaleString(Us.resolvedLanguage),we=async(U,H)=>{H.stopPropagation(),E(!0),await f(U)};return o.jsxs(o.Fragment,{children:[o.jsxs("article",{"data-comment-id":e.id,className:`comment-thread${e.resolved?" resolved":""}${e.orphaned?" orphaned":""}${a?" mention-target":""}${c?" review-current":""}`,onFocusCapture:p,onClick:()=>{window.getSelection()?.toString()||h()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:`comment-author${k?.has(e.authorId)?" participant-match":""}`,children:[o.jsx("strong",{children:e.authorDisplayName??q??S("editor.deletedUser")}),q&&o.jsxs("small",{children:["@",q]})]}),o.jsxs("span",{className:"comment-header-actions",children:[o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toISOString(),children:he(e.createdAt)}),e.editedAt&&o.jsx("small",{children:S("editor.editedAt",{time:he(e.editedAt)})})]}),e.authorId===s&&!G?.open&&o.jsx(Rc,{kind:"comment",disabled:Ee||N,onEdit:()=>je("edit-comment",e.content),onDelete:()=>fe(!0)})]})]}),o.jsx("div",{className:"comment-location",children:e.orphaned?S("editor.orphaned"):d?S("editor.commentLocation",{path:e.filePath,line:e.startLine}):S("editor.line",{line:e.startLine})}),e.selectedText&&o.jsx("blockquote",{className:"comment-selected-text",children:e.selectedText}),G?.open&&e.authorId===s?ee("edit-comment",S("editor.editComment"),x):o.jsx("p",{className:"comment-content",children:Lc(e.content)}),r&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(Vs,{"aria-hidden":!0,size:12}),S("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:U=>{we(r,U)},children:S("editor.markMentionRead")})]}),e.replies.length>0&&o.jsxs("div",{className:"comment-replies",children:[Z.canToggle&&o.jsxs("button",{type:"button",className:"comment-replies-toggle","aria-expanded":Z.expanded,"aria-controls":J,onClick:U=>{U.stopPropagation(),E(!Z.expanded)},children:[Z.expanded?o.jsx(Ip,{size:13,"aria-hidden":!0}):o.jsx(rr,{size:13,"aria-hidden":!0}),Z.expanded?S("editor.hideEarlierReplies"):S("editor.showEarlierReplies",{count:Z.hiddenCount})]}),o.jsx("div",{className:"comment-replies-list",id:J,children:Z.replies.map(U=>{const H=i?.get(U.id),Te=`edit-reply:${U.id}`,ke=F[Te]?.open&&U.authorId===s;return o.jsxs("div",{"data-comment-reply-id":U.id,className:`comment-reply${l===U.id?" mention-target":""}`,children:[o.jsxs("header",{children:[o.jsxs("span",{className:`comment-author${y&&k?.has(U.authorId)?" participant-match":""}`,children:[o.jsx("strong",{children:U.authorDisplayName??U.authorUsername??S("editor.deletedUser")}),U.authorUsername&&o.jsxs("small",{children:["@",U.authorUsername]})]}),o.jsxs("span",{className:"comment-header-actions",children:[o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:U.createdAt,title:new Date(U.createdAt).toISOString(),children:he(U.createdAt)}),U.editedAt&&o.jsx("small",{children:S("editor.editedAt",{time:he(U.editedAt)})})]}),U.authorId===s&&!ke&&o.jsx(Rc,{kind:"reply",disabled:Ee||N,onEdit:()=>je(Te,U.content),onDelete:()=>ve(U.id)})]})]}),ke?ee(Te,S("editor.editReply"),O=>C(U.id,O)):o.jsx("p",{className:"comment-content",children:Lc(U.content)}),H&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(Vs,{"aria-hidden":!0,size:12}),S("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:O=>{we(H,O)},children:S("editor.markMentionRead")})]})]},U.id)})})]}),e.resolved&&e.resolvedAt&&o.jsxs("div",{className:"comment-resolution",children:[o.jsx(bo,{size:12,"aria-hidden":!0}),o.jsxs("span",{children:[o.jsx(Op,{i18nKey:"editor.resolvedBy",values:{user:e.resolvedByDisplayName??e.resolvedByUsername??S("editor.deletedUser")},components:{user:o.jsx("strong",{className:"comment-resolution-user"})}}),e.resolvedByUsername&&o.jsxs("small",{className:"comment-resolution-user",children:[" @",e.resolvedByUsername]})," · ",o.jsx("time",{dateTime:e.resolvedAt,children:he(e.resolvedAt)})]})]}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",disabled:N||Ee,"aria-busy":N,onClick:U=>{U.stopPropagation(),!N&&(V(!0),m().finally(()=>V(!1)))},children:[e.resolved?o.jsx(Tm,{size:13}):o.jsx(bo,{size:13}),e.resolved?S("editor.reopen"):S("editor.resolve")]}),o.jsxs("button",{className:"reply-action",disabled:Ee||N,onClick:U=>{U.stopPropagation(),le?.open?n.hide(e.id,"reply"):je("reply")},children:[o.jsx(Dm,{size:13}),S(le?.content&&!le.open?"editor.resumeReply":"editor.reply")]})]}),ee("reply",S("editor.reply"),g)]}),o.jsx(Ws,{open:$,title:S("editor.deleteCommentTitle"),description:S("editor.deleteCommentDescription",{count:e.replies.length}),confirmLabel:S("common.delete"),danger:!0,onCancel:()=>fe(!1),onConfirm:()=>{j().then(U=>{U&&fe(!1)})}}),o.jsx(Ws,{open:!!Se,title:S("editor.deleteReplyTitle"),description:S("editor.deleteReplyDescription"),confirmLabel:S("common.delete"),danger:!0,onCancel:()=>ve(null),onConfirm:()=>{Se&&z(Se).then(U=>{U&&ve(null)})}})]})}function eS({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=Je(),[i,a]=u.useState([]),[l,c]=u.useState([]),[d,f]=u.useState(""),[h,p]=u.useState("read"),[m,g]=u.useState(null),[x,j]=u.useState(""),C=n.permission==="owner",z=async()=>{try{const[S,N]=await Promise.all([be(`/api/projects/${s}/members`),be("/api/users")]);a(S.members),c(N.users.filter(V=>V.id!==n.ownerId))}catch(S){j(ye(S))}};u.useEffect(()=>{t&&z()},[t,s]);const k=async()=>{if(d)try{await be(`/api/projects/${s}/members/${d}`,{method:"PUT",body:JSON.stringify({permission:h})}),f(""),p("read"),await z()}catch(S){j(ye(S))}},y=async(S,N)=>{try{await be(`/api/projects/${s}/members/${S.id}`,{method:"PUT",body:JSON.stringify({permission:N})}),await z()}catch(V){j(ye(V))}},P=async()=>{if(m)try{await be(`/api/projects/${s}/members/${m.id}`,{method:"DELETE"}),g(null),await z()}catch(S){j(ye(S))}},E=l.filter(S=>!i.some(N=>N.id===S.id));return o.jsxs(o.Fragment,{children:[o.jsx(dn,{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:[x&&o.jsx("p",{className:"error",children:x}),o.jsxs("div",{className:"share-owner",children:[o.jsx(Mr,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),C&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:d,onChange:S=>f(S.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),E.map(S=>o.jsx("option",{value:S.id,children:S.displayName??S.username},S.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:h,onChange:S=>p(S.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:!d,onClick:()=>{k()},children:[o.jsx(rm,{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(S=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(S.displayName??S.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:S.displayName??S.username}),o.jsxs("small",{children:["@",S.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!C,value:S.permission,onChange:N=>{y(S,N.target.value)},children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]}),C&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(S),children:o.jsx(On,{size:15})})]})]},S.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(Mr,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(Ws,{open:!!m,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:m?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{P()}})]})}const tS=u.lazy(()=>_t(()=>import("./CitationLibraryDialog-CU7Q7r0Z.js"),__vite__mapDeps([13,2,1,3,4,14,5,6,15,16,7]),import.meta.url).then(t=>({default:t.CitationLibraryDialog}))),nS=u.lazy(()=>_t(()=>import("./GitDialog-CZpnKw-J.js"),__vite__mapDeps([17,2,1,3,6,18,4,19,20,15,21,5,7,8,9]),import.meta.url).then(t=>({default:t.GitDialog}))),sS=u.lazy(()=>_t(()=>import("./HistoryDialog-DWYErBwj.js"),__vite__mapDeps([22,2,1,3,23,24,6,20,15,21,4,5,7,8,9]),import.meta.url).then(t=>({default:t.HistoryDialog}))),rS=u.lazy(()=>_t(()=>import("./SelectionHistoryDialog-CR5c3I8k.js"),__vite__mapDeps([25,2,1,3,23,4,5,6,7,8,9]),import.meta.url).then(t=>({default:t.SelectionHistoryDialog}))),iS=u.lazy(()=>_t(()=>import("./ProjectNavigationDialogs-BZxI3PJO.js"),__vite__mapDeps([26,2,1,3,7,6,5]),import.meta.url).then(t=>({default:t.ProjectSearchDialog}))),oS=u.lazy(()=>_t(()=>import("./ProjectNavigationDialogs-BZxI3PJO.js"),__vite__mapDeps([26,2,1,3,7,6,5]),import.meta.url).then(t=>({default:t.QuickOpenDialog})));function aS({user:t,project:e,projectId:n,activeFile:s,content:r,maxCitationBibtexBytes:i,files:a,directoryEntries:l,readOnly:c,workspaceLayout:d,changeWorkspaceLayout:f,resourcePreview:h,resourcePreviewLoading:p,setResourcePreview:m,setResourcePreviewLoading:g,uploadConflict:x,setUploadConflict:j,dismissUploadFeedback:C,uploadFiles:z,cleanMode:k,setCleanMode:y,cleanCompile:P,newFileOpen:E,setNewFileOpen:S,newFilePath:N,setNewFilePath:V,newFolderOpen:Y,setNewFolderOpen:ie,newFolderName:F,setNewFolderName:le,selectedFolder:G,fileDialogError:J,setFileDialogError:Z,createFile:Ee,createFolder:ce,moveEntry:Q,setMoveEntry:$,moveName:fe,setMoveName:Se,moveDestination:ve,setMoveDestination:je,movePath:ee,deleteEntry:q,setDeleteEntry:he,deleteActiveSessions:we,removePath:U,commentOpen:H,closeComment:Te,commentSelection:ke,commentText:O,setCommentText:I,commentSubmitting:te,commentError:Ne,addComment:_e,cancelComment:Ie,commentDraftRestored:$e,commentDraftCanRetarget:se,useCurrentCommentSelection:xe,shareOpen:Pe,setShareOpen:Le,citationLibraryOpen:D,setCitationLibraryOpen:ue,insertCitationAtCursor:Ue,quickOpen:Ye,setQuickOpen:nt,projectSearchOpen:pe,setProjectSearchOpen:A,openFile:X,jumpToSource:Oe,selectionHistoryTarget:ze,closeSelectionHistory:M,historyOpen:oe,setHistoryOpen:Re,gitOpen:re,setGitOpen:vt,save:B,permissionDowngrade:v,permissionDowngradeBusy:_,dismissPermissionDowngrade:K,discardPermissionDraft:dt}){const{t:L}=Je();return o.jsxs(o.Fragment,{children:[v&&o.jsx(dn,{open:!0,title:L("editor.collaboration.permissionDowngradeTitle"),description:v.localDraftReady&&v.otherTabDraft?L("editor.collaboration.permissionDowngradeMultipleDrafts"):v.otherTabDraft?L("editor.collaboration.permissionDowngradeOtherTab"):v.localDraftReady?L("editor.collaboration.permissionDowngradeDescription",{previous:L("common.readWrite")}):L("editor.collaboration.permissionDowngradeNoDraft"),onOpenChange:W=>{!W&&!_&&K()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:_,onClick:K,children:v.localDraftReady?L("editor.collaboration.permissionDowngradeKeep"):L("common.close")}),!v.otherTabDraft&&o.jsxs("button",{type:"button",className:"danger",disabled:_,onClick:()=>{dt()},children:[_?o.jsx(ut,{className:"spin",size:14}):v.localDraftReady?o.jsx(On,{size:14}):o.jsx(lm,{size:14}),v.localDraftReady?L("editor.collaboration.permissionDowngradeDiscard"):L("editor.collaboration.permissionDowngradeReload")]})]}),children:o.jsx("div",{})}),o.jsxs(dn,{open:!!h,extraWide:h?.kind==="image"||h?.kind==="pdf"||h?.kind==="text",title:h?.path??"",description:h?.kind==="large"?L("editor.resourceTooLarge",{size:lS(h.size),limit:`${Fo/1024/1024} MB`}):L(`editor.resourcePreview.${h?.kind??"text"}`),onOpenChange:W=>{W||(m(null),g(!1))},footer:h&&o.jsxs("a",{className:"primary resource-download",href:`${h.url}&download=1`,download:!0,children:[o.jsx(Ir,{size:14}),L("editor.downloadResource")]}),children:[h?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(go,{size:34}),o.jsx("strong",{children:L("editor.resourceTooLargeTitle")}),o.jsx("span",{children:L("editor.resourceTooLargeDescription")})]}),h?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(go,{size:34}),o.jsx("strong",{children:L("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:L("editor.resourceUnsupportedDescription")})]}),h?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:h.url,alt:h.path})}),h?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:h.url,title:h.path}),h?.kind==="text"&&(p?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(ut,{className:"spin",size:24}),o.jsx("span",{children:L("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:h.content}))]}),o.jsx(Ws,{open:!!x,title:L("editor.uploadOverwriteTitle"),description:L("editor.uploadOverwriteDescription",{files:x?.collisions.join(", ")??""}),confirmLabel:L("editor.uploadOverwrite"),danger:!0,onCancel:()=>{j(null),C()},onConfirm:()=>{const W=x;j(null),W&&z(W.files,new Set(W.collisions),W.directory)}}),o.jsx(Ws,{open:!!k,title:L(k==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:L(k==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:L("editor.cleanConfirm"),danger:k==="artifacts",onCancel:()=>y(null),onConfirm:()=>{const W=k;y(null),W&&P(W)}}),o.jsx(dn,{open:E,title:L("editor.newFile"),description:L("editor.newFileDescription"),onOpenChange:W=>{S(W),W||Z("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>S(!1),children:L("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{Ee()},children:L("common.create")})]}),children:o.jsxs(o.Fragment,{children:[J&&o.jsx("p",{className:"error dialog-error",children:J}),o.jsxs("label",{className:"form-field",children:[L("editor.filePath"),o.jsx("input",{autoFocus:!0,value:N,onChange:W=>V(W.target.value),onKeyDown:W=>{W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),Ee())}})]})]})}),o.jsx(dn,{open:Y,title:L("editor.newFolder"),description:L("editor.folderDestination",{folder:G||L("editor.projectRoot")}),onOpenChange:W=>{ie(W),W||Z("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>ie(!1),children:L("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ce()},children:L("common.create")})]}),children:o.jsxs(o.Fragment,{children:[J&&o.jsx("p",{className:"error dialog-error",children:J}),o.jsxs("label",{className:"form-field",children:[L("editor.folderName"),o.jsx("input",{autoFocus:!0,value:F,onChange:W=>le(W.target.value),onKeyDown:W=>{W.key==="Enter"&&ce()}})]})]})}),o.jsx(dn,{open:!!Q,title:L("editor.moveTitle",{name:Q?.path.split("/").at(-1)??""}),description:L("editor.moveDescription"),onOpenChange:W=>{W||($(null),Se(""),Z(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>$(null),children:L("common.cancel")}),o.jsx("button",{className:"primary",disabled:!fe.trim(),onClick:()=>{ee()},children:L("editor.moveApply")})]}),children:o.jsxs(o.Fragment,{children:[J&&o.jsx("p",{className:"error dialog-error",children:J}),o.jsxs("label",{className:"form-field",children:[L("editor.pathName"),o.jsx("input",{autoFocus:!0,value:fe,onChange:W=>Se(W.target.value),onKeyDown:W=>{W.key==="Enter"&&ee()}})]}),o.jsxs("label",{className:"form-field",children:[L("editor.destinationFolder"),o.jsxs("select",{value:ve,onChange:W=>je(W.target.value),children:[o.jsx("option",{value:"",children:L("editor.projectRoot")}),l.filter(W=>Q?.type!=="directory"||W.path!==Q.path&&!W.path.startsWith(`${Q.path}/`)).map(W=>o.jsx("option",{value:W.path,children:W.path},W.path))]})]})]})}),o.jsx(dn,{open:!!q,title:L("editor.deletePathTitle",{name:q?.path.split("/").at(-1)??""}),description:we.length?L("editor.deletePathActiveDescription",{path:q?.path??"",users:[...new Set(we.map(W=>W.name))].join(", ")}):L("editor.deletePathDescription",{path:q?.path??""}),onOpenChange:W=>{W||(he(null),Z(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>he(null),children:L("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{U()},children:L("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[J&&o.jsx("p",{className:"error dialog-error",children:J}),we.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(Nt,{size:15}),L("editor.deletePathWillClose")]})]})}),o.jsxs(dn,{open:H,draggable:!0,title:L("editor.addComment"),description:ke.selectedText?L("editor.commentDescription",{count:ke.endOffset-ke.startOffset}):L("editor.pointComment"),onOpenChange:W=>{W||Te()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:te,onClick:Ie,children:L("common.cancel")}),o.jsxs("button",{type:"button",className:"primary","aria-busy":te,disabled:te||!O.trim(),onClick:()=>{_e()},children:[te&&o.jsx(ut,{className:"spin",size:14}),L(te?"editor.commentSending":"editor.addComment")]})]}),children:[Ne&&o.jsx("p",{className:"error dialog-error",children:Ne}),$e&&o.jsxs("p",{className:"comment-draft-restored",children:[o.jsx("span",{children:L("editor.commentDraftRestored")}),se&&o.jsx("button",{type:"button",disabled:te,onClick:xe,children:L("editor.commentDraftUseSelection")})]}),o.jsxs("label",{className:"form-field",children:[L("editor.commentContent"),o.jsx(Id,{projectId:n,autoFocus:!0,rows:5,disabled:te,value:O,placeholder:L("editor.commentPlaceholder"),onChange:I,onKeyDown:W=>{(W.ctrlKey||W.metaKey)&&W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),W.stopPropagation(),_e())}})]}),ke.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:ke.selectedText})]}),o.jsx(eS,{open:Pe,onOpenChange:Le,project:e,projectId:n}),D&&o.jsx(Ic,{title:L("citationLibrary.title"),onClose:()=>ue(!1),children:o.jsx(tS,{open:!0,onOpenChange:ue,currentFile:s,currentSource:r,readOnly:c,currentUserId:t.id,maxBibtexBytes:i,onInsert:Ue})}),Ye&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(oS,{open:!0,files:a,onOpenChange:nt,onOpenFile:W=>{const bt=a.find(kt=>kt.path===W);bt&&X(bt)}})}),pe&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(iS,{open:!0,project:e,onOpenChange:A,onJump:(W,bt,kt)=>{d==="pdf-only"&&f("editor-pdf"),Oe(W,bt,kt)}})}),ze&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(rS,{open:!0,onOpenChange:W=>{W||M()},project:e,filePath:ze.filePath,selection:ze.selection,currentSource:ze.source})}),oe&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(sS,{open:!0,onOpenChange:Re,project:e,onBeforeMutation:e.permission==="read"?async()=>!0:B})}),e.ownerId===t.id&&re&&o.jsx(u.Suspense,{fallback:null,children:o.jsx(nS,{open:!0,onOpenChange:vt,project:e,onBeforeMutation:B})})]})}function lS(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}var cS=Object.defineProperty,Lt=(t,e)=>cS(t,"name",{value:e,configurable:!0});function _a(t){const e=u.forwardRef((n,s)=>{let{children:r,...i}=n,a=null,l=!1;const c=[];$o(r)&&typeof Rr=="function"&&(r=Rr(r._payload)),u.Children.forEach(r,p=>{if(Bd(p)){l=!0;const m=p;let g="child"in m.props?m.props.child:m.props.children;$o(g)&&typeof Rr=="function"&&(g=Rr(g._payload)),a=dS(m,g),c.push(a?.props?.children)}else c.push(p)}),a?a=u.cloneElement(a,void 0,c):!l&&u.Children.count(r)===1&&u.isValidElement(r)&&(a=r);const d=a?zd(a):void 0,f=ks(s,d);if(!a){if(r||r===0)throw new Error(l?pS(t):hS(t));return r}const h=Ud(i,a.props??{});return a.type!==u.Fragment&&(h.ref=s?f:d),u.cloneElement(a,h)});return e.displayName=`${t}.Slot`,e}Lt(_a,"createSlot");var $d=Symbol.for("radix.slottable");function uS(t){const e=Lt(n=>"child"in n?n.children(n.child):n.children,"Slottable");return e.displayName=`${t}.Slottable`,e.__radixId=$d,e}Lt(uS,"createSlottable");var dS=Lt((t,e)=>{if("child"in t.props){const n=t.props.child;return u.isValidElement(n)?u.cloneElement(n,void 0,t.props.children(n.props.children)):null}return u.isValidElement(e)?e:null},"getSlottableElementFromSlottable");function Ud(t,e){const n={...e};for(const s in e){const r=t[s],i=e[s];/^on[A-Z]/.test(s)?r&&i?n[s]=(...l)=>{const c=i(...l);return r(...l),c}:r&&(n[s]=r):s==="style"?n[s]={...r,...i}:s==="className"?n[s]=[r,i].filter(Boolean).join(" "):s==="aria-describedby"&&(n[s]=qd(i,r))}return{...t,...n}}Lt(Ud,"mergeProps");function zd(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}Lt(zd,"getElementRef");function Bd(t){return u.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===$d}Lt(Bd,"isSlottable");var fS=Symbol.for("react.lazy");function $o(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===fS&&"_payload"in t&&Wd(t._payload)}Lt($o,"isLazyComponent");function Wd(t){return typeof t=="object"&&t!==null&&"then"in t}Lt(Wd,"isPromiseLike");function qd(...t){const e=new Set;for(const n of t)if(typeof n=="string")for(const s of String(n).trim().split(/\s+/))s&&e.add(s);return e.size>0?Array.from(e).join(" "):void 0}Lt(qd,"concatAriaDescribedby");var hS=Lt(t=>`${t} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),pS=Lt(t=>`${t} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Rr=Pp[" use ".trim().toString()],mS=Object.defineProperty,gS=(t,e)=>mS(t,"name",{value:e,configurable:!0}),wS=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],hr=wS.reduce((t,e)=>{const n=_a(`Primitive.${e}`),s=u.forwardRef((r,i)=>{const{asChild:a,...l}=r,c=a?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(c,{...l,ref:i})});return s.displayName=`Primitive.${e}`,{...t,[e]:s}},{});function Vd(t,e){t&&$c.flushSync(()=>t.dispatchEvent(e))}gS(Vd,"dispatchDiscreteCustomEvent");var bS=Object.defineProperty,it=(t,e)=>bS(t,"name",{value:e,configurable:!0}),Uo="dismissableLayer.update",yS="dismissableLayer.pointerDownOutside",xS="dismissableLayer.focusOutside",Ac,Hd=u.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),SS=u.forwardRef(it(function(e,n){const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:l,onInteractOutside:c,onDismiss:d,...f}=e,h=u.useContext(Hd),[p,m]=u.useState(null),g=p?.ownerDocument??globalThis?.document,[,x]=u.useState({}),j=ks(n,m),C=Array.from(h.layers),[z]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),k=z?C.indexOf(z):-1,y=p?C.indexOf(p):-1,P=h.layersWithOutsidePointerEventsDisabled.size>0,E=y>=k,S=u.useRef(!1),N=Kd(F=>{a?.(F),c?.(F),F.defaultPrevented||d?.()},{ownerDocument:g,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:S,dismissableSurfaces:h.dismissableSurfaces,shouldHandlePointerDownOutside:u.useCallback(F=>{if(!(F instanceof Node))return!1;const le=[...h.branches].some(G=>G.contains(F));return E&&!le},[h.branches,E])}),V=Gd(F=>{if(r&&S.current)return;const le=F.target;[...h.branches].some(J=>J.contains(le))||(l?.(F),c?.(F),F.defaultPrevented||d?.())},g),Y=p?y===C.length-1:!1,ie=qs(F=>{F.key==="Escape"&&(i?.(F),!F.defaultPrevented&&d&&(F.preventDefault(),d()))});return u.useEffect(()=>{if(Y)return g.addEventListener("keydown",ie,{capture:!0}),()=>g.removeEventListener("keydown",ie,{capture:!0})},[g,Y,ie]),u.useEffect(()=>{if(p)return s&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(Ac=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(p)),h.layers.add(p),zo(),()=>{s&&(h.layersWithOutsidePointerEventsDisabled.delete(p),h.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=Ac))}},[p,g,s,h]),u.useEffect(()=>()=>{p&&(h.layers.delete(p),h.layersWithOutsidePointerEventsDisabled.delete(p),zo())},[p,h]),u.useEffect(()=>{const F=it(()=>x({}),"handleUpdate");return document.addEventListener(Uo,F),()=>document.removeEventListener(Uo,F)},[]),o.jsx(hr.div,{...f,ref:j,style:{pointerEvents:P?E?"auto":"none":void 0,...e.style},onFocusCapture:An(e.onFocusCapture,V.onFocusCapture),onBlurCapture:An(e.onBlurCapture,V.onBlurCapture),onPointerDownCapture:An(e.onPointerDownCapture,N.onPointerDownCapture)})},"DismissableLayer"));function vS(){const t=u.useContext(Hd),[e,n]=u.useState(null);return u.useEffect(()=>{if(e)return t.dismissableSurfaces.add(e),()=>{t.dismissableSurfaces.delete(e)}},[e,t.dismissableSurfaces]),n}it(vS,"useDismissableLayerSurface");var kS=it(()=>!0,"IS_TRUE");function Kd(t,e){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:s=!1,isDeferredPointerDownOutsideRef:r,dismissableSurfaces:i,shouldHandlePointerDownOutside:a=kS}=e,l=qs(t),c=u.useRef(!1),d=u.useRef(!1),f=u.useRef(new Map),h=u.useRef(()=>{});return u.useEffect(()=>{function p(){d.current=!1,r.current=!1,f.current.clear()}it(p,"resetOutsideInteraction");function m(){return Array.from(f.current.values()).some(Boolean)}it(m,"isOutsideInteractionIntercepted");function g(k){if(!d.current)return;const y=k.target;y instanceof Node&&[...i].some(E=>E.contains(y))||f.current.set(k.type,!0),k.type==="click"&&window.setTimeout(()=>{d.current&&h.current()},0)}it(g,"handleInteractionCapture");function x(k){d.current&&f.current.set(k.type,!1)}it(x,"handleInteractionBubble");const j=it(k=>{if(k.target&&!c.current){let y=function(){n.removeEventListener("click",h.current);const E=m();p(),E||La(yS,l,P,{discrete:!0})};if(it(y,"handleAndDispatchPointerDownOutsideEvent"),!a(k.target)){n.removeEventListener("click",h.current),p(),c.current=!1;return}const P={originalEvent:k};d.current=!0,r.current=s&&k.button===0,f.current.clear(),!s||k.button!==0?y():(n.removeEventListener("click",h.current),h.current=y,n.addEventListener("click",h.current,{once:!0}))}else n.removeEventListener("click",h.current),p();c.current=!1},"handlePointerDown"),C=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const k of C)n.addEventListener(k,g,!0),n.addEventListener(k,x);const z=window.setTimeout(()=>{n.addEventListener("pointerdown",j)},0);return()=>{window.clearTimeout(z),n.removeEventListener("pointerdown",j),n.removeEventListener("click",h.current);for(const k of C)n.removeEventListener(k,g,!0),n.removeEventListener(k,x)}},[n,l,s,r,i,a]),{onPointerDownCapture:it(()=>c.current=!0,"onPointerDownCapture")}}it(Kd,"usePointerDownOutside");function Gd(t,e=globalThis?.document){const n=qs(t),s=u.useRef(!1);return u.useEffect(()=>{const r=it(i=>{i.target&&!s.current&&La(xS,n,{originalEvent:i},{discrete:!1})},"handleFocus");return e.addEventListener("focusin",r),()=>e.removeEventListener("focusin",r)},[e,n]),{onFocusCapture:it(()=>s.current=!0,"onFocusCapture"),onBlurCapture:it(()=>s.current=!1,"onBlurCapture")}}it(Gd,"useFocusOutside");function zo(){const t=new CustomEvent(Uo);document.dispatchEvent(t)}it(zo,"dispatchUpdate");function La(t,e,n,{discrete:s}){const r=n.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&r.addEventListener(t,e,{once:!0}),s?Vd(r,i):r.dispatchEvent(i)}it(La,"handleAndDispatchCustomEvent");var CS=Object.defineProperty,et=(t,e)=>CS(t,"name",{value:e,configurable:!0}),po="focusScope.autoFocusOnMount",mo="focusScope.autoFocusOnUnmount",Nc={bubbles:!1,cancelable:!0},ES=u.forwardRef(et(function(e,n){const{loop:s=!1,trapped:r=!1,branches:i,onMountAutoFocus:a,onUnmountAutoFocus:l,...c}=e,[d,f]=u.useState(null),h=qs(a),p=qs(l),m=u.useRef(null),g=ks(n,f),x=u.useRef(i);u.useEffect(()=>{x.current=i});const j=u.useCallback(k=>k?d?.contains(k)?!0:!!x.current?.some(y=>y.contains(k)):!1,[d]),C=u.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;u.useEffect(()=>{if(r){let k=function(S){if(C.paused||!d)return;const N=S.target;j(N)?m.current=N:Zt(m.current,{select:!0})},y=function(S){if(C.paused||!d)return;const N=S.relatedTarget;N!==null&&(j(N)||Zt(m.current,{select:!0}))},P=function(S){if(document.activeElement===document.body)for(const V of S)V.removedNodes.length>0&&Zt(d)};et(k,"handleFocusIn"),et(y,"handleFocusOut"),et(P,"handleMutations"),document.addEventListener("focusin",k),document.addEventListener("focusout",y);const E=new MutationObserver(P);return d&&E.observe(d,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",k),document.removeEventListener("focusout",y),E.disconnect()}}},[r,d,C.paused,j]),u.useEffect(()=>{if(d){Oc.add(C);const k=document.activeElement;if(!d.contains(k)){const P=new CustomEvent(po,Nc);d.addEventListener(po,h),d.dispatchEvent(P),P.defaultPrevented||(Qd(rf(Aa(d)),{select:!0}),document.activeElement===k&&Zt(d))}return()=>{d.removeEventListener(po,h),setTimeout(()=>{const P=new CustomEvent(mo,Nc);d.addEventListener(mo,p),d.dispatchEvent(P),P.defaultPrevented||Zt(k??document.body,{select:!0}),d.removeEventListener(mo,p),Oc.remove(C)},0)}}},[d,h,p,C]);const z=u.useCallback(k=>{if(!s&&!r||C.paused)return;const y=k.key==="Tab"&&!k.altKey&&!k.ctrlKey&&!k.metaKey,P=document.activeElement;if(y&&P){const E=k.currentTarget,[S,N]=ef(E);S&&N?!k.shiftKey&&P===N?(k.preventDefault(),s&&Zt(S,{select:!0})):k.shiftKey&&P===S&&(k.preventDefault(),s&&Zt(N,{select:!0})):P===E&&k.preventDefault()}},[s,r,C.paused]);return o.jsx(hr.div,{tabIndex:-1,...c,ref:g,onKeyDown:z})},"FocusScope")),Jd=u.createContext(null);function Yd({registry:t,children:e}){return t?o.jsx(Jd.Provider,{value:t,children:e}):e}et(Yd,"FocusScopeBranchProvider");function Xd(){const[t,e]=u.useState([]),n=u.useMemo(()=>({add:et(s=>e(r=>r.includes(s)?r:[...r,s]),"add"),remove:et(s=>e(r=>r.filter(i=>i!==s)),"remove")}),[]);return{nodes:t,registry:n}}et(Xd,"useFocusScopeBranchRegistry");function Zd(t){const e=u.useContext(Jd);u.useEffect(()=>{if(!(!t||!e))return e.add(t),()=>e.remove(t)},[t,e])}et(Zd,"useFocusScopeBranch");function Qd(t,{select:e=!1}={}){const n=document.activeElement;for(const s of t)if(Zt(s,{select:e}),document.activeElement!==n)return}et(Qd,"focusFirst");function ef(t){const e=Aa(t),n=Bo(e,t),s=Bo(e.reverse(),t);return[n,s]}et(ef,"getTabbableEdges");function Aa(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:et(s=>{const r=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||r?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)e.push(n.currentNode);return e}et(Aa,"getTabbableCandidates");function Bo(t,e){const n=typeof e.checkVisibility=="function"&&e.checkVisibility({checkVisibilityCSS:!0});for(const s of t)if(!(n?!s.checkVisibility({checkVisibilityCSS:!0}):tf(s,{upTo:e})))return s}et(Bo,"findVisible");function tf(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}et(tf,"isHidden");function nf(t){return t instanceof HTMLInputElement&&"select"in t}et(nf,"isSelectableInput");function Zt(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&nf(t)&&e&&t.select()}}et(Zt,"focus");var Oc=sf();function sf(){let t=[];return{add(e){const n=t[0];e!==n&&n?.pause(),t=Wo(t,e),t.unshift(e)},remove(e){t=Wo(t,e),t[0]?.resume()}}}et(sf,"createFocusScopesStack");function Wo(t,e){const n=[...t],s=n.indexOf(e);return s!==-1&&n.splice(s,1),n}et(Wo,"arrayRemove");function rf(t){return t.filter(e=>e.tagName!=="A")}et(rf,"removeLinks");var jS=Object.defineProperty,DS=(t,e)=>jS(t,"name",{value:e,configurable:!0}),TS=u.forwardRef(DS(function(e,n){const{container:s,...r}=e,[i,a]=u.useState(!1);Fr(()=>a(!0),[]);const l=s||i&&globalThis?.document?.body;return l?$c.createPortal(o.jsx(hr.div,{...r,ref:n}),l):null},"Portal")),RS=Object.defineProperty,nn=(t,e)=>RS(t,"name",{value:e,configurable:!0});function of(t,e){return u.useReducer((n,s)=>e[n][s]??n,t)}nn(of,"useStateMachine");var af=nn(t=>{const{present:e,children:n}=t,s=lf(e),r=typeof n=="function"?n({present:s.isPresent}):u.Children.only(n),i=cf(s.ref,uf(r));return typeof n=="function"||s.isPresent?u.cloneElement(r,{ref:i}):null},"Presence");function lf(t){const[e,n]=u.useState(),s=u.useRef(null),r=u.useRef(t),i=u.useRef("none"),a=u.useRef(void 0),l=t?"mounted":"unmounted",[c,d]=of(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return u.useEffect(()=>{c==="mounted"?(i.current=a.current??ns(s.current),a.current=void 0):i.current="none"},[c]),Fr(()=>{const f=s.current,h=r.current;if(h!==t){const m=i.current,g=ns(f);t?(a.current=g,d("MOUNT")):g==="none"||f?.display==="none"?d("UNMOUNT"):d(h&&m!==g?"ANIMATION_OUT":"UNMOUNT"),r.current=t}},[t,d]),Fr(()=>{if(e){let f;const h=e.ownerDocument.defaultView??window,p=nn(g=>{const j=ns(s.current).includes(CSS.escape(g.animationName));if(g.target===e&&j&&(d("ANIMATION_END"),!r.current)){const C=e.style.animationFillMode;e.style.animationFillMode="forwards",f=h.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=C)})}},"handleAnimationEnd"),m=nn(g=>{g.target===e&&(i.current=ns(s.current))},"handleAnimationStart");return e.addEventListener("animationstart",m),e.addEventListener("animationcancel",p),e.addEventListener("animationend",p),()=>{h.clearTimeout(f),e.removeEventListener("animationstart",m),e.removeEventListener("animationcancel",p),e.removeEventListener("animationend",p)}}else d("ANIMATION_END")},[e,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:u.useCallback(f=>{if(f){const h=getComputedStyle(f);s.current=h,a.current=ns(h)}else s.current=null;n(f)},[])}}nn(lf,"usePresence");function qo(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}nn(qo,"setRef");function cf(...t){const e=u.useRef(t);return e.current=t,u.useCallback(n=>{const s=e.current;let r=!1;const i=s.map(a=>{const l=qo(a,n);return!r&&typeof l=="function"&&(r=!0),l});if(r)return()=>{for(let a=0;a<i.length;a++){const l=i[a];typeof l=="function"?l():qo(s[a],null)}}},[])}nn(cf,"useStableComposedRefs");function ns(t){return t?.animationName||"none"}nn(ns,"getAnimationName");function uf(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}nn(uf,"getElementRef");var _S=Object.defineProperty,Ht=(t,e)=>_S(t,"name",{value:e,configurable:!0}),Na="Popover",[df,yv]=Ap(Na,[zc]),Oa=zc(),[LS,Wn]=df(Na),AS=Ht(t=>{const{__scopePopover:e,children:n,open:s,defaultOpen:r,onOpenChange:i,modal:a=!1}=t,l=Oa(e),c=u.useRef(null),[d,f]=u.useState(!1),[h,p]=u.useState(0),[m,g]=u.useState(0),[x,j]=Rp({prop:s,defaultProp:r??!1,onChange:i,caller:Na});return o.jsx(im,{...l,children:o.jsx(LS,{scope:e,contentId:Vi(),titleId:Vi(),descriptionId:Vi(),titlePresent:h>0,descriptionPresent:m>0,setTitleCount:p,setDescriptionCount:g,triggerRef:c,open:x,onOpenChange:j,onOpenToggle:u.useCallback(()=>j(C=>!C),[j]),hasCustomAnchor:d,onCustomAnchorAdd:u.useCallback(()=>f(!0),[]),onCustomAnchorRemove:u.useCallback(()=>f(!1),[]),modal:a,children:n})})},"Popover"),NS="PopoverTrigger",OS=u.forwardRef(Ht(function(e,n){const{__scopePopover:s,...r}=e,i=Wn(NS,s),a=Oa(s),l=ks(n,i.triggerRef),c=o.jsx(hr.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":Pa(i.open),...r,ref:l,onClick:An(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:o.jsx(om,{asChild:!0,...a,children:c})},"PopoverTrigger")),ff="PopoverPortal",[PS,FS]=df(ff,{forceMount:void 0}),MS=Ht(t=>{const{__scopePopover:e,forceMount:n,children:s,container:r}=t,i=Wn(ff,e);return o.jsx(PS,{scope:e,forceMount:n,children:o.jsx(af,{present:n||i.open,children:o.jsx(TS,{asChild:!0,container:r,children:s})})})},"PopoverPortal"),sr="PopoverContent",IS=u.forwardRef(Ht(function(e,n){const s=FS(sr,e.__scopePopover),{forceMount:r=s.forceMount,...i}=e,a=Wn(sr,e.__scopePopover);return o.jsx(af,{present:r||a.open,children:a.modal?o.jsx(US,{...i,ref:n}):o.jsx(zS,{...i,ref:n})})},"PopoverContent")),$S=_a("PopoverContent.RemoveScroll"),US=u.forwardRef(Ht(function(e,n){const s=Wn(sr,e.__scopePopover),r=u.useRef(null),i=ks(n,r),a=u.useRef(!1),{nodes:l,registry:c}=Xd();return u.useEffect(()=>{const d=r.current;if(d)return _p(d)},[]),o.jsx(Fp,{as:$S,allowPinchZoom:!0,shards:u.useMemo(()=>[r,...l.map(d=>({current:d}))],[r,l]),children:o.jsx(hf,{...e,ref:i,branchNodes:l,branchRegistry:c,trapFocus:s.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:An(e.onCloseAutoFocus,d=>{d.preventDefault(),a.current||s.triggerRef.current?.focus()}),onPointerDownOutside:An(e.onPointerDownOutside,d=>{const f=d.detail.originalEvent,h=f.button===0&&f.ctrlKey===!0,p=f.button===2||h;a.current=p},{checkForDefaultPrevented:!1}),onFocusOutside:An(e.onFocusOutside,d=>d.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),zS=u.forwardRef(Ht(function(e,n){const s=Wn(sr,e.__scopePopover),r=u.useRef(!1),i=u.useRef(!1);return o.jsx(hf,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(r.current||s.triggerRef.current?.focus(),a.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(r.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const l=a.target;s.triggerRef.current?.contains(l)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})},"PopoverContentNonModal")),hf=u.forwardRef(Ht(function(e,n){const{__scopePopover:s,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,"aria-describedby":p,branchNodes:m,branchRegistry:g,...x}=e,j=Wn(sr,s),C=Oa(s),[z,k]=u.useState(null),y=ks(n,k);return Zd(z),Lp(),o.jsx(Yd,{registry:g,children:o.jsx(ES,{asChild:!0,loop:!0,trapped:r,branches:m,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o.jsx(SS,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:h,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onDismiss:()=>j.onOpenChange(!1),deferPointerDownOutside:!0,children:o.jsx(am,{"data-state":Pa(j.open),role:"dialog",id:j.contentId,"aria-labelledby":j.titlePresent?j.titleId:void 0,"aria-describedby":j.descriptionPresent?pf(p,j.descriptionId):p,...C,...x,ref:y,style:{...x.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})})},"PopoverContentImpl")),BS=u.forwardRef(Ht(function(e,n){const{__scopePopover:s,...r}=e,i=Wn("PopoverTitle",s),{setTitleCount:a}=i;return Fr(()=>(a(l=>l+1),()=>a(l=>l-1)),[a]),o.jsx(hr.h2,{id:i.titleId,...r,ref:n})},"PopoverTitle"));function Pa(t){return t?"open":"closed"}Ht(Pa,"getState");function pf(...t){const e=new Set;for(const n of t)if(typeof n=="string")for(const s of String(n).trim().split(/\s+/))s&&e.add(s);return e.size>0?Array.from(e).join(" "):void 0}Ht(pf,"concatAriaDescribedby");function WS({participants:t,selectedIds:e,topLevelOnly:n,onToggle:s,onClear:r,onTopLevelOnlyChange:i}){const{t:a}=Je(),[l,c]=u.useState(!1),d=u.useRef(null),f=e.size>0,h=t.find(g=>e.has(g.authorId)),p=g=>g.authorDisplayName??g.authorUsername??a("editor.deletedUser"),m=f?h?e.size===1?p(h):a("editor.commentParticipantsSelected",{name:p(h),count:e.size-1}):a("editor.commentParticipantsCount",{count:e.size}):a("editor.commentParticipantsAll");return o.jsxs("div",{className:"comment-participant-filter",children:[o.jsxs("div",{className:`comment-participants-trigger-group${f?" active":""}`,children:[o.jsxs(AS,{open:l,onOpenChange:c,children:[o.jsx(OS,{asChild:!0,children:o.jsxs("button",{type:"button",className:"comment-participants-toggle","aria-label":`${a("editor.commentParticipants")}: ${m}`,children:[o.jsx(Mr,{size:13,"aria-hidden":!0}),o.jsx("span",{className:"comment-participants-summary",children:f&&h?p(h):m}),f&&h&&e.size>1&&o.jsxs("span",{className:"comment-participants-extra-count",children:["+",e.size-1]}),o.jsx(rr,{size:12,"aria-hidden":!0,className:l?"expanded":""})]})}),o.jsx(MS,{children:o.jsxs(IS,{ref:d,className:"comment-participants-popover",side:"bottom",align:"end",sideOffset:6,collisionPadding:10,"aria-label":a("editor.commentParticipants"),onOpenAutoFocus:g=>{g.preventDefault();const x=d.current?.querySelector('input[type="checkbox"]:not(:disabled)');x?x.focus():d.current?.focus()},children:[o.jsxs("div",{className:"comment-participants-heading",children:[o.jsx(BS,{children:a("editor.commentParticipants")}),f&&o.jsx("button",{type:"button",onClick:r,children:a("editor.commentParticipantsClear")})]}),o.jsxs("div",{className:"comment-participants-list",children:[t.map(g=>{const x=p(g),j=e.has(g.authorId);return o.jsxs("label",{className:`comment-participant-option${j?" selected":""}`,children:[o.jsx("input",{type:"checkbox",checked:j,onChange:()=>s(g.authorId)}),o.jsx("span",{className:"comment-participant-avatar","aria-hidden":!0,children:Array.from(x.trim())[0]?.toLocaleUpperCase()??"?"}),o.jsxs("span",{className:"comment-participant-identity",children:[o.jsx("strong",{children:x}),g.authorUsername&&o.jsxs("small",{children:["@",g.authorUsername]})]})]},g.authorId??"deleted")}),t.length===0&&o.jsx("p",{className:"comment-participants-empty",children:a("editor.commentNoParticipants")})]}),o.jsxs("label",{className:"comment-participants-root-only",children:[o.jsx("input",{type:"checkbox",checked:n,disabled:!f,onChange:g=>i(g.target.checked)}),a("editor.commentTopLevelOnly")]})]})})]}),f&&o.jsx("button",{type:"button",className:"comment-participants-clear","aria-label":a("editor.commentParticipantsClear"),onClick:r,children:o.jsx(mn,{size:12,"aria-hidden":!0})})]}),f&&n&&o.jsx("span",{className:"comment-participants-scope",children:a("editor.commentTopLevelOnly")})]})}const mf=280;function qS(t,e,n,s,r){const i=e.map(c=>({comment:c,exitAt:null})),a=new Set(e.map(c=>c.id)),l=new Map(n.map(c=>[c.id,c]));return t.forEach((c,d)=>{const f=l.get(c.comment.id);a.has(c.comment.id)||!f||Jo(f,s)||i.splice(Math.min(d,i.length),0,{comment:f,exitAt:c.exitAt??r+mf+50})}),i}function VS(t,e,n,s){const[r,i]=u.useState(()=>({contextKey:s,visible:t,comments:e,entries:t.map(l=>({comment:l,exitAt:null}))}));(r.contextKey!==s||r.visible!==t||r.comments!==e)&&i({contextKey:s,visible:t,comments:e,entries:r.contextKey!==s?t.map(l=>({comment:l,exitAt:null})):qS(r.entries,t,e,n,Date.now())});const a=u.useCallback(l=>{i(c=>({...c,entries:c.entries.filter(d=>d.comment.id!==l||d.exitAt===null)}))},[]);return u.useEffect(()=>{const l=r.entries.flatMap(d=>d.exitAt===null?[]:[d.exitAt]);if(!l.length)return;const c=window.setTimeout(()=>{const d=Date.now();i(f=>({...f,entries:f.entries.filter(h=>h.exitAt===null||h.exitAt>d)}))},Math.max(0,Math.min(...l)-Date.now()));return()=>window.clearTimeout(c)},[r.entries]),{entries:r.entries,finishExit:a}}const HS=u.lazy(()=>_t(()=>import("./ProjectSettings-CZE_xDKn.js"),__vite__mapDeps([27,2,1,3,6,28,29,9,4,5,7,8]),import.meta.url).then(t=>({default:t.ProjectSettings})));function KS({sidePanel:t,onClose:e,project:n,projectId:s,site:r,files:i,currentUserId:a,comments:l,commentDraftStore:c,commentsLoading:d,commentsError:f,onRetryComments:h,unreadMentions:p,activeFile:m,singleCommentId:g,onShowAllComments:x,hasProjectCommentsScope:j,commentScope:C,onCommentScopeChange:z,focusedCommentId:k,commentFocusNonce:y,onMarkMentionRead:P,onMarkAllMentionsRead:E,onClearFocusComment:S,targetCommentId:N,targetReplyId:V,onFocusComment:Y,onToggleComment:ie,onReplyComment:F,onEditComment:le,onDeleteComment:G,onEditCommentReply:J,onDeleteCommentReply:Z,dictionaryWords:Ee,onDictionaryChange:ce,editorPreferences:Q,onEditorPreferences:$,spellCheckCount:fe,spellCheckUniqueCount:Se,spellCheckIndex:ve,onSpellCheckNavigate:je,onProject:ee}){const{t:q}=Je(),he=!!g,[we,U]=u.useState("unresolved"),[H,Te]=u.useState(!1),[ke,O]=u.useState("source"),[I,te]=u.useState(()=>new Set),[Ne,_e]=u.useState(!0),[Ie,$e]=u.useState(()=>new Map),[se,xe]=u.useState(null),Pe=u.useRef(new Map(l.map(v=>[v.id,v.resolved]))),Le=u.useMemo(()=>ag(l),[l]),D=u.useMemo(()=>{const v={activeFile:m,scope:C,unreadMentions:p,participantIds:I,topLevelOnly:Ne,unreadMentionsOnly:H};return{unresolved:Yi(l,{...v,filter:"unresolved"}).length,resolved:Yi(l,{...v,filter:"resolved"}).length,mentions:Yi(l,{...v,filter:we,unreadMentionsOnly:!0}).length}},[m,C,l,p,I,Ne,we,H]),ue=u.useMemo(()=>g?ug(l,g,m):cg(l,{activeFile:m,scope:C,filter:we,unreadMentions:p,sort:ke,participantIds:I,topLevelOnly:Ne,unreadMentionsOnly:H},[N,k]),[m,g,we,C,l,k,N,p,ke,I,Ne,H]),Ue=k&&ue.some(v=>v.id===k)?k:N&&ue.some(v=>v.id===N)?N:null,Ye=he?ue[0]?.id??null:se&&ue.some(v=>v.id===se)?se:Ue;u.useEffect(()=>{xe(null)},[k,y,N,V,m,C]),u.useEffect(()=>{se&&!ue.some(v=>v.id===se)&&xe(null)},[se,ue]);const nt=pg(ue,Ye),pe=JSON.stringify([t,g,C,C==="file"?m:"",we,ke,[...I].sort(),Ne,H]),{entries:A,finishExit:X}=VS(ue,l,he?"unresolved":we,pe);u.useEffect(()=>{const v=l.some(_=>(_.id===k||_.id===N)&&Pe.current.has(_.id)&&Pe.current.get(_.id)!==_.resolved);Pe.current=new Map(l.map(_=>[_.id,_.resolved])),v&&S()},[l,k,N,S]),u.useEffect(()=>{!j&&C!=="file"&&(S(),z("file"))},[C,j,S,z]),u.useEffect(()=>{if(t!=="comments"||se)return;const v=N&&V?`.comments [data-comment-reply-id="${V}"]`:N?`.comments .comment-thread[data-comment-id="${N}"]`:Ue?`.comments .comment-thread[data-comment-id="${Ue}"]`:"";if(!v)return;const _=document.querySelector(v);if(!_)return;const K=window.requestAnimationFrame(()=>_.scrollIntoView({block:N?"center":"nearest",behavior:"smooth"}));return()=>window.cancelAnimationFrame(K)},[t,se,Ue,y,N,V,ue]);const Oe=v=>{xe(null),Y(v)},ze=v=>{const _=mg(ue,Ye,v);_?Oe(_):S()},M=async v=>{const _=await P(v);if(!_||he||!H)return _;const K=p.find(L=>L.id===v)?.commentId;return K&&(p.some(L=>L.id!==v&&L.commentId===K)||(k===K||N===K)&&S()),_},oe=async()=>{await E()&&H&&S()},Re=v=>{v!==C&&(xe(null),S(),z(v))},re=v=>{v!==we&&(xe(null),S(),U(v))},vt=()=>{xe(null),S()},B=v=>{vt(),I.size===1&&I.has(v)&&_e(!0),te(_=>{const K=new Set(_);return K.has(v)?K.delete(v):K.add(v),K})};return t?o.jsxs(o.Fragment,{children:[o.jsx(Vo,{className:"resize-handle"}),o.jsx(ni,{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:q(he?"editor.currentComment":"editor.sourceComments")}),o.jsxs("span",{className:"drawer-title-actions",children:[!he&&p.length>0&&o.jsxs("button",{className:"drawer-mention-read-all",type:"button",onClick:()=>{oe()},title:q("editor.markAllMentionsRead"),children:[o.jsx(Vs,{"aria-hidden":!0,size:13}),o.jsx("span",{children:q("editor.markAllMentionsRead")})]}),o.jsx("button",{"aria-label":q("common.close"),onClick:e,children:o.jsx(mn,{size:17})})]})]}),he?o.jsx("div",{className:"comment-current-controls",children:o.jsxs("button",{type:"button",onClick:x,children:[o.jsx(vm,{size:14,"aria-hidden":!0}),q("editor.viewAllComments")]})}):o.jsxs("div",{className:"comment-review-controls",children:[o.jsxs("div",{className:"comment-review-queue-row",children:[j&&o.jsxs("div",{className:"comment-review-group",role:"group","aria-label":q("editor.commentScope"),children:[o.jsx("button",{type:"button",className:C==="file"?"active":"","aria-pressed":C==="file",onClick:()=>Re("file"),children:q("editor.commentScopeFile")}),o.jsx("button",{type:"button",className:C==="project"?"active":"","aria-pressed":C==="project",onClick:()=>Re("project"),children:q("editor.commentScopeProject")})]}),o.jsxs("div",{className:"comment-review-group",role:"group","aria-label":q("editor.commentFilter"),children:[o.jsx("button",{type:"button",className:we==="unresolved"?"active":"","aria-pressed":we==="unresolved",onClick:()=>re("unresolved"),children:q("editor.commentFilterUnresolved",{count:D.unresolved})}),o.jsx("button",{type:"button",className:we==="resolved"?"active":"","aria-pressed":we==="resolved",onClick:()=>re("resolved"),children:q("editor.commentFilterResolved",{count:D.resolved})})]}),o.jsxs("div",{className:"comment-review-navigation",children:[o.jsx("button",{type:"button",disabled:nt<=1,"aria-label":q("editor.commentPrevious"),title:q("editor.commentPrevious"),onClick:()=>ze(-1),children:o.jsx(Zp,{size:14})}),o.jsx("output",{"aria-live":"polite",children:q("editor.commentPosition",{current:nt,total:ue.length})}),o.jsx("button",{type:"button",disabled:ue.length===0||nt>0&&nt>=ue.length,"aria-label":q("editor.commentNext"),title:q("editor.commentNext"),onClick:()=>ze(1),children:o.jsx(Ho,{size:14})})]})]}),o.jsxs("div",{className:"comment-review-sort-row",children:[o.jsx(WS,{participants:Le,selectedIds:I,topLevelOnly:Ne,onToggle:B,onClear:()=>{vt(),te(new Set),_e(!0)},onTopLevelOnlyChange:v=>{vt(),_e(v)}},`${C}:${C==="file"?m:"project"}`),o.jsxs("button",{type:"button",className:`comment-unread-toggle${H?" active":""}`,"aria-pressed":H,"aria-label":q("editor.commentUnreadMentionsHint"),title:q("editor.commentUnreadMentionsHint"),onClick:()=>{vt(),Te(v=>!v)},children:[o.jsx(Vs,{size:12,"aria-hidden":!0}),q("editor.commentUnreadMentionsOnly"),o.jsx("span",{children:D.mentions})]}),o.jsxs("label",{className:"comment-review-sort","data-texlite-tooltip-always":!0,"data-tooltip":q(ke==="source"?"editor.commentSortSource":"editor.commentSortTime"),children:[o.jsx("span",{className:"sr-only",children:q("editor.commentSort")}),ke==="source"?o.jsx(um,{size:12,"aria-hidden":!0}):o.jsx(dm,{size:12,"aria-hidden":!0}),o.jsxs("select",{value:ke,"aria-label":`${q("editor.commentSort")}: ${q(ke==="source"?"editor.commentSortSource":"editor.commentSortTime")}`,onChange:v=>O(v.target.value),children:[o.jsx("option",{value:"source",children:q("editor.commentSortSourceShort")}),o.jsx("option",{value:"time",children:q("editor.commentSortTimeShort")})]})]})]})]}),f&&o.jsxs("div",{className:"comment-review-error",role:"alert",children:[o.jsx("span",{children:f}),o.jsx("button",{type:"button",onClick:()=>{h()},children:q("common.retry")})]}),d&&o.jsx("div",{className:"comment-review-loading",role:"status",children:q("common.loading")}),o.jsxs("div",{className:"comments",children:[A.map(({comment:v,exitAt:_})=>{const K=p.find(L=>L.commentId===v.id&&!L.replyId)?.id,dt=new Map(p.filter(L=>L.commentId===v.id&&L.replyId).map(L=>[L.replyId,L.id]));return o.jsx("div",{className:`comment-thread-slot${_!==null?" is-exiting":""}`,inert:_!==null?!0:void 0,"aria-hidden":_!==null?!0:void 0,style:{"--comment-exit-duration":`${mf}ms`},onAnimationEnd:L=>{L.target===L.currentTarget&&_!==null&&X(v.id)},children:o.jsx("div",{className:"comment-thread-slot-content",children:o.jsx(Q0,{projectId:s,comment:v,draftStore:c,currentUserId:a,unreadCommentMentionId:K,unreadReplyMentionIds:dt,highlightedComment:N===v.id&&!V,highlightedReplyId:N===v.id?V:null,currentComment:Ye===v.id,showFilePath:!he&&C==="project",replyExpansion:Ie.get(v.id),onReplyExpansionChange:L=>{$e(W=>W.get(v.id)===L?W:new Map(W).set(v.id,L))},selectedParticipantIds:he?void 0:I,highlightReplyParticipants:!he&&!Ne,onMarkMentionRead:M,onFocus:()=>Oe(v),onActivate:()=>xe(v.id),onToggle:()=>ie(v),onReply:L=>F(v,L),onEdit:L=>le(v,L),onDelete:()=>G(v),onEditReply:(L,W)=>J(v,L,W),onDeleteReply:L=>Z(v,L)})})},v.id)}),A.length===0&&!d&&!f&&o.jsx("p",{className:"muted padded",role:"status",children:he?q(l.some(v=>v.id===g&&v.resolved)?"editor.currentCommentResolved":"editor.currentCommentUnavailable"):l.length?q("editor.commentNoMatches"):q("editor.noComments")})]})]}),t==="settings"&&o.jsx(Np,{onClose:e,children:o.jsx(HS,{onClose:e,project:n,projectId:s,site:r,files:i,dictionaryWords:Ee,onDictionaryChange:ce,editorPreferences:Q,onEditorPreferences:$,spellCheckCount:fe,spellCheckUniqueCount:Se,spellCheckIndex:ve,onSpellCheckNavigate:je,onProject:ee},s)})]})})]}):null}function GS(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 JS(){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()},a=()=>{s=null;const c=n;n=null,!(c===null||c===e)&&(e=c,i())},l=c=>{n=c,s===null&&(s=GS(a))};return{getCursor:()=>t,getOutlineLine:()=>e,subscribe:c=>(r.add(c),()=>r.delete(c)),update:(c,d,f)=>{t.line===c&&t.column===d&&t.offset===f||(t={line:c,column:d,offset:f},(c!==e||s!==null)&&l(c))},reset:()=>{s?.(),s=null,n=null,t={line:1,column:1,offset:0},e!==1&&(e=1,i())},dispose:()=>{s?.(),s=null,n=null}}}function YS(t,e,n){return t.mainFile===e?t.items:!e||n.filePath!==e?[]:XS(n.content).map(s=>({...s,path:e}))}function XS(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`
|
|
20
|
+
`).forEach((r,i)=>{const a=r.match(n);a&&e.push({level:s[a[1]],title:a[2],line:i+1})}),e}const ZS=u.lazy(()=>_t(()=>import("./WordCountDialog-DUyR24vv.js"),__vite__mapDeps([30,2,1,3,28,6,4,5,7,8,9]),import.meta.url).then(t=>({default:t.WordCountDialog})));let _r=null;function Pc(){return _r||(_r=_t(()=>import("./citationLibrary-C9WnXB-1.js"),[],import.meta.url).catch(t=>{throw _r=null,t})),_r}function Xt(t){return t instanceof Error&&t.name==="AbortError"}const Fc=300;function QS({site:t,user:e,projectId:n,preload:s,mentionId:r=null,onMentionTargeted:i,onMentionsRead:a,onBack:l}){const{t:c}=Je(),d=u.useRef(n);d.current=n;const[f,h]=u.useState(null);u.useEffect(()=>(document.title=f?.name?`${t.siteName} | ${f.name}`:t.siteName,()=>{document.title=t.siteName}),[f?.name,t.siteName]);const[p,m]=u.useState(!1),[g,x]=u.useState([]),[j,C]=u.useState(null),[z,k]=u.useState({mainFile:"",items:[]}),[y,P]=u.useState(""),[E,S]=u.useState(""),[N,V]=u.useState(""),[Y,ie]=u.useState({filePath:"",content:""}),[F,le]=u.useState({path:"",hasIncludes:!1}),[G,J]=u.useState(""),[Z,Ee]=u.useState(!1),[ce,Q]=u.useState("editor.saved"),[$,fe]=u.useState(null),Se=u.useRef($);Se.current=$;const ve=u.useRef(null);ve.current||(ve.current=JS());const je=ve.current,[ee,q]=u.useState("pdf"),[he,we]=u.useState("log"),U=w=>{if(w==="pdf"){q("pdf");return}if(w==="diagnostics"){q("diagnostics");return}we(w),q("diagnostics")},{workspaceLayout:H,setWorkspaceLayout:Te}=n0(e.id,n),[ke,O]=u.useState(""),[I,te]=u.useState(""),[Ne,_e]=u.useState({selectedText:"",startOffset:0,endOffset:0}),Ie=u.useRef({selectedText:"",startOffset:0,endOffset:0}),$e=w=>{const b=Ie.current;b.selectedText===w.selectedText&&b.startOffset===w.startOffset&&b.endOffset===w.endOffset||(Ie.current=w,_e(w))},[se,xe]=u.useState(null),[Pe,Le]=u.useState(null),[D,ue]=u.useState(null),[Ue,Ye]=u.useState(null),[nt,pe]=u.useState(null),[A,X]=u.useState(!1),[Oe,ze]=u.useState(!1),[M,oe]=u.useState(!1),[Re,re]=u.useState(!1),[vt,B]=u.useState(null),[v,_]=u.useState(!1),[K,dt]=u.useState(null),[L,W]=u.useState(!1),[bt,kt]=u.useState(!1),[qn,ft]=u.useState(!1),[wi,De]=u.useState("full"),[Rs,gf]=u.useState(""),[bi,yi]=u.useState(!1),[wf,xi]=u.useState(""),[bf,Si]=u.useState(null),[_s,Vn]=u.useState(!1),[xn,Kt]=u.useState(null),[yf,vi]=u.useState(!1),[lt,Fa]=u.useState(()=>Nl(e.id,n));u.useEffect(()=>{const w=document.documentElement,b=lt.showTooltips?"on":"off";return w.setAttribute("data-texlite-tooltips",b),()=>{w.getAttribute("data-texlite-tooltips")===b&&w.removeAttribute("data-texlite-tooltips")}},[lt.showTooltips]);const[Hn,pr]=u.useState([]),rn=u.useRef([]);rn.current=Hn;const xf=u.useRef(null),mr=u.useRef(null),gr=u.useRef(0),ki=u.useRef(0),Fe=u.useRef(""),ht=u.useRef(""),Ma=u.useRef(()=>{}),Ci=u.useRef(H),Ia=u.useRef(0),Sn=u.useRef(null),$a=u.useRef(null),vn=u.useRef(null),kn=u.useRef(null),Kn=u.useRef(null),Gn=u.useRef(null),Jn=u.useRef(null),on=u.useRef(null),Ei=u.useRef(null),Gt=u.useRef(!1),an=u.useRef(null),Ua=u.useRef(l),ji=u.useRef(i),Di=u.useRef(a);Ua.current=l,ji.current=i,Di.current=a,Fe.current=y,ht.current=E,Ci.current=H,u.useEffect(()=>{if(!I)return;const w=window.setTimeout(()=>te(""),3e3);return()=>window.clearTimeout(w)},[I]);const Sf=u.useCallback((w,b,T=0)=>{je.update(w,b,T)},[je]);u.useEffect(()=>()=>je.dispose(),[je]),u.useEffect(()=>()=>{on.current?.abort(),on.current=null},[]);const wr=w=>{const b=rn.current,T=w(b);T!==b&&(rn.current=T,pr(T))};u.useEffect(()=>{rn.current=[],pr([]),Kt(null),B(null),Gn.current?.abort(),Gn.current=null,Jn.current?.abort(),Jn.current=null,on.current?.abort(),on.current=null,Ei.current=null,ue(null),Ye(null),pe(null),ft(!1),yi(!1),xi(""),Si(null)},[n]);const za=w=>{const b=rn.current,T=b.indexOf(w);if(T<0)return;const R=b.filter(ae=>ae!==w);if(rn.current=R,pr(R),Fe.current!==w)return;const me=R.length>0?R[Math.min(T,R.length-1)]:f?.mainFile??"";P(me)},{collaboration:qe,status:br,synced:Xe,activeSessions:Ba,formatLeaseStates:vf,compileState:Yn,setCompileState:Wa,filesEvent:Ze,commentsRevision:qa,historyWarning:kf,dictionaryRevision:Va,chktexSettingsRevision:Ha,localDraftReady:Ka,permission:Ti,reconnect:Cf,protocolUpgradeRequired:Ga,permissionDowngrade:Ef,dismissPermissionDowngrade:jf,discardLocalDraft:Df}=qx(n,e,E,f?.permission??"read",p,()=>Q("editor.offlineDraft")),{unreadMentions:Ja,refresh:Tf,markMentionRead:Rf,markAllMentionsRead:_f}=wg(n,qa,O),{pdfTarget:Lf,pdfViewport:Af,sourceJump:Nf,setPdfViewport:Of,resetPdfViewport:Pf,clearPdfViewport:Ya,jumpToSource:Xn,syncSourceToPdf:Ri,syncPdfToSource:Ff,syncVisiblePdfToSource:Mf}=t0({projectId:n,mainFile:E,activeFile:y,onOpenSourceFile:w=>Ma.current(w),onError:O,onShowPdf:()=>U("pdf"),onShowEditor:()=>{Ci.current==="pdf-only"&&Te("editor-pdf")}}),Xa=!!(f&&f.chktexEnabled&&y&&Xe&&kc(y)),Cn=e0({active:Xa,projectId:n,activeFile:y,content:N}),If=!!(f&&y&&Xe&&s0(y)&&(lt.spellCheck||f.chktexEnabled&&kc(y))),Ct=Qx({active:If,harperEnabled:lt.spellCheck,projectId:n,activeFile:y,content:N,dictionaryWords:g,additionalIssues:Cn.issues,additionalIssuesReady:!Xa||Cn.checked});u.useEffect(()=>{Fa(Nl(e.id,n))},[e.id,n]);const _i=w=>{V(w)};u.useEffect(()=>{if(!y||G!==y){ie(R=>R.filePath||R.content?{filePath:"",content:""}:R);return}const w=y,b=N,T=window.setTimeout(()=>{ie(R=>R.filePath===w&&R.content===b?R:{filePath:w,content:b})},Fc);return()=>window.clearTimeout(T)},[y,G,N]),u.useEffect(()=>{if(Fe.current=y,je.reset(),$e({selectedText:"",startOffset:0,endOffset:0}),!lt.openFilesInTabs){rn.current.length>0&&(rn.current=[],pr([]));return}y&&wr(w=>w.includes(y)?w:[...w,y])},[y,lt.openFilesInTabs,n,je]),u.useEffect(()=>{if(!Z)return;const w=b=>{b.preventDefault(),b.returnValue=""};return window.addEventListener("beforeunload",w),()=>window.removeEventListener("beforeunload",w)},[Z]),u.useEffect(()=>{if(br!=="disconnected")return;const w=new AbortController;return be(`/api/projects/${n}`,{signal:w.signal}).then(({project:b})=>{w.signal.aborted||(h(b),O(""))}).catch(b=>{if(!Xt(b)){if(b instanceof Pr&&[401,403,404].includes(b.status)){O(ye(b)),Ua.current();return}O(c("errors.collaborationUnavailable"))}}),()=>w.abort()},[br,n,c]);const yr=async(w={},b=ht.current)=>{Sn.current?.abort(),Sn.current=null;const T=w.signal?null:new AbortController;T&&(Sn.current=T);try{const R=b?`?mainFile=${encodeURIComponent(b)}`:"",me=await be(`/api/projects/${n}/completions${R}`,{signal:w.signal??T?.signal});(!w.isCurrent||w.isCurrent())&&C(me.index)}catch(R){if(Xt(R))return;(!w.isCurrent||w.isCurrent())&&C(null)}finally{T&&Sn.current===T&&(Sn.current=null)}},Li=async(w={},b=ht.current)=>{vn.current?.abort(),vn.current=null;const T=w.signal?null:new AbortController;T&&(vn.current=T);try{const R=b?`?mainFile=${encodeURIComponent(b)}`:"",me=await be(`/api/projects/${n}/outline${R}`,{signal:w.signal??T?.signal});(!w.isCurrent||w.isCurrent())&&ht.current===b&&k({mainFile:b,items:me.outline})}catch(R){if(Xt(R))return}finally{T&&vn.current===T&&(vn.current=null)}},Za=async(w={})=>{kn.current?.abort(),kn.current=null;const b=w.signal?null:new AbortController;b&&(kn.current=b);try{const T=await be(`/api/projects/${n}/dictionary`,{signal:w.signal??b?.signal});(!w.isCurrent||w.isCurrent())&&x(T.words)}catch(T){if(Xt(T))return;(!w.isCurrent||w.isCurrent())&&x([])}finally{b&&kn.current===b&&(kn.current=null)}};u.useEffect(()=>{let w=!1;const b=++Ia.current,T=new AbortController,R=()=>!w&&Ia.current===b;let me=!1,ae="";h(null),tl([]),k({mainFile:"",items:[]}),P(""),S(""),le({path:"",hasIncludes:!1}),V(""),J(""),Wa(null),Ya(),C(null),x([]),Mc();const de=(s?.projectId===n?s.project:be(`/api/projects/${n}`,{signal:T.signal})).then(Qe=>{R()&&(me=!0,ae=Qe.project.mainFile,h(Qe.project),P(Qe.project.mainFile),ht.current=Qe.project.mainFile,S(Qe.project.mainFile),vr(new Set(Ln(Qe.project.mainFile))))}).catch(Qe=>{R()&&O(ye(Qe))}),It=be(`/api/projects/${n}/files`,{signal:T.signal}).then(Qe=>{R()&&tl(Qe.files)}).catch(Qe=>{R()&&O(ye(Qe))});let yt=null;return Promise.allSettled([de,It]).then(()=>{!R()||!me||(yt=window.setTimeout(()=>{R()&&Promise.all([yr({signal:T.signal,isCurrent:R},ht.current||ae),Za({signal:T.signal,isCurrent:R})])},0))}),()=>{w=!0,yt!==null&&window.clearTimeout(yt),T.abort(),Sn.current?.abort(),Sn.current=null,vn.current?.abort(),vn.current=null,kn.current?.abort(),kn.current=null,Kn.current?.abort(),Kn.current=null}},[n,s]),u.useEffect(()=>{if(!(!f||!E)){if($a.current!==n){$a.current=n;return}yr({},E)}},[E,f?.id,n]),u.useEffect(()=>{if(!r||!f)return;Jn.current?.abort();const w=new AbortController;return Jn.current=w,be(`/api/projects/${n}/mentions/${encodeURIComponent(r)}`,{signal:w.signal}).then(({mention:b})=>{w.signal.aborted||(ue(b),Le(null),xe("comments"),P(b.filePath),ji.current?.(b.id))}).catch(b=>{Xt(b)||w.signal.aborted||(O(ye(b)),ji.current?.(r))}).finally(()=>{Jn.current===w&&(Jn.current=null)}),()=>w.abort()},[r,f?.id,n]),u.useEffect(()=>{Va&&Za()},[Va,n]),u.useEffect(()=>{if(!Ha)return;const w=new AbortController;return be(`/api/projects/${n}`,{signal:w.signal}).then(({project:b})=>{w.signal.aborted||h(T=>T?{...T,chktexEnabled:b.chktexEnabled}:b)}).catch(b=>{Xt(b)||O(ye(b))}),()=>w.abort()},[Ha,n]),u.useEffect(()=>{!f||br!=="connected"||Ti===f.permission||h(w=>w&&{...w,permission:Ti})},[Ti,f?.permission]),u.useEffect(()=>{if(!Ze)return;const w=Ze.kind==="delete"&&!!Ze.path&&jn(Ze.path,Fe.current),b=Ze.kind==="delete"&&!!Ze.path&&jn(Ze.path,ht.current);if(Ze.kind==="move"&&Ze.source&&Ze.destination){const R=Ze.source,me=Ze.destination,ae=de=>de===R?me:de.startsWith(`${R}/`)?`${me}${de.slice(R.length)}`:de;P(de=>ae(de)),S(de=>ae(de)),As(de=>de&&ae(de)),Sr(de=>de&&ae(de)),wr(de=>de.map(ae))}w&&(P(""),J(""),_i(""),te(c("editor.fileDeletedByCollaborator",{path:Ze.path}))),Ze.kind==="delete"&&Ze.path&&(As(R=>R&&jn(Ze.path,R)?null:R),Sr(R=>jn(Ze.path,R)?"":R),rl(R=>R&&jn(Ze.path,R.path)?null:R),wr(R=>R.filter(me=>!jn(Ze.path,me)))),Kn.current?.abort();const T=new AbortController;Kn.current=T,Promise.all([Wf({signal:T.signal}),be(`/api/projects/${n}`,{signal:T.signal})]).then(([R,me])=>{if(h(me.project),b&&S(me.project.mainFile),w&&R){const ae=R.find(de=>de.type==="file"&&de.path===me.project.mainFile)??R.find(de=>de.type==="file"&&fs(de.path));P(ae?.path??"")}yr({signal:T.signal}),Li({signal:T.signal},b?me.project.mainFile:ht.current)}).catch(R=>{Xt(R)}).finally(()=>{Kn.current===T&&(Kn.current=null)})},[Ze?.revision]),u.useEffect(()=>{if(qe.setActiveFile(y),!y)return;J(""),Q("editor.loading");const w=qe.getText(y),b=(T,R)=>{_i(w.toString()),J(y),R?.local&&f?.permission!=="read"?(gr.current+=1,Ee(!0),Q("editor.pending")):gr.current<=ki.current&&Q(Se.current?"editor.savedAt":"editor.saved")};return w.observe(b),(Xe||Ka)&&b(),()=>{w.unobserve(b)}},[y,qe,Xe,Ka,f?.permission]);const xr=async()=>{if(!Xe)throw new Error("Collaboration is not synchronized");const w=gr.current,b=await qe.flush();return ki.current=Math.max(ki.current,w),fe(b.persistedAt),/\.tex$/i.test(Fe.current)&&Li(),gr.current===w?(Ee(!1),Q("editor.savedAt")):Q("editor.pending"),b};u.useEffect(()=>{if(!Z||!y)return;if(!Xe){Q("editor.offlineDraft");return}Q("editor.pending");const w=window.setTimeout(()=>{Q("editor.saving"),xr().catch(()=>{Q(qe.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(w)},[N,Z,y,Xe]);const Ls=async()=>{if(!f||f.permission==="read"||!Xe||!y)return!1;Q("editor.saving");try{return await xr(),yr(),!0}catch(w){return Q("editor.saveFailed"),O(ye(w)||c("errors.collaborationUnavailable")),!1}},$f=async w=>{if(!f||bi)return;const b=w==="full"?ht.current||f.mainFile:Fe.current,T=w==="selection"?Ie.current.selectedText:"";if(!b)return;if(w==="selection"&&(!T.trim()||!/\.(?:tex|sty|cls)$/i.test(b))){te(c("editor.wordCountSelectionEmpty"));return}Gn.current?.abort();const R=new AbortController;Gn.current=R,De(w),gf(b),Si(null),xi(""),ft(!0),yi(!0);try{if(w==="full"&&Z&&f.permission!=="read"&&!await Ls())throw new Error(c("editor.wordCountSaveRequired"));const me=w==="selection"?{mode:w,path:b,source:T}:{mode:w,mainFile:b},ae=await be(`/api/projects/${n}/word-count`,{method:"POST",body:JSON.stringify(me),signal:R.signal});if(R.signal.aborted)return;Si(ae)}catch(me){if(Xt(me))return;R.signal.aborted||xi(ye(me))}finally{Gn.current===R&&(Gn.current=null,yi(!1))}},Ai=async(w,b,T=lt.texFmtConfig)=>{if(/\.bib$/i.test(w)){const me=await Pc();try{return{formatted:me.formatBibtex(b,t.maxCitationBibtexBytes)}}catch(ae){throw ae instanceof me.BibtexFormatError?ae.kind==="too-large"?new Error(c("citationLibrary.fileTooLarge",{size:me.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})):new Error(c("citationLibrary.fileInvalid")):ae}}return{formatted:(await $m(b,T)).output}},Qa=async w=>{if(!f||f.permission==="read"||!Xe||Gt.current||!Er(Fe.current))return;const b=Fe.current,T=qe.getText(b);Gt.current=!0,Vn(!0);let R=()=>{};const me=new Promise(de=>{R=de});an.current=me;let ae=null;try{ae=await qe.acquireFormatLease(b);const de=T.toString(),{formatted:It}=await Ai(b,de,w);if(Fe.current!==b||T.toString()!==de){O(c("editor.formatSourceChanged"));return}await ae.confirm();const yt=await Ki(de,It);if(Fe.current!==b||T.toString()!==de){O(c("editor.formatSourceChanged"));return}if(await ae.confirm(),Fe.current!==b||T.toString()!==de){O(c("editor.formatSourceChanged"));return}yt.length&&qe.applyTextEdits(b,yt),yt.length&&await xr(),Kt(null),O(""),te(c("editor.formatFileComplete"))}catch(de){Hi(de)?(Kt({action:"file",kind:de.kind,detail:de.message}),O("")):O(c("editor.formatFileFailed",{message:ye(de)}))}finally{ae&&await ae.release(),Gt.current=!1,Vn(!1),R(),an.current===me&&(an.current=null)}},Uf=async()=>{if(!lt.formatOnCompile||!f||f.permission==="read"||!Xe||!Er(Fe.current)||Gt.current)return;const w=Fe.current,b=qe.getText(w);Gt.current=!0,Vn(!0);let T=null;try{T=await qe.acquireFormatLease(w);const R=b.toString(),{formatted:me}=await Ai(w,R);await T.confirm();const ae=await Ki(R,me);if(Fe.current!==w||b.toString()!==R)throw new Error(c("editor.formatSourceChanged"));if(await T.confirm(),Fe.current!==w||b.toString()!==R)throw new Error(c("editor.formatSourceChanged"));ae.length&&qe.applyTextEdits(w,ae),ae.length&&await qe.flush(),Kt(null)}catch(R){Hi(R)?(Kt({action:"file",kind:R.kind,detail:R.message}),O("")):O(c("editor.formatFailedContinue",{message:ye(R)}))}finally{T&&await T.release(),Gt.current=!1,Vn(!1)}},zf=async()=>(an.current&&await an.current,await Uf(),Ls()),el=async w=>{if(!f||f.permission==="read"||!Xe||Gt.current||!Er(Fe.current))return;const b=Ie.current;if(!b.selectedText.trim()){te(c("editor.formatSelectionRequired"));return}const T=Fe.current,{startOffset:R,endOffset:me,selectedText:ae}=b,de=qe.getText(T);if(de.toString().slice(R,me)!==ae){O(c("editor.formatSelectionChanged"));return}Gt.current=!0,Vn(!0);let It=()=>{};const yt=new Promise(Jt=>{It=Jt});an.current=yt;let Qe=null;try{if(Qe=await qe.acquireFormatLease(T),de.toString().slice(R,me)!==ae){O(c("editor.formatSelectionChanged"));return}const Fs=await Ai(T,ae,w),Cp=Bm(ae,Fs.formatted);await Qe.confirm();const qi=await Ki(ae,Cp,R);if(Fe.current!==T||de.toString().slice(R,me)!==ae){O(c("editor.formatSelectionChanged"));return}if(await Qe.confirm(),Fe.current!==T||de.toString().slice(R,me)!==ae){O(c("editor.formatSelectionChanged"));return}qi.length&&qe.applyTextEdits(T,qi),qi.length&&await xr(),Kt(null),O(""),te(c("editor.formatSelectionComplete"))}catch(Jt){Hi(Jt)?(Kt({action:"selection",kind:Jt.kind,detail:Jt.message}),O("")):O(c("editor.formatFailed",{message:ye(Jt)}))}finally{Qe&&await Qe.release(),Gt.current=!1,Vn(!1),It(),an.current===yt&&(an.current=null)}},Bf=async w=>{const b=Fe.current;if(!/\.bib$/i.test(b)||f?.permission==="read"||!Xe)return te(c("citationLibrary.importRequiresWrite")),!1;const T=qe.getText(b);let R;try{R=await Pc()}catch(Fs){return O(ye(Fs)),!1}if(Fe.current!==b||!Xe)return!1;const me=T.toString(),ae=R.parseBibEntriesResult(me,t.maxCitationBibtexBytes);if(ae.status==="too-large")return te(c("citationLibrary.fileTooLarge",{size:R.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})),!1;if(ae.status==="invalid")return te(c("citationLibrary.fileInvalid")),!1;if(ae.entries.some(Fs=>Fs.citationKey.toLowerCase()===w.citationKey.toLowerCase()))return te(c("citationErrors.alreadyInFile",{key:w.citationKey})),!1;const de=Math.max(0,Math.min(me.length,je.getCursor().offset)),It=me.slice(0,de),yt=me.slice(de),Qe=It?It.endsWith(`
|
|
21
|
+
|
|
22
|
+
`)?"":It.endsWith(`
|
|
23
|
+
`)?`
|
|
24
|
+
`:`
|
|
25
|
+
|
|
26
|
+
`:"",Jt=yt?yt.startsWith(`
|
|
27
|
+
|
|
28
|
+
`)?"":yt.startsWith(`
|
|
29
|
+
`)?`
|
|
30
|
+
`:`
|
|
31
|
+
|
|
32
|
+
`:"";return qe.applyTextEdits(b,[{from:de,to:de,replacement:`${Qe}${w.bibtex.trim()}${Jt}`}]),te(c("citationLibrary.imported",{key:w.citationKey})),!0},{files:Mt,setFiles:tl,loadFiles:Wf,newFileOpen:qf,setNewFileOpen:nl,newFilePath:Vf,setNewFilePath:sl,resourcePreview:Hf,setResourcePreview:rl,resourcePreviewLoading:Kf,setResourcePreviewLoading:Gf,newFolderOpen:Jf,setNewFolderOpen:il,newFolderName:Yf,setNewFolderName:ol,fileDialogError:Xf,setFileDialogError:al,selectedFolder:ll,setSelectedFolder:As,selectedFile:Zf,setSelectedFile:Sr,expandedFolders:Qf,setExpandedFolders:vr,moveEntry:eh,setMoveEntry:cl,moveName:th,setMoveName:ul,moveDestination:nh,setMoveDestination:dl,deleteEntry:Ni,setDeleteEntry:fl,fileDragActive:sh,setFileDragActive:rh,uploadConflict:ih,setUploadConflict:oh,uploadingFiles:ah,uploadFeedback:lh,dismissUploadFeedback:hl,directoryEntries:ch,visibleEntries:uh,createFile:dh,createFolder:fh,uploadFiles:pl,upload:hh,openFile:Oi,movePath:ph,movePathToFolder:mh,removePath:gh}=Xx({projectId:n,site:t,activeFile:y,dirty:Z,save:Ls,onError:O,onProject:h,onActiveFile:P,onActiveMainFile:S});Ma.current=w=>{As(null),Sr(w),vr(b=>new Set([...b,...Ln(w)])),P(w)};const wh=w=>{if(w.id!==d.current)return;const b=w.mainFile!==f?.mainFile;h(w),b&&(ht.current=w.mainFile,Fe.current=w.mainFile,S(w.mainFile),P(w.mainFile),As(null),Sr(w.mainFile),vr(T=>new Set([...T,...Ln(w.mainFile)])))},ml=()=>ht.current||f?.mainFile||"",bh=()=>{const w=ml(),b=Fe.current;if(!b||!/\.tex$/i.test(b))return w;const T=Mt.filter(ae=>ae.type==="file"&&/\.tex$/i.test(ae.path)).length,R=qe.getText(b).toString();return jc(R)||T===1?(w!==b&&(ht.current=b,S(b)),b):w===b&&f?.mainFile&&f.mainFile!==b?(ht.current=f.mainFile,S(f.mainFile),f.mainFile):w};u.useEffect(()=>{!y||y!==E||G!==y||Y.filePath!==y||!y.toLocaleLowerCase().endsWith(".tex")||Mt.filter(b=>b.type==="file"&&/\.tex$/i.test(b.path)).length===0||y===f?.mainFile||!jc(Y.content)&&f?.mainFile&&(ht.current=f.mainFile,S(f.mainFile))},[y,E,G,Y,Mt,f?.mainFile]),u.useEffect(()=>{if(!lt.openFilesInTabs||Mt.length===0)return;const w=new Set(Mt.filter(b=>b.type==="file"&&fs(b.path)).map(b=>b.path));wr(b=>{const T=b.filter(R=>w.has(R));return T.length===b.length?b:T})},[Mt,lt.openFilesInTabs]);const{comments:ln,commentsFilePath:Pi,commentsReady:Fi,fileCommentsLoading:yh,fileCommentsError:xh,retryFileComments:Sh,reviewComments:vh,reviewCommentsLoading:kh,reviewCommentsError:Ch,retryReviewComments:Eh,commentScope:jh,setCommentScope:Dh,focusComment:gl,setFocusComment:Ns,commentOpen:Th,openComment:Rh,closeComment:_h,commentText:Lh,setCommentText:Ah,commentSelection:Nh,commentSubmitting:Oh,commentError:Ph,addComment:Fh,toggleComment:Mh,replyToComment:Ih,editComment:$h,deleteComment:Uh,editCommentReply:zh,deleteCommentReply:Bh,commentDraftStore:Wh,cancelComment:qh,commentDraftRestored:Vh,commentDraftCanRetarget:Hh,useCurrentCommentSelection:Kh}=og({projectId:n,activeFile:y,content:N,permission:f?.permission,revision:qa,selection:Ne,save:Ls,saveFailureMessage:c("errors.collaborationUnavailable"),onError:O,onAdded:()=>{Le(null),xe("comments")},onChanged:()=>{Tf()}});u.useEffect(()=>{if(!E||Y.filePath!==E)return;const w=Dc(Y.content).length>0;le(b=>b.path===E&&b.hasIncludes===w?b:{path:E,hasIncludes:w})},[E,Y]),u.useEffect(()=>{if(!E||!Xe||y===E)return;const w=qe.getText(E);let b=null;const T=()=>{const me=Dc(w.toString()).length>0;le(ae=>ae.path===E&&ae.hasIncludes===me?ae:{path:E,hasIncludes:me})},R=()=>{b!==null&&window.clearTimeout(b),b=window.setTimeout(()=>{b=null,T()},Fc)};return T(),w.observe(R),()=>{b!==null&&window.clearTimeout(b),w.unobserve(R)}},[y,E,qe,Xe]);const Gh=u.useMemo(()=>F.path===E&&F.hasIncludes,[E,F]),wl=w=>{pe(null),xe("comments"),Ns(null),Ye(w),Fe.current!==w.filePath&&Xn(w.filePath,w.startLine,1)},Jh=(w,b=!1)=>{const T=ln.find(R=>R.id===w&&R.filePath===y);if(!(!T||T.resolved||T.orphaned)){if(Ye(null),Ns(null),ue(null),b&&se==="comments"&&Pe===T.id){Le(null),pe(null),xe(null);return}Le(T.id),pe(R=>({id:T.id,filePath:T.filePath,nonce:(R?.nonce??0)+1})),xe("comments")}};u.useEffect(()=>{pe(null),Le(null)},[y]),u.useEffect(()=>{if(!Ue)return;const w=hg(Ue,y,G,Pi,Fi,ln);if(w){Ns({...w}),Ye(null);return}Ue.filePath===y&&G===y&&Pi===y&&Fi&&Ye(null)},[y,ln,Pi,Fi,G,Ue,Ns]);const Yh=async w=>{const b=await Rf(w);return b&&Di.current?.(1),b},Xh=async()=>{const w=Ja.length,b=await _f();return b&&w&&Di.current?.(w,!0),b};u.useEffect(()=>{if(!D||y!==D.filePath||se!=="comments")return;const w=ln.find(T=>T.id===D.commentId);if(!w||D.replyId&&!w.replies.some(T=>T.id===D.replyId)||Ei.current===D.id)return;Ei.current=D.id,wl(w);const b=window.setTimeout(()=>ue(T=>T?.id===D.id?null:T),3e3);return()=>window.clearTimeout(b)},[y,ln,se,D]);const{pdfUrl:cn,pdfCompiledAt:Os,pdfSizeBytes:Zh,pdfLoadingMode:Qh,pdfLoading:Mi,compileLog:Ii,compileDiagnostics:ep,compileOutcome:Ps,artifacts:bl,artifactPreview:tp,artifactLoading:np,editorNotice:sp,localCompiling:yl,cancelling:rp,cleaning:xl,compile:ip,cancelCompile:op,cleanCompile:ap,viewArtifact:lp}=Kx({projectId:n,project:f,mainFile:E,resolveCompileMainFile:bh,getCurrentMainFile:ml,initialLatest:s?.projectId===n?s.latestCompile:null,collaborationSynced:Xe,sharedState:Yn,onSharedState:Wa,save:zf,loadOutline:(w,b)=>Li({signal:w},b),onPreviewTab:U,onError:O,onCompileStart:()=>{O(""),te("")},onCompileSuccess:()=>{const w=Fe.current;if(w){const b=je.getCursor();Ri(w,b.line,b.column,{silent:!0})}},onPdfChanged:Ya});u.useEffect(()=>{if(!f||!E||!cn&&Mi)return;const w=window.setTimeout(()=>m(!0),cn?150:0);return()=>window.clearTimeout(w)},[f,Mi,cn]),u.useEffect(()=>{const w=b=>{(b.ctrlKey||b.metaKey)&&(!b.shiftKey&&b.key.toLocaleLowerCase()==="p"?(b.preventDefault(),W(!0)):b.shiftKey&&b.key.toLocaleLowerCase()==="f"&&(b.preventDefault(),kt(!0)))};return window.addEventListener("keydown",w,!0),()=>window.removeEventListener("keydown",w,!0)},[]);const Sl=w=>{Fa(w),Om(e.id,n,w)},vl=(w=!1)=>{const b=xn;if(!b)return;Kt(null),O(""),w&&Sl({...lt,texFmtConfig:""});const T=w?"":void 0;b.action==="selection"?el(T):Qa(T)},cp=async()=>{vi(!0);try{await Df()||(O(c("editor.collaboration.permissionDowngradeOtherTabBlocked")),vi(!1))}catch(w){O(ye(w)),vi(!1)}},kl=()=>{mr.current?.isCollapsed()?mr.current.expand():mr.current?.collapse()},up=u.useMemo(()=>YS(z,E,Y),[z,E,Y]),$i=u.useMemo(()=>Wm(Ii,Ps),[Ii,Ps]),Zn=H!=="pdf-only",Cl=H!=="editor-only",kr=w=>{Te(w),w==="pdf-only"&&U("pdf")},dp=u.useCallback(w=>{on.current?.abort();const b=new AbortController;on.current=b;const T=Fe.current,R=ht.current,me=new URLSearchParams({kind:w.kind,key:w.key,...T?{path:T}:{},...R?{mainFile:R}:{}});be(`/api/projects/${n}/references/resolve?${me}`,{signal:b.signal}).then(({target:ae})=>{if(!(b.signal.aborted||Fe.current!==T||ht.current!==R)){if(!ae){O(c(w.kind==="citation"?"editor.citationTargetNotFound":"editor.labelTargetNotFound",{key:w.key}));return}Ci.current==="pdf-only"&&kr("editor-pdf"),Xn(ae.path,ae.line,ae.column)}}).catch(ae=>{!b.signal.aborted&&!Xt(ae)&&O(ye(ae))}).finally(()=>{on.current===b&&(on.current=null)})},[Xn,n,c]),fp=Ni?Ba.filter(w=>w.filePath&&jn(Ni.path,w.filePath)):[];if(!f)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:ke||c("common.loading")}),ke&&o.jsx("button",{className:"primary",onClick:l,children:c("editor.backToProjects")})]});const un=f.permission==="read"||!Xe,Ui=vf.find(w=>w.path===y),zi=Ui&&!_s?Ui:null,hp=(w,b)=>{if(un)return;const T=Fe.current;if(!T)return;if(qe.getText(T).toString().slice(w.from,w.to)!==w.word){O(c("editor.spellCheckSourceChanged"));return}try{qe.applyTextEdits(T,[{from:w.from,to:w.to,replacement:b}])}catch(ae){O(ye(ae))}},Bi=Yn?.mainFile===E&&(Yn.status==="queued"||Yn.status==="running"),Cr=yl||Bi||xl,pp=y?qe.getText(y):null,mp=Os?new Date(Os).toLocaleString(Us.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",gp=E.split("/").at(-1)??E,wp=$i.warnings.length+$i.errors.length+bl.length,bp=cn?`${cn}${cn.includes("?")?"&":"?"}download=1`:"",Wi=E||f.mainFile,yp=!!(y&&y===Wi&&/\.tex$/i.test(y)),xp=!!(Wi&&/\.tex$/i.test(Wi)),El=w=>{const b=Mt.find(T=>T.path===w);b&&fs(b.path)?Oi(b):za(w)},Sp=w=>{document.getElementById(`editor-tab-${encodeURIComponent(w)}`)?.focus()},vp=(w,b)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(w.key))return;w.preventDefault();const T=w.key==="Home"?0:w.key==="End"?Hn.length-1:(b+(w.key==="ArrowLeft"?-1:1)+Hn.length)%Hn.length,R=Hn[T];R&&(El(R),window.requestAnimationFrame(()=>Sp(R)))},jl=Cr?Bi?Yn?.status==="queued"?c("editor.compileQueued"):c("editor.compilingBy",{name:Yn?.requestedBy.name??c("common.user")}):c("editor.compiling"):Ps==="failed"?cn&&Os?c("editor.compileFailedRetained",{time:new Date(Os).toLocaleString(Us.resolvedLanguage)}):c("editor.compileFailedNoPdf"):Ps==="cancelled"?c("compileControls.cancelled"):"",kp=ce==="editor.savedAt"&&$?c("editor.savedAt",{time:new Date($).toLocaleTimeString(Us.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):c(ce);return o.jsxs("div",{className:"workspace","data-texlite-tooltips":lt.showTooltips?"on":"off",children:[o.jsx(S0,{site:t,project:f,activeFile:y,saveStateLabel:kp,editorPreferences:lt,activeSessions:Ba,collaborationStatus:br,reconnectCollaboration:Cf,protocolUpgradeRequired:Ga,showEditor:Zn,filesCollapsed:A,toggleFilesPanel:kl,workspaceLayout:H,changeWorkspaceLayout:kr,onBack:l,onShare:()=>ze(!0),showCitationLibrary:Zn&&/\.bib$/i.test(y),citationLibraryOpen:v,onCitationLibrary:()=>_(!0),onHistory:()=>re(!0),onGit:()=>oe(!0),canManageGit:f.ownerId===e.id,formatting:_s,readOnly:un,collaborationSynced:Xe,onToggleComments:()=>{Le(null),xe(se==="comments"&&!Pe?null:"comments")},commentsOpen:se==="comments",unresolvedCommentCount:ln.filter(w=>!w.resolved).length,onToggleSettings:()=>xe(se==="settings"?null:"settings"),settingsOpen:se==="settings",compileBusy:Cr,sharedCompiling:Bi,localCompiling:yl,cancelling:rp,onCompile:ip,onCancelCompile:()=>{op()}}),Ga&&o.jsxs("div",{className:"workspace-update-banner",role:"alert",children:[o.jsx(Nt,{size:15}),o.jsx("span",{children:c("workspaceUpdates.protocolUpgrade")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),jl&&o.jsxs("div",{className:`compile-status-strip${Ps==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(ut,{className:Cr?"spin":"",size:14}),o.jsx("span",{children:jl})]}),(Ct.error||Cn.error||xn||zi)&&o.jsxs("div",{className:"client-tool-recoveries",children:[Ct.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:Ct.error,children:[o.jsx(Nt,{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:Ct.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:Ct.dismissError,children:o.jsx(mn,{size:13})})]}),Cn.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:Cn.error,children:[o.jsx(Nt,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c("chktex.recoveryTitle")}),c("chktex.recoveryHint")]}),o.jsx("div",{className:"client-tool-recovery-actions",children:o.jsx("button",{type:"button",onClick:Cn.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:Cn.dismissError,children:o.jsx(mn,{size:13})})]}),xn&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:xn.detail,children:[o.jsx(Nt,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c(xn.kind==="format"?"editor.texFmtOptionsRecoveryTitle":xn.kind==="load"?"editor.texFmtRecoveryTitle":"editor.texFmtRuntimeRecoveryTitle")}),c("editor.clientToolRecoveryHint")]}),o.jsxs("div",{className:"client-tool-recovery-actions",children:[o.jsx("button",{type:"button",disabled:_s||un,onClick:()=>vl(),children:c("common.retry")}),xn.kind==="format"&<.texFmtConfig.trim()&&o.jsx("button",{type:"button",disabled:_s||un,onClick:()=>vl(!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:()=>Kt(null),children:o.jsx(mn,{size:13})})]}),zi&&o.jsxs("div",{className:"client-tool-recovery format-lease-status",role:"status",children:[o.jsx(ut,{className:"spin",size:15}),o.jsx("span",{children:c("editor.formattingBy",{name:zi.holderName})})]})]}),kf&&o.jsxs("div",{className:"client-tool-recovery",role:"status",children:[o.jsx(Nt,{size:15}),o.jsx("span",{children:c("history.saveWarning")})]}),ke&&o.jsx("div",{className:"toast",onClick:()=>O(""),children:ke}),I&&o.jsx("div",{className:"toast success",onClick:()=>te(""),children:I}),o.jsxs(Mp,{autoSaveId:Tn("texlite-workspace-layout"),direction:"horizontal",className:"work-grid",children:[Zn&&o.jsx(P0,{project:f,filesPanel:mr,visibleEntries:uh,activeFile:y,activeMainFile:E,selectedFile:Zf,selectedFolder:ll,expandedFolders:Qf,fileDragActive:sh,uploadingFiles:ah,uploadFeedback:lh,readOnly:un,formatting:_s,canFormat:Er(y),activeFormatLease:!!Ui,collaborationSynced:Xe,editorFontSize:lt.fontSize,outline:up,sourceCursorStore:je,wordCountBusy:bi,hasSelection:!!Ne.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(y),hasFormatSelection:!!Ne.selectedText.trim(),uploadInput:xf,setSelectedFolder:As,setExpandedFolders:vr,setMoveEntry:cl,setMoveName:ul,setMoveDestination:dl,setDeleteEntry:fl,setFileDialogError:al,setNewFolderName:ol,setNewFolderOpen:il,setNewFilePath:sl,setNewFileOpen:nl,setQuickOpen:W,setProjectSearchOpen:kt,setFileDragActive:rh,dismissUploadFeedback:hl,setFilesCollapsed:X,toggleFilesPanel:kl,onError:O,uploadFiles:pl,upload:hh,openFile:Oi,movePathToFolder:mh,onFormatFile:()=>{Qa()},onFormatSelection:()=>{el()},jumpToSource:Xn,syncSourceToPdf:Ri,onWordCount:w=>{$f(w)}}),Zn&&o.jsx(Vo,{className:"resize-handle",children:o.jsx(Bc,{size:12})}),Zn&&o.jsx(B0,{project:f,activeFile:y,openTabs:Hn,content:N,loadedFile:G,readOnly:un,comments:ln,focusComment:gl,editorPreferences:lt,completionIndex:j,nativeSpellCheck:Ct.nativeFallback,spellCheckIssues:Ct.issues,spellCheckJump:Ct.jump,sourceJump:Nf,collaborativeText:pp,collaborationAwareness:qe.awareness,undoManager:y?qe.getUndoManager(y):void 0,editorNotice:sp,activateTab:El,closeTab:za,handleTabKeyDown:vp,updateEditorContent:_i,setSelection:(w,b,T)=>$e({selectedText:w,startOffset:b,endOffset:T}),onAddComment:(w,b,T,R)=>Rh({selectedText:w,startOffset:b,endOffset:T},R),onSelectionHistory:(w,b,T,R)=>{B({filePath:y,selection:{selectedText:w,startOffset:b,endOffset:T},source:R})},onCommentClick:Jh,onSpellCheckReplace:hp,onReferenceNavigate:dp,onCursor:Sf}),Cl&&o.jsx(G0,{projectId:n,activeMainFile:E,previewTab:ee,diagnosticTab:he,pdfUrl:cn,pdfLoadingMode:Qh,pdfLoading:Mi,pdfCompiledAt:Os,pdfSizeBytes:Zh,pdfCompiledLabel:mp,pdfTargetLabel:gp,pdfDownloadUrl:bp,pdfTarget:Lf,pdfViewport:Af,activeFile:y,compileBusy:Cr,compileLog:Ii,compileDiagnostics:ep,compileMessages:$i,artifacts:bl,artifactPreview:tp,artifactLoading:np,cleaning:xl,readOnly:un,collaborationSynced:Xe,workspaceLayout:H,showSyncResize:Zn&&Cl,diagnosticCount:wp,selectPreviewTab:U,changeWorkspaceLayout:kr,onSetPdfViewport:Of,onResetPdfViewport:Pf,syncVisiblePdfToSource:Mf,syncCurrentSourceToPdf:()=>{const w=Fe.current;if(!w)return Promise.resolve();const b=je.getCursor();return Ri(w,b.line,b.column)},syncPdfToSource:Ff,canSyncWithPdf:yp,canSyncPdfToSource:xp,files:Mt,jumpToSource:Xn,onSetCleanMode:dt,viewArtifact:lp}),o.jsx(KS,{sidePanel:se,onClose:()=>xe(null),project:f,projectId:n,site:t,files:Mt,currentUserId:e.id,comments:Pe?ln:vh,commentDraftStore:Wh,commentsLoading:Pe?yh:kh,commentsError:Pe?xh:Ch,onRetryComments:Pe?Sh:Eh,activeFile:y,singleCommentId:Pe,onShowAllComments:()=>Le(null),hasProjectCommentsScope:Gh,commentScope:jh,onCommentScopeChange:Dh,focusedCommentId:nt?.filePath===y?nt.id:gl?.id,commentFocusNonce:nt?.nonce,onClearFocusComment:()=>{pe(null),Ns(null),ue(null)},unreadMentions:Ja,onMarkMentionRead:Yh,onMarkAllMentionsRead:Xh,targetCommentId:D?.commentId,targetReplyId:D?.replyId,onFocusComment:wl,onToggleComment:Mh,onReplyComment:Ih,onEditComment:$h,onDeleteComment:Uh,onEditCommentReply:zh,onDeleteCommentReply:Bh,dictionaryWords:g,onDictionaryChange:x,editorPreferences:lt,onEditorPreferences:Sl,spellCheckCount:Ct.summary?.total??null,spellCheckUniqueCount:Ct.summary?.unique??null,spellCheckIndex:Ct.summary?Ct.index:-1,onSpellCheckNavigate:Ct.jumpToIssue,onProject:wh},n)]}),qn&&o.jsx(Ic,{title:c("editor.wordCountTitle"),onClose:()=>ft(!1),children:o.jsx(ZS,{open:!0,mode:wi,path:Rs,busy:bi,error:wf,result:bf,onOpenChange:ft})}),o.jsx(aS,{user:e,project:f,projectId:n,activeFile:y,content:N,maxCitationBibtexBytes:t.maxCitationBibtexBytes,files:Mt,directoryEntries:ch,readOnly:un,workspaceLayout:H,changeWorkspaceLayout:kr,resourcePreview:Hf,resourcePreviewLoading:Kf,setResourcePreview:rl,setResourcePreviewLoading:Gf,uploadConflict:ih,setUploadConflict:oh,dismissUploadFeedback:hl,uploadFiles:pl,cleanMode:K,setCleanMode:dt,cleanCompile:ap,newFileOpen:qf,setNewFileOpen:nl,newFilePath:Vf,setNewFilePath:sl,newFolderOpen:Jf,setNewFolderOpen:il,newFolderName:Yf,setNewFolderName:ol,selectedFolder:ll,fileDialogError:Xf,setFileDialogError:al,createFile:dh,createFolder:fh,moveEntry:eh,setMoveEntry:cl,moveName:th,setMoveName:ul,moveDestination:nh,setMoveDestination:dl,movePath:ph,deleteEntry:Ni,setDeleteEntry:fl,deleteActiveSessions:fp,removePath:gh,commentOpen:Th,closeComment:_h,commentSelection:Nh,commentText:Lh,setCommentText:Ah,commentSubmitting:Oh,cancelComment:qh,commentDraftRestored:Vh,commentDraftCanRetarget:Hh,useCurrentCommentSelection:Kh,commentError:Ph,addComment:Fh,shareOpen:Oe,setShareOpen:ze,citationLibraryOpen:v,setCitationLibraryOpen:_,insertCitationAtCursor:Bf,quickOpen:L,setQuickOpen:W,projectSearchOpen:bt,setProjectSearchOpen:kt,openFile:Oi,jumpToSource:Xn,selectionHistoryTarget:vt,closeSelectionHistory:()=>B(null),historyOpen:Re,setHistoryOpen:re,gitOpen:M,setGitOpen:oe,save:Ls,permissionDowngrade:Ef,permissionDowngradeBusy:yf,dismissPermissionDowngrade:jf,discardPermissionDraft:cp})]})}const xv=Object.freeze(Object.defineProperty({__proto__:null,ProjectWorkspace:QS},Symbol.toStringTag,{value:"Module"}));export{c0 as A,lv as B,bo as C,sg as D,fn as E,hm as F,Um as G,Ll as H,Lm as I,xo as J,cm as K,cv as L,xv as P,Tm as R,Rm as S,Kb as U,kc as a,hv as b,No as c,pv as d,mv as e,gv as f,$n as g,uv as h,Yt as i,i0 as j,Nd as k,Ra as l,Qo as m,l0 as n,Mo as o,ti as p,wv as q,fv as r,s0 as s,dv as t,Ts as u,fr as v,g0 as w,bv as x,Io as y,h0 as z};
|